diff --git a/.env b/.env deleted file mode 100644 index c471ff71e..000000000 --- a/.env +++ /dev/null @@ -1,60 +0,0 @@ -# Language code as supported by Sphinx: -# https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language -LANGUAGE ?= pt_BR - -# Branch used in the project and in CPython -BRANCH := 3.13 - -############################ -# Environment variables for 'merge' target -############################ -# -# Version(s) that still receive(s) bug fixes, not only security-related fixes. -# Versions in this variable will have their translation replaced with changes -# in currently active version being translated. These will have pomerge's -# --overwrite flag set. -BUGFIXBRANCH ?= 3.12 - -# Version(s) that are considered security fixes or EOL. Let's make them more -# stable, with more predictable state. These versions will not have translated -# strings replaced with translations update. These will have pomerge's -# --no-overwrite flag set. -OLDERBRANCHES ?= 3.11 3.10 3.9 3.8 3.7 3.6 2.7 -# -############################ - - -############################ -# Environment variables for 'build' target -############################ -# -# If set to -W, warnings will be considered as errors. -# Set to "" keep warnings as is. -SPHINXERRORHANDLING := "-W" -# -############################ - -########################### -# Environment variables for 'tx-install' target -########################### -# -# Specific Transifex CLI Client version to install. -# If unset, latest version will be used. -TX_CLI_VERSION ?= '1.6.12' - -# Install directory of TX_CLI_DIR. Consider using a directory already -# in the PATH environment variable because install script will add this -# directory to PATH in your ~/.bashrc. -TX_CLI_DIR ?= $(shell realpath ~/.local/bin) - -############################ -# Paths and URLs -############################ -# -PYTHON ?= $(shell which python3) -CPYTHON_DIR := cpython -LOCALE_DIR := Doc/locales -LOGS_DIR := logs -VENV_DIR := .venv -# -####### diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index ba0b877fc..000000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,27 +0,0 @@ -version: 2 -updates: - - package-ecosystem: "github-actions" - directory: "/" - schedule: - interval: "weekly" - assignees: - - "rffontenelle" - commit-message: - prefix: "gha" - groups: - all-github-actions: - patterns: - - "*" - - - package-ecosystem: "pip" - directory: "/" - schedule: - interval: "weekly" - assignees: - - "rffontenelle" - commit-message: - prefix: "pip" - groups: - all-pip-packages: - patterns: - - "*" diff --git a/.github/problem-matchers/sphinx.json b/.github/problem-matchers/sphinx.json deleted file mode 100644 index a0299d893..000000000 --- a/.github/problem-matchers/sphinx.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "problemMatcher": [ - { - "owner": "sphinx-problem-matcher", - "pattern": [ - { - "regexp": "^(.*):(\\d+):\\s+(\\w*):\\s+(.*)$", - "file": 1, - "line": 2, - "severity": 3, - "message": 4 - } - ] - }, - { - "owner": "sphinx-problem-matcher-loose", - "pattern": [ - { - "_comment": "A bit of a looser pattern, doesn't look for line numbers, just looks for file names relying on them to start with / and end with .rst", - "regexp": "(\/.*\\.rst):\\s+(\\w*):\\s+(.*)$", - "file": 1, - "severity": 2, - "message": 3 - } - ] - }, - { - "owner": "sphinx-problem-matcher-loose-no-severity", - "pattern": [ - { - "_comment": "Looks for file names ending with .rst and line numbers but without severity", - "regexp": "^(.*\\.rst):(\\d+):(.*)$", - "file": 1, - "line": 2, - "message": 3 - } - ] - } - ] -} diff --git a/.github/scripts/list-obsolete.py b/.github/scripts/list-obsolete.py deleted file mode 100755 index 2c5434913..000000000 --- a/.github/scripts/list-obsolete.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env python3 -# List PO files that no longer have a corresponding page in Python docs - -import os -import os.path -import sys -import subprocess - -def run(cmd): - return subprocess.check_output(cmd, shell=True, text=True) - -# Set POT root directory from command-line argument or hardcoded, then test it -pot_root = 'cpython/Doc/locales/pot/' - -if len(sys.argv) > 1: - pot_root = sys.argv[0] - -if not os.path.isdir(pot_root): - print(f'Unable to find the POT directory {pot_root}') - exit(1) - -# List PO files tracked by git -po_files = run('git ls-files | grep .po | tr "\n" " "').split() - -# Compare po vs pot, store po without corresponding pot -to_remove = [] -for file in sorted(po_files): - pot = os.path.join(pot_root, file + 't') - if not os.path.isfile(pot): - to_remove.append(file) - -# Exit if no obsolete, or print obsoletes files. -# If running in GitHub Actions, add a problem matcher to bring up the attention -if len(to_remove) == 0: - exit -else: - matcher = "" - if 'CI' in os.environ: - matcher = '::error::' - print(f'{matcher}The following files are absent in the documentation, hence they should be removed:\n') - for file in to_remove: - print(f'{matcher} ' + file) - print("") - exit(1) diff --git a/.github/scripts/prepmsg.sh b/.github/scripts/prepmsg.sh deleted file mode 100755 index 2111ab29a..000000000 --- a/.github/scripts/prepmsg.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/bin/bash -# Prepare message for Telegram notification -set -ex - -die() { echo "$0: error: $*" >&2; exit 1; } - -[ $# -ne 2 ] && die "Expected 1 input and 1 output files, got $#" -[ ! -f "$1" ] && die "Input file $1 not found, skipping." -[ -z "${GITHUB_REPOSITORY}" ] && die "GITHUB_REPOSITORY is empty." -[ -z "${GITHUB_RUN_ID}" ] && die "GITHUB_RUN_ID is empty." -[ -z "${GITHUB_JOB}" ] && die "GITHUB_JOB is empty." - -URL="https://github.com/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" - -input="$1" -output="$2" - -touch aux -if [[ "${GITHUB_JOB}" == "build" ]]; then - grep 'cpython/Doc/.*WARNING:' "$input" | \ - sed 's|.*/cpython/Doc/||' | \ - uniq | \ - sed 's|^|```\n|;s|$|\n```\n|' \ - > aux -elif [[ "${GITHUB_JOB}" == "lint" ]]; then - grep -P '^.*\.po:\d+:\s+.*\(.*\)$' "$input" | \ - sort -u | \ - sed 's|^|```\n|;s|$|\n```\n|' \ - > aux -else - die "Unexpected job name ${GITHUB_JOB}" -fi - -[[ $(cat aux) == "" ]] && die "Unexpected empty output message." - -echo "❌ *${GITHUB_JOB}* (ID [${GITHUB_RUN_ID}]($URL)):" > "$output"; -{ echo ""; cat aux; echo ""; } >> "$output" -rm aux diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml deleted file mode 100644 index 4f05a15ed..000000000 --- a/.github/workflows/check.yml +++ /dev/null @@ -1,235 +0,0 @@ -# Run some tests in the Python Doc translations - -name: Check - -on: - workflow_dispatch: - workflow_call: - pull_request: - branches: - - '3.13' - paths: - - '.github/workflows/check.yml' - - '.github/scripts/prepmsg.sh' - - '.github/scripts/list-obsolete.py' - - 'Makefile' - - 'requirements.txt' - - '*.po' - - '**/*.po' - push: - branches: - - '3.13' - paths: - - '.github/workflows/check.yml' - - '.github/scripts/prepmsg.sh' - - '.github/scripts/list-obsolete.py' - - 'Makefile' - - 'requirements.txt' - - '*.po' - - '**/*.po' - -permissions: - contents: read - -jobs: - # Build documentation handling warnings as errors. Always store logs. - # If success, make built docs artifact. If failure, notify telegram. - build: - name: Build translated docs - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4.1.7 - with: - fetch-depth: 5 - - - name: Set up Python 3 - uses: actions/setup-python@v5.1.1 - with: - python-version: '3' - - - name: Make sure the repository is up to date - if: github.event_name != 'pull_request' - run: git pull --rebase - - - name: Add problem matcher - uses: sphinx-doc/github-problem-matcher@v1.1 - - - name: Build docs - continue-on-error: true - id: build - run: | - make build - - - name: Upload artifact - docs - if: steps.build.outcome == 'success' - uses: actions/upload-artifact@v4.3.5 - with: - name: docs - path: cpython/Doc/build/html - - - name: Upload artifact - log files - if: always() - uses: actions/upload-artifact@v4.3.5 - with: - name: build-logs - path: logs/* - - - name: Prepare notification (only on error) - if: steps.build.outcome == 'failure' - id: prepare - run: .github/scripts/prepmsg.sh logs/build/err*.txt logs/notify.txt - env: - GITHUB_JOB: ${{ github.job }} - GITHUB_RUN_ID: ${{ github.run_id }} - GITHUB_REPOSITORY: ${{ github.repository }} - - - name: Notify via Telegram - if: steps.prepare.outcome == 'success' - uses: appleboy/telegram-action@v0.1.1 - with: - to: ${{ secrets.TELEGRAM_TO }} - token: ${{ secrets.TELEGRAM_TOKEN }} - format: markdown - disable_web_page_preview: true - message_file: logs/notify.txt - - - # Run sphinx-lint to find wrong reST syntax in PO files. Always store logs. - lint: - name: Lint translations - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4.1.7 - with: - fetch-depth: 5 - - - name: Set up Python 3 - uses: actions/setup-python@v5.1.1 - with: - python-version: '3' - - - name: Make sure the repository is up to date - if: github.event_name != 'pull_request' - run: git pull --rebase - - - name: Add problem matcher - uses: rffontenelle/sphinx-lint-problem-matcher@v1.0.0 - - - name: Run sphinx-lint - continue-on-error: true - id: lint - run: | - make lint - - - name: Upload artifact - log files - uses: actions/upload-artifact@v4.3.5 - with: - name: lint-logs - path: logs/* - - #- name: Prepare notification (only on error) - # if: step.lint.outcome == 'failure' - # id: prepare - # run: scripts/prepmsg.sh logs/build/err*.txt logs/notify.txt - # env: - # GITHUB_JOB: ${{ github.job }} - # GITHUB_RUN_ID: ${{ github.run_id }} - # GITHUB_REPOSITORY: ${{ github.repository }} - # - #- name: Notify via Telegram - # if: step.prepare.outcome == 'success' - # uses: appleboy/telegram-action@v0.1.1 - # with: - # to: ${{ secrets.TELEGRAM_TO }} - # token: ${{ secrets.TELEGRAM_TOKEN }} - # format: markdown - # disable_web_page_preview: true - # message_file: logs/notify.txt - - - # Spell check the PO files, and store them in logs/ directory - pospell: - name: Spell check translations - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4.1.7 - with: - fetch-depth: 5 - - - name: Set up Python 3 - uses: actions/setup-python@v5.1.1 - with: - python-version: '3' - - - name: Make sure the repository is up to date - if: github.event_name != 'pull_request' - run: git pull --rebase - - - name: Install Hunspell - run: sudo apt install hunspell hunspell-pt-br -y - - - name: Run pospell - continue-on-error: true - id: pospell - run: make spell - - - name: Upload artifact - log files - uses: actions/upload-artifact@v4.3.5 - with: - name: pospell-logs - path: logs/* - - - # Gather all strings in a single PO file, useful for Translation Memory - # Also run powrap, useful only for pull_request testing for dependabot - compendium: - runs-on: ubuntu-latest - steps: - - name: Check out ${{ github.repository }} - uses: actions/checkout@v4.1.7 - with: - fetch-depth: 5 - - - name: Set up Python 3 - uses: actions/setup-python@v5.1.1 - with: - python-version: '3' - - - name: Make sure the repository is up to date - if: github.event_name != 'pull_request' - run: git pull --rebase - - - name: Install dependencies - run: | - sudo apt update -y && sudo apt install gettext -y - pip3 install --upgrade pip - pip3 install -r requirements.txt - - - name: Generate compendium from PO files - run: | - pocompendium --correct compendium.po *.po **/*.po - powrap compendium.po - - - name: Upload artifact - uses: actions/upload-artifact@v4.3.5 - with: - name: compendium - path: compendium.po - - # List PO files that no longer have a corresponding page in Python docs - list-obsolete: - runs-on: ubuntu-latest - steps: - - name: Check out ${{ github.repository }} - uses: actions/checkout@v4.1.7 - - - name: Set up Python 3 - uses: actions/setup-python@v5.1.1 - with: - python-version: '3' - - - name: Generate POT files - run: make pot - - - name: List obsolete PO files, if any - run: python3 .github/scripts/list-obsolete.py diff --git a/.github/workflows/update.yml b/.github/workflows/update.yml deleted file mode 100644 index ac0f2e7c1..000000000 --- a/.github/workflows/update.yml +++ /dev/null @@ -1,226 +0,0 @@ -name: Update - -on: - workflow_dispatch: - inputs: - BRANCH: - description: CPython branch to use - required: false - type: string - default: '3.13' - pull_request: - paths: - - '.github/workflows/update.yml' - - 'Makefile' - - 'requirements.txt' - branches: - - '3.13' - push: - paths: - - '.github/workflows/update.yml' - - 'Makefile' - - 'requirements.txt' - branches: - - '3.13' - schedule: - - cron: '0 23 * * *' - -permissions: - contents: read - -jobs: - # Download translations from Transifex, keep PO and Logs artifacts - pull: - name: Pull from Transifex - runs-on: ubuntu-latest - steps: - - name: Check out ${{ github.repository }} - uses: actions/checkout@v4.1.7 - - - name: Get branch name on push or schedule - if: | - github.event_name == 'push' || - github.event_name == 'schedule' - run: echo "BRANCH=${GITHUB_REF_NAME}" >>$GITHUB_ENV - - - name: Get branch name on pull - if: github.event_name == 'pull_request' - run: echo "BRANCH=${GITHUB_BASE_REF}" >>$GITHUB_ENV - - - name: Get branch name on manual run - if: github.event_name == 'workflow_dispatch' - run: echo "BRANCH=${{ github.event.inputs.BRANCH }}" >> $GITHUB_ENV - - - name: Check out CPython - uses: actions/checkout@v4.1.7 - with: - repository: python/cpython - ref: ${{ env.BRANCH }} - path: cpython - - - name: Set up Python 3 - uses: actions/setup-python@v5.1.1 - with: - python-version: '3' - cache: 'pip' - cache-dependency-path: | - 'requirements.txt' - 'cpython/requirements.txt' - - - name: Install dependencies - run: sudo apt update -y && sudo apt install gettext tree -y - - - name: Pull translations - run: | - make tx-config TX_CLI_DIR=/usr/local/bin - if [ "${{ github.event_name }}" != 'pull_request' ]; then - make pull -o tx-config TX_CLI_DIR=/usr/local/bin - fi - env: - TX_TOKEN: ${{ secrets.TX_TOKEN }} - - - name: Upload artifact - po files - uses: actions/upload-artifact@v4.3.5 - with: - name: translations - path: | - *.po - **/*.po - .tx/ - - - name: Upload artifact - log files - if: always() - uses: actions/upload-artifact@v4.3.5 - with: - name: pull-logs - path: | - logs/* - /tmp/*.log - - - # Job for getting po files downloaded and storing this repository - push: - name: Push to repo - needs: [pull] - runs-on: ubuntu-latest - permissions: - contents: write - steps: - - name: Check out ${{ github.repository }} - uses: actions/checkout@v4.1.7 - - - name: Download PO files - uses: actions/download-artifact@v4.1.8 - with: - name: translations - - # Exclude file with only changes in POT-Creation-Date - - name: Changed files - shell: bash - run: | - git diff -I'^"POT-Creation-Date: ' --numstat *.po **/*.po | cut -f3 - git ls-files -o --exclude-standard *.po **/*.po - - - name: Commit and push changes - if: | - github.repository == 'python/python-docs-pt-br' && - github.event_name != 'pull_request' - run: | - git config user.name github-actions - git config user.email github-actions@github.com - make push - - - # Merge translations previously updated into older branches to make sure - # older versions of Python Docs gets translated as well. - # 'overwrite=true' means strings previously translated will get overwritten; - # other branches will preserve translated strings, only filling in new - # translations. - merge: - name: Merge into ${{ matrix.branch }} - needs: [push] - runs-on: ubuntu-latest - permissions: - contents: write - strategy: - fail-fast: false - max-parallel: 3 - matrix: - branch: ['3.12', '3.11', '3.10', '3.9', '3.8', '3.7', '3.6', '2.7'] - include: - - branch: 3.12 - overwrite: true - steps: - - name: Get branch name on push or schedule - if: | - github.event_name == 'push' || - github.event_name == 'schedule' - run: echo "CURRENT_BRANCH=${GITHUB_REF_NAME}" >>$GITHUB_ENV - - - name: Get branch name on pull - if: github.event_name == 'pull_request' - run: echo "CURRENT_BRANCH=${GITHUB_BASE_REF}" >>$GITHUB_ENV - - - name: Get branch name on manual run - if: github.event_name == 'workflow_dispatch' - run: echo "CURRENT_BRANCH=${{ github.event.inputs.BRANCH }}" >> $GITHUB_ENV - - - name: Check out source branch (${{ env.CURRENT_BRANCH }}) - uses: actions/checkout@v4.1.7 - with: - path: ${{ env.CURRENT_BRANCH }} - persist-credentials: false - - - name: Check out target branch (${{ matrix.branch }}) - uses: actions/checkout@v4.1.7 - with: - ref: ${{ matrix.branch }} - path: ${{ matrix.branch }} - - - name: Set up Python 3 - uses: actions/setup-python@v5.1.1 - with: - python-version: '3' - cache: 'pip' - cache-dependency-path: "${{ env.CURRENT_BRANCH }}/requirements.txt" - - - name: Install dependencies - run: | - sudo apt update -y && sudo apt install gettext -y - pip3 install pomerge powrap - - - name: Merge overwriting on stable release branch - if: ${{ matrix.overwrite == true }} - run: | - pomerge --from ${{ env.CURRENT_BRANCH }}/**/*.po --to ${{ matrix.branch }}/**/*.po - - - name: Merge without overwriting on EOL or security-fix release branch - if: ${{ matrix.overwrite != true }} - run: | - pomerge --no-overwrite --from ${{ env.CURRENT_BRANCH }}/**/*.po --to ${{ matrix.branch }}/**/*.po - - - name: Wrap catalog message files - run: | - powrap --modified -C ${{ matrix.branch }} - - #TODO: Solve make push to work with merge scenario - - name: Commit and push changes - if: | - github.repository == 'python/python-docs-pt-br' && - github.event_name != 'pull_request' - run: | - git config user.name github-actions - git config user.email github-actions@github.com - git diff -I'^"POT-Creation-Date: ' --numstat *.po **/*.po | cut -f3 | xargs -r git add - git add $(git ls-files -o --exclude-standard *.po **/*.po) .tx/config - git diff-index --cached --quiet HEAD || git commit -m "Merge ${{ env.CURRENT_BRANCH }} into ${{ matrix.branch }}" - working-directory: ${{ matrix.branch }} - - - # Call the check.yml workflow after updating to run some tests - call-build: - name: call - needs: push - if: github.event_name != 'pull_request' - uses: ./.github/workflows/check.yml - secrets: inherit diff --git a/.gitignore b/.gitignore index f5f9bf4ef..2a2ef4431 100644 --- a/.gitignore +++ b/.gitignore @@ -2,12 +2,8 @@ *.mo *.po~ -# we don't want venv directories -venv/ -.venv/ - # cpython checkout shouldn't be added cpython/ -# No need to keep logs -logs/ +# do not include potodo temporary file +.potodo/ diff --git a/.tx/config b/.tx/config index 56cdab6b6..5caa29b7d 100644 --- a/.tx/config +++ b/.tx/config @@ -1,4790 +1,5080 @@ [main] host = https://www.transifex.com -[o:python-doc:p:python-newest:r:about] -file_filter = .//LC_MESSAGES/about.po +[o:python-doc:p:python-313:r:about] +file_filter = about.po trans.pt_BR = about.po -source_file = ../../pot/about.pot +source_file = ../build/gettext/about.pot type = PO minimum_perc = 0 resource_name = about replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:bugs] -file_filter = .//LC_MESSAGES/bugs.po +[o:python-doc:p:python-313:r:bugs] +file_filter = bugs.po trans.pt_BR = bugs.po -source_file = ../../pot/bugs.pot +source_file = ../build/gettext/bugs.pot type = PO minimum_perc = 0 resource_name = bugs replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--abstract] -file_filter = .//LC_MESSAGES/c-api/abstract.po +[o:python-doc:p:python-313:r:c-api--abstract] +file_filter = c-api/abstract.po trans.pt_BR = c-api/abstract.po -source_file = ../../pot/c-api/abstract.pot +source_file = ../build/gettext/c-api/abstract.pot type = PO minimum_perc = 0 resource_name = c-api--abstract replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--allocation] -file_filter = .//LC_MESSAGES/c-api/allocation.po +[o:python-doc:p:python-313:r:c-api--allocation] +file_filter = c-api/allocation.po trans.pt_BR = c-api/allocation.po -source_file = ../../pot/c-api/allocation.pot +source_file = ../build/gettext/c-api/allocation.pot type = PO minimum_perc = 0 resource_name = c-api--allocation replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--apiabiversion] -file_filter = .//LC_MESSAGES/c-api/apiabiversion.po +[o:python-doc:p:python-313:r:c-api--apiabiversion] +file_filter = c-api/apiabiversion.po trans.pt_BR = c-api/apiabiversion.po -source_file = ../../pot/c-api/apiabiversion.pot +source_file = ../build/gettext/c-api/apiabiversion.pot type = PO minimum_perc = 0 resource_name = c-api--apiabiversion replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--arg] -file_filter = .//LC_MESSAGES/c-api/arg.po +[o:python-doc:p:python-313:r:c-api--arg] +file_filter = c-api/arg.po trans.pt_BR = c-api/arg.po -source_file = ../../pot/c-api/arg.pot +source_file = ../build/gettext/c-api/arg.pot type = PO minimum_perc = 0 resource_name = c-api--arg replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--bool] -file_filter = .//LC_MESSAGES/c-api/bool.po +[o:python-doc:p:python-313:r:c-api--bool] +file_filter = c-api/bool.po trans.pt_BR = c-api/bool.po -source_file = ../../pot/c-api/bool.pot +source_file = ../build/gettext/c-api/bool.pot type = PO minimum_perc = 0 resource_name = c-api--bool replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--buffer] -file_filter = .//LC_MESSAGES/c-api/buffer.po +[o:python-doc:p:python-313:r:c-api--buffer] +file_filter = c-api/buffer.po trans.pt_BR = c-api/buffer.po -source_file = ../../pot/c-api/buffer.pot +source_file = ../build/gettext/c-api/buffer.pot type = PO minimum_perc = 0 resource_name = c-api--buffer replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--bytearray] -file_filter = .//LC_MESSAGES/c-api/bytearray.po +[o:python-doc:p:python-313:r:c-api--bytearray] +file_filter = c-api/bytearray.po trans.pt_BR = c-api/bytearray.po -source_file = ../../pot/c-api/bytearray.pot +source_file = ../build/gettext/c-api/bytearray.pot type = PO minimum_perc = 0 resource_name = c-api--bytearray replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--bytes] -file_filter = .//LC_MESSAGES/c-api/bytes.po +[o:python-doc:p:python-313:r:c-api--bytes] +file_filter = c-api/bytes.po trans.pt_BR = c-api/bytes.po -source_file = ../../pot/c-api/bytes.pot +source_file = ../build/gettext/c-api/bytes.pot type = PO minimum_perc = 0 resource_name = c-api--bytes replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--call] -file_filter = .//LC_MESSAGES/c-api/call.po +[o:python-doc:p:python-313:r:c-api--call] +file_filter = c-api/call.po trans.pt_BR = c-api/call.po -source_file = ../../pot/c-api/call.pot +source_file = ../build/gettext/c-api/call.pot type = PO minimum_perc = 0 resource_name = c-api--call replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--capsule] -file_filter = .//LC_MESSAGES/c-api/capsule.po +[o:python-doc:p:python-313:r:c-api--capsule] +file_filter = c-api/capsule.po trans.pt_BR = c-api/capsule.po -source_file = ../../pot/c-api/capsule.pot +source_file = ../build/gettext/c-api/capsule.pot type = PO minimum_perc = 0 resource_name = c-api--capsule replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--cell] -file_filter = .//LC_MESSAGES/c-api/cell.po +[o:python-doc:p:python-313:r:c-api--cell] +file_filter = c-api/cell.po trans.pt_BR = c-api/cell.po -source_file = ../../pot/c-api/cell.pot +source_file = ../build/gettext/c-api/cell.pot type = PO minimum_perc = 0 resource_name = c-api--cell replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--code] -file_filter = .//LC_MESSAGES/c-api/code.po +[o:python-doc:p:python-313:r:c-api--code] +file_filter = c-api/code.po trans.pt_BR = c-api/code.po -source_file = ../../pot/c-api/code.pot +source_file = ../build/gettext/c-api/code.pot type = PO minimum_perc = 0 resource_name = c-api--code replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--codec] -file_filter = .//LC_MESSAGES/c-api/codec.po +[o:python-doc:p:python-313:r:c-api--codec] +file_filter = c-api/codec.po trans.pt_BR = c-api/codec.po -source_file = ../../pot/c-api/codec.pot +source_file = ../build/gettext/c-api/codec.pot type = PO minimum_perc = 0 resource_name = c-api--codec replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--complex] -file_filter = .//LC_MESSAGES/c-api/complex.po +[o:python-doc:p:python-313:r:c-api--complex] +file_filter = c-api/complex.po trans.pt_BR = c-api/complex.po -source_file = ../../pot/c-api/complex.pot +source_file = ../build/gettext/c-api/complex.pot type = PO minimum_perc = 0 resource_name = c-api--complex replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--concrete] -file_filter = .//LC_MESSAGES/c-api/concrete.po +[o:python-doc:p:python-313:r:c-api--concrete] +file_filter = c-api/concrete.po trans.pt_BR = c-api/concrete.po -source_file = ../../pot/c-api/concrete.pot +source_file = ../build/gettext/c-api/concrete.pot type = PO minimum_perc = 0 resource_name = c-api--concrete replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--contextvars] -file_filter = .//LC_MESSAGES/c-api/contextvars.po +[o:python-doc:p:python-313:r:c-api--contextvars] +file_filter = c-api/contextvars.po trans.pt_BR = c-api/contextvars.po -source_file = ../../pot/c-api/contextvars.pot +source_file = ../build/gettext/c-api/contextvars.pot type = PO minimum_perc = 0 resource_name = c-api--contextvars replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--conversion] -file_filter = .//LC_MESSAGES/c-api/conversion.po +[o:python-doc:p:python-313:r:c-api--conversion] +file_filter = c-api/conversion.po trans.pt_BR = c-api/conversion.po -source_file = ../../pot/c-api/conversion.pot +source_file = ../build/gettext/c-api/conversion.pot type = PO minimum_perc = 0 resource_name = c-api--conversion replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--coro] -file_filter = .//LC_MESSAGES/c-api/coro.po +[o:python-doc:p:python-313:r:c-api--coro] +file_filter = c-api/coro.po trans.pt_BR = c-api/coro.po -source_file = ../../pot/c-api/coro.pot +source_file = ../build/gettext/c-api/coro.pot type = PO minimum_perc = 0 resource_name = c-api--coro replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--datetime] -file_filter = .//LC_MESSAGES/c-api/datetime.po +[o:python-doc:p:python-313:r:c-api--datetime] +file_filter = c-api/datetime.po trans.pt_BR = c-api/datetime.po -source_file = ../../pot/c-api/datetime.pot +source_file = ../build/gettext/c-api/datetime.pot type = PO minimum_perc = 0 resource_name = c-api--datetime replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--descriptor] -file_filter = .//LC_MESSAGES/c-api/descriptor.po +[o:python-doc:p:python-313:r:c-api--descriptor] +file_filter = c-api/descriptor.po trans.pt_BR = c-api/descriptor.po -source_file = ../../pot/c-api/descriptor.pot +source_file = ../build/gettext/c-api/descriptor.pot type = PO minimum_perc = 0 resource_name = c-api--descriptor replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--dict] -file_filter = .//LC_MESSAGES/c-api/dict.po +[o:python-doc:p:python-313:r:c-api--dict] +file_filter = c-api/dict.po trans.pt_BR = c-api/dict.po -source_file = ../../pot/c-api/dict.pot +source_file = ../build/gettext/c-api/dict.pot type = PO minimum_perc = 0 resource_name = c-api--dict replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--exceptions] -file_filter = .//LC_MESSAGES/c-api/exceptions.po +[o:python-doc:p:python-313:r:c-api--exceptions] +file_filter = c-api/exceptions.po trans.pt_BR = c-api/exceptions.po -source_file = ../../pot/c-api/exceptions.pot +source_file = ../build/gettext/c-api/exceptions.pot type = PO minimum_perc = 0 resource_name = c-api--exceptions replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--file] -file_filter = .//LC_MESSAGES/c-api/file.po +[o:python-doc:p:python-313:r:c-api--file] +file_filter = c-api/file.po trans.pt_BR = c-api/file.po -source_file = ../../pot/c-api/file.pot +source_file = ../build/gettext/c-api/file.pot type = PO minimum_perc = 0 resource_name = c-api--file replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--float] -file_filter = .//LC_MESSAGES/c-api/float.po +[o:python-doc:p:python-313:r:c-api--float] +file_filter = c-api/float.po trans.pt_BR = c-api/float.po -source_file = ../../pot/c-api/float.pot +source_file = ../build/gettext/c-api/float.pot type = PO minimum_perc = 0 resource_name = c-api--float replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--frame] -file_filter = .//LC_MESSAGES/c-api/frame.po +[o:python-doc:p:python-313:r:c-api--frame] +file_filter = c-api/frame.po trans.pt_BR = c-api/frame.po -source_file = ../../pot/c-api/frame.pot +source_file = ../build/gettext/c-api/frame.pot type = PO minimum_perc = 0 resource_name = c-api--frame replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--function] -file_filter = .//LC_MESSAGES/c-api/function.po +[o:python-doc:p:python-313:r:c-api--function] +file_filter = c-api/function.po trans.pt_BR = c-api/function.po -source_file = ../../pot/c-api/function.pot +source_file = ../build/gettext/c-api/function.pot type = PO minimum_perc = 0 resource_name = c-api--function replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--gcsupport] -file_filter = .//LC_MESSAGES/c-api/gcsupport.po +[o:python-doc:p:python-313:r:c-api--gcsupport] +file_filter = c-api/gcsupport.po trans.pt_BR = c-api/gcsupport.po -source_file = ../../pot/c-api/gcsupport.pot +source_file = ../build/gettext/c-api/gcsupport.pot type = PO minimum_perc = 0 resource_name = c-api--gcsupport replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--gen] -file_filter = .//LC_MESSAGES/c-api/gen.po +[o:python-doc:p:python-313:r:c-api--gen] +file_filter = c-api/gen.po trans.pt_BR = c-api/gen.po -source_file = ../../pot/c-api/gen.pot +source_file = ../build/gettext/c-api/gen.pot type = PO minimum_perc = 0 resource_name = c-api--gen replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--hash] -file_filter = .//LC_MESSAGES/c-api/hash.po +[o:python-doc:p:python-313:r:c-api--hash] +file_filter = c-api/hash.po trans.pt_BR = c-api/hash.po -source_file = ../../pot/c-api/hash.pot +source_file = ../build/gettext/c-api/hash.pot type = PO minimum_perc = 0 resource_name = c-api--hash replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--import] -file_filter = .//LC_MESSAGES/c-api/import.po +[o:python-doc:p:python-313:r:c-api--import] +file_filter = c-api/import.po trans.pt_BR = c-api/import.po -source_file = ../../pot/c-api/import.pot +source_file = ../build/gettext/c-api/import.pot type = PO minimum_perc = 0 resource_name = c-api--import replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--index] -file_filter = .//LC_MESSAGES/c-api/index.po +[o:python-doc:p:python-313:r:c-api--index] +file_filter = c-api/index.po trans.pt_BR = c-api/index.po -source_file = ../../pot/c-api/index.pot +source_file = ../build/gettext/c-api/index.pot type = PO minimum_perc = 0 resource_name = c-api--index replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--init] -file_filter = .//LC_MESSAGES/c-api/init.po +[o:python-doc:p:python-313:r:c-api--init] +file_filter = c-api/init.po trans.pt_BR = c-api/init.po -source_file = ../../pot/c-api/init.pot +source_file = ../build/gettext/c-api/init.pot type = PO minimum_perc = 0 resource_name = c-api--init replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--init_config] -file_filter = .//LC_MESSAGES/c-api/init_config.po +[o:python-doc:p:python-313:r:c-api--init_config] +file_filter = c-api/init_config.po trans.pt_BR = c-api/init_config.po -source_file = ../../pot/c-api/init_config.pot +source_file = ../build/gettext/c-api/init_config.pot type = PO minimum_perc = 0 resource_name = c-api--init_config replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--intro] -file_filter = .//LC_MESSAGES/c-api/intro.po +[o:python-doc:p:python-313:r:c-api--intro] +file_filter = c-api/intro.po trans.pt_BR = c-api/intro.po -source_file = ../../pot/c-api/intro.pot +source_file = ../build/gettext/c-api/intro.pot type = PO minimum_perc = 0 resource_name = c-api--intro replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--iter] -file_filter = .//LC_MESSAGES/c-api/iter.po +[o:python-doc:p:python-313:r:c-api--iter] +file_filter = c-api/iter.po trans.pt_BR = c-api/iter.po -source_file = ../../pot/c-api/iter.pot +source_file = ../build/gettext/c-api/iter.pot type = PO minimum_perc = 0 resource_name = c-api--iter replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--iterator] -file_filter = .//LC_MESSAGES/c-api/iterator.po +[o:python-doc:p:python-313:r:c-api--iterator] +file_filter = c-api/iterator.po trans.pt_BR = c-api/iterator.po -source_file = ../../pot/c-api/iterator.pot +source_file = ../build/gettext/c-api/iterator.pot type = PO minimum_perc = 0 resource_name = c-api--iterator replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--list] -file_filter = .//LC_MESSAGES/c-api/list.po +[o:python-doc:p:python-313:r:c-api--list] +file_filter = c-api/list.po trans.pt_BR = c-api/list.po -source_file = ../../pot/c-api/list.pot +source_file = ../build/gettext/c-api/list.pot type = PO minimum_perc = 0 resource_name = c-api--list replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--long] -file_filter = .//LC_MESSAGES/c-api/long.po +[o:python-doc:p:python-313:r:c-api--long] +file_filter = c-api/long.po trans.pt_BR = c-api/long.po -source_file = ../../pot/c-api/long.pot +source_file = ../build/gettext/c-api/long.pot type = PO minimum_perc = 0 resource_name = c-api--long replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--mapping] -file_filter = .//LC_MESSAGES/c-api/mapping.po +[o:python-doc:p:python-313:r:c-api--mapping] +file_filter = c-api/mapping.po trans.pt_BR = c-api/mapping.po -source_file = ../../pot/c-api/mapping.pot +source_file = ../build/gettext/c-api/mapping.pot type = PO minimum_perc = 0 resource_name = c-api--mapping replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--marshal] -file_filter = .//LC_MESSAGES/c-api/marshal.po +[o:python-doc:p:python-313:r:c-api--marshal] +file_filter = c-api/marshal.po trans.pt_BR = c-api/marshal.po -source_file = ../../pot/c-api/marshal.pot +source_file = ../build/gettext/c-api/marshal.pot type = PO minimum_perc = 0 resource_name = c-api--marshal replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--memory] -file_filter = .//LC_MESSAGES/c-api/memory.po +[o:python-doc:p:python-313:r:c-api--memory] +file_filter = c-api/memory.po trans.pt_BR = c-api/memory.po -source_file = ../../pot/c-api/memory.pot +source_file = ../build/gettext/c-api/memory.pot type = PO minimum_perc = 0 resource_name = c-api--memory replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--memoryview] -file_filter = .//LC_MESSAGES/c-api/memoryview.po +[o:python-doc:p:python-313:r:c-api--memoryview] +file_filter = c-api/memoryview.po trans.pt_BR = c-api/memoryview.po -source_file = ../../pot/c-api/memoryview.pot +source_file = ../build/gettext/c-api/memoryview.pot type = PO minimum_perc = 0 resource_name = c-api--memoryview replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--method] -file_filter = .//LC_MESSAGES/c-api/method.po +[o:python-doc:p:python-313:r:c-api--method] +file_filter = c-api/method.po trans.pt_BR = c-api/method.po -source_file = ../../pot/c-api/method.pot +source_file = ../build/gettext/c-api/method.pot type = PO minimum_perc = 0 resource_name = c-api--method replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--module] -file_filter = .//LC_MESSAGES/c-api/module.po +[o:python-doc:p:python-313:r:c-api--module] +file_filter = c-api/module.po trans.pt_BR = c-api/module.po -source_file = ../../pot/c-api/module.pot +source_file = ../build/gettext/c-api/module.pot type = PO minimum_perc = 0 resource_name = c-api--module replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--monitoring] -file_filter = .//LC_MESSAGES/c-api/monitoring.po +[o:python-doc:p:python-313:r:c-api--monitoring] +file_filter = c-api/monitoring.po trans.pt_BR = c-api/monitoring.po -source_file = ../../pot/c-api/monitoring.pot +source_file = ../build/gettext/c-api/monitoring.pot type = PO minimum_perc = 0 resource_name = c-api--monitoring replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--none] -file_filter = .//LC_MESSAGES/c-api/none.po +[o:python-doc:p:python-313:r:c-api--none] +file_filter = c-api/none.po trans.pt_BR = c-api/none.po -source_file = ../../pot/c-api/none.pot +source_file = ../build/gettext/c-api/none.pot type = PO minimum_perc = 0 resource_name = c-api--none replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--number] -file_filter = .//LC_MESSAGES/c-api/number.po +[o:python-doc:p:python-313:r:c-api--number] +file_filter = c-api/number.po trans.pt_BR = c-api/number.po -source_file = ../../pot/c-api/number.pot +source_file = ../build/gettext/c-api/number.pot type = PO minimum_perc = 0 resource_name = c-api--number replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--object] -file_filter = .//LC_MESSAGES/c-api/object.po +[o:python-doc:p:python-313:r:c-api--object] +file_filter = c-api/object.po trans.pt_BR = c-api/object.po -source_file = ../../pot/c-api/object.pot +source_file = ../build/gettext/c-api/object.pot type = PO minimum_perc = 0 resource_name = c-api--object replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--objimpl] -file_filter = .//LC_MESSAGES/c-api/objimpl.po +[o:python-doc:p:python-313:r:c-api--objimpl] +file_filter = c-api/objimpl.po trans.pt_BR = c-api/objimpl.po -source_file = ../../pot/c-api/objimpl.pot +source_file = ../build/gettext/c-api/objimpl.pot type = PO minimum_perc = 0 resource_name = c-api--objimpl replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--perfmaps] -file_filter = .//LC_MESSAGES/c-api/perfmaps.po +[o:python-doc:p:python-313:r:c-api--perfmaps] +file_filter = c-api/perfmaps.po trans.pt_BR = c-api/perfmaps.po -source_file = ../../pot/c-api/perfmaps.pot +source_file = ../build/gettext/c-api/perfmaps.pot type = PO minimum_perc = 0 resource_name = c-api--perfmaps replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--refcounting] -file_filter = .//LC_MESSAGES/c-api/refcounting.po +[o:python-doc:p:python-313:r:c-api--refcounting] +file_filter = c-api/refcounting.po trans.pt_BR = c-api/refcounting.po -source_file = ../../pot/c-api/refcounting.pot +source_file = ../build/gettext/c-api/refcounting.pot type = PO minimum_perc = 0 resource_name = c-api--refcounting replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--reflection] -file_filter = .//LC_MESSAGES/c-api/reflection.po +[o:python-doc:p:python-313:r:c-api--reflection] +file_filter = c-api/reflection.po trans.pt_BR = c-api/reflection.po -source_file = ../../pot/c-api/reflection.pot +source_file = ../build/gettext/c-api/reflection.pot type = PO minimum_perc = 0 resource_name = c-api--reflection replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--sequence] -file_filter = .//LC_MESSAGES/c-api/sequence.po +[o:python-doc:p:python-313:r:c-api--sequence] +file_filter = c-api/sequence.po trans.pt_BR = c-api/sequence.po -source_file = ../../pot/c-api/sequence.pot +source_file = ../build/gettext/c-api/sequence.pot type = PO minimum_perc = 0 resource_name = c-api--sequence replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--set] -file_filter = .//LC_MESSAGES/c-api/set.po +[o:python-doc:p:python-313:r:c-api--set] +file_filter = c-api/set.po trans.pt_BR = c-api/set.po -source_file = ../../pot/c-api/set.pot +source_file = ../build/gettext/c-api/set.pot type = PO minimum_perc = 0 resource_name = c-api--set replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--slice] -file_filter = .//LC_MESSAGES/c-api/slice.po +[o:python-doc:p:python-313:r:c-api--slice] +file_filter = c-api/slice.po trans.pt_BR = c-api/slice.po -source_file = ../../pot/c-api/slice.pot +source_file = ../build/gettext/c-api/slice.pot type = PO minimum_perc = 0 resource_name = c-api--slice replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--stable] -file_filter = .//LC_MESSAGES/c-api/stable.po +[o:python-doc:p:python-313:r:c-api--stable] +file_filter = c-api/stable.po trans.pt_BR = c-api/stable.po -source_file = ../../pot/c-api/stable.pot +source_file = ../build/gettext/c-api/stable.pot type = PO minimum_perc = 0 resource_name = c-api--stable replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--structures] -file_filter = .//LC_MESSAGES/c-api/structures.po +[o:python-doc:p:python-313:r:c-api--structures] +file_filter = c-api/structures.po trans.pt_BR = c-api/structures.po -source_file = ../../pot/c-api/structures.pot +source_file = ../build/gettext/c-api/structures.pot type = PO minimum_perc = 0 resource_name = c-api--structures replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--sys] -file_filter = .//LC_MESSAGES/c-api/sys.po +[o:python-doc:p:python-313:r:c-api--sys] +file_filter = c-api/sys.po trans.pt_BR = c-api/sys.po -source_file = ../../pot/c-api/sys.pot +source_file = ../build/gettext/c-api/sys.pot type = PO minimum_perc = 0 resource_name = c-api--sys replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--time] -file_filter = .//LC_MESSAGES/c-api/time.po +[o:python-doc:p:python-313:r:c-api--time] +file_filter = c-api/time.po trans.pt_BR = c-api/time.po -source_file = ../../pot/c-api/time.pot +source_file = ../build/gettext/c-api/time.pot type = PO minimum_perc = 0 resource_name = c-api--time replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--tuple] -file_filter = .//LC_MESSAGES/c-api/tuple.po +[o:python-doc:p:python-313:r:c-api--tuple] +file_filter = c-api/tuple.po trans.pt_BR = c-api/tuple.po -source_file = ../../pot/c-api/tuple.pot +source_file = ../build/gettext/c-api/tuple.pot type = PO minimum_perc = 0 resource_name = c-api--tuple replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--type] -file_filter = .//LC_MESSAGES/c-api/type.po +[o:python-doc:p:python-313:r:c-api--type] +file_filter = c-api/type.po trans.pt_BR = c-api/type.po -source_file = ../../pot/c-api/type.pot +source_file = ../build/gettext/c-api/type.pot type = PO minimum_perc = 0 resource_name = c-api--type replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--typehints] -file_filter = .//LC_MESSAGES/c-api/typehints.po +[o:python-doc:p:python-313:r:c-api--typehints] +file_filter = c-api/typehints.po trans.pt_BR = c-api/typehints.po -source_file = ../../pot/c-api/typehints.pot +source_file = ../build/gettext/c-api/typehints.pot type = PO minimum_perc = 0 resource_name = c-api--typehints replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--typeobj] -file_filter = .//LC_MESSAGES/c-api/typeobj.po +[o:python-doc:p:python-313:r:c-api--typeobj] +file_filter = c-api/typeobj.po trans.pt_BR = c-api/typeobj.po -source_file = ../../pot/c-api/typeobj.pot +source_file = ../build/gettext/c-api/typeobj.pot type = PO minimum_perc = 0 resource_name = c-api--typeobj replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--unicode] -file_filter = .//LC_MESSAGES/c-api/unicode.po +[o:python-doc:p:python-313:r:c-api--unicode] +file_filter = c-api/unicode.po trans.pt_BR = c-api/unicode.po -source_file = ../../pot/c-api/unicode.pot +source_file = ../build/gettext/c-api/unicode.pot type = PO minimum_perc = 0 resource_name = c-api--unicode replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--utilities] -file_filter = .//LC_MESSAGES/c-api/utilities.po +[o:python-doc:p:python-313:r:c-api--utilities] +file_filter = c-api/utilities.po trans.pt_BR = c-api/utilities.po -source_file = ../../pot/c-api/utilities.pot +source_file = ../build/gettext/c-api/utilities.pot type = PO minimum_perc = 0 resource_name = c-api--utilities replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--veryhigh] -file_filter = .//LC_MESSAGES/c-api/veryhigh.po +[o:python-doc:p:python-313:r:c-api--veryhigh] +file_filter = c-api/veryhigh.po trans.pt_BR = c-api/veryhigh.po -source_file = ../../pot/c-api/veryhigh.pot +source_file = ../build/gettext/c-api/veryhigh.pot type = PO minimum_perc = 0 resource_name = c-api--veryhigh replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:c-api--weakref] -file_filter = .//LC_MESSAGES/c-api/weakref.po +[o:python-doc:p:python-313:r:c-api--weakref] +file_filter = c-api/weakref.po trans.pt_BR = c-api/weakref.po -source_file = ../../pot/c-api/weakref.pot +source_file = ../build/gettext/c-api/weakref.pot type = PO minimum_perc = 0 resource_name = c-api--weakref replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:contents] -file_filter = .//LC_MESSAGES/contents.po +[o:python-doc:p:python-313:r:contents] +file_filter = contents.po trans.pt_BR = contents.po -source_file = ../../pot/contents.pot +source_file = ../build/gettext/contents.pot type = PO minimum_perc = 0 resource_name = contents replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:copyright] -file_filter = .//LC_MESSAGES/copyright.po +[o:python-doc:p:python-313:r:copyright] +file_filter = copyright.po trans.pt_BR = copyright.po -source_file = ../../pot/copyright.pot +source_file = ../build/gettext/copyright.pot type = PO minimum_perc = 0 resource_name = copyright replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:deprecations--c-api-pending-removal-in-3_14] -file_filter = .//LC_MESSAGES/deprecations/c-api-pending-removal-in-3.14.po +[o:python-doc:p:python-313:r:deprecations--c-api-pending-removal-in-3_14] +file_filter = deprecations/c-api-pending-removal-in-3.14.po trans.pt_BR = deprecations/c-api-pending-removal-in-3.14.po -source_file = ../../pot/deprecations/c-api-pending-removal-in-3.14.pot +source_file = ../build/gettext/deprecations/c-api-pending-removal-in-3.14.pot type = PO minimum_perc = 0 resource_name = deprecations--c-api-pending-removal-in-3_14 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:deprecations--c-api-pending-removal-in-3_15] -file_filter = .//LC_MESSAGES/deprecations/c-api-pending-removal-in-3.15.po +[o:python-doc:p:python-313:r:deprecations--c-api-pending-removal-in-3_15] +file_filter = deprecations/c-api-pending-removal-in-3.15.po trans.pt_BR = deprecations/c-api-pending-removal-in-3.15.po -source_file = ../../pot/deprecations/c-api-pending-removal-in-3.15.pot +source_file = ../build/gettext/deprecations/c-api-pending-removal-in-3.15.pot type = PO minimum_perc = 0 resource_name = deprecations--c-api-pending-removal-in-3_15 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:deprecations--c-api-pending-removal-in-future] -file_filter = .//LC_MESSAGES/deprecations/c-api-pending-removal-in-future.po +[o:python-doc:p:python-313:r:deprecations--c-api-pending-removal-in-future] +file_filter = deprecations/c-api-pending-removal-in-future.po trans.pt_BR = deprecations/c-api-pending-removal-in-future.po -source_file = ../../pot/deprecations/c-api-pending-removal-in-future.pot +source_file = ../build/gettext/deprecations/c-api-pending-removal-in-future.pot type = PO minimum_perc = 0 resource_name = deprecations--c-api-pending-removal-in-future replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:deprecations--index] -file_filter = .//LC_MESSAGES/deprecations/index.po +[o:python-doc:p:python-313:r:deprecations--index] +file_filter = deprecations/index.po trans.pt_BR = deprecations/index.po -source_file = ../../pot/deprecations/index.pot +source_file = ../build/gettext/deprecations/index.pot type = PO minimum_perc = 0 resource_name = deprecations--index replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:deprecations--pending-removal-in-3_13] -file_filter = .//LC_MESSAGES/deprecations/pending-removal-in-3.13.po +[o:python-doc:p:python-313:r:deprecations--pending-removal-in-3_13] +file_filter = deprecations/pending-removal-in-3.13.po trans.pt_BR = deprecations/pending-removal-in-3.13.po -source_file = ../../pot/deprecations/pending-removal-in-3.13.pot +source_file = ../build/gettext/deprecations/pending-removal-in-3.13.pot type = PO minimum_perc = 0 resource_name = deprecations--pending-removal-in-3_13 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:deprecations--pending-removal-in-3_14] -file_filter = .//LC_MESSAGES/deprecations/pending-removal-in-3.14.po +[o:python-doc:p:python-313:r:deprecations--pending-removal-in-3_14] +file_filter = deprecations/pending-removal-in-3.14.po trans.pt_BR = deprecations/pending-removal-in-3.14.po -source_file = ../../pot/deprecations/pending-removal-in-3.14.pot +source_file = ../build/gettext/deprecations/pending-removal-in-3.14.pot type = PO minimum_perc = 0 resource_name = deprecations--pending-removal-in-3_14 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:deprecations--pending-removal-in-3_15] -file_filter = .//LC_MESSAGES/deprecations/pending-removal-in-3.15.po +[o:python-doc:p:python-313:r:deprecations--pending-removal-in-3_15] +file_filter = deprecations/pending-removal-in-3.15.po trans.pt_BR = deprecations/pending-removal-in-3.15.po -source_file = ../../pot/deprecations/pending-removal-in-3.15.pot +source_file = ../build/gettext/deprecations/pending-removal-in-3.15.pot type = PO minimum_perc = 0 resource_name = deprecations--pending-removal-in-3_15 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:deprecations--pending-removal-in-3_16] -file_filter = .//LC_MESSAGES/deprecations/pending-removal-in-3.16.po +[o:python-doc:p:python-313:r:deprecations--pending-removal-in-3_16] +file_filter = deprecations/pending-removal-in-3.16.po trans.pt_BR = deprecations/pending-removal-in-3.16.po -source_file = ../../pot/deprecations/pending-removal-in-3.16.pot +source_file = ../build/gettext/deprecations/pending-removal-in-3.16.pot type = PO minimum_perc = 0 resource_name = deprecations--pending-removal-in-3_16 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:deprecations--pending-removal-in-future] -file_filter = .//LC_MESSAGES/deprecations/pending-removal-in-future.po +[o:python-doc:p:python-313:r:deprecations--pending-removal-in-future] +file_filter = deprecations/pending-removal-in-future.po trans.pt_BR = deprecations/pending-removal-in-future.po -source_file = ../../pot/deprecations/pending-removal-in-future.pot +source_file = ../build/gettext/deprecations/pending-removal-in-future.pot type = PO minimum_perc = 0 resource_name = deprecations--pending-removal-in-future replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:distributing--index] -file_filter = .//LC_MESSAGES/distributing/index.po +[o:python-doc:p:python-313:r:distributing--index] +file_filter = distributing/index.po trans.pt_BR = distributing/index.po -source_file = ../../pot/distributing/index.pot +source_file = ../build/gettext/distributing/index.pot type = PO minimum_perc = 0 resource_name = distributing--index replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:extending--building] -file_filter = .//LC_MESSAGES/extending/building.po +[o:python-doc:p:python-313:r:extending--building] +file_filter = extending/building.po trans.pt_BR = extending/building.po -source_file = ../../pot/extending/building.pot +source_file = ../build/gettext/extending/building.pot type = PO minimum_perc = 0 resource_name = extending--building replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:extending--embedding] -file_filter = .//LC_MESSAGES/extending/embedding.po +[o:python-doc:p:python-313:r:extending--embedding] +file_filter = extending/embedding.po trans.pt_BR = extending/embedding.po -source_file = ../../pot/extending/embedding.pot +source_file = ../build/gettext/extending/embedding.pot type = PO minimum_perc = 0 resource_name = extending--embedding replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:extending--extending] -file_filter = .//LC_MESSAGES/extending/extending.po +[o:python-doc:p:python-313:r:extending--extending] +file_filter = extending/extending.po trans.pt_BR = extending/extending.po -source_file = ../../pot/extending/extending.pot +source_file = ../build/gettext/extending/extending.pot type = PO minimum_perc = 0 resource_name = extending--extending replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:extending--index] -file_filter = .//LC_MESSAGES/extending/index.po +[o:python-doc:p:python-313:r:extending--index] +file_filter = extending/index.po trans.pt_BR = extending/index.po -source_file = ../../pot/extending/index.pot +source_file = ../build/gettext/extending/index.pot type = PO minimum_perc = 0 resource_name = extending--index replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:extending--newtypes] -file_filter = .//LC_MESSAGES/extending/newtypes.po +[o:python-doc:p:python-313:r:extending--newtypes] +file_filter = extending/newtypes.po trans.pt_BR = extending/newtypes.po -source_file = ../../pot/extending/newtypes.pot +source_file = ../build/gettext/extending/newtypes.pot type = PO minimum_perc = 0 resource_name = extending--newtypes replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:extending--newtypes_tutorial] -file_filter = .//LC_MESSAGES/extending/newtypes_tutorial.po +[o:python-doc:p:python-313:r:extending--newtypes_tutorial] +file_filter = extending/newtypes_tutorial.po trans.pt_BR = extending/newtypes_tutorial.po -source_file = ../../pot/extending/newtypes_tutorial.pot +source_file = ../build/gettext/extending/newtypes_tutorial.pot type = PO minimum_perc = 0 resource_name = extending--newtypes_tutorial replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:extending--windows] -file_filter = .//LC_MESSAGES/extending/windows.po +[o:python-doc:p:python-313:r:extending--windows] +file_filter = extending/windows.po trans.pt_BR = extending/windows.po -source_file = ../../pot/extending/windows.pot +source_file = ../build/gettext/extending/windows.pot type = PO minimum_perc = 0 resource_name = extending--windows replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:faq--design] -file_filter = .//LC_MESSAGES/faq/design.po +[o:python-doc:p:python-313:r:faq--design] +file_filter = faq/design.po trans.pt_BR = faq/design.po -source_file = ../../pot/faq/design.pot +source_file = ../build/gettext/faq/design.pot type = PO minimum_perc = 0 resource_name = faq--design replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:faq--extending] -file_filter = .//LC_MESSAGES/faq/extending.po +[o:python-doc:p:python-313:r:faq--extending] +file_filter = faq/extending.po trans.pt_BR = faq/extending.po -source_file = ../../pot/faq/extending.pot +source_file = ../build/gettext/faq/extending.pot type = PO minimum_perc = 0 resource_name = faq--extending replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:faq--general] -file_filter = .//LC_MESSAGES/faq/general.po +[o:python-doc:p:python-313:r:faq--general] +file_filter = faq/general.po trans.pt_BR = faq/general.po -source_file = ../../pot/faq/general.pot +source_file = ../build/gettext/faq/general.pot type = PO minimum_perc = 0 resource_name = faq--general replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:faq--gui] -file_filter = .//LC_MESSAGES/faq/gui.po +[o:python-doc:p:python-313:r:faq--gui] +file_filter = faq/gui.po trans.pt_BR = faq/gui.po -source_file = ../../pot/faq/gui.pot +source_file = ../build/gettext/faq/gui.pot type = PO minimum_perc = 0 resource_name = faq--gui replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:faq--index] -file_filter = .//LC_MESSAGES/faq/index.po +[o:python-doc:p:python-313:r:faq--index] +file_filter = faq/index.po trans.pt_BR = faq/index.po -source_file = ../../pot/faq/index.pot +source_file = ../build/gettext/faq/index.pot type = PO minimum_perc = 0 resource_name = faq--index replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:faq--installed] -file_filter = .//LC_MESSAGES/faq/installed.po +[o:python-doc:p:python-313:r:faq--installed] +file_filter = faq/installed.po trans.pt_BR = faq/installed.po -source_file = ../../pot/faq/installed.pot +source_file = ../build/gettext/faq/installed.pot type = PO minimum_perc = 0 resource_name = faq--installed replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:faq--library] -file_filter = .//LC_MESSAGES/faq/library.po +[o:python-doc:p:python-313:r:faq--library] +file_filter = faq/library.po trans.pt_BR = faq/library.po -source_file = ../../pot/faq/library.pot +source_file = ../build/gettext/faq/library.pot type = PO minimum_perc = 0 resource_name = faq--library replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:faq--programming] -file_filter = .//LC_MESSAGES/faq/programming.po +[o:python-doc:p:python-313:r:faq--programming] +file_filter = faq/programming.po trans.pt_BR = faq/programming.po -source_file = ../../pot/faq/programming.pot +source_file = ../build/gettext/faq/programming.pot type = PO minimum_perc = 0 resource_name = faq--programming replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:faq--windows] -file_filter = .//LC_MESSAGES/faq/windows.po +[o:python-doc:p:python-313:r:faq--windows] +file_filter = faq/windows.po trans.pt_BR = faq/windows.po -source_file = ../../pot/faq/windows.pot +source_file = ../build/gettext/faq/windows.pot type = PO minimum_perc = 0 resource_name = faq--windows replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:glossary_] -file_filter = .//LC_MESSAGES/glossary.po +[o:python-doc:p:python-313:r:glossary_] +file_filter = glossary.po trans.pt_BR = glossary.po -source_file = ../../pot/glossary.pot +source_file = ../build/gettext/glossary.pot type = PO minimum_perc = 0 resource_name = glossary_ replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--annotations] -file_filter = .//LC_MESSAGES/howto/annotations.po +[o:python-doc:p:python-313:r:howto--annotations] +file_filter = howto/annotations.po trans.pt_BR = howto/annotations.po -source_file = ../../pot/howto/annotations.pot +source_file = ../build/gettext/howto/annotations.pot type = PO minimum_perc = 0 resource_name = howto--annotations replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--argparse] -file_filter = .//LC_MESSAGES/howto/argparse.po +[o:python-doc:p:python-313:r:howto--argparse] +file_filter = howto/argparse.po trans.pt_BR = howto/argparse.po -source_file = ../../pot/howto/argparse.pot +source_file = ../build/gettext/howto/argparse.pot type = PO minimum_perc = 0 resource_name = howto--argparse replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--clinic] -file_filter = .//LC_MESSAGES/howto/clinic.po +[o:python-doc:p:python-313:r:howto--argparse-optparse] +file_filter = howto/argparse-optparse.po +trans.pt_BR = howto/argparse-optparse.po +source_file = ../build/gettext/howto/argparse-optparse.pot +type = PO +minimum_perc = 0 +resource_name = howto--argparse-optparse +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:howto--clinic] +file_filter = howto/clinic.po trans.pt_BR = howto/clinic.po -source_file = ../../pot/howto/clinic.pot +source_file = ../build/gettext/howto/clinic.pot type = PO minimum_perc = 0 resource_name = howto--clinic replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--cporting] -file_filter = .//LC_MESSAGES/howto/cporting.po +[o:python-doc:p:python-313:r:howto--cporting] +file_filter = howto/cporting.po trans.pt_BR = howto/cporting.po -source_file = ../../pot/howto/cporting.pot +source_file = ../build/gettext/howto/cporting.pot type = PO minimum_perc = 0 resource_name = howto--cporting replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--curses] -file_filter = .//LC_MESSAGES/howto/curses.po +[o:python-doc:p:python-313:r:howto--curses] +file_filter = howto/curses.po trans.pt_BR = howto/curses.po -source_file = ../../pot/howto/curses.pot +source_file = ../build/gettext/howto/curses.pot type = PO minimum_perc = 0 resource_name = howto--curses replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--descriptor] -file_filter = .//LC_MESSAGES/howto/descriptor.po +[o:python-doc:p:python-313:r:howto--descriptor] +file_filter = howto/descriptor.po trans.pt_BR = howto/descriptor.po -source_file = ../../pot/howto/descriptor.pot +source_file = ../build/gettext/howto/descriptor.pot type = PO minimum_perc = 0 resource_name = howto--descriptor replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--enum] -file_filter = .//LC_MESSAGES/howto/enum.po +[o:python-doc:p:python-313:r:howto--enum] +file_filter = howto/enum.po trans.pt_BR = howto/enum.po -source_file = ../../pot/howto/enum.pot +source_file = ../build/gettext/howto/enum.pot type = PO minimum_perc = 0 resource_name = howto--enum replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--free-threading-extensions] -file_filter = .//LC_MESSAGES/howto/free-threading-extensions.po +[o:python-doc:p:python-313:r:howto--free-threading-extensions] +file_filter = howto/free-threading-extensions.po trans.pt_BR = howto/free-threading-extensions.po -source_file = ../../pot/howto/free-threading-extensions.pot +source_file = ../build/gettext/howto/free-threading-extensions.pot type = PO minimum_perc = 0 resource_name = howto--free-threading-extensions replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--functional] -file_filter = .//LC_MESSAGES/howto/functional.po +[o:python-doc:p:python-313:r:howto--free-threading-python] +file_filter = howto/free-threading-python.po +trans.pt_BR = howto/free-threading-python.po +source_file = ../build/gettext/howto/free-threading-python.pot +type = PO +minimum_perc = 0 +resource_name = howto--free-threading-python +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:howto--functional] +file_filter = howto/functional.po trans.pt_BR = howto/functional.po -source_file = ../../pot/howto/functional.pot +source_file = ../build/gettext/howto/functional.pot type = PO minimum_perc = 0 resource_name = howto--functional replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--gdb_helpers] -file_filter = .//LC_MESSAGES/howto/gdb_helpers.po +[o:python-doc:p:python-313:r:howto--gdb_helpers] +file_filter = howto/gdb_helpers.po trans.pt_BR = howto/gdb_helpers.po -source_file = ../../pot/howto/gdb_helpers.pot +source_file = ../build/gettext/howto/gdb_helpers.pot type = PO minimum_perc = 0 resource_name = howto--gdb_helpers replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--index] -file_filter = .//LC_MESSAGES/howto/index.po +[o:python-doc:p:python-313:r:howto--index] +file_filter = howto/index.po trans.pt_BR = howto/index.po -source_file = ../../pot/howto/index.pot +source_file = ../build/gettext/howto/index.pot type = PO minimum_perc = 0 resource_name = howto--index replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--instrumentation] -file_filter = .//LC_MESSAGES/howto/instrumentation.po +[o:python-doc:p:python-313:r:howto--instrumentation] +file_filter = howto/instrumentation.po trans.pt_BR = howto/instrumentation.po -source_file = ../../pot/howto/instrumentation.pot +source_file = ../build/gettext/howto/instrumentation.pot type = PO minimum_perc = 0 resource_name = howto--instrumentation replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--ipaddress] -file_filter = .//LC_MESSAGES/howto/ipaddress.po +[o:python-doc:p:python-313:r:howto--ipaddress] +file_filter = howto/ipaddress.po trans.pt_BR = howto/ipaddress.po -source_file = ../../pot/howto/ipaddress.pot +source_file = ../build/gettext/howto/ipaddress.pot type = PO minimum_perc = 0 resource_name = howto--ipaddress replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--isolating-extensions] -file_filter = .//LC_MESSAGES/howto/isolating-extensions.po +[o:python-doc:p:python-313:r:howto--isolating-extensions] +file_filter = howto/isolating-extensions.po trans.pt_BR = howto/isolating-extensions.po -source_file = ../../pot/howto/isolating-extensions.pot +source_file = ../build/gettext/howto/isolating-extensions.pot type = PO minimum_perc = 0 resource_name = howto--isolating-extensions replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--logging] -file_filter = .//LC_MESSAGES/howto/logging.po +[o:python-doc:p:python-313:r:howto--logging] +file_filter = howto/logging.po trans.pt_BR = howto/logging.po -source_file = ../../pot/howto/logging.pot +source_file = ../build/gettext/howto/logging.pot type = PO minimum_perc = 0 resource_name = howto--logging replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--logging-cookbook] -file_filter = .//LC_MESSAGES/howto/logging-cookbook.po +[o:python-doc:p:python-313:r:howto--logging-cookbook] +file_filter = howto/logging-cookbook.po trans.pt_BR = howto/logging-cookbook.po -source_file = ../../pot/howto/logging-cookbook.pot +source_file = ../build/gettext/howto/logging-cookbook.pot type = PO minimum_perc = 0 resource_name = howto--logging-cookbook replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--mro] -file_filter = .//LC_MESSAGES/howto/mro.po +[o:python-doc:p:python-313:r:howto--mro] +file_filter = howto/mro.po trans.pt_BR = howto/mro.po -source_file = ../../pot/howto/mro.pot +source_file = ../build/gettext/howto/mro.pot type = PO minimum_perc = 0 resource_name = howto--mro replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--perf_profiling] -file_filter = .//LC_MESSAGES/howto/perf_profiling.po +[o:python-doc:p:python-313:r:howto--perf_profiling] +file_filter = howto/perf_profiling.po trans.pt_BR = howto/perf_profiling.po -source_file = ../../pot/howto/perf_profiling.pot +source_file = ../build/gettext/howto/perf_profiling.pot type = PO minimum_perc = 0 resource_name = howto--perf_profiling replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--pyporting] -file_filter = .//LC_MESSAGES/howto/pyporting.po +[o:python-doc:p:python-313:r:howto--pyporting] +file_filter = howto/pyporting.po trans.pt_BR = howto/pyporting.po -source_file = ../../pot/howto/pyporting.pot +source_file = ../build/gettext/howto/pyporting.pot type = PO minimum_perc = 0 resource_name = howto--pyporting replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--regex] -file_filter = .//LC_MESSAGES/howto/regex.po +[o:python-doc:p:python-313:r:howto--regex] +file_filter = howto/regex.po trans.pt_BR = howto/regex.po -source_file = ../../pot/howto/regex.pot +source_file = ../build/gettext/howto/regex.pot type = PO minimum_perc = 0 resource_name = howto--regex replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--sockets] -file_filter = .//LC_MESSAGES/howto/sockets.po +[o:python-doc:p:python-313:r:howto--sockets] +file_filter = howto/sockets.po trans.pt_BR = howto/sockets.po -source_file = ../../pot/howto/sockets.pot +source_file = ../build/gettext/howto/sockets.pot type = PO minimum_perc = 0 resource_name = howto--sockets replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--sorting] -file_filter = .//LC_MESSAGES/howto/sorting.po +[o:python-doc:p:python-313:r:howto--sorting] +file_filter = howto/sorting.po trans.pt_BR = howto/sorting.po -source_file = ../../pot/howto/sorting.pot +source_file = ../build/gettext/howto/sorting.pot type = PO minimum_perc = 0 resource_name = howto--sorting replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--timerfd] -file_filter = .//LC_MESSAGES/howto/timerfd.po +[o:python-doc:p:python-313:r:howto--timerfd] +file_filter = howto/timerfd.po trans.pt_BR = howto/timerfd.po -source_file = ../../pot/howto/timerfd.pot +source_file = ../build/gettext/howto/timerfd.pot type = PO minimum_perc = 0 resource_name = howto--timerfd replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--unicode] -file_filter = .//LC_MESSAGES/howto/unicode.po +[o:python-doc:p:python-313:r:howto--unicode] +file_filter = howto/unicode.po trans.pt_BR = howto/unicode.po -source_file = ../../pot/howto/unicode.pot +source_file = ../build/gettext/howto/unicode.pot type = PO minimum_perc = 0 resource_name = howto--unicode replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:howto--urllib2] -file_filter = .//LC_MESSAGES/howto/urllib2.po +[o:python-doc:p:python-313:r:howto--urllib2] +file_filter = howto/urllib2.po trans.pt_BR = howto/urllib2.po -source_file = ../../pot/howto/urllib2.pot +source_file = ../build/gettext/howto/urllib2.pot type = PO minimum_perc = 0 resource_name = howto--urllib2 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:installing--index] -file_filter = .//LC_MESSAGES/installing/index.po +[o:python-doc:p:python-313:r:installing--index] +file_filter = installing/index.po trans.pt_BR = installing/index.po -source_file = ../../pot/installing/index.pot +source_file = ../build/gettext/installing/index.pot type = PO minimum_perc = 0 resource_name = installing--index replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--__future__] -file_filter = .//LC_MESSAGES/library/__future__.po +[o:python-doc:p:python-313:r:library--__future__] +file_filter = library/__future__.po trans.pt_BR = library/__future__.po -source_file = ../../pot/library/__future__.pot +source_file = ../build/gettext/library/__future__.pot type = PO minimum_perc = 0 resource_name = library--__future__ replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--__main__] -file_filter = .//LC_MESSAGES/library/__main__.po +[o:python-doc:p:python-313:r:library--__main__] +file_filter = library/__main__.po trans.pt_BR = library/__main__.po -source_file = ../../pot/library/__main__.pot +source_file = ../build/gettext/library/__main__.pot type = PO minimum_perc = 0 resource_name = library--__main__ replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--_thread] -file_filter = .//LC_MESSAGES/library/_thread.po +[o:python-doc:p:python-313:r:library--_thread] +file_filter = library/_thread.po trans.pt_BR = library/_thread.po -source_file = ../../pot/library/_thread.pot +source_file = ../build/gettext/library/_thread.pot type = PO minimum_perc = 0 resource_name = library--_thread replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--abc] -file_filter = .//LC_MESSAGES/library/abc.po +[o:python-doc:p:python-313:r:library--abc] +file_filter = library/abc.po trans.pt_BR = library/abc.po -source_file = ../../pot/library/abc.pot +source_file = ../build/gettext/library/abc.pot type = PO minimum_perc = 0 resource_name = library--abc replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--allos] -file_filter = .//LC_MESSAGES/library/allos.po +[o:python-doc:p:python-313:r:library--aifc] +file_filter = library/aifc.po +trans.pt_BR = library/aifc.po +source_file = ../build/gettext/library/aifc.pot +type = PO +minimum_perc = 0 +resource_name = library--aifc +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--allos] +file_filter = library/allos.po trans.pt_BR = library/allos.po -source_file = ../../pot/library/allos.pot +source_file = ../build/gettext/library/allos.pot type = PO minimum_perc = 0 resource_name = library--allos replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--archiving] -file_filter = .//LC_MESSAGES/library/archiving.po +[o:python-doc:p:python-313:r:library--archiving] +file_filter = library/archiving.po trans.pt_BR = library/archiving.po -source_file = ../../pot/library/archiving.pot +source_file = ../build/gettext/library/archiving.pot type = PO minimum_perc = 0 resource_name = library--archiving replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--argparse] -file_filter = .//LC_MESSAGES/library/argparse.po +[o:python-doc:p:python-313:r:library--argparse] +file_filter = library/argparse.po trans.pt_BR = library/argparse.po -source_file = ../../pot/library/argparse.pot +source_file = ../build/gettext/library/argparse.pot type = PO minimum_perc = 0 resource_name = library--argparse replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--array] -file_filter = .//LC_MESSAGES/library/array.po +[o:python-doc:p:python-313:r:library--array] +file_filter = library/array.po trans.pt_BR = library/array.po -source_file = ../../pot/library/array.pot +source_file = ../build/gettext/library/array.pot type = PO minimum_perc = 0 resource_name = library--array replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--ast] -file_filter = .//LC_MESSAGES/library/ast.po +[o:python-doc:p:python-313:r:library--ast] +file_filter = library/ast.po trans.pt_BR = library/ast.po -source_file = ../../pot/library/ast.pot +source_file = ../build/gettext/library/ast.pot type = PO minimum_perc = 0 resource_name = library--ast replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio] -file_filter = .//LC_MESSAGES/library/asyncio.po +[o:python-doc:p:python-313:r:library--asynchat] +file_filter = library/asynchat.po +trans.pt_BR = library/asynchat.po +source_file = ../build/gettext/library/asynchat.pot +type = PO +minimum_perc = 0 +resource_name = library--asynchat +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--asyncio] +file_filter = library/asyncio.po trans.pt_BR = library/asyncio.po -source_file = ../../pot/library/asyncio.pot +source_file = ../build/gettext/library/asyncio.pot type = PO minimum_perc = 0 resource_name = library--asyncio replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio-api-index] -file_filter = .//LC_MESSAGES/library/asyncio-api-index.po +[o:python-doc:p:python-313:r:library--asyncio-api-index] +file_filter = library/asyncio-api-index.po trans.pt_BR = library/asyncio-api-index.po -source_file = ../../pot/library/asyncio-api-index.pot +source_file = ../build/gettext/library/asyncio-api-index.pot type = PO minimum_perc = 0 resource_name = library--asyncio-api-index replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio-dev] -file_filter = .//LC_MESSAGES/library/asyncio-dev.po +[o:python-doc:p:python-313:r:library--asyncio-dev] +file_filter = library/asyncio-dev.po trans.pt_BR = library/asyncio-dev.po -source_file = ../../pot/library/asyncio-dev.pot +source_file = ../build/gettext/library/asyncio-dev.pot type = PO minimum_perc = 0 resource_name = library--asyncio-dev replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio-eventloop] -file_filter = .//LC_MESSAGES/library/asyncio-eventloop.po +[o:python-doc:p:python-313:r:library--asyncio-eventloop] +file_filter = library/asyncio-eventloop.po trans.pt_BR = library/asyncio-eventloop.po -source_file = ../../pot/library/asyncio-eventloop.pot +source_file = ../build/gettext/library/asyncio-eventloop.pot type = PO minimum_perc = 0 resource_name = library--asyncio-eventloop replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio-exceptions] -file_filter = .//LC_MESSAGES/library/asyncio-exceptions.po +[o:python-doc:p:python-313:r:library--asyncio-exceptions] +file_filter = library/asyncio-exceptions.po trans.pt_BR = library/asyncio-exceptions.po -source_file = ../../pot/library/asyncio-exceptions.pot +source_file = ../build/gettext/library/asyncio-exceptions.pot type = PO minimum_perc = 0 resource_name = library--asyncio-exceptions replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio-extending] -file_filter = .//LC_MESSAGES/library/asyncio-extending.po +[o:python-doc:p:python-313:r:library--asyncio-extending] +file_filter = library/asyncio-extending.po trans.pt_BR = library/asyncio-extending.po -source_file = ../../pot/library/asyncio-extending.pot +source_file = ../build/gettext/library/asyncio-extending.pot type = PO minimum_perc = 0 resource_name = library--asyncio-extending replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio-future] -file_filter = .//LC_MESSAGES/library/asyncio-future.po +[o:python-doc:p:python-313:r:library--asyncio-future] +file_filter = library/asyncio-future.po trans.pt_BR = library/asyncio-future.po -source_file = ../../pot/library/asyncio-future.pot +source_file = ../build/gettext/library/asyncio-future.pot type = PO minimum_perc = 0 resource_name = library--asyncio-future replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio-llapi-index] -file_filter = .//LC_MESSAGES/library/asyncio-llapi-index.po +[o:python-doc:p:python-313:r:library--asyncio-llapi-index] +file_filter = library/asyncio-llapi-index.po trans.pt_BR = library/asyncio-llapi-index.po -source_file = ../../pot/library/asyncio-llapi-index.pot +source_file = ../build/gettext/library/asyncio-llapi-index.pot type = PO minimum_perc = 0 resource_name = library--asyncio-llapi-index replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio-platforms] -file_filter = .//LC_MESSAGES/library/asyncio-platforms.po +[o:python-doc:p:python-313:r:library--asyncio-platforms] +file_filter = library/asyncio-platforms.po trans.pt_BR = library/asyncio-platforms.po -source_file = ../../pot/library/asyncio-platforms.pot +source_file = ../build/gettext/library/asyncio-platforms.pot type = PO minimum_perc = 0 resource_name = library--asyncio-platforms replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio-policy] -file_filter = .//LC_MESSAGES/library/asyncio-policy.po +[o:python-doc:p:python-313:r:library--asyncio-policy] +file_filter = library/asyncio-policy.po trans.pt_BR = library/asyncio-policy.po -source_file = ../../pot/library/asyncio-policy.pot +source_file = ../build/gettext/library/asyncio-policy.pot type = PO minimum_perc = 0 resource_name = library--asyncio-policy replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio-protocol] -file_filter = .//LC_MESSAGES/library/asyncio-protocol.po +[o:python-doc:p:python-313:r:library--asyncio-protocol] +file_filter = library/asyncio-protocol.po trans.pt_BR = library/asyncio-protocol.po -source_file = ../../pot/library/asyncio-protocol.pot +source_file = ../build/gettext/library/asyncio-protocol.pot type = PO minimum_perc = 0 resource_name = library--asyncio-protocol replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio-queue] -file_filter = .//LC_MESSAGES/library/asyncio-queue.po +[o:python-doc:p:python-313:r:library--asyncio-queue] +file_filter = library/asyncio-queue.po trans.pt_BR = library/asyncio-queue.po -source_file = ../../pot/library/asyncio-queue.pot +source_file = ../build/gettext/library/asyncio-queue.pot type = PO minimum_perc = 0 resource_name = library--asyncio-queue replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio-runner] -file_filter = .//LC_MESSAGES/library/asyncio-runner.po +[o:python-doc:p:python-313:r:library--asyncio-runner] +file_filter = library/asyncio-runner.po trans.pt_BR = library/asyncio-runner.po -source_file = ../../pot/library/asyncio-runner.pot +source_file = ../build/gettext/library/asyncio-runner.pot type = PO minimum_perc = 0 resource_name = library--asyncio-runner replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio-stream] -file_filter = .//LC_MESSAGES/library/asyncio-stream.po +[o:python-doc:p:python-313:r:library--asyncio-stream] +file_filter = library/asyncio-stream.po trans.pt_BR = library/asyncio-stream.po -source_file = ../../pot/library/asyncio-stream.pot +source_file = ../build/gettext/library/asyncio-stream.pot type = PO minimum_perc = 0 resource_name = library--asyncio-stream replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio-subprocess] -file_filter = .//LC_MESSAGES/library/asyncio-subprocess.po +[o:python-doc:p:python-313:r:library--asyncio-subprocess] +file_filter = library/asyncio-subprocess.po trans.pt_BR = library/asyncio-subprocess.po -source_file = ../../pot/library/asyncio-subprocess.pot +source_file = ../build/gettext/library/asyncio-subprocess.pot type = PO minimum_perc = 0 resource_name = library--asyncio-subprocess replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio-sync] -file_filter = .//LC_MESSAGES/library/asyncio-sync.po +[o:python-doc:p:python-313:r:library--asyncio-sync] +file_filter = library/asyncio-sync.po trans.pt_BR = library/asyncio-sync.po -source_file = ../../pot/library/asyncio-sync.pot +source_file = ../build/gettext/library/asyncio-sync.pot type = PO minimum_perc = 0 resource_name = library--asyncio-sync replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--asyncio-task] -file_filter = .//LC_MESSAGES/library/asyncio-task.po +[o:python-doc:p:python-313:r:library--asyncio-task] +file_filter = library/asyncio-task.po trans.pt_BR = library/asyncio-task.po -source_file = ../../pot/library/asyncio-task.pot +source_file = ../build/gettext/library/asyncio-task.pot type = PO minimum_perc = 0 resource_name = library--asyncio-task replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--atexit] -file_filter = .//LC_MESSAGES/library/atexit.po +[o:python-doc:p:python-313:r:library--asyncore] +file_filter = library/asyncore.po +trans.pt_BR = library/asyncore.po +source_file = ../build/gettext/library/asyncore.pot +type = PO +minimum_perc = 0 +resource_name = library--asyncore +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--atexit] +file_filter = library/atexit.po trans.pt_BR = library/atexit.po -source_file = ../../pot/library/atexit.pot +source_file = ../build/gettext/library/atexit.pot type = PO minimum_perc = 0 resource_name = library--atexit replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--audit_events] -file_filter = .//LC_MESSAGES/library/audit_events.po +[o:python-doc:p:python-313:r:library--audioop] +file_filter = library/audioop.po +trans.pt_BR = library/audioop.po +source_file = ../build/gettext/library/audioop.pot +type = PO +minimum_perc = 0 +resource_name = library--audioop +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--audit_events] +file_filter = library/audit_events.po trans.pt_BR = library/audit_events.po -source_file = ../../pot/library/audit_events.pot +source_file = ../build/gettext/library/audit_events.pot type = PO minimum_perc = 0 resource_name = library--audit_events replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--base64] -file_filter = .//LC_MESSAGES/library/base64.po +[o:python-doc:p:python-313:r:library--base64] +file_filter = library/base64.po trans.pt_BR = library/base64.po -source_file = ../../pot/library/base64.pot +source_file = ../build/gettext/library/base64.pot type = PO minimum_perc = 0 resource_name = library--base64 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--bdb] -file_filter = .//LC_MESSAGES/library/bdb.po +[o:python-doc:p:python-313:r:library--bdb] +file_filter = library/bdb.po trans.pt_BR = library/bdb.po -source_file = ../../pot/library/bdb.pot +source_file = ../build/gettext/library/bdb.pot type = PO minimum_perc = 0 resource_name = library--bdb replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--binary] -file_filter = .//LC_MESSAGES/library/binary.po +[o:python-doc:p:python-313:r:library--binary] +file_filter = library/binary.po trans.pt_BR = library/binary.po -source_file = ../../pot/library/binary.pot +source_file = ../build/gettext/library/binary.pot type = PO minimum_perc = 0 resource_name = library--binary replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--binascii] -file_filter = .//LC_MESSAGES/library/binascii.po +[o:python-doc:p:python-313:r:library--binascii] +file_filter = library/binascii.po trans.pt_BR = library/binascii.po -source_file = ../../pot/library/binascii.pot +source_file = ../build/gettext/library/binascii.pot type = PO minimum_perc = 0 resource_name = library--binascii replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--bisect] -file_filter = .//LC_MESSAGES/library/bisect.po +[o:python-doc:p:python-313:r:library--bisect] +file_filter = library/bisect.po trans.pt_BR = library/bisect.po -source_file = ../../pot/library/bisect.pot +source_file = ../build/gettext/library/bisect.pot type = PO minimum_perc = 0 resource_name = library--bisect replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--builtins] -file_filter = .//LC_MESSAGES/library/builtins.po +[o:python-doc:p:python-313:r:library--builtins] +file_filter = library/builtins.po trans.pt_BR = library/builtins.po -source_file = ../../pot/library/builtins.pot +source_file = ../build/gettext/library/builtins.pot type = PO minimum_perc = 0 resource_name = library--builtins replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--bz2] -file_filter = .//LC_MESSAGES/library/bz2.po +[o:python-doc:p:python-313:r:library--bz2] +file_filter = library/bz2.po trans.pt_BR = library/bz2.po -source_file = ../../pot/library/bz2.pot +source_file = ../build/gettext/library/bz2.pot type = PO minimum_perc = 0 resource_name = library--bz2 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--calendar] -file_filter = .//LC_MESSAGES/library/calendar.po +[o:python-doc:p:python-313:r:library--calendar] +file_filter = library/calendar.po trans.pt_BR = library/calendar.po -source_file = ../../pot/library/calendar.pot +source_file = ../build/gettext/library/calendar.pot type = PO minimum_perc = 0 resource_name = library--calendar replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--cmath] -file_filter = .//LC_MESSAGES/library/cmath.po +[o:python-doc:p:python-313:r:library--cgi] +file_filter = library/cgi.po +trans.pt_BR = library/cgi.po +source_file = ../build/gettext/library/cgi.pot +type = PO +minimum_perc = 0 +resource_name = library--cgi +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--cgitb] +file_filter = library/cgitb.po +trans.pt_BR = library/cgitb.po +source_file = ../build/gettext/library/cgitb.pot +type = PO +minimum_perc = 0 +resource_name = library--cgitb +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--chunk] +file_filter = library/chunk.po +trans.pt_BR = library/chunk.po +source_file = ../build/gettext/library/chunk.pot +type = PO +minimum_perc = 0 +resource_name = library--chunk +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--cmath] +file_filter = library/cmath.po trans.pt_BR = library/cmath.po -source_file = ../../pot/library/cmath.pot +source_file = ../build/gettext/library/cmath.pot type = PO minimum_perc = 0 resource_name = library--cmath replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--cmd] -file_filter = .//LC_MESSAGES/library/cmd.po +[o:python-doc:p:python-313:r:library--cmd] +file_filter = library/cmd.po trans.pt_BR = library/cmd.po -source_file = ../../pot/library/cmd.pot +source_file = ../build/gettext/library/cmd.pot type = PO minimum_perc = 0 resource_name = library--cmd replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--cmdline] -file_filter = .//LC_MESSAGES/library/cmdline.po +[o:python-doc:p:python-313:r:library--cmdline] +file_filter = library/cmdline.po trans.pt_BR = library/cmdline.po -source_file = ../../pot/library/cmdline.pot +source_file = ../build/gettext/library/cmdline.pot type = PO minimum_perc = 0 resource_name = library--cmdline replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--code] -file_filter = .//LC_MESSAGES/library/code.po +[o:python-doc:p:python-313:r:library--cmdlinelibs] +file_filter = library/cmdlinelibs.po +trans.pt_BR = library/cmdlinelibs.po +source_file = ../build/gettext/library/cmdlinelibs.pot +type = PO +minimum_perc = 0 +resource_name = library--cmdlinelibs +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--code] +file_filter = library/code.po trans.pt_BR = library/code.po -source_file = ../../pot/library/code.pot +source_file = ../build/gettext/library/code.pot type = PO minimum_perc = 0 resource_name = library--code replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--codecs] -file_filter = .//LC_MESSAGES/library/codecs.po +[o:python-doc:p:python-313:r:library--codecs] +file_filter = library/codecs.po trans.pt_BR = library/codecs.po -source_file = ../../pot/library/codecs.pot +source_file = ../build/gettext/library/codecs.pot type = PO minimum_perc = 0 resource_name = library--codecs replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--codeop] -file_filter = .//LC_MESSAGES/library/codeop.po +[o:python-doc:p:python-313:r:library--codeop] +file_filter = library/codeop.po trans.pt_BR = library/codeop.po -source_file = ../../pot/library/codeop.pot +source_file = ../build/gettext/library/codeop.pot type = PO minimum_perc = 0 resource_name = library--codeop replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--collections] -file_filter = .//LC_MESSAGES/library/collections.po +[o:python-doc:p:python-313:r:library--collections] +file_filter = library/collections.po trans.pt_BR = library/collections.po -source_file = ../../pot/library/collections.pot +source_file = ../build/gettext/library/collections.pot type = PO minimum_perc = 0 resource_name = library--collections replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--collections_abc] -file_filter = .//LC_MESSAGES/library/collections.abc.po +[o:python-doc:p:python-313:r:library--collections_abc] +file_filter = library/collections.abc.po trans.pt_BR = library/collections.abc.po -source_file = ../../pot/library/collections.abc.pot +source_file = ../build/gettext/library/collections.abc.pot type = PO minimum_perc = 0 resource_name = library--collections_abc replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--colorsys] -file_filter = .//LC_MESSAGES/library/colorsys.po +[o:python-doc:p:python-313:r:library--colorsys] +file_filter = library/colorsys.po trans.pt_BR = library/colorsys.po -source_file = ../../pot/library/colorsys.pot +source_file = ../build/gettext/library/colorsys.pot type = PO minimum_perc = 0 resource_name = library--colorsys replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--compileall] -file_filter = .//LC_MESSAGES/library/compileall.po +[o:python-doc:p:python-313:r:library--compileall] +file_filter = library/compileall.po trans.pt_BR = library/compileall.po -source_file = ../../pot/library/compileall.pot +source_file = ../build/gettext/library/compileall.pot type = PO minimum_perc = 0 resource_name = library--compileall replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--concurrency] -file_filter = .//LC_MESSAGES/library/concurrency.po +[o:python-doc:p:python-313:r:library--concurrency] +file_filter = library/concurrency.po trans.pt_BR = library/concurrency.po -source_file = ../../pot/library/concurrency.pot +source_file = ../build/gettext/library/concurrency.pot type = PO minimum_perc = 0 resource_name = library--concurrency replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--concurrent] -file_filter = .//LC_MESSAGES/library/concurrent.po +[o:python-doc:p:python-313:r:library--concurrent] +file_filter = library/concurrent.po trans.pt_BR = library/concurrent.po -source_file = ../../pot/library/concurrent.pot +source_file = ../build/gettext/library/concurrent.pot type = PO minimum_perc = 0 resource_name = library--concurrent replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--concurrent_futures] -file_filter = .//LC_MESSAGES/library/concurrent.futures.po +[o:python-doc:p:python-313:r:library--concurrent_futures] +file_filter = library/concurrent.futures.po trans.pt_BR = library/concurrent.futures.po -source_file = ../../pot/library/concurrent.futures.pot +source_file = ../build/gettext/library/concurrent.futures.pot type = PO minimum_perc = 0 resource_name = library--concurrent_futures replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--configparser] -file_filter = .//LC_MESSAGES/library/configparser.po +[o:python-doc:p:python-313:r:library--configparser] +file_filter = library/configparser.po trans.pt_BR = library/configparser.po -source_file = ../../pot/library/configparser.pot +source_file = ../build/gettext/library/configparser.pot type = PO minimum_perc = 0 resource_name = library--configparser replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--constants] -file_filter = .//LC_MESSAGES/library/constants.po +[o:python-doc:p:python-313:r:library--constants] +file_filter = library/constants.po trans.pt_BR = library/constants.po -source_file = ../../pot/library/constants.pot +source_file = ../build/gettext/library/constants.pot type = PO minimum_perc = 0 resource_name = library--constants replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--contextlib] -file_filter = .//LC_MESSAGES/library/contextlib.po +[o:python-doc:p:python-313:r:library--contextlib] +file_filter = library/contextlib.po trans.pt_BR = library/contextlib.po -source_file = ../../pot/library/contextlib.pot +source_file = ../build/gettext/library/contextlib.pot type = PO minimum_perc = 0 resource_name = library--contextlib replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--contextvars] -file_filter = .//LC_MESSAGES/library/contextvars.po +[o:python-doc:p:python-313:r:library--contextvars] +file_filter = library/contextvars.po trans.pt_BR = library/contextvars.po -source_file = ../../pot/library/contextvars.pot +source_file = ../build/gettext/library/contextvars.pot type = PO minimum_perc = 0 resource_name = library--contextvars replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--copy] -file_filter = .//LC_MESSAGES/library/copy.po +[o:python-doc:p:python-313:r:library--copy] +file_filter = library/copy.po trans.pt_BR = library/copy.po -source_file = ../../pot/library/copy.pot +source_file = ../build/gettext/library/copy.pot type = PO minimum_perc = 0 resource_name = library--copy replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--copyreg] -file_filter = .//LC_MESSAGES/library/copyreg.po +[o:python-doc:p:python-313:r:library--copyreg] +file_filter = library/copyreg.po trans.pt_BR = library/copyreg.po -source_file = ../../pot/library/copyreg.pot +source_file = ../build/gettext/library/copyreg.pot type = PO minimum_perc = 0 resource_name = library--copyreg replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--crypto] -file_filter = .//LC_MESSAGES/library/crypto.po +[o:python-doc:p:python-313:r:library--crypt] +file_filter = library/crypt.po +trans.pt_BR = library/crypt.po +source_file = ../build/gettext/library/crypt.pot +type = PO +minimum_perc = 0 +resource_name = library--crypt +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--crypto] +file_filter = library/crypto.po trans.pt_BR = library/crypto.po -source_file = ../../pot/library/crypto.pot +source_file = ../build/gettext/library/crypto.pot type = PO minimum_perc = 0 resource_name = library--crypto replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--csv] -file_filter = .//LC_MESSAGES/library/csv.po +[o:python-doc:p:python-313:r:library--csv] +file_filter = library/csv.po trans.pt_BR = library/csv.po -source_file = ../../pot/library/csv.pot +source_file = ../build/gettext/library/csv.pot type = PO minimum_perc = 0 resource_name = library--csv replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--ctypes] -file_filter = .//LC_MESSAGES/library/ctypes.po +[o:python-doc:p:python-313:r:library--ctypes] +file_filter = library/ctypes.po trans.pt_BR = library/ctypes.po -source_file = ../../pot/library/ctypes.pot +source_file = ../build/gettext/library/ctypes.pot type = PO minimum_perc = 0 resource_name = library--ctypes replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--curses] -file_filter = .//LC_MESSAGES/library/curses.po +[o:python-doc:p:python-313:r:library--curses] +file_filter = library/curses.po trans.pt_BR = library/curses.po -source_file = ../../pot/library/curses.pot +source_file = ../build/gettext/library/curses.pot type = PO minimum_perc = 0 resource_name = library--curses replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--curses_ascii] -file_filter = .//LC_MESSAGES/library/curses.ascii.po +[o:python-doc:p:python-313:r:library--curses_ascii] +file_filter = library/curses.ascii.po trans.pt_BR = library/curses.ascii.po -source_file = ../../pot/library/curses.ascii.pot +source_file = ../build/gettext/library/curses.ascii.pot type = PO minimum_perc = 0 resource_name = library--curses_ascii replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--curses_panel] -file_filter = .//LC_MESSAGES/library/curses.panel.po +[o:python-doc:p:python-313:r:library--curses_panel] +file_filter = library/curses.panel.po trans.pt_BR = library/curses.panel.po -source_file = ../../pot/library/curses.panel.pot +source_file = ../build/gettext/library/curses.panel.pot type = PO minimum_perc = 0 resource_name = library--curses_panel replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--custominterp] -file_filter = .//LC_MESSAGES/library/custominterp.po +[o:python-doc:p:python-313:r:library--custominterp] +file_filter = library/custominterp.po trans.pt_BR = library/custominterp.po -source_file = ../../pot/library/custominterp.pot +source_file = ../build/gettext/library/custominterp.pot type = PO minimum_perc = 0 resource_name = library--custominterp replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--dataclasses] -file_filter = .//LC_MESSAGES/library/dataclasses.po +[o:python-doc:p:python-313:r:library--dataclasses] +file_filter = library/dataclasses.po trans.pt_BR = library/dataclasses.po -source_file = ../../pot/library/dataclasses.pot +source_file = ../build/gettext/library/dataclasses.pot type = PO minimum_perc = 0 resource_name = library--dataclasses replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--datatypes] -file_filter = .//LC_MESSAGES/library/datatypes.po +[o:python-doc:p:python-313:r:library--datatypes] +file_filter = library/datatypes.po trans.pt_BR = library/datatypes.po -source_file = ../../pot/library/datatypes.pot +source_file = ../build/gettext/library/datatypes.pot type = PO minimum_perc = 0 resource_name = library--datatypes replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--datetime] -file_filter = .//LC_MESSAGES/library/datetime.po +[o:python-doc:p:python-313:r:library--datetime] +file_filter = library/datetime.po trans.pt_BR = library/datetime.po -source_file = ../../pot/library/datetime.pot +source_file = ../build/gettext/library/datetime.pot type = PO minimum_perc = 0 resource_name = library--datetime replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--dbm] -file_filter = .//LC_MESSAGES/library/dbm.po +[o:python-doc:p:python-313:r:library--dbm] +file_filter = library/dbm.po trans.pt_BR = library/dbm.po -source_file = ../../pot/library/dbm.pot +source_file = ../build/gettext/library/dbm.pot type = PO minimum_perc = 0 resource_name = library--dbm replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--debug] -file_filter = .//LC_MESSAGES/library/debug.po +[o:python-doc:p:python-313:r:library--debug] +file_filter = library/debug.po trans.pt_BR = library/debug.po -source_file = ../../pot/library/debug.pot +source_file = ../build/gettext/library/debug.pot type = PO minimum_perc = 0 resource_name = library--debug replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--decimal] -file_filter = .//LC_MESSAGES/library/decimal.po +[o:python-doc:p:python-313:r:library--decimal] +file_filter = library/decimal.po trans.pt_BR = library/decimal.po -source_file = ../../pot/library/decimal.pot +source_file = ../build/gettext/library/decimal.pot type = PO minimum_perc = 0 resource_name = library--decimal replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--development] -file_filter = .//LC_MESSAGES/library/development.po +[o:python-doc:p:python-313:r:library--development] +file_filter = library/development.po trans.pt_BR = library/development.po -source_file = ../../pot/library/development.pot +source_file = ../build/gettext/library/development.pot type = PO minimum_perc = 0 resource_name = library--development replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--devmode] -file_filter = .//LC_MESSAGES/library/devmode.po +[o:python-doc:p:python-313:r:library--devmode] +file_filter = library/devmode.po trans.pt_BR = library/devmode.po -source_file = ../../pot/library/devmode.pot +source_file = ../build/gettext/library/devmode.pot type = PO minimum_perc = 0 resource_name = library--devmode replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--dialog] -file_filter = .//LC_MESSAGES/library/dialog.po +[o:python-doc:p:python-313:r:library--dialog] +file_filter = library/dialog.po trans.pt_BR = library/dialog.po -source_file = ../../pot/library/dialog.pot +source_file = ../build/gettext/library/dialog.pot type = PO minimum_perc = 0 resource_name = library--dialog replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--difflib] -file_filter = .//LC_MESSAGES/library/difflib.po +[o:python-doc:p:python-313:r:library--difflib] +file_filter = library/difflib.po trans.pt_BR = library/difflib.po -source_file = ../../pot/library/difflib.pot +source_file = ../build/gettext/library/difflib.pot type = PO minimum_perc = 0 resource_name = library--difflib replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--dis] -file_filter = .//LC_MESSAGES/library/dis.po +[o:python-doc:p:python-313:r:library--dis] +file_filter = library/dis.po trans.pt_BR = library/dis.po -source_file = ../../pot/library/dis.pot +source_file = ../build/gettext/library/dis.pot type = PO minimum_perc = 0 resource_name = library--dis replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--distribution] -file_filter = .//LC_MESSAGES/library/distribution.po +[o:python-doc:p:python-313:r:library--distribution] +file_filter = library/distribution.po trans.pt_BR = library/distribution.po -source_file = ../../pot/library/distribution.pot +source_file = ../build/gettext/library/distribution.pot type = PO minimum_perc = 0 resource_name = library--distribution replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--doctest] -file_filter = .//LC_MESSAGES/library/doctest.po +[o:python-doc:p:python-313:r:library--distutils] +file_filter = library/distutils.po +trans.pt_BR = library/distutils.po +source_file = ../build/gettext/library/distutils.pot +type = PO +minimum_perc = 0 +resource_name = library--distutils +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--doctest] +file_filter = library/doctest.po trans.pt_BR = library/doctest.po -source_file = ../../pot/library/doctest.pot +source_file = ../build/gettext/library/doctest.pot type = PO minimum_perc = 0 resource_name = library--doctest replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--email] -file_filter = .//LC_MESSAGES/library/email.po +[o:python-doc:p:python-313:r:library--email] +file_filter = library/email.po trans.pt_BR = library/email.po -source_file = ../../pot/library/email.pot +source_file = ../build/gettext/library/email.pot type = PO minimum_perc = 0 resource_name = library--email replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--email_charset] -file_filter = .//LC_MESSAGES/library/email.charset.po +[o:python-doc:p:python-313:r:library--email_charset] +file_filter = library/email.charset.po trans.pt_BR = library/email.charset.po -source_file = ../../pot/library/email.charset.pot +source_file = ../build/gettext/library/email.charset.pot type = PO minimum_perc = 0 resource_name = library--email_charset replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--email_compat32-message] -file_filter = .//LC_MESSAGES/library/email.compat32-message.po +[o:python-doc:p:python-313:r:library--email_compat32-message] +file_filter = library/email.compat32-message.po trans.pt_BR = library/email.compat32-message.po -source_file = ../../pot/library/email.compat32-message.pot +source_file = ../build/gettext/library/email.compat32-message.pot type = PO minimum_perc = 0 resource_name = library--email_compat32-message replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--email_contentmanager] -file_filter = .//LC_MESSAGES/library/email.contentmanager.po +[o:python-doc:p:python-313:r:library--email_contentmanager] +file_filter = library/email.contentmanager.po trans.pt_BR = library/email.contentmanager.po -source_file = ../../pot/library/email.contentmanager.pot +source_file = ../build/gettext/library/email.contentmanager.pot type = PO minimum_perc = 0 resource_name = library--email_contentmanager replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--email_encoders] -file_filter = .//LC_MESSAGES/library/email.encoders.po +[o:python-doc:p:python-313:r:library--email_encoders] +file_filter = library/email.encoders.po trans.pt_BR = library/email.encoders.po -source_file = ../../pot/library/email.encoders.pot +source_file = ../build/gettext/library/email.encoders.pot type = PO minimum_perc = 0 resource_name = library--email_encoders replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--email_errors] -file_filter = .//LC_MESSAGES/library/email.errors.po +[o:python-doc:p:python-313:r:library--email_errors] +file_filter = library/email.errors.po trans.pt_BR = library/email.errors.po -source_file = ../../pot/library/email.errors.pot +source_file = ../build/gettext/library/email.errors.pot type = PO minimum_perc = 0 resource_name = library--email_errors replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--email_examples] -file_filter = .//LC_MESSAGES/library/email.examples.po +[o:python-doc:p:python-313:r:library--email_examples] +file_filter = library/email.examples.po trans.pt_BR = library/email.examples.po -source_file = ../../pot/library/email.examples.pot +source_file = ../build/gettext/library/email.examples.pot type = PO minimum_perc = 0 resource_name = library--email_examples replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--email_generator] -file_filter = .//LC_MESSAGES/library/email.generator.po +[o:python-doc:p:python-313:r:library--email_generator] +file_filter = library/email.generator.po trans.pt_BR = library/email.generator.po -source_file = ../../pot/library/email.generator.pot +source_file = ../build/gettext/library/email.generator.pot type = PO minimum_perc = 0 resource_name = library--email_generator replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--email_header] -file_filter = .//LC_MESSAGES/library/email.header.po +[o:python-doc:p:python-313:r:library--email_header] +file_filter = library/email.header.po trans.pt_BR = library/email.header.po -source_file = ../../pot/library/email.header.pot +source_file = ../build/gettext/library/email.header.pot type = PO minimum_perc = 0 resource_name = library--email_header replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--email_headerregistry] -file_filter = .//LC_MESSAGES/library/email.headerregistry.po +[o:python-doc:p:python-313:r:library--email_headerregistry] +file_filter = library/email.headerregistry.po trans.pt_BR = library/email.headerregistry.po -source_file = ../../pot/library/email.headerregistry.pot +source_file = ../build/gettext/library/email.headerregistry.pot type = PO minimum_perc = 0 resource_name = library--email_headerregistry replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--email_iterators] -file_filter = .//LC_MESSAGES/library/email.iterators.po +[o:python-doc:p:python-313:r:library--email_iterators] +file_filter = library/email.iterators.po trans.pt_BR = library/email.iterators.po -source_file = ../../pot/library/email.iterators.pot +source_file = ../build/gettext/library/email.iterators.pot type = PO minimum_perc = 0 resource_name = library--email_iterators replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--email_message] -file_filter = .//LC_MESSAGES/library/email.message.po +[o:python-doc:p:python-313:r:library--email_message] +file_filter = library/email.message.po trans.pt_BR = library/email.message.po -source_file = ../../pot/library/email.message.pot +source_file = ../build/gettext/library/email.message.pot type = PO minimum_perc = 0 resource_name = library--email_message replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--email_mime] -file_filter = .//LC_MESSAGES/library/email.mime.po +[o:python-doc:p:python-313:r:library--email_mime] +file_filter = library/email.mime.po trans.pt_BR = library/email.mime.po -source_file = ../../pot/library/email.mime.pot +source_file = ../build/gettext/library/email.mime.pot type = PO minimum_perc = 0 resource_name = library--email_mime replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--email_parser] -file_filter = .//LC_MESSAGES/library/email.parser.po +[o:python-doc:p:python-313:r:library--email_parser] +file_filter = library/email.parser.po trans.pt_BR = library/email.parser.po -source_file = ../../pot/library/email.parser.pot +source_file = ../build/gettext/library/email.parser.pot type = PO minimum_perc = 0 resource_name = library--email_parser replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--email_policy] -file_filter = .//LC_MESSAGES/library/email.policy.po +[o:python-doc:p:python-313:r:library--email_policy] +file_filter = library/email.policy.po trans.pt_BR = library/email.policy.po -source_file = ../../pot/library/email.policy.pot +source_file = ../build/gettext/library/email.policy.pot type = PO minimum_perc = 0 resource_name = library--email_policy replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--email_utils] -file_filter = .//LC_MESSAGES/library/email.utils.po +[o:python-doc:p:python-313:r:library--email_utils] +file_filter = library/email.utils.po trans.pt_BR = library/email.utils.po -source_file = ../../pot/library/email.utils.pot +source_file = ../build/gettext/library/email.utils.pot type = PO minimum_perc = 0 resource_name = library--email_utils replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--ensurepip] -file_filter = .//LC_MESSAGES/library/ensurepip.po +[o:python-doc:p:python-313:r:library--ensurepip] +file_filter = library/ensurepip.po trans.pt_BR = library/ensurepip.po -source_file = ../../pot/library/ensurepip.pot +source_file = ../build/gettext/library/ensurepip.pot type = PO minimum_perc = 0 resource_name = library--ensurepip replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--enum] -file_filter = .//LC_MESSAGES/library/enum.po +[o:python-doc:p:python-313:r:library--enum] +file_filter = library/enum.po trans.pt_BR = library/enum.po -source_file = ../../pot/library/enum.pot +source_file = ../build/gettext/library/enum.pot type = PO minimum_perc = 0 resource_name = library--enum replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--errno] -file_filter = .//LC_MESSAGES/library/errno.po +[o:python-doc:p:python-313:r:library--errno] +file_filter = library/errno.po trans.pt_BR = library/errno.po -source_file = ../../pot/library/errno.pot +source_file = ../build/gettext/library/errno.pot type = PO minimum_perc = 0 resource_name = library--errno replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--exceptions] -file_filter = .//LC_MESSAGES/library/exceptions.po +[o:python-doc:p:python-313:r:library--exceptions] +file_filter = library/exceptions.po trans.pt_BR = library/exceptions.po -source_file = ../../pot/library/exceptions.pot +source_file = ../build/gettext/library/exceptions.pot type = PO minimum_perc = 0 resource_name = library--exceptions replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--faulthandler] -file_filter = .//LC_MESSAGES/library/faulthandler.po +[o:python-doc:p:python-313:r:library--faulthandler] +file_filter = library/faulthandler.po trans.pt_BR = library/faulthandler.po -source_file = ../../pot/library/faulthandler.pot +source_file = ../build/gettext/library/faulthandler.pot type = PO minimum_perc = 0 resource_name = library--faulthandler replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--fcntl] -file_filter = .//LC_MESSAGES/library/fcntl.po +[o:python-doc:p:python-313:r:library--fcntl] +file_filter = library/fcntl.po trans.pt_BR = library/fcntl.po -source_file = ../../pot/library/fcntl.pot +source_file = ../build/gettext/library/fcntl.pot type = PO minimum_perc = 0 resource_name = library--fcntl replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--filecmp] -file_filter = .//LC_MESSAGES/library/filecmp.po +[o:python-doc:p:python-313:r:library--filecmp] +file_filter = library/filecmp.po trans.pt_BR = library/filecmp.po -source_file = ../../pot/library/filecmp.pot +source_file = ../build/gettext/library/filecmp.pot type = PO minimum_perc = 0 resource_name = library--filecmp replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--fileformats] -file_filter = .//LC_MESSAGES/library/fileformats.po +[o:python-doc:p:python-313:r:library--fileformats] +file_filter = library/fileformats.po trans.pt_BR = library/fileformats.po -source_file = ../../pot/library/fileformats.pot +source_file = ../build/gettext/library/fileformats.pot type = PO minimum_perc = 0 resource_name = library--fileformats replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--fileinput] -file_filter = .//LC_MESSAGES/library/fileinput.po +[o:python-doc:p:python-313:r:library--fileinput] +file_filter = library/fileinput.po trans.pt_BR = library/fileinput.po -source_file = ../../pot/library/fileinput.pot +source_file = ../build/gettext/library/fileinput.pot type = PO minimum_perc = 0 resource_name = library--fileinput replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--filesys] -file_filter = .//LC_MESSAGES/library/filesys.po +[o:python-doc:p:python-313:r:library--filesys] +file_filter = library/filesys.po trans.pt_BR = library/filesys.po -source_file = ../../pot/library/filesys.pot +source_file = ../build/gettext/library/filesys.pot type = PO minimum_perc = 0 resource_name = library--filesys replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--fnmatch] -file_filter = .//LC_MESSAGES/library/fnmatch.po +[o:python-doc:p:python-313:r:library--fnmatch] +file_filter = library/fnmatch.po trans.pt_BR = library/fnmatch.po -source_file = ../../pot/library/fnmatch.pot +source_file = ../build/gettext/library/fnmatch.pot type = PO minimum_perc = 0 resource_name = library--fnmatch replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--fractions] -file_filter = .//LC_MESSAGES/library/fractions.po +[o:python-doc:p:python-313:r:library--fractions] +file_filter = library/fractions.po trans.pt_BR = library/fractions.po -source_file = ../../pot/library/fractions.pot +source_file = ../build/gettext/library/fractions.pot type = PO minimum_perc = 0 resource_name = library--fractions replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--frameworks] -file_filter = .//LC_MESSAGES/library/frameworks.po +[o:python-doc:p:python-313:r:library--frameworks] +file_filter = library/frameworks.po trans.pt_BR = library/frameworks.po -source_file = ../../pot/library/frameworks.pot +source_file = ../build/gettext/library/frameworks.pot type = PO minimum_perc = 0 resource_name = library--frameworks replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--ftplib] -file_filter = .//LC_MESSAGES/library/ftplib.po +[o:python-doc:p:python-313:r:library--ftplib] +file_filter = library/ftplib.po trans.pt_BR = library/ftplib.po -source_file = ../../pot/library/ftplib.pot +source_file = ../build/gettext/library/ftplib.pot type = PO minimum_perc = 0 resource_name = library--ftplib replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--functional] -file_filter = .//LC_MESSAGES/library/functional.po +[o:python-doc:p:python-313:r:library--functional] +file_filter = library/functional.po trans.pt_BR = library/functional.po -source_file = ../../pot/library/functional.pot +source_file = ../build/gettext/library/functional.pot type = PO minimum_perc = 0 resource_name = library--functional replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--functions] -file_filter = .//LC_MESSAGES/library/functions.po +[o:python-doc:p:python-313:r:library--functions] +file_filter = library/functions.po trans.pt_BR = library/functions.po -source_file = ../../pot/library/functions.pot +source_file = ../build/gettext/library/functions.pot type = PO minimum_perc = 0 resource_name = library--functions replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--functools] -file_filter = .//LC_MESSAGES/library/functools.po +[o:python-doc:p:python-313:r:library--functools] +file_filter = library/functools.po trans.pt_BR = library/functools.po -source_file = ../../pot/library/functools.pot +source_file = ../build/gettext/library/functools.pot type = PO minimum_perc = 0 resource_name = library--functools replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--gc] -file_filter = .//LC_MESSAGES/library/gc.po +[o:python-doc:p:python-313:r:library--gc] +file_filter = library/gc.po trans.pt_BR = library/gc.po -source_file = ../../pot/library/gc.pot +source_file = ../build/gettext/library/gc.pot type = PO minimum_perc = 0 resource_name = library--gc replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--getopt] -file_filter = .//LC_MESSAGES/library/getopt.po +[o:python-doc:p:python-313:r:library--getopt] +file_filter = library/getopt.po trans.pt_BR = library/getopt.po -source_file = ../../pot/library/getopt.pot +source_file = ../build/gettext/library/getopt.pot type = PO minimum_perc = 0 resource_name = library--getopt replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--getpass] -file_filter = .//LC_MESSAGES/library/getpass.po +[o:python-doc:p:python-313:r:library--getpass] +file_filter = library/getpass.po trans.pt_BR = library/getpass.po -source_file = ../../pot/library/getpass.pot +source_file = ../build/gettext/library/getpass.pot type = PO minimum_perc = 0 resource_name = library--getpass replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--gettext] -file_filter = .//LC_MESSAGES/library/gettext.po +[o:python-doc:p:python-313:r:library--gettext] +file_filter = library/gettext.po trans.pt_BR = library/gettext.po -source_file = ../../pot/library/gettext.pot +source_file = ../build/gettext/library/gettext.pot type = PO minimum_perc = 0 resource_name = library--gettext replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--glob] -file_filter = .//LC_MESSAGES/library/glob.po +[o:python-doc:p:python-313:r:library--glob] +file_filter = library/glob.po trans.pt_BR = library/glob.po -source_file = ../../pot/library/glob.pot +source_file = ../build/gettext/library/glob.pot type = PO minimum_perc = 0 resource_name = library--glob replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--graphlib] -file_filter = .//LC_MESSAGES/library/graphlib.po +[o:python-doc:p:python-313:r:library--graphlib] +file_filter = library/graphlib.po trans.pt_BR = library/graphlib.po -source_file = ../../pot/library/graphlib.pot +source_file = ../build/gettext/library/graphlib.pot type = PO minimum_perc = 0 resource_name = library--graphlib replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--grp] -file_filter = .//LC_MESSAGES/library/grp.po +[o:python-doc:p:python-313:r:library--grp] +file_filter = library/grp.po trans.pt_BR = library/grp.po -source_file = ../../pot/library/grp.pot +source_file = ../build/gettext/library/grp.pot type = PO minimum_perc = 0 resource_name = library--grp replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--gzip] -file_filter = .//LC_MESSAGES/library/gzip.po +[o:python-doc:p:python-313:r:library--gzip] +file_filter = library/gzip.po trans.pt_BR = library/gzip.po -source_file = ../../pot/library/gzip.pot +source_file = ../build/gettext/library/gzip.pot type = PO minimum_perc = 0 resource_name = library--gzip replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--hashlib] -file_filter = .//LC_MESSAGES/library/hashlib.po +[o:python-doc:p:python-313:r:library--hashlib] +file_filter = library/hashlib.po trans.pt_BR = library/hashlib.po -source_file = ../../pot/library/hashlib.pot +source_file = ../build/gettext/library/hashlib.pot type = PO minimum_perc = 0 resource_name = library--hashlib replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--heapq] -file_filter = .//LC_MESSAGES/library/heapq.po +[o:python-doc:p:python-313:r:library--heapq] +file_filter = library/heapq.po trans.pt_BR = library/heapq.po -source_file = ../../pot/library/heapq.pot +source_file = ../build/gettext/library/heapq.pot type = PO minimum_perc = 0 resource_name = library--heapq replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--hmac] -file_filter = .//LC_MESSAGES/library/hmac.po +[o:python-doc:p:python-313:r:library--hmac] +file_filter = library/hmac.po trans.pt_BR = library/hmac.po -source_file = ../../pot/library/hmac.pot +source_file = ../build/gettext/library/hmac.pot type = PO minimum_perc = 0 resource_name = library--hmac replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--html] -file_filter = .//LC_MESSAGES/library/html.po +[o:python-doc:p:python-313:r:library--html] +file_filter = library/html.po trans.pt_BR = library/html.po -source_file = ../../pot/library/html.pot +source_file = ../build/gettext/library/html.pot type = PO minimum_perc = 0 resource_name = library--html replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--html_entities] -file_filter = .//LC_MESSAGES/library/html.entities.po +[o:python-doc:p:python-313:r:library--html_entities] +file_filter = library/html.entities.po trans.pt_BR = library/html.entities.po -source_file = ../../pot/library/html.entities.pot +source_file = ../build/gettext/library/html.entities.pot type = PO minimum_perc = 0 resource_name = library--html_entities replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--html_parser] -file_filter = .//LC_MESSAGES/library/html.parser.po +[o:python-doc:p:python-313:r:library--html_parser] +file_filter = library/html.parser.po trans.pt_BR = library/html.parser.po -source_file = ../../pot/library/html.parser.pot +source_file = ../build/gettext/library/html.parser.pot type = PO minimum_perc = 0 resource_name = library--html_parser replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--http] -file_filter = .//LC_MESSAGES/library/http.po +[o:python-doc:p:python-313:r:library--http] +file_filter = library/http.po trans.pt_BR = library/http.po -source_file = ../../pot/library/http.pot +source_file = ../build/gettext/library/http.pot type = PO minimum_perc = 0 resource_name = library--http replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--http_client] -file_filter = .//LC_MESSAGES/library/http.client.po +[o:python-doc:p:python-313:r:library--http_client] +file_filter = library/http.client.po trans.pt_BR = library/http.client.po -source_file = ../../pot/library/http.client.pot +source_file = ../build/gettext/library/http.client.pot type = PO minimum_perc = 0 resource_name = library--http_client replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--http_cookiejar] -file_filter = .//LC_MESSAGES/library/http.cookiejar.po +[o:python-doc:p:python-313:r:library--http_cookiejar] +file_filter = library/http.cookiejar.po trans.pt_BR = library/http.cookiejar.po -source_file = ../../pot/library/http.cookiejar.pot +source_file = ../build/gettext/library/http.cookiejar.pot type = PO minimum_perc = 0 resource_name = library--http_cookiejar replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--http_cookies] -file_filter = .//LC_MESSAGES/library/http.cookies.po +[o:python-doc:p:python-313:r:library--http_cookies] +file_filter = library/http.cookies.po trans.pt_BR = library/http.cookies.po -source_file = ../../pot/library/http.cookies.pot +source_file = ../build/gettext/library/http.cookies.pot type = PO minimum_perc = 0 resource_name = library--http_cookies replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--http_server] -file_filter = .//LC_MESSAGES/library/http.server.po +[o:python-doc:p:python-313:r:library--http_server] +file_filter = library/http.server.po trans.pt_BR = library/http.server.po -source_file = ../../pot/library/http.server.pot +source_file = ../build/gettext/library/http.server.pot type = PO minimum_perc = 0 resource_name = library--http_server replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--i18n] -file_filter = .//LC_MESSAGES/library/i18n.po +[o:python-doc:p:python-313:r:library--i18n] +file_filter = library/i18n.po trans.pt_BR = library/i18n.po -source_file = ../../pot/library/i18n.pot +source_file = ../build/gettext/library/i18n.pot type = PO minimum_perc = 0 resource_name = library--i18n replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--idle] -file_filter = .//LC_MESSAGES/library/idle.po +[o:python-doc:p:python-313:r:library--idle] +file_filter = library/idle.po trans.pt_BR = library/idle.po -source_file = ../../pot/library/idle.pot +source_file = ../build/gettext/library/idle.pot type = PO minimum_perc = 0 resource_name = library--idle replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--imaplib] -file_filter = .//LC_MESSAGES/library/imaplib.po +[o:python-doc:p:python-313:r:library--imaplib] +file_filter = library/imaplib.po trans.pt_BR = library/imaplib.po -source_file = ../../pot/library/imaplib.pot +source_file = ../build/gettext/library/imaplib.pot type = PO minimum_perc = 0 resource_name = library--imaplib replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--importlib] -file_filter = .//LC_MESSAGES/library/importlib.po +[o:python-doc:p:python-313:r:library--imghdr] +file_filter = library/imghdr.po +trans.pt_BR = library/imghdr.po +source_file = ../build/gettext/library/imghdr.pot +type = PO +minimum_perc = 0 +resource_name = library--imghdr +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--imp] +file_filter = library/imp.po +trans.pt_BR = library/imp.po +source_file = ../build/gettext/library/imp.pot +type = PO +minimum_perc = 0 +resource_name = library--imp +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--importlib] +file_filter = library/importlib.po trans.pt_BR = library/importlib.po -source_file = ../../pot/library/importlib.pot +source_file = ../build/gettext/library/importlib.pot type = PO minimum_perc = 0 resource_name = library--importlib replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--importlib_metadata] -file_filter = .//LC_MESSAGES/library/importlib.metadata.po +[o:python-doc:p:python-313:r:library--importlib_metadata] +file_filter = library/importlib.metadata.po trans.pt_BR = library/importlib.metadata.po -source_file = ../../pot/library/importlib.metadata.pot +source_file = ../build/gettext/library/importlib.metadata.pot type = PO minimum_perc = 0 resource_name = library--importlib_metadata replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--importlib_resources] -file_filter = .//LC_MESSAGES/library/importlib.resources.po +[o:python-doc:p:python-313:r:library--importlib_resources] +file_filter = library/importlib.resources.po trans.pt_BR = library/importlib.resources.po -source_file = ../../pot/library/importlib.resources.pot +source_file = ../build/gettext/library/importlib.resources.pot type = PO minimum_perc = 0 resource_name = library--importlib_resources replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--importlib_resources_abc] -file_filter = .//LC_MESSAGES/library/importlib.resources.abc.po +[o:python-doc:p:python-313:r:library--importlib_resources_abc] +file_filter = library/importlib.resources.abc.po trans.pt_BR = library/importlib.resources.abc.po -source_file = ../../pot/library/importlib.resources.abc.pot +source_file = ../build/gettext/library/importlib.resources.abc.pot type = PO minimum_perc = 0 resource_name = library--importlib_resources_abc replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--index] -file_filter = .//LC_MESSAGES/library/index.po +[o:python-doc:p:python-313:r:library--index] +file_filter = library/index.po trans.pt_BR = library/index.po -source_file = ../../pot/library/index.pot +source_file = ../build/gettext/library/index.pot type = PO minimum_perc = 0 resource_name = library--index replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--inspect] -file_filter = .//LC_MESSAGES/library/inspect.po +[o:python-doc:p:python-313:r:library--inspect] +file_filter = library/inspect.po trans.pt_BR = library/inspect.po -source_file = ../../pot/library/inspect.pot +source_file = ../build/gettext/library/inspect.pot type = PO minimum_perc = 0 resource_name = library--inspect replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--internet] -file_filter = .//LC_MESSAGES/library/internet.po +[o:python-doc:p:python-313:r:library--internet] +file_filter = library/internet.po trans.pt_BR = library/internet.po -source_file = ../../pot/library/internet.pot +source_file = ../build/gettext/library/internet.pot type = PO minimum_perc = 0 resource_name = library--internet replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--intro] -file_filter = .//LC_MESSAGES/library/intro.po +[o:python-doc:p:python-313:r:library--intro] +file_filter = library/intro.po trans.pt_BR = library/intro.po -source_file = ../../pot/library/intro.pot +source_file = ../build/gettext/library/intro.pot type = PO minimum_perc = 0 resource_name = library--intro replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--io] -file_filter = .//LC_MESSAGES/library/io.po +[o:python-doc:p:python-313:r:library--io] +file_filter = library/io.po trans.pt_BR = library/io.po -source_file = ../../pot/library/io.pot +source_file = ../build/gettext/library/io.pot type = PO minimum_perc = 0 resource_name = library--io replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--ipaddress] -file_filter = .//LC_MESSAGES/library/ipaddress.po +[o:python-doc:p:python-313:r:library--ipaddress] +file_filter = library/ipaddress.po trans.pt_BR = library/ipaddress.po -source_file = ../../pot/library/ipaddress.pot +source_file = ../build/gettext/library/ipaddress.pot type = PO minimum_perc = 0 resource_name = library--ipaddress replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--ipc] -file_filter = .//LC_MESSAGES/library/ipc.po +[o:python-doc:p:python-313:r:library--ipc] +file_filter = library/ipc.po trans.pt_BR = library/ipc.po -source_file = ../../pot/library/ipc.pot +source_file = ../build/gettext/library/ipc.pot type = PO minimum_perc = 0 resource_name = library--ipc replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--itertools] -file_filter = .//LC_MESSAGES/library/itertools.po +[o:python-doc:p:python-313:r:library--itertools] +file_filter = library/itertools.po trans.pt_BR = library/itertools.po -source_file = ../../pot/library/itertools.pot +source_file = ../build/gettext/library/itertools.pot type = PO minimum_perc = 0 resource_name = library--itertools replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--json] -file_filter = .//LC_MESSAGES/library/json.po +[o:python-doc:p:python-313:r:library--json] +file_filter = library/json.po trans.pt_BR = library/json.po -source_file = ../../pot/library/json.pot +source_file = ../build/gettext/library/json.pot type = PO minimum_perc = 0 resource_name = library--json replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--keyword] -file_filter = .//LC_MESSAGES/library/keyword.po +[o:python-doc:p:python-313:r:library--keyword] +file_filter = library/keyword.po trans.pt_BR = library/keyword.po -source_file = ../../pot/library/keyword.pot +source_file = ../build/gettext/library/keyword.pot type = PO minimum_perc = 0 resource_name = library--keyword replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--language] -file_filter = .//LC_MESSAGES/library/language.po +[o:python-doc:p:python-313:r:library--language] +file_filter = library/language.po trans.pt_BR = library/language.po -source_file = ../../pot/library/language.pot +source_file = ../build/gettext/library/language.pot type = PO minimum_perc = 0 resource_name = library--language replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--linecache] -file_filter = .//LC_MESSAGES/library/linecache.po +[o:python-doc:p:python-313:r:library--linecache] +file_filter = library/linecache.po trans.pt_BR = library/linecache.po -source_file = ../../pot/library/linecache.pot +source_file = ../build/gettext/library/linecache.pot type = PO minimum_perc = 0 resource_name = library--linecache replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--locale] -file_filter = .//LC_MESSAGES/library/locale.po +[o:python-doc:p:python-313:r:library--locale] +file_filter = library/locale.po trans.pt_BR = library/locale.po -source_file = ../../pot/library/locale.pot +source_file = ../build/gettext/library/locale.pot type = PO minimum_perc = 0 resource_name = library--locale replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--logging] -file_filter = .//LC_MESSAGES/library/logging.po +[o:python-doc:p:python-313:r:library--logging] +file_filter = library/logging.po trans.pt_BR = library/logging.po -source_file = ../../pot/library/logging.pot +source_file = ../build/gettext/library/logging.pot type = PO minimum_perc = 0 resource_name = library--logging replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--logging_config] -file_filter = .//LC_MESSAGES/library/logging.config.po +[o:python-doc:p:python-313:r:library--logging_config] +file_filter = library/logging.config.po trans.pt_BR = library/logging.config.po -source_file = ../../pot/library/logging.config.pot +source_file = ../build/gettext/library/logging.config.pot type = PO minimum_perc = 0 resource_name = library--logging_config replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--logging_handlers] -file_filter = .//LC_MESSAGES/library/logging.handlers.po +[o:python-doc:p:python-313:r:library--logging_handlers] +file_filter = library/logging.handlers.po trans.pt_BR = library/logging.handlers.po -source_file = ../../pot/library/logging.handlers.pot +source_file = ../build/gettext/library/logging.handlers.pot type = PO minimum_perc = 0 resource_name = library--logging_handlers replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--lzma] -file_filter = .//LC_MESSAGES/library/lzma.po +[o:python-doc:p:python-313:r:library--lzma] +file_filter = library/lzma.po trans.pt_BR = library/lzma.po -source_file = ../../pot/library/lzma.pot +source_file = ../build/gettext/library/lzma.pot type = PO minimum_perc = 0 resource_name = library--lzma replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--mailbox] -file_filter = .//LC_MESSAGES/library/mailbox.po +[o:python-doc:p:python-313:r:library--mailbox] +file_filter = library/mailbox.po trans.pt_BR = library/mailbox.po -source_file = ../../pot/library/mailbox.pot +source_file = ../build/gettext/library/mailbox.pot type = PO minimum_perc = 0 resource_name = library--mailbox replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--markup] -file_filter = .//LC_MESSAGES/library/markup.po +[o:python-doc:p:python-313:r:library--mailcap] +file_filter = library/mailcap.po +trans.pt_BR = library/mailcap.po +source_file = ../build/gettext/library/mailcap.pot +type = PO +minimum_perc = 0 +resource_name = library--mailcap +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--markup] +file_filter = library/markup.po trans.pt_BR = library/markup.po -source_file = ../../pot/library/markup.pot +source_file = ../build/gettext/library/markup.pot type = PO minimum_perc = 0 resource_name = library--markup replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--marshal] -file_filter = .//LC_MESSAGES/library/marshal.po +[o:python-doc:p:python-313:r:library--marshal] +file_filter = library/marshal.po trans.pt_BR = library/marshal.po -source_file = ../../pot/library/marshal.pot +source_file = ../build/gettext/library/marshal.pot type = PO minimum_perc = 0 resource_name = library--marshal replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--math] -file_filter = .//LC_MESSAGES/library/math.po +[o:python-doc:p:python-313:r:library--math] +file_filter = library/math.po trans.pt_BR = library/math.po -source_file = ../../pot/library/math.pot +source_file = ../build/gettext/library/math.pot type = PO minimum_perc = 0 resource_name = library--math replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--mimetypes] -file_filter = .//LC_MESSAGES/library/mimetypes.po +[o:python-doc:p:python-313:r:library--mimetypes] +file_filter = library/mimetypes.po trans.pt_BR = library/mimetypes.po -source_file = ../../pot/library/mimetypes.pot +source_file = ../build/gettext/library/mimetypes.pot type = PO minimum_perc = 0 resource_name = library--mimetypes replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--mm] -file_filter = .//LC_MESSAGES/library/mm.po +[o:python-doc:p:python-313:r:library--mm] +file_filter = library/mm.po trans.pt_BR = library/mm.po -source_file = ../../pot/library/mm.pot +source_file = ../build/gettext/library/mm.pot type = PO minimum_perc = 0 resource_name = library--mm replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--mmap] -file_filter = .//LC_MESSAGES/library/mmap.po +[o:python-doc:p:python-313:r:library--mmap] +file_filter = library/mmap.po trans.pt_BR = library/mmap.po -source_file = ../../pot/library/mmap.pot +source_file = ../build/gettext/library/mmap.pot type = PO minimum_perc = 0 resource_name = library--mmap replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--modulefinder] -file_filter = .//LC_MESSAGES/library/modulefinder.po +[o:python-doc:p:python-313:r:library--modulefinder] +file_filter = library/modulefinder.po trans.pt_BR = library/modulefinder.po -source_file = ../../pot/library/modulefinder.pot +source_file = ../build/gettext/library/modulefinder.pot type = PO minimum_perc = 0 resource_name = library--modulefinder replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--modules] -file_filter = .//LC_MESSAGES/library/modules.po +[o:python-doc:p:python-313:r:library--modules] +file_filter = library/modules.po trans.pt_BR = library/modules.po -source_file = ../../pot/library/modules.pot +source_file = ../build/gettext/library/modules.pot type = PO minimum_perc = 0 resource_name = library--modules replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--msvcrt] -file_filter = .//LC_MESSAGES/library/msvcrt.po +[o:python-doc:p:python-313:r:library--msilib] +file_filter = library/msilib.po +trans.pt_BR = library/msilib.po +source_file = ../build/gettext/library/msilib.pot +type = PO +minimum_perc = 0 +resource_name = library--msilib +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--msvcrt] +file_filter = library/msvcrt.po trans.pt_BR = library/msvcrt.po -source_file = ../../pot/library/msvcrt.pot +source_file = ../build/gettext/library/msvcrt.pot type = PO minimum_perc = 0 resource_name = library--msvcrt replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--multiprocessing] -file_filter = .//LC_MESSAGES/library/multiprocessing.po +[o:python-doc:p:python-313:r:library--multiprocessing] +file_filter = library/multiprocessing.po trans.pt_BR = library/multiprocessing.po -source_file = ../../pot/library/multiprocessing.pot +source_file = ../build/gettext/library/multiprocessing.pot type = PO minimum_perc = 0 resource_name = library--multiprocessing replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--multiprocessing_shared_memory] -file_filter = .//LC_MESSAGES/library/multiprocessing.shared_memory.po +[o:python-doc:p:python-313:r:library--multiprocessing_shared_memory] +file_filter = library/multiprocessing.shared_memory.po trans.pt_BR = library/multiprocessing.shared_memory.po -source_file = ../../pot/library/multiprocessing.shared_memory.pot +source_file = ../build/gettext/library/multiprocessing.shared_memory.pot type = PO minimum_perc = 0 resource_name = library--multiprocessing_shared_memory replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--netdata] -file_filter = .//LC_MESSAGES/library/netdata.po +[o:python-doc:p:python-313:r:library--netdata] +file_filter = library/netdata.po trans.pt_BR = library/netdata.po -source_file = ../../pot/library/netdata.pot +source_file = ../build/gettext/library/netdata.pot type = PO minimum_perc = 0 resource_name = library--netdata replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--netrc] -file_filter = .//LC_MESSAGES/library/netrc.po +[o:python-doc:p:python-313:r:library--netrc] +file_filter = library/netrc.po trans.pt_BR = library/netrc.po -source_file = ../../pot/library/netrc.pot +source_file = ../build/gettext/library/netrc.pot type = PO minimum_perc = 0 resource_name = library--netrc replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--numbers] -file_filter = .//LC_MESSAGES/library/numbers.po +[o:python-doc:p:python-313:r:library--nis] +file_filter = library/nis.po +trans.pt_BR = library/nis.po +source_file = ../build/gettext/library/nis.pot +type = PO +minimum_perc = 0 +resource_name = library--nis +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--nntplib] +file_filter = library/nntplib.po +trans.pt_BR = library/nntplib.po +source_file = ../build/gettext/library/nntplib.pot +type = PO +minimum_perc = 0 +resource_name = library--nntplib +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--numbers] +file_filter = library/numbers.po trans.pt_BR = library/numbers.po -source_file = ../../pot/library/numbers.pot +source_file = ../build/gettext/library/numbers.pot type = PO minimum_perc = 0 resource_name = library--numbers replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--numeric] -file_filter = .//LC_MESSAGES/library/numeric.po +[o:python-doc:p:python-313:r:library--numeric] +file_filter = library/numeric.po trans.pt_BR = library/numeric.po -source_file = ../../pot/library/numeric.pot +source_file = ../build/gettext/library/numeric.pot type = PO minimum_perc = 0 resource_name = library--numeric replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--operator] -file_filter = .//LC_MESSAGES/library/operator.po +[o:python-doc:p:python-313:r:library--operator] +file_filter = library/operator.po trans.pt_BR = library/operator.po -source_file = ../../pot/library/operator.pot +source_file = ../build/gettext/library/operator.pot type = PO minimum_perc = 0 resource_name = library--operator replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--optparse] -file_filter = .//LC_MESSAGES/library/optparse.po +[o:python-doc:p:python-313:r:library--optparse] +file_filter = library/optparse.po trans.pt_BR = library/optparse.po -source_file = ../../pot/library/optparse.pot +source_file = ../build/gettext/library/optparse.pot type = PO minimum_perc = 0 resource_name = library--optparse replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--os] -file_filter = .//LC_MESSAGES/library/os.po +[o:python-doc:p:python-313:r:library--os] +file_filter = library/os.po trans.pt_BR = library/os.po -source_file = ../../pot/library/os.pot +source_file = ../build/gettext/library/os.pot type = PO minimum_perc = 0 resource_name = library--os replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--os_path] -file_filter = .//LC_MESSAGES/library/os.path.po +[o:python-doc:p:python-313:r:library--os_path] +file_filter = library/os.path.po trans.pt_BR = library/os.path.po -source_file = ../../pot/library/os.path.pot +source_file = ../build/gettext/library/os.path.pot type = PO minimum_perc = 0 resource_name = library--os_path replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--pathlib] -file_filter = .//LC_MESSAGES/library/pathlib.po +[o:python-doc:p:python-313:r:library--ossaudiodev] +file_filter = library/ossaudiodev.po +trans.pt_BR = library/ossaudiodev.po +source_file = ../build/gettext/library/ossaudiodev.pot +type = PO +minimum_perc = 0 +resource_name = library--ossaudiodev +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--pathlib] +file_filter = library/pathlib.po trans.pt_BR = library/pathlib.po -source_file = ../../pot/library/pathlib.pot +source_file = ../build/gettext/library/pathlib.pot type = PO minimum_perc = 0 resource_name = library--pathlib replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--pdb] -file_filter = .//LC_MESSAGES/library/pdb.po +[o:python-doc:p:python-313:r:library--pdb] +file_filter = library/pdb.po trans.pt_BR = library/pdb.po -source_file = ../../pot/library/pdb.pot +source_file = ../build/gettext/library/pdb.pot type = PO minimum_perc = 0 resource_name = library--pdb replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--persistence] -file_filter = .//LC_MESSAGES/library/persistence.po +[o:python-doc:p:python-313:r:library--persistence] +file_filter = library/persistence.po trans.pt_BR = library/persistence.po -source_file = ../../pot/library/persistence.pot +source_file = ../build/gettext/library/persistence.pot type = PO minimum_perc = 0 resource_name = library--persistence replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--pickle] -file_filter = .//LC_MESSAGES/library/pickle.po +[o:python-doc:p:python-313:r:library--pickle] +file_filter = library/pickle.po trans.pt_BR = library/pickle.po -source_file = ../../pot/library/pickle.pot +source_file = ../build/gettext/library/pickle.pot type = PO minimum_perc = 0 resource_name = library--pickle replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--pickletools] -file_filter = .//LC_MESSAGES/library/pickletools.po +[o:python-doc:p:python-313:r:library--pickletools] +file_filter = library/pickletools.po trans.pt_BR = library/pickletools.po -source_file = ../../pot/library/pickletools.pot +source_file = ../build/gettext/library/pickletools.pot type = PO minimum_perc = 0 resource_name = library--pickletools replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--pkgutil] -file_filter = .//LC_MESSAGES/library/pkgutil.po +[o:python-doc:p:python-313:r:library--pipes] +file_filter = library/pipes.po +trans.pt_BR = library/pipes.po +source_file = ../build/gettext/library/pipes.pot +type = PO +minimum_perc = 0 +resource_name = library--pipes +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--pkgutil] +file_filter = library/pkgutil.po trans.pt_BR = library/pkgutil.po -source_file = ../../pot/library/pkgutil.pot +source_file = ../build/gettext/library/pkgutil.pot type = PO minimum_perc = 0 resource_name = library--pkgutil replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--platform] -file_filter = .//LC_MESSAGES/library/platform.po +[o:python-doc:p:python-313:r:library--platform] +file_filter = library/platform.po trans.pt_BR = library/platform.po -source_file = ../../pot/library/platform.pot +source_file = ../build/gettext/library/platform.pot type = PO minimum_perc = 0 resource_name = library--platform replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--plistlib] -file_filter = .//LC_MESSAGES/library/plistlib.po +[o:python-doc:p:python-313:r:library--plistlib] +file_filter = library/plistlib.po trans.pt_BR = library/plistlib.po -source_file = ../../pot/library/plistlib.pot +source_file = ../build/gettext/library/plistlib.pot type = PO minimum_perc = 0 resource_name = library--plistlib replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--poplib] -file_filter = .//LC_MESSAGES/library/poplib.po +[o:python-doc:p:python-313:r:library--poplib] +file_filter = library/poplib.po trans.pt_BR = library/poplib.po -source_file = ../../pot/library/poplib.pot +source_file = ../build/gettext/library/poplib.pot type = PO minimum_perc = 0 resource_name = library--poplib replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--posix] -file_filter = .//LC_MESSAGES/library/posix.po +[o:python-doc:p:python-313:r:library--posix] +file_filter = library/posix.po trans.pt_BR = library/posix.po -source_file = ../../pot/library/posix.pot +source_file = ../build/gettext/library/posix.pot type = PO minimum_perc = 0 resource_name = library--posix replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--pprint] -file_filter = .//LC_MESSAGES/library/pprint.po +[o:python-doc:p:python-313:r:library--pprint] +file_filter = library/pprint.po trans.pt_BR = library/pprint.po -source_file = ../../pot/library/pprint.pot +source_file = ../build/gettext/library/pprint.pot type = PO minimum_perc = 0 resource_name = library--pprint replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--profile] -file_filter = .//LC_MESSAGES/library/profile.po +[o:python-doc:p:python-313:r:library--profile] +file_filter = library/profile.po trans.pt_BR = library/profile.po -source_file = ../../pot/library/profile.pot +source_file = ../build/gettext/library/profile.pot type = PO minimum_perc = 0 resource_name = library--profile replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--pty] -file_filter = .//LC_MESSAGES/library/pty.po +[o:python-doc:p:python-313:r:library--pty] +file_filter = library/pty.po trans.pt_BR = library/pty.po -source_file = ../../pot/library/pty.pot +source_file = ../build/gettext/library/pty.pot type = PO minimum_perc = 0 resource_name = library--pty replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--pwd] -file_filter = .//LC_MESSAGES/library/pwd.po +[o:python-doc:p:python-313:r:library--pwd] +file_filter = library/pwd.po trans.pt_BR = library/pwd.po -source_file = ../../pot/library/pwd.pot +source_file = ../build/gettext/library/pwd.pot type = PO minimum_perc = 0 resource_name = library--pwd replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--py_compile] -file_filter = .//LC_MESSAGES/library/py_compile.po +[o:python-doc:p:python-313:r:library--py_compile] +file_filter = library/py_compile.po trans.pt_BR = library/py_compile.po -source_file = ../../pot/library/py_compile.pot +source_file = ../build/gettext/library/py_compile.pot type = PO minimum_perc = 0 resource_name = library--py_compile replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--pyclbr] -file_filter = .//LC_MESSAGES/library/pyclbr.po +[o:python-doc:p:python-313:r:library--pyclbr] +file_filter = library/pyclbr.po trans.pt_BR = library/pyclbr.po -source_file = ../../pot/library/pyclbr.pot +source_file = ../build/gettext/library/pyclbr.pot type = PO minimum_perc = 0 resource_name = library--pyclbr replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--pydoc] -file_filter = .//LC_MESSAGES/library/pydoc.po +[o:python-doc:p:python-313:r:library--pydoc] +file_filter = library/pydoc.po trans.pt_BR = library/pydoc.po -source_file = ../../pot/library/pydoc.pot +source_file = ../build/gettext/library/pydoc.pot type = PO minimum_perc = 0 resource_name = library--pydoc replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--pyexpat] -file_filter = .//LC_MESSAGES/library/pyexpat.po +[o:python-doc:p:python-313:r:library--pyexpat] +file_filter = library/pyexpat.po trans.pt_BR = library/pyexpat.po -source_file = ../../pot/library/pyexpat.pot +source_file = ../build/gettext/library/pyexpat.pot type = PO minimum_perc = 0 resource_name = library--pyexpat replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--python] -file_filter = .//LC_MESSAGES/library/python.po +[o:python-doc:p:python-313:r:library--python] +file_filter = library/python.po trans.pt_BR = library/python.po -source_file = ../../pot/library/python.pot +source_file = ../build/gettext/library/python.pot type = PO minimum_perc = 0 resource_name = library--python replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--queue] -file_filter = .//LC_MESSAGES/library/queue.po +[o:python-doc:p:python-313:r:library--queue] +file_filter = library/queue.po trans.pt_BR = library/queue.po -source_file = ../../pot/library/queue.pot +source_file = ../build/gettext/library/queue.pot type = PO minimum_perc = 0 resource_name = library--queue replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--quopri] -file_filter = .//LC_MESSAGES/library/quopri.po +[o:python-doc:p:python-313:r:library--quopri] +file_filter = library/quopri.po trans.pt_BR = library/quopri.po -source_file = ../../pot/library/quopri.pot +source_file = ../build/gettext/library/quopri.pot type = PO minimum_perc = 0 resource_name = library--quopri replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--random] -file_filter = .//LC_MESSAGES/library/random.po +[o:python-doc:p:python-313:r:library--random] +file_filter = library/random.po trans.pt_BR = library/random.po -source_file = ../../pot/library/random.pot +source_file = ../build/gettext/library/random.pot type = PO minimum_perc = 0 resource_name = library--random replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--re] -file_filter = .//LC_MESSAGES/library/re.po +[o:python-doc:p:python-313:r:library--re] +file_filter = library/re.po trans.pt_BR = library/re.po -source_file = ../../pot/library/re.pot +source_file = ../build/gettext/library/re.pot type = PO minimum_perc = 0 resource_name = library--re replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--readline] -file_filter = .//LC_MESSAGES/library/readline.po +[o:python-doc:p:python-313:r:library--readline] +file_filter = library/readline.po trans.pt_BR = library/readline.po -source_file = ../../pot/library/readline.pot +source_file = ../build/gettext/library/readline.pot type = PO minimum_perc = 0 resource_name = library--readline replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--reprlib] -file_filter = .//LC_MESSAGES/library/reprlib.po +[o:python-doc:p:python-313:r:library--removed] +file_filter = library/removed.po +trans.pt_BR = library/removed.po +source_file = ../build/gettext/library/removed.pot +type = PO +minimum_perc = 0 +resource_name = library--removed +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--reprlib] +file_filter = library/reprlib.po trans.pt_BR = library/reprlib.po -source_file = ../../pot/library/reprlib.pot +source_file = ../build/gettext/library/reprlib.pot type = PO minimum_perc = 0 resource_name = library--reprlib replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--resource] -file_filter = .//LC_MESSAGES/library/resource.po +[o:python-doc:p:python-313:r:library--resource] +file_filter = library/resource.po trans.pt_BR = library/resource.po -source_file = ../../pot/library/resource.pot +source_file = ../build/gettext/library/resource.pot type = PO minimum_perc = 0 resource_name = library--resource replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--rlcompleter] -file_filter = .//LC_MESSAGES/library/rlcompleter.po +[o:python-doc:p:python-313:r:library--rlcompleter] +file_filter = library/rlcompleter.po trans.pt_BR = library/rlcompleter.po -source_file = ../../pot/library/rlcompleter.pot +source_file = ../build/gettext/library/rlcompleter.pot type = PO minimum_perc = 0 resource_name = library--rlcompleter replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--runpy] -file_filter = .//LC_MESSAGES/library/runpy.po +[o:python-doc:p:python-313:r:library--runpy] +file_filter = library/runpy.po trans.pt_BR = library/runpy.po -source_file = ../../pot/library/runpy.pot +source_file = ../build/gettext/library/runpy.pot type = PO minimum_perc = 0 resource_name = library--runpy replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--sched] -file_filter = .//LC_MESSAGES/library/sched.po +[o:python-doc:p:python-313:r:library--sched] +file_filter = library/sched.po trans.pt_BR = library/sched.po -source_file = ../../pot/library/sched.pot +source_file = ../build/gettext/library/sched.pot type = PO minimum_perc = 0 resource_name = library--sched replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--secrets] -file_filter = .//LC_MESSAGES/library/secrets.po +[o:python-doc:p:python-313:r:library--secrets] +file_filter = library/secrets.po trans.pt_BR = library/secrets.po -source_file = ../../pot/library/secrets.pot +source_file = ../build/gettext/library/secrets.pot type = PO minimum_perc = 0 resource_name = library--secrets replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--security_warnings] -file_filter = .//LC_MESSAGES/library/security_warnings.po +[o:python-doc:p:python-313:r:library--security_warnings] +file_filter = library/security_warnings.po trans.pt_BR = library/security_warnings.po -source_file = ../../pot/library/security_warnings.pot +source_file = ../build/gettext/library/security_warnings.pot type = PO minimum_perc = 0 resource_name = library--security_warnings replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--select] -file_filter = .//LC_MESSAGES/library/select.po +[o:python-doc:p:python-313:r:library--select] +file_filter = library/select.po trans.pt_BR = library/select.po -source_file = ../../pot/library/select.pot +source_file = ../build/gettext/library/select.pot type = PO minimum_perc = 0 resource_name = library--select replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--selectors] -file_filter = .//LC_MESSAGES/library/selectors.po +[o:python-doc:p:python-313:r:library--selectors] +file_filter = library/selectors.po trans.pt_BR = library/selectors.po -source_file = ../../pot/library/selectors.pot +source_file = ../build/gettext/library/selectors.pot type = PO minimum_perc = 0 resource_name = library--selectors replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--shelve] -file_filter = .//LC_MESSAGES/library/shelve.po +[o:python-doc:p:python-313:r:library--shelve] +file_filter = library/shelve.po trans.pt_BR = library/shelve.po -source_file = ../../pot/library/shelve.pot +source_file = ../build/gettext/library/shelve.pot type = PO minimum_perc = 0 resource_name = library--shelve replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--shlex] -file_filter = .//LC_MESSAGES/library/shlex.po +[o:python-doc:p:python-313:r:library--shlex] +file_filter = library/shlex.po trans.pt_BR = library/shlex.po -source_file = ../../pot/library/shlex.pot +source_file = ../build/gettext/library/shlex.pot type = PO minimum_perc = 0 resource_name = library--shlex replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--shutil] -file_filter = .//LC_MESSAGES/library/shutil.po +[o:python-doc:p:python-313:r:library--shutil] +file_filter = library/shutil.po trans.pt_BR = library/shutil.po -source_file = ../../pot/library/shutil.pot +source_file = ../build/gettext/library/shutil.pot type = PO minimum_perc = 0 resource_name = library--shutil replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--signal] -file_filter = .//LC_MESSAGES/library/signal.po +[o:python-doc:p:python-313:r:library--signal] +file_filter = library/signal.po trans.pt_BR = library/signal.po -source_file = ../../pot/library/signal.pot +source_file = ../build/gettext/library/signal.pot type = PO minimum_perc = 0 resource_name = library--signal replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--site] -file_filter = .//LC_MESSAGES/library/site.po +[o:python-doc:p:python-313:r:library--site] +file_filter = library/site.po trans.pt_BR = library/site.po -source_file = ../../pot/library/site.pot +source_file = ../build/gettext/library/site.pot type = PO minimum_perc = 0 resource_name = library--site replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--smtplib] -file_filter = .//LC_MESSAGES/library/smtplib.po +[o:python-doc:p:python-313:r:library--smtpd] +file_filter = library/smtpd.po +trans.pt_BR = library/smtpd.po +source_file = ../build/gettext/library/smtpd.pot +type = PO +minimum_perc = 0 +resource_name = library--smtpd +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--smtplib] +file_filter = library/smtplib.po trans.pt_BR = library/smtplib.po -source_file = ../../pot/library/smtplib.pot +source_file = ../build/gettext/library/smtplib.pot type = PO minimum_perc = 0 resource_name = library--smtplib replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--socket] -file_filter = .//LC_MESSAGES/library/socket.po +[o:python-doc:p:python-313:r:library--sndhdr] +file_filter = library/sndhdr.po +trans.pt_BR = library/sndhdr.po +source_file = ../build/gettext/library/sndhdr.pot +type = PO +minimum_perc = 0 +resource_name = library--sndhdr +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--socket] +file_filter = library/socket.po trans.pt_BR = library/socket.po -source_file = ../../pot/library/socket.pot +source_file = ../build/gettext/library/socket.pot type = PO minimum_perc = 0 resource_name = library--socket replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--socketserver] -file_filter = .//LC_MESSAGES/library/socketserver.po +[o:python-doc:p:python-313:r:library--socketserver] +file_filter = library/socketserver.po trans.pt_BR = library/socketserver.po -source_file = ../../pot/library/socketserver.pot +source_file = ../build/gettext/library/socketserver.pot type = PO minimum_perc = 0 resource_name = library--socketserver replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--sqlite3] -file_filter = .//LC_MESSAGES/library/sqlite3.po +[o:python-doc:p:python-313:r:library--spwd] +file_filter = library/spwd.po +trans.pt_BR = library/spwd.po +source_file = ../build/gettext/library/spwd.pot +type = PO +minimum_perc = 0 +resource_name = library--spwd +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--sqlite3] +file_filter = library/sqlite3.po trans.pt_BR = library/sqlite3.po -source_file = ../../pot/library/sqlite3.pot +source_file = ../build/gettext/library/sqlite3.pot type = PO minimum_perc = 0 resource_name = library--sqlite3 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--ssl] -file_filter = .//LC_MESSAGES/library/ssl.po +[o:python-doc:p:python-313:r:library--ssl] +file_filter = library/ssl.po trans.pt_BR = library/ssl.po -source_file = ../../pot/library/ssl.pot +source_file = ../build/gettext/library/ssl.pot type = PO minimum_perc = 0 resource_name = library--ssl replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--stat] -file_filter = .//LC_MESSAGES/library/stat.po +[o:python-doc:p:python-313:r:library--stat] +file_filter = library/stat.po trans.pt_BR = library/stat.po -source_file = ../../pot/library/stat.pot +source_file = ../build/gettext/library/stat.pot type = PO minimum_perc = 0 resource_name = library--stat replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--statistics] -file_filter = .//LC_MESSAGES/library/statistics.po +[o:python-doc:p:python-313:r:library--statistics] +file_filter = library/statistics.po trans.pt_BR = library/statistics.po -source_file = ../../pot/library/statistics.pot +source_file = ../build/gettext/library/statistics.pot type = PO minimum_perc = 0 resource_name = library--statistics replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--stdtypes] -file_filter = .//LC_MESSAGES/library/stdtypes.po +[o:python-doc:p:python-313:r:library--stdtypes] +file_filter = library/stdtypes.po trans.pt_BR = library/stdtypes.po -source_file = ../../pot/library/stdtypes.pot +source_file = ../build/gettext/library/stdtypes.pot type = PO minimum_perc = 0 resource_name = library--stdtypes replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--string] -file_filter = .//LC_MESSAGES/library/string.po +[o:python-doc:p:python-313:r:library--string] +file_filter = library/string.po trans.pt_BR = library/string.po -source_file = ../../pot/library/string.pot +source_file = ../build/gettext/library/string.pot type = PO minimum_perc = 0 resource_name = library--string replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--stringprep] -file_filter = .//LC_MESSAGES/library/stringprep.po +[o:python-doc:p:python-313:r:library--stringprep] +file_filter = library/stringprep.po trans.pt_BR = library/stringprep.po -source_file = ../../pot/library/stringprep.pot +source_file = ../build/gettext/library/stringprep.pot type = PO minimum_perc = 0 resource_name = library--stringprep replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--struct] -file_filter = .//LC_MESSAGES/library/struct.po +[o:python-doc:p:python-313:r:library--struct] +file_filter = library/struct.po trans.pt_BR = library/struct.po -source_file = ../../pot/library/struct.pot +source_file = ../build/gettext/library/struct.pot type = PO minimum_perc = 0 resource_name = library--struct replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--subprocess] -file_filter = .//LC_MESSAGES/library/subprocess.po +[o:python-doc:p:python-313:r:library--subprocess] +file_filter = library/subprocess.po trans.pt_BR = library/subprocess.po -source_file = ../../pot/library/subprocess.pot +source_file = ../build/gettext/library/subprocess.pot type = PO minimum_perc = 0 resource_name = library--subprocess replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--superseded] -file_filter = .//LC_MESSAGES/library/superseded.po +[o:python-doc:p:python-313:r:library--sunau] +file_filter = library/sunau.po +trans.pt_BR = library/sunau.po +source_file = ../build/gettext/library/sunau.pot +type = PO +minimum_perc = 0 +resource_name = library--sunau +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--superseded] +file_filter = library/superseded.po trans.pt_BR = library/superseded.po -source_file = ../../pot/library/superseded.pot +source_file = ../build/gettext/library/superseded.pot type = PO minimum_perc = 0 resource_name = library--superseded replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--symtable] -file_filter = .//LC_MESSAGES/library/symtable.po +[o:python-doc:p:python-313:r:library--symtable] +file_filter = library/symtable.po trans.pt_BR = library/symtable.po -source_file = ../../pot/library/symtable.pot +source_file = ../build/gettext/library/symtable.pot type = PO minimum_perc = 0 resource_name = library--symtable replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--sys] -file_filter = .//LC_MESSAGES/library/sys.po +[o:python-doc:p:python-313:r:library--sys] +file_filter = library/sys.po trans.pt_BR = library/sys.po -source_file = ../../pot/library/sys.pot +source_file = ../build/gettext/library/sys.pot type = PO minimum_perc = 0 resource_name = library--sys replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--sys_monitoring] -file_filter = .//LC_MESSAGES/library/sys.monitoring.po +[o:python-doc:p:python-313:r:library--sys_monitoring] +file_filter = library/sys.monitoring.po trans.pt_BR = library/sys.monitoring.po -source_file = ../../pot/library/sys.monitoring.pot +source_file = ../build/gettext/library/sys.monitoring.pot type = PO minimum_perc = 0 resource_name = library--sys_monitoring replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--sys_path_init] -file_filter = .//LC_MESSAGES/library/sys_path_init.po +[o:python-doc:p:python-313:r:library--sys_path_init] +file_filter = library/sys_path_init.po trans.pt_BR = library/sys_path_init.po -source_file = ../../pot/library/sys_path_init.pot +source_file = ../build/gettext/library/sys_path_init.pot type = PO minimum_perc = 0 resource_name = library--sys_path_init replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--sysconfig] -file_filter = .//LC_MESSAGES/library/sysconfig.po +[o:python-doc:p:python-313:r:library--sysconfig] +file_filter = library/sysconfig.po trans.pt_BR = library/sysconfig.po -source_file = ../../pot/library/sysconfig.pot +source_file = ../build/gettext/library/sysconfig.pot type = PO minimum_perc = 0 resource_name = library--sysconfig replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--syslog] -file_filter = .//LC_MESSAGES/library/syslog.po +[o:python-doc:p:python-313:r:library--syslog] +file_filter = library/syslog.po trans.pt_BR = library/syslog.po -source_file = ../../pot/library/syslog.pot +source_file = ../build/gettext/library/syslog.pot type = PO minimum_perc = 0 resource_name = library--syslog replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--tabnanny] -file_filter = .//LC_MESSAGES/library/tabnanny.po +[o:python-doc:p:python-313:r:library--tabnanny] +file_filter = library/tabnanny.po trans.pt_BR = library/tabnanny.po -source_file = ../../pot/library/tabnanny.pot +source_file = ../build/gettext/library/tabnanny.pot type = PO minimum_perc = 0 resource_name = library--tabnanny replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--tarfile] -file_filter = .//LC_MESSAGES/library/tarfile.po +[o:python-doc:p:python-313:r:library--tarfile] +file_filter = library/tarfile.po trans.pt_BR = library/tarfile.po -source_file = ../../pot/library/tarfile.pot +source_file = ../build/gettext/library/tarfile.pot type = PO minimum_perc = 0 resource_name = library--tarfile replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--tempfile] -file_filter = .//LC_MESSAGES/library/tempfile.po +[o:python-doc:p:python-313:r:library--telnetlib] +file_filter = library/telnetlib.po +trans.pt_BR = library/telnetlib.po +source_file = ../build/gettext/library/telnetlib.pot +type = PO +minimum_perc = 0 +resource_name = library--telnetlib +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--tempfile] +file_filter = library/tempfile.po trans.pt_BR = library/tempfile.po -source_file = ../../pot/library/tempfile.pot +source_file = ../build/gettext/library/tempfile.pot type = PO minimum_perc = 0 resource_name = library--tempfile replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--termios] -file_filter = .//LC_MESSAGES/library/termios.po +[o:python-doc:p:python-313:r:library--termios] +file_filter = library/termios.po trans.pt_BR = library/termios.po -source_file = ../../pot/library/termios.pot +source_file = ../build/gettext/library/termios.pot type = PO minimum_perc = 0 resource_name = library--termios replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--test] -file_filter = .//LC_MESSAGES/library/test.po +[o:python-doc:p:python-313:r:library--test] +file_filter = library/test.po trans.pt_BR = library/test.po -source_file = ../../pot/library/test.pot +source_file = ../build/gettext/library/test.pot type = PO minimum_perc = 0 resource_name = library--test replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--text] -file_filter = .//LC_MESSAGES/library/text.po +[o:python-doc:p:python-313:r:library--text] +file_filter = library/text.po trans.pt_BR = library/text.po -source_file = ../../pot/library/text.pot +source_file = ../build/gettext/library/text.pot type = PO minimum_perc = 0 resource_name = library--text replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--textwrap] -file_filter = .//LC_MESSAGES/library/textwrap.po +[o:python-doc:p:python-313:r:library--textwrap] +file_filter = library/textwrap.po trans.pt_BR = library/textwrap.po -source_file = ../../pot/library/textwrap.pot +source_file = ../build/gettext/library/textwrap.pot type = PO minimum_perc = 0 resource_name = library--textwrap replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--threading] -file_filter = .//LC_MESSAGES/library/threading.po +[o:python-doc:p:python-313:r:library--threading] +file_filter = library/threading.po trans.pt_BR = library/threading.po -source_file = ../../pot/library/threading.pot +source_file = ../build/gettext/library/threading.pot type = PO minimum_perc = 0 resource_name = library--threading replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--time] -file_filter = .//LC_MESSAGES/library/time.po +[o:python-doc:p:python-313:r:library--time] +file_filter = library/time.po trans.pt_BR = library/time.po -source_file = ../../pot/library/time.pot +source_file = ../build/gettext/library/time.pot type = PO minimum_perc = 0 resource_name = library--time replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--timeit] -file_filter = .//LC_MESSAGES/library/timeit.po +[o:python-doc:p:python-313:r:library--timeit] +file_filter = library/timeit.po trans.pt_BR = library/timeit.po -source_file = ../../pot/library/timeit.pot +source_file = ../build/gettext/library/timeit.pot type = PO minimum_perc = 0 resource_name = library--timeit replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--tk] -file_filter = .//LC_MESSAGES/library/tk.po +[o:python-doc:p:python-313:r:library--tk] +file_filter = library/tk.po trans.pt_BR = library/tk.po -source_file = ../../pot/library/tk.pot +source_file = ../build/gettext/library/tk.pot type = PO minimum_perc = 0 resource_name = library--tk replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--tkinter] -file_filter = .//LC_MESSAGES/library/tkinter.po +[o:python-doc:p:python-313:r:library--tkinter] +file_filter = library/tkinter.po trans.pt_BR = library/tkinter.po -source_file = ../../pot/library/tkinter.pot +source_file = ../build/gettext/library/tkinter.pot type = PO minimum_perc = 0 resource_name = library--tkinter replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--tkinter_colorchooser] -file_filter = .//LC_MESSAGES/library/tkinter.colorchooser.po +[o:python-doc:p:python-313:r:library--tkinter_colorchooser] +file_filter = library/tkinter.colorchooser.po trans.pt_BR = library/tkinter.colorchooser.po -source_file = ../../pot/library/tkinter.colorchooser.pot +source_file = ../build/gettext/library/tkinter.colorchooser.pot type = PO minimum_perc = 0 resource_name = library--tkinter_colorchooser replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--tkinter_dnd] -file_filter = .//LC_MESSAGES/library/tkinter.dnd.po +[o:python-doc:p:python-313:r:library--tkinter_dnd] +file_filter = library/tkinter.dnd.po trans.pt_BR = library/tkinter.dnd.po -source_file = ../../pot/library/tkinter.dnd.pot +source_file = ../build/gettext/library/tkinter.dnd.pot type = PO minimum_perc = 0 resource_name = library--tkinter_dnd replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--tkinter_font] -file_filter = .//LC_MESSAGES/library/tkinter.font.po +[o:python-doc:p:python-313:r:library--tkinter_font] +file_filter = library/tkinter.font.po trans.pt_BR = library/tkinter.font.po -source_file = ../../pot/library/tkinter.font.pot +source_file = ../build/gettext/library/tkinter.font.pot type = PO minimum_perc = 0 resource_name = library--tkinter_font replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--tkinter_messagebox] -file_filter = .//LC_MESSAGES/library/tkinter.messagebox.po +[o:python-doc:p:python-313:r:library--tkinter_messagebox] +file_filter = library/tkinter.messagebox.po trans.pt_BR = library/tkinter.messagebox.po -source_file = ../../pot/library/tkinter.messagebox.pot +source_file = ../build/gettext/library/tkinter.messagebox.pot type = PO minimum_perc = 0 resource_name = library--tkinter_messagebox replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--tkinter_scrolledtext] -file_filter = .//LC_MESSAGES/library/tkinter.scrolledtext.po +[o:python-doc:p:python-313:r:library--tkinter_scrolledtext] +file_filter = library/tkinter.scrolledtext.po trans.pt_BR = library/tkinter.scrolledtext.po -source_file = ../../pot/library/tkinter.scrolledtext.pot +source_file = ../build/gettext/library/tkinter.scrolledtext.pot type = PO minimum_perc = 0 resource_name = library--tkinter_scrolledtext replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--tkinter_ttk] -file_filter = .//LC_MESSAGES/library/tkinter.ttk.po +[o:python-doc:p:python-313:r:library--tkinter_ttk] +file_filter = library/tkinter.ttk.po trans.pt_BR = library/tkinter.ttk.po -source_file = ../../pot/library/tkinter.ttk.pot +source_file = ../build/gettext/library/tkinter.ttk.pot type = PO minimum_perc = 0 resource_name = library--tkinter_ttk replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--token] -file_filter = .//LC_MESSAGES/library/token.po +[o:python-doc:p:python-313:r:library--token] +file_filter = library/token.po trans.pt_BR = library/token.po -source_file = ../../pot/library/token.pot +source_file = ../build/gettext/library/token.pot type = PO minimum_perc = 0 resource_name = library--token replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--tokenize] -file_filter = .//LC_MESSAGES/library/tokenize.po +[o:python-doc:p:python-313:r:library--tokenize] +file_filter = library/tokenize.po trans.pt_BR = library/tokenize.po -source_file = ../../pot/library/tokenize.pot +source_file = ../build/gettext/library/tokenize.pot type = PO minimum_perc = 0 resource_name = library--tokenize replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--tomllib] -file_filter = .//LC_MESSAGES/library/tomllib.po +[o:python-doc:p:python-313:r:library--tomllib] +file_filter = library/tomllib.po trans.pt_BR = library/tomllib.po -source_file = ../../pot/library/tomllib.pot +source_file = ../build/gettext/library/tomllib.pot type = PO minimum_perc = 0 resource_name = library--tomllib replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--trace] -file_filter = .//LC_MESSAGES/library/trace.po +[o:python-doc:p:python-313:r:library--trace] +file_filter = library/trace.po trans.pt_BR = library/trace.po -source_file = ../../pot/library/trace.pot +source_file = ../build/gettext/library/trace.pot type = PO minimum_perc = 0 resource_name = library--trace replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--traceback] -file_filter = .//LC_MESSAGES/library/traceback.po +[o:python-doc:p:python-313:r:library--traceback] +file_filter = library/traceback.po trans.pt_BR = library/traceback.po -source_file = ../../pot/library/traceback.pot +source_file = ../build/gettext/library/traceback.pot type = PO minimum_perc = 0 resource_name = library--traceback replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--tracemalloc] -file_filter = .//LC_MESSAGES/library/tracemalloc.po +[o:python-doc:p:python-313:r:library--tracemalloc] +file_filter = library/tracemalloc.po trans.pt_BR = library/tracemalloc.po -source_file = ../../pot/library/tracemalloc.pot +source_file = ../build/gettext/library/tracemalloc.pot type = PO minimum_perc = 0 resource_name = library--tracemalloc replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--tty] -file_filter = .//LC_MESSAGES/library/tty.po +[o:python-doc:p:python-313:r:library--tty] +file_filter = library/tty.po trans.pt_BR = library/tty.po -source_file = ../../pot/library/tty.pot +source_file = ../build/gettext/library/tty.pot type = PO minimum_perc = 0 resource_name = library--tty replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--turtle] -file_filter = .//LC_MESSAGES/library/turtle.po +[o:python-doc:p:python-313:r:library--turtle] +file_filter = library/turtle.po trans.pt_BR = library/turtle.po -source_file = ../../pot/library/turtle.pot +source_file = ../build/gettext/library/turtle.pot type = PO minimum_perc = 0 resource_name = library--turtle replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--types] -file_filter = .//LC_MESSAGES/library/types.po +[o:python-doc:p:python-313:r:library--types] +file_filter = library/types.po trans.pt_BR = library/types.po -source_file = ../../pot/library/types.pot +source_file = ../build/gettext/library/types.pot type = PO minimum_perc = 0 resource_name = library--types replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--typing] -file_filter = .//LC_MESSAGES/library/typing.po +[o:python-doc:p:python-313:r:library--typing] +file_filter = library/typing.po trans.pt_BR = library/typing.po -source_file = ../../pot/library/typing.pot +source_file = ../build/gettext/library/typing.pot type = PO minimum_perc = 0 resource_name = library--typing replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--unicodedata] -file_filter = .//LC_MESSAGES/library/unicodedata.po +[o:python-doc:p:python-313:r:library--unicodedata] +file_filter = library/unicodedata.po trans.pt_BR = library/unicodedata.po -source_file = ../../pot/library/unicodedata.pot +source_file = ../build/gettext/library/unicodedata.pot type = PO minimum_perc = 0 resource_name = library--unicodedata replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--unittest] -file_filter = .//LC_MESSAGES/library/unittest.po +[o:python-doc:p:python-313:r:library--unittest] +file_filter = library/unittest.po trans.pt_BR = library/unittest.po -source_file = ../../pot/library/unittest.pot +source_file = ../build/gettext/library/unittest.pot type = PO minimum_perc = 0 resource_name = library--unittest replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--unittest_mock] -file_filter = .//LC_MESSAGES/library/unittest.mock.po +[o:python-doc:p:python-313:r:library--unittest_mock] +file_filter = library/unittest.mock.po trans.pt_BR = library/unittest.mock.po -source_file = ../../pot/library/unittest.mock.pot +source_file = ../build/gettext/library/unittest.mock.pot type = PO minimum_perc = 0 resource_name = library--unittest_mock replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--unittest_mock-examples] -file_filter = .//LC_MESSAGES/library/unittest.mock-examples.po +[o:python-doc:p:python-313:r:library--unittest_mock-examples] +file_filter = library/unittest.mock-examples.po trans.pt_BR = library/unittest.mock-examples.po -source_file = ../../pot/library/unittest.mock-examples.pot +source_file = ../build/gettext/library/unittest.mock-examples.pot type = PO minimum_perc = 0 resource_name = library--unittest_mock-examples replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--unix] -file_filter = .//LC_MESSAGES/library/unix.po +[o:python-doc:p:python-313:r:library--unix] +file_filter = library/unix.po trans.pt_BR = library/unix.po -source_file = ../../pot/library/unix.pot +source_file = ../build/gettext/library/unix.pot type = PO minimum_perc = 0 resource_name = library--unix replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--urllib] -file_filter = .//LC_MESSAGES/library/urllib.po +[o:python-doc:p:python-313:r:library--urllib] +file_filter = library/urllib.po trans.pt_BR = library/urllib.po -source_file = ../../pot/library/urllib.pot +source_file = ../build/gettext/library/urllib.pot type = PO minimum_perc = 0 resource_name = library--urllib replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--urllib_error] -file_filter = .//LC_MESSAGES/library/urllib.error.po +[o:python-doc:p:python-313:r:library--urllib_error] +file_filter = library/urllib.error.po trans.pt_BR = library/urllib.error.po -source_file = ../../pot/library/urllib.error.pot +source_file = ../build/gettext/library/urllib.error.pot type = PO minimum_perc = 0 resource_name = library--urllib_error replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--urllib_parse] -file_filter = .//LC_MESSAGES/library/urllib.parse.po +[o:python-doc:p:python-313:r:library--urllib_parse] +file_filter = library/urllib.parse.po trans.pt_BR = library/urllib.parse.po -source_file = ../../pot/library/urllib.parse.pot +source_file = ../build/gettext/library/urllib.parse.pot type = PO minimum_perc = 0 resource_name = library--urllib_parse replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--urllib_request] -file_filter = .//LC_MESSAGES/library/urllib.request.po +[o:python-doc:p:python-313:r:library--urllib_request] +file_filter = library/urllib.request.po trans.pt_BR = library/urllib.request.po -source_file = ../../pot/library/urllib.request.pot +source_file = ../build/gettext/library/urllib.request.pot type = PO minimum_perc = 0 resource_name = library--urllib_request replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--urllib_robotparser] -file_filter = .//LC_MESSAGES/library/urllib.robotparser.po +[o:python-doc:p:python-313:r:library--urllib_robotparser] +file_filter = library/urllib.robotparser.po trans.pt_BR = library/urllib.robotparser.po -source_file = ../../pot/library/urllib.robotparser.pot +source_file = ../build/gettext/library/urllib.robotparser.pot type = PO minimum_perc = 0 resource_name = library--urllib_robotparser replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--uuid] -file_filter = .//LC_MESSAGES/library/uuid.po +[o:python-doc:p:python-313:r:library--uu] +file_filter = library/uu.po +trans.pt_BR = library/uu.po +source_file = ../build/gettext/library/uu.pot +type = PO +minimum_perc = 0 +resource_name = library--uu +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--uuid] +file_filter = library/uuid.po trans.pt_BR = library/uuid.po -source_file = ../../pot/library/uuid.pot +source_file = ../build/gettext/library/uuid.pot type = PO minimum_perc = 0 resource_name = library--uuid replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--venv] -file_filter = .//LC_MESSAGES/library/venv.po +[o:python-doc:p:python-313:r:library--venv] +file_filter = library/venv.po trans.pt_BR = library/venv.po -source_file = ../../pot/library/venv.pot +source_file = ../build/gettext/library/venv.pot type = PO minimum_perc = 0 resource_name = library--venv replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--warnings] -file_filter = .//LC_MESSAGES/library/warnings.po +[o:python-doc:p:python-313:r:library--warnings] +file_filter = library/warnings.po trans.pt_BR = library/warnings.po -source_file = ../../pot/library/warnings.pot +source_file = ../build/gettext/library/warnings.pot type = PO minimum_perc = 0 resource_name = library--warnings replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--wave] -file_filter = .//LC_MESSAGES/library/wave.po +[o:python-doc:p:python-313:r:library--wave] +file_filter = library/wave.po trans.pt_BR = library/wave.po -source_file = ../../pot/library/wave.pot +source_file = ../build/gettext/library/wave.pot type = PO minimum_perc = 0 resource_name = library--wave replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--weakref] -file_filter = .//LC_MESSAGES/library/weakref.po +[o:python-doc:p:python-313:r:library--weakref] +file_filter = library/weakref.po trans.pt_BR = library/weakref.po -source_file = ../../pot/library/weakref.pot +source_file = ../build/gettext/library/weakref.pot type = PO minimum_perc = 0 resource_name = library--weakref replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--webbrowser] -file_filter = .//LC_MESSAGES/library/webbrowser.po +[o:python-doc:p:python-313:r:library--webbrowser] +file_filter = library/webbrowser.po trans.pt_BR = library/webbrowser.po -source_file = ../../pot/library/webbrowser.pot +source_file = ../build/gettext/library/webbrowser.pot type = PO minimum_perc = 0 resource_name = library--webbrowser replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--windows] -file_filter = .//LC_MESSAGES/library/windows.po +[o:python-doc:p:python-313:r:library--windows] +file_filter = library/windows.po trans.pt_BR = library/windows.po -source_file = ../../pot/library/windows.pot +source_file = ../build/gettext/library/windows.pot type = PO minimum_perc = 0 resource_name = library--windows replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--winreg] -file_filter = .//LC_MESSAGES/library/winreg.po +[o:python-doc:p:python-313:r:library--winreg] +file_filter = library/winreg.po trans.pt_BR = library/winreg.po -source_file = ../../pot/library/winreg.pot +source_file = ../build/gettext/library/winreg.pot type = PO minimum_perc = 0 resource_name = library--winreg replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--winsound] -file_filter = .//LC_MESSAGES/library/winsound.po +[o:python-doc:p:python-313:r:library--winsound] +file_filter = library/winsound.po trans.pt_BR = library/winsound.po -source_file = ../../pot/library/winsound.pot +source_file = ../build/gettext/library/winsound.pot type = PO minimum_perc = 0 resource_name = library--winsound replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--wsgiref] -file_filter = .//LC_MESSAGES/library/wsgiref.po +[o:python-doc:p:python-313:r:library--wsgiref] +file_filter = library/wsgiref.po trans.pt_BR = library/wsgiref.po -source_file = ../../pot/library/wsgiref.pot +source_file = ../build/gettext/library/wsgiref.pot type = PO minimum_perc = 0 resource_name = library--wsgiref replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--xml] -file_filter = .//LC_MESSAGES/library/xml.po +[o:python-doc:p:python-313:r:library--xdrlib] +file_filter = library/xdrlib.po +trans.pt_BR = library/xdrlib.po +source_file = ../build/gettext/library/xdrlib.pot +type = PO +minimum_perc = 0 +resource_name = library--xdrlib +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--xml] +file_filter = library/xml.po trans.pt_BR = library/xml.po -source_file = ../../pot/library/xml.pot +source_file = ../build/gettext/library/xml.pot type = PO minimum_perc = 0 resource_name = library--xml replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--xml_dom] -file_filter = .//LC_MESSAGES/library/xml.dom.po +[o:python-doc:p:python-313:r:library--xml_dom] +file_filter = library/xml.dom.po trans.pt_BR = library/xml.dom.po -source_file = ../../pot/library/xml.dom.pot +source_file = ../build/gettext/library/xml.dom.pot type = PO minimum_perc = 0 resource_name = library--xml_dom replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--xml_dom_minidom] -file_filter = .//LC_MESSAGES/library/xml.dom.minidom.po +[o:python-doc:p:python-313:r:library--xml_dom_minidom] +file_filter = library/xml.dom.minidom.po trans.pt_BR = library/xml.dom.minidom.po -source_file = ../../pot/library/xml.dom.minidom.pot +source_file = ../build/gettext/library/xml.dom.minidom.pot type = PO minimum_perc = 0 resource_name = library--xml_dom_minidom replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--xml_dom_pulldom] -file_filter = .//LC_MESSAGES/library/xml.dom.pulldom.po +[o:python-doc:p:python-313:r:library--xml_dom_pulldom] +file_filter = library/xml.dom.pulldom.po trans.pt_BR = library/xml.dom.pulldom.po -source_file = ../../pot/library/xml.dom.pulldom.pot +source_file = ../build/gettext/library/xml.dom.pulldom.pot type = PO minimum_perc = 0 resource_name = library--xml_dom_pulldom replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--xml_etree_elementtree] -file_filter = .//LC_MESSAGES/library/xml.etree.elementtree.po +[o:python-doc:p:python-313:r:library--xml_etree_elementtree] +file_filter = library/xml.etree.elementtree.po trans.pt_BR = library/xml.etree.elementtree.po -source_file = ../../pot/library/xml.etree.elementtree.pot +source_file = ../build/gettext/library/xml.etree.elementtree.pot type = PO minimum_perc = 0 resource_name = library--xml_etree_elementtree replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--xml_sax] -file_filter = .//LC_MESSAGES/library/xml.sax.po +[o:python-doc:p:python-313:r:library--xml_sax] +file_filter = library/xml.sax.po trans.pt_BR = library/xml.sax.po -source_file = ../../pot/library/xml.sax.pot +source_file = ../build/gettext/library/xml.sax.pot type = PO minimum_perc = 0 resource_name = library--xml_sax replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--xml_sax_handler] -file_filter = .//LC_MESSAGES/library/xml.sax.handler.po +[o:python-doc:p:python-313:r:library--xml_sax_handler] +file_filter = library/xml.sax.handler.po trans.pt_BR = library/xml.sax.handler.po -source_file = ../../pot/library/xml.sax.handler.pot +source_file = ../build/gettext/library/xml.sax.handler.pot type = PO minimum_perc = 0 resource_name = library--xml_sax_handler replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--xml_sax_reader] -file_filter = .//LC_MESSAGES/library/xml.sax.reader.po +[o:python-doc:p:python-313:r:library--xml_sax_reader] +file_filter = library/xml.sax.reader.po trans.pt_BR = library/xml.sax.reader.po -source_file = ../../pot/library/xml.sax.reader.pot +source_file = ../build/gettext/library/xml.sax.reader.pot type = PO minimum_perc = 0 resource_name = library--xml_sax_reader replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--xml_sax_utils] -file_filter = .//LC_MESSAGES/library/xml.sax.utils.po +[o:python-doc:p:python-313:r:library--xml_sax_utils] +file_filter = library/xml.sax.utils.po trans.pt_BR = library/xml.sax.utils.po -source_file = ../../pot/library/xml.sax.utils.pot +source_file = ../build/gettext/library/xml.sax.utils.pot type = PO minimum_perc = 0 resource_name = library--xml_sax_utils replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--xmlrpc] -file_filter = .//LC_MESSAGES/library/xmlrpc.po +[o:python-doc:p:python-313:r:library--xmlrpc] +file_filter = library/xmlrpc.po trans.pt_BR = library/xmlrpc.po -source_file = ../../pot/library/xmlrpc.pot +source_file = ../build/gettext/library/xmlrpc.pot type = PO minimum_perc = 0 resource_name = library--xmlrpc replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--xmlrpc_client] -file_filter = .//LC_MESSAGES/library/xmlrpc.client.po +[o:python-doc:p:python-313:r:library--xmlrpc_client] +file_filter = library/xmlrpc.client.po trans.pt_BR = library/xmlrpc.client.po -source_file = ../../pot/library/xmlrpc.client.pot +source_file = ../build/gettext/library/xmlrpc.client.pot type = PO minimum_perc = 0 resource_name = library--xmlrpc_client replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--xmlrpc_server] -file_filter = .//LC_MESSAGES/library/xmlrpc.server.po +[o:python-doc:p:python-313:r:library--xmlrpc_server] +file_filter = library/xmlrpc.server.po trans.pt_BR = library/xmlrpc.server.po -source_file = ../../pot/library/xmlrpc.server.pot +source_file = ../build/gettext/library/xmlrpc.server.pot type = PO minimum_perc = 0 resource_name = library--xmlrpc_server replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--zipapp] -file_filter = .//LC_MESSAGES/library/zipapp.po +[o:python-doc:p:python-313:r:library--zipapp] +file_filter = library/zipapp.po trans.pt_BR = library/zipapp.po -source_file = ../../pot/library/zipapp.pot +source_file = ../build/gettext/library/zipapp.pot type = PO minimum_perc = 0 resource_name = library--zipapp replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--zipfile] -file_filter = .//LC_MESSAGES/library/zipfile.po +[o:python-doc:p:python-313:r:library--zipfile] +file_filter = library/zipfile.po trans.pt_BR = library/zipfile.po -source_file = ../../pot/library/zipfile.pot +source_file = ../build/gettext/library/zipfile.pot type = PO minimum_perc = 0 resource_name = library--zipfile replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--zipimport] -file_filter = .//LC_MESSAGES/library/zipimport.po +[o:python-doc:p:python-313:r:library--zipimport] +file_filter = library/zipimport.po trans.pt_BR = library/zipimport.po -source_file = ../../pot/library/zipimport.pot +source_file = ../build/gettext/library/zipimport.pot type = PO minimum_perc = 0 resource_name = library--zipimport replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--zlib] -file_filter = .//LC_MESSAGES/library/zlib.po +[o:python-doc:p:python-313:r:library--zlib] +file_filter = library/zlib.po trans.pt_BR = library/zlib.po -source_file = ../../pot/library/zlib.pot +source_file = ../build/gettext/library/zlib.pot type = PO minimum_perc = 0 resource_name = library--zlib replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--zoneinfo] -file_filter = .//LC_MESSAGES/library/zoneinfo.po +[o:python-doc:p:python-313:r:library--zoneinfo] +file_filter = library/zoneinfo.po trans.pt_BR = library/zoneinfo.po -source_file = ../../pot/library/zoneinfo.pot +source_file = ../build/gettext/library/zoneinfo.pot type = PO minimum_perc = 0 resource_name = library--zoneinfo replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:license] -file_filter = .//LC_MESSAGES/license.po +[o:python-doc:p:python-313:r:license] +file_filter = license.po trans.pt_BR = license.po -source_file = ../../pot/license.pot +source_file = ../build/gettext/license.pot type = PO minimum_perc = 0 resource_name = license replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:reference--compound_stmts] -file_filter = .//LC_MESSAGES/reference/compound_stmts.po +[o:python-doc:p:python-313:r:reference--compound_stmts] +file_filter = reference/compound_stmts.po trans.pt_BR = reference/compound_stmts.po -source_file = ../../pot/reference/compound_stmts.pot +source_file = ../build/gettext/reference/compound_stmts.pot type = PO minimum_perc = 0 resource_name = reference--compound_stmts replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:reference--datamodel] -file_filter = .//LC_MESSAGES/reference/datamodel.po +[o:python-doc:p:python-313:r:reference--datamodel] +file_filter = reference/datamodel.po trans.pt_BR = reference/datamodel.po -source_file = ../../pot/reference/datamodel.pot +source_file = ../build/gettext/reference/datamodel.pot type = PO minimum_perc = 0 resource_name = reference--datamodel replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:reference--executionmodel] -file_filter = .//LC_MESSAGES/reference/executionmodel.po +[o:python-doc:p:python-313:r:reference--executionmodel] +file_filter = reference/executionmodel.po trans.pt_BR = reference/executionmodel.po -source_file = ../../pot/reference/executionmodel.pot +source_file = ../build/gettext/reference/executionmodel.pot type = PO minimum_perc = 0 resource_name = reference--executionmodel replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:reference--expressions] -file_filter = .//LC_MESSAGES/reference/expressions.po +[o:python-doc:p:python-313:r:reference--expressions] +file_filter = reference/expressions.po trans.pt_BR = reference/expressions.po -source_file = ../../pot/reference/expressions.pot +source_file = ../build/gettext/reference/expressions.pot type = PO minimum_perc = 0 resource_name = reference--expressions replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:reference--grammar] -file_filter = .//LC_MESSAGES/reference/grammar.po +[o:python-doc:p:python-313:r:reference--grammar] +file_filter = reference/grammar.po trans.pt_BR = reference/grammar.po -source_file = ../../pot/reference/grammar.pot +source_file = ../build/gettext/reference/grammar.pot type = PO minimum_perc = 0 resource_name = reference--grammar replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:reference--import] -file_filter = .//LC_MESSAGES/reference/import.po +[o:python-doc:p:python-313:r:reference--import] +file_filter = reference/import.po trans.pt_BR = reference/import.po -source_file = ../../pot/reference/import.pot +source_file = ../build/gettext/reference/import.pot type = PO minimum_perc = 0 resource_name = reference--import replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:reference--index] -file_filter = .//LC_MESSAGES/reference/index.po +[o:python-doc:p:python-313:r:reference--index] +file_filter = reference/index.po trans.pt_BR = reference/index.po -source_file = ../../pot/reference/index.pot +source_file = ../build/gettext/reference/index.pot type = PO minimum_perc = 0 resource_name = reference--index replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:reference--introduction] -file_filter = .//LC_MESSAGES/reference/introduction.po +[o:python-doc:p:python-313:r:reference--introduction] +file_filter = reference/introduction.po trans.pt_BR = reference/introduction.po -source_file = ../../pot/reference/introduction.pot +source_file = ../build/gettext/reference/introduction.pot type = PO minimum_perc = 0 resource_name = reference--introduction replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:reference--lexical_analysis] -file_filter = .//LC_MESSAGES/reference/lexical_analysis.po +[o:python-doc:p:python-313:r:reference--lexical_analysis] +file_filter = reference/lexical_analysis.po trans.pt_BR = reference/lexical_analysis.po -source_file = ../../pot/reference/lexical_analysis.pot +source_file = ../build/gettext/reference/lexical_analysis.pot type = PO minimum_perc = 0 resource_name = reference--lexical_analysis replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:reference--simple_stmts] -file_filter = .//LC_MESSAGES/reference/simple_stmts.po +[o:python-doc:p:python-313:r:reference--simple_stmts] +file_filter = reference/simple_stmts.po trans.pt_BR = reference/simple_stmts.po -source_file = ../../pot/reference/simple_stmts.pot +source_file = ../build/gettext/reference/simple_stmts.pot type = PO minimum_perc = 0 resource_name = reference--simple_stmts replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:reference--toplevel_components] -file_filter = .//LC_MESSAGES/reference/toplevel_components.po +[o:python-doc:p:python-313:r:reference--toplevel_components] +file_filter = reference/toplevel_components.po trans.pt_BR = reference/toplevel_components.po -source_file = ../../pot/reference/toplevel_components.pot +source_file = ../build/gettext/reference/toplevel_components.pot type = PO minimum_perc = 0 resource_name = reference--toplevel_components replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:sphinx] -file_filter = .//LC_MESSAGES/sphinx.po +[o:python-doc:p:python-313:r:sphinx] +file_filter = sphinx.po trans.pt_BR = sphinx.po -source_file = ../../pot/sphinx.pot +source_file = ../build/gettext/sphinx.pot type = PO minimum_perc = 0 resource_name = sphinx replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--appendix] -file_filter = .//LC_MESSAGES/tutorial/appendix.po +[o:python-doc:p:python-313:r:tutorial--appendix] +file_filter = tutorial/appendix.po trans.pt_BR = tutorial/appendix.po -source_file = ../../pot/tutorial/appendix.pot +source_file = ../build/gettext/tutorial/appendix.pot type = PO minimum_perc = 0 resource_name = tutorial--appendix replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--appetite] -file_filter = .//LC_MESSAGES/tutorial/appetite.po +[o:python-doc:p:python-313:r:tutorial--appetite] +file_filter = tutorial/appetite.po trans.pt_BR = tutorial/appetite.po -source_file = ../../pot/tutorial/appetite.pot +source_file = ../build/gettext/tutorial/appetite.pot type = PO minimum_perc = 0 resource_name = tutorial--appetite replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--classes] -file_filter = .//LC_MESSAGES/tutorial/classes.po +[o:python-doc:p:python-313:r:tutorial--classes] +file_filter = tutorial/classes.po trans.pt_BR = tutorial/classes.po -source_file = ../../pot/tutorial/classes.pot +source_file = ../build/gettext/tutorial/classes.pot type = PO minimum_perc = 0 resource_name = tutorial--classes replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--controlflow] -file_filter = .//LC_MESSAGES/tutorial/controlflow.po +[o:python-doc:p:python-313:r:tutorial--controlflow] +file_filter = tutorial/controlflow.po trans.pt_BR = tutorial/controlflow.po -source_file = ../../pot/tutorial/controlflow.pot +source_file = ../build/gettext/tutorial/controlflow.pot type = PO minimum_perc = 0 resource_name = tutorial--controlflow replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--datastructures] -file_filter = .//LC_MESSAGES/tutorial/datastructures.po +[o:python-doc:p:python-313:r:tutorial--datastructures] +file_filter = tutorial/datastructures.po trans.pt_BR = tutorial/datastructures.po -source_file = ../../pot/tutorial/datastructures.pot +source_file = ../build/gettext/tutorial/datastructures.pot type = PO minimum_perc = 0 resource_name = tutorial--datastructures replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--errors] -file_filter = .//LC_MESSAGES/tutorial/errors.po +[o:python-doc:p:python-313:r:tutorial--errors] +file_filter = tutorial/errors.po trans.pt_BR = tutorial/errors.po -source_file = ../../pot/tutorial/errors.pot +source_file = ../build/gettext/tutorial/errors.pot type = PO minimum_perc = 0 resource_name = tutorial--errors replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--floatingpoint] -file_filter = .//LC_MESSAGES/tutorial/floatingpoint.po +[o:python-doc:p:python-313:r:tutorial--floatingpoint] +file_filter = tutorial/floatingpoint.po trans.pt_BR = tutorial/floatingpoint.po -source_file = ../../pot/tutorial/floatingpoint.pot +source_file = ../build/gettext/tutorial/floatingpoint.pot type = PO minimum_perc = 0 resource_name = tutorial--floatingpoint replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--index] -file_filter = .//LC_MESSAGES/tutorial/index.po +[o:python-doc:p:python-313:r:tutorial--index] +file_filter = tutorial/index.po trans.pt_BR = tutorial/index.po -source_file = ../../pot/tutorial/index.pot +source_file = ../build/gettext/tutorial/index.pot type = PO minimum_perc = 0 resource_name = tutorial--index replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--inputoutput] -file_filter = .//LC_MESSAGES/tutorial/inputoutput.po +[o:python-doc:p:python-313:r:tutorial--inputoutput] +file_filter = tutorial/inputoutput.po trans.pt_BR = tutorial/inputoutput.po -source_file = ../../pot/tutorial/inputoutput.pot +source_file = ../build/gettext/tutorial/inputoutput.pot type = PO minimum_perc = 0 resource_name = tutorial--inputoutput replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--interactive] -file_filter = .//LC_MESSAGES/tutorial/interactive.po +[o:python-doc:p:python-313:r:tutorial--interactive] +file_filter = tutorial/interactive.po trans.pt_BR = tutorial/interactive.po -source_file = ../../pot/tutorial/interactive.pot +source_file = ../build/gettext/tutorial/interactive.pot type = PO minimum_perc = 0 resource_name = tutorial--interactive replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--interpreter] -file_filter = .//LC_MESSAGES/tutorial/interpreter.po +[o:python-doc:p:python-313:r:tutorial--interpreter] +file_filter = tutorial/interpreter.po trans.pt_BR = tutorial/interpreter.po -source_file = ../../pot/tutorial/interpreter.pot +source_file = ../build/gettext/tutorial/interpreter.pot type = PO minimum_perc = 0 resource_name = tutorial--interpreter replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--introduction] -file_filter = .//LC_MESSAGES/tutorial/introduction.po +[o:python-doc:p:python-313:r:tutorial--introduction] +file_filter = tutorial/introduction.po trans.pt_BR = tutorial/introduction.po -source_file = ../../pot/tutorial/introduction.pot +source_file = ../build/gettext/tutorial/introduction.pot type = PO minimum_perc = 0 resource_name = tutorial--introduction replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--modules] -file_filter = .//LC_MESSAGES/tutorial/modules.po +[o:python-doc:p:python-313:r:tutorial--modules] +file_filter = tutorial/modules.po trans.pt_BR = tutorial/modules.po -source_file = ../../pot/tutorial/modules.pot +source_file = ../build/gettext/tutorial/modules.pot type = PO minimum_perc = 0 resource_name = tutorial--modules replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--stdlib] -file_filter = .//LC_MESSAGES/tutorial/stdlib.po +[o:python-doc:p:python-313:r:tutorial--stdlib] +file_filter = tutorial/stdlib.po trans.pt_BR = tutorial/stdlib.po -source_file = ../../pot/tutorial/stdlib.pot +source_file = ../build/gettext/tutorial/stdlib.pot type = PO minimum_perc = 0 resource_name = tutorial--stdlib replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--stdlib2] -file_filter = .//LC_MESSAGES/tutorial/stdlib2.po +[o:python-doc:p:python-313:r:tutorial--stdlib2] +file_filter = tutorial/stdlib2.po trans.pt_BR = tutorial/stdlib2.po -source_file = ../../pot/tutorial/stdlib2.pot +source_file = ../build/gettext/tutorial/stdlib2.pot type = PO minimum_perc = 0 resource_name = tutorial--stdlib2 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--venv] -file_filter = .//LC_MESSAGES/tutorial/venv.po +[o:python-doc:p:python-313:r:tutorial--venv] +file_filter = tutorial/venv.po trans.pt_BR = tutorial/venv.po -source_file = ../../pot/tutorial/venv.pot +source_file = ../build/gettext/tutorial/venv.pot type = PO minimum_perc = 0 resource_name = tutorial--venv replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:tutorial--whatnow] -file_filter = .//LC_MESSAGES/tutorial/whatnow.po +[o:python-doc:p:python-313:r:tutorial--whatnow] +file_filter = tutorial/whatnow.po trans.pt_BR = tutorial/whatnow.po -source_file = ../../pot/tutorial/whatnow.pot +source_file = ../build/gettext/tutorial/whatnow.pot type = PO minimum_perc = 0 resource_name = tutorial--whatnow replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:using--cmdline] -file_filter = .//LC_MESSAGES/using/cmdline.po +[o:python-doc:p:python-313:r:using--android] +file_filter = using/android.po +trans.pt_BR = using/android.po +source_file = ../build/gettext/using/android.pot +type = PO +minimum_perc = 0 +resource_name = using--android +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:using--cmdline] +file_filter = using/cmdline.po trans.pt_BR = using/cmdline.po -source_file = ../../pot/using/cmdline.pot +source_file = ../build/gettext/using/cmdline.pot type = PO minimum_perc = 0 resource_name = using--cmdline replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:using--configure] -file_filter = .//LC_MESSAGES/using/configure.po +[o:python-doc:p:python-313:r:using--configure] +file_filter = using/configure.po trans.pt_BR = using/configure.po -source_file = ../../pot/using/configure.pot +source_file = ../build/gettext/using/configure.pot type = PO minimum_perc = 0 resource_name = using--configure replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:using--editors] -file_filter = .//LC_MESSAGES/using/editors.po +[o:python-doc:p:python-313:r:using--editors] +file_filter = using/editors.po trans.pt_BR = using/editors.po -source_file = ../../pot/using/editors.pot +source_file = ../build/gettext/using/editors.pot type = PO minimum_perc = 0 resource_name = using--editors replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:using--index] -file_filter = .//LC_MESSAGES/using/index.po +[o:python-doc:p:python-313:r:using--index] +file_filter = using/index.po trans.pt_BR = using/index.po -source_file = ../../pot/using/index.pot +source_file = ../build/gettext/using/index.pot type = PO minimum_perc = 0 resource_name = using--index replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:using--ios] -file_filter = .//LC_MESSAGES/using/ios.po +[o:python-doc:p:python-313:r:using--ios] +file_filter = using/ios.po trans.pt_BR = using/ios.po -source_file = ../../pot/using/ios.pot +source_file = ../build/gettext/using/ios.pot type = PO minimum_perc = 0 resource_name = using--ios replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:using--mac] -file_filter = .//LC_MESSAGES/using/mac.po +[o:python-doc:p:python-313:r:using--mac] +file_filter = using/mac.po trans.pt_BR = using/mac.po -source_file = ../../pot/using/mac.pot +source_file = ../build/gettext/using/mac.pot type = PO minimum_perc = 0 resource_name = using--mac replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:using--unix] -file_filter = .//LC_MESSAGES/using/unix.po +[o:python-doc:p:python-313:r:using--unix] +file_filter = using/unix.po trans.pt_BR = using/unix.po -source_file = ../../pot/using/unix.pot +source_file = ../build/gettext/using/unix.pot type = PO minimum_perc = 0 resource_name = using--unix replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:using--windows] -file_filter = .//LC_MESSAGES/using/windows.po +[o:python-doc:p:python-313:r:using--windows] +file_filter = using/windows.po trans.pt_BR = using/windows.po -source_file = ../../pot/using/windows.pot +source_file = ../build/gettext/using/windows.pot type = PO minimum_perc = 0 resource_name = using--windows replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--2_0] -file_filter = .//LC_MESSAGES/whatsnew/2.0.po +[o:python-doc:p:python-313:r:whatsnew--2_0] +file_filter = whatsnew/2.0.po trans.pt_BR = whatsnew/2.0.po -source_file = ../../pot/whatsnew/2.0.pot +source_file = ../build/gettext/whatsnew/2.0.pot type = PO minimum_perc = 0 resource_name = whatsnew--2_0 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--2_1] -file_filter = .//LC_MESSAGES/whatsnew/2.1.po +[o:python-doc:p:python-313:r:whatsnew--2_1] +file_filter = whatsnew/2.1.po trans.pt_BR = whatsnew/2.1.po -source_file = ../../pot/whatsnew/2.1.pot +source_file = ../build/gettext/whatsnew/2.1.pot type = PO minimum_perc = 0 resource_name = whatsnew--2_1 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--2_2] -file_filter = .//LC_MESSAGES/whatsnew/2.2.po +[o:python-doc:p:python-313:r:whatsnew--2_2] +file_filter = whatsnew/2.2.po trans.pt_BR = whatsnew/2.2.po -source_file = ../../pot/whatsnew/2.2.pot +source_file = ../build/gettext/whatsnew/2.2.pot type = PO minimum_perc = 0 resource_name = whatsnew--2_2 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--2_3] -file_filter = .//LC_MESSAGES/whatsnew/2.3.po +[o:python-doc:p:python-313:r:whatsnew--2_3] +file_filter = whatsnew/2.3.po trans.pt_BR = whatsnew/2.3.po -source_file = ../../pot/whatsnew/2.3.pot +source_file = ../build/gettext/whatsnew/2.3.pot type = PO minimum_perc = 0 resource_name = whatsnew--2_3 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--2_4] -file_filter = .//LC_MESSAGES/whatsnew/2.4.po +[o:python-doc:p:python-313:r:whatsnew--2_4] +file_filter = whatsnew/2.4.po trans.pt_BR = whatsnew/2.4.po -source_file = ../../pot/whatsnew/2.4.pot +source_file = ../build/gettext/whatsnew/2.4.pot type = PO minimum_perc = 0 resource_name = whatsnew--2_4 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--2_5] -file_filter = .//LC_MESSAGES/whatsnew/2.5.po +[o:python-doc:p:python-313:r:whatsnew--2_5] +file_filter = whatsnew/2.5.po trans.pt_BR = whatsnew/2.5.po -source_file = ../../pot/whatsnew/2.5.pot +source_file = ../build/gettext/whatsnew/2.5.pot type = PO minimum_perc = 0 resource_name = whatsnew--2_5 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--2_6] -file_filter = .//LC_MESSAGES/whatsnew/2.6.po +[o:python-doc:p:python-313:r:whatsnew--2_6] +file_filter = whatsnew/2.6.po trans.pt_BR = whatsnew/2.6.po -source_file = ../../pot/whatsnew/2.6.pot +source_file = ../build/gettext/whatsnew/2.6.pot type = PO minimum_perc = 0 resource_name = whatsnew--2_6 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--2_7] -file_filter = .//LC_MESSAGES/whatsnew/2.7.po +[o:python-doc:p:python-313:r:whatsnew--2_7] +file_filter = whatsnew/2.7.po trans.pt_BR = whatsnew/2.7.po -source_file = ../../pot/whatsnew/2.7.pot +source_file = ../build/gettext/whatsnew/2.7.pot type = PO minimum_perc = 0 resource_name = whatsnew--2_7 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--3_0] -file_filter = .//LC_MESSAGES/whatsnew/3.0.po +[o:python-doc:p:python-313:r:whatsnew--3_0] +file_filter = whatsnew/3.0.po trans.pt_BR = whatsnew/3.0.po -source_file = ../../pot/whatsnew/3.0.pot +source_file = ../build/gettext/whatsnew/3.0.pot type = PO minimum_perc = 0 resource_name = whatsnew--3_0 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--3_1] -file_filter = .//LC_MESSAGES/whatsnew/3.1.po +[o:python-doc:p:python-313:r:whatsnew--3_1] +file_filter = whatsnew/3.1.po trans.pt_BR = whatsnew/3.1.po -source_file = ../../pot/whatsnew/3.1.pot +source_file = ../build/gettext/whatsnew/3.1.pot type = PO minimum_perc = 0 resource_name = whatsnew--3_1 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--3_10] -file_filter = .//LC_MESSAGES/whatsnew/3.10.po +[o:python-doc:p:python-313:r:whatsnew--3_10] +file_filter = whatsnew/3.10.po trans.pt_BR = whatsnew/3.10.po -source_file = ../../pot/whatsnew/3.10.pot +source_file = ../build/gettext/whatsnew/3.10.pot type = PO minimum_perc = 0 resource_name = whatsnew--3_10 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--3_11] -file_filter = .//LC_MESSAGES/whatsnew/3.11.po +[o:python-doc:p:python-313:r:whatsnew--3_11] +file_filter = whatsnew/3.11.po trans.pt_BR = whatsnew/3.11.po -source_file = ../../pot/whatsnew/3.11.pot +source_file = ../build/gettext/whatsnew/3.11.pot type = PO minimum_perc = 0 resource_name = whatsnew--3_11 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--3_12] -file_filter = .//LC_MESSAGES/whatsnew/3.12.po +[o:python-doc:p:python-313:r:whatsnew--3_12] +file_filter = whatsnew/3.12.po trans.pt_BR = whatsnew/3.12.po -source_file = ../../pot/whatsnew/3.12.pot +source_file = ../build/gettext/whatsnew/3.12.pot type = PO minimum_perc = 0 resource_name = whatsnew--3_12 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--3_13] -file_filter = .//LC_MESSAGES/whatsnew/3.13.po +[o:python-doc:p:python-313:r:whatsnew--3_13] +file_filter = whatsnew/3.13.po trans.pt_BR = whatsnew/3.13.po -source_file = ../../pot/whatsnew/3.13.pot +source_file = ../build/gettext/whatsnew/3.13.pot type = PO minimum_perc = 0 resource_name = whatsnew--3_13 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--3_2] -file_filter = .//LC_MESSAGES/whatsnew/3.2.po +[o:python-doc:p:python-313:r:whatsnew--3_2] +file_filter = whatsnew/3.2.po trans.pt_BR = whatsnew/3.2.po -source_file = ../../pot/whatsnew/3.2.pot +source_file = ../build/gettext/whatsnew/3.2.pot type = PO minimum_perc = 0 resource_name = whatsnew--3_2 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--3_3] -file_filter = .//LC_MESSAGES/whatsnew/3.3.po +[o:python-doc:p:python-313:r:whatsnew--3_3] +file_filter = whatsnew/3.3.po trans.pt_BR = whatsnew/3.3.po -source_file = ../../pot/whatsnew/3.3.pot +source_file = ../build/gettext/whatsnew/3.3.pot type = PO minimum_perc = 0 resource_name = whatsnew--3_3 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--3_4] -file_filter = .//LC_MESSAGES/whatsnew/3.4.po +[o:python-doc:p:python-313:r:whatsnew--3_4] +file_filter = whatsnew/3.4.po trans.pt_BR = whatsnew/3.4.po -source_file = ../../pot/whatsnew/3.4.pot +source_file = ../build/gettext/whatsnew/3.4.pot type = PO minimum_perc = 0 resource_name = whatsnew--3_4 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--3_5] -file_filter = .//LC_MESSAGES/whatsnew/3.5.po +[o:python-doc:p:python-313:r:whatsnew--3_5] +file_filter = whatsnew/3.5.po trans.pt_BR = whatsnew/3.5.po -source_file = ../../pot/whatsnew/3.5.pot +source_file = ../build/gettext/whatsnew/3.5.pot type = PO minimum_perc = 0 resource_name = whatsnew--3_5 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--3_6] -file_filter = .//LC_MESSAGES/whatsnew/3.6.po +[o:python-doc:p:python-313:r:whatsnew--3_6] +file_filter = whatsnew/3.6.po trans.pt_BR = whatsnew/3.6.po -source_file = ../../pot/whatsnew/3.6.pot +source_file = ../build/gettext/whatsnew/3.6.pot type = PO minimum_perc = 0 resource_name = whatsnew--3_6 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--3_7] -file_filter = .//LC_MESSAGES/whatsnew/3.7.po +[o:python-doc:p:python-313:r:whatsnew--3_7] +file_filter = whatsnew/3.7.po trans.pt_BR = whatsnew/3.7.po -source_file = ../../pot/whatsnew/3.7.pot +source_file = ../build/gettext/whatsnew/3.7.pot type = PO minimum_perc = 0 resource_name = whatsnew--3_7 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--3_8] -file_filter = .//LC_MESSAGES/whatsnew/3.8.po +[o:python-doc:p:python-313:r:whatsnew--3_8] +file_filter = whatsnew/3.8.po trans.pt_BR = whatsnew/3.8.po -source_file = ../../pot/whatsnew/3.8.pot +source_file = ../build/gettext/whatsnew/3.8.pot type = PO minimum_perc = 0 resource_name = whatsnew--3_8 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--3_9] -file_filter = .//LC_MESSAGES/whatsnew/3.9.po +[o:python-doc:p:python-313:r:whatsnew--3_9] +file_filter = whatsnew/3.9.po trans.pt_BR = whatsnew/3.9.po -source_file = ../../pot/whatsnew/3.9.pot +source_file = ../build/gettext/whatsnew/3.9.pot type = PO minimum_perc = 0 resource_name = whatsnew--3_9 replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--changelog] -file_filter = .//LC_MESSAGES/whatsnew/changelog.po +[o:python-doc:p:python-313:r:whatsnew--changelog] +file_filter = whatsnew/changelog.po trans.pt_BR = whatsnew/changelog.po -source_file = ../../pot/whatsnew/changelog.pot +source_file = ../build/gettext/whatsnew/changelog.pot type = PO minimum_perc = 0 resource_name = whatsnew--changelog replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:whatsnew--index] -file_filter = .//LC_MESSAGES/whatsnew/index.po +[o:python-doc:p:python-313:r:whatsnew--index] +file_filter = whatsnew/index.po trans.pt_BR = whatsnew/index.po -source_file = ../../pot/whatsnew/index.pot +source_file = ../build/gettext/whatsnew/index.pot type = PO minimum_perc = 0 resource_name = whatsnew--index diff --git a/Makefile b/Makefile deleted file mode 100644 index c38ca5b79..000000000 --- a/Makefile +++ /dev/null @@ -1,260 +0,0 @@ -# -# Makefile for Brazilian Portuguese Python Documentation -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# -# based on: https://github.com/python/python-docs-fr/blob/3.8/Makefile -# - -################# -# Configuration - -# Read environment variables from file to keep this clean move version -# changes elsewhere -include .env - -# Force the use of Bash -SHELL=/bin/bash - -# Time of starting this run -NOW := $(shell date +'%Y%m%-d-%H%M%Z') - -# Force realpath, not relative one -override CPYTHON_DIR := $(shell realpath $(CPYTHON_DIR)) - -override LOGS_DIR := $(shell realpath $(LOGS_DIR)) - -override VENV_DIR := $(shell realpath $(VENV_DIR)) -# -################# - -.PHONY: build clean help htmlview lint merge pot pull push setup spell tx-config tx-install venv - -help: - @echo "Please use 'make ' where is one of:" - @echo " build Build an local version in html; deps: 'setup'" - @echo " push Commit and push translations; no deps" - @echo " pull Download translations from Transifex; deps: 'tx-config'" - @echo " tx-config Regenerate Transifex config; deps: 'pot' and 'tx-install'" - @echo " tx-install Install Transifex CLI client; deps: no deps" - @echo " pot Regenerate POT files from sources; deps: 'setup'" - @echo " htmlview View docs in a web browser; deps: build" - @echo " spell Check spelling, storing output in $(POSPELL_TMP_DIR)" - @echo " lint Do some linting in PO file's Sphinx syntax. deps: 'venv'" - @echo " merge Merge $(BRANCH) branch's .po files into older branches" - @echo " Defaults overwrite in: $(BUGFIXBRANCH)" - @echo " and NOT overwrite in: $(OLDERBRANCHES)" - @echo " clean Do some house cleaning" - @echo "" - - -# build: build the documentation using the translation files currently available -# at the moment. For most up-to-date docs, run "tx-config" and "pull" -# before this. If passing SPHINXERRORHANDLING='', warnings will not be -# treated as errors, which is good to skip simple Sphinx syntax mistakes. -build: setup - @mkdir -p "$(CPYTHON_DIR)/$(LOCALE_DIR)/$(LANGUAGE)/LC_MESSAGES/" - @cp --parents *.po **/*.po "$(CPYTHON_DIR)/$(LOCALE_DIR)/$(LANGUAGE)/LC_MESSAGES/" - @echo "Building Python $(BRANCH) Documentation in $(LANGUAGE) ..." - @mkdir -p "$(LOGS_DIR)/build" - @$(MAKE) -C $(CPYTHON_DIR)/Doc/ \ - PYTHON=$(PYTHON) \ - SPHINXERRORHANDLING=$(SPHINXERRORHANDLING) \ - SPHINXOPTS="--keep-going \ - -D gettext_compact=0 \ - -D language=$(LANGUAGE) \ - -D latex_engine=xelatex \ - -D latex_elements.inputenc= \ - -D latex_elements.fontenc=" \ - html \ - 2> >(tee -a $(LOGS_DIR)/build/err-$(NOW).txt >&2) - - -# push: Commit and push translation files and Transifex config file to repo. -# First it git-adds tracked file that doesn't exclusively match changes -# in POT-Creation-Date header field. Then it git-adds untracked PO files -# that might have been created in the update process, and the Transifex -# configuration. Finally, only commit and push only if any file was -# git-added (staged); otherwise, it does nothing. -# The MSG variable has a default commit message, but one can override it -# e.g. make push MSG='my message' -push: - @git diff -I'^"POT-Creation-Date: ' --numstat *.po **/*.po | cut -f3 | xargs -r git add - @git add $(shell git ls-files -o *.po **/*.po) .tx/config - @git diff-index --cached --quiet HEAD || \ - { git commit -m "Update translations from Transifex" && git push; } - - -# pull: Download translations files from Transifex, and apply line wrapping. -# For downloading new translation files, first run "tx-config" target -# to update the translation file mapping. -pull: tx-config - @"$(TX_CLI_DIR)/tx" pull -l $(LANGUAGE) -t -f --use-git-timestamps - @"$(VENV_DIR)/bin/powrap" --quiet *.po **/*.po - - -# tx-config: Generate a new Transifex configuration file by reading -# the pot files generated by 'pot' target. The file is -# created in $(LOCALE_DIR)/.tx/config, and then is tweaked -# to fit the language's needs and then placed in .tx/config -# at the project's root directory. -tx-config: TRANSIFEX_PROJECT := python-newest -tx-config: pot tx-install - @cd $(CPYTHON_DIR)/$(LOCALE_DIR); \ - rm -rf .tx; \ - "$(VENV_DIR)/bin/sphinx-intl" create-txconfig; \ - "$(VENV_DIR)/bin/sphinx-intl" update-txconfig-resources \ - --transifex-organization-name python-doc \ - --transifex-project-name=$(TRANSIFEX_PROJECT) \ - --locale-dir . \ - --pot-dir pot - @mkdir -p .tx - @sed $(CPYTHON_DIR)/$(LOCALE_DIR)/.tx/config \ - -e "s|^file_filter *= .*|&\nx&|;" \ - -e "s|= pot/|= ../../pot/|" \ - > .tx/config - @sed -i .tx/config \ - -e "s|^xfile_filter *= .//LC_MESSAGES/|trans.$(LANGUAGE) = |;" - - -# tx-install: Install Transifex CLI client if not installed yet. Installs -# the TX_CLI_VERSION version into TX_CLI_DIR directory. If -# TX_CLI_VERSION not provided, uses the latest one. -tx-install: URL := https://raw.githubusercontent.com/transifex/cli/master/install.sh -tx-install: - @if [ ! -x "$(TX_CLI_DIR)/tx" ]; then \ - echo "Transifex TX Client not found, installing ..."; \ - cd "$(TX_CLI_DIR)"; \ - if [ -n "v$(TX_CLI_VERSION)" ]; then \ - curl -s -o- $(URL) | bash -s -- v$(TX_CLI_VERSION); \ - else \ - curl -s -o- $(URL) | bash; \ - fi; \ - fi - - -# pot: After running "setup" target, run sphinx-build's gettext target -# to generate .pot files under $(CPYTHON_DIR)/Doc/locales/pot. -pot: setup - @$(MAKE) -C $(CPYTHON_DIR)/Doc/ \ - VENVDIR=./venv \ - PYTHON=$(PYTHON) \ - ALLSPHINXOPTS='-E \ - -b gettext \ - -D gettext_compact=0 \ - -d build/.doctrees \ - . $(CPYTHON_DIR)/$(LOCALE_DIR)/pot' \ - build - - -# setup: After running "venv" target, prepare that virtual environment with -# a local clone of cpython repository and the translation files. -# If the directories exists, only update the cpython repository and -# the translation files copy which could have new/updated files. -setup: CPYTHON_URL := https://github.com/python/cpython -setup: venv - @if [ -z "$(BRANCH)" ]; then \ - echo "BRANCH is empty, should have git-branch. Unable to continue."; \ - exit 1; \ - fi - - @if ! [ -d "$(CPYTHON_DIR)" ]; then \ - echo "CPython repo not found; cloning ..."; \ - git clone --depth 1 --no-single-branch $(CPYTHON_URL) $(CPYTHON_DIR); \ - git -C "$(CPYTHON_DIR)" checkout $(BRANCH); \ - else \ - echo "CPython repo found; updating ..."; \ - git -C "$(CPYTHON_DIR)" checkout $(BRANCH); \ - git -C "$(CPYTHON_DIR)" pull --rebase; \ - fi - - @echo "Creating CPython's documentation virtual environment ..." - @if [ ! -d "$(CPYTHON_DIR)/Doc/venv" ]; then \ - $(MAKE) -C "$(CPYTHON_DIR)/Doc" PYTHON=$(PYTHON) venv; \ - fi - - -# venv: create a virtual environment which will be used by almost every -# other target of this script. CPython specific packages are installed -# in there specific venv (see 'setup' target). -venv: - @if [ ! -d "$(VENV_DIR)" ]; then \ - echo "Setting up language team's virtual environment ..."; \ - "$(PYTHON)" -m venv "$(VENV_DIR)"; \ - "$(VENV_DIR)/bin/python" -m pip install --upgrade pip; \ - mkdir -p "$(LOGS_DIR)"; \ - "$(VENV_DIR)/bin/pip" install --requirement requirements.txt \ - --log "$(LOGS_DIR)/venv-$(NOW).txt"; \ - fi - - -# htmlview: View the documentation locally, using Makefile's "htmlview" target. -# Run "build" before using this target. -htmlview: build - @INDEX="$(CPYTHON_DIR)/Doc/build/html/index.html"; \ - "$(PYTHON)" -c "import os, webbrowser; \ - webbrowser.open('file://' + os.path.realpath('$$INDEX'))" - - -# spell: run spell checking tool in all po files listed in SRCS variable, -# storing the output in text files DESTS for proofreading. The -# DESTS target run the spellchecking, while the typos.txt target -# gather all reported issues in one file, sorted without redundancy. -SRCS := $(wildcard *.po **/*.po) -DESTS := $(addprefix $(LOGS_DIR)/pospell-$(NOW)/out/,$(patsubst %.po,%.txt,$(SRCS))) -spell: venv $(DESTS) $(LOGS_DIR)/pospell-$(NOW)/all.txt - -$(LOGS_DIR)/pospell-$(NOW)/out/%.txt: %.po dict - @echo "Checking $< ..." - @mkdir -p $(@D) - @$(VENV_DIR)/bin/pospell -l "$(LANGUAGE)" -p dict $< > $@ || true - -$(LOGS_DIR)/pospell-$(NOW)/all.txt: - @echo "Gathering all typos in $(LOGS_DIR)/pospell-$(NOW)/all.txt ..." - @cut -d: -f3- $(DESTS) | sort -u > $@ - - -# merge: Merge translations from BRANCH (Python version currently aim of -# translation) into each branch listed by BUGFIXBRANCH and -# OLDERBRANCHES (branches of older Python versions) so that older -# versions of the Python Docs try make at least some use of the latest -# translations. OLDERBRANCHES has '--no-overwrite' flag so it does not -# overwrite translated strings, preserving history. -# After merging, only commit and push only if any file was git-added -# (staged) to the target branch; otherwise, it does nothing. -merge: venv $(BUGFIXBRANCH) $(OLDERBRANCHES) - -$(OLDERBRANCHES): OVERWRITEFLAG = --no-overwrite -$(BUGFIXBRANCH) $(OLDERBRANCHES): - @if [[ $@ == $(BRANCH) ]]; then \ - echo "Ignoring attempt to pomerge '$(BRANCH)' into itself."; \ - else \ - echo "Merging translations from $(BRANCH) branch into $@ ..."; \ - $(VENV_DIR)/bin/pomerge --from-files *.po **/*.po; \ - git checkout $@; \ - $(VENV_DIR)/bin/pomerge $(OVERWRITEFLAG) --to-files *.po **/*.po; \ - $(VENV_DIR)/bin/powrap --modified *.po **/*.po; \ - git add -u; \ - if [ -n "$(git diff --name-only --cached)" ]; then \ - git commit -m $(MSG); \ - git push; \ - else \ - echo 'Nothing to commit'; \ - fi; \ - git checkout $(BRANCH); \ - fi - - -# lint: Report reStructuredText syntax errors in the translation files -lint: venv - @mkdir -p "$(LOGS_DIR)" - @$(VENV_DIR)/bin/sphinx-lint *.po **/*.po |& \ - tee -a $(LOGS_DIR)/lint-$(NOW).txt || true - @echo "Lint output stored in $(LOGS_DIR)/lint-$(NOW).txt" - - -# clean: remove all .mo files and the venv directory that may exist and could -# have been created by the actions in other targets of this script. -clean: - rm -rf "$(VENV_DIR)" - rm -rf "$(CPYTHON_DIR)/$(LOCALE_DIR)" - [ -d "$(CPYTHON_DIR)" ] && $(MAKE) -C "$(CPYTHON_DIR)/Doc" clean-venv diff --git a/README.md b/README.md index 42d958ca3..ac3654ceb 100644 --- a/README.md +++ b/README.md @@ -1,68 +1,19 @@ # Brazilian Portuguese Translation of the Python Documentation -[![Update](https://github.com/python/python-docs-pt-br/actions/workflows/update.yml/badge.svg)](https://github.com/python/python-docs-pt-br/actions/workflows/update.yml) -[![Check](https://github.com/python/python-docs-pt-br/actions/workflows/check.yml/badge.svg)](https://github.com/python/python-docs-pt-br/actions/workflows/check.yml) +[![Workflow status badge][workflow_badge]][workflow_url] +[![Translation statistics badge][stats_badge]][transifex_url] -Check our [wiki](https://github.com/python/python-docs-pt-br/wiki) for more guidance on translating +Translation files for [Python 3.13 docs][docs_url]. -## Translation priorities +See list of incomplete translations in the [potodo.md][potodo] file. -The following modules we consider as priority targets, hence should -receive more attention than other modules/pages (0 has higher priority -than 2). Please helps assure they are a 100% translated. +See [main][main] branch for scripts, docs, license and more info. -### Priority 0 (probably they are completed) - - bugs - - glossary - - library/functions - - library/index - - library/intro - - library/constants - - library/stdtypes - - library/exceptions - - sphinx - - tutorial/ (all!) +[main]: https://github.com/python/python-docs-pt-br/tree/main +[potodo]: potodo.md?plain=1 +[docs_url]: https://docs.python.org/pt-br/3.13/ +[workflow_badge]: https://github.com/python/python-docs-pt-br/workflows/python-313/badge.svg +[workflow_url]: https://github.com/python/python-docs-pt-br/actions?workflow=python-313 +[stats_badge]: https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fgithub.com%2Fpython%2Fpython-docs-pt-br%2Fraw%2F3.13%2Fstats.json&query=completion&label=pt_BR +[transifex_url]: https://app.transifex.com/python-doc/python-newest/ -### Priority 1 - - reference/ (all) - - faq/ (all) - -### Priority 2 - - library/turtle - - library/sys - - library/argparse - - library/random - - library/statistics - - library/urllib.request - - library/smtplib - - library/datetime - - library/zlib - - library/gzip - - library/lzma - - library/tarfile - - library/timeit - - library/profile - - library/doctest - - library/unittest - - library/ (except the ones mentioned above) - -## Documentation Contribution Agreement - -NOTE REGARDING THE LICENSE FOR TRANSLATIONS: Python's documentation is -maintained using a global network of volunteers. By posting this -project on Transifex, GitHub, and other public places, and inviting -you to participate, we are proposing an agreement that you will -provide your improvements to Python's documentation or the translation -of Python's documentation for the PSF's use under the CC0 license -(available at -https://creativecommons.org/publicdomain/zero/1.0/legalcode). In -return, you may publicly claim credit for the portion of the -translation you contributed and if your translation is accepted by the -PSF, you may (but are not required to) submit a patch including an -appropriate annotation in the Misc/ACKS or TRANSLATORS file. Although -nothing in this Documentation Contribution Agreement obligates the PSF -to incorporate your textual contribution, your participation in the -Python community is welcomed and appreciated. - -You signify acceptance of this agreement by submitting your work to -the PSF for inclusion in the documentation. diff --git a/about.po b/about.po index a32aefd89..8652418c0 100644 --- a/about.po +++ b/about.po @@ -1,46 +1,43 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# André Girol , 2021 -# Amanda Savluchinske , 2021 -# Adorilson Bezerra , 2021 -# Clara Matos, 2022 -# Rafael Fontenelle , 2022 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Rafael Fontenelle , 2022\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../about.rst:3 -msgid "About these documents" -msgstr "Sobre esses documentos" +msgid "About this documentation" +msgstr "Sobre esta documentação" #: ../../about.rst:6 msgid "" -"These documents are generated from `reStructuredText`_ sources by `Sphinx`_, " -"a document processor specifically written for the Python documentation." +"Python's documentation is generated from `reStructuredText`_ sources using " +"`Sphinx`_, a documentation generator originally created for Python and now " +"maintained as an independent project." msgstr "" -"Esses documentos são gerados a partir de `reStructuredText`_ pelo `Sphinx`_, " -"um processador de documentos especificamente escrito para documentação " -"Python." +"A documentação do Python é gerada a partir de fontes `reStructuredText`_ " +"usando `Sphinx`_, um gerador de documentação criado originalmente para " +"Python e agora mantido como um projeto independente." -#: ../../about.rst:15 +#: ../../about.rst:16 msgid "" "Development of the documentation and its toolchain is an entirely volunteer " "effort, just like Python itself. If you want to contribute, please take a " @@ -52,19 +49,19 @@ msgstr "" "dê uma olhada na página :ref:`reporting-bugs` para informações sobre como " "fazer. Novos voluntários são sempre bem-vindos!" -#: ../../about.rst:20 +#: ../../about.rst:21 msgid "Many thanks go to:" msgstr "Agradecimentos especiais para:" -#: ../../about.rst:22 +#: ../../about.rst:23 msgid "" "Fred L. Drake, Jr., the creator of the original Python documentation toolset " -"and writer of much of the content;" +"and author of much of the content;" msgstr "" "Fred L. Drake, Jr., o criador do primeiro conjunto de ferramentas para " -"documentar Python e escritor de boa parte do conteúdo;" +"documentar Python e autor de boa parte do conteúdo;" -#: ../../about.rst:24 +#: ../../about.rst:25 msgid "" "the `Docutils `_ project for creating " "reStructuredText and the Docutils suite;" @@ -72,7 +69,7 @@ msgstr "" "O projeto `Docutils `_ por criar " "reStructuredText e o pacote Docutils;" -#: ../../about.rst:26 +#: ../../about.rst:27 msgid "" "Fredrik Lundh for his Alternative Python Reference project from which Sphinx " "got many good ideas." @@ -80,11 +77,11 @@ msgstr "" "Fredrik Lundh, pelo seu projeto de referência alternativa em Python, do qual " "Sphinx pegou muitas boas ideias." -#: ../../about.rst:31 -msgid "Contributors to the Python Documentation" -msgstr "Contribuidores da Documentação Python" +#: ../../about.rst:32 +msgid "Contributors to the Python documentation" +msgstr "Contribuidores da documentação do Python" -#: ../../about.rst:33 +#: ../../about.rst:34 msgid "" "Many people have contributed to the Python language, the Python standard " "library, and the Python documentation. See :source:`Misc/ACKS` in the " @@ -94,7 +91,7 @@ msgstr "" "padrão e sua documentação. Veja :source:`Misc/ACKS` na distribuição do " "código do Python para ver uma lista parcial de contribuidores." -#: ../../about.rst:37 +#: ../../about.rst:38 msgid "" "It is only with the input and contributions of the Python community that " "Python has such wonderful documentation -- Thank You!" diff --git a/bugs.po b/bugs.po index 9b9080f13..c9dac0c20 100644 --- a/bugs.po +++ b/bugs.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Felipefpl, 2021 -# Ana Carolina Gomes, 2023 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -46,9 +43,9 @@ msgid "" "Python as it streamlines the process and involves less people. Learn how to :" "ref:`contribute `." msgstr "" -"Às vezes, pode ser mais rápido consertar os bugs você mesmo e contribuir " -"com patches para o Python uma vez que isso agiliza o processo e envolve " -"menos pessoas. Veja aqui como :ref:`contribuir `." +"Às vezes, pode ser mais rápido consertar os bugs você mesmo e contribuir com " +"patches para o Python uma vez que isso agiliza o processo e envolve menos " +"pessoas. Veja aqui como :ref:`contribuir `." #: ../../bugs.rst:16 msgid "Documentation bugs" diff --git a/c-api/abstract.po b/c-api/abstract.po index 3a5bad996..91ccb756e 100644 --- a/c-api/abstract.po +++ b/c-api/abstract.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Felipefpl, 2021 -# Rafael Fontenelle , 2022 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Rafael Fontenelle , 2022\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -35,11 +34,10 @@ msgid "" "or all sequence types). When used on object types for which they do not " "apply, they will raise a Python exception." msgstr "" -"As funções neste capítulo interagem com os objetos do Python " -"independentemente do tipo deles ou com classes amplas dos tipos de objetos " -"(por exemplo, todos os tipos numéricos ou todos os tipos de sequência). " -"Quando usado nos tipos de objetos pros quais eles não se aplicam eles " -"levantarão uma exceção no Python." +"As funções neste capítulo interagem com objetos Python independentemente do " +"seu tipo, ou com classes amplas de tipos de objetos (por exemplo, todos os " +"tipos numéricos ou todos os tipos de sequência). Quando usadas em tipos de " +"objetos para os quais não se aplicam, elas irão levantar uma exceção Python." #: ../../c-api/abstract.rst:14 msgid "" @@ -48,7 +46,6 @@ msgid "" "`PyList_New`, but whose items have not been set to some non-\\ ``NULL`` " "value yet." msgstr "" -"Não é possível usar estas funções em objetos que não estão apropriadamente " -"inicializados, tal como uma objeto de lista que foi criado por :c:func:" -"`PyList_New`, mas cujos itens não foram definidos como algum valor não " -"``NULL`` ainda." +"Não é possível usar essas funções em objetos que não foram inicializados " +"corretamente, como um objeto de lista criado por :c:func:`PyList_New`, mas " +"cujos itens ainda não foram definidos para algum valor diferente de ``NULL``." diff --git a/c-api/allocation.po b/c-api/allocation.po index 3d978e286..e062649de 100644 --- a/c-api/allocation.po +++ b/c-api/allocation.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Welington Carlos , 2021 -# Felipefpl, 2021 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-03-21 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -32,17 +30,13 @@ msgstr "Alocando Objetos na Pilha" #: ../../c-api/allocation.rst:17 msgid "" "Initialize a newly allocated object *op* with its type and initial " -"reference. Returns the initialized object. If *type* indicates that the " -"object participates in the cyclic garbage detector, it is added to the " -"detector's set of observed objects. Other fields of the object are not " -"affected." +"reference. Returns the initialized object. Other fields of the object are " +"not affected." msgstr "" "Inicializa um objeto *op* recém-alocado com seu tipo e referência inicial. " -"Retorna o objeto inicializado. Se o *type* indica que o objeto participa no " -"detector de lixo cíclico ele é adicionado ao grupo do detector de objetos " -"observados. Outros campos do objeto não são afetados." +"Retorna o objeto inicializado. Outros campos do objeto não são afetados." -#: ../../c-api/allocation.rst:26 +#: ../../c-api/allocation.rst:24 msgid "" "This does everything :c:func:`PyObject_Init` does, and also initializes the " "length information for a variable-size object." @@ -50,7 +44,7 @@ msgstr "" "Isto faz tudo que o :c:func:`PyObject_Init` faz e também inicializa a " "informação de comprimento para um objeto de tamanho variável." -#: ../../c-api/allocation.rst:32 +#: ../../c-api/allocation.rst:30 msgid "" "Allocate a new Python object using the C structure type *TYPE* and the " "Python type object *typeobj* (``PyTypeObject*``). Fields not defined by the " @@ -66,7 +60,17 @@ msgstr "" "uma). O tamanho da alocação de memória é determinado do campo :c:member:" "`~PyTypeObject.tp_basicsize` do objeto tipo." -#: ../../c-api/allocation.rst:43 +#: ../../c-api/allocation.rst:38 +msgid "" +"Note that this function is unsuitable if *typeobj* has :c:macro:" +"`Py_TPFLAGS_HAVE_GC` set. For such objects, use :c:func:`PyObject_GC_New` " +"instead." +msgstr "" +"Note que esta função não é adequada se *typeobj* tiver :c:macro:" +"`Py_TPFLAGS_HAVE_GC` definido. Para tais objetos, use :c:func:" +"`PyObject_GC_New` em vez disso." + +#: ../../c-api/allocation.rst:45 msgid "" "Allocate a new Python object using the C structure type *TYPE* and the " "Python type object *typeobj* (``PyTypeObject*``). Fields not defined by the " @@ -88,7 +92,17 @@ msgstr "" "campos dentro da mesma alocação diminuindo o numero de alocações, melhorando " "a eficiência do gerenciamento de memória." -#: ../../c-api/allocation.rst:57 +#: ../../c-api/allocation.rst:56 +msgid "" +"Note that this function is unsuitable if *typeobj* has :c:macro:" +"`Py_TPFLAGS_HAVE_GC` set. For such objects, use :c:func:`PyObject_GC_NewVar` " +"instead." +msgstr "" +"Note que esta função não é adequada se *typeobj* tiver :c:macro:" +"`Py_TPFLAGS_HAVE_GC` definido. Para tais objetos, use :c:func:" +"`PyObject_GC_NewVar` em vez disso." + +#: ../../c-api/allocation.rst:63 msgid "" "Releases memory allocated to an object using :c:macro:`PyObject_New` or :c:" "macro:`PyObject_NewVar`. This is normally called from the :c:member:" @@ -102,7 +116,7 @@ msgstr "" "do objeto não devem ser acessados após esta chamada como a memória não é " "mais um objeto Python válido." -#: ../../c-api/allocation.rst:66 +#: ../../c-api/allocation.rst:72 msgid "" "Object which is visible in Python as ``None``. This should only be accessed " "using the :c:macro:`Py_None` macro, which evaluates to a pointer to this " @@ -112,10 +126,10 @@ msgstr "" "usando a macro :c:macro:`Py_None`, o qual avalia como um ponteiro para este " "objeto." -#: ../../c-api/allocation.rst:73 +#: ../../c-api/allocation.rst:79 msgid ":c:func:`PyModule_Create`" msgstr ":c:func:`PyModule_Create`" -#: ../../c-api/allocation.rst:74 +#: ../../c-api/allocation.rst:80 msgid "To allocate and create extension modules." msgstr "Para alocar e criar módulos de extensão." diff --git a/c-api/apiabiversion.po b/c-api/apiabiversion.po index 49af33910..fbcde9a02 100644 --- a/c-api/apiabiversion.po +++ b/c-api/apiabiversion.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Welington Carlos , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Felipefpl, 2021 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/arg.po b/c-api/arg.po index d34800172..db4bfb7d5 100644 --- a/c-api/arg.po +++ b/c-api/arg.po @@ -1,35 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2021 -# Welington Carlos , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Adson Rodrigues , 2021 -# Rafael Marques , 2021 -# Caio Carvalho , 2021 -# Welliton Malta , 2023 -# Julia Rizza , 2023 -# Italo Penaforte , 2024 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-04-25 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -39,13 +29,13 @@ msgstr "Análise de argumentos e construção de valores" #: ../../c-api/arg.rst:8 msgid "" -"These functions are useful when creating your own extensions functions and " +"These functions are useful when creating your own extension functions and " "methods. Additional information and examples are available in :ref:" "`extending-index`." msgstr "" -"Essas funções são úteis ao criar funções e métodos das suas extensões. " -"Informações adicionais e exemplos estão disponíveis em :ref:`extending-" -"index`." +"Essas funções são úteis ao criar suas próprias funções e métodos de " +"extensão. Informações adicionais e exemplos estão disponíveis em :ref:" +"`extending-index`." #: ../../c-api/arg.rst:12 msgid "" @@ -155,7 +145,7 @@ msgid "" "corresponding Python object, and shares the lifetime of this object. You " "won't have to release any memory yourself." msgstr "" -"Outros formatos usam um :class:`str` ou um :term:`objeto byte ou similar` " +"Outros formatos usam um :class:`str` ou um :term:`objeto bytes ou similar` " "somente leitura, como :class:`bytes`, e fornecem um ponteiro ``const char " "*`` para seu buffer. Nesse caso, o buffer é \"emprestado\": ele é gerenciado " "pelo objeto Python correspondente e compartilha o tempo de vida desse " @@ -212,9 +202,9 @@ msgid "" "strings, it is preferable to use the ``O&`` format with :c:func:" "`PyUnicode_FSConverter` as *converter*." msgstr "" -"Esse formato não aceita :term:`objetos byte ou similar `. " -"Se você quer aceitar caminhos de arquivos do sistema e convertê-los para " -"strings em C, é preferível que use o formato ``O&`` com :c:func:" +"Esse formato não aceita :term:`objetos bytes ou similar `. Se você quer aceitar caminhos de sistema de arquivos e convertê-" +"los para strings em C, é preferível que use o formato ``O&`` com :c:func:" "`PyUnicode_FSConverter` como *conversor*." #: ../../c-api/arg.rst:96 @@ -227,9 +217,7 @@ msgstr "" #: ../../c-api/arg.rst:100 msgid "``s*`` (:class:`str` or :term:`bytes-like object`) [Py_buffer]" -msgstr "" -"``s*`` (:class:`str` ou :term:`objeto byte ou similar `) " -"[Py_buffer]" +msgstr "``s*`` (:class:`str` ou :term:`objeto bytes ou similar`) [Py_buffer]" #: ../../c-api/arg.rst:101 msgid "" @@ -238,7 +226,7 @@ msgid "" "resulting C string may contain embedded NUL bytes. Unicode objects are " "converted to C strings using ``'utf-8'`` encoding." msgstr "" -"Esse formato aceita tanto objetos Unicode quanto objetos byte ou similar. " +"Esse formato aceita tanto objetos Unicode quanto objetos bytes ou similar. " "Preenche uma estrutura :c:type:`Py_buffer` fornecida pelo chamador. Nesse " "caso, a string em C resultante pode conter bytes NUL embutidos. Objetos " "Unicode são convertidos para strings em C usando codificação ``'utf-8'``." @@ -248,7 +236,7 @@ msgid "" "``s#`` (:class:`str`, read-only :term:`bytes-like object`) [const char \\*, :" "c:type:`Py_ssize_t`]" msgstr "" -"``s#`` (:class:`str`, :term:`objeto byte ou similar ` " +"``s#`` (:class:`str`, :term:`objeto bytes ou similar ` " "somente leitura) [const char \\*, :c:type:`Py_ssize_t`]" #: ../../c-api/arg.rst:107 @@ -265,7 +253,7 @@ msgstr "" "pode conter bytes nulos embutidos. Objetos Unicode são convertidos para " "strings em C usando codificação ``'utf-8'``." -#: ../../c-api/arg.rst:113 ../../c-api/arg.rst:581 +#: ../../c-api/arg.rst:113 ../../c-api/arg.rst:593 msgid "``z`` (:class:`str` or ``None``) [const char \\*]" msgstr "``z`` (:class:`str` ou ``None``) [const char \\*]" @@ -281,8 +269,8 @@ msgstr "" msgid "" "``z*`` (:class:`str`, :term:`bytes-like object` or ``None``) [Py_buffer]" msgstr "" -"``z*`` (:class:`str`, :term:`objeto byte ou similar ` ou " -"``None``) [Py_buffer]" +"``z*`` (:class:`str`, :term:`objeto bytes ou similar` ou ``None``) " +"[Py_buffer]" #: ../../c-api/arg.rst:118 msgid "" @@ -297,8 +285,8 @@ msgid "" "``z#`` (:class:`str`, read-only :term:`bytes-like object` or ``None``) " "[const char \\*, :c:type:`Py_ssize_t`]" msgstr "" -"``z#`` (:class:`str`, :term:`objeto byte ou similar ` " -"somente leitura ou ``None``) [const char \\*, :c:type:`Py_ssize_t`]" +"``z#`` (:class:`str`, :term:`objeto bytes ou similar` somente leitura ou " +"``None``) [const char \\*, :c:type:`Py_ssize_t`]" #: ../../c-api/arg.rst:122 msgid "" @@ -311,8 +299,7 @@ msgstr "" #: ../../c-api/arg.rst:125 msgid "``y`` (read-only :term:`bytes-like object`) [const char \\*]" msgstr "" -"``y`` (:term:`objeto byte ou similar ` somente leitura) " -"[const char \\*]" +"``y`` (:term:`objeto bytes ou similar` somente leitura) [const char \\*]" #: ../../c-api/arg.rst:126 msgid "" @@ -321,7 +308,7 @@ msgid "" "objects. The bytes buffer must not contain embedded null bytes; if it does, " "a :exc:`ValueError` exception is raised." msgstr "" -"Este formato converte um objeto byte ou similar para um ponteiro C para uma " +"Este formato converte um objeto bytes ou similar para um ponteiro C para uma " "string de caracteres :ref:`emprestada `; não aceita " "objetos Unicode. O buffer de bytes não pode conter bytes nulos embutidos; se " "isso ocorrer uma exceção :exc:`ValueError` será levantada." @@ -336,15 +323,14 @@ msgstr "" #: ../../c-api/arg.rst:136 msgid "``y*`` (:term:`bytes-like object`) [Py_buffer]" -msgstr "" -"``y*`` (:term:`objeto byte ou similar `) [Py_buffer]" +msgstr "``y*`` (:term:`objeto bytes ou similar`) [Py_buffer]" #: ../../c-api/arg.rst:137 msgid "" "This variant on ``s*`` doesn't accept Unicode objects, only bytes-like " "objects. **This is the recommended way to accept binary data.**" msgstr "" -"Esta variante em ``s*`` não aceita objetos unicode, apenas objetos byte ou " +"Esta variante em ``s*`` não aceita objetos unicode, apenas objetos bytes ou " "similar. **Esta é a maneira recomendada para aceitar dados binários.**" #: ../../c-api/arg.rst:141 @@ -352,15 +338,15 @@ msgid "" "``y#`` (read-only :term:`bytes-like object`) [const char \\*, :c:type:" "`Py_ssize_t`]" msgstr "" -"``y#`` (:term:`objeto byte ou similar ` somente leitura) " -"[const char \\*, :c:type:`Py_ssize_t`]" +"``y#`` (:term:`objeto bytes ou similar` somente leitura) [const char \\*, :c:" +"type:`Py_ssize_t`]" #: ../../c-api/arg.rst:142 msgid "" "This variant on ``s#`` doesn't accept Unicode objects, only bytes-like " "objects." msgstr "" -"Esta variação de ``s#`` não aceita objetos Unicode, apenas objetos byte ou " +"Esta variação de ``s#`` não aceita objetos Unicode, apenas objetos bytes ou " "similar." #: ../../c-api/arg.rst:145 @@ -410,8 +396,7 @@ msgstr "" #: ../../c-api/arg.rst:160 msgid "``w*`` (read-write :term:`bytes-like object`) [Py_buffer]" msgstr "" -"``w*`` (:term:`objeto byte ou similar ` de leitura e " -"escrita) [Py_buffer]" +"``w*`` (:term:`objeto bytes ou similar` de leitura e escrita) [Py_buffer]" #: ../../c-api/arg.rst:161 msgid "" @@ -483,7 +468,7 @@ msgid "" "recoding them. Instead, the implementation assumes that the byte string " "object uses the encoding passed in as parameter." msgstr "" -"O mesmo que ``es``, exceto que os objetos strings de bytes são passados ​​sem " +"O mesmo que ``es``, exceto que os objetos strings de bytes são passados sem " "os recodificar. Em vez disso, a implementação presume que o objeto string de " "bytes usa a codificação passada como parâmetro." @@ -583,7 +568,7 @@ msgid "" "recoding them. Instead, the implementation assumes that the byte string " "object uses the encoding passed in as parameter." msgstr "" -"O mesmo que ``es#``, exceto que os objetos strings de bytes são passados ​​sem " +"O mesmo que ``es#``, exceto que os objetos strings de bytes são passados sem " "que sejam recodificados. Em vez disso, a implementação presume que o objeto " "string de bytes usa a codificação passada como parâmetro." @@ -600,42 +585,69 @@ msgid "Numbers" msgstr "Números" #: ../../c-api/arg.rst:232 +msgid "" +"These formats allow representing Python numbers or single characters as C " +"numbers. Formats that require :class:`int`, :class:`float` or :class:" +"`complex` can also use the corresponding special methods :meth:`~object." +"__index__`, :meth:`~object.__float__` or :meth:`~object.__complex__` to " +"convert the Python object to the required type." +msgstr "" +"Esses formatos permitem representar números Python ou caracteres únicos como " +"números C. Formatos que exigem :class:`int`, :class:`float` ou :class:" +"`complex` também podem usar os métodos especiais correspondentes :meth:" +"`~object.__index__`, :meth:`~object.__float__` ou :meth:`~object." +"__complex__` para converter o objeto Python para o tipo necessário." + +#: ../../c-api/arg.rst:238 +msgid "" +"For signed integer formats, :exc:`OverflowError` is raised if the value is " +"out of range for the C type. For unsigned integer formats, no range checking " +"is done --- the most significant bits are silently truncated when the " +"receiving field is too small to receive the value." +msgstr "" +"Para formatos inteiros com sinal, :exc:`OverflowError` é levantada se o " +"valor estiver fora do intervalo para o tipo C. Para formatos inteiros não " +"assinados, nenhuma verificação de intervalo é feita --- os bits mais " +"significativos são silenciosamente truncados quando o campo de recebimento é " +"muito pequeno para receber o valor." + +#: ../../c-api/arg.rst:244 msgid "``b`` (:class:`int`) [unsigned char]" msgstr "``b`` (:class:`int`) [unsigned char]" -#: ../../c-api/arg.rst:233 +#: ../../c-api/arg.rst:245 msgid "" -"Convert a nonnegative Python integer to an unsigned tiny int, stored in a C :" -"c:expr:`unsigned char`." +"Convert a nonnegative Python integer to an unsigned tiny integer, stored in " +"a C :c:expr:`unsigned char`." msgstr "" "Converte um inteiro Python não negativo em um inteiro pequeno sem sinal " -"(unsigned tiny int), armazenado em um :c:expr:`unsigned char` do C." +"(unsigned tiny integer), armazenado em um :c:expr:`unsigned char` do C." -#: ../../c-api/arg.rst:236 ../../c-api/arg.rst:615 +#: ../../c-api/arg.rst:248 ../../c-api/arg.rst:627 msgid "``B`` (:class:`int`) [unsigned char]" msgstr "``B`` (:class:`int`) [unsigned char]" -#: ../../c-api/arg.rst:237 +#: ../../c-api/arg.rst:249 msgid "" -"Convert a Python integer to a tiny int without overflow checking, stored in " -"a C :c:expr:`unsigned char`." +"Convert a Python integer to a tiny integer without overflow checking, stored " +"in a C :c:expr:`unsigned char`." msgstr "" -"Converte um inteiro Python para um inteiro pequeno (tiny int) sem " +"Converte um inteiro Python para um inteiro pequeno (tiny integer) sem " "verificação de estouro, armazenado em um :c:expr:`unsigned char` do C." -#: ../../c-api/arg.rst:240 ../../c-api/arg.rst:609 +#: ../../c-api/arg.rst:252 ../../c-api/arg.rst:621 msgid "``h`` (:class:`int`) [short int]" msgstr "``h`` (:class:`int`) [short int]" -#: ../../c-api/arg.rst:241 +#: ../../c-api/arg.rst:253 msgid "Convert a Python integer to a C :c:expr:`short int`." msgstr "Converte um inteiro Python para um :c:expr:`short int` do C." -#: ../../c-api/arg.rst:243 ../../c-api/arg.rst:618 +#: ../../c-api/arg.rst:255 ../../c-api/arg.rst:630 msgid "``H`` (:class:`int`) [unsigned short int]" msgstr "``H`` (:class:`int`) [unsigned short int]" -#: ../../c-api/arg.rst:244 +#: ../../c-api/arg.rst:256 msgid "" "Convert a Python integer to a C :c:expr:`unsigned short int`, without " "overflow checking." @@ -643,19 +655,19 @@ msgstr "" "Converte um inteiro Python para um :c:expr:`unsigned short int` do C, sem " "verificação de estouro." -#: ../../c-api/arg.rst:247 ../../c-api/arg.rst:603 +#: ../../c-api/arg.rst:259 ../../c-api/arg.rst:615 msgid "``i`` (:class:`int`) [int]" msgstr "``i`` (:class:`int`) [int]" -#: ../../c-api/arg.rst:248 +#: ../../c-api/arg.rst:260 msgid "Convert a Python integer to a plain C :c:expr:`int`." msgstr "Converte um inteiro Python para um :c:expr:`int` simples do C." -#: ../../c-api/arg.rst:250 ../../c-api/arg.rst:621 +#: ../../c-api/arg.rst:262 ../../c-api/arg.rst:633 msgid "``I`` (:class:`int`) [unsigned int]" msgstr "``I`` (:class:`int`) [unsigned int]" -#: ../../c-api/arg.rst:251 +#: ../../c-api/arg.rst:263 msgid "" "Convert a Python integer to a C :c:expr:`unsigned int`, without overflow " "checking." @@ -663,19 +675,19 @@ msgstr "" "Converte um inteiro Python para um :c:expr:`unsigned int` do C, sem " "verificação de estouro." -#: ../../c-api/arg.rst:254 ../../c-api/arg.rst:612 +#: ../../c-api/arg.rst:266 ../../c-api/arg.rst:624 msgid "``l`` (:class:`int`) [long int]" msgstr "``l`` (:class:`int`) [long int]" -#: ../../c-api/arg.rst:255 +#: ../../c-api/arg.rst:267 msgid "Convert a Python integer to a C :c:expr:`long int`." msgstr "Converte um inteiro Python para um :c:expr:`long int` do C." -#: ../../c-api/arg.rst:257 ../../c-api/arg.rst:624 +#: ../../c-api/arg.rst:269 ../../c-api/arg.rst:636 msgid "``k`` (:class:`int`) [unsigned long]" msgstr "``k`` (:class:`int`) [unsigned long]" -#: ../../c-api/arg.rst:258 +#: ../../c-api/arg.rst:270 msgid "" "Convert a Python integer to a C :c:expr:`unsigned long` without overflow " "checking." @@ -683,19 +695,19 @@ msgstr "" "Converte um inteiro Python para um :c:expr:`unsigned long` do C sem " "verificação de estouro." -#: ../../c-api/arg.rst:261 ../../c-api/arg.rst:627 +#: ../../c-api/arg.rst:273 ../../c-api/arg.rst:639 msgid "``L`` (:class:`int`) [long long]" msgstr "``L`` (:class:`int`) [longo longo]" -#: ../../c-api/arg.rst:262 +#: ../../c-api/arg.rst:274 msgid "Convert a Python integer to a C :c:expr:`long long`." msgstr "Converte um inteiro Python para um :c:expr:`long long` do C." -#: ../../c-api/arg.rst:264 ../../c-api/arg.rst:630 +#: ../../c-api/arg.rst:276 ../../c-api/arg.rst:644 msgid "``K`` (:class:`int`) [unsigned long long]" msgstr "``K`` (:class:`int`) [unsigned long long]" -#: ../../c-api/arg.rst:265 +#: ../../c-api/arg.rst:277 msgid "" "Convert a Python integer to a C :c:expr:`unsigned long long` without " "overflow checking." @@ -703,19 +715,19 @@ msgstr "" "Converte um inteiro Python para um :c:expr:`unsigned long long` do C sem " "verificação de estouro." -#: ../../c-api/arg.rst:268 ../../c-api/arg.rst:633 +#: ../../c-api/arg.rst:280 ../../c-api/arg.rst:647 msgid "``n`` (:class:`int`) [:c:type:`Py_ssize_t`]" msgstr "``n`` (:class:`int`) [:c:type:`Py_ssize_t`]" -#: ../../c-api/arg.rst:269 +#: ../../c-api/arg.rst:281 msgid "Convert a Python integer to a C :c:type:`Py_ssize_t`." msgstr "Converte um inteiro Python para um :c:type:`Py_ssize_t` do C." -#: ../../c-api/arg.rst:271 +#: ../../c-api/arg.rst:283 msgid "``c`` (:class:`bytes` or :class:`bytearray` of length 1) [char]" msgstr "``c`` (:class:`bytes` ou :class:`bytearray` de comprimento 1) [char]" -#: ../../c-api/arg.rst:272 +#: ../../c-api/arg.rst:284 msgid "" "Convert a Python byte, represented as a :class:`bytes` or :class:`bytearray` " "object of length 1, to a C :c:expr:`char`." @@ -723,15 +735,15 @@ msgstr "" "Converte um byte Python, representado com um objeto :class:`byte` ou :class:" "`bytearray` de comprimento 1, para um :c:expr:`char` do C." -#: ../../c-api/arg.rst:275 +#: ../../c-api/arg.rst:287 msgid "Allow :class:`bytearray` objects." msgstr "Permite objetos :class:`bytearray`." -#: ../../c-api/arg.rst:278 ../../c-api/arg.rst:640 +#: ../../c-api/arg.rst:290 ../../c-api/arg.rst:654 msgid "``C`` (:class:`str` of length 1) [int]" msgstr "``C`` (:class:`str` de comprimento 1) [int]" -#: ../../c-api/arg.rst:279 +#: ../../c-api/arg.rst:291 msgid "" "Convert a Python character, represented as a :class:`str` object of length " "1, to a C :c:expr:`int`." @@ -739,42 +751,42 @@ msgstr "" "Converte um caractere Python, representado como uma :class:`str` objeto de " "comprimento 1, para um :c:expr:`int` do C" -#: ../../c-api/arg.rst:282 ../../c-api/arg.rst:647 +#: ../../c-api/arg.rst:294 ../../c-api/arg.rst:661 msgid "``f`` (:class:`float`) [float]" msgstr "``f``` (:class:`float`) [float]" -#: ../../c-api/arg.rst:283 +#: ../../c-api/arg.rst:295 msgid "Convert a Python floating-point number to a C :c:expr:`float`." msgstr "" "Converte um número de ponto flutuante Python para um :c:expr:`float` do C." -#: ../../c-api/arg.rst:285 ../../c-api/arg.rst:644 +#: ../../c-api/arg.rst:297 ../../c-api/arg.rst:658 msgid "``d`` (:class:`float`) [double]" msgstr "``d`` (:class:`float`) [double]" -#: ../../c-api/arg.rst:286 +#: ../../c-api/arg.rst:298 msgid "Convert a Python floating-point number to a C :c:expr:`double`." msgstr "" "Converte um número de ponto flutuante Python para um :c:expr:`double` do C." -#: ../../c-api/arg.rst:288 +#: ../../c-api/arg.rst:300 msgid "``D`` (:class:`complex`) [Py_complex]" msgstr "``D`` (:class:`complex`) [Py_complex]" -#: ../../c-api/arg.rst:289 +#: ../../c-api/arg.rst:301 msgid "Convert a Python complex number to a C :c:type:`Py_complex` structure." msgstr "" "Converte um número complexo Python para uma estrutura C :c:type:`Py_complex`" -#: ../../c-api/arg.rst:292 +#: ../../c-api/arg.rst:304 msgid "Other objects" msgstr "Outros objetos" -#: ../../c-api/arg.rst:294 ../../c-api/arg.rst:653 +#: ../../c-api/arg.rst:306 ../../c-api/arg.rst:667 msgid "``O`` (object) [PyObject \\*]" msgstr "``O`` (objeto) [PyObject\\*]" -#: ../../c-api/arg.rst:295 +#: ../../c-api/arg.rst:307 msgid "" "Store a Python object (without any conversion) in a C object pointer. The C " "program thus receives the actual object that was passed. A new :term:" @@ -786,11 +798,11 @@ msgstr "" "`referência forte` ao objeto não é criado (isto é sua contagem de " "referências não é aumentada). O ponteiro armazenado não é ``NULL``." -#: ../../c-api/arg.rst:301 +#: ../../c-api/arg.rst:313 msgid "``O!`` (object) [*typeobject*, PyObject \\*]" msgstr "``O!`` (objeto) [*typeobject*, PyObject \\*]" -#: ../../c-api/arg.rst:302 +#: ../../c-api/arg.rst:314 msgid "" "Store a Python object in a C object pointer. This is similar to ``O``, but " "takes two C arguments: the first is the address of a Python type object, the " @@ -804,11 +816,11 @@ msgstr "" "`PyObject*`) no qual o ponteiro do objeto está armazenado. Se o objeto " "Python não tiver o tipo necessário, :exc:`TypeError` é levantada." -#: ../../c-api/arg.rst:310 ../../c-api/arg.rst:671 -msgid "``O&`` (object) [*converter*, *anything*]" -msgstr "``O&`` (objeto) [*converter*, *anything*]" +#: ../../c-api/arg.rst:322 +msgid "``O&`` (object) [*converter*, *address*]" +msgstr "``O&`` (objeto) [*converter*, *address*]" -#: ../../c-api/arg.rst:311 +#: ../../c-api/arg.rst:323 msgid "" "Convert a Python object to a C variable through a *converter* function. " "This takes two arguments: the first is a function, the second is the address " @@ -820,7 +832,11 @@ msgstr "" "endereço da variável C (de tipo arbitrário), convertendo para :c:expr:" "`void*`. A função *converter* por sua vez, é chamada da seguinte maneira::" -#: ../../c-api/arg.rst:318 +#: ../../c-api/arg.rst:328 +msgid "status = converter(object, address);" +msgstr "status = converter(object, address);" + +#: ../../c-api/arg.rst:330 msgid "" "where *object* is the Python object to be converted and *address* is the :c:" "expr:`void*` argument that was passed to the ``PyArg_Parse*`` function. The " @@ -835,29 +851,37 @@ msgstr "" "conversão falhar. Quando a conversão falha, a função *converter* deve " "levantar uma exceção e deixar o conteúdo de *address* inalterado." -#: ../../c-api/arg.rst:324 +#: ../../c-api/arg.rst:339 msgid "" -"If the *converter* returns ``Py_CLEANUP_SUPPORTED``, it may get called a " -"second time if the argument parsing eventually fails, giving the converter a " -"chance to release any memory that it had already allocated. In this second " -"call, the *object* parameter will be ``NULL``; *address* will have the same " -"value as in the original call." +"If the *converter* returns :c:macro:`!Py_CLEANUP_SUPPORTED`, it may get " +"called a second time if the argument parsing eventually fails, giving the " +"converter a chance to release any memory that it had already allocated. In " +"this second call, the *object* parameter will be ``NULL``; *address* will " +"have the same value as in the original call." msgstr "" -"Se o *converter* retornar ``Py_CLEANUP_SUPPORTED``, ele poderá ser chamado " -"uma segunda vez se a análise do argumento eventualmente falhar, dando ao " -"conversor a chance de liberar qualquer memória que já havia alocado. Nesta " -"segunda chamada, o parâmetro *object* será ``NULL``; *address* terá o mesmo " -"valor que na chamada original." +"Se o *converter* retornar :c:macro:`!Py_CLEANUP_SUPPORTED`, ele poderá ser " +"chamado uma segunda vez se a análise do argumento eventualmente falhar, " +"dando ao conversor a chance de liberar qualquer memória que já havia " +"alocado. Nesta segunda chamada, o parâmetro *object* será ``NULL``; " +"*address* terá o mesmo valor que na chamada original." -#: ../../c-api/arg.rst:330 -msgid "``Py_CLEANUP_SUPPORTED`` was added." -msgstr "109 ``Py_CLEANUP_SUPPORTED`` foi adicionado." +#: ../../c-api/arg.rst:345 +msgid "" +"Examples of converters: :c:func:`PyUnicode_FSConverter` and :c:func:" +"`PyUnicode_FSDecoder`." +msgstr "" +"Exemplos de conversores: :c:func:`PyUnicode_FSConverter` e :c:func:" +"`PyUnicode_FSDecoder`." -#: ../../c-api/arg.rst:333 +#: ../../c-api/arg.rst:348 +msgid ":c:macro:`!Py_CLEANUP_SUPPORTED` was added." +msgstr ":c:macro:`!Py_CLEANUP_SUPPORTED` foi adicionado." + +#: ../../c-api/arg.rst:351 msgid "``p`` (:class:`bool`) [int]" msgstr "``p`` (:class:`bool`) [int]" -#: ../../c-api/arg.rst:334 +#: ../../c-api/arg.rst:352 msgid "" "Tests the value passed in for truth (a boolean **p**\\ redicate) and " "converts the result to its equivalent C true/false integer value. Sets the " @@ -871,11 +895,11 @@ msgstr "" "Isso aceita qualquer valor válido do Python. Veja :ref:`truth` para obter " "mais informações sobre como o Python testa valores para a verdade." -#: ../../c-api/arg.rst:342 ../../c-api/arg.rst:677 +#: ../../c-api/arg.rst:360 ../../c-api/arg.rst:691 msgid "``(items)`` (:class:`tuple`) [*matching-items*]" msgstr "``(items)`` (:class:`tuple`) [*matching-items*]" -#: ../../c-api/arg.rst:343 +#: ../../c-api/arg.rst:361 msgid "" "The object must be a Python sequence whose length is the number of format " "units in *items*. The C arguments must correspond to the individual format " @@ -886,22 +910,7 @@ msgstr "" "unidades de formato individuais em *items*. As unidades de formato para " "sequências podem ser aninhadas." -#: ../../c-api/arg.rst:347 -msgid "" -"It is possible to pass \"long\" integers (integers whose value exceeds the " -"platform's :c:macro:`LONG_MAX`) however no proper range checking is done --- " -"the most significant bits are silently truncated when the receiving field is " -"too small to receive the value (actually, the semantics are inherited from " -"downcasts in C --- your mileage may vary)." -msgstr "" -"É possível passar inteiros \"long\" (inteiros em que o valor excede a " -"constante da plataforma :c:macro:`LONG_MAX`) contudo nenhuma checagem de " -"intervalo é propriamente feita -- os bits mais significativos são " -"silenciosamente truncados quando o campo de recebimento é muito pequeno para " -"receber o valor (na verdade, a semântica é herdada de downcasts no C -- seu " -"raio de ação pode variar)." - -#: ../../c-api/arg.rst:353 +#: ../../c-api/arg.rst:365 msgid "" "A few other characters have a meaning in a format string. These may not " "occur inside nested parentheses. They are:" @@ -909,11 +918,11 @@ msgstr "" "Alguns outros caracteres possuem significados na string de formatação. Isso " "pode não ocorrer dentro de parênteses aninhados. Eles são:" -#: ../../c-api/arg.rst:356 +#: ../../c-api/arg.rst:368 msgid "``|``" msgstr "``|``" -#: ../../c-api/arg.rst:357 +#: ../../c-api/arg.rst:369 msgid "" "Indicates that the remaining arguments in the Python argument list are " "optional. The C variables corresponding to optional arguments should be " @@ -927,11 +936,11 @@ msgstr "" "é especificado, :c:func:`PyArg_ParseTuple` não toca no conteúdo da(s) " "variável(eis) C correspondente(s)." -#: ../../c-api/arg.rst:363 +#: ../../c-api/arg.rst:375 msgid "``$``" msgstr "``$``" -#: ../../c-api/arg.rst:364 +#: ../../c-api/arg.rst:376 msgid "" ":c:func:`PyArg_ParseTupleAndKeywords` only: Indicates that the remaining " "arguments in the Python argument list are keyword-only. Currently, all " @@ -944,11 +953,11 @@ msgstr "" "então ``|`` deve sempre ser especificado antes de ``$`` na string de " "formatação." -#: ../../c-api/arg.rst:372 +#: ../../c-api/arg.rst:384 msgid "``:``" msgstr "``:``" -#: ../../c-api/arg.rst:373 +#: ../../c-api/arg.rst:385 msgid "" "The list of format units ends here; the string after the colon is used as " "the function name in error messages (the \"associated value\" of the " @@ -958,11 +967,11 @@ msgstr "" "usada como o nome da função nas mensagens de erro (o \"valor associado\" da " "exceção que :c:func:`PyArg_ParseTuple` levanta)." -#: ../../c-api/arg.rst:377 +#: ../../c-api/arg.rst:389 msgid "``;``" msgstr "``;``" -#: ../../c-api/arg.rst:378 +#: ../../c-api/arg.rst:390 msgid "" "The list of format units ends here; the string after the semicolon is used " "as the error message *instead* of the default error message. ``:`` and ``;" @@ -972,7 +981,7 @@ msgstr "" "vírgula é usada como a mensagem de erro *ao invés* da mensagem de erro " "padrão. ``:`` e ``;`` se excluem mutuamente." -#: ../../c-api/arg.rst:382 +#: ../../c-api/arg.rst:394 msgid "" "Note that any Python object references which are provided to the caller are " "*borrowed* references; do not release them (i.e. do not decrement their " @@ -982,7 +991,7 @@ msgstr "" "chamador são referências *emprestadas*; não libera-as (isto é, não " "decremente a contagem de referências delas)!" -#: ../../c-api/arg.rst:386 +#: ../../c-api/arg.rst:398 msgid "" "Additional arguments passed to these functions must be addresses of " "variables whose type is determined by the format string; these are used to " @@ -998,7 +1007,7 @@ msgstr "" "parâmetros são usados como valores de entrada; eles devem concordar com o " "que é especificado para a unidade de formatação correspondente nesse caso." -#: ../../c-api/arg.rst:392 +#: ../../c-api/arg.rst:404 msgid "" "For the conversion to succeed, the *arg* object must match the format and " "the format must be exhausted. On success, the ``PyArg_Parse*`` functions " @@ -1015,11 +1024,11 @@ msgstr "" "correspondentes àquela unidade e às unidades de formatação seguintes são " "deixadas intocadas." -#: ../../c-api/arg.rst:401 +#: ../../c-api/arg.rst:413 msgid "API Functions" msgstr "Funções da API" -#: ../../c-api/arg.rst:405 +#: ../../c-api/arg.rst:417 msgid "" "Parse the parameters of a function that takes only positional parameters " "into local variables. Returns true on success; on failure, it returns false " @@ -1029,7 +1038,7 @@ msgstr "" "em variáveis locais. Retorna verdadeiro em caso de sucesso; em caso de " "falha, retorna falso e levanta a exceção apropriada." -#: ../../c-api/arg.rst:412 +#: ../../c-api/arg.rst:424 msgid "" "Identical to :c:func:`PyArg_ParseTuple`, except that it accepts a va_list " "rather than a variable number of arguments." @@ -1037,7 +1046,7 @@ msgstr "" "Idêntico a :c:func:`PyArg_ParseTuple`, exceto que aceita uma va_list ao " "invés de um número variável de argumentos." -#: ../../c-api/arg.rst:418 +#: ../../c-api/arg.rst:430 msgid "" "Parse the parameters of a function that takes both positional and keyword " "parameters into local variables. The *keywords* argument is a ``NULL``-" @@ -1054,7 +1063,7 @@ msgstr "" "`. Retorna verdadeiro em caso de sucesso; em caso " "de falha, retorna falso e levanta a exceção apropriada." -#: ../../c-api/arg.rst:429 +#: ../../c-api/arg.rst:441 msgid "" "The *keywords* parameter declaration is :c:expr:`char * const *` in C and :c:" "expr:`const char * const *` in C++. This can be overridden with the :c:macro:" @@ -1064,7 +1073,7 @@ msgstr "" "expr:`const char * const *` em C++. Isso pode ser substituído com a macro :" "c:macro:`PY_CXX_CONST`." -#: ../../c-api/arg.rst:433 +#: ../../c-api/arg.rst:445 msgid "" "Added support for :ref:`positional-only parameters `." @@ -1072,7 +1081,7 @@ msgstr "" "Adicionado suporte para :ref:`positional-only parameters `." -#: ../../c-api/arg.rst:437 +#: ../../c-api/arg.rst:449 msgid "" "The *keywords* parameter has now type :c:expr:`char * const *` in C and :c:" "expr:`const char * const *` in C++, instead of :c:expr:`char **`. Added " @@ -1082,7 +1091,7 @@ msgstr "" "expr:`const char * const *` em C++, no lugar de :c:expr:`char **`. " "Adicionado suporte para nomes de parâmetros nomeados não-ASCII." -#: ../../c-api/arg.rst:446 +#: ../../c-api/arg.rst:458 msgid "" "Identical to :c:func:`PyArg_ParseTupleAndKeywords`, except that it accepts a " "va_list rather than a variable number of arguments." @@ -1090,7 +1099,7 @@ msgstr "" "Idêntico a :c:func:`PyArg_ParseTupleAndKeywords`, exceto que aceita uma " "va_list ao invés de um número variável de argumentos." -#: ../../c-api/arg.rst:452 +#: ../../c-api/arg.rst:464 msgid "" "Ensure that the keys in the keywords argument dictionary are strings. This " "is only needed if :c:func:`PyArg_ParseTupleAndKeywords` is not used, since " @@ -1100,7 +1109,7 @@ msgstr "" "strings. Isso só é necessário se :c:func:`PyArg_ParseTupleAndKeywords` não é " "usado, já que o último já faz essa checagem." -#: ../../c-api/arg.rst:461 +#: ../../c-api/arg.rst:473 msgid "" "Parse the parameter of a function that takes a single positional parameter " "into a local variable. Returns true on success; on failure, it returns " @@ -1110,11 +1119,35 @@ msgstr "" "o converte em uma variável local. Retorna verdadeiro em caso de sucesso; em " "caso de falha, retorna falso e levanta a exceção apropriada." -#: ../../c-api/arg.rst:465 +#: ../../c-api/arg.rst:477 msgid "Example::" msgstr "Exemplo::" -#: ../../c-api/arg.rst:481 +#: ../../c-api/arg.rst:479 +msgid "" +"// Function using METH_O calling convention\n" +"static PyObject*\n" +"my_function(PyObject *module, PyObject *arg)\n" +"{\n" +" int value;\n" +" if (!PyArg_Parse(arg, \"i:my_function\", &value)) {\n" +" return NULL;\n" +" }\n" +" // ... use value ...\n" +"}" +msgstr "" +"// Função usando a convenção de chamada ao método METH_O\n" +"static PyObject*\n" +"my_function(PyObject *module, PyObject *arg)\n" +"{\n" +" int value;\n" +" if (!PyArg_Parse(arg, \"i:my_function\", &value)) {\n" +" return NULL;\n" +" }\n" +" // ... usar valor ...\n" +"}" + +#: ../../c-api/arg.rst:493 msgid "" "A simpler form of parameter retrieval which does not use a format string to " "specify the types of the arguments. Functions which use this method to " @@ -1147,7 +1180,7 @@ msgstr "" "contiver o número incorreto de elementos; uma exceção será definida se " "houver uma falha." -#: ../../c-api/arg.rst:496 +#: ../../c-api/arg.rst:508 msgid "" "This is an example of the use of this function, taken from the sources for " "the :mod:`!_weakref` helper module for weak references::" @@ -1155,7 +1188,35 @@ msgstr "" "Este é um exemplo do uso dessa função, tirado das fontes do módulo auxiliar " "para referências fracas :mod:`!_weakref`::" -#: ../../c-api/arg.rst:512 +#: ../../c-api/arg.rst:511 +msgid "" +"static PyObject *\n" +"weakref_ref(PyObject *self, PyObject *args)\n" +"{\n" +" PyObject *object;\n" +" PyObject *callback = NULL;\n" +" PyObject *result = NULL;\n" +"\n" +" if (PyArg_UnpackTuple(args, \"ref\", 1, 2, &object, &callback)) {\n" +" result = PyWeakref_NewRef(object, callback);\n" +" }\n" +" return result;\n" +"}" +msgstr "" +"static PyObject *\n" +"weakref_ref(PyObject *self, PyObject *args)\n" +"{\n" +" PyObject *object;\n" +" PyObject *callback = NULL;\n" +" PyObject *result = NULL;\n" +"\n" +" if (PyArg_UnpackTuple(args, \"ref\", 1, 2, &object, &callback)) {\n" +" result = PyWeakref_NewRef(object, callback);\n" +" }\n" +" return result;\n" +"}" + +#: ../../c-api/arg.rst:524 msgid "" "The call to :c:func:`PyArg_UnpackTuple` in this example is entirely " "equivalent to this call to :c:func:`PyArg_ParseTuple`::" @@ -1163,7 +1224,11 @@ msgstr "" "A chamada à :c:func:`PyArg_UnpackTuple` neste exemplo é inteiramente " "equivalente à chamada para :c:func:`PyArg_ParseTuple`::" -#: ../../c-api/arg.rst:519 +#: ../../c-api/arg.rst:527 +msgid "PyArg_ParseTuple(args, \"O|O:ref\", &object, &callback)" +msgstr "PyArg_ParseTuple(args, \"O|O:ref\", &object, &callback)" + +#: ../../c-api/arg.rst:531 msgid "" "The value to be inserted, if any, before :c:expr:`char * const *` in the " "*keywords* parameter declaration of :c:func:`PyArg_ParseTupleAndKeywords` " @@ -1177,11 +1242,11 @@ msgstr "" "padrão, é vazio para C e ``const`` for C++ (:c:expr:`const char * const *`). " "Para substituir, defina o valor desejado antes de incluir :file:`Python.h`." -#: ../../c-api/arg.rst:533 +#: ../../c-api/arg.rst:545 msgid "Building values" msgstr "Construindo valores" -#: ../../c-api/arg.rst:537 +#: ../../c-api/arg.rst:549 msgid "" "Create a new value based on a format string similar to those accepted by the " "``PyArg_Parse*`` family of functions and a sequence of values. Returns the " @@ -1193,7 +1258,7 @@ msgstr "" "Retorna o valor ou ``NULL`` em caso de erro; uma exceção será levantada se " "``NULL`` for retornado." -#: ../../c-api/arg.rst:542 +#: ../../c-api/arg.rst:554 msgid "" ":c:func:`Py_BuildValue` does not always build a tuple. It builds a tuple " "only if its format string contains two or more format units. If the format " @@ -1209,7 +1274,7 @@ msgstr "" "retornar uma tupla de tamanho 0 ou um, use parênteses na string de " "formatação." -#: ../../c-api/arg.rst:548 +#: ../../c-api/arg.rst:560 msgid "" "When memory buffers are passed as parameters to supply data to build " "objects, as for the ``s`` and ``s#`` formats, the required data is copied. " @@ -1228,7 +1293,7 @@ msgstr "" "`free` para aquela memória uma vez que :c:func:`Py_BuildValue` tiver " "retornado." -#: ../../c-api/arg.rst:556 +#: ../../c-api/arg.rst:568 msgid "" "In the following description, the quoted form is the format unit; the entry " "in (round) parentheses is the Python object type that the format unit will " @@ -1240,7 +1305,7 @@ msgstr "" "de formatação irá retornar; e a entrada em colchetes [quadrado] é o tipo " "do(s) valor(es) C a ser(em) passado(s)." -#: ../../c-api/arg.rst:560 +#: ../../c-api/arg.rst:572 msgid "" "The characters space, tab, colon and comma are ignored in format strings " "(but not within format units such as ``s#``). This can be used to make long " @@ -1251,11 +1316,11 @@ msgstr "" "pode ser usado para tornar strings de formatação longas um pouco mais " "legíveis." -#: ../../c-api/arg.rst:564 +#: ../../c-api/arg.rst:576 msgid "``s`` (:class:`str` or ``None``) [const char \\*]" msgstr "``s`` (:class:`str` ou ``None``) [const char \\*]" -#: ../../c-api/arg.rst:565 +#: ../../c-api/arg.rst:577 msgid "" "Convert a null-terminated C string to a Python :class:`str` object using " "``'utf-8'`` encoding. If the C string pointer is ``NULL``, ``None`` is used." @@ -1264,13 +1329,13 @@ msgstr "" "usando codificação ``'utf-8'``. Se o ponteiro da string C é ``NULL``, " "``None`` é usado." -#: ../../c-api/arg.rst:568 +#: ../../c-api/arg.rst:580 msgid "" "``s#`` (:class:`str` or ``None``) [const char \\*, :c:type:`Py_ssize_t`]" msgstr "" "``s#`` (:class:`str` ou ``None``) [const char \\*, :c:type:`Py_ssize_t`]" -#: ../../c-api/arg.rst:569 +#: ../../c-api/arg.rst:581 msgid "" "Convert a C string and its length to a Python :class:`str` object using " "``'utf-8'`` encoding. If the C string pointer is ``NULL``, the length is " @@ -1280,11 +1345,11 @@ msgstr "" "usando a codificação ``'utf-8'``. Se o ponteiro da string C é ``NULL``, o " "comprimento é ignorado e ``None`` é retornado." -#: ../../c-api/arg.rst:573 +#: ../../c-api/arg.rst:585 msgid "``y`` (:class:`bytes`) [const char \\*]" msgstr "``y`` (:class:`bytes`) [const char \\*]" -#: ../../c-api/arg.rst:574 +#: ../../c-api/arg.rst:586 msgid "" "This converts a C string to a Python :class:`bytes` object. If the C string " "pointer is ``NULL``, ``None`` is returned." @@ -1292,11 +1357,11 @@ msgstr "" "Isso converte uma string C para um objeto Python :class:`bytes`. Se o " "ponteiro da string C é ``NULL``, ``None`` é retornado." -#: ../../c-api/arg.rst:577 +#: ../../c-api/arg.rst:589 msgid "``y#`` (:class:`bytes`) [const char \\*, :c:type:`Py_ssize_t`]" msgstr "``y#`` (:class:`bytes`) [const char \\*, :c:type:`Py_ssize_t`]" -#: ../../c-api/arg.rst:578 +#: ../../c-api/arg.rst:590 msgid "" "This converts a C string and its lengths to a Python object. If the C " "string pointer is ``NULL``, ``None`` is returned." @@ -1304,25 +1369,25 @@ msgstr "" "Isso converte uma string C e seu comprimento para um objeto Python. Se o " "ponteiro da string C é ``NULL``, ``None`` é retornado." -#: ../../c-api/arg.rst:582 ../../c-api/arg.rst:598 +#: ../../c-api/arg.rst:594 ../../c-api/arg.rst:610 msgid "Same as ``s``." msgstr "O mesmo de ``s``." -#: ../../c-api/arg.rst:584 +#: ../../c-api/arg.rst:596 msgid "" "``z#`` (:class:`str` or ``None``) [const char \\*, :c:type:`Py_ssize_t`]" msgstr "" "``z#`` (:class:`str` ou ``None``) [const char \\*, :c:type:`Py_ssize_t`]" -#: ../../c-api/arg.rst:585 ../../c-api/arg.rst:601 +#: ../../c-api/arg.rst:597 ../../c-api/arg.rst:613 msgid "Same as ``s#``." msgstr "O mesmo de ``s#``." -#: ../../c-api/arg.rst:587 +#: ../../c-api/arg.rst:599 msgid "``u`` (:class:`str`) [const wchar_t \\*]" msgstr "``u`` (:class:`str`) [const wchar_t \\*]" -#: ../../c-api/arg.rst:588 +#: ../../c-api/arg.rst:600 msgid "" "Convert a null-terminated :c:type:`wchar_t` buffer of Unicode (UTF-16 or " "UCS-4) data to a Python Unicode object. If the Unicode buffer pointer is " @@ -1332,11 +1397,11 @@ msgstr "" "(UTF-16 ou UCS-4) para um objeto Python Unicode. Se o ponteiro do buffer " "Unicode é ``NULL``, ``None`` é retornado." -#: ../../c-api/arg.rst:592 +#: ../../c-api/arg.rst:604 msgid "``u#`` (:class:`str`) [const wchar_t \\*, :c:type:`Py_ssize_t`]" msgstr "``u#`` (:class:`str`) [const wchar_t \\*, :c:type:`Py_ssize_t`]" -#: ../../c-api/arg.rst:593 +#: ../../c-api/arg.rst:605 msgid "" "Convert a Unicode (UTF-16 or UCS-4) data buffer and its length to a Python " "Unicode object. If the Unicode buffer pointer is ``NULL``, the length is " @@ -1346,76 +1411,76 @@ msgstr "" "um objeto Python Unicode. Se o ponteiro do buffer Unicode é ``NULL``, o " "comprimento é ignorado e ``None`` é retornado." -#: ../../c-api/arg.rst:597 +#: ../../c-api/arg.rst:609 msgid "``U`` (:class:`str` or ``None``) [const char \\*]" msgstr "``U`` (:class:`str` ou ``None``) [const char \\*]" -#: ../../c-api/arg.rst:600 +#: ../../c-api/arg.rst:612 msgid "" "``U#`` (:class:`str` or ``None``) [const char \\*, :c:type:`Py_ssize_t`]" msgstr "" "``U#`` (:class:`str` ou ``None``) [const char \\*, :c:type:`Py_ssize_t`]" -#: ../../c-api/arg.rst:604 +#: ../../c-api/arg.rst:616 msgid "Convert a plain C :c:expr:`int` to a Python integer object." msgstr "Converte um simples :c:expr:`int` do C em um objeto inteiro do Python." -#: ../../c-api/arg.rst:606 +#: ../../c-api/arg.rst:618 msgid "``b`` (:class:`int`) [char]" msgstr "``b`` (:class:`int`) [char]" -#: ../../c-api/arg.rst:607 +#: ../../c-api/arg.rst:619 msgid "Convert a plain C :c:expr:`char` to a Python integer object." msgstr "" "Converte um simples :c:expr:`char` do C em um objeto inteiro do Python." -#: ../../c-api/arg.rst:610 +#: ../../c-api/arg.rst:622 msgid "Convert a plain C :c:expr:`short int` to a Python integer object." msgstr "" "Converte um simples :c:expr:`short int` do C em um objeto inteiro do Python." -#: ../../c-api/arg.rst:613 +#: ../../c-api/arg.rst:625 msgid "Convert a C :c:expr:`long int` to a Python integer object." msgstr "Converte um :c:expr:`long int` do C em um objeto inteiro do Python." -#: ../../c-api/arg.rst:616 +#: ../../c-api/arg.rst:628 msgid "Convert a C :c:expr:`unsigned char` to a Python integer object." msgstr "" "Converte um :c:expr:`unsigned char` do C em um objeto inteiro do Python." -#: ../../c-api/arg.rst:619 +#: ../../c-api/arg.rst:631 msgid "Convert a C :c:expr:`unsigned short int` to a Python integer object." msgstr "" "Converte um :c:expr:`unsigned short int` do C em um objeto inteiro do Python." -#: ../../c-api/arg.rst:622 +#: ../../c-api/arg.rst:634 msgid "Convert a C :c:expr:`unsigned int` to a Python integer object." msgstr "" "Converte um :c:expr:`unsigned int` do C em um objeto inteiro do Python." -#: ../../c-api/arg.rst:625 +#: ../../c-api/arg.rst:637 msgid "Convert a C :c:expr:`unsigned long` to a Python integer object." msgstr "" "Converte um :c:expr:`unsigned long` do C em um objeto inteiro do Python." -#: ../../c-api/arg.rst:628 +#: ../../c-api/arg.rst:640 msgid "Convert a C :c:expr:`long long` to a Python integer object." msgstr "Converte um :c:expr:`long long` do C em um objeto inteiro do Python." -#: ../../c-api/arg.rst:631 +#: ../../c-api/arg.rst:645 msgid "Convert a C :c:expr:`unsigned long long` to a Python integer object." msgstr "" "Converte um :c:expr:`unsigned long long` do C em um objeto inteiro do Python." -#: ../../c-api/arg.rst:634 +#: ../../c-api/arg.rst:648 msgid "Convert a C :c:type:`Py_ssize_t` to a Python integer." msgstr "Converte um :c:type:`Py_ssize_t` do C em um objeto inteiro do Python." -#: ../../c-api/arg.rst:636 +#: ../../c-api/arg.rst:650 msgid "``c`` (:class:`bytes` of length 1) [char]" msgstr "``c`` (:class:`bytes` de comprimento 1) [char]" -#: ../../c-api/arg.rst:637 +#: ../../c-api/arg.rst:651 msgid "" "Convert a C :c:expr:`int` representing a byte to a Python :class:`bytes` " "object of length 1." @@ -1423,7 +1488,7 @@ msgstr "" "Converte um :c:expr:`int` representando um byte do C em um objeto :class:" "`bytes` de comprimento 1 do Python." -#: ../../c-api/arg.rst:641 +#: ../../c-api/arg.rst:655 msgid "" "Convert a C :c:expr:`int` representing a character to Python :class:`str` " "object of length 1." @@ -1431,27 +1496,27 @@ msgstr "" "Converte um :c:expr:`int` representando um caractere do C em um objeto :" "class:`str` de comprimento 1 do Python." -#: ../../c-api/arg.rst:645 +#: ../../c-api/arg.rst:659 msgid "Convert a C :c:expr:`double` to a Python floating-point number." msgstr "" "Converte um :c:expr:`double` do C em um número ponto flutuante do Python." -#: ../../c-api/arg.rst:648 +#: ../../c-api/arg.rst:662 msgid "Convert a C :c:expr:`float` to a Python floating-point number." msgstr "" "Converte um :c:expr:`float` do C em um número ponto flutuante do Python." -#: ../../c-api/arg.rst:650 +#: ../../c-api/arg.rst:664 msgid "``D`` (:class:`complex`) [Py_complex \\*]" msgstr "``D`` (:class:`complex`) [Py_complex \\*]" -#: ../../c-api/arg.rst:651 +#: ../../c-api/arg.rst:665 msgid "Convert a C :c:type:`Py_complex` structure to a Python complex number." msgstr "" "Converte uma estrutura :c:type:`Py_complex` do C em um número complexo do " "Python." -#: ../../c-api/arg.rst:654 +#: ../../c-api/arg.rst:668 msgid "" "Pass a Python object untouched but create a new :term:`strong reference` to " "it (i.e. its reference count is incremented by one). If the object passed in " @@ -1468,19 +1533,19 @@ msgstr "" "levantar uma exceção. Se nenhuma exceção foi levantada ainda, :exc:" "`SystemError` é definida." -#: ../../c-api/arg.rst:663 +#: ../../c-api/arg.rst:677 msgid "``S`` (object) [PyObject \\*]" msgstr "``S`` (objeto) [PyObject \\*]" -#: ../../c-api/arg.rst:664 +#: ../../c-api/arg.rst:678 msgid "Same as ``O``." msgstr "O mesmo que ``O``." -#: ../../c-api/arg.rst:666 +#: ../../c-api/arg.rst:680 msgid "``N`` (object) [PyObject \\*]" msgstr "``N`` (objeto) [PyObject \\*]" -#: ../../c-api/arg.rst:667 +#: ../../c-api/arg.rst:681 msgid "" "Same as ``O``, except it doesn't create a new :term:`strong reference`. " "Useful when the object is created by a call to an object constructor in the " @@ -1490,7 +1555,11 @@ msgstr "" "Útil quando o objeto é criado por uma chamada a um construtor de objeto na " "lista de argumento." -#: ../../c-api/arg.rst:672 +#: ../../c-api/arg.rst:685 +msgid "``O&`` (object) [*converter*, *anything*]" +msgstr "``O&`` (objeto) [*converter*, *anything*]" + +#: ../../c-api/arg.rst:686 msgid "" "Convert *anything* to a Python object through a *converter* function. The " "function is called with *anything* (which should be compatible with :c:expr:" @@ -1502,7 +1571,7 @@ msgstr "" "`void*`) como argumento e deve retornar um \"novo\" objeto Python, ou " "``NULL`` se um erro ocorreu." -#: ../../c-api/arg.rst:678 +#: ../../c-api/arg.rst:692 msgid "" "Convert a sequence of C values to a Python tuple with the same number of " "items." @@ -1510,11 +1579,11 @@ msgstr "" "Converte uma sequência de valores C para uma tupla Python com o mesmo número " "de itens." -#: ../../c-api/arg.rst:680 +#: ../../c-api/arg.rst:694 msgid "``[items]`` (:class:`list`) [*matching-items*]" msgstr "``[items]`` (:class:`list`) [*matching-items*]" -#: ../../c-api/arg.rst:681 +#: ../../c-api/arg.rst:695 msgid "" "Convert a sequence of C values to a Python list with the same number of " "items." @@ -1522,11 +1591,11 @@ msgstr "" "Converte uma sequência de valores C para uma lista Python com o mesmo número " "de itens." -#: ../../c-api/arg.rst:683 +#: ../../c-api/arg.rst:697 msgid "``{items}`` (:class:`dict`) [*matching-items*]" msgstr "``{items}`` (:class:`dict`) [*matching-items*]" -#: ../../c-api/arg.rst:684 +#: ../../c-api/arg.rst:698 msgid "" "Convert a sequence of C values to a Python dictionary. Each pair of " "consecutive C values adds one item to the dictionary, serving as key and " @@ -1536,7 +1605,7 @@ msgstr "" "valores consecutivos do C adiciona um item ao dicionário, servindo como " "chave e valor, respectivamente." -#: ../../c-api/arg.rst:688 +#: ../../c-api/arg.rst:702 msgid "" "If there is an error in the format string, the :exc:`SystemError` exception " "is set and ``NULL`` returned." @@ -1544,7 +1613,7 @@ msgstr "" "Se existir um erro na string de formatação, a exceção :exc:`SystemError` é " "definida e ``NULL`` é retornado." -#: ../../c-api/arg.rst:693 +#: ../../c-api/arg.rst:707 msgid "" "Identical to :c:func:`Py_BuildValue`, except that it accepts a va_list " "rather than a variable number of arguments." diff --git a/c-api/bool.po b/c-api/bool.po index 70cefcc72..91c20c65b 100644 --- a/c-api/bool.po +++ b/c-api/bool.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Julio Biason, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/buffer.po b/c-api/buffer.po index dcfa980ce..0f4763b6e 100644 --- a/c-api/buffer.po +++ b/c-api/buffer.po @@ -1,38 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# (Douglas da Silva) , 2021 -# Julio Gadioli Soares , 2021 -# felipe caridade fernandes , 2021 -# Danielle Farias , 2021 -# Julia Rizza , 2021 -# Nícolas Prado , 2021 -# Leandro Braga , 2021 -# Ana Carolina Dias, 2022 -# Marco Rougeth , 2023 -# Julio Biason, 2023 -# Victor D. G., 2023 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-05 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-02 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -68,31 +55,35 @@ msgstr "" #: ../../c-api/buffer.rst:29 msgid "" -"Python provides such a facility at the C level in the form of the :ref:" -"`buffer protocol `. This protocol has two sides:" +"Python provides such a facility at the C and Python level in the form of " +"the :ref:`buffer protocol `. This protocol has two sides:" msgstr "" -"Python fornece essa facilidade no nível C sob a forma de :ref:`protocolo de " -"buffer `. Este protocolo tem dois lados:" +"Python fornece essa facilidade no nível C e Python sob a forma de :ref:" +"`protocolo de buffer `. Este protocolo tem dois lados:" #: ../../c-api/buffer.rst:34 msgid "" "on the producer side, a type can export a \"buffer interface\" which allows " "objects of that type to expose information about their underlying buffer. " -"This interface is described in the section :ref:`buffer-structs`;" +"This interface is described in the section :ref:`buffer-structs`; for Python " +"see :ref:`python-buffer-protocol`." msgstr "" "do lado do produtor, um tipo pode exportar uma \"interface de buffer\" que " "permite que objetos desse tipo exponham informações sobre o buffer " -"subjacente. Esta interface é descrita na seção :ref:`buffer-structs`;" +"subjacente. Esta interface é descrita na seção :ref:`buffer-structs`; para " +"Python, consulte :ref:`python-buffer-protocol`." -#: ../../c-api/buffer.rst:38 +#: ../../c-api/buffer.rst:39 msgid "" "on the consumer side, several means are available to obtain a pointer to the " -"raw underlying data of an object (for example a method parameter)." +"raw underlying data of an object (for example a method parameter). For " +"Python see :class:`memoryview`." msgstr "" "do lado do consumidor, vários meios estão disponíveis para obter o ponteiro " -"para os dados subjacentes de um objeto (por exemplo, um parâmetro de método)." +"para os dados subjacentes de um objeto (por exemplo, um parâmetro de " +"método). Para Python, consulte :ref:`python-buffer-protocol`." -#: ../../c-api/buffer.rst:41 +#: ../../c-api/buffer.rst:43 msgid "" "Simple objects such as :class:`bytes` and :class:`bytearray` expose their " "underlying buffer in byte-oriented form. Other forms are possible; for " @@ -104,7 +95,7 @@ msgstr "" "exemplo, os elementos expostos por uma :class:`array.array` podem ser " "valores de vários bytes." -#: ../../c-api/buffer.rst:45 +#: ../../c-api/buffer.rst:47 msgid "" "An example consumer of the buffer interface is the :meth:`~io.BufferedIOBase." "write` method of file objects: any object that can export a series of bytes " @@ -125,7 +116,7 @@ msgstr "" "permitir ou rejeitar a exportação para buffers de leitura e escrita ou " "somente leitura." -#: ../../c-api/buffer.rst:53 +#: ../../c-api/buffer.rst:55 msgid "" "There are two ways for a consumer of the buffer interface to acquire a " "buffer over a target object:" @@ -133,11 +124,11 @@ msgstr "" "Existem duas maneiras para um consumidor da interface de buffer adquirir um " "buffer em um objeto alvo:" -#: ../../c-api/buffer.rst:56 +#: ../../c-api/buffer.rst:58 msgid "call :c:func:`PyObject_GetBuffer` with the right parameters;" msgstr "chamada de :c:func:`PyObject_GetBuffer` com os parâmetros certos;" -#: ../../c-api/buffer.rst:58 +#: ../../c-api/buffer.rst:60 msgid "" "call :c:func:`PyArg_ParseTuple` (or one of its siblings) with one of the " "``y*``, ``w*`` or ``s*`` :ref:`format codes `." @@ -145,7 +136,7 @@ msgstr "" "chamada de :c:func:`PyArg_ParseTuple` (ou um dos seus irmãos) com um dos :" "ref:`códigos de formatação ` ``y*``, ``w*`` ou ``s*``." -#: ../../c-api/buffer.rst:61 +#: ../../c-api/buffer.rst:63 msgid "" "In both cases, :c:func:`PyBuffer_Release` must be called when the buffer " "isn't needed anymore. Failure to do so could lead to various issues such as " @@ -156,10 +147,18 @@ msgstr "" "tais como vazamentos de recursos." #: ../../c-api/buffer.rst:69 +msgid "" +"The buffer protocol is now accessible in Python, see :ref:`python-buffer-" +"protocol` and :class:`memoryview`." +msgstr "" +"O protocolo de buffer agora está acessível em Python, veja :ref:`python-" +"buffer-protocol` e :class:`memoryview`." + +#: ../../c-api/buffer.rst:75 msgid "Buffer structure" msgstr "Estrutura de Buffer" -#: ../../c-api/buffer.rst:71 +#: ../../c-api/buffer.rst:77 msgid "" "Buffer structures (or simply \"buffers\") are useful as a way to expose the " "binary data from another object to the Python programmer. They can also be " @@ -180,7 +179,7 @@ msgstr "" "operacional, ou pode ser usado para transmitir dados estruturados no formato " "nativo e formato de memória." -#: ../../c-api/buffer.rst:80 +#: ../../c-api/buffer.rst:86 msgid "" "Contrary to most data types exposed by the Python interpreter, buffers are " "not :c:type:`PyObject` pointers but rather simple C structures. This allows " @@ -194,7 +193,7 @@ msgstr "" "simples. Quando um invólucro genérico em torno de um buffer é necessário, um " "objeto :ref:`memoryview ` pode ser criado." -#: ../../c-api/buffer.rst:86 +#: ../../c-api/buffer.rst:92 msgid "" "For short instructions how to write an exporting object, see :ref:`Buffer " "Object Structures `. For obtaining a buffer, see :c:func:" @@ -204,7 +203,7 @@ msgstr "" "consulte :ref:`Buffer Object Structures `. Para obter um " "buffer, veja :c:func:`PyObject_GetBuffer`." -#: ../../c-api/buffer.rst:94 +#: ../../c-api/buffer.rst:100 msgid "" "A pointer to the start of the logical structure described by the buffer " "fields. This can be any location within the underlying physical memory block " @@ -216,7 +215,7 @@ msgstr "" "subjacente do exportador. Por exemplo, com negativo :c:member:`~Py_buffer." "strides` o valor pode apontar para o final do bloco de memória." -#: ../../c-api/buffer.rst:99 +#: ../../c-api/buffer.rst:105 msgid "" "For :term:`contiguous` arrays, the value points to the beginning of the " "memory block." @@ -224,7 +223,7 @@ msgstr "" "Para vetores :term:`contíguos `, o valor aponta para o início do " "bloco de memória." -#: ../../c-api/buffer.rst:104 +#: ../../c-api/buffer.rst:110 msgid "" "A new reference to the exporting object. The reference is owned by the " "consumer and automatically released (i.e. reference count decremented) and " @@ -237,7 +236,7 @@ msgstr "" "`PyBuffer_Release`. O campo é equivalmente ao valor de retorno de qualquer " "função do padrão C-API." -#: ../../c-api/buffer.rst:111 +#: ../../c-api/buffer.rst:117 msgid "" "As a special case, for *temporary* buffers that are wrapped by :c:func:" "`PyMemoryView_FromBuffer` or :c:func:`PyBuffer_FillInfo` this field is " @@ -247,7 +246,7 @@ msgstr "" "c:func:`PyMemoryView_FromBuffer` ou :c:func:`PyBuffer_FillInfo` esse campo é " "``NULL``. Em geral, objetos exportadores NÃO DEVEM usar esse esquema." -#: ../../c-api/buffer.rst:118 +#: ../../c-api/buffer.rst:124 msgid "" "``product(shape) * itemsize``. For contiguous arrays, this is the length of " "the underlying memory block. For non-contiguous arrays, it is the length " @@ -259,7 +258,7 @@ msgstr "" "que a estrutura lógica teria se fosse copiado para uma representação " "contígua." -#: ../../c-api/buffer.rst:123 +#: ../../c-api/buffer.rst:129 msgid "" "Accessing ``((char *)buf)[0] up to ((char *)buf)[len-1]`` is only valid if " "the buffer has been obtained by a request that guarantees contiguity. In " @@ -271,7 +270,7 @@ msgstr "" "maioria dos casos, esse pedido será :c:macro:`PyBUF_SIMPLE` ou :c:macro:" "`PyBUF_WRITABLE`." -#: ../../c-api/buffer.rst:129 +#: ../../c-api/buffer.rst:135 msgid "" "An indicator of whether the buffer is read-only. This field is controlled by " "the :c:macro:`PyBUF_WRITABLE` flag." @@ -279,7 +278,7 @@ msgstr "" "Um indicador de se o buffer é somente leitura. Este campo é controlado pelo " "sinalizador :c:macro:`PyBUF_WRITABLE`." -#: ../../c-api/buffer.rst:134 +#: ../../c-api/buffer.rst:140 msgid "" "Item size in bytes of a single element. Same as the value of :func:`struct." "calcsize` called on non-``NULL`` :c:member:`~Py_buffer.format` values." @@ -288,7 +287,7 @@ msgstr "" "func:`struct.calcsize` chamado em valores não ``NULL`` de :c:member:" "`~Py_buffer.format`." -#: ../../c-api/buffer.rst:137 +#: ../../c-api/buffer.rst:143 msgid "" "Important exception: If a consumer requests a buffer without the :c:macro:" "`PyBUF_FORMAT` flag, :c:member:`~Py_buffer.format` will be set to " @@ -300,7 +299,7 @@ msgstr "" "``NULL``, mas :c:member:`~Py_buffer.itemsize` ainda terá seu valor para o " "formato original." -#: ../../c-api/buffer.rst:142 +#: ../../c-api/buffer.rst:148 msgid "" "If :c:member:`~Py_buffer.shape` is present, the equality ``product(shape) * " "itemsize == len`` still holds and the consumer can use :c:member:`~Py_buffer." @@ -310,7 +309,7 @@ msgstr "" "* itemsize == len`` ainda é válida e o usuário pode usar :c:member:" "`~Py_buffer.itemsize` para navegar o buffer." -#: ../../c-api/buffer.rst:146 +#: ../../c-api/buffer.rst:152 msgid "" "If :c:member:`~Py_buffer.shape` is ``NULL`` as a result of a :c:macro:" "`PyBUF_SIMPLE` or a :c:macro:`PyBUF_WRITABLE` request, the consumer must " @@ -320,7 +319,7 @@ msgstr "" "`PyBUF_SIMPLE` ou uma requisição :c:macro:`PyBUF_WRITABLE`, o consumidor " "deve ignorar :c:member:`~Py_buffer.itemsize` e presumir ``itemsize == 1``." -#: ../../c-api/buffer.rst:152 +#: ../../c-api/buffer.rst:158 msgid "" "A *NULL* terminated string in :mod:`struct` module style syntax describing " "the contents of a single item. If this is ``NULL``, ``\"B\"`` (unsigned " @@ -330,11 +329,11 @@ msgstr "" "descrevendo os conteúdos de um único item. Se isso é ``NULL``, ``\"B\"`` " "(unsigned bytes) é presumido." -#: ../../c-api/buffer.rst:156 +#: ../../c-api/buffer.rst:162 msgid "This field is controlled by the :c:macro:`PyBUF_FORMAT` flag." msgstr "Este campo é controlado pelo sinalizador :c:macro:`PyBUF_FORMAT`." -#: ../../c-api/buffer.rst:160 +#: ../../c-api/buffer.rst:166 msgid "" "The number of dimensions the memory represents as an n-dimensional array. If " "it is ``0``, :c:member:`~Py_buffer.buf` points to a single item representing " @@ -348,7 +347,7 @@ msgstr "" "member:`~Py_buffer.strides` e :c:member:`~Py_buffer.suboffsets` DEVEM ser " "``NULL``. O número máximo de dimensões é dado por :c:macro:`PyBUF_MAX_NDIM`." -#: ../../c-api/buffer.rst:168 +#: ../../c-api/buffer.rst:174 msgid "" "An array of :c:type:`Py_ssize_t` of length :c:member:`~Py_buffer.ndim` " "indicating the shape of the memory as an n-dimensional array. Note that " @@ -360,7 +359,7 @@ msgstr "" "que a forma ``shape[0] * ... * shape[ndim-1] * itemsize`` DEVE ser igual a :" "c:member:`~Py_buffer.len`." -#: ../../c-api/buffer.rst:173 +#: ../../c-api/buffer.rst:179 msgid "" "Shape values are restricted to ``shape[n] >= 0``. The case ``shape[n] == 0`` " "requires special attention. See `complex arrays`_ for further information." @@ -368,11 +367,11 @@ msgstr "" "Os valores da forma são restritos a ``shape[n] >= 0``. The case ``shape[n] " "== 0`` requer atenção especial. Veja `complex arrays`_ para mais informações." -#: ../../c-api/buffer.rst:177 +#: ../../c-api/buffer.rst:183 msgid "The shape array is read-only for the consumer." msgstr "A forma de acesso a matriz é de somente leitura para o usuário." -#: ../../c-api/buffer.rst:181 +#: ../../c-api/buffer.rst:187 msgid "" "An array of :c:type:`Py_ssize_t` of length :c:member:`~Py_buffer.ndim` " "giving the number of bytes to skip to get to a new element in each dimension." @@ -381,7 +380,7 @@ msgstr "" "dando o número de bytes para saltar para obter um novo elemento em cada " "dimensão." -#: ../../c-api/buffer.rst:185 +#: ../../c-api/buffer.rst:191 msgid "" "Stride values can be any integer. For regular arrays, strides are usually " "positive, but a consumer MUST be able to handle the case ``strides[n] <= " @@ -392,11 +391,11 @@ msgstr "" "capaz de lidar com o caso ``strides[n] <= 0``. Veja `complex arrays`_ para " "mais informações." -#: ../../c-api/buffer.rst:189 +#: ../../c-api/buffer.rst:195 msgid "The strides array is read-only for the consumer." msgstr "A matriz de passos é somente leitura para o consumidor." -#: ../../c-api/buffer.rst:193 +#: ../../c-api/buffer.rst:199 msgid "" "An array of :c:type:`Py_ssize_t` of length :c:member:`~Py_buffer.ndim`. If " "``suboffsets[n] >= 0``, the values stored along the nth dimension are " @@ -411,7 +410,7 @@ msgstr "" "negativo indica que não deve ocorrer desreferenciação (caminhando em um " "bloco de memória contíguo)." -#: ../../c-api/buffer.rst:200 +#: ../../c-api/buffer.rst:206 msgid "" "If all suboffsets are negative (i.e. no de-referencing is needed), then this " "field must be ``NULL`` (the default value)." @@ -419,7 +418,7 @@ msgstr "" "Se todos os subconjuntos forem negativos (ou seja, não é necessário fazer " "referência), então este campo deve ser ``NULL`` (o valor padrão)." -#: ../../c-api/buffer.rst:203 +#: ../../c-api/buffer.rst:209 msgid "" "This type of array representation is used by the Python Imaging Library " "(PIL). See `complex arrays`_ for further information how to access elements " @@ -429,11 +428,11 @@ msgstr "" "(PIL). Veja `complex arrays`_ para obter mais informações sobre como acessar " "elementos dessa matriz.a matriz." -#: ../../c-api/buffer.rst:207 +#: ../../c-api/buffer.rst:213 msgid "The suboffsets array is read-only for the consumer." msgstr "A matriz de subconjuntos é somente leitura para o consumidor." -#: ../../c-api/buffer.rst:211 +#: ../../c-api/buffer.rst:217 msgid "" "This is for use internally by the exporting object. For example, this might " "be re-cast as an integer by the exporter and used to store flags about " @@ -446,11 +445,11 @@ msgstr "" "ser liberados quando o buffer é liberado. O consumidor NÃO DEVE alterar esse " "valor." -#: ../../c-api/buffer.rst:218 +#: ../../c-api/buffer.rst:224 msgid "Constants:" msgstr "Constantes:" -#: ../../c-api/buffer.rst:222 +#: ../../c-api/buffer.rst:228 msgid "" "The maximum number of dimensions the memory represents. Exporters MUST " "respect this limit, consumers of multi-dimensional buffers SHOULD be able to " @@ -461,11 +460,11 @@ msgstr "" "capazes de liader com até :c:macro:`!PyBUF_MAX_NDIM` dimensões. Atualmente " "definido como 64." -#: ../../c-api/buffer.rst:231 +#: ../../c-api/buffer.rst:237 msgid "Buffer request types" msgstr "Tipos de solicitação do buffer" -#: ../../c-api/buffer.rst:233 +#: ../../c-api/buffer.rst:239 msgid "" "Buffers are usually obtained by sending a buffer request to an exporting " "object via :c:func:`PyObject_GetBuffer`. Since the complexity of the logical " @@ -478,18 +477,18 @@ msgstr "" "consumidor usa o argumento *flags* para especificar o tipo de buffer exato " "que pode manipular." -#: ../../c-api/buffer.rst:238 +#: ../../c-api/buffer.rst:244 msgid "" "All :c:type:`Py_buffer` fields are unambiguously defined by the request type." msgstr "" "Todos os campos :c:type:`Py_buffer` são definidos de forma não-ambígua pelo " "tipo de requisição." -#: ../../c-api/buffer.rst:242 +#: ../../c-api/buffer.rst:248 msgid "request-independent fields" msgstr "campos independentes do pedido" -#: ../../c-api/buffer.rst:243 +#: ../../c-api/buffer.rst:249 msgid "" "The following fields are not influenced by *flags* and must always be filled " "in with the correct values: :c:member:`~Py_buffer.obj`, :c:member:" @@ -501,23 +500,26 @@ msgstr "" "`~Py_buffer.buf`, :c:member:`~Py_buffer.len`, :c:member:`~Py_buffer." "itemsize`, :c:member:`~Py_buffer.ndim`." -#: ../../c-api/buffer.rst:249 +#: ../../c-api/buffer.rst:254 msgid "readonly, format" msgstr "apenas em formato" -#: ../../c-api/buffer.rst:253 +#: ../../c-api/buffer.rst:258 msgid "" "Controls the :c:member:`~Py_buffer.readonly` field. If set, the exporter " "MUST provide a writable buffer or else report failure. Otherwise, the " "exporter MAY provide either a read-only or writable buffer, but the choice " -"MUST be consistent for all consumers." +"MUST be consistent for all consumers. For example, :c:expr:`PyBUF_SIMPLE | " +"PyBUF_WRITABLE` can be used to request a simple writable buffer." msgstr "" -"Controla o campo :c:member:`~Py_buffer.readonly`. Se configurado, o " -"exportador DEVE fornecer um buffer gravável ou então reportar falha. Caso " -"contrário, o exportador pode fornecer um buffer de somente leitura ou " -"gravável, mas a escolha DEVE ser consistente para todos os consumidores." +"Controla o campo :c:member:`~Py_buffer.readonly` . Se configurado, o " +"exportador DEVE fornecer um buffer gravável ou então relatar falha. Do " +"contrário, o exportador PODE fornecer um buffer somente leitura ou um buffer " +"gravável , mas a escolha DEVE ser consistente para todos os consumidores. " +"Por exemplo, :c:expr:`PyBUF_SIMPLE | PyBUF_WRITABLE` pode ser usado para " +"requisitar um buffer simples gravável." -#: ../../c-api/buffer.rst:260 +#: ../../c-api/buffer.rst:266 msgid "" "Controls the :c:member:`~Py_buffer.format` field. If set, this field MUST be " "filled in correctly. Otherwise, this field MUST be ``NULL``." @@ -526,7 +528,7 @@ msgstr "" "DEVE ser preenchido corretamente. Caso contrário, este campo DEVE ser " "``NULL``." -#: ../../c-api/buffer.rst:264 +#: ../../c-api/buffer.rst:270 msgid "" ":c:macro:`PyBUF_WRITABLE` can be \\|'d to any of the flags in the next " "section. Since :c:macro:`PyBUF_SIMPLE` is defined as 0, :c:macro:" @@ -538,20 +540,22 @@ msgstr "" "c:macro:`PyBUF_WRITABLE` pode ser usado como uma bandeira autônoma para " "solicitar um buffer simples gravável." -#: ../../c-api/buffer.rst:268 +#: ../../c-api/buffer.rst:274 msgid "" -":c:macro:`PyBUF_FORMAT` can be \\|'d to any of the flags except :c:macro:" -"`PyBUF_SIMPLE`. The latter already implies format ``B`` (unsigned bytes)." +":c:macro:`PyBUF_FORMAT` must be \\|'d to any of the flags except :c:macro:" +"`PyBUF_SIMPLE`, because the latter already implies format ``B`` (unsigned " +"bytes). :c:macro:`!PyBUF_FORMAT` cannot be used on its own." msgstr "" -":c:macro:`PyBUF_FORMAT` pode ser \\|'d para qualquer um dos sinalizadores, " -"exceto :c:macro:`PyBUF_SIMPLE`. O último já implica o formato ``B`` (bytes " -"não assinados)." +":c:macro:`PyBUF_FORMAT` deve ser \\|'d para qualquer um dos sinalizadores " +"exceto :c:macro:`PyBUF_SIMPLE`, uma vez que este já indica que o formato " +"``B`` (unsigned bytes). :c:macro:`!PyBUF_FORMAT` não pode ser utilizado " +"sozinho." -#: ../../c-api/buffer.rst:273 +#: ../../c-api/buffer.rst:280 msgid "shape, strides, suboffsets" msgstr "forma, avanços, suboffsets" -#: ../../c-api/buffer.rst:275 +#: ../../c-api/buffer.rst:282 msgid "" "The flags that control the logical structure of the memory are listed in " "decreasing order of complexity. Note that each flag contains all bits of the " @@ -561,57 +565,57 @@ msgstr "" "ordem decrescente de complexidade. Observe que cada bandeira contém todos os " "bits das bandeiras abaixo." -#: ../../c-api/buffer.rst:282 ../../c-api/buffer.rst:306 -#: ../../c-api/buffer.rst:331 +#: ../../c-api/buffer.rst:289 ../../c-api/buffer.rst:313 +#: ../../c-api/buffer.rst:338 msgid "Request" msgstr "Solicitação" -#: ../../c-api/buffer.rst:282 ../../c-api/buffer.rst:306 -#: ../../c-api/buffer.rst:331 +#: ../../c-api/buffer.rst:289 ../../c-api/buffer.rst:313 +#: ../../c-api/buffer.rst:338 msgid "shape" msgstr "Forma" -#: ../../c-api/buffer.rst:282 ../../c-api/buffer.rst:306 -#: ../../c-api/buffer.rst:331 +#: ../../c-api/buffer.rst:289 ../../c-api/buffer.rst:313 +#: ../../c-api/buffer.rst:338 msgid "strides" msgstr "Avanços" -#: ../../c-api/buffer.rst:282 ../../c-api/buffer.rst:306 -#: ../../c-api/buffer.rst:331 +#: ../../c-api/buffer.rst:289 ../../c-api/buffer.rst:313 +#: ../../c-api/buffer.rst:338 msgid "suboffsets" msgstr "subconjuntos" -#: ../../c-api/buffer.rst:284 ../../c-api/buffer.rst:286 -#: ../../c-api/buffer.rst:288 ../../c-api/buffer.rst:308 -#: ../../c-api/buffer.rst:310 ../../c-api/buffer.rst:312 -#: ../../c-api/buffer.rst:314 ../../c-api/buffer.rst:333 -#: ../../c-api/buffer.rst:335 ../../c-api/buffer.rst:337 -#: ../../c-api/buffer.rst:339 ../../c-api/buffer.rst:341 -#: ../../c-api/buffer.rst:343 ../../c-api/buffer.rst:345 -#: ../../c-api/buffer.rst:347 +#: ../../c-api/buffer.rst:291 ../../c-api/buffer.rst:293 +#: ../../c-api/buffer.rst:295 ../../c-api/buffer.rst:315 +#: ../../c-api/buffer.rst:317 ../../c-api/buffer.rst:319 +#: ../../c-api/buffer.rst:321 ../../c-api/buffer.rst:340 +#: ../../c-api/buffer.rst:342 ../../c-api/buffer.rst:344 +#: ../../c-api/buffer.rst:346 ../../c-api/buffer.rst:348 +#: ../../c-api/buffer.rst:350 ../../c-api/buffer.rst:352 +#: ../../c-api/buffer.rst:354 msgid "yes" msgstr "sim" -#: ../../c-api/buffer.rst:284 ../../c-api/buffer.rst:333 -#: ../../c-api/buffer.rst:335 +#: ../../c-api/buffer.rst:291 ../../c-api/buffer.rst:340 +#: ../../c-api/buffer.rst:342 msgid "if needed" msgstr "se necessário" -#: ../../c-api/buffer.rst:286 ../../c-api/buffer.rst:288 -#: ../../c-api/buffer.rst:290 ../../c-api/buffer.rst:308 -#: ../../c-api/buffer.rst:310 ../../c-api/buffer.rst:312 -#: ../../c-api/buffer.rst:314 ../../c-api/buffer.rst:337 -#: ../../c-api/buffer.rst:339 ../../c-api/buffer.rst:341 -#: ../../c-api/buffer.rst:343 ../../c-api/buffer.rst:345 -#: ../../c-api/buffer.rst:347 +#: ../../c-api/buffer.rst:293 ../../c-api/buffer.rst:295 +#: ../../c-api/buffer.rst:297 ../../c-api/buffer.rst:315 +#: ../../c-api/buffer.rst:317 ../../c-api/buffer.rst:319 +#: ../../c-api/buffer.rst:321 ../../c-api/buffer.rst:344 +#: ../../c-api/buffer.rst:346 ../../c-api/buffer.rst:348 +#: ../../c-api/buffer.rst:350 ../../c-api/buffer.rst:352 +#: ../../c-api/buffer.rst:354 msgid "NULL" msgstr "NULL" -#: ../../c-api/buffer.rst:297 +#: ../../c-api/buffer.rst:304 msgid "contiguity requests" msgstr "requisições contíguas" -#: ../../c-api/buffer.rst:299 +#: ../../c-api/buffer.rst:306 msgid "" "C or Fortran :term:`contiguity ` can be explicitly requested, " "with and without stride information. Without stride information, the buffer " @@ -621,32 +625,32 @@ msgstr "" "solicitadas, com ou sem informação de avanço. Sem informação de avanço, o " "buffer deve ser C-contíguo." -#: ../../c-api/buffer.rst:306 ../../c-api/buffer.rst:331 +#: ../../c-api/buffer.rst:313 ../../c-api/buffer.rst:338 msgid "contig" msgstr "contig" -#: ../../c-api/buffer.rst:308 ../../c-api/buffer.rst:314 -#: ../../c-api/buffer.rst:345 ../../c-api/buffer.rst:347 +#: ../../c-api/buffer.rst:315 ../../c-api/buffer.rst:321 +#: ../../c-api/buffer.rst:352 ../../c-api/buffer.rst:354 msgid "C" msgstr "C" -#: ../../c-api/buffer.rst:310 +#: ../../c-api/buffer.rst:317 msgid "F" msgstr "F" -#: ../../c-api/buffer.rst:312 +#: ../../c-api/buffer.rst:319 msgid "C or F" msgstr "C ou F" -#: ../../c-api/buffer.rst:314 +#: ../../c-api/buffer.rst:321 msgid ":c:macro:`PyBUF_ND`" msgstr ":c:macro:`PyBUF_ND`" -#: ../../c-api/buffer.rst:319 +#: ../../c-api/buffer.rst:326 msgid "compound requests" msgstr "requisições compostas" -#: ../../c-api/buffer.rst:321 +#: ../../c-api/buffer.rst:328 msgid "" "All possible requests are fully defined by some combination of the flags in " "the previous section. For convenience, the buffer protocol provides " @@ -657,7 +661,7 @@ msgstr "" "protocolo do buffer fornece combinações frequentemente utilizadas como " "sinalizadores únicos." -#: ../../c-api/buffer.rst:325 +#: ../../c-api/buffer.rst:332 msgid "" "In the following table *U* stands for undefined contiguity. The consumer " "would have to call :c:func:`PyBuffer_IsContiguous` to determine contiguity." @@ -665,39 +669,39 @@ msgstr "" "Na seguinte tabela *U* significa contiguidade indefinida. O consumidor deve " "chamar :c:func:`PyBuffer_IsContiguous` para determinar a contiguidade." -#: ../../c-api/buffer.rst:331 +#: ../../c-api/buffer.rst:338 msgid "readonly" msgstr "readonly" -#: ../../c-api/buffer.rst:331 +#: ../../c-api/buffer.rst:338 msgid "format" -msgstr "formato" +msgstr "format" -#: ../../c-api/buffer.rst:333 ../../c-api/buffer.rst:335 -#: ../../c-api/buffer.rst:337 ../../c-api/buffer.rst:339 -#: ../../c-api/buffer.rst:341 ../../c-api/buffer.rst:343 +#: ../../c-api/buffer.rst:340 ../../c-api/buffer.rst:342 +#: ../../c-api/buffer.rst:344 ../../c-api/buffer.rst:346 +#: ../../c-api/buffer.rst:348 ../../c-api/buffer.rst:350 msgid "U" msgstr "U" -#: ../../c-api/buffer.rst:333 ../../c-api/buffer.rst:337 -#: ../../c-api/buffer.rst:341 ../../c-api/buffer.rst:345 +#: ../../c-api/buffer.rst:340 ../../c-api/buffer.rst:344 +#: ../../c-api/buffer.rst:348 ../../c-api/buffer.rst:352 msgid "0" msgstr "0" -#: ../../c-api/buffer.rst:335 ../../c-api/buffer.rst:339 -#: ../../c-api/buffer.rst:343 ../../c-api/buffer.rst:347 +#: ../../c-api/buffer.rst:342 ../../c-api/buffer.rst:346 +#: ../../c-api/buffer.rst:350 ../../c-api/buffer.rst:354 msgid "1 or 0" msgstr "1 ou 0" -#: ../../c-api/buffer.rst:352 +#: ../../c-api/buffer.rst:359 msgid "Complex arrays" msgstr "Vetores Complexos" -#: ../../c-api/buffer.rst:355 +#: ../../c-api/buffer.rst:362 msgid "NumPy-style: shape and strides" msgstr "Estilo NumPy: forma e avanços" -#: ../../c-api/buffer.rst:357 +#: ../../c-api/buffer.rst:364 msgid "" "The logical structure of NumPy-style arrays is defined by :c:member:" "`~Py_buffer.itemsize`, :c:member:`~Py_buffer.ndim`, :c:member:`~Py_buffer." @@ -707,7 +711,7 @@ msgstr "" "`~Py_buffer.itemsize`, :c:member:`~Py_buffer.ndim`, :c:member:`~Py_buffer." "shape` e :c:member:`~Py_buffer.strides`." -#: ../../c-api/buffer.rst:360 +#: ../../c-api/buffer.rst:367 msgid "" "If ``ndim == 0``, the memory location pointed to by :c:member:`~Py_buffer." "buf` is interpreted as a scalar of size :c:member:`~Py_buffer.itemsize`. In " @@ -719,7 +723,7 @@ msgstr "" "`~Py_buffer.itemsize`. Nesse caso, ambos :c:member:`~Py_buffer.shape` e :c:" "member:`~Py_buffer.strides` são ``NULL``." -#: ../../c-api/buffer.rst:364 +#: ../../c-api/buffer.rst:371 msgid "" "If :c:member:`~Py_buffer.strides` is ``NULL``, the array is interpreted as a " "standard n-dimensional C-array. Otherwise, the consumer must access an n-" @@ -729,7 +733,17 @@ msgstr "" "vetor C n-dimensional padrão. Caso contrário, o consumidor deve acessar um " "vetor n-dimensional como a seguir:" -#: ../../c-api/buffer.rst:374 +#: ../../c-api/buffer.rst:375 +msgid "" +"ptr = (char *)buf + indices[0] * strides[0] + ... + indices[n-1] * " +"strides[n-1];\n" +"item = *((typeof(item) *)ptr);" +msgstr "" +"ptr = (char *)buf + indices[0] * strides[0] + ... + indices[n-1] * " +"strides[n-1];\n" +"item = *((typeof(item) *)ptr);" + +#: ../../c-api/buffer.rst:381 msgid "" "As noted above, :c:member:`~Py_buffer.buf` can point to any location within " "the actual memory block. An exporter can check the validity of a buffer with " @@ -739,11 +753,65 @@ msgstr "" "localização dentro do bloco de memória em si. Um exportador pode verificar a " "validade de um buffer com essa função:" -#: ../../c-api/buffer.rst:408 +#: ../../c-api/buffer.rst:385 +msgid "" +"def verify_structure(memlen, itemsize, ndim, shape, strides, offset):\n" +" \"\"\"Verify that the parameters represent a valid array within\n" +" the bounds of the allocated memory:\n" +" char *mem: start of the physical memory block\n" +" memlen: length of the physical memory block\n" +" offset: (char *)buf - mem\n" +" \"\"\"\n" +" if offset % itemsize:\n" +" return False\n" +" if offset < 0 or offset+itemsize > memlen:\n" +" return False\n" +" if any(v % itemsize for v in strides):\n" +" return False\n" +"\n" +" if ndim <= 0:\n" +" return ndim == 0 and not shape and not strides\n" +" if 0 in shape:\n" +" return True\n" +"\n" +" imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)\n" +" if strides[j] <= 0)\n" +" imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)\n" +" if strides[j] > 0)\n" +"\n" +" return 0 <= offset+imin and offset+imax+itemsize <= memlen" +msgstr "" +"def verify_structure(memlen, itemsize, ndim, shape, strides, offset):\n" +" \"\"\"Verifica se os parâmetros representa um vetor válido dentro\n" +" dos limites da memória alocada:\n" +" char *mem: início do bloco de memória física\n" +" memlen: comprimento do bloco de memória física\n" +" offset: (char *)buf - mem\n" +" \"\"\"\n" +" if offset % itemsize:\n" +" return False\n" +" if offset < 0 or offset+itemsize > memlen:\n" +" return False\n" +" if any(v % itemsize for v in strides):\n" +" return False\n" +"\n" +" if ndim <= 0:\n" +" return ndim == 0 and not shape and not strides\n" +" if 0 in shape:\n" +" return True\n" +"\n" +" imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)\n" +" if strides[j] <= 0)\n" +" imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)\n" +" if strides[j] > 0)\n" +"\n" +" return 0 <= offset+imin and offset+imax+itemsize <= memlen" + +#: ../../c-api/buffer.rst:415 msgid "PIL-style: shape, strides and suboffsets" msgstr "Estilo-PIL: forma, avanços e suboffsets" -#: ../../c-api/buffer.rst:410 +#: ../../c-api/buffer.rst:417 msgid "" "In addition to the regular items, PIL-style arrays can contain pointers that " "must be followed in order to get to the next element in a dimension. For " @@ -762,7 +830,7 @@ msgstr "" "matrizes ``char x[2][3]`` que podem estar localizadas em qualquer lugar na " "memória." -#: ../../c-api/buffer.rst:419 +#: ../../c-api/buffer.rst:426 msgid "" "Here is a function that returns a pointer to the element in an N-D array " "pointed to by an N-dimensional index when there are both non-``NULL`` " @@ -772,11 +840,39 @@ msgstr "" "apontada por um índice N-dimensional onde existem ambos passos e " "subconjuntos não-``NULL``::" -#: ../../c-api/buffer.rst:438 +#: ../../c-api/buffer.rst:430 +msgid "" +"void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,\n" +" Py_ssize_t *suboffsets, Py_ssize_t *indices) {\n" +" char *pointer = (char*)buf;\n" +" int i;\n" +" for (i = 0; i < ndim; i++) {\n" +" pointer += strides[i] * indices[i];\n" +" if (suboffsets[i] >=0 ) {\n" +" pointer = *((char**)pointer) + suboffsets[i];\n" +" }\n" +" }\n" +" return (void*)pointer;\n" +"}" +msgstr "" +"void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,\n" +" Py_ssize_t *suboffsets, Py_ssize_t *indices) {\n" +" char *pointer = (char*)buf;\n" +" int i;\n" +" for (i = 0; i < ndim; i++) {\n" +" pointer += strides[i] * indices[i];\n" +" if (suboffsets[i] >=0 ) {\n" +" pointer = *((char**)pointer) + suboffsets[i];\n" +" }\n" +" }\n" +" return (void*)pointer;\n" +"}" + +#: ../../c-api/buffer.rst:445 msgid "Buffer-related functions" msgstr "Funções relacionadas ao Buffer" -#: ../../c-api/buffer.rst:442 +#: ../../c-api/buffer.rst:449 msgid "" "Return ``1`` if *obj* supports the buffer interface otherwise ``0``. When " "``1`` is returned, it doesn't guarantee that :c:func:`PyObject_GetBuffer` " @@ -786,7 +882,7 @@ msgstr "" "Quando ``1`` é retornado, isso não garante que :c:func:`PyObject_GetBuffer` " "será bem sucedida. Esta função é sempre bem sucedida." -#: ../../c-api/buffer.rst:449 +#: ../../c-api/buffer.rst:456 msgid "" "Send a request to *exporter* to fill in *view* as specified by *flags*. If " "the exporter cannot provide a buffer of the exact type, it MUST raise :exc:" @@ -797,7 +893,7 @@ msgstr "" "tipo especificado, ele DEVE levantar :exc:`BufferError`, definir ``view-" ">obj`` para ``NULL`` e retornar ``-1``." -#: ../../c-api/buffer.rst:454 +#: ../../c-api/buffer.rst:461 msgid "" "On success, fill in *view*, set ``view->obj`` to a new reference to " "*exporter* and return 0. In the case of chained buffer providers that " @@ -810,7 +906,7 @@ msgstr "" "DEVE se referir a este objeto em vez de *exporter* (Veja :ref:`Buffer Object " "Structures `)." -#: ../../c-api/buffer.rst:459 +#: ../../c-api/buffer.rst:466 msgid "" "Successful calls to :c:func:`PyObject_GetBuffer` must be paired with calls " "to :c:func:`PyBuffer_Release`, similar to :c:func:`malloc` and :c:func:" @@ -822,7 +918,7 @@ msgstr "" "func:`malloc` e :c:func:`free`. Assim, após o consumidor terminar com o " "buffer, :c:func:`PyBuffer_Release` deve ser chamado exatamente uma vez." -#: ../../c-api/buffer.rst:467 +#: ../../c-api/buffer.rst:474 msgid "" "Release the buffer *view* and release the :term:`strong reference` (i.e. " "decrement the reference count) to the view's supporting object, ``view-" @@ -834,7 +930,7 @@ msgstr "" "``view->obj``. Esta função DEVE ser chamada quando o buffer não estiver mais " "sendo usado, ou o vazamento de referências pode acontecer." -#: ../../c-api/buffer.rst:472 +#: ../../c-api/buffer.rst:479 msgid "" "It is an error to call this function on a buffer that was not obtained via :" "c:func:`PyObject_GetBuffer`." @@ -842,7 +938,7 @@ msgstr "" "É um erro chamar essa função em um buffer que não foi obtido via :c:func:" "`PyObject_GetBuffer`." -#: ../../c-api/buffer.rst:478 +#: ../../c-api/buffer.rst:485 msgid "" "Return the implied :c:member:`~Py_buffer.itemsize` from :c:member:" "`~Py_buffer.format`. On error, raise an exception and return -1." @@ -850,7 +946,7 @@ msgstr "" "Retorna o :c:member:`~Py_buffer.itemsize` implícito de :c:member:`~Py_buffer." "format`. Em erro, levantar e exceção e retornar -1." -#: ../../c-api/buffer.rst:486 +#: ../../c-api/buffer.rst:493 msgid "" "Return ``1`` if the memory defined by the *view* is C-style (*order* is " "``'C'``) or Fortran-style (*order* is ``'F'``) :term:`contiguous` or either " @@ -862,7 +958,7 @@ msgstr "" "``'F'``) ou qualquer outra (*order* é ``'A'``). Retorna ``0`` caso " "contrário. Essa função é sempre bem sucedida." -#: ../../c-api/buffer.rst:493 +#: ../../c-api/buffer.rst:500 msgid "" "Get the memory area pointed to by the *indices* inside the given *view*. " "*indices* must point to an array of ``view->ndim`` indices." @@ -870,7 +966,7 @@ msgstr "" "Recebe a área de memória apontada pelos *indices* dentro da *view* dada. " "*indices* deve apontar para um array de ``view->ndim`` índices." -#: ../../c-api/buffer.rst:499 +#: ../../c-api/buffer.rst:506 msgid "" "Copy contiguous *len* bytes from *buf* to *view*. *fort* can be ``'C'`` or " "``'F'`` (for C-style or Fortran-style ordering). ``0`` is returned on " @@ -880,7 +976,7 @@ msgstr "" "``'F'`` (para ordenação estilo C ou estilo Fortran). Retorna ``0`` em caso " "de sucesso e ``-1`` em caso de erro." -#: ../../c-api/buffer.rst:506 +#: ../../c-api/buffer.rst:513 msgid "" "Copy *len* bytes from *src* to its contiguous representation in *buf*. " "*order* can be ``'C'`` or ``'F'`` or ``'A'`` (for C-style or Fortran-style " @@ -891,11 +987,11 @@ msgstr "" "qualquer uma). O retorno é ``0`` em caso de sucesso e ``-1`` em caso de " "falha." -#: ../../c-api/buffer.rst:510 +#: ../../c-api/buffer.rst:517 msgid "This function fails if *len* != *src->len*." msgstr "Esta função falha se *len* != *src->len*." -#: ../../c-api/buffer.rst:515 +#: ../../c-api/buffer.rst:522 msgid "" "Copy data from *src* to *dest* buffer. Can convert between C-style and or " "Fortran-style buffers." @@ -903,11 +999,11 @@ msgstr "" "Copia os dados do buffer *src* para o buffer *dest*. Pode converter entre " "buffers de estilo C e/ou estilo Fortran." -#: ../../c-api/buffer.rst:518 +#: ../../c-api/buffer.rst:525 msgid "``0`` is returned on success, ``-1`` on error." msgstr "``0`` é retornado em caso de sucesso, ``-1`` em caso de erro." -#: ../../c-api/buffer.rst:522 +#: ../../c-api/buffer.rst:529 msgid "" "Fill the *strides* array with byte-strides of a :term:`contiguous` (C-style " "if *order* is ``'C'`` or Fortran-style if *order* is ``'F'``) array of the " @@ -917,7 +1013,7 @@ msgstr "" "(estilo C se *order* é ``'C'`` ou estilo Fortran se *order* for ``'F'``) da " "forma dada com o número dado de bytes por elemento." -#: ../../c-api/buffer.rst:529 +#: ../../c-api/buffer.rst:536 msgid "" "Handle buffer requests for an exporter that wants to expose *buf* of size " "*len* with writability set according to *readonly*. *buf* is interpreted as " @@ -927,7 +1023,7 @@ msgstr "" "tamanho *len* com capacidade de escrita definida de acordo com *readonly*. " "*buf* é interpretada como uma sequência de bytes sem sinal." -#: ../../c-api/buffer.rst:533 +#: ../../c-api/buffer.rst:540 msgid "" "The *flags* argument indicates the request type. This function always fills " "in *view* as specified by flags, unless *buf* has been designated as read-" @@ -937,7 +1033,7 @@ msgstr "" "*view* como especificado por *flags*, a não ser que *buf* seja designado " "como somente leitura e :c:macro:`PyBUF_WRITABLE` esteja definido em *flags*." -#: ../../c-api/buffer.rst:537 +#: ../../c-api/buffer.rst:544 msgid "" "On success, set ``view->obj`` to a new reference to *exporter* and return 0. " "Otherwise, raise :exc:`BufferError`, set ``view->obj`` to ``NULL`` and " @@ -947,7 +1043,7 @@ msgstr "" "*exporter* e retorna 0. Caso contrário, levante :exc:`BufferError` , defina " "``view->obj`` para ``NULL`` e retorne ``-1`` ;" -#: ../../c-api/buffer.rst:541 +#: ../../c-api/buffer.rst:548 msgid "" "If this function is used as part of a :ref:`getbufferproc `, " "*exporter* MUST be set to the exporting object and *flags* must be passed " @@ -978,14 +1074,14 @@ msgstr "objeto buffer" msgid "PyBufferProcs (C type)" msgstr "PyBufferProcs (tipo C)" -#: ../../c-api/buffer.rst:294 +#: ../../c-api/buffer.rst:301 msgid "contiguous" msgstr "contíguo" -#: ../../c-api/buffer.rst:294 +#: ../../c-api/buffer.rst:301 msgid "C-contiguous" msgstr "contíguo C" -#: ../../c-api/buffer.rst:294 +#: ../../c-api/buffer.rst:301 msgid "Fortran contiguous" msgstr "contíguo Fortran" diff --git a/c-api/bytearray.po b/c-api/bytearray.po index cc26922a9..357748c39 100644 --- a/c-api/bytearray.po +++ b/c-api/bytearray.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# msilvavieira, 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/bytes.po b/c-api/bytes.po index eb16cc821..a57235785 100644 --- a/c-api/bytes.po +++ b/c-api/bytes.po @@ -1,38 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Tiago Henrique , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Julio Gadioli Soares , 2021 -# Marco Rougeth , 2023 -# Rafael Fontenelle , 2023 -# Victor D. G., 2023 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../c-api/bytes.rst:6 msgid "Bytes Objects" -msgstr "Objetos Bytes" +msgstr "Objetos bytes" #: ../../c-api/bytes.rst:8 msgid "" diff --git a/c-api/call.po b/c-api/call.po index e9470409d..f38ad3533 100644 --- a/c-api/call.po +++ b/c-api/call.po @@ -1,32 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Renan Lopes , 2024 -# Alexandre B A Villares, 2024 -# Mozart Dias Martins, 2024 -# Adorilson Bezerra , 2024 -# Flávio Neves, 2024 -# Claudio Rogerio Carvalho Filho , 2024 -# Ana Carolina Dias, 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -51,6 +44,12 @@ msgstr "" "Instâncias de classe que definem :c:member:`~PyTypeObject.tp_call` são " "chamáveis. A assinatura do slot é::" +#: ../../c-api/call.rst:17 +msgid "" +"PyObject *tp_call(PyObject *callable, PyObject *args, PyObject *kwargs);" +msgstr "" +"PyObject *tp_call(PyObject *callable, PyObject *args, PyObject *kwargs);" + #: ../../c-api/call.rst:19 msgid "" "A call is made using a tuple for the positional arguments and a dict for the " @@ -286,6 +285,10 @@ msgstr "" "Dado um argumento de chamada de vetor *nargsf*, retorna o número real de " "argumentos. Atualmente equivalente a::" +#: ../../c-api/call.rst:140 +msgid "(Py_ssize_t)(nargsf & ~PY_VECTORCALL_ARGUMENTS_OFFSET)" +msgstr "(Py_ssize_t)(nargsf & ~PY_VECTORCALL_ARGUMENTS_OFFSET)" + #: ../../c-api/call.rst:142 msgid "" "However, the function ``PyVectorcall_NARGS`` should be used to allow for " @@ -425,7 +428,7 @@ msgstr ":c:func:`PyObject_CallFunction`" #: ../../c-api/call.rst:197 ../../c-api/call.rst:199 msgid "format" -msgstr "formato" +msgstr "format" #: ../../c-api/call.rst:199 msgid ":c:func:`PyObject_CallMethod`" diff --git a/c-api/capsule.po b/c-api/capsule.po index c77038510..85cce02d6 100644 --- a/c-api/capsule.po +++ b/c-api/capsule.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -56,6 +56,10 @@ msgid "The type of a destructor callback for a capsule. Defined as::" msgstr "" "O tipo de um retorno de chamada destruidor para uma cápsula. Definido como::" +#: ../../c-api/capsule.rst:29 +msgid "typedef void (*PyCapsule_Destructor)(PyObject *);" +msgstr "typedef void (*PyCapsule_Destructor)(PyObject *);" + #: ../../c-api/capsule.rst:31 msgid "" "See :c:func:`PyCapsule_New` for the semantics of PyCapsule_Destructor " diff --git a/c-api/cell.po b/c-api/cell.po index 736a871da..b3cc3af69 100644 --- a/c-api/cell.po +++ b/c-api/cell.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-12 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -38,9 +38,9 @@ msgid "" "support from the generated byte-code; these are not automatically de-" "referenced when accessed. Cell objects are not likely to be useful elsewhere." msgstr "" -"Objetos \"cell\" são usados ​​para implementar variáveis ​​referenciadas por " +"Objetos \"cell\" são usados para implementar variáveis referenciadas por " "múltiplos escopos. Para cada variável, um objeto célula é criado para " -"armazenar o valor; as variáveis ​​locais de cada quadro de pilha que " +"armazenar o valor; as variáveis locais de cada quadro de pilha que " "referencia o valor contém uma referência para as células de escopos externos " "que também usam essa variável. Quando o valor é acessado, o valor contido na " "célula é usado em vez do próprio objeto da célula. Essa des-referência do " diff --git a/c-api/code.po b/c-api/code.po index 87c7e2e58..9174dcc21 100644 --- a/c-api/code.po +++ b/c-api/code.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# PAULO NASCIMENTO, 2024 -# Welliton Malta , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-28 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -64,14 +62,22 @@ msgstr "" "função sempre tem sucesso." #: ../../c-api/code.rst:35 -msgid "Return the number of free variables in a code object." -msgstr "Retorna o número de variáveis livres em um objeto código." +msgid "" +"Return the number of :term:`free (closure) variables ` in " +"a code object." +msgstr "" +"Retorna o número de :term:`variáveis livres (de clausura) ` em um objeto código." -#: ../../c-api/code.rst:39 -msgid "Return the position of the first free variable in a code object." -msgstr "Retorna a posição da primeira variável livre em um objeto código." +#: ../../c-api/code.rst:40 +msgid "" +"Return the position of the first :term:`free (closure) variable ` in a code object." +msgstr "" +"Retorna a posição da primeira :term:`variável livre (de clausura) ` em um objeto código." -#: ../../c-api/code.rst:43 +#: ../../c-api/code.rst:45 msgid "" "Renamed from ``PyCode_GetFirstFree`` as part of :ref:`unstable-c-api`. The " "old name is deprecated, but will remain available until the signature " @@ -81,7 +87,7 @@ msgstr "" "nome antigo foi descontinuado, mas continuará disponível até que a " "assinatura mude novamente." -#: ../../c-api/code.rst:49 +#: ../../c-api/code.rst:51 msgid "" "Return a new code object. If you need a dummy code object to create a " "frame, use :c:func:`PyCode_NewEmpty` instead." @@ -89,7 +95,7 @@ msgstr "" "Devolve um novo objeto código. Se precisar de um objeto código vazio para " "criar um quadro, use :c:func:`PyCode_NewEmpty`" -#: ../../c-api/code.rst:52 +#: ../../c-api/code.rst:54 msgid "" "Since the definition of the bytecode changes often, calling :c:func:" "`PyUnstable_Code_New` directly can bind you to a precise Python version." @@ -98,7 +104,7 @@ msgstr "" "`PyUnstable_Code_New` diretamente pode vinculá-lo a uma versão de Python " "específica." -#: ../../c-api/code.rst:55 +#: ../../c-api/code.rst:57 msgid "" "The many arguments of this function are inter-dependent in complex ways, " "meaning that subtle changes to values are likely to result in incorrect " @@ -109,11 +115,11 @@ msgstr "" "de resultar em execução incorreta ou erros fatais de VM. Tenha extremo " "cuidado ao usar esta função." -#: ../../c-api/code.rst:59 +#: ../../c-api/code.rst:61 msgid "Added ``qualname`` and ``exceptiontable`` parameters." msgstr "Adicionou os parâmetros ``qualname`` e ``exceptiontable``" -#: ../../c-api/code.rst:66 +#: ../../c-api/code.rst:68 msgid "" "Renamed from ``PyCode_New`` as part of :ref:`unstable-c-api`. The old name " "is deprecated, but will remain available until the signature changes again." @@ -122,7 +128,7 @@ msgstr "" "antigo foi descontinuado, mas continuará disponível até que a assinatura " "mude novamente." -#: ../../c-api/code.rst:72 +#: ../../c-api/code.rst:74 msgid "" "Similar to :c:func:`PyUnstable_Code_New`, but with an extra " "\"posonlyargcount\" for positional-only arguments. The same caveats that " @@ -132,15 +138,15 @@ msgstr "" "extra para argumentos somente-posicionais. As mesmas ressalvas que se " "aplicam a ``PyUnstable_Code_New`` também se aplicam a essa função." -#: ../../c-api/code.rst:77 +#: ../../c-api/code.rst:79 msgid "as ``PyCode_NewWithPosOnlyArgs``" msgstr "Como ``PyCode_NewWithPosOnlyArgs``" -#: ../../c-api/code.rst:79 +#: ../../c-api/code.rst:81 msgid "Added ``qualname`` and ``exceptiontable`` parameters." msgstr "Adicionados os parâmetros ``qualname`` e ``exceptiontable``" -#: ../../c-api/code.rst:84 +#: ../../c-api/code.rst:86 msgid "" "Renamed to ``PyUnstable_Code_NewWithPosOnlyArgs``. The old name is " "deprecated, but will remain available until the signature changes again." @@ -148,7 +154,7 @@ msgstr "" "Renomeado para ``PyUnstable_Code_NewWithPosOnlyArgs``. O nome antigo foi " "descontinuado, mas continuará disponível até que a assinatura mude novamente." -#: ../../c-api/code.rst:90 +#: ../../c-api/code.rst:92 msgid "" "Return a new empty code object with the specified filename, function name, " "and first line number. The resulting code object will raise an ``Exception`` " @@ -158,7 +164,7 @@ msgstr "" "número da primeira linha especificados. O objeto código resultante irá " "levantar uma ``Exception`` se executado." -#: ../../c-api/code.rst:96 +#: ../../c-api/code.rst:98 msgid "" "Return the line number of the instruction that occurs on or before " "``byte_offset`` and ends after it. If you just need the line number of a " @@ -168,17 +174,16 @@ msgstr "" "``byte_offset`` e termina depois disso. Se você só precisa do número da " "linha de um quadro, use :c:func:`PyFrame_GetLineNumber`." -#: ../../c-api/code.rst:99 +#: ../../c-api/code.rst:101 msgid "" -"For efficiently iterating over the line numbers in a code object, use `the " -"API described in PEP 626 `_." +"For efficiently iterating over the line numbers in a code object, use :pep:" +"`the API described in PEP 626 <0626#out-of-process-debuggers-and-profilers>`." msgstr "" "Para iterar eficientemente sobre os números de linha em um objeto código, " -"use `a API descrita em PEP 626 `_ ." +"use :pep:`a API descrita na PEP 626 <0626#out-of-process-debuggers-and-" +"profilers>` ." -#: ../../c-api/code.rst:104 +#: ../../c-api/code.rst:106 msgid "" "Sets the passed ``int`` pointers to the source code line and column numbers " "for the instruction at ``byte_offset``. Sets the value to ``0`` when " @@ -189,11 +194,11 @@ msgstr "" "``0`` quando as informações não estão disponíveis para nenhum elemento em " "particular." -#: ../../c-api/code.rst:108 +#: ../../c-api/code.rst:110 msgid "Returns ``1`` if the function succeeds and 0 otherwise." msgstr "Retorna ``1`` se a função for bem-sucedida e 0 caso contrário." -#: ../../c-api/code.rst:114 +#: ../../c-api/code.rst:116 msgid "" "Equivalent to the Python code ``getattr(co, 'co_code')``. Returns a strong " "reference to a :c:type:`PyBytesObject` representing the bytecode in a code " @@ -204,7 +209,7 @@ msgstr "" "objeto código. Em caso de erro, ``NULL`` é retornado e uma exceção é " "levantada." -#: ../../c-api/code.rst:119 +#: ../../c-api/code.rst:121 msgid "" "This ``PyBytesObject`` may be created on-demand by the interpreter and does " "not necessarily represent the bytecode actually executed by CPython. The " @@ -214,7 +219,7 @@ msgstr "" "representa necessariamente o bytecode realmente executado pelo CPython. O " "caso de uso primário para esta função são depuradores e criadores de perfil." -#: ../../c-api/code.rst:127 +#: ../../c-api/code.rst:129 msgid "" "Equivalent to the Python code ``getattr(co, 'co_varnames')``. Returns a new " "reference to a :c:type:`PyTupleObject` containing the names of the local " @@ -224,7 +229,7 @@ msgstr "" "nova referência a um :c:type:`PyTupleObject` contendo os nomes das variáveis " "locais. Em caso de erro, ``NULL`` é retornado e uma exceção é levantada." -#: ../../c-api/code.rst:136 +#: ../../c-api/code.rst:138 msgid "" "Equivalent to the Python code ``getattr(co, 'co_cellvars')``. Returns a new " "reference to a :c:type:`PyTupleObject` containing the names of the local " @@ -236,17 +241,19 @@ msgstr "" "locais referenciadas por funções aninhadas. Em caso de erro, ``NULL`` é " "retornado e uma exceção é levantada." -#: ../../c-api/code.rst:145 +#: ../../c-api/code.rst:147 msgid "" "Equivalent to the Python code ``getattr(co, 'co_freevars')``. Returns a new " -"reference to a :c:type:`PyTupleObject` containing the names of the free " -"variables. On error, ``NULL`` is returned and an exception is raised." +"reference to a :c:type:`PyTupleObject` containing the names of the :term:" +"`free (closure) variables `. On error, ``NULL`` is " +"returned and an exception is raised." msgstr "" "Equivalente ao código Python ``getattr(co, 'co_freevars')``. Retorna uma " -"nova referência a um :c:type:`PyTupleObject` contendo os nomes das variáveis " -"livres. Em caso de erro, ``NULL`` é retornado e uma exceção é levantada." +"nova referência a um :c:type:`PyTupleObject` contendo os nomes das :term:" +"`variáveis livres (de clausura) `. Em caso de erro, " +"``NULL`` é retornado e uma exceção é levantada." -#: ../../c-api/code.rst:153 +#: ../../c-api/code.rst:156 msgid "" "Register *callback* as a code object watcher for the current interpreter. " "Return an ID which may be passed to :c:func:`PyCode_ClearWatcher`. In case " @@ -258,7 +265,7 @@ msgstr "" "`PyCode_ClearWatcher`. Em caso de erro (por exemplo, não há IDs de " "observadores disponíveis), devolve ``-1`` e define uma exceção." -#: ../../c-api/code.rst:162 +#: ../../c-api/code.rst:165 msgid "" "Clear watcher identified by *watcher_id* previously returned from :c:func:" "`PyCode_AddWatcher` for the current interpreter. Return ``0`` on success, or " @@ -270,7 +277,7 @@ msgstr "" "caso de sucesso ou ``-1`` em caso de erro e levanta uma exceção (ex., se o " "*watcher_id* dado não foi registrado.)" -#: ../../c-api/code.rst:171 +#: ../../c-api/code.rst:174 msgid "" "Enumeration of possible code object watcher events: - " "``PY_CODE_EVENT_CREATE`` - ``PY_CODE_EVENT_DESTROY``" @@ -278,11 +285,11 @@ msgstr "" "Enumeração dos possíveis eventos de observador do objeto código: " "``PY_CODE_EVENT_CREATE`` - ``PY_CODE_EVENT_DESTROY``" -#: ../../c-api/code.rst:179 +#: ../../c-api/code.rst:182 msgid "Type of a code object watcher callback function." msgstr "Tipo de uma função de callback de observador de objeto código." -#: ../../c-api/code.rst:181 +#: ../../c-api/code.rst:184 msgid "" "If *event* is ``PY_CODE_EVENT_CREATE``, then the callback is invoked after " "`co` has been fully initialized. Otherwise, the callback is invoked before " @@ -294,7 +301,7 @@ msgstr "" "invocada antes que a destruição de `co` ocorra, para que o estado anterior " "de *co* possa ser inspecionado." -#: ../../c-api/code.rst:186 +#: ../../c-api/code.rst:189 msgid "" "If *event* is ``PY_CODE_EVENT_DESTROY``, taking a reference in the callback " "to the about-to-be-destroyed code object will resurrect it and prevent it " @@ -307,7 +314,7 @@ msgstr "" "qualquer observador de funções de retorno ativos naquele momento serão " "chamados novamente." -#: ../../c-api/code.rst:191 +#: ../../c-api/code.rst:194 msgid "" "Users of this API should not rely on internal runtime implementation " "details. Such details may include, but are not limited to, the exact order " @@ -323,17 +330,17 @@ msgstr "" "visíveis para os observadores (incluindo se uma função de retorno é chamada " "ou não), isso não muda a semântica do código Python executado." -#: ../../c-api/code.rst:198 +#: ../../c-api/code.rst:201 msgid "" "If the callback sets an exception, it must return ``-1``; this exception " "will be printed as an unraisable exception using :c:func:" "`PyErr_WriteUnraisable`. Otherwise it should return ``0``." msgstr "" -"Se a função de retorno definir uma exceção, ela deverá retornar ``-1``; essa " -"exceção será impressa como uma exceção não reprovável usando :c:func:" +"Se a função de retorno definir uma exceção, ela deverá retornar ``-1``. Essa " +"exceção será exibida como uma exceção não levantável usando :c:func:" "`PyErr_WriteUnraisable`. Caso contrário, deverá retornar ``0``." -#: ../../c-api/code.rst:202 +#: ../../c-api/code.rst:205 msgid "" "There may already be a pending exception set on entry to the callback. In " "this case, the callback should return ``0`` with the same exception still " @@ -345,13 +352,13 @@ msgstr "" "de retorno. Nesse caso, a função de retorno deve retornar ``0`` com a mesma " "exceção ainda definida. Isso significa que a função de retorno não pode " "chamar nenhuma outra API que possa definir uma exceção, a menos que salve e " -"limpe o estado da exceção primeiro e o restaure antes de retornar." +"limpe o estado da exceção primeiro e restaure a exceção antes de retornar." -#: ../../c-api/code.rst:212 +#: ../../c-api/code.rst:215 msgid "Extra information" msgstr "Informação adicional" -#: ../../c-api/code.rst:214 +#: ../../c-api/code.rst:217 msgid "" "To support low-level extensions to frame evaluation, such as external just-" "in-time compilers, it is possible to attach arbitrary extra data to code " @@ -361,7 +368,7 @@ msgstr "" "como compiladores \"just-in-time\", é possível anexar dados arbitrários " "adicionais a objetos código." -#: ../../c-api/code.rst:218 +#: ../../c-api/code.rst:221 msgid "" "These functions are part of the unstable C API tier: this functionality is a " "CPython implementation detail, and the API may change without deprecation " @@ -371,13 +378,13 @@ msgstr "" "um detalhe de implementação do CPython, e a API pode mudar sem avisos de " "descontinuidade." -#: ../../c-api/code.rst:224 +#: ../../c-api/code.rst:227 msgid "Return a new an opaque index value used to adding data to code objects." msgstr "" "Retorna um novo e opaco valor de índice usado para adicionar dados a objetos " "código." -#: ../../c-api/code.rst:226 +#: ../../c-api/code.rst:229 msgid "" "You generally call this function once (per interpreter) and use the result " "with ``PyCode_GetExtra`` and ``PyCode_SetExtra`` to manipulate data on " @@ -387,7 +394,7 @@ msgstr "" "o resultado com ``PyCode_GetExtra`` e ``PyCode_SetExtra`` para manipular " "dados em objetos código individuais." -#: ../../c-api/code.rst:230 +#: ../../c-api/code.rst:233 msgid "" "If *free* is not ``NULL``: when a code object is deallocated, *free* will be " "called on non-``NULL`` data stored under the new index. Use :c:func:" @@ -397,11 +404,11 @@ msgstr "" "chamado em dados não-``NULL`` armazenados sob o novo índice. Use :c:func:" "`Py_DecRef` quando armazenar :c:type:`PyObject`." -#: ../../c-api/code.rst:236 +#: ../../c-api/code.rst:239 msgid "as ``_PyEval_RequestCodeExtraIndex``" msgstr "como ``_PyEval_RequestCodeExtraIndex``" -#: ../../c-api/code.rst:240 +#: ../../c-api/code.rst:243 msgid "" "Renamed to ``PyUnstable_Eval_RequestCodeExtraIndex``. The old private name " "is deprecated, but will be available until the API changes." @@ -409,7 +416,7 @@ msgstr "" "Renomeado para ``PyUnstable_Eval_RequestCodeExtraIndex``. O nome antigo nome " "privado foi descontinuado, mas continuará disponível até a mudança da API." -#: ../../c-api/code.rst:246 +#: ../../c-api/code.rst:249 msgid "" "Set *extra* to the extra data stored under the given index. Return 0 on " "success. Set an exception and return -1 on failure." @@ -418,7 +425,7 @@ msgstr "" "Retorna 0 em caso de sucesso. Define uma exceção e retorna -1 em caso de " "erro." -#: ../../c-api/code.rst:249 +#: ../../c-api/code.rst:252 msgid "" "If no data was set under the index, set *extra* to ``NULL`` and return 0 " "without setting an exception." @@ -426,11 +433,11 @@ msgstr "" "Se nenhum dado foi determinado sob o índice, define *extra* como ``NULL`` e " "retorna 0 sem definir nenhuma exceção." -#: ../../c-api/code.rst:254 +#: ../../c-api/code.rst:257 msgid "as ``_PyCode_GetExtra``" msgstr "como ``_PyCode_GetExtra``" -#: ../../c-api/code.rst:258 +#: ../../c-api/code.rst:261 msgid "" "Renamed to ``PyUnstable_Code_GetExtra``. The old private name is deprecated, " "but will be available until the API changes." @@ -438,7 +445,7 @@ msgstr "" "Renomeado para ``PyUnstable_Code_GetExtra``. O nome antigo privado foi " "descontinuado, mas continuará disponível até a mudança da API." -#: ../../c-api/code.rst:264 +#: ../../c-api/code.rst:267 msgid "" "Set the extra data stored under the given index to *extra*. Return 0 on " "success. Set an exception and return -1 on failure." @@ -446,11 +453,11 @@ msgstr "" "Define os dados extras armazenados sob o índice dado a *extra*. Retorna 0 em " "caso de sucesso. Define uma exceção e retorna -1 em caso de erro." -#: ../../c-api/code.rst:269 +#: ../../c-api/code.rst:272 msgid "as ``_PyCode_SetExtra``" msgstr "como ``_PyCode_SetExtra``" -#: ../../c-api/code.rst:273 +#: ../../c-api/code.rst:276 msgid "" "Renamed to ``PyUnstable_Code_SetExtra``. The old private name is deprecated, " "but will be available until the API changes." @@ -470,22 +477,22 @@ msgstr "código" msgid "code object" msgstr "objeto código" -#: ../../c-api/code.rst:62 +#: ../../c-api/code.rst:64 msgid "PyCode_New (C function)" msgstr "PyCode_New (função C)" -#: ../../c-api/code.rst:75 +#: ../../c-api/code.rst:77 msgid "PyCode_NewWithPosOnlyArgs (C function)" msgstr "PyCode_NewWithPosOnlyArgs (função C)" -#: ../../c-api/code.rst:234 +#: ../../c-api/code.rst:237 msgid "_PyEval_RequestCodeExtraIndex (C function)" msgstr "_PyEval_RequestCodeExtraIndex (função C)" -#: ../../c-api/code.rst:252 +#: ../../c-api/code.rst:255 msgid "_PyCode_GetExtra (C function)" msgstr "_PyCode_GetExtra (função C)" -#: ../../c-api/code.rst:267 +#: ../../c-api/code.rst:270 msgid "_PyCode_SetExtra (C function)" msgstr "_PyCode_SetExtra (função C)" diff --git a/c-api/codec.po b/c-api/codec.po index a8579e56e..9149c1e42 100644 --- a/c-api/codec.po +++ b/c-api/codec.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2024 -# Tiago Henrique , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/complex.po b/c-api/complex.po index 9d8cc6d8b..c4b28f80a 100644 --- a/c-api/complex.po +++ b/c-api/complex.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Renan Lopes , 2021 -# Marco Rougeth , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -71,6 +69,18 @@ msgstr "" msgid "The structure is defined as::" msgstr "A estrutura é definida como::" +#: ../../c-api/complex.rst:35 +msgid "" +"typedef struct {\n" +" double real;\n" +" double imag;\n" +"} Py_complex;" +msgstr "" +"typedef struct {\n" +" double real;\n" +" double imag;\n" +"} Py_complex;" + #: ../../c-api/complex.rst:43 msgid "" "Return the sum of two complex numbers, using the C :c:type:`Py_complex` " diff --git a/c-api/concrete.po b/c-api/concrete.po index 262d9aa78..3ccd95448 100644 --- a/c-api/concrete.po +++ b/c-api/concrete.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Vinicius Gubiani Ferreira , 2023 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -93,7 +91,7 @@ msgstr "Coleções" #: ../../c-api/concrete.rst:91 msgid "Function Objects" -msgstr "Objetos Função" +msgstr "Objetos Function" #: ../../c-api/concrete.rst:102 msgid "Other Objects" diff --git a/c-api/contextvars.po b/c-api/contextvars.po index 821ce8863..25656918a 100644 --- a/c-api/contextvars.po +++ b/c-api/contextvars.po @@ -1,35 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Vinicius Gubiani Ferreira , 2021 -# Alexsandro Matias de Almeida , 2021 -# Leandro Braga , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Leandro Braga , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../c-api/contextvars.rst:6 msgid "Context Variables Objects" -msgstr "Objetos de variáveis ​​de contexto" +msgstr "Objetos de variáveis de contexto" #: ../../c-api/contextvars.rst:15 msgid "" @@ -41,6 +37,20 @@ msgstr "" "foram **alteradas** para usar ponteiros :c:type:`PyObject` em vez de :c:type:" "`PyContext`, :c:type:`PyContextVar` e :c:type:`PyContextToken`. Por exemplo::" +#: ../../c-api/contextvars.rst:20 +msgid "" +"// in 3.7.0:\n" +"PyContext *PyContext_New(void);\n" +"\n" +"// in 3.7.1+:\n" +"PyObject *PyContext_New(void);" +msgstr "" +"// no 3.7.0:\n" +"PyContext *PyContext_New(void);\n" +"\n" +"// no 3.7.1+:\n" +"PyObject *PyContext_New(void);" + #: ../../c-api/contextvars.rst:26 msgid "See :issue:`34762` for more details." msgstr "Veja :issue:`34762` para mais detalhes." diff --git a/c-api/conversion.po b/c-api/conversion.po index b8b20373c..714507c36 100644 --- a/c-api/conversion.po +++ b/c-api/conversion.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/coro.po b/c-api/coro.po index 3b617dc55..1f2a2e5d5 100644 --- a/c-api/coro.po +++ b/c-api/coro.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/datetime.po b/c-api/datetime.po index 87149f4a9..61b38ae32 100644 --- a/c-api/datetime.po +++ b/c-api/datetime.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Adjamilton Júnior , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2022 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2022\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -39,42 +37,63 @@ msgid "" "structure into a static variable, :c:data:`!PyDateTimeAPI`, that is used by " "the following macros." msgstr "" +"Vários objetos de data e hora são fornecidos pelo módulo :mod:`datetime`. " +"Antes de usar qualquer uma dessas funções, o arquivo de cabeçalho :file:" +"`datetime.h` deve ser incluído na sua fonte (observe que isso não é incluído " +"por :file:`Python.h`) e a macro :c:macro:`!PyDateTime_IMPORT` deve ser " +"chamada, geralmente como parte da função de inicialização do módulo. A macro " +"coloca um ponteiro para uma estrutura C em uma variável estática, :c:data:`!" +"PyDateTimeAPI`, usada pelas macros a seguir." #: ../../c-api/datetime.rst:18 msgid "This subtype of :c:type:`PyObject` represents a Python date object." msgstr "" +"Esta é uma instância de :c:type:`PyObject` representando o objeto data do " +"Python." #: ../../c-api/datetime.rst:22 msgid "This subtype of :c:type:`PyObject` represents a Python datetime object." msgstr "" +"Esta é uma instância de :c:type:`PyObject` representando o objeto datetime " +"do Python." #: ../../c-api/datetime.rst:26 msgid "This subtype of :c:type:`PyObject` represents a Python time object." msgstr "" +"Esta é uma instância de :c:type:`PyObject` representando o objeto hora do " +"Python." #: ../../c-api/datetime.rst:30 msgid "" "This subtype of :c:type:`PyObject` represents the difference between two " "datetime values." msgstr "" +"Esta é uma instância de :c:type:`PyObject` representando a diferença entre " +"dois valores de datetime." #: ../../c-api/datetime.rst:34 msgid "" "This instance of :c:type:`PyTypeObject` represents the Python date type; it " "is the same object as :class:`datetime.date` in the Python layer." msgstr "" +"Esta instância de :c:type:`PyTypeObject` representa o tipo data do Python; é " +"o mesmo objeto que :class:`datetime.date` na camada de Python." #: ../../c-api/datetime.rst:39 msgid "" "This instance of :c:type:`PyTypeObject` represents the Python datetime type; " "it is the same object as :class:`datetime.datetime` in the Python layer." msgstr "" +"Esta instância de :c:type:`PyTypeObject` representa o tipo datetime do " +"Python; é o mesmo objeto que :class:`datetime.datetime` na camada de Python." #: ../../c-api/datetime.rst:44 msgid "" "This instance of :c:type:`PyTypeObject` represents the Python time type; it " "is the same object as :class:`datetime.time` in the Python layer." msgstr "" +"Esta instância de :c:type:`PyTypeObject` representa o tipo hora do Python; é " +"o mesmo objeto que :class:`datetime.time` na camada de Python." #: ../../c-api/datetime.rst:49 msgid "" @@ -82,12 +101,17 @@ msgid "" "difference between two datetime values; it is the same object as :class:" "`datetime.timedelta` in the Python layer." msgstr "" +"Esta instância de :c:type:`PyTypeObject` representa o tipo Python para a " +"diferença entre dois valores de datetime; é o mesmo objeto que :class:" +"`datetime.timedelta` na camada de Python." #: ../../c-api/datetime.rst:55 msgid "" "This instance of :c:type:`PyTypeObject` represents the Python time zone info " "type; it is the same object as :class:`datetime.tzinfo` in the Python layer." msgstr "" +"Esta instância de :c:type:`PyTypeObject` representa o tipo fuso horário do " +"Python; é o mesmo objeto que :class:`datetime.tzinfo` na camada de Python." #: ../../c-api/datetime.rst:59 msgid "Macro for access to the UTC singleton:" @@ -111,14 +135,17 @@ msgid "" "of :c:data:`!PyDateTime_DateType`. *ob* must not be ``NULL``. This " "function always succeeds." msgstr "" +"Retorna verdadeiro se *ob* for do tipo :c:data:`PyDateTime_DateType` ou um " +"subtipo de :c:data:`!PyDateTime_DateType`. *ob* não deve ser ``NULL``. Esta " +"função sempre tem sucesso." #: ../../c-api/datetime.rst:80 msgid "" "Return true if *ob* is of type :c:data:`PyDateTime_DateType`. *ob* must not " "be ``NULL``. This function always succeeds." msgstr "" -"Retorna true se *ob* for do tipo :c:data:`PyDateTime_DateType`. *ob* não " -"deve ser ``NULL``. Esta função sempre tem sucesso." +"Retorna verdadeiro se *ob* for do tipo :c:data:`PyDateTime_DateType`. *ob* " +"não deve ser ``NULL``. Esta função sempre tem sucesso." #: ../../c-api/datetime.rst:86 msgid "" @@ -126,14 +153,17 @@ msgid "" "subtype of :c:data:`!PyDateTime_DateTimeType`. *ob* must not be ``NULL``. " "This function always succeeds." msgstr "" +"Retorna verdadeiro se *ob* é do tipo :c:data:`PyDateTime_DateTimeType` ou um " +"subtipo de :c:data:`!PyDateTime_DateTimeType`. *ob* não deve ser ``NULL``. " +"Esta função sempre tem sucesso." #: ../../c-api/datetime.rst:93 msgid "" "Return true if *ob* is of type :c:data:`PyDateTime_DateTimeType`. *ob* must " "not be ``NULL``. This function always succeeds." msgstr "" -"Retorna true se *ob* for do tipo :c:data:`PyDateTime_DateTimeType`. *ob* não " -"deve ser ``NULL``. Esta função sempre tem sucesso." +"Retorna verdadeiro se *ob* for do tipo :c:data:`PyDateTime_DateTimeType`. " +"*ob* não deve ser ``NULL``. Esta função sempre tem sucesso." #: ../../c-api/datetime.rst:99 msgid "" @@ -141,14 +171,17 @@ msgid "" "of :c:data:`!PyDateTime_TimeType`. *ob* must not be ``NULL``. This " "function always succeeds." msgstr "" +"Retorna verdadeiro se *ob* é do tipo :c:data:`PyDateTime_TimeType` ou um " +"subtipo de :c:data:`!PyDateTime_TimeType`. *ob* não deve ser ``NULL``. Esta " +"função sempre tem sucesso." #: ../../c-api/datetime.rst:106 msgid "" "Return true if *ob* is of type :c:data:`PyDateTime_TimeType`. *ob* must not " "be ``NULL``. This function always succeeds." msgstr "" -"Retorna true se *ob* for do tipo :c:data:`PyDateTime_TimeType`. *ob* não " -"deve ser ``NULL``. Esta função sempre tem sucesso." +"Retorna verdadeiro se *ob* for do tipo :c:data:`PyDateTime_TimeType`. *ob* " +"não deve ser ``NULL``. Esta função sempre tem sucesso." #: ../../c-api/datetime.rst:112 msgid "" @@ -156,14 +189,17 @@ msgid "" "of :c:data:`!PyDateTime_DeltaType`. *ob* must not be ``NULL``. This " "function always succeeds." msgstr "" +"Retorna verdadeiro se *ob* for do tipo :c:data:`PyDateTime_DeltaType` ou um " +"subtipo de :c:data:`!PyDateTime_DeltaType`. *ob* não pode ser ``NULL``. Esta " +"função sempre tem sucesso." #: ../../c-api/datetime.rst:119 msgid "" "Return true if *ob* is of type :c:data:`PyDateTime_DeltaType`. *ob* must not " "be ``NULL``. This function always succeeds." msgstr "" -"Retorna true se *ob* for do tipo :c:data:`PyDateTime_DeltaType`. *ob* não " -"deve ser ``NULL``. Esta função sempre tem sucesso." +"Retorna verdadeiro se *ob* for do tipo :c:data:`PyDateTime_DeltaType`. *ob* " +"não deve ser ``NULL``. Esta função sempre tem sucesso." #: ../../c-api/datetime.rst:125 msgid "" @@ -171,14 +207,17 @@ msgid "" "of :c:data:`!PyDateTime_TZInfoType`. *ob* must not be ``NULL``. This " "function always succeeds." msgstr "" +"Retorna verdadeiro se *ob* for do tipo :c:data:`PyDateTime_TZInfoType` ou um " +"subtipo de :c:data:`!PyDateTime_TZInfoType`. *ob* não pode ser ``NULL``. " +"Esta função sempre tem sucesso." #: ../../c-api/datetime.rst:132 msgid "" "Return true if *ob* is of type :c:data:`PyDateTime_TZInfoType`. *ob* must " "not be ``NULL``. This function always succeeds." msgstr "" -"Retorna true se *ob* for do tipo :c:data:`PyDateTime_TZInfoType`. *ob* não " -"deve ser ``NULL``. Esta função sempre tem sucesso." +"Retorna verdadeiro se *ob* for do tipo :c:data:`PyDateTime_TZInfoType`. *ob* " +"não deve ser ``NULL``. Esta função sempre tem sucesso." #: ../../c-api/datetime.rst:136 msgid "Macros to create objects:" @@ -258,6 +297,10 @@ msgid "" "`PyDateTime_DateTime`). The argument must not be ``NULL``, and the type is " "not checked:" msgstr "" +"Macros para extrair campos de objetos *date*. O argumento deve ser uma " +"instância de :c:type:`PyDateTime_Date`, inclusive subclasses (como :c:type:" +"`PyDateTime_DateTime`). O argumento não deve ser ``NULL``, e o tipo não é " +"verificado:" #: ../../c-api/datetime.rst:202 msgid "Return the year, as a positive int." @@ -277,6 +320,9 @@ msgid "" "instance of :c:type:`PyDateTime_DateTime`, including subclasses. The " "argument must not be ``NULL``, and the type is not checked:" msgstr "" +"Macros para extrair campos de objetos *datetime*. O argumento deve ser uma " +"instância de :c:type:`PyDateTime_DateTime`, inclusive subclasses. O " +"argumento não deve ser ``NULL``, e o tipo não é verificado:" #: ../../c-api/datetime.rst:221 ../../c-api/datetime.rst:259 msgid "Return the hour, as an int from 0 through 23." @@ -308,6 +354,9 @@ msgid "" "instance of :c:type:`PyDateTime_Time`, including subclasses. The argument " "must not be ``NULL``, and the type is not checked:" msgstr "" +"Macros para extrair campos de objetos *time*. O argumento deve ser uma " +"instância de :c:type:`PyDateTime_Time`, inclusive subclasses. O argumento " +"não deve ser ``NULL``, e o tipo não é verificado:" #: ../../c-api/datetime.rst:291 msgid "" @@ -315,6 +364,9 @@ msgid "" "instance of :c:type:`PyDateTime_Delta`, including subclasses. The argument " "must not be ``NULL``, and the type is not checked:" msgstr "" +"Macros para extrair campos de objetos *time delta*. O argumento deve ser uma " +"instância de :c:type:`PyDateTime_Delta`, inclusive subclasses. O argumento " +"não deve ser ``NULL``, e o tipo não é verificado:" #: ../../c-api/datetime.rst:297 msgid "Return the number of days, as an int from -999999999 to 999999999." @@ -335,16 +387,17 @@ msgstr "Macros para a conveniência de módulos implementando a API de DB:" #: ../../c-api/datetime.rst:320 msgid "" "Create and return a new :class:`datetime.datetime` object given an argument " -"tuple suitable for passing to :meth:`datetime.datetime.fromtimestamp()`." +"tuple suitable for passing to :meth:`datetime.datetime.fromtimestamp`." msgstr "" -"Cria e retorna um novo objeto :class:`datetime.datetime`, com uma tupla de " -"argumentos adequada para passar para :meth:`datetime.datetime." -"fromtimestamp()`." +"Cria e retorna um novo objeto :class:`datetime.datetime` dado uma tupla de " +"argumentos que possa ser passada ao método :meth:`datetime.datetime." +"fromtimestamp`." #: ../../c-api/datetime.rst:326 msgid "" "Create and return a new :class:`datetime.date` object given an argument " -"tuple suitable for passing to :meth:`datetime.date.fromtimestamp()`." +"tuple suitable for passing to :meth:`datetime.date.fromtimestamp`." msgstr "" -"Cria e retorna um novo objeto :class:`datetime.date`, com uma tupla de " -"argumentos adequada para passar para :meth:`datetime.date.fromtimestamp()`." +"Cria e retorna um novo objeto :class:`datetime.date` dado uma tupla de " +"argumentos que possa ser passada ao método :meth:`datetime.date." +"fromtimestamp`." diff --git a/c-api/descriptor.po b/c-api/descriptor.po index 4f911099c..9ff4c53bf 100644 --- a/c-api/descriptor.po +++ b/c-api/descriptor.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/dict.po b/c-api/dict.po index c275b56f9..3a991dddd 100644 --- a/c-api/dict.po +++ b/c-api/dict.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Aline Balogh , 2021 -# felipe caridade fernandes , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-28 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -239,9 +236,8 @@ msgstr "" #: ../../c-api/dict.rst:159 msgid "" -"Similar than :c:func:`PyDict_GetItemRef`, but *key* is specified as a :c:" -"expr:`const char*` UTF-8 encoded bytes string, rather than a :c:expr:" -"`PyObject*`." +"Similar to :c:func:`PyDict_GetItemRef`, but *key* is specified as a :c:expr:" +"`const char*` UTF-8 encoded bytes string, rather than a :c:expr:`PyObject*`." msgstr "" "Similar a :c:func:`PyDict_GetItemRef`, mas *key* é especificada como uma " "string de bytes :c:expr:`const char*` codificada em UTF-8, em vez de um :c:" @@ -321,11 +317,11 @@ msgstr "" #: ../../c-api/dict.rst:209 msgid "" -"This is similar to :meth:`dict.pop`, but without the default value and not " -"raising :exc:`KeyError` if the key missing." +"Similar to :meth:`dict.pop`, but without the default value and not raising :" +"exc:`KeyError` if the key missing." msgstr "" -"Isto é semelhante a :meth:`dict.pop`, mas sem o valor padrão e sem levantar :" -"exc:`KeyError` se a chave estiver ausente." +"Similar a :meth:`dict.pop`, mas sem o valor padrão e sem levantar :exc:" +"`KeyError` se a chave estiver ausente." #: ../../c-api/dict.rst:217 msgid "" @@ -392,6 +388,24 @@ msgstr "" msgid "For example::" msgstr "Por exemplo::" +#: ../../c-api/dict.rst:263 +msgid "" +"PyObject *key, *value;\n" +"Py_ssize_t pos = 0;\n" +"\n" +"while (PyDict_Next(self->dict, &pos, &key, &value)) {\n" +" /* do something interesting with the values... */\n" +" ...\n" +"}" +msgstr "" +"PyObject *key, *value;\n" +"Py_ssize_t pos = 0;\n" +"\n" +"while (PyDict_Next(self->dict, &pos, &key, &value)) {\n" +" /* fazer algo de interessante com os valores... */\n" +" ...\n" +"}" + #: ../../c-api/dict.rst:271 msgid "" "The dictionary *p* should not be mutated during iteration. It is safe to " @@ -402,6 +416,44 @@ msgstr "" "modificar os valores das chaves à medida que você itera no dicionário, mas " "apenas enquanto o conjunto de chaves não mudar. Por exemplo::" +#: ../../c-api/dict.rst:275 +msgid "" +"PyObject *key, *value;\n" +"Py_ssize_t pos = 0;\n" +"\n" +"while (PyDict_Next(self->dict, &pos, &key, &value)) {\n" +" long i = PyLong_AsLong(value);\n" +" if (i == -1 && PyErr_Occurred()) {\n" +" return -1;\n" +" }\n" +" PyObject *o = PyLong_FromLong(i + 1);\n" +" if (o == NULL)\n" +" return -1;\n" +" if (PyDict_SetItem(self->dict, key, o) < 0) {\n" +" Py_DECREF(o);\n" +" return -1;\n" +" }\n" +" Py_DECREF(o);\n" +"}" +msgstr "" +"PyObject *key, *value;\n" +"Py_ssize_t pos = 0;\n" +"\n" +"while (PyDict_Next(self->dict, &pos, &key, &value)) {\n" +" long i = PyLong_AsLong(value);\n" +" if (i == -1 && PyErr_Occurred()) {\n" +" return -1;\n" +" }\n" +" PyObject *o = PyLong_FromLong(i + 1);\n" +" if (o == NULL)\n" +" return -1;\n" +" if (PyDict_SetItem(self->dict, key, o) < 0) {\n" +" Py_DECREF(o);\n" +" return -1;\n" +" }\n" +" Py_DECREF(o);\n" +"}" + #: ../../c-api/dict.rst:293 msgid "" "The function is not thread-safe in the :term:`free-threaded dict);\n" +"while (PyDict_Next(self->dict, &pos, &key, &value)) {\n" +" ...\n" +"}\n" +"Py_END_CRITICAL_SECTION();" +msgstr "" +"Py_BEGIN_CRITICAL_SECTION(self->dict);\n" +"while (PyDict_Next(self->dict, &pos, &key, &value)) {\n" +" ...\n" +"}\n" +"Py_END_CRITICAL_SECTION();" + #: ../../c-api/dict.rst:307 msgid "" "Iterate over mapping object *b* adding key-value pairs to dictionary *a*. " @@ -459,6 +525,18 @@ msgstr "" "vence. Retorne ``0`` em caso de sucesso ou ``-1`` se uma exceção foi " "levantada. Python equivalente (exceto para o valor de retorno)::" +#: ../../c-api/dict.rst:333 +msgid "" +"def PyDict_MergeFromSeq2(a, seq2, override):\n" +" for key, value in seq2:\n" +" if override or key not in a:\n" +" a[key] = value" +msgstr "" +"def PyDict_MergeFromSeq2(a, seq2, override):\n" +" for key, value in seq2:\n" +" if override or key not in a:\n" +" a[key] = value" + #: ../../c-api/dict.rst:340 msgid "" "Register *callback* as a dictionary watcher. Return a non-negative integer " @@ -587,8 +665,8 @@ msgid "" "will be printed as an unraisable exception using :c:func:" "`PyErr_WriteUnraisable`. Otherwise it should return ``0``." msgstr "" -"Se a função de retorno definir uma exceção, ela deverá retornar ``-1``; essa " -"exceção será impressa como uma exceção não reprovável usando :c:func:" +"Se a função de retorno definir uma exceção, ela deverá retornar ``-1``. Essa " +"exceção será exibida como uma exceção não levantável usando :c:func:" "`PyErr_WriteUnraisable`. Caso contrário, deverá retornar ``0``." #: ../../c-api/dict.rst:413 @@ -603,7 +681,7 @@ msgstr "" "de retorno. Nesse caso, a função de retorno deve retornar ``0`` com a mesma " "exceção ainda definida. Isso significa que a função de retorno não pode " "chamar nenhuma outra API que possa definir uma exceção, a menos que salve e " -"limpe o estado da exceção primeiro e o restaure antes de retornar." +"limpe o estado da exceção primeiro e restaure a exceção antes de retornar." #: ../../c-api/dict.rst:8 msgid "object" diff --git a/c-api/exceptions.po b/c-api/exceptions.po index dfa0d4a29..daa07d797 100644 --- a/c-api/exceptions.po +++ b/c-api/exceptions.po @@ -1,36 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Alexsandro Matias de Almeida , 2021 -# Misael borges , 2021 -# Richard Nixon , 2021 -# Renan Lopes , 2021 -# a76d6fb6142d7607ab0526dcbddb02d7_7bf0da0 <3b5fb0f281c8dfb4c0170f2ee2a6cfcf_843623>, 2021 -# i17obot , 2022 -# Marco Rougeth , 2023 -# Flávio Neves, 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# Leonardo Rodrigues da Costa, 2023 -# Guilherme Alves da Silva, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -99,15 +88,11 @@ msgstr "" #: ../../c-api/exceptions.rst:37 msgid "" -"The error indicator is **not** the result of :func:`sys.exc_info()`. The " +"The error indicator is **not** the result of :func:`sys.exc_info`. The " "former corresponds to an exception that is not yet caught (and is therefore " "still propagating), while the latter returns an exception after it is caught " "(and has therefore stopped propagating)." msgstr "" -"O indicador de erro **not** é resultado de :func:`sys.exc_info()`. O " -"primeiro corresponde a uma exceção que ainda não foi capturada (e, portanto, " -"ainda está se propagando), enquanto o segundo retorna uma exceção após ser " -"capturada (e, portanto, parou de se propagar)." #: ../../c-api/exceptions.rst:44 msgid "Printing and clearing" @@ -327,8 +312,8 @@ msgstr "" #: ../../c-api/exceptions.rst:234 ../../c-api/exceptions.rst:242 #: ../../c-api/exceptions.rst:253 ../../c-api/exceptions.rst:263 #: ../../c-api/exceptions.rst:271 ../../c-api/exceptions.rst:281 -msgid ":ref:`Availability `: Windows." -msgstr ":ref:`Disponibilidade `: Windows." +msgid "Availability" +msgstr "Disponibilidade" #: ../../c-api/exceptions.rst:239 msgid "" @@ -544,6 +529,17 @@ msgstr "" msgid "For example::" msgstr "Por exemplo::" +#: ../../c-api/exceptions.rst:451 +msgid "" +"{\n" +" PyObject *exc = PyErr_GetRaisedException();\n" +"\n" +" /* ... code that might produce other errors ... */\n" +"\n" +" PyErr_SetRaisedException(exc);\n" +"}" +msgstr "" + #: ../../c-api/exceptions.rst:459 msgid "" ":c:func:`PyErr_GetHandledException`, to save the exception currently being " @@ -579,6 +575,18 @@ msgid "" "exceptions or save and restore the error indicator temporarily." msgstr "" +#: ../../c-api/exceptions.rst:495 +msgid "" +"{\n" +" PyObject *type, *value, *traceback;\n" +" PyErr_Fetch(&type, &value, &traceback);\n" +"\n" +" /* ... code that might produce other errors ... */\n" +"\n" +" PyErr_Restore(type, value, traceback);\n" +"}" +msgstr "" + #: ../../c-api/exceptions.rst:509 msgid "Use :c:func:`PyErr_SetRaisedException` instead." msgstr "" @@ -626,6 +634,13 @@ msgid "" "appropriately is desired, the following additional snippet is needed::" msgstr "" +#: ../../c-api/exceptions.rst:550 +msgid "" +"if (tb != NULL) {\n" +" PyException_SetTraceback(val, tb);\n" +"}" +msgstr "" + #: ../../c-api/exceptions.rst:557 msgid "" "Retrieve the active exception instance, as would be returned by :func:`sys." @@ -821,9 +836,9 @@ msgstr "" #: ../../c-api/exceptions.rst:736 msgid "" -"The :attr:`!__module__` attribute of the new class is set to the first part " -"(up to the last dot) of the *name* argument, and the class name is set to " -"the last part (after the last dot). The *base* argument can be used to " +"The :attr:`~type.__module__` attribute of the new class is set to the first " +"part (up to the last dot) of the *name* argument, and the class name is set " +"to the last part (after the last dot). The *base* argument can be used to " "specify alternate base classes; it can either be only one class or a tuple " "of classes. The *dict* argument can be used to specify a dictionary of class " "variables and methods." @@ -1097,451 +1112,459 @@ msgid "" "all the variables:" msgstr "" -#: ../../c-api/exceptions.rst:1027 ../../c-api/exceptions.rst:1160 -#: ../../c-api/exceptions.rst:1205 +#: ../../c-api/exceptions.rst:1028 ../../c-api/exceptions.rst:1163 +#: ../../c-api/exceptions.rst:1208 msgid "C Name" msgstr "Nome C" -#: ../../c-api/exceptions.rst:1027 ../../c-api/exceptions.rst:1205 +#: ../../c-api/exceptions.rst:1028 ../../c-api/exceptions.rst:1208 msgid "Python Name" msgstr "Nome Python" -#: ../../c-api/exceptions.rst:1027 ../../c-api/exceptions.rst:1160 -#: ../../c-api/exceptions.rst:1205 +#: ../../c-api/exceptions.rst:1028 ../../c-api/exceptions.rst:1163 +#: ../../c-api/exceptions.rst:1208 msgid "Notes" msgstr "Notas" -#: ../../c-api/exceptions.rst:1029 +#: ../../c-api/exceptions.rst:1030 msgid ":c:data:`PyExc_BaseException`" msgstr ":c:data:`PyExc_BaseException`" -#: ../../c-api/exceptions.rst:1029 +#: ../../c-api/exceptions.rst:1030 msgid ":exc:`BaseException`" msgstr ":exc:`BaseException`" -#: ../../c-api/exceptions.rst:1029 ../../c-api/exceptions.rst:1031 -#: ../../c-api/exceptions.rst:1033 ../../c-api/exceptions.rst:1079 -#: ../../c-api/exceptions.rst:1091 +#: ../../c-api/exceptions.rst:1030 ../../c-api/exceptions.rst:1032 +#: ../../c-api/exceptions.rst:1034 ../../c-api/exceptions.rst:1080 +#: ../../c-api/exceptions.rst:1092 msgid "[1]_" msgstr "[1]_" -#: ../../c-api/exceptions.rst:1031 +#: ../../c-api/exceptions.rst:1032 msgid ":c:data:`PyExc_Exception`" msgstr ":c:data:`PyExc_Exception`" -#: ../../c-api/exceptions.rst:1031 +#: ../../c-api/exceptions.rst:1032 msgid ":exc:`Exception`" msgstr ":exc:`Exception`" -#: ../../c-api/exceptions.rst:1033 +#: ../../c-api/exceptions.rst:1034 msgid ":c:data:`PyExc_ArithmeticError`" msgstr ":c:data:`PyExc_ArithmeticError`" -#: ../../c-api/exceptions.rst:1033 +#: ../../c-api/exceptions.rst:1034 msgid ":exc:`ArithmeticError`" msgstr ":exc:`ArithmeticError`" -#: ../../c-api/exceptions.rst:1035 +#: ../../c-api/exceptions.rst:1036 msgid ":c:data:`PyExc_AssertionError`" msgstr ":c:data:`PyExc_AssertionError`" -#: ../../c-api/exceptions.rst:1035 +#: ../../c-api/exceptions.rst:1036 msgid ":exc:`AssertionError`" msgstr ":exc:`AssertionError`" -#: ../../c-api/exceptions.rst:1037 +#: ../../c-api/exceptions.rst:1038 msgid ":c:data:`PyExc_AttributeError`" msgstr ":c:data:`PyExc_AttributeError`" -#: ../../c-api/exceptions.rst:1037 +#: ../../c-api/exceptions.rst:1038 msgid ":exc:`AttributeError`" msgstr ":exc:`AttributeError`" -#: ../../c-api/exceptions.rst:1039 +#: ../../c-api/exceptions.rst:1040 msgid ":c:data:`PyExc_BlockingIOError`" msgstr ":c:data:`PyExc_BlockingIOError`" -#: ../../c-api/exceptions.rst:1039 +#: ../../c-api/exceptions.rst:1040 msgid ":exc:`BlockingIOError`" msgstr ":exc:`BlockingIOError`" -#: ../../c-api/exceptions.rst:1041 +#: ../../c-api/exceptions.rst:1042 msgid ":c:data:`PyExc_BrokenPipeError`" msgstr ":c:data:`PyExc_BrokenPipeError`" -#: ../../c-api/exceptions.rst:1041 +#: ../../c-api/exceptions.rst:1042 msgid ":exc:`BrokenPipeError`" msgstr ":exc:`BrokenPipeError`" -#: ../../c-api/exceptions.rst:1043 +#: ../../c-api/exceptions.rst:1044 msgid ":c:data:`PyExc_BufferError`" msgstr ":c:data:`PyExc_BufferError`" -#: ../../c-api/exceptions.rst:1043 +#: ../../c-api/exceptions.rst:1044 msgid ":exc:`BufferError`" msgstr ":exc:`BufferError`" -#: ../../c-api/exceptions.rst:1045 +#: ../../c-api/exceptions.rst:1046 msgid ":c:data:`PyExc_ChildProcessError`" msgstr ":c:data:`PyExc_ChildProcessError`" -#: ../../c-api/exceptions.rst:1045 +#: ../../c-api/exceptions.rst:1046 msgid ":exc:`ChildProcessError`" msgstr ":exc:`ChildProcessError`" -#: ../../c-api/exceptions.rst:1047 +#: ../../c-api/exceptions.rst:1048 msgid ":c:data:`PyExc_ConnectionAbortedError`" msgstr ":c:data:`PyExc_ConnectionAbortedError`" -#: ../../c-api/exceptions.rst:1047 +#: ../../c-api/exceptions.rst:1048 msgid ":exc:`ConnectionAbortedError`" msgstr ":exc:`ConnectionAbortedError`" -#: ../../c-api/exceptions.rst:1049 +#: ../../c-api/exceptions.rst:1050 msgid ":c:data:`PyExc_ConnectionError`" msgstr ":c:data:`PyExc_ConnectionError`" -#: ../../c-api/exceptions.rst:1049 +#: ../../c-api/exceptions.rst:1050 msgid ":exc:`ConnectionError`" msgstr ":exc:`ConnectionError`" -#: ../../c-api/exceptions.rst:1051 +#: ../../c-api/exceptions.rst:1052 msgid ":c:data:`PyExc_ConnectionRefusedError`" msgstr ":c:data:`PyExc_ConnectionRefusedError`" -#: ../../c-api/exceptions.rst:1051 +#: ../../c-api/exceptions.rst:1052 msgid ":exc:`ConnectionRefusedError`" msgstr ":exc:`ConnectionRefusedError`" -#: ../../c-api/exceptions.rst:1053 +#: ../../c-api/exceptions.rst:1054 msgid ":c:data:`PyExc_ConnectionResetError`" msgstr ":c:data:`PyExc_ConnectionResetError`" -#: ../../c-api/exceptions.rst:1053 +#: ../../c-api/exceptions.rst:1054 msgid ":exc:`ConnectionResetError`" msgstr ":exc:`ConnectionResetError`" -#: ../../c-api/exceptions.rst:1055 +#: ../../c-api/exceptions.rst:1056 msgid ":c:data:`PyExc_EOFError`" msgstr ":c:data:`PyExc_EOFError`" -#: ../../c-api/exceptions.rst:1055 +#: ../../c-api/exceptions.rst:1056 msgid ":exc:`EOFError`" msgstr ":exc:`EOFError`" -#: ../../c-api/exceptions.rst:1057 +#: ../../c-api/exceptions.rst:1058 msgid ":c:data:`PyExc_FileExistsError`" msgstr ":c:data:`PyExc_FileExistsError`" -#: ../../c-api/exceptions.rst:1057 +#: ../../c-api/exceptions.rst:1058 msgid ":exc:`FileExistsError`" msgstr ":exc:`FileExistsError`" -#: ../../c-api/exceptions.rst:1059 +#: ../../c-api/exceptions.rst:1060 msgid ":c:data:`PyExc_FileNotFoundError`" msgstr ":c:data:`PyExc_FileNotFoundError`" -#: ../../c-api/exceptions.rst:1059 +#: ../../c-api/exceptions.rst:1060 msgid ":exc:`FileNotFoundError`" msgstr ":exc:`FileNotFoundError`" -#: ../../c-api/exceptions.rst:1061 +#: ../../c-api/exceptions.rst:1062 msgid ":c:data:`PyExc_FloatingPointError`" msgstr ":c:data:`PyExc_FloatingPointError`" -#: ../../c-api/exceptions.rst:1061 +#: ../../c-api/exceptions.rst:1062 msgid ":exc:`FloatingPointError`" msgstr ":exc:`FloatingPointError`" -#: ../../c-api/exceptions.rst:1063 +#: ../../c-api/exceptions.rst:1064 msgid ":c:data:`PyExc_GeneratorExit`" msgstr ":c:data:`PyExc_GeneratorExit`" -#: ../../c-api/exceptions.rst:1063 +#: ../../c-api/exceptions.rst:1064 msgid ":exc:`GeneratorExit`" msgstr ":exc:`GeneratorExit`" -#: ../../c-api/exceptions.rst:1065 +#: ../../c-api/exceptions.rst:1066 msgid ":c:data:`PyExc_ImportError`" msgstr ":c:data:`PyExc_ImportError`" -#: ../../c-api/exceptions.rst:1065 +#: ../../c-api/exceptions.rst:1066 msgid ":exc:`ImportError`" msgstr ":exc:`ImportError`" -#: ../../c-api/exceptions.rst:1067 +#: ../../c-api/exceptions.rst:1068 msgid ":c:data:`PyExc_IndentationError`" msgstr ":c:data:`PyExc_IndentationError`" -#: ../../c-api/exceptions.rst:1067 +#: ../../c-api/exceptions.rst:1068 msgid ":exc:`IndentationError`" msgstr ":exc:`IndentationError`" -#: ../../c-api/exceptions.rst:1069 +#: ../../c-api/exceptions.rst:1070 msgid ":c:data:`PyExc_IndexError`" msgstr ":c:data:`PyExc_IndexError`" -#: ../../c-api/exceptions.rst:1069 +#: ../../c-api/exceptions.rst:1070 msgid ":exc:`IndexError`" msgstr ":exc:`IndexError`" -#: ../../c-api/exceptions.rst:1071 +#: ../../c-api/exceptions.rst:1072 msgid ":c:data:`PyExc_InterruptedError`" msgstr ":c:data:`PyExc_InterruptedError`" -#: ../../c-api/exceptions.rst:1071 +#: ../../c-api/exceptions.rst:1072 msgid ":exc:`InterruptedError`" msgstr ":exc:`InterruptedError`" -#: ../../c-api/exceptions.rst:1073 +#: ../../c-api/exceptions.rst:1074 msgid ":c:data:`PyExc_IsADirectoryError`" msgstr ":c:data:`PyExc_IsADirectoryError`" -#: ../../c-api/exceptions.rst:1073 +#: ../../c-api/exceptions.rst:1074 msgid ":exc:`IsADirectoryError`" msgstr ":exc:`IsADirectoryError`" -#: ../../c-api/exceptions.rst:1075 +#: ../../c-api/exceptions.rst:1076 msgid ":c:data:`PyExc_KeyError`" msgstr ":c:data:`PyExc_KeyError`" -#: ../../c-api/exceptions.rst:1075 +#: ../../c-api/exceptions.rst:1076 msgid ":exc:`KeyError`" msgstr ":exc:`KeyError`" -#: ../../c-api/exceptions.rst:1077 +#: ../../c-api/exceptions.rst:1078 msgid ":c:data:`PyExc_KeyboardInterrupt`" msgstr ":c:data:`PyExc_KeyboardInterrupt`" -#: ../../c-api/exceptions.rst:1077 +#: ../../c-api/exceptions.rst:1078 msgid ":exc:`KeyboardInterrupt`" msgstr ":exc:`KeyboardInterrupt`" -#: ../../c-api/exceptions.rst:1079 +#: ../../c-api/exceptions.rst:1080 msgid ":c:data:`PyExc_LookupError`" msgstr ":c:data:`PyExc_LookupError`" -#: ../../c-api/exceptions.rst:1079 +#: ../../c-api/exceptions.rst:1080 msgid ":exc:`LookupError`" msgstr ":exc:`LookupError`" -#: ../../c-api/exceptions.rst:1081 +#: ../../c-api/exceptions.rst:1082 msgid ":c:data:`PyExc_MemoryError`" msgstr ":c:data:`PyExc_MemoryError`" -#: ../../c-api/exceptions.rst:1081 +#: ../../c-api/exceptions.rst:1082 msgid ":exc:`MemoryError`" msgstr ":exc:`MemoryError`" -#: ../../c-api/exceptions.rst:1083 +#: ../../c-api/exceptions.rst:1084 msgid ":c:data:`PyExc_ModuleNotFoundError`" msgstr ":c:data:`PyExc_ModuleNotFoundError`" -#: ../../c-api/exceptions.rst:1083 +#: ../../c-api/exceptions.rst:1084 msgid ":exc:`ModuleNotFoundError`" msgstr ":exc:`ModuleNotFoundError`" -#: ../../c-api/exceptions.rst:1085 +#: ../../c-api/exceptions.rst:1086 msgid ":c:data:`PyExc_NameError`" msgstr ":c:data:`PyExc_NameError`" -#: ../../c-api/exceptions.rst:1085 +#: ../../c-api/exceptions.rst:1086 msgid ":exc:`NameError`" msgstr ":exc:`NameError`" -#: ../../c-api/exceptions.rst:1087 +#: ../../c-api/exceptions.rst:1088 msgid ":c:data:`PyExc_NotADirectoryError`" msgstr ":c:data:`PyExc_NotADirectoryError`" -#: ../../c-api/exceptions.rst:1087 +#: ../../c-api/exceptions.rst:1088 msgid ":exc:`NotADirectoryError`" msgstr ":exc:`NotADirectoryError`" -#: ../../c-api/exceptions.rst:1089 +#: ../../c-api/exceptions.rst:1090 msgid ":c:data:`PyExc_NotImplementedError`" msgstr ":c:data:`PyExc_NotImplementedError`" -#: ../../c-api/exceptions.rst:1089 +#: ../../c-api/exceptions.rst:1090 msgid ":exc:`NotImplementedError`" msgstr ":exc:`NotImplementedError`" -#: ../../c-api/exceptions.rst:1091 +#: ../../c-api/exceptions.rst:1092 msgid ":c:data:`PyExc_OSError`" msgstr ":c:data:`PyExc_OSError`" -#: ../../c-api/exceptions.rst:1091 +#: ../../c-api/exceptions.rst:1092 msgid ":exc:`OSError`" msgstr ":exc:`OSError`" -#: ../../c-api/exceptions.rst:1093 +#: ../../c-api/exceptions.rst:1094 msgid ":c:data:`PyExc_OverflowError`" msgstr ":c:data:`PyExc_OverflowError`" -#: ../../c-api/exceptions.rst:1093 +#: ../../c-api/exceptions.rst:1094 msgid ":exc:`OverflowError`" msgstr ":exc:`OverflowError`" -#: ../../c-api/exceptions.rst:1095 +#: ../../c-api/exceptions.rst:1096 msgid ":c:data:`PyExc_PermissionError`" msgstr ":c:data:`PyExc_PermissionError`" -#: ../../c-api/exceptions.rst:1095 +#: ../../c-api/exceptions.rst:1096 msgid ":exc:`PermissionError`" msgstr ":exc:`PermissionError`" -#: ../../c-api/exceptions.rst:1097 +#: ../../c-api/exceptions.rst:1098 msgid ":c:data:`PyExc_ProcessLookupError`" msgstr ":c:data:`PyExc_ProcessLookupError`" -#: ../../c-api/exceptions.rst:1097 +#: ../../c-api/exceptions.rst:1098 msgid ":exc:`ProcessLookupError`" msgstr ":exc:`ProcessLookupError`" -#: ../../c-api/exceptions.rst:1099 +#: ../../c-api/exceptions.rst:1100 +msgid ":c:data:`PyExc_PythonFinalizationError`" +msgstr "" + +#: ../../c-api/exceptions.rst:1100 +msgid ":exc:`PythonFinalizationError`" +msgstr "" + +#: ../../c-api/exceptions.rst:1102 msgid ":c:data:`PyExc_RecursionError`" msgstr ":c:data:`PyExc_RecursionError`" -#: ../../c-api/exceptions.rst:1099 +#: ../../c-api/exceptions.rst:1102 msgid ":exc:`RecursionError`" msgstr ":exc:`RecursionError`" -#: ../../c-api/exceptions.rst:1101 +#: ../../c-api/exceptions.rst:1104 msgid ":c:data:`PyExc_ReferenceError`" msgstr ":c:data:`PyExc_ReferenceError`" -#: ../../c-api/exceptions.rst:1101 +#: ../../c-api/exceptions.rst:1104 msgid ":exc:`ReferenceError`" msgstr ":exc:`ReferenceError`" -#: ../../c-api/exceptions.rst:1103 +#: ../../c-api/exceptions.rst:1106 msgid ":c:data:`PyExc_RuntimeError`" msgstr ":c:data:`PyExc_RuntimeError`" -#: ../../c-api/exceptions.rst:1103 +#: ../../c-api/exceptions.rst:1106 msgid ":exc:`RuntimeError`" msgstr ":exc:`RuntimeError`" -#: ../../c-api/exceptions.rst:1105 +#: ../../c-api/exceptions.rst:1108 msgid ":c:data:`PyExc_StopAsyncIteration`" msgstr ":c:data:`PyExc_StopAsyncIteration`" -#: ../../c-api/exceptions.rst:1105 +#: ../../c-api/exceptions.rst:1108 msgid ":exc:`StopAsyncIteration`" msgstr ":exc:`StopAsyncIteration`" -#: ../../c-api/exceptions.rst:1107 +#: ../../c-api/exceptions.rst:1110 msgid ":c:data:`PyExc_StopIteration`" msgstr ":c:data:`PyExc_StopIteration`" -#: ../../c-api/exceptions.rst:1107 +#: ../../c-api/exceptions.rst:1110 msgid ":exc:`StopIteration`" msgstr ":exc:`StopIteration`" -#: ../../c-api/exceptions.rst:1109 +#: ../../c-api/exceptions.rst:1112 msgid ":c:data:`PyExc_SyntaxError`" msgstr ":c:data:`PyExc_SyntaxError`" -#: ../../c-api/exceptions.rst:1109 +#: ../../c-api/exceptions.rst:1112 msgid ":exc:`SyntaxError`" msgstr ":exc:`SyntaxError`" -#: ../../c-api/exceptions.rst:1111 +#: ../../c-api/exceptions.rst:1114 msgid ":c:data:`PyExc_SystemError`" msgstr ":c:data:`PyExc_SystemError`" -#: ../../c-api/exceptions.rst:1111 +#: ../../c-api/exceptions.rst:1114 msgid ":exc:`SystemError`" msgstr ":exc:`SystemError`" -#: ../../c-api/exceptions.rst:1113 +#: ../../c-api/exceptions.rst:1116 msgid ":c:data:`PyExc_SystemExit`" msgstr ":c:data:`PyExc_SystemExit`" -#: ../../c-api/exceptions.rst:1113 +#: ../../c-api/exceptions.rst:1116 msgid ":exc:`SystemExit`" msgstr ":exc:`SystemExit`" -#: ../../c-api/exceptions.rst:1115 +#: ../../c-api/exceptions.rst:1118 msgid ":c:data:`PyExc_TabError`" msgstr ":c:data:`PyExc_TabError`" -#: ../../c-api/exceptions.rst:1115 +#: ../../c-api/exceptions.rst:1118 msgid ":exc:`TabError`" msgstr ":exc:`TabError`" -#: ../../c-api/exceptions.rst:1117 +#: ../../c-api/exceptions.rst:1120 msgid ":c:data:`PyExc_TimeoutError`" msgstr ":c:data:`PyExc_TimeoutError`" -#: ../../c-api/exceptions.rst:1117 +#: ../../c-api/exceptions.rst:1120 msgid ":exc:`TimeoutError`" msgstr ":exc:`TimeoutError`" -#: ../../c-api/exceptions.rst:1119 +#: ../../c-api/exceptions.rst:1122 msgid ":c:data:`PyExc_TypeError`" msgstr ":c:data:`PyExc_TypeError`" -#: ../../c-api/exceptions.rst:1119 +#: ../../c-api/exceptions.rst:1122 msgid ":exc:`TypeError`" msgstr ":exc:`TypeError`" -#: ../../c-api/exceptions.rst:1121 +#: ../../c-api/exceptions.rst:1124 msgid ":c:data:`PyExc_UnboundLocalError`" msgstr ":c:data:`PyExc_UnboundLocalError`" -#: ../../c-api/exceptions.rst:1121 +#: ../../c-api/exceptions.rst:1124 msgid ":exc:`UnboundLocalError`" msgstr ":exc:`UnboundLocalError`" -#: ../../c-api/exceptions.rst:1123 +#: ../../c-api/exceptions.rst:1126 msgid ":c:data:`PyExc_UnicodeDecodeError`" msgstr ":c:data:`PyExc_UnicodeDecodeError`" -#: ../../c-api/exceptions.rst:1123 +#: ../../c-api/exceptions.rst:1126 msgid ":exc:`UnicodeDecodeError`" msgstr ":exc:`UnicodeDecodeError`" -#: ../../c-api/exceptions.rst:1125 +#: ../../c-api/exceptions.rst:1128 msgid ":c:data:`PyExc_UnicodeEncodeError`" msgstr ":c:data:`PyExc_UnicodeEncodeError`" -#: ../../c-api/exceptions.rst:1125 +#: ../../c-api/exceptions.rst:1128 msgid ":exc:`UnicodeEncodeError`" msgstr ":exc:`UnicodeEncodeError`" -#: ../../c-api/exceptions.rst:1127 +#: ../../c-api/exceptions.rst:1130 msgid ":c:data:`PyExc_UnicodeError`" msgstr ":c:data:`PyExc_UnicodeError`" -#: ../../c-api/exceptions.rst:1127 +#: ../../c-api/exceptions.rst:1130 msgid ":exc:`UnicodeError`" msgstr ":exc:`UnicodeError`" -#: ../../c-api/exceptions.rst:1129 +#: ../../c-api/exceptions.rst:1132 msgid ":c:data:`PyExc_UnicodeTranslateError`" msgstr ":c:data:`PyExc_UnicodeTranslateError`" -#: ../../c-api/exceptions.rst:1129 +#: ../../c-api/exceptions.rst:1132 msgid ":exc:`UnicodeTranslateError`" msgstr ":exc:`UnicodeTranslateError`" -#: ../../c-api/exceptions.rst:1131 +#: ../../c-api/exceptions.rst:1134 msgid ":c:data:`PyExc_ValueError`" msgstr ":c:data:`PyExc_ValueError`" -#: ../../c-api/exceptions.rst:1131 +#: ../../c-api/exceptions.rst:1134 msgid ":exc:`ValueError`" msgstr ":exc:`ValueError`" -#: ../../c-api/exceptions.rst:1133 +#: ../../c-api/exceptions.rst:1136 msgid ":c:data:`PyExc_ZeroDivisionError`" msgstr ":c:data:`PyExc_ZeroDivisionError`" -#: ../../c-api/exceptions.rst:1133 +#: ../../c-api/exceptions.rst:1136 msgid ":exc:`ZeroDivisionError`" msgstr ":exc:`ZeroDivisionError`" -#: ../../c-api/exceptions.rst:1136 +#: ../../c-api/exceptions.rst:1139 msgid "" ":c:data:`PyExc_BlockingIOError`, :c:data:`PyExc_BrokenPipeError`, :c:data:" "`PyExc_ChildProcessError`, :c:data:`PyExc_ConnectionError`, :c:data:" @@ -1561,47 +1584,47 @@ msgstr "" "`PyExc_PermissionError`, :c:data:`PyExc_ProcessLookupError` e :c:data:" "`PyExc_TimeoutError` foram introduzidos seguindo a :pep:`3151`." -#: ../../c-api/exceptions.rst:1146 +#: ../../c-api/exceptions.rst:1149 msgid ":c:data:`PyExc_StopAsyncIteration` and :c:data:`PyExc_RecursionError`." msgstr ":c:data:`PyExc_StopAsyncIteration` e :c:data:`PyExc_RecursionError`." -#: ../../c-api/exceptions.rst:1149 +#: ../../c-api/exceptions.rst:1152 msgid ":c:data:`PyExc_ModuleNotFoundError`." msgstr ":c:data:`PyExc_ModuleNotFoundError`." -#: ../../c-api/exceptions.rst:1152 +#: ../../c-api/exceptions.rst:1155 msgid "These are compatibility aliases to :c:data:`PyExc_OSError`:" msgstr "Esses são os aliases de compatibilidade para :c:data:`PyExc_OSError`:" -#: ../../c-api/exceptions.rst:1162 +#: ../../c-api/exceptions.rst:1165 msgid ":c:data:`!PyExc_EnvironmentError`" msgstr "" -#: ../../c-api/exceptions.rst:1164 +#: ../../c-api/exceptions.rst:1167 msgid ":c:data:`!PyExc_IOError`" msgstr "" -#: ../../c-api/exceptions.rst:1166 +#: ../../c-api/exceptions.rst:1169 msgid ":c:data:`!PyExc_WindowsError`" msgstr "" -#: ../../c-api/exceptions.rst:1166 +#: ../../c-api/exceptions.rst:1169 msgid "[2]_" msgstr "[2]_" -#: ../../c-api/exceptions.rst:1169 +#: ../../c-api/exceptions.rst:1172 msgid "These aliases used to be separate exception types." msgstr "Esses aliases costumavam ser tipos de exceção separados." -#: ../../c-api/exceptions.rst:1172 ../../c-api/exceptions.rst:1233 +#: ../../c-api/exceptions.rst:1175 ../../c-api/exceptions.rst:1236 msgid "Notes:" msgstr "Notas:" -#: ../../c-api/exceptions.rst:1175 +#: ../../c-api/exceptions.rst:1178 msgid "This is a base class for other standard exceptions." msgstr "Esta é uma classe base para outras exceções padrão." -#: ../../c-api/exceptions.rst:1178 +#: ../../c-api/exceptions.rst:1181 msgid "" "Only defined on Windows; protect code that uses this by testing that the " "preprocessor macro ``MS_WINDOWS`` is defined." @@ -1609,11 +1632,11 @@ msgstr "" "Defina apenas no Windows; proteja o código que usa isso testando se a macro " "do pré-processador ``MS_WINDOWS`` está definida." -#: ../../c-api/exceptions.rst:1184 +#: ../../c-api/exceptions.rst:1187 msgid "Standard Warning Categories" msgstr "Categorias de aviso padrão" -#: ../../c-api/exceptions.rst:1186 +#: ../../c-api/exceptions.rst:1189 msgid "" "All standard Python warning categories are available as global variables " "whose names are ``PyExc_`` followed by the Python exception name. These have " @@ -1621,103 +1644,103 @@ msgid "" "here are all the variables:" msgstr "" -#: ../../c-api/exceptions.rst:1207 +#: ../../c-api/exceptions.rst:1210 msgid ":c:data:`PyExc_Warning`" msgstr ":c:data:`PyExc_Warning`" -#: ../../c-api/exceptions.rst:1207 +#: ../../c-api/exceptions.rst:1210 msgid ":exc:`Warning`" msgstr ":exc:`Warning`" -#: ../../c-api/exceptions.rst:1207 +#: ../../c-api/exceptions.rst:1210 msgid "[3]_" msgstr "[3]_" -#: ../../c-api/exceptions.rst:1209 +#: ../../c-api/exceptions.rst:1212 msgid ":c:data:`PyExc_BytesWarning`" msgstr ":c:data:`PyExc_BytesWarning`" -#: ../../c-api/exceptions.rst:1209 +#: ../../c-api/exceptions.rst:1212 msgid ":exc:`BytesWarning`" msgstr ":exc:`BytesWarning`" -#: ../../c-api/exceptions.rst:1211 +#: ../../c-api/exceptions.rst:1214 msgid ":c:data:`PyExc_DeprecationWarning`" msgstr ":c:data:`PyExc_DeprecationWarning`" -#: ../../c-api/exceptions.rst:1211 +#: ../../c-api/exceptions.rst:1214 msgid ":exc:`DeprecationWarning`" msgstr ":exc:`DeprecationWarning`" -#: ../../c-api/exceptions.rst:1213 +#: ../../c-api/exceptions.rst:1216 msgid ":c:data:`PyExc_FutureWarning`" msgstr ":c:data:`PyExc_FutureWarning`" -#: ../../c-api/exceptions.rst:1213 +#: ../../c-api/exceptions.rst:1216 msgid ":exc:`FutureWarning`" msgstr ":exc:`FutureWarning`" -#: ../../c-api/exceptions.rst:1215 +#: ../../c-api/exceptions.rst:1218 msgid ":c:data:`PyExc_ImportWarning`" msgstr ":c:data:`PyExc_ImportWarning`" -#: ../../c-api/exceptions.rst:1215 +#: ../../c-api/exceptions.rst:1218 msgid ":exc:`ImportWarning`" msgstr ":exc:`ImportWarning`" -#: ../../c-api/exceptions.rst:1217 +#: ../../c-api/exceptions.rst:1220 msgid ":c:data:`PyExc_PendingDeprecationWarning`" msgstr ":c:data:`PyExc_PendingDeprecationWarning`" -#: ../../c-api/exceptions.rst:1217 +#: ../../c-api/exceptions.rst:1220 msgid ":exc:`PendingDeprecationWarning`" msgstr ":exc:`PendingDeprecationWarning`" -#: ../../c-api/exceptions.rst:1219 +#: ../../c-api/exceptions.rst:1222 msgid ":c:data:`PyExc_ResourceWarning`" msgstr ":c:data:`PyExc_ResourceWarning`" -#: ../../c-api/exceptions.rst:1219 +#: ../../c-api/exceptions.rst:1222 msgid ":exc:`ResourceWarning`" msgstr ":exc:`ResourceWarning`" -#: ../../c-api/exceptions.rst:1221 +#: ../../c-api/exceptions.rst:1224 msgid ":c:data:`PyExc_RuntimeWarning`" msgstr ":c:data:`PyExc_RuntimeWarning`" -#: ../../c-api/exceptions.rst:1221 +#: ../../c-api/exceptions.rst:1224 msgid ":exc:`RuntimeWarning`" msgstr ":exc:`RuntimeWarning`" -#: ../../c-api/exceptions.rst:1223 +#: ../../c-api/exceptions.rst:1226 msgid ":c:data:`PyExc_SyntaxWarning`" msgstr ":c:data:`PyExc_SyntaxWarning`" -#: ../../c-api/exceptions.rst:1223 +#: ../../c-api/exceptions.rst:1226 msgid ":exc:`SyntaxWarning`" msgstr ":exc:`SyntaxWarning`" -#: ../../c-api/exceptions.rst:1225 +#: ../../c-api/exceptions.rst:1228 msgid ":c:data:`PyExc_UnicodeWarning`" msgstr ":c:data:`PyExc_UnicodeWarning`" -#: ../../c-api/exceptions.rst:1225 +#: ../../c-api/exceptions.rst:1228 msgid ":exc:`UnicodeWarning`" msgstr ":exc:`UnicodeWarning`" -#: ../../c-api/exceptions.rst:1227 +#: ../../c-api/exceptions.rst:1230 msgid ":c:data:`PyExc_UserWarning`" msgstr ":c:data:`PyExc_UserWarning`" -#: ../../c-api/exceptions.rst:1227 +#: ../../c-api/exceptions.rst:1230 msgid ":exc:`UserWarning`" msgstr ":exc:`UserWarning`" -#: ../../c-api/exceptions.rst:1230 +#: ../../c-api/exceptions.rst:1233 msgid ":c:data:`PyExc_ResourceWarning`." msgstr ":c:data:`PyExc_ResourceWarning`." -#: ../../c-api/exceptions.rst:1236 +#: ../../c-api/exceptions.rst:1239 msgid "This is a base class for other standard warning categories." msgstr "Esta é uma classe base para outras categorias de aviso padrão." @@ -1884,6 +1907,10 @@ msgstr "" msgid "PyExc_ProcessLookupError (C var)" msgstr "" +#: ../../c-api/exceptions.rst:971 +msgid "PyExc_PythonFinalizationError (C var)" +msgstr "" + #: ../../c-api/exceptions.rst:971 msgid "PyExc_RecursionError (C var)" msgstr "" @@ -1956,58 +1983,58 @@ msgstr "" msgid "PyExc_ZeroDivisionError (C var)" msgstr "" -#: ../../c-api/exceptions.rst:1154 +#: ../../c-api/exceptions.rst:1157 msgid "PyExc_EnvironmentError (C var)" msgstr "" -#: ../../c-api/exceptions.rst:1154 +#: ../../c-api/exceptions.rst:1157 msgid "PyExc_IOError (C var)" msgstr "" -#: ../../c-api/exceptions.rst:1154 +#: ../../c-api/exceptions.rst:1157 msgid "PyExc_WindowsError (C var)" msgstr "" -#: ../../c-api/exceptions.rst:1191 +#: ../../c-api/exceptions.rst:1194 msgid "PyExc_Warning (C var)" msgstr "" -#: ../../c-api/exceptions.rst:1191 +#: ../../c-api/exceptions.rst:1194 msgid "PyExc_BytesWarning (C var)" msgstr "" -#: ../../c-api/exceptions.rst:1191 +#: ../../c-api/exceptions.rst:1194 msgid "PyExc_DeprecationWarning (C var)" msgstr "" -#: ../../c-api/exceptions.rst:1191 +#: ../../c-api/exceptions.rst:1194 msgid "PyExc_FutureWarning (C var)" msgstr "" -#: ../../c-api/exceptions.rst:1191 +#: ../../c-api/exceptions.rst:1194 msgid "PyExc_ImportWarning (C var)" msgstr "" -#: ../../c-api/exceptions.rst:1191 +#: ../../c-api/exceptions.rst:1194 msgid "PyExc_PendingDeprecationWarning (C var)" msgstr "" -#: ../../c-api/exceptions.rst:1191 +#: ../../c-api/exceptions.rst:1194 msgid "PyExc_ResourceWarning (C var)" msgstr "" -#: ../../c-api/exceptions.rst:1191 +#: ../../c-api/exceptions.rst:1194 msgid "PyExc_RuntimeWarning (C var)" msgstr "" -#: ../../c-api/exceptions.rst:1191 +#: ../../c-api/exceptions.rst:1194 msgid "PyExc_SyntaxWarning (C var)" msgstr "" -#: ../../c-api/exceptions.rst:1191 +#: ../../c-api/exceptions.rst:1194 msgid "PyExc_UnicodeWarning (C var)" msgstr "" -#: ../../c-api/exceptions.rst:1191 +#: ../../c-api/exceptions.rst:1194 msgid "PyExc_UserWarning (C var)" msgstr "" diff --git a/c-api/file.po b/c-api/file.po index 3120316c8..fc7b04d4a 100644 --- a/c-api/file.po +++ b/c-api/file.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/float.po b/c-api/float.po index 8ec9d225f..1fe3ae94b 100644 --- a/c-api/float.po +++ b/c-api/float.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/frame.po b/c-api/frame.po index 60ca00632..500391fd4 100644 --- a/c-api/frame.po +++ b/c-api/frame.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Ruan Aragão , 2022 -# Flávio Neves, 2023 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2022-11-05 19:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -179,34 +177,61 @@ msgid "" msgstr "" #: ../../c-api/frame.rst:134 -msgid "As part of :pep:`667`, return a proxy object for optimized scopes." +msgid "" +"As part of :pep:`667`, return an instance of :c:var:" +"`PyFrameLocalsProxy_Type`." msgstr "" #: ../../c-api/frame.rst:140 msgid "Return the line number that *frame* is currently executing." msgstr "Retorna o número da linha do *frame* atualmente em execução." -#: ../../c-api/frame.rst:145 +#: ../../c-api/frame.rst:144 +msgid "Frame Locals Proxies" +msgstr "" + +#: ../../c-api/frame.rst:148 +msgid "" +"The :attr:`~frame.f_locals` attribute on a :ref:`frame object ` is an instance of a \"frame-locals proxy\". The proxy object " +"exposes a write-through view of the underlying locals dictionary for the " +"frame. This ensures that the variables exposed by ``f_locals`` are always up " +"to date with the live local variables in the frame itself." +msgstr "" + +#: ../../c-api/frame.rst:154 +msgid "See :pep:`667` for more information." +msgstr "" + +#: ../../c-api/frame.rst:158 +msgid "The type of frame :func:`locals` proxy objects." +msgstr "" + +#: ../../c-api/frame.rst:162 +msgid "Return non-zero if *obj* is a frame :func:`locals` proxy." +msgstr "" + +#: ../../c-api/frame.rst:165 msgid "Internal Frames" msgstr "" -#: ../../c-api/frame.rst:147 +#: ../../c-api/frame.rst:167 msgid "Unless using :pep:`523`, you will not need this." msgstr "" -#: ../../c-api/frame.rst:151 +#: ../../c-api/frame.rst:171 msgid "The interpreter's internal frame representation." msgstr "" -#: ../../c-api/frame.rst:157 +#: ../../c-api/frame.rst:177 msgid "Return a :term:`strong reference` to the code object for the frame." msgstr "" -#: ../../c-api/frame.rst:164 +#: ../../c-api/frame.rst:184 msgid "Return the byte offset into the last executed instruction." msgstr "" -#: ../../c-api/frame.rst:171 +#: ../../c-api/frame.rst:191 msgid "" "Return the currently executing line number, or -1 if there is no line number." msgstr "" diff --git a/c-api/function.po b/c-api/function.po index 1280ab1f9..f9d141e45 100644 --- a/c-api/function.po +++ b/c-api/function.po @@ -1,32 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Italo Penaforte , 2021 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../c-api/function.rst:6 msgid "Function Objects" -msgstr "Objetos Função" +msgstr "Objetos Function" #: ../../c-api/function.rst:10 msgid "There are a few functions specific to Python functions." @@ -43,7 +42,7 @@ msgid "" "FunctionType``." msgstr "" "Esta é uma instância de :c:type:`PyTypeObject` e representa o tipo de função " -"Python. Está exposto aos programadores Python como ``types.FunctionType``." +"Python. Está exposta a programadores Python como ``types.FunctionType``." #: ../../c-api/function.rst:28 msgid "" @@ -51,9 +50,9 @@ msgid "" "`PyFunction_Type`). The parameter must not be ``NULL``. This function " "always succeeds." msgstr "" -"Retorna verdadeiro se *o* é um objeto de função (tem tipo :c:data:" +"Retorna verdadeiro se *o* for um objeto função (tem tipo :c:data:" "`PyFunction_Type`). O parâmetro não deve ser ``NULL``. Esta função sempre " -"tem sucesso." +"obtém sucesso." #: ../../c-api/function.rst:34 msgid "" @@ -61,7 +60,7 @@ msgid "" "*globals* must be a dictionary with the global variables accessible to the " "function." msgstr "" -"Retorna um novo objeto função associado ao código objeto *code*. *globals* " +"Retorna um novo objeto função associado ao objeto código *code*. *globals* " "deve ser um dicionário com as variáveis globais acessíveis à função." #: ../../c-api/function.rst:37 @@ -72,6 +71,11 @@ msgid "" "is set to the same value as the code object's :attr:`~codeobject." "co_qualname` field." msgstr "" +"O nome e *docstring* da função são adquiridos pelo objeto código. O " +"atributo :attr:`~function.__module__` é adquirido por meio de *globals*. Os " +"valores-padrão de argumentos, anotações, e fechamento são definidos como " +"``NULL``. O atributo :attr:`~function.__qualname__` é definido com o mesmo " +"valor do campo :attr:`~codeobject.co_qualname` de um objeto código." #: ../../c-api/function.rst:46 msgid "" @@ -80,10 +84,15 @@ msgid "" "object or ``NULL``; if ``NULL``, the :attr:`!__qualname__` attribute is set " "to the same value as the code object's :attr:`~codeobject.co_qualname` field." msgstr "" +"Similar a :c:func:`PyFunction_New`, mas também permite definir o atributo :" +"attr:`~function.__qualname__` do objeto função. *qualname* deve ser um " +"objeto Unicode ou ``NULL``. Se ``NULL``, o atributo :attr:`!__qualname__` é " +"definido com o mesmo valor do campo :attr:`~codeobject.co_qualname` do " +"objeto código." #: ../../c-api/function.rst:57 msgid "Return the code object associated with the function object *op*." -msgstr "Retorna o objeto de código associado ao objeto função *op*." +msgstr "Retorna o objeto código associado ao objeto função *op*." #: ../../c-api/function.rst:62 msgid "Return the globals dictionary associated with the function object *op*." @@ -95,51 +104,58 @@ msgid "" "attribute of the :ref:`function object ` *op*. It can be " "*NULL*." msgstr "" +"Retorna uma :term:`referência emprestada` ao atributo :attr:`~function." +"__module__` do :ref:`objeto função ` *op*. Pode ser " +"`NULL`." #: ../../c-api/function.rst:71 msgid "" "This is normally a :class:`string ` containing the module name, but can " "be set to any other object by Python code." msgstr "" +"Normalmente, trata-se de um :class:`string ` contendo o nome do módulo, " +"mas pode ser definido como qualquer outro objeto pelo código Python." #: ../../c-api/function.rst:77 msgid "" "Return the argument default values of the function object *op*. This can be " "a tuple of arguments or ``NULL``." msgstr "" -"Retorna o argumento os valores padrão do objeto função *op*. Isso pode ser " -"uma tupla de argumentos ou ``NULL``." +"Retorna os valores-padrão de argumentos do objeto função *op*. Pode ser uma " +"tupla de argumentos ou ``NULL``." #: ../../c-api/function.rst:83 msgid "" "Set the argument default values for the function object *op*. *defaults* " "must be ``Py_None`` or a tuple." msgstr "" -"Define o argumento valores padrão para o objeto função *op*. *defaults* deve " -"ser ``Py_None`` ou uma tupla." +"Define os valores-padrão dos argumentos do objeto função *op*. *defaults* " +"deve ser ``Py_None`` ou uma tupla." #: ../../c-api/function.rst:86 ../../c-api/function.rst:109 #: ../../c-api/function.rst:123 msgid "Raises :exc:`SystemError` and returns ``-1`` on failure." -msgstr "Levanta :exc:`SystemError` e retorna ``-1`` em falha." +msgstr "Levanta :exc:`SystemError` e retorna ``-1`` em caso de falha." #: ../../c-api/function.rst:91 msgid "Set the vectorcall field of a given function object *func*." -msgstr "" +msgstr "Define o campo *vectorcall* de um objeto função *func*." #: ../../c-api/function.rst:93 msgid "" "Warning: extensions using this API must preserve the behavior of the " "unaltered (default) vectorcall function!" msgstr "" +"Atenção: extensões que usam essa API devem preservar o comportamento " +"inalterado (padrão) de uma função *vectorcall*!" #: ../../c-api/function.rst:100 msgid "" "Return the closure associated with the function object *op*. This can be " "``NULL`` or a tuple of cell objects." msgstr "" -"Retorna o fechamento associado ao objeto função *op*. Isso pode ser ``NULL`` " -"ou uma tupla de objetos de célula." +"Retorna o fechamento associado ao objeto função *op*. Pode ser ``NULL`` ou " +"uma tupla de objetos célula." #: ../../c-api/function.rst:106 msgid "" @@ -172,6 +188,10 @@ msgid "" "case of error (e.g. no more watcher IDs available), return ``-1`` and set an " "exception." msgstr "" +"Registra *callback* como uma sentinela de função para o interpretador atual. " +"Retorna um ID que pode ser passado para :c:func:`PyFunction_ClearWatcher`. " +"Em caso de erro (por exemplo, sem novos IDs de sentinelas disponíveis), " +"retorna ``-1`` e define uma exceção." #: ../../c-api/function.rst:138 msgid "" @@ -180,34 +200,60 @@ msgid "" "success, or ``-1`` and set an exception on error (e.g. if the given " "*watcher_id* was never registered.)" msgstr "" +"Cancela o registro da sentinela identificada pelo *watcher_id* retornado " +"por :c:func:`PyFunction_AddWatcher` para o interpretador atual. Retorna " +"``0`` em caso de sucesso, ou ``-1`` e define uma exceção em caso de erro " +"(por exemplo, ao receber um *watcher_id* desconhecido.)" #: ../../c-api/function.rst:148 -msgid "" -"Enumeration of possible function watcher events: - " -"``PyFunction_EVENT_CREATE`` - ``PyFunction_EVENT_DESTROY`` - " -"``PyFunction_EVENT_MODIFY_CODE`` - ``PyFunction_EVENT_MODIFY_DEFAULTS`` - " -"``PyFunction_EVENT_MODIFY_KWDEFAULTS``" +msgid "Enumeration of possible function watcher events:" msgstr "" -#: ../../c-api/function.rst:160 -msgid "Type of a function watcher callback function." +#: ../../c-api/function.rst:150 +msgid "``PyFunction_EVENT_CREATE``" +msgstr "" + +#: ../../c-api/function.rst:151 +msgid "``PyFunction_EVENT_DESTROY``" +msgstr "" + +#: ../../c-api/function.rst:152 +msgid "``PyFunction_EVENT_MODIFY_CODE``" +msgstr "" + +#: ../../c-api/function.rst:153 +msgid "``PyFunction_EVENT_MODIFY_DEFAULTS``" +msgstr "" + +#: ../../c-api/function.rst:154 +msgid "``PyFunction_EVENT_MODIFY_KWDEFAULTS``" msgstr "" -#: ../../c-api/function.rst:162 +#: ../../c-api/function.rst:161 +msgid "Type of a function watcher callback function." +msgstr "Tipo de uma função de retorno de sentinela de função." + +#: ../../c-api/function.rst:163 msgid "" "If *event* is ``PyFunction_EVENT_CREATE`` or ``PyFunction_EVENT_DESTROY`` " "then *new_value* will be ``NULL``. Otherwise, *new_value* will hold a :term:" "`borrowed reference` to the new value that is about to be stored in *func* " "for the attribute that is being modified." msgstr "" +"Se *event* for ``PyFunction_EVENT_CREATE`` ou ``PyFunction_EVENT_DESTROY``, " +"*new_value* será ``NULL``. Senão, *new_value* portará uma :term:`referência " +"emprestada` ao novo valor prestes a ser guardado em *func* para o atributo " +"que está sendo modificado." -#: ../../c-api/function.rst:167 +#: ../../c-api/function.rst:168 msgid "" "The callback may inspect but must not modify *func*; doing so could have " "unpredictable effects, including infinite recursion." msgstr "" +"A função de retorno poderá somente inspecionar, e não modificar *func*. Caso " +"contrário, poderíamos ter efeitos imprevisíveis, incluindo recursão infinita." -#: ../../c-api/function.rst:170 +#: ../../c-api/function.rst:171 msgid "" "If *event* is ``PyFunction_EVENT_CREATE``, then the callback is invoked " "after `func` has been fully initialized. Otherwise, the callback is invoked " @@ -218,26 +264,39 @@ msgid "" "behavior depending on optimization decisions, it does not change the " "semantics of the Python code being executed." msgstr "" - -#: ../../c-api/function.rst:179 +"Se *event* for ``PyFunction_EVENT_CREATE``, a função de retorno será " +"invocada após *func* ter sido completamente inicializada. Caso contrário, a " +"função de retorno será invocada antes de modificar *func*, então o estado " +"anterior de *func* poderá ser inspecionado. O ambiente de execução pode " +"otimizar a criação de objetos função, quando possível, ao ignorá-las. Nesses " +"casos, nenhum evento será emitido. Apesar de decisões de otimização criarem " +"diferenças de comportamento em tempo de execução, elas não mudam a semântica " +"do código Python sendo executado." + +#: ../../c-api/function.rst:180 msgid "" "If *event* is ``PyFunction_EVENT_DESTROY``, Taking a reference in the " "callback to the about-to-be-destroyed function will resurrect it, preventing " "it from being freed at this time. When the resurrected object is destroyed " "later, any watcher callbacks active at that time will be called again." msgstr "" +"Se *event* for ``PyFunction_EVENT_DESTROY``, então obter uma referência " +"dentro da função de retorno para a função prestes a ser destruída irá revivê-" +"la, impedindo que esta função seja liberada nesse tempo. Quando o objeto " +"revivido for destruído, quaisquer funções de retorno sentinelas ativas nesse " +"momento poderão ser chamadas novamente." -#: ../../c-api/function.rst:184 +#: ../../c-api/function.rst:185 msgid "" "If the callback sets an exception, it must return ``-1``; this exception " "will be printed as an unraisable exception using :c:func:" "`PyErr_WriteUnraisable`. Otherwise it should return ``0``." msgstr "" -"Se a função de retorno definir uma exceção, ela deverá retornar ``-1``; essa " -"exceção será impressa como uma exceção não reprovável usando :c:func:" +"Se a função de retorno definir uma exceção, ela deverá retornar ``-1``. Essa " +"exceção será exibida como uma exceção não levantável usando :c:func:" "`PyErr_WriteUnraisable`. Caso contrário, deverá retornar ``0``." -#: ../../c-api/function.rst:188 +#: ../../c-api/function.rst:189 msgid "" "There may already be a pending exception set on entry to the callback. In " "this case, the callback should return ``0`` with the same exception still " @@ -245,11 +304,11 @@ msgid "" "exception unless it saves and clears the exception state first, and restores " "it before returning." msgstr "" -"É possível que já exista uma exceção pendente definida na entrada da chamada " +"É possível que já exista uma exceção pendente definida na entrada da função " "de retorno. Nesse caso, a função de retorno deve retornar ``0`` com a mesma " -"exceção ainda definida. Isso significa que a callback não pode chamar " -"nenhuma outra API que possa definir uma exceção, a menos que salve e limpe o " -"estado da exceção primeiro e o restaure antes de retornar." +"exceção ainda definida. Isso significa que a função de retorno não pode " +"chamar nenhuma outra API que possa definir uma exceção, a menos que salve e " +"limpe o estado da exceção primeiro e restaure a exceção antes de retornar." #: ../../c-api/function.rst:8 msgid "object" diff --git a/c-api/gcsupport.po b/c-api/gcsupport.po index 3ab930a46..529990ed2 100644 --- a/c-api/gcsupport.po +++ b/c-api/gcsupport.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rodrigo Cândido, 2022 -# Andressa Lima Ferreira, 2023 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -279,9 +277,21 @@ msgstr "" #: ../../c-api/gcsupport.rst:185 msgid "" -"If *o* is not ``NULL``, call the *visit* callback, with arguments *o* and " -"*arg*. If *visit* returns a non-zero value, then return it. Using this " -"macro, :c:member:`~PyTypeObject.tp_traverse` handlers look like::" +"If the :c:expr:`PyObject *` *o* is not ``NULL``, call the *visit* callback, " +"with arguments *o* and *arg*. If *visit* returns a non-zero value, then " +"return it. Using this macro, :c:member:`~PyTypeObject.tp_traverse` handlers " +"look like::" +msgstr "" + +#: ../../c-api/gcsupport.rst:190 +msgid "" +"static int\n" +"my_traverse(Noddy *self, visitproc visit, void *arg)\n" +"{\n" +" Py_VISIT(self->foo);\n" +" Py_VISIT(self->bar);\n" +" return 0;\n" +"}" msgstr "" #: ../../c-api/gcsupport.rst:198 @@ -375,7 +385,7 @@ msgstr "" msgid "" "Type of the visitor function to be passed to :c:func:" "`PyUnstable_GC_VisitObjects`. *arg* is the same as the *arg* passed to " -"``PyUnstable_GC_VisitObjects``. Return ``0`` to continue iteration, return " -"``1`` to stop iteration. Other return values are reserved for now so " +"``PyUnstable_GC_VisitObjects``. Return ``1`` to continue iteration, return " +"``0`` to stop iteration. Other return values are reserved for now so " "behavior on returning anything else is undefined." msgstr "" diff --git a/c-api/gen.po b/c-api/gen.po index 99276656a..3cefd30b0 100644 --- a/c-api/gen.po +++ b/c-api/gen.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/hash.po b/c-api/hash.po index 55e397dff..4af9fddc0 100644 --- a/c-api/hash.po +++ b/c-api/hash.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2024-02-23 14:15+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/import.po b/c-api/import.po index 642f57785..1fd7c66b3 100644 --- a/c-api/import.po +++ b/c-api/import.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Ozeas Santos , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-19 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -191,17 +190,17 @@ msgstr "" #: ../../c-api/import.rst:139 msgid "" -"The module's :attr:`__spec__` and :attr:`__loader__` will be set, if not set " -"already, with the appropriate values. The spec's loader will be set to the " -"module's ``__loader__`` (if set) and to an instance of :class:`~importlib." -"machinery.SourceFileLoader` otherwise." +"The module's :attr:`~module.__spec__` and :attr:`~module.__loader__` will be " +"set, if not set already, with the appropriate values. The spec's loader " +"will be set to the module's :attr:`!__loader__` (if set) and to an instance " +"of :class:`~importlib.machinery.SourceFileLoader` otherwise." msgstr "" #: ../../c-api/import.rst:144 msgid "" -"The module's :attr:`__file__` attribute will be set to the code object's :" -"attr:`~codeobject.co_filename`. If applicable, :attr:`__cached__` will also " -"be set." +"The module's :attr:`~module.__file__` attribute will be set to the code " +"object's :attr:`~codeobject.co_filename`. If applicable, :attr:`~module." +"__cached__` will also be set." msgstr "" #: ../../c-api/import.rst:148 @@ -230,17 +229,15 @@ msgstr "" #: ../../c-api/import.rst:157 msgid "" -"The setting of :attr:`__cached__` and :attr:`__loader__` is deprecated. See :" -"class:`~importlib.machinery.ModuleSpec` for alternatives." +"The setting of :attr:`~module.__cached__` and :attr:`~module.__loader__` is " +"deprecated. See :class:`~importlib.machinery.ModuleSpec` for alternatives." msgstr "" #: ../../c-api/import.rst:165 msgid "" -"Like :c:func:`PyImport_ExecCodeModule`, but the :attr:`__file__` attribute " -"of the module object is set to *pathname* if it is non-``NULL``." +"Like :c:func:`PyImport_ExecCodeModule`, but the :attr:`~module.__file__` " +"attribute of the module object is set to *pathname* if it is non-``NULL``." msgstr "" -"Como :c:func:`PyImport_ExecCodeModule`, mas o atributo :attr:`__file__` do " -"objeto módulo é definido como *pathname* se não for ``NULL``." #: ../../c-api/import.rst:168 msgid "See also :c:func:`PyImport_ExecCodeModuleWithPathnames`." @@ -248,18 +245,15 @@ msgstr "Veja também :c:func:`PyImport_ExecCodeModuleWithPathnames`." #: ../../c-api/import.rst:173 msgid "" -"Like :c:func:`PyImport_ExecCodeModuleEx`, but the :attr:`__cached__` " +"Like :c:func:`PyImport_ExecCodeModuleEx`, but the :attr:`~module.__cached__` " "attribute of the module object is set to *cpathname* if it is non-``NULL``. " "Of the three functions, this is the preferred one to use." msgstr "" -"Como :c:func:`PyImport_ExecCodeModuleEx`, mas o atributo :attr:`__cached__` " -"do objeto módulo é definido como *cpathname* se não for ``NULL``. Das três " -"funções, esta é a preferida para usar." #: ../../c-api/import.rst:179 msgid "" -"Setting :attr:`__cached__` is deprecated. See :class:`~importlib.machinery." -"ModuleSpec` for alternatives." +"Setting :attr:`~module.__cached__` is deprecated. See :class:`~importlib." +"machinery.ModuleSpec` for alternatives." msgstr "" #: ../../c-api/import.rst:186 @@ -276,7 +270,7 @@ msgstr "" #: ../../c-api/import.rst:192 msgid "" -"Uses :func:`!imp.source_from_cache()` in calculating the source path if only " +"Uses :func:`!imp.source_from_cache` in calculating the source path if only " "the bytecode path is provided." msgstr "" @@ -376,6 +370,16 @@ msgstr "" "`Tools/freeze/` na distribuição fonte do Python). Sua definição, encontrada " "em :file:`Include/import.h`, é::" +#: ../../c-api/import.rst:270 +msgid "" +"struct _frozen {\n" +" const char *name;\n" +" const unsigned char *code;\n" +" int size;\n" +" bool is_package;\n" +"};" +msgstr "" + #: ../../c-api/import.rst:277 msgid "" "The new ``is_package`` field indicates whether the module is a package or " diff --git a/c-api/index.po b/c-api/index.po index 8a9928fe7..8fc1eeb78 100644 --- a/c-api/index.po +++ b/c-api/index.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Marco Rougeth , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:48+0000\n" -"Last-Translator: Marco Rougeth , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/init.po b/c-api/init.po index 41551dddd..6fccb3f6e 100644 --- a/c-api/init.po +++ b/c-api/init.po @@ -1,50 +1,45 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Rafael Marques , 2021 -# a76d6fb6142d7607ab0526dcbddb02d7_7bf0da0 <3b5fb0f281c8dfb4c0170f2ee2a6cfcf_843623>, 2021 -# Andre Weber, 2021 -# Rodrigo Cândido, 2022 -# Claudio Rogerio Carvalho Filho , 2023 -# Marco Rougeth , 2023 -# i17obot , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../c-api/init.rst:8 msgid "Initialization, Finalization, and Threads" -msgstr "Inicialização, Finalização e Threads" +msgstr "Inicialização, finalização e threads" #: ../../c-api/init.rst:10 -msgid "See also :ref:`Python Initialization Configuration `." +msgid "" +"See :ref:`Python Initialization Configuration ` for details on " +"how to configure the interpreter prior to initialization." msgstr "" -"Consulte também :ref:`Configuração de Inicialização do Python `." +"Veja :ref:`Configuração de inicialização do Python ` para " +"detalhes sobre como configurar o interpretador antes da inicialização." -#: ../../c-api/init.rst:15 +#: ../../c-api/init.rst:16 msgid "Before Python Initialization" -msgstr "Antes da Inicialização do Python" +msgstr "Antes da inicialização do Python" -#: ../../c-api/init.rst:17 +#: ../../c-api/init.rst:18 msgid "" "In an application embedding Python, the :c:func:`Py_Initialize` function " "must be called before using any other Python/C API functions; with the " @@ -56,148 +51,190 @@ msgstr "" "de algumas funções e as :ref:`variáveis globais de configuração `." -#: ../../c-api/init.rst:22 +#: ../../c-api/init.rst:23 msgid "" "The following functions can be safely called before Python is initialized:" msgstr "" "As seguintes funções podem ser seguramente chamadas antes da inicialização " "do Python." -#: ../../c-api/init.rst:24 +#: ../../c-api/init.rst:25 +msgid "Functions that initialize the interpreter:" +msgstr "Funções que inicializam o interpretador:" + +#: ../../c-api/init.rst:27 +msgid ":c:func:`Py_Initialize`" +msgstr ":c:func:`Py_Initialize`" + +#: ../../c-api/init.rst:28 +msgid ":c:func:`Py_InitializeEx`" +msgstr ":c:func:`Py_InitializeEx`" + +#: ../../c-api/init.rst:29 +msgid ":c:func:`Py_InitializeFromConfig`" +msgstr ":c:func:`Py_InitializeFromConfig`" + +#: ../../c-api/init.rst:30 +msgid ":c:func:`Py_BytesMain`" +msgstr ":c:func:`Py_BytesMain`" + +#: ../../c-api/init.rst:31 +msgid ":c:func:`Py_Main`" +msgstr ":c:func:`Py_Main`" + +#: ../../c-api/init.rst:32 +msgid "the runtime pre-initialization functions covered in :ref:`init-config`" +msgstr "" +"as funções de pré-inicialização de tempo de execução cobertas em :ref:`init-" +"config`" + +#: ../../c-api/init.rst:34 msgid "Configuration functions:" -msgstr "Funções de Configuração" +msgstr "Funções de configuração:" -#: ../../c-api/init.rst:26 +#: ../../c-api/init.rst:36 msgid ":c:func:`PyImport_AppendInittab`" msgstr ":c:func:`PyImport_AppendInittab`" -#: ../../c-api/init.rst:27 +#: ../../c-api/init.rst:37 msgid ":c:func:`PyImport_ExtendInittab`" msgstr ":c:func:`PyImport_ExtendInittab`" -#: ../../c-api/init.rst:28 +#: ../../c-api/init.rst:38 msgid ":c:func:`!PyInitFrozenExtensions`" -msgstr "" +msgstr ":c:func:`!PyInitFrozenExtensions`" -#: ../../c-api/init.rst:29 +#: ../../c-api/init.rst:39 msgid ":c:func:`PyMem_SetAllocator`" msgstr ":c:func:`PyMem_SetAllocator`" -#: ../../c-api/init.rst:30 +#: ../../c-api/init.rst:40 msgid ":c:func:`PyMem_SetupDebugHooks`" msgstr ":c:func:`PyMem_SetupDebugHooks`" -#: ../../c-api/init.rst:31 +#: ../../c-api/init.rst:41 msgid ":c:func:`PyObject_SetArenaAllocator`" msgstr ":c:func:`PyObject_SetArenaAllocator`" -#: ../../c-api/init.rst:32 +#: ../../c-api/init.rst:42 msgid ":c:func:`Py_SetProgramName`" msgstr ":c:func:`Py_SetProgramName`" -#: ../../c-api/init.rst:33 +#: ../../c-api/init.rst:43 msgid ":c:func:`Py_SetPythonHome`" msgstr ":c:func:`Py_SetPythonHome`" -#: ../../c-api/init.rst:34 +#: ../../c-api/init.rst:44 msgid ":c:func:`PySys_ResetWarnOptions`" msgstr ":c:func:`PySys_ResetWarnOptions`" -#: ../../c-api/init.rst:36 +#: ../../c-api/init.rst:45 +msgid "the configuration functions covered in :ref:`init-config`" +msgstr "as funções de configuração cobertas em :ref:`init-config`" + +#: ../../c-api/init.rst:47 msgid "Informative functions:" -msgstr "Funções Informativas:" +msgstr "Funções informativas:" -#: ../../c-api/init.rst:38 +#: ../../c-api/init.rst:49 ../../c-api/init.rst:57 msgid ":c:func:`Py_IsInitialized`" msgstr ":c:func:`Py_IsInitialized`" -#: ../../c-api/init.rst:39 +#: ../../c-api/init.rst:50 msgid ":c:func:`PyMem_GetAllocator`" msgstr ":c:func:`PyMem_GetAllocator`" -#: ../../c-api/init.rst:40 +#: ../../c-api/init.rst:51 msgid ":c:func:`PyObject_GetArenaAllocator`" msgstr ":c:func:`PyObject_GetArenaAllocator`" -#: ../../c-api/init.rst:41 +#: ../../c-api/init.rst:52 msgid ":c:func:`Py_GetBuildInfo`" msgstr ":c:func:`Py_GetBuildInfo`" -#: ../../c-api/init.rst:42 +#: ../../c-api/init.rst:53 msgid ":c:func:`Py_GetCompiler`" msgstr ":c:func:`Py_GetCompiler`" -#: ../../c-api/init.rst:43 +#: ../../c-api/init.rst:54 msgid ":c:func:`Py_GetCopyright`" msgstr ":c:func:`Py_GetCopyright`" -#: ../../c-api/init.rst:44 +#: ../../c-api/init.rst:55 msgid ":c:func:`Py_GetPlatform`" msgstr ":c:func:`Py_GetPlatform`" -#: ../../c-api/init.rst:45 +#: ../../c-api/init.rst:56 msgid ":c:func:`Py_GetVersion`" msgstr ":c:func:`Py_GetVersion`" -#: ../../c-api/init.rst:47 +#: ../../c-api/init.rst:59 msgid "Utilities:" msgstr "Utilitários:" -#: ../../c-api/init.rst:49 +#: ../../c-api/init.rst:61 msgid ":c:func:`Py_DecodeLocale`" msgstr ":c:func:`Py_DecodeLocale`" -#: ../../c-api/init.rst:51 +#: ../../c-api/init.rst:62 +msgid "" +"the status reporting and utility functions covered in :ref:`init-config`" +msgstr "" +"o relatório de status é funções utilitárias cobertas em :ref:`init-config`" + +#: ../../c-api/init.rst:64 msgid "Memory allocators:" msgstr "Alocadores de memória:" -#: ../../c-api/init.rst:53 +#: ../../c-api/init.rst:66 msgid ":c:func:`PyMem_RawMalloc`" msgstr ":c:func:`PyMem_RawMalloc`" -#: ../../c-api/init.rst:54 +#: ../../c-api/init.rst:67 msgid ":c:func:`PyMem_RawRealloc`" msgstr ":c:func:`PyMem_RawRealloc`" -#: ../../c-api/init.rst:55 +#: ../../c-api/init.rst:68 msgid ":c:func:`PyMem_RawCalloc`" msgstr ":c:func:`PyMem_RawCalloc`" -#: ../../c-api/init.rst:56 +#: ../../c-api/init.rst:69 msgid ":c:func:`PyMem_RawFree`" msgstr ":c:func:`PyMem_RawFree`" -#: ../../c-api/init.rst:58 +#: ../../c-api/init.rst:71 msgid "Synchronization:" -msgstr "" +msgstr "Sincronização:" -#: ../../c-api/init.rst:60 +#: ../../c-api/init.rst:73 msgid ":c:func:`PyMutex_Lock`" -msgstr "" +msgstr ":c:func:`PyMutex_Lock`" -#: ../../c-api/init.rst:61 +#: ../../c-api/init.rst:74 msgid ":c:func:`PyMutex_Unlock`" -msgstr "" +msgstr ":c:func:`PyMutex_Unlock`" -#: ../../c-api/init.rst:65 +#: ../../c-api/init.rst:78 msgid "" -"The following functions **should not be called** before :c:func:" -"`Py_Initialize`: :c:func:`Py_EncodeLocale`, :c:func:`Py_GetPath`, :c:func:" +"Despite their apparent similarity to some of the functions listed above, the " +"following functions **should not be called** before the interpreter has been " +"initialized: :c:func:`Py_EncodeLocale`, :c:func:`Py_GetPath`, :c:func:" "`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`, :c:func:" "`Py_GetProgramFullPath`, :c:func:`Py_GetPythonHome`, :c:func:" -"`Py_GetProgramName` and :c:func:`PyEval_InitThreads`." +"`Py_GetProgramName`, :c:func:`PyEval_InitThreads`, and :c:func:`Py_RunMain`." msgstr "" -"As seguintes funções **não devem ser chamadas** antes :c:func:" -"`Py_Initialize`: :c:func:`Py_EncodeLocale`, :c:func:`Py_GetPath`, :c:func:" +"Apesar de sua aparente semelhança com algumas das funções listadas acima, as " +"seguintes funções **não devem ser chamadas** antes que o interpretador tenha " +"sido inicializado: :c:func:`Py_EncodeLocale`, :c:func:`Py_GetPath`, :c:func:" "`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`, :c:func:" "`Py_GetProgramFullPath`, :c:func:`Py_GetPythonHome`, :c:func:" -"`Py_GetProgramName` e :c:func:`PyEval_InitThreads`." +"`Py_GetProgramName`, :c:func:`PyEval_InitThreads`, e :c:func:`Py_RunMain`." -#: ../../c-api/init.rst:75 +#: ../../c-api/init.rst:90 msgid "Global configuration variables" msgstr "Variáveis de configuração global" -#: ../../c-api/init.rst:77 +#: ../../c-api/init.rst:92 msgid "" "Python has variables for the global configuration to control different " "features and options. By default, these flags are controlled by :ref:" @@ -208,7 +245,7 @@ msgstr "" "controlados por :ref:`opções de linha de comando `." -#: ../../c-api/init.rst:81 +#: ../../c-api/init.rst:96 msgid "" "When a flag is set by an option, the value of the flag is the number of " "times that the option was set. For example, ``-b`` sets :c:data:" @@ -220,14 +257,17 @@ msgstr "" "`Py_BytesWarningFlag` para 1 e ``-bb`` define :c:data:`Py_BytesWarningFlag` " "para 2." -#: ../../c-api/init.rst:87 +#: ../../c-api/init.rst:102 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "bytes_warning` should be used instead, see :ref:`Python Initialization " "Configuration `." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração :c:member:`PyConfig.bytes_warning` deve ser usada em seu lugar, " +"consulte :ref:`Configuração de inicialização do Python `." -#: ../../c-api/init.rst:91 +#: ../../c-api/init.rst:106 msgid "" "Issue a warning when comparing :class:`bytes` or :class:`bytearray` with :" "class:`str` or :class:`bytes` with :class:`int`. Issue an error if greater " @@ -237,18 +277,21 @@ msgstr "" "`str` ou :class:`bytes` com :class:`int`. Emite um erro se for maior ou " "igual a ``2``." -#: ../../c-api/init.rst:95 +#: ../../c-api/init.rst:110 msgid "Set by the :option:`-b` option." msgstr "Definida pela opção :option:`-b`." -#: ../../c-api/init.rst:101 +#: ../../c-api/init.rst:116 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "parser_debug` should be used instead, see :ref:`Python Initialization " "Configuration `." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração :c:member:`PyConfig.parser_debug` deve ser usada em seu lugar, " +"consulte :ref:`Configuração de inicialização do Python `." -#: ../../c-api/init.rst:105 +#: ../../c-api/init.rst:120 msgid "" "Turn on parser debugging output (for expert only, depending on compilation " "options)." @@ -256,7 +299,7 @@ msgstr "" "Ativa a saída de depuração do analisador sintático (somente para " "especialistas, dependendo das opções de compilação)." -#: ../../c-api/init.rst:108 +#: ../../c-api/init.rst:123 msgid "" "Set by the :option:`-d` option and the :envvar:`PYTHONDEBUG` environment " "variable." @@ -264,22 +307,25 @@ msgstr "" "Definida pela a opção :option:`-d` e a variável de ambiente :envvar:" "`PYTHONDEBUG`." -#: ../../c-api/init.rst:115 +#: ../../c-api/init.rst:130 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "write_bytecode` should be used instead, see :ref:`Python Initialization " "Configuration `." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração :c:member:`PyConfig.write_bytecode` deve ser usada em seu " +"lugar, consulte :ref:`Configuração de inicialização do Python `." -#: ../../c-api/init.rst:119 +#: ../../c-api/init.rst:134 msgid "" "If set to non-zero, Python won't try to write ``.pyc`` files on the import " "of source modules." msgstr "" -"Se definido como diferente de zero, o Python não tentará escrever arquivos " +"Se definida como diferente de zero, o Python não tentará escrever arquivos " "``.pyc`` na importação de módulos fonte." -#: ../../c-api/init.rst:122 +#: ../../c-api/init.rst:137 msgid "" "Set by the :option:`-B` option and the :envvar:`PYTHONDONTWRITEBYTECODE` " "environment variable." @@ -287,14 +333,17 @@ msgstr "" "Definida pela opção :option:`-B` e pela variável de ambiente :envvar:" "`PYTHONDONTWRITEBYTECODE`." -#: ../../c-api/init.rst:129 +#: ../../c-api/init.rst:144 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "pathconfig_warnings` should be used instead, see :ref:`Python Initialization " "Configuration `." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração :c:member:`PyConfig.pathconfig_warnings` deve ser usada em seu " +"lugar, consulte :ref:`Configuração de inicialização do Python `." -#: ../../c-api/init.rst:133 +#: ../../c-api/init.rst:148 msgid "" "Suppress error messages when calculating the module search path in :c:func:" "`Py_GetPath`." @@ -302,18 +351,24 @@ msgstr "" "Suprime mensagens de erro ao calcular o caminho de pesquisa do módulo em :c:" "func:`Py_GetPath`." -#: ../../c-api/init.rst:136 +#: ../../c-api/init.rst:151 msgid "Private flag used by ``_freeze_module`` and ``frozenmain`` programs." msgstr "" +"Sinalizador privado usado pelos programas ``_freeze_module`` e " +"``frozenmain``." -#: ../../c-api/init.rst:142 +#: ../../c-api/init.rst:157 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "hash_seed` and :c:member:`PyConfig.use_hash_seed` should be used instead, " "see :ref:`Python Initialization Configuration `." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração de :c:member:`PyConfig.hash_seed` e :c:member:`PyConfig." +"use_hash_seed` deve ser usada em seu lugar, consulte :ref:`Configuração de " +"inicialização do Python `." -#: ../../c-api/init.rst:147 +#: ../../c-api/init.rst:162 msgid "" "Set to ``1`` if the :envvar:`PYTHONHASHSEED` environment variable is set to " "a non-empty string." @@ -321,7 +376,7 @@ msgstr "" "Definida como ``1`` se a variável de ambiente :envvar:`PYTHONHASHSEED` " "estiver definida como uma string não vazia." -#: ../../c-api/init.rst:150 +#: ../../c-api/init.rst:165 msgid "" "If the flag is non-zero, read the :envvar:`PYTHONHASHSEED` environment " "variable to initialize the secret hash seed." @@ -329,31 +384,39 @@ msgstr "" "Se o sinalizador for diferente de zero, lê a variável de ambiente :envvar:" "`PYTHONHASHSEED` para inicializar a semente de hash secreta." -#: ../../c-api/init.rst:157 +#: ../../c-api/init.rst:172 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "use_environment` should be used instead, see :ref:`Python Initialization " "Configuration `." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração :c:member:`PyConfig.use_environment` deve ser usada em seu " +"lugar, consulte :ref:`Configuração de inicialização do Python `." -#: ../../c-api/init.rst:161 +#: ../../c-api/init.rst:176 msgid "" "Ignore all :envvar:`!PYTHON*` environment variables, e.g. :envvar:" "`PYTHONPATH` and :envvar:`PYTHONHOME`, that might be set." msgstr "" +"Ignora todas as variáveis de ambiente :envvar:`!PYTHON*`, por exemplo :" +"envvar:`PYTHONPATH` e :envvar:`PYTHONHOME`, que podem estar definidas." -#: ../../c-api/init.rst:164 +#: ../../c-api/init.rst:179 msgid "Set by the :option:`-E` and :option:`-I` options." msgstr "Definida pelas opções :option:`-E` e :option:`-I`." -#: ../../c-api/init.rst:170 +#: ../../c-api/init.rst:185 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "inspect` should be used instead, see :ref:`Python Initialization " "Configuration `." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração :c:member:`PyConfig.inspect` deve ser usada em seu lugar, " +"consulte :ref:`Configuração de inicialização do Python `." -#: ../../c-api/init.rst:174 +#: ../../c-api/init.rst:189 msgid "" "When a script is passed as first argument or the :option:`-c` option is " "used, enter interactive mode after executing the script or the command, even " @@ -363,7 +426,7 @@ msgstr "" "usada, entre no modo interativo após executar o script ou o comando, mesmo " "quando :data:`sys.stdin` não parece ser um terminal." -#: ../../c-api/init.rst:178 +#: ../../c-api/init.rst:193 msgid "" "Set by the :option:`-i` option and the :envvar:`PYTHONINSPECT` environment " "variable." @@ -371,25 +434,31 @@ msgstr "" "Definida pela opção :option:`-i` e pela variável de ambiente :envvar:" "`PYTHONINSPECT`." -#: ../../c-api/init.rst:185 +#: ../../c-api/init.rst:200 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "interactive` should be used instead, see :ref:`Python Initialization " "Configuration `." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração :c:member:`PyConfig.interactive` deve ser usada em seu lugar, " +"consulte :ref:`Configuração de inicialização do Python `." -#: ../../c-api/init.rst:189 +#: ../../c-api/init.rst:204 msgid "Set by the :option:`-i` option." msgstr "Definida pela opção :option:`-i`." -#: ../../c-api/init.rst:195 +#: ../../c-api/init.rst:210 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "isolated` should be used instead, see :ref:`Python Initialization " "Configuration `." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração :c:member:`PyConfig.isolated` deve ser usada em seu lugar, " +"consulte :ref:`Configuração de inicialização do Python `." -#: ../../c-api/init.rst:199 +#: ../../c-api/init.rst:214 msgid "" "Run Python in isolated mode. In isolated mode :data:`sys.path` contains " "neither the script's directory nor the user's site-packages directory." @@ -398,18 +467,22 @@ msgstr "" "contém nem o diretório do script nem o diretório de pacotes de sites do " "usuário." -#: ../../c-api/init.rst:202 +#: ../../c-api/init.rst:217 msgid "Set by the :option:`-I` option." msgstr "Definida pela opção :option:`-I`." -#: ../../c-api/init.rst:210 +#: ../../c-api/init.rst:225 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyPreConfig." "legacy_windows_fs_encoding` should be used instead, see :ref:`Python " "Initialization Configuration `." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração :c:member:`PyPreConfig.legacy_windows_fs_encoding` deve ser " +"usada em seu lugar, consulte :ref:`Configuração de inicialização do Python " +"`." -#: ../../c-api/init.rst:214 +#: ../../c-api/init.rst:229 msgid "" "If the flag is non-zero, use the ``mbcs`` encoding with ``replace`` error " "handler, instead of the UTF-8 encoding with ``surrogatepass`` error handler, " @@ -420,7 +493,7 @@ msgstr "" "erros ``surrogatepass``, para a codificação do sistema de arquivos e :term:" "`tratador de erros e codificação do sistema de arquivos`." -#: ../../c-api/init.rst:218 +#: ../../c-api/init.rst:233 msgid "" "Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` environment " "variable is set to a non-empty string." @@ -428,28 +501,33 @@ msgstr "" "Definida como ``1`` se a variável de ambiente :envvar:" "`PYTHONLEGACYWINDOWSFSENCODING` estiver definida como uma string não vazia." -#: ../../c-api/init.rst:221 +#: ../../c-api/init.rst:236 msgid "See :pep:`529` for more details." msgstr "Veja :pep:`529` para mais detalhes." -#: ../../c-api/init.rst:223 ../../c-api/init.rst:241 -msgid ":ref:`Availability `: Windows." -msgstr ":ref:`Disponibilidade `: Windows." +#: ../../c-api/init.rst:238 ../../c-api/init.rst:256 +msgid "Availability" +msgstr "Disponibilidade" -#: ../../c-api/init.rst:229 +#: ../../c-api/init.rst:244 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "legacy_windows_stdio` should be used instead, see :ref:`Python " "Initialization Configuration `." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração :c:member:`PyConfig.legacy_windows_stdio` deve ser usada em seu " +"lugar, consulte :ref:`Configuração de inicialização do Python `." -#: ../../c-api/init.rst:233 +#: ../../c-api/init.rst:248 msgid "" "If the flag is non-zero, use :class:`io.FileIO` instead of :class:`!io." "_WindowsConsoleIO` for :mod:`sys` standard streams." msgstr "" +"Se o sinalizador for diferente de zero, usa :class:`io.FileIO` em vez de :" +"class:`!io._WindowsConsoleIO` para fluxos padrão :mod:`sys`." -#: ../../c-api/init.rst:236 +#: ../../c-api/init.rst:251 msgid "" "Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSSTDIO` environment variable " "is set to a non-empty string." @@ -457,18 +535,21 @@ msgstr "" "Definida como ``1`` se a variável de ambiente :envvar:" "`PYTHONLEGACYWINDOWSSTDIO` estiver definida como uma string não vazia." -#: ../../c-api/init.rst:239 +#: ../../c-api/init.rst:254 msgid "See :pep:`528` for more details." -msgstr "Veja :pep:`528` para mais detalhes." +msgstr "Veja a :pep:`528` para mais detalhes." -#: ../../c-api/init.rst:247 +#: ../../c-api/init.rst:262 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "site_import` should be used instead, see :ref:`Python Initialization " "Configuration `." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração :c:member:`PyConfig.site_import` deve ser usada em seu lugar, " +"consulte :ref:`Configuração de inicialização do Python `." -#: ../../c-api/init.rst:251 +#: ../../c-api/init.rst:266 msgid "" "Disable the import of the module :mod:`site` and the site-dependent " "manipulations of :data:`sys.path` that it entails. Also disable these " @@ -480,18 +561,21 @@ msgstr "" "manipulações se :mod:`site` for explicitamente importado mais tarde (chame :" "func:`site.main` se você quiser que eles sejam acionados)." -#: ../../c-api/init.rst:256 +#: ../../c-api/init.rst:271 msgid "Set by the :option:`-S` option." msgstr "Definida pela opção :option:`-S`." -#: ../../c-api/init.rst:262 +#: ../../c-api/init.rst:277 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "user_site_directory` should be used instead, see :ref:`Python Initialization " "Configuration `." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração :c:member:`PyConfig.user_site_directory` deve ser usada em seu " +"lugar, consulte :ref:`Configuração de inicialização do Python `." -#: ../../c-api/init.rst:266 +#: ../../c-api/init.rst:281 msgid "" "Don't add the :data:`user site-packages directory ` to :data:" "`sys.path`." @@ -499,7 +583,7 @@ msgstr "" "Não adiciona o :data:`diretório site-packages de usuário ` a :data:`sys.path`." -#: ../../c-api/init.rst:269 +#: ../../c-api/init.rst:284 msgid "" "Set by the :option:`-s` and :option:`-I` options, and the :envvar:" "`PYTHONNOUSERSITE` environment variable." @@ -507,14 +591,17 @@ msgstr "" "Definida pelas opções :option:`-s` e :option:`-I`, e pela variável de " "ambiente :envvar:`PYTHONNOUSERSITE`." -#: ../../c-api/init.rst:276 +#: ../../c-api/init.rst:291 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "optimization_level` should be used instead, see :ref:`Python Initialization " "Configuration `." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração :c:member:`PyConfig.optimization_level` deve ser usada em seu " +"lugar, consulte :ref:`Configuração de inicialização do Python `." -#: ../../c-api/init.rst:280 +#: ../../c-api/init.rst:295 msgid "" "Set by the :option:`-O` option and the :envvar:`PYTHONOPTIMIZE` environment " "variable." @@ -522,36 +609,42 @@ msgstr "" "Definida pela opção :option:`-O` e pela variável de ambiente :envvar:" "`PYTHONOPTIMIZE`." -#: ../../c-api/init.rst:287 +#: ../../c-api/init.rst:302 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "quiet` should be used instead, see :ref:`Python Initialization Configuration " "`." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração :c:member:`PyConfig.quiet` deve ser usada em seu lugar, " +"consulte :ref:`Configuração de inicialização do Python `." -#: ../../c-api/init.rst:291 +#: ../../c-api/init.rst:306 msgid "" "Don't display the copyright and version messages even in interactive mode." msgstr "" -"Não exibe as mensagens de direito autoral e de versão nem mesmo no modo " +"Não exibe as mensagens de direitos autorais e de versão nem mesmo no modo " "interativo." -#: ../../c-api/init.rst:293 +#: ../../c-api/init.rst:308 msgid "Set by the :option:`-q` option." msgstr "Definida pela opção :option:`-q`." -#: ../../c-api/init.rst:301 +#: ../../c-api/init.rst:316 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "buffered_stdio` should be used instead, see :ref:`Python Initialization " "Configuration `." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração :c:member:`PyConfig.buffered_stdio` deve ser usada em seu " +"lugar, consulte :ref:`Configuração de inicialização do Python `." -#: ../../c-api/init.rst:305 +#: ../../c-api/init.rst:320 msgid "Force the stdout and stderr streams to be unbuffered." msgstr "Força os fluxos stdout e stderr a não serem armazenados em buffer." -#: ../../c-api/init.rst:307 +#: ../../c-api/init.rst:322 msgid "" "Set by the :option:`-u` option and the :envvar:`PYTHONUNBUFFERED` " "environment variable." @@ -559,14 +652,17 @@ msgstr "" "Definida pela opção :option:`-u` e pela variável de ambiente :envvar:" "`PYTHONUNBUFFERED`." -#: ../../c-api/init.rst:314 +#: ../../c-api/init.rst:329 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "verbose` should be used instead, see :ref:`Python Initialization " "Configuration `." msgstr "" +"Esta API é mantida para compatibilidade com versões anteriores: a " +"configuração :c:member:`PyConfig.verbose` deve ser usada em seu lugar, " +"consulte :ref:`Configuração de inicialização do Python `." -#: ../../c-api/init.rst:318 +#: ../../c-api/init.rst:333 msgid "" "Print a message each time a module is initialized, showing the place " "(filename or built-in module) from which it is loaded. If greater or equal " @@ -579,7 +675,7 @@ msgstr "" "a busca por um módulo. Também fornece informações sobre a limpeza do módulo " "na saída." -#: ../../c-api/init.rst:323 +#: ../../c-api/init.rst:338 msgid "" "Set by the :option:`-v` option and the :envvar:`PYTHONVERBOSE` environment " "variable." @@ -587,11 +683,11 @@ msgstr "" "Definida pela a opção :option:`-v` e a variável de ambiente :envvar:" "`PYTHONVERBOSE`." -#: ../../c-api/init.rst:330 +#: ../../c-api/init.rst:345 msgid "Initializing and finalizing the interpreter" msgstr "Inicializando e encerrando o interpretador" -#: ../../c-api/init.rst:345 +#: ../../c-api/init.rst:360 msgid "" "Initialize the Python interpreter. In an application embedding Python, " "this should be called before using any other Python/C API functions; see :" @@ -602,50 +698,90 @@ msgstr "" "veja :ref:`Antes da Inicialização do Python ` para algumas " "exceções." -#: ../../c-api/init.rst:349 +#: ../../c-api/init.rst:364 msgid "" "This initializes the table of loaded modules (``sys.modules``), and creates " -"the fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. It " +"the fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. It " "also initializes the module search path (``sys.path``). It does not set " -"``sys.argv``; use the new :c:type:`PyConfig` API of the :ref:`Python " -"Initialization Configuration ` for that. This is a no-op when " -"called for a second time (without calling :c:func:`Py_FinalizeEx` first). " -"There is no return value; it is a fatal error if the initialization fails." -msgstr "" - -#: ../../c-api/init.rst:359 ../../c-api/init.rst:373 -msgid "" -"Use the :c:func:`Py_InitializeFromConfig` function to customize the :ref:" -"`Python Initialization Configuration `." +"``sys.argv``; use the :ref:`Python Initialization Configuration ` API for that. This is a no-op when called for a second time " +"(without calling :c:func:`Py_FinalizeEx` first). There is no return value; " +"it is a fatal error if the initialization fails." +msgstr "" +"Isso inicializa a tabela de módulos carregados (``sys.modules``) e cria os " +"módulos fundamentais :mod:`builtins`, :mod:`__main__` e :mod:`sys`. Também " +"inicializa o caminho de pesquisa de módulos (``sys.path``). Isso não define " +"``sys.argv``; use a API da :ref:`Configuração de inicialização do Python " +"` para isso. Isso é um no-op quando chamado pela segunda vez " +"(sem chamar :c:func:`Py_FinalizeEx` primeiro). Não há valor de retorno; é um " +"erro fatal se a inicialização falhar." + +#: ../../c-api/init.rst:372 ../../c-api/init.rst:386 +msgid "" +"Use :c:func:`Py_InitializeFromConfig` to customize the :ref:`Python " +"Initialization Configuration `." msgstr "" +"Usa :c:func:`Py_InitializeFromConfig` para personalizar a :ref:`Configuração " +"de inicialização do Python `." -#: ../../c-api/init.rst:363 +#: ../../c-api/init.rst:376 msgid "" "On Windows, changes the console mode from ``O_TEXT`` to ``O_BINARY``, which " "will also affect non-Python uses of the console using the C Runtime." msgstr "" +"No Windows, altera o modo do console de ``O_TEXT`` para ``O_BINARY``, o que " +"também afetará usos não Python do console usando o Runtime C." -#: ../../c-api/init.rst:369 +#: ../../c-api/init.rst:382 msgid "" "This function works like :c:func:`Py_Initialize` if *initsigs* is ``1``. If " "*initsigs* is ``0``, it skips initialization registration of signal " -"handlers, which might be useful when Python is embedded." +"handlers, which may be useful when CPython is embedded as part of a larger " +"application." +msgstr "" +"Esta função funciona como :c:func:`Py_Initialize` se *initsigs* for ``1``. " +"Se *initsigs* for ``0``, ela pula o registro de inicialização de " +"manipuladores de sinal, o que pode ser útil quando o CPython é incorporado " +"como parte de uma aplicação maior." + +#: ../../c-api/init.rst:392 +msgid "" +"Initialize Python from *config* configuration, as described in :ref:`init-" +"from-config`." msgstr "" +"Inicializa o Python a partir da configuração *config*, conforme descrito em :" +"ref:`init-from-config`." -#: ../../c-api/init.rst:379 +#: ../../c-api/init.rst:395 +msgid "" +"See the :ref:`init-config` section for details on pre-initializing the " +"interpreter, populating the runtime configuration structure, and querying " +"the returned status structure." +msgstr "" +"Consulte a seção :ref:`init-config` para obter detalhes sobre como pré-" +"inicializar o interpretador, preencher a estrutura de configuração do tempo " +"de execução e consultar a estrutura de status retornada." + +#: ../../c-api/init.rst:402 msgid "" "Return true (nonzero) when the Python interpreter has been initialized, " "false (zero) if not. After :c:func:`Py_FinalizeEx` is called, this returns " "false until :c:func:`Py_Initialize` is called again." msgstr "" +"Retorna true (diferente de zero) quando o interpretador Python foi " +"inicializado, false (zero) se não. Após :c:func:`Py_FinalizeEx` ser chamado, " +"isso retorna false até que :c:func:`Py_Initialize` seja chamado novamente." -#: ../../c-api/init.rst:386 +#: ../../c-api/init.rst:409 msgid "" "Return true (non-zero) if the main Python interpreter is :term:`shutting " "down `. Return false (zero) otherwise." msgstr "" +"Retorna verdadeiro (diferente de zero) se o interpretador Python principal " +"estiver em :term:`desligamento `. Retorna falso (zero) " +"caso contrário." -#: ../../c-api/init.rst:394 +#: ../../c-api/init.rst:417 msgid "" "Undo all initializations made by :c:func:`Py_Initialize` and subsequent use " "of Python/C API functions, and destroy all sub-interpreters (see :c:func:" @@ -655,21 +791,27 @@ msgid "" "second time (without calling :c:func:`Py_Initialize` again first)." msgstr "" -#: ../../c-api/init.rst:401 +#: ../../c-api/init.rst:424 msgid "" "Since this is the reverse of :c:func:`Py_Initialize`, it should be called in " "the same thread with the same interpreter active. That means the main " "thread and the main interpreter. This should never be called while :c:func:" "`Py_RunMain` is running." msgstr "" +"Como isso é o inverso de :c:func:`Py_Initialize`, ele deve ser chamado na " +"mesma thread com o mesmo interpretador ativo. Isso significa a thread " +"principal e o interpretador principal. Isso nunca deve ser chamado enquanto :" +"c:func:`Py_RunMain` estiver em execução." -#: ../../c-api/init.rst:406 +#: ../../c-api/init.rst:429 msgid "" "Normally the return value is ``0``. If there were errors during finalization " "(flushing buffered data), ``-1`` is returned." msgstr "" +"Normalmente, o valor de retorno é ``0``. Se houver erros durante a " +"finalização (limpeza de dados armazenados em buffer), ``-1`` será retornado." -#: ../../c-api/init.rst:410 +#: ../../c-api/init.rst:433 msgid "" "This function is provided for a number of reasons. An embedding application " "might want to restart Python without having to restart the application " @@ -679,8 +821,15 @@ msgid "" "in an application a developer might want to free all memory allocated by " "Python before exiting from the application." msgstr "" +"Esta função é fornecida por vários motivos. Uma aplicação de incorporação " +"pode querer reiniciar o Python sem precisar reiniciar a própria aplicação. " +"Uma aplicação que carregou o interpretador Python de uma biblioteca " +"carregável dinamicamente (ou DLL) pode querer liberar toda a memória alocada " +"pelo Python antes de descarregar a DLL. Durante uma busca por vazamentos de " +"memória em uma aplicação, um desenvolvedor pode querer liberar toda a " +"memória alocada pelo Python antes de sair da aplicação." -#: ../../c-api/init.rst:418 +#: ../../c-api/init.rst:441 msgid "" "**Bugs and caveats:** The destruction of modules and objects in modules is " "done in random order; this may cause destructors (:meth:`~object.__del__` " @@ -695,7 +844,7 @@ msgid "" "more than once." msgstr "" -#: ../../c-api/init.rst:429 +#: ../../c-api/init.rst:452 msgid "" "Raises an :ref:`auditing event ` ``cpython." "_PySys_ClearAuditHooks`` with no arguments." @@ -703,24 +852,215 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``cpython." "_PySys_ClearAuditHooks`` sem argumentos." -#: ../../c-api/init.rst:435 +#: ../../c-api/init.rst:459 msgid "" "This is a backwards-compatible version of :c:func:`Py_FinalizeEx` that " "disregards the return value." msgstr "" +"Esta é uma versão compatível com retrocompatibilidade de :c:func:" +"`Py_FinalizeEx` que desconsidera o valor de retorno." + +#: ../../c-api/init.rst:465 +msgid "" +"Similar to :c:func:`Py_Main` but *argv* is an array of bytes strings, " +"allowing the calling application to delegate the text decoding step to the " +"CPython runtime." +msgstr "" +"Semelhante a :c:func:`Py_Main`, mas *argv* é um vetor de strings de bytes, " +"permitindo que o aplicativo de chamada delegue a etapa de decodificação de " +"texto ao tempo de execução do CPython." + +#: ../../c-api/init.rst:474 +msgid "" +"The main program for the standard interpreter, encapsulating a full " +"initialization/finalization cycle, as well as additional behaviour to " +"implement reading configurations settings from the environment and command " +"line, and then executing ``__main__`` in accordance with :ref:`using-on-" +"cmdline`." +msgstr "" +"O programa principal para o interpretador padrão, encapsulando um ciclo " +"completo de inicialização/finalização, bem como comportamento adicional para " +"implementar a leitura de configurações do ambiente e da linha de comando e, " +"em seguida, executar ``__main__`` de acordo com :ref:`using-on-cmdline`." + +#: ../../c-api/init.rst:480 +msgid "" +"This is made available for programs which wish to support the full CPython " +"command line interface, rather than just embedding a Python runtime in a " +"larger application." +msgstr "" +"Isso é disponibilizado para programas que desejam oferecer suporte à " +"interface de linha de comando completa do CPython, em vez de apenas " +"incorporar um tempo de execução do Python em uma aplicação maior." + +#: ../../c-api/init.rst:484 +msgid "" +"The *argc* and *argv* parameters are similar to those which are passed to a " +"C program's :c:func:`main` function, except that the *argv* entries are " +"first converted to ``wchar_t`` using :c:func:`Py_DecodeLocale`. It is also " +"important to note that the argument list entries may be modified to point to " +"strings other than those passed in (however, the contents of the strings " +"pointed to by the argument list are not modified)." +msgstr "" +"Os parâmetros *argc* e *argv* são semelhantes aos passados ​​para a função :c:" +"func:`main` de um programa C, exceto que as entradas *argv* são primeiro " +"convertidas para ``wchar_t`` usando :c:func:`Py_DecodeLocale`. Também é " +"importante observar que as entradas da lista de argumentos podem ser " +"modificadas para apontar para strings diferentes daquelas passadas (no " +"entanto, o conteúdo das strings apontadas pela lista de argumentos não é " +"modificado)." + +#: ../../c-api/init.rst:491 +msgid "" +"The return value will be ``0`` if the interpreter exits normally (i.e., " +"without an exception), ``1`` if the interpreter exits due to an exception, " +"or ``2`` if the argument list does not represent a valid Python command line." +msgstr "" +"O valor de retorno será ``0`` se o interpretador sair normalmente (ou seja, " +"sem uma exceção), ``1`` se o interpretador sair devido a uma exceção ou " +"``2`` se a lista de argumentos não representar uma linha de comando Python " +"válida." + +#: ../../c-api/init.rst:496 +msgid "" +"Note that if an otherwise unhandled :exc:`SystemExit` is raised, this " +"function will not return ``1``, but exit the process, as long as " +"``Py_InspectFlag`` is not set. If ``Py_InspectFlag`` is set, execution will " +"drop into the interactive Python prompt, at which point a second otherwise " +"unhandled :exc:`SystemExit` will still exit the process, while any other " +"means of exiting will set the return value as described above." +msgstr "" +"Observe que, se uma :exc:`SystemExit`, que de outra forma não seria tratado, " +"for levantada, esta função não retornará ``1``, mas encerrará o processo, " +"desde que ``Py_InspectFlag`` não esteja definido. Se ``Py_InspectFlag`` " +"estiver definido, a execução cairá no prompt interativo do Python, momento " +"em que um segundo :exc:`SystemExit`, que de outra forma não seria tratado, " +"ainda encerrará o processo, enquanto qualquer outro meio de saída definirá o " +"valor de retorno conforme descrito acima." + +#: ../../c-api/init.rst:503 +msgid "" +"In terms of the CPython runtime configuration APIs documented in the :ref:" +"`runtime configuration ` section (and without accounting for " +"error handling), ``Py_Main`` is approximately equivalent to::" +msgstr "" +"Em termos das APIs de configuração de tempo de execução do CPython " +"documentadas na seção de :ref:`configuração de runtime ` (e sem " +"levar em conta o tratamento de erros), ``Py_Main`` é aproximadamente " +"equivalente a::" + +#: ../../c-api/init.rst:507 +msgid "" +"PyConfig config;\n" +"PyConfig_InitPythonConfig(&config);\n" +"PyConfig_SetArgv(&config, argc, argv);\n" +"Py_InitializeFromConfig(&config);\n" +"PyConfig_Clear(&config);\n" +"\n" +"Py_RunMain();" +msgstr "" +"PyConfig config;\n" +"PyConfig_InitPythonConfig(&config);\n" +"PyConfig_SetArgv(&config, argc, argv);\n" +"Py_InitializeFromConfig(&config);\n" +"PyConfig_Clear(&config);\n" +"\n" +"Py_RunMain();" + +#: ../../c-api/init.rst:515 +msgid "" +"In normal usage, an embedding application will call this function *instead* " +"of calling :c:func:`Py_Initialize`, :c:func:`Py_InitializeEx` or :c:func:" +"`Py_InitializeFromConfig` directly, and all settings will be applied as " +"described elsewhere in this documentation. If this function is instead " +"called *after* a preceding runtime initialization API call, then exactly " +"which environmental and command line configuration settings will be updated " +"is version dependent (as it depends on which settings correctly support " +"being modified after they have already been set once when the runtime was " +"first initialized)." +msgstr "" +"Em uso normal, uma aplicação de incorporação chamará esta função *em vez* de " +"chamar :c:func:`Py_Initialize`, :c:func:`Py_InitializeEx` ou :c:func:" +"`Py_InitializeFromConfig` diretamente, e todas as configurações serão " +"aplicadas conforme descrito em outra parte desta documentação. Se esta " +"função for chamada *após* uma chamada anterior à API de inicialização do " +"runtime, as configurações de ambiente e de linha de comando que serão " +"atualizadas dependem da versão (pois dependem de quais configurações " +"oferecem suporte corretamente à modificação após já terem sido definidas uma " +"vez na primeira inicialização do runtime)." + +#: ../../c-api/init.rst:528 +msgid "Executes the main module in a fully configured CPython runtime." +msgstr "" + +#: ../../c-api/init.rst:530 +msgid "" +"Executes the command (:c:member:`PyConfig.run_command`), the script (:c:" +"member:`PyConfig.run_filename`) or the module (:c:member:`PyConfig." +"run_module`) specified on the command line or in the configuration. If none " +"of these values are set, runs the interactive Python prompt (REPL) using the " +"``__main__`` module's global namespace." +msgstr "" + +#: ../../c-api/init.rst:536 +msgid "" +"If :c:member:`PyConfig.inspect` is not set (the default), the return value " +"will be ``0`` if the interpreter exits normally (that is, without raising an " +"exception), or ``1`` if the interpreter exits due to an exception. If an " +"otherwise unhandled :exc:`SystemExit` is raised, the function will " +"immediately exit the process instead of returning ``1``." +msgstr "" + +#: ../../c-api/init.rst:542 +msgid "" +"If :c:member:`PyConfig.inspect` is set (such as when the :option:`-i` option " +"is used), rather than returning when the interpreter exits, execution will " +"instead resume in an interactive Python prompt (REPL) using the ``__main__`` " +"module's global namespace. If the interpreter exited with an exception, it " +"is immediately raised in the REPL session. The function return value is then " +"determined by the way the *REPL session* terminates: returning ``0`` if the " +"session terminates without raising an unhandled exception, exiting " +"immediately for an unhandled :exc:`SystemExit`, and returning ``1`` for any " +"other unhandled exception." +msgstr "" + +#: ../../c-api/init.rst:552 +msgid "" +"This function always finalizes the Python interpreter regardless of whether " +"it returns a value or immediately exits the process due to an unhandled :exc:" +"`SystemExit` exception." +msgstr "" + +#: ../../c-api/init.rst:556 +msgid "" +"See :ref:`Python Configuration ` for an example of a " +"customized Python that always runs in isolated mode using :c:func:" +"`Py_RunMain`." +msgstr "" + +#: ../../c-api/init.rst:562 +msgid "" +"Register an :mod:`atexit` callback for the target interpreter *interp*. This " +"is similar to :c:func:`Py_AtExit`, but takes an explicit interpreter and " +"data pointer for the callback." +msgstr "" + +#: ../../c-api/init.rst:566 +msgid "The :term:`GIL` must be held for *interp*." +msgstr "" -#: ../../c-api/init.rst:440 +#: ../../c-api/init.rst:571 msgid "Process-wide parameters" msgstr "" -#: ../../c-api/init.rst:450 +#: ../../c-api/init.rst:581 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "program_name` should be used instead, see :ref:`Python Initialization " "Configuration `." msgstr "" -#: ../../c-api/init.rst:454 +#: ../../c-api/init.rst:585 msgid "" "This function should be called before :c:func:`Py_Initialize` is called for " "the first time, if it is called at all. It tells the interpreter the value " @@ -744,37 +1084,37 @@ msgstr "" "programa. Nenhum código no interpretador Python mudará o conteúdo deste " "armazenamento." -#: ../../c-api/init.rst:465 ../../c-api/init.rst:704 ../../c-api/init.rst:740 -#: ../../c-api/init.rst:766 +#: ../../c-api/init.rst:596 ../../c-api/init.rst:838 ../../c-api/init.rst:874 +#: ../../c-api/init.rst:900 msgid "" "Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a :c:expr:" -"`wchar_*` string." +"`wchar_t*` string." msgstr "" -#: ../../c-api/init.rst:473 +#: ../../c-api/init.rst:604 msgid "" "Return the program name set with :c:member:`PyConfig.program_name`, or the " "default. The returned string points into static storage; the caller should " "not modify its value." msgstr "" -#: ../../c-api/init.rst:477 ../../c-api/init.rst:499 ../../c-api/init.rst:543 -#: ../../c-api/init.rst:564 ../../c-api/init.rst:590 ../../c-api/init.rst:778 +#: ../../c-api/init.rst:608 ../../c-api/init.rst:630 ../../c-api/init.rst:676 +#: ../../c-api/init.rst:698 ../../c-api/init.rst:724 ../../c-api/init.rst:912 msgid "" "This function should not be called before :c:func:`Py_Initialize`, otherwise " "it returns ``NULL``." msgstr "" -#: ../../c-api/init.rst:480 ../../c-api/init.rst:502 ../../c-api/init.rst:546 -#: ../../c-api/init.rst:567 ../../c-api/init.rst:595 ../../c-api/init.rst:781 +#: ../../c-api/init.rst:611 ../../c-api/init.rst:633 ../../c-api/init.rst:679 +#: ../../c-api/init.rst:701 ../../c-api/init.rst:729 ../../c-api/init.rst:915 msgid "It now returns ``NULL`` if called before :c:func:`Py_Initialize`." msgstr "" -#: ../../c-api/init.rst:483 ../../c-api/init.rst:570 +#: ../../c-api/init.rst:614 ../../c-api/init.rst:704 msgid "Get :data:`sys.executable` instead." msgstr "" -#: ../../c-api/init.rst:489 +#: ../../c-api/init.rst:620 msgid "" "Return the *prefix* for installed platform-independent files. This is " "derived through a number of complicated rules from the program name set " @@ -784,15 +1124,17 @@ msgid "" "should not modify its value. This corresponds to the :makevar:`prefix` " "variable in the top-level :file:`Makefile` and the :option:`--prefix` " "argument to the :program:`configure` script at build time. The value is " -"available to Python code as ``sys.prefix``. It is only useful on Unix. See " -"also the next function." +"available to Python code as ``sys.base_prefix``. It is only useful on Unix. " +"See also the next function." msgstr "" -#: ../../c-api/init.rst:505 -msgid "Get :data:`sys.prefix` instead." +#: ../../c-api/init.rst:636 +msgid "" +"Get :data:`sys.base_prefix` instead, or :data:`sys.prefix` if :ref:`virtual " +"environments ` need to be handled." msgstr "" -#: ../../c-api/init.rst:511 +#: ../../c-api/init.rst:643 msgid "" "Return the *exec-prefix* for installed platform-*dependent* files. This is " "derived through a number of complicated rules from the program name set " @@ -802,11 +1144,11 @@ msgid "" "caller should not modify its value. This corresponds to the :makevar:" "`exec_prefix` variable in the top-level :file:`Makefile` and the ``--exec-" "prefix`` argument to the :program:`configure` script at build time. The " -"value is available to Python code as ``sys.exec_prefix``. It is only useful " -"on Unix." +"value is available to Python code as ``sys.base_exec_prefix``. It is only " +"useful on Unix." msgstr "" -#: ../../c-api/init.rst:521 +#: ../../c-api/init.rst:654 msgid "" "Background: The exec-prefix differs from the prefix when platform dependent " "files (such as executables and shared libraries) are installed in a " @@ -815,7 +1157,7 @@ msgid "" "independent may be installed in :file:`/usr/local`." msgstr "" -#: ../../c-api/init.rst:527 +#: ../../c-api/init.rst:660 msgid "" "Generally speaking, a platform is a combination of hardware and software " "families, e.g. Sparc machines running the Solaris 2.x operating system are " @@ -829,7 +1171,7 @@ msgid "" "independent from the Python version by which they were compiled!)." msgstr "" -#: ../../c-api/init.rst:538 +#: ../../c-api/init.rst:671 msgid "" "System administrators will know how to configure the :program:`mount` or :" "program:`automount` programs to share :file:`/usr/local` between platforms " @@ -837,11 +1179,13 @@ msgid "" "platform." msgstr "" -#: ../../c-api/init.rst:549 -msgid "Get :data:`sys.exec_prefix` instead." +#: ../../c-api/init.rst:682 +msgid "" +"Get :data:`sys.base_exec_prefix` instead, or :data:`sys.exec_prefix` if :ref:" +"`virtual environments ` need to be handled." msgstr "" -#: ../../c-api/init.rst:558 +#: ../../c-api/init.rst:692 msgid "" "Return the full program name of the Python executable; this is computed as " "a side-effect of deriving the default module search path from the program " @@ -850,7 +1194,7 @@ msgid "" "available to Python code as ``sys.executable``." msgstr "" -#: ../../c-api/init.rst:580 +#: ../../c-api/init.rst:714 msgid "" "Return the default module search path; this is computed from the program " "name (set by :c:member:`PyConfig.program_name`) and some environment " @@ -863,11 +1207,11 @@ msgid "" "for loading modules." msgstr "" -#: ../../c-api/init.rst:598 +#: ../../c-api/init.rst:732 msgid "Get :data:`sys.path` instead." msgstr "" -#: ../../c-api/init.rst:604 +#: ../../c-api/init.rst:738 msgid "" "Return the version of this Python interpreter. This is a string that looks " "something like ::" @@ -875,7 +1219,11 @@ msgstr "" "Retorna a verão deste interpretador Python. Esta é uma string que se parece " "com ::" -#: ../../c-api/init.rst:611 +#: ../../c-api/init.rst:741 +msgid "\"3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \\n[GCC 4.2.3]\"" +msgstr "" + +#: ../../c-api/init.rst:745 msgid "" "The first word (up to the first space character) is the current Python " "version; the first characters are the major and minor version separated by a " @@ -884,11 +1232,11 @@ msgid "" "version`." msgstr "" -#: ../../c-api/init.rst:616 +#: ../../c-api/init.rst:750 msgid "See also the :c:var:`Py_Version` constant." msgstr "" -#: ../../c-api/init.rst:623 +#: ../../c-api/init.rst:757 msgid "" "Return the platform identifier for the current platform. On Unix, this is " "formed from the \"official\" name of the operating system, converted to " @@ -899,7 +1247,7 @@ msgid "" "available to Python code as ``sys.platform``." msgstr "" -#: ../../c-api/init.rst:634 +#: ../../c-api/init.rst:768 msgid "" "Return the official copyright string for the current Python version, for " "example" @@ -907,17 +1255,17 @@ msgstr "" "Retorna a string oficial de direitos autoriais para a versão atual do " "Python, por exemplo" -#: ../../c-api/init.rst:636 +#: ../../c-api/init.rst:770 msgid "``'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'``" msgstr "" -#: ../../c-api/init.rst:640 +#: ../../c-api/init.rst:774 msgid "" "The returned string points into static storage; the caller should not modify " "its value. The value is available to Python code as ``sys.copyright``." msgstr "" -#: ../../c-api/init.rst:646 +#: ../../c-api/init.rst:780 msgid "" "Return an indication of the compiler used to build the current Python " "version, in square brackets, for example::" @@ -925,14 +1273,18 @@ msgstr "" "Retorna uma indicação do compilador usado para construir a atual versão do " "Python, em colchetes, por exemplo::" -#: ../../c-api/init.rst:653 ../../c-api/init.rst:667 +#: ../../c-api/init.rst:783 +msgid "\"[GCC 2.7.2.2]\"" +msgstr "" + +#: ../../c-api/init.rst:787 ../../c-api/init.rst:801 msgid "" "The returned string points into static storage; the caller should not modify " "its value. The value is available to Python code as part of the variable " "``sys.version``." msgstr "" -#: ../../c-api/init.rst:660 +#: ../../c-api/init.rst:794 msgid "" "Return information about the sequence number and build date and time of the " "current Python interpreter instance, for example ::" @@ -940,7 +1292,11 @@ msgstr "" "Retorna informação sobre o número de sequência e a data e hora da construção " "da instância atual do interpretador Python, por exemplo ::" -#: ../../c-api/init.rst:679 +#: ../../c-api/init.rst:797 +msgid "\"#67, Aug 1 1997, 22:34:28\"" +msgstr "" + +#: ../../c-api/init.rst:813 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "argv`, :c:member:`PyConfig.parse_argv` and :c:member:`PyConfig.safe_path` " @@ -948,7 +1304,7 @@ msgid "" "config>`." msgstr "" -#: ../../c-api/init.rst:684 +#: ../../c-api/init.rst:818 msgid "" "Set :data:`sys.argv` based on *argc* and *argv*. These parameters are " "similar to those passed to the program's :c:func:`main` function with the " @@ -959,7 +1315,7 @@ msgid "" "fatal condition is signalled using :c:func:`Py_FatalError`." msgstr "" -#: ../../c-api/init.rst:692 +#: ../../c-api/init.rst:826 msgid "" "If *updatepath* is zero, this is all the function does. If *updatepath* is " "non-zero, the function also modifies :data:`sys.path` according to the " @@ -969,73 +1325,77 @@ msgstr "" "é zero, a função também modifica :data:`sys.path` de acordo com o seguinte " "algoritmo:" -#: ../../c-api/init.rst:696 +#: ../../c-api/init.rst:830 msgid "" "If the name of an existing script is passed in ``argv[0]``, the absolute " "path of the directory where the script is located is prepended to :data:`sys." "path`." msgstr "" -#: ../../c-api/init.rst:699 +#: ../../c-api/init.rst:833 msgid "" "Otherwise (that is, if *argc* is ``0`` or ``argv[0]`` doesn't point to an " "existing file name), an empty string is prepended to :data:`sys.path`, which " "is the same as prepending the current working directory (``\".\"``)." msgstr "" -#: ../../c-api/init.rst:707 ../../c-api/init.rst:743 +#: ../../c-api/init.rst:841 ../../c-api/init.rst:877 msgid "" "See also :c:member:`PyConfig.orig_argv` and :c:member:`PyConfig.argv` " "members of the :ref:`Python Initialization Configuration `." msgstr "" -#: ../../c-api/init.rst:711 +#: ../../c-api/init.rst:845 msgid "" "It is recommended that applications embedding the Python interpreter for " "purposes other than executing a single script pass ``0`` as *updatepath*, " "and update :data:`sys.path` themselves if desired. See :cve:`2008-5983`." msgstr "" -#: ../../c-api/init.rst:716 +#: ../../c-api/init.rst:850 msgid "" "On versions before 3.1.3, you can achieve the same effect by manually " "popping the first :data:`sys.path` element after having called :c:func:" "`PySys_SetArgv`, for example using::" msgstr "" -#: ../../c-api/init.rst:732 +#: ../../c-api/init.rst:854 +msgid "PyRun_SimpleString(\"import sys; sys.path.pop(0)\\n\");" +msgstr "" + +#: ../../c-api/init.rst:866 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "argv` and :c:member:`PyConfig.parse_argv` should be used instead, see :ref:" "`Python Initialization Configuration `." msgstr "" -#: ../../c-api/init.rst:736 +#: ../../c-api/init.rst:870 msgid "" "This function works like :c:func:`PySys_SetArgvEx` with *updatepath* set to " "``1`` unless the :program:`python` interpreter was started with the :option:" "`-I`." msgstr "" -#: ../../c-api/init.rst:746 +#: ../../c-api/init.rst:880 msgid "The *updatepath* value depends on :option:`-I`." msgstr "" -#: ../../c-api/init.rst:753 +#: ../../c-api/init.rst:887 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." "home` should be used instead, see :ref:`Python Initialization Configuration " "`." msgstr "" -#: ../../c-api/init.rst:757 +#: ../../c-api/init.rst:891 msgid "" "Set the default \"home\" directory, that is, the location of the standard " "Python libraries. See :envvar:`PYTHONHOME` for the meaning of the argument " "string." msgstr "" -#: ../../c-api/init.rst:761 +#: ../../c-api/init.rst:895 msgid "" "The argument should point to a zero-terminated character string in static " "storage whose contents will not change for the duration of the program's " @@ -1043,24 +1403,24 @@ msgid "" "this storage." msgstr "" -#: ../../c-api/init.rst:774 +#: ../../c-api/init.rst:908 msgid "" "Return the default \"home\", that is, the value set by :c:member:`PyConfig." "home`, or the value of the :envvar:`PYTHONHOME` environment variable if it " "is set." msgstr "" -#: ../../c-api/init.rst:784 +#: ../../c-api/init.rst:918 msgid "" "Get :c:member:`PyConfig.home` or :envvar:`PYTHONHOME` environment variable " "instead." msgstr "" -#: ../../c-api/init.rst:792 +#: ../../c-api/init.rst:926 msgid "Thread State and the Global Interpreter Lock" -msgstr "" +msgstr "Estado de thread e trava global do interpretador" -#: ../../c-api/init.rst:799 +#: ../../c-api/init.rst:933 msgid "" "The Python interpreter is not fully thread-safe. In order to support multi-" "threaded Python programs, there's a global lock, called the :term:`global " @@ -1072,7 +1432,7 @@ msgid "" "once instead of twice." msgstr "" -#: ../../c-api/init.rst:809 +#: ../../c-api/init.rst:943 msgid "" "Therefore, the rule exists that only the thread that has acquired the :term:" "`GIL` may operate on Python objects or call Python/C API functions. In order " @@ -1081,8 +1441,15 @@ msgid "" "released around potentially blocking I/O operations like reading or writing " "a file, so that other Python threads can run in the meantime." msgstr "" +"Portanto, existe a regra de que somente a thread que adquiriu a :term:`GIL` " +"pode operar em objetos Python ou chamar funções da API C/Python. Para emular " +"a simultaneidade de execução, o interpretador tenta alternar threads " +"regularmente (consulte :func:`sys.setswitchinterval`). A trava também é " +"liberada em operações de E/S potencialmente bloqueantes, como ler ou " +"escrever um arquivo, para que outras threads Python possam ser executadas " +"enquanto isso." -#: ../../c-api/init.rst:819 +#: ../../c-api/init.rst:953 msgid "" "The Python interpreter keeps some thread-specific bookkeeping information " "inside a data structure called :c:type:`PyThreadState`. There's also one " @@ -1090,11 +1457,11 @@ msgid "" "retrieved using :c:func:`PyThreadState_Get`." msgstr "" -#: ../../c-api/init.rst:825 +#: ../../c-api/init.rst:959 msgid "Releasing the GIL from extension code" msgstr "" -#: ../../c-api/init.rst:827 +#: ../../c-api/init.rst:961 msgid "" "Most extension code manipulating the :term:`GIL` has the following simple " "structure::" @@ -1102,11 +1469,27 @@ msgstr "" "A maioria dos códigos de extensão que manipulam a :term:`GIL` tem a seguinte " "estrutura::" -#: ../../c-api/init.rst:836 +#: ../../c-api/init.rst:964 +msgid "" +"Save the thread state in a local variable.\n" +"Release the global interpreter lock.\n" +"... Do some blocking I/O operation ...\n" +"Reacquire the global interpreter lock.\n" +"Restore the thread state from the local variable." +msgstr "" + +#: ../../c-api/init.rst:970 msgid "This is so common that a pair of macros exists to simplify it::" msgstr "" -#: ../../c-api/init.rst:846 +#: ../../c-api/init.rst:972 +msgid "" +"Py_BEGIN_ALLOW_THREADS\n" +"... Do some blocking I/O operation ...\n" +"Py_END_ALLOW_THREADS" +msgstr "" + +#: ../../c-api/init.rst:980 msgid "" "The :c:macro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a " "hidden local variable; the :c:macro:`Py_END_ALLOW_THREADS` macro closes the " @@ -1115,11 +1498,20 @@ msgstr "" "A macro :c:macro:`Py_BEGIN_ALLOW_THREADS` abre um novo bloco e declara uma " "variável local oculta; a macro :c:macro:`Py_END_ALLOW_THREADS` fecha o bloco." -#: ../../c-api/init.rst:850 +#: ../../c-api/init.rst:984 msgid "The block above expands to the following code::" msgstr "" -#: ../../c-api/init.rst:862 +#: ../../c-api/init.rst:986 +msgid "" +"PyThreadState *_save;\n" +"\n" +"_save = PyEval_SaveThread();\n" +"... Do some blocking I/O operation ...\n" +"PyEval_RestoreThread(_save);" +msgstr "" + +#: ../../c-api/init.rst:996 msgid "" "Here is how these functions work: the global interpreter lock is used to " "protect the pointer to the current thread state. When releasing the lock " @@ -1130,7 +1522,7 @@ msgid "" "state, the lock must be acquired before storing the thread state pointer." msgstr "" -#: ../../c-api/init.rst:871 +#: ../../c-api/init.rst:1005 msgid "" "Calling system I/O functions is the most common use case for releasing the " "GIL, but it can also be useful before calling long-running computations " @@ -1140,11 +1532,11 @@ msgid "" "compressing or hashing data." msgstr "" -#: ../../c-api/init.rst:882 +#: ../../c-api/init.rst:1016 msgid "Non-Python created threads" msgstr "" -#: ../../c-api/init.rst:884 +#: ../../c-api/init.rst:1018 msgid "" "When threads are created using the dedicated Python APIs (such as the :mod:" "`threading` module), a thread state is automatically associated to them and " @@ -1154,7 +1546,7 @@ msgid "" "for them." msgstr "" -#: ../../c-api/init.rst:891 +#: ../../c-api/init.rst:1025 msgid "" "If you need to call Python code from these threads (often this will be part " "of a callback API provided by the aforementioned third-party library), you " @@ -1165,14 +1557,27 @@ msgid "" "finally free the thread state data structure." msgstr "" -#: ../../c-api/init.rst:899 +#: ../../c-api/init.rst:1033 msgid "" "The :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` functions " "do all of the above automatically. The typical idiom for calling into " "Python from a C thread is::" msgstr "" -#: ../../c-api/init.rst:913 +#: ../../c-api/init.rst:1037 +msgid "" +"PyGILState_STATE gstate;\n" +"gstate = PyGILState_Ensure();\n" +"\n" +"/* Perform Python actions here. */\n" +"result = CallSomeFunction();\n" +"/* evaluate result or handle exception */\n" +"\n" +"/* Release the thread. No Python API allowed beyond this point. */\n" +"PyGILState_Release(gstate);" +msgstr "" + +#: ../../c-api/init.rst:1047 msgid "" "Note that the ``PyGILState_*`` functions assume there is only one global " "interpreter (created automatically by :c:func:`Py_Initialize`). Python " @@ -1181,11 +1586,11 @@ msgid "" "``PyGILState_*`` API is unsupported." msgstr "" -#: ../../c-api/init.rst:923 +#: ../../c-api/init.rst:1057 msgid "Cautions about fork()" msgstr "Cuidados com o uso de fork()" -#: ../../c-api/init.rst:925 +#: ../../c-api/init.rst:1059 msgid "" "Another important thing to note about threads is their behaviour in the face " "of the C :c:func:`fork` call. On most systems with :c:func:`fork`, after a " @@ -1194,7 +1599,7 @@ msgid "" "CPython's runtime." msgstr "" -#: ../../c-api/init.rst:931 +#: ../../c-api/init.rst:1065 msgid "" "The fact that only the \"current\" thread remains means any locks held by " "other threads will never be released. Python solves this for :func:`os.fork` " @@ -1211,7 +1616,7 @@ msgid "" "locks, but is not always able to." msgstr "" -#: ../../c-api/init.rst:946 +#: ../../c-api/init.rst:1080 msgid "" "The fact that all other threads go away also means that CPython's runtime " "state there must be cleaned up properly, which :func:`os.fork` does. This " @@ -1224,11 +1629,11 @@ msgid "" "called immediately after." msgstr "" -#: ../../c-api/init.rst:959 +#: ../../c-api/init.rst:1093 msgid "High-level API" msgstr "" -#: ../../c-api/init.rst:961 +#: ../../c-api/init.rst:1095 msgid "" "These are the most commonly used types and functions when writing C " "extension code, or when embedding the Python interpreter:" @@ -1236,7 +1641,7 @@ msgstr "" "Estes são os tipos e as funções mais comumente usados na escrita de um " "código de extensão em C, ou ao incorporar o interpretador Python:" -#: ../../c-api/init.rst:966 +#: ../../c-api/init.rst:1100 msgid "" "This data structure represents the state shared by a number of cooperating " "threads. Threads belonging to the same interpreter share their module " @@ -1244,7 +1649,7 @@ msgid "" "in this structure." msgstr "" -#: ../../c-api/init.rst:971 +#: ../../c-api/init.rst:1105 msgid "" "Threads belonging to different interpreters initially share nothing, except " "process state like available memory, open file descriptors and such. The " @@ -1252,30 +1657,30 @@ msgid "" "which interpreter they belong." msgstr "" -#: ../../c-api/init.rst:979 +#: ../../c-api/init.rst:1113 msgid "" "This data structure represents the state of a single thread. The only " "public data member is:" msgstr "" -#: ../../c-api/init.rst:984 +#: ../../c-api/init.rst:1118 msgid "This thread's interpreter state." msgstr "" -#: ../../c-api/init.rst:995 +#: ../../c-api/init.rst:1129 msgid "Deprecated function which does nothing." msgstr "Função descontinuada que não faz nada." -#: ../../c-api/init.rst:997 +#: ../../c-api/init.rst:1131 msgid "" "In Python 3.6 and older, this function created the GIL if it didn't exist." msgstr "" -#: ../../c-api/init.rst:999 +#: ../../c-api/init.rst:1133 msgid "The function now does nothing." msgstr "" -#: ../../c-api/init.rst:1002 +#: ../../c-api/init.rst:1136 msgid "" "This function is now called by :c:func:`Py_Initialize()`, so you don't have " "to call it yourself anymore." @@ -1283,13 +1688,13 @@ msgstr "" "Esta função agora é chamada por :c:func:`Py_Initialize()`, então não há mais " "necessidade de você chamá-la." -#: ../../c-api/init.rst:1006 +#: ../../c-api/init.rst:1140 msgid "" "This function cannot be called before :c:func:`Py_Initialize()` anymore." msgstr "" "Esta função não pode mais ser chamada antes de :c:func:`Py_Initialize()`." -#: ../../c-api/init.rst:1016 +#: ../../c-api/init.rst:1150 msgid "" "Release the global interpreter lock (if it has been created) and reset the " "thread state to ``NULL``, returning the previous thread state (which is not " @@ -1297,7 +1702,7 @@ msgid "" "acquired it." msgstr "" -#: ../../c-api/init.rst:1024 +#: ../../c-api/init.rst:1158 msgid "" "Acquire the global interpreter lock (if it has been created) and set the " "thread state to *tstate*, which must not be ``NULL``. If the lock has been " @@ -1305,8 +1710,8 @@ msgid "" "ensues." msgstr "" -#: ../../c-api/init.rst:1030 ../../c-api/init.rst:1089 -#: ../../c-api/init.rst:1371 +#: ../../c-api/init.rst:1164 ../../c-api/init.rst:1224 +#: ../../c-api/init.rst:1520 msgid "" "Calling this function from a thread when the runtime is finalizing will " "terminate the thread, even if the thread was not created by Python. You can " @@ -1315,44 +1720,49 @@ msgid "" "avoid unwanted termination." msgstr "" -#: ../../c-api/init.rst:1038 +#: ../../c-api/init.rst:1172 msgid "" "Return the current thread state. The global interpreter lock must be held. " "When the current thread state is ``NULL``, this issues a fatal error (so " "that the caller needn't check for ``NULL``)." msgstr "" -#: ../../c-api/init.rst:1042 +#: ../../c-api/init.rst:1176 msgid "See also :c:func:`PyThreadState_GetUnchecked`." msgstr "" -#: ../../c-api/init.rst:1047 +#: ../../c-api/init.rst:1181 msgid "" "Similar to :c:func:`PyThreadState_Get`, but don't kill the process with a " "fatal error if it is NULL. The caller is responsible to check if the result " "is NULL." msgstr "" -#: ../../c-api/init.rst:1051 +#: ../../c-api/init.rst:1185 msgid "" "In Python 3.5 to 3.12, the function was private and known as " "``_PyThreadState_UncheckedGet()``." msgstr "" -#: ../../c-api/init.rst:1058 +#: ../../c-api/init.rst:1192 msgid "" "Swap the current thread state with the thread state given by the argument " -"*tstate*, which may be ``NULL``. The global interpreter lock must be held " -"and is not released." +"*tstate*, which may be ``NULL``." +msgstr "" + +#: ../../c-api/init.rst:1195 +msgid "" +"The :term:`GIL` does not need to be held, but will be held upon returning if " +"*tstate* is non-``NULL``." msgstr "" -#: ../../c-api/init.rst:1063 +#: ../../c-api/init.rst:1198 msgid "" "The following functions use thread-local storage, and are not compatible " "with sub-interpreters:" msgstr "" -#: ../../c-api/init.rst:1068 +#: ../../c-api/init.rst:1203 msgid "" "Ensure that the current thread is ready to call the Python C API regardless " "of the current state of Python, or of the global interpreter lock. This may " @@ -1374,7 +1784,7 @@ msgstr "" "estado anterior antes de Release(). Por exemplo, o uso normal das macros :c:" "macro:`Py_BEGIN_ALLOW_THREADS` e :c:macro:`Py_END_ALLOW_THREADS` é aceitável." -#: ../../c-api/init.rst:1078 +#: ../../c-api/init.rst:1213 msgid "" "The return value is an opaque \"handle\" to the thread state when :c:func:" "`PyGILState_Ensure` was called, and must be passed to :c:func:" @@ -1384,13 +1794,13 @@ msgid "" "func:`PyGILState_Release`." msgstr "" -#: ../../c-api/init.rst:1085 +#: ../../c-api/init.rst:1220 msgid "" "When the function returns, the current thread will hold the GIL and be able " "to call arbitrary Python code. Failure is a fatal error." msgstr "" -#: ../../c-api/init.rst:1097 +#: ../../c-api/init.rst:1232 msgid "" "Release any resources previously acquired. After this call, Python's state " "will be the same as it was prior to the corresponding :c:func:" @@ -1398,13 +1808,13 @@ msgid "" "caller, hence the use of the GILState API)." msgstr "" -#: ../../c-api/init.rst:1102 +#: ../../c-api/init.rst:1237 msgid "" "Every call to :c:func:`PyGILState_Ensure` must be matched by a call to :c:" "func:`PyGILState_Release` on the same thread." msgstr "" -#: ../../c-api/init.rst:1108 +#: ../../c-api/init.rst:1243 msgid "" "Get the current thread state for this thread. May return ``NULL`` if no " "GILState API has been used on the current thread. Note that the main thread " @@ -1412,7 +1822,7 @@ msgid "" "made on the main thread. This is mainly a helper/diagnostic function." msgstr "" -#: ../../c-api/init.rst:1116 +#: ../../c-api/init.rst:1251 msgid "" "Return ``1`` if the current thread is holding the GIL and ``0`` otherwise. " "This function can be called from any thread at any time. Only if it has had " @@ -1423,13 +1833,13 @@ msgid "" "otherwise behave differently." msgstr "" -#: ../../c-api/init.rst:1128 +#: ../../c-api/init.rst:1263 msgid "" "The following macros are normally used without a trailing semicolon; look " "for example usage in the Python source distribution." msgstr "" -#: ../../c-api/init.rst:1134 +#: ../../c-api/init.rst:1269 msgid "" "This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();" "``. Note that it contains an opening brace; it must be matched with a " @@ -1441,7 +1851,7 @@ msgstr "" "deve ser combinado com a seguinte macro :c:macro:`Py_END_ALLOW_THREADS`. " "Veja acima para uma discussão mais aprofundada desta macro." -#: ../../c-api/init.rst:1142 +#: ../../c-api/init.rst:1277 msgid "" "This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it " "contains a closing brace; it must be matched with an earlier :c:macro:" @@ -1453,7 +1863,7 @@ msgstr "" "macro:`Py_BEGIN_ALLOW_THREADS` anterior. Veja acima para uma discussão mais " "aprofundada desta macro." -#: ../../c-api/init.rst:1150 +#: ../../c-api/init.rst:1285 msgid "" "This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to :" "c:macro:`Py_END_ALLOW_THREADS` without the closing brace." @@ -1461,7 +1871,7 @@ msgstr "" "Esta macro se expande para ``PyEval_RestoreThread(_save);``: é equivalente " "a :c:macro:`Py_END_ALLOW_THREADS` sem a chave de fechamento." -#: ../../c-api/init.rst:1156 +#: ../../c-api/init.rst:1291 msgid "" "This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to :" "c:macro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable " @@ -1471,27 +1881,27 @@ msgstr "" "a :c:macro:`Py_BEGIN_ALLOW_THREADS` sem a chave de abertura e declaração de " "variável." -#: ../../c-api/init.rst:1162 +#: ../../c-api/init.rst:1297 msgid "Low-level API" msgstr "" -#: ../../c-api/init.rst:1164 +#: ../../c-api/init.rst:1299 msgid "" "All of the following functions must be called after :c:func:`Py_Initialize`." msgstr "" -#: ../../c-api/init.rst:1166 +#: ../../c-api/init.rst:1301 msgid ":c:func:`Py_Initialize()` now initializes the :term:`GIL`." msgstr "" -#: ../../c-api/init.rst:1172 +#: ../../c-api/init.rst:1307 msgid "" "Create a new interpreter state object. The global interpreter lock need not " "be held, but may be held if it is necessary to serialize calls to this " "function." msgstr "" -#: ../../c-api/init.rst:1176 +#: ../../c-api/init.rst:1311 msgid "" "Raises an :ref:`auditing event ` ``cpython." "PyInterpreterState_New`` with no arguments." @@ -1499,13 +1909,13 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``cpython." "PyInterpreterState_New`` sem argumentos." -#: ../../c-api/init.rst:1181 +#: ../../c-api/init.rst:1316 msgid "" "Reset all information in an interpreter state object. The global " "interpreter lock must be held." msgstr "" -#: ../../c-api/init.rst:1184 +#: ../../c-api/init.rst:1319 msgid "" "Raises an :ref:`auditing event ` ``cpython." "PyInterpreterState_Clear`` with no arguments." @@ -1513,160 +1923,171 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``cpython." "PyInterpreterState_Clear`` sem argumentos." -#: ../../c-api/init.rst:1189 +#: ../../c-api/init.rst:1324 msgid "" "Destroy an interpreter state object. The global interpreter lock need not " "be held. The interpreter state must have been reset with a previous call " "to :c:func:`PyInterpreterState_Clear`." msgstr "" -#: ../../c-api/init.rst:1196 +#: ../../c-api/init.rst:1331 msgid "" "Create a new thread state object belonging to the given interpreter object. " "The global interpreter lock need not be held, but may be held if it is " "necessary to serialize calls to this function." msgstr "" -#: ../../c-api/init.rst:1203 +#: ../../c-api/init.rst:1338 msgid "" "Reset all information in a thread state object. The global interpreter lock " "must be held." msgstr "" -#: ../../c-api/init.rst:1206 +#: ../../c-api/init.rst:1341 msgid "" "This function now calls the :c:member:`PyThreadState.on_delete` callback. " "Previously, that happened in :c:func:`PyThreadState_Delete`." msgstr "" -#: ../../c-api/init.rst:1213 +#: ../../c-api/init.rst:1345 +msgid "The :c:member:`PyThreadState.on_delete` callback was removed." +msgstr "" + +#: ../../c-api/init.rst:1351 msgid "" "Destroy a thread state object. The global interpreter lock need not be " "held. The thread state must have been reset with a previous call to :c:func:" "`PyThreadState_Clear`." msgstr "" -#: ../../c-api/init.rst:1220 +#: ../../c-api/init.rst:1358 msgid "" "Destroy the current thread state and release the global interpreter lock. " -"Like :c:func:`PyThreadState_Delete`, the global interpreter lock need not be " +"Like :c:func:`PyThreadState_Delete`, the global interpreter lock must be " "held. The thread state must have been reset with a previous call to :c:func:" "`PyThreadState_Clear`." msgstr "" -#: ../../c-api/init.rst:1228 +#: ../../c-api/init.rst:1366 msgid "Get the current frame of the Python thread state *tstate*." msgstr "" -#: ../../c-api/init.rst:1230 +#: ../../c-api/init.rst:1368 msgid "" "Return a :term:`strong reference`. Return ``NULL`` if no frame is currently " "executing." msgstr "" -#: ../../c-api/init.rst:1233 +#: ../../c-api/init.rst:1371 msgid "See also :c:func:`PyEval_GetFrame`." msgstr "" -#: ../../c-api/init.rst:1235 ../../c-api/init.rst:1244 -#: ../../c-api/init.rst:1253 +#: ../../c-api/init.rst:1373 ../../c-api/init.rst:1382 +#: ../../c-api/init.rst:1391 msgid "*tstate* must not be ``NULL``." msgstr "" -#: ../../c-api/init.rst:1242 +#: ../../c-api/init.rst:1380 msgid "" "Get the unique thread state identifier of the Python thread state *tstate*." msgstr "" -#: ../../c-api/init.rst:1251 +#: ../../c-api/init.rst:1389 msgid "Get the interpreter of the Python thread state *tstate*." msgstr "" -#: ../../c-api/init.rst:1260 +#: ../../c-api/init.rst:1398 msgid "Suspend tracing and profiling in the Python thread state *tstate*." msgstr "" -#: ../../c-api/init.rst:1262 +#: ../../c-api/init.rst:1400 msgid "Resume them using the :c:func:`PyThreadState_LeaveTracing` function." msgstr "" -#: ../../c-api/init.rst:1269 +#: ../../c-api/init.rst:1407 msgid "" "Resume tracing and profiling in the Python thread state *tstate* suspended " "by the :c:func:`PyThreadState_EnterTracing` function." msgstr "" -#: ../../c-api/init.rst:1272 +#: ../../c-api/init.rst:1410 msgid "" "See also :c:func:`PyEval_SetTrace` and :c:func:`PyEval_SetProfile` functions." msgstr "" -#: ../../c-api/init.rst:1280 +#: ../../c-api/init.rst:1418 msgid "Get the current interpreter." msgstr "" -#: ../../c-api/init.rst:1282 +#: ../../c-api/init.rst:1420 msgid "" "Issue a fatal error if there no current Python thread state or no current " "interpreter. It cannot return NULL." msgstr "" -#: ../../c-api/init.rst:1285 ../../c-api/init.rst:1295 +#: ../../c-api/init.rst:1423 ../../c-api/init.rst:1433 +#: ../../c-api/init.rst:1455 msgid "The caller must hold the GIL." msgstr "" -#: ../../c-api/init.rst:1292 +#: ../../c-api/init.rst:1430 msgid "" "Return the interpreter's unique ID. If there was any error in doing so then " "``-1`` is returned and an error is set." msgstr "" -#: ../../c-api/init.rst:1302 +#: ../../c-api/init.rst:1440 msgid "" "Return a dictionary in which interpreter-specific data may be stored. If " "this function returns ``NULL`` then no exception has been raised and the " "caller should assume no interpreter-specific dict is available." msgstr "" -#: ../../c-api/init.rst:1306 +#: ../../c-api/init.rst:1444 msgid "" "This is not a replacement for :c:func:`PyModule_GetState()`, which " "extensions should use to store interpreter-specific state information." msgstr "" -#: ../../c-api/init.rst:1313 +#: ../../c-api/init.rst:1452 +msgid "" +"Return a :term:`strong reference` to the ``__main__`` :ref:`module object " +"` for the given interpreter." +msgstr "" + +#: ../../c-api/init.rst:1462 msgid "Type of a frame evaluation function." msgstr "" -#: ../../c-api/init.rst:1315 +#: ../../c-api/init.rst:1464 msgid "" "The *throwflag* parameter is used by the ``throw()`` method of generators: " "if non-zero, handle the current exception." msgstr "" -#: ../../c-api/init.rst:1318 +#: ../../c-api/init.rst:1467 msgid "The function now takes a *tstate* parameter." msgstr "" -#: ../../c-api/init.rst:1321 +#: ../../c-api/init.rst:1470 msgid "" "The *frame* parameter changed from ``PyFrameObject*`` to " "``_PyInterpreterFrame*``." msgstr "" -#: ../../c-api/init.rst:1326 +#: ../../c-api/init.rst:1475 msgid "Get the frame evaluation function." msgstr "" -#: ../../c-api/init.rst:1328 ../../c-api/init.rst:1336 +#: ../../c-api/init.rst:1477 ../../c-api/init.rst:1485 msgid "See the :pep:`523` \"Adding a frame evaluation API to CPython\"." msgstr "" -#: ../../c-api/init.rst:1334 +#: ../../c-api/init.rst:1483 msgid "Set the frame evaluation function." msgstr "" -#: ../../c-api/init.rst:1343 +#: ../../c-api/init.rst:1492 msgid "" "Return a dictionary in which extensions can store thread-specific state " "information. Each extension should use a unique key to use to store state " @@ -1675,7 +2096,7 @@ msgid "" "raised and the caller should assume no current thread state is available." msgstr "" -#: ../../c-api/init.rst:1352 +#: ../../c-api/init.rst:1501 msgid "" "Asynchronously raise an exception in a thread. The *id* argument is the " "thread id of the target thread; *exc* is the exception object to be raised. " @@ -1687,33 +2108,33 @@ msgid "" "raises no exceptions." msgstr "" -#: ../../c-api/init.rst:1360 +#: ../../c-api/init.rst:1509 msgid "" "The type of the *id* parameter changed from :c:expr:`long` to :c:expr:" "`unsigned long`." msgstr "" -#: ../../c-api/init.rst:1366 +#: ../../c-api/init.rst:1515 msgid "" "Acquire the global interpreter lock and set the current thread state to " "*tstate*, which must not be ``NULL``. The lock must have been created " "earlier. If this thread already has the lock, deadlock ensues." msgstr "" -#: ../../c-api/init.rst:1377 +#: ../../c-api/init.rst:1526 msgid "" "Updated to be consistent with :c:func:`PyEval_RestoreThread`, :c:func:" "`Py_END_ALLOW_THREADS`, and :c:func:`PyGILState_Ensure`, and terminate the " "current thread if called while the interpreter is finalizing." msgstr "" -#: ../../c-api/init.rst:1382 +#: ../../c-api/init.rst:1531 msgid "" ":c:func:`PyEval_RestoreThread` is a higher-level function which is always " "available (even when threads have not been initialized)." msgstr "" -#: ../../c-api/init.rst:1388 +#: ../../c-api/init.rst:1537 msgid "" "Reset the current thread state to ``NULL`` and release the global " "interpreter lock. The lock must have been created earlier and must be held " @@ -1722,17 +2143,17 @@ msgid "" "isn't, a fatal error is reported." msgstr "" -#: ../../c-api/init.rst:1394 +#: ../../c-api/init.rst:1543 msgid "" ":c:func:`PyEval_SaveThread` is a higher-level function which is always " "available (even when threads have not been initialized)." msgstr "" -#: ../../c-api/init.rst:1401 +#: ../../c-api/init.rst:1550 msgid "Sub-interpreter support" msgstr "" -#: ../../c-api/init.rst:1403 +#: ../../c-api/init.rst:1552 msgid "" "While in most uses, you will only embed a single Python interpreter, there " "are cases where you need to create several independent interpreters in the " @@ -1740,7 +2161,7 @@ msgid "" "to do that." msgstr "" -#: ../../c-api/init.rst:1408 +#: ../../c-api/init.rst:1557 msgid "" "The \"main\" interpreter is the first one created when the runtime " "initializes. It is usually the only Python interpreter in a process. Unlike " @@ -1751,31 +2172,31 @@ msgid "" "returns a pointer to its state." msgstr "" -#: ../../c-api/init.rst:1415 +#: ../../c-api/init.rst:1564 msgid "" "You can switch between sub-interpreters using the :c:func:" "`PyThreadState_Swap` function. You can create and destroy them using the " "following functions:" msgstr "" -#: ../../c-api/init.rst:1421 +#: ../../c-api/init.rst:1570 msgid "" "Structure containing most parameters to configure a sub-interpreter. Its " "values are used only in :c:func:`Py_NewInterpreterFromConfig` and never " "modified by the runtime." msgstr "" -#: ../../c-api/init.rst:1427 +#: ../../c-api/init.rst:1576 msgid "Structure fields:" msgstr "Campos de estrutura:" -#: ../../c-api/init.rst:1431 +#: ../../c-api/init.rst:1580 msgid "" "If this is ``0`` then the sub-interpreter will use its own \"object\" " "allocator state. Otherwise it will use (share) the main interpreter's." msgstr "" -#: ../../c-api/init.rst:1435 +#: ../../c-api/init.rst:1584 msgid "" "If this is ``0`` then :c:member:`~PyInterpreterConfig." "check_multi_interp_extensions` must be ``1`` (non-zero). If this is ``1`` " @@ -1783,44 +2204,44 @@ msgid "" "`PyInterpreterConfig_OWN_GIL`." msgstr "" -#: ../../c-api/init.rst:1443 +#: ../../c-api/init.rst:1592 msgid "" "If this is ``0`` then the runtime will not support forking the process in " "any thread where the sub-interpreter is currently active. Otherwise fork is " "unrestricted." msgstr "" -#: ../../c-api/init.rst:1447 +#: ../../c-api/init.rst:1596 msgid "" "Note that the :mod:`subprocess` module still works when fork is disallowed." msgstr "" -#: ../../c-api/init.rst:1452 +#: ../../c-api/init.rst:1601 msgid "" "If this is ``0`` then the runtime will not support replacing the current " "process via exec (e.g. :func:`os.execv`) in any thread where the sub-" "interpreter is currently active. Otherwise exec is unrestricted." msgstr "" -#: ../../c-api/init.rst:1457 +#: ../../c-api/init.rst:1606 msgid "" "Note that the :mod:`subprocess` module still works when exec is disallowed." msgstr "" -#: ../../c-api/init.rst:1462 +#: ../../c-api/init.rst:1611 msgid "" "If this is ``0`` then the sub-interpreter's :mod:`threading` module won't " "create threads. Otherwise threads are allowed." msgstr "" -#: ../../c-api/init.rst:1468 +#: ../../c-api/init.rst:1617 msgid "" "If this is ``0`` then the sub-interpreter's :mod:`threading` module won't " "create daemon threads. Otherwise daemon threads are allowed (as long as :c:" "member:`~PyInterpreterConfig.allow_threads` is non-zero)." msgstr "" -#: ../../c-api/init.rst:1475 +#: ../../c-api/init.rst:1624 msgid "" "If this is ``0`` then all extension modules may be imported, including " "legacy (single-phase init) modules, in any thread where the sub-interpreter " @@ -1829,37 +2250,37 @@ msgid "" "`Py_mod_multiple_interpreters`.)" msgstr "" -#: ../../c-api/init.rst:1482 +#: ../../c-api/init.rst:1631 msgid "" "This must be ``1`` (non-zero) if :c:member:`~PyInterpreterConfig." "use_main_obmalloc` is ``0``." msgstr "" -#: ../../c-api/init.rst:1487 +#: ../../c-api/init.rst:1636 msgid "" "This determines the operation of the GIL for the sub-interpreter. It may be " "one of the following:" msgstr "" -#: ../../c-api/init.rst:1494 +#: ../../c-api/init.rst:1643 msgid "Use the default selection (:c:macro:`PyInterpreterConfig_SHARED_GIL`)." msgstr "" -#: ../../c-api/init.rst:1498 +#: ../../c-api/init.rst:1647 msgid "Use (share) the main interpreter's GIL." msgstr "" -#: ../../c-api/init.rst:1502 +#: ../../c-api/init.rst:1651 msgid "Use the sub-interpreter's own GIL." msgstr "" -#: ../../c-api/init.rst:1504 +#: ../../c-api/init.rst:1653 msgid "" "If this is :c:macro:`PyInterpreterConfig_OWN_GIL` then :c:member:" "`PyInterpreterConfig.use_main_obmalloc` must be ``0``." msgstr "" -#: ../../c-api/init.rst:1518 +#: ../../c-api/init.rst:1667 msgid "" "Create a new sub-interpreter. This is an (almost) totally separate " "environment for the execution of Python code. In particular, the new " @@ -1872,13 +2293,13 @@ msgid "" "underlying file descriptors)." msgstr "" -#: ../../c-api/init.rst:1528 +#: ../../c-api/init.rst:1677 msgid "" "The given *config* controls the options with which the interpreter is " "initialized." msgstr "" -#: ../../c-api/init.rst:1531 +#: ../../c-api/init.rst:1680 msgid "" "Upon success, *tstate_p* will be set to the first thread state created in " "the new sub-interpreter. This thread state is made in the current thread " @@ -1889,7 +2310,7 @@ msgid "" "state." msgstr "" -#: ../../c-api/init.rst:1540 +#: ../../c-api/init.rst:1689 msgid "" "Like all other Python/C API functions, the global interpreter lock must be " "held before calling this function and is still held when it returns. " @@ -1901,13 +2322,31 @@ msgid "" "released here." msgstr "" -#: ../../c-api/init.rst:1551 +#: ../../c-api/init.rst:1700 msgid "" "Sub-interpreters are most effective when isolated from each other, with " "certain functionality restricted::" msgstr "" -#: ../../c-api/init.rst:1565 +#: ../../c-api/init.rst:1703 +msgid "" +"PyInterpreterConfig config = {\n" +" .use_main_obmalloc = 0,\n" +" .allow_fork = 0,\n" +" .allow_exec = 0,\n" +" .allow_threads = 1,\n" +" .allow_daemon_threads = 0,\n" +" .check_multi_interp_extensions = 1,\n" +" .gil = PyInterpreterConfig_OWN_GIL,\n" +"};\n" +"PyThreadState *tstate = NULL;\n" +"PyStatus status = Py_NewInterpreterFromConfig(&tstate, &config);\n" +"if (PyStatus_Exception(status)) {\n" +" Py_ExitStatusException(status);\n" +"}" +msgstr "" + +#: ../../c-api/init.rst:1718 msgid "" "Note that the config is used only briefly and does not get modified. During " "initialization the config's values are converted into various :c:type:" @@ -1915,11 +2354,11 @@ msgid "" "internally on the :c:type:`PyInterpreterState`." msgstr "" -#: ../../c-api/init.rst:1574 +#: ../../c-api/init.rst:1727 msgid "Extension modules are shared between (sub-)interpreters as follows:" msgstr "" -#: ../../c-api/init.rst:1576 +#: ../../c-api/init.rst:1729 msgid "" "For modules using multi-phase initialization, e.g. :c:func:" "`PyModule_FromDefAndSpec`, a separate module object is created and " @@ -1927,7 +2366,7 @@ msgid "" "are shared between these module objects." msgstr "" -#: ../../c-api/init.rst:1582 +#: ../../c-api/init.rst:1735 msgid "" "For modules using single-phase initialization, e.g. :c:func:" "`PyModule_Create`, the first time a particular extension is imported, it is " @@ -1939,7 +2378,7 @@ msgid "" "might cause unwanted behavior (see `Bugs and caveats`_ below)." msgstr "" -#: ../../c-api/init.rst:1593 +#: ../../c-api/init.rst:1746 msgid "" "Note that this is different from what happens when an extension is imported " "after the interpreter has been completely re-initialized by calling :c:func:" @@ -1949,7 +2388,7 @@ msgid "" "shared between these modules." msgstr "" -#: ../../c-api/init.rst:1613 +#: ../../c-api/init.rst:1766 msgid "" "Create a new sub-interpreter. This is essentially just a wrapper around :c:" "func:`Py_NewInterpreterFromConfig` with a config that preserves the existing " @@ -1958,7 +2397,7 @@ msgid "" "single-phase init modules." msgstr "" -#: ../../c-api/init.rst:1625 +#: ../../c-api/init.rst:1778 msgid "" "Destroy the (sub-)interpreter represented by the given thread state. The " "given thread state must be the current thread state. See the discussion of " @@ -1968,17 +2407,17 @@ msgid "" "be held before calling this function. No GIL is held when it returns." msgstr "" -#: ../../c-api/init.rst:1633 +#: ../../c-api/init.rst:1786 msgid "" ":c:func:`Py_FinalizeEx` will destroy all sub-interpreters that haven't been " "explicitly destroyed at that point." msgstr "" -#: ../../c-api/init.rst:1638 +#: ../../c-api/init.rst:1791 msgid "A Per-Interpreter GIL" msgstr "" -#: ../../c-api/init.rst:1640 +#: ../../c-api/init.rst:1793 msgid "" "Using :c:func:`Py_NewInterpreterFromConfig` you can create a sub-interpreter " "that is completely isolated from other interpreters, including having its " @@ -1990,7 +2429,7 @@ msgid "" "just using threads. (See :pep:`554`.)" msgstr "" -#: ../../c-api/init.rst:1650 +#: ../../c-api/init.rst:1803 msgid "" "Using an isolated interpreter requires vigilance in preserving that " "isolation. That especially means not sharing any objects or mutable state " @@ -2004,7 +2443,7 @@ msgid "" "builtin objects." msgstr "" -#: ../../c-api/init.rst:1661 +#: ../../c-api/init.rst:1814 msgid "" "If you preserve isolation then you will have access to proper multi-core " "computing without the complications that come with free-threading. Failure " @@ -2016,7 +2455,7 @@ msgstr "" "falha em preservar o isolamento traz a exposição a todas as consequências de " "threads livres, incluindo corridas e travamentos difíceis de depurar." -#: ../../c-api/init.rst:1666 +#: ../../c-api/init.rst:1819 msgid "" "Aside from that, one of the main challenges of using multiple isolated " "interpreters is how to communicate between them safely (not break isolation) " @@ -2026,11 +2465,11 @@ msgid "" "sharing) data between interpreters." msgstr "" -#: ../../c-api/init.rst:1677 +#: ../../c-api/init.rst:1830 msgid "Bugs and caveats" msgstr "" -#: ../../c-api/init.rst:1679 +#: ../../c-api/init.rst:1832 msgid "" "Because sub-interpreters (and the main interpreter) are part of the same " "process, the insulation between them isn't perfect --- for example, using " @@ -2043,7 +2482,7 @@ msgid "" "should be avoided if possible." msgstr "" -#: ../../c-api/init.rst:1689 +#: ../../c-api/init.rst:1842 msgid "" "Special care should be taken to avoid sharing user-defined functions, " "methods, instances or classes between sub-interpreters, since import " @@ -2052,7 +2491,7 @@ msgid "" "objects from which the above are reachable." msgstr "" -#: ../../c-api/init.rst:1695 +#: ../../c-api/init.rst:1848 msgid "" "Also note that combining this functionality with ``PyGILState_*`` APIs is " "delicate, because these APIs assume a bijection between Python thread states " @@ -2064,25 +2503,25 @@ msgid "" "created threads will probably be broken when using sub-interpreters." msgstr "" -#: ../../c-api/init.rst:1706 +#: ../../c-api/init.rst:1859 msgid "Asynchronous Notifications" msgstr "Notificações assíncronas" -#: ../../c-api/init.rst:1708 +#: ../../c-api/init.rst:1861 msgid "" "A mechanism is provided to make asynchronous notifications to the main " "interpreter thread. These notifications take the form of a function pointer " "and a void pointer argument." msgstr "" -#: ../../c-api/init.rst:1715 +#: ../../c-api/init.rst:1868 msgid "" "Schedule a function to be called from the main interpreter thread. On " "success, ``0`` is returned and *func* is queued for being called in the main " "thread. On failure, ``-1`` is returned without setting any exception." msgstr "" -#: ../../c-api/init.rst:1719 +#: ../../c-api/init.rst:1872 msgid "" "When successfully queued, *func* will be *eventually* called from the main " "interpreter thread with the argument *arg*. It will be called " @@ -2090,17 +2529,17 @@ msgid "" "these conditions met:" msgstr "" -#: ../../c-api/init.rst:1724 +#: ../../c-api/init.rst:1877 msgid "on a :term:`bytecode` boundary;" msgstr "" -#: ../../c-api/init.rst:1725 +#: ../../c-api/init.rst:1878 msgid "" "with the main thread holding the :term:`global interpreter lock` (*func* can " "therefore use the full C API)." msgstr "" -#: ../../c-api/init.rst:1728 +#: ../../c-api/init.rst:1881 msgid "" "*func* must return ``0`` on success, or ``-1`` on failure with an exception " "set. *func* won't be interrupted to perform another asynchronous " @@ -2108,20 +2547,20 @@ msgid "" "if the global interpreter lock is released." msgstr "" -#: ../../c-api/init.rst:1733 +#: ../../c-api/init.rst:1886 msgid "" "This function doesn't need a current thread state to run, and it doesn't " "need the global interpreter lock." msgstr "" -#: ../../c-api/init.rst:1736 +#: ../../c-api/init.rst:1889 msgid "" "To call this function in a subinterpreter, the caller must hold the GIL. " "Otherwise, the function *func* can be scheduled to be called from the wrong " "interpreter." msgstr "" -#: ../../c-api/init.rst:1741 +#: ../../c-api/init.rst:1894 msgid "" "This is a low-level function, only useful for very special cases. There is " "no guarantee that *func* will be called as quick as possible. If the main " @@ -2131,7 +2570,7 @@ msgid "" "`PyGILState API`." msgstr "" -#: ../../c-api/init.rst:1750 +#: ../../c-api/init.rst:1903 msgid "" "If this function is called in a subinterpreter, the function *func* is now " "scheduled to be called from the subinterpreter, rather than being called " @@ -2139,18 +2578,18 @@ msgid "" "scheduled calls." msgstr "" -#: ../../c-api/init.rst:1759 +#: ../../c-api/init.rst:1912 msgid "Profiling and Tracing" msgstr "" -#: ../../c-api/init.rst:1764 +#: ../../c-api/init.rst:1917 msgid "" "The Python interpreter provides some low-level support for attaching " "profiling and execution tracing facilities. These are used for profiling, " "debugging, and coverage analysis tools." msgstr "" -#: ../../c-api/init.rst:1768 +#: ../../c-api/init.rst:1921 msgid "" "This C interface allows the profiling or tracing code to avoid the overhead " "of calling through Python-level callable objects, making a direct C function " @@ -2160,7 +2599,7 @@ msgid "" "reported to the Python-level trace functions in previous versions." msgstr "" -#: ../../c-api/init.rst:1778 +#: ../../c-api/init.rst:1931 msgid "" "The type of the trace function registered using :c:func:`PyEval_SetProfile` " "and :c:func:`PyEval_SetTrace`. The first parameter is the object passed to " @@ -2172,66 +2611,66 @@ msgid "" "value of *what*:" msgstr "" -#: ../../c-api/init.rst:1787 +#: ../../c-api/init.rst:1940 msgid "Value of *what*" msgstr "" -#: ../../c-api/init.rst:1787 +#: ../../c-api/init.rst:1940 msgid "Meaning of *arg*" msgstr "" -#: ../../c-api/init.rst:1789 +#: ../../c-api/init.rst:1942 msgid ":c:data:`PyTrace_CALL`" msgstr "" -#: ../../c-api/init.rst:1789 ../../c-api/init.rst:1794 -#: ../../c-api/init.rst:1805 +#: ../../c-api/init.rst:1942 ../../c-api/init.rst:1947 +#: ../../c-api/init.rst:1958 msgid "Always :c:data:`Py_None`." msgstr "" -#: ../../c-api/init.rst:1791 +#: ../../c-api/init.rst:1944 msgid ":c:data:`PyTrace_EXCEPTION`" msgstr "" -#: ../../c-api/init.rst:1791 +#: ../../c-api/init.rst:1944 msgid "Exception information as returned by :func:`sys.exc_info`." msgstr "" -#: ../../c-api/init.rst:1794 +#: ../../c-api/init.rst:1947 msgid ":c:data:`PyTrace_LINE`" msgstr "" -#: ../../c-api/init.rst:1796 +#: ../../c-api/init.rst:1949 msgid ":c:data:`PyTrace_RETURN`" msgstr "" -#: ../../c-api/init.rst:1796 +#: ../../c-api/init.rst:1949 msgid "" "Value being returned to the caller, or ``NULL`` if caused by an exception." msgstr "" -#: ../../c-api/init.rst:1799 +#: ../../c-api/init.rst:1952 msgid ":c:data:`PyTrace_C_CALL`" msgstr "" -#: ../../c-api/init.rst:1799 ../../c-api/init.rst:1801 -#: ../../c-api/init.rst:1803 +#: ../../c-api/init.rst:1952 ../../c-api/init.rst:1954 +#: ../../c-api/init.rst:1956 msgid "Function object being called." msgstr "" -#: ../../c-api/init.rst:1801 +#: ../../c-api/init.rst:1954 msgid ":c:data:`PyTrace_C_EXCEPTION`" msgstr "" -#: ../../c-api/init.rst:1803 +#: ../../c-api/init.rst:1956 msgid ":c:data:`PyTrace_C_RETURN`" msgstr "" -#: ../../c-api/init.rst:1805 +#: ../../c-api/init.rst:1958 msgid ":c:data:`PyTrace_OPCODE`" msgstr "" -#: ../../c-api/init.rst:1810 +#: ../../c-api/init.rst:1963 msgid "" "The value of the *what* parameter to a :c:type:`Py_tracefunc` function when " "a new call to a function or method is being reported, or a new entry into a " @@ -2240,7 +2679,7 @@ msgid "" "the corresponding frame." msgstr "" -#: ../../c-api/init.rst:1819 +#: ../../c-api/init.rst:1972 msgid "" "The value of the *what* parameter to a :c:type:`Py_tracefunc` function when " "an exception has been raised. The callback function is called with this " @@ -2252,7 +2691,7 @@ msgid "" "profiler." msgstr "" -#: ../../c-api/init.rst:1830 +#: ../../c-api/init.rst:1983 msgid "" "The value passed as the *what* parameter to a :c:type:`Py_tracefunc` " "function (but not a profiling function) when a line-number event is being " @@ -2260,31 +2699,31 @@ msgid "" "f_trace_lines` to *0* on that frame." msgstr "" -#: ../../c-api/init.rst:1838 +#: ../../c-api/init.rst:1991 msgid "" "The value for the *what* parameter to :c:type:`Py_tracefunc` functions when " "a call is about to return." msgstr "" -#: ../../c-api/init.rst:1844 +#: ../../c-api/init.rst:1997 msgid "" "The value for the *what* parameter to :c:type:`Py_tracefunc` functions when " "a C function is about to be called." msgstr "" -#: ../../c-api/init.rst:1850 +#: ../../c-api/init.rst:2003 msgid "" "The value for the *what* parameter to :c:type:`Py_tracefunc` functions when " "a C function has raised an exception." msgstr "" -#: ../../c-api/init.rst:1856 +#: ../../c-api/init.rst:2009 msgid "" "The value for the *what* parameter to :c:type:`Py_tracefunc` functions when " "a C function has returned." msgstr "" -#: ../../c-api/init.rst:1862 +#: ../../c-api/init.rst:2015 msgid "" "The value for the *what* parameter to :c:type:`Py_tracefunc` functions (but " "not profiling functions) when a new opcode is about to be executed. This " @@ -2292,7 +2731,7 @@ msgid "" "attr:`~frame.f_trace_opcodes` to *1* on the frame." msgstr "" -#: ../../c-api/init.rst:1870 +#: ../../c-api/init.rst:2023 msgid "" "Set the profiler function to *func*. The *obj* parameter is passed to the " "function as its first parameter, and may be any Python object, or ``NULL``. " @@ -2302,29 +2741,29 @@ msgid "" "`PyTrace_LINE` :c:data:`PyTrace_OPCODE` and :c:data:`PyTrace_EXCEPTION`." msgstr "" -#: ../../c-api/init.rst:1877 +#: ../../c-api/init.rst:2030 msgid "See also the :func:`sys.setprofile` function." msgstr "" -#: ../../c-api/init.rst:1879 ../../c-api/init.rst:1886 -#: ../../c-api/init.rst:1905 ../../c-api/init.rst:1912 +#: ../../c-api/init.rst:2032 ../../c-api/init.rst:2039 +#: ../../c-api/init.rst:2058 ../../c-api/init.rst:2065 msgid "The caller must hold the :term:`GIL`." msgstr "" -#: ../../c-api/init.rst:1883 +#: ../../c-api/init.rst:2036 msgid "" "Like :c:func:`PyEval_SetProfile` but sets the profile function in all " "running threads belonging to the current interpreter instead of the setting " "it only on the current thread." msgstr "" -#: ../../c-api/init.rst:1888 +#: ../../c-api/init.rst:2041 msgid "" "As :c:func:`PyEval_SetProfile`, this function ignores any exceptions raised " "while setting the profile functions in all threads." msgstr "" -#: ../../c-api/init.rst:1896 +#: ../../c-api/init.rst:2049 msgid "" "Set the tracing function to *func*. This is similar to :c:func:" "`PyEval_SetProfile`, except the tracing function does receive line-number " @@ -2335,28 +2774,28 @@ msgid "" "*what* parameter." msgstr "" -#: ../../c-api/init.rst:1903 +#: ../../c-api/init.rst:2056 msgid "See also the :func:`sys.settrace` function." msgstr "" -#: ../../c-api/init.rst:1909 +#: ../../c-api/init.rst:2062 msgid "" "Like :c:func:`PyEval_SetTrace` but sets the tracing function in all running " "threads belonging to the current interpreter instead of the setting it only " "on the current thread." msgstr "" -#: ../../c-api/init.rst:1914 +#: ../../c-api/init.rst:2067 msgid "" "As :c:func:`PyEval_SetTrace`, this function ignores any exceptions raised " "while setting the trace functions in all threads." msgstr "" -#: ../../c-api/init.rst:1920 +#: ../../c-api/init.rst:2073 msgid "Reference tracing" msgstr "" -#: ../../c-api/init.rst:1926 +#: ../../c-api/init.rst:2079 msgid "" "The type of the trace function registered using :c:func:" "`PyRefTracer_SetTracer`. The first parameter is a Python object that has " @@ -2366,19 +2805,19 @@ msgid "" "provided when :c:func:`PyRefTracer_SetTracer` was called." msgstr "" -#: ../../c-api/init.rst:1936 +#: ../../c-api/init.rst:2089 msgid "" "The value for the *event* parameter to :c:type:`PyRefTracer` functions when " "a Python object has been created." msgstr "" -#: ../../c-api/init.rst:1941 +#: ../../c-api/init.rst:2094 msgid "" "The value for the *event* parameter to :c:type:`PyRefTracer` functions when " "a Python object has been destroyed." msgstr "" -#: ../../c-api/init.rst:1946 +#: ../../c-api/init.rst:2099 msgid "" "Register a reference tracer function. The function will be called when a new " "Python has been created or when an object is going to be destroyed. If " @@ -2387,7 +2826,7 @@ msgid "" "return ``-1`` on error." msgstr "" -#: ../../c-api/init.rst:1952 +#: ../../c-api/init.rst:2105 msgid "" "Not that tracer functions **must not** create Python objects inside or " "otherwise the call will be re-entrant. The tracer also **must not** clear " @@ -2395,11 +2834,11 @@ msgid "" "the tracer function is called." msgstr "" -#: ../../c-api/init.rst:1957 ../../c-api/init.rst:1968 +#: ../../c-api/init.rst:2110 ../../c-api/init.rst:2121 msgid "The GIL must be held when calling this function." msgstr "" -#: ../../c-api/init.rst:1963 +#: ../../c-api/init.rst:2116 msgid "" "Get the registered reference tracer function and the value of the opaque " "data pointer that was registered when :c:func:`PyRefTracer_SetTracer` was " @@ -2407,48 +2846,48 @@ msgid "" "set the **data** pointer to NULL." msgstr "" -#: ../../c-api/init.rst:1975 +#: ../../c-api/init.rst:2128 msgid "Advanced Debugger Support" msgstr "" -#: ../../c-api/init.rst:1980 +#: ../../c-api/init.rst:2133 msgid "" "These functions are only intended to be used by advanced debugging tools." msgstr "" -#: ../../c-api/init.rst:1985 +#: ../../c-api/init.rst:2138 msgid "" "Return the interpreter state object at the head of the list of all such " "objects." msgstr "" -#: ../../c-api/init.rst:1990 +#: ../../c-api/init.rst:2143 msgid "Return the main interpreter state object." msgstr "" -#: ../../c-api/init.rst:1995 +#: ../../c-api/init.rst:2148 msgid "" "Return the next interpreter state object after *interp* from the list of all " "such objects." msgstr "" -#: ../../c-api/init.rst:2001 +#: ../../c-api/init.rst:2154 msgid "" "Return the pointer to the first :c:type:`PyThreadState` object in the list " "of threads associated with the interpreter *interp*." msgstr "" -#: ../../c-api/init.rst:2007 +#: ../../c-api/init.rst:2160 msgid "" "Return the next thread state object after *tstate* from the list of all such " "objects belonging to the same :c:type:`PyInterpreterState` object." msgstr "" -#: ../../c-api/init.rst:2014 +#: ../../c-api/init.rst:2167 msgid "Thread Local Storage Support" msgstr "" -#: ../../c-api/init.rst:2018 +#: ../../c-api/init.rst:2171 msgid "" "The Python interpreter provides low-level support for thread-local storage " "(TLS) which wraps the underlying native TLS implementation to support the " @@ -2458,19 +2897,19 @@ msgid "" "thread." msgstr "" -#: ../../c-api/init.rst:2025 +#: ../../c-api/init.rst:2178 msgid "" "The GIL does *not* need to be held when calling these functions; they supply " "their own locking." msgstr "" -#: ../../c-api/init.rst:2028 +#: ../../c-api/init.rst:2181 msgid "" "Note that :file:`Python.h` does not include the declaration of the TLS APIs, " "you need to include :file:`pythread.h` to use thread-local storage." msgstr "" -#: ../../c-api/init.rst:2032 +#: ../../c-api/init.rst:2185 msgid "" "None of these API functions handle memory management on behalf of the :c:" "expr:`void*` values. You need to allocate and deallocate them yourself. If " @@ -2478,22 +2917,22 @@ msgid "" "don't do refcount operations on them either." msgstr "" -#: ../../c-api/init.rst:2040 +#: ../../c-api/init.rst:2193 msgid "Thread Specific Storage (TSS) API" msgstr "" -#: ../../c-api/init.rst:2042 +#: ../../c-api/init.rst:2195 msgid "" "TSS API is introduced to supersede the use of the existing TLS API within " "the CPython interpreter. This API uses a new type :c:type:`Py_tss_t` " "instead of :c:expr:`int` to represent thread keys." msgstr "" -#: ../../c-api/init.rst:2048 +#: ../../c-api/init.rst:2201 msgid "\"A New C-API for Thread-Local Storage in CPython\" (:pep:`539`)" msgstr "" -#: ../../c-api/init.rst:2053 +#: ../../c-api/init.rst:2206 msgid "" "This data structure represents the state of a thread key, the definition of " "which may depend on the underlying TLS implementation, and it has an " @@ -2501,7 +2940,7 @@ msgid "" "public members in this structure." msgstr "" -#: ../../c-api/init.rst:2058 +#: ../../c-api/init.rst:2211 msgid "" "When :ref:`Py_LIMITED_API ` is not defined, static allocation of " "this type by :c:macro:`Py_tss_NEEDS_INIT` is allowed." @@ -2509,24 +2948,24 @@ msgstr "" "Quando :ref:`Py_LIMITED_API ` não é definido, a alocação estática " "deste tipo por :c:macro:`Py_tss_NEEDS_INIT` é permitida." -#: ../../c-api/init.rst:2064 +#: ../../c-api/init.rst:2217 msgid "" "This macro expands to the initializer for :c:type:`Py_tss_t` variables. Note " "that this macro won't be defined with :ref:`Py_LIMITED_API `." msgstr "" -#: ../../c-api/init.rst:2069 +#: ../../c-api/init.rst:2222 msgid "Dynamic Allocation" msgstr "Alocação dinâmica" -#: ../../c-api/init.rst:2071 +#: ../../c-api/init.rst:2224 msgid "" "Dynamic allocation of the :c:type:`Py_tss_t`, required in extension modules " "built with :ref:`Py_LIMITED_API `, where static allocation of this " "type is not possible due to its implementation being opaque at build time." msgstr "" -#: ../../c-api/init.rst:2078 +#: ../../c-api/init.rst:2231 msgid "" "Return a value which is the same state as a value initialized with :c:macro:" "`Py_tss_NEEDS_INIT`, or ``NULL`` in the case of dynamic allocation failure." @@ -2534,23 +2973,23 @@ msgstr "" "Retorna um valor que é o mesmo estado de um valor inicializado com :c:macro:" "`Py_tss_NEEDS_INIT`, ou ``NULL`` no caso de falha de alocação dinâmica." -#: ../../c-api/init.rst:2085 +#: ../../c-api/init.rst:2238 msgid "" "Free the given *key* allocated by :c:func:`PyThread_tss_alloc`, after first " "calling :c:func:`PyThread_tss_delete` to ensure any associated thread locals " "have been unassigned. This is a no-op if the *key* argument is ``NULL``." msgstr "" -#: ../../c-api/init.rst:2091 +#: ../../c-api/init.rst:2244 msgid "" "A freed key becomes a dangling pointer. You should reset the key to ``NULL``." msgstr "" -#: ../../c-api/init.rst:2096 +#: ../../c-api/init.rst:2249 msgid "Methods" msgstr "Métodos" -#: ../../c-api/init.rst:2098 +#: ../../c-api/init.rst:2251 msgid "" "The parameter *key* of these functions must not be ``NULL``. Moreover, the " "behaviors of :c:func:`PyThread_tss_set` and :c:func:`PyThread_tss_get` are " @@ -2558,13 +2997,13 @@ msgid "" "func:`PyThread_tss_create`." msgstr "" -#: ../../c-api/init.rst:2106 +#: ../../c-api/init.rst:2259 msgid "" "Return a non-zero value if the given :c:type:`Py_tss_t` has been initialized " "by :c:func:`PyThread_tss_create`." msgstr "" -#: ../../c-api/init.rst:2112 +#: ../../c-api/init.rst:2265 msgid "" "Return a zero value on successful initialization of a TSS key. The behavior " "is undefined if the value pointed to by the *key* argument is not " @@ -2578,7 +3017,7 @@ msgstr "" "repetidamente na mesma tecla -- chamá-la em uma tecla já inicializada não " "funciona e retorna imediatamente com sucesso." -#: ../../c-api/init.rst:2121 +#: ../../c-api/init.rst:2274 msgid "" "Destroy a TSS key to forget the values associated with the key across all " "threads, and change the key's initialization state to uninitialized. A " @@ -2587,31 +3026,31 @@ msgid "" "key -- calling it on an already destroyed key is a no-op." msgstr "" -#: ../../c-api/init.rst:2130 +#: ../../c-api/init.rst:2283 msgid "" "Return a zero value to indicate successfully associating a :c:expr:`void*` " "value with a TSS key in the current thread. Each thread has a distinct " "mapping of the key to a :c:expr:`void*` value." msgstr "" -#: ../../c-api/init.rst:2137 +#: ../../c-api/init.rst:2290 msgid "" "Return the :c:expr:`void*` value associated with a TSS key in the current " "thread. This returns ``NULL`` if no value is associated with the key in the " "current thread." msgstr "" -#: ../../c-api/init.rst:2145 +#: ../../c-api/init.rst:2298 msgid "Thread Local Storage (TLS) API" msgstr "" -#: ../../c-api/init.rst:2147 +#: ../../c-api/init.rst:2300 msgid "" "This API is superseded by :ref:`Thread Specific Storage (TSS) API `." msgstr "" -#: ../../c-api/init.rst:2152 +#: ../../c-api/init.rst:2305 msgid "" "This version of the API does not support platforms where the native TLS key " "is defined in a way that cannot be safely cast to ``int``. On such " @@ -2620,58 +3059,62 @@ msgid "" "platforms." msgstr "" -#: ../../c-api/init.rst:2157 +#: ../../c-api/init.rst:2310 msgid "" "Due to the compatibility problem noted above, this version of the API should " "not be used in new code." msgstr "" -#: ../../c-api/init.rst:2168 +#: ../../c-api/init.rst:2321 msgid "Synchronization Primitives" msgstr "" -#: ../../c-api/init.rst:2170 +#: ../../c-api/init.rst:2323 msgid "The C-API provides a basic mutual exclusion lock." msgstr "" -#: ../../c-api/init.rst:2174 +#: ../../c-api/init.rst:2327 msgid "" "A mutual exclusion lock. The :c:type:`!PyMutex` should be initialized to " "zero to represent the unlocked state. For example::" msgstr "" -#: ../../c-api/init.rst:2179 +#: ../../c-api/init.rst:2330 +msgid "PyMutex mutex = {0};" +msgstr "" + +#: ../../c-api/init.rst:2332 msgid "" "Instances of :c:type:`!PyMutex` should not be copied or moved. Both the " "contents and address of a :c:type:`!PyMutex` are meaningful, and it must " "remain at a fixed, writable location in memory." msgstr "" -#: ../../c-api/init.rst:2185 +#: ../../c-api/init.rst:2338 msgid "" "A :c:type:`!PyMutex` currently occupies one byte, but the size should be " "considered unstable. The size may change in future Python releases without " "a deprecation period." msgstr "" -#: ../../c-api/init.rst:2193 +#: ../../c-api/init.rst:2346 msgid "" "Lock mutex *m*. If another thread has already locked it, the calling thread " "will block until the mutex is unlocked. While blocked, the thread will " "temporarily release the :term:`GIL` if it is held." msgstr "" -#: ../../c-api/init.rst:2201 +#: ../../c-api/init.rst:2354 msgid "" "Unlock mutex *m*. The mutex must be locked --- otherwise, the function will " "issue a fatal error." msgstr "" -#: ../../c-api/init.rst:2209 +#: ../../c-api/init.rst:2362 msgid "Python Critical Section API" msgstr "" -#: ../../c-api/init.rst:2211 +#: ../../c-api/init.rst:2364 msgid "" "The critical section API provides a deadlock avoidance layer on top of per-" "object locks for :term:`free-threaded ` CPython. They are " @@ -2679,7 +3122,7 @@ msgid "" "no-ops in versions of Python with the global interpreter lock." msgstr "" -#: ../../c-api/init.rst:2216 +#: ../../c-api/init.rst:2369 msgid "" "Critical sections avoid deadlocks by implicitly suspending active critical " "sections and releasing the locks during calls to :c:func:" @@ -2689,7 +3132,7 @@ msgid "" "-- they are useful because their behavior is similar to the :term:`GIL`." msgstr "" -#: ../../c-api/init.rst:2223 +#: ../../c-api/init.rst:2376 msgid "" "The functions and structs used by the macros are exposed for cases where C " "macros are not available. They should only be used as in the given macro " @@ -2697,7 +3140,7 @@ msgid "" "future Python versions." msgstr "" -#: ../../c-api/init.rst:2230 +#: ../../c-api/init.rst:2383 msgid "" "Operations that need to lock two objects at once must use :c:macro:" "`Py_BEGIN_CRITICAL_SECTION2`. You *cannot* use nested critical sections to " @@ -2706,203 +3149,241 @@ msgid "" "lock more than two objects at once." msgstr "" -#: ../../c-api/init.rst:2236 +#: ../../c-api/init.rst:2389 msgid "Example usage::" msgstr "Exemplo de uso::" -#: ../../c-api/init.rst:2247 +#: ../../c-api/init.rst:2391 +msgid "" +"static PyObject *\n" +"set_field(MyObject *self, PyObject *value)\n" +"{\n" +" Py_BEGIN_CRITICAL_SECTION(self);\n" +" Py_SETREF(self->field, Py_XNewRef(value));\n" +" Py_END_CRITICAL_SECTION();\n" +" Py_RETURN_NONE;\n" +"}" +msgstr "" + +#: ../../c-api/init.rst:2400 msgid "" "In the above example, :c:macro:`Py_SETREF` calls :c:macro:`Py_DECREF`, which " "can call arbitrary code through an object's deallocation function. The " -"critical section API avoids potentital deadlocks due to reentrancy and lock " +"critical section API avoids potential deadlocks due to reentrancy and lock " "ordering by allowing the runtime to temporarily suspend the critical section " "if the code triggered by the finalizer blocks and calls :c:func:" "`PyEval_SaveThread`." msgstr "" -#: ../../c-api/init.rst:2255 +#: ../../c-api/init.rst:2408 msgid "" "Acquires the per-object lock for the object *op* and begins a critical " "section." msgstr "" -#: ../../c-api/init.rst:2258 ../../c-api/init.rst:2272 -#: ../../c-api/init.rst:2287 ../../c-api/init.rst:2301 +#: ../../c-api/init.rst:2411 ../../c-api/init.rst:2425 +#: ../../c-api/init.rst:2440 ../../c-api/init.rst:2454 msgid "In the free-threaded build, this macro expands to::" msgstr "" -#: ../../c-api/init.rst:2264 ../../c-api/init.rst:2293 +#: ../../c-api/init.rst:2413 +msgid "" +"{\n" +" PyCriticalSection _py_cs;\n" +" PyCriticalSection_Begin(&_py_cs, (PyObject*)(op))" +msgstr "" + +#: ../../c-api/init.rst:2417 ../../c-api/init.rst:2446 msgid "In the default build, this macro expands to ``{``." msgstr "" -#: ../../c-api/init.rst:2270 +#: ../../c-api/init.rst:2423 msgid "Ends the critical section and releases the per-object lock." msgstr "" -#: ../../c-api/init.rst:2277 ../../c-api/init.rst:2306 +#: ../../c-api/init.rst:2427 +msgid "" +" PyCriticalSection_End(&_py_cs);\n" +"}" +msgstr "" + +#: ../../c-api/init.rst:2430 ../../c-api/init.rst:2459 msgid "In the default build, this macro expands to ``}``." msgstr "" -#: ../../c-api/init.rst:2283 +#: ../../c-api/init.rst:2436 msgid "" "Acquires the per-objects locks for the objects *a* and *b* and begins a " "critical section. The locks are acquired in a consistent order (lowest " "address first) to avoid lock ordering deadlocks." msgstr "" -#: ../../c-api/init.rst:2299 +#: ../../c-api/init.rst:2442 +msgid "" +"{\n" +" PyCriticalSection2 _py_cs2;\n" +" PyCriticalSection2_Begin(&_py_cs2, (PyObject*)(a), (PyObject*)(b))" +msgstr "" + +#: ../../c-api/init.rst:2452 msgid "Ends the critical section and releases the per-object locks." msgstr "" -#: ../../c-api/init.rst:335 +#: ../../c-api/init.rst:2456 +msgid "" +" PyCriticalSection2_End(&_py_cs2);\n" +"}" +msgstr "" + +#: ../../c-api/init.rst:350 msgid "PyEval_InitThreads()" msgstr "" -#: ../../c-api/init.rst:335 +#: ../../c-api/init.rst:350 msgid "modules (in module sys)" msgstr "" -#: ../../c-api/init.rst:335 ../../c-api/init.rst:576 +#: ../../c-api/init.rst:350 ../../c-api/init.rst:710 msgid "path (in module sys)" msgstr "" -#: ../../c-api/init.rst:335 ../../c-api/init.rst:576 ../../c-api/init.rst:1011 -#: ../../c-api/init.rst:1510 ../../c-api/init.rst:1605 +#: ../../c-api/init.rst:350 ../../c-api/init.rst:710 ../../c-api/init.rst:1145 +#: ../../c-api/init.rst:1659 ../../c-api/init.rst:1758 msgid "module" msgstr "módulo" -#: ../../c-api/init.rst:335 ../../c-api/init.rst:1510 ../../c-api/init.rst:1605 +#: ../../c-api/init.rst:350 ../../c-api/init.rst:1659 ../../c-api/init.rst:1758 msgid "builtins" msgstr "builtins" -#: ../../c-api/init.rst:335 ../../c-api/init.rst:1510 ../../c-api/init.rst:1605 +#: ../../c-api/init.rst:350 ../../c-api/init.rst:1659 ../../c-api/init.rst:1758 msgid "__main__" msgstr "__main__" -#: ../../c-api/init.rst:335 ../../c-api/init.rst:1510 ../../c-api/init.rst:1605 +#: ../../c-api/init.rst:350 ../../c-api/init.rst:1659 ../../c-api/init.rst:1758 msgid "sys" msgstr "sys" -#: ../../c-api/init.rst:335 ../../c-api/init.rst:576 +#: ../../c-api/init.rst:350 ../../c-api/init.rst:710 msgid "search" msgstr "pesquisa" -#: ../../c-api/init.rst:335 ../../c-api/init.rst:576 +#: ../../c-api/init.rst:350 ../../c-api/init.rst:710 msgid "path" msgstr "caminho" -#: ../../c-api/init.rst:335 ../../c-api/init.rst:1570 ../../c-api/init.rst:1623 +#: ../../c-api/init.rst:350 ../../c-api/init.rst:1723 ../../c-api/init.rst:1776 msgid "Py_FinalizeEx (C function)" msgstr "" -#: ../../c-api/init.rst:445 +#: ../../c-api/init.rst:576 msgid "Py_Initialize()" msgstr "" -#: ../../c-api/init.rst:445 ../../c-api/init.rst:674 +#: ../../c-api/init.rst:576 ../../c-api/init.rst:808 msgid "main()" msgstr "" -#: ../../c-api/init.rst:445 +#: ../../c-api/init.rst:576 msgid "Py_GetPath()" msgstr "" -#: ../../c-api/init.rst:555 +#: ../../c-api/init.rst:689 msgid "executable (in module sys)" msgstr "" -#: ../../c-api/init.rst:609 ../../c-api/init.rst:651 ../../c-api/init.rst:665 +#: ../../c-api/init.rst:743 ../../c-api/init.rst:785 ../../c-api/init.rst:799 msgid "version (in module sys)" msgstr "" -#: ../../c-api/init.rst:621 +#: ../../c-api/init.rst:755 msgid "platform (in module sys)" msgstr "" -#: ../../c-api/init.rst:638 +#: ../../c-api/init.rst:772 msgid "copyright (in module sys)" msgstr "" -#: ../../c-api/init.rst:674 +#: ../../c-api/init.rst:808 msgid "Py_FatalError()" msgstr "" -#: ../../c-api/init.rst:674 +#: ../../c-api/init.rst:808 msgid "argv (in module sys)" msgstr "" -#: ../../c-api/init.rst:794 +#: ../../c-api/init.rst:928 msgid "global interpreter lock" msgstr "trava global do interpretador" -#: ../../c-api/init.rst:794 +#: ../../c-api/init.rst:928 msgid "interpreter lock" msgstr "" -#: ../../c-api/init.rst:794 +#: ../../c-api/init.rst:928 msgid "lock, interpreter" msgstr "" -#: ../../c-api/init.rst:807 +#: ../../c-api/init.rst:941 msgid "setswitchinterval (in module sys)" msgstr "" -#: ../../c-api/init.rst:816 +#: ../../c-api/init.rst:950 msgid "PyThreadState (C type)" msgstr "" -#: ../../c-api/init.rst:842 +#: ../../c-api/init.rst:976 msgid "Py_BEGIN_ALLOW_THREADS (C macro)" msgstr "" -#: ../../c-api/init.rst:842 +#: ../../c-api/init.rst:976 msgid "Py_END_ALLOW_THREADS (C macro)" msgstr "" -#: ../../c-api/init.rst:858 +#: ../../c-api/init.rst:992 msgid "PyEval_RestoreThread (C function)" msgstr "" -#: ../../c-api/init.rst:858 +#: ../../c-api/init.rst:992 msgid "PyEval_SaveThread (C function)" msgstr "" -#: ../../c-api/init.rst:989 +#: ../../c-api/init.rst:1123 msgid "PyEval_AcquireThread()" msgstr "" -#: ../../c-api/init.rst:989 +#: ../../c-api/init.rst:1123 msgid "PyEval_ReleaseThread()" msgstr "" -#: ../../c-api/init.rst:989 +#: ../../c-api/init.rst:1123 msgid "PyEval_SaveThread()" msgstr "" -#: ../../c-api/init.rst:989 +#: ../../c-api/init.rst:1123 msgid "PyEval_RestoreThread()" msgstr "" -#: ../../c-api/init.rst:1011 +#: ../../c-api/init.rst:1145 msgid "_thread" msgstr "_thread" -#: ../../c-api/init.rst:1510 ../../c-api/init.rst:1605 +#: ../../c-api/init.rst:1659 ../../c-api/init.rst:1758 msgid "stdout (in module sys)" -msgstr "" +msgstr "stdout (no módulo sys)" -#: ../../c-api/init.rst:1510 ../../c-api/init.rst:1605 +#: ../../c-api/init.rst:1659 ../../c-api/init.rst:1758 msgid "stderr (in module sys)" -msgstr "" +msgstr "stderr (no módulo sys)" -#: ../../c-api/init.rst:1510 ../../c-api/init.rst:1605 +#: ../../c-api/init.rst:1659 ../../c-api/init.rst:1758 msgid "stdin (in module sys)" -msgstr "" +msgstr "stdin (no módulo sys)" -#: ../../c-api/init.rst:1570 +#: ../../c-api/init.rst:1723 msgid "Py_Initialize (C function)" msgstr "" -#: ../../c-api/init.rst:1600 +#: ../../c-api/init.rst:1753 msgid "close (in module os)" msgstr "" diff --git a/c-api/init_config.po b/c-api/init_config.po index da7753bd2..96bbb06e7 100644 --- a/c-api/init_config.po +++ b/c-api/init_config.po @@ -1,32 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Italo Penaforte , 2021 -# And Past , 2021 -# Hélio Júnior , 2021 -# Rodrigo Cândido, 2022 -# Lívia Pavini Zeviani, 2022 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-26 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-03-14 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -99,6 +92,42 @@ msgid "Example of customized Python always running in isolated mode::" msgstr "" "Exemplo de Python personalizado sendo executado sempre em um modo isolado:" +#: ../../c-api/init_config.rst:41 +msgid "" +"int main(int argc, char **argv)\n" +"{\n" +" PyStatus status;\n" +"\n" +" PyConfig config;\n" +" PyConfig_InitPythonConfig(&config);\n" +" config.isolated = 1;\n" +"\n" +" /* Decode command line arguments.\n" +" Implicitly preinitialize Python (in isolated mode). */\n" +" status = PyConfig_SetBytesArgv(&config, argc, argv);\n" +" if (PyStatus_Exception(status)) {\n" +" goto exception;\n" +" }\n" +"\n" +" status = Py_InitializeFromConfig(&config);\n" +" if (PyStatus_Exception(status)) {\n" +" goto exception;\n" +" }\n" +" PyConfig_Clear(&config);\n" +"\n" +" return Py_RunMain();\n" +"\n" +"exception:\n" +" PyConfig_Clear(&config);\n" +" if (PyStatus_IsExit(status)) {\n" +" return status.exitcode;\n" +" }\n" +" /* Display the error message and exit the process with\n" +" non-zero exit code */\n" +" Py_ExitStatusException(status);\n" +"}" +msgstr "" + #: ../../c-api/init_config.rst:76 msgid "PyWideStringList" msgstr "PyWideStringList" @@ -249,6 +278,29 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" +#: ../../c-api/init_config.rst:191 +msgid "" +"PyStatus alloc(void **ptr, size_t size)\n" +"{\n" +" *ptr = PyMem_RawMalloc(size);\n" +" if (*ptr == NULL) {\n" +" return PyStatus_NoMemory();\n" +" }\n" +" return PyStatus_Ok();\n" +"}\n" +"\n" +"int main(int argc, char **argv)\n" +"{\n" +" void *ptr;\n" +" PyStatus status = alloc(&ptr, 16);\n" +" if (PyStatus_Exception(status)) {\n" +" Py_ExitStatusException(status);\n" +" }\n" +" PyMem_Free(ptr);\n" +" return 0;\n" +"}" +msgstr "" + #: ../../c-api/init_config.rst:213 msgid "PyPreConfig" msgstr "PyPreConfig" @@ -461,11 +513,9 @@ msgstr "Define :c:member:`PyConfig.filesystem_errors` para ``\"replace\"``." #: ../../c-api/init_config.rst:324 msgid "" -"Initialized the from :envvar:`PYTHONLEGACYWINDOWSFSENCODING` environment " +"Initialized from the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` environment " "variable value." msgstr "" -"Inicializado a partir do valor da variável de ambiente :envvar:" -"`PYTHONLEGACYWINDOWSFSENCODING`." #: ../../c-api/init_config.rst:327 ../../c-api/init_config.rst:935 msgid "" @@ -596,7 +646,7 @@ msgstr "" "Analisa argumentos de linha de comando *argv* (strings largas) se :c:member:" "`~PyPreConfig.parse_argv` de *preconfig* for diferente de zero." -#: ../../c-api/init_config.rst:401 ../../c-api/init_config.rst:1360 +#: ../../c-api/init_config.rst:401 ../../c-api/init_config.rst:1359 msgid "" "The caller is responsible to handle exceptions (error or exit) using :c:func:" "`PyStatus_Exception` and :c:func:`Py_ExitStatusException`." @@ -616,7 +666,7 @@ msgstr "" "Para :ref:`configuração do Python ` (:c:func:" "`PyPreConfig_InitPythonConfig`), se o Python for inicializado com argumentos " "de linha de comando, os argumentos de linha de comando também devem ser " -"passados ​​para pré-inicializar o Python, pois eles têm um efeito na pré-" +"passados para pré-inicializar o Python, pois eles têm um efeito na pré-" "configuração como codificações. Por exemplo, a opção de linha de comando :" "option:`-X utf8 <-X>` habilita o :ref:`Modo UTF-8 do Python `." @@ -653,6 +703,26 @@ msgstr "" "Exemplo usando a pré-inicialização para habilitar o :ref:`modo UTF-8 do " "Python `." +#: ../../c-api/init_config.rst:424 +msgid "" +"PyStatus status;\n" +"PyPreConfig preconfig;\n" +"PyPreConfig_InitPythonConfig(&preconfig);\n" +"\n" +"preconfig.utf8_mode = 1;\n" +"\n" +"status = Py_PreInitialize(&preconfig);\n" +"if (PyStatus_Exception(status)) {\n" +" Py_ExitStatusException(status);\n" +"}\n" +"\n" +"/* at this point, Python speaks UTF-8 */\n" +"\n" +"Py_Initialize();\n" +"/* ... use Python API here ... */\n" +"Py_Finalize();" +msgstr "" + #: ../../c-api/init_config.rst:443 msgid "PyConfig" msgstr "PyConfig" @@ -1863,19 +1933,17 @@ msgstr "" msgid "The ``show_alloc_count`` field has been removed." msgstr "" -#: ../../c-api/init_config.rst:1352 -msgid "Initialization with PyConfig" -msgstr "" - #: ../../c-api/init_config.rst:1354 -msgid "Function to initialize Python:" +msgid "Initialization with PyConfig" msgstr "" -#: ../../c-api/init_config.rst:1358 -msgid "Initialize Python from *config* configuration." +#: ../../c-api/init_config.rst:1356 +msgid "" +"Initializing the interpreter from a populated configuration struct is " +"handled by calling :c:func:`Py_InitializeFromConfig`." msgstr "" -#: ../../c-api/init_config.rst:1363 +#: ../../c-api/init_config.rst:1362 msgid "" "If :c:func:`PyImport_FrozenModules`, :c:func:`PyImport_AppendInittab` or :c:" "func:`PyImport_ExtendInittab` are used, they must be set or called after " @@ -1884,17 +1952,46 @@ msgid "" "`PyImport_ExtendInittab` must be called before each Python initialization." msgstr "" -#: ../../c-api/init_config.rst:1370 +#: ../../c-api/init_config.rst:1369 msgid "" "The current configuration (``PyConfig`` type) is stored in " "``PyInterpreterState.config``." msgstr "" -#: ../../c-api/init_config.rst:1373 +#: ../../c-api/init_config.rst:1372 msgid "Example setting the program name::" msgstr "" -#: ../../c-api/init_config.rst:1401 +#: ../../c-api/init_config.rst:1374 +msgid "" +"void init_python(void)\n" +"{\n" +" PyStatus status;\n" +"\n" +" PyConfig config;\n" +" PyConfig_InitPythonConfig(&config);\n" +"\n" +" /* Set the program name. Implicitly preinitialize Python. */\n" +" status = PyConfig_SetString(&config, &config.program_name,\n" +" L\"/path/to/my_program\");\n" +" if (PyStatus_Exception(status)) {\n" +" goto exception;\n" +" }\n" +"\n" +" status = Py_InitializeFromConfig(&config);\n" +" if (PyStatus_Exception(status)) {\n" +" goto exception;\n" +" }\n" +" PyConfig_Clear(&config);\n" +" return;\n" +"\n" +"exception:\n" +" PyConfig_Clear(&config);\n" +" Py_ExitStatusException(status);\n" +"}" +msgstr "" + +#: ../../c-api/init_config.rst:1400 msgid "" "More complete example modifying the default configuration, read the " "configuration, and then override some parameters. Note that since 3.11, many " @@ -1903,18 +2000,73 @@ msgid "" "called will be left unchanged by initialization::" msgstr "" -#: ../../c-api/init_config.rst:1464 +#: ../../c-api/init_config.rst:1407 +msgid "" +"PyStatus init_python(const char *program_name)\n" +"{\n" +" PyStatus status;\n" +"\n" +" PyConfig config;\n" +" PyConfig_InitPythonConfig(&config);\n" +"\n" +" /* Set the program name before reading the configuration\n" +" (decode byte string from the locale encoding).\n" +"\n" +" Implicitly preinitialize Python. */\n" +" status = PyConfig_SetBytesString(&config, &config.program_name,\n" +" program_name);\n" +" if (PyStatus_Exception(status)) {\n" +" goto done;\n" +" }\n" +"\n" +" /* Read all configuration at once */\n" +" status = PyConfig_Read(&config);\n" +" if (PyStatus_Exception(status)) {\n" +" goto done;\n" +" }\n" +"\n" +" /* Specify sys.path explicitly */\n" +" /* If you want to modify the default set of paths, finish\n" +" initialization first and then use PySys_GetObject(\"path\") */\n" +" config.module_search_paths_set = 1;\n" +" status = PyWideStringList_Append(&config.module_search_paths,\n" +" L\"/path/to/stdlib\");\n" +" if (PyStatus_Exception(status)) {\n" +" goto done;\n" +" }\n" +" status = PyWideStringList_Append(&config.module_search_paths,\n" +" L\"/path/to/more/modules\");\n" +" if (PyStatus_Exception(status)) {\n" +" goto done;\n" +" }\n" +"\n" +" /* Override executable computed by PyConfig_Read() */\n" +" status = PyConfig_SetString(&config, &config.executable,\n" +" L\"/path/to/my_executable\");\n" +" if (PyStatus_Exception(status)) {\n" +" goto done;\n" +" }\n" +"\n" +" status = Py_InitializeFromConfig(&config);\n" +"\n" +"done:\n" +" PyConfig_Clear(&config);\n" +" return status;\n" +"}" +msgstr "" + +#: ../../c-api/init_config.rst:1463 msgid "Isolated Configuration" msgstr "" -#: ../../c-api/init_config.rst:1466 +#: ../../c-api/init_config.rst:1465 msgid "" ":c:func:`PyPreConfig_InitIsolatedConfig` and :c:func:" "`PyConfig_InitIsolatedConfig` functions create a configuration to isolate " "Python from the system. For example, to embed Python into an application." msgstr "" -#: ../../c-api/init_config.rst:1471 +#: ../../c-api/init_config.rst:1470 msgid "" "This configuration ignores global configuration variables, environment " "variables, command line arguments (:c:member:`PyConfig.argv` is not parsed) " @@ -1922,115 +2074,115 @@ msgid "" "LC_CTYPE locale are left unchanged. Signal handlers are not installed." msgstr "" -#: ../../c-api/init_config.rst:1476 +#: ../../c-api/init_config.rst:1475 msgid "" "Configuration files are still used with this configuration to determine " "paths that are unspecified. Ensure :c:member:`PyConfig.home` is specified to " "avoid computing the default path configuration." msgstr "" -#: ../../c-api/init_config.rst:1484 +#: ../../c-api/init_config.rst:1483 msgid "Python Configuration" msgstr "Configuração do Python" -#: ../../c-api/init_config.rst:1486 +#: ../../c-api/init_config.rst:1485 msgid "" ":c:func:`PyPreConfig_InitPythonConfig` and :c:func:" "`PyConfig_InitPythonConfig` functions create a configuration to build a " "customized Python which behaves as the regular Python." msgstr "" -#: ../../c-api/init_config.rst:1490 +#: ../../c-api/init_config.rst:1489 msgid "" "Environments variables and command line arguments are used to configure " "Python, whereas global configuration variables are ignored." msgstr "" -#: ../../c-api/init_config.rst:1493 +#: ../../c-api/init_config.rst:1492 msgid "" "This function enables C locale coercion (:pep:`538`) and :ref:`Python UTF-8 " "Mode ` (:pep:`540`) depending on the LC_CTYPE locale, :envvar:" "`PYTHONUTF8` and :envvar:`PYTHONCOERCECLOCALE` environment variables." msgstr "" -#: ../../c-api/init_config.rst:1502 +#: ../../c-api/init_config.rst:1501 msgid "Python Path Configuration" msgstr "" -#: ../../c-api/init_config.rst:1504 +#: ../../c-api/init_config.rst:1503 msgid ":c:type:`PyConfig` contains multiple fields for the path configuration:" msgstr "" -#: ../../c-api/init_config.rst:1506 +#: ../../c-api/init_config.rst:1505 msgid "Path configuration inputs:" msgstr "" -#: ../../c-api/init_config.rst:1508 +#: ../../c-api/init_config.rst:1507 msgid ":c:member:`PyConfig.home`" msgstr ":c:member:`PyConfig.home`" -#: ../../c-api/init_config.rst:1509 +#: ../../c-api/init_config.rst:1508 msgid ":c:member:`PyConfig.platlibdir`" msgstr ":c:member:`PyConfig.platlibdir`" -#: ../../c-api/init_config.rst:1510 +#: ../../c-api/init_config.rst:1509 msgid ":c:member:`PyConfig.pathconfig_warnings`" msgstr ":c:member:`PyConfig.pathconfig_warnings`" -#: ../../c-api/init_config.rst:1511 +#: ../../c-api/init_config.rst:1510 msgid ":c:member:`PyConfig.program_name`" msgstr ":c:member:`PyConfig.program_name`" -#: ../../c-api/init_config.rst:1512 +#: ../../c-api/init_config.rst:1511 msgid ":c:member:`PyConfig.pythonpath_env`" msgstr ":c:member:`PyConfig.pythonpath_env`" -#: ../../c-api/init_config.rst:1513 +#: ../../c-api/init_config.rst:1512 msgid "current working directory: to get absolute paths" msgstr "" -#: ../../c-api/init_config.rst:1514 +#: ../../c-api/init_config.rst:1513 msgid "" "``PATH`` environment variable to get the program full path (from :c:member:" "`PyConfig.program_name`)" msgstr "" -#: ../../c-api/init_config.rst:1516 +#: ../../c-api/init_config.rst:1515 msgid "``__PYVENV_LAUNCHER__`` environment variable" msgstr "" -#: ../../c-api/init_config.rst:1517 +#: ../../c-api/init_config.rst:1516 msgid "" "(Windows only) Application paths in the registry under " "\"Software\\Python\\PythonCore\\X.Y\\PythonPath\" of HKEY_CURRENT_USER and " "HKEY_LOCAL_MACHINE (where X.Y is the Python version)." msgstr "" -#: ../../c-api/init_config.rst:1521 +#: ../../c-api/init_config.rst:1520 msgid "Path configuration output fields:" msgstr "" -#: ../../c-api/init_config.rst:1523 +#: ../../c-api/init_config.rst:1522 msgid ":c:member:`PyConfig.base_exec_prefix`" msgstr ":c:member:`PyConfig.base_exec_prefix`" -#: ../../c-api/init_config.rst:1524 +#: ../../c-api/init_config.rst:1523 msgid ":c:member:`PyConfig.base_executable`" msgstr ":c:member:`PyConfig.base_executable`" -#: ../../c-api/init_config.rst:1525 +#: ../../c-api/init_config.rst:1524 msgid ":c:member:`PyConfig.base_prefix`" msgstr ":c:member:`PyConfig.base_prefix`" -#: ../../c-api/init_config.rst:1526 +#: ../../c-api/init_config.rst:1525 msgid ":c:member:`PyConfig.exec_prefix`" msgstr ":c:member:`PyConfig.exec_prefix`" -#: ../../c-api/init_config.rst:1527 +#: ../../c-api/init_config.rst:1526 msgid ":c:member:`PyConfig.executable`" msgstr ":c:member:`PyConfig.executable`" -#: ../../c-api/init_config.rst:1528 +#: ../../c-api/init_config.rst:1527 msgid "" ":c:member:`PyConfig.module_search_paths_set`, :c:member:`PyConfig." "module_search_paths`" @@ -2038,11 +2190,11 @@ msgstr "" ":c:member:`PyConfig.module_search_paths_set`, :c:member:`PyConfig." "module_search_paths`" -#: ../../c-api/init_config.rst:1530 +#: ../../c-api/init_config.rst:1529 msgid ":c:member:`PyConfig.prefix`" msgstr ":c:member:`PyConfig.prefix`" -#: ../../c-api/init_config.rst:1532 +#: ../../c-api/init_config.rst:1531 msgid "" "If at least one \"output field\" is not set, Python calculates the path " "configuration to fill unset fields. If :c:member:`~PyConfig." @@ -2051,7 +2203,7 @@ msgid "" "module_search_paths_set` is set to ``1``." msgstr "" -#: ../../c-api/init_config.rst:1538 +#: ../../c-api/init_config.rst:1537 msgid "" "It is possible to completely ignore the function calculating the default " "path configuration by setting explicitly all path configuration output " @@ -2061,52 +2213,52 @@ msgid "" "modification." msgstr "" -#: ../../c-api/init_config.rst:1545 +#: ../../c-api/init_config.rst:1544 msgid "" "Set :c:member:`~PyConfig.pathconfig_warnings` to ``0`` to suppress warnings " "when calculating the path configuration (Unix only, Windows does not log any " "warning)." msgstr "" -#: ../../c-api/init_config.rst:1548 +#: ../../c-api/init_config.rst:1547 msgid "" "If :c:member:`~PyConfig.base_prefix` or :c:member:`~PyConfig." "base_exec_prefix` fields are not set, they inherit their value from :c:" "member:`~PyConfig.prefix` and :c:member:`~PyConfig.exec_prefix` respectively." msgstr "" -#: ../../c-api/init_config.rst:1552 +#: ../../c-api/init_config.rst:1551 msgid ":c:func:`Py_RunMain` and :c:func:`Py_Main` modify :data:`sys.path`:" msgstr "" -#: ../../c-api/init_config.rst:1554 +#: ../../c-api/init_config.rst:1553 msgid "" "If :c:member:`~PyConfig.run_filename` is set and is a directory which " "contains a ``__main__.py`` script, prepend :c:member:`~PyConfig." "run_filename` to :data:`sys.path`." msgstr "" -#: ../../c-api/init_config.rst:1557 +#: ../../c-api/init_config.rst:1556 msgid "If :c:member:`~PyConfig.isolated` is zero:" msgstr "" -#: ../../c-api/init_config.rst:1559 +#: ../../c-api/init_config.rst:1558 msgid "" "If :c:member:`~PyConfig.run_module` is set, prepend the current directory " "to :data:`sys.path`. Do nothing if the current directory cannot be read." msgstr "" -#: ../../c-api/init_config.rst:1561 +#: ../../c-api/init_config.rst:1560 msgid "" "If :c:member:`~PyConfig.run_filename` is set, prepend the directory of the " "filename to :data:`sys.path`." msgstr "" -#: ../../c-api/init_config.rst:1563 +#: ../../c-api/init_config.rst:1562 msgid "Otherwise, prepend an empty string to :data:`sys.path`." msgstr "" -#: ../../c-api/init_config.rst:1565 +#: ../../c-api/init_config.rst:1564 msgid "" "If :c:member:`~PyConfig.site_import` is non-zero, :data:`sys.path` can be " "modified by the :mod:`site` module. If :c:member:`~PyConfig." @@ -2115,170 +2267,143 @@ msgid "" "data:`sys.path`." msgstr "" -#: ../../c-api/init_config.rst:1571 +#: ../../c-api/init_config.rst:1570 msgid "The following configuration files are used by the path configuration:" msgstr "" -#: ../../c-api/init_config.rst:1573 +#: ../../c-api/init_config.rst:1572 msgid "``pyvenv.cfg``" msgstr "``pyvenv.cfg``" -#: ../../c-api/init_config.rst:1574 +#: ../../c-api/init_config.rst:1573 msgid "``._pth`` file (ex: ``python._pth``)" msgstr "" -#: ../../c-api/init_config.rst:1575 +#: ../../c-api/init_config.rst:1574 msgid "``pybuilddir.txt`` (Unix only)" msgstr "" -#: ../../c-api/init_config.rst:1577 +#: ../../c-api/init_config.rst:1576 msgid "If a ``._pth`` file is present:" msgstr "" -#: ../../c-api/init_config.rst:1579 +#: ../../c-api/init_config.rst:1578 msgid "Set :c:member:`~PyConfig.isolated` to ``1``." msgstr "" -#: ../../c-api/init_config.rst:1580 +#: ../../c-api/init_config.rst:1579 msgid "Set :c:member:`~PyConfig.use_environment` to ``0``." msgstr "" -#: ../../c-api/init_config.rst:1581 +#: ../../c-api/init_config.rst:1580 msgid "Set :c:member:`~PyConfig.site_import` to ``0``." msgstr "" -#: ../../c-api/init_config.rst:1582 +#: ../../c-api/init_config.rst:1581 msgid "Set :c:member:`~PyConfig.safe_path` to ``1``." msgstr "" -#: ../../c-api/init_config.rst:1584 +#: ../../c-api/init_config.rst:1583 msgid "" "The ``__PYVENV_LAUNCHER__`` environment variable is used to set :c:member:" "`PyConfig.base_executable`." msgstr "" -#: ../../c-api/init_config.rst:1589 -msgid "Py_RunMain()" -msgstr "Py_RunMain()" - -#: ../../c-api/init_config.rst:1593 -msgid "" -"Execute the command (:c:member:`PyConfig.run_command`), the script (:c:" -"member:`PyConfig.run_filename`) or the module (:c:member:`PyConfig." -"run_module`) specified on the command line or in the configuration." -msgstr "" - -#: ../../c-api/init_config.rst:1598 -msgid "By default and when if :option:`-i` option is used, run the REPL." -msgstr "" - -#: ../../c-api/init_config.rst:1600 -msgid "" -"Finally, finalizes Python and returns an exit status that can be passed to " -"the ``exit()`` function." -msgstr "" - -#: ../../c-api/init_config.rst:1603 -msgid "" -"See :ref:`Python Configuration ` for an example of " -"customized Python always running in isolated mode using :c:func:`Py_RunMain`." -msgstr "" - -#: ../../c-api/init_config.rst:1609 +#: ../../c-api/init_config.rst:1588 msgid "Py_GetArgcArgv()" msgstr "Py_GetArgcArgv()" -#: ../../c-api/init_config.rst:1613 +#: ../../c-api/init_config.rst:1592 msgid "Get the original command line arguments, before Python modified them." msgstr "" -#: ../../c-api/init_config.rst:1615 +#: ../../c-api/init_config.rst:1594 msgid "See also :c:member:`PyConfig.orig_argv` member." msgstr "" -#: ../../c-api/init_config.rst:1619 +#: ../../c-api/init_config.rst:1598 msgid "Multi-Phase Initialization Private Provisional API" msgstr "" -#: ../../c-api/init_config.rst:1621 +#: ../../c-api/init_config.rst:1600 msgid "" "This section is a private provisional API introducing multi-phase " "initialization, the core feature of :pep:`432`:" msgstr "" -#: ../../c-api/init_config.rst:1624 +#: ../../c-api/init_config.rst:1603 msgid "\"Core\" initialization phase, \"bare minimum Python\":" msgstr "" -#: ../../c-api/init_config.rst:1626 +#: ../../c-api/init_config.rst:1605 msgid "Builtin types;" msgstr "" -#: ../../c-api/init_config.rst:1627 +#: ../../c-api/init_config.rst:1606 msgid "Builtin exceptions;" msgstr "" -#: ../../c-api/init_config.rst:1628 +#: ../../c-api/init_config.rst:1607 msgid "Builtin and frozen modules;" msgstr "" -#: ../../c-api/init_config.rst:1629 +#: ../../c-api/init_config.rst:1608 msgid "" "The :mod:`sys` module is only partially initialized (ex: :data:`sys.path` " "doesn't exist yet)." msgstr "" -#: ../../c-api/init_config.rst:1632 +#: ../../c-api/init_config.rst:1611 msgid "\"Main\" initialization phase, Python is fully initialized:" msgstr "" -#: ../../c-api/init_config.rst:1634 +#: ../../c-api/init_config.rst:1613 msgid "Install and configure :mod:`importlib`;" msgstr "" -#: ../../c-api/init_config.rst:1635 +#: ../../c-api/init_config.rst:1614 msgid "Apply the :ref:`Path Configuration `;" msgstr "" -#: ../../c-api/init_config.rst:1636 +#: ../../c-api/init_config.rst:1615 msgid "Install signal handlers;" msgstr "" -#: ../../c-api/init_config.rst:1637 +#: ../../c-api/init_config.rst:1616 msgid "" "Finish :mod:`sys` module initialization (ex: create :data:`sys.stdout` and :" "data:`sys.path`);" msgstr "" -#: ../../c-api/init_config.rst:1639 +#: ../../c-api/init_config.rst:1618 msgid "" "Enable optional features like :mod:`faulthandler` and :mod:`tracemalloc`;" msgstr "" -#: ../../c-api/init_config.rst:1640 +#: ../../c-api/init_config.rst:1619 msgid "Import the :mod:`site` module;" msgstr "" -#: ../../c-api/init_config.rst:1641 +#: ../../c-api/init_config.rst:1620 msgid "etc." msgstr "etc." -#: ../../c-api/init_config.rst:1643 +#: ../../c-api/init_config.rst:1622 msgid "Private provisional API:" msgstr "" -#: ../../c-api/init_config.rst:1645 +#: ../../c-api/init_config.rst:1624 msgid "" ":c:member:`PyConfig._init_main`: if set to ``0``, :c:func:" "`Py_InitializeFromConfig` stops at the \"Core\" initialization phase." msgstr "" -#: ../../c-api/init_config.rst:1650 +#: ../../c-api/init_config.rst:1629 msgid "" "Move to the \"Main\" initialization phase, finish the Python initialization." msgstr "" -#: ../../c-api/init_config.rst:1652 +#: ../../c-api/init_config.rst:1631 msgid "" "No module is imported during the \"Core\" phase and the ``importlib`` module " "is not configured: the :ref:`Path Configuration ` is only " @@ -2287,14 +2412,14 @@ msgid "" "maybe install a custom :data:`sys.meta_path` importer or an import hook, etc." msgstr "" -#: ../../c-api/init_config.rst:1658 +#: ../../c-api/init_config.rst:1637 msgid "" "It may become possible to calculate the :ref:`Path Configuration ` in Python, after the Core phase and before the Main phase, which is " "one of the :pep:`432` motivation." msgstr "" -#: ../../c-api/init_config.rst:1662 +#: ../../c-api/init_config.rst:1641 msgid "" "The \"Core\" phase is not properly defined: what should be and what should " "not be available at this phase is not specified yet. The API is marked as " @@ -2302,12 +2427,49 @@ msgid "" "until a proper public API is designed." msgstr "" -#: ../../c-api/init_config.rst:1667 +#: ../../c-api/init_config.rst:1646 msgid "" "Example running Python code between \"Core\" and \"Main\" initialization " "phases::" msgstr "" +#: ../../c-api/init_config.rst:1649 +msgid "" +"void init_python(void)\n" +"{\n" +" PyStatus status;\n" +"\n" +" PyConfig config;\n" +" PyConfig_InitPythonConfig(&config);\n" +" config._init_main = 0;\n" +"\n" +" /* ... customize 'config' configuration ... */\n" +"\n" +" status = Py_InitializeFromConfig(&config);\n" +" PyConfig_Clear(&config);\n" +" if (PyStatus_Exception(status)) {\n" +" Py_ExitStatusException(status);\n" +" }\n" +"\n" +" /* Use sys.stderr because sys.stdout is only created\n" +" by _Py_InitializeMain() */\n" +" int res = PyRun_SimpleString(\n" +" \"import sys; \"\n" +" \"print('Run Python code before _Py_InitializeMain', \"\n" +" \"file=sys.stderr)\");\n" +" if (res < 0) {\n" +" exit(1);\n" +" }\n" +"\n" +" /* ... put more configuration code here ... */\n" +"\n" +" status = _Py_InitializeMain();\n" +" if (PyStatus_Exception(status)) {\n" +" Py_ExitStatusException(status);\n" +" }\n" +"}" +msgstr "" + #: ../../c-api/init_config.rst:558 msgid "main()" msgstr "" diff --git a/c-api/intro.po b/c-api/intro.po index 4d743a8f7..843c197b6 100644 --- a/c-api/intro.po +++ b/c-api/intro.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Ruan Aragão , 2021 -# Leticia Portella , 2021 -# Italo Penaforte , 2021 -# felipe caridade fernandes , 2021 -# Marco Rougeth , 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-05 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-04-25 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -115,6 +109,14 @@ msgstr "" "Todas as definições de função, tipo e macro necessárias para usar a API " "Python/C estão incluídas em seu código pela seguinte linha::" +#: ../../c-api/intro.rst:51 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include " +msgstr "" +"#define PY_SSIZE_T_CLEAN\n" +"#include " + #: ../../c-api/intro.rst:54 msgid "" "This implies inclusion of the following standard headers: ````, " @@ -255,6 +257,32 @@ msgstr "" "*name* é o nome do módulo, e deve ser o único item não-\\ ``static`` " "definido no arquivo do módulo. Exemplo::" +#: ../../c-api/intro.rst:119 +msgid "" +"static struct PyModuleDef spam_module = {\n" +" PyModuleDef_HEAD_INIT,\n" +" .m_name = \"spam\",\n" +" ...\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_spam(void)\n" +"{\n" +" return PyModule_Create(&spam_module);\n" +"}" +msgstr "" +"static struct PyModuleDef spam_module = {\n" +" PyModuleDef_HEAD_INIT,\n" +" .m_name = \"spam\",\n" +" ...\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_spam(void)\n" +"{\n" +" return PyModule_Create(&spam_module);\n" +"}" + #: ../../c-api/intro.rst:134 msgid "Return the absolute value of ``x``." msgstr "Retorna o valor absoluto de ``x``." @@ -262,10 +290,8 @@ msgstr "Retorna o valor absoluto de ``x``." #: ../../c-api/intro.rst:140 msgid "" "Ask the compiler to always inline a static inline function. The compiler can " -"ignore it and decides to not inline the function." +"ignore it and decide to not inline the function." msgstr "" -"Pede ao compilador para sempre embutir uma função em linha estática. O " -"compilador pode ignorá-lo e decide não inserir a função." #: ../../c-api/intro.rst:143 msgid "" @@ -303,6 +329,10 @@ msgstr "" msgid "It must be specified before the function return type. Usage::" msgstr "Deve ser especificado antes do tipo de retorno da função. Uso::" +#: ../../c-api/intro.rst:156 +msgid "static inline Py_ALWAYS_INLINE int random(void) { return 4; }" +msgstr "" + #: ../../c-api/intro.rst:162 msgid "" "Argument must be a character or an integer in the range [-128, 127] or [0, " @@ -325,6 +355,10 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" +#: ../../c-api/intro.rst:172 +msgid "Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);" +msgstr "Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);" + #: ../../c-api/intro.rst:174 msgid "MSVC support was added." msgstr "Suporte a MSVC foi adicionado." @@ -363,6 +397,10 @@ msgstr "" msgid "Usage::" msgstr "Uso::" +#: ../../c-api/intro.rst:208 +msgid "Py_NO_INLINE static int random(void) { return 4; }" +msgstr "" + #: ../../c-api/intro.rst:214 msgid "" "Convert ``x`` to a C string. E.g. ``Py_STRINGIFY(123)`` returns ``\"123\"``." @@ -441,6 +479,17 @@ msgstr "" "Use :c:macro:`PyDoc_STRVAR` para docstrings para ter suporte à compilação do " "Python sem docstrings, conforme especificado em :pep:`7`." +#: ../../c-api/intro.rst:258 +msgid "" +"PyDoc_STRVAR(pop_doc, \"Remove and return the rightmost element.\");\n" +"\n" +"static PyMethodDef deque_methods[] = {\n" +" // ...\n" +" {\"pop\", (PyCFunction)deque_pop, METH_NOARGS, pop_doc},\n" +" // ...\n" +"}" +msgstr "" + #: ../../c-api/intro.rst:268 msgid "" "Creates a docstring for the given input string or an empty string if " @@ -457,6 +506,15 @@ msgstr "" "Use :c:macro:`PyDoc_STR` ao especificar docstrings para ter suporte à " "compilação do Python sem docstrings, conforme especificado em :pep:`7`." +#: ../../c-api/intro.rst:276 +msgid "" +"static PyMethodDef pysqlite_row_methods[] = {\n" +" {\"keys\", (PyCFunction)pysqlite_row_keys, METH_NOARGS,\n" +" PyDoc_STR(\"Returns the keys of the row.\")},\n" +" {NULL, NULL}\n" +"};" +msgstr "" + #: ../../c-api/intro.rst:286 msgid "Objects, Types and Reference Counts" msgstr "Objetos, tipos e contagens de referências" @@ -638,6 +696,16 @@ msgstr "" "(esquecendo o tratamento de erros por enquanto; uma maneira melhor de " "codificar isso é mostrada abaixo)::" +#: ../../c-api/intro.rst:415 +msgid "" +"PyObject *t;\n" +"\n" +"t = PyTuple_New(3);\n" +"PyTuple_SetItem(t, 0, PyLong_FromLong(1L));\n" +"PyTuple_SetItem(t, 1, PyLong_FromLong(2L));\n" +"PyTuple_SetItem(t, 2, PyUnicode_FromString(\"three\"));" +msgstr "" + #: ../../c-api/intro.rst:422 msgid "" "Here, :c:func:`PyLong_FromLong` returns a new reference which is immediately " @@ -686,6 +754,14 @@ msgstr "" "código acima podem ser substituídos pelos seguintes (que também cuidam da " "verificação de erros)::" +#: ../../c-api/intro.rst:441 +msgid "" +"PyObject *tuple, *list;\n" +"\n" +"tuple = Py_BuildValue(\"(iis)\", 1, 2, \"three\");\n" +"list = Py_BuildValue(\"[iis]\", 1, 2, \"three\");" +msgstr "" + #: ../../c-api/intro.rst:446 msgid "" "It is much more common to use :c:func:`PyObject_SetItem` and friends with " @@ -697,6 +773,30 @@ msgid "" "sequence) to a given item::" msgstr "" +#: ../../c-api/intro.rst:453 +msgid "" +"int\n" +"set_all(PyObject *target, PyObject *item)\n" +"{\n" +" Py_ssize_t i, n;\n" +"\n" +" n = PyObject_Length(target);\n" +" if (n < 0)\n" +" return -1;\n" +" for (i = 0; i < n; i++) {\n" +" PyObject *index = PyLong_FromSsize_t(i);\n" +" if (!index)\n" +" return -1;\n" +" if (PyObject_SetItem(target, index, item) < 0) {\n" +" Py_DECREF(index);\n" +" return -1;\n" +" }\n" +" Py_DECREF(index);\n" +" }\n" +" return 0;\n" +"}" +msgstr "" + #: ../../c-api/intro.rst:476 msgid "" "The situation is slightly different for function return values. While " @@ -747,6 +847,62 @@ msgstr "" "soma dos itens em uma lista de inteiros; uma vez usando :c:func:" "`PyList_GetItem`, e uma vez usando :c:func:`PySequence_GetItem`. ::" +#: ../../c-api/intro.rst:501 +msgid "" +"long\n" +"sum_list(PyObject *list)\n" +"{\n" +" Py_ssize_t i, n;\n" +" long total = 0, value;\n" +" PyObject *item;\n" +"\n" +" n = PyList_Size(list);\n" +" if (n < 0)\n" +" return -1; /* Not a list */\n" +" for (i = 0; i < n; i++) {\n" +" item = PyList_GetItem(list, i); /* Can't fail */\n" +" if (!PyLong_Check(item)) continue; /* Skip non-integers */\n" +" value = PyLong_AsLong(item);\n" +" if (value == -1 && PyErr_Occurred())\n" +" /* Integer too big to fit in a C long, bail out */\n" +" return -1;\n" +" total += value;\n" +" }\n" +" return total;\n" +"}" +msgstr "" + +#: ../../c-api/intro.rst:527 +msgid "" +"long\n" +"sum_sequence(PyObject *sequence)\n" +"{\n" +" Py_ssize_t i, n;\n" +" long total = 0, value;\n" +" PyObject *item;\n" +" n = PySequence_Length(sequence);\n" +" if (n < 0)\n" +" return -1; /* Has no length */\n" +" for (i = 0; i < n; i++) {\n" +" item = PySequence_GetItem(sequence, i);\n" +" if (item == NULL)\n" +" return -1; /* Not a sequence, or other failure */\n" +" if (PyLong_Check(item)) {\n" +" value = PyLong_AsLong(item);\n" +" Py_DECREF(item);\n" +" if (value == -1 && PyErr_Occurred())\n" +" /* Integer too big to fit in a C long, bail out */\n" +" return -1;\n" +" total += value;\n" +" }\n" +" else {\n" +" Py_DECREF(item); /* Discard reference ownership */\n" +" }\n" +" }\n" +" return total;\n" +"}" +msgstr "" + #: ../../c-api/intro.rst:561 msgid "Types" msgstr "Tipos" @@ -862,13 +1018,13 @@ msgid "" msgstr "" "O estado de exceção completo consiste em três objetos (todos os quais podem " "ser ``NULL``): o tipo de exceção, o valor de exceção correspondente e o " -"traceback. Eles têm os mesmos significados que o resultado do Python de " +"traceback. Eles têm os mesmos significados que o resultado no Python de " "``sys.exc_info()``; no entanto, eles não são os mesmos: os objetos Python " "representam a última exceção sendo tratada por uma instrução Python :keyword:" "`try` ... :keyword:`except`, enquanto o estado de exceção de nível C só " "existe enquanto uma exceção está sendo transmitido entre funções C até " -"atingir o loop principal do interpretador de bytecode Python, que se " -"encarrega de transferi-lo para ``sys.exc_info()`` e amigos." +"atingir o laço de repetição principal do interpretador de bytecode Python, " +"que se encarrega de transferi-lo para ``sys.exc_info()`` e amigos." #: ../../c-api/intro.rst:629 msgid "" @@ -922,10 +1078,66 @@ msgid "" "why you like Python, we show the equivalent Python code::" msgstr "" +#: ../../c-api/intro.rst:655 +msgid "" +"def incr_item(dict, key):\n" +" try:\n" +" item = dict[key]\n" +" except KeyError:\n" +" item = 0\n" +" dict[key] = item + 1" +msgstr "" + #: ../../c-api/intro.rst:664 msgid "Here is the corresponding C code, in all its glory::" msgstr "Aqui está o código C correspondente, em toda sua glória::" +#: ../../c-api/intro.rst:666 +msgid "" +"int\n" +"incr_item(PyObject *dict, PyObject *key)\n" +"{\n" +" /* Objects all initialized to NULL for Py_XDECREF */\n" +" PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;\n" +" int rv = -1; /* Return value initialized to -1 (failure) */\n" +"\n" +" item = PyObject_GetItem(dict, key);\n" +" if (item == NULL) {\n" +" /* Handle KeyError only: */\n" +" if (!PyErr_ExceptionMatches(PyExc_KeyError))\n" +" goto error;\n" +"\n" +" /* Clear the error and use zero: */\n" +" PyErr_Clear();\n" +" item = PyLong_FromLong(0L);\n" +" if (item == NULL)\n" +" goto error;\n" +" }\n" +" const_one = PyLong_FromLong(1L);\n" +" if (const_one == NULL)\n" +" goto error;\n" +"\n" +" incremented_item = PyNumber_Add(item, const_one);\n" +" if (incremented_item == NULL)\n" +" goto error;\n" +"\n" +" if (PyObject_SetItem(dict, key, incremented_item) < 0)\n" +" goto error;\n" +" rv = 0; /* Success */\n" +" /* Continue with cleanup code */\n" +"\n" +" error:\n" +" /* Cleanup code, shared by success and failure path */\n" +"\n" +" /* Use Py_XDECREF() to ignore NULL references */\n" +" Py_XDECREF(item);\n" +" Py_XDECREF(const_one);\n" +" Py_XDECREF(incremented_item);\n" +"\n" +" return rv; /* -1 for error, 0 for success */\n" +"}" +msgstr "" + #: ../../c-api/intro.rst:716 msgid "" "This example represents an endorsed use of the ``goto`` statement in C! It " @@ -1200,7 +1412,7 @@ msgstr "" #: ../../c-api/intro.rst:627 msgid "exc_info (in module sys)" -msgstr "" +msgstr "exc_info (no módulo sys)" #: ../../c-api/intro.rst:662 ../../c-api/intro.rst:709 msgid "incr_item()" diff --git a/c-api/iter.po b/c-api/iter.po index a4f8785d6..d13adca04 100644 --- a/c-api/iter.po +++ b/c-api/iter.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Italo Penaforte , 2021 -# Rafael Fontenelle , 2022 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2022\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -71,6 +69,54 @@ msgstr "" "Para escrever um laço que itere sobre um iterador, o código C deve ser algo " "como isto::" +#: ../../c-api/iter.rst:33 +msgid "" +"PyObject *iterator = PyObject_GetIter(obj);\n" +"PyObject *item;\n" +"\n" +"if (iterator == NULL) {\n" +" /* propagate error */\n" +"}\n" +"\n" +"while ((item = PyIter_Next(iterator))) {\n" +" /* do something with item */\n" +" ...\n" +" /* release reference when done */\n" +" Py_DECREF(item);\n" +"}\n" +"\n" +"Py_DECREF(iterator);\n" +"\n" +"if (PyErr_Occurred()) {\n" +" /* propagate error */\n" +"}\n" +"else {\n" +" /* continue doing useful work */\n" +"}" +msgstr "" +"PyObject *iterator = PyObject_GetIter(obj);\n" +"PyObject *item;\n" +"\n" +"if (iterator == NULL) {\n" +" /* propaga o erro */\n" +"}\n" +"\n" +"while ((item = PyIter_Next(iterator))) {\n" +" /* faz algo com o item */\n" +" ...\n" +" /* liberar a referência quando concluído */\n" +" Py_DECREF(item);\n" +"}\n" +"\n" +"Py_DECREF(iterator);\n" +"\n" +"if (PyErr_Occurred()) {\n" +" /* propaga o erro */\n" +"}\n" +"else {\n" +" /* continua fazendo algum trabalho útil */\n" +"}" + #: ../../c-api/iter.rst:59 msgid "" "The enum value used to represent different results of :c:func:`PyIter_Send`." diff --git a/c-api/iterator.po b/c-api/iterator.po index e0c26f3c4..f68f313ec 100644 --- a/c-api/iterator.po +++ b/c-api/iterator.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Felipefpl, 2021 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/list.po b/c-api/list.po index 66f5bbba3..7899393e8 100644 --- a/c-api/list.po +++ b/c-api/list.po @@ -1,29 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Livia Cavalcanti , 2021 -# Marco Rougeth , 2023 -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/long.po b/c-api/long.po index 9fe52a8f4..bd57c5335 100644 --- a/c-api/long.po +++ b/c-api/long.po @@ -1,29 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Marco Rougeth , 2024 -# Claudio Rogerio Carvalho Filho , 2024 -# Welington Carlos , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -199,43 +195,54 @@ msgid "" "most-significant bit is not a sign bit. Flags other than endian are ignored." msgstr "" -#: ../../c-api/long.rst:149 ../../c-api/long.rst:175 +#: ../../c-api/long.rst:148 ../../c-api/long.rst:184 msgid "" "Return a C :c:expr:`long` representation of *obj*. If *obj* is not an " "instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` " "method (if present) to convert it to a :c:type:`PyLongObject`." msgstr "" -#: ../../c-api/long.rst:153 +#: ../../c-api/long.rst:152 msgid "" "Raise :exc:`OverflowError` if the value of *obj* is out of range for a :c:" "expr:`long`." msgstr "" -#: ../../c-api/long.rst:156 ../../c-api/long.rst:184 ../../c-api/long.rst:205 -#: ../../c-api/long.rst:225 ../../c-api/long.rst:248 +#: ../../c-api/long.rst:155 ../../c-api/long.rst:193 ../../c-api/long.rst:214 +#: ../../c-api/long.rst:234 ../../c-api/long.rst:257 msgid "Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate." msgstr "" "Retorna ``-1`` no caso de erro. Use :c:func:`PyErr_Occurred` para " "desambiguar." -#: ../../c-api/long.rst:158 ../../c-api/long.rst:186 ../../c-api/long.rst:207 -#: ../../c-api/long.rst:229 ../../c-api/long.rst:313 ../../c-api/long.rst:333 +#: ../../c-api/long.rst:157 ../../c-api/long.rst:195 ../../c-api/long.rst:216 +#: ../../c-api/long.rst:238 ../../c-api/long.rst:322 ../../c-api/long.rst:342 msgid "Use :meth:`~object.__index__` if available." msgstr "Usa :meth:`~object.__index__`, se disponível." -#: ../../c-api/long.rst:161 ../../c-api/long.rst:189 ../../c-api/long.rst:210 -#: ../../c-api/long.rst:232 ../../c-api/long.rst:316 ../../c-api/long.rst:336 +#: ../../c-api/long.rst:160 ../../c-api/long.rst:198 ../../c-api/long.rst:219 +#: ../../c-api/long.rst:241 ../../c-api/long.rst:325 ../../c-api/long.rst:345 msgid "This function will no longer use :meth:`~object.__int__`." msgstr "" #: ../../c-api/long.rst:167 msgid "" +"A :term:`soft deprecated` alias. Exactly equivalent to the preferred " +"``PyLong_AsLong``. In particular, it can fail with :exc:`OverflowError` or " +"another exception." +msgstr "" + +#: ../../c-api/long.rst:171 +msgid "The function is soft deprecated." +msgstr "" + +#: ../../c-api/long.rst:176 +msgid "" "Similar to :c:func:`PyLong_AsLong`, but store the result in a C :c:expr:" "`int` instead of a C :c:expr:`long`." msgstr "" -#: ../../c-api/long.rst:179 +#: ../../c-api/long.rst:188 msgid "" "If the value of *obj* is greater than :c:macro:`LONG_MAX` or less than :c:" "macro:`LONG_MIN`, set *\\*overflow* to ``1`` or ``-1``, respectively, and " @@ -243,20 +250,20 @@ msgid "" "exception occurs set *\\*overflow* to ``0`` and return ``-1`` as usual." msgstr "" -#: ../../c-api/long.rst:198 ../../c-api/long.rst:216 +#: ../../c-api/long.rst:207 ../../c-api/long.rst:225 msgid "" "Return a C :c:expr:`long long` representation of *obj*. If *obj* is not an " "instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` " "method (if present) to convert it to a :c:type:`PyLongObject`." msgstr "" -#: ../../c-api/long.rst:202 +#: ../../c-api/long.rst:211 msgid "" "Raise :exc:`OverflowError` if the value of *obj* is out of range for a :c:" "expr:`long long`." msgstr "" -#: ../../c-api/long.rst:220 +#: ../../c-api/long.rst:229 msgid "" "If the value of *obj* is greater than :c:macro:`LLONG_MAX` or less than :c:" "macro:`LLONG_MIN`, set *\\*overflow* to ``1`` or ``-1``, respectively, and " @@ -264,7 +271,7 @@ msgid "" "exception occurs set *\\*overflow* to ``0`` and return ``-1`` as usual." msgstr "" -#: ../../c-api/long.rst:242 +#: ../../c-api/long.rst:251 msgid "" "Return a C :c:type:`Py_ssize_t` representation of *pylong*. *pylong* must " "be an instance of :c:type:`PyLongObject`." @@ -272,7 +279,7 @@ msgstr "" "Retorna uma representação de :c:type:`Py_ssize_t` C de *pylong*. *pylong* " "deve ser uma instância de :c:type:`PyLongObject`." -#: ../../c-api/long.rst:245 +#: ../../c-api/long.rst:254 msgid "" "Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:" "type:`Py_ssize_t`." @@ -280,19 +287,19 @@ msgstr "" "Levanta :exc:`OverflowError` se o valor de *pylong* estiver fora do " "intervalo de um :c:type:`Py_ssize_t`." -#: ../../c-api/long.rst:257 +#: ../../c-api/long.rst:266 msgid "" "Return a C :c:expr:`unsigned long` representation of *pylong*. *pylong* " "must be an instance of :c:type:`PyLongObject`." msgstr "" -#: ../../c-api/long.rst:260 +#: ../../c-api/long.rst:269 msgid "" "Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:" "expr:`unsigned long`." msgstr "" -#: ../../c-api/long.rst:263 +#: ../../c-api/long.rst:272 msgid "" "Returns ``(unsigned long)-1`` on error. Use :c:func:`PyErr_Occurred` to " "disambiguate." @@ -300,7 +307,7 @@ msgstr "" "Retorna ``(unsigned long)-1`` no caso de erro. Use :c:func:`PyErr_Occurred` " "para desambiguar." -#: ../../c-api/long.rst:273 +#: ../../c-api/long.rst:282 msgid "" "Return a C :c:type:`size_t` representation of *pylong*. *pylong* must be an " "instance of :c:type:`PyLongObject`." @@ -308,7 +315,7 @@ msgstr "" "Retorna uma representação de :c:type:`size_t` C de *pylong*. *pylong* deve " "ser uma instância de :c:type:`PyLongObject`." -#: ../../c-api/long.rst:276 +#: ../../c-api/long.rst:285 msgid "" "Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:" "type:`size_t`." @@ -316,7 +323,7 @@ msgstr "" "Levanta :exc:`OverflowError` se o valor de *pylong* estiver fora do " "intervalo de um :c:type:`size_t`." -#: ../../c-api/long.rst:279 +#: ../../c-api/long.rst:288 msgid "" "Returns ``(size_t)-1`` on error. Use :c:func:`PyErr_Occurred` to " "disambiguate." @@ -324,19 +331,19 @@ msgstr "" "Retorna ``(size)-1`` no caso de erro. Use :c:func:`PyErr_Occurred` para " "desambiguar." -#: ../../c-api/long.rst:288 +#: ../../c-api/long.rst:297 msgid "" "Return a C :c:expr:`unsigned long long` representation of *pylong*. " "*pylong* must be an instance of :c:type:`PyLongObject`." msgstr "" -#: ../../c-api/long.rst:291 +#: ../../c-api/long.rst:300 msgid "" "Raise :exc:`OverflowError` if the value of *pylong* is out of range for an :" "c:expr:`unsigned long long`." msgstr "" -#: ../../c-api/long.rst:294 +#: ../../c-api/long.rst:303 msgid "" "Returns ``(unsigned long long)-1`` on error. Use :c:func:`PyErr_Occurred` to " "disambiguate." @@ -344,27 +351,27 @@ msgstr "" "Retorna ``(unsigned long long)-1`` no caso de erro. Use :c:func:" "`PyErr_Occurred` para desambiguar." -#: ../../c-api/long.rst:297 +#: ../../c-api/long.rst:306 msgid "" "A negative *pylong* now raises :exc:`OverflowError`, not :exc:`TypeError`." msgstr "" "Um *pylong* negativo agora levanta :exc:`OverflowError`, não :exc:" "`TypeError`." -#: ../../c-api/long.rst:303 +#: ../../c-api/long.rst:312 msgid "" "Return a C :c:expr:`unsigned long` representation of *obj*. If *obj* is not " "an instance of :c:type:`PyLongObject`, first call its :meth:`~object." "__index__` method (if present) to convert it to a :c:type:`PyLongObject`." msgstr "" -#: ../../c-api/long.rst:307 +#: ../../c-api/long.rst:316 msgid "" "If the value of *obj* is out of range for an :c:expr:`unsigned long`, return " "the reduction of that value modulo ``ULONG_MAX + 1``." msgstr "" -#: ../../c-api/long.rst:310 +#: ../../c-api/long.rst:319 msgid "" "Returns ``(unsigned long)-1`` on error. Use :c:func:`PyErr_Occurred` to " "disambiguate." @@ -372,20 +379,20 @@ msgstr "" "Retorna ``(unsigned long)-1`` no caso de erro. Use :c:func:`PyErr_Occurred` " "para desambiguar." -#: ../../c-api/long.rst:322 +#: ../../c-api/long.rst:331 msgid "" "Return a C :c:expr:`unsigned long long` representation of *obj*. If *obj* " "is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object." "__index__` method (if present) to convert it to a :c:type:`PyLongObject`." msgstr "" -#: ../../c-api/long.rst:327 +#: ../../c-api/long.rst:336 msgid "" "If the value of *obj* is out of range for an :c:expr:`unsigned long long`, " "return the reduction of that value modulo ``ULLONG_MAX + 1``." msgstr "" -#: ../../c-api/long.rst:330 +#: ../../c-api/long.rst:339 msgid "" "Returns ``(unsigned long long)-1`` on error. Use :c:func:`PyErr_Occurred` " "to disambiguate." @@ -393,26 +400,26 @@ msgstr "" "Retorna ``(unsigned long long)-1`` no caso de erro. Use :c:func:" "`PyErr_Occurred` para desambiguar." -#: ../../c-api/long.rst:342 +#: ../../c-api/long.rst:351 msgid "" "Return a C :c:expr:`double` representation of *pylong*. *pylong* must be an " "instance of :c:type:`PyLongObject`." msgstr "" -#: ../../c-api/long.rst:345 +#: ../../c-api/long.rst:354 msgid "" "Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:" "expr:`double`." msgstr "" -#: ../../c-api/long.rst:348 +#: ../../c-api/long.rst:357 msgid "" "Returns ``-1.0`` on error. Use :c:func:`PyErr_Occurred` to disambiguate." msgstr "" "Retorna ``-1.0`` no caso de erro. Use :c:func:`PyErr_Occurred` para " "desambiguar." -#: ../../c-api/long.rst:353 +#: ../../c-api/long.rst:362 msgid "" "Convert a Python integer *pylong* to a C :c:expr:`void` pointer. If *pylong* " "cannot be converted, an :exc:`OverflowError` will be raised. This is only " @@ -420,35 +427,35 @@ msgid "" "c:func:`PyLong_FromVoidPtr`." msgstr "" -#: ../../c-api/long.rst:358 +#: ../../c-api/long.rst:367 msgid "" "Returns ``NULL`` on error. Use :c:func:`PyErr_Occurred` to disambiguate." msgstr "" "Retorna ``NULL`` no caso de erro. Use :c:func:`PyErr_Occurred` para " "desambiguar." -#: ../../c-api/long.rst:363 +#: ../../c-api/long.rst:372 msgid "" "Copy the Python integer value *pylong* to a native *buffer* of size " "*n_bytes*. The *flags* can be set to ``-1`` to behave similarly to a C cast, " "or to values documented below to control the behavior." msgstr "" -#: ../../c-api/long.rst:367 +#: ../../c-api/long.rst:376 msgid "" "Returns ``-1`` with an exception raised on error. This may happen if " "*pylong* cannot be interpreted as an integer, or if *pylong* was negative " "and the ``Py_ASNATIVEBYTES_REJECT_NEGATIVE`` flag was set." msgstr "" -#: ../../c-api/long.rst:371 +#: ../../c-api/long.rst:380 msgid "" "Otherwise, returns the number of bytes required to store the value. If this " "is equal to or less than *n_bytes*, the entire value was copied. All " "*n_bytes* of the buffer are written: large buffers are padded with zeroes." msgstr "" -#: ../../c-api/long.rst:376 +#: ../../c-api/long.rst:385 msgid "" "If the returned value is greater than than *n_bytes*, the value was " "truncated: as many of the lowest bits of the value as could fit are written, " @@ -456,106 +463,154 @@ msgid "" "style downcast." msgstr "" -#: ../../c-api/long.rst:383 +#: ../../c-api/long.rst:392 msgid "" "Overflow is not considered an error. If the returned value is larger than " "*n_bytes*, most significant bits were discarded." msgstr "" -#: ../../c-api/long.rst:386 +#: ../../c-api/long.rst:395 msgid "``0`` will never be returned." msgstr "" -#: ../../c-api/long.rst:388 +#: ../../c-api/long.rst:397 msgid "Values are always copied as two's-complement." msgstr "" -#: ../../c-api/long.rst:390 +#: ../../c-api/long.rst:399 msgid "Usage example::" msgstr "" -#: ../../c-api/long.rst:406 +#: ../../c-api/long.rst:401 +msgid "" +"int32_t value;\n" +"Py_ssize_t bytes = PyLong_AsNativeBytes(pylong, &value, sizeof(value), -1);\n" +"if (bytes < 0) {\n" +" // Failed. A Python exception was set with the reason.\n" +" return NULL;\n" +"}\n" +"else if (bytes <= (Py_ssize_t)sizeof(value)) {\n" +" // Success!\n" +"}\n" +"else {\n" +" // Overflow occurred, but 'value' contains the truncated\n" +" // lowest bits of pylong.\n" +"}" +msgstr "" + +#: ../../c-api/long.rst:415 msgid "" "Passing zero to *n_bytes* will return the size of a buffer that would be " "large enough to hold the value. This may be larger than technically " "necessary, but not unreasonably so. If *n_bytes=0*, *buffer* may be ``NULL``." msgstr "" -#: ../../c-api/long.rst:413 +#: ../../c-api/long.rst:422 msgid "" "Passing *n_bytes=0* to this function is not an accurate way to determine the " "bit length of the value." msgstr "" -#: ../../c-api/long.rst:416 +#: ../../c-api/long.rst:425 msgid "" "To get at the entire Python value of an unknown size, the function can be " "called twice: first to determine the buffer size, then to fill it::" msgstr "" -#: ../../c-api/long.rst:447 +#: ../../c-api/long.rst:428 +msgid "" +"// Ask how much space we need.\n" +"Py_ssize_t expected = PyLong_AsNativeBytes(pylong, NULL, 0, -1);\n" +"if (expected < 0) {\n" +" // Failed. A Python exception was set with the reason.\n" +" return NULL;\n" +"}\n" +"assert(expected != 0); // Impossible per the API definition.\n" +"uint8_t *bignum = malloc(expected);\n" +"if (!bignum) {\n" +" PyErr_SetString(PyExc_MemoryError, \"bignum malloc failed.\");\n" +" return NULL;\n" +"}\n" +"// Safely get the entire value.\n" +"Py_ssize_t bytes = PyLong_AsNativeBytes(pylong, bignum, expected, -1);\n" +"if (bytes < 0) { // Exception has been set.\n" +" free(bignum);\n" +" return NULL;\n" +"}\n" +"else if (bytes > expected) { // This should not be possible.\n" +" PyErr_SetString(PyExc_RuntimeError,\n" +" \"Unexpected bignum truncation after a size check.\");\n" +" free(bignum);\n" +" return NULL;\n" +"}\n" +"// The expected success given the above pre-check.\n" +"// ... use bignum ...\n" +"free(bignum);" +msgstr "" + +#: ../../c-api/long.rst:456 msgid "" "*flags* is either ``-1`` (``Py_ASNATIVEBYTES_DEFAULTS``) to select defaults " -"that behave most like a C cast, or a combintation of the other flags in the " +"that behave most like a C cast, or a combination of the other flags in the " "table below. Note that ``-1`` cannot be combined with other flags." msgstr "" -#: ../../c-api/long.rst:452 +#: ../../c-api/long.rst:461 msgid "" "Currently, ``-1`` corresponds to ``Py_ASNATIVEBYTES_NATIVE_ENDIAN | " "Py_ASNATIVEBYTES_UNSIGNED_BUFFER``." msgstr "" -#: ../../c-api/long.rst:456 +#: ../../c-api/long.rst:467 msgid "Flag" msgstr "Sinalizador" -#: ../../c-api/long.rst:456 +#: ../../c-api/long.rst:467 msgid "Value" msgstr "Valor" -#: ../../c-api/long.rst:458 +#: ../../c-api/long.rst:469 msgid "``-1``" msgstr "" -#: ../../c-api/long.rst:459 +#: ../../c-api/long.rst:470 msgid "``0``" msgstr "``0``" -#: ../../c-api/long.rst:460 +#: ../../c-api/long.rst:471 msgid "``1``" msgstr "``1``" -#: ../../c-api/long.rst:461 +#: ../../c-api/long.rst:472 msgid "``3``" msgstr "``3``" -#: ../../c-api/long.rst:462 +#: ../../c-api/long.rst:473 msgid "``4``" msgstr "``4``" -#: ../../c-api/long.rst:463 +#: ../../c-api/long.rst:474 msgid "``8``" msgstr "``8``" -#: ../../c-api/long.rst:464 +#: ../../c-api/long.rst:475 msgid "``16``" msgstr "" -#: ../../c-api/long.rst:467 +#: ../../c-api/long.rst:478 msgid "" "Specifying ``Py_ASNATIVEBYTES_NATIVE_ENDIAN`` will override any other endian " "flags. Passing ``2`` is reserved." msgstr "" -#: ../../c-api/long.rst:470 +#: ../../c-api/long.rst:481 msgid "" "By default, sufficient buffer will be requested to include a sign bit. For " "example, when converting 128 with *n_bytes=1*, the function will return 2 " "(or more) in order to store a zero sign bit." msgstr "" -#: ../../c-api/long.rst:474 +#: ../../c-api/long.rst:485 msgid "" "If ``Py_ASNATIVEBYTES_UNSIGNED_BUFFER`` is specified, a zero sign bit will " "be omitted from size calculations. This allows, for example, 128 to fit in a " @@ -565,7 +620,7 @@ msgid "" "requested." msgstr "" -#: ../../c-api/long.rst:481 +#: ../../c-api/long.rst:492 msgid "" "Specifying ``Py_ASNATIVEBYTES_REJECT_NEGATIVE`` causes an exception to be " "set if *pylong* is negative. Without this flag, negative values will be " @@ -573,7 +628,7 @@ msgid "" "of whether ``Py_ASNATIVEBYTES_UNSIGNED_BUFFER`` was specified." msgstr "" -#: ../../c-api/long.rst:486 +#: ../../c-api/long.rst:497 msgid "" "If ``Py_ASNATIVEBYTES_ALLOW_INDEX`` is specified and a non-integer value is " "passed, its :meth:`~object.__index__` method will be called first. This may " @@ -583,7 +638,7 @@ msgid "" "`TypeError`." msgstr "" -#: ../../c-api/long.rst:495 +#: ../../c-api/long.rst:506 msgid "" "With the default *flags* (``-1``, or *UNSIGNED_BUFFER* without " "*REJECT_NEGATIVE*), multiple Python integers can map to a single value " @@ -591,22 +646,22 @@ msgid "" "buffer and set all its bits. This matches typical C cast behavior." msgstr "" -#: ../../c-api/long.rst:506 +#: ../../c-api/long.rst:517 msgid "" "On success, return a read only :term:`named tuple`, that holds information " "about Python's internal representation of integers. See :data:`sys.int_info` " "for description of individual fields." msgstr "" -#: ../../c-api/long.rst:510 +#: ../../c-api/long.rst:521 msgid "On failure, return ``NULL`` with an exception set." msgstr "Em caso de falha, retorna ``NULL`` com uma exceção definida." -#: ../../c-api/long.rst:517 +#: ../../c-api/long.rst:528 msgid "Return 1 if *op* is compact, 0 otherwise." msgstr "" -#: ../../c-api/long.rst:519 +#: ../../c-api/long.rst:530 msgid "" "This function makes it possible for performance-critical code to implement a " "“fast path” for small integers. For compact values use :c:func:" @@ -614,23 +669,23 @@ msgid "" "`PyLong_As* ` function or :c:func:`PyLong_AsNativeBytes`." msgstr "" -#: ../../c-api/long.rst:525 +#: ../../c-api/long.rst:536 msgid "The speedup is expected to be negligible for most users." msgstr "" -#: ../../c-api/long.rst:527 +#: ../../c-api/long.rst:538 msgid "" "Exactly what values are considered compact is an implementation detail and " "is subject to change." msgstr "" -#: ../../c-api/long.rst:532 +#: ../../c-api/long.rst:546 msgid "" "If *op* is compact, as determined by :c:func:`PyUnstable_Long_IsCompact`, " "return its value." msgstr "" -#: ../../c-api/long.rst:535 +#: ../../c-api/long.rst:549 msgid "Otherwise, the return value is undefined." msgstr "" @@ -646,23 +701,23 @@ msgstr "" msgid "integer" msgstr "inteiro" -#: ../../c-api/long.rst:145 +#: ../../c-api/long.rst:144 msgid "LONG_MAX (C macro)" msgstr "" -#: ../../c-api/long.rst:145 ../../c-api/long.rst:195 ../../c-api/long.rst:238 -#: ../../c-api/long.rst:253 ../../c-api/long.rst:269 ../../c-api/long.rst:285 +#: ../../c-api/long.rst:144 ../../c-api/long.rst:204 ../../c-api/long.rst:247 +#: ../../c-api/long.rst:262 ../../c-api/long.rst:278 ../../c-api/long.rst:294 msgid "OverflowError (built-in exception)" msgstr "" -#: ../../c-api/long.rst:238 +#: ../../c-api/long.rst:247 msgid "PY_SSIZE_T_MAX (C macro)" msgstr "" -#: ../../c-api/long.rst:253 +#: ../../c-api/long.rst:262 msgid "ULONG_MAX (C macro)" msgstr "" -#: ../../c-api/long.rst:269 +#: ../../c-api/long.rst:278 msgid "SIZE_MAX (C macro)" msgstr "" diff --git a/c-api/mapping.po b/c-api/mapping.po index f6c29fcdd..75664db23 100644 --- a/c-api/mapping.po +++ b/c-api/mapping.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/marshal.po b/c-api/marshal.po index 48ff06ffb..70732fb9e 100644 --- a/c-api/marshal.po +++ b/c-api/marshal.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/memory.po b/c-api/memory.po index 6110fa5b4..45e18afe7 100644 --- a/c-api/memory.po +++ b/c-api/memory.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Raphael Mendonça, 2021 -# Marco Rougeth , 2021 -# Welington Carlos , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Rodrigo Cândido, 2022 -# Vitor Buxbaum Orlandi, 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 02:33+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Vitor Buxbaum Orlandi, 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -82,6 +76,19 @@ msgid "" "in the following example::" msgstr "" +#: ../../c-api/memory.rst:58 +msgid "" +"PyObject *res;\n" +"char *buf = (char *) malloc(BUFSIZ); /* for I/O */\n" +"\n" +"if (buf == NULL)\n" +" return PyErr_NoMemory();\n" +"...Do some I/O operation involving buf...\n" +"res = PyBytes_FromString(buf);\n" +"free(buf); /* malloc'ed */\n" +"return res;" +msgstr "" + #: ../../c-api/memory.rst:68 msgid "" "In this example, the memory request for the I/O buffer is handled by the C " @@ -132,59 +139,70 @@ msgid "" "details on how every domain allocates memory or what internal functions each " "domain calls is considered an implementation detail, but for debugging " "purposes a simplified table can be found at :ref:`here `. There is no hard requirement to use the memory returned by the " -"allocation functions belonging to a given domain for only the purposes " -"hinted by that domain (although this is the recommended practice). For " -"example, one could use the memory returned by :c:func:`PyMem_RawMalloc` for " -"allocating Python objects or the memory returned by :c:func:" -"`PyObject_Malloc` for allocating memory for buffers." +"allocators>`. The APIs used to allocate and free a block of memory must be " +"from the same domain. For example, :c:func:`PyMem_Free` must be used to free " +"memory allocated using :c:func:`PyMem_Malloc`." msgstr "" -#: ../../c-api/memory.rst:112 +#: ../../c-api/memory.rst:109 msgid "The three allocation domains are:" msgstr "" -#: ../../c-api/memory.rst:114 +#: ../../c-api/memory.rst:111 msgid "" "Raw domain: intended for allocating memory for general-purpose memory " "buffers where the allocation *must* go to the system allocator or where the " "allocator can operate without the :term:`GIL`. The memory is requested " -"directly to the system." +"directly from the system. See :ref:`Raw Memory Interface `." msgstr "" -#: ../../c-api/memory.rst:119 +#: ../../c-api/memory.rst:116 msgid "" "\"Mem\" domain: intended for allocating memory for Python buffers and " "general-purpose memory buffers where the allocation must be performed with " -"the :term:`GIL` held. The memory is taken from the Python private heap." +"the :term:`GIL` held. The memory is taken from the Python private heap. See :" +"ref:`Memory Interface `." msgstr "" -#: ../../c-api/memory.rst:123 +#: ../../c-api/memory.rst:121 msgid "" -"Object domain: intended for allocating memory belonging to Python objects. " -"The memory is taken from the Python private heap." +"Object domain: intended for allocating memory for Python objects. The memory " +"is taken from the Python private heap. See :ref:`Object allocators " +"`." msgstr "" #: ../../c-api/memory.rst:126 msgid "" -"When freeing memory previously allocated by the allocating functions " -"belonging to a given domain,the matching specific deallocating functions " -"must be used. For example, :c:func:`PyMem_Free` must be used to free memory " -"allocated using :c:func:`PyMem_Malloc`." +"The :term:`free-threaded ` build requires that only Python " +"objects are allocated using the \"object\" domain and that all Python " +"objects are allocated using that domain. This differs from the prior Python " +"versions, where this was only a best practice and not a hard requirement." msgstr "" -#: ../../c-api/memory.rst:131 -msgid "Raw Memory Interface" +#: ../../c-api/memory.rst:130 +msgid "" +"For example, buffers (non-Python objects) should be allocated using :c:func:" +"`PyMem_Malloc`, :c:func:`PyMem_RawMalloc`, or :c:func:`malloc`, but not :c:" +"func:`PyObject_Malloc`." msgstr "" #: ../../c-api/memory.rst:133 +msgid "See :ref:`Memory Allocation APIs `." +msgstr "" + +#: ../../c-api/memory.rst:139 +msgid "Raw Memory Interface" +msgstr "" + +#: ../../c-api/memory.rst:141 msgid "" "The following function sets are wrappers to the system allocator. These " "functions are thread-safe, the :term:`GIL ` does " "not need to be held." msgstr "" -#: ../../c-api/memory.rst:137 +#: ../../c-api/memory.rst:145 msgid "" "The :ref:`default raw memory allocator ` uses the " "following functions: :c:func:`malloc`, :c:func:`calloc`, :c:func:`realloc` " @@ -192,63 +210,63 @@ msgid "" "requesting zero bytes." msgstr "" -#: ../../c-api/memory.rst:146 ../../c-api/memory.rst:217 -#: ../../c-api/memory.rst:325 +#: ../../c-api/memory.rst:154 ../../c-api/memory.rst:225 +#: ../../c-api/memory.rst:335 msgid "" "Allocates *n* bytes and returns a pointer of type :c:expr:`void*` to the " "allocated memory, or ``NULL`` if the request fails." msgstr "" -#: ../../c-api/memory.rst:149 +#: ../../c-api/memory.rst:157 msgid "" "Requesting zero bytes returns a distinct non-``NULL`` pointer if possible, " "as if ``PyMem_RawMalloc(1)`` had been called instead. The memory will not " "have been initialized in any way." msgstr "" -#: ../../c-api/memory.rst:156 ../../c-api/memory.rst:227 -#: ../../c-api/memory.rst:335 +#: ../../c-api/memory.rst:164 ../../c-api/memory.rst:235 +#: ../../c-api/memory.rst:345 msgid "" "Allocates *nelem* elements each whose size in bytes is *elsize* and returns " "a pointer of type :c:expr:`void*` to the allocated memory, or ``NULL`` if " "the request fails. The memory is initialized to zeros." msgstr "" -#: ../../c-api/memory.rst:160 +#: ../../c-api/memory.rst:168 msgid "" "Requesting zero elements or elements of size zero bytes returns a distinct " "non-``NULL`` pointer if possible, as if ``PyMem_RawCalloc(1, 1)`` had been " "called instead." msgstr "" -#: ../../c-api/memory.rst:169 ../../c-api/memory.rst:240 -#: ../../c-api/memory.rst:348 +#: ../../c-api/memory.rst:177 ../../c-api/memory.rst:248 +#: ../../c-api/memory.rst:358 msgid "" "Resizes the memory block pointed to by *p* to *n* bytes. The contents will " "be unchanged to the minimum of the old and the new sizes." msgstr "" -#: ../../c-api/memory.rst:172 +#: ../../c-api/memory.rst:180 msgid "" "If *p* is ``NULL``, the call is equivalent to ``PyMem_RawMalloc(n)``; else " "if *n* is equal to zero, the memory block is resized but is not freed, and " "the returned pointer is non-``NULL``." msgstr "" -#: ../../c-api/memory.rst:176 +#: ../../c-api/memory.rst:184 msgid "" "Unless *p* is ``NULL``, it must have been returned by a previous call to :c:" "func:`PyMem_RawMalloc`, :c:func:`PyMem_RawRealloc` or :c:func:" "`PyMem_RawCalloc`." msgstr "" -#: ../../c-api/memory.rst:180 +#: ../../c-api/memory.rst:188 msgid "" "If the request fails, :c:func:`PyMem_RawRealloc` returns ``NULL`` and *p* " "remains a valid pointer to the previous memory area." msgstr "" -#: ../../c-api/memory.rst:186 +#: ../../c-api/memory.rst:194 msgid "" "Frees the memory block pointed to by *p*, which must have been returned by a " "previous call to :c:func:`PyMem_RawMalloc`, :c:func:`PyMem_RawRealloc` or :c:" @@ -256,73 +274,73 @@ msgid "" "called before, undefined behavior occurs." msgstr "" -#: ../../c-api/memory.rst:191 ../../c-api/memory.rst:261 -#: ../../c-api/memory.rst:369 +#: ../../c-api/memory.rst:199 ../../c-api/memory.rst:269 +#: ../../c-api/memory.rst:379 msgid "If *p* is ``NULL``, no operation is performed." msgstr "" -#: ../../c-api/memory.rst:197 +#: ../../c-api/memory.rst:205 msgid "Memory Interface" msgstr "Interface da Memória" -#: ../../c-api/memory.rst:199 ../../c-api/memory.rst:305 +#: ../../c-api/memory.rst:207 ../../c-api/memory.rst:315 msgid "" "The following function sets, modeled after the ANSI C standard, but " "specifying behavior when requesting zero bytes, are available for allocating " "and releasing memory from the Python heap." msgstr "" -#: ../../c-api/memory.rst:203 +#: ../../c-api/memory.rst:211 msgid "" "The :ref:`default memory allocator ` uses the :" "ref:`pymalloc memory allocator `." msgstr "" -#: ../../c-api/memory.rst:208 ../../c-api/memory.rst:320 +#: ../../c-api/memory.rst:216 ../../c-api/memory.rst:330 msgid "" "The :term:`GIL ` must be held when using these " "functions." msgstr "" -#: ../../c-api/memory.rst:213 +#: ../../c-api/memory.rst:221 msgid "" "The default allocator is now pymalloc instead of system :c:func:`malloc`." msgstr "" -#: ../../c-api/memory.rst:220 +#: ../../c-api/memory.rst:228 msgid "" "Requesting zero bytes returns a distinct non-``NULL`` pointer if possible, " "as if ``PyMem_Malloc(1)`` had been called instead. The memory will not have " "been initialized in any way." msgstr "" -#: ../../c-api/memory.rst:231 +#: ../../c-api/memory.rst:239 msgid "" "Requesting zero elements or elements of size zero bytes returns a distinct " "non-``NULL`` pointer if possible, as if ``PyMem_Calloc(1, 1)`` had been " "called instead." msgstr "" -#: ../../c-api/memory.rst:243 +#: ../../c-api/memory.rst:251 msgid "" "If *p* is ``NULL``, the call is equivalent to ``PyMem_Malloc(n)``; else if " "*n* is equal to zero, the memory block is resized but is not freed, and the " "returned pointer is non-``NULL``." msgstr "" -#: ../../c-api/memory.rst:247 +#: ../../c-api/memory.rst:255 msgid "" "Unless *p* is ``NULL``, it must have been returned by a previous call to :c:" "func:`PyMem_Malloc`, :c:func:`PyMem_Realloc` or :c:func:`PyMem_Calloc`." msgstr "" -#: ../../c-api/memory.rst:250 +#: ../../c-api/memory.rst:258 msgid "" "If the request fails, :c:func:`PyMem_Realloc` returns ``NULL`` and *p* " "remains a valid pointer to the previous memory area." msgstr "" -#: ../../c-api/memory.rst:256 +#: ../../c-api/memory.rst:264 msgid "" "Frees the memory block pointed to by *p*, which must have been returned by a " "previous call to :c:func:`PyMem_Malloc`, :c:func:`PyMem_Realloc` or :c:func:" @@ -330,20 +348,20 @@ msgid "" "undefined behavior occurs." msgstr "" -#: ../../c-api/memory.rst:263 +#: ../../c-api/memory.rst:271 msgid "" "The following type-oriented macros are provided for convenience. Note that " "*TYPE* refers to any C type." msgstr "" -#: ../../c-api/memory.rst:269 +#: ../../c-api/memory.rst:277 msgid "" "Same as :c:func:`PyMem_Malloc`, but allocates ``(n * sizeof(TYPE))`` bytes " "of memory. Returns a pointer cast to ``TYPE*``. The memory will not have " "been initialized in any way." msgstr "" -#: ../../c-api/memory.rst:276 +#: ../../c-api/memory.rst:284 msgid "" "Same as :c:func:`PyMem_Realloc`, but the memory block is resized to ``(n * " "sizeof(TYPE))`` bytes. Returns a pointer cast to ``TYPE*``. On return, *p* " @@ -351,17 +369,17 @@ msgid "" "failure." msgstr "" -#: ../../c-api/memory.rst:281 +#: ../../c-api/memory.rst:289 msgid "" "This is a C preprocessor macro; *p* is always reassigned. Save the original " "value of *p* to avoid losing memory when handling errors." msgstr "" -#: ../../c-api/memory.rst:287 +#: ../../c-api/memory.rst:295 msgid "Same as :c:func:`PyMem_Free`." msgstr "" -#: ../../c-api/memory.rst:289 +#: ../../c-api/memory.rst:297 msgid "" "In addition, the following macro sets are provided for calling the Python " "memory allocator directly, without involving the C API functions listed " @@ -369,35 +387,35 @@ msgid "" "across Python versions and is therefore deprecated in extension modules." msgstr "" -#: ../../c-api/memory.rst:294 +#: ../../c-api/memory.rst:302 msgid "``PyMem_MALLOC(size)``" msgstr "``PyMem_MALLOC(size)``" -#: ../../c-api/memory.rst:295 +#: ../../c-api/memory.rst:303 msgid "``PyMem_NEW(type, size)``" msgstr "``PyMem_NEW(type, size)``" -#: ../../c-api/memory.rst:296 +#: ../../c-api/memory.rst:304 msgid "``PyMem_REALLOC(ptr, size)``" msgstr "``PyMem_REALLOC(ptr, size)``" -#: ../../c-api/memory.rst:297 +#: ../../c-api/memory.rst:305 msgid "``PyMem_RESIZE(ptr, type, size)``" msgstr "" -#: ../../c-api/memory.rst:298 +#: ../../c-api/memory.rst:306 msgid "``PyMem_FREE(ptr)``" msgstr "``PyMem_FREE(ptr)``" -#: ../../c-api/memory.rst:299 +#: ../../c-api/memory.rst:307 msgid "``PyMem_DEL(ptr)``" msgstr "``PyMem_DEL(ptr)``" -#: ../../c-api/memory.rst:303 +#: ../../c-api/memory.rst:313 msgid "Object allocators" msgstr "Alocadores de objeto" -#: ../../c-api/memory.rst:310 +#: ../../c-api/memory.rst:320 msgid "" "There is no guarantee that the memory returned by these allocators can be " "successfully cast to a Python object when intercepting the allocating " @@ -405,47 +423,47 @@ msgid "" "Memory Allocators ` section." msgstr "" -#: ../../c-api/memory.rst:315 +#: ../../c-api/memory.rst:325 msgid "" "The :ref:`default object allocator ` uses the :" "ref:`pymalloc memory allocator `." msgstr "" -#: ../../c-api/memory.rst:328 +#: ../../c-api/memory.rst:338 msgid "" "Requesting zero bytes returns a distinct non-``NULL`` pointer if possible, " "as if ``PyObject_Malloc(1)`` had been called instead. The memory will not " "have been initialized in any way." msgstr "" -#: ../../c-api/memory.rst:339 +#: ../../c-api/memory.rst:349 msgid "" "Requesting zero elements or elements of size zero bytes returns a distinct " "non-``NULL`` pointer if possible, as if ``PyObject_Calloc(1, 1)`` had been " "called instead." msgstr "" -#: ../../c-api/memory.rst:351 +#: ../../c-api/memory.rst:361 msgid "" "If *p* is ``NULL``, the call is equivalent to ``PyObject_Malloc(n)``; else " "if *n* is equal to zero, the memory block is resized but is not freed, and " "the returned pointer is non-``NULL``." msgstr "" -#: ../../c-api/memory.rst:355 +#: ../../c-api/memory.rst:365 msgid "" "Unless *p* is ``NULL``, it must have been returned by a previous call to :c:" "func:`PyObject_Malloc`, :c:func:`PyObject_Realloc` or :c:func:" "`PyObject_Calloc`." msgstr "" -#: ../../c-api/memory.rst:358 +#: ../../c-api/memory.rst:368 msgid "" "If the request fails, :c:func:`PyObject_Realloc` returns ``NULL`` and *p* " "remains a valid pointer to the previous memory area." msgstr "" -#: ../../c-api/memory.rst:364 +#: ../../c-api/memory.rst:374 msgid "" "Frees the memory block pointed to by *p*, which must have been returned by a " "previous call to :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc` or :c:" @@ -453,283 +471,283 @@ msgid "" "called before, undefined behavior occurs." msgstr "" -#: ../../c-api/memory.rst:375 +#: ../../c-api/memory.rst:385 msgid "Default Memory Allocators" msgstr "Alocadores de memória padrão" -#: ../../c-api/memory.rst:377 +#: ../../c-api/memory.rst:387 msgid "Default memory allocators:" msgstr "Alocadores de memória padrão:" -#: ../../c-api/memory.rst:380 +#: ../../c-api/memory.rst:390 msgid "Configuration" msgstr "Configuração" -#: ../../c-api/memory.rst:380 +#: ../../c-api/memory.rst:390 msgid "Name" msgstr "Nome" -#: ../../c-api/memory.rst:380 +#: ../../c-api/memory.rst:390 msgid "PyMem_RawMalloc" msgstr "PyMem_RawMalloc" -#: ../../c-api/memory.rst:380 +#: ../../c-api/memory.rst:390 msgid "PyMem_Malloc" msgstr "PyMem_Malloc" -#: ../../c-api/memory.rst:380 +#: ../../c-api/memory.rst:390 msgid "PyObject_Malloc" msgstr "PyObject_Malloc" -#: ../../c-api/memory.rst:382 +#: ../../c-api/memory.rst:392 msgid "Release build" msgstr "" -#: ../../c-api/memory.rst:382 +#: ../../c-api/memory.rst:392 msgid "``\"pymalloc\"``" msgstr "``\"pymalloc\"``" -#: ../../c-api/memory.rst:382 ../../c-api/memory.rst:384 +#: ../../c-api/memory.rst:392 ../../c-api/memory.rst:394 msgid "``malloc``" msgstr "``malloc``" -#: ../../c-api/memory.rst:382 +#: ../../c-api/memory.rst:392 msgid "``pymalloc``" msgstr "``pymalloc``" -#: ../../c-api/memory.rst:383 +#: ../../c-api/memory.rst:393 msgid "Debug build" msgstr "" -#: ../../c-api/memory.rst:383 +#: ../../c-api/memory.rst:393 msgid "``\"pymalloc_debug\"``" msgstr "``\"pymalloc_debug\"``" -#: ../../c-api/memory.rst:383 ../../c-api/memory.rst:385 +#: ../../c-api/memory.rst:393 ../../c-api/memory.rst:395 msgid "``malloc`` + debug" msgstr "" -#: ../../c-api/memory.rst:383 +#: ../../c-api/memory.rst:393 msgid "``pymalloc`` + debug" msgstr "" -#: ../../c-api/memory.rst:384 +#: ../../c-api/memory.rst:394 msgid "Release build, without pymalloc" msgstr "" -#: ../../c-api/memory.rst:384 +#: ../../c-api/memory.rst:394 msgid "``\"malloc\"``" msgstr "``\"malloc\"``" -#: ../../c-api/memory.rst:385 +#: ../../c-api/memory.rst:395 msgid "Debug build, without pymalloc" msgstr "" -#: ../../c-api/memory.rst:385 +#: ../../c-api/memory.rst:395 msgid "``\"malloc_debug\"``" msgstr "``\"malloc_debug\"``" -#: ../../c-api/memory.rst:388 +#: ../../c-api/memory.rst:398 msgid "Legend:" msgstr "" -#: ../../c-api/memory.rst:390 +#: ../../c-api/memory.rst:400 msgid "Name: value for :envvar:`PYTHONMALLOC` environment variable." msgstr "" -#: ../../c-api/memory.rst:391 +#: ../../c-api/memory.rst:401 msgid "" "``malloc``: system allocators from the standard C library, C functions: :c:" "func:`malloc`, :c:func:`calloc`, :c:func:`realloc` and :c:func:`free`." msgstr "" -#: ../../c-api/memory.rst:393 +#: ../../c-api/memory.rst:403 msgid "``pymalloc``: :ref:`pymalloc memory allocator `." msgstr "" -#: ../../c-api/memory.rst:394 +#: ../../c-api/memory.rst:404 msgid "" "``mimalloc``: :ref:`mimalloc memory allocator `. The pymalloc " "allocator will be used if mimalloc support isn't available." msgstr "" -#: ../../c-api/memory.rst:396 +#: ../../c-api/memory.rst:406 msgid "" "\"+ debug\": with :ref:`debug hooks on the Python memory allocators `." msgstr "" -#: ../../c-api/memory.rst:398 +#: ../../c-api/memory.rst:408 msgid "\"Debug build\": :ref:`Python build in debug mode `." msgstr "" -#: ../../c-api/memory.rst:403 +#: ../../c-api/memory.rst:413 msgid "Customize Memory Allocators" msgstr "Alocadores de memória" -#: ../../c-api/memory.rst:409 +#: ../../c-api/memory.rst:419 msgid "" "Structure used to describe a memory block allocator. The structure has the " "following fields:" msgstr "" -#: ../../c-api/memory.rst:413 ../../c-api/memory.rst:660 +#: ../../c-api/memory.rst:423 ../../c-api/memory.rst:670 msgid "Field" msgstr "Campo" -#: ../../c-api/memory.rst:413 ../../c-api/memory.rst:660 +#: ../../c-api/memory.rst:423 ../../c-api/memory.rst:670 msgid "Meaning" msgstr "Significado" -#: ../../c-api/memory.rst:415 ../../c-api/memory.rst:662 +#: ../../c-api/memory.rst:425 ../../c-api/memory.rst:672 msgid "``void *ctx``" msgstr "``void *ctx``" -#: ../../c-api/memory.rst:415 ../../c-api/memory.rst:662 +#: ../../c-api/memory.rst:425 ../../c-api/memory.rst:672 msgid "user context passed as first argument" msgstr "" -#: ../../c-api/memory.rst:417 +#: ../../c-api/memory.rst:427 msgid "``void* malloc(void *ctx, size_t size)``" msgstr "``void* malloc(void *ctx, size_t size)``" -#: ../../c-api/memory.rst:417 +#: ../../c-api/memory.rst:427 msgid "allocate a memory block" msgstr "" -#: ../../c-api/memory.rst:419 +#: ../../c-api/memory.rst:429 msgid "``void* calloc(void *ctx, size_t nelem, size_t elsize)``" msgstr "``void* calloc(void *ctx, size_t nelem, size_t elsize)``" -#: ../../c-api/memory.rst:419 +#: ../../c-api/memory.rst:429 msgid "allocate a memory block initialized with zeros" msgstr "" -#: ../../c-api/memory.rst:422 +#: ../../c-api/memory.rst:432 msgid "``void* realloc(void *ctx, void *ptr, size_t new_size)``" msgstr "``void* realloc(void *ctx, void *ptr, size_t new_size)``" -#: ../../c-api/memory.rst:422 +#: ../../c-api/memory.rst:432 msgid "allocate or resize a memory block" msgstr "" -#: ../../c-api/memory.rst:424 +#: ../../c-api/memory.rst:434 msgid "``void free(void *ctx, void *ptr)``" msgstr "``void free(void *ctx, void *ptr)``" -#: ../../c-api/memory.rst:424 +#: ../../c-api/memory.rst:434 msgid "free a memory block" msgstr "" -#: ../../c-api/memory.rst:427 +#: ../../c-api/memory.rst:437 msgid "" "The :c:type:`!PyMemAllocator` structure was renamed to :c:type:" "`PyMemAllocatorEx` and a new ``calloc`` field was added." msgstr "" -#: ../../c-api/memory.rst:434 +#: ../../c-api/memory.rst:444 msgid "Enum used to identify an allocator domain. Domains:" msgstr "" -#: ../../c-api/memory.rst:440 ../../c-api/memory.rst:449 -#: ../../c-api/memory.rst:458 +#: ../../c-api/memory.rst:450 ../../c-api/memory.rst:459 +#: ../../c-api/memory.rst:468 msgid "Functions:" msgstr "Funções:" -#: ../../c-api/memory.rst:442 +#: ../../c-api/memory.rst:452 msgid ":c:func:`PyMem_RawMalloc`" msgstr ":c:func:`PyMem_RawMalloc`" -#: ../../c-api/memory.rst:443 +#: ../../c-api/memory.rst:453 msgid ":c:func:`PyMem_RawRealloc`" msgstr ":c:func:`PyMem_RawRealloc`" -#: ../../c-api/memory.rst:444 +#: ../../c-api/memory.rst:454 msgid ":c:func:`PyMem_RawCalloc`" msgstr ":c:func:`PyMem_RawCalloc`" -#: ../../c-api/memory.rst:445 +#: ../../c-api/memory.rst:455 msgid ":c:func:`PyMem_RawFree`" msgstr ":c:func:`PyMem_RawFree`" -#: ../../c-api/memory.rst:451 +#: ../../c-api/memory.rst:461 msgid ":c:func:`PyMem_Malloc`," msgstr ":c:func:`PyMem_Malloc`," -#: ../../c-api/memory.rst:452 +#: ../../c-api/memory.rst:462 msgid ":c:func:`PyMem_Realloc`" msgstr ":c:func:`PyMem_Realloc`" -#: ../../c-api/memory.rst:453 +#: ../../c-api/memory.rst:463 msgid ":c:func:`PyMem_Calloc`" msgstr ":c:func:`PyMem_Calloc`" -#: ../../c-api/memory.rst:454 +#: ../../c-api/memory.rst:464 msgid ":c:func:`PyMem_Free`" msgstr ":c:func:`PyMem_Free`" -#: ../../c-api/memory.rst:460 +#: ../../c-api/memory.rst:470 msgid ":c:func:`PyObject_Malloc`" msgstr ":c:func:`PyObject_Malloc`" -#: ../../c-api/memory.rst:461 +#: ../../c-api/memory.rst:471 msgid ":c:func:`PyObject_Realloc`" msgstr ":c:func:`PyObject_Realloc`" -#: ../../c-api/memory.rst:462 +#: ../../c-api/memory.rst:472 msgid ":c:func:`PyObject_Calloc`" msgstr ":c:func:`PyObject_Calloc`" -#: ../../c-api/memory.rst:463 +#: ../../c-api/memory.rst:473 msgid ":c:func:`PyObject_Free`" msgstr ":c:func:`PyObject_Free`" -#: ../../c-api/memory.rst:467 +#: ../../c-api/memory.rst:477 msgid "Get the memory block allocator of the specified domain." msgstr "" -#: ../../c-api/memory.rst:472 +#: ../../c-api/memory.rst:482 msgid "Set the memory block allocator of the specified domain." msgstr "" -#: ../../c-api/memory.rst:474 +#: ../../c-api/memory.rst:484 msgid "" "The new allocator must return a distinct non-``NULL`` pointer when " "requesting zero bytes." msgstr "" -#: ../../c-api/memory.rst:477 +#: ../../c-api/memory.rst:487 msgid "" "For the :c:macro:`PYMEM_DOMAIN_RAW` domain, the allocator must be thread-" "safe: the :term:`GIL ` is not held when the " "allocator is called." msgstr "" -#: ../../c-api/memory.rst:481 +#: ../../c-api/memory.rst:491 msgid "" "For the remaining domains, the allocator must also be thread-safe: the " "allocator may be called in different interpreters that do not share a " "``GIL``." msgstr "" -#: ../../c-api/memory.rst:485 +#: ../../c-api/memory.rst:495 msgid "" "If the new allocator is not a hook (does not call the previous allocator), " "the :c:func:`PyMem_SetupDebugHooks` function must be called to reinstall the " "debug hooks on top on the new allocator." msgstr "" -#: ../../c-api/memory.rst:489 +#: ../../c-api/memory.rst:499 msgid "" "See also :c:member:`PyPreConfig.allocator` and :ref:`Preinitialize Python " "with PyPreConfig `." msgstr "" -#: ../../c-api/memory.rst:494 +#: ../../c-api/memory.rst:504 msgid ":c:func:`PyMem_SetAllocator` does have the following contract:" msgstr "" -#: ../../c-api/memory.rst:496 +#: ../../c-api/memory.rst:506 msgid "" "It can be called after :c:func:`Py_PreInitialize` and before :c:func:" "`Py_InitializeFromConfig` to install a custom memory allocator. There are no " @@ -739,7 +757,7 @@ msgid "" "domains>` for more information." msgstr "" -#: ../../c-api/memory.rst:504 +#: ../../c-api/memory.rst:514 msgid "" "If called after Python has finish initializing (after :c:func:" "`Py_InitializeFromConfig` has been called) the allocator **must** wrap the " @@ -747,21 +765,21 @@ msgid "" "arbitrary one is **not supported**." msgstr "" -#: ../../c-api/memory.rst:509 +#: ../../c-api/memory.rst:519 msgid "All allocators must be thread-safe." msgstr "" -#: ../../c-api/memory.rst:515 +#: ../../c-api/memory.rst:525 msgid "" "Setup :ref:`debug hooks in the Python memory allocators ` " "to detect memory errors." msgstr "" -#: ../../c-api/memory.rst:522 +#: ../../c-api/memory.rst:532 msgid "Debug hooks on the Python memory allocators" msgstr "" -#: ../../c-api/memory.rst:524 +#: ../../c-api/memory.rst:534 msgid "" "When :ref:`Python is built in debug mode `, the :c:func:" "`PyMem_SetupDebugHooks` function is called at the :ref:`Python " @@ -769,19 +787,19 @@ msgid "" "allocators to detect memory errors." msgstr "" -#: ../../c-api/memory.rst:529 +#: ../../c-api/memory.rst:539 msgid "" "The :envvar:`PYTHONMALLOC` environment variable can be used to install debug " "hooks on a Python compiled in release mode (ex: ``PYTHONMALLOC=debug``)." msgstr "" -#: ../../c-api/memory.rst:532 +#: ../../c-api/memory.rst:542 msgid "" "The :c:func:`PyMem_SetupDebugHooks` function can be used to set debug hooks " "after calling :c:func:`PyMem_SetAllocator`." msgstr "" -#: ../../c-api/memory.rst:535 +#: ../../c-api/memory.rst:545 msgid "" "These debug hooks fill dynamically allocated memory blocks with special, " "recognizable bit patterns. Newly allocated memory is filled with the byte " @@ -791,25 +809,25 @@ msgid "" "these bytes are unlikely to be valid addresses, floats, or ASCII strings." msgstr "" -#: ../../c-api/memory.rst:542 +#: ../../c-api/memory.rst:552 msgid "Runtime checks:" msgstr "Checagens em Tempo de Execução:" -#: ../../c-api/memory.rst:544 +#: ../../c-api/memory.rst:554 msgid "" "Detect API violations. For example, detect if :c:func:`PyObject_Free` is " "called on a memory block allocated by :c:func:`PyMem_Malloc`." msgstr "" -#: ../../c-api/memory.rst:546 +#: ../../c-api/memory.rst:556 msgid "Detect write before the start of the buffer (buffer underflow)." msgstr "" -#: ../../c-api/memory.rst:547 +#: ../../c-api/memory.rst:557 msgid "Detect write after the end of the buffer (buffer overflow)." msgstr "" -#: ../../c-api/memory.rst:548 +#: ../../c-api/memory.rst:558 msgid "" "Check that the :term:`GIL ` is held when allocator " "functions of :c:macro:`PYMEM_DOMAIN_OBJ` (ex: :c:func:`PyObject_Malloc`) " @@ -817,7 +835,7 @@ msgid "" "called." msgstr "" -#: ../../c-api/memory.rst:553 +#: ../../c-api/memory.rst:563 msgid "" "On error, the debug hooks use the :mod:`tracemalloc` module to get the " "traceback where a memory block was allocated. The traceback is only " @@ -825,7 +843,7 @@ msgid "" "memory block was traced." msgstr "" -#: ../../c-api/memory.rst:558 +#: ../../c-api/memory.rst:568 msgid "" "Let *S* = ``sizeof(size_t)``. ``2*S`` bytes are added at each end of each " "block of *N* bytes requested. The memory layout is like so, where p " @@ -835,49 +853,49 @@ msgid "" "from a Python slice):" msgstr "" -#: ../../c-api/memory.rst:564 +#: ../../c-api/memory.rst:574 msgid "``p[-2*S:-S]``" msgstr "``p[-2*S:-S]``" -#: ../../c-api/memory.rst:565 +#: ../../c-api/memory.rst:575 msgid "" "Number of bytes originally asked for. This is a size_t, big-endian (easier " "to read in a memory dump)." msgstr "" -#: ../../c-api/memory.rst:567 +#: ../../c-api/memory.rst:577 msgid "``p[-S]``" msgstr "``p[-S]``" -#: ../../c-api/memory.rst:568 +#: ../../c-api/memory.rst:578 msgid "API identifier (ASCII character):" msgstr "" -#: ../../c-api/memory.rst:570 +#: ../../c-api/memory.rst:580 msgid "``'r'`` for :c:macro:`PYMEM_DOMAIN_RAW`." msgstr "" -#: ../../c-api/memory.rst:571 +#: ../../c-api/memory.rst:581 msgid "``'m'`` for :c:macro:`PYMEM_DOMAIN_MEM`." msgstr "" -#: ../../c-api/memory.rst:572 +#: ../../c-api/memory.rst:582 msgid "``'o'`` for :c:macro:`PYMEM_DOMAIN_OBJ`." msgstr "" -#: ../../c-api/memory.rst:574 +#: ../../c-api/memory.rst:584 msgid "``p[-S+1:0]``" msgstr "``p[-S+1:0]``" -#: ../../c-api/memory.rst:575 +#: ../../c-api/memory.rst:585 msgid "Copies of PYMEM_FORBIDDENBYTE. Used to catch under- writes and reads." msgstr "" -#: ../../c-api/memory.rst:577 +#: ../../c-api/memory.rst:587 msgid "``p[0:N]``" msgstr "``p[0:N]``" -#: ../../c-api/memory.rst:578 +#: ../../c-api/memory.rst:588 msgid "" "The requested memory, filled with copies of PYMEM_CLEANBYTE, used to catch " "reference to uninitialized memory. When a realloc-like function is called " @@ -888,25 +906,25 @@ msgid "" "bytes are also filled with PYMEM_DEADBYTE." msgstr "" -#: ../../c-api/memory.rst:586 +#: ../../c-api/memory.rst:596 msgid "``p[N:N+S]``" msgstr "``p[N:N+S]``" -#: ../../c-api/memory.rst:587 +#: ../../c-api/memory.rst:597 msgid "Copies of PYMEM_FORBIDDENBYTE. Used to catch over- writes and reads." msgstr "" -#: ../../c-api/memory.rst:589 +#: ../../c-api/memory.rst:599 msgid "``p[N+S:N+2*S]``" msgstr "``p[N+S:N+2*S]``" -#: ../../c-api/memory.rst:590 +#: ../../c-api/memory.rst:600 msgid "" "Only used if the ``PYMEM_DEBUG_SERIALNO`` macro is defined (not defined by " "default)." msgstr "" -#: ../../c-api/memory.rst:593 +#: ../../c-api/memory.rst:603 msgid "" "A serial number, incremented by 1 on each call to a malloc-like or realloc-" "like function. Big-endian :c:type:`size_t`. If \"bad memory\" is detected " @@ -916,7 +934,7 @@ msgid "" "number is incremented, and exists so you can set such a breakpoint easily." msgstr "" -#: ../../c-api/memory.rst:600 +#: ../../c-api/memory.rst:610 msgid "" "A realloc-like or free-like function first checks that the " "PYMEM_FORBIDDENBYTE bytes at each end are intact. If they've been altered, " @@ -929,7 +947,7 @@ msgid "" "getting used)." msgstr "" -#: ../../c-api/memory.rst:609 +#: ../../c-api/memory.rst:619 msgid "" "The :c:func:`PyMem_SetupDebugHooks` function now also works on Python " "compiled in release mode. On error, the debug hooks now use :mod:" @@ -938,7 +956,7 @@ msgid "" "`PYMEM_DOMAIN_OBJ` and :c:macro:`PYMEM_DOMAIN_MEM` domains are called." msgstr "" -#: ../../c-api/memory.rst:617 +#: ../../c-api/memory.rst:627 msgid "" "Byte patterns ``0xCB`` (``PYMEM_CLEANBYTE``), ``0xDB`` (``PYMEM_DEADBYTE``) " "and ``0xFB`` (``PYMEM_FORBIDDENBYTE``) have been replaced with ``0xCD``, " @@ -946,11 +964,11 @@ msgid "" "``malloc()`` and ``free()``." msgstr "" -#: ../../c-api/memory.rst:627 +#: ../../c-api/memory.rst:637 msgid "The pymalloc allocator" msgstr "" -#: ../../c-api/memory.rst:629 +#: ../../c-api/memory.rst:639 msgid "" "Python has a *pymalloc* allocator optimized for small objects (smaller or " "equal to 512 bytes) with a short lifetime. It uses memory mappings called " @@ -959,75 +977,75 @@ msgid "" "`PyMem_RawRealloc` for allocations larger than 512 bytes." msgstr "" -#: ../../c-api/memory.rst:635 +#: ../../c-api/memory.rst:645 msgid "" "*pymalloc* is the :ref:`default allocator ` of " "the :c:macro:`PYMEM_DOMAIN_MEM` (ex: :c:func:`PyMem_Malloc`) and :c:macro:" "`PYMEM_DOMAIN_OBJ` (ex: :c:func:`PyObject_Malloc`) domains." msgstr "" -#: ../../c-api/memory.rst:639 +#: ../../c-api/memory.rst:649 msgid "The arena allocator uses the following functions:" msgstr "" -#: ../../c-api/memory.rst:641 +#: ../../c-api/memory.rst:651 msgid ":c:func:`!VirtualAlloc` and :c:func:`!VirtualFree` on Windows," msgstr "" -#: ../../c-api/memory.rst:642 +#: ../../c-api/memory.rst:652 msgid ":c:func:`!mmap` and :c:func:`!munmap` if available," msgstr "" -#: ../../c-api/memory.rst:643 +#: ../../c-api/memory.rst:653 msgid ":c:func:`malloc` and :c:func:`free` otherwise." msgstr ":c:func:`malloc` e :c:func:`free` do contrário." -#: ../../c-api/memory.rst:645 +#: ../../c-api/memory.rst:655 msgid "" "This allocator is disabled if Python is configured with the :option:`--" "without-pymalloc` option. It can also be disabled at runtime using the :" "envvar:`PYTHONMALLOC` environment variable (ex: ``PYTHONMALLOC=malloc``)." msgstr "" -#: ../../c-api/memory.rst:650 +#: ../../c-api/memory.rst:660 msgid "Customize pymalloc Arena Allocator" msgstr "" -#: ../../c-api/memory.rst:656 +#: ../../c-api/memory.rst:666 msgid "" "Structure used to describe an arena allocator. The structure has three " "fields:" msgstr "" -#: ../../c-api/memory.rst:664 +#: ../../c-api/memory.rst:674 msgid "``void* alloc(void *ctx, size_t size)``" msgstr "``void* alloc(void *ctx, size_t size)``" -#: ../../c-api/memory.rst:664 +#: ../../c-api/memory.rst:674 msgid "allocate an arena of size bytes" msgstr "" -#: ../../c-api/memory.rst:666 +#: ../../c-api/memory.rst:676 msgid "``void free(void *ctx, void *ptr, size_t size)``" msgstr "" -#: ../../c-api/memory.rst:666 +#: ../../c-api/memory.rst:676 msgid "free an arena" msgstr "" -#: ../../c-api/memory.rst:671 +#: ../../c-api/memory.rst:681 msgid "Get the arena allocator." msgstr "" -#: ../../c-api/memory.rst:675 +#: ../../c-api/memory.rst:685 msgid "Set the arena allocator." msgstr "" -#: ../../c-api/memory.rst:680 +#: ../../c-api/memory.rst:690 msgid "The mimalloc allocator" msgstr "" -#: ../../c-api/memory.rst:684 +#: ../../c-api/memory.rst:694 msgid "" "Python supports the mimalloc allocator when the underlying platform support " "is available. mimalloc \"is a general purpose allocator with excellent " @@ -1035,39 +1053,39 @@ msgid "" "runtime systems of the Koka and Lean languages.\"" msgstr "" -#: ../../c-api/memory.rst:689 +#: ../../c-api/memory.rst:699 msgid "tracemalloc C API" msgstr "" -#: ../../c-api/memory.rst:695 +#: ../../c-api/memory.rst:705 msgid "Track an allocated memory block in the :mod:`tracemalloc` module." msgstr "" -#: ../../c-api/memory.rst:697 +#: ../../c-api/memory.rst:707 msgid "" "Return ``0`` on success, return ``-1`` on error (failed to allocate memory " "to store the trace). Return ``-2`` if tracemalloc is disabled." msgstr "" -#: ../../c-api/memory.rst:700 +#: ../../c-api/memory.rst:710 msgid "If memory block is already tracked, update the existing trace." msgstr "" -#: ../../c-api/memory.rst:704 +#: ../../c-api/memory.rst:714 msgid "" "Untrack an allocated memory block in the :mod:`tracemalloc` module. Do " "nothing if the block was not tracked." msgstr "" -#: ../../c-api/memory.rst:707 +#: ../../c-api/memory.rst:717 msgid "Return ``-2`` if tracemalloc is disabled, otherwise return ``0``." msgstr "" -#: ../../c-api/memory.rst:713 +#: ../../c-api/memory.rst:723 msgid "Examples" msgstr "Exemplos" -#: ../../c-api/memory.rst:715 +#: ../../c-api/memory.rst:725 msgid "" "Here is the example from section :ref:`memoryoverview`, rewritten so that " "the I/O buffer is allocated from the Python heap by using the first function " @@ -1075,11 +1093,37 @@ msgid "" msgstr "" #: ../../c-api/memory.rst:728 +msgid "" +"PyObject *res;\n" +"char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */\n" +"\n" +"if (buf == NULL)\n" +" return PyErr_NoMemory();\n" +"/* ...Do some I/O operation involving buf... */\n" +"res = PyBytes_FromString(buf);\n" +"PyMem_Free(buf); /* allocated with PyMem_Malloc */\n" +"return res;" +msgstr "" + +#: ../../c-api/memory.rst:738 msgid "The same code using the type-oriented function set::" msgstr "" #: ../../c-api/memory.rst:740 msgid "" +"PyObject *res;\n" +"char *buf = PyMem_New(char, BUFSIZ); /* for I/O */\n" +"\n" +"if (buf == NULL)\n" +" return PyErr_NoMemory();\n" +"/* ...Do some I/O operation involving buf... */\n" +"res = PyBytes_FromString(buf);\n" +"PyMem_Del(buf); /* allocated with PyMem_New */\n" +"return res;" +msgstr "" + +#: ../../c-api/memory.rst:750 +msgid "" "Note that in the two examples above, the buffer is always manipulated via " "functions belonging to the same set. Indeed, it is required to use the same " "memory API family for a given memory block, so that the risk of mixing " @@ -1088,14 +1132,25 @@ msgid "" "different allocators operating on different heaps. ::" msgstr "" -#: ../../c-api/memory.rst:755 +#: ../../c-api/memory.rst:757 +msgid "" +"char *buf1 = PyMem_New(char, BUFSIZ);\n" +"char *buf2 = (char *) malloc(BUFSIZ);\n" +"char *buf3 = (char *) PyMem_Malloc(BUFSIZ);\n" +"...\n" +"PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */\n" +"free(buf2); /* Right -- allocated via malloc() */\n" +"free(buf1); /* Fatal -- should be PyMem_Del() */" +msgstr "" + +#: ../../c-api/memory.rst:765 msgid "" "In addition to the functions aimed at handling raw memory blocks from the " "Python heap, objects in Python are allocated and released with :c:macro:" "`PyObject_New`, :c:macro:`PyObject_NewVar` and :c:func:`PyObject_Del`." msgstr "" -#: ../../c-api/memory.rst:759 +#: ../../c-api/memory.rst:769 msgid "" "These will be explained in the next chapter on defining and implementing new " "object types in C." diff --git a/c-api/memoryview.po b/c-api/memoryview.po index 7e6e8a2ec..d605c36ba 100644 --- a/c-api/memoryview.po +++ b/c-api/memoryview.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/method.po b/c-api/method.po index 98672273e..04ddb49f7 100644 --- a/c-api/method.po +++ b/c-api/method.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Adorilson Bezerra , 2021 -# Cássio Nomura , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/module.po b/c-api/module.po index 5aab0786f..d149963b9 100644 --- a/c-api/module.po +++ b/c-api/module.po @@ -1,29 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 -# Rodrigo Cândido, 2022 -# Welliton Malta , 2023 -# Marco Rougeth , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-28 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -57,28 +53,32 @@ msgstr "" #: ../../c-api/module.rst:40 msgid "" -"Return a new module object with the :attr:`__name__` attribute set to " -"*name*. The module's :attr:`__name__`, :attr:`__doc__`, :attr:`__package__`, " -"and :attr:`__loader__` attributes are filled in (all but :attr:`__name__` " -"are set to ``None``); the caller is responsible for providing a :attr:" -"`__file__` attribute." +"Return a new module object with :attr:`module.__name__` set to *name*. The " +"module's :attr:`!__name__`, :attr:`~module.__doc__`, :attr:`~module." +"__package__` and :attr:`~module.__loader__` attributes are filled in (all " +"but :attr:`!__name__` are set to ``None``). The caller is responsible for " +"setting a :attr:`~module.__file__` attribute." msgstr "" -"Retorna um novo objeto de módulo com o atributo :attr:`__name__` definido " -"como *name*. Os atributos de módulo :attr:`__name__`, :attr:`__doc__`, :attr:" -"`__package__` e :attr:`__loader__` são preenchidos (todos exceto :attr:" -"`__name__` são definidos como ``None``); O chamador é responsásvel por " -"providenciar um atributo :attr:`__file__`." +"Retorna um novo objeto de módulo com :attr:`module.__name__` definido como " +"*name*. Os atributos :attr:`!__name__`, :attr:`~module.__doc__`, :attr:" +"`~module.__package__` e :attr:`~module.__loader__` do módulo são preenchidos " +"(todos, exceto :attr:`!__name__`, são definidos como ``None``). O chamador é " +"responsável por definir um atributo :attr:`~module.__file__`." -#: ../../c-api/module.rst:46 ../../c-api/module.rst:270 -#: ../../c-api/module.rst:470 +#: ../../c-api/module.rst:46 ../../c-api/module.rst:272 +#: ../../c-api/module.rst:474 msgid "Return ``NULL`` with an exception set on error." msgstr "Retorna ``NULL`` com uma exceção definida em caso de erro." #: ../../c-api/module.rst:50 -msgid ":attr:`__package__` and :attr:`__loader__` are set to ``None``." -msgstr ":attr:`__package__` e :attr:`__loader__` são definidos como ``None``." +msgid "" +":attr:`~module.__package__` and :attr:`~module.__loader__` are now set to " +"``None``." +msgstr "" +":attr:`~module.__package__` e :attr:`~module.__loader__` agora estão " +"definidos como ``None``." -#: ../../c-api/module.rst:56 +#: ../../c-api/module.rst:57 msgid "" "Similar to :c:func:`PyModule_NewObject`, but the name is a UTF-8 encoded " "string instead of a Unicode object." @@ -86,7 +86,7 @@ msgstr "" "Semelhante a :c:func:`PyModule_NewObject`, mas o nome é uma string " "codificada em UTF-8 em vez de um objeto Unicode." -#: ../../c-api/module.rst:64 +#: ../../c-api/module.rst:65 msgid "" "Return the dictionary object that implements *module*'s namespace; this " "object is the same as the :attr:`~object.__dict__` attribute of the module " @@ -98,7 +98,7 @@ msgstr "" "módulo. Se *module* não for um objeto de módulo (ou um subtipo de um objeto " "de módulo), :exc:`SystemError` é levantada e ``NULL`` é retornado." -#: ../../c-api/module.rst:69 +#: ../../c-api/module.rst:70 msgid "" "It is recommended extensions use other ``PyModule_*`` and ``PyObject_*`` " "functions rather than directly manipulate a module's :attr:`~object." @@ -108,17 +108,17 @@ msgstr "" "``PyObject_*`` em vez de manipular diretamente o :attr:`~object.__dict__` de " "um módulo." -#: ../../c-api/module.rst:80 +#: ../../c-api/module.rst:81 msgid "" -"Return *module*'s :attr:`__name__` value. If the module does not provide " -"one, or if it is not a string, :exc:`SystemError` is raised and ``NULL`` is " -"returned." +"Return *module*'s :attr:`~module.__name__` value. If the module does not " +"provide one, or if it is not a string, :exc:`SystemError` is raised and " +"``NULL`` is returned." msgstr "" -"Retorna o valor :attr:`__name__` do *módulo*. Se o módulo não fornecer um, " -"ou se não for uma string, :exc:`SystemError` é levantada e ``NULL`` é " -"retornado." +"Retorna o valor :attr:`~module.__name__` do *module*. Se o módulo não " +"fornecer um, ou se não for uma string, :exc:`SystemError` é levantada e " +"``NULL`` é retornado." -#: ../../c-api/module.rst:88 +#: ../../c-api/module.rst:90 msgid "" "Similar to :c:func:`PyModule_GetNameObject` but return the name encoded to " "``'utf-8'``." @@ -126,7 +126,7 @@ msgstr "" "Semelhante a :c:func:`PyModule_GetNameObject` mas retorna o nome codificado " "em ``'utf-8'``" -#: ../../c-api/module.rst:93 +#: ../../c-api/module.rst:95 msgid "" "Return the \"state\" of the module, that is, a pointer to the block of " "memory allocated at module creation time, or ``NULL``. See :c:member:" @@ -136,7 +136,7 @@ msgstr "" "alocado no momento de criação do módulo, ou ``NULL``. Ver :c:member:" "`PyModuleDef.m_size`." -#: ../../c-api/module.rst:100 +#: ../../c-api/module.rst:102 msgid "" "Return a pointer to the :c:type:`PyModuleDef` struct from which the module " "was created, or ``NULL`` if the module wasn't created from a definition." @@ -144,19 +144,19 @@ msgstr "" "Retorna um ponteiro para a estrutura :c:type:`PyModuleDef` da qual o módulo " "foi criado, ou ``NULL`` se o módulo não foi criado de uma definição." -#: ../../c-api/module.rst:110 +#: ../../c-api/module.rst:112 msgid "" "Return the name of the file from which *module* was loaded using *module*'s :" -"attr:`__file__` attribute. If this is not defined, or if it is not a " -"unicode string, raise :exc:`SystemError` and return ``NULL``; otherwise " -"return a reference to a Unicode object." +"attr:`~module.__file__` attribute. If this is not defined, or if it is not " +"a string, raise :exc:`SystemError` and return ``NULL``; otherwise return a " +"reference to a Unicode object." msgstr "" -"Retorna o nome do arquivo do qual o *módulo* foi carregado usando o " -"atributo :attr:`__file__` do *módulo*. Se não estiver definido, ou se não " -"for uma string unicode, levanta :exc:`SystemError` e retorna ``NULL``; Caso " -"contrário, retorna uma referência a um objeto Unicode." +"Retorna o nome do arquivo do qual o *module* foi carregado usando o " +"atributo :attr:`~module.__file__` do *module*. Se não estiver definido, ou " +"se não for uma string unicode, levanta :exc:`SystemError` e retorna " +"``NULL``; Caso contrário, retorna uma referência a um objeto Unicode." -#: ../../c-api/module.rst:120 +#: ../../c-api/module.rst:122 msgid "" "Similar to :c:func:`PyModule_GetFilenameObject` but return the filename " "encoded to 'utf-8'." @@ -164,7 +164,7 @@ msgstr "" "Semelhante a :c:func:`PyModule_GetFilenameObject` mas retorna o nome do " "arquivo codificado em 'utf-8'." -#: ../../c-api/module.rst:123 +#: ../../c-api/module.rst:125 msgid "" ":c:func:`PyModule_GetFilename` raises :exc:`UnicodeEncodeError` on " "unencodable filenames, use :c:func:`PyModule_GetFilenameObject` instead." @@ -172,11 +172,11 @@ msgstr "" ":c:func:`PyModule_GetFilename`: levanta :exc:`UnicodeEncodeError` quando há " "nomes de arquivos não codificáveis, use :c:func:`PyModule_GetFilenameObject`." -#: ../../c-api/module.rst:131 +#: ../../c-api/module.rst:133 msgid "Initializing C modules" msgstr "Inicializando módulos C" -#: ../../c-api/module.rst:133 +#: ../../c-api/module.rst:135 msgid "" "Modules objects are usually created from extension modules (shared libraries " "which export an initialization function), or compiled-in modules (where the " @@ -189,7 +189,7 @@ msgstr "" "func:`PyImport_AppendInittab`). Ver :ref:`building` ou :ref:`extending-with-" "embedding` para mais detalhes." -#: ../../c-api/module.rst:138 +#: ../../c-api/module.rst:140 msgid "" "The initialization function can either pass a module definition instance to :" "c:func:`PyModule_Create`, and return the resulting module object, or request " @@ -200,7 +200,7 @@ msgstr "" "solicitar \"inicialização multifásica\" retornando a própria estrutura de " "definição." -#: ../../c-api/module.rst:144 +#: ../../c-api/module.rst:146 msgid "" "The module definition struct, which holds all information needed to create a " "module object. There is usually only one statically initialized variable of " @@ -210,15 +210,15 @@ msgstr "" "necessária para criar um objeto de módulo. Geralmente, há apenas uma " "variável inicializada estaticamente desse tipo para cada módulo." -#: ../../c-api/module.rst:150 +#: ../../c-api/module.rst:152 msgid "Always initialize this member to :c:macro:`PyModuleDef_HEAD_INIT`." msgstr "Sempre inicializa este membro para :c:macro:`PyModuleDef_HEAD_INIT`." -#: ../../c-api/module.rst:154 +#: ../../c-api/module.rst:156 msgid "Name for the new module." msgstr "Nome para o novo módulo." -#: ../../c-api/module.rst:158 +#: ../../c-api/module.rst:160 msgid "" "Docstring for the module; usually a docstring variable created with :c:macro:" "`PyDoc_STRVAR` is used." @@ -226,7 +226,7 @@ msgstr "" "Docstring para o módulo; geralmente uma variável docstring criada com :c:" "macro:`PyDoc_STRVAR` é usada." -#: ../../c-api/module.rst:163 +#: ../../c-api/module.rst:165 msgid "" "Module state may be kept in a per-module memory area that can be retrieved " "with :c:func:`PyModule_GetState`, rather than in static globals. This makes " @@ -237,7 +237,7 @@ msgstr "" "estáticos. Isso torna os módulos seguros para uso em vários " "subinterpretadores." -#: ../../c-api/module.rst:167 +#: ../../c-api/module.rst:169 msgid "" "This memory area is allocated based on *m_size* on module creation, and " "freed when the module object is deallocated, after the :c:member:" @@ -247,7 +247,7 @@ msgstr "" "liberada quando o objeto do módulo é desalocado, após a função :c:member:" "`~PyModuleDef.m_free` ter sido chamada, se presente." -#: ../../c-api/module.rst:171 +#: ../../c-api/module.rst:173 msgid "" "Setting ``m_size`` to ``-1`` means that the module does not support sub-" "interpreters, because it has global state." @@ -255,7 +255,7 @@ msgstr "" "Definir ``m_size`` como ``-1`` significa que o módulo não oferece suporte a " "subinterpretadores, porque ele tem estado global." -#: ../../c-api/module.rst:174 +#: ../../c-api/module.rst:176 msgid "" "Setting it to a non-negative value means that the module can be re-" "initialized and specifies the additional amount of memory it requires for " @@ -267,11 +267,11 @@ msgstr "" "para seu estado. ``m_size`` não negativo é necessário para inicialização " "multifásica." -#: ../../c-api/module.rst:179 +#: ../../c-api/module.rst:181 msgid "See :PEP:`3121` for more details." msgstr "Ver :PEP:`3121` para mais detalhes." -#: ../../c-api/module.rst:183 +#: ../../c-api/module.rst:185 msgid "" "A pointer to a table of module-level functions, described by :c:type:" "`PyMethodDef` values. Can be ``NULL`` if no functions are present." @@ -280,7 +280,7 @@ msgstr "" "valores :c:type:`PyMethodDef`. Pode ser ``NULL`` se nenhuma função estiver " "presente." -#: ../../c-api/module.rst:188 +#: ../../c-api/module.rst:190 msgid "" "An array of slot definitions for multi-phase initialization, terminated by a " "``{0, NULL}`` entry. When using single-phase initialization, *m_slots* must " @@ -290,7 +290,7 @@ msgstr "" "por uma entrada ``{0, NULL}``. Ao usar inicialização monofásica, *m_slots* " "deve ser ``NULL``." -#: ../../c-api/module.rst:194 +#: ../../c-api/module.rst:196 msgid "" "Prior to version 3.5, this member was always set to ``NULL``, and was " "defined as:" @@ -298,7 +298,7 @@ msgstr "" "Antes da versão 3.5, esse membro era sempre definido como ``NULL`` e era " "definido como:" -#: ../../c-api/module.rst:201 +#: ../../c-api/module.rst:203 msgid "" "A traversal function to call during GC traversal of the module object, or " "``NULL`` if not needed." @@ -306,8 +306,8 @@ msgstr "" "Uma função de travessia para chamar durante a travessia do GC do objeto do " "módulo, ou ``NULL`` se não for necessário." -#: ../../c-api/module.rst:204 ../../c-api/module.rst:219 -#: ../../c-api/module.rst:240 +#: ../../c-api/module.rst:206 ../../c-api/module.rst:221 +#: ../../c-api/module.rst:242 msgid "" "This function is not called if the module state was requested but is not " "allocated yet. This is the case immediately after the module is created and " @@ -323,12 +323,12 @@ msgstr "" "for maior que 0 e o estado do módulo (como retornado por :c:func:" "`PyModule_GetState`) for ``NULL``." -#: ../../c-api/module.rst:211 ../../c-api/module.rst:232 -#: ../../c-api/module.rst:247 +#: ../../c-api/module.rst:213 ../../c-api/module.rst:234 +#: ../../c-api/module.rst:249 msgid "No longer called before the module state is allocated." msgstr "Não é mais chamado antes que o estado do módulo seja alocado." -#: ../../c-api/module.rst:216 +#: ../../c-api/module.rst:218 msgid "" "A clear function to call during GC clearing of the module object, or " "``NULL`` if not needed." @@ -336,7 +336,7 @@ msgstr "" "Uma função de limpeza para chamar durante a limpeza do GC do objeto do " "módulo, ou ``NULL`` se não for necessário." -#: ../../c-api/module.rst:226 +#: ../../c-api/module.rst:228 msgid "" "Like :c:member:`PyTypeObject.tp_clear`, this function is not *always* called " "before a module is deallocated. For example, when reference counting is " @@ -344,8 +344,13 @@ msgid "" "collector is not involved and :c:member:`~PyModuleDef.m_free` is called " "directly." msgstr "" +"Assim como :c:member:`PyTypeObject.tp_clear`, esta função não é *sempre* " +"chamada antes de um módulo ser desalocado. Por exemplo, quando a contagem de " +"referências é suficiente para determinar que um objeto não é mais usado, o " +"coletor de lixo cíclico não é envolvido e :c:member:`~PyModuleDef.m_free` é " +"chamado diretamente." -#: ../../c-api/module.rst:237 +#: ../../c-api/module.rst:239 msgid "" "A function to call during deallocation of the module object, or ``NULL`` if " "not needed." @@ -353,11 +358,11 @@ msgstr "" "Uma função para ser chamada durante a desalocação do objeto do módulo, ou " "``NULL`` se não for necessário." -#: ../../c-api/module.rst:251 +#: ../../c-api/module.rst:253 msgid "Single-phase initialization" msgstr "inicialização de fase única" -#: ../../c-api/module.rst:253 +#: ../../c-api/module.rst:255 msgid "" "The module initialization function may create and return the module object " "directly. This is referred to as \"single-phase initialization\", and uses " @@ -367,21 +372,24 @@ msgstr "" "diretamente. Isso é chamado de \"inicialização de fase única\" e usa uma das " "duas funções de criação de módulo a seguir:" -#: ../../c-api/module.rst:259 +#: ../../c-api/module.rst:261 msgid "" "Create a new module object, given the definition in *def*. This behaves " "like :c:func:`PyModule_Create2` with *module_api_version* set to :c:macro:" "`PYTHON_API_VERSION`." msgstr "" +"Cria um novo objeto de módulo, dada a definição em *def*. Isso se comporta " +"como :c:func:`PyModule_Create2` com *module_api_version* definido como :c:" +"macro:`PYTHON_API_VERSION`" -#: ../../c-api/module.rst:266 +#: ../../c-api/module.rst:268 msgid "" "Create a new module object, given the definition in *def*, assuming the API " "version *module_api_version*. If that version does not match the version of " "the running interpreter, a :exc:`RuntimeWarning` is emitted." msgstr "" -#: ../../c-api/module.rst:274 +#: ../../c-api/module.rst:276 msgid "" "Most uses of this function should be using :c:func:`PyModule_Create` " "instead; only use this if you are sure you need it." @@ -389,18 +397,18 @@ msgstr "" "A maioria dos usos dessa função deve ser feita com :c:func:" "`PyModule_Create`; use-o apenas se tiver certeza de que precisa." -#: ../../c-api/module.rst:277 +#: ../../c-api/module.rst:279 msgid "" "Before it is returned from in the initialization function, the resulting " "module object is typically populated using functions like :c:func:" "`PyModule_AddObjectRef`." msgstr "" -#: ../../c-api/module.rst:283 +#: ../../c-api/module.rst:285 msgid "Multi-phase initialization" msgstr "Inicialização multifásica" -#: ../../c-api/module.rst:285 +#: ../../c-api/module.rst:287 msgid "" "An alternate way to specify extensions is to request \"multi-phase " "initialization\". Extension modules created this way behave more like Python " @@ -410,7 +418,7 @@ msgid "" "__init__` methods of classes." msgstr "" -#: ../../c-api/module.rst:292 +#: ../../c-api/module.rst:294 msgid "" "Unlike modules created using single-phase initialization, these modules are " "not singletons: if the *sys.modules* entry is removed and the module is re-" @@ -423,14 +431,14 @@ msgid "" "__dict__` or individual classes created with :c:func:`PyType_FromSpec`)." msgstr "" -#: ../../c-api/module.rst:302 +#: ../../c-api/module.rst:304 msgid "" "All modules created using multi-phase initialization are expected to " "support :ref:`sub-interpreters `. Making sure " "multiple modules are independent is typically enough to achieve this." msgstr "" -#: ../../c-api/module.rst:306 +#: ../../c-api/module.rst:308 msgid "" "To request multi-phase initialization, the initialization function " "(PyInit_modulename) returns a :c:type:`PyModuleDef` instance with non-empty :" @@ -438,7 +446,7 @@ msgid "" "instance must be initialized with the following function:" msgstr "" -#: ../../c-api/module.rst:313 +#: ../../c-api/module.rst:315 msgid "" "Ensures a module definition is a properly initialized Python object that " "correctly reports its type and reference count." @@ -446,54 +454,54 @@ msgstr "" "Garante que uma definição de módulo é um objeto Python devidamente " "inicializado que reporta corretamente seu tipo e contagem de referências." -#: ../../c-api/module.rst:316 +#: ../../c-api/module.rst:318 msgid "Returns *def* cast to ``PyObject*``, or ``NULL`` if an error occurred." msgstr "" -#: ../../c-api/module.rst:320 +#: ../../c-api/module.rst:322 msgid "" "The *m_slots* member of the module definition must point to an array of " "``PyModuleDef_Slot`` structures:" msgstr "" -#: ../../c-api/module.rst:327 +#: ../../c-api/module.rst:329 msgid "A slot ID, chosen from the available values explained below." msgstr "" "Um ID de lot, escolhido a partir dos valores disponíveis explicados abaixo." -#: ../../c-api/module.rst:331 +#: ../../c-api/module.rst:333 msgid "Value of the slot, whose meaning depends on the slot ID." msgstr "Valor do slot, cujo significado depende do ID do slot." -#: ../../c-api/module.rst:335 +#: ../../c-api/module.rst:337 msgid "The *m_slots* array must be terminated by a slot with id 0." msgstr "" -#: ../../c-api/module.rst:337 +#: ../../c-api/module.rst:339 msgid "The available slot types are:" msgstr "Os tipos de slot disponíveis são:" -#: ../../c-api/module.rst:341 +#: ../../c-api/module.rst:343 msgid "" "Specifies a function that is called to create the module object itself. The " "*value* pointer of this slot must point to a function of the signature:" msgstr "" -#: ../../c-api/module.rst:348 +#: ../../c-api/module.rst:350 msgid "" "The function receives a :py:class:`~importlib.machinery.ModuleSpec` " "instance, as defined in :PEP:`451`, and the module definition. It should " "return a new module object, or set an error and return ``NULL``." msgstr "" -#: ../../c-api/module.rst:353 +#: ../../c-api/module.rst:355 msgid "" "This function should be kept minimal. In particular, it should not call " "arbitrary Python code, as trying to import the same module again may result " "in an infinite loop." msgstr "" -#: ../../c-api/module.rst:357 +#: ../../c-api/module.rst:359 msgid "" "Multiple ``Py_mod_create`` slots may not be specified in one module " "definition." @@ -501,7 +509,7 @@ msgstr "" "Múltiplos slots ``Py_mod_create`` podem não estar especificados em uma " "definição de módulo." -#: ../../c-api/module.rst:360 +#: ../../c-api/module.rst:362 msgid "" "If ``Py_mod_create`` is not specified, the import machinery will create a " "normal module object using :c:func:`PyModule_New`. The name is taken from " @@ -510,7 +518,7 @@ msgid "" "through symlinks, all while sharing a single module definition." msgstr "" -#: ../../c-api/module.rst:366 +#: ../../c-api/module.rst:368 msgid "" "There is no requirement for the returned object to be an instance of :c:type:" "`PyModule_Type`. Any type can be used, as long as it supports setting and " @@ -520,7 +528,7 @@ msgid "" "``Py_mod_create``." msgstr "" -#: ../../c-api/module.rst:375 +#: ../../c-api/module.rst:377 msgid "" "Specifies a function that is called to *execute* the module. This is " "equivalent to executing the code of a Python module: typically, this " @@ -528,7 +536,7 @@ msgid "" "function is:" msgstr "" -#: ../../c-api/module.rst:384 +#: ../../c-api/module.rst:386 msgid "" "If multiple ``Py_mod_exec`` slots are specified, they are processed in the " "order they appear in the *m_slots* array." @@ -536,55 +544,55 @@ msgstr "" "Se vários slots ``Py_mod_exec`` forem especificados, eles serão processados " "na ordem em que aparecem no vetor *m_slots*." -#: ../../c-api/module.rst:389 ../../c-api/module.rst:422 +#: ../../c-api/module.rst:391 ../../c-api/module.rst:424 msgid "Specifies one of the following values:" msgstr "" -#: ../../c-api/module.rst:395 +#: ../../c-api/module.rst:397 msgid "The module does not support being imported in subinterpreters." msgstr "" -#: ../../c-api/module.rst:399 +#: ../../c-api/module.rst:401 msgid "" "The module supports being imported in subinterpreters, but only when they " "share the main interpreter's GIL. (See :ref:`isolating-extensions-howto`.)" msgstr "" -#: ../../c-api/module.rst:405 +#: ../../c-api/module.rst:407 msgid "" "The module supports being imported in subinterpreters, even when they have " "their own GIL. (See :ref:`isolating-extensions-howto`.)" msgstr "" -#: ../../c-api/module.rst:409 +#: ../../c-api/module.rst:411 msgid "" "This slot determines whether or not importing this module in a " "subinterpreter will fail." msgstr "" -#: ../../c-api/module.rst:412 +#: ../../c-api/module.rst:414 msgid "" "Multiple ``Py_mod_multiple_interpreters`` slots may not be specified in one " "module definition." msgstr "" -#: ../../c-api/module.rst:415 +#: ../../c-api/module.rst:417 msgid "" "If ``Py_mod_multiple_interpreters`` is not specified, the import machinery " -"defaults to ``Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED``." +"defaults to ``Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED``." msgstr "" -#: ../../c-api/module.rst:426 +#: ../../c-api/module.rst:430 msgid "" "The module depends on the presence of the global interpreter lock (GIL), and " "may access global state without synchronization." msgstr "" -#: ../../c-api/module.rst:431 +#: ../../c-api/module.rst:435 msgid "The module is safe to run without an active GIL." msgstr "" -#: ../../c-api/module.rst:433 +#: ../../c-api/module.rst:437 msgid "" "This slot is ignored by Python builds not configured with :option:`--disable-" "gil`. Otherwise, it determines whether or not importing this module will " @@ -592,27 +600,27 @@ msgid "" "threaded-cpython` for more detail." msgstr "" -#: ../../c-api/module.rst:438 +#: ../../c-api/module.rst:442 msgid "" "Multiple ``Py_mod_gil`` slots may not be specified in one module definition." msgstr "" -#: ../../c-api/module.rst:440 +#: ../../c-api/module.rst:444 msgid "" "If ``Py_mod_gil`` is not specified, the import machinery defaults to " "``Py_MOD_GIL_USED``." msgstr "" -#: ../../c-api/module.rst:445 +#: ../../c-api/module.rst:449 msgid "See :PEP:`489` for more details on multi-phase initialization." msgstr "" "Ver :PEP:`489` para obter mais detalhes sobre a inicialização multifásica." -#: ../../c-api/module.rst:448 +#: ../../c-api/module.rst:452 msgid "Low-level module creation functions" msgstr "Funções de criação de módulo de baixo nível" -#: ../../c-api/module.rst:450 +#: ../../c-api/module.rst:454 msgid "" "The following functions are called under the hood when using multi-phase " "initialization. They can be used directly, for example when creating module " @@ -620,14 +628,14 @@ msgid "" "``PyModule_ExecDef`` must be called to fully initialize a module." msgstr "" -#: ../../c-api/module.rst:457 +#: ../../c-api/module.rst:461 msgid "" "Create a new module object, given the definition in *def* and the ModuleSpec " "*spec*. This behaves like :c:func:`PyModule_FromDefAndSpec2` with " "*module_api_version* set to :c:macro:`PYTHON_API_VERSION`." msgstr "" -#: ../../c-api/module.rst:465 +#: ../../c-api/module.rst:469 msgid "" "Create a new module object, given the definition in *def* and the ModuleSpec " "*spec*, assuming the API version *module_api_version*. If that version does " @@ -635,24 +643,24 @@ msgid "" "emitted." msgstr "" -#: ../../c-api/module.rst:474 +#: ../../c-api/module.rst:478 msgid "" "Most uses of this function should be using :c:func:`PyModule_FromDefAndSpec` " "instead; only use this if you are sure you need it." msgstr "" -#: ../../c-api/module.rst:481 +#: ../../c-api/module.rst:485 msgid "Process any execution slots (:c:data:`Py_mod_exec`) given in *def*." msgstr "" -#: ../../c-api/module.rst:487 +#: ../../c-api/module.rst:491 msgid "" "Set the docstring for *module* to *docstring*. This function is called " "automatically when creating a module from ``PyModuleDef``, using either " "``PyModule_Create`` or ``PyModule_FromDefAndSpec``." msgstr "" -#: ../../c-api/module.rst:496 +#: ../../c-api/module.rst:500 msgid "" "Add the functions from the ``NULL`` terminated *functions* array to " "*module*. Refer to the :c:type:`PyMethodDef` documentation for details on " @@ -664,11 +672,11 @@ msgid "" "``PyModule_FromDefAndSpec``." msgstr "" -#: ../../c-api/module.rst:508 +#: ../../c-api/module.rst:512 msgid "Support functions" msgstr "" -#: ../../c-api/module.rst:510 +#: ../../c-api/module.rst:514 msgid "" "The module initialization function (if using single phase initialization) or " "a function called from a module execution slot (if using multi-phase " @@ -676,29 +684,45 @@ msgid "" "module state:" msgstr "" -#: ../../c-api/module.rst:517 +#: ../../c-api/module.rst:521 msgid "" "Add an object to *module* as *name*. This is a convenience function which " "can be used from the module's initialization function." msgstr "" -#: ../../c-api/module.rst:520 +#: ../../c-api/module.rst:524 msgid "" "On success, return ``0``. On error, raise an exception and return ``-1``." msgstr "" -#: ../../c-api/module.rst:522 +#: ../../c-api/module.rst:526 ../../c-api/module.rst:577 +#: ../../c-api/module.rst:604 +msgid "Example usage::" +msgstr "Exemplo de uso::" + +#: ../../c-api/module.rst:528 msgid "" -"Return ``-1`` if *value* is ``NULL``. It must be called with an exception " -"raised in this case." +"static int\n" +"add_spam(PyObject *module, int value)\n" +"{\n" +" PyObject *obj = PyLong_FromLong(value);\n" +" if (obj == NULL) {\n" +" return -1;\n" +" }\n" +" int res = PyModule_AddObjectRef(module, \"spam\", obj);\n" +" Py_DECREF(obj);\n" +" return res;\n" +" }" msgstr "" -#: ../../c-api/module.rst:525 ../../c-api/module.rst:572 -#: ../../c-api/module.rst:599 -msgid "Example usage::" -msgstr "Exemplo de uso::" +#: ../../c-api/module.rst:540 +msgid "" +"To be convenient, the function accepts ``NULL`` *value* with an exception " +"set. In this case, return ``-1`` and just leave the raised exception " +"unchanged." +msgstr "" -#: ../../c-api/module.rst:539 +#: ../../c-api/module.rst:544 msgid "" "The example can also be written without checking explicitly if *obj* is " "``NULL``::" @@ -706,13 +730,25 @@ msgstr "" "O exemplo também pode ser escrito sem verificar explicitamente se *obj* é " "``NULL``::" -#: ../../c-api/module.rst:551 +#: ../../c-api/module.rst:547 +msgid "" +"static int\n" +"add_spam(PyObject *module, int value)\n" +"{\n" +" PyObject *obj = PyLong_FromLong(value);\n" +" int res = PyModule_AddObjectRef(module, \"spam\", obj);\n" +" Py_XDECREF(obj);\n" +" return res;\n" +" }" +msgstr "" + +#: ../../c-api/module.rst:556 msgid "" "Note that ``Py_XDECREF()`` should be used instead of ``Py_DECREF()`` in this " "case, since *obj* can be ``NULL``." msgstr "" -#: ../../c-api/module.rst:554 +#: ../../c-api/module.rst:559 msgid "" "The number of different *name* strings passed to this function should be " "kept small, usually by only using statically allocated strings as *name*. " @@ -722,7 +758,7 @@ msgid "" "internally to create a key object." msgstr "" -#: ../../c-api/module.rst:567 +#: ../../c-api/module.rst:572 msgid "" "Similar to :c:func:`PyModule_AddObjectRef`, but \"steals\" a reference to " "*value*. It can be called with a result of function that returns a new " @@ -730,49 +766,70 @@ msgid "" "variable." msgstr "" -#: ../../c-api/module.rst:583 +#: ../../c-api/module.rst:579 +msgid "" +"if (PyModule_Add(module, \"spam\", PyBytes_FromString(value)) < 0) {\n" +" goto error;\n" +"}" +msgstr "" + +#: ../../c-api/module.rst:588 msgid "" "Similar to :c:func:`PyModule_AddObjectRef`, but steals a reference to " "*value* on success (if it returns ``0``)." msgstr "" -#: ../../c-api/module.rst:586 +#: ../../c-api/module.rst:591 msgid "" "The new :c:func:`PyModule_Add` or :c:func:`PyModule_AddObjectRef` functions " "are recommended, since it is easy to introduce reference leaks by misusing " "the :c:func:`PyModule_AddObject` function." msgstr "" -#: ../../c-api/module.rst:593 +#: ../../c-api/module.rst:598 msgid "" "Unlike other functions that steal references, ``PyModule_AddObject()`` only " "releases the reference to *value* **on success**." msgstr "" -#: ../../c-api/module.rst:596 +#: ../../c-api/module.rst:601 msgid "" "This means that its return value must be checked, and calling code must :c:" "func:`Py_XDECREF` *value* manually on error." msgstr "" -#: ../../c-api/module.rst:614 -msgid ":c:func:`PyModule_AddObject` is :term:`soft deprecated`." +#: ../../c-api/module.rst:606 +msgid "" +"PyObject *obj = PyBytes_FromString(value);\n" +"if (PyModule_AddObject(module, \"spam\", obj) < 0) {\n" +" // If 'obj' is not NULL and PyModule_AddObject() failed,\n" +" // 'obj' strong reference must be deleted with Py_XDECREF().\n" +" // If 'obj' is NULL, Py_XDECREF() does nothing.\n" +" Py_XDECREF(obj);\n" +" goto error;\n" +"}\n" +"// PyModule_AddObject() stole a reference to obj:\n" +"// Py_XDECREF(obj) is not needed here." msgstr "" #: ../../c-api/module.rst:619 +msgid ":c:func:`PyModule_AddObject` is :term:`soft deprecated`." +msgstr "" + +#: ../../c-api/module.rst:624 msgid "" "Add an integer constant to *module* as *name*. This convenience function " "can be used from the module's initialization function. Return ``-1`` with an " "exception set on error, ``0`` on success." msgstr "" -#: ../../c-api/module.rst:623 +#: ../../c-api/module.rst:628 msgid "" "This is a convenience function that calls :c:func:`PyLong_FromLong` and :c:" "func:`PyModule_AddObjectRef`; see their documentation for details." msgstr "" -#: ../../c-api/module.rst:629 +#: ../../c-api/module.rst:634 msgid "" "Add a string constant to *module* as *name*. This convenience function can " "be used from the module's initialization function. The string *value* must " @@ -780,14 +837,14 @@ msgid "" "on success." msgstr "" -#: ../../c-api/module.rst:634 +#: ../../c-api/module.rst:639 msgid "" "This is a convenience function that calls :c:func:" "`PyUnicode_InternFromString` and :c:func:`PyModule_AddObjectRef`; see their " "documentation for details." msgstr "" -#: ../../c-api/module.rst:641 +#: ../../c-api/module.rst:646 msgid "" "Add an int constant to *module*. The name and the value are taken from " "*macro*. For example ``PyModule_AddIntMacro(module, AF_INET)`` adds the int " @@ -795,11 +852,11 @@ msgid "" "with an exception set on error, ``0`` on success." msgstr "" -#: ../../c-api/module.rst:649 +#: ../../c-api/module.rst:654 msgid "Add a string constant to *module*." msgstr "" -#: ../../c-api/module.rst:653 +#: ../../c-api/module.rst:658 msgid "" "Add a type object to *module*. The type object is finalized by calling " "internally :c:func:`PyType_Ready`. The name of the type object is taken from " @@ -807,7 +864,7 @@ msgid "" "``-1`` with an exception set on error, ``0`` on success." msgstr "" -#: ../../c-api/module.rst:663 +#: ../../c-api/module.rst:668 msgid "" "Indicate that *module* does or does not support running without the global " "interpreter lock (GIL), using one of the values from :c:macro:`Py_mod_gil`. " @@ -818,25 +875,25 @@ msgid "" "Return ``-1`` with an exception set on error, ``0`` on success." msgstr "" -#: ../../c-api/module.rst:676 +#: ../../c-api/module.rst:681 msgid "Module lookup" msgstr "Pesquisa por módulos" -#: ../../c-api/module.rst:678 +#: ../../c-api/module.rst:683 msgid "" "Single-phase initialization creates singleton modules that can be looked up " "in the context of the current interpreter. This allows the module object to " "be retrieved later with only a reference to the module definition." msgstr "" -#: ../../c-api/module.rst:682 +#: ../../c-api/module.rst:687 msgid "" "These functions will not work on modules created using multi-phase " "initialization, since multiple such modules can be created from a single " "definition." msgstr "" -#: ../../c-api/module.rst:687 +#: ../../c-api/module.rst:692 msgid "" "Returns the module object that was created from *def* for the current " "interpreter. This method requires that the module object has been attached " @@ -845,18 +902,18 @@ msgid "" "to the interpreter state yet, it returns ``NULL``." msgstr "" -#: ../../c-api/module.rst:694 +#: ../../c-api/module.rst:699 msgid "" "Attaches the module object passed to the function to the interpreter state. " "This allows the module object to be accessible via :c:func:" "`PyState_FindModule`." msgstr "" -#: ../../c-api/module.rst:697 +#: ../../c-api/module.rst:702 msgid "Only effective on modules created using single-phase initialization." msgstr "" -#: ../../c-api/module.rst:699 +#: ../../c-api/module.rst:704 msgid "" "Python calls ``PyState_AddModule`` automatically after importing a module, " "so it is unnecessary (but harmless) to call it from module initialization " @@ -867,17 +924,17 @@ msgid "" "state updates)." msgstr "" -#: ../../c-api/module.rst:707 ../../c-api/module.rst:718 +#: ../../c-api/module.rst:712 ../../c-api/module.rst:723 msgid "The caller must hold the GIL." msgstr "" -#: ../../c-api/module.rst:709 +#: ../../c-api/module.rst:714 msgid "Return ``-1`` with an exception set on error, ``0`` on success." msgstr "" "Retorna ``-1`` com uma exceção definida em caso de erro, ``0`` em caso de " "sucesso." -#: ../../c-api/module.rst:715 +#: ../../c-api/module.rst:720 msgid "" "Removes the module object created from *def* from the interpreter state. " "Return ``-1`` with an exception set on error, ``0`` on success." @@ -895,30 +952,30 @@ msgstr "módulo" msgid "ModuleType (in module types)" msgstr "" -#: ../../c-api/module.rst:33 ../../c-api/module.rst:76 +#: ../../c-api/module.rst:33 ../../c-api/module.rst:77 msgid "__name__ (module attribute)" -msgstr "" +msgstr "__name__ (atributo de módulo)" #: ../../c-api/module.rst:33 msgid "__doc__ (module attribute)" -msgstr "" +msgstr "__doc__ (atributo de módulo)" -#: ../../c-api/module.rst:33 ../../c-api/module.rst:106 +#: ../../c-api/module.rst:33 ../../c-api/module.rst:108 msgid "__file__ (module attribute)" -msgstr "" +msgstr "__file__ (atributo de módulo)" #: ../../c-api/module.rst:33 msgid "__package__ (module attribute)" -msgstr "" +msgstr "__package__ (atributo de módulo)" #: ../../c-api/module.rst:33 msgid "__loader__ (module attribute)" -msgstr "" +msgstr "__loader__ (atributo de módulo)" -#: ../../c-api/module.rst:62 +#: ../../c-api/module.rst:63 msgid "__dict__ (module attribute)" -msgstr "" +msgstr "__dict__ (atributo de módulo)" -#: ../../c-api/module.rst:76 ../../c-api/module.rst:106 +#: ../../c-api/module.rst:77 ../../c-api/module.rst:108 msgid "SystemError (built-in exception)" msgstr "" diff --git a/c-api/monitoring.po b/c-api/monitoring.po index ad91c273e..6acb7237c 100644 --- a/c-api/monitoring.po +++ b/c-api/monitoring.po @@ -1,31 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Pedro Fonini, 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-20 06:40+0000\n" -"PO-Revision-Date: 2024-05-11 01:07+0000\n" -"Last-Translator: Pedro Fonini, 2024\n" +"POT-Creation-Date: 2025-03-21 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../c-api/monitoring.rst:6 msgid "Monitoring C API" -msgstr "API C de Monitoramento" +msgstr "API C de monitoramento" #: ../../c-api/monitoring.rst:8 msgid "Added in version 3.13." @@ -43,7 +43,7 @@ msgstr "" #: ../../c-api/monitoring.rst:15 msgid "Generating Execution Events" -msgstr "Gerando Eventos de Execução" +msgstr "Gerando eventos de execução" #: ../../c-api/monitoring.rst:17 msgid "" @@ -210,3 +210,156 @@ msgid "" msgstr "" "Estados de monitoramento podem ser gerenciados com a ajuda de escopos de " "monitoramento. Um escopo corresponderia tipicamente a um função python." + +#: ../../c-api/monitoring.rst:138 +msgid "" +"Enter a monitored scope. ``event_types`` is an array of the event IDs for " +"events that may be fired from the scope. For example, the ID of a " +"``PY_START`` event is the value ``PY_MONITORING_EVENT_PY_START``, which is " +"numerically equal to the base-2 logarithm of ``sys.monitoring.events." +"PY_START``. ``state_array`` is an array with a monitoring state entry for " +"each event in ``event_types``, it is allocated by the user but populated by :" +"c:func:`!PyMonitoring_EnterScope` with information about the activation " +"state of the event. The size of ``event_types`` (and hence also of " +"``state_array``) is given in ``length``." +msgstr "" +"Insere um escopo monitorado. ``event_types`` é um vetor de IDs de eventos " +"para eventos que podem ser disparados do escopo. Por exemplo, a ID de um " +"evento ``PY_START`` é o valor ``PY_MONITORING_EVENT_PY_START``, que é " +"numericamente igual ao logaritmo de base 2 de ``sys.monitoring.events." +"PY_START``. ``state_array`` é um vetor com uma entrada de estado de " +"monitoramento para cada evento em ``event_types``, é alocado pelo usuário, " +"mas preenchido por :c:func:`!PyMonitoring_EnterScope` com informações sobre " +"o estado de ativação do evento. O tamanho de ``event_types`` (e, portanto, " +"também de ``state_array``) é fornecido em ``length``." + +#: ../../c-api/monitoring.rst:148 +msgid "" +"The ``version`` argument is a pointer to a value which should be allocated " +"by the user together with ``state_array`` and initialized to 0, and then set " +"only by :c:func:`!PyMonitoring_EnterScope` itself. It allows this function " +"to determine whether event states have changed since the previous call, and " +"to return quickly if they have not." +msgstr "" +"O argumento ``version`` é um ponteiro para um valor que deve ser alocado " +"pelo usuário junto com ``state_array`` e inicializado como 0, e então " +"definido somente pelo próprio :c:func:`!PyMonitoring_EnterScope`. Ele " +"permite que esta função determine se os estados de eventos mudaram desde a " +"chamada anterior, e retorne rapidamente se não mudaram." + +#: ../../c-api/monitoring.rst:154 +msgid "" +"The scopes referred to here are lexical scopes: a function, class or " +"method. :c:func:`!PyMonitoring_EnterScope` should be called whenever the " +"lexical scope is entered. Scopes can be reentered, reusing the same " +"*state_array* and *version*, in situations like when emulating a recursive " +"Python function. When a code-like's execution is paused, such as when " +"emulating a generator, the scope needs to be exited and re-entered." +msgstr "" +"Os escopos mencionados aqui são escopos lexicais: uma função, classe ou " +"método. :c:func:`!PyMonitoring_EnterScope` deve ser chamada sempre que o " +"escopo lexical for inserido. Os escopos podem ser inseridos novamente, " +"reutilizando o mesmo *state_array* e *version*, em situações como ao emular " +"uma função Python recursiva. Quando a execução de um código semelhante é " +"pausada, como ao emular um gerador, o escopo precisa ser encerrado e " +"inserido novamente." + +#: ../../c-api/monitoring.rst:161 +msgid "The macros for *event_types* are:" +msgstr "As macros para *event_types* são:" + +#: ../../c-api/monitoring.rst:169 +msgid "Macro" +msgstr "Macro" + +#: ../../c-api/monitoring.rst:169 +msgid "Event" +msgstr "Evento" + +#: ../../c-api/monitoring.rst:171 +msgid ":monitoring-event:`BRANCH`" +msgstr ":monitoring-event:`BRANCH`" + +#: ../../c-api/monitoring.rst:172 +msgid ":monitoring-event:`CALL`" +msgstr ":monitoring-event:`CALL`" + +#: ../../c-api/monitoring.rst:173 +msgid ":monitoring-event:`C_RAISE`" +msgstr ":monitoring-event:`C_RAISE`" + +#: ../../c-api/monitoring.rst:174 +msgid ":monitoring-event:`C_RETURN`" +msgstr ":monitoring-event:`C_RETURN`" + +#: ../../c-api/monitoring.rst:175 +msgid ":monitoring-event:`EXCEPTION_HANDLED`" +msgstr ":monitoring-event:`EXCEPTION_HANDLED`" + +#: ../../c-api/monitoring.rst:176 +msgid ":monitoring-event:`INSTRUCTION`" +msgstr ":monitoring-event:`INSTRUCTION`" + +#: ../../c-api/monitoring.rst:177 +msgid ":monitoring-event:`JUMP`" +msgstr ":monitoring-event:`JUMP`" + +#: ../../c-api/monitoring.rst:178 +msgid ":monitoring-event:`LINE`" +msgstr ":monitoring-event:`LINE`" + +#: ../../c-api/monitoring.rst:179 +msgid ":monitoring-event:`PY_RESUME`" +msgstr ":monitoring-event:`PY_RESUME`" + +#: ../../c-api/monitoring.rst:180 +msgid ":monitoring-event:`PY_RETURN`" +msgstr ":monitoring-event:`PY_RETURN`" + +#: ../../c-api/monitoring.rst:181 +msgid ":monitoring-event:`PY_START`" +msgstr ":monitoring-event:`PY_START`" + +#: ../../c-api/monitoring.rst:182 +msgid ":monitoring-event:`PY_THROW`" +msgstr ":monitoring-event:`PY_THROW`" + +#: ../../c-api/monitoring.rst:183 +msgid ":monitoring-event:`PY_UNWIND`" +msgstr ":monitoring-event:`PY_UNWIND`" + +#: ../../c-api/monitoring.rst:184 +msgid ":monitoring-event:`PY_YIELD`" +msgstr ":monitoring-event:`PY_YIELD`" + +#: ../../c-api/monitoring.rst:185 +msgid ":monitoring-event:`RAISE`" +msgstr ":monitoring-event:`RAISE`" + +#: ../../c-api/monitoring.rst:186 +msgid ":monitoring-event:`RERAISE`" +msgstr ":monitoring-event:`RERAISE`" + +#: ../../c-api/monitoring.rst:187 +msgid ":monitoring-event:`STOP_ITERATION`" +msgstr ":monitoring-event:`STOP_ITERATION`" + +#: ../../c-api/monitoring.rst:192 +msgid "" +"Exit the last scope that was entered with :c:func:`!PyMonitoring_EnterScope`." +msgstr "" +"Sai do último escopo no qual se entrou com :c:func:`!" +"PyMonitoring_EnterScope`." + +#: ../../c-api/monitoring.rst:197 +msgid "" +"Return true if the event corresponding to the event ID *ev* is a :ref:`local " +"event `." +msgstr "" +"Retorna verdadeiro se o evento correspondente ao ID do evento *ev* for um :" +"ref:`evento local `." + +#: ../../c-api/monitoring.rst:204 +msgid "This function is :term:`soft deprecated`." +msgstr "" +"Esta função está :term:`suavemente descontinuada `." diff --git a/c-api/none.po b/c-api/none.po index 96acc9fb0..2e3a2617b 100644 --- a/c-api/none.po +++ b/c-api/none.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/number.po b/c-api/number.po index d266acc4f..dd186cf1e 100644 --- a/c-api/number.po +++ b/c-api/number.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-19 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -327,15 +326,15 @@ msgstr "função embutida" #: ../../c-api/number.rst:67 msgid "divmod" -msgstr "" +msgstr "divmod" #: ../../c-api/number.rst:75 ../../c-api/number.rst:195 msgid "pow" -msgstr "" +msgstr "pow" #: ../../c-api/number.rst:97 msgid "abs" -msgstr "" +msgstr "abs" #: ../../c-api/number.rst:241 msgid "int" diff --git a/c-api/object.po b/c-api/object.po index 8ee517abe..4a56dcbe4 100644 --- a/c-api/object.po +++ b/c-api/object.po @@ -1,29 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2024 -# Vitor Buxbaum Orlandi, 2024 -# Claudio Rogerio Carvalho Filho , 2024 -# Welington Carlos , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-19 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-10 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -221,19 +217,20 @@ msgstr "" #: ../../c-api/object.rst:113 msgid "" "Exceptions that occur when this calls :meth:`~object.__getattr__` and :meth:" -"`~object.__getattribute__` methods are silently ignored. For proper error " -"handling, use :c:func:`PyObject_HasAttrWithError`, :c:func:" -"`PyObject_GetOptionalAttr` or :c:func:`PyObject_GetAttr` instead." +"`~object.__getattribute__` methods aren't propagated, but instead given to :" +"func:`sys.unraisablehook`. For proper error handling, use :c:func:" +"`PyObject_HasAttrWithError`, :c:func:`PyObject_GetOptionalAttr` or :c:func:" +"`PyObject_GetAttr` instead." msgstr "" -#: ../../c-api/object.rst:121 +#: ../../c-api/object.rst:122 msgid "" "This is the same as :c:func:`PyObject_HasAttr`, but *attr_name* is specified " "as a :c:expr:`const char*` UTF-8 encoded bytes string, rather than a :c:expr:" "`PyObject*`." msgstr "" -#: ../../c-api/object.rst:127 +#: ../../c-api/object.rst:128 msgid "" "Exceptions that occur when this calls :meth:`~object.__getattr__` and :meth:" "`~object.__getattribute__` methods or while creating the temporary :class:" @@ -242,39 +239,39 @@ msgid "" "or :c:func:`PyObject_GetAttrString` instead." msgstr "" -#: ../../c-api/object.rst:137 +#: ../../c-api/object.rst:138 msgid "" "Retrieve an attribute named *attr_name* from object *o*. Returns the " "attribute value on success, or ``NULL`` on failure. This is the equivalent " "of the Python expression ``o.attr_name``." msgstr "" -#: ../../c-api/object.rst:141 +#: ../../c-api/object.rst:142 msgid "" "If the missing attribute should not be treated as a failure, you can use :c:" "func:`PyObject_GetOptionalAttr` instead." msgstr "" -#: ../../c-api/object.rst:147 +#: ../../c-api/object.rst:148 msgid "" "This is the same as :c:func:`PyObject_GetAttr`, but *attr_name* is specified " "as a :c:expr:`const char*` UTF-8 encoded bytes string, rather than a :c:expr:" "`PyObject*`." msgstr "" -#: ../../c-api/object.rst:151 +#: ../../c-api/object.rst:152 msgid "" "If the missing attribute should not be treated as a failure, you can use :c:" "func:`PyObject_GetOptionalAttrString` instead." msgstr "" -#: ../../c-api/object.rst:157 +#: ../../c-api/object.rst:158 msgid "" "Variant of :c:func:`PyObject_GetAttr` which doesn't raise :exc:" "`AttributeError` if the attribute is not found." msgstr "" -#: ../../c-api/object.rst:160 +#: ../../c-api/object.rst:161 msgid "" "If the attribute is found, return ``1`` and set *\\*result* to a new :term:" "`strong reference` to the attribute. If the attribute is not found, return " @@ -283,14 +280,14 @@ msgid "" "``-1`` and set *\\*result* to ``NULL``." msgstr "" -#: ../../c-api/object.rst:172 +#: ../../c-api/object.rst:173 msgid "" "This is the same as :c:func:`PyObject_GetOptionalAttr`, but *attr_name* is " "specified as a :c:expr:`const char*` UTF-8 encoded bytes string, rather than " "a :c:expr:`PyObject*`." msgstr "" -#: ../../c-api/object.rst:180 +#: ../../c-api/object.rst:181 msgid "" "Generic attribute getter function that is meant to be put into a type " "object's ``tp_getattro`` slot. It looks for a descriptor in the dictionary " @@ -300,34 +297,34 @@ msgid "" "descriptors don't. Otherwise, an :exc:`AttributeError` is raised." msgstr "" -#: ../../c-api/object.rst:190 +#: ../../c-api/object.rst:191 msgid "" "Set the value of the attribute named *attr_name*, for object *o*, to the " "value *v*. Raise an exception and return ``-1`` on failure; return ``0`` on " "success. This is the equivalent of the Python statement ``o.attr_name = v``." msgstr "" -#: ../../c-api/object.rst:195 +#: ../../c-api/object.rst:196 msgid "" "If *v* is ``NULL``, the attribute is deleted. This behaviour is deprecated " "in favour of using :c:func:`PyObject_DelAttr`, but there are currently no " "plans to remove it." msgstr "" -#: ../../c-api/object.rst:202 +#: ../../c-api/object.rst:203 msgid "" "This is the same as :c:func:`PyObject_SetAttr`, but *attr_name* is specified " "as a :c:expr:`const char*` UTF-8 encoded bytes string, rather than a :c:expr:" "`PyObject*`." msgstr "" -#: ../../c-api/object.rst:206 +#: ../../c-api/object.rst:207 msgid "" "If *v* is ``NULL``, the attribute is deleted, but this feature is deprecated " "in favour of using :c:func:`PyObject_DelAttrString`." msgstr "" -#: ../../c-api/object.rst:209 +#: ../../c-api/object.rst:210 msgid "" "The number of different attribute names passed to this function should be " "kept small, usually by using a statically allocated string as *attr_name*. " @@ -337,7 +334,7 @@ msgid "" "internally to create a key object." msgstr "" -#: ../../c-api/object.rst:219 +#: ../../c-api/object.rst:220 msgid "" "Generic attribute setter and deleter function that is meant to be put into a " "type object's :c:member:`~PyTypeObject.tp_setattro` slot. It looks for a " @@ -349,20 +346,20 @@ msgid "" "returned." msgstr "" -#: ../../c-api/object.rst:231 +#: ../../c-api/object.rst:232 msgid "" "Delete attribute named *attr_name*, for object *o*. Returns ``-1`` on " "failure. This is the equivalent of the Python statement ``del o.attr_name``." msgstr "" -#: ../../c-api/object.rst:237 +#: ../../c-api/object.rst:238 msgid "" "This is the same as :c:func:`PyObject_DelAttr`, but *attr_name* is specified " "as a :c:expr:`const char*` UTF-8 encoded bytes string, rather than a :c:expr:" "`PyObject*`." msgstr "" -#: ../../c-api/object.rst:241 +#: ../../c-api/object.rst:242 msgid "" "The number of different attribute names passed to this function should be " "kept small, usually by using a statically allocated string as *attr_name*. " @@ -372,13 +369,13 @@ msgid "" "internally to create a key object for lookup." msgstr "" -#: ../../c-api/object.rst:252 +#: ../../c-api/object.rst:253 msgid "" "A generic implementation for the getter of a ``__dict__`` descriptor. It " "creates the dictionary if necessary." msgstr "" -#: ../../c-api/object.rst:255 +#: ../../c-api/object.rst:256 msgid "" "This function may also be called to get the :py:attr:`~object.__dict__` of " "the object *o*. Pass ``NULL`` for *context* when calling it. Since this " @@ -387,30 +384,30 @@ msgid "" "the object." msgstr "" -#: ../../c-api/object.rst:261 +#: ../../c-api/object.rst:262 msgid "On failure, returns ``NULL`` with an exception set." msgstr "" -#: ../../c-api/object.rst:268 +#: ../../c-api/object.rst:269 msgid "" "A generic implementation for the setter of a ``__dict__`` descriptor. This " "implementation does not allow the dictionary to be deleted." msgstr "" -#: ../../c-api/object.rst:276 +#: ../../c-api/object.rst:277 msgid "" "Return a pointer to :py:attr:`~object.__dict__` of the object *obj*. If " "there is no ``__dict__``, return ``NULL`` without setting an exception." msgstr "" -#: ../../c-api/object.rst:279 +#: ../../c-api/object.rst:280 msgid "" "This function may need to allocate memory for the dictionary, so it may be " "more efficient to call :c:func:`PyObject_GetAttr` when accessing an " "attribute on the object." msgstr "" -#: ../../c-api/object.rst:286 +#: ../../c-api/object.rst:287 msgid "" "Compare the values of *o1* and *o2* using the operation specified by *opid*, " "which must be one of :c:macro:`Py_LT`, :c:macro:`Py_LE`, :c:macro:`Py_EQ`, :" @@ -421,33 +418,33 @@ msgid "" "success, or ``NULL`` on failure." msgstr "" -#: ../../c-api/object.rst:296 +#: ../../c-api/object.rst:297 msgid "" "Compare the values of *o1* and *o2* using the operation specified by *opid*, " "like :c:func:`PyObject_RichCompare`, but returns ``-1`` on error, ``0`` if " "the result is false, ``1`` otherwise." msgstr "" -#: ../../c-api/object.rst:301 +#: ../../c-api/object.rst:302 msgid "" "If *o1* and *o2* are the same object, :c:func:`PyObject_RichCompareBool` " "will always return ``1`` for :c:macro:`Py_EQ` and ``0`` for :c:macro:`Py_NE`." msgstr "" -#: ../../c-api/object.rst:306 +#: ../../c-api/object.rst:307 msgid "" "Format *obj* using *format_spec*. This is equivalent to the Python " "expression ``format(obj, format_spec)``." msgstr "" -#: ../../c-api/object.rst:309 +#: ../../c-api/object.rst:310 msgid "" "*format_spec* may be ``NULL``. In this case the call is equivalent to " "``format(obj)``. Returns the formatted string on success, ``NULL`` on " "failure." msgstr "" -#: ../../c-api/object.rst:317 +#: ../../c-api/object.rst:318 msgid "" "Compute a string representation of object *o*. Returns the string " "representation on success, ``NULL`` on failure. This is the equivalent of " @@ -455,7 +452,7 @@ msgid "" "function." msgstr "" -#: ../../c-api/object.rst:321 ../../c-api/object.rst:345 +#: ../../c-api/object.rst:322 ../../c-api/object.rst:346 msgid "" "This function now includes a debug assertion to help ensure that it does not " "silently discard an active exception." @@ -463,7 +460,7 @@ msgstr "" "Essa função agora inclui uma asserção de depuração para ajudar a garantir " "que ela não descarte silenciosamente uma exceção ativa." -#: ../../c-api/object.rst:329 +#: ../../c-api/object.rst:330 msgid "" "As :c:func:`PyObject_Repr`, compute a string representation of object *o*, " "but escape the non-ASCII characters in the string returned by :c:func:" @@ -472,7 +469,7 @@ msgid "" "Called by the :func:`ascii` built-in function." msgstr "" -#: ../../c-api/object.rst:340 +#: ../../c-api/object.rst:341 msgid "" "Compute a string representation of object *o*. Returns the string " "representation on success, ``NULL`` on failure. This is the equivalent of " @@ -480,7 +477,7 @@ msgid "" "function and, therefore, by the :func:`print` function." msgstr "" -#: ../../c-api/object.rst:354 +#: ../../c-api/object.rst:355 msgid "" "Compute a bytes representation of object *o*. ``NULL`` is returned on " "failure and a bytes object on success. This is equivalent to the Python " @@ -489,73 +486,73 @@ msgid "" "bytes object." msgstr "" -#: ../../c-api/object.rst:363 +#: ../../c-api/object.rst:364 msgid "" "Return ``1`` if the class *derived* is identical to or derived from the " "class *cls*, otherwise return ``0``. In case of an error, return ``-1``." msgstr "" -#: ../../c-api/object.rst:366 ../../c-api/object.rst:385 +#: ../../c-api/object.rst:367 ../../c-api/object.rst:386 msgid "" "If *cls* is a tuple, the check will be done against every entry in *cls*. " "The result will be ``1`` when at least one of the checks returns ``1``, " "otherwise it will be ``0``." msgstr "" -#: ../../c-api/object.rst:370 +#: ../../c-api/object.rst:371 msgid "" -"If *cls* has a :meth:`~class.__subclasscheck__` method, it will be called to " +"If *cls* has a :meth:`~type.__subclasscheck__` method, it will be called to " "determine the subclass status as described in :pep:`3119`. Otherwise, " "*derived* is a subclass of *cls* if it is a direct or indirect subclass, i." -"e. contained in ``cls.__mro__``." +"e. contained in :attr:`cls.__mro__ `." msgstr "" -#: ../../c-api/object.rst:375 +#: ../../c-api/object.rst:376 msgid "" "Normally only class objects, i.e. instances of :class:`type` or a derived " "class, are considered classes. However, objects can override this by having " -"a :attr:`~class.__bases__` attribute (which must be a tuple of base classes)." +"a :attr:`~type.__bases__` attribute (which must be a tuple of base classes)." msgstr "" -#: ../../c-api/object.rst:382 +#: ../../c-api/object.rst:383 msgid "" "Return ``1`` if *inst* is an instance of the class *cls* or a subclass of " "*cls*, or ``0`` if not. On error, returns ``-1`` and sets an exception." msgstr "" -#: ../../c-api/object.rst:389 +#: ../../c-api/object.rst:390 msgid "" -"If *cls* has a :meth:`~class.__instancecheck__` method, it will be called to " +"If *cls* has a :meth:`~type.__instancecheck__` method, it will be called to " "determine the subclass status as described in :pep:`3119`. Otherwise, " "*inst* is an instance of *cls* if its class is a subclass of *cls*." msgstr "" -#: ../../c-api/object.rst:393 +#: ../../c-api/object.rst:394 msgid "" "An instance *inst* can override what is considered its class by having a :" -"attr:`~instance.__class__` attribute." +"attr:`~object.__class__` attribute." msgstr "" -#: ../../c-api/object.rst:396 +#: ../../c-api/object.rst:397 msgid "" "An object *cls* can override if it is considered a class, and what its base " -"classes are, by having a :attr:`~class.__bases__` attribute (which must be a " +"classes are, by having a :attr:`~type.__bases__` attribute (which must be a " "tuple of base classes)." msgstr "" -#: ../../c-api/object.rst:405 +#: ../../c-api/object.rst:406 msgid "" "Compute and return the hash value of an object *o*. On failure, return " "``-1``. This is the equivalent of the Python expression ``hash(o)``." msgstr "" -#: ../../c-api/object.rst:408 +#: ../../c-api/object.rst:409 msgid "" "The return type is now Py_hash_t. This is a signed integer the same size " "as :c:type:`Py_ssize_t`." msgstr "" -#: ../../c-api/object.rst:415 +#: ../../c-api/object.rst:416 msgid "" "Set a :exc:`TypeError` indicating that ``type(o)`` is not :term:`hashable` " "and return ``-1``. This function receives special treatment when stored in a " @@ -563,21 +560,21 @@ msgid "" "that it is not hashable." msgstr "" -#: ../../c-api/object.rst:423 +#: ../../c-api/object.rst:424 msgid "" "Returns ``1`` if the object *o* is considered to be true, and ``0`` " "otherwise. This is equivalent to the Python expression ``not not o``. On " "failure, return ``-1``." msgstr "" -#: ../../c-api/object.rst:430 +#: ../../c-api/object.rst:431 msgid "" "Returns ``0`` if the object *o* is considered to be true, and ``1`` " "otherwise. This is equivalent to the Python expression ``not o``. On " "failure, return ``-1``." msgstr "" -#: ../../c-api/object.rst:439 +#: ../../c-api/object.rst:440 msgid "" "When *o* is non-``NULL``, returns a type object corresponding to the object " "type of object *o*. On failure, raises :exc:`SystemError` and returns " @@ -588,13 +585,13 @@ msgid "" "when a new :term:`strong reference` is needed." msgstr "" -#: ../../c-api/object.rst:451 +#: ../../c-api/object.rst:452 msgid "" "Return non-zero if the object *o* is of type *type* or a subtype of *type*, " "and ``0`` otherwise. Both parameters must be non-``NULL``." msgstr "" -#: ../../c-api/object.rst:460 +#: ../../c-api/object.rst:461 msgid "" "Return the length of object *o*. If the object *o* provides either the " "sequence and mapping protocols, the sequence length is returned. On error, " @@ -602,7 +599,7 @@ msgid "" "``len(o)``." msgstr "" -#: ../../c-api/object.rst:467 +#: ../../c-api/object.rst:468 msgid "" "Return an estimated length for the object *o*. First try to return its " "actual length, then an estimate using :meth:`~object.__length_hint__`, and " @@ -611,26 +608,36 @@ msgid "" "defaultvalue)``." msgstr "" -#: ../../c-api/object.rst:477 +#: ../../c-api/object.rst:478 msgid "" "Return element of *o* corresponding to the object *key* or ``NULL`` on " "failure. This is the equivalent of the Python expression ``o[key]``." msgstr "" -#: ../../c-api/object.rst:483 +#: ../../c-api/object.rst:484 msgid "" "Map the object *key* to the value *v*. Raise an exception and return ``-1`` " "on failure; return ``0`` on success. This is the equivalent of the Python " "statement ``o[key] = v``. This function *does not* steal a reference to *v*." msgstr "" -#: ../../c-api/object.rst:491 +#: ../../c-api/object.rst:492 msgid "" "Remove the mapping for the object *key* from the object *o*. Return ``-1`` " "on failure. This is equivalent to the Python statement ``del o[key]``." msgstr "" -#: ../../c-api/object.rst:497 +#: ../../c-api/object.rst:498 +msgid "" +"This is the same as :c:func:`PyObject_DelItem`, but *key* is specified as a :" +"c:expr:`const char*` UTF-8 encoded bytes string, rather than a :c:expr:" +"`PyObject*`." +msgstr "" +"É o mesmo que :c:func:`PyObject_DelItem`, mas *key* é especificada como uma " +"string de bytes :c:expr:`const char*` codificada em UTF-8, em vez de um :c:" +"expr:`PyObject*`." + +#: ../../c-api/object.rst:505 msgid "" "This is equivalent to the Python expression ``dir(o)``, returning a " "(possibly empty) list of strings appropriate for the object argument, or " @@ -640,7 +647,7 @@ msgid "" "`PyErr_Occurred` will return false." msgstr "" -#: ../../c-api/object.rst:506 +#: ../../c-api/object.rst:514 msgid "" "This is equivalent to the Python expression ``iter(o)``. It returns a new " "iterator for the object argument, or the object itself if the object is " @@ -648,7 +655,14 @@ msgid "" "object cannot be iterated." msgstr "" -#: ../../c-api/object.rst:514 +#: ../../c-api/object.rst:522 +msgid "" +"This is equivalent to the Python ``__iter__(self): return self`` method. It " +"is intended for :term:`iterator` types, to be used in the :c:member:" +"`PyTypeObject.tp_iter` slot." +msgstr "" + +#: ../../c-api/object.rst:528 msgid "" "This is the equivalent to the Python expression ``aiter(o)``. Takes an :" "class:`AsyncIterable` object and returns an :class:`AsyncIterator` for it. " @@ -657,104 +671,104 @@ msgid "" "``NULL`` if the object cannot be iterated." msgstr "" -#: ../../c-api/object.rst:524 +#: ../../c-api/object.rst:538 msgid "Get a pointer to subclass-specific data reserved for *cls*." msgstr "" -#: ../../c-api/object.rst:526 +#: ../../c-api/object.rst:540 msgid "" "The object *o* must be an instance of *cls*, and *cls* must have been " "created using negative :c:member:`PyType_Spec.basicsize`. Python does not " "check this." msgstr "" -#: ../../c-api/object.rst:530 +#: ../../c-api/object.rst:544 msgid "On error, set an exception and return ``NULL``." msgstr "" -#: ../../c-api/object.rst:536 +#: ../../c-api/object.rst:550 msgid "" "Return the size of the instance memory space reserved for *cls*, i.e. the " "size of the memory :c:func:`PyObject_GetTypeData` returns." msgstr "" -#: ../../c-api/object.rst:539 +#: ../../c-api/object.rst:553 msgid "" "This may be larger than requested using :c:member:`-PyType_Spec.basicsize " "`; it is safe to use this larger size (e.g. with :c:" "func:`!memset`)." msgstr "" -#: ../../c-api/object.rst:542 +#: ../../c-api/object.rst:556 msgid "" "The type *cls* **must** have been created using negative :c:member:" "`PyType_Spec.basicsize`. Python does not check this." msgstr "" -#: ../../c-api/object.rst:546 +#: ../../c-api/object.rst:560 msgid "On error, set an exception and return a negative value." msgstr "" -#: ../../c-api/object.rst:552 +#: ../../c-api/object.rst:566 msgid "" "Get a pointer to per-item data for a class with :c:macro:" "`Py_TPFLAGS_ITEMS_AT_END`." msgstr "" -#: ../../c-api/object.rst:555 +#: ../../c-api/object.rst:569 msgid "" "On error, set an exception and return ``NULL``. :py:exc:`TypeError` is " "raised if *o* does not have :c:macro:`Py_TPFLAGS_ITEMS_AT_END` set." msgstr "" -#: ../../c-api/object.rst:563 +#: ../../c-api/object.rst:577 msgid "Visit the managed dictionary of *obj*." msgstr "" -#: ../../c-api/object.rst:565 ../../c-api/object.rst:574 +#: ../../c-api/object.rst:579 ../../c-api/object.rst:588 msgid "" "This function must only be called in a traverse function of the type which " "has the :c:macro:`Py_TPFLAGS_MANAGED_DICT` flag set." msgstr "" -#: ../../c-api/object.rst:572 +#: ../../c-api/object.rst:586 msgid "Clear the managed dictionary of *obj*." msgstr "" -#: ../../c-api/object.rst:315 ../../c-api/object.rst:327 -#: ../../c-api/object.rst:352 ../../c-api/object.rst:403 -#: ../../c-api/object.rst:437 ../../c-api/object.rst:458 +#: ../../c-api/object.rst:316 ../../c-api/object.rst:328 +#: ../../c-api/object.rst:353 ../../c-api/object.rst:404 +#: ../../c-api/object.rst:438 ../../c-api/object.rst:459 msgid "built-in function" msgstr "função embutida" -#: ../../c-api/object.rst:315 +#: ../../c-api/object.rst:316 msgid "repr" msgstr "repr" -#: ../../c-api/object.rst:327 +#: ../../c-api/object.rst:328 msgid "ascii" msgstr "ascii" -#: ../../c-api/object.rst:335 +#: ../../c-api/object.rst:336 msgid "string" msgstr "string" -#: ../../c-api/object.rst:335 +#: ../../c-api/object.rst:336 msgid "PyObject_Str (C function)" msgstr "" -#: ../../c-api/object.rst:352 +#: ../../c-api/object.rst:353 msgid "bytes" msgstr "bytes" -#: ../../c-api/object.rst:403 +#: ../../c-api/object.rst:404 msgid "hash" msgstr "hash" -#: ../../c-api/object.rst:437 +#: ../../c-api/object.rst:438 msgid "type" msgstr "tipo" -#: ../../c-api/object.rst:458 +#: ../../c-api/object.rst:459 msgid "len" msgstr "len" diff --git a/c-api/objimpl.po b/c-api/objimpl.po index ea12cc3b5..366890454 100644 --- a/c-api/objimpl.po +++ b/c-api/objimpl.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2024 -# Raphael Mendonça, 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:49+0000\n" -"Last-Translator: Raphael Mendonça, 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/perfmaps.po b/c-api/perfmaps.po index 8238e657b..6d317d330 100644 --- a/c-api/perfmaps.po +++ b/c-api/perfmaps.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-07 14:15+0000\n" -"PO-Revision-Date: 2023-05-24 13:07+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -98,6 +98,14 @@ msgstr "" "Escreve uma única entrada no arquivo ``/tmp/perf-$pid.map``. Esta função é " "segura para thread. Aqui está a aparência de um exemplo de entrada::" +#: ../../c-api/perfmaps.rst:38 +msgid "" +"# address size name\n" +"7f3529fcf759 b py::bar:/run/t.py" +msgstr "" +"# endereço tamanho nome\n" +"7f3529fcf759 b py::bar:/run/t.py" + #: ../../c-api/perfmaps.rst:41 msgid "" "Will call :c:func:`PyUnstable_PerfMapState_Init` before writing the entry, " diff --git a/c-api/refcounting.po b/c-api/refcounting.po index 176b48e6f..231d08cdc 100644 --- a/c-api/refcounting.po +++ b/c-api/refcounting.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -111,11 +110,10 @@ msgid "" "use :c:func:`Py_XINCREF`." msgstr "" -#: ../../c-api/refcounting.rst:64 ../../c-api/refcounting.rst:132 +#: ../../c-api/refcounting.rst:64 msgid "" -"Do not expect this function to actually modify *o* in any way. For at least " -"`some objects `_, this function has no " -"effect." +"Do not expect this function to actually modify *o* in any way. For at least :" +"pep:`some objects <0683>`, this function has no effect." msgstr "" #: ../../c-api/refcounting.rst:74 @@ -150,10 +148,20 @@ msgstr "" msgid "For example::" msgstr "Por exemplo::" +#: ../../c-api/refcounting.rst:93 +msgid "" +"Py_INCREF(obj);\n" +"self->attr = obj;" +msgstr "" + #: ../../c-api/refcounting.rst:96 msgid "can be written as::" msgstr "" +#: ../../c-api/refcounting.rst:98 +msgid "self->attr = Py_NewRef(obj);" +msgstr "" + #: ../../c-api/refcounting.rst:100 msgid "See also :c:func:`Py_INCREF`." msgstr "" @@ -191,6 +199,12 @@ msgid "" "use :c:func:`Py_XDECREF`." msgstr "" +#: ../../c-api/refcounting.rst:132 +msgid "" +"Do not expect this function to actually modify *o* in any way. For at least :" +"pep:`some objects <683>`, this function has no effect." +msgstr "" + #: ../../c-api/refcounting.rst:138 msgid "" "The deallocation function can cause arbitrary Python code to be invoked (e." @@ -256,10 +270,20 @@ msgstr "" msgid "As in case of :c:func:`Py_CLEAR`, \"the obvious\" code can be deadly::" msgstr "" +#: ../../c-api/refcounting.rst:197 +msgid "" +"Py_DECREF(dst);\n" +"dst = src;" +msgstr "" + #: ../../c-api/refcounting.rst:200 msgid "The safe way is::" msgstr "" +#: ../../c-api/refcounting.rst:202 +msgid "Py_SETREF(dst, src);" +msgstr "" + #: ../../c-api/refcounting.rst:204 msgid "" "That arranges to set *dst* to *src* _before_ releasing the reference to the " diff --git a/c-api/reflection.po b/c-api/reflection.po index 0d90700ee..8eacd247a 100644 --- a/c-api/reflection.po +++ b/c-api/reflection.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-28 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -85,7 +84,7 @@ msgstr "" "cache no objeto frame e permanecerá ativo enquanto o objeto frame o fizer. " "Ao contrário de :c:func:`PyEval_GetFrameLocals` e :func:`locals`, chamadas " "subsequentes para esta função no mesmo quadro atualizarão o conteúdo do " -"dicionário em cache para refletir as mudanças no estado das variáveis ​​locais " +"dicionário em cache para refletir as mudanças no estado das variáveis locais " "em vez de retornar um novo snapshot." #: ../../c-api/reflection.rst:39 diff --git a/c-api/sequence.po b/c-api/sequence.po index f80cfbef9..9de81df31 100644 --- a/c-api/sequence.po +++ b/c-api/sequence.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Adorilson Bezerra , 2021 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -36,14 +35,19 @@ msgid "" "since in general it is impossible to determine what type of keys the class " "supports. This function always succeeds." msgstr "" +"Retorna ``1`` se o objeto fornecer o protocolo de sequência e ``0`` caso " +"contrário. Note que ele retorna ``1`` para classes Python com um método :" +"meth:`~object.__getitem__` a menos que sejam subclasses de :class:`dict` já " +"que no caso geral é impossível determinar que tipo de chaves a classe provê. " +"Esta função sempre obtém sucesso." #: ../../c-api/sequence.rst:23 msgid "" "Returns the number of objects in sequence *o* on success, and ``-1`` on " "failure. This is equivalent to the Python expression ``len(o)``." msgstr "" -"Retorna o número de objetos em sequência *o* em caso de sucesso e ``-1`` em " -"caso de falha. Isso é equivalente à expressão Python ``len(o)``." +"Retorna o número de objetos na sequência *o* em caso de sucesso, ou ``-1`` " +"em caso de falha. Equivale à expressão Python ``len(o)``." #: ../../c-api/sequence.rst:29 msgid "" @@ -51,7 +55,7 @@ msgid "" "failure. This is the equivalent of the Python expression ``o1 + o2``." msgstr "" "Retorna a concatenação de *o1* e *o2* em caso de sucesso, e ``NULL`` em caso " -"de falha. Este é o equivalente da expressão Python ``o1 + o2``." +"de falha. Equivale à expressão Python ``o1 + o2``." #: ../../c-api/sequence.rst:35 msgid "" @@ -60,8 +64,7 @@ msgid "" "count``." msgstr "" "Retorna o resultado da repetição do objeto sequência *o* *count* vezes ou " -"``NULL`` em caso de falha. Este é o equivalente da expressão Python ``o * " -"count``." +"``NULL`` em caso de falha. Equivale à expressão Python ``o * count``." #: ../../c-api/sequence.rst:41 msgid "" @@ -70,8 +73,8 @@ msgid "" "the equivalent of the Python expression ``o1 += o2``." msgstr "" "Retorna a concatenação de *o1* e *o2* em caso de sucesso, e ``NULL`` em caso " -"de falha. A operação é feita *no local* quando *o1* suportar. Este é o " -"equivalente da expressão Python ``o1 += o2``." +"de falha. A operação é feita *localmente* se *o1* permitir. Equivale à " +"expressão Python ``o1 += o2``." #: ../../c-api/sequence.rst:48 msgid "" @@ -80,16 +83,16 @@ msgid "" "it. This is the equivalent of the Python expression ``o *= count``." msgstr "" "Retorna o resultado da repetição do objeto sequência *o* *count* vezes ou " -"``NULL`` em caso de falha. A operação é feita *localmente* quando *o* " -"suportar. Este é o equivalente da expressão Python ``o *= count``." +"``NULL`` em caso de falha. A operação é feita *localmente* se *o* permitir. " +"Equivale à expressão Python ``o *= count``." #: ../../c-api/sequence.rst:55 msgid "" "Return the *i*\\ th element of *o*, or ``NULL`` on failure. This is the " "equivalent of the Python expression ``o[i]``." msgstr "" -"Retorna o elemento *i* de *o* ou ``NULL`` em caso de falha. Este é o " -"equivalente da expressão Python ``o[i]``." +"Retorna o elemento *i* de *o* ou ``NULL`` em caso de falha. Equivale à " +"expressão Python ``o[i]``." #: ../../c-api/sequence.rst:61 msgid "" @@ -97,7 +100,7 @@ msgid "" "on failure. This is the equivalent of the Python expression ``o[i1:i2]``." msgstr "" "Retorna a fatia do objeto sequência *o* entre *i1* e *i2*, ou ``NULL`` em " -"caso de falha. Este é o equivalente da expressão Python ``o[i1:i2]``." +"caso de falha. Equivale à expressão Python ``o[i1:i2]``." #: ../../c-api/sequence.rst:67 msgid "" @@ -107,23 +110,24 @@ msgid "" "reference to *v*." msgstr "" "Atribui o objeto *v* ao elemento *i* de *o*. Levanta uma exceção e retorna " -"``-1`` em caso de falha; retorna ``0`` em caso de sucesso. Isso é " -"equivalente à instrução Python ``o[i]=v``. Esta função *não* rouba uma " -"referência a *v*." +"``-1`` em caso de falha; retorna ``0`` em caso de sucesso. Esta função *não* " +"rouba uma referência a *v*. Equivale à instrução Python ``o[i]=v``." #: ../../c-api/sequence.rst:72 msgid "" "If *v* is ``NULL``, the element is deleted, but this feature is deprecated " "in favour of using :c:func:`PySequence_DelItem`." msgstr "" +"Se *v* for ``NULL``, o elemento será removido, mas este recurso foi " +"descontinuado em favor do uso de :c:func:`PySequence_DelItem`." #: ../../c-api/sequence.rst:78 msgid "" "Delete the *i*\\ th element of object *o*. Returns ``-1`` on failure. This " "is the equivalent of the Python statement ``del o[i]``." msgstr "" -"Exclui o elemento *i* do objeto *o*. Retorna ``-1`` em caso de falha. Isso é " -"equivalente à instrução Python ``del o[i]``." +"Exclui o elemento *i* do objeto *o*. Retorna ``-1`` em caso de falha. " +"Equivale à instrução Python ``del o[i]``." #: ../../c-api/sequence.rst:84 msgid "" @@ -131,7 +135,7 @@ msgid "" "to *i2*. This is the equivalent of the Python statement ``o[i1:i2] = v``." msgstr "" "Atribui o objeto sequência *v* à fatia no objeto sequência *o* de *i1* a " -"*i2*. Isso é equivalente à instrução Python ``o[i1:i2] = v``." +"*i2*. Equivale à instrução Python ``o[i1:i2] = v``." #: ../../c-api/sequence.rst:90 msgid "" @@ -139,7 +143,7 @@ msgid "" "on failure. This is the equivalent of the Python statement ``del o[i1:i2]``." msgstr "" "Exclui a fatia no objeto sequência *o* de *i1* a *i2*. Retorna ``-1`` em " -"caso de falha. Isso é equivalente à instrução Python ``del o[i1:i2]``." +"caso de falha. Equivale à instrução Python ``del o[i1:i2]``." #: ../../c-api/sequence.rst:96 msgid "" @@ -147,6 +151,9 @@ msgid "" "number of keys for which ``o[key] == value``. On failure, return ``-1``. " "This is equivalent to the Python expression ``o.count(value)``." msgstr "" +"Retorna a quantidade de ocorrências de *value* em *o*, isto é, retorna a " +"quantidade de chaves onde ``o[key] == value``. Em caso de falha, retorna " +"``-1``. Equivale à expressão Python ``o.count(value)``." #: ../../c-api/sequence.rst:103 msgid "" @@ -154,12 +161,17 @@ msgid "" "return ``1``, otherwise return ``0``. On error, return ``-1``. This is " "equivalent to the Python expression ``value in o``." msgstr "" +"Determina se *o* contém *value*. Se um item em *o* for igual a *value*, " +"retorna ``1``, senão, retorna ``0``. Em caso de erro, retorna ``-1``. " +"Equivale à expressão Python ``value in o``." #: ../../c-api/sequence.rst:110 msgid "" "Return the first index *i* for which ``o[i] == value``. On error, return " "``-1``. This is equivalent to the Python expression ``o.index(value)``." msgstr "" +"Retorna o primeiro índice *i* tal que ``o[i] == value``. Em caso de erro, " +"retorna ``-1``. Equivale à expressão Python ``o.index(value)``." #: ../../c-api/sequence.rst:116 msgid "" @@ -167,6 +179,9 @@ msgid "" "or ``NULL`` on failure. The returned list is guaranteed to be new. This is " "equivalent to the Python expression ``list(o)``." msgstr "" +"Retorna um objeto lista com o mesmo conteúdo da sequência ou iterável *o*, " +"ou ``NULL`` em caso de falha. Garante-se que a lista retornada será nova. " +"Equivale à expressão Python ``list(o)``." #: ../../c-api/sequence.rst:125 msgid "" @@ -175,6 +190,10 @@ msgid "" "returned, otherwise a tuple will be constructed with the appropriate " "contents. This is equivalent to the Python expression ``tuple(o)``." msgstr "" +"Retorna o objeto tupla com o mesmo conteúdo da sequência ou iterável *o*, ou " +"``NULL`` em caso de falha. Se *o* for uma tupla, retorna uma nova " +"referência. Senão, uma tupla será construída com o conteúdo apropriado. " +"Equivale à expressão Python ``tuple(o)``." #: ../../c-api/sequence.rst:133 msgid "" @@ -183,6 +202,10 @@ msgid "" "iterable, raises :exc:`TypeError` with *m* as the message text. Returns " "``NULL`` on failure." msgstr "" +"Retorna a sequência ou iterável *o* como um objeto usável por outras funções " +"da família ``PySequence_Fast*``. Se o objeto não for uma sequência ou " +"iterável, levanta :exc:`TypeError` com *m* sendo o texto da mensagem. " +"Retorna ``NULL`` em caso de falha." #: ../../c-api/sequence.rst:138 msgid "" @@ -190,12 +213,17 @@ msgid "" "a :c:type:`PyTupleObject` or a :c:type:`PyListObject` and access the data " "fields of *o* directly." msgstr "" +"As funções ``PySequence_Fast*`` têm esse nome porque presumem que *o* é um :" +"c:type:`PyTupleObject` ou um :c:type:`PyListObject` e porque acessam os " +"campos de dados de *o* diretamente." #: ../../c-api/sequence.rst:142 msgid "" "As a CPython implementation detail, if *o* is already a sequence or list, it " "will be returned." msgstr "" +"Como detalhe de implementação de CPython, se *o* já for uma sequência ou " +"lista, ele será retornado." #: ../../c-api/sequence.rst:148 msgid "" @@ -205,18 +233,27 @@ msgid "" "`PySequence_Fast_GET_SIZE` is faster because it can assume *o* is a list or " "tuple." msgstr "" +"Retorna o comprimento de *o*, presumindo que *o* foi retornado por :c:func:" +"`PySequence_Fast` e que *o* não seja ``NULL``. O tamanho também pode ser " +"obtido ao chamar :c:func:`PySequence_Size` em *o*, mas :c:func:" +"`PySequence_Fast_GET_SIZE` é mais rápida, ao supor que *o* é uma lista ou " +"tupla." #: ../../c-api/sequence.rst:157 msgid "" "Return the *i*\\ th element of *o*, assuming that *o* was returned by :c:" "func:`PySequence_Fast`, *o* is not ``NULL``, and that *i* is within bounds." msgstr "" +"Retorna o elemento *i* de *o*, presumindo que *o* foi retornado por :c:func:" +"`PySequence_Fast`, que *o* seja ``NULL``, e que *i* esteja nos limites." #: ../../c-api/sequence.rst:163 msgid "" "Return the underlying array of PyObject pointers. Assumes that *o* was " "returned by :c:func:`PySequence_Fast` and *o* is not ``NULL``." msgstr "" +"Retorna o vetor subjacente de ponteiros PyObject. Presume que *o* foi " +"retornado por :c:func:`PySequence_Fast` e que *o* não seja ``NULL``." #: ../../c-api/sequence.rst:166 msgid "" @@ -224,6 +261,9 @@ msgid "" "So, only use the underlying array pointer in contexts where the sequence " "cannot change." msgstr "" +"Note que, se uma lista for redimensionada, a realocação poderá reposicionar " +"o vetor de itens. Portanto, só use o ponteiro de vetor subjacente em " +"contextos onde a sequência não mudará." #: ../../c-api/sequence.rst:173 msgid "" @@ -232,6 +272,9 @@ msgid "" "`PySequence_Check` on *o* is true and without adjustment for negative " "indices." msgstr "" +"Retorna o elemento *i* de *o*, ou ``NULL`` em caso de falha. É uma forma " +"mais rápida de :c:func:`PySequence_GetItem`, mas sem verificar se :c:func:" +"`PySequence_Check` em *o* é verdadeiro e sem ajustar índices negativos." #: ../../c-api/sequence.rst:21 ../../c-api/sequence.rst:123 msgid "built-in function" diff --git a/c-api/set.po b/c-api/set.po index 33518301f..883fb1dd9 100644 --- a/c-api/set.po +++ b/c-api/set.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Vitor Buxbaum Orlandi, 2021 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/slice.po b/c-api/slice.po index 68198e235..18782489f 100644 --- a/c-api/slice.po +++ b/c-api/slice.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-12 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -125,10 +124,34 @@ msgstr "" "invocação deve ser substituída por uma combinação de :c:func:" "`PySlice_Unpack` e :c:func:`PySlice_AdjustIndices` sendo ::" +#: ../../c-api/slice.rst:64 +msgid "" +"if (PySlice_GetIndicesEx(slice, length, &start, &stop, &step, &slicelength) " +"< 0) {\n" +" // return error\n" +"}" +msgstr "" +"if (PySlice_GetIndicesEx(slice, length, &start, &stop, &step, &slicelength) " +"< 0) {\n" +" // retorna erro\n" +"}" + #: ../../c-api/slice.rst:68 msgid "is replaced by ::" msgstr "substituído por ::" +#: ../../c-api/slice.rst:70 +msgid "" +"if (PySlice_Unpack(slice, &start, &stop, &step) < 0) {\n" +" // return error\n" +"}\n" +"slicelength = PySlice_AdjustIndices(length, &start, &stop, step);" +msgstr "" +"if (PySlice_Unpack(slice, &start, &stop, &step) < 0) {\n" +" // retorna erro\n" +"}\n" +"slicelength = PySlice_AdjustIndices(length, &start, &stop, step);" + #: ../../c-api/slice.rst:79 msgid "" "If ``Py_LIMITED_API`` is not set or set to the value between ``0x03050400`` " @@ -198,12 +221,20 @@ msgstr "Objeto Ellipsis" #: ../../c-api/slice.rst:123 msgid "" +"The type of Python :const:`Ellipsis` object. Same as :class:`types." +"EllipsisType` in the Python layer." +msgstr "" +"O tipo do objeto Python :const:`Ellipsis`. O mesmo que :class:`types." +"EllipsisType` na camada Python." + +#: ../../c-api/slice.rst:129 +msgid "" "The Python ``Ellipsis`` object. This object has no methods. Like :c:data:" "`Py_None`, it is an :term:`immortal` singleton object." msgstr "" "O objeto Python ``Ellipsis``. Este objeto não tem métodos. Como :c:data:" "`Py_None`, é um objeto singleton :term:`imortal`." -#: ../../c-api/slice.rst:126 +#: ../../c-api/slice.rst:132 msgid ":c:data:`Py_Ellipsis` is immortal." msgstr ":c:data:`Py_Ellipsis` é imortal." diff --git a/c-api/stable.po b/c-api/stable.po index bbaafb0c5..3ad18f28b 100644 --- a/c-api/stable.po +++ b/c-api/stable.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2023 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-21 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -149,13 +148,13 @@ msgstr "API C Limitada" #: ../../c-api/stable.rst:67 msgid "" "Python 3.2 introduced the *Limited API*, a subset of Python's C API. " -"Extensions that only use the Limited API can be compiled once and work with " -"multiple versions of Python. Contents of the Limited API are :ref:`listed " +"Extensions that only use the Limited API can be compiled once and be loaded " +"on multiple versions of Python. Contents of the Limited API are :ref:`listed " "below `." msgstr "" "Python 3.2 introduziu a *API Limitada*, um subconjunto da API C do Python. " -"Extensões que apenas usam o Limited API podem ser compiladas uma vez e " -"funcionar com várias versões do Python. Os conteúdos da API Limitada estão :" +"Extensões que apenas usam o Limited API podem ser compiladas uma vez e ser " +"carregadas em várias versões do Python. Os conteúdos da API Limitada estão :" "ref:`listados abaixo `." #: ../../c-api/stable.rst:74 @@ -170,15 +169,14 @@ msgstr "" msgid "" "Define ``Py_LIMITED_API`` to the value of :c:macro:`PY_VERSION_HEX` " "corresponding to the lowest Python version your extension supports. The " -"extension will work without recompilation with all Python 3 releases from " -"the specified one onward, and can use Limited API introduced up to that " -"version." +"extension will be ABI-compatible with all Python 3 releases from the " +"specified one onward, and can use Limited API introduced up to that version." msgstr "" "Defina ``Py_LIMITED_API`` com o valor de :c:macro:`PY_VERSION_HEX` " "correspondente à versão mais baixa do Python que sua extensão suporta. A " -"extensão funcionará sem recompilação com todas as versões do Python 3 a " -"partir da especificada e poderá usar a API Limitada introduzida até aquela " -"versão." +"extensão terá compatibilidade com a ABI de todas as versões do Python 3 a " +"partir daquela especificada, e poderá usar a API Limitada introduzida até " +"aquela versão." #: ../../c-api/stable.rst:83 msgid "" @@ -206,12 +204,27 @@ msgstr "ABI Estável" #: ../../c-api/stable.rst:96 msgid "" "To enable this, Python provides a *Stable ABI*: a set of symbols that will " -"remain compatible across Python 3.x versions." +"remain ABI-compatible across Python 3.x versions." msgstr "" -"Para habilitar isso, o Python fornece uma *ABI estável*: um conjunto de " -"símbolos que permanecerão compatíveis em todas as versões do Python 3.x." +"Para habilitar isso, o Python fornece uma *ABI Estável*: um conjunto de " +"símbolos que permanecerão compatíveis com ABI em todas as versões do Python " +"3.x." -#: ../../c-api/stable.rst:99 +#: ../../c-api/stable.rst:101 +msgid "" +"The Stable ABI prevents ABI issues, like linker errors due to missing " +"symbols or data corruption due to changes in structure layouts or function " +"signatures. However, other changes in Python can change the *behavior* of " +"extensions. See Python's Backwards Compatibility Policy (:pep:`387`) for " +"details." +msgstr "" +"O ABI Estável previne problemas de ABI, como erros de ligador devido a " +"símbolos ausentes ou corrupção de dados devido a alterações em layouts de " +"estrutura ou assinaturas de função. No entanto, outras alterações no Python " +"podem alterar o *comportamento* das extensões. Veja a Política de " +"Retrocompatibilidade do Python (:pep:`387`) para detalhes." + +#: ../../c-api/stable.rst:107 msgid "" "The Stable ABI contains symbols exposed in the :ref:`Limited API `, but also other ones – for example, functions necessary to support " @@ -221,7 +234,7 @@ msgstr "" "api>`, mas também outros -- por exemplo, funções necessárias para suportar " "versões mais antigas da API Limitada." -#: ../../c-api/stable.rst:103 +#: ../../c-api/stable.rst:111 msgid "" "On Windows, extensions that use the Stable ABI should be linked against " "``python3.dll`` rather than a version-specific library such as ``python39." @@ -231,7 +244,7 @@ msgstr "" "``python3.dll`` em vez de uma biblioteca específica de versão, como " "``python39.dll``." -#: ../../c-api/stable.rst:107 +#: ../../c-api/stable.rst:115 msgid "" "On some platforms, Python will look for and load shared library files named " "with the ``abi3`` tag (e.g. ``mymodule.abi3.so``). It does not check if such " @@ -247,7 +260,7 @@ msgstr "" "com a API Limitada 3.10+ não sejam instaladas em versões mais baixas do " "Python." -#: ../../c-api/stable.rst:114 +#: ../../c-api/stable.rst:122 msgid "" "All functions in the Stable ABI are present as functions in Python's shared " "library, not solely as macros. This makes them usable from languages that " @@ -257,11 +270,11 @@ msgstr "" "compartilhada do Python, não apenas como macros. Isso as torna utilizáveis " "em linguagens que não utilizam o pré-processador C." -#: ../../c-api/stable.rst:120 +#: ../../c-api/stable.rst:128 msgid "Limited API Scope and Performance" msgstr "Escopo e Desempenho da API Limitada" -#: ../../c-api/stable.rst:122 +#: ../../c-api/stable.rst:130 msgid "" "The goal for the Limited API is to allow everything that is possible with " "the full C API, but possibly with a performance penalty." @@ -269,7 +282,7 @@ msgstr "" "O objetivo da API Limitada é permitir tudo o que é possível com a API C " "completa, mas possivelmente com uma penalidade de desempenho." -#: ../../c-api/stable.rst:125 +#: ../../c-api/stable.rst:133 msgid "" "For example, while :c:func:`PyList_GetItem` is available, its “unsafe” macro " "variant :c:func:`PyList_GET_ITEM` is not. The macro can be faster because it " @@ -280,7 +293,7 @@ msgstr "" "mais rápida porque pode depender de detalhes de implementação específicos da " "versão do objeto da lista." -#: ../../c-api/stable.rst:130 +#: ../../c-api/stable.rst:138 msgid "" "Without ``Py_LIMITED_API`` defined, some C API functions are inlined or " "replaced by macros. Defining ``Py_LIMITED_API`` disables this inlining, " @@ -292,7 +305,7 @@ msgstr "" "desativa esse inline, permitindo estabilidade à medida que as estruturas de " "dados do Python são aprimoradas, mas possivelmente reduzindo o desempenho." -#: ../../c-api/stable.rst:135 +#: ../../c-api/stable.rst:143 msgid "" "By leaving out the ``Py_LIMITED_API`` definition, it is possible to compile " "a Limited API extension with a version-specific ABI. This can improve " @@ -309,11 +322,11 @@ msgstr "" "disponível -- por exemplo, para pré-lançamentos de uma próxima versão do " "Python." -#: ../../c-api/stable.rst:144 +#: ../../c-api/stable.rst:152 msgid "Limited API Caveats" msgstr "Limitações da API Limitada" -#: ../../c-api/stable.rst:146 +#: ../../c-api/stable.rst:154 msgid "" "Note that compiling with ``Py_LIMITED_API`` is *not* a complete guarantee " "that code conforms to the :ref:`Limited API ` or the :ref:" @@ -326,7 +339,7 @@ msgstr "" "apenas definições, mas uma API também inclui outras questões, como semântica " "esperada." -#: ../../c-api/stable.rst:151 +#: ../../c-api/stable.rst:159 msgid "" "One issue that ``Py_LIMITED_API`` does not guard against is calling a " "function with arguments that are invalid in a lower Python version. For " @@ -342,7 +355,7 @@ msgstr "" "argumento será usado diretamente, causando uma referência ``NULL`` e uma " "falha. Um argumento similar funciona para campos de estruturas." -#: ../../c-api/stable.rst:158 +#: ../../c-api/stable.rst:166 msgid "" "Another issue is that some struct fields are currently not hidden when " "``Py_LIMITED_API`` is defined, even though they're part of the Limited API." @@ -351,7 +364,7 @@ msgstr "" "quando ``Py_LIMITED_API`` é definido, mesmo que eles façam parte da API " "Limitada." -#: ../../c-api/stable.rst:161 +#: ../../c-api/stable.rst:169 msgid "" "For these reasons, we recommend testing an extension with *all* minor Python " "versions it supports, and preferably to build with the *lowest* such version." @@ -360,7 +373,7 @@ msgstr "" "menores do Python que ela oferece suporte e, preferencialmente, construir " "com a versão *mais baixa* dessas." -#: ../../c-api/stable.rst:164 +#: ../../c-api/stable.rst:172 msgid "" "We also recommend reviewing documentation of all used API to check if it is " "explicitly part of the Limited API. Even with ``Py_LIMITED_API`` defined, a " @@ -372,7 +385,7 @@ msgstr "" "definição de ``Py_LIMITED_API``, algumas declarações privadas são expostas " "por razões técnicas (ou até mesmo acidentalmente, como bugs)." -#: ../../c-api/stable.rst:169 +#: ../../c-api/stable.rst:177 msgid "" "Also note that the Limited API is not necessarily stable: compiling with " "``Py_LIMITED_API`` with Python 3.8 means that the extension will run with " @@ -386,11 +399,11 @@ msgstr "" "Python 3.12. Em particular, partes da API Limitada podem ser descontinuadas " "e removidas, desde que a ABI Estável permaneça estável." -#: ../../c-api/stable.rst:179 +#: ../../c-api/stable.rst:187 msgid "Platform Considerations" msgstr "Considerações da plataforma" -#: ../../c-api/stable.rst:181 +#: ../../c-api/stable.rst:189 msgid "" "ABI stability depends not only on Python, but also on the compiler used, " "lower-level libraries and compiler options. For the purposes of the :ref:" @@ -403,7 +416,7 @@ msgstr "" "\"plataforma\". Geralmente, eles dependem do tipo de sistema operacional e " "da arquitetura do processador." -#: ../../c-api/stable.rst:186 +#: ../../c-api/stable.rst:194 msgid "" "It is the responsibility of each particular distributor of Python to ensure " "that all Python versions on a particular platform are built in a way that " @@ -416,11 +429,11 @@ msgstr "" "e macOS disponibilizadas pela ``python.org`` e por muitos distribuidores " "terceiros." -#: ../../c-api/stable.rst:196 +#: ../../c-api/stable.rst:204 msgid "Contents of Limited API" msgstr "Conteúdo da API Limitada" -#: ../../c-api/stable.rst:199 +#: ../../c-api/stable.rst:207 msgid "" "Currently, the :ref:`Limited API ` includes the following " "items:" diff --git a/c-api/structures.po b/c-api/structures.po index 4441e66bb..fe9c6d4ff 100644 --- a/c-api/structures.po +++ b/c-api/structures.po @@ -1,34 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2023 -# Rodrigo Cendamore, 2023 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-03-14 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../c-api/structures.rst:6 msgid "Common Object Structures" -msgstr "Estruturas Comuns de Objetos" +msgstr "Estruturas comuns de objetos" #: ../../c-api/structures.rst:8 msgid "" @@ -80,6 +77,11 @@ msgid "" "Access to the members must be done by using the macros :c:macro:" "`Py_REFCNT`, :c:macro:`Py_TYPE`, and :c:macro:`Py_SIZE`." msgstr "" +"Esta é uma extensão de :c:type:`PyObject` que adiciona o campo :c:member:" +"`~PyVarObject.ob_size`. Isso é usado apenas para objetos que têm alguma " +"noção de *comprimento*. Esse tipo não costuma aparecer na API Python/C. O " +"acesso aos membros deve ser feito através das macros :c:macro:`Py_REFCNT`, :" +"c:macro:`Py_TYPE`, e :c:macro:`Py_SIZE`." #: ../../c-api/structures.rst:47 msgid "" @@ -89,6 +91,10 @@ msgstr "" "Este é um macro usado ao declarar novos tipos que representam objetos sem " "comprimento variável. O macro PyObject_HEAD se expande para::" +#: ../../c-api/structures.rst:50 +msgid "PyObject ob_base;" +msgstr "" + #: ../../c-api/structures.rst:52 msgid "See documentation of :c:type:`PyObject` above." msgstr "Veja documentação de :c:type:`PyObject` acima." @@ -100,87 +106,102 @@ msgid "" "expands to::" msgstr "" +#: ../../c-api/structures.rst:61 +msgid "PyVarObject ob_base;" +msgstr "" + #: ../../c-api/structures.rst:63 msgid "See documentation of :c:type:`PyVarObject` above." msgstr "Veja documentação de :c:type:`PyVarObject` acima." #: ../../c-api/structures.rst:68 msgid "" +"The base class of all other objects, the same as :class:`object` in Python." +msgstr "" + +#: ../../c-api/structures.rst:73 +msgid "" "Test if the *x* object is the *y* object, the same as ``x is y`` in Python." msgstr "" "Testa se o objeto *x* é o objeto *y*, o mesmo que ``x is y`` em Python." -#: ../../c-api/structures.rst:75 +#: ../../c-api/structures.rst:80 msgid "" "Test if an object is the ``None`` singleton, the same as ``x is None`` in " "Python." msgstr "" -#: ../../c-api/structures.rst:83 +#: ../../c-api/structures.rst:88 msgid "" "Test if an object is the ``True`` singleton, the same as ``x is True`` in " "Python." msgstr "" -#: ../../c-api/structures.rst:91 +#: ../../c-api/structures.rst:96 msgid "" "Test if an object is the ``False`` singleton, the same as ``x is False`` in " "Python." msgstr "" -#: ../../c-api/structures.rst:99 +#: ../../c-api/structures.rst:104 msgid "Get the type of the Python object *o*." msgstr "" -#: ../../c-api/structures.rst:101 +#: ../../c-api/structures.rst:106 msgid "Return a :term:`borrowed reference`." msgstr "" -#: ../../c-api/structures.rst:103 +#: ../../c-api/structures.rst:108 msgid "Use the :c:func:`Py_SET_TYPE` function to set an object type." msgstr "" -#: ../../c-api/structures.rst:105 +#: ../../c-api/structures.rst:110 msgid "" ":c:func:`Py_TYPE()` is changed to an inline static function. The parameter " "type is no longer :c:expr:`const PyObject*`." msgstr "" -#: ../../c-api/structures.rst:112 +#: ../../c-api/structures.rst:117 msgid "" "Return non-zero if the object *o* type is *type*. Return zero otherwise. " "Equivalent to: ``Py_TYPE(o) == type``." msgstr "" -#: ../../c-api/structures.rst:120 +#: ../../c-api/structures.rst:125 msgid "Set the object *o* type to *type*." msgstr "" -#: ../../c-api/structures.rst:127 +#: ../../c-api/structures.rst:132 msgid "Get the size of the Python object *o*." msgstr "" -#: ../../c-api/structures.rst:129 +#: ../../c-api/structures.rst:134 msgid "Use the :c:func:`Py_SET_SIZE` function to set an object size." msgstr "" -#: ../../c-api/structures.rst:131 +#: ../../c-api/structures.rst:136 msgid "" ":c:func:`Py_SIZE()` is changed to an inline static function. The parameter " "type is no longer :c:expr:`const PyVarObject*`." msgstr "" -#: ../../c-api/structures.rst:138 +#: ../../c-api/structures.rst:143 msgid "Set the object *o* size to *size*." msgstr "" -#: ../../c-api/structures.rst:145 +#: ../../c-api/structures.rst:150 msgid "" "This is a macro which expands to initialization values for a new :c:type:" "`PyObject` type. This macro expands to::" msgstr "" -#: ../../c-api/structures.rst:154 +#: ../../c-api/structures.rst:153 +msgid "" +"_PyObject_EXTRA_INIT\n" +"1, type," +msgstr "" + +#: ../../c-api/structures.rst:159 msgid "" "This is a macro which expands to initialization values for a new :c:type:" "`PyVarObject` type, including the :c:member:`~PyVarObject.ob_size` field. " @@ -188,10 +209,16 @@ msgid "" msgstr "" #: ../../c-api/structures.rst:163 +msgid "" +"_PyObject_EXTRA_INIT\n" +"1, type, size," +msgstr "" + +#: ../../c-api/structures.rst:168 msgid "Implementing functions and methods" msgstr "" -#: ../../c-api/structures.rst:167 +#: ../../c-api/structures.rst:172 msgid "" "Type of the functions used to implement most Python callables in C. " "Functions of this type take two :c:expr:`PyObject*` parameters and return " @@ -201,60 +228,97 @@ msgid "" "reference." msgstr "" -#: ../../c-api/structures.rst:174 +#: ../../c-api/structures.rst:179 msgid "The function signature is::" msgstr "A assinatura da função é::" #: ../../c-api/structures.rst:181 msgid "" +"PyObject *PyCFunction(PyObject *self,\n" +" PyObject *args);" +msgstr "" + +#: ../../c-api/structures.rst:186 +msgid "" "Type of the functions used to implement Python callables in C with " "signature :ref:`METH_VARARGS | METH_KEYWORDS `. " "The function signature is::" msgstr "" -#: ../../c-api/structures.rst:192 +#: ../../c-api/structures.rst:190 +msgid "" +"PyObject *PyCFunctionWithKeywords(PyObject *self,\n" +" PyObject *args,\n" +" PyObject *kwargs);" +msgstr "" + +#: ../../c-api/structures.rst:197 msgid "" "Type of the functions used to implement Python callables in C with " "signature :c:macro:`METH_FASTCALL`. The function signature is::" msgstr "" -#: ../../c-api/structures.rst:202 +#: ../../c-api/structures.rst:201 +msgid "" +"PyObject *PyCFunctionFast(PyObject *self,\n" +" PyObject *const *args,\n" +" Py_ssize_t nargs);" +msgstr "" + +#: ../../c-api/structures.rst:207 msgid "" "Type of the functions used to implement Python callables in C with " "signature :ref:`METH_FASTCALL | METH_KEYWORDS `. The function signature is::" msgstr "" -#: ../../c-api/structures.rst:213 +#: ../../c-api/structures.rst:211 +msgid "" +"PyObject *PyCFunctionFastWithKeywords(PyObject *self,\n" +" PyObject *const *args,\n" +" Py_ssize_t nargs,\n" +" PyObject *kwnames);" +msgstr "" + +#: ../../c-api/structures.rst:218 msgid "" "Type of the functions used to implement Python callables in C with " "signature :ref:`METH_METHOD | METH_FASTCALL | METH_KEYWORDS `. The function signature is::" msgstr "" -#: ../../c-api/structures.rst:228 +#: ../../c-api/structures.rst:222 +msgid "" +"PyObject *PyCMethod(PyObject *self,\n" +" PyTypeObject *defining_class,\n" +" PyObject *const *args,\n" +" Py_ssize_t nargs,\n" +" PyObject *kwnames)" +msgstr "" + +#: ../../c-api/structures.rst:233 msgid "" "Structure used to describe a method of an extension type. This structure " "has four fields:" msgstr "" -#: ../../c-api/structures.rst:233 +#: ../../c-api/structures.rst:238 msgid "Name of the method." -msgstr "" +msgstr "Nome do método." -#: ../../c-api/structures.rst:237 +#: ../../c-api/structures.rst:242 msgid "Pointer to the C implementation." msgstr "" -#: ../../c-api/structures.rst:241 +#: ../../c-api/structures.rst:246 msgid "Flags bits indicating how the call should be constructed." msgstr "" -#: ../../c-api/structures.rst:245 +#: ../../c-api/structures.rst:250 msgid "Points to the contents of the docstring." msgstr "" -#: ../../c-api/structures.rst:247 +#: ../../c-api/structures.rst:252 msgid "" "The :c:member:`~PyMethodDef.ml_meth` is a C function pointer. The functions " "may be of different types, but they always return :c:expr:`PyObject*`. If " @@ -264,18 +328,18 @@ msgid "" "implementation uses the specific C type of the *self* object." msgstr "" -#: ../../c-api/structures.rst:255 +#: ../../c-api/structures.rst:260 msgid "" "The :c:member:`~PyMethodDef.ml_flags` field is a bitfield which can include " "the following flags. The individual flags indicate either a calling " "convention or a binding convention." msgstr "" -#: ../../c-api/structures.rst:260 +#: ../../c-api/structures.rst:265 msgid "There are these calling conventions:" msgstr "" -#: ../../c-api/structures.rst:264 +#: ../../c-api/structures.rst:269 msgid "" "This is the typical calling convention, where the methods have the type :c:" "type:`PyCFunction`. The function expects two :c:expr:`PyObject*` values. The " @@ -285,7 +349,7 @@ msgid "" "func:`PyArg_ParseTuple` or :c:func:`PyArg_UnpackTuple`." msgstr "" -#: ../../c-api/structures.rst:274 +#: ../../c-api/structures.rst:279 msgid "" "Can only be used in certain combinations with other flags: :ref:" "`METH_VARARGS | METH_KEYWORDS `, :ref:" @@ -294,11 +358,11 @@ msgid "" "METH_KEYWORDS>`." msgstr "" -#: ../../c-api/structures.rst:282 +#: ../../c-api/structures.rst:287 msgid ":c:expr:`METH_VARARGS | METH_KEYWORDS`" -msgstr "" +msgstr ":c:expr:`METH_VARARGS | METH_KEYWORDS`" -#: ../../c-api/structures.rst:283 +#: ../../c-api/structures.rst:288 msgid "" "Methods with these flags must be of type :c:type:`PyCFunctionWithKeywords`. " "The function expects three parameters: *self*, *args*, *kwargs* where " @@ -307,7 +371,7 @@ msgid "" "using :c:func:`PyArg_ParseTupleAndKeywords`." msgstr "" -#: ../../c-api/structures.rst:292 +#: ../../c-api/structures.rst:297 msgid "" "Fast calling convention supporting only positional arguments. The methods " "have the type :c:type:`PyCFunctionFast`. The first parameter is *self*, the " @@ -316,15 +380,15 @@ msgid "" "the array)." msgstr "" -#: ../../c-api/structures.rst:302 +#: ../../c-api/structures.rst:307 msgid "``METH_FASTCALL`` is now part of the :ref:`stable ABI `." msgstr "" -#: ../../c-api/structures.rst:307 +#: ../../c-api/structures.rst:312 msgid ":c:expr:`METH_FASTCALL | METH_KEYWORDS`" -msgstr "" +msgstr ":c:expr:`METH_FASTCALL | METH_KEYWORDS`" -#: ../../c-api/structures.rst:308 +#: ../../c-api/structures.rst:313 msgid "" "Extension of :c:macro:`METH_FASTCALL` supporting also keyword arguments, " "with methods of type :c:type:`PyCFunctionFastWithKeywords`. Keyword " @@ -336,17 +400,17 @@ msgid "" "the positional arguments." msgstr "" -#: ../../c-api/structures.rst:323 +#: ../../c-api/structures.rst:328 msgid "" "Can only be used in the combination with other flags: :ref:`METH_METHOD | " "METH_FASTCALL | METH_KEYWORDS `." msgstr "" -#: ../../c-api/structures.rst:329 +#: ../../c-api/structures.rst:334 msgid ":c:expr:`METH_METHOD | METH_FASTCALL | METH_KEYWORDS`" -msgstr "" +msgstr ":c:expr:`METH_METHOD | METH_FASTCALL | METH_KEYWORDS`" -#: ../../c-api/structures.rst:330 +#: ../../c-api/structures.rst:335 msgid "" "Extension of :ref:`METH_FASTCALL | METH_KEYWORDS ` supporting the *defining class*, that is, the class that " @@ -354,14 +418,14 @@ msgid "" "``Py_TYPE(self)``." msgstr "" -#: ../../c-api/structures.rst:335 +#: ../../c-api/structures.rst:340 msgid "" "The method needs to be of type :c:type:`PyCMethod`, the same as for " "``METH_FASTCALL | METH_KEYWORDS`` with ``defining_class`` argument added " "after ``self``." msgstr "" -#: ../../c-api/structures.rst:344 +#: ../../c-api/structures.rst:349 msgid "" "Methods without parameters don't need to check whether arguments are given " "if they are listed with the :c:macro:`METH_NOARGS` flag. They need to be of " @@ -370,13 +434,13 @@ msgid "" "the second parameter will be ``NULL``." msgstr "" -#: ../../c-api/structures.rst:350 +#: ../../c-api/structures.rst:355 msgid "" "The function must have 2 parameters. Since the second parameter is unused, :" "c:macro:`Py_UNUSED` can be used to prevent a compiler warning." msgstr "" -#: ../../c-api/structures.rst:356 +#: ../../c-api/structures.rst:361 msgid "" "Methods with a single object argument can be listed with the :c:macro:" "`METH_O` flag, instead of invoking :c:func:`PyArg_ParseTuple` with a " @@ -385,7 +449,7 @@ msgid "" "single argument." msgstr "" -#: ../../c-api/structures.rst:362 +#: ../../c-api/structures.rst:367 msgid "" "These two constants are not used to indicate the calling convention but the " "binding when use with methods of classes. These may not be used for " @@ -393,27 +457,27 @@ msgid "" "any given method." msgstr "" -#: ../../c-api/structures.rst:372 +#: ../../c-api/structures.rst:377 msgid "" "The method will be passed the type object as the first parameter rather than " "an instance of the type. This is used to create *class methods*, similar to " "what is created when using the :func:`classmethod` built-in function." msgstr "" -#: ../../c-api/structures.rst:382 +#: ../../c-api/structures.rst:387 msgid "" "The method will be passed ``NULL`` as the first parameter rather than an " "instance of the type. This is used to create *static methods*, similar to " "what is created when using the :func:`staticmethod` built-in function." msgstr "" -#: ../../c-api/structures.rst:386 +#: ../../c-api/structures.rst:391 msgid "" "One other constant controls whether a method is loaded in place of another " "definition with the same method name." msgstr "" -#: ../../c-api/structures.rst:392 +#: ../../c-api/structures.rst:397 msgid "" "The method will be loaded in place of existing definitions. Without " "*METH_COEXIST*, the default is to skip repeated definitions. Since slot " @@ -426,20 +490,20 @@ msgid "" "wrapper object calls." msgstr "" -#: ../../c-api/structures.rst:404 +#: ../../c-api/structures.rst:409 msgid "" "Turn *ml* into a Python :term:`callable` object. The caller must ensure that " "*ml* outlives the :term:`callable`. Typically, *ml* is defined as a static " "variable." msgstr "" -#: ../../c-api/structures.rst:408 +#: ../../c-api/structures.rst:413 msgid "" "The *self* parameter will be passed as the *self* argument to the C function " "in ``ml->ml_meth`` when invoked. *self* can be ``NULL``." msgstr "" -#: ../../c-api/structures.rst:412 +#: ../../c-api/structures.rst:417 msgid "" "The :term:`callable` object's ``__module__`` attribute can be set from the " "given *module* argument. *module* should be a Python string, which will be " @@ -447,71 +511,71 @@ msgid "" "can be set to :const:`None` or ``NULL``." msgstr "" -#: ../../c-api/structures.rst:418 +#: ../../c-api/structures.rst:423 msgid ":attr:`function.__module__`" -msgstr "" +msgstr ":attr:`function.__module__`" -#: ../../c-api/structures.rst:420 +#: ../../c-api/structures.rst:425 msgid "" "The *cls* parameter will be passed as the *defining_class* argument to the C " "function. Must be set if :c:macro:`METH_METHOD` is set on ``ml->ml_flags``." msgstr "" -#: ../../c-api/structures.rst:429 +#: ../../c-api/structures.rst:434 msgid "Equivalent to ``PyCMethod_New(ml, self, module, NULL)``." -msgstr "" +msgstr "Equivalente a ``PyCMethod_New(ml, self, module, NULL)``." -#: ../../c-api/structures.rst:434 +#: ../../c-api/structures.rst:439 msgid "Equivalent to ``PyCMethod_New(ml, self, NULL, NULL)``." -msgstr "" +msgstr "Equivalente a ``PyCMethod_New(ml, self, NULL, NULL)``." -#: ../../c-api/structures.rst:438 +#: ../../c-api/structures.rst:443 msgid "Accessing attributes of extension types" msgstr "" -#: ../../c-api/structures.rst:442 +#: ../../c-api/structures.rst:447 msgid "" "Structure which describes an attribute of a type which corresponds to a C " "struct member. When defining a class, put a NULL-terminated array of these " "structures in the :c:member:`~PyTypeObject.tp_members` slot." msgstr "" -#: ../../c-api/structures.rst:447 +#: ../../c-api/structures.rst:452 msgid "Its fields are, in order:" msgstr "" -#: ../../c-api/structures.rst:451 +#: ../../c-api/structures.rst:456 msgid "" "Name of the member. A NULL value marks the end of a ``PyMemberDef[]`` array." msgstr "" -#: ../../c-api/structures.rst:454 +#: ../../c-api/structures.rst:459 msgid "The string should be static, no copy is made of it." msgstr "" -#: ../../c-api/structures.rst:458 +#: ../../c-api/structures.rst:463 msgid "" "The type of the member in the C struct. See :ref:`PyMemberDef-types` for the " "possible values." msgstr "" -#: ../../c-api/structures.rst:463 +#: ../../c-api/structures.rst:468 msgid "" "The offset in bytes that the member is located on the type’s object struct." msgstr "" -#: ../../c-api/structures.rst:467 +#: ../../c-api/structures.rst:472 msgid "" "Zero or more of the :ref:`PyMemberDef-flags`, combined using bitwise OR." msgstr "" -#: ../../c-api/structures.rst:471 +#: ../../c-api/structures.rst:476 msgid "" "The docstring, or NULL. The string should be static, no copy is made of it. " "Typically, it is defined using :c:macro:`PyDoc_STR`." msgstr "" -#: ../../c-api/structures.rst:475 +#: ../../c-api/structures.rst:480 msgid "" "By default (when :c:member:`~PyMemberDef.flags` is ``0``), members allow " "both read and write access. Use the :c:macro:`Py_READONLY` flag for read-" @@ -520,7 +584,7 @@ msgid "" "`T_OBJECT`) members can be deleted." msgstr "" -#: ../../c-api/structures.rst:484 +#: ../../c-api/structures.rst:489 msgid "" "For heap-allocated types (created using :c:func:`PyType_FromSpec` or " "similar), ``PyMemberDef`` may contain a definition for the special member " @@ -529,11 +593,20 @@ msgid "" "``Py_T_PYSSIZET`` and ``Py_READONLY``, for example::" msgstr "" -#: ../../c-api/structures.rst:496 +#: ../../c-api/structures.rst:495 +msgid "" +"static PyMemberDef spam_type_members[] = {\n" +" {\"__vectorcalloffset__\", Py_T_PYSSIZET,\n" +" offsetof(Spam_object, vectorcall), Py_READONLY},\n" +" {NULL} /* Sentinel */\n" +"};" +msgstr "" + +#: ../../c-api/structures.rst:501 msgid "(You may need to ``#include `` for :c:func:`!offsetof`.)" msgstr "" -#: ../../c-api/structures.rst:498 +#: ../../c-api/structures.rst:503 msgid "" "The legacy offsets :c:member:`~PyTypeObject.tp_dictoffset` and :c:member:" "`~PyTypeObject.tp_weaklistoffset` can be defined similarly using " @@ -542,77 +615,77 @@ msgid "" "and :c:macro:`Py_TPFLAGS_MANAGED_WEAKREF` instead." msgstr "" -#: ../../c-api/structures.rst:506 +#: ../../c-api/structures.rst:511 msgid "" "``PyMemberDef`` is always available. Previously, it required including " "``\"structmember.h\"``." msgstr "" -#: ../../c-api/structures.rst:511 +#: ../../c-api/structures.rst:516 msgid "" "Get an attribute belonging to the object at address *obj_addr*. The " "attribute is described by ``PyMemberDef`` *m*. Returns ``NULL`` on error." msgstr "" -#: ../../c-api/structures.rst:517 +#: ../../c-api/structures.rst:522 msgid "" "``PyMember_GetOne`` is always available. Previously, it required including " "``\"structmember.h\"``." msgstr "" -#: ../../c-api/structures.rst:522 +#: ../../c-api/structures.rst:527 msgid "" "Set an attribute belonging to the object at address *obj_addr* to object " "*o*. The attribute to set is described by ``PyMemberDef`` *m*. Returns " "``0`` if successful and a negative value on failure." msgstr "" -#: ../../c-api/structures.rst:528 +#: ../../c-api/structures.rst:533 msgid "" "``PyMember_SetOne`` is always available. Previously, it required including " "``\"structmember.h\"``." msgstr "" -#: ../../c-api/structures.rst:534 +#: ../../c-api/structures.rst:539 msgid "Member flags" msgstr "" -#: ../../c-api/structures.rst:536 +#: ../../c-api/structures.rst:541 msgid "The following flags can be used with :c:member:`PyMemberDef.flags`:" msgstr "" -#: ../../c-api/structures.rst:540 +#: ../../c-api/structures.rst:545 msgid "Not writable." msgstr "" -#: ../../c-api/structures.rst:544 +#: ../../c-api/structures.rst:549 msgid "" "Emit an ``object.__getattr__`` :ref:`audit event ` before " "reading." msgstr "" -#: ../../c-api/structures.rst:549 +#: ../../c-api/structures.rst:554 msgid "" "Indicates that the :c:member:`~PyMemberDef.offset` of this ``PyMemberDef`` " "entry indicates an offset from the subclass-specific data, rather than from " "``PyObject``." msgstr "" -#: ../../c-api/structures.rst:553 +#: ../../c-api/structures.rst:558 msgid "" "Can only be used as part of :c:member:`Py_tp_members ` :c:type:`slot ` when creating a class using " "negative :c:member:`~PyType_Spec.basicsize`. It is mandatory in that case." msgstr "" -#: ../../c-api/structures.rst:558 +#: ../../c-api/structures.rst:563 msgid "" "This flag is only used in :c:type:`PyType_Slot`. When setting :c:member:" "`~PyTypeObject.tp_members` during class creation, Python clears it and sets :" "c:member:`PyMemberDef.offset` to the offset from the ``PyObject`` struct." msgstr "" -#: ../../c-api/structures.rst:570 +#: ../../c-api/structures.rst:575 msgid "" "The :c:macro:`!RESTRICTED`, :c:macro:`!READ_RESTRICTED` and :c:macro:`!" "WRITE_RESTRICTED` macros available with ``#include \"structmember.h\"`` are " @@ -621,7 +694,7 @@ msgid "" "nothing." msgstr "" -#: ../../c-api/structures.rst:581 +#: ../../c-api/structures.rst:586 msgid "" "The :c:macro:`!READONLY` macro was renamed to :c:macro:`Py_READONLY`. The :c:" "macro:`!PY_AUDIT_READ` macro was renamed with the ``Py_`` prefix. The new " @@ -630,11 +703,11 @@ msgid "" "names." msgstr "" -#: ../../c-api/structures.rst:590 +#: ../../c-api/structures.rst:595 msgid "Member types" msgstr "" -#: ../../c-api/structures.rst:592 +#: ../../c-api/structures.rst:597 msgid "" ":c:member:`PyMemberDef.type` can be one of the following macros " "corresponding to various C types. When the member is accessed in Python, it " @@ -643,147 +716,149 @@ msgid "" "exception such as :exc:`TypeError` or :exc:`ValueError` is raised." msgstr "" -#: ../../c-api/structures.rst:600 +#: ../../c-api/structures.rst:605 msgid "" "Unless marked (D), attributes defined this way cannot be deleted using e.g. :" "keyword:`del` or :py:func:`delattr`." msgstr "" -#: ../../c-api/structures.rst:604 +#: ../../c-api/structures.rst:609 msgid "Macro name" msgstr "" -#: ../../c-api/structures.rst:604 +#: ../../c-api/structures.rst:609 msgid "C type" -msgstr "Tipo C" +msgstr "Tipo em C" -#: ../../c-api/structures.rst:604 +#: ../../c-api/structures.rst:609 msgid "Python type" -msgstr "Tipo Python" +msgstr "Tipo em Python" -#: ../../c-api/structures.rst:606 +#: ../../c-api/structures.rst:611 msgid ":c:expr:`char`" msgstr ":c:expr:`char`" -#: ../../c-api/structures.rst:606 ../../c-api/structures.rst:607 -#: ../../c-api/structures.rst:608 ../../c-api/structures.rst:609 -#: ../../c-api/structures.rst:610 ../../c-api/structures.rst:611 -#: ../../c-api/structures.rst:612 ../../c-api/structures.rst:613 -#: ../../c-api/structures.rst:614 ../../c-api/structures.rst:615 -#: ../../c-api/structures.rst:616 +#: ../../c-api/structures.rst:611 ../../c-api/structures.rst:612 +#: ../../c-api/structures.rst:613 ../../c-api/structures.rst:614 +#: ../../c-api/structures.rst:615 ../../c-api/structures.rst:616 +#: ../../c-api/structures.rst:617 ../../c-api/structures.rst:618 +#: ../../c-api/structures.rst:619 ../../c-api/structures.rst:620 +#: ../../c-api/structures.rst:621 msgid ":py:class:`int`" -msgstr "" +msgstr ":py:class:`int`" -#: ../../c-api/structures.rst:607 +#: ../../c-api/structures.rst:612 msgid ":c:expr:`short`" msgstr ":c:expr:`short`" -#: ../../c-api/structures.rst:608 +#: ../../c-api/structures.rst:613 msgid ":c:expr:`int`" msgstr ":c:expr:`int`" -#: ../../c-api/structures.rst:609 +#: ../../c-api/structures.rst:614 msgid ":c:expr:`long`" msgstr ":c:expr:`long`" -#: ../../c-api/structures.rst:610 +#: ../../c-api/structures.rst:615 msgid ":c:expr:`long long`" -msgstr "" +msgstr ":c:expr:`long long`" -#: ../../c-api/structures.rst:611 +#: ../../c-api/structures.rst:616 msgid ":c:expr:`unsigned char`" msgstr ":c:expr:`unsigned char`" -#: ../../c-api/structures.rst:612 +#: ../../c-api/structures.rst:617 msgid ":c:expr:`unsigned int`" msgstr ":c:expr:`unsigned int`" -#: ../../c-api/structures.rst:613 +#: ../../c-api/structures.rst:618 msgid ":c:expr:`unsigned short`" msgstr ":c:expr:`unsigned short`" -#: ../../c-api/structures.rst:614 +#: ../../c-api/structures.rst:619 msgid ":c:expr:`unsigned long`" msgstr ":c:expr:`unsigned long`" -#: ../../c-api/structures.rst:615 +#: ../../c-api/structures.rst:620 msgid ":c:expr:`unsigned long long`" -msgstr "" +msgstr ":c:expr:`unsigned long long`" -#: ../../c-api/structures.rst:616 +#: ../../c-api/structures.rst:621 msgid ":c:expr:`Py_ssize_t`" -msgstr "" +msgstr ":c:expr:`Py_ssize_t`" -#: ../../c-api/structures.rst:617 +#: ../../c-api/structures.rst:622 msgid ":c:expr:`float`" msgstr ":c:expr:`float`" -#: ../../c-api/structures.rst:617 ../../c-api/structures.rst:618 +#: ../../c-api/structures.rst:622 ../../c-api/structures.rst:623 msgid ":py:class:`float`" msgstr ":py:class:`float`" -#: ../../c-api/structures.rst:618 +#: ../../c-api/structures.rst:623 msgid ":c:expr:`double`" msgstr ":c:expr:`double`" -#: ../../c-api/structures.rst:619 +#: ../../c-api/structures.rst:624 msgid ":c:expr:`char` (written as 0 or 1)" -msgstr "" +msgstr ":c:expr:`char` (escrito como 0 ou 1)" -#: ../../c-api/structures.rst:619 +#: ../../c-api/structures.rst:624 msgid ":py:class:`bool`" -msgstr "" +msgstr ":py:class:`bool`" -#: ../../c-api/structures.rst:621 +#: ../../c-api/structures.rst:626 msgid ":c:expr:`const char *` (*)" -msgstr "" +msgstr ":c:expr:`const char *` (*)" -#: ../../c-api/structures.rst:621 ../../c-api/structures.rst:622 +#: ../../c-api/structures.rst:626 ../../c-api/structures.rst:627 msgid ":py:class:`str` (RO)" -msgstr "" +msgstr ":py:class:`str` (RO)" -#: ../../c-api/structures.rst:622 +#: ../../c-api/structures.rst:627 msgid ":c:expr:`const char[]` (*)" -msgstr "" +msgstr ":c:expr:`const char[]` (*)" -#: ../../c-api/structures.rst:623 +#: ../../c-api/structures.rst:628 msgid ":c:expr:`char` (0-127)" -msgstr "" +msgstr ":c:expr:`char` (0-127)" -#: ../../c-api/structures.rst:623 +#: ../../c-api/structures.rst:628 msgid ":py:class:`str` (**)" -msgstr "" +msgstr ":py:class:`str` (**)" -#: ../../c-api/structures.rst:624 +#: ../../c-api/structures.rst:629 msgid ":c:expr:`PyObject *`" -msgstr "" +msgstr ":c:expr:`PyObject *`" -#: ../../c-api/structures.rst:624 +#: ../../c-api/structures.rst:629 msgid ":py:class:`object` (D)" -msgstr "" +msgstr ":py:class:`object` (D)" -#: ../../c-api/structures.rst:627 +#: ../../c-api/structures.rst:632 msgid "" "(*): Zero-terminated, UTF8-encoded C string. With :c:macro:`!Py_T_STRING` " "the C representation is a pointer; with :c:macro:`!Py_T_STRING_INPLACE` the " "string is stored directly in the structure." msgstr "" -#: ../../c-api/structures.rst:632 +#: ../../c-api/structures.rst:637 msgid "(**): String of length 1. Only ASCII is accepted." msgstr "" -#: ../../c-api/structures.rst:634 +#: ../../c-api/structures.rst:639 msgid "(RO): Implies :c:macro:`Py_READONLY`." -msgstr "" +msgstr "(RO): implica :c:macro:`Py_READONLY`." -#: ../../c-api/structures.rst:636 +#: ../../c-api/structures.rst:641 msgid "" "(D): Can be deleted, in which case the pointer is set to ``NULL``. Reading a " "``NULL`` pointer raises :py:exc:`AttributeError`." msgstr "" +"(D): pode ser deletado, neste caso o ponteiro é definido para ``NULL``. Ler " +"um ponteiro ``NULL`` levanta uma exceção :py:exc:`AttributeError`." -#: ../../c-api/structures.rst:662 +#: ../../c-api/structures.rst:667 msgid "" "In previous versions, the macros were only available with ``#include " "\"structmember.h\"`` and were named without the ``Py_`` prefix (e.g. as " @@ -791,174 +866,174 @@ msgid "" "with the following deprecated types:" msgstr "" -#: ../../c-api/structures.rst:670 +#: ../../c-api/structures.rst:675 msgid "" "Like ``Py_T_OBJECT_EX``, but ``NULL`` is converted to ``None``. This results " "in surprising behavior in Python: deleting the attribute effectively sets it " "to ``None``." msgstr "" -#: ../../c-api/structures.rst:676 +#: ../../c-api/structures.rst:681 msgid "Always ``None``. Must be used with :c:macro:`Py_READONLY`." -msgstr "" +msgstr "Sempre ``None``. Deve ser usado com :c:macro:`Py_READONLY`." -#: ../../c-api/structures.rst:679 +#: ../../c-api/structures.rst:684 msgid "Defining Getters and Setters" msgstr "" -#: ../../c-api/structures.rst:683 +#: ../../c-api/structures.rst:688 msgid "" "Structure to define property-like access for a type. See also description of " "the :c:member:`PyTypeObject.tp_getset` slot." msgstr "" -#: ../../c-api/structures.rst:688 +#: ../../c-api/structures.rst:693 msgid "attribute name" msgstr "" -#: ../../c-api/structures.rst:692 +#: ../../c-api/structures.rst:697 msgid "C function to get the attribute." msgstr "" -#: ../../c-api/structures.rst:696 +#: ../../c-api/structures.rst:701 msgid "" "Optional C function to set or delete the attribute. If ``NULL``, the " "attribute is read-only." msgstr "" -#: ../../c-api/structures.rst:701 +#: ../../c-api/structures.rst:706 msgid "optional docstring" msgstr "" -#: ../../c-api/structures.rst:705 +#: ../../c-api/structures.rst:710 msgid "" "Optional user data pointer, providing additional data for getter and setter." msgstr "" -#: ../../c-api/structures.rst:709 +#: ../../c-api/structures.rst:714 msgid "" "The ``get`` function takes one :c:expr:`PyObject*` parameter (the instance) " "and a user data pointer (the associated ``closure``):" msgstr "" -#: ../../c-api/structures.rst:712 +#: ../../c-api/structures.rst:717 msgid "" "It should return a new reference on success or ``NULL`` with a set exception " "on failure." msgstr "" -#: ../../c-api/structures.rst:717 +#: ../../c-api/structures.rst:722 msgid "" "``set`` functions take two :c:expr:`PyObject*` parameters (the instance and " "the value to be set) and a user data pointer (the associated ``closure``):" msgstr "" -#: ../../c-api/structures.rst:720 +#: ../../c-api/structures.rst:725 msgid "" "In case the attribute should be deleted the second parameter is ``NULL``. " "Should return ``0`` on success or ``-1`` with a set exception on failure." msgstr "" -#: ../../c-api/structures.rst:370 ../../c-api/structures.rst:380 +#: ../../c-api/structures.rst:375 ../../c-api/structures.rst:385 msgid "built-in function" msgstr "função embutida" -#: ../../c-api/structures.rst:370 +#: ../../c-api/structures.rst:375 msgid "classmethod" msgstr "classmethod" -#: ../../c-api/structures.rst:380 +#: ../../c-api/structures.rst:385 msgid "staticmethod" msgstr "staticmethod" -#: ../../c-api/structures.rst:563 +#: ../../c-api/structures.rst:568 msgid "READ_RESTRICTED (C macro)" -msgstr "" +msgstr "READ_RESTRICTED (macro C)" -#: ../../c-api/structures.rst:563 +#: ../../c-api/structures.rst:568 msgid "WRITE_RESTRICTED (C macro)" -msgstr "" +msgstr "WRITE_RESTRICTED (macro C)" -#: ../../c-api/structures.rst:563 +#: ../../c-api/structures.rst:568 msgid "RESTRICTED (C macro)" -msgstr "" +msgstr "RESTRICTED (macro C)" -#: ../../c-api/structures.rst:576 +#: ../../c-api/structures.rst:581 msgid "READONLY (C macro)" -msgstr "" +msgstr "READONLY (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_BYTE (C macro)" -msgstr "" +msgstr "T_BYTE (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_SHORT (C macro)" -msgstr "" +msgstr "T_SHORT (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_INT (C macro)" -msgstr "" +msgstr "T_INT (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_LONG (C macro)" -msgstr "" +msgstr "T_LONG (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_LONGLONG (C macro)" -msgstr "" +msgstr "T_LONGLONG (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_UBYTE (C macro)" -msgstr "" +msgstr "T_UBYTE (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_USHORT (C macro)" -msgstr "" +msgstr "T_USHORT (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_UINT (C macro)" -msgstr "" +msgstr "T_UINT (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_ULONG (C macro)" -msgstr "" +msgstr "T_ULONG (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_ULONGULONG (C macro)" -msgstr "" +msgstr "T_ULONGULONG (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_PYSSIZET (C macro)" -msgstr "" +msgstr "T_PYSSIZET (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_FLOAT (C macro)" msgstr "T_FLOAT (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_DOUBLE (C macro)" -msgstr "" +msgstr "T_DOUBLE (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_BOOL (C macro)" -msgstr "" +msgstr "T_BOOL (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_CHAR (C macro)" -msgstr "" +msgstr "T_CHAR (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_STRING (C macro)" -msgstr "" +msgstr "T_STRING (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_STRING_INPLACE (C macro)" -msgstr "" +msgstr "T_STRING_INPLACE (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "T_OBJECT_EX (C macro)" -msgstr "" +msgstr "T_OBJECT_EX (macro C)" -#: ../../c-api/structures.rst:639 +#: ../../c-api/structures.rst:644 msgid "structmember.h" -msgstr "" +msgstr "structmember.h" diff --git a/c-api/sys.po b/c-api/sys.po index ccf22b89f..36bd4969c 100644 --- a/c-api/sys.po +++ b/c-api/sys.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -224,7 +224,7 @@ msgid "" msgstr "" "Decodifica uma string de bytes do :term:`tratador de erros e codificação do " "sistema de arquivos`. Se o tratador de erros for o :ref:`tratador de errors " -"surrogateescape `, bytes não decodificáveis ​​são " +"surrogateescape `, bytes não decodificáveis são " "decodificados como caracteres no intervalo U+DC80..U+DCFF; e se uma string " "de bytes puder ser decodificada como um caractere substituto, os bytes são " "escapados usando o tratador de erros surrogateescape em vez de decodificá-" @@ -578,6 +578,10 @@ msgid "" "should be called by *func*." msgstr "" +#: ../../c-api/sys.rst:432 +msgid ":c:func:`PyUnstable_AtExit` for passing a ``void *data`` argument." +msgstr "" + #: ../../c-api/sys.rst:101 msgid "USE_STACKCHECK (C macro)" msgstr "" diff --git a/c-api/time.po b/c-api/time.po index e69fbd675..c6e18b2aa 100644 --- a/c-api/time.po +++ b/c-api/time.po @@ -1,34 +1,33 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# felipe caridade fernandes , 2024 -# Pedro Fonini, 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-21 14:14+0000\n" -"PO-Revision-Date: 2024-05-11 01:07+0000\n" -"Last-Translator: Pedro Fonini, 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" -#: ../../c-api/time.rst:4 +#: ../../c-api/time.rst:6 msgid "PyTime C API" msgstr "API C PyTime" -#: ../../c-api/time.rst:8 +#: ../../c-api/time.rst:10 msgid "" "The clock C API provides access to system clocks. It is similar to the " "Python :mod:`time` module." @@ -36,18 +35,18 @@ msgstr "" "A API C de relógios provê acesso a relógios do sistema. Ela é similar ao " "módulo Python :mod:`time`." -#: ../../c-api/time.rst:11 +#: ../../c-api/time.rst:13 msgid "" "For C API related to the :mod:`datetime` module, see :ref:`datetimeobjects`." msgstr "" "Para uma API C relacionada ao módulo :mod:`datetime`, veja :ref:" "`datetimeobjects`." -#: ../../c-api/time.rst:15 +#: ../../c-api/time.rst:17 msgid "Types" msgstr "Tipos" -#: ../../c-api/time.rst:19 +#: ../../c-api/time.rst:21 msgid "" "A timestamp or duration in nanoseconds, represented as a signed 64-bit " "integer." @@ -55,7 +54,7 @@ msgstr "" "Um registro de data e hora ou uma duração em nanossegundos, representados " "como um inteiro de 64 bits com sinal." -#: ../../c-api/time.rst:22 +#: ../../c-api/time.rst:24 msgid "" "The reference point for timestamps depends on the clock used. For example, :" "c:func:`PyTime_Time` returns timestamps relative to the UNIX epoch." @@ -64,7 +63,7 @@ msgstr "" "usado. Por exemplo, :c:func:`PyTime_Time` retorna registros relativos à " "época UNIX." -#: ../../c-api/time.rst:25 +#: ../../c-api/time.rst:27 msgid "" "The supported range is around [-292.3 years; +292.3 years]. Using the Unix " "epoch (January 1st, 1970) as reference, the supported date range is around " @@ -75,19 +74,19 @@ msgstr "" "datas suportadas é em torno de [1677-09-21; 2262-04-11]. Os limites exatos " "são expostos como constantes:" -#: ../../c-api/time.rst:32 +#: ../../c-api/time.rst:34 msgid "Minimum value of :c:type:`PyTime_t`." msgstr "Valor mínimo de :c:type:`PyTime_t`." -#: ../../c-api/time.rst:36 +#: ../../c-api/time.rst:38 msgid "Maximum value of :c:type:`PyTime_t`." msgstr "Valor máximo de :c:type:`PyTime_t`." -#: ../../c-api/time.rst:40 +#: ../../c-api/time.rst:42 msgid "Clock Functions" msgstr "Funções de relógio" -#: ../../c-api/time.rst:42 +#: ../../c-api/time.rst:44 msgid "" "The following functions take a pointer to a :c:expr:`PyTime_t` that they set " "to the value of a particular clock. Details of each clock are given in the " @@ -97,7 +96,7 @@ msgstr "" "atribuem o valor de um determinado relógio. Detalhes de cada relógio estão " "disponíveis nas documentações das funções Python correspondentes." -#: ../../c-api/time.rst:47 +#: ../../c-api/time.rst:49 msgid "" "The functions return ``0`` on success, or ``-1`` (with an exception set) on " "failure." @@ -105,7 +104,7 @@ msgstr "" "As funções retornam ``0`` em caso de sucesso, ou ``-1`` (com uma exceção " "definida) em caso de falha." -#: ../../c-api/time.rst:50 +#: ../../c-api/time.rst:52 msgid "" "On integer overflow, they set the :c:data:`PyExc_OverflowError` exception " "and set ``*result`` to the value clamped to the ``[PyTime_MIN; PyTime_MAX]`` " @@ -118,7 +117,7 @@ msgstr "" "inteiros são provavelmente causados por uma má configuração do tempo do " "sistema)." -#: ../../c-api/time.rst:56 +#: ../../c-api/time.rst:58 msgid "" "As any other C API (unless otherwise specified), the functions must be " "called with the :term:`GIL` held." @@ -126,7 +125,7 @@ msgstr "" "Como qualquer outra API C (se não especificado o contrário), as funções " "devem ser chamadas sob posse da :term:`GIL`." -#: ../../c-api/time.rst:61 +#: ../../c-api/time.rst:63 msgid "" "Read the monotonic clock. See :func:`time.monotonic` for important details " "on this clock." @@ -134,7 +133,7 @@ msgstr "" "Lê o relógio monótono. Veja :func:`time.monotonic` para detalhes importantes " "sobre este relógio." -#: ../../c-api/time.rst:66 +#: ../../c-api/time.rst:68 msgid "" "Read the performance counter. See :func:`time.perf_counter` for important " "details on this clock." @@ -142,7 +141,7 @@ msgstr "" "Lê o contador de desempenho. Veja :func:`time.perf_counter` para detalhes " "importantes sobre este relógio." -#: ../../c-api/time.rst:71 +#: ../../c-api/time.rst:73 msgid "" "Read the “wall clock” time. See :func:`time.time` for details important on " "this clock." @@ -150,11 +149,11 @@ msgstr "" "Lê o \"relógio de parede\". Veja :func:`time.time` para detalhes importantes " "sobre este relógio." -#: ../../c-api/time.rst:76 +#: ../../c-api/time.rst:78 msgid "Raw Clock Functions" msgstr "Funções de relógio brutas" -#: ../../c-api/time.rst:78 +#: ../../c-api/time.rst:80 msgid "" "Similar to clock functions, but don't set an exception on error and don't " "require the caller to hold the GIL." @@ -162,11 +161,11 @@ msgstr "" "Similares às funções de relógio, mas não definem uma exceção em condições de " "erro, e não requerem que o chamador possua a trava `GIL`." -#: ../../c-api/time.rst:81 +#: ../../c-api/time.rst:83 msgid "On success, the functions return ``0``." msgstr "Em caso de sucesso, as funções retornam ``0``." -#: ../../c-api/time.rst:83 +#: ../../c-api/time.rst:85 msgid "" "On failure, they set ``*result`` to ``0`` and return ``-1``, *without* " "setting an exception. To get the cause of the error, acquire the GIL and " @@ -178,7 +177,7 @@ msgstr "" "chame a função regular (sem o sufixo ``Raw``). Obserrve que a função regular " "pode ser bem-sucedida mesmo após a bruta falhar." -#: ../../c-api/time.rst:90 +#: ../../c-api/time.rst:92 msgid "" "Similar to :c:func:`PyTime_Monotonic`, but don't set an exception on error " "and don't require holding the GIL." @@ -186,7 +185,7 @@ msgstr "" "Similar a :c:func:`PyTime_Monotonic`, mas não define uma exceção em caso de " "erro, e não exige a posse da GIL." -#: ../../c-api/time.rst:95 +#: ../../c-api/time.rst:97 msgid "" "Similar to :c:func:`PyTime_PerfCounter`, but don't set an exception on error " "and don't require holding the GIL." @@ -194,7 +193,7 @@ msgstr "" "Similar a :c:func:`PyTime_PerfCounter`, mas não define uma exceção em caso " "de erro e não requer a posse da GIL." -#: ../../c-api/time.rst:100 +#: ../../c-api/time.rst:102 msgid "" "Similar to :c:func:`PyTime_Time`, but don't set an exception on error and " "don't require holding the GIL." @@ -202,17 +201,17 @@ msgstr "" "Similar a :c:func:`PyTime_Time`, mas não define uma exceção em caso de erro " "e não requer a posse da GIL." -#: ../../c-api/time.rst:105 +#: ../../c-api/time.rst:107 msgid "Conversion functions" msgstr "Funções de conversão" -#: ../../c-api/time.rst:109 +#: ../../c-api/time.rst:111 msgid "Convert a timestamp to a number of seconds as a C :c:expr:`double`." msgstr "" "Converte um registro de data e hora para uma quantidade de segundos como um :" "c:expr:`double` C." -#: ../../c-api/time.rst:111 +#: ../../c-api/time.rst:113 msgid "" "The function cannot fail, but note that :c:expr:`double` has limited " "accuracy for large values." diff --git a/c-api/tuple.po b/c-api/tuple.po index 62b41ee13..3618f4da3 100644 --- a/c-api/tuple.po +++ b/c-api/tuple.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Alexandre B A Villares, 2021 -# Vitor Buxbaum Orlandi, 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-05 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -59,35 +57,38 @@ msgstr "" "subtipo do tipo tupla. Esta função sempre tem sucesso." #: ../../c-api/tuple.rst:36 -msgid "Return a new tuple object of size *len*, or ``NULL`` on failure." +msgid "" +"Return a new tuple object of size *len*, or ``NULL`` with an exception set " +"on failure." msgstr "" -"Retorna um novo objeto tupla de tamanho *len*, ou ``NULL`` em caso de falha." +"Retorna um novo objeto tupla de tamanho *len*, ou ``NULL`` com uma exceção " +"definida em caso de falha." -#: ../../c-api/tuple.rst:41 +#: ../../c-api/tuple.rst:42 msgid "" -"Return a new tuple object of size *n*, or ``NULL`` on failure. The tuple " -"values are initialized to the subsequent *n* C arguments pointing to Python " -"objects. ``PyTuple_Pack(2, a, b)`` is equivalent to " +"Return a new tuple object of size *n*, or ``NULL`` with an exception set on " +"failure. The tuple values are initialized to the subsequent *n* C arguments " +"pointing to Python objects. ``PyTuple_Pack(2, a, b)`` is equivalent to " "``Py_BuildValue(\"(OO)\", a, b)``." msgstr "" -"Retorna um novo objeto tupla de tamanho *n*, ou ``NULL`` em caso de falha. " -"Os valores da tupla são inicializados para os *n* argumentos C subsequentes " -"apontando para objetos Python. ```PyTuple_Pack(2, a, b)`` é equivalente a " -"``Py_BuildValue(\"(OO)\", a, b)``." - -#: ../../c-api/tuple.rst:48 -msgid "Take a pointer to a tuple object, and return the size of that tuple." -msgstr "Pega um ponteiro para um objeto tupla e retorna o tamanho dessa tupla." +"Retorna um novo objeto tupla de tamanho *n*, ou ``NULL`` com uma exceção em " +"caso de falha. Os valores da tupla são inicializados para os *n* argumentos " +"C subsequentes apontando para objetos Python. ```PyTuple_Pack(2, a, b)`` é " +"equivalente a ``Py_BuildValue(\"(OO)\", a, b)``." -#: ../../c-api/tuple.rst:53 +#: ../../c-api/tuple.rst:50 msgid "" -"Return the size of the tuple *p*, which must be non-``NULL`` and point to a " -"tuple; no error checking is performed." +"Take a pointer to a tuple object, and return the size of that tuple. On " +"error, return ``-1`` and with an exception set." msgstr "" -"Retorna o tamanho da tupla *p*, que deve ser diferente de ``NULL`` e apontar " -"para uma tupla; nenhuma verificação de erro é executada." +"Pega um ponteiro para um objeto tupla e retorna o tamanho dessa tupla. No " +"erro, retorna ``-1`` e com uma exceção definida." -#: ../../c-api/tuple.rst:59 +#: ../../c-api/tuple.rst:56 +msgid "Like :c:func:`PyTuple_Size`, but without error checking." +msgstr "Como :c:func:`PyTuple_Size`, mas sem verificação de erro." + +#: ../../c-api/tuple.rst:61 msgid "" "Return the object at position *pos* in the tuple pointed to by *p*. If " "*pos* is negative or out of bounds, return ``NULL`` and set an :exc:" @@ -97,28 +98,41 @@ msgstr "" "estiver fora dos limites, retorna ``NULL`` e define uma exceção :exc:" "`IndexError`." -#: ../../c-api/tuple.rst:62 +#: ../../c-api/tuple.rst:64 msgid "" "The returned reference is borrowed from the tuple *p* (that is: it is only " "valid as long as you hold a reference to *p*). To get a :term:`strong " "reference`, use :c:func:`Py_NewRef(PyTuple_GetItem(...)) ` or :c:" "func:`PySequence_GetItem`." msgstr "" +"A referência retornada é emprestada da tupla *p* (ou seja: ela só é válida " +"enquanto você mantém uma referência a *p*). Para obter uma :term:`referência " +"forte`, use :c:func:`Py_NewRef(PyTuple_GetItem(...)) ` ou :c:func:" +"`PySequence_GetItem`." -#: ../../c-api/tuple.rst:71 +#: ../../c-api/tuple.rst:73 msgid "Like :c:func:`PyTuple_GetItem`, but does no checking of its arguments." msgstr "" "Como :c:func:`PyTuple_GetItem`, mas faz nenhuma verificação de seus " "argumentos." -#: ../../c-api/tuple.rst:76 +#: ../../c-api/tuple.rst:78 msgid "" "Return the slice of the tuple pointed to by *p* between *low* and *high*, or " -"``NULL`` on failure. This is the equivalent of the Python expression " -"``p[low:high]``. Indexing from the end of the tuple is not supported." +"``NULL`` with an exception set on failure." msgstr "" +"Retorna a fatia da tupla apontada por *p* entre *low* e *high*, ou ``NULL`` " +"com uma exceção definida em caso de falha." -#: ../../c-api/tuple.rst:83 +#: ../../c-api/tuple.rst:81 +msgid "" +"This is the equivalent of the Python expression ``p[low:high]``. Indexing " +"from the end of the tuple is not supported." +msgstr "" +"Isso é o equivalente da expressão Python ``p[low:high]``. A indexação do " +"final da tupla não é suportada." + +#: ../../c-api/tuple.rst:87 msgid "" "Insert a reference to object *o* at position *pos* of the tuple pointed to " "by *p*. Return ``0`` on success. If *pos* is out of bounds, return ``-1`` " @@ -128,7 +142,7 @@ msgstr "" "*p*. Retorna ``0`` em caso de sucesso. Se *pos* estiver fora dos limites, " "retorne ``-1`` e define uma exceção :exc:`IndexError`." -#: ../../c-api/tuple.rst:89 +#: ../../c-api/tuple.rst:93 msgid "" "This function \"steals\" a reference to *o* and discards a reference to an " "item already in the tuple at the affected position." @@ -136,7 +150,7 @@ msgstr "" "Esta função \"rouba\" uma referência a *o* e descarta uma referência a um " "item já na tupla na posição afetada." -#: ../../c-api/tuple.rst:95 +#: ../../c-api/tuple.rst:99 msgid "" "Like :c:func:`PyTuple_SetItem`, but does no error checking, and should " "*only* be used to fill in brand new tuples." @@ -144,7 +158,8 @@ msgstr "" "Como :c:func:`PyTuple_SetItem`, mas não verifica erros e deve *apenas* ser " "usado para preencher novas tuplas." -#: ../../c-api/tuple.rst:98 ../../c-api/tuple.rst:209 ../../c-api/tuple.rst:227 +#: ../../c-api/tuple.rst:102 ../../c-api/tuple.rst:218 +#: ../../c-api/tuple.rst:236 msgid "" "Bounds checking is performed as an assertion if Python is built in :ref:" "`debug mode ` or :option:`with assertions <--with-assertions>`." @@ -153,7 +168,7 @@ msgstr "" "construído em :ref:`modo de depuração ` ou :option:`com " "asserções <--with-assertions>`." -#: ../../c-api/tuple.rst:103 +#: ../../c-api/tuple.rst:107 msgid "" "This function \"steals\" a reference to *o*, and, unlike :c:func:" "`PyTuple_SetItem`, does *not* discard a reference to any item that is being " @@ -164,7 +179,7 @@ msgstr "" "sendo substituído; qualquer referência na tupla na posição *pos* será " "perdida." -#: ../../c-api/tuple.rst:111 +#: ../../c-api/tuple.rst:115 msgid "" "Can be used to resize a tuple. *newsize* will be the new length of the " "tuple. Because tuples are *supposed* to be immutable, this should only be " @@ -190,11 +205,11 @@ msgstr "" "``-1`` e define ``*p`` para ``NULL``, e levanta :exc:`MemoryError` ou :exc:" "`SystemError`." -#: ../../c-api/tuple.rst:126 +#: ../../c-api/tuple.rst:130 msgid "Struct Sequence Objects" msgstr "Objetos sequência de estrutura" -#: ../../c-api/tuple.rst:128 +#: ../../c-api/tuple.rst:132 msgid "" "Struct sequence objects are the C equivalent of :func:`~collections." "namedtuple` objects, i.e. a sequence whose items can also be accessed " @@ -206,7 +221,7 @@ msgstr "" "ser acessados por meio de atributos. Para criar uma sequência de estrutura, " "você primeiro precisa criar um tipo de sequência de estrutura específico." -#: ../../c-api/tuple.rst:135 +#: ../../c-api/tuple.rst:139 msgid "" "Create a new struct sequence type from the data in *desc*, described below. " "Instances of the resulting type can be created with :c:func:" @@ -216,41 +231,50 @@ msgstr "" "descrito abaixo. Instâncias do tipo resultante podem ser criadas com :c:func:" "`PyStructSequence_New`." -#: ../../c-api/tuple.rst:141 +#: ../../c-api/tuple.rst:142 ../../c-api/tuple.rst:211 +msgid "Return ``NULL`` with an exception set on failure." +msgstr "Retorna ``NULL`` com uma exceção definida em caso de falha." + +#: ../../c-api/tuple.rst:147 msgid "Initializes a struct sequence type *type* from *desc* in place." msgstr "" "Inicializa um tipo de sequência de estrutura *type* de *desc* no lugar." -#: ../../c-api/tuple.rst:146 +#: ../../c-api/tuple.rst:152 msgid "" -"The same as ``PyStructSequence_InitType``, but returns ``0`` on success and " -"``-1`` on failure." +"Like :c:func:`PyStructSequence_InitType`, but returns ``0`` on success and " +"``-1`` with an exception set on failure." msgstr "" -"O mesmo que ``PyStructSequence_InitType``, mas retorna ``0`` em caso de " -"sucesso e ``-1`` em caso de falha." +"Como :c:func:`PyStructSequence_InitType`, mas retorna ``0`` em caso de " +"sucesso e ``-1`` com uma exceção definida em caso de falha." -#: ../../c-api/tuple.rst:154 +#: ../../c-api/tuple.rst:160 msgid "Contains the meta information of a struct sequence type to create." msgstr "" "Contém as metainformações de um tipo de sequência de estrutura a ser criado." -#: ../../c-api/tuple.rst:158 -msgid "Name of the struct sequence type." +#: ../../c-api/tuple.rst:164 +msgid "" +"Fully qualified name of the type; null-terminated UTF-8 encoded. The name " +"must contain the module name." msgstr "" +"Nome totalmente qualificado do tipo; codificado em UTF-8 terminado em nulo. " +"O nome deve conter o nome do módulo." -#: ../../c-api/tuple.rst:162 +#: ../../c-api/tuple.rst:169 msgid "Pointer to docstring for the type or ``NULL`` to omit." -msgstr "" +msgstr "Ponteiro para docstring para o tipo ou ``NULL`` para omitir" -#: ../../c-api/tuple.rst:166 +#: ../../c-api/tuple.rst:173 msgid "Pointer to ``NULL``-terminated array with field names of the new type." msgstr "" +"Ponteiro para um vetor terminado em ``NULL`` com nomes de campos do novo tipo" -#: ../../c-api/tuple.rst:170 +#: ../../c-api/tuple.rst:177 msgid "Number of fields visible to the Python side (if used as tuple)." -msgstr "" +msgstr "Número de campos visíveis para o lado Python (se usado como tupla)" -#: ../../c-api/tuple.rst:175 +#: ../../c-api/tuple.rst:182 msgid "" "Describes a field of a struct sequence. As a struct sequence is modeled as a " "tuple, all fields are typed as :c:expr:`PyObject*`. The index in the :c:" @@ -258,26 +282,33 @@ msgid "" "`PyStructSequence_Desc` determines which field of the struct sequence is " "described." msgstr "" +"Descreve um campo de uma sequência de estrutura. Como uma sequência de " +"estrutura é modelada como uma tupla, todos os campos são digitados como :c:" +"expr:`PyObject*`. O índice no vetor :c:member:`~PyStructSequence_Desc." +"fields` do :c:type:`PyStructSequence_Desc` determina qual campo da sequência " +"de estrutura é descrito." -#: ../../c-api/tuple.rst:183 +#: ../../c-api/tuple.rst:190 msgid "" "Name for the field or ``NULL`` to end the list of named fields, set to :c:" "data:`PyStructSequence_UnnamedField` to leave unnamed." msgstr "" +"Nome do campo ou ``NULL`` para terminar a lista de campos nomeados; definida " +"para :c:data:`PyStructSequence_UnnamedField` para deixar sem nome." -#: ../../c-api/tuple.rst:188 +#: ../../c-api/tuple.rst:195 msgid "Field docstring or ``NULL`` to omit." -msgstr "" +msgstr "Campo docstring ou ``NULL`` para omitir." -#: ../../c-api/tuple.rst:193 +#: ../../c-api/tuple.rst:200 msgid "Special value for a field name to leave it unnamed." msgstr "Valor especial para um nome de campo para deixá-lo sem nome." -#: ../../c-api/tuple.rst:195 +#: ../../c-api/tuple.rst:202 msgid "The type was changed from ``char *``." msgstr "O tipo foi alterado de ``char *``." -#: ../../c-api/tuple.rst:201 +#: ../../c-api/tuple.rst:208 msgid "" "Creates an instance of *type*, which must have been created with :c:func:" "`PyStructSequence_NewType`." @@ -285,20 +316,22 @@ msgstr "" "Cria um instância de *type*, que deve ser criada com :c:func:" "`PyStructSequence_NewType`." -#: ../../c-api/tuple.rst:207 +#: ../../c-api/tuple.rst:216 msgid "" "Return the object at position *pos* in the struct sequence pointed to by *p*." msgstr "" +"Retorna o objeto na posição *pos* na sequência de estrutura apontada por *p*." -#: ../../c-api/tuple.rst:215 +#: ../../c-api/tuple.rst:224 msgid "Alias to :c:func:`PyStructSequence_GetItem`." -msgstr "" +msgstr "Apelido para :c:func:`PyStructSequence_GetItem`." -#: ../../c-api/tuple.rst:217 +#: ../../c-api/tuple.rst:226 msgid "Now implemented as an alias to :c:func:`PyStructSequence_GetItem`." msgstr "" +"Agora implementada como um apelido para :c:func:`PyStructSequence_GetItem`." -#: ../../c-api/tuple.rst:223 +#: ../../c-api/tuple.rst:232 msgid "" "Sets the field at index *pos* of the struct sequence *p* to value *o*. " "Like :c:func:`PyTuple_SET_ITEM`, this should only be used to fill in brand " @@ -308,17 +341,18 @@ msgstr "" "*o*. Como :c:func:`PyTuple_SET_ITEM`, isto só deve ser usado para preencher " "novas instâncias." -#: ../../c-api/tuple.rst:232 +#: ../../c-api/tuple.rst:241 msgid "This function \"steals\" a reference to *o*." msgstr "Esta função \"rouba\" uma referência a *o*." -#: ../../c-api/tuple.rst:237 +#: ../../c-api/tuple.rst:246 msgid "Alias to :c:func:`PyStructSequence_SetItem`." -msgstr "" +msgstr "Apelido para :c:func:`PyStructSequence_SetItem`." -#: ../../c-api/tuple.rst:239 +#: ../../c-api/tuple.rst:248 msgid "Now implemented as an alias to :c:func:`PyStructSequence_SetItem`." msgstr "" +"Agora implementada como um apelido para :c:func:`PyStructSequence_SetItem`." #: ../../c-api/tuple.rst:8 msgid "object" diff --git a/c-api/type.po b/c-api/type.po index 7180969db..90fc2972c 100644 --- a/c-api/type.po +++ b/c-api/type.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 02:33+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-04-04 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -79,25 +79,25 @@ msgstr "O tipo de retorno é agora um ``unsigned long`` em vez de um ``long``." #: ../../c-api/type.rst:55 msgid "" "Return the type object's internal namespace, which is otherwise only exposed " -"via a read-only proxy (``cls.__dict__``). This is a replacement for " -"accessing :c:member:`~PyTypeObject.tp_dict` directly. The returned " -"dictionary must be treated as read-only." +"via a read-only proxy (:attr:`cls.__dict__ `). This is a " +"replacement for accessing :c:member:`~PyTypeObject.tp_dict` directly. The " +"returned dictionary must be treated as read-only." msgstr "" -#: ../../c-api/type.rst:60 +#: ../../c-api/type.rst:61 msgid "" "This function is meant for specific embedding and language-binding cases, " "where direct access to the dict is necessary and indirect access (e.g. via " "the proxy or :c:func:`PyObject_GetAttr`) isn't adequate." msgstr "" -#: ../../c-api/type.rst:64 +#: ../../c-api/type.rst:65 msgid "" "Extension modules should continue to use ``tp_dict``, directly or " "indirectly, when setting up their own types." msgstr "" -#: ../../c-api/type.rst:72 +#: ../../c-api/type.rst:73 msgid "" "Invalidate the internal lookup cache for the type and all of its subtypes. " "This function must be called after any manual modification of the attributes " @@ -107,7 +107,7 @@ msgstr "" "Esta função deve ser chamada após qualquer modificação manual dos atributos " "ou classes bases do tipo." -#: ../../c-api/type.rst:79 +#: ../../c-api/type.rst:80 msgid "" "Register *callback* as a type watcher. Return a non-negative integer ID " "which must be passed to future calls to :c:func:`PyType_Watch`. In case of " @@ -115,21 +115,27 @@ msgid "" "exception." msgstr "" -#: ../../c-api/type.rst:89 +#: ../../c-api/type.rst:85 +msgid "" +"In free-threaded builds, :c:func:`PyType_AddWatcher` is not thread-safe, so " +"it must be called at start up (before spawning the first thread)." +msgstr "" + +#: ../../c-api/type.rst:93 msgid "" "Clear watcher identified by *watcher_id* (previously returned from :c:func:" "`PyType_AddWatcher`). Return ``0`` on success, ``-1`` on error (e.g. if " "*watcher_id* was never registered.)" msgstr "" -#: ../../c-api/type.rst:93 +#: ../../c-api/type.rst:97 msgid "" "An extension should never call ``PyType_ClearWatcher`` with a *watcher_id* " "that was not returned to it by a previous call to :c:func:" "`PyType_AddWatcher`." msgstr "" -#: ../../c-api/type.rst:102 +#: ../../c-api/type.rst:106 msgid "" "Mark *type* as watched. The callback granted *watcher_id* by :c:func:" "`PyType_AddWatcher` will be called whenever :c:func:`PyType_Modified` " @@ -139,24 +145,24 @@ msgid "" "detail and subject to change.)" msgstr "" -#: ../../c-api/type.rst:109 +#: ../../c-api/type.rst:113 msgid "" "An extension should never call ``PyType_Watch`` with a *watcher_id* that was " "not returned to it by a previous call to :c:func:`PyType_AddWatcher`." msgstr "" -#: ../../c-api/type.rst:117 +#: ../../c-api/type.rst:121 msgid "Type of a type-watcher callback function." msgstr "" -#: ../../c-api/type.rst:119 +#: ../../c-api/type.rst:123 msgid "" "The callback must not modify *type* or cause :c:func:`PyType_Modified` to be " "called on *type* or any type in its MRO; violating this rule could cause " "infinite recursion." msgstr "" -#: ../../c-api/type.rst:128 +#: ../../c-api/type.rst:132 msgid "" "Return non-zero if the type object *o* sets the feature *feature*. Type " "features are denoted by single bit flags." @@ -164,28 +170,24 @@ msgstr "" "Retorna valor diferente de zero se o objeto tipo *o* define o recurso " "*feature*. Os recursos de tipo são denotados por sinalizadores de bit único." -#: ../../c-api/type.rst:134 +#: ../../c-api/type.rst:138 msgid "" "Return true if the type object includes support for the cycle detector; this " "tests the type flag :c:macro:`Py_TPFLAGS_HAVE_GC`." msgstr "" -#: ../../c-api/type.rst:140 +#: ../../c-api/type.rst:144 msgid "Return true if *a* is a subtype of *b*." msgstr "Retorna verdadeiro se *a* for um subtipo de *b*." -#: ../../c-api/type.rst:142 +#: ../../c-api/type.rst:146 msgid "" -"This function only checks for actual subtypes, which means that :meth:" -"`~class.__subclasscheck__` is not called on *b*. Call :c:func:" -"`PyObject_IsSubclass` to do the same check that :func:`issubclass` would do." +"This function only checks for actual subtypes, which means that :meth:`~type." +"__subclasscheck__` is not called on *b*. Call :c:func:`PyObject_IsSubclass` " +"to do the same check that :func:`issubclass` would do." msgstr "" -"Esta função só verifica pelos subtipos, o que significa que :meth:`~class." -"__subclasscheck__` não é chamado em *b*. Chame :c:func:" -"`PyObject_IsSubclass` para fazer a mesma verificação que :func:`issubclass` " -"faria." -#: ../../c-api/type.rst:150 +#: ../../c-api/type.rst:154 msgid "" "Generic handler for the :c:member:`~PyTypeObject.tp_alloc` slot of a type " "object. Use Python's default memory allocation mechanism to allocate a new " @@ -195,7 +197,7 @@ msgstr "" "objeto tipo. Use o mecanismo de alocação de memória padrão do Python para " "alocar uma nova instância e inicializar todo o seu conteúdo para ``NULL``." -#: ../../c-api/type.rst:156 +#: ../../c-api/type.rst:160 msgid "" "Generic handler for the :c:member:`~PyTypeObject.tp_new` slot of a type " "object. Create a new instance using the type's :c:member:`~PyTypeObject." @@ -205,7 +207,7 @@ msgstr "" "objeto tipo. Cria uma nova instância usando o slot :c:member:`~PyTypeObject." "tp_alloc` do tipo." -#: ../../c-api/type.rst:161 +#: ../../c-api/type.rst:165 msgid "" "Finalize a type object. This should be called on all type objects to finish " "their initialization. This function is responsible for adding inherited " @@ -217,7 +219,7 @@ msgstr "" "herdados da classe base de um tipo. Retorna ``0`` em caso de sucesso, ou " "retorna ``-1`` e define uma exceção em caso de erro." -#: ../../c-api/type.rst:167 +#: ../../c-api/type.rst:171 msgid "" "If some of the base classes implements the GC protocol and the provided type " "does not include the :c:macro:`Py_TPFLAGS_HAVE_GC` in its flags, then the GC " @@ -228,32 +230,32 @@ msgid "" "handle." msgstr "" -#: ../../c-api/type.rst:177 +#: ../../c-api/type.rst:181 msgid "" -"Return the type's name. Equivalent to getting the type's ``__name__`` " -"attribute." +"Return the type's name. Equivalent to getting the type's :attr:`~type." +"__name__` attribute." msgstr "" -#: ../../c-api/type.rst:183 +#: ../../c-api/type.rst:188 msgid "" -"Return the type's qualified name. Equivalent to getting the type's " -"``__qualname__`` attribute." +"Return the type's qualified name. Equivalent to getting the type's :attr:" +"`~type.__qualname__` attribute." msgstr "" -#: ../../c-api/type.rst:190 +#: ../../c-api/type.rst:195 msgid "" "Return the type's fully qualified name. Equivalent to ``f\"{type.__module__}." -"{type.__qualname__}\"``, or ``type.__qualname__`` if ``type.__module__`` is " -"not a string or is equal to ``\"builtins\"``." +"{type.__qualname__}\"``, or :attr:`type.__qualname__` if :attr:`type." +"__module__` is not a string or is equal to ``\"builtins\"``." msgstr "" -#: ../../c-api/type.rst:198 +#: ../../c-api/type.rst:203 msgid "" -"Return the type's module name. Equivalent to getting the ``type.__module__`` " -"attribute." +"Return the type's module name. Equivalent to getting the :attr:`type." +"__module__` attribute." msgstr "" -#: ../../c-api/type.rst:205 +#: ../../c-api/type.rst:210 msgid "" "Return the function pointer stored in the given slot. If the result is " "``NULL``, this indicates that either the slot is ``NULL``, or that the " @@ -265,19 +267,19 @@ msgstr "" "com parâmetros inválidos. Os chamadores normalmente lançarão o ponteiro do " "resultado no tipo de função apropriado." -#: ../../c-api/type.rst:211 +#: ../../c-api/type.rst:216 msgid "" "See :c:member:`PyType_Slot.slot` for possible values of the *slot* argument." msgstr "" "Veja :c:member:`PyType_Slot.slot` por possíveis valores do argumento *slot*." -#: ../../c-api/type.rst:215 +#: ../../c-api/type.rst:220 msgid "" ":c:func:`PyType_GetSlot` can now accept all types. Previously, it was " "limited to :ref:`heap types `." msgstr "" -#: ../../c-api/type.rst:221 +#: ../../c-api/type.rst:226 msgid "" "Return the module object associated with the given type when the type was " "created using :c:func:`PyType_FromModuleAndSpec`." @@ -285,7 +287,7 @@ msgstr "" "Retorna o objeto de módulo associado ao tipo fornecido quando o tipo foi " "criado usando :c:func:`PyType_FromModuleAndSpec`." -#: ../../c-api/type.rst:224 ../../c-api/type.rst:244 +#: ../../c-api/type.rst:229 ../../c-api/type.rst:249 msgid "" "If no module is associated with the given type, sets :py:class:`TypeError` " "and returns ``NULL``." @@ -293,7 +295,7 @@ msgstr "" "Se nenhum módulo estiver associado com o tipo fornecido, define :py:class:" "`TypeError` e retorna ``NULL``." -#: ../../c-api/type.rst:227 +#: ../../c-api/type.rst:232 msgid "" "This function is usually used to get the module in which a method is " "defined. Note that in such a method, ``PyType_GetModule(Py_TYPE(self))`` may " @@ -304,31 +306,31 @@ msgid "" "type:`!PyCMethod` cannot be used." msgstr "" -#: ../../c-api/type.rst:240 +#: ../../c-api/type.rst:245 msgid "" "Return the state of the module object associated with the given type. This " "is a shortcut for calling :c:func:`PyModule_GetState()` on the result of :c:" "func:`PyType_GetModule`." msgstr "" -#: ../../c-api/type.rst:247 +#: ../../c-api/type.rst:252 msgid "" "If the *type* has an associated module but its state is ``NULL``, returns " "``NULL`` without setting an exception." msgstr "" -#: ../../c-api/type.rst:254 +#: ../../c-api/type.rst:259 msgid "" "Find the first superclass whose module was created from the given :c:type:" "`PyModuleDef` *def*, and return that module." msgstr "" -#: ../../c-api/type.rst:257 +#: ../../c-api/type.rst:262 msgid "" "If no module is found, raises a :py:class:`TypeError` and returns ``NULL``." msgstr "" -#: ../../c-api/type.rst:259 +#: ../../c-api/type.rst:264 msgid "" "This function is intended to be used together with :c:func:" "`PyModule_GetState()` to get module state from slot methods (such as :c:" @@ -337,40 +339,40 @@ msgid "" "type:`PyCMethod` calling convention." msgstr "" -#: ../../c-api/type.rst:269 +#: ../../c-api/type.rst:274 msgid "Attempt to assign a version tag to the given type." msgstr "" -#: ../../c-api/type.rst:271 +#: ../../c-api/type.rst:276 msgid "" "Returns 1 if the type already had a valid version tag or a new one was " "assigned, or 0 if a new tag could not be assigned." msgstr "" -#: ../../c-api/type.rst:278 +#: ../../c-api/type.rst:283 msgid "Creating Heap-Allocated Types" msgstr "" -#: ../../c-api/type.rst:280 +#: ../../c-api/type.rst:285 msgid "" "The following functions and structs are used to create :ref:`heap types " "`." msgstr "" -#: ../../c-api/type.rst:285 +#: ../../c-api/type.rst:290 msgid "" "Create and return a :ref:`heap type ` from the *spec* (see :c:" "macro:`Py_TPFLAGS_HEAPTYPE`)." msgstr "" -#: ../../c-api/type.rst:288 +#: ../../c-api/type.rst:293 msgid "" "The metaclass *metaclass* is used to construct the resulting type object. " "When *metaclass* is ``NULL``, the metaclass is derived from *bases* (or " "*Py_tp_base[s]* slots if *bases* is ``NULL``, see below)." msgstr "" -#: ../../c-api/type.rst:292 +#: ../../c-api/type.rst:297 msgid "" "Metaclasses that override :c:member:`~PyTypeObject.tp_new` are not " "supported, except if ``tp_new`` is ``NULL``. (For backwards compatibility, " @@ -379,7 +381,7 @@ msgid "" "deprecated and in Python 3.14+ such metaclasses will not be supported.)" msgstr "" -#: ../../c-api/type.rst:299 +#: ../../c-api/type.rst:304 msgid "" "The *bases* argument can be used to specify base classes; it can either be " "only one class or a tuple of classes. If *bases* is ``NULL``, the " @@ -388,7 +390,7 @@ msgid "" "derives from :class:`object`." msgstr "" -#: ../../c-api/type.rst:305 +#: ../../c-api/type.rst:310 msgid "" "The *module* argument can be used to record the module in which the new " "class is defined. It must be a module object or ``NULL``. If not ``NULL``, " @@ -397,11 +399,11 @@ msgid "" "subclasses; it must be specified for each class individually." msgstr "" -#: ../../c-api/type.rst:312 +#: ../../c-api/type.rst:317 msgid "This function calls :c:func:`PyType_Ready` on the new type." msgstr "" -#: ../../c-api/type.rst:314 +#: ../../c-api/type.rst:319 msgid "" "Note that this function does *not* fully match the behavior of calling :py:" "class:`type() ` or using the :keyword:`class` statement. With user-" @@ -410,41 +412,41 @@ msgid "" "Specifically:" msgstr "" -#: ../../c-api/type.rst:321 +#: ../../c-api/type.rst:326 msgid "" ":py:meth:`~object.__new__` is not called on the new class (and it must be " "set to ``type.__new__``)." msgstr "" -#: ../../c-api/type.rst:323 +#: ../../c-api/type.rst:328 msgid ":py:meth:`~object.__init__` is not called on the new class." msgstr "" -#: ../../c-api/type.rst:324 +#: ../../c-api/type.rst:329 msgid ":py:meth:`~object.__init_subclass__` is not called on any bases." msgstr "" -#: ../../c-api/type.rst:325 +#: ../../c-api/type.rst:330 msgid ":py:meth:`~object.__set_name__` is not called on new descriptors." msgstr "" -#: ../../c-api/type.rst:331 +#: ../../c-api/type.rst:336 msgid "Equivalent to ``PyType_FromMetaclass(NULL, module, spec, bases)``." msgstr "" -#: ../../c-api/type.rst:337 +#: ../../c-api/type.rst:342 msgid "" "The function now accepts a single class as the *bases* argument and ``NULL`` " "as the ``tp_doc`` slot." msgstr "" -#: ../../c-api/type.rst:342 ../../c-api/type.rst:359 +#: ../../c-api/type.rst:347 ../../c-api/type.rst:364 msgid "" "The function now finds and uses a metaclass corresponding to the provided " "base classes. Previously, only :class:`type` instances were returned." msgstr "" -#: ../../c-api/type.rst:345 ../../c-api/type.rst:362 ../../c-api/type.rst:378 +#: ../../c-api/type.rst:350 ../../c-api/type.rst:367 ../../c-api/type.rst:383 msgid "" "The :c:member:`~PyTypeObject.tp_new` of the metaclass is *ignored*. which " "may result in incomplete initialization. Creating classes whose metaclass " @@ -452,60 +454,62 @@ msgid "" "it will be no longer allowed." msgstr "" -#: ../../c-api/type.rst:353 +#: ../../c-api/type.rst:358 msgid "Equivalent to ``PyType_FromMetaclass(NULL, NULL, spec, bases)``." msgstr "" -#: ../../c-api/type.rst:370 +#: ../../c-api/type.rst:375 msgid "Equivalent to ``PyType_FromMetaclass(NULL, NULL, spec, NULL)``." msgstr "" -#: ../../c-api/type.rst:374 +#: ../../c-api/type.rst:379 msgid "" "The function now finds and uses a metaclass corresponding to the base " "classes provided in *Py_tp_base[s]* slots. Previously, only :class:`type` " "instances were returned." msgstr "" -#: ../../c-api/type.rst:395 +#: ../../c-api/type.rst:400 msgid "Structure defining a type's behavior." msgstr "" -#: ../../c-api/type.rst:399 +#: ../../c-api/type.rst:404 msgid "Name of the type, used to set :c:member:`PyTypeObject.tp_name`." msgstr "" -#: ../../c-api/type.rst:403 +#: ../../c-api/type.rst:408 msgid "" "If positive, specifies the size of the instance in bytes. It is used to set :" "c:member:`PyTypeObject.tp_basicsize`." msgstr "" -#: ../../c-api/type.rst:406 +#: ../../c-api/type.rst:411 msgid "" "If zero, specifies that :c:member:`~PyTypeObject.tp_basicsize` should be " "inherited." msgstr "" -#: ../../c-api/type.rst:409 +#: ../../c-api/type.rst:414 msgid "" "If negative, the absolute value specifies how much space instances of the " "class need *in addition* to the superclass. Use :c:func:" "`PyObject_GetTypeData` to get a pointer to subclass-specific memory reserved " -"this way." +"this way. For negative :c:member:`!basicsize`, Python will insert padding " +"when needed to meet :c:member:`~PyTypeObject.tp_basicsize`'s alignment " +"requirements." msgstr "" -#: ../../c-api/type.rst:416 +#: ../../c-api/type.rst:424 msgid "Previously, this field could not be negative." msgstr "" -#: ../../c-api/type.rst:420 +#: ../../c-api/type.rst:428 msgid "" "Size of one element of a variable-size type, in bytes. Used to set :c:member:" "`PyTypeObject.tp_itemsize`. See ``tp_itemsize`` documentation for caveats." msgstr "" -#: ../../c-api/type.rst:424 +#: ../../c-api/type.rst:432 msgid "" "If zero, :c:member:`~PyTypeObject.tp_itemsize` is inherited. Extending " "arbitrary variable-sized classes is dangerous, since some types use a fixed " @@ -514,58 +518,58 @@ msgid "" "only possible in the following situations:" msgstr "" -#: ../../c-api/type.rst:431 +#: ../../c-api/type.rst:439 msgid "" "The base is not variable-sized (its :c:member:`~PyTypeObject.tp_itemsize`)." msgstr "" -#: ../../c-api/type.rst:433 +#: ../../c-api/type.rst:441 msgid "" "The requested :c:member:`PyType_Spec.basicsize` is positive, suggesting that " "the memory layout of the base class is known." msgstr "" -#: ../../c-api/type.rst:435 +#: ../../c-api/type.rst:443 msgid "" "The requested :c:member:`PyType_Spec.basicsize` is zero, suggesting that the " "subclass does not access the instance's memory directly." msgstr "" -#: ../../c-api/type.rst:438 +#: ../../c-api/type.rst:446 msgid "With the :c:macro:`Py_TPFLAGS_ITEMS_AT_END` flag." msgstr "" -#: ../../c-api/type.rst:442 +#: ../../c-api/type.rst:450 msgid "Type flags, used to set :c:member:`PyTypeObject.tp_flags`." msgstr "" -#: ../../c-api/type.rst:444 +#: ../../c-api/type.rst:452 msgid "" "If the ``Py_TPFLAGS_HEAPTYPE`` flag is not set, :c:func:" "`PyType_FromSpecWithBases` sets it automatically." msgstr "" -#: ../../c-api/type.rst:449 +#: ../../c-api/type.rst:457 msgid "" "Array of :c:type:`PyType_Slot` structures. Terminated by the special slot " "value ``{0, NULL}``." msgstr "" -#: ../../c-api/type.rst:452 +#: ../../c-api/type.rst:460 msgid "Each slot ID should be specified at most once." msgstr "" -#: ../../c-api/type.rst:462 +#: ../../c-api/type.rst:470 msgid "" "Structure defining optional functionality of a type, containing a slot ID " "and a value pointer." msgstr "" -#: ../../c-api/type.rst:467 +#: ../../c-api/type.rst:475 msgid "A slot ID." msgstr "" -#: ../../c-api/type.rst:469 +#: ../../c-api/type.rst:477 msgid "" "Slot IDs are named like the field names of the structures :c:type:" "`PyTypeObject`, :c:type:`PyNumberMethods`, :c:type:`PySequenceMethods`, :c:" @@ -573,42 +577,42 @@ msgid "" "prefix. For example, use:" msgstr "" -#: ../../c-api/type.rst:475 +#: ../../c-api/type.rst:483 msgid "``Py_tp_dealloc`` to set :c:member:`PyTypeObject.tp_dealloc`" msgstr "" -#: ../../c-api/type.rst:476 +#: ../../c-api/type.rst:484 msgid "``Py_nb_add`` to set :c:member:`PyNumberMethods.nb_add`" msgstr "" -#: ../../c-api/type.rst:477 +#: ../../c-api/type.rst:485 msgid "``Py_sq_length`` to set :c:member:`PySequenceMethods.sq_length`" msgstr "" -#: ../../c-api/type.rst:479 +#: ../../c-api/type.rst:487 msgid "" "The following “offset” fields cannot be set using :c:type:`PyType_Slot`:" msgstr "" -#: ../../c-api/type.rst:481 +#: ../../c-api/type.rst:489 msgid "" ":c:member:`~PyTypeObject.tp_weaklistoffset` (use :c:macro:" "`Py_TPFLAGS_MANAGED_WEAKREF` instead if possible)" msgstr "" -#: ../../c-api/type.rst:483 +#: ../../c-api/type.rst:491 msgid "" ":c:member:`~PyTypeObject.tp_dictoffset` (use :c:macro:" "`Py_TPFLAGS_MANAGED_DICT` instead if possible)" msgstr "" -#: ../../c-api/type.rst:485 +#: ../../c-api/type.rst:493 msgid "" ":c:member:`~PyTypeObject.tp_vectorcall_offset` (use " "``\"__vectorcalloffset__\"`` in :ref:`PyMemberDef `)" msgstr "" -#: ../../c-api/type.rst:489 +#: ../../c-api/type.rst:497 msgid "" "If it is not possible to switch to a ``MANAGED`` flag (for example, for " "vectorcall or to support Python older than 3.12), specify the offset in :c:" @@ -616,48 +620,48 @@ msgid "" "documentation ` for details." msgstr "" -#: ../../c-api/type.rst:495 +#: ../../c-api/type.rst:503 msgid "The following fields cannot be set at all when creating a heap type:" msgstr "" -#: ../../c-api/type.rst:497 +#: ../../c-api/type.rst:505 msgid "" ":c:member:`~PyTypeObject.tp_vectorcall` (use :c:member:`~PyTypeObject." "tp_new` and/or :c:member:`~PyTypeObject.tp_init`)" msgstr "" -#: ../../c-api/type.rst:501 +#: ../../c-api/type.rst:509 msgid "" "Internal fields: :c:member:`~PyTypeObject.tp_dict`, :c:member:`~PyTypeObject." "tp_mro`, :c:member:`~PyTypeObject.tp_cache`, :c:member:`~PyTypeObject." "tp_subclasses`, and :c:member:`~PyTypeObject.tp_weaklist`." msgstr "" -#: ../../c-api/type.rst:508 +#: ../../c-api/type.rst:516 msgid "" "Setting :c:data:`Py_tp_bases` or :c:data:`Py_tp_base` may be problematic on " "some platforms. To avoid issues, use the *bases* argument of :c:func:" "`PyType_FromSpecWithBases` instead." msgstr "" -#: ../../c-api/type.rst:515 +#: ../../c-api/type.rst:521 msgid "Slots in :c:type:`PyBufferProcs` may be set in the unlimited API." msgstr "" -#: ../../c-api/type.rst:517 +#: ../../c-api/type.rst:524 msgid "" ":c:member:`~PyBufferProcs.bf_getbuffer` and :c:member:`~PyBufferProcs." "bf_releasebuffer` are now available under the :ref:`limited API `." msgstr "" -#: ../../c-api/type.rst:524 +#: ../../c-api/type.rst:531 msgid "" "The desired value of the slot. In most cases, this is a pointer to a " "function." msgstr "" -#: ../../c-api/type.rst:527 +#: ../../c-api/type.rst:534 msgid "Slots other than ``Py_tp_doc`` may not be ``NULL``." msgstr "" diff --git a/c-api/typehints.po b/c-api/typehints.po index 2159a6a6d..5b8bd9527 100644 --- a/c-api/typehints.po +++ b/c-api/typehints.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Vitor Buxbaum Orlandi, 2021 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -52,7 +51,7 @@ msgid "" "lazily from ``__args__``. On failure, an exception is raised and ``NULL`` " "is returned." msgstr "" -"Cria um objeto :ref:`GenericAlias ​​`. Equivalente a " +"Cria um objeto :ref:`GenericAlias `. Equivalente a " "chamar a classe Python :class:`types.GenericAlias`. Os argumentos *origin* e " "*args* definem os atributos ``__origin__`` e ``__args__`` de " "``GenericAlias`` respectivamente. *origin* deve ser um :c:expr:" @@ -68,6 +67,26 @@ msgstr "" msgid "Here's an example of how to make an extension type generic::" msgstr "Aqui está um exemplo de como tornar um tipo de extensão genérico::" +#: ../../c-api/typehints.rst:30 +msgid "" +"...\n" +"static PyMethodDef my_obj_methods[] = {\n" +" // Other methods.\n" +" ...\n" +" {\"__class_getitem__\", Py_GenericAlias, METH_O|METH_CLASS, \"See PEP " +"585\"}\n" +" ...\n" +"}" +msgstr "" +"...\n" +"static PyMethodDef my_obj_methods[] = {\n" +" // Outros métodos.\n" +" ...\n" +" {\"__class_getitem__\", Py_GenericAlias, METH_O|METH_CLASS, \"Veja PEP " +"585\"}\n" +" ...\n" +"}" + #: ../../c-api/typehints.rst:38 msgid "The data model method :meth:`~object.__class_getitem__`." msgstr "O método de modelo de dados :meth:`~object.__class_getitem__`." diff --git a/c-api/typeobj.po b/c-api/typeobj.po index ec240d324..e2fd49276 100644 --- a/c-api/typeobj.po +++ b/c-api/typeobj.po @@ -1,37 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Marco Rougeth , 2021 -# (Douglas da Silva) , 2021 -# Claudio Rogerio Carvalho Filho , 2023 -# Vitor Buxbaum Orlandi, 2023 -# Pedro Fonini, 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../c-api/typeobj.rst:6 -msgid "Type Objects" -msgstr "Objetos tipo" +msgid "Type Object Structures" +msgstr "" #: ../../c-api/typeobj.rst:8 msgid "" @@ -148,7 +142,7 @@ msgstr ":c:member:`~PyTypeObject.tp_basicsize`" #: ../../c-api/typeobj.rst:0 ../../c-api/typeobj.rst:46 #: ../../c-api/typeobj.rst:48 ../../c-api/typeobj.rst:52 #: ../../c-api/typeobj.rst:99 ../../c-api/typeobj.rst:120 -#: ../../c-api/typeobj.rst:416 +#: ../../c-api/typeobj.rst:417 msgid ":c:type:`Py_ssize_t`" msgstr "" @@ -161,7 +155,7 @@ msgid ":c:member:`~PyTypeObject.tp_dealloc`" msgstr ":c:member:`~PyTypeObject.tp_dealloc`" #: ../../c-api/typeobj.rst:50 ../../c-api/typeobj.rst:142 -#: ../../c-api/typeobj.rst:146 ../../c-api/typeobj.rst:346 +#: ../../c-api/typeobj.rst:146 ../../c-api/typeobj.rst:347 msgid ":c:type:`destructor`" msgstr ":c:type:`destructor`" @@ -173,7 +167,7 @@ msgstr ":c:member:`~PyTypeObject.tp_vectorcall_offset`" msgid "(:c:member:`~PyTypeObject.tp_getattr`)" msgstr "(:c:member:`~PyTypeObject.tp_getattr`)" -#: ../../c-api/typeobj.rst:54 ../../c-api/typeobj.rst:370 +#: ../../c-api/typeobj.rst:54 ../../c-api/typeobj.rst:371 msgid ":c:type:`getattrfunc`" msgstr ":c:type:`getattrfunc`" @@ -192,7 +186,7 @@ msgstr "G" msgid "(:c:member:`~PyTypeObject.tp_setattr`)" msgstr "(:c:member:`~PyTypeObject.tp_setattr`)" -#: ../../c-api/typeobj.rst:57 ../../c-api/typeobj.rst:375 +#: ../../c-api/typeobj.rst:57 ../../c-api/typeobj.rst:376 msgid ":c:type:`setattrfunc`" msgstr ":c:type:`setattrfunc`" @@ -210,6 +204,7 @@ msgstr ":c:type:`PyAsyncMethods` *" #: ../../c-api/typeobj.rst:60 ../../c-api/typeobj.rst:64 #: ../../c-api/typeobj.rst:66 ../../c-api/typeobj.rst:68 +#: ../../c-api/typeobj.rst:82 msgid ":ref:`sub-slots`" msgstr ":ref:`sub-slots`" @@ -224,7 +219,7 @@ msgid ":c:member:`~PyTypeObject.tp_repr`" msgstr ":c:member:`~PyTypeObject.tp_repr`" #: ../../c-api/typeobj.rst:62 ../../c-api/typeobj.rst:74 -#: ../../c-api/typeobj.rst:368 +#: ../../c-api/typeobj.rst:369 msgid ":c:type:`reprfunc`" msgstr ":c:type:`reprfunc`" @@ -260,7 +255,7 @@ msgstr ":c:type:`PyMappingMethods` *" msgid ":c:member:`~PyTypeObject.tp_hash`" msgstr ":c:member:`~PyTypeObject.tp_hash`" -#: ../../c-api/typeobj.rst:70 ../../c-api/typeobj.rst:404 +#: ../../c-api/typeobj.rst:70 ../../c-api/typeobj.rst:405 msgid ":c:type:`hashfunc`" msgstr ":c:type:`hashfunc`" @@ -273,7 +268,7 @@ msgid ":c:member:`~PyTypeObject.tp_call`" msgstr ":c:member:`~PyTypeObject.tp_call`" #: ../../c-api/typeobj.rst:72 ../../c-api/typeobj.rst:237 -#: ../../c-api/typeobj.rst:240 ../../c-api/typeobj.rst:440 +#: ../../c-api/typeobj.rst:240 ../../c-api/typeobj.rst:441 msgid ":c:type:`ternaryfunc`" msgstr ":c:type:`ternaryfunc`" @@ -293,7 +288,7 @@ msgstr "__str__" msgid ":c:member:`~PyTypeObject.tp_getattro`" msgstr ":c:member:`~PyTypeObject.tp_getattro`" -#: ../../c-api/typeobj.rst:76 ../../c-api/typeobj.rst:381 +#: ../../c-api/typeobj.rst:76 ../../c-api/typeobj.rst:382 msgid ":c:type:`getattrofunc`" msgstr ":c:type:`getattrofunc`" @@ -301,7 +296,7 @@ msgstr ":c:type:`getattrofunc`" msgid ":c:member:`~PyTypeObject.tp_setattro`" msgstr ":c:member:`~PyTypeObject.tp_setattro`" -#: ../../c-api/typeobj.rst:79 ../../c-api/typeobj.rst:386 +#: ../../c-api/typeobj.rst:79 ../../c-api/typeobj.rst:387 msgid ":c:type:`setattrofunc`" msgstr ":c:type:`setattrofunc`" @@ -340,7 +335,7 @@ msgstr "__doc__" msgid ":c:member:`~PyTypeObject.tp_traverse`" msgstr ":c:member:`~PyTypeObject.tp_traverse`" -#: ../../c-api/typeobj.rst:88 ../../c-api/typeobj.rst:350 +#: ../../c-api/typeobj.rst:88 ../../c-api/typeobj.rst:351 msgid ":c:type:`traverseproc`" msgstr ":c:type:`traverseproc`" @@ -349,7 +344,7 @@ msgid ":c:member:`~PyTypeObject.tp_clear`" msgstr ":c:member:`~PyTypeObject.tp_clear`" #: ../../c-api/typeobj.rst:90 ../../c-api/typeobj.rst:130 -#: ../../c-api/typeobj.rst:248 ../../c-api/typeobj.rst:429 +#: ../../c-api/typeobj.rst:248 ../../c-api/typeobj.rst:430 msgid ":c:type:`inquiry`" msgstr ":c:type:`inquiry`" @@ -357,7 +352,7 @@ msgstr ":c:type:`inquiry`" msgid ":c:member:`~PyTypeObject.tp_richcompare`" msgstr ":c:member:`~PyTypeObject.tp_richcompare`" -#: ../../c-api/typeobj.rst:92 ../../c-api/typeobj.rst:406 +#: ../../c-api/typeobj.rst:92 ../../c-api/typeobj.rst:407 msgid ":c:type:`richcmpfunc`" msgstr ":c:type:`richcmpfunc`" @@ -373,7 +368,7 @@ msgstr "" msgid ":c:member:`~PyTypeObject.tp_iter`" msgstr ":c:member:`~PyTypeObject.tp_iter`" -#: ../../c-api/typeobj.rst:101 ../../c-api/typeobj.rst:412 +#: ../../c-api/typeobj.rst:101 ../../c-api/typeobj.rst:413 msgid ":c:type:`getiterfunc`" msgstr ":c:type:`getiterfunc`" @@ -385,7 +380,7 @@ msgstr "__iter__" msgid ":c:member:`~PyTypeObject.tp_iternext`" msgstr ":c:member:`~PyTypeObject.tp_iternext`" -#: ../../c-api/typeobj.rst:103 ../../c-api/typeobj.rst:414 +#: ../../c-api/typeobj.rst:103 ../../c-api/typeobj.rst:415 msgid ":c:type:`iternextfunc`" msgstr ":c:type:`iternextfunc`" @@ -436,15 +431,15 @@ msgstr ":c:member:`~PyTypeObject.tp_dict`" #: ../../c-api/typeobj.rst:0 ../../c-api/typeobj.rst:113 #: ../../c-api/typeobj.rst:132 ../../c-api/typeobj.rst:134 #: ../../c-api/typeobj.rst:136 ../../c-api/typeobj.rst:140 -#: ../../c-api/typeobj.rst:341 ../../c-api/typeobj.rst:346 -#: ../../c-api/typeobj.rst:356 ../../c-api/typeobj.rst:368 -#: ../../c-api/typeobj.rst:370 ../../c-api/typeobj.rst:381 -#: ../../c-api/typeobj.rst:392 ../../c-api/typeobj.rst:404 -#: ../../c-api/typeobj.rst:406 ../../c-api/typeobj.rst:412 -#: ../../c-api/typeobj.rst:414 ../../c-api/typeobj.rst:416 -#: ../../c-api/typeobj.rst:429 ../../c-api/typeobj.rst:431 -#: ../../c-api/typeobj.rst:435 ../../c-api/typeobj.rst:440 -#: ../../c-api/typeobj.rst:446 +#: ../../c-api/typeobj.rst:342 ../../c-api/typeobj.rst:347 +#: ../../c-api/typeobj.rst:357 ../../c-api/typeobj.rst:369 +#: ../../c-api/typeobj.rst:371 ../../c-api/typeobj.rst:382 +#: ../../c-api/typeobj.rst:393 ../../c-api/typeobj.rst:405 +#: ../../c-api/typeobj.rst:407 ../../c-api/typeobj.rst:413 +#: ../../c-api/typeobj.rst:415 ../../c-api/typeobj.rst:417 +#: ../../c-api/typeobj.rst:430 ../../c-api/typeobj.rst:432 +#: ../../c-api/typeobj.rst:436 ../../c-api/typeobj.rst:441 +#: ../../c-api/typeobj.rst:447 msgid ":c:type:`PyObject` *" msgstr ":c:type:`PyObject` *" @@ -456,7 +451,7 @@ msgstr "__dict__" msgid ":c:member:`~PyTypeObject.tp_descr_get`" msgstr ":c:member:`~PyTypeObject.tp_descr_get`" -#: ../../c-api/typeobj.rst:115 ../../c-api/typeobj.rst:392 +#: ../../c-api/typeobj.rst:115 ../../c-api/typeobj.rst:393 msgid ":c:type:`descrgetfunc`" msgstr ":c:type:`descrgetfunc`" @@ -468,7 +463,7 @@ msgstr "__get__" msgid ":c:member:`~PyTypeObject.tp_descr_set`" msgstr ":c:member:`~PyTypeObject.tp_descr_set`" -#: ../../c-api/typeobj.rst:117 ../../c-api/typeobj.rst:398 +#: ../../c-api/typeobj.rst:117 ../../c-api/typeobj.rst:399 msgid ":c:type:`descrsetfunc`" msgstr ":c:type:`descrsetfunc`" @@ -484,7 +479,7 @@ msgstr "" msgid ":c:member:`~PyTypeObject.tp_init`" msgstr ":c:member:`~PyTypeObject.tp_init`" -#: ../../c-api/typeobj.rst:122 ../../c-api/typeobj.rst:362 +#: ../../c-api/typeobj.rst:122 ../../c-api/typeobj.rst:363 msgid ":c:type:`initproc`" msgstr ":c:type:`initproc`" @@ -496,7 +491,7 @@ msgstr "__init__" msgid ":c:member:`~PyTypeObject.tp_alloc`" msgstr ":c:member:`~PyTypeObject.tp_alloc`" -#: ../../c-api/typeobj.rst:124 ../../c-api/typeobj.rst:341 +#: ../../c-api/typeobj.rst:124 ../../c-api/typeobj.rst:342 msgid ":c:type:`allocfunc`" msgstr ":c:type:`allocfunc`" @@ -504,7 +499,7 @@ msgstr ":c:type:`allocfunc`" msgid ":c:member:`~PyTypeObject.tp_new`" msgstr ":c:member:`~PyTypeObject.tp_new`" -#: ../../c-api/typeobj.rst:126 ../../c-api/typeobj.rst:356 +#: ../../c-api/typeobj.rst:126 ../../c-api/typeobj.rst:357 msgid ":c:type:`newfunc`" msgstr ":c:type:`newfunc`" @@ -516,7 +511,7 @@ msgstr "__new__" msgid ":c:member:`~PyTypeObject.tp_free`" msgstr ":c:member:`~PyTypeObject.tp_free`" -#: ../../c-api/typeobj.rst:128 ../../c-api/typeobj.rst:348 +#: ../../c-api/typeobj.rst:128 ../../c-api/typeobj.rst:349 msgid ":c:type:`freefunc`" msgstr ":c:type:`freefunc`" @@ -553,7 +548,7 @@ msgid "[:c:member:`~PyTypeObject.tp_subclasses`]" msgstr "[:c:member:`~PyTypeObject.tp_subclasses`]" #: ../../c-api/typeobj.rst:0 ../../c-api/typeobj.rst:138 -#: ../../c-api/typeobj.rst:279 ../../c-api/typeobj.rst:348 +#: ../../c-api/typeobj.rst:279 ../../c-api/typeobj.rst:349 msgid "void *" msgstr "" @@ -637,10 +632,29 @@ msgstr "" msgid "**\"D\"**: default (if slot is set to ``NULL``)" msgstr "" +#: ../../c-api/typeobj.rst:172 +msgid "" +"X - PyType_Ready sets this value if it is NULL\n" +"~ - PyType_Ready always sets this value (it should be NULL)\n" +"? - PyType_Ready may set this value depending on other slots\n" +"\n" +"Also see the inheritance column (\"I\")." +msgstr "" + #: ../../c-api/typeobj.rst:180 msgid "**\"I\"**: inheritance" msgstr "" +#: ../../c-api/typeobj.rst:182 +msgid "" +"X - type slot is inherited via *PyType_Ready* if defined with a *NULL* " +"value\n" +"% - the slots of the sub-struct are inherited individually\n" +"G - inherited, but only in combination with other slots; see the slot's " +"description\n" +"? - it's complicated; see the slot's description" +msgstr "" + #: ../../c-api/typeobj.rst:189 msgid "" "Note that some slots are effectively inherited through the normal attribute " @@ -668,7 +682,7 @@ msgstr ":c:member:`~PyAsyncMethods.am_await`" #: ../../c-api/typeobj.rst:244 ../../c-api/typeobj.rst:246 #: ../../c-api/typeobj.rst:250 ../../c-api/typeobj.rst:277 #: ../../c-api/typeobj.rst:281 ../../c-api/typeobj.rst:291 -#: ../../c-api/typeobj.rst:431 +#: ../../c-api/typeobj.rst:432 msgid ":c:type:`unaryfunc`" msgstr ":c:type:`unaryfunc`" @@ -718,7 +732,7 @@ msgstr ":c:member:`~PyNumberMethods.nb_add`" #: ../../c-api/typeobj.rst:289 ../../c-api/typeobj.rst:293 #: ../../c-api/typeobj.rst:296 ../../c-api/typeobj.rst:302 #: ../../c-api/typeobj.rst:311 ../../c-api/typeobj.rst:322 -#: ../../c-api/typeobj.rst:435 +#: ../../c-api/typeobj.rst:436 msgid ":c:type:`binaryfunc`" msgstr ":c:type:`binaryfunc`" @@ -1007,7 +1021,7 @@ msgid ":c:member:`~PyMappingMethods.mp_length`" msgstr ":c:member:`~PyMappingMethods.mp_length`" #: ../../c-api/typeobj.rst:300 ../../c-api/typeobj.rst:309 -#: ../../c-api/typeobj.rst:416 +#: ../../c-api/typeobj.rst:417 msgid ":c:type:`lenfunc`" msgstr ":c:type:`lenfunc`" @@ -1027,7 +1041,7 @@ msgstr "__getitem__" msgid ":c:member:`~PyMappingMethods.mp_ass_subscript`" msgstr ":c:member:`~PyMappingMethods.mp_ass_subscript`" -#: ../../c-api/typeobj.rst:304 ../../c-api/typeobj.rst:462 +#: ../../c-api/typeobj.rst:304 ../../c-api/typeobj.rst:463 msgid ":c:type:`objobjargproc`" msgstr ":c:type:`objobjargproc`" @@ -1052,7 +1066,7 @@ msgid ":c:member:`~PySequenceMethods.sq_repeat`" msgstr ":c:member:`~PySequenceMethods.sq_repeat`" #: ../../c-api/typeobj.rst:313 ../../c-api/typeobj.rst:315 -#: ../../c-api/typeobj.rst:324 ../../c-api/typeobj.rst:446 +#: ../../c-api/typeobj.rst:324 ../../c-api/typeobj.rst:447 msgid ":c:type:`ssizeargfunc`" msgstr ":c:type:`ssizeargfunc`" @@ -1068,7 +1082,7 @@ msgstr ":c:member:`~PySequenceMethods.sq_item`" msgid ":c:member:`~PySequenceMethods.sq_ass_item`" msgstr ":c:member:`~PySequenceMethods.sq_ass_item`" -#: ../../c-api/typeobj.rst:317 ../../c-api/typeobj.rst:451 +#: ../../c-api/typeobj.rst:317 ../../c-api/typeobj.rst:452 msgid ":c:type:`ssizeobjargproc`" msgstr ":c:type:`ssizeobjargproc`" @@ -1080,7 +1094,7 @@ msgstr "" msgid ":c:member:`~PySequenceMethods.sq_contains`" msgstr ":c:member:`~PySequenceMethods.sq_contains`" -#: ../../c-api/typeobj.rst:320 ../../c-api/typeobj.rst:457 +#: ../../c-api/typeobj.rst:320 ../../c-api/typeobj.rst:458 msgid ":c:type:`objobjproc`" msgstr ":c:type:`objobjproc`" @@ -1104,6 +1118,10 @@ msgstr ":c:member:`~PyBufferProcs.bf_getbuffer`" msgid ":c:func:`getbufferproc`" msgstr ":c:func:`getbufferproc`" +#: ../../c-api/typeobj.rst:328 +msgid "__buffer__" +msgstr "" + #: ../../c-api/typeobj.rst:330 msgid ":c:member:`~PyBufferProcs.bf_releasebuffer`" msgstr ":c:member:`~PyBufferProcs.bf_releasebuffer`" @@ -1112,24 +1130,28 @@ msgstr ":c:member:`~PyBufferProcs.bf_releasebuffer`" msgid ":c:func:`releasebufferproc`" msgstr ":c:func:`releasebufferproc`" -#: ../../c-api/typeobj.rst:336 +#: ../../c-api/typeobj.rst:330 +msgid "__release_\\ buffer\\__" +msgstr "" + +#: ../../c-api/typeobj.rst:337 msgid "slot typedefs" msgstr "" -#: ../../c-api/typeobj.rst:339 +#: ../../c-api/typeobj.rst:340 msgid "typedef" msgstr "typedef" -#: ../../c-api/typeobj.rst:339 +#: ../../c-api/typeobj.rst:340 msgid "Parameter Types" msgstr "" -#: ../../c-api/typeobj.rst:339 +#: ../../c-api/typeobj.rst:340 msgid "Return Type" msgstr "" -#: ../../c-api/typeobj.rst:346 ../../c-api/typeobj.rst:348 -#: ../../c-api/typeobj.rst:424 +#: ../../c-api/typeobj.rst:347 ../../c-api/typeobj.rst:349 +#: ../../c-api/typeobj.rst:425 msgid "void" msgstr "void" @@ -1137,20 +1159,20 @@ msgstr "void" msgid ":c:type:`visitproc`" msgstr ":c:type:`visitproc`" -#: ../../c-api/typeobj.rst:0 ../../c-api/typeobj.rst:350 -#: ../../c-api/typeobj.rst:362 ../../c-api/typeobj.rst:375 -#: ../../c-api/typeobj.rst:386 ../../c-api/typeobj.rst:398 -#: ../../c-api/typeobj.rst:418 ../../c-api/typeobj.rst:429 -#: ../../c-api/typeobj.rst:451 ../../c-api/typeobj.rst:457 -#: ../../c-api/typeobj.rst:462 +#: ../../c-api/typeobj.rst:0 ../../c-api/typeobj.rst:351 +#: ../../c-api/typeobj.rst:363 ../../c-api/typeobj.rst:376 +#: ../../c-api/typeobj.rst:387 ../../c-api/typeobj.rst:399 +#: ../../c-api/typeobj.rst:419 ../../c-api/typeobj.rst:430 +#: ../../c-api/typeobj.rst:452 ../../c-api/typeobj.rst:458 +#: ../../c-api/typeobj.rst:463 msgid "int" msgstr "int" -#: ../../c-api/typeobj.rst:404 +#: ../../c-api/typeobj.rst:405 msgid "Py_hash_t" msgstr "Py_hash_t" -#: ../../c-api/typeobj.rst:418 +#: ../../c-api/typeobj.rst:419 msgid ":c:type:`getbufferproc`" msgstr ":c:type:`getbufferproc`" @@ -1158,30 +1180,120 @@ msgstr ":c:type:`getbufferproc`" msgid ":c:type:`Py_buffer` *" msgstr "" -#: ../../c-api/typeobj.rst:424 +#: ../../c-api/typeobj.rst:425 msgid ":c:type:`releasebufferproc`" msgstr ":c:type:`releasebufferproc`" -#: ../../c-api/typeobj.rst:469 +#: ../../c-api/typeobj.rst:470 msgid "See :ref:`slot-typedefs` below for more detail." msgstr "" -#: ../../c-api/typeobj.rst:473 +#: ../../c-api/typeobj.rst:474 msgid "PyTypeObject Definition" msgstr "" -#: ../../c-api/typeobj.rst:475 +#: ../../c-api/typeobj.rst:476 msgid "" "The structure definition for :c:type:`PyTypeObject` can be found in :file:" -"`Include/object.h`. For convenience of reference, this repeats the " +"`Include/cpython/object.h`. For convenience of reference, this repeats the " "definition found there:" msgstr "" -#: ../../c-api/typeobj.rst:485 +#: ../../c-api/typeobj.rst:482 +msgid "" +"typedef struct _typeobject {\n" +" PyObject_VAR_HEAD\n" +" const char *tp_name; /* For printing, in format \".\" */\n" +" Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */\n" +"\n" +" /* Methods to implement standard operations */\n" +"\n" +" destructor tp_dealloc;\n" +" Py_ssize_t tp_vectorcall_offset;\n" +" getattrfunc tp_getattr;\n" +" setattrfunc tp_setattr;\n" +" PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)\n" +" or tp_reserved (Python 3) */\n" +" reprfunc tp_repr;\n" +"\n" +" /* Method suites for standard classes */\n" +"\n" +" PyNumberMethods *tp_as_number;\n" +" PySequenceMethods *tp_as_sequence;\n" +" PyMappingMethods *tp_as_mapping;\n" +"\n" +" /* More standard operations (here for binary compatibility) */\n" +"\n" +" hashfunc tp_hash;\n" +" ternaryfunc tp_call;\n" +" reprfunc tp_str;\n" +" getattrofunc tp_getattro;\n" +" setattrofunc tp_setattro;\n" +"\n" +" /* Functions to access object as input/output buffer */\n" +" PyBufferProcs *tp_as_buffer;\n" +"\n" +" /* Flags to define presence of optional/expanded features */\n" +" unsigned long tp_flags;\n" +"\n" +" const char *tp_doc; /* Documentation string */\n" +"\n" +" /* Assigned meaning in release 2.0 */\n" +" /* call function for all accessible objects */\n" +" traverseproc tp_traverse;\n" +"\n" +" /* delete references to contained objects */\n" +" inquiry tp_clear;\n" +"\n" +" /* Assigned meaning in release 2.1 */\n" +" /* rich comparisons */\n" +" richcmpfunc tp_richcompare;\n" +"\n" +" /* weak reference enabler */\n" +" Py_ssize_t tp_weaklistoffset;\n" +"\n" +" /* Iterators */\n" +" getiterfunc tp_iter;\n" +" iternextfunc tp_iternext;\n" +"\n" +" /* Attribute descriptor and subclassing stuff */\n" +" struct PyMethodDef *tp_methods;\n" +" struct PyMemberDef *tp_members;\n" +" struct PyGetSetDef *tp_getset;\n" +" // Strong reference on a heap type, borrowed reference on a static type\n" +" struct _typeobject *tp_base;\n" +" PyObject *tp_dict;\n" +" descrgetfunc tp_descr_get;\n" +" descrsetfunc tp_descr_set;\n" +" Py_ssize_t tp_dictoffset;\n" +" initproc tp_init;\n" +" allocfunc tp_alloc;\n" +" newfunc tp_new;\n" +" freefunc tp_free; /* Low-level free-memory routine */\n" +" inquiry tp_is_gc; /* For PyObject_IS_GC */\n" +" PyObject *tp_bases;\n" +" PyObject *tp_mro; /* method resolution order */\n" +" PyObject *tp_cache;\n" +" PyObject *tp_subclasses;\n" +" PyObject *tp_weaklist;\n" +" destructor tp_del;\n" +"\n" +" /* Type attribute cache version tag. Added in version 2.6 */\n" +" unsigned int tp_version_tag;\n" +"\n" +" destructor tp_finalize;\n" +" vectorcallfunc tp_vectorcall;\n" +"\n" +" /* bitset of which type-watchers care about this type */\n" +" unsigned char tp_watched;\n" +"} PyTypeObject;\n" +msgstr "" + +#: ../../c-api/typeobj.rst:486 msgid "PyObject Slots" msgstr "" -#: ../../c-api/typeobj.rst:487 +#: ../../c-api/typeobj.rst:488 msgid "" "The type object structure extends the :c:type:`PyVarObject` structure. The :" "c:member:`~PyVarObject.ob_size` field is used for dynamic types (created by :" @@ -1191,7 +1303,7 @@ msgid "" "the :c:member:`~PyVarObject.ob_size` field." msgstr "" -#: ../../c-api/typeobj.rst:496 +#: ../../c-api/typeobj.rst:497 msgid "" "This is the type object's reference count, initialized to ``1`` by the " "``PyObject_HEAD_INIT`` macro. Note that for :ref:`statically allocated type " @@ -1201,47 +1313,47 @@ msgid "" "instances *do* count as references." msgstr "" -#: ../../c-api/typeobj.rst:503 ../../c-api/typeobj.rst:526 -#: ../../c-api/typeobj.rst:540 ../../c-api/typeobj.rst:584 -#: ../../c-api/typeobj.rst:627 ../../c-api/typeobj.rst:686 -#: ../../c-api/typeobj.rst:727 ../../c-api/typeobj.rst:744 -#: ../../c-api/typeobj.rst:761 ../../c-api/typeobj.rst:779 -#: ../../c-api/typeobj.rst:803 ../../c-api/typeobj.rst:820 -#: ../../c-api/typeobj.rst:832 ../../c-api/typeobj.rst:844 -#: ../../c-api/typeobj.rst:877 ../../c-api/typeobj.rst:899 -#: ../../c-api/typeobj.rst:919 ../../c-api/typeobj.rst:940 -#: ../../c-api/typeobj.rst:966 ../../c-api/typeobj.rst:985 -#: ../../c-api/typeobj.rst:1001 ../../c-api/typeobj.rst:1040 -#: ../../c-api/typeobj.rst:1051 ../../c-api/typeobj.rst:1061 -#: ../../c-api/typeobj.rst:1071 ../../c-api/typeobj.rst:1085 -#: ../../c-api/typeobj.rst:1103 ../../c-api/typeobj.rst:1126 -#: ../../c-api/typeobj.rst:1144 ../../c-api/typeobj.rst:1157 -#: ../../c-api/typeobj.rst:1179 ../../c-api/typeobj.rst:1223 -#: ../../c-api/typeobj.rst:1244 ../../c-api/typeobj.rst:1263 -#: ../../c-api/typeobj.rst:1293 ../../c-api/typeobj.rst:1315 -#: ../../c-api/typeobj.rst:1341 ../../c-api/typeobj.rst:1426 -#: ../../c-api/typeobj.rst:1500 ../../c-api/typeobj.rst:1561 -#: ../../c-api/typeobj.rst:1597 ../../c-api/typeobj.rst:1622 -#: ../../c-api/typeobj.rst:1645 ../../c-api/typeobj.rst:1658 -#: ../../c-api/typeobj.rst:1673 ../../c-api/typeobj.rst:1687 -#: ../../c-api/typeobj.rst:1717 ../../c-api/typeobj.rst:1749 -#: ../../c-api/typeobj.rst:1775 ../../c-api/typeobj.rst:1793 -#: ../../c-api/typeobj.rst:1822 ../../c-api/typeobj.rst:1866 -#: ../../c-api/typeobj.rst:1883 ../../c-api/typeobj.rst:1924 -#: ../../c-api/typeobj.rst:1946 ../../c-api/typeobj.rst:1978 -#: ../../c-api/typeobj.rst:2006 ../../c-api/typeobj.rst:2019 -#: ../../c-api/typeobj.rst:2029 ../../c-api/typeobj.rst:2046 -#: ../../c-api/typeobj.rst:2063 ../../c-api/typeobj.rst:2077 -#: ../../c-api/typeobj.rst:2123 ../../c-api/typeobj.rst:2146 +#: ../../c-api/typeobj.rst:504 ../../c-api/typeobj.rst:527 +#: ../../c-api/typeobj.rst:544 ../../c-api/typeobj.rst:588 +#: ../../c-api/typeobj.rst:666 ../../c-api/typeobj.rst:742 +#: ../../c-api/typeobj.rst:783 ../../c-api/typeobj.rst:800 +#: ../../c-api/typeobj.rst:817 ../../c-api/typeobj.rst:835 +#: ../../c-api/typeobj.rst:859 ../../c-api/typeobj.rst:876 +#: ../../c-api/typeobj.rst:888 ../../c-api/typeobj.rst:900 +#: ../../c-api/typeobj.rst:933 ../../c-api/typeobj.rst:955 +#: ../../c-api/typeobj.rst:975 ../../c-api/typeobj.rst:996 +#: ../../c-api/typeobj.rst:1022 ../../c-api/typeobj.rst:1041 +#: ../../c-api/typeobj.rst:1057 ../../c-api/typeobj.rst:1096 +#: ../../c-api/typeobj.rst:1107 ../../c-api/typeobj.rst:1117 +#: ../../c-api/typeobj.rst:1127 ../../c-api/typeobj.rst:1141 +#: ../../c-api/typeobj.rst:1159 ../../c-api/typeobj.rst:1182 +#: ../../c-api/typeobj.rst:1200 ../../c-api/typeobj.rst:1213 +#: ../../c-api/typeobj.rst:1235 ../../c-api/typeobj.rst:1279 +#: ../../c-api/typeobj.rst:1300 ../../c-api/typeobj.rst:1319 +#: ../../c-api/typeobj.rst:1349 ../../c-api/typeobj.rst:1371 +#: ../../c-api/typeobj.rst:1397 ../../c-api/typeobj.rst:1482 +#: ../../c-api/typeobj.rst:1556 ../../c-api/typeobj.rst:1617 +#: ../../c-api/typeobj.rst:1653 ../../c-api/typeobj.rst:1678 +#: ../../c-api/typeobj.rst:1701 ../../c-api/typeobj.rst:1714 +#: ../../c-api/typeobj.rst:1729 ../../c-api/typeobj.rst:1743 +#: ../../c-api/typeobj.rst:1773 ../../c-api/typeobj.rst:1805 +#: ../../c-api/typeobj.rst:1831 ../../c-api/typeobj.rst:1849 +#: ../../c-api/typeobj.rst:1878 ../../c-api/typeobj.rst:1922 +#: ../../c-api/typeobj.rst:1939 ../../c-api/typeobj.rst:1980 +#: ../../c-api/typeobj.rst:2002 ../../c-api/typeobj.rst:2034 +#: ../../c-api/typeobj.rst:2062 ../../c-api/typeobj.rst:2075 +#: ../../c-api/typeobj.rst:2085 ../../c-api/typeobj.rst:2102 +#: ../../c-api/typeobj.rst:2119 ../../c-api/typeobj.rst:2133 +#: ../../c-api/typeobj.rst:2166 ../../c-api/typeobj.rst:2189 msgid "**Inheritance:**" msgstr "" -#: ../../c-api/typeobj.rst:505 ../../c-api/typeobj.rst:542 -#: ../../c-api/typeobj.rst:586 +#: ../../c-api/typeobj.rst:506 ../../c-api/typeobj.rst:546 +#: ../../c-api/typeobj.rst:590 msgid "This field is not inherited by subtypes." msgstr "" -#: ../../c-api/typeobj.rst:510 +#: ../../c-api/typeobj.rst:511 msgid "" "This is the type's type, in other words its metatype. It is initialized by " "the argument to the ``PyObject_HEAD_INIT`` macro, and its value should " @@ -1253,7 +1365,11 @@ msgid "" "doing anything else. This is typically done like this::" msgstr "" -#: ../../c-api/typeobj.rst:521 +#: ../../c-api/typeobj.rst:520 +msgid "Foo_Type.ob_type = &PyType_Type;" +msgstr "" + +#: ../../c-api/typeobj.rst:522 msgid "" "This should be done before any instances of the type are created. :c:func:" "`PyType_Ready` checks if :c:member:`~PyObject.ob_type` is ``NULL``, and if " @@ -1261,31 +1377,37 @@ msgid "" "class. :c:func:`PyType_Ready` will not change this field if it is non-zero." msgstr "" -#: ../../c-api/typeobj.rst:528 ../../c-api/typeobj.rst:688 -#: ../../c-api/typeobj.rst:805 ../../c-api/typeobj.rst:901 -#: ../../c-api/typeobj.rst:921 ../../c-api/typeobj.rst:1624 -#: ../../c-api/typeobj.rst:1647 ../../c-api/typeobj.rst:1777 -#: ../../c-api/typeobj.rst:1795 ../../c-api/typeobj.rst:1868 -#: ../../c-api/typeobj.rst:1980 ../../c-api/typeobj.rst:2125 +#: ../../c-api/typeobj.rst:529 ../../c-api/typeobj.rst:744 +#: ../../c-api/typeobj.rst:861 ../../c-api/typeobj.rst:957 +#: ../../c-api/typeobj.rst:977 ../../c-api/typeobj.rst:1680 +#: ../../c-api/typeobj.rst:1703 ../../c-api/typeobj.rst:1833 +#: ../../c-api/typeobj.rst:1851 ../../c-api/typeobj.rst:1924 +#: ../../c-api/typeobj.rst:2036 ../../c-api/typeobj.rst:2168 msgid "This field is inherited by subtypes." msgstr "" -#: ../../c-api/typeobj.rst:532 +#: ../../c-api/typeobj.rst:533 msgid "PyVarObject Slots" msgstr "" -#: ../../c-api/typeobj.rst:536 +#: ../../c-api/typeobj.rst:537 msgid "" "For :ref:`statically allocated type objects `, this should be " "initialized to zero. For :ref:`dynamically allocated type objects `, this field has a special internal meaning." msgstr "" -#: ../../c-api/typeobj.rst:546 +#: ../../c-api/typeobj.rst:541 +msgid "" +"This field should be accessed using the :c:func:`Py_SIZE()` and :c:func:" +"`Py_SET_SIZE()` macros." +msgstr "" + +#: ../../c-api/typeobj.rst:550 msgid "PyTypeObject Slots" msgstr "" -#: ../../c-api/typeobj.rst:548 +#: ../../c-api/typeobj.rst:552 msgid "" "Each slot has a section describing inheritance. If :c:func:`PyType_Ready` " "may set a value when the field is set to ``NULL`` then there will also be a " @@ -1293,7 +1415,7 @@ msgid "" "`PyBaseObject_Type` and :c:data:`PyType_Type` effectively act as defaults.)" msgstr "" -#: ../../c-api/typeobj.rst:555 +#: ../../c-api/typeobj.rst:559 msgid "" "Pointer to a NUL-terminated string containing the name of the type. For " "types that are accessible as module globals, the string should be the full " @@ -1305,105 +1427,161 @@ msgid "" "tp_name` initializer ``\"P.Q.M.T\"``." msgstr "" -#: ../../c-api/typeobj.rst:563 +#: ../../c-api/typeobj.rst:567 msgid "" "For :ref:`dynamically allocated type objects `, this should just " "be the type name, and the module name explicitly stored in the type dict as " "the value for key ``'__module__'``." msgstr "" -#: ../../c-api/typeobj.rst:568 +#: ../../c-api/typeobj.rst:572 msgid "" "For :ref:`statically allocated type objects `, the *tp_name* " "field should contain a dot. Everything before the last dot is made " -"accessible as the :attr:`__module__` attribute, and everything after the " -"last dot is made accessible as the :attr:`~definition.__name__` attribute." +"accessible as the :attr:`~type.__module__` attribute, and everything after " +"the last dot is made accessible as the :attr:`~type.__name__` attribute." msgstr "" -#: ../../c-api/typeobj.rst:574 +#: ../../c-api/typeobj.rst:578 msgid "" "If no dot is present, the entire :c:member:`~PyTypeObject.tp_name` field is " -"made accessible as the :attr:`~definition.__name__` attribute, and the :attr:" -"`__module__` attribute is undefined (unless explicitly set in the " +"made accessible as the :attr:`~type.__name__` attribute, and the :attr:" +"`~type.__module__` attribute is undefined (unless explicitly set in the " "dictionary, as explained above). This means your type will be impossible to " "pickle. Additionally, it will not be listed in module documentations " "created with pydoc." msgstr "" -#: ../../c-api/typeobj.rst:580 +#: ../../c-api/typeobj.rst:584 msgid "" "This field must not be ``NULL``. It is the only required field in :c:func:" "`PyTypeObject` (other than potentially :c:member:`~PyTypeObject." "tp_itemsize`)." msgstr "" -#: ../../c-api/typeobj.rst:592 +#: ../../c-api/typeobj.rst:596 msgid "" "These fields allow calculating the size in bytes of instances of the type." msgstr "" -#: ../../c-api/typeobj.rst:594 +#: ../../c-api/typeobj.rst:598 msgid "" "There are two kinds of types: types with fixed-length instances have a zero :" -"c:member:`~PyTypeObject.tp_itemsize` field, types with variable-length " -"instances have a non-zero :c:member:`~PyTypeObject.tp_itemsize` field. For " -"a type with fixed-length instances, all instances have the same size, given " -"in :c:member:`~PyTypeObject.tp_basicsize`." +"c:member:`!tp_itemsize` field, types with variable-length instances have a " +"non-zero :c:member:`!tp_itemsize` field. For a type with fixed-length " +"instances, all instances have the same size, given in :c:member:`!" +"tp_basicsize`. (Exceptions to this rule can be made using :c:func:" +"`PyUnstable_Object_GC_NewWithExtraData`.)" msgstr "" -#: ../../c-api/typeobj.rst:599 +#: ../../c-api/typeobj.rst:605 msgid "" "For a type with variable-length instances, the instances must have an :c:" -"member:`~PyVarObject.ob_size` field, and the instance size is :c:member:" -"`~PyTypeObject.tp_basicsize` plus N times :c:member:`~PyTypeObject." -"tp_itemsize`, where N is the \"length\" of the object. The value of N is " -"typically stored in the instance's :c:member:`~PyVarObject.ob_size` field. " -"There are exceptions: for example, ints use a negative :c:member:" -"`~PyVarObject.ob_size` to indicate a negative number, and N is " -"``abs(ob_size)`` there. Also, the presence of an :c:member:`~PyVarObject." -"ob_size` field in the instance layout doesn't mean that the instance " -"structure is variable-length (for example, the structure for the list type " -"has fixed-length instances, yet those instances have a meaningful :c:member:" -"`~PyVarObject.ob_size` field)." +"member:`~PyVarObject.ob_size` field, and the instance size is :c:member:`!" +"tp_basicsize` plus N times :c:member:`!tp_itemsize`, where N is the " +"\"length\" of the object." msgstr "" #: ../../c-api/typeobj.rst:610 msgid "" -"The basic size includes the fields in the instance declared by the macro :c:" -"macro:`PyObject_HEAD` or :c:macro:`PyObject_VAR_HEAD` (whichever is used to " -"declare the instance struct) and this in turn includes the :c:member:" -"`~PyObject._ob_prev` and :c:member:`~PyObject._ob_next` fields if they are " -"present. This means that the only correct way to get an initializer for " -"the :c:member:`~PyTypeObject.tp_basicsize` is to use the ``sizeof`` operator " -"on the struct used to declare the instance layout. The basic size does not " -"include the GC header size." +"Functions like :c:func:`PyObject_NewVar` will take the value of N as an " +"argument, and store in the instance's :c:member:`~PyVarObject.ob_size` " +"field. Note that the :c:member:`~PyVarObject.ob_size` field may later be " +"used for other purposes. For example, :py:type:`int` instances use the bits " +"of :c:member:`~PyVarObject.ob_size` in an implementation-defined way; the " +"underlying storage and its size should be accessed using :c:func:" +"`PyLong_Export`." +msgstr "" + +#: ../../c-api/typeobj.rst:620 +msgid "" +"The :c:member:`~PyVarObject.ob_size` field should be accessed using the :c:" +"func:`Py_SIZE()` and :c:func:`Py_SET_SIZE()` macros." +msgstr "" + +#: ../../c-api/typeobj.rst:623 +msgid "" +"Also, the presence of an :c:member:`~PyVarObject.ob_size` field in the " +"instance layout doesn't mean that the instance structure is variable-length. " +"For example, the :py:type:`list` type has fixed-length instances, yet those " +"instances have a :c:member:`~PyVarObject.ob_size` field. (As with :py:type:" +"`int`, avoid reading lists' :c:member:`!ob_size` directly. Call :c:func:" +"`PyList_Size` instead.)" +msgstr "" + +#: ../../c-api/typeobj.rst:630 +msgid "" +"The :c:member:`!tp_basicsize` includes size needed for data of the type's :c:" +"member:`~PyTypeObject.tp_base`, plus any extra data needed by each instance." msgstr "" -#: ../../c-api/typeobj.rst:618 +#: ../../c-api/typeobj.rst:634 msgid "" -"A note about alignment: if the variable items require a particular " -"alignment, this should be taken care of by the value of :c:member:" -"`~PyTypeObject.tp_basicsize`. Example: suppose a type implements an array " -"of ``double``. :c:member:`~PyTypeObject.tp_itemsize` is ``sizeof(double)``. " -"It is the programmer's responsibility that :c:member:`~PyTypeObject." -"tp_basicsize` is a multiple of ``sizeof(double)`` (assuming this is the " -"alignment requirement for ``double``)." +"The correct way to set :c:member:`!tp_basicsize` is to use the ``sizeof`` " +"operator on the struct used to declare the instance layout. This struct must " +"include the struct used to declare the base type. In other words, :c:member:" +"`!tp_basicsize` must be greater than or equal to the base's :c:member:`!" +"tp_basicsize`." msgstr "" -#: ../../c-api/typeobj.rst:625 +#: ../../c-api/typeobj.rst:640 msgid "" -"For any type with variable-length instances, this field must not be ``NULL``." +"Since every type is a subtype of :py:type:`object`, this struct must " +"include :c:type:`PyObject` or :c:type:`PyVarObject` (depending on whether :c:" +"member:`~PyVarObject.ob_size` should be included). These are usually defined " +"by the macro :c:macro:`PyObject_HEAD` or :c:macro:`PyObject_VAR_HEAD`, " +"respectively." msgstr "" -#: ../../c-api/typeobj.rst:629 +#: ../../c-api/typeobj.rst:646 msgid "" -"These fields are inherited separately by subtypes. If the base type has a " -"non-zero :c:member:`~PyTypeObject.tp_itemsize`, it is generally not safe to " -"set :c:member:`~PyTypeObject.tp_itemsize` to a different non-zero value in a " -"subtype (though this depends on the implementation of the base type)." +"The basic size does not include the GC header size, as that header is not " +"part of :c:macro:`PyObject_HEAD`." msgstr "" -#: ../../c-api/typeobj.rst:637 +#: ../../c-api/typeobj.rst:649 +msgid "" +"For cases where struct used to declare the base type is unknown, see :c:" +"member:`PyType_Spec.basicsize` and :c:func:`PyType_FromMetaclass`." +msgstr "" + +#: ../../c-api/typeobj.rst:652 +msgid "Notes about alignment:" +msgstr "" + +#: ../../c-api/typeobj.rst:654 +msgid "" +":c:member:`!tp_basicsize` must be a multiple of ``_Alignof(PyObject)``. When " +"using ``sizeof`` on a ``struct`` that includes :c:macro:`PyObject_HEAD`, as " +"recommended, the compiler ensures this. When not using a C ``struct``, or " +"when using compiler extensions like ``__attribute__((packed))``, it is up to " +"you." +msgstr "" + +#: ../../c-api/typeobj.rst:659 +msgid "" +"If the variable items require a particular alignment, :c:member:`!" +"tp_basicsize` and :c:member:`!tp_itemsize` must each be a multiple of that " +"alignment. For example, if a type's variable part stores a ``double``, it is " +"your responsibility that both fields are a multiple of ``_Alignof(double)``." +msgstr "" + +#: ../../c-api/typeobj.rst:668 +msgid "" +"These fields are inherited separately by subtypes. (That is, if the field is " +"set to zero, :c:func:`PyType_Ready` will copy the value from the base type, " +"indicating that the instances do not need additional storage.)" +msgstr "" + +#: ../../c-api/typeobj.rst:673 +msgid "" +"If the base type has a non-zero :c:member:`~PyTypeObject.tp_itemsize`, it is " +"generally not safe to set :c:member:`~PyTypeObject.tp_itemsize` to a " +"different non-zero value in a subtype (though this depends on the " +"implementation of the base type)." +msgstr "" + +#: ../../c-api/typeobj.rst:680 msgid "" "A pointer to the instance destructor function. This function must be " "defined unless the type guarantees that its instances will never be " @@ -1411,7 +1589,11 @@ msgid "" "The function signature is::" msgstr "" -#: ../../c-api/typeobj.rst:643 +#: ../../c-api/typeobj.rst:684 +msgid "void tp_dealloc(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:686 msgid "" "The destructor function is called by the :c:func:`Py_DECREF` and :c:func:" "`Py_XDECREF` macros when the new reference count is zero. At this point, " @@ -1429,14 +1611,23 @@ msgid "" "allocated using :c:macro:`PyObject_GC_New` or :c:macro:`PyObject_GC_NewVar`." msgstr "" -#: ../../c-api/typeobj.rst:658 +#: ../../c-api/typeobj.rst:701 msgid "" "If the type supports garbage collection (has the :c:macro:" "`Py_TPFLAGS_HAVE_GC` flag bit set), the destructor should call :c:func:" "`PyObject_GC_UnTrack` before clearing any member fields." msgstr "" -#: ../../c-api/typeobj.rst:670 +#: ../../c-api/typeobj.rst:705 +msgid "" +"static void foo_dealloc(foo_object *self) {\n" +" PyObject_GC_UnTrack(self);\n" +" Py_CLEAR(self->ref);\n" +" Py_TYPE(self)->tp_free((PyObject *)self);\n" +"}" +msgstr "" + +#: ../../c-api/typeobj.rst:713 msgid "" "Finally, if the type is heap allocated (:c:macro:`Py_TPFLAGS_HEAPTYPE`), the " "deallocator should release the owned reference to its type object (via :c:" @@ -1444,28 +1635,51 @@ msgid "" "dangling pointers, the recommended way to achieve this is:" msgstr "" -#: ../../c-api/typeobj.rst:693 +#: ../../c-api/typeobj.rst:719 +msgid "" +"static void foo_dealloc(foo_object *self) {\n" +" PyTypeObject *tp = Py_TYPE(self);\n" +" // free references and buffers here\n" +" tp->tp_free(self);\n" +" Py_DECREF(tp);\n" +"}" +msgstr "" + +#: ../../c-api/typeobj.rst:730 +msgid "" +"In a garbage collected Python, :c:member:`!tp_dealloc` may be called from " +"any Python thread, not just the thread which created the object (if the " +"object becomes part of a refcount cycle, that cycle might be collected by a " +"garbage collection on any thread). This is not a problem for Python API " +"calls, since the thread on which :c:member:`!tp_dealloc` is called will own " +"the Global Interpreter Lock (GIL). However, if the object being destroyed " +"in turn destroys objects from some other C or C++ library, care should be " +"taken to ensure that destroying those objects on the thread which called :c:" +"member:`!tp_dealloc` will not violate any assumptions of the library." +msgstr "" + +#: ../../c-api/typeobj.rst:749 msgid "" "An optional offset to a per-instance function that implements calling the " "object using the :ref:`vectorcall protocol `, a more efficient " "alternative of the simpler :c:member:`~PyTypeObject.tp_call`." msgstr "" -#: ../../c-api/typeobj.rst:698 +#: ../../c-api/typeobj.rst:754 msgid "" "This field is only used if the flag :c:macro:`Py_TPFLAGS_HAVE_VECTORCALL` is " "set. If so, this must be a positive integer containing the offset in the " "instance of a :c:type:`vectorcallfunc` pointer." msgstr "" -#: ../../c-api/typeobj.rst:702 +#: ../../c-api/typeobj.rst:758 msgid "" "The *vectorcallfunc* pointer may be ``NULL``, in which case the instance " "behaves as if :c:macro:`Py_TPFLAGS_HAVE_VECTORCALL` was not set: calling the " "instance falls back to :c:member:`~PyTypeObject.tp_call`." msgstr "" -#: ../../c-api/typeobj.rst:706 +#: ../../c-api/typeobj.rst:762 msgid "" "Any class that sets ``Py_TPFLAGS_HAVE_VECTORCALL`` must also set :c:member:" "`~PyTypeObject.tp_call` and make sure its behaviour is consistent with the " @@ -1473,13 +1687,13 @@ msgid "" "`PyVectorcall_Call`." msgstr "" -#: ../../c-api/typeobj.rst:713 +#: ../../c-api/typeobj.rst:769 msgid "" "Before version 3.8, this slot was named ``tp_print``. In Python 2.x, it was " "used for printing to a file. In Python 3.0 to 3.7, it was unused." msgstr "" -#: ../../c-api/typeobj.rst:719 +#: ../../c-api/typeobj.rst:775 msgid "" "Before version 3.12, it was not recommended for :ref:`mutable heap types " "` to implement the vectorcall protocol. When a user sets :attr:" @@ -1489,7 +1703,7 @@ msgid "" "`Py_TPFLAGS_HAVE_VECTORCALL` flag." msgstr "" -#: ../../c-api/typeobj.rst:729 +#: ../../c-api/typeobj.rst:785 msgid "" "This field is always inherited. However, the :c:macro:" "`Py_TPFLAGS_HAVE_VECTORCALL` flag is not always inherited. If it's not set, " @@ -1497,11 +1711,11 @@ msgid "" "func:`PyVectorcall_Call` is explicitly called." msgstr "" -#: ../../c-api/typeobj.rst:738 +#: ../../c-api/typeobj.rst:794 msgid "An optional pointer to the get-attribute-string function." msgstr "" -#: ../../c-api/typeobj.rst:740 +#: ../../c-api/typeobj.rst:796 msgid "" "This field is deprecated. When it is defined, it should point to a function " "that acts the same as the :c:member:`~PyTypeObject.tp_getattro` function, " @@ -1509,13 +1723,13 @@ msgid "" "attribute name." msgstr "" -#: ../../c-api/typeobj.rst:746 ../../c-api/typeobj.rst:942 +#: ../../c-api/typeobj.rst:802 ../../c-api/typeobj.rst:998 msgid "" "Group: :c:member:`~PyTypeObject.tp_getattr`, :c:member:`~PyTypeObject." "tp_getattro`" msgstr "" -#: ../../c-api/typeobj.rst:748 +#: ../../c-api/typeobj.rst:804 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_getattro`: a subtype inherits both :c:member:`~PyTypeObject.tp_getattr` " @@ -1524,12 +1738,12 @@ msgid "" "tp_getattro` are both ``NULL``." msgstr "" -#: ../../c-api/typeobj.rst:755 ../../c-api/typeobj.rst:955 +#: ../../c-api/typeobj.rst:811 ../../c-api/typeobj.rst:1011 msgid "" "An optional pointer to the function for setting and deleting attributes." msgstr "" -#: ../../c-api/typeobj.rst:757 +#: ../../c-api/typeobj.rst:813 msgid "" "This field is deprecated. When it is defined, it should point to a function " "that acts the same as the :c:member:`~PyTypeObject.tp_setattro` function, " @@ -1537,13 +1751,13 @@ msgid "" "attribute name." msgstr "" -#: ../../c-api/typeobj.rst:763 ../../c-api/typeobj.rst:968 +#: ../../c-api/typeobj.rst:819 ../../c-api/typeobj.rst:1024 msgid "" "Group: :c:member:`~PyTypeObject.tp_setattr`, :c:member:`~PyTypeObject." "tp_setattro`" msgstr "" -#: ../../c-api/typeobj.rst:765 +#: ../../c-api/typeobj.rst:821 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_setattro`: a subtype inherits both :c:member:`~PyTypeObject.tp_setattr` " @@ -1552,34 +1766,38 @@ msgid "" "tp_setattro` are both ``NULL``." msgstr "" -#: ../../c-api/typeobj.rst:772 +#: ../../c-api/typeobj.rst:828 msgid "" "Pointer to an additional structure that contains fields relevant only to " "objects which implement :term:`awaitable` and :term:`asynchronous iterator` " "protocols at the C-level. See :ref:`async-structs` for details." msgstr "" -#: ../../c-api/typeobj.rst:776 +#: ../../c-api/typeobj.rst:832 msgid "Formerly known as ``tp_compare`` and ``tp_reserved``." msgstr "" -#: ../../c-api/typeobj.rst:781 +#: ../../c-api/typeobj.rst:837 msgid "" "The :c:member:`~PyTypeObject.tp_as_async` field is not inherited, but the " "contained fields are inherited individually." msgstr "" -#: ../../c-api/typeobj.rst:789 +#: ../../c-api/typeobj.rst:845 msgid "" "An optional pointer to a function that implements the built-in function :" "func:`repr`." msgstr "" -#: ../../c-api/typeobj.rst:792 +#: ../../c-api/typeobj.rst:848 msgid "The signature is the same as for :c:func:`PyObject_Repr`::" msgstr "" -#: ../../c-api/typeobj.rst:796 +#: ../../c-api/typeobj.rst:850 +msgid "PyObject *tp_repr(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:852 msgid "" "The function must return a string or a Unicode object. Ideally, this " "function should return a string that, when passed to :func:`eval`, given a " @@ -1588,81 +1806,85 @@ msgid "" "``'>'`` from which both the type and the value of the object can be deduced." msgstr "" -#: ../../c-api/typeobj.rst:807 ../../c-api/typeobj.rst:886 -#: ../../c-api/typeobj.rst:923 ../../c-api/typeobj.rst:948 -#: ../../c-api/typeobj.rst:974 ../../c-api/typeobj.rst:1015 -#: ../../c-api/typeobj.rst:1570 ../../c-api/typeobj.rst:1604 -#: ../../c-api/typeobj.rst:1721 ../../c-api/typeobj.rst:1754 -#: ../../c-api/typeobj.rst:1829 ../../c-api/typeobj.rst:1870 -#: ../../c-api/typeobj.rst:1888 ../../c-api/typeobj.rst:1930 -#: ../../c-api/typeobj.rst:1951 ../../c-api/typeobj.rst:1982 +#: ../../c-api/typeobj.rst:863 ../../c-api/typeobj.rst:942 +#: ../../c-api/typeobj.rst:979 ../../c-api/typeobj.rst:1004 +#: ../../c-api/typeobj.rst:1030 ../../c-api/typeobj.rst:1071 +#: ../../c-api/typeobj.rst:1626 ../../c-api/typeobj.rst:1660 +#: ../../c-api/typeobj.rst:1777 ../../c-api/typeobj.rst:1810 +#: ../../c-api/typeobj.rst:1885 ../../c-api/typeobj.rst:1926 +#: ../../c-api/typeobj.rst:1944 ../../c-api/typeobj.rst:1986 +#: ../../c-api/typeobj.rst:2007 ../../c-api/typeobj.rst:2038 msgid "**Default:**" msgstr "**Padrão:**" -#: ../../c-api/typeobj.rst:809 +#: ../../c-api/typeobj.rst:865 msgid "" "When this field is not set, a string of the form ``<%s object at %p>`` is " "returned, where ``%s`` is replaced by the type name, and ``%p`` by the " "object's memory address." msgstr "" -#: ../../c-api/typeobj.rst:816 +#: ../../c-api/typeobj.rst:872 msgid "" "Pointer to an additional structure that contains fields relevant only to " "objects which implement the number protocol. These fields are documented " "in :ref:`number-structs`." msgstr "" -#: ../../c-api/typeobj.rst:822 +#: ../../c-api/typeobj.rst:878 msgid "" "The :c:member:`~PyTypeObject.tp_as_number` field is not inherited, but the " "contained fields are inherited individually." msgstr "" -#: ../../c-api/typeobj.rst:828 +#: ../../c-api/typeobj.rst:884 msgid "" "Pointer to an additional structure that contains fields relevant only to " "objects which implement the sequence protocol. These fields are documented " "in :ref:`sequence-structs`." msgstr "" -#: ../../c-api/typeobj.rst:834 +#: ../../c-api/typeobj.rst:890 msgid "" "The :c:member:`~PyTypeObject.tp_as_sequence` field is not inherited, but the " "contained fields are inherited individually." msgstr "" -#: ../../c-api/typeobj.rst:840 +#: ../../c-api/typeobj.rst:896 msgid "" "Pointer to an additional structure that contains fields relevant only to " "objects which implement the mapping protocol. These fields are documented " "in :ref:`mapping-structs`." msgstr "" -#: ../../c-api/typeobj.rst:846 +#: ../../c-api/typeobj.rst:902 msgid "" "The :c:member:`~PyTypeObject.tp_as_mapping` field is not inherited, but the " "contained fields are inherited individually." msgstr "" -#: ../../c-api/typeobj.rst:854 +#: ../../c-api/typeobj.rst:910 msgid "" "An optional pointer to a function that implements the built-in function :" "func:`hash`." msgstr "" -#: ../../c-api/typeobj.rst:857 +#: ../../c-api/typeobj.rst:913 msgid "The signature is the same as for :c:func:`PyObject_Hash`::" msgstr "" -#: ../../c-api/typeobj.rst:861 +#: ../../c-api/typeobj.rst:915 +msgid "Py_hash_t tp_hash(PyObject *);" +msgstr "" + +#: ../../c-api/typeobj.rst:917 msgid "" "The value ``-1`` should not be returned as a normal return value; when an " "error occurs during the computation of the hash value, the function should " "set an exception and return ``-1``." msgstr "" -#: ../../c-api/typeobj.rst:865 +#: ../../c-api/typeobj.rst:921 msgid "" "When this field is not set (*and* :c:member:`~PyTypeObject.tp_richcompare` " "is not set), an attempt to take the hash of the object raises :exc:" @@ -1670,7 +1892,7 @@ msgid "" "`PyObject_HashNotImplemented`." msgstr "" -#: ../../c-api/typeobj.rst:869 +#: ../../c-api/typeobj.rst:925 msgid "" "This field can be set explicitly to :c:func:`PyObject_HashNotImplemented` to " "block inheritance of the hash method from a parent type. This is interpreted " @@ -1681,13 +1903,13 @@ msgid "" "`PyObject_HashNotImplemented`." msgstr "" -#: ../../c-api/typeobj.rst:879 ../../c-api/typeobj.rst:1563 +#: ../../c-api/typeobj.rst:935 ../../c-api/typeobj.rst:1619 msgid "" "Group: :c:member:`~PyTypeObject.tp_hash`, :c:member:`~PyTypeObject." "tp_richcompare`" msgstr "" -#: ../../c-api/typeobj.rst:881 +#: ../../c-api/typeobj.rst:937 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_richcompare`: a subtype inherits both of :c:member:`~PyTypeObject." @@ -1696,18 +1918,22 @@ msgid "" "are both ``NULL``." msgstr "" -#: ../../c-api/typeobj.rst:888 +#: ../../c-api/typeobj.rst:944 msgid ":c:data:`PyBaseObject_Type` uses :c:func:`PyObject_GenericHash`." msgstr "" -#: ../../c-api/typeobj.rst:893 +#: ../../c-api/typeobj.rst:949 msgid "" "An optional pointer to a function that implements calling the object. This " "should be ``NULL`` if the object is not callable. The signature is the same " "as for :c:func:`PyObject_Call`::" msgstr "" -#: ../../c-api/typeobj.rst:906 +#: ../../c-api/typeobj.rst:953 +msgid "PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs);" +msgstr "" + +#: ../../c-api/typeobj.rst:962 msgid "" "An optional pointer to a function that implements the built-in operation :" "func:`str`. (Note that :class:`str` is a type now, and :func:`str` calls " @@ -1716,11 +1942,15 @@ msgid "" "this handler.)" msgstr "" -#: ../../c-api/typeobj.rst:911 +#: ../../c-api/typeobj.rst:967 msgid "The signature is the same as for :c:func:`PyObject_Str`::" msgstr "" -#: ../../c-api/typeobj.rst:915 +#: ../../c-api/typeobj.rst:969 +msgid "PyObject *tp_str(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:971 msgid "" "The function must return a string or a Unicode object. It should be a " "\"friendly\" string representation of the object, as this is the " @@ -1728,28 +1958,32 @@ msgid "" "function." msgstr "" -#: ../../c-api/typeobj.rst:925 +#: ../../c-api/typeobj.rst:981 msgid "" "When this field is not set, :c:func:`PyObject_Repr` is called to return a " "string representation." msgstr "" -#: ../../c-api/typeobj.rst:931 +#: ../../c-api/typeobj.rst:987 msgid "An optional pointer to the get-attribute function." msgstr "" -#: ../../c-api/typeobj.rst:933 +#: ../../c-api/typeobj.rst:989 msgid "The signature is the same as for :c:func:`PyObject_GetAttr`::" msgstr "" -#: ../../c-api/typeobj.rst:937 +#: ../../c-api/typeobj.rst:991 +msgid "PyObject *tp_getattro(PyObject *self, PyObject *attr);" +msgstr "" + +#: ../../c-api/typeobj.rst:993 msgid "" "It is usually convenient to set this field to :c:func:" "`PyObject_GenericGetAttr`, which implements the normal way of looking for " "object attributes." msgstr "" -#: ../../c-api/typeobj.rst:944 +#: ../../c-api/typeobj.rst:1000 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_getattr`: a subtype inherits both :c:member:`~PyTypeObject.tp_getattr` " @@ -1758,15 +1992,19 @@ msgid "" "tp_getattro` are both ``NULL``." msgstr "" -#: ../../c-api/typeobj.rst:950 +#: ../../c-api/typeobj.rst:1006 msgid ":c:data:`PyBaseObject_Type` uses :c:func:`PyObject_GenericGetAttr`." msgstr "" -#: ../../c-api/typeobj.rst:957 +#: ../../c-api/typeobj.rst:1013 msgid "The signature is the same as for :c:func:`PyObject_SetAttr`::" msgstr "" -#: ../../c-api/typeobj.rst:961 +#: ../../c-api/typeobj.rst:1015 +msgid "int tp_setattro(PyObject *self, PyObject *attr, PyObject *value);" +msgstr "" + +#: ../../c-api/typeobj.rst:1017 msgid "" "In addition, setting *value* to ``NULL`` to delete an attribute must be " "supported. It is usually convenient to set this field to :c:func:" @@ -1774,7 +2012,7 @@ msgid "" "attributes." msgstr "" -#: ../../c-api/typeobj.rst:970 +#: ../../c-api/typeobj.rst:1026 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_setattr`: a subtype inherits both :c:member:`~PyTypeObject.tp_setattr` " @@ -1783,24 +2021,24 @@ msgid "" "tp_setattro` are both ``NULL``." msgstr "" -#: ../../c-api/typeobj.rst:976 +#: ../../c-api/typeobj.rst:1032 msgid ":c:data:`PyBaseObject_Type` uses :c:func:`PyObject_GenericSetAttr`." msgstr "" -#: ../../c-api/typeobj.rst:981 +#: ../../c-api/typeobj.rst:1037 msgid "" "Pointer to an additional structure that contains fields relevant only to " "objects which implement the buffer interface. These fields are documented " "in :ref:`buffer-structs`." msgstr "" -#: ../../c-api/typeobj.rst:987 +#: ../../c-api/typeobj.rst:1043 msgid "" "The :c:member:`~PyTypeObject.tp_as_buffer` field is not inherited, but the " "contained fields are inherited individually." msgstr "" -#: ../../c-api/typeobj.rst:993 +#: ../../c-api/typeobj.rst:1049 msgid "" "This field is a bit mask of various flags. Some flags indicate variant " "semantics for certain situations; others are used to indicate that certain " @@ -1812,7 +2050,7 @@ msgid "" "accessed and must be considered to have a zero or ``NULL`` value instead." msgstr "" -#: ../../c-api/typeobj.rst:1003 +#: ../../c-api/typeobj.rst:1059 msgid "" "Inheritance of this field is complicated. Most flag bits are inherited " "individually, i.e. if the base type has a flag bit set, the subtype inherits " @@ -1828,17 +2066,17 @@ msgid "" "*really* inherited individually?" msgstr "" -#: ../../c-api/typeobj.rst:1017 +#: ../../c-api/typeobj.rst:1073 msgid "" ":c:data:`PyBaseObject_Type` uses ``Py_TPFLAGS_DEFAULT | " "Py_TPFLAGS_BASETYPE``." msgstr "" -#: ../../c-api/typeobj.rst:1020 +#: ../../c-api/typeobj.rst:1076 msgid "**Bit Masks:**" msgstr "" -#: ../../c-api/typeobj.rst:1024 +#: ../../c-api/typeobj.rst:1080 msgid "" "The following bit masks are currently defined; these can be ORed together " "using the ``|`` operator to form the value of the :c:member:`~PyTypeObject." @@ -1847,7 +2085,7 @@ msgid "" "zero." msgstr "" -#: ../../c-api/typeobj.rst:1031 +#: ../../c-api/typeobj.rst:1087 msgid "" "This bit is set when the type object itself is allocated on the heap, for " "example, types created dynamically using :c:func:`PyType_FromSpec`. In this " @@ -1860,32 +2098,32 @@ msgid "" "reference cycle with their own module object." msgstr "" -#: ../../c-api/typeobj.rst:1042 ../../c-api/typeobj.rst:1053 -#: ../../c-api/typeobj.rst:1063 ../../c-api/typeobj.rst:1073 -#: ../../c-api/typeobj.rst:1105 +#: ../../c-api/typeobj.rst:1098 ../../c-api/typeobj.rst:1109 +#: ../../c-api/typeobj.rst:1119 ../../c-api/typeobj.rst:1129 +#: ../../c-api/typeobj.rst:1161 msgid "???" msgstr "???" -#: ../../c-api/typeobj.rst:1047 +#: ../../c-api/typeobj.rst:1103 msgid "" "This bit is set when the type can be used as the base type of another type. " "If this bit is clear, the type cannot be subtyped (similar to a \"final\" " "class in Java)." msgstr "" -#: ../../c-api/typeobj.rst:1058 +#: ../../c-api/typeobj.rst:1114 msgid "" "This bit is set when the type object has been fully initialized by :c:func:" "`PyType_Ready`." msgstr "" -#: ../../c-api/typeobj.rst:1068 +#: ../../c-api/typeobj.rst:1124 msgid "" "This bit is set while :c:func:`PyType_Ready` is in the process of " "initializing the type object." msgstr "" -#: ../../c-api/typeobj.rst:1078 +#: ../../c-api/typeobj.rst:1134 msgid "" "This bit is set when the object supports garbage collection. If this bit is " "set, instances must be created using :c:macro:`PyObject_GC_New` and " @@ -1895,14 +2133,14 @@ msgid "" "tp_clear` are present in the type object." msgstr "" -#: ../../c-api/typeobj.rst:1087 ../../c-api/typeobj.rst:1428 -#: ../../c-api/typeobj.rst:1502 +#: ../../c-api/typeobj.rst:1143 ../../c-api/typeobj.rst:1484 +#: ../../c-api/typeobj.rst:1558 msgid "" "Group: :c:macro:`Py_TPFLAGS_HAVE_GC`, :c:member:`~PyTypeObject." "tp_traverse`, :c:member:`~PyTypeObject.tp_clear`" msgstr "" -#: ../../c-api/typeobj.rst:1089 +#: ../../c-api/typeobj.rst:1145 msgid "" "The :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is inherited together with the :c:" "member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` " @@ -1912,105 +2150,105 @@ msgid "" "values." msgstr "" -#: ../../c-api/typeobj.rst:1099 +#: ../../c-api/typeobj.rst:1155 msgid "" "This is a bitmask of all the bits that pertain to the existence of certain " "fields in the type object and its extension structures. Currently, it " "includes the following bits: :c:macro:`Py_TPFLAGS_HAVE_STACKLESS_EXTENSION`." msgstr "" -#: ../../c-api/typeobj.rst:1110 +#: ../../c-api/typeobj.rst:1166 msgid "This bit indicates that objects behave like unbound methods." msgstr "" -#: ../../c-api/typeobj.rst:1112 +#: ../../c-api/typeobj.rst:1168 msgid "If this flag is set for ``type(meth)``, then:" msgstr "" -#: ../../c-api/typeobj.rst:1114 +#: ../../c-api/typeobj.rst:1170 msgid "" "``meth.__get__(obj, cls)(*args, **kwds)`` (with ``obj`` not None) must be " "equivalent to ``meth(obj, *args, **kwds)``." msgstr "" -#: ../../c-api/typeobj.rst:1117 +#: ../../c-api/typeobj.rst:1173 msgid "" "``meth.__get__(None, cls)(*args, **kwds)`` must be equivalent to " "``meth(*args, **kwds)``." msgstr "" -#: ../../c-api/typeobj.rst:1120 +#: ../../c-api/typeobj.rst:1176 msgid "" "This flag enables an optimization for typical method calls like ``obj." "meth()``: it avoids creating a temporary \"bound method\" object for ``obj." "meth``." msgstr "" -#: ../../c-api/typeobj.rst:1128 +#: ../../c-api/typeobj.rst:1184 msgid "" "This flag is never inherited by types without the :c:macro:" "`Py_TPFLAGS_IMMUTABLETYPE` flag set. For extension types, it is inherited " "whenever :c:member:`~PyTypeObject.tp_descr_get` is inherited." msgstr "" -#: ../../c-api/typeobj.rst:1134 +#: ../../c-api/typeobj.rst:1190 msgid "" -"This bit indicates that instances of the class have a ``__dict__`` " +"This bit indicates that instances of the class have a `~object.__dict__` " "attribute, and that the space for the dictionary is managed by the VM." msgstr "" -#: ../../c-api/typeobj.rst:1137 +#: ../../c-api/typeobj.rst:1193 msgid "If this flag is set, :c:macro:`Py_TPFLAGS_HAVE_GC` should also be set." msgstr "" -#: ../../c-api/typeobj.rst:1139 +#: ../../c-api/typeobj.rst:1195 msgid "" "The type traverse function must call :c:func:`PyObject_VisitManagedDict` and " "its clear function must call :c:func:`PyObject_ClearManagedDict`." msgstr "" -#: ../../c-api/typeobj.rst:1146 +#: ../../c-api/typeobj.rst:1202 msgid "" "This flag is inherited unless the :c:member:`~PyTypeObject.tp_dictoffset` " "field is set in a superclass." msgstr "" -#: ../../c-api/typeobj.rst:1152 +#: ../../c-api/typeobj.rst:1208 msgid "" "This bit indicates that instances of the class should be weakly " "referenceable." msgstr "" -#: ../../c-api/typeobj.rst:1159 +#: ../../c-api/typeobj.rst:1215 msgid "" "This flag is inherited unless the :c:member:`~PyTypeObject." "tp_weaklistoffset` field is set in a superclass." msgstr "" -#: ../../c-api/typeobj.rst:1165 +#: ../../c-api/typeobj.rst:1221 msgid "" "Only usable with variable-size types, i.e. ones with non-zero :c:member:" "`~PyTypeObject.tp_itemsize`." msgstr "" -#: ../../c-api/typeobj.rst:1168 +#: ../../c-api/typeobj.rst:1224 msgid "" "Indicates that the variable-sized portion of an instance of this type is at " "the end of the instance's memory area, at an offset of ``Py_TYPE(obj)-" ">tp_basicsize`` (which may be different in each subclass)." msgstr "" -#: ../../c-api/typeobj.rst:1173 +#: ../../c-api/typeobj.rst:1229 msgid "" "When setting this flag, be sure that all superclasses either use this memory " "layout, or are not variable-sized. Python does not check this." msgstr "" -#: ../../c-api/typeobj.rst:1181 +#: ../../c-api/typeobj.rst:1237 msgid "This flag is inherited." msgstr "" -#: ../../c-api/typeobj.rst:1195 +#: ../../c-api/typeobj.rst:1251 msgid "" "These flags are used by functions such as :c:func:`PyLong_Check` to quickly " "determine if a type is a subclass of a built-in type; such specific checks " @@ -2020,90 +2258,90 @@ msgid "" "behave differently depending on what kind of check is used." msgstr "" -#: ../../c-api/typeobj.rst:1206 +#: ../../c-api/typeobj.rst:1262 msgid "" "This bit is set when the :c:member:`~PyTypeObject.tp_finalize` slot is " "present in the type structure." msgstr "" -#: ../../c-api/typeobj.rst:1211 +#: ../../c-api/typeobj.rst:1267 msgid "" "This flag isn't necessary anymore, as the interpreter assumes the :c:member:" "`~PyTypeObject.tp_finalize` slot is always present in the type structure." msgstr "" -#: ../../c-api/typeobj.rst:1219 +#: ../../c-api/typeobj.rst:1275 msgid "" "This bit is set when the class implements the :ref:`vectorcall protocol " "`. See :c:member:`~PyTypeObject.tp_vectorcall_offset` for " "details." msgstr "" -#: ../../c-api/typeobj.rst:1225 +#: ../../c-api/typeobj.rst:1281 msgid "" "This bit is inherited if :c:member:`~PyTypeObject.tp_call` is also inherited." msgstr "" -#: ../../c-api/typeobj.rst:1232 +#: ../../c-api/typeobj.rst:1288 msgid "" "This flag is now removed from a class when the class's :py:meth:`~object." "__call__` method is reassigned." msgstr "" -#: ../../c-api/typeobj.rst:1235 +#: ../../c-api/typeobj.rst:1291 msgid "This flag can now be inherited by mutable classes." msgstr "" -#: ../../c-api/typeobj.rst:1239 +#: ../../c-api/typeobj.rst:1295 msgid "" "This bit is set for type objects that are immutable: type attributes cannot " "be set nor deleted." msgstr "" -#: ../../c-api/typeobj.rst:1241 +#: ../../c-api/typeobj.rst:1297 msgid "" ":c:func:`PyType_Ready` automatically applies this flag to :ref:`static types " "`." msgstr "" -#: ../../c-api/typeobj.rst:1246 +#: ../../c-api/typeobj.rst:1302 msgid "This flag is not inherited." msgstr "" -#: ../../c-api/typeobj.rst:1252 +#: ../../c-api/typeobj.rst:1308 msgid "" "Disallow creating instances of the type: set :c:member:`~PyTypeObject." "tp_new` to NULL and don't create the ``__new__`` key in the type dictionary." msgstr "" -#: ../../c-api/typeobj.rst:1256 +#: ../../c-api/typeobj.rst:1312 msgid "" "The flag must be set before creating the type, not after. For example, it " "must be set before :c:func:`PyType_Ready` is called on the type." msgstr "" -#: ../../c-api/typeobj.rst:1259 +#: ../../c-api/typeobj.rst:1315 msgid "" "The flag is set automatically on :ref:`static types ` if :c:" "member:`~PyTypeObject.tp_base` is NULL or ``&PyBaseObject_Type`` and :c:" "member:`~PyTypeObject.tp_new` is NULL." msgstr "" -#: ../../c-api/typeobj.rst:1265 +#: ../../c-api/typeobj.rst:1321 msgid "" "This flag is not inherited. However, subclasses will not be instantiable " "unless they provide a non-NULL :c:member:`~PyTypeObject.tp_new` (which is " "only possible via the C API)." msgstr "" -#: ../../c-api/typeobj.rst:1272 +#: ../../c-api/typeobj.rst:1328 msgid "" "To disallow instantiating a class directly but allow instantiating its " "subclasses (e.g. for an :term:`abstract base class`), do not use this flag. " "Instead, make :c:member:`~PyTypeObject.tp_new` only succeed for subclasses." msgstr "" -#: ../../c-api/typeobj.rst:1283 +#: ../../c-api/typeobj.rst:1339 msgid "" "This bit indicates that instances of the class may match mapping patterns " "when used as the subject of a :keyword:`match` block. It is automatically " @@ -2111,23 +2349,23 @@ msgid "" "unset when registering :class:`collections.abc.Sequence`." msgstr "" -#: ../../c-api/typeobj.rst:1290 ../../c-api/typeobj.rst:1312 +#: ../../c-api/typeobj.rst:1346 ../../c-api/typeobj.rst:1368 msgid "" ":c:macro:`Py_TPFLAGS_MAPPING` and :c:macro:`Py_TPFLAGS_SEQUENCE` are " "mutually exclusive; it is an error to enable both flags simultaneously." msgstr "" -#: ../../c-api/typeobj.rst:1295 +#: ../../c-api/typeobj.rst:1351 msgid "" "This flag is inherited by types that do not already set :c:macro:" "`Py_TPFLAGS_SEQUENCE`." msgstr "" -#: ../../c-api/typeobj.rst:1298 ../../c-api/typeobj.rst:1320 +#: ../../c-api/typeobj.rst:1354 ../../c-api/typeobj.rst:1376 msgid ":pep:`634` -- Structural Pattern Matching: Specification" -msgstr "" +msgstr ":pep:`634` -- Structural Pattern Matching: Specification" -#: ../../c-api/typeobj.rst:1305 +#: ../../c-api/typeobj.rst:1361 msgid "" "This bit indicates that instances of the class may match sequence patterns " "when used as the subject of a :keyword:`match` block. It is automatically " @@ -2135,49 +2373,53 @@ msgid "" "unset when registering :class:`collections.abc.Mapping`." msgstr "" -#: ../../c-api/typeobj.rst:1317 +#: ../../c-api/typeobj.rst:1373 msgid "" "This flag is inherited by types that do not already set :c:macro:" "`Py_TPFLAGS_MAPPING`." msgstr "" -#: ../../c-api/typeobj.rst:1327 +#: ../../c-api/typeobj.rst:1383 msgid "" "Internal. Do not set or unset this flag. To indicate that a class has " "changed call :c:func:`PyType_Modified`" msgstr "" -#: ../../c-api/typeobj.rst:1331 +#: ../../c-api/typeobj.rst:1387 msgid "" "This flag is present in header files, but is not be used. It will be removed " "in a future version of CPython" msgstr "" -#: ../../c-api/typeobj.rst:1337 +#: ../../c-api/typeobj.rst:1393 msgid "" "An optional pointer to a NUL-terminated C string giving the docstring for " -"this type object. This is exposed as the :attr:`__doc__` attribute on the " -"type and instances of the type." +"this type object. This is exposed as the :attr:`~type.__doc__` attribute on " +"the type and instances of the type." msgstr "" -#: ../../c-api/typeobj.rst:1343 +#: ../../c-api/typeobj.rst:1399 msgid "This field is *not* inherited by subtypes." msgstr "" -#: ../../c-api/typeobj.rst:1348 +#: ../../c-api/typeobj.rst:1404 msgid "" "An optional pointer to a traversal function for the garbage collector. This " "is only used if the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is set. The " "signature is::" msgstr "" -#: ../../c-api/typeobj.rst:1353 ../../c-api/typeobj.rst:1497 +#: ../../c-api/typeobj.rst:1407 +msgid "int tp_traverse(PyObject *self, visitproc visit, void *arg);" +msgstr "" + +#: ../../c-api/typeobj.rst:1409 ../../c-api/typeobj.rst:1553 msgid "" "More information about Python's garbage collection scheme can be found in " "section :ref:`supporting-cycle-detection`." msgstr "" -#: ../../c-api/typeobj.rst:1356 +#: ../../c-api/typeobj.rst:1412 msgid "" "The :c:member:`~PyTypeObject.tp_traverse` pointer is used by the garbage " "collector to detect reference cycles. A typical implementation of a :c:" @@ -2187,7 +2429,19 @@ msgid "" "`!_thread` extension module::" msgstr "" -#: ../../c-api/typeobj.rst:1371 +#: ../../c-api/typeobj.rst:1418 +msgid "" +"static int\n" +"local_traverse(localobject *self, visitproc visit, void *arg)\n" +"{\n" +" Py_VISIT(self->args);\n" +" Py_VISIT(self->kw);\n" +" Py_VISIT(self->dict);\n" +" return 0;\n" +"}" +msgstr "" + +#: ../../c-api/typeobj.rst:1427 msgid "" "Note that :c:func:`Py_VISIT` is called only on those members that can " "participate in reference cycles. Although there is also a ``self->key`` " @@ -2195,32 +2449,47 @@ msgid "" "part of a reference cycle." msgstr "" -#: ../../c-api/typeobj.rst:1375 +#: ../../c-api/typeobj.rst:1431 msgid "" "On the other hand, even if you know a member can never be part of a cycle, " "as a debugging aid you may want to visit it anyway just so the :mod:`gc` " "module's :func:`~gc.get_referents` function will include it." msgstr "" -#: ../../c-api/typeobj.rst:1379 +#: ../../c-api/typeobj.rst:1435 msgid "" "Heap types (:c:macro:`Py_TPFLAGS_HEAPTYPE`) must visit their type with::" msgstr "" -#: ../../c-api/typeobj.rst:1383 +#: ../../c-api/typeobj.rst:1437 +msgid "Py_VISIT(Py_TYPE(self));" +msgstr "" + +#: ../../c-api/typeobj.rst:1439 msgid "" "It is only needed since Python 3.9. To support Python 3.8 and older, this " "line must be conditional::" msgstr "" -#: ../../c-api/typeobj.rst:1390 +#: ../../c-api/typeobj.rst:1442 +msgid "" +"#if PY_VERSION_HEX >= 0x03090000\n" +" Py_VISIT(Py_TYPE(self));\n" +"#endif" +msgstr "" + +#: ../../c-api/typeobj.rst:1446 msgid "" "If the :c:macro:`Py_TPFLAGS_MANAGED_DICT` bit is set in the :c:member:" "`~PyTypeObject.tp_flags` field, the traverse function must call :c:func:" "`PyObject_VisitManagedDict` like this::" msgstr "" -#: ../../c-api/typeobj.rst:1397 +#: ../../c-api/typeobj.rst:1450 +msgid "PyObject_VisitManagedDict((PyObject*)self, visit, arg);" +msgstr "" + +#: ../../c-api/typeobj.rst:1453 msgid "" "When implementing :c:member:`~PyTypeObject.tp_traverse`, only the members " "that the instance *owns* (by having :term:`strong references ` hold a reference to " "their type. Their traversal function must therefore either visit :c:func:" @@ -2249,14 +2518,14 @@ msgid "" "superclass). If they do not, the type object may not be garbage-collected." msgstr "" -#: ../../c-api/typeobj.rst:1421 +#: ../../c-api/typeobj.rst:1477 msgid "" "Heap-allocated types are expected to visit ``Py_TYPE(self)`` in " "``tp_traverse``. In earlier versions of Python, due to `bug 40217 `_, doing this may lead to crashes in subclasses." msgstr "" -#: ../../c-api/typeobj.rst:1430 +#: ../../c-api/typeobj.rst:1486 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_clear` and the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit: the flag bit, :c:" @@ -2264,14 +2533,18 @@ msgid "" "are all inherited from the base type if they are all zero in the subtype." msgstr "" -#: ../../c-api/typeobj.rst:1438 +#: ../../c-api/typeobj.rst:1494 msgid "" "An optional pointer to a clear function for the garbage collector. This is " "only used if the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is set. The " "signature is::" msgstr "" -#: ../../c-api/typeobj.rst:1443 +#: ../../c-api/typeobj.rst:1497 +msgid "int tp_clear(PyObject *);" +msgstr "" + +#: ../../c-api/typeobj.rst:1499 msgid "" "The :c:member:`~PyTypeObject.tp_clear` member function is used to break " "reference cycles in cyclic garbage detected by the garbage collector. Taken " @@ -2286,7 +2559,7 @@ msgid "" "good reason to avoid implementing :c:member:`~PyTypeObject.tp_clear`." msgstr "" -#: ../../c-api/typeobj.rst:1453 +#: ../../c-api/typeobj.rst:1509 msgid "" "Implementations of :c:member:`~PyTypeObject.tp_clear` should drop the " "instance's references to those of its members that may be Python objects, " @@ -2294,7 +2567,20 @@ msgid "" "example::" msgstr "" -#: ../../c-api/typeobj.rst:1467 +#: ../../c-api/typeobj.rst:1513 +msgid "" +"static int\n" +"local_clear(localobject *self)\n" +"{\n" +" Py_CLEAR(self->key);\n" +" Py_CLEAR(self->args);\n" +" Py_CLEAR(self->kw);\n" +" Py_CLEAR(self->dict);\n" +" return 0;\n" +"}" +msgstr "" + +#: ../../c-api/typeobj.rst:1523 msgid "" "The :c:func:`Py_CLEAR` macro should be used, because clearing references is " "delicate: the reference to the contained object must not be released (via :" @@ -2309,14 +2595,18 @@ msgid "" "performs the operations in a safe order." msgstr "" -#: ../../c-api/typeobj.rst:1479 +#: ../../c-api/typeobj.rst:1535 msgid "" "If the :c:macro:`Py_TPFLAGS_MANAGED_DICT` bit is set in the :c:member:" "`~PyTypeObject.tp_flags` field, the traverse function must call :c:func:" "`PyObject_ClearManagedDict` like this::" msgstr "" -#: ../../c-api/typeobj.rst:1485 +#: ../../c-api/typeobj.rst:1539 +msgid "PyObject_ClearManagedDict((PyObject*)self);" +msgstr "" + +#: ../../c-api/typeobj.rst:1541 msgid "" "Note that :c:member:`~PyTypeObject.tp_clear` is not *always* called before " "an instance is deallocated. For example, when reference counting is enough " @@ -2324,7 +2614,7 @@ msgid "" "is not involved and :c:member:`~PyTypeObject.tp_dealloc` is called directly." msgstr "" -#: ../../c-api/typeobj.rst:1491 +#: ../../c-api/typeobj.rst:1547 msgid "" "Because the goal of :c:member:`~PyTypeObject.tp_clear` functions is to break " "reference cycles, it's not necessary to clear contained objects like Python " @@ -2334,7 +2624,7 @@ msgid "" "invoke :c:member:`~PyTypeObject.tp_clear`." msgstr "" -#: ../../c-api/typeobj.rst:1504 +#: ../../c-api/typeobj.rst:1560 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_traverse` and the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit: the flag bit, :" @@ -2342,18 +2632,22 @@ msgid "" "are all inherited from the base type if they are all zero in the subtype." msgstr "" -#: ../../c-api/typeobj.rst:1512 +#: ../../c-api/typeobj.rst:1568 msgid "" "An optional pointer to the rich comparison function, whose signature is::" msgstr "" -#: ../../c-api/typeobj.rst:1516 +#: ../../c-api/typeobj.rst:1570 +msgid "PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);" +msgstr "" + +#: ../../c-api/typeobj.rst:1572 msgid "" "The first parameter is guaranteed to be an instance of the type that is " "defined by :c:type:`PyTypeObject`." msgstr "" -#: ../../c-api/typeobj.rst:1519 +#: ../../c-api/typeobj.rst:1575 msgid "" "The function should return the result of the comparison (usually ``Py_True`` " "or ``Py_False``). If the comparison is undefined, it must return " @@ -2361,50 +2655,50 @@ msgid "" "set an exception condition." msgstr "" -#: ../../c-api/typeobj.rst:1524 +#: ../../c-api/typeobj.rst:1580 msgid "" "The following constants are defined to be used as the third argument for :c:" "member:`~PyTypeObject.tp_richcompare` and for :c:func:`PyObject_RichCompare`:" msgstr "" -#: ../../c-api/typeobj.rst:1530 +#: ../../c-api/typeobj.rst:1586 msgid "Constant" msgstr "Constante" -#: ../../c-api/typeobj.rst:1530 +#: ../../c-api/typeobj.rst:1586 msgid "Comparison" msgstr "Comparação" -#: ../../c-api/typeobj.rst:1532 +#: ../../c-api/typeobj.rst:1588 msgid "``<``" msgstr "``<``" -#: ../../c-api/typeobj.rst:1534 +#: ../../c-api/typeobj.rst:1590 msgid "``<=``" msgstr "``<=``" -#: ../../c-api/typeobj.rst:1536 +#: ../../c-api/typeobj.rst:1592 msgid "``==``" msgstr "``==``" -#: ../../c-api/typeobj.rst:1538 +#: ../../c-api/typeobj.rst:1594 msgid "``!=``" msgstr "``!=``" -#: ../../c-api/typeobj.rst:1540 +#: ../../c-api/typeobj.rst:1596 msgid "``>``" msgstr "``>``" -#: ../../c-api/typeobj.rst:1542 +#: ../../c-api/typeobj.rst:1598 msgid "``>=``" msgstr "``>=``" -#: ../../c-api/typeobj.rst:1545 +#: ../../c-api/typeobj.rst:1601 msgid "" "The following macro is defined to ease writing rich comparison functions:" msgstr "" -#: ../../c-api/typeobj.rst:1549 +#: ../../c-api/typeobj.rst:1605 msgid "" "Return ``Py_True`` or ``Py_False`` from the function, depending on the " "result of a comparison. VAL_A and VAL_B must be orderable by C comparison " @@ -2412,15 +2706,15 @@ msgid "" "specifies the requested operation, as for :c:func:`PyObject_RichCompare`." msgstr "" -#: ../../c-api/typeobj.rst:1555 +#: ../../c-api/typeobj.rst:1611 msgid "The returned value is a new :term:`strong reference`." msgstr "" -#: ../../c-api/typeobj.rst:1557 +#: ../../c-api/typeobj.rst:1613 msgid "On error, sets an exception and returns ``NULL`` from the function." msgstr "" -#: ../../c-api/typeobj.rst:1565 +#: ../../c-api/typeobj.rst:1621 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_hash`: a subtype inherits :c:member:`~PyTypeObject.tp_richcompare` and :c:" @@ -2428,7 +2722,7 @@ msgid "" "tp_richcompare` and :c:member:`~PyTypeObject.tp_hash` are both ``NULL``." msgstr "" -#: ../../c-api/typeobj.rst:1572 +#: ../../c-api/typeobj.rst:1628 msgid "" ":c:data:`PyBaseObject_Type` provides a :c:member:`~PyTypeObject." "tp_richcompare` implementation, which may be inherited. However, if only :c:" @@ -2437,13 +2731,13 @@ msgid "" "comparisons." msgstr "" -#: ../../c-api/typeobj.rst:1581 +#: ../../c-api/typeobj.rst:1637 msgid "" "While this field is still supported, :c:macro:`Py_TPFLAGS_MANAGED_WEAKREF` " "should be used instead, if at all possible." msgstr "" -#: ../../c-api/typeobj.rst:1584 +#: ../../c-api/typeobj.rst:1640 msgid "" "If the instances of this type are weakly referenceable, this field is " "greater than zero and contains the offset in the instance structure of the " @@ -2453,19 +2747,19 @@ msgid "" "`PyObject*` which is initialized to ``NULL``." msgstr "" -#: ../../c-api/typeobj.rst:1591 +#: ../../c-api/typeobj.rst:1647 msgid "" "Do not confuse this field with :c:member:`~PyTypeObject.tp_weaklist`; that " "is the list head for weak references to the type object itself." msgstr "" -#: ../../c-api/typeobj.rst:1594 +#: ../../c-api/typeobj.rst:1650 msgid "" "It is an error to set both the :c:macro:`Py_TPFLAGS_MANAGED_WEAKREF` bit " "and :c:member:`~PyTypeObject.tp_weaklistoffset`." msgstr "" -#: ../../c-api/typeobj.rst:1599 +#: ../../c-api/typeobj.rst:1655 msgid "" "This field is inherited by subtypes, but see the rules listed below. A " "subtype may override this offset; this means that the subtype uses a " @@ -2474,7 +2768,7 @@ msgid "" "not be a problem." msgstr "" -#: ../../c-api/typeobj.rst:1606 +#: ../../c-api/typeobj.rst:1662 msgid "" "If the :c:macro:`Py_TPFLAGS_MANAGED_WEAKREF` bit is set in the :c:member:" "`~PyTypeObject.tp_flags` field, then :c:member:`~PyTypeObject." @@ -2482,24 +2776,32 @@ msgid "" "unsafe to use this field." msgstr "" -#: ../../c-api/typeobj.rst:1614 +#: ../../c-api/typeobj.rst:1670 msgid "" "An optional pointer to a function that returns an :term:`iterator` for the " "object. Its presence normally signals that the instances of this type are :" "term:`iterable` (although sequences may be iterable without this function)." msgstr "" -#: ../../c-api/typeobj.rst:1618 +#: ../../c-api/typeobj.rst:1674 msgid "This function has the same signature as :c:func:`PyObject_GetIter`::" msgstr "" -#: ../../c-api/typeobj.rst:1629 +#: ../../c-api/typeobj.rst:1676 +msgid "PyObject *tp_iter(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:1685 msgid "" "An optional pointer to a function that returns the next item in an :term:" "`iterator`. The signature is::" msgstr "" -#: ../../c-api/typeobj.rst:1634 +#: ../../c-api/typeobj.rst:1688 +msgid "PyObject *tp_iternext(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:1690 msgid "" "When the iterator is exhausted, it must return ``NULL``; a :exc:" "`StopIteration` exception may or may not be set. When another error occurs, " @@ -2507,74 +2809,74 @@ msgid "" "this type are iterators." msgstr "" -#: ../../c-api/typeobj.rst:1639 +#: ../../c-api/typeobj.rst:1695 msgid "" "Iterator types should also define the :c:member:`~PyTypeObject.tp_iter` " "function, and that function should return the iterator instance itself (not " "a new iterator instance)." msgstr "" -#: ../../c-api/typeobj.rst:1643 +#: ../../c-api/typeobj.rst:1699 msgid "This function has the same signature as :c:func:`PyIter_Next`." msgstr "" -#: ../../c-api/typeobj.rst:1652 +#: ../../c-api/typeobj.rst:1708 msgid "" "An optional pointer to a static ``NULL``-terminated array of :c:type:" "`PyMethodDef` structures, declaring regular methods of this type." msgstr "" -#: ../../c-api/typeobj.rst:1655 +#: ../../c-api/typeobj.rst:1711 msgid "" "For each entry in the array, an entry is added to the type's dictionary " "(see :c:member:`~PyTypeObject.tp_dict` below) containing a method descriptor." msgstr "" -#: ../../c-api/typeobj.rst:1660 +#: ../../c-api/typeobj.rst:1716 msgid "" "This field is not inherited by subtypes (methods are inherited through a " "different mechanism)." msgstr "" -#: ../../c-api/typeobj.rst:1666 +#: ../../c-api/typeobj.rst:1722 msgid "" "An optional pointer to a static ``NULL``-terminated array of :c:type:" "`PyMemberDef` structures, declaring regular data members (fields or slots) " "of instances of this type." msgstr "" -#: ../../c-api/typeobj.rst:1670 +#: ../../c-api/typeobj.rst:1726 msgid "" "For each entry in the array, an entry is added to the type's dictionary " "(see :c:member:`~PyTypeObject.tp_dict` below) containing a member descriptor." msgstr "" -#: ../../c-api/typeobj.rst:1675 +#: ../../c-api/typeobj.rst:1731 msgid "" "This field is not inherited by subtypes (members are inherited through a " "different mechanism)." msgstr "" -#: ../../c-api/typeobj.rst:1681 +#: ../../c-api/typeobj.rst:1737 msgid "" "An optional pointer to a static ``NULL``-terminated array of :c:type:" "`PyGetSetDef` structures, declaring computed attributes of instances of this " "type." msgstr "" -#: ../../c-api/typeobj.rst:1684 +#: ../../c-api/typeobj.rst:1740 msgid "" "For each entry in the array, an entry is added to the type's dictionary " "(see :c:member:`~PyTypeObject.tp_dict` below) containing a getset descriptor." msgstr "" -#: ../../c-api/typeobj.rst:1689 +#: ../../c-api/typeobj.rst:1745 msgid "" "This field is not inherited by subtypes (computed attributes are inherited " "through a different mechanism)." msgstr "" -#: ../../c-api/typeobj.rst:1695 +#: ../../c-api/typeobj.rst:1751 msgid "" "An optional pointer to a base type from which type properties are " "inherited. At this level, only single inheritance is supported; multiple " @@ -2582,7 +2884,7 @@ msgid "" "metatype." msgstr "" -#: ../../c-api/typeobj.rst:1703 +#: ../../c-api/typeobj.rst:1759 msgid "" "Slot initialization is subject to the rules of initializing globals. C99 " "requires the initializers to be \"address constants\". Function designators " @@ -2590,7 +2892,7 @@ msgid "" "valid C99 address constants." msgstr "" -#: ../../c-api/typeobj.rst:1708 +#: ../../c-api/typeobj.rst:1764 msgid "" "However, the unary '&' operator applied to a non-static variable like :c:" "data:`PyBaseObject_Type` is not required to produce an address constant. " @@ -2598,27 +2900,27 @@ msgid "" "strictly standard conforming in this particular behavior." msgstr "" -#: ../../c-api/typeobj.rst:1714 +#: ../../c-api/typeobj.rst:1770 msgid "" "Consequently, :c:member:`~PyTypeObject.tp_base` should be set in the " "extension module's init function." msgstr "" -#: ../../c-api/typeobj.rst:1719 +#: ../../c-api/typeobj.rst:1775 msgid "This field is not inherited by subtypes (obviously)." msgstr "" -#: ../../c-api/typeobj.rst:1723 +#: ../../c-api/typeobj.rst:1779 msgid "" "This field defaults to ``&PyBaseObject_Type`` (which to Python programmers " "is known as the type :class:`object`)." msgstr "" -#: ../../c-api/typeobj.rst:1729 +#: ../../c-api/typeobj.rst:1785 msgid "The type's dictionary is stored here by :c:func:`PyType_Ready`." msgstr "" -#: ../../c-api/typeobj.rst:1731 +#: ../../c-api/typeobj.rst:1787 msgid "" "This field should normally be initialized to ``NULL`` before PyType_Ready is " "called; it may also be initialized to a dictionary containing initial " @@ -2629,64 +2931,72 @@ msgid "" "be treated as read-only." msgstr "" -#: ../../c-api/typeobj.rst:1739 +#: ../../c-api/typeobj.rst:1795 msgid "" "Some types may not store their dictionary in this slot. Use :c:func:" "`PyType_GetDict` to retrieve the dictionary for an arbitrary type." msgstr "" -#: ../../c-api/typeobj.rst:1745 +#: ../../c-api/typeobj.rst:1801 msgid "" "Internals detail: For static builtin types, this is always ``NULL``. " "Instead, the dict for such types is stored on ``PyInterpreterState``. Use :c:" "func:`PyType_GetDict` to get the dict for an arbitrary type." msgstr "" -#: ../../c-api/typeobj.rst:1751 +#: ../../c-api/typeobj.rst:1807 msgid "" "This field is not inherited by subtypes (though the attributes defined in " "here are inherited through a different mechanism)." msgstr "" -#: ../../c-api/typeobj.rst:1756 +#: ../../c-api/typeobj.rst:1812 msgid "" "If this field is ``NULL``, :c:func:`PyType_Ready` will assign a new " "dictionary to it." msgstr "" -#: ../../c-api/typeobj.rst:1761 +#: ../../c-api/typeobj.rst:1817 msgid "" "It is not safe to use :c:func:`PyDict_SetItem` on or otherwise modify :c:" "member:`~PyTypeObject.tp_dict` with the dictionary C-API." msgstr "" -#: ../../c-api/typeobj.rst:1767 +#: ../../c-api/typeobj.rst:1823 msgid "An optional pointer to a \"descriptor get\" function." msgstr "" -#: ../../c-api/typeobj.rst:1769 ../../c-api/typeobj.rst:1785 -#: ../../c-api/typeobj.rst:1849 ../../c-api/typeobj.rst:1879 -#: ../../c-api/typeobj.rst:1903 +#: ../../c-api/typeobj.rst:1825 ../../c-api/typeobj.rst:1841 +#: ../../c-api/typeobj.rst:1905 ../../c-api/typeobj.rst:1935 +#: ../../c-api/typeobj.rst:1959 msgid "The function signature is::" msgstr "A assinatura da função é::" -#: ../../c-api/typeobj.rst:1782 +#: ../../c-api/typeobj.rst:1827 +msgid "PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);" +msgstr "" + +#: ../../c-api/typeobj.rst:1838 msgid "" "An optional pointer to a function for setting and deleting a descriptor's " "value." msgstr "" -#: ../../c-api/typeobj.rst:1789 +#: ../../c-api/typeobj.rst:1843 +msgid "int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);" +msgstr "" + +#: ../../c-api/typeobj.rst:1845 msgid "The *value* argument is set to ``NULL`` to delete the value." msgstr "" -#: ../../c-api/typeobj.rst:1800 +#: ../../c-api/typeobj.rst:1856 msgid "" "While this field is still supported, :c:macro:`Py_TPFLAGS_MANAGED_DICT` " "should be used instead, if at all possible." msgstr "" -#: ../../c-api/typeobj.rst:1803 +#: ../../c-api/typeobj.rst:1859 msgid "" "If the instances of this type have a dictionary containing instance " "variables, this field is non-zero and contains the offset in the instances " @@ -2694,19 +3004,19 @@ msgid "" "func:`PyObject_GenericGetAttr`." msgstr "" -#: ../../c-api/typeobj.rst:1808 +#: ../../c-api/typeobj.rst:1864 msgid "" "Do not confuse this field with :c:member:`~PyTypeObject.tp_dict`; that is " "the dictionary for attributes of the type object itself." msgstr "" -#: ../../c-api/typeobj.rst:1811 +#: ../../c-api/typeobj.rst:1867 msgid "" "The value specifies the offset of the dictionary from the start of the " "instance structure." msgstr "" -#: ../../c-api/typeobj.rst:1813 +#: ../../c-api/typeobj.rst:1869 msgid "" "The :c:member:`~PyTypeObject.tp_dictoffset` should be regarded as write-" "only. To get the pointer to the dictionary call :c:func:" @@ -2715,13 +3025,13 @@ msgid "" "to call :c:func:`PyObject_GetAttr` when accessing an attribute on the object." msgstr "" -#: ../../c-api/typeobj.rst:1819 +#: ../../c-api/typeobj.rst:1875 msgid "" -"It is an error to set both the :c:macro:`Py_TPFLAGS_MANAGED_WEAKREF` bit " -"and :c:member:`~PyTypeObject.tp_dictoffset`." +"It is an error to set both the :c:macro:`Py_TPFLAGS_MANAGED_DICT` bit and :c:" +"member:`~PyTypeObject.tp_dictoffset`." msgstr "" -#: ../../c-api/typeobj.rst:1824 +#: ../../c-api/typeobj.rst:1880 msgid "" "This field is inherited by subtypes. A subtype should not override this " "offset; doing so could be unsafe, if C code tries to access the dictionary " @@ -2729,25 +3039,25 @@ msgid "" "`Py_TPFLAGS_MANAGED_DICT`." msgstr "" -#: ../../c-api/typeobj.rst:1831 +#: ../../c-api/typeobj.rst:1887 msgid "" "This slot has no default. For :ref:`static types `, if the " "field is ``NULL`` then no :attr:`~object.__dict__` gets created for " "instances." msgstr "" -#: ../../c-api/typeobj.rst:1834 +#: ../../c-api/typeobj.rst:1890 msgid "" "If the :c:macro:`Py_TPFLAGS_MANAGED_DICT` bit is set in the :c:member:" "`~PyTypeObject.tp_flags` field, then :c:member:`~PyTypeObject.tp_dictoffset` " "will be set to ``-1``, to indicate that it is unsafe to use this field." msgstr "" -#: ../../c-api/typeobj.rst:1842 +#: ../../c-api/typeobj.rst:1898 msgid "An optional pointer to an instance initialization function." msgstr "" -#: ../../c-api/typeobj.rst:1844 +#: ../../c-api/typeobj.rst:1900 msgid "" "This function corresponds to the :meth:`~object.__init__` method of " "classes. Like :meth:`!__init__`, it is possible to create an instance " @@ -2755,14 +3065,18 @@ msgid "" "instance by calling its :meth:`!__init__` method again." msgstr "" -#: ../../c-api/typeobj.rst:1853 +#: ../../c-api/typeobj.rst:1907 +msgid "int tp_init(PyObject *self, PyObject *args, PyObject *kwds);" +msgstr "" + +#: ../../c-api/typeobj.rst:1909 msgid "" "The self argument is the instance to be initialized; the *args* and *kwds* " "arguments represent positional and keyword arguments of the call to :meth:" "`~object.__init__`." msgstr "" -#: ../../c-api/typeobj.rst:1857 +#: ../../c-api/typeobj.rst:1913 msgid "" "The :c:member:`~PyTypeObject.tp_init` function, if not ``NULL``, is called " "when an instance is created normally by calling its type, after the type's :" @@ -2774,43 +3088,52 @@ msgid "" "subtype's :c:member:`~PyTypeObject.tp_init` is called." msgstr "" -#: ../../c-api/typeobj.rst:1864 +#: ../../c-api/typeobj.rst:1920 msgid "Returns ``0`` on success, ``-1`` and sets an exception on error." msgstr "" -#: ../../c-api/typeobj.rst:1872 +#: ../../c-api/typeobj.rst:1928 msgid "" "For :ref:`static types ` this field does not have a default." msgstr "" -#: ../../c-api/typeobj.rst:1877 +#: ../../c-api/typeobj.rst:1933 msgid "An optional pointer to an instance allocation function." msgstr "" -#: ../../c-api/typeobj.rst:1885 +#: ../../c-api/typeobj.rst:1937 +msgid "PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);" +msgstr "" + +#: ../../c-api/typeobj.rst:1941 msgid "" "This field is inherited by static subtypes, but not by dynamic subtypes " "(subtypes created by a class statement)." msgstr "" -#: ../../c-api/typeobj.rst:1890 +#: ../../c-api/typeobj.rst:1946 msgid "" "For dynamic subtypes, this field is always set to :c:func:" "`PyType_GenericAlloc`, to force a standard heap allocation strategy." msgstr "" -#: ../../c-api/typeobj.rst:1894 +#: ../../c-api/typeobj.rst:1950 msgid "" "For static subtypes, :c:data:`PyBaseObject_Type` uses :c:func:" "`PyType_GenericAlloc`. That is the recommended value for all statically " "defined types." msgstr "" -#: ../../c-api/typeobj.rst:1901 +#: ../../c-api/typeobj.rst:1957 msgid "An optional pointer to an instance creation function." msgstr "" -#: ../../c-api/typeobj.rst:1907 +#: ../../c-api/typeobj.rst:1961 +msgid "" +"PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);" +msgstr "" + +#: ../../c-api/typeobj.rst:1963 msgid "" "The *subtype* argument is the type of the object being created; the *args* " "and *kwds* arguments represent positional and keyword arguments of the call " @@ -2819,7 +3142,7 @@ msgid "" "that type (but not an unrelated type)." msgstr "" -#: ../../c-api/typeobj.rst:1913 +#: ../../c-api/typeobj.rst:1969 msgid "" "The :c:member:`~PyTypeObject.tp_new` function should call ``subtype-" ">tp_alloc(subtype, nitems)`` to allocate space for the object, and then do " @@ -2831,20 +3154,20 @@ msgid "" "be deferred to :c:member:`~PyTypeObject.tp_init`." msgstr "" -#: ../../c-api/typeobj.rst:1921 +#: ../../c-api/typeobj.rst:1977 msgid "" "Set the :c:macro:`Py_TPFLAGS_DISALLOW_INSTANTIATION` flag to disallow " "creating instances of the type in Python." msgstr "" -#: ../../c-api/typeobj.rst:1926 +#: ../../c-api/typeobj.rst:1982 msgid "" "This field is inherited by subtypes, except it is not inherited by :ref:" "`static types ` whose :c:member:`~PyTypeObject.tp_base` is " "``NULL`` or ``&PyBaseObject_Type``." msgstr "" -#: ../../c-api/typeobj.rst:1932 +#: ../../c-api/typeobj.rst:1988 msgid "" "For :ref:`static types ` this field has no default. This means " "if the slot is defined as ``NULL``, the type cannot be called to create new " @@ -2852,40 +3175,44 @@ msgid "" "factory function." msgstr "" -#: ../../c-api/typeobj.rst:1940 +#: ../../c-api/typeobj.rst:1996 msgid "" "An optional pointer to an instance deallocation function. Its signature is::" msgstr "" -#: ../../c-api/typeobj.rst:1944 +#: ../../c-api/typeobj.rst:1998 +msgid "void tp_free(void *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:2000 msgid "" "An initializer that is compatible with this signature is :c:func:" "`PyObject_Free`." msgstr "" -#: ../../c-api/typeobj.rst:1948 +#: ../../c-api/typeobj.rst:2004 msgid "" "This field is inherited by static subtypes, but not by dynamic subtypes " "(subtypes created by a class statement)" msgstr "" -#: ../../c-api/typeobj.rst:1953 +#: ../../c-api/typeobj.rst:2009 msgid "" "In dynamic subtypes, this field is set to a deallocator suitable to match :c:" "func:`PyType_GenericAlloc` and the value of the :c:macro:" "`Py_TPFLAGS_HAVE_GC` flag bit." msgstr "" -#: ../../c-api/typeobj.rst:1957 +#: ../../c-api/typeobj.rst:2013 msgid "" "For static subtypes, :c:data:`PyBaseObject_Type` uses :c:func:`PyObject_Del`." msgstr "" -#: ../../c-api/typeobj.rst:1962 +#: ../../c-api/typeobj.rst:2018 msgid "An optional pointer to a function called by the garbage collector." msgstr "" -#: ../../c-api/typeobj.rst:1964 +#: ../../c-api/typeobj.rst:2020 msgid "" "The garbage collector needs to know whether a particular object is " "collectible or not. Normally, it is sufficient to look at the object's " @@ -2897,89 +3224,93 @@ msgid "" "instance. The signature is::" msgstr "" -#: ../../c-api/typeobj.rst:1974 +#: ../../c-api/typeobj.rst:2028 +msgid "int tp_is_gc(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:2030 msgid "" "(The only example of this are types themselves. The metatype, :c:data:" "`PyType_Type`, defines this function to distinguish between statically and :" "ref:`dynamically allocated types `.)" msgstr "" -#: ../../c-api/typeobj.rst:1984 +#: ../../c-api/typeobj.rst:2040 msgid "" "This slot has no default. If this field is ``NULL``, :c:macro:" "`Py_TPFLAGS_HAVE_GC` is used as the functional equivalent." msgstr "" -#: ../../c-api/typeobj.rst:1990 +#: ../../c-api/typeobj.rst:2046 msgid "Tuple of base types." msgstr "" -#: ../../c-api/typeobj.rst:1992 ../../c-api/typeobj.rst:2016 +#: ../../c-api/typeobj.rst:2048 ../../c-api/typeobj.rst:2072 msgid "" "This field should be set to ``NULL`` and treated as read-only. Python will " "fill it in when the type is :c:func:`initialized `." msgstr "" -#: ../../c-api/typeobj.rst:1995 +#: ../../c-api/typeobj.rst:2051 msgid "" "For dynamically created classes, the ``Py_tp_bases`` :c:type:`slot " "` can be used instead of the *bases* argument of :c:func:" "`PyType_FromSpecWithBases`. The argument form is preferred." msgstr "" -#: ../../c-api/typeobj.rst:2002 +#: ../../c-api/typeobj.rst:2058 msgid "" "Multiple inheritance does not work well for statically defined types. If you " "set ``tp_bases`` to a tuple, Python will not raise an error, but some slots " "will only be inherited from the first base." msgstr "" -#: ../../c-api/typeobj.rst:2008 ../../c-api/typeobj.rst:2031 -#: ../../c-api/typeobj.rst:2048 ../../c-api/typeobj.rst:2065 -#: ../../c-api/typeobj.rst:2079 +#: ../../c-api/typeobj.rst:2064 ../../c-api/typeobj.rst:2087 +#: ../../c-api/typeobj.rst:2104 ../../c-api/typeobj.rst:2121 +#: ../../c-api/typeobj.rst:2135 msgid "This field is not inherited." msgstr "" -#: ../../c-api/typeobj.rst:2013 +#: ../../c-api/typeobj.rst:2069 msgid "" "Tuple containing the expanded set of base types, starting with the type " "itself and ending with :class:`object`, in Method Resolution Order." msgstr "" -#: ../../c-api/typeobj.rst:2021 +#: ../../c-api/typeobj.rst:2077 msgid "" "This field is not inherited; it is calculated fresh by :c:func:" "`PyType_Ready`." msgstr "" -#: ../../c-api/typeobj.rst:2027 +#: ../../c-api/typeobj.rst:2083 msgid "Unused. Internal use only." msgstr "" -#: ../../c-api/typeobj.rst:2036 +#: ../../c-api/typeobj.rst:2092 msgid "" "A collection of subclasses. Internal use only. May be an invalid pointer." msgstr "" -#: ../../c-api/typeobj.rst:2038 +#: ../../c-api/typeobj.rst:2094 msgid "" -"To get a list of subclasses, call the Python method :py:meth:`~class." +"To get a list of subclasses, call the Python method :py:meth:`~type." "__subclasses__`." msgstr "" -#: ../../c-api/typeobj.rst:2043 +#: ../../c-api/typeobj.rst:2099 msgid "" "For some types, this field does not hold a valid :c:expr:`PyObject*`. The " "type was changed to :c:expr:`void*` to indicate this." msgstr "" -#: ../../c-api/typeobj.rst:2053 +#: ../../c-api/typeobj.rst:2109 msgid "" "Weak reference list head, for weak references to this type object. Not " "inherited. Internal use only." msgstr "" -#: ../../c-api/typeobj.rst:2058 +#: ../../c-api/typeobj.rst:2114 msgid "" "Internals detail: For the static builtin types this is always ``NULL``, even " "if weakrefs are added. Instead, the weakrefs for each are stored on " @@ -2987,21 +3318,25 @@ msgid "" "``_PyObject_GET_WEAKREFS_LISTPTR()`` macro to avoid the distinction." msgstr "" -#: ../../c-api/typeobj.rst:2070 +#: ../../c-api/typeobj.rst:2126 msgid "" "This field is deprecated. Use :c:member:`~PyTypeObject.tp_finalize` instead." msgstr "" -#: ../../c-api/typeobj.rst:2075 +#: ../../c-api/typeobj.rst:2131 msgid "Used to index into the method cache. Internal use only." msgstr "" -#: ../../c-api/typeobj.rst:2084 +#: ../../c-api/typeobj.rst:2140 msgid "" "An optional pointer to an instance finalization function. Its signature is::" msgstr "" -#: ../../c-api/typeobj.rst:2088 +#: ../../c-api/typeobj.rst:2142 +msgid "void tp_finalize(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:2144 msgid "" "If :c:member:`~PyTypeObject.tp_finalize` is set, the interpreter calls it " "once when finalizing an instance. It is called either from the garbage " @@ -3011,38 +3346,40 @@ msgid "" "object in a sane state." msgstr "" -#: ../../c-api/typeobj.rst:2095 +#: ../../c-api/typeobj.rst:2151 msgid "" ":c:member:`~PyTypeObject.tp_finalize` should not mutate the current " "exception status; therefore, a recommended way to write a non-trivial " "finalizer is::" msgstr "" -#: ../../c-api/typeobj.rst:2112 +#: ../../c-api/typeobj.rst:2154 msgid "" -"Also, note that, in a garbage collected Python, :c:member:`~PyTypeObject." -"tp_dealloc` may be called from any Python thread, not just the thread which " -"created the object (if the object becomes part of a refcount cycle, that " -"cycle might be collected by a garbage collection on any thread). This is " -"not a problem for Python API calls, since the thread on which tp_dealloc is " -"called will own the Global Interpreter Lock (GIL). However, if the object " -"being destroyed in turn destroys objects from some other C or C++ library, " -"care should be taken to ensure that destroying those objects on the thread " -"which called tp_dealloc will not violate any assumptions of the library." +"static void\n" +"local_finalize(PyObject *self)\n" +"{\n" +" /* Save the current exception, if any. */\n" +" PyObject *exc = PyErr_GetRaisedException();\n" +"\n" +" /* ... */\n" +"\n" +" /* Restore the saved exception. */\n" +" PyErr_SetRaisedException(exc);\n" +"}" msgstr "" -#: ../../c-api/typeobj.rst:2131 +#: ../../c-api/typeobj.rst:2174 msgid "" "Before version 3.8 it was necessary to set the :c:macro:" "`Py_TPFLAGS_HAVE_FINALIZE` flags bit in order for this field to be used. " "This is no longer required." msgstr "" -#: ../../c-api/typeobj.rst:2135 +#: ../../c-api/typeobj.rst:2178 msgid "\"Safe object finalization\" (:pep:`442`)" msgstr "\"Finalização segura de objetos\" (:pep:`442`)" -#: ../../c-api/typeobj.rst:2140 +#: ../../c-api/typeobj.rst:2183 msgid "" "Vectorcall function to use for calls of this type object. In other words, it " "is used to implement :ref:`vectorcall ` for ``type.__call__``. " @@ -3050,65 +3387,65 @@ msgid "" "meth:`~object.__new__` and :meth:`~object.__init__` is used." msgstr "" -#: ../../c-api/typeobj.rst:2148 +#: ../../c-api/typeobj.rst:2191 msgid "This field is never inherited." msgstr "" -#: ../../c-api/typeobj.rst:2150 +#: ../../c-api/typeobj.rst:2193 msgid "(the field exists since 3.8 but it's only used since 3.9)" msgstr "" -#: ../../c-api/typeobj.rst:2155 +#: ../../c-api/typeobj.rst:2198 msgid "Internal. Do not use." msgstr "" -#: ../../c-api/typeobj.rst:2163 +#: ../../c-api/typeobj.rst:2206 msgid "Static Types" msgstr "" -#: ../../c-api/typeobj.rst:2165 +#: ../../c-api/typeobj.rst:2208 msgid "" "Traditionally, types defined in C code are *static*, that is, a static :c:" "type:`PyTypeObject` structure is defined directly in code and initialized " "using :c:func:`PyType_Ready`." msgstr "" -#: ../../c-api/typeobj.rst:2169 +#: ../../c-api/typeobj.rst:2212 msgid "" "This results in types that are limited relative to types defined in Python:" msgstr "" -#: ../../c-api/typeobj.rst:2171 +#: ../../c-api/typeobj.rst:2214 msgid "" "Static types are limited to one base, i.e. they cannot use multiple " "inheritance." msgstr "" -#: ../../c-api/typeobj.rst:2173 +#: ../../c-api/typeobj.rst:2216 msgid "" "Static type objects (but not necessarily their instances) are immutable. It " "is not possible to add or modify the type object's attributes from Python." msgstr "" -#: ../../c-api/typeobj.rst:2175 +#: ../../c-api/typeobj.rst:2218 msgid "" "Static type objects are shared across :ref:`sub-interpreters `, so they should not include any subinterpreter-" "specific state." msgstr "" -#: ../../c-api/typeobj.rst:2179 +#: ../../c-api/typeobj.rst:2222 msgid "" "Also, since :c:type:`PyTypeObject` is only part of the :ref:`Limited API " "` as an opaque struct, any extension modules using static " "types must be compiled for a specific Python minor version." msgstr "" -#: ../../c-api/typeobj.rst:2187 +#: ../../c-api/typeobj.rst:2230 msgid "Heap Types" msgstr "Tipos no heap" -#: ../../c-api/typeobj.rst:2189 +#: ../../c-api/typeobj.rst:2232 msgid "" "An alternative to :ref:`static types ` is *heap-allocated " "types*, or *heap types* for short, which correspond closely to classes " @@ -3116,29 +3453,75 @@ msgid "" "`Py_TPFLAGS_HEAPTYPE` flag set." msgstr "" -#: ../../c-api/typeobj.rst:2194 +#: ../../c-api/typeobj.rst:2237 msgid "" "This is done by filling a :c:type:`PyType_Spec` structure and calling :c:" "func:`PyType_FromSpec`, :c:func:`PyType_FromSpecWithBases`, :c:func:" "`PyType_FromModuleAndSpec`, or :c:func:`PyType_FromMetaclass`." msgstr "" -#: ../../c-api/typeobj.rst:2202 +#: ../../c-api/typeobj.rst:2245 msgid "Number Object Structures" msgstr "" -#: ../../c-api/typeobj.rst:2209 +#: ../../c-api/typeobj.rst:2252 msgid "" "This structure holds pointers to the functions which an object uses to " "implement the number protocol. Each function is used by the function of " "similar name documented in the :ref:`number` section." msgstr "" -#: ../../c-api/typeobj.rst:2215 ../../c-api/typeobj.rst:2539 +#: ../../c-api/typeobj.rst:2258 ../../c-api/typeobj.rst:2582 msgid "Here is the structure definition::" msgstr "" -#: ../../c-api/typeobj.rst:2262 +#: ../../c-api/typeobj.rst:2260 +msgid "" +"typedef struct {\n" +" binaryfunc nb_add;\n" +" binaryfunc nb_subtract;\n" +" binaryfunc nb_multiply;\n" +" binaryfunc nb_remainder;\n" +" binaryfunc nb_divmod;\n" +" ternaryfunc nb_power;\n" +" unaryfunc nb_negative;\n" +" unaryfunc nb_positive;\n" +" unaryfunc nb_absolute;\n" +" inquiry nb_bool;\n" +" unaryfunc nb_invert;\n" +" binaryfunc nb_lshift;\n" +" binaryfunc nb_rshift;\n" +" binaryfunc nb_and;\n" +" binaryfunc nb_xor;\n" +" binaryfunc nb_or;\n" +" unaryfunc nb_int;\n" +" void *nb_reserved;\n" +" unaryfunc nb_float;\n" +"\n" +" binaryfunc nb_inplace_add;\n" +" binaryfunc nb_inplace_subtract;\n" +" binaryfunc nb_inplace_multiply;\n" +" binaryfunc nb_inplace_remainder;\n" +" ternaryfunc nb_inplace_power;\n" +" binaryfunc nb_inplace_lshift;\n" +" binaryfunc nb_inplace_rshift;\n" +" binaryfunc nb_inplace_and;\n" +" binaryfunc nb_inplace_xor;\n" +" binaryfunc nb_inplace_or;\n" +"\n" +" binaryfunc nb_floor_divide;\n" +" binaryfunc nb_true_divide;\n" +" binaryfunc nb_inplace_floor_divide;\n" +" binaryfunc nb_inplace_true_divide;\n" +"\n" +" unaryfunc nb_index;\n" +"\n" +" binaryfunc nb_matrix_multiply;\n" +" binaryfunc nb_inplace_matrix_multiply;\n" +"} PyNumberMethods;" +msgstr "" + +#: ../../c-api/typeobj.rst:2305 msgid "" "Binary and ternary functions must check the type of all their operands, and " "implement the necessary conversions (at least one of the operands is an " @@ -3148,31 +3531,31 @@ msgid "" "and set an exception." msgstr "" -#: ../../c-api/typeobj.rst:2271 +#: ../../c-api/typeobj.rst:2314 msgid "" "The :c:member:`~PyNumberMethods.nb_reserved` field should always be " "``NULL``. It was previously called :c:member:`!nb_long`, and was renamed in " "Python 3.0.1." msgstr "" -#: ../../c-api/typeobj.rst:2316 +#: ../../c-api/typeobj.rst:2359 msgid "Mapping Object Structures" msgstr "" -#: ../../c-api/typeobj.rst:2323 +#: ../../c-api/typeobj.rst:2366 msgid "" "This structure holds pointers to the functions which an object uses to " "implement the mapping protocol. It has three members:" msgstr "" -#: ../../c-api/typeobj.rst:2328 +#: ../../c-api/typeobj.rst:2371 msgid "" "This function is used by :c:func:`PyMapping_Size` and :c:func:" "`PyObject_Size`, and has the same signature. This slot may be set to " "``NULL`` if the object has no defined length." msgstr "" -#: ../../c-api/typeobj.rst:2334 +#: ../../c-api/typeobj.rst:2377 msgid "" "This function is used by :c:func:`PyObject_GetItem` and :c:func:" "`PySequence_GetSlice`, and has the same signature as :c:func:`!" @@ -3180,7 +3563,7 @@ msgid "" "`PyMapping_Check` function to return ``1``, it can be ``NULL`` otherwise." msgstr "" -#: ../../c-api/typeobj.rst:2342 +#: ../../c-api/typeobj.rst:2385 msgid "" "This function is used by :c:func:`PyObject_SetItem`, :c:func:" "`PyObject_DelItem`, :c:func:`PySequence_SetSlice` and :c:func:" @@ -3190,17 +3573,17 @@ msgid "" "deletion." msgstr "" -#: ../../c-api/typeobj.rst:2353 +#: ../../c-api/typeobj.rst:2396 msgid "Sequence Object Structures" msgstr "" -#: ../../c-api/typeobj.rst:2360 +#: ../../c-api/typeobj.rst:2403 msgid "" "This structure holds pointers to the functions which an object uses to " "implement the sequence protocol." msgstr "" -#: ../../c-api/typeobj.rst:2365 +#: ../../c-api/typeobj.rst:2408 msgid "" "This function is used by :c:func:`PySequence_Size` and :c:func:" "`PyObject_Size`, and has the same signature. It is also used for handling " @@ -3208,21 +3591,21 @@ msgid "" "member:`~PySequenceMethods.sq_ass_item` slots." msgstr "" -#: ../../c-api/typeobj.rst:2372 +#: ../../c-api/typeobj.rst:2415 msgid "" "This function is used by :c:func:`PySequence_Concat` and has the same " "signature. It is also used by the ``+`` operator, after trying the numeric " "addition via the :c:member:`~PyNumberMethods.nb_add` slot." msgstr "" -#: ../../c-api/typeobj.rst:2378 +#: ../../c-api/typeobj.rst:2421 msgid "" "This function is used by :c:func:`PySequence_Repeat` and has the same " "signature. It is also used by the ``*`` operator, after trying numeric " "multiplication via the :c:member:`~PyNumberMethods.nb_multiply` slot." msgstr "" -#: ../../c-api/typeobj.rst:2384 +#: ../../c-api/typeobj.rst:2427 msgid "" "This function is used by :c:func:`PySequence_GetItem` and has the same " "signature. It is also used by :c:func:`PyObject_GetItem`, after trying the " @@ -3231,7 +3614,7 @@ msgid "" "``1``, it can be ``NULL`` otherwise." msgstr "" -#: ../../c-api/typeobj.rst:2390 +#: ../../c-api/typeobj.rst:2433 msgid "" "Negative indexes are handled as follows: if the :c:member:" "`~PySequenceMethods.sq_length` slot is filled, it is called and the sequence " @@ -3240,7 +3623,7 @@ msgid "" "index is passed as is to the function." msgstr "" -#: ../../c-api/typeobj.rst:2397 +#: ../../c-api/typeobj.rst:2440 msgid "" "This function is used by :c:func:`PySequence_SetItem` and has the same " "signature. It is also used by :c:func:`PyObject_SetItem` and :c:func:" @@ -3249,14 +3632,14 @@ msgid "" "``NULL`` if the object does not support item assignment and deletion." msgstr "" -#: ../../c-api/typeobj.rst:2406 +#: ../../c-api/typeobj.rst:2449 msgid "" "This function may be used by :c:func:`PySequence_Contains` and has the same " "signature. This slot may be left to ``NULL``, in this case :c:func:`!" "PySequence_Contains` simply traverses the sequence until it finds a match." msgstr "" -#: ../../c-api/typeobj.rst:2413 +#: ../../c-api/typeobj.rst:2456 msgid "" "This function is used by :c:func:`PySequence_InPlaceConcat` and has the same " "signature. It should modify its first operand, and return it. This slot " @@ -3266,7 +3649,7 @@ msgid "" "c:member:`~PyNumberMethods.nb_inplace_add` slot." msgstr "" -#: ../../c-api/typeobj.rst:2422 +#: ../../c-api/typeobj.rst:2465 msgid "" "This function is used by :c:func:`PySequence_InPlaceRepeat` and has the same " "signature. It should modify its first operand, and return it. This slot " @@ -3276,72 +3659,76 @@ msgid "" "via the :c:member:`~PyNumberMethods.nb_inplace_multiply` slot." msgstr "" -#: ../../c-api/typeobj.rst:2433 +#: ../../c-api/typeobj.rst:2476 msgid "Buffer Object Structures" msgstr "" -#: ../../c-api/typeobj.rst:2441 +#: ../../c-api/typeobj.rst:2484 msgid "" "This structure holds pointers to the functions required by the :ref:`Buffer " "protocol `. The protocol defines how an exporter object can " "expose its internal data to consumer objects." msgstr "" -#: ../../c-api/typeobj.rst:2447 ../../c-api/typeobj.rst:2496 -#: ../../c-api/typeobj.rst:2550 ../../c-api/typeobj.rst:2561 -#: ../../c-api/typeobj.rst:2573 ../../c-api/typeobj.rst:2583 +#: ../../c-api/typeobj.rst:2490 ../../c-api/typeobj.rst:2539 +#: ../../c-api/typeobj.rst:2593 ../../c-api/typeobj.rst:2604 +#: ../../c-api/typeobj.rst:2616 ../../c-api/typeobj.rst:2626 msgid "The signature of this function is::" msgstr "" -#: ../../c-api/typeobj.rst:2451 +#: ../../c-api/typeobj.rst:2492 +msgid "int (PyObject *exporter, Py_buffer *view, int flags);" +msgstr "" + +#: ../../c-api/typeobj.rst:2494 msgid "" "Handle a request to *exporter* to fill in *view* as specified by *flags*. " "Except for point (3), an implementation of this function MUST take these " "steps:" msgstr "" -#: ../../c-api/typeobj.rst:2455 +#: ../../c-api/typeobj.rst:2498 msgid "" "Check if the request can be met. If not, raise :exc:`BufferError`, set :c:" "expr:`view->obj` to ``NULL`` and return ``-1``." msgstr "" -#: ../../c-api/typeobj.rst:2458 +#: ../../c-api/typeobj.rst:2501 msgid "Fill in the requested fields." msgstr "" -#: ../../c-api/typeobj.rst:2460 +#: ../../c-api/typeobj.rst:2503 msgid "Increment an internal counter for the number of exports." msgstr "" -#: ../../c-api/typeobj.rst:2462 +#: ../../c-api/typeobj.rst:2505 msgid "" "Set :c:expr:`view->obj` to *exporter* and increment :c:expr:`view->obj`." msgstr "" -#: ../../c-api/typeobj.rst:2464 +#: ../../c-api/typeobj.rst:2507 msgid "Return ``0``." msgstr "Retorna ``0``." -#: ../../c-api/typeobj.rst:2466 +#: ../../c-api/typeobj.rst:2509 msgid "" "If *exporter* is part of a chain or tree of buffer providers, two main " "schemes can be used:" msgstr "" -#: ../../c-api/typeobj.rst:2469 +#: ../../c-api/typeobj.rst:2512 msgid "" "Re-export: Each member of the tree acts as the exporting object and sets :c:" "expr:`view->obj` to a new reference to itself." msgstr "" -#: ../../c-api/typeobj.rst:2472 +#: ../../c-api/typeobj.rst:2515 msgid "" "Redirect: The buffer request is redirected to the root object of the tree. " "Here, :c:expr:`view->obj` will be a new reference to the root object." msgstr "" -#: ../../c-api/typeobj.rst:2476 +#: ../../c-api/typeobj.rst:2519 msgid "" "The individual fields of *view* are described in section :ref:`Buffer " "structure `, the rules how an exporter must react to " @@ -3349,7 +3736,7 @@ msgid "" "types>`." msgstr "" -#: ../../c-api/typeobj.rst:2481 +#: ../../c-api/typeobj.rst:2524 msgid "" "All memory pointed to in the :c:type:`Py_buffer` structure belongs to the " "exporter and must remain valid until there are no consumers left. :c:member:" @@ -3358,19 +3745,23 @@ msgid "" "internal` are read-only for the consumer." msgstr "" -#: ../../c-api/typeobj.rst:2488 +#: ../../c-api/typeobj.rst:2531 msgid "" ":c:func:`PyBuffer_FillInfo` provides an easy way of exposing a simple bytes " "buffer while dealing correctly with all request types." msgstr "" -#: ../../c-api/typeobj.rst:2491 +#: ../../c-api/typeobj.rst:2534 msgid "" ":c:func:`PyObject_GetBuffer` is the interface for the consumer that wraps " "this function." msgstr "" -#: ../../c-api/typeobj.rst:2500 +#: ../../c-api/typeobj.rst:2541 +msgid "void (PyObject *exporter, Py_buffer *view);" +msgstr "" + +#: ../../c-api/typeobj.rst:2543 msgid "" "Handle a request to release the resources of the buffer. If no resources " "need to be released, :c:member:`PyBufferProcs.bf_releasebuffer` may be " @@ -3378,15 +3769,15 @@ msgid "" "these optional steps:" msgstr "" -#: ../../c-api/typeobj.rst:2505 +#: ../../c-api/typeobj.rst:2548 msgid "Decrement an internal counter for the number of exports." msgstr "" -#: ../../c-api/typeobj.rst:2507 +#: ../../c-api/typeobj.rst:2550 msgid "If the counter is ``0``, free all memory associated with *view*." msgstr "" -#: ../../c-api/typeobj.rst:2509 +#: ../../c-api/typeobj.rst:2552 msgid "" "The exporter MUST use the :c:member:`~Py_buffer.internal` field to keep " "track of buffer-specific resources. This field is guaranteed to remain " @@ -3394,68 +3785,94 @@ msgid "" "*view* argument." msgstr "" -#: ../../c-api/typeobj.rst:2515 +#: ../../c-api/typeobj.rst:2558 msgid "" "This function MUST NOT decrement :c:expr:`view->obj`, since that is done " "automatically in :c:func:`PyBuffer_Release` (this scheme is useful for " "breaking reference cycles)." msgstr "" -#: ../../c-api/typeobj.rst:2520 +#: ../../c-api/typeobj.rst:2563 msgid "" ":c:func:`PyBuffer_Release` is the interface for the consumer that wraps this " "function." msgstr "" -#: ../../c-api/typeobj.rst:2528 +#: ../../c-api/typeobj.rst:2571 msgid "Async Object Structures" msgstr "" -#: ../../c-api/typeobj.rst:2536 +#: ../../c-api/typeobj.rst:2579 msgid "" "This structure holds pointers to the functions required to implement :term:" "`awaitable` and :term:`asynchronous iterator` objects." msgstr "" -#: ../../c-api/typeobj.rst:2554 +#: ../../c-api/typeobj.rst:2584 +msgid "" +"typedef struct {\n" +" unaryfunc am_await;\n" +" unaryfunc am_aiter;\n" +" unaryfunc am_anext;\n" +" sendfunc am_send;\n" +"} PyAsyncMethods;" +msgstr "" + +#: ../../c-api/typeobj.rst:2595 +msgid "PyObject *am_await(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:2597 msgid "" "The returned object must be an :term:`iterator`, i.e. :c:func:`PyIter_Check` " "must return ``1`` for it." msgstr "" -#: ../../c-api/typeobj.rst:2557 +#: ../../c-api/typeobj.rst:2600 msgid "" "This slot may be set to ``NULL`` if an object is not an :term:`awaitable`." msgstr "" -#: ../../c-api/typeobj.rst:2565 +#: ../../c-api/typeobj.rst:2606 +msgid "PyObject *am_aiter(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:2608 msgid "" "Must return an :term:`asynchronous iterator` object. See :meth:`~object." "__anext__` for details." msgstr "" -#: ../../c-api/typeobj.rst:2568 +#: ../../c-api/typeobj.rst:2611 msgid "" "This slot may be set to ``NULL`` if an object does not implement " "asynchronous iteration protocol." msgstr "" -#: ../../c-api/typeobj.rst:2577 +#: ../../c-api/typeobj.rst:2618 +msgid "PyObject *am_anext(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:2620 msgid "" "Must return an :term:`awaitable` object. See :meth:`~object.__anext__` for " "details. This slot may be set to ``NULL``." msgstr "" -#: ../../c-api/typeobj.rst:2587 +#: ../../c-api/typeobj.rst:2628 +msgid "PySendResult am_send(PyObject *self, PyObject *arg, PyObject **result);" +msgstr "" + +#: ../../c-api/typeobj.rst:2630 msgid "" "See :c:func:`PyIter_Send` for details. This slot may be set to ``NULL``." msgstr "" -#: ../../c-api/typeobj.rst:2596 +#: ../../c-api/typeobj.rst:2639 msgid "Slot Type typedefs" msgstr "" -#: ../../c-api/typeobj.rst:2600 +#: ../../c-api/typeobj.rst:2643 msgid "" "The purpose of this function is to separate memory allocation from memory " "initialization. It should return a pointer to a block of memory of adequate " @@ -3469,80 +3886,80 @@ msgid "" "length of the block should be :c:member:`~PyTypeObject.tp_basicsize`." msgstr "" -#: ../../c-api/typeobj.rst:2610 +#: ../../c-api/typeobj.rst:2653 msgid "" "This function should not do any other instance initialization, not even to " "allocate additional memory; that should be done by :c:member:`~PyTypeObject." "tp_new`." msgstr "" -#: ../../c-api/typeobj.rst:2617 +#: ../../c-api/typeobj.rst:2660 msgid "See :c:member:`~PyTypeObject.tp_free`." msgstr "" -#: ../../c-api/typeobj.rst:2621 +#: ../../c-api/typeobj.rst:2664 msgid "See :c:member:`~PyTypeObject.tp_new`." msgstr "" -#: ../../c-api/typeobj.rst:2625 +#: ../../c-api/typeobj.rst:2668 msgid "See :c:member:`~PyTypeObject.tp_init`." msgstr "" -#: ../../c-api/typeobj.rst:2629 +#: ../../c-api/typeobj.rst:2672 msgid "See :c:member:`~PyTypeObject.tp_repr`." msgstr "" -#: ../../c-api/typeobj.rst:2633 ../../c-api/typeobj.rst:2642 +#: ../../c-api/typeobj.rst:2676 ../../c-api/typeobj.rst:2685 msgid "Return the value of the named attribute for the object." msgstr "" -#: ../../c-api/typeobj.rst:2637 ../../c-api/typeobj.rst:2648 +#: ../../c-api/typeobj.rst:2680 ../../c-api/typeobj.rst:2691 msgid "" "Set the value of the named attribute for the object. The value argument is " "set to ``NULL`` to delete the attribute." msgstr "" -#: ../../c-api/typeobj.rst:2644 +#: ../../c-api/typeobj.rst:2687 msgid "See :c:member:`~PyTypeObject.tp_getattro`." msgstr "" -#: ../../c-api/typeobj.rst:2651 +#: ../../c-api/typeobj.rst:2694 msgid "See :c:member:`~PyTypeObject.tp_setattro`." msgstr "" -#: ../../c-api/typeobj.rst:2655 +#: ../../c-api/typeobj.rst:2698 msgid "See :c:member:`~PyTypeObject.tp_descr_get`." msgstr "" -#: ../../c-api/typeobj.rst:2659 +#: ../../c-api/typeobj.rst:2702 msgid "See :c:member:`~PyTypeObject.tp_descr_set`." msgstr "" -#: ../../c-api/typeobj.rst:2663 +#: ../../c-api/typeobj.rst:2706 msgid "See :c:member:`~PyTypeObject.tp_hash`." msgstr "" -#: ../../c-api/typeobj.rst:2667 +#: ../../c-api/typeobj.rst:2710 msgid "See :c:member:`~PyTypeObject.tp_richcompare`." msgstr "" -#: ../../c-api/typeobj.rst:2671 +#: ../../c-api/typeobj.rst:2714 msgid "See :c:member:`~PyTypeObject.tp_iter`." msgstr "" -#: ../../c-api/typeobj.rst:2675 +#: ../../c-api/typeobj.rst:2718 msgid "See :c:member:`~PyTypeObject.tp_iternext`." msgstr "" -#: ../../c-api/typeobj.rst:2689 +#: ../../c-api/typeobj.rst:2732 msgid "See :c:member:`~PyAsyncMethods.am_send`." msgstr "" -#: ../../c-api/typeobj.rst:2705 +#: ../../c-api/typeobj.rst:2748 msgid "Examples" msgstr "Exemplos" -#: ../../c-api/typeobj.rst:2707 +#: ../../c-api/typeobj.rst:2750 msgid "" "The following are simple examples of Python type definitions. They include " "common usage you may encounter. Some demonstrate tricky corner cases. For " @@ -3550,46 +3967,179 @@ msgid "" "and :ref:`new-types-topics`." msgstr "" -#: ../../c-api/typeobj.rst:2712 +#: ../../c-api/typeobj.rst:2755 msgid "A basic :ref:`static type `::" msgstr "" -#: ../../c-api/typeobj.rst:2729 +#: ../../c-api/typeobj.rst:2757 +msgid "" +"typedef struct {\n" +" PyObject_HEAD\n" +" const char *data;\n" +"} MyObject;\n" +"\n" +"static PyTypeObject MyObject_Type = {\n" +" PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"mymod.MyObject\",\n" +" .tp_basicsize = sizeof(MyObject),\n" +" .tp_doc = PyDoc_STR(\"My objects\"),\n" +" .tp_new = myobj_new,\n" +" .tp_dealloc = (destructor)myobj_dealloc,\n" +" .tp_repr = (reprfunc)myobj_repr,\n" +"};" +msgstr "" + +#: ../../c-api/typeobj.rst:2772 msgid "" "You may also find older code (especially in the CPython code base) with a " "more verbose initializer::" msgstr "" -#: ../../c-api/typeobj.rst:2773 +#: ../../c-api/typeobj.rst:2775 +msgid "" +"static PyTypeObject MyObject_Type = {\n" +" PyVarObject_HEAD_INIT(NULL, 0)\n" +" \"mymod.MyObject\", /* tp_name */\n" +" sizeof(MyObject), /* tp_basicsize */\n" +" 0, /* tp_itemsize */\n" +" (destructor)myobj_dealloc, /* tp_dealloc */\n" +" 0, /* tp_vectorcall_offset */\n" +" 0, /* tp_getattr */\n" +" 0, /* tp_setattr */\n" +" 0, /* tp_as_async */\n" +" (reprfunc)myobj_repr, /* tp_repr */\n" +" 0, /* tp_as_number */\n" +" 0, /* tp_as_sequence */\n" +" 0, /* tp_as_mapping */\n" +" 0, /* tp_hash */\n" +" 0, /* tp_call */\n" +" 0, /* tp_str */\n" +" 0, /* tp_getattro */\n" +" 0, /* tp_setattro */\n" +" 0, /* tp_as_buffer */\n" +" 0, /* tp_flags */\n" +" PyDoc_STR(\"My objects\"), /* tp_doc */\n" +" 0, /* tp_traverse */\n" +" 0, /* tp_clear */\n" +" 0, /* tp_richcompare */\n" +" 0, /* tp_weaklistoffset */\n" +" 0, /* tp_iter */\n" +" 0, /* tp_iternext */\n" +" 0, /* tp_methods */\n" +" 0, /* tp_members */\n" +" 0, /* tp_getset */\n" +" 0, /* tp_base */\n" +" 0, /* tp_dict */\n" +" 0, /* tp_descr_get */\n" +" 0, /* tp_descr_set */\n" +" 0, /* tp_dictoffset */\n" +" 0, /* tp_init */\n" +" 0, /* tp_alloc */\n" +" myobj_new, /* tp_new */\n" +"};" +msgstr "" + +#: ../../c-api/typeobj.rst:2816 msgid "A type that supports weakrefs, instance dicts, and hashing::" msgstr "" -#: ../../c-api/typeobj.rst:2798 +#: ../../c-api/typeobj.rst:2818 +msgid "" +"typedef struct {\n" +" PyObject_HEAD\n" +" const char *data;\n" +"} MyObject;\n" +"\n" +"static PyTypeObject MyObject_Type = {\n" +" PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"mymod.MyObject\",\n" +" .tp_basicsize = sizeof(MyObject),\n" +" .tp_doc = PyDoc_STR(\"My objects\"),\n" +" .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |\n" +" Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_MANAGED_DICT |\n" +" Py_TPFLAGS_MANAGED_WEAKREF,\n" +" .tp_new = myobj_new,\n" +" .tp_traverse = (traverseproc)myobj_traverse,\n" +" .tp_clear = (inquiry)myobj_clear,\n" +" .tp_alloc = PyType_GenericNew,\n" +" .tp_dealloc = (destructor)myobj_dealloc,\n" +" .tp_repr = (reprfunc)myobj_repr,\n" +" .tp_hash = (hashfunc)myobj_hash,\n" +" .tp_richcompare = PyBaseObject_Type.tp_richcompare,\n" +"};" +msgstr "" + +#: ../../c-api/typeobj.rst:2841 msgid "" "A str subclass that cannot be subclassed and cannot be called to create " "instances (e.g. uses a separate factory func) using :c:macro:" "`Py_TPFLAGS_DISALLOW_INSTANTIATION` flag::" msgstr "" -#: ../../c-api/typeobj.rst:2817 +#: ../../c-api/typeobj.rst:2845 +msgid "" +"typedef struct {\n" +" PyUnicodeObject raw;\n" +" char *extra;\n" +"} MyStr;\n" +"\n" +"static PyTypeObject MyStr_Type = {\n" +" PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"mymod.MyStr\",\n" +" .tp_basicsize = sizeof(MyStr),\n" +" .tp_base = NULL, // set to &PyUnicode_Type in module init\n" +" .tp_doc = PyDoc_STR(\"my custom str\"),\n" +" .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,\n" +" .tp_repr = (reprfunc)myobj_repr,\n" +"};" +msgstr "" + +#: ../../c-api/typeobj.rst:2860 msgid "" "The simplest :ref:`static type ` with fixed-length instances::" msgstr "" -#: ../../c-api/typeobj.rst:2828 +#: ../../c-api/typeobj.rst:2862 +msgid "" +"typedef struct {\n" +" PyObject_HEAD\n" +"} MyObject;\n" +"\n" +"static PyTypeObject MyObject_Type = {\n" +" PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"mymod.MyObject\",\n" +"};" +msgstr "" + +#: ../../c-api/typeobj.rst:2871 msgid "" "The simplest :ref:`static type ` with variable-length " "instances::" msgstr "" -#: ../../c-api/typeobj.rst:787 ../../c-api/typeobj.rst:852 +#: ../../c-api/typeobj.rst:2873 +msgid "" +"typedef struct {\n" +" PyObject_VAR_HEAD\n" +" const char *data[1];\n" +"} MyObject;\n" +"\n" +"static PyTypeObject MyObject_Type = {\n" +" PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"mymod.MyObject\",\n" +" .tp_basicsize = sizeof(MyObject) - sizeof(char *),\n" +" .tp_itemsize = sizeof(char *),\n" +"};" +msgstr "" + +#: ../../c-api/typeobj.rst:843 ../../c-api/typeobj.rst:908 msgid "built-in function" msgstr "função embutida" -#: ../../c-api/typeobj.rst:787 +#: ../../c-api/typeobj.rst:843 msgid "repr" msgstr "repr" -#: ../../c-api/typeobj.rst:852 +#: ../../c-api/typeobj.rst:908 msgid "hash" msgstr "hash" diff --git a/c-api/unicode.po b/c-api/unicode.po index 0c979fa43..e255b3cbd 100644 --- a/c-api/unicode.po +++ b/c-api/unicode.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Julio Gadioli Soares , 2021 -# Welington Carlos , 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# felipe caridade fernandes , 2023 -# Rafael Fontenelle , 2023 -# Marco Rougeth , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-19 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Marco Rougeth , 2024\n" +"POT-Creation-Date: 2025-05-16 14:58+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -34,7 +29,7 @@ msgstr "Objetos Unicode e Codecs" #: ../../c-api/unicode.rst:12 msgid "Unicode Objects" -msgstr "" +msgstr "Objetos Unicode" #: ../../c-api/unicode.rst:14 msgid "" @@ -45,27 +40,39 @@ msgid "" "65536; otherwise, code points must be below 1114112 (which is the full " "Unicode range)." msgstr "" +"Desde a implementação da :pep:`393` no Python 3.3, os objetos Unicode usam " +"internamente uma variedade de representações para permitir o processamento " +"de toda a gama de caracteres Unicode, mantendo a eficiência de memória. Há " +"casos especiais para strings em que todos os pontos de código estão abaixo " +"de 128, 256 ou 65536; caso contrário, os pontos de código devem estar abaixo " +"de 1114112 (que é a gama completa de caracteres Unicode)." #: ../../c-api/unicode.rst:20 msgid "" "UTF-8 representation is created on demand and cached in the Unicode object." msgstr "" +"A representação UTF-8 é criada sob demanda e armazenada em cache no objeto " +"Unicode." #: ../../c-api/unicode.rst:23 msgid "" "The :c:type:`Py_UNICODE` representation has been removed since Python 3.12 " "with deprecated APIs. See :pep:`623` for more information." msgstr "" +"A representação :c:type:`Py_UNICODE` foi removida desde o Python 3.12 com " +"APIs descontinuadas. Consulte :pep:`623` para obter mais informações." #: ../../c-api/unicode.rst:29 msgid "Unicode Type" -msgstr "" +msgstr "Tipo Unicode" #: ../../c-api/unicode.rst:31 msgid "" "These are the basic Unicode object types used for the Unicode implementation " "in Python:" msgstr "" +"Estes são os tipos básicos de objetos Unicode usados ​​para a implementação " +"Unicode em Python:" #: ../../c-api/unicode.rst:38 msgid "" @@ -73,12 +80,18 @@ msgid "" "characters of 32 bits, 16 bits and 8 bits, respectively. When dealing with " "single Unicode characters, use :c:type:`Py_UCS4`." msgstr "" +"Esses tipos são definições de tipo para tipos inteiros sem sinal, amplos o " +"suficiente para conter caracteres de 32 bits, 16 bits e 8 bits, " +"respectivamente. Ao lidar com caracteres Unicode simples, use :c:type:" +"`Py_UCS4`." #: ../../c-api/unicode.rst:47 msgid "" "This is a typedef of :c:type:`wchar_t`, which is a 16-bit type or 32-bit " "type depending on the platform." msgstr "" +"Este é um typedef de :c:type:`wchar_t`, que é um tipo de 16 bits ou 32 bits, " +"dependendo da plataforma." #: ../../c-api/unicode.rst:50 msgid "" @@ -86,6 +99,9 @@ msgid "" "whether you selected a \"narrow\" or \"wide\" Unicode version of Python at " "build time." msgstr "" +"Em versões anteriores, esse era um tipo de 16 bits ou de 32 bits, dependendo " +"se você selecionava uma versão Unicode \"estreita\" ou \"ampla\" do Python " +"no momento da construção." #: ../../c-api/unicode.rst:62 msgid "" @@ -93,76 +109,110 @@ msgid "" "almost all cases, they shouldn't be used directly, since all API functions " "that deal with Unicode objects take and return :c:type:`PyObject` pointers." msgstr "" +"Esses subtipos de :c:type:`PyObject` representam um objeto Unicode do " +"Python. Em quase todos os casos, eles não devem ser usados ​​diretamente, pois " +"todas as funções da API que lidam com objetos Unicode recebem e retornam " +"ponteiros :c:type:`PyObject`." #: ../../c-api/unicode.rst:71 msgid "" -"This instance of :c:type:`PyTypeObject` represents the Python Unicode type. " +"This instance of :c:type:`PyTypeObject` represents the Python Unicode type. " "It is exposed to Python code as ``str``." msgstr "" +"Esta instância de :c:type:`PyTypeObject` representa o tipo Unicode do " +"Python. Ela é exposta ao código Python como ``str``." + +#: ../../c-api/unicode.rst:77 +msgid "" +"This instance of :c:type:`PyTypeObject` represents the Python Unicode " +"iterator type. It is used to iterate over Unicode string objects." +msgstr "" +"Esta instância de :c:type:`PyTypeObject` representa o tipo iterador Unicode " +"do Python. É usada para iterar sobre objetos string Unicode." -#: ../../c-api/unicode.rst:75 +#: ../../c-api/unicode.rst:81 msgid "" "The following APIs are C macros and static inlined functions for fast checks " "and access to internal read-only data of Unicode objects:" msgstr "" +"As seguintes APIs são macros C e funções estáticas embutidas para " +"verificações rápidas e acesso a dados internos somente leitura de objetos " +"Unicode:" -#: ../../c-api/unicode.rst:80 +#: ../../c-api/unicode.rst:86 msgid "" "Return true if the object *obj* is a Unicode object or an instance of a " "Unicode subtype. This function always succeeds." msgstr "" +"Retorna verdadeiro se o objeto *obj* for um objeto Unicode ou uma instância " +"de um subtipo Unicode. Esta função sempre tem sucesso." -#: ../../c-api/unicode.rst:86 +#: ../../c-api/unicode.rst:92 msgid "" "Return true if the object *obj* is a Unicode object, but not an instance of " "a subtype. This function always succeeds." msgstr "" +"Retorna verdadeiro se o objeto *obj* for um objeto Unicode, mas não uma " +"instância de um subtipo. Esta função sempre tem sucesso." -#: ../../c-api/unicode.rst:92 +#: ../../c-api/unicode.rst:98 msgid "Returns ``0``. This API is kept only for backward compatibility." -msgstr "" +msgstr "Retorna ``0``. Essa API é mantida apenas para retrocompatibilidade." -#: ../../c-api/unicode.rst:96 +#: ../../c-api/unicode.rst:102 msgid "This API does nothing since Python 3.12." -msgstr "" +msgstr "Esta API não faz nada desde o Python 3.12." -#: ../../c-api/unicode.rst:102 +#: ../../c-api/unicode.rst:108 msgid "" "Return the length of the Unicode string, in code points. *unicode* has to " "be a Unicode object in the \"canonical\" representation (not checked)." msgstr "" +"Retorna o comprimento da string Unicode, em pontos de código. *unicode* deve " +"ser um objeto Unicode na representação \"canônica\" (não marcado)." -#: ../../c-api/unicode.rst:112 +#: ../../c-api/unicode.rst:118 msgid "" "Return a pointer to the canonical representation cast to UCS1, UCS2 or UCS4 " "integer types for direct character access. No checks are performed if the " "canonical representation has the correct character size; use :c:func:" "`PyUnicode_KIND` to select the right function." msgstr "" +"Retorna um ponteiro para a representação canônica convertida para tipos " +"inteiros UCS1, UCS2 ou UCS4 para acesso direto aos caracteres. Nenhuma " +"verificação é realizada se a representação canônica tem o tamanho de " +"caractere correto; use :c:func:`PyUnicode_KIND` para selecionar a função " +"correta." -#: ../../c-api/unicode.rst:124 +#: ../../c-api/unicode.rst:130 msgid "Return values of the :c:func:`PyUnicode_KIND` macro." -msgstr "" +msgstr "Valores de retorno da macro :c:func:`PyUnicode_KIND`." -#: ../../c-api/unicode.rst:128 +#: ../../c-api/unicode.rst:134 msgid "``PyUnicode_WCHAR_KIND`` has been removed." -msgstr "" +msgstr "``PyUnicode_WCHAR_KIND`` foi removida." -#: ../../c-api/unicode.rst:134 +#: ../../c-api/unicode.rst:140 msgid "" "Return one of the PyUnicode kind constants (see above) that indicate how " "many bytes per character this Unicode object uses to store its data. " "*unicode* has to be a Unicode object in the \"canonical\" representation " "(not checked)." msgstr "" +"Retorna uma das constantes do tipo PyUnicode (veja acima) que indicam " +"quantos bytes por caractere este objeto Unicode usa para armazenar seus " +"dados. *unicode* precisa ser um objeto Unicode na representação " +"\"canônica\" (não marcado)." -#: ../../c-api/unicode.rst:143 +#: ../../c-api/unicode.rst:149 msgid "" "Return a void pointer to the raw Unicode buffer. *unicode* has to be a " "Unicode object in the \"canonical\" representation (not checked)." msgstr "" +"Retorna um ponteiro vazio para o buffer Unicode bruto. *unicode* deve ser um " +"objeto Unicode na representação \"canônica\" (não marcado)." -#: ../../c-api/unicode.rst:152 +#: ../../c-api/unicode.rst:158 msgid "" "Write into a canonical representation *data* (as obtained with :c:func:" "`PyUnicode_DATA`). This function performs no sanity checks, and is intended " @@ -171,190 +221,215 @@ msgid "" "(starts at 0) and *value* is the new code point value which should be " "written to that location." msgstr "" +"Escreva em uma representação canônica *data* (conforme obtido com :c:func:" +"`PyUnicode_DATA`). Esta função não realiza verificações de sanidade e " +"destina-se ao uso em laços. O chamador deve armazenar em cache o valor de " +"*type* e o ponteiro *data* conforme obtidos de outras chamadas. *índice* é o " +"índice na string (começa em 0) e *value* é o novo valor do ponto de código " +"que deve ser escrito naquele local." -#: ../../c-api/unicode.rst:165 +#: ../../c-api/unicode.rst:171 msgid "" "Read a code point from a canonical representation *data* (as obtained with :" "c:func:`PyUnicode_DATA`). No checks or ready calls are performed." msgstr "" +"Lê um ponto de código de uma representação canônica *data* (conforme obtido " +"com :c:func:`PyUnicode_DATA`). Nenhuma verificação ou chamada pronta é " +"realizada." -#: ../../c-api/unicode.rst:173 +#: ../../c-api/unicode.rst:179 msgid "" "Read a character from a Unicode object *unicode*, which must be in the " "\"canonical\" representation. This is less efficient than :c:func:" "`PyUnicode_READ` if you do multiple consecutive reads." msgstr "" +"Lê um caractere de um objeto Unicode *unicode*, que deve estar na " +"representação \"canônica\". Isso é menos eficiente do que :c:func:" +"`PyUnicode_READ` se você fizer várias leituras consecutivas." -#: ../../c-api/unicode.rst:182 +#: ../../c-api/unicode.rst:188 msgid "" "Return the maximum code point that is suitable for creating another string " "based on *unicode*, which must be in the \"canonical\" representation. This " "is always an approximation but more efficient than iterating over the string." msgstr "" +"Retorna o ponto de código máximo adequado para criar outra string baseada em " +"*unicode*, que deve estar na representação \"canônica\". Isso é sempre uma " +"aproximação, mas é mais eficiente do que iterar sobre a string." -#: ../../c-api/unicode.rst:191 +#: ../../c-api/unicode.rst:197 msgid "" "Return ``1`` if the string is a valid identifier according to the language " "definition, section :ref:`identifiers`. Return ``0`` otherwise." msgstr "" +"Retorna ``1`` se a string é um identificador válido conforme a definição da " +"linguagem, seção :ref:`identifiers`. Do contrário, retorna ``0``." -#: ../../c-api/unicode.rst:194 +#: ../../c-api/unicode.rst:200 msgid "" "The function does not call :c:func:`Py_FatalError` anymore if the string is " "not ready." msgstr "" +"A função não chama mais :c:func:`Py_FatalError` se a string não estiver " +"pronta." -#: ../../c-api/unicode.rst:200 +#: ../../c-api/unicode.rst:206 msgid "Unicode Character Properties" -msgstr "" +msgstr "Propriedade de caracteres Unicode" -#: ../../c-api/unicode.rst:202 +#: ../../c-api/unicode.rst:208 msgid "" "Unicode provides many different character properties. The most often needed " "ones are available through these macros which are mapped to C functions " "depending on the Python configuration." msgstr "" +"O Unicode fornece muitas propriedades de caracteres diferentes. As mais " +"frequentemente necessárias estão disponíveis por meio destas macros, que são " +"mapeadas para funções C, dependendo da configuração do Python." -#: ../../c-api/unicode.rst:209 +#: ../../c-api/unicode.rst:215 msgid "" "Return ``1`` or ``0`` depending on whether *ch* is a whitespace character." msgstr "" +"Retorna ``1`` ou ``0`` dependendo se *ch* é um caractere de espaço em branco." -#: ../../c-api/unicode.rst:214 +#: ../../c-api/unicode.rst:220 msgid "" "Return ``1`` or ``0`` depending on whether *ch* is a lowercase character." -msgstr "" +msgstr "Retorna ``1`` ou ``0`` dependendo se *ch* é um caractere minúsculo." -#: ../../c-api/unicode.rst:219 +#: ../../c-api/unicode.rst:225 msgid "" "Return ``1`` or ``0`` depending on whether *ch* is an uppercase character." -msgstr "" +msgstr "Retorna ``1`` ou ``0`` dependendo se *ch* é um caractere maiúsculo." -#: ../../c-api/unicode.rst:224 +#: ../../c-api/unicode.rst:230 msgid "" "Return ``1`` or ``0`` depending on whether *ch* is a titlecase character." -msgstr "" +msgstr "Retorna ``1`` ou ``0`` dependendo se *ch* é um caractere em TitleCase." -#: ../../c-api/unicode.rst:229 +#: ../../c-api/unicode.rst:235 msgid "" "Return ``1`` or ``0`` depending on whether *ch* is a linebreak character." msgstr "" +"Retorna ``1`` ou ``0`` dependendo se *ch* é um caractere de quebra de linha." -#: ../../c-api/unicode.rst:234 +#: ../../c-api/unicode.rst:240 msgid "Return ``1`` or ``0`` depending on whether *ch* is a decimal character." -msgstr "" +msgstr "Retorna ``1`` ou ``0`` dependendo se *ch* é um caractere decimal." -#: ../../c-api/unicode.rst:239 +#: ../../c-api/unicode.rst:245 msgid "Return ``1`` or ``0`` depending on whether *ch* is a digit character." -msgstr "" +msgstr "Retorna ``1`` ou ``0`` dependendo se *ch* é um caractere de dígito." -#: ../../c-api/unicode.rst:244 +#: ../../c-api/unicode.rst:250 msgid "Return ``1`` or ``0`` depending on whether *ch* is a numeric character." -msgstr "" +msgstr "Retorna ``1`` ou ``0`` dependendo se *ch* é um caractere numérico." -#: ../../c-api/unicode.rst:249 +#: ../../c-api/unicode.rst:255 msgid "" "Return ``1`` or ``0`` depending on whether *ch* is an alphabetic character." -msgstr "" +msgstr "Retorna ``1`` ou ``0`` dependendo se *ch* é um caractere alfabético." -#: ../../c-api/unicode.rst:254 +#: ../../c-api/unicode.rst:260 msgid "" "Return ``1`` or ``0`` depending on whether *ch* is an alphanumeric character." -msgstr "" +msgstr "Retorna ``1`` ou ``0`` dependendo se *ch* é um caractere alfanumérico." -#: ../../c-api/unicode.rst:259 +#: ../../c-api/unicode.rst:265 msgid "" -"Return ``1`` or ``0`` depending on whether *ch* is a printable character. " -"Nonprintable characters are those characters defined in the Unicode " -"character database as \"Other\" or \"Separator\", excepting the ASCII space " -"(0x20) which is considered printable. (Note that printable characters in " -"this context are those which should not be escaped when :func:`repr` is " -"invoked on a string. It has no bearing on the handling of strings written " -"to :data:`sys.stdout` or :data:`sys.stderr`.)" +"Return ``1`` or ``0`` depending on whether *ch* is a printable character, in " +"the sense of :meth:`str.isprintable`." msgstr "" +"Retorna ``1`` ou ``0`` dependendo se *ch* é um caractere imprimível, no " +"sentido de :meth:`str.isprintable`." -#: ../../c-api/unicode.rst:268 +#: ../../c-api/unicode.rst:269 msgid "These APIs can be used for fast direct character conversions:" msgstr "" -#: ../../c-api/unicode.rst:273 +#: ../../c-api/unicode.rst:274 msgid "Return the character *ch* converted to lower case." msgstr "" -#: ../../c-api/unicode.rst:278 +#: ../../c-api/unicode.rst:279 msgid "Return the character *ch* converted to upper case." msgstr "" -#: ../../c-api/unicode.rst:283 +#: ../../c-api/unicode.rst:284 msgid "Return the character *ch* converted to title case." msgstr "" -#: ../../c-api/unicode.rst:288 +#: ../../c-api/unicode.rst:289 msgid "" "Return the character *ch* converted to a decimal positive integer. Return " "``-1`` if this is not possible. This function does not raise exceptions." msgstr "" -#: ../../c-api/unicode.rst:294 +#: ../../c-api/unicode.rst:295 msgid "" "Return the character *ch* converted to a single digit integer. Return ``-1`` " "if this is not possible. This function does not raise exceptions." msgstr "" -#: ../../c-api/unicode.rst:300 +#: ../../c-api/unicode.rst:301 msgid "" "Return the character *ch* converted to a double. Return ``-1.0`` if this is " "not possible. This function does not raise exceptions." msgstr "" -#: ../../c-api/unicode.rst:304 +#: ../../c-api/unicode.rst:305 msgid "These APIs can be used to work with surrogates:" msgstr "" -#: ../../c-api/unicode.rst:308 +#: ../../c-api/unicode.rst:309 msgid "Check if *ch* is a surrogate (``0xD800 <= ch <= 0xDFFF``)." msgstr "" -#: ../../c-api/unicode.rst:312 +#: ../../c-api/unicode.rst:313 msgid "Check if *ch* is a high surrogate (``0xD800 <= ch <= 0xDBFF``)." msgstr "" -#: ../../c-api/unicode.rst:316 +#: ../../c-api/unicode.rst:317 msgid "Check if *ch* is a low surrogate (``0xDC00 <= ch <= 0xDFFF``)." msgstr "" -#: ../../c-api/unicode.rst:320 +#: ../../c-api/unicode.rst:321 msgid "" -"Join two surrogate characters and return a single :c:type:`Py_UCS4` value. " +"Join two surrogate code points and return a single :c:type:`Py_UCS4` value. " "*high* and *low* are respectively the leading and trailing surrogates in a " "surrogate pair. *high* must be in the range [0xD800; 0xDBFF] and *low* must " "be in the range [0xDC00; 0xDFFF]." msgstr "" -#: ../../c-api/unicode.rst:327 +#: ../../c-api/unicode.rst:328 msgid "Creating and accessing Unicode strings" msgstr "" -#: ../../c-api/unicode.rst:329 +#: ../../c-api/unicode.rst:330 msgid "" "To create Unicode objects and access their basic sequence properties, use " "these APIs:" msgstr "" -#: ../../c-api/unicode.rst:334 +#: ../../c-api/unicode.rst:335 msgid "" "Create a new Unicode object. *maxchar* should be the true maximum code " "point to be placed in the string. As an approximation, it can be rounded up " "to the nearest value in the sequence 127, 255, 65535, 1114111." msgstr "" -#: ../../c-api/unicode.rst:338 +#: ../../c-api/unicode.rst:339 msgid "" "This is the recommended way to allocate a new Unicode object. Objects " "created using this function are not resizable." msgstr "" -#: ../../c-api/unicode.rst:347 +#: ../../c-api/unicode.rst:342 +msgid "On error, set an exception and return ``NULL``." +msgstr "" + +#: ../../c-api/unicode.rst:350 msgid "" "Create a new Unicode object with the given *kind* (possible values are :c:" "macro:`PyUnicode_1BYTE_KIND` etc., as returned by :c:func:" @@ -366,7 +441,7 @@ msgstr "" "c:func:`PyUnicode_KIND`). O *buffer* deve apontar para um array de unidades " "com *size* de 1, 2 ou 4 bytes por caractere, conforme fornecido pelo tipo." -#: ../../c-api/unicode.rst:352 +#: ../../c-api/unicode.rst:355 msgid "" "If necessary, the input *buffer* is copied and transformed into the " "canonical representation. For example, if the *buffer* is a UCS4 string (:c:" @@ -374,7 +449,7 @@ msgid "" "range, it will be transformed into UCS1 (:c:macro:`PyUnicode_1BYTE_KIND`)." msgstr "" -#: ../../c-api/unicode.rst:363 +#: ../../c-api/unicode.rst:366 msgid "" "Create a Unicode object from the char buffer *str*. The bytes will be " "interpreted as being UTF-8 encoded. The buffer is copied into the new " @@ -382,29 +457,29 @@ msgid "" "data is not allowed." msgstr "" -#: ../../c-api/unicode.rst:369 +#: ../../c-api/unicode.rst:372 msgid "This function raises :exc:`SystemError` when:" msgstr "" -#: ../../c-api/unicode.rst:371 +#: ../../c-api/unicode.rst:374 msgid "*size* < 0," msgstr "" -#: ../../c-api/unicode.rst:372 +#: ../../c-api/unicode.rst:375 msgid "*str* is ``NULL`` and *size* > 0" msgstr "" -#: ../../c-api/unicode.rst:374 +#: ../../c-api/unicode.rst:377 msgid "*str* == ``NULL`` with *size* > 0 is not allowed anymore." msgstr "" -#: ../../c-api/unicode.rst:380 +#: ../../c-api/unicode.rst:383 msgid "" "Create a Unicode object from a UTF-8 encoded null-terminated char buffer " "*str*." msgstr "" -#: ../../c-api/unicode.rst:386 +#: ../../c-api/unicode.rst:389 msgid "" "Take a C :c:func:`printf`\\ -style *format* string and a variable number of " "arguments, calculate the size of the resulting Python Unicode string and " @@ -413,7 +488,7 @@ msgid "" "*format* ASCII-encoded string." msgstr "" -#: ../../c-api/unicode.rst:392 +#: ../../c-api/unicode.rst:395 msgid "" "A conversion specifier contains two or more characters and has the following " "components, which must occur in this order:" @@ -421,11 +496,11 @@ msgstr "" "Um especificador de conversão contém dois ou mais caracteres e tem os " "seguintes componentes, que devem aparecer nesta ordem:" -#: ../../c-api/unicode.rst:395 +#: ../../c-api/unicode.rst:398 msgid "The ``'%'`` character, which marks the start of the specifier." msgstr "O caractere ``'%'``, que determina o início do especificador." -#: ../../c-api/unicode.rst:397 +#: ../../c-api/unicode.rst:400 msgid "" "Conversion flags (optional), which affect the result of some conversion " "types." @@ -433,7 +508,7 @@ msgstr "" "Flags de conversão (opcional), que afetam o resultado de alguns tipos de " "conversão." -#: ../../c-api/unicode.rst:400 +#: ../../c-api/unicode.rst:403 msgid "" "Minimum field width (optional). If specified as an ``'*'`` (asterisk), the " "actual width is given in the next argument, which must be of type :c:expr:" @@ -441,7 +516,7 @@ msgid "" "optional precision." msgstr "" -#: ../../c-api/unicode.rst:405 +#: ../../c-api/unicode.rst:408 msgid "" "Precision (optional), given as a ``'.'`` (dot) followed by the precision. If " "specified as ``'*'`` (an asterisk), the actual precision is given in the " @@ -449,316 +524,316 @@ msgid "" "comes after the precision." msgstr "" -#: ../../c-api/unicode.rst:410 +#: ../../c-api/unicode.rst:413 msgid "Length modifier (optional)." -msgstr "Modificador de Comprimento(opcional)." +msgstr "Modificador de comprimento (opcional)." -#: ../../c-api/unicode.rst:412 +#: ../../c-api/unicode.rst:415 msgid "Conversion type." -msgstr "Tipos de Conversão" +msgstr "Tipos de conversão." -#: ../../c-api/unicode.rst:414 +#: ../../c-api/unicode.rst:417 msgid "The conversion flag characters are:" msgstr "Os caracteres flags de conversão são:" -#: ../../c-api/unicode.rst:419 +#: ../../c-api/unicode.rst:422 msgid "Flag" msgstr "Sinalizador" -#: ../../c-api/unicode.rst:419 +#: ../../c-api/unicode.rst:422 msgid "Meaning" msgstr "Significado" -#: ../../c-api/unicode.rst:421 +#: ../../c-api/unicode.rst:424 msgid "``0``" msgstr "``0``" -#: ../../c-api/unicode.rst:421 +#: ../../c-api/unicode.rst:424 msgid "The conversion will be zero padded for numeric values." msgstr "A conversão será preenchida por zeros para valores numéricos." -#: ../../c-api/unicode.rst:423 +#: ../../c-api/unicode.rst:426 msgid "``-``" msgstr "" -#: ../../c-api/unicode.rst:423 +#: ../../c-api/unicode.rst:426 msgid "" "The converted value is left adjusted (overrides the ``0`` flag if both are " "given)." msgstr "" -#: ../../c-api/unicode.rst:427 +#: ../../c-api/unicode.rst:430 msgid "" "The length modifiers for following integer conversions (``d``, ``i``, ``o``, " "``u``, ``x``, or ``X``) specify the type of the argument (:c:expr:`int` by " "default):" msgstr "" -#: ../../c-api/unicode.rst:434 +#: ../../c-api/unicode.rst:437 msgid "Modifier" msgstr "" -#: ../../c-api/unicode.rst:434 +#: ../../c-api/unicode.rst:437 msgid "Types" msgstr "Tipos" -#: ../../c-api/unicode.rst:436 +#: ../../c-api/unicode.rst:439 msgid "``l``" msgstr "``l``" -#: ../../c-api/unicode.rst:436 +#: ../../c-api/unicode.rst:439 msgid ":c:expr:`long` or :c:expr:`unsigned long`" msgstr "" -#: ../../c-api/unicode.rst:438 +#: ../../c-api/unicode.rst:441 msgid "``ll``" msgstr "" -#: ../../c-api/unicode.rst:438 +#: ../../c-api/unicode.rst:441 msgid ":c:expr:`long long` or :c:expr:`unsigned long long`" msgstr "" -#: ../../c-api/unicode.rst:440 +#: ../../c-api/unicode.rst:443 msgid "``j``" msgstr "" -#: ../../c-api/unicode.rst:440 +#: ../../c-api/unicode.rst:443 msgid ":c:type:`intmax_t` or :c:type:`uintmax_t`" msgstr "" -#: ../../c-api/unicode.rst:442 +#: ../../c-api/unicode.rst:445 msgid "``z``" msgstr "" -#: ../../c-api/unicode.rst:442 +#: ../../c-api/unicode.rst:445 msgid ":c:type:`size_t` or :c:type:`ssize_t`" msgstr "" -#: ../../c-api/unicode.rst:444 +#: ../../c-api/unicode.rst:447 msgid "``t``" msgstr "" -#: ../../c-api/unicode.rst:444 +#: ../../c-api/unicode.rst:447 msgid ":c:type:`ptrdiff_t`" msgstr "" -#: ../../c-api/unicode.rst:447 +#: ../../c-api/unicode.rst:450 msgid "" "The length modifier ``l`` for following conversions ``s`` or ``V`` specify " "that the type of the argument is :c:expr:`const wchar_t*`." msgstr "" -#: ../../c-api/unicode.rst:450 +#: ../../c-api/unicode.rst:453 msgid "The conversion specifiers are:" msgstr "" -#: ../../c-api/unicode.rst:456 +#: ../../c-api/unicode.rst:459 msgid "Conversion Specifier" msgstr "" -#: ../../c-api/unicode.rst:457 +#: ../../c-api/unicode.rst:460 msgid "Type" msgstr "Tipo" -#: ../../c-api/unicode.rst:458 +#: ../../c-api/unicode.rst:461 msgid "Comment" msgstr "Comentário" -#: ../../c-api/unicode.rst:460 +#: ../../c-api/unicode.rst:463 msgid "``%``" msgstr "``%``" -#: ../../c-api/unicode.rst:461 +#: ../../c-api/unicode.rst:464 msgid "*n/a*" msgstr "*n/d*" -#: ../../c-api/unicode.rst:462 +#: ../../c-api/unicode.rst:465 msgid "The literal ``%`` character." msgstr "" -#: ../../c-api/unicode.rst:464 +#: ../../c-api/unicode.rst:467 msgid "``d``, ``i``" msgstr "" -#: ../../c-api/unicode.rst:465 ../../c-api/unicode.rst:469 -#: ../../c-api/unicode.rst:473 ../../c-api/unicode.rst:477 -#: ../../c-api/unicode.rst:481 +#: ../../c-api/unicode.rst:468 ../../c-api/unicode.rst:472 +#: ../../c-api/unicode.rst:476 ../../c-api/unicode.rst:480 +#: ../../c-api/unicode.rst:484 msgid "Specified by the length modifier" msgstr "" -#: ../../c-api/unicode.rst:466 +#: ../../c-api/unicode.rst:469 msgid "The decimal representation of a signed C integer." msgstr "" -#: ../../c-api/unicode.rst:468 +#: ../../c-api/unicode.rst:471 msgid "``u``" msgstr "" -#: ../../c-api/unicode.rst:470 +#: ../../c-api/unicode.rst:473 msgid "The decimal representation of an unsigned C integer." msgstr "" -#: ../../c-api/unicode.rst:472 +#: ../../c-api/unicode.rst:475 msgid "``o``" msgstr "``o``" -#: ../../c-api/unicode.rst:474 +#: ../../c-api/unicode.rst:477 msgid "The octal representation of an unsigned C integer." msgstr "" -#: ../../c-api/unicode.rst:476 +#: ../../c-api/unicode.rst:479 msgid "``x``" msgstr "``x``" -#: ../../c-api/unicode.rst:478 +#: ../../c-api/unicode.rst:481 msgid "The hexadecimal representation of an unsigned C integer (lowercase)." msgstr "" -#: ../../c-api/unicode.rst:480 +#: ../../c-api/unicode.rst:483 msgid "``X``" msgstr "" -#: ../../c-api/unicode.rst:482 +#: ../../c-api/unicode.rst:485 msgid "The hexadecimal representation of an unsigned C integer (uppercase)." msgstr "" -#: ../../c-api/unicode.rst:484 +#: ../../c-api/unicode.rst:487 msgid "``c``" msgstr "``c``" -#: ../../c-api/unicode.rst:485 +#: ../../c-api/unicode.rst:488 msgid ":c:expr:`int`" msgstr ":c:expr:`int`" -#: ../../c-api/unicode.rst:486 +#: ../../c-api/unicode.rst:489 msgid "A single character." msgstr "" -#: ../../c-api/unicode.rst:488 +#: ../../c-api/unicode.rst:491 msgid "``s``" msgstr "``s``" -#: ../../c-api/unicode.rst:489 +#: ../../c-api/unicode.rst:492 msgid ":c:expr:`const char*` or :c:expr:`const wchar_t*`" msgstr "" -#: ../../c-api/unicode.rst:490 +#: ../../c-api/unicode.rst:493 msgid "A null-terminated C character array." msgstr "Uma matriz de caracteres C com terminação nula." -#: ../../c-api/unicode.rst:492 +#: ../../c-api/unicode.rst:495 msgid "``p``" msgstr "``p``" -#: ../../c-api/unicode.rst:493 +#: ../../c-api/unicode.rst:496 msgid ":c:expr:`const void*`" msgstr "" -#: ../../c-api/unicode.rst:494 +#: ../../c-api/unicode.rst:497 msgid "" "The hex representation of a C pointer. Mostly equivalent to " "``printf(\"%p\")`` except that it is guaranteed to start with the literal " "``0x`` regardless of what the platform's ``printf`` yields." msgstr "" -#: ../../c-api/unicode.rst:499 +#: ../../c-api/unicode.rst:502 msgid "``A``" msgstr "" -#: ../../c-api/unicode.rst:500 ../../c-api/unicode.rst:504 -#: ../../c-api/unicode.rst:514 ../../c-api/unicode.rst:518 -#: ../../c-api/unicode.rst:522 ../../c-api/unicode.rst:527 +#: ../../c-api/unicode.rst:503 ../../c-api/unicode.rst:507 +#: ../../c-api/unicode.rst:517 ../../c-api/unicode.rst:521 +#: ../../c-api/unicode.rst:525 ../../c-api/unicode.rst:530 msgid ":c:expr:`PyObject*`" msgstr "" -#: ../../c-api/unicode.rst:501 +#: ../../c-api/unicode.rst:504 msgid "The result of calling :func:`ascii`." msgstr "" -#: ../../c-api/unicode.rst:503 +#: ../../c-api/unicode.rst:506 msgid "``U``" msgstr "" -#: ../../c-api/unicode.rst:505 +#: ../../c-api/unicode.rst:508 msgid "A Unicode object." msgstr "" -#: ../../c-api/unicode.rst:507 +#: ../../c-api/unicode.rst:510 msgid "``V``" msgstr "" -#: ../../c-api/unicode.rst:508 +#: ../../c-api/unicode.rst:511 msgid ":c:expr:`PyObject*`, :c:expr:`const char*` or :c:expr:`const wchar_t*`" msgstr "" -#: ../../c-api/unicode.rst:509 +#: ../../c-api/unicode.rst:512 msgid "" "A Unicode object (which may be ``NULL``) and a null-terminated C character " "array as a second parameter (which will be used, if the first parameter is " "``NULL``)." msgstr "" -#: ../../c-api/unicode.rst:513 +#: ../../c-api/unicode.rst:516 msgid "``S``" msgstr "" -#: ../../c-api/unicode.rst:515 +#: ../../c-api/unicode.rst:518 msgid "The result of calling :c:func:`PyObject_Str`." msgstr "" -#: ../../c-api/unicode.rst:517 +#: ../../c-api/unicode.rst:520 msgid "``R``" msgstr "" -#: ../../c-api/unicode.rst:519 +#: ../../c-api/unicode.rst:522 msgid "The result of calling :c:func:`PyObject_Repr`." msgstr "" -#: ../../c-api/unicode.rst:521 +#: ../../c-api/unicode.rst:524 msgid "``T``" msgstr "" -#: ../../c-api/unicode.rst:523 +#: ../../c-api/unicode.rst:526 msgid "" "Get the fully qualified name of an object type; call :c:func:" "`PyType_GetFullyQualifiedName`." msgstr "" -#: ../../c-api/unicode.rst:526 +#: ../../c-api/unicode.rst:529 msgid "``#T``" msgstr "" -#: ../../c-api/unicode.rst:528 +#: ../../c-api/unicode.rst:531 msgid "" "Similar to ``T`` format, but use a colon (``:``) as separator between the " "module name and the qualified name." msgstr "" -#: ../../c-api/unicode.rst:531 +#: ../../c-api/unicode.rst:534 msgid "``N``" msgstr "``N``" -#: ../../c-api/unicode.rst:532 ../../c-api/unicode.rst:537 +#: ../../c-api/unicode.rst:535 ../../c-api/unicode.rst:540 msgid ":c:expr:`PyTypeObject*`" msgstr "" -#: ../../c-api/unicode.rst:533 +#: ../../c-api/unicode.rst:536 msgid "" "Get the fully qualified name of a type; call :c:func:" "`PyType_GetFullyQualifiedName`." msgstr "" -#: ../../c-api/unicode.rst:536 +#: ../../c-api/unicode.rst:539 msgid "``#N``" msgstr "" -#: ../../c-api/unicode.rst:538 +#: ../../c-api/unicode.rst:541 msgid "" "Similar to ``N`` format, but use a colon (``:``) as separator between the " "module name and the qualified name." msgstr "" -#: ../../c-api/unicode.rst:542 +#: ../../c-api/unicode.rst:545 msgid "" "The width formatter unit is number of characters rather than bytes. The " "precision formatter unit is number of bytes or :c:type:`wchar_t` items (if " @@ -768,28 +843,28 @@ msgid "" "``PyObject*`` argument is not ``NULL``)." msgstr "" -#: ../../c-api/unicode.rst:550 +#: ../../c-api/unicode.rst:553 msgid "" "Unlike to C :c:func:`printf` the ``0`` flag has effect even when a precision " "is given for integer conversions (``d``, ``i``, ``u``, ``o``, ``x``, or " "``X``)." msgstr "" -#: ../../c-api/unicode.rst:554 +#: ../../c-api/unicode.rst:557 msgid "Support for ``\"%lld\"`` and ``\"%llu\"`` added." msgstr "Suporte adicionado para ``\"%lld\"`` e ``\"%llu\"``." -#: ../../c-api/unicode.rst:557 +#: ../../c-api/unicode.rst:560 msgid "Support for ``\"%li\"``, ``\"%lli\"`` and ``\"%zi\"`` added." msgstr "" -#: ../../c-api/unicode.rst:560 +#: ../../c-api/unicode.rst:563 msgid "" "Support width and precision formatter for ``\"%s\"``, ``\"%A\"``, " "``\"%U\"``, ``\"%V\"``, ``\"%S\"``, ``\"%R\"`` added." msgstr "" -#: ../../c-api/unicode.rst:564 +#: ../../c-api/unicode.rst:567 msgid "" "Support for conversion specifiers ``o`` and ``X``. Support for length " "modifiers ``j`` and ``t``. Length modifiers are now applied to all integer " @@ -798,40 +873,50 @@ msgid "" "flag ``-``." msgstr "" -#: ../../c-api/unicode.rst:572 +#: ../../c-api/unicode.rst:575 msgid "" "An unrecognized format character now sets a :exc:`SystemError`. In previous " "versions it caused all the rest of the format string to be copied as-is to " "the result string, and any extra arguments discarded." msgstr "" -#: ../../c-api/unicode.rst:576 +#: ../../c-api/unicode.rst:579 msgid "Support for ``%T``, ``%#T``, ``%N`` and ``%#N`` formats added." msgstr "" -#: ../../c-api/unicode.rst:582 +#: ../../c-api/unicode.rst:585 msgid "" "Identical to :c:func:`PyUnicode_FromFormat` except that it takes exactly two " "arguments." msgstr "" -#: ../../c-api/unicode.rst:588 +#: ../../c-api/unicode.rst:591 msgid "" "Copy an instance of a Unicode subtype to a new true Unicode object if " "necessary. If *obj* is already a true Unicode object (not a subtype), return " "a new :term:`strong reference` to the object." msgstr "" -#: ../../c-api/unicode.rst:592 +#: ../../c-api/unicode.rst:595 msgid "" "Objects other than Unicode or its subtypes will cause a :exc:`TypeError`." msgstr "" -#: ../../c-api/unicode.rst:598 +#: ../../c-api/unicode.rst:600 +msgid "Create a Unicode Object from the given Unicode code point *ordinal*." +msgstr "" + +#: ../../c-api/unicode.rst:602 +msgid "" +"The ordinal must be in ``range(0x110000)``. A :exc:`ValueError` is raised in " +"the case it is not." +msgstr "" + +#: ../../c-api/unicode.rst:609 msgid "Decode an encoded object *obj* to a Unicode object." msgstr "" -#: ../../c-api/unicode.rst:600 +#: ../../c-api/unicode.rst:611 msgid "" ":class:`bytes`, :class:`bytearray` and other :term:`bytes-like objects " "` are decoded according to the given *encoding* and using " @@ -839,23 +924,48 @@ msgid "" "interface use the default values (see :ref:`builtincodecs` for details)." msgstr "" -#: ../../c-api/unicode.rst:606 +#: ../../c-api/unicode.rst:617 msgid "" "All other objects, including Unicode objects, cause a :exc:`TypeError` to be " "set." msgstr "" -#: ../../c-api/unicode.rst:609 +#: ../../c-api/unicode.rst:620 msgid "" "The API returns ``NULL`` if there was an error. The caller is responsible " "for decref'ing the returned objects." msgstr "" -#: ../../c-api/unicode.rst:615 +#: ../../c-api/unicode.rst:626 +msgid "" +"Return a mapping suitable for decoding a custom single-byte encoding. Given " +"a Unicode string *string* of up to 256 characters representing an encoding " +"table, returns either a compact internal mapping object or a dictionary " +"mapping character ordinals to byte values. Raises a :exc:`TypeError` and " +"return ``NULL`` on invalid input. .. versionadded:: 3.2" +msgstr "" + +#: ../../c-api/unicode.rst:636 +msgid "" +"Return the name of the default string encoding, ``\"utf-8\"``. See :func:" +"`sys.getdefaultencoding`." +msgstr "" + +#: ../../c-api/unicode.rst:639 +msgid "" +"The returned string does not need to be freed, and is valid until " +"interpreter shutdown." +msgstr "" + +#: ../../c-api/unicode.rst:645 msgid "Return the length of the Unicode object, in code points." msgstr "" -#: ../../c-api/unicode.rst:626 +#: ../../c-api/unicode.rst:647 +msgid "On error, set an exception and return ``-1``." +msgstr "" + +#: ../../c-api/unicode.rst:658 msgid "" "Copy characters from one Unicode object into another. This function " "performs character conversion when necessary and falls back to :c:func:`!" @@ -863,52 +973,61 @@ msgid "" "otherwise returns the number of copied characters." msgstr "" -#: ../../c-api/unicode.rst:637 +#: ../../c-api/unicode.rst:669 msgid "" "Fill a string with a character: write *fill_char* into ``unicode[start:" "start+length]``." msgstr "" -#: ../../c-api/unicode.rst:640 +#: ../../c-api/unicode.rst:672 msgid "" "Fail if *fill_char* is bigger than the string maximum character, or if the " "string has more than 1 reference." msgstr "" -#: ../../c-api/unicode.rst:643 +#: ../../c-api/unicode.rst:675 msgid "" "Return the number of written character, or return ``-1`` and raise an " "exception on error." msgstr "" -#: ../../c-api/unicode.rst:652 +#: ../../c-api/unicode.rst:684 msgid "" "Write a character to a string. The string must have been created through :c:" "func:`PyUnicode_New`. Since Unicode strings are supposed to be immutable, " "the string must not be shared, or have been hashed yet." msgstr "" -#: ../../c-api/unicode.rst:656 +#: ../../c-api/unicode.rst:688 msgid "" "This function checks that *unicode* is a Unicode object, that the index is " "not out of bounds, and that the object can be modified safely (i.e. that it " "its reference count is one)." msgstr "" -#: ../../c-api/unicode.rst:665 +#: ../../c-api/unicode.rst:692 +msgid "Return ``0`` on success, ``-1`` on error with an exception set." +msgstr "" + +#: ../../c-api/unicode.rst:699 msgid "" "Read a character from a string. This function checks that *unicode* is a " "Unicode object and the index is not out of bounds, in contrast to :c:func:" "`PyUnicode_READ_CHAR`, which performs no error checking." msgstr "" -#: ../../c-api/unicode.rst:675 +#: ../../c-api/unicode.rst:703 +msgid "Return character on success, ``-1`` on error with an exception set." +msgstr "" + +#: ../../c-api/unicode.rst:711 msgid "" "Return a substring of *unicode*, from character index *start* (included) to " -"character index *end* (excluded). Negative indices are not supported." +"character index *end* (excluded). Negative indices are not supported. On " +"error, set an exception and return ``NULL``." msgstr "" -#: ../../c-api/unicode.rst:684 +#: ../../c-api/unicode.rst:721 msgid "" "Copy the string *unicode* into a UCS4 buffer, including a null character, if " "*copy_null* is set. Returns ``NULL`` and sets an exception on error (in " @@ -916,7 +1035,7 @@ msgid "" "*unicode*). *buffer* is returned on success." msgstr "" -#: ../../c-api/unicode.rst:694 +#: ../../c-api/unicode.rst:731 msgid "" "Copy the string *unicode* into a new UCS4 buffer that is allocated using :c:" "func:`PyMem_Malloc`. If this fails, ``NULL`` is returned with a :exc:" @@ -924,17 +1043,17 @@ msgid "" "appended." msgstr "" -#: ../../c-api/unicode.rst:703 +#: ../../c-api/unicode.rst:740 msgid "Locale Encoding" msgstr "" -#: ../../c-api/unicode.rst:705 +#: ../../c-api/unicode.rst:742 msgid "" "The current locale encoding can be used to decode text from the operating " "system." msgstr "" -#: ../../c-api/unicode.rst:712 +#: ../../c-api/unicode.rst:749 msgid "" "Decode a string from UTF-8 on Android and VxWorks, or from the current " "locale encoding on other platforms. The supported error handlers are " @@ -943,21 +1062,21 @@ msgid "" "null character but cannot contain embedded null characters." msgstr "" -#: ../../c-api/unicode.rst:719 +#: ../../c-api/unicode.rst:756 msgid "" "Use :c:func:`PyUnicode_DecodeFSDefaultAndSize` to decode a string from the :" "term:`filesystem encoding and error handler`." msgstr "" -#: ../../c-api/unicode.rst:722 ../../c-api/unicode.rst:757 +#: ../../c-api/unicode.rst:759 ../../c-api/unicode.rst:794 msgid "This function ignores the :ref:`Python UTF-8 Mode `." msgstr "" -#: ../../c-api/unicode.rst:726 ../../c-api/unicode.rst:823 +#: ../../c-api/unicode.rst:763 ../../c-api/unicode.rst:879 msgid "The :c:func:`Py_DecodeLocale` function." msgstr "" -#: ../../c-api/unicode.rst:730 +#: ../../c-api/unicode.rst:767 msgid "" "The function now also uses the current locale encoding for the " "``surrogateescape`` error handler, except on Android. Previously, :c:func:" @@ -965,13 +1084,13 @@ msgid "" "locale encoding was used for ``strict``." msgstr "" -#: ../../c-api/unicode.rst:739 +#: ../../c-api/unicode.rst:776 msgid "" "Similar to :c:func:`PyUnicode_DecodeLocaleAndSize`, but compute the string " "length using :c:func:`!strlen`." msgstr "" -#: ../../c-api/unicode.rst:747 +#: ../../c-api/unicode.rst:784 msgid "" "Encode a Unicode object to UTF-8 on Android and VxWorks, or to the current " "locale encoding on other platforms. The supported error handlers are " @@ -980,17 +1099,17 @@ msgid "" "`bytes` object. *unicode* cannot contain embedded null characters." msgstr "" -#: ../../c-api/unicode.rst:754 +#: ../../c-api/unicode.rst:791 msgid "" "Use :c:func:`PyUnicode_EncodeFSDefault` to encode a string to the :term:" "`filesystem encoding and error handler`." msgstr "" -#: ../../c-api/unicode.rst:761 ../../c-api/unicode.rst:854 +#: ../../c-api/unicode.rst:798 ../../c-api/unicode.rst:910 msgid "The :c:func:`Py_EncodeLocale` function." msgstr "" -#: ../../c-api/unicode.rst:765 +#: ../../c-api/unicode.rst:802 msgid "" "The function now also uses the current locale encoding for the " "``surrogateescape`` error handler, except on Android. Previously, :c:func:" @@ -998,103 +1117,124 @@ msgid "" "locale encoding was used for ``strict``." msgstr "" -#: ../../c-api/unicode.rst:774 +#: ../../c-api/unicode.rst:811 msgid "File System Encoding" msgstr "" -#: ../../c-api/unicode.rst:776 +#: ../../c-api/unicode.rst:813 msgid "" "Functions encoding to and decoding from the :term:`filesystem encoding and " "error handler` (:pep:`383` and :pep:`529`)." msgstr "" -#: ../../c-api/unicode.rst:779 +#: ../../c-api/unicode.rst:816 msgid "" "To encode file names to :class:`bytes` during argument parsing, the " -"``\"O&\"`` converter should be used, passing :c:func:`PyUnicode_FSConverter` " -"as the conversion function:" +"``\"O&\"`` converter should be used, passing :c:func:`!" +"PyUnicode_FSConverter` as the conversion function:" msgstr "" -#: ../../c-api/unicode.rst:785 +#: ../../c-api/unicode.rst:822 msgid "" -"ParseTuple converter: encode :class:`str` objects -- obtained directly or " -"through the :class:`os.PathLike` interface -- to :class:`bytes` using :c:" -"func:`PyUnicode_EncodeFSDefault`; :class:`bytes` objects are output as-is. " -"*result* must be a :c:expr:`PyBytesObject*` which must be released when it " -"is no longer used." +":ref:`PyArg_Parse\\* converter `: encode :class:`str` objects " +"-- obtained directly or through the :class:`os.PathLike` interface -- to :" +"class:`bytes` using :c:func:`PyUnicode_EncodeFSDefault`; :class:`bytes` " +"objects are output as-is. *result* must be an address of a C variable of " +"type :c:expr:`PyObject*` (or :c:expr:`PyBytesObject*`). On success, set the " +"variable to a new :term:`strong reference` to a :ref:`bytes object " +"` which must be released when it is no longer used and return " +"a non-zero value (:c:macro:`Py_CLEANUP_SUPPORTED`). Embedded null bytes are " +"not allowed in the result. On failure, return ``0`` with an exception set." msgstr "" -#: ../../c-api/unicode.rst:793 ../../c-api/unicode.rst:810 +#: ../../c-api/unicode.rst:834 +msgid "" +"If *obj* is ``NULL``, the function releases a strong reference stored in the " +"variable referred by *result* and returns ``1``." +msgstr "" + +#: ../../c-api/unicode.rst:839 ../../c-api/unicode.rst:866 msgid "Accepts a :term:`path-like object`." msgstr "Aceita um :term:`objeto caminho ou similar`." -#: ../../c-api/unicode.rst:796 +#: ../../c-api/unicode.rst:842 msgid "" "To decode file names to :class:`str` during argument parsing, the ``\"O&\"`` " -"converter should be used, passing :c:func:`PyUnicode_FSDecoder` as the " +"converter should be used, passing :c:func:`!PyUnicode_FSDecoder` as the " "conversion function:" msgstr "" -#: ../../c-api/unicode.rst:802 +#: ../../c-api/unicode.rst:848 msgid "" -"ParseTuple converter: decode :class:`bytes` objects -- obtained either " -"directly or indirectly through the :class:`os.PathLike` interface -- to :" -"class:`str` using :c:func:`PyUnicode_DecodeFSDefaultAndSize`; :class:`str` " -"objects are output as-is. *result* must be a :c:expr:`PyUnicodeObject*` " -"which must be released when it is no longer used." +":ref:`PyArg_Parse\\* converter `: decode :class:`bytes` objects " +"-- obtained either directly or indirectly through the :class:`os.PathLike` " +"interface -- to :class:`str` using :c:func:" +"`PyUnicode_DecodeFSDefaultAndSize`; :class:`str` objects are output as-is. " +"*result* must be an address of a C variable of type :c:expr:`PyObject*` (or :" +"c:expr:`PyUnicodeObject*`). On success, set the variable to a new :term:" +"`strong reference` to a :ref:`Unicode object ` which must be " +"released when it is no longer used and return a non-zero value (:c:macro:" +"`Py_CLEANUP_SUPPORTED`). Embedded null characters are not allowed in the " +"result. On failure, return ``0`` with an exception set." msgstr "" -#: ../../c-api/unicode.rst:816 +#: ../../c-api/unicode.rst:861 +msgid "" +"If *obj* is ``NULL``, release the strong reference to the object referred to " +"by *result* and return ``1``." +msgstr "" + +#: ../../c-api/unicode.rst:872 msgid "Decode a string from the :term:`filesystem encoding and error handler`." msgstr "" -#: ../../c-api/unicode.rst:818 +#: ../../c-api/unicode.rst:874 msgid "" "If you need to decode a string from the current locale encoding, use :c:func:" "`PyUnicode_DecodeLocaleAndSize`." msgstr "" -#: ../../c-api/unicode.rst:825 ../../c-api/unicode.rst:838 -#: ../../c-api/unicode.rst:858 +#: ../../c-api/unicode.rst:881 ../../c-api/unicode.rst:894 +#: ../../c-api/unicode.rst:914 msgid "" "The :term:`filesystem error handler ` " "is now used." msgstr "" -#: ../../c-api/unicode.rst:832 +#: ../../c-api/unicode.rst:888 msgid "" "Decode a null-terminated string from the :term:`filesystem encoding and " "error handler`." msgstr "" -#: ../../c-api/unicode.rst:835 +#: ../../c-api/unicode.rst:891 msgid "" "If the string length is known, use :c:func:" "`PyUnicode_DecodeFSDefaultAndSize`." msgstr "" -#: ../../c-api/unicode.rst:845 +#: ../../c-api/unicode.rst:901 msgid "" "Encode a Unicode object to the :term:`filesystem encoding and error " "handler`, and return :class:`bytes`. Note that the resulting :class:`bytes` " "object can contain null bytes." msgstr "" -#: ../../c-api/unicode.rst:849 +#: ../../c-api/unicode.rst:905 msgid "" "If you need to encode a string to the current locale encoding, use :c:func:" "`PyUnicode_EncodeLocale`." msgstr "" -#: ../../c-api/unicode.rst:863 +#: ../../c-api/unicode.rst:919 msgid "wchar_t Support" msgstr "" -#: ../../c-api/unicode.rst:865 +#: ../../c-api/unicode.rst:921 msgid ":c:type:`wchar_t` support for platforms which support it:" msgstr "" -#: ../../c-api/unicode.rst:869 +#: ../../c-api/unicode.rst:925 msgid "" "Create a Unicode object from the :c:type:`wchar_t` buffer *wstr* of the " "given *size*. Passing ``-1`` as the *size* indicates that the function must " @@ -1102,7 +1242,7 @@ msgid "" "failure." msgstr "" -#: ../../c-api/unicode.rst:877 +#: ../../c-api/unicode.rst:933 msgid "" "Copy the Unicode object contents into the :c:type:`wchar_t` buffer *wstr*. " "At most *size* :c:type:`wchar_t` characters are copied (excluding a possibly " @@ -1110,13 +1250,13 @@ msgid "" "`wchar_t` characters copied or ``-1`` in case of an error." msgstr "" -#: ../../c-api/unicode.rst:882 +#: ../../c-api/unicode.rst:938 msgid "" "When *wstr* is ``NULL``, instead return the *size* that would be required to " "store all of *unicode* including a terminating null." msgstr "" -#: ../../c-api/unicode.rst:885 +#: ../../c-api/unicode.rst:941 msgid "" "Note that the resulting :c:expr:`wchar_t*` string may or may not be null-" "terminated. It is the responsibility of the caller to make sure that the :c:" @@ -1126,7 +1266,7 @@ msgid "" "most C functions." msgstr "" -#: ../../c-api/unicode.rst:895 +#: ../../c-api/unicode.rst:951 msgid "" "Convert the Unicode object to a wide character string. The output string " "always ends with a null character. If *size* is not ``NULL``, write the " @@ -1137,37 +1277,37 @@ msgid "" "`wchar_t*` string contains null characters a :exc:`ValueError` is raised." msgstr "" -#: ../../c-api/unicode.rst:903 +#: ../../c-api/unicode.rst:959 msgid "" "Returns a buffer allocated by :c:macro:`PyMem_New` (use :c:func:`PyMem_Free` " "to free it) on success. On error, returns ``NULL`` and *\\*size* is " "undefined. Raises a :exc:`MemoryError` if memory allocation is failed." msgstr "" -#: ../../c-api/unicode.rst:910 +#: ../../c-api/unicode.rst:966 msgid "" "Raises a :exc:`ValueError` if *size* is ``NULL`` and the :c:expr:`wchar_t*` " "string contains null characters." msgstr "" -#: ../../c-api/unicode.rst:918 +#: ../../c-api/unicode.rst:974 msgid "Built-in Codecs" msgstr "" -#: ../../c-api/unicode.rst:920 +#: ../../c-api/unicode.rst:976 msgid "" "Python provides a set of built-in codecs which are written in C for speed. " "All of these codecs are directly usable via the following functions." msgstr "" -#: ../../c-api/unicode.rst:923 +#: ../../c-api/unicode.rst:979 msgid "" "Many of the following APIs take two arguments encoding and errors, and they " "have the same semantics as the ones of the built-in :func:`str` string " "object constructor." msgstr "" -#: ../../c-api/unicode.rst:927 +#: ../../c-api/unicode.rst:983 msgid "" "Setting encoding to ``NULL`` causes the default encoding to be used which is " "UTF-8. The file system calls should use :c:func:`PyUnicode_FSConverter` for " @@ -1175,28 +1315,28 @@ msgid "" "handler` internally." msgstr "" -#: ../../c-api/unicode.rst:932 +#: ../../c-api/unicode.rst:988 msgid "" "Error handling is set by errors which may also be set to ``NULL`` meaning to " "use the default handling defined for the codec. Default error handling for " "all built-in codecs is \"strict\" (:exc:`ValueError` is raised)." msgstr "" -#: ../../c-api/unicode.rst:936 +#: ../../c-api/unicode.rst:992 msgid "" "The codecs all use a similar interface. Only deviations from the following " "generic ones are documented for simplicity." msgstr "" -#: ../../c-api/unicode.rst:941 +#: ../../c-api/unicode.rst:997 msgid "Generic Codecs" msgstr "" -#: ../../c-api/unicode.rst:943 +#: ../../c-api/unicode.rst:999 msgid "These are the generic codec APIs:" msgstr "" -#: ../../c-api/unicode.rst:949 +#: ../../c-api/unicode.rst:1005 msgid "" "Create a Unicode object by decoding *size* bytes of the encoded string " "*str*. *encoding* and *errors* have the same meaning as the parameters of " @@ -1205,7 +1345,7 @@ msgid "" "was raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:959 +#: ../../c-api/unicode.rst:1015 msgid "" "Encode a Unicode object and return the result as Python bytes object. " "*encoding* and *errors* have the same meaning as the parameters of the same " @@ -1214,21 +1354,21 @@ msgid "" "was raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:967 +#: ../../c-api/unicode.rst:1023 msgid "UTF-8 Codecs" msgstr "" -#: ../../c-api/unicode.rst:969 +#: ../../c-api/unicode.rst:1025 msgid "These are the UTF-8 codec APIs:" msgstr "" -#: ../../c-api/unicode.rst:974 +#: ../../c-api/unicode.rst:1030 msgid "" "Create a Unicode object by decoding *size* bytes of the UTF-8 encoded string " "*str*. Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:981 +#: ../../c-api/unicode.rst:1037 msgid "" "If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF8`. If " "*consumed* is not ``NULL``, trailing incomplete UTF-8 byte sequences will " @@ -1236,14 +1376,20 @@ msgid "" "of bytes that have been decoded will be stored in *consumed*." msgstr "" -#: ../../c-api/unicode.rst:989 +#: ../../c-api/unicode.rst:1045 msgid "" "Encode a Unicode object using UTF-8 and return the result as Python bytes " "object. Error handling is \"strict\". Return ``NULL`` if an exception was " "raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:996 +#: ../../c-api/unicode.rst:1049 ../../c-api/unicode.rst:1064 +msgid "" +"The function fails if the string contains surrogate code points (``U+D800`` " +"- ``U+DFFF``)." +msgstr "" + +#: ../../c-api/unicode.rst:1055 msgid "" "Return a pointer to the UTF-8 encoding of the Unicode object, and store the " "size of the encoded representation (in bytes) in *size*. The *size* " @@ -1252,13 +1398,13 @@ msgid "" "regardless of whether there are any other null code points." msgstr "" -#: ../../c-api/unicode.rst:1002 +#: ../../c-api/unicode.rst:1061 msgid "" "On error, set an exception, set *size* to ``-1`` (if it's not NULL) and " "return ``NULL``." msgstr "" -#: ../../c-api/unicode.rst:1005 +#: ../../c-api/unicode.rst:1067 msgid "" "This caches the UTF-8 representation of the string in the Unicode object, " "and subsequent calls will return a pointer to the same buffer. The caller " @@ -1267,40 +1413,57 @@ msgid "" "collected." msgstr "" -#: ../../c-api/unicode.rst:1012 ../../c-api/unicode.rst:1025 +#: ../../c-api/unicode.rst:1074 ../../c-api/unicode.rst:1096 msgid "The return type is now ``const char *`` rather of ``char *``." msgstr "" -#: ../../c-api/unicode.rst:1015 +#: ../../c-api/unicode.rst:1077 msgid "This function is a part of the :ref:`limited API `." msgstr "" -#: ../../c-api/unicode.rst:1021 +#: ../../c-api/unicode.rst:1083 msgid "As :c:func:`PyUnicode_AsUTF8AndSize`, but does not store the size." msgstr "" -#: ../../c-api/unicode.rst:1030 +#: ../../c-api/unicode.rst:1087 +msgid "" +"This function does not have any special behavior for `null characters " +"`_ embedded within *unicode*. " +"As a result, strings containing null characters will remain in the returned " +"string, which some C functions might interpret as the end of the string, " +"leading to truncation. If truncation is an issue, it is recommended to use :" +"c:func:`PyUnicode_AsUTF8AndSize` instead." +msgstr "" + +#: ../../c-api/unicode.rst:1101 msgid "UTF-32 Codecs" msgstr "" -#: ../../c-api/unicode.rst:1032 +#: ../../c-api/unicode.rst:1103 msgid "These are the UTF-32 codec APIs:" msgstr "" -#: ../../c-api/unicode.rst:1038 +#: ../../c-api/unicode.rst:1109 msgid "" "Decode *size* bytes from a UTF-32 encoded buffer string and return the " "corresponding Unicode object. *errors* (if non-``NULL``) defines the error " "handling. It defaults to \"strict\"." msgstr "" -#: ../../c-api/unicode.rst:1042 ../../c-api/unicode.rst:1092 +#: ../../c-api/unicode.rst:1113 ../../c-api/unicode.rst:1163 msgid "" "If *byteorder* is non-``NULL``, the decoder starts decoding using the given " "byte order::" msgstr "" -#: ../../c-api/unicode.rst:1049 +#: ../../c-api/unicode.rst:1116 ../../c-api/unicode.rst:1166 +msgid "" +"*byteorder == -1: little endian\n" +"*byteorder == 0: native order\n" +"*byteorder == 1: big endian" +msgstr "" + +#: ../../c-api/unicode.rst:1120 msgid "" "If ``*byteorder`` is zero, and the first four bytes of the input data are a " "byte order mark (BOM), the decoder switches to this byte order and the BOM " @@ -1308,21 +1471,21 @@ msgid "" "``-1`` or ``1``, any byte order mark is copied to the output." msgstr "" -#: ../../c-api/unicode.rst:1054 +#: ../../c-api/unicode.rst:1125 msgid "" "After completion, *\\*byteorder* is set to the current byte order at the end " "of input data." msgstr "" -#: ../../c-api/unicode.rst:1057 ../../c-api/unicode.rst:1108 +#: ../../c-api/unicode.rst:1128 ../../c-api/unicode.rst:1179 msgid "If *byteorder* is ``NULL``, the codec starts in native order mode." msgstr "" -#: ../../c-api/unicode.rst:1059 ../../c-api/unicode.rst:1110 +#: ../../c-api/unicode.rst:1130 ../../c-api/unicode.rst:1181 msgid "Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:1065 +#: ../../c-api/unicode.rst:1136 msgid "" "If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF32`. If " "*consumed* is not ``NULL``, :c:func:`PyUnicode_DecodeUTF32Stateful` will not " @@ -1331,29 +1494,29 @@ msgid "" "number of bytes that have been decoded will be stored in *consumed*." msgstr "" -#: ../../c-api/unicode.rst:1074 +#: ../../c-api/unicode.rst:1145 msgid "" "Return a Python byte string using the UTF-32 encoding in native byte order. " "The string always starts with a BOM mark. Error handling is \"strict\". " "Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:1080 +#: ../../c-api/unicode.rst:1151 msgid "UTF-16 Codecs" msgstr "" -#: ../../c-api/unicode.rst:1082 +#: ../../c-api/unicode.rst:1153 msgid "These are the UTF-16 codec APIs:" msgstr "" -#: ../../c-api/unicode.rst:1088 +#: ../../c-api/unicode.rst:1159 msgid "" "Decode *size* bytes from a UTF-16 encoded buffer string and return the " "corresponding Unicode object. *errors* (if non-``NULL``) defines the error " "handling. It defaults to \"strict\"." msgstr "" -#: ../../c-api/unicode.rst:1099 +#: ../../c-api/unicode.rst:1170 msgid "" "If ``*byteorder`` is zero, and the first two bytes of the input data are a " "byte order mark (BOM), the decoder switches to this byte order and the BOM " @@ -1362,13 +1525,13 @@ msgid "" "result in either a ``\\ufeff`` or a ``\\ufffe`` character)." msgstr "" -#: ../../c-api/unicode.rst:1105 +#: ../../c-api/unicode.rst:1176 msgid "" "After completion, ``*byteorder`` is set to the current byte order at the end " "of input data." msgstr "" -#: ../../c-api/unicode.rst:1116 +#: ../../c-api/unicode.rst:1187 msgid "" "If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF16`. If " "*consumed* is not ``NULL``, :c:func:`PyUnicode_DecodeUTF16Stateful` will not " @@ -1378,28 +1541,28 @@ msgid "" "*consumed*." msgstr "" -#: ../../c-api/unicode.rst:1125 +#: ../../c-api/unicode.rst:1196 msgid "" "Return a Python byte string using the UTF-16 encoding in native byte order. " "The string always starts with a BOM mark. Error handling is \"strict\". " "Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:1131 +#: ../../c-api/unicode.rst:1202 msgid "UTF-7 Codecs" msgstr "" -#: ../../c-api/unicode.rst:1133 +#: ../../c-api/unicode.rst:1204 msgid "These are the UTF-7 codec APIs:" msgstr "" -#: ../../c-api/unicode.rst:1138 +#: ../../c-api/unicode.rst:1209 msgid "" "Create a Unicode object by decoding *size* bytes of the UTF-7 encoded string " "*str*. Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:1145 +#: ../../c-api/unicode.rst:1216 msgid "" "If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF7`. If " "*consumed* is not ``NULL``, trailing incomplete UTF-7 base-64 sections will " @@ -1407,101 +1570,101 @@ msgid "" "of bytes that have been decoded will be stored in *consumed*." msgstr "" -#: ../../c-api/unicode.rst:1152 +#: ../../c-api/unicode.rst:1223 msgid "Unicode-Escape Codecs" msgstr "" -#: ../../c-api/unicode.rst:1154 +#: ../../c-api/unicode.rst:1225 msgid "These are the \"Unicode Escape\" codec APIs:" msgstr "" -#: ../../c-api/unicode.rst:1160 +#: ../../c-api/unicode.rst:1231 msgid "" "Create a Unicode object by decoding *size* bytes of the Unicode-Escape " "encoded string *str*. Return ``NULL`` if an exception was raised by the " "codec." msgstr "" -#: ../../c-api/unicode.rst:1166 +#: ../../c-api/unicode.rst:1237 msgid "" "Encode a Unicode object using Unicode-Escape and return the result as a " "bytes object. Error handling is \"strict\". Return ``NULL`` if an " "exception was raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:1172 +#: ../../c-api/unicode.rst:1243 msgid "Raw-Unicode-Escape Codecs" msgstr "" -#: ../../c-api/unicode.rst:1174 +#: ../../c-api/unicode.rst:1245 msgid "These are the \"Raw Unicode Escape\" codec APIs:" msgstr "" -#: ../../c-api/unicode.rst:1180 +#: ../../c-api/unicode.rst:1251 msgid "" "Create a Unicode object by decoding *size* bytes of the Raw-Unicode-Escape " "encoded string *str*. Return ``NULL`` if an exception was raised by the " "codec." msgstr "" -#: ../../c-api/unicode.rst:1186 +#: ../../c-api/unicode.rst:1257 msgid "" "Encode a Unicode object using Raw-Unicode-Escape and return the result as a " "bytes object. Error handling is \"strict\". Return ``NULL`` if an " "exception was raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:1192 +#: ../../c-api/unicode.rst:1263 msgid "Latin-1 Codecs" msgstr "" -#: ../../c-api/unicode.rst:1194 +#: ../../c-api/unicode.rst:1265 msgid "" "These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 " "Unicode ordinals and only these are accepted by the codecs during encoding." msgstr "" -#: ../../c-api/unicode.rst:1200 +#: ../../c-api/unicode.rst:1271 msgid "" "Create a Unicode object by decoding *size* bytes of the Latin-1 encoded " "string *str*. Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:1206 +#: ../../c-api/unicode.rst:1277 msgid "" "Encode a Unicode object using Latin-1 and return the result as Python bytes " "object. Error handling is \"strict\". Return ``NULL`` if an exception was " "raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:1212 +#: ../../c-api/unicode.rst:1283 msgid "ASCII Codecs" msgstr "" -#: ../../c-api/unicode.rst:1214 +#: ../../c-api/unicode.rst:1285 msgid "" "These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All " "other codes generate errors." msgstr "" -#: ../../c-api/unicode.rst:1220 +#: ../../c-api/unicode.rst:1291 msgid "" "Create a Unicode object by decoding *size* bytes of the ASCII encoded string " "*str*. Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:1226 +#: ../../c-api/unicode.rst:1297 msgid "" "Encode a Unicode object using ASCII and return the result as Python bytes " "object. Error handling is \"strict\". Return ``NULL`` if an exception was " "raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:1232 +#: ../../c-api/unicode.rst:1303 msgid "Character Map Codecs" msgstr "" -#: ../../c-api/unicode.rst:1234 +#: ../../c-api/unicode.rst:1305 msgid "" "This codec is special in that it can be used to implement many different " "codecs (and this is in fact what was done to obtain most of the standard " @@ -1511,18 +1674,18 @@ msgid "" "sequences work well." msgstr "" -#: ../../c-api/unicode.rst:1240 +#: ../../c-api/unicode.rst:1311 msgid "These are the mapping codec APIs:" msgstr "" -#: ../../c-api/unicode.rst:1245 +#: ../../c-api/unicode.rst:1316 msgid "" "Create a Unicode object by decoding *size* bytes of the encoded string *str* " "using the given *mapping* object. Return ``NULL`` if an exception was " "raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:1249 +#: ../../c-api/unicode.rst:1320 msgid "" "If *mapping* is ``NULL``, Latin-1 decoding will be applied. Else *mapping* " "must map bytes ordinals (integers in the range from 0 to 255) to Unicode " @@ -1532,14 +1695,14 @@ msgid "" "treated as undefined mappings and cause an error." msgstr "" -#: ../../c-api/unicode.rst:1260 +#: ../../c-api/unicode.rst:1331 msgid "" "Encode a Unicode object using the given *mapping* object and return the " "result as a bytes object. Error handling is \"strict\". Return ``NULL`` if " "an exception was raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:1264 +#: ../../c-api/unicode.rst:1335 msgid "" "The *mapping* object must map Unicode ordinal integers to bytes objects, " "integers in the range from 0 to 255 or ``None``. Unmapped character " @@ -1547,41 +1710,41 @@ msgid "" "``None`` are treated as \"undefined mapping\" and cause an error." msgstr "" -#: ../../c-api/unicode.rst:1270 +#: ../../c-api/unicode.rst:1341 msgid "The following codec API is special in that maps Unicode to Unicode." msgstr "" -#: ../../c-api/unicode.rst:1274 +#: ../../c-api/unicode.rst:1345 msgid "" "Translate a string by applying a character mapping table to it and return " "the resulting Unicode object. Return ``NULL`` if an exception was raised by " "the codec." msgstr "" -#: ../../c-api/unicode.rst:1278 +#: ../../c-api/unicode.rst:1349 msgid "" "The mapping table must map Unicode ordinal integers to Unicode ordinal " "integers or ``None`` (causing deletion of the character)." msgstr "" -#: ../../c-api/unicode.rst:1281 +#: ../../c-api/unicode.rst:1352 msgid "" "Mapping tables need only provide the :meth:`~object.__getitem__` interface; " "dictionaries and sequences work well. Unmapped character ordinals (ones " "which cause a :exc:`LookupError`) are left untouched and are copied as-is." msgstr "" -#: ../../c-api/unicode.rst:1285 +#: ../../c-api/unicode.rst:1356 msgid "" "*errors* has the usual meaning for codecs. It may be ``NULL`` which " "indicates to use the default error handling." msgstr "" -#: ../../c-api/unicode.rst:1290 +#: ../../c-api/unicode.rst:1361 msgid "MBCS codecs for Windows" msgstr "" -#: ../../c-api/unicode.rst:1292 +#: ../../c-api/unicode.rst:1363 msgid "" "These are the MBCS codec APIs. They are currently only available on Windows " "and use the Win32 MBCS converters to implement the conversions. Note that " @@ -1589,13 +1752,13 @@ msgid "" "is defined by the user settings on the machine running the codec." msgstr "" -#: ../../c-api/unicode.rst:1299 +#: ../../c-api/unicode.rst:1370 msgid "" "Create a Unicode object by decoding *size* bytes of the MBCS encoded string " "*str*. Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:1306 +#: ../../c-api/unicode.rst:1377 msgid "" "If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeMBCS`. If " "*consumed* is not ``NULL``, :c:func:`PyUnicode_DecodeMBCSStateful` will not " @@ -1603,44 +1766,50 @@ msgid "" "will be stored in *consumed*." msgstr "" -#: ../../c-api/unicode.rst:1314 +#: ../../c-api/unicode.rst:1386 +msgid "" +"Similar to :c:func:`PyUnicode_DecodeMBCSStateful`, except uses the code page " +"specified by *code_page*." +msgstr "" + +#: ../../c-api/unicode.rst:1392 msgid "" "Encode a Unicode object using MBCS and return the result as Python bytes " "object. Error handling is \"strict\". Return ``NULL`` if an exception was " "raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:1321 +#: ../../c-api/unicode.rst:1399 msgid "" "Encode the Unicode object using the specified code page and return a Python " "bytes object. Return ``NULL`` if an exception was raised by the codec. Use :" "c:macro:`!CP_ACP` code page to get the MBCS encoder." msgstr "" -#: ../../c-api/unicode.rst:1329 +#: ../../c-api/unicode.rst:1407 msgid "Methods & Slots" msgstr "" -#: ../../c-api/unicode.rst:1335 +#: ../../c-api/unicode.rst:1413 msgid "Methods and Slot Functions" msgstr "" -#: ../../c-api/unicode.rst:1337 +#: ../../c-api/unicode.rst:1415 msgid "" "The following APIs are capable of handling Unicode objects and strings on " "input (we refer to them as strings in the descriptions) and return Unicode " "objects or integers as appropriate." msgstr "" -#: ../../c-api/unicode.rst:1341 +#: ../../c-api/unicode.rst:1419 msgid "They all return ``NULL`` or ``-1`` if an exception occurs." msgstr "" -#: ../../c-api/unicode.rst:1346 +#: ../../c-api/unicode.rst:1424 msgid "Concat two strings giving a new Unicode string." msgstr "" -#: ../../c-api/unicode.rst:1351 +#: ../../c-api/unicode.rst:1429 msgid "" "Split a string giving a list of Unicode strings. If *sep* is ``NULL``, " "splitting will be done at all whitespace substrings. Otherwise, splits " @@ -1649,27 +1818,73 @@ msgid "" "list." msgstr "" -#: ../../c-api/unicode.rst:1359 +#: ../../c-api/unicode.rst:1434 ../../c-api/unicode.rst:1444 +#: ../../c-api/unicode.rst:1465 ../../c-api/unicode.rst:1478 +msgid "On error, return ``NULL`` with an exception set." +msgstr "" + +#: ../../c-api/unicode.rst:1436 +msgid "Equivalent to :py:meth:`str.split`." +msgstr "" + +#: ../../c-api/unicode.rst:1441 +msgid "" +"Similar to :c:func:`PyUnicode_Split`, but splitting will be done beginning " +"at the end of the string." +msgstr "" + +#: ../../c-api/unicode.rst:1446 +msgid "Equivalent to :py:meth:`str.rsplit`." +msgstr "" + +#: ../../c-api/unicode.rst:1451 msgid "" "Split a Unicode string at line breaks, returning a list of Unicode strings. " "CRLF is considered to be one line break. If *keepends* is ``0``, the Line " "break characters are not included in the resulting strings." msgstr "" -#: ../../c-api/unicode.rst:1366 +#: ../../c-api/unicode.rst:1458 +msgid "" +"Split a Unicode string at the first occurrence of *sep*, and return a 3-" +"tuple containing the part before the separator, the separator itself, and " +"the part after the separator. If the separator is not found, return a 3-" +"tuple containing the string itself, followed by two empty strings." +msgstr "" + +#: ../../c-api/unicode.rst:1463 ../../c-api/unicode.rst:1476 +msgid "*sep* must not be empty." +msgstr "" + +#: ../../c-api/unicode.rst:1467 +msgid "Equivalent to :py:meth:`str.partition`." +msgstr "" + +#: ../../c-api/unicode.rst:1472 +msgid "" +"Similar to :c:func:`PyUnicode_Partition`, but split a Unicode string at the " +"last occurrence of *sep*. If the separator is not found, return a 3-tuple " +"containing two empty strings, followed by the string itself." +msgstr "" + +#: ../../c-api/unicode.rst:1480 +msgid "Equivalent to :py:meth:`str.rpartition`." +msgstr "" + +#: ../../c-api/unicode.rst:1485 msgid "" "Join a sequence of strings using the given *separator* and return the " "resulting Unicode string." msgstr "" -#: ../../c-api/unicode.rst:1373 +#: ../../c-api/unicode.rst:1492 msgid "" "Return ``1`` if *substr* matches ``unicode[start:end]`` at the given tail " "end (*direction* == ``-1`` means to do a prefix match, *direction* == ``1`` " "a suffix match), ``0`` otherwise. Return ``-1`` if an error occurred." msgstr "" -#: ../../c-api/unicode.rst:1381 +#: ../../c-api/unicode.rst:1500 msgid "" "Return the first position of *substr* in ``unicode[start:end]`` using the " "given *direction* (*direction* == ``1`` means to do a forward search, " @@ -1678,7 +1893,7 @@ msgid "" "``-2`` indicates that an error occurred and an exception has been set." msgstr "" -#: ../../c-api/unicode.rst:1391 +#: ../../c-api/unicode.rst:1510 msgid "" "Return the first position of the character *ch* in ``unicode[start:end]`` " "using the given *direction* (*direction* == ``1`` means to do a forward " @@ -1688,56 +1903,57 @@ msgid "" "set." msgstr "" -#: ../../c-api/unicode.rst:1399 +#: ../../c-api/unicode.rst:1518 msgid "" "*start* and *end* are now adjusted to behave like ``unicode[start:end]``." msgstr "" -#: ../../c-api/unicode.rst:1406 +#: ../../c-api/unicode.rst:1525 msgid "" "Return the number of non-overlapping occurrences of *substr* in " "``unicode[start:end]``. Return ``-1`` if an error occurred." msgstr "" -#: ../../c-api/unicode.rst:1413 +#: ../../c-api/unicode.rst:1532 msgid "" "Replace at most *maxcount* occurrences of *substr* in *unicode* with " "*replstr* and return the resulting Unicode object. *maxcount* == ``-1`` " "means replace all occurrences." msgstr "" -#: ../../c-api/unicode.rst:1420 +#: ../../c-api/unicode.rst:1539 msgid "" "Compare two strings and return ``-1``, ``0``, ``1`` for less than, equal, " "and greater than, respectively." msgstr "" -#: ../../c-api/unicode.rst:1423 +#: ../../c-api/unicode.rst:1542 msgid "" "This function returns ``-1`` upon failure, so one should call :c:func:" "`PyErr_Occurred` to check for errors." msgstr "" -#: ../../c-api/unicode.rst:1429 +#: ../../c-api/unicode.rst:1548 msgid "" "Compare a Unicode object with a char buffer which is interpreted as being " "UTF-8 or ASCII encoded and return true (``1``) if they are equal, or false " -"(``0``) otherwise. If the Unicode object contains surrogate characters or " -"the C string is not valid UTF-8, false (``0``) is returned." +"(``0``) otherwise. If the Unicode object contains surrogate code points " +"(``U+D800`` - ``U+DFFF``) or the C string is not valid UTF-8, false (``0``) " +"is returned." msgstr "" -#: ../../c-api/unicode.rst:1435 ../../c-api/unicode.rst:1456 +#: ../../c-api/unicode.rst:1555 ../../c-api/unicode.rst:1576 msgid "This function does not raise exceptions." msgstr "" -#: ../../c-api/unicode.rst:1442 +#: ../../c-api/unicode.rst:1562 msgid "" "Similar to :c:func:`PyUnicode_EqualToUTF8AndSize`, but compute *string* " "length using :c:func:`!strlen`. If the Unicode object contains null " "characters, false (``0``) is returned." msgstr "" -#: ../../c-api/unicode.rst:1451 +#: ../../c-api/unicode.rst:1571 msgid "" "Compare a Unicode object, *unicode*, with *string* and return ``-1``, ``0``, " "``1`` for less than, equal, and greater than, respectively. It is best to " @@ -1745,47 +1961,47 @@ msgid "" "string as ISO-8859-1 if it contains non-ASCII characters." msgstr "" -#: ../../c-api/unicode.rst:1461 +#: ../../c-api/unicode.rst:1581 msgid "Rich compare two Unicode strings and return one of the following:" msgstr "" -#: ../../c-api/unicode.rst:1463 +#: ../../c-api/unicode.rst:1583 msgid "``NULL`` in case an exception was raised" msgstr "" -#: ../../c-api/unicode.rst:1464 +#: ../../c-api/unicode.rst:1584 msgid ":c:data:`Py_True` or :c:data:`Py_False` for successful comparisons" msgstr "" -#: ../../c-api/unicode.rst:1465 +#: ../../c-api/unicode.rst:1585 msgid ":c:data:`Py_NotImplemented` in case the type combination is unknown" msgstr "" -#: ../../c-api/unicode.rst:1467 +#: ../../c-api/unicode.rst:1587 msgid "" "Possible values for *op* are :c:macro:`Py_GT`, :c:macro:`Py_GE`, :c:macro:" "`Py_EQ`, :c:macro:`Py_NE`, :c:macro:`Py_LT`, and :c:macro:`Py_LE`." msgstr "" -#: ../../c-api/unicode.rst:1473 +#: ../../c-api/unicode.rst:1593 msgid "" "Return a new string object from *format* and *args*; this is analogous to " "``format % args``." msgstr "" -#: ../../c-api/unicode.rst:1479 +#: ../../c-api/unicode.rst:1599 msgid "" "Check whether *substr* is contained in *unicode* and return true or false " "accordingly." msgstr "" -#: ../../c-api/unicode.rst:1482 +#: ../../c-api/unicode.rst:1602 msgid "" "*substr* has to coerce to a one element Unicode string. ``-1`` is returned " "if there was an error." msgstr "" -#: ../../c-api/unicode.rst:1488 +#: ../../c-api/unicode.rst:1608 msgid "" "Intern the argument :c:expr:`*p_unicode` in place. The argument must be the " "address of a pointer variable pointing to a Python Unicode string object. " @@ -1796,7 +2012,7 @@ msgid "" "interns it." msgstr "" -#: ../../c-api/unicode.rst:1495 +#: ../../c-api/unicode.rst:1615 msgid "" "(Clarification: even though there is a lot of talk about references, think " "of this function as reference-neutral. You must own the object you pass in; " @@ -1804,39 +2020,39 @@ msgid "" "the result.)" msgstr "" -#: ../../c-api/unicode.rst:1500 +#: ../../c-api/unicode.rst:1620 msgid "" "This function never raises an exception. On error, it leaves its argument " "unchanged without interning it." msgstr "" -#: ../../c-api/unicode.rst:1503 +#: ../../c-api/unicode.rst:1623 msgid "" "Instances of subclasses of :py:class:`str` may not be interned, that is, :c:" "expr:`PyUnicode_CheckExact(*p_unicode)` must be true. If it is not, then -- " "as with any other error -- the argument is left unchanged." msgstr "" -#: ../../c-api/unicode.rst:1507 +#: ../../c-api/unicode.rst:1627 msgid "" "Note that interned strings are not “immortal”. You must keep a reference to " "the result to benefit from interning." msgstr "" -#: ../../c-api/unicode.rst:1513 +#: ../../c-api/unicode.rst:1633 msgid "" "A combination of :c:func:`PyUnicode_FromString` and :c:func:" "`PyUnicode_InternInPlace`, meant for statically allocated strings." msgstr "" -#: ../../c-api/unicode.rst:1516 +#: ../../c-api/unicode.rst:1636 msgid "" "Return a new (\"owned\") reference to either a new Unicode string object " "that has been interned, or an earlier interned string object with the same " "value." msgstr "" -#: ../../c-api/unicode.rst:1520 +#: ../../c-api/unicode.rst:1640 msgid "" "Python may keep a reference to the result, or make it :term:`immortal`, " "preventing it from being garbage-collected promptly. For interning an " @@ -1845,6 +2061,6 @@ msgid "" "`PyUnicode_InternInPlace` directly." msgstr "" -#: ../../c-api/unicode.rst:1528 +#: ../../c-api/unicode.rst:1648 msgid "Strings interned this way are made :term:`immortal`." msgstr "" diff --git a/c-api/utilities.po b/c-api/utilities.po index 1de7d47e7..c4849684e 100644 --- a/c-api/utilities.po +++ b/c-api/utilities.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Claudio Rogerio Carvalho Filho , " -"2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/c-api/veryhigh.po b/c-api/veryhigh.po index 9940ee441..0a035a432 100644 --- a/c-api/veryhigh.po +++ b/c-api/veryhigh.po @@ -1,32 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-24 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../c-api/veryhigh.rst:8 msgid "The Very High Level Layer" -msgstr "A camada de Mais Alto Nível" +msgstr "A camada de nível muito alto" #: ../../c-api/veryhigh.rst:10 msgid "" @@ -34,6 +33,9 @@ msgid "" "in a file or a buffer, but they will not let you interact in a more detailed " "way with the interpreter." msgstr "" +"As funções neste capítulo permitirão que você execute um código-fonte Python " +"fornecido em um arquivo ou buffer, mas não permitirão que você interaja de " +"forma mais detalhada com o interpretador." #: ../../c-api/veryhigh.rst:14 msgid "" @@ -42,6 +44,10 @@ msgid "" "`Py_file_input`, and :c:data:`Py_single_input`. These are described " "following the functions which accept them as parameters." msgstr "" +"Várias dessas funções aceitam um símbolo de início da gramática como " +"parâmetro. Os símbolos de início disponíveis são :c:data:`Py_eval_input`, :c:" +"data:`Py_file_input` e :c:data:`Py_single_input`. Eles são descritos " +"seguindo as funções que os aceitam como parâmetros." #: ../../c-api/veryhigh.rst:19 msgid "" @@ -54,50 +60,41 @@ msgid "" "it is certain that they were created by the same library that the Python " "runtime is using." msgstr "" +"Note também que várias dessas funções aceitam parâmetros :c:expr:`FILE*`. Um " +"problema específico que precisa ser tratado com cuidado é que a estrutura :c:" +"type:`FILE` para diferentes bibliotecas C pode ser diferente e incompatível. " +"No Windows (pelo menos), é possível que extensões vinculadas dinamicamente " +"usem bibliotecas diferentes, então deve-se tomar cuidado para que os " +"parâmetros :c:expr:`FILE*` sejam passados para essas funções somente se for " +"certo que elas foram criadas pela mesma biblioteca que o tempo de execução " +"do Python está usando." #: ../../c-api/veryhigh.rst:30 msgid "" -"The main program for the standard interpreter. This is made available for " -"programs which embed Python. The *argc* and *argv* parameters should be " -"prepared exactly as those which are passed to a C program's :c:func:`main` " -"function (converted to wchar_t according to the user's locale). It is " -"important to note that the argument list may be modified (but the contents " -"of the strings pointed to by the argument list are not). The return value " -"will be ``0`` if the interpreter exits normally (i.e., without an " -"exception), ``1`` if the interpreter exits due to an exception, or ``2`` if " -"the parameter list does not represent a valid Python command line." -msgstr "" - -#: ../../c-api/veryhigh.rst:40 -msgid "" -"Note that if an otherwise unhandled :exc:`SystemExit` is raised, this " -"function will not return ``1``, but exit the process, as long as :c:member:" -"`PyConfig.inspect` is zero." -msgstr "" - -#: ../../c-api/veryhigh.rst:47 -msgid "Similar to :c:func:`Py_Main` but *argv* is an array of bytes strings." -msgstr "" - -#: ../../c-api/veryhigh.rst:54 -msgid "" "This is a simplified interface to :c:func:`PyRun_AnyFileExFlags` below, " "leaving *closeit* set to ``0`` and *flags* set to ``NULL``." msgstr "" +"Esta é uma interface simplificada para :c:func:`PyRun_AnyFileExFlags` " +"abaixo, deixando *closeit* definido como ``0`` e *flags* definido como " +"``NULL``." -#: ../../c-api/veryhigh.rst:60 +#: ../../c-api/veryhigh.rst:36 msgid "" "This is a simplified interface to :c:func:`PyRun_AnyFileExFlags` below, " "leaving the *closeit* argument set to ``0``." msgstr "" +"Esta é uma interface simplificada para :c:func:`PyRun_AnyFileExFlags` " +"abaixo, deixando o argumento *closeit* definido como ``0``." -#: ../../c-api/veryhigh.rst:66 +#: ../../c-api/veryhigh.rst:42 msgid "" "This is a simplified interface to :c:func:`PyRun_AnyFileExFlags` below, " "leaving the *flags* argument set to ``NULL``." msgstr "" +"Esta é uma interface simplificada para :c:func:`PyRun_AnyFileExFlags` " +"abaixo, deixando o argumento *flags* definido como ``NULL``." -#: ../../c-api/veryhigh.rst:72 +#: ../../c-api/veryhigh.rst:48 msgid "" "If *fp* refers to a file associated with an interactive device (console or " "terminal input or Unix pseudo-terminal), return the value of :c:func:" @@ -107,14 +104,25 @@ msgid "" "uses ``\"???\"`` as the filename. If *closeit* is true, the file is closed " "before ``PyRun_SimpleFileExFlags()`` returns." msgstr "" +"Se *fp* se referir a um arquivo associado a um dispositivo interativo " +"(entrada de console ou terminal ou pseudo-terminal Unix), retorna o valor " +"de :c:func:`PyRun_InteractiveLoop`, caso contrário, retorna o resultado de :" +"c:func:`PyRun_SimpleFile`. *filename* é decodificado da codificação do " +"sistema de arquivos (:func:`sys.getfilesystemencoding`). Se *filename* for " +"``NULL``, esta função usa ``\"???\"`` como o nome do arquivo. Se *closeit* " +"for verdadeiro, o arquivo será fechado antes de " +"``PyRun_SimpleFileExFlags()`` retornar." -#: ../../c-api/veryhigh.rst:84 +#: ../../c-api/veryhigh.rst:60 msgid "" "This is a simplified interface to :c:func:`PyRun_SimpleStringFlags` below, " "leaving the :c:struct:`PyCompilerFlags`\\* argument set to ``NULL``." msgstr "" +"Esta é uma interface simplificada para :c:func:`PyRun_SimpleStringFlags` " +"abaixo, deixando o argumento :c:struct:`PyCompilerFlags`\\* definido como " +"``NULL``." -#: ../../c-api/veryhigh.rst:90 +#: ../../c-api/veryhigh.rst:66 msgid "" "Executes the Python source code from *command* in the :mod:`__main__` module " "according to the *flags* argument. If :mod:`__main__` does not already " @@ -122,27 +130,40 @@ msgid "" "was raised. If there was an error, there is no way to get the exception " "information. For the meaning of *flags*, see below." msgstr "" +"Executa o código-fonte Python de *command* no módulo :mod:`__main__` de " +"acordo com o argumento *flags*. Se :mod:`__main__` ainda não existir, ele " +"será criado. Retorna ``0`` em caso de sucesso ou ``-1`` se uma exceção foi " +"gerada. Se houve um erro, não há como obter as informações da exceção. Para " +"o significado de *flags*, veja abaixo." -#: ../../c-api/veryhigh.rst:96 +#: ../../c-api/veryhigh.rst:72 msgid "" "Note that if an otherwise unhandled :exc:`SystemExit` is raised, this " "function will not return ``-1``, but exit the process, as long as :c:member:" "`PyConfig.inspect` is zero." msgstr "" +"Observe que se uma exceção :exc:`SystemExit` não tratada for levantada, esta " +"função não retornará ``-1``, mas sairá do processo, desde que :c:member:" +"`PyConfig.inspect` seja zero." -#: ../../c-api/veryhigh.rst:103 +#: ../../c-api/veryhigh.rst:79 msgid "" "This is a simplified interface to :c:func:`PyRun_SimpleFileExFlags` below, " "leaving *closeit* set to ``0`` and *flags* set to ``NULL``." msgstr "" +"Esta é uma interface simplificada para :c:func:`PyRun_SimpleFileExFlags` " +"abaixo, deixando *closeit* definido como ``0`` e *flags* definido como " +"``NULL``." -#: ../../c-api/veryhigh.rst:109 +#: ../../c-api/veryhigh.rst:85 msgid "" "This is a simplified interface to :c:func:`PyRun_SimpleFileExFlags` below, " "leaving *flags* set to ``NULL``." msgstr "" +"Esta é uma interface simplificada para :c:func:`PyRun_SimpleFileExFlags` " +"abaixo, deixando o *flags* definido como ``NULL``." -#: ../../c-api/veryhigh.rst:115 +#: ../../c-api/veryhigh.rst:91 msgid "" "Similar to :c:func:`PyRun_SimpleStringFlags`, but the Python source code is " "read from *fp* instead of an in-memory string. *filename* should be the name " @@ -150,29 +171,43 @@ msgid "" "handler`. If *closeit* is true, the file is closed before " "``PyRun_SimpleFileExFlags()`` returns." msgstr "" +"Semelhante a :c:func:`PyRun_SimpleStringFlags`, mas o código-fonte Python é " +"lido de *fp* em vez de uma string na memória. *filename* deve ser o nome do " +"arquivo, ele é decodificado a partir do :term:`tratador de erros e " +"codificação do sistema de arquivos`. Se *closeit* for true, o arquivo será " +"fechado antes que ``PyRun_SimpleFileExFlags()`` retorne." -#: ../../c-api/veryhigh.rst:122 +#: ../../c-api/veryhigh.rst:98 msgid "" "On Windows, *fp* should be opened as binary mode (e.g. ``fopen(filename, " "\"rb\")``). Otherwise, Python may not handle script file with LF line ending " "correctly." msgstr "" +"No Windows, *fp* deve ser aberto como modo binário (por exemplo, " +"``fopen(filename, \"rb\")``). Caso contrário, o Python pode não manipular " +"corretamente o arquivo de script com final de linha LF." -#: ../../c-api/veryhigh.rst:128 +#: ../../c-api/veryhigh.rst:104 msgid "" "This is a simplified interface to :c:func:`PyRun_InteractiveOneFlags` below, " "leaving *flags* set to ``NULL``." msgstr "" +"Esta é uma interface simplificada para :c:func:`PyRun_InteractiveOneFlags` " +"abaixo, deixando *flags* definido como ``NULL``." -#: ../../c-api/veryhigh.rst:134 +#: ../../c-api/veryhigh.rst:110 msgid "" "Read and execute a single statement from a file associated with an " "interactive device according to the *flags* argument. The user will be " "prompted using ``sys.ps1`` and ``sys.ps2``. *filename* is decoded from the :" "term:`filesystem encoding and error handler`." msgstr "" +"Lê e executa uma única instrução de um arquivo associado a um dispositivo " +"interativo de acordo com o argumento *flags*. O usuário será solicitado " +"usando ``sys.ps1`` e ``sys.ps2``. *filename* é decodificado a partir do :" +"term:`tratador de erros e codificação do sistema de arquivos`." -#: ../../c-api/veryhigh.rst:139 +#: ../../c-api/veryhigh.rst:115 msgid "" "Returns ``0`` when the input was executed successfully, ``-1`` if there was " "an exception, or an error code from the :file:`errcode.h` include file " @@ -180,22 +215,34 @@ msgid "" "`errcode.h` is not included by :file:`Python.h`, so must be included " "specifically if needed.)" msgstr "" +"Retorna ``0`` quando a entrada foi executada com sucesso, ``-1`` se houve " +"uma exceção ou um código de erro do arquivo de inclusão :file:`errcode.h` " +"distribuído como parte do Python se houve um erro de análise. (Observe que :" +"file:`errcode.h` não é incluído por :file:`Python.h`, então deve ser " +"incluído especificamente se necessário.)" -#: ../../c-api/veryhigh.rst:148 +#: ../../c-api/veryhigh.rst:124 msgid "" "This is a simplified interface to :c:func:`PyRun_InteractiveLoopFlags` " "below, leaving *flags* set to ``NULL``." msgstr "" +"Esta é uma interface simplificada para :c:func:`PyRun_InteractiveLoopFlags` " +"abaixo, deixando *flags* definido como ``NULL``." -#: ../../c-api/veryhigh.rst:154 +#: ../../c-api/veryhigh.rst:130 msgid "" "Read and execute statements from a file associated with an interactive " "device until EOF is reached. The user will be prompted using ``sys.ps1`` " "and ``sys.ps2``. *filename* is decoded from the :term:`filesystem encoding " "and error handler`. Returns ``0`` at EOF or a negative number upon failure." msgstr "" +"Lê e executa instruções de um arquivo associado a um dispositivo interativo " +"até que o EOF seja atingido. O usuário será consultado usando ``sys.ps1`` e " +"``sys.ps2``. *filename* é decodificado a partir do :term:`tratador de erros " +"e codificação do sistema de arquivos`. Retorna ``0`` no EOF ou um número " +"negativo em caso de falha." -#: ../../c-api/veryhigh.rst:162 +#: ../../c-api/veryhigh.rst:138 msgid "" "Can be set to point to a function with the prototype ``int func(void)``. " "The function will be called when Python's interpreter prompt is about to " @@ -204,14 +251,22 @@ msgid "" "prompt with other event loops, as done in the :file:`Modules/_tkinter.c` in " "the Python source code." msgstr "" +"Pode ser definido para apontar para uma função com o protótipo ``int " +"func(void)``. A função será chamada quando o prompt do interpretador do " +"Python estiver prestes a ficar ocioso e aguardar a entrada do usuário no " +"terminal. O valor de retorno é ignorado. A substituição deste hook pode ser " +"usada para integrar o prompt do interpretador com outros laços de eventos, " +"como feito em :file:`Modules/_tkinter.c` no código-fonte do Python." -#: ../../c-api/veryhigh.rst:170 ../../c-api/veryhigh.rst:194 +#: ../../c-api/veryhigh.rst:146 ../../c-api/veryhigh.rst:170 msgid "" "This function is only called from the :ref:`main interpreter `." msgstr "" +"Esta função só é chamada pelo :ref:`interpretador principal `." -#: ../../c-api/veryhigh.rst:177 +#: ../../c-api/veryhigh.rst:153 msgid "" "Can be set to point to a function with the prototype ``char *func(FILE " "*stdin, FILE *stdout, char *prompt)``, overriding the default function used " @@ -221,27 +276,42 @@ msgid "" "string. For example, The :mod:`readline` module sets this hook to provide " "line-editing and tab-completion features." msgstr "" +"Pode ser definido para apontar para uma função com o protótipo ``char " +"*func(FILE *stdin, FILE *stdout, char *prompt)``, substituindo a função " +"padrão usada para ler uma única linha de entrada no prompt do interpretador. " +"Espera-se que a função produza a string *prompt* se não for ``NULL`` e, em " +"seguida, leia uma linha de entrada do arquivo de entrada padrão fornecido, " +"retornando a string resultante. Por exemplo, o módulo :mod:`readline` define " +"este gancho para fornecer recursos de edição de linha e preenchimento de " +"tabulação." -#: ../../c-api/veryhigh.rst:186 +#: ../../c-api/veryhigh.rst:162 msgid "" "The result must be a string allocated by :c:func:`PyMem_RawMalloc` or :c:" "func:`PyMem_RawRealloc`, or ``NULL`` if an error occurred." msgstr "" +"O resultado deve ser uma string alocada por :c:func:`PyMem_RawMalloc` ou :c:" +"func:`PyMem_RawRealloc`, ou ``NULL`` se ocorrer um erro." -#: ../../c-api/veryhigh.rst:189 +#: ../../c-api/veryhigh.rst:165 msgid "" "The result must be allocated by :c:func:`PyMem_RawMalloc` or :c:func:" "`PyMem_RawRealloc`, instead of being allocated by :c:func:`PyMem_Malloc` or :" "c:func:`PyMem_Realloc`." msgstr "" +"O resultado deve ser alocado por :c:func:`PyMem_RawMalloc` ou :c:func:" +"`PyMem_RawRealloc`, em vez de ser alocado por :c:func:`PyMem_Malloc` ou :c:" +"func:`PyMem_Realloc`." -#: ../../c-api/veryhigh.rst:200 +#: ../../c-api/veryhigh.rst:176 msgid "" "This is a simplified interface to :c:func:`PyRun_StringFlags` below, leaving " "*flags* set to ``NULL``." msgstr "" +"Esta é uma interface simplificada para :c:func:`PyRun_StringFlags` abaixo, " +"deixando *flags* definido como ``NULL``." -#: ../../c-api/veryhigh.rst:206 +#: ../../c-api/veryhigh.rst:182 msgid "" "Execute Python source code from *str* in the context specified by the " "objects *globals* and *locals* with the compiler flags specified by " @@ -249,32 +319,45 @@ msgid "" "implements the mapping protocol. The parameter *start* specifies the start " "token that should be used to parse the source code." msgstr "" +"Execut o código-fonte Python de *str* no contexto especificado pelos objetos " +"*globals* e *locals* com os sinalizadores do compilador especificados por " +"*flags*. *globals* deve ser um dicionário; *locals* pode ser qualquer objeto " +"que implemente o protocolo de mapeamento. O parâmetro *start* especifica o " +"token de início que deve ser usado para analisar o código-fonte." -#: ../../c-api/veryhigh.rst:212 +#: ../../c-api/veryhigh.rst:188 msgid "" "Returns the result of executing the code as a Python object, or ``NULL`` if " "an exception was raised." msgstr "" +"Retorna o resultado da execução do código como um objeto Python, ou ``NULL`` " +"se uma exceção foi levantada." -#: ../../c-api/veryhigh.rst:218 +#: ../../c-api/veryhigh.rst:194 msgid "" "This is a simplified interface to :c:func:`PyRun_FileExFlags` below, leaving " "*closeit* set to ``0`` and *flags* set to ``NULL``." msgstr "" +"Esta é uma interface simplificada para :c:func:`PyRun_FileExFlags` abaixo, " +"deixando *closeit* definido como ``0`` e *flags* definido como ``NULL``." -#: ../../c-api/veryhigh.rst:224 +#: ../../c-api/veryhigh.rst:200 msgid "" "This is a simplified interface to :c:func:`PyRun_FileExFlags` below, leaving " "*flags* set to ``NULL``." msgstr "" +"Esta é uma interface simplificada para :c:func:`PyRun_FileExFlags` abaixo, " +"deixando *flags* definido como ``NULL``." -#: ../../c-api/veryhigh.rst:230 +#: ../../c-api/veryhigh.rst:206 msgid "" "This is a simplified interface to :c:func:`PyRun_FileExFlags` below, leaving " "*closeit* set to ``0``." msgstr "" +"Esta é uma interface simplificada para :c:func:`PyRun_FileExFlags` abaixo, " +"deixando *closeit* definido como ``0``." -#: ../../c-api/veryhigh.rst:236 +#: ../../c-api/veryhigh.rst:212 msgid "" "Similar to :c:func:`PyRun_StringFlags`, but the Python source code is read " "from *fp* instead of an in-memory string. *filename* should be the name of " @@ -282,20 +365,29 @@ msgid "" "handler`. If *closeit* is true, the file is closed before :c:func:" "`PyRun_FileExFlags` returns." msgstr "" +"Semelhante a :c:func:`PyRun_StringFlags`, mas o código-fonte Python é lido " +"de *fp* em vez de uma string na memória. *filename* deve ser o nome do " +"arquivo, ele é decodificado a partir do :term:`tratador de erros e " +"codificação do sistema de arquivos`. Se *closeit* for true, o arquivo será " +"fechado antes que :c:func:`PyRun_FileExFlags` retorne." -#: ../../c-api/veryhigh.rst:245 +#: ../../c-api/veryhigh.rst:221 msgid "" "This is a simplified interface to :c:func:`Py_CompileStringFlags` below, " "leaving *flags* set to ``NULL``." msgstr "" +"Esta é uma interface simplificada para :c:func:`Py_CompileStringFlags` " +"abaixo, deixando *flags* definido como ``NULL``." -#: ../../c-api/veryhigh.rst:251 +#: ../../c-api/veryhigh.rst:227 msgid "" "This is a simplified interface to :c:func:`Py_CompileStringExFlags` below, " "with *optimize* set to ``-1``." msgstr "" +"Esta é uma interface simplificada para :c:func:`Py_CompileStringExFlags` " +"abaixo, com *optimize* definido como ``-1``." -#: ../../c-api/veryhigh.rst:257 +#: ../../c-api/veryhigh.rst:233 msgid "" "Parse and compile the Python source code in *str*, returning the resulting " "code object. The start token is given by *start*; this can be used to " @@ -305,8 +397,16 @@ msgid "" "may appear in tracebacks or :exc:`SyntaxError` exception messages. This " "returns ``NULL`` if the code cannot be parsed or compiled." msgstr "" +"Analisa e compil o código-fonte Python em *str*, retornando o objeto de " +"código resultante. O token inicial é fornecido por *start*; isso pode ser " +"usado para restringir o código que pode ser compilado e deve ser :c:data:" +"`Py_eval_input`, :c:data:`Py_file_input` ou :c:data:`Py_single_input`. O " +"nome do arquivo especificado por *filename* é usado para construir o objeto " +"de código e pode aparecer em tracebacks ou mensagens de exceção :exc:" +"`SyntaxError`. Isso retorna ``NULL`` se o código não puder ser analisado ou " +"compilado." -#: ../../c-api/veryhigh.rst:265 +#: ../../c-api/veryhigh.rst:241 msgid "" "The integer *optimize* specifies the optimization level of the compiler; a " "value of ``-1`` selects the optimization level of the interpreter as given " @@ -314,21 +414,33 @@ msgid "" "``__debug__`` is true), ``1`` (asserts are removed, ``__debug__`` is false) " "or ``2`` (docstrings are removed too)." msgstr "" +"O inteiro *optimize* especifica o nível de otimização do compilador; um " +"valor de ``-1`` seleciona o nível de otimização do interpretador dado pela " +"opção :option:`-O`. Níveis explícitos são ``0`` (nenhuma otimização; " +"``__debug__`` é verdadeiro), ``1`` (instruções ``assert`` são removidas, " +"``__debug__`` é falso) ou ``2`` (strings de documentação também são " +"removidas)." -#: ../../c-api/veryhigh.rst:276 +#: ../../c-api/veryhigh.rst:252 msgid "" "Like :c:func:`Py_CompileStringObject`, but *filename* is a byte string " "decoded from the :term:`filesystem encoding and error handler`." msgstr "" +"Como :c:func:`Py_CompileStringObject`, mas *filename* é uma string de bytes " +"decodificada a partir do :term:`tratador de erros e codificação do sistema " +"de arquivos`." -#: ../../c-api/veryhigh.rst:283 +#: ../../c-api/veryhigh.rst:259 msgid "" "This is a simplified interface to :c:func:`PyEval_EvalCodeEx`, with just the " "code object, and global and local variables. The other arguments are set to " "``NULL``." msgstr "" +"Esta é uma interface simplificada para :c:func:`PyEval_EvalCodeEx`, com " +"apenas o objeto código e variáveis locais e globais. Os outros argumentos " +"são definidos como ``NULL``." -#: ../../c-api/veryhigh.rst:290 +#: ../../c-api/veryhigh.rst:266 msgid "" "Evaluate a precompiled code object, given a particular environment for its " "evaluation. This environment consists of a dictionary of global variables, " @@ -336,14 +448,21 @@ msgid "" "defaults, a dictionary of default values for :ref:`keyword-only ` arguments and a closure tuple of cells." msgstr "" +"Avalia um objeto código pré-compilado, dado um ambiente particular para sua " +"avaliação. Este ambiente consiste em um dicionário de variáveis globais, um " +"objeto mapeamento de variáveis locais, vetores de argumentos, nomeados e " +"padrões, um dicionário de valores padrões para argumentos :ref:`somente-" +"nomeados ` e uma tupla de clausura de células." -#: ../../c-api/veryhigh.rst:299 +#: ../../c-api/veryhigh.rst:275 msgid "" "Evaluate an execution frame. This is a simplified interface to :c:func:" "`PyEval_EvalFrameEx`, for backward compatibility." msgstr "" +"Avalia um quadro de execução. Esta é uma interface simplificada para :c:func:" +"`PyEval_EvalFrameEx`, para retrocompatibilidade." -#: ../../c-api/veryhigh.rst:305 +#: ../../c-api/veryhigh.rst:281 msgid "" "This is the main, unvarnished function of Python interpretation. The code " "object associated with the execution frame *f* is executed, interpreting " @@ -352,8 +471,14 @@ msgid "" "immediately be thrown; this is used for the :meth:`~generator.throw` methods " "of generator objects." msgstr "" +"Esta é a função principal e sem retoques da interpretação Python. O objeto " +"código associado ao quadro de execução *f* é executado, interpretando " +"bytecode e executando chamadas conforme necessário. O parâmetro adicional " +"*throwflag* pode ser ignorado na maioria das vezes - se verdadeiro, ele faz " +"com que uma exceção seja levantada imediatamente; isso é usado para os " +"métodos :meth:`~generator.throw` de objetos geradores." -#: ../../c-api/veryhigh.rst:312 +#: ../../c-api/veryhigh.rst:288 msgid "" "This function now includes a debug assertion to help ensure that it does not " "silently discard an active exception." @@ -361,74 +486,113 @@ msgstr "" "Essa função agora inclui uma asserção de depuração para ajudar a garantir " "que ela não descarte silenciosamente uma exceção ativa." -#: ../../c-api/veryhigh.rst:319 +#: ../../c-api/veryhigh.rst:295 msgid "" "This function changes the flags of the current evaluation frame, and returns " "true on success, false on failure." msgstr "" +"Esta função altera os sinalizadores do quadro de avaliação atual e retorna " +"verdadeiro em caso de sucesso e falso em caso de falha." -#: ../../c-api/veryhigh.rst:327 +#: ../../c-api/veryhigh.rst:303 msgid "" "The start symbol from the Python grammar for isolated expressions; for use " "with :c:func:`Py_CompileString`." msgstr "" +"O símbolo inicial da gramática Python para expressões isoladas; para uso " +"com :c:func:`Py_CompileString`." -#: ../../c-api/veryhigh.rst:335 +#: ../../c-api/veryhigh.rst:311 msgid "" "The start symbol from the Python grammar for sequences of statements as read " "from a file or other source; for use with :c:func:`Py_CompileString`. This " "is the symbol to use when compiling arbitrarily long Python source code." msgstr "" +"O símbolo de início da gramática Python para sequências de instruções " +"conforme lidas de um arquivo ou outra fonte; para uso com :c:func:" +"`Py_CompileString`. Este é o símbolo a ser usado ao compilar código-fonte " +"Python arbitrariamente longo." -#: ../../c-api/veryhigh.rst:344 +#: ../../c-api/veryhigh.rst:320 msgid "" "The start symbol from the Python grammar for a single statement; for use " "with :c:func:`Py_CompileString`. This is the symbol used for the interactive " "interpreter loop." msgstr "" +"O símbolo de início da gramática Python para uma única declaração; para uso " +"com :c:func:`Py_CompileString`. Este é o símbolo usado para o laço do " +"interpretador interativo." -#: ../../c-api/veryhigh.rst:351 +#: ../../c-api/veryhigh.rst:327 msgid "" "This is the structure used to hold compiler flags. In cases where code is " "only being compiled, it is passed as ``int flags``, and in cases where code " "is being executed, it is passed as ``PyCompilerFlags *flags``. In this " "case, ``from __future__ import`` can modify *flags*." msgstr "" +"Esta é a estrutura usada para manter os sinalizadores do compilador. Em " +"casos onde o código está apenas sendo compilado, ele é passado como ``int " +"flags``, e em casos onde o código está sendo executado, ele é passado como " +"``PyCompilerFlags *flags``. Neste caso, ``from __future__ import`` pode " +"modificar *flags*." -#: ../../c-api/veryhigh.rst:356 +#: ../../c-api/veryhigh.rst:332 msgid "" "Whenever ``PyCompilerFlags *flags`` is ``NULL``, :c:member:`~PyCompilerFlags." "cf_flags` is treated as equal to ``0``, and any modification due to ``from " "__future__ import`` is discarded." msgstr "" +"Sempre que ``PyCompilerFlags *flags`` for ``NULL``, :c:member:" +"`~PyCompilerFlags.cf_flags` é tratado como igual a ``0``, e qualquer " +"modificação devido a ``from __future__ import`` é descartada." -#: ../../c-api/veryhigh.rst:362 +#: ../../c-api/veryhigh.rst:338 msgid "Compiler flags." -msgstr "" +msgstr "Sinalizadores do compilador." -#: ../../c-api/veryhigh.rst:366 +#: ../../c-api/veryhigh.rst:342 msgid "" "*cf_feature_version* is the minor Python version. It should be initialized " "to ``PY_MINOR_VERSION``." msgstr "" +"*cf_feature_version* é a versão secundária do Python. Deve ser inicializada " +"como ``PY_MINOR_VERSION``." -#: ../../c-api/veryhigh.rst:369 +#: ../../c-api/veryhigh.rst:345 msgid "" "The field is ignored by default, it is used if and only if ``PyCF_ONLY_AST`` " "flag is set in :c:member:`~PyCompilerFlags.cf_flags`." msgstr "" +"O campo é ignorado por padrão, ele é usado se e somente se o sinalizador " +"``PyCF_ONLY_AST`` estiver definido em :c:member:`~PyCompilerFlags.cf_flags`." -#: ../../c-api/veryhigh.rst:372 +#: ../../c-api/veryhigh.rst:348 msgid "Added *cf_feature_version* field." +msgstr "Adicionado campo *cf_feature_version*." + +#: ../../c-api/veryhigh.rst:351 +msgid "The available compiler flags are accessible as macros:" +msgstr "Os sinalizadores do compilador disponíveis são acessíveis como macros:" + +#: ../../c-api/veryhigh.rst:360 +msgid "" +"See :ref:`compiler flags ` in documentation of the :py:" +"mod:`!ast` Python module, which exports these constants under the same names." msgstr "" +"Veja :ref:`sinalizadores do compilador ` na documentação " +"do módulo Python :py:mod:`!ast`, que exporta essas constantes com os mesmos " +"nomes." -#: ../../c-api/veryhigh.rst:378 +#: ../../c-api/veryhigh.rst:366 msgid "" "This bit can be set in *flags* to cause division operator ``/`` to be " "interpreted as \"true division\" according to :pep:`238`." msgstr "" +"Este bit pode ser definido em *flags* para fazer com que o operador de " +"divisão ``/`` seja interpretado como \"divisão verdadeira\" de acordo com a :" +"pep:`238`." -#: ../../c-api/veryhigh.rst:325 ../../c-api/veryhigh.rst:333 -#: ../../c-api/veryhigh.rst:342 +#: ../../c-api/veryhigh.rst:301 ../../c-api/veryhigh.rst:309 +#: ../../c-api/veryhigh.rst:318 msgid "Py_CompileString (C function)" -msgstr "" +msgstr "Py_CompileString (função C)" diff --git a/c-api/weakref.po b/c-api/weakref.po index 49e01717c..a78e218a4 100644 --- a/c-api/weakref.po +++ b/c-api/weakref.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/contents.po b/contents.po index 42df5b791..cb6d283f9 100644 --- a/contents.po +++ b/contents.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Erick Simões , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Erick Simões , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/copyright.po b/copyright.po index f2ff87e51..1750ea091 100644 --- a/copyright.po +++ b/copyright.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Ademar Nowasky Junior , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/deprecations/c-api-pending-removal-in-3.14.po b/deprecations/c-api-pending-removal-in-3.14.po index 493f6df84..189b37edb 100644 --- a/deprecations/c-api-pending-removal-in-3.14.po +++ b/deprecations/c-api-pending-removal-in-3.14.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2024-08-02 14:17+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:08+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -51,160 +51,163 @@ msgstr "" "3.11:" #: ../../deprecations/c-api-pending-removal-in-3.14.rst:12 -msgid "``PySys_SetArgvEx()``: set :c:member:`PyConfig.argv` instead." -msgstr "``PySys_SetArgvEx()``: defina :c:member:`PyConfig.argv`." - -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:13 -msgid "``PySys_SetArgv()``: set :c:member:`PyConfig.argv` instead." -msgstr "``PySys_SetArgv()``: defina :c:member:`PyConfig.argv`." +msgid ":c:func:`!PySys_SetArgvEx()`: Set :c:member:`PyConfig.argv` instead." +msgstr ":c:func:`!PySys_SetArgvEx()`: defina :c:member:`PyConfig.argv`." #: ../../deprecations/c-api-pending-removal-in-3.14.rst:14 -msgid "``Py_SetProgramName()``: set :c:member:`PyConfig.program_name` instead." -msgstr "``Py_SetProgramName()``: defina :c:member:`PyConfig.program_name`." +msgid ":c:func:`!PySys_SetArgv()`: Set :c:member:`PyConfig.argv` instead." +msgstr ":c:func:`!PySys_SetArgv()`: defina :c:member:`PyConfig.argv`." + +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:16 +msgid "" +":c:func:`!Py_SetProgramName()`: Set :c:member:`PyConfig.program_name` " +"instead." +msgstr "" +":c:func:`!Py_SetProgramName()`: defina :c:member:`PyConfig.program_name`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:15 -msgid "``Py_SetPythonHome()``: set :c:member:`PyConfig.home` instead." -msgstr "``Py_SetPythonHome()``: defina :c:member:`PyConfig.home`." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:18 +msgid ":c:func:`!Py_SetPythonHome()`: Set :c:member:`PyConfig.home` instead." +msgstr ":c:func:`!Py_SetPythonHome()`: defina :c:member:`PyConfig.home`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:17 -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:45 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:21 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:71 msgid "" "The :c:func:`Py_InitializeFromConfig` API should be used with :c:type:" "`PyConfig` instead." msgstr "" -"A API :c:func:`Py_InitializeFromConfig` deve ser usada com :c:type:" -"`PyConfig`." +"Em vez disso, a API :c:func:`Py_InitializeFromConfig` deve ser usada com :c:" +"type:`PyConfig`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:20 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:24 msgid "Global configuration variables:" msgstr "Variáveis de configuração globais" -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:22 -msgid ":c:var:`Py_DebugFlag`: use :c:member:`PyConfig.parser_debug` instead." -msgstr ":c:var:`Py_DebugFlag`: use :c:member:`PyConfig.parser_debug`." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:26 +msgid ":c:var:`Py_DebugFlag`: Use :c:member:`PyConfig.parser_debug` instead." +msgstr ":c:var:`Py_DebugFlag`: Use :c:member:`PyConfig.parser_debug`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:23 -msgid ":c:var:`Py_VerboseFlag`: use :c:member:`PyConfig.verbose` instead." -msgstr ":c:var:`Py_VerboseFlag`: use :c:member:`PyConfig.verbose`." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:28 +msgid ":c:var:`Py_VerboseFlag`: Use :c:member:`PyConfig.verbose` instead." +msgstr ":c:var:`Py_VerboseFlag`: Use :c:member:`PyConfig.verbose`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:24 -msgid ":c:var:`Py_QuietFlag`: use :c:member:`PyConfig.quiet` instead." -msgstr ":c:var:`Py_QuietFlag`: use :c:member:`PyConfig.quiet`." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:30 +msgid ":c:var:`Py_QuietFlag`: Use :c:member:`PyConfig.quiet` instead." +msgstr ":c:var:`Py_QuietFlag`: Use :c:member:`PyConfig.quiet`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:25 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:32 msgid "" -":c:var:`Py_InteractiveFlag`: use :c:member:`PyConfig.interactive` instead." -msgstr ":c:var:`Py_InteractiveFlag`: use :c:member:`PyConfig.interactive`." +":c:var:`Py_InteractiveFlag`: Use :c:member:`PyConfig.interactive` instead." +msgstr ":c:var:`Py_InteractiveFlag`: Use :c:member:`PyConfig.interactive`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:26 -msgid ":c:var:`Py_InspectFlag`: use :c:member:`PyConfig.inspect` instead." -msgstr ":c:var:`Py_InspectFlag`: use :c:member:`PyConfig.inspect`." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:34 +msgid ":c:var:`Py_InspectFlag`: Use :c:member:`PyConfig.inspect` instead." +msgstr ":c:var:`Py_InspectFlag`: Use :c:member:`PyConfig.inspect`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:27 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:36 msgid "" -":c:var:`Py_OptimizeFlag`: use :c:member:`PyConfig.optimization_level` " +":c:var:`Py_OptimizeFlag`: Use :c:member:`PyConfig.optimization_level` " "instead." -msgstr ":c:var:`Py_OptimizeFlag`: use :c:member:`PyConfig.optimization_level`." +msgstr ":c:var:`Py_OptimizeFlag`: Use :c:member:`PyConfig.optimization_level`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:28 -msgid ":c:var:`Py_NoSiteFlag`: use :c:member:`PyConfig.site_import` instead." -msgstr ":c:var:`Py_NoSiteFlag`: use :c:member:`PyConfig.site_import`." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:38 +msgid ":c:var:`Py_NoSiteFlag`: Use :c:member:`PyConfig.site_import` instead." +msgstr ":c:var:`Py_NoSiteFlag`: Use :c:member:`PyConfig.site_import`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:29 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:40 msgid "" -":c:var:`Py_BytesWarningFlag`: use :c:member:`PyConfig.bytes_warning` instead." -msgstr ":c:var:`Py_BytesWarningFlag`: use :c:member:`PyConfig.bytes_warning`." +":c:var:`Py_BytesWarningFlag`: Use :c:member:`PyConfig.bytes_warning` instead." +msgstr ":c:var:`Py_BytesWarningFlag`: Use :c:member:`PyConfig.bytes_warning`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:30 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:42 msgid "" -":c:var:`Py_FrozenFlag`: use :c:member:`PyConfig.pathconfig_warnings` instead." -msgstr ":c:var:`Py_FrozenFlag`: use :c:member:`PyConfig.pathconfig_warnings`." +":c:var:`Py_FrozenFlag`: Use :c:member:`PyConfig.pathconfig_warnings` instead." +msgstr ":c:var:`Py_FrozenFlag`: Use :c:member:`PyConfig.pathconfig_warnings`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:31 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:44 msgid "" -":c:var:`Py_IgnoreEnvironmentFlag`: use :c:member:`PyConfig.use_environment` " +":c:var:`Py_IgnoreEnvironmentFlag`: Use :c:member:`PyConfig.use_environment` " "instead." msgstr "" -":c:var:`Py_IgnoreEnvironmentFlag`: use :c:member:`PyConfig.use_environment`." +":c:var:`Py_IgnoreEnvironmentFlag`: Use :c:member:`PyConfig.use_environment`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:32 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:46 msgid "" -":c:var:`Py_DontWriteBytecodeFlag`: use :c:member:`PyConfig.write_bytecode` " +":c:var:`Py_DontWriteBytecodeFlag`: Use :c:member:`PyConfig.write_bytecode` " "instead." msgstr "" -":c:var:`Py_DontWriteBytecodeFlag`: use :c:member:`PyConfig.write_bytecode`." +":c:var:`Py_DontWriteBytecodeFlag`: Use :c:member:`PyConfig.write_bytecode`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:33 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:48 msgid "" -":c:var:`Py_NoUserSiteDirectory`: use :c:member:`PyConfig." +":c:var:`Py_NoUserSiteDirectory`: Use :c:member:`PyConfig." "user_site_directory` instead." msgstr "" -":c:var:`Py_NoUserSiteDirectory`: use :c:member:`PyConfig." +":c:var:`Py_NoUserSiteDirectory`: Use :c:member:`PyConfig." "user_site_directory`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:34 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:50 msgid "" -":c:var:`Py_UnbufferedStdioFlag`: use :c:member:`PyConfig.buffered_stdio` " +":c:var:`Py_UnbufferedStdioFlag`: Use :c:member:`PyConfig.buffered_stdio` " "instead." msgstr "" -":c:var:`Py_UnbufferedStdioFlag`: use :c:member:`PyConfig.buffered_stdio`." +":c:var:`Py_UnbufferedStdioFlag`: Use :c:member:`PyConfig.buffered_stdio`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:35 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:52 msgid "" -":c:var:`Py_HashRandomizationFlag`: use :c:member:`PyConfig.use_hash_seed` " +":c:var:`Py_HashRandomizationFlag`: Use :c:member:`PyConfig.use_hash_seed` " "and :c:member:`PyConfig.hash_seed` instead." msgstr "" -":c:var:`Py_HashRandomizationFlag`: use :c:member:`PyConfig.use_hash_seed` e :" +":c:var:`Py_HashRandomizationFlag`: Use :c:member:`PyConfig.use_hash_seed` e :" "c:member:`PyConfig.hash_seed`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:37 -msgid ":c:var:`Py_IsolatedFlag`: use :c:member:`PyConfig.isolated` instead." -msgstr ":c:var:`Py_IsolatedFlag`: use :c:member:`PyConfig.isolated`." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:55 +msgid ":c:var:`Py_IsolatedFlag`: Use :c:member:`PyConfig.isolated` instead." +msgstr ":c:var:`Py_IsolatedFlag`: Use :c:member:`PyConfig.isolated`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:38 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:57 msgid "" -":c:var:`Py_LegacyWindowsFSEncodingFlag`: use :c:member:`PyPreConfig." +":c:var:`Py_LegacyWindowsFSEncodingFlag`: Use :c:member:`PyPreConfig." "legacy_windows_fs_encoding` instead." msgstr "" -":c:var:`Py_LegacyWindowsFSEncodingFlag`: use :c:member:`PyPreConfig." +":c:var:`Py_LegacyWindowsFSEncodingFlag`: Use :c:member:`PyPreConfig." "legacy_windows_fs_encoding`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:39 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:59 msgid "" -":c:var:`Py_LegacyWindowsStdioFlag`: use :c:member:`PyConfig." +":c:var:`Py_LegacyWindowsStdioFlag`: Use :c:member:`PyConfig." "legacy_windows_stdio` instead." msgstr "" -":c:var:`Py_LegacyWindowsStdioFlag`: use :c:member:`PyConfig." +":c:var:`Py_LegacyWindowsStdioFlag`: Use :c:member:`PyConfig." "legacy_windows_stdio`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:40 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:61 msgid "" -":c:var:`!Py_FileSystemDefaultEncoding`: use :c:member:`PyConfig." +":c:var:`!Py_FileSystemDefaultEncoding`: Use :c:member:`PyConfig." "filesystem_encoding` instead." msgstr "" -":c:var:`!Py_FileSystemDefaultEncoding`: use :c:member:`PyConfig." +":c:var:`!Py_FileSystemDefaultEncoding`: Use :c:member:`PyConfig." "filesystem_encoding`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:41 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:63 msgid "" -":c:var:`!Py_HasFileSystemDefaultEncoding`: use :c:member:`PyConfig." +":c:var:`!Py_HasFileSystemDefaultEncoding`: Use :c:member:`PyConfig." "filesystem_encoding` instead." msgstr "" -":c:var:`!Py_HasFileSystemDefaultEncoding`: use :c:member:`PyConfig." +":c:var:`!Py_HasFileSystemDefaultEncoding`: Use :c:member:`PyConfig." "filesystem_encoding`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:42 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:65 msgid "" -":c:var:`!Py_FileSystemDefaultEncodeErrors`: use :c:member:`PyConfig." +":c:var:`!Py_FileSystemDefaultEncodeErrors`: Use :c:member:`PyConfig." "filesystem_errors` instead." msgstr "" -":c:var:`!Py_FileSystemDefaultEncodeErrors`: use :c:member:`PyConfig." +":c:var:`!Py_FileSystemDefaultEncodeErrors`: Use :c:member:`PyConfig." "filesystem_errors`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:43 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:67 msgid "" -":c:var:`!Py_UTF8Mode`: use :c:member:`PyPreConfig.utf8_mode` instead. (see :" +":c:var:`!Py_UTF8Mode`: Use :c:member:`PyPreConfig.utf8_mode` instead. (see :" "c:func:`Py_PreInitialize`)" msgstr "" -":c:var:`!Py_UTF8Mode`: use :c:member:`PyPreConfig.utf8_mode`. (veja :c:func:" +":c:var:`!Py_UTF8Mode`: Use :c:member:`PyPreConfig.utf8_mode`. (veja :c:func:" "`Py_PreInitialize`)" diff --git a/deprecations/c-api-pending-removal-in-3.15.po b/deprecations/c-api-pending-removal-in-3.15.po index 2e1d7f169..28d086df2 100644 --- a/deprecations/c-api-pending-removal-in-3.15.po +++ b/deprecations/c-api-pending-removal-in-3.15.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-02 14:15+0000\n" -"PO-Revision-Date: 2024-08-02 14:17+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -33,63 +33,71 @@ msgstr "A cópia empacotada do ``libmpdecimal``." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:5 msgid "" -":c:func:`PyImport_ImportModuleNoBlock`: use :c:func:`PyImport_ImportModule` " -"instead." +"The :c:func:`PyImport_ImportModuleNoBlock`: Use :c:func:" +"`PyImport_ImportModule` instead." msgstr "" -":c:func:`PyImport_ImportModuleNoBlock`: use :c:func:`PyImport_ImportModule`." - -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:6 -msgid ":c:func:`PyWeakref_GET_OBJECT`: use :c:func:`PyWeakref_GetRef` instead." -msgstr ":c:func:`PyWeakref_GET_OBJECT`: use :c:func:`PyWeakref_GetRef`." +"The :c:func:`PyImport_ImportModuleNoBlock`: use :c:func:" +"`PyImport_ImportModule`." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:7 -msgid ":c:func:`PyWeakref_GetObject`: use :c:func:`PyWeakref_GetRef` instead." -msgstr ":c:func:`PyWeakref_GetObject`: use :c:func:`PyWeakref_GetRef`." - -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:8 -msgid ":c:type:`!Py_UNICODE_WIDE` type: use :c:type:`wchar_t` instead." -msgstr "O tipo :c:type:`!Py_UNICODE_WIDE`: use :c:type:`wchar_t`." +msgid "" +":c:func:`PyWeakref_GetObject` and :c:func:`PyWeakref_GET_OBJECT`: Use :c:" +"func:`PyWeakref_GetRef` instead." +msgstr "" +":c:func:`PyWeakref_GetObject` e :c:func:`PyWeakref_GET_OBJECT`: use :c:func:" +"`PyWeakref_GetRef`." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:9 -msgid ":c:type:`Py_UNICODE` type: use :c:type:`wchar_t` instead." -msgstr "O tipo :c:type:`Py_UNICODE`: use :c:type:`wchar_t`." +msgid "" +":c:type:`Py_UNICODE` type and the :c:macro:`!Py_UNICODE_WIDE` macro: Use :c:" +"type:`wchar_t` instead." +msgstr "" +"O tipo :c:type:`Py_UNICODE` e a macro :c:macro:`!Py_UNICODE_WIDE`: use :c:" +"type:`wchar_t`." -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:10 +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:11 msgid "Python initialization functions:" msgstr "Funções de inicialização do Python" -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:12 +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:13 msgid "" -":c:func:`PySys_ResetWarnOptions`: clear :data:`sys.warnoptions` and :data:`!" +":c:func:`PySys_ResetWarnOptions`: Clear :data:`sys.warnoptions` and :data:`!" "warnings.filters` instead." msgstr "" ":c:func:`PySys_ResetWarnOptions`: apague :data:`sys.warnoptions` e :data:`!" "warnings.filters`." -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:14 -msgid ":c:func:`Py_GetExecPrefix`: get :data:`sys.exec_prefix` instead." -msgstr ":c:func:`Py_GetExecPrefix`: obtenha :data:`sys.exec_prefix`." - #: ../../deprecations/c-api-pending-removal-in-3.15.rst:15 -msgid ":c:func:`Py_GetPath`: get :data:`sys.path` instead." -msgstr ":c:func:`Py_GetPath`: obtenha :data:`sys.path`." - -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:16 -msgid ":c:func:`Py_GetPrefix`: get :data:`sys.prefix` instead." -msgstr ":c:func:`Py_GetPrefix`: obtenha :data:`sys.prefix`." +msgid "" +":c:func:`Py_GetExecPrefix`: Get :data:`sys.base_exec_prefix` and :data:`sys." +"exec_prefix` instead." +msgstr "" +":c:func:`Py_GetExecPrefix`: obtenha :data:`sys.base_exec_prefix` e :data:" +"`sys.exec_prefix`." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:17 -msgid ":c:func:`Py_GetProgramFullPath`: get :data:`sys.executable` instead." -msgstr ":c:func:`Py_GetProgramFullPath`: obtenha :data:`sys.executable`." - -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:18 -msgid ":c:func:`Py_GetProgramName`: get :data:`sys.executable` instead." -msgstr ":c:func:`Py_GetProgramName`: obtenha :data:`sys.executable`." +msgid ":c:func:`Py_GetPath`: Get :data:`sys.path` instead." +msgstr ":c:func:`Py_GetPath`: leia :data:`sys.path`." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:19 msgid "" -":c:func:`Py_GetPythonHome`: get :c:member:`PyConfig.home` or the :envvar:" +":c:func:`Py_GetPrefix`: Get :data:`sys.base_prefix` and :data:`sys.prefix` " +"instead." +msgstr "" +":c:func:`Py_GetPrefix`: obtenha :data:`sys.base_prefix` e :data:`sys.prefix`." + +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:21 +msgid ":c:func:`Py_GetProgramFullPath`: Get :data:`sys.executable` instead." +msgstr ":c:func:`Py_GetProgramFullPath`: leia :data:`sys.executable`." + +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:23 +msgid ":c:func:`Py_GetProgramName`: Get :data:`sys.executable` instead." +msgstr ":c:func:`Py_GetProgramName`: leia :data:`sys.executable`." + +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:25 +msgid "" +":c:func:`Py_GetPythonHome`: Get :c:member:`PyConfig.home` or the :envvar:" "`PYTHONHOME` environment variable instead." msgstr "" -":c:func:`Py_GetPythonHome`: obtenha :c:member:`PyConfig.home` ou a variável " -"de ambiente :envvar:`PYTHONHOME`." +":c:func:`Py_GetPythonHome`: leia :c:member:`PyConfig.home` ou a variável de " +"ambiente :envvar:`PYTHONHOME`." diff --git a/deprecations/c-api-pending-removal-in-future.po b/deprecations/c-api-pending-removal-in-future.po index 21ec83bd3..2af91422d 100644 --- a/deprecations/c-api-pending-removal-in-future.po +++ b/deprecations/c-api-pending-removal-in-future.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2024-08-02 14:17+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -32,122 +32,124 @@ msgid "" "The following APIs are deprecated and will be removed, although there is " "currently no date scheduled for their removal." msgstr "" -"As APIs a seguir foram descontinuado e serão removidas, embora atualmente " +"As APIs a seguir foram descontinuadas e serão removidas, embora atualmente " "não haja uma data agendada para sua remoção." #: ../../deprecations/c-api-pending-removal-in-future.rst:7 -msgid ":c:macro:`Py_TPFLAGS_HAVE_FINALIZE`: unneeded since Python 3.8." +msgid ":c:macro:`Py_TPFLAGS_HAVE_FINALIZE`: Unneeded since Python 3.8." msgstr ":c:macro:`Py_TPFLAGS_HAVE_FINALIZE`: desnecessária desde o Python 3.8." -#: ../../deprecations/c-api-pending-removal-in-future.rst:8 -msgid ":c:func:`PyErr_Fetch`: use :c:func:`PyErr_GetRaisedException` instead." +#: ../../deprecations/c-api-pending-removal-in-future.rst:9 +msgid ":c:func:`PyErr_Fetch`: Use :c:func:`PyErr_GetRaisedException` instead." msgstr ":c:func:`PyErr_Fetch`: use :c:func:`PyErr_GetRaisedException`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:9 +#: ../../deprecations/c-api-pending-removal-in-future.rst:11 msgid "" -":c:func:`PyErr_NormalizeException`: use :c:func:`PyErr_GetRaisedException` " +":c:func:`PyErr_NormalizeException`: Use :c:func:`PyErr_GetRaisedException` " "instead." msgstr "" ":c:func:`PyErr_NormalizeException`: use :c:func:`PyErr_GetRaisedException`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:10 +#: ../../deprecations/c-api-pending-removal-in-future.rst:13 msgid "" -":c:func:`PyErr_Restore`: use :c:func:`PyErr_SetRaisedException` instead." +":c:func:`PyErr_Restore`: Use :c:func:`PyErr_SetRaisedException` instead." msgstr ":c:func:`PyErr_Restore`: use :c:func:`PyErr_SetRaisedException`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:11 +#: ../../deprecations/c-api-pending-removal-in-future.rst:15 msgid "" -":c:func:`PyModule_GetFilename`: use :c:func:`PyModule_GetFilenameObject` " +":c:func:`PyModule_GetFilename`: Use :c:func:`PyModule_GetFilenameObject` " "instead." msgstr "" ":c:func:`PyModule_GetFilename`: use :c:func:`PyModule_GetFilenameObject`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:12 -msgid ":c:func:`PyOS_AfterFork`: use :c:func:`PyOS_AfterFork_Child` instead." +#: ../../deprecations/c-api-pending-removal-in-future.rst:17 +msgid ":c:func:`PyOS_AfterFork`: Use :c:func:`PyOS_AfterFork_Child` instead." msgstr ":c:func:`PyOS_AfterFork`: use :c:func:`PyOS_AfterFork_Child`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:13 +#: ../../deprecations/c-api-pending-removal-in-future.rst:19 msgid "" -":c:func:`PySlice_GetIndicesEx`: use :c:func:`PySlice_Unpack` and :c:func:" +":c:func:`PySlice_GetIndicesEx`: Use :c:func:`PySlice_Unpack` and :c:func:" "`PySlice_AdjustIndices` instead." msgstr "" ":c:func:`PySlice_GetIndicesEx`: use :c:func:`PySlice_Unpack` e :c:func:" "`PySlice_AdjustIndices`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:14 +#: ../../deprecations/c-api-pending-removal-in-future.rst:21 msgid "" -":c:func:`!PyUnicode_AsDecodedObject`: use :c:func:`PyCodec_Decode` instead." +":c:func:`!PyUnicode_AsDecodedObject`: Use :c:func:`PyCodec_Decode` instead." msgstr ":c:func:`!PyUnicode_AsDecodedObject`: use :c:func:`PyCodec_Decode`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:15 +#: ../../deprecations/c-api-pending-removal-in-future.rst:23 msgid "" -":c:func:`!PyUnicode_AsDecodedUnicode`: use :c:func:`PyCodec_Decode` instead." -msgstr ":c:func:`!PyUnicode_AsDecodedUnicode`: use :c:func:`PyCodec_Decode`." +":c:func:`!PyUnicode_AsDecodedUnicode`: Use :c:func:`PyCodec_Decode` instead." +msgstr ":c:func:`!PyUnicode_AsDecodedUnicode`: Use :c:func:`PyCodec_Decode`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:16 +#: ../../deprecations/c-api-pending-removal-in-future.rst:25 msgid "" -":c:func:`!PyUnicode_AsEncodedObject`: use :c:func:`PyCodec_Encode` instead." +":c:func:`!PyUnicode_AsEncodedObject`: Use :c:func:`PyCodec_Encode` instead." msgstr ":c:func:`!PyUnicode_AsEncodedObject`: use :c:func:`PyCodec_Encode`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:17 +#: ../../deprecations/c-api-pending-removal-in-future.rst:27 msgid "" -":c:func:`!PyUnicode_AsEncodedUnicode`: use :c:func:`PyCodec_Encode` instead." -msgstr ":c:func:`!PyUnicode_AsEncodedUnicode`: use :c:func:`PyCodec_Encode`." +":c:func:`!PyUnicode_AsEncodedUnicode`: Use :c:func:`PyCodec_Encode` instead." +msgstr ":c:func:`!PyUnicode_AsEncodedUnicode`: Use :c:func:`PyCodec_Encode`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:18 -msgid ":c:func:`PyUnicode_READY`: unneeded since Python 3.12" +#: ../../deprecations/c-api-pending-removal-in-future.rst:29 +msgid ":c:func:`PyUnicode_READY`: Unneeded since Python 3.12" msgstr ":c:func:`PyUnicode_READY`: desnecessário desde o Python 3.12" -#: ../../deprecations/c-api-pending-removal-in-future.rst:19 -msgid ":c:func:`!PyErr_Display`: use :c:func:`PyErr_DisplayException` instead." +#: ../../deprecations/c-api-pending-removal-in-future.rst:31 +msgid ":c:func:`!PyErr_Display`: Use :c:func:`PyErr_DisplayException` instead." msgstr ":c:func:`!PyErr_Display`: use :c:func:`PyErr_DisplayException`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:20 +#: ../../deprecations/c-api-pending-removal-in-future.rst:33 msgid "" -":c:func:`!_PyErr_ChainExceptions`: use ``_PyErr_ChainExceptions1`` instead." -msgstr ":c:func:`!_PyErr_ChainExceptions`: use ``_PyErr_ChainExceptions1``." +":c:func:`!_PyErr_ChainExceptions`: Use :c:func:`!_PyErr_ChainExceptions1` " +"instead." +msgstr "" +":c:func:`!_PyErr_ChainExceptions`: use :c:func:`!_PyErr_ChainExceptions1`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:21 +#: ../../deprecations/c-api-pending-removal-in-future.rst:35 msgid "" ":c:member:`!PyBytesObject.ob_shash` member: call :c:func:`PyObject_Hash` " "instead." msgstr "" "O membro :c:member:`!PyBytesObject.ob_shash`: chame :c:func:`PyObject_Hash`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:23 +#: ../../deprecations/c-api-pending-removal-in-future.rst:37 msgid ":c:member:`!PyDictObject.ma_version_tag` member." msgstr "O membro :c:member:`!PyDictObject.ma_version_tag`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:24 +#: ../../deprecations/c-api-pending-removal-in-future.rst:38 msgid "Thread Local Storage (TLS) API:" msgstr "API do Thread Local Storage (TLS):" -#: ../../deprecations/c-api-pending-removal-in-future.rst:26 +#: ../../deprecations/c-api-pending-removal-in-future.rst:40 msgid "" -":c:func:`PyThread_create_key`: use :c:func:`PyThread_tss_alloc` instead." +":c:func:`PyThread_create_key`: Use :c:func:`PyThread_tss_alloc` instead." msgstr ":c:func:`PyThread_create_key`: use :c:func:`PyThread_tss_alloc`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:27 -msgid ":c:func:`PyThread_delete_key`: use :c:func:`PyThread_tss_free` instead." +#: ../../deprecations/c-api-pending-removal-in-future.rst:42 +msgid ":c:func:`PyThread_delete_key`: Use :c:func:`PyThread_tss_free` instead." msgstr ":c:func:`PyThread_delete_key`: use :c:func:`PyThread_tss_free`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:28 +#: ../../deprecations/c-api-pending-removal-in-future.rst:44 msgid "" -":c:func:`PyThread_set_key_value`: use :c:func:`PyThread_tss_set` instead." +":c:func:`PyThread_set_key_value`: Use :c:func:`PyThread_tss_set` instead." msgstr ":c:func:`PyThread_set_key_value`: use :c:func:`PyThread_tss_set`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:29 +#: ../../deprecations/c-api-pending-removal-in-future.rst:46 msgid "" -":c:func:`PyThread_get_key_value`: use :c:func:`PyThread_tss_get` instead." +":c:func:`PyThread_get_key_value`: Use :c:func:`PyThread_tss_get` instead." msgstr ":c:func:`PyThread_get_key_value`: use :c:func:`PyThread_tss_get`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:30 +#: ../../deprecations/c-api-pending-removal-in-future.rst:48 msgid "" -":c:func:`PyThread_delete_key_value`: use :c:func:`PyThread_tss_delete` " +":c:func:`PyThread_delete_key_value`: Use :c:func:`PyThread_tss_delete` " "instead." msgstr "" ":c:func:`PyThread_delete_key_value`: use :c:func:`PyThread_tss_delete`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:31 -msgid ":c:func:`PyThread_ReInitTLS`: unneeded since Python 3.7." +#: ../../deprecations/c-api-pending-removal-in-future.rst:50 +msgid ":c:func:`PyThread_ReInitTLS`: Unneeded since Python 3.7." msgstr ":c:func:`PyThread_ReInitTLS`: desnecessário desde o Python 3.7." diff --git a/deprecations/index.po b/deprecations/index.po index 198d22fa5..89d9fe813 100644 --- a/deprecations/index.po +++ b/deprecations/index.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2024-07-29 04:07+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-16 14:58+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -48,7 +48,7 @@ msgid "" "since Python 3.8, now cause a :exc:`DeprecationWarning` to be emitted at " "runtime when they are accessed or used, and will be removed in Python 3.14:" msgstr "" -":mod:`ast`: Os seguintes recursos foram descontinuados na documentação desde " +":mod:`ast`: os seguintes recursos foram descontinuados na documentação desde " "Python 3.8, agora fazem com que um :exc:`DeprecationWarning` seja emitido em " "tempo de execução quando eles são acessados ou usados, e serão removidos no " "Python 3.14:" @@ -78,10 +78,11 @@ msgid "" "Use :class:`ast.Constant` instead. (Contributed by Serhiy Storchaka in :gh:" "`90953`.)" msgstr "" -"Usa :class:`ast.Constant` em vez disso. (Contribuição de Serhiy Storchaka " +"Em vez disso, use :class:`ast.Constant`. (Contribuição de Serhiy Storchaka " "em :gh:`90953`.)" #: ../../deprecations/pending-removal-in-3.14.rst:22 +#: ../../deprecations/pending-removal-in-3.16.rst:19 msgid ":mod:`asyncio`:" msgstr ":mod:`asyncio`:" @@ -92,7 +93,7 @@ msgid "" "class:`~asyncio.SafeChildWatcher` are deprecated and will be removed in " "Python 3.14. (Contributed by Kumar Aditya in :gh:`94597`.)" msgstr "" -"As classes filhas do observador :class:`~asyncio.MultiLoopChildWatcher`, :" +"As classes filhas dos observadores :class:`~asyncio.MultiLoopChildWatcher`, :" "class:`~asyncio.FastChildWatcher`, :class:`~asyncio.AbstractChildWatcher` e :" "class:`~asyncio.SafeChildWatcher` foram descontinuadas e serão removidas no " "Python 3.14. (Contribuição de Kumar Aditya em :gh:`94597`.)" @@ -130,7 +131,7 @@ msgid "" msgstr "" ":mod:`collections.abc`: :class:`~collections.abc.ByteString` foi " "descontinuado. Prefira :class:`!Sequence` ou :class:`~collections.abc." -"Buffer` Para uso em tipagem, prefira uma união, como ``bytes | bytearray`` " +"Buffer`. Para uso em tipagem, prefira uma união, como ``bytes | bytearray`` " "ou :class:`collections.abc.Buffer`. (Contribuição de Shantanu Jain em :gh:" "`91896`.)" @@ -143,46 +144,38 @@ msgstr "" "localtime`. (Contribuição de Alan Williams em :gh:`72346`.)" #: ../../deprecations/pending-removal-in-3.14.rst:50 -msgid "" -":mod:`importlib`: ``__package__`` and ``__cached__`` will cease to be set or " -"taken into consideration by the import system (:gh:`97879`)." -msgstr "" -":mod:`importlib`: ``__package__`` e ``__cached__`` deixarão de ser definidos " -"ou levados em consideração pelo sistema de importação (:gh:`97879`)." - -#: ../../deprecations/pending-removal-in-3.14.rst:53 msgid ":mod:`importlib.abc` deprecated classes:" msgstr ":mod:`importlib.abc` descontinuou as classes:" -#: ../../deprecations/pending-removal-in-3.14.rst:55 +#: ../../deprecations/pending-removal-in-3.14.rst:52 msgid ":class:`!importlib.abc.ResourceReader`" msgstr ":class:`!importlib.abc.ResourceReader`" -#: ../../deprecations/pending-removal-in-3.14.rst:56 +#: ../../deprecations/pending-removal-in-3.14.rst:53 msgid ":class:`!importlib.abc.Traversable`" msgstr ":class:`!importlib.abc.Traversable`" -#: ../../deprecations/pending-removal-in-3.14.rst:57 +#: ../../deprecations/pending-removal-in-3.14.rst:54 msgid ":class:`!importlib.abc.TraversableResources`" msgstr ":class:`!importlib.abc.TraversableResources`" -#: ../../deprecations/pending-removal-in-3.14.rst:59 +#: ../../deprecations/pending-removal-in-3.14.rst:56 msgid "Use :mod:`importlib.resources.abc` classes instead:" -msgstr "Em vez disso, use classes :mod:`importlib.resources.abc`:" +msgstr "Em vez disso, use classes de :mod:`importlib.resources.abc`:" -#: ../../deprecations/pending-removal-in-3.14.rst:61 +#: ../../deprecations/pending-removal-in-3.14.rst:58 msgid ":class:`importlib.resources.abc.Traversable`" msgstr ":class:`importlib.resources.abc.Traversable`" -#: ../../deprecations/pending-removal-in-3.14.rst:62 +#: ../../deprecations/pending-removal-in-3.14.rst:59 msgid ":class:`importlib.resources.abc.TraversableResources`" msgstr ":class:`importlib.resources.abc.TraversableResources`" -#: ../../deprecations/pending-removal-in-3.14.rst:64 +#: ../../deprecations/pending-removal-in-3.14.rst:61 msgid "(Contributed by Jason R. Coombs and Hugo van Kemenade in :gh:`93963`.)" msgstr "(Contribuição de Jason R. Coombs e Hugo van Kemenade em :gh:`93963`.)" -#: ../../deprecations/pending-removal-in-3.14.rst:66 +#: ../../deprecations/pending-removal-in-3.14.rst:63 msgid "" ":mod:`itertools` had undocumented, inefficient, historically buggy, and " "inconsistent support for copy, deepcopy, and pickle operations. This will be " @@ -195,7 +188,7 @@ msgstr "" "significativa no volume de código e na carga de manutenção. (Contribuição de " "Raymond Hettinger em :gh:`101588`.)" -#: ../../deprecations/pending-removal-in-3.14.rst:72 +#: ../../deprecations/pending-removal-in-3.14.rst:69 msgid "" ":mod:`multiprocessing`: The default start method will change to a safer one " "on Linux, BSDs, and other non-macOS POSIX platforms where ``'fork'`` is " @@ -205,7 +198,7 @@ msgid "" "set_start_method` APIs to explicitly specify when your code *requires* " "``'fork'``. See :ref:`multiprocessing-start-methods`." msgstr "" -":mod:`multiprocessing`: O método de inicialização padrão será alterado para " +":mod:`multiprocessing`: o método de inicialização padrão será alterado para " "um mais seguro no Linux, BSDs e outras plataformas POSIX não-macOS onde " "``'fork'`` é atualmente o padrão (:gh:`84559`). Adicionar um aviso de tempo " "de execução sobre isso foi considerado muito perturbador, pois não se espera " @@ -214,7 +207,7 @@ msgstr "" "explicitamente quando seu código *requer* ``'fork'``. Veja :ref:" "`multiprocessing-start-methods`." -#: ../../deprecations/pending-removal-in-3.14.rst:80 +#: ../../deprecations/pending-removal-in-3.14.rst:77 msgid "" ":mod:`pathlib`: :meth:`~pathlib.PurePath.is_relative_to` and :meth:`~pathlib." "PurePath.relative_to`: passing additional arguments is deprecated." @@ -222,7 +215,7 @@ msgstr "" ":mod:`pathlib`: :meth:`~pathlib.PurePath.is_relative_to` e :meth:`~pathlib." "PurePath.relative_to`: passar argumentos adicionais foi descontinuado." -#: ../../deprecations/pending-removal-in-3.14.rst:84 +#: ../../deprecations/pending-removal-in-3.14.rst:81 msgid "" ":mod:`pkgutil`: :func:`~pkgutil.find_loader` and :func:`~pkgutil.get_loader` " "now raise :exc:`DeprecationWarning`; use :func:`importlib.util.find_spec` " @@ -232,57 +225,37 @@ msgstr "" "agora levantam :exc:`DeprecationWarning`; use :func:`importlib.util." "find_spec` em vez disto. (Contribuição de Nikita Sobolev em :gh:`97850`.)" -#: ../../deprecations/pending-removal-in-3.14.rst:89 +#: ../../deprecations/pending-removal-in-3.14.rst:86 msgid ":mod:`pty`:" msgstr ":mod:`pty`:" -#: ../../deprecations/pending-removal-in-3.14.rst:91 +#: ../../deprecations/pending-removal-in-3.14.rst:88 msgid "``master_open()``: use :func:`pty.openpty`." msgstr "``master_open()``: use :func:`pty.openpty`." -#: ../../deprecations/pending-removal-in-3.14.rst:92 +#: ../../deprecations/pending-removal-in-3.14.rst:89 msgid "``slave_open()``: use :func:`pty.openpty`." msgstr "``slave_open()``: use :func:`pty.openpty`." -#: ../../deprecations/pending-removal-in-3.14.rst:94 +#: ../../deprecations/pending-removal-in-3.14.rst:91 msgid ":mod:`sqlite3`:" msgstr ":mod:`sqlite3`:" -#: ../../deprecations/pending-removal-in-3.14.rst:96 +#: ../../deprecations/pending-removal-in-3.14.rst:93 msgid ":data:`~sqlite3.version` and :data:`~sqlite3.version_info`." msgstr ":data:`~sqlite3.version` e :data:`~sqlite3.version_info`." -#: ../../deprecations/pending-removal-in-3.14.rst:98 +#: ../../deprecations/pending-removal-in-3.14.rst:95 msgid "" ":meth:`~sqlite3.Cursor.execute` and :meth:`~sqlite3.Cursor.executemany` if :" "ref:`named placeholders ` are used and *parameters* is " "a sequence instead of a :class:`dict`." msgstr "" ":meth:`~sqlite3.Cursor.execute` e :meth:`~sqlite3.Cursor.executemany` se :" -"ref:`espaços reservados nomeados ` forem usados ​​e " +"ref:`espaços reservados nomeados ` forem usados e " "*parameters* for uma sequência em vez de um :class:`dict` ." -#: ../../deprecations/pending-removal-in-3.14.rst:102 -msgid "" -"date and datetime adapter, date and timestamp converter: see the :mod:" -"`sqlite3` documentation for suggested replacement recipes." -msgstr "" -"adaptador de data e hora, conversor de registro de data e hora: veja a " -"documentação de :mod:`sqlite3` para receitas de substituição sugeridas." - -#: ../../deprecations/pending-removal-in-3.14.rst:105 -msgid "" -":class:`types.CodeType`: Accessing :attr:`~codeobject.co_lnotab` was " -"deprecated in :pep:`626` since 3.10 and was planned to be removed in 3.12, " -"but it only got a proper :exc:`DeprecationWarning` in 3.12. May be removed " -"in 3.14. (Contributed by Nikita Sobolev in :gh:`101866`.)" -msgstr "" -":class:`types.CodeType`: O acesso a :attr:`~codeobject.co_lnotab` foi " -"descontinuado na :pep:`626` desde 3.10 e foi planejado para ser removido em " -"3.12, mas só recebeu uma :exc:`DeprecationWarning` adequada em 3.12. Pode " -"ser removido em 3.14. (Contribuição de Nikita Sobolev em :gh:`101866`.)" - -#: ../../deprecations/pending-removal-in-3.14.rst:112 +#: ../../deprecations/pending-removal-in-3.14.rst:99 msgid "" ":mod:`typing`: :class:`~typing.ByteString`, deprecated since Python 3.9, now " "causes a :exc:`DeprecationWarning` to be emitted when it is used." @@ -290,7 +263,7 @@ msgstr "" ":mod:`typing`: :class:`~typing.ByteString`, descontinuado desde Python 3.9, " "agora faz com que uma :exc:`DeprecationWarning` seja emitida quando é usado." -#: ../../deprecations/pending-removal-in-3.14.rst:115 +#: ../../deprecations/pending-removal-in-3.14.rst:102 msgid "" ":mod:`urllib`: :class:`!urllib.parse.Quoter` is deprecated: it was not " "intended to be a public API. (Contributed by Gregory P. Smith in :gh:" @@ -306,149 +279,334 @@ msgid "Pending Removal in Python 3.15" msgstr "Remoção pendente no Python 3.15" #: ../../deprecations/pending-removal-in-3.15.rst:4 +#: ../../deprecations/pending-removal-in-3.16.rst:4 +msgid "The import system:" +msgstr "O sistema de importação:" + +#: ../../deprecations/pending-removal-in-3.15.rst:6 msgid "" -":class:`http.server.CGIHTTPRequestHandler` will be removed along with its " -"related ``--cgi`` flag to ``python -m http.server``. It was obsolete and " -"rarely used. No direct replacement exists. *Anything* is better than CGI " -"to interface a web server with a request handler." +"Setting :attr:`~module.__cached__` on a module while failing to set :attr:" +"`__spec__.cached ` is deprecated. In " +"Python 3.15, :attr:`!__cached__` will cease to be set or take into " +"consideration by the import system or standard library. (:gh:`97879`)" msgstr "" -":class:`http.server.CGIHTTPRequestHandler` será removido junto com seu " -"sinalizador relacionado ``--cgi`` para ``python -m http.server``. Estava " -"descontinuado e raramente usado. Não existe substituição direta. *Qualquer " -"coisa* é melhor que CGI para fazer a interface de um servidor web com um " -"manipulador de solicitações." +"A definição de :attr:`~module.__cached__` em um módulo enquanto falha na " +"definição de :attr:`__spec__.cached ` " +"está descontinuado. No Python 3.15, :attr:`!__cached__` deixará de ser " +"definido ou levado em consideração pelo sistema de importação ou pela " +"biblioteca padrão. (:gh:`97879`)" -#: ../../deprecations/pending-removal-in-3.15.rst:9 +#: ../../deprecations/pending-removal-in-3.15.rst:11 msgid "" -":class:`locale`: :func:`locale.getdefaultlocale` was deprecated in Python " -"3.11 and originally planned for removal in Python 3.13 (:gh:`90817`), but " -"removal has been postponed to Python 3.15. Use :func:`locale.setlocale()`, :" -"func:`locale.getencoding()` and :func:`locale.getlocale()` instead. " -"(Contributed by Hugo van Kemenade in :gh:`111187`.)" +"Setting :attr:`~module.__package__` on a module while failing to set :attr:" +"`__spec__.parent ` is deprecated. In " +"Python 3.15, :attr:`!__package__` will cease to be set or take into " +"consideration by the import system or standard library. (:gh:`97879`)" msgstr "" -":class:`locale`: :func:`locale.getdefaultlocale` foi descontinuada no Python " -"3.11 e originalmente planejada para remoção no Python 3.13 (:gh:`90817`), " -"mas a remoção foi adiada para o Python 3.15. Use :func:`locale." -"setlocale()`, :func:`locale.getencoding()` e :func:`locale.getlocale()` em " -"vez disso. (Contribuição de Hugo van Kemenade em :gh:`111187`.)" +"A definição de :attr:`~module.__package__` em um módulo enquanto falha na " +"definição de :attr:`__spec__.parent ` " +"está descontinuado. No Python 3.15, :attr:`!__package__` deixará de ser " +"definido ou levado em consideração pelo sistema de importação ou pela " +"biblioteca padrão. (:gh:`97879`)" #: ../../deprecations/pending-removal-in-3.15.rst:16 +msgid ":mod:`ctypes`:" +msgstr ":mod:`ctypes`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:18 msgid "" -":mod:`pathlib`: :meth:`pathlib.PurePath.is_reserved` is deprecated and " -"scheduled for removal in Python 3.15. Use :func:`os.path.isreserved` to " -"detect reserved paths on Windows." +"The undocumented :func:`!ctypes.SetPointerType` function has been deprecated " +"since Python 3.13." msgstr "" -":mod:`pathlib`: :meth:`pathlib.PurePath.is_reserved` está descontinuado e " -"agendado para remoção no Python 3.15. Use :func:`os.path.isreserved` para " -"detectar caminhos reservados no Windows." +"A função não documentada :func:`!ctypes.SetPointerType` foi descontinuada " +"desde o Python 3.13." #: ../../deprecations/pending-removal-in-3.15.rst:21 +msgid ":mod:`http.server`:" +msgstr ":mod:`http.server`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:23 msgid "" -":mod:`platform`: :func:`~platform.java_ver` is deprecated and will be " -"removed in 3.15. It was largely untested, had a confusing API, and was only " -"useful for Jython support. (Contributed by Nikita Sobolev in :gh:`116349`.)" +"The obsolete and rarely used :class:`~http.server.CGIHTTPRequestHandler` has " +"been deprecated since Python 3.13. No direct replacement exists. *Anything* " +"is better than CGI to interface a web server with a request handler." msgstr "" -":mod:`platform`: :func:`~platform.java_ver` está descontinuada e será " -"removida na versão 3.15. Ela não foi testada em grande parte, tinha uma API " -"confusa e só era útil para suporte a Jython. (Contribuição de Nikita Sobolev " -"em :gh:`116349`.)" +"A classe obsoleta e raramente usada :class:`~http.server." +"CGIHTTPRequestHandler` foi descontinuada desde o Python 3.13. Não existe " +"substituição direta. *Qualquer coisa* é melhor que CGI para fazer a " +"interface de um servidor web com um manipulador de requisição." -#: ../../deprecations/pending-removal-in-3.15.rst:27 +#: ../../deprecations/pending-removal-in-3.15.rst:29 msgid "" -":mod:`threading`: Passing any arguments to :func:`threading.RLock` is now " -"deprecated. C version allows any numbers of args and kwargs, but they are " -"just ignored. Python version does not allow any arguments. All arguments " -"will be removed from :func:`threading.RLock` in Python 3.15. (Contributed by " -"Nikita Sobolev in :gh:`102029`.)" +"The :option:`!--cgi` flag to the :program:`python -m http.server` command-" +"line interface has been deprecated since Python 3.13." msgstr "" -":mod:`threading`: Passar qualquer argumento para :func:`threading.RLock` " -"agora está descontinuado. A versão C permite qualquer número de args e " -"kwargs, mas eles são simplesmente ignorados. A versão Python não permite " -"nenhum argumento. Todos os argumentos serão removidos de :func:`threading." -"RLock` no Python 3.15. (Contribuição de Nikita Sobolev em :gh:`102029`.)" +"O sinalizador :option:`!--cgi` para a interface de linha de comando :program:" +"`python -m http.server` foi descontinuado desde o Python 3.13." + +#: ../../deprecations/pending-removal-in-3.15.rst:32 +#: ../../deprecations/pending-removal-in-future.rst:56 +msgid ":mod:`importlib`:" +msgstr ":mod:`importlib`:" #: ../../deprecations/pending-removal-in-3.15.rst:34 -msgid ":class:`typing.NamedTuple`:" -msgstr ":class:`typing.NamedTuple`:" +msgid "``load_module()`` method: use ``exec_module()`` instead." +msgstr "Método ``load_module()``: use ``exec_module()``." #: ../../deprecations/pending-removal-in-3.15.rst:36 +msgid ":class:`locale`:" +msgstr ":class:`locale`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:38 msgid "" -"The undocumented keyword argument syntax for creating :class:`!NamedTuple` " -"classes (``NT = NamedTuple(\"NT\", x=int)``) is deprecated, and will be " -"disallowed in 3.15. Use the class-based syntax or the functional syntax " -"instead." +"The :func:`~locale.getdefaultlocale` function has been deprecated since " +"Python 3.11. Its removal was originally planned for Python 3.13 (:gh:" +"`90817`), but has been postponed to Python 3.15. Use :func:`~locale." +"getlocale`, :func:`~locale.setlocale`, and :func:`~locale.getencoding` " +"instead. (Contributed by Hugo van Kemenade in :gh:`111187`.)" msgstr "" -"A sintaxe de argumento nomeado não documentada para criar classes :class:`!" -"NamedTuple` (``NT = NamedTuple(\"NT\", x=int)``) está descontinuada e não " -"será permitida em 3.15. Use a sintaxe baseada em classe ou a sintaxe " -"funcional." - -#: ../../deprecations/pending-removal-in-3.15.rst:40 -msgid "" -"When using the functional syntax to create a :class:`!NamedTuple` class, " -"failing to pass a value to the *fields* parameter (``NT = " -"NamedTuple(\"NT\")``) is deprecated. Passing ``None`` to the *fields* " -"parameter (``NT = NamedTuple(\"NT\", None)``) is also deprecated. Both will " -"be disallowed in Python 3.15. To create a :class:`!NamedTuple` class with 0 " -"fields, use ``class NT(NamedTuple): pass`` or ``NT = NamedTuple(\"NT\", " -"[])``." -msgstr "" -"Ao usar a sintaxe funcional para criar uma classe :class:`!NamedTuple`, " -"falhar ao passar um valor para o parâmetro *fields* (``NT = " -"NamedTuple(\"NT\")``) está descontinuada. Passar ``None`` para o parâmetro " -"*fields* (``NT = NamedTuple(\"NT\", None)``) também está descontinuada. " -"Ambos não serão permitidos no Python 3.15. Para criar uma classe :class:`!" -"NamedTuple` com 0 campos, use ``class NT(NamedTuple): pass`` ou ``NT = " -"NamedTuple(\"NT\", [])``." - -#: ../../deprecations/pending-removal-in-3.15.rst:47 -msgid "" -":class:`typing.TypedDict`: When using the functional syntax to create a :" -"class:`!TypedDict` class, failing to pass a value to the *fields* parameter " -"(``TD = TypedDict(\"TD\")``) is deprecated. Passing ``None`` to the *fields* " -"parameter (``TD = TypedDict(\"TD\", None)``) is also deprecated. Both will " -"be disallowed in Python 3.15. To create a :class:`!TypedDict` class with 0 " -"fields, use ``class TD(TypedDict): pass`` or ``TD = TypedDict(\"TD\", {})``." -msgstr "" -":class:`typing.TypedDict`: Ao usar a sintaxe funcional para criar uma " -"classe :class:`!TypedDict`, falhar ao passar um valor para o parâmetro " -"*fields* (``TD = TypedDict(\"TD\")``) está descontinuada. Passar ``None`` " -"para o parâmetro *fields* (``TD = TypedDict(\"TD\", None)``) também está " -"descontinuada. Ambos não serão permitidos no Python 3.15. Para criar uma " -"classe :class:`!TypedDict` com 0 campos, use ``class TD(TypedDict): pass`` " -"ou ``TD = TypedDict(\"TD\", {})``." +"A função :func:`~locale.getdefaultlocale` foi descontinuada desde o Python " +"3.11. Sua remoção foi planejada originalmente para o Python 3.13 (:gh:" +"`90817`), mas foi adiada para o Python 3.15. Em vez disso, use :func:" +"`~locale.getlocale`, :func:`~locale.setlocale` e :func:`~locale." +"getencoding`. (Contribuição de Hugo van Kemenade em :gh:`111187`.)" + +#: ../../deprecations/pending-removal-in-3.15.rst:46 +msgid ":mod:`pathlib`:" +msgstr ":mod:`pathlib`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:48 +msgid "" +":meth:`.PurePath.is_reserved` has been deprecated since Python 3.13. Use :" +"func:`os.path.isreserved` to detect reserved paths on Windows." +msgstr "" +":meth:`.PurePath.is_reserved` foi descontinuado desde o Python 3.13. Use :" +"func:`os.path.isreserved` para detectar caminhos reservados no Windows." + +#: ../../deprecations/pending-removal-in-3.15.rst:52 +msgid ":mod:`platform`:" +msgstr ":mod:`platform`:" #: ../../deprecations/pending-removal-in-3.15.rst:54 msgid "" -":mod:`wave`: Deprecate the ``getmark()``, ``setmark()`` and ``getmarkers()`` " -"methods of the :class:`wave.Wave_read` and :class:`wave.Wave_write` classes. " -"They will be removed in Python 3.15. (Contributed by Victor Stinner in :gh:" -"`105096`.)" +":func:`~platform.java_ver` has been deprecated since Python 3.13. This " +"function is only useful for Jython support, has a confusing API, and is " +"largely untested." +msgstr "" +":func:`~platform.java_ver` foi descontinuada desde o Python 3.13. Esta " +"função é útil apenas para suporte Jython, tem uma API confusa e é amplamente " +"não testada." + +#: ../../deprecations/pending-removal-in-3.15.rst:58 +msgid ":mod:`sysconfig`:" +msgstr ":mod:`sysconfig`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:60 +msgid "" +"The *check_home* argument of :func:`sysconfig.is_python_build` has been " +"deprecated since Python 3.12." +msgstr "" +"O argumento *check_home* de :func:`sysconfig.is_python_build` foi " +"descontinuado desde o Python 3.12." + +#: ../../deprecations/pending-removal-in-3.15.rst:63 +msgid ":mod:`threading`:" +msgstr ":mod:`threading`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:65 +msgid "" +":func:`~threading.RLock` will take no arguments in Python 3.15. Passing any " +"arguments has been deprecated since Python 3.14, as the Python version does " +"not permit any arguments, but the C version allows any number of positional " +"or keyword arguments, ignoring every argument." +msgstr "" +":func:`~threading.RLock` não aceitará argumentos no Python 3.15. A passagem " +"quaisquer argumentos foi descontinuada desde o Python 3.14, pois a versão " +"Python não permite nenhum argumento, mas a versão C permite qualquer número " +"de argumentos posicionais ou nomeados, ignorando todos os argumentos." + +#: ../../deprecations/pending-removal-in-3.15.rst:71 +msgid ":mod:`types`:" +msgstr ":mod:`types`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:73 +msgid "" +":class:`types.CodeType`: Accessing :attr:`~codeobject.co_lnotab` was " +"deprecated in :pep:`626` since 3.10 and was planned to be removed in 3.12, " +"but it only got a proper :exc:`DeprecationWarning` in 3.12. May be removed " +"in 3.15. (Contributed by Nikita Sobolev in :gh:`101866`.)" msgstr "" -":mod:`wave`: Descontinua os métodos ``getmark()``, ``setmark()`` e " -"``getmarkers()`` das classes :class:`wave.Wave_read` e :class:`wave." -"Wave_write`. Eles serão removidos no Python 3.15. (Contribuição de Victor " -"Stinner em :gh:`105096`.)" +":class:`types.CodeType`: o acesso a :attr:`~codeobject.co_lnotab` foi " +"descontinuado na :pep:`626` desde 3.10 e foi planejado para ser removido em " +"3.12, mas só recebeu uma :exc:`DeprecationWarning` adequada em 3.12. Pode " +"ser removido em 3.15. (Contribuição de Nikita Sobolev em :gh:`101866`.)" + +#: ../../deprecations/pending-removal-in-3.15.rst:80 +msgid ":mod:`typing`:" +msgstr ":mod:`typing`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:82 +msgid "" +"The undocumented keyword argument syntax for creating :class:`~typing." +"NamedTuple` classes (e.g. ``Point = NamedTuple(\"Point\", x=int, y=int)``) " +"has been deprecated since Python 3.13. Use the class-based syntax or the " +"functional syntax instead." +msgstr "" +"A sintaxe de argumento nomeado não documentada para criar classes :class:" +"`~typing.NamedTuple` (por exemplo, ``Point = NamedTuple(\"Point\", x=int, " +"y=int)``) foi descontinuada desde o Python 3.13. Use a sintaxe baseada em " +"classe ou a sintaxe funcional em vez disso." + +#: ../../deprecations/pending-removal-in-3.15.rst:88 +msgid "" +"When using the functional syntax of :class:`~typing.TypedDict`\\s, failing " +"to pass a value to the *fields* parameter (``TD = TypedDict(\"TD\")``) or " +"passing ``None`` (``TD = TypedDict(\"TD\", None)``) has been deprecated " +"since Python 3.13. Use ``class TD(TypedDict): pass`` or ``TD = " +"TypedDict(\"TD\", {})`` to create a TypedDict with zero field." +msgstr "" +"Ao usar a sintaxe funcional de :class:`~typing.TypedDict`\\s, não passar um " +"valor para o parâmetro *fields* (``TD = TypedDict(\"TD\")``) ou passar " +"``None`` (``TD = TypedDict(\"TD\", None)``) foi está descontinuado desde o " +"Python 3.13. Use ``class TD(TypedDict): pass`` ou ``TD = TypedDict(\"TD\", " +"{})`` para criar uma classe TypedDict com nenhum campo." + +#: ../../deprecations/pending-removal-in-3.15.rst:95 +msgid "" +"The :func:`typing.no_type_check_decorator` decorator function has been " +"deprecated since Python 3.13. After eight years in the :mod:`typing` module, " +"it has yet to be supported by any major type checker." +msgstr "" +"A função decoradora :func:`typing.no_type_check_decorator` foi descontinuada " +"desde o Python 3.13. Após oito anos no módulo :mod:`typing`, ela ainda não " +"foi suportada por nenhum verificador de tipo importante." + +#: ../../deprecations/pending-removal-in-3.15.rst:100 +msgid ":mod:`wave`:" +msgstr ":mod:`wave`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:102 +msgid "" +"The :meth:`~wave.Wave_read.getmark`, :meth:`!setmark`, and :meth:`~wave." +"Wave_read.getmarkers` methods of the :class:`~wave.Wave_read` and :class:" +"`~wave.Wave_write` classes have been deprecated since Python 3.13." +msgstr "" +"Os métodos :meth:`~wave.Wave_read.getmark`, :meth:`!setmark` e :meth:`~wave." +"Wave_read.getmarkers` das classes :class:`~wave.Wave_read` e :class:`~wave." +"Wave_write` foram descontinuados desde o Python 3.13." #: ../../deprecations/pending-removal-in-3.16.rst:2 -msgid "Pending Removal in Python 3.16" +msgid "Pending removal in Python 3.16" msgstr "Remoção pendente no Python 3.16" -#: ../../deprecations/pending-removal-in-3.16.rst:4 +#: ../../deprecations/pending-removal-in-3.16.rst:6 +msgid "" +"Setting :attr:`~module.__loader__` on a module while failing to set :attr:" +"`__spec__.loader ` is deprecated. In " +"Python 3.16, :attr:`!__loader__` will cease to be set or taken into " +"consideration by the import system or the standard library." +msgstr "" +"A definição de :attr:`~module.__loader__` em um módulo enquanto falha na " +"definição de :attr:`__spec__.loader ` " +"está descontinuado. No Python 3.16, :attr:`!__loader__` deixará de ser " +"definido ou levado em consideração pelo sistema de importação ou pela " +"biblioteca padrão." + +#: ../../deprecations/pending-removal-in-3.16.rst:11 +msgid ":mod:`array`:" +msgstr ":mod:`array`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:13 +msgid "" +"The ``'u'`` format code (:c:type:`wchar_t`) has been deprecated in " +"documentation since Python 3.3 and at runtime since Python 3.13. Use the " +"``'w'`` format code (:c:type:`Py_UCS4`) for Unicode characters instead." +msgstr "" +"O código de formato ``'u'`` (:c:type:`wchar_t`) foi descontinuado na " +"documentação desde o Python 3.3 e do ambiente de execução desde o Python " +"3.13. Em vez disso, use o código de formato ``'w'`` (:c:type:`Py_UCS4`) para " +"caracteres Unicode." + +#: ../../deprecations/pending-removal-in-3.16.rst:21 +msgid "" +":func:`!asyncio.iscoroutinefunction` is deprecated and will be removed in " +"Python 3.16, use :func:`inspect.iscoroutinefunction` instead. (Contributed " +"by Jiahao Li and Kumar Aditya in :gh:`122875`.)" +msgstr "" +":func:`!asyncio.iscoroutinefunction` foi descontinuado e será removido no " +"Python 3.16, use :func:`inspect.iscoroutinefunction` em vez disso. " +"(Contribuição de Jiahao Li e Kumar Aditya em :gh:`122875`.)" + +#: ../../deprecations/pending-removal-in-3.16.rst:26 +#: ../../deprecations/pending-removal-in-future.rst:10 +msgid ":mod:`builtins`:" +msgstr ":mod:`builtins`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:28 +msgid "" +"Bitwise inversion on boolean types, ``~True`` or ``~False`` has been " +"deprecated since Python 3.12, as it produces surprising and unintuitive " +"results (``-2`` and ``-1``). Use ``not x`` instead for the logical negation " +"of a Boolean. In the rare case that you need the bitwise inversion of the " +"underlying integer, convert to ``int`` explicitly (``~int(x)``)." +msgstr "" +"A inversão bit a bit em tipos booleanos, ``~True`` ou ``~False`` foi " +"descontinuada desde o Python 3.12, pois produz resultados surpreendentes e " +"não intuitivos (``-2`` e ``-1``). Em vez disso, use ``not x`` para a negação " +"lógica de um booleano. No caso raro de você precisar da inversão bit a bit " +"do inteiro subjacente, converta para ``int`` explicitamente (``~int(x)``)." + +#: ../../deprecations/pending-removal-in-3.16.rst:35 +msgid ":mod:`shutil`:" +msgstr ":mod:`shutil`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:37 msgid "" -":mod:`array`: :class:`array.array` ``'u'`` type (:c:type:`wchar_t`): use the " -"``'w'`` type instead (``Py_UCS4``)." +"The :class:`!ExecError` exception has been deprecated since Python 3.14. It " +"has not been used by any function in :mod:`!shutil` since Python 3.4, and is " +"now an alias of :exc:`RuntimeError`." msgstr "" -":mod:`array`: :class:`array.array`: tipo ``'u'`` (:c:type:`wchar_t`): use o " -"tipo ``'w'`` (``Py_UCS4``)." +"A exceção :class:`!ExecError` foi descontinuada desde o Python 3.14. Ela não " +"foi usada por nenhuma função em :mod:`!shutil` desde o Python 3.4, e agora é " +"um alias de :exc:`RuntimeError`." + +#: ../../deprecations/pending-removal-in-3.16.rst:42 +msgid ":mod:`symtable`:" +msgstr ":mod:`symtable`:" -#: ../../deprecations/pending-removal-in-3.16.rst:8 +#: ../../deprecations/pending-removal-in-3.16.rst:44 msgid "" -":mod:`symtable`: Deprecate :meth:`symtable.Class.get_methods` due to the " -"lack of interest. (Contributed by Bénédikt Tran in :gh:`119698`.)" +"The :meth:`Class.get_methods ` method has been " +"deprecated since Python 3.14." msgstr "" -":mod:`symtable`: Descontinua :meth:`symtable.Class.get_methods` por falta de " -"interesse. (Contribuição de Bénédikt Tran em :gh:`119698`.)" +"O método :meth:`Class.get_methods ` foi " +"descontinuado desde o Python 3.14." + +#: ../../deprecations/pending-removal-in-3.16.rst:47 +msgid ":mod:`sys`:" +msgstr ":mod:`sys`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:49 +msgid "" +"The :func:`~sys._enablelegacywindowsfsencoding` function has been deprecated " +"since Python 3.13. Use the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` " +"environment variable instead." +msgstr "" +"A função :func:`~sys._enablelegacywindowsfsencoding` foi descontinuada desde " +"o Python 3.13. Em vez disso, use a variável de ambiente :envvar:" +"`PYTHONLEGACYWINDOWSFSENCODING`." + +#: ../../deprecations/pending-removal-in-3.16.rst:53 +msgid ":mod:`tarfile`:" +msgstr ":mod:`tarfile`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:55 +msgid "" +"The undocumented and unused :attr:`!TarFile.tarfile` attribute has been " +"deprecated since Python 3.13." +msgstr "" +"O atributo não documentado e não utilizado :attr:`!TarFile.tarfile` foi " +"descontinuado desde o Python 3.13." #: ../../deprecations/c-api-pending-removal-in-future.rst:2 #: ../../deprecations/pending-removal-in-future.rst:2 @@ -468,36 +626,24 @@ msgid "" ":mod:`argparse`: Nesting argument groups and nesting mutually exclusive " "groups are deprecated." msgstr "" -":mod:`argparse`: O aninhamento de grupos de argumentos e o aninhamento de " +":mod:`argparse`: o aninhamento de grupos de argumentos e o aninhamento de " "grupos mutuamente exclusivos estão descontinuados." -#: ../../deprecations/pending-removal-in-future.rst:10 -msgid ":mod:`array`'s ``'u'`` format code (:gh:`57281`)" -msgstr "código de formatação ``'u'`` do :mod:`array` (:gh:`57281`)" - #: ../../deprecations/pending-removal-in-future.rst:12 -msgid ":mod:`builtins`:" -msgstr ":mod:`builtins`:" - -#: ../../deprecations/pending-removal-in-future.rst:14 -msgid "``~bool``, bitwise inversion on bool." -msgstr "``~bool``, inversão bit a bit em booleanos." - -#: ../../deprecations/pending-removal-in-future.rst:15 msgid "``bool(NotImplemented)``." msgstr "``bool(NotImplemented)``." -#: ../../deprecations/pending-removal-in-future.rst:16 +#: ../../deprecations/pending-removal-in-future.rst:13 msgid "" "Generators: ``throw(type, exc, tb)`` and ``athrow(type, exc, tb)`` signature " "is deprecated: use ``throw(exc)`` and ``athrow(exc)`` instead, the single " "argument signature." msgstr "" -"Geradores: A assinatura ``throw(type, exc, tb)`` e ``athrow(type, exc, tb)`` " +"Geradores: a assinatura ``throw(type, exc, tb)`` e ``athrow(type, exc, tb)`` " "está descontinuada: use ``throw(exc)`` e ``athrow(exc)``, a assinatura do " "argumento único." -#: ../../deprecations/pending-removal-in-future.rst:19 +#: ../../deprecations/pending-removal-in-future.rst:16 msgid "" "Currently Python accepts numeric literals immediately followed by keywords, " "for example ``0in x``, ``1or x``, ``0if 1else 2``. It allows confusing and " @@ -518,7 +664,7 @@ msgstr "" "e :keyword:`or`. Em uma versão futura, será alterado para um erro de " "sintaxe. (:gh:`87999`)" -#: ../../deprecations/pending-removal-in-future.rst:27 +#: ../../deprecations/pending-removal-in-future.rst:24 msgid "" "Support for ``__index__()`` and ``__int__()`` method returning non-int type: " "these methods will be required to return an instance of a strict subclass " @@ -528,7 +674,7 @@ msgstr "" "int: esses métodos serão necessários para retornar uma instância de uma " "subclasse estrita de :class:`int`." -#: ../../deprecations/pending-removal-in-future.rst:30 +#: ../../deprecations/pending-removal-in-future.rst:27 msgid "" "Support for ``__float__()`` method returning a strict subclass of :class:" "`float`: these methods will be required to return an instance of :class:" @@ -538,7 +684,7 @@ msgstr "" "class:`float`: esses métodos serão necessários para retornar uma instância " "de :class:`float`." -#: ../../deprecations/pending-removal-in-future.rst:33 +#: ../../deprecations/pending-removal-in-future.rst:30 msgid "" "Support for ``__complex__()`` method returning a strict subclass of :class:" "`complex`: these methods will be required to return an instance of :class:" @@ -548,11 +694,11 @@ msgstr "" "class:`complex`: esses métodos serão necessários para retornar uma instância " "de :class:`complex`." -#: ../../deprecations/pending-removal-in-future.rst:36 +#: ../../deprecations/pending-removal-in-future.rst:33 msgid "Delegation of ``int()`` to ``__trunc__()`` method." msgstr "Delegação do método ``int()`` para o ``__trunc__()``." -#: ../../deprecations/pending-removal-in-future.rst:37 +#: ../../deprecations/pending-removal-in-future.rst:34 msgid "" "Passing a complex number as the *real* or *imag* argument in the :func:" "`complex` constructor is now deprecated; it should only be passed as a " @@ -564,28 +710,28 @@ msgstr "" "único argumento posicional. (Contribuição de Serhiy Storchaka em :gh:" "`109218`.)" -#: ../../deprecations/pending-removal-in-future.rst:42 +#: ../../deprecations/pending-removal-in-future.rst:39 msgid "" ":mod:`calendar`: ``calendar.January`` and ``calendar.February`` constants " "are deprecated and replaced by :data:`calendar.JANUARY` and :data:`calendar." "FEBRUARY`. (Contributed by Prince Roshan in :gh:`103636`.)" msgstr "" -":mod:`calendar`: As constantes ``calendar.January`` e ``calendar.February`` " +":mod:`calendar`: as constantes ``calendar.January`` e ``calendar.February`` " "foram descontinuadas e substituídas por :data:`calendar.JANUARY` e :data:" "`calendar.FEBRUARY`. (Contribuição de Prince Roshan em :gh:`103636`.)" -#: ../../deprecations/pending-removal-in-future.rst:47 +#: ../../deprecations/pending-removal-in-future.rst:44 msgid "" ":attr:`codeobject.co_lnotab`: use the :meth:`codeobject.co_lines` method " "instead." msgstr "" ":attr:`codeobject.co_lnotab`: use o método :meth:`codeobject.co_lines`." -#: ../../deprecations/pending-removal-in-future.rst:50 +#: ../../deprecations/pending-removal-in-future.rst:47 msgid ":mod:`datetime`:" msgstr ":mod:`datetime`:" -#: ../../deprecations/pending-removal-in-future.rst:52 +#: ../../deprecations/pending-removal-in-future.rst:49 msgid "" ":meth:`~datetime.datetime.utcnow`: use ``datetime.datetime.now(tz=datetime." "UTC)``." @@ -593,7 +739,7 @@ msgstr "" ":meth:`~datetime.datetime.utcnow`: use ``datetime.datetime.now(tz=datetime." "UTC)``." -#: ../../deprecations/pending-removal-in-future.rst:54 +#: ../../deprecations/pending-removal-in-future.rst:51 msgid "" ":meth:`~datetime.datetime.utcfromtimestamp`: use ``datetime.datetime." "fromtimestamp(timestamp, tz=datetime.UTC)``." @@ -601,68 +747,60 @@ msgstr "" ":meth:`~datetime.datetime.utcfromtimestamp`: use ``datetime.datetime." "fromtimestamp(timestamp, tz=datetime.UTC)``." -#: ../../deprecations/pending-removal-in-future.rst:57 +#: ../../deprecations/pending-removal-in-future.rst:54 msgid ":mod:`gettext`: Plural value must be an integer." -msgstr ":mod:`gettext`: O valor de plural deve ser um número inteiro." +msgstr ":mod:`gettext`: o valor de plural deve ser um número inteiro." -#: ../../deprecations/pending-removal-in-future.rst:59 -msgid ":mod:`importlib`:" -msgstr ":mod:`importlib`:" - -#: ../../deprecations/pending-removal-in-future.rst:61 -msgid "``load_module()`` method: use ``exec_module()`` instead." -msgstr "Método ``load_module()``: use ``exec_module()`` em vez disso." - -#: ../../deprecations/pending-removal-in-future.rst:62 +#: ../../deprecations/pending-removal-in-future.rst:58 msgid "" ":func:`~importlib.util.cache_from_source` *debug_override* parameter is " "deprecated: use the *optimization* parameter instead." msgstr "" "O parâmetro *debug_override* de :func:`~importlib.util.cache_from_source` " -"foi descontinuado: em vez disso, use o parâmetro *optimization*." +"foi descontinuado: use o parâmetro *optimization*." -#: ../../deprecations/pending-removal-in-future.rst:65 +#: ../../deprecations/pending-removal-in-future.rst:61 msgid ":mod:`importlib.metadata`:" msgstr ":mod:`importlib.metadata`:" -#: ../../deprecations/pending-removal-in-future.rst:67 +#: ../../deprecations/pending-removal-in-future.rst:63 msgid "``EntryPoints`` tuple interface." msgstr "Interface de tupla ``EntryPoints``." -#: ../../deprecations/pending-removal-in-future.rst:68 +#: ../../deprecations/pending-removal-in-future.rst:64 msgid "Implicit ``None`` on return values." msgstr "``None`` implícito nos valores de retorno." -#: ../../deprecations/pending-removal-in-future.rst:70 +#: ../../deprecations/pending-removal-in-future.rst:66 msgid "" ":mod:`logging`: the ``warn()`` method has been deprecated since Python 3.3, " -"use :meth:`~logging.warning()` instead." +"use :meth:`~logging.warning` instead." msgstr "" ":mod:`logging`: o método ``warn()`` foi descontinuado desde o Python 3.3, " -"use :meth:`~logging.warning()`." +"use :meth:`~logging.warning`." -#: ../../deprecations/pending-removal-in-future.rst:73 +#: ../../deprecations/pending-removal-in-future.rst:69 msgid "" ":mod:`mailbox`: Use of StringIO input and text mode is deprecated, use " "BytesIO and binary mode instead." msgstr "" -":mod:`mailbox`: O uso da entrada StringIO e do modo de texto foi " +":mod:`mailbox`: o uso da entrada StringIO e do modo de texto foi " "descontinuado; em vez disso, use BytesIO e o modo binário." -#: ../../deprecations/pending-removal-in-future.rst:76 +#: ../../deprecations/pending-removal-in-future.rst:72 msgid "" ":mod:`os`: Calling :func:`os.register_at_fork` in multi-threaded process." -msgstr ":mod:`os`: Chamar :func:`os.register_at_fork` em processo multithread." +msgstr ":mod:`os`: chame :func:`os.register_at_fork` em processo multithread." -#: ../../deprecations/pending-removal-in-future.rst:78 +#: ../../deprecations/pending-removal-in-future.rst:74 msgid "" ":class:`!pydoc.ErrorDuringImport`: A tuple value for *exc_info* parameter is " "deprecated, use an exception instance." msgstr "" -":class:`!pydoc.ErrorDuringImport`: Um valor de tupla para o parâmetro " +":class:`!pydoc.ErrorDuringImport`: um valor de tupla para o parâmetro " "*exc_info* foi descontinuado, use uma instância de exceção." -#: ../../deprecations/pending-removal-in-future.rst:81 +#: ../../deprecations/pending-removal-in-future.rst:77 msgid "" ":mod:`re`: More strict rules are now applied for numerical group references " "and group names in regular expressions. Only sequence of ASCII digits is " @@ -670,96 +808,88 @@ msgid "" "replacement strings can now only contain ASCII letters and digits and " "underscore. (Contributed by Serhiy Storchaka in :gh:`91760`.)" msgstr "" -":mod:`re`: Regras mais rigorosas agora são aplicadas para referências " +":mod:`re`: regras mais rigorosas agora são aplicadas para referências " "numéricas de grupos e nomes de grupos em expressões regulares. Apenas a " "sequência de dígitos ASCII agora é aceita como referência numérica. O nome " "do grupo em padrões de bytes e strings de substituição agora pode conter " "apenas letras e dígitos ASCII e sublinhado. (Contribuição de Serhiy " "Storchaka em :gh:`91760`.)" -#: ../../deprecations/pending-removal-in-future.rst:88 +#: ../../deprecations/pending-removal-in-future.rst:84 msgid "" ":mod:`!sre_compile`, :mod:`!sre_constants` and :mod:`!sre_parse` modules." msgstr "" "Módulos :mod:`!sre_compile`, :mod:`!sre_constants` e :mod:`!sre_parse`." -#: ../../deprecations/pending-removal-in-future.rst:90 +#: ../../deprecations/pending-removal-in-future.rst:86 msgid "" ":mod:`shutil`: :func:`~shutil.rmtree`'s *onerror* parameter is deprecated in " "Python 3.12; use the *onexc* parameter instead." msgstr "" -":mod:`shutil`: O parâmetro *onerror* de :func:`~shutil.rmtree` foi " +":mod:`shutil`: o parâmetro *onerror* de :func:`~shutil.rmtree` foi " "descontinuado no Python 3.12; use o parâmetro *onexc*." -#: ../../deprecations/pending-removal-in-future.rst:93 +#: ../../deprecations/pending-removal-in-future.rst:89 msgid ":mod:`ssl` options and protocols:" msgstr "Protocolos e opções de :mod:`ssl`" -#: ../../deprecations/pending-removal-in-future.rst:95 +#: ../../deprecations/pending-removal-in-future.rst:91 msgid ":class:`ssl.SSLContext` without protocol argument is deprecated." msgstr ":class:`ssl.SSLContext` sem argumento de protocolo foi descontinuado." -#: ../../deprecations/pending-removal-in-future.rst:96 +#: ../../deprecations/pending-removal-in-future.rst:92 msgid "" ":class:`ssl.SSLContext`: :meth:`~ssl.SSLContext.set_npn_protocols` and :meth:" "`!selected_npn_protocol` are deprecated: use ALPN instead." msgstr "" ":class:`ssl.SSLContext`: :meth:`~ssl.SSLContext.set_npn_protocols` e :meth:`!" -"selected_npn_protocol` foram descontinuados: use ALPN." +"selected_npn_protocol` foram descontinuados, use ALPN." -#: ../../deprecations/pending-removal-in-future.rst:99 +#: ../../deprecations/pending-removal-in-future.rst:95 msgid "``ssl.OP_NO_SSL*`` options" msgstr "Opções de ``ssl.OP_NO_SSL*``" -#: ../../deprecations/pending-removal-in-future.rst:100 +#: ../../deprecations/pending-removal-in-future.rst:96 msgid "``ssl.OP_NO_TLS*`` options" msgstr "Opções de ``ssl.OP_NO_TLS*``" -#: ../../deprecations/pending-removal-in-future.rst:101 +#: ../../deprecations/pending-removal-in-future.rst:97 msgid "``ssl.PROTOCOL_SSLv3``" msgstr "``ssl.PROTOCOL_SSLv3``" -#: ../../deprecations/pending-removal-in-future.rst:102 +#: ../../deprecations/pending-removal-in-future.rst:98 msgid "``ssl.PROTOCOL_TLS``" msgstr "``ssl.PROTOCOL_TLS``" -#: ../../deprecations/pending-removal-in-future.rst:103 +#: ../../deprecations/pending-removal-in-future.rst:99 msgid "``ssl.PROTOCOL_TLSv1``" msgstr "``ssl.PROTOCOL_TLSv1``" -#: ../../deprecations/pending-removal-in-future.rst:104 +#: ../../deprecations/pending-removal-in-future.rst:100 msgid "``ssl.PROTOCOL_TLSv1_1``" msgstr "``ssl.PROTOCOL_TLSv1_1``" -#: ../../deprecations/pending-removal-in-future.rst:105 +#: ../../deprecations/pending-removal-in-future.rst:101 msgid "``ssl.PROTOCOL_TLSv1_2``" msgstr "``ssl.PROTOCOL_TLSv1_2``" -#: ../../deprecations/pending-removal-in-future.rst:106 +#: ../../deprecations/pending-removal-in-future.rst:102 msgid "``ssl.TLSVersion.SSLv3``" msgstr "``ssl.TLSVersion.SSLv3``" -#: ../../deprecations/pending-removal-in-future.rst:107 +#: ../../deprecations/pending-removal-in-future.rst:103 msgid "``ssl.TLSVersion.TLSv1``" msgstr "``ssl.TLSVersion.TLSv1``" -#: ../../deprecations/pending-removal-in-future.rst:108 +#: ../../deprecations/pending-removal-in-future.rst:104 msgid "``ssl.TLSVersion.TLSv1_1``" msgstr "``ssl.TLSVersion.TLSv1_1``" -#: ../../deprecations/pending-removal-in-future.rst:110 -msgid "" -":func:`sysconfig.is_python_build` *check_home* parameter is deprecated and " -"ignored." -msgstr "" -"O parâmetro *check_home* de :func:`sysconfig.is_python_build` foi " -"descontinuado e é ignorado." - -#: ../../deprecations/pending-removal-in-future.rst:113 +#: ../../deprecations/pending-removal-in-future.rst:106 msgid ":mod:`threading` methods:" msgstr "Métodos de :mod:`threading`:" -#: ../../deprecations/pending-removal-in-future.rst:115 +#: ../../deprecations/pending-removal-in-future.rst:108 msgid "" ":meth:`!threading.Condition.notifyAll`: use :meth:`~threading.Condition." "notify_all`." @@ -767,11 +897,11 @@ msgstr "" ":meth:`!threading.Condition.notifyAll`: use :meth:`~threading.Condition." "notify_all`." -#: ../../deprecations/pending-removal-in-future.rst:116 +#: ../../deprecations/pending-removal-in-future.rst:109 msgid ":meth:`!threading.Event.isSet`: use :meth:`~threading.Event.is_set`." msgstr ":meth:`!threading.Event.isSet`: use :meth:`~threading.Event.is_set`." -#: ../../deprecations/pending-removal-in-future.rst:117 +#: ../../deprecations/pending-removal-in-future.rst:110 msgid "" ":meth:`!threading.Thread.isDaemon`, :meth:`threading.Thread.setDaemon`: use :" "attr:`threading.Thread.daemon` attribute." @@ -779,7 +909,7 @@ msgstr "" ":meth:`!threading.Thread.isDaemon`, :meth:`threading.Thread.setDaemon`: use " "o atributo :attr:`threading.Thread.daemon`." -#: ../../deprecations/pending-removal-in-future.rst:119 +#: ../../deprecations/pending-removal-in-future.rst:112 msgid "" ":meth:`!threading.Thread.getName`, :meth:`threading.Thread.setName`: use :" "attr:`threading.Thread.name` attribute." @@ -787,20 +917,20 @@ msgstr "" ":meth:`!threading.Thread.getName`, :meth:`threading.Thread.setName`: use o " "atributo :attr:`threading.Thread.name`." -#: ../../deprecations/pending-removal-in-future.rst:121 +#: ../../deprecations/pending-removal-in-future.rst:114 msgid ":meth:`!threading.currentThread`: use :meth:`threading.current_thread`." msgstr "" ":meth:`!threading.currentThread`: use :meth:`threading.current_thread`." -#: ../../deprecations/pending-removal-in-future.rst:122 +#: ../../deprecations/pending-removal-in-future.rst:115 msgid ":meth:`!threading.activeCount`: use :meth:`threading.active_count`." msgstr ":meth:`!threading.activeCount`: use :meth:`threading.active_count`." -#: ../../deprecations/pending-removal-in-future.rst:124 +#: ../../deprecations/pending-removal-in-future.rst:117 msgid ":class:`typing.Text` (:gh:`92332`)." msgstr ":class:`typing.Text` (:gh:`92332`)." -#: ../../deprecations/pending-removal-in-future.rst:126 +#: ../../deprecations/pending-removal-in-future.rst:119 msgid "" ":class:`unittest.IsolatedAsyncioTestCase`: it is deprecated to return a " "value that is not ``None`` from a test case." @@ -808,7 +938,7 @@ msgstr "" ":class:`unittest.IsolatedAsyncioTestCase`: foi descontinuado retornar um " "valor que não seja ``None`` de um caso de teste." -#: ../../deprecations/pending-removal-in-future.rst:129 +#: ../../deprecations/pending-removal-in-future.rst:122 msgid "" ":mod:`urllib.parse` deprecated functions: :func:`~urllib.parse.urlparse` " "instead" @@ -816,62 +946,62 @@ msgstr "" "Funções descontinuadas de :mod:`urllib.parse`: use :func:`~urllib.parse." "urlparse`" -#: ../../deprecations/pending-removal-in-future.rst:131 +#: ../../deprecations/pending-removal-in-future.rst:124 msgid "``splitattr()``" msgstr "``splitattr()``" -#: ../../deprecations/pending-removal-in-future.rst:132 +#: ../../deprecations/pending-removal-in-future.rst:125 msgid "``splithost()``" msgstr "``splithost()``" -#: ../../deprecations/pending-removal-in-future.rst:133 +#: ../../deprecations/pending-removal-in-future.rst:126 msgid "``splitnport()``" msgstr "``splitnport()``" -#: ../../deprecations/pending-removal-in-future.rst:134 +#: ../../deprecations/pending-removal-in-future.rst:127 msgid "``splitpasswd()``" msgstr "``splitpasswd()``" -#: ../../deprecations/pending-removal-in-future.rst:135 +#: ../../deprecations/pending-removal-in-future.rst:128 msgid "``splitport()``" msgstr "``splitport()``" -#: ../../deprecations/pending-removal-in-future.rst:136 +#: ../../deprecations/pending-removal-in-future.rst:129 msgid "``splitquery()``" msgstr "``splitquery()``" -#: ../../deprecations/pending-removal-in-future.rst:137 +#: ../../deprecations/pending-removal-in-future.rst:130 msgid "``splittag()``" msgstr "``splittag()``" -#: ../../deprecations/pending-removal-in-future.rst:138 +#: ../../deprecations/pending-removal-in-future.rst:131 msgid "``splittype()``" msgstr "``splittype()``" -#: ../../deprecations/pending-removal-in-future.rst:139 +#: ../../deprecations/pending-removal-in-future.rst:132 msgid "``splituser()``" msgstr "``splituser()``" -#: ../../deprecations/pending-removal-in-future.rst:140 +#: ../../deprecations/pending-removal-in-future.rst:133 msgid "``splitvalue()``" msgstr "``splitvalue()``" -#: ../../deprecations/pending-removal-in-future.rst:141 +#: ../../deprecations/pending-removal-in-future.rst:134 msgid "``to_bytes()``" msgstr "``to_bytes()``" -#: ../../deprecations/pending-removal-in-future.rst:143 +#: ../../deprecations/pending-removal-in-future.rst:136 msgid "" ":mod:`urllib.request`: :class:`~urllib.request.URLopener` and :class:" "`~urllib.request.FancyURLopener` style of invoking requests is deprecated. " "Use newer :func:`~urllib.request.urlopen` functions and methods." msgstr "" -":mod:`urllib.request`: O estilo de :class:`~urllib.request.URLopener` e :" +":mod:`urllib.request`: o estilo de :class:`~urllib.request.URLopener` e :" "class:`~urllib.request.FancyURLopener` de invocar solicitações foi " "descontinuado. Use as mais novas funções e métodos :func:`~urllib.request." "urlopen`." -#: ../../deprecations/pending-removal-in-future.rst:147 +#: ../../deprecations/pending-removal-in-future.rst:140 msgid "" ":mod:`wsgiref`: ``SimpleHandler.stdout.write()`` should not do partial " "writes." @@ -879,7 +1009,7 @@ msgstr "" ":mod:`wsgiref`: ``SimpleHandler.stdout.write()`` não deve fazer gravações " "parciais." -#: ../../deprecations/pending-removal-in-future.rst:150 +#: ../../deprecations/pending-removal-in-future.rst:143 msgid "" ":mod:`xml.etree.ElementTree`: Testing the truth value of an :class:`~xml." "etree.ElementTree.Element` is deprecated. In a future release it will always " @@ -891,7 +1021,7 @@ msgstr "" "sempre retornará ``True``. Em vez disso, prefira os testes explícitos " "``len(elem)`` ou ``elem is not None``." -#: ../../deprecations/pending-removal-in-future.rst:155 +#: ../../deprecations/pending-removal-in-future.rst:148 msgid "" ":meth:`zipimport.zipimporter.load_module` is deprecated: use :meth:" "`~zipimport.zipimporter.exec_module` instead." @@ -927,159 +1057,162 @@ msgstr "" "3.11:" #: ../../deprecations/c-api-pending-removal-in-3.14.rst:12 -msgid "``PySys_SetArgvEx()``: set :c:member:`PyConfig.argv` instead." -msgstr "``PySys_SetArgvEx()``: defina :c:member:`PyConfig.argv`." - -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:13 -msgid "``PySys_SetArgv()``: set :c:member:`PyConfig.argv` instead." -msgstr "``PySys_SetArgv()``: defina :c:member:`PyConfig.argv`." +msgid ":c:func:`!PySys_SetArgvEx()`: Set :c:member:`PyConfig.argv` instead." +msgstr ":c:func:`!PySys_SetArgvEx()`: defina :c:member:`PyConfig.argv`." #: ../../deprecations/c-api-pending-removal-in-3.14.rst:14 -msgid "``Py_SetProgramName()``: set :c:member:`PyConfig.program_name` instead." -msgstr "``Py_SetProgramName()``: defina :c:member:`PyConfig.program_name`." +msgid ":c:func:`!PySys_SetArgv()`: Set :c:member:`PyConfig.argv` instead." +msgstr ":c:func:`!PySys_SetArgv()`: defina :c:member:`PyConfig.argv`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:15 -msgid "``Py_SetPythonHome()``: set :c:member:`PyConfig.home` instead." -msgstr "``Py_SetPythonHome()``: defina :c:member:`PyConfig.home`." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:16 +msgid "" +":c:func:`!Py_SetProgramName()`: Set :c:member:`PyConfig.program_name` " +"instead." +msgstr "" +":c:func:`!Py_SetProgramName()`: defina :c:member:`PyConfig.program_name`." + +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:18 +msgid ":c:func:`!Py_SetPythonHome()`: Set :c:member:`PyConfig.home` instead." +msgstr ":c:func:`!Py_SetPythonHome()`: defina :c:member:`PyConfig.home`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:17 -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:45 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:21 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:71 msgid "" "The :c:func:`Py_InitializeFromConfig` API should be used with :c:type:" "`PyConfig` instead." msgstr "" -"A API :c:func:`Py_InitializeFromConfig` deve ser usada com :c:type:" -"`PyConfig`." +"Em vez disso, a API :c:func:`Py_InitializeFromConfig` deve ser usada com :c:" +"type:`PyConfig`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:20 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:24 msgid "Global configuration variables:" msgstr "Variáveis de configuração globais" -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:22 -msgid ":c:var:`Py_DebugFlag`: use :c:member:`PyConfig.parser_debug` instead." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:26 +msgid ":c:var:`Py_DebugFlag`: Use :c:member:`PyConfig.parser_debug` instead." msgstr ":c:var:`Py_DebugFlag`: use :c:member:`PyConfig.parser_debug`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:23 -msgid ":c:var:`Py_VerboseFlag`: use :c:member:`PyConfig.verbose` instead." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:28 +msgid ":c:var:`Py_VerboseFlag`: Use :c:member:`PyConfig.verbose` instead." msgstr ":c:var:`Py_VerboseFlag`: use :c:member:`PyConfig.verbose`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:24 -msgid ":c:var:`Py_QuietFlag`: use :c:member:`PyConfig.quiet` instead." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:30 +msgid ":c:var:`Py_QuietFlag`: Use :c:member:`PyConfig.quiet` instead." msgstr ":c:var:`Py_QuietFlag`: use :c:member:`PyConfig.quiet`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:25 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:32 msgid "" -":c:var:`Py_InteractiveFlag`: use :c:member:`PyConfig.interactive` instead." +":c:var:`Py_InteractiveFlag`: Use :c:member:`PyConfig.interactive` instead." msgstr ":c:var:`Py_InteractiveFlag`: use :c:member:`PyConfig.interactive`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:26 -msgid ":c:var:`Py_InspectFlag`: use :c:member:`PyConfig.inspect` instead." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:34 +msgid ":c:var:`Py_InspectFlag`: Use :c:member:`PyConfig.inspect` instead." msgstr ":c:var:`Py_InspectFlag`: use :c:member:`PyConfig.inspect`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:27 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:36 msgid "" -":c:var:`Py_OptimizeFlag`: use :c:member:`PyConfig.optimization_level` " +":c:var:`Py_OptimizeFlag`: Use :c:member:`PyConfig.optimization_level` " "instead." msgstr ":c:var:`Py_OptimizeFlag`: use :c:member:`PyConfig.optimization_level`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:28 -msgid ":c:var:`Py_NoSiteFlag`: use :c:member:`PyConfig.site_import` instead." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:38 +msgid ":c:var:`Py_NoSiteFlag`: Use :c:member:`PyConfig.site_import` instead." msgstr ":c:var:`Py_NoSiteFlag`: use :c:member:`PyConfig.site_import`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:29 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:40 msgid "" -":c:var:`Py_BytesWarningFlag`: use :c:member:`PyConfig.bytes_warning` instead." +":c:var:`Py_BytesWarningFlag`: Use :c:member:`PyConfig.bytes_warning` instead." msgstr ":c:var:`Py_BytesWarningFlag`: use :c:member:`PyConfig.bytes_warning`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:30 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:42 msgid "" -":c:var:`Py_FrozenFlag`: use :c:member:`PyConfig.pathconfig_warnings` instead." +":c:var:`Py_FrozenFlag`: Use :c:member:`PyConfig.pathconfig_warnings` instead." msgstr ":c:var:`Py_FrozenFlag`: use :c:member:`PyConfig.pathconfig_warnings`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:31 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:44 msgid "" -":c:var:`Py_IgnoreEnvironmentFlag`: use :c:member:`PyConfig.use_environment` " +":c:var:`Py_IgnoreEnvironmentFlag`: Use :c:member:`PyConfig.use_environment` " "instead." msgstr "" ":c:var:`Py_IgnoreEnvironmentFlag`: use :c:member:`PyConfig.use_environment`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:32 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:46 msgid "" -":c:var:`Py_DontWriteBytecodeFlag`: use :c:member:`PyConfig.write_bytecode` " +":c:var:`Py_DontWriteBytecodeFlag`: Use :c:member:`PyConfig.write_bytecode` " "instead." msgstr "" ":c:var:`Py_DontWriteBytecodeFlag`: use :c:member:`PyConfig.write_bytecode`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:33 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:48 msgid "" -":c:var:`Py_NoUserSiteDirectory`: use :c:member:`PyConfig." +":c:var:`Py_NoUserSiteDirectory`: Use :c:member:`PyConfig." "user_site_directory` instead." msgstr "" ":c:var:`Py_NoUserSiteDirectory`: use :c:member:`PyConfig." "user_site_directory`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:34 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:50 msgid "" -":c:var:`Py_UnbufferedStdioFlag`: use :c:member:`PyConfig.buffered_stdio` " +":c:var:`Py_UnbufferedStdioFlag`: Use :c:member:`PyConfig.buffered_stdio` " "instead." msgstr "" ":c:var:`Py_UnbufferedStdioFlag`: use :c:member:`PyConfig.buffered_stdio`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:35 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:52 msgid "" -":c:var:`Py_HashRandomizationFlag`: use :c:member:`PyConfig.use_hash_seed` " +":c:var:`Py_HashRandomizationFlag`: Use :c:member:`PyConfig.use_hash_seed` " "and :c:member:`PyConfig.hash_seed` instead." msgstr "" ":c:var:`Py_HashRandomizationFlag`: use :c:member:`PyConfig.use_hash_seed` e :" "c:member:`PyConfig.hash_seed`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:37 -msgid ":c:var:`Py_IsolatedFlag`: use :c:member:`PyConfig.isolated` instead." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:55 +msgid ":c:var:`Py_IsolatedFlag`: Use :c:member:`PyConfig.isolated` instead." msgstr ":c:var:`Py_IsolatedFlag`: use :c:member:`PyConfig.isolated`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:38 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:57 msgid "" -":c:var:`Py_LegacyWindowsFSEncodingFlag`: use :c:member:`PyPreConfig." +":c:var:`Py_LegacyWindowsFSEncodingFlag`: Use :c:member:`PyPreConfig." "legacy_windows_fs_encoding` instead." msgstr "" ":c:var:`Py_LegacyWindowsFSEncodingFlag`: use :c:member:`PyPreConfig." "legacy_windows_fs_encoding`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:39 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:59 msgid "" -":c:var:`Py_LegacyWindowsStdioFlag`: use :c:member:`PyConfig." +":c:var:`Py_LegacyWindowsStdioFlag`: Use :c:member:`PyConfig." "legacy_windows_stdio` instead." msgstr "" ":c:var:`Py_LegacyWindowsStdioFlag`: use :c:member:`PyConfig." "legacy_windows_stdio`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:40 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:61 msgid "" -":c:var:`!Py_FileSystemDefaultEncoding`: use :c:member:`PyConfig." +":c:var:`!Py_FileSystemDefaultEncoding`: Use :c:member:`PyConfig." "filesystem_encoding` instead." msgstr "" ":c:var:`!Py_FileSystemDefaultEncoding`: use :c:member:`PyConfig." "filesystem_encoding`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:41 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:63 msgid "" -":c:var:`!Py_HasFileSystemDefaultEncoding`: use :c:member:`PyConfig." +":c:var:`!Py_HasFileSystemDefaultEncoding`: Use :c:member:`PyConfig." "filesystem_encoding` instead." msgstr "" ":c:var:`!Py_HasFileSystemDefaultEncoding`: use :c:member:`PyConfig." "filesystem_encoding`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:42 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:65 msgid "" -":c:var:`!Py_FileSystemDefaultEncodeErrors`: use :c:member:`PyConfig." +":c:var:`!Py_FileSystemDefaultEncodeErrors`: Use :c:member:`PyConfig." "filesystem_errors` instead." msgstr "" ":c:var:`!Py_FileSystemDefaultEncodeErrors`: use :c:member:`PyConfig." "filesystem_errors`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:43 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:67 msgid "" -":c:var:`!Py_UTF8Mode`: use :c:member:`PyPreConfig.utf8_mode` instead. (see :" +":c:var:`!Py_UTF8Mode`: Use :c:member:`PyPreConfig.utf8_mode` instead. (see :" "c:func:`Py_PreInitialize`)" msgstr "" ":c:var:`!Py_UTF8Mode`: use :c:member:`PyPreConfig.utf8_mode`. (veja :c:func:" @@ -1091,188 +1224,198 @@ msgstr "A cópia empacotada do ``libmpdecimal``." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:5 msgid "" -":c:func:`PyImport_ImportModuleNoBlock`: use :c:func:`PyImport_ImportModule` " -"instead." +"The :c:func:`PyImport_ImportModuleNoBlock`: Use :c:func:" +"`PyImport_ImportModule` instead." msgstr "" -":c:func:`PyImport_ImportModuleNoBlock`: use :c:func:`PyImport_ImportModule`." - -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:6 -msgid ":c:func:`PyWeakref_GET_OBJECT`: use :c:func:`PyWeakref_GetRef` instead." -msgstr ":c:func:`PyWeakref_GET_OBJECT`: use :c:func:`PyWeakref_GetRef`." +"The :c:func:`PyImport_ImportModuleNoBlock`: use :c:func:" +"`PyImport_ImportModule`." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:7 -msgid ":c:func:`PyWeakref_GetObject`: use :c:func:`PyWeakref_GetRef` instead." -msgstr ":c:func:`PyWeakref_GetObject`: use :c:func:`PyWeakref_GetRef`." - -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:8 -msgid ":c:type:`!Py_UNICODE_WIDE` type: use :c:type:`wchar_t` instead." -msgstr "O tipo :c:type:`!Py_UNICODE_WIDE`: use :c:type:`wchar_t`." +msgid "" +":c:func:`PyWeakref_GetObject` and :c:func:`PyWeakref_GET_OBJECT`: Use :c:" +"func:`PyWeakref_GetRef` instead." +msgstr "" +":c:func:`PyWeakref_GetObject` e :c:func:`PyWeakref_GET_OBJECT`: use :c:func:" +"`PyWeakref_GetRef`." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:9 -msgid ":c:type:`Py_UNICODE` type: use :c:type:`wchar_t` instead." -msgstr "O tipo :c:type:`Py_UNICODE`: use :c:type:`wchar_t`." +msgid "" +":c:type:`Py_UNICODE` type and the :c:macro:`!Py_UNICODE_WIDE` macro: Use :c:" +"type:`wchar_t` instead." +msgstr "" +"O tipo :c:type:`Py_UNICODE` e a macro :c:macro:`!Py_UNICODE_WIDE`: use :c:" +"type:`wchar_t`." -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:10 +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:11 msgid "Python initialization functions:" msgstr "Funções de inicialização do Python" -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:12 +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:13 msgid "" -":c:func:`PySys_ResetWarnOptions`: clear :data:`sys.warnoptions` and :data:`!" +":c:func:`PySys_ResetWarnOptions`: Clear :data:`sys.warnoptions` and :data:`!" "warnings.filters` instead." msgstr "" ":c:func:`PySys_ResetWarnOptions`: apague :data:`sys.warnoptions` e :data:`!" "warnings.filters`." -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:14 -msgid ":c:func:`Py_GetExecPrefix`: get :data:`sys.exec_prefix` instead." -msgstr ":c:func:`Py_GetExecPrefix`: obtenha :data:`sys.exec_prefix`." - #: ../../deprecations/c-api-pending-removal-in-3.15.rst:15 -msgid ":c:func:`Py_GetPath`: get :data:`sys.path` instead." -msgstr ":c:func:`Py_GetPath`: obtenha :data:`sys.path`." - -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:16 -msgid ":c:func:`Py_GetPrefix`: get :data:`sys.prefix` instead." -msgstr ":c:func:`Py_GetPrefix`: obtenha :data:`sys.prefix`." +msgid "" +":c:func:`Py_GetExecPrefix`: Get :data:`sys.base_exec_prefix` and :data:`sys." +"exec_prefix` instead." +msgstr "" +":c:func:`Py_GetExecPrefix`: obtenha :data:`sys.base_exec_prefix` e :data:" +"`sys.exec_prefix`." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:17 -msgid ":c:func:`Py_GetProgramFullPath`: get :data:`sys.executable` instead." -msgstr ":c:func:`Py_GetProgramFullPath`: obtenha :data:`sys.executable`." - -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:18 -msgid ":c:func:`Py_GetProgramName`: get :data:`sys.executable` instead." -msgstr ":c:func:`Py_GetProgramName`: obtenha :data:`sys.executable`." +msgid ":c:func:`Py_GetPath`: Get :data:`sys.path` instead." +msgstr ":c:func:`Py_GetPath`: leia :data:`sys.path`." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:19 msgid "" -":c:func:`Py_GetPythonHome`: get :c:member:`PyConfig.home` or the :envvar:" +":c:func:`Py_GetPrefix`: Get :data:`sys.base_prefix` and :data:`sys.prefix` " +"instead." +msgstr "" +":c:func:`Py_GetPrefix`: obtenha :data:`sys.base_prefix` e :data:`sys.prefix`." + +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:21 +msgid ":c:func:`Py_GetProgramFullPath`: Get :data:`sys.executable` instead." +msgstr ":c:func:`Py_GetProgramFullPath`: leia :data:`sys.executable`." + +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:23 +msgid ":c:func:`Py_GetProgramName`: Get :data:`sys.executable` instead." +msgstr ":c:func:`Py_GetProgramName`: leia :data:`sys.executable`." + +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:25 +msgid "" +":c:func:`Py_GetPythonHome`: Get :c:member:`PyConfig.home` or the :envvar:" "`PYTHONHOME` environment variable instead." msgstr "" -":c:func:`Py_GetPythonHome`: obtenha :c:member:`PyConfig.home` ou a variável " -"de ambiente :envvar:`PYTHONHOME`." +":c:func:`Py_GetPythonHome`: leia :c:member:`PyConfig.home` ou a variável de " +"ambiente :envvar:`PYTHONHOME`." #: ../../deprecations/c-api-pending-removal-in-future.rst:4 msgid "" "The following APIs are deprecated and will be removed, although there is " "currently no date scheduled for their removal." msgstr "" -"As APIs a seguir foram descontinuado e serão removidas, embora atualmente " +"As APIs a seguir foram descontinuadas e serão removidas, embora atualmente " "não haja uma data agendada para sua remoção." #: ../../deprecations/c-api-pending-removal-in-future.rst:7 -msgid ":c:macro:`Py_TPFLAGS_HAVE_FINALIZE`: unneeded since Python 3.8." +msgid ":c:macro:`Py_TPFLAGS_HAVE_FINALIZE`: Unneeded since Python 3.8." msgstr ":c:macro:`Py_TPFLAGS_HAVE_FINALIZE`: desnecessária desde o Python 3.8." -#: ../../deprecations/c-api-pending-removal-in-future.rst:8 -msgid ":c:func:`PyErr_Fetch`: use :c:func:`PyErr_GetRaisedException` instead." +#: ../../deprecations/c-api-pending-removal-in-future.rst:9 +msgid ":c:func:`PyErr_Fetch`: Use :c:func:`PyErr_GetRaisedException` instead." msgstr ":c:func:`PyErr_Fetch`: use :c:func:`PyErr_GetRaisedException`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:9 +#: ../../deprecations/c-api-pending-removal-in-future.rst:11 msgid "" -":c:func:`PyErr_NormalizeException`: use :c:func:`PyErr_GetRaisedException` " +":c:func:`PyErr_NormalizeException`: Use :c:func:`PyErr_GetRaisedException` " "instead." msgstr "" ":c:func:`PyErr_NormalizeException`: use :c:func:`PyErr_GetRaisedException`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:10 +#: ../../deprecations/c-api-pending-removal-in-future.rst:13 msgid "" -":c:func:`PyErr_Restore`: use :c:func:`PyErr_SetRaisedException` instead." +":c:func:`PyErr_Restore`: Use :c:func:`PyErr_SetRaisedException` instead." msgstr ":c:func:`PyErr_Restore`: use :c:func:`PyErr_SetRaisedException`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:11 +#: ../../deprecations/c-api-pending-removal-in-future.rst:15 msgid "" -":c:func:`PyModule_GetFilename`: use :c:func:`PyModule_GetFilenameObject` " +":c:func:`PyModule_GetFilename`: Use :c:func:`PyModule_GetFilenameObject` " "instead." msgstr "" ":c:func:`PyModule_GetFilename`: use :c:func:`PyModule_GetFilenameObject`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:12 -msgid ":c:func:`PyOS_AfterFork`: use :c:func:`PyOS_AfterFork_Child` instead." +#: ../../deprecations/c-api-pending-removal-in-future.rst:17 +msgid ":c:func:`PyOS_AfterFork`: Use :c:func:`PyOS_AfterFork_Child` instead." msgstr ":c:func:`PyOS_AfterFork`: use :c:func:`PyOS_AfterFork_Child`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:13 +#: ../../deprecations/c-api-pending-removal-in-future.rst:19 msgid "" -":c:func:`PySlice_GetIndicesEx`: use :c:func:`PySlice_Unpack` and :c:func:" +":c:func:`PySlice_GetIndicesEx`: Use :c:func:`PySlice_Unpack` and :c:func:" "`PySlice_AdjustIndices` instead." msgstr "" ":c:func:`PySlice_GetIndicesEx`: use :c:func:`PySlice_Unpack` e :c:func:" "`PySlice_AdjustIndices`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:14 +#: ../../deprecations/c-api-pending-removal-in-future.rst:21 msgid "" -":c:func:`!PyUnicode_AsDecodedObject`: use :c:func:`PyCodec_Decode` instead." +":c:func:`!PyUnicode_AsDecodedObject`: Use :c:func:`PyCodec_Decode` instead." msgstr ":c:func:`!PyUnicode_AsDecodedObject`: use :c:func:`PyCodec_Decode`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:15 +#: ../../deprecations/c-api-pending-removal-in-future.rst:23 msgid "" -":c:func:`!PyUnicode_AsDecodedUnicode`: use :c:func:`PyCodec_Decode` instead." +":c:func:`!PyUnicode_AsDecodedUnicode`: Use :c:func:`PyCodec_Decode` instead." msgstr ":c:func:`!PyUnicode_AsDecodedUnicode`: use :c:func:`PyCodec_Decode`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:16 +#: ../../deprecations/c-api-pending-removal-in-future.rst:25 msgid "" -":c:func:`!PyUnicode_AsEncodedObject`: use :c:func:`PyCodec_Encode` instead." +":c:func:`!PyUnicode_AsEncodedObject`: Use :c:func:`PyCodec_Encode` instead." msgstr ":c:func:`!PyUnicode_AsEncodedObject`: use :c:func:`PyCodec_Encode`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:17 +#: ../../deprecations/c-api-pending-removal-in-future.rst:27 msgid "" -":c:func:`!PyUnicode_AsEncodedUnicode`: use :c:func:`PyCodec_Encode` instead." +":c:func:`!PyUnicode_AsEncodedUnicode`: Use :c:func:`PyCodec_Encode` instead." msgstr ":c:func:`!PyUnicode_AsEncodedUnicode`: use :c:func:`PyCodec_Encode`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:18 -msgid ":c:func:`PyUnicode_READY`: unneeded since Python 3.12" +#: ../../deprecations/c-api-pending-removal-in-future.rst:29 +msgid ":c:func:`PyUnicode_READY`: Unneeded since Python 3.12" msgstr ":c:func:`PyUnicode_READY`: desnecessário desde o Python 3.12" -#: ../../deprecations/c-api-pending-removal-in-future.rst:19 -msgid ":c:func:`!PyErr_Display`: use :c:func:`PyErr_DisplayException` instead." +#: ../../deprecations/c-api-pending-removal-in-future.rst:31 +msgid ":c:func:`!PyErr_Display`: Use :c:func:`PyErr_DisplayException` instead." msgstr ":c:func:`!PyErr_Display`: use :c:func:`PyErr_DisplayException`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:20 +#: ../../deprecations/c-api-pending-removal-in-future.rst:33 msgid "" -":c:func:`!_PyErr_ChainExceptions`: use ``_PyErr_ChainExceptions1`` instead." -msgstr ":c:func:`!_PyErr_ChainExceptions`: use ``_PyErr_ChainExceptions1``." +":c:func:`!_PyErr_ChainExceptions`: Use :c:func:`!_PyErr_ChainExceptions1` " +"instead." +msgstr "" +":c:func:`!_PyErr_ChainExceptions`: use :c:func:`!_PyErr_ChainExceptions1`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:21 +#: ../../deprecations/c-api-pending-removal-in-future.rst:35 msgid "" ":c:member:`!PyBytesObject.ob_shash` member: call :c:func:`PyObject_Hash` " "instead." msgstr "" "O membro :c:member:`!PyBytesObject.ob_shash`: chame :c:func:`PyObject_Hash`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:23 +#: ../../deprecations/c-api-pending-removal-in-future.rst:37 msgid ":c:member:`!PyDictObject.ma_version_tag` member." msgstr "O membro :c:member:`!PyDictObject.ma_version_tag`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:24 +#: ../../deprecations/c-api-pending-removal-in-future.rst:38 msgid "Thread Local Storage (TLS) API:" msgstr "API do Thread Local Storage (TLS):" -#: ../../deprecations/c-api-pending-removal-in-future.rst:26 +#: ../../deprecations/c-api-pending-removal-in-future.rst:40 msgid "" -":c:func:`PyThread_create_key`: use :c:func:`PyThread_tss_alloc` instead." +":c:func:`PyThread_create_key`: Use :c:func:`PyThread_tss_alloc` instead." msgstr ":c:func:`PyThread_create_key`: use :c:func:`PyThread_tss_alloc`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:27 -msgid ":c:func:`PyThread_delete_key`: use :c:func:`PyThread_tss_free` instead." +#: ../../deprecations/c-api-pending-removal-in-future.rst:42 +msgid ":c:func:`PyThread_delete_key`: Use :c:func:`PyThread_tss_free` instead." msgstr ":c:func:`PyThread_delete_key`: use :c:func:`PyThread_tss_free`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:28 +#: ../../deprecations/c-api-pending-removal-in-future.rst:44 msgid "" -":c:func:`PyThread_set_key_value`: use :c:func:`PyThread_tss_set` instead." +":c:func:`PyThread_set_key_value`: Use :c:func:`PyThread_tss_set` instead." msgstr ":c:func:`PyThread_set_key_value`: use :c:func:`PyThread_tss_set`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:29 +#: ../../deprecations/c-api-pending-removal-in-future.rst:46 msgid "" -":c:func:`PyThread_get_key_value`: use :c:func:`PyThread_tss_get` instead." +":c:func:`PyThread_get_key_value`: Use :c:func:`PyThread_tss_get` instead." msgstr ":c:func:`PyThread_get_key_value`: use :c:func:`PyThread_tss_get`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:30 +#: ../../deprecations/c-api-pending-removal-in-future.rst:48 msgid "" -":c:func:`PyThread_delete_key_value`: use :c:func:`PyThread_tss_delete` " +":c:func:`PyThread_delete_key_value`: Use :c:func:`PyThread_tss_delete` " "instead." msgstr "" ":c:func:`PyThread_delete_key_value`: use :c:func:`PyThread_tss_delete`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:31 -msgid ":c:func:`PyThread_ReInitTLS`: unneeded since Python 3.7." +#: ../../deprecations/c-api-pending-removal-in-future.rst:50 +msgid ":c:func:`PyThread_ReInitTLS`: Unneeded since Python 3.7." msgstr ":c:func:`PyThread_ReInitTLS`: desnecessário desde o Python 3.7." diff --git a/deprecations/pending-removal-in-3.13.po b/deprecations/pending-removal-in-3.13.po index 5e1c4e905..a10abd05a 100644 --- a/deprecations/pending-removal-in-3.13.po +++ b/deprecations/pending-removal-in-3.13.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-26 14:15+0000\n" -"PO-Revision-Date: 2024-07-26 14:16+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -189,10 +189,10 @@ msgstr "``read_text()``" #: ../../deprecations/pending-removal-in-3.13.rst:51 msgid "" -"Use :func:`importlib.resources.files()` instead. Refer to `importlib-" +"Use :func:`importlib.resources.files` instead. Refer to `importlib-" "resources: Migrating from Legacy `_ (:gh:`106531`)" msgstr "" -"Use :func:`importlib.resources.files()` em vez disso. Confira `importlib-" +"Use :func:`importlib.resources.files` em vez disso. Confira `importlib-" "resources: Migrando do legado `_ , em inglês (:gh:`106531`)" diff --git a/deprecations/pending-removal-in-3.14.po b/deprecations/pending-removal-in-3.14.po index 1f751879d..27742da2f 100644 --- a/deprecations/pending-removal-in-3.14.po +++ b/deprecations/pending-removal-in-3.14.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-26 14:15+0000\n" -"PO-Revision-Date: 2024-07-20 00:54+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -43,7 +43,7 @@ msgid "" "since Python 3.8, now cause a :exc:`DeprecationWarning` to be emitted at " "runtime when they are accessed or used, and will be removed in Python 3.14:" msgstr "" -":mod:`ast`: Os seguintes recursos foram descontinuados na documentação desde " +":mod:`ast`: os seguintes recursos foram descontinuados na documentação desde " "Python 3.8, agora fazem com que um :exc:`DeprecationWarning` seja emitido em " "tempo de execução quando eles são acessados ou usados, e serão removidos no " "Python 3.14:" @@ -73,7 +73,7 @@ msgid "" "Use :class:`ast.Constant` instead. (Contributed by Serhiy Storchaka in :gh:" "`90953`.)" msgstr "" -"Usa :class:`ast.Constant` em vez disso. (Contribuição de Serhiy Storchaka " +"Em vez disso, use :class:`ast.Constant`. (Contribuição de Serhiy Storchaka " "em :gh:`90953`.)" #: ../../deprecations/pending-removal-in-3.14.rst:22 @@ -138,46 +138,38 @@ msgstr "" "localtime`. (Contribuição de Alan Williams em :gh:`72346`.)" #: ../../deprecations/pending-removal-in-3.14.rst:50 -msgid "" -":mod:`importlib`: ``__package__`` and ``__cached__`` will cease to be set or " -"taken into consideration by the import system (:gh:`97879`)." -msgstr "" -":mod:`importlib`: ``__package__`` e ``__cached__`` deixarão de ser definidos " -"ou levados em consideração pelo sistema de importação (:gh:`97879`)." - -#: ../../deprecations/pending-removal-in-3.14.rst:53 msgid ":mod:`importlib.abc` deprecated classes:" msgstr ":mod:`importlib.abc` descontinuou as classes:" -#: ../../deprecations/pending-removal-in-3.14.rst:55 +#: ../../deprecations/pending-removal-in-3.14.rst:52 msgid ":class:`!importlib.abc.ResourceReader`" msgstr ":class:`!importlib.abc.ResourceReader`" -#: ../../deprecations/pending-removal-in-3.14.rst:56 +#: ../../deprecations/pending-removal-in-3.14.rst:53 msgid ":class:`!importlib.abc.Traversable`" msgstr ":class:`!importlib.abc.Traversable`" -#: ../../deprecations/pending-removal-in-3.14.rst:57 +#: ../../deprecations/pending-removal-in-3.14.rst:54 msgid ":class:`!importlib.abc.TraversableResources`" msgstr ":class:`!importlib.abc.TraversableResources`" -#: ../../deprecations/pending-removal-in-3.14.rst:59 +#: ../../deprecations/pending-removal-in-3.14.rst:56 msgid "Use :mod:`importlib.resources.abc` classes instead:" -msgstr "Em vez disso, use classes :mod:`importlib.resources.abc`:" +msgstr "Em vez disso, use classes de :mod:`importlib.resources.abc`:" -#: ../../deprecations/pending-removal-in-3.14.rst:61 +#: ../../deprecations/pending-removal-in-3.14.rst:58 msgid ":class:`importlib.resources.abc.Traversable`" msgstr ":class:`importlib.resources.abc.Traversable`" -#: ../../deprecations/pending-removal-in-3.14.rst:62 +#: ../../deprecations/pending-removal-in-3.14.rst:59 msgid ":class:`importlib.resources.abc.TraversableResources`" msgstr ":class:`importlib.resources.abc.TraversableResources`" -#: ../../deprecations/pending-removal-in-3.14.rst:64 +#: ../../deprecations/pending-removal-in-3.14.rst:61 msgid "(Contributed by Jason R. Coombs and Hugo van Kemenade in :gh:`93963`.)" msgstr "(Contribuição de Jason R. Coombs e Hugo van Kemenade em :gh:`93963`.)" -#: ../../deprecations/pending-removal-in-3.14.rst:66 +#: ../../deprecations/pending-removal-in-3.14.rst:63 msgid "" ":mod:`itertools` had undocumented, inefficient, historically buggy, and " "inconsistent support for copy, deepcopy, and pickle operations. This will be " @@ -190,7 +182,7 @@ msgstr "" "significativa no volume de código e na carga de manutenção. (Contribuição de " "Raymond Hettinger em :gh:`101588`.)" -#: ../../deprecations/pending-removal-in-3.14.rst:72 +#: ../../deprecations/pending-removal-in-3.14.rst:69 msgid "" ":mod:`multiprocessing`: The default start method will change to a safer one " "on Linux, BSDs, and other non-macOS POSIX platforms where ``'fork'`` is " @@ -200,7 +192,7 @@ msgid "" "set_start_method` APIs to explicitly specify when your code *requires* " "``'fork'``. See :ref:`multiprocessing-start-methods`." msgstr "" -":mod:`multiprocessing`: O método de inicialização padrão será alterado para " +":mod:`multiprocessing`: o método de inicialização padrão será alterado para " "um mais seguro no Linux, BSDs e outras plataformas POSIX não-macOS onde " "``'fork'`` é atualmente o padrão (:gh:`84559`). Adicionar um aviso de tempo " "de execução sobre isso foi considerado muito perturbador, pois não se espera " @@ -209,7 +201,7 @@ msgstr "" "explicitamente quando seu código *requer* ``'fork'``. Veja :ref:" "`multiprocessing-start-methods`." -#: ../../deprecations/pending-removal-in-3.14.rst:80 +#: ../../deprecations/pending-removal-in-3.14.rst:77 msgid "" ":mod:`pathlib`: :meth:`~pathlib.PurePath.is_relative_to` and :meth:`~pathlib." "PurePath.relative_to`: passing additional arguments is deprecated." @@ -217,7 +209,7 @@ msgstr "" ":mod:`pathlib`: :meth:`~pathlib.PurePath.is_relative_to` e :meth:`~pathlib." "PurePath.relative_to`: passar argumentos adicionais foi descontinuado." -#: ../../deprecations/pending-removal-in-3.14.rst:84 +#: ../../deprecations/pending-removal-in-3.14.rst:81 msgid "" ":mod:`pkgutil`: :func:`~pkgutil.find_loader` and :func:`~pkgutil.get_loader` " "now raise :exc:`DeprecationWarning`; use :func:`importlib.util.find_spec` " @@ -227,57 +219,37 @@ msgstr "" "agora levantam :exc:`DeprecationWarning`; use :func:`importlib.util." "find_spec` em vez disto. (Contribuição de Nikita Sobolev em :gh:`97850`.)" -#: ../../deprecations/pending-removal-in-3.14.rst:89 +#: ../../deprecations/pending-removal-in-3.14.rst:86 msgid ":mod:`pty`:" msgstr ":mod:`pty`:" -#: ../../deprecations/pending-removal-in-3.14.rst:91 +#: ../../deprecations/pending-removal-in-3.14.rst:88 msgid "``master_open()``: use :func:`pty.openpty`." msgstr "``master_open()``: use :func:`pty.openpty`." -#: ../../deprecations/pending-removal-in-3.14.rst:92 +#: ../../deprecations/pending-removal-in-3.14.rst:89 msgid "``slave_open()``: use :func:`pty.openpty`." msgstr "``slave_open()``: use :func:`pty.openpty`." -#: ../../deprecations/pending-removal-in-3.14.rst:94 +#: ../../deprecations/pending-removal-in-3.14.rst:91 msgid ":mod:`sqlite3`:" msgstr ":mod:`sqlite3`:" -#: ../../deprecations/pending-removal-in-3.14.rst:96 +#: ../../deprecations/pending-removal-in-3.14.rst:93 msgid ":data:`~sqlite3.version` and :data:`~sqlite3.version_info`." msgstr ":data:`~sqlite3.version` e :data:`~sqlite3.version_info`." -#: ../../deprecations/pending-removal-in-3.14.rst:98 +#: ../../deprecations/pending-removal-in-3.14.rst:95 msgid "" ":meth:`~sqlite3.Cursor.execute` and :meth:`~sqlite3.Cursor.executemany` if :" "ref:`named placeholders ` are used and *parameters* is " "a sequence instead of a :class:`dict`." msgstr "" ":meth:`~sqlite3.Cursor.execute` e :meth:`~sqlite3.Cursor.executemany` se :" -"ref:`espaços reservados nomeados ` forem usados ​​e " +"ref:`espaços reservados nomeados ` forem usados e " "*parameters* for uma sequência em vez de um :class:`dict` ." -#: ../../deprecations/pending-removal-in-3.14.rst:102 -msgid "" -"date and datetime adapter, date and timestamp converter: see the :mod:" -"`sqlite3` documentation for suggested replacement recipes." -msgstr "" -"adaptador de data e hora, conversor de registro de data e hora: veja a " -"documentação de :mod:`sqlite3` para receitas de substituição sugeridas." - -#: ../../deprecations/pending-removal-in-3.14.rst:105 -msgid "" -":class:`types.CodeType`: Accessing :attr:`~codeobject.co_lnotab` was " -"deprecated in :pep:`626` since 3.10 and was planned to be removed in 3.12, " -"but it only got a proper :exc:`DeprecationWarning` in 3.12. May be removed " -"in 3.14. (Contributed by Nikita Sobolev in :gh:`101866`.)" -msgstr "" -":class:`types.CodeType`: O acesso a :attr:`~codeobject.co_lnotab` foi " -"descontinuado na :pep:`626` desde 3.10 e foi planejado para ser removido em " -"3.12, mas só recebeu uma :exc:`DeprecationWarning` adequada em 3.12. Pode " -"ser removido em 3.14. (Contribuição de Nikita Sobolev em :gh:`101866`.)" - -#: ../../deprecations/pending-removal-in-3.14.rst:112 +#: ../../deprecations/pending-removal-in-3.14.rst:99 msgid "" ":mod:`typing`: :class:`~typing.ByteString`, deprecated since Python 3.9, now " "causes a :exc:`DeprecationWarning` to be emitted when it is used." @@ -285,7 +257,7 @@ msgstr "" ":mod:`typing`: :class:`~typing.ByteString`, descontinuado desde Python 3.9, " "agora faz com que uma :exc:`DeprecationWarning` seja emitida quando é usado." -#: ../../deprecations/pending-removal-in-3.14.rst:115 +#: ../../deprecations/pending-removal-in-3.14.rst:102 msgid "" ":mod:`urllib`: :class:`!urllib.parse.Quoter` is deprecated: it was not " "intended to be a public API. (Contributed by Gregory P. Smith in :gh:" diff --git a/deprecations/pending-removal-in-3.15.po b/deprecations/pending-removal-in-3.15.po index 06261f9f2..96da645c0 100644 --- a/deprecations/pending-removal-in-3.15.po +++ b/deprecations/pending-removal-in-3.15.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-20 00:52+0000\n" -"PO-Revision-Date: 2024-07-20 00:54+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-16 14:58+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -28,126 +28,216 @@ msgid "Pending Removal in Python 3.15" msgstr "Remoção pendente no Python 3.15" #: ../../deprecations/pending-removal-in-3.15.rst:4 +msgid "The import system:" +msgstr "O sistema de importação:" + +#: ../../deprecations/pending-removal-in-3.15.rst:6 msgid "" -":class:`http.server.CGIHTTPRequestHandler` will be removed along with its " -"related ``--cgi`` flag to ``python -m http.server``. It was obsolete and " -"rarely used. No direct replacement exists. *Anything* is better than CGI " -"to interface a web server with a request handler." +"Setting :attr:`~module.__cached__` on a module while failing to set :attr:" +"`__spec__.cached ` is deprecated. In " +"Python 3.15, :attr:`!__cached__` will cease to be set or take into " +"consideration by the import system or standard library. (:gh:`97879`)" msgstr "" -":class:`http.server.CGIHTTPRequestHandler` será removido junto com seu " -"sinalizador relacionado ``--cgi`` para ``python -m http.server``. Estava " -"descontinuado e raramente usado. Não existe substituição direta. *Qualquer " -"coisa* é melhor que CGI para fazer a interface de um servidor web com um " -"manipulador de solicitações." +"A definição de :attr:`~module.__cached__` em um módulo enquanto falha na " +"definição de :attr:`__spec__.cached ` " +"está descontinuado. No Python 3.15, :attr:`!__cached__` deixará de ser " +"definido ou levado em consideração pelo sistema de importação ou pela " +"biblioteca padrão. (:gh:`97879`)" -#: ../../deprecations/pending-removal-in-3.15.rst:9 +#: ../../deprecations/pending-removal-in-3.15.rst:11 msgid "" -":class:`locale`: :func:`locale.getdefaultlocale` was deprecated in Python " -"3.11 and originally planned for removal in Python 3.13 (:gh:`90817`), but " -"removal has been postponed to Python 3.15. Use :func:`locale.setlocale()`, :" -"func:`locale.getencoding()` and :func:`locale.getlocale()` instead. " -"(Contributed by Hugo van Kemenade in :gh:`111187`.)" +"Setting :attr:`~module.__package__` on a module while failing to set :attr:" +"`__spec__.parent ` is deprecated. In " +"Python 3.15, :attr:`!__package__` will cease to be set or take into " +"consideration by the import system or standard library. (:gh:`97879`)" msgstr "" -":class:`locale`: :func:`locale.getdefaultlocale` foi descontinuada no Python " -"3.11 e originalmente planejada para remoção no Python 3.13 (:gh:`90817`), " -"mas a remoção foi adiada para o Python 3.15. Use :func:`locale." -"setlocale()`, :func:`locale.getencoding()` e :func:`locale.getlocale()` em " -"vez disso. (Contribuição de Hugo van Kemenade em :gh:`111187`.)" +"A definição de :attr:`~module.__package__` em um módulo enquanto falha na " +"definição de :attr:`__spec__.parent ` " +"está descontinuado. No Python 3.15, :attr:`!__package__` deixará de ser " +"definido ou levado em consideração pelo sistema de importação ou pela " +"biblioteca padrão. (:gh:`97879`)" #: ../../deprecations/pending-removal-in-3.15.rst:16 +msgid ":mod:`ctypes`:" +msgstr ":mod:`ctypes`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:18 msgid "" -":mod:`pathlib`: :meth:`pathlib.PurePath.is_reserved` is deprecated and " -"scheduled for removal in Python 3.15. Use :func:`os.path.isreserved` to " -"detect reserved paths on Windows." +"The undocumented :func:`!ctypes.SetPointerType` function has been deprecated " +"since Python 3.13." msgstr "" -":mod:`pathlib`: :meth:`pathlib.PurePath.is_reserved` está descontinuado e " -"agendado para remoção no Python 3.15. Use :func:`os.path.isreserved` para " -"detectar caminhos reservados no Windows." +"A função não documentada :func:`!ctypes.SetPointerType` foi descontinuada " +"desde o Python 3.13." #: ../../deprecations/pending-removal-in-3.15.rst:21 +msgid ":mod:`http.server`:" +msgstr ":mod:`http.server`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:23 msgid "" -":mod:`platform`: :func:`~platform.java_ver` is deprecated and will be " -"removed in 3.15. It was largely untested, had a confusing API, and was only " -"useful for Jython support. (Contributed by Nikita Sobolev in :gh:`116349`.)" +"The obsolete and rarely used :class:`~http.server.CGIHTTPRequestHandler` has " +"been deprecated since Python 3.13. No direct replacement exists. *Anything* " +"is better than CGI to interface a web server with a request handler." msgstr "" -":mod:`platform`: :func:`~platform.java_ver` está descontinuada e será " -"removida na versão 3.15. Ela não foi testada em grande parte, tinha uma API " -"confusa e só era útil para suporte a Jython. (Contribuição de Nikita Sobolev " -"em :gh:`116349`.)" +"A classe obsoleta e raramente usada :class:`~http.server." +"CGIHTTPRequestHandler` foi descontinuada desde o Python 3.13. Não existe " +"substituição direta. *Qualquer coisa* é melhor que CGI para fazer a " +"interface de um servidor web com um manipulador de requisição." -#: ../../deprecations/pending-removal-in-3.15.rst:27 +#: ../../deprecations/pending-removal-in-3.15.rst:29 msgid "" -":mod:`threading`: Passing any arguments to :func:`threading.RLock` is now " -"deprecated. C version allows any numbers of args and kwargs, but they are " -"just ignored. Python version does not allow any arguments. All arguments " -"will be removed from :func:`threading.RLock` in Python 3.15. (Contributed by " -"Nikita Sobolev in :gh:`102029`.)" +"The :option:`!--cgi` flag to the :program:`python -m http.server` command-" +"line interface has been deprecated since Python 3.13." msgstr "" -":mod:`threading`: Passar qualquer argumento para :func:`threading.RLock` " -"agora está descontinuado. A versão C permite qualquer número de args e " -"kwargs, mas eles são simplesmente ignorados. A versão Python não permite " -"nenhum argumento. Todos os argumentos serão removidos de :func:`threading." -"RLock` no Python 3.15. (Contribuição de Nikita Sobolev em :gh:`102029`.)" +"O sinalizador :option:`!--cgi` para a interface de linha de comando :program:" +"`python -m http.server` foi descontinuado desde o Python 3.13." + +#: ../../deprecations/pending-removal-in-3.15.rst:32 +msgid ":mod:`importlib`:" +msgstr ":mod:`importlib`:" #: ../../deprecations/pending-removal-in-3.15.rst:34 -msgid ":class:`typing.NamedTuple`:" -msgstr ":class:`typing.NamedTuple`:" +msgid "``load_module()`` method: use ``exec_module()`` instead." +msgstr "Método ``load_module()``: use ``exec_module()``." #: ../../deprecations/pending-removal-in-3.15.rst:36 +msgid ":class:`locale`:" +msgstr ":class:`locale`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:38 +msgid "" +"The :func:`~locale.getdefaultlocale` function has been deprecated since " +"Python 3.11. Its removal was originally planned for Python 3.13 (:gh:" +"`90817`), but has been postponed to Python 3.15. Use :func:`~locale." +"getlocale`, :func:`~locale.setlocale`, and :func:`~locale.getencoding` " +"instead. (Contributed by Hugo van Kemenade in :gh:`111187`.)" +msgstr "" +"A função :func:`~locale.getdefaultlocale` foi descontinuada desde o Python " +"3.11. Sua remoção foi planejada originalmente para o Python 3.13 (:gh:" +"`90817`), mas foi adiada para o Python 3.15. Em vez disso, use :func:" +"`~locale.getlocale`, :func:`~locale.setlocale` e :func:`~locale." +"getencoding`. (Contribuição de Hugo van Kemenade em :gh:`111187`.)" + +#: ../../deprecations/pending-removal-in-3.15.rst:46 +msgid ":mod:`pathlib`:" +msgstr ":mod:`pathlib`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:48 msgid "" -"The undocumented keyword argument syntax for creating :class:`!NamedTuple` " -"classes (``NT = NamedTuple(\"NT\", x=int)``) is deprecated, and will be " -"disallowed in 3.15. Use the class-based syntax or the functional syntax " -"instead." -msgstr "" -"A sintaxe de argumento nomeado não documentada para criar classes :class:`!" -"NamedTuple` (``NT = NamedTuple(\"NT\", x=int)``) está descontinuada e não " -"será permitida em 3.15. Use a sintaxe baseada em classe ou a sintaxe " -"funcional." - -#: ../../deprecations/pending-removal-in-3.15.rst:40 -msgid "" -"When using the functional syntax to create a :class:`!NamedTuple` class, " -"failing to pass a value to the *fields* parameter (``NT = " -"NamedTuple(\"NT\")``) is deprecated. Passing ``None`` to the *fields* " -"parameter (``NT = NamedTuple(\"NT\", None)``) is also deprecated. Both will " -"be disallowed in Python 3.15. To create a :class:`!NamedTuple` class with 0 " -"fields, use ``class NT(NamedTuple): pass`` or ``NT = NamedTuple(\"NT\", " -"[])``." -msgstr "" -"Ao usar a sintaxe funcional para criar uma classe :class:`!NamedTuple`, " -"falhar ao passar um valor para o parâmetro *fields* (``NT = " -"NamedTuple(\"NT\")``) está descontinuada. Passar ``None`` para o parâmetro " -"*fields* (``NT = NamedTuple(\"NT\", None)``) também está descontinuada. " -"Ambos não serão permitidos no Python 3.15. Para criar uma classe :class:`!" -"NamedTuple` com 0 campos, use ``class NT(NamedTuple): pass`` ou ``NT = " -"NamedTuple(\"NT\", [])``." - -#: ../../deprecations/pending-removal-in-3.15.rst:47 -msgid "" -":class:`typing.TypedDict`: When using the functional syntax to create a :" -"class:`!TypedDict` class, failing to pass a value to the *fields* parameter " -"(``TD = TypedDict(\"TD\")``) is deprecated. Passing ``None`` to the *fields* " -"parameter (``TD = TypedDict(\"TD\", None)``) is also deprecated. Both will " -"be disallowed in Python 3.15. To create a :class:`!TypedDict` class with 0 " -"fields, use ``class TD(TypedDict): pass`` or ``TD = TypedDict(\"TD\", {})``." -msgstr "" -":class:`typing.TypedDict`: Ao usar a sintaxe funcional para criar uma " -"classe :class:`!TypedDict`, falhar ao passar um valor para o parâmetro " -"*fields* (``TD = TypedDict(\"TD\")``) está descontinuada. Passar ``None`` " -"para o parâmetro *fields* (``TD = TypedDict(\"TD\", None)``) também está " -"descontinuada. Ambos não serão permitidos no Python 3.15. Para criar uma " -"classe :class:`!TypedDict` com 0 campos, use ``class TD(TypedDict): pass`` " -"ou ``TD = TypedDict(\"TD\", {})``." +":meth:`.PurePath.is_reserved` has been deprecated since Python 3.13. Use :" +"func:`os.path.isreserved` to detect reserved paths on Windows." +msgstr "" +":meth:`.PurePath.is_reserved` foi descontinuado desde o Python 3.13. Use :" +"func:`os.path.isreserved` para detectar caminhos reservados no Windows." + +#: ../../deprecations/pending-removal-in-3.15.rst:52 +msgid ":mod:`platform`:" +msgstr ":mod:`platform`:" #: ../../deprecations/pending-removal-in-3.15.rst:54 msgid "" -":mod:`wave`: Deprecate the ``getmark()``, ``setmark()`` and ``getmarkers()`` " -"methods of the :class:`wave.Wave_read` and :class:`wave.Wave_write` classes. " -"They will be removed in Python 3.15. (Contributed by Victor Stinner in :gh:" -"`105096`.)" +":func:`~platform.java_ver` has been deprecated since Python 3.13. This " +"function is only useful for Jython support, has a confusing API, and is " +"largely untested." +msgstr "" +":func:`~platform.java_ver` foi descontinuada desde o Python 3.13. Esta " +"função é útil apenas para suporte Jython, tem uma API confusa e é amplamente " +"não testada." + +#: ../../deprecations/pending-removal-in-3.15.rst:58 +msgid ":mod:`sysconfig`:" +msgstr ":mod:`sysconfig`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:60 +msgid "" +"The *check_home* argument of :func:`sysconfig.is_python_build` has been " +"deprecated since Python 3.12." +msgstr "" +"O argumento *check_home* de :func:`sysconfig.is_python_build` foi " +"descontinuado desde o Python 3.12." + +#: ../../deprecations/pending-removal-in-3.15.rst:63 +msgid ":mod:`threading`:" +msgstr ":mod:`threading`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:65 +msgid "" +":func:`~threading.RLock` will take no arguments in Python 3.15. Passing any " +"arguments has been deprecated since Python 3.14, as the Python version does " +"not permit any arguments, but the C version allows any number of positional " +"or keyword arguments, ignoring every argument." +msgstr "" +":func:`~threading.RLock` não aceitará argumentos no Python 3.15. A passagem " +"quaisquer argumentos foi descontinuada desde o Python 3.14, pois a versão " +"Python não permite nenhum argumento, mas a versão C permite qualquer número " +"de argumentos posicionais ou nomeados, ignorando todos os argumentos." + +#: ../../deprecations/pending-removal-in-3.15.rst:71 +msgid ":mod:`types`:" +msgstr ":mod:`types`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:73 +msgid "" +":class:`types.CodeType`: Accessing :attr:`~codeobject.co_lnotab` was " +"deprecated in :pep:`626` since 3.10 and was planned to be removed in 3.12, " +"but it only got a proper :exc:`DeprecationWarning` in 3.12. May be removed " +"in 3.15. (Contributed by Nikita Sobolev in :gh:`101866`.)" +msgstr "" +":class:`types.CodeType`: o acesso a :attr:`~codeobject.co_lnotab` foi " +"descontinuado na :pep:`626` desde 3.10 e foi planejado para ser removido em " +"3.12, mas só recebeu uma :exc:`DeprecationWarning` adequada em 3.12. Pode " +"ser removido em 3.15. (Contribuição de Nikita Sobolev em :gh:`101866`.)" + +#: ../../deprecations/pending-removal-in-3.15.rst:80 +msgid ":mod:`typing`:" +msgstr ":mod:`typing`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:82 +msgid "" +"The undocumented keyword argument syntax for creating :class:`~typing." +"NamedTuple` classes (e.g. ``Point = NamedTuple(\"Point\", x=int, y=int)``) " +"has been deprecated since Python 3.13. Use the class-based syntax or the " +"functional syntax instead." +msgstr "" +"A sintaxe de argumento nomeado não documentada para criar classes :class:" +"`~typing.NamedTuple` (por exemplo, ``Point = NamedTuple(\"Point\", x=int, " +"y=int)``) foi descontinuada desde o Python 3.13. Use a sintaxe baseada em " +"classe ou a sintaxe funcional em vez disso." + +#: ../../deprecations/pending-removal-in-3.15.rst:88 +msgid "" +"When using the functional syntax of :class:`~typing.TypedDict`\\s, failing " +"to pass a value to the *fields* parameter (``TD = TypedDict(\"TD\")``) or " +"passing ``None`` (``TD = TypedDict(\"TD\", None)``) has been deprecated " +"since Python 3.13. Use ``class TD(TypedDict): pass`` or ``TD = " +"TypedDict(\"TD\", {})`` to create a TypedDict with zero field." +msgstr "" +"Ao usar a sintaxe funcional de :class:`~typing.TypedDict`\\s, não passar um " +"valor para o parâmetro *fields* (``TD = TypedDict(\"TD\")``) ou passar " +"``None`` (``TD = TypedDict(\"TD\", None)``) foi está descontinuado desde o " +"Python 3.13. Use ``class TD(TypedDict): pass`` ou ``TD = TypedDict(\"TD\", " +"{})`` para criar uma classe TypedDict com nenhum campo." + +#: ../../deprecations/pending-removal-in-3.15.rst:95 +msgid "" +"The :func:`typing.no_type_check_decorator` decorator function has been " +"deprecated since Python 3.13. After eight years in the :mod:`typing` module, " +"it has yet to be supported by any major type checker." +msgstr "" +"A função decoradora :func:`typing.no_type_check_decorator` foi descontinuada " +"desde o Python 3.13. Após oito anos no módulo :mod:`typing`, ela ainda não " +"foi suportada por nenhum verificador de tipo importante." + +#: ../../deprecations/pending-removal-in-3.15.rst:100 +msgid ":mod:`wave`:" +msgstr ":mod:`wave`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:102 +msgid "" +"The :meth:`~wave.Wave_read.getmark`, :meth:`!setmark`, and :meth:`~wave." +"Wave_read.getmarkers` methods of the :class:`~wave.Wave_read` and :class:" +"`~wave.Wave_write` classes have been deprecated since Python 3.13." msgstr "" -":mod:`wave`: Descontinua os métodos ``getmark()``, ``setmark()`` e " -"``getmarkers()`` das classes :class:`wave.Wave_read` e :class:`wave." -"Wave_write`. Eles serão removidos no Python 3.15. (Contribuição de Victor " -"Stinner em :gh:`105096`.)" +"Os métodos :meth:`~wave.Wave_read.getmark`, :meth:`!setmark` e :meth:`~wave." +"Wave_read.getmarkers` das classes :class:`~wave.Wave_read` e :class:`~wave." +"Wave_write` foram descontinuados desde o Python 3.13." diff --git a/deprecations/pending-removal-in-3.16.po b/deprecations/pending-removal-in-3.16.po index 583ef4cec..a1808fe0a 100644 --- a/deprecations/pending-removal-in-3.16.po +++ b/deprecations/pending-removal-in-3.16.po @@ -1,44 +1,144 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2024-07-20 00:54+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../deprecations/pending-removal-in-3.16.rst:2 -msgid "Pending Removal in Python 3.16" +msgid "Pending removal in Python 3.16" msgstr "Remoção pendente no Python 3.16" #: ../../deprecations/pending-removal-in-3.16.rst:4 +msgid "The import system:" +msgstr "O sistema de importação:" + +#: ../../deprecations/pending-removal-in-3.16.rst:6 +msgid "" +"Setting :attr:`~module.__loader__` on a module while failing to set :attr:" +"`__spec__.loader ` is deprecated. In " +"Python 3.16, :attr:`!__loader__` will cease to be set or taken into " +"consideration by the import system or the standard library." +msgstr "" +"A definição de :attr:`~module.__loader__` em um módulo enquanto falha na " +"definição de :attr:`__spec__.loader ` " +"está descontinuado. No Python 3.16, :attr:`!__loader__` deixará de ser " +"definido ou levado em consideração pelo sistema de importação ou pela " +"biblioteca padrão." + +#: ../../deprecations/pending-removal-in-3.16.rst:11 +msgid ":mod:`array`:" +msgstr ":mod:`array`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:13 +msgid "" +"The ``'u'`` format code (:c:type:`wchar_t`) has been deprecated in " +"documentation since Python 3.3 and at runtime since Python 3.13. Use the " +"``'w'`` format code (:c:type:`Py_UCS4`) for Unicode characters instead." +msgstr "" +"O código de formato ``'u'`` (:c:type:`wchar_t`) foi descontinuado na " +"documentação desde o Python 3.3 e do ambiente de execução desde o Python " +"3.13. Em vez disso, use o código de formato ``'w'`` (:c:type:`Py_UCS4`) para " +"caracteres Unicode." + +#: ../../deprecations/pending-removal-in-3.16.rst:19 +msgid ":mod:`asyncio`:" +msgstr ":mod:`asyncio`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:21 +msgid "" +":func:`!asyncio.iscoroutinefunction` is deprecated and will be removed in " +"Python 3.16, use :func:`inspect.iscoroutinefunction` instead. (Contributed " +"by Jiahao Li and Kumar Aditya in :gh:`122875`.)" +msgstr "" +":func:`!asyncio.iscoroutinefunction` foi descontinuado e será removido no " +"Python 3.16, use :func:`inspect.iscoroutinefunction` em vez disso. " +"(Contribuição de Jiahao Li e Kumar Aditya em :gh:`122875`.)" + +#: ../../deprecations/pending-removal-in-3.16.rst:26 +msgid ":mod:`builtins`:" +msgstr ":mod:`builtins`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:28 +msgid "" +"Bitwise inversion on boolean types, ``~True`` or ``~False`` has been " +"deprecated since Python 3.12, as it produces surprising and unintuitive " +"results (``-2`` and ``-1``). Use ``not x`` instead for the logical negation " +"of a Boolean. In the rare case that you need the bitwise inversion of the " +"underlying integer, convert to ``int`` explicitly (``~int(x)``)." +msgstr "" +"A inversão bit a bit em tipos booleanos, ``~True`` ou ``~False`` foi " +"descontinuada desde o Python 3.12, pois produz resultados surpreendentes e " +"não intuitivos (``-2`` e ``-1``). Em vez disso, use ``not x`` para a negação " +"lógica de um booleano. No caso raro de você precisar da inversão bit a bit " +"do inteiro subjacente, converta para ``int`` explicitamente (``~int(x)``)." + +#: ../../deprecations/pending-removal-in-3.16.rst:35 +msgid ":mod:`shutil`:" +msgstr ":mod:`shutil`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:37 +msgid "" +"The :class:`!ExecError` exception has been deprecated since Python 3.14. It " +"has not been used by any function in :mod:`!shutil` since Python 3.4, and is " +"now an alias of :exc:`RuntimeError`." +msgstr "" +"A exceção :class:`!ExecError` foi descontinuada desde o Python 3.14. Ela não " +"foi usada por nenhuma função em :mod:`!shutil` desde o Python 3.4, e agora é " +"um alias de :exc:`RuntimeError`." + +#: ../../deprecations/pending-removal-in-3.16.rst:42 +msgid ":mod:`symtable`:" +msgstr ":mod:`symtable`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:44 msgid "" -":mod:`array`: :class:`array.array` ``'u'`` type (:c:type:`wchar_t`): use the " -"``'w'`` type instead (``Py_UCS4``)." +"The :meth:`Class.get_methods ` method has been " +"deprecated since Python 3.14." msgstr "" -":mod:`array`: :class:`array.array`: tipo ``'u'`` (:c:type:`wchar_t`): use o " -"tipo ``'w'`` (``Py_UCS4``)." +"O método :meth:`Class.get_methods ` foi " +"descontinuado desde o Python 3.14." + +#: ../../deprecations/pending-removal-in-3.16.rst:47 +msgid ":mod:`sys`:" +msgstr ":mod:`sys`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:49 +msgid "" +"The :func:`~sys._enablelegacywindowsfsencoding` function has been deprecated " +"since Python 3.13. Use the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` " +"environment variable instead." +msgstr "" +"A função :func:`~sys._enablelegacywindowsfsencoding` foi descontinuada desde " +"o Python 3.13. Em vez disso, use a variável de ambiente :envvar:" +"`PYTHONLEGACYWINDOWSFSENCODING`." + +#: ../../deprecations/pending-removal-in-3.16.rst:53 +msgid ":mod:`tarfile`:" +msgstr ":mod:`tarfile`:" -#: ../../deprecations/pending-removal-in-3.16.rst:8 +#: ../../deprecations/pending-removal-in-3.16.rst:55 msgid "" -":mod:`symtable`: Deprecate :meth:`symtable.Class.get_methods` due to the " -"lack of interest. (Contributed by Bénédikt Tran in :gh:`119698`.)" +"The undocumented and unused :attr:`!TarFile.tarfile` attribute has been " +"deprecated since Python 3.13." msgstr "" -":mod:`symtable`: Descontinua :meth:`symtable.Class.get_methods` por falta de " -"interesse. (Contribuição de Bénédikt Tran em :gh:`119698`.)" +"O atributo não documentado e não utilizado :attr:`!TarFile.tarfile` foi " +"descontinuado desde o Python 3.13." diff --git a/deprecations/pending-removal-in-future.po b/deprecations/pending-removal-in-future.po index c316e153c..4f0e0bd8d 100644 --- a/deprecations/pending-removal-in-future.po +++ b/deprecations/pending-removal-in-future.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2024-07-20 00:54+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-02 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -44,32 +44,24 @@ msgstr "" "grupos mutuamente exclusivos estão descontinuados." #: ../../deprecations/pending-removal-in-future.rst:10 -msgid ":mod:`array`'s ``'u'`` format code (:gh:`57281`)" -msgstr "código de formatação ``'u'`` do :mod:`array` (:gh:`57281`)" - -#: ../../deprecations/pending-removal-in-future.rst:12 msgid ":mod:`builtins`:" msgstr ":mod:`builtins`:" -#: ../../deprecations/pending-removal-in-future.rst:14 -msgid "``~bool``, bitwise inversion on bool." -msgstr "``~bool``, inversão bit a bit em booleanos." - -#: ../../deprecations/pending-removal-in-future.rst:15 +#: ../../deprecations/pending-removal-in-future.rst:12 msgid "``bool(NotImplemented)``." msgstr "``bool(NotImplemented)``." -#: ../../deprecations/pending-removal-in-future.rst:16 +#: ../../deprecations/pending-removal-in-future.rst:13 msgid "" "Generators: ``throw(type, exc, tb)`` and ``athrow(type, exc, tb)`` signature " "is deprecated: use ``throw(exc)`` and ``athrow(exc)`` instead, the single " "argument signature." msgstr "" -"Geradores: A assinatura ``throw(type, exc, tb)`` e ``athrow(type, exc, tb)`` " +"Geradores: a assinatura ``throw(type, exc, tb)`` e ``athrow(type, exc, tb)`` " "está descontinuada: use ``throw(exc)`` e ``athrow(exc)``, a assinatura do " "argumento único." -#: ../../deprecations/pending-removal-in-future.rst:19 +#: ../../deprecations/pending-removal-in-future.rst:16 msgid "" "Currently Python accepts numeric literals immediately followed by keywords, " "for example ``0in x``, ``1or x``, ``0if 1else 2``. It allows confusing and " @@ -90,7 +82,7 @@ msgstr "" "e :keyword:`or`. Em uma versão futura, será alterado para um erro de " "sintaxe. (:gh:`87999`)" -#: ../../deprecations/pending-removal-in-future.rst:27 +#: ../../deprecations/pending-removal-in-future.rst:24 msgid "" "Support for ``__index__()`` and ``__int__()`` method returning non-int type: " "these methods will be required to return an instance of a strict subclass " @@ -100,7 +92,7 @@ msgstr "" "int: esses métodos serão necessários para retornar uma instância de uma " "subclasse estrita de :class:`int`." -#: ../../deprecations/pending-removal-in-future.rst:30 +#: ../../deprecations/pending-removal-in-future.rst:27 msgid "" "Support for ``__float__()`` method returning a strict subclass of :class:" "`float`: these methods will be required to return an instance of :class:" @@ -110,7 +102,7 @@ msgstr "" "class:`float`: esses métodos serão necessários para retornar uma instância " "de :class:`float`." -#: ../../deprecations/pending-removal-in-future.rst:33 +#: ../../deprecations/pending-removal-in-future.rst:30 msgid "" "Support for ``__complex__()`` method returning a strict subclass of :class:" "`complex`: these methods will be required to return an instance of :class:" @@ -120,11 +112,11 @@ msgstr "" "class:`complex`: esses métodos serão necessários para retornar uma instância " "de :class:`complex`." -#: ../../deprecations/pending-removal-in-future.rst:36 +#: ../../deprecations/pending-removal-in-future.rst:33 msgid "Delegation of ``int()`` to ``__trunc__()`` method." msgstr "Delegação do método ``int()`` para o ``__trunc__()``." -#: ../../deprecations/pending-removal-in-future.rst:37 +#: ../../deprecations/pending-removal-in-future.rst:34 msgid "" "Passing a complex number as the *real* or *imag* argument in the :func:" "`complex` constructor is now deprecated; it should only be passed as a " @@ -136,28 +128,28 @@ msgstr "" "único argumento posicional. (Contribuição de Serhiy Storchaka em :gh:" "`109218`.)" -#: ../../deprecations/pending-removal-in-future.rst:42 +#: ../../deprecations/pending-removal-in-future.rst:39 msgid "" ":mod:`calendar`: ``calendar.January`` and ``calendar.February`` constants " "are deprecated and replaced by :data:`calendar.JANUARY` and :data:`calendar." "FEBRUARY`. (Contributed by Prince Roshan in :gh:`103636`.)" msgstr "" -":mod:`calendar`: As constantes ``calendar.January`` e ``calendar.February`` " +":mod:`calendar`: as constantes ``calendar.January`` e ``calendar.February`` " "foram descontinuadas e substituídas por :data:`calendar.JANUARY` e :data:" "`calendar.FEBRUARY`. (Contribuição de Prince Roshan em :gh:`103636`.)" -#: ../../deprecations/pending-removal-in-future.rst:47 +#: ../../deprecations/pending-removal-in-future.rst:44 msgid "" ":attr:`codeobject.co_lnotab`: use the :meth:`codeobject.co_lines` method " "instead." msgstr "" ":attr:`codeobject.co_lnotab`: use o método :meth:`codeobject.co_lines`." -#: ../../deprecations/pending-removal-in-future.rst:50 +#: ../../deprecations/pending-removal-in-future.rst:47 msgid ":mod:`datetime`:" msgstr ":mod:`datetime`:" -#: ../../deprecations/pending-removal-in-future.rst:52 +#: ../../deprecations/pending-removal-in-future.rst:49 msgid "" ":meth:`~datetime.datetime.utcnow`: use ``datetime.datetime.now(tz=datetime." "UTC)``." @@ -165,7 +157,7 @@ msgstr "" ":meth:`~datetime.datetime.utcnow`: use ``datetime.datetime.now(tz=datetime." "UTC)``." -#: ../../deprecations/pending-removal-in-future.rst:54 +#: ../../deprecations/pending-removal-in-future.rst:51 msgid "" ":meth:`~datetime.datetime.utcfromtimestamp`: use ``datetime.datetime." "fromtimestamp(timestamp, tz=datetime.UTC)``." @@ -173,68 +165,64 @@ msgstr "" ":meth:`~datetime.datetime.utcfromtimestamp`: use ``datetime.datetime." "fromtimestamp(timestamp, tz=datetime.UTC)``." -#: ../../deprecations/pending-removal-in-future.rst:57 +#: ../../deprecations/pending-removal-in-future.rst:54 msgid ":mod:`gettext`: Plural value must be an integer." -msgstr ":mod:`gettext`: O valor de plural deve ser um número inteiro." +msgstr ":mod:`gettext`: o valor de plural deve ser um número inteiro." -#: ../../deprecations/pending-removal-in-future.rst:59 +#: ../../deprecations/pending-removal-in-future.rst:56 msgid ":mod:`importlib`:" msgstr ":mod:`importlib`:" -#: ../../deprecations/pending-removal-in-future.rst:61 -msgid "``load_module()`` method: use ``exec_module()`` instead." -msgstr "Método ``load_module()``: use ``exec_module()`` em vez disso." - -#: ../../deprecations/pending-removal-in-future.rst:62 +#: ../../deprecations/pending-removal-in-future.rst:58 msgid "" ":func:`~importlib.util.cache_from_source` *debug_override* parameter is " "deprecated: use the *optimization* parameter instead." msgstr "" "O parâmetro *debug_override* de :func:`~importlib.util.cache_from_source` " -"foi descontinuado: em vez disso, use o parâmetro *optimization*." +"foi descontinuado: use o parâmetro *optimization*." -#: ../../deprecations/pending-removal-in-future.rst:65 +#: ../../deprecations/pending-removal-in-future.rst:61 msgid ":mod:`importlib.metadata`:" msgstr ":mod:`importlib.metadata`:" -#: ../../deprecations/pending-removal-in-future.rst:67 +#: ../../deprecations/pending-removal-in-future.rst:63 msgid "``EntryPoints`` tuple interface." msgstr "Interface de tupla ``EntryPoints``." -#: ../../deprecations/pending-removal-in-future.rst:68 +#: ../../deprecations/pending-removal-in-future.rst:64 msgid "Implicit ``None`` on return values." msgstr "``None`` implícito nos valores de retorno." -#: ../../deprecations/pending-removal-in-future.rst:70 +#: ../../deprecations/pending-removal-in-future.rst:66 msgid "" ":mod:`logging`: the ``warn()`` method has been deprecated since Python 3.3, " -"use :meth:`~logging.warning()` instead." +"use :meth:`~logging.warning` instead." msgstr "" ":mod:`logging`: o método ``warn()`` foi descontinuado desde o Python 3.3, " -"use :meth:`~logging.warning()`." +"use :meth:`~logging.warning`." -#: ../../deprecations/pending-removal-in-future.rst:73 +#: ../../deprecations/pending-removal-in-future.rst:69 msgid "" ":mod:`mailbox`: Use of StringIO input and text mode is deprecated, use " "BytesIO and binary mode instead." msgstr "" -":mod:`mailbox`: O uso da entrada StringIO e do modo de texto foi " +":mod:`mailbox`: o uso da entrada StringIO e do modo de texto foi " "descontinuado; em vez disso, use BytesIO e o modo binário." -#: ../../deprecations/pending-removal-in-future.rst:76 +#: ../../deprecations/pending-removal-in-future.rst:72 msgid "" ":mod:`os`: Calling :func:`os.register_at_fork` in multi-threaded process." -msgstr ":mod:`os`: Chamar :func:`os.register_at_fork` em processo multithread." +msgstr ":mod:`os`: chame :func:`os.register_at_fork` em processo multithread." -#: ../../deprecations/pending-removal-in-future.rst:78 +#: ../../deprecations/pending-removal-in-future.rst:74 msgid "" ":class:`!pydoc.ErrorDuringImport`: A tuple value for *exc_info* parameter is " "deprecated, use an exception instance." msgstr "" -":class:`!pydoc.ErrorDuringImport`: Um valor de tupla para o parâmetro " +":class:`!pydoc.ErrorDuringImport`: um valor de tupla para o parâmetro " "*exc_info* foi descontinuado, use uma instância de exceção." -#: ../../deprecations/pending-removal-in-future.rst:81 +#: ../../deprecations/pending-removal-in-future.rst:77 msgid "" ":mod:`re`: More strict rules are now applied for numerical group references " "and group names in regular expressions. Only sequence of ASCII digits is " @@ -242,96 +230,88 @@ msgid "" "replacement strings can now only contain ASCII letters and digits and " "underscore. (Contributed by Serhiy Storchaka in :gh:`91760`.)" msgstr "" -":mod:`re`: Regras mais rigorosas agora são aplicadas para referências " +":mod:`re`: regras mais rigorosas agora são aplicadas para referências " "numéricas de grupos e nomes de grupos em expressões regulares. Apenas a " "sequência de dígitos ASCII agora é aceita como referência numérica. O nome " "do grupo em padrões de bytes e strings de substituição agora pode conter " "apenas letras e dígitos ASCII e sublinhado. (Contribuição de Serhiy " "Storchaka em :gh:`91760`.)" -#: ../../deprecations/pending-removal-in-future.rst:88 +#: ../../deprecations/pending-removal-in-future.rst:84 msgid "" ":mod:`!sre_compile`, :mod:`!sre_constants` and :mod:`!sre_parse` modules." msgstr "" "Módulos :mod:`!sre_compile`, :mod:`!sre_constants` e :mod:`!sre_parse`." -#: ../../deprecations/pending-removal-in-future.rst:90 +#: ../../deprecations/pending-removal-in-future.rst:86 msgid "" ":mod:`shutil`: :func:`~shutil.rmtree`'s *onerror* parameter is deprecated in " "Python 3.12; use the *onexc* parameter instead." msgstr "" -":mod:`shutil`: O parâmetro *onerror* de :func:`~shutil.rmtree` foi " +":mod:`shutil`: o parâmetro *onerror* de :func:`~shutil.rmtree` foi " "descontinuado no Python 3.12; use o parâmetro *onexc*." -#: ../../deprecations/pending-removal-in-future.rst:93 +#: ../../deprecations/pending-removal-in-future.rst:89 msgid ":mod:`ssl` options and protocols:" msgstr "Protocolos e opções de :mod:`ssl`" -#: ../../deprecations/pending-removal-in-future.rst:95 +#: ../../deprecations/pending-removal-in-future.rst:91 msgid ":class:`ssl.SSLContext` without protocol argument is deprecated." msgstr ":class:`ssl.SSLContext` sem argumento de protocolo foi descontinuado." -#: ../../deprecations/pending-removal-in-future.rst:96 +#: ../../deprecations/pending-removal-in-future.rst:92 msgid "" ":class:`ssl.SSLContext`: :meth:`~ssl.SSLContext.set_npn_protocols` and :meth:" "`!selected_npn_protocol` are deprecated: use ALPN instead." msgstr "" ":class:`ssl.SSLContext`: :meth:`~ssl.SSLContext.set_npn_protocols` e :meth:`!" -"selected_npn_protocol` foram descontinuados: use ALPN." +"selected_npn_protocol` foram descontinuados, use ALPN." -#: ../../deprecations/pending-removal-in-future.rst:99 +#: ../../deprecations/pending-removal-in-future.rst:95 msgid "``ssl.OP_NO_SSL*`` options" msgstr "Opções de ``ssl.OP_NO_SSL*``" -#: ../../deprecations/pending-removal-in-future.rst:100 +#: ../../deprecations/pending-removal-in-future.rst:96 msgid "``ssl.OP_NO_TLS*`` options" msgstr "Opções de ``ssl.OP_NO_TLS*``" -#: ../../deprecations/pending-removal-in-future.rst:101 +#: ../../deprecations/pending-removal-in-future.rst:97 msgid "``ssl.PROTOCOL_SSLv3``" msgstr "``ssl.PROTOCOL_SSLv3``" -#: ../../deprecations/pending-removal-in-future.rst:102 +#: ../../deprecations/pending-removal-in-future.rst:98 msgid "``ssl.PROTOCOL_TLS``" msgstr "``ssl.PROTOCOL_TLS``" -#: ../../deprecations/pending-removal-in-future.rst:103 +#: ../../deprecations/pending-removal-in-future.rst:99 msgid "``ssl.PROTOCOL_TLSv1``" msgstr "``ssl.PROTOCOL_TLSv1``" -#: ../../deprecations/pending-removal-in-future.rst:104 +#: ../../deprecations/pending-removal-in-future.rst:100 msgid "``ssl.PROTOCOL_TLSv1_1``" msgstr "``ssl.PROTOCOL_TLSv1_1``" -#: ../../deprecations/pending-removal-in-future.rst:105 +#: ../../deprecations/pending-removal-in-future.rst:101 msgid "``ssl.PROTOCOL_TLSv1_2``" msgstr "``ssl.PROTOCOL_TLSv1_2``" -#: ../../deprecations/pending-removal-in-future.rst:106 +#: ../../deprecations/pending-removal-in-future.rst:102 msgid "``ssl.TLSVersion.SSLv3``" msgstr "``ssl.TLSVersion.SSLv3``" -#: ../../deprecations/pending-removal-in-future.rst:107 +#: ../../deprecations/pending-removal-in-future.rst:103 msgid "``ssl.TLSVersion.TLSv1``" msgstr "``ssl.TLSVersion.TLSv1``" -#: ../../deprecations/pending-removal-in-future.rst:108 +#: ../../deprecations/pending-removal-in-future.rst:104 msgid "``ssl.TLSVersion.TLSv1_1``" msgstr "``ssl.TLSVersion.TLSv1_1``" -#: ../../deprecations/pending-removal-in-future.rst:110 -msgid "" -":func:`sysconfig.is_python_build` *check_home* parameter is deprecated and " -"ignored." -msgstr "" -"O parâmetro *check_home* de :func:`sysconfig.is_python_build` foi " -"descontinuado e é ignorado." - -#: ../../deprecations/pending-removal-in-future.rst:113 +#: ../../deprecations/pending-removal-in-future.rst:106 msgid ":mod:`threading` methods:" msgstr "Métodos de :mod:`threading`:" -#: ../../deprecations/pending-removal-in-future.rst:115 +#: ../../deprecations/pending-removal-in-future.rst:108 msgid "" ":meth:`!threading.Condition.notifyAll`: use :meth:`~threading.Condition." "notify_all`." @@ -339,11 +319,11 @@ msgstr "" ":meth:`!threading.Condition.notifyAll`: use :meth:`~threading.Condition." "notify_all`." -#: ../../deprecations/pending-removal-in-future.rst:116 +#: ../../deprecations/pending-removal-in-future.rst:109 msgid ":meth:`!threading.Event.isSet`: use :meth:`~threading.Event.is_set`." msgstr ":meth:`!threading.Event.isSet`: use :meth:`~threading.Event.is_set`." -#: ../../deprecations/pending-removal-in-future.rst:117 +#: ../../deprecations/pending-removal-in-future.rst:110 msgid "" ":meth:`!threading.Thread.isDaemon`, :meth:`threading.Thread.setDaemon`: use :" "attr:`threading.Thread.daemon` attribute." @@ -351,7 +331,7 @@ msgstr "" ":meth:`!threading.Thread.isDaemon`, :meth:`threading.Thread.setDaemon`: use " "o atributo :attr:`threading.Thread.daemon`." -#: ../../deprecations/pending-removal-in-future.rst:119 +#: ../../deprecations/pending-removal-in-future.rst:112 msgid "" ":meth:`!threading.Thread.getName`, :meth:`threading.Thread.setName`: use :" "attr:`threading.Thread.name` attribute." @@ -359,20 +339,20 @@ msgstr "" ":meth:`!threading.Thread.getName`, :meth:`threading.Thread.setName`: use o " "atributo :attr:`threading.Thread.name`." -#: ../../deprecations/pending-removal-in-future.rst:121 +#: ../../deprecations/pending-removal-in-future.rst:114 msgid ":meth:`!threading.currentThread`: use :meth:`threading.current_thread`." msgstr "" ":meth:`!threading.currentThread`: use :meth:`threading.current_thread`." -#: ../../deprecations/pending-removal-in-future.rst:122 +#: ../../deprecations/pending-removal-in-future.rst:115 msgid ":meth:`!threading.activeCount`: use :meth:`threading.active_count`." msgstr ":meth:`!threading.activeCount`: use :meth:`threading.active_count`." -#: ../../deprecations/pending-removal-in-future.rst:124 +#: ../../deprecations/pending-removal-in-future.rst:117 msgid ":class:`typing.Text` (:gh:`92332`)." msgstr ":class:`typing.Text` (:gh:`92332`)." -#: ../../deprecations/pending-removal-in-future.rst:126 +#: ../../deprecations/pending-removal-in-future.rst:119 msgid "" ":class:`unittest.IsolatedAsyncioTestCase`: it is deprecated to return a " "value that is not ``None`` from a test case." @@ -380,7 +360,7 @@ msgstr "" ":class:`unittest.IsolatedAsyncioTestCase`: foi descontinuado retornar um " "valor que não seja ``None`` de um caso de teste." -#: ../../deprecations/pending-removal-in-future.rst:129 +#: ../../deprecations/pending-removal-in-future.rst:122 msgid "" ":mod:`urllib.parse` deprecated functions: :func:`~urllib.parse.urlparse` " "instead" @@ -388,51 +368,51 @@ msgstr "" "Funções descontinuadas de :mod:`urllib.parse`: use :func:`~urllib.parse." "urlparse`" -#: ../../deprecations/pending-removal-in-future.rst:131 +#: ../../deprecations/pending-removal-in-future.rst:124 msgid "``splitattr()``" msgstr "``splitattr()``" -#: ../../deprecations/pending-removal-in-future.rst:132 +#: ../../deprecations/pending-removal-in-future.rst:125 msgid "``splithost()``" msgstr "``splithost()``" -#: ../../deprecations/pending-removal-in-future.rst:133 +#: ../../deprecations/pending-removal-in-future.rst:126 msgid "``splitnport()``" msgstr "``splitnport()``" -#: ../../deprecations/pending-removal-in-future.rst:134 +#: ../../deprecations/pending-removal-in-future.rst:127 msgid "``splitpasswd()``" msgstr "``splitpasswd()``" -#: ../../deprecations/pending-removal-in-future.rst:135 +#: ../../deprecations/pending-removal-in-future.rst:128 msgid "``splitport()``" msgstr "``splitport()``" -#: ../../deprecations/pending-removal-in-future.rst:136 +#: ../../deprecations/pending-removal-in-future.rst:129 msgid "``splitquery()``" msgstr "``splitquery()``" -#: ../../deprecations/pending-removal-in-future.rst:137 +#: ../../deprecations/pending-removal-in-future.rst:130 msgid "``splittag()``" msgstr "``splittag()``" -#: ../../deprecations/pending-removal-in-future.rst:138 +#: ../../deprecations/pending-removal-in-future.rst:131 msgid "``splittype()``" msgstr "``splittype()``" -#: ../../deprecations/pending-removal-in-future.rst:139 +#: ../../deprecations/pending-removal-in-future.rst:132 msgid "``splituser()``" msgstr "``splituser()``" -#: ../../deprecations/pending-removal-in-future.rst:140 +#: ../../deprecations/pending-removal-in-future.rst:133 msgid "``splitvalue()``" msgstr "``splitvalue()``" -#: ../../deprecations/pending-removal-in-future.rst:141 +#: ../../deprecations/pending-removal-in-future.rst:134 msgid "``to_bytes()``" msgstr "``to_bytes()``" -#: ../../deprecations/pending-removal-in-future.rst:143 +#: ../../deprecations/pending-removal-in-future.rst:136 msgid "" ":mod:`urllib.request`: :class:`~urllib.request.URLopener` and :class:" "`~urllib.request.FancyURLopener` style of invoking requests is deprecated. " @@ -443,7 +423,7 @@ msgstr "" "descontinuado. Use as mais novas funções e métodos :func:`~urllib.request." "urlopen`." -#: ../../deprecations/pending-removal-in-future.rst:147 +#: ../../deprecations/pending-removal-in-future.rst:140 msgid "" ":mod:`wsgiref`: ``SimpleHandler.stdout.write()`` should not do partial " "writes." @@ -451,7 +431,7 @@ msgstr "" ":mod:`wsgiref`: ``SimpleHandler.stdout.write()`` não deve fazer gravações " "parciais." -#: ../../deprecations/pending-removal-in-future.rst:150 +#: ../../deprecations/pending-removal-in-future.rst:143 msgid "" ":mod:`xml.etree.ElementTree`: Testing the truth value of an :class:`~xml." "etree.ElementTree.Element` is deprecated. In a future release it will always " @@ -463,7 +443,7 @@ msgstr "" "sempre retornará ``True``. Em vez disso, prefira os testes explícitos " "``len(elem)`` ou ``elem is not None``." -#: ../../deprecations/pending-removal-in-future.rst:155 +#: ../../deprecations/pending-removal-in-future.rst:148 msgid "" ":meth:`zipimport.zipimporter.load_module` is deprecated: use :meth:" "`~zipimport.zipimporter.exec_module` instead." diff --git a/dict b/dict deleted file mode 100644 index 13d5b70be..000000000 --- a/dict +++ /dev/null @@ -1,427 +0,0 @@ -Aahz -Abelson -ActivePython -Andrew -Android -Apple -Argparse -args -ArgumentParser -array -arrays -ascii -Ascii -async -asyncio -autoinicialização -aux -await -backend -backends -backport -bash -Bash -Beck -BeOpen -Bernstein -Bicking -bignum -binutils -bitbucket -Black -Blackbox -Blake Winton -Boddie -Boer -booleana -booleanas -Booleanas -booleano -booleanos -Borland -Bourne -breadth -buffer -buffers -bug -bugs -bytearray -bytearrays -bytecode -bytecodes -bzip -carregável -Cédric -Centrum -cfuhash -chamável -Changelog -Chapman -char -Christian -Circus -class -codec -Codecs -Coghlan -Collin -Compaq -const -contrabarra -Cookbook -cookies -Corporation -corrotina -corrotinas -ctypes -curl -currying -Cynthia -Cython -Dalke -Dan -D'Aprano -datetime -DateTime -deadlock -def -Delphi -desserialização -desserializar -dict -dicts -distutils -Distutils -dll -doc -docstring -docstrings -doctest -doctests -Docutils -Drake -dtoa -dunder -Efford -egid -ElementTree -elif -else -Emacs -email -Emily -emoji -emojis -Eric -Éric -errno -euid -Excel -except -exe -exec -execv -exp -false -float -Flying -foo -fork -Foundation -framework -frameworks -François -Fred -Fredrik -freeware -genexp -genexps -Gerald -gettext -Giampolo -GiB -git -Git -github -GitHub -glob -Gnumeric -Golden -Gordin -Gordon -Gregory -Grönholm -gzip -Hammond -Harold -hash -Haskell -Heimes -Heller -Henstridge -Hettinger -Hewlett -Hilbert -host -Hylton -HyperText -Ian -ids -if -import -index -Index -initgroups -Initiatives -int -Irix -IronPython -Jay -Jelke -Jeremy -Jewett -Jr -Julie -Jython -Kent -kernel -Kernel -kernels -KiB -kqueue -Krell -Kuchling -Language -len -libffi -libmpdec -libtclsam -libtksam -Lisp -listcomp -listcomps -localtime -log -logger -Logger -loggers -Loggers -logging -Logging -logs -loop -loops -Ltd -Ltda -Lucasfilm -Lundh -lzma -Mac -MacAfee -Macintosh -mail -mailheader -Majkowski -Marek -Mark -Markup -marshal -Mathematisch -McAfee -McMillan -memoizar -memoryview -MemoryView -Mertz -metacaractere -Metacaractere -metacaracteres -Metacaracteres -metaclasse -metaclasses -Microsoft -Minus -Mitch -mixin -mmap -Monty -Moshe -multithread -NaN -NaNs -National -ncurses -netrc -Neumann -Nick -numpy -NumPy -NxN -Object -OpenSolaris -OpenSuse -OverflowError -Packaging -Packard -patches -Patterns -pdb -PEP -Perl -Pillow -Pinard -pip -plugin -plugins -popen -PowerShell -printf -prompt -proxy -pty -PureProxy -py -Py -pyc -PyChecker -Pydb -Pylint -PyObject -PyPy -PyQt -PySide -python -Python -Pythônico -PythonLabs -Pythonwin -PythonWin -PyUnit -pyvenv -PyWin -PyZipFile -qNaN -Qt -Queens -Randal -Raymond -read -referenciável -regex -repr -Research -Reston -reStructuredText -rfc -rgid -root -Rossum -Roundup -Ruby -ruid -runner -Salmela -Sauvage -scanf -Scheme -Scintilla -scipy -script -scripts -Sébastien -self -serialização -setgroups -setup -setuptools -sgid -shareware -shebang -Shebang -shell -shells -Singleton -SipHash -Slice -slot -slots -smalltalk -sNaN -Snow -so -Solaris -SourceForge -spec -Sphinx -sscanf -Standard -stderr -stdin -stdout -Stichting -str -streams -Streams -stride -string -strtod -Studio -subcontexto -subcontextos -subpacote -subpacotes -subst -substring -subteste -suid -Sussman -switch -sys -tar -Tcl -Telnet -termcap -thread -threading -threads -Tix -Tk -Tkinter -token -tokens -traceback -true -try -tty -Tuininga -typedef -unicode -Unicode -unittest -upload -urllib -Usenet -User -ValueError -voltage -VxWorks -Water -wchar -while -widgets -Win -Windows -Winter -Winton -www -wxPython -wxwidgets -wxWidgets -WxWidgets -Xt -Yellow -Zadka -zipfile -ZipFile -zlib -Zope diff --git a/distributing/index.po b/distributing/index.po index 3606663a3..fa6c3c6d0 100644 --- a/distributing/index.po +++ b/distributing/index.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/extending/building.po b/extending/building.po index 660391905..d42bc1bf9 100644 --- a/extending/building.po +++ b/extending/building.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:51+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -77,6 +77,22 @@ msgstr "" "codificação *punycode* do Python com hifenes substituídos por sublinhados. " "Em Python::" +#: ../../extending/building.rst:32 +msgid "" +"def initfunc_name(name):\n" +" try:\n" +" suffix = b'_' + name.encode('ascii')\n" +" except UnicodeEncodeError:\n" +" suffix = b'U_' + name.encode('punycode').replace(b'-', b'_')\n" +" return b'PyInit' + suffix" +msgstr "" +"def nome_func_iniciadora(nome):\n" +" try:\n" +" sufixo = b'_' + nome.encode('ascii')\n" +" except UnicodeEncodeError:\n" +" sufixo = b'U_' + nome.encode('punycode').replace(b'-', b'_')\n" +" return b'PyInit' + sufixo" + #: ../../extending/building.rst:39 msgid "" "It is possible to export multiple modules from a single shared library by " diff --git a/extending/embedding.po b/extending/embedding.po index 31367f2d3..a770c4e50 100644 --- a/extending/embedding.po +++ b/extending/embedding.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 02:33+0000\n" -"PO-Revision-Date: 2021-06-28 00:51+0000\n" -"Last-Translator: Claudio Rogerio Carvalho Filho , " -"2021\n" +"POT-Creation-Date: 2025-03-07 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -41,6 +39,15 @@ msgid "" "writing some scripts in Python. You can also use it yourself if some of the " "functionality can be written in Python more easily." msgstr "" +"Os capítulos anteriores discutiram como estender o Python, ou seja, como " +"expandir a funcionalidade do Python anexando uma biblioteca de funções em C " +"a ele. Também é possível fazer o inverso: enriquecer sua aplicação em C/C++ " +"incorporando o Python nela. A incorporação fornece à sua aplicação a " +"capacidade de implementar parte da funcionalidade da aplicação em Python em " +"vez de C ou C++. Isso pode ser usado para diversos propósitos; um exemplo " +"seria permitir que os usuários personalizem a aplicação de acordo com suas " +"necessidades escrevendo alguns scripts em Python. Você também pode usá-la se " +"parte da funcionalidade puder ser escrita em Python mais facilmente." #: ../../extending/embedding.rst:20 msgid "" @@ -50,6 +57,12 @@ msgid "" "nothing to do with Python --- instead, some parts of the application " "occasionally call the Python interpreter to run some Python code." msgstr "" +"Incorporar o Python é semelhante a estendê-lo, mas não exatamente. A " +"diferença é que, ao estender o Python, o programa principal da aplicação " +"ainda é o interpretador Python, enquanto que, se você incorporar o Python, o " +"programa principal pode não ter nada a ver com o Python — em vez disso, " +"algumas partes da aplicação chamam ocasionalmente o interpretador Python " +"para executar algum código Python." #: ../../extending/embedding.rst:26 msgid "" @@ -93,6 +106,44 @@ msgid "" "used to perform some operation on a file. ::" msgstr "" +#: ../../extending/embedding.rst:56 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"\n" +"int\n" +"main(int argc, char *argv[])\n" +"{\n" +" PyStatus status;\n" +" PyConfig config;\n" +" PyConfig_InitPythonConfig(&config);\n" +"\n" +" /* optional but recommended */\n" +" status = PyConfig_SetBytesString(&config, &config.program_name, " +"argv[0]);\n" +" if (PyStatus_Exception(status)) {\n" +" goto exception;\n" +" }\n" +"\n" +" status = Py_InitializeFromConfig(&config);\n" +" if (PyStatus_Exception(status)) {\n" +" goto exception;\n" +" }\n" +" PyConfig_Clear(&config);\n" +"\n" +" PyRun_SimpleString(\"from time import time,ctime\\n\"\n" +" \"print('Today is', ctime(time()))\\n\");\n" +" if (Py_FinalizeEx() < 0) {\n" +" exit(120);\n" +" }\n" +" return 0;\n" +"\n" +" exception:\n" +" PyConfig_Clear(&config);\n" +" Py_ExitStatusException(status);\n" +"}" +msgstr "" + #: ../../extending/embedding.rst:92 msgid "" "``#define PY_SSIZE_T_CLEAN`` was used to indicate that ``Py_ssize_t`` should " @@ -199,6 +250,82 @@ msgstr "" msgid "The code to run a function defined in a Python script is:" msgstr "" +#: ../../extending/embedding.rst:162 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"\n" +"int\n" +"main(int argc, char *argv[])\n" +"{\n" +" PyObject *pName, *pModule, *pFunc;\n" +" PyObject *pArgs, *pValue;\n" +" int i;\n" +"\n" +" if (argc < 3) {\n" +" fprintf(stderr,\"Usage: call pythonfile funcname [args]\\n\");\n" +" return 1;\n" +" }\n" +"\n" +" Py_Initialize();\n" +" pName = PyUnicode_DecodeFSDefault(argv[1]);\n" +" /* Error checking of pName left out */\n" +"\n" +" pModule = PyImport_Import(pName);\n" +" Py_DECREF(pName);\n" +"\n" +" if (pModule != NULL) {\n" +" pFunc = PyObject_GetAttrString(pModule, argv[2]);\n" +" /* pFunc is a new reference */\n" +"\n" +" if (pFunc && PyCallable_Check(pFunc)) {\n" +" pArgs = PyTuple_New(argc - 3);\n" +" for (i = 0; i < argc - 3; ++i) {\n" +" pValue = PyLong_FromLong(atoi(argv[i + 3]));\n" +" if (!pValue) {\n" +" Py_DECREF(pArgs);\n" +" Py_DECREF(pModule);\n" +" fprintf(stderr, \"Cannot convert argument\\n\");\n" +" return 1;\n" +" }\n" +" /* pValue reference stolen here: */\n" +" PyTuple_SetItem(pArgs, i, pValue);\n" +" }\n" +" pValue = PyObject_CallObject(pFunc, pArgs);\n" +" Py_DECREF(pArgs);\n" +" if (pValue != NULL) {\n" +" printf(\"Result of call: %ld\\n\", PyLong_AsLong(pValue));\n" +" Py_DECREF(pValue);\n" +" }\n" +" else {\n" +" Py_DECREF(pFunc);\n" +" Py_DECREF(pModule);\n" +" PyErr_Print();\n" +" fprintf(stderr,\"Call failed\\n\");\n" +" return 1;\n" +" }\n" +" }\n" +" else {\n" +" if (PyErr_Occurred())\n" +" PyErr_Print();\n" +" fprintf(stderr, \"Cannot find function \\\"%s\\\"\\n\", " +"argv[2]);\n" +" }\n" +" Py_XDECREF(pFunc);\n" +" Py_DECREF(pModule);\n" +" }\n" +" else {\n" +" PyErr_Print();\n" +" fprintf(stderr, \"Failed to load \\\"%s\\\"\\n\", argv[1]);\n" +" return 1;\n" +" }\n" +" if (Py_FinalizeEx() < 0) {\n" +" return 120;\n" +" }\n" +" return 0;\n" +"}\n" +msgstr "" + #: ../../extending/embedding.rst:165 msgid "" "This code loads a Python script using ``argv[1]``, and calls the function " @@ -208,10 +335,27 @@ msgid "" "a Python script, such as:" msgstr "" +#: ../../extending/embedding.rst:171 +msgid "" +"def multiply(a,b):\n" +" print(\"Will compute\", a, \"times\", b)\n" +" c = 0\n" +" for i in range(0, a):\n" +" c = c + b\n" +" return c" +msgstr "" + #: ../../extending/embedding.rst:180 msgid "then the result should be:" msgstr "" +#: ../../extending/embedding.rst:182 +msgid "" +"$ call multiply multiply 3 2\n" +"Will compute 3 times 2\n" +"Result of call: 6" +msgstr "" + #: ../../extending/embedding.rst:188 msgid "" "Although the program is quite large for its functionality, most of the code " @@ -219,14 +363,33 @@ msgid "" "interesting part with respect to embedding Python starts with ::" msgstr "" +#: ../../extending/embedding.rst:192 +msgid "" +"Py_Initialize();\n" +"pName = PyUnicode_DecodeFSDefault(argv[1]);\n" +"/* Error checking of pName left out */\n" +"pModule = PyImport_Import(pName);" +msgstr "" + #: ../../extending/embedding.rst:197 msgid "" "After initializing the interpreter, the script is loaded using :c:func:" "`PyImport_Import`. This routine needs a Python string as its argument, " -"which is constructed using the :c:func:`PyUnicode_FromString` data " +"which is constructed using the :c:func:`PyUnicode_DecodeFSDefault` data " "conversion routine. ::" msgstr "" +#: ../../extending/embedding.rst:202 +msgid "" +"pFunc = PyObject_GetAttrString(pModule, argv[2]);\n" +"/* pFunc is a new reference */\n" +"\n" +"if (pFunc && PyCallable_Check(pFunc)) {\n" +" ...\n" +"}\n" +"Py_XDECREF(pFunc);" +msgstr "" + #: ../../extending/embedding.rst:210 msgid "" "Once the script is loaded, the name we're looking for is retrieved using :c:" @@ -236,6 +399,10 @@ msgid "" "Python function is then made with::" msgstr "" +#: ../../extending/embedding.rst:216 +msgid "pValue = PyObject_CallObject(pFunc, pArgs);" +msgstr "" + #: ../../extending/embedding.rst:218 msgid "" "Upon return of the function, ``pValue`` is either ``NULL`` or it contains a " @@ -259,12 +426,49 @@ msgid "" "like you would write a normal Python extension. For example::" msgstr "" +#: ../../extending/embedding.rst:237 +msgid "" +"static int numargs=0;\n" +"\n" +"/* Return the number of arguments of the application command line */\n" +"static PyObject*\n" +"emb_numargs(PyObject *self, PyObject *args)\n" +"{\n" +" if(!PyArg_ParseTuple(args, \":numargs\"))\n" +" return NULL;\n" +" return PyLong_FromLong(numargs);\n" +"}\n" +"\n" +"static PyMethodDef EmbMethods[] = {\n" +" {\"numargs\", emb_numargs, METH_VARARGS,\n" +" \"Return the number of arguments received by the process.\"},\n" +" {NULL, NULL, 0, NULL}\n" +"};\n" +"\n" +"static PyModuleDef EmbModule = {\n" +" PyModuleDef_HEAD_INIT, \"emb\", NULL, -1, EmbMethods,\n" +" NULL, NULL, NULL, NULL\n" +"};\n" +"\n" +"static PyObject*\n" +"PyInit_emb(void)\n" +"{\n" +" return PyModule_Create(&EmbModule);\n" +"}" +msgstr "" + #: ../../extending/embedding.rst:265 msgid "" "Insert the above code just above the :c:func:`main` function. Also, insert " "the following two statements before the call to :c:func:`Py_Initialize`::" msgstr "" +#: ../../extending/embedding.rst:268 +msgid "" +"numargs = argc;\n" +"PyImport_AppendInittab(\"emb\", &PyInit_emb);" +msgstr "" + #: ../../extending/embedding.rst:271 msgid "" "These two lines initialize the ``numargs`` variable, and make the :func:`!" @@ -272,6 +476,12 @@ msgid "" "these extensions, the Python script can do things like" msgstr "" +#: ../../extending/embedding.rst:275 +msgid "" +"import emb\n" +"print(\"Number of arguments\", emb.numargs())" +msgstr "" + #: ../../extending/embedding.rst:280 msgid "" "In a real application, the methods will expose an API of the application to " @@ -318,12 +528,26 @@ msgid "" "compiling:" msgstr "" +#: ../../extending/embedding.rst:318 +msgid "" +"$ /opt/bin/python3.11-config --cflags\n" +"-I/opt/include/python3.11 -I/opt/include/python3.11 -Wsign-compare -DNDEBUG " +"-g -fwrapv -O3 -Wall" +msgstr "" + #: ../../extending/embedding.rst:323 msgid "" "``pythonX.Y-config --ldflags --embed`` will give you the recommended flags " "when linking:" msgstr "" +#: ../../extending/embedding.rst:326 +msgid "" +"$ /opt/bin/python3.11-config --ldflags --embed\n" +"-L/opt/lib/python3.11/config-3.11-x86_64-linux-gnu -L/opt/lib -lpython3.11 -" +"lpthread -ldl -lutil -lm" +msgstr "" + #: ../../extending/embedding.rst:332 msgid "" "To avoid confusion between several Python installations (and especially " @@ -343,3 +567,12 @@ msgid "" "extract the configuration values that you will want to combine together. " "For example:" msgstr "" + +#: ../../extending/embedding.rst:346 +msgid "" +">>> import sysconfig\n" +">>> sysconfig.get_config_var('LIBS')\n" +"'-lpthread -ldl -lutil'\n" +">>> sysconfig.get_config_var('LINKFORSHARED')\n" +"'-Xlinker -export-dynamic'" +msgstr "" diff --git a/extending/extending.po b/extending/extending.po index 705c029fc..fa6a276e0 100644 --- a/extending/extending.po +++ b/extending/extending.po @@ -1,29 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Mariana Costa , 2021 -# Julia Rizza , 2021 -# Melissa Weber Mendonça , 2021 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:51+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -107,6 +103,12 @@ msgstr "" "retorna um número inteiro. Queremos que essa função seja chamável a partir " "do Python como abaixo:" +#: ../../extending/extending.rst:48 +msgid "" +">>> import spam\n" +">>> status = spam.system(\"ls -l\")" +msgstr "" + #: ../../extending/extending.rst:53 msgid "" "Begin by creating a file :file:`spammodule.c`. (Historically, if a module " @@ -123,6 +125,14 @@ msgstr "" msgid "The first two lines of our file can be::" msgstr "As duas primeiras linhas do nosso arquivo podem ser::" +#: ../../extending/extending.rst:60 ../../extending/extending.rst:663 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include " +msgstr "" +"#define PY_SSIZE_T_CLEAN\n" +"#include " + #: ../../extending/extending.rst:63 msgid "" "which pulls in the Python API (you can add a comment describing the purpose " @@ -167,6 +177,21 @@ msgid "" "(we'll see shortly how it ends up being called)::" msgstr "" +#: ../../extending/extending.rst:89 +msgid "" +"static PyObject *\n" +"spam_system(PyObject *self, PyObject *args)\n" +"{\n" +" const char *command;\n" +" int sts;\n" +"\n" +" if (!PyArg_ParseTuple(args, \"s\", &command))\n" +" return NULL;\n" +" sts = system(command);\n" +" return PyLong_FromLong(sts);\n" +"}" +msgstr "" + #: ../../extending/extending.rst:101 msgid "" "There is a straightforward translation from the argument list in Python (for " @@ -327,12 +352,38 @@ msgid "" "you usually declare a static object variable at the beginning of your file::" msgstr "" +#: ../../extending/extending.rst:209 +msgid "static PyObject *SpamError;" +msgstr "" + #: ../../extending/extending.rst:211 msgid "" "and initialize it in your module's initialization function (:c:func:`!" "PyInit_spam`) with an exception object::" msgstr "" +#: ../../extending/extending.rst:214 +msgid "" +"PyMODINIT_FUNC\n" +"PyInit_spam(void)\n" +"{\n" +" PyObject *m;\n" +"\n" +" m = PyModule_Create(&spammodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +"\n" +" SpamError = PyErr_NewException(\"spam.error\", NULL, NULL);\n" +" if (PyModule_AddObjectRef(m, \"error\", SpamError) < 0) {\n" +" Py_CLEAR(SpamError);\n" +" Py_DECREF(m);\n" +" return NULL;\n" +" }\n" +"\n" +" return m;\n" +"}" +msgstr "" + #: ../../extending/extending.rst:233 msgid "" "Note that the Python name for the exception object is :exc:`!spam.error`. " @@ -364,6 +415,25 @@ msgid "" "using a call to :c:func:`PyErr_SetString` as shown below::" msgstr "" +#: ../../extending/extending.rst:251 +msgid "" +"static PyObject *\n" +"spam_system(PyObject *self, PyObject *args)\n" +"{\n" +" const char *command;\n" +" int sts;\n" +"\n" +" if (!PyArg_ParseTuple(args, \"s\", &command))\n" +" return NULL;\n" +" sts = system(command);\n" +" if (sts < 0) {\n" +" PyErr_SetString(SpamError, \"System command failed\");\n" +" return NULL;\n" +" }\n" +" return PyLong_FromLong(sts);\n" +"}" +msgstr "" + #: ../../extending/extending.rst:271 msgid "Back to the Example" msgstr "" @@ -374,6 +444,12 @@ msgid "" "this statement::" msgstr "" +#: ../../extending/extending.rst:276 +msgid "" +"if (!PyArg_ParseTuple(args, \"s\", &command))\n" +" return NULL;" +msgstr "" + #: ../../extending/extending.rst:279 msgid "" "It returns ``NULL`` (the error indicator for functions returning object " @@ -391,6 +467,10 @@ msgid "" "it the string we just got from :c:func:`PyArg_ParseTuple`::" msgstr "" +#: ../../extending/extending.rst:290 +msgid "sts = system(command);" +msgstr "" + #: ../../extending/extending.rst:292 msgid "" "Our :func:`!spam.system` function must return the value of :c:data:`!sts` as " @@ -398,6 +478,10 @@ msgid "" "`PyLong_FromLong`. ::" msgstr "" +#: ../../extending/extending.rst:295 +msgid "return PyLong_FromLong(sts);" +msgstr "" + #: ../../extending/extending.rst:297 msgid "" "In this case, it will return an integer object. (Yes, even integers are " @@ -412,6 +496,12 @@ msgid "" "macro:`Py_RETURN_NONE` macro)::" msgstr "" +#: ../../extending/extending.rst:305 +msgid "" +"Py_INCREF(Py_None);\n" +"return Py_None;" +msgstr "" + #: ../../extending/extending.rst:308 msgid "" ":c:data:`Py_None` is the C name for the special Python object ``None``. It " @@ -429,6 +519,17 @@ msgid "" "programs. First, we need to list its name and address in a \"method table\"::" msgstr "" +#: ../../extending/extending.rst:321 +msgid "" +"static PyMethodDef SpamMethods[] = {\n" +" ...\n" +" {\"system\", spam_system, METH_VARARGS,\n" +" \"Execute a shell command.\"},\n" +" ...\n" +" {NULL, NULL, 0, NULL} /* Sentinel */\n" +"};" +msgstr "" + #: ../../extending/extending.rst:329 msgid "" "Note the third entry (``METH_VARARGS``). This is a flag telling the " @@ -459,6 +560,18 @@ msgid "" "The method table must be referenced in the module definition structure::" msgstr "" +#: ../../extending/extending.rst:346 +msgid "" +"static struct PyModuleDef spammodule = {\n" +" PyModuleDef_HEAD_INIT,\n" +" \"spam\", /* name of module */\n" +" spam_doc, /* module documentation, may be NULL */\n" +" -1, /* size of per-interpreter state of the module,\n" +" or -1 if the module keeps state in global variables. */\n" +" SpamMethods\n" +"};" +msgstr "" + #: ../../extending/extending.rst:355 msgid "" "This structure, in turn, must be passed to the interpreter in the module's " @@ -467,6 +580,15 @@ msgid "" "only non-\\ ``static`` item defined in the module file::" msgstr "" +#: ../../extending/extending.rst:360 +msgid "" +"PyMODINIT_FUNC\n" +"PyInit_spam(void)\n" +"{\n" +" return PyModule_Create(&spammodule);\n" +"}" +msgstr "" + #: ../../extending/extending.rst:366 msgid "" "Note that :c:macro:`PyMODINIT_FUNC` declares the function as ``PyObject *`` " @@ -496,6 +618,59 @@ msgid "" "`PyImport_AppendInittab`, optionally followed by an import of the module::" msgstr "" +#: ../../extending/extending.rst:386 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"\n" +"int\n" +"main(int argc, char *argv[])\n" +"{\n" +" PyStatus status;\n" +" PyConfig config;\n" +" PyConfig_InitPythonConfig(&config);\n" +"\n" +" /* Add a built-in module, before Py_Initialize */\n" +" if (PyImport_AppendInittab(\"spam\", PyInit_spam) == -1) {\n" +" fprintf(stderr, \"Error: could not extend in-built modules " +"table\\n\");\n" +" exit(1);\n" +" }\n" +"\n" +" /* Pass argv[0] to the Python interpreter */\n" +" status = PyConfig_SetBytesString(&config, &config.program_name, " +"argv[0]);\n" +" if (PyStatus_Exception(status)) {\n" +" goto exception;\n" +" }\n" +"\n" +" /* Initialize the Python interpreter. Required.\n" +" If this step fails, it will be a fatal error. */\n" +" status = Py_InitializeFromConfig(&config);\n" +" if (PyStatus_Exception(status)) {\n" +" goto exception;\n" +" }\n" +" PyConfig_Clear(&config);\n" +"\n" +" /* Optionally import the module; alternatively,\n" +" import can be deferred until the embedded script\n" +" imports it. */\n" +" PyObject *pmodule = PyImport_ImportModule(\"spam\");\n" +" if (!pmodule) {\n" +" PyErr_Print();\n" +" fprintf(stderr, \"Error: could not import module 'spam'\\n\");\n" +" }\n" +"\n" +" // ... use Python C API here ...\n" +"\n" +" return 0;\n" +"\n" +" exception:\n" +" PyConfig_Clear(&config);\n" +" Py_ExitStatusException(status);\n" +"}" +msgstr "" + #: ../../extending/extending.rst:436 msgid "" "Removing entries from ``sys.modules`` or importing compiled modules into " @@ -544,6 +719,10 @@ msgid "" "line to the file :file:`Modules/Setup.local` describing your file:" msgstr "" +#: ../../extending/extending.rst:473 +msgid "spam spammodule.o" +msgstr "" + #: ../../extending/extending.rst:477 msgid "" "and rebuild the interpreter by running :program:`make` in the toplevel " @@ -559,6 +738,10 @@ msgid "" "listed on the line in the configuration file as well, for instance:" msgstr "" +#: ../../extending/extending.rst:486 +msgid "spam spammodule.o -lX11" +msgstr "" + #: ../../extending/extending.rst:494 msgid "Calling Python Functions from C" msgstr "" @@ -593,6 +776,33 @@ msgid "" "function might be part of a module definition::" msgstr "" +#: ../../extending/extending.rst:517 +msgid "" +"static PyObject *my_callback = NULL;\n" +"\n" +"static PyObject *\n" +"my_set_callback(PyObject *dummy, PyObject *args)\n" +"{\n" +" PyObject *result = NULL;\n" +" PyObject *temp;\n" +"\n" +" if (PyArg_ParseTuple(args, \"O:set_callback\", &temp)) {\n" +" if (!PyCallable_Check(temp)) {\n" +" PyErr_SetString(PyExc_TypeError, \"parameter must be " +"callable\");\n" +" return NULL;\n" +" }\n" +" Py_XINCREF(temp); /* Add a reference to new callback */\n" +" Py_XDECREF(my_callback); /* Dispose of previous callback */\n" +" my_callback = temp; /* Remember new callback */\n" +" /* Boilerplate to return \"None\" */\n" +" Py_INCREF(Py_None);\n" +" result = Py_None;\n" +" }\n" +" return result;\n" +"}" +msgstr "" + #: ../../extending/extending.rst:540 msgid "" "This function must be registered with the interpreter using the :c:macro:" @@ -621,6 +831,20 @@ msgid "" "or more format codes between parentheses. For example::" msgstr "" +#: ../../extending/extending.rst:561 +msgid "" +"int arg;\n" +"PyObject *arglist;\n" +"PyObject *result;\n" +"...\n" +"arg = 123;\n" +"...\n" +"/* Time to call the callback */\n" +"arglist = Py_BuildValue(\"(i)\", arg);\n" +"result = PyObject_CallObject(my_callback, arglist);\n" +"Py_DECREF(arglist);" +msgstr "" + #: ../../extending/extending.rst:572 msgid "" ":c:func:`PyObject_CallObject` returns a Python object pointer: this is the " @@ -650,6 +874,14 @@ msgid "" "should be cleared by calling :c:func:`PyErr_Clear`. For example::" msgstr "" +#: ../../extending/extending.rst:593 +msgid "" +"if (result == NULL)\n" +" return NULL; /* Pass error back */\n" +"...use result...\n" +"Py_DECREF(result);" +msgstr "" + #: ../../extending/extending.rst:598 msgid "" "Depending on the desired interface to the Python callback function, you may " @@ -662,6 +894,19 @@ msgid "" "you want to pass an integral event code, you might use the following code::" msgstr "" +#: ../../extending/extending.rst:607 +msgid "" +"PyObject *arglist;\n" +"...\n" +"arglist = Py_BuildValue(\"(l)\", eventcode);\n" +"result = PyObject_CallObject(my_callback, arglist);\n" +"Py_DECREF(arglist);\n" +"if (result == NULL)\n" +" return NULL; /* Pass error back */\n" +"/* Here maybe use the result */\n" +"Py_DECREF(result);" +msgstr "" + #: ../../extending/extending.rst:617 msgid "" "Note the placement of ``Py_DECREF(arglist)`` immediately after the call, " @@ -677,6 +922,19 @@ msgid "" "above example, we use :c:func:`Py_BuildValue` to construct the dictionary. ::" msgstr "" +#: ../../extending/extending.rst:625 +msgid "" +"PyObject *dict;\n" +"...\n" +"dict = Py_BuildValue(\"{s:i}\", \"name\", val);\n" +"result = PyObject_Call(my_callback, NULL, dict);\n" +"Py_DECREF(dict);\n" +"if (result == NULL)\n" +" return NULL; /* Pass error back */\n" +"/* Here maybe use the result */\n" +"Py_DECREF(result);" +msgstr "" + #: ../../extending/extending.rst:639 msgid "Extracting Parameters in Extension Functions" msgstr "" @@ -685,6 +943,10 @@ msgstr "" msgid "The :c:func:`PyArg_ParseTuple` function is declared as follows::" msgstr "" +#: ../../extending/extending.rst:645 +msgid "int PyArg_ParseTuple(PyObject *arg, const char *format, ...);" +msgstr "" + #: ../../extending/extending.rst:647 msgid "" "The *arg* argument must be a tuple object containing an argument list passed " @@ -715,6 +977,75 @@ msgstr "" msgid "Some example calls::" msgstr "" +#: ../../extending/extending.rst:668 +msgid "" +"int ok;\n" +"int i, j;\n" +"long k, l;\n" +"const char *s;\n" +"Py_ssize_t size;\n" +"\n" +"ok = PyArg_ParseTuple(args, \"\"); /* No arguments */\n" +" /* Python call: f() */" +msgstr "" + +#: ../../extending/extending.rst:679 +msgid "" +"ok = PyArg_ParseTuple(args, \"s\", &s); /* A string */\n" +" /* Possible Python call: f('whoops!') */" +msgstr "" + +#: ../../extending/extending.rst:684 +msgid "" +"ok = PyArg_ParseTuple(args, \"lls\", &k, &l, &s); /* Two longs and a string " +"*/\n" +" /* Possible Python call: f(1, 2, 'three') */" +msgstr "" + +#: ../../extending/extending.rst:689 +msgid "" +"ok = PyArg_ParseTuple(args, \"(ii)s#\", &i, &j, &s, &size);\n" +" /* A pair of ints and a string, whose size is also returned */\n" +" /* Possible Python call: f((1, 2), 'three') */" +msgstr "" + +#: ../../extending/extending.rst:695 +msgid "" +"{\n" +" const char *file;\n" +" const char *mode = \"r\";\n" +" int bufsize = 0;\n" +" ok = PyArg_ParseTuple(args, \"s|si\", &file, &mode, &bufsize);\n" +" /* A string, and optionally another string and an integer */\n" +" /* Possible Python calls:\n" +" f('spam')\n" +" f('spam', 'w')\n" +" f('spam', 'wb', 100000) */\n" +"}" +msgstr "" + +#: ../../extending/extending.rst:709 +msgid "" +"{\n" +" int left, top, right, bottom, h, v;\n" +" ok = PyArg_ParseTuple(args, \"((ii)(ii))(ii)\",\n" +" &left, &top, &right, &bottom, &h, &v);\n" +" /* A rectangle and a point */\n" +" /* Possible Python call:\n" +" f(((0, 0), (400, 300)), (10, 10)) */\n" +"}" +msgstr "" + +#: ../../extending/extending.rst:720 +msgid "" +"{\n" +" Py_complex c;\n" +" ok = PyArg_ParseTuple(args, \"D:myfunction\", &c);\n" +" /* a complex, also providing a function name for errors */\n" +" /* Possible Python call: myfunction(1+2j) */\n" +"}" +msgstr "" + #: ../../extending/extending.rst:731 msgid "Keyword Parameters for Extension Functions" msgstr "" @@ -724,6 +1055,13 @@ msgid "" "The :c:func:`PyArg_ParseTupleAndKeywords` function is declared as follows::" msgstr "" +#: ../../extending/extending.rst:737 +msgid "" +"int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,\n" +" const char *format, char * const " +"*kwlist, ...);" +msgstr "" + #: ../../extending/extending.rst:740 msgid "" "The *arg* and *format* parameters are identical to those of the :c:func:" @@ -749,6 +1087,60 @@ msgid "" "Philbrick (philbrick@hks.com)::" msgstr "" +#: ../../extending/extending.rst:759 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"\n" +"static PyObject *\n" +"keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)\n" +"{\n" +" int voltage;\n" +" const char *state = \"a stiff\";\n" +" const char *action = \"voom\";\n" +" const char *type = \"Norwegian Blue\";\n" +"\n" +" static char *kwlist[] = {\"voltage\", \"state\", \"action\", \"type\", " +"NULL};\n" +"\n" +" if (!PyArg_ParseTupleAndKeywords(args, keywds, \"i|sss\", kwlist,\n" +" &voltage, &state, &action, &type))\n" +" return NULL;\n" +"\n" +" printf(\"-- This parrot wouldn't %s if you put %i Volts through it." +"\\n\",\n" +" action, voltage);\n" +" printf(\"-- Lovely plumage, the %s -- It's %s!\\n\", type, state);\n" +"\n" +" Py_RETURN_NONE;\n" +"}\n" +"\n" +"static PyMethodDef keywdarg_methods[] = {\n" +" /* The cast of the function is necessary since PyCFunction values\n" +" * only take two PyObject* parameters, and keywdarg_parrot() takes\n" +" * three.\n" +" */\n" +" {\"parrot\", (PyCFunction)(void(*)(void))keywdarg_parrot, METH_VARARGS | " +"METH_KEYWORDS,\n" +" \"Print a lovely skit to standard output.\"},\n" +" {NULL, NULL, 0, NULL} /* sentinel */\n" +"};\n" +"\n" +"static struct PyModuleDef keywdargmodule = {\n" +" PyModuleDef_HEAD_INIT,\n" +" \"keywdarg\",\n" +" NULL,\n" +" -1,\n" +" keywdarg_methods\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_keywdarg(void)\n" +"{\n" +" return PyModule_Create(&keywdargmodule);\n" +"}" +msgstr "" + #: ../../extending/extending.rst:811 msgid "Building Arbitrary Values" msgstr "" @@ -759,6 +1151,10 @@ msgid "" "declared as follows::" msgstr "" +#: ../../extending/extending.rst:816 +msgid "PyObject *Py_BuildValue(const char *format, ...);" +msgstr "" + #: ../../extending/extending.rst:818 msgid "" "It recognizes a set of format units similar to the ones recognized by :c:" @@ -784,6 +1180,27 @@ msgid "" "Examples (to the left the call, to the right the resulting Python value):" msgstr "" +#: ../../extending/extending.rst:833 +msgid "" +"Py_BuildValue(\"\") None\n" +"Py_BuildValue(\"i\", 123) 123\n" +"Py_BuildValue(\"iii\", 123, 456, 789) (123, 456, 789)\n" +"Py_BuildValue(\"s\", \"hello\") 'hello'\n" +"Py_BuildValue(\"y\", \"hello\") b'hello'\n" +"Py_BuildValue(\"ss\", \"hello\", \"world\") ('hello', 'world')\n" +"Py_BuildValue(\"s#\", \"hello\", 4) 'hell'\n" +"Py_BuildValue(\"y#\", \"hello\", 4) b'hell'\n" +"Py_BuildValue(\"()\") ()\n" +"Py_BuildValue(\"(i)\", 123) (123,)\n" +"Py_BuildValue(\"(ii)\", 123, 456) (123, 456)\n" +"Py_BuildValue(\"(i,i)\", 123, 456) (123, 456)\n" +"Py_BuildValue(\"[i,i]\", 123, 456) [123, 456]\n" +"Py_BuildValue(\"{s:i,s:i}\",\n" +" \"abc\", 123, \"def\", 456) {'abc': 123, 'def': 456}\n" +"Py_BuildValue(\"((ii)(ii)) (ii)\",\n" +" 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))" +msgstr "" + #: ../../extending/extending.rst:857 msgid "Reference Counts" msgstr "Contagens de referências" @@ -1021,6 +1438,18 @@ msgid "" "instance::" msgstr "" +#: ../../extending/extending.rst:1027 +msgid "" +"void\n" +"bug(PyObject *list)\n" +"{\n" +" PyObject *item = PyList_GetItem(list, 0);\n" +"\n" +" PyList_SetItem(list, 1, PyLong_FromLong(0L));\n" +" PyObject_Print(item, stdout, 0); /* BUG! */\n" +"}" +msgstr "" + #: ../../extending/extending.rst:1036 msgid "" "This function first borrows a reference to ``list[0]``, then replaces " @@ -1055,6 +1484,20 @@ msgid "" "increment the reference count. The correct version of the function reads::" msgstr "" +#: ../../extending/extending.rst:1058 +msgid "" +"void\n" +"no_bug(PyObject *list)\n" +"{\n" +" PyObject *item = PyList_GetItem(list, 0);\n" +"\n" +" Py_INCREF(item);\n" +" PyList_SetItem(list, 1, PyLong_FromLong(0L));\n" +" PyObject_Print(item, stdout, 0);\n" +" Py_DECREF(item);\n" +"}" +msgstr "" + #: ../../extending/extending.rst:1069 msgid "" "This is a true story. An older version of Python contained variants of this " @@ -1075,6 +1518,19 @@ msgid "" "previous one::" msgstr "" +#: ../../extending/extending.rst:1082 +msgid "" +"void\n" +"bug(PyObject *list)\n" +"{\n" +" PyObject *item = PyList_GetItem(list, 0);\n" +" Py_BEGIN_ALLOW_THREADS\n" +" ...some blocking I/O call...\n" +" Py_END_ALLOW_THREADS\n" +" PyObject_Print(item, stdout, 0); /* BUG! */\n" +"}" +msgstr "" + #: ../../extending/extending.rst:1096 msgid "NULL Pointers" msgstr "" @@ -1223,6 +1679,10 @@ msgid "" "following this convention::" msgstr "" +#: ../../extending/extending.rst:1207 +msgid "modulename.attributename" +msgstr "" + #: ../../extending/extending.rst:1209 msgid "" "The convenience function :c:func:`PyCapsule_Import` makes it easy to load a " @@ -1259,18 +1719,52 @@ msgid "" "``static`` like everything else::" msgstr "" +#: ../../extending/extending.rst:1232 +msgid "" +"static int\n" +"PySpam_System(const char *command)\n" +"{\n" +" return system(command);\n" +"}" +msgstr "" + #: ../../extending/extending.rst:1238 msgid "The function :c:func:`!spam_system` is modified in a trivial way::" msgstr "" +#: ../../extending/extending.rst:1240 +msgid "" +"static PyObject *\n" +"spam_system(PyObject *self, PyObject *args)\n" +"{\n" +" const char *command;\n" +" int sts;\n" +"\n" +" if (!PyArg_ParseTuple(args, \"s\", &command))\n" +" return NULL;\n" +" sts = PySpam_System(command);\n" +" return PyLong_FromLong(sts);\n" +"}" +msgstr "" + #: ../../extending/extending.rst:1252 msgid "In the beginning of the module, right after the line ::" msgstr "" +#: ../../extending/extending.rst:1254 +msgid "#include " +msgstr "" + #: ../../extending/extending.rst:1256 msgid "two more lines must be added::" msgstr "" +#: ../../extending/extending.rst:1258 +msgid "" +"#define SPAM_MODULE\n" +"#include \"spammodule.h\"" +msgstr "" + #: ../../extending/extending.rst:1261 msgid "" "The ``#define`` is used to tell the header file that it is being included in " @@ -1279,6 +1773,35 @@ msgid "" "array::" msgstr "" +#: ../../extending/extending.rst:1265 +msgid "" +"PyMODINIT_FUNC\n" +"PyInit_spam(void)\n" +"{\n" +" PyObject *m;\n" +" static void *PySpam_API[PySpam_API_pointers];\n" +" PyObject *c_api_object;\n" +"\n" +" m = PyModule_Create(&spammodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +"\n" +" /* Initialize the C API pointer array */\n" +" PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;\n" +"\n" +" /* Create a Capsule containing the API pointer array's address */\n" +" c_api_object = PyCapsule_New((void *)PySpam_API, \"spam._C_API\", " +"NULL);\n" +"\n" +" if (PyModule_Add(m, \"_C_API\", c_api_object) < 0) {\n" +" Py_DECREF(m);\n" +" return NULL;\n" +" }\n" +"\n" +" return m;\n" +"}" +msgstr "" + #: ../../extending/extending.rst:1290 msgid "" "Note that ``PySpam_API`` is declared ``static``; otherwise the pointer array " @@ -1291,6 +1814,58 @@ msgid "" "like this::" msgstr "" +#: ../../extending/extending.rst:1296 +msgid "" +"#ifndef Py_SPAMMODULE_H\n" +"#define Py_SPAMMODULE_H\n" +"#ifdef __cplusplus\n" +"extern \"C\" {\n" +"#endif\n" +"\n" +"/* Header file for spammodule */\n" +"\n" +"/* C API functions */\n" +"#define PySpam_System_NUM 0\n" +"#define PySpam_System_RETURN int\n" +"#define PySpam_System_PROTO (const char *command)\n" +"\n" +"/* Total number of C API pointers */\n" +"#define PySpam_API_pointers 1\n" +"\n" +"\n" +"#ifdef SPAM_MODULE\n" +"/* This section is used when compiling spammodule.c */\n" +"\n" +"static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;\n" +"\n" +"#else\n" +"/* This section is used in modules that use spammodule's API */\n" +"\n" +"static void **PySpam_API;\n" +"\n" +"#define PySpam_System \\\n" +" (*(PySpam_System_RETURN (*)PySpam_System_PROTO) " +"PySpam_API[PySpam_System_NUM])\n" +"\n" +"/* Return -1 on error, 0 on success.\n" +" * PyCapsule_Import will set an exception if there's an error.\n" +" */\n" +"static int\n" +"import_spam(void)\n" +"{\n" +" PySpam_API = (void **)PyCapsule_Import(\"spam._C_API\", 0);\n" +" return (PySpam_API != NULL) ? 0 : -1;\n" +"}\n" +"\n" +"#endif\n" +"\n" +"#ifdef __cplusplus\n" +"}\n" +"#endif\n" +"\n" +"#endif /* !defined(Py_SPAMMODULE_H) */" +msgstr "" + #: ../../extending/extending.rst:1344 msgid "" "All that a client module must do in order to have access to the function :c:" @@ -1298,6 +1873,23 @@ msgid "" "import_spam` in its initialization function::" msgstr "" +#: ../../extending/extending.rst:1348 +msgid "" +"PyMODINIT_FUNC\n" +"PyInit_client(void)\n" +"{\n" +" PyObject *m;\n" +"\n" +" m = PyModule_Create(&clientmodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +" if (import_spam() < 0)\n" +" return NULL;\n" +" /* additional initialization can happen here */\n" +" return m;\n" +"}" +msgstr "" + #: ../../extending/extending.rst:1362 msgid "" "The main disadvantage of this approach is that the file :file:`spammodule.h` " diff --git a/extending/index.po b/extending/index.po index 3d1f6e498..62d577317 100644 --- a/extending/index.po +++ b/extending/index.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/extending/newtypes.po b/extending/newtypes.po index 19ec24aca..28883d1ff 100644 --- a/extending/newtypes.po +++ b/extending/newtypes.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2023 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -41,6 +39,96 @@ msgid "" "in :ref:`debug builds ` omitted:" msgstr "" +#: ../../extending/newtypes.rst:17 +msgid "" +"typedef struct _typeobject {\n" +" PyObject_VAR_HEAD\n" +" const char *tp_name; /* For printing, in format \".\" */\n" +" Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */\n" +"\n" +" /* Methods to implement standard operations */\n" +"\n" +" destructor tp_dealloc;\n" +" Py_ssize_t tp_vectorcall_offset;\n" +" getattrfunc tp_getattr;\n" +" setattrfunc tp_setattr;\n" +" PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)\n" +" or tp_reserved (Python 3) */\n" +" reprfunc tp_repr;\n" +"\n" +" /* Method suites for standard classes */\n" +"\n" +" PyNumberMethods *tp_as_number;\n" +" PySequenceMethods *tp_as_sequence;\n" +" PyMappingMethods *tp_as_mapping;\n" +"\n" +" /* More standard operations (here for binary compatibility) */\n" +"\n" +" hashfunc tp_hash;\n" +" ternaryfunc tp_call;\n" +" reprfunc tp_str;\n" +" getattrofunc tp_getattro;\n" +" setattrofunc tp_setattro;\n" +"\n" +" /* Functions to access object as input/output buffer */\n" +" PyBufferProcs *tp_as_buffer;\n" +"\n" +" /* Flags to define presence of optional/expanded features */\n" +" unsigned long tp_flags;\n" +"\n" +" const char *tp_doc; /* Documentation string */\n" +"\n" +" /* Assigned meaning in release 2.0 */\n" +" /* call function for all accessible objects */\n" +" traverseproc tp_traverse;\n" +"\n" +" /* delete references to contained objects */\n" +" inquiry tp_clear;\n" +"\n" +" /* Assigned meaning in release 2.1 */\n" +" /* rich comparisons */\n" +" richcmpfunc tp_richcompare;\n" +"\n" +" /* weak reference enabler */\n" +" Py_ssize_t tp_weaklistoffset;\n" +"\n" +" /* Iterators */\n" +" getiterfunc tp_iter;\n" +" iternextfunc tp_iternext;\n" +"\n" +" /* Attribute descriptor and subclassing stuff */\n" +" struct PyMethodDef *tp_methods;\n" +" struct PyMemberDef *tp_members;\n" +" struct PyGetSetDef *tp_getset;\n" +" // Strong reference on a heap type, borrowed reference on a static type\n" +" struct _typeobject *tp_base;\n" +" PyObject *tp_dict;\n" +" descrgetfunc tp_descr_get;\n" +" descrsetfunc tp_descr_set;\n" +" Py_ssize_t tp_dictoffset;\n" +" initproc tp_init;\n" +" allocfunc tp_alloc;\n" +" newfunc tp_new;\n" +" freefunc tp_free; /* Low-level free-memory routine */\n" +" inquiry tp_is_gc; /* For PyObject_IS_GC */\n" +" PyObject *tp_bases;\n" +" PyObject *tp_mro; /* method resolution order */\n" +" PyObject *tp_cache;\n" +" PyObject *tp_subclasses;\n" +" PyObject *tp_weaklist;\n" +" destructor tp_del;\n" +"\n" +" /* Type attribute cache version tag. Added in version 2.6 */\n" +" unsigned int tp_version_tag;\n" +"\n" +" destructor tp_finalize;\n" +" vectorcallfunc tp_vectorcall;\n" +"\n" +" /* bitset of which type-watchers care about this type */\n" +" unsigned char tp_watched;\n" +"} PyTypeObject;\n" +msgstr "" + #: ../../extending/newtypes.rst:20 msgid "" "Now that's a *lot* of methods. Don't worry too much though -- if you have a " @@ -58,6 +146,10 @@ msgid "" "new type. ::" msgstr "" +#: ../../extending/newtypes.rst:31 +msgid "const char *tp_name; /* For printing */" +msgstr "" + #: ../../extending/newtypes.rst:33 msgid "" "The name of the type -- as mentioned in the previous chapter, this will " @@ -65,6 +157,10 @@ msgid "" "choose something that will be helpful in such a situation! ::" msgstr "" +#: ../../extending/newtypes.rst:37 +msgid "Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */" +msgstr "" + #: ../../extending/newtypes.rst:39 msgid "" "These fields tell the runtime how much memory to allocate when new objects " @@ -74,6 +170,10 @@ msgid "" "later. ::" msgstr "" +#: ../../extending/newtypes.rst:44 +msgid "const char *tp_doc;" +msgstr "" + #: ../../extending/newtypes.rst:46 msgid "" "Here you can put a string (or its address) that you want returned when the " @@ -90,6 +190,10 @@ msgstr "" msgid "Finalization and De-allocation" msgstr "" +#: ../../extending/newtypes.rst:64 +msgid "destructor tp_dealloc;" +msgstr "" + #: ../../extending/newtypes.rst:66 msgid "" "This function is called when the reference count of the instance of your " @@ -99,12 +203,34 @@ msgid "" "of this function::" msgstr "" +#: ../../extending/newtypes.rst:72 +msgid "" +"static void\n" +"newdatatype_dealloc(newdatatypeobject *obj)\n" +"{\n" +" free(obj->obj_UnderlyingDatatypePtr);\n" +" Py_TYPE(obj)->tp_free((PyObject *)obj);\n" +"}" +msgstr "" + #: ../../extending/newtypes.rst:79 msgid "" "If your type supports garbage collection, the destructor should call :c:func:" "`PyObject_GC_UnTrack` before clearing any member fields::" msgstr "" +#: ../../extending/newtypes.rst:82 +msgid "" +"static void\n" +"newdatatype_dealloc(newdatatypeobject *obj)\n" +"{\n" +" PyObject_GC_UnTrack(obj);\n" +" Py_CLEAR(obj->other_obj);\n" +" ...\n" +" Py_TYPE(obj)->tp_free((PyObject *)obj);\n" +"}" +msgstr "" + #: ../../extending/newtypes.rst:95 msgid "" "One important requirement of the deallocator function is that it leaves any " @@ -120,6 +246,35 @@ msgid "" "c:func:`PyErr_Fetch` and :c:func:`PyErr_Restore` functions::" msgstr "" +#: ../../extending/newtypes.rst:107 +msgid "" +"static void\n" +"my_dealloc(PyObject *obj)\n" +"{\n" +" MyObject *self = (MyObject *) obj;\n" +" PyObject *cbresult;\n" +"\n" +" if (self->my_callback != NULL) {\n" +" PyObject *err_type, *err_value, *err_traceback;\n" +"\n" +" /* This saves the current exception state */\n" +" PyErr_Fetch(&err_type, &err_value, &err_traceback);\n" +"\n" +" cbresult = PyObject_CallNoArgs(self->my_callback);\n" +" if (cbresult == NULL)\n" +" PyErr_WriteUnraisable(self->my_callback);\n" +" else\n" +" Py_DECREF(cbresult);\n" +"\n" +" /* This restores the saved exception state */\n" +" PyErr_Restore(err_type, err_value, err_traceback);\n" +"\n" +" Py_DECREF(self->my_callback);\n" +" }\n" +" Py_TYPE(obj)->tp_free((PyObject*)self);\n" +"}" +msgstr "" + #: ../../extending/newtypes.rst:134 msgid "" "There are limitations to what you can safely do in a deallocator function. " @@ -155,6 +310,12 @@ msgid "" "`print` function just calls :func:`str`.) These handlers are both optional." msgstr "" +#: ../../extending/newtypes.rst:163 +msgid "" +"reprfunc tp_repr;\n" +"reprfunc tp_str;" +msgstr "" + #: ../../extending/newtypes.rst:166 msgid "" "The :c:member:`~PyTypeObject.tp_repr` handler should return a string object " @@ -162,6 +323,16 @@ msgid "" "a simple example::" msgstr "" +#: ../../extending/newtypes.rst:170 +msgid "" +"static PyObject *\n" +"newdatatype_repr(newdatatypeobject *obj)\n" +"{\n" +" return PyUnicode_FromFormat(\"Repr-ified_newdatatype{{size:%d}}\",\n" +" obj->obj_UnderlyingDatatypePtr->size);\n" +"}" +msgstr "" + #: ../../extending/newtypes.rst:177 msgid "" "If no :c:member:`~PyTypeObject.tp_repr` handler is specified, the " @@ -184,6 +355,16 @@ msgstr "" msgid "Here is a simple example::" msgstr "" +#: ../../extending/newtypes.rst:190 +msgid "" +"static PyObject *\n" +"newdatatype_str(newdatatypeobject *obj)\n" +"{\n" +" return PyUnicode_FromFormat(\"Stringified_newdatatype{{size:%d}}\",\n" +" obj->obj_UnderlyingDatatypePtr->size);\n" +"}" +msgstr "" + #: ../../extending/newtypes.rst:200 msgid "Attribute Management" msgstr "" @@ -207,6 +388,15 @@ msgid "" "whichever pair makes more sense for the implementation's convenience. ::" msgstr "" +#: ../../extending/newtypes.rst:214 +msgid "" +"getattrfunc tp_getattr; /* char * version */\n" +"setattrfunc tp_setattr;\n" +"/* ... */\n" +"getattrofunc tp_getattro; /* PyObject * version */\n" +"setattrofunc tp_setattro;" +msgstr "" + #: ../../extending/newtypes.rst:220 msgid "" "If accessing attributes of an object is always a simple operation (this will " @@ -262,6 +452,13 @@ msgstr "" msgid "The tables are declared as three fields of the type object::" msgstr "" +#: ../../extending/newtypes.rst:255 +msgid "" +"struct PyMethodDef *tp_methods;\n" +"struct PyMemberDef *tp_members;\n" +"struct PyGetSetDef *tp_getset;" +msgstr "" + #: ../../extending/newtypes.rst:259 msgid "" "If :c:member:`~PyTypeObject.tp_methods` is not ``NULL``, it must refer to an " @@ -269,6 +466,16 @@ msgid "" "instance of this structure::" msgstr "" +#: ../../extending/newtypes.rst:263 +msgid "" +"typedef struct PyMethodDef {\n" +" const char *ml_name; /* method name */\n" +" PyCFunction ml_meth; /* implementation function */\n" +" int ml_flags; /* flags */\n" +" const char *ml_doc; /* docstring */\n" +"} PyMethodDef;" +msgstr "" + #: ../../extending/newtypes.rst:270 msgid "" "One entry should be defined for each method provided by the type; no entries " @@ -285,6 +492,17 @@ msgid "" "defined as::" msgstr "" +#: ../../extending/newtypes.rst:279 +msgid "" +"typedef struct PyMemberDef {\n" +" const char *name;\n" +" int type;\n" +" int offset;\n" +" int flags;\n" +" const char *doc;\n" +"} PyMemberDef;" +msgstr "" + #: ../../extending/newtypes.rst:287 msgid "" "For each entry in the table, a :term:`descriptor` will be constructed and " @@ -304,7 +522,7 @@ msgid "" "defined this way can have an associated doc string simply by providing the " "text in the table. An application can use the introspection API to retrieve " "the descriptor from the class object, and get the doc string using its :attr:" -"`!__doc__` attribute." +"`~type.__doc__` attribute." msgstr "" #: ../../extending/newtypes.rst:301 @@ -339,6 +557,23 @@ msgstr "" msgid "Here is an example::" msgstr "Aqui está um exemplo::" +#: ../../extending/newtypes.rst:331 +msgid "" +"static PyObject *\n" +"newdatatype_getattr(newdatatypeobject *obj, char *name)\n" +"{\n" +" if (strcmp(name, \"data\") == 0)\n" +" {\n" +" return PyLong_FromLong(obj->data);\n" +" }\n" +"\n" +" PyErr_Format(PyExc_AttributeError,\n" +" \"'%.100s' object has no attribute '%.400s'\",\n" +" Py_TYPE(obj)->tp_name, name);\n" +" return NULL;\n" +"}" +msgstr "" + #: ../../extending/newtypes.rst:345 msgid "" "The :c:member:`~PyTypeObject.tp_setattr` handler is called when the :meth:" @@ -349,10 +584,24 @@ msgid "" "tp_setattr` handler should be set to ``NULL``. ::" msgstr "" +#: ../../extending/newtypes.rst:351 +msgid "" +"static int\n" +"newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)\n" +"{\n" +" PyErr_Format(PyExc_RuntimeError, \"Read-only attribute: %s\", name);\n" +" return -1;\n" +"}" +msgstr "" + #: ../../extending/newtypes.rst:359 msgid "Object Comparison" msgstr "" +#: ../../extending/newtypes.rst:363 +msgid "richcmpfunc tp_richcompare;" +msgstr "" + #: ../../extending/newtypes.rst:365 msgid "" "The :c:member:`~PyTypeObject.tp_richcompare` handler is called when " @@ -378,6 +627,35 @@ msgid "" "the size of an internal pointer is equal::" msgstr "" +#: ../../extending/newtypes.rst:381 +msgid "" +"static PyObject *\n" +"newdatatype_richcmp(newdatatypeobject *obj1, newdatatypeobject *obj2, int " +"op)\n" +"{\n" +" PyObject *result;\n" +" int c, size1, size2;\n" +"\n" +" /* code to make sure that both arguments are of type\n" +" newdatatype omitted */\n" +"\n" +" size1 = obj1->obj_UnderlyingDatatypePtr->size;\n" +" size2 = obj2->obj_UnderlyingDatatypePtr->size;\n" +"\n" +" switch (op) {\n" +" case Py_LT: c = size1 < size2; break;\n" +" case Py_LE: c = size1 <= size2; break;\n" +" case Py_EQ: c = size1 == size2; break;\n" +" case Py_NE: c = size1 != size2; break;\n" +" case Py_GT: c = size1 > size2; break;\n" +" case Py_GE: c = size1 >= size2; break;\n" +" }\n" +" result = c ? Py_True : Py_False;\n" +" Py_INCREF(result);\n" +" return result;\n" +" }" +msgstr "" + #: ../../extending/newtypes.rst:408 msgid "Abstract Protocol Support" msgstr "" @@ -403,6 +681,13 @@ msgid "" "slot, but a slot may still be unfilled.) ::" msgstr "" +#: ../../extending/newtypes.rst:425 +msgid "" +"PyNumberMethods *tp_as_number;\n" +"PySequenceMethods *tp_as_sequence;\n" +"PyMappingMethods *tp_as_mapping;" +msgstr "" + #: ../../extending/newtypes.rst:429 msgid "" "If you wish your object to be able to act like a number, a sequence, or a " @@ -414,12 +699,29 @@ msgid "" "distribution. ::" msgstr "" +#: ../../extending/newtypes.rst:436 +msgid "hashfunc tp_hash;" +msgstr "" + #: ../../extending/newtypes.rst:438 msgid "" "This function, if you choose to provide it, should return a hash number for " "an instance of your data type. Here is a simple example::" msgstr "" +#: ../../extending/newtypes.rst:441 +msgid "" +"static Py_hash_t\n" +"newdatatype_hash(newdatatypeobject *obj)\n" +"{\n" +" Py_hash_t result;\n" +" result = obj->some_size + 32767 * obj->some_number;\n" +" if (result == -1)\n" +" result = -2;\n" +" return result;\n" +"}" +msgstr "" + #: ../../extending/newtypes.rst:451 msgid "" ":c:type:`Py_hash_t` is a signed integer type with a platform-varying width. " @@ -428,6 +730,10 @@ msgid "" "computation is successful, as seen above." msgstr "" +#: ../../extending/newtypes.rst:458 +msgid "ternaryfunc tp_call;" +msgstr "" + #: ../../extending/newtypes.rst:460 msgid "" "This function is called when an instance of your data type is \"called\", " @@ -465,6 +771,34 @@ msgstr "" msgid "Here is a toy ``tp_call`` implementation::" msgstr "" +#: ../../extending/newtypes.rst:480 +msgid "" +"static PyObject *\n" +"newdatatype_call(newdatatypeobject *obj, PyObject *args, PyObject *kwds)\n" +"{\n" +" PyObject *result;\n" +" const char *arg1;\n" +" const char *arg2;\n" +" const char *arg3;\n" +"\n" +" if (!PyArg_ParseTuple(args, \"sss:call\", &arg1, &arg2, &arg3)) {\n" +" return NULL;\n" +" }\n" +" result = PyUnicode_FromFormat(\n" +" \"Returning -- value: [%d] arg1: [%s] arg2: [%s] arg3: [%s]\\n\",\n" +" obj->obj_UnderlyingDatatypePtr->size,\n" +" arg1, arg2, arg3);\n" +" return result;\n" +"}" +msgstr "" + +#: ../../extending/newtypes.rst:500 +msgid "" +"/* Iterators */\n" +"getiterfunc tp_iter;\n" +"iternextfunc tp_iternext;" +msgstr "" + #: ../../extending/newtypes.rst:504 msgid "" "These functions provide support for the iterator protocol. Both handlers " @@ -541,12 +875,33 @@ msgid "" "Concretely, here is how the statically declared type object would look::" msgstr "" +#: ../../extending/newtypes.rst:555 +msgid "" +"static PyTypeObject TrivialType = {\n" +" PyVarObject_HEAD_INIT(NULL, 0)\n" +" /* ... other members omitted for brevity ... */\n" +" .tp_flags = Py_TPFLAGS_MANAGED_WEAKREF | ...,\n" +"};" +msgstr "" + #: ../../extending/newtypes.rst:562 msgid "" "The only further addition is that ``tp_dealloc`` needs to clear any weak " "references (by calling :c:func:`PyObject_ClearWeakRefs`)::" msgstr "" +#: ../../extending/newtypes.rst:565 +msgid "" +"static void\n" +"Trivial_dealloc(TrivialObject *self)\n" +"{\n" +" /* Clear weakrefs first before calling any destructors */\n" +" PyObject_ClearWeakRefs((PyObject *) self);\n" +" /* ... remainder of destruction code omitted for brevity ... */\n" +" Py_TYPE(self)->tp_free((PyObject *) self);\n" +"}" +msgstr "" + #: ../../extending/newtypes.rst:576 msgid "More Suggestions" msgstr "" @@ -567,6 +922,14 @@ msgid "" "sample of its use might be something like the following::" msgstr "" +#: ../../extending/newtypes.rst:588 +msgid "" +"if (!PyObject_TypeCheck(some_object, &MyType)) {\n" +" PyErr_SetString(PyExc_TypeError, \"arg #1 not a mything\");\n" +" return NULL;\n" +"}" +msgstr "" + #: ../../extending/newtypes.rst:594 msgid "Download CPython source releases." msgstr "" diff --git a/extending/newtypes_tutorial.po b/extending/newtypes_tutorial.po index 9e08c354f..03c6fbadb 100644 --- a/extending/newtypes_tutorial.po +++ b/extending/newtypes_tutorial.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# felipe caridade fernandes , 2021 -# Rafael Fontenelle , 2022 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 02:33+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Rafael Fontenelle , 2022\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -82,6 +80,54 @@ msgid "" "`PyType_FromSpec` function, which isn't covered in this tutorial." msgstr "" +#: ../../extending/newtypes_tutorial.rst:48 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"\n" +"typedef struct {\n" +" PyObject_HEAD\n" +" /* Type-specific fields go here. */\n" +"} CustomObject;\n" +"\n" +"static PyTypeObject CustomType = {\n" +" .ob_base = PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"custom.Custom\",\n" +" .tp_doc = PyDoc_STR(\"Custom objects\"),\n" +" .tp_basicsize = sizeof(CustomObject),\n" +" .tp_itemsize = 0,\n" +" .tp_flags = Py_TPFLAGS_DEFAULT,\n" +" .tp_new = PyType_GenericNew,\n" +"};\n" +"\n" +"static PyModuleDef custommodule = {\n" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"custom\",\n" +" .m_doc = \"Example module that creates an extension type.\",\n" +" .m_size = -1,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_custom(void)\n" +"{\n" +" PyObject *m;\n" +" if (PyType_Ready(&CustomType) < 0)\n" +" return NULL;\n" +"\n" +" m = PyModule_Create(&custommodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +"\n" +" if (PyModule_AddObjectRef(m, \"Custom\", (PyObject *) &CustomType) < 0) " +"{\n" +" Py_DECREF(m);\n" +" return NULL;\n" +" }\n" +"\n" +" return m;\n" +"}\n" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:50 msgid "" "Now that's quite a bit to take in at once, but hopefully bits will seem " @@ -114,6 +160,13 @@ msgstr "" msgid "The first bit is::" msgstr "O primeiro bit é ::" +#: ../../extending/newtypes_tutorial.rst:63 +msgid "" +"typedef struct {\n" +" PyObject_HEAD\n" +"} CustomObject;" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:67 msgid "" "This is what a Custom object will contain. ``PyObject_HEAD`` is mandatory " @@ -138,10 +191,31 @@ msgid "" "standard Python floats::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:83 +msgid "" +"typedef struct {\n" +" PyObject_HEAD\n" +" double ob_fval;\n" +"} PyFloatObject;" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:88 msgid "The second bit is the definition of the type object. ::" msgstr "O segundo bit é a definição do objeto de tipo. ::" +#: ../../extending/newtypes_tutorial.rst:90 +msgid "" +"static PyTypeObject CustomType = {\n" +" .ob_base = PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"custom.Custom\",\n" +" .tp_doc = PyDoc_STR(\"Custom objects\"),\n" +" .tp_basicsize = sizeof(CustomObject),\n" +" .tp_itemsize = 0,\n" +" .tp_flags = Py_TPFLAGS_DEFAULT,\n" +" .tp_new = PyType_GenericNew,\n" +"};" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:101 msgid "" "We recommend using C99-style designated initializers as above, to avoid " @@ -161,18 +235,34 @@ msgstr "" msgid "We're going to pick it apart, one field at a time::" msgstr "Vamos separá-lo, um campo de cada vez ::" +#: ../../extending/newtypes_tutorial.rst:112 +msgid ".ob_base = PyVarObject_HEAD_INIT(NULL, 0)" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:114 msgid "" "This line is mandatory boilerplate to initialize the ``ob_base`` field " "mentioned above. ::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:117 +msgid ".tp_name = \"custom.Custom\"," +msgstr "" + #: ../../extending/newtypes_tutorial.rst:119 msgid "" "The name of our type. This will appear in the default textual " "representation of our objects and in some error messages, for example:" msgstr "" +#: ../../extending/newtypes_tutorial.rst:122 +msgid "" +">>> \"\" + custom.Custom()\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: can only concatenate str (not \"custom.Custom\") to str" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:129 msgid "" "Note that the name is a dotted name that includes both the module name and " @@ -182,6 +272,12 @@ msgid "" "your type compatible with the :mod:`pydoc` and :mod:`pickle` modules. ::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:135 +msgid "" +".tp_basicsize = sizeof(CustomObject),\n" +".tp_itemsize = 0," +msgstr "" + #: ../../extending/newtypes_tutorial.rst:138 msgid "" "This is so that Python knows how much memory to allocate when creating new :" @@ -194,8 +290,8 @@ msgid "" "If you want your type to be subclassable from Python, and your type has the " "same :c:member:`~PyTypeObject.tp_basicsize` as its base type, you may have " "problems with multiple inheritance. A Python subclass of your type will " -"have to list your type first in its :attr:`~class.__bases__`, or else it " -"will not be able to call your type's :meth:`~object.__new__` method without " +"have to list your type first in its :attr:`~type.__bases__`, or else it will " +"not be able to call your type's :meth:`~object.__new__` method without " "getting an error. You can avoid this problem by ensuring that your type has " "a larger value for :c:member:`~PyTypeObject.tp_basicsize` than its base type " "does. Most of the time, this will be true anyway, because either your base " @@ -207,6 +303,10 @@ msgstr "" msgid "We set the class flags to :c:macro:`Py_TPFLAGS_DEFAULT`. ::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:156 +msgid ".tp_flags = Py_TPFLAGS_DEFAULT," +msgstr "" + #: ../../extending/newtypes_tutorial.rst:158 msgid "" "All types should include this constant in their flags. It enables all of " @@ -219,6 +319,10 @@ msgid "" "We provide a doc string for the type in :c:member:`~PyTypeObject.tp_doc`. ::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:164 +msgid ".tp_doc = PyDoc_STR(\"Custom objects\")," +msgstr "" + #: ../../extending/newtypes_tutorial.rst:166 msgid "" "To enable object creation, we have to provide a :c:member:`~PyTypeObject." @@ -228,12 +332,22 @@ msgid "" "`PyType_GenericNew`. ::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:171 +msgid ".tp_new = PyType_GenericNew," +msgstr "" + #: ../../extending/newtypes_tutorial.rst:173 msgid "" "Everything else in the file should be familiar, except for some code in :c:" "func:`!PyInit_custom`::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:176 +msgid "" +"if (PyType_Ready(&CustomType) < 0)\n" +" return;" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:179 msgid "" "This initializes the :class:`!Custom` type, filling in a number of members " @@ -241,26 +355,62 @@ msgid "" "that we initially set to ``NULL``. ::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:183 +msgid "" +"if (PyModule_AddObjectRef(m, \"Custom\", (PyObject *) &CustomType) < 0) {\n" +" Py_DECREF(m);\n" +" return NULL;\n" +"}" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:188 msgid "" "This adds the type to the module dictionary. This allows us to create :" "class:`!Custom` instances by calling the :class:`!Custom` class:" msgstr "" +#: ../../extending/newtypes_tutorial.rst:191 +msgid "" +">>> import custom\n" +">>> mycustom = custom.Custom()" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:196 msgid "" "That's it! All that remains is to build it; put the above code in a file " "called :file:`custom.c`," msgstr "" +#: ../../extending/newtypes_tutorial.rst:199 +msgid "" +"[build-system]\n" +"requires = [\"setuptools\"]\n" +"build-backend = \"setuptools.build_meta\"\n" +"\n" +"[project]\n" +"name = \"custom\"\n" +"version = \"1\"\n" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:201 msgid "in a file called :file:`pyproject.toml`, and" msgstr "" +#: ../../extending/newtypes_tutorial.rst:203 +msgid "" +"from setuptools import Extension, setup\n" +"setup(ext_modules=[Extension(\"custom\", [\"custom.c\"])])" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:208 msgid "in a file called :file:`setup.py`; then typing" msgstr "" +#: ../../extending/newtypes_tutorial.rst:210 +#: ../../extending/newtypes_tutorial.rst:525 +msgid "$ python -m pip install ." +msgstr "" + #: ../../extending/newtypes_tutorial.rst:214 msgid "" "in a shell should produce a file :file:`custom.so` in a subdirectory and " @@ -291,6 +441,141 @@ msgid "" "custom2` that adds these capabilities:" msgstr "" +#: ../../extending/newtypes_tutorial.rst:231 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"#include /* for offsetof() */\n" +"\n" +"typedef struct {\n" +" PyObject_HEAD\n" +" PyObject *first; /* first name */\n" +" PyObject *last; /* last name */\n" +" int number;\n" +"} CustomObject;\n" +"\n" +"static void\n" +"Custom_dealloc(CustomObject *self)\n" +"{\n" +" Py_XDECREF(self->first);\n" +" Py_XDECREF(self->last);\n" +" Py_TYPE(self)->tp_free((PyObject *) self);\n" +"}\n" +"\n" +"static PyObject *\n" +"Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n" +"{\n" +" CustomObject *self;\n" +" self = (CustomObject *) type->tp_alloc(type, 0);\n" +" if (self != NULL) {\n" +" self->first = PyUnicode_FromString(\"\");\n" +" if (self->first == NULL) {\n" +" Py_DECREF(self);\n" +" return NULL;\n" +" }\n" +" self->last = PyUnicode_FromString(\"\");\n" +" if (self->last == NULL) {\n" +" Py_DECREF(self);\n" +" return NULL;\n" +" }\n" +" self->number = 0;\n" +" }\n" +" return (PyObject *) self;\n" +"}\n" +"\n" +"static int\n" +"Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)\n" +"{\n" +" static char *kwlist[] = {\"first\", \"last\", \"number\", NULL};\n" +" PyObject *first = NULL, *last = NULL;\n" +"\n" +" if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|OOi\", kwlist,\n" +" &first, &last,\n" +" &self->number))\n" +" return -1;\n" +"\n" +" if (first) {\n" +" Py_XSETREF(self->first, Py_NewRef(first));\n" +" }\n" +" if (last) {\n" +" Py_XSETREF(self->last, Py_NewRef(last));\n" +" }\n" +" return 0;\n" +"}\n" +"\n" +"static PyMemberDef Custom_members[] = {\n" +" {\"first\", Py_T_OBJECT_EX, offsetof(CustomObject, first), 0,\n" +" \"first name\"},\n" +" {\"last\", Py_T_OBJECT_EX, offsetof(CustomObject, last), 0,\n" +" \"last name\"},\n" +" {\"number\", Py_T_INT, offsetof(CustomObject, number), 0,\n" +" \"custom number\"},\n" +" {NULL} /* Sentinel */\n" +"};\n" +"\n" +"static PyObject *\n" +"Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))\n" +"{\n" +" if (self->first == NULL) {\n" +" PyErr_SetString(PyExc_AttributeError, \"first\");\n" +" return NULL;\n" +" }\n" +" if (self->last == NULL) {\n" +" PyErr_SetString(PyExc_AttributeError, \"last\");\n" +" return NULL;\n" +" }\n" +" return PyUnicode_FromFormat(\"%S %S\", self->first, self->last);\n" +"}\n" +"\n" +"static PyMethodDef Custom_methods[] = {\n" +" {\"name\", (PyCFunction) Custom_name, METH_NOARGS,\n" +" \"Return the name, combining the first and last name\"\n" +" },\n" +" {NULL} /* Sentinel */\n" +"};\n" +"\n" +"static PyTypeObject CustomType = {\n" +" .ob_base = PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"custom2.Custom\",\n" +" .tp_doc = PyDoc_STR(\"Custom objects\"),\n" +" .tp_basicsize = sizeof(CustomObject),\n" +" .tp_itemsize = 0,\n" +" .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,\n" +" .tp_new = Custom_new,\n" +" .tp_init = (initproc) Custom_init,\n" +" .tp_dealloc = (destructor) Custom_dealloc,\n" +" .tp_members = Custom_members,\n" +" .tp_methods = Custom_methods,\n" +"};\n" +"\n" +"static PyModuleDef custommodule = {\n" +" .m_base =PyModuleDef_HEAD_INIT,\n" +" .m_name = \"custom2\",\n" +" .m_doc = \"Example module that creates an extension type.\",\n" +" .m_size = -1,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_custom2(void)\n" +"{\n" +" PyObject *m;\n" +" if (PyType_Ready(&CustomType) < 0)\n" +" return NULL;\n" +"\n" +" m = PyModule_Create(&custommodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +"\n" +" if (PyModule_AddObjectRef(m, \"Custom\", (PyObject *) &CustomType) < 0) " +"{\n" +" Py_DECREF(m);\n" +" return NULL;\n" +" }\n" +"\n" +" return m;\n" +"}\n" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:234 msgid "This version of the module has a number of changes." msgstr "Esta versão do módulo possui várias alterações." @@ -307,16 +592,41 @@ msgstr "" msgid "The object structure is updated accordingly::" msgstr "A estrutura do objeto é atualizada de acordo ::" +#: ../../extending/newtypes_tutorial.rst:242 +msgid "" +"typedef struct {\n" +" PyObject_HEAD\n" +" PyObject *first; /* first name */\n" +" PyObject *last; /* last name */\n" +" int number;\n" +"} CustomObject;" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:249 msgid "" "Because we now have data to manage, we have to be more careful about object " "allocation and deallocation. At a minimum, we need a deallocation method::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:252 +msgid "" +"static void\n" +"Custom_dealloc(CustomObject *self)\n" +"{\n" +" Py_XDECREF(self->first);\n" +" Py_XDECREF(self->last);\n" +" Py_TYPE(self)->tp_free((PyObject *) self);\n" +"}" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:260 msgid "which is assigned to the :c:member:`~PyTypeObject.tp_dealloc` member::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:262 +msgid ".tp_dealloc = (destructor) Custom_dealloc," +msgstr "" + #: ../../extending/newtypes_tutorial.rst:264 msgid "" "This method first clears the reference counts of the two Python attributes. :" @@ -343,10 +653,38 @@ msgid "" "strings, so we provide a ``tp_new`` implementation::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:282 +msgid "" +"static PyObject *\n" +"Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n" +"{\n" +" CustomObject *self;\n" +" self = (CustomObject *) type->tp_alloc(type, 0);\n" +" if (self != NULL) {\n" +" self->first = PyUnicode_FromString(\"\");\n" +" if (self->first == NULL) {\n" +" Py_DECREF(self);\n" +" return NULL;\n" +" }\n" +" self->last = PyUnicode_FromString(\"\");\n" +" if (self->last == NULL) {\n" +" Py_DECREF(self);\n" +" return NULL;\n" +" }\n" +" self->number = 0;\n" +" }\n" +" return (PyObject *) self;\n" +"}" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:303 msgid "and install it in the :c:member:`~PyTypeObject.tp_new` member::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:305 +msgid ".tp_new = Custom_new," +msgstr "" + #: ../../extending/newtypes_tutorial.rst:307 msgid "" "The ``tp_new`` handler is responsible for creating (as opposed to " @@ -380,6 +718,10 @@ msgid "" "slot to allocate memory::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:329 +msgid "self = (CustomObject *) type->tp_alloc(type, 0);" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:331 msgid "" "Since memory allocation may fail, we must check the :c:member:`~PyTypeObject." @@ -413,10 +755,43 @@ msgid "" "initial values for our instance::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:354 +msgid "" +"static int\n" +"Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)\n" +"{\n" +" static char *kwlist[] = {\"first\", \"last\", \"number\", NULL};\n" +" PyObject *first = NULL, *last = NULL, *tmp;\n" +"\n" +" if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|OOi\", kwlist,\n" +" &first, &last,\n" +" &self->number))\n" +" return -1;\n" +"\n" +" if (first) {\n" +" tmp = self->first;\n" +" Py_INCREF(first);\n" +" self->first = first;\n" +" Py_XDECREF(tmp);\n" +" }\n" +" if (last) {\n" +" tmp = self->last;\n" +" Py_INCREF(last);\n" +" self->last = last;\n" +" Py_XDECREF(tmp);\n" +" }\n" +" return 0;\n" +"}" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:380 msgid "by filling the :c:member:`~PyTypeObject.tp_init` slot. ::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:382 +msgid ".tp_init = (initproc) Custom_init," +msgstr "" + #: ../../extending/newtypes_tutorial.rst:384 msgid "" "The :c:member:`~PyTypeObject.tp_init` slot is exposed in Python as the :meth:" @@ -436,6 +811,15 @@ msgid "" "``first`` member like this::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:397 +msgid "" +"if (first) {\n" +" Py_XDECREF(self->first);\n" +" Py_INCREF(first);\n" +" self->first = first;\n" +"}" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:403 msgid "" "But this would be risky. Our type doesn't restrict the type of the " @@ -480,11 +864,28 @@ msgid "" "of ways to do that. The simplest way is to define member definitions::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:425 +msgid "" +"static PyMemberDef Custom_members[] = {\n" +" {\"first\", Py_T_OBJECT_EX, offsetof(CustomObject, first), 0,\n" +" \"first name\"},\n" +" {\"last\", Py_T_OBJECT_EX, offsetof(CustomObject, last), 0,\n" +" \"last name\"},\n" +" {\"number\", Py_T_INT, offsetof(CustomObject, number), 0,\n" +" \"custom number\"},\n" +" {NULL} /* Sentinel */\n" +"};" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:435 msgid "" "and put the definitions in the :c:member:`~PyTypeObject.tp_members` slot::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:437 +msgid ".tp_members = Custom_members," +msgstr "" + #: ../../extending/newtypes_tutorial.rst:439 msgid "" "Each member definition has a member name, type, offset, access flags and " @@ -505,10 +906,27 @@ msgstr "" #: ../../extending/newtypes_tutorial.rst:450 msgid "" -"We define a single method, :meth:`!Custom.name()`, that outputs the objects " +"We define a single method, :meth:`!Custom.name`, that outputs the objects " "name as the concatenation of the first and last names. ::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:453 +msgid "" +"static PyObject *\n" +"Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))\n" +"{\n" +" if (self->first == NULL) {\n" +" PyErr_SetString(PyExc_AttributeError, \"first\");\n" +" return NULL;\n" +" }\n" +" if (self->last == NULL) {\n" +" PyErr_SetString(PyExc_AttributeError, \"last\");\n" +" return NULL;\n" +" }\n" +" return PyUnicode_FromFormat(\"%S %S\", self->first, self->last);\n" +"}" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:467 msgid "" "The method is implemented as a C function that takes a :class:`!Custom` (or :" @@ -519,6 +937,12 @@ msgid "" "method is equivalent to the Python method:" msgstr "" +#: ../../extending/newtypes_tutorial.rst:474 +msgid "" +"def name(self):\n" +" return \"%s %s\" % (self.first, self.last)" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:479 msgid "" "Note that we have to check for the possibility that our :attr:`!first` and :" @@ -536,6 +960,16 @@ msgstr "" "Agora que definimos o método, precisamos criar uma array de definições de " "métodos::" +#: ../../extending/newtypes_tutorial.rst:488 +msgid "" +"static PyMethodDef Custom_methods[] = {\n" +" {\"name\", (PyCFunction) Custom_name, METH_NOARGS,\n" +" \"Return the name, combining the first and last name\"\n" +" },\n" +" {NULL} /* Sentinel */\n" +"};" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:495 msgid "" "(note that we used the :c:macro:`METH_NOARGS` flag to indicate that the " @@ -546,6 +980,10 @@ msgstr "" msgid "and assign it to the :c:member:`~PyTypeObject.tp_methods` slot::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:500 +msgid ".tp_methods = Custom_methods," +msgstr "" + #: ../../extending/newtypes_tutorial.rst:502 msgid "" "Finally, we'll make our type usable as a base class for subclassing. We've " @@ -554,6 +992,10 @@ msgid "" "to add the :c:macro:`Py_TPFLAGS_BASETYPE` to our class flag definition::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:507 +msgid ".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE," +msgstr "" + #: ../../extending/newtypes_tutorial.rst:509 msgid "" "We rename :c:func:`!PyInit_custom` to :c:func:`!PyInit_custom2`, update the " @@ -565,6 +1007,15 @@ msgstr "" msgid "Finally, we update our :file:`setup.py` file to include the new module," msgstr "" +#: ../../extending/newtypes_tutorial.rst:515 +msgid "" +"from setuptools import Extension, setup\n" +"setup(ext_modules=[\n" +" Extension(\"custom\", [\"custom.c\"]),\n" +" Extension(\"custom2\", [\"custom2.c\"]),\n" +"])" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:523 msgid "and then we re-install so that we can ``import custom2``:" msgstr "" @@ -582,6 +1033,184 @@ msgid "" "make sure that these attributes always contain strings." msgstr "" +#: ../../extending/newtypes_tutorial.rst:538 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"#include /* for offsetof() */\n" +"\n" +"typedef struct {\n" +" PyObject_HEAD\n" +" PyObject *first; /* first name */\n" +" PyObject *last; /* last name */\n" +" int number;\n" +"} CustomObject;\n" +"\n" +"static void\n" +"Custom_dealloc(CustomObject *self)\n" +"{\n" +" Py_XDECREF(self->first);\n" +" Py_XDECREF(self->last);\n" +" Py_TYPE(self)->tp_free((PyObject *) self);\n" +"}\n" +"\n" +"static PyObject *\n" +"Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n" +"{\n" +" CustomObject *self;\n" +" self = (CustomObject *) type->tp_alloc(type, 0);\n" +" if (self != NULL) {\n" +" self->first = PyUnicode_FromString(\"\");\n" +" if (self->first == NULL) {\n" +" Py_DECREF(self);\n" +" return NULL;\n" +" }\n" +" self->last = PyUnicode_FromString(\"\");\n" +" if (self->last == NULL) {\n" +" Py_DECREF(self);\n" +" return NULL;\n" +" }\n" +" self->number = 0;\n" +" }\n" +" return (PyObject *) self;\n" +"}\n" +"\n" +"static int\n" +"Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)\n" +"{\n" +" static char *kwlist[] = {\"first\", \"last\", \"number\", NULL};\n" +" PyObject *first = NULL, *last = NULL;\n" +"\n" +" if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|UUi\", kwlist,\n" +" &first, &last,\n" +" &self->number))\n" +" return -1;\n" +"\n" +" if (first) {\n" +" Py_SETREF(self->first, Py_NewRef(first));\n" +" }\n" +" if (last) {\n" +" Py_SETREF(self->last, Py_NewRef(last));\n" +" }\n" +" return 0;\n" +"}\n" +"\n" +"static PyMemberDef Custom_members[] = {\n" +" {\"number\", Py_T_INT, offsetof(CustomObject, number), 0,\n" +" \"custom number\"},\n" +" {NULL} /* Sentinel */\n" +"};\n" +"\n" +"static PyObject *\n" +"Custom_getfirst(CustomObject *self, void *closure)\n" +"{\n" +" return Py_NewRef(self->first);\n" +"}\n" +"\n" +"static int\n" +"Custom_setfirst(CustomObject *self, PyObject *value, void *closure)\n" +"{\n" +" if (value == NULL) {\n" +" PyErr_SetString(PyExc_TypeError, \"Cannot delete the first " +"attribute\");\n" +" return -1;\n" +" }\n" +" if (!PyUnicode_Check(value)) {\n" +" PyErr_SetString(PyExc_TypeError,\n" +" \"The first attribute value must be a string\");\n" +" return -1;\n" +" }\n" +" Py_SETREF(self->first, Py_NewRef(value));\n" +" return 0;\n" +"}\n" +"\n" +"static PyObject *\n" +"Custom_getlast(CustomObject *self, void *closure)\n" +"{\n" +" return Py_NewRef(self->last);\n" +"}\n" +"\n" +"static int\n" +"Custom_setlast(CustomObject *self, PyObject *value, void *closure)\n" +"{\n" +" if (value == NULL) {\n" +" PyErr_SetString(PyExc_TypeError, \"Cannot delete the last " +"attribute\");\n" +" return -1;\n" +" }\n" +" if (!PyUnicode_Check(value)) {\n" +" PyErr_SetString(PyExc_TypeError,\n" +" \"The last attribute value must be a string\");\n" +" return -1;\n" +" }\n" +" Py_SETREF(self->last, Py_NewRef(value));\n" +" return 0;\n" +"}\n" +"\n" +"static PyGetSetDef Custom_getsetters[] = {\n" +" {\"first\", (getter) Custom_getfirst, (setter) Custom_setfirst,\n" +" \"first name\", NULL},\n" +" {\"last\", (getter) Custom_getlast, (setter) Custom_setlast,\n" +" \"last name\", NULL},\n" +" {NULL} /* Sentinel */\n" +"};\n" +"\n" +"static PyObject *\n" +"Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))\n" +"{\n" +" return PyUnicode_FromFormat(\"%S %S\", self->first, self->last);\n" +"}\n" +"\n" +"static PyMethodDef Custom_methods[] = {\n" +" {\"name\", (PyCFunction) Custom_name, METH_NOARGS,\n" +" \"Return the name, combining the first and last name\"\n" +" },\n" +" {NULL} /* Sentinel */\n" +"};\n" +"\n" +"static PyTypeObject CustomType = {\n" +" .ob_base = PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"custom3.Custom\",\n" +" .tp_doc = PyDoc_STR(\"Custom objects\"),\n" +" .tp_basicsize = sizeof(CustomObject),\n" +" .tp_itemsize = 0,\n" +" .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,\n" +" .tp_new = Custom_new,\n" +" .tp_init = (initproc) Custom_init,\n" +" .tp_dealloc = (destructor) Custom_dealloc,\n" +" .tp_members = Custom_members,\n" +" .tp_methods = Custom_methods,\n" +" .tp_getset = Custom_getsetters,\n" +"};\n" +"\n" +"static PyModuleDef custommodule = {\n" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"custom3\",\n" +" .m_doc = \"Example module that creates an extension type.\",\n" +" .m_size = -1,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_custom3(void)\n" +"{\n" +" PyObject *m;\n" +" if (PyType_Ready(&CustomType) < 0)\n" +" return NULL;\n" +"\n" +" m = PyModule_Create(&custommodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +"\n" +" if (PyModule_AddObjectRef(m, \"Custom\", (PyObject *) &CustomType) < 0) " +"{\n" +" Py_DECREF(m);\n" +" return NULL;\n" +" }\n" +"\n" +" return m;\n" +"}\n" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:541 msgid "" "To provide greater control, over the :attr:`!first` and :attr:`!last` " @@ -589,6 +1218,37 @@ msgid "" "functions for getting and setting the :attr:`!first` attribute::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:545 +msgid "" +"static PyObject *\n" +"Custom_getfirst(CustomObject *self, void *closure)\n" +"{\n" +" Py_INCREF(self->first);\n" +" return self->first;\n" +"}\n" +"\n" +"static int\n" +"Custom_setfirst(CustomObject *self, PyObject *value, void *closure)\n" +"{\n" +" PyObject *tmp;\n" +" if (value == NULL) {\n" +" PyErr_SetString(PyExc_TypeError, \"Cannot delete the first " +"attribute\");\n" +" return -1;\n" +" }\n" +" if (!PyUnicode_Check(value)) {\n" +" PyErr_SetString(PyExc_TypeError,\n" +" \"The first attribute value must be a string\");\n" +" return -1;\n" +" }\n" +" tmp = self->first;\n" +" Py_INCREF(value);\n" +" self->first = value;\n" +" Py_DECREF(tmp);\n" +" return 0;\n" +"}" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:572 msgid "" "The getter function is passed a :class:`!Custom` object and a \"closure\", " @@ -611,10 +1271,25 @@ msgstr "" msgid "We create an array of :c:type:`PyGetSetDef` structures::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:585 +msgid "" +"static PyGetSetDef Custom_getsetters[] = {\n" +" {\"first\", (getter) Custom_getfirst, (setter) Custom_setfirst,\n" +" \"first name\", NULL},\n" +" {\"last\", (getter) Custom_getlast, (setter) Custom_setlast,\n" +" \"last name\", NULL},\n" +" {NULL} /* Sentinel */\n" +"};" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:593 msgid "and register it in the :c:member:`~PyTypeObject.tp_getset` slot::" msgstr "e registra isso num slot :c:member:`~PyTypeObject.tp_getset`::" +#: ../../extending/newtypes_tutorial.rst:595 +msgid ".tp_getset = Custom_getsetters," +msgstr "" + #: ../../extending/newtypes_tutorial.rst:597 msgid "" "The last item in a :c:type:`PyGetSetDef` structure is the \"closure\" " @@ -626,12 +1301,50 @@ msgstr "" msgid "We also remove the member definitions for these attributes::" msgstr "Também removemos as definições de membros para esses atributos::" +#: ../../extending/newtypes_tutorial.rst:602 +msgid "" +"static PyMemberDef Custom_members[] = {\n" +" {\"number\", Py_T_INT, offsetof(CustomObject, number), 0,\n" +" \"custom number\"},\n" +" {NULL} /* Sentinel */\n" +"};" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:608 msgid "" "We also need to update the :c:member:`~PyTypeObject.tp_init` handler to only " "allow strings [#]_ to be passed::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:611 +msgid "" +"static int\n" +"Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)\n" +"{\n" +" static char *kwlist[] = {\"first\", \"last\", \"number\", NULL};\n" +" PyObject *first = NULL, *last = NULL, *tmp;\n" +"\n" +" if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|UUi\", kwlist,\n" +" &first, &last,\n" +" &self->number))\n" +" return -1;\n" +"\n" +" if (first) {\n" +" tmp = self->first;\n" +" Py_INCREF(first);\n" +" self->first = first;\n" +" Py_DECREF(tmp);\n" +" }\n" +" if (last) {\n" +" tmp = self->last;\n" +" Py_INCREF(last);\n" +" self->last = last;\n" +" Py_DECREF(tmp);\n" +" }\n" +" return 0;\n" +"}" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:637 msgid "" "With these changes, we can assure that the ``first`` and ``last`` members " @@ -660,6 +1373,13 @@ msgid "" "This can happen when objects are involved in cycles. For example, consider:" msgstr "" +#: ../../extending/newtypes_tutorial.rst:656 +msgid "" +">>> l = []\n" +">>> l.append(l)\n" +">>> del l" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:662 msgid "" "In this example, we create a list that contains itself. When we delete it, " @@ -677,6 +1397,15 @@ msgid "" "those two reasons, :class:`!Custom` objects can participate in cycles:" msgstr "" +#: ../../extending/newtypes_tutorial.rst:673 +msgid "" +">>> import custom3\n" +">>> class Derived(custom3.Custom): pass\n" +"...\n" +">>> n = Derived()\n" +">>> n.some_attribute = n" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:681 msgid "" "To allow a :class:`!Custom` instance participating in a reference cycle to " @@ -685,12 +1414,229 @@ msgid "" "these slots:" msgstr "" +#: ../../extending/newtypes_tutorial.rst:685 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"#include /* for offsetof() */\n" +"\n" +"typedef struct {\n" +" PyObject_HEAD\n" +" PyObject *first; /* first name */\n" +" PyObject *last; /* last name */\n" +" int number;\n" +"} CustomObject;\n" +"\n" +"static int\n" +"Custom_traverse(CustomObject *self, visitproc visit, void *arg)\n" +"{\n" +" Py_VISIT(self->first);\n" +" Py_VISIT(self->last);\n" +" return 0;\n" +"}\n" +"\n" +"static int\n" +"Custom_clear(CustomObject *self)\n" +"{\n" +" Py_CLEAR(self->first);\n" +" Py_CLEAR(self->last);\n" +" return 0;\n" +"}\n" +"\n" +"static void\n" +"Custom_dealloc(CustomObject *self)\n" +"{\n" +" PyObject_GC_UnTrack(self);\n" +" Custom_clear(self);\n" +" Py_TYPE(self)->tp_free((PyObject *) self);\n" +"}\n" +"\n" +"static PyObject *\n" +"Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n" +"{\n" +" CustomObject *self;\n" +" self = (CustomObject *) type->tp_alloc(type, 0);\n" +" if (self != NULL) {\n" +" self->first = PyUnicode_FromString(\"\");\n" +" if (self->first == NULL) {\n" +" Py_DECREF(self);\n" +" return NULL;\n" +" }\n" +" self->last = PyUnicode_FromString(\"\");\n" +" if (self->last == NULL) {\n" +" Py_DECREF(self);\n" +" return NULL;\n" +" }\n" +" self->number = 0;\n" +" }\n" +" return (PyObject *) self;\n" +"}\n" +"\n" +"static int\n" +"Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)\n" +"{\n" +" static char *kwlist[] = {\"first\", \"last\", \"number\", NULL};\n" +" PyObject *first = NULL, *last = NULL;\n" +"\n" +" if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|UUi\", kwlist,\n" +" &first, &last,\n" +" &self->number))\n" +" return -1;\n" +"\n" +" if (first) {\n" +" Py_SETREF(self->first, Py_NewRef(first));\n" +" }\n" +" if (last) {\n" +" Py_SETREF(self->last, Py_NewRef(last));\n" +" }\n" +" return 0;\n" +"}\n" +"\n" +"static PyMemberDef Custom_members[] = {\n" +" {\"number\", Py_T_INT, offsetof(CustomObject, number), 0,\n" +" \"custom number\"},\n" +" {NULL} /* Sentinel */\n" +"};\n" +"\n" +"static PyObject *\n" +"Custom_getfirst(CustomObject *self, void *closure)\n" +"{\n" +" return Py_NewRef(self->first);\n" +"}\n" +"\n" +"static int\n" +"Custom_setfirst(CustomObject *self, PyObject *value, void *closure)\n" +"{\n" +" if (value == NULL) {\n" +" PyErr_SetString(PyExc_TypeError, \"Cannot delete the first " +"attribute\");\n" +" return -1;\n" +" }\n" +" if (!PyUnicode_Check(value)) {\n" +" PyErr_SetString(PyExc_TypeError,\n" +" \"The first attribute value must be a string\");\n" +" return -1;\n" +" }\n" +" Py_XSETREF(self->first, Py_NewRef(value));\n" +" return 0;\n" +"}\n" +"\n" +"static PyObject *\n" +"Custom_getlast(CustomObject *self, void *closure)\n" +"{\n" +" return Py_NewRef(self->last);\n" +"}\n" +"\n" +"static int\n" +"Custom_setlast(CustomObject *self, PyObject *value, void *closure)\n" +"{\n" +" if (value == NULL) {\n" +" PyErr_SetString(PyExc_TypeError, \"Cannot delete the last " +"attribute\");\n" +" return -1;\n" +" }\n" +" if (!PyUnicode_Check(value)) {\n" +" PyErr_SetString(PyExc_TypeError,\n" +" \"The last attribute value must be a string\");\n" +" return -1;\n" +" }\n" +" Py_XSETREF(self->last, Py_NewRef(value));\n" +" return 0;\n" +"}\n" +"\n" +"static PyGetSetDef Custom_getsetters[] = {\n" +" {\"first\", (getter) Custom_getfirst, (setter) Custom_setfirst,\n" +" \"first name\", NULL},\n" +" {\"last\", (getter) Custom_getlast, (setter) Custom_setlast,\n" +" \"last name\", NULL},\n" +" {NULL} /* Sentinel */\n" +"};\n" +"\n" +"static PyObject *\n" +"Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))\n" +"{\n" +" return PyUnicode_FromFormat(\"%S %S\", self->first, self->last);\n" +"}\n" +"\n" +"static PyMethodDef Custom_methods[] = {\n" +" {\"name\", (PyCFunction) Custom_name, METH_NOARGS,\n" +" \"Return the name, combining the first and last name\"\n" +" },\n" +" {NULL} /* Sentinel */\n" +"};\n" +"\n" +"static PyTypeObject CustomType = {\n" +" .ob_base = PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"custom4.Custom\",\n" +" .tp_doc = PyDoc_STR(\"Custom objects\"),\n" +" .tp_basicsize = sizeof(CustomObject),\n" +" .tp_itemsize = 0,\n" +" .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | " +"Py_TPFLAGS_HAVE_GC,\n" +" .tp_new = Custom_new,\n" +" .tp_init = (initproc) Custom_init,\n" +" .tp_dealloc = (destructor) Custom_dealloc,\n" +" .tp_traverse = (traverseproc) Custom_traverse,\n" +" .tp_clear = (inquiry) Custom_clear,\n" +" .tp_members = Custom_members,\n" +" .tp_methods = Custom_methods,\n" +" .tp_getset = Custom_getsetters,\n" +"};\n" +"\n" +"static PyModuleDef custommodule = {\n" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"custom4\",\n" +" .m_doc = \"Example module that creates an extension type.\",\n" +" .m_size = -1,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_custom4(void)\n" +"{\n" +" PyObject *m;\n" +" if (PyType_Ready(&CustomType) < 0)\n" +" return NULL;\n" +"\n" +" m = PyModule_Create(&custommodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +"\n" +" if (PyModule_AddObjectRef(m, \"Custom\", (PyObject *) &CustomType) < 0) " +"{\n" +" Py_DECREF(m);\n" +" return NULL;\n" +" }\n" +"\n" +" return m;\n" +"}\n" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:688 msgid "" "First, the traversal method lets the cyclic GC know about subobjects that " "could participate in cycles::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:691 +msgid "" +"static int\n" +"Custom_traverse(CustomObject *self, visitproc visit, void *arg)\n" +"{\n" +" int vret;\n" +" if (self->first) {\n" +" vret = visit(self->first, arg);\n" +" if (vret != 0)\n" +" return vret;\n" +" }\n" +" if (self->last) {\n" +" vret = visit(self->last, arg);\n" +" if (vret != 0)\n" +" return vret;\n" +" }\n" +" return 0;\n" +"}" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:708 msgid "" "For each subobject that can participate in cycles, we need to call the :c:" @@ -707,6 +1653,17 @@ msgid "" "boilerplate in ``Custom_traverse``::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:718 +msgid "" +"static int\n" +"Custom_traverse(CustomObject *self, visitproc visit, void *arg)\n" +"{\n" +" Py_VISIT(self->first);\n" +" Py_VISIT(self->last);\n" +" return 0;\n" +"}" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:727 msgid "" "The :c:member:`~PyTypeObject.tp_traverse` implementation must name its " @@ -719,6 +1676,17 @@ msgid "" "participate in cycles::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:733 +msgid "" +"static int\n" +"Custom_clear(CustomObject *self)\n" +"{\n" +" Py_CLEAR(self->first);\n" +" Py_CLEAR(self->last);\n" +" return 0;\n" +"}" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:741 msgid "" "Notice the use of the :c:func:`Py_CLEAR` macro. It is the recommended and " @@ -733,6 +1701,14 @@ msgstr "" msgid "You could emulate :c:func:`Py_CLEAR` by writing::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:751 +msgid "" +"PyObject *tmp;\n" +"tmp = self->first;\n" +"self->first = NULL;\n" +"Py_XDECREF(tmp);" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:756 msgid "" "Nevertheless, it is much easier and less error-prone to always use :c:func:" @@ -750,11 +1726,27 @@ msgid "" "`PyObject_GC_UnTrack` and ``Custom_clear``::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:767 +msgid "" +"static void\n" +"Custom_dealloc(CustomObject *self)\n" +"{\n" +" PyObject_GC_UnTrack(self);\n" +" Custom_clear(self);\n" +" Py_TYPE(self)->tp_free((PyObject *) self);\n" +"}" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:775 msgid "" "Finally, we add the :c:macro:`Py_TPFLAGS_HAVE_GC` flag to the class flags::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:777 +msgid "" +".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC," +msgstr "" + #: ../../extending/newtypes_tutorial.rst:779 msgid "" "That's pretty much it. If we had written custom :c:member:`~PyTypeObject." @@ -783,6 +1775,91 @@ msgid "" "that increases an internal counter:" msgstr "" +#: ../../extending/newtypes_tutorial.rst:797 +msgid "" +">>> import sublist\n" +">>> s = sublist.SubList(range(3))\n" +">>> s.extend(s)\n" +">>> print(len(s))\n" +"6\n" +">>> print(s.increment())\n" +"1\n" +">>> print(s.increment())\n" +"2" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:809 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"\n" +"typedef struct {\n" +" PyListObject list;\n" +" int state;\n" +"} SubListObject;\n" +"\n" +"static PyObject *\n" +"SubList_increment(SubListObject *self, PyObject *unused)\n" +"{\n" +" self->state++;\n" +" return PyLong_FromLong(self->state);\n" +"}\n" +"\n" +"static PyMethodDef SubList_methods[] = {\n" +" {\"increment\", (PyCFunction) SubList_increment, METH_NOARGS,\n" +" PyDoc_STR(\"increment state counter\")},\n" +" {NULL},\n" +"};\n" +"\n" +"static int\n" +"SubList_init(SubListObject *self, PyObject *args, PyObject *kwds)\n" +"{\n" +" if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0)\n" +" return -1;\n" +" self->state = 0;\n" +" return 0;\n" +"}\n" +"\n" +"static PyTypeObject SubListType = {\n" +" PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"sublist.SubList\",\n" +" .tp_doc = PyDoc_STR(\"SubList objects\"),\n" +" .tp_basicsize = sizeof(SubListObject),\n" +" .tp_itemsize = 0,\n" +" .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,\n" +" .tp_init = (initproc) SubList_init,\n" +" .tp_methods = SubList_methods,\n" +"};\n" +"\n" +"static PyModuleDef sublistmodule = {\n" +" PyModuleDef_HEAD_INIT,\n" +" .m_name = \"sublist\",\n" +" .m_doc = \"Example module that creates an extension type.\",\n" +" .m_size = -1,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_sublist(void)\n" +"{\n" +" PyObject *m;\n" +" SubListType.tp_base = &PyList_Type;\n" +" if (PyType_Ready(&SubListType) < 0)\n" +" return NULL;\n" +"\n" +" m = PyModule_Create(&sublistmodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +"\n" +" if (PyModule_AddObjectRef(m, \"SubList\", (PyObject *) &SubListType) < " +"0) {\n" +" Py_DECREF(m);\n" +" return NULL;\n" +" }\n" +"\n" +" return m;\n" +"}\n" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:812 msgid "" "As you can see, the source code closely resembles the :class:`!Custom` " @@ -790,6 +1867,14 @@ msgid "" "between them. ::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:815 +msgid "" +"typedef struct {\n" +" PyListObject list;\n" +" int state;\n" +"} SubListObject;" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:820 msgid "" "The primary difference for derived type objects is that the base type's " @@ -804,6 +1889,18 @@ msgid "" "*``::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:827 +msgid "" +"static int\n" +"SubList_init(SubListObject *self, PyObject *args, PyObject *kwds)\n" +"{\n" +" if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0)\n" +" return -1;\n" +" self->state = 0;\n" +" return 0;\n" +"}" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:836 msgid "" "We see above how to call through to the :meth:`~object.__init__` method of " @@ -828,6 +1925,30 @@ msgid "" "function::" msgstr "" +#: ../../extending/newtypes_tutorial.rst:851 +msgid "" +"PyMODINIT_FUNC\n" +"PyInit_sublist(void)\n" +"{\n" +" PyObject* m;\n" +" SubListType.tp_base = &PyList_Type;\n" +" if (PyType_Ready(&SubListType) < 0)\n" +" return NULL;\n" +"\n" +" m = PyModule_Create(&sublistmodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +"\n" +" if (PyModule_AddObjectRef(m, \"SubList\", (PyObject *) &SubListType) < " +"0) {\n" +" Py_DECREF(m);\n" +" return NULL;\n" +" }\n" +"\n" +" return m;\n" +"}" +msgstr "" + #: ../../extending/newtypes_tutorial.rst:871 msgid "" "Before calling :c:func:`PyType_Ready`, the type structure must have the :c:" diff --git a/extending/windows.po b/extending/windows.po index bc2cc9351..93c45a216 100644 --- a/extending/windows.po +++ b/extending/windows.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# felipe caridade fernandes , 2021 -# Rafael Fontenelle , 2023 -# Guilherme Alves da Silva, 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Guilherme Alves da Silva, 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -198,10 +195,10 @@ msgid "" msgstr "" "Suponha que você esteja construindo dois módulos de carregamento dinâmico, B " "e C, que devem compartilhar outro bloco de código A. No Unix, você *não* " -"passaria :file:`A.a` ao vinculador para :file:`B.so` e :file:`C.so`; isso " -"faria com que fosse incluído duas vezes, para que B e C tivessem sua própria " +"passaria :file:`A.a` ao ligador para :file:`B.so` e :file:`C.so`; isso faria " +"com que fosse incluído duas vezes, para que B e C tivessem sua própria " "cópia. No Windows, a construção :file:`A.dll` também construirá :file:`A." -"lib`. Você *passa* :file:`A.lib` ao vinculador para B e C. :file:`A.lib` não " +"lib`. Você *passa* :file:`A.lib` ao ligador para B e C. :file:`A.lib` não " "contém código; apenas contém informações que serão usadas em tempo de " "execução para acessar o código de A." @@ -237,8 +234,16 @@ msgid "" "spam), you could use these commands::" msgstr "" "Ao criar DLLs no Windows, você deve passar :file:`pythonXY.lib` para o " -"vinculador. Para construir duas DLLs, spam e ni (que usa funções C " -"encontradas em spam), você pode usar estes comandos::" +"ligador. Para construir duas DLLs, spam e ni (que usa funções C encontradas " +"em spam), você pode usar estes comandos::" + +#: ../../extending/windows.rst:115 +msgid "" +"cl /LD /I/python/include spam.c ../libs/pythonXY.lib\n" +"cl /LD /I/python/include ni.c spam.lib ../libs/pythonXY.lib" +msgstr "" +"cl /LD /I/python/include spam.c ../libs/pythonXY.lib\n" +"cl /LD /I/python/include ni.c spam.lib ../libs/pythonXY.lib" #: ../../extending/windows.rst:118 msgid "" diff --git a/faq/design.po b/faq/design.po index 081cdff75..61a33f366 100644 --- a/faq/design.po +++ b/faq/design.po @@ -1,38 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Fernando, 2021 -# Aline Balogh , 2021 -# Amanda Savluchinske , 2021 -# Alexsandro Matias de Almeida , 2021 -# Vitor Buxbaum Orlandi, 2023 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../faq/design.rst:3 msgid "Design and History FAQ" -msgstr "Design e Histórico FAQ" +msgstr "FAQ sobre design e histórico" #: ../../faq/design.rst:6 msgid "Contents" @@ -63,6 +56,18 @@ msgstr "" "humano. Ocasionalmente, programadores C irão encontrar um fragmento de " "código como este::" +#: ../../faq/design.rst:21 +msgid "" +"if (x <= y)\n" +" x++;\n" +" y--;\n" +"z++;" +msgstr "" +"if (x <= y)\n" +" x++;\n" +" y--;\n" +"z++;" + #: ../../faq/design.rst:26 msgid "" "Only the ``x++`` statement is executed if the condition is true, but the " @@ -127,6 +132,14 @@ msgstr "Por que o cálculo de pontos flutuantes são tão imprecisos?" msgid "Users are often surprised by results like this::" msgstr "Usuários são frequentemente surpreendidos por resultados como este::" +#: ../../faq/design.rst:58 +msgid "" +">>> 1.2 - 1.0\n" +"0.19999999999999996" +msgstr "" +">>> 1.2 - 1.0\n" +"0.19999999999999996" + #: ../../faq/design.rst:61 msgid "" "and think it is a bug in Python. It's not. This has little to do with " @@ -163,6 +176,10 @@ msgstr "" "podem ser expressados exatamente em ponto flutuante binário. Por exemplo, " "após::" +#: ../../faq/design.rst:75 +msgid ">>> x = 1.2" +msgstr ">>> x = 1.2" + #: ../../faq/design.rst:77 msgid "" "the value stored for ``x`` is a (very good) approximation to the decimal " @@ -173,10 +190,18 @@ msgstr "" "``1.2``, mas não é exatamente igual. Em uma máquina típica, o valor real " "armazenado é::" +#: ../../faq/design.rst:81 +msgid "1.0011001100110011001100110011001100110011001100110011 (binary)" +msgstr "1.0011001100110011001100110011001100110011001100110011 (binário)" + #: ../../faq/design.rst:83 msgid "which is exactly::" msgstr "que é exatamente::" +#: ../../faq/design.rst:85 +msgid "1.1999999999999999555910790149937383830547332763671875 (decimal)" +msgstr "1.1999999999999999555910790149937383830547332763671875 (decimal)" + #: ../../faq/design.rst:87 msgid "" "The typical precision of 53 bits provides Python floats with 15--16 decimal " @@ -332,6 +357,14 @@ msgstr "" "Expressões de atribuição usando o operador morsa ``:=`` atribuem uma " "variável em uma expressão::" +#: ../../faq/design.rst:161 +msgid "" +"while chunk := fp.read(200):\n" +" print(chunk)" +msgstr "" +"while chunk := fp.read(200):\n" +" print(chunk)" + #: ../../faq/design.rst:164 msgid "See :pep:`572` for more information." msgstr "Veja :pep:`572` para mais informações." @@ -408,10 +441,18 @@ msgstr "" "maior parte desses novos métodos foram amplamente aceitos, mas o que parece " "deixar alguns programadores desconfortáveis é::" +#: ../../faq/design.rst:201 +msgid "\", \".join(['1', '2', '4', '8', '16'])" +msgstr "\", \".join(['1', '2', '4', '8', '16'])" + #: ../../faq/design.rst:203 msgid "which gives the result::" msgstr "que dá o resultado::" +#: ../../faq/design.rst:205 +msgid "\"1, 2, 4, 8, 16\"" +msgstr "\"1, 2, 4, 8, 16\"" + #: ../../faq/design.rst:207 msgid "There are two common arguments against this usage." msgstr "Existem dois argumentos comuns contra esse uso." @@ -443,6 +484,10 @@ msgstr "" "dificuldade em ter :meth:`~str.split` como um método string, já que nesse " "caso é fácil ver que ::" +#: ../../faq/design.rst:220 +msgid "\"1, 2, 4, 8, 16\".split(\", \")" +msgstr "\"1, 2, 4, 8, 16\".split(\", \")" + #: ../../faq/design.rst:222 msgid "" "is an instruction to a string literal to return the substrings delimited by " @@ -481,6 +526,20 @@ msgstr "" "nenhuma exceção for levantada. Na verdade, capturar uma exceção é caro. Nas " "versões do Python anteriores à 2.0 era comum usar esta expressão::" +#: ../../faq/design.rst:240 +msgid "" +"try:\n" +" value = mydict[key]\n" +"except KeyError:\n" +" mydict[key] = getvalue(key)\n" +" value = mydict[key]" +msgstr "" +"try:\n" +" value = mydict[key]\n" +"except KeyError:\n" +" mydict[key] = getvalue(key)\n" +" value = mydict[key]" + #: ../../faq/design.rst:246 msgid "" "This only made sense when you expected the dict to have the key almost all " @@ -490,6 +549,18 @@ msgstr "" "chave quase que toda vez. Se esse não fosse o caso, você escrevia desta " "maneira::" +#: ../../faq/design.rst:249 +msgid "" +"if key in mydict:\n" +" value = mydict[key]\n" +"else:\n" +" value = mydict[key] = getvalue(key)" +msgstr "" +"if key in mydict:\n" +" value = mydict[key]\n" +"else:\n" +" value = mydict[key] = getvalue(key)" + #: ../../faq/design.rst:254 msgid "" "For this specific case, you could also use ``value = dict.setdefault(key, " @@ -529,6 +600,22 @@ msgstr "" "possibilidades, você pode criar um dicionário mapeando valores de caso para " "funções a serem chamadas. Por exemplo::" +#: ../../faq/design.rst:272 +msgid "" +"functions = {'a': function_1,\n" +" 'b': function_2,\n" +" 'c': self.method_1}\n" +"\n" +"func = functions[value]\n" +"func()" +msgstr "" +"functions = {'a': function_1,\n" +" 'b': function_2,\n" +" 'c': self.method_1}\n" +"\n" +"func = functions[value]\n" +"func()" + #: ../../faq/design.rst:279 msgid "" "For calling methods on objects, you can simplify yet further by using the :" @@ -538,6 +625,26 @@ msgstr "" "função embutida :func:`getattr` para recuperar métodos com um nome " "específico::" +#: ../../faq/design.rst:282 +msgid "" +"class MyVisitor:\n" +" def visit_a(self):\n" +" ...\n" +"\n" +" def dispatch(self, value):\n" +" method_name = 'visit_' + str(value)\n" +" method = getattr(self, method_name)\n" +" method()" +msgstr "" +"class MyVisitor:\n" +" def visit_a(self):\n" +" ...\n" +"\n" +" def dispatch(self, value):\n" +" method_name = 'visit_' + str(value)\n" +" method = getattr(self, method_name)\n" +" method()" + #: ../../faq/design.rst:291 msgid "" "It's suggested that you use a prefix for the method names, such as " @@ -632,12 +739,12 @@ msgstr "" #: ../../faq/design.rst:330 msgid "" "`Cython `_ compiles a modified version of Python with " -"optional annotations into C extensions. `Nuitka `_ " -"is an up-and-coming compiler of Python into C++ code, aiming to support the " +"optional annotations into C extensions. `Nuitka `_ is " +"an up-and-coming compiler of Python into C++ code, aiming to support the " "full Python language." msgstr "" -"`Cython `_ compila uma versão modificada do Python com " -"anotações opcionais em extensões C. `Nuitka `_ é um " +"O `Cython `_ compila uma versão modificada do Python " +"com anotações opcionais em extensões C. `Nuitka `_ é um " "compilador emergente de Python em código C++, com o objetivo de oferecer " "suporte à linguagem Python completa." @@ -666,16 +773,16 @@ msgstr "" #: ../../faq/design.rst:347 msgid "" "Other implementations (such as `Jython `_ or `PyPy " -"`_), however, can rely on a different mechanism such " -"as a full-blown garbage collector. This difference can cause some subtle " -"porting problems if your Python code depends on the behavior of the " -"reference counting implementation." +"`_), however, can rely on a different mechanism such as a " +"full-blown garbage collector. This difference can cause some subtle porting " +"problems if your Python code depends on the behavior of the reference " +"counting implementation." msgstr "" "Outras implementações (como `Jython `_ ou `PyPy " -"`_), no entanto, podem contar com um mecanismo " -"diferente, como um coletor de lixo maduro. Essa diferença pode causar alguns " -"problemas sutis de portabilidade se o seu código Python depender do " -"comportamento da implementação de contagem de referências." +"`_), no entanto, podem contar com um mecanismo diferente, " +"como um coletor de lixo maduro. Essa diferença pode causar alguns problemas " +"sutis de portabilidade se o seu código Python depender do comportamento da " +"implementação de contagem de referências." #: ../../faq/design.rst:353 msgid "" @@ -685,6 +792,16 @@ msgstr "" "Em algumas implementações do Python, o código a seguir (que funciona bem no " "CPython) provavelmente ficará sem descritores de arquivo:" +#: ../../faq/design.rst:356 +msgid "" +"for file in very_long_list_of_files:\n" +" f = open(file)\n" +" c = f.read(1)" +msgstr "" +"for file in very_long_list_of_files:\n" +" f = open(file)\n" +" c = f.read(1)" + #: ../../faq/design.rst:360 msgid "" "Indeed, using CPython's reference counting and destructor scheme, each new " @@ -694,8 +811,8 @@ msgid "" msgstr "" "Na verdade, usando o esquema de contagem de referências e destrutor de " "referências do CPython, cada nova atribuição a ``f`` fecha o arquivo " -"anterior. Com um GC tradicional, entretanto, esses objetos de arquivo só " -"serão coletados (e fechados) em intervalos variados e possivelmente longos." +"anterior. Com um GC tradicional, entretanto, esses objetos arquivo só serão " +"coletados (e fechados) em intervalos variados e possivelmente longos." #: ../../faq/design.rst:365 msgid "" @@ -708,6 +825,16 @@ msgstr "" "keyword:`with`; isso funcionará independentemente do esquema de " "gerenciamento de memória::" +#: ../../faq/design.rst:369 +msgid "" +"for file in very_long_list_of_files:\n" +" with open(file) as f:\n" +" c = f.read(1)" +msgstr "" +"for file in very_long_list_of_files:\n" +" with open(file) as f:\n" +" c = f.read(1)" + #: ../../faq/design.rst:375 msgid "Why doesn't CPython use a more traditional garbage collection scheme?" msgstr "" @@ -952,6 +1079,14 @@ msgstr "" "construir uma nova lista com o mesmo valor ela não será encontrada; por " "exemplo.::" +#: ../../faq/design.rst:483 +msgid "" +"mydict = {[1, 2]: '12'}\n" +"print(mydict[[1, 2]])" +msgstr "" +"mydict = {[1, 2]: '12'}\n" +"print(mydict[[1, 2]])" + #: ../../faq/design.rst:486 msgid "" "would raise a :exc:`KeyError` exception because the id of the ``[1, 2]`` " @@ -1020,6 +1155,42 @@ msgstr "" "estrutura baseada em hash) permaneça fixo enquanto o objeto estiver no " "dicionário (ou outra estrutura). ::" +#: ../../faq/design.rst:513 +msgid "" +"class ListWrapper:\n" +" def __init__(self, the_list):\n" +" self.the_list = the_list\n" +"\n" +" def __eq__(self, other):\n" +" return self.the_list == other.the_list\n" +"\n" +" def __hash__(self):\n" +" l = self.the_list\n" +" result = 98767 - len(l)*555\n" +" for i, el in enumerate(l):\n" +" try:\n" +" result = result + (hash(el) % 9999999) * 1001 + i\n" +" except Exception:\n" +" result = (result % 7777777) + i * 333\n" +" return result" +msgstr "" +"class ListWrapper:\n" +" def __init__(self, the_list):\n" +" self.the_list = the_list\n" +"\n" +" def __eq__(self, other):\n" +" return self.the_list == other.the_list\n" +"\n" +" def __hash__(self):\n" +" l = self.the_list\n" +" result = 98767 - len(l)*555\n" +" for i, el in enumerate(l):\n" +" try:\n" +" result = result + (hash(el) % 9999999) * 1001 + i\n" +" except Exception:\n" +" result = (result % 7777777) + i * 333\n" +" return result" + #: ../../faq/design.rst:530 msgid "" "Note that the hash computation is complicated by the possibility that some " @@ -1089,10 +1260,17 @@ msgstr "" "ordena e retorna. Por exemplo, aqui é como se itera em cima das chaves de um " "dicionário de maneira ordenada::" +#: ../../faq/design.rst:559 +msgid "" +"for key in sorted(mydict):\n" +" ... # do whatever with mydict[key]..." +msgstr "" +"for key in sorted(mydict):\n" +" ... # use mydict[key] conforme quiser..." + #: ../../faq/design.rst:564 msgid "How do you specify and enforce an interface spec in Python?" -msgstr "" -"Como você especifica e aplica uma especificação de interface no Python?" +msgstr "Como você especifica e aplica um spec de interface no Python?" #: ../../faq/design.rst:566 msgid "" @@ -1219,6 +1397,28 @@ msgstr "" "convenientemente emular todos os usos razoáveis das construções ``go`` ou " "``goto`` de C, Fortran e outras linguagens. Por exemplo::" +#: ../../faq/design.rst:620 +msgid "" +"class label(Exception): pass # declare a label\n" +"\n" +"try:\n" +" ...\n" +" if condition: raise label() # goto label\n" +" ...\n" +"except label: # where to goto\n" +" pass\n" +"..." +msgstr "" +"class label(Exception): pass # declara um label\n" +"\n" +"try:\n" +" ...\n" +" if condition: raise label() # goto label\n" +" ...\n" +"except label: # destino do goto\n" +" pass\n" +"..." + #: ../../faq/design.rst:630 msgid "" "This doesn't allow you to jump into the middle of a loop, but that's usually " @@ -1268,12 +1468,26 @@ msgstr "" "Se você estiver tentando criar nomes de caminho do Windows, observe que " "todas as chamadas do sistema do Windows também aceitam barras::" +#: ../../faq/design.rst:651 +msgid "f = open(\"/mydir/file.txt\") # works fine!" +msgstr "f = open(\"/mydir/file.txt\") # funciona normalmente!" + #: ../../faq/design.rst:653 msgid "" "If you're trying to build a pathname for a DOS command, try e.g. one of ::" msgstr "" -"Se você estiver tentando criar um nome de caminho para um comando DOS, " -"tente, por exemplo. um de ::" +"Se você estiver tentando construir um nome de caminho para um comando DOS, " +"tente, por exemplo, algum desses ::" + +#: ../../faq/design.rst:655 +msgid "" +"dir = r\"\\this\\is\\my\\dos\\dir\" \"\\\\\"\n" +"dir = r\"\\this\\is\\my\\dos\\dir\\ \"[:-1]\n" +"dir = \"\\\\this\\\\is\\\\my\\\\dos\\\\dir\\\\\"" +msgstr "" +"dir = r\"\\this\\is\\my\\dos\\dir\" \"\\\\\"\n" +"dir = r\"\\this\\is\\my\\dos\\dir\\ \"[:-1]\n" +"dir = \"\\\\this\\\\is\\\\my\\\\dos\\\\dir\\\\\"" #: ../../faq/design.rst:661 msgid "Why doesn't Python have a \"with\" statement for attribute assignments?" @@ -1290,6 +1504,16 @@ msgstr "" "chamando o código na entrada e na saída do bloco. Algumas linguagens têm uma " "construção desta forma::" +#: ../../faq/design.rst:667 +msgid "" +"with obj:\n" +" a = 1 # equivalent to obj.a = 1\n" +" total = total + 1 # obj.total = obj.total + 1" +msgstr "" +"with obj:\n" +" a = 1 # equivalente a obj.a = 1\n" +" total = total + 1 # obj.total = obj.total + 1" + #: ../../faq/design.rst:671 msgid "In Python, such a construct would be ambiguous." msgstr "Em Python, tal construção seria ambígua." @@ -1324,6 +1548,16 @@ msgstr "" msgid "For instance, take the following incomplete snippet::" msgstr "Por exemplo, pegue o seguinte trecho incompleto::" +#: ../../faq/design.rst:686 +msgid "" +"def foo(a):\n" +" with a:\n" +" print(x)" +msgstr "" +"def foo(a):\n" +" with a:\n" +" print(x)" + #: ../../faq/design.rst:690 msgid "" "The snippet assumes that ``a`` must have a member attribute called ``x``. " @@ -1349,10 +1583,32 @@ msgstr "" "(redução do volume de código) pode, no entanto, ser facilmente alcançado em " "Python por atribuição. Em vez de::" +#: ../../faq/design.rst:699 +msgid "" +"function(args).mydict[index][index].a = 21\n" +"function(args).mydict[index][index].b = 42\n" +"function(args).mydict[index][index].c = 63" +msgstr "" +"function(args).mydict[index][index].a = 21\n" +"function(args).mydict[index][index].b = 42\n" +"function(args).mydict[index][index].c = 63" + #: ../../faq/design.rst:703 msgid "write this::" msgstr "escreva isso::" +#: ../../faq/design.rst:705 +msgid "" +"ref = function(args).mydict[index][index]\n" +"ref.a = 21\n" +"ref.b = 42\n" +"ref.c = 63" +msgstr "" +"ref = function(args).mydict[index][index]\n" +"ref.a = 21\n" +"ref.b = 42\n" +"ref.c = 63" + #: ../../faq/design.rst:710 msgid "" "This also has the side-effect of increasing execution speed because name " @@ -1405,10 +1661,26 @@ msgstr "" "Os dois pontos são obrigatórios primeiramente para melhorar a leitura (um " "dos resultados da linguagem experimental ABC). Considere isso::" +#: ../../faq/design.rst:735 +msgid "" +"if a == b\n" +" print(a)" +msgstr "" +"if a == b\n" +" print(a)" + #: ../../faq/design.rst:738 msgid "versus ::" msgstr "versus ::" +#: ../../faq/design.rst:740 +msgid "" +"if a == b:\n" +" print(a)" +msgstr "" +"if a == b:\n" +" print(a)" + #: ../../faq/design.rst:743 msgid "" "Notice how the second one is slightly easier to read. Notice further how a " @@ -1416,8 +1688,8 @@ msgid "" "English." msgstr "" "Note como a segunda é ligeiramente mais fácil de ler. Note com mais atenção " -"como os dois pontos iniciam o exemplo nessa resposta de perguntas " -"frequentes; é um uso padrão em Português." +"como os dois pontos iniciam o exemplo nessa resposta de FAQ; é um uso padrão " +"em inglês." #: ../../faq/design.rst:746 msgid "" @@ -1443,6 +1715,22 @@ msgstr "" "O Python deixa você adicionar uma vírgula ao final de listas, tuplas e " "dicionários::" +#: ../../faq/design.rst:757 +msgid "" +"[1, 2, 3,]\n" +"('a', 'b', 'c',)\n" +"d = {\n" +" \"A\": [1, 5],\n" +" \"B\": [6, 7], # last trailing comma is optional but good style\n" +"}" +msgstr "" +"[1, 2, 3,]\n" +"('a', 'b', 'c',)\n" +"d = {\n" +" \"A\": [1, 5],\n" +" \"B\": [6, 7], # a vírgula ao final é opcional, mas é bom estilo\n" +"}" + #: ../../faq/design.rst:765 msgid "There are several reasons to allow this." msgstr "Existem várias razões para permitir isso." @@ -1467,6 +1755,22 @@ msgstr "" "Acidentalmente omitir a vírgula pode levar a erros que são difíceis de " "diagnosticar. Por exemplo::" +#: ../../faq/design.rst:775 +msgid "" +"x = [\n" +" \"fee\",\n" +" \"fie\"\n" +" \"foo\",\n" +" \"fum\"\n" +"]" +msgstr "" +"x = [\n" +" \"fee\",\n" +" \"fie\"\n" +" \"foo\",\n" +" \"fum\"\n" +"]" + #: ../../faq/design.rst:782 msgid "" "This list looks like it has four elements, but it actually contains three: " diff --git a/faq/extending.po b/faq/extending.po index ec038aaff..79b6c8c17 100644 --- a/faq/extending.po +++ b/faq/extending.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# mvpetri , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Rogério Araújo , 2021 -# Alexsandro Matias de Almeida , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Alexsandro Matias de Almeida , " -"2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -75,7 +70,7 @@ msgstr "" #: ../../faq/extending.rst:37 msgid "Writing C is hard; are there any alternatives?" -msgstr "A escrita em C é difícil, Há algumas alternativas?" +msgstr "Escrever C é difícil; há alguma alternativa?" #: ../../faq/extending.rst:39 msgid "" @@ -93,6 +88,11 @@ msgid "" "Cython and Pyrex make it possible to write an extension without having to " "learn Python's C API." msgstr "" +"O `Cython `_ e o seu parente `Pyrex `_ são compiladores que aceitam " +"uma forma de Python levemente modificada e geram o código C correspondente. " +"Cython e Pyrex possibilitam escrever extensões sem que seja necessário " +"aprender a usar a API C do Python." #: ../../faq/extending.rst:50 msgid "" @@ -104,6 +104,13 @@ msgid "" "`_ are also alternatives for wrapping C++ " "libraries." msgstr "" +"Se você precisar interagir com alguma biblioteca C ou C++ que não é " +"suportada por nenhuma extensão do Python no momento, você pode tentar " +"envolver os tipos de dados e funções da biblioteca usando uma ferramenta " +"como o `SWIG `_. `SIP `__, `CXX `_ `Boost `_, e `Weave `_ " +"são outras alternativas para criar invólucros de bibliotecas C++." #: ../../faq/extending.rst:61 msgid "How can I execute arbitrary Python statements from C?" @@ -118,10 +125,18 @@ msgid "" "func:`PyRun_String`; see the source for :c:func:`PyRun_SimpleString` in " "``Python/pythonrun.c``." msgstr "" +"A função mais alto-nível para isso é a :c:func:`PyRun_SimpleString`, que " +"recebe como único argumento uma string a ser executada no contexto do módulo " +"``__main__`` e retorna ``0`` para sucesso e ``-1`` quando uma exceção " +"ocorrer (incluindo :exc:`SyntaxError`). Se quiser mais controle, use :c:" +"func:`PyRun_String`; veja o código-fonte de :c:func:`PyRun_SimpleString` em " +"``Python/pythonrun.c``." #: ../../faq/extending.rst:72 msgid "How can I evaluate an arbitrary Python expression from C?" msgstr "" +"Como posso executar e obter o resultado de uma expressão Python arbitrária a " +"partir de C?" #: ../../faq/extending.rst:74 msgid "" @@ -129,6 +144,9 @@ msgid "" "start symbol :c:data:`Py_eval_input`; it parses an expression, evaluates it " "and returns its value." msgstr "" +"Chame a função :c:func:`PyRun_String` da pergunta anterior passando :c:data:" +"`Py_eval_input` como o símbolo de início; ela faz a análise sintática de uma " +"expressão, a executa, e retorna o seu valor." #: ../../faq/extending.rst:80 msgid "How do I extract C values from a Python object?" @@ -141,6 +159,10 @@ msgid "" "specified index. Lists have similar functions, :c:func:`PyList_Size` and :c:" "func:`PyList_GetItem`." msgstr "" +"Depende do tipo do objeto. Se for uma tupla, a :c:func:`PyTuple_Size` " +"retorna o seu comprimento e a :c:func:`PyTuple_GetItem` retorna o item em um " +"determinado índice. Listas têm funções similares, :c:func:`PyList_Size` e :" +"c:func:`PyList_GetItem`." #: ../../faq/extending.rst:87 msgid "" @@ -149,6 +171,10 @@ msgid "" "Note that Python bytes objects may contain null bytes so C's :c:func:`!" "strlen` should not be used." msgstr "" +"Para bytes, a :c:func:`PyBytes_Size` retorna o comprimento e a :c:func:" +"`PyBytes_AsStringAndSize` fornece um ponteiro para o seu valor e o seu " +"comprimento. Note que objetos bytes em Python podem conter bytes nulos, de " +"forma que a :c:func:`!strlen` do C não deve ser usada." #: ../../faq/extending.rst:92 msgid "" @@ -156,6 +182,9 @@ msgid "" "use :c:func:`PyBytes_Check`, :c:func:`PyTuple_Check`, :c:func:" "`PyList_Check`, etc." msgstr "" +"Para testar o tipo de um objeto, primeiramente se certifique de que ele não " +"é ``NULL``, e então use :c:func:`PyBytes_Check`, :c:func:`PyTuple_Check`, :c:" +"func:`PyList_Check`, etc." #: ../../faq/extending.rst:95 msgid "" @@ -166,6 +195,12 @@ msgid "" "as many other useful protocols such as numbers (:c:func:`PyNumber_Index` et " "al.) and mappings in the PyMapping APIs." msgstr "" +"Também existe uma API alto-nível para objetos Python fornecida pela chamada " +"interface \"abstrata\" -- leia ``Include/abstract.h`` para mais detalhes. " +"Ela permite interagir com qualquer tipo de sequência Python usando chamadas " +"como :c:func:`PySequence_Length`, :c:func:`PySequence_GetItem`, etc, além de " +"vários outros protocolos úteis tais como números (:c:func:`PyNumber_Index` e " +"outros) e mapeamentos nas APIs PyMapping." #: ../../faq/extending.rst:104 msgid "How do I use Py_BuildValue() to create a tuple of arbitrary length?" @@ -175,11 +210,11 @@ msgstr "" #: ../../faq/extending.rst:106 msgid "You can't. Use :c:func:`PyTuple_Pack` instead." -msgstr "" +msgstr "Não é possível. Use a função :c:func:`PyTuple_Pack` para isso." #: ../../faq/extending.rst:110 msgid "How do I call an object's method from C?" -msgstr "" +msgstr "Como eu chamo um método de um objeto a partir do C?" #: ../../faq/extending.rst:112 msgid "" @@ -188,6 +223,20 @@ msgid "" "to call, a format string like that used with :c:func:`Py_BuildValue`, and " "the argument values::" msgstr "" +"A função :c:func:`PyObject_CallMethod` pode ser usada para chamar um método " +"arbitrário de um objeto. Os parâmetros são o objeto, o nome do método a ser " +"chamado, uma string de formato como a usada em :c:func:`Py_BuildValue`, e os " +"valores dos argumentos::" + +#: ../../faq/extending.rst:117 +msgid "" +"PyObject *\n" +"PyObject_CallMethod(PyObject *object, const char *method_name,\n" +" const char *arg_format, ...);" +msgstr "" +"PyObject *\n" +"PyObject_CallMethod(PyObject *object, const char *method_name,\n" +" const char *arg_format, ...);" #: ../../faq/extending.rst:121 msgid "" @@ -195,12 +244,35 @@ msgid "" "defined. You are responsible for eventually :c:func:`Py_DECREF`\\ 'ing the " "return value." msgstr "" +"Isso funciona para qualquer objeto que tenha métodos -- sejam eles embutidos " +"ou definidos por usuário. Você fica então responsável por chamar :c:func:" +"`Py_DECREF` no valor de retorno." #: ../../faq/extending.rst:124 msgid "" "To call, e.g., a file object's \"seek\" method with arguments 10, 0 " "(assuming the file object pointer is \"f\")::" msgstr "" +"Para chamar, por exemplo, o método \"seek\" de um objeto arquivo com " +"argumentos 10, 0 (presumindo que \"f\" é o ponteiro para o objeto arquivo)::" + +#: ../../faq/extending.rst:127 +msgid "" +"res = PyObject_CallMethod(f, \"seek\", \"(ii)\", 10, 0);\n" +"if (res == NULL) {\n" +" ... an exception occurred ...\n" +"}\n" +"else {\n" +" Py_DECREF(res);\n" +"}" +msgstr "" +"res = PyObject_CallMethod(f, \"seek\", \"(ii)\", 10, 0);\n" +"if (res == NULL) {\n" +" ... ocorreu uma exceção ...\n" +"}\n" +"else {\n" +" Py_DECREF(res);\n" +"}" #: ../../faq/extending.rst:135 msgid "" @@ -209,12 +281,18 @@ msgid "" "format, and to call a function with one argument, surround the argument in " "parentheses, e.g. \"(i)\"." msgstr "" +"Note que a função :c:func:`PyObject_CallObject` *sempre* recebe os " +"argumentos da chamada como uma tupla, de forma que para chamar uma função " +"sem argumentos deve-se passar \"()\" como formato, e para chamar uma função " +"com 1 argumento, coloque-o entre parênteses, por exemplo \"(i)\"." #: ../../faq/extending.rst:142 msgid "" "How do I catch the output from PyErr_Print() (or anything that prints to " "stdout/stderr)?" msgstr "" +"Como posso capturar a saída da função PyErr_Print() (ou qualquer outra coisa " +"que escreva para stdout/stderr)?" #: ../../faq/extending.rst:144 msgid "" @@ -223,22 +301,82 @@ msgid "" "print_error, or just allow the standard traceback mechanism to work. Then, " "the output will go wherever your ``write()`` method sends it." msgstr "" +"Com código Python, defina um objeto que suporte o método ``write()``. " +"Atribua esse objeto a :data:`sys.stdout` e :data:`sys.stderr`. Chame " +"print_error, or simplesmente deixe o mecanismo padrão de traceback " +"acontecer. Assim, a saída irá para onde quer que o seu método ``write()`` a " +"envie." #: ../../faq/extending.rst:149 msgid "The easiest way to do this is to use the :class:`io.StringIO` class:" -msgstr "" +msgstr "O jeito mais fácil de fazer isso é usar a classe :class:`io.StringIO`:" + +#: ../../faq/extending.rst:151 +msgid "" +">>> import io, sys\n" +">>> sys.stdout = io.StringIO()\n" +">>> print('foo')\n" +">>> print('hello world!')\n" +">>> sys.stderr.write(sys.stdout.getvalue())\n" +"foo\n" +"hello world!" +msgstr "" +">>> import io, sys\n" +">>> sys.stdout = io.StringIO()\n" +">>> print('foo')\n" +">>> print('hello world!')\n" +">>> sys.stderr.write(sys.stdout.getvalue())\n" +"foo\n" +"hello world!" #: ../../faq/extending.rst:161 msgid "A custom object to do the same would look like this:" msgstr "Um objeto personalizado para fazer a mesma coisa seria esse:" +#: ../../faq/extending.rst:163 +msgid "" +">>> import io, sys\n" +">>> class StdoutCatcher(io.TextIOBase):\n" +"... def __init__(self):\n" +"... self.data = []\n" +"... def write(self, stuff):\n" +"... self.data.append(stuff)\n" +"...\n" +">>> import sys\n" +">>> sys.stdout = StdoutCatcher()\n" +">>> print('foo')\n" +">>> print('hello world!')\n" +">>> sys.stderr.write(''.join(sys.stdout.data))\n" +"foo\n" +"hello world!" +msgstr "" +">>> import io, sys\n" +">>> class StdoutCatcher(io.TextIOBase):\n" +"... def __init__(self):\n" +"... self.data = []\n" +"... def write(self, stuff):\n" +"... self.data.append(stuff)\n" +"...\n" +">>> import sys\n" +">>> sys.stdout = StdoutCatcher()\n" +">>> print('foo')\n" +">>> print('hello world!')\n" +">>> sys.stderr.write(''.join(sys.stdout.data))\n" +"foo\n" +"hello world!" + #: ../../faq/extending.rst:182 msgid "How do I access a module written in Python from C?" -msgstr "" +msgstr "Como faço para acessar a partir do C um módulo escrito em Python?" #: ../../faq/extending.rst:184 msgid "You can get a pointer to the module object as follows::" msgstr "" +"Você pode obter um pointeiro para o objeto de módulo da seguinte maneira::" + +#: ../../faq/extending.rst:186 +msgid "module = PyImport_ImportModule(\"\");" +msgstr "module = PyImport_ImportModule(\"\");" #: ../../faq/extending.rst:188 msgid "" @@ -248,22 +386,35 @@ msgid "" "module into any namespace -- it only ensures it has been initialized and is " "stored in :data:`sys.modules`." msgstr "" +"Se o módulo ainda não foi importado (isto é, ainda não aparece no :data:`sys." +"modules`), essa função vai inicializar o módulo; caso contrário, ela vai " +"simplesmente retornar o valor de ``sys.modules[\"\"]``. Note " +"que ela não adiciona o módulo a nenhum espaço de nomes -- ela simplesmente " +"garante que ele foi inicializado e colocado no :data:`sys.modules`." #: ../../faq/extending.rst:194 msgid "" "You can then access the module's attributes (i.e. any name defined in the " "module) as follows::" msgstr "" +"Você pode então acessar os atributos do módulo (isto é, qualquer nome " +"definido no módulo) assim::" + +#: ../../faq/extending.rst:197 +msgid "attr = PyObject_GetAttrString(module, \"\");" +msgstr "attr = PyObject_GetAttrString(module, \"\");" #: ../../faq/extending.rst:199 msgid "" "Calling :c:func:`PyObject_SetAttrString` to assign to variables in the " "module also works." msgstr "" +"Chamar :c:func:`PyObject_SetAttrString` para definir variáveis no módulo " +"também funciona." #: ../../faq/extending.rst:204 msgid "How do I interface to C++ objects from Python?" -msgstr "" +msgstr "Como posso interagir com objetos C++ a partir do Python?" #: ../../faq/extending.rst:206 msgid "" @@ -274,14 +425,20 @@ msgid "" "building a new Python type around a C structure (pointer) type will also " "work for C++ objects." msgstr "" +"Dependendo das suas necessidades, há diversas abordagens. Para fazer isso " +"manualmente, comece lendo :ref:`o documento \"Estendendo e Incorporando\" " +"`. Note que, para o sistema Python em tempo de execução, " +"não há muita diferença entre C e C++ -- de forma que a estratégia de " +"construir um novo tipo Python ao redor de uma estrutura C (ou ponteiro para " +"uma) também funciona para objetos C++." #: ../../faq/extending.rst:212 msgid "For C++ libraries, see :ref:`c-wrapper-software`." -msgstr "" +msgstr "Para bibliotecas C++, veja :ref:`c-wrapper-software`." #: ../../faq/extending.rst:216 msgid "I added a module using the Setup file and the make fails; why?" -msgstr "" +msgstr "Adicionei um módulo usando o arquivo de Setup e o make falha; por quê?" #: ../../faq/extending.rst:218 msgid "" @@ -289,51 +446,83 @@ msgid "" "fails. (Fixing this requires some ugly shell script hackery, and this bug " "is so minor that it doesn't seem worth the effort.)" msgstr "" +"O Setup deve terminar com uma quebra de linha; se não houver uma quebra de " +"linha no final, o processo de compilação falha. (Consertar isso requer umas " +"gambiarras feias em shell script, e esse bug é tão pequeno que o esforço não " +"parece valer a pena.)" #: ../../faq/extending.rst:224 msgid "How do I debug an extension?" -msgstr "" +msgstr "Como eu depuro uma extensão?" #: ../../faq/extending.rst:226 msgid "" "When using GDB with dynamically loaded extensions, you can't set a " "breakpoint in your extension until your extension is loaded." msgstr "" +"Ao usar o GDB com extensões carregadas dinamicamente, você não consegue " +"definir um ponto de interrupção antes da sua extensão ser carregada." #: ../../faq/extending.rst:229 msgid "In your ``.gdbinit`` file (or interactively), add the command:" msgstr "" +"No seu arquivo ``.gdbinit`` (ou então interativamente), adicione o comando:" + +#: ../../faq/extending.rst:231 +msgid "br _PyImport_LoadDynamicModule" +msgstr "br _PyImport_LoadDynamicModule" #: ../../faq/extending.rst:235 msgid "Then, when you run GDB:" +msgstr "Então, ao executar o GDB:" + +#: ../../faq/extending.rst:237 +msgid "" +"$ gdb /local/bin/python\n" +"gdb) run myscript.py\n" +"gdb) continue # repeat until your extension is loaded\n" +"gdb) finish # so that your extension is loaded\n" +"gdb) br myfunction.c:50\n" +"gdb) continue" msgstr "" +"$ gdb /local/bin/python\n" +"gdb) run myscript.py\n" +"gdb) continue # repita até que a sua extensão seja carregada\n" +"gdb) finish # para que a sua extensão seja carregada\n" +"gdb) br myfunction.c:50\n" +"gdb) continue" #: ../../faq/extending.rst:247 msgid "" "I want to compile a Python module on my Linux system, but some files are " "missing. Why?" msgstr "" +"Quero compilar um módulo Python no meu sistema Linux, mas alguns arquivos " +"estão faltando. Por quê?" #: ../../faq/extending.rst:249 msgid "" -"Most packaged versions of Python don't include the :file:`/usr/lib/python2." -"{x}/config/` directory, which contains various files required for compiling " +"Most packaged versions of Python omit some files required for compiling " "Python extensions." msgstr "" +"A maioria das versões empacotadas de Python omitem alguns arquivos " +"necessários para compilar extensões do Python." -#: ../../faq/extending.rst:253 -msgid "For Red Hat, install the python-devel RPM to get the necessary files." +#: ../../faq/extending.rst:252 +msgid "For Red Hat, install the python3-devel RPM to get the necessary files." msgstr "" +"Em sistemas Red Hat, instale o RPM python3-devel para obter os arquivos " +"necessários." -#: ../../faq/extending.rst:255 -msgid "For Debian, run ``apt-get install python-dev``." -msgstr "" +#: ../../faq/extending.rst:254 +msgid "For Debian, run ``apt-get install python3-dev``." +msgstr "Para Debian, execute ``apt-get install python3-dev``." -#: ../../faq/extending.rst:258 +#: ../../faq/extending.rst:257 msgid "How do I tell \"incomplete input\" from \"invalid input\"?" -msgstr "" +msgstr "Como posso distinguir \"entrada incompleta\" de \"entrada inválida\"?" -#: ../../faq/extending.rst:260 +#: ../../faq/extending.rst:259 msgid "" "Sometimes you want to emulate the Python interactive interpreter's behavior, " "where it gives you a continuation prompt when the input is incomplete (e.g. " @@ -341,14 +530,22 @@ msgid "" "parentheses or triple string quotes), but it gives you a syntax error " "message immediately when the input is invalid." msgstr "" +"Às vezes você quer emular o comportamento do interpretador interativo do " +"Python, que te dá um prompt de continuação quando a entrada está incompleta " +"(por exemplo, você digitou o início de uma instrução \"if\", ou então não " +"fechou os parênteses ou aspas triplas), mas que te dá um mensagem de erro de " +"sintaxe imediatamente se a entrada for inválida." -#: ../../faq/extending.rst:266 +#: ../../faq/extending.rst:265 msgid "" "In Python you can use the :mod:`codeop` module, which approximates the " "parser's behavior sufficiently. IDLE uses this, for example." msgstr "" +"Em Python você pode usar o módulo :mod:`codeop`, que aproxima " +"suficientemente o comportamento do analisador sintático. Por exemplo, o " +"IDLE o usa." -#: ../../faq/extending.rst:269 +#: ../../faq/extending.rst:268 msgid "" "The easiest way to do it in C is to call :c:func:`PyRun_InteractiveLoop` " "(perhaps in a separate thread) and let the Python interpreter handle the " @@ -356,33 +553,52 @@ msgid "" "to point at your custom input function. See ``Modules/readline.c`` and " "``Parser/myreadline.c`` for more hints." msgstr "" +"Em C, a forma mais fácil de fazer isso é chamar :c:func:" +"`PyRun_InteractiveLoop` (talvez em uma thread separada) e deixar o " +"interpretador do Python tratar a entrada para você. Você tambémm pode " +"apontar o :c:func:`PyOS_ReadlineFunctionPointer` para a sua função de " +"entrada personalizada. Consulte ``Modules/readline.c`` e ``Parser/myreadline." +"c`` para mais dicas." -#: ../../faq/extending.rst:276 +#: ../../faq/extending.rst:275 msgid "How do I find undefined g++ symbols __builtin_new or __pure_virtual?" msgstr "" +"Como encontro os símbolos __builtin_new ou __pure_virtual não-definidos no g+" +"+?" -#: ../../faq/extending.rst:278 +#: ../../faq/extending.rst:277 msgid "" "To dynamically load g++ extension modules, you must recompile Python, relink " "it using g++ (change LINKCC in the Python Modules Makefile), and link your " "extension module using g++ (e.g., ``g++ -shared -o mymodule.so mymodule.o``)." msgstr "" +"Para carregar dinamicamente módulos de extensão feitos com g++, você precisa " +"recompilar o Python, usando o g++ como ligador (mude a constante LINKCC no " +"Makefile dos módulos de extensão do Python), e use o g++ também como ligador " +"do seu módulo (por exemplo, ``g++ -shared -o mymodule.so mymodule.o``)." -#: ../../faq/extending.rst:284 +#: ../../faq/extending.rst:283 msgid "" "Can I create an object class with some methods implemented in C and others " "in Python (e.g. through inheritance)?" msgstr "" +"Posso criar uma classe de objetos com alguns métodos implementados em C e " +"outros em Python (por exemplo, via herança)?" -#: ../../faq/extending.rst:286 +#: ../../faq/extending.rst:285 msgid "" "Yes, you can inherit from built-in classes such as :class:`int`, :class:" "`list`, :class:`dict`, etc." msgstr "" +"Sim, você pode herdar de classes embutidas como :class:`int`, :class:" +"`list`, :class:`dict` etc." -#: ../../faq/extending.rst:289 +#: ../../faq/extending.rst:288 msgid "" "The Boost Python Library (BPL, https://www.boost.org/libs/python/doc/index." "html) provides a way of doing this from C++ (i.e. you can inherit from an " "extension class written in C++ using the BPL)." msgstr "" +"A Boost Python Library (BPL, https://www.boost.org/libs/python/doc/index." +"html) fornece uma forma de fazer isso a partir do C++ (quer dizer, você " +"consegue herdar de uma classe de extensão escrita em C++ usando a BPL)." diff --git a/faq/general.po b/faq/general.po index 35065c169..c6dcc36df 100644 --- a/faq/general.po +++ b/faq/general.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Bruno Leuenroth , 2021 -# Nicolas Evangelista, 2022 -# Vitor Buxbaum Orlandi, 2023 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -219,7 +214,7 @@ msgid "" "would be foolish to write an Amoeba-specific language, so I decided that I " "needed a language that was generally extensible." msgstr "" -"Percebi que uma linguagem de script com uma sintaxe semelhante a do ABC, mas " +"Percebi que uma linguagem de script com uma sintaxe semelhante a da ABC, mas " "com acesso às chamadas do sistema Amoeba, preencheria a necessidade. Percebi " "também que seria uma boa escrever uma linguagem específica para o Amoeba, " "então, decidi que precisava de uma linguagem realmente extensível." @@ -691,17 +686,14 @@ msgstr "" #: ../../faq/general.rst:311 msgid "" "The latest stable releases can always be found on the `Python download page " -"`_. There are two production-ready " -"versions of Python: 2.x and 3.x. The recommended version is 3.x, which is " -"supported by most widely used libraries. Although 2.x is still widely used, " -"`it is not maintained anymore `_." -msgstr "" -"As últimas versões estáveis ​​sempre podem ser encontradas na `página de " -"download do Python `_. Existem duas " -"versões prontas para produção do Python: 2.x e 3.x. A versão recomendada é 3." -"x, que é suportada pelas bibliotecas mais usadas. Embora 2.x ainda seja " -"amplamente utilizado, `não é mais mantido `_." +"`_. Python 3.x is the recommended version " +"and supported by most widely used libraries. Python 2.x :pep:`is not " +"maintained anymore <373>`." +msgstr "" +"As últimas versões estáveis podem sempre ser encontradas na `página de " +"download do Python `_. O Python 3.x é a " +"versão recomendada e suportada pela maioria das bibliotecas amplamente " +"utilizadas. Python 2.x :pep:`não é mais mantido <373>`." #: ../../faq/general.rst:318 msgid "How many people are using Python?" @@ -913,6 +905,58 @@ msgstr "" "outra janela. Se eles não conseguirem se lembrar dos métodos de uma lista, " "eles podem fazer algo assim::" +#: ../../faq/general.rst:412 +msgid "" +">>> L = []\n" +">>> dir(L)\n" +"['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',\n" +"'__dir__', '__doc__', '__eq__', '__format__', '__ge__',\n" +"'__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__',\n" +"'__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__',\n" +"'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',\n" +"'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',\n" +"'__sizeof__', '__str__', '__subclasshook__', 'append', 'clear',\n" +"'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',\n" +"'reverse', 'sort']\n" +">>> [d for d in dir(L) if '__' not in d]\n" +"['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', " +"'remove', 'reverse', 'sort']\n" +"\n" +">>> help(L.append)\n" +"Help on built-in function append:\n" +"\n" +"append(...)\n" +" L.append(object) -> None -- append object to end\n" +"\n" +">>> L.append(1)\n" +">>> L\n" +"[1]" +msgstr "" +">>> L = []\n" +">>> dir(L)\n" +"['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',\n" +"'__dir__', '__doc__', '__eq__', '__format__', '__ge__',\n" +"'__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__',\n" +"'__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__',\n" +"'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',\n" +"'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',\n" +"'__sizeof__', '__str__', '__subclasshook__', 'append', 'clear',\n" +"'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',\n" +"'reverse', 'sort']\n" +">>> [d for d in dir(L) if '__' not in d]\n" +"['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', " +"'remove', 'reverse', 'sort']\n" +"\n" +">>> help(L.append)\n" +"Help on built-in function append:\n" +"\n" +"append(...)\n" +" L.append(object) -> None -- append object to end\n" +"\n" +">>> L.append(1)\n" +">>> L\n" +"[1]" + #: ../../faq/general.rst:436 msgid "" "With the interpreter, documentation is never far from the student as they " diff --git a/faq/gui.po b/faq/gui.po index 6b5408f4f..77ebedabf 100644 --- a/faq/gui.po +++ b/faq/gui.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Italo Penaforte , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -125,9 +122,9 @@ msgstr "" "Em plataformas diferentes do Windows, sim, e você nem precisa de threads! " "Mas você terá que reestruturar seu código de E/S um pouco. O Tk tem o " "equivalente à chamada :c:func:`!XtAddInput` do Xt, que permite que você " -"registre uma função de retorno de chamada que será chamada a partir do loop " -"principal do Tk quando E/S é possível em um descritor de arquivo. Consulte :" -"ref:`tkinter-file-handlers`." +"registre uma função de retorno de chamada que será chamada a partir do laço " +"de repetição principal do Tk quando E/S é possível em um descritor de " +"arquivo. Consulte :ref:`tkinter-file-handlers`." #: ../../faq/gui.rst:64 msgid "I can't get key bindings to work in Tkinter: why?" diff --git a/faq/index.po b/faq/index.po index 52244246e..d4023450d 100644 --- a/faq/index.po +++ b/faq/index.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Ruan Aragão , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Ruan Aragão , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/faq/installed.po b/faq/installed.po index b24c418c7..e23bfca95 100644 --- a/faq/installed.po +++ b/faq/installed.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Tiago Henrique , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Bruno Leuenroth , 2021 -# Rafael Fontenelle , 2022 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Rafael Fontenelle , 2022\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/faq/library.po b/faq/library.po index 9b7ec0129..5389ed89d 100644 --- a/faq/library.po +++ b/faq/library.po @@ -1,32 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Adson Rodrigues , 2021 -# Alexandre B A Villares, 2021 -# Mariana Costa , 2021 -# a76d6fb6142d7607ab0526dcbddb02d7_7bf0da0 <3b5fb0f281c8dfb4c0170f2ee2a6cfcf_843623>, 2021 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -109,6 +102,14 @@ msgstr "" "módulos escritos em C e vinculados ao interpretador; para obter uma dessas " "listas, digite::" +#: ../../faq/library.rst:42 +msgid "" +"import sys\n" +"print(sys.builtin_module_names)" +msgstr "" +"import sys\n" +"print(sys.builtin_module_names)" + #: ../../faq/library.rst:47 msgid "How do I make a Python script executable on Unix?" msgstr "Como tornar um script Python executável no Unix?" @@ -139,6 +140,10 @@ msgstr "" "A segunda coisa pode ser feita de várias maneiras. A maneira mais direta é " "escrever ::" +#: ../../faq/library.rst:59 +msgid "#!/usr/local/bin/python" +msgstr "#!/usr/local/bin/python" + #: ../../faq/library.rst:61 msgid "" "as the very first line of your file, using the pathname for where the Python " @@ -159,6 +164,10 @@ msgstr "" "Unix suportam o seguinte, presumindo que o interpretador Python esteja em um " "diretório no :envvar:`PATH` do usuário::" +#: ../../faq/library.rst:69 +msgid "#!/usr/bin/env python" +msgstr "#!/usr/bin/env python" + #: ../../faq/library.rst:71 msgid "" "*Don't* do this for CGI scripts. The :envvar:`PATH` variable for CGI " @@ -179,6 +188,18 @@ msgstr "" "program:`/usr/bin/env` falha; ou não há nenhum programa env. Nesse caso, " "você pode tentar o seguinte hack (graças a Alex Rezinsky):" +#: ../../faq/library.rst:79 +msgid "" +"#! /bin/sh\n" +"\"\"\":\"\n" +"exec python $0 ${1+\"$@\"}\n" +"\"\"\"" +msgstr "" +"#! /bin/sh\n" +"\"\"\":\"\n" +"exec python $0 ${1+\"$@\"}\n" +"\"\"\"" + #: ../../faq/library.rst:86 msgid "" "The minor disadvantage is that this defines the script's __doc__ string. " @@ -187,6 +208,10 @@ msgstr "" "Uma pequena desvantagem é que isso define o script's __doc__ string. " "Entretanto, você pode corrigir isso adicionando ::" +#: ../../faq/library.rst:89 +msgid "__doc__ = \"\"\"...Whatever...\"\"\"" +msgstr "__doc__ = \"\"\"...Alguma coisa...\"\"\"" + #: ../../faq/library.rst:94 msgid "Is there a curses/termcap package for Python?" msgstr "Existe um pacote de curses/termcap para Python?" @@ -243,10 +268,22 @@ msgstr "" "O maior problema é que o manipulador de sinal é declarado com uma lista de " "argumentos incorretos. Isso é chamado como ::" +#: ../../faq/library.rst:123 +msgid "handler(signum, frame)" +msgstr "manipulador(num_sinal, quadro)" + #: ../../faq/library.rst:125 msgid "so it should be declared with two parameters::" msgstr "portanto, isso deve ser declarado com dois parâmetros::" +#: ../../faq/library.rst:127 +msgid "" +"def handler(signum, frame):\n" +" ..." +msgstr "" +"def manipulador(num_sinal, quadro):\n" +" ..." + #: ../../faq/library.rst:132 msgid "Common tasks" msgstr "Tarefas comuns" @@ -295,6 +332,14 @@ msgstr "" msgid "The \"global main logic\" of your program may be as simple as ::" msgstr "A lógica principal do seu programa pode tão simples quanto ::" +#: ../../faq/library.rst:154 +msgid "" +"if __name__ == \"__main__\":\n" +" main_logic()" +msgstr "" +"if __name__ == \"__main__\":\n" +" main_logic()" + #: ../../faq/library.rst:157 msgid "at the bottom of the main module of your program." msgstr "no botão do módulo principal do seus programa." @@ -328,6 +373,14 @@ msgstr "" "Os \"módulos de suporte\" que não se destinam a ser o módulo principal de um " "programa podem incluir um autoteste do módulo. ::" +#: ../../faq/library.rst:170 +msgid "" +"if __name__ == \"__main__\":\n" +" self_test()" +msgstr "" +"if __name__ == \"__main__\":\n" +" self_test()" + #: ../../faq/library.rst:173 msgid "" "Even programs that interact with complex external interfaces may be tested " @@ -406,6 +459,32 @@ msgstr "" "Uma solução simples é adicionar um tempo de espera no final do programa até " "que todos os threads sejam concluídos::" +#: ../../faq/library.rst:253 +msgid "" +"import threading, time\n" +"\n" +"def thread_task(name, n):\n" +" for i in range(n):\n" +" print(name, i)\n" +"\n" +"for i in range(10):\n" +" T = threading.Thread(target=thread_task, args=(str(i), i))\n" +" T.start()\n" +"\n" +"time.sleep(10) # <---------------------------!" +msgstr "" +"import threading, time\n" +"\n" +"def thread_task(name, n):\n" +" for i in range(n):\n" +" print(name, i)\n" +"\n" +"for i in range(10):\n" +" T = threading.Thread(target=thread_task, args=(str(i), i))\n" +" T.start()\n" +"\n" +"time.sleep(10) # <---------------------------!" + #: ../../faq/library.rst:265 msgid "" "But now (on many platforms) the threads don't run in parallel, but appear to " @@ -423,6 +502,30 @@ msgstr "" "Uma solução simples é adicionar um pequeno tempo de espera no início da " "função::" +#: ../../faq/library.rst:271 +msgid "" +"def thread_task(name, n):\n" +" time.sleep(0.001) # <--------------------!\n" +" for i in range(n):\n" +" print(name, i)\n" +"\n" +"for i in range(10):\n" +" T = threading.Thread(target=thread_task, args=(str(i), i))\n" +" T.start()\n" +"\n" +"time.sleep(10)" +msgstr "" +"def thread_task(name, n):\n" +" time.sleep(0.001) # <--------------------!\n" +" for i in range(n):\n" +" print(name, i)\n" +"\n" +"for i in range(10):\n" +" T = threading.Thread(target=thread_task, args=(str(i), i))\n" +" T.start()\n" +"\n" +"time.sleep(10)" + #: ../../faq/library.rst:282 msgid "" "Instead of trying to guess a good delay value for :func:`time.sleep`, it's " @@ -470,10 +573,114 @@ msgstr "" msgid "Here's a trivial example::" msgstr "Aqui está um exemplo simples::" +#: ../../faq/library.rst:304 +msgid "" +"import threading, queue, time\n" +"\n" +"# The worker thread gets jobs off the queue. When the queue is empty, it\n" +"# assumes there will be no more work and exits.\n" +"# (Realistically workers will run until terminated.)\n" +"def worker():\n" +" print('Running worker')\n" +" time.sleep(0.1)\n" +" while True:\n" +" try:\n" +" arg = q.get(block=False)\n" +" except queue.Empty:\n" +" print('Worker', threading.current_thread(), end=' ')\n" +" print('queue empty')\n" +" break\n" +" else:\n" +" print('Worker', threading.current_thread(), end=' ')\n" +" print('running with argument', arg)\n" +" time.sleep(0.5)\n" +"\n" +"# Create queue\n" +"q = queue.Queue()\n" +"\n" +"# Start a pool of 5 workers\n" +"for i in range(5):\n" +" t = threading.Thread(target=worker, name='worker %i' % (i+1))\n" +" t.start()\n" +"\n" +"# Begin adding work to the queue\n" +"for i in range(50):\n" +" q.put(i)\n" +"\n" +"# Give threads time to run\n" +"print('Main thread sleeping')\n" +"time.sleep(5)" +msgstr "" +"import threading, queue, time\n" +"\n" +"# A thread do worker obtém a tarefa da fila. Quando a fila está vazia,\n" +"# ela presume que não haverá mais tarefas e encerra.\n" +"# (Realisticamente, workers trabalharão até serem encerrados.)\n" +"def worker():\n" +" print('Running worker')\n" +" time.sleep(0.1)\n" +" while True:\n" +" try:\n" +" arg = q.get(block=False)\n" +" except queue.Empty:\n" +" print('Worker', threading.current_thread(), end=' ')\n" +" print('queue empty')\n" +" break\n" +" else:\n" +" print('Worker', threading.current_thread(), end=' ')\n" +" print('running with argument', arg)\n" +" time.sleep(0.5)\n" +"\n" +"# Cria a fila\n" +"q = queue.Queue()\n" +"\n" +"# Inicia um pool de 5 workers\n" +"for i in range(5):\n" +" t = threading.Thread(target=worker, name='worker %i' % (i+1))\n" +" t.start()\n" +"\n" +"# Começa a adicionar tarefa à fila\n" +"for i in range(50):\n" +" q.put(i)\n" +"\n" +"# Dá às threads tempo para executar\n" +"print('Main thread sleeping')\n" +"time.sleep(5)" + #: ../../faq/library.rst:340 msgid "When run, this will produce the following output:" msgstr "Quando executado, isso produzirá a seguinte saída:" +#: ../../faq/library.rst:342 +msgid "" +"Running worker\n" +"Running worker\n" +"Running worker\n" +"Running worker\n" +"Running worker\n" +"Main thread sleeping\n" +"Worker running with argument 0\n" +"Worker running with argument 1\n" +"Worker running with argument 2\n" +"Worker running with argument 3\n" +"Worker running with argument 4\n" +"Worker running with argument 5\n" +"..." +msgstr "" +"Running worker\n" +"Running worker\n" +"Running worker\n" +"Running worker\n" +"Running worker\n" +"Main thread sleeping\n" +"Worker running with argument 0\n" +"Worker running with argument 1\n" +"Worker running with argument 2\n" +"Worker running with argument 3\n" +"Worker running with argument 4\n" +"Worker running with argument 5\n" +"..." + #: ../../faq/library.rst:358 msgid "" "Consult the module's documentation for more details; the :class:`~queue." @@ -523,10 +730,48 @@ msgstr "" "Por exemplo, as seguintes operações são todas atômicas (L, L1, L2 são " "listas, D, D1, D2 são dicionários, x, y são objetos, i, j são inteiros)::" +#: ../../faq/library.rst:380 +msgid "" +"L.append(x)\n" +"L1.extend(L2)\n" +"x = L[i]\n" +"x = L.pop()\n" +"L1[i:j] = L2\n" +"L.sort()\n" +"x = y\n" +"x.field = y\n" +"D[x] = y\n" +"D1.update(D2)\n" +"D.keys()" +msgstr "" +"L.append(x)\n" +"L1.extend(L2)\n" +"x = L[i]\n" +"x = L.pop()\n" +"L1[i:j] = L2\n" +"L.sort()\n" +"x = y\n" +"x.field = y\n" +"D[x] = y\n" +"D1.update(D2)\n" +"D.keys()" + #: ../../faq/library.rst:392 msgid "These aren't::" msgstr "Esses não são::" +#: ../../faq/library.rst:394 +msgid "" +"i = i+1\n" +"L.append(L[-1])\n" +"L[i] = L[j]\n" +"D[x] = D[x] + 1" +msgstr "" +"i = i+1\n" +"L.append(L[-1])\n" +"L[i] = L[j]\n" +"D[x] = D[x] + 1" + #: ../../faq/library.rst:399 msgid "" "Operations that replace other objects may invoke those other objects' :meth:" @@ -733,7 +978,7 @@ msgstr "" "que em volumes NTFS do Windows, ele não copia `fluxos de dados alternativos " "`_ nem " "`forks de recursos `__ em " -"volumes HFS+ do macOS, embora ambos sejam raramente usados ​​agora. Ele também " +"volumes HFS+ do macOS, embora ambos sejam raramente usados agora. Ele também " "não copia permissões de arquivo e metadados, embora usar :func:`shutil." "copy2` em vez disso preserve a maioria (embora não todos) deles." @@ -759,6 +1004,20 @@ msgstr "" "Por exemplo, o código a seguir lê dois inteiros de 2 bytes e um inteiro de 4 " "bytes no formato big-endian de um arquivo:" +#: ../../faq/library.rst:512 +msgid "" +"import struct\n" +"\n" +"with open(filename, \"rb\") as f:\n" +" s = f.read(8)\n" +" x, y, z = struct.unpack(\">hhl\", s)" +msgstr "" +"import struct\n" +"\n" +"with open(filename, \"rb\") as f:\n" +" s = f.read(8)\n" +" x, y, z = struct.unpack(\">hhl\", s)" + #: ../../faq/library.rst:518 msgid "" "The '>' in the format string forces big-endian data; the letter 'h' reads " @@ -876,6 +1135,16 @@ msgstr "" "exemplo, você pode confundir módulos de extensão tentando fazer E/S). Se " "for, use :func:`os.close`::" +#: ../../faq/library.rst:655 +msgid "" +"os.close(stdin.fileno())\n" +"os.close(stdout.fileno())\n" +"os.close(stderr.fileno())" +msgstr "" +"os.close(stdin.fileno())\n" +"os.close(stdout.fileno())\n" +"os.close(stderr.fileno())" + #: ../../faq/library.rst:659 msgid "Or you can use the numeric constants 0, 1 and 2, respectively." msgstr "Ou você pode usar as constantes numéricas 0, 1 e 2, respectivamente." @@ -934,6 +1203,42 @@ msgstr "" "Aqui está um remetente de e-mail interativo muito simples. Este método " "funcionará em qualquer host que suporte o protocolo SMTP. ::" +#: ../../faq/library.rst:695 +msgid "" +"import sys, smtplib\n" +"\n" +"fromaddr = input(\"From: \")\n" +"toaddrs = input(\"To: \").split(',')\n" +"print(\"Enter message, end with ^D:\")\n" +"msg = ''\n" +"while True:\n" +" line = sys.stdin.readline()\n" +" if not line:\n" +" break\n" +" msg += line\n" +"\n" +"# The actual mail send\n" +"server = smtplib.SMTP('localhost')\n" +"server.sendmail(fromaddr, toaddrs, msg)\n" +"server.quit()" +msgstr "" +"import sys, smtplib\n" +"\n" +"fromaddr = input(\"From: \")\n" +"toaddrs = input(\"To: \").split(',')\n" +"print(\"Enter message, end with ^D:\")\n" +"msg = ''\n" +"while True:\n" +" line = sys.stdin.readline()\n" +" if not line:\n" +" break\n" +" msg += line\n" +"\n" +"# O envio de e-mail real\n" +"server = smtplib.SMTP('localhost')\n" +"server.sendmail(fromaddr, toaddrs, msg)\n" +"server.quit()" + #: ../../faq/library.rst:712 msgid "" "A Unix-only alternative uses sendmail. The location of the sendmail program " @@ -946,6 +1251,34 @@ msgstr "" "``/usr/sbin/sendmail``. A página de manual do sendmail vai ajudar você. Aqui " "está um código de exemplo::" +#: ../../faq/library.rst:717 +msgid "" +"import os\n" +"\n" +"SENDMAIL = \"/usr/sbin/sendmail\" # sendmail location\n" +"p = os.popen(\"%s -t -i\" % SENDMAIL, \"w\")\n" +"p.write(\"To: receiver@example.com\\n\")\n" +"p.write(\"Subject: test\\n\")\n" +"p.write(\"\\n\") # blank line separating headers from body\n" +"p.write(\"Some text\\n\")\n" +"p.write(\"some more text\\n\")\n" +"sts = p.close()\n" +"if sts != 0:\n" +" print(\"Sendmail exit status\", sts)" +msgstr "" +"import os\n" +"\n" +"SENDMAIL = \"/usr/sbin/sendmail\" # local do sendmail\n" +"p = os.popen(\"%s -t -i\" % SENDMAIL, \"w\")\n" +"p.write(\"To: receiver@example.com\\n\")\n" +"p.write(\"Subject: teste\\n\")\n" +"p.write(\"\\n\") # linha vazia separando cabeçalho do corpo\n" +"p.write(\"Algum texto\\n\")\n" +"p.write(\"mais um pouco de texto\\n\")\n" +"sts = p.close()\n" +"if sts != 0:\n" +" print(\"Status de saída do sendmail\", sts)" + #: ../../faq/library.rst:732 msgid "How do I avoid blocking in the connect() method of a socket?" msgstr "Como evito um bloqueio no método connect() de um soquete?" @@ -1069,6 +1402,14 @@ msgstr "" "O módulo padrão :mod:`random` implementa um gerador de números aleatórios. O " "uso é simples::" +#: ../../faq/library.rst:796 +msgid "" +"import random\n" +"random.random()" +msgstr "" +"import random\n" +"random.random()" + #: ../../faq/library.rst:799 msgid "This returns a random floating-point number in the range [0, 1)." msgstr "Isso retorna um número flutuante aleatório no intervalo [0, 1)." diff --git a/faq/programming.po b/faq/programming.po index 31a368108..1f022543b 100644 --- a/faq/programming.po +++ b/faq/programming.po @@ -1,40 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Tiago Henrique , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Aline Balogh , 2021 -# Augusta Carla Klug , 2021 -# Leonardo Mendes, 2021 -# Rodrigo Cendamore, 2023 -# Vitor Buxbaum Orlandi, 2023 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-04-11 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../faq/programming.rst:5 msgid "Programming FAQ" -msgstr "FAQ referente a Programação" +msgstr "FAQ sobre programação" #: ../../faq/programming.rst:8 msgid "Contents" @@ -42,15 +33,15 @@ msgstr "Conteúdo" #: ../../faq/programming.rst:12 msgid "General Questions" -msgstr "Questões Gerais" +msgstr "Perguntas gerais" #: ../../faq/programming.rst:15 msgid "" "Is there a source code level debugger with breakpoints, single-stepping, " "etc.?" msgstr "" -"Existe um depurador a nível de código-fonte que possuo pontos de interrupção " -"(breakpoints), single-stepping etc.?" +"Existe um depurador a nível de código-fonte que possua pontos de interrupção " +"(*breakpoints*), single-stepping, etc.?" #: ../../faq/programming.rst:17 ../../faq/programming.rst:58 msgid "Yes." @@ -62,7 +53,7 @@ msgid "" "func:`breakpoint` allows you to drop into any of them." msgstr "" "Vários depuradores para Python estão descritos abaixo, e a função embutida :" -"func:`breakpoint` permite que você caia em qualquer um deles." +"func:`breakpoint` permite que você caia em qualquer um desses pontos." #: ../../faq/programming.rst:22 msgid "" @@ -71,11 +62,10 @@ msgid "" "Library Reference Manual `. You can also write your own debugger by " "using the code for pdb as an example." msgstr "" -"O módulo pdb é um depurador cujo funcionamento ocorre em modo Console " -"simples mas, adequado para o Python. Faz parte da biblioteca padrão do " -"Python e está documentado em :mod:`documented in the Library Reference " -"Manual 1`. Caso necessário, também é possível a construção do seu próprio " -"depurador usando o código do pdb como um exemplo." +"O módulo pdb é um depurador em modo Console simples, mas adequado, para o " +"Python. Faz parte da biblioteca padrão do Python e está documentado no :mod:" +"`manual de referencia da biblioteca `. Você também pode construir do " +"seu próprio depurador usando o código do pdb como um exemplo." #: ../../faq/programming.rst:27 msgid "" @@ -84,10 +74,10 @@ msgid "" "github.com/python/cpython/blob/main/Tools/scripts/idle3>`_), includes a " "graphical debugger." msgstr "" -"A IDLE (Ambiente Interativo de Desenvolvimento), que faz parte da " +"O IDLE é um ambiente interativo de desenvolvimento que faz parte da " "distribuição padrão do Python (normalmente acessível como `Tools/scripts/" "idle3 `_), " -"inclui um depurador gráfico" +"e inclui um depurador gráfico." #: ../../faq/programming.rst:32 msgid "" @@ -98,12 +88,12 @@ msgid "" "the `ActivePython `_ " "distribution." msgstr "" -"O PythonWin é uma IDE feita para o Python que inclui um depurador de GUI " -"baseado no pdb. O depurador PythonWin colora os pontos de interrupção e tem " -"alguns recursos legais, como a depuração de programas que não são PythonWin. " -"O PythonWin está disponível como parte do projeto `pywin32 `_ e como parte da distribuição `ActivePython `_." +"O PythonWin é uma IDE feita para o Python que inclui um depurador gráfico " +"baseado no pdb. O depurador do PythonWin colore os pontos de interrupção e " +"tem alguns recursos legais, como a depuração de programas que não são " +"PythonWin. O PythonWin está disponível como parte do projeto `pywin32 " +"`_ e como parte da distribuição " +"`ActivePython `_." #: ../../faq/programming.rst:39 msgid "" @@ -127,14 +117,14 @@ msgid "" "debugging tools that integrates with version-control software." msgstr "" "`Visual Studio Code `_ é uma IDE com " -"ferramentas de depuração que integra com softwares de controle de versão." +"ferramentas de depuração integrada com softwares de controle de versão." #: ../../faq/programming.rst:47 msgid "" "There are a number of commercial Python IDEs that include graphical " "debuggers. They include:" msgstr "" -"Há uma série de IDE comerciais para desenvolvimento com o Python que incluem " +"Há uma série de IDE comerciais para desenvolvimento com o Python que inclui " "depuradores gráficos. Dentre tantas temos:" #: ../../faq/programming.rst:50 @@ -161,6 +151,9 @@ msgid "" "`_ do basic checking that will help you " "catch bugs sooner." msgstr "" +"`Pylint `_ e `Pyflakes " +"`_ fazem verificações básicas que te " +"ajudarão a encontrar erros mais cedo." #: ../../faq/programming.rst:64 msgid "" @@ -168,6 +161,9 @@ msgid "" "`_, and `Pytype `_ can check type hints in Python source code." msgstr "" +"Verificadores de tipo estático como `Mypy `_, `Pyre " +"`_ e `Pytype `_ " +"conseguem verificar dicas de tipo em código-fonte Python." #: ../../faq/programming.rst:73 msgid "How can I create a stand-alone binary from a Python script?" @@ -185,7 +181,7 @@ msgstr "" "o que deseja é um programa autônomo que os usuários possam baixar e executar " "sem ter que instalar a distribuição Python primeiro. Existem várias " "ferramentas que determinam o conjunto de módulos exigidos por um programa e " -"vinculam esses módulos junto com o binário do Python para produzir um único " +"vinculam esses módulos ao binário do Python para produzir um único " "executável." #: ../../faq/programming.rst:81 @@ -196,6 +192,11 @@ msgid "" "can embed all your modules into a new program, which is then linked with the " "standard Python modules." msgstr "" +"Uma delas é usar a ferramenta *freeze*, que está incluída na árvore de " +"código-fonte Python como `Tools/freeze `_. Ela converte o *bytecode* de Python em vetores de " +"C. Com um compilador de C, você consegue incorporar todos os seus módulos em " +"um novo programa, que é então vinculado aos módulos-padrão de Python." #: ../../faq/programming.rst:87 msgid "" @@ -209,15 +210,16 @@ msgid "" "rest of the Python interpreter to form a self-contained binary which acts " "exactly like your script." msgstr "" -"Ela funciona escaneando seu código recursivamente pelas instruções de " -"importação (ambas as formas) e procurando pelos módulos no caminho padrão do " -"Python e também no diretório fonte (para módulos embutidos). Então torna o " -"bytecode de módulos escritos em Python em código C (inicializadores de vetor " -"que podem ser transformado em objetos código usando o módulo marshal) e cria " -"um arquivo de configurações customizado que só contém aqueles módulos " -"embutidos que são na realidade usados no programa. A ferramenta então " -"compila os códigos gerados em C e liga como o resto do interpretador Python " -"para formar um binário autônomo que age exatamente como seu script." +"A *freeze* trabalha percorrendo seu código recursivamente, procurando por " +"instruções de importação (ambas as formas), e procurando por módulos tanto " +"no caminho padrão do Python, quanto por módulos embutidos no diretório " +"fonte. Ela então transforma o *bytecode* de módulos Python em código C " +"(inicializadores de vetor que podem ser transformados em objetos código " +"usando o módulo `marshal`), e depois cria um arquivo de configurações " +"personalizado que só contém os módulos embutidos usados no programa. A " +"ferramenta então compila os códigos C e os vincula como o resto do " +"interpretador Python, formando um binário autônomo que funciona exatamente " +"como seu *script*." #: ../../faq/programming.rst:96 msgid "" @@ -233,7 +235,7 @@ msgstr "`Nuitka `_ (Multiplataforma)" #: ../../faq/programming.rst:100 msgid "`PyInstaller `_ (Cross-platform)" -msgstr "" +msgstr "`PyInstaller `_ (Multiplataforma)" #: ../../faq/programming.rst:101 msgid "" @@ -254,7 +256,7 @@ msgstr "`py2app `_ (somente macOS)" #: ../../faq/programming.rst:104 msgid "`py2exe `_ (Windows only)" -msgstr "" +msgstr "`py2exe `_ (somente Windows)" #: ../../faq/programming.rst:107 msgid "Are there coding standards or a style guide for Python programs?" @@ -268,17 +270,17 @@ msgid "" "as :pep:`8`." msgstr "" "Sim. O guia de estilo esperado para módulos e biblioteca padrão possui o " -"nome de PEP8 e podes acessar a sua documentação em :pep:`8`." +"nome de PEP8 e você pode acessar a sua documentação em :pep:`8`." #: ../../faq/programming.rst:114 msgid "Core Language" -msgstr "Núcleo da Linguagem" +msgstr "Núcleo da linguagem" #: ../../faq/programming.rst:119 msgid "Why am I getting an UnboundLocalError when the variable has a value?" msgstr "" -"Porque estou recebo o erro UnboundLocalError quando a variável possui um " -"valor associado?" +"Porque recebo o erro UnboundLocalError quando a variável possui um valor " +"associado?" #: ../../faq/programming.rst:121 msgid "" @@ -286,6 +288,9 @@ msgid "" "working code when it is modified by adding an assignment statement somewhere " "in the body of a function." msgstr "" +"Pode ser uma surpresa obter a exceção :exc:`UnboundLocalError` em um código " +"previamente funcional quando adicionamos uma instrução de atribuição em " +"algum lugar no corpo de uma função." #: ../../faq/programming.rst:125 msgid "This code:" @@ -308,21 +313,20 @@ msgid "" "Consequently when the earlier ``print(x)`` attempts to print the " "uninitialized local variable and an error results." msgstr "" -"Isso acontece devido ao fato de que quando realizamos uma tarefa numa " -"variável de um determinado escopo, essa variável torna-se-á local desse " -"escopo acabando por esconder qualquer variável similar que foi mencionada no " -"escopo externo. Uma vez que a última declaração de foo atribuir um novo " -"valor a ``x``, o compilador o reconhecera como uma variável local. " -"Consequentemente, quando o ``print(x)`` anterior tentar imprimir a variável " -"local não inicializada acabará resultando num." +"Isso acontece porque, quando atribuímos um valor a uma variável em " +"determinado escopo, essa variável torna-se local desse escopo, acabando por " +"esconder qualquer outra variável de mesmo nome no escopo externo. Como a " +"última instrução em foo atribui um novo valor a ``x``, o interpretador a " +"reconhece como uma variável local. Consequentemente, quando o ``print(x)`` " +"anterior tentar exibir a variável local não inicializada, um erro aparece." #: ../../faq/programming.rst:155 msgid "" "In the example above you can access the outer scope variable by declaring it " "global:" msgstr "" -"No exemplo acima, podemos acessar a variável do escopo externo declarando-o " -"globalmente:" +"No exemplo acima, podemos acessar a variável do escopo externo declarando-a " +"como global:" #: ../../faq/programming.rst:167 msgid "" @@ -330,17 +334,17 @@ msgid "" "the superficially analogous situation with class and instance variables) you " "are actually modifying the value of the variable in the outer scope:" msgstr "" -"Esta declaração explícita é necessária para lembrá-lo de que (ao contrário " -"da situação superficialmente análoga com variáveis de classe e instância), " -"você realmente está modificando o valor da variável no escopo externo:" +"Esta declaração explícita é necessária para lembrarmos que estamos " +"modificando o valor da variável no escopo externo (ao contrário da situação " +"superficialmente análoga com variáveis de classe e instância):" #: ../../faq/programming.rst:174 msgid "" "You can do a similar thing in a nested scope using the :keyword:`nonlocal` " "keyword:" msgstr "" -"Você pode fazer uma coisa semelhante num escopo aninhado usando o argumento " -"nomeado :keyword:`nonlocal`:" +"Podemos fazer algo parecido num escopo aninhado usando a palavra reservada :" +"keyword:`nonlocal`:" #: ../../faq/programming.rst:192 msgid "What are the rules for local and global variables in Python?" @@ -356,7 +360,7 @@ msgstr "" "Em Python, as variáveis que são apenas utilizadas (referenciadas) dentro de " "uma função são implicitamente globais. Se uma variável for associada a um " "valor em qualquer lugar dentro do corpo da função, presume-se que a mesma " -"será local, a menos que seja explicitamente declarado como global." +"seja local, a menos que seja explicitamente declarada como global." #: ../../faq/programming.rst:198 msgid "" @@ -382,7 +386,7 @@ msgid "" "Why do lambdas defined in a loop with different values all return the same " "result?" msgstr "" -"Por que os lambdas definidos em um loop com valores diferentes retornam o " +"Por que os lambdas definidos em um laço com valores diferentes retornam o " "mesmo resultado?" #: ../../faq/programming.rst:210 @@ -390,8 +394,18 @@ msgid "" "Assume you use a for loop to define a few different lambdas (or even plain " "functions), e.g.::" msgstr "" -"Suponha que utilizes um loop for para definir algumas funções lambdas (ou " -"mesmo funções simples), por exemplo.::" +"Suponha que se utilize um laço `for` para definir algumas funções lambdas " +"(ou mesmo funções simples), por exemplo.::" + +#: ../../faq/programming.rst:213 +msgid "" +">>> squares = []\n" +">>> for x in range(5):\n" +"... squares.append(lambda: x**2)" +msgstr "" +">>> squares = []\n" +">>> for x in range(5):\n" +"... squares.append(lambda: x**2)" #: ../../faq/programming.rst:217 msgid "" @@ -400,11 +414,23 @@ msgid "" "``1``, ``4``, ``9``, and ``16``. However, when you actually try you will " "see that they all return ``16``::" msgstr "" -"Isso oferece uma lista que contém 5 lambdas que calculam ``x**2``. Poderás " -"esperar que, quando invocado, os mesmo retornem, respectivamente, ``0``, " -"``1``, ``4``, ``9``, e ``16``. No entanto, quando realmente tentares, verás " +"Isso oferece uma lista que contém 5 lambdas que calculam ``x**2``. Você " +"pensar que, quando invocado, os mesmos retornam, respectivamente, ``0``, " +"``1``, ``4``, ``9``, e ``16``. No entanto, quando realmente tentar, vai ver " "que todos retornam ``16``::" +#: ../../faq/programming.rst:222 +msgid "" +">>> squares[2]()\n" +"16\n" +">>> squares[4]()\n" +"16" +msgstr "" +">>> squares[2]()\n" +"16\n" +">>> squares[4]()\n" +"16" + #: ../../faq/programming.rst:227 msgid "" "This happens because ``x`` is not local to the lambdas, but is defined in " @@ -413,20 +439,40 @@ msgid "" "the functions now return ``4**2``, i.e. ``16``. You can also verify this by " "changing the value of ``x`` and see how the results of the lambdas change::" msgstr "" -"Isso acontece porque ``x`` não é local para o lambdas, mas é definido no " +"Isso acontece porque ``x`` não é local para os lambdas, mas é definido no " "escopo externo, e é acessado quando o lambda for chamado --- não quando é " -"definido. No final do loop, o valor de ``x`` será ``4``, e então, todas as " -"funções agora retornarão ``4**2``, ou seja, ``16``. Também poderás verificar " -"isso alterando o valor de ``x`` e vendo como os resultados dos lambdas " -"mudam::" +"definido. No final do laço, o valor de ``x`` será ``4``, e então, todas as " +"funções agora retornarão ``4**2``, ou seja, ``16``. Também é possível " +"verificar isso alterando o valor de ``x`` e vendo como os resultados dos " +"lambdas mudam::" + +#: ../../faq/programming.rst:233 +msgid "" +">>> x = 8\n" +">>> squares[2]()\n" +"64" +msgstr "" +">>> x = 8\n" +">>> squares[2]()\n" +"64" #: ../../faq/programming.rst:237 msgid "" "In order to avoid this, you need to save the values in variables local to " "the lambdas, so that they don't rely on the value of the global ``x``::" msgstr "" -"Para evitar isso, precisarás salvar os valores nas variáveis locais para os " -"lambdas, para que eles não dependam do valor de ``x`` global::" +"Para evitar isso, é necessário salvar os valores nas variáveis locais para " +"os lambdas, para que eles não dependam do valor de ``x`` global::" + +#: ../../faq/programming.rst:240 +msgid "" +">>> squares = []\n" +">>> for x in range(5):\n" +"... squares.append(lambda n=x: n**2)" +msgstr "" +">>> squares = []\n" +">>> for x in range(5):\n" +"... squares.append(lambda n=x: n**2)" #: ../../faq/programming.rst:244 msgid "" @@ -436,13 +482,25 @@ msgid "" "the first lambda, ``1`` in the second, ``2`` in the third, and so on. " "Therefore each lambda will now return the correct result::" msgstr "" -"Aqui, ``n=x`` cria uma nova variável ``n`` local para o lambda e calculada " -"quando o lambda será definido para que ele tenha o mesmo valor que ``x`` " -"tenha nesse ponto no loop. Isso significa que o valor de ``n`` será ``0`` no " +"Aqui, ``n=x`` cria uma nova variável ``n`` local para o lambda e é calculada " +"quando o lambda é definido para que ele tenha o mesmo valor que ``x`` tem " +"nesse ponto no laço. Isso significa que o valor de ``n`` será ``0`` no " "primeiro \"ciclo\" do lambda, ``1`` no segundo \"ciclo\", ``2`` no terceiro, " "e assim por diante. Portanto, cada lambda agora retornará o resultado " "correto::" +#: ../../faq/programming.rst:250 +msgid "" +">>> squares[2]()\n" +"4\n" +">>> squares[4]()\n" +"16" +msgstr "" +">>> squares[2]()\n" +"4\n" +">>> squares[4]()\n" +"16" + #: ../../faq/programming.rst:255 msgid "" "Note that this behaviour is not peculiar to lambdas, but applies to regular " @@ -467,7 +525,7 @@ msgstr "" "A maneira canônica de compartilhar informações entre módulos dentro de um " "único programa é criando um módulo especial (geralmente chamado de config ou " "cfg). Basta importar o módulo de configuração em todos os módulos da sua " -"aplicação; O módulo ficará disponível como um nome global. Como há apenas " +"aplicação; o módulo ficará disponível como um nome global. Como há apenas " "uma instância de cada módulo, todas as alterações feitas no objeto do módulo " "se refletem em todos os lugares. Por exemplo:" @@ -475,21 +533,43 @@ msgstr "" msgid "config.py::" msgstr "config.py::" +#: ../../faq/programming.rst:270 +msgid "x = 0 # Default value of the 'x' configuration setting" +msgstr "x = 0 # Valor padrão para a configuração de 'x'" + #: ../../faq/programming.rst:272 msgid "mod.py::" msgstr "mod.py::" +#: ../../faq/programming.rst:274 +msgid "" +"import config\n" +"config.x = 1" +msgstr "" +"import config\n" +"config.x = 1" + #: ../../faq/programming.rst:277 msgid "main.py::" msgstr "main.py::" +#: ../../faq/programming.rst:279 +msgid "" +"import config\n" +"import mod\n" +"print(config.x)" +msgstr "" +"import config\n" +"import mod\n" +"print(config.x)" + #: ../../faq/programming.rst:283 msgid "" "Note that using a module is also the basis for implementing the singleton " "design pattern, for the same reason." msgstr "" -"Note que usar um módulo também é a base para a implementação de padrões de " -"design singleton, pela mesma razão." +"Note que usar um módulo também é a base para a implementação do padrão de " +"projeto Singleton, pela mesma razão." #: ../../faq/programming.rst:288 msgid "What are the \"best practices\" for using import in a module?" @@ -503,9 +583,9 @@ msgid "" "importer's namespace, and makes it much harder for linters to detect " "undefined names." msgstr "" -"Em geral, não use ``from modulename import *``. Ao fazê-lo, o espaço de " -"nomes do importador é mais difícil e torna muito mais difícil para as " -"ferramentas linters detectar nomes indefinidos." +"Em geral, não use ``from nomemódulo import *``. Isso desorganiza o espaço de " +"nomes do importador e torna muito mais difícil para as ferramentas de " +"análise estática detectarem nomes indefinidos." #: ../../faq/programming.rst:294 msgid "" @@ -515,7 +595,7 @@ msgid "" "module imports, but using multiple imports per line uses less screen space." msgstr "" "Faça a importação de módulos na parte superior do arquivo. Isso deixa claro " -"quais outros módulos nosso código necessita e evita dúvidas sobre por " +"quais outros módulos nosso código necessita e evita dúvidas sobre, por " "exemplo, se o nome do módulo está no escopo. Usar uma importação por linha " "facilita a adição e exclusão de importações de módulos, porém, usar várias " "importações num única linha, ocupa menos espaço da tela." @@ -529,14 +609,17 @@ msgid "" "standard library modules -- e.g. :mod:`sys`, :mod:`os`, :mod:`argparse`, :" "mod:`re`" msgstr "" -"módulos padrões da biblioteca -- por exemplo: :mod:`sys`, :mod:`os`, :mod:" -"`argparse`, :mod:`re`" +"módulos da biblioteca padrão -- por exemplo: :mod:`sys`, :mod:`os`, :mod:" +"`argparse` e :mod:`re`" #: ../../faq/programming.rst:302 msgid "" "third-party library modules (anything installed in Python's site-packages " "directory) -- e.g. :mod:`!dateutil`, :mod:`!requests`, :mod:`!PIL.Image`" msgstr "" +"módulos de biblioteca de terceiros (qualquer instalação feita contida no " +"repositório de códigos na pasta site-packages) -- por exemplo: :mod:`!" +"dateutil`, :mod:`!requests` e :mod:`!PIL.Image`" #: ../../faq/programming.rst:304 msgid "locally developed modules" @@ -558,11 +641,11 @@ msgid "" "That's because names in the 1st are not yet available, because the first " "module is busy importing the 2nd." msgstr "" -"As importações circulares estão bem onde ambos os módulos utilizam a forma " -"de importação \"import 1\". Eles falham quando o 2º módulo quer pegar um " -"nome do primeiro (\"from module import name\") e a importação está no nível " +"As importações circulares vão bem onde ambos os módulos utilizam a forma de " +"importação \"import \". Elas falham quando o 2º módulo quer pegar um " +"nome do primeiro (\"from módulo import nome\") e a importação está no nível " "superior. Isso porque os nomes no primeiro ainda não estão disponíveis, " -"porque o primeiro módulo está ocupado importando o 2º." +"porque o 1º módulo está ocupado importando o 2º." #: ../../faq/programming.rst:315 msgid "" @@ -606,16 +689,16 @@ msgid "" "of scope, the module is probably available in :data:`sys.modules`." msgstr "" "Apenas mova as importações para um escopo local, como dentro da definição de " -"função, se for necessário resolver algum tipo de problema, como exemplo, " -"evitar importações circulares ou tentar reduzir o tempo de inicialização do " -"módulo. Esta técnica é especialmente útil se muitas das importações forem " -"desnecessárias, dependendo de como o programa é executado. Também podemos " -"desejar mover as importações para uma função se os módulos forem usados " -"somente nessa função. Note que carregar um módulo pela primeira vez pode ser " -"demorado devido ao tempo de inicialização de cada módulo, no entanto, " -"carregar um módulo várias vezes é praticamente imperceptível, tendo somente " -"o custo de processamento de pesquisas no dicionário de nomes. Mesmo que o " -"nome do módulo tenha saído do escopo, o módulo provavelmente estará " +"função, se for necessário resolver algum tipo de problema, como, por " +"exemplo, evitar importações circulares ou tentar reduzir o tempo de " +"inicialização do módulo. Esta técnica é especialmente útil se muitas das " +"importações forem desnecessárias, dependendo de como o programa é executado. " +"Também podemos desejar mover as importações para uma função se os módulos " +"forem usados somente nessa função. Note que carregar um módulo pela primeira " +"vez pode ser demorado devido ao tempo de inicialização de cada módulo, no " +"entanto, carregar um módulo várias vezes é praticamente imperceptível, tendo " +"somente o custo de processamento de pesquisas no dicionário de nomes. Mesmo " +"que o nome do módulo tenha saído do escopo, o módulo provavelmente estará " "disponível em :data:`sys.modules`." #: ../../faq/programming.rst:338 @@ -630,15 +713,28 @@ msgstr "" "Este tipo de erro geralmente pega programadores neófitos. Considere esta " "função::" +#: ../../faq/programming.rst:342 +msgid "" +"def foo(mydict={}): # Danger: shared reference to one dict for all calls\n" +" ... compute something ...\n" +" mydict[key] = value\n" +" return mydict" +msgstr "" +"def foo(meudict={}): # Perigo: referência compartilhada a um dicionário " +"para todas as chamadas\n" +" ... faz alguma coisa ...\n" +" meudict[chave] = valor\n" +" return meudict" + #: ../../faq/programming.rst:347 msgid "" "The first time you call this function, ``mydict`` contains a single item. " "The second time, ``mydict`` contains two items because when ``foo()`` begins " "executing, ``mydict`` starts out with an item already in it." msgstr "" -"A primeira vez que chamares essa função, ``mydict`` irá conter um único " -"item. A segunda vez, ``mydict`` irá conter dois itens, porque quando " -"``foo()`` começar a ser executado, ``mydict`` começará com um item já " +"Na primeira vez que chamar essa função, ``meudict`` vai conter um único " +"item. Na segunda vez, ``meudict`` vai conter dois itens porque, quando " +"``foo()`` começar a ser executado, ``meudict`` começará com um item já " "existente." #: ../../faq/programming.rst:351 @@ -649,10 +745,10 @@ msgid "" "dictionary in this example, subsequent calls to the function will refer to " "this changed object." msgstr "" -"Muitas vezes, espera-se que ao invocar uma função seja criado novos objetos " -"referente aos valores padrão. Isso não é o que acontecerá. Os valores padrão " -"são criados exatamente uma vez, quando a função está sendo definida. Se esse " -"objeto for alterado, como o dicionário neste exemplo, as chamadas " +"Muitas vezes, espera-se que ao invocar uma função sejam criados novos " +"objetos referente aos valores padrão. Isso não é o que acontece. Os valores " +"padrão são criados exatamente uma vez, quando a função está sendo definida. " +"Se esse objeto for alterado, como o dicionário neste exemplo, as chamadas " "subsequentes para a essa função se referirão a este objeto alterado." #: ../../faq/programming.rst:356 @@ -676,13 +772,31 @@ msgstr "" "Por causa desse recurso, é uma boa prática de programação para evitar o uso " "de objetos mutáveis contendo valores padrão. Em vez disso, utilize ``None`` " "como o valor padrão e dentro da função, verifique se o parâmetro é ``None`` " -"e crie uma nova lista /dicionário/ o que quer que seja. Por exemplo, escreva " -"o seguinte código::" +"e crie uma nova lista, dicionário ou o que quer que seja. Por exemplo, " +"escreva o seguinte código::" + +#: ../../faq/programming.rst:365 +msgid "" +"def foo(mydict={}):\n" +" ..." +msgstr "" +"def foo(meudict={}):\n" +" ..." #: ../../faq/programming.rst:368 msgid "but::" msgstr "mas::" +#: ../../faq/programming.rst:370 +msgid "" +"def foo(mydict=None):\n" +" if mydict is None:\n" +" mydict = {} # create a new dict for local namespace" +msgstr "" +"def foo(meudict=None):\n" +" if meudict is None:\n" +" meudict = {} # cria um novo dicionário para o espaço de nomes local" + #: ../../faq/programming.rst:374 msgid "" "This feature can be useful. When you have a function that's time-consuming " @@ -691,26 +805,50 @@ msgid "" "value is requested again. This is called \"memoizing\", and can be " "implemented like this::" msgstr "" -"Esse recurso pode ser útil. Quando tiveres uma função que consome muito " -"tempo para calcular, uma técnica comum é armazenar em cache os parâmetros e " -"o valor resultante de cada chamada para a função e retornar o valor em cache " +"Esse recurso pode ser útil. Quando se tem uma função que consome muito tempo " +"para calcular, uma técnica comum é armazenar em cache os parâmetros e o " +"valor resultante de cada chamada para a função e retornar o valor em cache " "se o mesmo valor for solicitado novamente. Isso se chama \"memoizar\", e " "pode ser implementado da seguinte forma::" +#: ../../faq/programming.rst:379 +msgid "" +"# Callers can only provide two parameters and optionally pass _cache by " +"keyword\n" +"def expensive(arg1, arg2, *, _cache={}):\n" +" if (arg1, arg2) in _cache:\n" +" return _cache[(arg1, arg2)]\n" +"\n" +" # Calculate the value\n" +" result = ... expensive computation ...\n" +" _cache[(arg1, arg2)] = result # Store result in the cache\n" +" return result" +msgstr "" +"# Chamadores só podem fornecer dois parâmetros e opcionalmente passar _cache " +"como parâmetro nomeado\n" +"def expensive(arg1, arg2, *, _cache={}):\n" +" if (arg1, arg2) in _cache:\n" +" return _cache[(arg1, arg2)]\n" +"\n" +" # Cacula o valor\n" +" result = ... cálculo custoso ...\n" +" _cache[(arg1, arg2)] = result # Armazena o resultado no cache\n" +" return result" + #: ../../faq/programming.rst:389 msgid "" "You could use a global variable containing a dictionary instead of the " "default value; it's a matter of taste." msgstr "" -"Poderias usar uma variável global contendo um dicionário ao invés do valor " +"Pode-se usar uma variável global contendo um dicionário ao invés do valor " "padrão; isso é uma questão de gosto." #: ../../faq/programming.rst:394 msgid "" "How can I pass optional or keyword parameters from one function to another?" msgstr "" -"Como passar parâmetros opcionais ou parâmetros na forma de keyword de uma " -"função a outra?" +"Como passo parâmetros opcionais ou parâmetros nomeados de uma função para " +"outra?" #: ../../faq/programming.rst:396 msgid "" @@ -725,6 +863,20 @@ msgstr "" "também, passar esses argumentos ao invocar outra função usando ``*`` e " "``**``::" +#: ../../faq/programming.rst:401 +msgid "" +"def f(x, *args, **kwargs):\n" +" ...\n" +" kwargs['width'] = '14.3c'\n" +" ...\n" +" g(x, *args, **kwargs)" +msgstr "" +"def f(x, *args, **kwargs):\n" +" ...\n" +" kwargs['width'] = '14.3c'\n" +" ...\n" +" g(x, *args, **kwargs)" + #: ../../faq/programming.rst:415 msgid "What is the difference between arguments and parameters?" msgstr "Qual a diferença entre argumentos e parâmetros?" @@ -737,6 +889,20 @@ msgid "" "`kind of arguments ` a function can accept. For example, given " "the function definition::" msgstr "" +":term:`Parâmetros ` são definidos pelos nomes que aparecem na " +"definição da função, enquanto :term:`argumentos ` são os valores " +"que serão passados para a função no momento em que esta estiver sendo " +"invocada. Os parâmetros irão definir quais os :term:`tipos de argumentos " +"` que uma função pode receber. Por exemplo, dada a definição da " +"função::" + +#: ../../faq/programming.rst:423 +msgid "" +"def func(foo, bar=None, **kwargs):\n" +" pass" +msgstr "" +"def func(foo, bar=None, **kwargs):\n" +" pass" #: ../../faq/programming.rst:426 msgid "" @@ -746,9 +912,13 @@ msgstr "" "*foo*, *bar* e *kwargs* são parâmetros de ``func``. Dessa forma, ao invocar " "``func``, por exemplo::" +#: ../../faq/programming.rst:429 +msgid "func(42, bar=314, extra=somevar)" +msgstr "func(42, bar=314, extra=algumvalor)" + #: ../../faq/programming.rst:431 msgid "the values ``42``, ``314``, and ``somevar`` are arguments." -msgstr "os valores ``42``, ``314``, e ``somevar`` são os argumentos." +msgstr "os valores ``42``, ``314``, e ``algumvalor`` são os argumentos." #: ../../faq/programming.rst:435 msgid "Why did changing list 'y' also change list 'x'?" @@ -756,18 +926,36 @@ msgstr "Por que ao alterar a lista 'y' também altera a lista 'x'?" #: ../../faq/programming.rst:437 msgid "If you wrote code like::" -msgstr "Se escreveres um código como::" +msgstr "Se você escreveu um código como::" + +#: ../../faq/programming.rst:439 +msgid "" +">>> x = []\n" +">>> y = x\n" +">>> y.append(10)\n" +">>> y\n" +"[10]\n" +">>> x\n" +"[10]" +msgstr "" +">>> x = []\n" +">>> y = x\n" +">>> y.append(10)\n" +">>> y\n" +"[10]\n" +">>> x\n" +"[10]" #: ../../faq/programming.rst:447 msgid "" "you might be wondering why appending an element to ``y`` changed ``x`` too." msgstr "" -"Poderás estar se perguntando por que acrescentar um elemento a ``y`` também " +"pode estar se perguntando por que acrescentar um elemento a ``y`` também " "mudou ``x``." #: ../../faq/programming.rst:449 msgid "There are two factors that produce this result:" -msgstr "Há 2 fatores que produzem esse resultado, são eles:" +msgstr "Há dois fatores que produzem esse resultado:" #: ../../faq/programming.rst:451 msgid "" @@ -776,11 +964,11 @@ msgid "" "the same object ``x`` refers to. This means that there is only one object " "(the list), and both ``x`` and ``y`` refer to it." msgstr "" -"As variáveis são simplesmente nomes que referem-se a objetos. Ao escrevermos " -"``y = x`` não criará uma cópia da lista -- criará uma nova variável ``y`` " -"que irá se referir ao mesmo objeto que ``x`` está se referindo. Isso " -"significa que existe apenas um objeto (lista), e ambos nomes (variáveis) " -"``x`` e ``y`` estão associados ao mesmo." +"As variáveis são simplesmente nomes que referem-se a objetos. Usar ``y = x`` " +"não cria uma cópia da lista. Isso cria uma nova variável ``y`` que faz " +"referência ao mesmo objeto ao qual ``x`` está se referindo. Isso significa " +"que existe apenas um objeto (a lista) e que ambos ``x`` e ``y`` fazem " +"referência a ele." #: ../../faq/programming.rst:455 msgid "" @@ -795,11 +983,32 @@ msgid "" "changed from ``[]`` to ``[10]``. Since both the variables refer to the same " "object, using either name accesses the modified value ``[10]``." msgstr "" +"Após a chamada para :meth:`!append`, o conteúdo do objeto mutável mudou de " +"``[]`` para ``[10]``. Uma vez que ambas as variáveis referem-se ao mesmo " +"objeto, usar qualquer um dos nomes acessará o valor modificado ``[10]``." #: ../../faq/programming.rst:461 msgid "If we instead assign an immutable object to ``x``::" msgstr "Se por acaso, atribuímos um objeto imutável a ``x``::" +#: ../../faq/programming.rst:463 +msgid "" +">>> x = 5 # ints are immutable\n" +">>> y = x\n" +">>> x = x + 1 # 5 can't be mutated, we are creating a new object here\n" +">>> x\n" +"6\n" +">>> y\n" +"5" +msgstr "" +">>> x = 5 # ints são imutáveis\n" +">>> y = x\n" +">>> x = x + 1 # 5 não pode ser mutado, estamos criando um novo objeto aqui\n" +">>> x\n" +"6\n" +">>> y\n" +"5" + #: ../../faq/programming.rst:471 msgid "" "we can see that in this case ``x`` and ``y`` are not equal anymore. This is " @@ -810,14 +1019,14 @@ msgid "" "objects (the ints ``6`` and ``5``) and two variables that refer to them " "(``x`` now refers to ``6`` but ``y`` still refers to ``5``)." msgstr "" -"veremos que nesse caso ``x`` e ``y`` não são mais iguais. Isso ocorre porque " -"os números inteiros são :term:`imutáveis `, e quando fizermos ``x " -"= x + 1`` não estaremos mudando o int ``5`` e incrementando o seu valor; em " -"vez disso, estamos criando um novo objeto (o int ``6``) e associando ``x`` " -"(isto é, mudando para o objeto no qual ``x`` se refere). Após esta " -"atribuição, temos dois objetos (os ints ``6`` e ``5``) e duas variáveis que " -"referem-se a elas (``x`` agora se refere a ``6`` mas ``y`` ainda refere-se a " -"``5``)." +"podemos ver que nesse caso ``x`` e ``y`` não são mais iguais. Isso ocorre " +"porque os números inteiros são :term:`imutáveis `, e quando " +"fazemos ``x = x + 1`` não estamos mudando o int ``5`` e incrementando o seu " +"valor. Em vez disso, estamos criando um novo objeto (o int ``6``) e " +"atribuindo-o a ``x`` (isto é, mudando para o objeto no qual ``x`` se " +"refere). Após esta atribuição, temos dois objetos (os ints ``6`` e ``5``) e " +"duas variáveis que referem-se a elas (``x`` agora se refere a ``6``, mas " +"``y`` ainda refere-se a ``5``)." #: ../../faq/programming.rst:479 msgid "" @@ -830,6 +1039,15 @@ msgid "" "will give you a sorted copy of ``y``, you'll instead end up with ``None``, " "which will likely cause your program to generate an easily diagnosed error." msgstr "" +"Algumas operações (por exemplo, ``y.append(10)`` e ``y.sort()``) alteram o " +"objeto, enquanto operações superficialmente semelhantes (por exemplo, ``y = " +"y + [10]`` e :func:`sorted(y) `) criam um novo objeto. Em geral, em " +"Python (e em todos os casos na biblioteca padrão) um método que causa " +"mutação em um objeto retornará ``None`` para ajudar a evitar confundir os " +"dois tipos de operações. Portanto, se você escrever por engano ``y.sort()`` " +"pensando que lhe dará uma cópia ordenada de ``y``, você terminará com " +"``None``, o que provavelmente fará com que seu programa gere um erro " +"facilmente diagnosticado." #: ../../faq/programming.rst:488 msgid "" @@ -843,9 +1061,9 @@ msgstr "" "No entanto, há uma classe de operações em que a mesma operação às vezes tem " "comportamentos diferentes com tipos diferentes: os operadores de atribuição " "aumentada. Por exemplo, ``+=`` transforma listas, mas não tuplas ou ints " -"(``a_list += [1, 2, 3]`` é equivalente a ``a_list.extend([1, 2, 3])`` a " -"altera ``a_list``, sendo que ``some_tuple += (1, 2, 3)`` e ``some_int += 1`` " -"cria novos objetos)." +"(``uma_lista += [1, 2, 3]`` equivale a ``uma_lista.extend([1, 2, 3])`` a " +"transforma ``uma_lista``, sendo que ``alguma_tupla += (1, 2, 3)`` e " +"``algum_int += 1`` cria novos objetos)." #: ../../faq/programming.rst:495 msgid "In other words:" @@ -857,9 +1075,9 @@ msgid "" "etc.), we can use some specific operations to mutate it and all the " "variables that refer to it will see the change." msgstr "" -"Se tivermos objetos mutáveis (:class:`list`, :class:`dict`, :class:`set`, " -"etc.), podemos usar algumas operações específicas para altera-lo e todas as " -"variáveis que se referem a ela sofreram também a mudança." +"Se tivermos um objeto mutável (:class:`list`, :class:`dict`, :class:`set`, " +"etc.), podemos usar algumas operações específicas para alterá-lo e todas as " +"variáveis que fazem referência a ele verão também a mudança." #: ../../faq/programming.rst:500 msgid "" @@ -869,22 +1087,22 @@ msgid "" "new object." msgstr "" "Caso tenhamos um objeto imutável (:class:`str`, :class:`int`, :class:" -"`tuple`, etc.), todas as variáveis que se referem as mesmas sempre verão o " -"mesmo valor, mas as operações que transformam-se nesses valores sempre " -"retornarão novos objetos." +"`tuple`, etc.), todas as variáveis que se referem a ele sempre verão o mesmo " +"valor, mas as operações que transformam-se nesses valores sempre retornarão " +"novos objetos." #: ../../faq/programming.rst:505 msgid "" "If you want to know if two variables refer to the same object or not, you " "can use the :keyword:`is` operator, or the built-in function :func:`id`." msgstr "" -"Se quiseres saber se duas variáveis se referem ao mesmo objeto ou não, podes " -"usar a palavra-chave :keyword:`is`, ou a função embutida :func:`id`." +"Caso queira saber se duas variáveis fazem referência ao mesmo objeto ou não, " +"pode-se usar o operador :keyword:`is` ou a função embutida :func:`id`." #: ../../faq/programming.rst:510 msgid "How do I write a function with output parameters (call by reference)?" msgstr "" -"Como escrever uma função com parâmetros de saída (invocada por referência)?" +"Como escrevo uma função com parâmetros de saída (chamada por referência)?" #: ../../faq/programming.rst:512 msgid "" @@ -894,39 +1112,129 @@ msgid "" "You can achieve the desired effect in a number of ways." msgstr "" "Lembre-se de que os argumentos são passados por atribuição em Python. Uma " -"vez que a tarefa apenas cria referências a objetos, não existe \"alias\" " -"entre um nome de argumento naquele que invocado e o destinatário, portanto, " -"não há referência de chamada por si. Podes alcançar o efeito desejado de " +"vez que a atribuição apenas cria referências a objetos, não existe apelido " +"entre um nome de argumento no chamador e no chamado e, portanto, não há " +"referência de chamada por si. É possível alcançar o efeito desejado de " "várias maneiras." #: ../../faq/programming.rst:517 msgid "By returning a tuple of the results::" -msgstr "Retornando um Tupla com os resultados::" +msgstr "Retornando um tupla com os resultados::" + +#: ../../faq/programming.rst:519 +msgid "" +">>> def func1(a, b):\n" +"... a = 'new-value' # a and b are local names\n" +"... b = b + 1 # assigned to new objects\n" +"... return a, b # return new values\n" +"...\n" +">>> x, y = 'old-value', 99\n" +">>> func1(x, y)\n" +"('new-value', 100)" +msgstr "" +">>> def func1(a, b):\n" +"... a = 'valor-novo' # a e b são nomes locais\n" +"... b = b + 1 # atribuídos a novos objetos\n" +"... return a, b # retorna novos valores\n" +"...\n" +">>> x, y = 'valor-antigo', 99\n" +">>> func1(x, y)\n" +"('valor-novo', 100)" #: ../../faq/programming.rst:528 msgid "This is almost always the clearest solution." -msgstr "Esta quase sempre é a solução mais clara." +msgstr "Esta é quase sempre a solução mais clara." #: ../../faq/programming.rst:530 msgid "" "By using global variables. This isn't thread-safe, and is not recommended." msgstr "" -"Utilizando variáveis globais. Essa forma de trabalho não é segura para uso " -"com thread e portanto, a mesma não é recomendada." +"Utilizando variáveis globais. Essa forma não é segura para thread e, " +"portanto, não é recomendada." #: ../../faq/programming.rst:532 msgid "By passing a mutable (changeable in-place) object::" msgstr "" "Pela passagem de um objeto mutável (que possa ser alterado internamente)::" +#: ../../faq/programming.rst:534 +msgid "" +">>> def func2(a):\n" +"... a[0] = 'new-value' # 'a' references a mutable list\n" +"... a[1] = a[1] + 1 # changes a shared object\n" +"...\n" +">>> args = ['old-value', 99]\n" +">>> func2(args)\n" +">>> args\n" +"['new-value', 100]" +msgstr "" +">>> def func2(a):\n" +"... a[0] = 'valor-novo' # 'a' referencia uma lista mutável\n" +"... a[1] = a[1] + 1 # altera um objeto compartilhado\n" +"...\n" +">>> args = ['valor-antigo', 99]\n" +">>> func2(args)\n" +">>> args\n" +"['valor-novo', 100]" + #: ../../faq/programming.rst:543 msgid "By passing in a dictionary that gets mutated::" -msgstr "Pela passagem de um dicionário que seja mutável::" +msgstr "Pela passagem de um dicionário que sofra mutação::" + +#: ../../faq/programming.rst:545 +msgid "" +">>> def func3(args):\n" +"... args['a'] = 'new-value' # args is a mutable dictionary\n" +"... args['b'] = args['b'] + 1 # change it in-place\n" +"...\n" +">>> args = {'a': 'old-value', 'b': 99}\n" +">>> func3(args)\n" +">>> args\n" +"{'a': 'new-value', 'b': 100}" +msgstr "" +">>> def func3(args):\n" +"... args['a'] = 'valor-novo' # args é um dicionário mutável\n" +"... args['b'] = args['b'] + 1 # alteração local, nele mesmo\n" +"...\n" +">>> args = {'a': 'valor-antigo', 'b': 99}\n" +">>> func3(args)\n" +">>> args\n" +"{'a': 'valor-novo', 'b': 100}" #: ../../faq/programming.rst:554 msgid "Or bundle up values in a class instance::" msgstr "Ou agrupando valores numa instância de classe::" +#: ../../faq/programming.rst:556 +msgid "" +">>> class Namespace:\n" +"... def __init__(self, /, **args):\n" +"... for key, value in args.items():\n" +"... setattr(self, key, value)\n" +"...\n" +">>> def func4(args):\n" +"... args.a = 'new-value' # args is a mutable Namespace\n" +"... args.b = args.b + 1 # change object in-place\n" +"...\n" +">>> args = Namespace(a='old-value', b=99)\n" +">>> func4(args)\n" +">>> vars(args)\n" +"{'a': 'new-value', 'b': 100}" +msgstr "" +">>> class Namespace:\n" +"... def __init__(self, /, **args):\n" +"... for key, value in args.items():\n" +"... setattr(self, key, value)\n" +"...\n" +">>> def func4(args):\n" +"... args.a = 'valor-novo' # args é um Namespace mutável\n" +"... args.b = args.b + 1 # alteração local do objeto, nele mesmo\n" +"...\n" +">>> args = Namespace(a='valor-antigo', b=99)\n" +">>> func4(args)\n" +">>> vars(args)\n" +"{'a': 'valor-novo', 'b': 100}" + #: ../../faq/programming.rst:571 msgid "There's almost never a good reason to get this complicated." msgstr "Quase nunca existe uma boa razão para complicar isso." @@ -934,7 +1242,7 @@ msgstr "Quase nunca existe uma boa razão para complicar isso." #: ../../faq/programming.rst:573 msgid "Your best choice is to return a tuple containing the multiple results." msgstr "" -"A sua melhor escolha será retornar uma Tupla contendo os múltiplos " +"A sua melhor escolha será retornar uma tupla contendo os múltiplos " "resultados." #: ../../faq/programming.rst:577 @@ -948,22 +1256,56 @@ msgid "" "returns a function ``f(x)`` that computes the value ``a*x+b``. Using nested " "scopes::" msgstr "" -"Existem duas opções: podes usar escopos aninhados ou poderás usar objetos " -"chamáveis. Por exemplo, suponha que desejasses definir que ``linear(a,b)`` " -"retorne uma função ``f(x)`` que calcule o valor ``a*x+b``. Usando escopos " +"Existem duas opções: pode-se usar escopos aninhados ou usar objetos " +"chamáveis. Por exemplo, suponha que queira definir ``linear(a,b)``, o qual " +"retorna uma função ``f(x)`` que calcula o valor ``a*x+b``. Usando escopos " "aninhados, temos::" +#: ../../faq/programming.rst:583 +msgid "" +"def linear(a, b):\n" +" def result(x):\n" +" return a * x + b\n" +" return result" +msgstr "" +"def linear(a, b):\n" +" def result(x):\n" +" return a * x + b\n" +" return result" + #: ../../faq/programming.rst:588 msgid "Or using a callable object::" -msgstr "Ou utilizando objetos chamáveis::" +msgstr "Ou utilizando um objeto chamável::" + +#: ../../faq/programming.rst:590 +msgid "" +"class linear:\n" +"\n" +" def __init__(self, a, b):\n" +" self.a, self.b = a, b\n" +"\n" +" def __call__(self, x):\n" +" return self.a * x + self.b" +msgstr "" +"class linear:\n" +"\n" +" def __init__(self, a, b):\n" +" self.a, self.b = a, b\n" +"\n" +" def __call__(self, x):\n" +" return self.a * x + self.b" #: ../../faq/programming.rst:598 msgid "In both cases, ::" msgstr "Em ambos os casos::" +#: ../../faq/programming.rst:600 +msgid "taxes = linear(0.3, 2)" +msgstr "taxas = linear(0.3, 2)" + #: ../../faq/programming.rst:602 msgid "gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``." -msgstr "dado um objeto chamável, onde ``taxes(10e6) == 0.3 * 10e6 + 2``." +msgstr "resulta em um objeto chamável, onde ``taxes(10e6) == 0.3 * 10e6 + 2``." #: ../../faq/programming.rst:604 msgid "" @@ -972,13 +1314,59 @@ msgid "" "callables can share their signature via inheritance::" msgstr "" "A abordagem do objeto chamável tem a desvantagem de que é um pouco mais " -"lento e resulta num código ligeiramente mais longo. No entanto, note que uma " +"lenta e resulta num código ligeiramente mais longo. No entanto, note que uma " "coleção de chamáveis pode compartilhar sua assinatura via herança::" +#: ../../faq/programming.rst:608 +msgid "" +"class exponential(linear):\n" +" # __init__ inherited\n" +" def __call__(self, x):\n" +" return self.a * (x ** self.b)" +msgstr "" +"class exponential(linear):\n" +" # __init__ herdado\n" +" def __call__(self, x):\n" +" return self.a * (x ** self.b)" + #: ../../faq/programming.rst:613 msgid "Object can encapsulate state for several methods::" msgstr "Objetos podem encapsular o estado para vários métodos::" +#: ../../faq/programming.rst:615 +msgid "" +"class counter:\n" +"\n" +" value = 0\n" +"\n" +" def set(self, x):\n" +" self.value = x\n" +"\n" +" def up(self):\n" +" self.value = self.value + 1\n" +"\n" +" def down(self):\n" +" self.value = self.value - 1\n" +"\n" +"count = counter()\n" +"inc, dec, reset = count.up, count.down, count.set" +msgstr "" +"class counter:\n" +"\n" +" value = 0\n" +"\n" +" def set(self, x):\n" +" self.value = x\n" +"\n" +" def up(self):\n" +" self.value = self.value + 1\n" +"\n" +" def down(self):\n" +" self.value = self.value - 1\n" +"\n" +"count = counter()\n" +"inc, dec, reset = count.up, count.down, count.set" + #: ../../faq/programming.rst:631 msgid "" "Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the " @@ -1008,10 +1396,18 @@ msgstr "" "Alguns objetos podem ser copiados com mais facilidade. Os dicionários têm um " "método :meth:`~dict.copy`::" +#: ../../faq/programming.rst:644 +msgid "newdict = olddict.copy()" +msgstr "novodict = antigodict.copy()" + #: ../../faq/programming.rst:646 msgid "Sequences can be copied by slicing::" msgstr "As sequências podem ser copiadas através do uso de fatiamento::" +#: ../../faq/programming.rst:648 +msgid "new_l = l[:]" +msgstr "nova_l = l[:]" + #: ../../faq/programming.rst:652 msgid "How can I find the methods or attributes of an object?" msgstr "Como posso encontrar os métodos ou atributos de um objeto?" @@ -1022,6 +1418,9 @@ msgid "" "an alphabetized list of the names containing the instance attributes and " "methods and attributes defined by its class." msgstr "" +"Para uma instância ``x`` de uma classe definida pelo usuário, :func:`dir(x) " +"` retorna uma lista organizada alfabeticamente dos nomes contidos, os " +"atributos da instância e os métodos e atributos definidos por sua classe." #: ../../faq/programming.rst:660 msgid "How can my code discover the name of an object?" @@ -1039,6 +1438,30 @@ msgstr "" "verdade para as instruções ``def`` e ``class``, mas nesse caso o valor é um " "chamável. Considere o seguinte código::" +#: ../../faq/programming.rst:667 +msgid "" +">>> class A:\n" +"... pass\n" +"...\n" +">>> B = A\n" +">>> a = B()\n" +">>> b = a\n" +">>> print(b)\n" +"<__main__.A object at 0x16D07CC>\n" +">>> print(a)\n" +"<__main__.A object at 0x16D07CC>" +msgstr "" +">>> class A:\n" +"... pass\n" +"...\n" +">>> B = A\n" +">>> a = B()\n" +">>> b = a\n" +">>> print(b)\n" +"<__main__.A object at 0x16D07CC>\n" +">>> print(a)\n" +"<__main__.A object at 0x16D07CC>" + #: ../../faq/programming.rst:678 msgid "" "Arguably the class has a name: even though it is bound to two names and " @@ -1047,6 +1470,11 @@ msgid "" "instance's name is ``a`` or ``b``, since both names are bound to the same " "value." msgstr "" +"Provavelmente, a classe tem um nome: mesmo que seja vinculada a dois nomes e " +"invocada através do nome ``B``, a instância criada ainda é relatada como uma " +"instância da classe ``A``. No entanto, é impossível dizer se o nome da " +"instância é ``a`` ou ``b``, uma vez que ambos os nomes estão vinculados ao " +"mesmo valor." #: ../../faq/programming.rst:683 msgid "" @@ -1056,7 +1484,7 @@ msgid "" "approach might be beneficial." msgstr "" "De um modo geral, não deveria ser necessário que o seu código \"conheça os " -"nomes\" de valores específicos. A menos que escrevas deliberadamente " +"nomes\" de valores específicos. A menos que se escreva deliberadamente " "programas introspectivos, isso geralmente é uma indicação de que uma mudança " "de abordagem pode ser benéfica." @@ -1077,7 +1505,7 @@ msgid "" msgstr "" "Da mesma forma que você pega o nome daquele gato que encontrou na sua " "varanda: o próprio gato (objeto) não pode lhe dizer o seu nome, e ele " -"realmente não se importa -- então a única maneira de descobrir como ele se " +"realmente não se importa -- então, a única maneira de descobrir como ele se " "chama é perguntar a todos os seus vizinhos (espaços de nomes) se é o gato " "deles (objeto)..." @@ -1086,7 +1514,7 @@ msgid "" "....and don't be surprised if you'll find that it's known by many names, or " "no name at all!" msgstr "" -"....e não fique surpreso se você encontrar que é conhecido por muitos nomes, " +"....e não fique surpreso se você descobrir que é conhecido por muitos nomes, " "ou até mesmo nenhum nome." #: ../../faq/programming.rst:701 @@ -1097,6 +1525,14 @@ msgstr "O que há com a precedência do operador vírgula?" msgid "Comma is not an operator in Python. Consider this session::" msgstr "A vírgula não é um operador em Python. Considere este código::" +#: ../../faq/programming.rst:705 +msgid "" +">>> \"a\" in \"b\", \"a\"\n" +"(False, 'a')" +msgstr "" +">>> \"a\" in \"b\", \"a\"\n" +"(False, 'a')" + #: ../../faq/programming.rst:708 msgid "" "Since the comma is not an operator, but a separator between expressions the " @@ -1105,10 +1541,18 @@ msgstr "" "Uma vez que a vírgula não seja um operador, mas um separador entre as " "expressões acima, o código será avaliado como se tivéssemos entrado::" +#: ../../faq/programming.rst:711 +msgid "(\"a\" in \"b\"), \"a\"" +msgstr "(\"a\" in \"b\"), \"a\"" + #: ../../faq/programming.rst:713 msgid "not::" msgstr "não::" +#: ../../faq/programming.rst:715 +msgid "\"a\" in (\"b\", \"a\")" +msgstr "\"a\" in (\"b\", \"a\")" + #: ../../faq/programming.rst:717 msgid "" "The same is true of the various assignment operators (``=``, ``+=`` etc). " @@ -1121,19 +1565,35 @@ msgstr "" #: ../../faq/programming.rst:722 msgid "Is there an equivalent of C's \"?:\" ternary operator?" -msgstr "Existe um equivalente ao operador \"?:\" ternário do C?" +msgstr "Existe um equivalente ao operador ternário \"?:\" do C?" #: ../../faq/programming.rst:724 msgid "Yes, there is. The syntax is as follows::" -msgstr "Sim existe. A sintaxe é a seguinte::" +msgstr "Sim, existe. A sintaxe é a seguinte::" + +#: ../../faq/programming.rst:726 +msgid "" +"[on_true] if [expression] else [on_false]\n" +"\n" +"x, y = 50, 25\n" +"small = x if x < y else y" +msgstr "" +"[quando_verdadeiro] if [expressão] else [quando_falso]\n" +"\n" +"x, y = 50, 25\n" +"small = x if x < y else y" #: ../../faq/programming.rst:731 msgid "" "Before this syntax was introduced in Python 2.5, a common idiom was to use " "logical operators::" msgstr "" -"Antes que essa sintaxe fosse introduzida no Python 2.5, um idioma comum era " -"usar operadores lógicos::" +"Antes que essa sintaxe fosse introduzida no Python 2.5, uma expressão comum " +"era usar operadores lógicos::" + +#: ../../faq/programming.rst:734 +msgid "[expression] and [on_true] or [on_false]" +msgstr "[expressão] and [quando_verdadeiro] or [quando_falso]" #: ../../faq/programming.rst:736 msgid "" @@ -1142,8 +1602,8 @@ msgid "" "if ... else ...`` form." msgstr "" "No entanto, essa forma não é segura, pois pode dar resultados inesperados " -"quando *on_true* possuir um valor booleano falso. Portanto, é sempre melhor " -"usar a forma ``... if ... else ...``." +"quando *quando_verdadeiro* tiver um valor booleano falso. Portanto, é sempre " +"melhor usar a forma ``... if ... else ...``." #: ../../faq/programming.rst:742 msgid "Is it possible to write obfuscated one-liners in Python?" @@ -1155,6 +1615,61 @@ msgid "" "lambda`. See the following three examples, slightly adapted from Ulf " "Bartelt::" msgstr "" +"Sim. Normalmente, isso é feito aninhando :keyword:`lambda` dentro de :" +"keyword:`!lambda`. Veja os três exemplos a seguir, ligeiramente adaptados de " +"Ulf Bartelt::" + +#: ../../faq/programming.rst:747 +msgid "" +"from functools import reduce\n" +"\n" +"# Primes < 1000\n" +"print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,\n" +"map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))\n" +"\n" +"# First 10 Fibonacci numbers\n" +"print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:\n" +"f(x,f), range(10))))\n" +"\n" +"# Mandelbrot set\n" +"print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+'\\n'+y,map(lambda " +"y,\n" +"Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,\n" +"Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,\n" +"i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y\n" +">=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(\n" +"64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy\n" +"))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))\n" +"# \\___ ___/ \\___ ___/ | | |__ lines on screen\n" +"# V V | |______ columns on screen\n" +"# | | |__________ maximum of \"iterations\"\n" +"# | |_________________ range on y axis\n" +"# |____________________________ range on x axis" +msgstr "" +"from functools import reduce\n" +"\n" +"# Primos < 1000\n" +"print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,\n" +"map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))\n" +"\n" +"# Primeiros 10 números de Fibonacci\n" +"print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:\n" +"f(x,f), range(10))))\n" +"\n" +"# Conjunto de Mandelbrot\n" +"print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+'\\n'+y,map(lambda " +"y,\n" +"Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,\n" +"Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,\n" +"i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y\n" +">=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(\n" +"64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy\n" +"))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))\n" +"# \\___ ___/ \\___ ___/ | | |__ linhas na tela\n" +"# V V | |______ colunas na tela\n" +"# | | |__________ máximo de \"interações\"\n" +"# | |_________________ faixa no eixo y\n" +"# |____________________________ faixa no eixo x" #: ../../faq/programming.rst:771 msgid "Don't try this at home, kids!" @@ -1174,12 +1689,26 @@ msgid "" "only parameters. Its documentation looks like this::" msgstr "" "Uma barra na lista de argumentos de uma função indica que os parâmetros " -"anteriores a ela são somente-posicionais. Os parâmetros somente-posicionais " -"são aqueles que não têm nome utilizável externamente. Ao chamar uma função " +"anteriores a ela são somente-posicionais. Os parâmetros somente-posicionais " +"são aqueles que não têm nome utilizável externamente. Ao chamar uma função " "que aceita parâmetros somente-posicionais, os argumentos são mapeados para " "parâmetros com base apenas em sua posição. Por exemplo, :func:`divmod` é uma " "função que aceita parâmetros somente-posicionais. Sua documentação tem esta " -"forma:" +"forma::" + +#: ../../faq/programming.rst:786 +msgid "" +">>> help(divmod)\n" +"Help on built-in function divmod in module builtins:\n" +"\n" +"divmod(x, y, /)\n" +" Return the tuple (x//y, x%y). Invariant: div*y + mod == x." +msgstr "" +">>> help(divmod)\n" +"Help on built-in function divmod in module builtins:\n" +"\n" +"divmod(x, y, /)\n" +" Return the tuple (x//y, x%y). Invariant: div*y + mod == x." #: ../../faq/programming.rst:792 msgid "" @@ -1191,13 +1720,25 @@ msgstr "" "são somente-posicionais. Assim, chamar :func:`divmod` com argumentos " "nomeados levaria a um erro::" +#: ../../faq/programming.rst:796 +msgid "" +">>> divmod(x=3, y=4)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: divmod() takes no keyword arguments" +msgstr "" +">>> divmod(x=3, y=4)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: divmod() takes no keyword arguments" + #: ../../faq/programming.rst:803 msgid "Numbers and strings" -msgstr "Números e Strings" +msgstr "Números e strings" #: ../../faq/programming.rst:806 msgid "How do I specify hexadecimal and octal integers?" -msgstr "Como faço para especificar números inteiros hexadecimais e octal?" +msgstr "Como faço para especificar números inteiros hexadecimais e octais?" #: ../../faq/programming.rst:808 msgid "" @@ -1209,6 +1750,16 @@ msgstr "" "zero e, em seguida, um \"o\" minúsculo ou maiúsculo. Por exemplo, para " "definir a variável \"a\" para o valor octal \"10\" (8 em decimal), digite::" +#: ../../faq/programming.rst:812 +msgid "" +">>> a = 0o10\n" +">>> a\n" +"8" +msgstr "" +">>> a = 0o10\n" +">>> a\n" +"8" + #: ../../faq/programming.rst:816 msgid "" "Hexadecimal is just as easy. Simply precede the hexadecimal number with a " @@ -1220,6 +1771,22 @@ msgstr "" "ser especificados em letras maiúsculas e minúsculas. Por exemplo, no " "interpretador Python::" +#: ../../faq/programming.rst:820 +msgid "" +">>> a = 0xa5\n" +">>> a\n" +"165\n" +">>> b = 0XB2\n" +">>> b\n" +"178" +msgstr "" +">>> a = 0xa5\n" +">>> a\n" +"165\n" +">>> b = 0XB2\n" +">>> b\n" +"178" + #: ../../faq/programming.rst:829 msgid "Why does -22 // 10 return -3?" msgstr "Por que -22 // 10 retorna -3?" @@ -1229,8 +1796,12 @@ msgid "" "It's primarily driven by the desire that ``i % j`` have the same sign as " "``j``. If you want that, and also want::" msgstr "" -"É principalmente direcionado pelo desejo de que ``i % j`` possui o mesmo " -"sinal que ``j``. Se quiseres isso, e também se desejares::" +"Esta dúvida é primariamente direcionado pelo desejo de que ``i % j`` tenha o " +"mesmo sinal que ``j``. Se quiser isso, e também quiser::" + +#: ../../faq/programming.rst:834 +msgid "i == (i // j) * j + (i % j)" +msgstr "i == (i // j) * j + (i % j)" #: ../../faq/programming.rst:836 msgid "" @@ -1258,24 +1829,39 @@ msgstr "" #: ../../faq/programming.rst:848 msgid "How do I get int literal attribute instead of SyntaxError?" -msgstr "" +msgstr "Como obtenho um atributo de um literal int em vez de SyntaxError?" #: ../../faq/programming.rst:850 msgid "" "Trying to lookup an ``int`` literal attribute in the normal manner gives a :" "exc:`SyntaxError` because the period is seen as a decimal point::" msgstr "" +"Tentar obter um atributo de um literal ``int`` da maneira normal retorna um :" +"exc:`SyntaxError` porque o ponto é visto como um ponto decimal::" + +#: ../../faq/programming.rst:853 +msgid "" +">>> 1.__class__\n" +" File \"\", line 1\n" +" 1.__class__\n" +" ^\n" +"SyntaxError: invalid decimal literal" +msgstr "" +">>> 1.__class__\n" +" File \"\", line 1\n" +" 1.__class__\n" +" ^\n" +"SyntaxError: invalid decimal literal" #: ../../faq/programming.rst:859 msgid "" "The solution is to separate the literal from the period with either a space " "or parentheses." -msgstr "" -"A solução é separar o literal do ponto-final com um espaço ou parênteses." +msgstr "A solução é separar o literal do ponto com um espaço ou parênteses." #: ../../faq/programming.rst:869 msgid "How do I convert a string to a number?" -msgstr "Como faço para converter uma String em um número?" +msgstr "Como faço para converter uma string em um número?" #: ../../faq/programming.rst:871 msgid "" @@ -1283,9 +1869,9 @@ msgid "" "``int('144') == 144``. Similarly, :func:`float` converts to a floating-" "point number, e.g. ``float('144') == 144.0``." msgstr "" -"Para inteiros, use o tipo embutido :func:`int`, por exemplo, ``int('144') == " -"144``. Da mesma forma, :func:`float` converterá para um valor do tipo ponto " -"flutuante, por exemplo ``float('144') == 144.0``." +"Para inteiros, use o construtor do tipo embutido :func:`int`, por exemplo, " +"``int('144') == 144``. Da mesma forma, :func:`float` converterá para um " +"número de ponto flutuante, por exemplo ``float('144') == 144.0``." #: ../../faq/programming.rst:875 msgid "" @@ -1326,12 +1912,13 @@ msgid "" "does not allow leading '0' in a decimal number (except '0')." msgstr "" ":func:`eval` também tem o efeito de interpretar números como expressões " -"Python, para que, por exemplo, ``eval('09')`` dá um erro de sintaxe porque " -"Python não permite '0' inicial em um número decimal (exceto '0')." +"Python, de forma que, por exemplo, ``eval('09')`` resulta em um erro de " +"sintaxe porque Python não permite '0' inicial em um número decimal (exceto " +"'0')." #: ../../faq/programming.rst:895 msgid "How do I convert a number to a string?" -msgstr "Como faço para converter um número numa string?" +msgstr "Como faço para converter um número em uma string?" #: ../../faq/programming.rst:897 msgid "" @@ -1342,10 +1929,16 @@ msgid "" "sections, e.g. ``\"{:04d}\".format(144)`` yields ``'0144'`` and ``\"{:.3f}\"." "format(1.0/3.0)`` yields ``'0.333'``." msgstr "" +"Para converter, por exemplo, o número ``144`` para a string ``'144'``, use o " +"construtor do tipo embutido :func:`str`. Caso queira uma representação " +"hexadecimal ou octal, use as funções embutidas :func:`hex` ou :func:`oct`. " +"Para a formatação sofisticada, veja as seções :ref:`f-strings` e :ref:" +"`formatstrings`, por exemplo, ``\"{:04d}\".format(144)`` produz ``'0144'`` e " +"``\"{:.3f}\".format(1.0/3.0)`` produz ``'0.333'``." #: ../../faq/programming.rst:906 msgid "How do I modify a string in place?" -msgstr "Como faço para modificar uma string no lugar?" +msgstr "Como faço para modificar uma string internamente?" #: ../../faq/programming.rst:908 msgid "" @@ -1355,16 +1948,61 @@ msgid "" "unicode data, try using an :class:`io.StringIO` object or the :mod:`array` " "module::" msgstr "" -"Você não poder fazer isso as Strings são objetos imutáveis. Na maioria das " -"situações, você simplesmente deve construir uma nova string a partir das " -"várias partes das quais desejas que a sua nova String tenha. No entanto, se " -"precisares de um objeto com a capacidade de modificar dados Unicode " -"internamente, tente usar a classe :class:`io.StringIO` ou o módulo :mod:" -"`array`::" +"Você não pode fazer isso porque as strings são objetos imutáveis. Na maioria " +"das situações, você simplesmente deve construir uma nova string a partir das " +"várias partes das quais deseja montá-la. No entanto, caso precise de um " +"objeto com a capacidade de modificar dados Unicode internamente, tente usar " +"a classe :class:`io.StringIO` ou o módulo :mod:`array`::" + +#: ../../faq/programming.rst:914 +msgid "" +">>> import io\n" +">>> s = \"Hello, world\"\n" +">>> sio = io.StringIO(s)\n" +">>> sio.getvalue()\n" +"'Hello, world'\n" +">>> sio.seek(7)\n" +"7\n" +">>> sio.write(\"there!\")\n" +"6\n" +">>> sio.getvalue()\n" +"'Hello, there!'\n" +"\n" +">>> import array\n" +">>> a = array.array('w', s)\n" +">>> print(a)\n" +"array('w', 'Hello, world')\n" +">>> a[0] = 'y'\n" +">>> print(a)\n" +"array('w', 'yello, world')\n" +">>> a.tounicode()\n" +"'yello, world'" +msgstr "" +">>> import io\n" +">>> s = \"Hello, world\"\n" +">>> sio = io.StringIO(s)\n" +">>> sio.getvalue()\n" +"'Hello, world'\n" +">>> sio.seek(7)\n" +"7\n" +">>> sio.write(\"there!\")\n" +"6\n" +">>> sio.getvalue()\n" +"'Hello, there!'\n" +"\n" +">>> import array\n" +">>> a = array.array('w', s)\n" +">>> print(a)\n" +"array('w', 'Hello, world')\n" +">>> a[0] = 'y'\n" +">>> print(a)\n" +"array('w', 'yello, world')\n" +">>> a.tounicode()\n" +"'yello, world'" #: ../../faq/programming.rst:938 msgid "How do I use strings to call functions/methods?" -msgstr "Como faço para invocar funções/métodos através de uma String?" +msgstr "Como faço para invocar funções/métodos através de strings?" #: ../../faq/programming.rst:940 msgid "There are various techniques." @@ -1377,14 +2015,44 @@ msgid "" "names of the functions. This is also the primary technique used to emulate " "a case construct::" msgstr "" -"A melhor forma é usar um dicionário que mapeie a Strings para funções. A " -"principal vantagem desta técnica é que as Strings não precisam combinar os " -"nomes das funções. Esta é também a principal técnica utilizada para emular " -"uma construção de maiúsculas e minúsculas ::" +"A melhor forma é usar um dicionário que mapeie strings para funções. A " +"principal vantagem desta técnica é que estas strings não precisam " +"corresponder aos nomes das funções. Esta é também a principal técnica " +"utilizada para emular uma construção de instrução estilo *case*::" + +#: ../../faq/programming.rst:947 +msgid "" +"def a():\n" +" pass\n" +"\n" +"def b():\n" +" pass\n" +"\n" +"dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs\n" +"\n" +"dispatch[get_input()]() # Note trailing parens to call function" +msgstr "" +"def a():\n" +" pass\n" +"\n" +"def b():\n" +" pass\n" +"\n" +"dispatch = {'go': a, 'stop': b} # Note a falta de parênteses para funções\n" +"\n" +"dispatch[get_input()]() # Note os parênteses ao final para chamar a função" #: ../../faq/programming.rst:957 msgid "Use the built-in function :func:`getattr`::" -msgstr "Utilize a função embutida :func:`getattr`::" +msgstr "Usar a função embutida :func:`getattr`::" + +#: ../../faq/programming.rst:959 +msgid "" +"import foo\n" +"getattr(foo, 'bar')()" +msgstr "" +"import foo\n" +"getattr(foo, 'bar')()" #: ../../faq/programming.rst:962 msgid "" @@ -1398,17 +2066,57 @@ msgstr "" msgid "This is used in several places in the standard library, like this::" msgstr "A mesma é usado em vários lugares na biblioteca padrão, como este::" +#: ../../faq/programming.rst:967 +msgid "" +"class Foo:\n" +" def do_foo(self):\n" +" ...\n" +"\n" +" def do_bar(self):\n" +" ...\n" +"\n" +"f = getattr(foo_instance, 'do_' + opname)\n" +"f()" +msgstr "" +"class Foo:\n" +" def faz_foo(self):\n" +" ...\n" +"\n" +" def faz_bar(self):\n" +" ...\n" +"\n" +"f = getattr(instancia_foo, 'faz_' + opname)\n" +"f()" + #: ../../faq/programming.rst:978 msgid "Use :func:`locals` to resolve the function name::" msgstr "Use :func:`locals` para determinar o nome da função::" +#: ../../faq/programming.rst:980 +msgid "" +"def myFunc():\n" +" print(\"hello\")\n" +"\n" +"fname = \"myFunc\"\n" +"\n" +"f = locals()[fname]\n" +"f()" +msgstr "" +"def minhaFunc():\n" +" print(\"hello\")\n" +"\n" +"fname = \"minhaFunc\"\n" +"\n" +"f = locals()[fname]\n" +"f()" + #: ../../faq/programming.rst:990 msgid "" -"Is there an equivalent to Perl's chomp() for removing trailing newlines from " -"strings?" +"Is there an equivalent to Perl's ``chomp()`` for removing trailing newlines " +"from strings?" msgstr "" -"Existe um equivalente em Perl ``chomp()`` para remover linhas novas de uma " -"String?" +"Existe um equivalente em Perl ``chomp()`` para remover linhas novas ao final " +"de strings?" #: ../../faq/programming.rst:992 msgid "" @@ -1418,11 +2126,25 @@ msgid "" "empty lines at the end, the line terminators for all the blank lines will be " "removed::" msgstr "" -"Podes utilizar ``S.rstrip(\"\\r\\n\")`` para remover todas as ocorrência de " -"qualquer terminador de linha que esteja no final da string ``S`` sem remover " -"os espaços em branco. Se a string ``S`` representar mais de uma linha, " -"contendo várias linhas vazias no final, os terminadores de linha de todas " -"linhas em branco serão removidos::" +"Pode-se utilizar ``S.rstrip(\"\\r\\n\")`` para remover todas as ocorrência " +"de qualquer terminador de linha que esteja no final da string ``S`` sem " +"remover os espaços em branco. Se a string ``S`` representar mais de uma " +"linha, contendo várias linhas vazias no final, os terminadores de linha de " +"todas linhas em branco serão removidos::" + +#: ../../faq/programming.rst:998 +msgid "" +">>> lines = (\"line 1 \\r\\n\"\n" +"... \"\\r\\n\"\n" +"... \"\\r\\n\")\n" +">>> lines.rstrip(\"\\n\\r\")\n" +"'line 1 '" +msgstr "" +">>> linhas = (\"linha 1 \\r\\n\"\n" +"... \"\\r\\n\"\n" +"... \"\\r\\n\")\n" +">>> linhas.rstrip(\"\\n\\r\")\n" +"'linha 1 '" #: ../../faq/programming.rst:1004 msgid "" @@ -1433,8 +2155,8 @@ msgstr "" "rstrip()`` dessa maneira funciona bem." #: ../../faq/programming.rst:1009 -msgid "Is there a scanf() or sscanf() equivalent?" -msgstr "Existe uma função scanf() ou sscanf() ou algo equivalente?" +msgid "Is there a ``scanf()`` or ``sscanf()`` equivalent?" +msgstr "Existe uma função ``scanf()`` ou ``sscanf()`` ou algo equivalente?" #: ../../faq/programming.rst:1011 msgid "Not as such." @@ -1445,15 +2167,15 @@ msgid "" "For simple input parsing, the easiest approach is usually to split the line " "into whitespace-delimited words using the :meth:`~str.split` method of " "string objects and then convert decimal strings to numeric values using :" -"func:`int` or :func:`float`. :meth:`!split()` supports an optional \"sep\" " +"func:`int` or :func:`float`. :meth:`!split` supports an optional \"sep\" " "parameter which is useful if the line uses something other than whitespace " "as a separator." msgstr "" "Para a análise de entrada simples, a abordagem mais fácil geralmente é " "dividir a linha em palavras delimitadas por espaços em branco usando o " -"método :meth:`str.split` de objetos Strings e, em seguida, converter as " -"Strings decimais para valores numéricos usando a função :func:`int` ou a " -"função :func:`float`. A função :meth:`!split()` aceita um parâmetro \"sep\" " +"método :meth:`~str.split` de objetos strings e, em seguida, converter as " +"strings decimais para valores numéricos usando a função :func:`int` ou a " +"função :func:`float`. O método :meth:`!split` aceita um parâmetro \"sep\" " "opcional que é útil se a linha utilizar algo diferente de espaço em branco " "como separador." @@ -1462,10 +2184,14 @@ msgid "" "For more complicated input parsing, regular expressions are more powerful " "than C's ``sscanf`` and better suited for the task." msgstr "" +"Para análise de entradas de textos mais complicadas, as expressões regulares " +"são mais poderosas do que a ``sscanf`` do C e mais adequadas para essa " +"tarefa." #: ../../faq/programming.rst:1024 -msgid "What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?" -msgstr "O que significa o erro 'UnicodeDecodeError' ou 'UnicodeEncodeError'?" +msgid "What does ``UnicodeDecodeError`` or ``UnicodeEncodeError`` error mean?" +msgstr "" +"O que significa o erro ``UnicodeDecodeError`` ou ``UnicodeEncodeError``?" #: ../../faq/programming.rst:1026 msgid "See the :ref:`unicode-howto`." @@ -1473,31 +2199,77 @@ msgstr "Consulte :ref:`unicode-howto`." #: ../../faq/programming.rst:1032 msgid "Can I end a raw string with an odd number of backslashes?" -msgstr "" +msgstr "Posso terminar uma string bruta com um número ímpar de contrabarras?" #: ../../faq/programming.rst:1034 msgid "" "A raw string ending with an odd number of backslashes will escape the " "string's quote::" msgstr "" +"Uma string bruta terminando com um número ímpar de contrabarras vai escapar " +"as aspas da string::" + +#: ../../faq/programming.rst:1036 +msgid "" +">>> r'C:\\this\\will\\not\\work\\'\n" +" File \"\", line 1\n" +" r'C:\\this\\will\\not\\work\\'\n" +" ^\n" +"SyntaxError: unterminated string literal (detected at line 1)" +msgstr "" +">>> r'C:\\isso\\não\\vai\\funcionar\\'\n" +" File \"\", line 1\n" +" r'C:\\isso\\não\\vai\\funcionar\\'\n" +" ^\n" +"SyntaxError: unterminated string literal (detected at line 1)" #: ../../faq/programming.rst:1042 msgid "" "There are several workarounds for this. One is to use regular strings and " "double the backslashes::" msgstr "" +"Há várias soluções alternativas para isso. Uma delas é usar strings " +"regulares e duplicar as contrabarras::" + +#: ../../faq/programming.rst:1045 +msgid "" +">>> 'C:\\\\this\\\\will\\\\work\\\\'\n" +"'C:\\\\this\\\\will\\\\work\\\\'" +msgstr "" +">>> 'C:\\\\isso\\\\vai\\\\funcionar\\\\'\n" +"'C:\\\\isso\\\\vai\\\\funcionar\\\\'" #: ../../faq/programming.rst:1048 msgid "" "Another is to concatenate a regular string containing an escaped backslash " "to the raw string::" msgstr "" +"Outra é concatenar uma string regular contendo uma contrabarra de escape à " +"string bruta::" + +#: ../../faq/programming.rst:1051 +msgid "" +">>> r'C:\\this\\will\\work' '\\\\'\n" +"'C:\\\\this\\\\will\\\\work\\\\'" +msgstr "" +">>> r'C:\\isso\\vai\\funcionar' '\\\\'\n" +"'C:\\\\isso\\\\vai\\\\funcionar\\\\'" #: ../../faq/programming.rst:1054 msgid "" "It is also possible to use :func:`os.path.join` to append a backslash on " "Windows::" msgstr "" +"Também é possível usar :func:`os.path.join` para acrescentar uma contrabarra " +"no Windows::" + +#: ../../faq/programming.rst:1056 +msgid "" +">>> os.path.join(r'C:\\this\\will\\work', '')\n" +"'C:\\\\this\\\\will\\\\work\\\\'" +msgstr "" +">>> os.path.join(r'C:\\isso\\vai\\funcionar', '')\n" +"'C:\\\\isso\\\\vai\\\\funcionar\\\\'" #: ../../faq/programming.rst:1059 msgid "" @@ -1506,10 +2278,23 @@ msgid "" "the value of the raw string. That is, the backslash remains present in the " "value of the raw string::" msgstr "" +"Note que, embora uma contrabarra vai \"escapar\" uma aspa para fins de " +"determinar onde a string bruta termina, nenhum escape ocorre ao interpretar " +"o valor da string bruta. Ou seja, a contrabarra permanece presente no valor " +"da string bruta::" + +#: ../../faq/programming.rst:1064 +msgid "" +">>> r'backslash\\'preserved'\n" +"\"backslash\\\\'preserved\"" +msgstr "" +">>> r'contrabarra\\'preservada'\n" +"\"contrabarra\\\\'preservada\"" #: ../../faq/programming.rst:1067 msgid "Also see the specification in the :ref:`language reference `." msgstr "" +"Veja também a especificação na :ref:`referência da linguagem `." #: ../../faq/programming.rst:1070 msgid "Performance" @@ -1534,15 +2319,15 @@ msgid "" "focuses on :term:`CPython`." msgstr "" "As características da desempenho podem variar conforme a implementação do " -"Python. Esse FAQ foca em :term:`CPython`." +"Python. Esse FAQ se concentra no :term:`CPython`." #: ../../faq/programming.rst:1080 msgid "" "Behaviour can vary across operating systems, especially when talking about I/" "O or multi-threading." msgstr "" -"O comportamento pode variar em cada Sistemas Operacionais, especialmente " -"quando estivermos tratando de I/o ou multi-threading." +"O comportamento pode variar em cada sistemas operacionais, especialmente " +"quando estivermos tratando de E/S ou multi-threading." #: ../../faq/programming.rst:1082 msgid "" @@ -1557,7 +2342,7 @@ msgid "" "Writing benchmark scripts will allow you to iterate quickly when searching " "for improvements (see the :mod:`timeit` module)." msgstr "" -"Escrever Scripts de benchmark permitirá iterar rapidamente buscando " +"Escrever scripts de benchmark permitirá iterar rapidamente buscando " "melhorias (veja o módulo :mod:`timeit`)." #: ../../faq/programming.rst:1086 @@ -1595,7 +2380,7 @@ msgid "" "Use the right data structures. Study documentation for the :ref:`bltin-" "types` and the :mod:`collections` module." msgstr "" -"Use as estruturas de dados corretas. Documentação de estudo para :ref:`bltin-" +"Usar as estruturas de dados corretas. Estude a documentação para :ref:`bltin-" "types` e o módulo :mod:`collections`." #: ../../faq/programming.rst:1101 @@ -1609,7 +2394,7 @@ msgid "" "advanced usage)." msgstr "" "Quando a biblioteca padrão fornecer um tipo primitivo para fazer algo, é " -"provável (embora não garantido) que este seja mais rápido do que qualquer " +"provável (embora não garantido) que isso seja mais rápido do que qualquer " "alternativa que possa surgir. Isso geralmente é verdade para os tipos " "primitivos escritos em C, como os embutidos e alguns tipos de extensão. Por " "exemplo, certifique-se de usar o método embutido :meth:`list.sort` ou a " @@ -1641,6 +2426,14 @@ msgid "" "skills, you can also :ref:`write a C extension module ` " "yourself." msgstr "" +"Se você atingiu o limite do que Python puro pode permitir, existem " +"ferramentas para levá-lo mais longe. Por exemplo, o `Cython `_ pode compilar uma versão ligeiramente modificada do código Python " +"numa extensão C e pode ser usado em muitas plataformas diferentes. O Cython " +"pode tirar proveito da compilação (e anotações tipo opcional) para tornar o " +"seu código significativamente mais rápido do que quando interpretado. Se " +"você está confiante em suas habilidades de programação C, também pode :ref:" +"`escrever um módulo de extensão de C `." #: ../../faq/programming.rst:1125 msgid "" @@ -1652,7 +2445,7 @@ msgstr "" #: ../../faq/programming.rst:1131 msgid "What is the most efficient way to concatenate many strings together?" -msgstr "Qual é a maneira mais eficiente de concatenar muitas Strings?" +msgstr "Qual é a maneira mais eficiente de concatenar muitas strings?" #: ../../faq/programming.rst:1133 msgid "" @@ -1661,10 +2454,10 @@ msgid "" "creates a new object. In the general case, the total runtime cost is " "quadratic in the total string length." msgstr "" -"A classe :class:`str` e a classe :class:`bytes` são objetos imutáveis, " -"portanto, concatenar muitas Strings em é ineficiente, pois cada concatenação " -"criará um novo objeto String. No caso geral, o custo total do tempo de " -"execução é quadrático no comprimento total da String." +"Objetos das classes :class:`str` e :class:`bytes` são imutáveis e, portanto, " +"concatenar muitas strings é ineficiente, pois cada concatenação criará um " +"novo objeto. No caso geral, o custo total do tempo de execução é quadrático " +"no comprimento total da string." #: ../../faq/programming.rst:1138 msgid "" @@ -1674,6 +2467,18 @@ msgstr "" "Para juntar vários objetos :class:`str`, a linguagem recomendada colocá-los " "numa lista e invocar o método :meth:`str.join`::" +#: ../../faq/programming.rst:1141 +msgid "" +"chunks = []\n" +"for s in my_strings:\n" +" chunks.append(s)\n" +"result = ''.join(chunks)" +msgstr "" +"chunks = []\n" +"for s in my_strings:\n" +" chunks.append(s)\n" +"result = ''.join(chunks)" + #: ../../faq/programming.rst:1146 msgid "(another reasonably efficient idiom is to use :class:`io.StringIO`)" msgstr "" @@ -1689,9 +2494,19 @@ msgstr "" "uma classe :class:`bytearray` usando a concatenação local (com o operador " "``+=``)::" +#: ../../faq/programming.rst:1151 +msgid "" +"result = bytearray()\n" +"for b in my_bytes_objects:\n" +" result += b" +msgstr "" +"result = bytearray()\n" +"for b in my_bytes_objects:\n" +" result += b" + #: ../../faq/programming.rst:1157 msgid "Sequences (Tuples/Lists)" -msgstr "Sequencias (Tuples/Lists)" +msgstr "Sequencias (Tuplas/Listas)" #: ../../faq/programming.rst:1160 msgid "How do I convert between tuples and lists?" @@ -1742,6 +2557,11 @@ msgid "" "(next to last) index and so forth. Think of ``seq[-n]`` as the same as " "``seq[len(seq)-n]``." msgstr "" +"Sequências em Python são indexadas com números positivos e números " +"negativos. Para números positivos, 0 é o índice do primeiro elemento, 1 é o " +"índice do segundo elemento e assim por diante. Para números negativos, -1 é " +"índice do último elemento e -2 é o penúltimo (anterior ao último) índice e " +"assim por diante. Pense em ``seq[-n]`` como o mesmo que ``seq[len(seq)-n]``." #: ../../faq/programming.rst:1184 msgid "" @@ -1749,6 +2569,9 @@ msgid "" "all of the string except for its last character, which is useful for " "removing the trailing newline from a string." msgstr "" +"Usar índices negativos pode ser muito conveniente. Por exemplo, ``S[:-1]`` é " +"a string inteira exceto pelo seu último caractere, o que é útil para remover " +"o caractere de nova linha no final de uma string." #: ../../faq/programming.rst:1190 msgid "How do I iterate over a sequence in reverse order?" @@ -1758,6 +2581,14 @@ msgstr "Como que eu itero uma sequência na ordem inversa?" msgid "Use the :func:`reversed` built-in function::" msgstr "Use a função embutida :func:`reversed`::" +#: ../../faq/programming.rst:1194 +msgid "" +"for x in reversed(sequence):\n" +" ... # do something with x ..." +msgstr "" +"for x in reversed(sequence):\n" +" ... # faz alguma coisa com x ..." + #: ../../faq/programming.rst:1197 msgid "" "This won't touch your original sequence, but build a new copy with reversed " @@ -1768,11 +2599,13 @@ msgstr "" #: ../../faq/programming.rst:1202 msgid "How do you remove duplicates from a list?" -msgstr "Como que remove itens duplicados de uma lista?" +msgstr "Como que removo itens duplicados de uma lista?" #: ../../faq/programming.rst:1204 msgid "See the Python Cookbook for a long discussion of many ways to do this:" msgstr "" +"Veja o Python Cookbook para uma longa discussão de várias formas de fazer " +"isso:" #: ../../faq/programming.rst:1206 msgid "https://code.activestate.com/recipes/52560/" @@ -1783,6 +2616,28 @@ msgid "" "If you don't mind reordering the list, sort it and then scan from the end of " "the list, deleting duplicates as you go::" msgstr "" +"Se você não se importar em reordenar a lista, ordene-a e depois examine a " +"partir do final da lista, excluindo duplicatas conforme avança::" + +#: ../../faq/programming.rst:1211 +msgid "" +"if mylist:\n" +" mylist.sort()\n" +" last = mylist[-1]\n" +" for i in range(len(mylist)-2, -1, -1):\n" +" if last == mylist[i]:\n" +" del mylist[i]\n" +" else:\n" +" last = mylist[i]" +msgstr "" +"if mylist:\n" +" mylist.sort()\n" +" last = mylist[-1]\n" +" for i in range(len(mylist)-2, -1, -1):\n" +" if last == mylist[i]:\n" +" del mylist[i]\n" +" else:\n" +" last = mylist[i]" #: ../../faq/programming.rst:1220 msgid "" @@ -1793,6 +2648,10 @@ msgstr "" "(isto é, eles são todos :term:`hasheáveis `) isso é muitas vezes " "mais rápido ::" +#: ../../faq/programming.rst:1223 +msgid "mylist = list(set(mylist))" +msgstr "mylist = list(set(mylist))" + #: ../../faq/programming.rst:1225 msgid "" "This converts the list into a set, thereby removing duplicates, and then " @@ -1803,7 +2662,7 @@ msgstr "" #: ../../faq/programming.rst:1230 msgid "How do you remove multiple items from a list" -msgstr "Como remover múltiplos itens de uma lista" +msgstr "Como remover múltiplos itens de uma lista?" #: ../../faq/programming.rst:1232 msgid "" @@ -1812,6 +2671,20 @@ msgid "" "replacement with an implicit or explicit forward iteration. Here are three " "variations.::" msgstr "" +"Assim como para remover valores duplicados, explicitamente iterar em uma " +"lista reversa com uma condição de remoção é uma possibilidade. Contudo, é " +"mais fácil e rápido usar substituição de fatias com um iteração reversa " +"implícita ou explícita. Aqui estão três variações.::" + +#: ../../faq/programming.rst:1237 +msgid "" +"mylist[:] = filter(keep_function, mylist)\n" +"mylist[:] = (x for x in mylist if keep_condition)\n" +"mylist[:] = [x for x in mylist if keep_condition]" +msgstr "" +"mylist[:] = filter(keep_function, mylist)\n" +"mylist[:] = (x for x in mylist if keep_condition)\n" +"mylist[:] = [x for x in mylist if keep_condition]" #: ../../faq/programming.rst:1241 msgid "The list comprehension may be fastest." @@ -1825,12 +2698,19 @@ msgstr "Como fazer um vetor em Python?" msgid "Use a list::" msgstr "Utilize uma lista::" +#: ../../faq/programming.rst:1249 +msgid "[\"this\", 1, \"is\", \"an\", \"array\"]" +msgstr "[\"isto\", 1, \"é\", \"um\", \"vetor\"]" + #: ../../faq/programming.rst:1251 msgid "" "Lists are equivalent to C or Pascal arrays in their time complexity; the " "primary difference is that a Python list can contain objects of many " "different types." msgstr "" +"Listas são equivalentes aos vetores de C ou Pascal em termos de complexidade " +"de tempo; a diferença primária é que uma lista em Python pode conter objetos " +"de tipos diferentes." #: ../../faq/programming.rst:1254 msgid "" @@ -1839,11 +2719,22 @@ msgid "" "lists. Also note that `NumPy `_ and other third party " "packages define array-like structures with various characteristics as well." msgstr "" +"O módulo ``array`` também provê métodos para criar vetores de tipos fixos " +"com representações compactas, mas eles são mais lentos para indexar que " +"listas. Observe também que `NumPy `_ e outros pacotes " +"de terceiros definem estruturas semelhantes a arrays com várias " +"características." #: ../../faq/programming.rst:1260 msgid "" "To get Lisp-style linked lists, you can emulate *cons cells* using tuples::" msgstr "" +"Para obter listas ligadas no estilo Lisp, você pode emular *células cons* " +"usando tuplas::" + +#: ../../faq/programming.rst:1262 +msgid "lisp_list = (\"like\", (\"this\", (\"example\", None) ) )" +msgstr "lista_lisp = (\"como\", (\"este\", (\"exemplo\", None) ) )" #: ../../faq/programming.rst:1264 msgid "" @@ -1852,6 +2743,10 @@ msgid "" "``lisp_list[1]``. Only do this if you're sure you really need to, because " "it's usually a lot slower than using Python lists." msgstr "" +"Se mutabilidade é desejada, você pode usar listas no lugar de tuplas. Aqui " +"o análogo de um *car* Lisp é ``lista_lisp[0]`` e o análogo de *cdr* é " +"``lista_lisp[1]``. Faça isso somente se você tem certeza que precisa disso, " +"porque isso é usualmente muito mais lento que usar listas Python." #: ../../faq/programming.rst:1273 msgid "How do I create a multidimensional list?" @@ -1859,16 +2754,38 @@ msgstr "Como faço para criar uma lista multidimensional?" #: ../../faq/programming.rst:1275 msgid "You probably tried to make a multidimensional array like this::" -msgstr "Você provavelmente tentou fazer um Array multidimensional como isso::" +msgstr "Você provavelmente tentou fazer um vetor multidimensional assim::" + +#: ../../faq/programming.rst:1277 +msgid ">>> A = [[None] * 2] * 3" +msgstr ">>> A = [[None] * 2] * 3" #: ../../faq/programming.rst:1279 msgid "This looks correct if you print it:" msgstr "Isso parece correto se você imprimir:" +#: ../../faq/programming.rst:1285 +msgid "" +">>> A\n" +"[[None, None], [None, None], [None, None]]" +msgstr "" +">>> A\n" +"[[None, None], [None, None], [None, None]]" + #: ../../faq/programming.rst:1290 msgid "But when you assign a value, it shows up in multiple places:" msgstr "Mas quando atribuíres um valor, o mesmo aparecerá em vários lugares:" +#: ../../faq/programming.rst:1296 +msgid "" +">>> A[0][0] = 5\n" +">>> A\n" +"[[5, None], [5, None], [5, None]]" +msgstr "" +">>> A[0][0] = 5\n" +">>> A\n" +"[[5, None], [5, None], [5, None]]" + #: ../../faq/programming.rst:1302 msgid "" "The reason is that replicating a list with ``*`` doesn't create copies, it " @@ -1886,44 +2803,92 @@ msgid "" "The suggested approach is to create a list of the desired length first and " "then fill in each element with a newly created list::" msgstr "" -"A abordagem sugerida é criar uma lista de comprimento desejado primeiro e, " -"em seguida, preencher cada elemento com uma lista recém-criada::" +"A abordagem sugerida é criar uma lista com o comprimento desejado primeiro " +"e, em seguida, preencher cada elemento com uma lista recém-criada::" + +#: ../../faq/programming.rst:1310 +msgid "" +"A = [None] * 3\n" +"for i in range(3):\n" +" A[i] = [None] * 2" +msgstr "" +"A = [None] * 3\n" +"for i in range(3):\n" +" A[i] = [None] * 2" #: ../../faq/programming.rst:1314 msgid "" "This generates a list containing 3 different lists of length two. You can " "also use a list comprehension::" msgstr "" -"Isso gera uma lista contendo 3 listas diferentes contendo 2 itens cadas. " -"Você também pode usar uma compreensão de lista::" +"Isso gera uma lista contendo 3 listas diferentes contendo 2 itens cada. Você " +"também pode usar uma compreensão de lista::" + +#: ../../faq/programming.rst:1317 +msgid "" +"w, h = 2, 3\n" +"A = [[None] * w for i in range(h)]" +msgstr "" +"w, h = 2, 3\n" +"A = [[None] * w for i in range(h)]" #: ../../faq/programming.rst:1320 msgid "" "Or, you can use an extension that provides a matrix datatype; `NumPy " "`_ is the best known." msgstr "" +"Ou você pode usar uma extensão que provê um tipo de dados matrix; `NumPy " +"`_ é o mais conhecido." #: ../../faq/programming.rst:1325 msgid "How do I apply a method or function to a sequence of objects?" -msgstr "" +msgstr "Como eu aplico um método ou função para uma sequência de objetos?" #: ../../faq/programming.rst:1327 msgid "" "To call a method or function and accumulate the return values is a list, a :" "term:`list comprehension` is an elegant solution::" msgstr "" +"Para chamar um método ou função e acumular os valores retornados como uma " +"lista, uma :term:`compreensão de lista` é uma solução elegante::" + +#: ../../faq/programming.rst:1330 +msgid "" +"result = [obj.method() for obj in mylist]\n" +"\n" +"result = [function(obj) for obj in mylist]" +msgstr "" +"result = [obj.method() for obj in mylist]\n" +"\n" +"result = [function(obj) for obj in mylist]" #: ../../faq/programming.rst:1334 msgid "" "To just run the method or function without saving the return values, a " "plain :keyword:`for` loop will suffice::" msgstr "" +"Para apenas chamar o método ou função sem salvar os valores retornados, um " +"laço :keyword:`for` será o suficiente::" + +#: ../../faq/programming.rst:1337 +msgid "" +"for obj in mylist:\n" +" obj.method()\n" +"\n" +"for obj in mylist:\n" +" function(obj)" +msgstr "" +"for obj in mylist:\n" +" obj.method()\n" +"\n" +"for obj in mylist:\n" +" function(obj)" #: ../../faq/programming.rst:1346 msgid "" "Why does a_tuple[i] += ['item'] raise an exception when the addition works?" msgstr "" -"Porque a_tuple[i] += ['item'] levanta uma exceção quando a adição funciona?" +"Porque uma_tupla[i] += ['item'] levanta uma exceção quando a adição funciona?" #: ../../faq/programming.rst:1348 msgid "" @@ -1931,6 +2896,9 @@ msgid "" "operators are *assignment* operators, and the difference between mutable and " "immutable objects in Python." msgstr "" +"Isso se deve a uma combinação do fato de que os operadores de atribuição " +"aumentada são operadores de *atribuição* e à diferença entre objetos " +"mutáveis e imutáveis no Python." #: ../../faq/programming.rst:1352 msgid "" @@ -1938,11 +2906,28 @@ msgid "" "applied to elements of a tuple that point to mutable objects, but we'll use " "a ``list`` and ``+=`` as our exemplar." msgstr "" +"Essa discussão se aplica em geral quando operadores de atribuição aumentada " +"são aplicados a elementos de uma tupla que aponta para objetos mutáveis, mas " +"usaremos uma ``lista`` e ``+=`` como exemplo." #: ../../faq/programming.rst:1356 msgid "If you wrote::" msgstr "Se você escrever::" +#: ../../faq/programming.rst:1358 +msgid "" +">>> a_tuple = (1, 2)\n" +">>> a_tuple[0] += 1\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: 'tuple' object does not support item assignment" +msgstr "" +">>> a_tuple = (1, 2)\n" +">>> a_tuple[0] += 1\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: 'tuple' object does not support item assignment" + #: ../../faq/programming.rst:1364 msgid "" "The reason for the exception should be immediately clear: ``1`` is added to " @@ -1951,6 +2936,11 @@ msgid "" "to element ``0`` of the tuple, we get an error because we can't change what " "an element of a tuple points to." msgstr "" +"O motivo da exceção deve ser imediatamente claro: ``1`` é adicionado ao " +"objeto que ``a_tuple[0]`` aponta para (``1``), produzindo o objeto de " +"resultado, ``2``, mas quando tentamos atribuir o resultado do cálculo, " +"``2``, ao elemento ``0`` da tupla, recebemos um erro porque não podemos " +"alterar o que um elemento de uma tupla aponta." #: ../../faq/programming.rst:1370 msgid "" @@ -1960,23 +2950,61 @@ msgstr "" "Por baixo, o que a instrução de atribuição aumentada está fazendo é " "aproximadamente isso::" +#: ../../faq/programming.rst:1373 +msgid "" +">>> result = a_tuple[0] + 1\n" +">>> a_tuple[0] = result\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: 'tuple' object does not support item assignment" +msgstr "" +">>> result = a_tuple[0] + 1\n" +">>> a_tuple[0] = result\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: 'tuple' object does not support item assignment" + #: ../../faq/programming.rst:1379 msgid "" "It is the assignment part of the operation that produces the error, since a " "tuple is immutable." msgstr "" -"A parte da atribuição da operação que produz o erro, já que a tupla é " +"Essa é a parte da atribuição da operação que produz o erro, já que a tupla é " "imutável." #: ../../faq/programming.rst:1382 msgid "When you write something like::" msgstr "Quando você escreve algo como::" +#: ../../faq/programming.rst:1384 +msgid "" +">>> a_tuple = (['foo'], 'bar')\n" +">>> a_tuple[0] += ['item']\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: 'tuple' object does not support item assignment" +msgstr "" +">>> a_tuple = (['foo'], 'bar')\n" +">>> a_tuple[0] += ['item']\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: 'tuple' object does not support item assignment" + #: ../../faq/programming.rst:1390 msgid "" "The exception is a bit more surprising, and even more surprising is the fact " "that even though there was an error, the append worked::" msgstr "" +"A exceção é um pouco mais surpreendente, e ainda mais surpreendente é o fato " +"de que, embora tenha havido um erro, o acréscimo à lista funcionou::" + +#: ../../faq/programming.rst:1393 +msgid "" +">>> a_tuple[0]\n" +"['foo', 'item']" +msgstr "" +">>> a_tuple[0]\n" +"['foo', 'item']" #: ../../faq/programming.rst:1396 msgid "" @@ -1987,11 +3015,38 @@ msgid "" "to calling :meth:`!extend` on the list and returning the list. That's why " "we say that for lists, ``+=`` is a \"shorthand\" for :meth:`!list.extend`::" msgstr "" +"Para entender por que isso acontece, você precisa saber que (a) se um objeto " +"implementa um método mágico :meth:`~object.__iadd__`, ele é chamado quando a " +"atribuição aumentada ``+=`` é executada, e seu valor de retorno é o que é " +"usado na instrução de atribuição; e (b) para listas, :meth:`!__iadd__` é " +"equivalente a chamar :meth:`!extend` na lista e retornar a lista. É por isso " +"que dizemos que, para listas, ``+=`` é uma “abreviação” para :meth:`!list." +"extend`::" + +#: ../../faq/programming.rst:1404 +msgid "" +">>> a_list = []\n" +">>> a_list += [1]\n" +">>> a_list\n" +"[1]" +msgstr "" +">>> a_list = []\n" +">>> a_list += [1]\n" +">>> a_list\n" +"[1]" #: ../../faq/programming.rst:1409 msgid "This is equivalent to::" msgstr "Isso equivale a::" +#: ../../faq/programming.rst:1411 +msgid "" +">>> result = a_list.__iadd__([1])\n" +">>> a_list = result" +msgstr "" +">>> result = a_list.__iadd__([1])\n" +">>> a_list = result" + #: ../../faq/programming.rst:1414 msgid "" "The object pointed to by a_list has been mutated, and the pointer to the " @@ -1999,10 +3054,29 @@ msgid "" "assignment is a no-op, since it is a pointer to the same object that " "``a_list`` was previously pointing to, but the assignment still happens." msgstr "" +"O objeto apontado por a_list foi alterado e o ponteiro para o objeto " +"alterado é atribuído novamente a ``a_list``. O resultado final da atribuição " +"é um no-op, pois é um ponteiro para o mesmo objeto para o qual ``a_list`` " +"estava apontando anteriormente, mas a atribuição ainda acontece." #: ../../faq/programming.rst:1419 msgid "Thus, in our tuple example what is happening is equivalent to::" msgstr "" +"Portanto, em nosso exemplo da tupla, o que está acontecendo é equivalente a:" + +#: ../../faq/programming.rst:1421 +msgid "" +">>> result = a_tuple[0].__iadd__(['item'])\n" +">>> a_tuple[0] = result\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: 'tuple' object does not support item assignment" +msgstr "" +">>> result = a_tuple[0].__iadd__(['item'])\n" +">>> a_tuple[0] = result\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: 'tuple' object does not support item assignment" #: ../../faq/programming.rst:1427 msgid "" @@ -2011,12 +3085,18 @@ msgid "" "points to, that final assignment still results in an error, because tuples " "are immutable." msgstr "" +"O :meth:`!__iadd__` é bem-sucedido e, portanto, a lista é estendida, mas " +"mesmo que ``result`` aponte para o mesmo objeto para o qual ``a_tuple[0]`` " +"já aponta, essa atribuição final ainda resulta em um erro, pois as tuplas " +"são imutáveis." #: ../../faq/programming.rst:1433 msgid "" "I want to do a complicated sort: can you do a Schwartzian Transform in " "Python?" msgstr "" +"Quero fazer uma ordenação confusa: você pode fazer uma transformação " +"schwartziana em Python?" #: ../../faq/programming.rst:1435 msgid "" @@ -2025,6 +3105,18 @@ msgid "" "value\". In Python, use the ``key`` argument for the :meth:`list.sort` " "method::" msgstr "" +"A técnica, atribuída a Randal Schwartz da comunidade Perl, ordena os " +"elementos de uma lista por uma métrica que mapeia cada elemento para seu " +"“valor de ordem”. Em Python, use o argumento ``key`` para o método :meth:" +"`list.sort`::" + +#: ../../faq/programming.rst:1439 +msgid "" +"Isorted = L[:]\n" +"Isorted.sort(key=lambda s: int(s[10:15]))" +msgstr "" +"Isorted = L[:]\n" +"Isorted.sort(key=lambda s: int(s[10:15]))" #: ../../faq/programming.rst:1444 msgid "How can I sort one list by values from another list?" @@ -2035,6 +3127,32 @@ msgid "" "Merge them into an iterator of tuples, sort the resulting list, and then " "pick out the element you want. ::" msgstr "" +"Combine-as em um iterador de tuplas, ordene a lista resultante e, em " +"seguida, escolha o elemento desejado:" + +#: ../../faq/programming.rst:1449 +msgid "" +">>> list1 = [\"what\", \"I'm\", \"sorting\", \"by\"]\n" +">>> list2 = [\"something\", \"else\", \"to\", \"sort\"]\n" +">>> pairs = zip(list1, list2)\n" +">>> pairs = sorted(pairs)\n" +">>> pairs\n" +"[(\"I'm\", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', " +"'something')]\n" +">>> result = [x[1] for x in pairs]\n" +">>> result\n" +"['else', 'sort', 'to', 'something']" +msgstr "" +">>> list1 = [\"lista\", \"usada\", \"na\", \"ordenação\"]\n" +">>> list2 = [\"alguma\", \"coisa\", \"para\", \"ordenar\"]\n" +">>> pairs = zip(list1, list2)\n" +">>> pairs = sorted(pairs)\n" +">>> pairs\n" +"[('lista', 'alguma'), ('na', 'para'), ('ordenação', 'ordenar'), ('usada', " +"'coisa')]\n" +">>> result = [x[1] for x in pairs]\n" +">>> result\n" +"['alguma', 'para', 'ordenar', 'coisa']" #: ../../faq/programming.rst:1461 msgid "Objects" @@ -2051,6 +3169,10 @@ msgid "" "which embody both the data (attributes) and code (methods) specific to a " "datatype." msgstr "" +"Uma classe é o tipo de objeto específico criado pela execução da instrução " +"class. Os objetos classe são usados como modelos para criar objetos " +"instância, que incorporam os dados (atributos) e o código (métodos) " +"específicos de um tipo de dado." #: ../../faq/programming.rst:1470 msgid "" @@ -2061,6 +3183,13 @@ msgid "" "for a mailbox, and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, " "``OutlookMailbox`` that handle various specific mailbox formats." msgstr "" +"Uma classe pode ser baseada em uma ou mais outras classes, chamadas de " +"classe(s) base(s), herdando seus atributos e métodos. Isso permite que um " +"modelo de objeto seja sucessivamente refinado por herança. Você pode ter " +"uma classe genérica ``Mailbox`` que fornece métodos básicos para uma caixa " +"de correio e subclasses como ``MboxMailbox``, ``MaildirMailbox``, " +"``OutlookMailbox`` que manipula vários formatos específicos de caixa de " +"correio." #: ../../faq/programming.rst:1479 msgid "What is a method?" @@ -2072,6 +3201,19 @@ msgid "" "name(arguments...)``. Methods are defined as functions inside the class " "definition::" msgstr "" +"Um método é uma função em algum objeto ``x`` que você normalmente chama com " +"``x.name(arguments...)``. Métodos são definidos como funções dentro da " +"definição da classe::" + +#: ../../faq/programming.rst:1485 +msgid "" +"class C:\n" +" def meth(self, arg):\n" +" return arg * 2 + self.attribute" +msgstr "" +"class C:\n" +" def meth(self, arg):\n" +" return arg * 2 + self.attribute" #: ../../faq/programming.rst:1491 msgid "What is self?" @@ -2084,6 +3226,10 @@ msgid "" "c)`` for some instance ``x`` of the class in which the definition occurs; " "the called method will think it is called as ``meth(x, a, b, c)``." msgstr "" +"Self é apenas um nome convencional para o primeiro argumento de um método. " +"Um método definido como ``meth(self, a, b, c)`` deve ser chamado com ``x." +"meth(a, b, c)`` para alguma instância ``x`` da classe em que a definição " +"ocorre; o método chamado pensará que é chamado com ``meth(x, a, b, c)``." #: ../../faq/programming.rst:1498 msgid "See also :ref:`why-self`." @@ -2106,6 +3252,12 @@ msgid "" "built-in types, e.g. ``isinstance(obj, str)`` or ``isinstance(obj, (int, " "float, complex))``." msgstr "" +"Use a função embutida :func:`isinstance(obj, cls) `. Você pode " +"verificar se um objeto é uma instância de qualquer uma de várias classes " +"fornecendo um tupla em vez de uma única classe, por exemplo, " +"``isinstance(obj, (class1, class2, ...))``, e também pode verificar se um " +"objeto é de um dos tipos embutidos no Python, por exemplo, ``isinstance(obj, " +"str)`` ou ``isinstance(obj, (int, float, complex))``." #: ../../faq/programming.rst:1511 msgid "" @@ -2114,6 +3266,66 @@ msgid "" "registered class even if hasn't directly or indirectly inherited from it. " "To test for \"true inheritance\", scan the :term:`MRO` of the class:" msgstr "" +"Observe que :func:`isinstance` também verifica se há herança virtual de uma :" +"term:`classe base abstrata`. Portanto, o teste retorna ``True`` para uma " +"classe registrada, mesmo que não tenha herdado direta ou indiretamente dela. " +"Para testar a \"herança verdadeira\", verifique o :term:`MRO` da classe:" + +#: ../../faq/programming.rst:1516 +msgid "" +"from collections.abc import Mapping\n" +"\n" +"class P:\n" +" pass\n" +"\n" +"class C(P):\n" +" pass\n" +"\n" +"Mapping.register(P)" +msgstr "" +"from collections.abc import Mapping\n" +"\n" +"class P:\n" +" pass\n" +"\n" +"class C(P):\n" +" pass\n" +"\n" +"Mapping.register(P)" + +#: ../../faq/programming.rst:1528 +msgid "" +">>> c = C()\n" +">>> isinstance(c, C) # direct\n" +"True\n" +">>> isinstance(c, P) # indirect\n" +"True\n" +">>> isinstance(c, Mapping) # virtual\n" +"True\n" +"\n" +"# Actual inheritance chain\n" +">>> type(c).__mro__\n" +"(, , )\n" +"\n" +"# Test for \"true inheritance\"\n" +">>> Mapping in type(c).__mro__\n" +"False" +msgstr "" +">>> c = C()\n" +">>> isinstance(c, C) # direta\n" +"True\n" +">>> isinstance(c, P) # indireta\n" +"True\n" +">>> isinstance(c, Mapping) # virtual\n" +"True\n" +"\n" +"# Cadeira de herança real\n" +">>> type(c).__mro__\n" +"(, , )\n" +"\n" +"# Teste pela \"herança verdadeira\"\n" +">>> Mapping in type(c).__mro__\n" +"False" #: ../../faq/programming.rst:1546 msgid "" @@ -2124,16 +3336,62 @@ msgid "" "and doing a different thing based on what class it is. For example, if you " "have a function that does something::" msgstr "" +"Observe que a maioria dos programas não usa :func:`isinstance` em classes " +"definidas pelo usuário com muita frequência. Se você estiver desenvolvendo " +"as classes por conta própria, um estilo orientado a objetos mais adequado é " +"definir métodos nas classes que encapsulam um comportamento específico, em " +"vez de verificar a classe do objeto e fazer uma coisa diferente com base na " +"classe que ele é. Por exemplo, se você tiver uma função que faz algo::" + +#: ../../faq/programming.rst:1553 +msgid "" +"def search(obj):\n" +" if isinstance(obj, Mailbox):\n" +" ... # code to search a mailbox\n" +" elif isinstance(obj, Document):\n" +" ... # code to search a document\n" +" elif ..." +msgstr "" +"def search(obj):\n" +" if isinstance(obj, Mailbox):\n" +" ... # código para pesquisar uma caixa de correio\n" +" elif isinstance(obj, documento):\n" +" ... # código para pesquisar um documento\n" +" elif ..." #: ../../faq/programming.rst:1560 msgid "" "A better approach is to define a ``search()`` method on all the classes and " "just call it::" msgstr "" +"Uma abordagem melhor é definir um método ``search()`` em todas as classes e " +"apenas chamá-lo::" + +#: ../../faq/programming.rst:1563 +msgid "" +"class Mailbox:\n" +" def search(self):\n" +" ... # code to search a mailbox\n" +"\n" +"class Document:\n" +" def search(self):\n" +" ... # code to search a document\n" +"\n" +"obj.search()" +msgstr "" +"class Mailbox:\n" +" def search(self):\n" +" ... # código para pesquisar uma caixa de correio\n" +"\n" +"class documento:\n" +" def search(self):\n" +" ... # código para pesquisar um documento\n" +"\n" +"obj.search()" #: ../../faq/programming.rst:1575 msgid "What is delegation?" -msgstr "O que é delegation?" +msgstr "O que é delegação?" #: ../../faq/programming.rst:1577 msgid "" @@ -2143,6 +3401,11 @@ msgid "" "implementation of the method you're interested in changing and delegates all " "other methods to the corresponding method of ``x``." msgstr "" +"A delegação é uma técnica orientada a objetos (também chamada de padrão de " +"projeto). Digamos que você tenha um objeto ``x`` e queira alterar o " +"comportamento de apenas um de seus métodos. Você pode criar uma nova classe " +"que forneça uma nova implementação do método que você está interessado em " +"alterar e delegar todos os outros métodos ao método correspondente de ``x``." #: ../../faq/programming.rst:1583 msgid "" @@ -2150,6 +3413,33 @@ msgid "" "following class implements a class that behaves like a file but converts all " "written data to uppercase::" msgstr "" +"Com Python, você pode implementar delegação facilmente. Por exemplo, o " +"trecho de código a seguir implementa uma classe que se comporta como um " +"arquivo, mas converte todos os dados gravados em letras maiúsculas::" + +#: ../../faq/programming.rst:1587 +msgid "" +"class UpperOut:\n" +"\n" +" def __init__(self, outfile):\n" +" self._outfile = outfile\n" +"\n" +" def write(self, s):\n" +" self._outfile.write(s.upper())\n" +"\n" +" def __getattr__(self, name):\n" +" return getattr(self._outfile, name)" +msgstr "" +"class UpperOut:\n" +"\n" +" def __init__(self, outfile):\n" +" self._outfile = outfile\n" +"\n" +" def write(self, s):\n" +" self._outfile.write(s.upper())\n" +"\n" +" def __getattr__(self, name):\n" +" return getattr(self._outfile, name)" #: ../../faq/programming.rst:1598 msgid "" @@ -2160,6 +3450,13 @@ msgid "" "__getattr__` method; consult :ref:`the language reference ` for more information about controlling attribute access." msgstr "" +"Aqui, a classe ``UpperOut`` redefine o método ``write()`` para converter o " +"argumento string em maiúsculas antes de chamar o método ``self._outfile." +"write()`` subjacente. Todos os outros métodos são delegados ao objeto " +"``self._outfile`` subjacente. A delegação é realizada por meio do método :" +"meth:`~object.__getattr__`; consulte :ref:`a referência da linguagem " +"` para obter mais informações sobre o controle de acesso a " +"atributo." #: ../../faq/programming.rst:1605 msgid "" @@ -2169,99 +3466,242 @@ msgid "" "implementation of :meth:`!__setattr__` is roughly equivalent to the " "following::" msgstr "" +"Observe que, em casos mais gerais, a delegação pode se tornar mais " +"complicada. Quando o atributo precisa ser definido e recuperado, a classe " +"deve definir um método :meth:`~object.__setattr__` também, e deve fazê-lo " +"com cuidado. A implementação básica do :meth:`!__setattr__` é " +"aproximadamente equivalente ao seguinte::" + +#: ../../faq/programming.rst:1610 +msgid "" +"class X:\n" +" ...\n" +" def __setattr__(self, name, value):\n" +" self.__dict__[name] = value\n" +" ..." +msgstr "" +"class X:\n" +" ...\n" +" def __setattr__(self, name, value):\n" +" self.__dict__[name] = value\n" +" ..." #: ../../faq/programming.rst:1616 msgid "" -"Most :meth:`!__setattr__` implementations must modify :meth:`self.__dict__ " -"` to store local state for self without causing an infinite " -"recursion." +"Many :meth:`~object.__setattr__` implementations call :meth:`!object." +"__setattr__` to set an attribute on self without causing infinite recursion::" +msgstr "" +"Muitas implementações do método :meth:`~object.__setattr__` chamam o :meth:`!" +"object.__setattr__` para definir um atributo em si mesmo sem causar recursão " +"infinita::" + +#: ../../faq/programming.rst:1619 +msgid "" +"class X:\n" +" def __setattr__(self, name, value):\n" +" # Custom logic here...\n" +" object.__setattr__(self, name, value)" +msgstr "" +"class X:\n" +" def __setattr__(self, name, value):\n" +" # Lógica personalizada aqui...\n" +" object.__setattr__(self, name, value)" + +#: ../../faq/programming.rst:1624 +msgid "" +"Alternatively, it is possible to set attributes by inserting entries into :" +"attr:`self.__dict__ ` directly." msgstr "" +"Como alternativa, é possível definir atributos inserindo entradas em :attr:" +"`self.__dict__ ` diretamente." -#: ../../faq/programming.rst:1622 +#: ../../faq/programming.rst:1629 msgid "" "How do I call a method defined in a base class from a derived class that " "extends it?" msgstr "" -"Como eu chamo um método definido numa classe base derivada de uma classe que " -"estende ela?" +"Como eu chamo um método definido em uma classe base a partir de uma classe " +"derivada que a estende?" -#: ../../faq/programming.rst:1624 +#: ../../faq/programming.rst:1631 msgid "Use the built-in :func:`super` function::" msgstr "Use a função embutida :func:`super`::" -#: ../../faq/programming.rst:1630 +#: ../../faq/programming.rst:1633 +msgid "" +"class Derived(Base):\n" +" def meth(self):\n" +" super().meth() # calls Base.meth" +msgstr "" +"class Derived(Base):\n" +" def meth(self):\n" +" super().meth() # chama Base.meth" + +#: ../../faq/programming.rst:1637 msgid "" "In the example, :func:`super` will automatically determine the instance from " "which it was called (the ``self`` value), look up the :term:`method " "resolution order` (MRO) with ``type(self).__mro__``, and return the next in " "line after ``Derived`` in the MRO: ``Base``." msgstr "" +"No exemplo, :func:`super` determinará automaticamente a instância da qual " +"foi chamado (o valor de ``self``), procura a :term:`ordem de resolução de " +"métodos` (MRO) com ``type(self).__mro__`` e então retorna o próximo na linha " +"após ``Derived`` no MRO: ``Base``." -#: ../../faq/programming.rst:1637 +#: ../../faq/programming.rst:1644 msgid "How can I organize my code to make it easier to change the base class?" msgstr "" "Como eu posso organizar meu código para facilitar a troca da classe base?" -#: ../../faq/programming.rst:1639 +#: ../../faq/programming.rst:1646 msgid "" "You could assign the base class to an alias and derive from the alias. Then " "all you have to change is the value assigned to the alias. Incidentally, " "this trick is also handy if you want to decide dynamically (e.g. depending " "on availability of resources) which base class to use. Example::" msgstr "" - -#: ../../faq/programming.rst:1654 +"Você poderia atribuir a classe base a um apelido e derivar do apelido. " +"Então, tudo o que você precisa alterar é o valor atribuído ao apelido. " +"Aliás, esse truque também é útil se você quiser decidir dinamicamente (por " +"exemplo, dependendo do disponibilidade de recursos) qual classe base usar. " +"Exemplo::" + +#: ../../faq/programming.rst:1651 +msgid "" +"class Base:\n" +" ...\n" +"\n" +"BaseAlias = Base\n" +"\n" +"class Derived(BaseAlias):\n" +" ..." +msgstr "" +"class Base:\n" +" ...\n" +"\n" +"BaseAlias = Base\n" +"\n" +"class Derived(BaseAlias):\n" +" ..." + +#: ../../faq/programming.rst:1661 msgid "How do I create static class data and static class methods?" msgstr "" +"Como faço para criar dados de classe estáticos e métodos de classe estáticos?" -#: ../../faq/programming.rst:1656 +#: ../../faq/programming.rst:1663 msgid "" "Both static data and static methods (in the sense of C++ or Java) are " "supported in Python." msgstr "" +"Tanto dados estáticos quanto métodos estáticos (no sentido de C++ ou Java) " +"são possíveis com Python." -#: ../../faq/programming.rst:1659 +#: ../../faq/programming.rst:1666 msgid "" "For static data, simply define a class attribute. To assign a new value to " "the attribute, you have to explicitly use the class name in the assignment::" msgstr "" +"Para dados estáticos, basta definir um atributo de classe. Para atribuir um " +"novo valor ao atributo, você precisa usar explicitamente o nome da classe na " +"atribuição::" + +#: ../../faq/programming.rst:1669 +msgid "" +"class C:\n" +" count = 0 # number of times C.__init__ called\n" +"\n" +" def __init__(self):\n" +" C.count = C.count + 1\n" +"\n" +" def getcount(self):\n" +" return C.count # or return self.count" +msgstr "" +"class C:\n" +" count = 0 # número de vezes que C.__init__ foi chamado\n" +"\n" +" def __init__(self):\n" +" C.count = C.count + 1\n" +"\n" +" def getcount(self):\n" +" return C.count # ou return self.count" -#: ../../faq/programming.rst:1671 +#: ../../faq/programming.rst:1678 msgid "" "``c.count`` also refers to ``C.count`` for any ``c`` such that " "``isinstance(c, C)`` holds, unless overridden by ``c`` itself or by some " "class on the base-class search path from ``c.__class__`` back to ``C``." msgstr "" +"``c.count`` também se refere a ``C.count`` para qualquer ``c`` de modo que " +"``isinstance(c, C)`` seja válido, a menos que seja substituído pelo próprio " +"``c`` ou por alguma classe no caminho de busca da classe base de ``c." +"__class__`` até ``C``." -#: ../../faq/programming.rst:1675 +#: ../../faq/programming.rst:1682 msgid "" "Caution: within a method of C, an assignment like ``self.count = 42`` " "creates a new and unrelated instance named \"count\" in ``self``'s own " "dict. Rebinding of a class-static data name must always specify the class " "whether inside a method or not::" msgstr "" +"Cuidado: em um método de C, uma atribuição como ``self.count = 42`` cria uma " +"instância nova e não-relacionada chamada \"count\" no próprio dicionário de " +"``self``. A revinculação de um nome de dado de classe estático deve sempre " +"especificar a classe, seja dentro de um método ou não::" -#: ../../faq/programming.rst:1682 +#: ../../faq/programming.rst:1687 +msgid "C.count = 314" +msgstr "C.count = 314" + +#: ../../faq/programming.rst:1689 msgid "Static methods are possible::" msgstr "Métodos estáticos são possíveis::" -#: ../../faq/programming.rst:1690 +#: ../../faq/programming.rst:1691 +msgid "" +"class C:\n" +" @staticmethod\n" +" def static(arg1, arg2, arg3):\n" +" # No 'self' parameter!\n" +" ..." +msgstr "" +"class C:\n" +" @staticmethod\n" +" def static(arg1, arg2, arg3):\n" +" # Sem parâmetro 'self'!\n" +" ..." + +#: ../../faq/programming.rst:1697 msgid "" "However, a far more straightforward way to get the effect of a static method " "is via a simple module-level function::" msgstr "" +"No entanto, uma maneira muito mais direta de obter o efeito de um método " +"estático é por meio de uma simples função em nível de módulo::" + +#: ../../faq/programming.rst:1700 +msgid "" +"def getcount():\n" +" return C.count" +msgstr "" +"def getcount():\n" +" return C.count" -#: ../../faq/programming.rst:1696 +#: ../../faq/programming.rst:1703 msgid "" "If your code is structured so as to define one class (or tightly related " "class hierarchy) per module, this supplies the desired encapsulation." msgstr "" +"Se o seu código está estruturado de modo a definir uma classe (ou uma " +"hierarquia de classes estreitamente relacionada) por módulo, isso fornecerá " +"o encapsulamento desejado." -#: ../../faq/programming.rst:1701 +#: ../../faq/programming.rst:1708 msgid "How can I overload constructors (or methods) in Python?" msgstr "Como eu posso sobrecarregar construtores (ou métodos) em Python?" -#: ../../faq/programming.rst:1703 +#: ../../faq/programming.rst:1710 msgid "" "This answer actually applies to all methods, but the question usually comes " "up first in the context of constructors." @@ -2269,37 +3709,73 @@ msgstr "" "Essa resposta na verdade se aplica para todos os métodos, mas a pergunta " "normalmente aparece primeiro no contexto de construtores." -#: ../../faq/programming.rst:1706 +#: ../../faq/programming.rst:1713 msgid "In C++ you'd write" msgstr "Em C++ escreveríamos" #: ../../faq/programming.rst:1715 msgid "" +"class C {\n" +" C() { cout << \"No arguments\\n\"; }\n" +" C(int i) { cout << \"Argument is \" << i << \"\\n\"; }\n" +"}" +msgstr "" +"class C {\n" +" C() { cout << \"Sem argumentos\\n\"; }\n" +" C(int i) { cout << \"Argumento é igual a \" << i << \"\\n\"; }\n" +"}" + +#: ../../faq/programming.rst:1722 +msgid "" "In Python you have to write a single constructor that catches all cases " "using default arguments. For example::" msgstr "" -"Em Python você tem que escrever um único construtor que pega todos os casos " +"Em Python, você tem que escrever um único construtor que pega todos os casos " "usando argumentos padrão. Por exemplo::" #: ../../faq/programming.rst:1725 +msgid "" +"class C:\n" +" def __init__(self, i=None):\n" +" if i is None:\n" +" print(\"No arguments\")\n" +" else:\n" +" print(\"Argument is\", i)" +msgstr "" +"class C:\n" +" def __init__(self, i=None):\n" +" if i is None:\n" +" print(\"Sem argumentos\")\n" +" else:\n" +" print(\"Argumento é igual a\", i)" + +#: ../../faq/programming.rst:1732 msgid "This is not entirely equivalent, but close enough in practice." msgstr "Isso não é inteiramente equivalente, mas já está bem próximo." -#: ../../faq/programming.rst:1727 +#: ../../faq/programming.rst:1734 msgid "You could also try a variable-length argument list, e.g. ::" msgstr "" "Você também pode tentar uma lista de argumentos de comprimento variável, por " "exemplo::" -#: ../../faq/programming.rst:1732 +#: ../../faq/programming.rst:1736 +msgid "" +"def __init__(self, *args):\n" +" ..." +msgstr "" +"def __init__(self, *args):\n" +" ..." + +#: ../../faq/programming.rst:1739 msgid "The same approach works for all method definitions." msgstr "A mesma abordagem funciona para todas as definições de métodos." -#: ../../faq/programming.rst:1736 +#: ../../faq/programming.rst:1743 msgid "I try to use __spam and I get an error about _SomeClassName__spam." msgstr "Eu tentei usar __spam e recebi um erro sobre _SomeClassName__spam." -#: ../../faq/programming.rst:1738 +#: ../../faq/programming.rst:1745 msgid "" "Variable names with double leading underscores are \"mangled\" to provide a " "simple but effective way to define class private variables. Any identifier " @@ -2308,21 +3784,58 @@ msgid "" "``classname`` is the current class name with any leading underscores " "stripped." msgstr "" +"Os nomes de variáveis com dois sublinhados à esquerda são \"manipulados\" " +"para fornecer uma maneira simples, mas eficaz, de definir variáveis privadas " +"de classe. Qualquer identificador no formato ``__spam`` (pelo menos dois " +"sublinhados à esquerda, no máximo um sublinhado à direita) é textualmente " +"substituído por ``_classname__spam``, em que ``classname`` é o nome da " +"classe atual sem nenhum sublinhado à esquerda." -#: ../../faq/programming.rst:1744 +#: ../../faq/programming.rst:1751 msgid "" "The identifier can be used unchanged within the class, but to access it " "outside the class, the mangled name must be used:" msgstr "" - -#: ../../faq/programming.rst:1761 +"O identificador pode ser usado normalmente dentro da classe, mas para acessá-" +"lo fora da classe, deve ser usado o nome manipulado:" + +#: ../../faq/programming.rst:1754 +msgid "" +"class A:\n" +" def __one(self):\n" +" return 1\n" +" def two(self):\n" +" return 2 * self.__one()\n" +"\n" +"class B(A):\n" +" def three(self):\n" +" return 3 * self._A__one()\n" +"\n" +"four = 4 * A()._A__one()" +msgstr "" +"class A:\n" +" def __one(self):\n" +" return 1\n" +" def two(self):\n" +" return 2 * self.__one()\n" +"\n" +"class B(A):\n" +" def three(self):\n" +" return 3 * self._A__one()\n" +"\n" +"four = 4 * A()._A__one()" + +#: ../../faq/programming.rst:1768 msgid "" "In particular, this does not guarantee privacy since an outside user can " "still deliberately access the private attribute; many Python programmers " "never bother to use private variable names at all." msgstr "" +"Em particular, isso não garante a privacidade, pois um usuário externo ainda " +"pode acessar deliberadamente o atributo privado; muitas pessoas que usam " +"Python nunca se preocuparam em usar nomes de variáveis privadas." -#: ../../faq/programming.rst:1767 +#: ../../faq/programming.rst:1774 msgid "" "The :ref:`private name mangling specifications ` for " "details and special cases." @@ -2330,24 +3843,27 @@ msgstr "" "O :ref:`especificações de desfiguração de nome privado ` para detalhes e casos especiais." -#: ../../faq/programming.rst:1771 +#: ../../faq/programming.rst:1778 msgid "My class defines __del__ but it is not called when I delete the object." msgstr "" "Minha classe define __del__, mas o mesmo não é chamado quando eu excluo o " "objeto." -#: ../../faq/programming.rst:1773 +#: ../../faq/programming.rst:1780 msgid "There are several possible reasons for this." msgstr "Há várias razões possíveis para isto." -#: ../../faq/programming.rst:1775 +#: ../../faq/programming.rst:1782 msgid "" "The :keyword:`del` statement does not necessarily call :meth:`~object." "__del__` -- it simply decrements the object's reference count, and if this " "reaches zero :meth:`!__del__` is called." msgstr "" +"A instrução :keyword:`del` não necessariamente chama o método :meth:`~object." +"__del__` - ele simplesmente diminui o contagem de referências do objeto e, " +"se ele chegar a zero, o :meth:`!__del__` é chamado." -#: ../../faq/programming.rst:1779 +#: ../../faq/programming.rst:1786 msgid "" "If your data structures contain circular links (e.g. a tree where each child " "has a parent reference and each parent has a list of children) the reference " @@ -2360,8 +3876,19 @@ msgid "" "run :func:`gc.collect` to force a collection, but there *are* pathological " "cases where objects will never be collected." msgstr "" +"Se suas estruturas de dados contiverem links circulares (por exemplo, uma " +"árvore em que cada filho tem uma referência para o pai e cada pai tem uma " +"lista de filhos), a contagem de referências nunca voltará a zero. De vez em " +"quando, o Python executa um algoritmo para detectar esses ciclos, mas o " +"coletor de lixo pode ser executado algum tempo depois que a última " +"referência da sua estrutura de dados desaparecer, de modo que o seu método :" +"meth:`!__del__` pode ser chamado em um momento inconveniente e aleatório. " +"Isso é inconveniente se você estiver tentando reproduzir um problema. Pior " +"ainda, a ordem em quais objetos o métodos :meth:`!__del__` são executados é " +"arbitrária. Você pode executar :func:`gc.collect` para forçar um coleção, " +"mas *há* casos patológicos em que os objetos nunca serão coletados." -#: ../../faq/programming.rst:1790 +#: ../../faq/programming.rst:1797 msgid "" "Despite the cycle collector, it's still a good idea to define an explicit " "``close()`` method on objects to be called whenever you're done with them. " @@ -2370,38 +3897,54 @@ msgid "" "``close()`` and ``close()`` should make sure that it can be called more than " "once for the same object." msgstr "" +"Apesar do coletor de ciclos, ainda é uma boa ideia definir um método " +"``close()`` explícito nos objetos a ser chamado sempre que você terminar de " +"usá-los. O método ``close()`` pode então remover o atributo que se refere a " +"subobjetos. Não chame :meth:`!__del__` diretamente - :meth:`!__del__` deve " +"chamar ``close()`` e ``close()`` deve garantir que ele possa ser chamado " +"mais de uma vez para o mesmo objeto." -#: ../../faq/programming.rst:1797 +#: ../../faq/programming.rst:1804 msgid "" "Another way to avoid cyclical references is to use the :mod:`weakref` " "module, which allows you to point to objects without incrementing their " "reference count. Tree data structures, for instance, should use weak " "references for their parent and sibling references (if they need them!)." msgstr "" +"Outra forma de evitar referências cíclicas é usar o módulo :mod:`weakref`, " +"que permite apontar para objetos sem incrementar o contagem de referências. " +"As estruturas de dados em árvore, por exemplo, devem usar o referência fraca " +"para referenciar seus pais e irmãos (se precisarem deles!)." -#: ../../faq/programming.rst:1810 +#: ../../faq/programming.rst:1817 msgid "" "Finally, if your :meth:`!__del__` method raises an exception, a warning " "message is printed to :data:`sys.stderr`." msgstr "" +"Por fim, se seu método :meth:`!__del__` levanta uma exceção, uma mensagem de " +"alerta será enviada para :data:`sys.stderr`." -#: ../../faq/programming.rst:1815 +#: ../../faq/programming.rst:1822 msgid "How do I get a list of all instances of a given class?" msgstr "" "Como eu consigo pegar uma lista de todas as instâncias de uma dada classe?" -#: ../../faq/programming.rst:1817 +#: ../../faq/programming.rst:1824 msgid "" "Python does not keep track of all instances of a class (or of a built-in " "type). You can program the class's constructor to keep track of all " "instances by keeping a list of weak references to each instance." msgstr "" +"Python não mantém o controle de todas as instâncias de uma classe (ou de um " +"tipo embutido). Você pode programar o construtor da classe para manter o " +"controle de todas as instâncias, mantendo uma lista de referências fracas " +"para cada instância." -#: ../../faq/programming.rst:1823 +#: ../../faq/programming.rst:1830 msgid "Why does the result of ``id()`` appear to be not unique?" msgstr "Por que o resultado de ``id()`` aparenta não ser único?" -#: ../../faq/programming.rst:1825 +#: ../../faq/programming.rst:1832 msgid "" "The :func:`id` builtin returns an integer that is guaranteed to be unique " "during the lifetime of the object. Since in CPython, this is the object's " @@ -2409,199 +3952,504 @@ msgid "" "memory, the next freshly created object is allocated at the same position in " "memory. This is illustrated by this example:" msgstr "" +"A função embutida :func:`id` retorna um inteiro que é garantido ser único " +"durante a vida útil do objeto. Como em CPython esse número é o endereço de " +"memória do objeto, acontece com frequência que, depois que um objeto é " +"excluído da memória, o próximo objeto recém-criado é alocado na mesma " +"posição na memória. Isso é ilustrado por este exemplo:" -#: ../../faq/programming.rst:1836 +#: ../../faq/programming.rst:1843 msgid "" "The two ids belong to different integer objects that are created before, and " "deleted immediately after execution of the ``id()`` call. To be sure that " "objects whose id you want to examine are still alive, create another " "reference to the object:" msgstr "" +"Os dois ids pertencem a diferentes objetos inteiros que são criados antes e " +"excluídos imediatamente após a execução da chamada de ``id()``. Para ter " +"certeza de que os objetos cujo id você deseja examinar ainda estão vivos, " +"crie outra referencia para o objeto:" -#: ../../faq/programming.rst:1849 +#: ../../faq/programming.rst:1856 msgid "When can I rely on identity tests with the *is* operator?" msgstr "Quando eu posso depender dos testes de identidade com o operador *is*?" -#: ../../faq/programming.rst:1851 +#: ../../faq/programming.rst:1858 msgid "" "The ``is`` operator tests for object identity. The test ``a is b`` is " "equivalent to ``id(a) == id(b)``." msgstr "" +"O operador ``is`` testa a identidade do objeto. O teste ``a is b`` equivale " +"a ``id(a) == id(b)``." -#: ../../faq/programming.rst:1854 +#: ../../faq/programming.rst:1861 msgid "" "The most important property of an identity test is that an object is always " "identical to itself, ``a is a`` always returns ``True``. Identity tests are " "usually faster than equality tests. And unlike equality tests, identity " "tests are guaranteed to return a boolean ``True`` or ``False``." msgstr "" +"A propriedade mais importante de um teste de identidade é que um objeto é " +"sempre idêntico a si mesmo, ``a is a`` sempre retorna ``True``. Testes de " +"identidade são geralmente mais rápidos do que os testes de igualdade. E, ao " +"contrário dos testes de igualdade, teste de identidade garante que retorno " +"seja um booleano ``True`` ou ``False``." -#: ../../faq/programming.rst:1859 +#: ../../faq/programming.rst:1866 msgid "" "However, identity tests can *only* be substituted for equality tests when " "object identity is assured. Generally, there are three circumstances where " "identity is guaranteed:" msgstr "" +"Entretanto, o teste de identidade *somente* pode ser substituído por testes " +"de igualdade quando a identidade do objeto é garantida. Em geral, há três " +"circunstâncias em que a identidade é garantida:" -#: ../../faq/programming.rst:1863 +#: ../../faq/programming.rst:1870 msgid "" -"1) Assignments create new names but do not change object identity. After " -"the assignment ``new = old``, it is guaranteed that ``new is old``." +"Assignments create new names but do not change object identity. After the " +"assignment ``new = old``, it is guaranteed that ``new is old``." msgstr "" +"Atribuições criam novos nomes, mas não alteram a identidade do objeto. Após " +"a atribuição ``new = old``, é garantido que ``new is old``." -#: ../../faq/programming.rst:1866 +#: ../../faq/programming.rst:1873 msgid "" -"2) Putting an object in a container that stores object references does not " +"Putting an object in a container that stores object references does not " "change object identity. After the list assignment ``s[0] = x``, it is " "guaranteed that ``s[0] is x``." msgstr "" +"Colocar um objeto em um contêiner que armazena referências de objetos não " +"altera a identidade do objeto. Após a lista atribuição ``s[0] = x``, é " +"garantido que ``s[0] is x``." -#: ../../faq/programming.rst:1870 +#: ../../faq/programming.rst:1877 msgid "" -"3) If an object is a singleton, it means that only one instance of that " -"object can exist. After the assignments ``a = None`` and ``b = None``, it " -"is guaranteed that ``a is b`` because ``None`` is a singleton." +"If an object is a singleton, it means that only one instance of that object " +"can exist. After the assignments ``a = None`` and ``b = None``, it is " +"guaranteed that ``a is b`` because ``None`` is a singleton." msgstr "" +"Se um objeto for um Singleton, isso significa que só pode existir uma " +"instância desse objeto. Depois de atribuição ``a = None`` e ``b = None``, é " +"garantido que ``a is b`` porque ``None`` é um Singleton." -#: ../../faq/programming.rst:1874 +#: ../../faq/programming.rst:1881 msgid "" "In most other circumstances, identity tests are inadvisable and equality " "tests are preferred. In particular, identity tests should not be used to " "check constants such as :class:`int` and :class:`str` which aren't " "guaranteed to be singletons::" msgstr "" +"Na maioria das outras circunstâncias, o teste de identidade é " +"desaconselhável e os testes de igualdade são preferíveis. Em particular, " +"teste de identidade não deve ser usado para verificar constantes, como :" +"class:`int` e :class:`str`, que não têm garantia de serem Singletons::" + +#: ../../faq/programming.rst:1886 +msgid "" +">>> a = 1000\n" +">>> b = 500\n" +">>> c = b + 500\n" +">>> a is c\n" +"False\n" +"\n" +">>> a = 'Python'\n" +">>> b = 'Py'\n" +">>> c = b + 'thon'\n" +">>> a is c\n" +"False" +msgstr "" +">>> a = 1000\n" +">>> b = 500\n" +">>> c = b + 500\n" +">>> a is c\n" +"False\n" +"\n" +">>> a = 'Python'\n" +">>> b = 'Py'\n" +">>> c = b + 'thon'\n" +">>> a is c\n" +"False" -#: ../../faq/programming.rst:1891 +#: ../../faq/programming.rst:1898 msgid "Likewise, new instances of mutable containers are never identical::" msgstr "" "Do mesmo jeito, novas instâncias de contêineres mutáveis nunca são " "idênticas::" -#: ../../faq/programming.rst:1898 +#: ../../faq/programming.rst:1900 +msgid "" +">>> a = []\n" +">>> b = []\n" +">>> a is b\n" +"False" +msgstr "" +">>> a = []\n" +">>> b = []\n" +">>> a is b\n" +"False" + +#: ../../faq/programming.rst:1905 msgid "" "In the standard library code, you will see several common patterns for " "correctly using identity tests:" msgstr "" +"No código da biblioteca padrão, você encontrará vários padrões comuns para " +"usar corretamente o teste de identidade:" -#: ../../faq/programming.rst:1901 +#: ../../faq/programming.rst:1908 msgid "" -"1) As recommended by :pep:`8`, an identity test is the preferred way to " -"check for ``None``. This reads like plain English in code and avoids " -"confusion with other objects that may have boolean values that evaluate to " -"false." +"As recommended by :pep:`8`, an identity test is the preferred way to check " +"for ``None``. This reads like plain English in code and avoids confusion " +"with other objects that may have boolean values that evaluate to false." msgstr "" +"Conforme recomendado por :pep:`8`, um teste de identidade é a maneira " +"preferida de verificar ``None``. Isso é lido como se fosse inglês simples " +"no código e evita confusão com outros objetos que podem ter valor booleano " +"avaliado para falso." -#: ../../faq/programming.rst:1905 +#: ../../faq/programming.rst:1912 msgid "" -"2) Detecting optional arguments can be tricky when ``None`` is a valid input " +"Detecting optional arguments can be tricky when ``None`` is a valid input " "value. In those situations, you can create a singleton sentinel object " "guaranteed to be distinct from other objects. For example, here is how to " -"implement a method that behaves like :meth:`dict.pop`::" -msgstr "" - -#: ../../faq/programming.rst:1921 -msgid "" -"3) Container implementations sometimes need to augment equality tests with " +"implement a method that behaves like :meth:`dict.pop`:" +msgstr "" +"A detecção de argumento opcional pode ser complicada quando ``None`` é uma " +"valor de entrada válido. Nessas situações, você pode criar um objeto " +"Singleton sinalizador com garantia de ser distinto de outros objetos. Por " +"exemplo, veja como implementar um método que se comporta como :meth:`dict." +"pop`:" + +#: ../../faq/programming.rst:1917 +msgid "" +"_sentinel = object()\n" +"\n" +"def pop(self, key, default=_sentinel):\n" +" if key in self:\n" +" value = self[key]\n" +" del self[key]\n" +" return value\n" +" if default is _sentinel:\n" +" raise KeyError(key)\n" +" return default" +msgstr "" +"_sentinel = object()\n" +"\n" +"def pop(self, key, default=_sentinel):\n" +" if key in self:\n" +" value = self[key]\n" +" del self[key]\n" +" return value\n" +" if default is _sentinel:\n" +" raise KeyError(key)\n" +" return default" + +#: ../../faq/programming.rst:1930 +msgid "" +"Container implementations sometimes need to augment equality tests with " "identity tests. This prevents the code from being confused by objects such " "as ``float('NaN')`` that are not equal to themselves." msgstr "" +"Implementações de contêiner às vezes precisam combinar testes de igualdade " +"com testes de identidade. Isso evita que o código seja confundido por " +"objetos como ``float('NaN')`` que não são iguais a si mesmos." -#: ../../faq/programming.rst:1925 +#: ../../faq/programming.rst:1934 msgid "" "For example, here is the implementation of :meth:`!collections.abc.Sequence." "__contains__`::" msgstr "" +"Por exemplo, aqui está a implementação de :meth:`!collections.abc.Sequence." +"__contains__`::" -#: ../../faq/programming.rst:1936 +#: ../../faq/programming.rst:1937 +msgid "" +"def __contains__(self, value):\n" +" for v in self:\n" +" if v is value or v == value:\n" +" return True\n" +" return False" +msgstr "" +"def __contains__(self, value):\n" +" for v in self:\n" +" if v is value or v == value:\n" +" return True\n" +" return False" + +#: ../../faq/programming.rst:1945 msgid "" "How can a subclass control what data is stored in an immutable instance?" msgstr "" +"Como uma subclasse pode controlar quais dados são armazenados em uma " +"instância imutável?" -#: ../../faq/programming.rst:1938 +#: ../../faq/programming.rst:1947 msgid "" "When subclassing an immutable type, override the :meth:`~object.__new__` " "method instead of the :meth:`~object.__init__` method. The latter only runs " "*after* an instance is created, which is too late to alter data in an " "immutable instance." msgstr "" +"Quando estender um tipo imutável, sobrescreva o método :meth:`~object." +"__new__` em vez do método :meth:`~object.__init__`. O último só é executado " +"*depois* que uma instância é criada, o que é tarde demais para alterar os " +"dados em uma instância imutável." -#: ../../faq/programming.rst:1943 +#: ../../faq/programming.rst:1952 msgid "" "All of these immutable classes have a different signature than their parent " "class:" msgstr "" - -#: ../../faq/programming.rst:1969 +"Todas essas classes imutáveis têm um assinatura diferente da sua classe base:" + +#: ../../faq/programming.rst:1955 +msgid "" +"from datetime import date\n" +"\n" +"class FirstOfMonthDate(date):\n" +" \"Always choose the first day of the month\"\n" +" def __new__(cls, year, month, day):\n" +" return super().__new__(cls, year, month, 1)\n" +"\n" +"class NamedInt(int):\n" +" \"Allow text names for some numbers\"\n" +" xlat = {'zero': 0, 'one': 1, 'ten': 10}\n" +" def __new__(cls, value):\n" +" value = cls.xlat.get(value, value)\n" +" return super().__new__(cls, value)\n" +"\n" +"class TitleStr(str):\n" +" \"Convert str to name suitable for a URL path\"\n" +" def __new__(cls, s):\n" +" s = s.lower().replace(' ', '-')\n" +" s = ''.join([c for c in s if c.isalnum() or c == '-'])\n" +" return super().__new__(cls, s)" +msgstr "" +"from datetime import date\n" +"\n" +"class FirstOfMonthDate(date):\n" +" \"Usa sempre o primeiro dia do mês\"\n" +" def __new__(cls, year, month, day):\n" +" return super().__new__(cls, year, month, 1)\n" +"\n" +"class NamedInt(int):\n" +" \"Permite o nome em texto para alguns números\"\n" +" xlat = {'zero': 0, 'one': 1, 'ten': 10}\n" +" def __new__(cls, value):\n" +" value = cls.xlat.get(value, value)\n" +" return super().__new__(cls, value)\n" +"\n" +"class TitleStr(str):\n" +" \"Converte string para um nome adequado para uma URL\"\n" +" def __new__(cls, s):\n" +" s = s.lower().replace(' ', '-')\n" +" s = ''.join([c for c in s if c.isalnum() or c == '-'])\n" +" return super().__new__(cls, s)" + +#: ../../faq/programming.rst:1978 msgid "The classes can be used like this:" -msgstr "" - -#: ../../faq/programming.rst:1986 +msgstr "As classes podem ser usadas da seguinte forma:" + +#: ../../faq/programming.rst:1980 +msgid "" +">>> FirstOfMonthDate(2012, 2, 14)\n" +"FirstOfMonthDate(2012, 2, 1)\n" +">>> NamedInt('ten')\n" +"10\n" +">>> NamedInt(20)\n" +"20\n" +">>> TitleStr('Blog: Why Python Rocks')\n" +"'blog-why-python-rocks'" +msgstr "" +">>> FirstOfMonthDate(2012, 2, 14)\n" +"FirstOfMonthDate(2012, 2, 1)\n" +">>> NamedInt('ten')\n" +"10\n" +">>> NamedInt(20)\n" +"20\n" +">>> TitleStr('Blog: Porque Python domina')\n" +"'blog-porque-python-domina'" + +#: ../../faq/programming.rst:1995 msgid "How do I cache method calls?" -msgstr "" +msgstr "Como faço para armazenar em cache as chamadas de um método?" -#: ../../faq/programming.rst:1988 +#: ../../faq/programming.rst:1997 msgid "" "The two principal tools for caching methods are :func:`functools." "cached_property` and :func:`functools.lru_cache`. The former stores results " "at the instance level and the latter at the class level." msgstr "" +"As duas principais ferramentas para armazenamento em cache de métodos são :" +"func:`functools.cached_property` e :func:`functools.lru_cache`. A primeira " +"armazena resultados no nível de instância e a segunda no nível de classe." -#: ../../faq/programming.rst:1993 +#: ../../faq/programming.rst:2002 msgid "" "The *cached_property* approach only works with methods that do not take any " "arguments. It does not create a reference to the instance. The cached " "method result will be kept only as long as the instance is alive." msgstr "" +"A abordagem *cached_property* funciona somente com métodos que não aceitam " +"nenhum argumento. Ela não cria uma referência para a instância. O resultado " +"do método será mantido em cache somente enquanto a instância estiver ativa." -#: ../../faq/programming.rst:1997 +#: ../../faq/programming.rst:2006 msgid "" "The advantage is that when an instance is no longer used, the cached method " "result will be released right away. The disadvantage is that if instances " "accumulate, so too will the accumulated method results. They can grow " "without bound." msgstr "" +"A vantagem é que, quando um instância não for mais usada, o resultado do " +"método armazenado em cache será liberado imediatamente. A desvantagem é " +"que, se as instâncias se acumularem, os resultados do método também serão " +"acumulados. Eles podem crescer sem limites." -#: ../../faq/programming.rst:2002 +#: ../../faq/programming.rst:2011 msgid "" "The *lru_cache* approach works with methods that have :term:`hashable` " "arguments. It creates a reference to the instance unless special efforts " "are made to pass in weak references." msgstr "" +"A abordagem *lru_cache* funciona com métodos que têm argumento :term:" +"`hasheável`. Ele cria uma referência para a instância, a menos que sejam " +"feitos esforços especiais para passar referências fracas." -#: ../../faq/programming.rst:2006 +#: ../../faq/programming.rst:2015 msgid "" "The advantage of the least recently used algorithm is that the cache is " "bounded by the specified *maxsize*. The disadvantage is that instances are " "kept alive until they age out of the cache or until the cache is cleared." msgstr "" +"A vantagem do algoritmo menos recentemente usado é que o cache é limitado " +"pelo *maxsize* especificado. A desvantagem é que as instâncias são mantidas " +"vivas até que saiam do cache ou até que o cache seja limpo." -#: ../../faq/programming.rst:2011 +#: ../../faq/programming.rst:2020 msgid "This example shows the various techniques::" msgstr "Esse exemplo mostra as várias técnicas::" -#: ../../faq/programming.rst:2035 +#: ../../faq/programming.rst:2022 +msgid "" +"class Weather:\n" +" \"Lookup weather information on a government website\"\n" +"\n" +" def __init__(self, station_id):\n" +" self._station_id = station_id\n" +" # The _station_id is private and immutable\n" +"\n" +" def current_temperature(self):\n" +" \"Latest hourly observation\"\n" +" # Do not cache this because old results\n" +" # can be out of date.\n" +"\n" +" @cached_property\n" +" def location(self):\n" +" \"Return the longitude/latitude coordinates of the station\"\n" +" # Result only depends on the station_id\n" +"\n" +" @lru_cache(maxsize=20)\n" +" def historic_rainfall(self, date, units='mm'):\n" +" \"Rainfall on a given date\"\n" +" # Depends on the station_id, date, and units." +msgstr "" +"class Weather:\n" +" \"Procura informações de tempo em sites governamentais\"\n" +"\n" +" def __init__(self, station_id):\n" +" self._station_id = station_id\n" +" # O _station_id é privado e imutável\n" +"\n" +" def current_temperature(self):\n" +" \"Última observação horária\"\n" +" # Não armazena isso em cache porque os dados anteriores\n" +" # podem estar desatualizados.\n" +"\n" +" @cached_property\n" +" def location(self):\n" +" \"Retornas as coordenadas longitude/latitude coordinates da " +"estação\"\n" +" # Resultado depende apenas de station_id\n" +"\n" +" @lru_cache(maxsize=20)\n" +" def historic_rainfall(self, date, units='mm'):\n" +" \"Precipitação em uma determinada data\"\n" +" # Depende de station_id, date, e units." + +#: ../../faq/programming.rst:2044 msgid "" "The above example assumes that the *station_id* never changes. If the " "relevant instance attributes are mutable, the *cached_property* approach " "can't be made to work because it cannot detect changes to the attributes." msgstr "" +"O exemplo acima assume que o *station_id* nunca muda. Se os atribuitos " +"relevantes da instância forem mutáveis, a abordagem *cached_property* não " +"poderá usada porque não é capaz de detectar alterações no atributo." -#: ../../faq/programming.rst:2040 +#: ../../faq/programming.rst:2049 msgid "" "To make the *lru_cache* approach work when the *station_id* is mutable, the " "class needs to define the :meth:`~object.__eq__` and :meth:`~object." "__hash__` methods so that the cache can detect relevant attribute updates::" msgstr "" - -#: ../../faq/programming.rst:2066 +"Para que a abordagem *lru_cache* funcione quando *station_id* for mutável, a " +"classe precisa definir os métodos :meth:`~object.__eq__` e :meth:`~object." +"__hash__` para que o cache possa detectar atualizações relevantes do " +"atributo::" + +#: ../../faq/programming.rst:2053 +msgid "" +"class Weather:\n" +" \"Example with a mutable station identifier\"\n" +"\n" +" def __init__(self, station_id):\n" +" self.station_id = station_id\n" +"\n" +" def change_station(self, station_id):\n" +" self.station_id = station_id\n" +"\n" +" def __eq__(self, other):\n" +" return self.station_id == other.station_id\n" +"\n" +" def __hash__(self):\n" +" return hash(self.station_id)\n" +"\n" +" @lru_cache(maxsize=20)\n" +" def historic_rainfall(self, date, units='cm'):\n" +" 'Rainfall on a given date'\n" +" # Depends on the station_id, date, and units." +msgstr "" +"class Weather:\n" +" \"Examplo com um identificador de estação mutável\"\n" +"\n" +" def __init__(self, station_id):\n" +" self.station_id = station_id\n" +"\n" +" def change_station(self, station_id):\n" +" self.station_id = station_id\n" +"\n" +" def __eq__(self, other):\n" +" return self.station_id == other.station_id\n" +"\n" +" def __hash__(self):\n" +" return hash(self.station_id)\n" +"\n" +" @lru_cache(maxsize=20)\n" +" def historic_rainfall(self, date, units='cm'):\n" +" \"Precipitação em uma determinada data\"\n" +" # Depende de station_id, date, e units." + +#: ../../faq/programming.rst:2075 msgid "Modules" msgstr "Módulos" -#: ../../faq/programming.rst:2069 +#: ../../faq/programming.rst:2078 msgid "How do I create a .pyc file?" msgstr "Como faço para criar um arquivo .pyc?" -#: ../../faq/programming.rst:2071 +#: ../../faq/programming.rst:2080 msgid "" "When a module is imported for the first time (or when the source file has " "changed since the current compiled file was created) a ``.pyc`` file " @@ -2611,8 +4459,16 @@ msgid "" "file, and ends with ``.pyc``, with a middle component that depends on the " "particular ``python`` binary that created it. (See :pep:`3147` for details.)" msgstr "" +"Quando um módulo é importado pela primeira vez (ou quando o arquivo de " +"origem foi alterado desde que o arquivo compilado atual foi criado), um " +"arquivo ``.pyc`` contendo o código compilado deve ser criado em um " +"subdiretório ``__pycache__`` do diretório que contém o arquivo ``.py``. O " +"arquivo ``.pyc`` terá um nome de arquivo que começa com o mesmo nome do " +"arquivo ``.py`` e termina com ``.pyc``, com um componente intermediário que " +"depende do binário ``python`` específico que o criou. (Consulte :pep:`3147` " +"para obter detalhes.)" -#: ../../faq/programming.rst:2079 +#: ../../faq/programming.rst:2088 msgid "" "One reason that a ``.pyc`` file may not be created is a permissions problem " "with the directory containing the source file, meaning that the " @@ -2620,8 +4476,13 @@ msgid "" "example, if you develop as one user but run as another, such as if you are " "testing with a web server." msgstr "" +"Um dos motivos pelos quais um arquivo ``.pyc`` pode não ser criado é um " +"problema de permissões no diretório que contém o arquivo de origem, o que " +"significa que o subdiretório ``__pycache__`` não pode ser criado. Isso pode " +"acontecer, por exemplo, se você desenvolver como um usuário, mas executar " +"como outro, como se estivesse testando em um servidor web." -#: ../../faq/programming.rst:2084 +#: ../../faq/programming.rst:2093 msgid "" "Unless the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable is set, " "creation of a .pyc file is automatic if you're importing a module and Python " @@ -2629,8 +4490,13 @@ msgid "" "``__pycache__`` subdirectory and write the compiled module to that " "subdirectory." msgstr "" +"A menos que a variável de ambiente :envvar:`PYTHONDONTWRITEBYTECODE` esteja " +"definida, a criação de um arquivo .pyc será automática se você estiver " +"importando um módulo e o Python tiver a capacidade (permissões, espaço livre " +"etc.) de criar um subdiretório ``__pycache__`` e gravar o módulo compilado " +"nesse subdiretório." -#: ../../faq/programming.rst:2089 +#: ../../faq/programming.rst:2098 msgid "" "Running Python on a top level script is not considered an import and no ``." "pyc`` will be created. For example, if you have a top-level module ``foo." @@ -2639,40 +4505,71 @@ msgid "" "``xyz`` because ``xyz`` is imported, but no ``.pyc`` file will be created " "for ``foo`` since ``foo.py`` isn't being imported." msgstr "" +"A execução do Python em um script de nível superior não é considerada uma " +"importação e nenhum ``.pyc`` será criado. Por exemplo, se você tiver um " +"módulo de nível superior ``foo.py`` que importa outro módulo ``xyz.py`` , ao " +"executar ``foo`` (digitando ``python foo.py`` no console do sistema " +"operacional (SO)), um ``.pyc`` será criado para ``xyz`` porque ``xyz`` é " +"importado, mas nenhum arquivo ``.pyc`` será criado para ``foo``, pois ``foo." +"py`` não está sendo importado." -#: ../../faq/programming.rst:2096 +#: ../../faq/programming.rst:2105 msgid "" "If you need to create a ``.pyc`` file for ``foo`` -- that is, to create a ``." "pyc`` file for a module that is not imported -- you can, using the :mod:" "`py_compile` and :mod:`compileall` modules." msgstr "" +"Se você precisar criar um arquivo ``.pyc`` para ``foo``, ou seja, criar um " +"arquivo ``.pyc`` para um módulo que não é importado, você pode usar os " +"módulos :mod:`py_compile` e :mod:`compileall`." -#: ../../faq/programming.rst:2100 +#: ../../faq/programming.rst:2109 msgid "" "The :mod:`py_compile` module can manually compile any module. One way is to " "use the ``compile()`` function in that module interactively::" msgstr "" +"O módulo :mod:`py_compile` pode compilar manualmente qualquer módulo. Uma " +"maneira é usar interativamente a função ``compile()`` nesse módulo::" -#: ../../faq/programming.rst:2106 +#: ../../faq/programming.rst:2112 +msgid "" +">>> import py_compile\n" +">>> py_compile.compile('foo.py')" +msgstr "" +">>> import py_compile\n" +">>> py_compile.compile('foo.py')" + +#: ../../faq/programming.rst:2115 msgid "" "This will write the ``.pyc`` to a ``__pycache__`` subdirectory in the same " "location as ``foo.py`` (or you can override that with the optional parameter " "``cfile``)." msgstr "" +"Isso gravará o ``.pyc`` em um subdiretório ``__pycache__`` no mesmo local " +"que ``foo.py`` (ou você pode substituir isso com o parâmetro opcional " +"``cfile`` )." -#: ../../faq/programming.rst:2110 +#: ../../faq/programming.rst:2119 msgid "" "You can also automatically compile all files in a directory or directories " "using the :mod:`compileall` module. You can do it from the shell prompt by " "running ``compileall.py`` and providing the path of a directory containing " "Python files to compile::" msgstr "" +"Você também pode compilar automaticamente todos os arquivos em um diretório " +"ou diretórios usando o módulo :mod:`compileall`. Você pode fazer isso no " +"console do SO executando ``compileall.py`` e fornecendo o caminho de um " +"diretório que contenha os arquivos Python a serem compilados::" -#: ../../faq/programming.rst:2119 +#: ../../faq/programming.rst:2124 +msgid "python -m compileall ." +msgstr "python -m compileall ." + +#: ../../faq/programming.rst:2128 msgid "How do I find the current module name?" msgstr "Como encontro o nome do módulo atual?" -#: ../../faq/programming.rst:2121 +#: ../../faq/programming.rst:2130 msgid "" "A module can find out its own module name by looking at the predefined " "global variable ``__name__``. If this has the value ``'__main__'``, the " @@ -2680,80 +4577,126 @@ msgid "" "importing them also provide a command-line interface or a self-test, and " "only execute this code after checking ``__name__``::" msgstr "" +"Um módulo pode descobrir seu próprio nome consultando a variável global " +"predefinida ``__name__`` . Se ela tiver o valor ``'__main__'`` , o programa " +"estará sendo executado como um script. Muitos módulos que são normalmente " +"usados ao serem importados também fornecem uma interface de linha de comando " +"ou um autoteste, e só executam esse código depois de verificar ``__name__``::" #: ../../faq/programming.rst:2136 -msgid "How can I have modules that mutually import each other?" +msgid "" +"def main():\n" +" print('Running test...')\n" +" ...\n" +"\n" +"if __name__ == '__main__':\n" +" main()" msgstr "" +"def main():\n" +" print('Executando teste...')\n" +" ...\n" +"\n" +"if __name__ == '__main__':\n" +" main()" + +#: ../../faq/programming.rst:2145 +msgid "How can I have modules that mutually import each other?" +msgstr "Como posso ter módulos que se importam mutuamente?" -#: ../../faq/programming.rst:2138 +#: ../../faq/programming.rst:2147 msgid "Suppose you have the following modules:" msgstr "Suponha que tenhas os seguintes módulos:" -#: ../../faq/programming.rst:2140 +#: ../../faq/programming.rst:2149 msgid ":file:`foo.py`::" msgstr ":file:`foo.py`::" -#: ../../faq/programming.rst:2145 +#: ../../faq/programming.rst:2151 +msgid "" +"from bar import bar_var\n" +"foo_var = 1" +msgstr "" +"from bar importar bar_var\n" +"foo_var = 1" + +#: ../../faq/programming.rst:2154 msgid ":file:`bar.py`::" msgstr ":file:`bar.py`::" -#: ../../faq/programming.rst:2150 +#: ../../faq/programming.rst:2156 +msgid "" +"from foo import foo_var\n" +"bar_var = 2" +msgstr "" +"from foo import foo_var\n" +"bar_var = 2" + +#: ../../faq/programming.rst:2159 msgid "The problem is that the interpreter will perform the following steps:" msgstr "O problema é que o interpretador vai realizar os seguintes passos:" -#: ../../faq/programming.rst:2152 +#: ../../faq/programming.rst:2161 msgid "main imports ``foo``" -msgstr "" +msgstr "Programa principal importa ``foo``" -#: ../../faq/programming.rst:2153 +#: ../../faq/programming.rst:2162 msgid "Empty globals for ``foo`` are created" -msgstr "" +msgstr "São criados globais vazios para ``foo``" -#: ../../faq/programming.rst:2154 +#: ../../faq/programming.rst:2163 msgid "``foo`` is compiled and starts executing" -msgstr "" +msgstr "``foo`` é compilado e começa a ser executado" -#: ../../faq/programming.rst:2155 +#: ../../faq/programming.rst:2164 msgid "``foo`` imports ``bar``" -msgstr "" +msgstr "``foo`` importa ``bar``" -#: ../../faq/programming.rst:2156 +#: ../../faq/programming.rst:2165 msgid "Empty globals for ``bar`` are created" -msgstr "" +msgstr "São criados globais vazios para ``bar``" -#: ../../faq/programming.rst:2157 +#: ../../faq/programming.rst:2166 msgid "``bar`` is compiled and starts executing" -msgstr "" +msgstr "``bar`` é compilado e começa a ser executado" -#: ../../faq/programming.rst:2158 +#: ../../faq/programming.rst:2167 msgid "" "``bar`` imports ``foo`` (which is a no-op since there already is a module " "named ``foo``)" msgstr "" +"``bar`` importa ``foo`` (o que não é executado de fato, pois já existe um " +"módulo chamado ``foo``)" -#: ../../faq/programming.rst:2159 +#: ../../faq/programming.rst:2168 msgid "" "The import mechanism tries to read ``foo_var`` from ``foo`` globals, to set " "``bar.foo_var = foo.foo_var``" msgstr "" +"O mecanismo de importação tenta ler ``foo_var`` do ``foo`` em globais, para " +"definir ``bar.foo_var = foo.foo_var``" -#: ../../faq/programming.rst:2161 +#: ../../faq/programming.rst:2170 msgid "" "The last step fails, because Python isn't done with interpreting ``foo`` yet " "and the global symbol dictionary for ``foo`` is still empty." msgstr "" +"A última etapa falha, pois Python ainda não terminou de interpretar ``foo`` " +"e o dicionário de símbolos global para ``foo`` ainda está vazio." -#: ../../faq/programming.rst:2164 +#: ../../faq/programming.rst:2173 msgid "" "The same thing happens when you use ``import foo``, and then try to access " "``foo.foo_var`` in global code." msgstr "" +"O mesmo acontece quando você usa ``import foo`` e, em seguida, tenta acessar " +"``foo.foo_var`` no código global." -#: ../../faq/programming.rst:2167 +#: ../../faq/programming.rst:2176 msgid "There are (at least) three possible workarounds for this problem." msgstr "" +"Há (pelo menos) três possíveis soluções alternativas para esse problema." -#: ../../faq/programming.rst:2169 +#: ../../faq/programming.rst:2178 msgid "" "Guido van Rossum recommends avoiding all uses of ``from import ..." "``, and placing all code inside functions. Initializations of global " @@ -2761,55 +4704,73 @@ msgid "" "only. This means everything from an imported module is referenced as " "``.``." msgstr "" +"Guido van Rossum recomenda evitar todos os usos de ``from import ..." +"`` e colocar todo o código dentro de funções. As inicializações de " +"variáveis globais e variáveis de classe devem usar apenas constantes ou " +"funções embutidas. Isso significa que tudo de um módulo importado é " +"referenciado como ``.``." -#: ../../faq/programming.rst:2174 +#: ../../faq/programming.rst:2183 msgid "" "Jim Roskind suggests performing steps in the following order in each module:" msgstr "" +"Jim Roskind sugere a execução das etapas na seguinte ordem em cada módulo:" -#: ../../faq/programming.rst:2176 +#: ../../faq/programming.rst:2185 msgid "" "exports (globals, functions, and classes that don't need imported base " "classes)" msgstr "" +"exportações (globais, função e classes que não precisam de classes base " +"importadas)" -#: ../../faq/programming.rst:2178 +#: ../../faq/programming.rst:2187 msgid "``import`` statements" -msgstr "Declaração ``import``" +msgstr "instruções ``import``" -#: ../../faq/programming.rst:2179 +#: ../../faq/programming.rst:2188 msgid "" "active code (including globals that are initialized from imported values)." msgstr "" "código ativo (incluindo globais que são inicializadas de valores importados)" -#: ../../faq/programming.rst:2181 +#: ../../faq/programming.rst:2190 msgid "" "Van Rossum doesn't like this approach much because the imports appear in a " "strange place, but it does work." msgstr "" +"Van Rossum não gosta muito dessa abordagem porque a importação aparece em um " +"lugar estranho, mas ela funciona." -#: ../../faq/programming.rst:2184 +#: ../../faq/programming.rst:2193 msgid "" "Matthias Urlichs recommends restructuring your code so that the recursive " "import is not necessary in the first place." msgstr "" +"Matthias Urlichs recomenda reestruturar seu código para que importação " +"recursiva não seja necessária em primeiro lugar." -#: ../../faq/programming.rst:2187 +#: ../../faq/programming.rst:2196 msgid "These solutions are not mutually exclusive." -msgstr "Essas soluções não são mutualmente exclusivas." +msgstr "Essas soluções não são mutuamente exclusivas." -#: ../../faq/programming.rst:2191 +#: ../../faq/programming.rst:2200 msgid "__import__('x.y.z') returns ; how do I get z?" -msgstr "__import__('x.y.z') returns ; how do I get z?" +msgstr "__import__('x.y.z') retorna ; como faço para obter z?" -#: ../../faq/programming.rst:2193 +#: ../../faq/programming.rst:2202 msgid "" "Consider using the convenience function :func:`~importlib.import_module` " "from :mod:`importlib` instead::" msgstr "" +"Em vez disso, considere usar a conveniente função :func:`~importlib." +"import_module` de :mod:`importlib`::" -#: ../../faq/programming.rst:2200 +#: ../../faq/programming.rst:2205 +msgid "z = importlib.import_module('x.y.z')" +msgstr "z = importlib.import_module('x.y.z')" + +#: ../../faq/programming.rst:2209 msgid "" "When I edit an imported module and reimport it, the changes don't show up. " "Why does this happen?" @@ -2817,7 +4778,7 @@ msgstr "" "Quando eu edito um módulo importado e o reimporto, as mudanças não aparecem. " "Por que isso acontece?" -#: ../../faq/programming.rst:2202 +#: ../../faq/programming.rst:2211 msgid "" "For reasons of efficiency as well as consistency, Python only reads the " "module file on the first time a module is imported. If it didn't, in a " @@ -2825,24 +4786,65 @@ msgid "" "module, the basic module would be parsed and re-parsed many times. To force " "re-reading of a changed module, do this::" msgstr "" +"Por motivos de eficiência e consistência, o Python só lê o arquivo do módulo " +"na primeira vez em que um módulo é importado. Caso contrário, em um " +"programa que consiste em muitos módulos em que cada um importa o mesmo " +"módulo básico, o módulo básico seria analisado e reanalisado várias vezes. " +"Para forçar a releitura de um módulo alterado, faça o seguinte::" -#: ../../faq/programming.rst:2212 +#: ../../faq/programming.rst:2217 +msgid "" +"import importlib\n" +"import modname\n" +"importlib.reload(modname)" +msgstr "" +"import importlib\n" +"import modname\n" +"importlib.reload(modname)" + +#: ../../faq/programming.rst:2221 msgid "" "Warning: this technique is not 100% fool-proof. In particular, modules " "containing statements like ::" msgstr "" -"Aviso: essa técnica não é 100% a prova de falhas. Em particular, módulos " +"Aviso: essa técnica não é 100% à prova de falhas. Em particular, módulos " "contendo instruções como ::" -#: ../../faq/programming.rst:2217 +#: ../../faq/programming.rst:2224 +msgid "from modname import some_objects" +msgstr "from modname import some_objects" + +#: ../../faq/programming.rst:2226 msgid "" "will continue to work with the old version of the imported objects. If the " "module contains class definitions, existing class instances will *not* be " "updated to use the new class definition. This can result in the following " "paradoxical behaviour::" msgstr "" +"continuará com a versão antiga dos objetos importados. Se o módulo contiver " +"definições de classe, as instâncias de classe existentes *não* serão " +"atualizadas para usar a nova definição da classe. Isso pode resultar no " +"seguinte comportamento paradoxal::" -#: ../../faq/programming.rst:2230 +#: ../../faq/programming.rst:2231 +msgid "" +">>> import importlib\n" +">>> import cls\n" +">>> c = cls.C() # Create an instance of C\n" +">>> importlib.reload(cls)\n" +"\n" +">>> isinstance(c, cls.C) # isinstance is false?!?\n" +"False" +msgstr "" +">>> import importlib\n" +">>> import cls\n" +">>> c = cls.C() # Cria uma instância de C\n" +">>> importlib.reload(cls)\n" +"\n" +">>> isinstance(c, cls.C) # isinstance é falso?!?\n" +"False" + +#: ../../faq/programming.rst:2239 msgid "" "The nature of the problem is made clear if you print out the \"identity\" of " "the class objects::" @@ -2850,13 +4852,25 @@ msgstr "" "A natureza do problema fica clara se você exibir a \"identidade\" dos " "objetos da classe::" +#: ../../faq/programming.rst:2242 +msgid "" +">>> hex(id(c.__class__))\n" +"'0x7352a0'\n" +">>> hex(id(cls.C))\n" +"'0x4198d0'" +msgstr "" +">>> hex(id(c.__class__))\n" +"'0x7352a0'\n" +">>> hex(id(cls.C))\n" +"'0x4198d0'" + #: ../../faq/programming.rst:408 msgid "argument" msgstr "argumento" #: ../../faq/programming.rst:408 msgid "difference from parameter" -msgstr "" +msgstr "diferença de parâmetro" #: ../../faq/programming.rst:408 msgid "parameter" @@ -2864,4 +4878,4 @@ msgstr "parâmetro" #: ../../faq/programming.rst:408 msgid "difference from argument" -msgstr "" +msgstr "diferença de argumento" diff --git a/faq/windows.po b/faq/windows.po index 6b6549ad6..bc4ad1612 100644 --- a/faq/windows.po +++ b/faq/windows.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Ruan Aragão , 2021 -# Adorilson Bezerra , 2021 -# Amanda Savluchinske , 2021 -# Raul Lima , 2021 -# Hortencia_Arliane , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -68,6 +62,10 @@ msgstr "" "reconhecer quando iniciar porque você verá um \"Prompt de Comando do " "Windows\", que geralmente tem esta forma:" +#: ../../faq/windows.rst:35 +msgid "C:\\>" +msgstr "C:\\>" + #: ../../faq/windows.rst:39 msgid "" "The letter may be different, and there might be other things after it, so " @@ -76,6 +74,10 @@ msgstr "" "A letra pode ser diferente, e pode haver outras coisas depois, então você " "facilmente pode ver algo como:" +#: ../../faq/windows.rst:42 +msgid "D:\\YourName\\Projects\\Python>" +msgstr "D:\\SeuNome\\Projetos\\Python>" + #: ../../faq/windows.rst:46 msgid "" "depending on how your computer has been set up and what else you have " @@ -110,10 +112,28 @@ msgstr "" "abriu a janela de comando, você deve tentar digitar o comando \"py\" e o " "observar o retorno:" +#: ../../faq/windows.rst:60 +msgid "C:\\Users\\YourName> py" +msgstr "C:\\Users\\SeuNome> py" + #: ../../faq/windows.rst:64 msgid "You should then see something like:" msgstr "Você deve então ver algo como:" +#: ../../faq/windows.rst:66 +msgid "" +"Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit " +"(Intel)] on win32\n" +"Type \"help\", \"copyright\", \"credits\" or \"license\" for more " +"information.\n" +">>>" +msgstr "" +"Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit " +"(Intel)] on win32\n" +"Type \"help\", \"copyright\", \"credits\" or \"license\" for more " +"information.\n" +">>>" + #: ../../faq/windows.rst:72 msgid "" "You have started the interpreter in \"interactive mode\". That means you can " @@ -127,6 +147,18 @@ msgstr "" "do Python. Verifique isso digitando algumas instruções de sua escolha e veja " "os resultados:" +#: ../../faq/windows.rst:77 +msgid "" +">>> print(\"Hello\")\n" +"Hello\n" +">>> \"Hello\" * 3\n" +"'HelloHelloHello'" +msgstr "" +">>> print(\"Olá\")\n" +"Olá\n" +">>> \"Olá\" * 3\n" +"'OláOláOlá'" + #: ../../faq/windows.rst:84 msgid "" "Many people use the interactive mode as a convenient yet highly programmable " @@ -169,9 +201,13 @@ msgstr "" "Agora que sabemos que o comando ``py`` é reconhecido, você pode dar seu " "script Python para ele. Você terá que dar um caminho absoluto ou relativo " "para o script Python. Vamos dizer que seu script Python está localizado na " -"sua área de trabalho e se chama ``hello.py``, e seu prompt de comando está " +"sua área de trabalho e se chama ``oi.py``, e seu prompt de comando está " "aberto no seu diretório raiz de forma que você está vendo algo similar a::" +#: ../../faq/windows.rst:104 +msgid "C:\\Users\\YourName>" +msgstr "C:\\Users\\SeuNome>" + #: ../../faq/windows.rst:106 msgid "" "So now you'll ask the ``py`` command to give your script to Python by typing " @@ -180,6 +216,14 @@ msgstr "" "Então, agora você solicitará o comando ``py`` para fornecer seu script para " "Python, digitando ``py`` seguido pelo seu caminho de script::" +#: ../../faq/windows.rst:110 +msgid "" +"C:\\Users\\YourName> py Desktop\\hello.py\n" +"hello" +msgstr "" +"C:\\Users\\SeuNome> py Desktop\\oi.py\n" +"oi" + #: ../../faq/windows.rst:114 msgid "How do I make Python scripts executable?" msgstr "Como eu faço para criar programas Python executáveis?" @@ -327,7 +371,7 @@ msgstr "" "enquanto a vinculação em tempo de execução significa vincular a :file:" "`python{NN}.dll`. (Nota geral: :file:`python{NN}.lib` é a chamada \"import " "lib\" correspondente a :file:`python{NN}.dll`. Apenas define símbolos para o " -"vinculador.)" +"ligador.)" #: ../../faq/windows.rst:182 msgid "" @@ -394,6 +438,20 @@ msgstr "" "Em suma, você pode utilizar o código a seguir para inicializar o " "interpretador Python com seu módulo de extensão." +#: ../../faq/windows.rst:210 +msgid "" +"#include \n" +"...\n" +"Py_Initialize(); // Initialize Python.\n" +"initmyAppc(); // Initialize (import) the helper class.\n" +"PyRun_SimpleString(\"import myApp\"); // Import the shadow class." +msgstr "" +"#include \n" +"...\n" +"Py_Initialize(); // Inicializa Python.\n" +"initmyAppc(); // Inicializa (importa) a classe auxiliar.\n" +"PyRun_SimpleString(\"import myApp\"); // Importa a classe sombra." + #: ../../faq/windows.rst:218 msgid "" "There are two problems with Python's C API which will become apparent if you " @@ -423,6 +481,16 @@ msgstr "" "Problema 2: SWIG gera o seguinte código ao gerar invólucros para funções sem " "retorno:" +#: ../../faq/windows.rst:229 +msgid "" +"Py_INCREF(Py_None);\n" +"_resultobj = Py_None;\n" +"return _resultobj;" +msgstr "" +"Py_INCREF(Py_None);\n" +"_resultobj = Py_None;\n" +"return _resultobj;" + #: ../../faq/windows.rst:235 msgid "" "Alas, Py_None is a macro that expands to a reference to a complex data " @@ -434,6 +502,10 @@ msgstr "" "Novamente, esse código falhará em um ambiente com vários compiladores. " "Substitua esse código por:" +#: ../../faq/windows.rst:239 +msgid "return Py_BuildValue(\"\");" +msgstr "return Py_BuildValue(\"\");" + #: ../../faq/windows.rst:243 msgid "" "It may be possible to use SWIG's ``%typemap`` command to make the change " diff --git a/glossary.po b/glossary.po index 5ee410e5b..d0d7e7c96 100644 --- a/glossary.po +++ b/glossary.po @@ -1,34 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# felipe caridade fernandes , 2021 -# Marco Rougeth , 2021 -# Welington Carlos , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Alexandre B A Villares, 2021 -# Vinicius Gubiani Ferreira , 2021 -# yyyyyyyan , 2021 -# David Macedo, 2022 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-03-21 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -90,17 +81,16 @@ msgid "" "module), import finders and loaders (in the :mod:`importlib.abc` module). " "You can create your own ABCs with the :mod:`abc` module." msgstr "" -"Classes bases abstratas complementam :term:`tipagem pato `, " -"fornecendo uma maneira de definir interfaces quando outras técnicas, como :" -"func:`hasattr`, seriam desajeitadas ou sutilmente erradas (por exemplo, com :" -"ref:`métodos mágicos `). CBAs introduzem subclasses " -"virtuais, classes que não herdam de uma classe mas ainda são reconhecidas " -"por :func:`isinstance` e :func:`issubclass`; veja a documentação do módulo :" -"mod:`abc`. Python vem com muitas CBAs embutidas para estruturas de dados (no " -"módulo :mod:`collections.abc`), números (no módulo :mod:`numbers`), fluxos " -"(no módulo :mod:`io`), localizadores e carregadores de importação (no " -"módulo :mod:`importlib.abc`). Você pode criar suas próprias CBAs com o " -"módulo :mod:`abc`." +"Classes bases abstratas complementam :term:`tipagem pato`, fornecendo uma " +"maneira de definir interfaces quando outras técnicas, como :func:`hasattr`, " +"seriam desajeitadas ou sutilmente erradas (por exemplo, com :ref:`métodos " +"mágicos `). ABCs introduzem subclasses virtuais, classes que " +"não herdam de uma classe mas ainda são reconhecidas por :func:`isinstance` " +"e :func:`issubclass`; veja a documentação do módulo :mod:`abc`. Python vem " +"com muitas ABCs embutidas para estruturas de dados (no módulo :mod:" +"`collections.abc`), números (no módulo :mod:`numbers`), fluxos (no módulo :" +"mod:`io`), localizadores e carregadores de importação (no módulo :mod:" +"`importlib.abc`). Você pode criar suas próprias ABCs com o módulo :mod:`abc`." #: ../../glossary.rst:38 msgid "annotation" @@ -122,8 +112,8 @@ msgid "" "in the :attr:`__annotations__` special attribute of modules, classes, and " "functions, respectively." msgstr "" -"Anotações de variáveis ​​locais não podem ser acessadas em tempo de execução, " -"mas anotações de variáveis ​​globais, atributos de classe e funções são " +"Anotações de variáveis ​locais não podem ser acessadas em tempo de execução, " +"mas anotações de variáveis ​globais, atributos de classe e funções são " "armazenadas no atributo especial :attr:`__annotations__` de módulos, classes " "e funções, respectivamente." @@ -161,6 +151,14 @@ msgstr "" "dicionário precedido por ``**``. Por exemplo, ``3`` e ``5`` são ambos " "argumentos nomeados na chamada da função :func:`complex` a seguir::" +#: ../../glossary.rst:64 +msgid "" +"complex(real=3, imag=5)\n" +"complex(**{'real': 3, 'imag': 5})" +msgstr "" +"complex(real=3, imag=5)\n" +"complex(**{'real': 3, 'imag': 5})" + #: ../../glossary.rst:67 msgid "" ":dfn:`positional argument`: an argument that is not a keyword argument. " @@ -174,6 +172,14 @@ msgstr "" "por ``*``. Por exemplo, ``3`` e ``5`` são ambos argumentos posicionais nas " "chamadas a seguir::" +#: ../../glossary.rst:73 +msgid "" +"complex(3, 5)\n" +"complex(*(3, 5))" +msgstr "" +"complex(3, 5)\n" +"complex(*(3, 5))" + #: ../../glossary.rst:76 msgid "" "Arguments are assigned to the named local variables in a function body. See " @@ -206,8 +212,8 @@ msgid "" "statement by defining :meth:`~object.__aenter__` and :meth:`~object." "__aexit__` methods. Introduced by :pep:`492`." msgstr "" -"Um objeto que controla o ambiente visto numa instrução :keyword:`async with` " -"por meio da definição dos métodos :meth:`~object.__aenter__` e :meth:" +"Um objeto que controla o ambiente envolto numa instrução :keyword:`async " +"with` por meio da definição dos métodos :meth:`~object.__aenter__` e :meth:" "`~object.__aexit__`. Introduzido pela :pep:`492`." #: ../../glossary.rst:89 @@ -268,13 +274,13 @@ msgstr "" #: ../../glossary.rst:112 msgid "" "Each :keyword:`yield` temporarily suspends processing, remembering the " -"location execution state (including local variables and pending try-" -"statements). When the *asynchronous generator iterator* effectively resumes " -"with another awaitable returned by :meth:`~object.__anext__`, it picks up " -"where it left off. See :pep:`492` and :pep:`525`." +"execution state (including local variables and pending try-statements). " +"When the *asynchronous generator iterator* effectively resumes with another " +"awaitable returned by :meth:`~object.__anext__`, it picks up where it left " +"off. See :pep:`492` and :pep:`525`." msgstr "" "Cada :keyword:`yield` suspende temporariamente o processamento, lembrando o " -"estado de execução do local (incluindo variáveis locais e instruções ``try`` " +"estado de execução (incluindo variáveis locais e instruções ``try`` " "pendentes). Quando o *iterador gerador assíncrono* é efetivamente retomado " "com outro aguardável retornado por :meth:`~object.__anext__`, ele inicia de " "onde parou. Veja :pep:`492` e :pep:`525`." @@ -425,7 +431,7 @@ msgstr "" #: ../../glossary.rst:174 msgid "bytes-like object" -msgstr "objeto byte ou similar" +msgstr "objeto bytes ou similar" #: ../../glossary.rst:176 msgid "" @@ -438,8 +444,8 @@ msgid "" msgstr "" "Um objeto com suporte ao o :ref:`bufferobjects` e que pode exportar um " "buffer C :term:`contíguo `. Isso inclui todos os objetos :class:" -"`bytes`, :class:`bytearray` e :class:`array.array`, além de muitos objetos :" -"class:`memoryview` comuns. Objetos byte ou similar podem ser usados para " +"`bytes`, :class:`bytearray` e :class:`array.array`, além de muitos objetos :" +"class:`memoryview` comuns. Objetos bytes ou similar podem ser usados para " "várias operações que funcionam com dados binários; isso inclui compactação, " "salvamento em um arquivo binário e envio por um soquete." @@ -453,12 +459,13 @@ msgid "" "include :class:`bytes` and a :class:`memoryview` of a :class:`bytes` object." msgstr "" "Algumas operações precisam que os dados binários sejam mutáveis. A " -"documentação geralmente se refere a eles como \"objetos byte ou similar para " -"leitura e escrita\". Exemplos de objetos de buffer mutável incluem :class:" -"`bytearray` e um :class:`memoryview` de um :class:`bytearray`. Outras " +"documentação geralmente se refere a eles como \"objetos bytes ou similar " +"para leitura e escrita\". Exemplos de objetos de buffer mutável incluem :" +"class:`bytearray` e um :class:`memoryview` de um :class:`bytearray`. Outras " "operações exigem que os dados binários sejam armazenados em objetos " -"imutáveis (\"objetos byte ou similar para somente leitura\"); exemplos disso " -"incluem :class:`bytes` e a :class:`memoryview` de um objeto :class:`bytes`." +"imutáveis (\"objetos bytes ou similar para somente leitura\"); exemplos " +"disso incluem :class:`bytes` e a :class:`memoryview` de um objeto :class:" +"`bytes`." #: ../../glossary.rst:191 msgid "bytecode" @@ -505,6 +512,10 @@ msgstr "" "Um chamável é um objeto que pode ser chamado, possivelmente com um conjunto " "de argumentos (veja :term:`argumento`), com a seguinte sintaxe::" +#: ../../glossary.rst:210 +msgid "callable(argument1, argument2, argumentN)" +msgstr "chamavel(argumento1, argumento2, argumentoN)" + #: ../../glossary.rst:212 msgid "" "A :term:`function`, and by extension a :term:`method`, is a callable. An " @@ -553,10 +564,71 @@ msgstr "" "nível da classe (ou seja, não em uma instância da classe)." #: ../../glossary.rst:228 +msgid "closure variable" +msgstr "variável de clausura" + +#: ../../glossary.rst:230 +msgid "" +"A :term:`free variable` referenced from a :term:`nested scope` that is " +"defined in an outer scope rather than being resolved at runtime from the " +"globals or builtin namespaces. May be explicitly defined with the :keyword:" +"`nonlocal` keyword to allow write access, or implicitly defined if the " +"variable is only being read." +msgstr "" +"Uma :term:`variável livre` referenciada de um :term:`escopo aninhado` que é " +"definida em um escopo externo em vez de ser resolvida em tempo de execução a " +"partir dos espaços de nomes embutido ou globais. Pode ser explicitamente " +"definida com a palavra reservada :keyword:`nonlocal` para permitir acesso de " +"gravação, ou implicitamente definida se a variável estiver sendo somente " +"lida." + +#: ../../glossary.rst:235 +msgid "" +"For example, in the ``inner`` function in the following code, both ``x`` and " +"``print`` are :term:`free variables `, but only ``x`` is a " +"*closure variable*::" +msgstr "" +"Por exemplo, na função ``interna`` no código a seguir, tanto ``x`` quanto " +"``print`` são :term:`variáveis ​livres `, mas somente ``x`` é " +"uma *variável de clausura*::" + +#: ../../glossary.rst:238 +msgid "" +"def outer():\n" +" x = 0\n" +" def inner():\n" +" nonlocal x\n" +" x += 1\n" +" print(x)\n" +" return inner" +msgstr "" +"def externa():\n" +" x = 0\n" +" def interna():\n" +" nonlocal x\n" +" x += 1\n" +" print(x)\n" +" return interna" + +#: ../../glossary.rst:246 +msgid "" +"Due to the :attr:`codeobject.co_freevars` attribute (which, despite its " +"name, only includes the names of closure variables rather than listing all " +"referenced free variables), the more general :term:`free variable` term is " +"sometimes used even when the intended meaning is to refer specifically to " +"closure variables." +msgstr "" +"Devido ao atributo :attr:`codeobject.co_freevars` (que, apesar do nome, " +"inclui apenas os nomes das variáveis ​de clausura em vez de listar todas as " +"variáveis ​livres referenciadas), o termo mais geral :term:`variável livre` " +"às vezes é usado mesmo quando o significado pretendido é se referir " +"especificamente às variáveis ​de clausura." + +#: ../../glossary.rst:250 msgid "complex number" msgstr "número complexo" -#: ../../glossary.rst:230 +#: ../../glossary.rst:252 msgid "" "An extension of the familiar real number system in which all numbers are " "expressed as a sum of a real part and an imaginary part. Imaginary numbers " @@ -580,45 +652,89 @@ msgstr "" "sabe se irá precisar deles, é quase certo que você pode ignorá-los sem " "problemas." -#: ../../glossary.rst:240 +#: ../../glossary.rst:262 +msgid "context" +msgstr "contexto" + +#: ../../glossary.rst:264 +msgid "" +"This term has different meanings depending on where and how it is used. Some " +"common meanings:" +msgstr "" +"Este termo tem diferentes significados dependendo de onde e como ele é " +"usado. Alguns significados comuns:" + +#: ../../glossary.rst:267 +msgid "" +"The temporary state or environment established by a :term:`context manager` " +"via a :keyword:`with` statement." +msgstr "" +"O estado ou ambiente temporário estabelecido por um :term:`gerenciador de " +"contexto` por meio de uma instrução :keyword:`with`." + +#: ../../glossary.rst:269 +msgid "" +"The collection of key­value bindings associated with a particular :class:" +"`contextvars.Context` object and accessed via :class:`~contextvars." +"ContextVar` objects. Also see :term:`context variable`." +msgstr "" +"A coleção de ligações de chave-valor associadas a um objeto :class:" +"`contextvars.Context` específico e acessadas por meio de objetos :class:" +"`~contextvars.ContextVar`. Veja também :term:`variável de contexto`." + +#: ../../glossary.rst:273 +msgid "" +"A :class:`contextvars.Context` object. Also see :term:`current context`." +msgstr "" +"Um objeto :class:`contextvars.Context`. Veja também :term:`contexto atual`." + +#: ../../glossary.rst:275 +msgid "context management protocol" +msgstr "protocolo de gerenciamento de contexto" + +#: ../../glossary.rst:277 +msgid "" +"The :meth:`~object.__enter__` and :meth:`~object.__exit__` methods called by " +"the :keyword:`with` statement. See :pep:`343`." +msgstr "" +"Os métodos :meth:`~object.__enter__` e :meth:`~object.__exit__` chamados " +"pela instrução :keyword:`with`. Veja :pep:`343`." + +#: ../../glossary.rst:279 msgid "context manager" msgstr "gerenciador de contexto" -#: ../../glossary.rst:242 +#: ../../glossary.rst:281 msgid "" -"An object which controls the environment seen in a :keyword:`with` statement " -"by defining :meth:`~object.__enter__` and :meth:`~object.__exit__` methods. " -"See :pep:`343`." +"An object which implements the :term:`context management protocol` and " +"controls the environment seen in a :keyword:`with` statement. See :pep:" +"`343`." msgstr "" -"Um objeto que controla o ambiente visto numa instrução :keyword:`with` por " -"meio da definição dos métodos :meth:`~object.__enter__` e :meth:`~object." -"__exit__`. Veja :pep:`343`." +"Um objeto que implementa o :term:`protocolo de gerenciamento de contexto` e " +"controla o ambiente envolto em uma instrução :keyword:`with`. Veja :pep:" +"`343`." -#: ../../glossary.rst:245 +#: ../../glossary.rst:284 msgid "context variable" msgstr "variável de contexto" -#: ../../glossary.rst:247 +#: ../../glossary.rst:286 msgid "" -"A variable which can have different values depending on its context. This is " -"similar to Thread-Local Storage in which each execution thread may have a " -"different value for a variable. However, with context variables, there may " -"be several contexts in one execution thread and the main usage for context " -"variables is to keep track of variables in concurrent asynchronous tasks. " -"See :mod:`contextvars`." +"A variable whose value depends on which context is the :term:`current " +"context`. Values are accessed via :class:`contextvars.ContextVar` objects. " +"Context variables are primarily used to isolate state between concurrent " +"asynchronous tasks." msgstr "" -"Uma variável que pode ter valores diferentes, dependendo do seu contexto. " -"Isso é semelhante ao armazenamento local de threads, no qual cada thread " -"pode ter um valor diferente para uma variável. No entanto, com variáveis de " -"contexto, pode haver vários contextos em uma thread e o principal uso para " -"variáveis de contexto é acompanhar as variáveis em tarefas assíncronas " -"simultâneas. Veja :mod:`contextvars`." +"Uma variável cujo valor depende de qual contexto é o :term:`contexto atual`. " +"Os valores são acessados ​por meio de objetos :class:`contextvars." +"ContextVar`. Variáveis de contexto são usadas principalmente para isolar o " +"estado entre tarefas assíncronas simultâneas." -#: ../../glossary.rst:254 +#: ../../glossary.rst:290 msgid "contiguous" msgstr "contíguo" -#: ../../glossary.rst:258 +#: ../../glossary.rst:294 msgid "" "A buffer is considered contiguous exactly if it is either *C-contiguous* or " "*Fortran contiguous*. Zero-dimensional buffers are C and Fortran " @@ -636,11 +752,11 @@ msgstr "" "visitar itens em ordem de endereço de memória. No entanto, nos vetores " "contíguos do Fortran, o primeiro índice varia mais rapidamente." -#: ../../glossary.rst:266 +#: ../../glossary.rst:302 msgid "coroutine" msgstr "corrotina" -#: ../../glossary.rst:268 +#: ../../glossary.rst:304 msgid "" "Coroutines are a more generalized form of subroutines. Subroutines are " "entered at one point and exited at another point. Coroutines can be " @@ -652,11 +768,11 @@ msgstr "" "entrar, sair, e continuar em muitos pontos diferentes. Elas podem ser " "implementadas com a instrução :keyword:`async def`. Veja também :pep:`492`." -#: ../../glossary.rst:273 +#: ../../glossary.rst:309 msgid "coroutine function" msgstr "função de corrotina" -#: ../../glossary.rst:275 +#: ../../glossary.rst:311 msgid "" "A function which returns a :term:`coroutine` object. A coroutine function " "may be defined with the :keyword:`async def` statement, and may contain :" @@ -668,11 +784,11 @@ msgstr "" "conter as palavras chaves :keyword:`await`, :keyword:`async for`, e :keyword:" "`async with`. Isso foi introduzido pela :pep:`492`." -#: ../../glossary.rst:280 +#: ../../glossary.rst:316 msgid "CPython" msgstr "CPython" -#: ../../glossary.rst:282 +#: ../../glossary.rst:318 msgid "" "The canonical implementation of the Python programming language, as " "distributed on `python.org `_. The term \"CPython\" " @@ -684,11 +800,32 @@ msgstr "" "\"CPython\" é usado quando necessário distinguir esta implementação de " "outras como Jython ou IronPython." -#: ../../glossary.rst:286 +#: ../../glossary.rst:322 +msgid "current context" +msgstr "contexto atual" + +#: ../../glossary.rst:324 +msgid "" +"The :term:`context` (:class:`contextvars.Context` object) that is currently " +"used by :class:`~contextvars.ContextVar` objects to access (get or set) the " +"values of :term:`context variables `. Each thread has its " +"own current context. Frameworks for executing asynchronous tasks (see :mod:" +"`asyncio`) associate each task with a context which becomes the current " +"context whenever the task starts or resumes execution." +msgstr "" +"O :term:`contexto` (objeto :class:`contextvars.Context`) que é usado " +"atualmente pelos objetos :class:`~contextvars.ContextVar` para acessar " +"(obter ou definir) os valores de :term:`variáveis de contexto `. Cada thread tem seu próprio contexto atual. Frameworks para " +"executar tarefas assíncronas (veja :mod:`asyncio`) associam cada tarefa a um " +"contexto que se torna o contexto atual sempre que a tarefa inicia ou retoma " +"a execução." + +#: ../../glossary.rst:330 msgid "decorator" msgstr "decorador" -#: ../../glossary.rst:288 +#: ../../glossary.rst:332 msgid "" "A function returning another function, usually applied as a function " "transformation using the ``@wrapper`` syntax. Common examples for " @@ -698,7 +835,7 @@ msgstr "" "transformação de função usando a sintaxe ``@wrapper``. Exemplos comuns para " "decoradores são :func:`classmethod` e :func:`staticmethod`." -#: ../../glossary.rst:292 +#: ../../glossary.rst:336 msgid "" "The decorator syntax is merely syntactic sugar, the following two function " "definitions are semantically equivalent::" @@ -706,7 +843,25 @@ msgstr "" "A sintaxe do decorador é meramente um açúcar sintático, as duas definições " "de funções a seguir são semanticamente equivalentes::" -#: ../../glossary.rst:303 +#: ../../glossary.rst:339 +msgid "" +"def f(arg):\n" +" ...\n" +"f = staticmethod(f)\n" +"\n" +"@staticmethod\n" +"def f(arg):\n" +" ..." +msgstr "" +"def f(arg):\n" +" ...\n" +"f = staticmethod(f)\n" +"\n" +"@staticmethod\n" +"def f(arg):\n" +" ..." + +#: ../../glossary.rst:347 msgid "" "The same concept exists for classes, but is less commonly used there. See " "the documentation for :ref:`function definitions ` and :ref:`class " @@ -716,11 +871,11 @@ msgstr "" "a documentação de :ref:`definições de função ` e :ref:`definições " "de classe ` para obter mais informações sobre decoradores." -#: ../../glossary.rst:306 +#: ../../glossary.rst:350 msgid "descriptor" msgstr "descritor" -#: ../../glossary.rst:308 +#: ../../glossary.rst:352 msgid "" "Any object which defines the methods :meth:`~object.__get__`, :meth:`~object." "__set__`, or :meth:`~object.__delete__`. When a class attribute is a " @@ -743,7 +898,7 @@ msgstr "" "funcionalidades incluindo funções, métodos, propriedades, métodos de classe, " "métodos estáticos e referências para superclasses." -#: ../../glossary.rst:319 +#: ../../glossary.rst:363 msgid "" "For more information about descriptors' methods, see :ref:`descriptors` or " "the :ref:`Descriptor How To Guide `." @@ -751,11 +906,11 @@ msgstr "" "Para obter mais informações sobre os métodos dos descritores, veja: :ref:" "`descriptors` ou o :ref:`Guia de Descritores `." -#: ../../glossary.rst:321 +#: ../../glossary.rst:365 msgid "dictionary" msgstr "dicionário" -#: ../../glossary.rst:323 +#: ../../glossary.rst:367 msgid "" "An associative array, where arbitrary keys are mapped to values. The keys " "can be any object with :meth:`~object.__hash__` and :meth:`~object.__eq__` " @@ -765,11 +920,11 @@ msgstr "" "chaves podem ser quaisquer objetos que possuam os métodos :meth:`~object." "__hash__` e :meth:`~object.__eq__`. Isso é chamado de hash em Perl." -#: ../../glossary.rst:327 +#: ../../glossary.rst:371 msgid "dictionary comprehension" msgstr "compreensão de dicionário" -#: ../../glossary.rst:329 +#: ../../glossary.rst:373 msgid "" "A compact way to process all or part of the elements in an iterable and " "return a dictionary with the results. ``results = {n: n ** 2 for n in " @@ -781,11 +936,11 @@ msgstr "" "for n in range(10)}`` gera um dicionário contendo a chave ``n`` mapeada para " "o valor ``n ** 2``. Veja :ref:`comprehensions`." -#: ../../glossary.rst:333 +#: ../../glossary.rst:377 msgid "dictionary view" msgstr "visão de dicionário" -#: ../../glossary.rst:335 +#: ../../glossary.rst:379 msgid "" "The objects returned from :meth:`dict.keys`, :meth:`dict.values`, and :meth:" "`dict.items` are called dictionary views. They provide a dynamic view on the " @@ -800,30 +955,30 @@ msgstr "" "dicionário a se tornar uma lista completa use ``list(dictview)``. Veja :ref:" "`dict-views`." -#: ../../glossary.rst:341 +#: ../../glossary.rst:385 msgid "docstring" msgstr "docstring" -#: ../../glossary.rst:343 +#: ../../glossary.rst:387 msgid "" "A string literal which appears as the first expression in a class, function " "or module. While ignored when the suite is executed, it is recognized by " -"the compiler and put into the :attr:`!__doc__` attribute of the enclosing " -"class, function or module. Since it is available via introspection, it is " -"the canonical place for documentation of the object." +"the compiler and put into the :attr:`~definition.__doc__` attribute of the " +"enclosing class, function or module. Since it is available via " +"introspection, it is the canonical place for documentation of the object." msgstr "" "Abreviatura de \"documentation string\" (string de documentação). Uma string " "literal que aparece como primeira expressão numa classe, função ou módulo. " "Ainda que sejam ignoradas quando a suíte é executada, é reconhecida pelo " -"compilador que a coloca no atributo :attr:`!__doc__` da classe, função ou " -"módulo que a encapsula. Como ficam disponíveis por meio de introspecção, " -"docstrings são o lugar canônico para documentação do objeto." +"compilador que a coloca no atributo :attr:`~definition.__doc__` da classe, " +"função ou módulo que a encapsula. Como ficam disponíveis por meio de " +"introspecção, docstrings são o lugar canônico para documentação do objeto." -#: ../../glossary.rst:349 +#: ../../glossary.rst:393 msgid "duck-typing" msgstr "tipagem pato" -#: ../../glossary.rst:351 +#: ../../glossary.rst:395 msgid "" "A programming style which does not look at an object's type to determine if " "it has the right interface; instead, the method or attribute is simply " @@ -847,11 +1002,11 @@ msgstr "" "class>`.) Ao invés disso, são normalmente empregados testes :func:`hasattr` " "ou programação :term:`EAFP`." -#: ../../glossary.rst:360 +#: ../../glossary.rst:404 msgid "EAFP" msgstr "EAFP" -#: ../../glossary.rst:362 +#: ../../glossary.rst:406 msgid "" "Easier to ask for forgiveness than permission. This common Python coding " "style assumes the existence of valid keys or attributes and catches " @@ -868,11 +1023,11 @@ msgstr "" "keyword:`try` e :keyword:`except`. A técnica diverge do estilo :term:`LBYL`, " "comum em outras linguagens como C, por exemplo." -#: ../../glossary.rst:368 +#: ../../glossary.rst:412 msgid "expression" msgstr "expressão" -#: ../../glossary.rst:370 +#: ../../glossary.rst:414 msgid "" "A piece of syntax which can be evaluated to some value. In other words, an " "expression is an accumulation of expression elements like literals, names, " @@ -891,11 +1046,11 @@ msgstr "" "como, por exemplo, :keyword:`while`. Atribuições também são instruções, não " "expressões." -#: ../../glossary.rst:377 +#: ../../glossary.rst:421 msgid "extension module" msgstr "módulo de extensão" -#: ../../glossary.rst:379 +#: ../../glossary.rst:423 msgid "" "A module written in C or C++, using Python's C API to interact with the core " "and with user code." @@ -903,11 +1058,11 @@ msgstr "" "Um módulo escrito em C ou C++, usando a API C do Python para interagir tanto " "com código de usuário quanto do núcleo." -#: ../../glossary.rst:381 +#: ../../glossary.rst:425 msgid "f-string" msgstr "f-string" -#: ../../glossary.rst:383 +#: ../../glossary.rst:427 msgid "" "String literals prefixed with ``'f'`` or ``'F'`` are commonly called \"f-" "strings\" which is short for :ref:`formatted string literals `. " @@ -917,11 +1072,11 @@ msgstr "" "strings\" que é uma abreviação de :ref:`formatted string literals `. Veja também :pep:`498`." -#: ../../glossary.rst:386 +#: ../../glossary.rst:430 msgid "file object" msgstr "objeto arquivo" -#: ../../glossary.rst:388 +#: ../../glossary.rst:432 msgid "" "An object exposing a file-oriented API (with methods such as :meth:`!read` " "or :meth:`!write`) to an underlying resource. Depending on the way it was " @@ -938,7 +1093,7 @@ msgstr "" "soquetes, pipes, etc.). Objetos arquivo também são chamados de :dfn:`objetos " "arquivo ou similares` ou :dfn:`fluxos`." -#: ../../glossary.rst:396 +#: ../../glossary.rst:440 msgid "" "There are actually three categories of file objects: raw :term:`binary files " "`, buffered :term:`binary files ` and :term:`text " @@ -952,19 +1107,19 @@ msgstr "" "módulo :mod:`io`. A forma canônica para criar um objeto arquivo é usando a " "função :func:`open`." -#: ../../glossary.rst:401 +#: ../../glossary.rst:445 msgid "file-like object" msgstr "objeto arquivo ou similar" -#: ../../glossary.rst:403 +#: ../../glossary.rst:447 msgid "A synonym for :term:`file object`." msgstr "Um sinônimo do termo :term:`objeto arquivo`." -#: ../../glossary.rst:404 +#: ../../glossary.rst:448 msgid "filesystem encoding and error handler" msgstr "tratador de erros e codificação do sistema de arquivos" -#: ../../glossary.rst:406 +#: ../../glossary.rst:450 msgid "" "Encoding and error handler used by Python to decode bytes from the operating " "system and encode Unicode to the operating system." @@ -972,7 +1127,7 @@ msgstr "" "Tratador de erros e codificação usado pelo Python para decodificar bytes do " "sistema operacional e codificar Unicode para o sistema operacional." -#: ../../glossary.rst:409 +#: ../../glossary.rst:453 msgid "" "The filesystem encoding must guarantee to successfully decode all bytes " "below 128. If the file system encoding fails to provide this guarantee, API " @@ -983,7 +1138,7 @@ msgstr "" "arquivos falhar em fornecer essa garantia, as funções da API podem levantar :" "exc:`UnicodeError`." -#: ../../glossary.rst:413 +#: ../../glossary.rst:457 msgid "" "The :func:`sys.getfilesystemencoding` and :func:`sys." "getfilesystemencodeerrors` functions can be used to get the filesystem " @@ -993,7 +1148,7 @@ msgstr "" "getfilesystemencodeerrors` podem ser usadas para obter o tratador de erros e " "codificação do sistema de arquivos." -#: ../../glossary.rst:417 +#: ../../glossary.rst:461 msgid "" "The :term:`filesystem encoding and error handler` are configured at Python " "startup by the :c:func:`PyConfig_Read` function: see :c:member:`~PyConfig." @@ -1005,15 +1160,15 @@ msgstr "" "veja os membros :c:member:`~PyConfig.filesystem_encoding` e :c:member:" "`~PyConfig.filesystem_errors` do :c:type:`PyConfig`." -#: ../../glossary.rst:422 +#: ../../glossary.rst:466 msgid "See also the :term:`locale encoding`." msgstr "Veja também :term:`codificação da localidade`." -#: ../../glossary.rst:423 +#: ../../glossary.rst:467 msgid "finder" msgstr "localizador" -#: ../../glossary.rst:425 +#: ../../glossary.rst:469 msgid "" "An object that tries to find the :term:`loader` for a module that is being " "imported." @@ -1021,7 +1176,7 @@ msgstr "" "Um objeto que tenta encontrar o :term:`carregador` para um módulo que está " "sendo importado." -#: ../../glossary.rst:428 +#: ../../glossary.rst:472 msgid "" "There are two types of finder: :term:`meta path finders ` " "for use with :data:`sys.meta_path`, and :term:`path entry finders ` para uso com :data:`sys.meta_path`, e :term:`localizadores de " "entrada de caminho ` para uso com :data:`sys.path_hooks`." -#: ../../glossary.rst:432 -msgid "See :ref:`importsystem` and :mod:`importlib` for much more detail." -msgstr "Veja :ref:`importsystem` e :mod:`importlib` para muito mais detalhes." +#: ../../glossary.rst:476 +msgid "" +"See :ref:`finders-and-loaders` and :mod:`importlib` for much more detail." +msgstr "" +"Veja :ref:`finders-and-loaders` e :mod:`importlib` para muito mais detalhes." -#: ../../glossary.rst:433 +#: ../../glossary.rst:477 msgid "floor division" msgstr "divisão pelo piso" -#: ../../glossary.rst:435 +#: ../../glossary.rst:479 msgid "" "Mathematical division that rounds down to nearest integer. The floor " "division operator is ``//``. For example, the expression ``11 // 4`` " @@ -1053,11 +1210,11 @@ msgstr "" "de ponto flutuante. Note que ``(-11) // 4`` é ``-3`` porque é ``-2.75`` " "arredondado *para baixo*. Consulte a :pep:`238`." -#: ../../glossary.rst:440 +#: ../../glossary.rst:484 msgid "free threading" msgstr "threads livres" -#: ../../glossary.rst:442 +#: ../../glossary.rst:486 msgid "" "A threading model where multiple threads can run Python bytecode " "simultaneously within the same interpreter. This is in contrast to the :" @@ -1069,11 +1226,31 @@ msgstr "" "`trava global do interpretador` que permite apenas uma thread por vez " "executar bytecode Python. Veja :pep:`703`." -#: ../../glossary.rst:446 +#: ../../glossary.rst:490 +msgid "free variable" +msgstr "variável livre" + +#: ../../glossary.rst:492 +msgid "" +"Formally, as defined in the :ref:`language execution model `, a " +"free variable is any variable used in a namespace which is not a local " +"variable in that namespace. See :term:`closure variable` for an example. " +"Pragmatically, due to the name of the :attr:`codeobject.co_freevars` " +"attribute, the term is also sometimes used as a synonym for :term:`closure " +"variable`." +msgstr "" +"Formalmente, conforme definido no :ref:`modelo de execução de linguagem " +"`, uma variável livre é qualquer variável usada em um espaço de " +"nomes que não seja uma variável local naquele espaço de nomes. Veja :term:" +"`variável de clausura` para um exemplo. Pragmaticamente, devido ao nome do " +"atributo :attr:`codeobject.co_freevars`, o termo também é usado algumas " +"vezes como sinônimo de :term:`variável de clausura`." + +#: ../../glossary.rst:497 msgid "function" msgstr "função" -#: ../../glossary.rst:448 +#: ../../glossary.rst:499 msgid "" "A series of statements which returns some value to a caller. It can also be " "passed zero or more :term:`arguments ` which may be used in the " @@ -1085,15 +1262,15 @@ msgstr "" "usados na execução do corpo. Veja também :term:`parâmetro`, :term:`método` e " "a seção :ref:`function`." -#: ../../glossary.rst:452 +#: ../../glossary.rst:503 msgid "function annotation" msgstr "anotação de função" -#: ../../glossary.rst:454 +#: ../../glossary.rst:505 msgid "An :term:`annotation` of a function parameter or return value." msgstr "Uma :term:`anotação` de um parâmetro de função ou valor de retorno." -#: ../../glossary.rst:456 +#: ../../glossary.rst:507 msgid "" "Function annotations are usually used for :term:`type hints `: " "for example, this function is expected to take two :class:`int` arguments " @@ -1103,11 +1280,19 @@ msgstr "" "hint>`: por exemplo, essa função espera receber dois argumentos :class:`int` " "e também é esperado que devolva um valor :class:`int`::" -#: ../../glossary.rst:464 +#: ../../glossary.rst:512 +msgid "" +"def sum_two_numbers(a: int, b: int) -> int:\n" +" return a + b" +msgstr "" +"def soma_dois_numeros(a: int, b: int) -> int:\n" +" return a + b" + +#: ../../glossary.rst:515 msgid "Function annotation syntax is explained in section :ref:`function`." msgstr "A sintaxe de anotação de função é explicada na seção :ref:`function`." -#: ../../glossary.rst:466 +#: ../../glossary.rst:517 msgid "" "See :term:`variable annotation` and :pep:`484`, which describe this " "functionality. Also see :ref:`annotations-howto` for best practices on " @@ -1117,11 +1302,11 @@ msgstr "" "funcionalidade. Veja também :ref:`annotations-howto` para as melhores " "práticas sobre como trabalhar com anotações." -#: ../../glossary.rst:470 +#: ../../glossary.rst:521 msgid "__future__" msgstr "__future__" -#: ../../glossary.rst:472 +#: ../../glossary.rst:523 msgid "" "A :ref:`future statement `, ``from __future__ import ``, " "directs the compiler to compile the current module using syntax or semantics " @@ -1138,11 +1323,21 @@ msgstr "" "avaliando suas variáveis, você pode ver quando um novo recurso foi " "inicialmente adicionado à linguagem e quando será (ou se já é) o padrão::" -#: ../../glossary.rst:483 +#: ../../glossary.rst:531 +msgid "" +">>> import __future__\n" +">>> __future__.division\n" +"_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)" +msgstr "" +">>> import __future__\n" +">>> __future__.division\n" +"_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)" + +#: ../../glossary.rst:534 msgid "garbage collection" msgstr "coleta de lixo" -#: ../../glossary.rst:485 +#: ../../glossary.rst:536 msgid "" "The process of freeing memory when it is not used anymore. Python performs " "garbage collection via reference counting and a cyclic garbage collector " @@ -1155,11 +1350,11 @@ msgstr "" "é capaz de detectar e interromper referências cíclicas. O coletor de lixo " "pode ser controlado usando o módulo :mod:`gc`." -#: ../../glossary.rst:490 ../../glossary.rst:491 +#: ../../glossary.rst:541 ../../glossary.rst:542 msgid "generator" msgstr "gerador" -#: ../../glossary.rst:493 +#: ../../glossary.rst:544 msgid "" "A function which returns a :term:`generator iterator`. It looks like a " "normal function except that it contains :keyword:`yield` expressions for " @@ -1172,7 +1367,7 @@ msgstr "" "um laço \"for\" ou que podem ser obtidos um de cada vez com a função :func:" "`next`." -#: ../../glossary.rst:498 +#: ../../glossary.rst:549 msgid "" "Usually refers to a generator function, but may refer to a *generator " "iterator* in some contexts. In cases where the intended meaning isn't " @@ -1182,32 +1377,32 @@ msgstr "" "*iterador gerador* em alguns contextos. Em alguns casos onde o significado " "desejado não está claro, usar o termo completo evita ambiguidade." -#: ../../glossary.rst:501 +#: ../../glossary.rst:552 msgid "generator iterator" msgstr "iterador gerador" -#: ../../glossary.rst:503 +#: ../../glossary.rst:554 msgid "An object created by a :term:`generator` function." msgstr "Um objeto criado por uma função :term:`geradora `." -#: ../../glossary.rst:505 +#: ../../glossary.rst:556 msgid "" "Each :keyword:`yield` temporarily suspends processing, remembering the " -"location execution state (including local variables and pending try-" -"statements). When the *generator iterator* resumes, it picks up where it " -"left off (in contrast to functions which start fresh on every invocation)." +"execution state (including local variables and pending try-statements). " +"When the *generator iterator* resumes, it picks up where it left off (in " +"contrast to functions which start fresh on every invocation)." msgstr "" "Cada :keyword:`yield` suspende temporariamente o processamento, memorizando " -"o estado da execução local (incluindo variáveis locais e instruções try " +"o estado da execução (incluindo variáveis locais e instruções try " "pendentes). Quando o *iterador gerador* retorna, ele se recupera do último " "ponto onde estava (em contrapartida as funções que iniciam uma nova execução " "a cada vez que são invocadas)." -#: ../../glossary.rst:511 ../../glossary.rst:512 +#: ../../glossary.rst:562 ../../glossary.rst:563 msgid "generator expression" msgstr "expressão geradora" -#: ../../glossary.rst:514 +#: ../../glossary.rst:565 msgid "" "An :term:`expression` that returns an :term:`iterator`. It looks like a " "normal expression followed by a :keyword:`!for` clause defining a loop " @@ -1219,11 +1414,20 @@ msgstr "" "laço, um intervalo, e uma cláusula :keyword:`!if` opcional. A expressão " "combinada gera valores para uma função encapsuladora::" -#: ../../glossary.rst:521 +#: ../../glossary.rst:570 +msgid "" +">>> sum(i*i for i in range(10)) # sum of squares 0, 1, 4, ... 81\n" +"285" +msgstr "" +">>> sum(i*i for i in range(10)) # soma dos quadrados 0, 1, 4, ... " +"81\n" +"285" + +#: ../../glossary.rst:572 msgid "generic function" msgstr "função genérica" -#: ../../glossary.rst:523 +#: ../../glossary.rst:574 msgid "" "A function composed of multiple functions implementing the same operation " "for different types. Which implementation should be used during a call is " @@ -1233,7 +1437,7 @@ msgstr "" "diferentes tipos. Qual implementação deverá ser usada durante a execução é " "determinada pelo algoritmo de despacho." -#: ../../glossary.rst:527 +#: ../../glossary.rst:578 msgid "" "See also the :term:`single dispatch` glossary entry, the :func:`functools." "singledispatch` decorator, and :pep:`443`." @@ -1241,11 +1445,11 @@ msgstr "" "Veja também a entrada :term:`despacho único` no glossário, o decorador :func:" "`functools.singledispatch`, e a :pep:`443`." -#: ../../glossary.rst:529 +#: ../../glossary.rst:580 msgid "generic type" msgstr "tipo genérico" -#: ../../glossary.rst:531 +#: ../../glossary.rst:582 msgid "" "A :term:`type` that can be parameterized; typically a :ref:`container " "class` such as :class:`list` or :class:`dict`. Used for :" @@ -1255,7 +1459,7 @@ msgstr "" "contêiner` tal como :class:`list` ou :class:`dict`. Usado " "para :term:`dicas de tipo ` e :term:`anotações `." -#: ../../glossary.rst:536 +#: ../../glossary.rst:587 msgid "" "For more details, see :ref:`generic alias types`, :pep:" "`483`, :pep:`484`, :pep:`585`, and the :mod:`typing` module." @@ -1263,19 +1467,19 @@ msgstr "" "Para mais detalhes, veja :ref:`tipo apelido genérico `, :" "pep:`483`, :pep:`484`, :pep:`585`, e o módulo :mod:`typing`." -#: ../../glossary.rst:538 +#: ../../glossary.rst:589 msgid "GIL" msgstr "GIL" -#: ../../glossary.rst:540 +#: ../../glossary.rst:591 msgid "See :term:`global interpreter lock`." msgstr "Veja :term:`trava global do interpretador`." -#: ../../glossary.rst:541 +#: ../../glossary.rst:592 msgid "global interpreter lock" msgstr "trava global do interpretador" -#: ../../glossary.rst:543 +#: ../../glossary.rst:594 msgid "" "The mechanism used by the :term:`CPython` interpreter to assure that only " "one thread executes Python :term:`bytecode` at a time. This simplifies the " @@ -1293,7 +1497,7 @@ msgstr "" "interpretador em si seja multitarefa, às custas de muito do paralelismo já " "provido por máquinas multiprocessador." -#: ../../glossary.rst:552 +#: ../../glossary.rst:603 msgid "" "However, some extension modules, either standard or third-party, are " "designed so as to release the GIL when doing computationally intensive tasks " @@ -1305,28 +1509,28 @@ msgstr "" "computacionalmente muito intensas, como compactação ou cálculos de hash. " "Além disso, a GIL é sempre liberado nas operações de E/S." -#: ../../glossary.rst:557 +#: ../../glossary.rst:608 msgid "" "As of Python 3.13, the GIL can be disabled using the :option:`--disable-gil` " "build configuration. After building Python with this option, code must be " -"run with :option:`-X gil 0 <-X>` or after setting the :envvar:`PYTHON_GIL=0 " +"run with :option:`-X gil=0 <-X>` or after setting the :envvar:`PYTHON_GIL=0 " "` environment variable. This feature enables improved " "performance for multi-threaded applications and makes it easier to use multi-" "core CPUs efficiently. For more details, see :pep:`703`." msgstr "" "A partir de Python 3.13, o GIL pode ser desabilitado usando a configuração " "de construção :option:`--disable-gil`. Depois de construir Python com essa " -"opção, o código deve ser executado com a opção :option:`-X gil 0 <-X>` ou a " +"opção, o código deve ser executado com a opção :option:`-X gil=0 <-X>` ou a " "variável de ambiente :envvar:`PYTHON_GIL=0 ` deve estar " "definida. Esse recurso provê um desempenho melhor para aplicações com " "múltiplas threads e torna mais fácil o uso eficiente de CPUs com múltiplos " "núcleos. Para mais detalhes, veja :pep:`703`." -#: ../../glossary.rst:563 +#: ../../glossary.rst:614 msgid "hash-based pyc" msgstr "pyc baseado em hash" -#: ../../glossary.rst:565 +#: ../../glossary.rst:616 msgid "" "A bytecode cache file that uses the hash rather than the last-modified time " "of the corresponding source file to determine its validity. See :ref:`pyc-" @@ -1336,11 +1540,11 @@ msgstr "" "arquivo de código-fonte foi modificado pela última vez, para determinar a " "sua validade. Veja :ref:`pyc-invalidation`." -#: ../../glossary.rst:568 +#: ../../glossary.rst:619 msgid "hashable" msgstr "hasheável" -#: ../../glossary.rst:570 +#: ../../glossary.rst:621 msgid "" "An object is *hashable* if it has a hash value which never changes during " "its lifetime (it needs a :meth:`~object.__hash__` method), and can be " @@ -1353,7 +1557,7 @@ msgstr "" "Objetos hasheáveis que são comparados como iguais devem ter o mesmo valor de " "hash." -#: ../../glossary.rst:576 +#: ../../glossary.rst:627 msgid "" "Hashability makes an object usable as a dictionary key and a set member, " "because these data structures use the hash value internally." @@ -1362,7 +1566,7 @@ msgstr "" "dicionário e como um membro de conjunto, pois estas estruturas de dados " "utilizam os valores de hash internamente." -#: ../../glossary.rst:579 +#: ../../glossary.rst:630 msgid "" "Most of Python's immutable built-in objects are hashable; mutable containers " "(such as lists or dictionaries) are not; immutable containers (such as " @@ -1379,11 +1583,11 @@ msgstr "" "desigual (exceto entre si mesmos), e o seu valor hash é derivado a partir do " "seu :func:`id`." -#: ../../glossary.rst:586 +#: ../../glossary.rst:637 msgid "IDLE" msgstr "IDLE" -#: ../../glossary.rst:588 +#: ../../glossary.rst:639 msgid "" "An Integrated Development and Learning Environment for Python. :ref:`idle` " "is a basic editor and interpreter environment which ships with the standard " @@ -1393,39 +1597,33 @@ msgstr "" "`idle` é um editor básico e um ambiente interpretador que vem junto com a " "distribuição padrão do Python." -#: ../../glossary.rst:591 +#: ../../glossary.rst:642 msgid "immortal" msgstr "imortal" -#: ../../glossary.rst:593 -msgid "" -"If an object is immortal, its reference count is never modified, and " -"therefore it is never deallocated." -msgstr "" -"Se um objeto é imortal, sua contagem de referências nunca é modificada, e " -"portanto ele nunca será desalocado." - -#: ../../glossary.rst:596 +#: ../../glossary.rst:644 msgid "" -"Built-in strings and singletons are immortal objects. For example, :const:" -"`True` and :const:`None` singletons are immmortal." +"*Immortal objects* are a CPython implementation detail introduced in :pep:" +"`683`." msgstr "" -"Strings embutidas e singletons são objetos imortais. Por exemplo, os " -"singletons :const:`True` e :const:`None` são imortais." +"*Objetos imortais* são um detalhe da implementação do CPython introduzida " +"na :pep:`683`." -#: ../../glossary.rst:599 +#: ../../glossary.rst:647 msgid "" -"See `PEP 683 – Immortal Objects, Using a Fixed Refcount `_ for more information." +"If an object is immortal, its :term:`reference count` is never modified, and " +"therefore it is never deallocated while the interpreter is running. For " +"example, :const:`True` and :const:`None` are immortal in CPython." msgstr "" -"Veja `PEP 683 – Immortal Objects, Using a Fixed Refcount `_ para mais informações." +"Se um objeto é imortal, sua :term:`contagem de referências` nunca é " +"modificada e, portanto, nunca é desalocado enquanto o interpretador está em " +"execução. Por exemplo, :const:`True` e :const:`None` são imortais no CPython." -#: ../../glossary.rst:601 +#: ../../glossary.rst:650 msgid "immutable" msgstr "imutável" -#: ../../glossary.rst:603 +#: ../../glossary.rst:652 msgid "" "An object with a fixed value. Immutable objects include numbers, strings " "and tuples. Such an object cannot be altered. A new object has to be " @@ -1439,11 +1637,11 @@ msgstr "" "têm um papel importante em lugares onde um valor constante de hash seja " "necessário, como por exemplo uma chave em um dicionário." -#: ../../glossary.rst:608 +#: ../../glossary.rst:657 msgid "import path" msgstr "caminho de importação" -#: ../../glossary.rst:610 +#: ../../glossary.rst:659 msgid "" "A list of locations (or :term:`path entries `) that are searched " "by the :term:`path based finder` for modules to import. During import, this " @@ -1456,11 +1654,11 @@ msgstr "" "partir de :data:`sys.path`, mas para subpacotes ela também pode vir do " "atributo ``__path__`` de pacotes-pai." -#: ../../glossary.rst:615 +#: ../../glossary.rst:664 msgid "importing" msgstr "importação" -#: ../../glossary.rst:617 +#: ../../glossary.rst:666 msgid "" "The process by which Python code in one module is made available to Python " "code in another module." @@ -1468,11 +1666,11 @@ msgstr "" "O processo pelo qual o código Python em um módulo é disponibilizado para o " "código Python em outro módulo." -#: ../../glossary.rst:619 +#: ../../glossary.rst:668 msgid "importer" msgstr "importador" -#: ../../glossary.rst:621 +#: ../../glossary.rst:670 msgid "" "An object that both finds and loads a module; both a :term:`finder` and :" "term:`loader` object." @@ -1480,11 +1678,11 @@ msgstr "" "Um objeto que localiza e carrega um módulo; Tanto um :term:`localizador` e o " "objeto :term:`carregador`." -#: ../../glossary.rst:623 +#: ../../glossary.rst:672 msgid "interactive" msgstr "interativo" -#: ../../glossary.rst:625 +#: ../../glossary.rst:674 msgid "" "Python has an interactive interpreter which means you can enter statements " "and expressions at the interpreter prompt, immediately execute them and see " @@ -1502,11 +1700,11 @@ msgstr "" "do comando ``help(x)``). Para saber mais sobre modo interativo, veja :ref:" "`tut-interac`." -#: ../../glossary.rst:632 +#: ../../glossary.rst:681 msgid "interpreted" msgstr "interpretado" -#: ../../glossary.rst:634 +#: ../../glossary.rst:683 msgid "" "Python is an interpreted language, as opposed to a compiled one, though the " "distinction can be blurry because of the presence of the bytecode compiler. " @@ -1524,11 +1722,11 @@ msgstr "" "geralmente serem executados mais lentamente. Veja também :term:`interativo " "`." -#: ../../glossary.rst:641 +#: ../../glossary.rst:690 msgid "interpreter shutdown" msgstr "desligamento do interpretador" -#: ../../glossary.rst:643 +#: ../../glossary.rst:692 msgid "" "When asked to shut down, the Python interpreter enters a special phase where " "it gradually releases all allocated resources, such as modules and various " @@ -1549,7 +1747,7 @@ msgstr "" "depende podem não funcionar mais (exemplos comuns são os módulos de " "bibliotecas, ou os mecanismos de avisos)." -#: ../../glossary.rst:652 +#: ../../glossary.rst:701 msgid "" "The main reason for interpreter shutdown is that the ``__main__`` module or " "the script being run has finished executing." @@ -1557,28 +1755,28 @@ msgstr "" "A principal razão para o interpretador desligar, é que o módulo ``__main__`` " "ou o script sendo executado terminou sua execução." -#: ../../glossary.rst:654 +#: ../../glossary.rst:703 msgid "iterable" msgstr "iterável" -#: ../../glossary.rst:656 +#: ../../glossary.rst:705 msgid "" "An object capable of returning its members one at a time. Examples of " "iterables include all sequence types (such as :class:`list`, :class:`str`, " "and :class:`tuple`) and some non-sequence types like :class:`dict`, :term:" "`file objects `, and objects of any classes you define with an :" -"meth:`~iterator.__iter__` method or with a :meth:`~object.__getitem__` " -"method that implements :term:`sequence` semantics." +"meth:`~object.__iter__` method or with a :meth:`~object.__getitem__` method " +"that implements :term:`sequence` semantics." msgstr "" "Um objeto capaz de retornar seus membros um de cada vez. Exemplos de " "iteráveis incluem todos os tipos de sequência (tais como :class:`list`, :" "class:`str` e :class:`tuple`) e alguns tipos de não-sequência, como o :class:" -"`dict`, :term:`objetos arquivos `, além dos objetos de " -"quaisquer classes que você definir com um método :meth:`~iterator.__iter__` " +"`dict` e :term:`objetos arquivos `, além dos objetos de " +"quaisquer classes que você definir com um método :meth:`~object.__iter__` " "ou :meth:`~object.__getitem__` que implementam a semântica de :term:" "`sequência` ." -#: ../../glossary.rst:664 +#: ../../glossary.rst:713 msgid "" "Iterables can be used in a :keyword:`for` loop and in many other places " "where a sequence is needed (:func:`zip`, :func:`map`, ...). When an " @@ -1600,11 +1798,11 @@ msgstr "" "uma variável temporária para armazenar o iterador durante a execução do " "laço. Veja também :term:`iterador`, :term:`sequência`, e :term:`gerador`." -#: ../../glossary.rst:674 +#: ../../glossary.rst:723 msgid "iterator" msgstr "iterador" -#: ../../glossary.rst:676 +#: ../../glossary.rst:725 msgid "" "An object representing a stream of data. Repeated calls to the iterator's :" "meth:`~iterator.__next__` method (or passing it to the built-in function :" @@ -1637,11 +1835,11 @@ msgstr "" "iterador apenas iria retornar o mesmo objeto iterador esgotado já utilizado " "na iteração anterior, como se fosse um contêiner vazio." -#: ../../glossary.rst:691 +#: ../../glossary.rst:740 msgid "More information can be found in :ref:`typeiter`." msgstr "Mais informações podem ser encontradas em :ref:`typeiter`." -#: ../../glossary.rst:695 +#: ../../glossary.rst:744 msgid "" "CPython does not consistently apply the requirement that an iterator define :" "meth:`~iterator.__iter__`. And also please note that the free-threading " @@ -1651,11 +1849,11 @@ msgstr "" "meth:`~iterator.__iter__`. E também observe que o CPython com threads livres " "não garante a segurança do thread das operações do iterador." -#: ../../glossary.rst:700 +#: ../../glossary.rst:749 msgid "key function" msgstr "função chave" -#: ../../glossary.rst:702 +#: ../../glossary.rst:751 msgid "" "A key function or collation function is a callable that returns a value used " "for sorting or ordering. For example, :func:`locale.strxfrm` is used to " @@ -1666,7 +1864,7 @@ msgstr "" "para produzir uma chave de ordenação que leva o locale em consideração para " "fins de ordenação." -#: ../../glossary.rst:707 +#: ../../glossary.rst:756 msgid "" "A number of tools in Python accept key functions to control how elements are " "ordered or grouped. They include :func:`min`, :func:`max`, :func:`sorted`, :" @@ -1678,7 +1876,7 @@ msgstr "" "`min`, :func:`max`, :func:`sorted`, :meth:`list.sort`, :func:`heapq.merge`, :" "func:`heapq.nsmallest`, :func:`heapq.nlargest` e :func:`itertools.groupby`." -#: ../../glossary.rst:713 +#: ../../glossary.rst:762 msgid "" "There are several ways to create a key function. For example. the :meth:" "`str.lower` method can serve as a key function for case insensitive sorts. " @@ -1693,23 +1891,23 @@ msgstr "" "caixa. Alternativamente, uma função chave ad-hoc pode ser construída a " "partir de uma expressão :keyword:`lambda`, como ``lambda r: (r[0], r[2])``. " "Além disso, :func:`operator.attrgetter`, :func:`operator.itemgetter` e :func:" -"`operator.methodcaller` são três construtores de função chave. Consulte o :" -"ref:`HowTo de Ordenação ` para ver exemplos de como criar e " +"`operator.methodcaller` são três construtores de função chave. Consulte o " +"guia de :ref:`Ordenação ` para ver exemplos de como criar e " "utilizar funções chave." -#: ../../glossary.rst:720 +#: ../../glossary.rst:769 msgid "keyword argument" msgstr "argumento nomeado" -#: ../../glossary.rst:722 ../../glossary.rst:1021 +#: ../../glossary.rst:771 ../../glossary.rst:1086 msgid "See :term:`argument`." msgstr "Veja :term:`argumento`." -#: ../../glossary.rst:723 +#: ../../glossary.rst:772 msgid "lambda" msgstr "lambda" -#: ../../glossary.rst:725 +#: ../../glossary.rst:774 msgid "" "An anonymous inline function consisting of a single :term:`expression` which " "is evaluated when the function is called. The syntax to create a lambda " @@ -1719,11 +1917,11 @@ msgstr "" "é avaliada quando a função é chamada. A sintaxe para criar uma função lambda " "é ``lambda [parameters]: expression``" -#: ../../glossary.rst:728 +#: ../../glossary.rst:777 msgid "LBYL" msgstr "LBYL" -#: ../../glossary.rst:730 +#: ../../glossary.rst:779 msgid "" "Look before you leap. This coding style explicitly tests for pre-conditions " "before making calls or lookups. This style contrasts with the :term:`EAFP` " @@ -1736,7 +1934,7 @@ msgstr "" "contrasta com a abordagem :term:`EAFP` e é caracterizada pela presença de " "muitas instruções :keyword:`if`." -#: ../../glossary.rst:735 +#: ../../glossary.rst:784 msgid "" "In a multi-threaded environment, the LBYL approach can risk introducing a " "race condition between \"the looking\" and \"the leaping\". For example, " @@ -1750,11 +1948,19 @@ msgstr "" "thread remover *key* do *mapping* após o teste, mas antes da olhada. Esse " "problema pode ser resolvido com travas ou usando a abordagem EAFP." -#: ../../glossary.rst:740 +#: ../../glossary.rst:789 +msgid "lexical analyzer" +msgstr "analisador léxico" + +#: ../../glossary.rst:792 +msgid "Formal name for the *tokenizer*; see :term:`token`." +msgstr "Nome formal para o *tokenizador*; veja :term:`token`." + +#: ../../glossary.rst:793 msgid "list" msgstr "lista" -#: ../../glossary.rst:742 +#: ../../glossary.rst:795 msgid "" "A built-in Python :term:`sequence`. Despite its name it is more akin to an " "array in other languages than to a linked list since access to elements is " @@ -1764,11 +1970,11 @@ msgstr "" "de um vetor em outras linguagens do que uma lista encadeada, como o acesso " "aos elementos é da ordem *O*\\ (1)." -#: ../../glossary.rst:745 +#: ../../glossary.rst:798 msgid "list comprehension" msgstr "compreensão de lista" -#: ../../glossary.rst:747 +#: ../../glossary.rst:800 msgid "" "A compact way to process all or part of the elements in a sequence and " "return a list with the results. ``result = ['{:#04x}'.format(x) for x in " @@ -1783,27 +1989,39 @@ msgstr "" "keyword:`if` é opcional. Se omitida, todos os elementos no ``range(256)`` " "serão processados." -#: ../../glossary.rst:753 +#: ../../glossary.rst:806 msgid "loader" msgstr "carregador" -#: ../../glossary.rst:755 +#: ../../glossary.rst:808 msgid "" -"An object that loads a module. It must define a method named :meth:" -"`load_module`. A loader is typically returned by a :term:`finder`. See :pep:" -"`302` for details and :class:`importlib.abc.Loader` for an :term:`abstract " -"base class`." +"An object that loads a module. It must define the :meth:`!exec_module` and :" +"meth:`!create_module` methods to implement the :class:`~importlib.abc." +"Loader` interface. A loader is typically returned by a :term:`finder`. See " +"also:" msgstr "" -"Um objeto que carrega um módulo. Deve definir um método chamado :meth:" -"`load_module`. Um carregador é normalmente devolvido por um :term:" -"`localizador`. Veja a :pep:`302` para detalhes e :class:`importlib.abc." -"Loader` para um :term:`classe base abstrata`." +"Um objeto que carrega um módulo. Ele deve definir os métodos :meth:`!" +"exec_module` e :meth:`!create_module` para implementar a interface :class:" +"`~importlib.abc.Loader`. Um carregador é normalmente retornado por um :term:" +"`localizador`. Veja também:" + +#: ../../glossary.rst:814 +msgid ":ref:`finders-and-loaders`" +msgstr ":ref:`finders-and-loaders`" + +#: ../../glossary.rst:815 +msgid ":class:`importlib.abc.Loader`" +msgstr ":class:`importlib.abc.Loader`" + +#: ../../glossary.rst:816 +msgid ":pep:`302`" +msgstr ":pep:`302`" -#: ../../glossary.rst:759 +#: ../../glossary.rst:817 msgid "locale encoding" msgstr "codificação da localidade" -#: ../../glossary.rst:761 +#: ../../glossary.rst:819 msgid "" "On Unix, it is the encoding of the LC_CTYPE locale. It can be set with :func:" "`locale.setlocale(locale.LC_CTYPE, new_locale) `." @@ -1811,41 +2029,41 @@ msgstr "" "No Unix, é a codificação da localidade do LC_CTYPE, que pode ser definida " "com :func:`locale.setlocale(locale.LC_CTYPE, new_locale) `." -#: ../../glossary.rst:764 +#: ../../glossary.rst:822 msgid "On Windows, it is the ANSI code page (ex: ``\"cp1252\"``)." msgstr "No Windows, é a página de código ANSI (ex: ``\"cp1252\"``)." -#: ../../glossary.rst:766 +#: ../../glossary.rst:824 msgid "" "On Android and VxWorks, Python uses ``\"utf-8\"`` as the locale encoding." msgstr "" "No Android e no VxWorks, o Python usa ``\"utf-8\"`` como a codificação da " "localidade." -#: ../../glossary.rst:768 +#: ../../glossary.rst:826 msgid ":func:`locale.getencoding` can be used to get the locale encoding." msgstr "" ":func:`locale.getencoding` pode ser usado para obter a codificação da " "localidade." -#: ../../glossary.rst:770 +#: ../../glossary.rst:828 msgid "See also the :term:`filesystem encoding and error handler`." msgstr "" "Veja também :term:`tratador de erros e codificação do sistema de arquivos`." -#: ../../glossary.rst:771 +#: ../../glossary.rst:829 msgid "magic method" msgstr "método mágico" -#: ../../glossary.rst:775 +#: ../../glossary.rst:833 msgid "An informal synonym for :term:`special method`." msgstr "Um sinônimo informal para um :term:`método especial`." -#: ../../glossary.rst:776 +#: ../../glossary.rst:834 msgid "mapping" msgstr "mapeamento" -#: ../../glossary.rst:778 +#: ../../glossary.rst:836 msgid "" "A container object that supports arbitrary key lookups and implements the " "methods specified in the :class:`collections.abc.Mapping` or :class:" @@ -1861,11 +2079,11 @@ msgstr "" "`collections.defaultdict`, :class:`collections.OrderedDict` e :class:" "`collections.Counter`." -#: ../../glossary.rst:784 +#: ../../glossary.rst:842 msgid "meta path finder" msgstr "localizador de metacaminho" -#: ../../glossary.rst:786 +#: ../../glossary.rst:844 msgid "" "A :term:`finder` returned by a search of :data:`sys.meta_path`. Meta path " "finders are related to, but different from :term:`path entry finders `." -#: ../../glossary.rst:790 +#: ../../glossary.rst:848 msgid "" "See :class:`importlib.abc.MetaPathFinder` for the methods that meta path " "finders implement." @@ -1883,11 +2101,11 @@ msgstr "" "Veja :class:`importlib.abc.MetaPathFinder` para os métodos que localizadores " "de metacaminho implementam." -#: ../../glossary.rst:792 +#: ../../glossary.rst:850 msgid "metaclass" msgstr "metaclasse" -#: ../../glossary.rst:794 +#: ../../glossary.rst:852 msgid "" "The class of a class. Class definitions create a class name, a class " "dictionary, and a list of base classes. The metaclass is responsible for " @@ -1910,15 +2128,15 @@ msgstr "" "atributos, para incluir proteção contra acesso concorrente, rastrear a " "criação de objetos, implementar singletons, dentre muitas outras tarefas." -#: ../../glossary.rst:804 +#: ../../glossary.rst:862 msgid "More information can be found in :ref:`metaclasses`." msgstr "Mais informações podem ser encontradas em :ref:`metaclasses`." -#: ../../glossary.rst:773 ../../glossary.rst:805 ../../glossary.rst:1170 +#: ../../glossary.rst:831 ../../glossary.rst:863 ../../glossary.rst:1231 msgid "method" msgstr "método" -#: ../../glossary.rst:807 +#: ../../glossary.rst:865 msgid "" "A function which is defined inside a class body. If called as an attribute " "of an instance of that class, the method will get the instance object as its " @@ -1930,11 +2148,11 @@ msgstr "" "objeto como seu primeiro :term:`argumento` (que comumente é chamado de " "``self``). Veja :term:`função` e :term:`escopo aninhado`." -#: ../../glossary.rst:811 +#: ../../glossary.rst:869 msgid "method resolution order" msgstr "ordem de resolução de métodos" -#: ../../glossary.rst:813 +#: ../../glossary.rst:871 msgid "" "Method Resolution Order is the order in which base classes are searched for " "a member during lookup. See :ref:`python_2.3_mro` for details of the " @@ -1944,11 +2162,11 @@ msgstr "" "são buscados durante a pesquisa. Veja :ref:`python_2.3_mro` para detalhes do " "algoritmo usado pelo interpretador do Python desde a versão 2.3." -#: ../../glossary.rst:816 +#: ../../glossary.rst:874 msgid "module" msgstr "módulo" -#: ../../glossary.rst:818 +#: ../../glossary.rst:876 msgid "" "An object that serves as an organizational unit of Python code. Modules " "have a namespace containing arbitrary Python objects. Modules are loaded " @@ -1959,15 +2177,15 @@ msgstr "" "módulos são carregados pelo Python através do processo de :term:" "`importação`." -#: ../../glossary.rst:822 +#: ../../glossary.rst:880 msgid "See also :term:`package`." msgstr "Veja também :term:`pacote`." -#: ../../glossary.rst:823 +#: ../../glossary.rst:881 msgid "module spec" -msgstr "especificação do módulo" +msgstr "spec de módulo" -#: ../../glossary.rst:825 +#: ../../glossary.rst:883 msgid "" "A namespace containing the import-related information used to load a module. " "An instance of :class:`importlib.machinery.ModuleSpec`." @@ -1976,19 +2194,23 @@ msgstr "" "usadas para carregar um módulo. Uma instância de :class:`importlib.machinery." "ModuleSpec`." -#: ../../glossary.rst:827 +#: ../../glossary.rst:886 +msgid "See also :ref:`module-specs`." +msgstr "Veja também :ref:`module-specs`." + +#: ../../glossary.rst:887 msgid "MRO" msgstr "MRO" -#: ../../glossary.rst:829 +#: ../../glossary.rst:889 msgid "See :term:`method resolution order`." msgstr "Veja :term:`ordem de resolução de métodos`." -#: ../../glossary.rst:830 +#: ../../glossary.rst:890 msgid "mutable" msgstr "mutável" -#: ../../glossary.rst:832 +#: ../../glossary.rst:892 msgid "" "Mutable objects can change their value but keep their :func:`id`. See also :" "term:`immutable`." @@ -1996,11 +2218,11 @@ msgstr "" "Objeto mutável é aquele que pode modificar seus valor mas manter seu :func:" "`id`. Veja também :term:`imutável`." -#: ../../glossary.rst:834 +#: ../../glossary.rst:894 msgid "named tuple" msgstr "tupla nomeada" -#: ../../glossary.rst:836 +#: ../../glossary.rst:896 msgid "" "The term \"named tuple\" applies to any type or class that inherits from " "tuple and whose indexable elements are also accessible using named " @@ -2010,7 +2232,7 @@ msgstr "" "tupla e cujos elementos indexáveis também são acessíveis usando atributos " "nomeados. O tipo ou classe pode ter outras funcionalidades também." -#: ../../glossary.rst:840 +#: ../../glossary.rst:900 msgid "" "Several built-in types are named tuples, including the values returned by :" "func:`time.localtime` and :func:`os.stat`. Another example is :data:`sys." @@ -2020,7 +2242,23 @@ msgstr "" "retornados por :func:`time.localtime` e :func:`os.stat`. Outro exemplo é :" "data:`sys.float_info`::" -#: ../../glossary.rst:851 +#: ../../glossary.rst:904 +msgid "" +">>> sys.float_info[1] # indexed access\n" +"1024\n" +">>> sys.float_info.max_exp # named field access\n" +"1024\n" +">>> isinstance(sys.float_info, tuple) # kind of tuple\n" +"True" +msgstr "" +">>> sys.float_info[1] # acesso indexado\n" +"1024\n" +">>> sys.float_info.max_exp # acesso a campo nomeado\n" +"1024\n" +">>> isinstance(sys.float_info, tuple) # tipo de tupla\n" +"True" + +#: ../../glossary.rst:911 msgid "" "Some named tuples are built-in types (such as the above examples). " "Alternatively, a named tuple can be created from a regular class definition " @@ -2039,11 +2277,11 @@ msgstr "" "métodos extras, que podem não ser encontrados quando foi escrita " "manualmente, ou em tuplas nomeadas embutidas." -#: ../../glossary.rst:859 +#: ../../glossary.rst:919 msgid "namespace" msgstr "espaço de nomes" -#: ../../glossary.rst:861 +#: ../../glossary.rst:921 msgid "" "The place where a variable is stored. Namespaces are implemented as " "dictionaries. There are the local, global and built-in namespaces as well " @@ -2066,31 +2304,46 @@ msgstr "" "claro que estas funções são implementadas pelos módulos :mod:`random` e :mod:" "`itertools` respectivamente." -#: ../../glossary.rst:871 +#: ../../glossary.rst:931 msgid "namespace package" msgstr "pacote de espaço de nomes" -#: ../../glossary.rst:873 +#: ../../glossary.rst:933 msgid "" -"A :pep:`420` :term:`package` which serves only as a container for " -"subpackages. Namespace packages may have no physical representation, and " -"specifically are not like a :term:`regular package` because they have no " -"``__init__.py`` file." +"A :term:`package` which serves only as a container for subpackages. " +"Namespace packages may have no physical representation, and specifically are " +"not like a :term:`regular package` because they have no ``__init__.py`` file." msgstr "" -"Um :term:`pacote` da :pep:`420` que serve apenas como container para sub " -"pacotes. Pacotes de espaços de nomes podem não ter representação física, e " -"especificamente não são como um :term:`pacote regular` porque eles não tem " -"um arquivo ``__init__.py``." +"Um :term:`pacote` que serve apenas como contêiner para subpacotes. Pacotes " +"de espaços de nomes podem não ter representação física, e especificamente " +"não são como um :term:`pacote regular` porque eles não tem um arquivo " +"``__init__.py``." -#: ../../glossary.rst:878 +#: ../../glossary.rst:938 +msgid "" +"Namespace packages allow several individually installable packages to have a " +"common parent package. Otherwise, it is recommended to use a :term:`regular " +"package`." +msgstr "" +"Pacotes de espaço de nomes permitem que vários pacotes instaláveis ​​" +"individualmente tenham um pacote pai comum. Caso contrário, é recomendado " +"usar um :term:`pacote regular`." + +#: ../../glossary.rst:941 +msgid "" +"For more information, see :pep:`420` and :ref:`reference-namespace-package`." +msgstr "" +"Para mais informações, veja :pep:`420` e :ref:`reference-namespace-package`." + +#: ../../glossary.rst:943 msgid "See also :term:`module`." msgstr "Veja também :term:`módulo`." -#: ../../glossary.rst:879 +#: ../../glossary.rst:944 msgid "nested scope" msgstr "escopo aninhado" -#: ../../glossary.rst:881 +#: ../../glossary.rst:946 msgid "" "The ability to refer to a variable in an enclosing definition. For " "instance, a function defined inside another function can refer to variables " @@ -2107,11 +2360,11 @@ msgstr "" "escrever para o espaço de nomes global. O :keyword:`nonlocal` permite " "escrita para escopos externos." -#: ../../glossary.rst:888 +#: ../../glossary.rst:953 msgid "new-style class" msgstr "classe estilo novo" -#: ../../glossary.rst:890 +#: ../../glossary.rst:955 msgid "" "Old name for the flavor of classes now used for all class objects. In " "earlier Python versions, only new-style classes could use Python's newer, " @@ -2124,11 +2377,11 @@ msgstr "" "descritores, propriedades, :meth:`~object.__getattribute__`, métodos de " "classe, e métodos estáticos." -#: ../../glossary.rst:895 +#: ../../glossary.rst:960 msgid "object" msgstr "objeto" -#: ../../glossary.rst:897 +#: ../../glossary.rst:962 msgid "" "Any data with state (attributes or value) and defined behavior (methods). " "Also the ultimate base class of any :term:`new-style class`." @@ -2137,11 +2390,11 @@ msgstr "" "definidos (métodos). Também a última classe base de qualquer :term:`classe " "estilo novo`." -#: ../../glossary.rst:900 +#: ../../glossary.rst:965 msgid "optimized scope" msgstr "escopo otimizado" -#: ../../glossary.rst:902 +#: ../../glossary.rst:967 msgid "" "A scope where target local variable names are reliably known to the compiler " "when the code is compiled, allowing optimization of read and write access to " @@ -2160,11 +2413,11 @@ msgstr "" "de um conjunto conhecido de nomes de variáveis locais e não locais são " "restritas a escopos otimizados." -#: ../../glossary.rst:909 +#: ../../glossary.rst:974 msgid "package" msgstr "pacote" -#: ../../glossary.rst:911 +#: ../../glossary.rst:976 msgid "" "A Python :term:`module` which can contain submodules or recursively, " "subpackages. Technically, a package is a Python module with a ``__path__`` " @@ -2174,16 +2427,16 @@ msgstr "" "subpacotes. Tecnicamente, um pacote é um módulo Python com um atributo " "``__path__``." -#: ../../glossary.rst:915 +#: ../../glossary.rst:980 msgid "See also :term:`regular package` and :term:`namespace package`." msgstr "" "Veja também :term:`pacote regular` e :term:`pacote de espaço de nomes`." -#: ../../glossary.rst:916 +#: ../../glossary.rst:981 msgid "parameter" msgstr "parâmetro" -#: ../../glossary.rst:918 +#: ../../glossary.rst:983 msgid "" "A named entity in a :term:`function` (or method) definition that specifies " "an :term:`argument` (or in some cases, arguments) that the function can " @@ -2193,7 +2446,7 @@ msgstr "" "método) que específica um :term:`argumento` (ou em alguns casos, " "argumentos) que a função pode receber. Existem cinco tipos de parâmetros:" -#: ../../glossary.rst:922 +#: ../../glossary.rst:987 msgid "" ":dfn:`positional-or-keyword`: specifies an argument that can be passed " "either :term:`positionally ` or as a :term:`keyword argument " @@ -2204,7 +2457,11 @@ msgstr "" "term:`posicional ` quanto :term:`nomeado `. Esse é o " "tipo padrão de parâmetro, por exemplo *foo* e *bar* a seguir::" -#: ../../glossary.rst:931 +#: ../../glossary.rst:992 +msgid "def func(foo, bar=None): ..." +msgstr "def func(foo, bar=None): ..." + +#: ../../glossary.rst:996 msgid "" ":dfn:`positional-only`: specifies an argument that can be supplied only by " "position. Positional-only parameters can be defined by including a ``/`` " @@ -2214,9 +2471,13 @@ msgstr "" ":dfn:`somente-posicional`: especifica um argumento que pode ser fornecido " "apenas por posição. Parâmetros somente-posicionais podem ser definidos " "incluindo o caractere ``/`` na lista de parâmetros da definição da função " -"após eles, por exemplo *posonly1* e *posonly2* a seguir::" +"após eles, por exemplo *somentepos1* e *somentepos2* a seguir::" + +#: ../../glossary.rst:1001 +msgid "def func(posonly1, posonly2, /, positional_or_keyword): ..." +msgstr "def func(somentepos1, somentepos2, /, posicional_ou_nomeado): ..." -#: ../../glossary.rst:940 +#: ../../glossary.rst:1005 msgid "" ":dfn:`keyword-only`: specifies an argument that can be supplied only by " "keyword. Keyword-only parameters can be defined by including a single var-" @@ -2227,10 +2488,14 @@ msgstr "" ":dfn:`somente-nomeado`: especifica um argumento que pode ser passado para a " "função somente por nome. Parâmetros somente-nomeados podem ser definidos com " "um simples parâmetro var-posicional ou um ``*`` antes deles na lista de " -"parâmetros na definição da função, por exemplo *kw_only1* and *kw_only2* a " -"seguir::" +"parâmetros na definição da função, por exemplo *somente_nom1* and " +"*somente_nom2* a seguir::" -#: ../../glossary.rst:948 +#: ../../glossary.rst:1011 +msgid "def func(arg, *, kw_only1, kw_only2): ..." +msgstr "def func(arg, *, somente_nom1, somente_nom2): ..." + +#: ../../glossary.rst:1013 msgid "" ":dfn:`var-positional`: specifies that an arbitrary sequence of positional " "arguments can be provided (in addition to any positional arguments already " @@ -2243,7 +2508,11 @@ msgstr "" "aceito por outros parâmetros). Tal parâmetro pode ser definido colocando um " "``*`` antes do nome do parâmetro, por exemplo *args* a seguir::" -#: ../../glossary.rst:956 +#: ../../glossary.rst:1019 +msgid "def func(*args, **kwargs): ..." +msgstr "def func(*args, **kwargs): ..." + +#: ../../glossary.rst:1021 msgid "" ":dfn:`var-keyword`: specifies that arbitrarily many keyword arguments can be " "provided (in addition to any keyword arguments already accepted by other " @@ -2255,7 +2524,7 @@ msgstr "" "aceito por outros parâmetros). Tal parâmetro pode definido colocando-se " "``**`` antes do nome, por exemplo *kwargs* no exemplo acima." -#: ../../glossary.rst:962 +#: ../../glossary.rst:1027 msgid "" "Parameters can specify both optional and required arguments, as well as " "default values for some optional arguments." @@ -2263,22 +2532,22 @@ msgstr "" "Parâmetros podem especificar tanto argumentos opcionais quanto obrigatórios, " "assim como valores padrão para alguns argumentos opcionais." -#: ../../glossary.rst:965 +#: ../../glossary.rst:1030 msgid "" "See also the :term:`argument` glossary entry, the FAQ question on :ref:`the " "difference between arguments and parameters `, " "the :class:`inspect.Parameter` class, the :ref:`function` section, and :pep:" "`362`." msgstr "" -"Veja o termo :term:`argumento` no glossário, a pergunta sobre :ref:`a " -"diferença entre argumentos e parâmetros `, a " -"classe :class:`inspect.Parameter`, a seção :ref:`function` e a :pep:`362`." +"Veja também o termo :term:`argumento` no glossário, a pergunta do FAQ sobre :" +"ref:`a diferença entre argumentos e parâmetros `, " +"a classe :class:`inspect.Parameter`, a seção :ref:`function` e a :pep:`362`." -#: ../../glossary.rst:969 +#: ../../glossary.rst:1034 msgid "path entry" msgstr "entrada de caminho" -#: ../../glossary.rst:971 +#: ../../glossary.rst:1036 msgid "" "A single location on the :term:`import path` which the :term:`path based " "finder` consults to find modules for importing." @@ -2286,11 +2555,11 @@ msgstr "" "Um local único no :term:`caminho de importação` que o :term:`localizador " "baseado no caminho` consulta para encontrar módulos a serem importados." -#: ../../glossary.rst:973 +#: ../../glossary.rst:1038 msgid "path entry finder" msgstr "localizador de entrada de caminho" -#: ../../glossary.rst:975 +#: ../../glossary.rst:1040 msgid "" "A :term:`finder` returned by a callable on :data:`sys.path_hooks` (i.e. a :" "term:`path entry hook`) which knows how to locate modules given a :term:" @@ -2300,7 +2569,7 @@ msgstr "" "(ou seja, um :term:`gancho de entrada de caminho`) que sabe como localizar " "os módulos :term:`entrada de caminho`." -#: ../../glossary.rst:979 +#: ../../glossary.rst:1044 msgid "" "See :class:`importlib.abc.PathEntryFinder` for the methods that path entry " "finders implement." @@ -2308,11 +2577,11 @@ msgstr "" "Veja :class:`importlib.abc.PathEntryFinder` para os métodos que " "localizadores de entrada de caminho implementam." -#: ../../glossary.rst:981 +#: ../../glossary.rst:1046 msgid "path entry hook" msgstr "gancho de entrada de caminho" -#: ../../glossary.rst:983 +#: ../../glossary.rst:1048 msgid "" "A callable on the :data:`sys.path_hooks` list which returns a :term:`path " "entry finder` if it knows how to find modules on a specific :term:`path " @@ -2322,11 +2591,11 @@ msgstr "" "`localizador de entrada de caminho` caso saiba como localizar módulos em " "uma :term:`entrada de caminho` específica." -#: ../../glossary.rst:986 +#: ../../glossary.rst:1051 msgid "path based finder" msgstr "localizador baseado no caminho" -#: ../../glossary.rst:988 +#: ../../glossary.rst:1053 msgid "" "One of the default :term:`meta path finders ` which " "searches an :term:`import path` for modules." @@ -2334,11 +2603,11 @@ msgstr "" "Um dos :term:`localizadores de metacaminho ` padrão que " "procura por um :term:`caminho de importação` de módulos." -#: ../../glossary.rst:990 +#: ../../glossary.rst:1055 msgid "path-like object" msgstr "objeto caminho ou similar" -#: ../../glossary.rst:992 +#: ../../glossary.rst:1057 msgid "" "An object representing a file system path. A path-like object is either a :" "class:`str` or :class:`bytes` object representing a path, or an object " @@ -2358,11 +2627,11 @@ msgstr "" "fsencode` podem ser usadas para garantir um :class:`str` ou :class:`bytes` " "como resultado, respectivamente. Introduzido na :pep:`519`." -#: ../../glossary.rst:1000 +#: ../../glossary.rst:1065 msgid "PEP" msgstr "PEP" -#: ../../glossary.rst:1002 +#: ../../glossary.rst:1067 msgid "" "Python Enhancement Proposal. A PEP is a design document providing " "information to the Python community, or describing a new feature for Python " @@ -2374,7 +2643,7 @@ msgstr "" "para o Python ou seus predecessores ou ambientes. PEPs devem prover uma " "especificação técnica concisa e um racional para funcionalidades propostas." -#: ../../glossary.rst:1008 +#: ../../glossary.rst:1073 msgid "" "PEPs are intended to be the primary mechanisms for proposing major new " "features, for collecting community input on an issue, and for documenting " @@ -2388,15 +2657,15 @@ msgstr "" "Python. O autor da PEP é responsável por construir um consenso dentro da " "comunidade e documentar opiniões dissidentes." -#: ../../glossary.rst:1014 +#: ../../glossary.rst:1079 msgid "See :pep:`1`." msgstr "Veja :pep:`1`." -#: ../../glossary.rst:1015 +#: ../../glossary.rst:1080 msgid "portion" msgstr "porção" -#: ../../glossary.rst:1017 +#: ../../glossary.rst:1082 msgid "" "A set of files in a single directory (possibly stored in a zip file) that " "contribute to a namespace package, as defined in :pep:`420`." @@ -2405,15 +2674,15 @@ msgstr "" "um arquivo zip) que contribuem para um pacote de espaço de nomes, conforme " "definido em :pep:`420`." -#: ../../glossary.rst:1019 +#: ../../glossary.rst:1084 msgid "positional argument" msgstr "argumento posicional" -#: ../../glossary.rst:1022 +#: ../../glossary.rst:1087 msgid "provisional API" msgstr "API provisória" -#: ../../glossary.rst:1024 +#: ../../glossary.rst:1089 msgid "" "A provisional API is one which has been deliberately excluded from the " "standard library's backwards compatibility guarantees. While major changes " @@ -2432,7 +2701,7 @@ msgstr "" "gratuitamente -- elas irão ocorrer apenas se sérias falhas fundamentais " "forem descobertas, que foram esquecidas anteriormente a inclusão da API." -#: ../../glossary.rst:1033 +#: ../../glossary.rst:1098 msgid "" "Even for provisional APIs, backwards incompatible changes are seen as a " "\"solution of last resort\" - every attempt will still be made to find a " @@ -2443,7 +2712,7 @@ msgstr "" "encontrar uma resolução retroativa compatível para quaisquer problemas " "encontrados." -#: ../../glossary.rst:1037 +#: ../../glossary.rst:1102 msgid "" "This process allows the standard library to continue to evolve over time, " "without locking in problematic design errors for extended periods of time. " @@ -2453,19 +2722,19 @@ msgstr "" "passar do tempo, sem se prender em erros de design problemáticos por " "períodos de tempo prolongados. Veja :pep:`411` para mais detalhes." -#: ../../glossary.rst:1040 +#: ../../glossary.rst:1105 msgid "provisional package" msgstr "pacote provisório" -#: ../../glossary.rst:1042 +#: ../../glossary.rst:1107 msgid "See :term:`provisional API`." msgstr "Veja :term:`API provisória`." -#: ../../glossary.rst:1043 +#: ../../glossary.rst:1108 msgid "Python 3000" msgstr "Python 3000" -#: ../../glossary.rst:1045 +#: ../../glossary.rst:1110 msgid "" "Nickname for the Python 3.x release line (coined long ago when the release " "of version 3 was something in the distant future.) This is also abbreviated " @@ -2475,11 +2744,11 @@ msgstr "" "tempo, quando o lançamento da versão 3 era algo em um futuro muito " "distante.) Esse termo possui a seguinte abreviação: \"Py3k\"." -#: ../../glossary.rst:1048 +#: ../../glossary.rst:1113 msgid "Pythonic" msgstr "Pythônico" -#: ../../glossary.rst:1050 +#: ../../glossary.rst:1115 msgid "" "An idea or piece of code which closely follows the most common idioms of the " "Python language, rather than implementing code using concepts common to " @@ -2488,22 +2757,39 @@ msgid "" "languages don't have this type of construct, so people unfamiliar with " "Python sometimes use a numerical counter instead::" msgstr "" -"Uma ideia ou um pedaço de código que segue de perto os idiomas mais comuns " -"da linguagem Python, ao invés de implementar códigos usando conceitos comuns " -"a outros idiomas. Por exemplo, um idioma comum em Python é fazer um loop " -"sobre todos os elementos de uma iterável usando a instrução :keyword:`for`. " -"Muitas outras linguagens não têm esse tipo de construção, então as pessoas " -"que não estão familiarizadas com o Python usam um contador numérico::" +"Uma ideia ou um pedaço de código que segue de perto as formas de escritas " +"mais comuns da linguagem Python, ao invés de implementar códigos usando " +"conceitos comuns a outras linguagens. Por exemplo, um formato comum em " +"Python é fazer um laço sobre todos os elementos de uma iterável usando a " +"instrução :keyword:`for`. Muitas outras linguagens não têm esse tipo de " +"construção, então as pessoas que não estão familiarizadas com o Python usam " +"um contador numérico::" -#: ../../glossary.rst:1060 +#: ../../glossary.rst:1122 +msgid "" +"for i in range(len(food)):\n" +" print(food[i])" +msgstr "" +"for i in range(len(comida)):\n" +" print(comida[i])" + +#: ../../glossary.rst:1125 msgid "As opposed to the cleaner, Pythonic method::" -msgstr "Ao contrário do método limpo, ou então, Pythônico::" +msgstr "Ao contrário do método mais limpo, Pythônico::" + +#: ../../glossary.rst:1127 +msgid "" +"for piece in food:\n" +" print(piece)" +msgstr "" +"for parte in comida:\n" +" print(parte)" -#: ../../glossary.rst:1064 +#: ../../glossary.rst:1129 msgid "qualified name" msgstr "nome qualificado" -#: ../../glossary.rst:1066 +#: ../../glossary.rst:1131 msgid "" "A dotted name showing the \"path\" from a module's global scope to a class, " "function or method defined in that module, as defined in :pep:`3155`. For " @@ -2516,7 +2802,33 @@ msgstr "" "funções e classes de nível superior, o nome qualificado é o mesmo que o nome " "do objeto::" -#: ../../glossary.rst:1083 +#: ../../glossary.rst:1136 +msgid "" +">>> class C:\n" +"... class D:\n" +"... def meth(self):\n" +"... pass\n" +"...\n" +">>> C.__qualname__\n" +"'C'\n" +">>> C.D.__qualname__\n" +"'C.D'\n" +">>> C.D.meth.__qualname__\n" +"'C.D.meth'" +msgstr "" +">>> class C:\n" +"... class D:\n" +"... def metodo(self):\n" +"... pass\n" +"...\n" +">>> C.__qualname__\n" +"'C'\n" +">>> C.D.__qualname__\n" +"'C.D'\n" +">>> C.D.metodo.__qualname__\n" +"'C.D.metodo'" + +#: ../../glossary.rst:1148 msgid "" "When used to refer to modules, the *fully qualified name* means the entire " "dotted path to the module, including any parent packages, e.g. ``email.mime." @@ -2526,11 +2838,21 @@ msgstr "" "significa todo o caminho pontilhado para o módulo, incluindo quaisquer " "pacotes pai, por exemplo: ``email.mime.text``::" -#: ../../glossary.rst:1090 +#: ../../glossary.rst:1152 +msgid "" +">>> import email.mime.text\n" +">>> email.mime.text.__name__\n" +"'email.mime.text'" +msgstr "" +">>> import email.mime.text\n" +">>> email.mime.text.__name__\n" +"'email.mime.text'" + +#: ../../glossary.rst:1155 msgid "reference count" msgstr "contagem de referências" -#: ../../glossary.rst:1092 +#: ../../glossary.rst:1157 msgid "" "The number of references to an object. When the reference count of an " "object drops to zero, it is deallocated. Some objects are :term:`immortal` " @@ -2549,11 +2871,11 @@ msgstr "" "função :func:`sys.getrefcount` para retornar a contagem de referências para " "um objeto específico." -#: ../../glossary.rst:1100 +#: ../../glossary.rst:1165 msgid "regular package" msgstr "pacote regular" -#: ../../glossary.rst:1102 +#: ../../glossary.rst:1167 msgid "" "A traditional :term:`package`, such as a directory containing an ``__init__." "py`` file." @@ -2561,15 +2883,15 @@ msgstr "" "Um :term:`pacote` tradicional, como um diretório contendo um arquivo " "``__init__.py``." -#: ../../glossary.rst:1105 +#: ../../glossary.rst:1170 msgid "See also :term:`namespace package`." msgstr "Veja também :term:`pacote de espaço de nomes`." -#: ../../glossary.rst:1106 +#: ../../glossary.rst:1171 msgid "REPL" msgstr "REPL" -#: ../../glossary.rst:1108 +#: ../../glossary.rst:1173 msgid "" "An acronym for the \"read–eval–print loop\", another name for the :term:" "`interactive` interpreter shell." @@ -2577,11 +2899,11 @@ msgstr "" "Um acrônimo para \"read–eval–print loop\", outro nome para o console :term:" "`interativo` do interpretador." -#: ../../glossary.rst:1110 +#: ../../glossary.rst:1175 msgid "__slots__" msgstr "__slots__" -#: ../../glossary.rst:1112 +#: ../../glossary.rst:1177 msgid "" "A declaration inside a class that saves memory by pre-declaring space for " "instance attributes and eliminating instance dictionaries. Though popular, " @@ -2595,11 +2917,11 @@ msgstr "" "melhor se for reservada para casos raros, onde existe uma grande quantidade " "de instâncias em uma aplicação onde a memória é crítica." -#: ../../glossary.rst:1117 +#: ../../glossary.rst:1182 msgid "sequence" msgstr "sequência" -#: ../../glossary.rst:1119 +#: ../../glossary.rst:1184 msgid "" "An :term:`iterable` which supports efficient element access using integer " "indices via the :meth:`~object.__getitem__` special method and defines a :" @@ -2607,8 +2929,8 @@ msgid "" "built-in sequence types are :class:`list`, :class:`str`, :class:`tuple`, " "and :class:`bytes`. Note that :class:`dict` also supports :meth:`~object." "__getitem__` and :meth:`!__len__`, but is considered a mapping rather than a " -"sequence because the lookups use arbitrary :term:`immutable` keys rather " -"than integers." +"sequence because the lookups use arbitrary :term:`hashable` keys rather than " +"integers." msgstr "" "Um :term:`iterável` com suporte para acesso eficiente a seus elementos " "através de índices inteiros via método especial :meth:`~object.__getitem__` " @@ -2617,9 +2939,9 @@ msgstr "" "`str`, :class:`tuple`, e :class:`bytes`. Note que :class:`dict` também tem " "suporte para :meth:`~object.__getitem__` e :meth:`!__len__`, mas é " "considerado um mapeamento e não uma sequência porque a busca usa uma chave :" -"term:`imutável` arbitrária em vez de inteiros." +"term:`hasheável` arbitrária em vez de inteiros." -#: ../../glossary.rst:1128 +#: ../../glossary.rst:1193 msgid "" "The :class:`collections.abc.Sequence` abstract base class defines a much " "richer interface that goes beyond just :meth:`~object.__getitem__` and :meth:" @@ -2637,11 +2959,11 @@ msgstr "" "`~abc.ABCMeta.register`. Para mais documentação sobre métodos de sequências " "em geral, veja :ref:`Operações comuns de sequências `." -#: ../../glossary.rst:1137 +#: ../../glossary.rst:1202 msgid "set comprehension" msgstr "compreensão de conjunto" -#: ../../glossary.rst:1139 +#: ../../glossary.rst:1204 msgid "" "A compact way to process all or part of the elements in an iterable and " "return a set with the results. ``results = {c for c in 'abracadabra' if c " @@ -2653,11 +2975,11 @@ msgstr "" "'abracadabra' if c not in 'abc'}`` gera um conjunto de strings ``{'r', 'd'}" "``. Veja :ref:`comprehensions`." -#: ../../glossary.rst:1143 +#: ../../glossary.rst:1208 msgid "single dispatch" msgstr "despacho único" -#: ../../glossary.rst:1145 +#: ../../glossary.rst:1210 msgid "" "A form of :term:`generic function` dispatch where the implementation is " "chosen based on the type of a single argument." @@ -2665,11 +2987,11 @@ msgstr "" "Uma forma de despacho de :term:`função genérica` onde a implementação é " "escolhida com base no tipo de um único argumento." -#: ../../glossary.rst:1147 +#: ../../glossary.rst:1212 msgid "slice" msgstr "fatia" -#: ../../glossary.rst:1149 +#: ../../glossary.rst:1214 msgid "" "An object usually containing a portion of a :term:`sequence`. A slice is " "created using the subscript notation, ``[]`` with colons between numbers " @@ -2681,38 +3003,29 @@ msgstr "" "pontos entre números, como em ``variable_name[1:3:5]``. A notação de suporte " "(subscrito) utiliza objetos :class:`slice` internamente." -#: ../../glossary.rst:1153 +#: ../../glossary.rst:1218 msgid "soft deprecated" msgstr "suavemente descontinuado" -#: ../../glossary.rst:1155 +#: ../../glossary.rst:1220 msgid "" -"A soft deprecation can be used when using an API which should no longer be " -"used to write new code, but it remains safe to continue using it in existing " -"code. The API remains documented and tested, but will not be developed " -"further (no enhancement)." +"A soft deprecated API should not be used in new code, but it is safe for " +"already existing code to use it. The API remains documented and tested, but " +"will not be enhanced further." msgstr "" -"Uma descontinuação suave pode ser usada quando uma API não deveria ser usada " -"para escrever código novo, mas continua sendo seguro a continuação de uso em " -"código existente. A API continua sendo documentada e testada, mas não será " -"mais desenvolvida (sem melhorias)." +"Uma API suavemente descontinuada não deve ser usada em código novo, mas é " +"seguro para código já existente usá-la. A API continua documentada e " +"testada, mas não será melhorada." -#: ../../glossary.rst:1160 +#: ../../glossary.rst:1224 msgid "" -"The main difference between a \"soft\" and a (regular) \"hard\" deprecation " -"is that the soft deprecation does not imply scheduling the removal of the " -"deprecated API." +"Soft deprecation, unlike normal deprecation, does not plan on removing the " +"API and will not emit warnings." msgstr "" -"A principal diferença entre uma descontinuação \"suave\" e uma " -"descontinuação (regular) \"física\" é que a descontinuação suave não implica " -"no planejamento da remoção da API." +"A descontinuação suave, diferentemente da descontinuação normal, não planeja " +"remover a API e não emitirá avisos." -#: ../../glossary.rst:1164 -msgid "Another difference is that a soft deprecation does not issue a warning." -msgstr "" -"Uma outra diferença é que a descontinuação suave não provoca um alerta." - -#: ../../glossary.rst:1166 +#: ../../glossary.rst:1227 msgid "" "See `PEP 387: Soft Deprecation `_." @@ -2720,11 +3033,11 @@ msgstr "" "Veja `PEP 387: Descontinuação suave `_." -#: ../../glossary.rst:1168 +#: ../../glossary.rst:1229 msgid "special method" msgstr "método especial" -#: ../../glossary.rst:1172 +#: ../../glossary.rst:1233 msgid "" "A method that is called implicitly by Python to execute a certain operation " "on a type, such as addition. Such methods have names starting and ending " @@ -2736,11 +3049,11 @@ msgstr "" "iniciando e terminando com dois underscores. Métodos especiais estão " "documentados em :ref:`specialnames`." -#: ../../glossary.rst:1176 +#: ../../glossary.rst:1237 msgid "statement" msgstr "instrução" -#: ../../glossary.rst:1178 +#: ../../glossary.rst:1239 msgid "" "A statement is part of a suite (a \"block\" of code). A statement is either " "an :term:`expression` or one of several constructs with a keyword, such as :" @@ -2750,11 +3063,11 @@ msgstr "" "ou uma :term:`expressão` ou uma de várias construções com uma palavra " "reservada, tal como :keyword:`if`, :keyword:`while` ou :keyword:`for`." -#: ../../glossary.rst:1181 +#: ../../glossary.rst:1242 msgid "static type checker" msgstr "verificador de tipo estático" -#: ../../glossary.rst:1183 +#: ../../glossary.rst:1244 msgid "" "An external tool that reads Python code and analyzes it, looking for issues " "such as incorrect types. See also :term:`type hints ` and the :" @@ -2764,11 +3077,11 @@ msgstr "" "problemas como tipos incorretos. Consulte também :term:`dicas de tipo ` e o módulo :mod:`typing`." -#: ../../glossary.rst:1186 +#: ../../glossary.rst:1247 msgid "strong reference" msgstr "referência forte" -#: ../../glossary.rst:1188 +#: ../../glossary.rst:1249 msgid "" "In Python's C API, a strong reference is a reference to an object which is " "owned by the code holding the reference. The strong reference is taken by " @@ -2780,7 +3093,7 @@ msgstr "" "chamando :c:func:`Py_INCREF` quando a referência é criada e liberada com :c:" "func:`Py_DECREF` quando a referência é excluída." -#: ../../glossary.rst:1194 +#: ../../glossary.rst:1255 msgid "" "The :c:func:`Py_NewRef` function can be used to create a strong reference to " "an object. Usually, the :c:func:`Py_DECREF` function must be called on the " @@ -2792,15 +3105,15 @@ msgstr "" "na referência forte antes de sair do escopo da referência forte, para evitar " "o vazamento de uma referência." -#: ../../glossary.rst:1199 +#: ../../glossary.rst:1260 msgid "See also :term:`borrowed reference`." msgstr "Veja também :term:`referência emprestada`." -#: ../../glossary.rst:1200 +#: ../../glossary.rst:1261 msgid "text encoding" msgstr "codificador de texto" -#: ../../glossary.rst:1202 +#: ../../glossary.rst:1263 msgid "" "A string in Python is a sequence of Unicode code points (in range " "``U+0000``--``U+10FFFF``). To store or transfer a string, it needs to be " @@ -2810,7 +3123,7 @@ msgstr "" "intervalo ``U+0000``--``U+10FFFF``). Para armazenar ou transferir uma " "string, ela precisa ser serializada como uma sequência de bytes." -#: ../../glossary.rst:1206 +#: ../../glossary.rst:1267 msgid "" "Serializing a string into a sequence of bytes is known as \"encoding\", and " "recreating the string from the sequence of bytes is known as \"decoding\"." @@ -2819,7 +3132,7 @@ msgstr "" "\"codificação\" e a recriação da string a partir de uma sequência de bytes é " "conhecida como \"decodificação\"." -#: ../../glossary.rst:1209 +#: ../../glossary.rst:1270 msgid "" "There are a variety of different text serialization :ref:`codecs `, which are collectively referred to as \"text encodings\"." @@ -2827,11 +3140,11 @@ msgstr "" "Há uma variedade de diferentes serializações de texto :ref:`codecs `, que são coletivamente chamadas de \"codificações de texto\"." -#: ../../glossary.rst:1212 +#: ../../glossary.rst:1273 msgid "text file" msgstr "arquivo texto" -#: ../../glossary.rst:1214 +#: ../../glossary.rst:1275 msgid "" "A :term:`file object` able to read and write :class:`str` objects. Often, a " "text file actually accesses a byte-oriented datastream and handles the :term:" @@ -2846,19 +3159,41 @@ msgstr "" "``'w'``), :data:`sys.stdin`, :data:`sys.stdout`, e instâncias de :class:`io." "StringIO`." -#: ../../glossary.rst:1221 +#: ../../glossary.rst:1282 msgid "" "See also :term:`binary file` for a file object able to read and write :term:" "`bytes-like objects `." msgstr "" -"Veja também :term:`arquivo binário ` para um objeto arquivo " -"apto a ler e escrever :term:`objetos byte ou similar `." +"Veja também :term:`arquivo binário` para um objeto arquivo apto a ler e " +"escrever :term:`objetos bytes ou similar `." + +#: ../../glossary.rst:1284 +msgid "token" +msgstr "token" + +#: ../../glossary.rst:1287 +msgid "" +"A small unit of source code, generated by the :ref:`lexical analyzer " +"` (also called the *tokenizer*). Names, numbers, strings, " +"operators, newlines and similar are represented by tokens." +msgstr "" +"Uma pequena unidade de código-fonte, gerada pelo :ref:`analisador léxico " +"` (também chamado de *tokenizador*). Nomes, números, strings, " +"operadores, quebras de linha e similares são representados por tokens." + +#: ../../glossary.rst:1292 +msgid "" +"The :mod:`tokenize` module exposes Python's lexical analyzer. The :mod:" +"`token` module contains information on the various types of tokens." +msgstr "" +"O módulo :mod:`tokenize` expõe o analisador léxico do Python. O módulo :mod:" +"`token` contém informações sobre os vários tipos de tokens." -#: ../../glossary.rst:1223 +#: ../../glossary.rst:1295 msgid "triple-quoted string" msgstr "aspas triplas" -#: ../../glossary.rst:1225 +#: ../../glossary.rst:1297 msgid "" "A string which is bound by three instances of either a quotation mark (\") " "or an apostrophe ('). While they don't provide any functionality not " @@ -2876,51 +3211,73 @@ msgstr "" "caractere de continuação, fazendo-as especialmente úteis quando escrevemos " "documentação em docstrings." -#: ../../glossary.rst:1232 +#: ../../glossary.rst:1304 msgid "type" msgstr "tipo" -#: ../../glossary.rst:1234 +#: ../../glossary.rst:1306 msgid "" "The type of a Python object determines what kind of object it is; every " -"object has a type. An object's type is accessible as its :attr:`~instance." +"object has a type. An object's type is accessible as its :attr:`~object." "__class__` attribute or can be retrieved with ``type(obj)``." msgstr "" -"O tipo de um objeto Python determina qual tipo de objeto ele é; cada objeto " -"tem um tipo. Um tipo de objeto é acessível pelo atributo :attr:`~instância." -"__class__` ou pode ser recuperado com ``type(obj)``." +"O tipo de um objeto Python determina qual classe de objeto ele é; cada " +"objeto tem um tipo. Um tipo de objeto é acessível pelo atributo :attr:" +"`~object.__class__` ou pode ser recuperado com ``type(obj)``." -#: ../../glossary.rst:1238 +#: ../../glossary.rst:1310 msgid "type alias" -msgstr "tipo alias" +msgstr "apelido de tipo" -#: ../../glossary.rst:1240 +#: ../../glossary.rst:1312 msgid "A synonym for a type, created by assigning the type to an identifier." msgstr "" "Um sinônimo para um tipo, criado através da atribuição do tipo para um " "identificador." -#: ../../glossary.rst:1242 +#: ../../glossary.rst:1314 msgid "" "Type aliases are useful for simplifying :term:`type hints `. For " "example::" msgstr "" -"Tipos alias são úteis para simplificar :term:`dicas de tipo `. " -"Por exemplo::" +"Apelidos de tipo são úteis para simplificar :term:`dicas de tipo `. Por exemplo::" -#: ../../glossary.rst:1249 +#: ../../glossary.rst:1317 +msgid "" +"def remove_gray_shades(\n" +" colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:\n" +" pass" +msgstr "" +"def remove_tons_de_cinza(\n" +" cores: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:\n" +" pass" + +#: ../../glossary.rst:1321 msgid "could be made more readable like this::" msgstr "pode tornar-se mais legível desta forma::" -#: ../../glossary.rst:1256 ../../glossary.rst:1270 +#: ../../glossary.rst:1323 +msgid "" +"Color = tuple[int, int, int]\n" +"\n" +"def remove_gray_shades(colors: list[Color]) -> list[Color]:\n" +" pass" +msgstr "" +"Cor = tuple[int, int, int]\n" +"\n" +"def remove_tons_de_cinza(cores: list[Cor]) -> list[Cor]:\n" +" pass" + +#: ../../glossary.rst:1328 ../../glossary.rst:1342 msgid "See :mod:`typing` and :pep:`484`, which describe this functionality." msgstr "Veja :mod:`typing` e :pep:`484`, a qual descreve esta funcionalidade." -#: ../../glossary.rst:1257 +#: ../../glossary.rst:1329 msgid "type hint" msgstr "dica de tipo" -#: ../../glossary.rst:1259 +#: ../../glossary.rst:1331 msgid "" "An :term:`annotation` that specifies the expected type for a variable, a " "class attribute, or a function parameter or return value." @@ -2928,7 +3285,7 @@ msgstr "" "Uma :term:`anotação` que especifica o tipo esperado para uma variável, um " "atributo de classe, ou um parâmetro de função ou um valor de retorno." -#: ../../glossary.rst:1262 +#: ../../glossary.rst:1334 msgid "" "Type hints are optional and are not enforced by Python but they are useful " "to :term:`static type checkers `. They can also aid " @@ -2938,7 +3295,7 @@ msgstr "" "úteis para :term:`verificadores de tipo estático `. " "Eles também ajudam IDEs a completar e refatorar código." -#: ../../glossary.rst:1266 +#: ../../glossary.rst:1338 msgid "" "Type hints of global variables, class attributes, and functions, but not " "local variables, can be accessed using :func:`typing.get_type_hints`." @@ -2947,11 +3304,11 @@ msgstr "" "não de variáveis locais, podem ser acessadas usando :func:`typing." "get_type_hints`." -#: ../../glossary.rst:1271 +#: ../../glossary.rst:1343 msgid "universal newlines" msgstr "novas linhas universais" -#: ../../glossary.rst:1273 +#: ../../glossary.rst:1345 msgid "" "A manner of interpreting text streams in which all of the following are " "recognized as ending a line: the Unix end-of-line convention ``'\\n'``, the " @@ -2965,22 +3322,30 @@ msgstr "" "no Macintosh ``'\\r'``. Veja :pep:`278` e :pep:`3116`, bem como :func:`bytes." "splitlines` para uso adicional." -#: ../../glossary.rst:1278 +#: ../../glossary.rst:1350 msgid "variable annotation" msgstr "anotação de variável" -#: ../../glossary.rst:1280 +#: ../../glossary.rst:1352 msgid "An :term:`annotation` of a variable or a class attribute." msgstr "Uma :term:`anotação` de uma variável ou um atributo de classe." -#: ../../glossary.rst:1282 +#: ../../glossary.rst:1354 msgid "" "When annotating a variable or a class attribute, assignment is optional::" msgstr "" "Ao fazer uma anotação de uma variável ou um atributo de classe, a atribuição " "é opcional::" -#: ../../glossary.rst:1287 +#: ../../glossary.rst:1356 +msgid "" +"class C:\n" +" field: 'annotation'" +msgstr "" +"class C:\n" +" campo: 'anotação'" + +#: ../../glossary.rst:1359 msgid "" "Variable annotations are usually used for :term:`type hints `: " "for example this variable is expected to take :class:`int` values::" @@ -2989,12 +3354,16 @@ msgstr "" "`: por exemplo, espera-se que esta variável receba valores do " "tipo :class:`int`::" -#: ../../glossary.rst:1293 +#: ../../glossary.rst:1363 +msgid "count: int = 0" +msgstr "contagem: int = 0" + +#: ../../glossary.rst:1365 msgid "Variable annotation syntax is explained in section :ref:`annassign`." msgstr "" "A sintaxe de anotação de variável é explicada na seção :ref:`annassign`." -#: ../../glossary.rst:1295 +#: ../../glossary.rst:1367 msgid "" "See :term:`function annotation`, :pep:`484` and :pep:`526`, which describe " "this functionality. Also see :ref:`annotations-howto` for best practices on " @@ -3004,11 +3373,11 @@ msgstr "" "funcionalidade. Veja também :ref:`annotations-howto` para as melhores " "práticas sobre como trabalhar com anotações." -#: ../../glossary.rst:1299 +#: ../../glossary.rst:1371 msgid "virtual environment" msgstr "ambiente virtual" -#: ../../glossary.rst:1301 +#: ../../glossary.rst:1373 msgid "" "A cooperatively isolated runtime environment that allows Python users and " "applications to install and upgrade Python distribution packages without " @@ -3019,15 +3388,15 @@ msgstr "" "instalarem e atualizarem pacotes Python sem interferir no comportamento de " "outras aplicações Python em execução no mesmo sistema." -#: ../../glossary.rst:1306 +#: ../../glossary.rst:1378 msgid "See also :mod:`venv`." msgstr "Veja também :mod:`venv`." -#: ../../glossary.rst:1307 +#: ../../glossary.rst:1379 msgid "virtual machine" msgstr "máquina virtual" -#: ../../glossary.rst:1309 +#: ../../glossary.rst:1381 msgid "" "A computer defined entirely in software. Python's virtual machine executes " "the :term:`bytecode` emitted by the bytecode compiler." @@ -3035,11 +3404,11 @@ msgstr "" "Um computador definido inteiramente em software. A máquina virtual de Python " "executa o :term:`bytecode` emitido pelo compilador de bytecode." -#: ../../glossary.rst:1311 +#: ../../glossary.rst:1383 msgid "Zen of Python" msgstr "Zen do Python" -#: ../../glossary.rst:1313 +#: ../../glossary.rst:1385 msgid "" "Listing of Python design principles and philosophies that are helpful in " "understanding and using the language. The listing can be found by typing " @@ -3049,18 +3418,18 @@ msgstr "" "compreensão e uso da linguagem. A lista é exibida quando se digita " "\"``import this``\" no console interativo." -#: ../../glossary.rst:256 +#: ../../glossary.rst:292 msgid "C-contiguous" msgstr "contíguo C" -#: ../../glossary.rst:256 +#: ../../glossary.rst:292 msgid "Fortran contiguous" msgstr "contíguo Fortran" -#: ../../glossary.rst:773 +#: ../../glossary.rst:831 msgid "magic" msgstr "mágico" -#: ../../glossary.rst:1170 +#: ../../glossary.rst:1231 msgid "special" msgstr "especial" diff --git a/howto/annotations.po b/howto/annotations.po index ba392c455..e4aec6d7b 100644 --- a/howto/annotations.po +++ b/howto/annotations.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Flávio Neves, 2022 -# Nicolas Evangelista, 2022 -# PAULO NASCIMENTO, 2024 -# Adorilson Bezerra , 2024 -# José Carlos, 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -35,7 +29,7 @@ msgstr "Boas práticas para anotações" #: ../../howto/annotations.rst:0 msgid "author" -msgstr "Autor" +msgstr "autor" #: ../../howto/annotations.rst:7 msgid "Larry Hastings" @@ -194,6 +188,26 @@ msgstr "" "``__annotations__`` de uma classe pode inesperadamente retornar o dicionário " "de anotações de uma *classe base.* Por exemplo::" +#: ../../howto/annotations.rst:89 +msgid "" +"class Base:\n" +" a: int = 3\n" +" b: str = 'abc'\n" +"\n" +"class Derived(Base):\n" +" pass\n" +"\n" +"print(Derived.__annotations__)" +msgstr "" +"class Base:\n" +" a: int = 3\n" +" b: str = 'abc'\n" +"\n" +"class Derived(Base):\n" +" pass\n" +"\n" +"print(Derived.__annotations__)" + #: ../../howto/annotations.rst:98 msgid "This will print the annotations dict from ``Base``, not ``Derived``." msgstr "" @@ -204,17 +218,17 @@ msgid "" "Your code will have to have a separate code path if the object you're " "examining is a class (``isinstance(o, type)``). In that case, best practice " "relies on an implementation detail of Python 3.9 and before: if a class has " -"annotations defined, they are stored in the class's ``__dict__`` " +"annotations defined, they are stored in the class's :attr:`~type.__dict__` " "dictionary. Since the class may or may not have annotations defined, best " -"practice is to call the ``get`` method on the class dict." +"practice is to call the :meth:`~dict.get` method on the class dict." msgstr "" -"Seu código deve seguir uma abordagem diferente caso o objeto que você esteja " -"examinando seja uma classe (``isinstance(o, type)``). Nesse caso, a melhor " -"prática está ligada a um detalhe de implementação do Python 3.9 e " -"anteriores: se a classe possui anotações definidas, elas são armazenadas no " -"dicionário ``__dict__`` da classe. Como a classe pode ou não ter anotações " -"definidas, a melhor prática é chamar o método ``get`` no dicionário da " -"classe." +"Seu código terá que ter um caminho de código separado se o objeto que você " +"está examinando for uma classe (``isinstance(o, type)``). Nesse caso, a " +"melhor prática depende de um detalhe de implementação do Python 3.9 e " +"anteriores: se uma classe tiver anotações definidas, elas serão armazenadas " +"no dicionário :attr:`~type.__dict__` da classe. Como a classe pode ou não " +"ter anotações definidas, a melhor prática é chamar o método :meth:`~dict." +"get` no dict da classe." #: ../../howto/annotations.rst:109 msgid "" @@ -226,6 +240,18 @@ msgstr "" "segura o atributo ``__annotations__`` em um objeto arbitrário em Python 3.9 " "e anteriores::" +#: ../../howto/annotations.rst:113 +msgid "" +"if isinstance(o, type):\n" +" ann = o.__dict__.get('__annotations__', None)\n" +"else:\n" +" ann = getattr(o, '__annotations__', None)" +msgstr "" +"if isinstance(o, type):\n" +" ann = o.__dict__.get('__annotations__', None)\n" +"else:\n" +" ann = getattr(o, '__annotations__', None)" + #: ../../howto/annotations.rst:118 msgid "" "After running this code, ``ann`` should be either a dictionary or ``None``. " @@ -238,13 +264,13 @@ msgstr "" #: ../../howto/annotations.rst:123 msgid "" -"Note that some exotic or malformed type objects may not have a ``__dict__`` " -"attribute, so for extra safety you may also wish to use :func:`getattr` to " -"access ``__dict__``." +"Note that some exotic or malformed type objects may not have a :attr:`~type." +"__dict__` attribute, so for extra safety you may also wish to use :func:" +"`getattr` to access :attr:`!__dict__`." msgstr "" -"Note que alguns tipos de objetos exóticos ou mal formatados podem não " -"possuir um atributo ``__dict__``, então por precaução você também pode " -"querer usar :func:`getattr` para acessar ``__dict__``." +"Observe que alguns objetos de tipos exóticos ou malformados podem não ter " +"atributo um :attr:`~type.__dict__`, portanto, para maior segurança, talvez " +"você também queira usar :func:`getattr` para acessar :attr:`!__dict__`." #: ../../howto/annotations.rst:129 msgid "Manually Un-Stringizing Stringized Annotations" @@ -463,6 +489,18 @@ msgstr "" "string será posta entre aspas. Na prática a anotação receberá aspas " "*duplas*. Por exemplo::" +#: ../../howto/annotations.rst:227 +msgid "" +"from __future__ import annotations\n" +"def foo(a: \"str\"): pass\n" +"\n" +"print(foo.__annotations__)" +msgstr "" +"from __future__ import annotations\n" +"def foo(a: \"str\"): pass\n" +"\n" +"print(foo.__annotations__)" + #: ../../howto/annotations.rst:232 msgid "" "This prints ``{'a': \"'str'\"}``. This shouldn't really be considered a " diff --git a/howto/argparse-optparse.po b/howto/argparse-optparse.po new file mode 100644 index 000000000..c451b34d8 --- /dev/null +++ b/howto/argparse-optparse.po @@ -0,0 +1,182 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../howto/argparse-optparse.rst:8 +msgid "Migrating ``optparse`` code to ``argparse``" +msgstr "Migrando código ``optparse`` para ``argparse``" + +#: ../../howto/argparse-optparse.rst:10 +msgid "" +"The :mod:`argparse` module offers several higher level features not natively " +"provided by the :mod:`optparse` module, including:" +msgstr "" +"O módulo :mod:`argparse` oferece vários recursos de nível mais alto não " +"fornecidos nativamente pelo módulo :mod:`optparse`, incluindo:" + +#: ../../howto/argparse-optparse.rst:13 +msgid "Handling positional arguments." +msgstr "Tratando argumentos posicionais." + +#: ../../howto/argparse-optparse.rst:14 +msgid "Supporting subcommands." +msgstr "Prover suporte a subcomandos." + +#: ../../howto/argparse-optparse.rst:15 +msgid "Allowing alternative option prefixes like ``+`` and ``/``." +msgstr "Permitir prefixos alternativos de opções como ``+`` e ``/``." + +#: ../../howto/argparse-optparse.rst:16 +msgid "Handling zero-or-more and one-or-more style arguments." +msgstr "Manipular argumentos de estilo \"zero ou mais\" e \"um ou mais\"." + +#: ../../howto/argparse-optparse.rst:17 +msgid "Producing more informative usage messages." +msgstr "Produzir mensagens de uso mais informativas." + +#: ../../howto/argparse-optparse.rst:18 +msgid "Providing a much simpler interface for custom ``type`` and ``action``." +msgstr "" +"Fornecer uma interface muito mais simples para ``type`` e ``action`` " +"personalizados." + +#: ../../howto/argparse-optparse.rst:20 +msgid "" +"Originally, the :mod:`argparse` module attempted to maintain compatibility " +"with :mod:`optparse`. However, the fundamental design differences between " +"supporting declarative command line option processing (while leaving " +"positional argument processing to application code), and supporting both " +"named options and positional arguments in the declarative interface mean " +"that the API has diverged from that of ``optparse`` over time." +msgstr "" +"Originalmente, o módulo :mod:`argparse` tentou manter a compatibilidade com :" +"mod:`optparse`. No entanto, as diferenças fundamentais de design entre " +"suportar o processamento de opções de linha de comando declarativas " +"(enquanto deixa o processamento de argumentos posicionais para o código da " +"aplicação) e suportar opções nomeadas e argumentos posicionais na interface " +"declarativa significam que a API divergiu daquela de ``optparse`` ao longo " +"do tempo." + +#: ../../howto/argparse-optparse.rst:27 +msgid "" +"As described in :ref:`choosing-an-argument-parser`, applications that are " +"currently using :mod:`optparse` and are happy with the way it works can just " +"continue to use ``optparse``." +msgstr "" +"Conforme descrito em :ref:`choosing-an-argument-parser`, as aplicações que " +"atualmente usam :mod:`optparse` e estão satisfeitos com a forma como ele " +"funciona podem continuar usando ``optparse``." + +#: ../../howto/argparse-optparse.rst:31 +msgid "" +"Application developers that are considering migrating should also review the " +"list of intrinsic behavioural differences described in that section before " +"deciding whether or not migration is desirable." +msgstr "" +"Os desenvolvedores de aplicações que estão pensando em migrar também devem " +"revisar a lista de diferenças comportamentais intrínsecas descritas nessa " +"seção antes de decidir se a migração é desejável ou não." + +#: ../../howto/argparse-optparse.rst:35 +msgid "" +"For applications that do choose to migrate from :mod:`optparse` to :mod:" +"`argparse`, the following suggestions should be helpful:" +msgstr "" +"Para aplicações que optam por migrar de :mod:`optparse` para :mod:" +"`argparse`, as seguintes sugestões devem ser úteis:" + +#: ../../howto/argparse-optparse.rst:38 +msgid "" +"Replace all :meth:`optparse.OptionParser.add_option` calls with :meth:" +"`ArgumentParser.add_argument` calls." +msgstr "" +"Substituir todas as chamadas de :meth:`optparse.OptionParser.add_option` por " +"chamadas de :meth:`ArgumentParser.add_argument`." + +#: ../../howto/argparse-optparse.rst:41 +msgid "" +"Replace ``(options, args) = parser.parse_args()`` with ``args = parser." +"parse_args()`` and add additional :meth:`ArgumentParser.add_argument` calls " +"for the positional arguments. Keep in mind that what was previously called " +"``options``, now in the :mod:`argparse` context is called ``args``." +msgstr "" +"Substituir ``(options, args) = parser.parse_args()`` por ``args = parser." +"parse_args()`` e adicionar chamadas adicionais a :meth:`ArgumentParser." +"add_argument` para os argumentos posicionais. Tenha em mente que o que " +"anteriormente era chamado de ``options``, agora no contexto do :mod:" +"`argparse` é chamado de ``args``." + +#: ../../howto/argparse-optparse.rst:46 +msgid "" +"Replace :meth:`optparse.OptionParser.disable_interspersed_args` by using :" +"meth:`~ArgumentParser.parse_intermixed_args` instead of :meth:" +"`~ArgumentParser.parse_args`." +msgstr "" +"Substituir :meth:`optparse.OptionParser.disable_interspersed_args` usando :" +"meth:`~ArgumentParser.parse_intermixed_args` em vez de :meth:" +"`~ArgumentParser.parse_args`." + +#: ../../howto/argparse-optparse.rst:50 +msgid "" +"Replace callback actions and the ``callback_*`` keyword arguments with " +"``type`` or ``action`` arguments." +msgstr "" +"Substituir ações de função de retorno e argumentos nomeados ``callback_*`` " +"por argumentos ``type`` ou ``action``." + +#: ../../howto/argparse-optparse.rst:53 +msgid "" +"Replace string names for ``type`` keyword arguments with the corresponding " +"type objects (e.g. int, float, complex, etc)." +msgstr "" +"Substituir nomes de strings para argumentos nomeados ``type`` pelos objetos " +"de tipo correspondentes (por exemplo, int, float, complex, etc)." + +#: ../../howto/argparse-optparse.rst:56 +msgid "" +"Replace :class:`optparse.Values` with :class:`Namespace` and :exc:`optparse." +"OptionError` and :exc:`optparse.OptionValueError` with :exc:`ArgumentError`." +msgstr "" +"Substituir :class:`optparse.Values` por :class:`Namespace` e :exc:`optparse." +"OptionError` e :exc:`optparse.OptionValueError` por :exc:`ArgumentError`." + +#: ../../howto/argparse-optparse.rst:60 +msgid "" +"Replace strings with implicit arguments such as ``%default`` or ``%prog`` " +"with the standard Python syntax to use dictionaries to format strings, that " +"is, ``%(default)s`` and ``%(prog)s``." +msgstr "" +"Substituir strings com argumentos implícitos tal como ``%default`` ou " +"``%prog`` pela sintaxe padrão do Python para usar dicionários para formatar " +"strings, ou seja, ``%(default)s`` e ``%(prog)s``." + +#: ../../howto/argparse-optparse.rst:64 +msgid "" +"Replace the OptionParser constructor ``version`` argument with a call to " +"``parser.add_argument('--version', action='version', version='')``." +msgstr "" +"Substituir o argumento ``version`` do construtor do OptionParser por uma " +"chamada a ``parser.add_argument('--version', action='version', version='')``." diff --git a/howto/argparse.po b/howto/argparse.po index 4cd7bcff5..f39898aae 100644 --- a/howto/argparse.po +++ b/howto/argparse.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Humberto Rocha , 2021 -# Hemílio Lauro , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-05 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -49,22 +46,34 @@ msgstr "" #: ../../howto/argparse.rst:16 msgid "" -"There are two other modules that fulfill the same task, namely :mod:`getopt` " -"(an equivalent for ``getopt()`` from the C language) and the deprecated :mod:" -"`optparse`. Note also that :mod:`argparse` is based on :mod:`optparse`, and " -"therefore very similar in terms of usage." +"The standard library includes two other libraries directly related to " +"command-line parameter processing: the lower level :mod:`optparse` module " +"(which may require more code to configure for a given application, but also " +"allows an application to request behaviors that ``argparse`` doesn't " +"support), and the very low level :mod:`getopt` (which specifically serves as " +"an equivalent to the :c:func:`!getopt` family of functions available to C " +"programmers). While neither of those modules is covered directly in this " +"guide, many of the core concepts in ``argparse`` first originated in " +"``optparse``, so some aspects of this tutorial will also be relevant to " +"``optparse`` users." msgstr "" -"Existem outros dois módulos que cumprem esta mesma tarefa, chamados :mod:" -"`getopt` (equivalente ao ``getopt()`` da linguagem C) e outro que hoje está " -"descontinuado :mod:`optparse`. Note também que o :mod:`argparse` é baseado " -"no módulo :mod:`optparse`, e, portanto, possui bastante similaridade em " -"termos de uso." - -#: ../../howto/argparse.rst:24 +"A biblioteca padrão inclui duas outras bibliotecas diretamente relacionadas " +"ao processamento de parâmetros de linha de comando: o módulo de nível " +"inferior :mod:`optparse` (que pode exigir mais código para configurar uma " +"determinada aplicação, mas também permite que uma aplicação solicite " +"comportamentos que ``argparse`` não suporta), e o nível muito baixo :mod:" +"`getopt` (que serve especificamente como um equivalente à família de " +"funções :c:func:`!getopt` disponível para programadores C). Embora nenhum " +"desses módulos seja abordado diretamente neste guia, muitos dos conceitos " +"principais em ``argparse`` se originaram primeiro em ``optparse``, então " +"alguns aspectos deste tutorial também serão relevantes para usuários de " +"``optparse``." + +#: ../../howto/argparse.rst:29 msgid "Concepts" msgstr "Conceitos" -#: ../../howto/argparse.rst:26 +#: ../../howto/argparse.rst:31 msgid "" "Let's show the sort of functionality that we are going to explore in this " "introductory tutorial by making use of the :command:`ls` command:" @@ -72,11 +81,49 @@ msgstr "" "Demonstraremos o tipo de funcionalidade que vamos explorar neste tutorial " "introdutório fazendo uso do comando :command:`ls`:" -#: ../../howto/argparse.rst:48 +#: ../../howto/argparse.rst:34 +msgid "" +"$ ls\n" +"cpython devguide prog.py pypy rm-unused-function.patch\n" +"$ ls pypy\n" +"ctypes_configure demo dotviewer include lib_pypy lib-python ...\n" +"$ ls -l\n" +"total 20\n" +"drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython\n" +"drwxr-xr-x 4 wena wena 4096 Feb 8 12:04 devguide\n" +"-rwxr-xr-x 1 wena wena 535 Feb 19 00:05 prog.py\n" +"drwxr-xr-x 14 wena wena 4096 Feb 7 00:59 pypy\n" +"-rw-r--r-- 1 wena wena 741 Feb 18 01:01 rm-unused-function.patch\n" +"$ ls --help\n" +"Usage: ls [OPTION]... [FILE]...\n" +"List information about the FILEs (the current directory by default).\n" +"Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.\n" +"..." +msgstr "" +"$ ls\n" +"cpython devguide prog.py pypy rm-unused-function.patch\n" +"$ ls pypy\n" +"ctypes_configure demo dotviewer include lib_pypy lib-python ...\n" +"$ ls -l\n" +"total 20\n" +"drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython\n" +"drwxr-xr-x 4 wena wena 4096 Feb 8 12:04 devguide\n" +"-rwxr-xr-x 1 wena wena 535 Feb 19 00:05 prog.py\n" +"drwxr-xr-x 14 wena wena 4096 Feb 7 00:59 pypy\n" +"-rw-r--r-- 1 wena wena 741 Feb 18 01:01 rm-unused-function.patch\n" +"$ ls --help\n" +"Uso: ls [OPÇÃO]... [ARQUIVO]...\n" +"Lista informações sobre os ARQUIVOs (no diretório atual por padrão).\n" +"Lista as entradas em ordem alfabética se não for usada nenhuma opção -" +"cftuvSUX\n" +"nem --sort..\n" +"..." + +#: ../../howto/argparse.rst:53 msgid "A few concepts we can learn from the four commands:" msgstr "Alguns conceitos que podemos aprender a partir destes quatro comandos:" -#: ../../howto/argparse.rst:50 +#: ../../howto/argparse.rst:55 msgid "" "The :command:`ls` command is useful when run without any options at all. It " "defaults to displaying the contents of the current directory." @@ -84,7 +131,7 @@ msgstr "" "O comando :command:`ls` é útil quando usado sem nenhuma opção. Por padrão, " "ele mostra o conteúdo do diretório atual." -#: ../../howto/argparse.rst:53 +#: ../../howto/argparse.rst:58 msgid "" "If we want beyond what it provides by default, we tell it a bit more. In " "this case, we want it to display a different directory, ``pypy``. What we " @@ -104,7 +151,7 @@ msgstr "" "SRC DEST``. A primeira posição é *o que você deseja copiar* e a segunda " "posição é *para onde você deseja copiar*." -#: ../../howto/argparse.rst:62 +#: ../../howto/argparse.rst:67 msgid "" "Now, say we want to change behaviour of the program. In our example, we " "display more info for each file instead of just showing the file names. The " @@ -115,7 +162,7 @@ msgstr "" "mostrar os nomes dos arquivos. O ``-l`` nesse caso é conhecido como um " "argumento opcional." -#: ../../howto/argparse.rst:66 +#: ../../howto/argparse.rst:71 msgid "" "That's a snippet of the help text. It's very useful in that you can come " "across a program you have never used before, and can figure out how it works " @@ -125,25 +172,63 @@ msgstr "" "programa que nunca usastes antes e poder descobrir como o mesmo funciona " "simplesmente lendo o seu texto de ajuda." -#: ../../howto/argparse.rst:72 +#: ../../howto/argparse.rst:77 msgid "The basics" msgstr "O básico" -#: ../../howto/argparse.rst:74 +#: ../../howto/argparse.rst:79 msgid "Let us start with a very simple example which does (almost) nothing::" msgstr "Comecemos com um exemplo muito simples que irá fazer (quase) nada::" -#: ../../howto/argparse.rst:80 ../../howto/argparse.rst:188 -#: ../../howto/argparse.rst:209 +#: ../../howto/argparse.rst:81 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.parse_args()" +msgstr "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.parse_args()" + +#: ../../howto/argparse.rst:85 ../../howto/argparse.rst:193 +#: ../../howto/argparse.rst:214 msgid "Following is a result of running the code:" msgstr "A seguir, temos o resultado da execução do código:" -#: ../../howto/argparse.rst:97 ../../howto/argparse.rst:254 -#: ../../howto/argparse.rst:298 +#: ../../howto/argparse.rst:87 +msgid "" +"$ python prog.py\n" +"$ python prog.py --help\n" +"usage: prog.py [-h]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"$ python prog.py --verbose\n" +"usage: prog.py [-h]\n" +"prog.py: error: unrecognized arguments: --verbose\n" +"$ python prog.py foo\n" +"usage: prog.py [-h]\n" +"prog.py: error: unrecognized arguments: foo" +msgstr "" +"$ python prog.py\n" +"$ python prog.py --help\n" +"usage: prog.py [-h]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"$ python prog.py --verbose\n" +"usage: prog.py [-h]\n" +"prog.py: error: unrecognized arguments: --verbose\n" +"$ python prog.py foo\n" +"usage: prog.py [-h]\n" +"prog.py: error: unrecognized arguments: foo" + +#: ../../howto/argparse.rst:102 ../../howto/argparse.rst:259 +#: ../../howto/argparse.rst:303 msgid "Here is what is happening:" msgstr "Eis aqui o que está acontecendo:" -#: ../../howto/argparse.rst:99 +#: ../../howto/argparse.rst:104 msgid "" "Running the script without any options results in nothing displayed to " "stdout. Not so useful." @@ -151,7 +236,7 @@ msgstr "" "Executar o script sem qualquer opção resultará que nada será exibido em " "stdout. Isso não é útil." -#: ../../howto/argparse.rst:102 +#: ../../howto/argparse.rst:107 msgid "" "The second one starts to display the usefulness of the :mod:`argparse` " "module. We have done almost nothing, but already we get a nice help message." @@ -159,7 +244,7 @@ msgstr "" "O segundo começa a exibir as utilidades do módulo :mod:`argparse`. Não " "fizemos quase nada, mas já recebemos uma boa mensagem de ajuda." -#: ../../howto/argparse.rst:105 +#: ../../howto/argparse.rst:110 msgid "" "The ``--help`` option, which can also be shortened to ``-h``, is the only " "option we get for free (i.e. no need to specify it). Specifying anything " @@ -171,23 +256,67 @@ msgstr "" "Determinar qualquer outra coisa resulta num erro. Mas mesmo assim, recebemos " "uma mensagem de uso bastante útil, também de graça." -#: ../../howto/argparse.rst:112 +#: ../../howto/argparse.rst:117 msgid "Introducing Positional arguments" msgstr "Apresentando os argumentos posicionais" -#: ../../howto/argparse.rst:114 +#: ../../howto/argparse.rst:119 msgid "An example::" msgstr "Um exemplo::" -#: ../../howto/argparse.rst:122 +#: ../../howto/argparse.rst:121 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"echo\")\n" +"args = parser.parse_args()\n" +"print(args.echo)" +msgstr "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"echo\")\n" +"args = parser.parse_args()\n" +"print(args.echo)" + +#: ../../howto/argparse.rst:127 msgid "And running the code:" msgstr "E executando o código:" -#: ../../howto/argparse.rst:140 +#: ../../howto/argparse.rst:129 +msgid "" +"$ python prog.py\n" +"usage: prog.py [-h] echo\n" +"prog.py: error: the following arguments are required: echo\n" +"$ python prog.py --help\n" +"usage: prog.py [-h] echo\n" +"\n" +"positional arguments:\n" +" echo\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"$ python prog.py foo\n" +"foo" +msgstr "" +"$ python prog.py\n" +"usage: prog.py [-h] echo\n" +"prog.py: error: the following arguments are required: echo\n" +"$ python prog.py --help\n" +"usage: prog.py [-h] echo\n" +"\n" +"positional arguments:\n" +" echo\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"$ python prog.py foo\n" +"foo" + +#: ../../howto/argparse.rst:145 msgid "Here is what's happening:" msgstr "Aqui está o que acontecerá:" -#: ../../howto/argparse.rst:142 +#: ../../howto/argparse.rst:147 msgid "" "We've added the :meth:`~ArgumentParser.add_argument` method, which is what " "we use to specify which command-line options the program is willing to " @@ -199,12 +328,12 @@ msgstr "" "disposto a aceitar. Neste caso, eu o nomeei ``echo`` para que ele esteja de " "acordo com sua função." -#: ../../howto/argparse.rst:146 +#: ../../howto/argparse.rst:151 msgid "Calling our program now requires us to specify an option." msgstr "" "Chamar o nosso programa neste momento, requer a especificação de uma opção." -#: ../../howto/argparse.rst:148 +#: ../../howto/argparse.rst:153 msgid "" "The :meth:`~ArgumentParser.parse_args` method actually returns some data " "from the options specified, in this case, ``echo``." @@ -212,7 +341,7 @@ msgstr "" "O método :meth:`~ArgumentParser.parse_args` realmente retorna alguns dados " "das opções especificadas, neste caso, ``echo``." -#: ../../howto/argparse.rst:151 +#: ../../howto/argparse.rst:156 msgid "" "The variable is some form of 'magic' that :mod:`argparse` performs for free " "(i.e. no need to specify which variable that value is stored in). You will " @@ -224,7 +353,7 @@ msgstr "" "armazenado). Você também notará que seu nome corresponde ao argumento string " "dado ao método, ``echo``." -#: ../../howto/argparse.rst:156 +#: ../../howto/argparse.rst:161 msgid "" "Note however that, although the help display looks nice and all, it " "currently is not as helpful as it can be. For example we see that we got " @@ -238,15 +367,79 @@ msgstr "" "de adivinhar ou ler o código-fonte. Então, vamos torná-lo um pouco mais " "útil::" -#: ../../howto/argparse.rst:167 +#: ../../howto/argparse.rst:166 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"echo\", help=\"echo the string you use here\")\n" +"args = parser.parse_args()\n" +"print(args.echo)" +msgstr "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"echo\", help=\"echo the string you use here\")\n" +"args = parser.parse_args()\n" +"print(args.echo)" + +#: ../../howto/argparse.rst:172 msgid "And we get:" msgstr "E, iremos obter:" -#: ../../howto/argparse.rst:180 +#: ../../howto/argparse.rst:174 +msgid "" +"$ python prog.py -h\n" +"usage: prog.py [-h] echo\n" +"\n" +"positional arguments:\n" +" echo echo the string you use here\n" +"\n" +"options:\n" +" -h, --help show this help message and exit" +msgstr "" +"$ python prog.py -h\n" +"usage: prog.py [-h] echo\n" +"\n" +"positional arguments:\n" +" echo echo the string you use here\n" +"\n" +"options:\n" +" -h, --help show this help message and exit" + +#: ../../howto/argparse.rst:185 msgid "Now, how about doing something even more useful::" msgstr "Agora, que tal fazer algo ainda mais útil::" -#: ../../howto/argparse.rst:198 +#: ../../howto/argparse.rst:187 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", help=\"display a square of a given " +"number\")\n" +"args = parser.parse_args()\n" +"print(args.square**2)" +msgstr "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", help=\"display a square of a given " +"number\")\n" +"args = parser.parse_args()\n" +"print(args.square**2)" + +#: ../../howto/argparse.rst:195 +msgid "" +"$ python prog.py 4\n" +"Traceback (most recent call last):\n" +" File \"prog.py\", line 5, in \n" +" print(args.square**2)\n" +"TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'" +msgstr "" +"$ python prog.py 4\n" +"Traceback (most recent call last):\n" +" File \"prog.py\", line 5, in \n" +" print(args.square**2)\n" +"TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'" + +#: ../../howto/argparse.rst:203 msgid "" "That didn't go so well. That's because :mod:`argparse` treats the options we " "give it as strings, unless we tell it otherwise. So, let's tell :mod:" @@ -256,7 +449,39 @@ msgstr "" "damos a ele como strings, a menos que digamos o contrário. Então, vamos " "dizer ao :mod:`argparse` para tratar essa entrada como um inteiro::" -#: ../../howto/argparse.rst:219 +#: ../../howto/argparse.rst:207 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", help=\"display a square of a given " +"number\",\n" +" type=int)\n" +"args = parser.parse_args()\n" +"print(args.square**2)" +msgstr "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", help=\"display a square of a given " +"number\",\n" +" type=int)\n" +"args = parser.parse_args()\n" +"print(args.square**2)" + +#: ../../howto/argparse.rst:216 +msgid "" +"$ python prog.py 4\n" +"16\n" +"$ python prog.py four\n" +"usage: prog.py [-h] square\n" +"prog.py: error: argument square: invalid int value: 'four'" +msgstr "" +"$ python prog.py 4\n" +"16\n" +"$ python prog.py four\n" +"usage: prog.py [-h] square\n" +"prog.py: error: argument square: invalid int value: 'four'" + +#: ../../howto/argparse.rst:224 msgid "" "That went well. The program now even helpfully quits on bad illegal input " "before proceeding." @@ -264,11 +489,11 @@ msgstr "" "Correu bem. O programa agora até fecha com ajuda de entrada ilegal ruim " "antes de prosseguir." -#: ../../howto/argparse.rst:224 +#: ../../howto/argparse.rst:229 msgid "Introducing Optional arguments" msgstr "Apresentando os argumentos opcionais" -#: ../../howto/argparse.rst:226 +#: ../../howto/argparse.rst:231 msgid "" "So far we have been playing with positional arguments. Let us have a look on " "how to add optional ones::" @@ -276,12 +501,58 @@ msgstr "" "Até agora, jogamos com argumentos posicionais. Vamos dar uma olhada em como " "adicionar opcionais::" -#: ../../howto/argparse.rst:236 ../../howto/argparse.rst:282 -#: ../../howto/argparse.rst:398 ../../howto/argparse.rst:432 +#: ../../howto/argparse.rst:234 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"--verbosity\", help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"if args.verbosity:\n" +" print(\"verbosity turned on\")" +msgstr "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"--verbosity\", help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"if args.verbosity:\n" +" print(\"verbosity turned on\")" + +#: ../../howto/argparse.rst:241 ../../howto/argparse.rst:287 +#: ../../howto/argparse.rst:403 ../../howto/argparse.rst:437 msgid "And the output:" msgstr "E a saída:" -#: ../../howto/argparse.rst:256 +#: ../../howto/argparse.rst:243 +msgid "" +"$ python prog.py --verbosity 1\n" +"verbosity turned on\n" +"$ python prog.py\n" +"$ python prog.py --help\n" +"usage: prog.py [-h] [--verbosity VERBOSITY]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --verbosity VERBOSITY\n" +" increase output verbosity\n" +"$ python prog.py --verbosity\n" +"usage: prog.py [-h] [--verbosity VERBOSITY]\n" +"prog.py: error: argument --verbosity: expected one argument" +msgstr "" +"$ python prog.py --verbosity 1\n" +"verbosity turned on\n" +"$ python prog.py\n" +"$ python prog.py --help\n" +"usage: prog.py [-h] [--verbosity VERBOSITY]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --verbosity VERBOSITY\n" +" increase output verbosity\n" +"$ python prog.py --verbosity\n" +"usage: prog.py [-h] [--verbosity VERBOSITY]\n" +"prog.py: error: argument --verbosity: expected one argument" + +#: ../../howto/argparse.rst:261 msgid "" "The program is written so as to display something when ``--verbosity`` is " "specified and display nothing when not." @@ -289,7 +560,7 @@ msgstr "" "O programa é escrito de forma a exibir algo quando ``--verbosity`` é " "especificado e não exibir nada quando não for." -#: ../../howto/argparse.rst:259 +#: ../../howto/argparse.rst:264 msgid "" "To show that the option is actually optional, there is no error when running " "the program without it. Note that by default, if an optional argument isn't " @@ -303,11 +574,11 @@ msgstr "" "como valor, razão pela qual falha no teste de verdade da instrução :keyword:" "`if`." -#: ../../howto/argparse.rst:265 +#: ../../howto/argparse.rst:270 msgid "The help message is a bit different." msgstr "A mensagem de ajuda é um pouco diferente." -#: ../../howto/argparse.rst:267 +#: ../../howto/argparse.rst:272 msgid "" "When using the ``--verbosity`` option, one must also specify some value, any " "value." @@ -315,7 +586,7 @@ msgstr "" "Ao usar a opção ``--verbosity``, deve-se também especificar algum valor, " "qualquer valor." -#: ../../howto/argparse.rst:270 +#: ../../howto/argparse.rst:275 msgid "" "The above example accepts arbitrary integer values for ``--verbosity``, but " "for our simple program, only two values are actually useful, ``True`` or " @@ -325,7 +596,51 @@ msgstr "" "mas para nosso programa simples, apenas dois valores são realmente úteis, " "``True`` ou ``False``. Vamos modificar o código de acordo::" -#: ../../howto/argparse.rst:300 +#: ../../howto/argparse.rst:279 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"--verbose\", help=\"increase output verbosity\",\n" +" action=\"store_true\")\n" +"args = parser.parse_args()\n" +"if args.verbose:\n" +" print(\"verbosity turned on\")" +msgstr "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"--verbose\", help=\"increase output verbosity\",\n" +" action=\"store_true\")\n" +"args = parser.parse_args()\n" +"if args.verbose:\n" +" print(\"verbosity turned on\")" + +#: ../../howto/argparse.rst:289 +msgid "" +"$ python prog.py --verbose\n" +"verbosity turned on\n" +"$ python prog.py --verbose 1\n" +"usage: prog.py [-h] [--verbose]\n" +"prog.py: error: unrecognized arguments: 1\n" +"$ python prog.py --help\n" +"usage: prog.py [-h] [--verbose]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --verbose increase output verbosity" +msgstr "" +"$ python prog.py --verbose\n" +"verbosity turned on\n" +"$ python prog.py --verbose 1\n" +"usage: prog.py [-h] [--verbose]\n" +"prog.py: error: unrecognized arguments: 1\n" +"$ python prog.py --help\n" +"usage: prog.py [-h] [--verbose]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --verbose increase output verbosity" + +#: ../../howto/argparse.rst:305 msgid "" "The option is now more of a flag than something that requires a value. We " "even changed the name of the option to match that idea. Note that we now " @@ -340,7 +655,7 @@ msgstr "" "o valor ``True`` para ``args.verbose``. Não especificá-la implica em " "``False``." -#: ../../howto/argparse.rst:307 +#: ../../howto/argparse.rst:312 msgid "" "It complains when you specify a value, in true spirit of what flags actually " "are." @@ -348,15 +663,15 @@ msgstr "" "Ele reclama quando você especifica um valor, no verdadeiro espírito do que " "os sinalizadores realmente são." -#: ../../howto/argparse.rst:310 +#: ../../howto/argparse.rst:315 msgid "Notice the different help text." msgstr "Observe o texto de ajuda diferente." -#: ../../howto/argparse.rst:314 +#: ../../howto/argparse.rst:319 msgid "Short options" msgstr "Opções curtas" -#: ../../howto/argparse.rst:316 +#: ../../howto/argparse.rst:321 msgid "" "If you are familiar with command line usage, you will notice that I haven't " "yet touched on the topic of short versions of the options. It's quite " @@ -365,35 +680,125 @@ msgstr "" "Se você estiver familiarizado com o uso da linha de comando, notará que " "ainda não toquei no tópico das versões curtas das opções. É bem simples::" -#: ../../howto/argparse.rst:328 +#: ../../howto/argparse.rst:325 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"-v\", \"--verbose\", help=\"increase output " +"verbosity\",\n" +" action=\"store_true\")\n" +"args = parser.parse_args()\n" +"if args.verbose:\n" +" print(\"verbosity turned on\")" +msgstr "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"-v\", \"--verbose\", help=\"increase output " +"verbosity\",\n" +" action=\"store_true\")\n" +"args = parser.parse_args()\n" +"if args.verbose:\n" +" print(\"verbosity turned on\")" + +#: ../../howto/argparse.rst:333 msgid "And here goes:" msgstr "E aqui vai:" -#: ../../howto/argparse.rst:341 +#: ../../howto/argparse.rst:335 +msgid "" +"$ python prog.py -v\n" +"verbosity turned on\n" +"$ python prog.py --help\n" +"usage: prog.py [-h] [-v]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -v, --verbose increase output verbosity" +msgstr "" +"$ python prog.py -v\n" +"verbosity turned on\n" +"$ python prog.py --help\n" +"usage: prog.py [-h] [-v]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -v, --verbose increase output verbosity" + +#: ../../howto/argparse.rst:346 msgid "Note that the new ability is also reflected in the help text." msgstr "Observe que a nova habilidade também é refletida no texto de ajuda." -#: ../../howto/argparse.rst:345 +#: ../../howto/argparse.rst:350 msgid "Combining Positional and Optional arguments" msgstr "Combinando argumentos posicionais e opcionais" -#: ../../howto/argparse.rst:347 +#: ../../howto/argparse.rst:352 msgid "Our program keeps growing in complexity::" msgstr "Nosso programa continua crescendo em complexidade::" -#: ../../howto/argparse.rst:362 +#: ../../howto/argparse.rst:354 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display a square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\",\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"if args.verbose:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"else:\n" +" print(answer)" +msgstr "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display a square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\",\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"if args.verbose:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"else:\n" +" print(answer)" + +#: ../../howto/argparse.rst:367 msgid "And now the output:" msgstr "E agora a saída:" -#: ../../howto/argparse.rst:376 +#: ../../howto/argparse.rst:369 +msgid "" +"$ python prog.py\n" +"usage: prog.py [-h] [-v] square\n" +"prog.py: error: the following arguments are required: square\n" +"$ python prog.py 4\n" +"16\n" +"$ python prog.py 4 --verbose\n" +"the square of 4 equals 16\n" +"$ python prog.py --verbose 4\n" +"the square of 4 equals 16" +msgstr "" +"$ python prog.py\n" +"usage: prog.py [-h] [-v] square\n" +"prog.py: error: the following arguments are required: square\n" +"$ python prog.py 4\n" +"16\n" +"$ python prog.py 4 --verbose\n" +"the square of 4 equals 16\n" +"$ python prog.py --verbose 4\n" +"the square of 4 equals 16" + +#: ../../howto/argparse.rst:381 msgid "We've brought back a positional argument, hence the complaint." msgstr "Trouxemos de volta um argumento posicional, daí a reclamação." -#: ../../howto/argparse.rst:378 +#: ../../howto/argparse.rst:383 msgid "Note that the order does not matter." msgstr "Observe que a ordem não importa." -#: ../../howto/argparse.rst:380 +#: ../../howto/argparse.rst:385 msgid "" "How about we give this program of ours back the ability to have multiple " "verbosity values, and actually get to use them::" @@ -401,7 +806,65 @@ msgstr "" "Que tal devolvermos a este nosso programa a capacidade de ter vários valores " "de verbosidade e realmente usá-los::" -#: ../../howto/argparse.rst:414 +#: ../../howto/argparse.rst:388 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display a square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", type=int,\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"if args.verbosity == 2:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"elif args.verbosity == 1:\n" +" print(f\"{args.square}^2 == {answer}\")\n" +"else:\n" +" print(answer)" +msgstr "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display a square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", type=int,\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"if args.verbosity == 2:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"elif args.verbosity == 1:\n" +" print(f\"{args.square}^2 == {answer}\")\n" +"else:\n" +" print(answer)" + +#: ../../howto/argparse.rst:405 +msgid "" +"$ python prog.py 4\n" +"16\n" +"$ python prog.py 4 -v\n" +"usage: prog.py [-h] [-v VERBOSITY] square\n" +"prog.py: error: argument -v/--verbosity: expected one argument\n" +"$ python prog.py 4 -v 1\n" +"4^2 == 16\n" +"$ python prog.py 4 -v 2\n" +"the square of 4 equals 16\n" +"$ python prog.py 4 -v 3\n" +"16" +msgstr "" +"$ python prog.py 4\n" +"16\n" +"$ python prog.py 4 -v\n" +"usage: prog.py [-h] [-v VERBOSITY] square\n" +"prog.py: error: argument -v/--verbosity: expected one argument\n" +"$ python prog.py 4 -v 1\n" +"4^2 == 16\n" +"$ python prog.py 4 -v 2\n" +"the square of 4 equals 16\n" +"$ python prog.py 4 -v 3\n" +"16" + +#: ../../howto/argparse.rst:419 msgid "" "These all look good except the last one, which exposes a bug in our program. " "Let's fix it by restricting the values the ``--verbosity`` option can " @@ -411,7 +874,71 @@ msgstr "" "programa. Vamos corrigi-lo restringindo os valores que a opção ``--" "verbosity`` pode aceitar::" -#: ../../howto/argparse.rst:450 +#: ../../howto/argparse.rst:422 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display a square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", type=int, choices=[0, 1, 2],\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"if args.verbosity == 2:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"elif args.verbosity == 1:\n" +" print(f\"{args.square}^2 == {answer}\")\n" +"else:\n" +" print(answer)" +msgstr "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display a square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", type=int, choices=[0, 1, 2],\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"if args.verbosity == 2:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"elif args.verbosity == 1:\n" +" print(f\"{args.square}^2 == {answer}\")\n" +"else:\n" +" print(answer)" + +#: ../../howto/argparse.rst:439 +msgid "" +"$ python prog.py 4 -v 3\n" +"usage: prog.py [-h] [-v {0,1,2}] square\n" +"prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, " +"1, 2)\n" +"$ python prog.py 4 -h\n" +"usage: prog.py [-h] [-v {0,1,2}] square\n" +"\n" +"positional arguments:\n" +" square display a square of a given number\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -v, --verbosity {0,1,2}\n" +" increase output verbosity" +msgstr "" +"$ python prog.py 4 -v 3\n" +"usage: prog.py [-h] [-v {0,1,2}] square\n" +"prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, " +"1, 2)\n" +"$ python prog.py 4 -h\n" +"usage: prog.py [-h] [-v {0,1,2}] square\n" +"\n" +"positional arguments:\n" +" square display a square of a given number\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -v, --verbosity {0,1,2}\n" +" increase output verbosity" + +#: ../../howto/argparse.rst:455 msgid "" "Note that the change also reflects both in the error message as well as the " "help string." @@ -419,7 +946,7 @@ msgstr "" "Observe que a alteração também reflete tanto na mensagem de erro quanto na " "string de ajuda." -#: ../../howto/argparse.rst:453 +#: ../../howto/argparse.rst:458 msgid "" "Now, let's use a different approach of playing with verbosity, which is " "pretty common. It also matches the way the CPython executable handles its " @@ -430,7 +957,39 @@ msgstr "" "CPython trata seu próprio argumento de verbosidade (verifique a saída de " "``python --help``)::" -#: ../../howto/argparse.rst:472 +#: ../../howto/argparse.rst:462 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display the square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", action=\"count\",\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"if args.verbosity == 2:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"elif args.verbosity == 1:\n" +" print(f\"{args.square}^2 == {answer}\")\n" +"else:\n" +" print(answer)" +msgstr "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display the square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", action=\"count\",\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"if args.verbosity == 2:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"elif args.verbosity == 1:\n" +" print(f\"{args.square}^2 == {answer}\")\n" +"else:\n" +" print(answer)" + +#: ../../howto/argparse.rst:477 msgid "" "We have introduced another action, \"count\", to count the number of " "occurrences of specific options." @@ -438,7 +997,55 @@ msgstr "" "Introduzimos outra ação, \"contar\", para contar o número de ocorrências de " "opções específicas." -#: ../../howto/argparse.rst:501 +#: ../../howto/argparse.rst:481 +msgid "" +"$ python prog.py 4\n" +"16\n" +"$ python prog.py 4 -v\n" +"4^2 == 16\n" +"$ python prog.py 4 -vv\n" +"the square of 4 equals 16\n" +"$ python prog.py 4 --verbosity --verbosity\n" +"the square of 4 equals 16\n" +"$ python prog.py 4 -v 1\n" +"usage: prog.py [-h] [-v] square\n" +"prog.py: error: unrecognized arguments: 1\n" +"$ python prog.py 4 -h\n" +"usage: prog.py [-h] [-v] square\n" +"\n" +"positional arguments:\n" +" square display a square of a given number\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -v, --verbosity increase output verbosity\n" +"$ python prog.py 4 -vvv\n" +"16" +msgstr "" +"$ python prog.py 4\n" +"16\n" +"$ python prog.py 4 -v\n" +"4^2 == 16\n" +"$ python prog.py 4 -vv\n" +"the square of 4 equals 16\n" +"$ python prog.py 4 --verbosity --verbosity\n" +"the square of 4 equals 16\n" +"$ python prog.py 4 -v 1\n" +"usage: prog.py [-h] [-v] square\n" +"prog.py: error: unrecognized arguments: 1\n" +"$ python prog.py 4 -h\n" +"usage: prog.py [-h] [-v] square\n" +"\n" +"positional arguments:\n" +" square display a square of a given number\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -v, --verbosity increase output verbosity\n" +"$ python prog.py 4 -vvv\n" +"16" + +#: ../../howto/argparse.rst:506 msgid "" "Yes, it's now more of a flag (similar to ``action=\"store_true\"``) in the " "previous version of our script. That should explain the complaint." @@ -446,11 +1053,11 @@ msgstr "" "Sim, agora é mais um sinalizador (semelhante a ``action=\"store_true\"``) na " "versão anterior do nosso script. Isso deve explicar a reclamação." -#: ../../howto/argparse.rst:504 +#: ../../howto/argparse.rst:509 msgid "It also behaves similar to \"store_true\" action." msgstr "Ele também se comporta de maneira semelhante à ação \"store_true\"." -#: ../../howto/argparse.rst:506 +#: ../../howto/argparse.rst:511 msgid "" "Now here's a demonstration of what the \"count\" action gives. You've " "probably seen this sort of usage before." @@ -458,7 +1065,7 @@ msgstr "" "Agora aqui está uma demonstração do que a ação \"contar\" oferece. Você " "provavelmente já viu esse tipo de uso antes." -#: ../../howto/argparse.rst:509 +#: ../../howto/argparse.rst:514 msgid "" "And if you don't specify the ``-v`` flag, that flag is considered to have " "``None`` value." @@ -466,7 +1073,7 @@ msgstr "" "E se você não especificar o sinalizador ``-v``, esse sinalizador será " "considerado como tendo valor ``None``." -#: ../../howto/argparse.rst:512 +#: ../../howto/argparse.rst:517 msgid "" "As should be expected, specifying the long form of the flag, we should get " "the same output." @@ -474,7 +1081,7 @@ msgstr "" "Como deve ser esperado, especificando a forma longa do sinalizador, devemos " "obter a mesma saída." -#: ../../howto/argparse.rst:515 +#: ../../howto/argparse.rst:520 msgid "" "Sadly, our help output isn't very informative on the new ability our script " "has acquired, but that can always be fixed by improving the documentation " @@ -485,19 +1092,77 @@ msgstr "" "melhorando a documentação de nosso script (por exemplo, através do argumento " "nomeado ``help``)." -#: ../../howto/argparse.rst:519 +#: ../../howto/argparse.rst:524 msgid "That last output exposes a bug in our program." msgstr "Essa última saída expõe um bug em nosso programa." -#: ../../howto/argparse.rst:522 +#: ../../howto/argparse.rst:527 msgid "Let's fix::" msgstr "Vamos corrigir::" -#: ../../howto/argparse.rst:541 +#: ../../howto/argparse.rst:529 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display a square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", action=\"count\",\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"\n" +"# bugfix: replace == with >=\n" +"if args.verbosity >= 2:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"elif args.verbosity >= 1:\n" +" print(f\"{args.square}^2 == {answer}\")\n" +"else:\n" +" print(answer)" +msgstr "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display a square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", action=\"count\",\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"\n" +"# bugfix: replace == with >=\n" +"if args.verbosity >= 2:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"elif args.verbosity >= 1:\n" +" print(f\"{args.square}^2 == {answer}\")\n" +"else:\n" +" print(answer)" + +#: ../../howto/argparse.rst:546 msgid "And this is what it gives:" msgstr "E isso aqui é o mesmo retorna:" -#: ../../howto/argparse.rst:556 +#: ../../howto/argparse.rst:548 +msgid "" +"$ python prog.py 4 -vvv\n" +"the square of 4 equals 16\n" +"$ python prog.py 4 -vvvv\n" +"the square of 4 equals 16\n" +"$ python prog.py 4\n" +"Traceback (most recent call last):\n" +" File \"prog.py\", line 11, in \n" +" if args.verbosity >= 2:\n" +"TypeError: '>=' not supported between instances of 'NoneType' and 'int'" +msgstr "" +"$ python prog.py 4 -vvv\n" +"the square of 4 equals 16\n" +"$ python prog.py 4 -vvvv\n" +"the square of 4 equals 16\n" +"$ python prog.py 4\n" +"Traceback (most recent call last):\n" +" File \"prog.py\", line 11, in \n" +" if args.verbosity >= 2:\n" +"TypeError: '>=' not supported between instances of 'NoneType' and 'int'" + +#: ../../howto/argparse.rst:561 msgid "" "First output went well, and fixes the bug we had before. That is, we want " "any value >= 2 to be as verbose as possible." @@ -505,15 +1170,47 @@ msgstr "" "A primeira saída correu bem e corrige o bug que tínhamos antes. Ou seja, " "queremos que qualquer valor >= 2 seja o mais detalhado possível." -#: ../../howto/argparse.rst:559 +#: ../../howto/argparse.rst:564 msgid "Third output not so good." msgstr "A terceira saída não está tão boa." -#: ../../howto/argparse.rst:561 +#: ../../howto/argparse.rst:566 msgid "Let's fix that bug::" msgstr "Vamos corrigir esse bug::" -#: ../../howto/argparse.rst:578 +#: ../../howto/argparse.rst:568 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display a square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", action=\"count\", default=0,\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"if args.verbosity >= 2:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"elif args.verbosity >= 1:\n" +" print(f\"{args.square}^2 == {answer}\")\n" +"else:\n" +" print(answer)" +msgstr "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display a square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", action=\"count\", default=0,\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"if args.verbosity >= 2:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"elif args.verbosity >= 1:\n" +" print(f\"{args.square}^2 == {answer}\")\n" +"else:\n" +" print(answer)" + +#: ../../howto/argparse.rst:583 msgid "" "We've just introduced yet another keyword, ``default``. We've set it to " "``0`` in order to make it comparable to the other int values. Remember that " @@ -527,12 +1224,20 @@ msgstr "" "obtém o valor ``None``, e isso não pode ser comparado a um valor int (daí a " "exceção :exc:`TypeError`)." -#: ../../howto/argparse.rst:585 +#: ../../howto/argparse.rst:590 msgid "And:" msgstr "E:" #: ../../howto/argparse.rst:592 msgid "" +"$ python prog.py 4\n" +"16" +msgstr "" +"$ python prog.py 4\n" +"16" + +#: ../../howto/argparse.rst:597 +msgid "" "You can go quite far just with what we've learned so far, and we have only " "scratched the surface. The :mod:`argparse` module is very powerful, and " "we'll explore a bit more of it before we end this tutorial." @@ -541,22 +1246,87 @@ msgstr "" "arranhamos a superfície. O módulo :mod:`argparse` é muito poderoso, e vamos " "explorar um pouco mais antes de terminar este tutorial." -#: ../../howto/argparse.rst:599 +#: ../../howto/argparse.rst:604 msgid "Getting a little more advanced" msgstr "Avançando um pouco mais" -#: ../../howto/argparse.rst:601 +#: ../../howto/argparse.rst:606 msgid "" "What if we wanted to expand our tiny program to perform other powers, not " "just squares::" msgstr "" "E se quiséssemos expandir nosso pequeno programa, ampliando seu potencial::" -#: ../../howto/argparse.rst:618 ../../howto/argparse.rst:656 +#: ../../howto/argparse.rst:609 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"x\", type=int, help=\"the base\")\n" +"parser.add_argument(\"y\", type=int, help=\"the exponent\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", action=\"count\", default=0)\n" +"args = parser.parse_args()\n" +"answer = args.x**args.y\n" +"if args.verbosity >= 2:\n" +" print(f\"{args.x} to the power {args.y} equals {answer}\")\n" +"elif args.verbosity >= 1:\n" +" print(f\"{args.x}^{args.y} == {answer}\")\n" +"else:\n" +" print(answer)" +msgstr "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"x\", type=int, help=\"the base\")\n" +"parser.add_argument(\"y\", type=int, help=\"the exponent\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", action=\"count\", default=0)\n" +"args = parser.parse_args()\n" +"answer = args.x**args.y\n" +"if args.verbosity >= 2:\n" +" print(f\"{args.x} to the power {args.y} equals {answer}\")\n" +"elif args.verbosity >= 1:\n" +" print(f\"{args.x}^{args.y} == {answer}\")\n" +"else:\n" +" print(answer)" + +#: ../../howto/argparse.rst:623 ../../howto/argparse.rst:661 +#: ../../howto/argparse.rst:877 msgid "Output:" msgstr "Saída:" -#: ../../howto/argparse.rst:639 +#: ../../howto/argparse.rst:625 +msgid "" +"$ python prog.py\n" +"usage: prog.py [-h] [-v] x y\n" +"prog.py: error: the following arguments are required: x, y\n" +"$ python prog.py -h\n" +"usage: prog.py [-h] [-v] x y\n" +"\n" +"positional arguments:\n" +" x the base\n" +" y the exponent\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -v, --verbosity\n" +"$ python prog.py 4 2 -v\n" +"4^2 == 16" +msgstr "" +"$ python prog.py\n" +"usage: prog.py [-h] [-v] x y\n" +"prog.py: error: the following arguments are required: x, y\n" +"$ python prog.py -h\n" +"usage: prog.py [-h] [-v] x y\n" +"\n" +"positional arguments:\n" +" x the base\n" +" y the exponent\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -v, --verbosity\n" +"$ python prog.py 4 2 -v\n" +"4^2 == 16" + +#: ../../howto/argparse.rst:644 msgid "" "Notice that so far we've been using verbosity level to *change* the text " "that gets displayed. The following example instead uses verbosity level to " @@ -566,11 +1336,57 @@ msgstr "" "texto que é exibido. O exemplo a seguir usa o nível de verbosidade para " "exibir *mais* texto::" -#: ../../howto/argparse.rst:672 +#: ../../howto/argparse.rst:648 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"x\", type=int, help=\"the base\")\n" +"parser.add_argument(\"y\", type=int, help=\"the exponent\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", action=\"count\", default=0)\n" +"args = parser.parse_args()\n" +"answer = args.x**args.y\n" +"if args.verbosity >= 2:\n" +" print(f\"Running '{__file__}'\")\n" +"if args.verbosity >= 1:\n" +" print(f\"{args.x}^{args.y} == \", end=\"\")\n" +"print(answer)" +msgstr "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"x\", type=int, help=\"the base\")\n" +"parser.add_argument(\"y\", type=int, help=\"the exponent\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", action=\"count\", default=0)\n" +"args = parser.parse_args()\n" +"answer = args.x**args.y\n" +"if args.verbosity >= 2:\n" +" print(f\"Running '{__file__}'\")\n" +"if args.verbosity >= 1:\n" +" print(f\"{args.x}^{args.y} == \", end=\"\")\n" +"print(answer)" + +#: ../../howto/argparse.rst:663 +msgid "" +"$ python prog.py 4 2\n" +"16\n" +"$ python prog.py 4 2 -v\n" +"4^2 == 16\n" +"$ python prog.py 4 2 -vv\n" +"Running 'prog.py'\n" +"4^2 == 16" +msgstr "" +"$ python prog.py 4 2\n" +"16\n" +"$ python prog.py 4 2 -v\n" +"4^2 == 16\n" +"$ python prog.py 4 2 -vv\n" +"Running 'prog.py'\n" +"4^2 == 16" + +#: ../../howto/argparse.rst:677 msgid "Specifying ambiguous arguments" msgstr "Especificando argumentos ambíguos" -#: ../../howto/argparse.rst:674 +#: ../../howto/argparse.rst:679 msgid "" "When there is ambiguity in deciding whether an argument is positional or for " "an argument, ``--`` can be used to tell :meth:`~ArgumentParser.parse_args` " @@ -580,11 +1396,51 @@ msgstr "" "argumento, ``--`` pode ser usado para dizer :meth:`~ArgumentParser." "parse_args` que tudo depois disso é um argumento posicional::" -#: ../../howto/argparse.rst:699 +#: ../../howto/argparse.rst:683 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-n', nargs='+')\n" +">>> parser.add_argument('args', nargs='*')\n" +"\n" +">>> # ambiguous, so parse_args assumes it's an option\n" +">>> parser.parse_args(['-f'])\n" +"usage: PROG [-h] [-n N [N ...]] [args ...]\n" +"PROG: error: unrecognized arguments: -f\n" +"\n" +">>> parser.parse_args(['--', '-f'])\n" +"Namespace(args=['-f'], n=None)\n" +"\n" +">>> # ambiguous, so the -n option greedily accepts arguments\n" +">>> parser.parse_args(['-n', '1', '2', '3'])\n" +"Namespace(args=[], n=['1', '2', '3'])\n" +"\n" +">>> parser.parse_args(['-n', '1', '--', '2', '3'])\n" +"Namespace(args=['2', '3'], n=['1'])" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-n', nargs='+')\n" +">>> parser.add_argument('args', nargs='*')\n" +"\n" +">>> # ambiguous, so parse_args assumes it's an option\n" +">>> parser.parse_args(['-f'])\n" +"usage: PROG [-h] [-n N [N ...]] [args ...]\n" +"PROG: error: unrecognized arguments: -f\n" +"\n" +">>> parser.parse_args(['--', '-f'])\n" +"Namespace(args=['-f'], n=None)\n" +"\n" +">>> # ambiguous, so the -n option greedily accepts arguments\n" +">>> parser.parse_args(['-n', '1', '2', '3'])\n" +"Namespace(args=[], n=['1', '2', '3'])\n" +"\n" +">>> parser.parse_args(['-n', '1', '--', '2', '3'])\n" +"Namespace(args=['2', '3'], n=['1'])" + +#: ../../howto/argparse.rst:704 msgid "Conflicting options" msgstr "Opções conflitantes" -#: ../../howto/argparse.rst:701 +#: ../../howto/argparse.rst:706 msgid "" "So far, we have been working with two methods of an :class:`argparse." "ArgumentParser` instance. Let's introduce a third one, :meth:" @@ -600,7 +1456,45 @@ msgstr "" "para que a nova funcionalidade faça mais sentido: vamos introduzir a opção " "``--quiet``, que será o oposto da opção ``--verbose``::" -#: ../../howto/argparse.rst:727 +#: ../../howto/argparse.rst:714 +msgid "" +"import argparse\n" +"\n" +"parser = argparse.ArgumentParser()\n" +"group = parser.add_mutually_exclusive_group()\n" +"group.add_argument(\"-v\", \"--verbose\", action=\"store_true\")\n" +"group.add_argument(\"-q\", \"--quiet\", action=\"store_true\")\n" +"parser.add_argument(\"x\", type=int, help=\"the base\")\n" +"parser.add_argument(\"y\", type=int, help=\"the exponent\")\n" +"args = parser.parse_args()\n" +"answer = args.x**args.y\n" +"\n" +"if args.quiet:\n" +" print(answer)\n" +"elif args.verbose:\n" +" print(f\"{args.x} to the power {args.y} equals {answer}\")\n" +"else:\n" +" print(f\"{args.x}^{args.y} == {answer}\")" +msgstr "" +"import argparse\n" +"\n" +"parser = argparse.ArgumentParser()\n" +"group = parser.add_mutually_exclusive_group()\n" +"group.add_argument(\"-v\", \"--verbose\", action=\"store_true\")\n" +"group.add_argument(\"-q\", \"--quiet\", action=\"store_true\")\n" +"parser.add_argument(\"x\", type=int, help=\"the base\")\n" +"parser.add_argument(\"y\", type=int, help=\"the exponent\")\n" +"args = parser.parse_args()\n" +"answer = args.x**args.y\n" +"\n" +"if args.quiet:\n" +" print(answer)\n" +"elif args.verbose:\n" +" print(f\"{args.x} to the power {args.y} equals {answer}\")\n" +"else:\n" +" print(f\"{args.x}^{args.y} == {answer}\")" + +#: ../../howto/argparse.rst:732 msgid "" "Our program is now simpler, and we've lost some functionality for the sake " "of demonstration. Anyways, here's the output:" @@ -608,7 +1502,35 @@ msgstr "" "Nosso programa agora está mais simples e perdemos algumas funcionalidades " "para demonstração. De qualquer forma, aqui está a saída:" -#: ../../howto/argparse.rst:745 +#: ../../howto/argparse.rst:735 +msgid "" +"$ python prog.py 4 2\n" +"4^2 == 16\n" +"$ python prog.py 4 2 -q\n" +"16\n" +"$ python prog.py 4 2 -v\n" +"4 to the power 2 equals 16\n" +"$ python prog.py 4 2 -vq\n" +"usage: prog.py [-h] [-v | -q] x y\n" +"prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose\n" +"$ python prog.py 4 2 -v --quiet\n" +"usage: prog.py [-h] [-v | -q] x y\n" +"prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose" +msgstr "" +"$ python prog.py 4 2\n" +"4^2 == 16\n" +"$ python prog.py 4 2 -q\n" +"16\n" +"$ python prog.py 4 2 -v\n" +"4 to the power 2 equals 16\n" +"$ python prog.py 4 2 -vq\n" +"usage: prog.py [-h] [-v | -q] x y\n" +"prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose\n" +"$ python prog.py 4 2 -v --quiet\n" +"usage: prog.py [-h] [-v | -q] x y\n" +"prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose" + +#: ../../howto/argparse.rst:750 msgid "" "That should be easy to follow. I've added that last output so you can see " "the sort of flexibility you get, i.e. mixing long form options with short " @@ -618,7 +1540,7 @@ msgstr "" "possa ver o tipo de flexibilidade que obtém, ou seja, misturar opções de " "formato longo com formatos curtos." -#: ../../howto/argparse.rst:749 +#: ../../howto/argparse.rst:754 msgid "" "Before we conclude, you probably want to tell your users the main purpose of " "your program, just in case they don't know::" @@ -626,7 +1548,47 @@ msgstr "" "Antes de concluirmos, você provavelmente quer dizer aos seus usuários o " "propósito principal do seu programa, caso eles não saibam::" -#: ../../howto/argparse.rst:770 +#: ../../howto/argparse.rst:757 +msgid "" +"import argparse\n" +"\n" +"parser = argparse.ArgumentParser(description=\"calculate X to the power of " +"Y\")\n" +"group = parser.add_mutually_exclusive_group()\n" +"group.add_argument(\"-v\", \"--verbose\", action=\"store_true\")\n" +"group.add_argument(\"-q\", \"--quiet\", action=\"store_true\")\n" +"parser.add_argument(\"x\", type=int, help=\"the base\")\n" +"parser.add_argument(\"y\", type=int, help=\"the exponent\")\n" +"args = parser.parse_args()\n" +"answer = args.x**args.y\n" +"\n" +"if args.quiet:\n" +" print(answer)\n" +"elif args.verbose:\n" +" print(f\"{args.x} to the power {args.y} equals {answer}\")\n" +"else:\n" +" print(f\"{args.x}^{args.y} == {answer}\")" +msgstr "" +"import argparse\n" +"\n" +"parser = argparse.ArgumentParser(description=\"calculate X to the power of " +"Y\")\n" +"group = parser.add_mutually_exclusive_group()\n" +"group.add_argument(\"-v\", \"--verbose\", action=\"store_true\")\n" +"group.add_argument(\"-q\", \"--quiet\", action=\"store_true\")\n" +"parser.add_argument(\"x\", type=int, help=\"the base\")\n" +"parser.add_argument(\"y\", type=int, help=\"the exponent\")\n" +"args = parser.parse_args()\n" +"answer = args.x**args.y\n" +"\n" +"if args.quiet:\n" +" print(answer)\n" +"elif args.verbose:\n" +" print(f\"{args.x} to the power {args.y} equals {answer}\")\n" +"else:\n" +" print(f\"{args.x}^{args.y} == {answer}\")" + +#: ../../howto/argparse.rst:775 msgid "" "Note that slight difference in the usage text. Note the ``[-v | -q]``, which " "tells us that we can either use ``-v`` or ``-q``, but not both at the same " @@ -635,11 +1597,41 @@ msgstr "" "Observe essa pequena diferença no texto de uso. Observe o ``[-v | -q]``, que " "nos diz que podemos usar ``-v`` ou ``-q``, mas não ambos ao mesmo tempo:" -#: ../../howto/argparse.rst:792 +#: ../../howto/argparse.rst:779 ../../howto/argparse.rst:806 +msgid "" +"$ python prog.py --help\n" +"usage: prog.py [-h] [-v | -q] x y\n" +"\n" +"calculate X to the power of Y\n" +"\n" +"positional arguments:\n" +" x the base\n" +" y the exponent\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -v, --verbose\n" +" -q, --quiet" +msgstr "" +"$ python prog.py --help\n" +"usage: prog.py [-h] [-v | -q] x y\n" +"\n" +"calculate X to the power of Y\n" +"\n" +"positional arguments:\n" +" x the base\n" +" y the exponent\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -v, --verbose\n" +" -q, --quiet" + +#: ../../howto/argparse.rst:797 msgid "How to translate the argparse output" msgstr "Como traduzir a saída do argparse" -#: ../../howto/argparse.rst:794 +#: ../../howto/argparse.rst:799 msgid "" "The output of the :mod:`argparse` module such as its help text and error " "messages are all made translatable using the :mod:`gettext` module. This " @@ -651,11 +1643,11 @@ msgstr "" "os aplicativos localizem facilmente as mensagens produzidas por :mod:" "`argparse`. Veja também :ref:`i18n-howto`." -#: ../../howto/argparse.rst:799 +#: ../../howto/argparse.rst:804 msgid "For instance, in this :mod:`argparse` output:" msgstr "Por exemplo, nesta saída :mod:`argparse`:" -#: ../../howto/argparse.rst:817 +#: ../../howto/argparse.rst:822 msgid "" "The strings ``usage:``, ``positional arguments:``, ``options:`` and ``show " "this help message and exit`` are all translatable." @@ -663,7 +1655,7 @@ msgstr "" "As strings ``usage:``, ``positional arguments:``, ``options:`` e ``show this " "help message and exit`` são todos traduzíveis." -#: ../../howto/argparse.rst:820 +#: ../../howto/argparse.rst:825 msgid "" "In order to translate these strings, they must first be extracted into a ``." "po`` file. For example, using `Babel `__, run this " @@ -673,7 +1665,11 @@ msgstr "" "``.po``. Por exemplo, usando `Babel `__, execute " "este comando:" -#: ../../howto/argparse.rst:828 +#: ../../howto/argparse.rst:829 +msgid "$ pybabel extract -o messages.po /usr/lib/python3.12/argparse.py" +msgstr "$ pybabel extract -o messages.po /usr/lib/python3.12/argparse.py" + +#: ../../howto/argparse.rst:833 msgid "" "This command will extract all translatable strings from the :mod:`argparse` " "module and output them into a file named ``messages.po``. This command " @@ -683,7 +1679,7 @@ msgstr "" "e as enviará para um arquivo chamado ``messages.po``. Este comando presume " "que sua instalação do Python está em ``/usr/lib``." -#: ../../howto/argparse.rst:832 +#: ../../howto/argparse.rst:837 msgid "" "You can find out the location of the :mod:`argparse` module on your system " "using this script::" @@ -691,7 +1687,15 @@ msgstr "" "Você pode descobrir a localização do módulo :mod:`argparse` em seu sistema " "usando este script::" -#: ../../howto/argparse.rst:838 +#: ../../howto/argparse.rst:840 +msgid "" +"import argparse\n" +"print(argparse.__file__)" +msgstr "" +"import argparse\n" +"print(argparse.__file__)" + +#: ../../howto/argparse.rst:843 msgid "" "Once the messages in the ``.po`` file are translated and the translations " "are installed using :mod:`gettext`, :mod:`argparse` will be able to display " @@ -701,7 +1705,7 @@ msgstr "" "instaladas usando :mod:`gettext`, :mod:`argparse` será capaz de exibir as " "mensagens traduzidas." -#: ../../howto/argparse.rst:842 +#: ../../howto/argparse.rst:847 msgid "" "To translate your own strings in the :mod:`argparse` output, use :mod:" "`gettext`." @@ -709,11 +1713,116 @@ msgstr "" "Para traduzir suas próprias strings na saída :mod:`argparse`, use :mod:" "`gettext`." -#: ../../howto/argparse.rst:845 +#: ../../howto/argparse.rst:850 +msgid "Custom type converters" +msgstr "Conversores de tipo personalizados" + +#: ../../howto/argparse.rst:852 +msgid "" +"The :mod:`argparse` module allows you to specify custom type converters for " +"your command-line arguments. This allows you to modify user input before " +"it's stored in the :class:`argparse.Namespace`. This can be useful when you " +"need to pre-process the input before it is used in your program." +msgstr "" +"O módulo :mod:`argparse` permite que você especifique conversores de tipo " +"personalizados para seus argumentos de linha de comando. Isso permite " +"modificar a entrada de usuário antes de armazená-la na :class:`argparse." +"Namespace`. Isso pode ser útil quando você precisa pré-processar a entrada " +"antes dela ser usada em seu programa." + +#: ../../howto/argparse.rst:857 +msgid "" +"When using a custom type converter, you can use any callable that takes a " +"single string argument (the argument value) and returns the converted value. " +"However, if you need to handle more complex scenarios, you can use a custom " +"action class with the **action** parameter instead." +msgstr "" +"Ao usar um conversor de tipo personalizado, você pode usar qualquer chamável " +"que recebe uma única string como argumento (o valor do argumento) e retorna " +"o valor convertido. Porém, se você precisa tratar de cenários mais " +"complexos, você pode usar uma classe de ação personalizada com o parâmetro " +"**action**." + +#: ../../howto/argparse.rst:862 +msgid "" +"For example, let's say you want to handle arguments with different prefixes " +"and process them accordingly::" +msgstr "" +"Por exemplo, digamos que vcoê deseja tratar de argumentos com diferentes " +"prefixos e processá-los adequadamente::" + +#: ../../howto/argparse.rst:865 +msgid "" +"import argparse\n" +"\n" +"parser = argparse.ArgumentParser(prefix_chars='-+')\n" +"\n" +"parser.add_argument('-a', metavar='', action='append',\n" +" type=lambda x: ('-', x))\n" +"parser.add_argument('+a', metavar='', action='append',\n" +" type=lambda x: ('+', x))\n" +"\n" +"args = parser.parse_args()\n" +"print(args)" +msgstr "" +"import argparse\n" +"\n" +"parser = argparse.ArgumentParser(prefix_chars='-+')\n" +"\n" +"parser.add_argument('-a', metavar='', action='append',\n" +" type=lambda x: ('-', x))\n" +"parser.add_argument('+a', metavar='', action='append',\n" +" type=lambda x: ('+', x))\n" +"\n" +"args = parser.parse_args()\n" +"print(args)" + +#: ../../howto/argparse.rst:879 +msgid "" +"$ python prog.py -a value1 +a value2\n" +"Namespace(a=[('-', 'value1'), ('+', 'value2')])" +msgstr "" +"$ python prog.py -a valor1 +a valor2\n" +"Namespace(a=[('-', 'valor1'), ('+', 'valor2')])" + +#: ../../howto/argparse.rst:884 +msgid "In this example, we:" +msgstr "Neste exemplos, nós:" + +#: ../../howto/argparse.rst:886 +msgid "" +"Created a parser with custom prefix characters using the ``prefix_chars`` " +"parameter." +msgstr "" +"Criamos um analisador sintático com caracteres de prefixo personalizado " +"usando parâmetro ``prefix_chars``." + +#: ../../howto/argparse.rst:889 +msgid "" +"Defined two arguments, ``-a`` and ``+a``, which used the ``type`` parameter " +"to create custom type converters to store the value in a tuple with the " +"prefix." +msgstr "" +"Definimos dois argumentos, ``-a`` e ``+a``, que usaram o parâmetro ``type`` " +"para criar conversores de tipo personalizados para armazenar o valor em uma " +"tupla com o prefixo." + +#: ../../howto/argparse.rst:892 +msgid "" +"Without the custom type converters, the arguments would have treated the ``-" +"a`` and ``+a`` as the same argument, which would have been undesirable. By " +"using custom type converters, we were able to differentiate between the two " +"arguments." +msgstr "" +"Sem os conversores de tipo personalizados, os argumentos tratariam ``-a`` e " +"``+a`` como o mesmo argumento, o que não era o desejado. Ao usar conversores " +"de tipo personalizados, conseguimos diferenciar entre dois argumentos." + +#: ../../howto/argparse.rst:897 msgid "Conclusion" msgstr "Conclusão" -#: ../../howto/argparse.rst:847 +#: ../../howto/argparse.rst:899 msgid "" "The :mod:`argparse` module offers a lot more than shown here. Its docs are " "quite detailed and thorough, and full of examples. Having gone through this " diff --git a/howto/clinic.po b/howto/clinic.po index 1c81718cc..006af2e19 100644 --- a/howto/clinic.po +++ b/howto/clinic.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Vitor Buxbaum Orlandi, 2024 -# Claudio Rogerio Carvalho Filho , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Claudio Rogerio Carvalho Filho , " -"2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/howto/cporting.po b/howto/cporting.po index d1d510943..0e0f513a1 100644 --- a/howto/cporting.po +++ b/howto/cporting.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:52+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/howto/curses.po b/howto/curses.po index d38411bc3..9cbc088d8 100644 --- a/howto/curses.po +++ b/howto/curses.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Marciel Leal , 2021 -# Aline Balogh , 2021 -# 82596da39877db21448335599650eb68_ac09920 <1d2e18e2f37f0ba6c4f06b239e0670bd_848591>, 2021 -# Danilo Lima , 2021 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:53+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-04-11 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -165,10 +159,10 @@ msgid "" "that, see the Python library guide's section on ncurses, and the C manual " "pages for ncurses. It will, however, give you the basic ideas." msgstr "" -"Este HOWTO é uma introdução à escrita de programas em modo texto com curses " -"e Python. Isto não pretende ser um guia completo da PAI curses; para isso, " -"veja a seção ncurses no guia da biblioteca Python, e o manual de ncurses. " -"Isto, no entanto, lhe dará uma ideia básica." +"Este documento é uma introdução à escrita de programas em modo texto com " +"curses e Python. Isto não pretende ser um guia completo da API curses; para " +"isso, veja a seção ncurses no guia da biblioteca Python, e o manual de " +"ncurses. Isto, no entanto, lhe dará uma ideia básica." #: ../../howto/curses.rst:80 msgid "Starting and ending a curses application" @@ -184,6 +178,12 @@ msgid "" "after the name of the corresponding C variable. ::" msgstr "" +#: ../../howto/curses.rst:90 +msgid "" +"import curses\n" +"stdscr = curses.initscr()" +msgstr "" + #: ../../howto/curses.rst:93 msgid "" "Usually curses applications turn off automatic echoing of keys to the " @@ -194,6 +194,10 @@ msgstr "" "tela, para que seja possível ler chaves e somente exibi-las sob certas " "circunstâncias. Isto requer a chamada da função :func:`~curses.noecho`. ::" +#: ../../howto/curses.rst:98 +msgid "curses.noecho()" +msgstr "" + #: ../../howto/curses.rst:100 msgid "" "Applications will also commonly need to react to keys instantly, without " @@ -204,6 +208,10 @@ msgstr "" "sem requisitar que a tecla Enter seja pressionada; isto é chamado de modo " "cbreak, ao contrário do modo de entrada buferizada usual. ::" +#: ../../howto/curses.rst:104 +msgid "curses.cbreak()" +msgstr "" + #: ../../howto/curses.rst:106 msgid "" "Terminals usually return special keys, such as the cursor keys or navigation " @@ -220,6 +228,10 @@ msgstr "" "valor especial como :const:`curses.KEY_LEFT`. Para permitir que curses faça " "esse trabalho, você precisará habilitar o modo keypad. ::" +#: ../../howto/curses.rst:113 +msgid "stdscr.keypad(True)" +msgstr "" + #: ../../howto/curses.rst:115 msgid "" "Terminating a curses application is much easier than starting one. You'll " @@ -228,6 +240,13 @@ msgstr "" "Finalizar uma aplicação curses é mais fácil do que iniciar uma. Você " "precisará executar::" +#: ../../howto/curses.rst:118 +msgid "" +"curses.nocbreak()\n" +"stdscr.keypad(False)\n" +"curses.echo()" +msgstr "" + #: ../../howto/curses.rst:122 msgid "" "to reverse the curses-friendly terminal settings. Then call the :func:" @@ -238,6 +257,10 @@ msgstr "" "a função :func:`~curses.endwin` para restaurar o terminal para seu modo de " "operação original. ::" +#: ../../howto/curses.rst:126 +msgid "curses.endwin()" +msgstr "" + #: ../../howto/curses.rst:128 msgid "" "A common problem when debugging a curses application is to get your terminal " @@ -262,6 +285,25 @@ msgstr "" "mais simples importando a função :func:`curses.wrapper` e utilizando-a desta " "forma::" +#: ../../howto/curses.rst:137 +msgid "" +"from curses import wrapper\n" +"\n" +"def main(stdscr):\n" +" # Clear screen\n" +" stdscr.clear()\n" +"\n" +" # This raises ZeroDivisionError when i == 10.\n" +" for i in range(0, 11):\n" +" v = i-10\n" +" stdscr.addstr(i, 0, '10 divided by {} is {}'.format(v, 10/v))\n" +"\n" +" stdscr.refresh()\n" +" stdscr.getkey()\n" +"\n" +"wrapper(main)" +msgstr "" + #: ../../howto/curses.rst:153 msgid "" "The :func:`~curses.wrapper` function takes a callable object and does the " @@ -305,6 +347,13 @@ msgstr "" "func:`~curses.newwin` cria uma nova janela de um dado tamanho, retornando o " "novo objeto janela. ::" +#: ../../howto/curses.rst:178 +msgid "" +"begin_x = 20; begin_y = 7\n" +"height = 5; width = 40\n" +"win = curses.newwin(height, width, begin_y, begin_x)" +msgstr "" + #: ../../howto/curses.rst:182 msgid "" "Note that the coordinate system used in curses is unusual. Coordinates are " @@ -377,6 +426,24 @@ msgstr "" "altura e largura, enquanto atualizar o pad requer dar as coordenadas da área " "na tela onde uma subseção do pad será exibida. ::" +#: ../../howto/curses.rst:223 +msgid "" +"pad = curses.newpad(100, 100)\n" +"# These loops fill the pad with letters; addch() is\n" +"# explained in the next section\n" +"for y in range(0, 99):\n" +" for x in range(0, 99):\n" +" pad.addch(y,x, ord('a') + (x*x+y*y) % 26)\n" +"\n" +"# Displays a section of the pad in the middle of the screen.\n" +"# (0,0) : coordinate of upper-left corner of pad area to display.\n" +"# (5,5) : coordinate of upper-left corner of window area to be filled\n" +"# with pad content.\n" +"# (20, 75) : coordinate of lower-right corner of window area to be\n" +"# : filled with pad content.\n" +"pad.refresh( 0,0, 5,5, 20,75)" +msgstr "" + #: ../../howto/curses.rst:238 msgid "" "The :meth:`!refresh` call displays a section of the pad in the rectangle " @@ -645,6 +712,13 @@ msgid "" "you could code::" msgstr "" +#: ../../howto/curses.rst:364 +msgid "" +"stdscr.addstr(0, 0, \"Current mode: Typing mode\",\n" +" curses.A_REVERSE)\n" +"stdscr.refresh()" +msgstr "" + #: ../../howto/curses.rst:368 msgid "" "The curses library also supports color on those terminals that provide it. " @@ -678,6 +752,12 @@ msgstr "" msgid "An example, which displays a line of text using color pair 1::" msgstr "" +#: ../../howto/curses.rst:391 +msgid "" +"stdscr.addstr(\"Pretty text\", curses.color_pair(1))\n" +"stdscr.refresh()" +msgstr "" + #: ../../howto/curses.rst:394 msgid "" "As I said before, a color pair consists of a foreground and background " @@ -701,6 +781,10 @@ msgid "" "background, you would call::" msgstr "" +#: ../../howto/curses.rst:408 +msgid "curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)" +msgstr "" + #: ../../howto/curses.rst:410 msgid "" "When you change a color pair, any text already displayed using that color " @@ -708,6 +792,10 @@ msgid "" "color with::" msgstr "" +#: ../../howto/curses.rst:414 +msgid "stdscr.addstr(0,0, \"RED ALERT!\", curses.color_pair(1))" +msgstr "" + #: ../../howto/curses.rst:416 msgid "" "Very fancy terminals can change the definitions of the actual colors to a " @@ -773,6 +861,18 @@ msgid "" "program may look something like this::" msgstr "" +#: ../../howto/curses.rst:462 +msgid "" +"while True:\n" +" c = stdscr.getch()\n" +" if c == ord('p'):\n" +" PrintDocument()\n" +" elif c == ord('q'):\n" +" break # Exit the while loop\n" +" elif c == curses.KEY_HOME:\n" +" x = y = 0" +msgstr "" + #: ../../howto/curses.rst:471 msgid "" "The :mod:`curses.ascii` module supplies ASCII class membership functions " @@ -792,6 +892,14 @@ msgid "" "number of characters. ::" msgstr "" +#: ../../howto/curses.rst:484 +msgid "" +"curses.echo() # Enable echoing of characters\n" +"\n" +"# Get a 15-character string, with the cursor on the top line\n" +"s = stdscr.getstr(0,0, 15)" +msgstr "" + #: ../../howto/curses.rst:489 msgid "" "The :mod:`curses.textpad` module supplies a text box that supports an Emacs-" @@ -800,6 +908,27 @@ msgid "" "results either with or without trailing spaces. Here's an example::" msgstr "" +#: ../../howto/curses.rst:495 +msgid "" +"import curses\n" +"from curses.textpad import Textbox, rectangle\n" +"\n" +"def main(stdscr):\n" +" stdscr.addstr(0, 0, \"Enter IM message: (hit Ctrl-G to send)\")\n" +"\n" +" editwin = curses.newwin(5,30, 2,1)\n" +" rectangle(stdscr, 1,0, 1+5+1, 1+30+1)\n" +" stdscr.refresh()\n" +"\n" +" box = Textbox(editwin)\n" +"\n" +" # Let the user edit until Ctrl-G is struck.\n" +" box.edit()\n" +"\n" +" # Get resulting contents\n" +" message = box.gather()" +msgstr "" + #: ../../howto/curses.rst:513 msgid "" "See the library documentation on :mod:`curses.textpad` for more details." diff --git a/howto/descriptor.po b/howto/descriptor.po index f9d3146b6..23164f9c9 100644 --- a/howto/descriptor.po +++ b/howto/descriptor.po @@ -1,34 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-14 17:56+0000\n" -"PO-Revision-Date: 2021-06-28 00:53+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../howto/descriptor.rst:5 msgid "Descriptor Guide" -msgstr "" +msgstr "Guia de descritores" #: ../../howto/descriptor.rst:0 msgid "Author" @@ -120,9 +117,21 @@ msgstr "Exemplo simples: um descritor que retorna uma constante" #: ../../howto/descriptor.rst:45 msgid "" -"The :class:`Ten` class is a descriptor whose :meth:`__get__` method always " -"returns the constant ``10``:" +"The :class:`!Ten` class is a descriptor whose :meth:`~object.__get__` method " +"always returns the constant ``10``:" +msgstr "" +"A classe :class:`!Ten` é um descritor cujo método :meth:`~object.__get__` " +"sempre retorna a constante ``10``:" + +#: ../../howto/descriptor.rst:48 +msgid "" +"class Ten:\n" +" def __get__(self, obj, objtype=None):\n" +" return 10" msgstr "" +"class Ten:\n" +" def __get__(self, obj, objtype=None):\n" +" return 10" #: ../../howto/descriptor.rst:54 msgid "" @@ -132,6 +141,16 @@ msgstr "" "Para usar o descritor, ele deve ser armazenado como uma variável de classe " "em outra classe:" +#: ../../howto/descriptor.rst:56 +msgid "" +"class A:\n" +" x = 5 # Regular class attribute\n" +" y = Ten() # Descriptor instance" +msgstr "" +"class A:\n" +" x = 5 # Atributo de classe comum\n" +" y = Ten() # Instância de descritor" + #: ../../howto/descriptor.rst:62 msgid "" "An interactive session shows the difference between normal attribute lookup " @@ -140,6 +159,20 @@ msgstr "" "Uma sessão interativa mostra a diferença entre a pesquisa de atributo normal " "e a pesquisa de descritor:" +#: ../../howto/descriptor.rst:65 +msgid "" +">>> a = A() # Make an instance of class A\n" +">>> a.x # Normal attribute lookup\n" +"5\n" +">>> a.y # Descriptor lookup\n" +"10" +msgstr "" +">>> a = A() # Cria uma instância da classeA\n" +">>> a.x # Pesquisa de atributo normal\n" +"5\n" +">>> a.y # Pesquisa de descritor\n" +"10" + #: ../../howto/descriptor.rst:73 msgid "" "In the ``a.x`` attribute lookup, the dot operator finds ``'x': 5`` in the " @@ -147,6 +180,10 @@ msgid "" "descriptor instance, recognized by its ``__get__`` method. Calling that " "method returns ``10``." msgstr "" +"Na pesquisa de atributo ``a.x``, o operador ponto encontra ``'x': 5`` no " +"dicionário de classe. Na pesquisa ``a.y``, o operador ponto encontra uma " +"instância de descritor, reconhecida por seu método ``__get__``. Chamar esse " +"método retorna ``10``." #: ../../howto/descriptor.rst:78 msgid "" @@ -182,6 +219,36 @@ msgstr "" "Descritores interessantes normalmente executam cálculos em vez de retornar " "constantes:" +#: ../../howto/descriptor.rst:93 +msgid "" +"import os\n" +"\n" +"class DirectorySize:\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" return len(os.listdir(obj.dirname))\n" +"\n" +"class Directory:\n" +"\n" +" size = DirectorySize() # Descriptor instance\n" +"\n" +" def __init__(self, dirname):\n" +" self.dirname = dirname # Regular instance attribute" +msgstr "" +"import os\n" +"\n" +"class DirectorySize:\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" return len(os.listdir(obj.dirname))\n" +"\n" +"class Directory:\n" +"\n" +" size = DirectorySize() # Instância de descritor\n" +"\n" +" def __init__(self, dirname):\n" +" self.dirname = dirname # Atributo de instância regular" + #: ../../howto/descriptor.rst:109 msgid "" "An interactive session shows that the lookup is dynamic — it computes " @@ -190,21 +257,49 @@ msgstr "" "Uma sessão interativa mostra que a pesquisa é dinâmica – calcula respostas " "diferentes e atualizadas a cada vez::" +#: ../../howto/descriptor.rst:112 +msgid "" +">>> s = Directory('songs')\n" +">>> g = Directory('games')\n" +">>> s.size # The songs directory has twenty " +"files\n" +"20\n" +">>> g.size # The games directory has three " +"files\n" +"3\n" +">>> os.remove('games/chess') # Delete a game\n" +">>> g.size # File count is automatically " +"updated\n" +"2" +msgstr "" +">>> s = Directory('songs')\n" +">>> g = Directory('games')\n" +">>> s.size # O jogo de músicas tem vinte " +"arquivos\n" +"20\n" +">>> g.size # O diretório de jogos tem três " +"arquivos\n" +"3\n" +">>> os.remove('games/chess') # Exclui um jogo\n" +">>> g.size # Contagem de arquivos é atualizada " +"automaticamente\n" +"2" + #: ../../howto/descriptor.rst:122 msgid "" "Besides showing how descriptors can run computations, this example also " -"reveals the purpose of the parameters to :meth:`__get__`. The *self* " -"parameter is *size*, an instance of *DirectorySize*. The *obj* parameter is " -"either *g* or *s*, an instance of *Directory*. It is the *obj* parameter " -"that lets the :meth:`__get__` method learn the target directory. The " -"*objtype* parameter is the class *Directory*." +"reveals the purpose of the parameters to :meth:`~object.__get__`. The " +"*self* parameter is *size*, an instance of *DirectorySize*. The *obj* " +"parameter is either *g* or *s*, an instance of *Directory*. It is the *obj* " +"parameter that lets the :meth:`~object.__get__` method learn the target " +"directory. The *objtype* parameter is the class *Directory*." msgstr "" "Além de mostrar como os descritores podem executar cálculos, este exemplo " -"também revela o propósito dos parâmetros para :meth:`__get__`. O parâmetro " -"*self* é *size*, uma instância de *DirectorySize*. O parâmetro *obj* é *g* " -"ou *s*, uma instância de *Directory*. É o parâmetro *obj* que permite ao " -"método :meth:`__get__` aprender o diretório de destino. O parâmetro " -"*objtype* é a classe *Directory*." +"também revela o propósito dos parâmetros para :meth:`~object.__get__`. O " +"parâmetro *self* é *size*, uma instância de *DirectorySize*. O parâmetro " +"*obj* é *g* ou *s*, uma instância de *Directory*. É o parâmetro *obj* que " +"permite ao método :meth:`~object.__get__` aprender o diretório de destino. O " +"parâmetro *objtype* é a classe *Directory*." #: ../../howto/descriptor.rst:131 msgid "Managed attributes" @@ -215,14 +310,14 @@ msgid "" "A popular use for descriptors is managing access to instance data. The " "descriptor is assigned to a public attribute in the class dictionary while " "the actual data is stored as a private attribute in the instance " -"dictionary. The descriptor's :meth:`__get__` and :meth:`__set__` methods " -"are triggered when the public attribute is accessed." +"dictionary. The descriptor's :meth:`~object.__get__` and :meth:`~object." +"__set__` methods are triggered when the public attribute is accessed." msgstr "" "Um uso popular para descritores é gerenciar o acesso aos dados da instância. " "O descritor é atribuído a um atributo público no dicionário da classe, " "enquanto os dados reais são armazenados como um atributo privado no " -"dicionário da instância. Os métodos :meth:`__get__` e :meth:`__set__` do " -"descritor são disparados quando o atributo público é acessado." +"dicionário da instância. Os métodos :meth:`~object.__get__` e :meth:`~object." +"__set__` do descritor são disparados quando o atributo público é acessado." #: ../../howto/descriptor.rst:139 msgid "" @@ -234,6 +329,60 @@ msgstr "" "privado. Quando o atributo público é acessado, o descritor registra a " "pesquisa ou atualização:" +#: ../../howto/descriptor.rst:143 +msgid "" +"import logging\n" +"\n" +"logging.basicConfig(level=logging.INFO)\n" +"\n" +"class LoggedAgeAccess:\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" value = obj._age\n" +" logging.info('Accessing %r giving %r', 'age', value)\n" +" return value\n" +"\n" +" def __set__(self, obj, value):\n" +" logging.info('Updating %r to %r', 'age', value)\n" +" obj._age = value\n" +"\n" +"class Person:\n" +"\n" +" age = LoggedAgeAccess() # Descriptor instance\n" +"\n" +" def __init__(self, name, age):\n" +" self.name = name # Regular instance attribute\n" +" self.age = age # Calls __set__()\n" +"\n" +" def birthday(self):\n" +" self.age += 1 # Calls both __get__() and __set__()" +msgstr "" +"import logging\n" +"\n" +"logging.basicConfig(level=logging.INFO)\n" +"\n" +"class LoggedAgeAccess:\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" value = obj._age\n" +" logging.info('Accessing %r giving %r', 'age', value)\n" +" return value\n" +"\n" +" def __set__(self, obj, value):\n" +" logging.info('Updating %r to %r', 'age', value)\n" +" obj._age = value\n" +"\n" +"class Person:\n" +"\n" +" age = LoggedAgeAccess() # Instância de descritor\n" +"\n" +" def __init__(self, name, age):\n" +" self.name = name # Atributo de instância regular\n" +" self.age = age # Chama __set__()\n" +"\n" +" def birthday(self):\n" +" self.age += 1 # Chama __get__() e __set__()" + #: ../../howto/descriptor.rst:172 msgid "" "An interactive session shows that all access to the managed attribute *age* " @@ -242,6 +391,64 @@ msgstr "" "Uma sessão interativa mostra que todo o acesso ao atributo gerenciado *age* " "é registrado, mas que o atributo regular *name* não é registrado:" +#: ../../howto/descriptor.rst:181 +msgid "" +">>> mary = Person('Mary M', 30) # The initial age update is logged\n" +"INFO:root:Updating 'age' to 30\n" +">>> dave = Person('David D', 40)\n" +"INFO:root:Updating 'age' to 40\n" +"\n" +">>> vars(mary) # The actual data is in a private " +"attribute\n" +"{'name': 'Mary M', '_age': 30}\n" +">>> vars(dave)\n" +"{'name': 'David D', '_age': 40}\n" +"\n" +">>> mary.age # Access the data and log the " +"lookup\n" +"INFO:root:Accessing 'age' giving 30\n" +"30\n" +">>> mary.birthday() # Updates are logged as well\n" +"INFO:root:Accessing 'age' giving 30\n" +"INFO:root:Updating 'age' to 31\n" +"\n" +">>> dave.name # Regular attribute lookup isn't " +"logged\n" +"'David D'\n" +">>> dave.age # Only the managed attribute is " +"logged\n" +"INFO:root:Accessing 'age' giving 40\n" +"40" +msgstr "" +">>> mary = Person('Mary M', 30) # A atualização inicial de idade é " +"registrada\n" +"INFO:root:Updating 'age' to 30\n" +">>> dave = Person('David D', 40)\n" +"INFO:root:Updating 'age' to 40\n" +"\n" +">>> vars(mary) # Os dados estão em um atributo " +"privado\n" +"{'name': 'Mary M', '_age': 30}\n" +">>> vars(dave)\n" +"{'name': 'David D', '_age': 40}\n" +"\n" +">>> mary.age # Acessa os dados e registra a " +"pesquisa\n" +"INFO:root:Accessing 'age' giving 30\n" +"30\n" +">>> mary.birthday() # Atualizações são registradas " +"também\n" +"INFO:root:Accessing 'age' giving 30\n" +"INFO:root:Updating 'age' to 31\n" +"\n" +">>> dave.name # Pesquisa de atributo regular não é " +"registrada\n" +"'David D'\n" +">>> dave.age # Apenas o atributo gerenciado é " +"registrado\n" +"INFO:root:Accessing 'age' giving 40\n" +"40" + #: ../../howto/descriptor.rst:206 msgid "" "One major issue with this example is that the private name *_age* is " @@ -268,35 +475,139 @@ msgstr "" #: ../../howto/descriptor.rst:218 msgid "" -"In this example, the :class:`Person` class has two descriptor instances, " -"*name* and *age*. When the :class:`Person` class is defined, it makes a " -"callback to :meth:`__set_name__` in *LoggedAccess* so that the field names " -"can be recorded, giving each descriptor its own *public_name* and " +"In this example, the :class:`!Person` class has two descriptor instances, " +"*name* and *age*. When the :class:`!Person` class is defined, it makes a " +"callback to :meth:`~object.__set_name__` in *LoggedAccess* so that the field " +"names can be recorded, giving each descriptor its own *public_name* and " "*private_name*:" msgstr "" -"Neste exemplo, a classe :class:`Person` tem duas instâncias de descritor, " -"*name* e *age*. Quando a classe :class:`Person` é definida, ela faz uma " -"função de retorno para :meth:`__set_name__` em *LoggedAccess* para que os " -"nomes dos campos possam ser registrados, dando a cada descritor o seu " +"Neste exemplo, a classe :class:`!Person` tem duas instâncias de descritor, " +"*name* e *age*. Quando a classe :class:`!Person` é definida, ela faz uma " +"função de retorno para :meth:`~object.__set_name__` em *LoggedAccess* para " +"que os nomes dos campos possam ser registrados, dando a cada descritor o seu " "próprio *public_name* e *private_name*:" +#: ../../howto/descriptor.rst:223 +msgid "" +"import logging\n" +"\n" +"logging.basicConfig(level=logging.INFO)\n" +"\n" +"class LoggedAccess:\n" +"\n" +" def __set_name__(self, owner, name):\n" +" self.public_name = name\n" +" self.private_name = '_' + name\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" value = getattr(obj, self.private_name)\n" +" logging.info('Accessing %r giving %r', self.public_name, value)\n" +" return value\n" +"\n" +" def __set__(self, obj, value):\n" +" logging.info('Updating %r to %r', self.public_name, value)\n" +" setattr(obj, self.private_name, value)\n" +"\n" +"class Person:\n" +"\n" +" name = LoggedAccess() # First descriptor instance\n" +" age = LoggedAccess() # Second descriptor instance\n" +"\n" +" def __init__(self, name, age):\n" +" self.name = name # Calls the first descriptor\n" +" self.age = age # Calls the second descriptor\n" +"\n" +" def birthday(self):\n" +" self.age += 1" +msgstr "" +"import logging\n" +"\n" +"logging.basicConfig(level=logging.INFO)\n" +"\n" +"class LoggedAccess:\n" +"\n" +" def __set_name__(self, owner, name):\n" +" self.public_name = name\n" +" self.private_name = '_' + name\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" value = getattr(obj, self.private_name)\n" +" logging.info('Accessing %r giving %r', self.public_name, value)\n" +" return value\n" +"\n" +" def __set__(self, obj, value):\n" +" logging.info('Updating %r to %r', self.public_name, value)\n" +" setattr(obj, self.private_name, value)\n" +"\n" +"class Person:\n" +"\n" +" name = LoggedAccess() # Primeira instância de descritor\n" +" age = LoggedAccess() # Segunda instância de descritor\n" +"\n" +" def __init__(self, name, age):\n" +" self.name = name # Chama o primeiro descritor\n" +" self.age = age # Chama o segundo descritor\n" +"\n" +" def birthday(self):\n" +" self.age += 1" + #: ../../howto/descriptor.rst:256 msgid "" -"An interactive session shows that the :class:`Person` class has called :meth:" -"`__set_name__` so that the field names would be recorded. Here we call :" -"func:`vars` to look up the descriptor without triggering it:" +"An interactive session shows that the :class:`!Person` class has called :" +"meth:`~object.__set_name__` so that the field names would be recorded. Here " +"we call :func:`vars` to look up the descriptor without triggering it:" msgstr "" -"Uma sessão interativa mostra que a classe :class:`Person` chamou :meth:" -"`__set_name__` para que os nomes dos campos fossem registrados. Aqui " +"Uma sessão interativa mostra que a classe :class:`!Person` chamou :meth:" +"`~object.__set_name__` para que os nomes dos campos fossem registrados. Aqui " "chamamos :func:`vars` para pesquisar o descritor sem acioná-lo:" +#: ../../howto/descriptor.rst:260 +msgid "" +">>> vars(vars(Person)['name'])\n" +"{'public_name': 'name', 'private_name': '_name'}\n" +">>> vars(vars(Person)['age'])\n" +"{'public_name': 'age', 'private_name': '_age'}" +msgstr "" +">>> vars(vars(Person)['name'])\n" +"{'public_name': 'name', 'private_name': '_name'}\n" +">>> vars(vars(Person)['age'])\n" +"{'public_name': 'age', 'private_name': '_age'}" + #: ../../howto/descriptor.rst:267 msgid "The new class now logs access to both *name* and *age*:" msgstr "A nova classe agora registra acesso a *name* e *age*:" +#: ../../howto/descriptor.rst:275 +msgid "" +">>> pete = Person('Peter P', 10)\n" +"INFO:root:Updating 'name' to 'Peter P'\n" +"INFO:root:Updating 'age' to 10\n" +">>> kate = Person('Catherine C', 20)\n" +"INFO:root:Updating 'name' to 'Catherine C'\n" +"INFO:root:Updating 'age' to 20" +msgstr "" +">>> pete = Person('Peter P', 10)\n" +"INFO:root:Updating 'name' to 'Peter P'\n" +"INFO:root:Updating 'age' to 10\n" +">>> kate = Person('Catherine C', 20)\n" +"INFO:root:Updating 'name' to 'Catherine C'\n" +"INFO:root:Updating 'age' to 20" + #: ../../howto/descriptor.rst:284 msgid "The two *Person* instances contain only the private names:" +msgstr "As duas instâncias *Person* contêm apenas os nomes privados:" + +#: ../../howto/descriptor.rst:286 +msgid "" +">>> vars(pete)\n" +"{'_name': 'Peter P', '_age': 10}\n" +">>> vars(kate)\n" +"{'_name': 'Catherine C', '_age': 20}" msgstr "" +">>> vars(pete)\n" +"{'_name': 'Peter P', '_age': 10}\n" +">>> vars(kate)\n" +"{'_name': 'Catherine C', '_age': 20}" #: ../../howto/descriptor.rst:295 msgid "Closing thoughts" @@ -304,19 +615,24 @@ msgstr "Pensamentos finais" #: ../../howto/descriptor.rst:297 msgid "" -"A :term:`descriptor` is what we call any object that defines :meth:" -"`__get__`, :meth:`__set__`, or :meth:`__delete__`." +"A :term:`descriptor` is what we call any object that defines :meth:`~object." +"__get__`, :meth:`~object.__set__`, or :meth:`~object.__delete__`." msgstr "" "Um :term:`descritor` é o que chamamos de qualquer objeto que define :meth:" -"`__get__`, :meth:`__set__` ou :meth:`__delete__`." +"`~object.__get__`, :meth:`~object.__set__` ou :meth:`~object.__delete__`." #: ../../howto/descriptor.rst:300 msgid "" -"Optionally, descriptors can have a :meth:`__set_name__` method. This is " -"only used in cases where a descriptor needs to know either the class where " -"it was created or the name of class variable it was assigned to. (This " -"method, if present, is called even if the class is not a descriptor.)" +"Optionally, descriptors can have a :meth:`~object.__set_name__` method. " +"This is only used in cases where a descriptor needs to know either the class " +"where it was created or the name of class variable it was assigned to. " +"(This method, if present, is called even if the class is not a descriptor.)" msgstr "" +"Opcionalmente, os descritores podem ter um método :meth:`~object." +"__set_name__`. Isso é usado somente em casos em que um descritor precisa " +"saber a classe onde foi criado ou o nome da variável de classe à qual foi " +"atribuído. (Este método, se presente, é chamado mesmo se a classe não for um " +"descritor.)" #: ../../howto/descriptor.rst:305 msgid "" @@ -324,18 +640,26 @@ msgid "" "descriptor is accessed indirectly with ``vars(some_class)" "[descriptor_name]``, the descriptor instance is returned without invoking it." msgstr "" +"Descritores são invocados pelo operador ponto durante a pesquisa de " +"atributos. Se um descritor for acessado indiretamente com ``vars(some_class)" +"[descriptor_name]``, a instância do descritor é retornada sem invocá-lo." #: ../../howto/descriptor.rst:309 msgid "" "Descriptors only work when used as class variables. When put in instances, " "they have no effect." msgstr "" +"Descritores só funcionam quando usados como variáveis de classe. Quando " +"colocados em instâncias, eles não têm efeito." #: ../../howto/descriptor.rst:312 msgid "" "The main motivation for descriptors is to provide a hook allowing objects " "stored in class variables to control what happens during attribute lookup." msgstr "" +"A principal motivação para descritores é fornecer um gancho permitindo que " +"objetos armazenados em variáveis de classe controlem o que acontece durante " +"a pesquisa de atributos." #: ../../howto/descriptor.rst:315 msgid "" @@ -343,6 +667,9 @@ msgid "" "Descriptors invert that relationship and allow the data being looked-up to " "have a say in the matter." msgstr "" +"Tradicionalmente, a classe de chamada controla o que acontece durante a " +"pesquisa. Descritores invertem esse relacionamento e permitem que os dados " +"pesquisados tenham uma palavra a dizer sobre o assunto." #: ../../howto/descriptor.rst:319 msgid "" @@ -351,20 +678,26 @@ msgid "" "`staticmethod`, :func:`property`, and :func:`functools.cached_property` are " "all implemented as descriptors." msgstr "" +"Descritores são usados em toda a linguagem. É como funções se transformam em " +"métodos vinculados. Ferramentas comuns como :func:`classmethod`, :func:" +"`staticmethod`, :func:`property` e :func:`functools.cached_property` são " +"todas implementadas como descritores." #: ../../howto/descriptor.rst:326 msgid "Complete Practical Example" -msgstr "" +msgstr "Exemplo completamente prático" #: ../../howto/descriptor.rst:328 msgid "" "In this example, we create a practical and powerful tool for locating " "notoriously hard to find data corruption bugs." msgstr "" +"Neste exemplo, criamos uma ferramenta prática e poderosa para localizar bugs " +"de corrupção de dados notoriamente difíceis de encontrar." #: ../../howto/descriptor.rst:333 msgid "Validator class" -msgstr "" +msgstr "Classe Validator" #: ../../howto/descriptor.rst:335 msgid "" @@ -373,98 +706,348 @@ msgid "" "restrictions. If those restrictions aren't met, it raises an exception to " "prevent data corruption at its source." msgstr "" +"Um validador é um descritor para acesso de atributo gerenciado. Antes de " +"armazenar quaisquer dados, ele verifica se o novo valor atende a várias " +"restrições de tipo e intervalo. Se essas restrições não forem atendidas, ele " +"levanta uma exceção para evitar corrupção de dados em sua origem." #: ../../howto/descriptor.rst:340 msgid "" -"This :class:`Validator` class is both an :term:`abstract base class` and a " +"This :class:`!Validator` class is both an :term:`abstract base class` and a " "managed attribute descriptor:" msgstr "" +"Esta classe :class:`!Validator` é uma :term:`classe base abstrata` e um " +"descritor de atributo gerenciado:" + +#: ../../howto/descriptor.rst:343 +msgid "" +"from abc import ABC, abstractmethod\n" +"\n" +"class Validator(ABC):\n" +"\n" +" def __set_name__(self, owner, name):\n" +" self.private_name = '_' + name\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" return getattr(obj, self.private_name)\n" +"\n" +" def __set__(self, obj, value):\n" +" self.validate(value)\n" +" setattr(obj, self.private_name, value)\n" +"\n" +" @abstractmethod\n" +" def validate(self, value):\n" +" pass" +msgstr "" +"from abc import ABC, abstractmethod\n" +"\n" +"class Validator(ABC):\n" +"\n" +" def __set_name__(self, owner, name):\n" +" self.private_name = '_' + name\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" return getattr(obj, self.private_name)\n" +"\n" +" def __set__(self, obj, value):\n" +" self.validate(value)\n" +" setattr(obj, self.private_name, value)\n" +"\n" +" @abstractmethod\n" +" def validate(self, value):\n" +" pass" #: ../../howto/descriptor.rst:363 msgid "" -"Custom validators need to inherit from :class:`Validator` and must supply a :" -"meth:`validate` method to test various restrictions as needed." +"Custom validators need to inherit from :class:`!Validator` and must supply " +"a :meth:`!validate` method to test various restrictions as needed." msgstr "" +"Validadores personalizados precisam herdar de :class:`!Validator` e devem " +"fornecer um método :meth:`!validate` para testar várias restrições conforme " +"necessário." #: ../../howto/descriptor.rst:368 msgid "Custom validators" -msgstr "" +msgstr "Validadores personalizados" #: ../../howto/descriptor.rst:370 msgid "Here are three practical data validation utilities:" -msgstr "" +msgstr "Vemos aqui três utilitários práticos de validação de dados:" #: ../../howto/descriptor.rst:372 msgid "" -":class:`OneOf` verifies that a value is one of a restricted set of options." +":class:`!OneOf` verifies that a value is one of a restricted set of options." msgstr "" +":class:`!OneOf` verifica se um valor é um de um conjunto restrito de opções." #: ../../howto/descriptor.rst:374 msgid "" -":class:`Number` verifies that a value is either an :class:`int` or :class:" +":class:`!Number` verifies that a value is either an :class:`int` or :class:" "`float`. Optionally, it verifies that a value is between a given minimum or " "maximum." msgstr "" +":class:`!Number` verifica se um valor é um :class:`int` ou :class:`float`. " +"Opcionalmente, ele verifica se um valor está entre um mínimo ou máximo dado." #: ../../howto/descriptor.rst:378 msgid "" -":class:`String` verifies that a value is a :class:`str`. Optionally, it " +":class:`!String` verifies that a value is a :class:`str`. Optionally, it " "validates a given minimum or maximum length. It can validate a user-defined " "`predicate `_ " "as well." msgstr "" +":class:`!String` verifica se um valor é um :class:`str`. Opcionalmente, ele " +"valida um comprimento mínimo ou máximo dado. Ele pode validar um `predicado " +"`_ definido " +"pelo usuário também." + +#: ../../howto/descriptor.rst:383 +msgid "" +"class OneOf(Validator):\n" +"\n" +" def __init__(self, *options):\n" +" self.options = set(options)\n" +"\n" +" def validate(self, value):\n" +" if value not in self.options:\n" +" raise ValueError(\n" +" f'Expected {value!r} to be one of {self.options!r}'\n" +" )\n" +"\n" +"class Number(Validator):\n" +"\n" +" def __init__(self, minvalue=None, maxvalue=None):\n" +" self.minvalue = minvalue\n" +" self.maxvalue = maxvalue\n" +"\n" +" def validate(self, value):\n" +" if not isinstance(value, (int, float)):\n" +" raise TypeError(f'Expected {value!r} to be an int or float')\n" +" if self.minvalue is not None and value < self.minvalue:\n" +" raise ValueError(\n" +" f'Expected {value!r} to be at least {self.minvalue!r}'\n" +" )\n" +" if self.maxvalue is not None and value > self.maxvalue:\n" +" raise ValueError(\n" +" f'Expected {value!r} to be no more than {self.maxvalue!r}'\n" +" )\n" +"\n" +"class String(Validator):\n" +"\n" +" def __init__(self, minsize=None, maxsize=None, predicate=None):\n" +" self.minsize = minsize\n" +" self.maxsize = maxsize\n" +" self.predicate = predicate\n" +"\n" +" def validate(self, value):\n" +" if not isinstance(value, str):\n" +" raise TypeError(f'Expected {value!r} to be an str')\n" +" if self.minsize is not None and len(value) < self.minsize:\n" +" raise ValueError(\n" +" f'Expected {value!r} to be no smaller than {self.minsize!" +"r}'\n" +" )\n" +" if self.maxsize is not None and len(value) > self.maxsize:\n" +" raise ValueError(\n" +" f'Expected {value!r} to be no bigger than {self.maxsize!r}'\n" +" )\n" +" if self.predicate is not None and not self.predicate(value):\n" +" raise ValueError(\n" +" f'Expected {self.predicate} to be true for {value!r}'\n" +" )" +msgstr "" +"class OneOf(Validator):\n" +"\n" +" def __init__(self, *options):\n" +" self.options = set(options)\n" +"\n" +" def validate(self, value):\n" +" if value not in self.options:\n" +" raise ValueError(\n" +" f'Expected {value!r} to be one of {self.options!r}'\n" +" )\n" +"\n" +"class Number(Validator):\n" +"\n" +" def __init__(self, minvalue=None, maxvalue=None):\n" +" self.minvalue = minvalue\n" +" self.maxvalue = maxvalue\n" +"\n" +" def validate(self, value):\n" +" if not isinstance(value, (int, float)):\n" +" raise TypeError(f'Expected {value!r} to be an int or float')\n" +" if self.minvalue is not None and value < self.minvalue:\n" +" raise ValueError(\n" +" f'Expected {value!r} to be at least {self.minvalue!r}'\n" +" )\n" +" if self.maxvalue is not None and value > self.maxvalue:\n" +" raise ValueError(\n" +" f'Expected {value!r} to be no more than {self.maxvalue!r}'\n" +" )\n" +"\n" +"class String(Validator):\n" +"\n" +" def __init__(self, minsize=None, maxsize=None, predicate=None):\n" +" self.minsize = minsize\n" +" self.maxsize = maxsize\n" +" self.predicate = predicate\n" +"\n" +" def validate(self, value):\n" +" if not isinstance(value, str):\n" +" raise TypeError(f'Expected {value!r} to be an str')\n" +" if self.minsize is not None and len(value) < self.minsize:\n" +" raise ValueError(\n" +" f'Expected {value!r} to be no smaller than {self.minsize!" +"r}'\n" +" )\n" +" if self.maxsize is not None and len(value) > self.maxsize:\n" +" raise ValueError(\n" +" f'Expected {value!r} to be no bigger than {self.maxsize!r}'\n" +" )\n" +" if self.predicate is not None and not self.predicate(value):\n" +" raise ValueError(\n" +" f'Expected {self.predicate} to be true for {value!r}'\n" +" )" -#: ../../howto/descriptor.rst:437 +#: ../../howto/descriptor.rst:439 msgid "Practical application" -msgstr "" +msgstr "Aplicação prática" -#: ../../howto/descriptor.rst:439 +#: ../../howto/descriptor.rst:441 msgid "Here's how the data validators can be used in a real class:" -msgstr "" - -#: ../../howto/descriptor.rst:454 +msgstr "Veja como os validadores de dados podem ser usados em uma classe real:" + +#: ../../howto/descriptor.rst:443 +msgid "" +"class Component:\n" +"\n" +" name = String(minsize=3, maxsize=10, predicate=str.isupper)\n" +" kind = OneOf('wood', 'metal', 'plastic')\n" +" quantity = Number(minvalue=0)\n" +"\n" +" def __init__(self, name, kind, quantity):\n" +" self.name = name\n" +" self.kind = kind\n" +" self.quantity = quantity" +msgstr "" +"class Component:\n" +"\n" +" name = String(minsize=3, maxsize=10, predicate=str.isupper)\n" +" kind = OneOf('wood', 'metal', 'plastic')\n" +" quantity = Number(minvalue=0)\n" +"\n" +" def __init__(self, name, kind, quantity):\n" +" self.name = name\n" +" self.kind = kind\n" +" self.quantity = quantity" + +#: ../../howto/descriptor.rst:456 msgid "The descriptors prevent invalid instances from being created:" -msgstr "" - -#: ../../howto/descriptor.rst:481 +msgstr "Os descritores impedem que instâncias inválidas sejam criadas:" + +#: ../../howto/descriptor.rst:458 +msgid "" +">>> Component('Widget', 'metal', 5) # Blocked: 'Widget' is not all " +"uppercase\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: Expected to be true for " +"'Widget'\n" +"\n" +">>> Component('WIDGET', 'metle', 5) # Blocked: 'metle' is misspelled\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: Expected 'metle' to be one of {'metal', 'plastic', 'wood'}\n" +"\n" +">>> Component('WIDGET', 'metal', -5) # Blocked: -5 is negative\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: Expected -5 to be at least 0\n" +"\n" +">>> Component('WIDGET', 'metal', 'V') # Blocked: 'V' isn't a number\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: Expected 'V' to be an int or float\n" +"\n" +">>> c = Component('WIDGET', 'metal', 5) # Allowed: The inputs are valid" +msgstr "" +">>> Component('Widget', 'metal', 5) # Bloqueado: 'Widget' não está todo " +"em letras maiúsculas\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: Expected to be true for " +"'Widget'\n" +"\n" +">>> Component('WIDGET', 'metle', 5) # Bloqueado: 'metle' contém um erro " +"de escrita\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: Expected 'metle' to be one of {'metal', 'plastic', 'wood'}\n" +"\n" +">>> Component('WIDGET', 'metal', -5) # Bloqueado: -5 é negativo\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: Expected -5 to be at least 0\n" +"\n" +">>> Component('WIDGET', 'metal', 'V') # Bloqueado: 'V' não é um número\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: Expected 'V' to be an int or float\n" +"\n" +">>> c = Component('WIDGET', 'metal', 5) # Permitido: As entradas são " +"válidas" + +#: ../../howto/descriptor.rst:484 msgid "Technical Tutorial" -msgstr "" +msgstr "Tutorial técnico" -#: ../../howto/descriptor.rst:483 +#: ../../howto/descriptor.rst:486 msgid "" "What follows is a more technical tutorial for the mechanics and details of " "how descriptors work." msgstr "" +"O que se segue é um tutorial mais técnico sobre a mecânica e os detalhes de " +"como os descritores funcionam." -#: ../../howto/descriptor.rst:488 +#: ../../howto/descriptor.rst:491 msgid "Abstract" msgstr "Resumo" -#: ../../howto/descriptor.rst:490 +#: ../../howto/descriptor.rst:493 msgid "" "Defines descriptors, summarizes the protocol, and shows how descriptors are " "called. Provides an example showing how object relational mappings work." msgstr "" +"Define descritores, resume o protocolo e mostra como os descritores são " +"chamados. Fornece um exemplo mostrando como mapeamentos relacionais de " +"objetos funcionam." -#: ../../howto/descriptor.rst:493 +#: ../../howto/descriptor.rst:496 msgid "" "Learning about descriptors not only provides access to a larger toolset, it " "creates a deeper understanding of how Python works." msgstr "" +"Aprender sobre descritores não apenas fornece acesso a um conjunto de " +"ferramentas maior, mas também cria uma compreensão mais profunda de como o " +"Python funciona." -#: ../../howto/descriptor.rst:498 +#: ../../howto/descriptor.rst:501 msgid "Definition and introduction" -msgstr "" +msgstr "Definição e introdução" -#: ../../howto/descriptor.rst:500 +#: ../../howto/descriptor.rst:503 msgid "" "In general, a descriptor is an attribute value that has one of the methods " -"in the descriptor protocol. Those methods are :meth:`__get__`, :meth:" -"`__set__`, and :meth:`__delete__`. If any of those methods are defined for " -"an attribute, it is said to be a :term:`descriptor`." +"in the descriptor protocol. Those methods are :meth:`~object.__get__`, :" +"meth:`~object.__set__`, and :meth:`~object.__delete__`. If any of those " +"methods are defined for an attribute, it is said to be a :term:`descriptor`." msgstr "" +"Em geral, um descritor é um valor de atributo que tem um dos métodos no " +"protocolo do descritor. Esses métodos são :meth:`~object.__get__`, :meth:" +"`~object.__set__` e :meth:`~object.__delete__`. Se qualquer um desses " +"métodos for definido para um atributo, ele é dito ser um :term:`descritor`." -#: ../../howto/descriptor.rst:505 +#: ../../howto/descriptor.rst:508 msgid "" "The default behavior for attribute access is to get, set, or delete the " "attribute from an object's dictionary. For instance, ``a.x`` has a lookup " @@ -475,48 +1058,68 @@ msgid "" "Where this occurs in the precedence chain depends on which descriptor " "methods were defined." msgstr "" +"O comportamento padrão para acesso a atributos é obter, definir ou excluir o " +"atributo do dicionário de um objeto. Por exemplo, ``a.x`` tem uma cadeia de " +"pesquisa começando com ``a.__dict__['x']``, depois ``type(a).__dict__['x']`` " +"e continuando pela ordem de resolução de métodos de ``type(a)``. Se o valor " +"pesquisado for um objeto que define um dos métodos descritores, o Python " +"pode substituir o comportamento padrão e invocar o método descritor. Onde " +"isso ocorre na cadeia de precedência depende de quais métodos descritores " +"foram definidos." -#: ../../howto/descriptor.rst:514 +#: ../../howto/descriptor.rst:517 msgid "" "Descriptors are a powerful, general purpose protocol. They are the " "mechanism behind properties, methods, static methods, class methods, and :" -"func:`super()`. They are used throughout Python itself. Descriptors " -"simplify the underlying C code and offer a flexible set of new tools for " -"everyday Python programs." +"func:`super`. They are used throughout Python itself. Descriptors simplify " +"the underlying C code and offer a flexible set of new tools for everyday " +"Python programs." msgstr "" +"Descritores são um protocolo poderoso de propósito geral. Eles são o " +"mecanismo por trás de propriedades, métodos, métodos estáticos, métodos de " +"classe e :func:`super`. Eles são usados em todo o Python. Descritores " +"simplificam o código C subjacente e oferecem um conjunto flexível de novas " +"ferramentas para programas Python do dia a dia." -#: ../../howto/descriptor.rst:522 +#: ../../howto/descriptor.rst:525 msgid "Descriptor protocol" -msgstr "" +msgstr "Protocolo Descriptor" -#: ../../howto/descriptor.rst:524 +#: ../../howto/descriptor.rst:527 msgid "``descr.__get__(self, obj, type=None)``" -msgstr "" +msgstr "``descr.__get__(self, obj, type=None)``" -#: ../../howto/descriptor.rst:526 +#: ../../howto/descriptor.rst:529 msgid "``descr.__set__(self, obj, value)``" -msgstr "" +msgstr "``descr.__set__(self, obj, value)``" -#: ../../howto/descriptor.rst:528 +#: ../../howto/descriptor.rst:531 msgid "``descr.__delete__(self, obj)``" -msgstr "" +msgstr "``descr.__delete__(self, obj)``" -#: ../../howto/descriptor.rst:530 +#: ../../howto/descriptor.rst:533 msgid "" "That is all there is to it. Define any of these methods and an object is " "considered a descriptor and can override default behavior upon being looked " "up as an attribute." msgstr "" +"É só isso. Defina qualquer um desses métodos e um objeto é considerado um " +"descritor e pode substituir o comportamento padrão ao ser pesquisado como um " +"atributo." -#: ../../howto/descriptor.rst:534 +#: ../../howto/descriptor.rst:537 msgid "" -"If an object defines :meth:`__set__` or :meth:`__delete__`, it is considered " -"a data descriptor. Descriptors that only define :meth:`__get__` are called " -"non-data descriptors (they are often used for methods but other uses are " -"possible)." +"If an object defines :meth:`~object.__set__` or :meth:`~object.__delete__`, " +"it is considered a data descriptor. Descriptors that only define :meth:" +"`~object.__get__` are called non-data descriptors (they are often used for " +"methods but other uses are possible)." msgstr "" +"Se um objeto define :meth:`~object.__set__` ou :meth:`~object.__delete__`, " +"ele é considerado um descritor de dados. Descritores que definem apenas :" +"meth:`~object.__get__` são chamados de descritores não-dados (eles são " +"frequentemente usados para métodos, mas outros usos são possíveis)." -#: ../../howto/descriptor.rst:539 +#: ../../howto/descriptor.rst:542 msgid "" "Data and non-data descriptors differ in how overrides are calculated with " "respect to entries in an instance's dictionary. If an instance's dictionary " @@ -524,282 +1127,676 @@ msgid "" "takes precedence. If an instance's dictionary has an entry with the same " "name as a non-data descriptor, the dictionary entry takes precedence." msgstr "" +"Descritores de dados e não dados diferem em como as substituições são " +"calculadas com relação às entradas no dicionário de uma instância. Se o " +"dicionário de uma instância tiver uma entrada com o mesmo nome de um " +"descritor de dados, o descritor de dados terá precedência. Se o dicionário " +"de uma instância tiver uma entrada com o mesmo nome de um descritor não " +"dados, a entrada do dicionário terá precedência." -#: ../../howto/descriptor.rst:545 +#: ../../howto/descriptor.rst:548 msgid "" -"To make a read-only data descriptor, define both :meth:`__get__` and :meth:" -"`__set__` with the :meth:`__set__` raising an :exc:`AttributeError` when " -"called. Defining the :meth:`__set__` method with an exception raising " -"placeholder is enough to make it a data descriptor." +"To make a read-only data descriptor, define both :meth:`~object.__get__` " +"and :meth:`~object.__set__` with the :meth:`~object.__set__` raising an :exc:" +"`AttributeError` when called. Defining the :meth:`~object.__set__` method " +"with an exception raising placeholder is enough to make it a data descriptor." msgstr "" +"Para criar um descritor de dados somente leitura, defina :meth:`~object." +"__get__` e :meth:`~object.__set__` com o :meth:`~object.__set__` levantando :" +"exc:`AttributeError` quando chamado. Definir o método :meth:`~object." +"__set__` com um espaço reservado levantando uma exceção é o suficiente para " +"torná-lo um descritor de dados." -#: ../../howto/descriptor.rst:552 +#: ../../howto/descriptor.rst:555 msgid "Overview of descriptor invocation" -msgstr "" +msgstr "Visão geral da invocação do descritor" -#: ../../howto/descriptor.rst:554 +#: ../../howto/descriptor.rst:557 msgid "" "A descriptor can be called directly with ``desc.__get__(obj)`` or ``desc." "__get__(None, cls)``." msgstr "" +"Um descritor pode ser chamado diretamente com ``desc.__get__(obj)`` ou " +"``desc.__get__(None, cls)``." -#: ../../howto/descriptor.rst:557 +#: ../../howto/descriptor.rst:560 msgid "" "But it is more common for a descriptor to be invoked automatically from " "attribute access." msgstr "" +"Mas é mais comum que um descritor seja invocado automaticamente a partir do " +"acesso ao atributo." -#: ../../howto/descriptor.rst:560 +#: ../../howto/descriptor.rst:563 msgid "" "The expression ``obj.x`` looks up the attribute ``x`` in the chain of " "namespaces for ``obj``. If the search finds a descriptor outside of the " -"instance ``__dict__``, its :meth:`__get__` method is invoked according to " -"the precedence rules listed below." +"instance :attr:`~object.__dict__`, its :meth:`~object.__get__` method is " +"invoked according to the precedence rules listed below." msgstr "" +"A expressão ``obj.x`` procura o atributo ``x`` na cadeia de espaços de nomes " +"para ``obj``. Se a busca encontrar um descritor fora da instância :attr:" +"`~object.__dict__`, seu método :meth:`~object.__get__` é invocado de acordo " +"com as regras de precedência listadas abaixo." -#: ../../howto/descriptor.rst:565 +#: ../../howto/descriptor.rst:568 msgid "" "The details of invocation depend on whether ``obj`` is an object, class, or " "instance of super." msgstr "" +"Os detalhes da invocação dependem se ``obj`` é um objeto, classe ou " +"instância de super." -#: ../../howto/descriptor.rst:570 +#: ../../howto/descriptor.rst:573 msgid "Invocation from an instance" -msgstr "" +msgstr "Invocação de uma instância" -#: ../../howto/descriptor.rst:572 +#: ../../howto/descriptor.rst:575 msgid "" "Instance lookup scans through a chain of namespaces giving data descriptors " "the highest priority, followed by instance variables, then non-data " -"descriptors, then class variables, and lastly :meth:`__getattr__` if it is " -"provided." +"descriptors, then class variables, and lastly :meth:`~object.__getattr__` if " +"it is provided." msgstr "" +"A pesquisa de instância verifica uma cadeia de espaços de nomes, dando aos " +"descritores de dados a maior prioridade, seguidos por variáveis de " +"instância, depois descritores que não são de dados, depois variáveis de " +"classe e, por último, :meth:`~object.__getattr__`, se fornecido." -#: ../../howto/descriptor.rst:577 +#: ../../howto/descriptor.rst:580 msgid "" "If a descriptor is found for ``a.x``, then it is invoked with: ``desc." "__get__(a, type(a))``." msgstr "" +"Se um descritor for encontrado para ``a.x``, ele será invocado com: ``desc." +"__get__(a, type(a))``." -#: ../../howto/descriptor.rst:580 +#: ../../howto/descriptor.rst:583 msgid "" "The logic for a dotted lookup is in :meth:`object.__getattribute__`. Here " "is a pure Python equivalent:" msgstr "" - -#: ../../howto/descriptor.rst:719 -msgid "" -"Note, there is no :meth:`__getattr__` hook in the :meth:`__getattribute__` " -"code. That is why calling :meth:`__getattribute__` directly or with " -"``super().__getattribute__`` will bypass :meth:`__getattr__` entirely." -msgstr "" - -#: ../../howto/descriptor.rst:723 +"A lógica para uma pesquisa pontilhada está em :meth:`object." +"__getattribute__`. Aqui está um equivalente Python puro:" + +#: ../../howto/descriptor.rst:586 +msgid "" +"def find_name_in_mro(cls, name, default):\n" +" \"Emulate _PyType_Lookup() in Objects/typeobject.c\"\n" +" for base in cls.__mro__:\n" +" if name in vars(base):\n" +" return vars(base)[name]\n" +" return default\n" +"\n" +"def object_getattribute(obj, name):\n" +" \"Emulate PyObject_GenericGetAttr() in Objects/object.c\"\n" +" null = object()\n" +" objtype = type(obj)\n" +" cls_var = find_name_in_mro(objtype, name, null)\n" +" descr_get = getattr(type(cls_var), '__get__', null)\n" +" if descr_get is not null:\n" +" if (hasattr(type(cls_var), '__set__')\n" +" or hasattr(type(cls_var), '__delete__')):\n" +" return descr_get(cls_var, obj, objtype) # data descriptor\n" +" if hasattr(obj, '__dict__') and name in vars(obj):\n" +" return vars(obj)[name] # instance variable\n" +" if descr_get is not null:\n" +" return descr_get(cls_var, obj, objtype) # non-data " +"descriptor\n" +" if cls_var is not null:\n" +" return cls_var # class variable\n" +" raise AttributeError(name)" +msgstr "" +"def find_name_in_mro(cls, name, default):\n" +" \"Emulate _PyType_Lookup() in Objects/typeobject.c\"\n" +" for base in cls.__mro__:\n" +" if name in vars(base):\n" +" return vars(base)[name]\n" +" return default\n" +"\n" +"def object_getattribute(obj, name):\n" +" \"Emulate PyObject_GenericGetAttr() in Objects/object.c\"\n" +" null = object()\n" +" objtype = type(obj)\n" +" cls_var = find_name_in_mro(objtype, name, null)\n" +" descr_get = getattr(type(cls_var), '__get__', null)\n" +" if descr_get is not null:\n" +" if (hasattr(type(cls_var), '__set__')\n" +" or hasattr(type(cls_var), '__delete__')):\n" +" return descr_get(cls_var, obj, objtype) # descritor de " +"dados\n" +" if hasattr(obj, '__dict__') and name in vars(obj):\n" +" return vars(obj)[name] # variável de " +"instância\n" +" if descr_get is not null:\n" +" return descr_get(cls_var, obj, objtype) # descritor de não " +"dados\n" +" if cls_var is not null:\n" +" return cls_var # variável de " +"classe\n" +" raise AttributeError(name)" + +#: ../../howto/descriptor.rst:722 +msgid "" +"Note, there is no :meth:`~object.__getattr__` hook in the :meth:`~object." +"__getattribute__` code. That is why calling :meth:`~object." +"__getattribute__` directly or with ``super().__getattribute__`` will bypass :" +"meth:`~object.__getattr__` entirely." +msgstr "" +"Note que não há nenhum gancho :meth:`~object.__getattr__` no código :meth:" +"`~object.__getattribute__`. É por isso que chamar :meth:`~object." +"__getattribute__` diretamente ou com ``super().__getattribute__`` ignorará :" +"meth:`~object.__getattr__` completamente." + +#: ../../howto/descriptor.rst:726 msgid "" "Instead, it is the dot operator and the :func:`getattr` function that are " -"responsible for invoking :meth:`__getattr__` whenever :meth:" -"`__getattribute__` raises an :exc:`AttributeError`. Their logic is " +"responsible for invoking :meth:`~object.__getattr__` whenever :meth:`~object." +"__getattribute__` raises an :exc:`AttributeError`. Their logic is " "encapsulated in a helper function:" msgstr "" - -#: ../../howto/descriptor.rst:773 +"Em vez disso, é o operador ponto e a função :func:`getattr` que são " +"responsáveis por invocar :meth:`~object.__getattr__` sempre que :meth:" +"`~object.__getattribute__` levanta um :exc:`AttributeError`. A lógica deles " +"é encapsulada em uma função auxiliar:" + +#: ../../howto/descriptor.rst:731 +msgid "" +"def getattr_hook(obj, name):\n" +" \"Emulate slot_tp_getattr_hook() in Objects/typeobject.c\"\n" +" try:\n" +" return obj.__getattribute__(name)\n" +" except AttributeError:\n" +" if not hasattr(type(obj), '__getattr__'):\n" +" raise\n" +" return type(obj).__getattr__(obj, name) # __getattr__" +msgstr "" +"def getattr_hook(obj, name):\n" +" \"Emulate slot_tp_getattr_hook() in Objects/typeobject.c\"\n" +" try:\n" +" return obj.__getattribute__(name)\n" +" except AttributeError:\n" +" if not hasattr(type(obj), '__getattr__'):\n" +" raise\n" +" return type(obj).__getattr__(obj, name) # __getattr__" + +#: ../../howto/descriptor.rst:776 msgid "Invocation from a class" -msgstr "" +msgstr "Invocação de uma classe" -#: ../../howto/descriptor.rst:775 +#: ../../howto/descriptor.rst:778 msgid "" -"The logic for a dotted lookup such as ``A.x`` is in :meth:`type." -"__getattribute__`. The steps are similar to those for :meth:`object." +"The logic for a dotted lookup such as ``A.x`` is in :meth:`!type." +"__getattribute__`. The steps are similar to those for :meth:`!object." "__getattribute__` but the instance dictionary lookup is replaced by a search " "through the class's :term:`method resolution order`." msgstr "" +"A lógica para uma pesquisa pontilhada como ``A.x`` está em :meth:`!type." +"__getattribute__`. Os passos são similares aos de :meth:`!object." +"__getattribute__` mas a pesquisa do dicionário de instância é substituída " +"por uma pesquisa através da :term:`ordem de resolução de métodos` da classe." -#: ../../howto/descriptor.rst:780 +#: ../../howto/descriptor.rst:783 msgid "If a descriptor is found, it is invoked with ``desc.__get__(None, A)``." msgstr "" +"Se um descritor for encontrado, ele será invocado com ``desc.__get__(None, " +"A)``." -#: ../../howto/descriptor.rst:782 +#: ../../howto/descriptor.rst:785 msgid "" "The full C implementation can be found in :c:func:`!type_getattro` and :c:" "func:`!_PyType_Lookup` in :source:`Objects/typeobject.c`." msgstr "" +"A implementação completa em C pode ser encontrada em :c:func:`!" +"type_getattro` e :c:func:`!_PyType_Lookup` em :source:`Objects/typeobject.c`." -#: ../../howto/descriptor.rst:787 +#: ../../howto/descriptor.rst:790 msgid "Invocation from super" -msgstr "" +msgstr "Invocação de super" -#: ../../howto/descriptor.rst:789 +#: ../../howto/descriptor.rst:792 msgid "" -"The logic for super's dotted lookup is in the :meth:`__getattribute__` " -"method for object returned by :func:`super`." +"The logic for super's dotted lookup is in the :meth:`~object." +"__getattribute__` method for object returned by :func:`super`." msgstr "" +"A lógica para a pesquisa pontilhada de super está no método :meth:`~object." +"__getattribute__` para o objeto retornado por :func:`super`." -#: ../../howto/descriptor.rst:792 +#: ../../howto/descriptor.rst:795 msgid "" "A dotted lookup such as ``super(A, obj).m`` searches ``obj.__class__." "__mro__`` for the base class ``B`` immediately following ``A`` and then " "returns ``B.__dict__['m'].__get__(obj, A)``. If not a descriptor, ``m`` is " "returned unchanged." msgstr "" +"Uma pesquisa pontilhada como ``super(A, obj).m`` pesquisa ``obj.__class__." +"__mro__`` para a classe base ``B`` imediatamente após ``A`` e então retorna " +"``B.__dict__['m'].__get__(obj, A)``. Se não for um descritor, ``m`` é " +"retornado inalterado." -#: ../../howto/descriptor.rst:797 +#: ../../howto/descriptor.rst:800 msgid "" "The full C implementation can be found in :c:func:`!super_getattro` in :" "source:`Objects/typeobject.c`. A pure Python equivalent can be found in " "`Guido's Tutorial `_." msgstr "" +"A implementação completa em C pode ser encontrada em :c:func:`!" +"super_getattro` em :source:`Objects/typeobject.c`. Um equivalente em Python " +"puro pode ser encontrado no `Tutorial do Guido `_." -#: ../../howto/descriptor.rst:804 +#: ../../howto/descriptor.rst:807 msgid "Summary of invocation logic" -msgstr "" +msgstr "Resumo da lógica de invocação" -#: ../../howto/descriptor.rst:806 +#: ../../howto/descriptor.rst:809 msgid "" -"The mechanism for descriptors is embedded in the :meth:`__getattribute__()` " -"methods for :class:`object`, :class:`type`, and :func:`super`." +"The mechanism for descriptors is embedded in the :meth:`~object." +"__getattribute__` methods for :class:`object`, :class:`type`, and :func:" +"`super`." msgstr "" +"O mecanismo para descritores está incorporado nos métodos :meth:`~object." +"__getattribute__` para :class:`object`, :class:`type` e :func:`super`." -#: ../../howto/descriptor.rst:809 +#: ../../howto/descriptor.rst:812 msgid "The important points to remember are:" -msgstr "" +msgstr "Os pontos importantes para lembrar são:" -#: ../../howto/descriptor.rst:811 -msgid "Descriptors are invoked by the :meth:`__getattribute__` method." +#: ../../howto/descriptor.rst:814 +msgid "Descriptors are invoked by the :meth:`~object.__getattribute__` method." msgstr "" +"Descritores são invocados pelo método :meth:`~object.__getattribute__`." -#: ../../howto/descriptor.rst:813 +#: ../../howto/descriptor.rst:816 msgid "" "Classes inherit this machinery from :class:`object`, :class:`type`, or :func:" "`super`." msgstr "" +"As classes herdam esse maquinário de :class:`object`, :class:`type` ou :func:" +"`super`." -#: ../../howto/descriptor.rst:816 +#: ../../howto/descriptor.rst:819 msgid "" -"Overriding :meth:`__getattribute__` prevents automatic descriptor calls " -"because all the descriptor logic is in that method." +"Overriding :meth:`~object.__getattribute__` prevents automatic descriptor " +"calls because all the descriptor logic is in that method." msgstr "" +"Substituir :meth:`~object.__getattribute__` impede chamadas automáticas do " +"descritor porque toda a lógica do descritor está nesse método." -#: ../../howto/descriptor.rst:819 +#: ../../howto/descriptor.rst:822 msgid "" -":meth:`object.__getattribute__` and :meth:`type.__getattribute__` make " -"different calls to :meth:`__get__`. The first includes the instance and may " -"include the class. The second puts in ``None`` for the instance and always " -"includes the class." +":meth:`!object.__getattribute__` and :meth:`!type.__getattribute__` make " +"different calls to :meth:`~object.__get__`. The first includes the instance " +"and may include the class. The second puts in ``None`` for the instance and " +"always includes the class." msgstr "" +":meth:`!object.__getattribute__` e :meth:`!type.__getattribute__` fazem " +"chamadas diferentes para :meth:`~object.__get__`. O primeiro inclui a " +"instância e pode incluir a classe. O segundo coloca ``None`` para a " +"instância e sempre inclui a classe." -#: ../../howto/descriptor.rst:824 +#: ../../howto/descriptor.rst:827 msgid "Data descriptors always override instance dictionaries." -msgstr "" +msgstr "Os descritores de dados sempre substituem os dicionários de instância." -#: ../../howto/descriptor.rst:826 +#: ../../howto/descriptor.rst:829 msgid "Non-data descriptors may be overridden by instance dictionaries." msgstr "" +"Descritores de não-dados podem ser substituídos pelos dicionários de " +"instância." -#: ../../howto/descriptor.rst:830 +#: ../../howto/descriptor.rst:833 msgid "Automatic name notification" -msgstr "" +msgstr "Notificação automática de nome" -#: ../../howto/descriptor.rst:832 +#: ../../howto/descriptor.rst:835 msgid "" "Sometimes it is desirable for a descriptor to know what class variable name " "it was assigned to. When a new class is created, the :class:`type` " "metaclass scans the dictionary of the new class. If any of the entries are " -"descriptors and if they define :meth:`__set_name__`, that method is called " -"with two arguments. The *owner* is the class where the descriptor is used, " -"and the *name* is the class variable the descriptor was assigned to." +"descriptors and if they define :meth:`~object.__set_name__`, that method is " +"called with two arguments. The *owner* is the class where the descriptor is " +"used, and the *name* is the class variable the descriptor was assigned to." msgstr "" +"Às vezes, é desejável que um descritor saiba a qual nome de variável de " +"classe ele foi atribuído. Quando uma nova classe é criada, a metaclasse :" +"class:`type` varre o dicionário da nova classe. Se qualquer uma das entradas " +"for descritor e se eles definirem :meth:`~object.__set_name__`, esse método " +"será chamado com dois argumentos. O *owner* é a classe onde o descritor é " +"usado, e o *name* é a variável de classe à qual o descritor foi atribuído." -#: ../../howto/descriptor.rst:839 +#: ../../howto/descriptor.rst:842 msgid "" "The implementation details are in :c:func:`!type_new` and :c:func:`!" "set_names` in :source:`Objects/typeobject.c`." msgstr "" +"Os detalhes de implementações estão em :c:func:`!type_new` e :c:func:`!" +"set_names` em :source:`Objects/typeobject.c`." -#: ../../howto/descriptor.rst:842 +#: ../../howto/descriptor.rst:845 msgid "" -"Since the update logic is in :meth:`type.__new__`, notifications only take " +"Since the update logic is in :meth:`!type.__new__`, notifications only take " "place at the time of class creation. If descriptors are added to the class " -"afterwards, :meth:`__set_name__` will need to be called manually." +"afterwards, :meth:`~object.__set_name__` will need to be called manually." msgstr "" +"Como a lógica de atualização está em :meth:`!type.__new__`, as notificações " +"só ocorrem no momento da criação da classe. Se descritores forem adicionados " +"à classe posteriormente, :meth:`~object.__set_name__` precisará ser chamado " +"manualmente." -#: ../../howto/descriptor.rst:848 +#: ../../howto/descriptor.rst:851 msgid "ORM example" -msgstr "" +msgstr "Exemplo de ORM" -#: ../../howto/descriptor.rst:850 +#: ../../howto/descriptor.rst:853 msgid "" "The following code is a simplified skeleton showing how data descriptors " "could be used to implement an `object relational mapping `_." msgstr "" +"O código a seguir é um esqueleto simplificado que mostra como os descritores " +"de dados podem ser usados para implementar um `mapeamento relacional de " +"objetos `_." -#: ../../howto/descriptor.rst:854 +#: ../../howto/descriptor.rst:857 msgid "" "The essential idea is that the data is stored in an external database. The " "Python instances only hold keys to the database's tables. Descriptors take " "care of lookups or updates:" msgstr "" - -#: ../../howto/descriptor.rst:873 -msgid "" -"We can use the :class:`Field` class to define `models `_ that describe the schema for each table in a " "database:" msgstr "" - -#: ../../howto/descriptor.rst:898 +"Podemos usar a classe :class:`!Field` para definir `modelos `_ que descrevem o esquema de cada tabela " +"em um banco de dados:" + +#: ../../howto/descriptor.rst:880 +msgid "" +"class Movie:\n" +" table = 'Movies' # Table name\n" +" key = 'title' # Primary key\n" +" director = Field()\n" +" year = Field()\n" +"\n" +" def __init__(self, key):\n" +" self.key = key\n" +"\n" +"class Song:\n" +" table = 'Music'\n" +" key = 'title'\n" +" artist = Field()\n" +" year = Field()\n" +" genre = Field()\n" +"\n" +" def __init__(self, key):\n" +" self.key = key" +msgstr "" +"class Movie:\n" +" table = 'Movies' # Nome da tabela\n" +" key = 'title' # Chave primária\n" +" director = Field()\n" +" year = Field()\n" +"\n" +" def __init__(self, key):\n" +" self.key = key\n" +"\n" +"class Song:\n" +" table = 'Music'\n" +" key = 'title'\n" +" artist = Field()\n" +" year = Field()\n" +" genre = Field()\n" +"\n" +" def __init__(self, key):\n" +" self.key = key" + +#: ../../howto/descriptor.rst:901 msgid "To use the models, first connect to the database::" -msgstr "" +msgstr "Para usar os modelos, primeiro conecte ao banco de dados::" #: ../../howto/descriptor.rst:903 msgid "" +">>> import sqlite3\n" +">>> conn = sqlite3.connect('entertainment.db')" +msgstr "" +">>> import sqlite3\n" +">>> conn = sqlite3.connect('entertainment.db')" + +#: ../../howto/descriptor.rst:906 +msgid "" "An interactive session shows how data is retrieved from the database and how " "it can be updated:" msgstr "" - -#: ../../howto/descriptor.rst:952 +"Uma sessão interativa mostra como os dados são recuperados do banco de dados " +"e como eles podem ser atualizados:" + +#: ../../howto/descriptor.rst:934 +msgid "" +">>> Movie('Star Wars').director\n" +"'George Lucas'\n" +">>> jaws = Movie('Jaws')\n" +">>> f'Released in {jaws.year} by {jaws.director}'\n" +"'Released in 1975 by Steven Spielberg'\n" +"\n" +">>> Song('Country Roads').artist\n" +"'John Denver'\n" +"\n" +">>> Movie('Star Wars').director = 'J.J. Abrams'\n" +">>> Movie('Star Wars').director\n" +"'J.J. Abrams'" +msgstr "" +">>> Movie('Star Wars').director\n" +"'George Lucas'\n" +">>> jaws = Movie('Jaws')\n" +">>> f'Released in {jaws.year} by {jaws.director}'\n" +"'Released in 1975 by Steven Spielberg'\n" +"\n" +">>> Song('Country Roads').artist\n" +"'John Denver'\n" +"\n" +">>> Movie('Star Wars').director = 'J.J. Abrams'\n" +">>> Movie('Star Wars').director\n" +"'J.J. Abrams'" + +#: ../../howto/descriptor.rst:955 msgid "Pure Python Equivalents" -msgstr "" +msgstr "Equivalentes de Python puro" -#: ../../howto/descriptor.rst:954 +#: ../../howto/descriptor.rst:957 msgid "" "The descriptor protocol is simple and offers exciting possibilities. " "Several use cases are so common that they have been prepackaged into built-" "in tools. Properties, bound methods, static methods, class methods, and " "\\_\\_slots\\_\\_ are all based on the descriptor protocol." msgstr "" +"O protocolo descritor é simples e oferece possibilidades interessantes. " +"Vários casos de uso são tão comuns que foram pré-empacotados em ferramentas " +"embutidas. Propriedades, métodos vinculados, métodos estáticos, métodos de " +"classe e \\_\\_slots\\_\\_ são todos baseados no protocolo descritor." -#: ../../howto/descriptor.rst:961 +#: ../../howto/descriptor.rst:964 msgid "Properties" msgstr "Propriedades" -#: ../../howto/descriptor.rst:963 +#: ../../howto/descriptor.rst:966 msgid "" "Calling :func:`property` is a succinct way of building a data descriptor " "that triggers a function call upon access to an attribute. Its signature " "is::" msgstr "" +"Chamar :func:`property` é uma maneira sucinta de construir um descritor de " +"dados que dispara uma chamada de função ao acessar um atributo. Sua " +"assinatura é::" -#: ../../howto/descriptor.rst:968 +#: ../../howto/descriptor.rst:969 +msgid "property(fget=None, fset=None, fdel=None, doc=None) -> property" +msgstr "property(fget=None, fset=None, fdel=None, doc=None) -> property" + +#: ../../howto/descriptor.rst:971 msgid "" "The documentation shows a typical use to define a managed attribute ``x``:" msgstr "" +"A documentação mostra um uso típico para definir um atributo gerenciado " +"``x``:" -#: ../../howto/descriptor.rst:992 +#: ../../howto/descriptor.rst:973 msgid "" -"To see how :func:`property` is implemented in terms of the descriptor " -"protocol, here is a pure Python equivalent:" +"class C:\n" +" def getx(self): return self.__x\n" +" def setx(self, value): self.__x = value\n" +" def delx(self): del self.__x\n" +" x = property(getx, setx, delx, \"I'm the 'x' property.\")" msgstr "" +"class C:\n" +" def getx(self): return self.__x\n" +" def setx(self, value): self.__x = value\n" +" def delx(self): del self.__x\n" +" x = property(getx, setx, delx, \"I'm the 'x' property.\")" -#: ../../howto/descriptor.rst:1143 +#: ../../howto/descriptor.rst:995 +msgid "" +"To see how :func:`property` is implemented in terms of the descriptor " +"protocol, here is a pure Python equivalent that implements most of the core " +"functionality:" +msgstr "" +"Para ver como :func:`property` é implementada em termos do protocolo " +"descritor, aqui está um equivalente Python puro que implementa a maior parte " +"da funcionalidade principal:" + +#: ../../howto/descriptor.rst:998 +msgid "" +"class Property:\n" +" \"Emulate PyProperty_Type() in Objects/descrobject.c\"\n" +"\n" +" def __init__(self, fget=None, fset=None, fdel=None, doc=None):\n" +" self.fget = fget\n" +" self.fset = fset\n" +" self.fdel = fdel\n" +" if doc is None and fget is not None:\n" +" doc = fget.__doc__\n" +" self.__doc__ = doc\n" +"\n" +" def __set_name__(self, owner, name):\n" +" self.__name__ = name\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" if obj is None:\n" +" return self\n" +" if self.fget is None:\n" +" raise AttributeError\n" +" return self.fget(obj)\n" +"\n" +" def __set__(self, obj, value):\n" +" if self.fset is None:\n" +" raise AttributeError\n" +" self.fset(obj, value)\n" +"\n" +" def __delete__(self, obj):\n" +" if self.fdel is None:\n" +" raise AttributeError\n" +" self.fdel(obj)\n" +"\n" +" def getter(self, fget):\n" +" return type(self)(fget, self.fset, self.fdel, self.__doc__)\n" +"\n" +" def setter(self, fset):\n" +" return type(self)(self.fget, fset, self.fdel, self.__doc__)\n" +"\n" +" def deleter(self, fdel):\n" +" return type(self)(self.fget, self.fset, fdel, self.__doc__)" +msgstr "" +"class Property:\n" +" \"Emulate PyProperty_Type() in Objects/descrobject.c\"\n" +"\n" +" def __init__(self, fget=None, fset=None, fdel=None, doc=None):\n" +" self.fget = fget\n" +" self.fset = fset\n" +" self.fdel = fdel\n" +" if doc is None and fget is not None:\n" +" doc = fget.__doc__\n" +" self.__doc__ = doc\n" +"\n" +" def __set_name__(self, owner, name):\n" +" self.__name__ = name\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" if obj is None:\n" +" return self\n" +" if self.fget is None:\n" +" raise AttributeError\n" +" return self.fget(obj)\n" +"\n" +" def __set__(self, obj, value):\n" +" if self.fset is None:\n" +" raise AttributeError\n" +" self.fset(obj, value)\n" +"\n" +" def __delete__(self, obj):\n" +" if self.fdel is None:\n" +" raise AttributeError\n" +" self.fdel(obj)\n" +"\n" +" def getter(self, fget):\n" +" return type(self)(fget, self.fset, self.fdel, self.__doc__)\n" +"\n" +" def setter(self, fset):\n" +" return type(self)(self.fget, fset, self.fdel, self.__doc__)\n" +"\n" +" def deleter(self, fdel):\n" +" return type(self)(self.fget, self.fset, fdel, self.__doc__)" + +#: ../../howto/descriptor.rst:1122 msgid "" "The :func:`property` builtin helps whenever a user interface has granted " "attribute access and then subsequent changes require the intervention of a " "method." msgstr "" +"O recurso embutido :func:`property` ajuda sempre que uma interface de " +"usuário concede acesso a atributos e alterações subsequentes exigem a " +"intervenção de um método." -#: ../../howto/descriptor.rst:1147 +#: ../../howto/descriptor.rst:1126 msgid "" "For instance, a spreadsheet class may grant access to a cell value through " "``Cell('b10').value``. Subsequent improvements to the program require the " @@ -808,153 +1805,352 @@ msgid "" "solution is to wrap access to the value attribute in a property data " "descriptor:" msgstr "" +"Por exemplo, uma classe de planilha pode conceder acesso a um valor de " +"célula por meio de ``Cell('b10').value``. Melhorias subsequentes no programa " +"exigem que a célula seja recalculada em cada acesso; no entanto, o " +"programador não quer afetar o código do cliente existente acessando o " +"atributo diretamente. A solução é encapsular o acesso ao atributo de valor " +"em um descritor de dados de propriedade:" + +#: ../../howto/descriptor.rst:1132 +msgid "" +"class Cell:\n" +" ...\n" +"\n" +" @property\n" +" def value(self):\n" +" \"Recalculate the cell before returning value\"\n" +" self.recalc()\n" +" return self._value" +msgstr "" +"class Cell:\n" +" ...\n" +"\n" +" @property\n" +" def value(self):\n" +" \"Recalculate the cell before returning value\"\n" +" self.recalc()\n" +" return self._value" -#: ../../howto/descriptor.rst:1164 +#: ../../howto/descriptor.rst:1143 msgid "" -"Either the built-in :func:`property` or our :func:`Property` equivalent " +"Either the built-in :func:`property` or our :func:`!Property` equivalent " "would work in this example." msgstr "" +"Tanto o :func:`property` embutida quanto nosso equivalente :func:`!Property` " +"funcionariam neste exemplo." -#: ../../howto/descriptor.rst:1169 +#: ../../howto/descriptor.rst:1148 msgid "Functions and methods" -msgstr "" +msgstr "Funções e métodos" -#: ../../howto/descriptor.rst:1171 +#: ../../howto/descriptor.rst:1150 msgid "" "Python's object oriented features are built upon a function based " "environment. Using non-data descriptors, the two are merged seamlessly." msgstr "" +"Os recursos orientados a objetos do Python são construídos sobre um ambiente " +"baseado em funções. Usando descritores de não-dados, os dois são mesclados " +"perfeitamente." -#: ../../howto/descriptor.rst:1174 +#: ../../howto/descriptor.rst:1153 msgid "" "Functions stored in class dictionaries get turned into methods when invoked. " "Methods only differ from regular functions in that the object instance is " "prepended to the other arguments. By convention, the instance is called " "*self* but could be called *this* or any other variable name." msgstr "" +"Funções armazenadas em dicionários de classe são transformadas em métodos " +"quando invocadas. Métodos diferem de funções regulares apenas porque a " +"instância do objeto é prefixada aos outros argumentos. Por convenção, a " +"instância é chamada *self*, mas poderia ser chamada *this* ou qualquer outro " +"nome de variável.trabalhar" -#: ../../howto/descriptor.rst:1179 +#: ../../howto/descriptor.rst:1158 msgid "" "Methods can be created manually with :class:`types.MethodType` which is " "roughly equivalent to:" msgstr "" - -#: ../../howto/descriptor.rst:1210 +"Os métodos podem ser criados manualmente com :class:`types.MethodType`, que " +"é aproximadamente equivalente a:" + +#: ../../howto/descriptor.rst:1161 +msgid "" +"class MethodType:\n" +" \"Emulate PyMethod_Type in Objects/classobject.c\"\n" +"\n" +" def __init__(self, func, obj):\n" +" self.__func__ = func\n" +" self.__self__ = obj\n" +"\n" +" def __call__(self, *args, **kwargs):\n" +" func = self.__func__\n" +" obj = self.__self__\n" +" return func(obj, *args, **kwargs)\n" +"\n" +" def __getattribute__(self, name):\n" +" \"Emulate method_getset() in Objects/classobject.c\"\n" +" if name == '__doc__':\n" +" return self.__func__.__doc__\n" +" return object.__getattribute__(self, name)\n" +"\n" +" def __getattr__(self, name):\n" +" \"Emulate method_getattro() in Objects/classobject.c\"\n" +" return getattr(self.__func__, name)\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" \"Emulate method_descr_get() in Objects/classobject.c\"\n" +" return self" +msgstr "" +"class MethodType:\n" +" \"Emulate PyMethod_Type in Objects/classobject.c\"\n" +"\n" +" def __init__(self, func, obj):\n" +" self.__func__ = func\n" +" self.__self__ = obj\n" +"\n" +" def __call__(self, *args, **kwargs):\n" +" func = self.__func__\n" +" obj = self.__self__\n" +" return func(obj, *args, **kwargs)\n" +"\n" +" def __getattribute__(self, name):\n" +" \"Emulate method_getset() in Objects/classobject.c\"\n" +" if name == '__doc__':\n" +" return self.__func__.__doc__\n" +" return object.__getattribute__(self, name)\n" +"\n" +" def __getattr__(self, name):\n" +" \"Emulate method_getattro() in Objects/classobject.c\"\n" +" return getattr(self.__func__, name)\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" \"Emulate method_descr_get() in Objects/classobject.c\"\n" +" return self" + +#: ../../howto/descriptor.rst:1189 msgid "" "To support automatic creation of methods, functions include the :meth:" -"`__get__` method for binding methods during attribute access. This means " -"that functions are non-data descriptors that return bound methods during " -"dotted lookup from an instance. Here's how it works:" -msgstr "" - -#: ../../howto/descriptor.rst:1226 +"`~object.__get__` method for binding methods during attribute access. This " +"means that functions are non-data descriptors that return bound methods " +"during dotted lookup from an instance. Here's how it works:" +msgstr "" +"Para dar suporte à criação automática de métodos, as funções incluem o " +"método :meth:`~object.__get__` para vincular métodos durante o acesso ao " +"atributo. Isso significa que as funções são descritores de não-dados que " +"retornam métodos vinculados durante a pesquisa pontilhada de uma instância. " +"Veja como funciona:" + +#: ../../howto/descriptor.rst:1194 +msgid "" +"class Function:\n" +" ...\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" \"Simulate func_descr_get() in Objects/funcobject.c\"\n" +" if obj is None:\n" +" return self\n" +" return MethodType(self, obj)" +msgstr "" +"class Function:\n" +" ...\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" \"Simulate func_descr_get() in Objects/funcobject.c\"\n" +" if obj is None:\n" +" return self\n" +" return MethodType(self, obj)" + +#: ../../howto/descriptor.rst:1205 msgid "" "Running the following class in the interpreter shows how the function " "descriptor works in practice:" msgstr "" +"A execução da classe a seguir no interpretador mostra como o descritor de " +"função funciona na prática:" + +#: ../../howto/descriptor.rst:1208 +msgid "" +"class D:\n" +" def f(self):\n" +" return self\n" +"\n" +"class D2:\n" +" pass" +msgstr "" +"class D:\n" +" def f(self):\n" +" return self\n" +"\n" +"class D2:\n" +" pass" -#: ../../howto/descriptor.rst:1247 +#: ../../howto/descriptor.rst:1226 msgid "" "The function has a :term:`qualified name` attribute to support introspection:" msgstr "" +"A função tem um atributo :term:`nome qualificado` para dar suporte à " +"introspecção:" + +#: ../../howto/descriptor.rst:1228 +msgid "" +">>> D.f.__qualname__\n" +"'D.f'" +msgstr "" +">>> D.f.__qualname__\n" +"'D.f'" -#: ../../howto/descriptor.rst:1254 +#: ../../howto/descriptor.rst:1233 msgid "" "Accessing the function through the class dictionary does not invoke :meth:" -"`__get__`. Instead, it just returns the underlying function object::" +"`~object.__get__`. Instead, it just returns the underlying function object::" msgstr "" +"Acessar a função por meio do dicionário de classes não invoca :meth:`~object." +"__get__`. Em vez disso, ele apenas retorna o objeto da função subjacente::" -#: ../../howto/descriptor.rst:1260 +#: ../../howto/descriptor.rst:1236 msgid "" -"Dotted access from a class calls :meth:`__get__` which just returns the " -"underlying function unchanged::" +">>> D.__dict__['f']\n" +"" msgstr "" +">>> D.__dict__['f']\n" +"" -#: ../../howto/descriptor.rst:1266 +#: ../../howto/descriptor.rst:1239 +msgid "" +"Dotted access from a class calls :meth:`~object.__get__` which just returns " +"the underlying function unchanged::" +msgstr "" +"O acesso pontilhado de uma classe chama :meth:`~object.__get__` que apenas " +"retorna a função subjacente inalterada::" + +#: ../../howto/descriptor.rst:1242 +msgid "" +">>> D.f\n" +"" +msgstr "" +">>> D.f\n" +"" + +#: ../../howto/descriptor.rst:1245 msgid "" "The interesting behavior occurs during dotted access from an instance. The " -"dotted lookup calls :meth:`__get__` which returns a bound method object::" +"dotted lookup calls :meth:`~object.__get__` which returns a bound method " +"object::" +msgstr "" +"O comportamento interessante ocorre durante o acesso pontuado de uma " +"instância. A pesquisa pontilhada chama :meth:`~object.__get__` que retorna " +"um objeto do método vinculado::" + +#: ../../howto/descriptor.rst:1248 +msgid "" +">>> d = D()\n" +">>> d.f\n" +">" msgstr "" +">>> d = D()\n" +">>> d.f\n" +">" -#: ../../howto/descriptor.rst:1273 +#: ../../howto/descriptor.rst:1252 msgid "" "Internally, the bound method stores the underlying function and the bound " "instance::" msgstr "" +"Internamente, o método vinculado armazena a função subjacente e a instância " +"vinculada::" -#: ../../howto/descriptor.rst:1282 +#: ../../howto/descriptor.rst:1255 +msgid "" +">>> d.f.__func__\n" +"\n" +"\n" +">>> d.f.__self__\n" +"<__main__.D object at 0x00B18C90>" +msgstr "" +">>> d.f.__func__\n" +"\n" +"\n" +">>> d.f.__self__\n" +"<__main__.D object at 0x00B18C90>" + +#: ../../howto/descriptor.rst:1261 msgid "" "If you have ever wondered where *self* comes from in regular methods or " "where *cls* comes from in class methods, this is it!" msgstr "" +"Se você já se perguntou de onde vem *self* em métodos regulares ou de onde " +"vem *cls* em métodos de classe, é isso!" -#: ../../howto/descriptor.rst:1287 +#: ../../howto/descriptor.rst:1266 msgid "Kinds of methods" -msgstr "" +msgstr "Tipos de métodos" -#: ../../howto/descriptor.rst:1289 +#: ../../howto/descriptor.rst:1268 msgid "" "Non-data descriptors provide a simple mechanism for variations on the usual " "patterns of binding functions into methods." msgstr "" +"Descritores de não-dados fornecem um mecanismo simples para variações nos " +"padrões usuais de vinculação de funções em métodos." -#: ../../howto/descriptor.rst:1292 +#: ../../howto/descriptor.rst:1271 msgid "" -"To recap, functions have a :meth:`__get__` method so that they can be " -"converted to a method when accessed as attributes. The non-data descriptor " -"transforms an ``obj.f(*args)`` call into ``f(obj, *args)``. Calling ``cls." -"f(*args)`` becomes ``f(*args)``." +"To recap, functions have a :meth:`~object.__get__` method so that they can " +"be converted to a method when accessed as attributes. The non-data " +"descriptor transforms an ``obj.f(*args)`` call into ``f(obj, *args)``. " +"Calling ``cls.f(*args)`` becomes ``f(*args)``." msgstr "" -#: ../../howto/descriptor.rst:1297 +#: ../../howto/descriptor.rst:1276 msgid "This chart summarizes the binding and its two most useful variants:" -msgstr "" +msgstr "Este gráfico resume a ligação e suas duas variantes mais úteis:" -#: ../../howto/descriptor.rst:1300 +#: ../../howto/descriptor.rst:1279 msgid "Transformation" msgstr "Transformação" -#: ../../howto/descriptor.rst:1300 +#: ../../howto/descriptor.rst:1279 msgid "Called from an object" -msgstr "" +msgstr "Chamada de um objeto" -#: ../../howto/descriptor.rst:1300 +#: ../../howto/descriptor.rst:1279 msgid "Called from a class" -msgstr "" +msgstr "Chamada de uma classe" -#: ../../howto/descriptor.rst:1303 +#: ../../howto/descriptor.rst:1282 msgid "function" msgstr "função" -#: ../../howto/descriptor.rst:1303 +#: ../../howto/descriptor.rst:1282 msgid "f(obj, \\*args)" msgstr "f(obj, \\*args)" -#: ../../howto/descriptor.rst:1303 ../../howto/descriptor.rst:1305 +#: ../../howto/descriptor.rst:1282 ../../howto/descriptor.rst:1284 msgid "f(\\*args)" msgstr "f(\\*args)" -#: ../../howto/descriptor.rst:1305 +#: ../../howto/descriptor.rst:1284 msgid "staticmethod" msgstr "staticmethod" -#: ../../howto/descriptor.rst:1307 +#: ../../howto/descriptor.rst:1286 msgid "classmethod" msgstr "classmethod" -#: ../../howto/descriptor.rst:1307 +#: ../../howto/descriptor.rst:1286 msgid "f(type(obj), \\*args)" msgstr "f(type(obj), \\*args)" -#: ../../howto/descriptor.rst:1307 +#: ../../howto/descriptor.rst:1286 msgid "f(cls, \\*args)" -msgstr "" +msgstr "f(cls, \\*args)" -#: ../../howto/descriptor.rst:1312 +#: ../../howto/descriptor.rst:1291 msgid "Static methods" -msgstr "" +msgstr "Métodos estáticos" -#: ../../howto/descriptor.rst:1314 +#: ../../howto/descriptor.rst:1293 msgid "" "Static methods return the underlying function without changes. Calling " "either ``c.f`` or ``C.f`` is the equivalent of a direct lookup into ``object." @@ -963,13 +2159,13 @@ msgid "" "a class." msgstr "" -#: ../../howto/descriptor.rst:1320 +#: ../../howto/descriptor.rst:1299 msgid "" "Good candidates for static methods are methods that do not reference the " "``self`` variable." msgstr "" -#: ../../howto/descriptor.rst:1323 +#: ../../howto/descriptor.rst:1302 msgid "" "For instance, a statistics package may include a container class for " "experimental data. The class provides normal methods for computing the " @@ -978,22 +2174,64 @@ msgid "" "but do not depend on the data. For instance, ``erf(x)`` is handy conversion " "routine that comes up in statistical work but does not directly depend on a " "particular dataset. It can be called either from an object or the class: " -"``s.erf(1.5) --> .9332`` or ``Sample.erf(1.5) --> .9332``." +"``s.erf(1.5) --> 0.9332`` or ``Sample.erf(1.5) --> 0.9332``." msgstr "" -#: ../../howto/descriptor.rst:1332 +#: ../../howto/descriptor.rst:1311 msgid "" "Since static methods return the underlying function with no changes, the " "example calls are unexciting:" msgstr "" -#: ../../howto/descriptor.rst:1349 +#: ../../howto/descriptor.rst:1314 +msgid "" +"class E:\n" +" @staticmethod\n" +" def f(x):\n" +" return x * 10" +msgstr "" +"class E:\n" +" @staticmethod\n" +" def f(x):\n" +" return x * 10" + +#: ../../howto/descriptor.rst:1321 +msgid "" +">>> E.f(3)\n" +"30\n" +">>> E().f(3)\n" +"30" +msgstr "" +">>> E.f(3)\n" +"30\n" +">>> E().f(3)\n" +"30" + +#: ../../howto/descriptor.rst:1328 msgid "" "Using the non-data descriptor protocol, a pure Python version of :func:" "`staticmethod` would look like this:" msgstr "" -#: ../../howto/descriptor.rst:1369 +#: ../../howto/descriptor.rst:1331 +msgid "" +"import functools\n" +"\n" +"class StaticMethod:\n" +" \"Emulate PyStaticMethod_Type() in Objects/funcobject.c\"\n" +"\n" +" def __init__(self, f):\n" +" self.f = f\n" +" functools.update_wrapper(self, f)\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" return self.f\n" +"\n" +" def __call__(self, *args, **kwds):\n" +" return self.f(*args, **kwds)" +msgstr "" + +#: ../../howto/descriptor.rst:1348 msgid "" "The :func:`functools.update_wrapper` call adds a ``__wrapped__`` attribute " "that refers to the underlying function. Also it carries forward the " @@ -1002,18 +2240,42 @@ msgid "" "__doc__`, and :attr:`~function.__annotations__`." msgstr "" -#: ../../howto/descriptor.rst:1438 +#: ../../howto/descriptor.rst:1417 msgid "Class methods" -msgstr "" +msgstr "Métodos de classe" -#: ../../howto/descriptor.rst:1440 +#: ../../howto/descriptor.rst:1419 msgid "" "Unlike static methods, class methods prepend the class reference to the " "argument list before calling the function. This format is the same for " "whether the caller is an object or a class:" msgstr "" -#: ../../howto/descriptor.rst:1458 +#: ../../howto/descriptor.rst:1423 +msgid "" +"class F:\n" +" @classmethod\n" +" def f(cls, x):\n" +" return cls.__name__, x" +msgstr "" +"class F:\n" +" @classmethod\n" +" def f(cls, x):\n" +" return cls.__name__, x" + +#: ../../howto/descriptor.rst:1430 +msgid "" +">>> F.f(3)\n" +"('F', 3)\n" +">>> F().f(3)\n" +"('F', 3)" +msgstr "" +">>> F.f(3)\n" +"('F', 3)\n" +">>> F().f(3)\n" +"('F', 3)" + +#: ../../howto/descriptor.rst:1437 msgid "" "This behavior is useful whenever the method only needs to have a class " "reference and does not rely on data stored in a specific instance. One use " @@ -1022,17 +2284,55 @@ msgid "" "of keys. The pure Python equivalent is:" msgstr "" -#: ../../howto/descriptor.rst:1475 +#: ../../howto/descriptor.rst:1443 +msgid "" +"class Dict(dict):\n" +" @classmethod\n" +" def fromkeys(cls, iterable, value=None):\n" +" \"Emulate dict_fromkeys() in Objects/dictobject.c\"\n" +" d = cls()\n" +" for key in iterable:\n" +" d[key] = value\n" +" return d" +msgstr "" + +#: ../../howto/descriptor.rst:1454 msgid "Now a new dictionary of unique keys can be constructed like this:" msgstr "" -#: ../../howto/descriptor.rst:1485 +#: ../../howto/descriptor.rst:1456 +msgid "" +">>> d = Dict.fromkeys('abracadabra')\n" +">>> type(d) is Dict\n" +"True\n" +">>> d\n" +"{'a': None, 'b': None, 'r': None, 'c': None, 'd': None}" +msgstr "" + +#: ../../howto/descriptor.rst:1464 msgid "" "Using the non-data descriptor protocol, a pure Python version of :func:" "`classmethod` would look like this:" msgstr "" -#: ../../howto/descriptor.rst:1550 +#: ../../howto/descriptor.rst:1467 +msgid "" +"import functools\n" +"\n" +"class ClassMethod:\n" +" \"Emulate PyClassMethod_Type() in Objects/funcobject.c\"\n" +"\n" +" def __init__(self, f):\n" +" self.f = f\n" +" functools.update_wrapper(self, f)\n" +"\n" +" def __get__(self, obj, cls=None):\n" +" if cls is None:\n" +" cls = type(obj)\n" +" return MethodType(self.f, cls)" +msgstr "" + +#: ../../howto/descriptor.rst:1529 msgid "" "The :func:`functools.update_wrapper` call in ``ClassMethod`` adds a " "``__wrapped__`` attribute that refers to the underlying function. Also it " @@ -1042,30 +2342,80 @@ msgid "" "__annotations__`." msgstr "" -#: ../../howto/descriptor.rst:1559 +#: ../../howto/descriptor.rst:1538 msgid "Member objects and __slots__" msgstr "" -#: ../../howto/descriptor.rst:1561 +#: ../../howto/descriptor.rst:1540 msgid "" "When a class defines ``__slots__``, it replaces instance dictionaries with a " "fixed-length array of slot values. From a user point of view that has " "several effects:" msgstr "" -#: ../../howto/descriptor.rst:1565 +#: ../../howto/descriptor.rst:1544 msgid "" "1. Provides immediate detection of bugs due to misspelled attribute " "assignments. Only attribute names specified in ``__slots__`` are allowed:" msgstr "" -#: ../../howto/descriptor.rst:1581 +#: ../../howto/descriptor.rst:1547 +msgid "" +"class Vehicle:\n" +" __slots__ = ('id_number', 'make', 'model')" +msgstr "" + +#: ../../howto/descriptor.rst:1552 +msgid "" +">>> auto = Vehicle()\n" +">>> auto.id_nubmer = 'VYE483814LQEX'\n" +"Traceback (most recent call last):\n" +" ...\n" +"AttributeError: 'Vehicle' object has no attribute 'id_nubmer'" +msgstr "" + +#: ../../howto/descriptor.rst:1560 msgid "" "2. Helps create immutable objects where descriptors manage access to private " "attributes stored in ``__slots__``:" msgstr "" -#: ../../howto/descriptor.rst:1616 +#: ../../howto/descriptor.rst:1563 +msgid "" +"class Immutable:\n" +"\n" +" __slots__ = ('_dept', '_name') # Replace the instance " +"dictionary\n" +"\n" +" def __init__(self, dept, name):\n" +" self._dept = dept # Store to private attribute\n" +" self._name = name # Store to private attribute\n" +"\n" +" @property # Read-only descriptor\n" +" def dept(self):\n" +" return self._dept\n" +"\n" +" @property\n" +" def name(self): # Read-only descriptor\n" +" return self._name" +msgstr "" + +#: ../../howto/descriptor.rst:1581 +msgid "" +">>> mark = Immutable('Botany', 'Mark Watney')\n" +">>> mark.dept\n" +"'Botany'\n" +">>> mark.dept = 'Space Pirate'\n" +"Traceback (most recent call last):\n" +" ...\n" +"AttributeError: property 'dept' of 'Immutable' object has no setter\n" +">>> mark.location = 'Mars'\n" +"Traceback (most recent call last):\n" +" ...\n" +"AttributeError: 'Immutable' object has no attribute 'location'" +msgstr "" + +#: ../../howto/descriptor.rst:1595 msgid "" "3. Saves memory. On a 64-bit Linux build, an instance with two attributes " "takes 48 bytes with ``__slots__`` and 152 bytes without. This `flyweight " @@ -1073,19 +2423,40 @@ msgid "" "only matters when a large number of instances are going to be created." msgstr "" -#: ../../howto/descriptor.rst:1621 +#: ../../howto/descriptor.rst:1600 msgid "" "4. Improves speed. Reading instance variables is 35% faster with " "``__slots__`` (as measured with Python 3.10 on an Apple M1 processor)." msgstr "" -#: ../../howto/descriptor.rst:1624 +#: ../../howto/descriptor.rst:1603 msgid "" "5. Blocks tools like :func:`functools.cached_property` which require an " "instance dictionary to function correctly:" msgstr "" -#: ../../howto/descriptor.rst:1646 +#: ../../howto/descriptor.rst:1606 +msgid "" +"from functools import cached_property\n" +"\n" +"class CP:\n" +" __slots__ = () # Eliminates the instance dict\n" +"\n" +" @cached_property # Requires an instance dict\n" +" def pi(self):\n" +" return 4 * sum((-1.0)**n / (2.0*n + 1.0)\n" +" for n in reversed(range(100_000)))" +msgstr "" + +#: ../../howto/descriptor.rst:1618 +msgid "" +">>> CP().pi\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: No '__dict__' attribute on 'CP' instance to cache 'pi' property." +msgstr "" + +#: ../../howto/descriptor.rst:1625 msgid "" "It is not possible to create an exact drop-in pure Python version of " "``__slots__`` because it requires direct access to C structures and control " @@ -1095,36 +2466,163 @@ msgid "" "managed by member descriptors:" msgstr "" -#: ../../howto/descriptor.rst:1691 -msgid "" -"The :meth:`type.__new__` method takes care of adding member objects to class " -"variables:" -msgstr "" - -#: ../../howto/descriptor.rst:1707 +#: ../../howto/descriptor.rst:1632 +msgid "" +"null = object()\n" +"\n" +"class Member:\n" +"\n" +" def __init__(self, name, clsname, offset):\n" +" 'Emulate PyMemberDef in Include/structmember.h'\n" +" # Also see descr_new() in Objects/descrobject.c\n" +" self.name = name\n" +" self.clsname = clsname\n" +" self.offset = offset\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" 'Emulate member_get() in Objects/descrobject.c'\n" +" # Also see PyMember_GetOne() in Python/structmember.c\n" +" if obj is None:\n" +" return self\n" +" value = obj._slotvalues[self.offset]\n" +" if value is null:\n" +" raise AttributeError(self.name)\n" +" return value\n" +"\n" +" def __set__(self, obj, value):\n" +" 'Emulate member_set() in Objects/descrobject.c'\n" +" obj._slotvalues[self.offset] = value\n" +"\n" +" def __delete__(self, obj):\n" +" 'Emulate member_delete() in Objects/descrobject.c'\n" +" value = obj._slotvalues[self.offset]\n" +" if value is null:\n" +" raise AttributeError(self.name)\n" +" obj._slotvalues[self.offset] = null\n" +"\n" +" def __repr__(self):\n" +" 'Emulate member_repr() in Objects/descrobject.c'\n" +" return f''" +msgstr "" + +#: ../../howto/descriptor.rst:1670 +msgid "" +"The :meth:`!type.__new__` method takes care of adding member objects to " +"class variables:" +msgstr "" + +#: ../../howto/descriptor.rst:1673 +msgid "" +"class Type(type):\n" +" 'Simulate how the type metaclass adds member objects for slots'\n" +"\n" +" def __new__(mcls, clsname, bases, mapping, **kwargs):\n" +" 'Emulate type_new() in Objects/typeobject.c'\n" +" # type_new() calls PyTypeReady() which calls add_methods()\n" +" slot_names = mapping.get('slot_names', [])\n" +" for offset, name in enumerate(slot_names):\n" +" mapping[name] = Member(name, clsname, offset)\n" +" return type.__new__(mcls, clsname, bases, mapping, **kwargs)" +msgstr "" + +#: ../../howto/descriptor.rst:1686 msgid "" "The :meth:`object.__new__` method takes care of creating instances that have " "slots instead of an instance dictionary. Here is a rough simulation in pure " "Python:" msgstr "" -#: ../../howto/descriptor.rst:1742 +#: ../../howto/descriptor.rst:1690 +msgid "" +"class Object:\n" +" 'Simulate how object.__new__() allocates memory for __slots__'\n" +"\n" +" def __new__(cls, *args, **kwargs):\n" +" 'Emulate object_new() in Objects/typeobject.c'\n" +" inst = super().__new__(cls)\n" +" if hasattr(cls, 'slot_names'):\n" +" empty_slots = [null] * len(cls.slot_names)\n" +" object.__setattr__(inst, '_slotvalues', empty_slots)\n" +" return inst\n" +"\n" +" def __setattr__(self, name, value):\n" +" 'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c'\n" +" cls = type(self)\n" +" if hasattr(cls, 'slot_names') and name not in cls.slot_names:\n" +" raise AttributeError(\n" +" f'{cls.__name__!r} object has no attribute {name!r}'\n" +" )\n" +" super().__setattr__(name, value)\n" +"\n" +" def __delattr__(self, name):\n" +" 'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c'\n" +" cls = type(self)\n" +" if hasattr(cls, 'slot_names') and name not in cls.slot_names:\n" +" raise AttributeError(\n" +" f'{cls.__name__!r} object has no attribute {name!r}'\n" +" )\n" +" super().__delattr__(name)" +msgstr "" + +#: ../../howto/descriptor.rst:1721 +msgid "" +"To use the simulation in a real class, just inherit from :class:`!Object` " +"and set the :term:`metaclass` to :class:`Type`:" +msgstr "" + +#: ../../howto/descriptor.rst:1724 +msgid "" +"class H(Object, metaclass=Type):\n" +" 'Instance variables stored in slots'\n" +"\n" +" slot_names = ['x', 'y']\n" +"\n" +" def __init__(self, x, y):\n" +" self.x = x\n" +" self.y = y" +msgstr "" + +#: ../../howto/descriptor.rst:1735 msgid "" -"To use the simulation in a real class, just inherit from :class:`Object` and " -"set the :term:`metaclass` to :class:`Type`:" +"At this point, the metaclass has loaded member objects for *x* and *y*::" msgstr "" -#: ../../howto/descriptor.rst:1756 +#: ../../howto/descriptor.rst:1737 msgid "" -"At this point, the metaclass has loaded member objects for *x* and *y*::" +">>> from pprint import pp\n" +">>> pp(dict(vars(H)))\n" +"{'__module__': '__main__',\n" +" '__doc__': 'Instance variables stored in slots',\n" +" 'slot_names': ['x', 'y'],\n" +" '__init__': ,\n" +" 'x': ,\n" +" 'y': }" msgstr "" -#: ../../howto/descriptor.rst:1777 +#: ../../howto/descriptor.rst:1756 msgid "" "When instances are created, they have a ``slot_values`` list where the " "attributes are stored:" msgstr "" -#: ../../howto/descriptor.rst:1789 +#: ../../howto/descriptor.rst:1759 +msgid "" +">>> h = H(10, 20)\n" +">>> vars(h)\n" +"{'_slotvalues': [10, 20]}\n" +">>> h.x = 55\n" +">>> vars(h)\n" +"{'_slotvalues': [55, 20]}" +msgstr "" + +#: ../../howto/descriptor.rst:1768 msgid "Misspelled or unassigned attributes will raise an exception:" msgstr "" + +#: ../../howto/descriptor.rst:1770 +msgid "" +">>> h.xz\n" +"Traceback (most recent call last):\n" +" ...\n" +"AttributeError: 'H' object has no attribute 'xz'" +msgstr "" diff --git a/howto/enum.po b/howto/enum.po index bc010385d..5a7db3d7d 100644 --- a/howto/enum.po +++ b/howto/enum.po @@ -1,48 +1,41 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Misael borges , 2021 -# Guilherme Alves da Silva, 2023 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-12 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:53+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../howto/enum.rst:5 msgid "Enum HOWTO" -msgstr "HOWTO Enum" +msgstr "Enum" #: ../../howto/enum.rst:11 msgid "" "An :class:`Enum` is a set of symbolic names bound to unique values. They " -"are similar to global variables, but they offer a more useful :func:" -"`repr()`, grouping, type-safety, and a few other features." +"are similar to global variables, but they offer a more useful :func:`repr`, " +"grouping, type-safety, and a few other features." msgstr "" -"Uma classe :class:`Enum` é um conjunto de nomes simbólicos vinculados a " -"valores únicos. Eles são semelhantes às variáveis globais, mas oferecem um :" -"func:`repr()` mais útil, agrupamento, segurança de tipo e alguns outros " -"recursos." +"Uma :class:`Enum` é um conjunto de nomes simbólicos vinculados a valores " +"únicos. São similares a variáveis globais, mas eles oferecem uma :func:" +"`repr` mais útil, agrupamento, segurança de tipo e alguns outros recursos." #: ../../howto/enum.rst:15 msgid "" @@ -52,10 +45,32 @@ msgstr "" "Eles são mais úteis quando você tem uma variável que pode ter uma seleção " "limitada de valores. Por exemplo, os dias da semana::" +#: ../../howto/enum.rst:18 +msgid "" +">>> from enum import Enum\n" +">>> class Weekday(Enum):\n" +"... MONDAY = 1\n" +"... TUESDAY = 2\n" +"... WEDNESDAY = 3\n" +"... THURSDAY = 4\n" +"... FRIDAY = 5\n" +"... SATURDAY = 6\n" +"... SUNDAY = 7" +msgstr "" + #: ../../howto/enum.rst:28 msgid "Or perhaps the RGB primary colors::" msgstr "Ou talvez as cores primárias RGB::" +#: ../../howto/enum.rst:30 +msgid "" +">>> from enum import Enum\n" +">>> class Color(Enum):\n" +"... RED = 1\n" +"... GREEN = 2\n" +"... BLUE = 3" +msgstr "" + #: ../../howto/enum.rst:36 msgid "" "As you can see, creating an :class:`Enum` is as simple as writing a class " @@ -90,6 +105,12 @@ msgstr "" "importante, mas de qualquer forma esse valor pode ser usado para obter o " "membro correspondente::" +#: ../../howto/enum.rst:50 +msgid "" +">>> Weekday(3)\n" +"" +msgstr "" + #: ../../howto/enum.rst:53 msgid "" "As you can see, the ``repr()`` of a member shows the enum name, the member " @@ -100,65 +121,123 @@ msgstr "" "do membro e o valor. O ``str()`` de um membro mostra apenas o nome do enum e " "o nome do membro::" +#: ../../howto/enum.rst:57 +msgid "" +">>> print(Weekday.THURSDAY)\n" +"Weekday.THURSDAY" +msgstr "" + #: ../../howto/enum.rst:60 msgid "The *type* of an enumeration member is the enum it belongs to::" msgstr "O *tipo* de um membro de enumeração é o enum ao qual ele pertence::" +#: ../../howto/enum.rst:62 +msgid "" +">>> type(Weekday.MONDAY)\n" +"\n" +">>> isinstance(Weekday.FRIDAY, Weekday)\n" +"True" +msgstr "" + #: ../../howto/enum.rst:67 -msgid "Enum members have an attribute that contains just their :attr:`name`::" +msgid "Enum members have an attribute that contains just their :attr:`!name`::" +msgstr "" + +#: ../../howto/enum.rst:69 +msgid "" +">>> print(Weekday.TUESDAY.name)\n" +"TUESDAY" msgstr "" -"Os membros do Enum têm um atributo que contém apenas seu :attr:`name`::" #: ../../howto/enum.rst:72 -msgid "Likewise, they have an attribute for their :attr:`value`::" -msgstr "Da mesma forma, eles têm um atributo para seu :attr:`value`::" +msgid "Likewise, they have an attribute for their :attr:`!value`::" +msgstr "" + +#: ../../howto/enum.rst:75 +msgid "" +">>> Weekday.WEDNESDAY.value\n" +"3" +msgstr "" #: ../../howto/enum.rst:78 msgid "" "Unlike many languages that treat enumerations solely as name/value pairs, " "Python Enums can have behavior added. For example, :class:`datetime.date` " -"has two methods for returning the weekday: :meth:`weekday` and :meth:" -"`isoweekday`. The difference is that one of them counts from 0-6 and the " -"other from 1-7. Rather than keep track of that ourselves we can add a method " -"to the :class:`Weekday` enum to extract the day from the :class:`date` " -"instance and return the matching enum member::" -msgstr "" -"Ao contrário de muitas linguagens que tratam enumerações apenas como pares " -"de nome/valor, Enums do Python podem ter comportamento adicionado. Por " -"exemplo, :class:`datetime.date` tem dois métodos para retornar o dia da " -"semana: :meth:`weekday` e :meth:`isoweekday`. A diferença é que um deles " -"conta de 0 a 6 e o outro de 1 a 7. Em vez de acompanhar isso nós mesmos, " -"podemos adicionar um método ao enum de :class:`Weekday` para extrair o dia " -"da instância de :class:`date` e retornar o membro enum correspondente::" - -#: ../../howto/enum.rst:90 -msgid "The complete :class:`Weekday` enum now looks like this::" -msgstr "O enum de :class:`Weekday` completa agora tem esta forma::" - -#: ../../howto/enum.rst:105 +"has two methods for returning the weekday: :meth:`~datetime.date.weekday` " +"and :meth:`~datetime.date.isoweekday`. The difference is that one of them " +"counts from 0-6 and the other from 1-7. Rather than keep track of that " +"ourselves we can add a method to the :class:`!Weekday` enum to extract the " +"day from the :class:`~datetime.date` instance and return the matching enum " +"member::" +msgstr "" + +#: ../../howto/enum.rst:87 +msgid "" +"@classmethod\n" +"def from_date(cls, date):\n" +" return cls(date.isoweekday())" +msgstr "" + +#: ../../howto/enum.rst:91 +msgid "The complete :class:`!Weekday` enum now looks like this::" +msgstr "" + +#: ../../howto/enum.rst:93 +msgid "" +">>> class Weekday(Enum):\n" +"... MONDAY = 1\n" +"... TUESDAY = 2\n" +"... WEDNESDAY = 3\n" +"... THURSDAY = 4\n" +"... FRIDAY = 5\n" +"... SATURDAY = 6\n" +"... SUNDAY = 7\n" +"... #\n" +"... @classmethod\n" +"... def from_date(cls, date):\n" +"... return cls(date.isoweekday())" +msgstr "" + +#: ../../howto/enum.rst:106 msgid "Now we can find out what today is! Observe::" msgstr "Agora podemos descobrir o que é hoje! Observar::" -#: ../../howto/enum.rst:111 +#: ../../howto/enum.rst:108 +msgid "" +">>> from datetime import date\n" +">>> Weekday.from_date(date.today())\n" +"" +msgstr "" + +#: ../../howto/enum.rst:112 msgid "" "Of course, if you're reading this on some other day, you'll see that day " "instead." msgstr "" "Claro, se você estiver lendo isso em algum outro dia, você verá esse dia." -#: ../../howto/enum.rst:113 +#: ../../howto/enum.rst:114 msgid "" -"This :class:`Weekday` enum is great if our variable only needs one day, but " +"This :class:`!Weekday` enum is great if our variable only needs one day, but " "what if we need several? Maybe we're writing a function to plot chores " "during a week, and don't want to use a :class:`list` -- we could use a " "different type of :class:`Enum`::" msgstr "" -"Este enum :class:`Weekday` é ótimo se nossa variável precisar apenas de um " -"dia, mas e se precisarmos de vários? Talvez estejamos escrevendo uma função " -"para traçar tarefas durante uma semana e não queremos usar uma :class:`list` " -"-- poderíamos usar um tipo diferente de :class:`Enum`::" -#: ../../howto/enum.rst:128 +#: ../../howto/enum.rst:119 +msgid "" +">>> from enum import Flag\n" +">>> class Weekday(Flag):\n" +"... MONDAY = 1\n" +"... TUESDAY = 2\n" +"... WEDNESDAY = 4\n" +"... THURSDAY = 8\n" +"... FRIDAY = 16\n" +"... SATURDAY = 32\n" +"... SUNDAY = 64" +msgstr "" + +#: ../../howto/enum.rst:129 msgid "" "We've changed two things: we're inherited from :class:`Flag`, and the values " "are all powers of 2." @@ -166,15 +245,20 @@ msgstr "" "Nós mudamos duas coisas: estamos herdando de :class:`Flag`, e os valores são " "todos potências de 2." -#: ../../howto/enum.rst:131 +#: ../../howto/enum.rst:132 msgid "" -"Just like the original :class:`Weekday` enum above, we can have a single " +"Just like the original :class:`!Weekday` enum above, we can have a single " "selection::" msgstr "" -"Assim como o enum :class:`Weekday` original acima, podemos ter uma seleção " -"única:" -#: ../../howto/enum.rst:137 +#: ../../howto/enum.rst:134 +msgid "" +">>> first_week_day = Weekday.MONDAY\n" +">>> first_week_day\n" +"" +msgstr "" + +#: ../../howto/enum.rst:138 msgid "" "But :class:`Flag` also allows us to combine several members into a single " "variable::" @@ -182,31 +266,79 @@ msgstr "" "Porem :class:`Flag` também nos permite combinar vários membros em uma única " "variável:" -#: ../../howto/enum.rst:144 +#: ../../howto/enum.rst:141 +msgid "" +">>> weekend = Weekday.SATURDAY | Weekday.SUNDAY\n" +">>> weekend\n" +"" +msgstr "" + +#: ../../howto/enum.rst:145 msgid "You can even iterate over a :class:`Flag` variable::" msgstr "Você pode até mesmo iterar sobre uma variável :class:`Flag`:" -#: ../../howto/enum.rst:151 +#: ../../howto/enum.rst:147 +msgid "" +">>> for day in weekend:\n" +"... print(day)\n" +"Weekday.SATURDAY\n" +"Weekday.SUNDAY" +msgstr "" + +#: ../../howto/enum.rst:152 msgid "Okay, let's get some chores set up::" msgstr "Certo, vamos configurar algumas tarefas domésticas:" -#: ../../howto/enum.rst:159 +#: ../../howto/enum.rst:154 +msgid "" +">>> chores_for_ethan = {\n" +"... 'feed the cat': Weekday.MONDAY | Weekday.WEDNESDAY | Weekday." +"FRIDAY,\n" +"... 'do the dishes': Weekday.TUESDAY | Weekday.THURSDAY,\n" +"... 'answer SO questions': Weekday.SATURDAY,\n" +"... }" +msgstr "" + +#: ../../howto/enum.rst:160 msgid "And a function to display the chores for a given day::" msgstr "E a função para mostrar as tarefas domésticas para um determinado dia:" -#: ../../howto/enum.rst:169 +#: ../../howto/enum.rst:162 +msgid "" +">>> def show_chores(chores, day):\n" +"... for chore, days in chores.items():\n" +"... if day in days:\n" +"... print(chore)\n" +"...\n" +">>> show_chores(chores_for_ethan, Weekday.SATURDAY)\n" +"answer SO questions" +msgstr "" + +#: ../../howto/enum.rst:170 msgid "" "In cases where the actual values of the members do not matter, you can save " -"yourself some work and use :func:`auto()` for the values::" +"yourself some work and use :func:`auto` for the values::" msgstr "" -"Nos casos onde os valores reais dos membros não importam, você pode " -"economizar trabalho e usar :func:`auto()` para os valores:" -#: ../../howto/enum.rst:188 +#: ../../howto/enum.rst:173 +msgid "" +">>> from enum import auto\n" +">>> class Weekday(Flag):\n" +"... MONDAY = auto()\n" +"... TUESDAY = auto()\n" +"... WEDNESDAY = auto()\n" +"... THURSDAY = auto()\n" +"... FRIDAY = auto()\n" +"... SATURDAY = auto()\n" +"... SUNDAY = auto()\n" +"... WEEKEND = SATURDAY | SUNDAY" +msgstr "" + +#: ../../howto/enum.rst:189 msgid "Programmatic access to enumeration members and their attributes" msgstr "Acesso programático aos membros da enumeração e seus atributos." -#: ../../howto/enum.rst:190 +#: ../../howto/enum.rst:191 msgid "" "Sometimes it's useful to access members in enumerations programmatically (i." "e. situations where ``Color.RED`` won't do because the exact color is not " @@ -217,26 +349,62 @@ msgstr "" "porque a cor exata não é conhecida no momento da escrita do programa)." "``Enum`` permite esse tipo de acesso:" -#: ../../howto/enum.rst:199 +#: ../../howto/enum.rst:195 +msgid "" +">>> Color(1)\n" +"\n" +">>> Color(3)\n" +"" +msgstr "" + +#: ../../howto/enum.rst:200 msgid "If you want to access enum members by *name*, use item access::" msgstr "" "Se você deseja ter acesso aos membros do enum pelo *nome*, use o acesso por " "itens:" -#: ../../howto/enum.rst:206 -msgid "If you have an enum member and need its :attr:`name` or :attr:`value`::" +#: ../../howto/enum.rst:202 +msgid "" +">>> Color['RED']\n" +"\n" +">>> Color['GREEN']\n" +"" +msgstr "" + +#: ../../howto/enum.rst:207 +msgid "" +"If you have an enum member and need its :attr:`!name` or :attr:`!value`::" +msgstr "" + +#: ../../howto/enum.rst:209 +msgid "" +">>> member = Color.RED\n" +">>> member.name\n" +"'RED'\n" +">>> member.value\n" +"1" msgstr "" -"Se você tem um membro do enum e precisa do seu :attr:`name` ou :attr:`value`:" -#: ../../howto/enum.rst:216 +#: ../../howto/enum.rst:217 msgid "Duplicating enum members and values" msgstr "Duplicar membros do enum e seus valores." -#: ../../howto/enum.rst:218 +#: ../../howto/enum.rst:219 msgid "Having two enum members with the same name is invalid::" msgstr "Ter dois membros de um enum com o mesmo nome é inválido:" -#: ../../howto/enum.rst:228 +#: ../../howto/enum.rst:221 +msgid "" +">>> class Shape(Enum):\n" +"... SQUARE = 2\n" +"... SQUARE = 3\n" +"...\n" +"Traceback (most recent call last):\n" +"...\n" +"TypeError: 'SQUARE' already defined as 2" +msgstr "" + +#: ../../howto/enum.rst:229 msgid "" "However, an enum member can have other names associated with it. Given two " "entries ``A`` and ``B`` with the same value (and ``A`` defined first), ``B`` " @@ -250,7 +418,23 @@ msgstr "" "membro ``A``. A Pesquisa por nome de ``A`` também retorna o membro ``A``. A " "pesquisa por nome de ``B`` também retorna o membro ``A``:" -#: ../../howto/enum.rst:249 +#: ../../howto/enum.rst:235 +msgid "" +">>> class Shape(Enum):\n" +"... SQUARE = 2\n" +"... DIAMOND = 1\n" +"... CIRCLE = 3\n" +"... ALIAS_FOR_SQUARE = 2\n" +"...\n" +">>> Shape.SQUARE\n" +"\n" +">>> Shape.ALIAS_FOR_SQUARE\n" +"\n" +">>> Shape(2)\n" +"" +msgstr "" + +#: ../../howto/enum.rst:250 msgid "" "Attempting to create a member with the same name as an already defined " "attribute (another member, a method, etc.) or attempting to create an " @@ -260,11 +444,11 @@ msgstr "" "membro, um método, etc.) ou tentar criar um atributo com o mesmo nome de um " "membro não é permitido." -#: ../../howto/enum.rst:255 +#: ../../howto/enum.rst:256 msgid "Ensuring unique enumeration values" msgstr "Garantindo valores únicos de enumeração" -#: ../../howto/enum.rst:257 +#: ../../howto/enum.rst:258 msgid "" "By default, enumerations allow multiple names as aliases for the same value. " "When this behavior isn't desired, you can use the :func:`unique` decorator::" @@ -273,38 +457,89 @@ msgstr "" "valor. Quando esse comportamento não é desejado, você pode usar o decorador :" "func:`unique`:" -#: ../../howto/enum.rst:274 +#: ../../howto/enum.rst:261 +msgid "" +">>> from enum import Enum, unique\n" +">>> @unique\n" +"... class Mistake(Enum):\n" +"... ONE = 1\n" +"... TWO = 2\n" +"... THREE = 3\n" +"... FOUR = 3\n" +"...\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: duplicate values found in : FOUR -> THREE" +msgstr "" + +#: ../../howto/enum.rst:275 msgid "Using automatic values" msgstr "Usando valores automáticos" -#: ../../howto/enum.rst:276 +#: ../../howto/enum.rst:277 msgid "If the exact value is unimportant you can use :class:`auto`::" msgstr "Se o exato valor não é importante, você pode usar :class:`auto`:" -#: ../../howto/enum.rst:287 +#: ../../howto/enum.rst:279 +msgid "" +">>> from enum import Enum, auto\n" +">>> class Color(Enum):\n" +"... RED = auto()\n" +"... BLUE = auto()\n" +"... GREEN = auto()\n" +"...\n" +">>> [member.value for member in Color]\n" +"[1, 2, 3]" +msgstr "" + +#: ../../howto/enum.rst:288 msgid "" -"The values are chosen by :func:`_generate_next_value_`, which can be " +"The values are chosen by :func:`~Enum._generate_next_value_`, which can be " "overridden::" msgstr "" -"Os valores são escolhidos por :func:`_generate_next_value_`, o qual pode ser " -"substituído:" -#: ../../howto/enum.rst:306 +#: ../../howto/enum.rst:291 msgid "" -"The :meth:`_generate_next_value_` method must be defined before any members." +">>> class AutoName(Enum):\n" +"... @staticmethod\n" +"... def _generate_next_value_(name, start, count, last_values):\n" +"... return name\n" +"...\n" +">>> class Ordinal(AutoName):\n" +"... NORTH = auto()\n" +"... SOUTH = auto()\n" +"... EAST = auto()\n" +"... WEST = auto()\n" +"...\n" +">>> [member.value for member in Ordinal]\n" +"['NORTH', 'SOUTH', 'EAST', 'WEST']" msgstr "" -"O método :meth:`_generate_next_value_` deve ser definido antes de qualquer " -"membro." -#: ../../howto/enum.rst:309 +#: ../../howto/enum.rst:307 +msgid "" +"The :meth:`~Enum._generate_next_value_` method must be defined before any " +"members." +msgstr "" + +#: ../../howto/enum.rst:310 msgid "Iteration" msgstr "Iteração" -#: ../../howto/enum.rst:311 +#: ../../howto/enum.rst:312 msgid "Iterating over the members of an enum does not provide the aliases::" msgstr "Iterar sobre os membros de um enum não fornece os apelidos:" -#: ../../howto/enum.rst:318 +#: ../../howto/enum.rst:314 +msgid "" +">>> list(Shape)\n" +"[, , ]\n" +">>> list(Weekday)\n" +"[, , , , , , ]" +msgstr "" + +#: ../../howto/enum.rst:319 msgid "" "Note that the aliases ``Shape.ALIAS_FOR_SQUARE`` and ``Weekday.WEEKEND`` " "aren't shown." @@ -312,7 +547,7 @@ msgstr "" "Note que os apelidos ``Shape.ALIAS_FOR_SQUARE`` e ``Weekday.WEEKEND`` não " "são mostrados." -#: ../../howto/enum.rst:320 +#: ../../howto/enum.rst:321 msgid "" "The special attribute ``__members__`` is a read-only ordered mapping of " "names to members. It includes all names defined in the enumeration, " @@ -322,7 +557,18 @@ msgstr "" "de nomes para os membros. Isso inclui todos os nomes definidos na " "enumeração, incluindo os apelidos:" -#: ../../howto/enum.rst:332 +#: ../../howto/enum.rst:325 +msgid "" +">>> for name, member in Shape.__members__.items():\n" +"... name, member\n" +"...\n" +"('SQUARE', )\n" +"('DIAMOND', )\n" +"('CIRCLE', )\n" +"('ALIAS_FOR_SQUARE', )" +msgstr "" + +#: ../../howto/enum.rst:333 msgid "" "The ``__members__`` attribute can be used for detailed programmatic access " "to the enumeration members. For example, finding all the aliases::" @@ -330,49 +576,93 @@ msgstr "" "O atributo ``__members__`` pode ser usado para um acesso programático " "detalhado aos membros da enumeração. Por exemplo, achar todos os apelidos:" -#: ../../howto/enum.rst:340 +#: ../../howto/enum.rst:336 +msgid "" +">>> [name for name, member in Shape.__members__.items() if member.name != " +"name]\n" +"['ALIAS_FOR_SQUARE']" +msgstr "" + +#: ../../howto/enum.rst:341 msgid "" "Aliases for flags include values with multiple flags set, such as ``3``, and " "no flags set, i.e. ``0``." msgstr "" -#: ../../howto/enum.rst:345 +#: ../../howto/enum.rst:346 msgid "Comparisons" msgstr "Comparações" -#: ../../howto/enum.rst:347 +#: ../../howto/enum.rst:348 msgid "Enumeration members are compared by identity::" +msgstr "Membros de uma enumeração são comparados por identidade::" + +#: ../../howto/enum.rst:350 +msgid "" +">>> Color.RED is Color.RED\n" +"True\n" +">>> Color.RED is Color.BLUE\n" +"False\n" +">>> Color.RED is not Color.BLUE\n" +"True" msgstr "" -#: ../../howto/enum.rst:356 +#: ../../howto/enum.rst:357 msgid "" "Ordered comparisons between enumeration values are *not* supported. Enum " "members are not integers (but see `IntEnum`_ below)::" msgstr "" -#: ../../howto/enum.rst:364 +#: ../../howto/enum.rst:360 +msgid "" +">>> Color.RED < Color.BLUE\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: '<' not supported between instances of 'Color' and 'Color'" +msgstr "" + +#: ../../howto/enum.rst:365 msgid "Equality comparisons are defined though::" msgstr "" -#: ../../howto/enum.rst:373 +#: ../../howto/enum.rst:367 +msgid "" +">>> Color.BLUE == Color.RED\n" +"False\n" +">>> Color.BLUE != Color.RED\n" +"True\n" +">>> Color.BLUE == Color.BLUE\n" +"True" +msgstr "" + +#: ../../howto/enum.rst:374 msgid "" "Comparisons against non-enumeration values will always compare not equal " "(again, :class:`IntEnum` was explicitly designed to behave differently, see " "below)::" msgstr "" -#: ../../howto/enum.rst:382 +#: ../../howto/enum.rst:378 +msgid "" +">>> Color.BLUE == 2\n" +"False" +msgstr "" + +#: ../../howto/enum.rst:383 msgid "" "It is possible to reload modules -- if a reloaded module contains enums, " "they will be recreated, and the new members may not compare identical/equal " "to the original members." msgstr "" +"É possivel recarregar módulos -- se um módulo recarregado contém enums, eles " +"serão recriados, e os novos membros não podem ser comparados de forma " +"identifica/igual a membros originais." -#: ../../howto/enum.rst:387 +#: ../../howto/enum.rst:388 msgid "Allowed members and attributes of enumerations" -msgstr "" +msgstr "Membros e atributos permitidos em enumerações" -#: ../../howto/enum.rst:389 +#: ../../howto/enum.rst:390 msgid "" "Most of the examples above use integers for enumeration values. Using " "integers is short and handy (and provided by default by the `Functional " @@ -380,64 +670,131 @@ msgid "" "doesn't care what the actual value of an enumeration is. But if the value " "*is* important, enumerations can have arbitrary values." msgstr "" +"A maioria dos exemplos acima usa inteiros como valores para os enums. Usar " +"inteiros é simples e prático (isso é disponibilizado como padrão pela `API " +"funcional`_), mas não é a única aplicação. Na grande maioria dos caso de " +"uso, não importa o valor de fato que um enum possui. Mas se o valor *é* " +"importante, enums podem ser valores arbitrários." -#: ../../howto/enum.rst:395 +#: ../../howto/enum.rst:396 msgid "" "Enumerations are Python classes, and can have methods and special methods as " "usual. If we have this enumeration::" msgstr "" - -#: ../../howto/enum.rst:415 +"Enumeções são classes Python, e podem ter métodos e até mesmo métodos " +"especiais como de usual. Se temos essa enumeração::" + +#: ../../howto/enum.rst:399 +msgid "" +">>> class Mood(Enum):\n" +"... FUNKY = 1\n" +"... HAPPY = 3\n" +"...\n" +"... def describe(self):\n" +"... # self is the member here\n" +"... return self.name, self.value\n" +"...\n" +"... def __str__(self):\n" +"... return 'my custom str! {0}'.format(self.value)\n" +"...\n" +"... @classmethod\n" +"... def favorite_mood(cls):\n" +"... # cls here is the enumeration\n" +"... return cls.HAPPY\n" +"..." +msgstr "" + +#: ../../howto/enum.rst:416 msgid "Then::" +msgstr "Então::" + +#: ../../howto/enum.rst:418 +msgid "" +">>> Mood.favorite_mood()\n" +"\n" +">>> Mood.HAPPY.describe()\n" +"('HAPPY', 3)\n" +">>> str(Mood.FUNKY)\n" +"'my custom str! 1'" msgstr "" -#: ../../howto/enum.rst:424 +#: ../../howto/enum.rst:425 msgid "" "The rules for what is allowed are as follows: names that start and end with " "a single underscore are reserved by enum and cannot be used; all other " "attributes defined within an enumeration will become members of this " -"enumeration, with the exception of special methods (:meth:`__str__`, :meth:" -"`__add__`, etc.), descriptors (methods are also descriptors), and variable " -"names listed in :attr:`_ignore_`." +"enumeration, with the exception of special methods (:meth:`~object." +"__str__`, :meth:`~object.__add__`, etc.), descriptors (methods are also " +"descriptors), and variable names listed in :attr:`~Enum._ignore_`." msgstr "" -#: ../../howto/enum.rst:431 +#: ../../howto/enum.rst:432 msgid "" -"Note: if your enumeration defines :meth:`__new__` and/or :meth:`__init__`, " -"any value(s) given to the enum member will be passed into those methods. See " -"`Planet`_ for an example." +"Note: if your enumeration defines :meth:`~object.__new__` and/or :meth:" +"`~object.__init__`, any value(s) given to the enum member will be passed " +"into those methods. See `Planet`_ for an example." msgstr "" -#: ../../howto/enum.rst:437 +#: ../../howto/enum.rst:438 msgid "" -"The :meth:`__new__` method, if defined, is used during creation of the Enum " -"members; it is then replaced by Enum's :meth:`__new__` which is used after " -"class creation for lookup of existing members. See :ref:`new-vs-init` for " -"more details." +"The :meth:`~object.__new__` method, if defined, is used during creation of " +"the Enum members; it is then replaced by Enum's :meth:`~object.__new__` " +"which is used after class creation for lookup of existing members. See :ref:" +"`new-vs-init` for more details." msgstr "" -#: ../../howto/enum.rst:444 +#: ../../howto/enum.rst:445 msgid "Restricted Enum subclassing" msgstr "" -#: ../../howto/enum.rst:446 +#: ../../howto/enum.rst:447 msgid "" "A new :class:`Enum` class must have one base enum class, up to one concrete " "data type, and as many :class:`object`-based mixin classes as needed. The " "order of these base classes is::" msgstr "" -#: ../../howto/enum.rst:453 +#: ../../howto/enum.rst:451 +msgid "" +"class EnumName([mix-in, ...,] [data-type,] base-enum):\n" +" pass" +msgstr "" + +#: ../../howto/enum.rst:454 msgid "" "Also, subclassing an enumeration is allowed only if the enumeration does not " "define any members. So this is forbidden::" msgstr "" +"Além disso, criar uma subclasse de uma enumeração é permitido apenas se a " +"enumeção não define nenhum membro. Pontando isso é proibido::" -#: ../../howto/enum.rst:463 +#: ../../howto/enum.rst:457 +msgid "" +">>> class MoreColor(Color):\n" +"... PINK = 17\n" +"...\n" +"Traceback (most recent call last):\n" +"...\n" +"TypeError: cannot extend " +msgstr "" + +#: ../../howto/enum.rst:464 msgid "But this is allowed::" +msgstr "Mas isso é permitido::" + +#: ../../howto/enum.rst:466 +msgid "" +">>> class Foo(Enum):\n" +"... def some_behavior(self):\n" +"... pass\n" +"...\n" +">>> class Bar(Foo):\n" +"... HAPPY = 1\n" +"... SAD = 2\n" +"..." msgstr "" -#: ../../howto/enum.rst:474 +#: ../../howto/enum.rst:475 msgid "" "Allowing subclassing of enums that define members would lead to a violation " "of some important invariants of types and instances. On the other hand, it " @@ -445,29 +802,46 @@ msgid "" "enumerations. (See `OrderedEnum`_ for an example.)" msgstr "" -#: ../../howto/enum.rst:483 +#: ../../howto/enum.rst:484 msgid "Dataclass support" -msgstr "" +msgstr "Suporte a dataclass" -#: ../../howto/enum.rst:485 +#: ../../howto/enum.rst:486 msgid "" "When inheriting from a :class:`~dataclasses.dataclass`, the :meth:`~Enum." "__repr__` omits the inherited class' name. For example::" msgstr "" -#: ../../howto/enum.rst:502 +#: ../../howto/enum.rst:489 +msgid "" +">>> from dataclasses import dataclass, field\n" +">>> @dataclass\n" +"... class CreatureDataMixin:\n" +"... size: str\n" +"... legs: int\n" +"... tail: bool = field(repr=False, default=True)\n" +"...\n" +">>> class Creature(CreatureDataMixin, Enum):\n" +"... BEETLE = 'small', 6\n" +"... DOG = 'medium', 4\n" +"...\n" +">>> Creature.DOG\n" +"" +msgstr "" + +#: ../../howto/enum.rst:503 msgid "" "Use the :func:`~dataclasses.dataclass` argument ``repr=False`` to use the " "standard :func:`repr`." msgstr "" -#: ../../howto/enum.rst:505 +#: ../../howto/enum.rst:506 msgid "" "Only the dataclass fields are shown in the value area, not the dataclass' " "name." msgstr "" -#: ../../howto/enum.rst:511 +#: ../../howto/enum.rst:512 msgid "" "Adding :func:`~dataclasses.dataclass` decorator to :class:`Enum` and its " "subclasses is not supported. It will not raise any errors, but it will " @@ -475,56 +849,96 @@ msgid "" "other::" msgstr "" -#: ../../howto/enum.rst:528 +#: ../../howto/enum.rst:517 +msgid "" +">>> @dataclass # don't do this: it does not make any sense\n" +"... class Color(Enum):\n" +"... RED = 1\n" +"... BLUE = 2\n" +"...\n" +">>> Color.RED is Color.BLUE\n" +"False\n" +">>> Color.RED == Color.BLUE # problem is here: they should not be equal\n" +"True" +msgstr "" + +#: ../../howto/enum.rst:529 msgid "Pickling" msgstr "Pickling" -#: ../../howto/enum.rst:530 +#: ../../howto/enum.rst:531 msgid "Enumerations can be pickled and unpickled::" msgstr "" -#: ../../howto/enum.rst:537 +#: ../../howto/enum.rst:533 +msgid "" +">>> from test.test_enum import Fruit\n" +">>> from pickle import dumps, loads\n" +">>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO))\n" +"True" +msgstr "" + +#: ../../howto/enum.rst:538 msgid "" "The usual restrictions for pickling apply: picklable enums must be defined " "in the top level of a module, since unpickling requires them to be " "importable from that module." msgstr "" -#: ../../howto/enum.rst:543 +#: ../../howto/enum.rst:544 msgid "" "With pickle protocol version 4 it is possible to easily pickle enums nested " "in other classes." msgstr "" -#: ../../howto/enum.rst:546 +#: ../../howto/enum.rst:547 msgid "" "It is possible to modify how enum members are pickled/unpickled by defining :" -"meth:`__reduce_ex__` in the enumeration class. The default method is by-" -"value, but enums with complicated values may want to use by-name::" +"meth:`~object.__reduce_ex__` in the enumeration class. The default method " +"is by-value, but enums with complicated values may want to use by-name::" msgstr "" -#: ../../howto/enum.rst:556 +#: ../../howto/enum.rst:551 +msgid "" +">>> import enum\n" +">>> class MyEnum(enum.Enum):\n" +"... __reduce_ex__ = enum.pickle_by_enum_name" +msgstr "" + +#: ../../howto/enum.rst:557 msgid "" "Using by-name for flags is not recommended, as unnamed aliases will not " "unpickle." msgstr "" -#: ../../howto/enum.rst:561 +#: ../../howto/enum.rst:562 msgid "Functional API" msgstr "API funcional" -#: ../../howto/enum.rst:563 +#: ../../howto/enum.rst:564 msgid "" "The :class:`Enum` class is callable, providing the following functional API::" msgstr "" +"A classe :class:`Enum` é chamável, fornecendo a API funcional a seguir::" + +#: ../../howto/enum.rst:566 +msgid "" +">>> Animal = Enum('Animal', 'ANT BEE CAT DOG')\n" +">>> Animal\n" +"\n" +">>> Animal.ANT\n" +"\n" +">>> list(Animal)\n" +"[, , , ]" +msgstr "" -#: ../../howto/enum.rst:573 +#: ../../howto/enum.rst:574 msgid "" "The semantics of this API resemble :class:`~collections.namedtuple`. The " "first argument of the call to :class:`Enum` is the name of the enumeration." msgstr "" -#: ../../howto/enum.rst:576 +#: ../../howto/enum.rst:577 msgid "" "The second argument is the *source* of enumeration member names. It can be " "a whitespace-separated string of names, a sequence of names, a sequence of 2-" @@ -533,17 +947,27 @@ msgid "" "enumerations; the others auto-assign increasing integers starting with 1 " "(use the ``start`` parameter to specify a different starting value). A new " "class derived from :class:`Enum` is returned. In other words, the above " -"assignment to :class:`Animal` is equivalent to::" +"assignment to :class:`!Animal` is equivalent to::" msgstr "" -#: ../../howto/enum.rst:592 +#: ../../howto/enum.rst:586 +msgid "" +">>> class Animal(Enum):\n" +"... ANT = 1\n" +"... BEE = 2\n" +"... CAT = 3\n" +"... DOG = 4\n" +"..." +msgstr "" + +#: ../../howto/enum.rst:593 msgid "" "The reason for defaulting to ``1`` as the starting number and not ``0`` is " "that ``0`` is ``False`` in a boolean sense, but by default enum members all " "evaluate to ``True``." msgstr "" -#: ../../howto/enum.rst:596 +#: ../../howto/enum.rst:597 msgid "" "Pickling enums created with the functional API can be tricky as frame stack " "implementation details are used to try and figure out which module the " @@ -552,76 +976,114 @@ msgid "" "Jython). The solution is to specify the module name explicitly as follows::" msgstr "" -#: ../../howto/enum.rst:606 +#: ../../howto/enum.rst:603 +msgid ">>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__)" +msgstr "" + +#: ../../howto/enum.rst:607 msgid "" "If ``module`` is not supplied, and Enum cannot determine what it is, the new " "Enum members will not be unpicklable; to keep errors closer to the source, " "pickling will be disabled." msgstr "" -#: ../../howto/enum.rst:610 +#: ../../howto/enum.rst:611 msgid "" "The new pickle protocol 4 also, in some circumstances, relies on :attr:" -"`~definition.__qualname__` being set to the location where pickle will be " -"able to find the class. For example, if the class was made available in " -"class SomeData in the global scope::" +"`~type.__qualname__` being set to the location where pickle will be able to " +"find the class. For example, if the class was made available in class " +"SomeData in the global scope::" msgstr "" -#: ../../howto/enum.rst:617 +#: ../../howto/enum.rst:616 +msgid "" +">>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal')" +msgstr "" + +#: ../../howto/enum.rst:618 msgid "The complete signature is::" +msgstr "A assinatura completa é::" + +#: ../../howto/enum.rst:620 +msgid "" +"Enum(\n" +" value='NewEnumName',\n" +" names=<...>,\n" +" *,\n" +" module='...',\n" +" qualname='...',\n" +" type=,\n" +" start=1,\n" +" )" msgstr "" -#: ../../howto/enum.rst:629 +#: ../../howto/enum.rst:630 msgid "*value*: What the new enum class will record as its name." msgstr "" -#: ../../howto/enum.rst:631 +#: ../../howto/enum.rst:632 msgid "" "*names*: The enum members. This can be a whitespace- or comma-separated " "string (values will start at 1 unless otherwise specified)::" msgstr "" -#: ../../howto/enum.rst:636 +#: ../../howto/enum.rst:635 +msgid "'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'" +msgstr "" + +#: ../../howto/enum.rst:637 msgid "or an iterator of names::" msgstr "" -#: ../../howto/enum.rst:640 +#: ../../howto/enum.rst:639 +msgid "['RED', 'GREEN', 'BLUE']" +msgstr "" + +#: ../../howto/enum.rst:641 msgid "or an iterator of (name, value) pairs::" msgstr "" -#: ../../howto/enum.rst:644 +#: ../../howto/enum.rst:643 +msgid "[('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)]" +msgstr "" + +#: ../../howto/enum.rst:645 msgid "or a mapping::" msgstr "" -#: ../../howto/enum.rst:648 +#: ../../howto/enum.rst:647 +msgid "{'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42}" +msgstr "" + +#: ../../howto/enum.rst:649 msgid "*module*: name of module where new enum class can be found." msgstr "" -#: ../../howto/enum.rst:650 +#: ../../howto/enum.rst:651 msgid "*qualname*: where in module new enum class can be found." msgstr "" -#: ../../howto/enum.rst:652 +#: ../../howto/enum.rst:653 msgid "*type*: type to mix in to new enum class." msgstr "" -#: ../../howto/enum.rst:654 +#: ../../howto/enum.rst:655 msgid "*start*: number to start counting at if only names are passed in." msgstr "" -#: ../../howto/enum.rst:656 +#: ../../howto/enum.rst:657 msgid "The *start* parameter was added." msgstr "" -#: ../../howto/enum.rst:661 +#: ../../howto/enum.rst:662 msgid "Derived Enumerations" msgstr "" -#: ../../howto/enum.rst:664 +#: ../../howto/enum.rst:665 msgid "IntEnum" msgstr "IntEnum" -#: ../../howto/enum.rst:666 +#: ../../howto/enum.rst:667 msgid "" "The first variation of :class:`Enum` that is provided is also a subclass of :" "class:`int`. Members of an :class:`IntEnum` can be compared to integers; by " @@ -629,22 +1091,65 @@ msgid "" "each other::" msgstr "" -#: ../../howto/enum.rst:687 +#: ../../howto/enum.rst:672 +msgid "" +">>> from enum import IntEnum\n" +">>> class Shape(IntEnum):\n" +"... CIRCLE = 1\n" +"... SQUARE = 2\n" +"...\n" +">>> class Request(IntEnum):\n" +"... POST = 1\n" +"... GET = 2\n" +"...\n" +">>> Shape == 1\n" +"False\n" +">>> Shape.CIRCLE == 1\n" +"True\n" +">>> Shape.CIRCLE == Request.POST\n" +"True" +msgstr "" + +#: ../../howto/enum.rst:688 msgid "" "However, they still can't be compared to standard :class:`Enum` " "enumerations::" msgstr "" -#: ../../howto/enum.rst:700 +#: ../../howto/enum.rst:690 +msgid "" +">>> class Shape(IntEnum):\n" +"... CIRCLE = 1\n" +"... SQUARE = 2\n" +"...\n" +">>> class Color(Enum):\n" +"... RED = 1\n" +"... GREEN = 2\n" +"...\n" +">>> Shape.CIRCLE == Color.RED\n" +"False" +msgstr "" + +#: ../../howto/enum.rst:701 msgid "" ":class:`IntEnum` values behave like integers in other ways you'd expect::" msgstr "" -#: ../../howto/enum.rst:711 +#: ../../howto/enum.rst:703 +msgid "" +">>> int(Shape.CIRCLE)\n" +"1\n" +">>> ['a', 'b', 'c'][Shape.CIRCLE]\n" +"'b'\n" +">>> [i for i in range(Shape.SQUARE)]\n" +"[0, 1]" +msgstr "" + +#: ../../howto/enum.rst:712 msgid "StrEnum" msgstr "StrEnum" -#: ../../howto/enum.rst:713 +#: ../../howto/enum.rst:714 msgid "" "The second variation of :class:`Enum` that is provided is also a subclass " "of :class:`str`. Members of a :class:`StrEnum` can be compared to strings; " @@ -652,11 +1157,11 @@ msgid "" "each other." msgstr "" -#: ../../howto/enum.rst:722 +#: ../../howto/enum.rst:723 msgid "IntFlag" msgstr "IntFlag" -#: ../../howto/enum.rst:724 +#: ../../howto/enum.rst:725 msgid "" "The next variation of :class:`Enum` provided, :class:`IntFlag`, is also " "based on :class:`int`. The difference being :class:`IntFlag` members can be " @@ -666,60 +1171,124 @@ msgid "" "is used." msgstr "" -#: ../../howto/enum.rst:732 +#: ../../howto/enum.rst:733 msgid "" "Any operation on an :class:`IntFlag` member besides the bit-wise operations " "will lose the :class:`IntFlag` membership." msgstr "" -#: ../../howto/enum.rst:735 +#: ../../howto/enum.rst:736 msgid "" "Bit-wise operations that result in invalid :class:`IntFlag` values will lose " "the :class:`IntFlag` membership. See :class:`FlagBoundary` for details." msgstr "" -#: ../../howto/enum.rst:742 +#: ../../howto/enum.rst:743 msgid "Sample :class:`IntFlag` class::" msgstr "" -#: ../../howto/enum.rst:758 +#: ../../howto/enum.rst:745 +msgid "" +">>> from enum import IntFlag\n" +">>> class Perm(IntFlag):\n" +"... R = 4\n" +"... W = 2\n" +"... X = 1\n" +"...\n" +">>> Perm.R | Perm.W\n" +"\n" +">>> Perm.R + Perm.W\n" +"6\n" +">>> RW = Perm.R | Perm.W\n" +">>> Perm.R in RW\n" +"True" +msgstr "" + +#: ../../howto/enum.rst:759 msgid "It is also possible to name the combinations::" msgstr "" -#: ../../howto/enum.rst:775 +#: ../../howto/enum.rst:761 +msgid "" +">>> class Perm(IntFlag):\n" +"... R = 4\n" +"... W = 2\n" +"... X = 1\n" +"... RWX = 7\n" +"...\n" +">>> Perm.RWX\n" +"\n" +">>> ~Perm.RWX\n" +"\n" +">>> Perm(7)\n" +"" +msgstr "" + +#: ../../howto/enum.rst:776 msgid "" "Named combinations are considered aliases. Aliases do not show up during " "iteration, but can be returned from by-value lookups." msgstr "" +"Combinações nomeadas são consideradas apelidos. Apelidos não aparecem " +"durante uma iteração, mas podem ser retornados por pesquisas por valor." -#: ../../howto/enum.rst:780 +#: ../../howto/enum.rst:781 msgid "" "Another important difference between :class:`IntFlag` and :class:`Enum` is " "that if no flags are set (the value is 0), its boolean evaluation is :data:" "`False`::" msgstr "" -#: ../../howto/enum.rst:788 +#: ../../howto/enum.rst:784 +msgid "" +">>> Perm.R & Perm.X\n" +"\n" +">>> bool(Perm.R & Perm.X)\n" +"False" +msgstr "" + +#: ../../howto/enum.rst:789 msgid "" "Because :class:`IntFlag` members are also subclasses of :class:`int` they " "can be combined with them (but may lose :class:`IntFlag` membership::" msgstr "" -#: ../../howto/enum.rst:799 +#: ../../howto/enum.rst:792 +msgid "" +">>> Perm.X | 4\n" +"\n" +"\n" +">>> Perm.X + 8\n" +"9" +msgstr "" + +#: ../../howto/enum.rst:800 msgid "" "The negation operator, ``~``, always returns an :class:`IntFlag` member with " "a positive value::" msgstr "" -#: ../../howto/enum.rst:805 +#: ../../howto/enum.rst:803 +msgid "" +">>> (~Perm.X).value == (Perm.R|Perm.W).value == 6\n" +"True" +msgstr "" + +#: ../../howto/enum.rst:806 msgid ":class:`IntFlag` members can also be iterated over::" msgstr "" -#: ../../howto/enum.rst:814 +#: ../../howto/enum.rst:808 +msgid "" +">>> list(RW)\n" +"[, ]" +msgstr "" + +#: ../../howto/enum.rst:815 msgid "Flag" msgstr "Sinalizador" -#: ../../howto/enum.rst:816 +#: ../../howto/enum.rst:817 msgid "" "The last variation is :class:`Flag`. Like :class:`IntFlag`, :class:`Flag` " "members can be combined using the bitwise operators (&, \\|, ^, ~). Unlike :" @@ -729,29 +1298,76 @@ msgid "" "value and let :class:`Flag` select an appropriate value." msgstr "" -#: ../../howto/enum.rst:825 +#: ../../howto/enum.rst:826 msgid "" "Like :class:`IntFlag`, if a combination of :class:`Flag` members results in " "no flags being set, the boolean evaluation is :data:`False`::" msgstr "" -#: ../../howto/enum.rst:839 +#: ../../howto/enum.rst:829 +msgid "" +">>> from enum import Flag, auto\n" +">>> class Color(Flag):\n" +"... RED = auto()\n" +"... BLUE = auto()\n" +"... GREEN = auto()\n" +"...\n" +">>> Color.RED & Color.GREEN\n" +"\n" +">>> bool(Color.RED & Color.GREEN)\n" +"False" +msgstr "" + +#: ../../howto/enum.rst:840 msgid "" "Individual flags should have values that are powers of two (1, 2, 4, " "8, ...), while combinations of flags will not::" msgstr "" -#: ../../howto/enum.rst:851 +#: ../../howto/enum.rst:843 +msgid "" +">>> class Color(Flag):\n" +"... RED = auto()\n" +"... BLUE = auto()\n" +"... GREEN = auto()\n" +"... WHITE = RED | BLUE | GREEN\n" +"...\n" +">>> Color.WHITE\n" +"" +msgstr "" + +#: ../../howto/enum.rst:852 msgid "" "Giving a name to the \"no flags set\" condition does not change its boolean " "value::" msgstr "" -#: ../../howto/enum.rst:865 +#: ../../howto/enum.rst:855 +msgid "" +">>> class Color(Flag):\n" +"... BLACK = 0\n" +"... RED = auto()\n" +"... BLUE = auto()\n" +"... GREEN = auto()\n" +"...\n" +">>> Color.BLACK\n" +"\n" +">>> bool(Color.BLACK)\n" +"False" +msgstr "" + +#: ../../howto/enum.rst:866 msgid ":class:`Flag` members can also be iterated over::" msgstr "" -#: ../../howto/enum.rst:875 +#: ../../howto/enum.rst:868 +msgid "" +">>> purple = Color.RED | Color.BLUE\n" +">>> list(purple)\n" +"[, ]" +msgstr "" + +#: ../../howto/enum.rst:876 msgid "" "For the majority of new code, :class:`Enum` and :class:`Flag` are strongly " "recommended, since :class:`IntEnum` and :class:`IntFlag` break some semantic " @@ -762,42 +1378,48 @@ msgid "" "enumerations, or for interoperability with other systems." msgstr "" -#: ../../howto/enum.rst:885 +#: ../../howto/enum.rst:886 msgid "Others" msgstr "Outros" -#: ../../howto/enum.rst:887 +#: ../../howto/enum.rst:888 msgid "" "While :class:`IntEnum` is part of the :mod:`enum` module, it would be very " "simple to implement independently::" msgstr "" -#: ../../howto/enum.rst:893 +#: ../../howto/enum.rst:891 +msgid "" +"class IntEnum(int, ReprEnum): # or Enum instead of ReprEnum\n" +" pass" +msgstr "" + +#: ../../howto/enum.rst:894 msgid "" "This demonstrates how similar derived enumerations can be defined; for " -"example a :class:`FloatEnum` that mixes in :class:`float` instead of :class:" +"example a :class:`!FloatEnum` that mixes in :class:`float` instead of :class:" "`int`." msgstr "" -#: ../../howto/enum.rst:896 +#: ../../howto/enum.rst:897 msgid "Some rules:" -msgstr "" +msgstr "Algumas regras:" -#: ../../howto/enum.rst:898 +#: ../../howto/enum.rst:899 msgid "" "When subclassing :class:`Enum`, mix-in types must appear before the :class:" "`Enum` class itself in the sequence of bases, as in the :class:`IntEnum` " "example above." msgstr "" -#: ../../howto/enum.rst:901 +#: ../../howto/enum.rst:902 msgid "" "Mix-in types must be subclassable. For example, :class:`bool` and :class:" "`range` are not subclassable and will throw an error during Enum creation if " "used as the mix-in type." msgstr "" -#: ../../howto/enum.rst:904 +#: ../../howto/enum.rst:905 msgid "" "While :class:`Enum` can have members of any type, once you mix in an " "additional type, all the members must have values of that type, e.g. :class:" @@ -805,183 +1427,228 @@ msgid "" "methods and don't specify another type." msgstr "" -#: ../../howto/enum.rst:908 +#: ../../howto/enum.rst:909 msgid "" -"When another data type is mixed in, the :attr:`value` attribute is *not the " -"same* as the enum member itself, although it is equivalent and will compare " -"equal." +"When another data type is mixed in, the :attr:`~Enum.value` attribute is " +"*not the same* as the enum member itself, although it is equivalent and will " +"compare equal." msgstr "" -#: ../../howto/enum.rst:911 +#: ../../howto/enum.rst:912 msgid "" -"A ``data type`` is a mixin that defines :meth:`__new__`, or a :class:" +"A ``data type`` is a mixin that defines :meth:`~object.__new__`, or a :class:" "`~dataclasses.dataclass`" msgstr "" -#: ../../howto/enum.rst:913 +#: ../../howto/enum.rst:914 msgid "" "%-style formatting: ``%s`` and ``%r`` call the :class:`Enum` class's :meth:" -"`__str__` and :meth:`__repr__` respectively; other codes (such as ``%i`` or " -"``%h`` for IntEnum) treat the enum member as its mixed-in type." +"`~object.__str__` and :meth:`~object.__repr__` respectively; other codes " +"(such as ``%i`` or ``%h`` for IntEnum) treat the enum member as its mixed-in " +"type." msgstr "" -#: ../../howto/enum.rst:916 +#: ../../howto/enum.rst:917 msgid "" ":ref:`Formatted string literals `, :meth:`str.format`, and :func:" -"`format` will use the enum's :meth:`__str__` method." +"`format` will use the enum's :meth:`~object.__str__` method." msgstr "" -#: ../../howto/enum.rst:921 +#: ../../howto/enum.rst:922 msgid "" "Because :class:`IntEnum`, :class:`IntFlag`, and :class:`StrEnum` are " "designed to be drop-in replacements for existing constants, their :meth:" -"`__str__` method has been reset to their data types' :meth:`__str__` method." +"`~object.__str__` method has been reset to their data types' :meth:`~object." +"__str__` method." msgstr "" -#: ../../howto/enum.rst:929 -msgid "When to use :meth:`__new__` vs. :meth:`__init__`" +#: ../../howto/enum.rst:930 +msgid "When to use :meth:`~object.__new__` vs. :meth:`~object.__init__`" msgstr "" -#: ../../howto/enum.rst:931 +#: ../../howto/enum.rst:932 msgid "" -":meth:`__new__` must be used whenever you want to customize the actual value " -"of the :class:`Enum` member. Any other modifications may go in either :meth:" -"`__new__` or :meth:`__init__`, with :meth:`__init__` being preferred." +":meth:`~object.__new__` must be used whenever you want to customize the " +"actual value of the :class:`Enum` member. Any other modifications may go in " +"either :meth:`~object.__new__` or :meth:`~object.__init__`, with :meth:" +"`~object.__init__` being preferred." msgstr "" -#: ../../howto/enum.rst:935 +#: ../../howto/enum.rst:936 msgid "" "For example, if you want to pass several items to the constructor, but only " "want one of them to be the value::" msgstr "" -#: ../../howto/enum.rst:962 +#: ../../howto/enum.rst:939 +msgid "" +">>> class Coordinate(bytes, Enum):\n" +"... \"\"\"\n" +"... Coordinate with binary codes that can be indexed by the int code.\n" +"... \"\"\"\n" +"... def __new__(cls, value, label, unit):\n" +"... obj = bytes.__new__(cls, [value])\n" +"... obj._value_ = value\n" +"... obj.label = label\n" +"... obj.unit = unit\n" +"... return obj\n" +"... PX = (0, 'P.X', 'km')\n" +"... PY = (1, 'P.Y', 'km')\n" +"... VX = (2, 'V.X', 'km/s')\n" +"... VY = (3, 'V.Y', 'km/s')\n" +"...\n" +"\n" +">>> print(Coordinate['PY'])\n" +"Coordinate.PY\n" +"\n" +">>> print(Coordinate(3))\n" +"Coordinate.VY" +msgstr "" + +#: ../../howto/enum.rst:963 msgid "" "*Do not* call ``super().__new__()``, as the lookup-only ``__new__`` is the " "one that is found; instead, use the data type directly." msgstr "" -#: ../../howto/enum.rst:967 +#: ../../howto/enum.rst:968 msgid "Finer Points" msgstr "" -#: ../../howto/enum.rst:970 +#: ../../howto/enum.rst:971 msgid "Supported ``__dunder__`` names" msgstr "Nomes ``__dunder__`` suportados" -#: ../../howto/enum.rst:972 +#: ../../howto/enum.rst:973 msgid "" -":attr:`__members__` is a read-only ordered mapping of ``member_name``:" -"``member`` items. It is only available on the class." +":attr:`~enum.EnumType.__members__` is a read-only ordered mapping of " +"``member_name``:``member`` items. It is only available on the class." msgstr "" -#: ../../howto/enum.rst:975 +#: ../../howto/enum.rst:976 msgid "" -":meth:`__new__`, if specified, must create and return the enum members; it " -"is also a very good idea to set the member's :attr:`_value_` appropriately. " -"Once all the members are created it is no longer used." +":meth:`~object.__new__`, if specified, must create and return the enum " +"members; it is also a very good idea to set the member's :attr:`~Enum." +"_value_` appropriately. Once all the members are created it is no longer " +"used." msgstr "" -#: ../../howto/enum.rst:981 +#: ../../howto/enum.rst:982 msgid "Supported ``_sunder_`` names" msgstr "Nomes ``_sunder_`` suportados" -#: ../../howto/enum.rst:983 +#: ../../howto/enum.rst:984 msgid ":attr:`~Enum._name_` -- name of the member" msgstr "" -#: ../../howto/enum.rst:984 +#: ../../howto/enum.rst:985 msgid ":attr:`~Enum._value_` -- value of the member; can be set in ``__new__``" msgstr "" -#: ../../howto/enum.rst:985 +#: ../../howto/enum.rst:986 msgid "" ":meth:`~Enum._missing_` -- a lookup function used when a value is not found; " "may be overridden" msgstr "" -#: ../../howto/enum.rst:987 +#: ../../howto/enum.rst:988 msgid "" ":attr:`~Enum._ignore_` -- a list of names, either as a :class:`list` or a :" "class:`str`, that will not be transformed into members, and will be removed " "from the final class" msgstr "" -#: ../../howto/enum.rst:990 +#: ../../howto/enum.rst:991 msgid "" ":meth:`~Enum._generate_next_value_` -- used to get an appropriate value for " "an enum member; may be overridden" msgstr "" -#: ../../howto/enum.rst:992 +#: ../../howto/enum.rst:993 msgid "" -":meth:`~Enum._add_alias_` -- adds a new name as an alias to an existing " +":meth:`~EnumType._add_alias_` -- adds a new name as an alias to an existing " "member." msgstr "" -#: ../../howto/enum.rst:994 +#: ../../howto/enum.rst:995 msgid "" -":meth:`~Enum._add_value_alias_` -- adds a new value as an alias to an " +":meth:`~EnumType._add_value_alias_` -- adds a new value as an alias to an " "existing member. See `MultiValueEnum`_ for an example." msgstr "" -#: ../../howto/enum.rst:999 +#: ../../howto/enum.rst:1000 msgid "" "For standard :class:`Enum` classes the next value chosen is the highest " "value seen incremented by one." msgstr "" -#: ../../howto/enum.rst:1002 +#: ../../howto/enum.rst:1003 msgid "" "For :class:`Flag` classes the next value chosen will be the next highest " "power-of-two." msgstr "" -#: ../../howto/enum.rst:1005 +#: ../../howto/enum.rst:1006 msgid "" "Prior versions would use the last seen value instead of the highest value." msgstr "" +"Versões anteriores usariam o último valor visualizado em vez do maior valor." -#: ../../howto/enum.rst:1008 +#: ../../howto/enum.rst:1009 msgid "``_missing_``, ``_order_``, ``_generate_next_value_``" msgstr "``_missing_``, ``_order_``, ``_generate_next_value_``" -#: ../../howto/enum.rst:1009 +#: ../../howto/enum.rst:1010 msgid "``_ignore_``" msgstr "``_ignore_``" -#: ../../howto/enum.rst:1010 +#: ../../howto/enum.rst:1011 msgid "``_add_alias_``, ``_add_value_alias_``" msgstr "" -#: ../../howto/enum.rst:1012 +#: ../../howto/enum.rst:1013 msgid "" -"To help keep Python 2 / Python 3 code in sync an :attr:`_order_` attribute " -"can be provided. It will be checked against the actual order of the " -"enumeration and raise an error if the two do not match::" +"To help keep Python 2 / Python 3 code in sync an :attr:`~Enum._order_` " +"attribute can be provided. It will be checked against the actual order of " +"the enumeration and raise an error if the two do not match::" msgstr "" -#: ../../howto/enum.rst:1030 +#: ../../howto/enum.rst:1017 msgid "" -"In Python 2 code the :attr:`_order_` attribute is necessary as definition " -"order is lost before it can be recorded." +">>> class Color(Enum):\n" +"... _order_ = 'RED GREEN BLUE'\n" +"... RED = 1\n" +"... BLUE = 3\n" +"... GREEN = 2\n" +"...\n" +"Traceback (most recent call last):\n" +"...\n" +"TypeError: member order does not match _order_:\n" +" ['RED', 'BLUE', 'GREEN']\n" +" ['RED', 'GREEN', 'BLUE']" msgstr "" -#: ../../howto/enum.rst:1035 +#: ../../howto/enum.rst:1031 +msgid "" +"In Python 2 code the :attr:`~Enum._order_` attribute is necessary as " +"definition order is lost before it can be recorded." +msgstr "" + +#: ../../howto/enum.rst:1036 msgid "_Private__names" msgstr "" -#: ../../howto/enum.rst:1037 +#: ../../howto/enum.rst:1038 msgid "" ":ref:`Private names ` are not converted to enum " "members, but remain normal attributes." msgstr "" -#: ../../howto/enum.rst:1044 +#: ../../howto/enum.rst:1045 msgid "``Enum`` member type" msgstr "" -#: ../../howto/enum.rst:1046 +#: ../../howto/enum.rst:1047 msgid "" "Enum members are instances of their enum class, and are normally accessed as " "``EnumClass.member``. In certain situations, such as writing custom enum " @@ -991,22 +1658,31 @@ msgid "" "strongly recommended." msgstr "" -#: ../../howto/enum.rst:1057 +#: ../../howto/enum.rst:1058 msgid "Creating members that are mixed with other data types" msgstr "" -#: ../../howto/enum.rst:1059 +#: ../../howto/enum.rst:1060 msgid "" "When subclassing other data types, such as :class:`int` or :class:`str`, " "with an :class:`Enum`, all values after the ``=`` are passed to that data " "type's constructor. For example::" msgstr "" -#: ../../howto/enum.rst:1071 +#: ../../howto/enum.rst:1064 +msgid "" +">>> class MyEnum(IntEnum): # help(int) -> int(x, base=10) -> integer\n" +"... example = '11', 16 # so x='11' and base=16\n" +"...\n" +">>> MyEnum.example.value # and hex(11) is...\n" +"17" +msgstr "" + +#: ../../howto/enum.rst:1072 msgid "Boolean value of ``Enum`` classes and members" msgstr "" -#: ../../howto/enum.rst:1073 +#: ../../howto/enum.rst:1074 msgid "" "Enum classes that are mixed with non-:class:`Enum` types (such as :class:" "`int`, :class:`str`, etc.) are evaluated according to the mixed-in type's " @@ -1015,152 +1691,253 @@ msgid "" "your class::" msgstr "" -#: ../../howto/enum.rst:1082 +#: ../../howto/enum.rst:1080 +msgid "" +"def __bool__(self):\n" +" return bool(self.value)" +msgstr "" + +#: ../../howto/enum.rst:1083 msgid "Plain :class:`Enum` classes always evaluate as :data:`True`." msgstr "" -#: ../../howto/enum.rst:1086 +#: ../../howto/enum.rst:1087 msgid "``Enum`` classes with methods" msgstr "" -#: ../../howto/enum.rst:1088 +#: ../../howto/enum.rst:1089 msgid "" "If you give your enum subclass extra methods, like the `Planet`_ class " "below, those methods will show up in a :func:`dir` of the member, but not of " "the class::" msgstr "" -#: ../../howto/enum.rst:1099 +#: ../../howto/enum.rst:1093 +msgid "" +">>> dir(Planet)\n" +"['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', " +"'VENUS', '__class__', '__doc__', '__members__', '__module__']\n" +">>> dir(Planet.EARTH)\n" +"['__class__', '__doc__', '__module__', 'mass', 'name', 'radius', " +"'surface_gravity', 'value']" +msgstr "" + +#: ../../howto/enum.rst:1100 msgid "Combining members of ``Flag``" msgstr "" -#: ../../howto/enum.rst:1101 +#: ../../howto/enum.rst:1102 msgid "" "Iterating over a combination of :class:`Flag` members will only return the " "members that are comprised of a single bit::" msgstr "" -#: ../../howto/enum.rst:1119 +#: ../../howto/enum.rst:1105 +msgid "" +">>> class Color(Flag):\n" +"... RED = auto()\n" +"... GREEN = auto()\n" +"... BLUE = auto()\n" +"... MAGENTA = RED | BLUE\n" +"... YELLOW = RED | GREEN\n" +"... CYAN = GREEN | BLUE\n" +"...\n" +">>> Color(3) # named combination\n" +"\n" +">>> Color(7) # not named combination\n" +"" +msgstr "" + +#: ../../howto/enum.rst:1120 msgid "``Flag`` and ``IntFlag`` minutia" msgstr "" -#: ../../howto/enum.rst:1121 +#: ../../howto/enum.rst:1122 msgid "Using the following snippet for our examples::" msgstr "" -#: ../../howto/enum.rst:1132 +#: ../../howto/enum.rst:1124 +msgid "" +">>> class Color(IntFlag):\n" +"... BLACK = 0\n" +"... RED = 1\n" +"... GREEN = 2\n" +"... BLUE = 4\n" +"... PURPLE = RED | BLUE\n" +"... WHITE = RED | GREEN | BLUE\n" +"..." +msgstr "" + +#: ../../howto/enum.rst:1133 msgid "the following are true:" msgstr "" -#: ../../howto/enum.rst:1134 +#: ../../howto/enum.rst:1135 msgid "single-bit flags are canonical" msgstr "" -#: ../../howto/enum.rst:1135 +#: ../../howto/enum.rst:1136 msgid "multi-bit and zero-bit flags are aliases" msgstr "" -#: ../../howto/enum.rst:1136 +#: ../../howto/enum.rst:1137 msgid "only canonical flags are returned during iteration::" msgstr "" -#: ../../howto/enum.rst:1141 +#: ../../howto/enum.rst:1139 +msgid "" +">>> list(Color.WHITE)\n" +"[, , ]" +msgstr "" + +#: ../../howto/enum.rst:1142 msgid "" "negating a flag or flag set returns a new flag/flag set with the " "corresponding positive integer value::" msgstr "" -#: ../../howto/enum.rst:1150 +#: ../../howto/enum.rst:1145 +msgid "" +">>> Color.BLUE\n" +"\n" +"\n" +">>> ~Color.BLUE\n" +"" +msgstr "" + +#: ../../howto/enum.rst:1151 msgid "names of pseudo-flags are constructed from their members' names::" msgstr "" -#: ../../howto/enum.rst:1163 +#: ../../howto/enum.rst:1153 +msgid "" +">>> (Color.RED | Color.GREEN).name\n" +"'RED|GREEN'\n" +"\n" +">>> class Perm(IntFlag):\n" +"... R = 4\n" +"... W = 2\n" +"... X = 1\n" +"...\n" +">>> (Perm.R & Perm.W).name is None # effectively Perm(0)\n" +"True" +msgstr "" + +#: ../../howto/enum.rst:1164 msgid "multi-bit flags, aka aliases, can be returned from operations::" msgstr "" -#: ../../howto/enum.rst:1174 +#: ../../howto/enum.rst:1166 +msgid "" +">>> Color.RED | Color.BLUE\n" +"\n" +"\n" +">>> Color(7) # or Color(-1)\n" +"\n" +"\n" +">>> Color(0)\n" +"" +msgstr "" + +#: ../../howto/enum.rst:1175 msgid "" "membership / containment checking: zero-valued flags are always considered " "to be contained::" msgstr "" -#: ../../howto/enum.rst:1180 +#: ../../howto/enum.rst:1178 +msgid "" +">>> Color.BLACK in Color.WHITE\n" +"True" +msgstr "" + +#: ../../howto/enum.rst:1181 msgid "" "otherwise, only if all bits of one flag are in the other flag will True be " "returned::" msgstr "" -#: ../../howto/enum.rst:1189 +#: ../../howto/enum.rst:1184 +msgid "" +">>> Color.PURPLE in Color.WHITE\n" +"True\n" +"\n" +">>> Color.GREEN in Color.PURPLE\n" +"False" +msgstr "" + +#: ../../howto/enum.rst:1190 msgid "" "There is a new boundary mechanism that controls how out-of-range / invalid " "bits are handled: ``STRICT``, ``CONFORM``, ``EJECT``, and ``KEEP``:" msgstr "" -#: ../../howto/enum.rst:1192 +#: ../../howto/enum.rst:1193 msgid "STRICT --> raises an exception when presented with invalid values" msgstr "" -#: ../../howto/enum.rst:1193 +#: ../../howto/enum.rst:1194 msgid "CONFORM --> discards any invalid bits" msgstr "" -#: ../../howto/enum.rst:1194 +#: ../../howto/enum.rst:1195 msgid "EJECT --> lose Flag status and become a normal int with the given value" msgstr "" -#: ../../howto/enum.rst:1195 +#: ../../howto/enum.rst:1196 msgid "KEEP --> keep the extra bits" msgstr "" -#: ../../howto/enum.rst:1197 +#: ../../howto/enum.rst:1198 msgid "keeps Flag status and extra bits" msgstr "" -#: ../../howto/enum.rst:1198 +#: ../../howto/enum.rst:1199 msgid "extra bits do not show up in iteration" msgstr "" -#: ../../howto/enum.rst:1199 +#: ../../howto/enum.rst:1200 msgid "extra bits do show up in repr() and str()" msgstr "" -#: ../../howto/enum.rst:1201 +#: ../../howto/enum.rst:1202 msgid "" "The default for Flag is ``STRICT``, the default for ``IntFlag`` is " "``EJECT``, and the default for ``_convert_`` is ``KEEP`` (see ``ssl." "Options`` for an example of when ``KEEP`` is needed)." msgstr "" -#: ../../howto/enum.rst:1209 +#: ../../howto/enum.rst:1210 msgid "How are Enums and Flags different?" msgstr "" -#: ../../howto/enum.rst:1211 +#: ../../howto/enum.rst:1212 msgid "" "Enums have a custom metaclass that affects many aspects of both derived :" "class:`Enum` classes and their instances (members)." msgstr "" -#: ../../howto/enum.rst:1216 +#: ../../howto/enum.rst:1217 msgid "Enum Classes" msgstr "" -#: ../../howto/enum.rst:1218 +#: ../../howto/enum.rst:1219 msgid "" "The :class:`EnumType` metaclass is responsible for providing the :meth:" -"`__contains__`, :meth:`__dir__`, :meth:`__iter__` and other methods that " -"allow one to do things with an :class:`Enum` class that fail on a typical " -"class, such as ``list(Color)`` or ``some_enum_var in Color``. :class:" -"`EnumType` is responsible for ensuring that various other methods on the " -"final :class:`Enum` class are correct (such as :meth:`__new__`, :meth:" -"`__getnewargs__`, :meth:`__str__` and :meth:`__repr__`)." +"`~object.__contains__`, :meth:`~object.__dir__`, :meth:`~object.__iter__` " +"and other methods that allow one to do things with an :class:`Enum` class " +"that fail on a typical class, such as ``list(Color)`` or ``some_enum_var in " +"Color``. :class:`EnumType` is responsible for ensuring that various other " +"methods on the final :class:`Enum` class are correct (such as :meth:`~object." +"__new__`, :meth:`~object.__getnewargs__`, :meth:`~object.__str__` and :meth:" +"`~object.__repr__`)." msgstr "" -#: ../../howto/enum.rst:1227 +#: ../../howto/enum.rst:1228 msgid "Flag Classes" msgstr "" -#: ../../howto/enum.rst:1229 +#: ../../howto/enum.rst:1230 msgid "" "Flags have an expanded view of aliasing: to be canonical, the value of a " "flag needs to be a power-of-two value, and not a duplicate name. So, in " @@ -1169,50 +1946,68 @@ msgid "" "considered an alias." msgstr "" -#: ../../howto/enum.rst:1235 +#: ../../howto/enum.rst:1236 msgid "Enum Members (aka instances)" msgstr "" -#: ../../howto/enum.rst:1237 +#: ../../howto/enum.rst:1238 msgid "" "The most interesting thing about enum members is that they are singletons. :" "class:`EnumType` creates them all while it is creating the enum class " -"itself, and then puts a custom :meth:`__new__` in place to ensure that no " -"new ones are ever instantiated by returning only the existing member " +"itself, and then puts a custom :meth:`~object.__new__` in place to ensure " +"that no new ones are ever instantiated by returning only the existing member " "instances." msgstr "" -#: ../../howto/enum.rst:1243 +#: ../../howto/enum.rst:1244 msgid "Flag Members" msgstr "" -#: ../../howto/enum.rst:1245 +#: ../../howto/enum.rst:1246 msgid "" "Flag members can be iterated over just like the :class:`Flag` class, and " "only the canonical members will be returned. For example::" msgstr "" -#: ../../howto/enum.rst:1251 +#: ../../howto/enum.rst:1249 +msgid "" +">>> list(Color)\n" +"[, , ]" +msgstr "" + +#: ../../howto/enum.rst:1252 msgid "(Note that ``BLACK``, ``PURPLE``, and ``WHITE`` do not show up.)" msgstr "" -#: ../../howto/enum.rst:1253 +#: ../../howto/enum.rst:1254 msgid "" "Inverting a flag member returns the corresponding positive value, rather " "than a negative value --- for example::" msgstr "" -#: ../../howto/enum.rst:1259 +#: ../../howto/enum.rst:1257 +msgid "" +">>> ~Color.RED\n" +"" +msgstr "" + +#: ../../howto/enum.rst:1260 msgid "" "Flag members have a length corresponding to the number of power-of-two " "values they contain. For example::" msgstr "" -#: ../../howto/enum.rst:1269 +#: ../../howto/enum.rst:1263 +msgid "" +">>> len(Color.PURPLE)\n" +"2" +msgstr "" + +#: ../../howto/enum.rst:1270 msgid "Enum Cookbook" msgstr "" -#: ../../howto/enum.rst:1272 +#: ../../howto/enum.rst:1273 msgid "" "While :class:`Enum`, :class:`IntEnum`, :class:`StrEnum`, :class:`Flag`, and :" "class:`IntFlag` are expected to cover the majority of use-cases, they cannot " @@ -1220,163 +2015,378 @@ msgid "" "that can be used directly, or as examples for creating one's own." msgstr "" -#: ../../howto/enum.rst:1279 +#: ../../howto/enum.rst:1280 msgid "Omitting values" msgstr "" -#: ../../howto/enum.rst:1281 +#: ../../howto/enum.rst:1282 msgid "" "In many use-cases, one doesn't care what the actual value of an enumeration " "is. There are several ways to define this type of simple enumeration:" msgstr "" -#: ../../howto/enum.rst:1284 +#: ../../howto/enum.rst:1285 msgid "use instances of :class:`auto` for the value" msgstr "" -#: ../../howto/enum.rst:1285 +#: ../../howto/enum.rst:1286 msgid "use instances of :class:`object` as the value" msgstr "" -#: ../../howto/enum.rst:1286 +#: ../../howto/enum.rst:1287 msgid "use a descriptive string as the value" msgstr "" -#: ../../howto/enum.rst:1287 +#: ../../howto/enum.rst:1288 msgid "" -"use a tuple as the value and a custom :meth:`__new__` to replace the tuple " -"with an :class:`int` value" +"use a tuple as the value and a custom :meth:`~object.__new__` to replace the " +"tuple with an :class:`int` value" msgstr "" -#: ../../howto/enum.rst:1290 +#: ../../howto/enum.rst:1291 msgid "" "Using any of these methods signifies to the user that these values are not " "important, and also enables one to add, remove, or reorder members without " "having to renumber the remaining members." msgstr "" -#: ../../howto/enum.rst:1296 +#: ../../howto/enum.rst:1297 msgid "Using :class:`auto`" msgstr "" -#: ../../howto/enum.rst:1298 +#: ../../howto/enum.rst:1299 msgid "Using :class:`auto` would look like::" msgstr "" -#: ../../howto/enum.rst:1310 +#: ../../howto/enum.rst:1301 +msgid "" +">>> class Color(Enum):\n" +"... RED = auto()\n" +"... BLUE = auto()\n" +"... GREEN = auto()\n" +"...\n" +">>> Color.GREEN\n" +"" +msgstr "" + +#: ../../howto/enum.rst:1311 msgid "Using :class:`object`" msgstr "" -#: ../../howto/enum.rst:1312 +#: ../../howto/enum.rst:1313 msgid "Using :class:`object` would look like::" msgstr "" -#: ../../howto/enum.rst:1322 +#: ../../howto/enum.rst:1315 +msgid "" +">>> class Color(Enum):\n" +"... RED = object()\n" +"... GREEN = object()\n" +"... BLUE = object()\n" +"...\n" +">>> Color.GREEN\n" +">" +msgstr "" + +#: ../../howto/enum.rst:1323 msgid "" "This is also a good example of why you might want to write your own :meth:" -"`__repr__`::" +"`~object.__repr__`::" msgstr "" -#: ../../howto/enum.rst:1338 +#: ../../howto/enum.rst:1326 +msgid "" +">>> class Color(Enum):\n" +"... RED = object()\n" +"... GREEN = object()\n" +"... BLUE = object()\n" +"... def __repr__(self):\n" +"... return \"<%s.%s>\" % (self.__class__.__name__, self._name_)\n" +"...\n" +">>> Color.GREEN\n" +"" +msgstr "" + +#: ../../howto/enum.rst:1339 msgid "Using a descriptive string" msgstr "" -#: ../../howto/enum.rst:1340 +#: ../../howto/enum.rst:1341 msgid "Using a string as the value would look like::" msgstr "" -#: ../../howto/enum.rst:1352 -msgid "Using a custom :meth:`__new__`" -msgstr "Usando um :meth:`__new__` personalizado" +#: ../../howto/enum.rst:1343 +msgid "" +">>> class Color(Enum):\n" +"... RED = 'stop'\n" +"... GREEN = 'go'\n" +"... BLUE = 'too fast!'\n" +"...\n" +">>> Color.GREEN\n" +"" +msgstr "" -#: ../../howto/enum.rst:1354 -msgid "Using an auto-numbering :meth:`__new__` would look like::" +#: ../../howto/enum.rst:1353 +msgid "Using a custom :meth:`~object.__new__`" msgstr "" -#: ../../howto/enum.rst:1371 +#: ../../howto/enum.rst:1355 +msgid "Using an auto-numbering :meth:`~object.__new__` would look like::" +msgstr "" + +#: ../../howto/enum.rst:1357 +msgid "" +">>> class AutoNumber(Enum):\n" +"... def __new__(cls):\n" +"... value = len(cls.__members__) + 1\n" +"... obj = object.__new__(cls)\n" +"... obj._value_ = value\n" +"... return obj\n" +"...\n" +">>> class Color(AutoNumber):\n" +"... RED = ()\n" +"... GREEN = ()\n" +"... BLUE = ()\n" +"...\n" +">>> Color.GREEN\n" +"" +msgstr "" + +#: ../../howto/enum.rst:1372 msgid "" "To make a more general purpose ``AutoNumber``, add ``*args`` to the " "signature::" msgstr "" -#: ../../howto/enum.rst:1381 +#: ../../howto/enum.rst:1374 +msgid "" +">>> class AutoNumber(Enum):\n" +"... def __new__(cls, *args): # this is the only change from above\n" +"... value = len(cls.__members__) + 1\n" +"... obj = object.__new__(cls)\n" +"... obj._value_ = value\n" +"... return obj\n" +"..." +msgstr "" + +#: ../../howto/enum.rst:1382 msgid "" "Then when you inherit from ``AutoNumber`` you can write your own " "``__init__`` to handle any extra arguments::" msgstr "" -#: ../../howto/enum.rst:1400 +#: ../../howto/enum.rst:1385 msgid "" -"The :meth:`__new__` method, if defined, is used during creation of the Enum " -"members; it is then replaced by Enum's :meth:`__new__` which is used after " -"class creation for lookup of existing members." +">>> class Swatch(AutoNumber):\n" +"... def __init__(self, pantone='unknown'):\n" +"... self.pantone = pantone\n" +"... AUBURN = '3497'\n" +"... SEA_GREEN = '1246'\n" +"... BLEACHED_CORAL = () # New color, no Pantone code yet!\n" +"...\n" +">>> Swatch.SEA_GREEN\n" +"\n" +">>> Swatch.SEA_GREEN.pantone\n" +"'1246'\n" +">>> Swatch.BLEACHED_CORAL.pantone\n" +"'unknown'" msgstr "" -#: ../../howto/enum.rst:1406 +#: ../../howto/enum.rst:1401 +msgid "" +"The :meth:`~object.__new__` method, if defined, is used during creation of " +"the Enum members; it is then replaced by Enum's :meth:`~object.__new__` " +"which is used after class creation for lookup of existing members." +msgstr "" + +#: ../../howto/enum.rst:1407 msgid "" "*Do not* call ``super().__new__()``, as the lookup-only ``__new__`` is the " "one that is found; instead, use the data type directly -- e.g.::" msgstr "" -#: ../../howto/enum.rst:1413 +#: ../../howto/enum.rst:1410 +msgid "obj = int.__new__(cls, value)" +msgstr "" + +#: ../../howto/enum.rst:1414 msgid "OrderedEnum" msgstr "OrderedEnum" -#: ../../howto/enum.rst:1415 +#: ../../howto/enum.rst:1416 msgid "" "An ordered enumeration that is not based on :class:`IntEnum` and so " "maintains the normal :class:`Enum` invariants (such as not being comparable " "to other enumerations)::" msgstr "" -#: ../../howto/enum.rst:1449 +#: ../../howto/enum.rst:1420 +msgid "" +">>> class OrderedEnum(Enum):\n" +"... def __ge__(self, other):\n" +"... if self.__class__ is other.__class__:\n" +"... return self.value >= other.value\n" +"... return NotImplemented\n" +"... def __gt__(self, other):\n" +"... if self.__class__ is other.__class__:\n" +"... return self.value > other.value\n" +"... return NotImplemented\n" +"... def __le__(self, other):\n" +"... if self.__class__ is other.__class__:\n" +"... return self.value <= other.value\n" +"... return NotImplemented\n" +"... def __lt__(self, other):\n" +"... if self.__class__ is other.__class__:\n" +"... return self.value < other.value\n" +"... return NotImplemented\n" +"...\n" +">>> class Grade(OrderedEnum):\n" +"... A = 5\n" +"... B = 4\n" +"... C = 3\n" +"... D = 2\n" +"... F = 1\n" +"...\n" +">>> Grade.C < Grade.A\n" +"True" +msgstr "" + +#: ../../howto/enum.rst:1450 msgid "DuplicateFreeEnum" msgstr "DuplicateFreeEnum" -#: ../../howto/enum.rst:1451 +#: ../../howto/enum.rst:1452 msgid "" "Raises an error if a duplicate member value is found instead of creating an " "alias::" msgstr "" -#: ../../howto/enum.rst:1476 +#: ../../howto/enum.rst:1455 +msgid "" +">>> class DuplicateFreeEnum(Enum):\n" +"... def __init__(self, *args):\n" +"... cls = self.__class__\n" +"... if any(self.value == e.value for e in cls):\n" +"... a = self.name\n" +"... e = cls(self.value).name\n" +"... raise ValueError(\n" +"... \"aliases not allowed in DuplicateFreeEnum: %r --> " +"%r\"\n" +"... % (a, e))\n" +"...\n" +">>> class Color(DuplicateFreeEnum):\n" +"... RED = 1\n" +"... GREEN = 2\n" +"... BLUE = 3\n" +"... GRENE = 2\n" +"...\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN'" +msgstr "" + +#: ../../howto/enum.rst:1477 msgid "" "This is a useful example for subclassing Enum to add or change other " "behaviors as well as disallowing aliases. If the only desired change is " "disallowing aliases, the :func:`unique` decorator can be used instead." msgstr "" -#: ../../howto/enum.rst:1482 +#: ../../howto/enum.rst:1483 msgid "MultiValueEnum" msgstr "" -#: ../../howto/enum.rst:1484 +#: ../../howto/enum.rst:1485 msgid "Supports having more than one value per member::" msgstr "" -#: ../../howto/enum.rst:1505 +#: ../../howto/enum.rst:1487 +msgid "" +">>> class MultiValueEnum(Enum):\n" +"... def __new__(cls, value, *values):\n" +"... self = object.__new__(cls)\n" +"... self._value_ = value\n" +"... for v in values:\n" +"... self._add_value_alias_(v)\n" +"... return self\n" +"...\n" +">>> class DType(MultiValueEnum):\n" +"... float32 = 'f', 8\n" +"... double64 = 'd', 9\n" +"...\n" +">>> DType('f')\n" +"\n" +">>> DType(9)\n" +"" +msgstr "" + +#: ../../howto/enum.rst:1506 msgid "Planet" msgstr "" -#: ../../howto/enum.rst:1507 +#: ../../howto/enum.rst:1508 msgid "" -"If :meth:`__new__` or :meth:`__init__` is defined, the value of the enum " -"member will be passed to those methods::" +"If :meth:`~object.__new__` or :meth:`~object.__init__` is defined, the value " +"of the enum member will be passed to those methods::" msgstr "" -#: ../../howto/enum.rst:1536 +#: ../../howto/enum.rst:1511 +msgid "" +">>> class Planet(Enum):\n" +"... MERCURY = (3.303e+23, 2.4397e6)\n" +"... VENUS = (4.869e+24, 6.0518e6)\n" +"... EARTH = (5.976e+24, 6.37814e6)\n" +"... MARS = (6.421e+23, 3.3972e6)\n" +"... JUPITER = (1.9e+27, 7.1492e7)\n" +"... SATURN = (5.688e+26, 6.0268e7)\n" +"... URANUS = (8.686e+25, 2.5559e7)\n" +"... NEPTUNE = (1.024e+26, 2.4746e7)\n" +"... def __init__(self, mass, radius):\n" +"... self.mass = mass # in kilograms\n" +"... self.radius = radius # in meters\n" +"... @property\n" +"... def surface_gravity(self):\n" +"... # universal gravitational constant (m3 kg-1 s-2)\n" +"... G = 6.67300E-11\n" +"... return G * self.mass / (self.radius * self.radius)\n" +"...\n" +">>> Planet.EARTH.value\n" +"(5.976e+24, 6378140.0)\n" +">>> Planet.EARTH.surface_gravity\n" +"9.802652743337129" +msgstr "" + +#: ../../howto/enum.rst:1537 msgid "TimePeriod" msgstr "TimePeriod" -#: ../../howto/enum.rst:1538 -msgid "An example to show the :attr:`_ignore_` attribute in use::" +#: ../../howto/enum.rst:1539 +msgid "An example to show the :attr:`~Enum._ignore_` attribute in use::" +msgstr "" + +#: ../../howto/enum.rst:1541 +msgid "" +">>> from datetime import timedelta\n" +">>> class Period(timedelta, Enum):\n" +"... \"different lengths of time\"\n" +"... _ignore_ = 'Period i'\n" +"... Period = vars()\n" +"... for i in range(367):\n" +"... Period['day_%d' % i] = i\n" +"...\n" +">>> list(Period)[:2]\n" +"[, ]\n" +">>> list(Period)[-2:]\n" +"[, ]" msgstr "" -#: ../../howto/enum.rst:1557 +#: ../../howto/enum.rst:1558 msgid "Subclassing EnumType" msgstr "" -#: ../../howto/enum.rst:1559 +#: ../../howto/enum.rst:1560 msgid "" "While most enum needs can be met by customizing :class:`Enum` subclasses, " "either with class decorators or custom functions, :class:`EnumType` can be " diff --git a/howto/free-threading-extensions.po b/howto/free-threading-extensions.po index fde63083e..6d45668ae 100644 --- a/howto/free-threading-extensions.po +++ b/howto/free-threading-extensions.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# felipe caridade fernandes , 2024 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2024-06-20 06:42+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -57,6 +55,16 @@ msgstr "" "está definida. Você pode usá-la para ativar o código que é executado apenas " "na construção de threads livres::" +#: ../../howto/free-threading-extensions.rst:22 +msgid "" +"#ifdef Py_GIL_DISABLED\n" +"/* code that only runs in the free-threaded build */\n" +"#endif" +msgstr "" +"#ifdef Py_GIL_DISABLED\n" +"/* código que só vai ser executado na construção de threads livres */\n" +"#endif" + #: ../../howto/free-threading-extensions.rst:27 msgid "Module Initialization" msgstr "Inicialização de módulo" @@ -98,6 +106,36 @@ msgstr "" "CPython, você deve proteger o slot com uma verificação de :c:data:" "`PY_VERSION_HEX`." +#: ../../howto/free-threading-extensions.rst:47 +msgid "" +"static struct PyModuleDef_Slot module_slots[] = {\n" +" ...\n" +"#if PY_VERSION_HEX >= 0x030D0000\n" +" {Py_mod_gil, Py_MOD_GIL_NOT_USED},\n" +"#endif\n" +" {0, NULL}\n" +"};\n" +"\n" +"static struct PyModuleDef moduledef = {\n" +" PyModuleDef_HEAD_INIT,\n" +" .m_slots = module_slots,\n" +" ...\n" +"};" +msgstr "" +"static struct PyModuleDef_Slot module_slots[] = {\n" +" ...\n" +"#if PY_VERSION_HEX >= 0x030D0000\n" +" {Py_mod_gil, Py_MOD_GIL_NOT_USED},\n" +"#endif\n" +" {0, NULL}\n" +"};\n" +"\n" +"static struct PyModuleDef moduledef = {\n" +" PyModuleDef_HEAD_INIT,\n" +" .m_slots = module_slots,\n" +" ...\n" +"};" + #: ../../howto/free-threading-extensions.rst:63 msgid "Single-Phase Initialization" msgstr "Inicialização monofásica" @@ -117,6 +155,44 @@ msgstr "" "chamada com ``#ifdef Py_GIL_DISABLED`` para evitar erros de compilação na " "construção regular." +#: ../../howto/free-threading-extensions.rst:73 +msgid "" +"static struct PyModuleDef moduledef = {\n" +" PyModuleDef_HEAD_INIT,\n" +" ...\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_mymodule(void)\n" +"{\n" +" PyObject *m = PyModule_Create(&moduledef);\n" +" if (m == NULL) {\n" +" return NULL;\n" +" }\n" +"#ifdef Py_GIL_DISABLED\n" +" PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);\n" +"#endif\n" +" return m;\n" +"}" +msgstr "" +"static struct PyModuleDef moduledef = {\n" +" PyModuleDef_HEAD_INIT,\n" +" ...\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_mymodule(void)\n" +"{\n" +" PyObject *m = PyModule_Create(&moduledef);\n" +" if (m == NULL) {\n" +" return NULL;\n" +" }\n" +"#ifdef Py_GIL_DISABLED\n" +" PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);\n" +"#endif\n" +" return m;\n" +"}" + #: ../../howto/free-threading-extensions.rst:93 msgid "General API Guidelines" msgstr "Diretrizes gerais de API" @@ -190,6 +266,24 @@ msgstr "" "dicionário enquanto itera sobre ele se o dicionário puder ser modificado " "simultaneamente::" +#: ../../howto/free-threading-extensions.rst:127 +msgid "" +"Py_BEGIN_CRITICAL_SECTION(dict);\n" +"PyObject *key, *value;\n" +"Py_ssize_t pos = 0;\n" +"while (PyDict_Next(dict, &pos, &key, &value)) {\n" +" ...\n" +"}\n" +"Py_END_CRITICAL_SECTION();" +msgstr "" +"Py_BEGIN_CRITICAL_SECTION(dict);\n" +"PyObject *key, *value;\n" +"Py_ssize_t pos = 0;\n" +"while (PyDict_Next(dict, &pos, &key, &value)) {\n" +" ...\n" +"}\n" +"Py_END_CRITICAL_SECTION();" + #: ../../howto/free-threading-extensions.rst:137 msgid "Borrowed References" msgstr "Referências emprestadas" @@ -318,11 +412,11 @@ msgstr "" "para fornecer implementações dessas funções para versões mais antigas do " "Python." -#: ../../howto/free-threading-extensions.rst:185 +#: ../../howto/free-threading-extensions.rst:187 msgid "Memory Allocation APIs" msgstr "APIs de alocação de memória" -#: ../../howto/free-threading-extensions.rst:187 +#: ../../howto/free-threading-extensions.rst:189 msgid "" "Python's memory management C API provides functions in three different :ref:" "`allocation domains `: \"raw\", \"mem\", and \"object\". " @@ -339,7 +433,7 @@ msgstr "" "versões anteriores do Python, onde era apenas uma melhor prática e não um " "requisito estrito." -#: ../../howto/free-threading-extensions.rst:196 +#: ../../howto/free-threading-extensions.rst:198 msgid "" "Search for uses of :c:func:`PyObject_Malloc` in your extension and check " "that the allocated memory is used for Python objects. Use :c:func:" @@ -349,11 +443,11 @@ msgstr "" "memória alocada é usada para objetos Python. Use :c:func:`PyMem_Malloc` para " "alocar buffers em vez de :c:func:`PyObject_Malloc`." -#: ../../howto/free-threading-extensions.rst:203 +#: ../../howto/free-threading-extensions.rst:205 msgid "Thread State and GIL APIs" msgstr "APIs da GIL e de estado de threads" -#: ../../howto/free-threading-extensions.rst:205 +#: ../../howto/free-threading-extensions.rst:207 msgid "" "Python provides a set of functions and macros to manage thread state and the " "GIL, such as:" @@ -361,19 +455,19 @@ msgstr "" "Python fornece um conjunto de funções e macros para gerenciar o estado de " "threads e a GIL, como:" -#: ../../howto/free-threading-extensions.rst:208 +#: ../../howto/free-threading-extensions.rst:210 msgid ":c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release`" msgstr ":c:func:`PyGILState_Ensure` e :c:func:`PyGILState_Release`" -#: ../../howto/free-threading-extensions.rst:209 +#: ../../howto/free-threading-extensions.rst:211 msgid ":c:func:`PyEval_SaveThread` and :c:func:`PyEval_RestoreThread`" msgstr ":c:func:`PyEval_SaveThread` e :c:func:`PyEval_RestoreThread`" -#: ../../howto/free-threading-extensions.rst:210 +#: ../../howto/free-threading-extensions.rst:212 msgid ":c:macro:`Py_BEGIN_ALLOW_THREADS` and :c:macro:`Py_END_ALLOW_THREADS`" msgstr ":c:macro:`Py_BEGIN_ALLOW_THREADS` e :c:macro:`Py_END_ALLOW_THREADS`" -#: ../../howto/free-threading-extensions.rst:212 +#: ../../howto/free-threading-extensions.rst:214 msgid "" "These functions should still be used in the free-threaded build to manage " "thread state even when the :term:`GIL` is disabled. For example, if you " @@ -387,7 +481,7 @@ msgstr "" "func:`PyGILState_Ensure` antes de chamar a API Python para garantir que a " "thread tenha um estado de thread válido para o Python." -#: ../../howto/free-threading-extensions.rst:218 +#: ../../howto/free-threading-extensions.rst:220 msgid "" "You should continue to call :c:func:`PyEval_SaveThread` or :c:macro:" "`Py_BEGIN_ALLOW_THREADS` around blocking operations, such as I/O or lock " @@ -399,11 +493,11 @@ msgstr "" "aquisições de trava, para permitir que outras threads executem o :term:" "`coletor de lixo cíclico `." -#: ../../howto/free-threading-extensions.rst:225 +#: ../../howto/free-threading-extensions.rst:227 msgid "Protecting Internal Extension State" msgstr "Protegendo o estado interno das extensões" -#: ../../howto/free-threading-extensions.rst:227 +#: ../../howto/free-threading-extensions.rst:229 msgid "" "Your extension may have internal state that was previously protected by the " "GIL. You may need to add locking to protect this state. The approach will " @@ -413,7 +507,7 @@ msgstr "" "GIL. Talvez seja necessário adicionar uma trava para proteger esse estado. A " "abordagem dependerá da sua extensão, mas alguns padrões comuns incluem:" -#: ../../howto/free-threading-extensions.rst:231 +#: ../../howto/free-threading-extensions.rst:233 msgid "" "**Caches**: global caches are a common source of shared state. Consider " "using a lock to protect the cache or disabling it in the free-threaded build " @@ -423,7 +517,7 @@ msgstr "" "Considere usar uma trava para proteger o cache ou desativá-lo na construção " "com threads livres se o cache não for crítico para o desempenho." -#: ../../howto/free-threading-extensions.rst:234 +#: ../../howto/free-threading-extensions.rst:236 msgid "" "**Global State**: global state may need to be protected by a lock or moved " "to thread local storage. C11 and C++11 provide the ``thread_local`` or " @@ -435,11 +529,11 @@ msgstr "" "``thread_local`` ou ``_Thread_local`` para `armazenamento local de thread " "`_." -#: ../../howto/free-threading-extensions.rst:241 +#: ../../howto/free-threading-extensions.rst:243 msgid "Building Extensions for the Free-Threaded Build" msgstr "Construindo extensões para a construção com threads livres" -#: ../../howto/free-threading-extensions.rst:243 +#: ../../howto/free-threading-extensions.rst:245 msgid "" "C API extensions need to be built specifically for the free-threaded build. " "The wheels, shared libraries, and binaries are indicated by a ``t`` suffix." @@ -448,7 +542,7 @@ msgstr "" "construção com threads livres. As wheels, bibliotecas compartilhadas e " "binários são indicados por um sufixo ``t``." -#: ../../howto/free-threading-extensions.rst:246 +#: ../../howto/free-threading-extensions.rst:248 msgid "" "`pypa/manylinux `_ supports the free-" "threaded build, with the ``t`` suffix, such as ``python3.13t``." @@ -456,7 +550,7 @@ msgstr "" "`pypa/manylinux `_ oferece suporte à " "construção com threads livres, com o sufixo ``t``, como ``python3.13t``." -#: ../../howto/free-threading-extensions.rst:248 +#: ../../howto/free-threading-extensions.rst:250 msgid "" "`pypa/cibuildwheel `_ supports the " "free-threaded build if you set `CIBW_FREE_THREADED_SUPPORT `_." -#: ../../howto/free-threading-extensions.rst:253 +#: ../../howto/free-threading-extensions.rst:255 msgid "Limited C API and Stable ABI" msgstr "API C limitada e ABI estável" -#: ../../howto/free-threading-extensions.rst:255 +#: ../../howto/free-threading-extensions.rst:257 msgid "" "The free-threaded build does not currently support the :ref:`Limited C API " "` or the stable ABI. If you use `setuptools `_: A community-maintained porting guide for " +"extension authors." +msgstr "" +"`Portando módulos de extensão para oferecer suporte a threads livres " +"`_: um guia de portabilidade " +"mantido pela comunidade para autores de extensões." diff --git a/howto/free-threading-python.po b/howto/free-threading-python.po new file mode 100644 index 000000000..5cb22f6a9 --- /dev/null +++ b/howto/free-threading-python.po @@ -0,0 +1,358 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../howto/free-threading-python.rst:5 +msgid "Python experimental support for free threading" +msgstr "Suporte experimental do Python para threads livres" + +#: ../../howto/free-threading-python.rst:7 +msgid "" +"Starting with the 3.13 release, CPython has experimental support for a build " +"of Python called :term:`free threading` where the :term:`global interpreter " +"lock` (GIL) is disabled. Free-threaded execution allows for full " +"utilization of the available processing power by running threads in parallel " +"on available CPU cores. While not all software will benefit from this " +"automatically, programs designed with threading in mind will run faster on " +"multi-core hardware." +msgstr "" +"A partir da versão 3.13, o CPython tem suporte experimental para uma " +"compilação do Python chamada :term:`threads livres` (em inglês, free " +"threading), onde a :term:`trava global do interpretador` (GIL) está " +"desabilitada. A execução com threads livres permite a utilização total do " +"poder de processamento disponível, executando threads em paralelo nos " +"núcleos de CPU disponíveis. Embora nem todos os softwares se beneficiem " +"disso automaticamente, os programas projetados com uso de threads em mente " +"serão executados mais rapidamente em hardware com vários núcleos." + +#: ../../howto/free-threading-python.rst:14 +msgid "" +"**The free-threaded mode is experimental** and work is ongoing to improve " +"it: expect some bugs and a substantial single-threaded performance hit." +msgstr "" +"**O modo de threads livres é experimental** e há um trabalho contínuo para " +"melhorá-lo: espere alguns bugs e uma perda substancial no desempenho da " +"thread única." + +#: ../../howto/free-threading-python.rst:17 +msgid "" +"This document describes the implications of free threading for Python code. " +"See :ref:`freethreading-extensions-howto` for information on how to write C " +"extensions that support the free-threaded build." +msgstr "" +"Este documento descreve as implicações de threads livres para o código " +"Python. Veja :ref:`freethreading-extensions-howto` para informações sobre " +"como escrever extensões C que oferecem suporte à construção com threads " +"livres." + +#: ../../howto/free-threading-python.rst:23 +msgid "" +":pep:`703` – Making the Global Interpreter Lock Optional in CPython for an " +"overall description of free-threaded Python." +msgstr "" +":pep:`703` – Tornando a trava global do interpretador opcional no CPython " +"para uma descrição geral do Python com threads livres." + +#: ../../howto/free-threading-python.rst:28 +msgid "Installation" +msgstr "Instalação" + +#: ../../howto/free-threading-python.rst:30 +msgid "" +"Starting with Python 3.13, the official macOS and Windows installers " +"optionally support installing free-threaded Python binaries. The installers " +"are available at https://www.python.org/downloads/." +msgstr "" +"A partir do Python 3.13, os instaladores oficiais do macOS e do Windows " +"oferecem suporte opcional à instalação de binários Python com threads " +"livres. Os instaladores estão disponíveis em https://www.python.org/" +"downloads/." + +#: ../../howto/free-threading-python.rst:34 +msgid "" +"For information on other platforms, see the `Installing a Free-Threaded " +"Python `_, a " +"community-maintained installation guide for installing free-threaded Python." +msgstr "" +"Para obter informações sobre outras plataformas, consulte `Instalando um " +"Python com threads livres `_, um guia de instalação mantido pela comunidade para " +"instalar o Python com threads livres." + +#: ../../howto/free-threading-python.rst:38 +msgid "" +"When building CPython from source, the :option:`--disable-gil` configure " +"option should be used to build a free-threaded Python interpreter." +msgstr "" +"Ao construir o CPython a partir do código-fonte, a opção de configuração :" +"option:`--disable-gil` deve ser usada para construir um interpretador Python " +"com threads livres." + +#: ../../howto/free-threading-python.rst:43 +msgid "Identifying free-threaded Python" +msgstr "Identificando um Python com threads livres" + +#: ../../howto/free-threading-python.rst:45 +msgid "" +"To check if the current interpreter supports free-threading, :option:`python " +"-VV <-V>` and :data:`sys.version` contain \"experimental free-threading " +"build\". The new :func:`sys._is_gil_enabled` function can be used to check " +"whether the GIL is actually disabled in the running process." +msgstr "" +"Para verificar se o interpretador atual oferece suporte a threads livres, :" +"option:`python -VV <-V>` e :data:`sys.version` contêm \"experimental free-" +"threading build\". A nova função :func:`sys._is_gil_enabled` pode ser usada " +"para verificar se a GIL está realmente desabilitada no processo em execução." + +#: ../../howto/free-threading-python.rst:50 +msgid "" +"The ``sysconfig.get_config_var(\"Py_GIL_DISABLED\")`` configuration variable " +"can be used to determine whether the build supports free threading. If the " +"variable is set to ``1``, then the build supports free threading. This is " +"the recommended mechanism for decisions related to the build configuration." +msgstr "" +"A variável de configuração ``sysconfig.get_config_var(\"Py_GIL_DISABLED\")`` " +"pode ser usada para determinar se a compilação tem suporte a threads livres. " +"Se a variável for definida como ``1``, a compilação tem suporte a threads " +"livres. Este é o mecanismo recomendado para decisões relacionadas à " +"configuração da construção." + +#: ../../howto/free-threading-python.rst:57 +msgid "The global interpreter lock in free-threaded Python" +msgstr "A trava global do interpretador no Python com threads livres" + +#: ../../howto/free-threading-python.rst:59 +msgid "" +"Free-threaded builds of CPython support optionally running with the GIL " +"enabled at runtime using the environment variable :envvar:`PYTHON_GIL` or " +"the command-line option :option:`-X gil`." +msgstr "" +"Construções com threads livres do CPython oferecem suporte a opcionalmente " +"executar com a GIL habilitada em tempo de execução usando a variável de " +"ambiente :envvar:`PYTHON_GIL` ou a opção de linha de comando :option:`-X " +"gil`." + +#: ../../howto/free-threading-python.rst:63 +msgid "" +"The GIL may also automatically be enabled when importing a C-API extension " +"module that is not explicitly marked as supporting free threading. A " +"warning will be printed in this case." +msgstr "" +"A GIL também pode ser habilitada automaticamente ao importar um módulo de " +"extensão da API C que não esteja explicitamente marcado como oferecendo " +"suporte a threads livres. Um aviso será impresso neste caso." + +#: ../../howto/free-threading-python.rst:67 +msgid "" +"In addition to individual package documentation, the following websites " +"track the status of popular packages support for free threading:" +msgstr "" +"Além da documentação de pacotes individuais, os seguintes sites rastreiam o " +"status do suporte de pacotes populares para threads livres:" + +#: ../../howto/free-threading-python.rst:70 +msgid "https://py-free-threading.github.io/tracking/" +msgstr "https://py-free-threading.github.io/tracking/" + +#: ../../howto/free-threading-python.rst:71 +msgid "https://hugovk.github.io/free-threaded-wheels/" +msgstr "https://hugovk.github.io/free-threaded-wheels/" + +#: ../../howto/free-threading-python.rst:75 +msgid "Thread safety" +msgstr "Segurança nas threads" + +#: ../../howto/free-threading-python.rst:77 +msgid "" +"The free-threaded build of CPython aims to provide similar thread-safety " +"behavior at the Python level to the default GIL-enabled build. Built-in " +"types like :class:`dict`, :class:`list`, and :class:`set` use internal locks " +"to protect against concurrent modifications in ways that behave similarly to " +"the GIL. However, Python has not historically guaranteed specific behavior " +"for concurrent modifications to these built-in types, so this should be " +"treated as a description of the current implementation, not a guarantee of " +"current or future behavior." +msgstr "" +"A construção com threads livres do CPython visa fornecer comportamento de " +"segurança às threads semelhante no nível do Python à construção padrão com " +"GIL habilitada. Tipos embutidos como :class:`dict`, :class:`list` e :class:" +"`set` usam travas internas para proteger contra modificações simultâneas de " +"maneiras que se comportam de forma semelhante à GIL. No entanto, o Python " +"não garantiu historicamente um comportamento específico para modificações " +"simultâneas a esses tipos embutidos, portanto, isso deve ser tratado como " +"uma descrição da implementação atual, não uma garantia de comportamento " +"atual ou futuro." + +#: ../../howto/free-threading-python.rst:88 +msgid "" +"It's recommended to use the :class:`threading.Lock` or other synchronization " +"primitives instead of relying on the internal locks of built-in types, when " +"possible." +msgstr "" +"É recomendável usar :class:`threading.Lock` ou outras primitivas de " +"sincronização em vez de depender de travas internas de tipos embutidos, " +"quando possível." + +#: ../../howto/free-threading-python.rst:94 +msgid "Known limitations" +msgstr "Limitações conhecidas" + +#: ../../howto/free-threading-python.rst:96 +msgid "" +"This section describes known limitations of the free-threaded CPython build." +msgstr "" +"Esta seção descreve as limitações conhecidas da construção do Python com " +"threads livres." + +#: ../../howto/free-threading-python.rst:99 +msgid "Immortalization" +msgstr "Imortalização" + +#: ../../howto/free-threading-python.rst:101 +msgid "" +"The free-threaded build of the 3.13 release makes some objects :term:" +"`immortal`. Immortal objects are not deallocated and have reference counts " +"that are never modified. This is done to avoid reference count contention " +"that would prevent efficient multi-threaded scaling." +msgstr "" +"A construção com threads livres da versão 3.13 torna alguns objetos :term:" +"`imortais `. Objetos imortais não são desalocados e têm contagens " +"de referência que nunca são modificadas. Isso é feito para evitar contenção " +"de contagem de referências que impediria o dimensionamento multithread " +"eficiente." + +#: ../../howto/free-threading-python.rst:106 +msgid "" +"An object will be made immortal when a new thread is started for the first " +"time after the main thread is running. The following objects are " +"immortalized:" +msgstr "" +"Um objeto será tornado imortal quando um novo thread for iniciado pela " +"primeira vez após o thread principal estar em execução. Os seguintes objetos " +"são imortalizados:" + +#: ../../howto/free-threading-python.rst:109 +msgid "" +":ref:`function ` objects declared at the module level" +msgstr "" +"objetos :ref:`função ` declarados no nível de módulo" + +#: ../../howto/free-threading-python.rst:110 +msgid ":ref:`method ` descriptors" +msgstr "descritores de :ref:`métodos `" + +#: ../../howto/free-threading-python.rst:111 +msgid ":ref:`code ` objects" +msgstr "objetos :ref:`código `" + +#: ../../howto/free-threading-python.rst:112 +msgid ":term:`module` objects and their dictionaries" +msgstr "objetos :term:`módulo` e seus dicionários" + +#: ../../howto/free-threading-python.rst:113 +msgid ":ref:`classes ` (type objects)" +msgstr ":ref:`classes ` (objetos de tipo)" + +#: ../../howto/free-threading-python.rst:115 +msgid "" +"Because immortal objects are never deallocated, applications that create " +"many objects of these types may see increased memory usage. This is " +"expected to be addressed in the 3.14 release." +msgstr "" +"Como objetos imortais nunca são desalocados, aplicações que criam muitos " +"objetos desses tipos podem ver aumento no uso de memória. Espera-se que isso " +"seja resolvido na versão 3.14." + +#: ../../howto/free-threading-python.rst:119 +msgid "" +"Additionally, numeric and string literals in the code as well as strings " +"returned by :func:`sys.intern` are also immortalized. This behavior is " +"expected to remain in the 3.14 free-threaded build." +msgstr "" +"Além disso, literais numéricos e de string no código, bem como strings " +"retornadas por :func:`sys.intern` também são imortalizados. Espera-se que " +"esse comportamento permaneça na construção com threads livres do 3.14." + +#: ../../howto/free-threading-python.rst:125 +msgid "Frame objects" +msgstr "Objetos quadro" + +#: ../../howto/free-threading-python.rst:127 +msgid "" +"It is not safe to access :ref:`frame ` objects from other " +"threads and doing so may cause your program to crash . This means that :" +"func:`sys._current_frames` is generally not safe to use in a free-threaded " +"build. Functions like :func:`inspect.currentframe` and :func:`sys." +"_getframe` are generally safe as long as the resulting frame object is not " +"passed to another thread." +msgstr "" +"Não é seguro acessar objetos :ref:`quadro ` de outros threads " +"e fazer isso pode fazer com que seu programa trave. Isso significa que :func:" +"`sys._current_frames` geralmente não é seguro para uso em uma construção com " +"threads livres. Funções como :func:`inspect.currentframe` e :func:`sys." +"_getframe` são geralmente seguras, desde que o objeto quadro resultante não " +"seja passado para outro thread." + +#: ../../howto/free-threading-python.rst:135 +msgid "Iterators" +msgstr "Iteradores" + +#: ../../howto/free-threading-python.rst:137 +msgid "" +"Sharing the same iterator object between multiple threads is generally not " +"safe and threads may see duplicate or missing elements when iterating or " +"crash the interpreter." +msgstr "" +"Compartilhar o mesmo objeto iterador entre vários threads geralmente não é " +"seguro e os threads podem ver elementos duplicados ou ausentes ao iterar ou " +"travar o interpretador." + +#: ../../howto/free-threading-python.rst:143 +msgid "Single-threaded performance" +msgstr "Desempenho com thread única" + +#: ../../howto/free-threading-python.rst:145 +msgid "" +"The free-threaded build has additional overhead when executing Python code " +"compared to the default GIL-enabled build. In 3.13, this overhead is about " +"40% on the `pyperformance `_ suite. " +"Programs that spend most of their time in C extensions or I/O will see less " +"of an impact. The largest impact is because the specializing adaptive " +"interpreter (:pep:`659`) is disabled in the free-threaded build. We expect " +"to re-enable it in a thread-safe way in the 3.14 release. This overhead is " +"expected to be reduced in upcoming Python release. We are aiming for an " +"overhead of 10% or less on the pyperformance suite compared to the default " +"GIL-enabled build." +msgstr "" +"A construção com threads livres tem sobrecarga adicional ao executar código " +"Python em comparação com a construção padrão com GIL habilitada. Na versão " +"3.13, essa sobrecarga é de cerca de 40% no conjunto de ferramentas " +"`pyperformance `_. Programas que " +"passam a maior parte do tempo em extensões C ou E/S verão menos impacto. O " +"maior impacto é porque o interpretador adaptativo especializado (:pep:`659`) " +"está desabilitado na construção com threads livres. Esperamos reabilitá-lo " +"de forma segura para threads na versão 3.14. Espera-se que essa sobrecarga " +"seja reduzida na próxima versão do Python. Estamos buscando uma sobrecarga " +"de 10% ou menos no conjunto de ferramentas pyperformance em comparação com a " +"construção padrão com GIL habilitada." diff --git a/howto/functional.po b/howto/functional.po index 2c06d78a6..b2ee710bd 100644 --- a/howto/functional.po +++ b/howto/functional.po @@ -1,40 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Ruan Aragão , 2021 -# Vinicius Gubiani Ferreira , 2021 -# i17obot , 2021 -# ApenasRR Mesmo , 2021 -# Raphael Mendonça, 2021 -# Italo Penaforte , 2021 -# Alexandre B A Villares, 2022 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 00:53+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../howto/functional.rst:5 msgid "Functional Programming HOWTO" -msgstr "Programação Funcional COMO FAZER" +msgstr "Programação Funcional" #: ../../howto/functional.rst:0 msgid "Author" @@ -493,6 +484,15 @@ msgstr "" "ser um iterador ou algum objeto para o qual :func:`iter` pode criar um " "iterador. Estas duas declarações são equivalentes::" +#: ../../howto/functional.rst:224 +msgid "" +"for i in iter(obj):\n" +" print(i)\n" +"\n" +"for i in obj:\n" +" print(i)" +msgstr "" + #: ../../howto/functional.rst:230 msgid "" "Iterators can be materialized as lists or tuples by using the :func:`list` " @@ -567,6 +567,26 @@ msgstr "" "Chamar :func:`iter` em um dicionário retorna um iterador que irá percorrer " "as chaves do dicionário::" +#: ../../howto/functional.rst:275 +msgid "" +">>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,\n" +"... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}\n" +">>> for key in m:\n" +"... print(key, m[key])\n" +"Jan 1\n" +"Feb 2\n" +"Mar 3\n" +"Apr 4\n" +"May 5\n" +"Jun 6\n" +"Jul 7\n" +"Aug 8\n" +"Sep 9\n" +"Oct 10\n" +"Nov 11\n" +"Dec 12" +msgstr "" + #: ../../howto/functional.rst:292 msgid "" "Note that starting with Python 3.7, dictionary iteration order is guaranteed " @@ -608,6 +628,16 @@ msgstr "" "TextIOBase.readline` até que não haja mais linhas no arquivo. Isso significa " "que você pode ler cada linha de um arquivo como este::" +#: ../../howto/functional.rst:313 +msgid "" +"for line in file:\n" +" # do something for each line\n" +" ..." +msgstr "" +"for line in file:\n" +" # do something for each line\n" +" ..." + #: ../../howto/functional.rst:317 msgid "" "Sets can take their contents from an iterable and let you iterate over the " @@ -616,6 +646,19 @@ msgstr "" "Os conjuntos podem tirar seus conteúdos de uma iterável e permitir que você " "faça uma iteração sobre os elementos do conjunto::" +#: ../../howto/functional.rst:320 +msgid "" +">>> S = {2, 3, 5, 7, 11, 13}\n" +">>> for i in S:\n" +"... print(i)\n" +"2\n" +"3\n" +"5\n" +"7\n" +"11\n" +"13" +msgstr "" + #: ../../howto/functional.rst:333 msgid "Generator expressions and list comprehensions" msgstr "Expressões do gerador e compreensões de lista" @@ -648,6 +691,17 @@ msgstr "" "haskell.org/). Você pode tirar todos os espaços em branco de um fluxo de " "strings com o seguinte código::" +#: ../../howto/functional.rst:346 +msgid "" +">>> line_list = [' line 1\\n', 'line 2 \\n', ' \\n', '']\n" +"\n" +">>> # Generator expression -- returns iterator\n" +">>> stripped_iter = (line.strip() for line in line_list)\n" +"\n" +">>> # List comprehension -- returns list\n" +">>> stripped_list = [line.strip() for line in line_list]" +msgstr "" + #: ../../howto/functional.rst:354 msgid "" "You can select only certain elements by adding an ``\"if\"`` condition::" @@ -655,6 +709,12 @@ msgstr "" "Você pode selecionar apenas determinados elementos adicionando uma condição " "``\"if\"``::" +#: ../../howto/functional.rst:356 +msgid "" +">>> stripped_list = [line.strip() for line in line_list\n" +"... if line != \"\"]" +msgstr "" + #: ../../howto/functional.rst:359 msgid "" "With a list comprehension, you get back a Python list; ``stripped_list`` is " @@ -684,6 +744,19 @@ msgstr "" "compreensões da lista são cercadas por colchetes (\"[]\"). As expressões do " "gerador têm a forma::" +#: ../../howto/functional.rst:370 +msgid "" +"( expression for expr in sequence1\n" +" if condition1\n" +" for expr2 in sequence2\n" +" if condition2\n" +" for expr3 in sequence3\n" +" ...\n" +" if condition3\n" +" for exprN in sequenceN\n" +" if conditionN )" +msgstr "" + #: ../../howto/functional.rst:380 msgid "" "Again, for a list comprehension only the outside brackets are different " @@ -715,6 +788,10 @@ msgstr "" "quiser criar um iterador que será imediatamente passado para uma função, " "você pode escrever::" +#: ../../howto/functional.rst:391 +msgid "obj_total = sum(obj.count for obj in list_all_objects())" +msgstr "" + #: ../../howto/functional.rst:393 msgid "" "The ``for...in`` clauses contain the sequences to be iterated over. The " @@ -739,6 +816,23 @@ msgstr "" "Em outras palavras, uma lista de compreensão ou expressão do gerador é " "equivalente ao seguinte código Python::" +#: ../../howto/functional.rst:402 +msgid "" +"for expr1 in sequence1:\n" +" if not (condition1):\n" +" continue # Skip this element\n" +" for expr2 in sequence2:\n" +" if not (condition2):\n" +" continue # Skip this element\n" +" ...\n" +" for exprN in sequenceN:\n" +" if not (conditionN):\n" +" continue # Skip this element\n" +"\n" +" # Output the value of\n" +" # the expression." +msgstr "" + #: ../../howto/functional.rst:416 msgid "" "This means that when there are multiple ``for...in`` clauses but no ``if`` " @@ -762,6 +856,14 @@ msgstr "" "parênteses. A primeira lista de compreensão abaixo é um erro de sintaxe, " "enquanto o segundo está correto::" +#: ../../howto/functional.rst:432 +msgid "" +"# Syntax error\n" +"[x, y for x in seq1 for y in seq2]\n" +"# Correct\n" +"[(x, y) for x in seq1 for y in seq2]" +msgstr "" + #: ../../howto/functional.rst:439 msgid "Generators" msgstr "Geradores" @@ -887,6 +989,20 @@ msgstr "" "gerador que implementa uma passagem em ordem de uma árvore usando geradores " "de forma recursiva. ::" +#: ../../howto/functional.rst:511 +msgid "" +"# A recursive generator that generates Tree leaves in in-order.\n" +"def inorder(t):\n" +" if t:\n" +" for x in inorder(t.left):\n" +" yield x\n" +"\n" +" yield t.label\n" +"\n" +" for x in inorder(t.right):\n" +" yield x" +msgstr "" + #: ../../howto/functional.rst:522 msgid "" "Two other examples in ``test_generators.py`` produce solutions for the N-" @@ -931,6 +1047,10 @@ msgstr "" "keyword:`yield` tornou-se uma expressão, retornando um valor que pode ser " "atribuído a uma variável ou operado de outra forma::" +#: ../../howto/functional.rst:543 +msgid "val = (yield i)" +msgstr "" + #: ../../howto/functional.rst:545 msgid "" "I recommend that you **always** put parentheses around a ``yield`` " @@ -977,6 +1097,19 @@ msgstr "" "Aqui está um contador simples que aumenta em 1 e permite alterar o valor do " "contador interno." +#: ../../howto/functional.rst:564 +msgid "" +"def counter(maximum):\n" +" i = 0\n" +" while i < maximum:\n" +" val = (yield i)\n" +" # If value provided, change counter\n" +" if val is not None:\n" +" i = val\n" +" else:\n" +" i += 1" +msgstr "" + #: ../../howto/functional.rst:576 msgid "And here's an example of changing the counter:" msgstr "E aqui um exemplo de mudança de contador:" @@ -1029,8 +1162,8 @@ msgid "" "The cumulative effect of these changes is to turn generators from one-way " "producers of information into both producers and consumers." msgstr "" -"O efeito cumulativo destas mudanças é transformar os geradores de produtores " -"unilaterais de informação em produtores e consumidores." +"The cumulative effect of these changes is to turn generators from one-way " +"producers of information into both producers and consumers." #: ../../howto/functional.rst:619 msgid "" @@ -1049,6 +1182,8 @@ msgstr "Funções embutidas" msgid "" "Let's look in more detail at built-in functions often used with iterators." msgstr "" +"Vamos ver com maiores detalhes as funções embutidas que são comunmente " +"usadas com iteradores." #: ../../howto/functional.rst:630 msgid "" @@ -1091,12 +1226,29 @@ msgid "" "element. ::" msgstr "" +#: ../../howto/functional.rst:669 +msgid "" +">>> for item in enumerate(['subject', 'verb', 'object']):\n" +"... print(item)\n" +"(0, 'subject')\n" +"(1, 'verb')\n" +"(2, 'object')" +msgstr "" + #: ../../howto/functional.rst:675 msgid "" ":func:`enumerate` is often used when looping through a list and recording " "the indexes at which certain conditions are met::" msgstr "" +#: ../../howto/functional.rst:678 +msgid "" +"f = open('data.txt', 'r')\n" +"for i, line in enumerate(f):\n" +" if line.strip() == '':\n" +" print('Blank line at line #%i' % i)" +msgstr "" + #: ../../howto/functional.rst:683 msgid "" ":func:`sorted(iterable, key=None, reverse=False) ` collects all the " @@ -1105,6 +1257,19 @@ msgid "" "constructed list's :meth:`~list.sort` method. ::" msgstr "" +#: ../../howto/functional.rst:688 +msgid "" +">>> import random\n" +">>> # Generate 8 random numbers between [0, 10000)\n" +">>> rand_list = random.sample(range(10000), 8)\n" +">>> rand_list\n" +"[769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]\n" +">>> sorted(rand_list)\n" +"[769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]\n" +">>> sorted(rand_list, reverse=True)\n" +"[9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]" +msgstr "" + #: ../../howto/functional.rst:698 msgid "" "(For a more detailed discussion of sorting, see the :ref:`sortinghowto`.)" @@ -1124,6 +1289,12 @@ msgid "" "and returns them in a tuple::" msgstr "" +#: ../../howto/functional.rst:723 +msgid "" +"zip(['a', 'b', 'c'], (1, 2, 3)) =>\n" +" ('a', 1), ('b', 2), ('c', 3)" +msgstr "" + #: ../../howto/functional.rst:726 msgid "" "It doesn't construct an in-memory list and exhaust all the input iterators " @@ -1139,6 +1310,12 @@ msgid "" "will be the same length as the shortest iterable. ::" msgstr "" +#: ../../howto/functional.rst:735 +msgid "" +"zip(['a', 'b'], (1, 2, 3)) =>\n" +" ('a', 1), ('b', 2)" +msgstr "" + #: ../../howto/functional.rst:738 msgid "" "You should avoid doing this, though, because an element may be taken from " @@ -1190,6 +1367,16 @@ msgid "" "defaults to 1::" msgstr "" +#: ../../howto/functional.rst:764 +msgid "" +"itertools.count() =>\n" +" 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...\n" +"itertools.count(10) =>\n" +" 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...\n" +"itertools.count(10, 5) =>\n" +" 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, ..." +msgstr "" + #: ../../howto/functional.rst:771 msgid "" ":func:`itertools.cycle(iter) ` saves a copy of the contents " @@ -1198,6 +1385,12 @@ msgid "" "infinitely. ::" msgstr "" +#: ../../howto/functional.rst:775 +msgid "" +"itertools.cycle([1, 2, 3, 4, 5]) =>\n" +" 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ..." +msgstr "" + #: ../../howto/functional.rst:778 msgid "" ":func:`itertools.repeat(elem, [n]) ` returns the provided " @@ -1205,6 +1398,14 @@ msgid "" "provided. ::" msgstr "" +#: ../../howto/functional.rst:781 +msgid "" +"itertools.repeat('abc') =>\n" +" abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...\n" +"itertools.repeat('abc', 5) =>\n" +" abc, abc, abc, abc, abc" +msgstr "" + #: ../../howto/functional.rst:786 msgid "" ":func:`itertools.chain(iterA, iterB, ...) ` takes an " @@ -1213,6 +1414,12 @@ msgid "" "the iterables have been exhausted. ::" msgstr "" +#: ../../howto/functional.rst:791 +msgid "" +"itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>\n" +" a, b, c, 1, 2, 3" +msgstr "" + #: ../../howto/functional.rst:794 msgid "" ":func:`itertools.islice(iter, [start], stop, [step]) ` " @@ -1224,6 +1431,16 @@ msgid "" "*step*. ::" msgstr "" +#: ../../howto/functional.rst:801 +msgid "" +"itertools.islice(range(10), 8) =>\n" +" 0, 1, 2, 3, 4, 5, 6, 7\n" +"itertools.islice(range(10), 2, 8) =>\n" +" 2, 3, 4, 5, 6, 7\n" +"itertools.islice(range(10), 2, 8, 2) =>\n" +" 2, 4, 6" +msgstr "" + #: ../../howto/functional.rst:808 msgid "" ":func:`itertools.tee(iter, [n]) ` replicates an iterator; it " @@ -1234,6 +1451,18 @@ msgid "" "and one of the new iterators is consumed more than the others. ::" msgstr "" +#: ../../howto/functional.rst:816 +msgid "" +"itertools.tee( itertools.count() ) =>\n" +" iterA, iterB\n" +"\n" +"where iterA ->\n" +" 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...\n" +"\n" +"and iterB ->\n" +" 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ..." +msgstr "" + #: ../../howto/functional.rst:827 msgid "Calling functions on elements" msgstr "" @@ -1254,6 +1483,15 @@ msgid "" "as the arguments::" msgstr "" +#: ../../howto/functional.rst:839 +msgid "" +"itertools.starmap(os.path.join,\n" +" [('/bin', 'python'), ('/usr', 'bin', 'java'),\n" +" ('/usr', 'bin', 'perl'), ('/usr', 'bin', 'ruby')])\n" +"=>\n" +" /bin/python, /usr/bin/java, /usr/bin/perl, /usr/bin/ruby" +msgstr "" + #: ../../howto/functional.rst:847 msgid "Selecting elements" msgstr "Selecionando elementos" @@ -1271,6 +1509,12 @@ msgid "" "predicate returns false::" msgstr "" +#: ../../howto/functional.rst:856 +msgid "" +"itertools.filterfalse(is_even, itertools.count()) =>\n" +" 1, 3, 5, 7, 9, 11, 13, 15, ..." +msgstr "" + #: ../../howto/functional.rst:859 msgid "" ":func:`itertools.takewhile(predicate, iter) ` returns " @@ -1278,6 +1522,18 @@ msgid "" "returns false, the iterator will signal the end of its results. ::" msgstr "" +#: ../../howto/functional.rst:863 +msgid "" +"def less_than_10(x):\n" +" return x < 10\n" +"\n" +"itertools.takewhile(less_than_10, itertools.count()) =>\n" +" 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n" +"\n" +"itertools.takewhile(is_even, itertools.count()) =>\n" +" 0" +msgstr "" + #: ../../howto/functional.rst:872 msgid "" ":func:`itertools.dropwhile(predicate, iter) ` discards " @@ -1285,6 +1541,15 @@ msgid "" "iterable's results. ::" msgstr "" +#: ../../howto/functional.rst:876 +msgid "" +"itertools.dropwhile(less_than_10, itertools.count()) =>\n" +" 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...\n" +"\n" +"itertools.dropwhile(is_even, itertools.count()) =>\n" +" 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..." +msgstr "" + #: ../../howto/functional.rst:882 msgid "" ":func:`itertools.compress(data, selectors) ` takes two " @@ -1293,6 +1558,12 @@ msgid "" "is exhausted::" msgstr "" +#: ../../howto/functional.rst:886 +msgid "" +"itertools.compress([1, 2, 3, 4, 5], [True, True, False, False, True]) =>\n" +" 1, 2, 5" +msgstr "" + #: ../../howto/functional.rst:891 msgid "Combinatoric functions" msgstr "" @@ -1304,6 +1575,20 @@ msgid "" "elements contained in *iterable*. ::" msgstr "" +#: ../../howto/functional.rst:897 +msgid "" +"itertools.combinations([1, 2, 3, 4, 5], 2) =>\n" +" (1, 2), (1, 3), (1, 4), (1, 5),\n" +" (2, 3), (2, 4), (2, 5),\n" +" (3, 4), (3, 5),\n" +" (4, 5)\n" +"\n" +"itertools.combinations([1, 2, 3, 4, 5], 3) =>\n" +" (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5),\n" +" (2, 3, 4), (2, 3, 5), (2, 4, 5),\n" +" (3, 4, 5)" +msgstr "" + #: ../../howto/functional.rst:908 msgid "" "The elements within each tuple remain in the same order as *iterable* " @@ -1313,6 +1598,21 @@ msgid "" "constraint on the order, returning all possible arrangements of length *r*::" msgstr "" +#: ../../howto/functional.rst:915 +msgid "" +"itertools.permutations([1, 2, 3, 4, 5], 2) =>\n" +" (1, 2), (1, 3), (1, 4), (1, 5),\n" +" (2, 1), (2, 3), (2, 4), (2, 5),\n" +" (3, 1), (3, 2), (3, 4), (3, 5),\n" +" (4, 1), (4, 2), (4, 3), (4, 5),\n" +" (5, 1), (5, 2), (5, 3), (5, 4)\n" +"\n" +"itertools.permutations([1, 2, 3, 4, 5]) =>\n" +" (1, 2, 3, 4, 5), (1, 2, 3, 5, 4), (1, 2, 4, 3, 5),\n" +" ...\n" +" (5, 4, 3, 2, 1)" +msgstr "" + #: ../../howto/functional.rst:927 msgid "" "If you don't supply a value for *r* the length of the iterable is used, " @@ -1325,6 +1625,13 @@ msgid "" "position and don't require that the contents of *iterable* are unique::" msgstr "" +#: ../../howto/functional.rst:933 +msgid "" +"itertools.permutations('aba', 3) =>\n" +" ('a', 'b', 'a'), ('a', 'a', 'b'), ('b', 'a', 'a'),\n" +" ('b', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a')" +msgstr "" + #: ../../howto/functional.rst:937 msgid "" "The identical tuple ``('a', 'a', 'b')`` occurs twice, but the two 'a' " @@ -1340,6 +1647,16 @@ msgid "" "the second element is selected. ::" msgstr "" +#: ../../howto/functional.rst:946 +msgid "" +"itertools.combinations_with_replacement([1, 2, 3, 4, 5], 2) =>\n" +" (1, 1), (1, 2), (1, 3), (1, 4), (1, 5),\n" +" (2, 2), (2, 3), (2, 4), (2, 5),\n" +" (3, 3), (3, 4), (3, 5),\n" +" (4, 4), (4, 5),\n" +" (5, 5)" +msgstr "" + #: ../../howto/functional.rst:955 msgid "Grouping elements" msgstr "Agrupando elementos" @@ -1360,6 +1677,31 @@ msgid "" "tuples containing a key value and an iterator for the elements with that key." msgstr "" +#: ../../howto/functional.rst:968 +msgid "" +"city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),\n" +" ('Anchorage', 'AK'), ('Nome', 'AK'),\n" +" ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),\n" +" ...\n" +" ]\n" +"\n" +"def get_state(city_state):\n" +" return city_state[1]\n" +"\n" +"itertools.groupby(city_list, get_state) =>\n" +" ('AL', iterator-1),\n" +" ('AK', iterator-2),\n" +" ('AZ', iterator-3), ...\n" +"\n" +"where\n" +"iterator-1 =>\n" +" ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')\n" +"iterator-2 =>\n" +" ('Anchorage', 'AK'), ('Nome', 'AK')\n" +"iterator-3 =>\n" +" ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')" +msgstr "" + #: ../../howto/functional.rst:990 msgid "" ":func:`~itertools.groupby` assumes that the underlying iterable's contents " @@ -1402,6 +1744,19 @@ msgstr "" msgid "Here's a small but realistic example::" msgstr "Aqui está um pequeno mas bem realístico exemplo::" +#: ../../howto/functional.rst:1017 +msgid "" +"import functools\n" +"\n" +"def log(message, subsystem):\n" +" \"\"\"Write the contents of 'message' to the specified subsystem.\"\"\"\n" +" print('%s: %s' % (subsystem, message))\n" +" ...\n" +"\n" +"server_log = functools.partial(log, subsystem='server')\n" +"server_log('Unable to open socket')" +msgstr "" + #: ../../howto/functional.rst:1027 msgid "" ":func:`functools.reduce(func, iter, [initial_value]) ` " @@ -1417,6 +1772,21 @@ msgid "" "``func(initial_value, A)`` is the first calculation. ::" msgstr "" +#: ../../howto/functional.rst:1039 +msgid "" +">>> import operator, functools\n" +">>> functools.reduce(operator.concat, ['A', 'BB', 'C'])\n" +"'ABBC'\n" +">>> functools.reduce(operator.concat, [])\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: reduce() of empty sequence with no initial value\n" +">>> functools.reduce(operator.mul, [1, 2, 3], 1)\n" +"6\n" +">>> functools.reduce(operator.mul, [], 1)\n" +"1" +msgstr "" + #: ../../howto/functional.rst:1051 msgid "" "If you use :func:`operator.add` with :func:`functools.reduce`, you'll add up " @@ -1430,6 +1800,18 @@ msgid "" "write the obvious :keyword:`for` loop::" msgstr "" +#: ../../howto/functional.rst:1066 +msgid "" +"import functools\n" +"# Instead of:\n" +"product = functools.reduce(operator.mul, [1, 2, 3], 1)\n" +"\n" +"# You can write:\n" +"product = 1\n" +"for i in [1, 2, 3]:\n" +" product *= i" +msgstr "" + #: ../../howto/functional.rst:1075 msgid "" "A related function is :func:`itertools.accumulate(iterable, func=operator." @@ -1438,6 +1820,15 @@ msgid "" "iterator that also yields each partial result::" msgstr "" +#: ../../howto/functional.rst:1080 +msgid "" +"itertools.accumulate([1, 2, 3, 4, 5]) =>\n" +" 1, 3, 6, 10, 15\n" +"\n" +"itertools.accumulate([1, 2, 3, 4, 5], operator.mul) =>\n" +" 1, 2, 6, 24, 120" +msgstr "" + #: ../../howto/functional.rst:1088 msgid "The operator module" msgstr "O módulo operator" @@ -1497,6 +1888,12 @@ msgid "" "need to define a new function at all::" msgstr "" +#: ../../howto/functional.rst:1115 +msgid "" +"stripped_lines = [line.strip() for line in lines]\n" +"existing_files = filter(os.path.exists, file_list)" +msgstr "" + #: ../../howto/functional.rst:1118 msgid "" "If the function you need doesn't exist, you need to write it. One way to " @@ -1506,12 +1903,28 @@ msgid "" "expression::" msgstr "" +#: ../../howto/functional.rst:1123 +msgid "" +"adder = lambda x, y: x+y\n" +"\n" +"print_assign = lambda name, value: name + '=' + str(value)" +msgstr "" + #: ../../howto/functional.rst:1127 msgid "" "An alternative is to just use the ``def`` statement and define a function in " "the usual way::" msgstr "" +#: ../../howto/functional.rst:1130 +msgid "" +"def adder(x, y):\n" +" return x + y\n" +"\n" +"def print_assign(name, value):\n" +" return name + '=' + str(value)" +msgstr "" + #: ../../howto/functional.rst:1136 msgid "" "Which alternative is preferable? That's a style question; my usual course " @@ -1535,6 +1948,12 @@ msgstr "" "complicada que é difícil de ler. Rápido, o que o seguinte código está " "fazendo? ::" +#: ../../howto/functional.rst:1146 +msgid "" +"import functools\n" +"total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]" +msgstr "" + #: ../../howto/functional.rst:1149 msgid "" "You can figure it out, but it takes time to disentangle the expression to " @@ -1545,23 +1964,43 @@ msgstr "" "descobrir o que está acontecendo. Usar uma breve instrução de ``def`` " "aninhada torna as coisas um pouco melhor::" +#: ../../howto/functional.rst:1153 +msgid "" +"import functools\n" +"def combine(a, b):\n" +" return 0, a[1] + b[1]\n" +"\n" +"total = functools.reduce(combine, items)[1]" +msgstr "" + #: ../../howto/functional.rst:1159 msgid "But it would be best of all if I had simply used a ``for`` loop::" msgstr "" "Mas seria o melhor de tudo se eu tivesse usado simplesmente um bucle " "``for``::" +#: ../../howto/functional.rst:1161 +msgid "" +"total = 0\n" +"for a, b in items:\n" +" total += b" +msgstr "" + #: ../../howto/functional.rst:1165 msgid "Or the :func:`sum` built-in and a generator expression::" msgstr "Ou o :func:`sum` embutida e uma expressão do gerador::" +#: ../../howto/functional.rst:1167 +msgid "total = sum(b for a, b in items)" +msgstr "" + #: ../../howto/functional.rst:1169 msgid "" "Many uses of :func:`functools.reduce` are clearer when written as ``for`` " "loops." msgstr "" "Muitas utilizações de :func:`functools.reduce` são mais claras quando " -"escritas como loops ``for``." +"escritas como laços ``for``." #: ../../howto/functional.rst:1171 msgid "" diff --git a/howto/gdb_helpers.po b/howto/gdb_helpers.po index bd61b0d70..148c386f2 100644 --- a/howto/gdb_helpers.po +++ b/howto/gdb_helpers.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-21 14:14+0000\n" -"PO-Revision-Date: 2024-02-25 01:11+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -156,6 +155,10 @@ msgstr "" "Se você não encontrar instruções para a sua versão do GDB, coloque isso no " "seu arquivo de configuração (``~/.gdbinit`` ou ``~/.config/gdb/gdbinit``)::" +#: ../../howto/gdb_helpers.rst:68 +msgid "add-auto-load-safe-path /path/to/cpython" +msgstr "add-auto-load-safe-path /caminho/para/cpython" + #: ../../howto/gdb_helpers.rst:70 msgid "You can also add multiple paths, separated by ``:``." msgstr "Você também pode adicionar vários caminhos, separados por ``:``." @@ -177,10 +180,22 @@ msgstr "" msgid "Fedora:" msgstr "Fedora:" +#: ../../howto/gdb_helpers.rst:82 +msgid "" +"sudo dnf install gdb\n" +"sudo dnf debuginfo-install python3" +msgstr "" +"sudo dnf install gdb\n" +"sudo dnf debuginfo-install python3" + #: ../../howto/gdb_helpers.rst:87 msgid "Ubuntu:" msgstr "Ubuntu:" +#: ../../howto/gdb_helpers.rst:89 +msgid "sudo apt install gdb python3-dbg" +msgstr "sudo apt install gdb python3-dbg" + #: ../../howto/gdb_helpers.rst:93 msgid "" "On several recent Linux systems, GDB can download debugging symbols " @@ -252,6 +267,64 @@ msgstr "" "Este é o aspecto de um backtrace do GDB (truncado) quando esta extensão está " "habilitada:" +#: ../../howto/gdb_helpers.rst:126 +msgid "" +"#0 0x000000000041a6b1 in PyObject_Malloc (nbytes=Cannot access memory at " +"address 0x7fffff7fefe8\n" +") at Objects/obmalloc.c:748\n" +"#1 0x000000000041b7c0 in _PyObject_DebugMallocApi (id=111 'o', nbytes=24) " +"at Objects/obmalloc.c:1445\n" +"#2 0x000000000041b717 in _PyObject_DebugMalloc (nbytes=24) at Objects/" +"obmalloc.c:1412\n" +"#3 0x000000000044060a in _PyUnicode_New (length=11) at Objects/" +"unicodeobject.c:346\n" +"#4 0x00000000004466aa in PyUnicodeUCS2_DecodeUTF8Stateful (s=0x5c2b8d " +"\"__lltrace__\", size=11, errors=0x0, consumed=\n" +" 0x0) at Objects/unicodeobject.c:2531\n" +"#5 0x0000000000446647 in PyUnicodeUCS2_DecodeUTF8 (s=0x5c2b8d " +"\"__lltrace__\", size=11, errors=0x0)\n" +" at Objects/unicodeobject.c:2495\n" +"#6 0x0000000000440d1b in PyUnicodeUCS2_FromStringAndSize (u=0x5c2b8d " +"\"__lltrace__\", size=11)\n" +" at Objects/unicodeobject.c:551\n" +"#7 0x0000000000440d94 in PyUnicodeUCS2_FromString (u=0x5c2b8d " +"\"__lltrace__\") at Objects/unicodeobject.c:569\n" +"#8 0x0000000000584abd in PyDict_GetItemString (v=\n" +" {'Yuck': , '__builtins__': , '__file__': 'Lib/test/crashers/nasty_eq_vs_dict.py', " +"'__package__': None, 'y': , 'dict': {0: 0, 1: " +"1, 2: 2, 3: 3}, '__cached__': None, '__name__': '__main__', 'z': , '__doc__': None}, key=\n" +" 0x5c2b8d \"__lltrace__\") at Objects/dictobject.c:2171" +msgstr "" +"#0 0x000000000041a6b1 in PyObject_Malloc (nbytes=Cannot access memory at " +"address 0x7fffff7fefe8\n" +") at Objects/obmalloc.c:748\n" +"#1 0x000000000041b7c0 in _PyObject_DebugMallocApi (id=111 'o', nbytes=24) " +"at Objects/obmalloc.c:1445\n" +"#2 0x000000000041b717 in _PyObject_DebugMalloc (nbytes=24) at Objects/" +"obmalloc.c:1412\n" +"#3 0x000000000044060a in _PyUnicode_New (length=11) at Objects/" +"unicodeobject.c:346\n" +"#4 0x00000000004466aa in PyUnicodeUCS2_DecodeUTF8Stateful (s=0x5c2b8d " +"\"__lltrace__\", size=11, errors=0x0, consumed=\n" +" 0x0) at Objects/unicodeobject.c:2531\n" +"#5 0x0000000000446647 in PyUnicodeUCS2_DecodeUTF8 (s=0x5c2b8d " +"\"__lltrace__\", size=11, errors=0x0)\n" +" at Objects/unicodeobject.c:2495\n" +"#6 0x0000000000440d1b in PyUnicodeUCS2_FromStringAndSize (u=0x5c2b8d " +"\"__lltrace__\", size=11)\n" +" at Objects/unicodeobject.c:551\n" +"#7 0x0000000000440d94 in PyUnicodeUCS2_FromString (u=0x5c2b8d " +"\"__lltrace__\") at Objects/unicodeobject.c:569\n" +"#8 0x0000000000584abd in PyDict_GetItemString (v=\n" +" {'Yuck': , '__builtins__': , '__file__': 'Lib/test/crashers/nasty_eq_vs_dict.py', " +"'__package__': None, 'y': , 'dict': {0: 0, 1: " +"1, 2: 2, 3: 3}, '__cached__': None, '__name__': '__main__', 'z': , '__doc__': None}, key=\n" +" 0x5c2b8d \"__lltrace__\") at Objects/dictobject.c:2171" + #: ../../howto/gdb_helpers.rst:142 msgid "" "Notice how the dictionary argument to ``PyDict_GetItemString`` is displayed " @@ -272,6 +345,46 @@ msgstr "" "inferior de um objeto, então converta o valor para um ponteiro do tipo " "apropriado. Por exemplo:" +#: ../../howto/gdb_helpers.rst:149 +msgid "" +"(gdb) p globals\n" +"$1 = {'__builtins__': , '__name__':\n" +"'__main__', 'ctypes': , '__doc__': None,\n" +"'__package__': None}\n" +"\n" +"(gdb) p *(PyDictObject*)globals\n" +"$2 = {ob_refcnt = 3, ob_type = 0x3dbdf85820, ma_fill = 5, ma_used = 5,\n" +"ma_mask = 7, ma_table = 0x63d0f8, ma_lookup = 0x3dbdc7ea70\n" +", ma_smalltable = {{me_hash = 7065186196740147912,\n" +"me_key = '__builtins__', me_value = },\n" +"{me_hash = -368181376027291943, me_key = '__name__',\n" +"me_value ='__main__'}, {me_hash = 0, me_key = 0x0, me_value = 0x0},\n" +"{me_hash = 0, me_key = 0x0, me_value = 0x0},\n" +"{me_hash = -9177857982131165996, me_key = 'ctypes',\n" +"me_value = },\n" +"{me_hash = -8518757509529533123, me_key = '__doc__', me_value = None},\n" +"{me_hash = 0, me_key = 0x0, me_value = 0x0}, {\n" +" me_hash = 6614918939584953775, me_key = '__package__', me_value = None}}}" +msgstr "" +"(gdb) p globals\n" +"$1 = {'__builtins__': , '__name__':\n" +"'__main__', 'ctypes': , '__doc__': None,\n" +"'__package__': None}\n" +"\n" +"(gdb) p *(PyDictObject*)globals\n" +"$2 = {ob_refcnt = 3, ob_type = 0x3dbdf85820, ma_fill = 5, ma_used = 5,\n" +"ma_mask = 7, ma_table = 0x63d0f8, ma_lookup = 0x3dbdc7ea70\n" +", ma_smalltable = {{me_hash = 7065186196740147912,\n" +"me_key = '__builtins__', me_value = },\n" +"{me_hash = -368181376027291943, me_key = '__name__',\n" +"me_value ='__main__'}, {me_hash = 0, me_key = 0x0, me_value = 0x0},\n" +"{me_hash = 0, me_key = 0x0, me_value = 0x0},\n" +"{me_hash = -9177857982131165996, me_key = 'ctypes',\n" +"me_value = },\n" +"{me_hash = -8518757509529533123, me_key = '__doc__', me_value = None},\n" +"{me_hash = 0, me_key = 0x0, me_value = 0x0}, {\n" +" me_hash = 6614918939584953775, me_key = '__package__', me_value = None}}}" + #: ../../howto/gdb_helpers.rst:168 msgid "" "Note that the pretty-printers do not actually call ``repr()``. For basic " @@ -294,20 +407,36 @@ msgstr "" "`PyLongObject *`) fornece uma representação que não é distinguível de um " "inteiro de nível de máquina regular." +#: ../../howto/gdb_helpers.rst:177 +msgid "" +"(gdb) p some_machine_integer\n" +"$3 = 42\n" +"\n" +"(gdb) p some_python_integer\n" +"$4 = 42" +msgstr "" +"(gdb) p some_machine_integer\n" +"$3 = 42\n" +"\n" +"(gdb) p some_python_integer\n" +"$4 = 42" + #: ../../howto/gdb_helpers.rst:183 msgid "" "The internal structure can be revealed with a cast to :c:expr:`PyLongObject " -"*`:" +"*`::" msgstr "" "A estrutura interna pode ser revelada com um elenco para :c:expr:" -"`PyLongObject *`." +"`PyLongObject *`::" #: ../../howto/gdb_helpers.rst:185 msgid "" -"(gdb) p *(PyLongObject*)some_python_integer $5 = {ob_base = {ob_base = " -"{ob_refcnt = 8, ob_type = 0x3dad39f5e0}, ob_size = 1}, ob_digit = {42}}" +"(gdb) p *(PyLongObject*)some_python_integer\n" +"$5 = {ob_base = {ob_base = {ob_refcnt = 8, ob_type = 0x3dad39f5e0}, ob_size " +"= 1},\n" +"ob_digit = {42}}" msgstr "" -"(gdb) p *(PyLongObject*)some_python_integer $5 = {ob_base = {ob_base = " +"(gdb) p *(PyLongObject*)algum_inteiro_python $5 = {ob_base = {ob_base = " "{ob_refcnt = 8, ob_type = 0x3dad39f5e0}, ob_size = 1}, ob_digit = {42}}" #: ../../howto/gdb_helpers.rst:189 @@ -318,6 +447,14 @@ msgstr "" "Uma confusão semelhante pode surgir com o tipo ``str``, onde a saída se " "parece muito com a a impressão embutida do gdb para ``char *``." +#: ../../howto/gdb_helpers.rst:192 +msgid "" +"(gdb) p ptr_to_python_str\n" +"$6 = '__builtins__'" +msgstr "" +"(gdb) p ptr_to_python_str\n" +"$6 = '__builtins__'" + #: ../../howto/gdb_helpers.rst:195 msgid "" "The pretty-printer for ``str`` instances defaults to using single-quotes (as " @@ -329,6 +466,14 @@ msgstr "" "padrão para valores de ``char *`` usa aspas duplas e contém um endereço " "hexadecimal." +#: ../../howto/gdb_helpers.rst:199 +msgid "" +"(gdb) p ptr_to_char_star\n" +"$7 = 0x6d72c0 \"hello world\"" +msgstr "" +"(gdb) p ptr_to_char_star\n" +"$7 = 0x6d72c0 \"hello world\"" + #: ../../howto/gdb_helpers.rst:202 msgid "" "Again, the implementation details can be revealed with a cast to :c:expr:" @@ -337,6 +482,16 @@ msgstr "" "Novamente, os detalhes de implementação podem ser revelados com um chamada " "a :c:expr:`PyUnicodeObject *`::." +#: ../../howto/gdb_helpers.rst:205 +msgid "" +"(gdb) p *(PyUnicodeObject*)$6\n" +"$8 = {ob_base = {ob_refcnt = 33, ob_type = 0x3dad3a95a0}, length = 12,\n" +"str = 0x7ffff2128500, hash = 7065186196740147912, state = 1, defenc = 0x0}" +msgstr "" +"(gdb) p *(PyUnicodeObject*)$6\n" +"$8 = {ob_base = {ob_refcnt = 33, ob_type = 0x3dad3a95a0}, length = 12,\n" +"str = 0x7ffff2128500, hash = 7065186196740147912, state = 1, defenc = 0x0}" + #: ../../howto/gdb_helpers.rst:210 msgid "``py-list``" msgstr "``py-list``" @@ -351,6 +506,34 @@ msgstr "" "(se houver) para o quadro atual na thread selecionada. A linha atual é " "marcada com um \">\"::" +#: ../../howto/gdb_helpers.rst:216 +msgid "" +"(gdb) py-list\n" +" 901 if options.profile:\n" +" 902 options.profile = False\n" +" 903 profile_me()\n" +" 904 return\n" +" 905\n" +">906 u = UI()\n" +" 907 if not u.quit:\n" +" 908 try:\n" +" 909 gtk.main()\n" +" 910 except KeyboardInterrupt:\n" +" 911 # properly quit on a keyboard interrupt..." +msgstr "" +"(gdb) py-list\n" +" 901 if options.profile:\n" +" 902 options.profile = False\n" +" 903 profile_me()\n" +" 904 return\n" +" 905\n" +">906 u = UI()\n" +" 907 if not u.quit:\n" +" 908 try:\n" +" 909 gtk.main()\n" +" 910 except KeyboardInterrupt:\n" +" 911 # properly quit on a keyboard interrupt..." + #: ../../howto/gdb_helpers.rst:229 msgid "" "Use ``py-list START`` to list at a different line number within the Python " @@ -397,6 +580,32 @@ msgstr "Eles emitem o número do quadro (no nível C) dentro da thread." msgid "For example::" msgstr "Por exemplo::" +#: ../../howto/gdb_helpers.rst:250 +msgid "" +"(gdb) py-up\n" +"#37 Frame 0x9420b04, for file /usr/lib/python2.6/site-packages/\n" +"gnome_sudoku/main.py, line 906, in start_game ()\n" +" u = UI()\n" +"(gdb) py-up\n" +"#40 Frame 0x948e82c, for file /usr/lib/python2.6/site-packages/\n" +"gnome_sudoku/gnome_sudoku.py, line 22, in start_game(main=)\n" +" main.start_game()\n" +"(gdb) py-up\n" +"Unable to find an older python frame" +msgstr "" +"(gdb) py-up\n" +"#37 Frame 0x9420b04, for file /usr/lib/python2.6/site-packages/\n" +"gnome_sudoku/main.py, line 906, in start_game ()\n" +" u = UI()\n" +"(gdb) py-up\n" +"#40 Frame 0x948e82c, for file /usr/lib/python2.6/site-packages/\n" +"gnome_sudoku/gnome_sudoku.py, line 22, in start_game(main=)\n" +" main.start_game()\n" +"(gdb) py-up\n" +"Unable to find an older python frame" + #: ../../howto/gdb_helpers.rst:261 msgid "so we're at the top of the Python stack." msgstr "de forma estamos no topo da pilha do Python." @@ -415,6 +624,84 @@ msgstr "" msgid "Going back down::" msgstr "Voltando para baixo::" +#: ../../howto/gdb_helpers.rst:269 +msgid "" +"(gdb) py-down\n" +"#37 Frame 0x9420b04, for file /usr/lib/python2.6/site-packages/gnome_sudoku/" +"main.py, line 906, in start_game ()\n" +" u = UI()\n" +"(gdb) py-down\n" +"#34 (unable to read python frame information)\n" +"(gdb) py-down\n" +"#23 (unable to read python frame information)\n" +"(gdb) py-down\n" +"#19 (unable to read python frame information)\n" +"(gdb) py-down\n" +"#14 Frame 0x99262ac, for file /usr/lib/python2.6/site-packages/gnome_sudoku/" +"game_selector.py, line 201, in run_swallowed_dialog " +"(self=, puzzle=None, saved_games=[{'gsd.auto_fills': 0, 'tracking': {}, " +"'trackers': {}, 'notes': [], 'saved_at': 1270084485, 'game': '7 8 0 0 0 0 0 " +"5 6 0 0 9 0 8 0 1 0 0 0 4 6 0 0 0 0 7 0 6 5 0 0 0 4 7 9 2 0 0 0 9 0 1 0 0 0 " +"3 9 7 6 0 0 0 1 8 0 6 0 0 0 0 2 8 0 0 0 5 0 4 0 6 0 0 2 1 0 0 0 0 0 4 5\\n7 " +"8 0 0 0 0 0 5 6 0 0 9 0 8 0 1 0 0 0 4 6 0 0 0 0 7 0 6 5 1 8 3 4 7 9 2 0 0 0 " +"9 0 1 0 0 0 3 9 7 6 0 0 0 1 8 0 6 0 0 0 0 2 8 0 0 0 5 0 4 0 6 0 0 2 1 0 0 0 " +"0 0 4 5', 'gsd.impossible_hints': 0, 'timer.__absolute_start_time__': , 'gsd.hints': 0, 'timer.active_time': , 'timer.total_time': }], dialog=, saved_game_model=, sudoku_maker=, main_page=0) " +"at remote 0x98fa6e4>, d=)\n" +" gtk.main()\n" +"(gdb) py-down\n" +"#8 (unable to read python frame information)\n" +"(gdb) py-down\n" +"Unable to find a newer python frame" +msgstr "" +"(gdb) py-down\n" +"#37 Frame 0x9420b04, for file /usr/lib/python2.6/site-packages/gnome_sudoku/" +"main.py, line 906, in start_game ()\n" +" u = UI()\n" +"(gdb) py-down\n" +"#34 (unable to read python frame information)\n" +"(gdb) py-down\n" +"#23 (unable to read python frame information)\n" +"(gdb) py-down\n" +"#19 (unable to read python frame information)\n" +"(gdb) py-down\n" +"#14 Frame 0x99262ac, for file /usr/lib/python2.6/site-packages/gnome_sudoku/" +"game_selector.py, line 201, in run_swallowed_dialog " +"(self=, puzzle=None, saved_games=[{'gsd.auto_fills': 0, 'tracking': {}, " +"'trackers': {}, 'notes': [], 'saved_at': 1270084485, 'game': '7 8 0 0 0 0 0 " +"5 6 0 0 9 0 8 0 1 0 0 0 4 6 0 0 0 0 7 0 6 5 0 0 0 4 7 9 2 0 0 0 9 0 1 0 0 0 " +"3 9 7 6 0 0 0 1 8 0 6 0 0 0 0 2 8 0 0 0 5 0 4 0 6 0 0 2 1 0 0 0 0 0 4 5\\n7 " +"8 0 0 0 0 0 5 6 0 0 9 0 8 0 1 0 0 0 4 6 0 0 0 0 7 0 6 5 1 8 3 4 7 9 2 0 0 0 " +"9 0 1 0 0 0 3 9 7 6 0 0 0 1 8 0 6 0 0 0 0 2 8 0 0 0 5 0 4 0 6 0 0 2 1 0 0 0 " +"0 0 4 5', 'gsd.impossible_hints': 0, 'timer.__absolute_start_time__': , 'gsd.hints': 0, 'timer.active_time': , 'timer.total_time': }], dialog=, saved_game_model=, sudoku_maker=, main_page=0) " +"at remote 0x98fa6e4>, d=)\n" +" gtk.main()\n" +"(gdb) py-down\n" +"#8 (unable to read python frame information)\n" +"(gdb) py-down\n" +"Unable to find a newer python frame" + #: ../../howto/gdb_helpers.rst:289 msgid "and we're at the bottom of the Python stack." msgstr "e estamos na parte inferior da pilha do Python." @@ -430,6 +717,56 @@ msgstr "" "``py-up`` e ``py-down`` podem mover vários quadros Python de uma vez. Por " "exemplo::" +#: ../../howto/gdb_helpers.rst:295 +msgid "" +"(gdb) py-up\n" +"#6 Frame 0x7ffff7fb62b0, for file /tmp/rec.py, line 5, in recursive_function " +"(n=0)\n" +" time.sleep(5)\n" +"#6 Frame 0x7ffff7fb6240, for file /tmp/rec.py, line 7, in recursive_function " +"(n=1)\n" +" recursive_function(n-1)\n" +"#6 Frame 0x7ffff7fb61d0, for file /tmp/rec.py, line 7, in recursive_function " +"(n=2)\n" +" recursive_function(n-1)\n" +"#6 Frame 0x7ffff7fb6160, for file /tmp/rec.py, line 7, in recursive_function " +"(n=3)\n" +" recursive_function(n-1)\n" +"#6 Frame 0x7ffff7fb60f0, for file /tmp/rec.py, line 7, in recursive_function " +"(n=4)\n" +" recursive_function(n-1)\n" +"#6 Frame 0x7ffff7fb6080, for file /tmp/rec.py, line 7, in recursive_function " +"(n=5)\n" +" recursive_function(n-1)\n" +"#6 Frame 0x7ffff7fb6020, for file /tmp/rec.py, line 9, in ()\n" +" recursive_function(5)\n" +"(gdb) py-up\n" +"Unable to find an older python frame" +msgstr "" +"(gdb) py-up\n" +"#6 Frame 0x7ffff7fb62b0, for file /tmp/rec.py, line 5, in recursive_function " +"(n=0)\n" +" time.sleep(5)\n" +"#6 Frame 0x7ffff7fb6240, for file /tmp/rec.py, line 7, in recursive_function " +"(n=1)\n" +" recursive_function(n-1)\n" +"#6 Frame 0x7ffff7fb61d0, for file /tmp/rec.py, line 7, in recursive_function " +"(n=2)\n" +" recursive_function(n-1)\n" +"#6 Frame 0x7ffff7fb6160, for file /tmp/rec.py, line 7, in recursive_function " +"(n=3)\n" +" recursive_function(n-1)\n" +"#6 Frame 0x7ffff7fb60f0, for file /tmp/rec.py, line 7, in recursive_function " +"(n=4)\n" +" recursive_function(n-1)\n" +"#6 Frame 0x7ffff7fb6080, for file /tmp/rec.py, line 7, in recursive_function " +"(n=5)\n" +" recursive_function(n-1)\n" +"#6 Frame 0x7ffff7fb6020, for file /tmp/rec.py, line 9, in ()\n" +" recursive_function(5)\n" +"(gdb) py-up\n" +"Unable to find an older python frame" + #: ../../howto/gdb_helpers.rst:315 msgid "``py-bt``" msgstr "``py-bt``" @@ -442,6 +779,76 @@ msgstr "" "O comando ``py-bt`` tenta mostrar uma rastreabilidade em nível Python da " "thread atual." +#: ../../howto/gdb_helpers.rst:322 +msgid "" +"(gdb) py-bt\n" +"#8 (unable to read python frame information)\n" +"#11 Frame 0x9aead74, for file /usr/lib/python2.6/site-packages/gnome_sudoku/" +"dialog_swallower.py, line 48, in run_dialog " +"(self=, main_page=0) " +"at remote 0x98fa6e4>, d=)\n" +" gtk.main()\n" +"#14 Frame 0x99262ac, for file /usr/lib/python2.6/site-packages/gnome_sudoku/" +"game_selector.py, line 201, in run_swallowed_dialog " +"(self=, puzzle=None, saved_games=[{'gsd.auto_fills': 0, 'tracking': {}, " +"'trackers': {}, 'notes': [], 'saved_at': 1270084485, 'game': '7 8 0 0 0 0 0 " +"5 6 0 0 9 0 8 0 1 0 0 0 4 6 0 0 0 0 7 0 6 5 0 0 0 4 7 9 2 0 0 0 9 0 1 0 0 0 " +"3 9 7 6 0 0 0 1 8 0 6 0 0 0 0 2 8 0 0 0 5 0 4 0 6 0 0 2 1 0 0 0 0 0 4 5\\n7 " +"8 0 0 0 0 0 5 6 0 0 9 0 8 0 1 0 0 0 4 6 0 0 0 0 7 0 6 5 1 8 3 4 7 9 2 0 0 0 " +"9 0 1 0 0 0 3 9 7 6 0 0 0 1 8 0 6 0 0 0 0 2 8 0 0 0 5 0 4 0 6 0 0 2 1 0 0 0 " +"0 0 4 5', 'gsd.impossible_hints': 0, 'timer.__absolute_start_time__': , 'gsd.hints': 0, 'timer.active_time': , 'timer.total_time': }], dialog=, saved_game_model=, sudoku_maker=)\n" +" main.start_game()" +msgstr "" +"(gdb) py-bt\n" +"#8 (unable to read python frame information)\n" +"#11 Frame 0x9aead74, for file /usr/lib/python2.6/site-packages/gnome_sudoku/" +"dialog_swallower.py, line 48, in run_dialog " +"(self=, main_page=0) " +"at remote 0x98fa6e4>, d=)\n" +" gtk.main()\n" +"#14 Frame 0x99262ac, for file /usr/lib/python2.6/site-packages/gnome_sudoku/" +"game_selector.py, line 201, in run_swallowed_dialog " +"(self=, puzzle=None, saved_games=[{'gsd.auto_fills': 0, 'tracking': {}, " +"'trackers': {}, 'notes': [], 'saved_at': 1270084485, 'game': '7 8 0 0 0 0 0 " +"5 6 0 0 9 0 8 0 1 0 0 0 4 6 0 0 0 0 7 0 6 5 0 0 0 4 7 9 2 0 0 0 9 0 1 0 0 0 " +"3 9 7 6 0 0 0 1 8 0 6 0 0 0 0 2 8 0 0 0 5 0 4 0 6 0 0 2 1 0 0 0 0 0 4 5\\n7 " +"8 0 0 0 0 0 5 6 0 0 9 0 8 0 1 0 0 0 4 6 0 0 0 0 7 0 6 5 1 8 3 4 7 9 2 0 0 0 " +"9 0 1 0 0 0 3 9 7 6 0 0 0 1 8 0 6 0 0 0 0 2 8 0 0 0 5 0 4 0 6 0 0 2 1 0 0 0 " +"0 0 4 5', 'gsd.impossible_hints': 0, 'timer.__absolute_start_time__': , 'gsd.hints': 0, 'timer.active_time': , 'timer.total_time': }], dialog=, saved_game_model=, sudoku_maker=)\n" +" main.start_game()" + #: ../../howto/gdb_helpers.rst:336 msgid "" "The frame numbers correspond to those displayed by GDB's standard " @@ -464,6 +871,28 @@ msgstr "" "procura em locais dentro da thread atual, depois em globais e, finalmente, " "em embutidos::" +#: ../../howto/gdb_helpers.rst:346 +msgid "" +"(gdb) py-print self\n" +"local 'self' = ,\n" +"main_page=0) at remote 0x98fa6e4>\n" +"(gdb) py-print __name__\n" +"global '__name__' = 'gnome_sudoku.dialog_swallower'\n" +"(gdb) py-print len\n" +"builtin 'len' = \n" +"(gdb) py-print scarlet_pimpernel\n" +"'scarlet_pimpernel' not found" +msgstr "" +"(gdb) py-print self\n" +"local 'self' = ,\n" +"main_page=0) at remote 0x98fa6e4>\n" +"(gdb) py-print __name__\n" +"global '__name__' = 'gnome_sudoku.dialog_swallower'\n" +"(gdb) py-print len\n" +"builtin 'len' = \n" +"(gdb) py-print scarlet_pimpernel\n" +"'scarlet_pimpernel' not found" + #: ../../howto/gdb_helpers.rst:356 msgid "" "If the current C frame corresponds to multiple Python frames, ``py-print`` " @@ -484,6 +913,18 @@ msgstr "" "O comando ``py-locals`` busca todas as variáveis locais do Python no quadro " "Python atual na thread selecionada e imprime suas representações::" +#: ../../howto/gdb_helpers.rst:365 +msgid "" +"(gdb) py-locals\n" +"self = ,\n" +"main_page=0) at remote 0x98fa6e4>\n" +"d = " +msgstr "" +"(gdb) py-locals\n" +"self = ,\n" +"main_page=0) at remote 0x98fa6e4>\n" +"d = " + #: ../../howto/gdb_helpers.rst:370 msgid "" "If the current C frame corresponds to multiple Python frames, locals from " @@ -492,6 +933,38 @@ msgstr "" "Se o quadro C atual corresponder a vários quadros Python, serão mostrados os " "locais de todos eles:" +#: ../../howto/gdb_helpers.rst:373 +msgid "" +"(gdb) py-locals\n" +"Locals for recursive_function\n" +"n = 0\n" +"Locals for recursive_function\n" +"n = 1\n" +"Locals for recursive_function\n" +"n = 2\n" +"Locals for recursive_function\n" +"n = 3\n" +"Locals for recursive_function\n" +"n = 4\n" +"Locals for recursive_function\n" +"n = 5\n" +"Locals for " +msgstr "" +"(gdb) py-locals\n" +"Locals for recursive_function\n" +"n = 0\n" +"Locals for recursive_function\n" +"n = 1\n" +"Locals for recursive_function\n" +"n = 2\n" +"Locals for recursive_function\n" +"n = 3\n" +"Locals for recursive_function\n" +"n = 4\n" +"Locals for recursive_function\n" +"n = 5\n" +"Locals for " + #: ../../howto/gdb_helpers.rst:390 msgid "Use with GDB commands" msgstr "Uso com comandos do GDB" @@ -507,6 +980,50 @@ msgstr "" "comando ``frame`` para ir a um quadro específico dentro da thread " "selecionada, assim::" +#: ../../howto/gdb_helpers.rst:396 +msgid "" +"(gdb) py-bt\n" +"(output snipped)\n" +"#68 Frame 0xaa4560, for file Lib/test/regrtest.py, line 1548, in " +"()\n" +" main()\n" +"(gdb) frame 68\n" +"#68 0x00000000004cd1e6 in PyEval_EvalFrameEx (f=Frame 0xaa4560, for file Lib/" +"test/regrtest.py, line 1548, in (), throwflag=0) at Python/ceval." +"c:2665\n" +"2665 x = call_function(&sp, oparg);\n" +"(gdb) py-list\n" +"1543 # Run the tests in a context manager that temporary changes the " +"CWD to a\n" +"1544 # temporary and writable directory. If it's not possible to " +"create or\n" +"1545 # change the CWD, the original CWD will be used. The original " +"CWD is\n" +"1546 # available from test_support.SAVEDCWD.\n" +"1547 with test_support.temp_cwd(TESTCWD, quiet=True):\n" +">1548 main()" +msgstr "" +"(gdb) py-bt\n" +"(output snipped)\n" +"#68 Frame 0xaa4560, for file Lib/test/regrtest.py, line 1548, in " +"()\n" +" main()\n" +"(gdb) frame 68\n" +"#68 0x00000000004cd1e6 in PyEval_EvalFrameEx (f=Frame 0xaa4560, for file Lib/" +"test/regrtest.py, line 1548, in (), throwflag=0) at Python/ceval." +"c:2665\n" +"2665 x = call_function(&sp, oparg);\n" +"(gdb) py-list\n" +"1543 # Run the tests in a context manager that temporary changes the " +"CWD to a\n" +"1544 # temporary and writable directory. If it's not possible to " +"create or\n" +"1545 # change the CWD, the original CWD will be used. The original " +"CWD is\n" +"1546 # available from test_support.SAVEDCWD.\n" +"1547 with test_support.temp_cwd(TESTCWD, quiet=True):\n" +">1548 main()" + #: ../../howto/gdb_helpers.rst:411 msgid "" "The ``info threads`` command will give you a list of the threads within the " @@ -516,6 +1033,24 @@ msgstr "" "processo, e você pode usar o comando ``thread`` para selecionar uma " "diferente::" +#: ../../howto/gdb_helpers.rst:414 +msgid "" +"(gdb) info threads\n" +" 105 Thread 0x7fffefa18710 (LWP 10260) sem_wait () at ../nptl/sysdeps/unix/" +"sysv/linux/x86_64/sem_wait.S:86\n" +" 104 Thread 0x7fffdf5fe710 (LWP 10259) sem_wait () at ../nptl/sysdeps/unix/" +"sysv/linux/x86_64/sem_wait.S:86\n" +"* 1 Thread 0x7ffff7fe2700 (LWP 10145) 0x00000038e46d73e3 in select () at ../" +"sysdeps/unix/syscall-template.S:82" +msgstr "" +"(gdb) info threads\n" +" 105 Thread 0x7fffefa18710 (LWP 10260) sem_wait () at ../nptl/sysdeps/unix/" +"sysv/linux/x86_64/sem_wait.S:86\n" +" 104 Thread 0x7fffdf5fe710 (LWP 10259) sem_wait () at ../nptl/sysdeps/unix/" +"sysv/linux/x86_64/sem_wait.S:86\n" +"* 1 Thread 0x7ffff7fe2700 (LWP 10145) 0x00000038e46d73e3 in select () at ../" +"sysdeps/unix/syscall-template.S:82" + #: ../../howto/gdb_helpers.rst:419 msgid "" "You can use ``thread apply all COMMAND`` or (``t a a COMMAND`` for short) to " @@ -525,3 +1060,161 @@ msgstr "" "Você pode usar ``thread apply all COMANDO`` ou (``t a a COMANDO`` para " "abreviar) para executar um comando em todas as threads. Com ``py-bt``, isso " "permite que você veja o que cada thread está fazendo no nível do Python::" + +#: ../../howto/gdb_helpers.rst:423 +msgid "" +"(gdb) t a a py-bt\n" +"\n" +"Thread 105 (Thread 0x7fffefa18710 (LWP 10260)):\n" +"#5 Frame 0x7fffd00019d0, for file /home/david/coding/python-svn/Lib/" +"threading.py, line 155, in _acquire_restore " +"(self=<_RLock(_Verbose__verbose=False, _RLock__owner=140737354016512, " +"_RLock__block=, _RLock__count=1) at remote " +"0xd7ff40>, count_owner=(1, 140737213728528), count=1, " +"owner=140737213728528)\n" +" self.__block.acquire()\n" +"#8 Frame 0x7fffac001640, for file /home/david/coding/python-svn/Lib/" +"threading.py, line 269, in wait " +"(self=<_Condition(_Condition__lock=<_RLock(_Verbose__verbose=False, " +"_RLock__owner=140737354016512, _RLock__block=, _RLock__count=1) at remote 0xd7ff40>, acquire=, _is_owned=, " +"_release_save=, release=, _acquire_restore=, " +"_Verbose__verbose=False, _Condition__waiters=[]) at remote 0xd7fd10>, " +"timeout=None, waiter=, saved_state=(1, " +"140737213728528))\n" +" self._acquire_restore(saved_state)\n" +"#12 Frame 0x7fffb8001a10, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 348, in f ()\n" +" cond.wait()\n" +"#16 Frame 0x7fffb8001c40, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 37, in task (tid=140737213728528)\n" +" f()\n" +"\n" +"Thread 104 (Thread 0x7fffdf5fe710 (LWP 10259)):\n" +"#5 Frame 0x7fffe4001580, for file /home/david/coding/python-svn/Lib/" +"threading.py, line 155, in _acquire_restore " +"(self=<_RLock(_Verbose__verbose=False, _RLock__owner=140737354016512, " +"_RLock__block=, _RLock__count=1) at remote " +"0xd7ff40>, count_owner=(1, 140736940992272), count=1, " +"owner=140736940992272)\n" +" self.__block.acquire()\n" +"#8 Frame 0x7fffc8002090, for file /home/david/coding/python-svn/Lib/" +"threading.py, line 269, in wait " +"(self=<_Condition(_Condition__lock=<_RLock(_Verbose__verbose=False, " +"_RLock__owner=140737354016512, _RLock__block=, _RLock__count=1) at remote 0xd7ff40>, acquire=, _is_owned=, " +"_release_save=, release=, _acquire_restore=, " +"_Verbose__verbose=False, _Condition__waiters=[]) at remote 0xd7fd10>, " +"timeout=None, waiter=, saved_state=(1, " +"140736940992272))\n" +" self._acquire_restore(saved_state)\n" +"#12 Frame 0x7fffac001c90, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 348, in f ()\n" +" cond.wait()\n" +"#16 Frame 0x7fffac0011c0, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 37, in task (tid=140736940992272)\n" +" f()\n" +"\n" +"Thread 1 (Thread 0x7ffff7fe2700 (LWP 10145)):\n" +"#5 Frame 0xcb5380, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 16, in _wait ()\n" +" time.sleep(0.01)\n" +"#8 Frame 0x7fffd00024a0, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 378, in _check_notify " +"(self=, skipped=[], _mirrorOutput=False, testsRun=39, " +"buffer=False, _original_stderr=, " +"_stdout_buffer=, " +"_stderr_buffer=, " +"_moduleSetUpFailed=False, expectedFailures=[], errors=[], " +"_previousTestClass=, unexpectedSuccesses=[], " +"failures=[], shouldStop=False, failfast=False) at remote 0xc185a0>, " +"_threads=(0,), _cleanups=[], _type_equality_funcs={: , : " +", : " +", : " +", , _RLock__count=1) at remote " +"0xd7ff40>, count_owner=(1, 140737213728528), count=1, " +"owner=140737213728528)\n" +" self.__block.acquire()\n" +"#8 Frame 0x7fffac001640, for file /home/david/coding/python-svn/Lib/" +"threading.py, line 269, in wait " +"(self=<_Condition(_Condition__lock=<_RLock(_Verbose__verbose=False, " +"_RLock__owner=140737354016512, _RLock__block=, _RLock__count=1) at remote 0xd7ff40>, acquire=, _is_owned=, " +"_release_save=, release=, _acquire_restore=, " +"_Verbose__verbose=False, _Condition__waiters=[]) at remote 0xd7fd10>, " +"timeout=None, waiter=, saved_state=(1, " +"140737213728528))\n" +" self._acquire_restore(saved_state)\n" +"#12 Frame 0x7fffb8001a10, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 348, in f ()\n" +" cond.wait()\n" +"#16 Frame 0x7fffb8001c40, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 37, in task (tid=140737213728528)\n" +" f()\n" +"\n" +"Thread 104 (Thread 0x7fffdf5fe710 (LWP 10259)):\n" +"#5 Frame 0x7fffe4001580, for file /home/david/coding/python-svn/Lib/" +"threading.py, line 155, in _acquire_restore " +"(self=<_RLock(_Verbose__verbose=False, _RLock__owner=140737354016512, " +"_RLock__block=, _RLock__count=1) at remote " +"0xd7ff40>, count_owner=(1, 140736940992272), count=1, " +"owner=140736940992272)\n" +" self.__block.acquire()\n" +"#8 Frame 0x7fffc8002090, for file /home/david/coding/python-svn/Lib/" +"threading.py, line 269, in wait " +"(self=<_Condition(_Condition__lock=<_RLock(_Verbose__verbose=False, " +"_RLock__owner=140737354016512, _RLock__block=, _RLock__count=1) at remote 0xd7ff40>, acquire=, _is_owned=, " +"_release_save=, release=, _acquire_restore=, " +"_Verbose__verbose=False, _Condition__waiters=[]) at remote 0xd7fd10>, " +"timeout=None, waiter=, saved_state=(1, " +"140736940992272))\n" +" self._acquire_restore(saved_state)\n" +"#12 Frame 0x7fffac001c90, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 348, in f ()\n" +" cond.wait()\n" +"#16 Frame 0x7fffac0011c0, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 37, in task (tid=140736940992272)\n" +" f()\n" +"\n" +"Thread 1 (Thread 0x7ffff7fe2700 (LWP 10145)):\n" +"#5 Frame 0xcb5380, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 16, in _wait ()\n" +" time.sleep(0.01)\n" +"#8 Frame 0x7fffd00024a0, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 378, in _check_notify " +"(self=, skipped=[], _mirrorOutput=False, testsRun=39, " +"buffer=False, _original_stderr=, " +"_stdout_buffer=, " +"_stderr_buffer=, " +"_moduleSetUpFailed=False, expectedFailures=[], errors=[], " +"_previousTestClass=, unexpectedSuccesses=[], " +"failures=[], shouldStop=False, failfast=False) at remote 0xc185a0>, " +"_threads=(0,), _cleanups=[], _type_equality_funcs={: , : " +", : " +", : " +", , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Marco Rougeth , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-21 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:53+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -36,107 +34,111 @@ msgid "" "effort to foster documentation that's more detailed than the Python Library " "Reference." msgstr "" -"Python HOWTOs são documentos que cobrem um tópico específico em " +"Python HOWTOs (COMOFAZER) são documentos que cobrem um tópico específico em " "profundidade. Modelada na coleção HOWTO do Linux Documentation Project, esta " "coleção é um esforço para promover uma documentação mais detalhada do que a " "Referência da Biblioteca do Python." -#: ../../howto/index.rst:37 +#: ../../howto/index.rst:38 msgid "General:" msgstr "Geral:" -#: ../../howto/index.rst:39 +#: ../../howto/index.rst:40 msgid ":ref:`annotations-howto`" msgstr ":ref:`annotations-howto`" -#: ../../howto/index.rst:40 +#: ../../howto/index.rst:41 msgid ":ref:`argparse-tutorial`" msgstr ":ref:`argparse-tutorial`" -#: ../../howto/index.rst:41 +#: ../../howto/index.rst:42 msgid ":ref:`descriptorhowto`" msgstr ":ref:`descriptorhowto`" -#: ../../howto/index.rst:42 +#: ../../howto/index.rst:43 msgid ":ref:`enum-howto`" msgstr ":ref:`enum-howto`" -#: ../../howto/index.rst:43 +#: ../../howto/index.rst:44 msgid ":ref:`functional-howto`" msgstr ":ref:`functional-howto`" -#: ../../howto/index.rst:44 +#: ../../howto/index.rst:45 msgid ":ref:`ipaddress-howto`" msgstr ":ref:`ipaddress-howto`" -#: ../../howto/index.rst:45 +#: ../../howto/index.rst:46 msgid ":ref:`logging-howto`" msgstr ":ref:`logging-howto`" -#: ../../howto/index.rst:46 +#: ../../howto/index.rst:47 msgid ":ref:`logging-cookbook`" msgstr ":ref:`logging-cookbook`" -#: ../../howto/index.rst:47 +#: ../../howto/index.rst:48 msgid ":ref:`regex-howto`" msgstr ":ref:`regex-howto`" -#: ../../howto/index.rst:48 +#: ../../howto/index.rst:49 msgid ":ref:`sortinghowto`" msgstr ":ref:`sortinghowto`" -#: ../../howto/index.rst:49 +#: ../../howto/index.rst:50 msgid ":ref:`unicode-howto`" msgstr ":ref:`unicode-howto`" -#: ../../howto/index.rst:50 +#: ../../howto/index.rst:51 msgid ":ref:`urllib-howto`" msgstr ":ref:`urllib-howto`" -#: ../../howto/index.rst:52 +#: ../../howto/index.rst:53 msgid "Advanced development:" msgstr "Desenvolvimento avançado:" -#: ../../howto/index.rst:54 +#: ../../howto/index.rst:55 msgid ":ref:`curses-howto`" msgstr ":ref:`curses-howto`" -#: ../../howto/index.rst:55 +#: ../../howto/index.rst:56 +msgid ":ref:`freethreading-python-howto`" +msgstr ":ref:`freethreading-python-howto`" + +#: ../../howto/index.rst:57 msgid ":ref:`freethreading-extensions-howto`" msgstr ":ref:`freethreading-extensions-howto`" -#: ../../howto/index.rst:56 +#: ../../howto/index.rst:58 msgid ":ref:`isolating-extensions-howto`" msgstr ":ref:`isolating-extensions-howto`" -#: ../../howto/index.rst:57 +#: ../../howto/index.rst:59 msgid ":ref:`python_2.3_mro`" msgstr ":ref:`python_2.3_mro`" -#: ../../howto/index.rst:58 +#: ../../howto/index.rst:60 msgid ":ref:`socket-howto`" msgstr ":ref:`socket-howto`" -#: ../../howto/index.rst:59 +#: ../../howto/index.rst:61 msgid ":ref:`timerfd-howto`" msgstr ":ref:`timerfd-howto`" -#: ../../howto/index.rst:60 +#: ../../howto/index.rst:62 msgid ":ref:`cporting-howto`" msgstr ":ref:`cporting-howto`" -#: ../../howto/index.rst:62 +#: ../../howto/index.rst:64 msgid "Debugging and profiling:" msgstr "Depuração e perfilação:" -#: ../../howto/index.rst:64 +#: ../../howto/index.rst:66 msgid ":ref:`gdb`" msgstr ":ref:`gdb`" -#: ../../howto/index.rst:65 +#: ../../howto/index.rst:67 msgid ":ref:`instrumentation`" msgstr ":ref:`instrumentation`" -#: ../../howto/index.rst:66 +#: ../../howto/index.rst:68 msgid ":ref:`perf_profiling`" msgstr ":ref:`perf_profiling`" diff --git a/howto/instrumentation.po b/howto/instrumentation.po index b3fced3ad..f88018602 100644 --- a/howto/instrumentation.po +++ b/howto/instrumentation.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Hemílio Lauro , 2021 -# i17obot , 2021 -# Leandro Cavalcante Damascena , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 00:53+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -50,6 +45,10 @@ msgid "" "what the processes on a computer system are doing. They both use domain-" "specific languages allowing a user to write scripts which:" msgstr "" +"DTrace e SystemTap são ferramentas de monitoramento, cada uma fornecendo uma " +"maneira de inspecionar o que os processos em um sistema de computador estão " +"fazendo. Ambas usam linguagens específicas de domínio, permitindo que um " +"usuário escreva scripts que:" #: ../../howto/instrumentation.rst:16 msgid "filter which processes are to be observed" @@ -57,11 +56,11 @@ msgstr "filtrar quais processos devem ser observados" #: ../../howto/instrumentation.rst:17 msgid "gather data from the processes of interest" -msgstr "" +msgstr "coletem dados dos processos de interesse" #: ../../howto/instrumentation.rst:18 msgid "generate reports on the data" -msgstr "" +msgstr "gerem relatórios sobre os dados" #: ../../howto/instrumentation.rst:20 msgid "" @@ -69,6 +68,10 @@ msgid "" "as \"probes\", that can be observed by a DTrace or SystemTap script, making " "it easier to monitor what the CPython processes on a system are doing." msgstr "" +"A partir do Python 3.6, o CPython pode ser criado com \"marcadores\" " +"incorporados, também conhecidos como \"sondas\" (*probes*), que podem ser " +"observados por um script DTrace ou SystemTap, facilitando o monitoramento do " +"que os processos CPython em um sistema estão fazendo." #: ../../howto/instrumentation.rst:27 msgid "" @@ -77,10 +80,14 @@ msgid "" "DTrace scripts can stop working or work incorrectly without warning when " "changing CPython versions." msgstr "" +"Os marcadores DTrace são detalhes de implementação do interpretador CPython. " +"Não há garantias sobre a compatibilidade de sondas entre versões do CPython. " +"Os scripts DTrace podem parar de funcionar ou funcionar incorretamente sem " +"aviso ao alterar as versões do CPython." #: ../../howto/instrumentation.rst:34 msgid "Enabling the static markers" -msgstr "" +msgstr "Habilitando os marcadores estáticos" #: ../../howto/instrumentation.rst:36 msgid "" @@ -88,20 +95,37 @@ msgid "" "CPython with the embedded markers for SystemTap, the SystemTap development " "tools must be installed." msgstr "" +"O macOS vem com suporte embutido para DTrace. No Linux, para construir o " +"CPython com os marcadores incorporados para SystemTap, as ferramentas de " +"desenvolvimento SystemTap devem ser instaladas." #: ../../howto/instrumentation.rst:40 msgid "On a Linux machine, this can be done via::" -msgstr "" +msgstr "Em uma máquina Linux, isso pode ser feito via:" + +#: ../../howto/instrumentation.rst:42 +msgid "$ yum install systemtap-sdt-devel" +msgstr "$ yum install systemtap-sdt-devel" #: ../../howto/instrumentation.rst:44 msgid "or::" msgstr "ou::" +#: ../../howto/instrumentation.rst:46 +msgid "$ sudo apt-get install systemtap-sdt-dev" +msgstr "$ sudo apt-get install systemtap-sdt-dev" + #: ../../howto/instrumentation.rst:49 msgid "" "CPython must then be :option:`configured with the --with-dtrace option <--" "with-dtrace>`:" msgstr "" +"O CPython deve então ser :option:`configurado com a opção --with-dtrace <--" +"with-dtrace>`:" + +#: ../../howto/instrumentation.rst:52 +msgid "checking for --with-dtrace... yes" +msgstr "checking for --with-dtrace... yes" #: ../../howto/instrumentation.rst:56 msgid "" @@ -109,12 +133,66 @@ msgid "" "in the background and listing all probes made available by the Python " "provider::" msgstr "" +"No macOS, você pode listar as sondas DTrace disponíveis executando um " +"processo Python em segundo plano e listando todas as sondas disponibilizadas " +"pelo provedor Python::" + +#: ../../howto/instrumentation.rst:60 +msgid "" +"$ python3.6 -q &\n" +"$ sudo dtrace -l -P python$! # or: dtrace -l -m python3.6\n" +"\n" +" ID PROVIDER MODULE FUNCTION NAME\n" +"29564 python18035 python3.6 _PyEval_EvalFrameDefault " +"function-entry\n" +"29565 python18035 python3.6 dtrace_function_entry " +"function-entry\n" +"29566 python18035 python3.6 _PyEval_EvalFrameDefault " +"function-return\n" +"29567 python18035 python3.6 dtrace_function_return " +"function-return\n" +"29568 python18035 python3.6 collect gc-" +"done\n" +"29569 python18035 python3.6 collect gc-" +"start\n" +"29570 python18035 python3.6 _PyEval_EvalFrameDefault line\n" +"29571 python18035 python3.6 maybe_dtrace_line line" +msgstr "" +"$ python3.6 -q &\n" +"$ sudo dtrace -l -P python$! # or: dtrace -l -m python3.6\n" +"\n" +" ID PROVIDER MODULE FUNCTION NAME\n" +"29564 python18035 python3.6 _PyEval_EvalFrameDefault " +"function-entry\n" +"29565 python18035 python3.6 dtrace_function_entry " +"function-entry\n" +"29566 python18035 python3.6 _PyEval_EvalFrameDefault " +"function-return\n" +"29567 python18035 python3.6 dtrace_function_return " +"function-return\n" +"29568 python18035 python3.6 collect gc-" +"done\n" +"29569 python18035 python3.6 collect gc-" +"start\n" +"29570 python18035 python3.6 _PyEval_EvalFrameDefault line\n" +"29571 python18035 python3.6 maybe_dtrace_line line" #: ../../howto/instrumentation.rst:73 msgid "" "On Linux, you can verify if the SystemTap static markers are present in the " "built binary by seeing if it contains a \".note.stapsdt\" section." msgstr "" +"No Linux, você pode verificar se os marcadores estáticos do SystemTap estão " +"presentes no binário compilado, observando se ele contém uma seção \".note." +"stapsdt\"." + +#: ../../howto/instrumentation.rst:78 +msgid "" +"$ readelf -S ./python | grep .note.stapsdt\n" +"[30] .note.stapsdt NOTE 0000000000000000 00308d78" +msgstr "" +"$ readelf -S ./python | grep .note.stapsdt\n" +"[30] .note.stapsdt NOTE 0000000000000000 00308d78" #: ../../howto/instrumentation.rst:81 msgid "" @@ -122,10 +200,113 @@ msgid "" "shared` configure option), you need to look instead within the shared " "library. For example::" msgstr "" +"Se você construiu o Python como uma biblioteca compartilhada (com a opção de " +"configuração :option:`--enable-shared`), você precisa procurar dentro da " +"biblioteca compartilhada. Por exemplo::" + +#: ../../howto/instrumentation.rst:85 +msgid "" +"$ readelf -S libpython3.3dm.so.1.0 | grep .note.stapsdt\n" +"[29] .note.stapsdt NOTE 0000000000000000 00365b68" +msgstr "" +"$ readelf -S libpython3.3dm.so.1.0 | grep .note.stapsdt\n" +"[29] .note.stapsdt NOTE 0000000000000000 00365b68" #: ../../howto/instrumentation.rst:88 msgid "Sufficiently modern readelf can print the metadata::" -msgstr "" +msgstr "Um readelf moderno o suficiente pode exibir os metadados::" + +#: ../../howto/instrumentation.rst:90 +msgid "" +"$ readelf -n ./python\n" +"\n" +"Displaying notes found at file offset 0x00000254 with length 0x00000020:\n" +" Owner Data size Description\n" +" GNU 0x00000010 NT_GNU_ABI_TAG (ABI version " +"tag)\n" +" OS: Linux, ABI: 2.6.32\n" +"\n" +"Displaying notes found at file offset 0x00000274 with length 0x00000024:\n" +" Owner Data size Description\n" +" GNU 0x00000014 NT_GNU_BUILD_ID (unique build " +"ID bitstring)\n" +" Build ID: df924a2b08a7e89f6e11251d4602022977af2670\n" +"\n" +"Displaying notes found at file offset 0x002d6c30 with length 0x00000144:\n" +" Owner Data size Description\n" +" stapsdt 0x00000031 NT_STAPSDT (SystemTap probe " +"descriptors)\n" +" Provider: python\n" +" Name: gc__start\n" +" Location: 0x00000000004371c3, Base: 0x0000000000630ce2, Semaphore: " +"0x00000000008d6bf6\n" +" Arguments: -4@%ebx\n" +" stapsdt 0x00000030 NT_STAPSDT (SystemTap probe " +"descriptors)\n" +" Provider: python\n" +" Name: gc__done\n" +" Location: 0x00000000004374e1, Base: 0x0000000000630ce2, Semaphore: " +"0x00000000008d6bf8\n" +" Arguments: -8@%rax\n" +" stapsdt 0x00000045 NT_STAPSDT (SystemTap probe " +"descriptors)\n" +" Provider: python\n" +" Name: function__entry\n" +" Location: 0x000000000053db6c, Base: 0x0000000000630ce2, Semaphore: " +"0x00000000008d6be8\n" +" Arguments: 8@%rbp 8@%r12 -4@%eax\n" +" stapsdt 0x00000046 NT_STAPSDT (SystemTap probe " +"descriptors)\n" +" Provider: python\n" +" Name: function__return\n" +" Location: 0x000000000053dba8, Base: 0x0000000000630ce2, Semaphore: " +"0x00000000008d6bea\n" +" Arguments: 8@%rbp 8@%r12 -4@%eax" +msgstr "" +"$ readelf -n ./python\n" +"\n" +"Displaying notes found at file offset 0x00000254 with length 0x00000020:\n" +" Owner Data size Description\n" +" GNU 0x00000010 NT_GNU_ABI_TAG (ABI version " +"tag)\n" +" OS: Linux, ABI: 2.6.32\n" +"\n" +"Displaying notes found at file offset 0x00000274 with length 0x00000024:\n" +" Owner Data size Description\n" +" GNU 0x00000014 NT_GNU_BUILD_ID (unique build " +"ID bitstring)\n" +" Build ID: df924a2b08a7e89f6e11251d4602022977af2670\n" +"\n" +"Displaying notes found at file offset 0x002d6c30 with length 0x00000144:\n" +" Owner Data size Description\n" +" stapsdt 0x00000031 NT_STAPSDT (SystemTap probe " +"descriptors)\n" +" Provider: python\n" +" Name: gc__start\n" +" Location: 0x00000000004371c3, Base: 0x0000000000630ce2, Semaphore: " +"0x00000000008d6bf6\n" +" Arguments: -4@%ebx\n" +" stapsdt 0x00000030 NT_STAPSDT (SystemTap probe " +"descriptors)\n" +" Provider: python\n" +" Name: gc__done\n" +" Location: 0x00000000004374e1, Base: 0x0000000000630ce2, Semaphore: " +"0x00000000008d6bf8\n" +" Arguments: -8@%rax\n" +" stapsdt 0x00000045 NT_STAPSDT (SystemTap probe " +"descriptors)\n" +" Provider: python\n" +" Name: function__entry\n" +" Location: 0x000000000053db6c, Base: 0x0000000000630ce2, Semaphore: " +"0x00000000008d6be8\n" +" Arguments: 8@%rbp 8@%r12 -4@%eax\n" +" stapsdt 0x00000046 NT_STAPSDT (SystemTap probe " +"descriptors)\n" +" Provider: python\n" +" Name: function__return\n" +" Location: 0x000000000053dba8, Base: 0x0000000000630ce2, Semaphore: " +"0x00000000008d6bea\n" +" Arguments: 8@%rbp 8@%r12 -4@%eax" #: ../../howto/instrumentation.rst:125 msgid "" @@ -133,10 +314,13 @@ msgid "" "patch strategically placed machine code instructions to enable the tracing " "hooks used by a SystemTap script." msgstr "" +"Os metadados acima contêm informações sobre o SystemTap descrevendo como ele " +"pode corrigir instruções de código de máquina estrategicamente posicionadas " +"para habilitar os ganchos de rastreamento usados por um script do SystemTap." #: ../../howto/instrumentation.rst:131 msgid "Static DTrace probes" -msgstr "" +msgstr "Sondas estáticas do DTtrace" #: ../../howto/instrumentation.rst:133 msgid "" @@ -145,18 +329,136 @@ msgid "" "function called \"start\". In other words, import-time function invocations " "are not going to be listed:" msgstr "" +"O script DTrace de exemplo a seguir pode ser usado para mostrar a hierarquia " +"de chamada/retorno de um script Python, rastreando apenas dentro da " +"invocação de uma função chamada \"start\". Em outras palavras, invocações de " +"função em tempo de importação não serão listadas:" + +#: ../../howto/instrumentation.rst:138 +msgid "" +"self int indent;\n" +"\n" +"python$target:::function-entry\n" +"/copyinstr(arg1) == \"start\"/\n" +"{\n" +" self->trace = 1;\n" +"}\n" +"\n" +"python$target:::function-entry\n" +"/self->trace/\n" +"{\n" +" printf(\"%d\\t%*s:\", timestamp, 15, probename);\n" +" printf(\"%*s\", self->indent, \"\");\n" +" printf(\"%s:%s:%d\\n\", basename(copyinstr(arg0)), copyinstr(arg1), " +"arg2);\n" +" self->indent++;\n" +"}\n" +"\n" +"python$target:::function-return\n" +"/self->trace/\n" +"{\n" +" self->indent--;\n" +" printf(\"%d\\t%*s:\", timestamp, 15, probename);\n" +" printf(\"%*s\", self->indent, \"\");\n" +" printf(\"%s:%s:%d\\n\", basename(copyinstr(arg0)), copyinstr(arg1), " +"arg2);\n" +"}\n" +"\n" +"python$target:::function-return\n" +"/copyinstr(arg1) == \"start\"/\n" +"{\n" +" self->trace = 0;\n" +"}" +msgstr "" +"self int indent;\n" +"\n" +"python$target:::function-entry\n" +"/copyinstr(arg1) == \"start\"/\n" +"{\n" +" self->trace = 1;\n" +"}\n" +"\n" +"python$target:::function-entry\n" +"/self->trace/\n" +"{\n" +" printf(\"%d\\t%*s:\", timestamp, 15, probename);\n" +" printf(\"%*s\", self->indent, \"\");\n" +" printf(\"%s:%s:%d\\n\", basename(copyinstr(arg0)), copyinstr(arg1), " +"arg2);\n" +" self->indent++;\n" +"}\n" +"\n" +"python$target:::function-return\n" +"/self->trace/\n" +"{\n" +" self->indent--;\n" +" printf(\"%d\\t%*s:\", timestamp, 15, probename);\n" +" printf(\"%*s\", self->indent, \"\");\n" +" printf(\"%s:%s:%d\\n\", basename(copyinstr(arg0)), copyinstr(arg1), " +"arg2);\n" +"}\n" +"\n" +"python$target:::function-return\n" +"/copyinstr(arg1) == \"start\"/\n" +"{\n" +" self->trace = 0;\n" +"}" #: ../../howto/instrumentation.rst:172 ../../howto/instrumentation.rst:230 msgid "It can be invoked like this::" -msgstr "" +msgstr "Pode ser invocado assim::" + +#: ../../howto/instrumentation.rst:174 +msgid "$ sudo dtrace -q -s call_stack.d -c \"python3.6 script.py\"" +msgstr "$ sudo dtrace -q -s call_stack.d -c \"python3.6 script.py\"" #: ../../howto/instrumentation.rst:176 ../../howto/instrumentation.rst:236 msgid "The output looks like this:" msgstr "O resultado deve ser algo assim:" +#: ../../howto/instrumentation.rst:178 +msgid "" +"156641360502280 function-entry:call_stack.py:start:23\n" +"156641360518804 function-entry: call_stack.py:function_1:1\n" +"156641360532797 function-entry: call_stack.py:function_3:9\n" +"156641360546807 function-return: call_stack.py:function_3:10\n" +"156641360563367 function-return: call_stack.py:function_1:2\n" +"156641360578365 function-entry: call_stack.py:function_2:5\n" +"156641360591757 function-entry: call_stack.py:function_1:1\n" +"156641360605556 function-entry: call_stack.py:function_3:9\n" +"156641360617482 function-return: call_stack.py:function_3:10\n" +"156641360629814 function-return: call_stack.py:function_1:2\n" +"156641360642285 function-return: call_stack.py:function_2:6\n" +"156641360656770 function-entry: call_stack.py:function_3:9\n" +"156641360669707 function-return: call_stack.py:function_3:10\n" +"156641360687853 function-entry: call_stack.py:function_4:13\n" +"156641360700719 function-return: call_stack.py:function_4:14\n" +"156641360719640 function-entry: call_stack.py:function_5:18\n" +"156641360732567 function-return: call_stack.py:function_5:21\n" +"156641360747370 function-return:call_stack.py:start:28" +msgstr "" +"156641360502280 function-entry:call_stack.py:start:23\n" +"156641360518804 function-entry: call_stack.py:function_1:1\n" +"156641360532797 function-entry: call_stack.py:function_3:9\n" +"156641360546807 function-return: call_stack.py:function_3:10\n" +"156641360563367 function-return: call_stack.py:function_1:2\n" +"156641360578365 function-entry: call_stack.py:function_2:5\n" +"156641360591757 function-entry: call_stack.py:function_1:1\n" +"156641360605556 function-entry: call_stack.py:function_3:9\n" +"156641360617482 function-return: call_stack.py:function_3:10\n" +"156641360629814 function-return: call_stack.py:function_1:2\n" +"156641360642285 function-return: call_stack.py:function_2:6\n" +"156641360656770 function-entry: call_stack.py:function_3:9\n" +"156641360669707 function-return: call_stack.py:function_3:10\n" +"156641360687853 function-entry: call_stack.py:function_4:13\n" +"156641360700719 function-return: call_stack.py:function_4:14\n" +"156641360719640 function-entry: call_stack.py:function_5:18\n" +"156641360732567 function-return: call_stack.py:function_5:21\n" +"156641360747370 function-return:call_stack.py:start:28" + #: ../../howto/instrumentation.rst:201 msgid "Static SystemTap markers" -msgstr "" +msgstr "Marcadores estáticos do SystemTap" #: ../../howto/instrumentation.rst:203 msgid "" @@ -164,33 +466,104 @@ msgid "" "markers directly. This requires you to explicitly state the binary file " "containing them." msgstr "" +"A maneira de baixo nível de usar a integração do SystemTap é usar os " +"marcadores estáticos diretamente. Isso requer que você declare " +"explicitamente o arquivo binário que os contém." #: ../../howto/instrumentation.rst:207 msgid "" "For example, this SystemTap script can be used to show the call/return " "hierarchy of a Python script:" msgstr "" +"Por exemplo, este script SystemTap pode ser usado para mostrar a hierarquia " +"de chamada/retorno de um script Python:" + +#: ../../howto/instrumentation.rst:210 +msgid "" +"probe process(\"python\").mark(\"function__entry\") {\n" +" filename = user_string($arg1);\n" +" funcname = user_string($arg2);\n" +" lineno = $arg3;\n" +"\n" +" printf(\"%s => %s in %s:%d\\\\n\",\n" +" thread_indent(1), funcname, filename, lineno);\n" +"}\n" +"\n" +"probe process(\"python\").mark(\"function__return\") {\n" +" filename = user_string($arg1);\n" +" funcname = user_string($arg2);\n" +" lineno = $arg3;\n" +"\n" +" printf(\"%s <= %s in %s:%d\\\\n\",\n" +" thread_indent(-1), funcname, filename, lineno);\n" +"}" +msgstr "" +"probe process(\"python\").mark(\"function__entry\") {\n" +" filename = user_string($arg1);\n" +" funcname = user_string($arg2);\n" +" lineno = $arg3;\n" +"\n" +" printf(\"%s => %s in %s:%d\\\\n\",\n" +" thread_indent(1), funcname, filename, lineno);\n" +"}\n" +"\n" +"probe process(\"python\").mark(\"function__return\") {\n" +" filename = user_string($arg1);\n" +" funcname = user_string($arg2);\n" +" lineno = $arg3;\n" +"\n" +" printf(\"%s <= %s in %s:%d\\\\n\",\n" +" thread_indent(-1), funcname, filename, lineno);\n" +"}" + +#: ../../howto/instrumentation.rst:232 +msgid "" +"$ stap \\\n" +" show-call-hierarchy.stp \\\n" +" -c \"./python test.py\"" +msgstr "" +"$ stap \\\n" +" show-call-hierarchy.stp \\\n" +" -c \"./python test.py\"" + +#: ../../howto/instrumentation.rst:238 +msgid "" +"11408 python(8274): => __contains__ in Lib/_abcoll.py:362\n" +"11414 python(8274): => __getitem__ in Lib/os.py:425\n" +"11418 python(8274): => encode in Lib/os.py:490\n" +"11424 python(8274): <= encode in Lib/os.py:493\n" +"11428 python(8274): <= __getitem__ in Lib/os.py:426\n" +"11433 python(8274): <= __contains__ in Lib/_abcoll.py:366" +msgstr "" +"11408 python(8274): => __contains__ in Lib/_abcoll.py:362\n" +"11414 python(8274): => __getitem__ in Lib/os.py:425\n" +"11418 python(8274): => encode in Lib/os.py:490\n" +"11424 python(8274): <= encode in Lib/os.py:493\n" +"11428 python(8274): <= __getitem__ in Lib/os.py:426\n" +"11433 python(8274): <= __contains__ in Lib/_abcoll.py:366" #: ../../howto/instrumentation.rst:247 msgid "where the columns are:" -msgstr "" +msgstr "sendo as colunas:" #: ../../howto/instrumentation.rst:249 msgid "time in microseconds since start of script" -msgstr "" +msgstr "tempo em microssegundos desde o início do script" #: ../../howto/instrumentation.rst:250 msgid "name of executable" -msgstr "" +msgstr "nome do executável" #: ../../howto/instrumentation.rst:251 msgid "PID of process" -msgstr "" +msgstr "PID do processo" #: ../../howto/instrumentation.rst:253 msgid "" "and the remainder indicates the call/return hierarchy as the script executes." msgstr "" +"e o restante indica a hierarquia de chamada/retorno conforme o script é " +"executado." #: ../../howto/instrumentation.rst:255 msgid "" @@ -198,24 +571,42 @@ msgid "" "within the libpython shared library, and the probe's dotted path needs to " "reflect this. For example, this line from the above example:" msgstr "" +"Para uma construção com :option:`--enable-shared` do CPython, os marcadores " +"estão contidos na biblioteca compartilhada libpython, e o caminho pontilhado " +"da sonda precisa refletir isso. Por exemplo, esta linha do exemplo acima:" + +#: ../../howto/instrumentation.rst:259 +msgid "probe process(\"python\").mark(\"function__entry\") {" +msgstr "probe process(\"python\").mark(\"function__entry\") {" #: ../../howto/instrumentation.rst:263 msgid "should instead read:" +msgstr "deve ler-se em vez disso:" + +#: ../../howto/instrumentation.rst:265 +msgid "" +"probe process(\"python\").library(\"libpython3.6dm.so.1.0\")." +"mark(\"function__entry\") {" msgstr "" +"probe process(\"python\").library(\"libpython3.6dm.so.1.0\")." +"mark(\"function__entry\") {" #: ../../howto/instrumentation.rst:269 msgid "(assuming a :ref:`debug build ` of CPython 3.6)" msgstr "" +"(presumindo uma :ref:`construção de depuração ` do CPython 3.6)" #: ../../howto/instrumentation.rst:273 msgid "Available static markers" -msgstr "" +msgstr "Marcadores estáticos disponíveis" #: ../../howto/instrumentation.rst:277 msgid "" "This marker indicates that execution of a Python function has begun. It is " "only triggered for pure-Python (bytecode) functions." msgstr "" +"Este marcador indica que a execução de uma função Python começou. Ele é " +"acionado somente para funções Python puro (bytecode)." #: ../../howto/instrumentation.rst:280 msgid "" @@ -223,22 +614,29 @@ msgid "" "tracing script as positional arguments, which must be accessed using " "``$arg1``, ``$arg2``, ``$arg3``:" msgstr "" +"O nome do arquivo, o nome da função e o número da linha são fornecidos de " +"volta ao script de rastreamento como argumentos posicionais, que devem ser " +"acessados usando ``$arg1``, ``$arg2``, ``$arg3``:" #: ../../howto/instrumentation.rst:284 msgid "" "``$arg1`` : ``(const char *)`` filename, accessible using " "``user_string($arg1)``" msgstr "" +"``$arg1`` : nome de arquivo como ``(const char *)``, acessível usando " +"``user_string($arg1)``" #: ../../howto/instrumentation.rst:286 msgid "" "``$arg2`` : ``(const char *)`` function name, accessible using " "``user_string($arg2)``" msgstr "" +"``$arg2`` : nome da função como ``(const char *)``, acessível usando " +"``user_string($arg2)``" #: ../../howto/instrumentation.rst:289 msgid "``$arg3`` : ``int`` line number" -msgstr "" +msgstr "``$arg3`` : número da linha como ``int``" #: ../../howto/instrumentation.rst:293 msgid "" @@ -246,10 +644,13 @@ msgid "" "that execution of a Python function has ended (either via ``return``, or via " "an exception). It is only triggered for pure-Python (bytecode) functions." msgstr "" +"Este marcador é o inverso de :c:func:`!function__entry`, e indica que a " +"execução de uma função Python terminou (seja via ``return``, ou via uma " +"exceção). Ele é acionado somente para funções Python puro (bytecode)." #: ../../howto/instrumentation.rst:297 msgid "The arguments are the same as for :c:func:`!function__entry`" -msgstr "" +msgstr "Os argumentos são os mesmos de :c:func:`!function__entry`" #: ../../howto/instrumentation.rst:301 msgid "" @@ -257,34 +658,46 @@ msgid "" "equivalent of line-by-line tracing with a Python profiler. It is not " "triggered within C functions." msgstr "" +"Este marcador indica que uma linha Python está prestes a ser executada. É o " +"equivalente ao rastreamento linha por linha com um perfilador Python. Ele " +"não é acionado dentro de funções C." #: ../../howto/instrumentation.rst:305 msgid "The arguments are the same as for :c:func:`!function__entry`." -msgstr "" +msgstr "Os argumentos são os mesmos de :c:func:`!function__entry`." #: ../../howto/instrumentation.rst:309 msgid "" "Fires when the Python interpreter starts a garbage collection cycle. " -"``arg0`` is the generation to scan, like :func:`gc.collect()`." +"``arg0`` is the generation to scan, like :func:`gc.collect`." msgstr "" +"Dispara quando o interpretador Python inicia um ciclo de coleta de lixo. " +"``arg0`` é a geração a ser percurrida, como :func:`gc.collect`." #: ../../howto/instrumentation.rst:314 msgid "" "Fires when the Python interpreter finishes a garbage collection cycle. " "``arg0`` is the number of collected objects." msgstr "" +"Dispara quando o interpretador Python termina um ciclo de coleta de lixo. " +"``arg0`` é o número de objetos coletados." #: ../../howto/instrumentation.rst:319 msgid "" "Fires before :mod:`importlib` attempts to find and load the module. ``arg0`` " "is the module name." msgstr "" +"Dispara antes de :mod:`importlib` tentar encontrar e carregar o módulo. " +"``arg0`` é o nome do módulo." #: ../../howto/instrumentation.rst:326 msgid "" "Fires after :mod:`importlib`'s find_and_load function is called. ``arg0`` is " "the module name, ``arg1`` indicates if module was successfully loaded." msgstr "" +"Dispara após a função find_and_load do :mod:`importlib` ser chamada. " +"``arg0`` é o nome do módulo, ``arg1`` indica se o módulo foi carregado com " +"sucesso." #: ../../howto/instrumentation.rst:335 msgid "" @@ -292,10 +705,13 @@ msgid "" "the event name as C string, ``arg1`` is a :c:type:`PyObject` pointer to a " "tuple object." msgstr "" +"Dispara quando :func:`sys.audit` ou :c:func:`PySys_Audit` é chamada. " +"``arg0`` é o nome do evento como string C, ``arg1`` é um ponteiro :c:type:" +"`PyObject` para um objeto tupla." #: ../../howto/instrumentation.rst:343 msgid "SystemTap Tapsets" -msgstr "" +msgstr "Tapsets de SystemTap" #: ../../howto/instrumentation.rst:345 msgid "" @@ -303,22 +719,74 @@ msgid "" "\"tapset\": SystemTap's equivalent of a library, which hides some of the " "lower-level details of the static markers." msgstr "" +"A maneira mais avançada de usar a integração do SystemTap é usar um " +"\"tapset\": o equivalente do SystemTap a uma biblioteca, que oculta alguns " +"dos detalhes de nível inferior dos marcadores estáticos." #: ../../howto/instrumentation.rst:349 msgid "Here is a tapset file, based on a non-shared build of CPython:" msgstr "" +"Aqui está um arquivo tapset, baseado em uma construção não compartilhada do " +"CPython:" + +#: ../../howto/instrumentation.rst:351 +msgid "" +"/*\n" +" Provide a higher-level wrapping around the function__entry and\n" +" function__return markers:\n" +" \\*/\n" +"probe python.function.entry = process(\"python\").mark(\"function__entry\")\n" +"{\n" +" filename = user_string($arg1);\n" +" funcname = user_string($arg2);\n" +" lineno = $arg3;\n" +" frameptr = $arg4\n" +"}\n" +"probe python.function.return = process(\"python\")." +"mark(\"function__return\")\n" +"{\n" +" filename = user_string($arg1);\n" +" funcname = user_string($arg2);\n" +" lineno = $arg3;\n" +" frameptr = $arg4\n" +"}" +msgstr "" +"/*\n" +" Fornece um envólucro de mais alto nível em volta dos marcadores\n" +" function__entry e function__return:\n" +" \\*/\n" +"probe python.function.entry = process(\"python\").mark(\"function__entry\")\n" +"{\n" +" filename = user_string($arg1);\n" +" funcname = user_string($arg2);\n" +" lineno = $arg3;\n" +" frameptr = $arg4\n" +"}\n" +"probe python.function.return = process(\"python\")." +"mark(\"function__return\")\n" +"{\n" +" filename = user_string($arg1);\n" +" funcname = user_string($arg2);\n" +" lineno = $arg3;\n" +" frameptr = $arg4\n" +"}" #: ../../howto/instrumentation.rst:372 msgid "" "If this file is installed in SystemTap's tapset directory (e.g. ``/usr/share/" "systemtap/tapset``), then these additional probepoints become available:" msgstr "" +"Se este arquivo for instalado no diretório de tapsets do SystemTap (por " +"exemplo, ``/usr/share/systemtap/tapset``), estes pontos de sondagem " +"adicionais ficarão disponíveis:" #: ../../howto/instrumentation.rst:378 msgid "" "This probe point indicates that execution of a Python function has begun. It " "is only triggered for pure-Python (bytecode) functions." msgstr "" +"Este ponto de sondagem indica que a execução de uma função Python começou. " +"Ele é acionado somente para funções Python puro (bytecode)." #: ../../howto/instrumentation.rst:383 msgid "" @@ -327,6 +795,9 @@ msgid "" "``return``, or via an exception). It is only triggered for pure-Python " "(bytecode) functions." msgstr "" +"Este ponto de sondagem é o inverso de ``python.function.return``, e indica " +"que a execução de uma função Python terminou (seja via ``return``, ou via " +"uma exceção). Ele é acionado somente para funções Python puro (bytecode)." #: ../../howto/instrumentation.rst:390 msgid "Examples" @@ -338,6 +809,35 @@ msgid "" "example given above of tracing the Python function-call hierarchy, without " "needing to directly name the static markers:" msgstr "" +"Este script SystemTap usa o tapset acima para implementar de forma mais " +"limpa o exemplo dado acima de rastreamento da hierarquia de chamada de " +"função Python, sem precisar na diretamente" + +#: ../../howto/instrumentation.rst:395 +msgid "" +"probe python.function.entry\n" +"{\n" +" printf(\"%s => %s in %s:%d\\n\",\n" +" thread_indent(1), funcname, filename, lineno);\n" +"}\n" +"\n" +"probe python.function.return\n" +"{\n" +" printf(\"%s <= %s in %s:%d\\n\",\n" +" thread_indent(-1), funcname, filename, lineno);\n" +"}" +msgstr "" +"probe python.function.entry\n" +"{\n" +" printf(\"%s => %s in %s:%d\\n\",\n" +" thread_indent(1), funcname, filename, lineno);\n" +"}\n" +"\n" +"probe python.function.return\n" +"{\n" +" printf(\"%s <= %s in %s:%d\\n\",\n" +" thread_indent(-1), funcname, filename, lineno);\n" +"}" #: ../../howto/instrumentation.rst:410 msgid "" @@ -345,3 +845,46 @@ msgid "" "running CPython code, showing the top 20 most frequently entered bytecode " "frames, each second, across the whole system:" msgstr "" +"O script a seguir usa o tapset acima para fornecer uma visão geral de todo o " +"código CPython em execução, mostrando os 20 quadros de bytecode mais " +"frequentemente inseridos, a cada segundo, em todo o sistema:" + +#: ../../howto/instrumentation.rst:414 +msgid "" +"global fn_calls;\n" +"\n" +"probe python.function.entry\n" +"{\n" +" fn_calls[pid(), filename, funcname, lineno] += 1;\n" +"}\n" +"\n" +"probe timer.ms(1000) {\n" +" printf(\"\\033[2J\\033[1;1H\") /* clear screen \\*/\n" +" printf(\"%6s %80s %6s %30s %6s\\n\",\n" +" \"PID\", \"FILENAME\", \"LINE\", \"FUNCTION\", \"CALLS\")\n" +" foreach ([pid, filename, funcname, lineno] in fn_calls- limit 20) {\n" +" printf(\"%6d %80s %6d %30s %6d\\n\",\n" +" pid, filename, lineno, funcname,\n" +" fn_calls[pid, filename, funcname, lineno]);\n" +" }\n" +" delete fn_calls;\n" +"}" +msgstr "" +"global fn_calls;\n" +"\n" +"probe python.function.entry\n" +"{\n" +" fn_calls[pid(), filename, funcname, lineno] += 1;\n" +"}\n" +"\n" +"probe timer.ms(1000) {\n" +" printf(\"\\033[2J\\033[1;1H\") /* clear screen \\*/\n" +" printf(\"%6s %80s %6s %30s %6s\\n\",\n" +" \"PID\", \"FILENAME\", \"LINE\", \"FUNCTION\", \"CALLS\")\n" +" foreach ([pid, filename, funcname, lineno] in fn_calls- limit 20) {\n" +" printf(\"%6d %80s %6d %30s %6d\\n\",\n" +" pid, filename, lineno, funcname,\n" +" fn_calls[pid, filename, funcname, lineno]);\n" +" }\n" +" delete fn_calls;\n" +"}" diff --git a/howto/ipaddress.po b/howto/ipaddress.po index 3a33e45b2..a95d92716 100644 --- a/howto/ipaddress.po +++ b/howto/ipaddress.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Cauê Baasch de Souza , 2021 -# Misael borges , 2021 -# Hemílio Lauro , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:53+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -136,6 +131,18 @@ msgstr "" "Os endereços também podem ser criados diretamente a partir de números " "inteiros. Os valores que cabem em 32 bits são considerados endereços IPv4::" +#: ../../howto/ipaddress.rst:64 +msgid "" +">>> ipaddress.ip_address(3221225985)\n" +"IPv4Address('192.0.2.1')\n" +">>> ipaddress.ip_address(42540766411282592856903984951653826561)\n" +"IPv6Address('2001:db8::1')" +msgstr "" +">>> ipaddress.ip_address(3221225985)\n" +"IPv4Address('192.0.2.1')\n" +">>> ipaddress.ip_address(42540766411282592856903984951653826561)\n" +"IPv6Address('2001:db8::1')" + #: ../../howto/ipaddress.rst:69 msgid "" "To force the use of IPv4 or IPv6 addresses, the relevant classes can be " @@ -146,6 +153,22 @@ msgstr "" "invocadas diretamente. Isto é particularmente útil para forçar a criação de " "endereços IPv6 para números inteiros pequenos:" +#: ../../howto/ipaddress.rst:73 +msgid "" +">>> ipaddress.ip_address(1)\n" +"IPv4Address('0.0.0.1')\n" +">>> ipaddress.IPv4Address(1)\n" +"IPv4Address('0.0.0.1')\n" +">>> ipaddress.IPv6Address(1)\n" +"IPv6Address('::1')" +msgstr "" +">>> ipaddress.ip_address(1)\n" +"IPv4Address('0.0.0.1')\n" +">>> ipaddress.IPv4Address(1)\n" +"IPv4Address('0.0.0.1')\n" +">>> ipaddress.IPv6Address(1)\n" +"IPv6Address('::1')" + #: ../../howto/ipaddress.rst:82 msgid "Defining Networks" msgstr "Definindo redes" @@ -178,6 +201,18 @@ msgstr "" "Quanto aos endereços, é fornecida uma função de fábrica que determina " "automaticamente a versão correta do IP:" +#: ../../howto/ipaddress.rst:96 +msgid "" +">>> ipaddress.ip_network('192.0.2.0/24')\n" +"IPv4Network('192.0.2.0/24')\n" +">>> ipaddress.ip_network('2001:db8::0/96')\n" +"IPv6Network('2001:db8::/96')" +msgstr "" +">>> ipaddress.ip_network('192.0.2.0/24')\n" +"IPv4Network('192.0.2.0/24')\n" +">>> ipaddress.ip_network('2001:db8::0/96')\n" +"IPv6Network('2001:db8::/96')" + #: ../../howto/ipaddress.rst:101 msgid "" "Network objects cannot have any host bits set. The practical effect of this " @@ -204,6 +239,22 @@ msgstr "" "adicionais sejam forçados a zero, o sinalizador ``strict=False`` pode ser " "passada para o construtor::" +#: ../../howto/ipaddress.rst:112 +msgid "" +">>> ipaddress.ip_network('192.0.2.1/24')\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: 192.0.2.1/24 has host bits set\n" +">>> ipaddress.ip_network('192.0.2.1/24', strict=False)\n" +"IPv4Network('192.0.2.0/24')" +msgstr "" +">>> ipaddress.ip_network('192.0.2.1/24')\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: 192.0.2.1/24 has host bits set\n" +">>> ipaddress.ip_network('192.0.2.1/24', strict=False)\n" +"IPv4Network('192.0.2.0/24')" + #: ../../howto/ipaddress.rst:119 msgid "" "While the string form offers significantly more flexibility, networks can " @@ -217,6 +268,18 @@ msgstr "" "endereço único identificado pelo número inteiro, portanto o prefixo da rede " "inclui todo o endereço da rede::" +#: ../../howto/ipaddress.rst:124 +msgid "" +">>> ipaddress.ip_network(3221225984)\n" +"IPv4Network('192.0.2.0/32')\n" +">>> ipaddress.ip_network(42540766411282592856903984951653826560)\n" +"IPv6Network('2001:db8::/128')" +msgstr "" +">>> ipaddress.ip_network(3221225984)\n" +"IPv4Network('192.0.2.0/32')\n" +">>> ipaddress.ip_network(42540766411282592856903984951653826560)\n" +"IPv6Network('2001:db8::/128')" + #: ../../howto/ipaddress.rst:129 msgid "" "As with addresses, creation of a particular kind of network can be forced by " @@ -279,18 +342,92 @@ msgstr "" msgid "Extracting the IP version::" msgstr "Extraindo a versão do IP::" +#: ../../howto/ipaddress.rst:165 +msgid "" +">>> addr4 = ipaddress.ip_address('192.0.2.1')\n" +">>> addr6 = ipaddress.ip_address('2001:db8::1')\n" +">>> addr6.version\n" +"6\n" +">>> addr4.version\n" +"4" +msgstr "" +">>> addr4 = ipaddress.ip_address('192.0.2.1')\n" +">>> addr6 = ipaddress.ip_address('2001:db8::1')\n" +">>> addr6.version\n" +"6\n" +">>> addr4.version\n" +"4" + #: ../../howto/ipaddress.rst:172 msgid "Obtaining the network from an interface::" msgstr "Obtendo a rede de uma interface::" +#: ../../howto/ipaddress.rst:174 +msgid "" +">>> host4 = ipaddress.ip_interface('192.0.2.1/24')\n" +">>> host4.network\n" +"IPv4Network('192.0.2.0/24')\n" +">>> host6 = ipaddress.ip_interface('2001:db8::1/96')\n" +">>> host6.network\n" +"IPv6Network('2001:db8::/96')" +msgstr "" +">>> host4 = ipaddress.ip_interface('192.0.2.1/24')\n" +">>> host4.network\n" +"IPv4Network('192.0.2.0/24')\n" +">>> host6 = ipaddress.ip_interface('2001:db8::1/96')\n" +">>> host6.network\n" +"IPv6Network('2001:db8::/96')" + #: ../../howto/ipaddress.rst:181 msgid "Finding out how many individual addresses are in a network::" msgstr "Descobrindo quantos endereços individuais estão em uma rede::" +#: ../../howto/ipaddress.rst:183 +msgid "" +">>> net4 = ipaddress.ip_network('192.0.2.0/24')\n" +">>> net4.num_addresses\n" +"256\n" +">>> net6 = ipaddress.ip_network('2001:db8::0/96')\n" +">>> net6.num_addresses\n" +"4294967296" +msgstr "" +">>> net4 = ipaddress.ip_network('192.0.2.0/24')\n" +">>> net4.num_addresses\n" +"256\n" +">>> net6 = ipaddress.ip_network('2001:db8::0/96')\n" +">>> net6.num_addresses\n" +"4294967296" + #: ../../howto/ipaddress.rst:190 msgid "Iterating through the \"usable\" addresses on a network::" msgstr "Iterando através dos endereços \"utilizáveis\" em uma rede::" +#: ../../howto/ipaddress.rst:192 +msgid "" +">>> net4 = ipaddress.ip_network('192.0.2.0/24')\n" +">>> for x in net4.hosts():\n" +"... print(x)\n" +"192.0.2.1\n" +"192.0.2.2\n" +"192.0.2.3\n" +"192.0.2.4\n" +"...\n" +"192.0.2.252\n" +"192.0.2.253\n" +"192.0.2.254" +msgstr "" +">>> net4 = ipaddress.ip_network('192.0.2.0/24')\n" +">>> for x in net4.hosts():\n" +"... print(x)\n" +"192.0.2.1\n" +"192.0.2.2\n" +"192.0.2.3\n" +"192.0.2.4\n" +"...\n" +"192.0.2.252\n" +"192.0.2.253\n" +"192.0.2.254" + #: ../../howto/ipaddress.rst:205 msgid "" "Obtaining the netmask (i.e. set bits corresponding to the network prefix) or " @@ -304,6 +441,26 @@ msgstr "" msgid "Exploding or compressing the address::" msgstr "Explodindo ou compactando o endereço::" +#: ../../howto/ipaddress.rst:222 +msgid "" +">>> addr6.exploded\n" +"'2001:0db8:0000:0000:0000:0000:0000:0001'\n" +">>> addr6.compressed\n" +"'2001:db8::1'\n" +">>> net6.exploded\n" +"'2001:0db8:0000:0000:0000:0000:0000:0000/96'\n" +">>> net6.compressed\n" +"'2001:db8::/96'" +msgstr "" +">>> addr6.exploded\n" +"'2001:0db8:0000:0000:0000:0000:0000:0001'\n" +">>> addr6.compressed\n" +"'2001:db8::1'\n" +">>> net6.exploded\n" +"'2001:0db8:0000:0000:0000:0000:0000:0000/96'\n" +">>> net6.compressed\n" +"'2001:db8::/96'" + #: ../../howto/ipaddress.rst:231 msgid "" "While IPv4 doesn't support explosion or compression, the associated objects " @@ -319,23 +476,70 @@ msgstr "" #: ../../howto/ipaddress.rst:238 msgid "Networks as lists of Addresses" -msgstr "" +msgstr "Redes como listas de Addresses" #: ../../howto/ipaddress.rst:240 msgid "" "It's sometimes useful to treat networks as lists. This means it is possible " "to index them like this::" msgstr "" +"Às vezes é útil tratar redes como listas. Isso significa que é possível " +"indexá-las assim::" + +#: ../../howto/ipaddress.rst:243 +msgid "" +">>> net4[1]\n" +"IPv4Address('192.0.2.1')\n" +">>> net4[-1]\n" +"IPv4Address('192.0.2.255')\n" +">>> net6[1]\n" +"IPv6Address('2001:db8::1')\n" +">>> net6[-1]\n" +"IPv6Address('2001:db8::ffff:ffff')" +msgstr "" +">>> net4[1]\n" +"IPv4Address('192.0.2.1')\n" +">>> net4[-1]\n" +"IPv4Address('192.0.2.255')\n" +">>> net6[1]\n" +"IPv6Address('2001:db8::1')\n" +">>> net6[-1]\n" +"IPv6Address('2001:db8::ffff:ffff')" #: ../../howto/ipaddress.rst:253 msgid "" "It also means that network objects lend themselves to using the list " "membership test syntax like this::" msgstr "" +"Isso também significa que os objetos de rede se prestam ao uso da sintaxe de " +"teste de pertinência de lista como esta:" + +#: ../../howto/ipaddress.rst:256 +msgid "" +"if address in network:\n" +" # do something" +msgstr "" +"if endereço in rede:\n" +" # faz algo" #: ../../howto/ipaddress.rst:259 msgid "Containment testing is done efficiently based on the network prefix::" msgstr "" +"O teste de contenção é feito de forma eficiente com base no prefixo de rede::" + +#: ../../howto/ipaddress.rst:261 +msgid "" +">>> addr4 = ipaddress.ip_address('192.0.2.1')\n" +">>> addr4 in ipaddress.ip_network('192.0.2.0/24')\n" +"True\n" +">>> addr4 in ipaddress.ip_network('192.0.3.0/24')\n" +"False" +msgstr "" +">>> addr4 = ipaddress.ip_address('192.0.2.1')\n" +">>> addr4 in ipaddress.ip_network('192.0.2.0/24')\n" +"True\n" +">>> addr4 in ipaddress.ip_network('192.0.3.0/24')\n" +"False" #: ../../howto/ipaddress.rst:269 msgid "Comparisons" @@ -346,16 +550,28 @@ msgid "" ":mod:`ipaddress` provides some simple, hopefully intuitive ways to compare " "objects, where it makes sense::" msgstr "" +":mod:`ipaddress` fornece algumas maneiras simples e, esperançosamente, " +"intuitivas de comparar objetos, onde faz sentido::" + +#: ../../howto/ipaddress.rst:274 +msgid "" +">>> ipaddress.ip_address('192.0.2.1') < ipaddress.ip_address('192.0.2.2')\n" +"True" +msgstr "" +">>> ipaddress.ip_address('192.0.2.1') < ipaddress.ip_address('192.0.2.2')\n" +"True" #: ../../howto/ipaddress.rst:277 msgid "" "A :exc:`TypeError` exception is raised if you try to compare objects of " "different versions or different types." msgstr "" +"Uma exceção :exc:`TypeError` é levantada se você tentar comparar objetos de " +"versões ou tipos diferentes." #: ../../howto/ipaddress.rst:282 msgid "Using IP Addresses with other modules" -msgstr "" +msgstr "Usando endereços IP com outros módulos" #: ../../howto/ipaddress.rst:284 msgid "" @@ -363,10 +579,27 @@ msgid "" "accept objects from this module directly. Instead, they must be coerced to " "an integer or string that the other module will accept::" msgstr "" +"Outros módulos que usam endereços IP (como :mod:`socket`) geralmente não " +"aceitam objetos deste módulo diretamente. Em vez disso, eles devem ser " +"convertidos para um inteiro ou string que o outro módulo aceitará::" + +#: ../../howto/ipaddress.rst:288 +msgid "" +">>> addr4 = ipaddress.ip_address('192.0.2.1')\n" +">>> str(addr4)\n" +"'192.0.2.1'\n" +">>> int(addr4)\n" +"3221225985" +msgstr "" +">>> addr4 = ipaddress.ip_address('192.0.2.1')\n" +">>> str(addr4)\n" +"'192.0.2.1'\n" +">>> int(addr4)\n" +"3221225985" #: ../../howto/ipaddress.rst:296 msgid "Getting more detail when instance creation fails" -msgstr "" +msgstr "Obtendo mais detalhes quando a criação da instância falha" #: ../../howto/ipaddress.rst:298 msgid "" @@ -377,6 +610,12 @@ msgid "" "because it's necessary to know whether the value is *supposed* to be IPv4 or " "IPv6 in order to provide more detail on why it has been rejected." msgstr "" +"Ao criar objetos de endereço/rede/interface usando as funções de fábrica " +"agnósticas de versão, quaisquer erros serão relatados como :exc:`ValueError` " +"com uma mensagem de erro genérica que simplesmente diz que o valor passado " +"não foi reconhecido como um objeto daquele tipo. A falta de um erro " +"específico é porque é necessário saber se o valor *supõe* ser IPv4 ou IPv6 " +"para fornecer mais detalhes sobre o motivo de sua rejeição." #: ../../howto/ipaddress.rst:305 msgid "" @@ -386,12 +625,59 @@ msgid "" "`ipaddress.NetmaskValueError` to indicate exactly which part of the " "definition failed to parse correctly." msgstr "" +"Para dar suporte a casos de uso em que é útil ter acesso a esse detalhe " +"adicional, os construtores de classe individuais na verdade geram as " +"subclasses :exc:`ValueError` :exc:`ipaddress.AddressValueError` e :exc:" +"`ipaddress.NetmaskValueError` para indicar exatamente qual parte da " +"definição falhou ao ser analisada corretamente." #: ../../howto/ipaddress.rst:311 msgid "" "The error messages are significantly more detailed when using the class " "constructors directly. For example::" msgstr "" +"As mensagens de erro são significativamente mais detalhadas ao usar os " +"construtores de classe diretamente. Por exemplo::" + +#: ../../howto/ipaddress.rst:314 +msgid "" +">>> ipaddress.ip_address(\"192.168.0.256\")\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: '192.168.0.256' does not appear to be an IPv4 or IPv6 address\n" +">>> ipaddress.IPv4Address(\"192.168.0.256\")\n" +"Traceback (most recent call last):\n" +" ...\n" +"ipaddress.AddressValueError: Octet 256 (> 255) not permitted in " +"'192.168.0.256'\n" +"\n" +">>> ipaddress.ip_network(\"192.168.0.1/64\")\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: '192.168.0.1/64' does not appear to be an IPv4 or IPv6 network\n" +">>> ipaddress.IPv4Network(\"192.168.0.1/64\")\n" +"Traceback (most recent call last):\n" +" ...\n" +"ipaddress.NetmaskValueError: '64' is not a valid netmask" +msgstr "" +">>> ipaddress.ip_address(\"192.168.0.256\")\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: '192.168.0.256' does not appear to be an IPv4 or IPv6 address\n" +">>> ipaddress.IPv4Address(\"192.168.0.256\")\n" +"Traceback (most recent call last):\n" +" ...\n" +"ipaddress.AddressValueError: Octet 256 (> 255) not permitted in " +"'192.168.0.256'\n" +"\n" +">>> ipaddress.ip_network(\"192.168.0.1/64\")\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: '192.168.0.1/64' does not appear to be an IPv4 or IPv6 network\n" +">>> ipaddress.IPv4Network(\"192.168.0.1/64\")\n" +"Traceback (most recent call last):\n" +" ...\n" +"ipaddress.NetmaskValueError: '64' is not a valid netmask" #: ../../howto/ipaddress.rst:332 msgid "" @@ -399,3 +685,18 @@ msgid "" "their parent class, so if you're not concerned with the particular type of " "error, you can still write code like the following::" msgstr "" +"Entretanto, ambas as exceções específicas do módulo têm :exc:`ValueError` " +"como classe pai, então se você não estiver preocupado com o tipo específico " +"de erro, você ainda pode escrever código como o seguinte::" + +#: ../../howto/ipaddress.rst:336 +msgid "" +"try:\n" +" network = ipaddress.IPv4Network(address)\n" +"except ValueError:\n" +" print('address/netmask is invalid for IPv4:', address)" +msgstr "" +"try:\n" +" network = ipaddress.IPv4Network(address)\n" +"except ValueError:\n" +" print('endereço/máscara de rede é inválida para IPv4:', address)" diff --git a/howto/isolating-extensions.po b/howto/isolating-extensions.po index f54874afc..1c4bf895c 100644 --- a/howto/isolating-extensions.po +++ b/howto/isolating-extensions.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2022 -# Claudio Rogerio Carvalho Filho , 2022 -# Pedro Fonini, 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-21 14:14+0000\n" -"PO-Revision-Date: 2022-11-05 19:48+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -73,7 +70,7 @@ msgstr "" #: ../../howto/isolating-extensions.rst:31 msgid "Background" -msgstr "Informações preliminares" +msgstr "Contexto" #: ../../howto/isolating-extensions.rst:33 msgid "" @@ -215,6 +212,24 @@ msgstr "" "que vários objetos de módulo podem ser criados a partir de uma única " "biblioteca compartilhada. Por exemplo:" +#: ../../howto/isolating-extensions.rst:93 +msgid "" +">>> import sys\n" +">>> import binascii\n" +">>> old_binascii = binascii\n" +">>> del sys.modules['binascii']\n" +">>> import binascii # create a new module object\n" +">>> old_binascii == binascii\n" +"False" +msgstr "" +">>> import sys\n" +">>> import binascii\n" +">>> old_binascii = binascii\n" +">>> del sys.modules['binascii']\n" +">>> import binascii # cria um novo objeto do módulo\n" +">>> old_binascii == binascii\n" +"False" + #: ../../howto/isolating-extensions.rst:103 msgid "" "As a rule of thumb, the two modules should be completely independent. All " @@ -262,6 +277,30 @@ msgstr "" "``old_binascii.Error`` e ``binascii.Error`` são objetos separados. No código " "a seguir, a exceção *não* é capturada:" +#: ../../howto/isolating-extensions.rst:126 +msgid "" +">>> old_binascii.Error == binascii.Error\n" +"False\n" +">>> try:\n" +"... old_binascii.unhexlify(b'qwertyuiop')\n" +"... except binascii.Error:\n" +"... print('boo')\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +"binascii.Error: Non-hexadecimal digit found" +msgstr "" +">>> old_binascii.Error == binascii.Error\n" +"False\n" +">>> try:\n" +"... old_binascii.unhexlify(b'qwertyuiop')\n" +"... except binascii.Error:\n" +"... print('boo')\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +"binascii.Error: Non-hexadecimal digit found" + #: ../../howto/isolating-extensions.rst:139 msgid "" "This is expected. Notice that pure-Python modules behave the same way: it is " @@ -429,11 +468,44 @@ msgstr "" "seu módulo, you pode explicitamente torná-lo carregável somente uma vez por " "processo. Por exemplo::" -#: ../../howto/isolating-extensions.rst:234 +#: ../../howto/isolating-extensions.rst:218 +msgid "" +"// A process-wide flag\n" +"static int loaded = 0;\n" +"\n" +"// Mutex to provide thread safety (only needed for free-threaded Python)\n" +"static PyMutex modinit_mutex = {0};\n" +"\n" +"static int\n" +"exec_module(PyObject* module)\n" +"{\n" +" PyMutex_Lock(&modinit_mutex);\n" +" if (loaded) {\n" +" PyMutex_Unlock(&modinit_mutex);\n" +" PyErr_SetString(PyExc_ImportError,\n" +" \"cannot load module more than once per process\");\n" +" return -1;\n" +" }\n" +" loaded = 1;\n" +" PyMutex_Unlock(&modinit_mutex);\n" +" // ... rest of initialization\n" +"}" +msgstr "" + +#: ../../howto/isolating-extensions.rst:240 +msgid "" +"If your module's :c:member:`PyModuleDef.m_clear` function is able to prepare " +"for future re-initialization, it should clear the ``loaded`` flag. In this " +"case, your module won't support multiple instances existing *concurrently*, " +"but it will, for example, support being loaded after Python runtime shutdown " +"(:c:func:`Py_FinalizeEx`) and re-initialization (:c:func:`Py_Initialize`)." +msgstr "" + +#: ../../howto/isolating-extensions.rst:249 msgid "Module State Access from Functions" msgstr "Acesso ao estado de módulo a partir de funções" -#: ../../howto/isolating-extensions.rst:236 +#: ../../howto/isolating-extensions.rst:251 msgid "" "Accessing the state from module-level functions is straightforward. " "Functions get the module object as their first argument; for extracting the " @@ -443,7 +515,29 @@ msgstr "" "recebem o objeto de módulo como o primeiro argumento; para extrair o estado, " "você pode usar ``PyModule_GetState``::" -#: ../../howto/isolating-extensions.rst:251 +#: ../../howto/isolating-extensions.rst:255 +msgid "" +"static PyObject *\n" +"func(PyObject *module, PyObject *args)\n" +"{\n" +" my_struct *state = (my_struct*)PyModule_GetState(module);\n" +" if (state == NULL) {\n" +" return NULL;\n" +" }\n" +" // ... rest of logic\n" +"}" +msgstr "" +"static PyObject *\n" +"func(PyObject *module, PyObject *args)\n" +"{\n" +" my_struct *state = (my_struct*)PyModule_GetState(module);\n" +" if (state == NULL) {\n" +" return NULL;\n" +" }\n" +" // ... o resto da lógica\n" +"}" + +#: ../../howto/isolating-extensions.rst:266 msgid "" "``PyModule_GetState`` may return ``NULL`` without setting an exception if " "there is no module state, i.e. ``PyModuleDef.m_size`` was zero. In your own " @@ -454,11 +548,11 @@ msgstr "" "próprio módulo, você controla o ``m_size``, de forma que isso é fácil de " "prevenir." -#: ../../howto/isolating-extensions.rst:258 +#: ../../howto/isolating-extensions.rst:273 msgid "Heap Types" msgstr "Tipos no heap" -#: ../../howto/isolating-extensions.rst:260 +#: ../../howto/isolating-extensions.rst:275 msgid "" "Traditionally, types defined in C code are *static*; that is, ``static " "PyTypeObject`` structures defined directly in code and initialized using " @@ -468,7 +562,7 @@ msgstr "" "``static PyTypeObject`` definidas diretamente em código e inicializadas " "usando ``PyType_Ready()``." -#: ../../howto/isolating-extensions.rst:264 +#: ../../howto/isolating-extensions.rst:279 msgid "" "Such types are necessarily shared across the process. Sharing them between " "module objects requires paying attention to any state they own or access. To " @@ -481,7 +575,7 @@ msgstr "" "são imutáveis a nível do Python: por exemplo, você não pode atribuir ``str." "meuatributo = 123``." -#: ../../howto/isolating-extensions.rst:270 +#: ../../howto/isolating-extensions.rst:285 msgid "" "Sharing truly immutable objects between interpreters is fine, as long as " "they don't provide access to mutable objects. However, in CPython, every " @@ -498,7 +592,7 @@ msgstr "" "objeto Python entre interpretadores depende implicitamente do atual GIL do " "CPython (que é global a nível de processo)." -#: ../../howto/isolating-extensions.rst:277 +#: ../../howto/isolating-extensions.rst:292 msgid "" "Because they are immutable and process-global, static types cannot access " "\"their\" module state. If any method of such a type requires access to " @@ -512,16 +606,16 @@ msgstr "" "heap*, ou, abreviando, *tipo no heap*. Tipos no heap correspondem mais " "fielmente a classes criadas pela instrução ``class`` do Python." -#: ../../howto/isolating-extensions.rst:284 +#: ../../howto/isolating-extensions.rst:299 msgid "For new modules, using heap types by default is a good rule of thumb." msgstr "" "Para módulos novos, usar tipos no heap por padrão é uma boa regra geral." -#: ../../howto/isolating-extensions.rst:288 +#: ../../howto/isolating-extensions.rst:303 msgid "Changing Static Types to Heap Types" msgstr "Mudando tipos estáticos para tipos no heap" -#: ../../howto/isolating-extensions.rst:290 +#: ../../howto/isolating-extensions.rst:305 msgid "" "Static types can be converted to heap types, but note that the heap type API " "was not designed for \"lossless\" conversion from static types—that is, " @@ -538,7 +632,7 @@ msgstr "" "é serializável em pickle ou não, ou slots herdados). Sempre teste os " "detalhes que são importantes para você." -#: ../../howto/isolating-extensions.rst:299 +#: ../../howto/isolating-extensions.rst:314 msgid "" "Watch out for the following two points in particular (but note that this is " "not a comprehensive list):" @@ -546,7 +640,7 @@ msgstr "" "Fique atento em particular aos dois pontos a seguir (mas note the esta não é " "uma lista completa):" -#: ../../howto/isolating-extensions.rst:302 +#: ../../howto/isolating-extensions.rst:317 msgid "" "Unlike static types, heap type objects are mutable by default. Use the :c:" "macro:`Py_TPFLAGS_IMMUTABLETYPE` flag to prevent mutability." @@ -555,7 +649,7 @@ msgstr "" "o sinalizador :c:macro:`Py_TPFLAGS_IMMUTABLETYPE` para impedir a " "mutabilidade." -#: ../../howto/isolating-extensions.rst:304 +#: ../../howto/isolating-extensions.rst:319 msgid "" "Heap types inherit :c:member:`~PyTypeObject.tp_new` by default, so it may " "become possible to instantiate them from Python code. You can prevent this " @@ -565,11 +659,11 @@ msgstr "" "eles podem passar a ser instanciáveis a partir de código Python. Você pode " "impedir isso com o sinalizador :c:macro:`Py_TPFLAGS_DISALLOW_INSTANTIATION`." -#: ../../howto/isolating-extensions.rst:310 +#: ../../howto/isolating-extensions.rst:325 msgid "Defining Heap Types" msgstr "Definindo tipos no heap" -#: ../../howto/isolating-extensions.rst:312 +#: ../../howto/isolating-extensions.rst:327 msgid "" "Heap types can be created by filling a :c:struct:`PyType_Spec` structure, a " "description or \"blueprint\" of a class, and calling :c:func:" @@ -579,7 +673,7 @@ msgstr "" "`PyType_Spec`, uma descrição ou \"diagrama\" de uma classe, e chamando :c:" "func:`PyType_FromModuleAndSpec` para construir um novo objeto classe." -#: ../../howto/isolating-extensions.rst:317 +#: ../../howto/isolating-extensions.rst:332 msgid "" "Other functions, like :c:func:`PyType_FromSpec`, can also create heap types, " "but :c:func:`PyType_FromModuleAndSpec` associates the module with the class, " @@ -589,7 +683,7 @@ msgstr "" "heap, mas :c:func:`PyType_FromModuleAndSpec` associa a classe ao módulo, " "permitindo acesso ao estado do módulo a partir dos métodos." -#: ../../howto/isolating-extensions.rst:321 +#: ../../howto/isolating-extensions.rst:336 msgid "" "The class should generally be stored in *both* the module state (for safe " "access from C) and the module's ``__dict__`` (for access from Python code)." @@ -598,11 +692,11 @@ msgstr "" "seguro a partir do C) *quanto* no ``__dict__`` do módulo (para acesso a " "partir de código Python)." -#: ../../howto/isolating-extensions.rst:327 +#: ../../howto/isolating-extensions.rst:342 msgid "Garbage-Collection Protocol" msgstr "Protocolo de recolhimento de lixo" -#: ../../howto/isolating-extensions.rst:329 +#: ../../howto/isolating-extensions.rst:344 msgid "" "Instances of heap types hold a reference to their type. This ensures that " "the type isn't destroyed before all its instances are, but may result in " @@ -613,7 +707,7 @@ msgstr "" "pode resultar em ciclos de referência que precisam ser quebrados pelo " "coletor de lixo." -#: ../../howto/isolating-extensions.rst:334 +#: ../../howto/isolating-extensions.rst:349 msgid "" "To avoid memory leaks, instances of heap types must implement the garbage " "collection protocol. That is, heap types should:" @@ -621,11 +715,11 @@ msgstr "" "Para evitar vazamentos de memória, instâncias de tipos no heap precisam " "implementar o protocolo de recolhimento de lixo. Isto é, tipos no heap devem:" -#: ../../howto/isolating-extensions.rst:338 +#: ../../howto/isolating-extensions.rst:353 msgid "Have the :c:macro:`Py_TPFLAGS_HAVE_GC` flag." msgstr "Ter o sinalizador :c:macro:`Py_TPFLAGS_HAVE_GC`." -#: ../../howto/isolating-extensions.rst:339 +#: ../../howto/isolating-extensions.rst:354 msgid "" "Define a traverse function using ``Py_tp_traverse``, which visits the type " "(e.g. using ``Py_VISIT(Py_TYPE(self))``)." @@ -633,15 +727,15 @@ msgstr "" "Definir uma função de travessia usando ``Py_tp_traverse``, que visita o tipo " "(por exemplo, usando ``Py_VISIT(Py_TYPE(self))``)." -#: ../../howto/isolating-extensions.rst:342 +#: ../../howto/isolating-extensions.rst:357 msgid "" -"Please refer to the the documentation of :c:macro:`Py_TPFLAGS_HAVE_GC` and :" -"c:member:`~PyTypeObject.tp_traverse` for additional considerations." +"Please refer to the documentation of :c:macro:`Py_TPFLAGS_HAVE_GC` and :c:" +"member:`~PyTypeObject.tp_traverse` for additional considerations." msgstr "" -"Por favor veja as documentações de :c:macro:`Py_TPFLAGS_HAVE_GC` e de :c:" +"Por favor, veja a documentação de :c:macro:`Py_TPFLAGS_HAVE_GC` e de :c:" "member:`~PyTypeObject.tp_traverse` para considerações adicionais." -#: ../../howto/isolating-extensions.rst:346 +#: ../../howto/isolating-extensions.rst:361 msgid "" "The API for defining heap types grew organically, leaving it somewhat " "awkward to use in its current state. The following sections will guide you " @@ -651,11 +745,11 @@ msgstr "" "status quo no qual usá-la pode ser um pouco confuso. As seções a seguir vão " "lhe guiar pelos problemas mais comuns." -#: ../../howto/isolating-extensions.rst:352 +#: ../../howto/isolating-extensions.rst:367 msgid "``tp_traverse`` in Python 3.8 and lower" msgstr "``tp_traverse`` no Python 3.8 e anteriores" -#: ../../howto/isolating-extensions.rst:354 +#: ../../howto/isolating-extensions.rst:369 msgid "" "The requirement to visit the type from ``tp_traverse`` was added in Python " "3.9. If you support Python 3.8 and lower, the traverse function must *not* " @@ -665,7 +759,25 @@ msgstr "" "3.9. Se você suporta Python 3.8 e anteriores, a função de travessia *não* " "deve visitar o tipo, de forma que ela precisa ser mais complicada::" -#: ../../howto/isolating-extensions.rst:366 +#: ../../howto/isolating-extensions.rst:373 +msgid "" +"static int my_traverse(PyObject *self, visitproc visit, void *arg)\n" +"{\n" +" if (Py_Version >= 0x03090000) {\n" +" Py_VISIT(Py_TYPE(self));\n" +" }\n" +" return 0;\n" +"}" +msgstr "" +"static int my_traverse(PyObject *self, visitproc visit, void *arg)\n" +"{\n" +" if (Py_Version >= 0x03090000) {\n" +" Py_VISIT(Py_TYPE(self));\n" +" }\n" +" return 0;\n" +"}" + +#: ../../howto/isolating-extensions.rst:381 msgid "" "Unfortunately, :c:data:`Py_Version` was only added in Python 3.11. As a " "replacement, use:" @@ -673,11 +785,11 @@ msgstr "" "Infelizmente, o símbolo :c:data:`Py_Version` foi adicionado somente no " "Python 3.11. Para substituí-lo, use::" -#: ../../howto/isolating-extensions.rst:369 +#: ../../howto/isolating-extensions.rst:384 msgid ":c:macro:`PY_VERSION_HEX`, if not using the stable ABI, or" msgstr ":c:macro:`PY_VERSION_HEX`, caso não esteja usando a ABI estável, ou" -#: ../../howto/isolating-extensions.rst:370 +#: ../../howto/isolating-extensions.rst:385 msgid "" ":py:data:`sys.version_info` (via :c:func:`PySys_GetObject` and :c:func:" "`PyArg_ParseTuple`)." @@ -685,11 +797,11 @@ msgstr "" ":py:data:`sys.version_info` (via :c:func:`PySys_GetObject` e :c:func:" "`PyArg_ParseTuple`)." -#: ../../howto/isolating-extensions.rst:375 +#: ../../howto/isolating-extensions.rst:390 msgid "Delegating ``tp_traverse``" msgstr "Delegando a função ``tp_traverse``" -#: ../../howto/isolating-extensions.rst:377 +#: ../../howto/isolating-extensions.rst:392 msgid "" "If your traverse function delegates to the :c:member:`~PyTypeObject." "tp_traverse` of its base class (or another type), ensure that " @@ -701,16 +813,38 @@ msgstr "" "``Py_TYPE(self)`` seja visitado apenas uma vez. Observe que somente tipos no " "heap devem visitar o tipo em ``tp_traverse``." -#: ../../howto/isolating-extensions.rst:382 +#: ../../howto/isolating-extensions.rst:397 msgid "For example, if your traverse function includes::" msgstr "Por exemplo, se a sua função de travessia incluir::" -#: ../../howto/isolating-extensions.rst:386 +#: ../../howto/isolating-extensions.rst:399 +msgid "base->tp_traverse(self, visit, arg)" +msgstr "base->tp_traverse(self, visit, arg)" + +#: ../../howto/isolating-extensions.rst:401 msgid "...and ``base`` may be a static type, then it should also include::" msgstr "" "...e ``base`` puder ser um tipo estático, então ela também precisa incluir::" -#: ../../howto/isolating-extensions.rst:396 +#: ../../howto/isolating-extensions.rst:403 +msgid "" +"if (base->tp_flags & Py_TPFLAGS_HEAPTYPE) {\n" +" // a heap type's tp_traverse already visited Py_TYPE(self)\n" +"} else {\n" +" if (Py_Version >= 0x03090000) {\n" +" Py_VISIT(Py_TYPE(self));\n" +" }\n" +"}" +msgstr "" +"if (base->tp_flags & Py_TPFLAGS_HEAPTYPE) {\n" +" // uma tp_traverse do tipo heap já visitou Py_TYPE(self)\n" +"} else {\n" +" if (Py_Version >= 0x03090000) {\n" +" Py_VISIT(Py_TYPE(self));\n" +" }\n" +"}" + +#: ../../howto/isolating-extensions.rst:411 msgid "" "It is not necessary to handle the type's reference count in :c:member:" "`~PyTypeObject.tp_new` and :c:member:`~PyTypeObject.tp_clear`." @@ -718,11 +852,11 @@ msgstr "" "Não é necessário mexer na contagem de referências do tipo em :c:member:" "`~PyTypeObject.tp_new` e :c:member:`~PyTypeObject.tp_clear`." -#: ../../howto/isolating-extensions.rst:401 +#: ../../howto/isolating-extensions.rst:416 msgid "Defining ``tp_dealloc``" msgstr "Definindo ``tp_dealloc``" -#: ../../howto/isolating-extensions.rst:403 +#: ../../howto/isolating-extensions.rst:418 msgid "" "If your type has a custom :c:member:`~PyTypeObject.tp_dealloc` function, it " "needs to:" @@ -730,18 +864,18 @@ msgstr "" "Se o seu tipo tem uma função :c:member:`~PyTypeObject.tp_dealloc` " "customizada, ele precisa:" -#: ../../howto/isolating-extensions.rst:406 +#: ../../howto/isolating-extensions.rst:421 msgid "" "call :c:func:`PyObject_GC_UnTrack` before any fields are invalidated, and" msgstr "" "chamar :c:func:`PyObject_GC_UnTrack` antes que quaisquer campos sejam " "invalidados, e" -#: ../../howto/isolating-extensions.rst:407 +#: ../../howto/isolating-extensions.rst:422 msgid "decrement the reference count of the type." msgstr "decrementar o contador de referências do tipo." -#: ../../howto/isolating-extensions.rst:409 +#: ../../howto/isolating-extensions.rst:424 msgid "" "To keep the type valid while ``tp_free`` is called, the type's refcount " "needs to be decremented *after* the instance is deallocated. For example::" @@ -749,7 +883,27 @@ msgstr "" "Para que o tipo permaneça válido durante o ``tp_free``, o refcount do tipo " "precisa ser decrementado *depois* de a instância ser liberada. Por exemplo::" -#: ../../howto/isolating-extensions.rst:421 +#: ../../howto/isolating-extensions.rst:427 +msgid "" +"static void my_dealloc(PyObject *self)\n" +"{\n" +" PyObject_GC_UnTrack(self);\n" +" ...\n" +" PyTypeObject *type = Py_TYPE(self);\n" +" type->tp_free(self);\n" +" Py_DECREF(type);\n" +"}" +msgstr "" +"static void my_dealloc(PyObject *self)\n" +"{\n" +" PyObject_GC_UnTrack(self);\n" +" ...\n" +" PyTypeObject *type = Py_TYPE(self);\n" +" type->tp_free(self);\n" +" Py_DECREF(type);\n" +"}" + +#: ../../howto/isolating-extensions.rst:436 msgid "" "The default ``tp_dealloc`` function does this, so if your type does *not* " "override ``tp_dealloc`` you don't need to add it." @@ -757,11 +911,11 @@ msgstr "" "A função ``tp_dealloc`` padrão faz isso, de forma que se o seu tipo *não* a " "substitui você não precisa se preocupar." -#: ../../howto/isolating-extensions.rst:427 +#: ../../howto/isolating-extensions.rst:442 msgid "Not overriding ``tp_free``" msgstr "Evitar substituir ``tp_free``" -#: ../../howto/isolating-extensions.rst:429 +#: ../../howto/isolating-extensions.rst:444 msgid "" "The :c:member:`~PyTypeObject.tp_free` slot of a heap type must be set to :c:" "func:`PyObject_GC_Del`. This is the default; do not override it." @@ -769,21 +923,21 @@ msgstr "" "O slot :c:member:`~PyTypeObject.tp_free` de um tipo no heap deve ser :c:func:" "`PyObject_GC_Del`. Este é o padráo; não o substitua." -#: ../../howto/isolating-extensions.rst:435 +#: ../../howto/isolating-extensions.rst:450 msgid "Avoiding ``PyObject_New``" msgstr "Evitar ``PyObject_New``" -#: ../../howto/isolating-extensions.rst:437 +#: ../../howto/isolating-extensions.rst:452 msgid "GC-tracked objects need to be allocated using GC-aware functions." msgstr "" "Objetos rastreados pelo GC precisam ser alocados usando funções que " "reconheçam o GC." -#: ../../howto/isolating-extensions.rst:439 +#: ../../howto/isolating-extensions.rst:454 msgid "If you use use :c:func:`PyObject_New` or :c:func:`PyObject_NewVar`:" msgstr "Se você usaria :c:func:`PyObject_New` ou :c:func:`PyObject_NewVar`:" -#: ../../howto/isolating-extensions.rst:441 +#: ../../howto/isolating-extensions.rst:456 msgid "" "Get and call type's :c:member:`~PyTypeObject.tp_alloc` slot, if possible. " "That is, replace ``TYPE *o = PyObject_New(TYPE, typeobj)`` with::" @@ -791,7 +945,11 @@ msgstr "" "Se possível, chame o slot :c:member:`~PyTypeObject.tp_alloc` do tipo. Isto " "é, troque ``TYPE *o = PyObject_New(TYPE, typeobj)`` por::" -#: ../../howto/isolating-extensions.rst:446 +#: ../../howto/isolating-extensions.rst:459 +msgid "TYPE *o = typeobj->tp_alloc(typeobj, 0);" +msgstr "TYPE *o = typeobj->tp_alloc(typeobj, 0);" + +#: ../../howto/isolating-extensions.rst:461 msgid "" "Replace ``o = PyObject_NewVar(TYPE, typeobj, size)`` with the same, but use " "size instead of the 0." @@ -799,7 +957,7 @@ msgstr "" "No lugar de ``o = PyObject_NewVar(TYPE, typeobj, size)``, use também a forma " "acima, mas com ``size`` ao invés do ``0``." -#: ../../howto/isolating-extensions.rst:449 +#: ../../howto/isolating-extensions.rst:464 msgid "" "If the above is not possible (e.g. inside a custom ``tp_alloc``), call :c:" "func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar`::" @@ -808,11 +966,21 @@ msgstr "" "customizado), chame :c:func:`PyObject_GC_New` or :c:func:" "`PyObject_GC_NewVar`::" -#: ../../howto/isolating-extensions.rst:458 +#: ../../howto/isolating-extensions.rst:467 +msgid "" +"TYPE *o = PyObject_GC_New(TYPE, typeobj);\n" +"\n" +"TYPE *o = PyObject_GC_NewVar(TYPE, typeobj, size);" +msgstr "" +"TYPE *o = PyObject_GC_New(TYPE, typeobj);\n" +"\n" +"TYPE *o = PyObject_GC_NewVar(TYPE, typeobj, size);" + +#: ../../howto/isolating-extensions.rst:473 msgid "Module State Access from Classes" msgstr "Acessando o estado do módulo a partir de classes" -#: ../../howto/isolating-extensions.rst:460 +#: ../../howto/isolating-extensions.rst:475 msgid "" "If you have a type object defined with :c:func:`PyType_FromModuleAndSpec`, " "you can call :c:func:`PyType_GetModule` to get the associated module, and " @@ -822,7 +990,7 @@ msgstr "" "pode chamar :c:func:`PyType_GetModule` para acessar o módulo associado, e " "então :c:func:`PyModule_GetState` para acessar o estado do módulo." -#: ../../howto/isolating-extensions.rst:464 +#: ../../howto/isolating-extensions.rst:479 msgid "" "To save a some tedious error-handling boilerplate code, you can combine " "these two steps with :c:func:`PyType_GetModuleState`, resulting in::" @@ -830,11 +998,23 @@ msgstr "" "Para evitar o tedioso código de tratamento de erros de sempre, você pode " "combinar essas duas etapas com o :c:func:`PyType_GetModuleState` assim::" -#: ../../howto/isolating-extensions.rst:474 +#: ../../howto/isolating-extensions.rst:482 +msgid "" +"my_struct *state = (my_struct*)PyType_GetModuleState(type);\n" +"if (state == NULL) {\n" +" return NULL;\n" +"}" +msgstr "" +"my_struct *state = (my_struct*)PyType_GetModuleState(type);\n" +"if (state == NULL) {\n" +" return NULL;\n" +"}" + +#: ../../howto/isolating-extensions.rst:489 msgid "Module State Access from Regular Methods" msgstr "Acesso ao estado do módulo a partir de métodos regulares" -#: ../../howto/isolating-extensions.rst:476 +#: ../../howto/isolating-extensions.rst:491 msgid "" "Accessing the module-level state from methods of a class is somewhat more " "complicated, but is possible thanks to API introduced in Python 3.9. To get " @@ -846,7 +1026,7 @@ msgstr "" "Python 3.9. Para conseguir o estado, é necessário primeiro acessar a *classe " "definidora*, e então obter o estado do módulo a partir dela." -#: ../../howto/isolating-extensions.rst:481 +#: ../../howto/isolating-extensions.rst:496 msgid "" "The largest roadblock is getting *the class a method was defined in*, or " "that method's \"defining class\" for short. The defining class can have a " @@ -856,7 +1036,7 @@ msgstr "" "abreviando, a *classe definidora* desse método. A classe definidora pode " "guardar uma referência para o módulo do qual ela é parte." -#: ../../howto/isolating-extensions.rst:485 +#: ../../howto/isolating-extensions.rst:500 msgid "" "Do not confuse the defining class with ``Py_TYPE(self)``. If the method is " "called on a *subclass* of your type, ``Py_TYPE(self)`` will refer to that " @@ -867,7 +1047,7 @@ msgstr "" "referência àquela subclasse, a qual pode ter sido definida em um módulo " "diferente do seu." -#: ../../howto/isolating-extensions.rst:490 +#: ../../howto/isolating-extensions.rst:505 msgid "" "The following Python code can illustrate the concept. ``Base." "get_defining_class`` returns ``Base`` even if ``type(self) == Sub``:" @@ -875,7 +1055,29 @@ msgstr "" "O código Python a seguir ilustra esse conceito. ``Base.get_defining_class`` " "retorna ``Base`` mesmo quando ``type(self) == Sub``:" -#: ../../howto/isolating-extensions.rst:506 +#: ../../howto/isolating-extensions.rst:509 +msgid "" +"class Base:\n" +" def get_type_of_self(self):\n" +" return type(self)\n" +"\n" +" def get_defining_class(self):\n" +" return __class__\n" +"\n" +"class Sub(Base):\n" +" pass" +msgstr "" +"class Base:\n" +" def get_type_of_self(self):\n" +" return type(self)\n" +"\n" +" def get_defining_class(self):\n" +" return __class__\n" +"\n" +"class Sub(Base):\n" +" pass" + +#: ../../howto/isolating-extensions.rst:521 msgid "" "For a method to get its \"defining class\", it must use the :ref:" "`METH_METHOD | METH_FASTCALL | METH_KEYWORDS ` e a assinatura :c:" "type:`PyCMethod` correspondente:" -#: ../../howto/isolating-extensions.rst:518 +#: ../../howto/isolating-extensions.rst:526 +msgid "" +"PyObject *PyCMethod(\n" +" PyObject *self, // object the method was called on\n" +" PyTypeObject *defining_class, // defining class\n" +" PyObject *const *args, // C array of arguments\n" +" Py_ssize_t nargs, // length of \"args\"\n" +" PyObject *kwnames) // NULL, or dict of keyword arguments" +msgstr "" +"PyObject *PyCMethod(\n" +" PyObject *self, // objeto onde o módulo foi chamado\n" +" PyTypeObject *defining_class, // classe definidora\n" +" PyObject *const *args, // vetor C de argumentos\n" +" Py_ssize_t nargs, // comprimento de \"args\"\n" +" PyObject *kwnames) // NULL, ou dicionário de argumentos " +"nomeados" + +#: ../../howto/isolating-extensions.rst:533 msgid "" "Once you have the defining class, call :c:func:`PyType_GetModuleState` to " "get the state of its associated module." @@ -895,19 +1114,69 @@ msgstr "" "Uma vez que vc tem a classe definidora, chame :c:func:" "`PyType_GetModuleState` para obter o estado do módulo associado a ela." -#: ../../howto/isolating-extensions.rst:521 +#: ../../howto/isolating-extensions.rst:536 msgid "For example::" msgstr "Por exemplo::" -#: ../../howto/isolating-extensions.rst:549 +#: ../../howto/isolating-extensions.rst:538 +msgid "" +"static PyObject *\n" +"example_method(PyObject *self,\n" +" PyTypeObject *defining_class,\n" +" PyObject *const *args,\n" +" Py_ssize_t nargs,\n" +" PyObject *kwnames)\n" +"{\n" +" my_struct *state = (my_struct*)PyType_GetModuleState(defining_class);\n" +" if (state == NULL) {\n" +" return NULL;\n" +" }\n" +" ... // rest of logic\n" +"}\n" +"\n" +"PyDoc_STRVAR(example_method_doc, \"...\");\n" +"\n" +"static PyMethodDef my_methods[] = {\n" +" {\"example_method\",\n" +" (PyCFunction)(void(*)(void))example_method,\n" +" METH_METHOD|METH_FASTCALL|METH_KEYWORDS,\n" +" example_method_doc}\n" +" {NULL},\n" +"}" +msgstr "" +"static PyObject *\n" +"example_method(PyObject *self,\n" +" PyTypeObject *defining_class,\n" +" PyObject *const *args,\n" +" Py_ssize_t nargs,\n" +" PyObject *kwnames)\n" +"{\n" +" my_struct *state = (my_struct*)PyType_GetModuleState(defining_class);\n" +" if (state == NULL) {\n" +" return NULL;\n" +" }\n" +" ... // rest of logic\n" +"}\n" +"\n" +"PyDoc_STRVAR(example_method_doc, \"...\");\n" +"\n" +"static PyMethodDef my_methods[] = {\n" +" {\"example_method\",\n" +" (PyCFunction)(void(*)(void))example_method,\n" +" METH_METHOD|METH_FASTCALL|METH_KEYWORDS,\n" +" example_method_doc}\n" +" {NULL},\n" +"}" + +#: ../../howto/isolating-extensions.rst:564 msgid "Module State Access from Slot Methods, Getters and Setters" msgstr "Acesso ao estado do módulo a partir de métodos slot, getters e setters" -#: ../../howto/isolating-extensions.rst:553 +#: ../../howto/isolating-extensions.rst:568 msgid "This is new in Python 3.11." msgstr "Adicionado na versão 3.11" -#: ../../howto/isolating-extensions.rst:561 +#: ../../howto/isolating-extensions.rst:576 msgid "" "Slot methods—the fast C equivalents for special methods, such as :c:member:" "`~PyNumberMethods.nb_add` for :py:attr:`~object.__add__` or :c:member:" @@ -923,7 +1192,7 @@ msgstr "" "`PyCMethod`. O mesmo vale para getters e setters definidos com :c:type:" "`PyGetSetDef`." -#: ../../howto/isolating-extensions.rst:568 +#: ../../howto/isolating-extensions.rst:583 msgid "" "To access the module state in these cases, use the :c:func:" "`PyType_GetModuleByDef` function, and pass in the module definition. Once " @@ -933,7 +1202,21 @@ msgstr "" "`PyType_GetModuleByDef`, e passe a definição do módulo. Uma vez encontrado o " "módulo, chame :c:func:`PyModule_GetState` para obter o estado::" -#: ../../howto/isolating-extensions.rst:579 +#: ../../howto/isolating-extensions.rst:588 +msgid "" +"PyObject *module = PyType_GetModuleByDef(Py_TYPE(self), &module_def);\n" +"my_struct *state = (my_struct*)PyModule_GetState(module);\n" +"if (state == NULL) {\n" +" return NULL;\n" +"}" +msgstr "" +"PyObject *module = PyType_GetModuleByDef(Py_TYPE(self), &module_def);\n" +"my_struct *state = (my_struct*)PyModule_GetState(module);\n" +"if (state == NULL) {\n" +" return NULL;\n" +"}" + +#: ../../howto/isolating-extensions.rst:594 msgid "" ":c:func:`!PyType_GetModuleByDef` works by searching the :term:`method " "resolution order` (i.e. all superclasses) for the first superclass that has " @@ -943,7 +1226,7 @@ msgstr "" "`ordem de resolução de métodos` (isto é, todas as superclasses) a primeira " "superclasse que tem um módulo correspondente." -#: ../../howto/isolating-extensions.rst:585 +#: ../../howto/isolating-extensions.rst:600 msgid "" "In very exotic cases (inheritance chains spanning multiple modules created " "from the same definition), :c:func:`!PyType_GetModuleByDef` might not return " @@ -956,11 +1239,11 @@ msgstr "" "correta. De todo modo, essa função sempre vai retornar um módulo com a mesma " "definição, garantindo um layout de memória C compatível." -#: ../../howto/isolating-extensions.rst:593 +#: ../../howto/isolating-extensions.rst:608 msgid "Lifetime of the Module State" msgstr "Tempo de vida do estado do módulo" -#: ../../howto/isolating-extensions.rst:595 +#: ../../howto/isolating-extensions.rst:610 msgid "" "When a module object is garbage-collected, its module state is freed. For " "each pointer to (a part of) the module state, you must hold a reference to " @@ -970,7 +1253,7 @@ msgstr "" "liberado. Para cada ponteiro para o estado do módulo (ou uma parte dele), é " "necessário possuir uma referência ao objeto de módulo." -#: ../../howto/isolating-extensions.rst:599 +#: ../../howto/isolating-extensions.rst:614 msgid "" "Usually this is not an issue, because types created with :c:func:" "`PyType_FromModuleAndSpec`, and their instances, hold a reference to the " @@ -984,17 +1267,17 @@ msgstr "" "referências ao referenciar o estado do módulo a partir de outros lugares, " "como funções de retorno para bibliotecas externas." -#: ../../howto/isolating-extensions.rst:608 +#: ../../howto/isolating-extensions.rst:623 msgid "Open Issues" msgstr "Problemas em aberto" -#: ../../howto/isolating-extensions.rst:610 +#: ../../howto/isolating-extensions.rst:625 msgid "Several issues around per-module state and heap types are still open." msgstr "" "Vários problemas relacionados aos estados por módulo e aos tipos no heap " "ainda estão em aberto." -#: ../../howto/isolating-extensions.rst:612 +#: ../../howto/isolating-extensions.rst:627 msgid "" "Discussions about improving the situation are best held on the `capi-sig " "mailing list `__." -#: ../../howto/isolating-extensions.rst:617 +#: ../../howto/isolating-extensions.rst:632 msgid "Per-Class Scope" msgstr "Escopo por classe" -#: ../../howto/isolating-extensions.rst:619 +#: ../../howto/isolating-extensions.rst:634 msgid "" "It is currently (as of Python 3.11) not possible to attach state to " "individual *types* without relying on CPython implementation details (which " @@ -1020,11 +1303,11 @@ msgstr "" "podem mudar no futuro—talvez, ironicamente, para possibilitar uma solução " "adequada para o escopo por classe)." -#: ../../howto/isolating-extensions.rst:626 +#: ../../howto/isolating-extensions.rst:641 msgid "Lossless Conversion to Heap Types" msgstr "Conversão sem perdas para tipos no heap" -#: ../../howto/isolating-extensions.rst:628 +#: ../../howto/isolating-extensions.rst:643 msgid "" "The heap type API was not designed for \"lossless\" conversion from static " "types; that is, creating a type that works exactly like a given static type." diff --git a/howto/logging-cookbook.po b/howto/logging-cookbook.po index 56292974d..47989c3fa 100644 --- a/howto/logging-cookbook.po +++ b/howto/logging-cookbook.po @@ -1,34 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Katyanna Moura , 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2022 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 00:53+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../howto/logging-cookbook.rst:5 msgid "Logging Cookbook" -msgstr "Livro de Receitas do Logging" +msgstr "Livro de receitas do logging" #: ../../howto/logging-cookbook.rst:0 msgid "Author" @@ -44,6 +41,9 @@ msgid "" "found useful in the past. For links to tutorial and reference information, " "please see :ref:`cookbook-ref-links`." msgstr "" +"Esta página contém uma série de receitas relacionadas ao registro de " +"eventos, que foram considerados úteis no passado. Para obter links para " +"tutoriais e outras referências, veja :ref:`cookbook-ref-links`" #: ../../howto/logging-cookbook.rst:16 msgid "Using logging in multiple modules" @@ -60,38 +60,293 @@ msgid "" "logger calls to the child will pass up to the parent. Here is a main " "module::" msgstr "" +"Várias chamadas para ``logging.getLogger('someLogger')`` retorna a " +"referência para o mesmo objeto logger. Isso é verdadeiro não apenas dentro " +"do mesmo módulo, mas também entre módulo, desde que esteja no mesmo processo " +"do interpretador Python. Isso é verdadeiro para referências do mesmo objeto; " +"além disso, o código da aplicação pode definir e configurar um logger pai em " +"um módulo e criar (mas não configurar) um logger filho em um módulo " +"separado, e todas as chamadas de logger para o filho passarão para o pai. " +"Aqui está um módulo prinicipal::" + +#: ../../howto/logging-cookbook.rst:26 +msgid "" +"import logging\n" +"import auxiliary_module\n" +"\n" +"# create logger with 'spam_application'\n" +"logger = logging.getLogger('spam_application')\n" +"logger.setLevel(logging.DEBUG)\n" +"# create file handler which logs even debug messages\n" +"fh = logging.FileHandler('spam.log')\n" +"fh.setLevel(logging.DEBUG)\n" +"# create console handler with a higher log level\n" +"ch = logging.StreamHandler()\n" +"ch.setLevel(logging.ERROR)\n" +"# create formatter and add it to the handlers\n" +"formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - " +"%(message)s')\n" +"fh.setFormatter(formatter)\n" +"ch.setFormatter(formatter)\n" +"# add the handlers to the logger\n" +"logger.addHandler(fh)\n" +"logger.addHandler(ch)\n" +"\n" +"logger.info('creating an instance of auxiliary_module.Auxiliary')\n" +"a = auxiliary_module.Auxiliary()\n" +"logger.info('created an instance of auxiliary_module.Auxiliary')\n" +"logger.info('calling auxiliary_module.Auxiliary.do_something')\n" +"a.do_something()\n" +"logger.info('finished auxiliary_module.Auxiliary.do_something')\n" +"logger.info('calling auxiliary_module.some_function()')\n" +"auxiliary_module.some_function()\n" +"logger.info('done with auxiliary_module.some_function()')" +msgstr "" +"import logging\n" +"import auxiliary_module\n" +"\n" +"# cria objeto logger com 'spam_application'\n" +"logger = logging.getLogger('spam_application')\n" +"logger.setLevel(logging.DEBUG)\n" +"# cria manipulador de arquivo que registra até mesmo mensagens de debug\n" +"fh = logging.FileHandler('spam.log')\n" +"fh.setLevel(logging.DEBUG)\n" +"# cria manipulador de console com um nível de registro mais alto\n" +"ch = logging.StreamHandler()\n" +"ch.setLevel(logging.ERROR)\n" +"# cria formatador e adiciona aos manipuladores\n" +"formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - " +"%(message)s')\n" +"fh.setFormatter(formatter)\n" +"ch.setFormatter(formatter)\n" +"# adiciona os manipuladores ao logger\n" +"logger.addHandler(fh)\n" +"logger.addHandler(ch)\n" +"\n" +"logger.info('creating an instance of auxiliary_module.Auxiliary')\n" +"a = auxiliary_module.Auxiliary()\n" +"logger.info('created an instance of auxiliary_module.Auxiliary')\n" +"logger.info('calling auxiliary_module.Auxiliary.do_something')\n" +"a.do_something()\n" +"logger.info('finished auxiliary_module.Auxiliary.do_something')\n" +"logger.info('calling auxiliary_module.some_function()')\n" +"auxiliary_module.some_function()\n" +"logger.info('done with auxiliary_module.some_function()')" #: ../../howto/logging-cookbook.rst:56 msgid "Here is the auxiliary module::" -msgstr "" +msgstr "Aqui está o módulo auxiliar::" + +#: ../../howto/logging-cookbook.rst:58 +msgid "" +"import logging\n" +"\n" +"# create logger\n" +"module_logger = logging.getLogger('spam_application.auxiliary')\n" +"\n" +"class Auxiliary:\n" +" def __init__(self):\n" +" self.logger = logging.getLogger('spam_application.auxiliary." +"Auxiliary')\n" +" self.logger.info('creating an instance of Auxiliary')\n" +"\n" +" def do_something(self):\n" +" self.logger.info('doing something')\n" +" a = 1 + 1\n" +" self.logger.info('done doing something')\n" +"\n" +"def some_function():\n" +" module_logger.info('received a call to \"some_function\"')" +msgstr "" +"import logging\n" +"\n" +"# cria logger\n" +"module_logger = logging.getLogger('spam_application.auxiliary')\n" +"\n" +"class Auxiliary:\n" +" def __init__(self):\n" +" self.logger = logging.getLogger('spam_application.auxiliary." +"Auxiliary')\n" +" self.logger.info('creating an instance of Auxiliary')\n" +"\n" +" def do_something(self):\n" +" self.logger.info('doing something')\n" +" a = 1 + 1\n" +" self.logger.info('done doing something')\n" +"\n" +"def some_function():\n" +" module_logger.info('received a call to \"some_function\"')" #: ../../howto/logging-cookbook.rst:76 msgid "The output looks like this:" msgstr "O resultado deve ser algo assim:" +#: ../../howto/logging-cookbook.rst:78 +msgid "" +"2005-03-23 23:47:11,663 - spam_application - INFO -\n" +" creating an instance of auxiliary_module.Auxiliary\n" +"2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -\n" +" creating an instance of Auxiliary\n" +"2005-03-23 23:47:11,665 - spam_application - INFO -\n" +" created an instance of auxiliary_module.Auxiliary\n" +"2005-03-23 23:47:11,668 - spam_application - INFO -\n" +" calling auxiliary_module.Auxiliary.do_something\n" +"2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -\n" +" doing something\n" +"2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -\n" +" done doing something\n" +"2005-03-23 23:47:11,670 - spam_application - INFO -\n" +" finished auxiliary_module.Auxiliary.do_something\n" +"2005-03-23 23:47:11,671 - spam_application - INFO -\n" +" calling auxiliary_module.some_function()\n" +"2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -\n" +" received a call to 'some_function'\n" +"2005-03-23 23:47:11,673 - spam_application - INFO -\n" +" done with auxiliary_module.some_function()" +msgstr "" +"2005-03-23 23:47:11,663 - spam_application - INFO -\n" +" creating an instance of auxiliary_module.Auxiliary\n" +"2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -\n" +" creating an instance of Auxiliary\n" +"2005-03-23 23:47:11,665 - spam_application - INFO -\n" +" created an instance of auxiliary_module.Auxiliary\n" +"2005-03-23 23:47:11,668 - spam_application - INFO -\n" +" calling auxiliary_module.Auxiliary.do_something\n" +"2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -\n" +" doing something\n" +"2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -\n" +" done doing something\n" +"2005-03-23 23:47:11,670 - spam_application - INFO -\n" +" finished auxiliary_module.Auxiliary.do_something\n" +"2005-03-23 23:47:11,671 - spam_application - INFO -\n" +" calling auxiliary_module.some_function()\n" +"2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -\n" +" received a call to 'some_function'\n" +"2005-03-23 23:47:11,673 - spam_application - INFO -\n" +" done with auxiliary_module.some_function()" + #: ../../howto/logging-cookbook.rst:102 msgid "Logging from multiple threads" -msgstr "" +msgstr "Registro de eventos de várias threads" #: ../../howto/logging-cookbook.rst:104 msgid "" "Logging from multiple threads requires no special effort. The following " "example shows logging from the main (initial) thread and another thread::" msgstr "" +"O registro de eventos de várias threads não requer nenhum esforço especial. " +"O exemplo a seguir mostra o registro de eventos da thread principal " +"(inicial) thread e de outra thread::" + +#: ../../howto/logging-cookbook.rst:107 +msgid "" +"import logging\n" +"import threading\n" +"import time\n" +"\n" +"def worker(arg):\n" +" while not arg['stop']:\n" +" logging.debug('Hi from myfunc')\n" +" time.sleep(0.5)\n" +"\n" +"def main():\n" +" logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d " +"%(threadName)s %(message)s')\n" +" info = {'stop': False}\n" +" thread = threading.Thread(target=worker, args=(info,))\n" +" thread.start()\n" +" while True:\n" +" try:\n" +" logging.debug('Hello from main')\n" +" time.sleep(0.75)\n" +" except KeyboardInterrupt:\n" +" info['stop'] = True\n" +" break\n" +" thread.join()\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" +"import logging\n" +"import threading\n" +"import time\n" +"\n" +"def worker(arg):\n" +" while not arg['stop']:\n" +" logging.debug('Hi from myfunc')\n" +" time.sleep(0.5)\n" +"\n" +"def main():\n" +" logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d " +"%(threadName)s %(message)s')\n" +" info = {'stop': False}\n" +" thread = threading.Thread(target=worker, args=(info,))\n" +" thread.start()\n" +" while True:\n" +" try:\n" +" logging.debug('Hello from main')\n" +" time.sleep(0.75)\n" +" except KeyboardInterrupt:\n" +" info['stop'] = True\n" +" break\n" +" thread.join()\n" +"\n" +"if __name__ == '__main__':\n" +" main()" #: ../../howto/logging-cookbook.rst:133 msgid "When run, the script should print something like the following:" -msgstr "" +msgstr "Quando executado, o script deve exibir algo como o seguinte:" + +#: ../../howto/logging-cookbook.rst:135 +msgid "" +" 0 Thread-1 Hi from myfunc\n" +" 3 MainThread Hello from main\n" +" 505 Thread-1 Hi from myfunc\n" +" 755 MainThread Hello from main\n" +"1007 Thread-1 Hi from myfunc\n" +"1507 MainThread Hello from main\n" +"1508 Thread-1 Hi from myfunc\n" +"2010 Thread-1 Hi from myfunc\n" +"2258 MainThread Hello from main\n" +"2512 Thread-1 Hi from myfunc\n" +"3009 MainThread Hello from main\n" +"3013 Thread-1 Hi from myfunc\n" +"3515 Thread-1 Hi from myfunc\n" +"3761 MainThread Hello from main\n" +"4017 Thread-1 Hi from myfunc\n" +"4513 MainThread Hello from main\n" +"4518 Thread-1 Hi from myfunc" +msgstr "" +" 0 Thread-1 Hi from myfunc\n" +" 3 MainThread Hello from main\n" +" 505 Thread-1 Hi from myfunc\n" +" 755 MainThread Hello from main\n" +"1007 Thread-1 Hi from myfunc\n" +"1507 MainThread Hello from main\n" +"1508 Thread-1 Hi from myfunc\n" +"2010 Thread-1 Hi from myfunc\n" +"2258 MainThread Hello from main\n" +"2512 Thread-1 Hi from myfunc\n" +"3009 MainThread Hello from main\n" +"3013 Thread-1 Hi from myfunc\n" +"3515 Thread-1 Hi from myfunc\n" +"3761 MainThread Hello from main\n" +"4017 Thread-1 Hi from myfunc\n" +"4513 MainThread Hello from main\n" +"4518 Thread-1 Hi from myfunc" #: ../../howto/logging-cookbook.rst:155 msgid "" "This shows the logging output interspersed as one might expect. This " "approach works for more threads than shown here, of course." msgstr "" +"Isso mostra a saída de registro intercalada, como seria de se esperar. Essa " +"abordagem funciona para mais thread do que o mostrado aqui, é claro." #: ../../howto/logging-cookbook.rst:159 msgid "Multiple handlers and formatters" -msgstr "" +msgstr "Múltiplos manipuladores e formatadores" #: ../../howto/logging-cookbook.rst:161 msgid "" @@ -104,6 +359,68 @@ msgid "" "slight modification to the previous simple module-based configuration " "example::" msgstr "" +"Registradores (loggers) são objetos Python simples. O método :meth:`~Logger." +"addHandler` não tem cota mínima ou máxima para o número de manipuladores que " +"podem ser adicionados. Às vezes, é vantajoso para um aplicação registrar " +"todas as mensagens de todas as gravidades em um arquivo texto e, ao mesmo " +"tempo, registrar erro ou superior no console. Para definir isso, basta " +"configurar os manipuladores apropriados. As chamadas de registro no código " +"da aplicação permanecerão inalteradas. Aqui está uma pequena modificação no " +"exemplo anterior de configuração simples baseada em módulo::" + +#: ../../howto/logging-cookbook.rst:169 +msgid "" +"import logging\n" +"\n" +"logger = logging.getLogger('simple_example')\n" +"logger.setLevel(logging.DEBUG)\n" +"# create file handler which logs even debug messages\n" +"fh = logging.FileHandler('spam.log')\n" +"fh.setLevel(logging.DEBUG)\n" +"# create console handler with a higher log level\n" +"ch = logging.StreamHandler()\n" +"ch.setLevel(logging.ERROR)\n" +"# create formatter and add it to the handlers\n" +"formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - " +"%(message)s')\n" +"ch.setFormatter(formatter)\n" +"fh.setFormatter(formatter)\n" +"# add the handlers to logger\n" +"logger.addHandler(ch)\n" +"logger.addHandler(fh)\n" +"\n" +"# 'application' code\n" +"logger.debug('debug message')\n" +"logger.info('info message')\n" +"logger.warning('warn message')\n" +"logger.error('error message')\n" +"logger.critical('critical message')" +msgstr "" +"import logging\n" +"\n" +"logger = logging.getLogger('simple_example')\n" +"logger.setLevel(logging.DEBUG)\n" +"# cria manipulador de arquivo que regitra até mensagens de depuração\n" +"fh = logging.FileHandler('spam.log')\n" +"fh.setLevel(logging.DEBUG)\n" +"# cria manipulador de console com um nível de gravidade mais alto\n" +"ch = logging.StreamHandler()\n" +"ch.setLevel(logging.ERROR)\n" +"# cria formatador e adiciona-o ao manipulador\n" +"formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - " +"%(message)s')\n" +"ch.setFormatter(formatter)\n" +"fh.setFormatter(formatter)\n" +"# adiciona os manipuladores ao registrador\n" +"logger.addHandler(ch)\n" +"logger.addHandler(fh)\n" +"\n" +"# código da 'aplicação'\n" +"logger.debug('debug message')\n" +"logger.info('info message')\n" +"logger.warning('warn message')\n" +"logger.error('error message')\n" +"logger.critical('critical message')" #: ../../howto/logging-cookbook.rst:194 msgid "" @@ -111,6 +428,9 @@ msgid "" "All that changed was the addition and configuration of a new handler named " "*fh*." msgstr "" +"Observe que o código da 'aplicação' não se preocupa com vários " +"manipuladores. Tudo o que mudou foi a adição e a configuração de um novo " +"manipulador nomeado *fh*." #: ../../howto/logging-cookbook.rst:197 msgid "" @@ -123,6 +443,15 @@ msgid "" "to happen is to modify the severity level of the logger and/or handler to " "debug." msgstr "" +"A capacidade de criar novos manipuladores com filtros de severidade " +"superiores ou inferiores pode ser muito útil ao escrever e testar um " +"aplicação. Em vez de usar muitas instruções instrução para depuração, use " +"``logger.debug``: diferentemente da instrução print, que você terá de " +"excluir ou comentar posteriormente, a instrução logger.debug pode " +"permanecer intacta no código-fonte e ficar inativo até que você precise dela " +"novamente. Nesse momento, a única alteração que precisa ser feita é " +"modificar o nível de severidade do registrador e/ou manipulador para " +"depuração." #: ../../howto/logging-cookbook.rst:208 msgid "Logging to multiple destinations" @@ -137,14 +466,69 @@ msgid "" "console messages should not. Here's how you can achieve this::" msgstr "" +#: ../../howto/logging-cookbook.rst:216 +msgid "" +"import logging\n" +"\n" +"# set up logging to file - see previous section for more details\n" +"logging.basicConfig(level=logging.DEBUG,\n" +" format='%(asctime)s %(name)-12s %(levelname)-8s " +"%(message)s',\n" +" datefmt='%m-%d %H:%M',\n" +" filename='/tmp/myapp.log',\n" +" filemode='w')\n" +"# define a Handler which writes INFO messages or higher to the sys.stderr\n" +"console = logging.StreamHandler()\n" +"console.setLevel(logging.INFO)\n" +"# set a format which is simpler for console use\n" +"formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')\n" +"# tell the handler to use this format\n" +"console.setFormatter(formatter)\n" +"# add the handler to the root logger\n" +"logging.getLogger('').addHandler(console)\n" +"\n" +"# Now, we can log to the root logger, or any other logger. First the " +"root...\n" +"logging.info('Jackdaws love my big sphinx of quartz.')\n" +"\n" +"# Now, define a couple of other loggers which might represent areas in your\n" +"# application:\n" +"\n" +"logger1 = logging.getLogger('myapp.area1')\n" +"logger2 = logging.getLogger('myapp.area2')\n" +"\n" +"logger1.debug('Quick zephyrs blow, vexing daft Jim.')\n" +"logger1.info('How quickly daft jumping zebras vex.')\n" +"logger2.warning('Jail zesty vixen who grabbed pay from quack.')\n" +"logger2.error('The five boxing wizards jump quickly.')" +msgstr "" + #: ../../howto/logging-cookbook.rst:248 msgid "When you run this, on the console you will see" msgstr "" +#: ../../howto/logging-cookbook.rst:250 +msgid "" +"root : INFO Jackdaws love my big sphinx of quartz.\n" +"myapp.area1 : INFO How quickly daft jumping zebras vex.\n" +"myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.\n" +"myapp.area2 : ERROR The five boxing wizards jump quickly." +msgstr "" + #: ../../howto/logging-cookbook.rst:257 msgid "and in the file you will see something like" msgstr "" +#: ../../howto/logging-cookbook.rst:259 +msgid "" +"10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.\n" +"10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.\n" +"10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.\n" +"10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from " +"quack.\n" +"10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly." +msgstr "" + #: ../../howto/logging-cookbook.rst:267 msgid "" "As you can see, the DEBUG message only shows up in the file. The other " @@ -194,6 +578,47 @@ msgstr "" msgid "Suppose you configure logging with the following JSON:" msgstr "" +#: ../../howto/logging-cookbook.rst:295 +msgid "" +"{\n" +" \"version\": 1,\n" +" \"disable_existing_loggers\": false,\n" +" \"formatters\": {\n" +" \"simple\": {\n" +" \"format\": \"%(levelname)-8s - %(message)s\"\n" +" }\n" +" },\n" +" \"handlers\": {\n" +" \"stdout\": {\n" +" \"class\": \"logging.StreamHandler\",\n" +" \"level\": \"INFO\",\n" +" \"formatter\": \"simple\",\n" +" \"stream\": \"ext://sys.stdout\"\n" +" },\n" +" \"stderr\": {\n" +" \"class\": \"logging.StreamHandler\",\n" +" \"level\": \"ERROR\",\n" +" \"formatter\": \"simple\",\n" +" \"stream\": \"ext://sys.stderr\"\n" +" },\n" +" \"file\": {\n" +" \"class\": \"logging.FileHandler\",\n" +" \"formatter\": \"simple\",\n" +" \"filename\": \"app.log\",\n" +" \"mode\": \"w\"\n" +" }\n" +" },\n" +" \"root\": {\n" +" \"level\": \"DEBUG\",\n" +" \"handlers\": [\n" +" \"stderr\",\n" +" \"stdout\",\n" +" \"file\"\n" +" ]\n" +" }\n" +"}" +msgstr "" + #: ../../howto/logging-cookbook.rst:335 msgid "" "This configuration does *almost* what we want, except that ``sys.stdout`` " @@ -204,16 +629,52 @@ msgid "" "section parallel to ``formatters`` and ``handlers``:" msgstr "" +#: ../../howto/logging-cookbook.rst:341 +msgid "" +"{\n" +" \"filters\": {\n" +" \"warnings_and_below\": {\n" +" \"()\" : \"__main__.filter_maker\",\n" +" \"level\": \"WARNING\"\n" +" }\n" +" }\n" +"}" +msgstr "" + #: ../../howto/logging-cookbook.rst:352 msgid "and changing the section on the ``stdout`` handler to add it:" msgstr "" +#: ../../howto/logging-cookbook.rst:354 +msgid "" +"{\n" +" \"stdout\": {\n" +" \"class\": \"logging.StreamHandler\",\n" +" \"level\": \"INFO\",\n" +" \"formatter\": \"simple\",\n" +" \"stream\": \"ext://sys.stdout\",\n" +" \"filters\": [\"warnings_and_below\"]\n" +" }\n" +"}" +msgstr "" + #: ../../howto/logging-cookbook.rst:366 msgid "" "A filter is just a function, so we can define the ``filter_maker`` (a " "factory function) as follows:" msgstr "" +#: ../../howto/logging-cookbook.rst:369 +msgid "" +"def filter_maker(level):\n" +" level = getattr(logging, level)\n" +"\n" +" def filter(record):\n" +" return record.levelno <= level\n" +"\n" +" return filter" +msgstr "" + #: ../../howto/logging-cookbook.rst:379 msgid "" "This converts the string argument passed in to a numeric level, and returns " @@ -229,14 +690,110 @@ msgstr "" msgid "With the filter added, we can run ``main.py``, which in full is:" msgstr "" +#: ../../howto/logging-cookbook.rst:389 +msgid "" +"import json\n" +"import logging\n" +"import logging.config\n" +"\n" +"CONFIG = '''\n" +"{\n" +" \"version\": 1,\n" +" \"disable_existing_loggers\": false,\n" +" \"formatters\": {\n" +" \"simple\": {\n" +" \"format\": \"%(levelname)-8s - %(message)s\"\n" +" }\n" +" },\n" +" \"filters\": {\n" +" \"warnings_and_below\": {\n" +" \"()\" : \"__main__.filter_maker\",\n" +" \"level\": \"WARNING\"\n" +" }\n" +" },\n" +" \"handlers\": {\n" +" \"stdout\": {\n" +" \"class\": \"logging.StreamHandler\",\n" +" \"level\": \"INFO\",\n" +" \"formatter\": \"simple\",\n" +" \"stream\": \"ext://sys.stdout\",\n" +" \"filters\": [\"warnings_and_below\"]\n" +" },\n" +" \"stderr\": {\n" +" \"class\": \"logging.StreamHandler\",\n" +" \"level\": \"ERROR\",\n" +" \"formatter\": \"simple\",\n" +" \"stream\": \"ext://sys.stderr\"\n" +" },\n" +" \"file\": {\n" +" \"class\": \"logging.FileHandler\",\n" +" \"formatter\": \"simple\",\n" +" \"filename\": \"app.log\",\n" +" \"mode\": \"w\"\n" +" }\n" +" },\n" +" \"root\": {\n" +" \"level\": \"DEBUG\",\n" +" \"handlers\": [\n" +" \"stderr\",\n" +" \"stdout\",\n" +" \"file\"\n" +" ]\n" +" }\n" +"}\n" +"'''\n" +"\n" +"def filter_maker(level):\n" +" level = getattr(logging, level)\n" +"\n" +" def filter(record):\n" +" return record.levelno <= level\n" +"\n" +" return filter\n" +"\n" +"logging.config.dictConfig(json.loads(CONFIG))\n" +"logging.debug('A DEBUG message')\n" +"logging.info('An INFO message')\n" +"logging.warning('A WARNING message')\n" +"logging.error('An ERROR message')\n" +"logging.critical('A CRITICAL message')" +msgstr "" + #: ../../howto/logging-cookbook.rst:457 msgid "And after running it like this:" msgstr "" +#: ../../howto/logging-cookbook.rst:459 +msgid "python main.py 2>stderr.log >stdout.log" +msgstr "" + #: ../../howto/logging-cookbook.rst:463 msgid "We can see the results are as expected:" msgstr "" +#: ../../howto/logging-cookbook.rst:465 +msgid "" +"$ more *.log\n" +"::::::::::::::\n" +"app.log\n" +"::::::::::::::\n" +"DEBUG - A DEBUG message\n" +"INFO - An INFO message\n" +"WARNING - A WARNING message\n" +"ERROR - An ERROR message\n" +"CRITICAL - A CRITICAL message\n" +"::::::::::::::\n" +"stderr.log\n" +"::::::::::::::\n" +"ERROR - An ERROR message\n" +"CRITICAL - A CRITICAL message\n" +"::::::::::::::\n" +"stdout.log\n" +"::::::::::::::\n" +"INFO - An INFO message\n" +"WARNING - A WARNING message" +msgstr "" + #: ../../howto/logging-cookbook.rst:489 msgid "Configuration server example" msgstr "" @@ -245,6 +802,38 @@ msgstr "" msgid "Here is an example of a module using the logging configuration server::" msgstr "" +#: ../../howto/logging-cookbook.rst:493 +msgid "" +"import logging\n" +"import logging.config\n" +"import time\n" +"import os\n" +"\n" +"# read initial config file\n" +"logging.config.fileConfig('logging.conf')\n" +"\n" +"# create and start listener on port 9999\n" +"t = logging.config.listen(9999)\n" +"t.start()\n" +"\n" +"logger = logging.getLogger('simpleExample')\n" +"\n" +"try:\n" +" # loop through logging calls to see the difference\n" +" # new configurations make, until Ctrl+C is pressed\n" +" while True:\n" +" logger.debug('debug message')\n" +" logger.info('info message')\n" +" logger.warning('warn message')\n" +" logger.error('error message')\n" +" logger.critical('critical message')\n" +" time.sleep(5)\n" +"except KeyboardInterrupt:\n" +" # cleanup\n" +" logging.config.stopListening()\n" +" t.join()" +msgstr "" + #: ../../howto/logging-cookbook.rst:522 msgid "" "And here is a script that takes a filename and sends that file to the " @@ -252,6 +841,26 @@ msgid "" "configuration::" msgstr "" +#: ../../howto/logging-cookbook.rst:526 +msgid "" +"#!/usr/bin/env python\n" +"import socket, sys, struct\n" +"\n" +"with open(sys.argv[1], 'rb') as f:\n" +" data_to_send = f.read()\n" +"\n" +"HOST = 'localhost'\n" +"PORT = 9999\n" +"s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" +"print('connecting...')\n" +"s.connect((HOST, PORT))\n" +"print('sending config...')\n" +"s.send(struct.pack('>L', len(data_to_send)))\n" +"s.send(data_to_send)\n" +"s.close()\n" +"print('complete')" +msgstr "" + #: ../../howto/logging-cookbook.rst:547 msgid "Dealing with handlers that block" msgstr "" @@ -312,10 +921,33 @@ msgstr "" msgid "An example of using these two classes follows (imports omitted)::" msgstr "" +#: ../../howto/logging-cookbook.rst:589 +msgid "" +"que = queue.Queue(-1) # no limit on size\n" +"queue_handler = QueueHandler(que)\n" +"handler = logging.StreamHandler()\n" +"listener = QueueListener(que, handler)\n" +"root = logging.getLogger()\n" +"root.addHandler(queue_handler)\n" +"formatter = logging.Formatter('%(threadName)s: %(message)s')\n" +"handler.setFormatter(formatter)\n" +"listener.start()\n" +"# The log output will display the thread which generated\n" +"# the event (the main thread) rather than the internal\n" +"# thread which monitors the internal queue. This is what\n" +"# you want to happen.\n" +"root.warning('Look out!')\n" +"listener.stop()" +msgstr "" + #: ../../howto/logging-cookbook.rst:605 msgid "which, when run, will produce:" msgstr "" +#: ../../howto/logging-cookbook.rst:607 +msgid "MainThread: Look out!" +msgstr "" + #: ../../howto/logging-cookbook.rst:611 msgid "" "Although the earlier discussion wasn't specifically talking about async " @@ -350,18 +982,147 @@ msgid "" "`SocketHandler` instance to the root logger at the sending end::" msgstr "" +#: ../../howto/logging-cookbook.rst:638 +msgid "" +"import logging, logging.handlers\n" +"\n" +"rootLogger = logging.getLogger('')\n" +"rootLogger.setLevel(logging.DEBUG)\n" +"socketHandler = logging.handlers.SocketHandler('localhost',\n" +" logging.handlers.DEFAULT_TCP_LOGGING_PORT)\n" +"# don't bother with a formatter, since a socket handler sends the event as\n" +"# an unformatted pickle\n" +"rootLogger.addHandler(socketHandler)\n" +"\n" +"# Now, we can log to the root logger, or any other logger. First the " +"root...\n" +"logging.info('Jackdaws love my big sphinx of quartz.')\n" +"\n" +"# Now, define a couple of other loggers which might represent areas in your\n" +"# application:\n" +"\n" +"logger1 = logging.getLogger('myapp.area1')\n" +"logger2 = logging.getLogger('myapp.area2')\n" +"\n" +"logger1.debug('Quick zephyrs blow, vexing daft Jim.')\n" +"logger1.info('How quickly daft jumping zebras vex.')\n" +"logger2.warning('Jail zesty vixen who grabbed pay from quack.')\n" +"logger2.error('The five boxing wizards jump quickly.')" +msgstr "" + #: ../../howto/logging-cookbook.rst:662 msgid "" "At the receiving end, you can set up a receiver using the :mod:" "`socketserver` module. Here is a basic working example::" msgstr "" +#: ../../howto/logging-cookbook.rst:665 +msgid "" +"import pickle\n" +"import logging\n" +"import logging.handlers\n" +"import socketserver\n" +"import struct\n" +"\n" +"\n" +"class LogRecordStreamHandler(socketserver.StreamRequestHandler):\n" +" \"\"\"Handler for a streaming logging request.\n" +"\n" +" This basically logs the record using whatever logging policy is\n" +" configured locally.\n" +" \"\"\"\n" +"\n" +" def handle(self):\n" +" \"\"\"\n" +" Handle multiple requests - each expected to be a 4-byte length,\n" +" followed by the LogRecord in pickle format. Logs the record\n" +" according to whatever policy is configured locally.\n" +" \"\"\"\n" +" while True:\n" +" chunk = self.connection.recv(4)\n" +" if len(chunk) < 4:\n" +" break\n" +" slen = struct.unpack('>L', chunk)[0]\n" +" chunk = self.connection.recv(slen)\n" +" while len(chunk) < slen:\n" +" chunk = chunk + self.connection.recv(slen - len(chunk))\n" +" obj = self.unPickle(chunk)\n" +" record = logging.makeLogRecord(obj)\n" +" self.handleLogRecord(record)\n" +"\n" +" def unPickle(self, data):\n" +" return pickle.loads(data)\n" +"\n" +" def handleLogRecord(self, record):\n" +" # if a name is specified, we use the named logger rather than the " +"one\n" +" # implied by the record.\n" +" if self.server.logname is not None:\n" +" name = self.server.logname\n" +" else:\n" +" name = record.name\n" +" logger = logging.getLogger(name)\n" +" # N.B. EVERY record gets logged. This is because Logger.handle\n" +" # is normally called AFTER logger-level filtering. If you want\n" +" # to do filtering, do it at the client end to save wasting\n" +" # cycles and network bandwidth!\n" +" logger.handle(record)\n" +"\n" +"class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):\n" +" \"\"\"\n" +" Simple TCP socket-based logging receiver suitable for testing.\n" +" \"\"\"\n" +"\n" +" allow_reuse_address = True\n" +"\n" +" def __init__(self, host='localhost',\n" +" port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,\n" +" handler=LogRecordStreamHandler):\n" +" socketserver.ThreadingTCPServer.__init__(self, (host, port), " +"handler)\n" +" self.abort = 0\n" +" self.timeout = 1\n" +" self.logname = None\n" +"\n" +" def serve_until_stopped(self):\n" +" import select\n" +" abort = 0\n" +" while not abort:\n" +" rd, wr, ex = select.select([self.socket.fileno()],\n" +" [], [],\n" +" self.timeout)\n" +" if rd:\n" +" self.handle_request()\n" +" abort = self.abort\n" +"\n" +"def main():\n" +" logging.basicConfig(\n" +" format='%(relativeCreated)5d %(name)-15s %(levelname)-8s " +"%(message)s')\n" +" tcpserver = LogRecordSocketReceiver()\n" +" print('About to start TCP server...')\n" +" tcpserver.serve_until_stopped()\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" + #: ../../howto/logging-cookbook.rst:750 msgid "" "First run the server, and then the client. On the client side, nothing is " "printed on the console; on the server side, you should see something like:" msgstr "" +#: ../../howto/logging-cookbook.rst:753 +msgid "" +"About to start TCP server...\n" +" 59 root INFO Jackdaws love my big sphinx of quartz.\n" +" 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.\n" +" 69 myapp.area1 INFO How quickly daft jumping zebras vex.\n" +" 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.\n" +" 69 myapp.area2 ERROR The five boxing wizards jump quickly." +msgstr "" + #: ../../howto/logging-cookbook.rst:762 msgid "" "Note that there are some security issues with pickle in some scenarios. If " @@ -518,11 +1279,32 @@ msgid "" "configured ports clash with something else in your test environment." msgstr "" -#: ../../howto/logging-cookbook.rst:843 +#: ../../howto/logging-cookbook.rst:838 +msgid "" +"The default configuration uses a TCP socket on port 9020. You can use a Unix " +"Domain socket instead of a TCP socket by doing the following:" +msgstr "" + +#: ../../howto/logging-cookbook.rst:841 +msgid "" +"In :file:`listener.json`, add a ``socket`` key with the path to the domain " +"socket you want to use. If this key is present, the listener listens on the " +"corresponding domain socket and not on a TCP socket (the ``port`` key is " +"ignored)." +msgstr "" + +#: ../../howto/logging-cookbook.rst:846 +msgid "" +"In :file:`webapp.json`, change the socket handler configuration dictionary " +"so that the ``host`` value is the path to the domain socket, and set the " +"``port`` value to ``null``." +msgstr "" + +#: ../../howto/logging-cookbook.rst:856 msgid "Adding contextual information to your logging output" msgstr "" -#: ../../howto/logging-cookbook.rst:845 +#: ../../howto/logging-cookbook.rst:858 msgid "" "Sometimes you want logging output to contain contextual information in " "addition to the parameters passed to the logging call. For example, in a " @@ -538,11 +1320,11 @@ msgid "" "`Logger` instances becomes effectively unbounded." msgstr "" -#: ../../howto/logging-cookbook.rst:860 +#: ../../howto/logging-cookbook.rst:873 msgid "Using LoggerAdapters to impart contextual information" msgstr "" -#: ../../howto/logging-cookbook.rst:862 +#: ../../howto/logging-cookbook.rst:875 msgid "" "An easy way in which you can pass contextual information to be output along " "with logging event information is to use the :class:`LoggerAdapter` class. " @@ -553,7 +1335,7 @@ msgid "" "types of instances interchangeably." msgstr "" -#: ../../howto/logging-cookbook.rst:870 +#: ../../howto/logging-cookbook.rst:883 msgid "" "When you create an instance of :class:`LoggerAdapter`, you pass it a :class:" "`Logger` instance and a dict-like object which contains your contextual " @@ -564,7 +1346,18 @@ msgid "" "of :class:`LoggerAdapter`::" msgstr "" -#: ../../howto/logging-cookbook.rst:886 +#: ../../howto/logging-cookbook.rst:891 +msgid "" +"def debug(self, msg, /, *args, **kwargs):\n" +" \"\"\"\n" +" Delegate a debug call to the underlying logger, after adding\n" +" contextual information from this adapter instance.\n" +" \"\"\"\n" +" msg, kwargs = self.process(msg, kwargs)\n" +" self.logger.debug(msg, *args, **kwargs)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:899 msgid "" "The :meth:`~LoggerAdapter.process` method of :class:`LoggerAdapter` is where " "the contextual information is added to the logging output. It's passed the " @@ -577,7 +1370,7 @@ msgid "" "be silently overwritten." msgstr "" -#: ../../howto/logging-cookbook.rst:895 +#: ../../howto/logging-cookbook.rst:908 msgid "" "The advantage of using 'extra' is that the values in the dict-like object " "are merged into the :class:`LogRecord` instance's __dict__, allowing you to " @@ -588,21 +1381,38 @@ msgid "" "`~LoggerAdapter.process` to do what you need. Here is a simple example::" msgstr "" -#: ../../howto/logging-cookbook.rst:911 +#: ../../howto/logging-cookbook.rst:916 +msgid "" +"class CustomAdapter(logging.LoggerAdapter):\n" +" \"\"\"\n" +" This example adapter expects the passed in dict-like object to have a\n" +" 'connid' key, whose value in brackets is prepended to the log message.\n" +" \"\"\"\n" +" def process(self, msg, kwargs):\n" +" return '[%s] %s' % (self.extra['connid'], msg), kwargs" +msgstr "" + +#: ../../howto/logging-cookbook.rst:924 msgid "which you can use like this::" msgstr "" -#: ../../howto/logging-cookbook.rst:916 +#: ../../howto/logging-cookbook.rst:926 +msgid "" +"logger = logging.getLogger(__name__)\n" +"adapter = CustomAdapter(logger, {'connid': some_conn_id})" +msgstr "" + +#: ../../howto/logging-cookbook.rst:929 msgid "" "Then any events that you log to the adapter will have the value of " "``some_conn_id`` prepended to the log messages." msgstr "" -#: ../../howto/logging-cookbook.rst:920 +#: ../../howto/logging-cookbook.rst:933 msgid "Using objects other than dicts to pass contextual information" msgstr "" -#: ../../howto/logging-cookbook.rst:922 +#: ../../howto/logging-cookbook.rst:935 msgid "" "You don't need to pass an actual dict to a :class:`LoggerAdapter` - you " "could pass an instance of a class which implements ``__getitem__`` and " @@ -611,11 +1421,11 @@ msgid "" "would be constant)." msgstr "" -#: ../../howto/logging-cookbook.rst:931 +#: ../../howto/logging-cookbook.rst:944 msgid "Using Filters to impart contextual information" msgstr "" -#: ../../howto/logging-cookbook.rst:933 +#: ../../howto/logging-cookbook.rst:946 msgid "" "You can also add contextual information to log output using a user-defined :" "class:`Filter`. ``Filter`` instances are allowed to modify the " @@ -624,7 +1434,7 @@ msgid "" "class:`Formatter`." msgstr "" -#: ../../howto/logging-cookbook.rst:938 +#: ../../howto/logging-cookbook.rst:951 msgid "" "For example in a web application, the request being processed (or at least, " "the interesting parts of it) can be stored in a threadlocal (:class:" @@ -636,15 +1446,86 @@ msgid "" "an example script::" msgstr "" -#: ../../howto/logging-cookbook.rst:984 +#: ../../howto/logging-cookbook.rst:960 +msgid "" +"import logging\n" +"from random import choice\n" +"\n" +"class ContextFilter(logging.Filter):\n" +" \"\"\"\n" +" This is a filter which injects contextual information into the log.\n" +"\n" +" Rather than use actual contextual information, we just use random\n" +" data in this demo.\n" +" \"\"\"\n" +"\n" +" USERS = ['jim', 'fred', 'sheila']\n" +" IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']\n" +"\n" +" def filter(self, record):\n" +"\n" +" record.ip = choice(ContextFilter.IPS)\n" +" record.user = choice(ContextFilter.USERS)\n" +" return True\n" +"\n" +"if __name__ == '__main__':\n" +" levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, " +"logging.CRITICAL)\n" +" logging.basicConfig(level=logging.DEBUG,\n" +" format='%(asctime)-15s %(name)-5s %(levelname)-8s " +"IP: %(ip)-15s User: %(user)-8s %(message)s')\n" +" a1 = logging.getLogger('a.b.c')\n" +" a2 = logging.getLogger('d.e.f')\n" +"\n" +" f = ContextFilter()\n" +" a1.addFilter(f)\n" +" a2.addFilter(f)\n" +" a1.debug('A debug message')\n" +" a1.info('An info message with %s', 'some parameters')\n" +" for x in range(10):\n" +" lvl = choice(levels)\n" +" lvlname = logging.getLevelName(lvl)\n" +" a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, " +"'parameters')" +msgstr "" + +#: ../../howto/logging-cookbook.rst:997 msgid "which, when run, produces something like:" msgstr "" -#: ../../howto/logging-cookbook.rst:1002 +#: ../../howto/logging-cookbook.rst:999 +msgid "" +"2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A " +"debug message\n" +"2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An " +"info message with some parameters\n" +"2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A " +"message at CRITICAL level with 2 parameters\n" +"2010-09-06 22:38:15,300 d.e.f ERROR IP: 127.0.0.1 User: jim A " +"message at ERROR level with 2 parameters\n" +"2010-09-06 22:38:15,300 d.e.f DEBUG IP: 127.0.0.1 User: sheila A " +"message at DEBUG level with 2 parameters\n" +"2010-09-06 22:38:15,300 d.e.f ERROR IP: 123.231.231.123 User: fred A " +"message at ERROR level with 2 parameters\n" +"2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1 User: jim A " +"message at CRITICAL level with 2 parameters\n" +"2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A " +"message at CRITICAL level with 2 parameters\n" +"2010-09-06 22:38:15,300 d.e.f DEBUG IP: 192.168.0.1 User: jim A " +"message at DEBUG level with 2 parameters\n" +"2010-09-06 22:38:15,301 d.e.f ERROR IP: 127.0.0.1 User: sheila A " +"message at ERROR level with 2 parameters\n" +"2010-09-06 22:38:15,301 d.e.f DEBUG IP: 123.231.231.123 User: fred A " +"message at DEBUG level with 2 parameters\n" +"2010-09-06 22:38:15,301 d.e.f INFO IP: 123.231.231.123 User: fred A " +"message at INFO level with 2 parameters" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1015 msgid "Use of ``contextvars``" msgstr "" -#: ../../howto/logging-cookbook.rst:1004 +#: ../../howto/logging-cookbook.rst:1017 msgid "" "Since Python 3.7, the :mod:`contextvars` module has provided context-local " "storage which works for both :mod:`threading` and :mod:`asyncio` processing " @@ -654,7 +1535,7 @@ msgid "" "attributes handled by web applications." msgstr "" -#: ../../howto/logging-cookbook.rst:1010 +#: ../../howto/logging-cookbook.rst:1023 msgid "" "For the purposes of illustration, say that you have different web " "applications, each independent of the other but running in the same Python " @@ -665,18 +1546,188 @@ msgid "" "information such as client IP, HTTP request method and client username?" msgstr "" -#: ../../howto/logging-cookbook.rst:1017 +#: ../../howto/logging-cookbook.rst:1030 msgid "Let's assume that the library can be simulated by the following code:" msgstr "" -#: ../../howto/logging-cookbook.rst:1033 +#: ../../howto/logging-cookbook.rst:1032 +msgid "" +"# webapplib.py\n" +"import logging\n" +"import time\n" +"\n" +"logger = logging.getLogger(__name__)\n" +"\n" +"def useful():\n" +" # Just a representative event logged from the library\n" +" logger.debug('Hello from webapplib!')\n" +" # Just sleep for a bit so other threads get to run\n" +" time.sleep(0.01)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1046 msgid "" "We can simulate the multiple web applications by means of two simple " "classes, ``Request`` and ``WebApp``. These simulate how real threaded web " "applications work - each request is handled by a thread:" msgstr "" -#: ../../howto/logging-cookbook.rst:1177 +#: ../../howto/logging-cookbook.rst:1050 +msgid "" +"# main.py\n" +"import argparse\n" +"from contextvars import ContextVar\n" +"import logging\n" +"import os\n" +"from random import choice\n" +"import threading\n" +"import webapplib\n" +"\n" +"logger = logging.getLogger(__name__)\n" +"root = logging.getLogger()\n" +"root.setLevel(logging.DEBUG)\n" +"\n" +"class Request:\n" +" \"\"\"\n" +" A simple dummy request class which just holds dummy HTTP request " +"method,\n" +" client IP address and client username\n" +" \"\"\"\n" +" def __init__(self, method, ip, user):\n" +" self.method = method\n" +" self.ip = ip\n" +" self.user = user\n" +"\n" +"# A dummy set of requests which will be used in the simulation - we'll just " +"pick\n" +"# from this list randomly. Note that all GET requests are from 192.168.2." +"XXX\n" +"# addresses, whereas POST requests are from 192.16.3.XXX addresses. Three " +"users\n" +"# are represented in the sample requests.\n" +"\n" +"REQUESTS = [\n" +" Request('GET', '192.168.2.20', 'jim'),\n" +" Request('POST', '192.168.3.20', 'fred'),\n" +" Request('GET', '192.168.2.21', 'sheila'),\n" +" Request('POST', '192.168.3.21', 'jim'),\n" +" Request('GET', '192.168.2.22', 'fred'),\n" +" Request('POST', '192.168.3.22', 'sheila'),\n" +"]\n" +"\n" +"# Note that the format string includes references to request context " +"information\n" +"# such as HTTP method, client IP and username\n" +"\n" +"formatter = logging.Formatter('%(threadName)-11s %(appName)s %(name)-9s " +"%(user)-6s %(ip)s %(method)-4s %(message)s')\n" +"\n" +"# Create our context variables. These will be filled at the start of " +"request\n" +"# processing, and used in the logging that happens during that processing\n" +"\n" +"ctx_request = ContextVar('request')\n" +"ctx_appname = ContextVar('appname')\n" +"\n" +"class InjectingFilter(logging.Filter):\n" +" \"\"\"\n" +" A filter which injects context-specific information into logs and " +"ensures\n" +" that only information for a specific webapp is included in its log\n" +" \"\"\"\n" +" def __init__(self, app):\n" +" self.app = app\n" +"\n" +" def filter(self, record):\n" +" request = ctx_request.get()\n" +" record.method = request.method\n" +" record.ip = request.ip\n" +" record.user = request.user\n" +" record.appName = appName = ctx_appname.get()\n" +" return appName == self.app.name\n" +"\n" +"class WebApp:\n" +" \"\"\"\n" +" A dummy web application class which has its own handler and filter for " +"a\n" +" webapp-specific log.\n" +" \"\"\"\n" +" def __init__(self, name):\n" +" self.name = name\n" +" handler = logging.FileHandler(name + '.log', 'w')\n" +" f = InjectingFilter(self)\n" +" handler.setFormatter(formatter)\n" +" handler.addFilter(f)\n" +" root.addHandler(handler)\n" +" self.num_requests = 0\n" +"\n" +" def process_request(self, request):\n" +" \"\"\"\n" +" This is the dummy method for processing a request. It's called on a\n" +" different thread for every request. We store the context information " +"into\n" +" the context vars before doing anything else.\n" +" \"\"\"\n" +" ctx_request.set(request)\n" +" ctx_appname.set(self.name)\n" +" self.num_requests += 1\n" +" logger.debug('Request processing started')\n" +" webapplib.useful()\n" +" logger.debug('Request processing finished')\n" +"\n" +"def main():\n" +" fn = os.path.splitext(os.path.basename(__file__))[0]\n" +" adhf = argparse.ArgumentDefaultsHelpFormatter\n" +" ap = argparse.ArgumentParser(formatter_class=adhf, prog=fn,\n" +" description='Simulate a couple of web '\n" +" 'applications handling some '\n" +" 'requests, showing how request " +"'\n" +" 'context can be used to '\n" +" 'populate logs')\n" +" aa = ap.add_argument\n" +" aa('--count', '-c', type=int, default=100, help='How many requests to " +"simulate')\n" +" options = ap.parse_args()\n" +"\n" +" # Create the dummy webapps and put them in a list which we can use to " +"select\n" +" # from randomly\n" +" app1 = WebApp('app1')\n" +" app2 = WebApp('app2')\n" +" apps = [app1, app2]\n" +" threads = []\n" +" # Add a common handler which will capture all events\n" +" handler = logging.FileHandler('app.log', 'w')\n" +" handler.setFormatter(formatter)\n" +" root.addHandler(handler)\n" +"\n" +" # Generate calls to process requests\n" +" for i in range(options.count):\n" +" try:\n" +" # Pick an app at random and a request for it to process\n" +" app = choice(apps)\n" +" request = choice(REQUESTS)\n" +" # Process the request in its own thread\n" +" t = threading.Thread(target=app.process_request, " +"args=(request,))\n" +" threads.append(t)\n" +" t.start()\n" +" except KeyboardInterrupt:\n" +" break\n" +"\n" +" # Wait for the threads to terminate\n" +" for t in threads:\n" +" t.join()\n" +"\n" +" for app in apps:\n" +" print('%s processed %s requests' % (app.name, app.num_requests))\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1190 msgid "" "If you run the above, you should find that roughly half the requests go " "into :file:`app1.log` and the rest into :file:`app2.log`, and the all the " @@ -687,11 +1738,66 @@ msgid "" "illustrated by the following shell output:" msgstr "" -#: ../../howto/logging-cookbook.rst:1224 +#: ../../howto/logging-cookbook.rst:1197 +msgid "" +"~/logging-contextual-webapp$ python main.py\n" +"app1 processed 51 requests\n" +"app2 processed 49 requests\n" +"~/logging-contextual-webapp$ wc -l *.log\n" +" 153 app1.log\n" +" 147 app2.log\n" +" 300 app.log\n" +" 600 total\n" +"~/logging-contextual-webapp$ head -3 app1.log\n" +"Thread-3 (process_request) app1 __main__ jim 192.168.3.21 POST Request " +"processing started\n" +"Thread-3 (process_request) app1 webapplib jim 192.168.3.21 POST Hello " +"from webapplib!\n" +"Thread-5 (process_request) app1 __main__ jim 192.168.3.21 POST Request " +"processing started\n" +"~/logging-contextual-webapp$ head -3 app2.log\n" +"Thread-1 (process_request) app2 __main__ sheila 192.168.2.21 GET Request " +"processing started\n" +"Thread-1 (process_request) app2 webapplib sheila 192.168.2.21 GET Hello " +"from webapplib!\n" +"Thread-2 (process_request) app2 __main__ jim 192.168.2.20 GET Request " +"processing started\n" +"~/logging-contextual-webapp$ head app.log\n" +"Thread-1 (process_request) app2 __main__ sheila 192.168.2.21 GET Request " +"processing started\n" +"Thread-1 (process_request) app2 webapplib sheila 192.168.2.21 GET Hello " +"from webapplib!\n" +"Thread-2 (process_request) app2 __main__ jim 192.168.2.20 GET Request " +"processing started\n" +"Thread-3 (process_request) app1 __main__ jim 192.168.3.21 POST Request " +"processing started\n" +"Thread-2 (process_request) app2 webapplib jim 192.168.2.20 GET Hello " +"from webapplib!\n" +"Thread-3 (process_request) app1 webapplib jim 192.168.3.21 POST Hello " +"from webapplib!\n" +"Thread-4 (process_request) app2 __main__ fred 192.168.2.22 GET Request " +"processing started\n" +"Thread-5 (process_request) app1 __main__ jim 192.168.3.21 POST Request " +"processing started\n" +"Thread-4 (process_request) app2 webapplib fred 192.168.2.22 GET Hello " +"from webapplib!\n" +"Thread-6 (process_request) app1 __main__ jim 192.168.3.21 POST Request " +"processing started\n" +"~/logging-contextual-webapp$ grep app1 app1.log | wc -l\n" +"153\n" +"~/logging-contextual-webapp$ grep app2 app2.log | wc -l\n" +"147\n" +"~/logging-contextual-webapp$ grep app1 app.log | wc -l\n" +"153\n" +"~/logging-contextual-webapp$ grep app2 app.log | wc -l\n" +"147" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1237 msgid "Imparting contextual information in handlers" msgstr "" -#: ../../howto/logging-cookbook.rst:1226 +#: ../../howto/logging-cookbook.rst:1239 msgid "" "Each :class:`~Handler` has its own chain of filters. If you want to add " "contextual information to a :class:`LogRecord` without leaking it to other " @@ -699,11 +1805,33 @@ msgid "" "instead of modifying it in-place, as shown in the following script::" msgstr "" -#: ../../howto/logging-cookbook.rst:1253 +#: ../../howto/logging-cookbook.rst:1244 +msgid "" +"import copy\n" +"import logging\n" +"\n" +"def filter(record: logging.LogRecord):\n" +" record = copy.copy(record)\n" +" record.user = 'jim'\n" +" return record\n" +"\n" +"if __name__ == '__main__':\n" +" logger = logging.getLogger()\n" +" logger.setLevel(logging.INFO)\n" +" handler = logging.StreamHandler()\n" +" formatter = logging.Formatter('%(message)s from %(user)-8s')\n" +" handler.setFormatter(formatter)\n" +" handler.addFilter(filter)\n" +" logger.addHandler(handler)\n" +"\n" +" logger.info('A log message')" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1266 msgid "Logging to a single file from multiple processes" msgstr "" -#: ../../howto/logging-cookbook.rst:1255 +#: ../../howto/logging-cookbook.rst:1268 msgid "" "Although logging is thread-safe, and logging to a single file from multiple " "threads in a single process *is* supported, logging to a single file from " @@ -719,18 +1847,15 @@ msgid "" "you to adapt in your own applications." msgstr "" -#: ../../howto/logging-cookbook.rst:1268 +#: ../../howto/logging-cookbook.rst:1281 msgid "" "You could also write your own handler which uses the :class:" "`~multiprocessing.Lock` class from the :mod:`multiprocessing` module to " -"serialize access to the file from your processes. The existing :class:" -"`FileHandler` and subclasses do not make use of :mod:`multiprocessing` at " -"present, though they may do so in the future. Note that at present, the :mod:" -"`multiprocessing` module does not provide working lock functionality on all " -"platforms (see https://bugs.python.org/issue3770)." +"serialize access to the file from your processes. The stdlib :class:" +"`FileHandler` and subclasses do not make use of :mod:`multiprocessing`." msgstr "" -#: ../../howto/logging-cookbook.rst:1278 +#: ../../howto/logging-cookbook.rst:1288 msgid "" "Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send " "all logging events to one of the processes in your multi-process " @@ -745,13 +1870,230 @@ msgid "" "requirements::" msgstr "" -#: ../../howto/logging-cookbook.rst:1394 +#: ../../howto/logging-cookbook.rst:1299 +msgid "" +"# You'll need these imports in your own code\n" +"import logging\n" +"import logging.handlers\n" +"import multiprocessing\n" +"\n" +"# Next two import lines for this demo only\n" +"from random import choice, random\n" +"import time\n" +"\n" +"#\n" +"# Because you'll want to define the logging configurations for listener and " +"workers, the\n" +"# listener and worker process functions take a configurer parameter which is " +"a callable\n" +"# for configuring logging for that process. These functions are also passed " +"the queue,\n" +"# which they use for communication.\n" +"#\n" +"# In practice, you can configure the listener however you want, but note " +"that in this\n" +"# simple example, the listener does not apply level or filter logic to " +"received records.\n" +"# In practice, you would probably want to do this logic in the worker " +"processes, to avoid\n" +"# sending events which would be filtered out between processes.\n" +"#\n" +"# The size of the rotated files is made small so you can see the results " +"easily.\n" +"def listener_configurer():\n" +" root = logging.getLogger()\n" +" h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10)\n" +" f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s " +"%(levelname)-8s %(message)s')\n" +" h.setFormatter(f)\n" +" root.addHandler(h)\n" +"\n" +"# This is the listener process top-level loop: wait for logging events\n" +"# (LogRecords)on the queue and handle them, quit when you get a None for a\n" +"# LogRecord.\n" +"def listener_process(queue, configurer):\n" +" configurer()\n" +" while True:\n" +" try:\n" +" record = queue.get()\n" +" if record is None: # We send this as a sentinel to tell the " +"listener to quit.\n" +" break\n" +" logger = logging.getLogger(record.name)\n" +" logger.handle(record) # No level or filter logic applied - just " +"do it!\n" +" except Exception:\n" +" import sys, traceback\n" +" print('Whoops! Problem:', file=sys.stderr)\n" +" traceback.print_exc(file=sys.stderr)\n" +"\n" +"# Arrays used for random selections in this demo\n" +"\n" +"LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,\n" +" logging.ERROR, logging.CRITICAL]\n" +"\n" +"LOGGERS = ['a.b.c', 'd.e.f']\n" +"\n" +"MESSAGES = [\n" +" 'Random message #1',\n" +" 'Random message #2',\n" +" 'Random message #3',\n" +"]\n" +"\n" +"# The worker configuration is done at the start of the worker process run.\n" +"# Note that on Windows you can't rely on fork semantics, so each process\n" +"# will run the logging configuration code when it starts.\n" +"def worker_configurer(queue):\n" +" h = logging.handlers.QueueHandler(queue) # Just the one handler needed\n" +" root = logging.getLogger()\n" +" root.addHandler(h)\n" +" # send all messages, for demo; no other level or filter logic applied.\n" +" root.setLevel(logging.DEBUG)\n" +"\n" +"# This is the worker process top-level loop, which just logs ten events " +"with\n" +"# random intervening delays before terminating.\n" +"# The print messages are just so you know it's doing something!\n" +"def worker_process(queue, configurer):\n" +" configurer(queue)\n" +" name = multiprocessing.current_process().name\n" +" print('Worker started: %s' % name)\n" +" for i in range(10):\n" +" time.sleep(random())\n" +" logger = logging.getLogger(choice(LOGGERS))\n" +" level = choice(LEVELS)\n" +" message = choice(MESSAGES)\n" +" logger.log(level, message)\n" +" print('Worker finished: %s' % name)\n" +"\n" +"# Here's where the demo gets orchestrated. Create the queue, create and " +"start\n" +"# the listener, create ten workers and start them, wait for them to finish,\n" +"# then send a None to the queue to tell the listener to finish.\n" +"def main():\n" +" queue = multiprocessing.Queue(-1)\n" +" listener = multiprocessing.Process(target=listener_process,\n" +" args=(queue, listener_configurer))\n" +" listener.start()\n" +" workers = []\n" +" for i in range(10):\n" +" worker = multiprocessing.Process(target=worker_process,\n" +" args=(queue, worker_configurer))\n" +" workers.append(worker)\n" +" worker.start()\n" +" for w in workers:\n" +" w.join()\n" +" queue.put_nowait(None)\n" +" listener.join()\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1404 msgid "" "A variant of the above script keeps the logging in the main process, in a " "separate thread::" msgstr "" -#: ../../howto/logging-cookbook.rst:1489 +#: ../../howto/logging-cookbook.rst:1407 +msgid "" +"import logging\n" +"import logging.config\n" +"import logging.handlers\n" +"from multiprocessing import Process, Queue\n" +"import random\n" +"import threading\n" +"import time\n" +"\n" +"def logger_thread(q):\n" +" while True:\n" +" record = q.get()\n" +" if record is None:\n" +" break\n" +" logger = logging.getLogger(record.name)\n" +" logger.handle(record)\n" +"\n" +"\n" +"def worker_process(q):\n" +" qh = logging.handlers.QueueHandler(q)\n" +" root = logging.getLogger()\n" +" root.setLevel(logging.DEBUG)\n" +" root.addHandler(qh)\n" +" levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,\n" +" logging.CRITICAL]\n" +" loggers = ['foo', 'foo.bar', 'foo.bar.baz',\n" +" 'spam', 'spam.ham', 'spam.ham.eggs']\n" +" for i in range(100):\n" +" lvl = random.choice(levels)\n" +" logger = logging.getLogger(random.choice(loggers))\n" +" logger.log(lvl, 'Message no. %d', i)\n" +"\n" +"if __name__ == '__main__':\n" +" q = Queue()\n" +" d = {\n" +" 'version': 1,\n" +" 'formatters': {\n" +" 'detailed': {\n" +" 'class': 'logging.Formatter',\n" +" 'format': '%(asctime)s %(name)-15s %(levelname)-8s " +"%(processName)-10s %(message)s'\n" +" }\n" +" },\n" +" 'handlers': {\n" +" 'console': {\n" +" 'class': 'logging.StreamHandler',\n" +" 'level': 'INFO',\n" +" },\n" +" 'file': {\n" +" 'class': 'logging.FileHandler',\n" +" 'filename': 'mplog.log',\n" +" 'mode': 'w',\n" +" 'formatter': 'detailed',\n" +" },\n" +" 'foofile': {\n" +" 'class': 'logging.FileHandler',\n" +" 'filename': 'mplog-foo.log',\n" +" 'mode': 'w',\n" +" 'formatter': 'detailed',\n" +" },\n" +" 'errors': {\n" +" 'class': 'logging.FileHandler',\n" +" 'filename': 'mplog-errors.log',\n" +" 'mode': 'w',\n" +" 'level': 'ERROR',\n" +" 'formatter': 'detailed',\n" +" },\n" +" },\n" +" 'loggers': {\n" +" 'foo': {\n" +" 'handlers': ['foofile']\n" +" }\n" +" },\n" +" 'root': {\n" +" 'level': 'DEBUG',\n" +" 'handlers': ['console', 'file', 'errors']\n" +" },\n" +" }\n" +" workers = []\n" +" for i in range(5):\n" +" wp = Process(target=worker_process, name='worker %d' % (i + 1), " +"args=(q,))\n" +" workers.append(wp)\n" +" wp.start()\n" +" logging.config.dictConfig(d)\n" +" lp = threading.Thread(target=logger_thread, args=(q,))\n" +" lp.start()\n" +" # At this point, the main process could do some useful work of its own\n" +" # Once it's done that, it can wait for the workers to terminate...\n" +" for wp in workers:\n" +" wp.join()\n" +" # And now tell the logging thread to finish up, too\n" +" q.put(None)\n" +" lp.join()" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1499 msgid "" "This variant shows how you can e.g. apply configuration for particular " "loggers - e.g. the ``foo`` logger has a special handler which stores all " @@ -761,34 +2103,63 @@ msgid "" "appropriate destinations." msgstr "" -#: ../../howto/logging-cookbook.rst:1496 +#: ../../howto/logging-cookbook.rst:1506 msgid "Using concurrent.futures.ProcessPoolExecutor" msgstr "" -#: ../../howto/logging-cookbook.rst:1498 +#: ../../howto/logging-cookbook.rst:1508 msgid "" "If you want to use :class:`concurrent.futures.ProcessPoolExecutor` to start " "your worker processes, you need to create the queue slightly differently. " "Instead of" msgstr "" -#: ../../howto/logging-cookbook.rst:1506 +#: ../../howto/logging-cookbook.rst:1512 +msgid "queue = multiprocessing.Queue(-1)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1516 msgid "you should use" msgstr "" -#: ../../howto/logging-cookbook.rst:1512 +#: ../../howto/logging-cookbook.rst:1518 +msgid "" +"queue = multiprocessing.Manager().Queue(-1) # also works with the examples " +"above" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1522 msgid "and you can then replace the worker creation from this::" msgstr "" -#: ../../howto/logging-cookbook.rst:1523 +#: ../../howto/logging-cookbook.rst:1524 +msgid "" +"workers = []\n" +"for i in range(10):\n" +" worker = multiprocessing.Process(target=worker_process,\n" +" args=(queue, worker_configurer))\n" +" workers.append(worker)\n" +" worker.start()\n" +"for w in workers:\n" +" w.join()" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1533 msgid "to this (remembering to first import :mod:`concurrent.futures`)::" msgstr "" -#: ../../howto/logging-cookbook.rst:1530 +#: ../../howto/logging-cookbook.rst:1535 +msgid "" +"with concurrent.futures.ProcessPoolExecutor(max_workers=10) as executor:\n" +" for i in range(10):\n" +" executor.submit(worker_process, queue, worker_configurer)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1540 msgid "Deploying Web applications using Gunicorn and uWSGI" msgstr "" -#: ../../howto/logging-cookbook.rst:1532 +#: ../../howto/logging-cookbook.rst:1542 msgid "" "When deploying Web applications using `Gunicorn `_ or " "`uWSGI `_ (or similar), " @@ -800,11 +2171,11 @@ msgid "" "listener in production`_ for more details." msgstr "" -#: ../../howto/logging-cookbook.rst:1542 +#: ../../howto/logging-cookbook.rst:1552 msgid "Using file rotation" msgstr "" -#: ../../howto/logging-cookbook.rst:1547 +#: ../../howto/logging-cookbook.rst:1557 msgid "" "Sometimes you want to let a log file grow to a certain size, then open a new " "file and log to that. You may want to keep a certain number of these files, " @@ -813,13 +2184,52 @@ msgid "" "usage pattern, the logging package provides a :class:`RotatingFileHandler`::" msgstr "" -#: ../../howto/logging-cookbook.rst:1579 +#: ../../howto/logging-cookbook.rst:1563 +msgid "" +"import glob\n" +"import logging\n" +"import logging.handlers\n" +"\n" +"LOG_FILENAME = 'logging_rotatingfile_example.out'\n" +"\n" +"# Set up a specific logger with our desired output level\n" +"my_logger = logging.getLogger('MyLogger')\n" +"my_logger.setLevel(logging.DEBUG)\n" +"\n" +"# Add the log message handler to the logger\n" +"handler = logging.handlers.RotatingFileHandler(\n" +" LOG_FILENAME, maxBytes=20, backupCount=5)\n" +"\n" +"my_logger.addHandler(handler)\n" +"\n" +"# Log some messages\n" +"for i in range(20):\n" +" my_logger.debug('i = %d' % i)\n" +"\n" +"# See what files are created\n" +"logfiles = glob.glob('%s*' % LOG_FILENAME)\n" +"\n" +"for filename in logfiles:\n" +" print(filename)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1589 msgid "" "The result should be 6 separate files, each with part of the log history for " "the application:" msgstr "" -#: ../../howto/logging-cookbook.rst:1591 +#: ../../howto/logging-cookbook.rst:1592 +msgid "" +"logging_rotatingfile_example.out\n" +"logging_rotatingfile_example.out.1\n" +"logging_rotatingfile_example.out.2\n" +"logging_rotatingfile_example.out.3\n" +"logging_rotatingfile_example.out.4\n" +"logging_rotatingfile_example.out.5" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1601 msgid "" "The most current file is always :file:`logging_rotatingfile_example.out`, " "and each time it reaches the size limit it is renamed with the suffix " @@ -827,17 +2237,17 @@ msgid "" "(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased." msgstr "" -#: ../../howto/logging-cookbook.rst:1596 +#: ../../howto/logging-cookbook.rst:1606 msgid "" "Obviously this example sets the log length much too small as an extreme " "example. You would want to set *maxBytes* to an appropriate value." msgstr "" -#: ../../howto/logging-cookbook.rst:1604 +#: ../../howto/logging-cookbook.rst:1614 msgid "Use of alternative formatting styles" msgstr "" -#: ../../howto/logging-cookbook.rst:1606 +#: ../../howto/logging-cookbook.rst:1616 msgid "" "When logging was added to the Python standard library, the only way of " "formatting messages with variable content was to use the %-formatting " @@ -846,7 +2256,7 @@ msgid "" "Python 2.6)." msgstr "" -#: ../../howto/logging-cookbook.rst:1612 +#: ../../howto/logging-cookbook.rst:1622 msgid "" "Logging (as of 3.2) provides improved support for these two additional " "formatting styles. The :class:`Formatter` class been enhanced to take an " @@ -859,14 +2269,46 @@ msgid "" "session to show the possibilities:" msgstr "" -#: ../../howto/logging-cookbook.rst:1646 +#: ../../howto/logging-cookbook.rst:1632 +msgid "" +">>> import logging\n" +">>> root = logging.getLogger()\n" +">>> root.setLevel(logging.DEBUG)\n" +">>> handler = logging.StreamHandler()\n" +">>> bf = logging.Formatter('{asctime} {name} {levelname:8s} {message}',\n" +"... style='{')\n" +">>> handler.setFormatter(bf)\n" +">>> root.addHandler(handler)\n" +">>> logger = logging.getLogger('foo.bar')\n" +">>> logger.debug('This is a DEBUG message')\n" +"2010-10-28 15:11:55,341 foo.bar DEBUG This is a DEBUG message\n" +">>> logger.critical('This is a CRITICAL message')\n" +"2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message\n" +">>> df = logging.Formatter('$asctime $name ${levelname} $message',\n" +"... style='$')\n" +">>> handler.setFormatter(df)\n" +">>> logger.debug('This is a DEBUG message')\n" +"2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message\n" +">>> logger.critical('This is a CRITICAL message')\n" +"2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message\n" +">>>" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1656 msgid "" "Note that the formatting of logging messages for final output to logs is " "completely independent of how an individual logging message is constructed. " "That can still use %-formatting, as shown here::" msgstr "" -#: ../../howto/logging-cookbook.rst:1654 +#: ../../howto/logging-cookbook.rst:1660 +msgid "" +">>> logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message')\n" +"2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message\n" +">>>" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1664 msgid "" "Logging calls (``logger.debug()``, ``logger.info()`` etc.) only take " "positional parameters for the actual logging message itself, with keyword " @@ -882,7 +2324,7 @@ msgid "" "strings." msgstr "" -#: ../../howto/logging-cookbook.rst:1667 +#: ../../howto/logging-cookbook.rst:1677 msgid "" "There is, however, a way that you can use {}- and $- formatting to construct " "your individual log messages. Recall that for a message you can use an " @@ -891,7 +2333,28 @@ msgid "" "the following two classes::" msgstr "" -#: ../../howto/logging-cookbook.rst:1691 +#: ../../howto/logging-cookbook.rst:1683 ../../howto/logging-cookbook.rst:2771 +msgid "" +"class BraceMessage:\n" +" def __init__(self, fmt, /, *args, **kwargs):\n" +" self.fmt = fmt\n" +" self.args = args\n" +" self.kwargs = kwargs\n" +"\n" +" def __str__(self):\n" +" return self.fmt.format(*self.args, **self.kwargs)\n" +"\n" +"class DollarMessage:\n" +" def __init__(self, fmt, /, **kwargs):\n" +" self.fmt = fmt\n" +" self.kwargs = kwargs\n" +"\n" +" def __str__(self):\n" +" from string import Template\n" +" return Template(self.fmt).substitute(**self.kwargs)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1701 msgid "" "Either of these can be used in place of a format string, to allow {}- or $-" "formatting to be used to build the actual \"message\" part which appears in " @@ -902,21 +2365,40 @@ msgid "" "used as a synonym/alias for :func:`gettext.gettext` or its brethren)." msgstr "" -#: ../../howto/logging-cookbook.rst:1699 +#: ../../howto/logging-cookbook.rst:1709 msgid "" "The above classes are not included in Python, though they're easy enough to " "copy and paste into your own code. They can be used as follows (assuming " "that they're declared in a module called ``wherever``):" msgstr "" -#: ../../howto/logging-cookbook.rst:1721 +#: ../../howto/logging-cookbook.rst:1713 +msgid "" +">>> from wherever import BraceMessage as __\n" +">>> print(__('Message with {0} {name}', 2, name='placeholders'))\n" +"Message with 2 placeholders\n" +">>> class Point: pass\n" +"...\n" +">>> p = Point()\n" +">>> p.x = 0.5\n" +">>> p.y = 0.5\n" +">>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})',\n" +"... point=p))\n" +"Message with coordinates: (0.50, 0.50)\n" +">>> from wherever import DollarMessage as __\n" +">>> print(__('Message with $num $what', num=2, what='placeholders'))\n" +"Message with 2 placeholders\n" +">>>" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1731 msgid "" "While the above examples use ``print()`` to show how the formatting works, " "you would of course use ``logger.debug()`` or similar to actually log using " "this approach." msgstr "" -#: ../../howto/logging-cookbook.rst:1725 +#: ../../howto/logging-cookbook.rst:1735 msgid "" "One thing to note is that you pay no significant performance penalty with " "this approach: the actual formatting happens not when you make the logging " @@ -927,23 +2409,52 @@ msgid "" "sugar for a constructor call to one of the :samp:`{XXX}Message` classes." msgstr "" -#: ../../howto/logging-cookbook.rst:1733 +#: ../../howto/logging-cookbook.rst:1743 msgid "" "If you prefer, you can use a :class:`LoggerAdapter` to achieve a similar " "effect to the above, as in the following example::" msgstr "" -#: ../../howto/logging-cookbook.rst:1762 +#: ../../howto/logging-cookbook.rst:1746 +msgid "" +"import logging\n" +"\n" +"class Message:\n" +" def __init__(self, fmt, args):\n" +" self.fmt = fmt\n" +" self.args = args\n" +"\n" +" def __str__(self):\n" +" return self.fmt.format(*self.args)\n" +"\n" +"class StyleAdapter(logging.LoggerAdapter):\n" +" def log(self, level, msg, /, *args, stacklevel=1, **kwargs):\n" +" if self.isEnabledFor(level):\n" +" msg, kwargs = self.process(msg, kwargs)\n" +" self.logger.log(level, Message(msg, args), **kwargs,\n" +" stacklevel=stacklevel+1)\n" +"\n" +"logger = StyleAdapter(logging.getLogger(__name__))\n" +"\n" +"def main():\n" +" logger.debug('Hello, {}', 'world!')\n" +"\n" +"if __name__ == '__main__':\n" +" logging.basicConfig(level=logging.DEBUG)\n" +" main()" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1772 msgid "" "The above script should log the message ``Hello, world!`` when run with " "Python 3.8 or later." msgstr "" -#: ../../howto/logging-cookbook.rst:1771 +#: ../../howto/logging-cookbook.rst:1781 msgid "Customizing ``LogRecord``" msgstr "Personalizando o ``LogRecord``" -#: ../../howto/logging-cookbook.rst:1773 +#: ../../howto/logging-cookbook.rst:1783 msgid "" "Every logging event is represented by a :class:`LogRecord` instance. When an " "event is logged and not filtered out by a logger's level, a :class:" @@ -954,13 +2465,13 @@ msgid "" "was done:" msgstr "" -#: ../../howto/logging-cookbook.rst:1780 +#: ../../howto/logging-cookbook.rst:1790 msgid "" ":meth:`Logger.makeRecord`, which is called in the normal process of logging " "an event. This invoked :class:`LogRecord` directly to create an instance." msgstr "" -#: ../../howto/logging-cookbook.rst:1783 +#: ../../howto/logging-cookbook.rst:1793 msgid "" ":func:`makeLogRecord`, which is called with a dictionary containing " "attributes to be added to the LogRecord. This is typically invoked when a " @@ -969,27 +2480,27 @@ msgid "" "`~handlers.HTTPHandler`)." msgstr "" -#: ../../howto/logging-cookbook.rst:1789 +#: ../../howto/logging-cookbook.rst:1799 msgid "" "This has usually meant that if you need to do anything special with a :class:" "`LogRecord`, you've had to do one of the following." msgstr "" -#: ../../howto/logging-cookbook.rst:1792 +#: ../../howto/logging-cookbook.rst:1802 msgid "" "Create your own :class:`Logger` subclass, which overrides :meth:`Logger." "makeRecord`, and set it using :func:`~logging.setLoggerClass` before any " "loggers that you care about are instantiated." msgstr "" -#: ../../howto/logging-cookbook.rst:1795 +#: ../../howto/logging-cookbook.rst:1805 msgid "" "Add a :class:`Filter` to a logger or handler, which does the necessary " "special manipulation you need when its :meth:`~Filter.filter` method is " "called." msgstr "" -#: ../../howto/logging-cookbook.rst:1799 +#: ../../howto/logging-cookbook.rst:1809 msgid "" "The first approach would be a little unwieldy in the scenario where (say) " "several different libraries wanted to do different things. Each would " @@ -997,7 +2508,7 @@ msgid "" "last would win." msgstr "" -#: ../../howto/logging-cookbook.rst:1804 +#: ../../howto/logging-cookbook.rst:1814 msgid "" "The second approach works reasonably well for many cases, but does not allow " "you to e.g. use a specialized subclass of :class:`LogRecord`. Library " @@ -1006,7 +2517,11 @@ msgid "" "would do simply by adding new packages or modules and doing ::" msgstr "" -#: ../../howto/logging-cookbook.rst:1812 +#: ../../howto/logging-cookbook.rst:1820 +msgid "logger = logging.getLogger(__name__)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1822 msgid "" "at module level). It's probably one too many things to think about. " "Developers could also add the filter to a :class:`~logging.NullHandler` " @@ -1016,7 +2531,7 @@ msgid "" "developer." msgstr "" -#: ../../howto/logging-cookbook.rst:1818 +#: ../../howto/logging-cookbook.rst:1828 msgid "" "In Python 3.2 and later, :class:`~logging.LogRecord` creation is done " "through a factory, which you can specify. The factory is just a callable you " @@ -1026,7 +2541,7 @@ msgid "" "`LogRecord` is the default setting for the factory." msgstr "" -#: ../../howto/logging-cookbook.rst:1825 +#: ../../howto/logging-cookbook.rst:1835 msgid "" "This approach allows a custom factory to control all aspects of LogRecord " "creation. For example, you could return a subclass, or just add some " @@ -1034,7 +2549,19 @@ msgid "" "this::" msgstr "" -#: ../../howto/logging-cookbook.rst:1838 +#: ../../howto/logging-cookbook.rst:1839 +msgid "" +"old_factory = logging.getLogRecordFactory()\n" +"\n" +"def record_factory(*args, **kwargs):\n" +" record = old_factory(*args, **kwargs)\n" +" record.custom_attribute = 0xdecafbad\n" +" return record\n" +"\n" +"logging.setLogRecordFactory(record_factory)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1848 msgid "" "This pattern allows different libraries to chain factories together, and as " "long as they don't overwrite each other's attributes or unintentionally " @@ -1044,42 +2571,91 @@ msgid "" "used when the use of a :class:`Filter` does not provide the desired result." msgstr "" -#: ../../howto/logging-cookbook.rst:1850 +#: ../../howto/logging-cookbook.rst:1860 msgid "Subclassing QueueHandler and QueueListener- a ZeroMQ example" msgstr "" -#: ../../howto/logging-cookbook.rst:1853 ../../howto/logging-cookbook.rst:1986 +#: ../../howto/logging-cookbook.rst:1863 ../../howto/logging-cookbook.rst:1996 msgid "Subclass ``QueueHandler``" msgstr "" -#: ../../howto/logging-cookbook.rst:1855 +#: ../../howto/logging-cookbook.rst:1865 msgid "" "You can use a :class:`QueueHandler` subclass to send messages to other kinds " "of queues, for example a ZeroMQ 'publish' socket. In the example below,the " "socket is created separately and passed to the handler (as its 'queue')::" msgstr "" -#: ../../howto/logging-cookbook.rst:1874 +#: ../../howto/logging-cookbook.rst:1869 +msgid "" +"import zmq # using pyzmq, the Python binding for ZeroMQ\n" +"import json # for serializing records portably\n" +"\n" +"ctx = zmq.Context()\n" +"sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value\n" +"sock.bind('tcp://*:5556') # or wherever\n" +"\n" +"class ZeroMQSocketHandler(QueueHandler):\n" +" def enqueue(self, record):\n" +" self.queue.send_json(record.__dict__)\n" +"\n" +"\n" +"handler = ZeroMQSocketHandler(sock)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1884 msgid "" "Of course there are other ways of organizing this, for example passing in " "the data needed by the handler to create the socket::" msgstr "" -#: ../../howto/logging-cookbook.rst:1892 ../../howto/logging-cookbook.rst:1922 +#: ../../howto/logging-cookbook.rst:1887 +msgid "" +"class ZeroMQSocketHandler(QueueHandler):\n" +" def __init__(self, uri, socktype=zmq.PUB, ctx=None):\n" +" self.ctx = ctx or zmq.Context()\n" +" socket = zmq.Socket(self.ctx, socktype)\n" +" socket.bind(uri)\n" +" super().__init__(socket)\n" +"\n" +" def enqueue(self, record):\n" +" self.queue.send_json(record.__dict__)\n" +"\n" +" def close(self):\n" +" self.queue.close()" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1902 ../../howto/logging-cookbook.rst:1932 msgid "Subclass ``QueueListener``" msgstr "" -#: ../../howto/logging-cookbook.rst:1894 +#: ../../howto/logging-cookbook.rst:1904 msgid "" "You can also subclass :class:`QueueListener` to get messages from other " "kinds of queues, for example a ZeroMQ 'subscribe' socket. Here's an example::" msgstr "" -#: ../../howto/logging-cookbook.rst:1912 +#: ../../howto/logging-cookbook.rst:1907 +msgid "" +"class ZeroMQSocketListener(QueueListener):\n" +" def __init__(self, uri, /, *handlers, **kwargs):\n" +" self.ctx = kwargs.get('ctx') or zmq.Context()\n" +" socket = zmq.Socket(self.ctx, zmq.SUB)\n" +" socket.setsockopt_string(zmq.SUBSCRIBE, '') # subscribe to " +"everything\n" +" socket.connect(uri)\n" +" super().__init__(socket, *handlers, **kwargs)\n" +"\n" +" def dequeue(self):\n" +" msg = self.queue.recv_json()\n" +" return logging.makeLogRecord(msg)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:1922 msgid "Subclassing QueueHandler and QueueListener- a ``pynng`` example" msgstr "" -#: ../../howto/logging-cookbook.rst:1914 +#: ../../howto/logging-cookbook.rst:1924 msgid "" "In a similar way to the above section, we can implement a listener and " "handler using :pypi:`pynng`, which is a Python binding to `NNG `_ of the Django documentation." msgstr "" -#: ../../howto/logging-cookbook.rst:2160 +#: ../../howto/logging-cookbook.rst:2170 msgid "Using a rotator and namer to customize log rotation processing" msgstr "" -#: ../../howto/logging-cookbook.rst:2162 +#: ../../howto/logging-cookbook.rst:2172 msgid "" "An example of how you can define a namer and rotator is given in the " "following runnable script, which shows gzip compression of the log file::" msgstr "" -#: ../../howto/logging-cookbook.rst:2193 +#: ../../howto/logging-cookbook.rst:2175 +msgid "" +"import gzip\n" +"import logging\n" +"import logging.handlers\n" +"import os\n" +"import shutil\n" +"\n" +"def namer(name):\n" +" return name + \".gz\"\n" +"\n" +"def rotator(source, dest):\n" +" with open(source, 'rb') as f_in:\n" +" with gzip.open(dest, 'wb') as f_out:\n" +" shutil.copyfileobj(f_in, f_out)\n" +" os.remove(source)\n" +"\n" +"\n" +"rh = logging.handlers.RotatingFileHandler('rotated.log', maxBytes=128, " +"backupCount=5)\n" +"rh.rotator = rotator\n" +"rh.namer = namer\n" +"\n" +"root = logging.getLogger()\n" +"root.setLevel(logging.INFO)\n" +"root.addHandler(rh)\n" +"f = logging.Formatter('%(asctime)s %(message)s')\n" +"rh.setFormatter(f)\n" +"for i in range(1000):\n" +" root.info(f'Message no. {i + 1}')" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2203 msgid "" "After running this, you will see six new files, five of which are compressed:" msgstr "" -#: ../../howto/logging-cookbook.rst:2206 +#: ../../howto/logging-cookbook.rst:2205 +msgid "" +"$ ls rotated.log*\n" +"rotated.log rotated.log.2.gz rotated.log.4.gz\n" +"rotated.log.1.gz rotated.log.3.gz rotated.log.5.gz\n" +"$ zcat rotated.log.1.gz\n" +"2023-01-20 02:28:17,767 Message no. 996\n" +"2023-01-20 02:28:17,767 Message no. 997\n" +"2023-01-20 02:28:17,767 Message no. 998" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2216 msgid "A more elaborate multiprocessing example" msgstr "" -#: ../../howto/logging-cookbook.rst:2208 +#: ../../howto/logging-cookbook.rst:2218 msgid "" "The following working example shows how logging can be used with " "multiprocessing using configuration files. The configurations are fairly " @@ -1155,7 +2989,7 @@ msgid "" "in a real multiprocessing scenario." msgstr "" -#: ../../howto/logging-cookbook.rst:2213 +#: ../../howto/logging-cookbook.rst:2223 msgid "" "In the example, the main process spawns a listener process and some worker " "processes. Each of the main process, the listener and the workers have three " @@ -1168,17 +3002,240 @@ msgid "" "own scenario." msgstr "" -#: ../../howto/logging-cookbook.rst:2223 +#: ../../howto/logging-cookbook.rst:2233 msgid "" "Here's the script - the docstrings and the comments hopefully explain how it " "works::" msgstr "" -#: ../../howto/logging-cookbook.rst:2435 +#: ../../howto/logging-cookbook.rst:2236 +msgid "" +"import logging\n" +"import logging.config\n" +"import logging.handlers\n" +"from multiprocessing import Process, Queue, Event, current_process\n" +"import os\n" +"import random\n" +"import time\n" +"\n" +"class MyHandler:\n" +" \"\"\"\n" +" A simple handler for logging events. It runs in the listener process " +"and\n" +" dispatches events to loggers based on the name in the received record,\n" +" which then get dispatched, by the logging system, to the handlers\n" +" configured for those loggers.\n" +" \"\"\"\n" +"\n" +" def handle(self, record):\n" +" if record.name == \"root\":\n" +" logger = logging.getLogger()\n" +" else:\n" +" logger = logging.getLogger(record.name)\n" +"\n" +" if logger.isEnabledFor(record.levelno):\n" +" # The process name is transformed just to show that it's the " +"listener\n" +" # doing the logging to files and console\n" +" record.processName = '%s (for %s)' % (current_process().name, " +"record.processName)\n" +" logger.handle(record)\n" +"\n" +"def listener_process(q, stop_event, config):\n" +" \"\"\"\n" +" This could be done in the main process, but is just done in a separate\n" +" process for illustrative purposes.\n" +"\n" +" This initialises logging according to the specified configuration,\n" +" starts the listener and waits for the main process to signal completion\n" +" via the event. The listener is then stopped, and the process exits.\n" +" \"\"\"\n" +" logging.config.dictConfig(config)\n" +" listener = logging.handlers.QueueListener(q, MyHandler())\n" +" listener.start()\n" +" if os.name == 'posix':\n" +" # On POSIX, the setup logger will have been configured in the\n" +" # parent process, but should have been disabled following the\n" +" # dictConfig call.\n" +" # On Windows, since fork isn't used, the setup logger won't\n" +" # exist in the child, so it would be created and the message\n" +" # would appear - hence the \"if posix\" clause.\n" +" logger = logging.getLogger('setup')\n" +" logger.critical('Should not appear, because of disabled " +"logger ...')\n" +" stop_event.wait()\n" +" listener.stop()\n" +"\n" +"def worker_process(config):\n" +" \"\"\"\n" +" A number of these are spawned for the purpose of illustration. In\n" +" practice, they could be a heterogeneous bunch of processes rather than\n" +" ones which are identical to each other.\n" +"\n" +" This initialises logging according to the specified configuration,\n" +" and logs a hundred messages with random levels to randomly selected\n" +" loggers.\n" +"\n" +" A small sleep is added to allow other processes a chance to run. This\n" +" is not strictly needed, but it mixes the output from the different\n" +" processes a bit more than if it's left out.\n" +" \"\"\"\n" +" logging.config.dictConfig(config)\n" +" levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,\n" +" logging.CRITICAL]\n" +" loggers = ['foo', 'foo.bar', 'foo.bar.baz',\n" +" 'spam', 'spam.ham', 'spam.ham.eggs']\n" +" if os.name == 'posix':\n" +" # On POSIX, the setup logger will have been configured in the\n" +" # parent process, but should have been disabled following the\n" +" # dictConfig call.\n" +" # On Windows, since fork isn't used, the setup logger won't\n" +" # exist in the child, so it would be created and the message\n" +" # would appear - hence the \"if posix\" clause.\n" +" logger = logging.getLogger('setup')\n" +" logger.critical('Should not appear, because of disabled " +"logger ...')\n" +" for i in range(100):\n" +" lvl = random.choice(levels)\n" +" logger = logging.getLogger(random.choice(loggers))\n" +" logger.log(lvl, 'Message no. %d', i)\n" +" time.sleep(0.01)\n" +"\n" +"def main():\n" +" q = Queue()\n" +" # The main process gets a simple configuration which prints to the " +"console.\n" +" config_initial = {\n" +" 'version': 1,\n" +" 'handlers': {\n" +" 'console': {\n" +" 'class': 'logging.StreamHandler',\n" +" 'level': 'INFO'\n" +" }\n" +" },\n" +" 'root': {\n" +" 'handlers': ['console'],\n" +" 'level': 'DEBUG'\n" +" }\n" +" }\n" +" # The worker process configuration is just a QueueHandler attached to " +"the\n" +" # root logger, which allows all messages to be sent to the queue.\n" +" # We disable existing loggers to disable the \"setup\" logger used in " +"the\n" +" # parent process. This is needed on POSIX because the logger will\n" +" # be there in the child following a fork().\n" +" config_worker = {\n" +" 'version': 1,\n" +" 'disable_existing_loggers': True,\n" +" 'handlers': {\n" +" 'queue': {\n" +" 'class': 'logging.handlers.QueueHandler',\n" +" 'queue': q\n" +" }\n" +" },\n" +" 'root': {\n" +" 'handlers': ['queue'],\n" +" 'level': 'DEBUG'\n" +" }\n" +" }\n" +" # The listener process configuration shows that the full flexibility of\n" +" # logging configuration is available to dispatch events to handlers " +"however\n" +" # you want.\n" +" # We disable existing loggers to disable the \"setup\" logger used in " +"the\n" +" # parent process. This is needed on POSIX because the logger will\n" +" # be there in the child following a fork().\n" +" config_listener = {\n" +" 'version': 1,\n" +" 'disable_existing_loggers': True,\n" +" 'formatters': {\n" +" 'detailed': {\n" +" 'class': 'logging.Formatter',\n" +" 'format': '%(asctime)s %(name)-15s %(levelname)-8s " +"%(processName)-10s %(message)s'\n" +" },\n" +" 'simple': {\n" +" 'class': 'logging.Formatter',\n" +" 'format': '%(name)-15s %(levelname)-8s %(processName)-10s " +"%(message)s'\n" +" }\n" +" },\n" +" 'handlers': {\n" +" 'console': {\n" +" 'class': 'logging.StreamHandler',\n" +" 'formatter': 'simple',\n" +" 'level': 'INFO'\n" +" },\n" +" 'file': {\n" +" 'class': 'logging.FileHandler',\n" +" 'filename': 'mplog.log',\n" +" 'mode': 'w',\n" +" 'formatter': 'detailed'\n" +" },\n" +" 'foofile': {\n" +" 'class': 'logging.FileHandler',\n" +" 'filename': 'mplog-foo.log',\n" +" 'mode': 'w',\n" +" 'formatter': 'detailed'\n" +" },\n" +" 'errors': {\n" +" 'class': 'logging.FileHandler',\n" +" 'filename': 'mplog-errors.log',\n" +" 'mode': 'w',\n" +" 'formatter': 'detailed',\n" +" 'level': 'ERROR'\n" +" }\n" +" },\n" +" 'loggers': {\n" +" 'foo': {\n" +" 'handlers': ['foofile']\n" +" }\n" +" },\n" +" 'root': {\n" +" 'handlers': ['console', 'file', 'errors'],\n" +" 'level': 'DEBUG'\n" +" }\n" +" }\n" +" # Log some initial events, just to show that logging in the parent " +"works\n" +" # normally.\n" +" logging.config.dictConfig(config_initial)\n" +" logger = logging.getLogger('setup')\n" +" logger.info('About to create workers ...')\n" +" workers = []\n" +" for i in range(5):\n" +" wp = Process(target=worker_process, name='worker %d' % (i + 1),\n" +" args=(config_worker,))\n" +" workers.append(wp)\n" +" wp.start()\n" +" logger.info('Started worker: %s', wp.name)\n" +" logger.info('About to create listener ...')\n" +" stop_event = Event()\n" +" lp = Process(target=listener_process, name='listener',\n" +" args=(q, stop_event, config_listener))\n" +" lp.start()\n" +" logger.info('Started listener')\n" +" # We now hang around for the workers to finish their work.\n" +" for wp in workers:\n" +" wp.join()\n" +" # Workers all done, listening can now stop.\n" +" # Logging in the parent still works normally.\n" +" logger.info('Telling listener to stop ...')\n" +" stop_event.set()\n" +" lp.join()\n" +" logger.info('All done.')\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2445 msgid "Inserting a BOM into messages sent to a SysLogHandler" msgstr "" -#: ../../howto/logging-cookbook.rst:2437 +#: ../../howto/logging-cookbook.rst:2447 msgid "" ":rfc:`5424` requires that a Unicode message be sent to a syslog daemon as a " "set of bytes which have the following structure: an optional pure-ASCII " @@ -1187,7 +3244,7 @@ msgid "" "<5424#section-6>`.)" msgstr "" -#: ../../howto/logging-cookbook.rst:2443 +#: ../../howto/logging-cookbook.rst:2453 msgid "" "In Python 3.1, code was added to :class:`~logging.handlers.SysLogHandler` to " "insert a BOM into the message, but unfortunately, it was implemented " @@ -1195,7 +3252,7 @@ msgid "" "hence not allowing any pure-ASCII component to appear before it." msgstr "" -#: ../../howto/logging-cookbook.rst:2449 +#: ../../howto/logging-cookbook.rst:2459 msgid "" "As this behaviour is broken, the incorrect BOM insertion code is being " "removed from Python 3.2.4 and later. However, it is not being replaced, and " @@ -1204,33 +3261,37 @@ msgid "" "encoded using UTF-8, then you need to do the following:" msgstr "" -#: ../../howto/logging-cookbook.rst:2455 +#: ../../howto/logging-cookbook.rst:2465 msgid "" "Attach a :class:`~logging.Formatter` instance to your :class:`~logging." "handlers.SysLogHandler` instance, with a format string such as::" msgstr "" -#: ../../howto/logging-cookbook.rst:2461 +#: ../../howto/logging-cookbook.rst:2469 +msgid "'ASCII section\\ufeffUnicode section'" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2471 msgid "" "The Unicode code point U+FEFF, when encoded using UTF-8, will be encoded as " "a UTF-8 BOM -- the byte-string ``b'\\xef\\xbb\\xbf'``." msgstr "" -#: ../../howto/logging-cookbook.rst:2464 +#: ../../howto/logging-cookbook.rst:2474 msgid "" "Replace the ASCII section with whatever placeholders you like, but make sure " "that the data that appears in there after substitution is always ASCII (that " "way, it will remain unchanged after UTF-8 encoding)." msgstr "" -#: ../../howto/logging-cookbook.rst:2468 +#: ../../howto/logging-cookbook.rst:2478 msgid "" "Replace the Unicode section with whatever placeholders you like; if the data " "which appears there after substitution contains characters outside the ASCII " "range, that's fine -- it will be encoded using UTF-8." msgstr "" -#: ../../howto/logging-cookbook.rst:2472 +#: ../../howto/logging-cookbook.rst:2482 msgid "" "The formatted message *will* be encoded using UTF-8 encoding by " "``SysLogHandler``. If you follow the above rules, you should be able to " @@ -1239,11 +3300,11 @@ msgid "" "daemon may complain." msgstr "" -#: ../../howto/logging-cookbook.rst:2479 +#: ../../howto/logging-cookbook.rst:2489 msgid "Implementing structured logging" msgstr "" -#: ../../howto/logging-cookbook.rst:2481 +#: ../../howto/logging-cookbook.rst:2491 msgid "" "Although most logging messages are intended for reading by humans, and thus " "not readily machine-parseable, there might be circumstances where you want " @@ -1255,31 +3316,93 @@ msgid "" "machine-parseable manner::" msgstr "" -#: ../../howto/logging-cookbook.rst:2505 +#: ../../howto/logging-cookbook.rst:2499 +msgid "" +"import json\n" +"import logging\n" +"\n" +"class StructuredMessage:\n" +" def __init__(self, message, /, **kwargs):\n" +" self.message = message\n" +" self.kwargs = kwargs\n" +"\n" +" def __str__(self):\n" +" return '%s >>> %s' % (self.message, json.dumps(self.kwargs))\n" +"\n" +"_ = StructuredMessage # optional, to improve readability\n" +"\n" +"logging.basicConfig(level=logging.INFO, format='%(message)s')\n" +"logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2515 msgid "If the above script is run, it prints:" msgstr "" -#: ../../howto/logging-cookbook.rst:2511 ../../howto/logging-cookbook.rst:2553 +#: ../../howto/logging-cookbook.rst:2517 +msgid "" +"message 1 >>> {\"fnum\": 123.456, \"num\": 123, \"bar\": \"baz\", \"foo\": " +"\"bar\"}" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2521 ../../howto/logging-cookbook.rst:2563 msgid "" "Note that the order of items might be different according to the version of " "Python used." msgstr "" -#: ../../howto/logging-cookbook.rst:2514 +#: ../../howto/logging-cookbook.rst:2524 msgid "" "If you need more specialised processing, you can use a custom JSON encoder, " "as in the following complete example::" msgstr "" -#: ../../howto/logging-cookbook.rst:2547 +#: ../../howto/logging-cookbook.rst:2527 +msgid "" +"import json\n" +"import logging\n" +"\n" +"\n" +"class Encoder(json.JSONEncoder):\n" +" def default(self, o):\n" +" if isinstance(o, set):\n" +" return tuple(o)\n" +" elif isinstance(o, str):\n" +" return o.encode('unicode_escape').decode('ascii')\n" +" return super().default(o)\n" +"\n" +"class StructuredMessage:\n" +" def __init__(self, message, /, **kwargs):\n" +" self.message = message\n" +" self.kwargs = kwargs\n" +"\n" +" def __str__(self):\n" +" s = Encoder().encode(self.kwargs)\n" +" return '%s >>> %s' % (self.message, s)\n" +"\n" +"_ = StructuredMessage # optional, to improve readability\n" +"\n" +"def main():\n" +" logging.basicConfig(level=logging.INFO, format='%(message)s')\n" +" logging.info(_('message 1', set_value={1, 2, 3}, snowman='\\u2603'))\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2557 msgid "When the above script is run, it prints:" msgstr "" -#: ../../howto/logging-cookbook.rst:2562 +#: ../../howto/logging-cookbook.rst:2559 +msgid "message 1 >>> {\"snowman\": \"\\u2603\", \"set_value\": [1, 2, 3]}" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2572 msgid "Customizing handlers with :func:`dictConfig`" msgstr "" -#: ../../howto/logging-cookbook.rst:2564 +#: ../../howto/logging-cookbook.rst:2574 msgid "" "There are times when you want to customize logging handlers in particular " "ways, and if you use :func:`dictConfig` you may be able to do this without " @@ -1289,24 +3412,122 @@ msgid "" "customize handler creation using a plain function such as::" msgstr "" -#: ../../howto/logging-cookbook.rst:2578 +#: ../../howto/logging-cookbook.rst:2581 +msgid "" +"def owned_file_handler(filename, mode='a', encoding=None, owner=None):\n" +" if owner:\n" +" if not os.path.exists(filename):\n" +" open(filename, 'a').close()\n" +" shutil.chown(filename, *owner)\n" +" return logging.FileHandler(filename, mode, encoding)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2588 msgid "" "You can then specify, in a logging configuration passed to :func:" "`dictConfig`, that a logging handler be created by calling this function::" msgstr "" -#: ../../howto/logging-cookbook.rst:2611 +#: ../../howto/logging-cookbook.rst:2591 +msgid "" +"LOGGING = {\n" +" 'version': 1,\n" +" 'disable_existing_loggers': False,\n" +" 'formatters': {\n" +" 'default': {\n" +" 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'\n" +" },\n" +" },\n" +" 'handlers': {\n" +" 'file':{\n" +" # The values below are popped from this dictionary and\n" +" # used to create the handler, set the handler's level and\n" +" # its formatter.\n" +" '()': owned_file_handler,\n" +" 'level':'DEBUG',\n" +" 'formatter': 'default',\n" +" # The values below are passed to the handler creator callable\n" +" # as keyword arguments.\n" +" 'owner': ['pulse', 'pulse'],\n" +" 'filename': 'chowntest.log',\n" +" 'mode': 'w',\n" +" 'encoding': 'utf-8',\n" +" },\n" +" },\n" +" 'root': {\n" +" 'handlers': ['file'],\n" +" 'level': 'DEBUG',\n" +" },\n" +"}" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2621 msgid "" "In this example I am setting the ownership using the ``pulse`` user and " "group, just for the purposes of illustration. Putting it together into a " "working script, ``chowntest.py``::" msgstr "" -#: ../../howto/logging-cookbook.rst:2658 -msgid "To run this, you will probably need to run as ``root``:" +#: ../../howto/logging-cookbook.rst:2625 +msgid "" +"import logging, logging.config, os, shutil\n" +"\n" +"def owned_file_handler(filename, mode='a', encoding=None, owner=None):\n" +" if owner:\n" +" if not os.path.exists(filename):\n" +" open(filename, 'a').close()\n" +" shutil.chown(filename, *owner)\n" +" return logging.FileHandler(filename, mode, encoding)\n" +"\n" +"LOGGING = {\n" +" 'version': 1,\n" +" 'disable_existing_loggers': False,\n" +" 'formatters': {\n" +" 'default': {\n" +" 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'\n" +" },\n" +" },\n" +" 'handlers': {\n" +" 'file':{\n" +" # The values below are popped from this dictionary and\n" +" # used to create the handler, set the handler's level and\n" +" # its formatter.\n" +" '()': owned_file_handler,\n" +" 'level':'DEBUG',\n" +" 'formatter': 'default',\n" +" # The values below are passed to the handler creator callable\n" +" # as keyword arguments.\n" +" 'owner': ['pulse', 'pulse'],\n" +" 'filename': 'chowntest.log',\n" +" 'mode': 'w',\n" +" 'encoding': 'utf-8',\n" +" },\n" +" },\n" +" 'root': {\n" +" 'handlers': ['file'],\n" +" 'level': 'DEBUG',\n" +" },\n" +"}\n" +"\n" +"logging.config.dictConfig(LOGGING)\n" +"logger = logging.getLogger('mylogger')\n" +"logger.debug('A debug message')" msgstr "" #: ../../howto/logging-cookbook.rst:2668 +msgid "To run this, you will probably need to run as ``root``:" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2670 +msgid "" +"$ sudo python3.3 chowntest.py\n" +"$ cat chowntest.log\n" +"2013-11-05 09:34:51,128 DEBUG mylogger A debug message\n" +"$ ls -l chowntest.log\n" +"-rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2678 msgid "" "Note that this example uses Python 3.3 because that's where :func:`shutil." "chown` makes an appearance. This approach should work with any Python " @@ -1315,17 +3536,25 @@ msgid "" "change using e.g. :func:`os.chown`." msgstr "" -#: ../../howto/logging-cookbook.rst:2674 +#: ../../howto/logging-cookbook.rst:2684 msgid "" "In practice, the handler-creating function may be in a utility module " "somewhere in your project. Instead of the line in the configuration::" msgstr "" -#: ../../howto/logging-cookbook.rst:2679 +#: ../../howto/logging-cookbook.rst:2687 +msgid "'()': owned_file_handler," +msgstr "" + +#: ../../howto/logging-cookbook.rst:2689 msgid "you could use e.g.::" msgstr "" -#: ../../howto/logging-cookbook.rst:2683 +#: ../../howto/logging-cookbook.rst:2691 +msgid "'()': 'ext://project.util.owned_file_handler'," +msgstr "" + +#: ../../howto/logging-cookbook.rst:2693 msgid "" "where ``project.util`` can be replaced with the actual name of the package " "where the function resides. In the above working script, using ``'ext://" @@ -1333,25 +3562,25 @@ msgid "" "resolved by :func:`dictConfig` from the ``ext://`` specification." msgstr "" -#: ../../howto/logging-cookbook.rst:2688 +#: ../../howto/logging-cookbook.rst:2698 msgid "" "This example hopefully also points the way to how you could implement other " "types of file change - e.g. setting specific POSIX permission bits - in the " "same way, using :func:`os.chmod`." msgstr "" -#: ../../howto/logging-cookbook.rst:2692 +#: ../../howto/logging-cookbook.rst:2702 msgid "" "Of course, the approach could also be extended to types of handler other " "than a :class:`~logging.FileHandler` - for example, one of the rotating file " "handlers, or a different type of handler altogether." msgstr "" -#: ../../howto/logging-cookbook.rst:2702 +#: ../../howto/logging-cookbook.rst:2712 msgid "Using particular formatting styles throughout your application" msgstr "" -#: ../../howto/logging-cookbook.rst:2704 +#: ../../howto/logging-cookbook.rst:2714 msgid "" "In Python 3.2, the :class:`~logging.Formatter` gained a ``style`` keyword " "parameter which, while defaulting to ``%`` for backward compatibility, " @@ -1362,7 +3591,7 @@ msgid "" "is constructed." msgstr "" -#: ../../howto/logging-cookbook.rst:2711 +#: ../../howto/logging-cookbook.rst:2721 msgid "" "Logging calls (:meth:`~Logger.debug`, :meth:`~Logger.info` etc.) only take " "positional parameters for the actual logging message itself, with keyword " @@ -1377,7 +3606,7 @@ msgid "" "calls which are out there in existing code will be using %-format strings." msgstr "" -#: ../../howto/logging-cookbook.rst:2723 +#: ../../howto/logging-cookbook.rst:2733 msgid "" "There have been suggestions to associate format styles with specific " "loggers, but that approach also runs into backward compatibility problems " @@ -1385,7 +3614,7 @@ msgid "" "formatting." msgstr "" -#: ../../howto/logging-cookbook.rst:2727 +#: ../../howto/logging-cookbook.rst:2737 msgid "" "For logging to work interoperably between any third-party libraries and your " "code, decisions about formatting need to be made at the level of the " @@ -1393,11 +3622,11 @@ msgid "" "formatting styles can be accommodated." msgstr "" -#: ../../howto/logging-cookbook.rst:2734 +#: ../../howto/logging-cookbook.rst:2744 msgid "Using LogRecord factories" msgstr "" -#: ../../howto/logging-cookbook.rst:2736 +#: ../../howto/logging-cookbook.rst:2746 msgid "" "In Python 3.2, along with the :class:`~logging.Formatter` changes mentioned " "above, the logging package gained the ability to allow users to set their " @@ -1412,17 +3641,17 @@ msgid "" "implementation does." msgstr "" -#: ../../howto/logging-cookbook.rst:2747 +#: ../../howto/logging-cookbook.rst:2757 msgid "" "Refer to the reference documentation on :func:`setLogRecordFactory` and :" "class:`LogRecord` for more information." msgstr "" -#: ../../howto/logging-cookbook.rst:2752 +#: ../../howto/logging-cookbook.rst:2762 msgid "Using custom message objects" msgstr "" -#: ../../howto/logging-cookbook.rst:2754 +#: ../../howto/logging-cookbook.rst:2764 msgid "" "There is another, perhaps simpler way that you can use {}- and $- formatting " "to construct your individual log messages. You may recall (from :ref:" @@ -1432,7 +3661,7 @@ msgid "" "following two classes::" msgstr "" -#: ../../howto/logging-cookbook.rst:2779 +#: ../../howto/logging-cookbook.rst:2789 msgid "" "Either of these can be used in place of a format string, to allow {}- or $-" "formatting to be used to build the actual \"message\" part which appears in " @@ -1443,17 +3672,40 @@ msgid "" "using ``_`` for localization)." msgstr "" -#: ../../howto/logging-cookbook.rst:2787 +#: ../../howto/logging-cookbook.rst:2797 msgid "" "Examples of this approach are given below. Firstly, formatting with :meth:" "`str.format`::" msgstr "" -#: ../../howto/logging-cookbook.rst:2801 +#: ../../howto/logging-cookbook.rst:2800 +msgid "" +">>> __ = BraceMessage\n" +">>> print(__('Message with {0} {1}', 2, 'placeholders'))\n" +"Message with 2 placeholders\n" +">>> class Point: pass\n" +"...\n" +">>> p = Point()\n" +">>> p.x = 0.5\n" +">>> p.y = 0.5\n" +">>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', " +"point=p))\n" +"Message with coordinates: (0.50, 0.50)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2811 msgid "Secondly, formatting with :class:`string.Template`::" msgstr "" -#: ../../howto/logging-cookbook.rst:2808 +#: ../../howto/logging-cookbook.rst:2813 +msgid "" +">>> __ = DollarMessage\n" +">>> print(__('Message with $num $what', num=2, what='placeholders'))\n" +"Message with 2 placeholders\n" +">>>" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2818 msgid "" "One thing to note is that you pay no significant performance penalty with " "this approach: the actual formatting happens not when you make the logging " @@ -1465,11 +3717,11 @@ msgid "" "shown above." msgstr "" -#: ../../howto/logging-cookbook.rst:2822 +#: ../../howto/logging-cookbook.rst:2832 msgid "Configuring filters with :func:`dictConfig`" msgstr "" -#: ../../howto/logging-cookbook.rst:2824 +#: ../../howto/logging-cookbook.rst:2834 msgid "" "You *can* configure filters using :func:`~logging.config.dictConfig`, though " "it might not be obvious at first glance how to do it (hence this recipe). " @@ -1484,22 +3736,71 @@ msgid "" "complete example::" msgstr "" -#: ../../howto/logging-cookbook.rst:2877 +#: ../../howto/logging-cookbook.rst:2845 +msgid "" +"import logging\n" +"import logging.config\n" +"import sys\n" +"\n" +"class MyFilter(logging.Filter):\n" +" def __init__(self, param=None):\n" +" self.param = param\n" +"\n" +" def filter(self, record):\n" +" if self.param is None:\n" +" allow = True\n" +" else:\n" +" allow = self.param not in record.msg\n" +" if allow:\n" +" record.msg = 'changed: ' + record.msg\n" +" return allow\n" +"\n" +"LOGGING = {\n" +" 'version': 1,\n" +" 'filters': {\n" +" 'myfilter': {\n" +" '()': MyFilter,\n" +" 'param': 'noshow',\n" +" }\n" +" },\n" +" 'handlers': {\n" +" 'console': {\n" +" 'class': 'logging.StreamHandler',\n" +" 'filters': ['myfilter']\n" +" }\n" +" },\n" +" 'root': {\n" +" 'level': 'DEBUG',\n" +" 'handlers': ['console']\n" +" },\n" +"}\n" +"\n" +"if __name__ == '__main__':\n" +" logging.config.dictConfig(LOGGING)\n" +" logging.debug('hello')\n" +" logging.debug('hello - noshow')" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2887 msgid "" "This example shows how you can pass configuration data to the callable which " "constructs the instance, in the form of keyword parameters. When run, the " "above script will print:" msgstr "" -#: ../../howto/logging-cookbook.rst:2885 +#: ../../howto/logging-cookbook.rst:2891 +msgid "changed: hello" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2895 msgid "which shows that the filter is working as configured." msgstr "" -#: ../../howto/logging-cookbook.rst:2887 +#: ../../howto/logging-cookbook.rst:2897 msgid "A couple of extra points to note:" msgstr "" -#: ../../howto/logging-cookbook.rst:2889 +#: ../../howto/logging-cookbook.rst:2899 msgid "" "If you can't refer to the callable directly in the configuration (e.g. if it " "lives in a different module, and you can't import it directly where the " @@ -1509,7 +3810,7 @@ msgid "" "the above example." msgstr "" -#: ../../howto/logging-cookbook.rst:2896 +#: ../../howto/logging-cookbook.rst:2906 msgid "" "As well as for filters, this technique can also be used to configure custom " "handlers and formatters. See :ref:`logging-config-dict-userdef` for more " @@ -1518,11 +3819,11 @@ msgid "" "above." msgstr "" -#: ../../howto/logging-cookbook.rst:2905 +#: ../../howto/logging-cookbook.rst:2915 msgid "Customized exception formatting" msgstr "" -#: ../../howto/logging-cookbook.rst:2907 +#: ../../howto/logging-cookbook.rst:2917 msgid "" "There might be times when you want to do customized exception formatting - " "for argument's sake, let's say you want exactly one line per logged event, " @@ -1530,22 +3831,70 @@ msgid "" "formatter class, as shown in the following example::" msgstr "" -#: ../../howto/logging-cookbook.rst:2948 +#: ../../howto/logging-cookbook.rst:2922 +msgid "" +"import logging\n" +"\n" +"class OneLineExceptionFormatter(logging.Formatter):\n" +" def formatException(self, exc_info):\n" +" \"\"\"\n" +" Format an exception so that it prints on a single line.\n" +" \"\"\"\n" +" result = super().formatException(exc_info)\n" +" return repr(result) # or format into one line however you want to\n" +"\n" +" def format(self, record):\n" +" s = super().format(record)\n" +" if record.exc_text:\n" +" s = s.replace('\\n', '') + '|'\n" +" return s\n" +"\n" +"def configure_logging():\n" +" fh = logging.FileHandler('output.txt', 'w')\n" +" f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|',\n" +" '%d/%m/%Y %H:%M:%S')\n" +" fh.setFormatter(f)\n" +" root = logging.getLogger()\n" +" root.setLevel(logging.DEBUG)\n" +" root.addHandler(fh)\n" +"\n" +"def main():\n" +" configure_logging()\n" +" logging.info('Sample message')\n" +" try:\n" +" x = 1 / 0\n" +" except ZeroDivisionError as e:\n" +" logging.exception('ZeroDivisionError: %s', e)\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2958 msgid "When run, this produces a file with exactly two lines:" msgstr "" -#: ../../howto/logging-cookbook.rst:2955 +#: ../../howto/logging-cookbook.rst:2960 +msgid "" +"28/01/2015 07:21:23|INFO|Sample message|\n" +"28/01/2015 07:21:23|ERROR|ZeroDivisionError: integer division or modulo by " +"zero|'Traceback (most recent call last):\\n File \"logtest7.py\", line 30, " +"in main\\n x = 1 / 0\\nZeroDivisionError: integer division or modulo by " +"zero'|" +msgstr "" + +#: ../../howto/logging-cookbook.rst:2965 msgid "" "While the above treatment is simplistic, it points the way to how exception " "information can be formatted to your liking. The :mod:`traceback` module may " "be helpful for more specialized needs." msgstr "" -#: ../../howto/logging-cookbook.rst:2962 +#: ../../howto/logging-cookbook.rst:2972 msgid "Speaking logging messages" msgstr "" -#: ../../howto/logging-cookbook.rst:2964 +#: ../../howto/logging-cookbook.rst:2974 msgid "" "There might be situations when it is desirable to have logging messages " "rendered in an audible rather than a visible format. This is easy to do if " @@ -1562,24 +3911,56 @@ msgid "" "approach, which assumes that the ``espeak`` TTS package is available::" msgstr "" -#: ../../howto/logging-cookbook.rst:3006 +#: ../../howto/logging-cookbook.rst:2987 +msgid "" +"import logging\n" +"import subprocess\n" +"import sys\n" +"\n" +"class TTSHandler(logging.Handler):\n" +" def emit(self, record):\n" +" msg = self.format(record)\n" +" # Speak slowly in a female English voice\n" +" cmd = ['espeak', '-s150', '-ven+f3', msg]\n" +" p = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n" +" stderr=subprocess.STDOUT)\n" +" # wait for the program to finish\n" +" p.communicate()\n" +"\n" +"def configure_logging():\n" +" h = TTSHandler()\n" +" root = logging.getLogger()\n" +" root.addHandler(h)\n" +" # the default formatter just returns the message\n" +" root.setLevel(logging.DEBUG)\n" +"\n" +"def main():\n" +" logging.info('Hello')\n" +" logging.debug('Goodbye')\n" +"\n" +"if __name__ == '__main__':\n" +" configure_logging()\n" +" sys.exit(main())" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3016 msgid "" "When run, this script should say \"Hello\" and then \"Goodbye\" in a female " "voice." msgstr "" -#: ../../howto/logging-cookbook.rst:3008 +#: ../../howto/logging-cookbook.rst:3018 msgid "" "The above approach can, of course, be adapted to other TTS systems and even " "other systems altogether which can process messages via external programs " "run from a command line." msgstr "" -#: ../../howto/logging-cookbook.rst:3016 +#: ../../howto/logging-cookbook.rst:3026 msgid "Buffering logging messages and outputting them conditionally" msgstr "" -#: ../../howto/logging-cookbook.rst:3018 +#: ../../howto/logging-cookbook.rst:3028 msgid "" "There might be situations where you want to log messages in a temporary area " "and only output them if a certain condition occurs. For example, you may " @@ -1589,7 +3970,7 @@ msgid "" "debug information to be output as well as the error." msgstr "" -#: ../../howto/logging-cookbook.rst:3025 +#: ../../howto/logging-cookbook.rst:3035 msgid "" "Here is an example which shows how you could do this using a decorator for " "your functions where you want logging to behave this way. It makes use of " @@ -1602,7 +3983,7 @@ msgid "" "subclass of ``MemoryHandler`` if you want custom flushing behavior." msgstr "" -#: ../../howto/logging-cookbook.rst:3035 +#: ../../howto/logging-cookbook.rst:3045 msgid "" "The example script has a simple function, ``foo``, which just cycles through " "all the logging levels, writing to ``sys.stderr`` to say what level it's " @@ -1611,7 +3992,7 @@ msgid "" "levels - otherwise, it only logs at DEBUG, INFO and WARNING levels." msgstr "" -#: ../../howto/logging-cookbook.rst:3041 +#: ../../howto/logging-cookbook.rst:3051 msgid "" "The script just arranges to decorate ``foo`` with a decorator which will do " "the conditional logging that's required. The decorator takes a logger as a " @@ -1623,30 +4004,132 @@ msgid "" "respectively." msgstr "" -#: ../../howto/logging-cookbook.rst:3049 +#: ../../howto/logging-cookbook.rst:3059 msgid "Here's the script::" msgstr "" -#: ../../howto/logging-cookbook.rst:3112 +#: ../../howto/logging-cookbook.rst:3061 +msgid "" +"import logging\n" +"from logging.handlers import MemoryHandler\n" +"import sys\n" +"\n" +"logger = logging.getLogger(__name__)\n" +"logger.addHandler(logging.NullHandler())\n" +"\n" +"def log_if_errors(logger, target_handler=None, flush_level=None, " +"capacity=None):\n" +" if target_handler is None:\n" +" target_handler = logging.StreamHandler()\n" +" if flush_level is None:\n" +" flush_level = logging.ERROR\n" +" if capacity is None:\n" +" capacity = 100\n" +" handler = MemoryHandler(capacity, flushLevel=flush_level, " +"target=target_handler)\n" +"\n" +" def decorator(fn):\n" +" def wrapper(*args, **kwargs):\n" +" logger.addHandler(handler)\n" +" try:\n" +" return fn(*args, **kwargs)\n" +" except Exception:\n" +" logger.exception('call failed')\n" +" raise\n" +" finally:\n" +" super(MemoryHandler, handler).flush()\n" +" logger.removeHandler(handler)\n" +" return wrapper\n" +"\n" +" return decorator\n" +"\n" +"def write_line(s):\n" +" sys.stderr.write('%s\\n' % s)\n" +"\n" +"def foo(fail=False):\n" +" write_line('about to log at DEBUG ...')\n" +" logger.debug('Actually logged at DEBUG')\n" +" write_line('about to log at INFO ...')\n" +" logger.info('Actually logged at INFO')\n" +" write_line('about to log at WARNING ...')\n" +" logger.warning('Actually logged at WARNING')\n" +" if fail:\n" +" write_line('about to log at ERROR ...')\n" +" logger.error('Actually logged at ERROR')\n" +" write_line('about to log at CRITICAL ...')\n" +" logger.critical('Actually logged at CRITICAL')\n" +" return fail\n" +"\n" +"decorated_foo = log_if_errors(logger)(foo)\n" +"\n" +"if __name__ == '__main__':\n" +" logger.setLevel(logging.DEBUG)\n" +" write_line('Calling undecorated foo with False')\n" +" assert not foo(False)\n" +" write_line('Calling undecorated foo with True')\n" +" assert foo(True)\n" +" write_line('Calling decorated foo with False')\n" +" assert not decorated_foo(False)\n" +" write_line('Calling decorated foo with True')\n" +" assert decorated_foo(True)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3122 msgid "When this script is run, the following output should be observed:" msgstr "" -#: ../../howto/logging-cookbook.rst:3142 +#: ../../howto/logging-cookbook.rst:3124 +msgid "" +"Calling undecorated foo with False\n" +"about to log at DEBUG ...\n" +"about to log at INFO ...\n" +"about to log at WARNING ...\n" +"Calling undecorated foo with True\n" +"about to log at DEBUG ...\n" +"about to log at INFO ...\n" +"about to log at WARNING ...\n" +"about to log at ERROR ...\n" +"about to log at CRITICAL ...\n" +"Calling decorated foo with False\n" +"about to log at DEBUG ...\n" +"about to log at INFO ...\n" +"about to log at WARNING ...\n" +"Calling decorated foo with True\n" +"about to log at DEBUG ...\n" +"about to log at INFO ...\n" +"about to log at WARNING ...\n" +"about to log at ERROR ...\n" +"Actually logged at DEBUG\n" +"Actually logged at INFO\n" +"Actually logged at WARNING\n" +"Actually logged at ERROR\n" +"about to log at CRITICAL ...\n" +"Actually logged at CRITICAL" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3152 msgid "" "As you can see, actual logging output only occurs when an event is logged " "whose severity is ERROR or greater, but in that case, any previous events at " "lower severities are also logged." msgstr "" -#: ../../howto/logging-cookbook.rst:3146 +#: ../../howto/logging-cookbook.rst:3156 msgid "You can of course use the conventional means of decoration::" msgstr "" -#: ../../howto/logging-cookbook.rst:3156 +#: ../../howto/logging-cookbook.rst:3158 +msgid "" +"@log_if_errors(logger)\n" +"def foo(fail=False):\n" +" ..." +msgstr "" + +#: ../../howto/logging-cookbook.rst:3166 msgid "Sending logging messages to email, with buffering" msgstr "" -#: ../../howto/logging-cookbook.rst:3158 +#: ../../howto/logging-cookbook.rst:3168 msgid "" "To illustrate how you can send log messages via email, so that a set number " "of messages are sent per email, you can subclass :class:`~logging.handlers." @@ -1657,7 +4140,75 @@ msgid "" "argument to see the required and optional arguments.)" msgstr "" -#: ../../howto/logging-cookbook.rst:3230 +#: ../../howto/logging-cookbook.rst:3176 +msgid "" +"import logging\n" +"import logging.handlers\n" +"import smtplib\n" +"\n" +"class BufferingSMTPHandler(logging.handlers.BufferingHandler):\n" +" def __init__(self, mailhost, port, username, password, fromaddr, " +"toaddrs,\n" +" subject, capacity):\n" +" logging.handlers.BufferingHandler.__init__(self, capacity)\n" +" self.mailhost = mailhost\n" +" self.mailport = port\n" +" self.username = username\n" +" self.password = password\n" +" self.fromaddr = fromaddr\n" +" if isinstance(toaddrs, str):\n" +" toaddrs = [toaddrs]\n" +" self.toaddrs = toaddrs\n" +" self.subject = subject\n" +" self.setFormatter(logging.Formatter(\"%(asctime)s %(levelname)-5s " +"%(message)s\"))\n" +"\n" +" def flush(self):\n" +" if len(self.buffer) > 0:\n" +" try:\n" +" smtp = smtplib.SMTP(self.mailhost, self.mailport)\n" +" smtp.starttls()\n" +" smtp.login(self.username, self.password)\n" +" msg = \"From: %s\\r\\nTo: %s\\r\\nSubject: %s\\r\\n\\r\\n\" " +"% (self.fromaddr, ','.join(self.toaddrs), self.subject)\n" +" for record in self.buffer:\n" +" s = self.format(record)\n" +" msg = msg + s + \"\\r\\n\"\n" +" smtp.sendmail(self.fromaddr, self.toaddrs, msg)\n" +" smtp.quit()\n" +" except Exception:\n" +" if logging.raiseExceptions:\n" +" raise\n" +" self.buffer = []\n" +"\n" +"if __name__ == '__main__':\n" +" import argparse\n" +"\n" +" ap = argparse.ArgumentParser()\n" +" aa = ap.add_argument\n" +" aa('host', metavar='HOST', help='SMTP server')\n" +" aa('--port', '-p', type=int, default=587, help='SMTP port')\n" +" aa('user', metavar='USER', help='SMTP username')\n" +" aa('password', metavar='PASSWORD', help='SMTP password')\n" +" aa('to', metavar='TO', help='Addressee for emails')\n" +" aa('sender', metavar='SENDER', help='Sender email address')\n" +" aa('--subject', '-s',\n" +" default='Test Logging email from Python logging module (buffering)',\n" +" help='Subject of email')\n" +" options = ap.parse_args()\n" +" logger = logging.getLogger()\n" +" logger.setLevel(logging.DEBUG)\n" +" h = BufferingSMTPHandler(options.host, options.port, options.user,\n" +" options.password, options.sender,\n" +" options.to, options.subject, 10)\n" +" logger.addHandler(h)\n" +" for i in range(102):\n" +" logger.info(\"Info index = %d\", i)\n" +" h.flush()\n" +" h.close()" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3240 msgid "" "If you run this script and your SMTP server is correctly set up, you should " "find that it sends eleven emails to the addressee you specify. The first ten " @@ -1665,17 +4216,26 @@ msgid "" "messages. That makes up 102 messages as specified in the script." msgstr "" -#: ../../howto/logging-cookbook.rst:3238 +#: ../../howto/logging-cookbook.rst:3248 msgid "Formatting times using UTC (GMT) via configuration" msgstr "" -#: ../../howto/logging-cookbook.rst:3240 +#: ../../howto/logging-cookbook.rst:3250 msgid "" "Sometimes you want to format times using UTC, which can be done using a " "class such as ``UTCFormatter``, shown below::" msgstr "" -#: ../../howto/logging-cookbook.rst:3249 +#: ../../howto/logging-cookbook.rst:3253 +msgid "" +"import logging\n" +"import time\n" +"\n" +"class UTCFormatter(logging.Formatter):\n" +" converter = time.gmtime" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3259 msgid "" "and you can then use the ``UTCFormatter`` in your code instead of :class:" "`~logging.Formatter`. If you want to do that via configuration, you can use " @@ -1683,21 +4243,68 @@ msgid "" "the following complete example::" msgstr "" -#: ../../howto/logging-cookbook.rst:3292 +#: ../../howto/logging-cookbook.rst:3264 +msgid "" +"import logging\n" +"import logging.config\n" +"import time\n" +"\n" +"class UTCFormatter(logging.Formatter):\n" +" converter = time.gmtime\n" +"\n" +"LOGGING = {\n" +" 'version': 1,\n" +" 'disable_existing_loggers': False,\n" +" 'formatters': {\n" +" 'utc': {\n" +" '()': UTCFormatter,\n" +" 'format': '%(asctime)s %(message)s',\n" +" },\n" +" 'local': {\n" +" 'format': '%(asctime)s %(message)s',\n" +" }\n" +" },\n" +" 'handlers': {\n" +" 'console1': {\n" +" 'class': 'logging.StreamHandler',\n" +" 'formatter': 'utc',\n" +" },\n" +" 'console2': {\n" +" 'class': 'logging.StreamHandler',\n" +" 'formatter': 'local',\n" +" },\n" +" },\n" +" 'root': {\n" +" 'handlers': ['console1', 'console2'],\n" +" }\n" +"}\n" +"\n" +"if __name__ == '__main__':\n" +" logging.config.dictConfig(LOGGING)\n" +" logging.warning('The local time is %s', time.asctime())" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3302 msgid "When this script is run, it should print something like:" msgstr "" -#: ../../howto/logging-cookbook.rst:3299 +#: ../../howto/logging-cookbook.rst:3304 +msgid "" +"2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015\n" +"2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3309 msgid "" "showing how the time is formatted both as local time and UTC, one for each " "handler." msgstr "" -#: ../../howto/logging-cookbook.rst:3306 +#: ../../howto/logging-cookbook.rst:3316 msgid "Using a context manager for selective logging" msgstr "" -#: ../../howto/logging-cookbook.rst:3308 +#: ../../howto/logging-cookbook.rst:3318 msgid "" "There are times when it would be useful to temporarily change the logging " "configuration and revert it back after doing something. For this, a context " @@ -1707,7 +4314,36 @@ msgid "" "scope of the context manager::" msgstr "" -#: ../../howto/logging-cookbook.rst:3341 +#: ../../howto/logging-cookbook.rst:3325 +msgid "" +"import logging\n" +"import sys\n" +"\n" +"class LoggingContext:\n" +" def __init__(self, logger, level=None, handler=None, close=True):\n" +" self.logger = logger\n" +" self.level = level\n" +" self.handler = handler\n" +" self.close = close\n" +"\n" +" def __enter__(self):\n" +" if self.level is not None:\n" +" self.old_level = self.logger.level\n" +" self.logger.setLevel(self.level)\n" +" if self.handler:\n" +" self.logger.addHandler(self.handler)\n" +"\n" +" def __exit__(self, et, ev, tb):\n" +" if self.level is not None:\n" +" self.logger.setLevel(self.old_level)\n" +" if self.handler:\n" +" self.logger.removeHandler(self.handler)\n" +" if self.handler and self.close:\n" +" self.handler.close()\n" +" # implicit return of None => don't swallow exceptions" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3351 msgid "" "If you specify a level value, the logger's level is set to that value in the " "scope of the with block covered by the context manager. If you specify a " @@ -1716,13 +4352,33 @@ msgid "" "block exit - you could do this if you don't need the handler any more." msgstr "" -#: ../../howto/logging-cookbook.rst:3347 +#: ../../howto/logging-cookbook.rst:3357 msgid "" "To illustrate how it works, we can add the following block of code to the " "above::" msgstr "" -#: ../../howto/logging-cookbook.rst:3365 +#: ../../howto/logging-cookbook.rst:3360 +msgid "" +"if __name__ == '__main__':\n" +" logger = logging.getLogger('foo')\n" +" logger.addHandler(logging.StreamHandler())\n" +" logger.setLevel(logging.INFO)\n" +" logger.info('1. This should appear just once on stderr.')\n" +" logger.debug('2. This should not appear.')\n" +" with LoggingContext(logger, level=logging.DEBUG):\n" +" logger.debug('3. This should appear once on stderr.')\n" +" logger.debug('4. This should not appear.')\n" +" h = logging.StreamHandler(sys.stdout)\n" +" with LoggingContext(logger, level=logging.DEBUG, handler=h, " +"close=True):\n" +" logger.debug('5. This should appear twice - once on stderr and once " +"on stdout.')\n" +" logger.info('6. This should appear just once on stderr.')\n" +" logger.debug('7. This should not appear.')" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3375 msgid "" "We initially set the logger's level to ``INFO``, so message #1 appears and " "message #2 doesn't. We then change the level to ``DEBUG`` temporarily in the " @@ -1735,56 +4391,81 @@ msgid "" "(like message #1) whereas message #7 doesn't (just like message #2)." msgstr "" -#: ../../howto/logging-cookbook.rst:3375 +#: ../../howto/logging-cookbook.rst:3385 msgid "If we run the resulting script, the result is as follows:" msgstr "" -#: ../../howto/logging-cookbook.rst:3386 +#: ../../howto/logging-cookbook.rst:3387 +msgid "" +"$ python logctx.py\n" +"1. This should appear just once on stderr.\n" +"3. This should appear once on stderr.\n" +"5. This should appear twice - once on stderr and once on stdout.\n" +"5. This should appear twice - once on stderr and once on stdout.\n" +"6. This should appear just once on stderr." +msgstr "" + +#: ../../howto/logging-cookbook.rst:3396 msgid "" "If we run it again, but pipe ``stderr`` to ``/dev/null``, we see the " "following, which is the only message written to ``stdout``:" msgstr "" -#: ../../howto/logging-cookbook.rst:3394 -msgid "Once again, but piping ``stdout`` to ``/dev/null``, we get:" +#: ../../howto/logging-cookbook.rst:3399 +msgid "" +"$ python logctx.py 2>/dev/null\n" +"5. This should appear twice - once on stderr and once on stdout." msgstr "" #: ../../howto/logging-cookbook.rst:3404 +msgid "Once again, but piping ``stdout`` to ``/dev/null``, we get:" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3406 +msgid "" +"$ python logctx.py >/dev/null\n" +"1. This should appear just once on stderr.\n" +"3. This should appear once on stderr.\n" +"5. This should appear twice - once on stderr and once on stdout.\n" +"6. This should appear just once on stderr." +msgstr "" + +#: ../../howto/logging-cookbook.rst:3414 msgid "" "In this case, the message #5 printed to ``stdout`` doesn't appear, as " "expected." msgstr "" -#: ../../howto/logging-cookbook.rst:3406 +#: ../../howto/logging-cookbook.rst:3416 msgid "" "Of course, the approach described here can be generalised, for example to " "attach logging filters temporarily. Note that the above code works in Python " "2 as well as Python 3." msgstr "" -#: ../../howto/logging-cookbook.rst:3414 +#: ../../howto/logging-cookbook.rst:3424 msgid "A CLI application starter template" msgstr "" -#: ../../howto/logging-cookbook.rst:3416 +#: ../../howto/logging-cookbook.rst:3426 msgid "Here's an example which shows how you can:" msgstr "" -#: ../../howto/logging-cookbook.rst:3418 +#: ../../howto/logging-cookbook.rst:3428 msgid "Use a logging level based on command-line arguments" msgstr "" -#: ../../howto/logging-cookbook.rst:3419 +#: ../../howto/logging-cookbook.rst:3429 msgid "" "Dispatch to multiple subcommands in separate files, all logging at the same " "level in a consistent way" msgstr "" -#: ../../howto/logging-cookbook.rst:3421 +#: ../../howto/logging-cookbook.rst:3431 msgid "Make use of simple, minimal configuration" msgstr "" -#: ../../howto/logging-cookbook.rst:3423 +#: ../../howto/logging-cookbook.rst:3433 msgid "" "Suppose we have a command-line application whose job is to stop, start or " "restart some services. This could be organised for the purposes of " @@ -1795,53 +4476,191 @@ msgid "" "``logging.INFO``. Here's one way that ``app.py`` could be written::" msgstr "" -#: ../../howto/logging-cookbook.rst:3472 +#: ../../howto/logging-cookbook.rst:3441 +msgid "" +"import argparse\n" +"import importlib\n" +"import logging\n" +"import os\n" +"import sys\n" +"\n" +"def main(args=None):\n" +" scriptname = os.path.basename(__file__)\n" +" parser = argparse.ArgumentParser(scriptname)\n" +" levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')\n" +" parser.add_argument('--log-level', default='INFO', choices=levels)\n" +" subparsers = parser.add_subparsers(dest='command',\n" +" help='Available commands:')\n" +" start_cmd = subparsers.add_parser('start', help='Start a service')\n" +" start_cmd.add_argument('name', metavar='NAME',\n" +" help='Name of service to start')\n" +" stop_cmd = subparsers.add_parser('stop',\n" +" help='Stop one or more services')\n" +" stop_cmd.add_argument('names', metavar='NAME', nargs='+',\n" +" help='Name of service to stop')\n" +" restart_cmd = subparsers.add_parser('restart',\n" +" help='Restart one or more " +"services')\n" +" restart_cmd.add_argument('names', metavar='NAME', nargs='+',\n" +" help='Name of service to restart')\n" +" options = parser.parse_args()\n" +" # the code to dispatch commands could all be in this file. For the " +"purposes\n" +" # of illustration only, we implement each command in a separate module.\n" +" try:\n" +" mod = importlib.import_module(options.command)\n" +" cmd = getattr(mod, 'command')\n" +" except (ImportError, AttributeError):\n" +" print('Unable to find the code for command \\'%s\\'' % options." +"command)\n" +" return 1\n" +" # Could get fancy here and load configuration from file or dictionary\n" +" logging.basicConfig(level=options.log_level,\n" +" format='%(levelname)s %(name)s %(message)s')\n" +" cmd(options)\n" +"\n" +"if __name__ == '__main__':\n" +" sys.exit(main())" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3482 msgid "" "And the ``start``, ``stop`` and ``restart`` commands can be implemented in " "separate modules, like so for starting::" msgstr "" #: ../../howto/logging-cookbook.rst:3485 +msgid "" +"# start.py\n" +"import logging\n" +"\n" +"logger = logging.getLogger(__name__)\n" +"\n" +"def command(options):\n" +" logger.debug('About to start %s', options.name)\n" +" # actually do the command processing here ...\n" +" logger.info('Started the \\'%s\\' service.', options.name)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3495 msgid "and thus for stopping::" msgstr "" -#: ../../howto/logging-cookbook.rst:3506 +#: ../../howto/logging-cookbook.rst:3497 +msgid "" +"# stop.py\n" +"import logging\n" +"\n" +"logger = logging.getLogger(__name__)\n" +"\n" +"def command(options):\n" +" n = len(options.names)\n" +" if n == 1:\n" +" plural = ''\n" +" services = '\\'%s\\'' % options.names[0]\n" +" else:\n" +" plural = 's'\n" +" services = ', '.join('\\'%s\\'' % name for name in options.names)\n" +" i = services.rfind(', ')\n" +" services = services[:i] + ' and ' + services[i + 2:]\n" +" logger.debug('About to stop %s', services)\n" +" # actually do the command processing here ...\n" +" logger.info('Stopped the %s service%s.', services, plural)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3516 msgid "and similarly for restarting::" msgstr "" -#: ../../howto/logging-cookbook.rst:3527 +#: ../../howto/logging-cookbook.rst:3518 +msgid "" +"# restart.py\n" +"import logging\n" +"\n" +"logger = logging.getLogger(__name__)\n" +"\n" +"def command(options):\n" +" n = len(options.names)\n" +" if n == 1:\n" +" plural = ''\n" +" services = '\\'%s\\'' % options.names[0]\n" +" else:\n" +" plural = 's'\n" +" services = ', '.join('\\'%s\\'' % name for name in options.names)\n" +" i = services.rfind(', ')\n" +" services = services[:i] + ' and ' + services[i + 2:]\n" +" logger.debug('About to restart %s', services)\n" +" # actually do the command processing here ...\n" +" logger.info('Restarted the %s service%s.', services, plural)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3537 msgid "" "If we run this application with the default log level, we get output like " "this:" msgstr "" -#: ../../howto/logging-cookbook.rst:3540 +#: ../../howto/logging-cookbook.rst:3539 +msgid "" +"$ python app.py start foo\n" +"INFO start Started the 'foo' service.\n" +"\n" +"$ python app.py stop foo bar\n" +"INFO stop Stopped the 'foo' and 'bar' services.\n" +"\n" +"$ python app.py restart foo bar baz\n" +"INFO restart Restarted the 'foo', 'bar' and 'baz' services." +msgstr "" + +#: ../../howto/logging-cookbook.rst:3550 msgid "" "The first word is the logging level, and the second word is the module or " "package name of the place where the event was logged." msgstr "" -#: ../../howto/logging-cookbook.rst:3543 +#: ../../howto/logging-cookbook.rst:3553 msgid "" "If we change the logging level, then we can change the information sent to " "the log. For example, if we want more information:" msgstr "" -#: ../../howto/logging-cookbook.rst:3560 +#: ../../howto/logging-cookbook.rst:3556 +msgid "" +"$ python app.py --log-level DEBUG start foo\n" +"DEBUG start About to start foo\n" +"INFO start Started the 'foo' service.\n" +"\n" +"$ python app.py --log-level DEBUG stop foo bar\n" +"DEBUG stop About to stop 'foo' and 'bar'\n" +"INFO stop Stopped the 'foo' and 'bar' services.\n" +"\n" +"$ python app.py --log-level DEBUG restart foo bar baz\n" +"DEBUG restart About to restart 'foo', 'bar' and 'baz'\n" +"INFO restart Restarted the 'foo', 'bar' and 'baz' services." +msgstr "" + +#: ../../howto/logging-cookbook.rst:3570 msgid "And if we want less:" msgstr "" -#: ../../howto/logging-cookbook.rst:3568 +#: ../../howto/logging-cookbook.rst:3572 +msgid "" +"$ python app.py --log-level WARNING start foo\n" +"$ python app.py --log-level WARNING stop foo bar\n" +"$ python app.py --log-level WARNING restart foo bar baz" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3578 msgid "" "In this case, the commands don't print anything to the console, since " "nothing at ``WARNING`` level or above is logged by them." msgstr "" -#: ../../howto/logging-cookbook.rst:3574 +#: ../../howto/logging-cookbook.rst:3584 msgid "A Qt GUI for logging" msgstr "" -#: ../../howto/logging-cookbook.rst:3576 +#: ../../howto/logging-cookbook.rst:3586 msgid "" "A question that comes up from time to time is about how to log to a GUI " "application. The `Qt `_ framework is a popular cross-" @@ -1849,7 +4668,7 @@ msgid "" "`PyQt5` libraries." msgstr "" -#: ../../howto/logging-cookbook.rst:3581 +#: ../../howto/logging-cookbook.rst:3591 msgid "" "The following example shows how to log to a Qt GUI. This introduces a simple " "``QtHandler`` class which takes a callable, which should be a slot in the " @@ -1859,14 +4678,14 @@ msgid "" "logging messages at random levels with random short delays in between)." msgstr "" -#: ../../howto/logging-cookbook.rst:3588 +#: ../../howto/logging-cookbook.rst:3598 msgid "" "The worker thread is implemented using Qt's ``QThread`` class rather than " "the :mod:`threading` module, as there are circumstances where one has to use " "``QThread``, which offers better integration with other ``Qt`` components." msgstr "" -#: ../../howto/logging-cookbook.rst:3592 +#: ../../howto/logging-cookbook.rst:3602 msgid "" "The code should work with recent releases of any of ``PySide6``, ``PyQt6``, " "``PySide2`` or ``PyQt5``. You should be able to adapt the approach to " @@ -1874,11 +4693,262 @@ msgid "" "more detailed information." msgstr "" -#: ../../howto/logging-cookbook.rst:3829 +#: ../../howto/logging-cookbook.rst:3607 +msgid "" +"import datetime\n" +"import logging\n" +"import random\n" +"import sys\n" +"import time\n" +"\n" +"# Deal with minor differences between different Qt packages\n" +"try:\n" +" from PySide6 import QtCore, QtGui, QtWidgets\n" +" Signal = QtCore.Signal\n" +" Slot = QtCore.Slot\n" +"except ImportError:\n" +" try:\n" +" from PyQt6 import QtCore, QtGui, QtWidgets\n" +" Signal = QtCore.pyqtSignal\n" +" Slot = QtCore.pyqtSlot\n" +" except ImportError:\n" +" try:\n" +" from PySide2 import QtCore, QtGui, QtWidgets\n" +" Signal = QtCore.Signal\n" +" Slot = QtCore.Slot\n" +" except ImportError:\n" +" from PyQt5 import QtCore, QtGui, QtWidgets\n" +" Signal = QtCore.pyqtSignal\n" +" Slot = QtCore.pyqtSlot\n" +"\n" +"logger = logging.getLogger(__name__)\n" +"\n" +"\n" +"#\n" +"# Signals need to be contained in a QObject or subclass in order to be " +"correctly\n" +"# initialized.\n" +"#\n" +"class Signaller(QtCore.QObject):\n" +" signal = Signal(str, logging.LogRecord)\n" +"\n" +"#\n" +"# Output to a Qt GUI is only supposed to happen on the main thread. So, " +"this\n" +"# handler is designed to take a slot function which is set up to run in the " +"main\n" +"# thread. In this example, the function takes a string argument which is a\n" +"# formatted log message, and the log record which generated it. The " +"formatted\n" +"# string is just a convenience - you could format a string for output any " +"way\n" +"# you like in the slot function itself.\n" +"#\n" +"# You specify the slot function to do whatever GUI updates you want. The " +"handler\n" +"# doesn't know or care about specific UI elements.\n" +"#\n" +"class QtHandler(logging.Handler):\n" +" def __init__(self, slotfunc, *args, **kwargs):\n" +" super().__init__(*args, **kwargs)\n" +" self.signaller = Signaller()\n" +" self.signaller.signal.connect(slotfunc)\n" +"\n" +" def emit(self, record):\n" +" s = self.format(record)\n" +" self.signaller.signal.emit(s, record)\n" +"\n" +"#\n" +"# This example uses QThreads, which means that the threads at the Python " +"level\n" +"# are named something like \"Dummy-1\". The function below gets the Qt name " +"of the\n" +"# current thread.\n" +"#\n" +"def ctname():\n" +" return QtCore.QThread.currentThread().objectName()\n" +"\n" +"\n" +"#\n" +"# Used to generate random levels for logging.\n" +"#\n" +"LEVELS = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,\n" +" logging.CRITICAL)\n" +"\n" +"#\n" +"# This worker class represents work that is done in a thread separate to " +"the\n" +"# main thread. The way the thread is kicked off to do work is via a button " +"press\n" +"# that connects to a slot in the worker.\n" +"#\n" +"# Because the default threadName value in the LogRecord isn't much use, we " +"add\n" +"# a qThreadName which contains the QThread name as computed above, and pass " +"that\n" +"# value in an \"extra\" dictionary which is used to update the LogRecord " +"with the\n" +"# QThread name.\n" +"#\n" +"# This example worker just outputs messages sequentially, interspersed with\n" +"# random delays of the order of a few seconds.\n" +"#\n" +"class Worker(QtCore.QObject):\n" +" @Slot()\n" +" def start(self):\n" +" extra = {'qThreadName': ctname() }\n" +" logger.debug('Started work', extra=extra)\n" +" i = 1\n" +" # Let the thread run until interrupted. This allows reasonably " +"clean\n" +" # thread termination.\n" +" while not QtCore.QThread.currentThread().isInterruptionRequested():\n" +" delay = 0.5 + random.random() * 2\n" +" time.sleep(delay)\n" +" try:\n" +" if random.random() < 0.1:\n" +" raise ValueError('Exception raised: %d' % i)\n" +" else:\n" +" level = random.choice(LEVELS)\n" +" logger.log(level, 'Message after delay of %3.1f: %d', " +"delay, i, extra=extra)\n" +" except ValueError as e:\n" +" logger.exception('Failed: %s', e, extra=extra)\n" +" i += 1\n" +"\n" +"#\n" +"# Implement a simple UI for this cookbook example. This contains:\n" +"#\n" +"# * A read-only text edit window which holds formatted log messages\n" +"# * A button to start work and log stuff in a separate thread\n" +"# * A button to log something from the main thread\n" +"# * A button to clear the log window\n" +"#\n" +"class Window(QtWidgets.QWidget):\n" +"\n" +" COLORS = {\n" +" logging.DEBUG: 'black',\n" +" logging.INFO: 'blue',\n" +" logging.WARNING: 'orange',\n" +" logging.ERROR: 'red',\n" +" logging.CRITICAL: 'purple',\n" +" }\n" +"\n" +" def __init__(self, app):\n" +" super().__init__()\n" +" self.app = app\n" +" self.textedit = te = QtWidgets.QPlainTextEdit(self)\n" +" # Set whatever the default monospace font is for the platform\n" +" f = QtGui.QFont('nosuchfont')\n" +" if hasattr(f, 'Monospace'):\n" +" f.setStyleHint(f.Monospace)\n" +" else:\n" +" f.setStyleHint(f.StyleHint.Monospace) # for Qt6\n" +" te.setFont(f)\n" +" te.setReadOnly(True)\n" +" PB = QtWidgets.QPushButton\n" +" self.work_button = PB('Start background work', self)\n" +" self.log_button = PB('Log a message at a random level', self)\n" +" self.clear_button = PB('Clear log window', self)\n" +" self.handler = h = QtHandler(self.update_status)\n" +" # Remember to use qThreadName rather than threadName in the format " +"string.\n" +" fs = '%(asctime)s %(qThreadName)-12s %(levelname)-8s %(message)s'\n" +" formatter = logging.Formatter(fs)\n" +" h.setFormatter(formatter)\n" +" logger.addHandler(h)\n" +" # Set up to terminate the QThread when we exit\n" +" app.aboutToQuit.connect(self.force_quit)\n" +"\n" +" # Lay out all the widgets\n" +" layout = QtWidgets.QVBoxLayout(self)\n" +" layout.addWidget(te)\n" +" layout.addWidget(self.work_button)\n" +" layout.addWidget(self.log_button)\n" +" layout.addWidget(self.clear_button)\n" +" self.setFixedSize(900, 400)\n" +"\n" +" # Connect the non-worker slots and signals\n" +" self.log_button.clicked.connect(self.manual_update)\n" +" self.clear_button.clicked.connect(self.clear_display)\n" +"\n" +" # Start a new worker thread and connect the slots for the worker\n" +" self.start_thread()\n" +" self.work_button.clicked.connect(self.worker.start)\n" +" # Once started, the button should be disabled\n" +" self.work_button.clicked.connect(lambda : self.work_button." +"setEnabled(False))\n" +"\n" +" def start_thread(self):\n" +" self.worker = Worker()\n" +" self.worker_thread = QtCore.QThread()\n" +" self.worker.setObjectName('Worker')\n" +" self.worker_thread.setObjectName('WorkerThread') # for qThreadName\n" +" self.worker.moveToThread(self.worker_thread)\n" +" # This will start an event loop in the worker thread\n" +" self.worker_thread.start()\n" +"\n" +" def kill_thread(self):\n" +" # Just tell the worker to stop, then tell it to quit and wait for " +"that\n" +" # to happen\n" +" self.worker_thread.requestInterruption()\n" +" if self.worker_thread.isRunning():\n" +" self.worker_thread.quit()\n" +" self.worker_thread.wait()\n" +" else:\n" +" print('worker has already exited.')\n" +"\n" +" def force_quit(self):\n" +" # For use when the window is closed\n" +" if self.worker_thread.isRunning():\n" +" self.kill_thread()\n" +"\n" +" # The functions below update the UI and run in the main thread because\n" +" # that's where the slots are set up\n" +"\n" +" @Slot(str, logging.LogRecord)\n" +" def update_status(self, status, record):\n" +" color = self.COLORS.get(record.levelno, 'black')\n" +" s = '
%s
' % (color, status)\n" +" self.textedit.appendHtml(s)\n" +"\n" +" @Slot()\n" +" def manual_update(self):\n" +" # This function uses the formatted message passed in, but also uses\n" +" # information from the record to format the message in an " +"appropriate\n" +" # color according to its severity (level).\n" +" level = random.choice(LEVELS)\n" +" extra = {'qThreadName': ctname() }\n" +" logger.log(level, 'Manually logged!', extra=extra)\n" +"\n" +" @Slot()\n" +" def clear_display(self):\n" +" self.textedit.clear()\n" +"\n" +"\n" +"def main():\n" +" QtCore.QThread.currentThread().setObjectName('MainThread')\n" +" logging.getLogger().setLevel(logging.DEBUG)\n" +" app = QtWidgets.QApplication(sys.argv)\n" +" example = Window(app)\n" +" example.show()\n" +" if hasattr(app, 'exec'):\n" +" rc = app.exec()\n" +" else:\n" +" rc = app.exec_()\n" +" sys.exit(rc)\n" +"\n" +"if __name__=='__main__':\n" +" main()" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3839 msgid "Logging to syslog with RFC5424 support" msgstr "" -#: ../../howto/logging-cookbook.rst:3831 +#: ../../howto/logging-cookbook.rst:3841 msgid "" "Although :rfc:`5424` dates from 2009, most syslog servers are configured by " "default to use the older :rfc:`3164`, which hails from 2001. When " @@ -1888,14 +4958,84 @@ msgid "" "handlers.SysLogHandler` functionality has not been updated." msgstr "" -#: ../../howto/logging-cookbook.rst:3838 +#: ../../howto/logging-cookbook.rst:3848 msgid "" "RFC 5424 contains some useful features such as support for structured data, " "and if you need to be able to log to a syslog server with support for it, " "you can do so with a subclassed handler which looks something like this::" msgstr "" -#: ../../howto/logging-cookbook.rst:3904 +#: ../../howto/logging-cookbook.rst:3852 +msgid "" +"import datetime\n" +"import logging.handlers\n" +"import re\n" +"import socket\n" +"import time\n" +"\n" +"class SysLogHandler5424(logging.handlers.SysLogHandler):\n" +"\n" +" tz_offset = re.compile(r'([+-]\\d{2})(\\d{2})$')\n" +" escaped = re.compile(r'([\\]\"\\\\])')\n" +"\n" +" def __init__(self, *args, **kwargs):\n" +" self.msgid = kwargs.pop('msgid', None)\n" +" self.appname = kwargs.pop('appname', None)\n" +" super().__init__(*args, **kwargs)\n" +"\n" +" def format(self, record):\n" +" version = 1\n" +" asctime = datetime.datetime.fromtimestamp(record.created)." +"isoformat()\n" +" m = self.tz_offset.match(time.strftime('%z'))\n" +" has_offset = False\n" +" if m and time.timezone:\n" +" hrs, mins = m.groups()\n" +" if int(hrs) or int(mins):\n" +" has_offset = True\n" +" if not has_offset:\n" +" asctime += 'Z'\n" +" else:\n" +" asctime += f'{hrs}:{mins}'\n" +" try:\n" +" hostname = socket.gethostname()\n" +" except Exception:\n" +" hostname = '-'\n" +" appname = self.appname or '-'\n" +" procid = record.process\n" +" msgid = '-'\n" +" msg = super().format(record)\n" +" sdata = '-'\n" +" if hasattr(record, 'structured_data'):\n" +" sd = record.structured_data\n" +" # This should be a dict where the keys are SD-ID and the value " +"is a\n" +" # dict mapping PARAM-NAME to PARAM-VALUE (refer to the RFC for " +"what these\n" +" # mean)\n" +" # There's no error checking here - it's purely for illustration, " +"and you\n" +" # can adapt this code for use in production environments\n" +" parts = []\n" +"\n" +" def replacer(m):\n" +" g = m.groups()\n" +" return '\\\\' + g[0]\n" +"\n" +" for sdid, dv in sd.items():\n" +" part = f'[{sdid}'\n" +" for k, v in dv.items():\n" +" s = str(v)\n" +" s = self.escaped.sub(replacer, s)\n" +" part += f' {k}=\"{s}\"'\n" +" part += ']'\n" +" parts.append(part)\n" +" sdata = ''.join(parts)\n" +" return f'{version} {asctime} {hostname} {appname} {procid} {msgid} " +"{sdata} {msg}'" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3914 msgid "" "You'll need to be familiar with RFC 5424 to fully understand the above code, " "and it may be that you have slightly different needs (e.g. for how you pass " @@ -1904,11 +5044,22 @@ msgid "" "using something like this::" msgstr "" -#: ../../howto/logging-cookbook.rst:3918 +#: ../../howto/logging-cookbook.rst:3919 +msgid "" +"sd = {\n" +" 'foo@12345': {'bar': 'baz', 'baz': 'bozz', 'fizz': r'buzz'},\n" +" 'foo@54321': {'rab': 'baz', 'zab': 'bozz', 'zzif': r'buzz'}\n" +"}\n" +"extra = {'structured_data': sd}\n" +"i = 1\n" +"logger.debug('Message %d', i, extra=extra)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3928 msgid "How to treat a logger like an output stream" msgstr "" -#: ../../howto/logging-cookbook.rst:3920 +#: ../../howto/logging-cookbook.rst:3930 msgid "" "Sometimes, you need to interface to a third-party API which expects a file-" "like object to write to, but you want to direct the API's output to a " @@ -1916,17 +5067,69 @@ msgid "" "API. Here's a short script illustrating such a class:" msgstr "" -#: ../../howto/logging-cookbook.rst:3960 +#: ../../howto/logging-cookbook.rst:3935 +msgid "" +"import logging\n" +"\n" +"class LoggerWriter:\n" +" def __init__(self, logger, level):\n" +" self.logger = logger\n" +" self.level = level\n" +"\n" +" def write(self, message):\n" +" if message != '\\n': # avoid printing bare newlines, if you like\n" +" self.logger.log(self.level, message)\n" +"\n" +" def flush(self):\n" +" # doesn't actually do anything, but might be expected of a file-" +"like\n" +" # object - so optional depending on your situation\n" +" pass\n" +"\n" +" def close(self):\n" +" # doesn't actually do anything, but might be expected of a file-" +"like\n" +" # object - so optional depending on your situation. You might want\n" +" # to set a flag so that later calls to write raise an exception\n" +" pass\n" +"\n" +"def main():\n" +" logging.basicConfig(level=logging.DEBUG)\n" +" logger = logging.getLogger('demo')\n" +" info_fp = LoggerWriter(logger, logging.INFO)\n" +" debug_fp = LoggerWriter(logger, logging.DEBUG)\n" +" print('An INFO message', file=info_fp)\n" +" print('A DEBUG message', file=debug_fp)\n" +"\n" +"if __name__ == \"__main__\":\n" +" main()" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3970 msgid "When this script is run, it prints" msgstr "" -#: ../../howto/logging-cookbook.rst:3967 +#: ../../howto/logging-cookbook.rst:3972 +msgid "" +"INFO:demo:An INFO message\n" +"DEBUG:demo:A DEBUG message" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3977 msgid "" "You could also use ``LoggerWriter`` to redirect ``sys.stdout`` and ``sys." "stderr`` by doing something like this:" msgstr "" -#: ../../howto/logging-cookbook.rst:3977 +#: ../../howto/logging-cookbook.rst:3980 +msgid "" +"import sys\n" +"\n" +"sys.stdout = LoggerWriter(logger, logging.INFO)\n" +"sys.stderr = LoggerWriter(logger, logging.WARNING)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:3987 msgid "" "You should do this *after* configuring logging for your needs. In the above " "example, the :func:`~logging.basicConfig` call does this (using the ``sys." @@ -1934,25 +5137,59 @@ msgid "" "Then, you'd get this kind of result:" msgstr "" -#: ../../howto/logging-cookbook.rst:3990 +#: ../../howto/logging-cookbook.rst:3992 +msgid "" +">>> print('Foo')\n" +"INFO:demo:Foo\n" +">>> print('Bar', file=sys.stderr)\n" +"WARNING:demo:Bar\n" +">>>" +msgstr "" + +#: ../../howto/logging-cookbook.rst:4000 msgid "" "Of course, the examples above show output according to the format used by :" "func:`~logging.basicConfig`, but you can use a different formatter when you " "configure logging." msgstr "" -#: ../../howto/logging-cookbook.rst:3994 +#: ../../howto/logging-cookbook.rst:4004 msgid "" "Note that with the above scheme, you are somewhat at the mercy of buffering " "and the sequence of write calls which you are intercepting. For example, " "with the definition of ``LoggerWriter`` above, if you have the snippet" msgstr "" -#: ../../howto/logging-cookbook.rst:4003 +#: ../../howto/logging-cookbook.rst:4008 +msgid "" +"sys.stderr = LoggerWriter(logger, logging.WARNING)\n" +"1 / 0" +msgstr "" + +#: ../../howto/logging-cookbook.rst:4013 msgid "then running the script results in" msgstr "" -#: ../../howto/logging-cookbook.rst:4021 +#: ../../howto/logging-cookbook.rst:4015 +msgid "" +"WARNING:demo:Traceback (most recent call last):\n" +"\n" +"WARNING:demo: File \"/home/runner/cookbook-loggerwriter/test.py\", line 53, " +"in \n" +"\n" +"WARNING:demo:\n" +"WARNING:demo:main()\n" +"WARNING:demo: File \"/home/runner/cookbook-loggerwriter/test.py\", line 49, " +"in main\n" +"\n" +"WARNING:demo:\n" +"WARNING:demo:1 / 0\n" +"WARNING:demo:ZeroDivisionError\n" +"WARNING:demo::\n" +"WARNING:demo:division by zero" +msgstr "" + +#: ../../howto/logging-cookbook.rst:4031 msgid "" "As you can see, this output isn't ideal. That's because the underlying code " "which writes to ``sys.stderr`` makes multiple writes, each of which results " @@ -1962,17 +5199,49 @@ msgid "" "``LoggerWriter``:" msgstr "" -#: ../../howto/logging-cookbook.rst:4046 +#: ../../howto/logging-cookbook.rst:4037 +msgid "" +"class BufferingLoggerWriter(LoggerWriter):\n" +" def __init__(self, logger, level):\n" +" super().__init__(logger, level)\n" +" self.buffer = ''\n" +"\n" +" def write(self, message):\n" +" if '\\n' not in message:\n" +" self.buffer += message\n" +" else:\n" +" parts = message.split('\\n')\n" +" if self.buffer:\n" +" s = self.buffer + parts.pop(0)\n" +" self.logger.log(self.level, s)\n" +" self.buffer = parts.pop()\n" +" for part in parts:\n" +" self.logger.log(self.level, part)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:4056 msgid "" "This just buffers up stuff until a newline is seen, and then logs complete " "lines. With this approach, you get better output:" msgstr "" -#: ../../howto/logging-cookbook.rst:4062 +#: ../../howto/logging-cookbook.rst:4059 +msgid "" +"WARNING:demo:Traceback (most recent call last):\n" +"WARNING:demo: File \"/home/runner/cookbook-loggerwriter/main.py\", line 55, " +"in \n" +"WARNING:demo: main()\n" +"WARNING:demo: File \"/home/runner/cookbook-loggerwriter/main.py\", line 52, " +"in main\n" +"WARNING:demo: 1/0\n" +"WARNING:demo:ZeroDivisionError: division by zero" +msgstr "" + +#: ../../howto/logging-cookbook.rst:4072 msgid "Patterns to avoid" msgstr "" -#: ../../howto/logging-cookbook.rst:4064 +#: ../../howto/logging-cookbook.rst:4074 msgid "" "Although the preceding sections have described ways of doing things you " "might need to do or deal with, it is worth mentioning some usage patterns " @@ -1980,11 +5249,11 @@ msgid "" "The following sections are in no particular order." msgstr "" -#: ../../howto/logging-cookbook.rst:4070 +#: ../../howto/logging-cookbook.rst:4080 msgid "Opening the same log file multiple times" msgstr "" -#: ../../howto/logging-cookbook.rst:4072 +#: ../../howto/logging-cookbook.rst:4082 msgid "" "On Windows, you will generally not be able to open the same file multiple " "times as this will lead to a \"file is in use by another process\" error. " @@ -1992,32 +5261,32 @@ msgid "" "file multiple times. This could be done accidentally, for example by:" msgstr "" -#: ../../howto/logging-cookbook.rst:4077 +#: ../../howto/logging-cookbook.rst:4087 msgid "" "Adding a file handler more than once which references the same file (e.g. by " "a copy/paste/forget-to-change error)." msgstr "" -#: ../../howto/logging-cookbook.rst:4080 +#: ../../howto/logging-cookbook.rst:4090 msgid "" "Opening two files that look different, as they have different names, but are " "the same because one is a symbolic link to the other." msgstr "" -#: ../../howto/logging-cookbook.rst:4083 +#: ../../howto/logging-cookbook.rst:4093 msgid "" "Forking a process, following which both parent and child have a reference to " "the same file. This might be through use of the :mod:`multiprocessing` " "module, for example." msgstr "" -#: ../../howto/logging-cookbook.rst:4087 +#: ../../howto/logging-cookbook.rst:4097 msgid "" "Opening a file multiple times might *appear* to work most of the time, but " "can lead to a number of problems in practice:" msgstr "" -#: ../../howto/logging-cookbook.rst:4090 +#: ../../howto/logging-cookbook.rst:4100 msgid "" "Logging output can be garbled because multiple threads or processes try to " "write to the same file. Although logging guards against concurrent use of " @@ -2026,7 +5295,7 @@ msgid "" "different handler instances which happen to point to the same file." msgstr "" -#: ../../howto/logging-cookbook.rst:4096 +#: ../../howto/logging-cookbook.rst:4106 msgid "" "An attempt to delete a file (e.g. during file rotation) silently fails, " "because there is another reference pointing to it. This can lead to " @@ -2036,17 +5305,17 @@ msgid "" "being supposedly in place." msgstr "" -#: ../../howto/logging-cookbook.rst:4103 +#: ../../howto/logging-cookbook.rst:4113 msgid "" "Use the techniques outlined in :ref:`multiple-processes` to circumvent such " "issues." msgstr "" -#: ../../howto/logging-cookbook.rst:4107 +#: ../../howto/logging-cookbook.rst:4117 msgid "Using loggers as attributes in a class or passing them as parameters" msgstr "" -#: ../../howto/logging-cookbook.rst:4109 +#: ../../howto/logging-cookbook.rst:4119 msgid "" "While there might be unusual cases where you'll need to do this, in general " "there is no point because loggers are singletons. Code can always access a " @@ -2057,13 +5326,13 @@ msgid "" "module (and not the class) is the unit of software decomposition." msgstr "" -#: ../../howto/logging-cookbook.rst:4118 +#: ../../howto/logging-cookbook.rst:4128 msgid "" "Adding handlers other than :class:`~logging.NullHandler` to a logger in a " "library" msgstr "" -#: ../../howto/logging-cookbook.rst:4120 +#: ../../howto/logging-cookbook.rst:4130 msgid "" "Configuring logging by adding handlers, formatters and filters is the " "responsibility of the application developer, not the library developer. If " @@ -2071,11 +5340,11 @@ msgid "" "your loggers other than a :class:`~logging.NullHandler` instance." msgstr "" -#: ../../howto/logging-cookbook.rst:4126 +#: ../../howto/logging-cookbook.rst:4136 msgid "Creating a lot of loggers" msgstr "" -#: ../../howto/logging-cookbook.rst:4128 +#: ../../howto/logging-cookbook.rst:4138 msgid "" "Loggers are singletons that are never freed during a script execution, and " "so creating lots of loggers will use up memory which can't then be freed. " @@ -2086,38 +5355,38 @@ msgid "" "occasionally slightly more fine-grained than that)." msgstr "" -#: ../../howto/logging-cookbook.rst:4139 +#: ../../howto/logging-cookbook.rst:4149 msgid "Other resources" msgstr "Outros recursos" -#: ../../howto/logging-cookbook.rst:4143 +#: ../../howto/logging-cookbook.rst:4153 msgid "Module :mod:`logging`" msgstr "Módulo :mod:`logging`" -#: ../../howto/logging-cookbook.rst:4144 +#: ../../howto/logging-cookbook.rst:4154 msgid "API reference for the logging module." msgstr "Referência da API para o módulo de logging." -#: ../../howto/logging-cookbook.rst:4146 +#: ../../howto/logging-cookbook.rst:4156 msgid "Module :mod:`logging.config`" msgstr "Módulo :mod:`logging.config`" -#: ../../howto/logging-cookbook.rst:4147 +#: ../../howto/logging-cookbook.rst:4157 msgid "Configuration API for the logging module." msgstr "API de configuração para o módulo logging." -#: ../../howto/logging-cookbook.rst:4149 +#: ../../howto/logging-cookbook.rst:4159 msgid "Module :mod:`logging.handlers`" msgstr "Módulo :mod:`logging.handlers`" -#: ../../howto/logging-cookbook.rst:4150 +#: ../../howto/logging-cookbook.rst:4160 msgid "Useful handlers included with the logging module." -msgstr "Manipuladores úteis incluídos no módulo logging." +msgstr "Tratadores úteis incluídos no módulo logging." -#: ../../howto/logging-cookbook.rst:4152 +#: ../../howto/logging-cookbook.rst:4162 msgid ":ref:`Basic Tutorial `" msgstr ":ref:`Tutorial básico `" -#: ../../howto/logging-cookbook.rst:4154 +#: ../../howto/logging-cookbook.rst:4164 msgid ":ref:`Advanced Tutorial `" msgstr ":ref:`Tutorial avançado `" diff --git a/howto/logging.po b/howto/logging.po index b6e164ec0..09e810fbf 100644 --- a/howto/logging.po +++ b/howto/logging.po @@ -1,41 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Hildeberto Abreu Magalhães , 2021 -# Leticia Portella , 2021 -# Marco Rougeth , 2021 -# Katyanna Moura , 2021 -# Aline Balogh , 2021 -# i17obot , 2021 -# Claudio Rogerio Carvalho Filho , 2023 -# Vitor Buxbaum Orlandi, 2023 -# Vinicius vinicinbgs, 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 00:53+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../howto/logging.rst:5 msgid "Logging HOWTO" -msgstr "HowTo - Logging" +msgstr "Logging" #: ../../howto/logging.rst:0 msgid "Author" @@ -50,6 +40,9 @@ msgid "" "This page contains tutorial information. For links to reference information " "and a logging cookbook, please see :ref:`tutorial-ref-links`." msgstr "" +"Essa página contém informações relativas a tutoriais. Para links de " +"informações de referência e logging cookbook, por favor veja :ref:`tutorial-" +"ref-links`." #: ../../howto/logging.rst:17 msgid "Basic Logging Tutorial" @@ -86,6 +79,13 @@ msgid "" "see which logger methods to use when, see the table below. It states, for " "each of a set of common tasks, the best tool to use for that task." msgstr "" +"Você pode acessar a funcionalidade de logs criando um logger via ``logger = " +"getLogger(__name__)`` e, em seguida, chamar os métodos :meth:`~Logger." +"debug`, :meth:`~Logger.info`, :meth:`~Logger.warning`, :meth:`~Logger.error` " +"e :meth:`~Logger.critical`. Para determinar quando usar logging e ver quais " +"métodos de logger utilizar e quando, consulte a tabela abaixo. Ele indica, " +"para cada conjunto de tarefas comuns, a melhor ferramenta a ser usada para " +"essa tarefa." #: ../../howto/logging.rst:38 msgid "Task you want to perform" @@ -119,6 +119,8 @@ msgid "" "A logger's :meth:`~Logger.info` (or :meth:`~Logger.debug` method for very " "detailed output for diagnostic purposes)" msgstr "" +"O método :meth:`~Logger.info` de um logger (ou :meth:`~Logger.debug` para " +"saída muito detalhada para fins de diagnóstico)" #: ../../howto/logging.rst:49 msgid "Issue a warning regarding a particular runtime event" @@ -137,6 +139,9 @@ msgid "" "A logger's :meth:`~Logger.warning` method if there is nothing the client " "application can do about the situation, but the event should still be noted" msgstr "" +"O método :meth:`~Logger.warning` de um logger se não houver nada que a " +"aplicação cliente possa fazer sobre a situação, mas o evento ainda deve ser " +"registrado" #: ../../howto/logging.rst:60 msgid "Report an error regarding a particular runtime event" @@ -160,6 +165,9 @@ msgid "" "`~Logger.critical` method as appropriate for the specific error and " "application domain" msgstr "" +"Um método :meth:`~Logger.error`, :meth:`~Logger.exception` ou :meth:`~Logger." +"critical` do logger, conforme apropriado para o erro específico e domínio da " +"aplicação" #: ../../howto/logging.rst:70 msgid "" @@ -167,8 +175,11 @@ msgid "" "are used to track. The standard levels and their applicability are described " "below (in increasing order of severity):" msgstr "" +"Os métodos de logger são nomeados de acordo com o nível ou severidade dos " +"eventos que eles são usados para rastrear. Os níveis padrão e sua " +"aplicabilidade são descritos abaixo (em ordem crescente de severidade):" -#: ../../howto/logging.rst:77 ../../howto/logging.rst:871 +#: ../../howto/logging.rst:77 ../../howto/logging.rst:875 msgid "Level" msgstr "Nível" @@ -176,7 +187,7 @@ msgstr "Nível" msgid "When it's used" msgstr "Quando é usado" -#: ../../howto/logging.rst:79 ../../howto/logging.rst:881 +#: ../../howto/logging.rst:79 ../../howto/logging.rst:885 msgid "``DEBUG``" msgstr "``DEBUG``" @@ -187,7 +198,7 @@ msgstr "" "Informação detalhada, tipicamente de interesse apenas quando diagnosticando " "problemas." -#: ../../howto/logging.rst:82 ../../howto/logging.rst:879 +#: ../../howto/logging.rst:82 ../../howto/logging.rst:883 msgid "``INFO``" msgstr "``INFO``" @@ -195,7 +206,7 @@ msgstr "``INFO``" msgid "Confirmation that things are working as expected." msgstr "Confirmação de que as coisas estão funcionando como esperado." -#: ../../howto/logging.rst:85 ../../howto/logging.rst:877 +#: ../../howto/logging.rst:85 ../../howto/logging.rst:881 msgid "``WARNING``" msgstr "``WARNING``" @@ -209,7 +220,7 @@ msgstr "" "problema em um futuro próximo (ex.: 'pouco espaço em disco'). O software " "está ainda funcionando como esperado." -#: ../../howto/logging.rst:90 ../../howto/logging.rst:875 +#: ../../howto/logging.rst:90 ../../howto/logging.rst:879 msgid "``ERROR``" msgstr "``ERROR``" @@ -221,7 +232,7 @@ msgstr "" "Por conta de um problema mais grave, o software não conseguiu executar " "alguma função." -#: ../../howto/logging.rst:93 ../../howto/logging.rst:873 +#: ../../howto/logging.rst:93 ../../howto/logging.rst:877 msgid "``CRITICAL``" msgstr "``CRITICAL``" @@ -238,6 +249,9 @@ msgid "" "severity and higher will be tracked, unless the logging package is " "configured to do otherwise." msgstr "" +"O nível padrão é ``WARNING``, o que significa que somente os eventos desse " +"nível de severidade e superiores serão registrados, a menos que o logger do " +"pacote esteja configurado para fazer o contrário." #: ../../howto/logging.rst:100 msgid "" @@ -257,10 +271,24 @@ msgstr "Um exemplo simples" msgid "A very simple example is::" msgstr "Um exemplo bastante simples é::" +#: ../../howto/logging.rst:112 +msgid "" +"import logging\n" +"logging.warning('Watch out!') # will print a message to the console\n" +"logging.info('I told you so') # will not print anything" +msgstr "" +"import logging\n" +"logging.warning('Watch out!') # imprimirá uma mensagem no console\n" +"logging.info('I told you so') # não imprimirá nada" + #: ../../howto/logging.rst:116 msgid "If you type these lines into a script and run it, you'll see:" msgstr "Se você digitar essas linhas no script e executá-lo, você verá:" +#: ../../howto/logging.rst:118 +msgid "WARNING:root:Watch out!" +msgstr "" + #: ../../howto/logging.rst:122 msgid "" "printed out on the console. The ``INFO`` message doesn't appear because the " @@ -269,6 +297,11 @@ msgid "" "e. 'Watch out!'. The actual output can be formatted quite flexibly if you " "need that; formatting options will also be explained later." msgstr "" +"impresso no console. A mensagem ``INFO`` não aparece porque o nível padrão é " +"``WARNING``. A mensagem impressa inclui a indicação do nível e a descrição " +"do evento fornecido na chamada de registro, ou seja, 'Watch out!'. A saída " +"real pode ser formatada de maneira bastante flexível, se necessário; as " +"opções de formatação também serão explicadas mais tarde." #: ../../howto/logging.rst:128 msgid "" @@ -281,6 +314,13 @@ msgid "" "reason as well as others, it's better to create loggers and call their " "methods." msgstr "" +"Observe que neste exemplo, usamos funções diretamente no módulo ``logging``, " +"como ``logging.debug``, ao invés de criar um logger e chamar funções nele. " +"Essas funções operam no logger raiz, mas podem ser úteis, pois chamarão :" +"func:`~logging.basicConfig` para você se ele ainda não tiver sido chamado, " +"como neste exemplo. Em programas maiores, você geralmente desejará controlar " +"explicitamente a configuração de logging, no entanto - então, por esse " +"motivo, assim como por outros, é melhor criar loggers e chamar seus métodos." #: ../../howto/logging.rst:137 msgid "Logging to a file" @@ -293,6 +333,22 @@ msgid "" "Python interpreter, and don't just continue from the session described " "above::" msgstr "" +"Uma situação muito comum é a de registrar eventos de log em um arquivo, " +"então vamos dar uma olhada nisso a seguir. Certifique-se de tentar o " +"seguinte em um interpretador Python recém-iniciado, e não continue apenas a " +"partir da sessão descrita acima::" + +#: ../../howto/logging.rst:143 +msgid "" +"import logging\n" +"logger = logging.getLogger(__name__)\n" +"logging.basicConfig(filename='example.log', encoding='utf-8', level=logging." +"DEBUG)\n" +"logger.debug('This message should go to the log file')\n" +"logger.info('So should this')\n" +"logger.warning('And this, too')\n" +"logger.error('And non-ASCII stuff, too, like Øresund and Malmö')" +msgstr "" #: ../../howto/logging.rst:151 msgid "" @@ -311,6 +367,14 @@ msgstr "" "E agora se nós abrirmos o arquivo e olharmos o que temos, deveremos " "encontrar essas mensagens de log:" +#: ../../howto/logging.rst:161 +msgid "" +"DEBUG:__main__:This message should go to the log file\n" +"INFO:__main__:So should this\n" +"WARNING:__main__:And this, too\n" +"ERROR:__main__:And non-ASCII stuff, too, like Øresund and Malmö" +msgstr "" + #: ../../howto/logging.rst:168 msgid "" "This example also shows how you can set the logging level which acts as the " @@ -328,6 +392,10 @@ msgstr "" "Se você quer definir o nível de logging a partir de uma opção da linha de " "comando como:" +#: ../../howto/logging.rst:174 +msgid "--log=INFO" +msgstr "" + #: ../../howto/logging.rst:178 msgid "" "and you have the value of the parameter passed for ``--log`` in some " @@ -336,6 +404,10 @@ msgstr "" "e você tem o valor do parâmetro passado pelo ``--log`` em alguma variável " "*loglevel*, você pode usar::" +#: ../../howto/logging.rst:181 +msgid "getattr(logging, loglevel.upper())" +msgstr "" + #: ../../howto/logging.rst:183 msgid "" "to get the value which you'll pass to :func:`basicConfig` via the *level* " @@ -346,6 +418,17 @@ msgstr "" "argumento. Você pode querer verificar qualquer erros introduzidos pelo " "usuário, talvez como no exemplo a seguir::" +#: ../../howto/logging.rst:187 +msgid "" +"# assuming loglevel is bound to the string value obtained from the\n" +"# command line argument. Convert to upper case to allow the user to\n" +"# specify --log=DEBUG or --log=debug\n" +"numeric_level = getattr(logging, loglevel.upper(), None)\n" +"if not isinstance(numeric_level, int):\n" +" raise ValueError('Invalid log level: %s' % loglevel)\n" +"logging.basicConfig(level=numeric_level, ...)" +msgstr "" + #: ../../howto/logging.rst:195 msgid "" "The call to :func:`basicConfig` should come *before* any calls to a logger's " @@ -366,6 +449,12 @@ msgstr "" "execuções anteriores, você pode especificar o *filemode* argumento, mudando " "a chamada no exemplo acima::" +#: ../../howto/logging.rst:204 +msgid "" +"logging.basicConfig(filename='example.log', filemode='w', level=logging." +"DEBUG)" +msgstr "" + #: ../../howto/logging.rst:206 msgid "" "The output will be the same as before, but the log file is no longer " @@ -387,10 +476,20 @@ msgstr "" "Para logar o dado de uma variável, use o formato string para a mensagem " "descritiva do evento e adicione a variável como argumento. Exemplo::" +#: ../../howto/logging.rst:216 +msgid "" +"import logging\n" +"logging.warning('%s before you %s', 'Look', 'leap!')" +msgstr "" + #: ../../howto/logging.rst:219 msgid "will display:" msgstr "exibirá:" +#: ../../howto/logging.rst:221 +msgid "WARNING:root:Look before you leap!" +msgstr "" + #: ../../howto/logging.rst:225 msgid "" "As you can see, merging of variable data into the event description message " @@ -420,10 +519,27 @@ msgstr "" "Para mudar o formato usado para exibir mensagens, você precisa especificar o " "formato que quer usar::" +#: ../../howto/logging.rst:239 +msgid "" +"import logging\n" +"logging.basicConfig(format='%(levelname)s:%(message)s', level=logging." +"DEBUG)\n" +"logging.debug('This message should appear on the console')\n" +"logging.info('So should this')\n" +"logging.warning('And this, too')" +msgstr "" + #: ../../howto/logging.rst:245 msgid "which would print:" msgstr "que vai exibir:" +#: ../../howto/logging.rst:247 +msgid "" +"DEBUG:This message should appear on the console\n" +"INFO:So should this\n" +"WARNING:And this, too" +msgstr "" + #: ../../howto/logging.rst:253 msgid "" "Notice that the 'root' which appeared in earlier examples has disappeared. " @@ -452,10 +568,21 @@ msgstr "" "Para exibir a data e hora de um evento, você pode colocar '%(asctime)s' no " "seu formato string::" +#: ../../howto/logging.rst:267 +msgid "" +"import logging\n" +"logging.basicConfig(format='%(asctime)s %(message)s')\n" +"logging.warning('is when this event was logged.')" +msgstr "" + #: ../../howto/logging.rst:271 msgid "which should print something like this:" msgstr "que deve exibir algo assim:" +#: ../../howto/logging.rst:273 +msgid "2010-12-12 11:41:42,612 is when this event was logged." +msgstr "" + #: ../../howto/logging.rst:277 msgid "" "The default format for date/time display (shown above) is like ISO8601 or :" @@ -466,10 +593,22 @@ msgstr "" "`3339`. Se você precisa de mais controle sobre a formatação de data/hora, " "informe o *datefmt* argumento para ``basicConfig``, como neste exemplo::" +#: ../../howto/logging.rst:281 +msgid "" +"import logging\n" +"logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:" +"%M:%S %p')\n" +"logging.warning('is when this event was logged.')" +msgstr "" + #: ../../howto/logging.rst:285 msgid "which would display something like this:" msgstr "que deve exibir algo assim:" +#: ../../howto/logging.rst:287 +msgid "12/12/2010 11:46:36 AM is when this event was logged." +msgstr "" + #: ../../howto/logging.rst:291 msgid "" "The format of the *datefmt* argument is the same as supported by :func:`time." @@ -586,6 +725,10 @@ msgstr "" "Uma boa convenção para usar quando nomear loggers é usar um módulo-nível " "logger, em cada módulo que usa o logging, nomeado como sugerido abaixo::" +#: ../../howto/logging.rst:343 +msgid "logger = logging.getLogger(__name__)" +msgstr "" + #: ../../howto/logging.rst:345 msgid "" "This means that logger names track the package/module hierarchy, and it's " @@ -631,6 +774,10 @@ msgstr "" msgid "The default format set by :func:`basicConfig` for messages is:" msgstr "O formato padrão definido por :func:`basicConfig` para mensagens é:" +#: ../../howto/logging.rst:371 +msgid "severity:logger name:message" +msgstr "" + #: ../../howto/logging.rst:375 msgid "" "You can change this by passing a format string to :func:`basicConfig` with " @@ -640,19 +787,21 @@ msgstr "" #: ../../howto/logging.rst:380 msgid "Logging Flow" -msgstr "" +msgstr "Fluxo de Logging" #: ../../howto/logging.rst:382 msgid "" "The flow of log event information in loggers and handlers is illustrated in " "the following diagram." msgstr "" +"O fluxo dos eventos de log em loggers e handlers é ilustrado no diagrama a " +"seguir." -#: ../../howto/logging.rst:429 +#: ../../howto/logging.rst:433 msgid "Loggers" msgstr "Registradores" -#: ../../howto/logging.rst:431 +#: ../../howto/logging.rst:435 msgid "" ":class:`Logger` objects have a threefold job. First, they expose several " "methods to application code so that applications can log messages at " @@ -662,7 +811,7 @@ msgid "" "handlers." msgstr "" -#: ../../howto/logging.rst:437 +#: ../../howto/logging.rst:441 msgid "" "The most widely used methods on logger objects fall into two categories: " "configuration and message sending." @@ -670,11 +819,11 @@ msgstr "" "Os métodos mais usados em objetos logger se enquadram em duas categorias: " "configuração e envio de mensagem." -#: ../../howto/logging.rst:440 +#: ../../howto/logging.rst:444 msgid "These are the most common configuration methods:" msgstr "Esses são os métodos de configuração mais comuns:" -#: ../../howto/logging.rst:442 +#: ../../howto/logging.rst:446 msgid "" ":meth:`Logger.setLevel` specifies the lowest-severity log message a logger " "will handle, where debug is the lowest built-in severity level and critical " @@ -683,32 +832,35 @@ msgid "" "messages and will ignore DEBUG messages." msgstr "" -#: ../../howto/logging.rst:448 +#: ../../howto/logging.rst:452 msgid "" ":meth:`Logger.addHandler` and :meth:`Logger.removeHandler` add and remove " "handler objects from the logger object. Handlers are covered in more detail " "in :ref:`handler-basic`." msgstr "" -#: ../../howto/logging.rst:452 +#: ../../howto/logging.rst:456 msgid "" ":meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove " "filter objects from the logger object. Filters are covered in more detail " "in :ref:`filter`." msgstr "" -#: ../../howto/logging.rst:456 +#: ../../howto/logging.rst:460 msgid "" "You don't need to always call these methods on every logger you create. See " "the last two paragraphs in this section." msgstr "" +"Você não precisa sempre invocar esses métodos em cada logger que criar. Veja " +"os últimos dois paragrafos nessa seção." -#: ../../howto/logging.rst:459 +#: ../../howto/logging.rst:463 msgid "" "With the logger object configured, the following methods create log messages:" msgstr "" +"Com o objeto logger configurado, os seguintes métodos criam mensagens de log:" -#: ../../howto/logging.rst:461 +#: ../../howto/logging.rst:465 msgid "" ":meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`, :meth:" "`Logger.error`, and :meth:`Logger.critical` all create log records with a " @@ -721,14 +873,14 @@ msgid "" "exception information." msgstr "" -#: ../../howto/logging.rst:471 +#: ../../howto/logging.rst:475 msgid "" ":meth:`Logger.exception` creates a log message similar to :meth:`Logger." "error`. The difference is that :meth:`Logger.exception` dumps a stack trace " "along with it. Call this method only from an exception handler." msgstr "" -#: ../../howto/logging.rst:475 +#: ../../howto/logging.rst:479 msgid "" ":meth:`Logger.log` takes a log level as an explicit argument. This is a " "little more verbose for logging messages than using the log level " @@ -736,7 +888,7 @@ msgid "" "levels." msgstr "" -#: ../../howto/logging.rst:479 +#: ../../howto/logging.rst:483 msgid "" ":func:`getLogger` returns a reference to a logger instance with the " "specified name if it is provided, or ``root`` if not. The names are period-" @@ -748,7 +900,7 @@ msgid "" "descendants of ``foo``." msgstr "" -#: ../../howto/logging.rst:487 +#: ../../howto/logging.rst:491 msgid "" "Loggers have a concept of *effective level*. If a level is not explicitly " "set on a logger, the level of its parent is used instead as its effective " @@ -760,7 +912,7 @@ msgid "" "handlers." msgstr "" -#: ../../howto/logging.rst:495 +#: ../../howto/logging.rst:499 msgid "" "Child loggers propagate messages up to the handlers associated with their " "ancestor loggers. Because of this, it is unnecessary to define and configure " @@ -770,11 +922,11 @@ msgid "" "attribute of a logger to ``False``.)" msgstr "" -#: ../../howto/logging.rst:506 +#: ../../howto/logging.rst:510 msgid "Handlers" msgstr "Manipuladores" -#: ../../howto/logging.rst:508 +#: ../../howto/logging.rst:512 msgid "" ":class:`~logging.Handler` objects are responsible for dispatching the " "appropriate log messages (based on the log messages' severity) to the " @@ -787,14 +939,17 @@ msgid "" "of a specific severity to a specific location." msgstr "" -#: ../../howto/logging.rst:518 +#: ../../howto/logging.rst:522 msgid "" "The standard library includes quite a few handler types (see :ref:`useful-" "handlers`); the tutorials use mainly :class:`StreamHandler` and :class:" "`FileHandler` in its examples." msgstr "" +"A biblioteca padrão possui alguns tipos de handler (veja :ref:`useful-" +"handlers`); os tutoriais usam principalmente :class:`StreamHandler` e :class:" +"`FileHandler` nos seus exemplos." -#: ../../howto/logging.rst:522 +#: ../../howto/logging.rst:526 msgid "" "There are very few methods in a handler for application developers to " "concern themselves with. The only handler methods that seem relevant for " @@ -802,7 +957,7 @@ msgid "" "not creating custom handlers) are the following configuration methods:" msgstr "" -#: ../../howto/logging.rst:527 +#: ../../howto/logging.rst:531 msgid "" "The :meth:`~Handler.setLevel` method, just as in logger objects, specifies " "the lowest severity that will be dispatched to the appropriate destination. " @@ -812,19 +967,19 @@ msgid "" "send on." msgstr "" -#: ../../howto/logging.rst:533 +#: ../../howto/logging.rst:537 msgid "" ":meth:`~Handler.setFormatter` selects a Formatter object for this handler to " "use." msgstr "" -#: ../../howto/logging.rst:536 +#: ../../howto/logging.rst:540 msgid "" ":meth:`~Handler.addFilter` and :meth:`~Handler.removeFilter` respectively " "configure and deconfigure filter objects on handlers." msgstr "" -#: ../../howto/logging.rst:539 +#: ../../howto/logging.rst:543 msgid "" "Application code should not directly instantiate and use instances of :class:" "`Handler`. Instead, the :class:`Handler` class is a base class that defines " @@ -832,11 +987,11 @@ msgid "" "behavior that child classes can use (or override)." msgstr "" -#: ../../howto/logging.rst:546 +#: ../../howto/logging.rst:550 msgid "Formatters" msgstr "Formatadores" -#: ../../howto/logging.rst:548 +#: ../../howto/logging.rst:552 msgid "" "Formatter objects configure the final order, structure, and contents of the " "log message. Unlike the base :class:`logging.Handler` class, application " @@ -846,20 +1001,24 @@ msgid "" "string and a style indicator." msgstr "" -#: ../../howto/logging.rst:557 +#: ../../howto/logging.rst:561 msgid "" "If there is no message format string, the default is to use the raw " "message. If there is no date format string, the default date format is:" msgstr "" #: ../../howto/logging.rst:564 +msgid "%Y-%m-%d %H:%M:%S" +msgstr "" + +#: ../../howto/logging.rst:568 msgid "" "with the milliseconds tacked on at the end. The ``style`` is one of ``'%'``, " "``'{'``, or ``'$'``. If one of these is not specified, then ``'%'`` will be " "used." msgstr "" -#: ../../howto/logging.rst:567 +#: ../../howto/logging.rst:571 msgid "" "If the ``style`` is ``'%'``, the message format string uses ``%()s`` styled string substitution; the possible keys are documented in :" @@ -869,18 +1028,24 @@ msgid "" "should conform to what is expected by :meth:`string.Template.substitute`." msgstr "" -#: ../../howto/logging.rst:574 +#: ../../howto/logging.rst:578 msgid "Added the ``style`` parameter." msgstr "Adicionado o parâmetro ``style``." -#: ../../howto/logging.rst:577 +#: ../../howto/logging.rst:581 msgid "" "The following message format string will log the time in a human-readable " "format, the severity of the message, and the contents of the message, in " "that order::" msgstr "" +"A string de formato a seguir vai escrever o tempo em um formato légivel para " +"humanos, a severidade da mensagem, e o conteúdo da mensagem, nessa ordem::" -#: ../../howto/logging.rst:583 +#: ../../howto/logging.rst:585 +msgid "'%(asctime)s - %(levelname)s - %(message)s'" +msgstr "" + +#: ../../howto/logging.rst:587 msgid "" "Formatters use a user-configurable function to convert the creation time of " "a record to a tuple. By default, :func:`time.localtime` is used; to change " @@ -891,68 +1056,167 @@ msgid "" "in the Formatter class (to ``time.gmtime`` for GMT display)." msgstr "" -#: ../../howto/logging.rst:593 +#: ../../howto/logging.rst:597 msgid "Configuring Logging" msgstr "Configurando Logging" -#: ../../howto/logging.rst:597 +#: ../../howto/logging.rst:601 msgid "Programmers can configure logging in three ways:" msgstr "Programadores podem configurar logging de três formas:" -#: ../../howto/logging.rst:599 +#: ../../howto/logging.rst:603 msgid "" "Creating loggers, handlers, and formatters explicitly using Python code that " "calls the configuration methods listed above." msgstr "" -#: ../../howto/logging.rst:601 +#: ../../howto/logging.rst:605 msgid "" "Creating a logging config file and reading it using the :func:`fileConfig` " "function." msgstr "" -#: ../../howto/logging.rst:603 +#: ../../howto/logging.rst:607 msgid "" "Creating a dictionary of configuration information and passing it to the :" "func:`dictConfig` function." msgstr "" -#: ../../howto/logging.rst:606 +#: ../../howto/logging.rst:610 msgid "" "For the reference documentation on the last two options, see :ref:`logging-" "config-api`. The following example configures a very simple logger, a " "console handler, and a simple formatter using Python code::" msgstr "" -#: ../../howto/logging.rst:636 +#: ../../howto/logging.rst:614 +msgid "" +"import logging\n" +"\n" +"# create logger\n" +"logger = logging.getLogger('simple_example')\n" +"logger.setLevel(logging.DEBUG)\n" +"\n" +"# create console handler and set level to debug\n" +"ch = logging.StreamHandler()\n" +"ch.setLevel(logging.DEBUG)\n" +"\n" +"# create formatter\n" +"formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - " +"%(message)s')\n" +"\n" +"# add formatter to ch\n" +"ch.setFormatter(formatter)\n" +"\n" +"# add ch to logger\n" +"logger.addHandler(ch)\n" +"\n" +"# 'application' code\n" +"logger.debug('debug message')\n" +"logger.info('info message')\n" +"logger.warning('warn message')\n" +"logger.error('error message')\n" +"logger.critical('critical message')" +msgstr "" + +#: ../../howto/logging.rst:640 msgid "" "Running this module from the command line produces the following output:" msgstr "" -#: ../../howto/logging.rst:647 +#: ../../howto/logging.rst:642 +msgid "" +"$ python simple_logging_module.py\n" +"2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message\n" +"2005-03-19 15:10:26,620 - simple_example - INFO - info message\n" +"2005-03-19 15:10:26,695 - simple_example - WARNING - warn message\n" +"2005-03-19 15:10:26,697 - simple_example - ERROR - error message\n" +"2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message" +msgstr "" + +#: ../../howto/logging.rst:651 msgid "" "The following Python module creates a logger, handler, and formatter nearly " "identical to those in the example listed above, with the only difference " "being the names of the objects::" msgstr "" -#: ../../howto/logging.rst:666 +#: ../../howto/logging.rst:655 +msgid "" +"import logging\n" +"import logging.config\n" +"\n" +"logging.config.fileConfig('logging.conf')\n" +"\n" +"# create logger\n" +"logger = logging.getLogger('simpleExample')\n" +"\n" +"# 'application' code\n" +"logger.debug('debug message')\n" +"logger.info('info message')\n" +"logger.warning('warn message')\n" +"logger.error('error message')\n" +"logger.critical('critical message')" +msgstr "" + +#: ../../howto/logging.rst:670 msgid "Here is the logging.conf file:" msgstr "Aqui está o arquivo logging.conf:" -#: ../../howto/logging.rst:698 +#: ../../howto/logging.rst:672 +msgid "" +"[loggers]\n" +"keys=root,simpleExample\n" +"\n" +"[handlers]\n" +"keys=consoleHandler\n" +"\n" +"[formatters]\n" +"keys=simpleFormatter\n" +"\n" +"[logger_root]\n" +"level=DEBUG\n" +"handlers=consoleHandler\n" +"\n" +"[logger_simpleExample]\n" +"level=DEBUG\n" +"handlers=consoleHandler\n" +"qualname=simpleExample\n" +"propagate=0\n" +"\n" +"[handler_consoleHandler]\n" +"class=StreamHandler\n" +"level=DEBUG\n" +"formatter=simpleFormatter\n" +"args=(sys.stdout,)\n" +"\n" +"[formatter_simpleFormatter]\n" +"format=%(asctime)s - %(name)s - %(levelname)s - %(message)s" +msgstr "" + +#: ../../howto/logging.rst:702 msgid "" "The output is nearly identical to that of the non-config-file-based example:" msgstr "" -#: ../../howto/logging.rst:709 +#: ../../howto/logging.rst:704 +msgid "" +"$ python simple_logging_config.py\n" +"2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message\n" +"2005-03-19 15:38:55,979 - simpleExample - INFO - info message\n" +"2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message\n" +"2005-03-19 15:38:56,055 - simpleExample - ERROR - error message\n" +"2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message" +msgstr "" + +#: ../../howto/logging.rst:713 msgid "" "You can see that the config file approach has a few advantages over the " "Python code approach, mainly separation of configuration and code and the " "ability of noncoders to easily modify the logging properties." msgstr "" -#: ../../howto/logging.rst:713 +#: ../../howto/logging.rst:717 msgid "" "The :func:`fileConfig` function takes a default parameter, " "``disable_existing_loggers``, which defaults to ``True`` for reasons of " @@ -963,7 +1227,7 @@ msgid "" "information, and specify ``False`` for this parameter if you wish." msgstr "" -#: ../../howto/logging.rst:721 +#: ../../howto/logging.rst:725 msgid "" "The dictionary passed to :func:`dictConfig` can also specify a Boolean value " "with key ``disable_existing_loggers``, which if not specified explicitly in " @@ -972,7 +1236,7 @@ msgid "" "want - in which case, provide the key explicitly with a value of ``False``." msgstr "" -#: ../../howto/logging.rst:731 +#: ../../howto/logging.rst:735 msgid "" "Note that the class names referenced in config files need to be either " "relative to the logging module, or absolute values which can be resolved " @@ -983,7 +1247,7 @@ msgid "" "path)." msgstr "" -#: ../../howto/logging.rst:739 +#: ../../howto/logging.rst:743 msgid "" "In Python 3.2, a new means of configuring logging has been introduced, using " "dictionaries to hold configuration information. This provides a superset of " @@ -998,30 +1262,52 @@ msgid "" "a socket, or use whatever approach makes sense for your application." msgstr "" -#: ../../howto/logging.rst:751 +#: ../../howto/logging.rst:755 msgid "" "Here's an example of the same configuration as above, in YAML format for the " "new dictionary-based approach:" msgstr "" -#: ../../howto/logging.rst:775 +#: ../../howto/logging.rst:758 +msgid "" +"version: 1\n" +"formatters:\n" +" simple:\n" +" format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n" +"handlers:\n" +" console:\n" +" class: logging.StreamHandler\n" +" level: DEBUG\n" +" formatter: simple\n" +" stream: ext://sys.stdout\n" +"loggers:\n" +" simpleExample:\n" +" level: DEBUG\n" +" handlers: [console]\n" +" propagate: no\n" +"root:\n" +" level: DEBUG\n" +" handlers: [console]" +msgstr "" + +#: ../../howto/logging.rst:779 msgid "" "For more information about logging using a dictionary, see :ref:`logging-" "config-api`." msgstr "" -#: ../../howto/logging.rst:779 +#: ../../howto/logging.rst:783 msgid "What happens if no configuration is provided" msgstr "O que acontece se nenhuma configuração é fornecida" -#: ../../howto/logging.rst:781 +#: ../../howto/logging.rst:785 msgid "" "If no logging configuration is provided, it is possible to have a situation " "where a logging event needs to be output, but no handlers can be found to " "output the event." msgstr "" -#: ../../howto/logging.rst:785 +#: ../../howto/logging.rst:789 msgid "" "The event is output using a 'handler of last resort', stored in :data:" "`lastResort`. This internal handler is not associated with any logger, and " @@ -1033,32 +1319,32 @@ msgid "" "severities will be output." msgstr "" -#: ../../howto/logging.rst:796 +#: ../../howto/logging.rst:800 msgid "For versions of Python prior to 3.2, the behaviour is as follows:" msgstr "Para versões do Python anteriores à 3.2, o comportamento é o seguinte:" -#: ../../howto/logging.rst:798 +#: ../../howto/logging.rst:802 msgid "" "If :data:`raiseExceptions` is ``False`` (production mode), the event is " "silently dropped." msgstr "" -#: ../../howto/logging.rst:801 +#: ../../howto/logging.rst:805 msgid "" "If :data:`raiseExceptions` is ``True`` (development mode), a message 'No " "handlers could be found for logger X.Y.Z' is printed once." msgstr "" -#: ../../howto/logging.rst:804 +#: ../../howto/logging.rst:808 msgid "" "To obtain the pre-3.2 behaviour, :data:`lastResort` can be set to ``None``." msgstr "" -#: ../../howto/logging.rst:810 +#: ../../howto/logging.rst:814 msgid "Configuring Logging for a Library" msgstr "" -#: ../../howto/logging.rst:812 +#: ../../howto/logging.rst:816 msgid "" "When developing a library which uses logging, you should take care to " "document how the library uses logging - for example, the names of loggers " @@ -1069,7 +1355,7 @@ msgid "" "is regarded as the best default behaviour." msgstr "" -#: ../../howto/logging.rst:820 +#: ../../howto/logging.rst:824 msgid "" "If for some reason you *don't* want these messages printed in the absence of " "any logging configuration, you can attach a do-nothing handler to the top-" @@ -1081,7 +1367,7 @@ msgid "" "to those handlers, as normal." msgstr "" -#: ../../howto/logging.rst:829 +#: ../../howto/logging.rst:833 msgid "" "A do-nothing handler is included in the logging package: :class:`~logging." "NullHandler` (since Python 3.1). An instance of this handler could be added " @@ -1092,14 +1378,20 @@ msgid "" "etc. then the code::" msgstr "" -#: ../../howto/logging.rst:840 +#: ../../howto/logging.rst:841 +msgid "" +"import logging\n" +"logging.getLogger('foo').addHandler(logging.NullHandler())" +msgstr "" + +#: ../../howto/logging.rst:844 msgid "" "should have the desired effect. If an organisation produces a number of " "libraries, then the logger name specified can be 'orgname.foo' rather than " "just 'foo'." msgstr "" -#: ../../howto/logging.rst:844 +#: ../../howto/logging.rst:848 msgid "" "It is strongly advised that you *do not log to the root logger* in your " "library. Instead, use a logger with a unique and easily identifiable name, " @@ -1109,7 +1401,7 @@ msgid "" "library as they wish." msgstr "" -#: ../../howto/logging.rst:851 +#: ../../howto/logging.rst:855 msgid "" "It is strongly advised that you *do not add any handlers other than* :class:" "`~logging.NullHandler` *to your library's loggers*. This is because the " @@ -1120,11 +1412,11 @@ msgid "" "carry out unit tests and deliver logs which suit their requirements." msgstr "" -#: ../../howto/logging.rst:862 +#: ../../howto/logging.rst:866 msgid "Logging Levels" -msgstr "" +msgstr "Níveis de Logging" -#: ../../howto/logging.rst:864 +#: ../../howto/logging.rst:868 msgid "" "The numeric values of logging levels are given in the following table. These " "are primarily of interest if you want to define your own levels, and need " @@ -1132,40 +1424,45 @@ msgid "" "define a level with the same numeric value, it overwrites the predefined " "value; the predefined name is lost." msgstr "" +"Os valores númericos dos níveis de logging estão listados na tabela abaixo. " +"Eles são principalmente de interesse se você quiser definir seus próprios " +"níveis, e precisa deles para definir seus valores específicos relativos aos " +"níveis predefinidos. Se você define um nível com o mesmo valor númerico, ele " +"sobreescreve o valor predefinido; o nome predefinido é perdido." -#: ../../howto/logging.rst:871 +#: ../../howto/logging.rst:875 msgid "Numeric value" msgstr "Valor numérico" -#: ../../howto/logging.rst:873 +#: ../../howto/logging.rst:877 msgid "50" msgstr "50" -#: ../../howto/logging.rst:875 +#: ../../howto/logging.rst:879 msgid "40" msgstr "40" -#: ../../howto/logging.rst:877 +#: ../../howto/logging.rst:881 msgid "30" msgstr "30" -#: ../../howto/logging.rst:879 +#: ../../howto/logging.rst:883 msgid "20" msgstr "20" -#: ../../howto/logging.rst:881 +#: ../../howto/logging.rst:885 msgid "10" msgstr "10" -#: ../../howto/logging.rst:883 +#: ../../howto/logging.rst:887 msgid "``NOTSET``" msgstr "``NOTSET``" -#: ../../howto/logging.rst:883 +#: ../../howto/logging.rst:887 msgid "0" msgstr "0" -#: ../../howto/logging.rst:886 +#: ../../howto/logging.rst:890 msgid "" "Levels can also be associated with loggers, being set either by the " "developer or through loading a saved logging configuration. When a logging " @@ -1175,14 +1472,14 @@ msgid "" "basic mechanism controlling the verbosity of logging output." msgstr "" -#: ../../howto/logging.rst:893 +#: ../../howto/logging.rst:897 msgid "" "Logging messages are encoded as instances of the :class:`~logging.LogRecord` " "class. When a logger decides to actually log an event, a :class:`~logging." "LogRecord` instance is created from the logging message." msgstr "" -#: ../../howto/logging.rst:897 +#: ../../howto/logging.rst:901 msgid "" "Logging messages are subjected to a dispatch mechanism through the use of :" "dfn:`handlers`, which are instances of subclasses of the :class:`Handler` " @@ -1199,7 +1496,7 @@ msgid "" "at which point the passing to ancestor handlers stops)." msgstr "" -#: ../../howto/logging.rst:911 +#: ../../howto/logging.rst:915 msgid "" "Just as for loggers, handlers can have levels associated with them. A " "handler's level acts as a filter in the same way as a logger's level does. " @@ -1209,11 +1506,11 @@ msgid "" "`~Handler.emit`." msgstr "" -#: ../../howto/logging.rst:920 +#: ../../howto/logging.rst:924 msgid "Custom Levels" msgstr "" -#: ../../howto/logging.rst:922 +#: ../../howto/logging.rst:926 msgid "" "Defining your own levels is possible, but should not be necessary, as the " "existing levels have been chosen on the basis of practical experience. " @@ -1226,11 +1523,11 @@ msgid "" "given numeric value might mean different things for different libraries." msgstr "" -#: ../../howto/logging.rst:935 +#: ../../howto/logging.rst:939 msgid "Useful Handlers" msgstr "" -#: ../../howto/logging.rst:937 +#: ../../howto/logging.rst:941 msgid "" "In addition to the base :class:`Handler` class, many useful subclasses are " "provided:" @@ -1238,17 +1535,17 @@ msgstr "" "Em adição à classe base :class:`Handler`, muitas subclasses úteis são " "fornecidas:" -#: ../../howto/logging.rst:940 +#: ../../howto/logging.rst:944 msgid "" ":class:`StreamHandler` instances send messages to streams (file-like " "objects)." msgstr "" -#: ../../howto/logging.rst:943 +#: ../../howto/logging.rst:947 msgid ":class:`FileHandler` instances send messages to disk files." msgstr "" -#: ../../howto/logging.rst:945 +#: ../../howto/logging.rst:949 msgid "" ":class:`~handlers.BaseRotatingHandler` is the base class for handlers that " "rotate log files at a certain point. It is not meant to be instantiated " @@ -1256,61 +1553,61 @@ msgid "" "`~handlers.TimedRotatingFileHandler`." msgstr "" -#: ../../howto/logging.rst:950 +#: ../../howto/logging.rst:954 msgid "" ":class:`~handlers.RotatingFileHandler` instances send messages to disk " "files, with support for maximum log file sizes and log file rotation." msgstr "" -#: ../../howto/logging.rst:953 +#: ../../howto/logging.rst:957 msgid "" ":class:`~handlers.TimedRotatingFileHandler` instances send messages to disk " "files, rotating the log file at certain timed intervals." msgstr "" -#: ../../howto/logging.rst:956 +#: ../../howto/logging.rst:960 msgid "" ":class:`~handlers.SocketHandler` instances send messages to TCP/IP sockets. " "Since 3.4, Unix domain sockets are also supported." msgstr "" -#: ../../howto/logging.rst:959 +#: ../../howto/logging.rst:963 msgid "" ":class:`~handlers.DatagramHandler` instances send messages to UDP sockets. " "Since 3.4, Unix domain sockets are also supported." msgstr "" -#: ../../howto/logging.rst:962 +#: ../../howto/logging.rst:966 msgid "" ":class:`~handlers.SMTPHandler` instances send messages to a designated email " "address." msgstr "" -#: ../../howto/logging.rst:965 +#: ../../howto/logging.rst:969 msgid "" ":class:`~handlers.SysLogHandler` instances send messages to a Unix syslog " "daemon, possibly on a remote machine." msgstr "" -#: ../../howto/logging.rst:968 +#: ../../howto/logging.rst:972 msgid "" ":class:`~handlers.NTEventLogHandler` instances send messages to a Windows " "NT/2000/XP event log." msgstr "" -#: ../../howto/logging.rst:971 +#: ../../howto/logging.rst:975 msgid "" ":class:`~handlers.MemoryHandler` instances send messages to a buffer in " "memory, which is flushed whenever specific criteria are met." msgstr "" -#: ../../howto/logging.rst:974 +#: ../../howto/logging.rst:978 msgid "" ":class:`~handlers.HTTPHandler` instances send messages to an HTTP server " "using either ``GET`` or ``POST`` semantics." msgstr "" -#: ../../howto/logging.rst:977 +#: ../../howto/logging.rst:981 msgid "" ":class:`~handlers.WatchedFileHandler` instances watch the file they are " "logging to. If the file changes, it is closed and reopened using the file " @@ -1318,13 +1615,13 @@ msgid "" "support the underlying mechanism used." msgstr "" -#: ../../howto/logging.rst:982 +#: ../../howto/logging.rst:986 msgid "" ":class:`~handlers.QueueHandler` instances send messages to a queue, such as " "those implemented in the :mod:`queue` or :mod:`multiprocessing` modules." msgstr "" -#: ../../howto/logging.rst:985 +#: ../../howto/logging.rst:989 msgid "" ":class:`NullHandler` instances do nothing with error messages. They are used " "by library developers who want to use logging, but want to avoid the 'No " @@ -1333,15 +1630,15 @@ msgid "" "more information." msgstr "" -#: ../../howto/logging.rst:991 +#: ../../howto/logging.rst:995 msgid "The :class:`NullHandler` class." msgstr "A classe :class:`NullHandler`." -#: ../../howto/logging.rst:994 +#: ../../howto/logging.rst:998 msgid "The :class:`~handlers.QueueHandler` class." msgstr "A classe :class:`~handlers.QueueHandler`." -#: ../../howto/logging.rst:997 +#: ../../howto/logging.rst:1001 msgid "" "The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler` " "classes are defined in the core logging package. The other handlers are " @@ -1349,14 +1646,14 @@ msgid "" "module, :mod:`logging.config`, for configuration functionality.)" msgstr "" -#: ../../howto/logging.rst:1002 +#: ../../howto/logging.rst:1006 msgid "" "Logged messages are formatted for presentation through instances of the :" "class:`Formatter` class. They are initialized with a format string suitable " "for use with the % operator and a dictionary." msgstr "" -#: ../../howto/logging.rst:1006 +#: ../../howto/logging.rst:1010 msgid "" "For formatting multiple messages in a batch, instances of :class:" "`BufferingFormatter` can be used. In addition to the format string (which is " @@ -1364,7 +1661,7 @@ msgid "" "trailer format strings." msgstr "" -#: ../../howto/logging.rst:1011 +#: ../../howto/logging.rst:1015 msgid "" "When filtering based on logger level and/or handler level is not enough, " "instances of :class:`Filter` can be added to both :class:`Logger` and :class:" @@ -1374,18 +1671,18 @@ msgid "" "value, the message is not processed further." msgstr "" -#: ../../howto/logging.rst:1018 +#: ../../howto/logging.rst:1022 msgid "" "The basic :class:`Filter` functionality allows filtering by specific logger " "name. If this feature is used, messages sent to the named logger and its " "children are allowed through the filter, and all others dropped." msgstr "" -#: ../../howto/logging.rst:1026 +#: ../../howto/logging.rst:1030 msgid "Exceptions raised during logging" msgstr "Exceções levantadas durante logging" -#: ../../howto/logging.rst:1028 +#: ../../howto/logging.rst:1032 msgid "" "The logging package is designed to swallow exceptions which occur while " "logging in production. This is so that errors which occur while handling " @@ -1393,7 +1690,7 @@ msgid "" "errors - do not cause the application using logging to terminate prematurely." msgstr "" -#: ../../howto/logging.rst:1033 +#: ../../howto/logging.rst:1037 msgid "" ":class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never " "swallowed. Other exceptions which occur during the :meth:`~Handler.emit` " @@ -1401,7 +1698,7 @@ msgid "" "handleError` method." msgstr "" -#: ../../howto/logging.rst:1038 +#: ../../howto/logging.rst:1042 msgid "" "The default implementation of :meth:`~Handler.handleError` in :class:" "`Handler` checks to see if a module-level variable, :data:`raiseExceptions`, " @@ -1409,7 +1706,7 @@ msgid "" "the exception is swallowed." msgstr "" -#: ../../howto/logging.rst:1044 +#: ../../howto/logging.rst:1048 msgid "" "The default value of :data:`raiseExceptions` is ``True``. This is because " "during development, you typically want to be notified of any exceptions that " @@ -1417,11 +1714,11 @@ msgid "" "production usage." msgstr "" -#: ../../howto/logging.rst:1054 +#: ../../howto/logging.rst:1058 msgid "Using arbitrary objects as messages" msgstr "Usando objetos arbitrários como mensagens" -#: ../../howto/logging.rst:1056 +#: ../../howto/logging.rst:1060 msgid "" "In the preceding sections and examples, it has been assumed that the message " "passed when logging the event is a string. However, this is not the only " @@ -1433,11 +1730,11 @@ msgid "" "the wire." msgstr "" -#: ../../howto/logging.rst:1067 +#: ../../howto/logging.rst:1071 msgid "Optimization" msgstr "Optimização" -#: ../../howto/logging.rst:1069 +#: ../../howto/logging.rst:1073 msgid "" "Formatting of message arguments is deferred until it cannot be avoided. " "However, computing the arguments passed to the logging method can also be " @@ -1450,11 +1747,18 @@ msgstr "" #: ../../howto/logging.rst:1081 msgid "" +"if logger.isEnabledFor(logging.DEBUG):\n" +" logger.debug('Message with %s, %s', expensive_func1(),\n" +" expensive_func2())" +msgstr "" + +#: ../../howto/logging.rst:1085 +msgid "" "so that if the logger's threshold is set above ``DEBUG``, the calls to " "``expensive_func1`` and ``expensive_func2`` are never made." msgstr "" -#: ../../howto/logging.rst:1084 +#: ../../howto/logging.rst:1088 msgid "" "In some cases, :meth:`~Logger.isEnabledFor` can itself be more expensive " "than you'd like (e.g. for deeply nested loggers where an explicit level is " @@ -1466,7 +1770,7 @@ msgid "" "while the application is running (which is not all that common)." msgstr "" -#: ../../howto/logging.rst:1093 +#: ../../howto/logging.rst:1097 msgid "" "There are other optimizations which can be made for specific applications " "which need more precise control over what logging information is collected. " @@ -1474,94 +1778,94 @@ msgid "" "you don't need:" msgstr "" -#: ../../howto/logging.rst:1099 +#: ../../howto/logging.rst:1103 msgid "What you don't want to collect" msgstr "O que você não quer coletar" -#: ../../howto/logging.rst:1099 +#: ../../howto/logging.rst:1103 msgid "How to avoid collecting it" msgstr "" -#: ../../howto/logging.rst:1101 +#: ../../howto/logging.rst:1105 msgid "Information about where calls were made from." msgstr "" -#: ../../howto/logging.rst:1101 +#: ../../howto/logging.rst:1105 msgid "" "Set ``logging._srcfile`` to ``None``. This avoids calling :func:`sys." "_getframe`, which may help to speed up your code in environments like PyPy " "(which can't speed up code that uses :func:`sys._getframe`)." msgstr "" -#: ../../howto/logging.rst:1107 +#: ../../howto/logging.rst:1111 msgid "Threading information." msgstr "" -#: ../../howto/logging.rst:1107 +#: ../../howto/logging.rst:1111 msgid "Set ``logging.logThreads`` to ``False``." msgstr "" -#: ../../howto/logging.rst:1109 +#: ../../howto/logging.rst:1113 msgid "Current process ID (:func:`os.getpid`)" msgstr "" -#: ../../howto/logging.rst:1109 +#: ../../howto/logging.rst:1113 msgid "Set ``logging.logProcesses`` to ``False``." msgstr "" -#: ../../howto/logging.rst:1111 +#: ../../howto/logging.rst:1115 msgid "" "Current process name when using ``multiprocessing`` to manage multiple " "processes." msgstr "" -#: ../../howto/logging.rst:1111 +#: ../../howto/logging.rst:1115 msgid "Set ``logging.logMultiprocessing`` to ``False``." msgstr "" -#: ../../howto/logging.rst:1114 +#: ../../howto/logging.rst:1118 msgid "Current :class:`asyncio.Task` name when using ``asyncio``." msgstr "" -#: ../../howto/logging.rst:1114 +#: ../../howto/logging.rst:1118 msgid "Set ``logging.logAsyncioTasks`` to ``False``." msgstr "" -#: ../../howto/logging.rst:1118 +#: ../../howto/logging.rst:1122 msgid "" "Also note that the core logging module only includes the basic handlers. If " "you don't import :mod:`logging.handlers` and :mod:`logging.config`, they " "won't take up any memory." msgstr "" -#: ../../howto/logging.rst:1125 +#: ../../howto/logging.rst:1129 msgid "Other resources" msgstr "Outros recursos" -#: ../../howto/logging.rst:1129 +#: ../../howto/logging.rst:1133 msgid "Module :mod:`logging`" msgstr "Módulo :mod:`logging`" -#: ../../howto/logging.rst:1130 +#: ../../howto/logging.rst:1134 msgid "API reference for the logging module." msgstr "Referência da API para o módulo de logging." -#: ../../howto/logging.rst:1132 +#: ../../howto/logging.rst:1136 msgid "Module :mod:`logging.config`" msgstr "Módulo :mod:`logging.config`" -#: ../../howto/logging.rst:1133 +#: ../../howto/logging.rst:1137 msgid "Configuration API for the logging module." msgstr "API de configuração para o módulo logging." -#: ../../howto/logging.rst:1135 +#: ../../howto/logging.rst:1139 msgid "Module :mod:`logging.handlers`" msgstr "Módulo :mod:`logging.handlers`" -#: ../../howto/logging.rst:1136 +#: ../../howto/logging.rst:1140 msgid "Useful handlers included with the logging module." -msgstr "Manipuladores úteis incluídos no módulo logging." +msgstr "Tratadores úteis incluídos no módulo logging." -#: ../../howto/logging.rst:1138 +#: ../../howto/logging.rst:1142 msgid ":ref:`A logging cookbook `" msgstr ":ref:`Um livro de receitas do logging `" diff --git a/howto/mro.po b/howto/mro.po index c76340beb..53784583b 100644 --- a/howto/mro.po +++ b/howto/mro.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2024 -# Marco Rougeth , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2024-04-19 14:15+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-24 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -259,6 +257,30 @@ msgstr "" "com O a classe ``object``, que é o início de qualquer hierarquia para " "classes de novo estilo:" +#: ../../howto/mro.rst:120 +msgid "" +" -----------\n" +"| |\n" +"| O |\n" +"| / \\ |\n" +" - X Y /\n" +" | / | /\n" +" | / |/\n" +" A B\n" +" \\ /\n" +" ?" +msgstr "" +" -----------\n" +"| |\n" +"| O |\n" +"| / \\ |\n" +" - X Y /\n" +" | / | /\n" +" | / |/\n" +" A B\n" +" \\ /\n" +" ?" + #: ../../howto/mro.rst:133 msgid "" "In this case, it is not possible to derive a new class C from A and B, since " @@ -293,6 +315,10 @@ msgstr "" "Deixe-me apresentar algumas notações simples que serão úteis para a " "discussão a seguir. Usarei a notação de atalho::" +#: ../../howto/mro.rst:148 +msgid "C1 C2 ... CN" +msgstr "C1 C2 ... CN" + #: ../../howto/mro.rst:150 msgid "to indicate the list of classes [C1, C2, ... , CN]." msgstr "para indicar a lista de classes [C1, C2, ... , CN]." @@ -301,14 +327,26 @@ msgstr "para indicar a lista de classes [C1, C2, ... , CN]." msgid "The *head* of the list is its first element::" msgstr "*head* da lista é o seu primeiro elemento::" +#: ../../howto/mro.rst:154 +msgid "head = C1" +msgstr "head = C1" + #: ../../howto/mro.rst:156 msgid "whereas the *tail* is the rest of the list::" msgstr "enquanto *tail* é o resto da lista::" +#: ../../howto/mro.rst:158 +msgid "tail = C2 ... CN." +msgstr "tail = C2 ... CN." + #: ../../howto/mro.rst:160 msgid "I shall also use the notation::" msgstr "Também usarei a notação::" +#: ../../howto/mro.rst:162 +msgid "C + (C1 C2 ... CN) = C C1 C2 ... CN" +msgstr "C + (C1 C2 ... CN) = C C1 C2 ... CN" + #: ../../howto/mro.rst:164 msgid "to denote the sum of the lists [C] + [C1, C2, ... ,CN]." msgstr "para denotar a soma das listas [C] + [C1, C2, ..., CN]." @@ -339,6 +377,10 @@ msgstr "" msgid "In symbolic notation::" msgstr "Em notação simbólica::" +#: ../../howto/mro.rst:178 +msgid "L[C(B1 ... BN)] = C + merge(L[B1] ... L[BN], B1 ... BN)" +msgstr "L[C(B1 ... BN)] = C + merge(L[B1] ... L[BN], B1 ... BN)" + #: ../../howto/mro.rst:180 msgid "" "In particular, if C is the ``object`` class, which has no parents, the " @@ -347,6 +389,10 @@ msgstr "" "Em particular, se C é a classe ``object``, que não tem pais, a linearização " "é trivial::" +#: ../../howto/mro.rst:183 +msgid "L[object] = object." +msgstr "L[object] = object." + #: ../../howto/mro.rst:185 msgid "" "However, in general one has to compute the merge according to the following " @@ -394,6 +440,10 @@ msgstr "" "O cálculo da mesclagem é trivial se C tiver apenas um pai (herança única); " "nesse caso::" +#: ../../howto/mro.rst:205 +msgid "L[C(B)] = C + merge(L[B],B) = C + L[B]" +msgstr "L[C(B)] = C + merge(L[B],B) = C + L[B]" + #: ../../howto/mro.rst:207 msgid "" "However, in the case of multiple inheritance things are more cumbersome and " @@ -414,14 +464,76 @@ msgstr "Primeiro exemplo. Considere a seguinte hierarquia:" msgid "In this case the inheritance graph can be drawn as:" msgstr "Neste caso, o grafo de herança pode ser desenhado como:" +#: ../../howto/mro.rst:226 +msgid "" +" 6\n" +" ---\n" +"Level 3 | O | (more general)\n" +" / --- \\\n" +" / | \\ |\n" +" / | \\ |\n" +" / | \\ |\n" +" --- --- --- |\n" +"Level 2 3 | D | 4| E | | F | 5 |\n" +" --- --- --- |\n" +" \\ \\ _ / | |\n" +" \\ / \\ _ | |\n" +" \\ / \\ | |\n" +" --- --- |\n" +"Level 1 1 | B | | C | 2 |\n" +" --- --- |\n" +" \\ / |\n" +" \\ / \\ /\n" +" ---\n" +"Level 0 0 | A | (more specialized)\n" +" ---" +msgstr "" +" 6\n" +" ---\n" +"Nível 3 | O | (mais geral)\n" +" / --- \\\n" +" / | \\ |\n" +" / | \\ |\n" +" / | \\ |\n" +" --- --- --- |\n" +"Nível 2 3 | D | 4| E | | F | 5 |\n" +" --- --- --- |\n" +" \\ \\ _ / | |\n" +" \\ / \\ _ | |\n" +" \\ / \\ | |\n" +" --- --- |\n" +"Nível 1 1 | B | | C | 2 |\n" +" --- --- |\n" +" \\ / |\n" +" \\ / \\ /\n" +" ---\n" +"Nível 0 0 | A | (mais especializada)\n" +" ---" + #: ../../howto/mro.rst:251 msgid "The linearizations of O,D,E and F are trivial::" msgstr "As linearizações de O,D,E e F são triviais::" +#: ../../howto/mro.rst:253 +msgid "" +"L[O] = O\n" +"L[D] = D O\n" +"L[E] = E O\n" +"L[F] = F O" +msgstr "" +"L[O] = O\n" +"L[D] = D O\n" +"L[E] = E O\n" +"L[F] = F O" + #: ../../howto/mro.rst:258 msgid "The linearization of B can be computed as::" msgstr "A linearização de B pode ser calculada como::" +#: ../../howto/mro.rst:260 +msgid "L[B] = B + merge(DO, EO, DE)" +msgstr "L[B] = B + merge(DO, EO, DE)" + #: ../../howto/mro.rst:262 msgid "" "We see that D is a good head, therefore we take it and we are reduced to " @@ -436,14 +548,48 @@ msgstr "" "sequência. Então vemos que E é um bom *head*; nós pegamos isso e somos " "reduzidos a calcular ``merge(O,O)`` que dá O. Portanto::" +#: ../../howto/mro.rst:268 +msgid "L[B] = B D E O" +msgstr "L[B] = B D E O" + #: ../../howto/mro.rst:270 msgid "Using the same procedure one finds::" msgstr "Usando o mesmo procedimento encontra-se::" +#: ../../howto/mro.rst:272 +msgid "" +"L[C] = C + merge(DO,FO,DF)\n" +" = C + D + merge(O,FO,F)\n" +" = C + D + F + merge(O,O)\n" +" = C D F O" +msgstr "" +"L[C] = C + merge(DO,FO,DF)\n" +" = C + D + merge(O,FO,F)\n" +" = C + D + F + merge(O,O)\n" +" = C D F O" + #: ../../howto/mro.rst:277 msgid "Now we can compute::" msgstr "Agora podemos calcular::" +#: ../../howto/mro.rst:279 +msgid "" +"L[A] = A + merge(BDEO,CDFO,BC)\n" +" = A + B + merge(DEO,CDFO,C)\n" +" = A + B + C + merge(DEO,DFO)\n" +" = A + B + C + D + merge(EO,FO)\n" +" = A + B + C + D + E + merge(O,FO)\n" +" = A + B + C + D + E + F + merge(O,O)\n" +" = A B C D E F O" +msgstr "" +"L[A] = A + merge(BDEO,CDFO,BC)\n" +" = A + B + merge(DEO,CDFO,C)\n" +" = A + B + C + merge(DEO,DFO)\n" +" = A + B + C + D + merge(EO,FO)\n" +" = A + B + C + D + E + merge(O,FO)\n" +" = A + B + C + D + E + F + merge(O,O)\n" +" = A B C D E F O" + #: ../../howto/mro.rst:287 msgid "" "In this example, the linearization is ordered in a pretty nice way according " @@ -474,6 +620,52 @@ msgstr "" "entanto, mesmo uma pequena modificação muda completamente a ordem da " "hierarquia:" +#: ../../howto/mro.rst:307 +msgid "" +" 6\n" +" ---\n" +"Level 3 | O |\n" +" / --- \\\n" +" / | \\\n" +" / | \\\n" +" / | \\\n" +" --- --- ---\n" +"Level 2 2 | E | 4 | D | | F | 5\n" +" --- --- ---\n" +" \\ / \\ /\n" +" \\ / \\ /\n" +" \\ / \\ /\n" +" --- ---\n" +"Level 1 1 | B | | C | 3\n" +" --- ---\n" +" \\ /\n" +" \\ /\n" +" ---\n" +"Level 0 0 | A |\n" +" ---" +msgstr "" +" 6\n" +" ---\n" +"Nível 3 | O |\n" +" / --- \\\n" +" / | \\\n" +" / | \\\n" +" / | \\\n" +" --- --- ---\n" +"Nível 2 2 | E | 4 | D | | F | 5\n" +" --- --- ---\n" +" \\ / \\ /\n" +" \\ / \\ /\n" +" \\ / \\ /\n" +" --- ---\n" +"Nível 1 1 | B | | C | 3\n" +" --- ---\n" +" \\ /\n" +" \\ /\n" +" ---\n" +"Nível 0 0 | A |\n" +" ---" + #: ../../howto/mro.rst:332 msgid "" "Notice that the class E, which is in the second level of the hierarchy, " @@ -482,17 +674,17 @@ msgid "" msgstr "" "Observe que a classe E, que está no segundo nível da hierarquia, precede a " "classe C, que está no primeiro nível da hierarquia, ou seja, E é mais " -"especializado que C, mesmo que esteja em um nível superior." +"especializado que C, mesmo que esteja em um nível mais alto." #: ../../howto/mro.rst:336 msgid "" "A lazy programmer can obtain the MRO directly from Python 2.2, since in this " "case it coincides with the Python 2.3 linearization. It is enough to invoke " -"the .mro() method of class A:" +"the :meth:`~type.mro` method of class A:" msgstr "" "Um programador preguiçoso pode obter a MRO diretamente do Python 2.2, pois " "neste caso ela coincide com a linearização do Python 2.3. Basta invocar o " -"método .mro() da classe A:" +"método :meth:`~type.mro` da classe A:" #: ../../howto/mro.rst:345 msgid "" @@ -504,6 +696,20 @@ msgstr "" "envolvendo um sério desacordo de ordem. Neste caso, é simples calcular as " "linearizações de O, X, Y, A e B:" +#: ../../howto/mro.rst:349 +msgid "" +"L[O] = 0\n" +"L[X] = X O\n" +"L[Y] = Y O\n" +"L[A] = A X Y O\n" +"L[B] = B Y X O" +msgstr "" +"L[O] = 0\n" +"L[X] = X O\n" +"L[Y] = Y O\n" +"L[A] = A X Y O\n" +"L[B] = B Y X O" + #: ../../howto/mro.rst:357 msgid "" "However, it is impossible to compute the linearization for a class C that " @@ -512,6 +718,16 @@ msgstr "" "Porém, é impossível calcular a linearização para uma classe C que herda de A " "e B::" +#: ../../howto/mro.rst:360 +msgid "" +"L[C] = C + merge(AXYO, BYXO, AB)\n" +" = C + A + merge(XYO, BYXO, B)\n" +" = C + A + B + merge(XYO, YXO)" +msgstr "" +"L[C] = C + merge(AXYO, BYXO, AB)\n" +" = C + A + merge(XYO, BYXO, B)\n" +" = C + A + B + merge(XYO, YXO)" + #: ../../howto/mro.rst:364 msgid "" "At this point we cannot merge the lists XYO and YXO, since X is in the tail " @@ -552,15 +768,37 @@ msgstr "" msgid "with inheritance diagram" msgstr "com diagrama de herança" +#: ../../howto/mro.rst:386 +msgid "" +" O\n" +" |\n" +"(buy spam) F\n" +" | \\\n" +" | E (buy eggs)\n" +" | /\n" +" G\n" +"\n" +" (buy eggs or spam ?)" +msgstr "" +" O\n" +" |\n" +"(comprar spam) F\n" +" | \\\n" +" | E (comprar ovos)\n" +" | /\n" +" G\n" +"\n" +" (comprar ovos ou spam ?)" + #: ../../howto/mro.rst:399 msgid "" "We see that class G inherits from F and E, with F *before* E: therefore we " "would expect the attribute *G.remember2buy* to be inherited by *F." -"rembermer2buy* and not by *E.remember2buy*: nevertheless Python 2.2 gives" +"remember2buy* and not by *E.remember2buy*: nevertheless Python 2.2 gives" msgstr "" "Vemos que a classe G herda de F e E, com F *antes* de E: portanto, " "esperaríamos que o atributo *G.remember2buy* fosse herdado por *F." -"rembermer2buy* e não por *E.remember2buy*: no entanto, Python 2.2 dá" +"remember2buy* e não por *E.remember2buy*: no entanto, Python 2.2 dá" #: ../../howto/mro.rst:407 msgid "" @@ -572,6 +810,10 @@ msgstr "" "lista de precedência local, ou seja, a lista dos pais de G, não é preservada " "na linearização de G em Python 2.2::" +#: ../../howto/mro.rst:411 +msgid "L[G,P22]= G E F object # F *follows* E" +msgstr "L[G,P22]= G E F object # F *segue* E" + #: ../../howto/mro.rst:413 msgid "" "One could argue that the reason why F follows E in the Python 2.2 " @@ -605,6 +847,10 @@ msgstr "" "impedindo efetivamente o programador de gerar hierarquias ambíguas. A razão " "para isso é que o algoritmo C3 falha quando a mesclagem::" +#: ../../howto/mro.rst:435 +msgid "merge(FO,EFO,FE)" +msgstr "merge(FO,EFO,FE)" + #: ../../howto/mro.rst:437 msgid "" "cannot be computed, because F is in the tail of EFO and E is in the tail of " @@ -623,6 +869,26 @@ msgstr "" "G de E e F (o mais específico primeiro) e não de F e E; neste caso a MRO é " "GEF, sem dúvida." +#: ../../howto/mro.rst:444 +msgid "" +" O\n" +" |\n" +" F (spam)\n" +" / |\n" +"(eggs) E |\n" +" \\ |\n" +" G\n" +" (eggs, no doubt)" +msgstr "" +" O\n" +" |\n" +" F (spam)\n" +" / |\n" +"(ovos) E |\n" +" \\ |\n" +" G\n" +" (ovos, sem dúvida)" + #: ../../howto/mro.rst:456 msgid "" "Python 2.3 forces the programmer to write good hierarchies (or, at least, " @@ -689,10 +955,36 @@ msgstr "" "Para provar que a MRO para classes clássicas não é monotônica é bastante " "trivial, basta olhar o diagrama em losango:" +#: ../../howto/mro.rst:489 +msgid "" +" C\n" +" / \\\n" +" / \\\n" +"A B\n" +" \\ /\n" +" \\ /\n" +" D" +msgstr "" +" C\n" +" / \\\n" +" / \\\n" +"A B\n" +" \\ /\n" +" \\ /\n" +" D" + #: ../../howto/mro.rst:500 msgid "One easily discerns the inconsistency::" msgstr "Percebe-se facilmente a inconsistência::" +#: ../../howto/mro.rst:502 +msgid "" +"L[B,P21] = B C # B precedes C : B's methods win\n" +"L[D,P21] = D A C B C # B follows C : C's methods win!" +msgstr "" +"L[B,P21] = B C # B precede C : métodos de B venceram\n" +"L[D,P21] = D A C B C # B segue C : métodos de B venceram!" + #: ../../howto/mro.rst:505 msgid "" "On the other hand, there are no problems with the Python 2.2 and 2.3 MROs, " @@ -701,6 +993,10 @@ msgstr "" "Por outro lado, não há problemas com as MROs do Python 2.2 e do 2.3, elas " "fornecem ambos::" +#: ../../howto/mro.rst:508 +msgid "L[D] = D A B C" +msgstr "L[D] = D A B C" + #: ../../howto/mro.rst:510 msgid "" "Guido points out in his essay [#]_ that the classic MRO is not so bad in " @@ -734,6 +1030,28 @@ msgstr "" "verificar essas linearizações como exercício e desenhar o diagrama de " "herança ;-) ::" +#: ../../howto/mro.rst:534 +msgid "" +"L[A] = A O\n" +"L[B] = B O\n" +"L[C] = C O\n" +"L[D] = D O\n" +"L[E] = E O\n" +"L[K1]= K1 A B C O\n" +"L[K2]= K2 D B E O\n" +"L[K3]= K3 D A O\n" +"L[Z] = Z K1 K2 K3 D A B C E O" +msgstr "" +"L[A] = A O\n" +"L[B] = B O\n" +"L[C] = C O\n" +"L[D] = D O\n" +"L[E] = E O\n" +"L[K1]= K1 A B C O\n" +"L[K2]= K2 D B E O\n" +"L[K3]= K3 D A O\n" +"L[Z] = Z K1 K2 K3 D A B C E O" + #: ../../howto/mro.rst:544 msgid "" "Python 2.2 gives exactly the same linearizations for A, B, C, D, E, K1, K2 " @@ -742,6 +1060,10 @@ msgstr "" "Python 2.2 fornece exatamente as mesmas linearizações para A, B, C, D, E, " "K1, K2 e K3, mas uma linearização diferente para Z::" +#: ../../howto/mro.rst:547 +msgid "L[Z,P22] = Z K1 K3 A K2 D B C E O" +msgstr "L[Z,P22] = Z K1 K3 A K2 D B C E O" + #: ../../howto/mro.rst:549 msgid "" "It is clear that this linearization is *wrong*, since A comes before D " @@ -793,6 +1115,176 @@ msgstr "" "alterar a última linha para brincar com os vários exemplos que discuti neste " "artigo.::" +#: ../../howto/mro.rst:574 +msgid "" +"#\n" +"\n" +"\"\"\"C3 algorithm by Samuele Pedroni (with readability enhanced by me)." +"\"\"\"\n" +"\n" +"class __metaclass__(type):\n" +" \"All classes are metamagically modified to be nicely printed\"\n" +" __repr__ = lambda cls: cls.__name__\n" +"\n" +"class ex_2:\n" +" \"Serious order disagreement\" #From Guido\n" +" class O: pass\n" +" class X(O): pass\n" +" class Y(O): pass\n" +" class A(X,Y): pass\n" +" class B(Y,X): pass\n" +" try:\n" +" class Z(A,B): pass #creates Z(A,B) in Python 2.2\n" +" except TypeError:\n" +" pass # Z(A,B) cannot be created in Python 2.3\n" +"\n" +"class ex_5:\n" +" \"My first example\"\n" +" class O: pass\n" +" class F(O): pass\n" +" class E(O): pass\n" +" class D(O): pass\n" +" class C(D,F): pass\n" +" class B(D,E): pass\n" +" class A(B,C): pass\n" +"\n" +"class ex_6:\n" +" \"My second example\"\n" +" class O: pass\n" +" class F(O): pass\n" +" class E(O): pass\n" +" class D(O): pass\n" +" class C(D,F): pass\n" +" class B(E,D): pass\n" +" class A(B,C): pass\n" +"\n" +"class ex_9:\n" +" \"Difference between Python 2.2 MRO and C3\" #From Samuele\n" +" class O: pass\n" +" class A(O): pass\n" +" class B(O): pass\n" +" class C(O): pass\n" +" class D(O): pass\n" +" class E(O): pass\n" +" class K1(A,B,C): pass\n" +" class K2(D,B,E): pass\n" +" class K3(D,A): pass\n" +" class Z(K1,K2,K3): pass\n" +"\n" +"def merge(seqs):\n" +" print '\\n\\nCPL[%s]=%s' % (seqs[0][0],seqs),\n" +" res = []; i=0\n" +" while 1:\n" +" nonemptyseqs=[seq for seq in seqs if seq]\n" +" if not nonemptyseqs: return res\n" +" i+=1; print '\\n',i,'round: candidates...',\n" +" for seq in nonemptyseqs: # find merge candidates among seq heads\n" +" cand = seq[0]; print ' ',cand,\n" +" nothead=[s for s in nonemptyseqs if cand in s[1:]]\n" +" if nothead: cand=None #reject candidate\n" +" else: break\n" +" if not cand: raise \"Inconsistent hierarchy\"\n" +" res.append(cand)\n" +" for seq in nonemptyseqs: # remove cand\n" +" if seq[0] == cand: del seq[0]\n" +"\n" +"def mro(C):\n" +" \"Compute the class precedence list (mro) according to C3\"\n" +" return merge([[C]]+map(mro,C.__bases__)+[list(C.__bases__)])\n" +"\n" +"def print_mro(C):\n" +" print '\\nMRO[%s]=%s' % (C,mro(C))\n" +" print '\\nP22 MRO[%s]=%s' % (C,C.mro())\n" +"\n" +"print_mro(ex_9.Z)\n" +"\n" +"#" +msgstr "" +"#\n" +"\n" +"\"\"\"Algoritmo C3 por Samuele Pedroni (com legibilidade melhorada por mim)." +"\"\"\"\n" +"\n" +"class __metaclass__(type):\n" +" \"Todas as classes são modificadas metamagicamente para serem impressas " +"com aparência amigável\"\n" +" __repr__ = lambda cls: cls.__name__\n" +"\n" +"class ex_2:\n" +" \"Desacordo de ordem grave\" #por Guido\n" +" class O: pass\n" +" class X(O): pass\n" +" class Y(O): pass\n" +" class A(X,Y): pass\n" +" class B(Y,X): pass\n" +" try:\n" +" class Z(A,B): pass #cria Z(A,B) no Python 2.2\n" +" except TypeError:\n" +" pass # Z(A,B) não pode ser criado no Python 2.3\n" +"\n" +"class ex_5:\n" +" \"Meu primeiro exemplo\"\n" +" class O: pass\n" +" class F(O): pass\n" +" class E(O): pass\n" +" class D(O): pass\n" +" class C(D,F): pass\n" +" class B(D,E): pass\n" +" class A(B,C): pass\n" +"\n" +"class ex_6:\n" +" \"Meu segundo exemplo\"\n" +" class O: pass\n" +" class F(O): pass\n" +" class E(O): pass\n" +" class D(O): pass\n" +" class C(D,F): pass\n" +" class B(E,D): pass\n" +" class A(B,C): pass\n" +"\n" +"class ex_9:\n" +" \"Diferença entre MRO do Python 2.2 e o C3\" #por Samuele\n" +" class O: pass\n" +" class A(O): pass\n" +" class B(O): pass\n" +" class C(O): pass\n" +" class D(O): pass\n" +" class E(O): pass\n" +" class K1(A,B,C): pass\n" +" class K2(D,B,E): pass\n" +" class K3(D,A): pass\n" +" class Z(K1,K2,K3): pass\n" +"\n" +"def merge(seqs):\n" +" print '\\n\\nCPL[%s]=%s' % (seqs[0][0],seqs),\n" +" res = []; i=0\n" +" while 1:\n" +" nonemptyseqs=[seq for seq in seqs if seq]\n" +" if not nonemptyseqs: return res\n" +" i+=1; print '\\n',i,'round: candidates...',\n" +" for seq in nonemptyseqs: # encontra candidatos a mesclagem entre os " +"heads da sequência\n" +" cand = seq[0]; print ' ',cand,\n" +" nothead=[s for s in nonemptyseqs if cand in s[1:]]\n" +" if nothead: cand=None #rejeita candidato\n" +" else: break\n" +" if not cand: raise \"Hierarquia inconsistente\"\n" +" res.append(cand)\n" +" for seq in nonemptyseqs: # remove candidato\n" +" if seq[0] == cand: del seq[0]\n" +"\n" +"def mro(C):\n" +" \"Calcula a lista de precedência da classe (mro) conforme C3\"\n" +" return merge([[C]]+map(mro,C.__bases__)+[list(C.__bases__)])\n" +"\n" +"def print_mro(C):\n" +" print '\\nMRO[%s]=%s' % (C,mro(C))\n" +" print '\\nP22 MRO[%s]=%s' % (C,C.mro())\n" +"\n" +"print_mro(ex_9.Z)\n" +"\n" +"#" + #: ../../howto/mro.rst:656 msgid "That's all folks," msgstr "Isso é tudo, pessoal!" diff --git a/howto/perf_profiling.po b/howto/perf_profiling.po index ef688aa6b..26f872fc8 100644 --- a/howto/perf_profiling.po +++ b/howto/perf_profiling.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hemílio Lauro , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2023-05-24 13:07+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-04-18 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -95,16 +94,160 @@ msgstr "" msgid "For example, consider the following script:" msgstr "Por exemplo, considere o seguinte script:" +#: ../../howto/perf_profiling.rst:38 +msgid "" +"def foo(n):\n" +" result = 0\n" +" for _ in range(n):\n" +" result += 1\n" +" return result\n" +"\n" +"def bar(n):\n" +" foo(n)\n" +"\n" +"def baz(n):\n" +" bar(n)\n" +"\n" +"if __name__ == \"__main__\":\n" +" baz(1000000)" +msgstr "" +"def foo(n):\n" +" result = 0\n" +" for _ in range(n):\n" +" result += 1\n" +" return result\n" +"\n" +"def bar(n):\n" +" foo(n)\n" +"\n" +"def baz(n):\n" +" bar(n)\n" +"\n" +"if __name__ == \"__main__\":\n" +" baz(1000000)" + #: ../../howto/perf_profiling.rst:55 msgid "We can run ``perf`` to sample CPU stack traces at 9999 hertz::" msgstr "" "Podemos executar ``perf`` para obter amostras de rastreamentos de pilha da " "CPU em 9999 hertz::" +#: ../../howto/perf_profiling.rst:57 +msgid "$ perf record -F 9999 -g -o perf.data python my_script.py" +msgstr "$ perf record -F 9999 -g -o perf.data python meu_script.py" + #: ../../howto/perf_profiling.rst:59 msgid "Then we can use ``perf report`` to analyze the data:" msgstr "Então podemos usar ``perf report`` para analisar os dados:" +#: ../../howto/perf_profiling.rst:61 +msgid "" +"$ perf report --stdio -n -g\n" +"\n" +"# Children Self Samples Command Shared Object Symbol\n" +"# ........ ........ ............ .......... .................. ..........................................\n" +"#\n" +" 91.08% 0.00% 0 python.exe python.exe [.] " +"_start\n" +" |\n" +" ---_start\n" +" |\n" +" --90.71%--__libc_start_main\n" +" Py_BytesMain\n" +" |\n" +" |--56.88%--pymain_run_python.constprop.0\n" +" | |\n" +" | |--56.13%--_PyRun_AnyFileObject\n" +" | | _PyRun_SimpleFileObject\n" +" | | |\n" +" | | |--55.02%--run_mod\n" +" | | | |\n" +" | | | --54.65%--" +"PyEval_EvalCode\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | |\n" +" | | | " +"|--51.67%--_PyEval_EvalFrameDefault\n" +" | | | " +"| |\n" +" | | | " +"| |--11.52%--_PyLong_Add\n" +" | | | " +"| | |\n" +" | | | " +"| | |--2.97%--_PyObject_Malloc\n" +"..." +msgstr "" +"$ perf report --stdio -n -g\n" +"\n" +"# Children Self Samples Command Shared Object Symbol\n" +"# ........ ........ ............ .......... .................. ..........................................\n" +"#\n" +" 91.08% 0.00% 0 python.exe python.exe [.] " +"_start\n" +" |\n" +" ---_start\n" +" |\n" +" --90.71%--__libc_start_main\n" +" Py_BytesMain\n" +" |\n" +" |--56.88%--pymain_run_python.constprop.0\n" +" | |\n" +" | |--56.13%--_PyRun_AnyFileObject\n" +" | | _PyRun_SimpleFileObject\n" +" | | |\n" +" | | |--55.02%--run_mod\n" +" | | | |\n" +" | | | --54.65%--" +"PyEval_EvalCode\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | |\n" +" | | | " +"|--51.67%--_PyEval_EvalFrameDefault\n" +" | | | " +"| |\n" +" | | | " +"| |--11.52%--_PyLong_Add\n" +" | | | " +"| | |\n" +" | | | " +"| | |--2.97%--_PyObject_Malloc\n" +"..." + #: ../../howto/perf_profiling.rst:100 msgid "" "As you can see, the Python functions are not shown in the output, only " @@ -126,6 +269,128 @@ msgstr "" "Em vez disso, se executarmos o mesmo experimento com o suporte ``perf`` " "ativado, obteremos:" +#: ../../howto/perf_profiling.rst:107 +msgid "" +"$ perf report --stdio -n -g\n" +"\n" +"# Children Self Samples Command Shared Object Symbol\n" +"# ........ ........ ............ .......... .................. .....................................................................\n" +"#\n" +" 90.58% 0.36% 1 python.exe python.exe [.] " +"_start\n" +" |\n" +" ---_start\n" +" |\n" +" --89.86%--__libc_start_main\n" +" Py_BytesMain\n" +" |\n" +" |--55.43%--pymain_run_python.constprop.0\n" +" | |\n" +" | |--54.71%--_PyRun_AnyFileObject\n" +" | | _PyRun_SimpleFileObject\n" +" | | |\n" +" | | |--53.62%--run_mod\n" +" | | | |\n" +" | | | --53.26%--" +"PyEval_EvalCode\n" +" | | | py::" +":/src/script.py\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | py::baz:/" +"src/script.py\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | py::bar:/" +"src/script.py\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | py::foo:/" +"src/script.py\n" +" | | | |\n" +" | | | " +"|--51.81%--_PyEval_EvalFrameDefault\n" +" | | | " +"| |\n" +" | | | " +"| |--13.77%--_PyLong_Add\n" +" | | | " +"| | |\n" +" | | | " +"| | |--3.26%--_PyObject_Malloc" +msgstr "" +"$ perf report --stdio -n -g\n" +"\n" +"# Children Self Samples Command Shared Object Symbol\n" +"# ........ ........ ............ .......... .................. .....................................................................\n" +"#\n" +" 90.58% 0.36% 1 python.exe python.exe [.] " +"_start\n" +" |\n" +" ---_start\n" +" |\n" +" --89.86%--__libc_start_main\n" +" Py_BytesMain\n" +" |\n" +" |--55.43%--pymain_run_python.constprop.0\n" +" | |\n" +" | |--54.71%--_PyRun_AnyFileObject\n" +" | | _PyRun_SimpleFileObject\n" +" | | |\n" +" | | |--53.62%--run_mod\n" +" | | | |\n" +" | | | --53.26%--" +"PyEval_EvalCode\n" +" | | | py::" +":/src/script.py\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | py::baz:/" +"src/script.py\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | py::bar:/" +"src/script.py\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | py::foo:/" +"src/script.py\n" +" | | | |\n" +" | | | " +"|--51.81%--_PyEval_EvalFrameDefault\n" +" | | | " +"| |\n" +" | | | " +"| |--13.77%--_PyLong_Add\n" +" | | | " +"| | |\n" +" | | | " +"| | |--3.26%--_PyObject_Malloc" + #: ../../howto/perf_profiling.rst:152 msgid "How to enable ``perf`` profiling support" msgstr "Como habilitar o suporte a perfilação com ``perf``" @@ -154,18 +419,62 @@ msgstr "" msgid "Example, using the environment variable::" msgstr "Exemplo usando a variável de ambiente::" +#: ../../howto/perf_profiling.rst:165 +msgid "" +"$ PYTHONPERFSUPPORT=1 perf record -F 9999 -g -o perf.data python my_script." +"py\n" +"$ perf report -g -i perf.data" +msgstr "" +"$ PYTHONPERFSUPPORT=1 perf record -F 9999 -g -o perf.data python meu_script." +"py\n" +"$ perf report -g -i perf.data" + #: ../../howto/perf_profiling.rst:168 msgid "Example, using the :option:`!-X` option::" msgstr "Exemplo usando a opção :option:`!-X`::" +#: ../../howto/perf_profiling.rst:170 +msgid "" +"$ perf record -F 9999 -g -o perf.data python -X perf my_script.py\n" +"$ perf report -g -i perf.data" +msgstr "" +"$ perf record -F 9999 -g -o perf.data python -X perf meu_script.py\n" +"$ perf report -g -i perf.data" + #: ../../howto/perf_profiling.rst:173 msgid "Example, using the :mod:`sys` APIs in file :file:`example.py`:" msgstr "Exemplo usando as APIs de :mod:`sys` em :file:`example.py`:" +#: ../../howto/perf_profiling.rst:175 +msgid "" +"import sys\n" +"\n" +"sys.activate_stack_trampoline(\"perf\")\n" +"do_profiled_stuff()\n" +"sys.deactivate_stack_trampoline()\n" +"\n" +"non_profiled_stuff()" +msgstr "" +"import sys\n" +"\n" +"sys.activate_stack_trampoline(\"perf\")\n" +"do_profiled_stuff()\n" +"sys.deactivate_stack_trampoline()\n" +"\n" +"non_profiled_stuff()" + #: ../../howto/perf_profiling.rst:185 msgid "...then::" msgstr "... então::" +#: ../../howto/perf_profiling.rst:187 +msgid "" +"$ perf record -F 9999 -g -o perf.data python ./example.py\n" +"$ perf report -g -i perf.data" +msgstr "" +"$ perf record -F 9999 -g -o perf.data python ./example.py\n" +"$ perf report -g -i perf.data" + #: ../../howto/perf_profiling.rst:192 msgid "How to obtain the best results" msgstr "Como obter os melhores resultados" @@ -194,6 +503,10 @@ msgstr "" "Você pode verificar se o seu sistema foi compilado com este sinalizador " "executando::" +#: ../../howto/perf_profiling.rst:203 +msgid "$ python -m sysconfig | grep 'no-omit-frame-pointer'" +msgstr "$ python -m sysconfig | grep 'no-omit-frame-pointer'" + #: ../../howto/perf_profiling.rst:205 msgid "" "If you don't see any output it means that your interpreter has not been " @@ -267,10 +580,34 @@ msgstr "" "executar ``perf report``. Você precisa chamar o comando ``perf inject`` para " "injetar as informações JIT no arquivo ``perf.data``.::" +#: ../../howto/perf_profiling.rst:239 +msgid "" +"$ perf record -F 9999 -g -k 1 --call-graph dwarf -o perf.data python -" +"Xperf_jit my_script.py\n" +"$ perf inject -i perf.data --jit --output perf.jit.data\n" +"$ perf report -g -i perf.jit.data" +msgstr "" +"$ perf record -F 9999 -g -k 1 --call-graph dwarf -o perf.data python -" +"Xperf_jit meu_script.py\n" +"$ perf inject -i perf.data --jit --output perf.jit.data\n" +"$ perf report -g -i perf.jit.data" + #: ../../howto/perf_profiling.rst:243 msgid "or using the environment variable::" msgstr "ou usando a variável de ambiente::" +#: ../../howto/perf_profiling.rst:245 +msgid "" +"$ PYTHON_PERF_JIT_SUPPORT=1 perf record -F 9999 -g --call-graph dwarf -o " +"perf.data python my_script.py\n" +"$ perf inject -i perf.data --jit --output perf.jit.data\n" +"$ perf report -g -i perf.jit.data" +msgstr "" +"$ PYTHON_PERF_JIT_SUPPORT=1 perf record -F 9999 -g --call-graph dwarf -o " +"perf.data python meu_script.py\n" +"$ perf inject -i perf.data --jit --output perf.jit.data\n" +"$ perf report -g -i perf.jit.data" + #: ../../howto/perf_profiling.rst:249 msgid "" "``perf inject --jit`` command will read ``perf.data``, automatically pick up " @@ -289,22 +626,79 @@ msgstr "" #: ../../howto/perf_profiling.rst:257 msgid "" -"Notice that when using ``--call-graph dwarf`` the ``perf`` tool will take " -"snapshots of the stack of the process being profiled and save the " -"information in the ``perf.data`` file. By default the size of the stack dump " -"is 8192 bytes but the user can change the size by passing the size after " -"comma like ``--call-graph dwarf,4096``. The size of the stack dump is " -"important because if the size is too small ``perf`` will not be able to " -"unwind the stack and the output will be incomplete. On the other hand, if " -"the size is too big, then ``perf`` won't be able to sample the process as " -"frequently as it would like as the overhead will be higher." -msgstr "" -"Observe que ao usar ``--call-graph dwarf``, a ferramenta ``perf`` fará " -"snapshots da pilha do processo que está sendo perfilado e salvará as " -"informações no arquivo ``perf.data``. Por padrão, o tamanho do dump da pilha " -"é 8192 bytes, mas o usuário pode alterar o tamanho passando o tamanho após a " -"vírgula como ``--call-graph dwarf,4096``. O tamanho do dump da pilha é " -"importante porque se o tamanho for muito pequeno, ``perf`` não conseguirá " -"desenrolar a pilha e a saída ficará incompleta. Por outro lado, se o tamanho " -"for muito grande, então ``perf`` não conseguirá amostrar o processo com a " -"frequência que gostaria, pois a sobrecarga será maior." +"When using ``--call-graph dwarf``, the ``perf`` tool will take snapshots of " +"the stack of the process being profiled and save the information in the " +"``perf.data`` file. By default, the size of the stack dump is 8192 bytes, " +"but you can change the size by passing it after a comma like ``--call-graph " +"dwarf,16384``." +msgstr "" +"Ao usar ``--call-graph dwarf``, a ferramenta ``perf`` fará snapshots da " +"pilha do processo que está sendo perfilado e salvará as informações no " +"arquivo ``perf.data``. Por padrão, o tamanho do dump da pilha é de 8192 " +"bytes, mas você pode alterar o tamanho passando-o após uma vírgula, como ``--" +"call-graph dwarf,16384``." + +#: ../../howto/perf_profiling.rst:263 +msgid "" +"The size of the stack dump is important because if the size is too small " +"``perf`` will not be able to unwind the stack and the output will be " +"incomplete. On the other hand, if the size is too big, then ``perf`` won't " +"be able to sample the process as frequently as it would like as the overhead " +"will be higher." +msgstr "" +"O tamanho do dump da pilha é importante porque, se for muito pequeno, o " +"``perf`` não conseguirá desfazer o descompasso da pilha e a saída será " +"incompleta. Por outro lado, se for muito grande, o ``perf`` não conseguirá " +"amostrar o processo com a frequência desejada, pois a sobrecarga será maior." + +#: ../../howto/perf_profiling.rst:269 +msgid "" +"The stack size is particularly important when profiling Python code compiled " +"with low optimization levels (like ``-O0``), as these builds tend to have " +"larger stack frames. If you are compiling Python with ``-O0`` and not seeing " +"Python functions in your profiling output, try increasing the stack dump " +"size to 65528 bytes (the maximum)::" +msgstr "" +"O tamanho da pilha é particularmente importante ao criar perfis de código " +"Python compilado com níveis de otimização baixos (como ``-O0``), pois essas " +"construções tendem a ter quadros de pilha maiores. Se você estiver " +"compilando Python com ``-O0`` e não estiver vendo funções Python na saída do " +"perfil, tente aumentar o tamanho do despejo de pilha para 65528 bytes (o " +"máximo):" + +#: ../../howto/perf_profiling.rst:275 +msgid "" +"$ perf record -F 9999 -g -k 1 --call-graph dwarf,65528 -o perf.data python -" +"Xperf_jit my_script.py" +msgstr "" +"$ perf record -F 9999 -g -k 1 --call-graph dwarf,65528 -o perf.data python -" +"Xperf_jit meu_script.py" + +#: ../../howto/perf_profiling.rst:277 +msgid "Different compilation flags can significantly impact stack sizes:" +msgstr "" +"Diferentes sinalizadores de compilação podem impactar significativamente os " +"tamanhos de pilha:" + +#: ../../howto/perf_profiling.rst:279 +msgid "" +"Builds with ``-O0`` typically have much larger stack frames than those with " +"``-O1`` or higher" +msgstr "" +"Construções com ``-O0`` geralmente têm quadros de pilha muito maiores do que " +"aquelas com ``-O1`` ou superior" + +#: ../../howto/perf_profiling.rst:280 +msgid "" +"Adding optimizations (``-O1``, ``-O2``, etc.) typically reduces stack size" +msgstr "" +"Adiciona otimizações (``-O1``, ``-O2``, etc.) normalmente reduz o tamanho da " +"pilha" + +#: ../../howto/perf_profiling.rst:281 +msgid "" +"Frame pointers (``-fno-omit-frame-pointer``) generally provide more reliable " +"stack unwinding" +msgstr "" +"Os ponteiros de quadro (``-fno-omit-frame-pointer``) geralmente fornecem um " +"desenrolamento de pilha mais confiável" diff --git a/howto/pyporting.po b/howto/pyporting.po index 09689edc6..0d1d4cc4d 100644 --- a/howto/pyporting.po +++ b/howto/pyporting.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hemílio Lauro , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:53+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/howto/regex.po b/howto/regex.po index deb5fff56..305b2cc6a 100644 --- a/howto/regex.po +++ b/howto/regex.po @@ -1,38 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Welington Carlos , 2021 -# Ruan Aragão , 2021 -# i17obot , 2021 -# Denis Vicentainer , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Leticia Portella , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:53+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../howto/regex.rst:5 msgid "Regular Expression HOWTO" -msgstr "Expressões Regulares HOWTO" +msgstr "Expressões Regulares" #: ../../howto/regex.rst:0 msgid "Author" @@ -76,8 +69,8 @@ msgstr "" "essencialmente uma mini linguagem de programação altamente especializada " "incluída dentro do Python e disponível através do módulo :mod:`re`. Usando " "esta pequena linguagem, você especifica as regras para o conjunto de strings " -"possíveis que você quer combinar; esse conjunto pode conter sentenças em " -"inglês, endereços de e-mail, ou comandos TeX ou qualquer coisa que você " +"possíveis que você quer corresponder; esse conjunto pode conter sentenças em " +"português, endereços de e-mail, comandos TeX ou qualquer coisa que você " "queira. Você poderá então perguntar coisas como \"Essa string se enquadra " "dentro do padrão?\" ou \"Existe alguma parte da string que se enquadra nesse " "padrão?\". Você também pode usar as REs para modificar uma string ou dividi-" @@ -94,12 +87,12 @@ msgid "" "internals." msgstr "" "Os padrões das expressões regulares são compilados em uma série de bytecodes " -"que são então executadas por um mecanismo de combinação escrito em C. Para " -"usos avançados, talvez seja necessário prestar atenção em como o mecanismo " -"irá executar uma dada RE, e escrever a RE de forma que os bytecodes executem " -"de forma mais rápida. Otimização é um tema que não será visto neste " -"documento, porque ele requer que você tenha um bom entendimento dos " -"mecanismos de combinação internos." +"que são então executadas por um mecanismo de correspondência escrito em C. " +"Para usos avançados, talvez seja necessário prestar atenção em como o " +"mecanismo irá executar uma dada RE, e escrever a RE de forma que os " +"bytecodes executem de forma mais rápida. Otimização é um tema que não será " +"visto neste documento, porque ele requer que você tenha um bom entendimento " +"dos mecanismos de combinação internos." #: ../../howto/regex.rst:42 msgid "" @@ -112,21 +105,17 @@ msgid "" "more understandable." msgstr "" "A linguagem de expressão regular é relativamente pequena e restrita, por " -"isso nem\n" -"todas as tarefas de processamento de strings possíveis podem ser feitas " -"usando\n" -"expressões regulares. Existem também tarefas que podem ser feitas com " -"expressões\n" -"regulares, mas as expressões acabam por ser tornar muito complicadas. Nestes " -"casos, pode\n" -"ser melhor para você escrever um código Python para fazer o processamento;\n" -"embora um código Python seja mais lento do que uma expressão regular " -"elaborada,\n" -"ele provavelmente será mais compreensível." +"isso nem todas as tarefas de processamento de strings possíveis podem ser " +"feitas usando expressões regulares. Existem também tarefas que podem ser " +"feitas com expressões regulares, mas as expressões acabam por se tornarem " +"muito complicadas. Nestes casos, pode ser melhor para você escrever um " +"código Python para fazer o processamento; embora um código Python seja mais " +"lento do que uma expressão regular elaborada, ele provavelmente será mais " +"compreensível." #: ../../howto/regex.rst:51 msgid "Simple Patterns" -msgstr "Padrões Simples" +msgstr "Padrões simples" #: ../../howto/regex.rst:53 msgid "" @@ -138,7 +127,7 @@ msgstr "" "possíveis.\n" "Como as expressões regulares são usadas para operar em strings, vamos " "começar\n" -"com a tarefa mais comum: de correspondência caracteres." +"com a tarefa mais comum: correspondência de caracteres." #: ../../howto/regex.rst:57 msgid "" @@ -154,7 +143,7 @@ msgstr "" #: ../../howto/regex.rst:63 msgid "Matching Characters" -msgstr "Caracteres Correspondentes" +msgstr "Correspondendo caracteres" #: ../../howto/regex.rst:65 msgid "" @@ -164,11 +153,10 @@ msgid "" "``TEST`` as well; more about this later.)" msgstr "" "A maioria das letras e caracteres simplesmente irão corresponder entre si. " -"Por exemplo, a expressão regular ``teste``\n" -"irá combinar com a string ``teste`` totalmente. (Você pode habilitar o modo " -"de maiúsculas e minúsculas que faria com que\n" -"a RE corresponder com ``Test`` ou ``TEST`` também; veremos mais sobre isso " -"mais adiante.)" +"Por exemplo, a expressão regular ``teste`` irá combinar totalmente com a " +"string ``teste``. (Você pode habilitar o modo de maiúsculas e minúsculas que " +"faria a RE corresponder com ``Test`` ou ``TEST`` também; veremos mais sobre " +"isso mais adiante.)" #: ../../howto/regex.rst:70 msgid "" @@ -180,14 +168,10 @@ msgid "" "do." msgstr "" "Há exceções a essa regra, alguns caracteres são metacaracteres especiais, e " -"não se\n" -"correspondem. Em vez disso, eles sinalizam que alguma coisa fora do normal " -"deve\n" -"ser correspondida, ou eles afetam outras partes da RE, repetindo-as ou " -"alterando seus\n" -"significados. Grande parte deste documento é dedicada à discussão de vários " -"metacaracteres\n" -"e o que eles fazem." +"não se correspondem. Em vez disso, eles sinalizam que alguma coisa fora do " +"normal deve ser correspondida, ou eles afetam outras partes da RE, repetindo-" +"as ou alterando seus significados. Grande parte deste documento é dedicada à " +"discussão de vários metacaracteres e o que eles fazem." #: ../../howto/regex.rst:76 msgid "" @@ -197,6 +181,10 @@ msgstr "" "Aqui está a lista completa de metacaracteres; seus significados serão " "discutidos ao longo deste documento." +#: ../../howto/regex.rst:79 +msgid ". ^ $ * + ? { } [ ] \\ | ( )" +msgstr ". ^ $ * + ? { } [ ] \\ | ( )" + #: ../../howto/regex.rst:83 msgid "" "The first metacharacters we'll look at are ``[`` and ``]``. They're used for " @@ -208,14 +196,14 @@ msgid "" "characters. If you wanted to match only lowercase letters, your RE would be " "``[a-z]``." msgstr "" -"O primeiro metacaractere que vamos estudos é o ``[`` e o ``]``.  Eles são " +"O primeiro metacaractere que vamos estudar é o ``[`` e o ``]``. Eles são " "usados para especificar uma classe de caracteres, que é um conjunto de " "caracteres que você deseja combinar. Caracteres podem ser listados " -"individualmente ou um range de caracteres pode ser indicado dando dois " -"caracteres e separando-os por um ``'-'``.  Por exemplo, ``[abc]`` irá " +"individualmente ou um intervalo de caracteres pode ser indicado fornecendo " +"dois caracteres e separando-os por um ``'-'``. Por exemplo, ``[abc]`` irá " "encontrar qualquer caractere ``a``, ``b``, ou ``c``; isso é o mesmo que " -"escrever ``[a-c]``, que usa um range para expressar o mesmo conjunto de " -"caracteres, Se você deseja encontrar apenas letras minúsculas, sua RE seria " +"escrever ``[a-c]``, que usa um intervalo para expressar o mesmo conjunto de " +"caracteres. Se você deseja encontrar apenas letras minúsculas, sua RE seria " "``[a-z]``." #: ../../howto/regex.rst:92 @@ -225,6 +213,10 @@ msgid "" "``'$'``; ``'$'`` is usually a metacharacter, but inside a character class " "it's stripped of its special nature." msgstr "" +"Metacaracteres (exceto ``\\``) não são ativos dentro de classes. Por " +"exemplo, ``[akm$]`` irá corresponder com qualquer dos caracteres ``'a'``, " +"``'k'``, ``'m'`` ou ``'$'``; ``'$'`` é normalmente um metacaractere, mas " +"dentro de uma classe de caracteres ele perde sua natureza especial." #: ../../howto/regex.rst:97 msgid "" @@ -251,7 +243,7 @@ msgid "" "need to match a ``[`` or ``\\``, you can precede them with a backslash to " "remove their special meaning: ``\\[`` or ``\\\\``." msgstr "" -"Talvez o metacaractere mais importante é a contrabarra, ``\\``. Como as " +"Talvez o metacaractere mais importante seja a contrabarra, ``\\``. Como as " "strings literais em Python, a barra invertida pode ser seguida por vários " "caracteres para sinalizar várias sequências especiais. Ela também é usada " "para *escapar* todos os metacaracteres, e assim, você poder combiná-los em " @@ -298,7 +290,7 @@ msgid "" msgstr "" "A lista a seguir de sequências especiais não está completa. Para obter uma " "lista completa das sequências e definições de classe expandidas para padrões " -"de Strings Unicode, veja a última parte de :ref:`Sintaxe de Expressão " +"de strings Unicode, veja a última parte de :ref:`Sintaxe de Expressão " "Regular ` na referência da Biblioteca Padrão. Em geral, as " "versões Unicode correspondem a qualquer caractere que esteja na categoria " "apropriada do banco de dados Unicode." @@ -378,9 +370,9 @@ msgid "" "``[\\s,.]`` is a character class that will match any whitespace character, " "or ``','`` or ``'.'``." msgstr "" -"Estas sequências podem ser incluídas dentro de uma classe caractere. Por " -"exemplo, ``[\\s,.]`` É uma classe caractere que irá corresponder a qualquer " -"caractere ``espaço-em-branco``, ou ``,`` ou ``.``." +"Estas sequências podem ser incluídas dentro de uma classe de caractere. Por " +"exemplo, ``[\\s,.]`` É uma classe de caractere que irá corresponder a " +"qualquer caractere ``espaço-em-branco``, ou ``,`` ou ``.``." #: ../../howto/regex.rst:156 msgid "" @@ -397,7 +389,7 @@ msgstr "" #: ../../howto/regex.rst:163 msgid "Repeating Things" -msgstr "Repetindo Coisas" +msgstr "Repetindo coisas" #: ../../howto/regex.rst:165 msgid "" @@ -431,8 +423,8 @@ msgid "" "For example, ``ca*t`` will match ``'ct'`` (0 ``'a'`` characters), ``'cat'`` " "(1 ``'a'``), ``'caaat'`` (3 ``'a'`` characters), and so forth." msgstr "" -"Por exemplo, ``ca*t`` vai corresponder ``'ct'`` (0 ``'a'`` caracteres), " -"``'cat'`` (1 ``'a'``), ``'caaat'`` (3 ``'a'`` caracteres), e assim por " +"Por exemplo, ``ca*t`` vai corresponder ``'ct'`` (0 caracteres ``'a'``), " +"``'cat'`` (1 ``'a'``), ``'caaat'`` (3 caracteres ``'a'``), e assim por " "diante." #: ../../howto/regex.rst:178 @@ -442,10 +434,10 @@ msgid "" "portions of the pattern don't match, the matching engine will then back up " "and try again with fewer repetitions." msgstr "" -"Repetições, tais como ``*`` são gananciosas; ao repetir a RE, o motor de " +"Repetições tais como ``*`` são gulosas; ao repetir a RE, o motor de " "correspondência vai tentar repeti-la tantas vezes quanto possível. Se " "porções posteriores do padrão não corresponderem, o motor de " -"correspondência, em seguida, volta e tenta novamente com algumas repetições." +"correspondência, em seguida, volta e tenta novamente com menos repetições." #: ../../howto/regex.rst:183 msgid "" @@ -469,7 +461,7 @@ msgstr "Correspondência" #: ../../howto/regex.rst:189 msgid "Explanation" -msgstr "Explanação" +msgstr "Explicação" #: ../../howto/regex.rst:191 msgid "1" @@ -496,8 +488,8 @@ msgid "" "The engine matches ``[bcd]*``, going as far as it can, which is to the end " "of the string." msgstr "" -"O motor corresponde com [bcd]*, indo tão longe quanto possível, que é o fim " -"do string." +"O motor corresponde com ``[bcd]*``, indo tão longe quanto possível, que é o " +"fim do string." #: ../../howto/regex.rst:197 msgid "3" @@ -537,7 +529,7 @@ msgid "" "a ``'d'``." msgstr "" "Tenta ``b`` novamente, mas a posição corrente é a do último caractere, que é " -"um ``d``." +"um ``'d'``." #: ../../howto/regex.rst:209 ../../howto/regex.rst:213 msgid "6" @@ -550,7 +542,7 @@ msgstr "``abc``" #: ../../howto/regex.rst:209 msgid "Back up again, so that ``[bcd]*`` is only matching ``bc``." msgstr "" -"Voltando novamente, de modo que [bcd]* está correspondendo com ``bc`` " +"Voltando novamente, de modo que ``[bcd]*`` está correspondendo com ``bc`` " "somente." #: ../../howto/regex.rst:213 @@ -558,7 +550,7 @@ msgid "" "Try ``b`` again. This time the character at the current position is " "``'b'``, so it succeeds." msgstr "" -"Tenta ``b`` novamente. Desta vez, o caractere na posição corrente é ``b``, " +"Tenta ``b`` novamente. Desta vez, o caractere na posição corrente é ``'b'``, " "por isso sucesso." #: ../../howto/regex.rst:219 @@ -572,8 +564,8 @@ msgid "" msgstr "" "O final da RE foi atingido e correspondeu a ``'abcb'``. Isso demonstra como " "o mecanismo de correspondência vai tão longe quanto pode no início e, se " -"nenhuma correspondência for encontrada, ele fará o backup progressivamente e " -"tentará novamente o restante da RE. Ele fará backup até que tenha tentado " +"nenhuma correspondência for encontrada, ele fará a volta progressivamente e " +"tentará novamente o restante da RE. Ele fará voltas até que tenha tentado " "zero correspondências para ``[bcd]*``, e se isso falhar subsequentemente, o " "mecanismo concluirá que a string não corresponde a RE de forma alguma." @@ -586,6 +578,13 @@ msgid "" "similar example, ``ca+t`` will match ``'cat'`` (1 ``'a'``), ``'caaat'`` (3 " "``'a'``\\ s), but won't match ``'ct'``." msgstr "" +"Outro metacaractere de repetição é o ``+``, que corresponde a uma ou mais " +"vezes. Preste muita atenção para a diferença entre ``*`` e ``+``; ``*`` " +"corresponde com zero ou mais vezes, assim, o que quer que esteja sendo " +"repetido pode não estar presente, enquanto que ``+`` requer pelo menos uma " +"ocorrência. Para usar um exemplo similar, ``ca+t`` vai corresponder a " +"``'cat'``, (1 ``'a'``), ``'caaat'`` (3 ``'a'``\\ s), mas não corresponde com " +"``'ct'``." #: ../../howto/regex.rst:233 msgid "" @@ -594,6 +593,10 @@ msgid "" "marking something as being optional. For example, ``home-?brew`` matches " "either ``'homebrew'`` or ``'home-brew'``." msgstr "" +"Existem mais dois quantificadores ou operadores de repetição. O caractere de " +"ponto de interrogação, ``?``, corresponde a uma ou zero vez; você pode " +"pensar nisso como a marcação de algo sendo opcional. Por exemplo, ``home-?" +"brew`` corresponde tanto a ``'homebrew'`` quanto a ``'home-brew'``." #: ../../howto/regex.rst:238 msgid "" @@ -603,6 +606,11 @@ msgid "" "and ``'a///b'``. It won't match ``'ab'``, which has no slashes, or ``'a////" "b'``, which has four." msgstr "" +"O qualificador mais complicado é o ``{m,n}``, no qual *m* e *n* são números " +"inteiros decimais. Este qualificador significa que deve haver pelo menos *m* " +"repetições, e no máximo *n*. Por exemplo, ``a/{1,3}b`` irá corresponder a " +"``'a/b'``, ``'a//b'`` e ``'a///b'``. Não vai corresponder a ``'ab'``, que " +"não tem barras ou a ``'a////b'``, que tem quatro." #: ../../howto/regex.rst:244 msgid "" @@ -610,12 +618,18 @@ msgid "" "for the missing value. Omitting *m* is interpreted as a lower limit of 0, " "while omitting *n* results in an upper bound of infinity." msgstr "" +"Você pode omitir tanto *m* quanto *n*; nesse caso, um valor razoável é " +"presumido para o valor em falta. A omissão de *m* é interpretada como o " +"limite inferior de 0, enquanto a omissão de *n* resulta como limite superior " +"o infinito." #: ../../howto/regex.rst:248 msgid "" "The simplest case ``{m}`` matches the preceding item exactly *m* times. For " "example, ``a/{2}b`` will only match ``'a//b'``." msgstr "" +"O caso mais simples ``{m}`` corresponde ao item precedente exatamente *m* " +"vezes. Por exemplo, ``a/{2}b`` corresponderá somente a ``'a//b'``." #: ../../howto/regex.rst:251 msgid "" @@ -625,6 +639,11 @@ msgid "" "better to use ``*``, ``+``, or ``?`` when you can, simply because they're " "shorter and easier to read." msgstr "" +"Os leitores de uma inclinação reducionista podem notar que os três outros " +"quantificadores podem todos serem expressos utilizando esta notação. ``{0,}" +"`` é o mesmo que ``*``, ``{1,}`` é equivalente a ``+``, e ``{0,1}`` é o " +"mesmo que ``?``. É melhor usar ``*``, ``+`` ou ``?`` quando puder, " +"simplesmente porque eles são mais curtos e fáceis de ler." #: ../../howto/regex.rst:259 msgid "Using Regular Expressions" @@ -644,7 +663,7 @@ msgstr "" #: ../../howto/regex.rst:268 msgid "Compiling Regular Expressions" -msgstr "Compilando Expressões Regulares" +msgstr "Compilando expressões regulares" #: ../../howto/regex.rst:270 msgid "" @@ -656,17 +675,33 @@ msgstr "" "para várias operações, tais como a procura por padrões de correspondência ou " "realizar substituições de strings. ::" +#: ../../howto/regex.rst:274 +msgid "" +">>> import re\n" +">>> p = re.compile('ab*')\n" +">>> p\n" +"re.compile('ab*')" +msgstr "" +">>> import re\n" +">>> p = re.compile('ab*')\n" +">>> p\n" +"re.compile('ab*')" + #: ../../howto/regex.rst:279 msgid "" ":func:`re.compile` also accepts an optional *flags* argument, used to enable " "various special features and syntax variations. We'll go over the available " "settings later, but for now a single example will do::" msgstr "" -":func:`re.compile()` também aceita um argumento opcional *flags*, utilizados " +":func:`re.compile` também aceita um argumento opcional *flags*, utilizado " "para habilitar vários recursos especiais e variações de sintaxe. Nós vamos " "ver todas as configurações disponíveis mais tarde, mas por agora, um único " "exemplo vai servir::" +#: ../../howto/regex.rst:283 +msgid ">>> p = re.compile('ab*', re.IGNORECASE)" +msgstr ">>> p = re.compile('ab*', re.IGNORECASE)" + #: ../../howto/regex.rst:285 msgid "" "The RE is passed to :func:`re.compile` as a string. REs are handled as " @@ -695,7 +730,7 @@ msgstr "" #: ../../howto/regex.rst:299 msgid "The Backslash Plague" -msgstr "A praga da barra invertida" +msgstr "A praga da contrabarra" #: ../../howto/regex.rst:301 msgid "" @@ -704,8 +739,8 @@ msgid "" "used without invoking their special meaning. This conflicts with Python's " "usage of the same character for the same purpose in string literals." msgstr "" -"Como afirmado anteriormente, expressões regulares usam o caractere de barra " -"invertida (``\\``) para indicar formas especiais ou para permitir que " +"Como afirmado anteriormente, expressões regulares usam o caractere de " +"contrabarra (``\\``) para indicar formas especiais ou para permitir que " "caracteres especiais sejam usados sem invocar o seu significado especial. " "Isso entra em conflito com o uso pelo Python do mesmo caractere para o mesmo " "propósito nas strings literais." @@ -724,12 +759,12 @@ msgstr "" "Vamos dizer que você quer escrever uma RE que corresponde com a string " "``\\section``, que pode ser encontrada em um arquivo LaTeX. Para descobrir o " "que escrever no código do programa, comece com a string que se deseja " -"corresponder. Em seguida, você deve preceder qualquer barra invertida e " -"outros metacaracteres com uma barra invertida, tendo como resultado a string " -"``\\\\section``. A string resultante que deve ser passada para :func:`re." +"corresponder. Em seguida, você deve preceder qualquer contrabarra e outros " +"metacaracteres com uma contrabarra, tendo como resultado a string ``\\" +"\\section``. A string resultante que deve ser passada para :func:`re." "compile` deve ser ``\\\\section``. No entanto, para expressar isso como uma " -"string literal Python, ambas as barras invertidas devem ser precedidas com " -"uma barra invertida novamente." +"string literal Python, ambas as contrabarras devem ser precedidas com uma " +"contrabarra novamente." #: ../../howto/regex.rst:315 msgid "Characters" @@ -745,7 +780,7 @@ msgstr "``\\section``" #: ../../howto/regex.rst:317 msgid "Text string to be matched" -msgstr "string de texto a ser correspondida" +msgstr "String de texto a ser correspondida" #: ../../howto/regex.rst:319 msgid "``\\\\section``" @@ -753,7 +788,7 @@ msgstr "``\\\\section``" #: ../../howto/regex.rst:319 msgid "Escaped backslash for :func:`re.compile`" -msgstr "preceder com barra invertida para :func:`re.compile`" +msgstr "Preceder com contrabarra para :func:`re.compile`" #: ../../howto/regex.rst:321 ../../howto/regex.rst:348 msgid "``\"\\\\\\\\section\"``" @@ -761,7 +796,7 @@ msgstr "``\"\\\\\\\\section\"``" #: ../../howto/regex.rst:321 msgid "Escaped backslashes for a string literal" -msgstr "barras invertidas precedidas novamente para uma string literal" +msgstr "Contrabarras precedidas novamente para uma string literal" #: ../../howto/regex.rst:324 msgid "" @@ -771,12 +806,12 @@ msgid "" "literal. In REs that feature backslashes repeatedly, this leads to lots of " "repeated backslashes and makes the resulting strings difficult to understand." msgstr "" -"Em suma, para corresponder com uma barra invertida literal, tem de se " -"escrever ``'\\\\\\\\'`` como a string da RE, porque a expressão regular deve " -"ser ``\\\\``, e cada barra invertida deve ser expressa como ``\\\\`` dentro " -"de uma string literal Python normal. Em REs que apresentam barras invertidas " -"repetidas vezes, isso leva a um monte de barras invertidas repetidas e faz " -"as strings resultantes difíceis de entender." +"Em suma, para corresponder com uma contrabarra literal, tem de se escrever " +"``'\\\\\\\\'`` como a string da RE, porque a expressão regular deve ser ``\\" +"\\``, e cada contrabarra deve ser expressa como ``\\\\`` dentro de uma " +"string literal Python normal. Em REs que apresentam contrabarras repetidas " +"vezes, isso leva a um monte de contrabarras repetidas e faz as strings " +"resultantes difíceis de entender." #: ../../howto/regex.rst:330 msgid "" @@ -787,13 +822,13 @@ msgid "" "newline. Regular expressions will often be written in Python code using this " "raw string notation." msgstr "" -"A solução é usar a notação de string crua (raw) do Python para expressões " -"regulares; barras invertidas não são tratadas de nenhuma forma especial em " -"uma string literal se prefixada com ``r``, então ``r\"\\n\"`` é uma string " -"de dois caracteres contendo ``\\`` e ``n``, enquanto ``\"\\n\"`` é uma " -"string de um único caractere contendo uma nova linha. As expressões " -"regulares, muitas vezes, são escritas no código Python usando esta notação " -"de string crua (raw)." +"A solução é usar a notação de string bruta (raw) do Python para expressões " +"regulares; contrabarras não são tratadas de nenhuma forma especial em uma " +"string literal se prefixada com ``r``, então ``r\"\\n\"`` é uma string de " +"dois caracteres contendo ``\\`` e ``n``, enquanto ``\"\\n\"`` é uma string " +"de um único caractere contendo uma nova linha. As expressões regulares, " +"muitas vezes, são escritas no código Python usando esta notação de string " +"bruta (raw)." #: ../../howto/regex.rst:336 msgid "" @@ -803,14 +838,19 @@ msgid "" "means the sequences will be invalid if raw string notation or escaping the " "backslashes isn't used." msgstr "" +"Além disso, sequências de escape especiais que são válidas em expressões " +"regulares, mas não válidas como literais de string do Python, agora resultam " +"em uma :exc:`DeprecationWarning` e eventualmente se tornarão uma :exc:" +"`SyntaxError`, o que significa que as sequências serão inválidas se a " +"notação de string bruta ou o escape das contrabarras não forem usados." #: ../../howto/regex.rst:344 msgid "Regular String" -msgstr "String Regular" +msgstr "String regular" #: ../../howto/regex.rst:344 msgid "Raw string" -msgstr "**String Crua**" +msgstr "**String bruta**" #: ../../howto/regex.rst:346 msgid "``\"ab*\"``" @@ -834,7 +874,7 @@ msgstr "``r\"\\w+\\s+\\1\"``" #: ../../howto/regex.rst:355 msgid "Performing Matches" -msgstr "Executando Comparações" +msgstr "Executando correspondências" #: ../../howto/regex.rst:357 msgid "" @@ -844,7 +884,7 @@ msgid "" "for a complete listing." msgstr "" "Uma vez que você tem um objeto que representa uma expressão regular " -"compilada, o que você faz com ele? Objetos padrão têm vários métodos e " +"compilada, o que você faz com ele? Objetos Pattern têm vários métodos e " "atributos. Apenas os mais significativos serão vistos aqui; consulte a " "documentação do módulo :mod:`re` para uma lista completa." @@ -905,21 +945,40 @@ msgid "" "objects>` instance is returned, containing information about the match: " "where it starts and ends, the substring it matched, and more." msgstr "" +":meth:`~re.Pattern.match` e :meth:`~re.Pattern.search` retornam ``None`` se " +"não existir nenhuma correspondência encontrada. Se tiveram sucesso, uma " +"instância de :ref:`objeto correspondência ` é retornada, " +"contendo informações sobre a correspondência: onde ela começa e termina, a " +"substring com a qual ela teve correspondência, e mais." #: ../../howto/regex.rst:383 msgid "" "You can learn about this by interactively experimenting with the :mod:`re` " "module." msgstr "" +"Você pode aprender mais sobre isso experimentando interativamente com o " +"módulo :mod:`re`." #: ../../howto/regex.rst:386 msgid "" "This HOWTO uses the standard Python interpreter for its examples. First, run " "the Python interpreter, import the :mod:`re` module, and compile a RE::" msgstr "" -"Este HOWTO usa o interpretador Python padrão para seus exemplos. Primeiro, " -"execute o interpretador Python, importe o modulo :mod:`re`, e compile uma " -"RE::" +"Este documento usa o interpretador Python padrão para seus exemplos. " +"Primeiro, execute o interpretador Python, importe o módulo :mod:`re`, e " +"compile uma RE::" + +#: ../../howto/regex.rst:389 +msgid "" +">>> import re\n" +">>> p = re.compile('[a-z]+')\n" +">>> p\n" +"re.compile('[a-z]+')" +msgstr "" +">>> import re\n" +">>> p = re.compile('[a-z]+')\n" +">>> p\n" +"re.compile('[a-z]+')" #: ../../howto/regex.rst:394 msgid "" @@ -929,6 +988,22 @@ msgid "" "which will cause the interpreter to print no output. You can explicitly " "print the result of :meth:`!match` to make this clear. ::" msgstr "" +"Agora, você pode tentar corresponder várias strings com a RE ``[a-z]+``. Mas " +"uma string vazia não deveria corresponder com nada, uma vez que ``+`` " +"significa 'uma ou mais repetições'. :meth:`~re.Pattern.match` deve retornar " +"``None`` neste caso, o que fará com que o interpretador não imprima nenhuma " +"saída. Você pode imprimir explicitamente o resultado de :meth:`!match` para " +"deixar isso claro." + +#: ../../howto/regex.rst:400 +msgid "" +">>> p.match(\"\")\n" +">>> print(p.match(\"\"))\n" +"None" +msgstr "" +">>> p.match(\"\")\n" +">>> print(p.match(\"\"))\n" +"None" #: ../../howto/regex.rst:404 msgid "" @@ -936,6 +1011,20 @@ msgid "" "this case, :meth:`~re.Pattern.match` will return a :ref:`match object `, so you should store the result in a variable for later use. ::" msgstr "" +"Agora, vamos experimentá-la em uma string que ela deve corresponder, como " +"``tempo``. Neste caso, :meth:`~re.Pattern.match` irá retornar um :ref:" +"`objeto correspondência `, assim você deve armazenar o " +"resultado em uma variável para uso posterior." + +#: ../../howto/regex.rst:408 +msgid "" +">>> m = p.match('tempo')\n" +">>> m\n" +"" +msgstr "" +">>> m = p.match('tempo')\n" +">>> m\n" +"" #: ../../howto/regex.rst:412 msgid "" @@ -943,6 +1032,10 @@ msgid "" "about the matching string. Match object instances also have several methods " "and attributes; the most important ones are:" msgstr "" +"Agora você pode consultar o :ref:`objeto correspondência ` " +"para obter informações sobre a string correspondente. Instâncias do objeto " +"correspondência também tem vários métodos e atributos; os mais importantes " +"são os seguintes:" #: ../../howto/regex.rst:419 msgid "``group()``" @@ -975,12 +1068,29 @@ msgstr "``span()``" #: ../../howto/regex.rst:425 msgid "Return a tuple containing the (start, end) positions of the match" msgstr "" -"Retorna uma tupla contendo as posições (inicial, final) da string combinada" +"Retorna uma tupla contendo as posições (inicial, final) da string " +"correspondente" #: ../../howto/regex.rst:429 msgid "Trying these methods will soon clarify their meaning::" msgstr "Experimentando estes métodos teremos seus significado esclarecidos::" +#: ../../howto/regex.rst:431 +msgid "" +">>> m.group()\n" +"'tempo'\n" +">>> m.start(), m.end()\n" +"(0, 5)\n" +">>> m.span()\n" +"(0, 5)" +msgstr "" +">>> m.group()\n" +"'tempo'\n" +">>> m.start(), m.end()\n" +"(0, 5)\n" +">>> m.span()\n" +"(0, 5)" + #: ../../howto/regex.rst:438 msgid "" ":meth:`~re.Match.group` returns the substring that was matched by the RE. :" @@ -992,6 +1102,34 @@ msgid "" "scans through the string, so the match may not start at zero in that " "case. ::" msgstr "" +":meth:`~re.Match.group` retorna a substring que correspondeu com a RE. :" +"meth:`~re.Match.start` e :meth:`~re.Match.end` retornam os índices inicial e " +"o final da substring correspondente. :meth:`~re.Match.span` retorna tanto os " +"índices inicial e final em uma única tupla. Como o método :meth:`~re.Pattern." +"match` somente verifica se a RE corresponde ao início de uma string, :meth:`!" +"start` será sempre zero. No entanto, o método :meth:`~re.Pattern.search` dos " +"objetos padrão, varre toda a string, de modo que a substring correspondente " +"pode não iniciar em zero nesse caso." + +#: ../../howto/regex.rst:446 +msgid "" +">>> print(p.match('::: message'))\n" +"None\n" +">>> m = p.search('::: message'); print(m)\n" +"\n" +">>> m.group()\n" +"'message'\n" +">>> m.span()\n" +"(4, 11)" +msgstr "" +">>> print(p.match('::: message'))\n" +"None\n" +">>> m = p.search('::: message'); print(m)\n" +"\n" +">>> m.group()\n" +"'message'\n" +">>> m.span()\n" +"(4, 11)" #: ../../howto/regex.rst:455 msgid "" @@ -999,15 +1137,44 @@ msgid "" "` in a variable, and then check if it was ``None``. This " "usually looks like::" msgstr "" -"Nos programas reais, o estilo mais comum é armazenar o :ref:`objeto Match " -"` em uma variável e, em seguida, verificar se ela é ``None``. " -"Isso geralmente se parece com::" +"Nos programas reais, o estilo mais comum é armazenar o :ref:`objeto " +"correspondência ` em uma variável e, em seguida, verificar se " +"ela é ``None``. Isso geralmente se parece com::" + +#: ../../howto/regex.rst:459 +msgid "" +"p = re.compile( ... )\n" +"m = p.match( 'string goes here' )\n" +"if m:\n" +" print('Match found: ', m.group())\n" +"else:\n" +" print('No match')" +msgstr "" +"p = re.compile( ... )\n" +"m = p.match( 'string vai aqui' )\n" +"if m:\n" +" print('Correspondência encontrada: ', m.group())\n" +"else:\n" +" print('Sem correspondência')" #: ../../howto/regex.rst:466 msgid "" "Two pattern methods return all of the matches for a pattern. :meth:`~re." "Pattern.findall` returns a list of matching strings::" msgstr "" +"Dois métodos padrão retornam todas as correspondências de um padrão. :meth:" +"`~re.Pattern.findall` retorna uma lista de strings correspondentes:" + +#: ../../howto/regex.rst:469 +msgid "" +">>> p = re.compile(r'\\d+')\n" +">>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')\n" +"['12', '11', '10']" +msgstr "" +">>> p = re.compile(r'\\d+')\n" +">>> p.findall('12 percussionistas tocando tambores, 11 flautistas tocando " +"flautas, 10 lordes saltando')\n" +"['12', '11', '10']" #: ../../howto/regex.rst:473 msgid "" @@ -1017,6 +1184,12 @@ msgid "" "in a :exc:`DeprecationWarning` and will eventually become a :exc:" "`SyntaxError`. See :ref:`the-backslash-plague`." msgstr "" +"O prefixo ``r``, tornando literal uma literal de string bruta, é necessário " +"neste exemplo porque sequências de escape em uma literal de string " +"\"cozida\" normal que não são reconhecidas pelo Python, ao contrário de " +"expressões regulares, agora resultam em uma :exc:`DeprecationWarning` e " +"eventualmente se tornarão uma :exc:`SyntaxError`. Veja :ref:`the-backslash-" +"plague`." #: ../../howto/regex.rst:479 msgid "" @@ -1025,10 +1198,37 @@ msgid "" "sequence of :ref:`match object ` instances as an :term:" "`iterator`::" msgstr "" +":meth:`~re.Pattern.findall` tem que criar a lista inteira antes de poder " +"devolvê-la como resultado. O método :meth:`~re.Pattern.finditer` retorna uma " +"sequência de instâncias :ref:`objeto correspondência ` como " +"um :term:`iterator`::" + +#: ../../howto/regex.rst:483 +msgid "" +">>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')\n" +">>> iterator\n" +"\n" +">>> for match in iterator:\n" +"... print(match.span())\n" +"...\n" +"(0, 2)\n" +"(22, 24)\n" +"(29, 31)" +msgstr "" +">>> iterator = p.finditer('12 percussionistas tocando tambores, 11 ... " +"10 ...')\n" +">>> iterator\n" +"\n" +">>> for match in iterator:\n" +"... print(match.span())\n" +"...\n" +"(0, 2)\n" +"(22, 24)\n" +"(29, 31)" #: ../../howto/regex.rst:495 msgid "Module-Level Functions" -msgstr "Funções de Nível de Módulo" +msgstr "Funções de nível de módulo" #: ../../howto/regex.rst:497 msgid "" @@ -1039,6 +1239,25 @@ msgid "" "with the RE string added as the first argument, and still return either " "``None`` or a :ref:`match object ` instance. ::" msgstr "" +"Você não tem que criar um objeto padrão e chamar seus métodos; o módulo :mod:" +"`re` também fornece funções de nível superior chamadas :func:`~re.match`, :" +"func:`~re.search`, :func:`~re.findall`, :func:`~re.sub`, e assim por diante. " +"Estas funções recebem os mesmos argumentos que o método correspondente do " +"objeto padrão, com a string RE adicionada como o primeiro argumento, e ainda " +"retornam ``None`` ou uma instância :ref:`objeto correspondência `. ::" + +#: ../../howto/regex.rst:504 +msgid "" +">>> print(re.match(r'From\\s+', 'Fromage amk'))\n" +"None\n" +">>> re.match(r'From\\s+', 'From amk Thu May 14 19:12:10 1998')\n" +"" +msgstr "" +">>> print(re.match(r'From\\s+', 'Fromage amk'))\n" +"None\n" +">>> re.match(r'From\\s+', 'From amk Thu May 14 19:12:10 1998')\n" +"" #: ../../howto/regex.rst:509 msgid "" @@ -1047,6 +1266,10 @@ msgid "" "cache, so future calls using the same RE won't need to parse the pattern " "again and again." msgstr "" +"Sob o capô, estas funções simplesmente criam um objeto padrão para você e " +"chamam o método apropriado para ele. Elas também armazenam o objeto " +"compilado em um cache, para que futuras chamadas usando a mesma RE não " +"precisem analisar o padrão de novo e de novo." #: ../../howto/regex.rst:514 msgid "" @@ -1055,10 +1278,14 @@ msgid "" "pre-compiling it will save a few function calls. Outside of loops, there's " "not much difference thanks to the internal cache." msgstr "" +"Você deve usar essas funções de nível de módulo ou deve obter o padrão e " +"chamar seus métodos você mesmo? Se estiver acessando uma expressão regular " +"dentro de um laço de repetição, pré-compilá-la economizará algumas chamadas " +"de função. Fora dos laços, não há muita diferença graças ao cache interno." #: ../../howto/regex.rst:522 msgid "Compilation Flags" -msgstr "Sinalizadores de Compilação" +msgstr "Sinalizadores de compilação" #: ../../howto/regex.rst:526 msgid "" @@ -1106,6 +1333,8 @@ msgid "" "Makes several escapes like ``\\w``, ``\\b``, ``\\s`` and ``\\d`` match only " "on ASCII characters with the respective property." msgstr "" +"Faz com que vários escapes como ``\\w``, ``\\b``, ``\\s`` e ``\\d`` " +"correspondam apenas a caracteres ASCII com a respectiva propriedade." #: ../../howto/regex.rst:544 msgid ":const:`DOTALL`, :const:`S`" @@ -1113,7 +1342,7 @@ msgstr ":const:`DOTALL`, :const:`S`" #: ../../howto/regex.rst:544 msgid "Make ``.`` match any character, including newlines." -msgstr "" +msgstr "Faz o ``.`` corresponder a qualquer caractere, incluindo novas linhas." #: ../../howto/regex.rst:547 msgid ":const:`IGNORECASE`, :const:`I`" @@ -1121,7 +1350,7 @@ msgstr ":const:`IGNORECASE`, :const:`I`" #: ../../howto/regex.rst:547 msgid "Do case-insensitive matches." -msgstr "Faz combinações sem diferenciar maiúsculo de minúsculo" +msgstr "Faz combinações sem diferenciar maiúsculo de minúsculo." #: ../../howto/regex.rst:549 msgid ":const:`LOCALE`, :const:`L`" @@ -1141,7 +1370,7 @@ msgstr "Correspondência multilinha, afetando ``^`` e ``$``." #: ../../howto/regex.rst:554 msgid ":const:`VERBOSE`, :const:`X` (for 'extended')" -msgstr "" +msgstr ":const:`VERBOSE`, :const:`X` (de 'extended'; estendido em inglês)" #: ../../howto/regex.rst:554 msgid "" @@ -1165,12 +1394,30 @@ msgid "" "lowercasing doesn't take the current locale into account; it will if you " "also set the :const:`LOCALE` flag." msgstr "" +"Faz correspondência sem distinção entre maiúsculas e minúsculas; a classe de " +"caracteres e as strings literais corresponderão às letras ignorando " +"maiúsculas e minúsculas. Por exemplo, ``[A-Z]`` corresponderá às letras " +"minúsculas também. A correspondência Unicode completa também funciona, a " +"menos que o sinalizador :const:`ASCII` seja usado para desabilitar " +"correspondências não ASCII. Quando os padrões Unicode ``[a-z]`` ou ``[A-Z]`` " +"são usados em combinação com o sinalizador :const:`IGNORECASE`, eles " +"corresponderão às 52 letras ASCII e 4 letras não ASCII adicionais: " +"'İ' (U+0130, letra maiúscula latina I com ponto acima), 'ı' (U+0131, letra " +"minúscula latina i sem ponto), 'ſ' (U+017F, letra minúscula latina s longo) " +"e 'K' (U+212A, sinal Kelvin). ``Spam`` corresponderá a ``'Spam'``, " +"``'spam'``, ``'spAM'`` ou ``'ſpam'`` (o último é correspondido apenas no " +"modo Unicode). Essa capitalização em minúsculas não leva em conta a " +"localidade atual; levará se você também definir o sinalizador :const:" +"`LOCALE`." #: ../../howto/regex.rst:581 msgid "" "Make ``\\w``, ``\\W``, ``\\b``, ``\\B`` and case-insensitive matching " "dependent on the current locale instead of the Unicode database." msgstr "" +"Faz com que ``\\w``, ``\\W``, ``\\b``, ``\\B`` e a correspondência sem " +"diferenciação de maiúsculas e minúsculas dependam da localidade atual em vez " +"do banco de dados Unicode." #: ../../howto/regex.rst:584 msgid "" @@ -1190,6 +1437,23 @@ msgid "" "matching is already enabled by default in Python 3 for Unicode (str) " "patterns, and it is able to handle different locales/languages." msgstr "" +"Localidades são um recurso da biblioteca C destinado a ajudar na escrita de " +"programas que levam em conta as diferenças de idioma. Por exemplo, se você " +"estiver processando texto codificado em francês, você gostaria de ser capaz " +"de escrever ``\\w+`` para corresponder a palavras, mas ``\\w`` corresponde " +"apenas à classe de caracteres ``[A-Za-z]`` em padrões de bytes; ele não " +"corresponderá a bytes correspondentes a ``é`` ou ``ç``. Se seu sistema " +"estiver configurado corretamente e uma localidade francesa for selecionada, " +"certas funções C dirão ao programa que o byte correspondente a ``é`` também " +"deve ser considerado uma letra. Definir o sinalizador :const:`LOCALE` ao " +"compilar uma expressão regular fará com que o objeto compilado resultante " +"use essas funções C para ``\\w``; isso é mais lento, mas também permite que " +"``\\w+`` corresponda a palavras francesas como você esperaria. O uso deste " +"sinalizador é desencorajado no Python 3, pois o mecanismo de localidade é " +"muito pouco confiável, ele só manipula uma \"cultura\" por vez e só funciona " +"com localidades de 8 bits. A correspondência Unicode já está habilitada por " +"padrão no Python 3 para padrões Unicode (str), e é capaz de manipular " +"diferentes localidades/idiomas." #: ../../howto/regex.rst:606 msgid "" @@ -1223,8 +1487,8 @@ msgid "" "newline; without this flag, ``'.'`` will match anything *except* a newline." msgstr "" "Faz o caractere especial ``.`` corresponder com qualquer caractere que seja, " -"incluindo o nova linha; sem este sinalizador, ``.`` irá corresponder a " -"qualquer coisa, exceto o nova linha." +"incluindo uma nova linha; sem este sinalizador, ``.`` irá corresponder a " +"qualquer coisa, exceto uma nova linha." #: ../../howto/regex.rst:630 msgid "" @@ -1232,6 +1496,10 @@ msgid "" "only matching instead of full Unicode matching. This is only meaningful for " "Unicode patterns, and is ignored for byte patterns." msgstr "" +"Faz com que ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\s`` e ``\\S`` executem " +"a correspondência somente ASCII em vez da correspondência Unicode completa. " +"Isso é significativo apenas para padrões Unicode e é ignorado para padrões " +"de bytes." #: ../../howto/regex.rst:639 msgid "" @@ -1252,22 +1520,52 @@ msgstr "" "organizar e formatar a RE de maneira mais clara. Este sinalizador também " "permite que se coloque comentários dentro de uma RE que serão ignorados pelo " "mecanismo; os comentários são marcados por um \"#\" que não está nem em uma " -"classe de caracteres nem precedido por uma barra invertida não \"escapada\". " -"Por exemplo, aqui está uma RE que usa re.VERBOSE; veja, o quanto mais fácil " -"de ler é ?" +"classe de caracteres nem precedido por uma barra invertida não \"escapada\"." #: ../../howto/regex.rst:648 msgid "" "For example, here's a RE that uses :const:`re.VERBOSE`; see how much easier " "it is to read? ::" msgstr "" -"Por exemplo, aqui está uma RE que usa :const:`re.VERBOSE`; veja, o quanto " -"mais fácil de ler é? ::" +"Por exemplo, aqui está uma RE que usa :const:`re.VERBOSE`; consegue ver o " +"quanto mais fácil de ler é? ::" + +#: ../../howto/regex.rst:651 +msgid "" +"charref = re.compile(r\"\"\"\n" +" &[#] # Start of a numeric entity reference\n" +" (\n" +" 0[0-7]+ # Octal form\n" +" | [0-9]+ # Decimal form\n" +" | x[0-9a-fA-F]+ # Hexadecimal form\n" +" )\n" +" ; # Trailing semicolon\n" +"\"\"\", re.VERBOSE)" +msgstr "" +"charref = re.compile(r\"\"\"\n" +" &[#] # Início de uma referência à entidade numérica\n" +" (\n" +" 0[0-7]+ # Forma octal\n" +" | [0-9]+ # Forma decimal\n" +" | x[0-9a-fA-F]+ # Forma hexadecimal\n" +" )\n" +" ; # Ponto e vírgula ao final\n" +"\"\"\", re.VERBOSE)" #: ../../howto/regex.rst:661 msgid "Without the verbose setting, the RE would look like this::" msgstr "Sem o \"verbose\" definido, A RE iria se parecer como isto::" +#: ../../howto/regex.rst:663 +msgid "" +"charref = re.compile(\"&#(0[0-7]+\"\n" +" \"|[0-9]+\"\n" +" \"|x[0-9a-fA-F]+);\")" +msgstr "" +"charref = re.compile(\"&#(0[0-7]+\"\n" +" \"|[0-9]+\"\n" +" \"|x[0-9a-fA-F]+);\")" + #: ../../howto/regex.rst:667 msgid "" "In the above example, Python's automatic concatenation of string literals " @@ -1280,7 +1578,7 @@ msgstr "" #: ../../howto/regex.rst:673 msgid "More Pattern Power" -msgstr "Mais Poder dos Padrões" +msgstr "Mais poder dos padrões" #: ../../howto/regex.rst:675 msgid "" @@ -1294,7 +1592,7 @@ msgstr "" #: ../../howto/regex.rst:683 msgid "More Metacharacters" -msgstr "Mais Metacaracteres" +msgstr "Mais metacaracteres" #: ../../howto/regex.rst:685 msgid "" @@ -1315,9 +1613,9 @@ msgid "" "once at a given location, they can obviously be matched an infinite number " "of times." msgstr "" -"Alguns dos metacaracteres restantes a serem discutidos são como uma " -"afirmação de ``largura zero`` (zero-width assertions). Eles não fazem com " -"que o mecanismo avance pela string; ao contrário, eles não consomem nenhum " +"Alguns dos metacaracteres restantes a serem discutidos são como uma asserção " +"de ``largura zero`` (zero-width assertions). Eles não fazem com que o " +"mecanismo avance pela string; ao contrário, eles não consomem nenhum " "caractere, e simplesmente tem sucesso ou falha. Por exemplo, ``\\b`` é uma " "afirmação de que a posição atual está localizada nas bordas de uma palavra; " "a posição não é alterada de nenhuma maneira por ``\\b``. Isto significa que " @@ -1338,6 +1636,12 @@ msgid "" "``'Crow'`` or ``'Servo'``, not ``'Cro'``, a ``'w'`` or an ``'S'``, and " "``'ervo'``." msgstr "" +"Alternância, ou operador \"or\". Se *A* e *B* são expressões regulares, ``A|" +"B`` irá corresponder com qualquer string que corresponder com *A* ou *B*. ``|" +"`` tem uma prioridade muito baixa, a fim de fazê-lo funcionar razoavelmente " +"quando você está alternando entre strings de vários caracteres. ``Crow|" +"Servo`` irá corresponder tanto com ``'Crow'`` quanto com ``'Servo'``, e não " +"com ``'Cro'``, ``'w'`` ou ``'S'``, e ``'ervo'``." #: ../../howto/regex.rst:703 msgid "" @@ -1369,11 +1673,23 @@ msgid "" "a line, the RE to use is ``^From``. ::" msgstr "" "Por exemplo, para ter correspondência com a palavra ``From`` apenas no " -"início de uma linha, aRE a ser usada é ``^From``. ::" +"início de uma linha, a RE a ser usada é ``^From``. ::" + +#: ../../howto/regex.rst:714 +msgid "" +">>> print(re.search('^From', 'From Here to Eternity'))\n" +"\n" +">>> print(re.search('^From', 'Reciting From Memory'))\n" +"None" +msgstr "" +">>> print(re.search('^From', 'From Here to Eternity'))\n" +"\n" +">>> print(re.search('^From', 'Reciting From Memory'))\n" +"None" #: ../../howto/regex.rst:719 msgid "To match a literal ``'^'``, use ``\\^``." -msgstr "" +msgstr "Para corresponder a um ``'^'`` literal, use ``\\^``." #: ../../howto/regex.rst:721 msgid "``$``" @@ -1387,12 +1703,28 @@ msgstr "" "Corresponde ao fim de uma linha, que tanto é definido como o fim de uma " "string, ou qualquer local seguido por um caractere de nova linha. ::" +#: ../../howto/regex.rst:725 +msgid "" +">>> print(re.search('}$', '{block}'))\n" +"\n" +">>> print(re.search('}$', '{block} '))\n" +"None\n" +">>> print(re.search('}$', '{block}\\n'))\n" +"" +msgstr "" +">>> print(re.search('}$', '{block}'))\n" +"\n" +">>> print(re.search('}$', '{block} '))\n" +"None\n" +">>> print(re.search('}$', '{block}\\n'))\n" +"" + #: ../../howto/regex.rst:732 msgid "" "To match a literal ``'$'``, use ``\\$`` or enclose it inside a character " "class, as in ``[$]``." msgstr "" -"Para corresponder com um ``$`` literal, use ``\\$`` ou coloque-o dentro de " +"Para corresponder com um ``'$'`` literal, use ``\\$`` ou coloque-o dentro de " "uma classe de caracteres, como em ``[$]``." #: ../../howto/regex.rst:735 @@ -1432,10 +1764,10 @@ msgid "" "characters, so the end of a word is indicated by whitespace or a non-" "alphanumeric character." msgstr "" -"Borda de palavra. Esta é uma afirmação de ``largura zero`` que corresponde " -"apenas ao início ou ao final de uma palavra. Uma palavra é definida como uma " -"sequência de caracteres alfanuméricos, de modo que o fim de uma palavra é " -"indicado por espaços em branco ou um caractere não alfanumérico." +"Borda de palavra. Esta é uma asserção de largura zero que corresponde apenas " +"ao início ou ao fim de uma palavra. Uma palavra é definida como uma " +"sequência de caracteres alfanuméricos, então o fim de uma palavra é indicado " +"por espaço em branco ou um caractere não alfanumérico." #: ../../howto/regex.rst:750 msgid "" @@ -1445,6 +1777,24 @@ msgstr "" "O exemplo a seguir corresponde a ``class`` apenas quando é a palavra exata; " "ele não irá corresponder quando for contido dentro de uma outra palavra. ::" +#: ../../howto/regex.rst:753 +msgid "" +">>> p = re.compile(r'\\bclass\\b')\n" +">>> print(p.search('no class at all'))\n" +"\n" +">>> print(p.search('the declassified algorithm'))\n" +"None\n" +">>> print(p.search('one subclass is'))\n" +"None" +msgstr "" +">>> p = re.compile(r'\\bclass\\b')\n" +">>> print(p.search('no class at all'))\n" +"\n" +">>> print(p.search('the declassified algorithm'))\n" +"None\n" +">>> print(p.search('one subclass is'))\n" +"None" + #: ../../howto/regex.rst:761 msgid "" "There are two subtleties you should remember when using this special " @@ -1455,13 +1805,27 @@ msgid "" "won't match as you expect it to. The following example looks the same as our " "previous RE, but omits the ``'r'`` in front of the RE string. ::" msgstr "" -"Há duas sutilezas você deve lembrar ao usar essa sequência especial. Em " +"Há duas sutilezas que você deve lembrar ao usar essa sequência especial. Em " "primeiro lugar, esta é a pior colisão entre strings literais do Python e " "sequências de expressão regular. Nas strings literais do Python, ``\\b`` é o " "caractere backspace, o valor ASCII 8. Se você não estiver usando strings " -"cruas (raw), então Python irá converter o ``\\b`` em um backspace e sua RE " -"não irá funcionar da maneira que você espera. O exemplo a seguir parece " -"igual a nossa RE anterior, mas omite o ``r`` na frente da string RE. ::" +"brutas, então Python irá converter o ``\\b`` em um backspace e sua RE não " +"irá funcionar da maneira que você espera. O exemplo a seguir parece igual a " +"nossa RE anterior, mas omite o ``'r'`` na frente da string RE. ::" + +#: ../../howto/regex.rst:769 +msgid "" +">>> p = re.compile('\\bclass\\b')\n" +">>> print(p.search('no class at all'))\n" +"None\n" +">>> print(p.search('\\b' + 'class' + '\\b'))\n" +"" +msgstr "" +">>> p = re.compile('\\bclass\\b')\n" +">>> print(p.search('no class at all'))\n" +"None\n" +">>> print(p.search('\\b' + 'class' + '\\b'))\n" +"" #: ../../howto/regex.rst:775 msgid "" @@ -1470,7 +1834,7 @@ msgid "" "string literals." msgstr "" "Além disso, dentro de uma classe de caracteres, onde não há nenhum uso para " -"esta afirmação, ``\\b`` representa o caractere backspace, para " +"esta asserção, ``\\b`` representa o caractere backspace, para " "compatibilidade com strings literais do Python" #: ../../howto/regex.rst:779 @@ -1482,9 +1846,8 @@ msgid "" "Another zero-width assertion, this is the opposite of ``\\b``, only matching " "when the current position is not at a word boundary." msgstr "" -"Outra afirmação de ``largura zero``; isto é o oposto de ``\\b``, " -"correspondendo apenas quando a posição corrente não é de uma borda de " -"palavra." +"Outra asserção de largura zero; isto é o oposto de ``\\b``, correspondendo " +"apenas quando a posição corrente não é de uma borda de palavra." #: ../../howto/regex.rst:785 msgid "Grouping" @@ -1498,6 +1861,24 @@ msgid "" "of interest. For example, an RFC-822 header line is divided into a header " "name and a value, separated by a ``':'``, like this:" msgstr "" +"Frequentemente é necessário obter mais informações do que apenas se a RE " +"teve correspondência ou não. As expressões regulares são muitas vezes " +"utilizadas para dissecar strings escrevendo uma RE dividida em vários " +"subgrupos que correspondem a diferentes componentes de interesse. Por " +"exemplo, uma linha de cabeçalho RFC-822 é dividida em um nome de cabeçalho e " +"um valor, separados por um ``':'``, como essa:" + +#: ../../howto/regex.rst:793 +msgid "" +"From: author@example.com\n" +"User-Agent: Thunderbird 1.5.0.9 (X11/20061227)\n" +"MIME-Version: 1.0\n" +"To: editor@example.com" +msgstr "" +"From: author@example.com\n" +"User-Agent: Thunderbird 1.5.0.9 (X11/20061227)\n" +"MIME-Version: 1.0\n" +"To: editor@example.com" #: ../../howto/regex.rst:800 msgid "" @@ -1505,15 +1886,9 @@ msgid "" "header line, and has one group which matches the header name, and another " "group which matches the header's value." msgstr "" -"Isto pode ser gerenciado ao escrever uma expressão regular que corresponde " -"com uma linha inteira de cabeçalho, e tem um grupo que corresponde ao nome " -"do cabeçalho, e um outro grupo, que corresponde ao valor do cabeçalho. Os " -"grupos são marcados pelos metacaracteres ``(`` e ``)``. ``(`` e ``)`` têm " -"muito do mesmo significado que eles têm em expressões matemáticas; eles " -"agrupam as expressões contidas dentro deles, e você pode repetir o conteúdo " -"de um grupo com um qualificador de repetição, como ``*``, ``+``, ``?``, ou " -"``{m,n}``. Por exemplo, ``(ab)*`` irá corresponder a zero ou mais repetições " -"de ``ab``." +"Isto pode ser tratado escrevendo uma expressão regular que corresponde com " +"uma linha inteira de cabeçalho, e tem um grupo que corresponde ao nome do " +"cabeçalho, e um outro grupo, que corresponde ao valor do cabeçalho." #: ../../howto/regex.rst:804 msgid "" @@ -1524,6 +1899,22 @@ msgid "" "``, or ``{m,n}``. For example, ``(ab)*`` will match zero or more " "repetitions of ``ab``. ::" msgstr "" +"Os grupos são marcados pelos metacaracteres ``'('`` e ``')'``. ``'('`` e " +"``')'`` têm muito do mesmo significado que eles têm em expressões " +"matemáticas; eles agrupam as expressões contidas dentro deles, e você pode " +"repetir o conteúdo de um grupo com um qualificador de repetição, como ``*``, " +"``+``, ``?``, ou ``{m,n}``. Por exemplo, ``(ab)*`` irá corresponder a zero " +"ou mais repetições de ``ab``." + +#: ../../howto/regex.rst:811 +msgid "" +">>> p = re.compile('(ab)*')\n" +">>> print(p.match('ababababab').span())\n" +"(0, 10)" +msgstr "" +">>> p = re.compile('(ab)*')\n" +">>> print(p.match('ababababab').span())\n" +"(0, 10)" #: ../../howto/regex.rst:815 msgid "" @@ -1536,6 +1927,30 @@ msgid "" "we'll see how to express groups that don't capture the span of text that " "they match. ::" msgstr "" +"Grupos indicados com ``'('`` e ``')'`` também capturam o índice inicial e " +"final do texto que eles correspondem; isso pode ser obtido por meio da " +"passagem de um argumento para :meth:`~re.Match.group`, :meth:`~re.Match." +"start`, :meth:`~re.Match.end` e :meth:`~re.Match.span`. Os grupos são " +"numerados começando com 0. O grupo 0 está sempre presente; é toda a RE, de " +"forma que os métodos de :ref:`objeto de correspondência ` têm " +"todos o grupo 0 como seu argumento padrão. Mais tarde veremos como expressar " +"grupos que não capturam a extensão de texto com a qual eles correspondem. ::" + +#: ../../howto/regex.rst:824 +msgid "" +">>> p = re.compile('(a)b')\n" +">>> m = p.match('ab')\n" +">>> m.group()\n" +"'ab'\n" +">>> m.group(0)\n" +"'ab'" +msgstr "" +">>> p = re.compile('(a)b')\n" +">>> m = p.match('ab')\n" +">>> m.group()\n" +"'ab'\n" +">>> m.group(0)\n" +"'ab'" #: ../../howto/regex.rst:831 msgid "" @@ -1545,21 +1960,62 @@ msgid "" msgstr "" "Subgrupos são numerados a partir da esquerda para a direita, de forma " "crescente a partir de 1. Os grupos podem ser aninhados; para determinar o " -"número, basta contar os caracteres de abertura de parêntese - ``(``, indo da " +"número, basta contar os caracteres de abertura de parêntese ``(``, indo da " "esquerda para a direita. ::" +#: ../../howto/regex.rst:835 +msgid "" +">>> p = re.compile('(a(b)c)d')\n" +">>> m = p.match('abcd')\n" +">>> m.group(0)\n" +"'abcd'\n" +">>> m.group(1)\n" +"'abc'\n" +">>> m.group(2)\n" +"'b'" +msgstr "" +">>> p = re.compile('(a(b)c)d')\n" +">>> m = p.match('abcd')\n" +">>> m.group(0)\n" +"'abcd'\n" +">>> m.group(1)\n" +"'abc'\n" +">>> m.group(2)\n" +"'b'" + #: ../../howto/regex.rst:844 msgid "" ":meth:`~re.Match.group` can be passed multiple group numbers at a time, in " "which case it will return a tuple containing the corresponding values for " "those groups. ::" msgstr "" +":meth:`~re.Match.group` pode receber vários números de grupos de uma vez, e " +"nesse caso ele irá retornar uma tupla contendo os valores correspondentes " +"desses grupos. ::" + +#: ../../howto/regex.rst:847 +msgid "" +">>> m.group(2,1,2)\n" +"('b', 'abc', 'b')" +msgstr "" +">>> m.group(2,1,2)\n" +"('b', 'abc', 'b')" #: ../../howto/regex.rst:850 msgid "" "The :meth:`~re.Match.groups` method returns a tuple containing the strings " "for all the subgroups, from 1 up to however many there are. ::" msgstr "" +"O método :meth:`~re.Match.groups` retorna uma tupla contendo as strings de " +"todos os subgrupos, de 1 até o último. ::" + +#: ../../howto/regex.rst:853 +msgid "" +">>> m.groups()\n" +"('abc', 'b')" +msgstr "" +">>> m.groups()\n" +"('abc', 'b')" #: ../../howto/regex.rst:856 msgid "" @@ -1574,17 +2030,27 @@ msgstr "" "Referências anteriores em um padrão permitem que você especifique que o " "conteúdo de um grupo capturado anteriormente também deve ser encontrado na " "posição atual na sequência. Por exemplo, ``\\1`` terá sucesso se o conteúdo " -"exato do grupo 1 puder ser encontrado na posição atual, e falhar caso " -"contrário. Lembre-se que as strings literais do Python também usam a barra " -"invertida seguida por números para permitir a inclusão de caracteres " -"arbitrários em uma string, por isso certifique-se de usar strings cruas " -"(raw) ao incorporar referências anteriores em uma RE." +"exato do grupo 1 puder ser encontrado na posição atual, e falha caso " +"contrário. Lembre-se que as strings literais do Python também usam a " +"contrabarra seguida por números para permitir a inclusão de caracteres " +"arbitrários em uma string, por isso certifique-se de usar strings brutas ao " +"incorporar referências anteriores em uma RE." #: ../../howto/regex.rst:864 msgid "For example, the following RE detects doubled words in a string. ::" msgstr "" "Por exemplo, a seguinte RE detecta palavras duplicadas em uma string. ::" +#: ../../howto/regex.rst:866 +msgid "" +">>> p = re.compile(r'\\b(\\w+)\\s+\\1\\b')\n" +">>> p.search('Paris in the the spring').group()\n" +"'the the'" +msgstr "" +">>> p = re.compile(r'\\b(\\w+)\\s+\\1\\b')\n" +">>> p.search('Paris in the the spring').group()\n" +"'the the'" + #: ../../howto/regex.rst:870 msgid "" "Backreferences like this aren't often useful for just searching through a " @@ -1593,13 +2059,13 @@ msgid "" "substitutions." msgstr "" "Referências anteriores como esta não são, geralmente, muito úteis apenas " -"para fazer pesquisa percorrendo uma string — existem alguns formatos de " -"texto que repetem dados dessa forma — mas em breve você irá descobrir que " -"elas são muito úteis para realizar substituições de strings." +"para fazer pesquisa em uma string --- existem alguns formatos de texto que " +"repetem dados dessa forma --- mas em breve você irá descobrir que elas são " +"muito úteis para realizar substituições de strings." #: ../../howto/regex.rst:876 msgid "Non-capturing and Named Groups" -msgstr "Não captura e Grupos Nomeados" +msgstr "Não captura e grupos nomeados" #: ../../howto/regex.rst:878 msgid "" @@ -1613,8 +2079,7 @@ msgstr "" "interesse, quanto para agrupar e estruturar a própria RE. Em REs complexas, " "torna-se difícil manter o controle dos números dos grupos. Existem dois " "recursos que ajudam a lidar com esse problema. Ambos usam uma sintaxe comum " -"para extensões de expressão regular, então vamos olhar para isso em primeiro " -"lugar." +"para extensões de expressão regular, então vamos olhar primeiro para isso." #: ../../howto/regex.rst:884 msgid "" @@ -1626,6 +2091,14 @@ msgid "" "expressions would be assuming that ``&`` was a regular character and " "wouldn't have escaped it by writing ``\\&`` or ``[&]``." msgstr "" +"O Perl 5 é bem conhecido por suas poderosas adições às expressões regulares " +"padrão. Para esses novos recursos, os desenvolvedores do Perl não podiam " +"escolher novos metacaracteres de um único caractere ou novas sequências " +"especiais começando com ``\\`` sem tornar as expressões regulares do Perl " +"confusamente diferentes das REs padrão. Se eles escolhessem ``&`` como um " +"novo metacaractere, por exemplo, as expressões antigas estariam presumindo " +"que ``&`` era um caractere regular e não teriam escapado dele escrevendo " +"``\\&`` ou ``[&]``." #: ../../howto/regex.rst:891 msgid "" @@ -1643,7 +2116,7 @@ msgstr "" "não introduz quaisquer problemas de compatibilidade. Os caracteres " "imediatamente após um ``?`` indicam que a extensão está sendo usada, então " "``(?=foo)`` é uma coisa (uma asserção ``lookahead`` positiva) e ``(?:foo)`` " -"é outra coisa (um grupo de não captura contendo a subexpressão ``foo``)." +"é outra coisa (um grupo de não-captura contendo a subexpressão ``foo``)." #: ../../howto/regex.rst:899 msgid "" @@ -1651,12 +2124,18 @@ msgid "" "Perl's extension syntax. If the first character after the question mark is " "a ``P``, you know that it's an extension that's specific to Python." msgstr "" +"Python oferece suporte a diversas extensões do Perl e adiciona uma sintaxe " +"de extensão à sintaxe de extensão do Perl. Se o primeiro caractere após o " +"ponto de interrogação for um ``P``, você sabe que se trata de uma extensão " +"específica do Python." #: ../../howto/regex.rst:904 msgid "" "Now that we've looked at the general extension syntax, we can return to the " "features that simplify working with groups in complex REs." msgstr "" +"Agora que vimos a sintaxe geral da extensão, podemos retornar aos recursos " +"que simplificam o trabalho com grupos em REs complexas." #: ../../howto/regex.rst:907 msgid "" @@ -1665,6 +2144,27 @@ msgid "" "can make this fact explicit by using a non-capturing group: ``(?:...)``, " "where you can replace the ``...`` with any other regular expression. ::" msgstr "" +"Às vezes você vai querer usar um grupo para representar uma parte de uma " +"expressão regular, mas não está interessado em recuperar o conteúdo do " +"grupo. Você pode tornar isso explícito usando um grupo de não-captura: " +"``(?:...)``, onde você pode substituir o ``...`` por qualquer outra " +"expressão regular. ::" + +#: ../../howto/regex.rst:912 +msgid "" +">>> m = re.match(\"([abc])+\", \"abc\")\n" +">>> m.groups()\n" +"('c',)\n" +">>> m = re.match(\"(?:[abc])+\", \"abc\")\n" +">>> m.groups()\n" +"()" +msgstr "" +">>> m = re.match(\"([abc])+\", \"abc\")\n" +">>> m.groups()\n" +"('c',)\n" +">>> m = re.match(\"(?:[abc])+\", \"abc\")\n" +">>> m.groups()\n" +"()" #: ../../howto/regex.rst:919 msgid "" @@ -1679,14 +2179,15 @@ msgid "" "groups; neither form is any faster than the other." msgstr "" "Exceto pelo fato de que não é possível recuperar o conteúdo sobre o qual o " -"grupo corresponde, um grupo de não captura se comporta exatamente da mesma " +"grupo corresponde, um grupo de não-captura se comporta exatamente da mesma " "forma que um grupo de captura; você pode colocar qualquer coisa dentro dele, " -"repeti-lo com um metacaractere de repetição, como o '*', e aninhá-lo dentro " -"de outros grupos (de captura ou não captura). ``(?:...)`` é particularmente " -"útil para modificar um padrão existente, já que você pode adicionar novos " -"grupos sem alterar a forma como todos os outros grupos estão numerados. Deve " -"ser mencionado que não há diferença de desempenho na busca entre grupos de " -"captura e grupos de não captura; uma forma não é mais rápida que outra." +"repeti-lo com um metacaractere de repetição, como o ``*``, e aninhá-lo " +"dentro de outros grupos (de captura ou não-captura). ``(?:...)`` é " +"particularmente útil para modificar um padrão existente, já que você pode " +"adicionar novos grupos sem alterar a forma como todos os outros grupos estão " +"numerados. Deve ser mencionado que não há diferença de desempenho na busca " +"entre grupos de captura e grupos de não-captura; uma forma não é mais rápida " +"que outra." #: ../../howto/regex.rst:928 msgid "" @@ -1707,12 +2208,48 @@ msgid "" "still given numbers, so you can retrieve information about a group in two " "ways::" msgstr "" +"A sintaxe de um grupo nomeado é uma das extensões específicas do Python: ``(?" +"P...)``. *name* é, obviamente, o nome do grupo. Os grupos nomeados se " +"comportam exatamente como os grupos de captura, e, adicionalmente, associam " +"um nome a um grupo. Todos os métodos de :ref:`objeto correspondência ` que lidam com grupos de captura aceitam tanto inteiros que se " +"referem ao grupo por número ou strings que contêm o nome do grupo desejado. " +"Os grupos nomeados ainda recebem números, então você pode recuperar " +"informações sobre um grupo de duas maneiras::" + +#: ../../howto/regex.rst:939 +msgid "" +">>> p = re.compile(r'(?P\\b\\w+\\b)')\n" +">>> m = p.search( '(((( Lots of punctuation )))' )\n" +">>> m.group('word')\n" +"'Lots'\n" +">>> m.group(1)\n" +"'Lots'" +msgstr "" +">>> p = re.compile(r'(?P\\b\\w+\\b)')\n" +">>> m = p.search( '(((( Lots of punctuation )))' )\n" +">>> m.group('word')\n" +"'Lots'\n" +">>> m.group(1)\n" +"'Lots'" #: ../../howto/regex.rst:946 msgid "" "Additionally, you can retrieve named groups as a dictionary with :meth:`~re." "Match.groupdict`::" msgstr "" +"Além disso, você pode recuperar grupos nomeados como um dicionário com :meth:" +"`~re.Match.groupdict`::" + +#: ../../howto/regex.rst:949 +msgid "" +">>> m = re.match(r'(?P\\w+) (?P\\w+)', 'Jane Doe')\n" +">>> m.groupdict()\n" +"{'first': 'Jane', 'last': 'Doe'}" +msgstr "" +">>> m = re.match(r'(?P\\w+) (?P\\w+)', 'Jane Doe')\n" +">>> m.groupdict()\n" +"{'first': 'Jane', 'last': 'Doe'}" #: ../../howto/regex.rst:953 msgid "" @@ -1720,6 +2257,25 @@ msgid "" "instead of having to remember numbers. Here's an example RE from the :mod:" "`imaplib` module::" msgstr "" +"Os grupos nomeados são úteis porque eles permitem que você use nomes de " +"fácil lembrança, em vez de ter que lembrar de números. Aqui está um exemplo " +"de RE usando o módulo :mod:`imaplib`::" + +#: ../../howto/regex.rst:957 +msgid "" +"InternalDate = re.compile(r'INTERNALDATE \"'\n" +" r'(?P[ 123][0-9])-(?P[A-Z][a-z][a-z])-'\n" +" r'(?P[0-9][0-9][0-9][0-9])'\n" +" r' (?P[0-9][0-9]):(?P[0-9][0-9]):(?P[0-9][0-9])'\n" +" r' (?P[-+])(?P[0-9][0-9])(?P[0-9][0-9])'\n" +" r'\"')" +msgstr "" +"InternalDate = re.compile(r'INTERNALDATE \"'\n" +" r'(?P[ 123][0-9])-(?P[A-Z][a-z][a-z])-'\n" +" r'(?P[0-9][0-9][0-9][0-9])'\n" +" r' (?P[0-9][0-9]):(?P[0-9][0-9]):(?P[0-9][0-9])'\n" +" r' (?P[-+])(?P[0-9][0-9])(?P[0-9][0-9])'\n" +" r'\"')" #: ../../howto/regex.rst:964 msgid "" @@ -1739,10 +2295,27 @@ msgid "" "words, ``\\b(\\w+)\\s+\\1\\b`` can also be written as ``\\b(?" "P\\w+)\\s+(?P=word)\\b``::" msgstr "" +"A sintaxe para referências anteriores em uma expressão, tal como " +"``(...)\\1``, faz referência ao número do grupo. Existe, naturalmente, uma " +"variante que usa o nome do grupo em vez do número. Isto é outra extensão " +"Python: ``(?P=name)`` indica que o conteúdo do grupo chamado *name* deve, " +"novamente, ser correspondido no ponto atual. A expressão regular para " +"encontrar palavras duplicadas, ``(\\b\\w+)\\s+\\1``, também pode ser escrita " +"como ``(?P\\b\\w+)\\s+(?P=word)``::" + +#: ../../howto/regex.rst:974 +msgid "" +">>> p = re.compile(r'\\b(?P\\w+)\\s+(?P=word)\\b')\n" +">>> p.search('Paris in the the spring').group()\n" +"'the the'" +msgstr "" +">>> p = re.compile(r'\\b(?P\\w+)\\s+(?P=word)\\b')\n" +">>> p.search('Paris in the the spring').group()\n" +"'the the'" #: ../../howto/regex.rst:980 msgid "Lookahead Assertions" -msgstr "Asserções Lookahead" +msgstr "Asserções lookahead" #: ../../howto/regex.rst:982 msgid "" @@ -1750,7 +2323,7 @@ msgid "" "assertions are available in both positive and negative form, and look like " "this:" msgstr "" -"Outra afirmação de \"largura zero\" é a asserção lookahead. Asserções " +"Outra asserção de \"largura zero\" é a asserção lookahead. Asserções " "lookahead estão disponíveis tanto na forma positiva quanto na negativa, e se " "parece com isto:" @@ -1766,12 +2339,12 @@ msgid "" "tried, the matching engine doesn't advance at all; the rest of the pattern " "is tried right where the assertion started." msgstr "" -"Asserção lookahead positiva. Retorna sucesso se a expressão regular " +"Asserção lookahead positiva. É bem-sucedida se a expressão regular " "informada, aqui representada por ``...``, corresponde com o conteúdo da " -"localização atual, e retorna falha caso contrário. Mas, uma vez que a " -"expressão informada tenha sido testada, o mecanismo de correspondência não " -"faz qualquer avanço; o resto do padrão é tentado no mesmo local de onde a " -"afirmação foi iniciada." +"localização atual, e falha caso contrário. Mas, uma vez que a expressão " +"informada tenha sido testada, o mecanismo de correspondência não faz " +"qualquer avanço; o resto do padrão é tentado no mesmo local de onde a " +"asserção foi iniciada." #: ../../howto/regex.rst:992 msgid "``(?!...)``" @@ -1794,11 +2367,11 @@ msgid "" "name and an extension, separated by a ``.``. For example, in ``news.rc``, " "``news`` is the base name, and ``rc`` is the filename's extension." msgstr "" -"Para tornar isto concreto, vamos olhar para um caso em que um lookahead é " +"Para tornar isto concreto, vamos olhar para um caso em que uma lookahead é " "útil. Considere um padrão simples para corresponder com um nome de arquivo e " -"divida-o em pedaços, um nome base e uma extensão, separados por um ``.``. " -"Por exemplo, em ``news.rc,news`` é o nome base, e ``rc`` é a extensão do " -"nome de arquivo." +"dividi-lo em pedaços, um nome base e uma extensão, separados por um ``.``. " +"Por exemplo, em ``news.rc``, ``news`` é o nome base, e ``rc`` é a extensão " +"do nome de arquivo." #: ../../howto/regex.rst:1002 msgid "The pattern to match this is quite simple:" @@ -1817,6 +2390,12 @@ msgid "" "expression matches ``foo.bar`` and ``autoexec.bat`` and ``sendmail.cf`` and " "``printers.conf``." msgstr "" +"Observe que o ``.`` precisa ser tratado de forma especial, pois é um " +"metacaractere e, portanto, está dentro de uma classe de caracteres para " +"corresponder apenas a esse caractere específico. Observe também o ``$`` ao " +"final; ele é adicionado para garantir que todo o restante da string seja " +"incluído na extensão. Esta expressão regular corresponde a ``foo.bar``, " +"``autoexec.bat``, ``sendmail.cf`` e ``printers.conf``." #: ../../howto/regex.rst:1013 msgid "" @@ -1833,9 +2412,9 @@ msgid "" "requiring that the first character of the extension is not a ``b``. This is " "wrong, because the pattern also doesn't match ``foo.bar``." msgstr "" -"``.*[.][^b].*$`` A primeira tentativa acima tenta excluir bat, exigindo que " -"o primeiro caractere da extensão não é um b. Isso é errado, porque o padrão " -"também não corresponde a ``foo.bar``." +"``.*[.][^b].*$`` A primeira tentativa acima tenta excluir ``bat``, exigindo " +"que o primeiro caractere da extensão não seja um ``b``. Isso é errado, " +"porque o padrão também não corresponde a ``foo.bar``." #: ../../howto/regex.rst:1020 msgid "``.*[.]([^b]..|.[^a].|..[^t])$``" @@ -1880,14 +2459,14 @@ msgid "" "``bat`` and ``exe`` as extensions, the pattern would get even more " "complicated and confusing." msgstr "" -"O padrão está ficando realmente muito complicado agora, o que faz com que " +"Agora, o padrão está ficando realmente muito complicado, o que faz com que " "seja difícil de ler e compreender. Pior ainda, se o problema mudar e você " "quiser excluir tanto ``bat`` quanto ``exe`` como extensões, o padrão iria " "ficar ainda mais complicado e confuso." #: ../../howto/regex.rst:1041 msgid "A negative lookahead cuts through all this confusion:" -msgstr "Um lookahead negativo elimina toda esta confusão:" +msgstr "Uma lookahead negativo elimina toda esta confusão:" #: ../../howto/regex.rst:1043 msgid "" @@ -1898,11 +2477,11 @@ msgid "" "only starts with ``bat``, will be allowed. The ``[^.]*`` makes sure that " "the pattern works when there are multiple dots in the filename." msgstr "" -"``.*[.](?!bat$).*$`` O lookahead negativo significa: se a expressão ``bat`` " -"não corresponder até este momento, tente o resto do padrão; se ``bat$`` tem " -"correspondência, todo o padrão irá falhar. O final ``$`` é necessário para " -"garantir que algo como ``sample.batch``, onde a extensão só começa com o " -"``bat``, será permitido." +"``.*[.](?!bat$)[^.]*$`` A lookahead negativa significa: se a expressão " +"``bat`` não corresponder até este momento, tente o resto do padrão; se " +"``bat$`` tem correspondência, todo o padrão irá falhar. O final ``$`` é " +"necessário para garantir que algo como ``sample.batch``, onde a extensão só " +"começa com o ``bat``, será permitido." #: ../../howto/regex.rst:1050 msgid "" @@ -1911,7 +2490,7 @@ msgid "" "that end in either ``bat`` or ``exe``:" msgstr "" "Excluir uma outra extensão de nome de arquivo agora é fácil; basta fazer a " -"adição de uma alternativa dentro da afirmação. O padrão a seguir exclui os " +"adição de uma alternativa dentro da asserção. O padrão a seguir exclui os " "nomes de arquivos que terminam com ``bat`` ou ``exe``:" #: ../../howto/regex.rst:1054 @@ -1920,7 +2499,7 @@ msgstr "``.*[.](?!bat$|exe$)[^.]*$``" #: ../../howto/regex.rst:1058 msgid "Modifying Strings" -msgstr "Modificando Strings" +msgstr "Modificando strings" #: ../../howto/regex.rst:1060 msgid "" @@ -1963,10 +2542,12 @@ msgid "" "Does the same thing as :meth:`!sub`, but returns the new string and the " "number of replacements" msgstr "" +"Faz a mesma coisa que :meth:`!sub`, mas retorna a nova string e o número de " +"substituições" #: ../../howto/regex.rst:1080 msgid "Splitting Strings" -msgstr "Dividindo as Strings" +msgstr "Dividindo as strings" #: ../../howto/regex.rst:1082 msgid "" @@ -1977,6 +2558,13 @@ msgid "" "splitting by whitespace or by a fixed string. As you'd expect, there's a " "module-level :func:`re.split` function, too." msgstr "" +"O método :meth:`~re.Pattern.split` de um padrão divide uma string em pedaços " +"onde quer que a RE corresponda, retornando uma lista formada por esses " +"pedaços. É semelhante ao método :meth:`~str.split` de strings, mas oferece " +"muito mais generalidade nos delimitadores, e assim, você pode fazer disso " +"para fazer a divisão; :meth:`!split` só implementa a divisão de espaço em " +"branco ou por uma string fixa. Como você deve deduzir, existe também uma " +"função a nível de módulo :func:`re.split`." #: ../../howto/regex.rst:1093 msgid "" @@ -2004,6 +2592,15 @@ msgstr "" "como o elemento final da lista. No exemplo a seguir, o delimitador é " "qualquer sequência de caracteres não alfanuméricos. ::" +#: ../../howto/regex.rst:1104 +msgid "" +">>> p = re.compile(r'\\W+')\n" +">>> p.split('This is a test, short and sweet, of split().')\n" +"['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']\n" +">>> p.split('This is a test, short and sweet, of split().', 3)\n" +"['This', 'is', 'a', 'test, short and sweet, of split().']" +msgstr "" + #: ../../howto/regex.rst:1110 msgid "" "Sometimes you're not only interested in what the text between delimiters is, " @@ -2017,6 +2614,16 @@ msgstr "" "valores são também retornados como parte da lista. Compare as seguintes " "chamadas::" +#: ../../howto/regex.rst:1115 +msgid "" +">>> p = re.compile(r'\\W+')\n" +">>> p2 = re.compile(r'(\\W+)')\n" +">>> p.split('This... is a test.')\n" +"['This', 'is', 'a', 'test', '']\n" +">>> p2.split('This... is a test.')\n" +"['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']" +msgstr "" + #: ../../howto/regex.rst:1122 msgid "" "The module-level function :func:`re.split` adds the RE to be used as the " @@ -2025,6 +2632,16 @@ msgstr "" "A função de nível de módulo :func:`re.split` adiciona a RE a ser utilizada " "como o primeiro argumento, mas é, em determinadas circunstâncias, a mesma. ::" +#: ../../howto/regex.rst:1125 +msgid "" +">>> re.split(r'[\\W]+', 'Words, words, words.')\n" +"['Words', 'words', 'words', '']\n" +">>> re.split(r'([\\W]+)', 'Words, words, words.')\n" +"['Words', ', ', 'words', ', ', 'words', '.', '']\n" +">>> re.split(r'[\\W]+', 'Words, words, words.', 1)\n" +"['Words', 'words, words.']" +msgstr "" + #: ../../howto/regex.rst:1134 msgid "Search and Replace" msgstr "Busca e Substituição" @@ -2036,6 +2653,10 @@ msgid "" "replacement value, which can be either a string or a function, and the " "string to be processed." msgstr "" +"Outra tarefa comum é encontrar todas as combinações para um padrão e " +"substituí-las por uma string diferente. O método :meth:`~re.Pattern.sub` " +"recebe um valor de substituição, que pode ser uma string ou uma função, e a " +"string a ser processada." #: ../../howto/regex.rst:1143 msgid "" @@ -2062,6 +2683,17 @@ msgid "" "Here's a simple example of using the :meth:`~re.Pattern.sub` method. It " "replaces colour names with the word ``colour``::" msgstr "" +"Aqui está um exemplo simples do uso do método :meth:`~re.Pattern.sub`. Ele " +"substitui nomes de cores pela palavra ``colour``::" + +#: ../../howto/regex.rst:1154 +msgid "" +">>> p = re.compile('(blue|white|red)')\n" +">>> p.sub('colour', 'blue socks and red shoes')\n" +"'colour socks and colour shoes'\n" +">>> p.sub('colour', 'blue socks and red shoes', count=1)\n" +"'colour socks and red shoes'" +msgstr "" #: ../../howto/regex.rst:1160 msgid "" @@ -2069,12 +2701,33 @@ msgid "" "tuple containing the new string value and the number of replacements that " "were performed::" msgstr "" +"O método :meth:`~re.Pattern.subn` faz o mesmo trabalho, mas retorna uma " +"tupla com duas informações; contém uma string com novo valor e o número de " +"substituições que foram realizadas:" + +#: ../../howto/regex.rst:1163 +msgid "" +">>> p = re.compile('(blue|white|red)')\n" +">>> p.subn('colour', 'blue socks and red shoes')\n" +"('colour socks and colour shoes', 2)\n" +">>> p.subn('colour', 'no colours at all')\n" +"('no colours at all', 0)" +msgstr "" #: ../../howto/regex.rst:1169 msgid "" "Empty matches are replaced only when they're not adjacent to a previous " "empty match. ::" msgstr "" +"Correspondências vazias somente são substituídas quando não estão adjacente " +"(próxima) a uma correspondência vazia anterior." + +#: ../../howto/regex.rst:1172 +msgid "" +">>> p = re.compile('x*')\n" +">>> p.sub('-', 'abxd')\n" +"'-a-b--d-'" +msgstr "" #: ../../howto/regex.rst:1176 msgid "" @@ -2086,6 +2739,13 @@ msgid "" "incorporate portions of the original text in the resulting replacement " "string." msgstr "" +"Se a substituição (replacement) é uma string, qualquer barra invertida é " +"interpretada e processada. Isto é, ``\\n`` é convertido a um único caractere " +"de nova linha, ``\\r`` é convertido em um retorno do carro, e assim por " +"diante. Casos desconhecidos, como ``\\&`` são ignorados. Referências " +"anteriores (retrovisor - Aurelio), como ``\\6``, são substituídas com a " +"substring correspondida pelo grupo correspondente na RE. Isso permite que " +"você incorpore partes do texto original na string de substituição resultante." #: ../../howto/regex.rst:1183 msgid "" @@ -2095,6 +2755,13 @@ msgstr "" "Este exemplo corresponde com a palavra ``section``, seguida por uma string " "colocada entre ``{, }`` e altera ``section`` para ``subsection``::" +#: ../../howto/regex.rst:1186 +msgid "" +">>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)\n" +">>> p.sub(r'subsection{\\1}','section{First} section{second}')\n" +"'subsection{First} subsection{second}'" +msgstr "" + #: ../../howto/regex.rst:1190 msgid "" "There's also a syntax for referring to named groups as defined by the ``(?" @@ -2116,6 +2783,17 @@ msgstr "" "substituições a seguir são todas equivalentes, mas usam todas as três " "variações da string de substituição. ::" +#: ../../howto/regex.rst:1199 +msgid "" +">>> p = re.compile('section{ (?P [^}]* ) }', re.VERBOSE)\n" +">>> p.sub(r'subsection{\\1}','section{First}')\n" +"'subsection{First}'\n" +">>> p.sub(r'subsection{\\g<1>}','section{First}')\n" +"'subsection{First}'\n" +">>> p.sub(r'subsection{\\g}','section{First}')\n" +"'subsection{First}'" +msgstr "" + #: ../../howto/regex.rst:1207 msgid "" "*replacement* can also be a function, which gives you even more control. If " @@ -2139,6 +2817,18 @@ msgstr "" "No exemplo a seguir, a função de substituição traduz decimais em " "hexadecimal::" +#: ../../howto/regex.rst:1216 +msgid "" +">>> def hexrepl(match):\n" +"... \"Return the hex string for a decimal number\"\n" +"... value = int(match.group())\n" +"... return hex(value)\n" +"...\n" +">>> p = re.compile(r'\\d+')\n" +">>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')\n" +"'Call 0xffd2 for printing, 0xc000 for user code.'" +msgstr "" + #: ../../howto/regex.rst:1225 msgid "" "When using the module-level :func:`re.sub` function, the pattern is passed " @@ -2157,7 +2847,7 @@ msgstr "" #: ../../howto/regex.rst:1233 msgid "Common Problems" -msgstr "Problemas Comuns" +msgstr "Problemas comuns" #: ../../howto/regex.rst:1235 msgid "" @@ -2173,7 +2863,7 @@ msgstr "" #: ../../howto/regex.rst:1241 msgid "Use String Methods" -msgstr "Usando String Methods" +msgstr "Usando métodos de string" #: ../../howto/regex.rst:1243 msgid "" @@ -2186,6 +2876,15 @@ msgid "" "for the purpose, instead of the large, more generalized regular expression " "engine." msgstr "" +"Às vezes, usar o módulo :mod:`re` é um equívoco. Se você está fazendo " +"correspondência com uma string fixa, ou uma classe de caractere única, e " +"você não está usando nenhum recurso de :mod:`re` como o sinalizador :const:" +"`~re.IGNORECASE`, então pode não ser necessário todo o poder das expressões " +"regulares. Strings possui vários métodos para executar operações com strings " +"fixas e eles são, geralmente, muito mais rápidos, porque a implementação é " +"um único e pequeno laço de repetição em C que foi otimizado para esse " +"propósito, em vez do grande e mais generalizado mecanismo das expressões " +"regulares." #: ../../howto/regex.rst:1251 msgid "" @@ -2199,6 +2898,15 @@ msgid "" "``word`` have a word boundary on either side. This takes the job beyond :" "meth:`!replace`'s abilities.)" msgstr "" +"Um exemplo pode ser a substituição de uma string fixa única por outra; por " +"exemplo, você pode substituir ``word`` por ``deed``. :func:`re.sub` parece " +"ser a função a ser usada para isso, mas considere o método :meth:`~str." +"replace`. Note que :meth:`!replace` também irá substituir ``word`` dentro de " +"palavras, transformando ``swordfish`` em ``sdeedfish``, mas uma RE ingênua " +"teria feito isso também. (Para evitar a realização da substituição de partes " +"de palavras, o padrão teria que ser ``\\bword\\b``, a fim de exigir que " +"``word`` tenha um limite de palavra em ambos os lados (o recurso borda). " +"Isso leva o tarefa para além da capacidade de :meth:`!replace`.)" #: ../../howto/regex.rst:1260 msgid "" @@ -2208,6 +2916,11 @@ msgid "" "capable of doing both tasks and will be faster than any regular expression " "operation can be." msgstr "" +"Outra tarefa comum é apagar todas as ocorrências de um único caractere de " +"uma string ou substitui-lo por um outro caractere único. Você pode fazer " +"isso com algo como ``re.sub('\\n', ' ', S)``, mas :meth:`~str.translate` é " +"capaz de fazer ambas as tarefas e será mais rápida do que qualquer operação " +"de expressão regular pode ser." #: ../../howto/regex.rst:1266 msgid "" @@ -2230,12 +2943,36 @@ msgid "" "start at 0; if the match wouldn't start at zero, :func:`!match` will *not* " "report it. ::" msgstr "" +"A função :func:`~re.match` somente verifica se a RE corresponde ao início " +"da string, enquanto :func:`~re.search` fará a varredura através na string " +"procurando por uma correspondência. É importante manter esta distinção em " +"mente. Lembre-se, :func:`!match` só irá relatar uma correspondência bem-" +"sucedida que começa em 0; se a correspondência não começar em zero, :func:`!" +"match` não vai reportá-la." + +#: ../../howto/regex.rst:1279 +msgid "" +">>> print(re.match('super', 'superstition').span())\n" +"(0, 5)\n" +">>> print(re.match('super', 'insuperable'))\n" +"None" +msgstr "" #: ../../howto/regex.rst:1284 msgid "" "On the other hand, :func:`~re.search` will scan forward through the string, " "reporting the first match it finds. ::" msgstr "" +"Por outro lado, :func:`~re.search` fará a varredura percorrendo a string e " +"relatando a primeira correspondência que encontrar." + +#: ../../howto/regex.rst:1287 +msgid "" +">>> print(re.search('super', 'superstition').span())\n" +"(0, 5)\n" +">>> print(re.search('super', 'insuperable').span())\n" +"(2, 7)" +msgstr "" #: ../../howto/regex.rst:1292 msgid "" @@ -2271,7 +3008,7 @@ msgstr "" #: ../../howto/regex.rst:1307 msgid "Greedy versus Non-Greedy" -msgstr "Gulosos versus não Gulosos" +msgstr "Gulosos versus não-gulosos" #: ../../howto/regex.rst:1309 msgid "" @@ -2288,6 +3025,17 @@ msgstr "" "para combinar uma única tag HTML não funciona por causa da natureza gulosa " "de ``.*``. ::" +#: ../../howto/regex.rst:1315 +msgid "" +">>> s = 'Title'\n" +">>> len(s)\n" +"32\n" +">>> print(re.match('<.*>', s).span())\n" +"(0, 32)\n" +">>> print(re.match('<.*>', s).group())\n" +"Title" +msgstr "" + #: ../../howto/regex.rst:1323 msgid "" "The RE matches the ``'<'`` in ``''``, and the ``.*`` consumes the rest " @@ -2297,6 +3045,12 @@ msgid "" "The final match extends from the ``'<'`` in ``''`` to the ``'>'`` in " "``''``, which isn't what you want." msgstr "" +"A RE corresponde a ``'<'`` em ``''``, e o ``.*`` consome o resto da " +"string. Existe ainda mais coisa existente na RE, no entanto, e o ``>`` pode " +"não corresponder com o final da string, de modo que o mecanismo de expressão " +"regular tem que recuar caractere por caractere até encontrar uma " +"correspondência para a ``>``. A correspondência final se estende do ``'<'`` " +"em ``''`` ao ``'>'`` em ``''``, que não é o que você quer." #: ../../howto/regex.rst:1330 msgid "" @@ -2306,6 +3060,18 @@ msgid "" "matches, and when it fails, the engine advances a character at a time, " "retrying the ``'>'`` at every step. This produces just the right result::" msgstr "" +"Neste caso, a solução é usar os quantificadores não-gulosos ``*?``, ``+?``, " +"``??`` ou ``{m,n}?``, que corresponde com o mínimo de texto possível. No " +"exemplo acima, o ``'>'`` é tentado imediatamente após a primeira " +"correspondência de ``'<'``, e quando ele falhar, o mecanismo avança um " +"caractere de cada vez, experimentado ``'>'`` a cada passo. Isso produz " +"justamente o resultado correto::" + +#: ../../howto/regex.rst:1336 +msgid "" +">>> print(re.match('<.*?>', s).group())\n" +"" +msgstr "" #: ../../howto/regex.rst:1339 msgid "" @@ -2346,6 +3112,9 @@ msgid "" "regular expression can be helpful, because it allows you to format the " "regular expression more clearly." msgstr "" +"Para tais REs, especificar a flag :const:`re.VERBOSE` ao compilar a " +"expressão regular pode ser útil, porque permite que você formate a expressão " +"regular de forma mais clara." #: ../../howto/regex.rst:1358 msgid "" @@ -2366,10 +3135,26 @@ msgstr "" "caractere ``#`` até a próxima nova linha. Quando usados junto com strings de " "aspas triplas, isso permite as REs serem formatadas mais ordenadamente::" +#: ../../howto/regex.rst:1366 +msgid "" +"pat = re.compile(r\"\"\"\n" +" \\s* # Skip leading whitespace\n" +" (?P
[^:]+) # Header name\n" +" \\s* : # Whitespace, and a colon\n" +" (?P.*?) # The header's value -- *? used to\n" +" # lose the following trailing whitespace\n" +" \\s*$ # Trailing whitespace to end-of-line\n" +"\"\"\", re.VERBOSE)" +msgstr "" + #: ../../howto/regex.rst:1375 msgid "This is far more readable than::" msgstr "Isso é muito mais legível do que::" +#: ../../howto/regex.rst:1377 +msgid "pat = re.compile(r\"\\s*(?P
[^:]+)\\s*:(?P.*?)\\s*$\")" +msgstr "" + #: ../../howto/regex.rst:1381 msgid "Feedback" msgstr "Comentários" @@ -2396,3 +3181,11 @@ msgid "" "edition covered Python's now-removed :mod:`!regex` module, which won't help " "you much.) Consider checking it out from your library." msgstr "" +"O livro mais completo sobre expressões regulares é quase certamente o " +"Mastering Regular Expressions de Jeffrey Friedl’s, publicado pela O'Reilly. " +"Infelizmente, ele se concentra exclusivamente em sabores de expressões " +"regulares do Perl e do Java, e não contém qualquer material relativo a " +"Python, por isso não vai ser útil como uma referência para a programação em " +"Python. (A primeira edição cobre o módulo :mod:`!regex` agora removido do " +"Python, o que não vai te ajudar muito.) Considere removê-lo de sua " +"biblioteca." diff --git a/howto/sockets.po b/howto/sockets.po index b85ef5412..bf6dbcee2 100644 --- a/howto/sockets.po +++ b/howto/sockets.po @@ -1,34 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:53+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../howto/sockets.rst:5 msgid "Socket Programming HOWTO" -msgstr "HOWTO sobre a Programação de Soquetes" +msgstr "Programação de Soquetes" #: ../../howto/sockets.rst:0 msgid "Author" @@ -76,13 +73,13 @@ msgstr "" "Só trataremos dos soquetes INET (ou seja, IPv4), no entanto, os mesmos " "representam ao menos 99% dos soquetes que estão atualmente em uso. Só " "estudaremos os soquetes STREAM (ou seja, TCP) - a menos que você realmente " -"saiba o que está fazendo (nesse caso, este HOWTO não é para você!), terás um " -"melhor conhecimento sobre o comportamento e o desempenho dos soquetes STREAM " -"do que qualquer outra coisa. Tentarei aclarar o mistério sobre o que " -"realmente é um soquete, bem como, apresentarei dicas de como trabalhar com " -"soquetes bloqueantes e os não bloqueantes. Começaremos o estudo falando da " -"razão pela qual bloquear um soquete. Precisas saber como os mesmos (os " -"soquetes bloqueantes) antes de estudar os não bloqueantes" +"saiba o que está fazendo (nesse caso, este documento não é para você!), " +"terás um melhor conhecimento sobre o comportamento e o desempenho dos " +"soquetes STREAM do que qualquer outra coisa. Tentarei aclarar o mistério " +"sobre o que realmente é um soquete, bem como, apresentarei dicas de como " +"trabalhar com soquetes bloqueantes e os não bloqueantes. Começaremos o " +"estudo falando da razão pela qual bloquear um soquete. Precisas saber como " +"os mesmos (os soquetes bloqueantes) antes de estudar os não bloqueantes" #: ../../howto/sockets.rst:31 msgid "" @@ -138,6 +135,14 @@ msgstr "" "De forma geral, quando clicastes no link que te trouxe até esta página " "(documentação do Python), o que o teu navegador fez, foi o seguinte::" +#: ../../howto/sockets.rst:59 +msgid "" +"# create an INET, STREAMing socket\n" +"s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" +"# now connect to the web server on port 80 - the normal http port\n" +"s.connect((\"www.python.org\", 80))" +msgstr "" + #: ../../howto/sockets.rst:64 msgid "" "When the ``connect`` completes, the socket ``s`` can be used to send in a " @@ -160,6 +165,16 @@ msgstr "" "O que acontece no lado do servidor Web é um pouco mais complexo. Primeiro, o " "Servidor Web cria um \"soquete tipo servidor\"::" +#: ../../howto/sockets.rst:73 +msgid "" +"# create an INET, STREAMing socket\n" +"serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" +"# bind the socket to a public host, and a well-known port\n" +"serversocket.bind((socket.gethostname(), 80))\n" +"# become a server socket\n" +"serversocket.listen(5)" +msgstr "" + #: ../../howto/sockets.rst:80 msgid "" "A couple things to notice: we used ``socket.gethostname()`` so that the " @@ -206,7 +221,18 @@ msgid "" "mainloop of the web server::" msgstr "" "Agora que temos um soquete tipo \"servidor\", que está ouvindo a porta 80, " -"podemos entrar no mainloop do servidor web::" +"podemos entrar no laço de repetição principal do servidor web::" + +#: ../../howto/sockets.rst:98 +msgid "" +"while True:\n" +" # accept connections from outside\n" +" (clientsocket, address) = serversocket.accept()\n" +" # now do something with the clientsocket\n" +" # in this case, we'll pretend this is a threaded server\n" +" ct = client_thread(clientsocket)\n" +" ct.run()" +msgstr "" #: ../../howto/sockets.rst:106 msgid "" @@ -263,7 +289,7 @@ msgid "" "API." msgstr "" "A módulo :mod:`multiprocessing` faz a integração do IPC de forma " -"multiplataforma numa API de nível superior." +"multiplataforma numa API de nível mais alto." #: ../../howto/sockets.rst:134 msgid "Using a Socket" @@ -369,6 +395,43 @@ msgid "" "fixed length message::" msgstr "" +#: ../../howto/sockets.rst:183 +msgid "" +"class MySocket:\n" +" \"\"\"demonstration class only\n" +" - coded for clarity, not efficiency\n" +" \"\"\"\n" +"\n" +" def __init__(self, sock=None):\n" +" if sock is None:\n" +" self.sock = socket.socket(\n" +" socket.AF_INET, socket.SOCK_STREAM)\n" +" else:\n" +" self.sock = sock\n" +"\n" +" def connect(self, host, port):\n" +" self.sock.connect((host, port))\n" +"\n" +" def mysend(self, msg):\n" +" totalsent = 0\n" +" while totalsent < MSGLEN:\n" +" sent = self.sock.send(msg[totalsent:])\n" +" if sent == 0:\n" +" raise RuntimeError(\"socket connection broken\")\n" +" totalsent = totalsent + sent\n" +"\n" +" def myreceive(self):\n" +" chunks = []\n" +" bytes_recd = 0\n" +" while bytes_recd < MSGLEN:\n" +" chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048))\n" +" if chunk == b'':\n" +" raise RuntimeError(\"socket connection broken\")\n" +" chunks.append(chunk)\n" +" bytes_recd = bytes_recd + len(chunk)\n" +" return b''.join(chunks)" +msgstr "" + #: ../../howto/sockets.rst:217 msgid "" "The sending code here is usable for almost any messaging scheme - in Python " @@ -561,6 +624,16 @@ msgid "" "Python, you'll have little trouble with it in C::" msgstr "" +#: ../../howto/sockets.rst:345 +msgid "" +"ready_to_read, ready_to_write, in_error = \\\n" +" select.select(\n" +" potential_readers,\n" +" potential_writers,\n" +" potential_errs,\n" +" timeout)" +msgstr "" + #: ../../howto/sockets.rst:352 msgid "" "You pass ``select`` three lists: the first contains all sockets that you " diff --git a/howto/sorting.po b/howto/sorting.po index 551d5283e..6b2aadfd4 100644 --- a/howto/sorting.po +++ b/howto/sorting.po @@ -1,34 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Lucas Sanches , 2021 -# Hildeberto Abreu Magalhães , 2022 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:53+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../howto/sorting.rst:4 msgid "Sorting Techniques" -msgstr "" +msgstr "Técnicas de ordenação" #: ../../howto/sorting.rst:0 msgid "Author" @@ -68,6 +65,14 @@ msgstr "" "Uma ordenação ascendente simples é muito fácil: apenas chame a função :func:" "`sorted`. Retorna uma nova lista ordenada:" +#: ../../howto/sorting.rst:22 +msgid "" +">>> sorted([5, 2, 3, 1, 4])\n" +"[1, 2, 3, 4, 5]" +msgstr "" +">>> sorted([5, 2, 3, 1, 4])\n" +"[1, 2, 3, 4, 5]" + #: ../../howto/sorting.rst:27 msgid "" "You can also use the :meth:`list.sort` method. It modifies the list in-place " @@ -80,6 +85,18 @@ msgstr "" "menos conveniente que a função :func:`sorted` - mas se você não precisará da " "lista original, esta maneira é levemente mais eficiente." +#: ../../howto/sorting.rst:32 +msgid "" +">>> a = [5, 2, 3, 1, 4]\n" +">>> a.sort()\n" +">>> a\n" +"[1, 2, 3, 4, 5]" +msgstr "" +">>> a = [5, 2, 3, 1, 4]\n" +">>> a.sort()\n" +">>> a\n" +"[1, 2, 3, 4, 5]" + #: ../../howto/sorting.rst:39 msgid "" "Another difference is that the :meth:`list.sort` method is only defined for " @@ -88,6 +105,14 @@ msgstr "" "Outra diferença é que o método :meth:`list.sort` é aplicável apenas às " "listas. Em contrapartida, a função :func:`sorted` aceita qualquer iterável." +#: ../../howto/sorting.rst:42 +msgid "" +">>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})\n" +"[1, 2, 3, 4, 5]" +msgstr "" +">>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})\n" +"[1, 2, 3, 4, 5]" + #: ../../howto/sorting.rst:48 msgid "Key Functions" msgstr "Funções Chave" @@ -106,6 +131,12 @@ msgstr "" msgid "For example, here's a case-insensitive string comparison:" msgstr "Por exemplo, aqui há uma comparação case-insensitive de strings." +#: ../../howto/sorting.rst:56 +msgid "" +">>> sorted(\"This is a test string from Andrew\".split(), key=str.casefold)\n" +"['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']" +msgstr "" + #: ../../howto/sorting.rst:61 msgid "" "The value of the *key* parameter should be a function (or other callable) " @@ -126,6 +157,17 @@ msgstr "" "Uma padrão comum é ordenar objetos complexos utilizando algum índice do " "objeto como chave. Por exemplo:" +#: ../../howto/sorting.rst:69 +msgid "" +">>> student_tuples = [\n" +"... ('john', 'A', 15),\n" +"... ('jane', 'B', 12),\n" +"... ('dave', 'B', 10),\n" +"... ]\n" +">>> sorted(student_tuples, key=lambda student: student[2]) # sort by age\n" +"[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]" +msgstr "" + #: ../../howto/sorting.rst:79 msgid "" "The same technique works for objects with named attributes. For example:" @@ -133,6 +175,26 @@ msgstr "" "A mesma técnica funciona com objetos que possuem atributos nomeados. Por " "exemplo:" +#: ../../howto/sorting.rst:81 +msgid "" +">>> class Student:\n" +"... def __init__(self, name, grade, age):\n" +"... self.name = name\n" +"... self.grade = grade\n" +"... self.age = age\n" +"... def __repr__(self):\n" +"... return repr((self.name, self.grade, self.age))\n" +"\n" +">>> student_objects = [\n" +"... Student('john', 'A', 15),\n" +"... Student('jane', 'B', 12),\n" +"... Student('dave', 'B', 10),\n" +"... ]\n" +">>> sorted(student_objects, key=lambda student: student.age) # sort by " +"age\n" +"[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]" +msgstr "" + #: ../../howto/sorting.rst:99 msgid "" "Objects with named attributes can be made by a regular class as shown above, " @@ -151,6 +213,10 @@ msgid "" "The :mod:`operator` module has :func:`~operator.itemgetter`, :func:" "`~operator.attrgetter`, and a :func:`~operator.methodcaller` function." msgstr "" +"O padrão de :term:`função chave` mostrado acima é muito comum, por isso, " +"Python provê funções convenientes para tornar as funções de acesso mais " +"fáceis e rápidas. O módulo :mod:`operator` tem as funções :func:`~operator." +"itemgetter`, :func:`~operator.attrgetter` e :func:`~operator.methodcaller`" #: ../../howto/sorting.rst:111 msgid "Using those functions, the above examples become simpler and faster:" @@ -158,6 +224,17 @@ msgstr "" "Usando estas funções, os exemplos acima se tornam mais simples e mais " "rápidos:" +#: ../../howto/sorting.rst:113 +msgid "" +">>> from operator import itemgetter, attrgetter\n" +"\n" +">>> sorted(student_tuples, key=itemgetter(2))\n" +"[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]\n" +"\n" +">>> sorted(student_objects, key=attrgetter('age'))\n" +"[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]" +msgstr "" + #: ../../howto/sorting.rst:123 msgid "" "The operator module functions allow multiple levels of sorting. For example, " @@ -166,6 +243,15 @@ msgstr "" "As funções do módulo operator permite múltiplos níveis de ordenação. Por " "exemplo, ordenar por *grade* e então por *age*:" +#: ../../howto/sorting.rst:126 +msgid "" +">>> sorted(student_tuples, key=itemgetter(1,2))\n" +"[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]\n" +"\n" +">>> sorted(student_objects, key=attrgetter('grade', 'age'))\n" +"[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]" +msgstr "" + #: ../../howto/sorting.rst:134 msgid "" "The :mod:`functools` module provides another helpful tool for making key-" @@ -174,9 +260,23 @@ msgid "" "it suitable for use as a key-function." msgstr "" +#: ../../howto/sorting.rst:139 +msgid "" +">>> from functools import partial\n" +">>> from unicodedata import normalize\n" +"\n" +">>> names = 'Zoë Åbjørn Núñez Élana Zeke Abe Nubia Eloise'.split()\n" +"\n" +">>> sorted(names, key=partial(normalize, 'NFD'))\n" +"['Abe', 'Åbjørn', 'Eloise', 'Élana', 'Nubia', 'Núñez', 'Zeke', 'Zoë']\n" +"\n" +">>> sorted(names, key=partial(normalize, 'NFC'))\n" +"['Abe', 'Eloise', 'Nubia', 'Núñez', 'Zeke', 'Zoë', 'Åbjørn', 'Élana']" +msgstr "" + #: ../../howto/sorting.rst:153 msgid "Ascending and Descending" -msgstr "Ascendente e Descendente" +msgstr "Ascendente e descendente" #: ../../howto/sorting.rst:155 msgid "" @@ -189,6 +289,15 @@ msgstr "" "ordenações descendentes. Por exemplo, para retornar os dados de estudantes " "pela ordem inversa de *age*:" +#: ../../howto/sorting.rst:159 +msgid "" +">>> sorted(student_tuples, key=itemgetter(2), reverse=True)\n" +"[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]\n" +"\n" +">>> sorted(student_objects, key=attrgetter('age'), reverse=True)\n" +"[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]" +msgstr "" + #: ../../howto/sorting.rst:168 msgid "Sort Stability and Complex Sorts" msgstr "Estabilidade de Ordenação e Ordenações Complexas" @@ -203,6 +312,13 @@ msgstr "" "Sorting_algorithm#Stability>`_\\. Isso significa que quando múltiplos " "registros possuem a mesma chave, eles terão sua ordem original preservada." +#: ../../howto/sorting.rst:174 +msgid "" +">>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]\n" +">>> sorted(data, key=itemgetter(0))\n" +"[('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]" +msgstr "" + #: ../../howto/sorting.rst:180 msgid "" "Notice how the two records for *blue* retain their original order so that " @@ -222,6 +338,15 @@ msgstr "" "de estudante por ordem descendente de *grade* e então ascendente de *age*, " "primeiro ordene *age* e depois ordene novamente utilizando *grade*:" +#: ../../howto/sorting.rst:187 +msgid "" +">>> s = sorted(student_objects, key=attrgetter('age')) # sort on " +"secondary key\n" +">>> sorted(s, key=attrgetter('grade'), reverse=True) # now sort on " +"primary key, descending\n" +"[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]" +msgstr "" + #: ../../howto/sorting.rst:193 msgid "" "This can be abstracted out into a wrapper function that can take a list and " @@ -230,6 +355,17 @@ msgstr "" "Isso pode ser abstrato no caso das funções invólucros que podem receber uma " "lista e uma tupla com o campos e então ordená-los em múltiplos passos." +#: ../../howto/sorting.rst:196 +msgid "" +">>> def multisort(xs, specs):\n" +"... for key, reverse in reversed(specs):\n" +"... xs.sort(key=attrgetter(key), reverse=reverse)\n" +"... return xs\n" +"\n" +">>> multisort(list(student_objects), (('grade', True), ('age', False)))\n" +"[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]" +msgstr "" + #: ../../howto/sorting.rst:206 msgid "" "The `Timsort `_ algorithm used in " @@ -277,6 +413,15 @@ msgstr "" "Por exemplo, para ordenar os dados dos estudantes por *grade* usando a " "abordagem DSU:" +#: ../../howto/sorting.rst:224 +msgid "" +">>> decorated = [(student.grade, i, student) for i, student in " +"enumerate(student_objects)]\n" +">>> decorated.sort()\n" +">>> [student for grade, i, student in decorated] # undecorate\n" +"[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]" +msgstr "" + #: ../../howto/sorting.rst:231 msgid "" "This idiom works because tuples are compared lexicographically; the first " @@ -335,7 +480,7 @@ msgstr "" #: ../../howto/sorting.rst:253 msgid "Comparison Functions" -msgstr "" +msgstr "Funções de comparação" #: ../../howto/sorting.rst:255 msgid "" @@ -367,6 +512,10 @@ msgid "" "function::" msgstr "" +#: ../../howto/sorting.rst:273 +msgid "sorted(words, key=cmp_to_key(strcoll)) # locale-aware sort order" +msgstr "" + #: ../../howto/sorting.rst:276 msgid "Odds and Ends" msgstr "Curiosidades e conclusões" @@ -391,12 +540,33 @@ msgstr "" "efeito pode ser simulado sem o parâmetro usando a função embutida :func:" "`reversed` duas vezes:" +#: ../../howto/sorting.rst:288 +msgid "" +">>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]\n" +">>> standard_way = sorted(data, key=itemgetter(0), reverse=True)\n" +">>> double_reversed = list(reversed(sorted(reversed(data), " +"key=itemgetter(0))))\n" +">>> assert standard_way == double_reversed\n" +">>> standard_way\n" +"[('red', 1), ('red', 2), ('blue', 1), ('blue', 2)]" +msgstr "" + #: ../../howto/sorting.rst:297 msgid "" "The sort routines use ``<`` when making comparisons between two objects. So, " "it is easy to add a standard sort order to a class by defining an :meth:" "`~object.__lt__` method:" msgstr "" +"As rotinas de classificação usam ``<`` ao fazer comparações entre dois " +"objetos. Portanto, é fácil adicionar uma ordem de classificação padrão a uma " +"classe definindo um método :meth:`~object.__lt__`:" + +#: ../../howto/sorting.rst:301 +msgid "" +">>> Student.__lt__ = lambda self, other: self.age < other.age\n" +">>> sorted(student_objects)\n" +"[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]" +msgstr "" #: ../../howto/sorting.rst:307 msgid "" @@ -420,9 +590,17 @@ msgstr "" "dicionário, elas poderão ser usadas para ordenar uma lista separada de nomes " "de alunos:" +#: ../../howto/sorting.rst:319 +msgid "" +">>> students = ['dave', 'john', 'jane']\n" +">>> newgrades = {'john': 'F', 'jane':'A', 'dave': 'C'}\n" +">>> sorted(students, key=newgrades.__getitem__)\n" +"['jane', 'dave', 'john']" +msgstr "" + #: ../../howto/sorting.rst:327 msgid "Partial Sorts" -msgstr "" +msgstr "Ordenações parciais" #: ../../howto/sorting.rst:329 msgid "" diff --git a/howto/timerfd.po b/howto/timerfd.po index 7a4b0bcb6..111e0fef3 100644 --- a/howto/timerfd.po +++ b/howto/timerfd.po @@ -1,32 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-21 14:14+0000\n" -"PO-Revision-Date: 2024-05-11 01:08+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../howto/timerfd.rst:5 msgid "timer file descriptor HOWTO" -msgstr "HOWTO de descritor de arquivo de temporizador" +msgstr "Descritor de arquivo de temporizador" #: ../../howto/timerfd.rst:0 msgid "Release" @@ -40,7 +39,7 @@ msgstr "1.13" msgid "" "This HOWTO discusses Python's support for the linux timer file descriptor." msgstr "" -"Este HOWTO discute o suporte do Python para o descritor de arquivo de " +"Este documento discute o suporte do Python para o descritor de arquivo de " "temporizador do Linux." #: ../../howto/timerfd.rst:13 @@ -55,6 +54,48 @@ msgstr "" "O exemplo a seguir mostra como usar um descritor de arquivo de temporizador " "para executar uma função duas vezes por segundo:" +#: ../../howto/timerfd.rst:18 +msgid "" +"# Practical scripts should use really use a non-blocking timer,\n" +"# we use a blocking timer here for simplicity.\n" +"import os, time\n" +"\n" +"# Create the timer file descriptor\n" +"fd = os.timerfd_create(time.CLOCK_REALTIME)\n" +"\n" +"# Start the timer in 1 second, with an interval of half a second\n" +"os.timerfd_settime(fd, initial=1, interval=0.5)\n" +"\n" +"try:\n" +" # Process timer events four times.\n" +" for _ in range(4):\n" +" # read() will block until the timer expires\n" +" _ = os.read(fd, 8)\n" +" print(\"Timer expired\")\n" +"finally:\n" +" # Remember to close the timer file descriptor!\n" +" os.close(fd)" +msgstr "" +"# Scripts práticos devem realmente usar um timer sem bloqueio.\n" +"# Usamos um timer com bloqueio aqui para simplificar.\n" +"import os, time\n" +"\n" +"# Cria um descritor de arquivo de temporizador\n" +"fd = os.timerfd_create(time.CLOCK_REALTIME)\n" +"\n" +"# Inicia o temporizador em 1 segundo, com um intervalo de meio segundo\n" +"os.timerfd_settime(fd, initial=1, interval=0.5)\n" +"\n" +"try:\n" +" # Processa eventos do temporizador quatro vezes.\n" +" for _ in range(4):\n" +" # read() ser bloqueado até o temporizador expirar\n" +" _ = os.read(fd, 8)\n" +" print(\"Timer expired\")\n" +"finally:\n" +" # Lembre-se de fechar o descritor de arquivo de temporizador!\n" +" os.close(fd)" + #: ../../howto/timerfd.rst:40 msgid "" "To avoid the precision loss caused by the :class:`float` type, timer file " @@ -75,6 +116,244 @@ msgstr "" "descritores de arquivo de temporizador para esperar até que o descritor de " "arquivo esteja pronto para leitura:" +#: ../../howto/timerfd.rst:47 +msgid "" +"import os, time, select, socket, sys\n" +"\n" +"# Create an epoll object\n" +"ep = select.epoll()\n" +"\n" +"# In this example, use loopback address to send \"stop\" command to the " +"server.\n" +"#\n" +"# $ telnet 127.0.0.1 1234\n" +"# Trying 127.0.0.1...\n" +"# Connected to 127.0.0.1.\n" +"# Escape character is '^]'.\n" +"# stop\n" +"# Connection closed by foreign host.\n" +"#\n" +"sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" +"sock.bind((\"127.0.0.1\", 1234))\n" +"sock.setblocking(False)\n" +"sock.listen(1)\n" +"ep.register(sock, select.EPOLLIN)\n" +"\n" +"# Create timer file descriptors in non-blocking mode.\n" +"num = 3\n" +"fds = []\n" +"for _ in range(num):\n" +" fd = os.timerfd_create(time.CLOCK_REALTIME, flags=os.TFD_NONBLOCK)\n" +" fds.append(fd)\n" +" # Register the timer file descriptor for read events\n" +" ep.register(fd, select.EPOLLIN)\n" +"\n" +"# Start the timer with os.timerfd_settime_ns() in nanoseconds.\n" +"# Timer 1 fires every 0.25 seconds; timer 2 every 0.5 seconds; etc\n" +"for i, fd in enumerate(fds, start=1):\n" +" one_sec_in_nsec = 10**9\n" +" i = i * one_sec_in_nsec\n" +" os.timerfd_settime_ns(fd, initial=i//4, interval=i//4)\n" +"\n" +"timeout = 3\n" +"try:\n" +" conn = None\n" +" is_active = True\n" +" while is_active:\n" +" # Wait for the timer to expire for 3 seconds.\n" +" # epoll.poll() returns a list of (fd, event) pairs.\n" +" # fd is a file descriptor.\n" +" # sock and conn[=returned value of socket.accept()] are socket " +"objects, not file descriptors.\n" +" # So use sock.fileno() and conn.fileno() to get the file " +"descriptors.\n" +" events = ep.poll(timeout)\n" +"\n" +" # If more than one timer file descriptors are ready for reading at " +"once,\n" +" # epoll.poll() returns a list of (fd, event) pairs.\n" +" #\n" +" # In this example settings,\n" +" # 1st timer fires every 0.25 seconds in 0.25 seconds. (0.25, 0.5, " +"0.75, 1.0, ...)\n" +" # 2nd timer every 0.5 seconds in 0.5 seconds. (0.5, 1.0, 1.5, " +"2.0, ...)\n" +" # 3rd timer every 0.75 seconds in 0.75 seconds. (0.75, 1.5, 2.25, " +"3.0, ...)\n" +" #\n" +" # In 0.25 seconds, only 1st timer fires.\n" +" # In 0.5 seconds, 1st timer and 2nd timer fires at once.\n" +" # In 0.75 seconds, 1st timer and 3rd timer fires at once.\n" +" # In 1.5 seconds, 1st timer, 2nd timer and 3rd timer fires at " +"once.\n" +" #\n" +" # If a timer file descriptor is signaled more than once since\n" +" # the last os.read() call, os.read() returns the number of signaled\n" +" # as host order of class bytes.\n" +" print(f\"Signaled events={events}\")\n" +" for fd, event in events:\n" +" if event & select.EPOLLIN:\n" +" if fd == sock.fileno():\n" +" # Check if there is a connection request.\n" +" print(f\"Accepting connection {fd}\")\n" +" conn, addr = sock.accept()\n" +" conn.setblocking(False)\n" +" print(f\"Accepted connection {conn} from {addr}\")\n" +" ep.register(conn, select.EPOLLIN)\n" +" elif conn and fd == conn.fileno():\n" +" # Check if there is data to read.\n" +" print(f\"Reading data {fd}\")\n" +" data = conn.recv(1024)\n" +" if data:\n" +" # You should catch UnicodeDecodeError exception for " +"safety.\n" +" cmd = data.decode()\n" +" if cmd.startswith(\"stop\"):\n" +" print(f\"Stopping server\")\n" +" is_active = False\n" +" else:\n" +" print(f\"Unknown command: {cmd}\")\n" +" else:\n" +" # No more data, close connection\n" +" print(f\"Closing connection {fd}\")\n" +" ep.unregister(conn)\n" +" conn.close()\n" +" conn = None\n" +" elif fd in fds:\n" +" print(f\"Reading timer {fd}\")\n" +" count = int.from_bytes(os.read(fd, 8), byteorder=sys." +"byteorder)\n" +" print(f\"Timer {fds.index(fd) + 1} expired {count} " +"times\")\n" +" else:\n" +" print(f\"Unknown file descriptor {fd}\")\n" +"finally:\n" +" for fd in fds:\n" +" ep.unregister(fd)\n" +" os.close(fd)\n" +" ep.close()" +msgstr "" +"import os, time, select, socket, sys\n" +"\n" +"# Cria um objeto epoll\n" +"ep = select.epoll()\n" +"\n" +"# Neste exemplo, usa o endereço de loopback para enviar o comando \"stop\" " +"ao servidor.\n" +"#\n" +"# $ telnet 127.0.0.1 1234\n" +"# Trying 127.0.0.1...\n" +"# Connected to 127.0.0.1.\n" +"# Escape character is '^]'.\n" +"# stop\n" +"# Connection closed by foreign host.\n" +"#\n" +"sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" +"sock.bind((\"127.0.0.1\", 1234))\n" +"sock.setblocking(False)\n" +"sock.listen(1)\n" +"ep.register(sock, select.EPOLLIN)\n" +"\n" +"# Cria descritores de arquivo de temporizador no modo não bloqueante.\n" +"num = 3\n" +"fds = []\n" +"for _ in range(num):\n" +" fd = os.timerfd_create(time.CLOCK_REALTIME, flags=os.TFD_NONBLOCK)\n" +" fds.append(fd)\n" +" # Registra o descritor de arquivo do temporizador para eventos de " +"leitura\n" +" ep.register(fd, select.EPOLLIN)\n" +"\n" +"# Inicia o temporizador com os.timerfd_settime_ns() em nanossegundos.\n" +"# O temporizador 1 dispara a cada 0,25 segundos; o timer 2 a cada 0,5 " +"segundos; etc.\n" +"for i, fd in enumerate(fds, start=1):\n" +" one_sec_in_nsec = 10**9\n" +" i = i * one_sec_in_nsec\n" +" os.timerfd_settime_ns(fd, initial=i//4, interval=i//4)\n" +"\n" +"timeout = 3\n" +"try:\n" +" conn = None\n" +" is_active = True\n" +" while is_active:\n" +" # Aguarda o temporizador expirar por 3 segundos.\n" +" # epoll.poll() retorna uma lista de pares (fd, event).\n" +" # fd é um descritor de arquivo.\n" +" # sock e conn[=valor retornado de socket.accept()] são objetos de " +"socket, não descritores de arquivo.\n" +" # Então use sock.fileno() e conn.fileno() para obter os descritores " +"de arquivo.\n" +" events = ep.poll(timeout)\n" +"\n" +" # Se mais de um descritor de arquivo de timer estiver pronto para " +"leitura ao mesmo tempo,\n" +" # epoll.poll() retorna uma lista de pares (fd, event).\n" +" #\n" +" # Neste exemplo de configurações,\n" +" # O 1º temporizador dispara a cada 0,25 segundos em 0,25 " +"segundos. (0,25, 0,5, 0,75, 1,0, ...)\n" +" # O 2º temporizador dispara a cada 0,5 segundos em 0,5 segundos. " +"(0,5, 1,0, 1,5, 2,0, ...)\n" +" # O 3º temporizador dispara a cada 0,75 segundos em 0,75 " +"segundos. (0,75, 1,5, 2,25, 3,0, ...)\n" +" #\n" +" # Em 0,25 segundos, apenas o 1º temporizador dispara.\n" +" # Em 0,5 segundos, o 1º temporizador e o 2º temporizador disparam " +"ao mesmo tempo.\n" +" # Em 0,75 segundos, o 1º temporizador e o 3º temporizador " +"disparam ao mesmo tempo.\n" +" # Em 1,5 segundos, o 1º temporizador, o 2º temporizador e o 3º " +"temporizador disparam ao mesmo tempo.\n" +" #\n" +" # Se um descritor de arquivo de temporizador for sinalizado mais de " +"uma vez desde\n" +" # a última chamada de os.read(), os.read() retornará o número de " +"sinalizados\n" +" # como ordem de host de bytes de classe.\n" +" print(f\"Signaled events={events}\")\n" +" for fd, event in events:\n" +" if event & select.EPOLLIN:\n" +" if fd == sock.fileno():\n" +" # Verifica se há uma requisição de conexão.\n" +" print(f\"Accepting connection {fd}\")\n" +" conn, addr = sock.accept()\n" +" conn.setblocking(False)\n" +" print(f\"Accepted connection {conn} from {addr}\")\n" +" ep.register(conn, select.EPOLLIN)\n" +" elif conn and fd == conn.fileno():\n" +" # Verifica se há dados para ler.\n" +" print(f\"Reading data {fd}\")\n" +" data = conn.recv(1024)\n" +" if data:\n" +" # Você deveria capturar exceção UnicodeDecodeError " +"por segurança.\n" +" cmd = data.decode()\n" +" if cmd.startswith(\"stop\"):\n" +" print(f\"Stopping server\")\n" +" is_active = False\n" +" else:\n" +" print(f\"Unknown command: {cmd}\")\n" +" else:\n" +" # Acabaram os dados, fecha a conexão\n" +" print(f\"Closing connection {fd}\")\n" +" ep.unregister(conn)\n" +" conn.close()\n" +" conn = None\n" +" elif fd in fds:\n" +" print(f\"Reading timer {fd}\")\n" +" count = int.from_bytes(os.read(fd, 8), byteorder=sys." +"byteorder)\n" +" print(f\"Timer {fds.index(fd) + 1} expired {count} " +"times\")\n" +" else:\n" +" print(f\"Unknown file descriptor {fd}\")\n" +"finally:\n" +" for fd in fds:\n" +" ep.unregister(fd)\n" +" os.close(fd)\n" +" ep.close()" + #: ../../howto/timerfd.rst:153 msgid "" "This example shows how :func:`~select.select` can be used with timer file " @@ -83,3 +362,161 @@ msgstr "" "Este exemplo mostra como :func:`~select.select` pode ser usado com " "descritores de arquivo de temporizador para esperar até que o descritor de " "arquivo esteja pronto para leitura:" + +#: ../../howto/timerfd.rst:156 +msgid "" +"import os, time, select, socket, sys\n" +"\n" +"# In this example, use loopback address to send \"stop\" command to the " +"server.\n" +"#\n" +"# $ telnet 127.0.0.1 1234\n" +"# Trying 127.0.0.1...\n" +"# Connected to 127.0.0.1.\n" +"# Escape character is '^]'.\n" +"# stop\n" +"# Connection closed by foreign host.\n" +"#\n" +"sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" +"sock.bind((\"127.0.0.1\", 1234))\n" +"sock.setblocking(False)\n" +"sock.listen(1)\n" +"\n" +"# Create timer file descriptors in non-blocking mode.\n" +"num = 3\n" +"fds = [os.timerfd_create(time.CLOCK_REALTIME, flags=os.TFD_NONBLOCK)\n" +" for _ in range(num)]\n" +"select_fds = fds + [sock]\n" +"\n" +"# Start the timers with os.timerfd_settime() in seconds.\n" +"# Timer 1 fires every 0.25 seconds; timer 2 every 0.5 seconds; etc\n" +"for i, fd in enumerate(fds, start=1):\n" +" os.timerfd_settime(fd, initial=i/4, interval=i/4)\n" +"\n" +"timeout = 3\n" +"try:\n" +" conn = None\n" +" is_active = True\n" +" while is_active:\n" +" # Wait for the timer to expire for 3 seconds.\n" +" # select.select() returns a list of file descriptors or objects.\n" +" rfd, wfd, xfd = select.select(select_fds, select_fds, select_fds, " +"timeout)\n" +" for fd in rfd:\n" +" if fd == sock:\n" +" # Check if there is a connection request.\n" +" print(f\"Accepting connection {fd}\")\n" +" conn, addr = sock.accept()\n" +" conn.setblocking(False)\n" +" print(f\"Accepted connection {conn} from {addr}\")\n" +" select_fds.append(conn)\n" +" elif conn and fd == conn:\n" +" # Check if there is data to read.\n" +" print(f\"Reading data {fd}\")\n" +" data = conn.recv(1024)\n" +" if data:\n" +" # You should catch UnicodeDecodeError exception for " +"safety.\n" +" cmd = data.decode()\n" +" if cmd.startswith(\"stop\"):\n" +" print(f\"Stopping server\")\n" +" is_active = False\n" +" else:\n" +" print(f\"Unknown command: {cmd}\")\n" +" else:\n" +" # No more data, close connection\n" +" print(f\"Closing connection {fd}\")\n" +" select_fds.remove(conn)\n" +" conn.close()\n" +" conn = None\n" +" elif fd in fds:\n" +" print(f\"Reading timer {fd}\")\n" +" count = int.from_bytes(os.read(fd, 8), byteorder=sys." +"byteorder)\n" +" print(f\"Timer {fds.index(fd) + 1} expired {count} times\")\n" +" else:\n" +" print(f\"Unknown file descriptor {fd}\")\n" +"finally:\n" +" for fd in fds:\n" +" os.close(fd)\n" +" sock.close()\n" +" sock = None" +msgstr "" +"import os, time, select, socket, sys\n" +"\n" +"# Neste exemplo, usa o endereço de loopback para enviar o comando \"stop\" " +"ao servidor.\n" +"#\n" +"# $ telnet 127.0.0.1 1234\n" +"# Trying 127.0.0.1...\n" +"# Connected to 127.0.0.1.\n" +"# Escape character is '^]'.\n" +"# stop\n" +"# Connection closed by foreign host.\n" +"#\n" +"sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" +"sock.bind((\"127.0.0.1\", 1234))\n" +"sock.setblocking(False)\n" +"sock.listen(1)\n" +"\n" +"# Cria descritores de arquivo de temporizador no modo não bloqueante.\n" +"num = 3\n" +"fds = [os.timerfd_create(time.CLOCK_REALTIME, flags=os.TFD_NONBLOCK)\n" +" for _ in range(num)]\n" +"select_fds = fds + [sock]\n" +"\n" +"# Inicia o temporizador com os.timerfd_settime() em segundos.\n" +"# O temporizador 1 dispara a cada 0,25 segundos; o timer 2 a cada 0,5 " +"segundos; etc.\n" +"for i, fd in enumerate(fds, start=1):\n" +" os.timerfd_settime(fd, initial=i/4, interval=i/4)\n" +"\n" +"timeout = 3\n" +"try:\n" +" conn = None\n" +" is_active = True\n" +" while is_active:\n" +" # Aguarda o temporizador expirar por 3 segundos.\n" +" # select.select() retorna uma lista de objetos ou descritores de " +"arquivos.\n" +" rfd, wfd, xfd = select.select(select_fds, select_fds, select_fds, " +"timeout)\n" +" for fd in rfd:\n" +" if fd == sock:\n" +" # Verifica se há uma requisição de conexão.\n" +" print(f\"Accepting connection {fd}\")\n" +" conn, addr = sock.accept()\n" +" conn.setblocking(False)\n" +" print(f\"Accepted connection {conn} from {addr}\")\n" +" select_fds.append(conn)\n" +" elif conn and fd == conn:\n" +" # Verifica se há dados para ler.\n" +" print(f\"Reading data {fd}\")\n" +" data = conn.recv(1024)\n" +" if data:\n" +" # Você deveria capturar exceção UnicodeDecodeError por " +"segurança.\n" +" cmd = data.decode()\n" +" if cmd.startswith(\"stop\"):\n" +" print(f\"Stopping server\")\n" +" is_active = False\n" +" else:\n" +" print(f\"Unknown command: {cmd}\")\n" +" else:\n" +" # Acabaram os dados, fecha a conexão\n" +" print(f\"Closing connection {fd}\")\n" +" select_fds.remove(conn)\n" +" conn.close()\n" +" conn = None\n" +" elif fd in fds:\n" +" print(f\"Reading timer {fd}\")\n" +" count = int.from_bytes(os.read(fd, 8), byteorder=sys." +"byteorder)\n" +" print(f\"Timer {fds.index(fd) + 1} expired {count} times\")\n" +" else:\n" +" print(f\"Unknown file descriptor {fd}\")\n" +"finally:\n" +" for fd in fds:\n" +" os.close(fd)\n" +" sock.close()\n" +" sock = None" diff --git a/howto/unicode.po b/howto/unicode.po index b3beebaf5..ca46bdfb7 100644 --- a/howto/unicode.po +++ b/howto/unicode.po @@ -1,37 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Leticia Portella , 2021 -# Otávio Carneiro , 2021 -# Victor Matheus Castro , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 00:53+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../howto/unicode.rst:5 msgid "Unicode HOWTO" -msgstr "Unicode HOWTO" +msgstr "Unicode" #: ../../howto/unicode.rst:0 msgid "Release" @@ -119,6 +113,25 @@ msgstr "" "O padrão Unicode contém várias tabelas listando caracteres e seus pontos de " "código:" +#: ../../howto/unicode.rst:53 +msgid "" +"0061 'a'; LATIN SMALL LETTER A\n" +"0062 'b'; LATIN SMALL LETTER B\n" +"0063 'c'; LATIN SMALL LETTER C\n" +"...\n" +"007B '{'; LEFT CURLY BRACKET\n" +"...\n" +"2167 'Ⅷ'; ROMAN NUMERAL EIGHT\n" +"2168 'Ⅸ'; ROMAN NUMERAL NINE\n" +"...\n" +"265E '♞'; BLACK CHESS KNIGHT\n" +"265F '♟'; BLACK CHESS PAWN\n" +"...\n" +"1F600 '😀'; GRINNING FACE\n" +"1F609 '😉'; WINKING FACE\n" +"..." +msgstr "" + #: ../../howto/unicode.rst:71 msgid "" "Strictly, these definitions imply that it's meaningless to say 'this is " @@ -166,6 +179,13 @@ msgid "" "representation, the string \"Python\" might look like this:" msgstr "" +#: ../../howto/unicode.rst:101 +msgid "" +" P y t h o n\n" +"0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00\n" +" 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23" +msgstr "" + #: ../../howto/unicode.rst:107 msgid "" "This representation is straightforward but using it presents a number of " @@ -345,11 +365,28 @@ msgid "" "include a Unicode character in a string literal::" msgstr "" +#: ../../howto/unicode.rst:199 +msgid "" +"try:\n" +" with open('/tmp/input.txt', 'r') as f:\n" +" ...\n" +"except OSError:\n" +" # 'File not found' error message.\n" +" print(\"Fichier non trouvé\")" +msgstr "" + #: ../../howto/unicode.rst:206 msgid "" "Side note: Python 3 also supports using Unicode characters in identifiers::" msgstr "" +#: ../../howto/unicode.rst:208 +msgid "" +"répertoire = \"/tmp/records.log\"\n" +"with open(répertoire, \"w\") as f:\n" +" f.write(\"test\\n\")" +msgstr "" + #: ../../howto/unicode.rst:212 msgid "" "If you can't enter a particular character in your editor or want to keep the " @@ -358,6 +395,16 @@ msgid "" "delta glyph instead of a \\u escape.) ::" msgstr "" +#: ../../howto/unicode.rst:217 +msgid "" +">>> \"\\N{GREEK CAPITAL LETTER DELTA}\" # Using the character name\n" +"'\\u0394'\n" +">>> \"\\u0394\" # Using a 16-bit hex value\n" +"'\\u0394'\n" +">>> \"\\U00000394\" # Using a 32-bit hex value\n" +"'\\u0394'" +msgstr "" + #: ../../howto/unicode.rst:224 msgid "" "In addition, one can create a string using the :func:`~bytes.decode` method " @@ -376,6 +423,21 @@ msgid "" "examples show the differences::" msgstr "" +#: ../../howto/unicode.rst:236 +msgid "" +">>> b'\\x80abc'.decode(\"utf-8\", \"strict\")\n" +"Traceback (most recent call last):\n" +" ...\n" +"UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0:\n" +" invalid start byte\n" +">>> b'\\x80abc'.decode(\"utf-8\", \"replace\")\n" +"'\\ufffdabc'\n" +">>> b'\\x80abc'.decode(\"utf-8\", \"backslashreplace\")\n" +"'\\\\x80abc'\n" +">>> b'\\x80abc'.decode(\"utf-8\", \"ignore\")\n" +"'abc'" +msgstr "" + #: ../../howto/unicode.rst:248 msgid "" "Encodings are specified as strings containing the encoding's name. Python " @@ -394,6 +456,14 @@ msgid "" "returns the code point value::" msgstr "" +#: ../../howto/unicode.rst:260 +msgid "" +">>> chr(57344)\n" +"'\\ue000'\n" +">>> ord('\\ue000')\n" +"57344" +msgstr "" + #: ../../howto/unicode.rst:266 msgid "Converting to Bytes" msgstr "Convertendo para Bytes" @@ -420,6 +490,28 @@ msgstr "" msgid "The following example shows the different results::" msgstr "" +#: ../../howto/unicode.rst:282 +msgid "" +">>> u = chr(40960) + 'abcd' + chr(1972)\n" +">>> u.encode('utf-8')\n" +"b'\\xea\\x80\\x80abcd\\xde\\xb4'\n" +">>> u.encode('ascii')\n" +"Traceback (most recent call last):\n" +" ...\n" +"UnicodeEncodeError: 'ascii' codec can't encode character '\\ua000' in\n" +" position 0: ordinal not in range(128)\n" +">>> u.encode('ascii', 'ignore')\n" +"b'abcd'\n" +">>> u.encode('ascii', 'replace')\n" +"b'?abcd?'\n" +">>> u.encode('ascii', 'xmlcharrefreplace')\n" +"b'ꀀabcd޴'\n" +">>> u.encode('ascii', 'backslashreplace')\n" +"b'\\\\ua000abcd\\\\u07b4'\n" +">>> u.encode('ascii', 'namereplace')\n" +"b'\\\\N{YI SYLLABLE IT}abcd\\\\u07b4'" +msgstr "" + #: ../../howto/unicode.rst:301 msgid "" "The low-level routines for registering and accessing the available encodings " @@ -442,6 +534,16 @@ msgid "" "digits, not four::" msgstr "" +#: ../../howto/unicode.rst:317 +msgid "" +">>> s = \"a\\xac\\u1234\\u20ac\\U00008000\"\n" +"... # ^^^^ two-digit hex escape\n" +"... # ^^^^^^ four-digit Unicode escape\n" +"... # ^^^^^^^^^^ eight-digit Unicode escape\n" +">>> [ord(c) for c in s]\n" +"[97, 172, 4660, 8364, 32768]" +msgstr "" + #: ../../howto/unicode.rst:324 msgid "" "Using escape sequences for code points greater than 127 is fine in small " @@ -467,6 +569,15 @@ msgid "" "file::" msgstr "" +#: ../../howto/unicode.rst:339 +msgid "" +"#!/usr/bin/env python\n" +"# -*- coding: latin-1 -*-\n" +"\n" +"u = 'abcdé'\n" +"print(ord(u[-1]))" +msgstr "" + #: ../../howto/unicode.rst:345 msgid "" "The syntax is inspired by Emacs's notation for specifying variables local to " @@ -504,10 +615,34 @@ msgstr "" "O programa a seguir exibe alguma informação sobre diversos caracteres e " "imprime o valor numérico de um caractere em particular::" +#: ../../howto/unicode.rst:369 +msgid "" +"import unicodedata\n" +"\n" +"u = chr(233) + chr(0x0bf2) + chr(3972) + chr(6000) + chr(13231)\n" +"\n" +"for i, c in enumerate(u):\n" +" print(i, '%04x' % ord(c), unicodedata.category(c), end=\" \")\n" +" print(unicodedata.name(c))\n" +"\n" +"# Get numeric value of second character\n" +"print(unicodedata.numeric(u[1]))" +msgstr "" + #: ../../howto/unicode.rst:380 msgid "When run, this prints:" msgstr "Quando executado, isso imprime:" +#: ../../howto/unicode.rst:382 +msgid "" +"0 00e9 Ll LATIN SMALL LETTER E WITH ACUTE\n" +"1 0bf2 No TAMIL NUMBER ONE THOUSAND\n" +"2 0f84 Mn TIBETAN MARK HALANTA\n" +"3 1770 Lo TAGBANWA LETTER SA\n" +"4 33af So SQUARE RAD OVER S SQUARED\n" +"1000.0" +msgstr "" + #: ../../howto/unicode.rst:391 msgid "" "The category codes are abbreviations describing the nature of the character. " @@ -544,6 +679,13 @@ msgid "" "which becomes the pair of lowercase letters 'ss'." msgstr "" +#: ../../howto/unicode.rst:421 +msgid "" +">>> street = 'Gürzenichstraße'\n" +">>> street.casefold()\n" +"'gürzenichstrasse'" +msgstr "" + #: ../../howto/unicode.rst:425 msgid "" "A second tool is the :mod:`unicodedata` module's :func:`~unicodedata." @@ -554,10 +696,36 @@ msgid "" "combining characters differently:" msgstr "" +#: ../../howto/unicode.rst:434 +msgid "" +"import unicodedata\n" +"\n" +"def compare_strs(s1, s2):\n" +" def NFD(s):\n" +" return unicodedata.normalize('NFD', s)\n" +"\n" +" return NFD(s1) == NFD(s2)\n" +"\n" +"single_char = 'ê'\n" +"multiple_chars = '\\N{LATIN SMALL LETTER E}\\N{COMBINING CIRCUMFLEX " +"ACCENT}'\n" +"print('length of first string=', len(single_char))\n" +"print('length of second string=', len(multiple_chars))\n" +"print(compare_strs(single_char, multiple_chars))" +msgstr "" + #: ../../howto/unicode.rst:448 msgid "When run, this outputs:" msgstr "" +#: ../../howto/unicode.rst:450 +msgid "" +"$ python compare-strs.py\n" +"length of first string= 1\n" +"length of second string= 2\n" +"True" +msgstr "" + #: ../../howto/unicode.rst:457 msgid "" "The first argument to the :func:`~unicodedata.normalize` function is a " @@ -569,6 +737,24 @@ msgstr "" msgid "The Unicode Standard also specifies how to do caseless comparisons::" msgstr "" +#: ../../howto/unicode.rst:463 +msgid "" +"import unicodedata\n" +"\n" +"def compare_caseless(s1, s2):\n" +" def NFD(s):\n" +" return unicodedata.normalize('NFD', s)\n" +"\n" +" return NFD(NFD(s1).casefold()) == NFD(NFD(s2).casefold())\n" +"\n" +"# Example usage\n" +"single_char = 'ê'\n" +"multiple_chars = '\\N{LATIN CAPITAL LETTER E}\\N{COMBINING CIRCUMFLEX " +"ACCENT}'\n" +"\n" +"print(compare_caseless(single_char, multiple_chars))" +msgstr "" + #: ../../howto/unicode.rst:477 msgid "" "This will print ``True``. (Why is :func:`!NFD` invoked twice? Because " @@ -597,6 +783,16 @@ msgid "" "numerals::" msgstr "" +#: ../../howto/unicode.rst:496 +msgid "" +"import re\n" +"p = re.compile(r'\\d+')\n" +"\n" +"s = \"Over \\u0e55\\u0e57 57 flavours\"\n" +"m = p.search(s)\n" +"print(repr(m.group()))" +msgstr "" + #: ../../howto/unicode.rst:503 msgid "" "When executed, ``\\d+`` will match the Thai numerals and print them out. If " @@ -709,12 +905,27 @@ msgstr "" msgid "Reading Unicode from a file is therefore simple::" msgstr "" +#: ../../howto/unicode.rst:576 +msgid "" +"with open('unicode.txt', encoding='utf-8') as f:\n" +" for line in f:\n" +" print(repr(line))" +msgstr "" + #: ../../howto/unicode.rst:580 msgid "" "It's also possible to open files in update mode, allowing both reading and " "writing::" msgstr "" +#: ../../howto/unicode.rst:583 +msgid "" +"with open('test', encoding='utf-8', mode='w+') as f:\n" +" f.write('\\u4500 blah blah blah\\n')\n" +" f.seek(0)\n" +" print(repr(f.readline()[:1]))" +msgstr "" + #: ../../howto/unicode.rst:588 msgid "" "The Unicode character ``U+FEFF`` is used as a byte-order mark (BOM), and is " @@ -763,6 +974,13 @@ msgid "" "and it will be automatically converted to the right encoding for you::" msgstr "" +#: ../../howto/unicode.rst:622 +msgid "" +"filename = 'filename\\u4500abc'\n" +"with open(filename, 'w') as f:\n" +" f.write('blah\\n')" +msgstr "" + #: ../../howto/unicode.rst:626 msgid "" "Functions in the :mod:`os` module such as :func:`os.stat` will also accept " @@ -782,10 +1000,28 @@ msgid "" "error handler>` is UTF-8, running the following program::" msgstr "" +#: ../../howto/unicode.rst:639 +msgid "" +"fn = 'filename\\u4500abc'\n" +"f = open(fn, 'w')\n" +"f.close()\n" +"\n" +"import os\n" +"print(os.listdir(b'.'))\n" +"print(os.listdir('.'))" +msgstr "" + #: ../../howto/unicode.rst:647 msgid "will produce the following output:" msgstr "" +#: ../../howto/unicode.rst:649 +msgid "" +"$ python listdir-test.py\n" +"[b'filename\\xe4\\x94\\x80abc', ...]\n" +"['filename\\u4500abc', ...]" +msgstr "" + #: ../../howto/unicode.rst:655 msgid "" "The first list contains UTF-8-encoded filenames, and the second list " @@ -858,6 +1094,17 @@ msgid "" "it with a :class:`~codecs.StreamRecoder` to return bytes encoded in UTF-8::" msgstr "" +#: ../../howto/unicode.rst:701 +msgid "" +"new_f = codecs.StreamRecoder(f,\n" +" # en/decoder: used by read() to encode its results and\n" +" # by write() to decode its input.\n" +" codecs.getencoder('utf-8'), codecs.getdecoder('utf-8'),\n" +"\n" +" # reader/writer: used to read and write to the stream.\n" +" codecs.getreader('latin-1'), codecs.getwriter('latin-1') )" +msgstr "" + #: ../../howto/unicode.rst:711 msgid "Files in an Unknown Encoding" msgstr "" @@ -870,6 +1117,18 @@ msgid "" "``surrogateescape`` error handler::" msgstr "" +#: ../../howto/unicode.rst:718 +msgid "" +"with open(fname, 'r', encoding=\"ascii\", errors=\"surrogateescape\") as f:\n" +" data = f.read()\n" +"\n" +"# make changes to the string 'data'\n" +"\n" +"with open(fname + '.new', 'w',\n" +" encoding=\"ascii\", errors=\"surrogateescape\") as f:\n" +" f.write(data)" +msgstr "" + #: ../../howto/unicode.rst:727 msgid "" "The ``surrogateescape`` error handler will decode any non-ASCII bytes as " diff --git a/howto/urllib2.po b/howto/urllib2.po index f30f52088..52c14e79e 100644 --- a/howto/urllib2.po +++ b/howto/urllib2.po @@ -1,37 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Ruan Aragão , 2021 -# Otávio Carneiro , 2021 -# Adorilson Bezerra , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2023 -# Vitor Buxbaum Orlandi, 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:53+0000\n" -"Last-Translator: Vitor Buxbaum Orlandi, 2023\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../howto/urllib2.rst:5 msgid "HOWTO Fetch Internet Resources Using The urllib Package" -msgstr "Como Buscar Recursos Da Internet Usando O Pacote urllib" +msgstr "Como buscar recursos da Internet usando o pacote urllib" #: ../../howto/urllib2.rst:0 msgid "Author" @@ -111,10 +105,10 @@ msgstr "" "se depara com erros ou casos não triviais ao abrir URLs HTTP, você vai " "precisar entender um pouco mais do HyperText Transfer Protocol. A literatura " "de referência mais reconhecida e compreensível para o HTTP é :rfc:`2616`. " -"Ela é um documento técnico e não foi feita para ser fácil de ler. Este HOWTO " -"busca ilustrar o uso de *urllib* com detalhes suficientes sobre HTTP para te " -"permitir seguir adiante. Ele não tem a intenção de substituir a documentação " -"do :mod:`urllib.request`, mas é suplementar a ela." +"Ela é um documento técnico e não foi feita para ser fácil de ler. Este " +"documento busca ilustrar o uso de *urllib* com detalhes suficientes sobre " +"HTTP para te permitir seguir adiante. Ele não tem a intenção de substituir a " +"documentação do :mod:`urllib.request`, mas é suplementar a ela." #: ../../howto/urllib2.rst:44 msgid "Fetching URLs" @@ -124,6 +118,16 @@ msgstr "Acessando URLs" msgid "The simplest way to use urllib.request is as follows::" msgstr "O modo mais simples de usar urllib.request é o seguinte::" +#: ../../howto/urllib2.rst:48 +msgid "" +"import urllib.request\n" +"with urllib.request.urlopen('http://python.org/') as response:\n" +" html = response.read()" +msgstr "" +"import urllib.request\n" +"with urllib.request.urlopen('http://python.org/') as response:\n" +" html = response.read()" + #: ../../howto/urllib2.rst:52 msgid "" "If you wish to retrieve a resource via URL and store it in a temporary " @@ -134,6 +138,30 @@ msgstr "" "temporária, você pode fazê-lo com as funções :func:`shutil.copyfileobj` e :" "func:`tempfile.NamedTemporaryFile`::" +#: ../../howto/urllib2.rst:56 +msgid "" +"import shutil\n" +"import tempfile\n" +"import urllib.request\n" +"\n" +"with urllib.request.urlopen('http://python.org/') as response:\n" +" with tempfile.NamedTemporaryFile(delete=False) as tmp_file:\n" +" shutil.copyfileobj(response, tmp_file)\n" +"\n" +"with open(tmp_file.name) as html:\n" +" pass" +msgstr "" +"import shutil\n" +"import tempfile\n" +"import urllib.request\n" +"\n" +"with urllib.request.urlopen('http://python.org/') as response:\n" +" with tempfile.NamedTemporaryFile(delete=False) as tmp_file:\n" +" shutil.copyfileobj(response, tmp_file)\n" +"\n" +"with open(tmp_file.name) as html:\n" +" pass" + #: ../../howto/urllib2.rst:67 msgid "" "Many uses of urllib will be that simple (note that instead of an 'http:' URL " @@ -165,6 +193,20 @@ msgstr "" "resposta é um objeto arquivo ou similar, o que significa que você pode, por " "exemplo, chamar ``.read()`` na resposta::" +#: ../../howto/urllib2.rst:80 +msgid "" +"import urllib.request\n" +"\n" +"req = urllib.request.Request('http://python.org/')\n" +"with urllib.request.urlopen(req) as response:\n" +" the_page = response.read()" +msgstr "" +"import urllib.request\n" +"\n" +"req = urllib.request.Request('http://python.org/')\n" +"with urllib.request.urlopen(req) as response:\n" +" the_page = response.read()" + #: ../../howto/urllib2.rst:86 msgid "" "Note that urllib.request makes use of the same Request interface to handle " @@ -174,6 +216,10 @@ msgstr "" "esquemas URL. Por exemplo, você pode fazer uma solicitação FTP da seguinte " "forma::" +#: ../../howto/urllib2.rst:89 +msgid "req = urllib.request.Request('ftp://example.com/')" +msgstr "req = urllib.request.Request('ftp://example.com/')" + #: ../../howto/urllib2.rst:91 msgid "" "In the case of HTTP, there are two extra things that Request objects allow " @@ -182,10 +228,16 @@ msgid "" "request itself, to the server - this information is sent as HTTP " "\"headers\". Let's look at each of these in turn." msgstr "" +"No caso do HTTP, há duas coisas extras que os objetos Request permitem que " +"você faça: primeiro, você pode passar dados a serem enviados ao servidor. " +"Segundo, você pode passar informações extras (\"metadados\") *sobre* os " +"dados ou sobre a própria solicitação para o servidor — essas informações são " +"enviadas como \"cabeçalhos\" HTTP. Vamos analisar cada um deles " +"separadamente." #: ../../howto/urllib2.rst:98 msgid "Data" -msgstr "" +msgstr "Dados" #: ../../howto/urllib2.rst:100 msgid "" @@ -199,6 +251,46 @@ msgid "" "Request object as the ``data`` argument. The encoding is done using a " "function from the :mod:`urllib.parse` library. ::" msgstr "" +"Às vezes, você deseja enviar dados para uma URL (geralmente a URL se refere " +"a um script CGI (Common Gateway Interface) ou outra aplicação web). Com " +"HTTP, isso geralmente é feito usando o que é conhecido como uma solicitação " +"**POST**. Isso geralmente é o que seu navegador faz quando você envia um " +"formulário HTML preenchido na web. Nem todos os POSTs precisam vir de " +"formulários: você pode usar um POST para transmitir dados arbitrários para " +"sua própria aplicação. No caso comum de formulários HTML, os dados precisam " +"ser codificados de forma padrão e, em seguida, passados ​​para o objeto " +"Request como o argumento ``data``. A codificação é feita usando uma função " +"da biblioteca :mod:`urllib.parse`. ::" + +#: ../../howto/urllib2.rst:110 +msgid "" +"import urllib.parse\n" +"import urllib.request\n" +"\n" +"url = 'http://www.someserver.com/cgi-bin/register.cgi'\n" +"values = {'name' : 'Michael Foord',\n" +" 'location' : 'Northampton',\n" +" 'language' : 'Python' }\n" +"\n" +"data = urllib.parse.urlencode(values)\n" +"data = data.encode('ascii') # data should be bytes\n" +"req = urllib.request.Request(url, data)\n" +"with urllib.request.urlopen(req) as response:\n" +" the_page = response.read()" +msgstr "" +"import urllib.parse\n" +"import urllib.request\n" +"\n" +"url = 'http://www.someserver.com/cgi-bin/register.cgi'\n" +"values = {'name' : 'Michael Foord',\n" +" 'location' : 'Northampton',\n" +" 'language' : 'Python' }\n" +"\n" +"data = urllib.parse.urlencode(values)\n" +"data = data.encode('ascii') # data should be bytes\n" +"req = urllib.request.Request(url, data)\n" +"with urllib.request.urlopen(req) as response:\n" +" the_page = response.read()" #: ../../howto/urllib2.rst:124 msgid "" @@ -206,6 +298,10 @@ msgid "" "HTML forms - see `HTML Specification, Form Submission `_ for more details)." msgstr "" +"Observe que outras codificações às vezes são necessárias (por exemplo, para " +"envio de arquivos de formulários HTML - consulte `HTML Specification, Form " +"Submission `_ " +"para mais detalhes)." #: ../../howto/urllib2.rst:129 msgid "" @@ -219,11 +315,49 @@ msgid "" "side-effects, nor a POST requests from having no side-effects. Data can also " "be passed in an HTTP GET request by encoding it in the URL itself." msgstr "" +"Se você não passar o argumento ``data``, o urllib usará uma requisição " +"**GET**. Uma diferença entre requisições GET e POST é que as requisições " +"POST frequentemente têm \"efeitos colaterais\": elas alteram o estado do " +"sistema de alguma forma (por exemplo, ao fazer um pedido ao site para que " +"cem libras de spam enlatado sejam entregues em sua porta). Embora o padrão " +"HTTP deixe claro que os POSTs devem *sempre* causar efeitos colaterais, e as " +"requisições GET *nunca* causar efeitos colaterais, nada impede que uma " +"requisição GET tenha efeitos colaterais, nem que uma requisição POST não " +"tenha efeitos colaterais. Dados também podem ser passados ​​em uma requisição " +"HTTP GET codificando-os na própria URL." #: ../../howto/urllib2.rst:139 msgid "This is done as follows::" msgstr "Isso é feito como abaixo::" +#: ../../howto/urllib2.rst:141 +msgid "" +">>> import urllib.request\n" +">>> import urllib.parse\n" +">>> data = {}\n" +">>> data['name'] = 'Somebody Here'\n" +">>> data['location'] = 'Northampton'\n" +">>> data['language'] = 'Python'\n" +">>> url_values = urllib.parse.urlencode(data)\n" +">>> print(url_values) # The order may differ from below.\n" +"name=Somebody+Here&language=Python&location=Northampton\n" +">>> url = 'http://www.example.com/example.cgi'\n" +">>> full_url = url + '?' + url_values\n" +">>> data = urllib.request.urlopen(full_url)" +msgstr "" +">>> import urllib.request\n" +">>> import urllib.parse\n" +">>> data = {}\n" +">>> data['name'] = 'Alguem Aqui'\n" +">>> data['location'] = 'Northampton'\n" +">>> data['language'] = 'Python'\n" +">>> url_values = urllib.parse.urlencode(data)\n" +">>> print(url_values) # A ordem pode ser diferente da abaixo.\n" +"name=Alguem+Aqui&language=Python&location=Northampton\n" +">>> url = 'http://www.example.com/example.cgi'\n" +">>> full_url = url + '?' + url_values\n" +">>> data = urllib.request.urlopen(full_url)" + #: ../../howto/urllib2.rst:154 msgid "" "Notice that the full URL is created by adding a ``?`` to the URL, followed " @@ -234,13 +368,15 @@ msgstr "" #: ../../howto/urllib2.rst:158 msgid "Headers" -msgstr "" +msgstr "Cabeçalhos" #: ../../howto/urllib2.rst:160 msgid "" "We'll discuss here one particular HTTP header, to illustrate how to add " "headers to your HTTP request." msgstr "" +"Discutiremos aqui um cabeçalho HTTP específico para ilustrar como adicionar " +"cabeçalhos à sua solicitação HTTP." #: ../../howto/urllib2.rst:163 msgid "" @@ -254,6 +390,49 @@ msgid "" "the same request as above, but identifies itself as a version of Internet " "Explorer [#]_. ::" msgstr "" +"Alguns sites [#]_ não gostam de ser navegados por programas ou enviam " +"versões diferentes para navegadores diferentes [#]_. Por padrão, urllib se " +"identifica como ``Python-urllib/x.y`` (onde ``x`` e ``y`` são os números de " +"versão principal e secundária da versão do Python, por exemplo, ``Python-" +"urllib/2.5``), o que pode confundir o site ou simplesmente não funcionar. A " +"forma como um navegador se identifica é através do cabeçalho ``User-Agent`` " +"[#]_. Ao criar um objeto Request, você pode passar um dicionário de " +"cabeçalhos. O exemplo a seguir faz a mesma solicitação acima, mas se " +"identifica como uma versão do Internet Explorer [#]_. ::" + +#: ../../howto/urllib2.rst:174 +msgid "" +"import urllib.parse\n" +"import urllib.request\n" +"\n" +"url = 'http://www.someserver.com/cgi-bin/register.cgi'\n" +"user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'\n" +"values = {'name': 'Michael Foord',\n" +" 'location': 'Northampton',\n" +" 'language': 'Python' }\n" +"headers = {'User-Agent': user_agent}\n" +"\n" +"data = urllib.parse.urlencode(values)\n" +"data = data.encode('ascii')\n" +"req = urllib.request.Request(url, data, headers)\n" +"with urllib.request.urlopen(req) as response:\n" +" the_page = response.read()" +msgstr "" +"import urllib.parse\n" +"import urllib.request\n" +"\n" +"url = 'http://www.someserver.com/cgi-bin/register.cgi'\n" +"user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'\n" +"values = {'name': 'Michael Foord',\n" +" 'location': 'Northampton',\n" +" 'language': 'Python' }\n" +"headers = {'User-Agent': user_agent}\n" +"\n" +"data = urllib.parse.urlencode(values)\n" +"data = data.encode('ascii')\n" +"req = urllib.request.Request(url, data, headers)\n" +"with urllib.request.urlopen(req) as response:\n" +" the_page = response.read()" #: ../../howto/urllib2.rst:190 msgid "" @@ -261,6 +440,9 @@ msgid "" "geturl`_ which comes after we have a look at what happens when things go " "wrong." msgstr "" +"A resposta também possui dois métodos úteis. Veja a seção sobre `info e " +"geturl`_, que vem depois de analisarmos o que acontece quando as coisas dão " +"errado." #: ../../howto/urllib2.rst:195 msgid "Handling Exceptions" @@ -272,16 +454,21 @@ msgid "" "response (though as usual with Python APIs, built-in exceptions such as :exc:" "`ValueError`, :exc:`TypeError` etc. may also be raised)." msgstr "" +"*urlopen* levanta :exc:`~urllib.error.URLError` quando não consegue tratar " +"uma resposta (embora, como de costume com APIs Python, exceções embutidas " +"como :exc:`ValueError`, :exc:`TypeError` etc. também possam ser levantadas)." #: ../../howto/urllib2.rst:201 msgid "" ":exc:`~urllib.error.HTTPError` is the subclass of :exc:`~urllib.error." "URLError` raised in the specific case of HTTP URLs." msgstr "" +":exc:`~urllib.error.HTTPError` é a subclasse de :exc:`~urllib.error." +"URLError` levantada no caso específico de URLs HTTP." #: ../../howto/urllib2.rst:204 msgid "The exception classes are exported from the :mod:`urllib.error` module." -msgstr "" +msgstr "As classes de exceção são exportadas do módulo :mod:`urllib.error`." #: ../../howto/urllib2.rst:207 msgid "URLError" @@ -294,10 +481,30 @@ msgid "" "case, the exception raised will have a 'reason' attribute, which is a tuple " "containing an error code and a text error message." msgstr "" +"Frequentemente, URLError é levantada porque não há conexão de rede (nenhuma " +"rota para o servidor especificado) ou o servidor especificado não existe. " +"Nesse caso, a exceção gerada terá um atributo \"reason\", que é uma tupla " +"contendo um código de erro e uma mensagem de erro em texto." #: ../../howto/urllib2.rst:214 msgid "e.g. ::" -msgstr "" +msgstr "Por exemplo ::" + +#: ../../howto/urllib2.rst:216 +msgid "" +">>> req = urllib.request.Request('http://www.pretend_server.org')\n" +">>> try: urllib.request.urlopen(req)\n" +"... except urllib.error.URLError as e:\n" +"... print(e.reason)\n" +"...\n" +"(4, 'getaddrinfo failed')" +msgstr "" +">>> req = urllib.request.Request('http://www.pretend_server.org')\n" +">>> try: urllib.request.urlopen(req)\n" +"... except urllib.error.URLError as e:\n" +"... print(e.reason)\n" +"...\n" +"(4, 'getaddrinfo failed')" #: ../../howto/urllib2.rst:225 msgid "HTTPError" @@ -314,21 +521,34 @@ msgid "" "HTTPError`. Typical errors include '404' (page not found), '403' (request " "forbidden), and '401' (authentication required)." msgstr "" +"Cada resposta HTTP do servidor contém um \"código de status\" numérico. Às " +"vezes, o código de status indica que o servidor não consegue atender à " +"solicitação. Os manipuladores padrão lidarão com algumas dessas respostas " +"para você (por exemplo, se a resposta for um \"redirecionamento\" que " +"solicita que o cliente busque o documento de uma URL diferente, o urllib " +"cuidará disso para você). Para aquelas que ele não consegue tratar, o " +"urlopen lançará um :exc:`~urllib.error.HTTPError`. Erros típicos incluem " +"'404' (página não encontrada), '403' (solicitação proibida) e " +"'401' (autenticação necessária)." #: ../../howto/urllib2.rst:235 msgid "" "See section 10 of :rfc:`2616` for a reference on all the HTTP error codes." msgstr "" +"Veja a seção 10 de :rfc:`2616` para uma referência sobre todos os códigos de " +"erro HTTP." #: ../../howto/urllib2.rst:237 msgid "" "The :exc:`~urllib.error.HTTPError` instance raised will have an integer " "'code' attribute, which corresponds to the error sent by the server." msgstr "" +"A instância :exc:`~urllib.error.HTTPError` levantada terá um atributo " +"inteiro 'code', que corresponde ao erro enviado pelo servidor." #: ../../howto/urllib2.rst:241 msgid "Error Codes" -msgstr "" +msgstr "Códigos de erro" #: ../../howto/urllib2.rst:243 msgid "" @@ -336,6 +556,9 @@ msgid "" "codes in the 100--299 range indicate success, you will usually only see " "error codes in the 400--599 range." msgstr "" +"Como os tratadores padrão controlam redirecionamentos (códigos no intervalo " +"300) e códigos no intervalo 100-299 indicam sucesso, normalmente você verá " +"apenas códigos de erro no intervalo 400-599." #: ../../howto/urllib2.rst:247 msgid "" @@ -343,6 +566,147 @@ msgid "" "of response codes in that shows all the response codes used by :rfc:`2616`. " "The dictionary is reproduced here for convenience ::" msgstr "" +":attr:`http.server.BaseHTTPRequestHandler.responses` é um dicionário útil de " +"códigos de resposta que mostra todos os códigos de resposta usados ​​por :rfc:" +"`2616`. O dicionário é reproduzido aqui para facilitar ::" + +#: ../../howto/urllib2.rst:251 +msgid "" +"# Table mapping response codes to messages; entries have the\n" +"# form {code: (shortmessage, longmessage)}.\n" +"responses = {\n" +" 100: ('Continue', 'Request received, please continue'),\n" +" 101: ('Switching Protocols',\n" +" 'Switching to new protocol; obey Upgrade header'),\n" +"\n" +" 200: ('OK', 'Request fulfilled, document follows'),\n" +" 201: ('Created', 'Document created, URL follows'),\n" +" 202: ('Accepted',\n" +" 'Request accepted, processing continues off-line'),\n" +" 203: ('Non-Authoritative Information', 'Request fulfilled from cache'),\n" +" 204: ('No Content', 'Request fulfilled, nothing follows'),\n" +" 205: ('Reset Content', 'Clear input form for further input.'),\n" +" 206: ('Partial Content', 'Partial content follows.'),\n" +"\n" +" 300: ('Multiple Choices',\n" +" 'Object has several resources -- see URI list'),\n" +" 301: ('Moved Permanently', 'Object moved permanently -- see URI list'),\n" +" 302: ('Found', 'Object moved temporarily -- see URI list'),\n" +" 303: ('See Other', 'Object moved -- see Method and URL list'),\n" +" 304: ('Not Modified',\n" +" 'Document has not changed since given time'),\n" +" 305: ('Use Proxy',\n" +" 'You must use proxy specified in Location to access this '\n" +" 'resource.'),\n" +" 307: ('Temporary Redirect',\n" +" 'Object moved temporarily -- see URI list'),\n" +"\n" +" 400: ('Bad Request',\n" +" 'Bad request syntax or unsupported method'),\n" +" 401: ('Unauthorized',\n" +" 'No permission -- see authorization schemes'),\n" +" 402: ('Payment Required',\n" +" 'No payment -- see charging schemes'),\n" +" 403: ('Forbidden',\n" +" 'Request forbidden -- authorization will not help'),\n" +" 404: ('Not Found', 'Nothing matches the given URI'),\n" +" 405: ('Method Not Allowed',\n" +" 'Specified method is invalid for this server.'),\n" +" 406: ('Not Acceptable', 'URI not available in preferred format.'),\n" +" 407: ('Proxy Authentication Required', 'You must authenticate with '\n" +" 'this proxy before proceeding.'),\n" +" 408: ('Request Timeout', 'Request timed out; try again later.'),\n" +" 409: ('Conflict', 'Request conflict.'),\n" +" 410: ('Gone',\n" +" 'URI no longer exists and has been permanently removed.'),\n" +" 411: ('Length Required', 'Client must specify Content-Length.'),\n" +" 412: ('Precondition Failed', 'Precondition in headers is false.'),\n" +" 413: ('Request Entity Too Large', 'Entity is too large.'),\n" +" 414: ('Request-URI Too Long', 'URI is too long.'),\n" +" 415: ('Unsupported Media Type', 'Entity body in unsupported format.'),\n" +" 416: ('Requested Range Not Satisfiable',\n" +" 'Cannot satisfy request range.'),\n" +" 417: ('Expectation Failed',\n" +" 'Expect condition could not be satisfied.'),\n" +"\n" +" 500: ('Internal Server Error', 'Server got itself in trouble'),\n" +" 501: ('Not Implemented',\n" +" 'Server does not support this operation'),\n" +" 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),\n" +" 503: ('Service Unavailable',\n" +" 'The server cannot process the request due to a high load'),\n" +" 504: ('Gateway Timeout',\n" +" 'The gateway server did not receive a timely response'),\n" +" 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),\n" +" }" +msgstr "" +"# Tabela de mapeamento de códigos de resposta para mensagens;\n" +"# as entradas têm o formato {código: (mensagemcurta, mensagemlonga)}.\n" +"responses = {\n" +" 100: ('Continue', 'Request received, please continue'),\n" +" 101: ('Switching Protocols',\n" +" 'Switching to new protocol; obey Upgrade header'),\n" +"\n" +" 200: ('OK', 'Request fulfilled, document follows'),\n" +" 201: ('Created', 'Document created, URL follows'),\n" +" 202: ('Accepted',\n" +" 'Request accepted, processing continues off-line'),\n" +" 203: ('Non-Authoritative Information', 'Request fulfilled from cache'),\n" +" 204: ('No Content', 'Request fulfilled, nothing follows'),\n" +" 205: ('Reset Content', 'Clear input form for further input.'),\n" +" 206: ('Partial Content', 'Partial content follows.'),\n" +"\n" +" 300: ('Multiple Choices',\n" +" 'Object has several resources -- see URI list'),\n" +" 301: ('Moved Permanently', 'Object moved permanently -- see URI list'),\n" +" 302: ('Found', 'Object moved temporarily -- see URI list'),\n" +" 303: ('See Other', 'Object moved -- see Method and URL list'),\n" +" 304: ('Not Modified',\n" +" 'Document has not changed since given time'),\n" +" 305: ('Use Proxy',\n" +" 'You must use proxy specified in Location to access this '\n" +" 'resource.'),\n" +" 307: ('Temporary Redirect',\n" +" 'Object moved temporarily -- see URI list'),\n" +"\n" +" 400: ('Bad Request',\n" +" 'Bad request syntax or unsupported method'),\n" +" 401: ('Unauthorized',\n" +" 'No permission -- see authorization schemes'),\n" +" 402: ('Payment Required',\n" +" 'No payment -- see charging schemes'),\n" +" 403: ('Forbidden',\n" +" 'Request forbidden -- authorization will not help'),\n" +" 404: ('Not Found', 'Nothing matches the given URI'),\n" +" 405: ('Method Not Allowed',\n" +" 'Specified method is invalid for this server.'),\n" +" 406: ('Not Acceptable', 'URI not available in preferred format.'),\n" +" 407: ('Proxy Authentication Required', 'You must authenticate with '\n" +" 'this proxy before proceeding.'),\n" +" 408: ('Request Timeout', 'Request timed out; try again later.'),\n" +" 409: ('Conflict', 'Request conflict.'),\n" +" 410: ('Gone',\n" +" 'URI no longer exists and has been permanently removed.'),\n" +" 411: ('Length Required', 'Client must specify Content-Length.'),\n" +" 412: ('Precondition Failed', 'Precondition in headers is false.'),\n" +" 413: ('Request Entity Too Large', 'Entity is too large.'),\n" +" 414: ('Request-URI Too Long', 'URI is too long.'),\n" +" 415: ('Unsupported Media Type', 'Entity body in unsupported format.'),\n" +" 416: ('Requested Range Not Satisfiable',\n" +" 'Cannot satisfy request range.'),\n" +" 417: ('Expectation Failed',\n" +" 'Expect condition could not be satisfied.'),\n" +"\n" +" 500: ('Internal Server Error', 'Server got itself in trouble'),\n" +" 501: ('Not Implemented',\n" +" 'Server does not support this operation'),\n" +" 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),\n" +" 503: ('Service Unavailable',\n" +" 'The server cannot process the request due to a high load'),\n" +" 504: ('Gateway Timeout',\n" +" 'The gateway server did not receive a timely response'),\n" +" 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),\n" +" }" #: ../../howto/urllib2.rst:319 msgid "" @@ -352,6 +716,43 @@ msgid "" "attribute, it also has read, geturl, and info, methods as returned by the " "``urllib.response`` module::" msgstr "" +"Quando um erro é levantado, o servidor responde retornando um código de erro " +"HTTP *e* uma página de erro. Você pode usar a instância :exc:`~urllib.error." +"HTTPError` como resposta na página retornada. Isso significa que, além do " +"atributo code, ela também possui os métodos read, geturl e info, conforme " +"retornados pelo módulo ``urllib.response``::" + +#: ../../howto/urllib2.rst:324 +msgid "" +">>> req = urllib.request.Request('http://www.python.org/fish.html')\n" +">>> try:\n" +"... urllib.request.urlopen(req)\n" +"... except urllib.error.HTTPError as e:\n" +"... print(e.code)\n" +"... print(e.read())\n" +"...\n" +"404\n" +"b'\\n\\n\\nPage Not Found\\n\n" +" ..." +msgstr "" +">>> req = urllib.request.Request('http://www.python.org/fish.html')\n" +">>> try:\n" +"... urllib.request.urlopen(req)\n" +"... except urllib.error.HTTPError as e:\n" +"... print(e.code)\n" +"... print(e.read())\n" +"...\n" +"404\n" +"b'\\n\\n\\nPage Not Found\\n\n" +" ..." #: ../../howto/urllib2.rst:339 msgid "Wrapping it Up" @@ -363,24 +764,91 @@ msgid "" "`~urllib.error.URLError` there are two basic approaches. I prefer the second " "approach." msgstr "" +"Então, se você quiser se preparar para :exc:`~urllib.error.HTTPError` *ou* :" +"exc:`~urllib.error.URLError`, existem duas abordagens básicas. Eu prefiro a " +"segunda." #: ../../howto/urllib2.rst:345 msgid "Number 1" -msgstr "" +msgstr "Número 1" + +#: ../../howto/urllib2.rst:350 +msgid "" +"from urllib.request import Request, urlopen\n" +"from urllib.error import URLError, HTTPError\n" +"req = Request(someurl)\n" +"try:\n" +" response = urlopen(req)\n" +"except HTTPError as e:\n" +" print('The server couldn\\'t fulfill the request.')\n" +" print('Error code: ', e.code)\n" +"except URLError as e:\n" +" print('We failed to reach a server.')\n" +" print('Reason: ', e.reason)\n" +"else:\n" +" # everything is fine" +msgstr "" +"from urllib.request import Request, urlopen\n" +"from urllib.error import URLError, HTTPError\n" +"req = Request(someurl)\n" +"try:\n" +" response = urlopen(req)\n" +"except HTTPError as e:\n" +" print('The server couldn\\'t fulfill the request.')\n" +" print('Error code: ', e.code)\n" +"except URLError as e:\n" +" print('We failed to reach a server.')\n" +" print('Reason: ', e.reason)\n" +"else:\n" +" # tudo certo" #: ../../howto/urllib2.rst:367 msgid "" "The ``except HTTPError`` *must* come first, otherwise ``except URLError`` " "will *also* catch an :exc:`~urllib.error.HTTPError`." msgstr "" +"O ``except HTTPError`` *deve* vir primeiro, caso contrário, ``except " +"URLError`` *também* capturará uma :exc:`~urllib.error.HTTPError`." #: ../../howto/urllib2.rst:371 msgid "Number 2" -msgstr "" +msgstr "Número 2" + +#: ../../howto/urllib2.rst:375 +msgid "" +"from urllib.request import Request, urlopen\n" +"from urllib.error import URLError\n" +"req = Request(someurl)\n" +"try:\n" +" response = urlopen(req)\n" +"except URLError as e:\n" +" if hasattr(e, 'reason'):\n" +" print('We failed to reach a server.')\n" +" print('Reason: ', e.reason)\n" +" elif hasattr(e, 'code'):\n" +" print('The server couldn\\'t fulfill the request.')\n" +" print('Error code: ', e.code)\n" +"else:\n" +" # everything is fine" +msgstr "" +"from urllib.request import Request, urlopen\n" +"from urllib.error import URLError\n" +"req = Request(someurl)\n" +"try:\n" +" response = urlopen(req)\n" +"except URLError as e:\n" +" if hasattr(e, 'reason'):\n" +" print('We failed to reach a server.')\n" +" print('Reason: ', e.reason)\n" +" elif hasattr(e, 'code'):\n" +" print('The server couldn\\'t fulfill the request.')\n" +" print('Error code: ', e.code)\n" +"else:\n" +" # tudo certo" #: ../../howto/urllib2.rst:392 msgid "info and geturl" -msgstr "" +msgstr "info e geturl" #: ../../howto/urllib2.rst:394 msgid "" @@ -388,6 +856,9 @@ msgid "" "instance) has two useful methods :meth:`!info` and :meth:`!geturl` and is " "defined in the module :mod:`urllib.response`." msgstr "" +"A resposta retornada por urlopen (ou a instância :exc:`~urllib.error." +"HTTPError`) tem dois métodos úteis :meth:`!info` e :meth:`!geturl` e é " +"definida no módulo :mod:`urllib.response`." #: ../../howto/urllib2.rst:398 msgid "" @@ -396,6 +867,10 @@ msgid "" "redirect. The URL of the page fetched may not be the same as the URL " "requested." msgstr "" +"**geturl** - Isso retorna a URL real da página recuperada. Isso é útil " +"porque ``urlopen`` (ou o objeto de abertura utilizado) pode ter seguido um " +"redirecionamento. A URL da página recuperada pode não ser a mesma que a URL " +"solicitada." #: ../../howto/urllib2.rst:402 msgid "" @@ -403,6 +878,9 @@ msgid "" "fetched, particularly the headers sent by the server. It is currently an :" "class:`http.client.HTTPMessage` instance." msgstr "" +"**info** - Isso retorna um objeto semelhante a um dicionário que descreve a " +"página recuperada, particularmente os cabeçalhos enviados pelo servidor. " +"Atualmente, é uma instância de :class:`http.client.HTTPMessage`." #: ../../howto/urllib2.rst:406 msgid "" @@ -411,10 +889,14 @@ msgid "" "useful listing of HTTP headers with brief explanations of their meaning and " "use." msgstr "" +"Cabeçalhos típicos incluem 'Content-length', 'Content-type' e assim por " +"diante. Consulte a \"Referência rápida para cabeçalhos HTTP \" para obter uma lista útil de cabeçalhos HTTP com " +"breves explicações sobre seu significado e uso." #: ../../howto/urllib2.rst:413 msgid "Openers and Handlers" -msgstr "" +msgstr "Abridores e tratadores" #: ../../howto/urllib2.rst:415 msgid "" @@ -426,6 +908,13 @@ msgid "" "(http, ftp, etc.), or how to handle an aspect of URL opening, for example " "HTTP redirections or HTTP cookies." msgstr "" +"Ao buscar uma URL, você usa um abridor (uma instância do talvez confuso " +"nome :class:`urllib.request.OpenerDirector`). Normalmente, usamos o abridor " +"padrão - via ``urlopen`` -, mas você pode criar abridores personalizados. Os " +"abridores usam manipuladores. Todo o \"trabalho pesado\" é feito pelos " +"manipuladores. Cada manipulador sabe como abrir URLs para um esquema de URL " +"específico (http, ftp, etc.) ou como lidar com um aspecto da abertura de " +"URL, por exemplo, redirecionamentos HTTP ou cookies HTTP." #: ../../howto/urllib2.rst:423 msgid "" @@ -433,12 +922,17 @@ msgid "" "handlers installed, for example to get an opener that handles cookies, or to " "get an opener that does not handle redirections." msgstr "" +"Você vai querer criar abridores se quiser buscar URLs com manipuladores " +"específicos instalados, por exemplo, para obter um abridor que manipule " +"cookies ou para obter um abridor que não manipule redirecionamentos." #: ../../howto/urllib2.rst:427 msgid "" "To create an opener, instantiate an ``OpenerDirector``, and then call ``." "add_handler(some_handler_instance)`` repeatedly." msgstr "" +"Para criar um abridor, instancie um ``OpenerDirector`` e então chame ``." +"add_handler(some_handler_instance)`` repetidamente." #: ../../howto/urllib2.rst:430 msgid "" @@ -447,12 +941,18 @@ msgid "" "adds several handlers by default, but provides a quick way to add more and/" "or override the default handlers." msgstr "" +"Como alternativa, você pode usar ``build_opener``, que é uma função " +"conveniente para criar objetos de abertura com uma única chamada de função. " +"``build_opener`` adiciona vários tratadores por padrão, mas fornece uma " +"maneira rápida de adicionar mais e/ou substituir os tratadores padrão." #: ../../howto/urllib2.rst:435 msgid "" "Other sorts of handlers you might want to can handle proxies, " "authentication, and other common but slightly specialised situations." msgstr "" +"Outros tipos de manipuladores que você pode querer podem lidar com proxies, " +"autenticação e outras situações comuns, mas um pouco especializadas." #: ../../howto/urllib2.rst:438 msgid "" @@ -460,6 +960,9 @@ msgid "" "default opener. This means that calls to ``urlopen`` will use the opener you " "have installed." msgstr "" +"``install_opener`` pode ser usado para tornar um objeto ``opener`` o abridor " +"padrão (global). Isso significa que chamadas para ``urlopen`` usarão o " +"abridor que você instalou." #: ../../howto/urllib2.rst:442 msgid "" @@ -467,6 +970,9 @@ msgid "" "fetch urls in the same way as the ``urlopen`` function: there's no need to " "call ``install_opener``, except as a convenience." msgstr "" +"Objetos abridores têm um método ``open``, que pode ser chamado diretamente " +"para buscar URLs da mesma forma que a função ``urlopen``: não há necessidade " +"de chamar ``install_opener``, exceto por conveniência." #: ../../howto/urllib2.rst:448 msgid "Basic Authentication" @@ -493,6 +999,10 @@ msgstr "" msgid "e.g." msgstr "" +#: ../../howto/urllib2.rst:463 +msgid "WWW-Authenticate: Basic realm=\"cPanel Users\"" +msgstr "" + #: ../../howto/urllib2.rst:468 msgid "" "The client should then retry the request with the appropriate name and " @@ -520,6 +1030,29 @@ msgid "" "\"deeper\" than the URL you pass to .add_password() will also match. ::" msgstr "" +#: ../../howto/urllib2.rst:486 +msgid "" +"# create a password manager\n" +"password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()\n" +"\n" +"# Add the username and password.\n" +"# If we knew the realm, we could use it instead of None.\n" +"top_level_url = \"http://example.com/foo/\"\n" +"password_mgr.add_password(None, top_level_url, username, password)\n" +"\n" +"handler = urllib.request.HTTPBasicAuthHandler(password_mgr)\n" +"\n" +"# create \"opener\" (OpenerDirector instance)\n" +"opener = urllib.request.build_opener(handler)\n" +"\n" +"# use the opener to fetch a URL\n" +"opener.open(a_url)\n" +"\n" +"# Install the opener.\n" +"# Now all calls to urllib.request.urlopen use our opener.\n" +"urllib.request.install_opener(opener)" +msgstr "" + #: ../../howto/urllib2.rst:508 msgid "" "In the above example we only supplied our ``HTTPBasicAuthHandler`` to " @@ -555,6 +1088,13 @@ msgid "" "similar steps to setting up a `Basic Authentication`_ handler: ::" msgstr "" +#: ../../howto/urllib2.rst:534 +msgid "" +">>> proxy_support = urllib.request.ProxyHandler({})\n" +">>> opener = urllib.request.build_opener(proxy_support)\n" +">>> urllib.request.install_opener(opener)" +msgstr "" + #: ../../howto/urllib2.rst:540 msgid "" "Currently ``urllib.request`` *does not* support fetching of ``https`` " @@ -588,13 +1128,28 @@ msgid "" "sockets using ::" msgstr "" +#: ../../howto/urllib2.rst:562 +msgid "" +"import socket\n" +"import urllib.request\n" +"\n" +"# timeout in seconds\n" +"timeout = 10\n" +"socket.setdefaulttimeout(timeout)\n" +"\n" +"# this call to urllib.request.urlopen now uses the default timeout\n" +"# we have set in the socket module\n" +"req = urllib.request.Request('http://www.voidspace.org.uk')\n" +"response = urllib.request.urlopen(req)" +msgstr "" + #: ../../howto/urllib2.rst:579 msgid "Footnotes" msgstr "Notas de rodapé" #: ../../howto/urllib2.rst:581 msgid "This document was reviewed and revised by John Lee." -msgstr "" +msgstr "Este documento foi revisado e revisado por John Lee." #: ../../howto/urllib2.rst:583 msgid "Google for example." diff --git a/installing/index.po b/installing/index.po index 5482290bf..296e96034 100644 --- a/installing/index.po +++ b/installing/index.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2021 -# Ruan Aragão , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 00:54+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -202,6 +200,10 @@ msgstr "" "O comando a seguir instalará a versão mais recente de um módulo e suas " "dependências do Python Package Index::" +#: ../../installing/index.rst:84 +msgid "python -m pip install SomePackage" +msgstr "python -m pip install AlgumPacote" + #: ../../installing/index.rst:88 msgid "" "For POSIX users (including macOS and Linux users), the examples in this " @@ -232,6 +234,14 @@ msgstr "" "algum outro caractere especial que é interpretado pelo shell, o nome do " "pacote e a versão devem ser colocados entre aspas duplas::" +#: ../../installing/index.rst:100 +msgid "" +"python -m pip install SomePackage==1.0.4 # specific version\n" +"python -m pip install \"SomePackage>=1.0.4\" # minimum version" +msgstr "" +"python -m pip install AlgumPacote==1.0.4 # versão específica\n" +"python -m pip install \"AlgumPacote>=1.0.4\" # versão mínima" + #: ../../installing/index.rst:103 msgid "" "Normally, if a suitable module is already installed, attempting to install " @@ -242,6 +252,10 @@ msgstr "" "novamente não terá efeito. A atualização de módulos existentes deve ser " "solicitada explicitamente::" +#: ../../installing/index.rst:107 +msgid "python -m pip install --upgrade SomePackage" +msgstr "python -m pip install --upgrade AlgumPacote" + #: ../../installing/index.rst:109 msgid "" "More information and resources regarding ``pip`` and its capabilities can be " @@ -355,6 +369,18 @@ msgstr "" "em combinação com a opção ``-m`` para executar a cópia apropriada de " "``pip`` ::" +#: ../../installing/index.rst:171 +msgid "" +"python2 -m pip install SomePackage # default Python 2\n" +"python2.7 -m pip install SomePackage # specifically Python 2.7\n" +"python3 -m pip install SomePackage # default Python 3\n" +"python3.4 -m pip install SomePackage # specifically Python 3.4" +msgstr "" +"python2 -m pip install AlgumPacote # Python 2 padrão\n" +"python2.7 -m pip install AlgumPacote # Python 2.7 especificamente\n" +"python3 -m pip install AlgumPacote # Python 3 padrão\n" +"python3.4 -m pip install AlgumPacote # Python 3.4 especificamente" + #: ../../installing/index.rst:176 msgid "Appropriately versioned ``pip`` commands may also be available." msgstr "Comandos ``pip`` com versão apropriada também podem estar disponíveis." @@ -366,6 +392,18 @@ msgid "" msgstr "" "No Windows, use o iniciador Python ``py`` em combinação com a opção ``-m``::" +#: ../../installing/index.rst:181 +msgid "" +"py -2 -m pip install SomePackage # default Python 2\n" +"py -2.7 -m pip install SomePackage # specifically Python 2.7\n" +"py -3 -m pip install SomePackage # default Python 3\n" +"py -3.4 -m pip install SomePackage # specifically Python 3.4" +msgstr "" +"py -2 -m pip install AlgumPacote # Python 2 padrão\n" +"py -2.7 -m pip install AlgumPacote # Python 2.7 especificamente\n" +"py -3 -m pip install AlgumPacote # Python 3 padrão\n" +"py -3.4 -m pip install AlgumPacote # Python 3.4 especificamente" + #: ../../installing/index.rst:195 msgid "Common installation issues" msgstr "Problemas comuns de instalação" @@ -408,6 +446,10 @@ msgstr "" "É possível que o ``pip`` não seja instalado por padrão. Uma solução " "potencial é::" +#: ../../installing/index.rst:215 +msgid "python -m ensurepip --default-pip" +msgstr "python -m ensurepip --default-pip" + #: ../../installing/index.rst:217 msgid "" "There are also additional resources for `installing pip. , YEAR. # # Translators: -# Italo Penaforte , 2021 -# Octavio von Sydow , 2021 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 00:54+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -155,7 +152,7 @@ msgstr ":pep:`255`: *Simple Generators*" #: ../../library/__future__.rst:49 msgid "division" -msgstr "division" +msgstr "divisão" #: ../../library/__future__.rst:49 msgid "2.2.0a2" @@ -250,6 +247,14 @@ msgstr ":pep:`563`: *Postponed evaluation of annotations*" msgid "Each statement in :file:`__future__.py` is of the form::" msgstr "Cada instrução em :file:`__future__.py` é da forma::" +#: ../../library/__future__.rst:79 +msgid "" +"FeatureName = _Feature(OptionalRelease, MandatoryRelease,\n" +" CompilerFlag)" +msgstr "" +"FeatureName = _Feature(OptionalRelease, MandatoryRelease,\n" +" CompilerFlag)" + #: ../../library/__future__.rst:82 msgid "" "where, normally, *OptionalRelease* is less than *MandatoryRelease*, and both " @@ -258,6 +263,24 @@ msgstr "" "Onde, normalmente, *OptionalRelease* é inferior a *MandatoryRelease*, e " "ambos são tuplas de 5 entradas da mesma forma que :data:`sys.version_info`::" +#: ../../library/__future__.rst:85 +msgid "" +"(PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int\n" +" PY_MINOR_VERSION, # the 1; an int\n" +" PY_MICRO_VERSION, # the 0; an int\n" +" PY_RELEASE_LEVEL, # \"alpha\", \"beta\", \"candidate\" or \"final\"; " +"string\n" +" PY_RELEASE_SERIAL # the 3; an int\n" +")" +msgstr "" +"(PY_MAJOR_VERSION, # o 2 em 2.1.0a3; um int\n" +" PY_MINOR_VERSION, # o 1; um int\n" +" PY_MICRO_VERSION, # o 0; um int\n" +" PY_RELEASE_LEVEL, # \"alpha\", \"beta\", \"candidate\" ou \"final\"; uma " +"string\n" +" PY_RELEASE_SERIAL # o 3; um int\n" +")" + #: ../../library/__future__.rst:94 msgid "" "*OptionalRelease* records the first release in which the feature was " diff --git a/library/__main__.po b/library/__main__.po index bd0b7434e..c9feb5ceb 100644 --- a/library/__main__.po +++ b/library/__main__.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Henrique Junqueira, 2022 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-05 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 00:54+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -75,6 +73,16 @@ msgstr "" "o nome do módulo. Normalmente, este é o nome do próprio arquivo Python sem a " "extensão ``.py``::" +#: ../../library/__main__.rst:31 +msgid "" +">>> import configparser\n" +">>> configparser.__name__\n" +"'configparser'" +msgstr "" +">>> import configparser\n" +">>> configparser.__name__\n" +"'configparser'" + #: ../../library/__main__.rst:35 msgid "" "If the file is part of a package, ``__name__`` will also include the parent " @@ -83,6 +91,16 @@ msgstr "" "Caso o arquivo seja parte de um pacote, ``__name__`` também incluirá o nome " "da pasta raiz do pacote." +#: ../../library/__main__.rst:38 +msgid "" +">>> from concurrent.futures import process\n" +">>> process.__name__\n" +"'concurrent.futures.process'" +msgstr "" +">>> from concurrent.futures import process\n" +">>> process.__name__\n" +"'concurrent.futures.process'" + #: ../../library/__main__.rst:42 msgid "" "However, if the module is executed in the top-level code environment, its " @@ -117,12 +135,28 @@ msgstr "O ambiente de código principal pode ser:" msgid "the scope of an interactive prompt::" msgstr "o escopo de um prompt de comando interativo:" +#: ../../library/__main__.rst:57 +msgid "" +">>> __name__\n" +"'__main__'" +msgstr "" +">>> __name__\n" +"'__main__'" + #: ../../library/__main__.rst:60 msgid "the Python module passed to the Python interpreter as a file argument:" msgstr "" "o módulo Python passado ao interpretador do Python como um argumento " "correspondente ao nome do arquivo:" +#: ../../library/__main__.rst:62 +msgid "" +"$ python helloworld.py\n" +"Hello, world!" +msgstr "" +"$ python helloworld.py\n" +"Hello, world!" + #: ../../library/__main__.rst:67 msgid "" "the Python module or package passed to the Python interpreter with the :" @@ -131,12 +165,36 @@ msgstr "" "o módulo ou pacote Python passado ao interpretador do Python com o " "argumento :option:`-m`:" +#: ../../library/__main__.rst:70 +msgid "" +"$ python -m tarfile\n" +"usage: tarfile.py [-h] [-v] (...)" +msgstr "" +"$ python -m tarfile\n" +"usage: tarfile.py [-h] [-v] (...)" + #: ../../library/__main__.rst:75 msgid "Python code read by the Python interpreter from standard input:" msgstr "" "código Python lido pelo interpretador através da entrada padrão de linha de " "comando:" +#: ../../library/__main__.rst:77 +msgid "" +"$ echo \"import this\" | python\n" +"The Zen of Python, by Tim Peters\n" +"\n" +"Beautiful is better than ugly.\n" +"Explicit is better than implicit.\n" +"..." +msgstr "" +"$ echo \"import this\" | python\n" +"The Zen of Python, by Tim Peters\n" +"\n" +"Beautiful is better than ugly.\n" +"Explicit is better than implicit.\n" +"..." + #: ../../library/__main__.rst:86 msgid "" "Python code passed to the Python interpreter with the :option:`-c` argument:" @@ -144,6 +202,22 @@ msgstr "" "código Python passado ao interpretador do Python com o argumento :option:`-" "c`:" +#: ../../library/__main__.rst:88 +msgid "" +"$ python -c \"import this\"\n" +"The Zen of Python, by Tim Peters\n" +"\n" +"Beautiful is better than ugly.\n" +"Explicit is better than implicit.\n" +"..." +msgstr "" +"$ python -c \"import this\"\n" +"The Zen of Python, by Tim Peters\n" +"\n" +"Beautiful is better than ugly.\n" +"Explicit is better than implicit.\n" +"..." + #: ../../library/__main__.rst:97 msgid "" "In each of these situations, the top-level module's ``__name__`` is set to " @@ -164,6 +238,17 @@ msgstr "" "termo comum para executar código condicionalmente quando o módulo não é " "inicializado a partir de uma instrução de importação::" +#: ../../library/__main__.rst:105 +msgid "" +"if __name__ == '__main__':\n" +" # Execute when the module is not initialized from an import statement.\n" +" ..." +msgstr "" +"if __name__ == '__main__':\n" +" # Executa quando o módulo não é inicializado por uma instrução de " +"importação.\n" +" ..." + #: ../../library/__main__.rst:111 msgid "" "For a more detailed look at how ``__name__`` is set in all situations, see " @@ -210,6 +295,48 @@ msgstr "" "vezes, uma função chamada de ``main`` encapsula o comportamento principal do " "programa::" +#: ../../library/__main__.rst:131 +msgid "" +"# echo.py\n" +"\n" +"import shlex\n" +"import sys\n" +"\n" +"def echo(phrase: str) -> None:\n" +" \"\"\"A dummy wrapper around print.\"\"\"\n" +" # for demonstration purposes, you can imagine that there is some\n" +" # valuable and reusable logic inside this function\n" +" print(phrase)\n" +"\n" +"def main() -> int:\n" +" \"\"\"Echo the input arguments to standard output\"\"\"\n" +" phrase = shlex.join(sys.argv)\n" +" echo(phrase)\n" +" return 0\n" +"\n" +"if __name__ == '__main__':\n" +" sys.exit(main()) # next section explains the use of sys.exit" +msgstr "" +"# echo.py\n" +"\n" +"import shlex\n" +"import sys\n" +"\n" +"def echo(phrase: str) -> None:\n" +" \"\"\"Um invólucro fictício sobre print.\"\"\"\n" +" # com propósito de demonstração, imagine que existe\n" +" # uma lógica reutilizável valiosa nesta função\n" +" print(phrase)\n" +"\n" +"def main() -> int:\n" +" \"\"\"Ecoa os argumentos de entrada para a saída padrão.\"\"\"\n" +" phrase = shlex.join(sys.argv)\n" +" echo(phrase)\n" +" return 0\n" +"\n" +"if __name__ == '__main__':\n" +" sys.exit(main()) # a próxima seção explica o uso de sys.exit" + #: ../../library/__main__.rst:151 msgid "" "Note that if the module didn't encapsulate code inside the ``main`` function " @@ -249,12 +376,16 @@ msgid "" "pip.pypa.io/>`_ inserts the function call into a template script, where the " "return value of ``main`` is passed into :func:`sys.exit`. For example::" msgstr "" -"``main`` são funções frequentemente usadas ​​para criar ferramentas de linha " +"``main`` são funções frequentemente usadas para criar ferramentas de linha " "de comando especificando-as como pontos de entrada para scripts de console. " "Quando isto é feito, `pip `_ insere a chamada da " "função em um modelo de script, onde o valor de retorno de ``main`` é passado " "para :func:`sys.exit`. Por exemplo::" +#: ../../library/__main__.rst:173 +msgid "sys.exit(main())" +msgstr "sys.exit(main())" + #: ../../library/__main__.rst:175 msgid "" "Since the call to ``main`` is wrapped in :func:`sys.exit`, the expectation " @@ -320,6 +451,18 @@ msgstr "" "para fornecer uma interface de linha de comando para um pacote. Considere o " "seguinte pacote hipotético, \"bandclass\":" +#: ../../library/__main__.rst:206 +msgid "" +"bandclass\n" +" ├── __init__.py\n" +" ├── __main__.py\n" +" └── student.py" +msgstr "" +"bandclass\n" +" ├── __init__.py\n" +" ├── __main__.py\n" +" └── student.py" + #: ../../library/__main__.rst:213 msgid "" "``__main__.py`` will be executed when the package itself is invoked directly " @@ -329,6 +472,10 @@ msgstr "" "diretamente da linha de comando usando o sinalizador :option:`-m`. Por " "exemplo:" +#: ../../library/__main__.rst:216 +msgid "$ python -m bandclass" +msgstr "$ python -m bandclass" + #: ../../library/__main__.rst:220 msgid "" "This command will cause ``__main__.py`` to run. How you utilize this " @@ -341,6 +488,24 @@ msgstr "" "neste caso hipotético, pode fazer sentido permitir que o professor procure " "alunos::" +#: ../../library/__main__.rst:225 +msgid "" +"# bandclass/__main__.py\n" +"\n" +"import sys\n" +"from .student import search_students\n" +"\n" +"student_name = sys.argv[1] if len(sys.argv) >= 2 else ''\n" +"print(f'Found student: {search_students(student_name)}')" +msgstr "" +"# bandclass/__main__.py\n" +"\n" +"import sys\n" +"from .student import search_students\n" +"\n" +"student_name = sys.argv[1] if len(sys.argv) >= 2 else ''\n" +"print(f'Estudante encontrado(a): {search_students(student_name)}')" + #: ../../library/__main__.rst:233 msgid "" "Note that ``from .student import search_students`` is an example of a " @@ -376,6 +541,16 @@ msgstr "" "como esperado para o arquivo ``__main__.py`` dentro de um pacote, pois seu " "atributo ``__name__`` incluirá o caminho do pacote se importado::" +#: ../../library/__main__.rst:250 +msgid "" +">>> import asyncio.__main__\n" +">>> asyncio.__main__.__name__\n" +"'asyncio.__main__'" +msgstr "" +">>> import asyncio.__main__\n" +">>> asyncio.__main__.__name__\n" +"'asyncio.__main__'" + #: ../../library/__main__.rst:254 msgid "" "This won't work for ``__main__.py`` files in the root directory of a ``." @@ -437,14 +612,93 @@ msgid "Here is an example module that consumes the ``__main__`` namespace::" msgstr "" "Aqui está um módulo de exemplo que consome o espaço de nomes ``__main__``::" +#: ../../library/__main__.rst:284 +msgid "" +"# namely.py\n" +"\n" +"import __main__\n" +"\n" +"def did_user_define_their_name():\n" +" return 'my_name' in dir(__main__)\n" +"\n" +"def print_user_name():\n" +" if not did_user_define_their_name():\n" +" raise ValueError('Define the variable `my_name`!')\n" +"\n" +" if '__file__' in dir(__main__):\n" +" print(__main__.my_name, \"found in file\", __main__.__file__)\n" +" else:\n" +" print(__main__.my_name)" +msgstr "" +"# namely.py\n" +"\n" +"import __main__\n" +"\n" +"def did_user_define_their_name():\n" +" return 'my_name' in dir(__main__)\n" +"\n" +"def print_user_name():\n" +" if not did_user_define_their_name():\n" +" raise ValueError('Defina a variável `my_name`!')\n" +"\n" +" if '__file__' in dir(__main__):\n" +" print(__main__.my_name, \"encontrado no arquivo\", __main__." +"__file__)\n" +" else:\n" +" print(__main__.my_name)" + #: ../../library/__main__.rst:300 msgid "Example usage of this module could be as follows::" msgstr "Exemplo de uso deste módulo pode ser como abaixo::" +#: ../../library/__main__.rst:302 +msgid "" +"# start.py\n" +"\n" +"import sys\n" +"\n" +"from namely import print_user_name\n" +"\n" +"# my_name = \"Dinsdale\"\n" +"\n" +"def main():\n" +" try:\n" +" print_user_name()\n" +" except ValueError as ve:\n" +" return str(ve)\n" +"\n" +"if __name__ == \"__main__\":\n" +" sys.exit(main())" +msgstr "" +"# start.py\n" +"\n" +"import sys\n" +"\n" +"from namely import print_user_name\n" +"\n" +"# my_name = \"Dinsdale\"\n" +"\n" +"def main():\n" +" try:\n" +" print_user_name()\n" +" except ValueError as ve:\n" +" return str(ve)\n" +"\n" +"if __name__ == \"__main__\":\n" +" sys.exit(main())" + #: ../../library/__main__.rst:319 msgid "Now, if we started our program, the result would look like this:" msgstr "Agora, se iniciarmos nosso programa, o resultado seria assim:" +#: ../../library/__main__.rst:321 +msgid "" +"$ python start.py\n" +"Define the variable `my_name`!" +msgstr "" +"$ python start.py\n" +"Defina a variável `my_name`!" + #: ../../library/__main__.rst:326 msgid "" "The exit code of the program would be 1, indicating an error. Uncommenting " @@ -455,6 +709,14 @@ msgstr "" "linha com ``my_name = \"Dinsdale\"`` corrige o programa e agora ele sai com " "o código de status 0, indicando sucesso:" +#: ../../library/__main__.rst:330 +msgid "" +"$ python start.py\n" +"Dinsdale found in file /path/to/start.py" +msgstr "" +"$ python start.py\n" +"Dinsdale encontrado no arquivo /path/to/start.py" + #: ../../library/__main__.rst:335 msgid "" "Note that importing ``__main__`` doesn't cause any issues with " @@ -497,6 +759,34 @@ msgstr "" "O REPL do Python é outro exemplo de um \"ambiente principal\", então " "qualquer coisa definida no REPL se torna parte do escopo do ``__main__``::" +#: ../../library/__main__.rst:351 +msgid "" +">>> import namely\n" +">>> namely.did_user_define_their_name()\n" +"False\n" +">>> namely.print_user_name()\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: Define the variable `my_name`!\n" +">>> my_name = 'Jabberwocky'\n" +">>> namely.did_user_define_their_name()\n" +"True\n" +">>> namely.print_user_name()\n" +"Jabberwocky" +msgstr "" +">>> import namely\n" +">>> namely.did_user_define_their_name()\n" +"False\n" +">>> namely.print_user_name()\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: Defina a variável `my_name`!\n" +">>> my_name = 'Jabberwocky'\n" +">>> namely.did_user_define_their_name()\n" +"True\n" +">>> namely.print_user_name()\n" +"Jabberwocky" + #: ../../library/__main__.rst:364 msgid "" "Note that in this case the ``__main__`` scope doesn't contain a ``__file__`` " diff --git a/library/_thread.po b/library/_thread.po index d1d12ce3d..402db39a7 100644 --- a/library/_thread.po +++ b/library/_thread.po @@ -1,34 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Sheila Gomes , 2021 -# Jose Rafael Amaral , 2021 -# Octavio von Sydow , 2021 -# Marcos Jurach , 2021 -# Fabio Aragao , 2021 -# Loyanne Cristine , 2022 -# Marco Rougeth , 2023 -# Vitor Buxbaum Orlandi, 2023 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 00:54+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -67,7 +58,7 @@ msgstr "Gerado em erros específicos de segmento." #: ../../library/_thread.rst:35 msgid "This is now a synonym of the built-in :exc:`RuntimeError`." -msgstr "Este é agora um sinônimo do componente embutido :exc:`RuntimeError`." +msgstr "Agora este é um sinônimo da exceção embutida :exc:`RuntimeError`." #: ../../library/_thread.rst:41 msgid "This is the type of lock objects." @@ -79,14 +70,14 @@ msgid "" "function *function* with the argument list *args* (which must be a tuple). " "The optional *kwargs* argument specifies a dictionary of keyword arguments." msgstr "" -"Começa um novo tópico e retorna seu identificador. O tópico executa a função " -"*function* com a lista de argumentos *args* (que deve ser uma tupla). O " -"argumento opcional *kwargs* despecifica um dicionário de argumentos palavras-" -"chave" +"Começa uma nova thread e retorna seu identificador. A thread executa a " +"função *function* com a lista de argumentos *args* (que deve ser uma tupla). " +"O argumento opcional *kwargs* especifica um dicionário de argumentos " +"nomeados." #: ../../library/_thread.rst:50 msgid "When the function returns, the thread silently exits." -msgstr "Quando a função retorna, o tópico fecha silenciosamente." +msgstr "Quando a função retorna, a thread termina silenciosamente." #: ../../library/_thread.rst:52 msgid "" @@ -98,8 +89,8 @@ msgstr "" "Quando a função termina com uma exceção não processada, :func:`sys." "unraisablehook` é chamada para lidar com a exceção. O atributo *object* do " "argumento do hook é *function*. Por padrão, um stack trace (situação da " -"pilha de execução) é impresso e, em seguida, o thread sai (mas outros " -"threads continuam a ser executados)." +"pilha de execução) é exibido e, em seguida, a thread termina (mas outras " +"threads continuam a ser executadas)." #: ../../library/_thread.rst:57 msgid "" @@ -118,7 +109,7 @@ msgstr "" #: ../../library/_thread.rst:62 msgid ":func:`sys.unraisablehook` is now used to handle unhandled exceptions." msgstr "" -":func:`sys.unraisablehook` agora é usada para lidar com exceções não lidadas." +":func:`sys.unraisablehook` agora é usada para tratar exceções não tratadas." #: ../../library/_thread.rst:68 msgid "" @@ -126,7 +117,7 @@ msgid "" "use this function to interrupt the main thread, though there is no guarantee " "that the interruption will happen immediately." msgstr "" -"Simule o efeito de um sinal chegando na thread principal. Uma thread pode " +"Simula o efeito de um sinal chegando na thread principal. Uma thread pode " "usar esta função para interromper a thread principal, embora não haja " "garantia de que a interrupção ocorrerá imediatamente." @@ -143,8 +134,8 @@ msgid "" "If the given signal isn't handled by Python (it was set to :const:`signal." "SIG_DFL` or :const:`signal.SIG_IGN`), this function does nothing." msgstr "" -"Se o sinal fornecido não for tratado por Python (foi definido como :const:" -"`signal.SIG_DFL` ou :const:`signal.SIG_IGN`), esta função não faz nada." +"Se o sinal fornecido não for tratado pelo Python (o sinal foi definido como :" +"const:`signal.SIG_DFL` ou :const:`signal.SIG_IGN`), esta função faz nada." #: ../../library/_thread.rst:79 msgid "The *signum* argument is added to customize the signal number." @@ -165,8 +156,8 @@ msgid "" "Raise the :exc:`SystemExit` exception. When not caught, this will cause the " "thread to exit silently." msgstr "" -"Levanta a exceção :exc:`SystemExit`. Quando não for detectada, o thread " -"sairá silenciosamente." +"Levanta a exceção :exc:`SystemExit`. Quando não for detectada, a thread " +"terminará silenciosamente." #: ../../library/_thread.rst:104 msgid "" @@ -203,13 +194,9 @@ msgstr "" "a thread termine, após o que o valor poderá ser reciclado pelo sistema " "operacional)." -#: ../../library/_thread.rst:123 -msgid "" -":ref:`Availability `: Windows, FreeBSD, Linux, macOS, OpenBSD, " -"NetBSD, AIX, DragonFlyBSD, GNU/kFreeBSD." -msgstr "" -":ref:`Disponibilidade `: Windows, FreeBSD, Linux, macOS, " -"OpenBSD, NetBSD, AIX, DragonFlyBSD, GNU/kFreeBSD." +#: ../../library/_thread.rst:123 ../../library/_thread.rst:148 +msgid "Availability" +msgstr "Disponibilidade" #: ../../library/_thread.rst:127 msgid "Added support for GNU/kFreeBSD." @@ -250,10 +237,6 @@ msgstr "" "múltiplos de 4096 para o tamanho da pilha é a abordagem sugerida na ausência " "de informações mais específicas)." -#: ../../library/_thread.rst:148 -msgid ":ref:`Availability `: Windows, pthreads." -msgstr ":ref:`Disponibilidade `: Windows, pthreads." - #: ../../library/_thread.rst:150 msgid "Unix platforms with POSIX threads support." msgstr "Plataformas Unix com suporte a threads POSIX." @@ -281,8 +264,8 @@ msgid "" msgstr "" "Sem nenhum argumento opcional, esse método adquire a trava " "incondicionalmente, se necessário, aguardando até que seja liberada por " -"outro encadeamento (apenas um encadeamento por vez pode adquirir uma trava " -"--- esse é o motivo da sua existência)." +"outra thread (apenas uma thread por vez pode adquirir uma trava --- esse é o " +"motivo da sua existência)." #: ../../library/_thread.rst:171 msgid "" @@ -349,22 +332,35 @@ msgstr "" "Além desses métodos, os objetos de trava também podem ser usados através da " "instrução :keyword:`with`, por exemplo::" +#: ../../library/_thread.rst:205 +msgid "" +"import _thread\n" +"\n" +"a_lock = _thread.allocate_lock()\n" +"\n" +"with a_lock:\n" +" print(\"a_lock is locked while this executes\")" +msgstr "" +"import _thread\n" +"\n" +"uma_trava = _thread.allocate_lock()\n" +"\n" +"with uma_trava:\n" +" print(\"uma_trava está travada enquanto isto executa\")" + #: ../../library/_thread.rst:212 msgid "**Caveats:**" msgstr "**Ressalvas:**" #: ../../library/_thread.rst:216 msgid "" -"Threads interact strangely with interrupts: the :exc:`KeyboardInterrupt` " -"exception will be received by an arbitrary thread. (When the :mod:`signal` " -"module is available, interrupts always go to the main thread.)" +"Interrupts always go to the main thread (the :exc:`KeyboardInterrupt` " +"exception will be received by that thread.)" msgstr "" -"Threads interagem estranhamente com interrupções: a exceção :exc:" -"`KeyboardInterrupt` será recebida por uma thread arbitrário. (Quando o " -"módulo :mod:`signal` está disponível, as interrupções sempre vão para a " -"thread principal.)" +"Interrupções sempre vão para a thread principal (a exceção :exc:" +"`KeyboardInterrupt` será recebida por essa thread)." -#: ../../library/_thread.rst:220 +#: ../../library/_thread.rst:219 msgid "" "Calling :func:`sys.exit` or raising the :exc:`SystemExit` exception is " "equivalent to calling :func:`_thread.exit`." @@ -372,36 +368,30 @@ msgstr "" "Chamar :func:`sys.exit` ou levantar a exceção :exc:`SystemExit` é o " "equivalente a chamar :func:`_thread.exit`." -#: ../../library/_thread.rst:223 +#: ../../library/_thread.rst:222 msgid "" -"It is not possible to interrupt the :meth:`~threading.Lock.acquire` method " -"on a lock --- the :exc:`KeyboardInterrupt` exception will happen after the " -"lock has been acquired." +"It is platform-dependent whether the :meth:`~threading.Lock.acquire` method " +"on a lock can be interrupted (so that the :exc:`KeyboardInterrupt` exception " +"will happen immediately, rather than only after the lock has been acquired " +"or the operation has timed out). It can be interrupted on POSIX, but not on " +"Windows." msgstr "" -"Não é possível interromper o método :meth:`~threading.Lock.acquire` em uma " -"trava --- a exceção :exc:`KeyboardInterrupt` ocorrerá após a trava ter sido " -"adquirida." +"O método :meth:`~threading.Lock.acquire` de uma trava ser interrompido " +"depende da plataforma (de modo que a exceção :exc:`KeyboardInterrupt` " +"acontecerá imediatamente, em vez de quando a trava for travada, ou quando a " +"operação ultrapassar o tempo limite). O método pode ser interrompido em " +"POSIX, mas não em Windows." -#: ../../library/_thread.rst:227 +#: ../../library/_thread.rst:228 msgid "" "When the main thread exits, it is system defined whether the other threads " "survive. On most systems, they are killed without executing :keyword:" "`try` ... :keyword:`finally` clauses or executing object destructors." msgstr "" -"Quando a thread principal se encerra, é definido pelo sistema se as outras " -"threads sobrevivem. Na maioria dos sistemas, elas são eliminadas sem " -"executar cláusulas :keyword:`try` ... :keyword:`finally` ou executar " -"destruidores de objetos." - -#: ../../library/_thread.rst:232 -msgid "" -"When the main thread exits, it does not do any of its usual cleanup (except " -"that :keyword:`try` ... :keyword:`finally` clauses are honored), and the " -"standard I/O files are not flushed." -msgstr "" -"Quando a thread principal é encerrada, ela não realiza nenhuma limpeza usual " -"(exceto que as cláusulas :keyword:`try` ... :keyword:`finally` são honradas) " -"e os arquivos de E/S padrão não são liberados." +"Quando a thread principal se encerra, o fato de outras threads sobreviverem " +"depende do sistema. Na maioria dos sistemas, elas são eliminadas sem " +"executar cláusulas :keyword:`try` ... :keyword:`finally` ou destruidores de " +"objetos." #: ../../library/_thread.rst:7 msgid "light-weight processes" diff --git a/library/abc.po b/library/abc.po index 5593beeee..a14d6e6d5 100644 --- a/library/abc.po +++ b/library/abc.po @@ -1,34 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Bonifacio de Oliveira , 2021 -# Lilian Corrêa , 2021 -# Alexsandro Felix , 2021 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:54+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-02-28 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/abc.rst:2 msgid ":mod:`!abc` --- Abstract Base Classes" -msgstr "" +msgstr ":mod:`!abc` --- Classes base abstratas" #: ../../library/abc.rst:11 msgid "**Source code:** :source:`Lib/abc.py`" @@ -42,11 +39,10 @@ msgid "" "mod:`numbers` module regarding a type hierarchy for numbers based on ABCs.)" msgstr "" "Este módulo fornece a infraestrutura para definir :term:`classes base " -"abstratas ` (CBAs. Sigla em inglês ABC, de abstract " -"base class) em Python, como delineado em :pep:`3119`; veja o PEP para " -"entender o porquê isto foi adicionado ao Python. (Veja também :pep:`3141` e " -"o módulo :mod:`numbers` sobre uma hierarquia de tipo para números baseado " -"nas CBAs.)" +"abstratas ` (ABCs, do inglês *abstract base class*) em " +"Python, como delineado em :pep:`3119`; veja o PEP para entender o porquê " +"isto foi adicionado ao Python. (Veja também :pep:`3141` e o módulo :mod:" +"`numbers` sobre uma hierarquia de tipo para números baseado nas ABCs.)" #: ../../library/abc.rst:20 msgid "" @@ -56,14 +52,19 @@ msgid "" "class or instance provides a particular interface, for example, if it is :" "term:`hashable` or if it is a :term:`mapping`." msgstr "" +"O módulo :mod:`collections` tem algumas classes concretas que derivam de " +"ABCs; essas podem, evidentemente, ser ainda mais derivadas. Além disso, o " +"submódulo :mod:`collections.abc` tem algumas ABCs que podem ser usadas para " +"testar se uma classe ou instância oferece uma interface particular, por " +"exemplo, se é :term:`hasheável` ou se é um :term:`mapeamento`." #: ../../library/abc.rst:27 msgid "" "This module provides the metaclass :class:`ABCMeta` for defining ABCs and a " "helper class :class:`ABC` to alternatively define ABCs through inheritance:" msgstr "" -"Este módulo fornece a metaclasse :class:`ABCMeta` para definir CBAs e uma " -"classe auxiliar :class:`ABC` para alternativamente definir CBAs através de " +"Este módulo fornece a metaclasse :class:`ABCMeta` para definir ABCs e uma " +"classe auxiliar :class:`ABC` para alternativamente definir ABCs através de " "herança:" #: ../../library/abc.rst:32 @@ -72,6 +73,21 @@ msgid "" "an abstract base class can be created by simply deriving from :class:`!ABC` " "avoiding sometimes confusing metaclass usage, for example::" msgstr "" +"Uma classe auxiliar que tem :class:`ABCMeta` como sua metaclasse. Com essa " +"classe, uma classe base abstrata pode ser criada simplesmente derivando da :" +"class:`!ABC` evitando às vezes confundir o uso da metaclasse, por exemplo::" + +#: ../../library/abc.rst:36 +msgid "" +"from abc import ABC\n" +"\n" +"class MyABC(ABC):\n" +" pass" +msgstr "" +"from abc import ABC\n" +"\n" +"class MyABC(ABC):\n" +" pass" #: ../../library/abc.rst:41 msgid "" @@ -81,10 +97,27 @@ msgid "" "One may also define an abstract base class by passing the metaclass keyword " "and using :class:`!ABCMeta` directly, for example::" msgstr "" +"Note que o tipo da classe :class:`!ABC` ainda é :class:`ABCMeta`, portanto " +"herdar da :class:`!ABC` requer as precauções usuais a respeito do uso da " +"metaclasse, pois herança múltipla pode levar a conflitos de metaclasse. Pode-" +"se também definir uma classe base abstrata ao passar a palavra reservada " +"metaclasse e usar :class:`!ABCMeta` diretamente, por exemplo::" + +#: ../../library/abc.rst:47 +msgid "" +"from abc import ABCMeta\n" +"\n" +"class MyABC(metaclass=ABCMeta):\n" +" pass" +msgstr "" +"from abc import ABCMeta\n" +"\n" +"class MyABC(metaclass=ABCMeta):\n" +" pass" #: ../../library/abc.rst:57 msgid "Metaclass for defining Abstract Base Classes (ABCs)." -msgstr "Metaclasse para definir Classe Base Abstrata (CBAs)." +msgstr "Metaclasse para definir Classe Base Abstrata (ABCs)." #: ../../library/abc.rst:59 msgid "" @@ -97,26 +130,49 @@ msgid "" "will method implementations defined by the registering ABC be callable (not " "even via :func:`super`). [#]_" msgstr "" -"Use esta metaclasse para criar uma CBA. Uma CBA pode ser diretamente " -"subclasseada, e então agir como uma classe misturada. Você também pode " +"Use esta metaclasse para criar uma ABC. Uma ABC pode ser diretamente " +"estendida, e então agir como uma classe misturada. Você também pode " "registrar classes concretas não relacionadas (até mesmo classes embutidas) e " -"CBAs não relacionadas como \"subclasses virtuais\" -- estas e suas " -"descendentes serão consideradas subclasses da CBA de registro pela função " -"embutida :func:`issubclass`, mas a CBA de registro não irá aparecer na ORM " +"ABCs não relacionadas como \"subclasses virtuais\" -- estas e suas " +"descendentes serão consideradas subclasses da ABC de registro pela função " +"embutida :func:`issubclass`, mas a ABC de registro não irá aparecer na MRO " "(Ordem de Resolução do Método) e nem as implementações do método definidas " -"pela CBA de registro será chamável (nem mesmo via :func:`super`). [#]_" +"pela ABC de registro será chamável (nem mesmo via :func:`super`). [#]_" #: ../../library/abc.rst:68 msgid "" "Classes created with a metaclass of :class:`!ABCMeta` have the following " "method:" msgstr "" +"Classes criadas com a metaclasse de :class:`!ABCMeta` tem o seguinte método:" #: ../../library/abc.rst:72 msgid "" "Register *subclass* as a \"virtual subclass\" of this ABC. For example::" msgstr "" -"Registrar *subclasse* como uma \"subclasse virtual\" desta CBA. Por exemplo::" +"Registra *subclass* como uma \"subclasse virtual\" desta ABC. Por exemplo::" + +#: ../../library/abc.rst:75 +msgid "" +"from abc import ABC\n" +"\n" +"class MyABC(ABC):\n" +" pass\n" +"\n" +"MyABC.register(tuple)\n" +"\n" +"assert issubclass(tuple, MyABC)\n" +"assert isinstance((), MyABC)" +msgstr "" +"from abc import ABC\n" +"\n" +"class MyABC(ABC):\n" +" pass\n" +"\n" +"MyABC.register(tuple)\n" +"\n" +"assert issubclass(tuple, MyABC)\n" +"assert isinstance((), MyABC)" #: ../../library/abc.rst:85 msgid "Returns the registered subclass, to allow usage as a class decorator." @@ -129,6 +185,8 @@ msgid "" "To detect calls to :meth:`!register`, you can use the :func:" "`get_cache_token` function." msgstr "" +"Para detectar chamadas para :meth:`!register`, você pode usar a função :func:" +"`get_cache_token`." #: ../../library/abc.rst:92 msgid "You can also override this method in an abstract base class:" @@ -143,9 +201,14 @@ msgid "" "Check whether *subclass* is considered a subclass of this ABC. This means " "that you can customize the behavior of :func:`issubclass` further without " "the need to call :meth:`register` on every class you want to consider a " -"subclass of the ABC. (This class method is called from the :meth:`~class." +"subclass of the ABC. (This class method is called from the :meth:`~type." "__subclasscheck__` method of the ABC.)" msgstr "" +"Verifica se *subclass* é considerada uma subclasse desta ABC. Isto significa " +"que você pode personalizar ainda mais o comportamento de :func:`issubclass` " +"sem a necessidade de chamar :meth:`register` em toda classe que você queira " +"considerar uma subclasse da ABC. (Este método de classe é chamado do método :" +"meth:`~type.__subclasscheck__` da ABC.)" #: ../../library/abc.rst:104 msgid "" @@ -155,47 +218,119 @@ msgid "" "ABC, even if it would normally be one. If it returns :data:`!" "NotImplemented`, the subclass check is continued with the usual mechanism." msgstr "" +"Este método deve retornar ``True``, ``False`` ou :data:`NotImplemented`. Se " +"retornar ``True``, *subclass* é considerada uma subclasse desta ABC. Se " +"retornar ``False``, *subclass* não é considerada uma subclasse desta ABC, " +"mesmo que normalmente seria uma. Se retornar :data:`!NotImplemented`, a " +"verificação da subclasse é continuada com o mecanismo usual." #: ../../library/abc.rst:114 msgid "" "For a demonstration of these concepts, look at this example ABC definition::" msgstr "" -"Para uma demonstração destes conceitos, veja este exemplo de definição CBA::" +"Para uma demonstração destes conceitos, veja este exemplo de definição ABC::" + +#: ../../library/abc.rst:116 +msgid "" +"class Foo:\n" +" def __getitem__(self, index):\n" +" ...\n" +" def __len__(self):\n" +" ...\n" +" def get_iterator(self):\n" +" return iter(self)\n" +"\n" +"class MyIterable(ABC):\n" +"\n" +" @abstractmethod\n" +" def __iter__(self):\n" +" while False:\n" +" yield None\n" +"\n" +" def get_iterator(self):\n" +" return self.__iter__()\n" +"\n" +" @classmethod\n" +" def __subclasshook__(cls, C):\n" +" if cls is MyIterable:\n" +" if any(\"__iter__\" in B.__dict__ for B in C.__mro__):\n" +" return True\n" +" return NotImplemented\n" +"\n" +"MyIterable.register(Foo)" +msgstr "" +"class Foo:\n" +" def __getitem__(self, index):\n" +" ...\n" +" def __len__(self):\n" +" ...\n" +" def get_iterator(self):\n" +" return iter(self)\n" +"\n" +"class MyIterable(ABC):\n" +"\n" +" @abstractmethod\n" +" def __iter__(self):\n" +" while False:\n" +" yield None\n" +"\n" +" def get_iterator(self):\n" +" return self.__iter__()\n" +"\n" +" @classmethod\n" +" def __subclasshook__(cls, C):\n" +" if cls is MyIterable:\n" +" if any(\"__iter__\" in B.__dict__ for B in C.__mro__):\n" +" return True\n" +" return NotImplemented\n" +"\n" +"MyIterable.register(Foo)" #: ../../library/abc.rst:143 msgid "" -"The ABC ``MyIterable`` defines the standard iterable method, :meth:" -"`~iterator.__iter__`, as an abstract method. The implementation given here " -"can still be called from subclasses. The :meth:`!get_iterator` method is " -"also part of the ``MyIterable`` abstract base class, but it does not have to " -"be overridden in non-abstract derived classes." +"The ABC ``MyIterable`` defines the standard iterable method, :meth:`~object." +"__iter__`, as an abstract method. The implementation given here can still " +"be called from subclasses. The :meth:`!get_iterator` method is also part of " +"the ``MyIterable`` abstract base class, but it does not have to be " +"overridden in non-abstract derived classes." msgstr "" +"A ``MyIterable`` da ABC define o método iterável padrão, :meth:`~object." +"__iter__`, como um método abstrato. A implementação dada aqui pode ainda ser " +"chamada da subclasse. O método :meth:`!get_iterator` é também parte da " +"classe base abstrata ``MyIterable``, mas não precisa ser substituído nas " +"classes derivadas não abstratas." #: ../../library/abc.rst:149 msgid "" "The :meth:`__subclasshook__` class method defined here says that any class " -"that has an :meth:`~iterator.__iter__` method in its :attr:`~object." -"__dict__` (or in that of one of its base classes, accessed via the :attr:" -"`~class.__mro__` list) is considered a ``MyIterable`` too." +"that has an :meth:`~object.__iter__` method in its :attr:`~object.__dict__` " +"(or in that of one of its base classes, accessed via the :attr:`~type." +"__mro__` list) is considered a ``MyIterable`` too." msgstr "" "O método de classe :meth:`__subclasshook__` definido aqui diz que qualquer " -"classe que tenha um método :meth:`~iterador.__iter__` em seu :attr:`~objeto." +"classe que tenha um método :meth:`~object.__iter__` em seu :attr:`~object." "__dict__` (ou no de uma de suas classes base, acessados via lista :attr:" -"`~classe.__mro__`) é considerada uma ``MyIterable`` também." +"`~type.__mro__`) é considerada uma ``MyIterable`` também." #: ../../library/abc.rst:154 msgid "" "Finally, the last line makes ``Foo`` a virtual subclass of ``MyIterable``, " -"even though it does not define an :meth:`~iterator.__iter__` method (it uses " +"even though it does not define an :meth:`~object.__iter__` method (it uses " "the old-style iterable protocol, defined in terms of :meth:`~object.__len__` " "and :meth:`~object.__getitem__`). Note that this will not make " "``get_iterator`` available as a method of ``Foo``, so it is provided " "separately." msgstr "" +"Finalmente, a última linha faz de ``Foo`` uma subclasse virtual da " +"``MyIterable``, apesar de não definir um método :meth:`~object.__iter__` " +"(ela usa o protocolo iterável antigo, definido em termos de :meth:`~object." +"__len__` e :meth:`~object.__getitem__`). Note que isto não fará o " +"``get_iterator`` disponível como um método de ``Foo``, então ele é fornecido " +"separadamente." #: ../../library/abc.rst:163 msgid "The :mod:`!abc` module also provides the following decorator:" -msgstr "" +msgstr "O módulo :mod:`!abc` também fornece o seguinte decorador:" #: ../../library/abc.rst:167 msgid "A decorator indicating abstract methods." @@ -210,6 +345,13 @@ msgid "" "the normal 'super' call mechanisms. :func:`!abstractmethod` may be used to " "declare abstract methods for properties and descriptors." msgstr "" +"Usar este decorador requer que a metaclasse da classe seja :class:`ABCMeta` " +"ou seja derivada desta. Uma classe que tem uma metaclasse derivada de :class:" +"`!ABCMeta` não pode ser instanciada, a menos que todos os seus métodos " +"abstratos e propriedades estejam substituídos. Os métodos abstratos podem " +"ser chamados usando qualquer um dos mecanismos normais de chamadas a " +"'super'. :func:`!abstractmethod` pode ser usado para declarar métodos " +"abstratos para propriedades e descritores." #: ../../library/abc.rst:176 msgid "" @@ -220,6 +362,12 @@ msgid "" "\"virtual subclasses\" registered with the ABC's :meth:`~ABCMeta.register` " "method are not affected." msgstr "" +"Adicionar dinamicamente métodos abstratos a uma classe, ou tentar modificar " +"o status de abstração de um método ou classe uma vez que estejam criados, só " +"é suportado usando a função :func:`update_abstractmethods`. A :func:`!" +"abstractmethod` afeta apenas subclasses derivadas usando herança regular; " +"\"subclasses virtuais\" registradas com o método :meth:`~ABCMeta.register` " +"da ABC não são afetadas." #: ../../library/abc.rst:183 msgid "" @@ -227,6 +375,71 @@ msgid "" "descriptors, it should be applied as the innermost decorator, as shown in " "the following usage examples::" msgstr "" +"Quando :func:`!abstractmethod` é aplicado em combinação com outros " +"descritores de método, ele deve ser aplicado como o decorador mais interno, " +"como mostrado nos seguintes exemplos de uso::" + +#: ../../library/abc.rst:187 +msgid "" +"class C(ABC):\n" +" @abstractmethod\n" +" def my_abstract_method(self, arg1):\n" +" ...\n" +" @classmethod\n" +" @abstractmethod\n" +" def my_abstract_classmethod(cls, arg2):\n" +" ...\n" +" @staticmethod\n" +" @abstractmethod\n" +" def my_abstract_staticmethod(arg3):\n" +" ...\n" +"\n" +" @property\n" +" @abstractmethod\n" +" def my_abstract_property(self):\n" +" ...\n" +" @my_abstract_property.setter\n" +" @abstractmethod\n" +" def my_abstract_property(self, val):\n" +" ...\n" +"\n" +" @abstractmethod\n" +" def _get_x(self):\n" +" ...\n" +" @abstractmethod\n" +" def _set_x(self, val):\n" +" ...\n" +" x = property(_get_x, _set_x)" +msgstr "" +"class C(ABC):\n" +" @abstractmethod\n" +" def my_abstract_method(self, arg1):\n" +" ...\n" +" @classmethod\n" +" @abstractmethod\n" +" def my_abstract_classmethod(cls, arg2):\n" +" ...\n" +" @staticmethod\n" +" @abstractmethod\n" +" def my_abstract_staticmethod(arg3):\n" +" ...\n" +"\n" +" @property\n" +" @abstractmethod\n" +" def my_abstract_property(self):\n" +" ...\n" +" @my_abstract_property.setter\n" +" @abstractmethod\n" +" def my_abstract_property(self, val):\n" +" ...\n" +"\n" +" @abstractmethod\n" +" def _get_x(self):\n" +" ...\n" +" @abstractmethod\n" +" def _set_x(self, val):\n" +" ...\n" +" x = property(_get_x, _set_x)" #: ../../library/abc.rst:217 msgid "" @@ -236,6 +449,27 @@ msgid "" "of the methods used to compose the descriptor are abstract. For example, " "Python's built-in :class:`property` does the equivalent of::" msgstr "" +"Para que interopere corretamente com o maquinário da classe base abstrata, o " +"descritor precisa identificar-se como abstrato usando :attr:`!" +"__isabstractmethod__`. No geral, este atributo deve ser ``True`` se algum " +"dos métodos usados para compor o descritor for abstrato. Por exemplo, a :" +"class:`property` embutida do Python faz o equivalente a::" + +#: ../../library/abc.rst:223 +msgid "" +"class Descriptor:\n" +" ...\n" +" @property\n" +" def __isabstractmethod__(self):\n" +" return any(getattr(f, '__isabstractmethod__', False) for\n" +" f in (self._fget, self._fset, self._fdel))" +msgstr "" +"class Descriptor:\n" +" ...\n" +" @property\n" +" def __isabstractmethod__(self):\n" +" return any(getattr(f, '__isabstractmethod__', False) for\n" +" f in (self._fget, self._fset, self._fdel))" #: ../../library/abc.rst:232 msgid "" @@ -252,7 +486,7 @@ msgstr "" #: ../../library/abc.rst:239 msgid "The :mod:`!abc` module also supports the following legacy decorators:" -msgstr "" +msgstr "O módulo :mod:`!abc` também suporta os seguintes decoradores herdados:" #: ../../library/abc.rst:244 msgid "" @@ -279,6 +513,20 @@ msgstr "" "`classmethod` está agora corretamente identificado como abstrato quando " "aplicado a um método abstrato::" +#: ../../library/abc.rst:255 +msgid "" +"class C(ABC):\n" +" @classmethod\n" +" @abstractmethod\n" +" def my_abstract_classmethod(cls, arg):\n" +" ..." +msgstr "" +"class C(ABC):\n" +" @classmethod\n" +" @abstractmethod\n" +" def my_abstract_classmethod(cls, arg):\n" +" ..." + #: ../../library/abc.rst:265 msgid "" "It is now possible to use :class:`staticmethod` with :func:`abstractmethod`, " @@ -304,6 +552,20 @@ msgstr "" "`staticmethod` está agora corretamente identificado como abstrato quando " "aplicado a um método abstrato::" +#: ../../library/abc.rst:276 +msgid "" +"class C(ABC):\n" +" @staticmethod\n" +" @abstractmethod\n" +" def my_abstract_staticmethod(arg):\n" +" ..." +msgstr "" +"class C(ABC):\n" +" @staticmethod\n" +" @abstractmethod\n" +" def my_abstract_staticmethod(arg):\n" +" ..." + #: ../../library/abc.rst:285 msgid "" "It is now possible to use :class:`property`, :meth:`property.getter`, :meth:" @@ -330,6 +592,20 @@ msgstr "" "está agora corretamente identificado como abstrato quando aplicado a um " "método abstrato::" +#: ../../library/abc.rst:297 +msgid "" +"class C(ABC):\n" +" @property\n" +" @abstractmethod\n" +" def my_abstract_property(self):\n" +" ..." +msgstr "" +"class C(ABC):\n" +" @property\n" +" @abstractmethod\n" +" def my_abstract_property(self):\n" +" ..." + #: ../../library/abc.rst:303 msgid "" "The above example defines a read-only property; you can also define a read-" @@ -340,6 +616,28 @@ msgstr "" "definir uma propriedade abstrata de leitura e escrita marcando " "apropriadamente um ou mais dos métodos subjacentes como abstratos::" +#: ../../library/abc.rst:307 +msgid "" +"class C(ABC):\n" +" @property\n" +" def x(self):\n" +" ...\n" +"\n" +" @x.setter\n" +" @abstractmethod\n" +" def x(self, val):\n" +" ..." +msgstr "" +"class C(ABC):\n" +" @property\n" +" def x(self):\n" +" ...\n" +"\n" +" @x.setter\n" +" @abstractmethod\n" +" def x(self, val):\n" +" ..." + #: ../../library/abc.rst:317 msgid "" "If only some components are abstract, only those components need to be " @@ -349,9 +647,21 @@ msgstr "" "precisam ser atualizados para criar uma propriedade concreta em uma " "subclasse::" +#: ../../library/abc.rst:320 +msgid "" +"class D(C):\n" +" @C.x.setter\n" +" def x(self, val):\n" +" ..." +msgstr "" +"class D(C):\n" +" @C.x.setter\n" +" def x(self, val):\n" +" ..." + #: ../../library/abc.rst:326 msgid "The :mod:`!abc` module also provides the following functions:" -msgstr "" +msgstr "O módulo :mod:`!abc` também fornece as seguintes funções:" #: ../../library/abc.rst:330 msgid "Returns the current abstract base class cache token." diff --git a/library/aifc.po b/library/aifc.po new file mode 100644 index 000000000..46950271a --- /dev/null +++ b/library/aifc.po @@ -0,0 +1,46 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../library/aifc.rst:2 +msgid ":mod:`!aifc` --- Read and write AIFF and AIFC files" +msgstr ":mod:`!aifc` --- Lê e escreve arquivos AIFF e AIFC" + +#: ../../library/aifc.rst:10 +msgid "" +"This module is no longer part of the Python standard library. It was :ref:" +"`removed in Python 3.13 ` after being deprecated in " +"Python 3.11. The removal was decided in :pep:`594`." +msgstr "" +"Este módulo não faz mais parte da biblioteca padrão do Python. Ele foi :ref:" +"`removido no Python 3.13 ` após ser descontinuado no " +"Python 3.11. A remoção foi decidida na :pep:`594`." + +#: ../../library/aifc.rst:14 +msgid "" +"The last version of Python that provided the :mod:`!aifc` module was `Python " +"3.12 `_." +msgstr "" +"A última versão do Python que forneceu o módulo :mod:`!aifc` foi o `Python " +"3.12 `_." diff --git a/library/allos.po b/library/allos.po index ce12dc389..398b3fdb4 100644 --- a/library/allos.po +++ b/library/allos.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:54+0000\n" -"Last-Translator: Claudio Rogerio Carvalho Filho , " -"2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/archiving.po b/library/archiving.po index 51e9492bd..d48229e61 100644 --- a/library/archiving.po +++ b/library/archiving.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:54+0000\n" -"Last-Translator: Claudio Rogerio Carvalho Filho , " -"2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/argparse.po b/library/argparse.po index 6366d1db5..dcd474c01 100644 --- a/library/argparse.po +++ b/library/argparse.po @@ -1,41 +1,32 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# And Past , 2021 -# Alexandre B A Villares, 2021 -# i17obot , 2021 -# Danilo Lima , 2022 -# mvpetri , 2022 -# Marco Rougeth , 2022 -# Leticia Portella , 2023 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:54+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/argparse.rst:2 msgid "" -":mod:`!argparse` --- Parser for command-line options, arguments and sub-" -"commands" +":mod:`!argparse` --- Parser for command-line options, arguments and " +"subcommands" msgstr "" ":mod:`!argparse` --- Analisador sintático para opções de linha de comando, " "argumentos e subcomandos" @@ -44,11 +35,34 @@ msgstr "" msgid "**Source code:** :source:`Lib/argparse.py`" msgstr "**Código-fonte:** :source:`Lib/argparse.py`" +#: ../../library/argparse.rst:16 +msgid "" +"While :mod:`argparse` is the default recommended standard library module for " +"implementing basic command line applications, authors with more exacting " +"requirements for exactly how their command line applications behave may find " +"it doesn't provide the necessary level of control. Refer to :ref:`choosing-" +"an-argument-parser` for alternatives to consider when ``argparse`` doesn't " +"support behaviors that the application requires (such as entirely disabling " +"support for interspersed options and positional arguments, or accepting " +"option parameter values that start with ``-`` even when they correspond to " +"another defined option)." +msgstr "" +"Embora :mod:`argparse` seja o módulo de biblioteca padrão recomendado para " +"implementar aplicações básicas de linha de comando, autores com requisitos " +"mais rigorosos sobre como exatamente seus aplicativos de linha de comando se " +"comportam podem descobrir que ele não fornece o nível de controle " +"necessário. Consulte :ref:`choosing-an-argument-parser` para alternativas a " +"serem consideradas quando ``argparse`` não suporta comportamentos que a " +"aplicação requer (como desabilitar completamente o suporte para opções " +"intercaladas e argumentos posicionais, ou aceitar valores de parâmetros de " +"opção que começam com ``-`` mesmo quando correspondem a outra opção " +"definida)." + #: ../../library/argparse.rst-1 msgid "Tutorial" msgstr "Tutorial" -#: ../../library/argparse.rst:18 +#: ../../library/argparse.rst:30 msgid "" "This page contains the API reference information. For a more gentle " "introduction to Python command-line parsing, have a look at the :ref:" @@ -58,39 +72,47 @@ msgstr "" "mais prática para o parser de linha de comando Python, acesse o :ref:" "`tutorial do argparse `." -#: ../../library/argparse.rst:22 +#: ../../library/argparse.rst:34 msgid "" -"The :mod:`argparse` module makes it easy to write user-friendly command-line " -"interfaces. The program defines what arguments it requires, and :mod:" -"`argparse` will figure out how to parse those out of :data:`sys.argv`. The :" -"mod:`argparse` module also automatically generates help and usage messages. " -"The module will also issue errors when users give the program invalid " -"arguments." +"The :mod:`!argparse` module makes it easy to write user-friendly command-" +"line interfaces. The program defines what arguments it requires, and :mod:`!" +"argparse` will figure out how to parse those out of :data:`sys.argv`. The :" +"mod:`!argparse` module also automatically generates help and usage " +"messages. The module will also issue errors when users give the program " +"invalid arguments." msgstr "" -"O módulo :mod:`argparse` torna fácil a escrita de interfaces de linha de " +"O módulo :mod:`!argparse` torna fácil a escrita de interfaces de linha de " "comando amigáveis. O programa define quais argumentos são necessários e :mod:" -"`argparse` descobrirá como analisá-lo e interpretá-los a partir do :data:" -"`sys.argv`. O módulo :mod:`argparse` também gera automaticamente o texto " +"`!argparse` descobrirá como analisá-lo e interpretá-los a partir do :data:" +"`sys.argv`. O módulo :mod:`!argparse` também gera automaticamente o texto " "ajuda e mensagens de uso. O módulo também vai emitir erros quando o usuário " "prover argumentos inválidos para o programa." -#: ../../library/argparse.rst:30 -msgid "Core Functionality" -msgstr "Funcionalidade central" - -#: ../../library/argparse.rst:32 +#: ../../library/argparse.rst:40 msgid "" -"The :mod:`argparse` module's support for command-line interfaces is built " +"The :mod:`!argparse` module's support for command-line interfaces is built " "around an instance of :class:`argparse.ArgumentParser`. It is a container " "for argument specifications and has options that apply to the parser as " "whole::" msgstr "" -"O suporte do módulo :mod:`argparse` para interfaces de linha de comando é " +"O suporte do módulo :mod:`!argparse` para interfaces de linha de comando é " "construído em torno de uma instância de :class:`argparse.ArgumentParser`. É " "um contêiner para especificações de argumentos e possui opções que se " "aplicam ao analisador sintático como um todo::" -#: ../../library/argparse.rst:41 +#: ../../library/argparse.rst:44 +msgid "" +"parser = argparse.ArgumentParser(\n" +" prog='ProgramName',\n" +" description='What the program does',\n" +" epilog='Text at the bottom of help')" +msgstr "" +"parser = argparse.ArgumentParser(\n" +" prog='NomePrograma',\n" +" description='O que o programa faz',\n" +" epilog='Texto na parte inferior da memsagem de ajuda')" + +#: ../../library/argparse.rst:49 msgid "" "The :meth:`ArgumentParser.add_argument` method attaches individual argument " "specifications to the parser. It supports positional arguments, options " @@ -100,7 +122,19 @@ msgstr "" "argumentos individuais ao analisador. Ele oferece suporte a argumentos " "posicionais, opções que aceitam valores e sinalizadores liga/desliga::" -#: ../../library/argparse.rst:50 +#: ../../library/argparse.rst:53 +msgid "" +"parser.add_argument('filename') # positional argument\n" +"parser.add_argument('-c', '--count') # option that takes a value\n" +"parser.add_argument('-v', '--verbose',\n" +" action='store_true') # on/off flag" +msgstr "" +"parser.add_argument('filename') # argumento posicional\n" +"parser.add_argument('-c', '--count') # a opção recebe um valor\n" +"parser.add_argument('-v', '--verbose',\n" +" action='store_true') # sinalizador de ligar/desligar" + +#: ../../library/argparse.rst:58 msgid "" "The :meth:`ArgumentParser.parse_args` method runs the parser and places the " "extracted data in a :class:`argparse.Namespace` object::" @@ -108,264 +142,29 @@ msgstr "" "O método :meth:`ArgumentParser.parse_args` executa o analisador e coloca os " "dados extraídos em um objeto :class:`argparse.Namespace`::" -#: ../../library/argparse.rst:58 -msgid "Quick Links for add_argument()" -msgstr "Links rápidos para add_argument()" - -#: ../../library/argparse.rst:61 -msgid "Name" -msgstr "Nome" - #: ../../library/argparse.rst:61 -msgid "Description" -msgstr "Descrição" - -#: ../../library/argparse.rst:61 -msgid "Values" -msgstr "Valores" - -#: ../../library/argparse.rst:63 -msgid "action_" -msgstr "action_" - -#: ../../library/argparse.rst:63 -msgid "Specify how an argument should be handled" -msgstr "Especifica como um argumento deve ser tratado" - -#: ../../library/argparse.rst:63 -msgid "" -"``'store'``, ``'store_const'``, ``'store_true'``, ``'append'``, " -"``'append_const'``, ``'count'``, ``'help'``, ``'version'``" -msgstr "" -"``'store'``, ``'store_const'``, ``'store_true'``, ``'append'``, " -"``'append_const'``, ``'count'``, ``'help'``, ``'version'``" - -#: ../../library/argparse.rst:64 -msgid "choices_" -msgstr "choices_" - -#: ../../library/argparse.rst:64 -msgid "Limit values to a specific set of choices" -msgstr "Limita valores a um conjunto específico de opções" - -#: ../../library/argparse.rst:64 msgid "" -"``['foo', 'bar']``, ``range(1, 10)``, or :class:`~collections.abc.Container` " -"instance" +"args = parser.parse_args()\n" +"print(args.filename, args.count, args.verbose)" msgstr "" -"``['foo', 'bar']``, ``range(1, 10)`` ou instância :class:`~collections.abc." -"Container`" - -#: ../../library/argparse.rst:65 -msgid "const_" -msgstr "const_" +"args = parser.parse_args()\n" +"print(args.filename, args.count, args.verbose)" #: ../../library/argparse.rst:65 -msgid "Store a constant value" -msgstr "Armazena um valor constante" - -#: ../../library/argparse.rst:66 -msgid "default_" -msgstr "default_" - -#: ../../library/argparse.rst:66 -msgid "Default value used when an argument is not provided" -msgstr "Valor padrão usado quando um argumento não é fornecido" - -#: ../../library/argparse.rst:66 -msgid "Defaults to ``None``" -msgstr "O padrão é ``None``" - -#: ../../library/argparse.rst:67 -msgid "dest_" -msgstr "dest_" - -#: ../../library/argparse.rst:67 -msgid "Specify the attribute name used in the result namespace" -msgstr "Especifica o nome do atributo usado no espaço de nomes de resultado" - -#: ../../library/argparse.rst:68 -msgid "help_" -msgstr "help_" - -#: ../../library/argparse.rst:68 -msgid "Help message for an argument" -msgstr "Mensagem de ajuda para um argumento" - -#: ../../library/argparse.rst:69 -msgid "metavar_" -msgstr "metavar_" - -#: ../../library/argparse.rst:69 -msgid "Alternate display name for the argument as shown in help" -msgstr "" -"Nome de exibição alternativo para o argumento conforme mostrado na ajuda" - -#: ../../library/argparse.rst:70 -msgid "nargs_" -msgstr "nargs_" - -#: ../../library/argparse.rst:70 -msgid "Number of times the argument can be used" -msgstr "Número de vezes que o argumento pode ser usado" - -#: ../../library/argparse.rst:70 -msgid ":class:`int`, ``'?'``, ``'*'``, or ``'+'``" -msgstr ":class:`int`, ``'?'``, ``'*'``, ou ``'+'``" - -#: ../../library/argparse.rst:71 -msgid "required_" -msgstr "required_" - -#: ../../library/argparse.rst:71 -msgid "Indicate whether an argument is required or optional" -msgstr "Indica se um argumento é obrigatório ou opcional" - -#: ../../library/argparse.rst:71 -msgid "``True`` or ``False``" -msgstr "``True`` ou ``False``" - -#: ../../library/argparse.rst:72 -msgid ":ref:`type `" -msgstr ":ref:`type `" - -#: ../../library/argparse.rst:72 -msgid "Automatically convert an argument to the given type" -msgstr "Converte automaticamente um argumento para o tipo fornecido" - -#: ../../library/argparse.rst:72 msgid "" -":class:`int`, :class:`float`, ``argparse.FileType('w')``, or callable " -"function" +"If you're looking for a guide about how to upgrade :mod:`optparse` code to :" +"mod:`!argparse`, see :ref:`Upgrading Optparse Code `." msgstr "" -":class:`int`, :class:`float`, ``argparse.FileType('w')`` ou uma função " -"chamável" - -#: ../../library/argparse.rst:77 -msgid "Example" -msgstr "Exemplo" +"Se você estiver procurando um guia sobre como atualizar um código :mod:" +"`optparse` para :mod:`!argparse`, veja :ref:`Atualizando código optparse " +"`." -#: ../../library/argparse.rst:79 -msgid "" -"The following code is a Python program that takes a list of integers and " -"produces either the sum or the max::" -msgstr "" -"O código a seguir é um programa Python que recebe uma lista de inteiros e " -"apresenta a soma ou o máximo::" - -#: ../../library/argparse.rst:94 -msgid "" -"Assuming the above Python code is saved into a file called ``prog.py``, it " -"can be run at the command line and it provides useful help messages:" -msgstr "" -"Presumindo que o código Python acima seja salvo em um arquivo chamado ``prog." -"py``, ele pode ser executado pela linha de comando e fornece mensagens de " -"ajuda úteis:" - -#: ../../library/argparse.rst:111 -msgid "" -"When run with the appropriate arguments, it prints either the sum or the max " -"of the command-line integers:" -msgstr "" -"Quando executado com argumentos apropriados, a soma ou o maior número dos " -"números digitados na linha de comando:" - -#: ../../library/argparse.rst:122 -msgid "If invalid arguments are passed in, an error will be displayed:" -msgstr "Se argumentos inválidos forem passados, um erro será exibido:" - -#: ../../library/argparse.rst:130 -msgid "The following sections walk you through this example." -msgstr "As próximas seções apresentarão detalhes deste exemplo." - -#: ../../library/argparse.rst:134 -msgid "Creating a parser" -msgstr "Criando um analisador sintático" - -#: ../../library/argparse.rst:136 -msgid "" -"The first step in using the :mod:`argparse` is creating an :class:" -"`ArgumentParser` object::" -msgstr "" -"O primeiro passo ao utilizar o :mod:`argparse` é criar um objeto :class:" -"`ArgumentParser`::" - -#: ../../library/argparse.rst:141 -msgid "" -"The :class:`ArgumentParser` object will hold all the information necessary " -"to parse the command line into Python data types." -msgstr "" -"O objeto :class:`ArgumentParser` contém toda informação necessária para " -"análise e interpretação da linha de comando em tipos de dados Python." - -#: ../../library/argparse.rst:146 -msgid "Adding arguments" -msgstr "Adicionando argumentos" - -#: ../../library/argparse.rst:148 -msgid "" -"Filling an :class:`ArgumentParser` with information about program arguments " -"is done by making calls to the :meth:`~ArgumentParser.add_argument` method. " -"Generally, these calls tell the :class:`ArgumentParser` how to take the " -"strings on the command line and turn them into objects. This information is " -"stored and used when :meth:`~ArgumentParser.parse_args` is called. For " -"example::" -msgstr "" -"O preenchimento de :class:`ArgumentParser` com informações sobre os " -"argumentos do programa é feito por chamadas ao método :meth:`~ArgumentParser." -"add_argument`. Geralmente, estas chamadas informam ao :class:" -"`ArgumentParser` como traduzir strings da linha de comando e torná-los em " -"objetos. Esta informação é armazenada e utilizada quando o método :meth:" -"`~ArgumentParser.parse_args` é invocado. Por exemplo::" - -#: ../../library/argparse.rst:160 -msgid "" -"Later, calling :meth:`~ArgumentParser.parse_args` will return an object with " -"two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute " -"will be a list of one or more integers, and the ``accumulate`` attribute " -"will be either the :func:`sum` function, if ``--sum`` was specified at the " -"command line, or the :func:`max` function if it was not." -msgstr "" -"Em seguida, a chamada ao método :meth:`~ArgumentParser.parse_args` irá " -"retornar um objeto com dois atributos, ``integers`` e ``accumulate``. O " -"atributo ``integers`` será uma lista com um ou mais números inteiros, e o " -"atributo ``accumulate`` será ou a função :func:`sum`, se ``--sum`` for " -"especificado na linha de comando, ou a função :func:`max`, caso contrário." - -#: ../../library/argparse.rst:168 -msgid "Parsing arguments" -msgstr "Análise de argumentos" - -#: ../../library/argparse.rst:170 -msgid "" -":class:`ArgumentParser` parses arguments through the :meth:`~ArgumentParser." -"parse_args` method. This will inspect the command line, convert each " -"argument to the appropriate type and then invoke the appropriate action. In " -"most cases, this means a simple :class:`Namespace` object will be built up " -"from attributes parsed out of the command line::" -msgstr "" -":class:`ArgumentParser` analisa os argumentos através do método :meth:" -"`~ArgumentParser.parse_args`. Isso inspecionará a linha de comando, " -"converterá cada argumento no tipo apropriado e, em seguida, chamará a ação " -"apropriada. Na maioria dos casos, isso significa que um objeto :class:" -"`Namespace` simples será construído a partir de atributos analisados a " -"partir da linha de comando::" - -#: ../../library/argparse.rst:179 -msgid "" -"In a script, :meth:`~ArgumentParser.parse_args` will typically be called " -"with no arguments, and the :class:`ArgumentParser` will automatically " -"determine the command-line arguments from :data:`sys.argv`." -msgstr "" -"Em um script, :meth:`~ArgumentParser.parse_args` será tipicamente chamado " -"sem argumentos, e :class:`ArgumentParser` irá determinar automaticamente os " -"argumentos de linha de comando de :data:`sys.argv`." - -#: ../../library/argparse.rst:185 +#: ../../library/argparse.rst:69 msgid "ArgumentParser objects" msgstr "Objetos ArgumentParser" -#: ../../library/argparse.rst:194 +#: ../../library/argparse.rst:78 msgid "" "Create a new :class:`ArgumentParser` object. All parameters should be passed " "as keyword arguments. Each parameter has its own more detailed description " @@ -375,12 +174,12 @@ msgstr "" "passados como argumentos nomeados. Cada parâmetro tem sua própria descrição " "mais detalhada abaixo, mas em resumo eles são:" -#: ../../library/argparse.rst:198 +#: ../../library/argparse.rst:82 msgid "" "prog_ - The name of the program (default: ``os.path.basename(sys.argv[0])``)" msgstr "prog_ - O nome do programa (padrão: ``os.path.basename(sys.argv[0])``)" -#: ../../library/argparse.rst:201 +#: ../../library/argparse.rst:85 msgid "" "usage_ - The string describing the program usage (default: generated from " "arguments added to parser)" @@ -388,20 +187,20 @@ msgstr "" "usage_ - A string que descreve o uso do programa (padrão: gerado a partir de " "argumentos adicionados ao analisador sintático)" -#: ../../library/argparse.rst:204 +#: ../../library/argparse.rst:88 msgid "" "description_ - Text to display before the argument help (by default, no text)" msgstr "" "description_ - Texto para exibir antes da ajuda dos argumentos (por padrão, " "nenhum texto)" -#: ../../library/argparse.rst:207 +#: ../../library/argparse.rst:91 msgid "epilog_ - Text to display after the argument help (by default, no text)" msgstr "" "epilog_ - Texto para exibir após da ajuda dos argumentos (por padrão, nenhum " "texto)" -#: ../../library/argparse.rst:209 +#: ../../library/argparse.rst:93 msgid "" "parents_ - A list of :class:`ArgumentParser` objects whose arguments should " "also be included" @@ -409,11 +208,11 @@ msgstr "" "parents_ - Uma lista de objetos :class:`ArgumentParser` cujos argumentos " "também devem ser incluídos" -#: ../../library/argparse.rst:212 +#: ../../library/argparse.rst:96 msgid "formatter_class_ - A class for customizing the help output" msgstr "formatter_class_ - Uma classe para personalizar a saída de ajuda" -#: ../../library/argparse.rst:214 +#: ../../library/argparse.rst:98 msgid "" "prefix_chars_ - The set of characters that prefix optional arguments " "(default: '-')" @@ -421,7 +220,7 @@ msgstr "" "prefix_chars_ - O conjunto de caracteres que prefixam argumentos opcionais " "(padrão: \"-\")" -#: ../../library/argparse.rst:217 +#: ../../library/argparse.rst:101 msgid "" "fromfile_prefix_chars_ - The set of characters that prefix files from which " "additional arguments should be read (default: ``None``)" @@ -429,14 +228,14 @@ msgstr "" "fromfile_prefix_chars_ - O conjunto de caracteres que prefixam os arquivos " "dos quais os argumentos adicionais devem ser lidos (padrão: ``None``)" -#: ../../library/argparse.rst:220 +#: ../../library/argparse.rst:104 msgid "" "argument_default_ - The global default value for arguments (default: " "``None``)" msgstr "" "argument_default_ - O valor padrão global para argumentos (padrão: ``None``)" -#: ../../library/argparse.rst:223 +#: ../../library/argparse.rst:107 msgid "" "conflict_handler_ - The strategy for resolving conflicting optionals " "(usually unnecessary)" @@ -444,14 +243,14 @@ msgstr "" "conflict_handler_ - A estratégia para resolver opcionais conflitantes " "(geralmente desnecessário)" -#: ../../library/argparse.rst:226 +#: ../../library/argparse.rst:110 msgid "" "add_help_ - Add a ``-h/--help`` option to the parser (default: ``True``)" msgstr "" "add_help_ - Adiciona uma opção ``-h/--help`` para o analisador sintático " "(padrão: ``True``)" -#: ../../library/argparse.rst:228 +#: ../../library/argparse.rst:112 msgid "" "allow_abbrev_ - Allows long options to be abbreviated if the abbreviation is " "unambiguous. (default: ``True``)" @@ -459,19 +258,19 @@ msgstr "" "allow_abbrev_ - Permite que opções longas sejam abreviadas se a abreviação " "não for ambígua. (padrão: ``True``)" -#: ../../library/argparse.rst:231 +#: ../../library/argparse.rst:115 msgid "" -"exit_on_error_ - Determines whether or not ArgumentParser exits with error " -"info when an error occurs. (default: ``True``)" +"exit_on_error_ - Determines whether or not :class:`!ArgumentParser` exits " +"with error info when an error occurs. (default: ``True``)" msgstr "" -"exit_on_error_ - Determina se ArgumentParser sai ou não com informações de " -"erro quando ocorre um erro. (padrão: ``True``)" +"exit_on_error_ - Determina se :class:`!ArgumentParser` sai ou não com " +"informações de erro quando ocorre um erro. (padrão: ``True``)" -#: ../../library/argparse.rst:234 +#: ../../library/argparse.rst:118 msgid "*allow_abbrev* parameter was added." msgstr "O parâmetro *allow_abbrev* foi adicionado." -#: ../../library/argparse.rst:237 +#: ../../library/argparse.rst:121 msgid "" "In previous versions, *allow_abbrev* also disabled grouping of short flags " "such as ``-vv`` to mean ``-v -v``." @@ -479,50 +278,81 @@ msgstr "" "Em versões anteriores, *allow_abbrev* também desabilitava o agrupamento de " "sinalizadores curtos, como ``-vv`` para significar ``-v -v``." -#: ../../library/argparse.rst:241 +#: ../../library/argparse.rst:125 msgid "*exit_on_error* parameter was added." msgstr "O parâmetro *exit_on_error* foi adicionado." -#: ../../library/argparse.rst:244 ../../library/argparse.rst:782 +#: ../../library/argparse.rst:128 ../../library/argparse.rst:610 msgid "The following sections describe how each of these are used." msgstr "As seções a seguir descrevem como cada um deles é usado." -#: ../../library/argparse.rst:250 +#: ../../library/argparse.rst:134 msgid "prog" msgstr "prog" -#: ../../library/argparse.rst:252 +#: ../../library/argparse.rst:137 msgid "" -"By default, :class:`ArgumentParser` objects use ``sys.argv[0]`` to determine " -"how to display the name of the program in help messages. This default is " -"almost always desirable because it will make the help messages match how the " -"program was invoked on the command line. For example, consider a file named " -"``myprogram.py`` with the following code::" +"By default, :class:`ArgumentParser` calculates the name of the program to " +"display in help messages depending on the way the Python interpreter was run:" msgstr "" -"Por padrão, os objetos :class:`ArgumentParser` usam ``sys.argv[0]`` para " -"determinar como exibir o nome do programa nas mensagens de ajuda. Esse " -"padrão é quase sempre desejável porque fará com que as mensagens de ajuda " -"correspondam à forma como o programa foi chamado na linha de comando. Por " -"exemplo, considere um arquivo denominado ``myprogram.py`` com o seguinte " -"código::" +"Por padrão, :class:`ArgumentParser` calcula o nome do programa a ser exibido " +"nas mensagens de ajuda dependendo da maneira como o interpretador Python foi " +"executado:" -#: ../../library/argparse.rst:263 +#: ../../library/argparse.rst:140 msgid "" -"The help for this program will display ``myprogram.py`` as the program name " -"(regardless of where the program was invoked from):" +"The :func:`base name ` of ``sys.argv[0]`` if a file was " +"passed as argument." msgstr "" -"A ajuda para este programa exibirá ``myprogram.py`` como o nome do programa " -"(independentemente de onde o programa foi chamado):" +"O :func:`nome base ` de ``sys.argv[0]`` se um arquivo foi " +"passado como argumento." -#: ../../library/argparse.rst:282 +#: ../../library/argparse.rst:142 msgid "" -"To change this default behavior, another value can be supplied using the " -"``prog=`` argument to :class:`ArgumentParser`::" +"The Python interpreter name followed by ``sys.argv[0]`` if a directory or a " +"zipfile was passed as argument." msgstr "" -"Para alterar este comportamento padrão, outro valor pode ser fornecido " -"usando o argumento ``prog=`` para :class:`ArgumentParser`::" +"O nome do interpretador Python seguido por ``sys.argv[0]`` se um diretório " +"ou um arquivo zip foi passado como argumento." -#: ../../library/argparse.rst:292 +#: ../../library/argparse.rst:144 +msgid "" +"The Python interpreter name followed by ``-m`` followed by the module or " +"package name if the :option:`-m` option was used." +msgstr "" +"O nome do interpretador Python seguido por ``-m`` seguido pelo nome do " +"módulo ou pacote se a opção :option:`-m` foi usada." + +#: ../../library/argparse.rst:147 +msgid "" +"This default is almost always desirable because it will make the help " +"messages match the string that was used to invoke the program on the command " +"line. However, to change this default behavior, another value can be " +"supplied using the ``prog=`` argument to :class:`ArgumentParser`::" +msgstr "" +"Este padrão é quase sempre desejável porque fará com que as mensagens de " +"ajuda correspondam à string que foi usada para invocar o programa na linha " +"de comando. No entanto, para alterar esse comportamento padrão, outro valor " +"pode ser fornecido usando o argumento ``prog=`` para :class:" +"`ArgumentParser`::" + +#: ../../library/argparse.rst:152 +msgid "" +">>> parser = argparse.ArgumentParser(prog='myprogram')\n" +">>> parser.print_help()\n" +"usage: myprogram [-h]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='meuprograma')\n" +">>> parser.print_help()\n" +"usage: meuprograma [-h]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit" + +#: ../../library/argparse.rst:159 msgid "" "Note that the program name, whether determined from ``sys.argv[0]`` or from " "the ``prog=`` argument, is available to help messages using the ``%(prog)s`` " @@ -532,25 +362,71 @@ msgstr "" "ou do argumento ``prog=``, está disponível para mensagens de ajuda usando o " "especificador de formato ``%(prog)s``." -#: ../../library/argparse.rst:309 +#: ../../library/argparse.rst:165 +msgid "" +">>> parser = argparse.ArgumentParser(prog='myprogram')\n" +">>> parser.add_argument('--foo', help='foo of the %(prog)s program')\n" +">>> parser.print_help()\n" +"usage: myprogram [-h] [--foo FOO]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo FOO foo of the myprogram program" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='meuprograma')\n" +">>> parser.add_argument('--foo', help='foo do programa %(prog)s')\n" +">>> parser.print_help()\n" +"usage: meuprograma [-h] [--foo FOO]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo FOO foo do programa meuprograma" + +#: ../../library/argparse.rst:176 msgid "usage" msgstr "usage" -#: ../../library/argparse.rst:311 +#: ../../library/argparse.rst:178 msgid "" "By default, :class:`ArgumentParser` calculates the usage message from the " -"arguments it contains::" +"arguments it contains. The default message can be overridden with the " +"``usage=`` keyword argument::" msgstr "" "Por padrão, :class:`ArgumentParser` calcula a mensagem de uso a partir dos " -"argumentos que contém::" - -#: ../../library/argparse.rst:327 -msgid "" -"The default message can be overridden with the ``usage=`` keyword argument::" -msgstr "" -"A mensagem padrão pode ser substituído com o argumento nomeado ``usage=``::" - -#: ../../library/argparse.rst:342 +"argumentos que contém. A mensagem padrão pode ser substituída pelo argumento " +"nomeado ``usage=``::" + +#: ../../library/argparse.rst:182 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s " +"[options]')\n" +">>> parser.add_argument('--foo', nargs='?', help='foo help')\n" +">>> parser.add_argument('bar', nargs='+', help='bar help')\n" +">>> parser.print_help()\n" +"usage: PROG [options]\n" +"\n" +"positional arguments:\n" +" bar bar help\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo [FOO] foo help" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s " +"[options]')\n" +">>> parser.add_argument('--foo', nargs='?', help='foo help')\n" +">>> parser.add_argument('bar', nargs='+', help='bar help')\n" +">>> parser.print_help()\n" +"usage: PROG [options]\n" +"\n" +"positional arguments:\n" +" bar bar help\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo [FOO] foo help" + +#: ../../library/argparse.rst:195 msgid "" "The ``%(prog)s`` format specifier is available to fill in the program name " "in your usage messages." @@ -558,25 +434,25 @@ msgstr "" "O especificador de formato ``%(prog)s`` está disponível para preencher o " "nome do programa em suas mensagens de uso." -#: ../../library/argparse.rst:349 +#: ../../library/argparse.rst:202 msgid "description" -msgstr "descrição" +msgstr "description" -#: ../../library/argparse.rst:351 +#: ../../library/argparse.rst:204 msgid "" "Most calls to the :class:`ArgumentParser` constructor will use the " "``description=`` keyword argument. This argument gives a brief description " "of what the program does and how it works. In help messages, the " "description is displayed between the command-line usage string and the help " -"messages for the various arguments::" +"messages for the various arguments." msgstr "" "A maioria das chamadas para o construtor :class:`ArgumentParser` usará o " "argumento nomeado ``description=``. Este argumento fornece uma breve " "descrição do que o programa faz e como funciona. Nas mensagens de ajuda, a " "descrição é exibida entre a string de uso da linha de comando e as mensagens " -"de ajuda para os vários argumentos::" +"de ajuda para os vários argumentos." -#: ../../library/argparse.rst:366 +#: ../../library/argparse.rst:210 msgid "" "By default, the description will be line-wrapped so that it fits within the " "given space. To change this behavior, see the formatter_class_ argument." @@ -585,11 +461,11 @@ msgstr "" "espaço fornecido. Para alterar esse comportamento, consulte o argumento " "formatter_class_." -#: ../../library/argparse.rst:371 +#: ../../library/argparse.rst:215 msgid "epilog" msgstr "epilog" -#: ../../library/argparse.rst:373 +#: ../../library/argparse.rst:217 msgid "" "Some programs like to display additional description of the program after " "the description of the arguments. Such text can be specified using the " @@ -599,7 +475,35 @@ msgstr "" "descrição dos argumentos. Esse texto pode ser especificado usando o " "argumento ``epilog=`` para :class:`ArgumentParser`::" -#: ../../library/argparse.rst:390 +#: ../../library/argparse.rst:221 +msgid "" +">>> parser = argparse.ArgumentParser(\n" +"... description='A foo that bars',\n" +"... epilog=\"And that's how you'd foo a bar\")\n" +">>> parser.print_help()\n" +"usage: argparse.py [-h]\n" +"\n" +"A foo that bars\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"\n" +"And that's how you'd foo a bar" +msgstr "" +">>> parser = argparse.ArgumentParser(\n" +"... description='Um foo que faz bars',\n" +"... epilog=\"E é assim que você faria foo de bar\")\n" +">>> parser.print_help()\n" +"usage: argparse.py [-h]\n" +"\n" +"Um foo que faz bars\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"\n" +"E é assim que você faria foo de bar" + +#: ../../library/argparse.rst:234 msgid "" "As with the description_ argument, the ``epilog=`` text is by default line-" "wrapped, but this behavior can be adjusted with the formatter_class_ " @@ -609,11 +513,11 @@ msgstr "" "sua quebra de linha habilitada por padrão, mas este comportamento pode ser " "ajustado com o argumento formatter_class_ para :class:`ArgumentParser`." -#: ../../library/argparse.rst:396 +#: ../../library/argparse.rst:240 msgid "parents" msgstr "parents" -#: ../../library/argparse.rst:398 +#: ../../library/argparse.rst:242 msgid "" "Sometimes, several parsers share a common set of arguments. Rather than " "repeating the definitions of these arguments, a single parser with all the " @@ -631,7 +535,35 @@ msgstr "" "as ações posicionais e opcionais deles, e adiciona essas ações ao objeto :" "class:`ArgumentParser` sendo construído::" -#: ../../library/argparse.rst:418 +#: ../../library/argparse.rst:249 +msgid "" +">>> parent_parser = argparse.ArgumentParser(add_help=False)\n" +">>> parent_parser.add_argument('--parent', type=int)\n" +"\n" +">>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])\n" +">>> foo_parser.add_argument('foo')\n" +">>> foo_parser.parse_args(['--parent', '2', 'XXX'])\n" +"Namespace(foo='XXX', parent=2)\n" +"\n" +">>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])\n" +">>> bar_parser.add_argument('--bar')\n" +">>> bar_parser.parse_args(['--bar', 'YYY'])\n" +"Namespace(bar='YYY', parent=None)" +msgstr "" +">>> parent_parser = argparse.ArgumentParser(add_help=False)\n" +">>> parent_parser.add_argument('--parent', type=int)\n" +"\n" +">>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])\n" +">>> foo_parser.add_argument('foo')\n" +">>> foo_parser.parse_args(['--parent', '2', 'XXX'])\n" +"Namespace(foo='XXX', parent=2)\n" +"\n" +">>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])\n" +">>> bar_parser.add_argument('--bar')\n" +">>> bar_parser.parse_args(['--bar', 'YYY'])\n" +"Namespace(bar='YYY', parent=None)" + +#: ../../library/argparse.rst:262 msgid "" "Note that most parent parsers will specify ``add_help=False``. Otherwise, " "the :class:`ArgumentParser` will see two ``-h/--help`` options (one in the " @@ -641,7 +573,7 @@ msgstr "" "``add_help=False``. Caso contrário, o :class:`ArgumentParser` verá duas " "opções ``-h/--help`` (uma no pai e outra no filho) e levantará um erro." -#: ../../library/argparse.rst:423 +#: ../../library/argparse.rst:267 msgid "" "You must fully initialize the parsers before passing them via ``parents=``. " "If you change the parent parsers after the child parser, those changes will " @@ -651,11 +583,11 @@ msgstr "" "los via ``parents=``. Se você alterar os analisadores pais após o analisador " "filho, essas mudanças não serão refletidas no filho." -#: ../../library/argparse.rst:431 +#: ../../library/argparse.rst:275 msgid "formatter_class" msgstr "formatter_class" -#: ../../library/argparse.rst:433 +#: ../../library/argparse.rst:277 msgid "" ":class:`ArgumentParser` objects allow the help formatting to be customized " "by specifying an alternate formatting class. Currently, there are four such " @@ -665,7 +597,7 @@ msgstr "" "seja personalizada por meio da especificação de uma classe de formatação " "alternativa. Atualmente, há quatro dessas classes:" -#: ../../library/argparse.rst:442 +#: ../../library/argparse.rst:286 msgid "" ":class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give " "more control over how textual descriptions are displayed. By default, :class:" @@ -677,7 +609,50 @@ msgstr "" "objetos :class:`ArgumentParser` quebram em linha os textos description_ e " "epilog_ nas mensagens de ajuda da linha de comando::" -#: ../../library/argparse.rst:467 +#: ../../library/argparse.rst:291 +msgid "" +">>> parser = argparse.ArgumentParser(\n" +"... prog='PROG',\n" +"... description='''this description\n" +"... was indented weird\n" +"... but that is okay''',\n" +"... epilog='''\n" +"... likewise for this epilog whose whitespace will\n" +"... be cleaned up and whose words will be wrapped\n" +"... across a couple lines''')\n" +">>> parser.print_help()\n" +"usage: PROG [-h]\n" +"\n" +"this description was indented weird but that is okay\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"\n" +"likewise for this epilog whose whitespace will be cleaned up and whose " +"words\n" +"will be wrapped across a couple lines" +msgstr "" +">>> parser = argparse.ArgumentParser(\n" +"... prog='PROG',\n" +"... description='''esta descrição\n" +"... foi indentada de forma estranha,\n" +"... mas está tudo bem''',\n" +"... epilog='''\n" +"... da mesma forma para este epílogo, cujos espaços vão\n" +"... ser apagados e cujas palavras serão quebradas\n" +"... em algumas linhas''')\n" +">>> parser.print_help()\n" +"usage: PROG [-h]\n" +"\n" +"this description was indented weird but that is okay\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"\n" +"da mesma forma para este epílogo, cujos espaços vão ser apagados e\n" +"cujas palavras serão quebradas em algumas linhas" + +#: ../../library/argparse.rst:311 msgid "" "Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=`` " "indicates that description_ and epilog_ are already correctly formatted and " @@ -687,10 +662,56 @@ msgstr "" "que description_ e epilog_ já estão formatados corretamente e não devem ter " "suas linhas quebradas::" -#: ../../library/argparse.rst:493 +#: ../../library/argparse.rst:315 +msgid "" +">>> parser = argparse.ArgumentParser(\n" +"... prog='PROG',\n" +"... formatter_class=argparse.RawDescriptionHelpFormatter,\n" +"... description=textwrap.dedent('''\\\n" +"... Please do not mess up this text!\n" +"... --------------------------------\n" +"... I have indented it\n" +"... exactly the way\n" +"... I want it\n" +"... '''))\n" +">>> parser.print_help()\n" +"usage: PROG [-h]\n" +"\n" +"Please do not mess up this text!\n" +"--------------------------------\n" +" I have indented it\n" +" exactly the way\n" +" I want it\n" +"\n" +"options:\n" +" -h, --help show this help message and exit" +msgstr "" +">>> parser = argparse.ArgumentParser(\n" +"... prog='PROG',\n" +"... formatter_class=argparse.RawDescriptionHelpFormatter,\n" +"... description=textwrap.dedent('''\\\n" +"... Por favor, não bagunce este texto!\n" +"... --------------------------------\n" +"... Eu indentei o texto\n" +"... exatamente na forma\n" +"... que quero que fique\n" +"... '''))\n" +">>> parser.print_help()\n" +"usage: PROG [-h]\n" +"\n" +"Por favor, não bagunce este texto!\n" +"--------------------------------\n" +" Eu indentei o texto\n" +" exatamente na forma\n" +" que quero que fique\n" +"\n" +"options:\n" +" -h, --help show this help message and exit" + +#: ../../library/argparse.rst:337 msgid "" ":class:`RawTextHelpFormatter` maintains whitespace for all sorts of help " -"text, including argument descriptions. However, multiple new lines are " +"text, including argument descriptions. However, multiple newlines are " "replaced with one. If you wish to preserve multiple blank lines, add spaces " "between the newlines." msgstr "" @@ -699,7 +720,7 @@ msgstr "" "novas linhas são substituídas por uma. Se você deseja preservar várias " "linhas em branco, adicione espaços entre as novas linhas." -#: ../../library/argparse.rst:498 +#: ../../library/argparse.rst:342 msgid "" ":class:`ArgumentDefaultsHelpFormatter` automatically adds information about " "default values to each of the argument help messages::" @@ -707,7 +728,39 @@ msgstr "" ":class:`ArgumentDefaultsHelpFormatter` adiciona automaticamente informações " "sobre os valores padrão para cada uma das mensagens de ajuda do argumento::" -#: ../../library/argparse.rst:516 +#: ../../library/argparse.rst:345 +msgid "" +">>> parser = argparse.ArgumentParser(\n" +"... prog='PROG',\n" +"... formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n" +">>> parser.add_argument('--foo', type=int, default=42, help='FOO!')\n" +">>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')\n" +">>> parser.print_help()\n" +"usage: PROG [-h] [--foo FOO] [bar ...]\n" +"\n" +"positional arguments:\n" +" bar BAR! (default: [1, 2, 3])\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo FOO FOO! (default: 42)" +msgstr "" +">>> parser = argparse.ArgumentParser(\n" +"... prog='PROG',\n" +"... formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n" +">>> parser.add_argument('--foo', type=int, default=42, help='FOO!')\n" +">>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')\n" +">>> parser.print_help()\n" +"usage: PROG [-h] [--foo FOO] [bar ...]\n" +"\n" +"positional arguments:\n" +" bar BAR! (default: [1, 2, 3])\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo FOO FOO! (default: 42)" + +#: ../../library/argparse.rst:360 msgid "" ":class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for " "each argument as the display name for its values (rather than using the " @@ -717,24 +770,70 @@ msgstr "" "argumento como o nome de exibição para seus valores (em vez de usar o dest_ " "como o formatador regular faz)::" -#: ../../library/argparse.rst:537 +#: ../../library/argparse.rst:364 +msgid "" +">>> parser = argparse.ArgumentParser(\n" +"... prog='PROG',\n" +"... formatter_class=argparse.MetavarTypeHelpFormatter)\n" +">>> parser.add_argument('--foo', type=int)\n" +">>> parser.add_argument('bar', type=float)\n" +">>> parser.print_help()\n" +"usage: PROG [-h] [--foo int] float\n" +"\n" +"positional arguments:\n" +" float\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo int" +msgstr "" +">>> parser = argparse.ArgumentParser(\n" +"... prog='PROG',\n" +"... formatter_class=argparse.MetavarTypeHelpFormatter)\n" +">>> parser.add_argument('--foo', type=int)\n" +">>> parser.add_argument('bar', type=float)\n" +">>> parser.print_help()\n" +"usage: PROG [-h] [--foo int] float\n" +"\n" +"positional arguments:\n" +" float\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo int" + +#: ../../library/argparse.rst:381 msgid "prefix_chars" msgstr "prefix_chars" -#: ../../library/argparse.rst:539 +#: ../../library/argparse.rst:383 msgid "" "Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``. " "Parsers that need to support different or additional prefix characters, e.g. " "for options like ``+f`` or ``/foo``, may specify them using the " -"``prefix_chars=`` argument to the ArgumentParser constructor::" +"``prefix_chars=`` argument to the :class:`ArgumentParser` constructor::" msgstr "" "A maioria das opções de linha de comando usará ``-`` como prefixo, por " "exemplo, ``-f/--foo``. Analisadores sintáticos que precisam ter suporte a " "caracteres de prefixo diferentes ou adicionais, por exemplo, para opções " "como ``+f`` ou ``/foo``, podem especificá-las usando o argumento " -"``prefix_chars=`` para o construtor ArgumentParser::" +"``prefix_chars=`` para o construtor :class:`ArgumentParser`::" -#: ../../library/argparse.rst:551 +#: ../../library/argparse.rst:389 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')\n" +">>> parser.add_argument('+f')\n" +">>> parser.add_argument('++bar')\n" +">>> parser.parse_args('+f X ++bar Y'.split())\n" +"Namespace(bar='Y', f='X')" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')\n" +">>> parser.add_argument('+f')\n" +">>> parser.add_argument('++bar')\n" +">>> parser.parse_args('+f X ++bar Y'.split())\n" +"Namespace(bar='Y', f='X')" + +#: ../../library/argparse.rst:395 msgid "" "The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of " "characters that does not include ``-`` will cause ``-f/--foo`` options to be " @@ -744,11 +843,11 @@ msgstr "" "conjunto de caracteres que não inclua ``-`` fará com que as opções ``-f/--" "foo`` não sejam permitidas." -#: ../../library/argparse.rst:557 +#: ../../library/argparse.rst:401 msgid "fromfile_prefix_chars" msgstr "fromfile_prefix_chars" -#: ../../library/argparse.rst:559 +#: ../../library/argparse.rst:403 msgid "" "Sometimes, when dealing with a particularly long argument list, it may make " "sense to keep the list of arguments in a file rather than typing it out at " @@ -764,7 +863,25 @@ msgstr "" "qualquer um dos caracteres especificados serão tratados como arquivos e " "serão substituídos pelos argumentos que eles contêm. Por exemplo::" -#: ../../library/argparse.rst:574 +#: ../../library/argparse.rst:410 +msgid "" +">>> with open('args.txt', 'w', encoding=sys.getfilesystemencoding()) as fp:\n" +"... fp.write('-f\\nbar')\n" +"...\n" +">>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')\n" +">>> parser.add_argument('-f')\n" +">>> parser.parse_args(['-f', 'foo', '@args.txt'])\n" +"Namespace(f='bar')" +msgstr "" +">>> with open('args.txt', 'w', encoding=sys.getfilesystemencoding()) as fp:\n" +"... fp.write('-f\\nbar')\n" +"...\n" +">>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')\n" +">>> parser.add_argument('-f')\n" +">>> parser.parse_args(['-f', 'foo', '@args.txt'])\n" +"Namespace(f='bar')" + +#: ../../library/argparse.rst:418 msgid "" "Arguments read from a file must by default be one per line (but see also :" "meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they " @@ -780,7 +897,7 @@ msgstr "" "f', 'foo', '@args.txt']`` é considerada equivalente à expressão ``['-f', " "'foo', '-f', 'bar']``." -#: ../../library/argparse.rst:580 +#: ../../library/argparse.rst:424 msgid "" ":class:`ArgumentParser` uses :term:`filesystem encoding and error handler` " "to read the file containing arguments." @@ -788,7 +905,7 @@ msgstr "" ":class:`ArgumentParser` usa :term:`tratador de erros e codificação do " "sistema de arquivos` para ler o arquivo que contém argumentos." -#: ../../library/argparse.rst:583 +#: ../../library/argparse.rst:427 msgid "" "The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that " "arguments will never be treated as file references." @@ -797,13 +914,13 @@ msgstr "" "significando que os argumentos nunca serão tratados como referências de " "arquivo." -#: ../../library/argparse.rst:586 +#: ../../library/argparse.rst:430 msgid "" ":class:`ArgumentParser` changed encoding and errors to read arguments files " "from default (e.g. :func:`locale.getpreferredencoding(False) ` and ``\"strict\"``) to :term:`filesystem encoding and " -"error handler`. Arguments file should be encoded in UTF-8 instead of ANSI " -"Codepage on Windows." +"getpreferredencoding>` and ``\"strict\"``) to the :term:`filesystem encoding " +"and error handler`. Arguments file should be encoded in UTF-8 instead of " +"ANSI Codepage on Windows." msgstr "" ":class:`ArgumentParser` alterou a codificação e os erros para ler arquivos " "de argumentos do padrão (por exemplo, :func:`locale." @@ -812,11 +929,11 @@ msgstr "" "arquivo de argumentos deve ser codificado em UTF-8 em vez de página de " "código ANSI no Windows." -#: ../../library/argparse.rst:594 +#: ../../library/argparse.rst:438 msgid "argument_default" msgstr "argument_default" -#: ../../library/argparse.rst:596 +#: ../../library/argparse.rst:440 msgid "" "Generally, argument defaults are specified either by passing a default to :" "meth:`~ArgumentParser.add_argument` or by calling the :meth:`~ArgumentParser." @@ -836,11 +953,29 @@ msgstr "" "para suprimir globalmente a criação de atributos em chamadas :meth:" "`~ArgumentParser.parse_args`, fornecemos ``argument_default=SUPPRESS``::" -#: ../../library/argparse.rst:616 +#: ../../library/argparse.rst:449 +msgid "" +">>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)\n" +">>> parser.add_argument('--foo')\n" +">>> parser.add_argument('bar', nargs='?')\n" +">>> parser.parse_args(['--foo', '1', 'BAR'])\n" +"Namespace(bar='BAR', foo='1')\n" +">>> parser.parse_args([])\n" +"Namespace()" +msgstr "" +">>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)\n" +">>> parser.add_argument('--foo')\n" +">>> parser.add_argument('bar', nargs='?')\n" +">>> parser.parse_args(['--foo', '1', 'BAR'])\n" +"Namespace(bar='BAR', foo='1')\n" +">>> parser.parse_args([])\n" +"Namespace()" + +#: ../../library/argparse.rst:460 msgid "allow_abbrev" msgstr "allow_abbrev" -#: ../../library/argparse.rst:618 +#: ../../library/argparse.rst:462 msgid "" "Normally, when you pass an argument list to the :meth:`~ArgumentParser." "parse_args` method of an :class:`ArgumentParser`, it :ref:`recognizes " @@ -850,17 +985,33 @@ msgstr "" "`~ArgumentParser.parse_args` de um :class:`ArgumentParser`, ele :ref:" "`reconhece as abreviações ` de opções longas." -#: ../../library/argparse.rst:622 +#: ../../library/argparse.rst:466 msgid "This feature can be disabled by setting ``allow_abbrev`` to ``False``::" msgstr "" "Este recurso pode ser desabilitado configurando ``allow_abbrev`` para " "``False``::" -#: ../../library/argparse.rst:635 +#: ../../library/argparse.rst:468 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)\n" +">>> parser.add_argument('--foobar', action='store_true')\n" +">>> parser.add_argument('--foonley', action='store_false')\n" +">>> parser.parse_args(['--foon'])\n" +"usage: PROG [-h] [--foobar] [--foonley]\n" +"PROG: error: unrecognized arguments: --foon" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)\n" +">>> parser.add_argument('--foobar', action='store_true')\n" +">>> parser.add_argument('--foonley', action='store_false')\n" +">>> parser.parse_args(['--foon'])\n" +"usage: PROG [-h] [--foobar] [--foonley]\n" +"PROG: error: unrecognized arguments: --foon" + +#: ../../library/argparse.rst:479 msgid "conflict_handler" msgstr "conflict_handler" -#: ../../library/argparse.rst:637 +#: ../../library/argparse.rst:481 msgid "" ":class:`ArgumentParser` objects do not allow two actions with the same " "option string. By default, :class:`ArgumentParser` objects raise an " @@ -872,7 +1023,23 @@ msgstr "" "se for feita uma tentativa de criar um argumento com uma string de opção que " "já esteja em uso::" -#: ../../library/argparse.rst:649 +#: ../../library/argparse.rst:486 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-f', '--foo', help='old foo help')\n" +">>> parser.add_argument('--foo', help='new foo help')\n" +"Traceback (most recent call last):\n" +" ..\n" +"ArgumentError: argument --foo: conflicting option string(s): --foo" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-f', '--foo', help='ajuda antiga de foo')\n" +">>> parser.add_argument('--foo', help='nova ajuda de foo')\n" +"Traceback (most recent call last):\n" +" ..\n" +"ArgumentError: argument --foo: conflicting option string(s): --foo" + +#: ../../library/argparse.rst:493 msgid "" "Sometimes (e.g. when using parents_) it may be useful to simply override any " "older arguments with the same option string. To get this behavior, the " @@ -884,7 +1051,33 @@ msgstr "" "Para obter este comportamento, o valor ``'resolve'`` pode ser fornecido ao " "argumento ``conflict_handler=`` de :class:`ArgumentParser`::" -#: ../../library/argparse.rst:665 +#: ../../library/argparse.rst:498 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG', " +"conflict_handler='resolve')\n" +">>> parser.add_argument('-f', '--foo', help='old foo help')\n" +">>> parser.add_argument('--foo', help='new foo help')\n" +">>> parser.print_help()\n" +"usage: PROG [-h] [-f FOO] [--foo FOO]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -f FOO old foo help\n" +" --foo FOO new foo help" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG', " +"conflict_handler='resolve')\n" +">>> parser.add_argument('-f', '--foo', help='ajuda antiga de foo')\n" +">>> parser.add_argument('--foo', help='nova ajuda de foo')\n" +">>> parser.print_help()\n" +"usage: PROG [-h] [-f FOO] [--foo FOO]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -f FOO ajuda antiga de foo\n" +" --foo FOO nova ajuda de foo" + +#: ../../library/argparse.rst:509 msgid "" "Note that :class:`ArgumentParser` objects only remove an action if all of " "its option strings are overridden. So, in the example above, the old ``-f/--" @@ -896,29 +1089,22 @@ msgstr "" "antiga ação ``-f/--foo`` é mantida como a ação ``-f``, porque apenas a " "string de opção ``--foo`` foi substituída." -#: ../../library/argparse.rst:672 +#: ../../library/argparse.rst:516 msgid "add_help" msgstr "add_help" -#: ../../library/argparse.rst:674 +#: ../../library/argparse.rst:518 msgid "" -"By default, ArgumentParser objects add an option which simply displays the " -"parser's help message. For example, consider a file named ``myprogram.py`` " -"containing the following code::" +"By default, :class:`ArgumentParser` objects add an option which simply " +"displays the parser's help message. If ``-h`` or ``--help`` is supplied at " +"the command line, the :class:`!ArgumentParser` help will be printed." msgstr "" -"Por padrão, os objetos ArgumentParser adicionam uma opção que simplesmente " -"exibe a mensagem de ajuda do analisador. Por exemplo, considere um arquivo " -"chamado ``myprogram.py`` contendo o seguinte código::" +"Por padrão, os objetos :class:`ArgumentParser` adicionam uma opção que " +"simplesmente exibe a mensagem de ajuda do analisador sintático. Se ``-h`` ou " +"``--help`` for fornecido na linha de comando, a ajuda do :class:`!" +"ArgumentParser` será exibida." -#: ../../library/argparse.rst:683 -msgid "" -"If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser " -"help will be printed:" -msgstr "" -"Se ``-h`` ou ``--help`` for fornecido na linha de comando, a ajuda do " -"ArgumentParser será impressa:" - -#: ../../library/argparse.rst:695 +#: ../../library/argparse.rst:522 msgid "" "Occasionally, it may be useful to disable the addition of this help option. " "This can be achieved by passing ``False`` as the ``add_help=`` argument to :" @@ -928,7 +1114,25 @@ msgstr "" "pode ser feito passando ``False`` como o argumento ``add_help=`` para a " "classe :class:`ArgumentParser`::" -#: ../../library/argparse.rst:707 +#: ../../library/argparse.rst:526 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)\n" +">>> parser.add_argument('--foo', help='foo help')\n" +">>> parser.print_help()\n" +"usage: PROG [--foo FOO]\n" +"\n" +"options:\n" +" --foo FOO foo help" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)\n" +">>> parser.add_argument('--foo', help='ajuda de foo')\n" +">>> parser.print_help()\n" +"usage: PROG [--foo FOO]\n" +"\n" +"options:\n" +" --foo FOO ajuda de foo" + +#: ../../library/argparse.rst:534 msgid "" "The help option is typically ``-h/--help``. The exception to this is if the " "``prefix_chars=`` is specified and does not include ``-``, in which case ``-" @@ -940,21 +1144,38 @@ msgstr "" "``--help`` não são opções válidas. Neste caso, o primeiro caractere em " "``prefix_chars`` é usado para prefixar as opções de ajuda::" -#: ../../library/argparse.rst:722 +#: ../../library/argparse.rst:540 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')\n" +">>> parser.print_help()\n" +"usage: PROG [+h]\n" +"\n" +"options:\n" +" +h, ++help show this help message and exit" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')\n" +">>> parser.print_help()\n" +"usage: PROG [+h]\n" +"\n" +"options:\n" +" +h, ++help show this help message and exit" + +#: ../../library/argparse.rst:549 msgid "exit_on_error" msgstr "exit_on_error" -#: ../../library/argparse.rst:724 +#: ../../library/argparse.rst:551 msgid "" "Normally, when you pass an invalid argument list to the :meth:" "`~ArgumentParser.parse_args` method of an :class:`ArgumentParser`, it will " -"exit with error info." +"print a *message* to :data:`sys.stderr` and exit with a status code of 2." msgstr "" "Normalmente, quando você passa uma lista de argumentos inválidos para o " -"método :meth:`~ArgumentParser.parse_args` de um :class:`ArgumentParser`, ele " -"sairá com informações de erro." +"método :meth:`~ArgumentParser.parse_args` de uma instância de :class:" +"`ArgumentParser`, ele vai exibir uma *message* para :data:`sys.stderr` e vai " +"sair com o código de status de 2." -#: ../../library/argparse.rst:727 +#: ../../library/argparse.rst:555 msgid "" "If the user would like to catch errors manually, the feature can be enabled " "by setting ``exit_on_error`` to ``False``::" @@ -962,11 +1183,37 @@ msgstr "" "Se o usuário quiser detectar erros manualmente, o recurso pode ser " "habilitado configurando ``exit_on_error`` para ``False``::" -#: ../../library/argparse.rst:744 +#: ../../library/argparse.rst:558 +msgid "" +">>> parser = argparse.ArgumentParser(exit_on_error=False)\n" +">>> parser.add_argument('--integers', type=int)\n" +"_StoreAction(option_strings=['--integers'], dest='integers', nargs=None, " +"const=None, default=None, type=, choices=None, help=None, " +"metavar=None)\n" +">>> try:\n" +"... parser.parse_args('--integers a'.split())\n" +"... except argparse.ArgumentError:\n" +"... print('Catching an argumentError')\n" +"...\n" +"Catching an argumentError" +msgstr "" +">>> parser = argparse.ArgumentParser(exit_on_error=False)\n" +">>> parser.add_argument('--integers', type=int)\n" +"_StoreAction(option_strings=['--integers'], dest='integers', nargs=None, " +"const=None, default=None, type=, choices=None, help=None, " +"metavar=None)\n" +">>> try:\n" +"... parser.parse_args('--integers a'.split())\n" +"... except argparse.ArgumentError:\n" +"... print('Capturando um argumentError')\n" +"...\n" +"Capturando um argumentError" + +#: ../../library/argparse.rst:572 msgid "The add_argument() method" msgstr "O método add_argument()" -#: ../../library/argparse.rst:750 +#: ../../library/argparse.rst:578 msgid "" "Define how a single command-line argument should be parsed. Each parameter " "has its own more detailed description below, but in short they are:" @@ -975,15 +1222,15 @@ msgstr "" "parâmetro tem sua própria descrição mais detalhada abaixo, mas resumidamente " "são eles:" -#: ../../library/argparse.rst:753 +#: ../../library/argparse.rst:581 msgid "" -"`name or flags`_ - Either a name or a list of option strings, e.g. ``foo`` " -"or ``-f, --foo``." +"`name or flags`_ - Either a name or a list of option strings, e.g. ``'foo'`` " +"or ``'-f', '--foo'``." msgstr "" "`name ou flags`_ - Um nome ou uma lista de strings de opções, por exemplo. " -"``foo`` ou ``-f, --foo``." +"``'foo'`` ou ``'-f', '--foo'``." -#: ../../library/argparse.rst:756 +#: ../../library/argparse.rst:584 msgid "" "action_ - The basic type of action to be taken when this argument is " "encountered at the command line." @@ -991,18 +1238,18 @@ msgstr "" "action_ - O tipo básico de ação a ser executada quando esse argumento é " "encontrado na linha de comando." -#: ../../library/argparse.rst:759 +#: ../../library/argparse.rst:587 msgid "nargs_ - The number of command-line arguments that should be consumed." msgstr "" "nargs_ - O número de argumentos de linha de comando que devem ser consumidos." -#: ../../library/argparse.rst:761 +#: ../../library/argparse.rst:589 msgid "" "const_ - A constant value required by some action_ and nargs_ selections." msgstr "" "const_ - Um valor constante exigido por algumas seleções action_ e nargs_." -#: ../../library/argparse.rst:763 +#: ../../library/argparse.rst:591 msgid "" "default_ - The value produced if the argument is absent from the command " "line and if it is absent from the namespace object." @@ -1010,18 +1257,18 @@ msgstr "" "default_ - O valor produzido se o argumento estiver ausente da linha de " "comando e se estiver ausente do objeto espaço de nomes." -#: ../../library/argparse.rst:766 +#: ../../library/argparse.rst:594 msgid "" "type_ - The type to which the command-line argument should be converted." msgstr "" "type_ - O tipo para o qual o argumento de linha de comando deve ser " "convertido." -#: ../../library/argparse.rst:768 +#: ../../library/argparse.rst:596 msgid "choices_ - A sequence of the allowable values for the argument." msgstr "choices_ - Uma sequência dos valores permitidos para o argumento." -#: ../../library/argparse.rst:770 +#: ../../library/argparse.rst:598 msgid "" "required_ - Whether or not the command-line option may be omitted (optionals " "only)." @@ -1029,15 +1276,15 @@ msgstr "" "required_ - Se a opção de linha de comando pode ou não ser omitida (somente " "opcionais)." -#: ../../library/argparse.rst:773 +#: ../../library/argparse.rst:601 msgid "help_ - A brief description of what the argument does." msgstr "help_ - Uma breve descrição do que o argumento faz." -#: ../../library/argparse.rst:775 +#: ../../library/argparse.rst:603 msgid "metavar_ - A name for the argument in usage messages." msgstr "metavar_ - Um nome para o argumento nas mensagens de uso." -#: ../../library/argparse.rst:777 +#: ../../library/argparse.rst:605 msgid "" "dest_ - The name of the attribute to be added to the object returned by :" "meth:`parse_args`." @@ -1045,15 +1292,15 @@ msgstr "" "dest_ - O nome do atributo a ser adicionado ao objeto retornado por :meth:" "`parse_args`." -#: ../../library/argparse.rst:780 +#: ../../library/argparse.rst:608 msgid "deprecated_ - Whether or not use of the argument is deprecated." msgstr "deprecated_ - Se o uso do argumento foi descontinuado ou não." -#: ../../library/argparse.rst:788 +#: ../../library/argparse.rst:616 msgid "name or flags" msgstr "name ou flags" -#: ../../library/argparse.rst:790 +#: ../../library/argparse.rst:618 msgid "" "The :meth:`~ArgumentParser.add_argument` method must know whether an " "optional argument, like ``-f`` or ``--foo``, or a positional argument, like " @@ -1063,19 +1310,27 @@ msgid "" msgstr "" "O método :meth:`~ArgumentParser.add_argument` deve saber se um argumento " "opcional, como ``-f`` ou ``--foo``, ou um argumento posicional, como uma " -"lista de nomes de arquivos, é esperado. Os primeiros argumentos passados ​​" +"lista de nomes de arquivos, é esperado. Os primeiros argumentos passados " "para :meth:`~ArgumentParser.add_argument` devem, portanto, ser uma série de " "sinalizadores ou um simples nome de argumento." -#: ../../library/argparse.rst:796 +#: ../../library/argparse.rst:624 msgid "For example, an optional argument could be created like::" msgstr "Por exemplo, um argumento opcional poderia ser criado como::" -#: ../../library/argparse.rst:800 +#: ../../library/argparse.rst:626 +msgid ">>> parser.add_argument('-f', '--foo')" +msgstr ">>> parser.add_argument('-f', '--foo')" + +#: ../../library/argparse.rst:628 msgid "while a positional argument could be created like::" msgstr "enquanto um argumento posicional pode ser criado como::" -#: ../../library/argparse.rst:804 +#: ../../library/argparse.rst:630 +msgid ">>> parser.add_argument('bar')" +msgstr ">>> parser.add_argument('bar')" + +#: ../../library/argparse.rst:632 msgid "" "When :meth:`~ArgumentParser.parse_args` is called, optional arguments will " "be identified by the ``-`` prefix, and the remaining arguments will be " @@ -1085,11 +1340,35 @@ msgstr "" "serão identificados pelo prefixo ``-``, e os argumentos restantes serão " "considerados posicionais::" -#: ../../library/argparse.rst:823 +#: ../../library/argparse.rst:636 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-f', '--foo')\n" +">>> parser.add_argument('bar')\n" +">>> parser.parse_args(['BAR'])\n" +"Namespace(bar='BAR', foo=None)\n" +">>> parser.parse_args(['BAR', '--foo', 'FOO'])\n" +"Namespace(bar='BAR', foo='FOO')\n" +">>> parser.parse_args(['--foo', 'FOO'])\n" +"usage: PROG [-h] [-f FOO] bar\n" +"PROG: error: the following arguments are required: bar" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-f', '--foo')\n" +">>> parser.add_argument('bar')\n" +">>> parser.parse_args(['BAR'])\n" +"Namespace(bar='BAR', foo=None)\n" +">>> parser.parse_args(['BAR', '--foo', 'FOO'])\n" +"Namespace(bar='BAR', foo='FOO')\n" +">>> parser.parse_args(['--foo', 'FOO'])\n" +"usage: PROG [-h] [-f FOO] bar\n" +"PROG: error: the following arguments are required: bar" + +#: ../../library/argparse.rst:651 msgid "action" -msgstr "action" +msgstr "ação" -#: ../../library/argparse.rst:825 +#: ../../library/argparse.rst:653 msgid "" ":class:`ArgumentParser` objects associate command-line arguments with " "actions. These actions can do just about anything with the command-line " @@ -1106,15 +1385,15 @@ msgstr "" "os argumentos da linha de comando devem ser tratados. As ações fornecidas " "são:" -#: ../../library/argparse.rst:831 +#: ../../library/argparse.rst:659 msgid "" "``'store'`` - This just stores the argument's value. This is the default " -"action. For example::" +"action." msgstr "" "``'store'`` - Isso apenas armazena o valor do argumento. Esta é a ação " -"padrão. Por exemplo::" +"padrão." -#: ../../library/argparse.rst:839 +#: ../../library/argparse.rst:662 msgid "" "``'store_const'`` - This stores the value specified by the const_ keyword " "argument; note that the const_ keyword argument defaults to ``None``. The " @@ -1126,19 +1405,47 @@ msgstr "" "``None``. A ação ``'store_const'`` é mais comumente usada com argumentos " "opcionais que especificam algum tipo de sinalizador. Por exemplo::" -#: ../../library/argparse.rst:849 +#: ../../library/argparse.rst:667 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action='store_const', const=42)\n" +">>> parser.parse_args(['--foo'])\n" +"Namespace(foo=42)" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action='store_const', const=42)\n" +">>> parser.parse_args(['--foo'])\n" +"Namespace(foo=42)" + +#: ../../library/argparse.rst:672 msgid "" "``'store_true'`` and ``'store_false'`` - These are special cases of " "``'store_const'`` used for storing the values ``True`` and ``False`` " "respectively. In addition, they create default values of ``False`` and " -"``True`` respectively. For example::" +"``True`` respectively::" msgstr "" "``'store_true'`` e ``'store_false'`` - Estes são casos especiais de " "``'store_const'`` usados para armazenar os valores ``True`` e ``False`` " "respectivamente. Além disso, eles criam valores padrão de ``False`` e " -"``True`` respectivamente. Por exemplo::" +"``True`` respectivamente." -#: ../../library/argparse.rst:861 +#: ../../library/argparse.rst:677 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action='store_true')\n" +">>> parser.add_argument('--bar', action='store_false')\n" +">>> parser.add_argument('--baz', action='store_false')\n" +">>> parser.parse_args('--foo --bar'.split())\n" +"Namespace(foo=True, bar=False, baz=True)" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action='store_true')\n" +">>> parser.add_argument('--bar', action='store_false')\n" +">>> parser.add_argument('--baz', action='store_false')\n" +">>> parser.parse_args('--foo --bar'.split())\n" +"Namespace(foo=True, bar=False, baz=True)" + +#: ../../library/argparse.rst:684 msgid "" "``'append'`` - This stores a list, and appends each argument value to the " "list. It is useful to allow an option to be specified multiple times. If the " @@ -1152,7 +1459,19 @@ msgstr "" "valor analisado da opção, com quaisquer valores da linha de comando anexados " "após esses valores padrão. Exemplo de uso::" -#: ../../library/argparse.rst:872 +#: ../../library/argparse.rst:690 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action='append')\n" +">>> parser.parse_args('--foo 1 --foo 2'.split())\n" +"Namespace(foo=['1', '2'])" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action='append')\n" +">>> parser.parse_args('--foo 1 --foo 2'.split())\n" +"Namespace(foo=['1', '2'])" + +#: ../../library/argparse.rst:695 msgid "" "``'append_const'`` - This stores a list, and appends the value specified by " "the const_ keyword argument to the list; note that the const_ keyword " @@ -1166,7 +1485,55 @@ msgstr "" "útil quando vários argumentos precisam armazenar constantes na mesma lista. " "Por exemplo::" -#: ../../library/argparse.rst:884 +#: ../../library/argparse.rst:701 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--str', dest='types', action='append_const', " +"const=str)\n" +">>> parser.add_argument('--int', dest='types', action='append_const', " +"const=int)\n" +">>> parser.parse_args('--str --int'.split())\n" +"Namespace(types=[, ])" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--str', dest='types', action='append_const', " +"const=str)\n" +">>> parser.add_argument('--int', dest='types', action='append_const', " +"const=int)\n" +">>> parser.parse_args('--str --int'.split())\n" +"Namespace(types=[, ])" + +#: ../../library/argparse.rst:707 +msgid "" +"``'extend'`` - This stores a list and appends each item from the multi-value " +"argument list to it. The ``'extend'`` action is typically used with the " +"nargs_ keyword argument value ``'+'`` or ``'*'``. Note that when nargs_ is " +"``None`` (the default) or ``'?'``, each character of the argument string " +"will be appended to the list. Example usage::" +msgstr "" +"``'extend'`` - Isso armazena uma lista e anexa cada item da lista de " +"argumentos multivalorada a ela. A ação ``'extend'`` é normalmente usada com " +"o valor do argumento nomeado nargs_ ``'+'`` ou ``'*'``. Observe que quando " +"nargs_ é ``None`` (o padrão) ou ``'?'``, cada caractere da string do " +"argumento será anexado à lista. Exemplo de uso::" + +#: ../../library/argparse.rst:715 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument(\"--foo\", action=\"extend\", nargs=\"+\", " +"type=str)\n" +">>> parser.parse_args([\"--foo\", \"f1\", \"--foo\", \"f2\", \"f3\", " +"\"f4\"])\n" +"Namespace(foo=['f1', 'f2', 'f3', 'f4'])" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument(\"--foo\", action=\"extend\", nargs=\"+\", " +"type=str)\n" +">>> parser.parse_args([\"--foo\", \"f1\", \"--foo\", \"f2\", \"f3\", " +"\"f4\"])\n" +"Namespace(foo=['f1', 'f2', 'f3', 'f4'])" + +#: ../../library/argparse.rst:722 msgid "" "``'count'`` - This counts the number of times a keyword argument occurs. For " "example, this is useful for increasing verbosity levels::" @@ -1174,13 +1541,25 @@ msgstr "" "``'count'`` - Isso conta o número de vezes que um argumento nomeado ocorre. " "Por exemplo, isso é útil para aumentar os níveis de verbosidade::" -#: ../../library/argparse.rst:892 +#: ../../library/argparse.rst:725 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--verbose', '-v', action='count', default=0)\n" +">>> parser.parse_args(['-vvv'])\n" +"Namespace(verbose=3)" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--verbose', '-v', action='count', default=0)\n" +">>> parser.parse_args(['-vvv'])\n" +"Namespace(verbose=3)" + +#: ../../library/argparse.rst:730 msgid "Note, the *default* will be ``None`` unless explicitly set to *0*." msgstr "" "Observe que o *padrão* será ``None``, a menos que seja explicitamente " "definido como *0*." -#: ../../library/argparse.rst:894 +#: ../../library/argparse.rst:732 msgid "" "``'help'`` - This prints a complete help message for all the options in the " "current parser and then exits. By default a help action is automatically " @@ -1192,7 +1571,7 @@ msgstr "" "adicionada automaticamente ao analisador sintático. Veja :class:" "`ArgumentParser` para detalhes de como a saída é criada." -#: ../../library/argparse.rst:899 +#: ../../library/argparse.rst:737 msgid "" "``'version'`` - This expects a ``version=`` keyword argument in the :meth:" "`~ArgumentParser.add_argument` call, and prints version information and " @@ -1202,62 +1581,136 @@ msgstr "" "meth:`~ArgumentParser.add_argument` e imprime informações de versão e sai " "quando invocado::" -#: ../../library/argparse.rst:909 +#: ../../library/argparse.rst:741 msgid "" -"``'extend'`` - This stores a list, and extends each argument value to the " -"list. Example usage::" +">>> import argparse\n" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('--version', action='version', version='%(prog)s " +"2.0')\n" +">>> parser.parse_args(['--version'])\n" +"PROG 2.0" msgstr "" -"``'extend'`` - Isso armazena uma lista e estende cada valor de argumento " -"para a lista. Exemplo de uso::" +">>> import argparse\n" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('--version', action='version', version='%(prog)s " +"2.0')\n" +">>> parser.parse_args(['--version'])\n" +"PROG 2.0" -#: ../../library/argparse.rst:920 +#: ../../library/argparse.rst:747 msgid "" -"You may also specify an arbitrary action by passing an Action subclass or " -"other object that implements the same interface. The " -"``BooleanOptionalAction`` is available in ``argparse`` and adds support for " +"Only actions that consume command-line arguments (e.g. ``'store'``, " +"``'append'`` or ``'extend'``) can be used with positional arguments." +msgstr "" +"Somente ações que consomem argumentos de linha de comando (por exemplo, " +"``'store'``, ``'append'`` ou ``'extend'``) podem ser usadas com argumentos " +"posicionais." + +#: ../../library/argparse.rst:752 +msgid "" +"You may also specify an arbitrary action by passing an :class:`Action` " +"subclass or other object that implements the same interface. The :class:`!" +"BooleanOptionalAction` is available in :mod:`!argparse` and adds support for " "boolean actions such as ``--foo`` and ``--no-foo``::" msgstr "" -"Você também pode especificar uma ação arbitrária passando uma subclasse " -"Action ou outro objeto que implemente a mesma interface. O " -"``BooleanOptionalAction`` está disponível em ``argparse`` e adiciona suporte " -"para ações booleanas como ``--foo`` e ``--no-foo``::" +"Você também pode especificar uma ação arbitrária passando uma subclasse :" +"class:`Action` ou outro objeto que implemente a mesma interface. O :class:`!" +"BooleanOptionalAction` está disponível em :mod:`!argparse` e adiciona " +"suporte para ações booleanas como ``--foo`` e ``--no-foo``::" + +#: ../../library/argparse.rst:757 +msgid "" +">>> import argparse\n" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)\n" +">>> parser.parse_args(['--no-foo'])\n" +"Namespace(foo=False)" +msgstr "" +">>> import argparse\n" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)\n" +">>> parser.parse_args(['--no-foo'])\n" +"Namespace(foo=False)" -#: ../../library/argparse.rst:933 +#: ../../library/argparse.rst:765 msgid "" "The recommended way to create a custom action is to extend :class:`Action`, " -"overriding the ``__call__`` method and optionally the ``__init__`` and " -"``format_usage`` methods." +"overriding the :meth:`!__call__` method and optionally the :meth:`!__init__` " +"and :meth:`!format_usage` methods. You can also register custom actions " +"using the :meth:`~ArgumentParser.register` method and reference them by " +"their registered name." msgstr "" "A maneira recomendada de criar uma ação personalizada é estender :class:" -"`Action`, substituindo o método ``__call__`` e opcionalmente os métodos " -"``__init__`` e ``format_usage``." +"`Action`, substituindo o método :meth:`!__call__` e opcionalmente os " +"métodos :meth:`!__init__` e :meth:`!format_usage`. Você também pode " +"registrar ações personalizadas usando o método :meth:`~ArgumentParser." +"register` e referenciá-las pelo nome registrado." -#: ../../library/argparse.rst:937 +#: ../../library/argparse.rst:770 msgid "An example of a custom action::" msgstr "Um exemplo de uma ação personalizada::" -#: ../../library/argparse.rst:957 +#: ../../library/argparse.rst:772 +msgid "" +">>> class FooAction(argparse.Action):\n" +"... def __init__(self, option_strings, dest, nargs=None, **kwargs):\n" +"... if nargs is not None:\n" +"... raise ValueError(\"nargs not allowed\")\n" +"... super().__init__(option_strings, dest, **kwargs)\n" +"... def __call__(self, parser, namespace, values, option_string=None):\n" +"... print('%r %r %r' % (namespace, values, option_string))\n" +"... setattr(namespace, self.dest, values)\n" +"...\n" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action=FooAction)\n" +">>> parser.add_argument('bar', action=FooAction)\n" +">>> args = parser.parse_args('1 --foo 2'.split())\n" +"Namespace(bar=None, foo=None) '1' None\n" +"Namespace(bar='1', foo=None) '2' '--foo'\n" +">>> args\n" +"Namespace(bar='1', foo='2')" +msgstr "" +">>> class FooAction(argparse.Action):\n" +"... def __init__(self, option_strings, dest, nargs=None, **kwargs):\n" +"... if nargs is not None:\n" +"... raise ValueError(\"nargs not allowed\")\n" +"... super().__init__(option_strings, dest, **kwargs)\n" +"... def __call__(self, parser, namespace, values, option_string=None):\n" +"... print('%r %r %r' % (namespace, values, option_string))\n" +"... setattr(namespace, self.dest, values)\n" +"...\n" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action=FooAction)\n" +">>> parser.add_argument('bar', action=FooAction)\n" +">>> args = parser.parse_args('1 --foo 2'.split())\n" +"Namespace(bar=None, foo=None) '1' None\n" +"Namespace(bar='1', foo=None) '2' '--foo'\n" +">>> args\n" +"Namespace(bar='1', foo='2')" + +#: ../../library/argparse.rst:790 msgid "For more details, see :class:`Action`." msgstr "Para mais detalhes, veja :class:`Action`." -#: ../../library/argparse.rst:963 +#: ../../library/argparse.rst:796 msgid "nargs" msgstr "nargs" -#: ../../library/argparse.rst:965 +#: ../../library/argparse.rst:798 msgid "" -"ArgumentParser objects usually associate a single command-line argument with " -"a single action to be taken. The ``nargs`` keyword argument associates a " -"different number of command-line arguments with a single action. See also :" -"ref:`specifying-ambiguous-arguments`. The supported values are:" +":class:`ArgumentParser` objects usually associate a single command-line " +"argument with a single action to be taken. The ``nargs`` keyword argument " +"associates a different number of command-line arguments with a single " +"action. See also :ref:`specifying-ambiguous-arguments`. The supported values " +"are:" msgstr "" -"Os objetos ArgumentParser geralmente associam um único argumento de linha de " -"comando a uma única ação a ser executada. O argumento nomeado ``nargs`` " -"associa um número diferente de argumentos de linha de comando com uma única " -"ação. Veja também :ref:`specifying-ambiguous-arguments`. Os valores " -"suportados são:" +"Os objetos :class:`ArgumentParser` geralmente associam um único argumento de " +"linha de comando a uma única ação a ser executada. O argumento nomeado " +"``nargs`` associa um número diferente de argumentos de linha de comando com " +"uma única ação. Veja também :ref:`specifying-ambiguous-arguments`. Os " +"valores suportados são:" -#: ../../library/argparse.rst:970 +#: ../../library/argparse.rst:803 msgid "" "``N`` (an integer). ``N`` arguments from the command line will be gathered " "together into a list. For example::" @@ -1265,7 +1718,21 @@ msgstr "" "``N`` (um inteiro). Os argumentos ``N`` da linha de comando serão reunidos " "em uma lista. Por exemplo::" -#: ../../library/argparse.rst:979 +#: ../../library/argparse.rst:806 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', nargs=2)\n" +">>> parser.add_argument('bar', nargs=1)\n" +">>> parser.parse_args('c --foo a b'.split())\n" +"Namespace(bar=['c'], foo=['a', 'b'])" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', nargs=2)\n" +">>> parser.add_argument('bar', nargs=1)\n" +">>> parser.parse_args('c --foo a b'.split())\n" +"Namespace(bar=['c'], foo=['a', 'b'])" + +#: ../../library/argparse.rst:812 msgid "" "Note that ``nargs=1`` produces a list of one item. This is different from " "the default, in which the item is produced by itself." @@ -1273,7 +1740,7 @@ msgstr "" "Observe que ``nargs=1`` produz uma lista de um item. Isso é diferente do " "padrão, em que o item é produzido sozinho." -#: ../../library/argparse.rst:984 +#: ../../library/argparse.rst:817 msgid "" "``'?'``. One argument will be consumed from the command line if possible, " "and produced as a single item. If no command-line argument is present, the " @@ -1289,7 +1756,29 @@ msgstr "" "presente, mas não é seguida por um argumento de linha de comando. Neste caso " "o valor de const_ será produzido. Alguns exemplos para ilustrar isso::" -#: ../../library/argparse.rst:1001 +#: ../../library/argparse.rst:824 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', nargs='?', const='c', default='d')\n" +">>> parser.add_argument('bar', nargs='?', default='d')\n" +">>> parser.parse_args(['XX', '--foo', 'YY'])\n" +"Namespace(bar='XX', foo='YY')\n" +">>> parser.parse_args(['XX', '--foo'])\n" +"Namespace(bar='XX', foo='c')\n" +">>> parser.parse_args([])\n" +"Namespace(bar='d', foo='d')" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', nargs='?', const='c', default='d')\n" +">>> parser.add_argument('bar', nargs='?', default='d')\n" +">>> parser.parse_args(['XX', '--foo', 'YY'])\n" +"Namespace(bar='XX', foo='YY')\n" +">>> parser.parse_args(['XX', '--foo'])\n" +"Namespace(bar='XX', foo='c')\n" +">>> parser.parse_args([])\n" +"Namespace(bar='d', foo='d')" + +#: ../../library/argparse.rst:834 msgid "" "One of the more common uses of ``nargs='?'`` is to allow optional input and " "output files::" @@ -1297,7 +1786,33 @@ msgstr "" "Um dos usos mais comuns de ``nargs='?'`` é permitir arquivos de entrada e " "saída opcionais::" -#: ../../library/argparse.rst:1018 +#: ../../library/argparse.rst:837 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),\n" +"... default=sys.stdin)\n" +">>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),\n" +"... default=sys.stdout)\n" +">>> parser.parse_args(['input.txt', 'output.txt'])\n" +"Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,\n" +" outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)\n" +">>> parser.parse_args([])\n" +"Namespace(infile=<_io.TextIOWrapper name='' encoding='UTF-8'>,\n" +" outfile=<_io.TextIOWrapper name='' encoding='UTF-8'>)" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),\n" +"... default=sys.stdin)\n" +">>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),\n" +"... default=sys.stdout)\n" +">>> parser.parse_args(['input.txt', 'output.txt'])\n" +"Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,\n" +" outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)\n" +">>> parser.parse_args([])\n" +"Namespace(infile=<_io.TextIOWrapper name='' encoding='UTF-8'>,\n" +" outfile=<_io.TextIOWrapper name='' encoding='UTF-8'>)" + +#: ../../library/argparse.rst:851 msgid "" "``'*'``. All command-line arguments present are gathered into a list. Note " "that it generally doesn't make much sense to have more than one positional " @@ -1309,7 +1824,23 @@ msgstr "" "argumento posicional com ``nargs='*'``, mas vários argumentos opcionais com " "``nargs='*'`` são possíveis. Por exemplo::" -#: ../../library/argparse.rst:1032 +#: ../../library/argparse.rst:856 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', nargs='*')\n" +">>> parser.add_argument('--bar', nargs='*')\n" +">>> parser.add_argument('baz', nargs='*')\n" +">>> parser.parse_args('a b --foo x y --bar 1 2'.split())\n" +"Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', nargs='*')\n" +">>> parser.add_argument('--bar', nargs='*')\n" +">>> parser.add_argument('baz', nargs='*')\n" +">>> parser.parse_args('a b --foo x y --bar 1 2'.split())\n" +"Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])" + +#: ../../library/argparse.rst:865 msgid "" "``'+'``. Just like ``'*'``, all command-line args present are gathered into " "a list. Additionally, an error message will be generated if there wasn't at " @@ -1320,23 +1851,43 @@ msgstr "" "gerada se não houver pelo menos um argumento de linha de comando presente. " "Por exemplo::" -#: ../../library/argparse.rst:1044 +#: ../../library/argparse.rst:869 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('foo', nargs='+')\n" +">>> parser.parse_args(['a', 'b'])\n" +"Namespace(foo=['a', 'b'])\n" +">>> parser.parse_args([])\n" +"usage: PROG [-h] foo [foo ...]\n" +"PROG: error: the following arguments are required: foo" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('foo', nargs='+')\n" +">>> parser.parse_args(['a', 'b'])\n" +"Namespace(foo=['a', 'b'])\n" +">>> parser.parse_args([])\n" +"usage: PROG [-h] foo [foo ...]\n" +"PROG: error: the following arguments are required: foo" + +#: ../../library/argparse.rst:877 msgid "" "If the ``nargs`` keyword argument is not provided, the number of arguments " "consumed is determined by the action_. Generally this means a single " "command-line argument will be consumed and a single item (not a list) will " -"be produced." +"be produced. Actions that do not consume command-line arguments (e.g. " +"``'store_const'``) set ``nargs=0``." msgstr "" "Se o argumento nomeado ``nargs`` não for fornecido, o número de argumentos " -"consumidos é determinado pela action_. Geralmente, isso significa que um " -"único argumento de linha de comando será consumido e um único item (não uma " -"lista) será produzido." +"consumidos é determinado por action_. Geralmente, isso significa que um " +"único argumento de linha de comando será usado e um único item (não uma " +"lista) será produzido. Ações que não fazem uso de argumentos da linha de " +"comando (por exemplo, ``'store_const'``) definem ``nargs=0``." -#: ../../library/argparse.rst:1052 +#: ../../library/argparse.rst:887 msgid "const" msgstr "const" -#: ../../library/argparse.rst:1054 +#: ../../library/argparse.rst:889 msgid "" "The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to " "hold constant values that are not read from the command line but are " @@ -1348,7 +1899,7 @@ msgstr "" "necessários para as várias ações :class:`ArgumentParser`. Os dois usos mais " "comuns são:" -#: ../../library/argparse.rst:1058 +#: ../../library/argparse.rst:893 msgid "" "When :meth:`~ArgumentParser.add_argument` is called with " "``action='store_const'`` or ``action='append_const'``. These actions add " @@ -1364,7 +1915,7 @@ msgstr "" "exemplos. Se ``const`` não for fornecido :meth:`~ArgumentParser." "add_argument`, será recebido um valor padrão de ``None``." -#: ../../library/argparse.rst:1066 +#: ../../library/argparse.rst:901 msgid "" "When :meth:`~ArgumentParser.add_argument` is called with option strings " "(like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional " @@ -1380,7 +1931,7 @@ msgstr "" "argumento de linha de comando seguindo, o valor de ``const`` será presumido " "como sendo ``None``. Veja a descrição de nargs_ para exemplos." -#: ../../library/argparse.rst:1073 +#: ../../library/argparse.rst:908 msgid "" "``const=None`` by default, including when ``action='append_const'`` or " "``action='store_const'``." @@ -1388,11 +1939,11 @@ msgstr "" "``const=None`` por padrão, incluindo quando ``action='append_const'`` ou " "``action='store_const'``." -#: ../../library/argparse.rst:1080 +#: ../../library/argparse.rst:915 msgid "default" msgstr "default" -#: ../../library/argparse.rst:1082 +#: ../../library/argparse.rst:917 msgid "" "All optional arguments and some positional arguments may be omitted at the " "command line. The ``default`` keyword argument of :meth:`~ArgumentParser." @@ -1408,15 +1959,43 @@ msgstr "" "presente. Para argumentos opcionais, o valor ``default`` é usado quando a " "string de opção não estava presente na linha de comando::" -#: ../../library/argparse.rst:1096 +#: ../../library/argparse.rst:924 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', default=42)\n" +">>> parser.parse_args(['--foo', '2'])\n" +"Namespace(foo='2')\n" +">>> parser.parse_args([])\n" +"Namespace(foo=42)" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', default=42)\n" +">>> parser.parse_args(['--foo', '2'])\n" +"Namespace(foo='2')\n" +">>> parser.parse_args([])\n" +"Namespace(foo=42)" + +#: ../../library/argparse.rst:931 msgid "" "If the target namespace already has an attribute set, the action *default* " -"will not over write it::" +"will not overwrite it::" msgstr "" "Se o espaço de nomes de destino já tiver um atributo definido, a ação " "*default* não o substituirá::" -#: ../../library/argparse.rst:1104 +#: ../../library/argparse.rst:934 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', default=42)\n" +">>> parser.parse_args([], namespace=argparse.Namespace(foo=101))\n" +"Namespace(foo=101)" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', default=42)\n" +">>> parser.parse_args([], namespace=argparse.Namespace(foo=101))\n" +"Namespace(foo=101)" + +#: ../../library/argparse.rst:939 msgid "" "If the ``default`` value is a string, the parser parses the value as if it " "were a command-line argument. In particular, the parser applies any type_ " @@ -1429,7 +2008,21 @@ msgstr "" "atributo no valor de retorno :class:`Namespace`. Caso contrário, o " "analisador usa o valor como está::" -#: ../../library/argparse.rst:1115 +#: ../../library/argparse.rst:944 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--length', default='10', type=int)\n" +">>> parser.add_argument('--width', default=10.5, type=int)\n" +">>> parser.parse_args()\n" +"Namespace(length=10, width=10.5)" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--length', default='10', type=int)\n" +">>> parser.add_argument('--width', default=10.5, type=int)\n" +">>> parser.parse_args()\n" +"Namespace(length=10, width=10.5)" + +#: ../../library/argparse.rst:950 msgid "" "For positional arguments with nargs_ equal to ``?`` or ``*``, the " "``default`` value is used when no command-line argument was present::" @@ -1438,7 +2031,34 @@ msgstr "" "``default`` é usado quando nenhum argumento de linha de comando estava " "presente::" -#: ../../library/argparse.rst:1126 +#: ../../library/argparse.rst:953 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('foo', nargs='?', default=42)\n" +">>> parser.parse_args(['a'])\n" +"Namespace(foo='a')\n" +">>> parser.parse_args([])\n" +"Namespace(foo=42)" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('foo', nargs='?', default=42)\n" +">>> parser.parse_args(['a'])\n" +"Namespace(foo='a')\n" +">>> parser.parse_args([])\n" +"Namespace(foo=42)" + +#: ../../library/argparse.rst:960 +msgid "" +"For required_ arguments, the ``default`` value is ignored. For example, this " +"applies to positional arguments with nargs_ values other than ``?`` or " +"``*``, or optional arguments marked as ``required=True``." +msgstr "" +"Para argumentos obrigatórios, isto é, marcados com required_, o valor " +"``default`` é ignorado. Por exemplo, isso se aplica a argumentos posicionais " +"com valores de nargs_ diferentes de ``?`` ou ``*``, ou argumentos opcionais " +"marcados como ``required=True``." + +#: ../../library/argparse.rst:964 msgid "" "Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if " "the command-line argument was not present::" @@ -1446,11 +2066,27 @@ msgstr "" "Fornecer ``default=argparse.SUPPRESS`` faz com que nenhum atributo seja " "adicionado se o argumento da linha de comando não estiver presente::" -#: ../../library/argparse.rst:1140 +#: ../../library/argparse.rst:967 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', default=argparse.SUPPRESS)\n" +">>> parser.parse_args([])\n" +"Namespace()\n" +">>> parser.parse_args(['--foo', '1'])\n" +"Namespace(foo='1')" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', default=argparse.SUPPRESS)\n" +">>> parser.parse_args([])\n" +"Namespace()\n" +">>> parser.parse_args(['--foo', '1'])\n" +"Namespace(foo='1')" + +#: ../../library/argparse.rst:978 msgid "type" -msgstr "type" +msgstr "tipo" -#: ../../library/argparse.rst:1142 +#: ../../library/argparse.rst:980 msgid "" "By default, the parser reads command-line arguments in as simple strings. " "However, quite often the command-line string should instead be interpreted " @@ -1465,7 +2101,7 @@ msgstr "" "que qualquer verificação de tipo e conversões de tipo necessárias sejam " "realizadas." -#: ../../library/argparse.rst:1148 +#: ../../library/argparse.rst:986 msgid "" "If the type_ keyword is used with the default_ keyword, the type converter " "is only applied if the default is a string." @@ -1473,28 +2109,74 @@ msgstr "" "Se o argumento nomeado type_ for usado com default_, o conversor de tipo só " "será aplicado se o padrão for uma string." -#: ../../library/argparse.rst:1151 +#: ../../library/argparse.rst:989 msgid "" -"The argument to ``type`` can be any callable that accepts a single string. " -"If the function raises :exc:`ArgumentTypeError`, :exc:`TypeError`, or :exc:" +"The argument to ``type`` can be a callable that accepts a single string or " +"the name of a registered type (see :meth:`~ArgumentParser.register`) If the " +"function raises :exc:`ArgumentTypeError`, :exc:`TypeError`, or :exc:" "`ValueError`, the exception is caught and a nicely formatted error message " -"is displayed. No other exception types are handled." +"is displayed. Other exception types are not handled." msgstr "" -"O argumento para ``type`` pode ser qualquer chamável que aceite uma única " -"string. Se a função levantar :exc:`ArgumentTypeError`, :exc:`TypeError` ou :" -"exc:`ValueError`, a exceção será capturada e uma mensagem de erro bem " -"formatada será exibida. Nenhum outro tipo de exceção é tratado." +"O argumento para ``type`` pode ser um chamável que aceite uma única string " +"ou o nome de um tipo registrado (veja :meth:`~ArgumentParser.register`). Se " +"a função levantar :exc:`ArgumentTypeError`, :exc:`TypeError` ou :exc:" +"`ValueError`, a exceção será capturada e uma mensagem de erro bem formatada " +"será exibida. Nenhum outro tipo de exceção é tratado." -#: ../../library/argparse.rst:1156 +#: ../../library/argparse.rst:995 msgid "Common built-in types and functions can be used as type converters:" msgstr "" -"Tipos e funções embutidas comuns podem ser usados ​​como conversores de tipo:" - -#: ../../library/argparse.rst:1172 +"Tipos e funções embutidas comuns podem ser usados como conversores de tipo:" + +#: ../../library/argparse.rst:997 +msgid "" +"import argparse\n" +"import pathlib\n" +"\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument('count', type=int)\n" +"parser.add_argument('distance', type=float)\n" +"parser.add_argument('street', type=ascii)\n" +"parser.add_argument('code_point', type=ord)\n" +"parser.add_argument('dest_file', type=argparse.FileType('w', " +"encoding='latin-1'))\n" +"parser.add_argument('datapath', type=pathlib.Path)" +msgstr "" +"import argparse\n" +"import pathlib\n" +"\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument('count', type=int)\n" +"parser.add_argument('distance', type=float)\n" +"parser.add_argument('street', type=ascii)\n" +"parser.add_argument('code_point', type=ord)\n" +"parser.add_argument('dest_file', type=argparse.FileType('w', " +"encoding='latin-1'))\n" +"parser.add_argument('datapath', type=pathlib.Path)" + +#: ../../library/argparse.rst:1010 msgid "User defined functions can be used as well:" msgstr "Funções definidas pelo usuário também podem ser usadas:" -#: ../../library/argparse.rst:1184 +#: ../../library/argparse.rst:1012 +msgid "" +">>> def hyphenated(string):\n" +"... return '-'.join([word[:4] for word in string.casefold().split()])\n" +"...\n" +">>> parser = argparse.ArgumentParser()\n" +">>> _ = parser.add_argument('short_title', type=hyphenated)\n" +">>> parser.parse_args(['\"The Tale of Two Cities\"'])\n" +"Namespace(short_title='\"the-tale-of-two-citi')" +msgstr "" +">>> def hyphenated(string):\n" +"... return '-'.join([word[:4] for word in string.casefold().split()])\n" +"...\n" +">>> parser = argparse.ArgumentParser()\n" +">>> _ = parser.add_argument('short_title', type=hyphenated)\n" +">>> parser.parse_args(['\"Um conto de duas cidades\"'])\n" +"Namespace(short_title='\"um-cont-de-duas-cida')" + +#: ../../library/argparse.rst:1022 msgid "" "The :func:`bool` function is not recommended as a type converter. All it " "does is convert empty strings to ``False`` and non-empty strings to " @@ -1504,7 +2186,7 @@ msgstr "" "ele faz é converter strings vazias em ``False`` e strings não vazias em " "``True``. Geralmente não é isso que se deseja." -#: ../../library/argparse.rst:1188 +#: ../../library/argparse.rst:1026 msgid "" "In general, the ``type`` keyword is a convenience that should only be used " "for simple conversions that can only raise one of the three supported " @@ -1517,7 +2199,7 @@ msgstr "" "recursos mais interessante deve ser feita posteriormente, após a análise dos " "argumentos." -#: ../../library/argparse.rst:1193 +#: ../../library/argparse.rst:1031 msgid "" "For example, JSON or YAML conversions have complex error cases that require " "better reporting than can be given by the ``type`` keyword. A :exc:`~json." @@ -1529,22 +2211,23 @@ msgstr "" "Um :exc:`~json.JSONDecodeError` não seria bem formatado e uma exceção :exc:" "`FileNotFoundError` não seria tratada." -#: ../../library/argparse.rst:1198 +#: ../../library/argparse.rst:1036 msgid "" "Even :class:`~argparse.FileType` has its limitations for use with the " -"``type`` keyword. If one argument uses *FileType* and then a subsequent " -"argument fails, an error is reported but the file is not automatically " -"closed. In this case, it would be better to wait until after the parser has " -"run and then use the :keyword:`with`-statement to manage the files." +"``type`` keyword. If one argument uses :class:`~argparse.FileType` and then " +"a subsequent argument fails, an error is reported but the file is not " +"automatically closed. In this case, it would be better to wait until after " +"the parser has run and then use the :keyword:`with`-statement to manage the " +"files." msgstr "" "Mesmo :class:`~argparse.FileType` tem suas limitações para uso com o " -"argumento nomeado ``type``. Se um argumento usar *FileType* e um argumento " -"subsequente falhar, um erro será relatado, mas o arquivo não será fechado " -"automaticamente. Neste caso, seria melhor esperar até que o analisador tenha " -"sido executado e então usar a instrução :keyword:`with` para gerenciar os " -"arquivos." +"argumento nomeado ``type``. Se um argumento usar :class:`~argparse.FileType` " +"e um argumento subsequente falhar, um erro será relatado, mas o arquivo não " +"será fechado automaticamente. Neste caso, seria melhor esperar até que o " +"analisador tenha sido executado e então usar a instrução :keyword:`with` " +"para gerenciar os arquivos." -#: ../../library/argparse.rst:1204 +#: ../../library/argparse.rst:1043 msgid "" "For type checkers that simply check against a fixed set of values, consider " "using the choices_ keyword instead." @@ -1552,11 +2235,11 @@ msgstr "" "Para verificadores de tipo que simplesmente verificam um conjunto fixo de " "valores, considere usar o argumento nomeado choices_." -#: ../../library/argparse.rst:1211 +#: ../../library/argparse.rst:1050 msgid "choices" msgstr "choices" -#: ../../library/argparse.rst:1213 +#: ../../library/argparse.rst:1052 msgid "" "Some command-line arguments should be selected from a restricted set of " "values. These can be handled by passing a sequence object as the *choices* " @@ -1571,17 +2254,37 @@ msgstr "" "argumentos serão verificados e uma mensagem de erro será exibida se o " "argumento não for um dos valores aceitáveis::" -#: ../../library/argparse.rst:1228 +#: ../../library/argparse.rst:1058 +msgid "" +">>> parser = argparse.ArgumentParser(prog='game.py')\n" +">>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])\n" +">>> parser.parse_args(['rock'])\n" +"Namespace(move='rock')\n" +">>> parser.parse_args(['fire'])\n" +"usage: game.py [-h] {rock,paper,scissors}\n" +"game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',\n" +"'paper', 'scissors')" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='game.py')\n" +">>> parser.add_argument('move', choices=['pedra', 'papel', 'tesoura'])\n" +">>> parser.parse_args(['padra'])\n" +"Namespace(move='padr')\n" +">>> parser.parse_args(['fogo'])\n" +"usage: game.py [-h] {pedra,papel,tesoura}\n" +"game.py: error: argument move: invalid choice: 'fogo' (choose from 'pedra',\n" +"'papel', 'tesoura')" + +#: ../../library/argparse.rst:1067 msgid "" "Note that inclusion in the *choices* sequence is checked after any type_ " "conversions have been performed, so the type of the objects in the *choices* " -"sequence should match the type_ specified::" +"sequence should match the type_ specified." msgstr "" "Observe que a inclusão na sequência *choices* é verificada após qualquer " "conversão de type_ ter sido realizada, portanto o tipo dos objetos na " -"sequência *choices* deve corresponder ao type_ especificado::" +"sequência *choices* deve corresponder ao type_ especificado." -#: ../../library/argparse.rst:1240 +#: ../../library/argparse.rst:1071 msgid "" "Any sequence can be passed as the *choices* value, so :class:`list` " "objects, :class:`tuple` objects, and custom sequences are all supported." @@ -1590,7 +2293,7 @@ msgstr "" "objetos :class:`list`, objetos :class:`tuple` e sequências personalizadas " "são todos suportados." -#: ../../library/argparse.rst:1243 +#: ../../library/argparse.rst:1074 msgid "" "Use of :class:`enum.Enum` is not recommended because it is difficult to " "control its appearance in usage, help, and error messages." @@ -1598,7 +2301,7 @@ msgstr "" "O uso de :class:`enum.Enum` não é recomendado porque é difícil controlar sua " "aparência no uso, na ajuda e nas mensagens de erro." -#: ../../library/argparse.rst:1246 +#: ../../library/argparse.rst:1077 msgid "" "Formatted choices override the default *metavar* which is normally derived " "from *dest*. This is usually what you want because the user never sees the " @@ -1610,24 +2313,42 @@ msgstr "" "vê o parâmetro *dest*. Se esta exibição não for desejável (talvez porque " "haja muitas opções), basta especificar um metavar_ explícito." -#: ../../library/argparse.rst:1255 +#: ../../library/argparse.rst:1086 msgid "required" msgstr "required" -#: ../../library/argparse.rst:1257 +#: ../../library/argparse.rst:1088 msgid "" -"In general, the :mod:`argparse` module assumes that flags like ``-f`` and " +"In general, the :mod:`!argparse` module assumes that flags like ``-f`` and " "``--bar`` indicate *optional* arguments, which can always be omitted at the " "command line. To make an option *required*, ``True`` can be specified for " "the ``required=`` keyword argument to :meth:`~ArgumentParser.add_argument`::" msgstr "" -"Em geral, o módulo :mod:`argparse` presume que sinalizadores como ``-f`` e " +"Em geral, o módulo :mod:`!argparse` presume que sinalizadores como ``-f`` e " "``--bar`` indicam argumentos *opcionais*, que sempre podem ser omitidos na " "linha de comando. Para tornar uma opção obrigatória, ``True`` pode ser " "especificado para o argumento nomeado ``required=`` para :meth:" "`~ArgumentParser.add_argument`::" -#: ../../library/argparse.rst:1270 +#: ../../library/argparse.rst:1093 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', required=True)\n" +">>> parser.parse_args(['--foo', 'BAR'])\n" +"Namespace(foo='BAR')\n" +">>> parser.parse_args([])\n" +"usage: [-h] --foo FOO\n" +": error: the following arguments are required: --foo" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', required=True)\n" +">>> parser.parse_args(['--foo', 'BAR'])\n" +"Namespace(foo='BAR')\n" +">>> parser.parse_args([])\n" +"usage: [-h] --foo FOO\n" +": error: the following arguments are required: --foo" + +#: ../../library/argparse.rst:1101 msgid "" "As the example shows, if an option is marked as ``required``, :meth:" "`~ArgumentParser.parse_args` will report an error if that option is not " @@ -1637,7 +2358,7 @@ msgstr "" "`~ArgumentParser.parse_args` reportará um erro se essa opção não estiver " "presente na linha de comando." -#: ../../library/argparse.rst:1276 +#: ../../library/argparse.rst:1107 msgid "" "Required options are generally considered bad form because users expect " "*options* to be *optional*, and thus they should be avoided when possible." @@ -1646,23 +2367,23 @@ msgstr "" "usuários esperam que as *opções* sejam *opcionais* e, portanto, devem ser " "evitadas quando possível." -#: ../../library/argparse.rst:1283 +#: ../../library/argparse.rst:1114 msgid "help" msgstr "help" -#: ../../library/argparse.rst:1285 +#: ../../library/argparse.rst:1116 msgid "" "The ``help`` value is a string containing a brief description of the " "argument. When a user requests help (usually by using ``-h`` or ``--help`` " "at the command line), these ``help`` descriptions will be displayed with " -"each argument::" +"each argument." msgstr "" "O valor ``help`` é uma string contendo uma breve descrição do argumento. " "Quando um usuário solicita ajuda (geralmente usando ``-h`` ou ``--help`` na " "linha de comando), estas descrições de ``help`` serão exibidas com cada " -"argumento::" +"argumento." -#: ../../library/argparse.rst:1305 +#: ../../library/argparse.rst:1121 msgid "" "The ``help`` strings can include various format specifiers to avoid " "repetition of things like the program name or the argument default_. The " @@ -1676,7 +2397,33 @@ msgstr "" "``%(prog)s`` e a maioria dos argumentos nomeados para :meth:`~ArgumentParser." "add_argument`, por exemplo. ``%(default)s``, ``%(type)s``, etc.::" -#: ../../library/argparse.rst:1322 +#: ../../library/argparse.rst:1126 +msgid "" +">>> parser = argparse.ArgumentParser(prog='frobble')\n" +">>> parser.add_argument('bar', nargs='?', type=int, default=42,\n" +"... help='the bar to %(prog)s (default: %(default)s)')\n" +">>> parser.print_help()\n" +"usage: frobble [-h] [bar]\n" +"\n" +"positional arguments:\n" +" bar the bar to frobble (default: 42)\n" +"\n" +"options:\n" +" -h, --help show this help message and exit" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='frobble')\n" +">>> parser.add_argument('bar', nargs='?', type=int, default=42,\n" +"... help='the bar to %(prog)s (default: %(default)s)')\n" +">>> parser.print_help()\n" +"usage: frobble [-h] [bar]\n" +"\n" +"positional arguments:\n" +" bar the bar to frobble (default: 42)\n" +"\n" +"options:\n" +" -h, --help show this help message and exit" + +#: ../../library/argparse.rst:1138 msgid "" "As the help string supports %-formatting, if you want a literal ``%`` to " "appear in the help string, you must escape it as ``%%``." @@ -1685,44 +2432,126 @@ msgstr "" "que um literal ``%`` apareça na string de ajuda, você deve escapá-lo como ``%" "%``." -#: ../../library/argparse.rst:1325 +#: ../../library/argparse.rst:1141 msgid "" -":mod:`argparse` supports silencing the help entry for certain options, by " +":mod:`!argparse` supports silencing the help entry for certain options, by " "setting the ``help`` value to ``argparse.SUPPRESS``::" msgstr "" -":mod:`argparse` oferece suporte a silenciar a entrada de ajuda para certas " +":mod:`!argparse` oferece suporte a silenciar a entrada de ajuda para certas " "opções, definindo o valor ``help`` como ``argparse.SUPPRESS``::" -#: ../../library/argparse.rst:1340 +#: ../../library/argparse.rst:1144 +msgid "" +">>> parser = argparse.ArgumentParser(prog='frobble')\n" +">>> parser.add_argument('--foo', help=argparse.SUPPRESS)\n" +">>> parser.print_help()\n" +"usage: frobble [-h]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='frobble')\n" +">>> parser.add_argument('--foo', help=argparse.SUPPRESS)\n" +">>> parser.print_help()\n" +"usage: frobble [-h]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit" + +#: ../../library/argparse.rst:1156 msgid "metavar" msgstr "metavar" -#: ../../library/argparse.rst:1342 +#: ../../library/argparse.rst:1158 msgid "" "When :class:`ArgumentParser` generates help messages, it needs some way to " -"refer to each expected argument. By default, ArgumentParser objects use the " -"dest_ value as the \"name\" of each object. By default, for positional " -"argument actions, the dest_ value is used directly, and for optional " -"argument actions, the dest_ value is uppercased. So, a single positional " -"argument with ``dest='bar'`` will be referred to as ``bar``. A single " -"optional argument ``--foo`` that should be followed by a single command-line " -"argument will be referred to as ``FOO``. An example::" +"refer to each expected argument. By default, :class:`!ArgumentParser` " +"objects use the dest_ value as the \"name\" of each object. By default, for " +"positional argument actions, the dest_ value is used directly, and for " +"optional argument actions, the dest_ value is uppercased. So, a single " +"positional argument with ``dest='bar'`` will be referred to as ``bar``. A " +"single optional argument ``--foo`` that should be followed by a single " +"command-line argument will be referred to as ``FOO``. An example::" msgstr "" "Quando :class:`ArgumentParser` gera mensagens de ajuda, ele precisa de " -"alguma forma de se referir a cada argumento esperado. Por padrão, os objetos " -"ArgumentParser usam o valor dest_ como o \"nome\" de cada objeto. Por " -"padrão, para ações de argumentos posicionais, o valor dest_ é usado " -"diretamente, e para ações de argumentos opcionais, o valor dest_ é " +"alguma forma de se referir a cada argumento esperado. Por padrão, os " +"objetos :class:`!ArgumentParser` usam o valor dest_ como o \"nome\" de cada " +"objeto. Por padrão, para ações de argumentos posicionais, o valor dest_ é " +"usado diretamente, e para ações de argumentos opcionais, o valor dest_ é " "maiúsculo. Portanto, um único argumento posicional com ``dest='bar'`` será " "referido como ``bar``. Um único argumento opcional ``--foo`` que deve ser " "seguido por um único argumento de linha de comando será referido como " "``FOO``. Um exemplo::" -#: ../../library/argparse.rst:1366 +#: ../../library/argparse.rst:1167 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo')\n" +">>> parser.add_argument('bar')\n" +">>> parser.parse_args('X --foo Y'.split())\n" +"Namespace(bar='X', foo='Y')\n" +">>> parser.print_help()\n" +"usage: [-h] [--foo FOO] bar\n" +"\n" +"positional arguments:\n" +" bar\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo FOO" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo')\n" +">>> parser.add_argument('bar')\n" +">>> parser.parse_args('X --foo Y'.split())\n" +"Namespace(bar='X', foo='Y')\n" +">>> parser.print_help()\n" +"usage: [-h] [--foo FOO] bar\n" +"\n" +"positional arguments:\n" +" bar\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo FOO" + +#: ../../library/argparse.rst:1182 msgid "An alternative name can be specified with ``metavar``::" msgstr "Um nome alternativo pode ser especificado com ``metavar``::" -#: ../../library/argparse.rst:1383 +#: ../../library/argparse.rst:1184 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', metavar='YYY')\n" +">>> parser.add_argument('bar', metavar='XXX')\n" +">>> parser.parse_args('X --foo Y'.split())\n" +"Namespace(bar='X', foo='Y')\n" +">>> parser.print_help()\n" +"usage: [-h] [--foo YYY] XXX\n" +"\n" +"positional arguments:\n" +" XXX\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo YYY" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', metavar='YYY')\n" +">>> parser.add_argument('bar', metavar='XXX')\n" +">>> parser.parse_args('X --foo Y'.split())\n" +"Namespace(bar='X', foo='Y')\n" +">>> parser.print_help()\n" +"usage: [-h] [--foo YYY] XXX\n" +"\n" +"positional arguments:\n" +" XXX\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo YYY" + +#: ../../library/argparse.rst:1199 msgid "" "Note that ``metavar`` only changes the *displayed* name - the name of the " "attribute on the :meth:`~ArgumentParser.parse_args` object is still " @@ -1732,7 +2561,7 @@ msgstr "" "no objeto :meth:`~ArgumentParser.parse_args` ainda é determinado pelo valor " "dest_." -#: ../../library/argparse.rst:1387 +#: ../../library/argparse.rst:1203 msgid "" "Different values of ``nargs`` may cause the metavar to be used multiple " "times. Providing a tuple to ``metavar`` specifies a different display for " @@ -1742,11 +2571,35 @@ msgstr "" "múltiplas vezes. Fornecer uma tupla para ``metavar`` especifica uma exibição " "diferente para cada um dos argumentos::" -#: ../../library/argparse.rst:1406 +#: ../../library/argparse.rst:1207 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-x', nargs=2)\n" +">>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))\n" +">>> parser.print_help()\n" +"usage: PROG [-h] [-x X X] [--foo bar baz]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -x X X\n" +" --foo bar baz" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-x', nargs=2)\n" +">>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))\n" +">>> parser.print_help()\n" +"usage: PROG [-h] [-x X X] [--foo bar baz]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -x X X\n" +" --foo bar baz" + +#: ../../library/argparse.rst:1222 msgid "dest" msgstr "dest" -#: ../../library/argparse.rst:1408 +#: ../../library/argparse.rst:1224 msgid "" "Most :class:`ArgumentParser` actions add some value as an attribute of the " "object returned by :meth:`~ArgumentParser.parse_args`. The name of this " @@ -1762,7 +2615,19 @@ msgstr "" "é normalmente fornecido como o primeiro argumento para :meth:" "`~ArgumentParser.add_argument`::" -#: ../../library/argparse.rst:1420 +#: ../../library/argparse.rst:1231 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('bar')\n" +">>> parser.parse_args(['XXX'])\n" +"Namespace(bar='XXX')" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('bar')\n" +">>> parser.parse_args(['XXX'])\n" +"Namespace(bar='XXX')" + +#: ../../library/argparse.rst:1236 msgid "" "For optional argument actions, the value of ``dest`` is normally inferred " "from the option strings. :class:`ArgumentParser` generates the value of " @@ -1782,16 +2647,46 @@ msgstr "" "caracteres ``_`` para garantir que a string seja um nome de atributo válido. " "Os exemplos abaixo ilustram esse comportamento:" -#: ../../library/argparse.rst:1437 +#: ../../library/argparse.rst:1245 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('-f', '--foo-bar', '--foo')\n" +">>> parser.add_argument('-x', '-y')\n" +">>> parser.parse_args('-f 1 -x 2'.split())\n" +"Namespace(foo_bar='1', x='2')\n" +">>> parser.parse_args('--foo 1 -y 2'.split())\n" +"Namespace(foo_bar='1', x='2')" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('-f', '--foo-bar', '--foo')\n" +">>> parser.add_argument('-x', '-y')\n" +">>> parser.parse_args('-f 1 -x 2'.split())\n" +"Namespace(foo_bar='1', x='2')\n" +">>> parser.parse_args('--foo 1 -y 2'.split())\n" +"Namespace(foo_bar='1', x='2')" + +#: ../../library/argparse.rst:1253 msgid "``dest`` allows a custom attribute name to be provided::" msgstr "" "``dest`` permite que um nome de atributo personalizado seja fornecido::" -#: ../../library/argparse.rst:1448 +#: ../../library/argparse.rst:1255 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', dest='bar')\n" +">>> parser.parse_args('--foo XXX'.split())\n" +"Namespace(bar='XXX')" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', dest='bar')\n" +">>> parser.parse_args('--foo XXX'.split())\n" +"Namespace(bar='XXX')" + +#: ../../library/argparse.rst:1264 msgid "deprecated" msgstr "deprecated" -#: ../../library/argparse.rst:1450 +#: ../../library/argparse.rst:1266 msgid "" "During a project's lifetime, some arguments may need to be removed from the " "command line. Before removing them, you should inform your users that the " @@ -1799,7 +2694,7 @@ msgid "" "argument of :meth:`~ArgumentParser.add_argument`, which defaults to " "``False``, specifies if the argument is deprecated and will be removed in " "the future. For arguments, if ``deprecated`` is ``True``, then a warning " -"will be printed to standard error when the argument is used::" +"will be printed to :data:`sys.stderr` when the argument is used::" msgstr "" "Durante a vida de um projeto, alguns argumentos podem precisar ser removidos " "da linha de comando. Antes de removê-los, você deve informar aos seus " @@ -1807,161 +2702,328 @@ msgstr "" "argumento nomeado ``deprecated`` de :meth:`~ArgumentParser.add_argument`, " "cujo padrão é ``False``, especifica se o argumento está descontinuado e será " "removido no futuro. Para argumentos, se ``deprecated`` for ``True``, então " -"um aviso será impresso no erro padrão quando o argumento for usado::" +"um aviso será enviado para :data:`sys.stderr` (saída de erro) quando o " +"argumento for usado::" -#: ../../library/argparse.rst:1473 +#: ../../library/argparse.rst:1276 +msgid "" +">>> import argparse\n" +">>> parser = argparse.ArgumentParser(prog='snake.py')\n" +">>> parser.add_argument('--legs', default=0, type=int, deprecated=True)\n" +">>> parser.parse_args([])\n" +"Namespace(legs=0)\n" +">>> parser.parse_args(['--legs', '4'])\n" +"snake.py: warning: option '--legs' is deprecated\n" +"Namespace(legs=4)" +msgstr "" +">>> import argparse\n" +">>> parser = argparse.ArgumentParser(prog='snake.py')\n" +">>> parser.add_argument('--legs', default=0, type=int, deprecated=True)\n" +">>> parser.parse_args([])\n" +"Namespace(legs=0)\n" +">>> parser.parse_args(['--legs', '4'])\n" +"snake.py: warning: option '--legs' is deprecated\n" +"Namespace(legs=4)" + +#: ../../library/argparse.rst:1289 msgid "Action classes" msgstr "Classes de ação" -#: ../../library/argparse.rst:1475 +#: ../../library/argparse.rst:1291 msgid "" -"Action classes implement the Action API, a callable which returns a callable " -"which processes arguments from the command-line. Any object which follows " -"this API may be passed as the ``action`` parameter to :meth:`~ArgumentParser." -"add_argument`." -msgstr "" -"As classes de ação implementam a API de Action, um chamável que retorna um " -"chamável que processa argumentos da linha de comando. Qualquer objeto que " -"siga esta API pode ser passado como parâmetro ``action`` para :meth:" +":class:`!Action` classes implement the Action API, a callable which returns " +"a callable which processes arguments from the command-line. Any object which " +"follows this API may be passed as the ``action`` parameter to :meth:" "`~ArgumentParser.add_argument`." +msgstr "" +"As classes :class:`!Action` implementam a API de Action, um chamável que " +"retorna um chamável que processa argumentos da linha de comando. Qualquer " +"objeto que siga esta API pode ser passado como parâmetro ``action`` para :" +"meth:`~ArgumentParser.add_argument`." -#: ../../library/argparse.rst:1484 +#: ../../library/argparse.rst:1300 msgid "" -"Action objects are used by an ArgumentParser to represent the information " -"needed to parse a single argument from one or more strings from the command " -"line. The Action class must accept the two positional arguments plus any " -"keyword arguments passed to :meth:`ArgumentParser.add_argument` except for " -"the ``action`` itself." +":class:`!Action` objects are used by an :class:`ArgumentParser` to represent " +"the information needed to parse a single argument from one or more strings " +"from the command line. The :class:`!Action` class must accept the two " +"positional arguments plus any keyword arguments passed to :meth:" +"`ArgumentParser.add_argument` except for the ``action`` itself." msgstr "" +"Objetos :class:`!Action` são usados por um :class:`ArgumentParser` para " +"representar as informações necessárias para analisar um único argumento de " +"uma ou mais strings da linha de comando. A classe :class:`!Action` deve " +"aceitar os dois argumentos posicionais mais quaisquer argumentos nomeados " +"passados para :meth:`ArgumentParser.add_argument`, exceto o próprio " +"``action``." -#: ../../library/argparse.rst:1490 +#: ../../library/argparse.rst:1306 msgid "" -"Instances of Action (or return value of any callable to the ``action`` " -"parameter) should have attributes \"dest\", \"option_strings\", \"default\", " -"\"type\", \"required\", \"help\", etc. defined. The easiest way to ensure " -"these attributes are defined is to call ``Action.__init__``." +"Instances of :class:`!Action` (or return value of any callable to the " +"``action`` parameter) should have attributes :attr:`!dest`, :attr:`!" +"option_strings`, :attr:`!default`, :attr:`!type`, :attr:`!required`, :attr:`!" +"help`, etc. defined. The easiest way to ensure these attributes are defined " +"is to call :meth:`!Action.__init__`." msgstr "" +"Instâncias de :class:`!Action` (ou valor de retorno de qualquer chamável " +"para o parâmetro ``action``) devem ter atributos :attr:`!dest`, :attr:`!" +"option_strings`, :attr:`!default`, :attr:`!type`, :attr:`!required`, :attr:`!" +"help`, etc. definidos. A maneira mais fácil de garantir que esses atributos " +"sejam definidos é chamar :meth:`!Action.__init__`." -#: ../../library/argparse.rst:1495 +#: ../../library/argparse.rst:1314 msgid "" -"Action instances should be callable, so subclasses must override the " -"``__call__`` method, which should accept four parameters:" +":class:`!Action` instances should be callable, so subclasses must override " +"the :meth:`!__call__` method, which should accept four parameters:" msgstr "" +"As instâncias de :class:`!Action` devem ser chamáveis, portanto, as " +"subclasses devem substituir o método :meth:`!__call__`, que deve aceitar " +"quatro parâmetros:" -#: ../../library/argparse.rst:1498 -msgid "``parser`` - The ArgumentParser object which contains this action." -msgstr "" +#: ../../library/argparse.rst:1317 +msgid "" +"*parser* - The :class:`ArgumentParser` object which contains this action." +msgstr "*parser* - O objeto :class:`ArgumentParser` que contém esta ação." -#: ../../library/argparse.rst:1500 +#: ../../library/argparse.rst:1319 msgid "" -"``namespace`` - The :class:`Namespace` object that will be returned by :meth:" +"*namespace* - The :class:`Namespace` object that will be returned by :meth:" "`~ArgumentParser.parse_args`. Most actions add an attribute to this object " "using :func:`setattr`." msgstr "" +"*namespace* - O objeto :class:`Namespace` que será retornado por :meth:" +"`~ArgumentParser.parse_args`. A maioria das ações adicionam um atributo a " +"este objeto usando :func:`setattr`." -#: ../../library/argparse.rst:1504 +#: ../../library/argparse.rst:1323 msgid "" -"``values`` - The associated command-line arguments, with any type " -"conversions applied. Type conversions are specified with the type_ keyword " -"argument to :meth:`~ArgumentParser.add_argument`." +"*values* - The associated command-line arguments, with any type conversions " +"applied. Type conversions are specified with the type_ keyword argument to :" +"meth:`~ArgumentParser.add_argument`." msgstr "" +"*values* - Os argumentos de linha de comando associados, com qualquer " +"conversões de tipo aplicadas. Conversões de tipo são especificadas com o " +"argumento nomeado type_ para :meth:`~ArgumentParser.add_argument`." -#: ../../library/argparse.rst:1508 +#: ../../library/argparse.rst:1327 msgid "" -"``option_string`` - The option string that was used to invoke this action. " -"The ``option_string`` argument is optional, and will be absent if the action " -"is associated with a positional argument." +"*option_string* - The option string that was used to invoke this action. The " +"``option_string`` argument is optional, and will be absent if the action is " +"associated with a positional argument." msgstr "" +"*option_string* - A string da opção que foi usada para invocar esta ação. O " +"argumento ``option_string`` é opcional e estará ausente se a ação estiver " +"associada a um argumento posicional." -#: ../../library/argparse.rst:1512 +#: ../../library/argparse.rst:1331 msgid "" -"The ``__call__`` method may perform arbitrary actions, but will typically " -"set attributes on the ``namespace`` based on ``dest`` and ``values``." +"The :meth:`!__call__` method may perform arbitrary actions, but will " +"typically set attributes on the ``namespace`` based on ``dest`` and " +"``values``." msgstr "" +"O método :meth:`!__call__` pode executar ações arbitrárias, mas normalmente " +"definirá atributos em ``namespace`` com base em ``dest`` e ``values``." -#: ../../library/argparse.rst:1515 +#: ../../library/argparse.rst:1336 msgid "" -"Action subclasses can define a ``format_usage`` method that takes no " -"argument and return a string which will be used when printing the usage of " -"the program. If such method is not provided, a sensible default will be used." +":class:`!Action` subclasses can define a :meth:`!format_usage` method that " +"takes no argument and return a string which will be used when printing the " +"usage of the program. If such method is not provided, a sensible default " +"will be used." msgstr "" +"As subclasses de :class:`!Action` podem definir um método :meth:`!" +"format_usage` que não recebe argumento e retorna uma string que será usada " +"ao exibir a mensagem de uso do programa. Se tal método não for fornecido, um " +"padrão sensato será usado." -#: ../../library/argparse.rst:1520 +#: ../../library/argparse.rst:1342 msgid "The parse_args() method" -msgstr "" +msgstr "O método parse_args()" -#: ../../library/argparse.rst:1524 +#: ../../library/argparse.rst:1346 msgid "" "Convert argument strings to objects and assign them as attributes of the " "namespace. Return the populated namespace." msgstr "" +"Converte strings de argumento em objetos e os atribui como atributos do " +"espaço de nomes. Retorna o espaço de nomes preenchido." -#: ../../library/argparse.rst:1527 +#: ../../library/argparse.rst:1349 msgid "" "Previous calls to :meth:`add_argument` determine exactly what objects are " -"created and how they are assigned. See the documentation for :meth:" -"`add_argument` for details." +"created and how they are assigned. See the documentation for :meth:`!" +"add_argument` for details." msgstr "" +"Chamadas anteriores para :meth:`add_argument` determinam exatamente quais " +"objetos são criados e como eles são atribuídos. Veja a documentação de :meth:" +"`!add_argument` para detalhes." -#: ../../library/argparse.rst:1531 +#: ../../library/argparse.rst:1353 msgid "" "args_ - List of strings to parse. The default is taken from :data:`sys." "argv`." msgstr "" +"args_ - Lista de strings para analisar. O padrão é obtido de :data:`sys." +"argv`." -#: ../../library/argparse.rst:1534 +#: ../../library/argparse.rst:1356 msgid "" "namespace_ - An object to take the attributes. The default is a new empty :" "class:`Namespace` object." msgstr "" +"namespace_ - Um objeto para receber os atributos. O padrão é um novo objeto :" +"class:`Namespace` vazio." -#: ../../library/argparse.rst:1539 +#: ../../library/argparse.rst:1361 msgid "Option value syntax" -msgstr "" +msgstr "Sintaxe de valores da opção" -#: ../../library/argparse.rst:1541 +#: ../../library/argparse.rst:1363 msgid "" "The :meth:`~ArgumentParser.parse_args` method supports several ways of " "specifying the value of an option (if it takes one). In the simplest case, " "the option and its value are passed as two separate arguments::" msgstr "" +"O método :meth:`~ArgumentParser.parse_args` provê várias maneiras de " +"especificar o valor de uma opção (se ele pegar uma). No caso mais simples, a " +"opção e seu valor são passados como dois argumentos separados::" + +#: ../../library/argparse.rst:1367 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-x')\n" +">>> parser.add_argument('--foo')\n" +">>> parser.parse_args(['-x', 'X'])\n" +"Namespace(foo=None, x='X')\n" +">>> parser.parse_args(['--foo', 'FOO'])\n" +"Namespace(foo='FOO', x=None)" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-x')\n" +">>> parser.add_argument('--foo')\n" +">>> parser.parse_args(['-x', 'X'])\n" +"Namespace(foo=None, x='X')\n" +">>> parser.parse_args(['--foo', 'FOO'])\n" +"Namespace(foo='FOO', x=None)" -#: ../../library/argparse.rst:1553 +#: ../../library/argparse.rst:1375 msgid "" "For long options (options with names longer than a single character), the " "option and value can also be passed as a single command-line argument, using " "``=`` to separate them::" msgstr "" +"Para opções longas (opções com nomes maiores que um único caractere), a " +"opção e o valor também podem ser passados como um único argumento de linha " +"de comando, usando ``=`` para separá-los::" -#: ../../library/argparse.rst:1560 +#: ../../library/argparse.rst:1379 +msgid "" +">>> parser.parse_args(['--foo=FOO'])\n" +"Namespace(foo='FOO', x=None)" +msgstr "" +">>> parser.parse_args(['--foo=FOO'])\n" +"Namespace(foo='FOO', x=None)" + +#: ../../library/argparse.rst:1382 msgid "" "For short options (options only one character long), the option and its " "value can be concatenated::" msgstr "" +"Para opções curtas (opções com apenas um caractere), a opção e seu valor " +"podem ser concatenados:" + +#: ../../library/argparse.rst:1385 +msgid "" +">>> parser.parse_args(['-xX'])\n" +"Namespace(foo=None, x='X')" +msgstr "" +">>> parser.parse_args(['-xX'])\n" +"Namespace(foo=None, x='X')" -#: ../../library/argparse.rst:1566 +#: ../../library/argparse.rst:1388 msgid "" "Several short options can be joined together, using only a single ``-`` " "prefix, as long as only the last option (or none of them) requires a value::" msgstr "" +"Várias opções curtas podem ser unidas, usando apenas um único prefixo ``-``, " +"desde que apenas a última opção (ou nenhuma delas) exija um valor::" + +#: ../../library/argparse.rst:1391 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-x', action='store_true')\n" +">>> parser.add_argument('-y', action='store_true')\n" +">>> parser.add_argument('-z')\n" +">>> parser.parse_args(['-xyzZ'])\n" +"Namespace(x=True, y=True, z='Z')" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-x', action='store_true')\n" +">>> parser.add_argument('-y', action='store_true')\n" +">>> parser.add_argument('-z')\n" +">>> parser.parse_args(['-xyzZ'])\n" +"Namespace(x=True, y=True, z='Z')" -#: ../../library/argparse.rst:1578 +#: ../../library/argparse.rst:1400 msgid "Invalid arguments" msgstr "Argumentos inválidos" -#: ../../library/argparse.rst:1580 +#: ../../library/argparse.rst:1402 msgid "" "While parsing the command line, :meth:`~ArgumentParser.parse_args` checks " "for a variety of errors, including ambiguous options, invalid types, invalid " "options, wrong number of positional arguments, etc. When it encounters such " "an error, it exits and prints the error along with a usage message::" msgstr "" - -#: ../../library/argparse.rst:1606 +"Ao analisar a linha de comando, :meth:`~ArgumentParser.parse_args` verifica " +"uma variedade de erros, incluindo opções ambíguas, tipos inválidos, opções " +"inválidas, número incorreto de argumentos posicionais, etc. Quando encontra " +"tal erro, ele sai e imprime o erro junto com uma mensagem de uso::" + +#: ../../library/argparse.rst:1407 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('--foo', type=int)\n" +">>> parser.add_argument('bar', nargs='?')\n" +"\n" +">>> # invalid type\n" +">>> parser.parse_args(['--foo', 'spam'])\n" +"usage: PROG [-h] [--foo FOO] [bar]\n" +"PROG: error: argument --foo: invalid int value: 'spam'\n" +"\n" +">>> # invalid option\n" +">>> parser.parse_args(['--bar'])\n" +"usage: PROG [-h] [--foo FOO] [bar]\n" +"PROG: error: no such option: --bar\n" +"\n" +">>> # wrong number of arguments\n" +">>> parser.parse_args(['spam', 'badger'])\n" +"usage: PROG [-h] [--foo FOO] [bar]\n" +"PROG: error: extra arguments found: badger" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('--foo', type=int)\n" +">>> parser.add_argument('bar', nargs='?')\n" +"\n" +">>> # tipo inválido\n" +">>> parser.parse_args(['--foo', 'spam'])\n" +"usage: PROG [-h] [--foo FOO] [bar]\n" +"PROG: error: argument --foo: invalid int value: 'spam'\n" +"\n" +">>> # opção inválida\n" +">>> parser.parse_args(['--bar'])\n" +"usage: PROG [-h] [--foo FOO] [bar]\n" +"PROG: error: no such option: --bar\n" +"\n" +">>> # número errado de argumentos\n" +">>> parser.parse_args(['spam', 'badger'])\n" +"usage: PROG [-h] [--foo FOO] [bar]\n" +"PROG: error: extra arguments found: badger" + +#: ../../library/argparse.rst:1428 msgid "Arguments containing ``-``" msgstr "Argumentos contendo ``-``" -#: ../../library/argparse.rst:1608 +#: ../../library/argparse.rst:1430 msgid "" "The :meth:`~ArgumentParser.parse_args` method attempts to give errors " "whenever the user has clearly made a mistake, but some situations are " @@ -1972,161 +3034,425 @@ msgid "" "like negative numbers and there are no options in the parser that look like " "negative numbers::" msgstr "" - -#: ../../library/argparse.rst:1646 +"O método :meth:`~ArgumentParser.parse_args` tenta mostrar erros sempre que o " +"usuário claramente cometeu um erro, mas algumas situações são inerentemente " +"ambíguas. Por exemplo, o argumento de linha de comando ``-1`` pode ser uma " +"tentativa de especificar uma opção ou uma tentativa de fornecer um argumento " +"posicional. O método :meth:`~ArgumentParser.parse_args` é cauteloso aqui: " +"argumentos posicionais só podem começar com ``-`` se eles se parecerem com " +"números negativos e não houver opções no analisador sintático que se pareçam " +"com números negativos::" + +#: ../../library/argparse.rst:1438 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-x')\n" +">>> parser.add_argument('foo', nargs='?')\n" +"\n" +">>> # no negative number options, so -1 is a positional argument\n" +">>> parser.parse_args(['-x', '-1'])\n" +"Namespace(foo=None, x='-1')\n" +"\n" +">>> # no negative number options, so -1 and -5 are positional arguments\n" +">>> parser.parse_args(['-x', '-1', '-5'])\n" +"Namespace(foo='-5', x='-1')\n" +"\n" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-1', dest='one')\n" +">>> parser.add_argument('foo', nargs='?')\n" +"\n" +">>> # negative number options present, so -1 is an option\n" +">>> parser.parse_args(['-1', 'X'])\n" +"Namespace(foo=None, one='X')\n" +"\n" +">>> # negative number options present, so -2 is an option\n" +">>> parser.parse_args(['-2'])\n" +"usage: PROG [-h] [-1 ONE] [foo]\n" +"PROG: error: no such option: -2\n" +"\n" +">>> # negative number options present, so both -1s are options\n" +">>> parser.parse_args(['-1', '-1'])\n" +"usage: PROG [-h] [-1 ONE] [foo]\n" +"PROG: error: argument -1: expected one argument" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-x')\n" +">>> parser.add_argument('foo', nargs='?')\n" +"\n" +">>> # nenhuma opção de número negativo, então -1 é um argumento posicional\n" +">>> parser.parse_args(['-x', '-1'])\n" +"Namespace(foo=None, x='-1')\n" +"\n" +">>> # nenhuma opção de número negativo, então -1 e -5 são argumentos " +"posicionais\n" +">>> parser.parse_args(['-x', '-1', '-5'])\n" +"Namespace(foo='-5', x='-1')\n" +"\n" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-1', dest='one')\n" +">>> parser.add_argument('foo', nargs='?')\n" +"\n" +">>> # opção de número negativo presente, então -1 é uma opção\n" +">>> parser.parse_args(['-1', 'X'])\n" +"Namespace(foo=None, one='X')\n" +"\n" +">>> # opção de número negativo presente, então -2 é uma opção\n" +">>> parser.parse_args(['-2'])\n" +"usage: PROG [-h] [-1 ONE] [foo]\n" +"PROG: error: no such option: -2\n" +"\n" +">>> # opções de número negativo presentes, então ambos -1s são opções\n" +">>> parser.parse_args(['-1', '-1'])\n" +"usage: PROG [-h] [-1 ONE] [foo]\n" +"PROG: error: argument -1: expected one argument" + +#: ../../library/argparse.rst:1468 msgid "" "If you have positional arguments that must begin with ``-`` and don't look " "like negative numbers, you can insert the pseudo-argument ``'--'`` which " "tells :meth:`~ArgumentParser.parse_args` that everything after that is a " "positional argument::" msgstr "" +"Se você tiver argumentos posicionais que devem começar com ``-`` e não se " +"parecem com números negativos, você pode inserir o pseudoargumento ``'--'`` " +"que informa :meth:`~ArgumentParser.parse_args` que tudo depois disso é um " +"argumento posicional::" -#: ../../library/argparse.rst:1654 +#: ../../library/argparse.rst:1473 +msgid "" +">>> parser.parse_args(['--', '-f'])\n" +"Namespace(foo='-f', one=None)" +msgstr "" +">>> parser.parse_args(['--', '-f'])\n" +"Namespace(foo='-f', one=None)" + +#: ../../library/argparse.rst:1476 msgid "" "See also :ref:`the argparse howto on ambiguous arguments ` for more details." msgstr "" +"Veja também :ref:`o tutorial do argparse sobre argumentos ambíguos " +"` para mais detalhes." -#: ../../library/argparse.rst:1660 +#: ../../library/argparse.rst:1482 msgid "Argument abbreviations (prefix matching)" -msgstr "" +msgstr "Abreviações de argumento (correspondência de prefixo)" -#: ../../library/argparse.rst:1662 +#: ../../library/argparse.rst:1484 msgid "" "The :meth:`~ArgumentParser.parse_args` method :ref:`by default " "` allows long options to be abbreviated to a prefix, if the " "abbreviation is unambiguous (the prefix matches a unique option)::" msgstr "" - -#: ../../library/argparse.rst:1677 +"O método :meth:`~ArgumentParser.parse_args` :ref:`por padrão ` " +"permite que opções longas sejam abreviadas para um prefixo, se a abreviação " +"não for ambígua (o prefixo corresponde a uma opção única)::" + +#: ../../library/argparse.rst:1488 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-bacon')\n" +">>> parser.add_argument('-badger')\n" +">>> parser.parse_args('-bac MMM'.split())\n" +"Namespace(bacon='MMM', badger=None)\n" +">>> parser.parse_args('-bad WOOD'.split())\n" +"Namespace(bacon=None, badger='WOOD')\n" +">>> parser.parse_args('-ba BA'.split())\n" +"usage: PROG [-h] [-bacon BACON] [-badger BADGER]\n" +"PROG: error: ambiguous option: -ba could match -badger, -bacon" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-bacon')\n" +">>> parser.add_argument('-badger')\n" +">>> parser.parse_args('-bac MMM'.split())\n" +"Namespace(bacon='MMM', badger=None)\n" +">>> parser.parse_args('-bad WOOD'.split())\n" +"Namespace(bacon=None, badger='WOOD')\n" +">>> parser.parse_args('-ba BA'.split())\n" +"usage: PROG [-h] [-bacon BACON] [-badger BADGER]\n" +"PROG: error: ambiguous option: -ba could match -badger, -bacon" + +#: ../../library/argparse.rst:1499 msgid "" "An error is produced for arguments that could produce more than one options. " "This feature can be disabled by setting :ref:`allow_abbrev` to ``False``." msgstr "" +"Um erro é produzido para argumentos que podem produzir mais de uma opção. " +"Este recurso pode ser desabilitado definindo :ref:`allow_abbrev` como " +"``False``." -#: ../../library/argparse.rst:1683 +#: ../../library/argparse.rst:1505 msgid "Beyond ``sys.argv``" msgstr "Além do ``sys.argv``" -#: ../../library/argparse.rst:1685 +#: ../../library/argparse.rst:1507 msgid "" -"Sometimes it may be useful to have an ArgumentParser parse arguments other " -"than those of :data:`sys.argv`. This can be accomplished by passing a list " -"of strings to :meth:`~ArgumentParser.parse_args`. This is useful for " -"testing at the interactive prompt::" +"Sometimes it may be useful to have an :class:`ArgumentParser` parse " +"arguments other than those of :data:`sys.argv`. This can be accomplished by " +"passing a list of strings to :meth:`~ArgumentParser.parse_args`. This is " +"useful for testing at the interactive prompt::" msgstr "" +"Às vezes, pode ser útil ter uma instância de :class:`ArgumentParser` " +"analisando argumentos diferentes daqueles de :data:`sys.argv`. Isso pode ser " +"feito passando uma lista de strings para :meth:`~ArgumentParser.parse_args`. " +"Isso é útil para testar no prompt interativo::" -#: ../../library/argparse.rst:1705 +#: ../../library/argparse.rst:1512 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument(\n" +"... 'integers', metavar='int', type=int, choices=range(10),\n" +"... nargs='+', help='an integer in the range 0..9')\n" +">>> parser.add_argument(\n" +"... '--sum', dest='accumulate', action='store_const', const=sum,\n" +"... default=max, help='sum the integers (default: find the max)')\n" +">>> parser.parse_args(['1', '2', '3', '4'])\n" +"Namespace(accumulate=, integers=[1, 2, 3, 4])\n" +">>> parser.parse_args(['1', '2', '3', '4', '--sum'])\n" +"Namespace(accumulate=, integers=[1, 2, 3, 4])" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument(\n" +"... 'integers', metavar='int', type=int, choices=range(10),\n" +"... nargs='+', help='an integer in the range 0..9')\n" +">>> parser.add_argument(\n" +"... '--sum', dest='accumulate', action='store_const', const=sum,\n" +"... default=max, help='sum the integers (default: find the max)')\n" +">>> parser.parse_args(['1', '2', '3', '4'])\n" +"Namespace(accumulate=, integers=[1, 2, 3, 4])\n" +">>> parser.parse_args(['1', '2', '3', '4', '--sum'])\n" +"Namespace(accumulate=, integers=[1, 2, 3, 4])" + +#: ../../library/argparse.rst:1527 msgid "The Namespace object" msgstr "O objeto Namespace" -#: ../../library/argparse.rst:1709 +#: ../../library/argparse.rst:1531 msgid "" "Simple class used by default by :meth:`~ArgumentParser.parse_args` to create " "an object holding attributes and return it." msgstr "" +"Classe simples usada por padrão por :meth:`~ArgumentParser.parse_args` para " +"criar um objeto contendo atributos e retorná-lo." -#: ../../library/argparse.rst:1712 +#: ../../library/argparse.rst:1534 msgid "" "This class is deliberately simple, just an :class:`object` subclass with a " "readable string representation. If you prefer to have dict-like view of the " "attributes, you can use the standard Python idiom, :func:`vars`::" msgstr "" +"Esta classe é deliberadamente simples, apenas uma subclasse :class:`object` " +"com uma representação de string legível. Se você preferir ter uma visão dos " +"atributos do tipo dict, você pode usar o idioma padrão do Python, :func:" +"`vars`::" -#: ../../library/argparse.rst:1722 +#: ../../library/argparse.rst:1538 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo')\n" +">>> args = parser.parse_args(['--foo', 'BAR'])\n" +">>> vars(args)\n" +"{'foo': 'BAR'}" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo')\n" +">>> args = parser.parse_args(['--foo', 'BAR'])\n" +">>> vars(args)\n" +"{'foo': 'BAR'}" + +#: ../../library/argparse.rst:1544 msgid "" "It may also be useful to have an :class:`ArgumentParser` assign attributes " "to an already existing object, rather than a new :class:`Namespace` object. " "This can be achieved by specifying the ``namespace=`` keyword argument::" msgstr "" +"Também pode ser útil ter um :class:`ArgumentParser` atribuindo atributos a " +"um objeto já existente, em vez de um novo objeto :class:`Namespace`. Isso " +"pode ser obtido especificando o argumento nomeado ``namespace=``::" + +#: ../../library/argparse.rst:1548 +msgid "" +">>> class C:\n" +"... pass\n" +"...\n" +">>> c = C()\n" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo')\n" +">>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)\n" +">>> c.foo\n" +"'BAR'" +msgstr "" +">>> class C:\n" +"... pass\n" +"...\n" +">>> c = C()\n" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo')\n" +">>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)\n" +">>> c.foo\n" +"'BAR'" -#: ../../library/argparse.rst:1738 +#: ../../library/argparse.rst:1560 msgid "Other utilities" -msgstr "" +msgstr "Outros utilitários" -#: ../../library/argparse.rst:1741 +#: ../../library/argparse.rst:1563 msgid "Sub-commands" -msgstr "Sub-comandos" - -#: ../../library/argparse.rst:1748 -msgid "" -"Many programs split up their functionality into a number of sub-commands, " -"for example, the ``svn`` program can invoke sub-commands like ``svn " -"checkout``, ``svn update``, and ``svn commit``. Splitting up functionality " -"this way can be a particularly good idea when a program performs several " -"different functions which require different kinds of command-line " -"arguments. :class:`ArgumentParser` supports the creation of such sub-" -"commands with the :meth:`add_subparsers` method. The :meth:`add_subparsers` " -"method is normally called with no arguments and returns a special action " -"object. This object has a single method, :meth:`~_SubParsersAction." -"add_parser`, which takes a command name and any :class:`ArgumentParser` " -"constructor arguments, and returns an :class:`ArgumentParser` object that " -"can be modified as usual." -msgstr "" - -#: ../../library/argparse.rst:1760 +msgstr "Subcomandos" + +#: ../../library/argparse.rst:1570 +msgid "" +"Many programs split up their functionality into a number of subcommands, for " +"example, the ``svn`` program can invoke subcommands like ``svn checkout``, " +"``svn update``, and ``svn commit``. Splitting up functionality this way can " +"be a particularly good idea when a program performs several different " +"functions which require different kinds of command-line arguments. :class:" +"`ArgumentParser` supports the creation of such subcommands with the :meth:`!" +"add_subparsers` method. The :meth:`!add_subparsers` method is normally " +"called with no arguments and returns a special action object. This object " +"has a single method, :meth:`~_SubParsersAction.add_parser`, which takes a " +"command name and any :class:`!ArgumentParser` constructor arguments, and " +"returns an :class:`!ArgumentParser` object that can be modified as usual." +msgstr "" +"Muitos programas dividem sua funcionalidade em vários subcomandos, por " +"exemplo, o programa ``svn`` pode invocar subcomandos como ``svn checkout``, " +"``svn update`` e ``svn commit``. Dividir a funcionalidade dessa forma pode " +"ser uma ideia particularmente boa quando um programa executa várias funções " +"diferentes que exigem diferentes tipos de argumentos de linha de comando. :" +"class:`ArgumentParser` oferece suporte à criação de tais subcomandos com o " +"método :meth:`!add_subparsers`. O método :meth:`!add_subparsers` é " +"normalmente chamado sem argumentos e retorna um objeto de ação especial. " +"Este objeto tem um único método, :meth:`~_SubParsersAction.add_parser`, que " +"recebe um nome de comando e quaisquer argumentos do construtor :class:`!" +"ArgumentParser` e retorna um objeto :class:`!ArgumentParser` que pode ser " +"modificado normalmente." + +#: ../../library/argparse.rst:1582 msgid "Description of parameters:" msgstr "Descrição de parâmetros:" -#: ../../library/argparse.rst:1762 +#: ../../library/argparse.rst:1584 msgid "" -"title - title for the sub-parser group in help output; by default " +"*title* - title for the sub-parser group in help output; by default " "\"subcommands\" if description is provided, otherwise uses title for " "positional arguments" msgstr "" +"*title* - título para o grupo de subanalisadores na saída de ajuda; por " +"padrão \"subcomandos\" se a descrição for fornecida, caso contrário, usa o " +"título para argumentos posicionais" -#: ../../library/argparse.rst:1766 +#: ../../library/argparse.rst:1588 msgid "" -"description - description for the sub-parser group in help output, by " +"*description* - description for the sub-parser group in help output, by " "default ``None``" msgstr "" +"*description* - descrição para o grupo de subanalisadores na saída de ajuda, " +"por padrão ``None``" -#: ../../library/argparse.rst:1769 +#: ../../library/argparse.rst:1591 msgid "" -"prog - usage information that will be displayed with sub-command help, by " +"*prog* - usage information that will be displayed with sub-command help, by " "default the name of the program and any positional arguments before the " "subparser argument" msgstr "" +"*prog* - informações de uso que serão exibidas com a ajuda do subcomando, " +"por padrão o nome do programa e quaisquer argumentos posicionais antes do " +"argumento do subanalisador" -#: ../../library/argparse.rst:1773 +#: ../../library/argparse.rst:1595 msgid "" -"parser_class - class which will be used to create sub-parser instances, by " -"default the class of the current parser (e.g. ArgumentParser)" +"*parser_class* - class which will be used to create sub-parser instances, by " +"default the class of the current parser (e.g. :class:`ArgumentParser`)" msgstr "" +"*parser_class* - classe que será usada para criar instâncias de " +"subanalisadores, por padrão a classe do analisador atual (por exemplo, :" +"class:`ArgumentParser`)" -#: ../../library/argparse.rst:1776 +#: ../../library/argparse.rst:1598 msgid "" "action_ - the basic type of action to be taken when this argument is " "encountered at the command line" msgstr "" +"action_ - o tipo básico de ação a ser executada quando esse argumento é " +"encontrado na linha de comando" -#: ../../library/argparse.rst:1779 +#: ../../library/argparse.rst:1601 msgid "" "dest_ - name of the attribute under which sub-command name will be stored; " "by default ``None`` and no value is stored" msgstr "" +"dest_ - nome do atributo sob o qual o nome do subcomando será armazenado; " +"por padrão ``None`` e nenhum valor é armazenado" -#: ../../library/argparse.rst:1782 +#: ../../library/argparse.rst:1604 msgid "" "required_ - Whether or not a subcommand must be provided, by default " "``False`` (added in 3.7)" msgstr "" +"required_ - Se um subcomando deve ou não ser fornecido, por padrão ``False`` " +"(adicionado em 3.7)" -#: ../../library/argparse.rst:1785 +#: ../../library/argparse.rst:1607 msgid "help_ - help for sub-parser group in help output, by default ``None``" msgstr "" +"help_ - ajuda para o grupo de subanalisadores na saída de ajuda, por padrão " +"``None``" -#: ../../library/argparse.rst:1787 +#: ../../library/argparse.rst:1609 msgid "" -"metavar_ - string presenting available sub-commands in help; by default it " -"is ``None`` and presents sub-commands in form {cmd1, cmd2, ..}" +"metavar_ - string presenting available subcommands in help; by default it is " +"``None`` and presents subcommands in form {cmd1, cmd2, ..}" msgstr "" +"metavar_ - string que apresenta os subcomandos disponíveis na ajuda; por " +"padrão é ``None`` e apresenta os subcomandos no formato {cmd1, cmd2, ..}" -#: ../../library/argparse.rst:1790 +#: ../../library/argparse.rst:1612 msgid "Some example usage::" msgstr "Alguns exemplos de uso::" -#: ../../library/argparse.rst:1811 +#: ../../library/argparse.rst:1614 +msgid "" +">>> # create the top-level parser\n" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('--foo', action='store_true', help='foo help')\n" +">>> subparsers = parser.add_subparsers(help='subcommand help')\n" +">>>\n" +">>> # create the parser for the \"a\" command\n" +">>> parser_a = subparsers.add_parser('a', help='a help')\n" +">>> parser_a.add_argument('bar', type=int, help='bar help')\n" +">>>\n" +">>> # create the parser for the \"b\" command\n" +">>> parser_b = subparsers.add_parser('b', help='b help')\n" +">>> parser_b.add_argument('--baz', choices=('X', 'Y', 'Z'), help='baz " +"help')\n" +">>>\n" +">>> # parse some argument lists\n" +">>> parser.parse_args(['a', '12'])\n" +"Namespace(bar=12, foo=False)\n" +">>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])\n" +"Namespace(baz='Z', foo=True)" +msgstr "" +">>> # cria o analisador de nível superior\n" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('--foo', action='store_true', help='foo help')\n" +">>> subparsers = parser.add_subparsers(help='subcommand help')\n" +">>>\n" +">>> # cria o analisador para o comando \"a\"\n" +">>> parser_a = subparsers.add_parser('a', help='a help')\n" +">>> parser_a.add_argument('bar', type=int, help='bar help')\n" +">>>\n" +">>> # cria o analisador para o comando \"b\"\n" +">>> parser_b = subparsers.add_parser('b', help='b help')\n" +">>> parser_b.add_argument('--baz', choices=('X', 'Y', 'Z'), help='baz " +"help')\n" +">>>\n" +">>> # analisa algumas listas de argumentos\n" +">>> parser.parse_args(['a', '12'])\n" +"Namespace(bar=12, foo=False)\n" +">>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])\n" +"Namespace(baz='Z', foo=True)" + +#: ../../library/argparse.rst:1633 msgid "" "Note that the object returned by :meth:`parse_args` will only contain " "attributes for the main parser and the subparser that was selected by the " @@ -2135,8 +3461,14 @@ msgid "" "present, and when the ``b`` command is specified, only the ``foo`` and " "``baz`` attributes are present." msgstr "" +"Note que o objeto retornado por :meth:`parse_args` conterá apenas atributos " +"para o analisador principal e o subanalisador que foi selecionado pela linha " +"de comando (e não quaisquer outros subanalisadores). Então, no exemplo " +"acima, quando o comando ``a`` é especificado, apenas os atributos ``foo`` e " +"``bar`` estão presentes, e quando o comando ``b`` é especificado, apenas os " +"atributos ``foo`` e ``baz`` estão presentes." -#: ../../library/argparse.rst:1818 +#: ../../library/argparse.rst:1640 msgid "" "Similarly, when a help message is requested from a subparser, only the help " "for that particular parser will be printed. The help message will not " @@ -2144,37 +3476,233 @@ msgid "" "subparser command, however, can be given by supplying the ``help=`` argument " "to :meth:`~_SubParsersAction.add_parser` as above.)" msgstr "" - -#: ../../library/argparse.rst:1854 +"Similarmente, quando uma mensagem de ajuda é solicitada de um subanalisador, " +"somente a ajuda para aquele parser em particular será impressa. A mensagem " +"de ajuda não incluirá mensagens do analisador sintático pai ou do analisador " +"sintático irmão. (Uma mensagem de ajuda para cada comando do subanalisador, " +"entretanto, pode ser dada fornecendo o argumento ``help=`` para :meth:" +"`~_SubParsersAction.add_parser` como acima.)" + +#: ../../library/argparse.rst:1648 +msgid "" +">>> parser.parse_args(['--help'])\n" +"usage: PROG [-h] [--foo] {a,b} ...\n" +"\n" +"positional arguments:\n" +" {a,b} subcommand help\n" +" a a help\n" +" b b help\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo foo help\n" +"\n" +">>> parser.parse_args(['a', '--help'])\n" +"usage: PROG a [-h] bar\n" +"\n" +"positional arguments:\n" +" bar bar help\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"\n" +">>> parser.parse_args(['b', '--help'])\n" +"usage: PROG b [-h] [--baz {X,Y,Z}]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --baz {X,Y,Z} baz help" +msgstr "" +">>> parser.parse_args(['--help'])\n" +"usage: PROG [-h] [--foo] {a,b} ...\n" +"\n" +"positional arguments:\n" +" {a,b} subcommand help\n" +" a a help\n" +" b b help\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo foo help\n" +"\n" +">>> parser.parse_args(['a', '--help'])\n" +"usage: PROG a [-h] bar\n" +"\n" +"positional arguments:\n" +" bar bar help\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"\n" +">>> parser.parse_args(['b', '--help'])\n" +"usage: PROG b [-h] [--baz {X,Y,Z}]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --baz {X,Y,Z} baz help" + +#: ../../library/argparse.rst:1676 msgid "" "The :meth:`add_subparsers` method also supports ``title`` and " "``description`` keyword arguments. When either is present, the subparser's " "commands will appear in their own group in the help output. For example::" msgstr "" - -#: ../../library/argparse.rst:1875 +"O método :meth:`add_subparsers` também oferece suporte aos argumentos " +"nomeados ``title`` e ``description``. Quando qualquer um deles estiver " +"presente, os comandos do subanalisador aparecerão em seu próprio grupo na " +"saída de ajuda. Por exemplo::" + +#: ../../library/argparse.rst:1680 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> subparsers = parser.add_subparsers(title='subcommands',\n" +"... description='valid subcommands',\n" +"... help='additional help')\n" +">>> subparsers.add_parser('foo')\n" +">>> subparsers.add_parser('bar')\n" +">>> parser.parse_args(['-h'])\n" +"usage: [-h] {foo,bar} ...\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"\n" +"subcommands:\n" +" valid subcommands\n" +"\n" +" {foo,bar} additional help" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> subparsers = parser.add_subparsers(title='subcommands',\n" +"... description='valid subcommands',\n" +"... help='additional help')\n" +">>> subparsers.add_parser('foo')\n" +">>> subparsers.add_parser('bar')\n" +">>> parser.parse_args(['-h'])\n" +"usage: [-h] {foo,bar} ...\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"\n" +"subcommands:\n" +" valid subcommands\n" +"\n" +" {foo,bar} additional help" + +#: ../../library/argparse.rst:1697 msgid "" "Furthermore, :meth:`~_SubParsersAction.add_parser` supports an additional " "*aliases* argument, which allows multiple strings to refer to the same " "subparser. This example, like ``svn``, aliases ``co`` as a shorthand for " "``checkout``::" msgstr "" +"Além disso, :meth:`~_SubParsersAction.add_parser` oferece suporte a um " +"argumento *aliases* adicional, que permite que múltiplas strings se refiram " +"ao mesmo subanalisador. Este exemplo, como ``svn``, alias ``co`` como uma " +"abreviação para ``checkout``::" + +#: ../../library/argparse.rst:1702 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> subparsers = parser.add_subparsers()\n" +">>> checkout = subparsers.add_parser('checkout', aliases=['co'])\n" +">>> checkout.add_argument('foo')\n" +">>> parser.parse_args(['co', 'bar'])\n" +"Namespace(foo='bar')" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> subparsers = parser.add_subparsers()\n" +">>> checkout = subparsers.add_parser('checkout', aliases=['co'])\n" +">>> checkout.add_argument('foo')\n" +">>> parser.parse_args(['co', 'bar'])\n" +"Namespace(foo='bar')" -#: ../../library/argparse.rst:1887 +#: ../../library/argparse.rst:1709 msgid "" ":meth:`~_SubParsersAction.add_parser` supports also an additional " "*deprecated* argument, which allows to deprecate the subparser." msgstr "" +":meth:`~_SubParsersAction.add_parser` oferece suporte também um argumento " +"adicional *deprecated*, que permite descontinuar o subanalisador." -#: ../../library/argparse.rst:1901 +#: ../../library/argparse.rst:1723 msgid "" -"One particularly effective way of handling sub-commands is to combine the " -"use of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` " -"so that each subparser knows which Python function it should execute. For " +"One particularly effective way of handling subcommands is to combine the use " +"of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so " +"that each subparser knows which Python function it should execute. For " "example::" msgstr "" +"Uma maneira particularmente eficaz de lidar com subcomandos é combinar o uso " +"do método :meth:`add_subparsers` com chamadas para :meth:`set_defaults` para " +"que cada subanalisador saiba qual função Python ele deve executar. Por " +"exemplo::" + +#: ../../library/argparse.rst:1728 +msgid "" +">>> # subcommand functions\n" +">>> def foo(args):\n" +"... print(args.x * args.y)\n" +"...\n" +">>> def bar(args):\n" +"... print('((%s))' % args.z)\n" +"...\n" +">>> # create the top-level parser\n" +">>> parser = argparse.ArgumentParser()\n" +">>> subparsers = parser.add_subparsers(required=True)\n" +">>>\n" +">>> # create the parser for the \"foo\" command\n" +">>> parser_foo = subparsers.add_parser('foo')\n" +">>> parser_foo.add_argument('-x', type=int, default=1)\n" +">>> parser_foo.add_argument('y', type=float)\n" +">>> parser_foo.set_defaults(func=foo)\n" +">>>\n" +">>> # create the parser for the \"bar\" command\n" +">>> parser_bar = subparsers.add_parser('bar')\n" +">>> parser_bar.add_argument('z')\n" +">>> parser_bar.set_defaults(func=bar)\n" +">>>\n" +">>> # parse the args and call whatever function was selected\n" +">>> args = parser.parse_args('foo 1 -x 2'.split())\n" +">>> args.func(args)\n" +"2.0\n" +">>>\n" +">>> # parse the args and call whatever function was selected\n" +">>> args = parser.parse_args('bar XYZYX'.split())\n" +">>> args.func(args)\n" +"((XYZYX))" +msgstr "" +">>> # funções do subanalisador functions\n" +">>> def foo(args):\n" +"... print(args.x * args.y)\n" +"...\n" +">>> def bar(args):\n" +"... print('((%s))' % args.z)\n" +"...\n" +">>> # cria o analisador de nível superior\n" +">>> parser = argparse.ArgumentParser()\n" +">>> subparsers = parser.add_subparsers(required=True)\n" +">>>\n" +">>> # cria o analisador do comando \"foo\"\n" +">>> parser_foo = subparsers.add_parser('foo')\n" +">>> parser_foo.add_argument('-x', type=int, default=1)\n" +">>> parser_foo.add_argument('y', type=float)\n" +">>> parser_foo.set_defaults(func=foo)\n" +">>>\n" +">>> # cria o analisador do comando \"foo\"\n" +">>> parser_bar = subparsers.add_parser('bar')\n" +">>> parser_bar.add_argument('z')\n" +">>> parser_bar.set_defaults(func=bar)\n" +">>>\n" +">>> # analisa os argumentos e chama a função que for selecionada\n" +">>> args = parser.parse_args('foo 1 -x 2'.split())\n" +">>> args.func(args)\n" +"2.0\n" +">>>\n" +">>> # analisa os argumentos e chama a função que foi selecionada\n" +">>> args = parser.parse_args('bar XYZYX'.split())\n" +">>> args.func(args)\n" +"((XYZYX))" -#: ../../library/argparse.rst:1938 +#: ../../library/argparse.rst:1760 msgid "" "This way, you can let :meth:`parse_args` do the job of calling the " "appropriate function after argument parsing is complete. Associating " @@ -2183,16 +3711,43 @@ msgid "" "to check the name of the subparser that was invoked, the ``dest`` keyword " "argument to the :meth:`add_subparsers` call will work::" msgstr "" +"Dessa forma, você pode deixar :meth:`parse_args` fazer o trabalho de chamar " +"a função apropriada após a análise sintática do argumento ser concluída. " +"Associar funções com ações como essa é normalmente a maneira mais fácil de " +"lidar com as diferentes ações para cada um dos seus subanalisadores. No " +"entanto, se for necessário verificar o nome do subanalisador que foi " +"invocado, o argumento nomeado ``dest`` para a chamada :meth:`add_subparsers` " +"funcionará::" + +#: ../../library/argparse.rst:1767 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> subparsers = parser.add_subparsers(dest='subparser_name')\n" +">>> subparser1 = subparsers.add_parser('1')\n" +">>> subparser1.add_argument('-x')\n" +">>> subparser2 = subparsers.add_parser('2')\n" +">>> subparser2.add_argument('y')\n" +">>> parser.parse_args(['2', 'frobble'])\n" +"Namespace(subparser_name='2', y='frobble')" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> subparsers = parser.add_subparsers(dest='subparser_name')\n" +">>> subparser1 = subparsers.add_parser('1')\n" +">>> subparser1.add_argument('-x')\n" +">>> subparser2 = subparsers.add_parser('2')\n" +">>> subparser2.add_argument('y')\n" +">>> parser.parse_args(['2', 'frobble'])\n" +"Namespace(subparser_name='2', y='frobble')" -#: ../../library/argparse.rst:1954 -msgid "New *required* keyword argument." -msgstr "" +#: ../../library/argparse.rst:1776 +msgid "New *required* keyword-only parameter." +msgstr "Novo parâmetro somente-nomeado *required*." -#: ../../library/argparse.rst:1959 +#: ../../library/argparse.rst:1781 msgid "FileType objects" msgstr "Objetos FileType" -#: ../../library/argparse.rst:1963 +#: ../../library/argparse.rst:1785 msgid "" "The :class:`FileType` factory creates objects that can be passed to the type " "argument of :meth:`ArgumentParser.add_argument`. Arguments that have :class:" @@ -2200,95 +3755,324 @@ msgid "" "with the requested modes, buffer sizes, encodings and error handling (see " "the :func:`open` function for more details)::" msgstr "" - -#: ../../library/argparse.rst:1975 +"A fábrica :class:`FileType` cria objetos que podem ser passados para o " +"argumento de tipo de :meth:`ArgumentParser.add_argument`. Argumentos que têm " +"objetos :class:`FileType` como seu tipo abrirão argumentos de linha de " +"comando como arquivos com os modos solicitados, tamanhos de buffer, " +"codificações e tratamento de erros (veja a função :func:`open` para mais " +"detalhes)::" + +#: ../../library/argparse.rst:1791 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))\n" +">>> parser.add_argument('out', type=argparse.FileType('w', " +"encoding='UTF-8'))\n" +">>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])\n" +"Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, " +"raw=<_io.FileIO name='raw.dat' mode='wb'>)" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))\n" +">>> parser.add_argument('out', type=argparse.FileType('w', " +"encoding='UTF-8'))\n" +">>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])\n" +"Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, " +"raw=<_io.FileIO name='raw.dat' mode='wb'>)" + +#: ../../library/argparse.rst:1797 msgid "" "FileType objects understand the pseudo-argument ``'-'`` and automatically " "convert this into :data:`sys.stdin` for readable :class:`FileType` objects " "and :data:`sys.stdout` for writable :class:`FileType` objects::" msgstr "" +"Objetos FileType entendem o pseudoargumento ``'-'`` e o convertem " +"automaticamente em :data:`sys.stdin` para objetos :class:`FileType` legíveis " +"e :data:`sys.stdout` para objetos :class:`FileType` graváveis::" -#: ../../library/argparse.rst:1984 -msgid "Added the *encodings* and *errors* parameters." +#: ../../library/argparse.rst:1801 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('infile', type=argparse.FileType('r'))\n" +">>> parser.parse_args(['-'])\n" +"Namespace(infile=<_io.TextIOWrapper name='' encoding='UTF-8'>)" msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('infile', type=argparse.FileType('r'))\n" +">>> parser.parse_args(['-'])\n" +"Namespace(infile=<_io.TextIOWrapper name='' encoding='UTF-8'>)" + +#: ../../library/argparse.rst:1806 +msgid "Added the *encodings* and *errors* parameters." +msgstr "Adicionados os parâmetros *encodings* e *errors*." -#: ../../library/argparse.rst:1989 +#: ../../library/argparse.rst:1811 msgid "Argument groups" -msgstr "Grupos de Argumentos" +msgstr "Grupos de argumentos" -#: ../../library/argparse.rst:1993 +#: ../../library/argparse.rst:1816 msgid "" "By default, :class:`ArgumentParser` groups command-line arguments into " "\"positional arguments\" and \"options\" when displaying help messages. When " "there is a better conceptual grouping of arguments than this default one, " -"appropriate groups can be created using the :meth:`add_argument_group` " +"appropriate groups can be created using the :meth:`!add_argument_group` " "method::" msgstr "" - -#: ../../library/argparse.rst:2010 +"Por padrão, :class:`ArgumentParser` agrupa argumentos de linha de comando em " +"\"argumentos posicionais\" e \"opções\" ao exibir mensagens de ajuda. Quando " +"há um melhor agrupamento conceitual de argumentos do que este padrão, grupos " +"apropriados podem ser criados usando o método :meth:`!add_argument_group`::" + +#: ../../library/argparse.rst:1822 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)\n" +">>> group = parser.add_argument_group('group')\n" +">>> group.add_argument('--foo', help='foo help')\n" +">>> group.add_argument('bar', help='bar help')\n" +">>> parser.print_help()\n" +"usage: PROG [--foo FOO] bar\n" +"\n" +"group:\n" +" bar bar help\n" +" --foo FOO foo help" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)\n" +">>> group = parser.add_argument_group('grupo')\n" +">>> group.add_argument('--foo', help='ajuda de foo')\n" +">>> group.add_argument('bar', help='ajuda de bar')\n" +">>> parser.print_help()\n" +"usage: PROG [--foo FOO] bar\n" +"\n" +"grupo:\n" +" bar ajuda de bar\n" +" --foo FOO ajuda de foo" + +#: ../../library/argparse.rst:1833 msgid "" "The :meth:`add_argument_group` method returns an argument group object which " "has an :meth:`~ArgumentParser.add_argument` method just like a regular :" "class:`ArgumentParser`. When an argument is added to the group, the parser " "treats it just like a normal argument, but displays the argument in a " -"separate group for help messages. The :meth:`add_argument_group` method " +"separate group for help messages. The :meth:`!add_argument_group` method " "accepts *title* and *description* arguments which can be used to customize " "this display::" msgstr "" - -#: ../../library/argparse.rst:2036 +"O método :meth:`add_argument_group` retorna um objeto de grupo de argumentos " +"que tem um método :meth:`~ArgumentParser.add_argument` como um :class:" +"`ArgumentParser` regular. Quando um argumento é adicionado ao grupo, o " +"analisador o trata como um argumento normal, mas exibe o argumento em um " +"grupo separado para mensagens de ajuda. O método :meth:`!add_argument_group` " +"aceita argumentos *title* e *description* que podem ser usados para " +"personalizar esta exibição::" + +#: ../../library/argparse.rst:1841 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)\n" +">>> group1 = parser.add_argument_group('group1', 'group1 description')\n" +">>> group1.add_argument('foo', help='foo help')\n" +">>> group2 = parser.add_argument_group('group2', 'group2 description')\n" +">>> group2.add_argument('--bar', help='bar help')\n" +">>> parser.print_help()\n" +"usage: PROG [--bar BAR] foo\n" +"\n" +"group1:\n" +" group1 description\n" +"\n" +" foo foo help\n" +"\n" +"group2:\n" +" group2 description\n" +"\n" +" --bar BAR bar help" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)\n" +">>> group1 = parser.add_argument_group('grupo1', 'descrição do grupo1')\n" +">>> group1.add_argument('foo', help='ajuda de foo')\n" +">>> group2 = parser.add_argument_group('grupo2', 'descrição do grupo2')\n" +">>> group2.add_argument('--bar', help='ajuda de bar')\n" +">>> parser.print_help()\n" +"usage: PROG [--bar BAR] foo\n" +"\n" +"grupo1:\n" +" descrição de grupo1\n" +"\n" +" foo ajuda de foo\n" +"\n" +"grupo2:\n" +" descrição de grupo2\n" +"\n" +" --bar BAR ajuda de bar" + +#: ../../library/argparse.rst:1859 +msgid "" +"The optional, keyword-only parameters argument_default_ and " +"conflict_handler_ allow for finer-grained control of the behavior of the " +"argument group. These parameters have the same meaning as in the :class:" +"`ArgumentParser` constructor, but apply specifically to the argument group " +"rather than the entire parser." +msgstr "" +"Os parâmetros opcionais somente-nomeados argument_default_ e " +"conflict_handler_ permitem um controle mais refinado do comportamento do " +"grupo de argumentos. Esses parâmetros têm o mesmo significado que no " +"construtor :class:`ArgumentParser`, mas se aplicam especificamente ao grupo " +"de argumentos em vez de ao analisador sintático inteiro." + +#: ../../library/argparse.rst:1864 msgid "" "Note that any arguments not in your user-defined groups will end up back in " "the usual \"positional arguments\" and \"optional arguments\" sections." msgstr "" +"Observe que quaisquer argumentos que não estejam nos grupos definidos pelo " +"usuário retornarão às seções usuais de \"argumentos posicionais\" e " +"\"argumentos opcionais\"." -#: ../../library/argparse.rst:2039 +#: ../../library/argparse.rst:1867 msgid "" "Calling :meth:`add_argument_group` on an argument group is deprecated. This " "feature was never supported and does not always work correctly. The function " "exists on the API by accident through inheritance and will be removed in the " "future." msgstr "" +"Chamar :meth:`add_argument_group` em um grupo de argumentos está " +"descontinuado. Esse recurso nunca foi suportado e nem sempre funciona " +"corretamente. A função existe na API por acidente por herança e será " +"removida no futuro." -#: ../../library/argparse.rst:2047 +#: ../../library/argparse.rst:1875 msgid "Mutual exclusion" -msgstr "Exclusão Mútua" +msgstr "Exclusão mútua" -#: ../../library/argparse.rst:2051 +#: ../../library/argparse.rst:1879 msgid "" -"Create a mutually exclusive group. :mod:`argparse` will make sure that only " +"Create a mutually exclusive group. :mod:`!argparse` will make sure that only " "one of the arguments in the mutually exclusive group was present on the " "command line::" msgstr "" - -#: ../../library/argparse.rst:2067 +"Cria um grupo mutuamente exclusivo. :mod:`!argparse` garantirá que apenas um " +"dos argumentos no grupo mutuamente exclusivo esteja presente na linha de " +"comando::" + +#: ../../library/argparse.rst:1883 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> group = parser.add_mutually_exclusive_group()\n" +">>> group.add_argument('--foo', action='store_true')\n" +">>> group.add_argument('--bar', action='store_false')\n" +">>> parser.parse_args(['--foo'])\n" +"Namespace(bar=True, foo=True)\n" +">>> parser.parse_args(['--bar'])\n" +"Namespace(bar=False, foo=False)\n" +">>> parser.parse_args(['--foo', '--bar'])\n" +"usage: PROG [-h] [--foo | --bar]\n" +"PROG: error: argument --bar: not allowed with argument --foo" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> group = parser.add_mutually_exclusive_group()\n" +">>> group.add_argument('--foo', action='store_true')\n" +">>> group.add_argument('--bar', action='store_false')\n" +">>> parser.parse_args(['--foo'])\n" +"Namespace(bar=True, foo=True)\n" +">>> parser.parse_args(['--bar'])\n" +"Namespace(bar=False, foo=False)\n" +">>> parser.parse_args(['--foo', '--bar'])\n" +"usage: PROG [-h] [--foo | --bar]\n" +"PROG: error: argument --bar: not allowed with argument --foo" + +#: ../../library/argparse.rst:1895 msgid "" "The :meth:`add_mutually_exclusive_group` method also accepts a *required* " "argument, to indicate that at least one of the mutually exclusive arguments " "is required::" msgstr "" +"O método :meth:`add_mutually_exclusive_group` também aceita um argumento " +"*obrigatório*, para indicar que pelo menos um dos argumentos mutuamente " +"exclusivos é necessário::" -#: ../../library/argparse.rst:2079 +#: ../../library/argparse.rst:1899 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> group = parser.add_mutually_exclusive_group(required=True)\n" +">>> group.add_argument('--foo', action='store_true')\n" +">>> group.add_argument('--bar', action='store_false')\n" +">>> parser.parse_args([])\n" +"usage: PROG [-h] (--foo | --bar)\n" +"PROG: error: one of the arguments --foo --bar is required" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> group = parser.add_mutually_exclusive_group(required=True)\n" +">>> group.add_argument('--foo', action='store_true')\n" +">>> group.add_argument('--bar', action='store_false')\n" +">>> parser.parse_args([])\n" +"usage: PROG [-h] (--foo | --bar)\n" +"PROG: error: one of the arguments --foo --bar is required" + +#: ../../library/argparse.rst:1907 msgid "" "Note that currently mutually exclusive argument groups do not support the " "*title* and *description* arguments of :meth:`~ArgumentParser." "add_argument_group`. However, a mutually exclusive group can be added to an " "argument group that has a title and description. For example::" msgstr "" - -#: ../../library/argparse.rst:2102 +"Observe que atualmente grupos de argumentos mutuamente exclusivos não " +"oferecem suporte aos argumentos *title* e *description* de :meth:" +"`~ArgumentParser.add_argument_group`. No entanto, um grupo mutuamente " +"exclusivo pode ser adicionado a um grupo de argumentos que tenha um título e " +"uma descrição. Por exemplo::" + +#: ../../library/argparse.rst:1913 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> group = parser.add_argument_group('Group title', 'Group description')\n" +">>> exclusive_group = group.add_mutually_exclusive_group(required=True)\n" +">>> exclusive_group.add_argument('--foo', help='foo help')\n" +">>> exclusive_group.add_argument('--bar', help='bar help')\n" +">>> parser.print_help()\n" +"usage: PROG [-h] (--foo FOO | --bar BAR)\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"\n" +"Group title:\n" +" Group description\n" +"\n" +" --foo FOO foo help\n" +" --bar BAR bar help" +msgstr "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> group = parser.add_argument_group('Título do grupo', 'Descrição do " +"grupo')\n" +">>> exclusive_group = group.add_mutually_exclusive_group(required=True)\n" +">>> exclusive_group.add_argument('--foo', help='ajuda de foo')\n" +">>> exclusive_group.add_argument('--bar', help='ajuda de bar')\n" +">>> parser.print_help()\n" +"usage: PROG [-h] (--foo FOO | --bar BAR)\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"\n" +"Título do grupo:\n" +" Descrição do grupo\n" +"\n" +" --foo FOO foo help\n" +" --bar BAR bar help" + +#: ../../library/argparse.rst:1930 msgid "" "Calling :meth:`add_argument_group` or :meth:`add_mutually_exclusive_group` " "on a mutually exclusive group is deprecated. These features were never " "supported and do not always work correctly. The functions exist on the API " "by accident through inheritance and will be removed in the future." msgstr "" +"Chamar :meth:`add_argument_group` ou :meth:`add_mutually_exclusive_group` em " +"um grupo mutuamente exclusivo está descontinuado. Esses recursos nunca foram " +"suportados e nem sempre funcionam corretamente. As funções existem na API " +"por acidente por herança e serão removidas no futuro." -#: ../../library/argparse.rst:2110 +#: ../../library/argparse.rst:1938 msgid "Parser defaults" -msgstr "" +msgstr "Padrões do analisador sintático" -#: ../../library/argparse.rst:2114 +#: ../../library/argparse.rst:1942 msgid "" "Most of the time, the attributes of the object returned by :meth:" "`parse_args` will be fully determined by inspecting the command-line " @@ -2296,73 +4080,142 @@ msgid "" "additional attributes that are determined without any inspection of the " "command line to be added::" msgstr "" +"Na maioria das vezes, os atributos do objeto retornado por :meth:" +"`parse_args` serão totalmente determinados pela inspeção dos argumentos da " +"linha de comando e das ações dos argumentos. :meth:`set_defaults` permite " +"que alguns atributos adicionais que são determinados sem qualquer inspeção " +"da linha de comando sejam adicionados::" -#: ../../library/argparse.rst:2126 +#: ../../library/argparse.rst:1948 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('foo', type=int)\n" +">>> parser.set_defaults(bar=42, baz='badger')\n" +">>> parser.parse_args(['736'])\n" +"Namespace(bar=42, baz='badger', foo=736)" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('foo', type=int)\n" +">>> parser.set_defaults(bar=42, baz='badger')\n" +">>> parser.parse_args(['736'])\n" +"Namespace(bar=42, baz='badger', foo=736)" + +#: ../../library/argparse.rst:1954 msgid "" "Note that parser-level defaults always override argument-level defaults::" msgstr "" +"Observe que os padrões no nível do analisador sempre substituem os padrões " +"no nível do argumento:" + +#: ../../library/argparse.rst:1956 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', default='bar')\n" +">>> parser.set_defaults(foo='spam')\n" +">>> parser.parse_args([])\n" +"Namespace(foo='spam')" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', default='bar')\n" +">>> parser.set_defaults(foo='spam')\n" +">>> parser.parse_args([])\n" +"Namespace(foo='spam')" -#: ../../library/argparse.rst:2134 +#: ../../library/argparse.rst:1962 msgid "" "Parser-level defaults can be particularly useful when working with multiple " "parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an " "example of this type." msgstr "" +"Padrões de nível de analisador podem ser particularmente úteis ao trabalhar " +"com vários analisadores. Veja o método :meth:`~ArgumentParser." +"add_subparsers` para um exemplo desse tipo." -#: ../../library/argparse.rst:2140 +#: ../../library/argparse.rst:1968 msgid "" "Get the default value for a namespace attribute, as set by either :meth:" "`~ArgumentParser.add_argument` or by :meth:`~ArgumentParser.set_defaults`::" msgstr "" +"Obtém o valor padrão para um atributo de espaço de nomes, conforme definido " +"por :meth:`~ArgumentParser.add_argument` ou por :meth:`~ArgumentParser." +"set_defaults`::" -#: ../../library/argparse.rst:2151 +#: ../../library/argparse.rst:1972 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', default='badger')\n" +">>> parser.get_default('foo')\n" +"'badger'" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', default='badger')\n" +">>> parser.get_default('foo')\n" +"'badger'" + +#: ../../library/argparse.rst:1979 msgid "Printing help" msgstr "Imprimindo a ajuda" -#: ../../library/argparse.rst:2153 +#: ../../library/argparse.rst:1981 msgid "" "In most typical applications, :meth:`~ArgumentParser.parse_args` will take " "care of formatting and printing any usage or error messages. However, " "several formatting methods are available:" msgstr "" +"Na maioria das aplicações típicas, :meth:`~ArgumentParser.parse_args` " +"cuidará da formatação e da impressão de quaisquer mensagens de uso ou erro. " +"No entanto, vários métodos de formatação estão disponíveis:" -#: ../../library/argparse.rst:2159 +#: ../../library/argparse.rst:1987 msgid "" "Print a brief description of how the :class:`ArgumentParser` should be " "invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is " "assumed." msgstr "" +"Imprime uma breve descrição de como o :class:`ArgumentParser` deve ser " +"invocado na linha de comando. Se *file* for ``None``, :data:`sys.stdout` " +"será presumido." -#: ../../library/argparse.rst:2165 +#: ../../library/argparse.rst:1993 msgid "" "Print a help message, including the program usage and information about the " "arguments registered with the :class:`ArgumentParser`. If *file* is " "``None``, :data:`sys.stdout` is assumed." msgstr "" +"Imprime uma mensagem de ajuda, incluindo o uso do programa e informações " +"sobre os argumentos registrados com o :class:`ArgumentParser`. Se *file* for " +"``None``, :data:`sys.stdout` será presumido." -#: ../../library/argparse.rst:2169 +#: ../../library/argparse.rst:1997 msgid "" "There are also variants of these methods that simply return a string instead " "of printing it:" msgstr "" +"Também há variantes desses métodos que simplesmente retornam uma string em " +"vez de imprimi-la:" -#: ../../library/argparse.rst:2174 +#: ../../library/argparse.rst:2002 msgid "" "Return a string containing a brief description of how the :class:" "`ArgumentParser` should be invoked on the command line." msgstr "" +"Retorna uma string contendo uma breve descrição de como o :class:" +"`ArgumentParser` deve ser invocado na linha de comando." -#: ../../library/argparse.rst:2179 +#: ../../library/argparse.rst:2007 msgid "" "Return a string containing a help message, including the program usage and " "information about the arguments registered with the :class:`ArgumentParser`." msgstr "" +"Retorna uma string contendo uma mensagem de ajuda, incluindo o uso do " +"programa e informações sobre os argumentos registrados com o :class:" +"`ArgumentParser`." -#: ../../library/argparse.rst:2184 +#: ../../library/argparse.rst:2012 msgid "Partial parsing" msgstr "Análise parcial" -#: ../../library/argparse.rst:2188 +#: ../../library/argparse.rst:2016 msgid "" "Sometimes a script may only parse a few of the command-line arguments, " "passing the remaining arguments on to another script or program. In these " @@ -2372,227 +4225,298 @@ msgid "" "a two item tuple containing the populated namespace and the list of " "remaining argument strings." msgstr "" +"Às vezes, um script pode analisar apenas alguns dos argumentos da linha de " +"comando, passando os argumentos restantes para outro script ou programa. " +"Nesses casos, o método :meth:`~ArgumentParser.parse_known_args` pode ser " +"útil. Ele funciona muito como :meth:`~ArgumentParser.parse_args`, exceto que " +"não produz um erro quando argumentos extras estão presentes. Em vez disso, " +"ele retorna uma tupla de dois itens contendo o espaço de nomes preenchido e " +"a lista de strings de argumentos restantes." -#: ../../library/argparse.rst:2204 +#: ../../library/argparse.rst:2025 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action='store_true')\n" +">>> parser.add_argument('bar')\n" +">>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])\n" +"(Namespace(bar='BAR', foo=True), ['--badger', 'spam'])" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action='store_true')\n" +">>> parser.add_argument('bar')\n" +">>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])\n" +"(Namespace(bar='BAR', foo=True), ['--badger', 'spam'])" + +#: ../../library/argparse.rst:2032 msgid "" ":ref:`Prefix matching ` rules apply to :meth:" "`~ArgumentParser.parse_known_args`. The parser may consume an option even if " "it's just a prefix of one of its known options, instead of leaving it in the " "remaining arguments list." msgstr "" +"As regras de :ref:`correspondência de prefixo ` se aplicam " +"a :meth:`~ArgumentParser.parse_known_args`. O analisador pode usar uma opção " +"mesmo que seja apenas um prefixo de uma de suas opções conhecidas, em vez de " +"deixá-la na lista de argumentos restantes." -#: ../../library/argparse.rst:2211 +#: ../../library/argparse.rst:2039 msgid "Customizing file parsing" -msgstr "" +msgstr "Personalizando a análise de arquivos" -#: ../../library/argparse.rst:2215 +#: ../../library/argparse.rst:2043 msgid "" "Arguments that are read from a file (see the *fromfile_prefix_chars* keyword " "argument to the :class:`ArgumentParser` constructor) are read one argument " "per line. :meth:`convert_arg_line_to_args` can be overridden for fancier " "reading." msgstr "" +"Argumentos lidos de um arquivo (veja o argumento nomeado " +"*fromfile_prefix_chars* para o construtor :class:`ArgumentParser`) são lidos " +"com um argumento por linha. :meth:`convert_arg_line_to_args` pode ser " +"substituído para uma leitura mais sofisticada." -#: ../../library/argparse.rst:2220 +#: ../../library/argparse.rst:2048 msgid "" "This method takes a single argument *arg_line* which is a string read from " "the argument file. It returns a list of arguments parsed from this string. " "The method is called once per line read from the argument file, in order." msgstr "" +"Este método recebe um único argumento *arg_line* que é uma string lida do " +"arquivo de argumentos. Ele retorna uma lista de argumentos analisados dessa " +"string. O método é chamado uma vez por linha lida do arquivo de argumentos, " +"em ordem." -#: ../../library/argparse.rst:2224 +#: ../../library/argparse.rst:2052 msgid "" "A useful override of this method is one that treats each space-separated " "word as an argument. The following example demonstrates how to do this::" msgstr "" +"Uma substituição útil desse método é aquela que trata cada palavra separada " +"por espaços como um argumento. O exemplo a seguir demonstra como fazer isso::" + +#: ../../library/argparse.rst:2055 +msgid "" +"class MyArgumentParser(argparse.ArgumentParser):\n" +" def convert_arg_line_to_args(self, arg_line):\n" +" return arg_line.split()" +msgstr "" +"class MyArgumentParser(argparse.ArgumentParser):\n" +" def convert_arg_line_to_args(self, arg_line):\n" +" return arg_line.split()" -#: ../../library/argparse.rst:2233 +#: ../../library/argparse.rst:2061 msgid "Exiting methods" -msgstr "Métodos existentes" +msgstr "Métodos de saída" -#: ../../library/argparse.rst:2237 +#: ../../library/argparse.rst:2065 msgid "" "This method terminates the program, exiting with the specified *status* and, " -"if given, it prints a *message* before that. The user can override this " -"method to handle these steps differently::" +"if given, it prints a *message* to :data:`sys.stderr` before that. The user " +"can override this method to handle these steps differently::" msgstr "" +"Este método encerra o programa, saindo com o *status* especificado e, se " +"fornecido, imprime uma *message* para :data:`sys.stderr` antes disso. O " +"usuário pode sobrescrever este método para lidar com essas etapas de forma " +"diferente::" -#: ../../library/argparse.rst:2249 +#: ../../library/argparse.rst:2069 msgid "" -"This method prints a usage message including the *message* to the standard " -"error and terminates the program with a status code of 2." +"class ErrorCatchingArgumentParser(argparse.ArgumentParser):\n" +" def exit(self, status=0, message=None):\n" +" if status:\n" +" raise Exception(f'Exiting because of an error: {message}')\n" +" exit(status)" msgstr "" +"class ErrorCatchingArgumentParser(argparse.ArgumentParser):\n" +" def exit(self, status=0, message=None):\n" +" if status:\n" +" raise Exception(f'Exiting because of an error: {message}')\n" +" exit(status)" -#: ../../library/argparse.rst:2254 -msgid "Intermixed parsing" +#: ../../library/argparse.rst:2077 +msgid "" +"This method prints a usage message, including the *message*, to :data:`sys." +"stderr` and terminates the program with a status code of 2." msgstr "" +"Este método imprime uma mensagem de uso, incluindo a *message*, em :data:" +"`sys.stderr` e encerra o programa com um código de status 2." -#: ../../library/argparse.rst:2259 +#: ../../library/argparse.rst:2082 +msgid "Intermixed parsing" +msgstr "Análise misturada" + +#: ../../library/argparse.rst:2087 msgid "" "A number of Unix commands allow the user to intermix optional arguments with " "positional arguments. The :meth:`~ArgumentParser.parse_intermixed_args` " "and :meth:`~ArgumentParser.parse_known_intermixed_args` methods support this " "parsing style." msgstr "" +"Vários comandos Unix permitem que o usuário misture argumentos opcionais com " +"argumentos posicionais. Os métodos :meth:`~ArgumentParser." +"parse_intermixed_args` e :meth:`~ArgumentParser.parse_known_intermixed_args` " +"oferecem suporte a esse estilo de análise." -#: ../../library/argparse.rst:2264 +#: ../../library/argparse.rst:2092 msgid "" -"These parsers do not support all the argparse features, and will raise " -"exceptions if unsupported features are used. In particular, subparsers, and " -"mutually exclusive groups that include both optionals and positionals are " -"not supported." +"These parsers do not support all the :mod:`!argparse` features, and will " +"raise exceptions if unsupported features are used. In particular, " +"subparsers, and mutually exclusive groups that include both optionals and " +"positionals are not supported." msgstr "" +"Esses analisadores não oferecem suporte a todos os recursos do :mod:`!" +"argparse` e vão levantar exceções se recursos não suportados forem usados. " +"Em particular, subanalisadores e grupos mutuamente exclusivos que incluem " +"tanto opcionais quanto posicionais não são suportados." -#: ../../library/argparse.rst:2269 +#: ../../library/argparse.rst:2097 msgid "" "The following example shows the difference between :meth:`~ArgumentParser." "parse_known_args` and :meth:`~ArgumentParser.parse_intermixed_args`: the " "former returns ``['2', '3']`` as unparsed arguments, while the latter " "collects all the positionals into ``rest``. ::" msgstr "" - -#: ../../library/argparse.rst:2284 +"O exemplo a seguir mostra a diferença entre :meth:`~ArgumentParser." +"parse_known_args` e :meth:`~ArgumentParser.parse_intermixed_args`: o " +"primeiro retorna ``['2', '3']`` como argumentos não analisados, enquanto o " +"último coleta todos os posicionais em ``rest``. ::" + +#: ../../library/argparse.rst:2103 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo')\n" +">>> parser.add_argument('cmd')\n" +">>> parser.add_argument('rest', nargs='*', type=int)\n" +">>> parser.parse_known_args('doit 1 --foo bar 2 3'.split())\n" +"(Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])\n" +">>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())\n" +"Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo')\n" +">>> parser.add_argument('cmd')\n" +">>> parser.add_argument('rest', nargs='*', type=int)\n" +">>> parser.parse_known_args('doit 1 --foo bar 2 3'.split())\n" +"(Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])\n" +">>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())\n" +"Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])" + +#: ../../library/argparse.rst:2112 msgid "" ":meth:`~ArgumentParser.parse_known_intermixed_args` returns a two item tuple " "containing the populated namespace and the list of remaining argument " "strings. :meth:`~ArgumentParser.parse_intermixed_args` raises an error if " "there are any remaining unparsed argument strings." msgstr "" - -#: ../../library/argparse.rst:2294 -msgid "Upgrading optparse code" -msgstr "" - -#: ../../library/argparse.rst:2296 -msgid "" -"Originally, the :mod:`argparse` module had attempted to maintain " -"compatibility with :mod:`optparse`. However, :mod:`optparse` was difficult " -"to extend transparently, particularly with the changes required to support " -"the new ``nargs=`` specifiers and better usage messages. When most " -"everything in :mod:`optparse` had either been copy-pasted over or monkey-" -"patched, it no longer seemed practical to try to maintain the backwards " -"compatibility." -msgstr "" - -#: ../../library/argparse.rst:2303 -msgid "" -"The :mod:`argparse` module improves on the standard library :mod:`optparse` " -"module in a number of ways including:" -msgstr "" - -#: ../../library/argparse.rst:2306 -msgid "Handling positional arguments." -msgstr "Tratando argumentos posicionais." - -#: ../../library/argparse.rst:2307 -msgid "Supporting sub-commands." -msgstr "" - -#: ../../library/argparse.rst:2308 -msgid "Allowing alternative option prefixes like ``+`` and ``/``." -msgstr "" - -#: ../../library/argparse.rst:2309 -msgid "Handling zero-or-more and one-or-more style arguments." -msgstr "" - -#: ../../library/argparse.rst:2310 -msgid "Producing more informative usage messages." -msgstr "" - -#: ../../library/argparse.rst:2311 -msgid "Providing a much simpler interface for custom ``type`` and ``action``." -msgstr "" - -#: ../../library/argparse.rst:2313 -msgid "A partial upgrade path from :mod:`optparse` to :mod:`argparse`:" -msgstr "" - -#: ../../library/argparse.rst:2315 -msgid "" -"Replace all :meth:`optparse.OptionParser.add_option` calls with :meth:" -"`ArgumentParser.add_argument` calls." -msgstr "" - -#: ../../library/argparse.rst:2318 -msgid "" -"Replace ``(options, args) = parser.parse_args()`` with ``args = parser." -"parse_args()`` and add additional :meth:`ArgumentParser.add_argument` calls " -"for the positional arguments. Keep in mind that what was previously called " -"``options``, now in the :mod:`argparse` context is called ``args``." -msgstr "" - -#: ../../library/argparse.rst:2323 -msgid "" -"Replace :meth:`optparse.OptionParser.disable_interspersed_args` by using :" -"meth:`~ArgumentParser.parse_intermixed_args` instead of :meth:" -"`~ArgumentParser.parse_args`." -msgstr "" - -#: ../../library/argparse.rst:2327 -msgid "" -"Replace callback actions and the ``callback_*`` keyword arguments with " -"``type`` or ``action`` arguments." -msgstr "" - -#: ../../library/argparse.rst:2330 -msgid "" -"Replace string names for ``type`` keyword arguments with the corresponding " -"type objects (e.g. int, float, complex, etc)." -msgstr "" - -#: ../../library/argparse.rst:2333 -msgid "" -"Replace :class:`optparse.Values` with :class:`Namespace` and :exc:`optparse." -"OptionError` and :exc:`optparse.OptionValueError` with :exc:`ArgumentError`." -msgstr "" - -#: ../../library/argparse.rst:2337 -msgid "" -"Replace strings with implicit arguments such as ``%default`` or ``%prog`` " -"with the standard Python syntax to use dictionaries to format strings, that " -"is, ``%(default)s`` and ``%(prog)s``." -msgstr "" - -#: ../../library/argparse.rst:2341 -msgid "" -"Replace the OptionParser constructor ``version`` argument with a call to " -"``parser.add_argument('--version', action='version', version='')``." -msgstr "" - -#: ../../library/argparse.rst:2345 +":meth:`~ArgumentParser.parse_known_intermixed_args` retorna uma tupla de " +"dois itens contendo o espaço de nomes preenchido e a lista de strings de " +"argumentos restantes. :meth:`~ArgumentParser.parse_intermixed_args` levanta " +"um erro se houver strings de argumentos não analisadas restantes." + +#: ../../library/argparse.rst:2121 +msgid "Registering custom types or actions" +msgstr "Registrando ações e tipos personalizados" + +#: ../../library/argparse.rst:2125 +msgid "" +"Sometimes it's desirable to use a custom string in error messages to provide " +"more user-friendly output. In these cases, :meth:`!register` can be used to " +"register custom actions or types with a parser and allow you to reference " +"the type by their registered name instead of their callable name." +msgstr "" +"Às vezes, é desejável usar uma string personalizada em mensagens de erro " +"para fornecer uma saída mais amigável ao usuário. Nesses casos, :meth:`!" +"register` pode ser usado para registrar ações ou tipos personalizados com um " +"analisador sintático e permitir que você faça referência ao tipo pelo nome " +"registrado em vez do nome do chamável." + +#: ../../library/argparse.rst:2130 +msgid "" +"The :meth:`!register` method accepts three arguments - a *registry_name*, " +"specifying the internal registry where the object will be stored (e.g., " +"``action``, ``type``), *value*, which is the key under which the object will " +"be registered, and object, the callable to be registered." +msgstr "" +"O método :meth:`!register` aceita três argumentos - um *registry_name*, " +"especificando o registro interno onde o objeto será armazenado (por exemplo, " +"``action``, ``type``), *value*, que é a chave sob a qual o objeto será " +"registrado, e object, o chamável a ser registrado." + +#: ../../library/argparse.rst:2135 +msgid "" +"The following example shows how to register a custom type with a parser::" +msgstr "" +"O exemplo a seguir mostra como registrar um tipo personalizado com um " +"analisador:" + +#: ../../library/argparse.rst:2137 +msgid "" +">>> import argparse\n" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.register('type', 'hexadecimal integer', lambda s: int(s, 16))\n" +">>> parser.add_argument('--foo', type='hexadecimal integer')\n" +"_StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, " +"default=None, type='hexadecimal integer', choices=None, required=False, " +"help=None, metavar=None, deprecated=False)\n" +">>> parser.parse_args(['--foo', '0xFA'])\n" +"Namespace(foo=250)\n" +">>> parser.parse_args(['--foo', '1.2'])\n" +"usage: PROG [-h] [--foo FOO]\n" +"PROG: error: argument --foo: invalid 'hexadecimal integer' value: '1.2'" +msgstr "" +">>> import argparse\n" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.register('type', 'hexadecimal integer', lambda s: int(s, 16))\n" +">>> parser.add_argument('--foo', type='hexadecimal integer')\n" +"_StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, " +"default=None, type='hexadecimal integer', choices=None, required=False, " +"help=None, metavar=None, deprecated=False)\n" +">>> parser.parse_args(['--foo', '0xFA'])\n" +"Namespace(foo=250)\n" +">>> parser.parse_args(['--foo', '1.2'])\n" +"usage: PROG [-h] [--foo FOO]\n" +"PROG: error: argument --foo: invalid 'hexadecimal integer' value: '1.2'" + +#: ../../library/argparse.rst:2149 msgid "Exceptions" msgstr "Exceções" -#: ../../library/argparse.rst:2349 +#: ../../library/argparse.rst:2153 msgid "An error from creating or using an argument (optional or positional)." -msgstr "" +msgstr "Um erro ao criar ou usar um argumento (opcional ou posicional)." -#: ../../library/argparse.rst:2351 +#: ../../library/argparse.rst:2155 msgid "" "The string value of this exception is the message, augmented with " "information about the argument that caused it." msgstr "" +"O valor da string dessa exceção é a mensagem, complementada com informações " +"sobre o argumento que a causou." -#: ../../library/argparse.rst:2356 +#: ../../library/argparse.rst:2160 msgid "" "Raised when something goes wrong converting a command line string to a type." msgstr "" +"Levantada quando algo dá errado ao converter uma string de linha de comando " +"em um tipo." -#: ../../library/argparse.rst:982 +#: ../../library/argparse.rst:2164 +msgid "Guides and Tutorials" +msgstr "Guias e tutoriais" + +#: ../../library/argparse.rst:815 msgid "? (question mark)" msgstr "? (interrogação)" -#: ../../library/argparse.rst:982 ../../library/argparse.rst:1016 -#: ../../library/argparse.rst:1030 +#: ../../library/argparse.rst:815 ../../library/argparse.rst:849 +#: ../../library/argparse.rst:863 msgid "in argparse module" -msgstr "" +msgstr "no módulo argparse" -#: ../../library/argparse.rst:1016 +#: ../../library/argparse.rst:849 msgid "* (asterisk)" msgstr "* (asterisco)" -#: ../../library/argparse.rst:1030 +#: ../../library/argparse.rst:863 msgid "+ (plus)" msgstr "+ (mais)" diff --git a/library/array.po b/library/array.po index 445069b18..b1b9b8ca3 100644 --- a/library/array.po +++ b/library/array.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# (Douglas da Silva) , 2021 -# Misael borges , 2021 -# Juliana Karoline , 2021 -# Claudio Rogerio Carvalho Filho , 2024 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 00:54+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -206,7 +201,7 @@ msgstr "``'f'``" #: ../../library/array.rst:45 ../../library/array.rst:47 msgid "float" -msgstr "float" +msgstr "ponto flutuante" #: ../../library/array.rst:47 msgid "``'d'``" @@ -230,10 +225,13 @@ msgid "" "``Py_UNICODE``. This change doesn't affect its behavior because " "``Py_UNICODE`` is alias of :c:type:`wchar_t` since Python 3.3." msgstr "" +"``array('u')`` agora usa :c:type:`wchar_t` como tipo C no lugar do " +"descontinuado ``Py_UNICODE``. Essa mudança não afeta o comportamento pois " +"``Py_UNICODE`` é um apelido para :c:type:`wchar_t` desde Python 3.3." #: ../../library/array.rst:60 msgid "Please migrate to ``'w'`` typecode." -msgstr "" +msgstr "Por favor, migre para o código de tipo ``'w'``." #: ../../library/array.rst:64 msgid "" @@ -241,10 +239,13 @@ msgid "" "architecture (strictly speaking, by the C implementation). The actual size " "can be accessed through the :attr:`array.itemsize` attribute." msgstr "" +"A representação dos valores é definida pela arquitetura da máquina, mais " +"especificamente da implementação do C. O tamanho real pode ser acessado pelo " +"atributo :attr:`array.itemsize`." #: ../../library/array.rst:68 msgid "The module defines the following item:" -msgstr "" +msgstr "O módulo define o seguinte item:" #: ../../library/array.rst:73 msgid "A string with all available type codes." @@ -261,6 +262,10 @@ msgid "" "`bytearray` object, a Unicode string, or iterable over elements of the " "appropriate type." msgstr "" +"Um novo vetor cujos itens são restritos por *typecode* e inicializados a " +"partir do valor opcional *initializer*, que deve ser um objeto :class:" +"`bytes` ou :class:`bytearray`, uma string Unicode ou iterável sobre " +"elementos do tipo apropriado." #: ../../library/array.rst:86 msgid "" @@ -270,6 +275,11 @@ msgid "" "otherwise, the initializer's iterator is passed to the :meth:`extend` method " "to add initial items to the array." msgstr "" +"Se for fornecido um objeto :class:`bytes` ou :class:`bytearray`, o " +"inicializador é passado para o método :meth:`frombytes` do novo vetor; se " +"for fornecida uma string Unicode, o inicializador é passado para o método :" +"meth:`fromunicode`; caso contrário, o iterador do inicializador é passado " +"para o método :meth:`extend` para adicionar itens iniciais ao vetor." #: ../../library/array.rst:93 msgid "" @@ -280,12 +290,12 @@ msgid "" "interface, and may be used wherever :term:`bytes-like objects ` are supported." msgstr "" -"Objetos array tem suporte para as operações de sequência comuns: indexação, " -"fatiamento, concatenação, e multiplicação. Quando usando a atribuição de " -"fatias, o valor associado deve ser um objeto array com o mesmo código de " -"tipo; caso contrário, :exc:`TypeError` é levantada. Objetos array também " +"Objetos vetor tem suporte para as operações de sequência comuns: indexação, " +"fatiamento, concatenação e multiplicação. Quando usando a atribuição de " +"fatias, o valor associado deve ser um objeto vetor com o mesmo código de " +"tipo; caso contrário, :exc:`TypeError` é levantada. Objetos vetor também " "implementam a interface buffer, e também podem ser usados em qualquer lugar " -"onde :term:`objetos byte ou similar ` é permitido." +"onde :term:`objetos bytes ou similar ` é permitido." #: ../../library/array.rst:99 msgid "" @@ -297,7 +307,7 @@ msgstr "" #: ../../library/array.rst:104 msgid "The typecode character used to create the array." -msgstr "O caractere typecode usado para criar o vetor." +msgstr "O caractere de código de tipo usado para criar o vetor." #: ../../library/array.rst:109 msgid "The length in bytes of one array item in the internal representation." @@ -318,6 +328,14 @@ msgid "" "as long as the array exists and no length-changing operations are applied to " "it." msgstr "" +"Retorna uma tupla ``(address, length)`` com o endereço corrente da memória e " +"o tamanho em elementos do buffer usado para armazenar conteúdos do vetor. O " +"tamanho do buffer da memória em bytes pode ser computado como ``array." +"buffer_info()[1] * array.itemsize``. Isso é ocasionalmente útil quando se " +"está trabalhando com interfaces I/O de baixo nível (inerentemente inseguras) " +"que precisam de endereços de memória, como algumas operações :c:func:`!" +"ioctl`. Os números retornados são válidos enquanto o vetor existir e nenhuma " +"operação de alteração de tamanho for aplicada a ele." #: ../../library/array.rst:129 msgid "" @@ -342,7 +360,7 @@ msgid "" msgstr "" "\"Byteswap\" todos os itens do vetor. Isso é somente suportado para valores " "de 1, 2, 4 ou 8 bytes de tamanho; para outros tipos de valores é levantada :" -"exc:`RuntimeError` . Isso é útil quando estamos lendo dados de um arquivo " +"exc:`RuntimeError`. Isso é útil quando estamos lendo dados de um arquivo " "para serem escritos em um arquivo de outra máquina de ordem de bytes " "diferente." @@ -368,10 +386,14 @@ msgid "" "as an array of machine values (as if it had been read from a file using the :" "meth:`fromfile` method)." msgstr "" +"Adiciona itens do :term:`objeto bytes ou similar`, interpretando seu " +"conteúdo como um vetor (como se tivesse sido lido de um arquivo usando o " +"método :meth:`fromfile`)." #: ../../library/array.rst:163 msgid ":meth:`!fromstring` is renamed to :meth:`frombytes` for clarity." msgstr "" +":meth:`!fromstring` foi renomeado para :meth:`frombytes` para maior clareza." #: ../../library/array.rst:169 msgid "" @@ -400,6 +422,10 @@ msgid "" "Use ``array.frombytes(unicodestring.encode(enc))`` to append Unicode data to " "an array of some other type." msgstr "" +"Estende este vetor com dados da string Unicode fornecida. O vetor deve ter o " +"código de tipo ``'u'`` ou ``'w'``; caso contrário, uma :exc:`ValueError` é " +"levantada. Use ``array.frombytes(unicodestring.encode(enc))`` para anexar " +"dados Unicode a um vetor de algum outro tipo." #: ../../library/array.rst:191 msgid "" @@ -408,17 +434,21 @@ msgid "" "specified to search for *x* within a subsection of the array. Raise :exc:" "`ValueError` if *x* is not found." msgstr "" +"Retorna o menor *i* tal que *i* seja o índice da primeira ocorrência de *x* " +"no vetor. Os argumentos opcionais *start* e *stop* podem ser especificados " +"para procurar por *x* dentro de uma subseção do vetor. Levanta :exc:" +"`ValueError` se *x* não for encontrado." #: ../../library/array.rst:196 msgid "Added optional *start* and *stop* parameters." -msgstr "" +msgstr "Adicionados os parâmetros opcionais *start e *stop*." #: ../../library/array.rst:202 msgid "" "Insert a new item with value *x* in the array before position *i*. Negative " "values are treated as being relative to the end of the array." msgstr "" -"Insere um novo item com o *x* no vetor antes da posição *i*. Valores " +"Insere um novo item com o valor *x* no vetor antes da posição *i*. Valores " "negativos são tratados como sendo em relação ao fim do vetor." #: ../../library/array.rst:208 @@ -428,7 +458,8 @@ msgid "" "removed and returned." msgstr "" "Remove o item com o índice *i* do vetor e retorna este item. O valor padrão " -"do argumento é ``-1``, assim por padrão o último item é removido e retornado." +"do argumento opcional é ``-1``, assim por padrão o último item é removido e " +"retornado." #: ../../library/array.rst:215 msgid "Remove the first occurrence of *x* from the array." @@ -436,7 +467,7 @@ msgstr "Remove a primeira ocorrência de *x* do vetor." #: ../../library/array.rst:220 msgid "Remove all elements from the array." -msgstr "" +msgstr "Remove todos os elementos do vetor." #: ../../library/array.rst:227 msgid "Reverse the order of the items in the array." @@ -454,7 +485,7 @@ msgstr "" #: ../../library/array.rst:236 msgid ":meth:`!tostring` is renamed to :meth:`tobytes` for clarity." -msgstr "" +msgstr ":meth:`!tostring` foi nomeado para :meth:`tobytes` para maior clareza." #: ../../library/array.rst:242 msgid "Write all items (as machine values) to the :term:`file object` *f*." @@ -472,6 +503,10 @@ msgid "" "or ``'w'``; otherwise a :exc:`ValueError` is raised. Use ``array.tobytes()." "decode(enc)`` to obtain a Unicode string from an array of some other type." msgstr "" +"Devolve os itens do vetor como uma string Unicode. O vetor deve ser do tipo " +"``'u'`` ou ``'w'``; caso contrário :exc:`ValueError` é levantada. Use " +"``array.tobytes().decode(enc)`` para obter uma string Unicode de um vetor de " +"outros tipos." #: ../../library/array.rst:257 msgid "" @@ -486,6 +521,18 @@ msgid "" "Examples::" msgstr "" +#: ../../library/array.rst:269 +msgid "" +"array('l')\n" +"array('w', 'hello \\u2641')\n" +"array('l', [1, 2, 3, 4, 5])\n" +"array('d', [1.0, 2.0, 3.14, -inf, nan])" +msgstr "" +"array('l')\n" +"array('w', 'hello \\u2641')\n" +"array('l', [1, 2, 3, 4, 5])\n" +"array('d', [1.0, 2.0, 3.14, -inf, nan])" + #: ../../library/array.rst:277 msgid "Module :mod:`struct`" msgstr "Módulo :mod:`struct`" @@ -496,11 +543,11 @@ msgstr "Empacotamento e desempacotamento de dados binários heterogêneos." #: ../../library/array.rst:280 msgid "`NumPy `_" -msgstr "" +msgstr "`NumPy `_" #: ../../library/array.rst:281 msgid "The NumPy package defines another array type." -msgstr "" +msgstr "O pacote NumPy define outro tipo de vetor." #: ../../library/array.rst:7 msgid "arrays" diff --git a/library/ast.po b/library/ast.po index 803f84283..71966f049 100644 --- a/library/ast.po +++ b/library/ast.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Adorilson Bezerra , 2023 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 00:54+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-02 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -72,6 +67,352 @@ msgstr "Gramática Abstrata" msgid "The abstract grammar is currently defined as follows:" msgstr "A gramática abstrata está atualmente definida da seguinte forma:" +#: ../../library/ast.rst:37 +msgid "" +"-- ASDL's 4 builtin types are:\n" +"-- identifier, int, string, constant\n" +"\n" +"module Python\n" +"{\n" +" mod = Module(stmt* body, type_ignore* type_ignores)\n" +" | Interactive(stmt* body)\n" +" | Expression(expr body)\n" +" | FunctionType(expr* argtypes, expr returns)\n" +"\n" +" stmt = FunctionDef(identifier name, arguments args,\n" +" stmt* body, expr* decorator_list, expr? returns,\n" +" string? type_comment, type_param* type_params)\n" +" | AsyncFunctionDef(identifier name, arguments args,\n" +" stmt* body, expr* decorator_list, expr? " +"returns,\n" +" string? type_comment, type_param* type_params)\n" +"\n" +" | ClassDef(identifier name,\n" +" expr* bases,\n" +" keyword* keywords,\n" +" stmt* body,\n" +" expr* decorator_list,\n" +" type_param* type_params)\n" +" | Return(expr? value)\n" +"\n" +" | Delete(expr* targets)\n" +" | Assign(expr* targets, expr value, string? type_comment)\n" +" | TypeAlias(expr name, type_param* type_params, expr value)\n" +" | AugAssign(expr target, operator op, expr value)\n" +" -- 'simple' indicates that we annotate simple name without parens\n" +" | AnnAssign(expr target, expr annotation, expr? value, int " +"simple)\n" +"\n" +" -- use 'orelse' because else is a keyword in target languages\n" +" | For(expr target, expr iter, stmt* body, stmt* orelse, string? " +"type_comment)\n" +" | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, " +"string? type_comment)\n" +" | While(expr test, stmt* body, stmt* orelse)\n" +" | If(expr test, stmt* body, stmt* orelse)\n" +" | With(withitem* items, stmt* body, string? type_comment)\n" +" | AsyncWith(withitem* items, stmt* body, string? type_comment)\n" +"\n" +" | Match(expr subject, match_case* cases)\n" +"\n" +" | Raise(expr? exc, expr? cause)\n" +" | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* " +"finalbody)\n" +" | TryStar(stmt* body, excepthandler* handlers, stmt* orelse, stmt* " +"finalbody)\n" +" | Assert(expr test, expr? msg)\n" +"\n" +" | Import(alias* names)\n" +" | ImportFrom(identifier? module, alias* names, int? level)\n" +"\n" +" | Global(identifier* names)\n" +" | Nonlocal(identifier* names)\n" +" | Expr(expr value)\n" +" | Pass | Break | Continue\n" +"\n" +" -- col_offset is the byte offset in the utf8 string the parser " +"uses\n" +" attributes (int lineno, int col_offset, int? end_lineno, int? " +"end_col_offset)\n" +"\n" +" -- BoolOp() can use left & right?\n" +" expr = BoolOp(boolop op, expr* values)\n" +" | NamedExpr(expr target, expr value)\n" +" | BinOp(expr left, operator op, expr right)\n" +" | UnaryOp(unaryop op, expr operand)\n" +" | Lambda(arguments args, expr body)\n" +" | IfExp(expr test, expr body, expr orelse)\n" +" | Dict(expr* keys, expr* values)\n" +" | Set(expr* elts)\n" +" | ListComp(expr elt, comprehension* generators)\n" +" | SetComp(expr elt, comprehension* generators)\n" +" | DictComp(expr key, expr value, comprehension* generators)\n" +" | GeneratorExp(expr elt, comprehension* generators)\n" +" -- the grammar constrains where yield expressions can occur\n" +" | Await(expr value)\n" +" | Yield(expr? value)\n" +" | YieldFrom(expr value)\n" +" -- need sequences for compare to distinguish between\n" +" -- x < 4 < 3 and (x < 4) < 3\n" +" | Compare(expr left, cmpop* ops, expr* comparators)\n" +" | Call(expr func, expr* args, keyword* keywords)\n" +" | FormattedValue(expr value, int conversion, expr? format_spec)\n" +" | JoinedStr(expr* values)\n" +" | Constant(constant value, string? kind)\n" +"\n" +" -- the following expression can appear in assignment context\n" +" | Attribute(expr value, identifier attr, expr_context ctx)\n" +" | Subscript(expr value, expr slice, expr_context ctx)\n" +" | Starred(expr value, expr_context ctx)\n" +" | Name(identifier id, expr_context ctx)\n" +" | List(expr* elts, expr_context ctx)\n" +" | Tuple(expr* elts, expr_context ctx)\n" +"\n" +" -- can appear only in Subscript\n" +" | Slice(expr? lower, expr? upper, expr? step)\n" +"\n" +" -- col_offset is the byte offset in the utf8 string the parser " +"uses\n" +" attributes (int lineno, int col_offset, int? end_lineno, int? " +"end_col_offset)\n" +"\n" +" expr_context = Load | Store | Del\n" +"\n" +" boolop = And | Or\n" +"\n" +" operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift\n" +" | RShift | BitOr | BitXor | BitAnd | FloorDiv\n" +"\n" +" unaryop = Invert | Not | UAdd | USub\n" +"\n" +" cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn\n" +"\n" +" comprehension = (expr target, expr iter, expr* ifs, int is_async)\n" +"\n" +" excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)\n" +" attributes (int lineno, int col_offset, int? end_lineno, " +"int? end_col_offset)\n" +"\n" +" arguments = (arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs,\n" +" expr* kw_defaults, arg? kwarg, expr* defaults)\n" +"\n" +" arg = (identifier arg, expr? annotation, string? type_comment)\n" +" attributes (int lineno, int col_offset, int? end_lineno, int? " +"end_col_offset)\n" +"\n" +" -- keyword arguments supplied to call (NULL identifier for **kwargs)\n" +" keyword = (identifier? arg, expr value)\n" +" attributes (int lineno, int col_offset, int? end_lineno, int? " +"end_col_offset)\n" +"\n" +" -- import name with optional 'as' alias.\n" +" alias = (identifier name, identifier? asname)\n" +" attributes (int lineno, int col_offset, int? end_lineno, int? " +"end_col_offset)\n" +"\n" +" withitem = (expr context_expr, expr? optional_vars)\n" +"\n" +" match_case = (pattern pattern, expr? guard, stmt* body)\n" +"\n" +" pattern = MatchValue(expr value)\n" +" | MatchSingleton(constant value)\n" +" | MatchSequence(pattern* patterns)\n" +" | MatchMapping(expr* keys, pattern* patterns, identifier? rest)\n" +" | MatchClass(expr cls, pattern* patterns, identifier* kwd_attrs, " +"pattern* kwd_patterns)\n" +"\n" +" | MatchStar(identifier? name)\n" +" -- The optional \"rest\" MatchMapping parameter handles " +"capturing extra mapping keys\n" +"\n" +" | MatchAs(pattern? pattern, identifier? name)\n" +" | MatchOr(pattern* patterns)\n" +"\n" +" attributes (int lineno, int col_offset, int end_lineno, int " +"end_col_offset)\n" +"\n" +" type_ignore = TypeIgnore(int lineno, string tag)\n" +"\n" +" type_param = TypeVar(identifier name, expr? bound, expr? default_value)\n" +" | ParamSpec(identifier name, expr? default_value)\n" +" | TypeVarTuple(identifier name, expr? default_value)\n" +" attributes (int lineno, int col_offset, int end_lineno, int " +"end_col_offset)\n" +"}\n" +msgstr "" +"-- 4 tipos embutidos da ASDL são:\n" +"-- identifier, int, string, constant\n" +"\n" +"module Python\n" +"{\n" +" mod = Module(stmt* body, type_ignore* type_ignores)\n" +" | Interactive(stmt* body)\n" +" | Expression(expr body)\n" +" | FunctionType(expr* argtypes, expr returns)\n" +"\n" +" stmt = FunctionDef(identifier name, arguments args,\n" +" stmt* body, expr* decorator_list, expr? returns,\n" +" string? type_comment, type_param* type_params)\n" +" | AsyncFunctionDef(identifier name, arguments args,\n" +" stmt* body, expr* decorator_list, expr? " +"returns,\n" +" string? type_comment, type_param* type_params)\n" +"\n" +" | ClassDef(identifier name,\n" +" expr* bases,\n" +" keyword* keywords,\n" +" stmt* body,\n" +" expr* decorator_list,\n" +" type_param* type_params)\n" +" | Return(expr? value)\n" +"\n" +" | Delete(expr* targets)\n" +" | Assign(expr* targets, expr value, string? type_comment)\n" +" | TypeAlias(expr name, type_param* type_params, expr value)\n" +" | AugAssign(expr target, operator op, expr value)\n" +" -- 'simple' indica que anotamos nome simples sem parênteses\n" +" | AnnAssign(expr target, expr annotation, expr? value, int " +"simple)\n" +"\n" +" -- usa 'orelse' porque else é uma palavra reservada em idiomas " +"alvos\n" +" | For(expr target, expr iter, stmt* body, stmt* orelse, string? " +"type_comment)\n" +" | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, " +"string? type_comment)\n" +" | While(expr test, stmt* body, stmt* orelse)\n" +" | If(expr test, stmt* body, stmt* orelse)\n" +" | With(withitem* items, stmt* body, string? type_comment)\n" +" | AsyncWith(withitem* items, stmt* body, string? type_comment)\n" +"\n" +" | Match(expr subject, match_case* cases)\n" +"\n" +" | Raise(expr? exc, expr? cause)\n" +" | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* " +"finalbody)\n" +" | TryStar(stmt* body, excepthandler* handlers, stmt* orelse, stmt* " +"finalbody)\n" +" | Assert(expr test, expr? msg)\n" +"\n" +" | Import(alias* names)\n" +" | ImportFrom(identifier? module, alias* names, int? level)\n" +"\n" +" | Global(identifier* names)\n" +" | Nonlocal(identifier* names)\n" +" | Expr(expr value)\n" +" | Pass | Break | Continue\n" +"\n" +" -- col_offset é o deslocamente do bytes na string utf8 que o " +"analisador sintático usa\n" +" attributes (int lineno, int col_offset, int? end_lineno, int? " +"end_col_offset)\n" +"\n" +" -- BoolOp() pode usar esquerda e direita?\n" +" expr = BoolOp(boolop op, expr* values)\n" +" | NamedExpr(expr target, expr value)\n" +" | BinOp(expr left, operator op, expr right)\n" +" | UnaryOp(unaryop op, expr operand)\n" +" | Lambda(arguments args, expr body)\n" +" | IfExp(expr test, expr body, expr orelse)\n" +" | Dict(expr* keys, expr* values)\n" +" | Set(expr* elts)\n" +" | ListComp(expr elt, comprehension* generators)\n" +" | SetComp(expr elt, comprehension* generators)\n" +" | DictComp(expr key, expr value, comprehension* generators)\n" +" | GeneratorExp(expr elt, comprehension* generators)\n" +" -- as restrições gramaticais onde yield expressions pode ocorrer\n" +" | Await(expr value)\n" +" | Yield(expr? value)\n" +" | YieldFrom(expr value)\n" +" -- precisa de sequências para comparar para distringuir entre\n" +" -- x < 4 < 3 and (x < 4) < 3\n" +" | Compare(expr left, cmpop* ops, expr* comparators)\n" +" | Call(expr func, expr* args, keyword* keywords)\n" +" | FormattedValue(expr value, int conversion, expr? format_spec)\n" +" | JoinedStr(expr* values)\n" +" | Constant(constant value, string? kind)\n" +"\n" +" -- a expressão a seguir pode aparecer no contexto da atribuição\n" +" | Attribute(expr value, identifier attr, expr_context ctx)\n" +" | Subscript(expr value, expr slice, expr_context ctx)\n" +" | Starred(expr value, expr_context ctx)\n" +" | Name(identifier id, expr_context ctx)\n" +" | List(expr* elts, expr_context ctx)\n" +" | Tuple(expr* elts, expr_context ctx)\n" +"\n" +" -- pode aparecer apenas em subscrição\n" +" | Slice(expr? lower, expr? upper, expr? step)\n" +"\n" +" -- col_offset é o deslocamente do bytes na string utf8 que o " +"analisador sintático usa\n" +" attributes (int lineno, int col_offset, int? end_lineno, int? " +"end_col_offset)\n" +"\n" +" expr_context = Load | Store | Del\n" +"\n" +" boolop = And | Or\n" +"\n" +" operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift\n" +" | RShift | BitOr | BitXor | BitAnd | FloorDiv\n" +"\n" +" unaryop = Invert | Not | UAdd | USub\n" +"\n" +" cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn\n" +"\n" +" comprehension = (expr target, expr iter, expr* ifs, int is_async)\n" +"\n" +" excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)\n" +" attributes (int lineno, int col_offset, int? end_lineno, " +"int? end_col_offset)\n" +"\n" +" arguments = (arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs,\n" +" expr* kw_defaults, arg? kwarg, expr* defaults)\n" +"\n" +" arg = (identifier arg, expr? annotation, string? type_comment)\n" +" attributes (int lineno, int col_offset, int? end_lineno, int? " +"end_col_offset)\n" +"\n" +" -- argumentos nomeados fornecidos à chamada (identificador NULL para " +"**kwargs)\n" +" keyword = (identifier? arg, expr value)\n" +" attributes (int lineno, int col_offset, int? end_lineno, int? " +"end_col_offset)\n" +"\n" +" -- nomes de importação com o apelido opcional 'as'.\n" +" alias = (identifier name, identifier? asname)\n" +" attributes (int lineno, int col_offset, int? end_lineno, int? " +"end_col_offset)\n" +"\n" +" withitem = (expr context_expr, expr? optional_vars)\n" +"\n" +" match_case = (pattern pattern, expr? guard, stmt* body)\n" +"\n" +" pattern = MatchValue(expr value)\n" +" | MatchSingleton(constant value)\n" +" | MatchSequence(pattern* patterns)\n" +" | MatchMapping(expr* keys, pattern* patterns, identifier? rest)\n" +" | MatchClass(expr cls, pattern* patterns, identifier* kwd_attrs, " +"pattern* kwd_patterns)\n" +"\n" +" | MatchStar(identifier? name)\n" +" -- O parâmetro opcional de MatchMapping \"rest\" lida com a " +"captura de chaves extras de mapeamento\n" +"\n" +" | MatchAs(pattern? pattern, identifier? name)\n" +" | MatchOr(pattern* patterns)\n" +"\n" +" attributes (int lineno, int col_offset, int end_lineno, int " +"end_col_offset)\n" +"\n" +" type_ignore = TypeIgnore(int lineno, string tag)\n" +"\n" +" type_param = TypeVar(identifier name, expr? bound, expr? default_value)\n" +" | ParamSpec(identifier name, expr? default_value)\n" +" | TypeVarTuple(identifier name, expr? default_value)\n" +" attributes (int lineno, int col_offset, int end_lineno, int " +"end_col_offset)\n" +"}\n" + #: ../../library/ast.rst:42 msgid "Node classes" msgstr "Classes de nós" @@ -148,6 +489,16 @@ msgstr "" "mapeia nomes de campos (como também listado em :attr:`_fields`) para seus " "tipos." +#: ../../library/ast.rst:82 +msgid "" +">>> ast.TypeVar._field_types\n" +"{'name': , 'bound': ast.expr | None, 'default_value': ast.expr " +"| None}" +msgstr "" +">>> ast.TypeVar._field_types\n" +"{'name': , 'bound': ast.expr | None, 'default_value': ast.expr " +"| None}" + #: ../../library/ast.rst:94 msgid "" "Instances of :class:`ast.expr` and :class:`ast.stmt` subclasses have :attr:" @@ -211,6 +562,14 @@ msgstr "" "Por exemplo, para criar e popular um nó :class:`ast.UnaryOp`, você poderia " "usar ::" +#: ../../library/ast.rst:118 +msgid "" +"node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),\n" +" lineno=0, col_offset=0)" +msgstr "" +"node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),\n" +" lineno=0, col_offset=0)" + #: ../../library/ast.rst:121 msgid "" "If a field that is optional in the grammar is omitted from the constructor, " @@ -299,17 +658,35 @@ msgstr "" "gerado por :func:`ast.parse` com *mode* no padrão ``\"exec\"``." #: ../../library/ast.rst:176 -msgid "*body* is a :class:`list` of the module's :ref:`ast-statements`." -msgstr "*body* é uma :class:`list` das :ref:`ast-statements` do módulo." +msgid "``body`` is a :class:`list` of the module's :ref:`ast-statements`." +msgstr "``body`` é uma :class:`list` das :ref:`ast-statements` do módulo." #: ../../library/ast.rst:178 msgid "" -"*type_ignores* is a :class:`list` of the module's type ignore comments; see :" -"func:`ast.parse` for more details." +"``type_ignores`` is a :class:`list` of the module's type ignore comments; " +"see :func:`ast.parse` for more details." msgstr "" -"*type_ignores* é uma :class:`list` dos comentários de ignorar tipo do " +"``type_ignores`` é uma :class:`list` dos comentários de ignorar tipo do " "módulo; veja :func:`ast.parse` para mais detalhes." +#: ../../library/ast.rst:181 +msgid "" +">>> print(ast.dump(ast.parse('x = 1'), indent=4))\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Name(id='x', ctx=Store())],\n" +" value=Constant(value=1))])" +msgstr "" +">>> print(ast.dump(ast.parse('x = 1'), indent=4))\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Name(id='x', ctx=Store())],\n" +" value=Constant(value=1))])" + #: ../../library/ast.rst:194 msgid "" "A single Python :ref:`expression input `. Node type " @@ -320,10 +697,20 @@ msgstr "" #: ../../library/ast.rst:197 msgid "" -"*body* is a single node, one of the :ref:`expression types `." msgstr "" -"*body* é um nó único, um dos :ref:`tipos de expressão `." +"``body`` é um nó único, um dos :ref:`tipos de expressão `." + +#: ../../library/ast.rst:200 ../../library/ast.rst:270 +msgid "" +">>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Constant(value=123))" +msgstr "" +">>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Constant(value=123))" #: ../../library/ast.rst:209 msgid "" @@ -335,9 +722,35 @@ msgstr "" "``\"single\"``." #: ../../library/ast.rst:212 -msgid "*body* is a :class:`list` of :ref:`statement nodes `." -msgstr "" -"*body* é uma :class:`list` de :ref:`nós de instrução `." +msgid "``body`` is a :class:`list` of :ref:`statement nodes `." +msgstr "" +"``body`` é uma :class:`list` de :ref:`nós de instrução `." + +#: ../../library/ast.rst:214 +msgid "" +">>> print(ast.dump(ast.parse('x = 1; y = 2', mode='single'), indent=4))\n" +"Interactive(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Name(id='x', ctx=Store())],\n" +" value=Constant(value=1)),\n" +" Assign(\n" +" targets=[\n" +" Name(id='y', ctx=Store())],\n" +" value=Constant(value=2))])" +msgstr "" +">>> print(ast.dump(ast.parse('x = 1; y = 2', mode='single'), indent=4))\n" +"Interactive(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Name(id='x', ctx=Store())],\n" +" value=Constant(value=1)),\n" +" Assign(\n" +" targets=[\n" +" Name(id='y', ctx=Store())],\n" +" value=Constant(value=2))])" #: ../../library/ast.rst:231 msgid "" @@ -354,15 +767,50 @@ msgstr "" msgid "Such type comments would look like this::" msgstr "Esses comentários de tipo ficariam assim::" +#: ../../library/ast.rst:237 +msgid "" +"def sum_two_number(a, b):\n" +" # type: (int, int) -> int\n" +" return a + b" +msgstr "" +"def sum_two_number(a, b):\n" +" # tipo: (int, int) -> int\n" +" return a + b" + #: ../../library/ast.rst:241 msgid "" -"*argtypes* is a :class:`list` of :ref:`expression nodes `." +"``argtypes`` is a :class:`list` of :ref:`expression nodes `." msgstr "" -"*argtypes* é uma :class:`list` de :ref:`nós de expressão `." +"``argtypes`` é uma :class:`list` de :ref:`nós de expressão `." #: ../../library/ast.rst:243 -msgid "*returns* is a single :ref:`expression node `." -msgstr "*returns* é um único :ref:`nó de expressão `." +msgid "``returns`` is a single :ref:`expression node `." +msgstr "``returns`` é um único :ref:`nó de expressão `." + +#: ../../library/ast.rst:245 +msgid "" +">>> print(ast.dump(ast.parse('(int, str) -> List[int]', mode='func_type'), " +"indent=4))\n" +"FunctionType(\n" +" argtypes=[\n" +" Name(id='int', ctx=Load()),\n" +" Name(id='str', ctx=Load())],\n" +" returns=Subscript(\n" +" value=Name(id='List', ctx=Load()),\n" +" slice=Name(id='int', ctx=Load()),\n" +" ctx=Load()))" +msgstr "" +">>> print(ast.dump(ast.parse('(int, str) -> List[int]', mode='func_type'), " +"indent=4))\n" +"FunctionType(\n" +" argtypes=[\n" +" Name(id='int', ctx=Load()),\n" +" Name(id='str', ctx=Load())],\n" +" returns=Subscript(\n" +" value=Name(id='List', ctx=Load()),\n" +" slice=Name(id='int', ctx=Load()),\n" +" ctx=Load()))" #: ../../library/ast.rst:261 msgid "Literals" @@ -437,6 +885,48 @@ msgstr "" "Uma f-string, compreendendo uma série de nós :class:`FormattedValue` e :" "class:`Constant`." +#: ../../library/ast.rst:302 +msgid "" +">>> print(ast.dump(ast.parse('f\"sin({a}) is {sin(a):.3}\"', mode='eval'), " +"indent=4))\n" +"Expression(\n" +" body=JoinedStr(\n" +" values=[\n" +" Constant(value='sin('),\n" +" FormattedValue(\n" +" value=Name(id='a', ctx=Load()),\n" +" conversion=-1),\n" +" Constant(value=') is '),\n" +" FormattedValue(\n" +" value=Call(\n" +" func=Name(id='sin', ctx=Load()),\n" +" args=[\n" +" Name(id='a', ctx=Load())]),\n" +" conversion=-1,\n" +" format_spec=JoinedStr(\n" +" values=[\n" +" Constant(value='.3')]))]))" +msgstr "" +">>> print(ast.dump(ast.parse('f\"sin({a}) is {sin(a):.3}\"', mode='eval'), " +"indent=4))\n" +"Expression(\n" +" body=JoinedStr(\n" +" values=[\n" +" Constant(value='sin('),\n" +" FormattedValue(\n" +" value=Name(id='a', ctx=Load()),\n" +" conversion=-1),\n" +" Constant(value=') is '),\n" +" FormattedValue(\n" +" value=Call(\n" +" func=Name(id='sin', ctx=Load()),\n" +" args=[\n" +" Name(id='a', ctx=Load())]),\n" +" conversion=-1,\n" +" format_spec=JoinedStr(\n" +" values=[\n" +" Constant(value='.3')]))]))" + #: ../../library/ast.rst:327 msgid "" "A list or tuple. ``elts`` holds a list of nodes representing the elements. " @@ -447,12 +937,66 @@ msgstr "" "elementos. ``ctx`` é :class:`Store` se o contêiner for um alvo de atribuição " "(ou seja, ``(x,y)=algumacoisa``), e :class:`Load` caso contrário." +#: ../../library/ast.rst:331 +msgid "" +">>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4))\n" +"Expression(\n" +" body=List(\n" +" elts=[\n" +" Constant(value=1),\n" +" Constant(value=2),\n" +" Constant(value=3)],\n" +" ctx=Load()))\n" +">>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Tuple(\n" +" elts=[\n" +" Constant(value=1),\n" +" Constant(value=2),\n" +" Constant(value=3)],\n" +" ctx=Load()))" +msgstr "" +">>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4))\n" +"Expression(\n" +" body=List(\n" +" elts=[\n" +" Constant(value=1),\n" +" Constant(value=2),\n" +" Constant(value=3)],\n" +" ctx=Load()))\n" +">>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Tuple(\n" +" elts=[\n" +" Constant(value=1),\n" +" Constant(value=2),\n" +" Constant(value=3)],\n" +" ctx=Load()))" + #: ../../library/ast.rst:353 msgid "A set. ``elts`` holds a list of nodes representing the set's elements." msgstr "" "Um conjunto. ``elts`` contém uma lista de nós que representam os elementos " "do conjunto." +#: ../../library/ast.rst:355 +msgid "" +">>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Set(\n" +" elts=[\n" +" Constant(value=1),\n" +" Constant(value=2),\n" +" Constant(value=3)]))" +msgstr "" +">>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Set(\n" +" elts=[\n" +" Constant(value=1),\n" +" Constant(value=2),\n" +" Constant(value=3)]))" + #: ../../library/ast.rst:368 msgid "" "A dictionary. ``keys`` and ``values`` hold lists of nodes representing the " @@ -473,6 +1017,28 @@ msgstr "" "ser expandida vai para a lista ``values``, com um ``None`` na posição " "correspondente em ``keys``." +#: ../../library/ast.rst:376 +msgid "" +">>> print(ast.dump(ast.parse('{\"a\":1, **d}', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Dict(\n" +" keys=[\n" +" Constant(value='a'),\n" +" None],\n" +" values=[\n" +" Constant(value=1),\n" +" Name(id='d', ctx=Load())]))" +msgstr "" +">>> print(ast.dump(ast.parse('{\"a\":1, **d}', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Dict(\n" +" keys=[\n" +" Constant(value='a'),\n" +" None],\n" +" values=[\n" +" Constant(value=1),\n" +" Name(id='d', ctx=Load())]))" + #: ../../library/ast.rst:390 msgid "Variables" msgstr "Variáveis" @@ -495,6 +1061,50 @@ msgstr "" "variável, para atribuir um novo valor a ela ou para excluí-la. As " "referências de variáveis recebem um contexto para distinguir esses casos." +#: ../../library/ast.rst:406 +msgid "" +">>> print(ast.dump(ast.parse('a'), indent=4))\n" +"Module(\n" +" body=[\n" +" Expr(\n" +" value=Name(id='a', ctx=Load()))])\n" +"\n" +">>> print(ast.dump(ast.parse('a = 1'), indent=4))\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Name(id='a', ctx=Store())],\n" +" value=Constant(value=1))])\n" +"\n" +">>> print(ast.dump(ast.parse('del a'), indent=4))\n" +"Module(\n" +" body=[\n" +" Delete(\n" +" targets=[\n" +" Name(id='a', ctx=Del())])])" +msgstr "" +">>> print(ast.dump(ast.parse('a'), indent=4))\n" +"Module(\n" +" body=[\n" +" Expr(\n" +" value=Name(id='a', ctx=Load()))])\n" +"\n" +">>> print(ast.dump(ast.parse('a = 1'), indent=4))\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Name(id='a', ctx=Store())],\n" +" value=Constant(value=1))])\n" +"\n" +">>> print(ast.dump(ast.parse('del a'), indent=4))\n" +"Module(\n" +" body=[\n" +" Delete(\n" +" targets=[\n" +" Name(id='a', ctx=Del())])])" + #: ../../library/ast.rst:432 msgid "" "A ``*var`` variable reference. ``value`` holds the variable, typically a :" @@ -505,6 +1115,36 @@ msgstr "" "normalmente um nó :class:`Name`. Este tipo deve ser usado ao construir um " "nó :class:`Call` com ``*args``." +#: ../../library/ast.rst:436 +msgid "" +">>> print(ast.dump(ast.parse('a, *b = it'), indent=4))\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Tuple(\n" +" elts=[\n" +" Name(id='a', ctx=Store()),\n" +" Starred(\n" +" value=Name(id='b', ctx=Store()),\n" +" ctx=Store())],\n" +" ctx=Store())],\n" +" value=Name(id='it', ctx=Load()))])" +msgstr "" +">>> print(ast.dump(ast.parse('a, *b = it'), indent=4))\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Tuple(\n" +" elts=[\n" +" Name(id='a', ctx=Store()),\n" +" Starred(\n" +" value=Name(id='b', ctx=Store()),\n" +" ctx=Store())],\n" +" ctx=Store())],\n" +" value=Name(id='it', ctx=Load()))])" + #: ../../library/ast.rst:456 msgid "Expressions" msgstr "Expressões" @@ -523,6 +1163,24 @@ msgstr "" "um nó :class:`Constant`, um :class:`Name`, um :class:`Lambda`, um :class:" "`Yield` ou :class:`YieldFrom`." +#: ../../library/ast.rst:465 +msgid "" +">>> print(ast.dump(ast.parse('-a'), indent=4))\n" +"Module(\n" +" body=[\n" +" Expr(\n" +" value=UnaryOp(\n" +" op=USub(),\n" +" operand=Name(id='a', ctx=Load())))])" +msgstr "" +">>> print(ast.dump(ast.parse('-a'), indent=4))\n" +"Module(\n" +" body=[\n" +" Expr(\n" +" value=UnaryOp(\n" +" op=USub(),\n" +" operand=Name(id='a', ctx=Load())))])" + #: ../../library/ast.rst:478 msgid "" "A unary operation. ``op`` is the operator, and ``operand`` any expression " @@ -539,6 +1197,20 @@ msgstr "" "Tokens de operador unário. :class:`Not` é a palavra reservada ``not``, :" "class:`Invert` é o operador ``~``." +#: ../../library/ast.rst:490 +msgid "" +">>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))\n" +"Expression(\n" +" body=UnaryOp(\n" +" op=Not(),\n" +" operand=Name(id='x', ctx=Load())))" +msgstr "" +">>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))\n" +"Expression(\n" +" body=UnaryOp(\n" +" op=Not(),\n" +" operand=Name(id='x', ctx=Load())))" + #: ../../library/ast.rst:501 msgid "" "A binary operation (like addition or division). ``op`` is the operator, and " @@ -547,6 +1219,22 @@ msgstr "" "Uma operação binária (como adição ou divisão). ``op`` é o operador, e " "``left`` e ``right`` são quaisquer nós de expressão." +#: ../../library/ast.rst:504 +msgid "" +">>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))\n" +"Expression(\n" +" body=BinOp(\n" +" left=Name(id='x', ctx=Load()),\n" +" op=Add(),\n" +" right=Name(id='y', ctx=Load())))" +msgstr "" +">>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))\n" +"Expression(\n" +" body=BinOp(\n" +" left=Name(id='x', ctx=Load()),\n" +" op=Add(),\n" +" right=Name(id='y', ctx=Load())))" + #: ../../library/ast.rst:528 msgid "Binary operator tokens." msgstr "Tokens de operador binário." @@ -566,6 +1254,24 @@ msgstr "" msgid "This doesn't include ``not``, which is a :class:`UnaryOp`." msgstr "Isso não inclui ``not``, que é um :class:`UnaryOp`." +#: ../../library/ast.rst:540 +msgid "" +">>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))\n" +"Expression(\n" +" body=BoolOp(\n" +" op=Or(),\n" +" values=[\n" +" Name(id='x', ctx=Load()),\n" +" Name(id='y', ctx=Load())]))" +msgstr "" +">>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))\n" +"Expression(\n" +" body=BoolOp(\n" +" op=Or(),\n" +" values=[\n" +" Name(id='x', ctx=Load()),\n" +" Name(id='y', ctx=Load())]))" + #: ../../library/ast.rst:554 msgid "Boolean operator tokens." msgstr "Tokens de operador booleano." @@ -580,6 +1286,30 @@ msgstr "" "comparação, ``ops`` a lista de operadores e ``comparators`` a lista de " "valores após o primeiro elemento na comparação." +#: ../../library/ast.rst:563 +msgid "" +">>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Compare(\n" +" left=Constant(value=1),\n" +" ops=[\n" +" LtE(),\n" +" Lt()],\n" +" comparators=[\n" +" Name(id='a', ctx=Load()),\n" +" Constant(value=10)]))" +msgstr "" +">>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Compare(\n" +" left=Constant(value=1),\n" +" ops=[\n" +" LtE(),\n" +" Lt()],\n" +" comparators=[\n" +" Name(id='a', ctx=Load()),\n" +" Constant(value=10)]))" + #: ../../library/ast.rst:588 msgid "Comparison operator tokens." msgstr "Tokens de operador de comparação." @@ -594,7 +1324,7 @@ msgstr "" #: ../../library/ast.rst:596 msgid "``args`` holds a list of the arguments passed by position." -msgstr "``args`` contém uma lista dos argumentos passados ​​por posição." +msgstr "``args`` contém uma lista dos argumentos passados por posição." #: ../../library/ast.rst:597 msgid "" @@ -612,6 +1342,42 @@ msgstr "" "Os argumentos ``args`` e ``keywords`` são opcionais e padrão para listas " "vazias." +#: ../../library/ast.rst:602 +msgid "" +">>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), " +"indent=4))\n" +"Expression(\n" +" body=Call(\n" +" func=Name(id='func', ctx=Load()),\n" +" args=[\n" +" Name(id='a', ctx=Load()),\n" +" Starred(\n" +" value=Name(id='d', ctx=Load()),\n" +" ctx=Load())],\n" +" keywords=[\n" +" keyword(\n" +" arg='b',\n" +" value=Name(id='c', ctx=Load())),\n" +" keyword(\n" +" value=Name(id='e', ctx=Load()))]))" +msgstr "" +">>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), " +"indent=4))\n" +"Expression(\n" +" body=Call(\n" +" func=Name(id='func', ctx=Load()),\n" +" args=[\n" +" Name(id='a', ctx=Load()),\n" +" Starred(\n" +" value=Name(id='d', ctx=Load()),\n" +" ctx=Load())],\n" +" keywords=[\n" +" keyword(\n" +" arg='b',\n" +" value=Name(id='c', ctx=Load())),\n" +" keyword(\n" +" value=Name(id='e', ctx=Load()))]))" + #: ../../library/ast.rst:623 msgid "" "A keyword argument to a function call or class definition. ``arg`` is a raw " @@ -629,6 +1395,22 @@ msgstr "" "Uma expressão como ``a if b else c``. Cada campo contém um único nó, " "portanto, no exemplo a seguir, todos os três são nós :class:`Name`." +#: ../../library/ast.rst:632 +msgid "" +">>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4))\n" +"Expression(\n" +" body=IfExp(\n" +" test=Name(id='b', ctx=Load()),\n" +" body=Name(id='a', ctx=Load()),\n" +" orelse=Name(id='c', ctx=Load())))" +msgstr "" +">>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4))\n" +"Expression(\n" +" body=IfExp(\n" +" test=Name(id='b', ctx=Load()),\n" +" body=Name(id='a', ctx=Load()),\n" +" orelse=Name(id='c', ctx=Load())))" + #: ../../library/ast.rst:644 msgid "" "Attribute access, e.g. ``d.keys``. ``value`` is a node, typically a :class:" @@ -641,6 +1423,22 @@ msgstr "" "nome do atributo, e ``ctx`` é :class:`Load`, :class:`Store` ou :class:`Del` " "de acordo com como o atributo é acionado sobre." +#: ../../library/ast.rst:649 +msgid "" +">>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Attribute(\n" +" value=Name(id='snake', ctx=Load()),\n" +" attr='colour',\n" +" ctx=Load()))" +msgstr "" +">>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Attribute(\n" +" value=Name(id='snake', ctx=Load()),\n" +" attr='colour',\n" +" ctx=Load()))" + #: ../../library/ast.rst:661 msgid "" "A named expression. This AST node is produced by the assignment expressions " @@ -653,6 +1451,20 @@ msgstr "" "contrário do nó :class:`Assign` no qual o primeiro argumento pode ser " "múltiplos nós, neste caso ambos ``target`` e ``value`` devem ser nós únicos." +#: ../../library/ast.rst:666 +msgid "" +">>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))\n" +"Expression(\n" +" body=NamedExpr(\n" +" target=Name(id='x', ctx=Store()),\n" +" value=Constant(value=4)))" +msgstr "" +">>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))\n" +"Expression(\n" +" body=NamedExpr(\n" +" target=Name(id='x', ctx=Store()),\n" +" value=Constant(value=4)))" + #: ../../library/ast.rst:677 msgid "Subscripting" msgstr "Subscrição" @@ -669,6 +1481,34 @@ msgstr "" "uma :class:`Tuple` e conter uma :class:`Slice`. ``ctx`` é :class:`Load`, :" "class:`Store` ou :class:`Del` de acordo com a ação realizada com o subscrito." +#: ../../library/ast.rst:687 +msgid "" +">>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Subscript(\n" +" value=Name(id='l', ctx=Load()),\n" +" slice=Tuple(\n" +" elts=[\n" +" Slice(\n" +" lower=Constant(value=1),\n" +" upper=Constant(value=2)),\n" +" Constant(value=3)],\n" +" ctx=Load()),\n" +" ctx=Load()))" +msgstr "" +">>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Subscript(\n" +" value=Name(id='l', ctx=Load()),\n" +" slice=Tuple(\n" +" elts=[\n" +" Slice(\n" +" lower=Constant(value=1),\n" +" upper=Constant(value=2)),\n" +" Constant(value=3)],\n" +" ctx=Load()),\n" +" ctx=Load()))" + #: ../../library/ast.rst:705 msgid "" "Regular slicing (on the form ``lower:upper`` or ``lower:upper:step``). Can " @@ -679,6 +1519,26 @@ msgstr "" "Pode ocorrer apenas dentro do campo *slice* de :class:`Subscript`, " "diretamente ou como um elemento de :class:`Tuple`." +#: ../../library/ast.rst:709 +msgid "" +">>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Subscript(\n" +" value=Name(id='l', ctx=Load()),\n" +" slice=Slice(\n" +" lower=Constant(value=1),\n" +" upper=Constant(value=2)),\n" +" ctx=Load()))" +msgstr "" +">>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Subscript(\n" +" value=Name(id='l', ctx=Load()),\n" +" slice=Slice(\n" +" lower=Constant(value=1),\n" +" upper=Constant(value=2)),\n" +" ctx=Load()))" + #: ../../library/ast.rst:722 msgid "Comprehensions" msgstr "Compreensões" @@ -697,6 +1557,90 @@ msgstr "" msgid "``generators`` is a list of :class:`comprehension` nodes." msgstr "``generators`` é uma lista de nós de :class:`comprehension`." +#: ../../library/ast.rst:735 +msgid "" +">>> print(ast.dump(\n" +"... ast.parse('[x for x in numbers]', mode='eval'),\n" +"... indent=4,\n" +"... ))\n" +"Expression(\n" +" body=ListComp(\n" +" elt=Name(id='x', ctx=Load()),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='x', ctx=Store()),\n" +" iter=Name(id='numbers', ctx=Load()),\n" +" is_async=0)]))\n" +">>> print(ast.dump(\n" +"... ast.parse('{x: x**2 for x in numbers}', mode='eval'),\n" +"... indent=4,\n" +"... ))\n" +"Expression(\n" +" body=DictComp(\n" +" key=Name(id='x', ctx=Load()),\n" +" value=BinOp(\n" +" left=Name(id='x', ctx=Load()),\n" +" op=Pow(),\n" +" right=Constant(value=2)),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='x', ctx=Store()),\n" +" iter=Name(id='numbers', ctx=Load()),\n" +" is_async=0)]))\n" +">>> print(ast.dump(\n" +"... ast.parse('{x for x in numbers}', mode='eval'),\n" +"... indent=4,\n" +"... ))\n" +"Expression(\n" +" body=SetComp(\n" +" elt=Name(id='x', ctx=Load()),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='x', ctx=Store()),\n" +" iter=Name(id='numbers', ctx=Load()),\n" +" is_async=0)]))" +msgstr "" +">>> print(ast.dump(\n" +"... ast.parse('[x for x in numbers]', mode='eval'),\n" +"... indent=4,\n" +"... ))\n" +"Expression(\n" +" body=ListComp(\n" +" elt=Name(id='x', ctx=Load()),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='x', ctx=Store()),\n" +" iter=Name(id='numbers', ctx=Load()),\n" +" is_async=0)]))\n" +">>> print(ast.dump(\n" +"... ast.parse('{x: x**2 for x in numbers}', mode='eval'),\n" +"... indent=4,\n" +"... ))\n" +"Expression(\n" +" body=DictComp(\n" +" key=Name(id='x', ctx=Load()),\n" +" value=BinOp(\n" +" left=Name(id='x', ctx=Load()),\n" +" op=Pow(),\n" +" right=Constant(value=2)),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='x', ctx=Store()),\n" +" iter=Name(id='numbers', ctx=Load()),\n" +" is_async=0)]))\n" +">>> print(ast.dump(\n" +"... ast.parse('{x for x in numbers}', mode='eval'),\n" +"... indent=4,\n" +"... ))\n" +"Expression(\n" +" body=SetComp(\n" +" elt=Name(id='x', ctx=Load()),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='x', ctx=Store()),\n" +" iter=Name(id='numbers', ctx=Load()),\n" +" is_async=0)]))" + #: ../../library/ast.rst:781 msgid "" "One ``for`` clause in a comprehension. ``target`` is the reference to use " @@ -717,6 +1661,124 @@ msgstr "" "``is_async`` indica que uma compreensão é assíncrona (usando um ``async " "for`` em vez de ``for``). O valor é um número inteiro (0 ou 1)." +#: ../../library/ast.rst:789 +msgid "" +">>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', " +"mode='eval'),\n" +"... indent=4)) # Multiple comprehensions in one.\n" +"Expression(\n" +" body=ListComp(\n" +" elt=Call(\n" +" func=Name(id='ord', ctx=Load()),\n" +" args=[\n" +" Name(id='c', ctx=Load())]),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='line', ctx=Store()),\n" +" iter=Name(id='file', ctx=Load()),\n" +" is_async=0),\n" +" comprehension(\n" +" target=Name(id='c', ctx=Store()),\n" +" iter=Name(id='line', ctx=Load()),\n" +" is_async=0)]))\n" +"\n" +">>> print(ast.dump(ast.parse('(n**2 for n in it if n>5 if n<10)', " +"mode='eval'),\n" +"... indent=4)) # generator comprehension\n" +"Expression(\n" +" body=GeneratorExp(\n" +" elt=BinOp(\n" +" left=Name(id='n', ctx=Load()),\n" +" op=Pow(),\n" +" right=Constant(value=2)),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='n', ctx=Store()),\n" +" iter=Name(id='it', ctx=Load()),\n" +" ifs=[\n" +" Compare(\n" +" left=Name(id='n', ctx=Load()),\n" +" ops=[\n" +" Gt()],\n" +" comparators=[\n" +" Constant(value=5)]),\n" +" Compare(\n" +" left=Name(id='n', ctx=Load()),\n" +" ops=[\n" +" Lt()],\n" +" comparators=[\n" +" Constant(value=10)])],\n" +" is_async=0)]))\n" +"\n" +">>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'),\n" +"... indent=4)) # Async comprehension\n" +"Expression(\n" +" body=ListComp(\n" +" elt=Name(id='i', ctx=Load()),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='i', ctx=Store()),\n" +" iter=Name(id='soc', ctx=Load()),\n" +" is_async=1)]))" +msgstr "" +">>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', " +"mode='eval'),\n" +"... indent=4)) # Várias compreensões em uma.\n" +"Expression(\n" +" body=ListComp(\n" +" elt=Call(\n" +" func=Name(id='ord', ctx=Load()),\n" +" args=[\n" +" Name(id='c', ctx=Load())]),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='line', ctx=Store()),\n" +" iter=Name(id='file', ctx=Load()),\n" +" is_async=0),\n" +" comprehension(\n" +" target=Name(id='c', ctx=Store()),\n" +" iter=Name(id='line', ctx=Load()),\n" +" is_async=0)]))\n" +"\n" +">>> print(ast.dump(ast.parse('(n**2 for n in it if n>5 if n<10)', " +"mode='eval'),\n" +"... indent=4)) # compreensão de gerador\n" +"Expression(\n" +" body=GeneratorExp(\n" +" elt=BinOp(\n" +" left=Name(id='n', ctx=Load()),\n" +" op=Pow(),\n" +" right=Constant(value=2)),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='n', ctx=Store()),\n" +" iter=Name(id='it', ctx=Load()),\n" +" ifs=[\n" +" Compare(\n" +" left=Name(id='n', ctx=Load()),\n" +" ops=[\n" +" Gt()],\n" +" comparators=[\n" +" Constant(value=5)]),\n" +" Compare(\n" +" left=Name(id='n', ctx=Load()),\n" +" ops=[\n" +" Lt()],\n" +" comparators=[\n" +" Constant(value=10)])],\n" +" is_async=0)]))\n" +"\n" +">>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'),\n" +"... indent=4)) # compreensão de async\n" +"Expression(\n" +" body=ListComp(\n" +" elt=Name(id='i', ctx=Load()),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='i', ctx=Store()),\n" +" iter=Name(id='soc', ctx=Load()),\n" +" is_async=1)]))" + #: ../../library/ast.rst:851 msgid "Statements" msgstr "Instruções" @@ -739,13 +1801,57 @@ msgstr "" "`List` dentro de ``targets``." #: ../../library/ast.rst:863 ../../library/ast.rst:1158 -#: ../../library/ast.rst:1352 ../../library/ast.rst:1881 +#: ../../library/ast.rst:1352 ../../library/ast.rst:1918 msgid "" "``type_comment`` is an optional string with the type annotation as a comment." msgstr "" "``type_comment`` é uma string opcional com a anotação de tipo como " "comentário." +#: ../../library/ast.rst:865 +msgid "" +">>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Name(id='a', ctx=Store()),\n" +" Name(id='b', ctx=Store())],\n" +" value=Constant(value=1))])\n" +"\n" +">>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Tuple(\n" +" elts=[\n" +" Name(id='a', ctx=Store()),\n" +" Name(id='b', ctx=Store())],\n" +" ctx=Store())],\n" +" value=Name(id='c', ctx=Load()))])" +msgstr "" +">>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Name(id='a', ctx=Store()),\n" +" Name(id='b', ctx=Store())],\n" +" value=Constant(value=1))])\n" +"\n" +">>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Tuple(\n" +" elts=[\n" +" Name(id='a', ctx=Store()),\n" +" Name(id='b', ctx=Store())],\n" +" ctx=Store())],\n" +" value=Name(id='c', ctx=Load()))])" + #: ../../library/ast.rst:891 msgid "" "An assignment with a type annotation. ``target`` is a single node and can be " @@ -764,13 +1870,97 @@ msgid "" "(indicating a \"simple\" target). A \"simple\" target consists solely of a :" "class:`Name` node that does not appear between parentheses; all other " "targets are considered complex. Only simple targets appear in the :attr:" -"`__annotations__` dictionary of modules and classes." +"`~object.__annotations__` dictionary of modules and classes." msgstr "" "``simple`` é sempre 0 (indicando um alvo \"complexo\") ou 1 (indicando um " "alvo \"simples\"). Um alvo \"simples\" consiste apenas em um nó :class:" "`Name` que não aparece entre parênteses; todos os outros alvos são " "considerados complexos. Apenas alvos simples aparecem no dicionário :attr:" -"`__annotations__` de módulos e classes." +"`~object.__annotations__` de módulos e classes." + +#: ../../library/ast.rst:902 +msgid "" +">>> print(ast.dump(ast.parse('c: int'), indent=4))\n" +"Module(\n" +" body=[\n" +" AnnAssign(\n" +" target=Name(id='c', ctx=Store()),\n" +" annotation=Name(id='int', ctx=Load()),\n" +" simple=1)])\n" +"\n" +">>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with " +"parenthesis\n" +"Module(\n" +" body=[\n" +" AnnAssign(\n" +" target=Name(id='a', ctx=Store()),\n" +" annotation=Name(id='int', ctx=Load()),\n" +" value=Constant(value=1),\n" +" simple=0)])\n" +"\n" +">>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation\n" +"Module(\n" +" body=[\n" +" AnnAssign(\n" +" target=Attribute(\n" +" value=Name(id='a', ctx=Load()),\n" +" attr='b',\n" +" ctx=Store()),\n" +" annotation=Name(id='int', ctx=Load()),\n" +" simple=0)])\n" +"\n" +">>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript " +"annotation\n" +"Module(\n" +" body=[\n" +" AnnAssign(\n" +" target=Subscript(\n" +" value=Name(id='a', ctx=Load()),\n" +" slice=Constant(value=1),\n" +" ctx=Store()),\n" +" annotation=Name(id='int', ctx=Load()),\n" +" simple=0)])" +msgstr "" +">>> print(ast.dump(ast.parse('c: int'), indent=4))\n" +"Module(\n" +" body=[\n" +" AnnAssign(\n" +" target=Name(id='c', ctx=Store()),\n" +" annotation=Name(id='int', ctx=Load()),\n" +" simple=1)])\n" +"\n" +">>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with " +"parenthesis\n" +"Module(\n" +" body=[\n" +" AnnAssign(\n" +" target=Name(id='a', ctx=Store()),\n" +" annotation=Name(id='int', ctx=Load()),\n" +" value=Constant(value=1),\n" +" simple=0)])\n" +"\n" +">>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation\n" +"Module(\n" +" body=[\n" +" AnnAssign(\n" +" target=Attribute(\n" +" value=Name(id='a', ctx=Load()),\n" +" attr='b',\n" +" ctx=Store()),\n" +" annotation=Name(id='int', ctx=Load()),\n" +" simple=0)])\n" +"\n" +">>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript " +"annotation\n" +"Module(\n" +" body=[\n" +" AnnAssign(\n" +" target=Subscript(\n" +" value=Name(id='a', ctx=Load()),\n" +" slice=Constant(value=1),\n" +" ctx=Store()),\n" +" annotation=Name(id='int', ctx=Load()),\n" +" simple=0)])" #: ../../library/ast.rst:946 msgid "" @@ -791,6 +1981,24 @@ msgstr "" "O atributo ``target`` não pode ser da classe :class:`Tuple` ou :class:" "`List`, diferentemente dos alvos de :class:`Assign`." +#: ../../library/ast.rst:954 +msgid "" +">>> print(ast.dump(ast.parse('x += 2'), indent=4))\n" +"Module(\n" +" body=[\n" +" AugAssign(\n" +" target=Name(id='x', ctx=Store()),\n" +" op=Add(),\n" +" value=Constant(value=2))])" +msgstr "" +">>> print(ast.dump(ast.parse('x += 2'), indent=4))\n" +"Module(\n" +" body=[\n" +" AugAssign(\n" +" target=Name(id='x', ctx=Store()),\n" +" op=Add(),\n" +" value=Constant(value=2))])" + #: ../../library/ast.rst:967 msgid "" "A ``raise`` statement. ``exc`` is the exception object to be raised, " @@ -802,6 +2010,22 @@ msgstr "" "``raise`` independente. ``cause`` é a parte opcional para ``y`` em ``raise x " "from y``." +#: ../../library/ast.rst:971 +msgid "" +">>> print(ast.dump(ast.parse('raise x from y'), indent=4))\n" +"Module(\n" +" body=[\n" +" Raise(\n" +" exc=Name(id='x', ctx=Load()),\n" +" cause=Name(id='y', ctx=Load()))])" +msgstr "" +">>> print(ast.dump(ast.parse('raise x from y'), indent=4))\n" +"Module(\n" +" body=[\n" +" Raise(\n" +" exc=Name(id='x', ctx=Load()),\n" +" cause=Name(id='y', ctx=Load()))])" + #: ../../library/ast.rst:983 msgid "" "An assertion. ``test`` holds the condition, such as a :class:`Compare` node. " @@ -810,6 +2034,22 @@ msgstr "" "Uma asserção. ``test`` contém a condição, como um nó :class:`Compare`. " "``msg`` contém a mensagem de falha." +#: ../../library/ast.rst:986 +msgid "" +">>> print(ast.dump(ast.parse('assert x,y'), indent=4))\n" +"Module(\n" +" body=[\n" +" Assert(\n" +" test=Name(id='x', ctx=Load()),\n" +" msg=Name(id='y', ctx=Load()))])" +msgstr "" +">>> print(ast.dump(ast.parse('assert x,y'), indent=4))\n" +"Module(\n" +" body=[\n" +" Assert(\n" +" test=Name(id='x', ctx=Load()),\n" +" msg=Name(id='y', ctx=Load()))])" + #: ../../library/ast.rst:998 msgid "" "Represents a ``del`` statement. ``targets`` is a list of nodes, such as :" @@ -818,10 +2058,42 @@ msgstr "" "Representa uma instrução ``del``. ``targets`` é uma lista de nós, como nós :" "class:`Name`, :class:`Attribute` ou :class:`Subscript`." +#: ../../library/ast.rst:1001 +msgid "" +">>> print(ast.dump(ast.parse('del x,y,z'), indent=4))\n" +"Module(\n" +" body=[\n" +" Delete(\n" +" targets=[\n" +" Name(id='x', ctx=Del()),\n" +" Name(id='y', ctx=Del()),\n" +" Name(id='z', ctx=Del())])])" +msgstr "" +">>> print(ast.dump(ast.parse('del x,y,z'), indent=4))\n" +"Module(\n" +" body=[\n" +" Delete(\n" +" targets=[\n" +" Name(id='x', ctx=Del()),\n" +" Name(id='y', ctx=Del()),\n" +" Name(id='z', ctx=Del())])])" + #: ../../library/ast.rst:1015 msgid "A ``pass`` statement." msgstr "Uma instrução ``pass``." +#: ../../library/ast.rst:1017 +msgid "" +">>> print(ast.dump(ast.parse('pass'), indent=4))\n" +"Module(\n" +" body=[\n" +" Pass()])" +msgstr "" +">>> print(ast.dump(ast.parse('pass'), indent=4))\n" +"Module(\n" +" body=[\n" +" Pass()])" + #: ../../library/ast.rst:1027 msgid "" "A :ref:`type alias ` created through the :keyword:`type` " @@ -834,6 +2106,22 @@ msgstr "" "de :ref:`parâmetros de tipo `, e ``value`` é o valor do " "apelido do tipo." +#: ../../library/ast.rst:1032 +msgid "" +">>> print(ast.dump(ast.parse('type Alias = int'), indent=4))\n" +"Module(\n" +" body=[\n" +" TypeAlias(\n" +" name=Name(id='Alias', ctx=Store()),\n" +" value=Name(id='int', ctx=Load()))])" +msgstr "" +">>> print(ast.dump(ast.parse('type Alias = int'), indent=4))\n" +"Module(\n" +" body=[\n" +" TypeAlias(\n" +" name=Name(id='Alias', ctx=Store()),\n" +" value=Name(id='int', ctx=Load()))])" + #: ../../library/ast.rst:1043 msgid "" "Other statements which are only applicable inside functions or loops are " @@ -851,6 +2139,26 @@ msgid "An import statement. ``names`` is a list of :class:`alias` nodes." msgstr "" "Uma instrução de importação. ``names`` é uma lista de nós de :class:`alias`." +#: ../../library/ast.rst:1053 +msgid "" +">>> print(ast.dump(ast.parse('import x,y,z'), indent=4))\n" +"Module(\n" +" body=[\n" +" Import(\n" +" names=[\n" +" alias(name='x'),\n" +" alias(name='y'),\n" +" alias(name='z')])])" +msgstr "" +">>> print(ast.dump(ast.parse('import x,y,z'), indent=4))\n" +"Module(\n" +" body=[\n" +" Import(\n" +" names=[\n" +" alias(name='x'),\n" +" alias(name='y'),\n" +" alias(name='z')])])" + #: ../../library/ast.rst:1067 msgid "" "Represents ``from x import y``. ``module`` is a raw string of the 'from' " @@ -863,6 +2171,30 @@ msgstr "" "``from . import foo``. ``level`` é um número inteiro que contém o nível da " "importação relativa (0 significa importação absoluta)." +#: ../../library/ast.rst:1072 +msgid "" +">>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4))\n" +"Module(\n" +" body=[\n" +" ImportFrom(\n" +" module='y',\n" +" names=[\n" +" alias(name='x'),\n" +" alias(name='y'),\n" +" alias(name='z')],\n" +" level=0)])" +msgstr "" +">>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4))\n" +"Module(\n" +" body=[\n" +" ImportFrom(\n" +" module='y',\n" +" names=[\n" +" alias(name='x'),\n" +" alias(name='y'),\n" +" alias(name='z')],\n" +" level=0)])" + #: ../../library/ast.rst:1088 msgid "" "Both parameters are raw strings of the names. ``asname`` can be ``None`` if " @@ -871,6 +2203,28 @@ msgstr "" "Ambos os parâmetros são strings brutas dos nomes. ``asname`` pode ser " "``None`` se o nome normal for usado." +#: ../../library/ast.rst:1091 +msgid "" +">>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4))\n" +"Module(\n" +" body=[\n" +" ImportFrom(\n" +" module='foo.bar',\n" +" names=[\n" +" alias(name='a', asname='b'),\n" +" alias(name='c')],\n" +" level=2)])" +msgstr "" +">>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4))\n" +"Module(\n" +" body=[\n" +" ImportFrom(\n" +" module='foo.bar',\n" +" names=[\n" +" alias(name='a', asname='b'),\n" +" alias(name='c')],\n" +" level=2)])" + #: ../../library/ast.rst:1104 msgid "Control flow" msgstr "Fluxo de controle" @@ -901,6 +2255,58 @@ msgstr "" "aparecem como nós extras de :class:`If` dentro da seção ``orelse`` da " "cláusula anterior." +#: ../../library/ast.rst:1119 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... if x:\n" +"... ...\n" +"... elif y:\n" +"... ...\n" +"... else:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" If(\n" +" test=Name(id='x', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" orelse=[\n" +" If(\n" +" test=Name(id='y', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" orelse=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... if x:\n" +"... ...\n" +"... elif y:\n" +"... ...\n" +"... else:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" If(\n" +" test=Name(id='x', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" orelse=[\n" +" If(\n" +" test=Name(id='y', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" orelse=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" + #: ../../library/ast.rst:1149 msgid "" "A ``for`` loop. ``target`` holds the variable(s) the loop assigns to, as a " @@ -917,6 +2323,44 @@ msgstr "" "executar. Aqueles em ``orelse`` são executados se o laço terminar " "normalmente, ao invés de através de uma instrução ``break``." +#: ../../library/ast.rst:1160 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... for x in y:\n" +"... ...\n" +"... else:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" For(\n" +" target=Name(id='x', ctx=Store()),\n" +" iter=Name(id='y', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" orelse=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... for x in y:\n" +"... ...\n" +"... else:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" For(\n" +" target=Name(id='x', ctx=Store()),\n" +" iter=Name(id='y', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" orelse=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])" + #: ../../library/ast.rst:1183 msgid "" "A ``while`` loop. ``test`` holds the condition, such as a :class:`Compare` " @@ -925,10 +2369,100 @@ msgstr "" "Um laço ``while``. ``test`` contém a condição, como um nó de :class:" "`Compare`." +#: ../../library/ast.rst:1186 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... while x:\n" +"... ...\n" +"... else:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" While(\n" +" test=Name(id='x', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" orelse=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... while x:\n" +"... ...\n" +"... else:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" While(\n" +" test=Name(id='x', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" orelse=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])" + #: ../../library/ast.rst:1209 msgid "The ``break`` and ``continue`` statements." msgstr "As instruções ``break`` e ``continue``." +#: ../../library/ast.rst:1211 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... for a in b:\n" +"... if a > 5:\n" +"... break\n" +"... else:\n" +"... continue\n" +"...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" For(\n" +" target=Name(id='a', ctx=Store()),\n" +" iter=Name(id='b', ctx=Load()),\n" +" body=[\n" +" If(\n" +" test=Compare(\n" +" left=Name(id='a', ctx=Load()),\n" +" ops=[\n" +" Gt()],\n" +" comparators=[\n" +" Constant(value=5)]),\n" +" body=[\n" +" Break()],\n" +" orelse=[\n" +" Continue()])])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... for a in b:\n" +"... if a > 5:\n" +"... break\n" +"... else:\n" +"... continue\n" +"...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" For(\n" +" target=Name(id='a', ctx=Store()),\n" +" iter=Name(id='b', ctx=Load()),\n" +" body=[\n" +" If(\n" +" test=Compare(\n" +" left=Name(id='a', ctx=Load()),\n" +" ops=[\n" +" Gt()],\n" +" comparators=[\n" +" Constant(value=5)]),\n" +" body=[\n" +" Break()],\n" +" orelse=[\n" +" Continue()])])])" + #: ../../library/ast.rst:1242 msgid "" "``try`` blocks. All attributes are list of nodes to execute, except for " @@ -937,6 +2471,82 @@ msgstr "" "Blocos ``try``. Todos os atributos são uma lista de nós a serem executados, " "exceto ``handlers``, que é uma lista de nós de :class:`ExceptHandler`." +#: ../../library/ast.rst:1245 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... try:\n" +"... ...\n" +"... except Exception:\n" +"... ...\n" +"... except OtherException as e:\n" +"... ...\n" +"... else:\n" +"... ...\n" +"... finally:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Try(\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" handlers=[\n" +" ExceptHandler(\n" +" type=Name(id='Exception', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" ExceptHandler(\n" +" type=Name(id='OtherException', ctx=Load()),\n" +" name='e',\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])],\n" +" orelse=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" finalbody=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... try:\n" +"... ...\n" +"... except Exception:\n" +"... ...\n" +"... except OtherException as e:\n" +"... ...\n" +"... else:\n" +"... ...\n" +"... finally:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Try(\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" handlers=[\n" +" ExceptHandler(\n" +" type=Name(id='Exception', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" ExceptHandler(\n" +" type=Name(id='OtherException', ctx=Load()),\n" +" name='e',\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])],\n" +" orelse=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" finalbody=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])" + #: ../../library/ast.rst:1287 msgid "" "``try`` blocks which are followed by ``except*`` clauses. The attributes are " @@ -947,6 +2557,46 @@ msgstr "" "os mesmos de :class:`Try`, mas os nós :class:`ExceptHandler` em ``handlers`` " "são interpretados como blocos ``except*`` em vez de ``except``." +#: ../../library/ast.rst:1291 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... try:\n" +"... ...\n" +"... except* Exception:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" TryStar(\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" handlers=[\n" +" ExceptHandler(\n" +" type=Name(id='Exception', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... try:\n" +"... ...\n" +"... except* Exception:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" TryStar(\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" handlers=[\n" +" ExceptHandler(\n" +" type=Name(id='Exception', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" + #: ../../library/ast.rst:1316 msgid "" "A single ``except`` clause. ``type`` is the exception type it will match, " @@ -960,6 +2610,50 @@ msgstr "" "conter a exceção, ou ``None`` se a cláusula não tiver ``as foo``. ``body`` é " "uma lista de nós." +#: ../../library/ast.rst:1321 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... try:\n" +"... a + 1\n" +"... except TypeError:\n" +"... pass\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Try(\n" +" body=[\n" +" Expr(\n" +" value=BinOp(\n" +" left=Name(id='a', ctx=Load()),\n" +" op=Add(),\n" +" right=Constant(value=1)))],\n" +" handlers=[\n" +" ExceptHandler(\n" +" type=Name(id='TypeError', ctx=Load()),\n" +" body=[\n" +" Pass()])])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... try:\n" +"... a + 1\n" +"... except TypeError:\n" +"... pass\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Try(\n" +" body=[\n" +" Expr(\n" +" value=BinOp(\n" +" left=Name(id='a', ctx=Load()),\n" +" op=Add(),\n" +" right=Constant(value=1)))],\n" +" handlers=[\n" +" ExceptHandler(\n" +" type=Name(id='TypeError', ctx=Load()),\n" +" body=[\n" +" Pass()])])])" + #: ../../library/ast.rst:1347 msgid "" "A ``with`` block. ``items`` is a list of :class:`withitem` nodes " @@ -982,6 +2676,52 @@ msgstr "" "``optional_vars`` é um :class:`Name`, :class:`Tuple` ou :class:`List` para a " "parte ``as foo``, ou ``None`` se não for usado." +#: ../../library/ast.rst:1362 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... with a as b, c as d:\n" +"... something(b, d)\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" With(\n" +" items=[\n" +" withitem(\n" +" context_expr=Name(id='a', ctx=Load()),\n" +" optional_vars=Name(id='b', ctx=Store())),\n" +" withitem(\n" +" context_expr=Name(id='c', ctx=Load()),\n" +" optional_vars=Name(id='d', ctx=Store()))],\n" +" body=[\n" +" Expr(\n" +" value=Call(\n" +" func=Name(id='something', ctx=Load()),\n" +" args=[\n" +" Name(id='b', ctx=Load()),\n" +" Name(id='d', ctx=Load())]))])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... with a as b, c as d:\n" +"... something(b, d)\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" With(\n" +" items=[\n" +" withitem(\n" +" context_expr=Name(id='a', ctx=Load()),\n" +" optional_vars=Name(id='b', ctx=Store())),\n" +" withitem(\n" +" context_expr=Name(id='c', ctx=Load()),\n" +" optional_vars=Name(id='d', ctx=Store()))],\n" +" body=[\n" +" Expr(\n" +" value=Call(\n" +" func=Name(id='something', ctx=Load()),\n" +" args=[\n" +" Name(id='b', ctx=Load()),\n" +" Name(id='d', ctx=Load())]))])])" + #: ../../library/ast.rst:1388 msgid "Pattern matching" msgstr "Correspondência de padrões" @@ -1024,6 +2764,72 @@ msgstr "" "``body`` contém uma lista de nós a serem executados se o padrão corresponder " "e o resultado da avaliação da expressão de guarda for verdadeiro." +#: ../../library/ast.rst:1412 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case [x] if x>0:\n" +"... ...\n" +"... case tuple():\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchSequence(\n" +" patterns=[\n" +" MatchAs(name='x')]),\n" +" guard=Compare(\n" +" left=Name(id='x', ctx=Load()),\n" +" ops=[\n" +" Gt()],\n" +" comparators=[\n" +" Constant(value=0)]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" match_case(\n" +" pattern=MatchClass(\n" +" cls=Name(id='tuple', ctx=Load())),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case [x] if x>0:\n" +"... ...\n" +"... case tuple():\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchSequence(\n" +" patterns=[\n" +" MatchAs(name='x')]),\n" +" guard=Compare(\n" +" left=Name(id='x', ctx=Load()),\n" +" ops=[\n" +" Gt()],\n" +" comparators=[\n" +" Constant(value=0)]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" match_case(\n" +" pattern=MatchClass(\n" +" cls=Name(id='tuple', ctx=Load())),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" + #: ../../library/ast.rst:1450 msgid "" "A match literal or value pattern that compares by equality. ``value`` is an " @@ -1037,6 +2843,42 @@ msgstr "" "Este padrão será bem-sucedido se o assunto da correspondência for igual ao " "valor avaliado." +#: ../../library/ast.rst:1455 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case \"Relevant\":\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchValue(\n" +" value=Constant(value='Relevant')),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case \"Relevant\":\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchValue(\n" +" value=Constant(value='Relevant')),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" + #: ../../library/ast.rst:1478 msgid "" "A match literal pattern that compares by identity. ``value`` is the " @@ -1048,6 +2890,40 @@ msgstr "" "padrão será bem-sucedido se o assunto da correspondência for a constante " "fornecida." +#: ../../library/ast.rst:1482 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case None:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchSingleton(value=None),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case None:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchSingleton(value=None),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" + #: ../../library/ast.rst:1504 msgid "" "A match sequence pattern. ``patterns`` contains the patterns to be matched " @@ -1061,6 +2937,50 @@ msgstr "" "um nó ``MatchStar``, caso contrário corresponde a uma sequência de " "comprimento fixo." +#: ../../library/ast.rst:1509 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case [1, 2]:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchSequence(\n" +" patterns=[\n" +" MatchValue(\n" +" value=Constant(value=1)),\n" +" MatchValue(\n" +" value=Constant(value=2))]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case [1, 2]:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchSequence(\n" +" patterns=[\n" +" MatchValue(\n" +" value=Constant(value=1)),\n" +" MatchValue(\n" +" value=Constant(value=2))]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" + #: ../../library/ast.rst:1536 msgid "" "Matches the rest of the sequence in a variable length match sequence " @@ -1073,6 +2993,70 @@ msgstr "" "lista contendo os elementos restantes da sequência será vinculada a esse " "nome se o padrão de sequência geral for bem-sucedido." +#: ../../library/ast.rst:1540 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case [1, 2, *rest]:\n" +"... ...\n" +"... case [*_]:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchSequence(\n" +" patterns=[\n" +" MatchValue(\n" +" value=Constant(value=1)),\n" +" MatchValue(\n" +" value=Constant(value=2)),\n" +" MatchStar(name='rest')]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" match_case(\n" +" pattern=MatchSequence(\n" +" patterns=[\n" +" MatchStar()]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case [1, 2, *rest]:\n" +"... ...\n" +"... case [*_]:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchSequence(\n" +" patterns=[\n" +" MatchValue(\n" +" value=Constant(value=1)),\n" +" MatchValue(\n" +" value=Constant(value=2)),\n" +" MatchStar(name='rest')]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" match_case(\n" +" pattern=MatchSequence(\n" +" patterns=[\n" +" MatchStar()]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" + #: ../../library/ast.rst:1577 msgid "" "A match mapping pattern. ``keys`` is a sequence of expression nodes. " @@ -1102,6 +3086,66 @@ msgstr "" "restantes será vinculado a esse nome se o padrão de mapeamento geral for bem-" "sucedido." +#: ../../library/ast.rst:1589 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case {1: _, 2: _}:\n" +"... ...\n" +"... case {**rest}:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchMapping(\n" +" keys=[\n" +" Constant(value=1),\n" +" Constant(value=2)],\n" +" patterns=[\n" +" MatchAs(),\n" +" MatchAs()]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" match_case(\n" +" pattern=MatchMapping(rest='rest'),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case {1: _, 2: _}:\n" +"... ...\n" +"... case {**rest}:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchMapping(\n" +" keys=[\n" +" Constant(value=1),\n" +" Constant(value=2)],\n" +" patterns=[\n" +" MatchAs(),\n" +" MatchAs()]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" match_case(\n" +" pattern=MatchMapping(rest='rest'),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" + #: ../../library/ast.rst:1624 msgid "" "A match class pattern. ``cls`` is an expression giving the nominal class to " @@ -1143,6 +3187,90 @@ msgstr "" "tipos internos também são combinados dessa forma, conforme descrito na " "documentação da instrução match." +#: ../../library/ast.rst:1639 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case Point2D(0, 0):\n" +"... ...\n" +"... case Point3D(x=0, y=0, z=0):\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchClass(\n" +" cls=Name(id='Point2D', ctx=Load()),\n" +" patterns=[\n" +" MatchValue(\n" +" value=Constant(value=0)),\n" +" MatchValue(\n" +" value=Constant(value=0))]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" match_case(\n" +" pattern=MatchClass(\n" +" cls=Name(id='Point3D', ctx=Load()),\n" +" kwd_attrs=[\n" +" 'x',\n" +" 'y',\n" +" 'z'],\n" +" kwd_patterns=[\n" +" MatchValue(\n" +" value=Constant(value=0)),\n" +" MatchValue(\n" +" value=Constant(value=0)),\n" +" MatchValue(\n" +" value=Constant(value=0))]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case Point2D(0, 0):\n" +"... ...\n" +"... case Point3D(x=0, y=0, z=0):\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchClass(\n" +" cls=Name(id='Point2D', ctx=Load()),\n" +" patterns=[\n" +" MatchValue(\n" +" value=Constant(value=0)),\n" +" MatchValue(\n" +" value=Constant(value=0))]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" match_case(\n" +" pattern=MatchClass(\n" +" cls=Name(id='Point3D', ctx=Load()),\n" +" kwd_attrs=[\n" +" 'x',\n" +" 'y',\n" +" 'z'],\n" +" kwd_patterns=[\n" +" MatchValue(\n" +" value=Constant(value=0)),\n" +" MatchValue(\n" +" value=Constant(value=0)),\n" +" MatchValue(\n" +" value=Constant(value=0))]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" + #: ../../library/ast.rst:1686 msgid "" "A match \"as-pattern\", capture pattern or wildcard pattern. ``pattern`` " @@ -1165,6 +3293,62 @@ msgstr "" "sucedido. Se ``name`` for ``None``, ``pattern`` também deverá ser ``None`` e " "o nó representa o padrão curinga." +#: ../../library/ast.rst:1695 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case [x] as y:\n" +"... ...\n" +"... case _:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchAs(\n" +" pattern=MatchSequence(\n" +" patterns=[\n" +" MatchAs(name='x')]),\n" +" name='y'),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" match_case(\n" +" pattern=MatchAs(),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case [x] as y:\n" +"... ...\n" +"... case _:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchAs(\n" +" pattern=MatchSequence(\n" +" patterns=[\n" +" MatchAs(name='x')]),\n" +" name='y'),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" match_case(\n" +" pattern=MatchAs(),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" + #: ../../library/ast.rst:1728 msgid "" "A match \"or-pattern\". An or-pattern matches each of its subpatterns in " @@ -1179,11 +3363,123 @@ msgstr "" "sucedido, o padrão or falhará. O atributo ``patterns`` contém uma lista de " "nós de padrões de correspondência que serão comparados com o assunto." -#: ../../library/ast.rst:1762 +#: ../../library/ast.rst:1734 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case [x] | (y):\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchOr(\n" +" patterns=[\n" +" MatchSequence(\n" +" patterns=[\n" +" MatchAs(name='x')]),\n" +" MatchAs(name='y')]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case [x] | (y):\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchOr(\n" +" patterns=[\n" +" MatchSequence(\n" +" patterns=[\n" +" MatchAs(name='x')]),\n" +" MatchAs(name='y')]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])])" + +#: ../../library/ast.rst:1761 +msgid "Type annotations" +msgstr "Anotações de tipos" + +#: ../../library/ast.rst:1765 +msgid "" +"A ``# type: ignore`` comment located at *lineno*. *tag* is the optional tag " +"specified by the form ``# type: ignore ``." +msgstr "" +"Um comentário ``# type: ignore`` localizado em *lineno*. *tag* é a tag " +"opcional especificada pelo formato ``# type: ignore ``." + +#: ../../library/ast.rst:1768 +msgid "" +">>> print(ast.dump(ast.parse('x = 1 # type: ignore', type_comments=True), " +"indent=4))\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Name(id='x', ctx=Store())],\n" +" value=Constant(value=1))],\n" +" type_ignores=[\n" +" TypeIgnore(lineno=1, tag='')])\n" +">>> print(ast.dump(ast.parse('x: bool = 1 # type: ignore[assignment]', " +"type_comments=True), indent=4))\n" +"Module(\n" +" body=[\n" +" AnnAssign(\n" +" target=Name(id='x', ctx=Store()),\n" +" annotation=Name(id='bool', ctx=Load()),\n" +" value=Constant(value=1),\n" +" simple=1)],\n" +" type_ignores=[\n" +" TypeIgnore(lineno=1, tag='[assignment]')])" +msgstr "" +">>> print(ast.dump(ast.parse('x = 1 # type: ignore', type_comments=True), " +"indent=4))\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Name(id='x', ctx=Store())],\n" +" value=Constant(value=1))],\n" +" type_ignores=[\n" +" TypeIgnore(lineno=1, tag='')])\n" +">>> print(ast.dump(ast.parse('x: bool = 1 # type: ignore[assignment]', " +"type_comments=True), indent=4))\n" +"Module(\n" +" body=[\n" +" AnnAssign(\n" +" target=Name(id='x', ctx=Store()),\n" +" annotation=Name(id='bool', ctx=Load()),\n" +" value=Constant(value=1),\n" +" simple=1)],\n" +" type_ignores=[\n" +" TypeIgnore(lineno=1, tag='[assignment]')])" + +#: ../../library/ast.rst:1791 +msgid "" +":class:`!TypeIgnore` nodes are not generated when the *type_comments* " +"parameter is set to ``False`` (default). See :func:`ast.parse` for more " +"details." +msgstr "" +"Os nós :class:`!TypeIgnore` não são gerados quando o parâmetro " +"*type_comments* está definido como ``False`` (padrão). Consulte :func:`ast." +"parse` para obter mais detalhes." + +#: ../../library/ast.rst:1799 msgid "Type parameters" msgstr "Parâmetros de tipo" -#: ../../library/ast.rst:1764 +#: ../../library/ast.rst:1801 msgid "" ":ref:`Type parameters ` can exist on classes, functions, and " "type aliases." @@ -1191,66 +3487,190 @@ msgstr "" ":ref:`Parâmetros de tipo ` podem existir em classes, funções e " "apelidos de tipo." -#: ../../library/ast.rst:1769 +#: ../../library/ast.rst:1806 msgid "" -"A :class:`typing.TypeVar`. *name* is the name of the type variable. *bound* " -"is the bound or constraints, if any. If *bound* is a :class:`Tuple`, it " -"represents constraints; otherwise it represents the bound. *default_value* " -"is the default value; if the :class:`!TypeVar` has no default, this " -"attribute will be set to ``None``." +"A :class:`typing.TypeVar`. ``name`` is the name of the type variable. " +"``bound`` is the bound or constraints, if any. If ``bound`` is a :class:" +"`Tuple`, it represents constraints; otherwise it represents the bound. " +"``default_value`` is the default value; if the :class:`!TypeVar` has no " +"default, this attribute will be set to ``None``." msgstr "" -"Uma :class:`typing.TypeVar`. *name* é o nome da variável de tipo. *bound* é " -"o limite ou as restrições, se houver. Se *bound* for uma :class:`Tuple`, ele " -"representa restrições; caso contrário, representa o limite. *default_value* " -"é o valor padrão; se :class:`!TypeVar` não tiver padrão, este atributo será " -"definido como ``None``." +"Uma :class:`typing.TypeVar`. ``name`` é o nome da variável de tipo. " +"``bound`` é o limite ou as restrições, se houver. Se ``bound`` for uma :" +"class:`Tuple`, ele representa restrições; caso contrário, representa o " +"limite. ``default_value`` é o valor padrão; se :class:`!TypeVar` não tiver " +"padrão, este atributo será definido como ``None``." -#: ../../library/ast.rst:1794 ../../library/ast.rst:1829 -#: ../../library/ast.rst:1861 +#: ../../library/ast.rst:1812 +msgid "" +">>> print(ast.dump(ast.parse(\"type Alias[T: int = bool] = list[T]\"), " +"indent=4))\n" +"Module(\n" +" body=[\n" +" TypeAlias(\n" +" name=Name(id='Alias', ctx=Store()),\n" +" type_params=[\n" +" TypeVar(\n" +" name='T',\n" +" bound=Name(id='int', ctx=Load()),\n" +" default_value=Name(id='bool', ctx=Load()))],\n" +" value=Subscript(\n" +" value=Name(id='list', ctx=Load()),\n" +" slice=Name(id='T', ctx=Load()),\n" +" ctx=Load()))])" +msgstr "" +">>> print(ast.dump(ast.parse(\"type Alias[T: int = bool] = list[T]\"), " +"indent=4))\n" +"Module(\n" +" body=[\n" +" TypeAlias(\n" +" name=Name(id='Alias', ctx=Store()),\n" +" type_params=[\n" +" TypeVar(\n" +" name='T',\n" +" bound=Name(id='int', ctx=Load()),\n" +" default_value=Name(id='bool', ctx=Load()))],\n" +" value=Subscript(\n" +" value=Name(id='list', ctx=Load()),\n" +" slice=Name(id='T', ctx=Load()),\n" +" ctx=Load()))])" + +#: ../../library/ast.rst:1831 ../../library/ast.rst:1866 +#: ../../library/ast.rst:1898 msgid "Added the *default_value* parameter." msgstr "Adicionado o parâmetro *default_value*." -#: ../../library/ast.rst:1799 +#: ../../library/ast.rst:1836 msgid "" -"A :class:`typing.ParamSpec`. *name* is the name of the parameter " -"specification. *default_value* is the default value; if the :class:`!" +"A :class:`typing.ParamSpec`. ``name`` is the name of the parameter " +"specification. ``default_value`` is the default value; if the :class:`!" "ParamSpec` has no default, this attribute will be set to ``None``." msgstr "" -"Uma :class:`typing.ParamSpec`. *name* é o nome da especificação do " -"parâmetro. *default_value* é o valor padrão; se :class:`!ParamSpec` não " +"Uma :class:`typing.ParamSpec`. ``name`` é o nome da especificação do " +"parâmetro. ``default_value`` é o valor padrão; se :class:`!ParamSpec` não " "tiver padrão, este atributo será definido como ``None``." -#: ../../library/ast.rst:1834 +#: ../../library/ast.rst:1840 +msgid "" +">>> print(ast.dump(ast.parse(\"type Alias[**P = [int, str]] = Callable[P, " +"int]\"), indent=4))\n" +"Module(\n" +" body=[\n" +" TypeAlias(\n" +" name=Name(id='Alias', ctx=Store()),\n" +" type_params=[\n" +" ParamSpec(\n" +" name='P',\n" +" default_value=List(\n" +" elts=[\n" +" Name(id='int', ctx=Load()),\n" +" Name(id='str', ctx=Load())],\n" +" ctx=Load()))],\n" +" value=Subscript(\n" +" value=Name(id='Callable', ctx=Load()),\n" +" slice=Tuple(\n" +" elts=[\n" +" Name(id='P', ctx=Load()),\n" +" Name(id='int', ctx=Load())],\n" +" ctx=Load()),\n" +" ctx=Load()))])" +msgstr "" +">>> print(ast.dump(ast.parse(\"type Alias[**P = [int, str]] = Callable[P, " +"int]\"), indent=4))\n" +"Module(\n" +" body=[\n" +" TypeAlias(\n" +" name=Name(id='Alias', ctx=Store()),\n" +" type_params=[\n" +" ParamSpec(\n" +" name='P',\n" +" default_value=List(\n" +" elts=[\n" +" Name(id='int', ctx=Load()),\n" +" Name(id='str', ctx=Load())],\n" +" ctx=Load()))],\n" +" value=Subscript(\n" +" value=Name(id='Callable', ctx=Load()),\n" +" slice=Tuple(\n" +" elts=[\n" +" Name(id='P', ctx=Load()),\n" +" Name(id='int', ctx=Load())],\n" +" ctx=Load()),\n" +" ctx=Load()))])" + +#: ../../library/ast.rst:1871 msgid "" -"A :class:`typing.TypeVarTuple`. *name* is the name of the type variable " -"tuple. *default_value* is the default value; if the :class:`!TypeVarTuple` " +"A :class:`typing.TypeVarTuple`. ``name`` is the name of the type variable " +"tuple. ``default_value`` is the default value; if the :class:`!TypeVarTuple` " "has no default, this attribute will be set to ``None``." msgstr "" -"Uma :class:`typing.TypeVarTuple`. *name* é o nome da tupla da variável de " -"tipo. *default_value* é o valor padrão; se :class:`!TypeVarTuple` não tiver " -"padrão, este atributo será definido como ``None``." +"Uma :class:`typing.TypeVarTuple`. ``name`` é o nome da tupla da variável de " +"tipo. ``default_value`` é o valor padrão; se :class:`!TypeVarTuple` não " +"tiver padrão, este atributo será definido como ``None``." -#: ../../library/ast.rst:1865 +#: ../../library/ast.rst:1875 +msgid "" +">>> print(ast.dump(ast.parse(\"type Alias[*Ts = ()] = tuple[*Ts]\"), " +"indent=4))\n" +"Module(\n" +" body=[\n" +" TypeAlias(\n" +" name=Name(id='Alias', ctx=Store()),\n" +" type_params=[\n" +" TypeVarTuple(\n" +" name='Ts',\n" +" default_value=Tuple(ctx=Load()))],\n" +" value=Subscript(\n" +" value=Name(id='tuple', ctx=Load()),\n" +" slice=Tuple(\n" +" elts=[\n" +" Starred(\n" +" value=Name(id='Ts', ctx=Load()),\n" +" ctx=Load())],\n" +" ctx=Load()),\n" +" ctx=Load()))])" +msgstr "" +">>> print(ast.dump(ast.parse(\"type Alias[*Ts = ()] = tuple[*Ts]\"), " +"indent=4))\n" +"Module(\n" +" body=[\n" +" TypeAlias(\n" +" name=Name(id='Alias', ctx=Store()),\n" +" type_params=[\n" +" TypeVarTuple(\n" +" name='Ts',\n" +" default_value=Tuple(ctx=Load()))],\n" +" value=Subscript(\n" +" value=Name(id='tuple', ctx=Load()),\n" +" slice=Tuple(\n" +" elts=[\n" +" Starred(\n" +" value=Name(id='Ts', ctx=Load()),\n" +" ctx=Load())],\n" +" ctx=Load()),\n" +" ctx=Load()))])" + +#: ../../library/ast.rst:1902 msgid "Function and class definitions" msgstr "Definições de função e classe" -#: ../../library/ast.rst:1869 +#: ../../library/ast.rst:1906 msgid "A function definition." msgstr "Uma definição de função" -#: ../../library/ast.rst:1871 +#: ../../library/ast.rst:1908 msgid "``name`` is a raw string of the function name." msgstr "``name`` é uma string bruta do nome da função." -#: ../../library/ast.rst:1872 +#: ../../library/ast.rst:1909 msgid "``args`` is an :class:`arguments` node." msgstr "``args`` é um nó :class:`arguments`." -#: ../../library/ast.rst:1873 +#: ../../library/ast.rst:1910 msgid "``body`` is the list of nodes inside the function." msgstr "``body`` é a lista de nós dentro da função." -#: ../../library/ast.rst:1874 +#: ../../library/ast.rst:1911 msgid "" "``decorator_list`` is the list of decorators to be applied, stored outermost " "first (i.e. the first in the list will be applied last)." @@ -1259,21 +3679,21 @@ msgstr "" "primeiro na parte externa (ou seja, o primeiro da lista será aplicado por " "último)." -#: ../../library/ast.rst:1876 +#: ../../library/ast.rst:1913 msgid "``returns`` is the return annotation." msgstr "``returns`` é a anotação de retorno." -#: ../../library/ast.rst:1877 ../../library/ast.rst:2041 +#: ../../library/ast.rst:1914 ../../library/ast.rst:2077 msgid "``type_params`` is a list of :ref:`type parameters `." msgstr "" "``type_params`` é uma lista de :ref:`parâmetros de tipo `." -#: ../../library/ast.rst:1883 ../../library/ast.rst:2068 -#: ../../library/ast.rst:2079 +#: ../../library/ast.rst:1920 ../../library/ast.rst:2104 +#: ../../library/ast.rst:2115 msgid "Added ``type_params``." msgstr "Adicionado ``type_params``." -#: ../../library/ast.rst:1889 +#: ../../library/ast.rst:1926 msgid "" "``lambda`` is a minimal function definition that can be used inside an " "expression. Unlike :class:`FunctionDef`, ``body`` holds a single node." @@ -1281,17 +3701,41 @@ msgstr "" "``lambda`` é uma definição mínima de função que pode ser usada dentro de uma " "expressão. Ao contrário de :class:`FunctionDef`, ``body`` contém um único nó." -#: ../../library/ast.rst:1908 +#: ../../library/ast.rst:1929 +msgid "" +">>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4))\n" +"Module(\n" +" body=[\n" +" Expr(\n" +" value=Lambda(\n" +" args=arguments(\n" +" args=[\n" +" arg(arg='x'),\n" +" arg(arg='y')]),\n" +" body=Constant(value=Ellipsis)))])" +msgstr "" +">>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4))\n" +"Module(\n" +" body=[\n" +" Expr(\n" +" value=Lambda(\n" +" args=arguments(\n" +" args=[\n" +" arg(arg='x'),\n" +" arg(arg='y')]),\n" +" body=Constant(value=Ellipsis)))])" + +#: ../../library/ast.rst:1945 msgid "The arguments for a function." msgstr "Os argumentos para uma função." -#: ../../library/ast.rst:1910 +#: ../../library/ast.rst:1947 msgid "" "``posonlyargs``, ``args`` and ``kwonlyargs`` are lists of :class:`arg` nodes." msgstr "" "``posonlyargs``, ``args`` e ``kwonlyargs`` são listas de nós :class:`arg`." -#: ../../library/ast.rst:1911 +#: ../../library/ast.rst:1948 msgid "" "``vararg`` and ``kwarg`` are single :class:`arg` nodes, referring to the " "``*args, **kwargs`` parameters." @@ -1299,7 +3743,7 @@ msgstr "" "``vararg`` e ``kwarg`` são nós :class:`arg` únicos, referindo-se aos " "parâmetros ``*args, **kwargs``." -#: ../../library/ast.rst:1913 +#: ../../library/ast.rst:1950 msgid "" "``kw_defaults`` is a list of default values for keyword-only arguments. If " "one is ``None``, the corresponding argument is required." @@ -1307,17 +3751,17 @@ msgstr "" "``kw_defaults`` é uma lista de valores padrão para argumentos somente-" "nomeados. Se um for ``None``, o argumento correspondente é necessário." -#: ../../library/ast.rst:1915 +#: ../../library/ast.rst:1952 msgid "" "``defaults`` is a list of default values for arguments that can be passed " "positionally. If there are fewer defaults, they correspond to the last n " "arguments." msgstr "" "``defaults`` é uma lista de valores padrão para argumentos que podem ser " -"passados ​​posicionalmente. Se houver menos padrões, eles corresponderão aos " +"passados posicionalmente. Se houver menos padrões, eles corresponderão aos " "últimos n argumentos." -#: ../../library/ast.rst:1922 +#: ../../library/ast.rst:1959 msgid "" "A single argument in a list. ``arg`` is a raw string of the argument name; " "``annotation`` is its annotation, such as a :class:`Name` node." @@ -1325,17 +3769,105 @@ msgstr "" "Um único argumento em uma lista. ``arg`` é uma string bruta do nome do " "argumento; ``annotation`` é sua anotação, como um nó :class:`Name`." -#: ../../library/ast.rst:1927 +#: ../../library/ast.rst:1964 msgid "" "``type_comment`` is an optional string with the type annotation as a comment" msgstr "" "``type_comment`` é uma string opcional com a anotação de tipo como comentário" -#: ../../library/ast.rst:1969 +#: ../../library/ast.rst:1966 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... @decorator1\n" +"... @decorator2\n" +"... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return " +"annotation':\n" +"... pass\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" FunctionDef(\n" +" name='f',\n" +" args=arguments(\n" +" args=[\n" +" arg(\n" +" arg='a',\n" +" annotation=Constant(value='annotation')),\n" +" arg(arg='b'),\n" +" arg(arg='c')],\n" +" vararg=arg(arg='d'),\n" +" kwonlyargs=[\n" +" arg(arg='e'),\n" +" arg(arg='f')],\n" +" kw_defaults=[\n" +" None,\n" +" Constant(value=3)],\n" +" kwarg=arg(arg='g'),\n" +" defaults=[\n" +" Constant(value=1),\n" +" Constant(value=2)]),\n" +" body=[\n" +" Pass()],\n" +" decorator_list=[\n" +" Name(id='decorator1', ctx=Load()),\n" +" Name(id='decorator2', ctx=Load())],\n" +" returns=Constant(value='return annotation'))])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... @decorator1\n" +"... @decorator2\n" +"... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return " +"annotation':\n" +"... pass\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" FunctionDef(\n" +" name='f',\n" +" args=arguments(\n" +" args=[\n" +" arg(\n" +" arg='a',\n" +" annotation=Constant(value='annotation')),\n" +" arg(arg='b'),\n" +" arg(arg='c')],\n" +" vararg=arg(arg='d'),\n" +" kwonlyargs=[\n" +" arg(arg='e'),\n" +" arg(arg='f')],\n" +" kw_defaults=[\n" +" None,\n" +" Constant(value=3)],\n" +" kwarg=arg(arg='g'),\n" +" defaults=[\n" +" Constant(value=1),\n" +" Constant(value=2)]),\n" +" body=[\n" +" Pass()],\n" +" decorator_list=[\n" +" Name(id='decorator1', ctx=Load()),\n" +" Name(id='decorator2', ctx=Load())],\n" +" returns=Constant(value='return annotation'))])" + +#: ../../library/ast.rst:2006 msgid "A ``return`` statement." msgstr "Uma instrução ``return``." -#: ../../library/ast.rst:1983 +#: ../../library/ast.rst:2008 +msgid "" +">>> print(ast.dump(ast.parse('return 4'), indent=4))\n" +"Module(\n" +" body=[\n" +" Return(\n" +" value=Constant(value=4))])" +msgstr "" +">>> print(ast.dump(ast.parse('return 4'), indent=4))\n" +"Module(\n" +" body=[\n" +" Return(\n" +" value=Constant(value=4))])" + +#: ../../library/ast.rst:2020 msgid "" "A ``yield`` or ``yield from`` expression. Because these are expressions, " "they must be wrapped in an :class:`Expr` node if the value sent back is not " @@ -1345,37 +3877,105 @@ msgstr "" "ser agrupadas em um nó :class:`Expr` se o valor enviado de volta não for " "usado." -#: ../../library/ast.rst:2006 +#: ../../library/ast.rst:2023 +msgid "" +">>> print(ast.dump(ast.parse('yield x'), indent=4))\n" +"Module(\n" +" body=[\n" +" Expr(\n" +" value=Yield(\n" +" value=Name(id='x', ctx=Load())))])\n" +"\n" +">>> print(ast.dump(ast.parse('yield from x'), indent=4))\n" +"Module(\n" +" body=[\n" +" Expr(\n" +" value=YieldFrom(\n" +" value=Name(id='x', ctx=Load())))])" +msgstr "" +">>> print(ast.dump(ast.parse('yield x'), indent=4))\n" +"Module(\n" +" body=[\n" +" Expr(\n" +" value=Yield(\n" +" value=Name(id='x', ctx=Load())))])\n" +"\n" +">>> print(ast.dump(ast.parse('yield from x'), indent=4))\n" +"Module(\n" +" body=[\n" +" Expr(\n" +" value=YieldFrom(\n" +" value=Name(id='x', ctx=Load())))])" + +#: ../../library/ast.rst:2043 msgid "" "``global`` and ``nonlocal`` statements. ``names`` is a list of raw strings." msgstr "" "Instruções ``global`` e ``nonlocal``. ``names`` é uma lista de strings " "brutas." -#: ../../library/ast.rst:2031 +#: ../../library/ast.rst:2045 +msgid "" +">>> print(ast.dump(ast.parse('global x,y,z'), indent=4))\n" +"Module(\n" +" body=[\n" +" Global(\n" +" names=[\n" +" 'x',\n" +" 'y',\n" +" 'z'])])\n" +"\n" +">>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4))\n" +"Module(\n" +" body=[\n" +" Nonlocal(\n" +" names=[\n" +" 'x',\n" +" 'y',\n" +" 'z'])])" +msgstr "" +">>> print(ast.dump(ast.parse('global x,y,z'), indent=4))\n" +"Module(\n" +" body=[\n" +" Global(\n" +" names=[\n" +" 'x',\n" +" 'y',\n" +" 'z'])])\n" +"\n" +">>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4))\n" +"Module(\n" +" body=[\n" +" Nonlocal(\n" +" names=[\n" +" 'x',\n" +" 'y',\n" +" 'z'])])" + +#: ../../library/ast.rst:2068 msgid "A class definition." msgstr "Uma definição de classe" -#: ../../library/ast.rst:2033 +#: ../../library/ast.rst:2070 msgid "``name`` is a raw string for the class name" msgstr "``name`` é uma string bruta para o nome da classe" -#: ../../library/ast.rst:2034 +#: ../../library/ast.rst:2071 msgid "``bases`` is a list of nodes for explicitly specified base classes." msgstr "" "``bases`` é uma lista de nós para classes base especificadas explicitamente." -#: ../../library/ast.rst:2035 +#: ../../library/ast.rst:2072 msgid "" "``keywords`` is a list of :class:`.keyword` nodes, principally for " -"'metaclass'. Other keywords will be passed to the metaclass, as per " -"`PEP-3115 `_." +"'metaclass'. Other keywords will be passed to the metaclass, as per :pep:" +"`3115`." msgstr "" "``keywords`` é uma lista de nós :class:`.keyword`, principalmente para " "'metaclass'. Outras argumentos nomeados serão passadas para a metaclasse, " -"conforme `PEP-3115 `_." +"conforme a :pep:`3115`." -#: ../../library/ast.rst:2038 +#: ../../library/ast.rst:2074 msgid "" "``body`` is a list of nodes representing the code within the class " "definition." @@ -1383,15 +3983,63 @@ msgstr "" "``body`` é uma lista de nós que representam o código dentro da definição de " "classe." -#: ../../library/ast.rst:2040 +#: ../../library/ast.rst:2076 msgid "``decorator_list`` is a list of nodes, as in :class:`FunctionDef`." msgstr "``decorator_list`` é uma lista de nós, como em :class:`FunctionDef`." -#: ../../library/ast.rst:2072 +#: ../../library/ast.rst:2079 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... @decorator1\n" +"... @decorator2\n" +"... class Foo(base1, base2, metaclass=meta):\n" +"... pass\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" ClassDef(\n" +" name='Foo',\n" +" bases=[\n" +" Name(id='base1', ctx=Load()),\n" +" Name(id='base2', ctx=Load())],\n" +" keywords=[\n" +" keyword(\n" +" arg='metaclass',\n" +" value=Name(id='meta', ctx=Load()))],\n" +" body=[\n" +" Pass()],\n" +" decorator_list=[\n" +" Name(id='decorator1', ctx=Load()),\n" +" Name(id='decorator2', ctx=Load())])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... @decorator1\n" +"... @decorator2\n" +"... class Foo(base1, base2, metaclass=meta):\n" +"... pass\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" ClassDef(\n" +" name='Foo',\n" +" bases=[\n" +" Name(id='base1', ctx=Load()),\n" +" Name(id='base2', ctx=Load())],\n" +" keywords=[\n" +" keyword(\n" +" arg='metaclass',\n" +" value=Name(id='meta', ctx=Load()))],\n" +" body=[\n" +" Pass()],\n" +" decorator_list=[\n" +" Name(id='decorator1', ctx=Load()),\n" +" Name(id='decorator2', ctx=Load())])])" + +#: ../../library/ast.rst:2108 msgid "Async and await" msgstr "Async e await" -#: ../../library/ast.rst:2076 +#: ../../library/ast.rst:2112 msgid "" "An ``async def`` function definition. Has the same fields as :class:" "`FunctionDef`." @@ -1399,7 +4047,7 @@ msgstr "" "Uma definição de função ``async def``. Possui os mesmos campos que :class:" "`FunctionDef`." -#: ../../library/ast.rst:2085 +#: ../../library/ast.rst:2121 msgid "" "An ``await`` expression. ``value`` is what it waits for. Only valid in the " "body of an :class:`AsyncFunctionDef`." @@ -1407,7 +4055,39 @@ msgstr "" "Uma expressão ``await``. ``value`` é o que ela espera. Válido apenas no " "corpo de um :class:`AsyncFunctionDef`." -#: ../../library/ast.rst:2109 +#: ../../library/ast.rst:2124 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... async def f():\n" +"... await other_func()\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" AsyncFunctionDef(\n" +" name='f',\n" +" args=arguments(),\n" +" body=[\n" +" Expr(\n" +" value=Await(\n" +" value=Call(\n" +" func=Name(id='other_func', ctx=Load()))))])])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... async def f():\n" +"... await other_func()\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" AsyncFunctionDef(\n" +" name='f',\n" +" args=arguments(),\n" +" body=[\n" +" Expr(\n" +" value=Await(\n" +" value=Call(\n" +" func=Name(id='other_func', ctx=Load()))))])])" + +#: ../../library/ast.rst:2145 msgid "" "``async for`` loops and ``async with`` context managers. They have the same " "fields as :class:`For` and :class:`With`, respectively. Only valid in the " @@ -1417,7 +4097,7 @@ msgstr "" "mesmos campos que :class:`For` e :class:`With`, respectivamente. Válido " "apenas no corpo de :class:`AsyncFunctionDef`." -#: ../../library/ast.rst:2114 +#: ../../library/ast.rst:2150 msgid "" "When a string is parsed by :func:`ast.parse`, operator nodes (subclasses of :" "class:`ast.operator`, :class:`ast.unaryop`, :class:`ast.cmpop`, :class:`ast." @@ -1431,11 +4111,11 @@ msgstr "" "serão singletons. As alterações em um serão refletidas em todas as outras " "ocorrências do mesmo valor (por exemplo, :class:`ast.Add`)." -#: ../../library/ast.rst:2122 +#: ../../library/ast.rst:2158 msgid ":mod:`ast` Helpers" msgstr "Auxiliares de :mod:`ast`" -#: ../../library/ast.rst:2124 +#: ../../library/ast.rst:2160 msgid "" "Apart from the node classes, the :mod:`ast` module defines these utility " "functions and classes for traversing abstract syntax trees:" @@ -1443,7 +4123,7 @@ msgstr "" "Além das classes de nós, o módulo :mod:`ast` define essas funções e classes " "utilitárias para percorrer árvores de sintaxe abstrata:" -#: ../../library/ast.rst:2129 +#: ../../library/ast.rst:2165 msgid "" "Parse the source into an AST node. Equivalent to ``compile(source, " "filename, mode, flags=FLAGS_VALUE, optimize=optimize)``, where " @@ -1455,12 +4135,12 @@ msgstr "" "PyCF_ONLY_AST`` se ``optimize <= 0`` e ``ast.PyCF_OPTIMIZED_AST`` caso " "contrário." -#: ../../library/ast.rst:2134 +#: ../../library/ast.rst:2170 msgid "" "If ``type_comments=True`` is given, the parser is modified to check and " "return type comments as specified by :pep:`484` and :pep:`526`. This is " "equivalent to adding :data:`ast.PyCF_TYPE_COMMENTS` to the flags passed to :" -"func:`compile()`. This will report syntax errors for misplaced type " +"func:`compile`. This will report syntax errors for misplaced type " "comments. Without this flag, type comments will be ignored, and the " "``type_comment`` field on selected AST nodes will always be ``None``. In " "addition, the locations of ``# type: ignore`` comments will be returned as " @@ -1470,7 +4150,7 @@ msgstr "" "Se ``type_comments=True`` é fornecido, o analisador é modificado para " "verificar e retornar comentários do tipo, conforme especificado por :pep:" "`484` e :pep:`526`. Isso é equivalente a adicionar :data:`ast." -"PyCF_TYPE_COMMENTS` aos sinalizadores passados para :func:`compile()`. Isso " +"PyCF_TYPE_COMMENTS` aos sinalizadores passados para :func:`compile`. Isso " "relatará erros de sintaxe para comentários do tipo extraviado. Sem esse " "sinalizador, os comentários do tipo serão ignorados e o campo " "``type_comment`` nos nós AST selecionados sempre será ``None``. Além disso, " @@ -1478,7 +4158,7 @@ msgstr "" "atributo ``type_ignores`` de :class:`Module` (caso contrário, é sempre uma " "lista vazia)." -#: ../../library/ast.rst:2144 +#: ../../library/ast.rst:2180 msgid "" "In addition, if ``mode`` is ``'func_type'``, the input syntax is modified to " "correspond to :pep:`484` \"signature type comments\", e.g. ``(str, int) -> " @@ -1488,7 +4168,7 @@ msgstr "" "modificada para corresponder a \"comentários de tipo de assinatura\" de :pep:" "`484`, por exemplo, ``(str, int) -> List[str]``." -#: ../../library/ast.rst:2148 +#: ../../library/ast.rst:2184 msgid "" "Setting ``feature_version`` to a tuple ``(major, minor)`` will result in a " "\"best-effort\" attempt to parse using that Python version's grammar. For " @@ -1510,13 +4190,13 @@ msgstr "" "garantia de que a análise (ou sucesso da análise) seja a mesma que quando " "executada na versão Python correspondente a ``feature_version``." -#: ../../library/ast.rst:2158 +#: ../../library/ast.rst:2194 msgid "" "If source contains a null character (``\\0``), :exc:`ValueError` is raised." msgstr "" "Se a fonte contém um caractere nulo (``\\0``), :exc:`ValueError` é levantada." -#: ../../library/ast.rst:2161 +#: ../../library/ast.rst:2197 msgid "" "Note that successfully parsing source code into an AST object doesn't " "guarantee that the source code provided is valid Python code that can be " @@ -1532,7 +4212,7 @@ msgstr "" "uma instrução return, mas não pode ser compilado sozinho (precisa estar " "dentro de um nó de função)." -#: ../../library/ast.rst:2168 +#: ../../library/ast.rst:2204 msgid "" "In particular, :func:`ast.parse` won't do any scoping checks, which the " "compilation step does." @@ -1540,7 +4220,7 @@ msgstr "" "Em particular, :func:`ast.parse` não fará nenhuma verificação de escopo, o " "que a etapa de compilação faz." -#: ../../library/ast.rst:2172 +#: ../../library/ast.rst:2208 msgid "" "It is possible to crash the Python interpreter with a sufficiently large/" "complex string due to stack depth limitations in Python's AST compiler." @@ -1549,12 +4229,12 @@ msgstr "" "grande/complexa devido às limitações de profundidade da pilha no compilador " "de AST do Python." -#: ../../library/ast.rst:2176 +#: ../../library/ast.rst:2212 msgid "Added ``type_comments``, ``mode='func_type'`` and ``feature_version``." msgstr "" "Adicionado ``type_comments``, ``mode='func_type'`` e ``feature_version``." -#: ../../library/ast.rst:2179 +#: ../../library/ast.rst:2215 msgid "" "The minimum supported version for ``feature_version`` is now ``(3, 7)``. The " "``optimize`` argument was added." @@ -1562,7 +4242,7 @@ msgstr "" "A versão mínima suportada para ``feature_version`` agora é ``(3, 7)``. O " "argumento ``optimize`` foi adicionado." -#: ../../library/ast.rst:2186 +#: ../../library/ast.rst:2222 msgid "" "Unparse an :class:`ast.AST` object and generate a string with code that " "would produce an equivalent :class:`ast.AST` object if parsed back with :" @@ -1572,7 +4252,7 @@ msgstr "" "que produziria um objeto :class:`ast.AST` equivalente se analisado novamente " "com :func:`ast.parse`." -#: ../../library/ast.rst:2191 +#: ../../library/ast.rst:2227 msgid "" "The produced code string will not necessarily be equal to the original code " "that generated the :class:`ast.AST` object (without any compiler " @@ -1582,7 +4262,7 @@ msgstr "" "original que gerou o objeto :class:`ast.AST` (sem quaisquer otimizações do " "compilador, como tuplas/frozensets constantes)." -#: ../../library/ast.rst:2196 +#: ../../library/ast.rst:2232 msgid "" "Trying to unparse a highly complex expression would result with :exc:" "`RecursionError`." @@ -1590,7 +4270,7 @@ msgstr "" "Tentar desfazer análise de uma expressão altamente complexa resultaria em :" "exc:`RecursionError`." -#: ../../library/ast.rst:2204 +#: ../../library/ast.rst:2240 msgid "" "Evaluate an expression node or a string containing only a Python literal or " "container display. The string or node provided may only consist of the " @@ -1602,7 +4282,7 @@ msgstr "" "nas seguintes estruturas literais Python: strings, bytes, números, tuplas, " "listas, dicionários, conjuntos, booleanos, ``None`` e ``Ellipsis``." -#: ../../library/ast.rst:2209 +#: ../../library/ast.rst:2245 msgid "" "This can be used for evaluating strings containing Python values without the " "need to parse the values oneself. It is not capable of evaluating " @@ -1613,7 +4293,7 @@ msgstr "" "expressões arbitrariamente complexas, por exemplo, envolvendo operadores ou " "indexação." -#: ../../library/ast.rst:2214 +#: ../../library/ast.rst:2250 msgid "" "This function had been documented as \"safe\" in the past without defining " "what that meant. That was misleading. This is specifically designed not to " @@ -1634,7 +4314,7 @@ msgstr "" "CPU em algumas entradas. Portanto, não é recomendado chamá-la em dados não " "confiáveis." -#: ../../library/ast.rst:2224 +#: ../../library/ast.rst:2260 msgid "" "It is possible to crash the Python interpreter due to stack depth " "limitations in Python's AST compiler." @@ -1642,7 +4322,7 @@ msgstr "" "É possível travar o interpretador Python devido às limitações de " "profundidade da pilha no compilador AST do Python." -#: ../../library/ast.rst:2227 +#: ../../library/ast.rst:2263 msgid "" "It can raise :exc:`ValueError`, :exc:`TypeError`, :exc:`SyntaxError`, :exc:" "`MemoryError` and :exc:`RecursionError` depending on the malformed input." @@ -1650,21 +4330,21 @@ msgstr "" "Pode levantar :exc:`ValueError`, :exc:`TypeError`, :exc:`SyntaxError`, :exc:" "`MemoryError` e :exc:`RecursionError` dependendo da entrada malformada." -#: ../../library/ast.rst:2231 +#: ../../library/ast.rst:2267 msgid "Now allows bytes and set literals." msgstr "Agora permite bytes e literais de conjuntos." -#: ../../library/ast.rst:2234 +#: ../../library/ast.rst:2270 msgid "Now supports creating empty sets with ``'set()'``." msgstr "Agora oferece suporte à criação de conjuntos vazios com ``'set()'``." -#: ../../library/ast.rst:2237 +#: ../../library/ast.rst:2273 msgid "For string inputs, leading spaces and tabs are now stripped." msgstr "" "Para entradas de string, os espaços iniciais e tabulações agora são " "removidos." -#: ../../library/ast.rst:2243 +#: ../../library/ast.rst:2279 msgid "" "Return the docstring of the given *node* (which must be a :class:" "`FunctionDef`, :class:`AsyncFunctionDef`, :class:`ClassDef`, or :class:" @@ -1676,11 +4356,11 @@ msgstr "" "`Module`) ou ``None`` se não tiver uma docstring. Se *clean* for verdadeiro, " "limpa o recuo da docstring com :func:`inspect.cleandoc`." -#: ../../library/ast.rst:2249 +#: ../../library/ast.rst:2285 msgid ":class:`AsyncFunctionDef` is now supported." msgstr "Não há suporte a :class:`AsyncFunctionDef`." -#: ../../library/ast.rst:2255 +#: ../../library/ast.rst:2291 msgid "" "Get source code segment of the *source* that generated *node*. If some " "location information (:attr:`~ast.AST.lineno`, :attr:`~ast.AST.end_lineno`, :" @@ -1692,7 +4372,7 @@ msgstr "" "end_lineno`, :attr:`~ast.AST.col_offset` ou :attr:`~ast.AST.end_col_offset`) " "está faltando, retorna ``None``." -#: ../../library/ast.rst:2259 +#: ../../library/ast.rst:2295 msgid "" "If *padded* is ``True``, the first line of a multi-line statement will be " "padded with spaces to match its original position." @@ -1700,7 +4380,7 @@ msgstr "" "Se *padded* for ``True``, a primeira linha de uma instrução multilinha será " "preenchida com espaços para corresponder à sua posição original." -#: ../../library/ast.rst:2267 +#: ../../library/ast.rst:2303 msgid "" "When you compile a node tree with :func:`compile`, the compiler expects :" "attr:`~ast.AST.lineno` and :attr:`~ast.AST.col_offset` attributes for every " @@ -1716,7 +4396,7 @@ msgstr "" "definidos, definindo-os para os valores do nó pai. Ele funciona " "recursivamente a partir do *node*." -#: ../../library/ast.rst:2276 +#: ../../library/ast.rst:2312 msgid "" "Increment the line number and end line number of each node in the tree " "starting at *node* by *n*. This is useful to \"move code\" to a different " @@ -1726,7 +4406,7 @@ msgstr "" "começando em *node* em *n*. Isso é útil para \"mover código\" para um local " "diferente em um arquivo." -#: ../../library/ast.rst:2283 +#: ../../library/ast.rst:2319 msgid "" "Copy source location (:attr:`~ast.AST.lineno`, :attr:`~ast.AST.col_offset`, :" "attr:`~ast.AST.end_lineno`, and :attr:`~ast.AST.end_col_offset`) from " @@ -1736,7 +4416,7 @@ msgstr "" "col_offset`, :attr:`~ast.AST.end_lineno` e :attr:`~ast.AST.end_col_offset`) " "de *old_node* para *new_node* se possível e, então, retorna *new_node*." -#: ../../library/ast.rst:2290 +#: ../../library/ast.rst:2326 msgid "" "Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` " "that is present on *node*." @@ -1744,7 +4424,7 @@ msgstr "" "Produz uma tupla de ``(fieldname, value)`` para cada campo em ``node." "_fields`` que esteja presente em *node*." -#: ../../library/ast.rst:2296 +#: ../../library/ast.rst:2332 msgid "" "Yield all direct child nodes of *node*, that is, all fields that are nodes " "and all items of fields that are lists of nodes." @@ -1752,7 +4432,7 @@ msgstr "" "Produz todos os nós filhos diretos de *node*, ou seja, todos os campos que " "são nós e todos os itens de campos que são listas de nós." -#: ../../library/ast.rst:2302 +#: ../../library/ast.rst:2338 msgid "" "Recursively yield all descendant nodes in the tree starting at *node* " "(including *node* itself), in no specified order. This is useful if you " @@ -1763,7 +4443,7 @@ msgstr "" "útil se você quiser apenas modificar nós no lugar e não se importar com o " "contexto." -#: ../../library/ast.rst:2309 +#: ../../library/ast.rst:2345 msgid "" "A node visitor base class that walks the abstract syntax tree and calls a " "visitor function for every node found. This function may return a value " @@ -1773,7 +4453,7 @@ msgstr "" "e chama uma função de visitante para cada nó encontrado. Esta função pode " "retornar um valor que é encaminhado pelo método :meth:`visit`." -#: ../../library/ast.rst:2313 +#: ../../library/ast.rst:2349 msgid "" "This class is meant to be subclassed, with the subclass adding visitor " "methods." @@ -1781,7 +4461,7 @@ msgstr "" "Esta classe deve ser uma subclasse, com a subclasse adicionando métodos " "visitantes." -#: ../../library/ast.rst:2318 +#: ../../library/ast.rst:2354 msgid "" "Visit a node. The default implementation calls the method called :samp:" "`self.visit_{classname}` where *classname* is the name of the node class, " @@ -1791,11 +4471,11 @@ msgstr "" "visit_{nomedaclasse}` sendo *nomedaclasse* o nome da classe do nó, ou :meth:" "`generic_visit` se aquele método não existir." -#: ../../library/ast.rst:2324 +#: ../../library/ast.rst:2360 msgid "This visitor calls :meth:`visit` on all children of the node." msgstr "Este visitante chama :meth:`visit` em todos os filhos do nó." -#: ../../library/ast.rst:2326 +#: ../../library/ast.rst:2362 msgid "" "Note that child nodes of nodes that have a custom visitor method won't be " "visited unless the visitor calls :meth:`generic_visit` or visits them itself." @@ -1804,11 +4484,11 @@ msgstr "" "personalizado não serão visitados, a menos que o visitante chame :meth:" "`generic_visit` ou os visite por conta própria." -#: ../../library/ast.rst:2332 +#: ../../library/ast.rst:2368 msgid "Handles all constant nodes." msgstr "Manipula todos os nós constantes." -#: ../../library/ast.rst:2334 +#: ../../library/ast.rst:2370 msgid "" "Don't use the :class:`NodeVisitor` if you want to apply changes to nodes " "during traversal. For this a special visitor exists (:class:" @@ -1818,7 +4498,7 @@ msgstr "" "durante a travessia. Para isso existe um visitante especial (:class:" "`NodeTransformer`) que permite modificações." -#: ../../library/ast.rst:2340 +#: ../../library/ast.rst:2376 msgid "" "Methods :meth:`!visit_Num`, :meth:`!visit_Str`, :meth:`!visit_Bytes`, :meth:" "`!visit_NameConstant` and :meth:`!visit_Ellipsis` are deprecated now and " @@ -1830,7 +4510,7 @@ msgstr "" "descontinuados e não serão chamados em futuras versões do Python. Adicione " "um método :meth:`visit_Constant` para lidar com nós de constantes." -#: ../../library/ast.rst:2348 +#: ../../library/ast.rst:2384 msgid "" "A :class:`NodeVisitor` subclass that walks the abstract syntax tree and " "allows modification of nodes." @@ -1838,7 +4518,7 @@ msgstr "" "A subclasse :class:`NodeVisitor` que percorre a árvore de sintaxe abstrata e " "permite a modificação de nós." -#: ../../library/ast.rst:2351 +#: ../../library/ast.rst:2387 msgid "" "The :class:`NodeTransformer` will walk the AST and use the return value of " "the visitor methods to replace or remove the old node. If the return value " @@ -1852,7 +4532,7 @@ msgstr "" "caso contrário, ele será substituído pelo valor de retorno. O valor de " "retorno pode ser o nó original, caso em que não há substituição." -#: ../../library/ast.rst:2357 +#: ../../library/ast.rst:2393 msgid "" "Here is an example transformer that rewrites all occurrences of name lookups " "(``foo``) to ``data['foo']``::" @@ -1860,7 +4540,27 @@ msgstr "" "Aqui está um exemplo de transformador que rescreve todas as ocorrências de " "procuras por nome (``foo``) para ``data['foo']``::" -#: ../../library/ast.rst:2369 +#: ../../library/ast.rst:2396 +msgid "" +"class RewriteName(NodeTransformer):\n" +"\n" +" def visit_Name(self, node):\n" +" return Subscript(\n" +" value=Name(id='data', ctx=Load()),\n" +" slice=Constant(value=node.id),\n" +" ctx=node.ctx\n" +" )" +msgstr "" +"class RewriteName(NodeTransformer):\n" +"\n" +" def visit_Name(self, node):\n" +" return Subscript(\n" +" value=Name(id='data', ctx=Load()),\n" +" slice=Constant(value=node.id),\n" +" ctx=node.ctx\n" +" )" + +#: ../../library/ast.rst:2405 msgid "" "Keep in mind that if the node you're operating on has child nodes you must " "either transform the child nodes yourself or call the :meth:`~ast." @@ -1870,7 +4570,7 @@ msgstr "" "deve transformar os nós filhos por conta própria ou chamar o método :meth:" "`~ast.NodeVisitor.generic_visit` para o nó primeiro." -#: ../../library/ast.rst:2373 +#: ../../library/ast.rst:2409 msgid "" "For nodes that were part of a collection of statements (that applies to all " "statement nodes), the visitor may also return a list of nodes rather than " @@ -1880,7 +4580,7 @@ msgstr "" "todos os nós de instrução), o visitante também pode retornar uma lista de " "nós em vez de apenas um único nó." -#: ../../library/ast.rst:2377 +#: ../../library/ast.rst:2413 msgid "" "If :class:`NodeTransformer` introduces new nodes (that weren't part of " "original tree) without giving them location information (such as :attr:`~ast." @@ -1892,11 +4592,23 @@ msgstr "" "AST.lineno`), :func:`fix_missing_locations` deve ser chamado com o novo " "subárvore para recalcular as informações de localização::" -#: ../../library/ast.rst:2385 +#: ../../library/ast.rst:2418 +msgid "" +"tree = ast.parse('foo', mode='eval')\n" +"new_tree = fix_missing_locations(RewriteName().visit(tree))" +msgstr "" +"tree = ast.parse('foo', mode='eval')\n" +"new_tree = fix_missing_locations(RewriteName().visit(tree))" + +#: ../../library/ast.rst:2421 msgid "Usually you use the transformer like this::" msgstr "Normalmente você usa o transformador assim::" -#: ../../library/ast.rst:2392 +#: ../../library/ast.rst:2423 +msgid "node = YourTransformer().visit(node)" +msgstr "node = YourTransformer().visit(node)" + +#: ../../library/ast.rst:2428 msgid "" "Return a formatted dump of the tree in *node*. This is mainly useful for " "debugging purposes. If *annotate_fields* is true (by default), the returned " @@ -1914,7 +4626,7 @@ msgstr "" "deslocamentos de coluna não são despejados por padrão. Se isso for desejado, " "*include_attributes* pode ser definido como verdadeiro." -#: ../../library/ast.rst:2400 +#: ../../library/ast.rst:2436 msgid "" "If *indent* is a non-negative integer or string, then the tree will be " "pretty-printed with that indent level. An indent level of 0, negative, or " @@ -1930,7 +4642,7 @@ msgstr "" "indentação terá alguns espaços por nível. Se *indent* for uma string (como " "``\"\\t\"``), essa string será usada para indentar cada nível." -#: ../../library/ast.rst:2407 +#: ../../library/ast.rst:2443 msgid "" "If *show_empty* is ``False`` (the default), empty lists and fields that are " "``None`` will be omitted from the output." @@ -1938,19 +4650,71 @@ msgstr "" "Se *show_empty* for ``False`` (o padrão), listas vazias e campos que forem " "``None`` serão omitidos da saída." -#: ../../library/ast.rst:2410 +#: ../../library/ast.rst:2446 msgid "Added the *indent* option." msgstr "Adicionada a opção *indent*." -#: ../../library/ast.rst:2413 +#: ../../library/ast.rst:2449 msgid "Added the *show_empty* option." msgstr "Adicionada a opção *show_empty*." -#: ../../library/ast.rst:2447 +#: ../../library/ast.rst:2452 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... async def f():\n" +"... await other_func()\n" +"... \"\"\"), indent=4, show_empty=True))\n" +"Module(\n" +" body=[\n" +" AsyncFunctionDef(\n" +" name='f',\n" +" args=arguments(\n" +" posonlyargs=[],\n" +" args=[],\n" +" kwonlyargs=[],\n" +" kw_defaults=[],\n" +" defaults=[]),\n" +" body=[\n" +" Expr(\n" +" value=Await(\n" +" value=Call(\n" +" func=Name(id='other_func', ctx=Load()),\n" +" args=[],\n" +" keywords=[])))],\n" +" decorator_list=[],\n" +" type_params=[])],\n" +" type_ignores=[])" +msgstr "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... async def f():\n" +"... await other_func()\n" +"... \"\"\"), indent=4, show_empty=True))\n" +"Module(\n" +" body=[\n" +" AsyncFunctionDef(\n" +" name='f',\n" +" args=arguments(\n" +" posonlyargs=[],\n" +" args=[],\n" +" kwonlyargs=[],\n" +" kw_defaults=[],\n" +" defaults=[]),\n" +" body=[\n" +" Expr(\n" +" value=Await(\n" +" value=Call(\n" +" func=Name(id='other_func', ctx=Load()),\n" +" args=[],\n" +" keywords=[])))],\n" +" decorator_list=[],\n" +" type_params=[])],\n" +" type_ignores=[])" + +#: ../../library/ast.rst:2483 msgid "Compiler Flags" msgstr "Sinalizadores do compilador" -#: ../../library/ast.rst:2449 +#: ../../library/ast.rst:2485 msgid "" "The following flags may be passed to :func:`compile` in order to change " "effects on the compilation of a program:" @@ -1958,7 +4722,7 @@ msgstr "" "Os seguintes sinalizadores podem ser passados para :func:`compile` para " "alterar os efeitos na compilação de um programa:" -#: ../../library/ast.rst:2454 +#: ../../library/ast.rst:2490 msgid "" "Enables support for top-level ``await``, ``async for``, ``async with`` and " "async comprehensions." @@ -1966,7 +4730,7 @@ msgstr "" "Habilita suporte para ``await``, ``async for``, ``async with`` e " "compreensões assíncronas de nível superior." -#: ../../library/ast.rst:2461 +#: ../../library/ast.rst:2497 msgid "" "Generates and returns an abstract syntax tree instead of returning a " "compiled code object." @@ -1974,7 +4738,7 @@ msgstr "" "Gera e retorna uma árvore de sintaxe abstrata em vez de retornar um objeto " "de código compilado." -#: ../../library/ast.rst:2466 +#: ../../library/ast.rst:2502 msgid "" "The returned AST is optimized according to the *optimize* argument in :func:" "`compile` or :func:`ast.parse`." @@ -1982,7 +4746,7 @@ msgstr "" "O AST retornado é otimizado de acordo com o argumento *optimize* em :func:" "`compile` ou :func:`ast.parse`." -#: ../../library/ast.rst:2473 +#: ../../library/ast.rst:2509 msgid "" "Enables support for :pep:`484` and :pep:`526` style type comments (``# type: " "``, ``# type: ignore ``)." @@ -1990,11 +4754,11 @@ msgstr "" "Habilita suporte para comentários do tipo :pep:`484` e :pep:`526` (``# type: " "``, ``# type: ignore ``)." -#: ../../library/ast.rst:2482 +#: ../../library/ast.rst:2518 msgid "Command-Line Usage" msgstr "Uso na linha de comando" -#: ../../library/ast.rst:2486 +#: ../../library/ast.rst:2522 msgid "" "The :mod:`ast` module can be executed as a script from the command line. It " "is as simple as:" @@ -2002,15 +4766,19 @@ msgstr "" "O módulo :mod:`ast` pode ser executado como um script na linha de comando. É " "tão simples quanto:" -#: ../../library/ast.rst:2493 +#: ../../library/ast.rst:2525 +msgid "python -m ast [-m ] [-a] [infile]" +msgstr "python -m ast [-m ] [-a] [infile]" + +#: ../../library/ast.rst:2529 msgid "The following options are accepted:" msgstr "As seguintes opções são aceitas:" -#: ../../library/ast.rst:2499 +#: ../../library/ast.rst:2535 msgid "Show the help message and exit." msgstr "Mostra a mensagem de ajuda e sai." -#: ../../library/ast.rst:2504 +#: ../../library/ast.rst:2540 msgid "" "Specify what kind of code must be compiled, like the *mode* argument in :" "func:`parse`." @@ -2018,19 +4786,19 @@ msgstr "" "Especifica que tipo de código deve ser compilado, como o argumento *mode* " "em :func:`parse`." -#: ../../library/ast.rst:2509 +#: ../../library/ast.rst:2545 msgid "Don't parse type comments." msgstr "Não analisa comentários de tipo." -#: ../../library/ast.rst:2513 +#: ../../library/ast.rst:2549 msgid "Include attributes such as line numbers and column offsets." msgstr "Inclui atributos como números de linha e deslocamentos de colunas." -#: ../../library/ast.rst:2518 +#: ../../library/ast.rst:2554 msgid "Indentation of nodes in AST (number of spaces)." msgstr "indentação de nós em AST (número de espaços)." -#: ../../library/ast.rst:2520 +#: ../../library/ast.rst:2556 msgid "" "If :file:`infile` is specified its contents are parsed to AST and dumped to " "stdout. Otherwise, the content is read from stdin." @@ -2038,7 +4806,7 @@ msgstr "" "Se :file:`infile` for especificado, seu conteúdo será analisado no AST e " "despejado no stdout. Caso contrário, o conteúdo será lido em stdin." -#: ../../library/ast.rst:2526 +#: ../../library/ast.rst:2562 msgid "" "`Green Tree Snakes `_, an external " "documentation resource, has good details on working with Python ASTs." @@ -2047,7 +4815,7 @@ msgstr "" "de documentação externo, possui bons detalhes sobre trabalhar com ASTs do " "Python." -#: ../../library/ast.rst:2529 +#: ../../library/ast.rst:2565 msgid "" "`ASTTokens `_ " "annotates Python ASTs with the positions of tokens and text in the source " @@ -2059,7 +4827,7 @@ msgstr "" "as gerou. Isso é útil para ferramentas que fazem transformações de código-" "fonte." -#: ../../library/ast.rst:2534 +#: ../../library/ast.rst:2570 msgid "" "`leoAst.py `_ unifies the token-based and parse-tree-based views of python programs " @@ -2069,7 +4837,7 @@ msgstr "" "py>`_ unifica as visualizações baseadas em token e em árvore de análise de " "programas python, inserindo links duas vias entre tokens e nós de ast." -#: ../../library/ast.rst:2539 +#: ../../library/ast.rst:2575 msgid "" "`LibCST `_ parses code as a Concrete Syntax " "Tree that looks like an ast tree and keeps all formatting details. It's " @@ -2080,7 +4848,7 @@ msgstr "" "detalhes de formatação. É útil para construir linters e aplicações de " "refatoração automatizada (codemod)." -#: ../../library/ast.rst:2544 +#: ../../library/ast.rst:2580 msgid "" "`Parso `_ is a Python parser that supports " "error recovery and round-trip parsing for different Python versions (in " diff --git a/library/asynchat.po b/library/asynchat.po new file mode 100644 index 000000000..aa83d6212 --- /dev/null +++ b/library/asynchat.po @@ -0,0 +1,51 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../library/asynchat.rst:2 +msgid ":mod:`!asynchat` --- Asynchronous socket command/response handler" +msgstr "" +":mod:`!asynchat` --- Manipulador de comando/resposta de socket assíncrono" + +#: ../../library/asynchat.rst:10 +msgid "" +"This module is no longer part of the Python standard library. It was :ref:" +"`removed in Python 3.12 ` after being deprecated in " +"Python 3.6. The removal was decided in :pep:`594`." +msgstr "" +"Este módulo não faz mais parte da biblioteca padrão do Python. Ele foi :ref:" +"`removido no Python 3.12 ` após ser descontinuado no " +"Python 3.6. A remoção foi decidida na :pep:`594`." + +#: ../../library/asynchat.rst:14 +msgid "Applications should use the :mod:`asyncio` module instead." +msgstr "As aplicações devem usar o módulo :mod:`asyncio` em vez disso." + +#: ../../library/asynchat.rst:16 +msgid "" +"The last version of Python that provided the :mod:`!asynchat` module was " +"`Python 3.11 `_." +msgstr "" +"A última versão do Python que forneceu o módulo :mod:`!asynchat` foi o " +"`Python 3.11 `_." diff --git a/library/asyncio-api-index.po b/library/asyncio-api-index.po index 55a2de7d9..29c7ce300 100644 --- a/library/asyncio-api-index.po +++ b/library/asyncio-api-index.po @@ -1,33 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Leticia Portella , 2021 -# Adorilson Bezerra , 2021 -# Vinicius Gubiani Ferreira , 2021 -# Hildeberto Abreu Magalhães , 2021 -# Leandro Cavalcante Damascena , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-07 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:54+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/asyncio-dev.po b/library/asyncio-dev.po index cdf622690..4c2b9b90b 100644 --- a/library/asyncio-dev.po +++ b/library/asyncio-dev.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Marco Rougeth , 2022 -# Rafael Fontenelle , 2022 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 00:54+0000\n" -"Last-Translator: Rafael Fontenelle , 2022\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -82,6 +79,10 @@ msgid "" "at startup of the application::" msgstr "" +#: ../../library/asyncio-dev.rst:40 +msgid "logging.basicConfig(level=logging.DEBUG)" +msgstr "" + #: ../../library/asyncio-dev.rst:42 msgid "" "configuring the :mod:`warnings` module to display :exc:`ResourceWarning` " @@ -95,19 +96,12 @@ msgstr "Quando o modo de depuração está habilitado:" #: ../../library/asyncio-dev.rst:49 msgid "" -"asyncio checks for :ref:`coroutines that were not awaited ` and logs them; this mitigates the \"forgotten await\" " -"pitfall." -msgstr "" - -#: ../../library/asyncio-dev.rst:53 -msgid "" "Many non-threadsafe asyncio APIs (such as :meth:`loop.call_soon` and :meth:" "`loop.call_at` methods) raise an exception if they are called from a wrong " "thread." msgstr "" -#: ../../library/asyncio-dev.rst:57 +#: ../../library/asyncio-dev.rst:53 msgid "" "The execution time of the I/O selector is logged if it takes too long to " "perform an I/O operation." @@ -115,7 +109,7 @@ msgstr "" "O tempo de execução de um seletor de E/S é registrado se demorar muito para " "executar a operação E/S." -#: ../../library/asyncio-dev.rst:60 +#: ../../library/asyncio-dev.rst:56 msgid "" "Callbacks taking longer than 100 milliseconds are logged. The :attr:`loop." "slow_callback_duration` attribute can be used to set the minimum execution " @@ -125,11 +119,11 @@ msgstr "" "O atributo :attr:`loop.slow_callback_duration` pode ser usado para definir a " "duração de execução mínima em segundos para se considerada \"devagar\"." -#: ../../library/asyncio-dev.rst:68 +#: ../../library/asyncio-dev.rst:64 msgid "Concurrency and Multithreading" msgstr "Concorrência e Múltiplas Threads" -#: ../../library/asyncio-dev.rst:70 +#: ../../library/asyncio-dev.rst:66 msgid "" "An event loop runs in a thread (typically the main thread) and executes all " "callbacks and Tasks in its thread. While a Task is running in the event " @@ -138,7 +132,7 @@ msgid "" "executes the next Task." msgstr "" -#: ../../library/asyncio-dev.rst:76 +#: ../../library/asyncio-dev.rst:72 msgid "" "To schedule a :term:`callback` from another OS thread, the :meth:`loop." "call_soon_threadsafe` method should be used. Example::" @@ -146,7 +140,11 @@ msgstr "" "Para agendar uma :term:`callback` de outra thread do SO, o método :meth:" "`loop.call_soon_threadsafe` deve ser usado. Exemplo::" -#: ../../library/asyncio-dev.rst:81 +#: ../../library/asyncio-dev.rst:75 +msgid "loop.call_soon_threadsafe(callback, *args)" +msgstr "" + +#: ../../library/asyncio-dev.rst:77 msgid "" "Almost all asyncio objects are not thread safe, which is typically not a " "problem unless there is code that works with them from outside of a Task or " @@ -154,18 +152,34 @@ msgid "" "API, the :meth:`loop.call_soon_threadsafe` method should be used, e.g.::" msgstr "" -#: ../../library/asyncio-dev.rst:89 +#: ../../library/asyncio-dev.rst:83 +msgid "loop.call_soon_threadsafe(fut.cancel)" +msgstr "" + +#: ../../library/asyncio-dev.rst:85 msgid "" "To schedule a coroutine object from a different OS thread, the :func:" "`run_coroutine_threadsafe` function should be used. It returns a :class:" "`concurrent.futures.Future` to access the result::" msgstr "" -#: ../../library/asyncio-dev.rst:102 +#: ../../library/asyncio-dev.rst:89 +msgid "" +"async def coro_func():\n" +" return await asyncio.sleep(1, 42)\n" +"\n" +"# Later in another OS thread:\n" +"\n" +"future = asyncio.run_coroutine_threadsafe(coro_func(), loop)\n" +"# Wait for the result:\n" +"result = future.result()" +msgstr "" + +#: ../../library/asyncio-dev.rst:98 msgid "To handle signals the event loop must be run in the main thread." msgstr "" -#: ../../library/asyncio-dev.rst:105 +#: ../../library/asyncio-dev.rst:101 msgid "" "The :meth:`loop.run_in_executor` method can be used with a :class:" "`concurrent.futures.ThreadPoolExecutor` to execute blocking code in a " @@ -173,7 +187,7 @@ msgid "" "in." msgstr "" -#: ../../library/asyncio-dev.rst:110 +#: ../../library/asyncio-dev.rst:106 msgid "" "There is currently no way to schedule coroutines or callbacks directly from " "a different process (such as one started with :mod:`multiprocessing`). The :" @@ -186,29 +200,29 @@ msgid "" "different process." msgstr "" -#: ../../library/asyncio-dev.rst:124 +#: ../../library/asyncio-dev.rst:120 msgid "Running Blocking Code" msgstr "Executando código bloqueante" -#: ../../library/asyncio-dev.rst:126 +#: ../../library/asyncio-dev.rst:122 msgid "" "Blocking (CPU-bound) code should not be called directly. For example, if a " "function performs a CPU-intensive calculation for 1 second, all concurrent " "asyncio Tasks and IO operations would be delayed by 1 second." msgstr "" -#: ../../library/asyncio-dev.rst:131 +#: ../../library/asyncio-dev.rst:127 msgid "" "An executor can be used to run a task in a different thread or even in a " "different process to avoid blocking the OS thread with the event loop. See " "the :meth:`loop.run_in_executor` method for more details." msgstr "" -#: ../../library/asyncio-dev.rst:140 +#: ../../library/asyncio-dev.rst:136 msgid "Logging" msgstr "Gerando logs" -#: ../../library/asyncio-dev.rst:142 +#: ../../library/asyncio-dev.rst:138 msgid "" "asyncio uses the :mod:`logging` module and all logging is performed via the " "``\"asyncio\"`` logger." @@ -216,49 +230,92 @@ msgstr "" "asyncio usa o módulo :mod:`logging` e todo registro é feito via o " "registrador ``\"asyncio\"``." -#: ../../library/asyncio-dev.rst:145 +#: ../../library/asyncio-dev.rst:141 msgid "" "The default log level is :py:const:`logging.INFO`, which can be easily " "adjusted::" msgstr "" -#: ../../library/asyncio-dev.rst:151 +#: ../../library/asyncio-dev.rst:144 +msgid "logging.getLogger(\"asyncio\").setLevel(logging.WARNING)" +msgstr "" + +#: ../../library/asyncio-dev.rst:147 msgid "" "Network logging can block the event loop. It is recommended to use a " "separate thread for handling logs or use non-blocking IO. For example, see :" "ref:`blocking-handlers`." msgstr "" -#: ../../library/asyncio-dev.rst:159 +#: ../../library/asyncio-dev.rst:155 msgid "Detect never-awaited coroutines" msgstr "" -#: ../../library/asyncio-dev.rst:161 +#: ../../library/asyncio-dev.rst:157 msgid "" "When a coroutine function is called, but not awaited (e.g. ``coro()`` " "instead of ``await coro()``) or the coroutine is not scheduled with :meth:" "`asyncio.create_task`, asyncio will emit a :exc:`RuntimeWarning`::" msgstr "" -#: ../../library/asyncio-dev.rst:176 ../../library/asyncio-dev.rst:221 +#: ../../library/asyncio-dev.rst:162 +msgid "" +"import asyncio\n" +"\n" +"async def test():\n" +" print(\"never scheduled\")\n" +"\n" +"async def main():\n" +" test()\n" +"\n" +"asyncio.run(main())" +msgstr "" + +#: ../../library/asyncio-dev.rst:172 ../../library/asyncio-dev.rst:217 msgid "Output::" msgstr "Saída::" -#: ../../library/asyncio-dev.rst:181 ../../library/asyncio-dev.rst:237 +#: ../../library/asyncio-dev.rst:174 +msgid "" +"test.py:7: RuntimeWarning: coroutine 'test' was never awaited\n" +" test()" +msgstr "" + +#: ../../library/asyncio-dev.rst:177 ../../library/asyncio-dev.rst:233 msgid "Output in debug mode::" msgstr "" -#: ../../library/asyncio-dev.rst:194 +#: ../../library/asyncio-dev.rst:179 +msgid "" +"test.py:7: RuntimeWarning: coroutine 'test' was never awaited\n" +"Coroutine created at (most recent call last)\n" +" File \"../t.py\", line 9, in \n" +" asyncio.run(main(), debug=True)\n" +"\n" +" < .. >\n" +"\n" +" File \"../t.py\", line 7, in main\n" +" test()\n" +" test()" +msgstr "" + +#: ../../library/asyncio-dev.rst:190 msgid "" "The usual fix is to either await the coroutine or call the :meth:`asyncio." "create_task` function::" msgstr "" -#: ../../library/asyncio-dev.rst:202 +#: ../../library/asyncio-dev.rst:193 +msgid "" +"async def main():\n" +" await test()" +msgstr "" + +#: ../../library/asyncio-dev.rst:198 msgid "Detect never-retrieved exceptions" msgstr "" -#: ../../library/asyncio-dev.rst:204 +#: ../../library/asyncio-dev.rst:200 msgid "" "If a :meth:`Future.set_exception` is called but the Future object is never " "awaited on, the exception would never be propagated to the user code. In " @@ -266,12 +323,59 @@ msgid "" "garbage collected." msgstr "" -#: ../../library/asyncio-dev.rst:209 +#: ../../library/asyncio-dev.rst:205 msgid "Example of an unhandled exception::" msgstr "Exemplo de uma exceção não tratada::" -#: ../../library/asyncio-dev.rst:232 +#: ../../library/asyncio-dev.rst:207 +msgid "" +"import asyncio\n" +"\n" +"async def bug():\n" +" raise Exception(\"not consumed\")\n" +"\n" +"async def main():\n" +" asyncio.create_task(bug())\n" +"\n" +"asyncio.run(main())" +msgstr "" + +#: ../../library/asyncio-dev.rst:219 +msgid "" +"Task exception was never retrieved\n" +"future: \n" +" exception=Exception('not consumed')>\n" +"\n" +"Traceback (most recent call last):\n" +" File \"test.py\", line 4, in bug\n" +" raise Exception(\"not consumed\")\n" +"Exception: not consumed" +msgstr "" + +#: ../../library/asyncio-dev.rst:228 msgid "" ":ref:`Enable the debug mode ` to get the traceback where " "the task was created::" msgstr "" + +#: ../../library/asyncio-dev.rst:231 +msgid "asyncio.run(main(), debug=True)" +msgstr "" + +#: ../../library/asyncio-dev.rst:235 +msgid "" +"Task exception was never retrieved\n" +"future: \n" +" exception=Exception('not consumed') created at asyncio/tasks.py:321>\n" +"\n" +"source_traceback: Object created at (most recent call last):\n" +" File \"../t.py\", line 9, in \n" +" asyncio.run(main(), debug=True)\n" +"\n" +"< .. >\n" +"\n" +"Traceback (most recent call last):\n" +" File \"../t.py\", line 4, in bug\n" +" raise Exception(\"not consumed\")\n" +"Exception: not consumed" +msgstr "" diff --git a/library/asyncio-eventloop.po b/library/asyncio-eventloop.po index 684b00d7a..c982166d9 100644 --- a/library/asyncio-eventloop.po +++ b/library/asyncio-eventloop.po @@ -1,34 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Humberto Rocha , 2021 -# Raphael Mendonça, 2021 -# Italo Penaforte , 2021 -# i17obot , 2021 -# Vinicius Gubiani Ferreira , 2021 -# Adorilson Bezerra , 2022 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:54+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -260,15 +251,11 @@ msgstr "Executa o laço de eventos até que :meth:`stop` seja chamado." #: ../../library/asyncio-eventloop.rst:129 msgid "" -"If :meth:`stop` is called before :meth:`run_forever()` is called, the loop " +"If :meth:`stop` is called before :meth:`run_forever` is called, the loop " "will poll the I/O selector once with a timeout of zero, run all callbacks " "scheduled in response to I/O events (and those that were already scheduled), " "and then exit." msgstr "" -"Se :meth:`stop` for chamado antes que :meth:`run_forever()` seja chamado, o " -"laço irá pesquisar o seletor de E/S uma vez com um tempo limite de zero, " -"executar todas as funções de retorno agendadas na resposta de eventos de E/S " -"(e aqueles que já estavam agendados), e então sair." #: ../../library/asyncio-eventloop.rst:134 msgid "" @@ -324,20 +311,15 @@ msgstr "" "Este método é idempotente e irreversível. Nenhum outro método deve ser " "chamado depois que o laço de eventos esteja fechado." -#: ../../library/asyncio-eventloop.rst:167 +#: ../../library/asyncio-eventloop.rst:168 msgid "" "Schedule all currently open :term:`asynchronous generator` objects to close " -"with an :meth:`~agen.aclose()` call. After calling this method, the event " +"with an :meth:`~agen.aclose` call. After calling this method, the event " "loop will issue a warning if a new asynchronous generator is iterated. This " "should be used to reliably finalize all scheduled asynchronous generators." msgstr "" -"Agenda todos os objetos :term:`geradores assíncronos ` atualmente abertos para serem fechados com uma chamada :meth:" -"`~agen.aclose()`. Após chamar este método, o laço de eventos emitirá um " -"aviso se um novo gerador assíncrono for iterado. Isso deve ser utilizado " -"para finalizar de forma confiável todos os geradores assíncronos agendados." -#: ../../library/asyncio-eventloop.rst:173 +#: ../../library/asyncio-eventloop.rst:174 msgid "" "Note that there is no need to call this function when :func:`asyncio.run` is " "used." @@ -345,13 +327,22 @@ msgstr "" "Perceba que não é necessário chamar esta função quando :func:`asyncio.run` " "for usado." -#: ../../library/asyncio-eventloop.rst:176 -#: ../../library/asyncio-eventloop.rst:1269 -#: ../../library/asyncio-eventloop.rst:1712 +#: ../../library/asyncio-eventloop.rst:177 +#: ../../library/asyncio-eventloop.rst:1320 +#: ../../library/asyncio-eventloop.rst:1769 msgid "Example::" msgstr "Exemplo::" -#: ../../library/asyncio-eventloop.rst:188 +#: ../../library/asyncio-eventloop.rst:179 +msgid "" +"try:\n" +" loop.run_forever()\n" +"finally:\n" +" loop.run_until_complete(loop.shutdown_asyncgens())\n" +" loop.close()" +msgstr "" + +#: ../../library/asyncio-eventloop.rst:190 msgid "" "Schedule the closure of the default executor and wait for it to join all of " "the threads in the :class:`~concurrent.futures.ThreadPoolExecutor`. Once " @@ -363,7 +354,7 @@ msgstr "" "método tenha sido chamado, usar o executor padrão com :meth:`loop." "run_in_executor` levantará um :exc:`RuntimeError`." -#: ../../library/asyncio-eventloop.rst:194 +#: ../../library/asyncio-eventloop.rst:196 msgid "" "The *timeout* parameter specifies the amount of time (in :class:`float` " "seconds) the executor will be given to finish joining. With the default, " @@ -373,7 +364,7 @@ msgstr "" "segundos) que o executor terá para terminar a junção. Com o padrão ``None``, " "o executor tem permissão para um período de tempo ilimitado." -#: ../../library/asyncio-eventloop.rst:199 +#: ../../library/asyncio-eventloop.rst:201 msgid "" "If the *timeout* is reached, a :exc:`RuntimeWarning` is emitted and the " "default executor is terminated without waiting for its threads to finish " @@ -383,21 +374,21 @@ msgstr "" "e o executor padrão será finalizado sem esperar que suas threads terminem a " "junção." -#: ../../library/asyncio-eventloop.rst:205 +#: ../../library/asyncio-eventloop.rst:207 msgid "" "Do not call this method when using :func:`asyncio.run`, as the latter " "handles default executor shutdown automatically." msgstr "" -#: ../../library/asyncio-eventloop.rst:210 +#: ../../library/asyncio-eventloop.rst:212 msgid "Added the *timeout* parameter." msgstr "" -#: ../../library/asyncio-eventloop.rst:214 +#: ../../library/asyncio-eventloop.rst:216 msgid "Scheduling callbacks" msgstr "Agendando funções de retorno" -#: ../../library/asyncio-eventloop.rst:218 +#: ../../library/asyncio-eventloop.rst:220 msgid "" "Schedule the *callback* :term:`callback` to be called with *args* arguments " "at the next iteration of the event loop." @@ -405,13 +396,13 @@ msgstr "" "Agenda a *função de retorno* :term:`callback` para ser chamada com " "argumentos *args* na próxima iteração do laço de eventos." -#: ../../library/asyncio-eventloop.rst:221 +#: ../../library/asyncio-eventloop.rst:223 msgid "" "Return an instance of :class:`asyncio.Handle`, which can be used later to " "cancel the callback." msgstr "" -#: ../../library/asyncio-eventloop.rst:224 +#: ../../library/asyncio-eventloop.rst:226 msgid "" "Callbacks are called in the order in which they are registered. Each " "callback will be called exactly once." @@ -419,25 +410,32 @@ msgstr "" "Funções de retorno são chamadas na ordem em que elas foram registradas. Cada " "função de retorno será chamada exatamente uma vez." -#: ../../library/asyncio-eventloop.rst:227 +#: ../../library/asyncio-eventloop.rst:229 msgid "" "The optional keyword-only *context* argument specifies a custom :class:" "`contextvars.Context` for the *callback* to run in. Callbacks use the " "current context when no *context* is provided." msgstr "" -#: ../../library/asyncio-eventloop.rst:231 +#: ../../library/asyncio-eventloop.rst:233 msgid "Unlike :meth:`call_soon_threadsafe`, this method is not thread-safe." msgstr "" -#: ../../library/asyncio-eventloop.rst:235 +#: ../../library/asyncio-eventloop.rst:237 msgid "" "A thread-safe variant of :meth:`call_soon`. When scheduling callbacks from " "another thread, this function *must* be used, since :meth:`call_soon` is not " "thread-safe." msgstr "" -#: ../../library/asyncio-eventloop.rst:239 +#: ../../library/asyncio-eventloop.rst:241 +msgid "" +"This function is safe to be called from a reentrant context or signal " +"handler, however, it is not safe or fruitful to use the returned handle in " +"such contexts." +msgstr "" + +#: ../../library/asyncio-eventloop.rst:244 msgid "" "Raises :exc:`RuntimeError` if called on a loop that's been closed. This can " "happen on a secondary thread when the main application is shutting down." @@ -446,7 +444,7 @@ msgstr "" "pode acontecer em uma thread secundária quando a aplicação principal estiver " "desligando." -#: ../../library/asyncio-eventloop.rst:243 +#: ../../library/asyncio-eventloop.rst:248 msgid "" "See the :ref:`concurrency and multithreading ` " "section of the documentation." @@ -454,9 +452,9 @@ msgstr "" "Veja a seção :ref:`concorrência e multithreading ` " "da documentação." -#: ../../library/asyncio-eventloop.rst:246 -#: ../../library/asyncio-eventloop.rst:296 -#: ../../library/asyncio-eventloop.rst:316 +#: ../../library/asyncio-eventloop.rst:251 +#: ../../library/asyncio-eventloop.rst:301 +#: ../../library/asyncio-eventloop.rst:321 msgid "" "The *context* keyword-only parameter was added. See :pep:`567` for more " "details." @@ -464,7 +462,7 @@ msgstr "" "O parâmetro somente-nomeado *context* foi adicionado. Veja :pep:`567` para " "mais detalhes." -#: ../../library/asyncio-eventloop.rst:254 +#: ../../library/asyncio-eventloop.rst:259 msgid "" "Most :mod:`asyncio` scheduling functions don't allow passing keyword " "arguments. To do that, use :func:`functools.partial`::" @@ -472,7 +470,14 @@ msgstr "" "Maior parte das funções de agendamento :mod:`asyncio` não permite passar " "argumentos nomeados. Para fazer isso, use :func:`functools.partial`::" -#: ../../library/asyncio-eventloop.rst:261 +#: ../../library/asyncio-eventloop.rst:262 +msgid "" +"# will schedule \"print(\"Hello\", flush=True)\"\n" +"loop.call_soon(\n" +" functools.partial(print, \"Hello\", flush=True))" +msgstr "" + +#: ../../library/asyncio-eventloop.rst:266 msgid "" "Using partial objects is usually more convenient than using lambdas, as " "asyncio can render partial objects better in debug and error messages." @@ -481,11 +486,11 @@ msgstr "" "asyncio pode renderizar objetos parciais melhor durante debug e mensagens de " "erro." -#: ../../library/asyncio-eventloop.rst:269 +#: ../../library/asyncio-eventloop.rst:274 msgid "Scheduling delayed callbacks" msgstr "Agendando funções de retorno atrasadas" -#: ../../library/asyncio-eventloop.rst:271 +#: ../../library/asyncio-eventloop.rst:276 msgid "" "Event loop provides mechanisms to schedule callback functions to be called " "at some point in the future. Event loop uses monotonic clocks to track time." @@ -494,7 +499,7 @@ msgstr "" "serem chamadas em algum ponto no futuro. Laço de eventos usa relógios " "monotônico para acompanhar o tempo." -#: ../../library/asyncio-eventloop.rst:278 +#: ../../library/asyncio-eventloop.rst:283 msgid "" "Schedule *callback* to be called after the given *delay* number of seconds " "(can be either an int or a float)." @@ -502,8 +507,8 @@ msgstr "" "Agenda *callback* para ser chamada após o *delay* número de segundos " "fornecido (pode ser um inteiro ou um ponto flutuante)." -#: ../../library/asyncio-eventloop.rst:281 -#: ../../library/asyncio-eventloop.rst:313 +#: ../../library/asyncio-eventloop.rst:286 +#: ../../library/asyncio-eventloop.rst:318 msgid "" "An instance of :class:`asyncio.TimerHandle` is returned which can be used to " "cancel the callback." @@ -511,7 +516,7 @@ msgstr "" "Uma instância de :class:`asyncio.TimerHandle` é retornada, a qual pode ser " "usada para cancelar a função de retorno." -#: ../../library/asyncio-eventloop.rst:284 +#: ../../library/asyncio-eventloop.rst:289 msgid "" "*callback* will be called exactly once. If two callbacks are scheduled for " "exactly the same time, the order in which they are called is undefined." @@ -520,7 +525,7 @@ msgstr "" "agendadas para exatamente o mesmo tempo, a ordem na qual elas são chamadas é " "indefinida." -#: ../../library/asyncio-eventloop.rst:288 +#: ../../library/asyncio-eventloop.rst:293 msgid "" "The optional positional *args* will be passed to the callback when it is " "called. If you want the callback to be called with keyword arguments use :" @@ -530,7 +535,7 @@ msgstr "" "ela for chamada. Se você quiser que a função de retorno seja chamada com " "argumentos nomeados, use :func:`functools.partial`." -#: ../../library/asyncio-eventloop.rst:292 +#: ../../library/asyncio-eventloop.rst:297 msgid "" "An optional keyword-only *context* argument allows specifying a custom :" "class:`contextvars.Context` for the *callback* to run in. The current " @@ -540,7 +545,7 @@ msgstr "" "class:`contextvars.Context` customizado para executar na *função de " "retorno*. O contexto atual é usado quando nenhum *context* é fornecido." -#: ../../library/asyncio-eventloop.rst:300 +#: ../../library/asyncio-eventloop.rst:305 msgid "" "In Python 3.7 and earlier with the default event loop implementation, the " "*delay* could not exceed one day. This has been fixed in Python 3.8." @@ -548,7 +553,7 @@ msgstr "" "No Python 3.7 e anterior, com a implementação padrão do laço de eventos, o " "*delay* não poderia exceder um dia. Isto foi ajustado no Python 3.8." -#: ../../library/asyncio-eventloop.rst:307 +#: ../../library/asyncio-eventloop.rst:312 msgid "" "Schedule *callback* to be called at the given absolute timestamp *when* (an " "int or a float), using the same time reference as :meth:`loop.time`." @@ -557,11 +562,11 @@ msgstr "" "(um inteiro ou um ponto flutuante), usando o mesmo horário de referência " "que :meth:`loop.time`." -#: ../../library/asyncio-eventloop.rst:311 +#: ../../library/asyncio-eventloop.rst:316 msgid "This method's behavior is the same as :meth:`call_later`." msgstr "O comportamento deste método é o mesmo que :meth:`call_later`." -#: ../../library/asyncio-eventloop.rst:320 +#: ../../library/asyncio-eventloop.rst:325 msgid "" "In Python 3.7 and earlier with the default event loop implementation, the " "difference between *when* and the current time could not exceed one day. " @@ -571,7 +576,7 @@ msgstr "" "diferença entre *when* e o horário atual não poderia exceder um dia. Isto " "foi ajustado no Python 3.8." -#: ../../library/asyncio-eventloop.rst:327 +#: ../../library/asyncio-eventloop.rst:332 msgid "" "Return the current time, as a :class:`float` value, according to the event " "loop's internal monotonic clock." @@ -579,7 +584,7 @@ msgstr "" "Retorna o horário atual, como um valor :class:`float`, de acordo com o " "relógio monotônico interno do laço de eventos." -#: ../../library/asyncio-eventloop.rst:331 +#: ../../library/asyncio-eventloop.rst:336 msgid "" "In Python 3.7 and earlier timeouts (relative *delay* or absolute *when*) " "should not exceed one day. This has been fixed in Python 3.8." @@ -587,19 +592,19 @@ msgstr "" "No Python 3.7 e anterior, tempos limites (*delay* relativo ou *when* " "absoluto) não poderiam exceder um dia. Isto foi ajustado no Python 3.8." -#: ../../library/asyncio-eventloop.rst:337 +#: ../../library/asyncio-eventloop.rst:342 msgid "The :func:`asyncio.sleep` function." msgstr "A função :func:`asyncio.sleep`." -#: ../../library/asyncio-eventloop.rst:341 +#: ../../library/asyncio-eventloop.rst:346 msgid "Creating Futures and Tasks" msgstr "Criando Futures e Tasks" -#: ../../library/asyncio-eventloop.rst:345 +#: ../../library/asyncio-eventloop.rst:350 msgid "Create an :class:`asyncio.Future` object attached to the event loop." msgstr "Cria um objeto :class:`asyncio.Future` atachado ao laço de eventos." -#: ../../library/asyncio-eventloop.rst:347 +#: ../../library/asyncio-eventloop.rst:352 msgid "" "This is the preferred way to create Futures in asyncio. This lets third-" "party event loops provide alternative implementations of the Future object " @@ -609,13 +614,13 @@ msgstr "" "laços de eventos de terceiros forneçam implementações alternativas do objeto " "Future (com melhor desempenho ou instrumentação)." -#: ../../library/asyncio-eventloop.rst:355 +#: ../../library/asyncio-eventloop.rst:360 msgid "" "Schedule the execution of :ref:`coroutine ` *coro*. Return a :" "class:`Task` object." msgstr "" -#: ../../library/asyncio-eventloop.rst:358 +#: ../../library/asyncio-eventloop.rst:363 msgid "" "Third-party event loops can use their own subclass of :class:`Task` for " "interoperability. In this case, the result type is a subclass of :class:" @@ -625,7 +630,15 @@ msgstr "" "`Task` para interoperabilidade. Neste caso, o tipo do resultado é uma " "subclasse de :class:`Task`." -#: ../../library/asyncio-eventloop.rst:362 +#: ../../library/asyncio-eventloop.rst:367 +msgid "" +"The full function signature is largely the same as that of the :class:`Task` " +"constructor (or factory) - all of the keyword arguments to this function are " +"passed through to that interface, except *name*, or *context* if it is " +"``None``." +msgstr "" + +#: ../../library/asyncio-eventloop.rst:372 msgid "" "If the *name* argument is provided and not ``None``, it is set as the name " "of the task using :meth:`Task.set_name`." @@ -633,45 +646,68 @@ msgstr "" "Se o argumento *name* for fornecido e não é ``None``, ele é definido como o " "nome da tarefa, usando :meth:`Task.set_name`." -#: ../../library/asyncio-eventloop.rst:365 +#: ../../library/asyncio-eventloop.rst:375 msgid "" "An optional keyword-only *context* argument allows specifying a custom :" "class:`contextvars.Context` for the *coro* to run in. The current context " "copy is created when no *context* is provided." msgstr "" -#: ../../library/asyncio-eventloop.rst:369 +#: ../../library/asyncio-eventloop.rst:379 msgid "Added the *name* parameter." msgstr "Adicionado o parâmetro *name*." -#: ../../library/asyncio-eventloop.rst:372 +#: ../../library/asyncio-eventloop.rst:382 msgid "Added the *context* parameter." msgstr "Adicionado o parâmetro *context*." -#: ../../library/asyncio-eventloop.rst:377 +#: ../../library/asyncio-eventloop.rst:385 +msgid "" +"Added ``kwargs`` which passes on arbitrary extra parameters, including " +"``name`` and ``context``." +msgstr "" + +#: ../../library/asyncio-eventloop.rst:388 +msgid "" +"Rolled back the change that passes on *name* and *context* (if it is None), " +"while still passing on other arbitrary keyword arguments (to avoid breaking " +"backwards compatibility with 3.13.3)." +msgstr "" + +#: ../../library/asyncio-eventloop.rst:394 msgid "Set a task factory that will be used by :meth:`loop.create_task`." msgstr "" "Define a factory da tarefa que será usada por :meth:`loop.create_task`." -#: ../../library/asyncio-eventloop.rst:380 +#: ../../library/asyncio-eventloop.rst:397 msgid "" "If *factory* is ``None`` the default task factory will be set. Otherwise, " "*factory* must be a *callable* with the signature matching ``(loop, coro, " -"context=None)``, where *loop* is a reference to the active event loop, and " -"*coro* is a coroutine object. The callable must return a :class:`asyncio." -"Future`-compatible object." +"**kwargs)``, where *loop* is a reference to the active event loop, and " +"*coro* is a coroutine object. The callable must pass on all *kwargs*, and " +"return a :class:`asyncio.Task`-compatible object." msgstr "" -#: ../../library/asyncio-eventloop.rst:388 +#: ../../library/asyncio-eventloop.rst:403 +msgid "Required that all *kwargs* are passed on to :class:`asyncio.Task`." +msgstr "" + +#: ../../library/asyncio-eventloop.rst:406 +msgid "" +"*name* is no longer passed to task factories. *context* is no longer passed " +"to task factories if it is ``None``." +msgstr "" + +#: ../../library/asyncio-eventloop.rst:412 msgid "Return a task factory or ``None`` if the default one is in use." msgstr "" "Retorna uma factory de tarefa ou ``None`` se a factory padrão estiver em uso." -#: ../../library/asyncio-eventloop.rst:392 +#: ../../library/asyncio-eventloop.rst:416 msgid "Opening network connections" msgstr "Abrindo conexões de rede" -#: ../../library/asyncio-eventloop.rst:403 +#: ../../library/asyncio-eventloop.rst:428 msgid "" "Open a streaming transport connection to a given address specified by *host* " "and *port*." @@ -679,20 +715,20 @@ msgstr "" "Abre uma conexão de transporte para streaming, para um endereço fornecido, " "especificado por *host* e *port*." -#: ../../library/asyncio-eventloop.rst:406 +#: ../../library/asyncio-eventloop.rst:431 msgid "" "The socket family can be either :py:const:`~socket.AF_INET` or :py:const:" "`~socket.AF_INET6` depending on *host* (or the *family* argument, if " "provided)." msgstr "" -#: ../../library/asyncio-eventloop.rst:410 +#: ../../library/asyncio-eventloop.rst:435 msgid "The socket type will be :py:const:`~socket.SOCK_STREAM`." msgstr "" -#: ../../library/asyncio-eventloop.rst:412 -#: ../../library/asyncio-eventloop.rst:1180 -#: ../../library/asyncio-eventloop.rst:1196 +#: ../../library/asyncio-eventloop.rst:437 +#: ../../library/asyncio-eventloop.rst:1230 +#: ../../library/asyncio-eventloop.rst:1247 msgid "" "*protocol_factory* must be a callable returning an :ref:`asyncio protocol " "` implementation." @@ -700,7 +736,7 @@ msgstr "" "*protocol_factory* deve ser um chamável que retorne uma implementação do :" "ref:`protocolo asyncio `." -#: ../../library/asyncio-eventloop.rst:415 +#: ../../library/asyncio-eventloop.rst:440 msgid "" "This method will try to establish the connection in the background. When " "successful, it returns a ``(transport, protocol)`` pair." @@ -708,11 +744,11 @@ msgstr "" "Este método tentará estabelecer a conexão em segundo plano. Quando tiver " "sucesso, ele retorna um par ``(transport, protocol)``." -#: ../../library/asyncio-eventloop.rst:418 +#: ../../library/asyncio-eventloop.rst:443 msgid "The chronological synopsis of the underlying operation is as follows:" msgstr "A sinopse cronológica da operação subjacente é conforme abaixo:" -#: ../../library/asyncio-eventloop.rst:420 +#: ../../library/asyncio-eventloop.rst:445 msgid "" "The connection is established and a :ref:`transport ` is " "created for it." @@ -720,7 +756,7 @@ msgstr "" "A conexão é estabelecida e um :ref:`transporte ` é criado " "para ela." -#: ../../library/asyncio-eventloop.rst:423 +#: ../../library/asyncio-eventloop.rst:448 msgid "" "*protocol_factory* is called without arguments and is expected to return a :" "ref:`protocol ` instance." @@ -728,7 +764,7 @@ msgstr "" "*protocol_factory* é chamada sem argumentos e é esperada que retorne uma " "instância de :ref:`protocolo `." -#: ../../library/asyncio-eventloop.rst:426 +#: ../../library/asyncio-eventloop.rst:451 msgid "" "The protocol instance is coupled with the transport by calling its :meth:" "`~BaseProtocol.connection_made` method." @@ -736,22 +772,22 @@ msgstr "" "A instância de protocolo é acoplada com o transporte, através da chamada do " "seu método :meth:`~BaseProtocol.connection_made`." -#: ../../library/asyncio-eventloop.rst:429 +#: ../../library/asyncio-eventloop.rst:454 msgid "A ``(transport, protocol)`` tuple is returned on success." msgstr "Uma tupla ``(transport, protocol)`` é retornada ao ter sucesso." -#: ../../library/asyncio-eventloop.rst:431 +#: ../../library/asyncio-eventloop.rst:456 msgid "" "The created transport is an implementation-dependent bidirectional stream." msgstr "" "O transporte criado é um stream bi-direcional dependente de implementação." -#: ../../library/asyncio-eventloop.rst:434 -#: ../../library/asyncio-eventloop.rst:566 +#: ../../library/asyncio-eventloop.rst:459 +#: ../../library/asyncio-eventloop.rst:592 msgid "Other arguments:" msgstr "Outros argumentos:" -#: ../../library/asyncio-eventloop.rst:436 +#: ../../library/asyncio-eventloop.rst:461 msgid "" "*ssl*: if given and not false, a SSL/TLS transport is created (by default a " "plain TCP transport is created). If *ssl* is a :class:`ssl.SSLContext` " @@ -765,11 +801,11 @@ msgstr "" "for :const:`True`, um contexto padrão retornado de :func:`ssl." "create_default_context` é usado." -#: ../../library/asyncio-eventloop.rst:442 +#: ../../library/asyncio-eventloop.rst:467 msgid ":ref:`SSL/TLS security considerations `" msgstr ":ref:`Considerações de segurança sobre SSL/TLS `" -#: ../../library/asyncio-eventloop.rst:444 +#: ../../library/asyncio-eventloop.rst:469 msgid "" "*server_hostname* sets or overrides the hostname that the target server's " "certificate will be matched against. Should only be passed if *ssl* is not " @@ -787,7 +823,7 @@ msgstr "" "de hostname é desabilitado (o que é um risco de segurança sério, permitindo " "ataques potenciais man-in-the-middle)." -#: ../../library/asyncio-eventloop.rst:452 +#: ../../library/asyncio-eventloop.rst:477 msgid "" "*family*, *proto*, *flags* are the optional address family, protocol and " "flags to be passed through to getaddrinfo() for *host* resolution. If given, " @@ -799,7 +835,7 @@ msgstr "" "*host*. Se fornecidos, eles devem ser todos inteiros e constantes " "correspondentes do módulo :mod:`socket`." -#: ../../library/asyncio-eventloop.rst:457 +#: ../../library/asyncio-eventloop.rst:482 msgid "" "*happy_eyeballs_delay*, if given, enables Happy Eyeballs for this " "connection. It should be a floating-point number representing the amount of " @@ -815,7 +851,7 @@ msgstr "" "conforme definido na :rfc:`8305`. Um valor padrão sensível recomendado pela " "RFC é ``0.25`` (250 millisegundos)." -#: ../../library/asyncio-eventloop.rst:465 +#: ../../library/asyncio-eventloop.rst:490 msgid "" "*interleave* controls address reordering when a host name resolves to " "multiple IP addresses. If ``0`` or unspecified, no reordering is done, and " @@ -834,7 +870,7 @@ msgstr "" "definido na :rfc:`8305`. O padrão é ``0`` se *happy_eyeballs_delay* não for " "especificado, e ``1`` se ele for." -#: ../../library/asyncio-eventloop.rst:474 +#: ../../library/asyncio-eventloop.rst:499 msgid "" "*sock*, if given, should be an existing, already connected :class:`socket." "socket` object to be used by the transport. If *sock* is given, none of " @@ -847,16 +883,16 @@ msgstr "" "*happy_eyeballs_delay*, *interleave* e *local_addr* não devem ser " "especificados." -#: ../../library/asyncio-eventloop.rst:482 -#: ../../library/asyncio-eventloop.rst:597 -#: ../../library/asyncio-eventloop.rst:841 +#: ../../library/asyncio-eventloop.rst:507 +#: ../../library/asyncio-eventloop.rst:623 +#: ../../library/asyncio-eventloop.rst:871 msgid "" "The *sock* argument transfers ownership of the socket to the transport " "created. To close the socket, call the transport's :meth:`~asyncio." "BaseTransport.close` method." msgstr "" -#: ../../library/asyncio-eventloop.rst:486 +#: ../../library/asyncio-eventloop.rst:511 msgid "" "*local_addr*, if given, is a ``(local_host, local_port)`` tuple used to bind " "the socket locally. The *local_host* and *local_port* are looked up using " @@ -867,8 +903,8 @@ msgstr "" "são procurados usando ``getaddrinfo()``, de forma similar para *host* e " "*port*." -#: ../../library/asyncio-eventloop.rst:490 -#: ../../library/asyncio-eventloop.rst:935 +#: ../../library/asyncio-eventloop.rst:515 +#: ../../library/asyncio-eventloop.rst:967 msgid "" "*ssl_handshake_timeout* is (for a TLS connection) the time in seconds to " "wait for the TLS handshake to complete before aborting the connection. " @@ -878,17 +914,17 @@ msgstr "" "aguardar pelo encerramento do aperto de mão TLS, antes de abortar a conexão. " "``60.0`` segundos se for ``None`` (valor padrão)." -#: ../../library/asyncio-eventloop.rst:494 -#: ../../library/asyncio-eventloop.rst:750 -#: ../../library/asyncio-eventloop.rst:852 -#: ../../library/asyncio-eventloop.rst:939 +#: ../../library/asyncio-eventloop.rst:519 +#: ../../library/asyncio-eventloop.rst:778 +#: ../../library/asyncio-eventloop.rst:882 +#: ../../library/asyncio-eventloop.rst:971 msgid "" "*ssl_shutdown_timeout* is the time in seconds to wait for the SSL shutdown " "to complete before aborting the connection. ``30.0`` seconds if ``None`` " "(default)." msgstr "" -#: ../../library/asyncio-eventloop.rst:498 +#: ../../library/asyncio-eventloop.rst:523 msgid "" "*all_errors* determines what exceptions are raised when a connection cannot " "be created. By default, only a single ``Exception`` is raised: the first " @@ -898,27 +934,27 @@ msgid "" "(even if there is only one)." msgstr "" -#: ../../library/asyncio-eventloop.rst:508 -#: ../../library/asyncio-eventloop.rst:762 +#: ../../library/asyncio-eventloop.rst:533 +#: ../../library/asyncio-eventloop.rst:790 msgid "Added support for SSL/TLS in :class:`ProactorEventLoop`." msgstr "Adicionado suporte para SSL/TLS na :class:`ProactorEventLoop`." -#: ../../library/asyncio-eventloop.rst:512 +#: ../../library/asyncio-eventloop.rst:537 msgid "" "The socket option :ref:`socket.TCP_NODELAY ` is set " "by default for all TCP connections." msgstr "" -#: ../../library/asyncio-eventloop.rst:517 -#: ../../library/asyncio-eventloop.rst:862 +#: ../../library/asyncio-eventloop.rst:542 +#: ../../library/asyncio-eventloop.rst:892 msgid "Added the *ssl_handshake_timeout* parameter." msgstr "Adicionado o parâmetro *ssl_handshake_timeout*." -#: ../../library/asyncio-eventloop.rst:521 +#: ../../library/asyncio-eventloop.rst:546 msgid "Added the *happy_eyeballs_delay* and *interleave* parameters." msgstr "Adicionados os parâmetros *happy_eyeballs_delay* e *interleave*." -#: ../../library/asyncio-eventloop.rst:523 +#: ../../library/asyncio-eventloop.rst:548 msgid "" "Happy Eyeballs Algorithm: Success with Dual-Stack Hosts. When a server's " "IPv4 path and protocol are working, but the server's IPv6 path and protocol " @@ -929,24 +965,24 @@ msgid "" "visible delay and provides an algorithm." msgstr "" -#: ../../library/asyncio-eventloop.rst:532 +#: ../../library/asyncio-eventloop.rst:557 msgid "For more information: https://datatracker.ietf.org/doc/html/rfc6555" msgstr "" -#: ../../library/asyncio-eventloop.rst:536 -#: ../../library/asyncio-eventloop.rst:660 -#: ../../library/asyncio-eventloop.rst:776 -#: ../../library/asyncio-eventloop.rst:815 -#: ../../library/asyncio-eventloop.rst:866 -#: ../../library/asyncio-eventloop.rst:947 +#: ../../library/asyncio-eventloop.rst:561 +#: ../../library/asyncio-eventloop.rst:687 +#: ../../library/asyncio-eventloop.rst:804 +#: ../../library/asyncio-eventloop.rst:844 +#: ../../library/asyncio-eventloop.rst:896 +#: ../../library/asyncio-eventloop.rst:979 msgid "Added the *ssl_shutdown_timeout* parameter." msgstr "" -#: ../../library/asyncio-eventloop.rst:538 +#: ../../library/asyncio-eventloop.rst:563 msgid "*all_errors* was added." msgstr "" -#: ../../library/asyncio-eventloop.rst:543 +#: ../../library/asyncio-eventloop.rst:568 msgid "" "The :func:`open_connection` function is a high-level alternative API. It " "returns a pair of (:class:`StreamReader`, :class:`StreamWriter`) that can be " @@ -956,24 +992,24 @@ msgstr "" "retorna um par de (:class:`StreamReader`, :class:`StreamWriter`) que pode " "ser usado diretamente em código async/await." -#: ../../library/asyncio-eventloop.rst:553 +#: ../../library/asyncio-eventloop.rst:579 msgid "Create a datagram connection." msgstr "Cria uma conexão de datagrama." -#: ../../library/asyncio-eventloop.rst:555 +#: ../../library/asyncio-eventloop.rst:581 msgid "" "The socket family can be either :py:const:`~socket.AF_INET`, :py:const:" "`~socket.AF_INET6`, or :py:const:`~socket.AF_UNIX`, depending on *host* (or " "the *family* argument, if provided)." msgstr "" -#: ../../library/asyncio-eventloop.rst:559 +#: ../../library/asyncio-eventloop.rst:585 msgid "The socket type will be :py:const:`~socket.SOCK_DGRAM`." msgstr "" -#: ../../library/asyncio-eventloop.rst:561 -#: ../../library/asyncio-eventloop.rst:686 -#: ../../library/asyncio-eventloop.rst:833 +#: ../../library/asyncio-eventloop.rst:587 +#: ../../library/asyncio-eventloop.rst:714 +#: ../../library/asyncio-eventloop.rst:863 msgid "" "*protocol_factory* must be a callable returning a :ref:`protocol ` implementation." @@ -981,12 +1017,12 @@ msgstr "" "*protocol_factory* deve ser algo chamável, retornando uma implementação de :" "ref:`protocolo `." -#: ../../library/asyncio-eventloop.rst:564 -#: ../../library/asyncio-eventloop.rst:642 +#: ../../library/asyncio-eventloop.rst:590 +#: ../../library/asyncio-eventloop.rst:669 msgid "A tuple of ``(transport, protocol)`` is returned on success." msgstr "Uma tupla de ``(transport, protocol)`` é retornada em caso de sucesso." -#: ../../library/asyncio-eventloop.rst:568 +#: ../../library/asyncio-eventloop.rst:594 msgid "" "*local_addr*, if given, is a ``(local_host, local_port)`` tuple used to bind " "the socket locally. The *local_host* and *local_port* are looked up using :" @@ -996,7 +1032,7 @@ msgstr "" "usada para ligar o soquete localmente. O *local_host* e a *local_port* são " "procurados usando :meth:`getaddrinfo`." -#: ../../library/asyncio-eventloop.rst:572 +#: ../../library/asyncio-eventloop.rst:598 msgid "" "*remote_addr*, if given, is a ``(remote_host, remote_port)`` tuple used to " "connect the socket to a remote address. The *remote_host* and *remote_port* " @@ -1006,7 +1042,7 @@ msgstr "" "usada para conectar o soquete a um endereço remoto. O *remote_host* e a " "*remote_port* são procurados usando :meth:`getaddrinfo`." -#: ../../library/asyncio-eventloop.rst:576 +#: ../../library/asyncio-eventloop.rst:602 msgid "" "*family*, *proto*, *flags* are the optional address family, protocol and " "flags to be passed through to :meth:`getaddrinfo` for *host* resolution. If " @@ -1018,7 +1054,7 @@ msgstr "" "*host*. Se fornecido, esses devem ser todos inteiros do módulo de " "constantes :mod:`socket` correspondente." -#: ../../library/asyncio-eventloop.rst:581 +#: ../../library/asyncio-eventloop.rst:607 msgid "" "*reuse_port* tells the kernel to allow this endpoint to be bound to the same " "port as other existing endpoints are bound to, so long as they all set this " @@ -1027,7 +1063,7 @@ msgid "" "is not defined then this capability is unsupported." msgstr "" -#: ../../library/asyncio-eventloop.rst:587 +#: ../../library/asyncio-eventloop.rst:613 msgid "" "*allow_broadcast* tells the kernel to allow this endpoint to send messages " "to the broadcast address." @@ -1035,7 +1071,7 @@ msgstr "" "*allow_broadcast* avisa o kernel para permitir que este endpoint envie " "mensagens para o endereço de broadcast." -#: ../../library/asyncio-eventloop.rst:590 +#: ../../library/asyncio-eventloop.rst:616 msgid "" "*sock* can optionally be specified in order to use a preexisting, already " "connected, :class:`socket.socket` object to be used by the transport. If " @@ -1047,7 +1083,7 @@ msgstr "" "transporte. Se especificado, *local_addr* e *remote_addr* devem ser omitidos " "(devem ser :const:`None`)." -#: ../../library/asyncio-eventloop.rst:601 +#: ../../library/asyncio-eventloop.rst:627 msgid "" "See :ref:`UDP echo client protocol ` and :" "ref:`UDP echo server protocol ` examples." @@ -1056,24 +1092,24 @@ msgstr "" "ref:`protocolo UDP eco servidor ` para " "exemplos." -#: ../../library/asyncio-eventloop.rst:604 +#: ../../library/asyncio-eventloop.rst:630 msgid "" "The *family*, *proto*, *flags*, *reuse_address*, *reuse_port*, " "*allow_broadcast*, and *sock* parameters were added." msgstr "" -#: ../../library/asyncio-eventloop.rst:608 +#: ../../library/asyncio-eventloop.rst:634 msgid "Added support for Windows." msgstr "Adicionado suporte para Windows." -#: ../../library/asyncio-eventloop.rst:611 +#: ../../library/asyncio-eventloop.rst:637 msgid "" "The *reuse_address* parameter is no longer supported, as using :ref:`socket." "SO_REUSEADDR ` poses a significant security concern " "for UDP. Explicitly passing ``reuse_address=True`` will raise an exception." msgstr "" -#: ../../library/asyncio-eventloop.rst:617 +#: ../../library/asyncio-eventloop.rst:643 msgid "" "When multiple processes with differing UIDs assign sockets to an identical " "UDP socket address with ``SO_REUSEADDR``, incoming packets can become " @@ -1083,7 +1119,7 @@ msgstr "" "endereço de soquete UDP idêntico com ``SO_REUSEADDR``, pacotes recebidos " "podem ser distribuídos aleatoriamente entre os soquetes." -#: ../../library/asyncio-eventloop.rst:621 +#: ../../library/asyncio-eventloop.rst:647 msgid "" "For supported platforms, *reuse_port* can be used as a replacement for " "similar functionality. With *reuse_port*, :ref:`socket.SO_REUSEPORT `: Unix." -msgstr ":ref:`Disponibilidade `: Unix." +#: ../../library/asyncio-eventloop.rst:679 +#: ../../library/asyncio-eventloop.rst:835 +#: ../../library/asyncio-eventloop.rst:1300 +#: ../../library/asyncio-eventloop.rst:1840 +#: ../../library/asyncio-eventloop.rst:1847 +msgid "Availability" +msgstr "Disponibilidade" -#: ../../library/asyncio-eventloop.rst:654 +#: ../../library/asyncio-eventloop.rst:681 msgid "" "Added the *ssl_handshake_timeout* parameter. The *path* parameter can now be " "a :term:`path-like object`." @@ -1139,25 +1177,25 @@ msgstr "" "Adicionado o parâmetro *ssl_handshake_timeout*. O parâmetro *path* agora " "pode ser um :term:`path-like object`." -#: ../../library/asyncio-eventloop.rst:664 +#: ../../library/asyncio-eventloop.rst:691 msgid "Creating network servers" msgstr "Criando servidores de rede" -#: ../../library/asyncio-eventloop.rst:679 +#: ../../library/asyncio-eventloop.rst:707 msgid "" "Create a TCP server (socket type :const:`~socket.SOCK_STREAM`) listening on " "*port* of the *host* address." msgstr "" -#: ../../library/asyncio-eventloop.rst:682 +#: ../../library/asyncio-eventloop.rst:710 msgid "Returns a :class:`Server` object." msgstr "Retorna um objeto :class:`Server`." -#: ../../library/asyncio-eventloop.rst:684 +#: ../../library/asyncio-eventloop.rst:712 msgid "Arguments:" msgstr "Argumentos:" -#: ../../library/asyncio-eventloop.rst:689 +#: ../../library/asyncio-eventloop.rst:717 msgid "" "The *host* parameter can be set to several types which determine where the " "server would be listening:" @@ -1165,7 +1203,7 @@ msgstr "" "O parâmetro *host* pode ser definido para diversos tipos, o qual determina " "onde o servidor deve escutar:" -#: ../../library/asyncio-eventloop.rst:692 +#: ../../library/asyncio-eventloop.rst:720 msgid "" "If *host* is a string, the TCP server is bound to a single network interface " "specified by *host*." @@ -1173,7 +1211,7 @@ msgstr "" "Se *host* for uma string, o servidor TCP está vinculado a apenas uma " "interface de rede, especificada por *host*." -#: ../../library/asyncio-eventloop.rst:695 +#: ../../library/asyncio-eventloop.rst:723 msgid "" "If *host* is a sequence of strings, the TCP server is bound to all network " "interfaces specified by the sequence." @@ -1181,7 +1219,7 @@ msgstr "" "Se *host* é uma sequência de strings, o servidor TCP está vinculado a todas " "as interfaces de rede especificadas pela sequência." -#: ../../library/asyncio-eventloop.rst:698 +#: ../../library/asyncio-eventloop.rst:726 msgid "" "If *host* is an empty string or ``None``, all interfaces are assumed and a " "list of multiple sockets will be returned (most likely one for IPv4 and " @@ -1191,7 +1229,7 @@ msgstr "" "e uma lista de múltiplos soquetes será retornada (muito provavelmente um " "para IPv4 e outro para IPv6)." -#: ../../library/asyncio-eventloop.rst:702 +#: ../../library/asyncio-eventloop.rst:730 msgid "" "The *port* parameter can be set to specify which port the server should " "listen on. If ``0`` or ``None`` (the default), a random unused port will be " @@ -1204,18 +1242,18 @@ msgstr "" "interfaces de rede, uma porta aleatória diferente será selecionada para cada " "interface)." -#: ../../library/asyncio-eventloop.rst:707 +#: ../../library/asyncio-eventloop.rst:735 msgid "" "*family* can be set to either :const:`socket.AF_INET` or :const:`~socket." "AF_INET6` to force the socket to use IPv4 or IPv6. If not set, the *family* " "will be determined from host name (defaults to :const:`~socket.AF_UNSPEC`)." msgstr "" -#: ../../library/asyncio-eventloop.rst:712 +#: ../../library/asyncio-eventloop.rst:740 msgid "*flags* is a bitmask for :meth:`getaddrinfo`." msgstr "*flags* é uma máscara de bits para :meth:`getaddrinfo`." -#: ../../library/asyncio-eventloop.rst:714 +#: ../../library/asyncio-eventloop.rst:742 msgid "" "*sock* can optionally be specified in order to use a preexisting socket " "object. If specified, *host* and *port* must not be specified." @@ -1223,13 +1261,13 @@ msgstr "" "*sock* pode opcionalmente ser especificado para usar um objeto soquete pré-" "existente. Se especificado, *host* e *port* não devem ser especificados." -#: ../../library/asyncio-eventloop.rst:719 +#: ../../library/asyncio-eventloop.rst:747 msgid "" "The *sock* argument transfers ownership of the socket to the server created. " "To close the socket, call the server's :meth:`~asyncio.Server.close` method." msgstr "" -#: ../../library/asyncio-eventloop.rst:723 +#: ../../library/asyncio-eventloop.rst:751 msgid "" "*backlog* is the maximum number of queued connections passed to :meth:" "`~socket.socket.listen` (defaults to 100)." @@ -1237,7 +1275,7 @@ msgstr "" "*backlog* é o número máximo de conexões enfileiradas pasadas para :meth:" "`~socket.socket.listen` (padrão é 100)." -#: ../../library/asyncio-eventloop.rst:726 +#: ../../library/asyncio-eventloop.rst:754 msgid "" "*ssl* can be set to an :class:`~ssl.SSLContext` instance to enable TLS over " "the accepted connections." @@ -1245,7 +1283,7 @@ msgstr "" "*ssl* pode ser definido para uma instância de :class:`~ssl.SSLContext` para " "habilitar TLS sobre as conexões aceitas." -#: ../../library/asyncio-eventloop.rst:729 +#: ../../library/asyncio-eventloop.rst:757 msgid "" "*reuse_address* tells the kernel to reuse a local socket in ``TIME_WAIT`` " "state, without waiting for its natural timeout to expire. If not specified " @@ -1255,7 +1293,7 @@ msgstr "" "``TIME_WAIT``, serm aguardar pela expiração natural do seu tempo limite. Se " "não especificado, será automaticamente definida como ``True`` no Unix." -#: ../../library/asyncio-eventloop.rst:734 +#: ../../library/asyncio-eventloop.rst:762 msgid "" "*reuse_port* tells the kernel to allow this endpoint to be bound to the same " "port as other existing endpoints are bound to, so long as they all set this " @@ -1266,17 +1304,17 @@ msgstr "" "todos eles definam este sinalizador quando forem criados. Esta opção não é " "suportada no Windows." -#: ../../library/asyncio-eventloop.rst:739 +#: ../../library/asyncio-eventloop.rst:767 msgid "" "*keep_alive* set to ``True`` keeps connections active by enabling the " "periodic transmission of messages." msgstr "" -#: ../../library/asyncio-eventloop.rst:744 +#: ../../library/asyncio-eventloop.rst:772 msgid "Added the *keep_alive* parameter." msgstr "" -#: ../../library/asyncio-eventloop.rst:746 +#: ../../library/asyncio-eventloop.rst:774 msgid "" "*ssl_handshake_timeout* is (for a TLS server) the time in seconds to wait " "for the TLS handshake to complete before aborting the connection. ``60.0`` " @@ -1286,7 +1324,7 @@ msgstr "" "aguardar pelo aperto de mão TLS ser concluído, antes de abortar a conexão. " "``60.0`` segundos se ``None`` (valor padrão)." -#: ../../library/asyncio-eventloop.rst:754 +#: ../../library/asyncio-eventloop.rst:782 msgid "" "*start_serving* set to ``True`` (the default) causes the created server to " "start accepting connections immediately. When set to ``False``, the user " @@ -1298,18 +1336,18 @@ msgstr "" "usuário deve aguardar com :meth:`Server.start_serving` ou :meth:`Server." "serve_forever` para fazer o servidor começar a aceitar conexões." -#: ../../library/asyncio-eventloop.rst:766 +#: ../../library/asyncio-eventloop.rst:794 msgid "The *host* parameter can be a sequence of strings." msgstr "O parâmetro *host* pode ser uma sequência de strings." -#: ../../library/asyncio-eventloop.rst:770 +#: ../../library/asyncio-eventloop.rst:798 msgid "" "Added *ssl_handshake_timeout* and *start_serving* parameters. The socket " "option :ref:`socket.TCP_NODELAY ` is set by default " "for all TCP connections." msgstr "" -#: ../../library/asyncio-eventloop.rst:780 +#: ../../library/asyncio-eventloop.rst:808 msgid "" "The :func:`start_server` function is a higher-level alternative API that " "returns a pair of :class:`StreamReader` and :class:`StreamWriter` that can " @@ -1319,13 +1357,13 @@ msgstr "" "retorna um par de :class:`StreamReader` e :class:`StreamWriter` que pode ser " "usado em um código async/await." -#: ../../library/asyncio-eventloop.rst:791 +#: ../../library/asyncio-eventloop.rst:820 msgid "" "Similar to :meth:`loop.create_server` but works with the :py:const:`~socket." "AF_UNIX` socket family." msgstr "" -#: ../../library/asyncio-eventloop.rst:794 +#: ../../library/asyncio-eventloop.rst:823 msgid "" "*path* is the name of a Unix domain socket, and is required, unless a *sock* " "argument is provided. Abstract Unix sockets, :class:`str`, :class:`bytes`, " @@ -1335,14 +1373,14 @@ msgstr "" "que um argumento *sock* seja fornecido. Soquetes Unix abstratos, :class:" "`str`, :class:`bytes`, e caminhos :class:`~pathlib.Path` são suportados." -#: ../../library/asyncio-eventloop.rst:799 +#: ../../library/asyncio-eventloop.rst:828 msgid "" "If *cleanup_socket* is true then the Unix socket will automatically be " "removed from the filesystem when the server is closed, unless the socket has " "been replaced after the server has been created." msgstr "" -#: ../../library/asyncio-eventloop.rst:803 +#: ../../library/asyncio-eventloop.rst:832 msgid "" "See the documentation of the :meth:`loop.create_server` method for " "information about arguments to this method." @@ -1350,7 +1388,7 @@ msgstr "" "Veja a documentação do método :meth:`loop.create_server` para informações " "sobre argumentos para este método." -#: ../../library/asyncio-eventloop.rst:810 +#: ../../library/asyncio-eventloop.rst:839 msgid "" "Added the *ssl_handshake_timeout* and *start_serving* parameters. The *path* " "parameter can now be a :class:`~pathlib.Path` object." @@ -1358,15 +1396,15 @@ msgstr "" "Adicionados os parâmetros *ssl_handshake_timeout* estart_serving*. O " "parâmetros *path* agora pode ser um objeto da classe :class:`~pathlib.Path`." -#: ../../library/asyncio-eventloop.rst:819 +#: ../../library/asyncio-eventloop.rst:848 msgid "Added the *cleanup_socket* parameter." msgstr "" -#: ../../library/asyncio-eventloop.rst:826 +#: ../../library/asyncio-eventloop.rst:856 msgid "Wrap an already accepted connection into a transport/protocol pair." msgstr "Envolve uma conexão já aceita em um par transporte/protocolo." -#: ../../library/asyncio-eventloop.rst:828 +#: ../../library/asyncio-eventloop.rst:858 msgid "" "This method can be used by servers that accept connections outside of " "asyncio but that use asyncio to handle them." @@ -1374,12 +1412,12 @@ msgstr "" "Este método pode ser usado por servidores que aceitam conexões fora do " "asyncio, mas que usam asyncio para manipulá-las." -#: ../../library/asyncio-eventloop.rst:831 -#: ../../library/asyncio-eventloop.rst:921 +#: ../../library/asyncio-eventloop.rst:861 +#: ../../library/asyncio-eventloop.rst:953 msgid "Parameters:" msgstr "Parâmetros:" -#: ../../library/asyncio-eventloop.rst:836 +#: ../../library/asyncio-eventloop.rst:866 msgid "" "*sock* is a preexisting socket object returned from :meth:`socket.accept " "`." @@ -1387,7 +1425,7 @@ msgstr "" "*sock* é um objeto soquete pré-existente retornado a partir de :meth:`socket." "accept `." -#: ../../library/asyncio-eventloop.rst:845 +#: ../../library/asyncio-eventloop.rst:875 msgid "" "*ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the " "accepted connections." @@ -1395,7 +1433,7 @@ msgstr "" "*ssl* pode ser definido para um :class:`~ssl.SSLContext` para habilitar SSL " "sobre as conexões aceitas." -#: ../../library/asyncio-eventloop.rst:848 +#: ../../library/asyncio-eventloop.rst:878 msgid "" "*ssl_handshake_timeout* is (for an SSL connection) the time in seconds to " "wait for the SSL handshake to complete before aborting the connection. " @@ -1405,31 +1443,31 @@ msgstr "" "aguardar pelo aperto de mão SSL ser concluído, antes de abortar a conexão. " "``60.0`` segundos se ``None`` (valor padrão)." -#: ../../library/asyncio-eventloop.rst:856 +#: ../../library/asyncio-eventloop.rst:886 msgid "Returns a ``(transport, protocol)`` pair." msgstr "Retorna um par ``(transport, protocol)``." -#: ../../library/asyncio-eventloop.rst:870 +#: ../../library/asyncio-eventloop.rst:900 msgid "Transferring files" msgstr "Transferindo arquivos" -#: ../../library/asyncio-eventloop.rst:875 +#: ../../library/asyncio-eventloop.rst:906 msgid "" "Send a *file* over a *transport*. Return the total number of bytes sent." msgstr "" "Envia um *file* sobre um *transport*. Retorna o número total de bytes " "enviados." -#: ../../library/asyncio-eventloop.rst:878 +#: ../../library/asyncio-eventloop.rst:909 msgid "The method uses high-performance :meth:`os.sendfile` if available." msgstr "O método usa :meth:`os.sendfile` de alto desempenho, se disponível." -#: ../../library/asyncio-eventloop.rst:880 +#: ../../library/asyncio-eventloop.rst:911 msgid "*file* must be a regular file object opened in binary mode." msgstr "*file* deve ser um objeto arquivo regular aberto em modo binário." -#: ../../library/asyncio-eventloop.rst:882 -#: ../../library/asyncio-eventloop.rst:1127 +#: ../../library/asyncio-eventloop.rst:913 +#: ../../library/asyncio-eventloop.rst:1174 msgid "" "*offset* tells from where to start reading the file. If specified, *count* " "is the total number of bytes to transmit as opposed to sending the file " @@ -1444,7 +1482,7 @@ msgstr "" "meth:`file.tell() ` pode ser usado para obter o número atual " "de bytes enviados." -#: ../../library/asyncio-eventloop.rst:889 +#: ../../library/asyncio-eventloop.rst:920 msgid "" "*fallback* set to ``True`` makes asyncio to manually read and send the file " "when the platform does not support the sendfile system call (e.g. Windows or " @@ -1454,7 +1492,7 @@ msgstr "" "arquivo quando a plataforma não suporta a chamada de sistema sendfile (por " "exemplo Windows ou soquete SSL no Unix)." -#: ../../library/asyncio-eventloop.rst:893 +#: ../../library/asyncio-eventloop.rst:924 msgid "" "Raise :exc:`SendfileNotAvailableError` if the system does not support the " "*sendfile* syscall and *fallback* is ``False``." @@ -1462,22 +1500,22 @@ msgstr "" "Levanta :exc:`SendfileNotAvailableError` se o sistema não suporta a chamada " "de sistema *sendfile* e *fallback* é ``False``." -#: ../../library/asyncio-eventloop.rst:900 +#: ../../library/asyncio-eventloop.rst:931 msgid "TLS Upgrade" msgstr "Atualizando TLS" -#: ../../library/asyncio-eventloop.rst:907 +#: ../../library/asyncio-eventloop.rst:939 msgid "Upgrade an existing transport-based connection to TLS." msgstr "Atualiza um conexão baseada em transporte existente para TLS." -#: ../../library/asyncio-eventloop.rst:909 +#: ../../library/asyncio-eventloop.rst:941 msgid "" "Create a TLS coder/decoder instance and insert it between the *transport* " "and the *protocol*. The coder/decoder implements both *transport*-facing " "protocol and *protocol*-facing transport." msgstr "" -#: ../../library/asyncio-eventloop.rst:913 +#: ../../library/asyncio-eventloop.rst:945 msgid "" "Return the created two-interface instance. After *await*, the *protocol* " "must stop using the original *transport* and communicate with the returned " @@ -1485,13 +1523,13 @@ msgid "" "exchanges extra TLS session packets with *transport*." msgstr "" -#: ../../library/asyncio-eventloop.rst:918 +#: ../../library/asyncio-eventloop.rst:950 msgid "" "In some situations (e.g. when the passed transport is already closing) this " "may return ``None``." msgstr "" -#: ../../library/asyncio-eventloop.rst:923 +#: ../../library/asyncio-eventloop.rst:955 msgid "" "*transport* and *protocol* instances that methods like :meth:`~loop." "create_server` and :meth:`~loop.create_connection` return." @@ -1499,11 +1537,11 @@ msgstr "" "instâncias de *transport* e *protocol*, que métodos como :meth:`~loop." "create_server` e :meth:`~loop.create_connection` retornam." -#: ../../library/asyncio-eventloop.rst:927 +#: ../../library/asyncio-eventloop.rst:959 msgid "*sslcontext*: a configured instance of :class:`~ssl.SSLContext`." msgstr "*sslcontext*: uma instância configurada de :class:`~ssl.SSLContext`." -#: ../../library/asyncio-eventloop.rst:929 +#: ../../library/asyncio-eventloop.rst:961 msgid "" "*server_side* pass ``True`` when a server-side connection is being upgraded " "(like the one created by :meth:`~loop.create_server`)." @@ -1512,7 +1550,7 @@ msgstr "" "estiver sendo atualizada (como a que é criada por :meth:`~loop." "create_server`)." -#: ../../library/asyncio-eventloop.rst:932 +#: ../../library/asyncio-eventloop.rst:964 msgid "" "*server_hostname*: sets or overrides the host name that the target server's " "certificate will be matched against." @@ -1520,11 +1558,11 @@ msgstr "" "*server_hostname*: define ou substitui o nome do host no qual o servidor " "alvo do certificado será comparado." -#: ../../library/asyncio-eventloop.rst:952 +#: ../../library/asyncio-eventloop.rst:984 msgid "Watching file descriptors" msgstr "Observando descritores de arquivo" -#: ../../library/asyncio-eventloop.rst:956 +#: ../../library/asyncio-eventloop.rst:988 msgid "" "Start monitoring the *fd* file descriptor for read availability and invoke " "*callback* with the specified arguments once *fd* is available for reading." @@ -1533,13 +1571,20 @@ msgstr "" "leitura e invoca a *callback* com os argumentos especificados assim que *fd* " "esteja disponível para leitura." -#: ../../library/asyncio-eventloop.rst:962 +#: ../../library/asyncio-eventloop.rst:992 +#: ../../library/asyncio-eventloop.rst:1006 +msgid "" +"Any preexisting callback registered for *fd* is cancelled and replaced by " +"*callback*." +msgstr "" + +#: ../../library/asyncio-eventloop.rst:997 msgid "" "Stop monitoring the *fd* file descriptor for read availability. Returns " "``True`` if *fd* was previously being monitored for reads." msgstr "" -#: ../../library/asyncio-eventloop.rst:967 +#: ../../library/asyncio-eventloop.rst:1002 msgid "" "Start monitoring the *fd* file descriptor for write availability and invoke " "*callback* with the specified arguments once *fd* is available for writing." @@ -1548,8 +1593,8 @@ msgstr "" "escrita e invoca a *callback* com os argumentos especificados assim que *fd* " "esteja disponível para escrita." -#: ../../library/asyncio-eventloop.rst:971 -#: ../../library/asyncio-eventloop.rst:1236 +#: ../../library/asyncio-eventloop.rst:1009 +#: ../../library/asyncio-eventloop.rst:1287 msgid "" "Use :func:`functools.partial` :ref:`to pass keyword arguments ` to *callback*." @@ -1557,13 +1602,13 @@ msgstr "" "Use :func:`functools.partial` :ref:`para passar argumentos nomeados ` para a *callback*." -#: ../../library/asyncio-eventloop.rst:976 +#: ../../library/asyncio-eventloop.rst:1014 msgid "" "Stop monitoring the *fd* file descriptor for write availability. Returns " "``True`` if *fd* was previously being monitored for writes." msgstr "" -#: ../../library/asyncio-eventloop.rst:979 +#: ../../library/asyncio-eventloop.rst:1017 msgid "" "See also :ref:`Platform Support ` section for some " "limitations of these methods." @@ -1571,11 +1616,11 @@ msgstr "" "Veja também a seção de :ref:`Suporte a Plataformas ` para algumas limitações desses métodos." -#: ../../library/asyncio-eventloop.rst:984 +#: ../../library/asyncio-eventloop.rst:1022 msgid "Working with socket objects directly" msgstr "Trabalhando com objetos soquete diretamente" -#: ../../library/asyncio-eventloop.rst:986 +#: ../../library/asyncio-eventloop.rst:1024 msgid "" "In general, protocol implementations that use transport-based APIs such as :" "meth:`loop.create_connection` and :meth:`loop.create_server` are faster than " @@ -1589,7 +1634,7 @@ msgstr "" "Entretanto, existem alguns casos de uso quando o desempenho não é crítica, e " "trabalhar com objetos :class:`~socket.socket` diretamente é mais conveniente." -#: ../../library/asyncio-eventloop.rst:995 +#: ../../library/asyncio-eventloop.rst:1034 msgid "" "Receive up to *nbytes* from *sock*. Asynchronous version of :meth:`socket." "recv() `." @@ -1597,23 +1642,23 @@ msgstr "" "Recebe até *nbytes* do *sock*. Versão assíncrona de :meth:`socket.recv() " "`." -#: ../../library/asyncio-eventloop.rst:998 +#: ../../library/asyncio-eventloop.rst:1037 msgid "Return the received data as a bytes object." msgstr "Retorna os dados recebidos como um objeto de bytes." -#: ../../library/asyncio-eventloop.rst:1000 -#: ../../library/asyncio-eventloop.rst:1014 -#: ../../library/asyncio-eventloop.rst:1025 -#: ../../library/asyncio-eventloop.rst:1037 -#: ../../library/asyncio-eventloop.rst:1052 -#: ../../library/asyncio-eventloop.rst:1067 -#: ../../library/asyncio-eventloop.rst:1077 -#: ../../library/asyncio-eventloop.rst:1103 -#: ../../library/asyncio-eventloop.rst:1141 +#: ../../library/asyncio-eventloop.rst:1039 +#: ../../library/asyncio-eventloop.rst:1054 +#: ../../library/asyncio-eventloop.rst:1066 +#: ../../library/asyncio-eventloop.rst:1079 +#: ../../library/asyncio-eventloop.rst:1095 +#: ../../library/asyncio-eventloop.rst:1111 +#: ../../library/asyncio-eventloop.rst:1122 +#: ../../library/asyncio-eventloop.rst:1149 +#: ../../library/asyncio-eventloop.rst:1188 msgid "*sock* must be a non-blocking socket." msgstr "*sock* deve ser um soquete não bloqueante." -#: ../../library/asyncio-eventloop.rst:1002 +#: ../../library/asyncio-eventloop.rst:1041 msgid "" "Even though this method was always documented as a coroutine method, " "releases before Python 3.7 returned a :class:`Future`. Since Python 3.7 this " @@ -1623,7 +1668,7 @@ msgstr "" "versões anteriores ao Python 3.7 retornavam um :class:`Future`. Desde o " "Python 3.7 este é um método ``async def``." -#: ../../library/asyncio-eventloop.rst:1009 +#: ../../library/asyncio-eventloop.rst:1049 msgid "" "Receive data from *sock* into the *buf* buffer. Modeled after the blocking :" "meth:`socket.recv_into() ` method." @@ -1631,31 +1676,31 @@ msgstr "" "Dados recebidos do *sock* no buffer *buf*. Modelado baseado no método " "bloqueante :meth:`socket.recv_into() `." -#: ../../library/asyncio-eventloop.rst:1012 +#: ../../library/asyncio-eventloop.rst:1052 msgid "Return the number of bytes written to the buffer." msgstr "Retorna o número de bytes escritos no buffer." -#: ../../library/asyncio-eventloop.rst:1020 +#: ../../library/asyncio-eventloop.rst:1061 msgid "" "Receive a datagram of up to *bufsize* from *sock*. Asynchronous version of :" "meth:`socket.recvfrom() `." msgstr "" -#: ../../library/asyncio-eventloop.rst:1023 +#: ../../library/asyncio-eventloop.rst:1064 msgid "Return a tuple of (received data, remote address)." msgstr "" -#: ../../library/asyncio-eventloop.rst:1031 +#: ../../library/asyncio-eventloop.rst:1073 msgid "" "Receive a datagram of up to *nbytes* from *sock* into *buf*. Asynchronous " "version of :meth:`socket.recvfrom_into() `." msgstr "" -#: ../../library/asyncio-eventloop.rst:1035 +#: ../../library/asyncio-eventloop.rst:1077 msgid "Return a tuple of (number of bytes received, remote address)." msgstr "" -#: ../../library/asyncio-eventloop.rst:1043 +#: ../../library/asyncio-eventloop.rst:1086 msgid "" "Send *data* to the *sock* socket. Asynchronous version of :meth:`socket." "sendall() `." @@ -1663,7 +1708,7 @@ msgstr "" "Envia *data* para o soquete *sock*. Versão assíncrona de :meth:`socket." "sendall() `." -#: ../../library/asyncio-eventloop.rst:1046 +#: ../../library/asyncio-eventloop.rst:1089 msgid "" "This method continues to send to the socket until either all data in *data* " "has been sent or an error occurs. ``None`` is returned on success. On " @@ -1677,8 +1722,8 @@ msgstr "" "existe nenhuma forma de determinar quantos dados, se algum, foram " "processados com sucesso pelo destinatário na conexão." -#: ../../library/asyncio-eventloop.rst:1054 -#: ../../library/asyncio-eventloop.rst:1105 +#: ../../library/asyncio-eventloop.rst:1097 +#: ../../library/asyncio-eventloop.rst:1151 msgid "" "Even though the method was always documented as a coroutine method, before " "Python 3.7 it returned a :class:`Future`. Since Python 3.7, this is an " @@ -1688,26 +1733,26 @@ msgstr "" "antes do Python 3.7 ele retornava um :class:`Future`. Desde o Python 3.7, " "este é um método ``async def``." -#: ../../library/asyncio-eventloop.rst:1061 +#: ../../library/asyncio-eventloop.rst:1105 msgid "" "Send a datagram from *sock* to *address*. Asynchronous version of :meth:" "`socket.sendto() `." msgstr "" -#: ../../library/asyncio-eventloop.rst:1065 +#: ../../library/asyncio-eventloop.rst:1109 msgid "Return the number of bytes sent." msgstr "" -#: ../../library/asyncio-eventloop.rst:1073 +#: ../../library/asyncio-eventloop.rst:1118 msgid "Connect *sock* to a remote socket at *address*." msgstr "Conecta o *sock* em um endereço *address* remoto." -#: ../../library/asyncio-eventloop.rst:1075 +#: ../../library/asyncio-eventloop.rst:1120 msgid "" "Asynchronous version of :meth:`socket.connect() `." msgstr "Versão assíncrona de :meth:`socket.connect() `." -#: ../../library/asyncio-eventloop.rst:1079 +#: ../../library/asyncio-eventloop.rst:1124 msgid "" "``address`` no longer needs to be resolved. ``sock_connect`` will try to " "check if the *address* is already resolved by calling :func:`socket." @@ -1718,7 +1763,7 @@ msgstr "" "verificar se *address* já está resolvido chamando :func:`socket.inet_pton`. " "Se não estiver, :meth:`loop.getaddrinfo` será usado para resolver *address*." -#: ../../library/asyncio-eventloop.rst:1088 +#: ../../library/asyncio-eventloop.rst:1133 msgid "" ":meth:`loop.create_connection` and :func:`asyncio.open_connection() " "`." @@ -1726,7 +1771,7 @@ msgstr "" ":meth:`loop.create_connection` e :func:`asyncio.open_connection() " "`." -#: ../../library/asyncio-eventloop.rst:1094 +#: ../../library/asyncio-eventloop.rst:1140 msgid "" "Accept a connection. Modeled after the blocking :meth:`socket.accept() " "` method." @@ -1734,7 +1779,7 @@ msgstr "" "Aceita uma conexão. Modelado baseado no método bloqueante :meth:`socket." "accept() `." -#: ../../library/asyncio-eventloop.rst:1097 +#: ../../library/asyncio-eventloop.rst:1143 msgid "" "The socket must be bound to an address and listening for connections. The " "return value is a pair ``(conn, address)`` where *conn* is a *new* socket " @@ -1746,11 +1791,11 @@ msgstr "" "de soquete usável para enviar e receber dados na conexão, e *address* é o " "endereço vinculado ao soquete no outro extremo da conexão." -#: ../../library/asyncio-eventloop.rst:1112 +#: ../../library/asyncio-eventloop.rst:1158 msgid ":meth:`loop.create_server` and :func:`start_server`." msgstr ":meth:`loop.create_server` e :func:`start_server`." -#: ../../library/asyncio-eventloop.rst:1117 +#: ../../library/asyncio-eventloop.rst:1164 msgid "" "Send a file using high-performance :mod:`os.sendfile` if possible. Return " "the total number of bytes sent." @@ -1758,13 +1803,13 @@ msgstr "" "Envia um arquivo usando :mod:`os.sendfile` de alto desempenho se possível. " "Retorna o número total de bytes enviados." -#: ../../library/asyncio-eventloop.rst:1120 +#: ../../library/asyncio-eventloop.rst:1167 msgid "" "Asynchronous version of :meth:`socket.sendfile() `." msgstr "" "Versão assíncrona de :meth:`socket.sendfile() `." -#: ../../library/asyncio-eventloop.rst:1122 +#: ../../library/asyncio-eventloop.rst:1169 msgid "" "*sock* must be a non-blocking :const:`socket.SOCK_STREAM` :class:`~socket." "socket`." @@ -1772,11 +1817,11 @@ msgstr "" "*sock* deve ser um :class:`~socket.socket` :const:`socket.SOCK_STREAM` não " "bloqueante." -#: ../../library/asyncio-eventloop.rst:1125 +#: ../../library/asyncio-eventloop.rst:1172 msgid "*file* must be a regular file object open in binary mode." msgstr "*file* deve ser um objeto arquivo regular aberto em modo binário." -#: ../../library/asyncio-eventloop.rst:1134 +#: ../../library/asyncio-eventloop.rst:1181 msgid "" "*fallback*, when set to ``True``, makes asyncio manually read and send the " "file when the platform does not support the sendfile syscall (e.g. Windows " @@ -1786,7 +1831,7 @@ msgstr "" "manualmente o arquivo, quando a plataforma não suporta a chamada de sistema " "sendfile (por exemplo Windows ou soquete SSL no Unix)." -#: ../../library/asyncio-eventloop.rst:1138 +#: ../../library/asyncio-eventloop.rst:1185 msgid "" "Raise :exc:`SendfileNotAvailableError` if the system does not support " "*sendfile* syscall and *fallback* is ``False``." @@ -1794,19 +1839,19 @@ msgstr "" "Levanta :exc:`SendfileNotAvailableError` se o sistema não suporta chamadas " "de sistema *sendfile* e *fallback* é ``False``." -#: ../../library/asyncio-eventloop.rst:1147 +#: ../../library/asyncio-eventloop.rst:1194 msgid "DNS" msgstr "DNS" -#: ../../library/asyncio-eventloop.rst:1152 +#: ../../library/asyncio-eventloop.rst:1200 msgid "Asynchronous version of :meth:`socket.getaddrinfo`." msgstr "Versão assíncrona de :meth:`socket.getaddrinfo`." -#: ../../library/asyncio-eventloop.rst:1156 +#: ../../library/asyncio-eventloop.rst:1205 msgid "Asynchronous version of :meth:`socket.getnameinfo`." msgstr "Versão assíncrona de :meth:`socket.getnameinfo`." -#: ../../library/asyncio-eventloop.rst:1159 +#: ../../library/asyncio-eventloop.rst:1208 msgid "" "Both *getaddrinfo* and *getnameinfo* internally utilize their synchronous " "versions through the loop's default thread pool executor. When this executor " @@ -1816,7 +1861,7 @@ msgid "" "executor with a larger number of workers." msgstr "" -#: ../../library/asyncio-eventloop.rst:1166 +#: ../../library/asyncio-eventloop.rst:1215 msgid "" "Both *getaddrinfo* and *getnameinfo* methods were always documented to " "return a coroutine, but prior to Python 3.7 they were, in fact, returning :" @@ -1828,19 +1873,19 @@ msgstr "" "verdade, retornando objetos :class:`asyncio.Future`. A partir do Python 3.7, " "ambos os métodos são corrotinas." -#: ../../library/asyncio-eventloop.rst:1174 +#: ../../library/asyncio-eventloop.rst:1223 msgid "Working with pipes" msgstr "Trabalhando com encadeamentos" -#: ../../library/asyncio-eventloop.rst:1178 +#: ../../library/asyncio-eventloop.rst:1228 msgid "Register the read end of *pipe* in the event loop." msgstr "Registra o extremo da leitura de um *pipe* no laço de eventos." -#: ../../library/asyncio-eventloop.rst:1183 +#: ../../library/asyncio-eventloop.rst:1233 msgid "*pipe* is a :term:`file-like object `." msgstr "*pipe* é um :term:`objeto arquivo ou similar `." -#: ../../library/asyncio-eventloop.rst:1185 +#: ../../library/asyncio-eventloop.rst:1235 msgid "" "Return pair ``(transport, protocol)``, where *transport* supports the :class:" "`ReadTransport` interface and *protocol* is an object instantiated by the " @@ -1850,8 +1895,8 @@ msgstr "" "interface :class:`ReadTransport` e *protocol* é um objeto instanciado pelo " "*protocol_factory*." -#: ../../library/asyncio-eventloop.rst:1189 -#: ../../library/asyncio-eventloop.rst:1205 +#: ../../library/asyncio-eventloop.rst:1239 +#: ../../library/asyncio-eventloop.rst:1256 msgid "" "With :class:`SelectorEventLoop` event loop, the *pipe* is set to non-" "blocking mode." @@ -1859,15 +1904,15 @@ msgstr "" "Com o :class:`SelectorEventLoop` do laço de eventos, o *pipe* é definido " "para modo não bloqueante." -#: ../../library/asyncio-eventloop.rst:1194 +#: ../../library/asyncio-eventloop.rst:1245 msgid "Register the write end of *pipe* in the event loop." msgstr "Registra o extremo de escrita do *pipe* no laço de eventos." -#: ../../library/asyncio-eventloop.rst:1199 +#: ../../library/asyncio-eventloop.rst:1250 msgid "*pipe* is :term:`file-like object `." msgstr "*pipe* é um :term:`objeto arquivo ou similar `." -#: ../../library/asyncio-eventloop.rst:1201 +#: ../../library/asyncio-eventloop.rst:1252 msgid "" "Return pair ``(transport, protocol)``, where *transport* supports :class:" "`WriteTransport` interface and *protocol* is an object instantiated by the " @@ -1877,7 +1922,7 @@ msgstr "" "interface :class:`WriteTransport` e *protocol* é um objeto instanciado pelo " "*protocol_factory*." -#: ../../library/asyncio-eventloop.rst:1210 +#: ../../library/asyncio-eventloop.rst:1261 msgid "" ":class:`SelectorEventLoop` does not support the above methods on Windows. " "Use :class:`ProactorEventLoop` instead for Windows." @@ -1885,21 +1930,21 @@ msgstr "" ":class:`SelectorEventLoop` não suporta os métodos acima no Windows. Use :" "class:`ProactorEventLoop` ao invés para Windows." -#: ../../library/asyncio-eventloop.rst:1215 +#: ../../library/asyncio-eventloop.rst:1266 msgid "" "The :meth:`loop.subprocess_exec` and :meth:`loop.subprocess_shell` methods." msgstr "" "Os métodos :meth:`loop.subprocess_exec` e :meth:`loop.subprocess_shell`." -#: ../../library/asyncio-eventloop.rst:1220 +#: ../../library/asyncio-eventloop.rst:1271 msgid "Unix signals" msgstr "Sinais Unix" -#: ../../library/asyncio-eventloop.rst:1226 +#: ../../library/asyncio-eventloop.rst:1277 msgid "Set *callback* as the handler for the *signum* signal." msgstr "Define *callback* como o tratador para o sinal *signum*." -#: ../../library/asyncio-eventloop.rst:1228 +#: ../../library/asyncio-eventloop.rst:1279 msgid "" "The callback will be invoked by *loop*, along with other queued callbacks " "and runnable coroutines of that event loop. Unlike signal handlers " @@ -1912,7 +1957,7 @@ msgstr "" "uma função de retorno registrada com esta função tem autorização para " "interagir com o laço de eventos." -#: ../../library/asyncio-eventloop.rst:1233 +#: ../../library/asyncio-eventloop.rst:1284 msgid "" "Raise :exc:`ValueError` if the signal number is invalid or uncatchable. " "Raise :exc:`RuntimeError` if there is a problem setting up the handler." @@ -1921,18 +1966,18 @@ msgstr "" "capturar. Levanta :exc:`RuntimeError` se existe um problema definindo o " "tratador." -#: ../../library/asyncio-eventloop.rst:1239 +#: ../../library/asyncio-eventloop.rst:1290 msgid "" "Like :func:`signal.signal`, this function must be invoked in the main thread." msgstr "" "Assim como :func:`signal.signal`, esta função deve ser invocada na thread " "principal." -#: ../../library/asyncio-eventloop.rst:1244 +#: ../../library/asyncio-eventloop.rst:1295 msgid "Remove the handler for the *sig* signal." msgstr "Remove o tratador para o sinal *sig*." -#: ../../library/asyncio-eventloop.rst:1246 +#: ../../library/asyncio-eventloop.rst:1297 msgid "" "Return ``True`` if the signal handler was removed, or ``False`` if no " "handler was set for the given signal." @@ -1940,19 +1985,19 @@ msgstr "" "Retorna ``True`` se o tratador de sinal foi removido, ou ``False`` se nenhum " "tratador foi definido para o sinal fornecido." -#: ../../library/asyncio-eventloop.rst:1253 +#: ../../library/asyncio-eventloop.rst:1304 msgid "The :mod:`signal` module." msgstr "O módulo :mod:`signal`." -#: ../../library/asyncio-eventloop.rst:1257 +#: ../../library/asyncio-eventloop.rst:1308 msgid "Executing code in thread or process pools" msgstr "Executando código em conjuntos de threads ou processos" -#: ../../library/asyncio-eventloop.rst:1261 +#: ../../library/asyncio-eventloop.rst:1312 msgid "Arrange for *func* to be called in the specified executor." msgstr "Providencia para a *func* ser chamada no executor especificado." -#: ../../library/asyncio-eventloop.rst:1263 +#: ../../library/asyncio-eventloop.rst:1314 msgid "" "The *executor* argument should be an :class:`concurrent.futures.Executor` " "instance. The default executor is used if *executor* is ``None``. The " @@ -1961,7 +2006,50 @@ msgid "" "and used by :func:`run_in_executor` if needed." msgstr "" -#: ../../library/asyncio-eventloop.rst:1311 +#: ../../library/asyncio-eventloop.rst:1322 +msgid "" +"import asyncio\n" +"import concurrent.futures\n" +"\n" +"def blocking_io():\n" +" # File operations (such as logging) can block the\n" +" # event loop: run them in a thread pool.\n" +" with open('/dev/urandom', 'rb') as f:\n" +" return f.read(100)\n" +"\n" +"def cpu_bound():\n" +" # CPU-bound operations will block the event loop:\n" +" # in general it is preferable to run them in a\n" +" # process pool.\n" +" return sum(i * i for i in range(10 ** 7))\n" +"\n" +"async def main():\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" ## Options:\n" +"\n" +" # 1. Run in the default loop's executor:\n" +" result = await loop.run_in_executor(\n" +" None, blocking_io)\n" +" print('default thread pool', result)\n" +"\n" +" # 2. Run in a custom thread pool:\n" +" with concurrent.futures.ThreadPoolExecutor() as pool:\n" +" result = await loop.run_in_executor(\n" +" pool, blocking_io)\n" +" print('custom thread pool', result)\n" +"\n" +" # 3. Run in a custom process pool:\n" +" with concurrent.futures.ProcessPoolExecutor() as pool:\n" +" result = await loop.run_in_executor(\n" +" pool, cpu_bound)\n" +" print('custom process pool', result)\n" +"\n" +"if __name__ == '__main__':\n" +" asyncio.run(main())" +msgstr "" + +#: ../../library/asyncio-eventloop.rst:1362 msgid "" "Note that the entry point guard (``if __name__ == '__main__'``) is required " "for option 3 due to the peculiarities of :mod:`multiprocessing`, which is " @@ -1969,11 +2057,11 @@ msgid "" "importing of main module `." msgstr "" -#: ../../library/asyncio-eventloop.rst:1316 +#: ../../library/asyncio-eventloop.rst:1367 msgid "This method returns a :class:`asyncio.Future` object." msgstr "Este método retorna um objeto :class:`asyncio.Future`." -#: ../../library/asyncio-eventloop.rst:1318 +#: ../../library/asyncio-eventloop.rst:1369 msgid "" "Use :func:`functools.partial` :ref:`to pass keyword arguments ` to *func*." @@ -1981,7 +2069,7 @@ msgstr "" "Use :func:`functools.partial` :ref:`para passar argumentos nomeados ` para *func*." -#: ../../library/asyncio-eventloop.rst:1321 +#: ../../library/asyncio-eventloop.rst:1372 msgid "" ":meth:`loop.run_in_executor` no longer configures the ``max_workers`` of the " "thread pool executor it creates, instead leaving it up to the thread pool " @@ -1993,32 +2081,32 @@ msgstr "" "para o executor do conjunto de thread (:class:`~concurrent.futures." "ThreadPoolExecutor`) para setar o valor padrão." -#: ../../library/asyncio-eventloop.rst:1330 +#: ../../library/asyncio-eventloop.rst:1381 msgid "" "Set *executor* as the default executor used by :meth:`run_in_executor`. " "*executor* must be an instance of :class:`~concurrent.futures." "ThreadPoolExecutor`." msgstr "" -#: ../../library/asyncio-eventloop.rst:1334 +#: ../../library/asyncio-eventloop.rst:1385 msgid "" "*executor* must be an instance of :class:`~concurrent.futures." "ThreadPoolExecutor`." msgstr "" -#: ../../library/asyncio-eventloop.rst:1340 +#: ../../library/asyncio-eventloop.rst:1391 msgid "Error Handling API" msgstr "Tratando erros da API" -#: ../../library/asyncio-eventloop.rst:1342 +#: ../../library/asyncio-eventloop.rst:1393 msgid "Allows customizing how exceptions are handled in the event loop." msgstr "Permite customizar como exceções são tratadas no laço de eventos." -#: ../../library/asyncio-eventloop.rst:1346 +#: ../../library/asyncio-eventloop.rst:1397 msgid "Set *handler* as the new event loop exception handler." msgstr "Define *handler* como o novo tratador de exceções do laço de eventos." -#: ../../library/asyncio-eventloop.rst:1348 +#: ../../library/asyncio-eventloop.rst:1399 msgid "" "If *handler* is ``None``, the default exception handler will be set. " "Otherwise, *handler* must be a callable with the signature matching ``(loop, " @@ -2033,20 +2121,20 @@ msgstr "" "(veja a documentação :meth:`call_exception_handler` para detalhes a respeito " "do contexto)." -#: ../../library/asyncio-eventloop.rst:1356 +#: ../../library/asyncio-eventloop.rst:1407 msgid "" "If the handler is called on behalf of a :class:`~asyncio.Task` or :class:" "`~asyncio.Handle`, it is run in the :class:`contextvars.Context` of that " "task or callback handle." msgstr "" -#: ../../library/asyncio-eventloop.rst:1362 +#: ../../library/asyncio-eventloop.rst:1413 msgid "" "The handler may be called in the :class:`~contextvars.Context` of the task " "or handle where the exception originated." msgstr "" -#: ../../library/asyncio-eventloop.rst:1367 +#: ../../library/asyncio-eventloop.rst:1418 msgid "" "Return the current exception handler, or ``None`` if no custom exception " "handler was set." @@ -2054,11 +2142,11 @@ msgstr "" "Retorna o tratador de exceção atual, ou ``None`` se nenhum tratador de " "exceção customizado foi definido." -#: ../../library/asyncio-eventloop.rst:1374 +#: ../../library/asyncio-eventloop.rst:1425 msgid "Default exception handler." msgstr "Tratador de exceção padrão." -#: ../../library/asyncio-eventloop.rst:1376 +#: ../../library/asyncio-eventloop.rst:1427 msgid "" "This is called when an exception occurs and no exception handler is set. " "This can be called by a custom exception handler that wants to defer to the " @@ -2068,7 +2156,7 @@ msgstr "" "definido. Isso pode ser chamado por um tratador de exceção customizado que " "quer passar adiante para o comportamento do tratador padrão." -#: ../../library/asyncio-eventloop.rst:1380 +#: ../../library/asyncio-eventloop.rst:1431 msgid "" "*context* parameter has the same meaning as in :meth:" "`call_exception_handler`." @@ -2076,11 +2164,11 @@ msgstr "" "parâmetro *context* tem o mesmo significado que em :meth:" "`call_exception_handler`." -#: ../../library/asyncio-eventloop.rst:1385 +#: ../../library/asyncio-eventloop.rst:1436 msgid "Call the current event loop exception handler." msgstr "Chama o tratador de exceção do laço de eventos atual." -#: ../../library/asyncio-eventloop.rst:1387 +#: ../../library/asyncio-eventloop.rst:1438 msgid "" "*context* is a ``dict`` object containing the following keys (new keys may " "be introduced in future Python versions):" @@ -2088,66 +2176,71 @@ msgstr "" "*context* é um objeto ``dict`` contendo as seguintes chaves (novas chaves " "podem ser introduzidas em versões futuras do Python):" -#: ../../library/asyncio-eventloop.rst:1390 +#: ../../library/asyncio-eventloop.rst:1441 msgid "'message': Error message;" msgstr "'message': Mensagem de erro;" -#: ../../library/asyncio-eventloop.rst:1391 +#: ../../library/asyncio-eventloop.rst:1442 msgid "'exception' (optional): Exception object;" msgstr "'exception' (opcional): Objeto Exception;" -#: ../../library/asyncio-eventloop.rst:1392 +#: ../../library/asyncio-eventloop.rst:1443 msgid "'future' (optional): :class:`asyncio.Future` instance;" msgstr "'future' (opcional): instância de :class:`asyncio.Future`;" -#: ../../library/asyncio-eventloop.rst:1393 +#: ../../library/asyncio-eventloop.rst:1444 msgid "'task' (optional): :class:`asyncio.Task` instance;" msgstr "'task' (opcional): instância de :class:`asyncio.Task`;" -#: ../../library/asyncio-eventloop.rst:1394 +#: ../../library/asyncio-eventloop.rst:1445 msgid "'handle' (optional): :class:`asyncio.Handle` instance;" msgstr "'handle' (opcional): instância de :class:`asyncio.Handle`;" -#: ../../library/asyncio-eventloop.rst:1395 +#: ../../library/asyncio-eventloop.rst:1446 msgid "'protocol' (optional): :ref:`Protocol ` instance;" msgstr "" "'protocol' (opcional): instância de :ref:`Protocol `;" -#: ../../library/asyncio-eventloop.rst:1396 +#: ../../library/asyncio-eventloop.rst:1447 msgid "'transport' (optional): :ref:`Transport ` instance;" msgstr "" "'transport' (opcional): instância de :ref:`Transport `;" -#: ../../library/asyncio-eventloop.rst:1397 +#: ../../library/asyncio-eventloop.rst:1448 msgid "'socket' (optional): :class:`socket.socket` instance;" msgstr "'socket' (opcional): instância de :class:`socket.socket`;" -#: ../../library/asyncio-eventloop.rst:1398 +#: ../../library/asyncio-eventloop.rst:1449 +msgid "'source_traceback' (optional): Traceback of the source;" +msgstr "" + +#: ../../library/asyncio-eventloop.rst:1450 +msgid "'handle_traceback' (optional): Traceback of the handle;" +msgstr "" + +#: ../../library/asyncio-eventloop.rst:1451 msgid "'asyncgen' (optional): Asynchronous generator that caused" msgstr "'asyncgen' (opcional): Gerador assíncrono que causou" -#: ../../library/asyncio-eventloop.rst:1399 +#: ../../library/asyncio-eventloop.rst:1452 msgid "the exception." msgstr "a exceção." -#: ../../library/asyncio-eventloop.rst:1403 +#: ../../library/asyncio-eventloop.rst:1456 msgid "" "This method should not be overloaded in subclassed event loops. For custom " -"exception handling, use the :meth:`set_exception_handler()` method." +"exception handling, use the :meth:`set_exception_handler` method." msgstr "" -"Este método não deve ser substituído em subclasses de laços de evento. Para " -"tratamento de exceções customizadas, use o método :meth:" -"`set_exception_handler()`." -#: ../../library/asyncio-eventloop.rst:1408 +#: ../../library/asyncio-eventloop.rst:1461 msgid "Enabling debug mode" msgstr "Habilitando o modo de debug" -#: ../../library/asyncio-eventloop.rst:1412 +#: ../../library/asyncio-eventloop.rst:1465 msgid "Get the debug mode (:class:`bool`) of the event loop." msgstr "Obtém o modo de debug (:class:`bool`) do laço de eventos." -#: ../../library/asyncio-eventloop.rst:1414 +#: ../../library/asyncio-eventloop.rst:1467 msgid "" "The default value is ``True`` if the environment variable :envvar:" "`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False`` otherwise." @@ -2156,11 +2249,11 @@ msgstr "" "`PYTHONASYNCIODEBUG` estiver definida para uma string não vazia, ``False`` " "caso contrário." -#: ../../library/asyncio-eventloop.rst:1420 +#: ../../library/asyncio-eventloop.rst:1473 msgid "Set the debug mode of the event loop." msgstr "Define o modo de debug do laço de eventos." -#: ../../library/asyncio-eventloop.rst:1424 +#: ../../library/asyncio-eventloop.rst:1477 msgid "" "The new :ref:`Python Development Mode ` can now also be used to " "enable the debug mode." @@ -2168,26 +2261,26 @@ msgstr "" "O novo :ref:`Modo de Desenvolvimento do Python ` agora também pode " "ser usado para habilitar o modo de debug." -#: ../../library/asyncio-eventloop.rst:1429 +#: ../../library/asyncio-eventloop.rst:1482 msgid "" "This attribute can be used to set the minimum execution duration in seconds " "that is considered \"slow\". When debug mode is enabled, \"slow\" callbacks " "are logged." msgstr "" -#: ../../library/asyncio-eventloop.rst:1433 +#: ../../library/asyncio-eventloop.rst:1486 msgid "Default value is 100 milliseconds." msgstr "" -#: ../../library/asyncio-eventloop.rst:1437 +#: ../../library/asyncio-eventloop.rst:1490 msgid "The :ref:`debug mode of asyncio `." msgstr "O :ref:`modo de debug de asyncio `." -#: ../../library/asyncio-eventloop.rst:1441 +#: ../../library/asyncio-eventloop.rst:1494 msgid "Running Subprocesses" msgstr "Executando Subprocessos" -#: ../../library/asyncio-eventloop.rst:1443 +#: ../../library/asyncio-eventloop.rst:1496 msgid "" "Methods described in this subsections are low-level. In regular async/await " "code consider using the high-level :func:`asyncio.create_subprocess_shell` " @@ -2198,7 +2291,7 @@ msgstr "" "`asyncio.create_subprocess_shell` e :func:`asyncio.create_subprocess_exec` " "ao invés." -#: ../../library/asyncio-eventloop.rst:1450 +#: ../../library/asyncio-eventloop.rst:1503 msgid "" "On Windows, the default event loop :class:`ProactorEventLoop` supports " "subprocesses, whereas :class:`SelectorEventLoop` does not. See :ref:" @@ -2209,22 +2302,22 @@ msgstr "" "ref:`Suporte para subprocessos no Windows ` para " "detalhes." -#: ../../library/asyncio-eventloop.rst:1461 +#: ../../library/asyncio-eventloop.rst:1515 msgid "" "Create a subprocess from one or more string arguments specified by *args*." msgstr "" "Cria um subprocesso a partir de um ou mais argumentos de string " "especificados por *args*." -#: ../../library/asyncio-eventloop.rst:1464 +#: ../../library/asyncio-eventloop.rst:1518 msgid "*args* must be a list of strings represented by:" msgstr "*args* deve ser uma lista de strings representada por:" -#: ../../library/asyncio-eventloop.rst:1466 +#: ../../library/asyncio-eventloop.rst:1520 msgid ":class:`str`;" msgstr ":class:`str`;" -#: ../../library/asyncio-eventloop.rst:1467 +#: ../../library/asyncio-eventloop.rst:1521 msgid "" "or :class:`bytes`, encoded to the :ref:`filesystem encoding `." @@ -2232,7 +2325,7 @@ msgstr "" "ou :class:`bytes`, encodados na :ref:`codificação do sistema de arquivos " "`." -#: ../../library/asyncio-eventloop.rst:1470 +#: ../../library/asyncio-eventloop.rst:1524 msgid "" "The first string specifies the program executable, and the remaining strings " "specify the arguments. Together, string arguments form the ``argv`` of the " @@ -2242,7 +2335,7 @@ msgstr "" "remanescentes especificam os argumentos. Juntas, argumentos em string formam " "o ``argv`` do programa." -#: ../../library/asyncio-eventloop.rst:1474 +#: ../../library/asyncio-eventloop.rst:1528 msgid "" "This is similar to the standard library :class:`subprocess.Popen` class " "called with ``shell=False`` and the list of strings passed as the first " @@ -2255,7 +2348,7 @@ msgstr "" "argumento no qual é uma lista de strings, *subprocess_exec* recebe múltiplos " "argumentos string." -#: ../../library/asyncio-eventloop.rst:1480 +#: ../../library/asyncio-eventloop.rst:1534 msgid "" "The *protocol_factory* must be a callable returning a subclass of the :class:" "`asyncio.SubprocessProtocol` class." @@ -2263,29 +2356,29 @@ msgstr "" "O *protocol_factory* deve ser um chamável que retorne uma subclasse da " "classe :class:`asyncio.SubprocessProtocol`." -#: ../../library/asyncio-eventloop.rst:1483 +#: ../../library/asyncio-eventloop.rst:1537 msgid "Other parameters:" msgstr "Outros parâmetros:" -#: ../../library/asyncio-eventloop.rst:1485 +#: ../../library/asyncio-eventloop.rst:1539 msgid "*stdin* can be any of these:" msgstr "*stdin* pode ser qualquer um destes:" -#: ../../library/asyncio-eventloop.rst:1487 -#: ../../library/asyncio-eventloop.rst:1498 -#: ../../library/asyncio-eventloop.rst:1508 +#: ../../library/asyncio-eventloop.rst:1541 +#: ../../library/asyncio-eventloop.rst:1552 +#: ../../library/asyncio-eventloop.rst:1562 msgid "a file-like object" msgstr "" -#: ../../library/asyncio-eventloop.rst:1488 +#: ../../library/asyncio-eventloop.rst:1542 msgid "" "an existing file descriptor (a positive integer), for example those created " -"with :meth:`os.pipe()`" +"with :meth:`os.pipe`" msgstr "" -#: ../../library/asyncio-eventloop.rst:1489 -#: ../../library/asyncio-eventloop.rst:1499 -#: ../../library/asyncio-eventloop.rst:1509 +#: ../../library/asyncio-eventloop.rst:1543 +#: ../../library/asyncio-eventloop.rst:1553 +#: ../../library/asyncio-eventloop.rst:1563 msgid "" "the :const:`subprocess.PIPE` constant (default) which will create a new pipe " "and connect it," @@ -2293,9 +2386,9 @@ msgstr "" "a constante :const:`subprocess.PIPE` (padrão), a qual criará um novo " "encadeamento e conectar a ele," -#: ../../library/asyncio-eventloop.rst:1491 -#: ../../library/asyncio-eventloop.rst:1501 -#: ../../library/asyncio-eventloop.rst:1511 +#: ../../library/asyncio-eventloop.rst:1545 +#: ../../library/asyncio-eventloop.rst:1555 +#: ../../library/asyncio-eventloop.rst:1565 msgid "" "the value ``None`` which will make the subprocess inherit the file " "descriptor from this process" @@ -2303,9 +2396,9 @@ msgstr "" "o valor ``None``, o qual fará o subprocesso herdar o descritor de arquivo " "deste processo" -#: ../../library/asyncio-eventloop.rst:1493 -#: ../../library/asyncio-eventloop.rst:1503 -#: ../../library/asyncio-eventloop.rst:1513 +#: ../../library/asyncio-eventloop.rst:1547 +#: ../../library/asyncio-eventloop.rst:1557 +#: ../../library/asyncio-eventloop.rst:1567 msgid "" "the :const:`subprocess.DEVNULL` constant which indicates that the special :" "data:`os.devnull` file will be used" @@ -2313,15 +2406,15 @@ msgstr "" "a constante :const:`subprocess.DEVNULL`, a qual indica que o arquivo " "especial :data:`os.devnull` será usado" -#: ../../library/asyncio-eventloop.rst:1496 +#: ../../library/asyncio-eventloop.rst:1550 msgid "*stdout* can be any of these:" msgstr "*stdout* pode ser qualquer um destes:" -#: ../../library/asyncio-eventloop.rst:1506 +#: ../../library/asyncio-eventloop.rst:1560 msgid "*stderr* can be any of these:" msgstr "*stderr* pode ser qualquer um destes:" -#: ../../library/asyncio-eventloop.rst:1515 +#: ../../library/asyncio-eventloop.rst:1569 msgid "" "the :const:`subprocess.STDOUT` constant which will connect the standard " "error stream to the process' standard output stream" @@ -2329,7 +2422,7 @@ msgstr "" "a constante :const:`subprocess.STDOUT`, a qual irá conectar o stream de erro " "padrão ao stream de saída padrão do processo" -#: ../../library/asyncio-eventloop.rst:1518 +#: ../../library/asyncio-eventloop.rst:1572 msgid "" "All other keyword arguments are passed to :class:`subprocess.Popen` without " "interpretation, except for *bufsize*, *universal_newlines*, *shell*, *text*, " @@ -2340,7 +2433,7 @@ msgstr "" "*text*, *encoding* e *errors*, os quais não devem ser especificados de forma " "alguma." -#: ../../library/asyncio-eventloop.rst:1523 +#: ../../library/asyncio-eventloop.rst:1577 msgid "" "The ``asyncio`` subprocess API does not support decoding the streams as " "text. :func:`bytes.decode` can be used to convert the bytes returned from " @@ -2350,7 +2443,7 @@ msgstr "" "texto. :func:`bytes.decode` pode ser usado para converter os bytes " "retornados do stream para texto." -#: ../../library/asyncio-eventloop.rst:1527 +#: ../../library/asyncio-eventloop.rst:1581 msgid "" "If a file-like object passed as *stdin*, *stdout* or *stderr* represents a " "pipe, then the other side of this pipe should be registered with :meth:" @@ -2358,7 +2451,7 @@ msgid "" "the event loop." msgstr "" -#: ../../library/asyncio-eventloop.rst:1532 +#: ../../library/asyncio-eventloop.rst:1586 msgid "" "See the constructor of the :class:`subprocess.Popen` class for documentation " "on other arguments." @@ -2366,7 +2459,7 @@ msgstr "" "Veja o construtor da classe :class:`subprocess.Popen` para documentação " "sobre outros argumentos." -#: ../../library/asyncio-eventloop.rst:1535 +#: ../../library/asyncio-eventloop.rst:1589 msgid "" "Returns a pair of ``(transport, protocol)``, where *transport* conforms to " "the :class:`asyncio.SubprocessTransport` base class and *protocol* is an " @@ -2376,7 +2469,7 @@ msgstr "" "classe base :class:`asyncio.SubprocessTransport` e *protocol* é um objeto " "instanciado pelo *protocol_factory*." -#: ../../library/asyncio-eventloop.rst:1543 +#: ../../library/asyncio-eventloop.rst:1598 msgid "" "Create a subprocess from *cmd*, which can be a :class:`str` or a :class:" "`bytes` string encoded to the :ref:`filesystem encoding `, usando a sintaxe \"shell\" da plataforma." -#: ../../library/asyncio-eventloop.rst:1548 +#: ../../library/asyncio-eventloop.rst:1603 msgid "" "This is similar to the standard library :class:`subprocess.Popen` class " "called with ``shell=True``." @@ -2394,7 +2487,7 @@ msgstr "" "Isto é similar a classe :class:`subprocess.Popen` da biblioteca padrão sendo " "chanada com ``shell=True``." -#: ../../library/asyncio-eventloop.rst:1551 +#: ../../library/asyncio-eventloop.rst:1606 msgid "" "The *protocol_factory* must be a callable returning a subclass of the :class:" "`SubprocessProtocol` class." @@ -2402,7 +2495,7 @@ msgstr "" "O argumento *protocol_factory* deve ser um chamável que retorna uma " "subclasse da classe :class:`SubprocessProtocol`." -#: ../../library/asyncio-eventloop.rst:1554 +#: ../../library/asyncio-eventloop.rst:1609 msgid "" "See :meth:`~loop.subprocess_exec` for more details about the remaining " "arguments." @@ -2410,7 +2503,7 @@ msgstr "" "Veja :meth:`~loop.subprocess_exec` para mais detalhes sobre os argumentos " "remanescentes." -#: ../../library/asyncio-eventloop.rst:1557 +#: ../../library/asyncio-eventloop.rst:1612 msgid "" "Returns a pair of ``(transport, protocol)``, where *transport* conforms to " "the :class:`SubprocessTransport` base class and *protocol* is an object " @@ -2420,7 +2513,7 @@ msgstr "" "classe base :class:`SubprocessTransport` e *protocol* é um objeto " "instanciado pelo *protocol_factory*." -#: ../../library/asyncio-eventloop.rst:1562 +#: ../../library/asyncio-eventloop.rst:1617 msgid "" "It is the application's responsibility to ensure that all whitespace and " "special characters are quoted appropriately to avoid `shell injection " @@ -2436,11 +2529,11 @@ msgstr "" "usada para escapar espaços em branco e caracteres especiais apropriadamente " "em strings que serão usadas para construir comandos shell." -#: ../../library/asyncio-eventloop.rst:1571 +#: ../../library/asyncio-eventloop.rst:1626 msgid "Callback Handles" msgstr "Tratadores de função de retorno" -#: ../../library/asyncio-eventloop.rst:1575 +#: ../../library/asyncio-eventloop.rst:1630 msgid "" "A callback wrapper object returned by :meth:`loop.call_soon`, :meth:`loop." "call_soon_threadsafe`." @@ -2448,12 +2541,12 @@ msgstr "" "Um objeto invólucro de função de retorno retornado por :meth:`loop." "call_soon`, :meth:`loop.call_soon_threadsafe`." -#: ../../library/asyncio-eventloop.rst:1580 +#: ../../library/asyncio-eventloop.rst:1635 msgid "" "Return the :class:`contextvars.Context` object associated with the handle." msgstr "" -#: ../../library/asyncio-eventloop.rst:1587 +#: ../../library/asyncio-eventloop.rst:1642 msgid "" "Cancel the callback. If the callback has already been canceled or executed, " "this method has no effect." @@ -2461,11 +2554,11 @@ msgstr "" "Cancela a função de retorno. Se a função de retorno já tiver sido cancelada " "ou executada, este método não tem efeito." -#: ../../library/asyncio-eventloop.rst:1592 +#: ../../library/asyncio-eventloop.rst:1647 msgid "Return ``True`` if the callback was cancelled." msgstr "Retorna ``True`` se a função de retorno foi cancelada." -#: ../../library/asyncio-eventloop.rst:1598 +#: ../../library/asyncio-eventloop.rst:1653 msgid "" "A callback wrapper object returned by :meth:`loop.call_later`, and :meth:" "`loop.call_at`." @@ -2473,17 +2566,17 @@ msgstr "" "Um objeto invólucro de função de retorno retornado por :meth:`loop." "call_later`, e :meth:`loop.call_at`." -#: ../../library/asyncio-eventloop.rst:1601 +#: ../../library/asyncio-eventloop.rst:1656 msgid "This class is a subclass of :class:`Handle`." msgstr "Esta classe é uma subclasse de :class:`Handle`." -#: ../../library/asyncio-eventloop.rst:1605 +#: ../../library/asyncio-eventloop.rst:1660 msgid "Return a scheduled callback time as :class:`float` seconds." msgstr "" "Retorna o tempo de uma função de retorno agendada como :class:`float` " "segundos." -#: ../../library/asyncio-eventloop.rst:1607 +#: ../../library/asyncio-eventloop.rst:1662 msgid "" "The time is an absolute timestamp, using the same time reference as :meth:" "`loop.time`." @@ -2491,11 +2584,11 @@ msgstr "" "O tempo é um timestamp absoluto, usando a mesma referência de tempo que :" "meth:`loop.time`." -#: ../../library/asyncio-eventloop.rst:1614 +#: ../../library/asyncio-eventloop.rst:1669 msgid "Server Objects" msgstr "Objetos Server" -#: ../../library/asyncio-eventloop.rst:1616 +#: ../../library/asyncio-eventloop.rst:1671 msgid "" "Server objects are created by :meth:`loop.create_server`, :meth:`loop." "create_unix_server`, :func:`start_server`, and :func:`start_unix_server` " @@ -2504,11 +2597,11 @@ msgstr "" "Objetos Server são criados pelas funções :meth:`loop.create_server`, :meth:" "`loop.create_unix_server`, :func:`start_server`, e :func:`start_unix_server`." -#: ../../library/asyncio-eventloop.rst:1620 +#: ../../library/asyncio-eventloop.rst:1675 msgid "Do not instantiate the :class:`Server` class directly." msgstr "" -#: ../../library/asyncio-eventloop.rst:1624 +#: ../../library/asyncio-eventloop.rst:1679 msgid "" "*Server* objects are asynchronous context managers. When used in an ``async " "with`` statement, it's guaranteed that the Server object is closed and not " @@ -2519,18 +2612,34 @@ msgstr "" "não está aceitando novas conexões quando a instrução ``async with`` estiver " "completa::" -#: ../../library/asyncio-eventloop.rst:1637 +#: ../../library/asyncio-eventloop.rst:1684 +msgid "" +"srv = await loop.create_server(...)\n" +"\n" +"async with srv:\n" +" # some code\n" +"\n" +"# At this point, srv is closed and no longer accepts new connections." +msgstr "" +"srv = await loop.create_server(...)\n" +"\n" +"async with srv:\n" +" # algum código\n" +"\n" +"# Neste ponto, srv é fechado e não mais aceita novas conexões." + +#: ../../library/asyncio-eventloop.rst:1692 msgid "Server object is an asynchronous context manager since Python 3.7." msgstr "" "Objeto Server é um gerenciador de contexto assíncrono desde o Python 3.7." -#: ../../library/asyncio-eventloop.rst:1640 +#: ../../library/asyncio-eventloop.rst:1695 msgid "" "This class was exposed publicly as ``asyncio.Server`` in Python 3.9.11, " "3.10.3 and 3.11." msgstr "" -#: ../../library/asyncio-eventloop.rst:1645 +#: ../../library/asyncio-eventloop.rst:1700 msgid "" "Stop serving: close listening sockets and set the :attr:`sockets` attribute " "to ``None``." @@ -2538,7 +2647,7 @@ msgstr "" "Para de servir: fecha soquetes que estavam ouvindo e define o atributo :attr:" "`sockets` para ``None``." -#: ../../library/asyncio-eventloop.rst:1648 +#: ../../library/asyncio-eventloop.rst:1703 msgid "" "The sockets that represent existing incoming client connections are left " "open." @@ -2546,59 +2655,59 @@ msgstr "" "Os soquetes que representam conexões de clientes existentes que estão " "chegando são deixados em aberto." -#: ../../library/asyncio-eventloop.rst:1651 +#: ../../library/asyncio-eventloop.rst:1706 msgid "" "The server is closed asynchronously; use the :meth:`wait_closed` coroutine " "to wait until the server is closed (and no more connections are active)." msgstr "" -#: ../../library/asyncio-eventloop.rst:1657 +#: ../../library/asyncio-eventloop.rst:1712 msgid "Close all existing incoming client connections." msgstr "" -#: ../../library/asyncio-eventloop.rst:1659 +#: ../../library/asyncio-eventloop.rst:1714 msgid "" "Calls :meth:`~asyncio.BaseTransport.close` on all associated transports." msgstr "" -#: ../../library/asyncio-eventloop.rst:1662 +#: ../../library/asyncio-eventloop.rst:1717 msgid "" ":meth:`close` should be called before :meth:`close_clients` when closing the " "server to avoid races with new clients connecting." msgstr "" -#: ../../library/asyncio-eventloop.rst:1669 +#: ../../library/asyncio-eventloop.rst:1724 msgid "" "Close all existing incoming client connections immediately, without waiting " "for pending operations to complete." msgstr "" -#: ../../library/asyncio-eventloop.rst:1672 +#: ../../library/asyncio-eventloop.rst:1727 msgid "" "Calls :meth:`~asyncio.WriteTransport.abort` on all associated transports." msgstr "" -#: ../../library/asyncio-eventloop.rst:1675 +#: ../../library/asyncio-eventloop.rst:1730 msgid "" ":meth:`close` should be called before :meth:`abort_clients` when closing the " "server to avoid races with new clients connecting." msgstr "" -#: ../../library/asyncio-eventloop.rst:1682 +#: ../../library/asyncio-eventloop.rst:1737 msgid "Return the event loop associated with the server object." msgstr "Retorna o laço de eventos associado com o objeto server." -#: ../../library/asyncio-eventloop.rst:1688 +#: ../../library/asyncio-eventloop.rst:1744 msgid "Start accepting connections." msgstr "Começa a aceitar conexões." -#: ../../library/asyncio-eventloop.rst:1690 +#: ../../library/asyncio-eventloop.rst:1746 msgid "" "This method is idempotent, so it can be called when the server is already " "serving." msgstr "" -#: ../../library/asyncio-eventloop.rst:1693 +#: ../../library/asyncio-eventloop.rst:1749 msgid "" "The *start_serving* keyword-only parameter to :meth:`loop.create_server` " "and :meth:`asyncio.start_server` allows creating a Server object that is not " @@ -2612,7 +2721,7 @@ msgstr "" "meth:`Server.serve_forever` podem ser usados para fazer o Server começar a " "aceitar conexões." -#: ../../library/asyncio-eventloop.rst:1704 +#: ../../library/asyncio-eventloop.rst:1761 msgid "" "Start accepting connections until the coroutine is cancelled. Cancellation " "of ``serve_forever`` task causes the server to be closed." @@ -2620,7 +2729,7 @@ msgstr "" "Começa a aceitar conexões até que a corrotina seja cancelada. Cancelamento " "da task ``serve_forever`` causa o fechamento do servidor." -#: ../../library/asyncio-eventloop.rst:1708 +#: ../../library/asyncio-eventloop.rst:1765 msgid "" "This method can be called if the server is already accepting connections. " "Only one ``serve_forever`` task can exist per one *Server* object." @@ -2628,23 +2737,38 @@ msgstr "" "Este método pode ser chamado se o servidor já estiver aceitando conexões. " "Apenas uma task ``serve_forever`` pode existir para cada objeto *Server*." -#: ../../library/asyncio-eventloop.rst:1730 +#: ../../library/asyncio-eventloop.rst:1771 +msgid "" +"async def client_connected(reader, writer):\n" +" # Communicate with the client with\n" +" # reader/writer streams. For example:\n" +" await reader.readline()\n" +"\n" +"async def main(host, port):\n" +" srv = await asyncio.start_server(\n" +" client_connected, host, port)\n" +" await srv.serve_forever()\n" +"\n" +"asyncio.run(main('127.0.0.1', 0))" +msgstr "" + +#: ../../library/asyncio-eventloop.rst:1787 msgid "Return ``True`` if the server is accepting new connections." msgstr "Retorna ``True`` se o servidor estiver aceitando novas conexões." -#: ../../library/asyncio-eventloop.rst:1736 +#: ../../library/asyncio-eventloop.rst:1794 msgid "" "Wait until the :meth:`close` method completes and all active connections " "have finished." msgstr "" -#: ../../library/asyncio-eventloop.rst:1741 +#: ../../library/asyncio-eventloop.rst:1799 msgid "" "List of socket-like objects, ``asyncio.trsock.TransportSocket``, which the " "server is listening on." msgstr "" -#: ../../library/asyncio-eventloop.rst:1744 +#: ../../library/asyncio-eventloop.rst:1802 msgid "" "Prior to Python 3.7 ``Server.sockets`` used to return an internal list of " "server sockets directly. In 3.7 a copy of that list is returned." @@ -2653,11 +2777,11 @@ msgstr "" "interna de soquetes do server diretamente. No uma cópia dessa lista é " "retornada." -#: ../../library/asyncio-eventloop.rst:1754 +#: ../../library/asyncio-eventloop.rst:1812 msgid "Event Loop Implementations" msgstr "Implementações do Laço de Eventos" -#: ../../library/asyncio-eventloop.rst:1756 +#: ../../library/asyncio-eventloop.rst:1814 msgid "" "asyncio ships with two different event loop implementations: :class:" "`SelectorEventLoop` and :class:`ProactorEventLoop`." @@ -2665,17 +2789,17 @@ msgstr "" "asyncio vem com duas implementações de laço de eventos diferente: :class:" "`SelectorEventLoop` e :class:`ProactorEventLoop`." -#: ../../library/asyncio-eventloop.rst:1759 +#: ../../library/asyncio-eventloop.rst:1817 msgid "By default asyncio is configured to use :class:`EventLoop`." msgstr "" -#: ../../library/asyncio-eventloop.rst:1764 +#: ../../library/asyncio-eventloop.rst:1822 msgid "" "A subclass of :class:`AbstractEventLoop` based on the :mod:`selectors` " "module." msgstr "" -#: ../../library/asyncio-eventloop.rst:1767 +#: ../../library/asyncio-eventloop.rst:1825 msgid "" "Uses the most efficient *selector* available for the given platform. It is " "also possible to manually configure the exact selector implementation to be " @@ -2685,55 +2809,58 @@ msgstr "" "Também é possível configurar manualmente a implementação exata do seletor a " "ser utilizada::" -#: ../../library/asyncio-eventloop.rst:1782 -msgid ":ref:`Availability `: Unix, Windows." -msgstr ":ref:`Disponibilidade`: Unix, Windows." +#: ../../library/asyncio-eventloop.rst:1829 +msgid "" +"import asyncio\n" +"import selectors\n" +"\n" +"class MyPolicy(asyncio.DefaultEventLoopPolicy):\n" +" def new_event_loop(self):\n" +" selector = selectors.SelectSelector()\n" +" return asyncio.SelectorEventLoop(selector)\n" +"\n" +"asyncio.set_event_loop_policy(MyPolicy())" +msgstr "" -#: ../../library/asyncio-eventloop.rst:1787 +#: ../../library/asyncio-eventloop.rst:1845 msgid "" "A subclass of :class:`AbstractEventLoop` for Windows that uses \"I/O " "Completion Ports\" (IOCP)." msgstr "" -#: ../../library/asyncio-eventloop.rst:1789 -msgid ":ref:`Availability `: Windows." -msgstr ":ref:`Disponibilidade `: Windows." - -#: ../../library/asyncio-eventloop.rst:1793 +#: ../../library/asyncio-eventloop.rst:1851 msgid "" -"`MSDN documentation on I/O Completion Ports `_." +"`MSDN documentation on I/O Completion Ports `_." msgstr "" -"`Documentação da MSDN sobre conclusão de portas I/O `_." -#: ../../library/asyncio-eventloop.rst:1798 +#: ../../library/asyncio-eventloop.rst:1856 msgid "" "An alias to the most efficient available subclass of :class:" "`AbstractEventLoop` for the given platform." msgstr "" -#: ../../library/asyncio-eventloop.rst:1801 +#: ../../library/asyncio-eventloop.rst:1859 msgid "" "It is an alias to :class:`SelectorEventLoop` on Unix and :class:" "`ProactorEventLoop` on Windows." msgstr "" -#: ../../library/asyncio-eventloop.rst:1807 +#: ../../library/asyncio-eventloop.rst:1865 msgid "Abstract base class for asyncio-compliant event loops." msgstr "Classe base abstrata para laços de eventos compatíveis com asyncio." -#: ../../library/asyncio-eventloop.rst:1809 +#: ../../library/asyncio-eventloop.rst:1867 msgid "" "The :ref:`asyncio-event-loop-methods` section lists all methods that an " "alternative implementation of ``AbstractEventLoop`` should have defined." msgstr "" -#: ../../library/asyncio-eventloop.rst:1815 +#: ../../library/asyncio-eventloop.rst:1873 msgid "Examples" msgstr "Exemplos" -#: ../../library/asyncio-eventloop.rst:1817 +#: ../../library/asyncio-eventloop.rst:1875 msgid "" "Note that all examples in this section **purposefully** show how to use the " "low-level event loop APIs, such as :meth:`loop.run_forever` and :meth:`loop." @@ -2746,11 +2873,11 @@ msgstr "" "precisam ser escritas desta forma; considere usar as funções de alto nível " "como :func:`asyncio.run`." -#: ../../library/asyncio-eventloop.rst:1827 +#: ../../library/asyncio-eventloop.rst:1885 msgid "Hello World with call_soon()" msgstr "Hello World com call_soon()" -#: ../../library/asyncio-eventloop.rst:1829 +#: ../../library/asyncio-eventloop.rst:1887 msgid "" "An example using the :meth:`loop.call_soon` method to schedule a callback. " "The callback displays ``\"Hello World\"`` and then stops the event loop::" @@ -2759,7 +2886,28 @@ msgstr "" "retorno. A função de retorno exibe ``\"Hello World\"`` e então para o laço " "de eventos::" -#: ../../library/asyncio-eventloop.rst:1853 +#: ../../library/asyncio-eventloop.rst:1891 +msgid "" +"import asyncio\n" +"\n" +"def hello_world(loop):\n" +" \"\"\"A callback to print 'Hello World' and stop the event loop\"\"\"\n" +" print('Hello World')\n" +" loop.stop()\n" +"\n" +"loop = asyncio.new_event_loop()\n" +"\n" +"# Schedule a call to hello_world()\n" +"loop.call_soon(hello_world, loop)\n" +"\n" +"# Blocking call interrupted by loop.stop()\n" +"try:\n" +" loop.run_forever()\n" +"finally:\n" +" loop.close()" +msgstr "" + +#: ../../library/asyncio-eventloop.rst:1911 msgid "" "A similar :ref:`Hello World ` example created with a coroutine " "and the :func:`run` function." @@ -2767,11 +2915,11 @@ msgstr "" "Um exemplo similar a :ref:`Hello World ` criado com uma corrotina " "e a função :func:`run`." -#: ../../library/asyncio-eventloop.rst:1860 +#: ../../library/asyncio-eventloop.rst:1918 msgid "Display the current date with call_later()" msgstr "Exibe a data atual com call_later()" -#: ../../library/asyncio-eventloop.rst:1862 +#: ../../library/asyncio-eventloop.rst:1920 msgid "" "An example of a callback displaying the current date every second. The " "callback uses the :meth:`loop.call_later` method to reschedule itself after " @@ -2781,7 +2929,32 @@ msgstr "" "função de retorno usa o método :meth:`loop.call_later` para reagendar a si " "mesma depois de 5 segundos, e então para o laço de eventos::" -#: ../../library/asyncio-eventloop.rst:1890 +#: ../../library/asyncio-eventloop.rst:1924 +msgid "" +"import asyncio\n" +"import datetime\n" +"\n" +"def display_date(end_time, loop):\n" +" print(datetime.datetime.now())\n" +" if (loop.time() + 1.0) < end_time:\n" +" loop.call_later(1, display_date, end_time, loop)\n" +" else:\n" +" loop.stop()\n" +"\n" +"loop = asyncio.new_event_loop()\n" +"\n" +"# Schedule the first call to display_date()\n" +"end_time = loop.time() + 5.0\n" +"loop.call_soon(display_date, end_time, loop)\n" +"\n" +"# Blocking call interrupted by loop.stop()\n" +"try:\n" +" loop.run_forever()\n" +"finally:\n" +" loop.close()" +msgstr "" + +#: ../../library/asyncio-eventloop.rst:1948 msgid "" "A similar :ref:`current date ` example created with a " "coroutine and the :func:`run` function." @@ -2789,11 +2962,11 @@ msgstr "" "Um exemplo similar a :ref:`data atual ` criado com " "uma corrotina e a função :func:`run`." -#: ../../library/asyncio-eventloop.rst:1897 +#: ../../library/asyncio-eventloop.rst:1955 msgid "Watch a file descriptor for read events" msgstr "Observa um descritor de arquivo por eventos de leitura" -#: ../../library/asyncio-eventloop.rst:1899 +#: ../../library/asyncio-eventloop.rst:1957 msgid "" "Wait until a file descriptor received some data using the :meth:`loop." "add_reader` method and then close the event loop::" @@ -2801,7 +2974,43 @@ msgstr "" "Aguarda até que um descritor de arquivo tenha recebido alguns dados usando o " "método :meth:`loop.add_reader` e então fecha o laço de eventos::" -#: ../../library/asyncio-eventloop.rst:1937 +#: ../../library/asyncio-eventloop.rst:1960 +msgid "" +"import asyncio\n" +"from socket import socketpair\n" +"\n" +"# Create a pair of connected file descriptors\n" +"rsock, wsock = socketpair()\n" +"\n" +"loop = asyncio.new_event_loop()\n" +"\n" +"def reader():\n" +" data = rsock.recv(100)\n" +" print(\"Received:\", data.decode())\n" +"\n" +" # We are done: unregister the file descriptor\n" +" loop.remove_reader(rsock)\n" +"\n" +" # Stop the event loop\n" +" loop.stop()\n" +"\n" +"# Register the file descriptor for read event\n" +"loop.add_reader(rsock, reader)\n" +"\n" +"# Simulate the reception of data from the network\n" +"loop.call_soon(wsock.send, 'abc'.encode())\n" +"\n" +"try:\n" +" # Run the event loop\n" +" loop.run_forever()\n" +"finally:\n" +" # We are done. Close sockets and the event loop.\n" +" rsock.close()\n" +" wsock.close()\n" +" loop.close()" +msgstr "" + +#: ../../library/asyncio-eventloop.rst:1995 msgid "" "A similar :ref:`example ` using " "transports, protocols, and the :meth:`loop.create_connection` method." @@ -2809,7 +3018,7 @@ msgstr "" "Um :ref:`exemplo ` similar usando " "transportes, protocolos, e o método :meth:`loop.create_connection`." -#: ../../library/asyncio-eventloop.rst:1941 +#: ../../library/asyncio-eventloop.rst:1999 msgid "" "Another similar :ref:`example ` " "using the high-level :func:`asyncio.open_connection` function and streams." @@ -2817,16 +3026,43 @@ msgstr "" "Outro :ref:`exemplo ` similar " "usando a função de alto nível :func:`asyncio.open_connection` e streams." -#: ../../library/asyncio-eventloop.rst:1949 +#: ../../library/asyncio-eventloop.rst:2007 msgid "Set signal handlers for SIGINT and SIGTERM" msgstr "Define tratadores de sinais para SIGINT e SIGTERM" -#: ../../library/asyncio-eventloop.rst:1951 +#: ../../library/asyncio-eventloop.rst:2009 msgid "(This ``signals`` example only works on Unix.)" msgstr "(Este exemplo de ``signals`` apenas funciona no Unix.)" -#: ../../library/asyncio-eventloop.rst:1953 +#: ../../library/asyncio-eventloop.rst:2011 msgid "" "Register handlers for signals :const:`~signal.SIGINT` and :const:`~signal." "SIGTERM` using the :meth:`loop.add_signal_handler` method::" msgstr "" + +#: ../../library/asyncio-eventloop.rst:2014 +msgid "" +"import asyncio\n" +"import functools\n" +"import os\n" +"import signal\n" +"\n" +"def ask_exit(signame, loop):\n" +" print(\"got signal %s: exit\" % signame)\n" +" loop.stop()\n" +"\n" +"async def main():\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" for signame in {'SIGINT', 'SIGTERM'}:\n" +" loop.add_signal_handler(\n" +" getattr(signal, signame),\n" +" functools.partial(ask_exit, signame, loop))\n" +"\n" +" await asyncio.sleep(3600)\n" +"\n" +"print(\"Event loop running for 1 hour, press Ctrl+C to interrupt.\")\n" +"print(f\"pid {os.getpid()}: send SIGINT or SIGTERM to exit.\")\n" +"\n" +"asyncio.run(main())" +msgstr "" diff --git a/library/asyncio-exceptions.po b/library/asyncio-exceptions.po index 393d5bc02..dca6f6c05 100644 --- a/library/asyncio-exceptions.po +++ b/library/asyncio-exceptions.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Leticia Portella , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:54+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/asyncio-extending.po b/library/asyncio-extending.po index 2693205be..677798eca 100644 --- a/library/asyncio-extending.po +++ b/library/asyncio-extending.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rodrigo Vitorino, 2022 -# Juliana Barros Lima, 2022 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2022-11-05 19:48+0000\n" -"Last-Translator: Juliana Barros Lima, 2022\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -33,22 +32,22 @@ msgid "" "The main direction for :mod:`asyncio` extending is writing custom *event " "loop* classes. Asyncio has helpers that could be used to simplify this task." msgstr "" -"A direção principal para a extensão :mod:`asyncio` é escrever classes " -"personalizadas de *event loop*. Asyncio tem auxiliares que podem ser usados " -"para simplificar esta tarefa." +"A direção principal para estender o módulo :mod:`asyncio` é escrever classes " +"de *laços de eventos* personalizados. O Asyncio tem funções auxiliares que " +"podem ser usadas para simplificar essa tarefa." #: ../../library/asyncio-extending.rst:13 msgid "" "Third-parties should reuse existing asyncio code with caution, a new Python " "version is free to break backward compatibility in *internal* part of API." msgstr "" -"Terceiros devem reutilizar o código assíncrono existente com cuidado, uma " -"versão nova do Python pode quebrar a compatibilidade com versões anteriores " +"Terceiros devem reutilizar o código assíncrono existente com cuidado. Uma " +"versão nova de Python pode quebrar a compatibilidade com versões anteriores " "da parte *interna* da API." #: ../../library/asyncio-extending.rst:19 msgid "Writing a Custom Event Loop" -msgstr "Escrevendo um loop de evento personalizado" +msgstr "Escrevendo um laço de eventos personalizado" #: ../../library/asyncio-extending.rst:21 msgid "" @@ -63,8 +62,8 @@ msgid "" "A loop can get many common methods implementation for free by inheriting " "from :class:`asyncio.BaseEventLoop`." msgstr "" -"Um laço de repetição pode receber, através de herança, vários métodos de " -"implementação da classe :class:`asyncio.BaseEventLoop`." +"Um laço de eventos pode herdar várias implementações de métodos da classe :" +"class:`asyncio.BaseEventLoop`." #: ../../library/asyncio-extending.rst:27 msgid "" @@ -82,15 +81,13 @@ msgid "" "not documented and is considered as an *internal* API." msgstr "" "Por exemplo, ``loop.create_connection()``verifica os argumentos, resolve " -"alguns endereços DNS, e chama a função ``loop._make_socket_transport()`` que " -"deve ser implementada por ser uma classe herdada. " -"O " -"método``_make_socket_transport()`` não está documentado e é considerado " -"parte de uma API *interna*." +"endereços DNS, e chama a função ``loop._make_socket_transport()``, que deve " +"ser implementada pela classe herdada. O método``_make_socket_transport()`` " +"não está documentado, e é considerado parte de uma API *interna*." #: ../../library/asyncio-extending.rst:38 msgid "Future and Task private constructors" -msgstr "Construtores privados Future e Task" +msgstr "Construtores privados de Future e Task" #: ../../library/asyncio-extending.rst:40 msgid "" @@ -99,9 +96,9 @@ msgid "" "`loop.create_task`, or :func:`asyncio.create_task` factories instead." msgstr "" "As classes :class:`asyncio.Future` e :class:`asyncio.Task` nunca deverão ser " -"criadas diretamente, por favor, substitua pelas factories correspondentes: :" -"meth:`loop.create_future` e :meth:`loop.create_task` ou :func:`asyncio." -"create_task`." +"criadas diretamente. Por favor, as substitua pelas *factories* " +"correspondentes: :meth:`loop.create_future` e :meth:`loop.create_task` ou :" +"func:`asyncio.create_task`." #: ../../library/asyncio-extending.rst:44 msgid "" @@ -109,40 +106,40 @@ msgid "" "implementations for the sake of getting a complex and highly optimized code " "for free." msgstr "" -"Porém *event-loops* de terceiros podem *reusar* as implementações nativas de " -"Future e Task em detrimento de obter um código complexo e mais otimizado." +"Porém, *laços de eventos* de terceiros podem *reutilizar* as implementações " +"embutidas de Future e Task, obtendo um código complexo e altamente otimizado." #: ../../library/asyncio-extending.rst:47 msgid "For this purpose the following, *private* constructors are listed:" -msgstr "" -"Com este propósito, os seguintes construtores *privados* serão listados a " -"seguir:" +msgstr "Por isso, segue a listagem de construtores *privados*:" #: ../../library/asyncio-extending.rst:51 msgid "Create a built-in future instance." -msgstr "Criar uma uma instância Future nativa." +msgstr "Cria uma instância de Future embutida." #: ../../library/asyncio-extending.rst:53 msgid "*loop* is an optional event loop instance." -msgstr "*loop* é uma instância opcional do event-loop." +msgstr "*loop* é uma instância opcional do laço de eventos." #: ../../library/asyncio-extending.rst:57 msgid "Create a built-in task instance." -msgstr "" +msgstr "Cria uma instância embutida de Task." #: ../../library/asyncio-extending.rst:59 msgid "" "*loop* is an optional event loop instance. The rest of arguments are " "described in :meth:`loop.create_task` description." msgstr "" +"*loop* é uma instância opcional do laço de eventos. Os outros argumentos " +"estão descritos em :meth:`loop.create_task`." #: ../../library/asyncio-extending.rst:64 msgid "*context* argument is added." -msgstr "" +msgstr "o argumento *context* foi adicionado" #: ../../library/asyncio-extending.rst:69 msgid "Task lifetime support" -msgstr "" +msgstr "Suporte ao ciclo de vida de tarefas" #: ../../library/asyncio-extending.rst:71 msgid "" @@ -150,39 +147,46 @@ msgid "" "keep a task visible by :func:`asyncio.all_tasks` and :func:`asyncio." "current_task`:" msgstr "" +"Implementações de Task de terceiros devem chamar as seguintes funções para " +"manter uma tarefa visível para :func:`asyncio.all_tasks` e :func:`asyncio." +"current_task`:" #: ../../library/asyncio-extending.rst:76 msgid "Register a new *task* as managed by *asyncio*." -msgstr "" +msgstr "Registra uma nova *task* como gerenciada pelo *asyncio*." #: ../../library/asyncio-extending.rst:78 msgid "Call the function from a task constructor." -msgstr "" +msgstr "Chame esta função no construtor de uma tarefa." #: ../../library/asyncio-extending.rst:82 msgid "Unregister a *task* from *asyncio* internal structures." -msgstr "" +msgstr "Cancela o registro de *task* nas estruturas internas do *asyncio*." #: ../../library/asyncio-extending.rst:84 msgid "The function should be called when a task is about to finish." -msgstr "" +msgstr "Chame esta função quando a tarefa estiver terminando." #: ../../library/asyncio-extending.rst:88 msgid "Switch the current task to the *task* argument." -msgstr "" +msgstr "Troca a tarefa atual para o argumento *task*." #: ../../library/asyncio-extending.rst:90 msgid "" "Call the function just before executing a portion of embedded *coroutine* (:" "meth:`coroutine.send` or :meth:`coroutine.throw`)." msgstr "" +"Chame esta função logo antes de executar uma porção da *corrotina* embutida " +"(:meth:`coroutine.send` ou :meth:`coroutine.throw`)." #: ../../library/asyncio-extending.rst:95 msgid "Switch the current task back from *task* to ``None``." -msgstr "" +msgstr "Troca a tarefa atual de *task* para ``None``." #: ../../library/asyncio-extending.rst:97 msgid "" "Call the function just after :meth:`coroutine.send` or :meth:`coroutine." "throw` execution." msgstr "" +"Chame esta função logo após executar :meth:`coroutine.send` ou :meth:" +"`coroutine.throw`." diff --git a/library/asyncio-future.po b/library/asyncio-future.po index f68810b4e..b1fa2b2a1 100644 --- a/library/asyncio-future.po +++ b/library/asyncio-future.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Sheila Gomes , 2024 -# Adorilson Bezerra , 2024 -# Vitor Buxbaum Orlandi, 2024 -# Vinicius Gubiani Ferreira , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-26 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:55+0000\n" -"Last-Translator: Vinicius Gubiani Ferreira , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -230,6 +227,12 @@ msgid "" "setting a result or an exception for it::" msgstr "" +#: ../../library/asyncio-future.rst:154 +msgid "" +"if not fut.cancelled():\n" +" fut.set_result(42)" +msgstr "" + #: ../../library/asyncio-future.rst:159 msgid "Add a callback to be run when the Future is *done*." msgstr "" @@ -260,6 +263,13 @@ msgid "" "g.::" msgstr "" +#: ../../library/asyncio-future.rst:174 +msgid "" +"# Call 'print(\"Future:\", fut)' when \"fut\" is done.\n" +"fut.add_done_callback(\n" +" functools.partial(print, \"Future:\"))" +msgstr "" + #: ../../library/asyncio-future.rst:178 msgid "" "The *context* keyword-only parameter was added. See :pep:`567` for more " @@ -319,6 +329,37 @@ msgid "" "Task to set result for the Future, and waits until the Future has a result::" msgstr "" +#: ../../library/asyncio-future.rst:226 +msgid "" +"async def set_after(fut, delay, value):\n" +" # Sleep for *delay* seconds.\n" +" await asyncio.sleep(delay)\n" +"\n" +" # Set *value* as a result of *fut* Future.\n" +" fut.set_result(value)\n" +"\n" +"async def main():\n" +" # Get the current event loop.\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" # Create a new Future object.\n" +" fut = loop.create_future()\n" +"\n" +" # Run \"set_after()\" coroutine in a parallel Task.\n" +" # We are using the low-level \"loop.create_task()\" API here because\n" +" # we already have a reference to the event loop at hand.\n" +" # Otherwise we could have just used \"asyncio.create_task()\".\n" +" loop.create_task(\n" +" set_after(fut, 1, '... world'))\n" +"\n" +" print('hello ...')\n" +"\n" +" # Wait until *fut* has a result (1 second) and print it.\n" +" print(await fut)\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: ../../library/asyncio-future.rst:257 msgid "" "The Future object was designed to mimic :class:`concurrent.futures.Future`. " diff --git a/library/asyncio-llapi-index.po b/library/asyncio-llapi-index.po index 4ddb0354d..1014f227d 100644 --- a/library/asyncio-llapi-index.po +++ b/library/asyncio-llapi-index.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# msilvavieira, 2021 -# i17obot , 2021 -# Marco Rougeth , 2021 -# Vinicius Gubiani Ferreira , 2021 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:55+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -133,16 +127,16 @@ msgid "Close the event loop." msgstr "Fecha o laço de eventos." #: ../../library/asyncio-llapi-index.rst:59 -msgid ":meth:`loop.is_running()`" -msgstr ":meth:`loop.is_running()`" +msgid ":meth:`loop.is_running`" +msgstr ":meth:`loop.is_running`" #: ../../library/asyncio-llapi-index.rst:60 msgid "Return ``True`` if the event loop is running." msgstr "Retorna ``True`` se o laço de eventos estiver rodando." #: ../../library/asyncio-llapi-index.rst:62 -msgid ":meth:`loop.is_closed()`" -msgstr ":meth:`loop.is_closed()`" +msgid ":meth:`loop.is_closed`" +msgstr ":meth:`loop.is_closed`" #: ../../library/asyncio-llapi-index.rst:63 msgid "Return ``True`` if the event loop is closed." diff --git a/library/asyncio-platforms.po b/library/asyncio-platforms.po index b78cb082e..6a433ce8b 100644 --- a/library/asyncio-platforms.po +++ b/library/asyncio-platforms.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# felipe caridade fernandes , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:55+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -160,3 +158,13 @@ msgid "" "class:`~selectors.SelectSelector` or :class:`~selectors.PollSelector` to " "support character devices on these older versions of macOS. Example::" msgstr "" + +#: ../../library/asyncio-platforms.rst:100 +msgid "" +"import asyncio\n" +"import selectors\n" +"\n" +"selector = selectors.SelectSelector()\n" +"loop = asyncio.SelectorEventLoop(selector)\n" +"asyncio.set_event_loop(loop)" +msgstr "" diff --git a/library/asyncio-policy.po b/library/asyncio-policy.po index 7f0b6d13e..1a3f82b41 100644 --- a/library/asyncio-policy.po +++ b/library/asyncio-policy.po @@ -1,29 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Sheila Gomes , 2021 -# Vinicius Gubiani Ferreira , 2021 -# Rafael Fontenelle , 2021 -# Adorilson Bezerra , 2022 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 00:55+0000\n" -"Last-Translator: Adorilson Bezerra , 2022\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -169,8 +165,8 @@ msgid "" msgstr "" #: ../../library/asyncio-policy.rst:131 ../../library/asyncio-policy.rst:139 -msgid ":ref:`Availability `: Windows." -msgstr ":ref:`Disponibilidade `: Windows." +msgid "Availability" +msgstr "Disponibilidade" #: ../../library/asyncio-policy.rst:136 msgid "" @@ -398,3 +394,19 @@ msgid "" "`DefaultEventLoopPolicy` and override the methods for which custom behavior " "is wanted, e.g.::" msgstr "" + +#: ../../library/asyncio-policy.rst:317 +msgid "" +"class MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy):\n" +"\n" +" def get_event_loop(self):\n" +" \"\"\"Get the event loop.\n" +"\n" +" This may be None or an instance of EventLoop.\n" +" \"\"\"\n" +" loop = super().get_event_loop()\n" +" # Do something with loop ...\n" +" return loop\n" +"\n" +"asyncio.set_event_loop_policy(MyEventLoopPolicy())" +msgstr "" diff --git a/library/asyncio-protocol.po b/library/asyncio-protocol.po index a7d8ba6bc..9039b92a0 100644 --- a/library/asyncio-protocol.po +++ b/library/asyncio-protocol.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Humberto Rocha , 2021 -# Ruan Aragão , 2021 -# i17obot , 2021 -# Vinicius Gubiani Ferreira , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 02:33+0000\n" -"PO-Revision-Date: 2021-06-28 00:55+0000\n" -"Last-Translator: Vinicius Gubiani Ferreira , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -271,6 +266,13 @@ msgid "" "of the transport::" msgstr "" +#: ../../library/asyncio-protocol.rst:182 +msgid "" +"sock = transport.get_extra_info('socket')\n" +"if sock is not None:\n" +" print(sock.getsockopt(...))" +msgstr "" + #: ../../library/asyncio-protocol.rst:186 msgid "Categories of information that can be queried on some transports:" msgstr "" @@ -801,6 +803,14 @@ msgstr "" msgid "State machine:" msgstr "" +#: ../../library/asyncio-protocol.rst:585 +msgid "" +"start -> connection_made\n" +" [-> data_received]*\n" +" [-> eof_received]?\n" +"-> connection_lost -> end" +msgstr "" + #: ../../library/asyncio-protocol.rst:594 msgid "Buffered Streaming Protocols" msgstr "Protocolos de Streaming Bufferizados" @@ -867,6 +877,16 @@ msgid "" "won't be called after it." msgstr "" +#: ../../library/asyncio-protocol.rst:643 +msgid "" +"start -> connection_made\n" +" [-> get_buffer\n" +" [-> buffer_updated]?\n" +" ]*\n" +" [-> eof_received]?\n" +"-> connection_lost -> end" +msgstr "" + #: ../../library/asyncio-protocol.rst:654 msgid "Datagram Protocols" msgstr "Protocolos de Datagramas" @@ -971,6 +991,44 @@ msgid "" "back received data, and close the connection::" msgstr "" +#: ../../library/asyncio-protocol.rst:731 +msgid "" +"import asyncio\n" +"\n" +"\n" +"class EchoServerProtocol(asyncio.Protocol):\n" +" def connection_made(self, transport):\n" +" peername = transport.get_extra_info('peername')\n" +" print('Connection from {}'.format(peername))\n" +" self.transport = transport\n" +"\n" +" def data_received(self, data):\n" +" message = data.decode()\n" +" print('Data received: {!r}'.format(message))\n" +"\n" +" print('Send: {!r}'.format(message))\n" +" self.transport.write(data)\n" +"\n" +" print('Close the client socket')\n" +" self.transport.close()\n" +"\n" +"\n" +"async def main():\n" +" # Get a reference to the event loop as we plan to use\n" +" # low-level APIs.\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" server = await loop.create_server(\n" +" EchoServerProtocol,\n" +" '127.0.0.1', 8888)\n" +"\n" +" async with server:\n" +" await server.serve_forever()\n" +"\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: ../../library/asyncio-protocol.rst:769 msgid "" "The :ref:`TCP echo server using streams ` " @@ -987,6 +1045,51 @@ msgid "" "data, and waits until the connection is closed::" msgstr "" +#: ../../library/asyncio-protocol.rst:780 +msgid "" +"import asyncio\n" +"\n" +"\n" +"class EchoClientProtocol(asyncio.Protocol):\n" +" def __init__(self, message, on_con_lost):\n" +" self.message = message\n" +" self.on_con_lost = on_con_lost\n" +"\n" +" def connection_made(self, transport):\n" +" transport.write(self.message.encode())\n" +" print('Data sent: {!r}'.format(self.message))\n" +"\n" +" def data_received(self, data):\n" +" print('Data received: {!r}'.format(data.decode()))\n" +"\n" +" def connection_lost(self, exc):\n" +" print('The server closed the connection')\n" +" self.on_con_lost.set_result(True)\n" +"\n" +"\n" +"async def main():\n" +" # Get a reference to the event loop as we plan to use\n" +" # low-level APIs.\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" on_con_lost = loop.create_future()\n" +" message = 'Hello World!'\n" +"\n" +" transport, protocol = await loop.create_connection(\n" +" lambda: EchoClientProtocol(message, on_con_lost),\n" +" '127.0.0.1', 8888)\n" +"\n" +" # Wait until the protocol signals that the connection\n" +" # is lost and close the transport.\n" +" try:\n" +" await on_con_lost\n" +" finally:\n" +" transport.close()\n" +"\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: ../../library/asyncio-protocol.rst:825 msgid "" "The :ref:`TCP echo client using streams ` " @@ -1003,6 +1106,44 @@ msgid "" "sends back received data::" msgstr "" +#: ../../library/asyncio-protocol.rst:837 +msgid "" +"import asyncio\n" +"\n" +"\n" +"class EchoServerProtocol:\n" +" def connection_made(self, transport):\n" +" self.transport = transport\n" +"\n" +" def datagram_received(self, data, addr):\n" +" message = data.decode()\n" +" print('Received %r from %s' % (message, addr))\n" +" print('Send %r to %s' % (message, addr))\n" +" self.transport.sendto(data, addr)\n" +"\n" +"\n" +"async def main():\n" +" print(\"Starting UDP server\")\n" +"\n" +" # Get a reference to the event loop as we plan to use\n" +" # low-level APIs.\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" # One protocol instance will be created to serve all\n" +" # client requests.\n" +" transport, protocol = await loop.create_datagram_endpoint(\n" +" EchoServerProtocol,\n" +" local_addr=('127.0.0.1', 9999))\n" +"\n" +" try:\n" +" await asyncio.sleep(3600) # Serve for 1 hour.\n" +" finally:\n" +" transport.close()\n" +"\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: ../../library/asyncio-protocol.rst:876 msgid "UDP Echo Client" msgstr "" @@ -1013,6 +1154,57 @@ msgid "" "sends data and closes the transport when it receives the answer::" msgstr "" +#: ../../library/asyncio-protocol.rst:881 +msgid "" +"import asyncio\n" +"\n" +"\n" +"class EchoClientProtocol:\n" +" def __init__(self, message, on_con_lost):\n" +" self.message = message\n" +" self.on_con_lost = on_con_lost\n" +" self.transport = None\n" +"\n" +" def connection_made(self, transport):\n" +" self.transport = transport\n" +" print('Send:', self.message)\n" +" self.transport.sendto(self.message.encode())\n" +"\n" +" def datagram_received(self, data, addr):\n" +" print(\"Received:\", data.decode())\n" +"\n" +" print(\"Close the socket\")\n" +" self.transport.close()\n" +"\n" +" def error_received(self, exc):\n" +" print('Error received:', exc)\n" +"\n" +" def connection_lost(self, exc):\n" +" print(\"Connection closed\")\n" +" self.on_con_lost.set_result(True)\n" +"\n" +"\n" +"async def main():\n" +" # Get a reference to the event loop as we plan to use\n" +" # low-level APIs.\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" on_con_lost = loop.create_future()\n" +" message = \"Hello World!\"\n" +"\n" +" transport, protocol = await loop.create_datagram_endpoint(\n" +" lambda: EchoClientProtocol(message, on_con_lost),\n" +" remote_addr=('127.0.0.1', 9999))\n" +"\n" +" try:\n" +" await on_con_lost\n" +" finally:\n" +" transport.close()\n" +"\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: ../../library/asyncio-protocol.rst:933 msgid "Connecting Existing Sockets" msgstr "" @@ -1023,6 +1215,58 @@ msgid "" "method with a protocol::" msgstr "" +#: ../../library/asyncio-protocol.rst:938 +msgid "" +"import asyncio\n" +"import socket\n" +"\n" +"\n" +"class MyProtocol(asyncio.Protocol):\n" +"\n" +" def __init__(self, on_con_lost):\n" +" self.transport = None\n" +" self.on_con_lost = on_con_lost\n" +"\n" +" def connection_made(self, transport):\n" +" self.transport = transport\n" +"\n" +" def data_received(self, data):\n" +" print(\"Received:\", data.decode())\n" +"\n" +" # We are done: close the transport;\n" +" # connection_lost() will be called automatically.\n" +" self.transport.close()\n" +"\n" +" def connection_lost(self, exc):\n" +" # The socket has been closed\n" +" self.on_con_lost.set_result(True)\n" +"\n" +"\n" +"async def main():\n" +" # Get a reference to the event loop as we plan to use\n" +" # low-level APIs.\n" +" loop = asyncio.get_running_loop()\n" +" on_con_lost = loop.create_future()\n" +"\n" +" # Create a pair of connected sockets\n" +" rsock, wsock = socket.socketpair()\n" +"\n" +" # Register the socket to wait for data.\n" +" transport, protocol = await loop.create_connection(\n" +" lambda: MyProtocol(on_con_lost), sock=rsock)\n" +"\n" +" # Simulate the reception of data from the network.\n" +" loop.call_soon(wsock.send, 'abc'.encode())\n" +"\n" +" try:\n" +" await protocol.on_con_lost\n" +" finally:\n" +" transport.close()\n" +" wsock.close()\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: ../../library/asyncio-protocol.rst:989 msgid "" "The :ref:`watch a file descriptor for read events " @@ -1051,6 +1295,67 @@ msgstr "" msgid "The subprocess is created by the :meth:`loop.subprocess_exec` method::" msgstr "" +#: ../../library/asyncio-protocol.rst:1007 +msgid "" +"import asyncio\n" +"import sys\n" +"\n" +"class DateProtocol(asyncio.SubprocessProtocol):\n" +" def __init__(self, exit_future):\n" +" self.exit_future = exit_future\n" +" self.output = bytearray()\n" +" self.pipe_closed = False\n" +" self.exited = False\n" +"\n" +" def pipe_connection_lost(self, fd, exc):\n" +" self.pipe_closed = True\n" +" self.check_for_exit()\n" +"\n" +" def pipe_data_received(self, fd, data):\n" +" self.output.extend(data)\n" +"\n" +" def process_exited(self):\n" +" self.exited = True\n" +" # process_exited() method can be called before\n" +" # pipe_connection_lost() method: wait until both methods are\n" +" # called.\n" +" self.check_for_exit()\n" +"\n" +" def check_for_exit(self):\n" +" if self.pipe_closed and self.exited:\n" +" self.exit_future.set_result(True)\n" +"\n" +"async def get_date():\n" +" # Get a reference to the event loop as we plan to use\n" +" # low-level APIs.\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" code = 'import datetime; print(datetime.datetime.now())'\n" +" exit_future = asyncio.Future(loop=loop)\n" +"\n" +" # Create the subprocess controlled by DateProtocol;\n" +" # redirect the standard output into a pipe.\n" +" transport, protocol = await loop.subprocess_exec(\n" +" lambda: DateProtocol(exit_future),\n" +" sys.executable, '-c', code,\n" +" stdin=None, stderr=None)\n" +"\n" +" # Wait for the subprocess exit using the process_exited()\n" +" # method of the protocol.\n" +" await exit_future\n" +"\n" +" # Close the stdout pipe.\n" +" transport.close()\n" +"\n" +" # Read the output which was collected by the\n" +" # pipe_data_received() method of the protocol.\n" +" data = bytes(protocol.output)\n" +" return data.decode('ascii').rstrip()\n" +"\n" +"date = asyncio.run(get_date())\n" +"print(f\"Current date: {date}\")" +msgstr "" + #: ../../library/asyncio-protocol.rst:1065 msgid "" "See also the :ref:`same example ` " diff --git a/library/asyncio-queue.po b/library/asyncio-queue.po index b6f6a5a9f..c4289b129 100644 --- a/library/asyncio-queue.po +++ b/library/asyncio-queue.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Leticia Portella , 2021 -# Vinicius Gubiani Ferreira , 2021 -# Adorilson Bezerra , 2022 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 00:55+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-28 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -111,12 +106,12 @@ msgstr "Retorna ``True`` se existem :attr:`maxsize` itens na fila." #: ../../library/asyncio-queue.rst:57 msgid "" "If the queue was initialized with ``maxsize=0`` (the default), then :meth:" -"`full()` never returns ``True``." +"`full` never returns ``True``." msgstr "" -"Se a fila foi inicializada com ``maxsize=0`` (o padrão), então :meth:" -"`full()` nunca retorna ``True``." +"Se a fila foi inicializada com ``maxsize=0`` (o padrão), então :meth:`full` " +"nunca retorna ``True``." -#: ../../library/asyncio-queue.rst:62 +#: ../../library/asyncio-queue.rst:63 msgid "" "Remove and return an item from the queue. If queue is empty, wait until an " "item is available." @@ -124,7 +119,7 @@ msgstr "" "Remove e retorna um item da fila. Se a fila estiver vazia, aguarda até que " "um item esteja disponível." -#: ../../library/asyncio-queue.rst:65 +#: ../../library/asyncio-queue.rst:66 msgid "" "Raises :exc:`QueueShutDown` if the queue has been shut down and is empty, or " "if the queue has been shut down immediately." @@ -132,19 +127,19 @@ msgstr "" "Levanta :exc:`QueueShutDown` se a fila foi encerrada e está vazia, ou se a " "fila foi encerrada imediatamente." -#: ../../library/asyncio-queue.rst:70 +#: ../../library/asyncio-queue.rst:71 msgid "" "Return an item if one is immediately available, else raise :exc:`QueueEmpty`." msgstr "" "Retorna um item se houver um imediatamente disponível, caso contrário " "levanta :exc:`QueueEmpty`." -#: ../../library/asyncio-queue.rst:75 +#: ../../library/asyncio-queue.rst:77 msgid "Block until all items in the queue have been received and processed." msgstr "" "Bloqueia até que todos os itens na fila tenham sido recebidos e processados." -#: ../../library/asyncio-queue.rst:77 +#: ../../library/asyncio-queue.rst:79 msgid "" "The count of unfinished tasks goes up whenever an item is added to the " "queue. The count goes down whenever a consumer coroutine calls :meth:" @@ -158,7 +153,7 @@ msgstr "" "foi concluído. Quando a contagem de tarefas inacabadas chega a zero, :meth:" "`join` desbloqueia." -#: ../../library/asyncio-queue.rst:85 +#: ../../library/asyncio-queue.rst:88 msgid "" "Put an item into the queue. If the queue is full, wait until a free slot is " "available before adding the item." @@ -166,25 +161,25 @@ msgstr "" "Coloca um item na fila. Se a fila estiver cheia, aguarda até que uma posição " "livre esteja disponível antes de adicionar o item." -#: ../../library/asyncio-queue.rst:88 +#: ../../library/asyncio-queue.rst:91 msgid "Raises :exc:`QueueShutDown` if the queue has been shut down." msgstr "Levanta :exc:`QueueShutDown` se a fila foi encerrada." -#: ../../library/asyncio-queue.rst:92 +#: ../../library/asyncio-queue.rst:95 msgid "Put an item into the queue without blocking." msgstr "Coloca um item na fila sem bloqueá-la." -#: ../../library/asyncio-queue.rst:94 +#: ../../library/asyncio-queue.rst:97 msgid "If no free slot is immediately available, raise :exc:`QueueFull`." msgstr "" "Se nenhuma posição livre estiver imediatamente disponível, levanta :exc:" "`QueueFull`." -#: ../../library/asyncio-queue.rst:98 +#: ../../library/asyncio-queue.rst:101 msgid "Return the number of items in the queue." msgstr "Retorna o número de itens na fila." -#: ../../library/asyncio-queue.rst:102 +#: ../../library/asyncio-queue.rst:105 msgid "" "Shut down the queue, making :meth:`~Queue.get` and :meth:`~Queue.put` raise :" "exc:`QueueShutDown`." @@ -192,7 +187,7 @@ msgstr "" "Desliga a fila, fazendo com que :meth:`~Queue.get` e :meth:`~Queue.put` " "levantem :exc:`QueueShutDown`." -#: ../../library/asyncio-queue.rst:105 +#: ../../library/asyncio-queue.rst:108 msgid "" "By default, :meth:`~Queue.get` on a shut down queue will only raise once the " "queue is empty. Set *immediate* to true to make :meth:`~Queue.get` raise " @@ -202,7 +197,7 @@ msgstr "" "quando a fila estiver vazia. Defina *immediate* como verdadeiro para fazer :" "meth:`~Queue.get` levantar imediatamente." -#: ../../library/asyncio-queue.rst:109 +#: ../../library/asyncio-queue.rst:112 msgid "" "All blocked callers of :meth:`~Queue.put` and :meth:`~Queue.get` will be " "unblocked. If *immediate* is true, a task will be marked as done for each " @@ -214,21 +209,22 @@ msgstr "" "como concluída para cada item restante na fila, o que pode desbloquear " "chamadores de :meth:`~Queue.join`." -#: ../../library/asyncio-queue.rst:118 -msgid "Indicate that a formerly enqueued task is complete." -msgstr "Indica que a tarefa anteriormente enfileirada está concluída." +#: ../../library/asyncio-queue.rst:121 +msgid "Indicate that a formerly enqueued work item is complete." +msgstr "" +"Indica que o item de trabalho anteriormente enfileirado está concluído." -#: ../../library/asyncio-queue.rst:120 +#: ../../library/asyncio-queue.rst:123 msgid "" -"Used by queue consumers. For each :meth:`~Queue.get` used to fetch a task, a " -"subsequent call to :meth:`task_done` tells the queue that the processing on " -"the task is complete." +"Used by queue consumers. For each :meth:`~Queue.get` used to fetch a work " +"item, a subsequent call to :meth:`task_done` tells the queue that the " +"processing on the work item is complete." msgstr "" "Usada por consumidores de fila. Para cada :meth:`~Queue.get` usado para " -"buscar uma tarefa, uma chamada subsequente para :meth:`task_done` avisa à " -"fila, que o processamento na tarefa está concluído." +"buscar um item de trabalho, uma chamada subsequente para :meth:`task_done` " +"avisa à fila, que o processamento no item de trabalho está concluído." -#: ../../library/asyncio-queue.rst:124 +#: ../../library/asyncio-queue.rst:127 msgid "" "If a :meth:`join` is currently blocking, it will resume when all items have " "been processed (meaning that a :meth:`task_done` call was received for every " @@ -239,7 +235,7 @@ msgstr "" "chamada :meth:`task_done` foi recebida para cada item que foi chamado o " "método :meth:`~Queue.put` para colocar na fila)." -#: ../../library/asyncio-queue.rst:129 +#: ../../library/asyncio-queue.rst:132 msgid "" "``shutdown(immediate=True)`` calls :meth:`task_done` for each remaining item " "in the queue." @@ -247,7 +243,7 @@ msgstr "" "``shutdown(immediate=True)`` chama :meth:`task_done` para cada item restante " "na fila." -#: ../../library/asyncio-queue.rst:132 +#: ../../library/asyncio-queue.rst:135 msgid "" "Raises :exc:`ValueError` if called more times than there were items placed " "in the queue." @@ -255,11 +251,11 @@ msgstr "" "Levanta :exc:`ValueError` se chamada mais vezes do que a quantidade de itens " "existentes na fila." -#: ../../library/asyncio-queue.rst:137 +#: ../../library/asyncio-queue.rst:140 msgid "Priority Queue" msgstr "Fila de prioridade" -#: ../../library/asyncio-queue.rst:141 +#: ../../library/asyncio-queue.rst:144 msgid "" "A variant of :class:`Queue`; retrieves entries in priority order (lowest " "first)." @@ -267,16 +263,16 @@ msgstr "" "Uma variante de :class:`Queue`; recupera entradas em ordem de prioridade " "(mais baixas primeiro)." -#: ../../library/asyncio-queue.rst:144 +#: ../../library/asyncio-queue.rst:147 msgid "Entries are typically tuples of the form ``(priority_number, data)``." msgstr "" "Entradas são tipicamente tuplas no formato ``(priority_number, data)``." -#: ../../library/asyncio-queue.rst:149 +#: ../../library/asyncio-queue.rst:152 msgid "LIFO Queue" msgstr "Filas LIFO (último a entrar, primeiro a sair)" -#: ../../library/asyncio-queue.rst:153 +#: ../../library/asyncio-queue.rst:156 msgid "" "A variant of :class:`Queue` that retrieves most recently added entries first " "(last in, first out)." @@ -284,11 +280,11 @@ msgstr "" "Uma variante de :class:`Queue` que recupera as entradas adicionadas mais " "recentemente primeiro (último a entrar, primeiro a sair)." -#: ../../library/asyncio-queue.rst:158 +#: ../../library/asyncio-queue.rst:161 msgid "Exceptions" msgstr "Exceções" -#: ../../library/asyncio-queue.rst:162 +#: ../../library/asyncio-queue.rst:165 msgid "" "This exception is raised when the :meth:`~Queue.get_nowait` method is called " "on an empty queue." @@ -296,7 +292,7 @@ msgstr "" "Esta exceção é levantada quando o método :meth:`~Queue.get_nowait` é chamado " "em uma fila vazia." -#: ../../library/asyncio-queue.rst:168 +#: ../../library/asyncio-queue.rst:171 msgid "" "Exception raised when the :meth:`~Queue.put_nowait` method is called on a " "queue that has reached its *maxsize*." @@ -304,7 +300,7 @@ msgstr "" "Exceção levantada quando o método :meth:`~Queue.put_nowait` é chamado em uma " "fila que atingiu seu *maxsize*." -#: ../../library/asyncio-queue.rst:174 +#: ../../library/asyncio-queue.rst:177 msgid "" "Exception raised when :meth:`~Queue.put` or :meth:`~Queue.get` is called on " "a queue which has been shut down." @@ -312,13 +308,126 @@ msgstr "" "Exceção levantada quando :meth:`~Queue.put` ou :meth:`~Queue.get` é chamado " "em uma fila que foi desligada." -#: ../../library/asyncio-queue.rst:181 +#: ../../library/asyncio-queue.rst:184 msgid "Examples" msgstr "Exemplos" -#: ../../library/asyncio-queue.rst:185 +#: ../../library/asyncio-queue.rst:188 msgid "" "Queues can be used to distribute workload between several concurrent tasks::" msgstr "" "Filas podem ser usadas para distribuir cargas de trabalho entre diversas " "tarefas concorrentes::" + +#: ../../library/asyncio-queue.rst:191 +msgid "" +"import asyncio\n" +"import random\n" +"import time\n" +"\n" +"\n" +"async def worker(name, queue):\n" +" while True:\n" +" # Get a \"work item\" out of the queue.\n" +" sleep_for = await queue.get()\n" +"\n" +" # Sleep for the \"sleep_for\" seconds.\n" +" await asyncio.sleep(sleep_for)\n" +"\n" +" # Notify the queue that the \"work item\" has been processed.\n" +" queue.task_done()\n" +"\n" +" print(f'{name} has slept for {sleep_for:.2f} seconds')\n" +"\n" +"\n" +"async def main():\n" +" # Create a queue that we will use to store our \"workload\".\n" +" queue = asyncio.Queue()\n" +"\n" +" # Generate random timings and put them into the queue.\n" +" total_sleep_time = 0\n" +" for _ in range(20):\n" +" sleep_for = random.uniform(0.05, 1.0)\n" +" total_sleep_time += sleep_for\n" +" queue.put_nowait(sleep_for)\n" +"\n" +" # Create three worker tasks to process the queue concurrently.\n" +" tasks = []\n" +" for i in range(3):\n" +" task = asyncio.create_task(worker(f'worker-{i}', queue))\n" +" tasks.append(task)\n" +"\n" +" # Wait until the queue is fully processed.\n" +" started_at = time.monotonic()\n" +" await queue.join()\n" +" total_slept_for = time.monotonic() - started_at\n" +"\n" +" # Cancel our worker tasks.\n" +" for task in tasks:\n" +" task.cancel()\n" +" # Wait until all worker tasks are cancelled.\n" +" await asyncio.gather(*tasks, return_exceptions=True)\n" +"\n" +" print('====')\n" +" print(f'3 workers slept in parallel for {total_slept_for:.2f} seconds')\n" +" print(f'total expected sleep time: {total_sleep_time:.2f} seconds')\n" +"\n" +"\n" +"asyncio.run(main())" +msgstr "" +"import asyncio\n" +"import random\n" +"import time\n" +"\n" +"\n" +"async def worker(nome, fila):\n" +" while True:\n" +" # Retira um \"item de trabalho\" da fila.\n" +" dormir_por = await queue.get()\n" +"\n" +" # Dorme por \"dormir_por\" segundos.\n" +" await asyncio.sleep(dormir_por)\n" +"\n" +" # Notifica a fila de que o \"item de trabalho\" foi processado.\n" +" fila.task_done()\n" +"\n" +" print(f'{nome} dormiu por {dormir_por:.2f} segundos')\n" +"\n" +"\n" +"async def main():\n" +" # Cria uma fila para armazenar nossa \"carga de trabalho\".\n" +" fila = asyncio.Queue()\n" +"\n" +" # Gera tempos aleatórios e os insere na fila.\n" +" tempo_total_de_sono = 0\n" +" for _ in range(20):\n" +" dormir_por = random.uniform(0.05, 1.0)\n" +" tempo_total_de_sono += dormir_por\n" +" fila.put_nowait(dormir_por)\n" +"\n" +" # Cria três tarefas \"worker\" para processarem a fila " +"concorrentemente.\n" +" tarefas = []\n" +" for i in range(3):\n" +" tarefa = asyncio.create_task(worker(f'worker-{i}', fila))\n" +" tarefas.append(tarefa)\n" +"\n" +" # Espera até a fila ser completamente processada.\n" +" comecou_em = time.monotonic()\n" +" await fila.join()\n" +" tempo_dormido = time.monotonic() - comecou_em\n" +"\n" +" # Cancela nossas tarefas.\n" +" for tarefa in tarefas:\n" +" tarefa.cancel()\n" +" # Espera até todas as tarefas serem canceladas.\n" +" await asyncio.gather(*tarefas, return_exceptions=True)\n" +"\n" +" print('====')\n" +" print(f'3 trabalhadoras dormiram em paralelo por {tempo_dormido:.2f} " +"segundos')\n" +" print(f'Tempo total de sono esperado: {tempo_total_de_sono:.2f} " +"segundos')\n" +"\n" +"\n" +"asyncio.run(main())" diff --git a/library/asyncio-runner.po b/library/asyncio-runner.po index 9ee1aee5a..ca8dba2e4 100644 --- a/library/asyncio-runner.po +++ b/library/asyncio-runner.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Vinicius Gubiani Ferreira , 2022 -# Italo Penaforte , 2022 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 02:33+0000\n" -"PO-Revision-Date: 2022-11-05 19:48+0000\n" -"Last-Translator: Italo Penaforte , 2022\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -93,6 +92,15 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" +#: ../../library/asyncio-runner.rst:54 +msgid "" +"async def main():\n" +" await asyncio.sleep(1)\n" +" print('hello')\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: ../../library/asyncio-runner.rst:62 msgid "Updated to use :meth:`loop.shutdown_default_executor`." msgstr "Atualizado para usar :meth:`loop.shutdown_default_executor`." @@ -132,10 +140,20 @@ msgstr "" #: ../../library/asyncio-runner.rst:94 msgid "" -"Basically, :func:`asyncio.run()` example can be rewritten with the runner " +"Basically, :func:`asyncio.run` example can be rewritten with the runner " "usage::" msgstr "" +#: ../../library/asyncio-runner.rst:96 +msgid "" +"async def main():\n" +" await asyncio.sleep(1)\n" +" print('hello')\n" +"\n" +"with asyncio.Runner() as runner:\n" +" runner.run(main())" +msgstr "" + #: ../../library/asyncio-runner.rst:107 msgid "Run a :term:`coroutine ` *coro* in the embedded loop." msgstr "" diff --git a/library/asyncio-stream.po b/library/asyncio-stream.po index fe8446563..4e38a38a0 100644 --- a/library/asyncio-stream.po +++ b/library/asyncio-stream.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Cássio Nomura , 2021 -# i17obot , 2021 -# Adorilson Bezerra , 2022 -# Vinicius Gubiani Ferreira , 2022 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 02:33+0000\n" -"PO-Revision-Date: 2021-06-28 00:55+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-28 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -52,6 +47,28 @@ msgstr "" "Aqui está um exemplo de um cliente TCP realizando eco, escrito usando " "streams asyncio::" +#: ../../library/asyncio-stream.rst:22 ../../library/asyncio-stream.rst:430 +msgid "" +"import asyncio\n" +"\n" +"async def tcp_echo_client(message):\n" +" reader, writer = await asyncio.open_connection(\n" +" '127.0.0.1', 8888)\n" +"\n" +" print(f'Send: {message!r}')\n" +" writer.write(message.encode())\n" +" await writer.drain()\n" +"\n" +" data = await reader.read(100)\n" +" print(f'Received: {data.decode()!r}')\n" +"\n" +" print('Close the connection')\n" +" writer.close()\n" +" await writer.wait_closed()\n" +"\n" +"asyncio.run(tcp_echo_client('Hello World!'))" +msgstr "" + #: ../../library/asyncio-stream.rst:42 msgid "See also the `Examples`_ section below." msgstr "Veja também a seção `Exemplos`_ abaixo." @@ -68,7 +85,7 @@ msgstr "" "As seguintes funções asyncio de alto nível podem ser usadas para criar e " "trabalhar com streams:" -#: ../../library/asyncio-stream.rst:58 +#: ../../library/asyncio-stream.rst:59 msgid "" "Establish a network connection and return a pair of ``(reader, writer)`` " "objects." @@ -76,7 +93,7 @@ msgstr "" "Estabelece uma conexão de rede e retorna um par de objetos ``(reader, " "writer)``." -#: ../../library/asyncio-stream.rst:61 +#: ../../library/asyncio-stream.rst:62 msgid "" "The returned *reader* and *writer* objects are instances of :class:" "`StreamReader` and :class:`StreamWriter` classes." @@ -84,7 +101,7 @@ msgstr "" "Os objetos *reader* e *writer* retornados são instâncias das classes :class:" "`StreamReader` e :class:`StreamWriter`." -#: ../../library/asyncio-stream.rst:64 ../../library/asyncio-stream.rst:109 +#: ../../library/asyncio-stream.rst:65 ../../library/asyncio-stream.rst:112 msgid "" "*limit* determines the buffer size limit used by the returned :class:" "`StreamReader` instance. By default the *limit* is set to 64 KiB." @@ -92,7 +109,7 @@ msgstr "" "*limit* determina o tamanho limite do buffer usado pela instância :class:" "`StreamReader` retornada. Por padrão, *limit* é definido em 64 KiB." -#: ../../library/asyncio-stream.rst:68 +#: ../../library/asyncio-stream.rst:69 msgid "" "The rest of the arguments are passed directly to :meth:`loop." "create_connection`." @@ -100,37 +117,37 @@ msgstr "" "O resto dos argumentos é passado diretamente para :meth:`loop." "create_connection`." -#: ../../library/asyncio-stream.rst:73 ../../library/asyncio-stream.rst:147 +#: ../../library/asyncio-stream.rst:74 ../../library/asyncio-stream.rst:154 msgid "" "The *sock* argument transfers ownership of the socket to the :class:" "`StreamWriter` created. To close the socket, call its :meth:`~asyncio." "StreamWriter.close` method." msgstr "" -#: ../../library/asyncio-stream.rst:77 +#: ../../library/asyncio-stream.rst:78 msgid "Added the *ssl_handshake_timeout* parameter." msgstr "Adicionado o parâmetro *ssl_handshake_timeout*." -#: ../../library/asyncio-stream.rst:80 +#: ../../library/asyncio-stream.rst:81 msgid "Added the *happy_eyeballs_delay* and *interleave* parameters." msgstr "Adicionados os parâmetros *happy_eyeballs_delay* e *interleave*." -#: ../../library/asyncio-stream.rst:83 ../../library/asyncio-stream.rst:125 -#: ../../library/asyncio-stream.rst:157 ../../library/asyncio-stream.rst:187 +#: ../../library/asyncio-stream.rst:84 ../../library/asyncio-stream.rst:128 +#: ../../library/asyncio-stream.rst:164 ../../library/asyncio-stream.rst:195 msgid "Removed the *loop* parameter." msgstr "Removido o parâmetro *loop*." -#: ../../library/asyncio-stream.rst:86 ../../library/asyncio-stream.rst:128 -#: ../../library/asyncio-stream.rst:160 ../../library/asyncio-stream.rst:190 -#: ../../library/asyncio-stream.rst:383 +#: ../../library/asyncio-stream.rst:87 ../../library/asyncio-stream.rst:131 +#: ../../library/asyncio-stream.rst:167 ../../library/asyncio-stream.rst:198 +#: ../../library/asyncio-stream.rst:397 msgid "Added the *ssl_shutdown_timeout* parameter." msgstr "" -#: ../../library/asyncio-stream.rst:98 +#: ../../library/asyncio-stream.rst:101 msgid "Start a socket server." msgstr "Inicia um soquete no servidor." -#: ../../library/asyncio-stream.rst:100 +#: ../../library/asyncio-stream.rst:103 msgid "" "The *client_connected_cb* callback is called whenever a new client " "connection is established. It receives a ``(reader, writer)`` pair as two " @@ -142,7 +159,7 @@ msgstr "" "como dois argumentos, instâncias das classes :class:`StreamReader` e :class:" "`StreamWriter`." -#: ../../library/asyncio-stream.rst:105 +#: ../../library/asyncio-stream.rst:108 msgid "" "*client_connected_cb* can be a plain callable or a :ref:`coroutine function " "`; if it is a coroutine function, it will be automatically " @@ -152,83 +169,87 @@ msgstr "" "`função de corrotina`; se ele for uma função de corrotina, ele " "será automaticamente agendado como uma :class:`Task`." -#: ../../library/asyncio-stream.rst:113 +#: ../../library/asyncio-stream.rst:116 msgid "" "The rest of the arguments are passed directly to :meth:`loop.create_server`." msgstr "" "O resto dos argumentos são passados diretamente para :meth:`loop." "create_server`." -#: ../../library/asyncio-stream.rst:118 ../../library/asyncio-stream.rst:177 +#: ../../library/asyncio-stream.rst:121 ../../library/asyncio-stream.rst:185 msgid "" "The *sock* argument transfers ownership of the socket to the server created. " "To close the socket, call the server's :meth:`~asyncio.Server.close` method." msgstr "" -#: ../../library/asyncio-stream.rst:122 +#: ../../library/asyncio-stream.rst:125 msgid "Added the *ssl_handshake_timeout* and *start_serving* parameters." msgstr "" -#: ../../library/asyncio-stream.rst:133 +#: ../../library/asyncio-stream.rst:134 +msgid "Added the *keep_alive* parameter." +msgstr "" + +#: ../../library/asyncio-stream.rst:139 msgid "Unix Sockets" msgstr "Soquetes Unix" -#: ../../library/asyncio-stream.rst:138 +#: ../../library/asyncio-stream.rst:145 msgid "" "Establish a Unix socket connection and return a pair of ``(reader, writer)``." msgstr "" "Estabelece uma conexão de soquete Unix e retorna um par com ``(reader, " "writer)``." -#: ../../library/asyncio-stream.rst:141 +#: ../../library/asyncio-stream.rst:148 msgid "Similar to :func:`open_connection` but operates on Unix sockets." msgstr "Similar a :func:`open_connection`, mas opera em soquetes Unix." -#: ../../library/asyncio-stream.rst:143 +#: ../../library/asyncio-stream.rst:150 msgid "See also the documentation of :meth:`loop.create_unix_connection`." msgstr "" "Veja também a documentação do método :meth:`loop.create_unix_connection`." -#: ../../library/asyncio-stream.rst:151 ../../library/asyncio-stream.rst:181 -msgid ":ref:`Availability `: Unix." -msgstr ":ref:`Disponibilidade `: Unix." +#: ../../library/asyncio-stream.rst:158 ../../library/asyncio-stream.rst:189 +msgid "Availability" +msgstr "Disponibilidade" -#: ../../library/asyncio-stream.rst:153 +#: ../../library/asyncio-stream.rst:160 msgid "" "Added the *ssl_handshake_timeout* parameter. The *path* parameter can now be " "a :term:`path-like object`" msgstr "" -#: ../../library/asyncio-stream.rst:169 +#: ../../library/asyncio-stream.rst:177 msgid "Start a Unix socket server." msgstr "Inicia um servidor com soquete Unix." -#: ../../library/asyncio-stream.rst:171 +#: ../../library/asyncio-stream.rst:179 msgid "Similar to :func:`start_server` but works with Unix sockets." msgstr "Similar a :func:`start_server`, mas funciona com soquetes Unix." -#: ../../library/asyncio-stream.rst:173 +#: ../../library/asyncio-stream.rst:181 msgid "See also the documentation of :meth:`loop.create_unix_server`." msgstr "Veja também a documentação do método :meth:`loop.create_unix_server`." -#: ../../library/asyncio-stream.rst:183 +#: ../../library/asyncio-stream.rst:191 msgid "" "Added the *ssl_handshake_timeout* and *start_serving* parameters. The *path* " "parameter can now be a :term:`path-like object`." msgstr "" -#: ../../library/asyncio-stream.rst:195 +#: ../../library/asyncio-stream.rst:203 msgid "StreamReader" msgstr "StreamReader" -#: ../../library/asyncio-stream.rst:199 +#: ../../library/asyncio-stream.rst:207 msgid "" "Represents a reader object that provides APIs to read data from the IO " "stream. As an :term:`asynchronous iterable`, the object supports the :" "keyword:`async for` statement." msgstr "" -#: ../../library/asyncio-stream.rst:203 +#: ../../library/asyncio-stream.rst:211 msgid "" "It is not recommended to instantiate *StreamReader* objects directly; use :" "func:`open_connection` and :func:`start_server` instead." @@ -236,39 +257,39 @@ msgstr "" "Não é recomendado instanciar objetos *StreamReader* diretamente; use :func:" "`open_connection` e :func:`start_server` ao invés disso." -#: ../../library/asyncio-stream.rst:209 +#: ../../library/asyncio-stream.rst:217 msgid "Acknowledge the EOF." msgstr "" -#: ../../library/asyncio-stream.rst:213 +#: ../../library/asyncio-stream.rst:222 msgid "Read up to *n* bytes from the stream." msgstr "" -#: ../../library/asyncio-stream.rst:215 +#: ../../library/asyncio-stream.rst:224 msgid "" "If *n* is not provided or set to ``-1``, read until EOF, then return all " "read :class:`bytes`. If EOF was received and the internal buffer is empty, " "return an empty ``bytes`` object." msgstr "" -#: ../../library/asyncio-stream.rst:220 +#: ../../library/asyncio-stream.rst:229 msgid "If *n* is ``0``, return an empty ``bytes`` object immediately." msgstr "" -#: ../../library/asyncio-stream.rst:222 +#: ../../library/asyncio-stream.rst:231 msgid "" "If *n* is positive, return at most *n* available ``bytes`` as soon as at " "least 1 byte is available in the internal buffer. If EOF is received before " "any byte is read, return an empty ``bytes`` object." msgstr "" -#: ../../library/asyncio-stream.rst:229 +#: ../../library/asyncio-stream.rst:239 msgid "" "Read one line, where \"line\" is a sequence of bytes ending with ``\\n``." msgstr "" "Lê uma linha, onde \"line\" é uma sequência de bytes encerrando com ``\\n``." -#: ../../library/asyncio-stream.rst:232 +#: ../../library/asyncio-stream.rst:242 msgid "" "If EOF is received and ``\\n`` was not found, the method returns partially " "read data." @@ -276,7 +297,7 @@ msgstr "" "Se EOF é recebido e ``\\n`` não foi encontrado, o método retorna os dados " "parcialmente lidos." -#: ../../library/asyncio-stream.rst:235 +#: ../../library/asyncio-stream.rst:245 msgid "" "If EOF is received and the internal buffer is empty, return an empty " "``bytes`` object." @@ -284,11 +305,11 @@ msgstr "" "Se EOF for recebido e o buffer interno estiver vazio, retorna um objeto " "``bytes`` vazio." -#: ../../library/asyncio-stream.rst:240 +#: ../../library/asyncio-stream.rst:251 msgid "Read exactly *n* bytes." msgstr "Lê exatamente *n* bytes." -#: ../../library/asyncio-stream.rst:242 +#: ../../library/asyncio-stream.rst:253 msgid "" "Raise an :exc:`IncompleteReadError` if EOF is reached before *n* can be " "read. Use the :attr:`IncompleteReadError.partial` attribute to get the " @@ -298,11 +319,11 @@ msgstr "" "lidos. Use o atributo :attr:`IncompleteReadError.partial` para obter os " "dados parcialmente lidos." -#: ../../library/asyncio-stream.rst:248 +#: ../../library/asyncio-stream.rst:260 msgid "Read data from the stream until *separator* is found." msgstr "Lê dados a partir do stream até que *separator* seja encontrado." -#: ../../library/asyncio-stream.rst:250 +#: ../../library/asyncio-stream.rst:262 msgid "" "On success, the data and separator will be removed from the internal buffer " "(consumed). Returned data will include the separator at the end." @@ -310,7 +331,7 @@ msgstr "" "Ao ter sucesso, os dados e o separador serão removidos do buffer interno " "(consumido). Dados retornados irão incluir o separador no final." -#: ../../library/asyncio-stream.rst:254 +#: ../../library/asyncio-stream.rst:266 msgid "" "If the amount of data read exceeds the configured stream limit, a :exc:" "`LimitOverrunError` exception is raised, and the data is left in the " @@ -320,7 +341,7 @@ msgstr "" "uma exceção :exc:`LimitOverrunError` é levantada, e os dados são deixados no " "buffer interno e podem ser lidos novamente." -#: ../../library/asyncio-stream.rst:258 +#: ../../library/asyncio-stream.rst:270 msgid "" "If EOF is reached before the complete separator is found, an :exc:" "`IncompleteReadError` exception is raised, and the internal buffer is " @@ -332,7 +353,7 @@ msgstr "" "resetado. O atributo :attr:`IncompleteReadError.partial` pode conter uma " "parte do separador." -#: ../../library/asyncio-stream.rst:263 +#: ../../library/asyncio-stream.rst:275 msgid "" "The *separator* may also be a tuple of separators. In this case the return " "value will be the shortest possible that has any separator as the suffix. " @@ -340,27 +361,27 @@ msgid "" "separator is considered to be the one that matched." msgstr "" -#: ../../library/asyncio-stream.rst:273 +#: ../../library/asyncio-stream.rst:285 msgid "The *separator* parameter may now be a :class:`tuple` of separators." msgstr "" -#: ../../library/asyncio-stream.rst:278 +#: ../../library/asyncio-stream.rst:290 msgid "Return ``True`` if the buffer is empty and :meth:`feed_eof` was called." msgstr "" "Retorna ``True`` se o buffer estiver vazio e :meth:`feed_eof` foi chamado." -#: ../../library/asyncio-stream.rst:283 +#: ../../library/asyncio-stream.rst:295 msgid "StreamWriter" msgstr "StreamWriter" -#: ../../library/asyncio-stream.rst:287 +#: ../../library/asyncio-stream.rst:299 msgid "" "Represents a writer object that provides APIs to write data to the IO stream." msgstr "" "Representa um objeto de escrita que fornece APIs para escrever dados para o " "stream de IO." -#: ../../library/asyncio-stream.rst:290 +#: ../../library/asyncio-stream.rst:302 msgid "" "It is not recommended to instantiate *StreamWriter* objects directly; use :" "func:`open_connection` and :func:`start_server` instead." @@ -368,7 +389,7 @@ msgstr "" "Não é recomendado instanciar objetos *StreamWriter* diretamente; use :func:" "`open_connection` e :func:`start_server` ao invés." -#: ../../library/asyncio-stream.rst:296 +#: ../../library/asyncio-stream.rst:308 msgid "" "The method attempts to write the *data* to the underlying socket " "immediately. If that fails, the data is queued in an internal write buffer " @@ -378,11 +399,17 @@ msgstr "" "isso falhar, data é enfileirado em um buffer interno de escrita, até que " "possa ser enviado." -#: ../../library/asyncio-stream.rst:300 ../../library/asyncio-stream.rst:312 +#: ../../library/asyncio-stream.rst:312 ../../library/asyncio-stream.rst:324 msgid "The method should be used along with the ``drain()`` method::" msgstr "O método deve ser usado juntamente com o método ``drain()``::" -#: ../../library/asyncio-stream.rst:307 +#: ../../library/asyncio-stream.rst:314 +msgid "" +"stream.write(data)\n" +"await stream.drain()" +msgstr "" + +#: ../../library/asyncio-stream.rst:319 msgid "" "The method writes a list (or any iterable) of bytes to the underlying socket " "immediately. If that fails, the data is queued in an internal write buffer " @@ -392,17 +419,29 @@ msgstr "" "o soquete subjacente. Se isso falhar, os dados são enfileirados em um buffer " "de escrita interno até que possam ser enviados." -#: ../../library/asyncio-stream.rst:319 +#: ../../library/asyncio-stream.rst:326 +msgid "" +"stream.writelines(lines)\n" +"await stream.drain()" +msgstr "" + +#: ../../library/asyncio-stream.rst:331 msgid "The method closes the stream and the underlying socket." msgstr "O método fecha o stream e o soquete subjacente." -#: ../../library/asyncio-stream.rst:321 +#: ../../library/asyncio-stream.rst:333 msgid "" "The method should be used, though not mandatory, along with the " "``wait_closed()`` method::" msgstr "" -#: ../../library/asyncio-stream.rst:329 +#: ../../library/asyncio-stream.rst:336 +msgid "" +"stream.close()\n" +"await stream.wait_closed()" +msgstr "" + +#: ../../library/asyncio-stream.rst:341 msgid "" "Return ``True`` if the underlying transport supports the :meth:`write_eof` " "method, ``False`` otherwise." @@ -410,18 +449,18 @@ msgstr "" "Retorna ``True`` se o transporte subjacente suporta o método :meth:" "`write_eof`, ``False`` caso contrário." -#: ../../library/asyncio-stream.rst:334 +#: ../../library/asyncio-stream.rst:346 msgid "" "Close the write end of the stream after the buffered write data is flushed." msgstr "" "Fecha o extremo de escrita do stream após os dados no buffer de escrita " "terem sido descarregados." -#: ../../library/asyncio-stream.rst:339 +#: ../../library/asyncio-stream.rst:351 msgid "Return the underlying asyncio transport." msgstr "Retorna o transporte asyncio subjacente." -#: ../../library/asyncio-stream.rst:343 +#: ../../library/asyncio-stream.rst:355 msgid "" "Access optional transport information; see :meth:`BaseTransport." "get_extra_info` for details." @@ -429,12 +468,18 @@ msgstr "" "Acessa informações de transporte opcionais; veja :meth:`BaseTransport." "get_extra_info` para detalhes." -#: ../../library/asyncio-stream.rst:348 +#: ../../library/asyncio-stream.rst:361 msgid "Wait until it is appropriate to resume writing to the stream. Example::" msgstr "" "Aguarda até que seja apropriado continuar escrevendo no stream. Exemplo::" -#: ../../library/asyncio-stream.rst:354 +#: ../../library/asyncio-stream.rst:364 +msgid "" +"writer.write(data)\n" +"await writer.drain()" +msgstr "" + +#: ../../library/asyncio-stream.rst:367 msgid "" "This is a flow control method that interacts with the underlying IO write " "buffer. When the size of the buffer reaches the high watermark, *drain()* " @@ -448,19 +493,19 @@ msgstr "" "para a marca d'água baixa, e a escrita possa continuar. Quando não existe " "nada que cause uma espera, o método :meth:`drain` retorna imediatamente." -#: ../../library/asyncio-stream.rst:364 +#: ../../library/asyncio-stream.rst:378 msgid "Upgrade an existing stream-based connection to TLS." msgstr "" -#: ../../library/asyncio-stream.rst:366 +#: ../../library/asyncio-stream.rst:380 msgid "Parameters:" msgstr "Parâmetros:" -#: ../../library/asyncio-stream.rst:368 +#: ../../library/asyncio-stream.rst:382 msgid "*sslcontext*: a configured instance of :class:`~ssl.SSLContext`." msgstr "*sslcontext*: uma instância configurada de :class:`~ssl.SSLContext`." -#: ../../library/asyncio-stream.rst:370 +#: ../../library/asyncio-stream.rst:384 msgid "" "*server_hostname*: sets or overrides the host name that the target server's " "certificate will be matched against." @@ -468,50 +513,50 @@ msgstr "" "*server_hostname*: define ou substitui o nome do host no qual o servidor " "alvo do certificado será comparado." -#: ../../library/asyncio-stream.rst:373 +#: ../../library/asyncio-stream.rst:387 msgid "" "*ssl_handshake_timeout* is the time in seconds to wait for the TLS handshake " "to complete before aborting the connection. ``60.0`` seconds if ``None`` " "(default)." msgstr "" -#: ../../library/asyncio-stream.rst:377 +#: ../../library/asyncio-stream.rst:391 msgid "" "*ssl_shutdown_timeout* is the time in seconds to wait for the SSL shutdown " "to complete before aborting the connection. ``30.0`` seconds if ``None`` " "(default)." msgstr "" -#: ../../library/asyncio-stream.rst:389 +#: ../../library/asyncio-stream.rst:403 msgid "" "Return ``True`` if the stream is closed or in the process of being closed." msgstr "" "Retorna ``True`` se o stream estiver fechado ou em processo de ser fechado." -#: ../../library/asyncio-stream.rst:396 +#: ../../library/asyncio-stream.rst:411 msgid "Wait until the stream is closed." msgstr "Aguarda até que o stream seja fechado." -#: ../../library/asyncio-stream.rst:398 +#: ../../library/asyncio-stream.rst:413 msgid "" "Should be called after :meth:`close` to wait until the underlying connection " "is closed, ensuring that all data has been flushed before e.g. exiting the " "program." msgstr "" -#: ../../library/asyncio-stream.rst:406 +#: ../../library/asyncio-stream.rst:421 msgid "Examples" msgstr "Exemplos" -#: ../../library/asyncio-stream.rst:411 +#: ../../library/asyncio-stream.rst:426 msgid "TCP echo client using streams" msgstr "Cliente para eco TCP usando streams" -#: ../../library/asyncio-stream.rst:413 +#: ../../library/asyncio-stream.rst:428 msgid "TCP echo client using the :func:`asyncio.open_connection` function::" msgstr "Cliente de eco TCP usando a função :func:`asyncio.open_connection`::" -#: ../../library/asyncio-stream.rst:437 +#: ../../library/asyncio-stream.rst:452 msgid "" "The :ref:`TCP echo client protocol " "` example uses the low-level :meth:" @@ -521,15 +566,47 @@ msgstr "" "` usa o método de baixo nível :" "meth:`loop.create_connection`." -#: ../../library/asyncio-stream.rst:444 +#: ../../library/asyncio-stream.rst:459 msgid "TCP echo server using streams" msgstr "Servidor eco TCP usando streams" -#: ../../library/asyncio-stream.rst:446 +#: ../../library/asyncio-stream.rst:461 msgid "TCP echo server using the :func:`asyncio.start_server` function::" msgstr "Servidor eco TCP usando a função :func:`asyncio.start_server`::" -#: ../../library/asyncio-stream.rst:480 +#: ../../library/asyncio-stream.rst:463 +msgid "" +"import asyncio\n" +"\n" +"async def handle_echo(reader, writer):\n" +" data = await reader.read(100)\n" +" message = data.decode()\n" +" addr = writer.get_extra_info('peername')\n" +"\n" +" print(f\"Received {message!r} from {addr!r}\")\n" +"\n" +" print(f\"Send: {message!r}\")\n" +" writer.write(data)\n" +" await writer.drain()\n" +"\n" +" print(\"Close the connection\")\n" +" writer.close()\n" +" await writer.wait_closed()\n" +"\n" +"async def main():\n" +" server = await asyncio.start_server(\n" +" handle_echo, '127.0.0.1', 8888)\n" +"\n" +" addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets)\n" +" print(f'Serving on {addrs}')\n" +"\n" +" async with server:\n" +" await server.serve_forever()\n" +"\n" +"asyncio.run(main())" +msgstr "" + +#: ../../library/asyncio-stream.rst:495 msgid "" "The :ref:`TCP echo server protocol " "` example uses the :meth:`loop." @@ -539,30 +616,77 @@ msgstr "" "` utiliza o método :meth:`loop." "create_server`." -#: ../../library/asyncio-stream.rst:485 +#: ../../library/asyncio-stream.rst:500 msgid "Get HTTP headers" msgstr "Obtém headers HTTP" -#: ../../library/asyncio-stream.rst:487 +#: ../../library/asyncio-stream.rst:502 msgid "" "Simple example querying HTTP headers of the URL passed on the command line::" msgstr "" "Exemplo simples consultando cabeçalhos HTTP da URL passada na linha de " "comando::" -#: ../../library/asyncio-stream.rst:526 +#: ../../library/asyncio-stream.rst:504 +msgid "" +"import asyncio\n" +"import urllib.parse\n" +"import sys\n" +"\n" +"async def print_http_headers(url):\n" +" url = urllib.parse.urlsplit(url)\n" +" if url.scheme == 'https':\n" +" reader, writer = await asyncio.open_connection(\n" +" url.hostname, 443, ssl=True)\n" +" else:\n" +" reader, writer = await asyncio.open_connection(\n" +" url.hostname, 80)\n" +"\n" +" query = (\n" +" f\"HEAD {url.path or '/'} HTTP/1.0\\r\\n\"\n" +" f\"Host: {url.hostname}\\r\\n\"\n" +" f\"\\r\\n\"\n" +" )\n" +"\n" +" writer.write(query.encode('latin-1'))\n" +" while True:\n" +" line = await reader.readline()\n" +" if not line:\n" +" break\n" +"\n" +" line = line.decode('latin1').rstrip()\n" +" if line:\n" +" print(f'HTTP header> {line}')\n" +"\n" +" # Ignore the body, close the socket\n" +" writer.close()\n" +" await writer.wait_closed()\n" +"\n" +"url = sys.argv[1]\n" +"asyncio.run(print_http_headers(url))" +msgstr "" + +#: ../../library/asyncio-stream.rst:541 msgid "Usage::" msgstr "Uso::" -#: ../../library/asyncio-stream.rst:530 +#: ../../library/asyncio-stream.rst:543 +msgid "python example.py http://example.com/path/page.html" +msgstr "" + +#: ../../library/asyncio-stream.rst:545 msgid "or with HTTPS::" msgstr "ou com HTTPS::" -#: ../../library/asyncio-stream.rst:538 +#: ../../library/asyncio-stream.rst:547 +msgid "python example.py https://example.com/path/page.html" +msgstr "" + +#: ../../library/asyncio-stream.rst:553 msgid "Register an open socket to wait for data using streams" msgstr "Registra um soquete aberto para aguardar por dados usando streams" -#: ../../library/asyncio-stream.rst:540 +#: ../../library/asyncio-stream.rst:555 msgid "" "Coroutine waiting until a socket receives data using the :func:" "`open_connection` function::" @@ -570,7 +694,40 @@ msgstr "" "Corrotina aguardando até que um soquete receba dados usando a função :func:" "`open_connection`::" -#: ../../library/asyncio-stream.rst:575 +#: ../../library/asyncio-stream.rst:558 +msgid "" +"import asyncio\n" +"import socket\n" +"\n" +"async def wait_for_data():\n" +" # Get a reference to the current event loop because\n" +" # we want to access low-level APIs.\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" # Create a pair of connected sockets.\n" +" rsock, wsock = socket.socketpair()\n" +"\n" +" # Register the open socket to wait for data.\n" +" reader, writer = await asyncio.open_connection(sock=rsock)\n" +"\n" +" # Simulate the reception of data from the network\n" +" loop.call_soon(wsock.send, 'abc'.encode())\n" +"\n" +" # Wait for data\n" +" data = await reader.read(100)\n" +"\n" +" # Got data, we are done: close the socket\n" +" print(\"Received:\", data.decode())\n" +" writer.close()\n" +" await writer.wait_closed()\n" +"\n" +" # Close the second socket\n" +" wsock.close()\n" +"\n" +"asyncio.run(wait_for_data())" +msgstr "" + +#: ../../library/asyncio-stream.rst:590 msgid "" "The :ref:`register an open socket to wait for data using a protocol " "` example uses a low-level protocol and " @@ -580,7 +737,7 @@ msgstr "" "usando um protocolo ` utiliza um " "protocolo de baixo nível e o método :meth:`loop.create_connection`." -#: ../../library/asyncio-stream.rst:579 +#: ../../library/asyncio-stream.rst:594 msgid "" "The :ref:`watch a file descriptor for read events " "` example uses the low-level :meth:`loop." diff --git a/library/asyncio-subprocess.po b/library/asyncio-subprocess.po index 7c451873d..1cb18026a 100644 --- a/library/asyncio-subprocess.po +++ b/library/asyncio-subprocess.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Vinicius Gubiani Ferreira , 2021 -# i17obot , 2021 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:55+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-03-14 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -56,10 +51,58 @@ msgstr "" "Aqui está um exemplo de como asyncio pode executar um comando shell e obter " "o seu resultado::" +#: ../../library/asyncio-subprocess.rst:22 +msgid "" +"import asyncio\n" +"\n" +"async def run(cmd):\n" +" proc = await asyncio.create_subprocess_shell(\n" +" cmd,\n" +" stdout=asyncio.subprocess.PIPE,\n" +" stderr=asyncio.subprocess.PIPE)\n" +"\n" +" stdout, stderr = await proc.communicate()\n" +"\n" +" print(f'[{cmd!r} exited with {proc.returncode}]')\n" +" if stdout:\n" +" print(f'[stdout]\\n{stdout.decode()}')\n" +" if stderr:\n" +" print(f'[stderr]\\n{stderr.decode()}')\n" +"\n" +"asyncio.run(run('ls /zzz'))" +msgstr "" +"import asyncio\n" +"\n" +"async def run(cmd):\n" +" proc = await asyncio.create_subprocess_shell(\n" +" cmd,\n" +" stdout=asyncio.subprocess.PIPE,\n" +" stderr=asyncio.subprocess.PIPE)\n" +"\n" +" stdout, stderr = await proc.communicate()\n" +"\n" +" print(f'[{cmd!r} exited with {proc.returncode}]')\n" +" if stdout:\n" +" print(f'[stdout]\\n{stdout.decode()}')\n" +" if stderr:\n" +" print(f'[stderr]\\n{stderr.decode()}')\n" +"\n" +"asyncio.run(run('ls /zzz'))" + #: ../../library/asyncio-subprocess.rst:40 msgid "will print::" msgstr "irá exibir::" +#: ../../library/asyncio-subprocess.rst:42 +msgid "" +"['ls /zzz' exited with 1]\n" +"[stderr]\n" +"ls: /zzz: No such file or directory" +msgstr "" +"['ls /zzz' exited with 1]\n" +"[stderr]\n" +"ls: /zzz: No such file or directory" + #: ../../library/asyncio-subprocess.rst:46 msgid "" "Because all asyncio subprocess functions are asynchronous and asyncio " @@ -73,6 +116,22 @@ msgstr "" "trivial modificar o exemplo acima para executar diversos comandos " "simultaneamente::" +#: ../../library/asyncio-subprocess.rst:51 +msgid "" +"async def main():\n" +" await asyncio.gather(\n" +" run('ls /zzz'),\n" +" run('sleep 1; echo \"hello\"'))\n" +"\n" +"asyncio.run(main())" +msgstr "" +"async def main():\n" +" await asyncio.gather(\n" +" run('ls /zzz'),\n" +" run('sleep 1; echo \"hello\"'))\n" +"\n" +"asyncio.run(main())" + #: ../../library/asyncio-subprocess.rst:58 msgid "See also the `Examples`_ subsection." msgstr "Veja também a subseção `Exemplos`_." @@ -81,48 +140,50 @@ msgstr "Veja também a subseção `Exemplos`_." msgid "Creating Subprocesses" msgstr "Criando subprocessos" -#: ../../library/asyncio-subprocess.rst:67 +#: ../../library/asyncio-subprocess.rst:68 msgid "Create a subprocess." msgstr "Cria um subprocesso." -#: ../../library/asyncio-subprocess.rst:69 -#: ../../library/asyncio-subprocess.rst:87 +#: ../../library/asyncio-subprocess.rst:70 +#: ../../library/asyncio-subprocess.rst:89 msgid "" "The *limit* argument sets the buffer limit for :class:`StreamReader` " -"wrappers for :attr:`Process.stdout` and :attr:`Process.stderr` (if :const:" -"`subprocess.PIPE` is passed to *stdout* and *stderr* arguments)." +"wrappers for :attr:`~asyncio.subprocess.Process.stdout` and :attr:`~asyncio." +"subprocess.Process.stderr` (if :const:`subprocess.PIPE` is passed to " +"*stdout* and *stderr* arguments)." msgstr "" "O argumento *limit* define o limite do buffer para os invólucros :class:" -"`StreamReader` para :attr:`Process.stdout` e :attr:`Process.stderr` (se :" -"const:`subprocess.PIPE` for passado para os argumentos *stdout* e *stderr*)." +"`StreamReader` para :attr:`~asyncio.subprocess.Process.stdout` e :attr:" +"`~asyncio.subprocess.Process.stderr` (se :const:`subprocess.PIPE` for " +"passado para os argumentos *stdout* e *stderr*)." -#: ../../library/asyncio-subprocess.rst:73 -#: ../../library/asyncio-subprocess.rst:91 +#: ../../library/asyncio-subprocess.rst:74 +#: ../../library/asyncio-subprocess.rst:93 msgid "Return a :class:`~asyncio.subprocess.Process` instance." msgstr "Retorna uma instância de :class:`~asyncio.subprocess.Process`." -#: ../../library/asyncio-subprocess.rst:75 +#: ../../library/asyncio-subprocess.rst:76 msgid "" "See the documentation of :meth:`loop.subprocess_exec` for other parameters." msgstr "" "Veja a documentação de :meth:`loop.subprocess_exec` para outros parâmetros." -#: ../../library/asyncio-subprocess.rst:78 -#: ../../library/asyncio-subprocess.rst:105 +#: ../../library/asyncio-subprocess.rst:79 +#: ../../library/asyncio-subprocess.rst:107 msgid "Removed the *loop* parameter." msgstr "Removido o parâmetro *loop*." -#: ../../library/asyncio-subprocess.rst:85 +#: ../../library/asyncio-subprocess.rst:87 msgid "Run the *cmd* shell command." msgstr "Executa o comando *cmd* no shell." -#: ../../library/asyncio-subprocess.rst:93 +#: ../../library/asyncio-subprocess.rst:95 msgid "" "See the documentation of :meth:`loop.subprocess_shell` for other parameters." msgstr "" "Veja a documentação de :meth:`loop.subprocess_shell` para outros parâmetros." -#: ../../library/asyncio-subprocess.rst:98 +#: ../../library/asyncio-subprocess.rst:100 msgid "" "It is the application's responsibility to ensure that all whitespace and " "special characters are quoted appropriately to avoid `shell injection " @@ -138,7 +199,7 @@ msgstr "" "usada para escapar espaços em branco e caracteres especiais de shell " "apropriadamente em strings que serão usadas para construir comandos shell." -#: ../../library/asyncio-subprocess.rst:110 +#: ../../library/asyncio-subprocess.rst:112 msgid "" "Subprocesses are available for Windows if a :class:`ProactorEventLoop` is " "used. See :ref:`Subprocess Support on Windows ` " @@ -148,7 +209,7 @@ msgstr "" "`ProactorEventLoop` for usada. Veja :ref:`Suporte para subprocesso para " "Windows ` para detalhes." -#: ../../library/asyncio-subprocess.rst:116 +#: ../../library/asyncio-subprocess.rst:118 msgid "" "asyncio also has the following *low-level* APIs to work with subprocesses: :" "meth:`loop.subprocess_exec`, :meth:`loop.subprocess_shell`, :meth:`loop." @@ -162,37 +223,37 @@ msgstr "" "os :ref:`Transportes de Subprocesso ` e :ref:" "`Protocolos de Subprocesso `." -#: ../../library/asyncio-subprocess.rst:124 +#: ../../library/asyncio-subprocess.rst:126 msgid "Constants" msgstr "Constantes" -#: ../../library/asyncio-subprocess.rst:129 +#: ../../library/asyncio-subprocess.rst:131 msgid "Can be passed to the *stdin*, *stdout* or *stderr* parameters." msgstr "Pode ser passado para os parâmetros *stdin*, *stdout* ou *stderr*." -#: ../../library/asyncio-subprocess.rst:131 +#: ../../library/asyncio-subprocess.rst:133 msgid "" "If *PIPE* is passed to *stdin* argument, the :attr:`Process.stdin ` attribute will point to a :class:`StreamWriter` " -"instance." +"subprocess.Process.stdin>` attribute will point to a :class:`~asyncio." +"StreamWriter` instance." msgstr "" "Se *PIPE* for passado para o argumento *stdin*, o atributo :attr:`Process." "stdin ` irá apontar para uma instância :" -"class:`StreamWriter`." +"class:`~asyncio.StreamWriter`." -#: ../../library/asyncio-subprocess.rst:135 +#: ../../library/asyncio-subprocess.rst:137 msgid "" "If *PIPE* is passed to *stdout* or *stderr* arguments, the :attr:`Process." "stdout ` and :attr:`Process.stderr " "` attributes will point to :class:" -"`StreamReader` instances." +"`~asyncio.StreamReader` instances." msgstr "" "Se *PIPE* for passado para os argumentos *stdout* ou *stderr*, os atributos :" "attr:`Process.stdout ` e :attr:`Process." "stderr ` irão apontar para instâncias :" -"class:`StreamReader`." +"class:`~asyncio.StreamReader`." -#: ../../library/asyncio-subprocess.rst:143 +#: ../../library/asyncio-subprocess.rst:145 msgid "" "Special value that can be used as the *stderr* argument and indicates that " "standard error should be redirected into standard output." @@ -200,7 +261,7 @@ msgstr "" "Valor especial que pode ser usado como o argumento *stderr* e indica que a " "saída de erro padrão deve ser redirecionada para a saída padrão." -#: ../../library/asyncio-subprocess.rst:149 +#: ../../library/asyncio-subprocess.rst:151 msgid "" "Special value that can be used as the *stdin*, *stdout* or *stderr* argument " "to process creation functions. It indicates that the special file :data:`os." @@ -211,11 +272,11 @@ msgstr "" "especial :data:`os.devnull` será usado para o fluxo de subprocesso " "correspondente." -#: ../../library/asyncio-subprocess.rst:155 +#: ../../library/asyncio-subprocess.rst:157 msgid "Interacting with Subprocesses" msgstr "Interagindo com subprocessos" -#: ../../library/asyncio-subprocess.rst:157 +#: ../../library/asyncio-subprocess.rst:159 msgid "" "Both :func:`create_subprocess_exec` and :func:`create_subprocess_shell` " "functions return instances of the *Process* class. *Process* is a high-" @@ -227,15 +288,17 @@ msgstr "" "é um invólucro de alto nível que permite a comunicação com subprocessos e " "observar eles serem completados." -#: ../../library/asyncio-subprocess.rst:165 +#: ../../library/asyncio-subprocess.rst:167 msgid "" -"An object that wraps OS processes created by the :func:" -"`create_subprocess_exec` and :func:`create_subprocess_shell` functions." +"An object that wraps OS processes created by the :func:`~asyncio." +"create_subprocess_exec` and :func:`~asyncio.create_subprocess_shell` " +"functions." msgstr "" "Um objeto que envolve processos do sistema operacional criados pelas " -"funções :func:`create_subprocess_exec` e :func:`create_subprocess_shell`." +"funções :func:`~asyncio.create_subprocess_exec` e :func:`~asyncio." +"create_subprocess_shell`." -#: ../../library/asyncio-subprocess.rst:169 +#: ../../library/asyncio-subprocess.rst:171 msgid "" "This class is designed to have a similar API to the :class:`subprocess." "Popen` class, but there are some notable differences:" @@ -243,7 +306,7 @@ msgstr "" "Esta classe é projetada para ter uma API similar a classe :class:`subprocess." "Popen`, mas existem algumas diferenças notáveis:" -#: ../../library/asyncio-subprocess.rst:173 +#: ../../library/asyncio-subprocess.rst:175 msgid "" "unlike Popen, Process instances do not have an equivalent to the :meth:" "`~subprocess.Popen.poll` method;" @@ -251,7 +314,7 @@ msgstr "" "ao contrário de Popen, instâncias de Process não têm um equivalente ao " "método :meth:`~subprocess.Popen.poll`;" -#: ../../library/asyncio-subprocess.rst:176 +#: ../../library/asyncio-subprocess.rst:178 msgid "" "the :meth:`~asyncio.subprocess.Process.communicate` and :meth:`~asyncio." "subprocess.Process.wait` methods don't have a *timeout* parameter: use the :" @@ -261,7 +324,7 @@ msgstr "" "subprocess.Process.wait` não têm um parâmetro *timeout*: utilize a função :" "func:`~ascyncio.wait_for`;" -#: ../../library/asyncio-subprocess.rst:180 +#: ../../library/asyncio-subprocess.rst:182 msgid "" "the :meth:`Process.wait() ` method is " "asynchronous, whereas :meth:`subprocess.Popen.wait` method is implemented as " @@ -271,15 +334,15 @@ msgstr "" "assíncrono, enquanto que o método :meth:`subprocess.Popen.wait` é " "implementado como um laço bloqueante para indicar que está ocupado;" -#: ../../library/asyncio-subprocess.rst:184 +#: ../../library/asyncio-subprocess.rst:186 msgid "the *universal_newlines* parameter is not supported." msgstr "o parâmetro *universal_newlines* não é suportado." -#: ../../library/asyncio-subprocess.rst:186 +#: ../../library/asyncio-subprocess.rst:188 msgid "This class is :ref:`not thread safe `." msgstr "Esta classe :ref:`não é segura para thread `." -#: ../../library/asyncio-subprocess.rst:188 +#: ../../library/asyncio-subprocess.rst:190 msgid "" "See also the :ref:`Subprocess and Threads ` " "section." @@ -287,15 +350,15 @@ msgstr "" "Veja também a seção :ref:`Subprocesso e Threads `." -#: ../../library/asyncio-subprocess.rst:193 +#: ../../library/asyncio-subprocess.rst:196 msgid "Wait for the child process to terminate." msgstr "Aguarda o processo filho encerrar." -#: ../../library/asyncio-subprocess.rst:195 +#: ../../library/asyncio-subprocess.rst:198 msgid "Set and return the :attr:`returncode` attribute." msgstr "Define e retorna o atributo :attr:`returncode`." -#: ../../library/asyncio-subprocess.rst:199 +#: ../../library/asyncio-subprocess.rst:202 msgid "" "This method can deadlock when using ``stdout=PIPE`` or ``stderr=PIPE`` and " "the child process generates so much output that it blocks waiting for the OS " @@ -308,29 +371,29 @@ msgstr "" "dados. Use o método :meth:`communicate` ao usar encadeamentos para evitar " "essa condição." -#: ../../library/asyncio-subprocess.rst:207 +#: ../../library/asyncio-subprocess.rst:211 msgid "Interact with process:" msgstr "Interage com processo:" -#: ../../library/asyncio-subprocess.rst:209 +#: ../../library/asyncio-subprocess.rst:213 msgid "send data to *stdin* (if *input* is not ``None``);" msgstr "envia dados para *stdin* (se *input* for diferente de ``None``);" -#: ../../library/asyncio-subprocess.rst:210 +#: ../../library/asyncio-subprocess.rst:214 msgid "closes *stdin*;" msgstr "fecha *stdin*;" -#: ../../library/asyncio-subprocess.rst:211 +#: ../../library/asyncio-subprocess.rst:215 msgid "read data from *stdout* and *stderr*, until EOF is reached;" msgstr "" "lê dados a partir de *stdout* e *stderr*, até que EOF (fim do arquivo) seja " "atingido;" -#: ../../library/asyncio-subprocess.rst:212 +#: ../../library/asyncio-subprocess.rst:216 msgid "wait for process to terminate." msgstr "aguarda o processo encerrar." -#: ../../library/asyncio-subprocess.rst:214 +#: ../../library/asyncio-subprocess.rst:218 msgid "" "The optional *input* argument is the data (:class:`bytes` object) that will " "be sent to the child process." @@ -338,11 +401,11 @@ msgstr "" "O argumento opcional *input* é a informação (objeto :class:`bytes`) que será " "enviada para o processo filho." -#: ../../library/asyncio-subprocess.rst:217 +#: ../../library/asyncio-subprocess.rst:221 msgid "Return a tuple ``(stdout_data, stderr_data)``." msgstr "Retorna uma tupla ``(stdout_data, stderr_data)``." -#: ../../library/asyncio-subprocess.rst:219 +#: ../../library/asyncio-subprocess.rst:223 msgid "" "If either :exc:`BrokenPipeError` or :exc:`ConnectionResetError` exception is " "raised when writing *input* into *stdin*, the exception is ignored. This " @@ -354,7 +417,7 @@ msgstr "" "condição ocorre quando o processo encerra antes de todos os dados serem " "escritos em *stdin*." -#: ../../library/asyncio-subprocess.rst:224 +#: ../../library/asyncio-subprocess.rst:228 msgid "" "If it is desired to send data to the process' *stdin*, the process needs to " "be created with ``stdin=PIPE``. Similarly, to get anything other than " @@ -366,7 +429,7 @@ msgstr "" "de ``None`` na tupla resultante, o processo precisa ser criado com os " "argumentos ``stdout=PIPE`` e/ou ``stderr=PIPE``." -#: ../../library/asyncio-subprocess.rst:230 +#: ../../library/asyncio-subprocess.rst:234 msgid "" "Note, that the data read is buffered in memory, so do not use this method if " "the data size is large or unlimited." @@ -374,15 +437,15 @@ msgstr "" "Perceba que, os dados lidos são armazenados em um buffer na memória, então " "não use este método se o tamanho dos dados é grande ou ilimitado." -#: ../../library/asyncio-subprocess.rst:235 -msgid "*stdin* gets closed when `input=None` too." -msgstr "*stdin* é fechado quando `input=None` é também." - #: ../../library/asyncio-subprocess.rst:239 +msgid "*stdin* gets closed when ``input=None`` too." +msgstr "*stdin* é fechado quando ``input=None`` é também." + +#: ../../library/asyncio-subprocess.rst:243 msgid "Sends the signal *signal* to the child process." msgstr "Envia o sinal *signal* para o processo filho." -#: ../../library/asyncio-subprocess.rst:243 +#: ../../library/asyncio-subprocess.rst:247 msgid "" "On Windows, :py:const:`~signal.SIGTERM` is an alias for :meth:`terminate`. " "``CTRL_C_EVENT`` and ``CTRL_BREAK_EVENT`` can be sent to processes started " @@ -393,11 +456,11 @@ msgstr "" "iniciados com um parâmetro *creationflags*, o qual inclui " "``CREATE_NEW_PROCESS_GROUP``." -#: ../../library/asyncio-subprocess.rst:250 +#: ../../library/asyncio-subprocess.rst:254 msgid "Stop the child process." msgstr "Interrompe o processo filho." -#: ../../library/asyncio-subprocess.rst:252 +#: ../../library/asyncio-subprocess.rst:256 msgid "" "On POSIX systems this method sends :py:const:`~signal.SIGTERM` to the child " "process." @@ -405,7 +468,7 @@ msgstr "" "Em sistemas POSIX este método envia :py:const:`~signal.SIGTERM` para o " "processo filho." -#: ../../library/asyncio-subprocess.rst:255 +#: ../../library/asyncio-subprocess.rst:259 msgid "" "On Windows the Win32 API function :c:func:`!TerminateProcess` is called to " "stop the child process." @@ -413,45 +476,47 @@ msgstr "" "No Windows a função :c:func:`!TerminateProcess` da API Win32 é chamada para " "interromper o processo filho." -#: ../../library/asyncio-subprocess.rst:260 +#: ../../library/asyncio-subprocess.rst:264 msgid "Kill the child process." msgstr "Mata o processo filho." -#: ../../library/asyncio-subprocess.rst:262 +#: ../../library/asyncio-subprocess.rst:266 msgid "" -"On POSIX systems this method sends :py:data:`SIGKILL` to the child process." +"On POSIX systems this method sends :py:data:`~signal.SIGKILL` to the child " +"process." msgstr "" -"Em sistemas POSIX este método envia :py:data:`SIGKILL` para o processo filho." +"Em sistemas POSIX este método envia :py:data:`~signal.SIGKILL` para o " +"processo filho." -#: ../../library/asyncio-subprocess.rst:265 +#: ../../library/asyncio-subprocess.rst:269 msgid "On Windows this method is an alias for :meth:`terminate`." msgstr "No Windows, este método é um atalho para :meth:`terminate`." -#: ../../library/asyncio-subprocess.rst:269 +#: ../../library/asyncio-subprocess.rst:273 msgid "" -"Standard input stream (:class:`StreamWriter`) or ``None`` if the process was " -"created with ``stdin=None``." +"Standard input stream (:class:`~asyncio.StreamWriter`) or ``None`` if the " +"process was created with ``stdin=None``." msgstr "" -"Fluxo de entrada padrão (:class:`StreamWriter`) ou ``None`` se o processo " -"foi criado com ``stdin=None``." +"Fluxo de entrada padrão (:class:`~asyncio.StreamWriter`) ou ``None`` se o " +"processo foi criado com ``stdin=None``." -#: ../../library/asyncio-subprocess.rst:274 +#: ../../library/asyncio-subprocess.rst:278 msgid "" -"Standard output stream (:class:`StreamReader`) or ``None`` if the process " -"was created with ``stdout=None``." +"Standard output stream (:class:`~asyncio.StreamReader`) or ``None`` if the " +"process was created with ``stdout=None``." msgstr "" -"Fluxo de saída padrão (:class:`StreamReader`) ou ``None`` se o processo foi " -"criado com ``stdout=None``." +"Fluxo de saída padrão (:class:`~asyncio.StreamReader`) ou ``None`` se o " +"processo foi criado com ``stdout=None``." -#: ../../library/asyncio-subprocess.rst:279 +#: ../../library/asyncio-subprocess.rst:283 msgid "" -"Standard error stream (:class:`StreamReader`) or ``None`` if the process was " -"created with ``stderr=None``." +"Standard error stream (:class:`~asyncio.StreamReader`) or ``None`` if the " +"process was created with ``stderr=None``." msgstr "" -"Erro de fluxo padrão (:class:`StreamReader`) ou ``None`` se o processo foi " -"criado com ``stderr=None``." +"Erro de fluxo padrão (:class:`~asyncio.StreamReader`) ou ``None`` se o " +"processo foi criado com ``stderr=None``." -#: ../../library/asyncio-subprocess.rst:284 +#: ../../library/asyncio-subprocess.rst:288 msgid "" "Use the :meth:`communicate` method rather than :attr:`process.stdin.write() " "`, :attr:`await process.stdout.read() ` or :attr:`await " @@ -463,27 +528,28 @@ msgstr "" "process.stderr.read() `. Isso evita deadlocks devido a fluxos " "pausando a leitura ou escrita, e bloqueando o processo filho." -#: ../../library/asyncio-subprocess.rst:293 +#: ../../library/asyncio-subprocess.rst:297 msgid "Process identification number (PID)." msgstr "Número de identificação do processo (PID)." -#: ../../library/asyncio-subprocess.rst:295 +#: ../../library/asyncio-subprocess.rst:299 msgid "" -"Note that for processes created by the :func:`create_subprocess_shell` " -"function, this attribute is the PID of the spawned shell." +"Note that for processes created by the :func:`~asyncio." +"create_subprocess_shell` function, this attribute is the PID of the spawned " +"shell." msgstr "" -"Perceba que para processos criados pela função :func:" -"`create_subprocess_shell`, este atributo é o PID do console gerado." +"Perceba que para processos criados pela função :func:`~asyncio." +"create_subprocess_shell`, este atributo é o PID do console gerado." -#: ../../library/asyncio-subprocess.rst:300 +#: ../../library/asyncio-subprocess.rst:304 msgid "Return code of the process when it exits." msgstr "Retorna o código do processo quando o mesmo terminar." -#: ../../library/asyncio-subprocess.rst:302 +#: ../../library/asyncio-subprocess.rst:306 msgid "A ``None`` value indicates that the process has not terminated yet." msgstr "Um valor ``None`` indica que o processo ainda não terminou." -#: ../../library/asyncio-subprocess.rst:304 +#: ../../library/asyncio-subprocess.rst:308 msgid "" "A negative value ``-N`` indicates that the child was terminated by signal " "``N`` (POSIX only)." @@ -491,11 +557,11 @@ msgstr "" "Um valor negativo ``-N`` indica que o filho foi terminado pelo sinal ``N`` " "(POSIX apenas)." -#: ../../library/asyncio-subprocess.rst:311 +#: ../../library/asyncio-subprocess.rst:315 msgid "Subprocess and Threads" msgstr "Subprocesso e Threads" -#: ../../library/asyncio-subprocess.rst:313 +#: ../../library/asyncio-subprocess.rst:317 msgid "" "Standard asyncio event loop supports running subprocesses from different " "threads by default." @@ -503,7 +569,7 @@ msgstr "" "Laço de eventos padrão do asyncio suporta a execução de subprocessos a " "partir de diferentes threads por padrão." -#: ../../library/asyncio-subprocess.rst:316 +#: ../../library/asyncio-subprocess.rst:320 msgid "" "On Windows subprocesses are provided by :class:`ProactorEventLoop` only " "(default), :class:`SelectorEventLoop` has no subprocess support." @@ -512,7 +578,7 @@ msgstr "" "`ProactorEventLoop` apenas (por padrão), a classe :class:`SelectorEventLoop` " "não tem suporte a subprocesso." -#: ../../library/asyncio-subprocess.rst:319 +#: ../../library/asyncio-subprocess.rst:323 msgid "" "On UNIX *child watchers* are used for subprocess finish waiting, see :ref:" "`asyncio-watchers` for more info." @@ -521,7 +587,7 @@ msgstr "" "encerramento de subprocesso, veja :ref:`asyncio-watchers` para mais " "informações." -#: ../../library/asyncio-subprocess.rst:325 +#: ../../library/asyncio-subprocess.rst:329 msgid "" "UNIX switched to use :class:`ThreadedChildWatcher` for spawning subprocesses " "from different threads without any limitation." @@ -529,7 +595,7 @@ msgstr "" "UNIX mudou para usar :class:`ThreadedChildWatcher` para gerar subprocessos a " "partir de diferentes threads sem qualquer limitação." -#: ../../library/asyncio-subprocess.rst:328 +#: ../../library/asyncio-subprocess.rst:332 msgid "" "Spawning a subprocess with *inactive* current child watcher raises :exc:" "`RuntimeError`." @@ -537,7 +603,7 @@ msgstr "" "Gerar um subprocesso com um monitor *inativo* para o filho atual, levanta :" "exc:`RuntimeError`." -#: ../../library/asyncio-subprocess.rst:331 +#: ../../library/asyncio-subprocess.rst:335 msgid "" "Note that alternative event loop implementations might have own limitations; " "please refer to their documentation." @@ -545,7 +611,7 @@ msgstr "" "Perceba que implementações alternativas do laço de eventos podem ter " "limitações próprias; por favor, verifique a sua documentação." -#: ../../library/asyncio-subprocess.rst:336 +#: ../../library/asyncio-subprocess.rst:340 msgid "" "The :ref:`Concurrency and multithreading in asyncio ` section." @@ -553,11 +619,11 @@ msgstr "" "A seção :ref:`Concorrência e multithreading em asyncio `." -#: ../../library/asyncio-subprocess.rst:341 +#: ../../library/asyncio-subprocess.rst:345 msgid "Examples" msgstr "Exemplos" -#: ../../library/asyncio-subprocess.rst:343 +#: ../../library/asyncio-subprocess.rst:347 msgid "" "An example using the :class:`~asyncio.subprocess.Process` class to control a " "subprocess and the :class:`StreamReader` class to read from its standard " @@ -567,12 +633,60 @@ msgstr "" "controlar um subprocesso e a classe :class:`StreamReader` para ler a partir " "da sua saída padrão." -#: ../../library/asyncio-subprocess.rst:349 +#: ../../library/asyncio-subprocess.rst:353 msgid "" "The subprocess is created by the :func:`create_subprocess_exec` function::" msgstr "O subprocesso é criado pela função :func:`create_subprocess_exec`::" -#: ../../library/asyncio-subprocess.rst:376 +#: ../../library/asyncio-subprocess.rst:356 +msgid "" +"import asyncio\n" +"import sys\n" +"\n" +"async def get_date():\n" +" code = 'import datetime; print(datetime.datetime.now())'\n" +"\n" +" # Create the subprocess; redirect the standard output\n" +" # into a pipe.\n" +" proc = await asyncio.create_subprocess_exec(\n" +" sys.executable, '-c', code,\n" +" stdout=asyncio.subprocess.PIPE)\n" +"\n" +" # Read one line of output.\n" +" data = await proc.stdout.readline()\n" +" line = data.decode('ascii').rstrip()\n" +"\n" +" # Wait for the subprocess exit.\n" +" await proc.wait()\n" +" return line\n" +"\n" +"date = asyncio.run(get_date())\n" +"print(f\"Current date: {date}\")" +msgstr "" +"import asyncio\n" +"import sys\n" +"\n" +"async def get_date():\n" +" code = 'import datetime; print(datetime.datetime.now())'\n" +"\n" +" # Cria um subprocesso; redireciona a saída padrão\n" +" # para o encadeamento.\n" +" proc = await asyncio.create_subprocess_exec(\n" +" sys.executable, '-c', code,\n" +" stdout=asyncio.subprocess.PIPE)\n" +"\n" +" # Lê uma linha da saída.\n" +" data = await proc.stdout.readline()\n" +" line = data.decode('ascii').rstrip()\n" +"\n" +" # Espera o subprocesso sair.\n" +" await proc.wait()\n" +" return line\n" +"\n" +"date = asyncio.run(get_date())\n" +"print(f\"Current date: {date}\")" + +#: ../../library/asyncio-subprocess.rst:380 msgid "" "See also the :ref:`same example ` written " "using low-level APIs." diff --git a/library/asyncio-sync.po b/library/asyncio-sync.po index f77d526de..e2016b07b 100644 --- a/library/asyncio-sync.po +++ b/library/asyncio-sync.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Italo Penaforte , 2021 -# i17obot , 2021 -# Adorilson Bezerra , 2022 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 02:33+0000\n" -"PO-Revision-Date: 2021-06-28 00:55+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-28 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -101,70 +96,91 @@ msgstr "" msgid "The preferred way to use a Lock is an :keyword:`async with` statement::" msgstr "" -#: ../../library/asyncio-sync.rst:56 ../../library/asyncio-sync.rst:199 -#: ../../library/asyncio-sync.rst:304 +#: ../../library/asyncio-sync.rst:50 +msgid "" +"lock = asyncio.Lock()\n" +"\n" +"# ... later\n" +"async with lock:\n" +" # access shared state" +msgstr "" + +#: ../../library/asyncio-sync.rst:56 ../../library/asyncio-sync.rst:201 +#: ../../library/asyncio-sync.rst:309 msgid "which is equivalent to::" msgstr "" -#: ../../library/asyncio-sync.rst:67 ../../library/asyncio-sync.rst:112 -#: ../../library/asyncio-sync.rst:187 ../../library/asyncio-sync.rst:292 -#: ../../library/asyncio-sync.rst:347 +#: ../../library/asyncio-sync.rst:58 +msgid "" +"lock = asyncio.Lock()\n" +"\n" +"# ... later\n" +"await lock.acquire()\n" +"try:\n" +" # access shared state\n" +"finally:\n" +" lock.release()" +msgstr "" + +#: ../../library/asyncio-sync.rst:67 ../../library/asyncio-sync.rst:113 +#: ../../library/asyncio-sync.rst:189 ../../library/asyncio-sync.rst:297 +#: ../../library/asyncio-sync.rst:353 msgid "Removed the *loop* parameter." msgstr "Removido o parâmetro *loop*." -#: ../../library/asyncio-sync.rst:72 +#: ../../library/asyncio-sync.rst:73 msgid "Acquire the lock." msgstr "" -#: ../../library/asyncio-sync.rst:74 +#: ../../library/asyncio-sync.rst:75 msgid "" "This method waits until the lock is *unlocked*, sets it to *locked* and " "returns ``True``." msgstr "" -#: ../../library/asyncio-sync.rst:77 +#: ../../library/asyncio-sync.rst:78 msgid "" "When more than one coroutine is blocked in :meth:`acquire` waiting for the " "lock to be unlocked, only one coroutine eventually proceeds." msgstr "" -#: ../../library/asyncio-sync.rst:81 +#: ../../library/asyncio-sync.rst:82 msgid "" "Acquiring a lock is *fair*: the coroutine that proceeds will be the first " "coroutine that started waiting on the lock." msgstr "" -#: ../../library/asyncio-sync.rst:86 +#: ../../library/asyncio-sync.rst:87 msgid "Release the lock." msgstr "" -#: ../../library/asyncio-sync.rst:88 +#: ../../library/asyncio-sync.rst:89 msgid "When the lock is *locked*, reset it to *unlocked* and return." msgstr "" -#: ../../library/asyncio-sync.rst:90 +#: ../../library/asyncio-sync.rst:91 msgid "If the lock is *unlocked*, a :exc:`RuntimeError` is raised." msgstr "" -#: ../../library/asyncio-sync.rst:94 +#: ../../library/asyncio-sync.rst:95 msgid "Return ``True`` if the lock is *locked*." msgstr "" -#: ../../library/asyncio-sync.rst:98 +#: ../../library/asyncio-sync.rst:99 msgid "Event" msgstr "Evento" -#: ../../library/asyncio-sync.rst:102 +#: ../../library/asyncio-sync.rst:103 msgid "An event object. Not thread-safe." msgstr "" -#: ../../library/asyncio-sync.rst:104 +#: ../../library/asyncio-sync.rst:105 msgid "" "An asyncio event can be used to notify multiple asyncio tasks that some " "event has happened." msgstr "" -#: ../../library/asyncio-sync.rst:107 +#: ../../library/asyncio-sync.rst:108 msgid "" "An Event object manages an internal flag that can be set to *true* with the :" "meth:`~Event.set` method and reset to *false* with the :meth:`clear` " @@ -172,57 +188,81 @@ msgid "" "*true*. The flag is set to *false* initially." msgstr "" -#: ../../library/asyncio-sync.rst:117 ../../library/asyncio-sync.rst:371 +#: ../../library/asyncio-sync.rst:118 ../../library/asyncio-sync.rst:377 msgid "Example::" msgstr "Exemplo::" -#: ../../library/asyncio-sync.rst:142 -msgid "Wait until the event is set." +#: ../../library/asyncio-sync.rst:120 +msgid "" +"async def waiter(event):\n" +" print('waiting for it ...')\n" +" await event.wait()\n" +" print('... got it!')\n" +"\n" +"async def main():\n" +" # Create an Event object.\n" +" event = asyncio.Event()\n" +"\n" +" # Spawn a Task to wait until 'event' is set.\n" +" waiter_task = asyncio.create_task(waiter(event))\n" +"\n" +" # Sleep for 1 second and set the event.\n" +" await asyncio.sleep(1)\n" +" event.set()\n" +"\n" +" # Wait until the waiter task is finished.\n" +" await waiter_task\n" +"\n" +"asyncio.run(main())" msgstr "" #: ../../library/asyncio-sync.rst:144 +msgid "Wait until the event is set." +msgstr "" + +#: ../../library/asyncio-sync.rst:146 msgid "" "If the event is set, return ``True`` immediately. Otherwise block until " "another task calls :meth:`~Event.set`." msgstr "" -#: ../../library/asyncio-sync.rst:149 +#: ../../library/asyncio-sync.rst:151 msgid "Set the event." msgstr "" -#: ../../library/asyncio-sync.rst:151 +#: ../../library/asyncio-sync.rst:153 msgid "All tasks waiting for event to be set will be immediately awakened." msgstr "" -#: ../../library/asyncio-sync.rst:156 +#: ../../library/asyncio-sync.rst:158 msgid "Clear (unset) the event." msgstr "" -#: ../../library/asyncio-sync.rst:158 +#: ../../library/asyncio-sync.rst:160 msgid "" "Tasks awaiting on :meth:`~Event.wait` will now block until the :meth:`~Event." "set` method is called again." msgstr "" -#: ../../library/asyncio-sync.rst:163 +#: ../../library/asyncio-sync.rst:165 msgid "Return ``True`` if the event is set." msgstr "" -#: ../../library/asyncio-sync.rst:167 +#: ../../library/asyncio-sync.rst:169 msgid "Condition" msgstr "Condição" -#: ../../library/asyncio-sync.rst:171 +#: ../../library/asyncio-sync.rst:173 msgid "A Condition object. Not thread-safe." msgstr "" -#: ../../library/asyncio-sync.rst:173 +#: ../../library/asyncio-sync.rst:175 msgid "" "An asyncio condition primitive can be used by a task to wait for some event " "to happen and then get exclusive access to a shared resource." msgstr "" -#: ../../library/asyncio-sync.rst:177 +#: ../../library/asyncio-sync.rst:179 msgid "" "In essence, a Condition object combines the functionality of an :class:" "`Event` and a :class:`Lock`. It is possible to have multiple Condition " @@ -231,104 +271,126 @@ msgid "" "that shared resource." msgstr "" -#: ../../library/asyncio-sync.rst:183 +#: ../../library/asyncio-sync.rst:185 msgid "" "The optional *lock* argument must be a :class:`Lock` object or ``None``. In " "the latter case a new Lock object is created automatically." msgstr "" -#: ../../library/asyncio-sync.rst:190 +#: ../../library/asyncio-sync.rst:192 msgid "" "The preferred way to use a Condition is an :keyword:`async with` statement::" msgstr "" -#: ../../library/asyncio-sync.rst:212 +#: ../../library/asyncio-sync.rst:195 +msgid "" +"cond = asyncio.Condition()\n" +"\n" +"# ... later\n" +"async with cond:\n" +" await cond.wait()" +msgstr "" + +#: ../../library/asyncio-sync.rst:203 +msgid "" +"cond = asyncio.Condition()\n" +"\n" +"# ... later\n" +"await cond.acquire()\n" +"try:\n" +" await cond.wait()\n" +"finally:\n" +" cond.release()" +msgstr "" + +#: ../../library/asyncio-sync.rst:215 msgid "Acquire the underlying lock." msgstr "" -#: ../../library/asyncio-sync.rst:214 +#: ../../library/asyncio-sync.rst:217 msgid "" "This method waits until the underlying lock is *unlocked*, sets it to " "*locked* and returns ``True``." msgstr "" -#: ../../library/asyncio-sync.rst:219 +#: ../../library/asyncio-sync.rst:222 msgid "" "Wake up *n* tasks (1 by default) waiting on this condition. If fewer than " "*n* tasks are waiting they are all awakened." msgstr "" -#: ../../library/asyncio-sync.rst:222 ../../library/asyncio-sync.rst:237 +#: ../../library/asyncio-sync.rst:225 ../../library/asyncio-sync.rst:240 msgid "" "The lock must be acquired before this method is called and released shortly " "after. If called with an *unlocked* lock a :exc:`RuntimeError` error is " "raised." msgstr "" -#: ../../library/asyncio-sync.rst:228 +#: ../../library/asyncio-sync.rst:231 msgid "Return ``True`` if the underlying lock is acquired." msgstr "" -#: ../../library/asyncio-sync.rst:232 +#: ../../library/asyncio-sync.rst:235 msgid "Wake up all tasks waiting on this condition." msgstr "" -#: ../../library/asyncio-sync.rst:234 +#: ../../library/asyncio-sync.rst:237 msgid "This method acts like :meth:`notify`, but wakes up all waiting tasks." msgstr "" -#: ../../library/asyncio-sync.rst:243 +#: ../../library/asyncio-sync.rst:246 msgid "Release the underlying lock." msgstr "" -#: ../../library/asyncio-sync.rst:245 +#: ../../library/asyncio-sync.rst:248 msgid "When invoked on an unlocked lock, a :exc:`RuntimeError` is raised." msgstr "" -#: ../../library/asyncio-sync.rst:250 +#: ../../library/asyncio-sync.rst:254 msgid "Wait until notified." msgstr "" -#: ../../library/asyncio-sync.rst:252 +#: ../../library/asyncio-sync.rst:256 msgid "" "If the calling task has not acquired the lock when this method is called, a :" "exc:`RuntimeError` is raised." msgstr "" -#: ../../library/asyncio-sync.rst:255 +#: ../../library/asyncio-sync.rst:259 msgid "" "This method releases the underlying lock, and then blocks until it is " "awakened by a :meth:`notify` or :meth:`notify_all` call. Once awakened, the " "Condition re-acquires its lock and this method returns ``True``." msgstr "" -#: ../../library/asyncio-sync.rst:260 +#: ../../library/asyncio-sync.rst:264 msgid "" "Note that a task *may* return from this call spuriously, which is why the " -"caller should always re-check the state and be prepared to :meth:`wait` " -"again. For this reason, you may prefer to use :meth:`wait_for` instead." +"caller should always re-check the state and be prepared to :meth:`~Condition." +"wait` again. For this reason, you may prefer to use :meth:`~Condition." +"wait_for` instead." msgstr "" -#: ../../library/asyncio-sync.rst:267 +#: ../../library/asyncio-sync.rst:272 msgid "Wait until a predicate becomes *true*." msgstr "" -#: ../../library/asyncio-sync.rst:269 +#: ../../library/asyncio-sync.rst:274 msgid "" "The predicate must be a callable which result will be interpreted as a " -"boolean value. The method will repeatedly :meth:`wait` until the predicate " -"evaluates to *true*. The final value is the return value." +"boolean value. The method will repeatedly :meth:`~Condition.wait` until the " +"predicate evaluates to *true*. The final value is the return value." msgstr "" -#: ../../library/asyncio-sync.rst:276 +#: ../../library/asyncio-sync.rst:281 msgid "Semaphore" msgstr "" -#: ../../library/asyncio-sync.rst:280 +#: ../../library/asyncio-sync.rst:285 msgid "A Semaphore object. Not thread-safe." msgstr "" -#: ../../library/asyncio-sync.rst:282 +#: ../../library/asyncio-sync.rst:287 msgid "" "A semaphore manages an internal counter which is decremented by each :meth:" "`acquire` call and incremented by each :meth:`release` call. The counter can " @@ -336,69 +398,90 @@ msgid "" "waiting until some task calls :meth:`release`." msgstr "" -#: ../../library/asyncio-sync.rst:288 +#: ../../library/asyncio-sync.rst:293 msgid "" "The optional *value* argument gives the initial value for the internal " "counter (``1`` by default). If the given value is less than ``0`` a :exc:" "`ValueError` is raised." msgstr "" -#: ../../library/asyncio-sync.rst:295 +#: ../../library/asyncio-sync.rst:300 msgid "" "The preferred way to use a Semaphore is an :keyword:`async with` statement::" msgstr "" -#: ../../library/asyncio-sync.rst:317 +#: ../../library/asyncio-sync.rst:303 +msgid "" +"sem = asyncio.Semaphore(10)\n" +"\n" +"# ... later\n" +"async with sem:\n" +" # work with shared resource" +msgstr "" + +#: ../../library/asyncio-sync.rst:311 +msgid "" +"sem = asyncio.Semaphore(10)\n" +"\n" +"# ... later\n" +"await sem.acquire()\n" +"try:\n" +" # work with shared resource\n" +"finally:\n" +" sem.release()" +msgstr "" + +#: ../../library/asyncio-sync.rst:323 msgid "Acquire a semaphore." msgstr "" -#: ../../library/asyncio-sync.rst:319 +#: ../../library/asyncio-sync.rst:325 msgid "" "If the internal counter is greater than zero, decrement it by one and return " "``True`` immediately. If it is zero, wait until a :meth:`release` is called " "and return ``True``." msgstr "" -#: ../../library/asyncio-sync.rst:325 +#: ../../library/asyncio-sync.rst:331 msgid "Returns ``True`` if semaphore can not be acquired immediately." msgstr "" -#: ../../library/asyncio-sync.rst:329 +#: ../../library/asyncio-sync.rst:335 msgid "" "Release a semaphore, incrementing the internal counter by one. Can wake up a " "task waiting to acquire the semaphore." msgstr "" -#: ../../library/asyncio-sync.rst:332 +#: ../../library/asyncio-sync.rst:338 msgid "" "Unlike :class:`BoundedSemaphore`, :class:`Semaphore` allows making more " "``release()`` calls than ``acquire()`` calls." msgstr "" -#: ../../library/asyncio-sync.rst:337 +#: ../../library/asyncio-sync.rst:343 msgid "BoundedSemaphore" msgstr "BoundedSemaphore" -#: ../../library/asyncio-sync.rst:341 +#: ../../library/asyncio-sync.rst:347 msgid "A bounded semaphore object. Not thread-safe." msgstr "" -#: ../../library/asyncio-sync.rst:343 +#: ../../library/asyncio-sync.rst:349 msgid "" "Bounded Semaphore is a version of :class:`Semaphore` that raises a :exc:" "`ValueError` in :meth:`~Semaphore.release` if it increases the internal " "counter above the initial *value*." msgstr "" -#: ../../library/asyncio-sync.rst:352 +#: ../../library/asyncio-sync.rst:358 msgid "Barrier" msgstr "" -#: ../../library/asyncio-sync.rst:356 +#: ../../library/asyncio-sync.rst:362 msgid "A barrier object. Not thread-safe." msgstr "" -#: ../../library/asyncio-sync.rst:358 +#: ../../library/asyncio-sync.rst:364 msgid "" "A barrier is a simple synchronization primitive that allows to block until " "*parties* number of tasks are waiting on it. Tasks can wait on the :meth:" @@ -407,85 +490,127 @@ msgid "" "waiting tasks would unblock simultaneously." msgstr "" -#: ../../library/asyncio-sync.rst:364 +#: ../../library/asyncio-sync.rst:370 msgid "" ":keyword:`async with` can be used as an alternative to awaiting on :meth:" "`~Barrier.wait`." msgstr "" -#: ../../library/asyncio-sync.rst:367 +#: ../../library/asyncio-sync.rst:373 msgid "The barrier can be reused any number of times." msgstr "" -#: ../../library/asyncio-sync.rst:394 +#: ../../library/asyncio-sync.rst:379 +msgid "" +"async def example_barrier():\n" +" # barrier with 3 parties\n" +" b = asyncio.Barrier(3)\n" +"\n" +" # create 2 new waiting tasks\n" +" asyncio.create_task(b.wait())\n" +" asyncio.create_task(b.wait())\n" +"\n" +" await asyncio.sleep(0)\n" +" print(b)\n" +"\n" +" # The third .wait() call passes the barrier\n" +" await b.wait()\n" +" print(b)\n" +" print(\"barrier passed\")\n" +"\n" +" await asyncio.sleep(0)\n" +" print(b)\n" +"\n" +"asyncio.run(example_barrier())" +msgstr "" + +#: ../../library/asyncio-sync.rst:400 msgid "Result of this example is::" msgstr "" -#: ../../library/asyncio-sync.rst:405 +#: ../../library/asyncio-sync.rst:402 +msgid "" +"\n" +"\n" +"barrier passed\n" +"" +msgstr "" + +#: ../../library/asyncio-sync.rst:412 msgid "" "Pass the barrier. When all the tasks party to the barrier have called this " "function, they are all unblocked simultaneously." msgstr "" -#: ../../library/asyncio-sync.rst:408 +#: ../../library/asyncio-sync.rst:415 msgid "" "When a waiting or blocked task in the barrier is cancelled, this task exits " "the barrier which stays in the same state. If the state of the barrier is " "\"filling\", the number of waiting task decreases by 1." msgstr "" -#: ../../library/asyncio-sync.rst:413 +#: ../../library/asyncio-sync.rst:420 msgid "" "The return value is an integer in the range of 0 to ``parties-1``, different " "for each task. This can be used to select a task to do some special " "housekeeping, e.g.::" msgstr "" -#: ../../library/asyncio-sync.rst:423 +#: ../../library/asyncio-sync.rst:424 +msgid "" +"...\n" +"async with barrier as position:\n" +" if position == 0:\n" +" # Only one task prints this\n" +" print('End of *draining phase*')" +msgstr "" + +#: ../../library/asyncio-sync.rst:430 msgid "" "This method may raise a :class:`BrokenBarrierError` exception if the barrier " "is broken or reset while a task is waiting. It could raise a :exc:" "`CancelledError` if a task is cancelled." msgstr "" -#: ../../library/asyncio-sync.rst:429 +#: ../../library/asyncio-sync.rst:437 msgid "" "Return the barrier to the default, empty state. Any tasks waiting on it " "will receive the :class:`BrokenBarrierError` exception." msgstr "" -#: ../../library/asyncio-sync.rst:432 +#: ../../library/asyncio-sync.rst:440 msgid "" "If a barrier is broken it may be better to just leave it and create a new " "one." msgstr "" -#: ../../library/asyncio-sync.rst:436 +#: ../../library/asyncio-sync.rst:445 msgid "" "Put the barrier into a broken state. This causes any active or future calls " -"to :meth:`wait` to fail with the :class:`BrokenBarrierError`. Use this for " -"example if one of the tasks needs to abort, to avoid infinite waiting tasks." +"to :meth:`~Barrier.wait` to fail with the :class:`BrokenBarrierError`. Use " +"this for example if one of the tasks needs to abort, to avoid infinite " +"waiting tasks." msgstr "" -#: ../../library/asyncio-sync.rst:443 +#: ../../library/asyncio-sync.rst:452 msgid "The number of tasks required to pass the barrier." msgstr "" -#: ../../library/asyncio-sync.rst:447 +#: ../../library/asyncio-sync.rst:456 msgid "The number of tasks currently waiting in the barrier while filling." msgstr "" -#: ../../library/asyncio-sync.rst:451 +#: ../../library/asyncio-sync.rst:460 msgid "A boolean that is ``True`` if the barrier is in the broken state." msgstr "" -#: ../../library/asyncio-sync.rst:456 +#: ../../library/asyncio-sync.rst:465 msgid "" "This exception, a subclass of :exc:`RuntimeError`, is raised when the :class:" "`Barrier` object is reset or broken." msgstr "" -#: ../../library/asyncio-sync.rst:464 +#: ../../library/asyncio-sync.rst:473 msgid "" "Acquiring a lock using ``await lock`` or ``yield from lock`` and/or :keyword:" "`with` statement (``with await lock``, ``with (yield from lock)``) was " diff --git a/library/asyncio-task.po b/library/asyncio-task.po index 4282a584e..27a2cd011 100644 --- a/library/asyncio-task.po +++ b/library/asyncio-task.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Italo Penaforte , 2021 -# Danilo Lima , 2021 -# Adorilson Bezerra , 2022 -# Vinicius Gubiani Ferreira , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-26 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:55+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-04-18 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -60,6 +54,20 @@ msgstr "" "trecho de código imprime \"hello\", espera 1 segundo, e então imprime " "\"world\"::" +#: ../../library/asyncio-task.rst:30 +msgid "" +">>> import asyncio\n" +"\n" +">>> async def main():\n" +"... print('hello')\n" +"... await asyncio.sleep(1)\n" +"... print('world')\n" +"\n" +">>> asyncio.run(main())\n" +"hello\n" +"world" +msgstr "" + #: ../../library/asyncio-task.rst:41 msgid "" "Note that simply calling a coroutine will not schedule it to be executed::" @@ -67,6 +75,12 @@ msgstr "" "Perceba que simplesmente chamar uma corrotina não irá agendá-la para ser " "executada::" +#: ../../library/asyncio-task.rst:44 +msgid "" +">>> main()\n" +"" +msgstr "" + #: ../../library/asyncio-task.rst:47 msgid "To actually run a coroutine, asyncio provides the following mechanisms:" msgstr "" @@ -89,10 +103,38 @@ msgstr "" "esperar por 1 segundo e, em seguida, exibirá \"world\" após esperar por " "*outros* 2 segundos::" +#: ../../library/asyncio-task.rst:56 +msgid "" +"import asyncio\n" +"import time\n" +"\n" +"async def say_after(delay, what):\n" +" await asyncio.sleep(delay)\n" +" print(what)\n" +"\n" +"async def main():\n" +" print(f\"started at {time.strftime('%X')}\")\n" +"\n" +" await say_after(1, 'hello')\n" +" await say_after(2, 'world')\n" +"\n" +" print(f\"finished at {time.strftime('%X')}\")\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: ../../library/asyncio-task.rst:73 msgid "Expected output::" msgstr "Resultado esperado::" +#: ../../library/asyncio-task.rst:75 +msgid "" +"started at 17:13:52\n" +"hello\n" +"world\n" +"finished at 17:13:55" +msgstr "" + #: ../../library/asyncio-task.rst:80 msgid "" "The :func:`asyncio.create_task` function to run coroutines concurrently as " @@ -109,6 +151,25 @@ msgstr "" "Vamos modificar o exemplo acima e executar duas corrotinas ``say_after`` " "*concorrentemente*::" +#: ../../library/asyncio-task.rst:86 +msgid "" +"async def main():\n" +" task1 = asyncio.create_task(\n" +" say_after(1, 'hello'))\n" +"\n" +" task2 = asyncio.create_task(\n" +" say_after(2, 'world'))\n" +"\n" +" print(f\"started at {time.strftime('%X')}\")\n" +"\n" +" # Wait until both tasks are completed (should take\n" +" # around 2 seconds.)\n" +" await task1\n" +" await task2\n" +"\n" +" print(f\"finished at {time.strftime('%X')}\")" +msgstr "" + #: ../../library/asyncio-task.rst:102 msgid "" "Note that expected output now shows that the snippet runs 1 second faster " @@ -117,12 +178,37 @@ msgstr "" "Perceba que a saída esperada agora mostra que o trecho de código é executado " "1 segundo mais rápido do que antes::" +#: ../../library/asyncio-task.rst:105 +msgid "" +"started at 17:14:32\n" +"hello\n" +"world\n" +"finished at 17:14:34" +msgstr "" + #: ../../library/asyncio-task.rst:110 msgid "" "The :class:`asyncio.TaskGroup` class provides a more modern alternative to :" "func:`create_task`. Using this API, the last example becomes::" msgstr "" +#: ../../library/asyncio-task.rst:114 +msgid "" +"async def main():\n" +" async with asyncio.TaskGroup() as tg:\n" +" task1 = tg.create_task(\n" +" say_after(1, 'hello'))\n" +"\n" +" task2 = tg.create_task(\n" +" say_after(2, 'world'))\n" +"\n" +" print(f\"started at {time.strftime('%X')}\")\n" +"\n" +" # The await is implicit when the context manager exits.\n" +"\n" +" print(f\"finished at {time.strftime('%X')}\")" +msgstr "" + #: ../../library/asyncio-task.rst:128 msgid "The timing and output should be the same as for the previous version." msgstr "" @@ -161,6 +247,25 @@ msgstr "" "Corrotinas Python são *aguardáveis* e portanto podem ser aguardadas a partir " "de outras corrotinas::" +#: ../../library/asyncio-task.rst:152 +msgid "" +"import asyncio\n" +"\n" +"async def nested():\n" +" return 42\n" +"\n" +"async def main():\n" +" # Nothing happens if we just call \"nested()\".\n" +" # A coroutine object is created but not awaited,\n" +" # so it *won't run at all*.\n" +" nested() # will raise a \"RuntimeWarning\".\n" +"\n" +" # Let's do it differently now and await it:\n" +" print(await nested()) # will print \"42\".\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: ../../library/asyncio-task.rst:170 msgid "" "In this documentation the term \"coroutine\" can be used for two closely " @@ -197,6 +302,25 @@ msgstr "" "`asyncio.create_task`, a corrotina é automaticamente agendada para executar " "em breve::" +#: ../../library/asyncio-task.rst:187 +msgid "" +"import asyncio\n" +"\n" +"async def nested():\n" +" return 42\n" +"\n" +"async def main():\n" +" # Schedule nested() to run soon concurrently\n" +" # with \"main()\".\n" +" task = asyncio.create_task(nested())\n" +"\n" +" # \"task\" can now be used to cancel \"nested()\", or\n" +" # can simply be awaited to wait until it is complete:\n" +" await task\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: ../../library/asyncio-task.rst:205 msgid "Futures" msgstr "Futuros" @@ -241,6 +365,18 @@ msgstr "" "Objetos Future, algumas vezes expostos por bibliotecas e algumas APIs " "asyncio, podem ser aguardados::" +#: ../../library/asyncio-task.rst:221 +msgid "" +"async def main():\n" +" await function_that_returns_a_future_object()\n" +"\n" +" # this is also valid:\n" +" await asyncio.gather(\n" +" function_that_returns_a_future_object(),\n" +" some_python_coroutine()\n" +" )" +msgstr "" + #: ../../library/asyncio-task.rst:230 msgid "" "A good example of a low-level function that returns a Future object is :meth:" @@ -310,11 +446,27 @@ msgstr "" "mesmo da função ser finalizada. Para tarefas de segundo plano \"atire-e-" "esqueça\", junte-as em uma coleção::" -#: ../../library/asyncio-task.rst:287 ../../library/asyncio-task.rst:1141 +#: ../../library/asyncio-task.rst:272 +msgid "" +"background_tasks = set()\n" +"\n" +"for i in range(10):\n" +" task = asyncio.create_task(some_coro(param=i))\n" +"\n" +" # Add task to the set. This creates a strong reference.\n" +" background_tasks.add(task)\n" +"\n" +" # To prevent keeping references to finished tasks forever,\n" +" # make each task remove its own reference from the set after\n" +" # completion:\n" +" task.add_done_callback(background_tasks.discard)" +msgstr "" + +#: ../../library/asyncio-task.rst:287 ../../library/asyncio-task.rst:1192 msgid "Added the *name* parameter." msgstr "Adicionado o parâmetro *name*." -#: ../../library/asyncio-task.rst:290 ../../library/asyncio-task.rst:1148 +#: ../../library/asyncio-task.rst:290 ../../library/asyncio-task.rst:1199 msgid "Added the *context* parameter." msgstr "Adicionado o parâmetro *context*." @@ -377,12 +529,22 @@ msgstr "" msgid "Close the given coroutine if the task group is not active." msgstr "" -#: ../../library/asyncio-task.rst:345 ../../library/asyncio-task.rst:503 -#: ../../library/asyncio-task.rst:676 ../../library/asyncio-task.rst:734 -#: ../../library/asyncio-task.rst:760 ../../library/asyncio-task.rst:800 +#: ../../library/asyncio-task.rst:345 ../../library/asyncio-task.rst:551 +#: ../../library/asyncio-task.rst:724 ../../library/asyncio-task.rst:782 +#: ../../library/asyncio-task.rst:808 ../../library/asyncio-task.rst:849 msgid "Example::" msgstr "Exemplo::" +#: ../../library/asyncio-task.rst:347 +msgid "" +"async def main():\n" +" async with asyncio.TaskGroup() as tg:\n" +" task1 = tg.create_task(some_coro(...))\n" +" task2 = tg.create_task(another_coro(...))\n" +" print(f\"Both tasks have completed now: {task1.result()}, {task2." +"result()}\")" +msgstr "" + #: ../../library/asyncio-task.rst:353 msgid "" "The ``async with`` statement will wait for all tasks in the group to finish. " @@ -465,14 +627,69 @@ msgid "" msgstr "" #: ../../library/asyncio-task.rst:418 +msgid "Terminating a Task Group" +msgstr "" + +#: ../../library/asyncio-task.rst:420 +msgid "" +"While terminating a task group is not natively supported by the standard " +"library, termination can be achieved by adding an exception-raising task to " +"the task group and ignoring the raised exception:" +msgstr "" + +#: ../../library/asyncio-task.rst:424 +msgid "" +"import asyncio\n" +"from asyncio import TaskGroup\n" +"\n" +"class TerminateTaskGroup(Exception):\n" +" \"\"\"Exception raised to terminate a task group.\"\"\"\n" +"\n" +"async def force_terminate_task_group():\n" +" \"\"\"Used to force termination of a task group.\"\"\"\n" +" raise TerminateTaskGroup()\n" +"\n" +"async def job(task_id, sleep_time):\n" +" print(f'Task {task_id}: start')\n" +" await asyncio.sleep(sleep_time)\n" +" print(f'Task {task_id}: done')\n" +"\n" +"async def main():\n" +" try:\n" +" async with TaskGroup() as group:\n" +" # spawn some tasks\n" +" group.create_task(job(1, 0.5))\n" +" group.create_task(job(2, 1.5))\n" +" # sleep for 1 second\n" +" await asyncio.sleep(1)\n" +" # add an exception-raising task to force the group to terminate\n" +" group.create_task(force_terminate_task_group())\n" +" except* TerminateTaskGroup:\n" +" pass\n" +"\n" +"asyncio.run(main())" +msgstr "" + +#: ../../library/asyncio-task.rst:456 +msgid "Expected output:" +msgstr "" + +#: ../../library/asyncio-task.rst:458 +msgid "" +"Task 1: start\n" +"Task 2: start\n" +"Task 1: done" +msgstr "" + +#: ../../library/asyncio-task.rst:465 msgid "Sleeping" msgstr "Dormindo" -#: ../../library/asyncio-task.rst:422 +#: ../../library/asyncio-task.rst:470 msgid "Block for *delay* seconds." msgstr "Bloqueia por *delay* segundos." -#: ../../library/asyncio-task.rst:424 +#: ../../library/asyncio-task.rst:472 msgid "" "If *result* is provided, it is returned to the caller when the coroutine " "completes." @@ -480,14 +697,14 @@ msgstr "" "Se *result* é fornecido, é retornado para o autor da chamada quando a " "corrotina termina." -#: ../../library/asyncio-task.rst:427 +#: ../../library/asyncio-task.rst:475 msgid "" "``sleep()`` always suspends the current task, allowing other tasks to run." msgstr "" "``sleep()`` sempre suspende a tarefa atual, permitindo que outras tarefas " "sejam executadas." -#: ../../library/asyncio-task.rst:430 +#: ../../library/asyncio-task.rst:478 msgid "" "Setting the delay to 0 provides an optimized path to allow other tasks to " "run. This can be used by long-running functions to avoid blocking the event " @@ -498,28 +715,45 @@ msgstr "" "para evitar que bloqueiem o laço de eventos por toda a duração da chamada da " "função." -#: ../../library/asyncio-task.rst:436 +#: ../../library/asyncio-task.rst:484 msgid "" "Example of coroutine displaying the current date every second for 5 seconds::" msgstr "" "Exemplo de uma corrotina exibindo a data atual a cada segundo durante 5 " "segundos::" -#: ../../library/asyncio-task.rst:454 ../../library/asyncio-task.rst:552 -#: ../../library/asyncio-task.rst:651 ../../library/asyncio-task.rst:825 -#: ../../library/asyncio-task.rst:879 ../../library/asyncio-task.rst:936 +#: ../../library/asyncio-task.rst:487 +msgid "" +"import asyncio\n" +"import datetime\n" +"\n" +"async def display_date():\n" +" loop = asyncio.get_running_loop()\n" +" end_time = loop.time() + 5.0\n" +" while True:\n" +" print(datetime.datetime.now())\n" +" if (loop.time() + 1.0) >= end_time:\n" +" break\n" +" await asyncio.sleep(1)\n" +"\n" +"asyncio.run(display_date())" +msgstr "" + +#: ../../library/asyncio-task.rst:502 ../../library/asyncio-task.rst:600 +#: ../../library/asyncio-task.rst:699 ../../library/asyncio-task.rst:874 +#: ../../library/asyncio-task.rst:929 ../../library/asyncio-task.rst:986 msgid "Removed the *loop* parameter." msgstr "Removido o parâmetro *loop*." -#: ../../library/asyncio-task.rst:457 +#: ../../library/asyncio-task.rst:505 msgid "Raises :exc:`ValueError` if *delay* is :data:`~math.nan`." msgstr "" -#: ../../library/asyncio-task.rst:462 +#: ../../library/asyncio-task.rst:510 msgid "Running Tasks Concurrently" msgstr "Executando tarefas concorrentemente" -#: ../../library/asyncio-task.rst:466 +#: ../../library/asyncio-task.rst:514 msgid "" "Run :ref:`awaitable objects ` in the *aws* sequence " "*concurrently*." @@ -527,7 +761,7 @@ msgstr "" "Executa :ref:`objetos aguardáveis ` na sequência *aws* " "de forma *concorrente*." -#: ../../library/asyncio-task.rst:469 +#: ../../library/asyncio-task.rst:517 msgid "" "If any awaitable in *aws* is a coroutine, it is automatically scheduled as a " "Task." @@ -535,7 +769,7 @@ msgstr "" "Se qualquer aguardável em *aws* é uma corrotina, ele é automaticamente " "agendado como uma Tarefa." -#: ../../library/asyncio-task.rst:472 +#: ../../library/asyncio-task.rst:520 msgid "" "If all awaitables are completed successfully, the result is an aggregate " "list of returned values. The order of result values corresponds to the " @@ -545,7 +779,7 @@ msgstr "" "lista agregada de valores retornados. A ordem dos valores resultantes " "corresponde a ordem dos aguardáveis em *aws*." -#: ../../library/asyncio-task.rst:476 +#: ../../library/asyncio-task.rst:524 msgid "" "If *return_exceptions* is ``False`` (default), the first raised exception is " "immediately propagated to the task that awaits on ``gather()``. Other " @@ -557,7 +791,7 @@ msgstr "" "``gather()``. Outros aguardáveis na sequência *aws* **não serão cancelados** " "e irão continuar a executar." -#: ../../library/asyncio-task.rst:481 +#: ../../library/asyncio-task.rst:529 msgid "" "If *return_exceptions* is ``True``, exceptions are treated the same as " "successful results, and aggregated in the result list." @@ -565,7 +799,7 @@ msgstr "" "Se *return_exceptions* for ``True``, exceções são tratadas da mesma forma " "que resultados com sucesso, e agregadas na lista de resultados." -#: ../../library/asyncio-task.rst:484 +#: ../../library/asyncio-task.rst:532 msgid "" "If ``gather()`` is *cancelled*, all submitted awaitables (that have not " "completed yet) are also *cancelled*." @@ -573,7 +807,7 @@ msgstr "" "Se ``gather()`` for *cancelado*, todos os aguardáveis que foram submetidos " "(que não foram concluídos ainda) também são *cancelados*." -#: ../../library/asyncio-task.rst:487 +#: ../../library/asyncio-task.rst:535 msgid "" "If any Task or Future from the *aws* sequence is *cancelled*, it is treated " "as if it raised :exc:`CancelledError` -- the ``gather()`` call is **not** " @@ -586,7 +820,7 @@ msgstr "" "cancelamento de uma Tarefa/Futuro submetida ocasione outras Tarefas/Futuros " "a serem cancelados." -#: ../../library/asyncio-task.rst:494 +#: ../../library/asyncio-task.rst:542 msgid "" "A new alternative to create and run tasks concurrently and wait for their " "completion is :class:`asyncio.TaskGroup`. *TaskGroup* provides stronger " @@ -596,7 +830,46 @@ msgid "" "tasks)." msgstr "" -#: ../../library/asyncio-task.rst:541 +#: ../../library/asyncio-task.rst:553 +msgid "" +"import asyncio\n" +"\n" +"async def factorial(name, number):\n" +" f = 1\n" +" for i in range(2, number + 1):\n" +" print(f\"Task {name}: Compute factorial({number}), currently i={i}..." +"\")\n" +" await asyncio.sleep(1)\n" +" f *= i\n" +" print(f\"Task {name}: factorial({number}) = {f}\")\n" +" return f\n" +"\n" +"async def main():\n" +" # Schedule three calls *concurrently*:\n" +" L = await asyncio.gather(\n" +" factorial(\"A\", 2),\n" +" factorial(\"B\", 3),\n" +" factorial(\"C\", 4),\n" +" )\n" +" print(L)\n" +"\n" +"asyncio.run(main())\n" +"\n" +"# Expected output:\n" +"#\n" +"# Task A: Compute factorial(2), currently i=2...\n" +"# Task B: Compute factorial(3), currently i=2...\n" +"# Task C: Compute factorial(4), currently i=2...\n" +"# Task A: factorial(2) = 2\n" +"# Task B: Compute factorial(3), currently i=3...\n" +"# Task C: Compute factorial(4), currently i=3...\n" +"# Task B: factorial(3) = 6\n" +"# Task C: Compute factorial(4), currently i=4...\n" +"# Task C: factorial(4) = 24\n" +"# [2, 6, 24]" +msgstr "" + +#: ../../library/asyncio-task.rst:589 msgid "" "If *return_exceptions* is false, cancelling gather() after it has been " "marked done won't cancel any submitted awaitables. For instance, gather can " @@ -605,7 +878,7 @@ msgid "" "the awaitables) from gather won't cancel any other awaitables." msgstr "" -#: ../../library/asyncio-task.rst:548 +#: ../../library/asyncio-task.rst:596 msgid "" "If the *gather* itself is cancelled, the cancellation is propagated " "regardless of *return_exceptions*." @@ -613,7 +886,7 @@ msgstr "" "Se *gather* por si mesmo for cancelado, o cancelamento é propagado " "independente de *return_exceptions*." -#: ../../library/asyncio-task.rst:555 +#: ../../library/asyncio-task.rst:603 msgid "" "Deprecation warning is emitted if no positional arguments are provided or " "not all positional arguments are Future-like objects and there is no running " @@ -623,15 +896,15 @@ msgstr "" "fornecido, ou nem todos os argumentos posicionais são objetos similar a " "Futuro, e não existe nenhum laço de eventos em execução." -#: ../../library/asyncio-task.rst:564 +#: ../../library/asyncio-task.rst:612 msgid "Eager Task Factory" msgstr "" -#: ../../library/asyncio-task.rst:568 +#: ../../library/asyncio-task.rst:616 msgid "A task factory for eager task execution." msgstr "" -#: ../../library/asyncio-task.rst:570 +#: ../../library/asyncio-task.rst:618 msgid "" "When using this factory (via :meth:`loop.set_task_factory(asyncio." "eager_task_factory) `), coroutines begin execution " @@ -641,13 +914,13 @@ msgid "" "synchronously." msgstr "" -#: ../../library/asyncio-task.rst:576 +#: ../../library/asyncio-task.rst:624 msgid "" "A common example where this is beneficial is coroutines which employ caching " "or memoization to avoid actual I/O when possible." msgstr "" -#: ../../library/asyncio-task.rst:581 +#: ../../library/asyncio-task.rst:629 msgid "" "Immediate execution of the coroutine is a semantic change. If the coroutine " "returns or raises, the task is never scheduled to the event loop. If the " @@ -656,32 +929,32 @@ msgid "" "the application's task execution order is likely to change." msgstr "" -#: ../../library/asyncio-task.rst:592 +#: ../../library/asyncio-task.rst:640 msgid "" "Create an eager task factory, similar to :func:`eager_task_factory`, using " "the provided *custom_task_constructor* when creating a new task instead of " "the default :class:`Task`." msgstr "" -#: ../../library/asyncio-task.rst:596 +#: ../../library/asyncio-task.rst:644 msgid "" "*custom_task_constructor* must be a *callable* with the signature matching " "the signature of :class:`Task.__init__ `. The callable must return a :" "class:`asyncio.Task`-compatible object." msgstr "" -#: ../../library/asyncio-task.rst:600 +#: ../../library/asyncio-task.rst:648 msgid "" "This function returns a *callable* intended to be used as a task factory of " "an event loop via :meth:`loop.set_task_factory(factory) `)." msgstr "" -#: ../../library/asyncio-task.rst:607 +#: ../../library/asyncio-task.rst:655 msgid "Shielding From Cancellation" msgstr "Protegendo contra cancelamento" -#: ../../library/asyncio-task.rst:611 +#: ../../library/asyncio-task.rst:659 msgid "" "Protect an :ref:`awaitable object ` from being :meth:" "`cancelled `." @@ -689,20 +962,30 @@ msgstr "" "Protege um :ref:`objeto aguardável ` de ser :meth:" "`cancelado `." -#: ../../library/asyncio-task.rst:614 ../../library/asyncio-task.rst:780 +#: ../../library/asyncio-task.rst:662 ../../library/asyncio-task.rst:829 msgid "If *aw* is a coroutine it is automatically scheduled as a Task." msgstr "" "Se *aw* é uma corrotina, ela é automaticamente agendada como uma Tarefa." -#: ../../library/asyncio-task.rst:616 +#: ../../library/asyncio-task.rst:664 msgid "The statement::" msgstr "A instrução::" -#: ../../library/asyncio-task.rst:621 +#: ../../library/asyncio-task.rst:666 +msgid "" +"task = asyncio.create_task(something())\n" +"res = await shield(task)" +msgstr "" + +#: ../../library/asyncio-task.rst:669 msgid "is equivalent to::" msgstr "é equivalente a::" -#: ../../library/asyncio-task.rst:625 +#: ../../library/asyncio-task.rst:671 +msgid "res = await something()" +msgstr "" + +#: ../../library/asyncio-task.rst:673 msgid "" "*except* that if the coroutine containing it is cancelled, the Task running " "in ``something()`` is not cancelled. From the point of view of " @@ -716,7 +999,7 @@ msgstr "" "cancelado, então a expressão \"await\" ainda levanta um :exc:" "`CancelledError`." -#: ../../library/asyncio-task.rst:631 +#: ../../library/asyncio-task.rst:679 msgid "" "If ``something()`` is cancelled by other means (i.e. from within itself) " "that would also cancel ``shield()``." @@ -724,7 +1007,7 @@ msgstr "" "Se ``something()`` é cancelada por outros meios (isto é, dentro ou a partir " "de si mesma) isso também iria cancelar ``shield()``." -#: ../../library/asyncio-task.rst:634 +#: ../../library/asyncio-task.rst:682 msgid "" "If it is desired to completely ignore cancellation (not recommended) the " "``shield()`` function should be combined with a try/except clause, as " @@ -734,7 +1017,16 @@ msgstr "" "função ``shield()`` deve ser combinada com uma cláusula try/except, conforme " "abaixo::" -#: ../../library/asyncio-task.rst:646 +#: ../../library/asyncio-task.rst:686 +msgid "" +"task = asyncio.create_task(something())\n" +"try:\n" +" res = await shield(task)\n" +"except CancelledError:\n" +" res = None" +msgstr "" + +#: ../../library/asyncio-task.rst:694 msgid "" "Save a reference to tasks passed to this function, to avoid a task " "disappearing mid-execution. The event loop only keeps weak references to " @@ -747,7 +1039,7 @@ msgstr "" "é referenciada por nada mais pode ser removida pelo coletor de lixo a " "qualquer momento, antes mesmo da função ser finalizada." -#: ../../library/asyncio-task.rst:654 +#: ../../library/asyncio-task.rst:702 msgid "" "Deprecation warning is emitted if *aw* is not Future-like object and there " "is no running event loop." @@ -755,30 +1047,37 @@ msgstr "" "Aviso de descontinuidade é emitido se *aw* não é um objeto similar a Futuro, " "e não existe nenhum laço de eventos em execução." -#: ../../library/asyncio-task.rst:660 +#: ../../library/asyncio-task.rst:708 msgid "Timeouts" msgstr "Tempo limite" -#: ../../library/asyncio-task.rst:664 +#: ../../library/asyncio-task.rst:712 msgid "" "Return an :ref:`asynchronous context manager ` that " "can be used to limit the amount of time spent waiting on something." msgstr "" -#: ../../library/asyncio-task.rst:668 +#: ../../library/asyncio-task.rst:716 msgid "" "*delay* can either be ``None``, or a float/int number of seconds to wait. If " "*delay* is ``None``, no time limit will be applied; this can be useful if " "the delay is unknown when the context manager is created." msgstr "" -#: ../../library/asyncio-task.rst:673 +#: ../../library/asyncio-task.rst:721 msgid "" "In either case, the context manager can be rescheduled after creation using :" "meth:`Timeout.reschedule`." msgstr "" -#: ../../library/asyncio-task.rst:682 +#: ../../library/asyncio-task.rst:726 +msgid "" +"async def main():\n" +" async with asyncio.timeout(10):\n" +" await long_running_task()" +msgstr "" + +#: ../../library/asyncio-task.rst:730 msgid "" "If ``long_running_task`` takes more than 10 seconds to complete, the context " "manager will cancel the current task and handle the resulting :exc:`asyncio." @@ -786,69 +1085,113 @@ msgid "" "can be caught and handled." msgstr "" -#: ../../library/asyncio-task.rst:689 +#: ../../library/asyncio-task.rst:737 msgid "" "The :func:`asyncio.timeout` context manager is what transforms the :exc:" "`asyncio.CancelledError` into a :exc:`TimeoutError`, which means the :exc:" "`TimeoutError` can only be caught *outside* of the context manager." msgstr "" -#: ../../library/asyncio-task.rst:694 +#: ../../library/asyncio-task.rst:742 msgid "Example of catching :exc:`TimeoutError`::" msgstr "" -#: ../../library/asyncio-task.rst:705 +#: ../../library/asyncio-task.rst:744 +msgid "" +"async def main():\n" +" try:\n" +" async with asyncio.timeout(10):\n" +" await long_running_task()\n" +" except TimeoutError:\n" +" print(\"The long operation timed out, but we've handled it.\")\n" +"\n" +" print(\"This statement will run regardless.\")" +msgstr "" + +#: ../../library/asyncio-task.rst:753 msgid "" "The context manager produced by :func:`asyncio.timeout` can be rescheduled " "to a different deadline and inspected." msgstr "" -#: ../../library/asyncio-task.rst:710 +#: ../../library/asyncio-task.rst:758 msgid "" "An :ref:`asynchronous context manager ` for " "cancelling overdue coroutines." msgstr "" -#: ../../library/asyncio-task.rst:713 +#: ../../library/asyncio-task.rst:761 msgid "" "``when`` should be an absolute time at which the context should time out, as " "measured by the event loop's clock:" msgstr "" -#: ../../library/asyncio-task.rst:716 +#: ../../library/asyncio-task.rst:764 msgid "If ``when`` is ``None``, the timeout will never trigger." msgstr "" -#: ../../library/asyncio-task.rst:717 +#: ../../library/asyncio-task.rst:765 msgid "" "If ``when < loop.time()``, the timeout will trigger on the next iteration of " "the event loop." msgstr "" -#: ../../library/asyncio-task.rst:722 +#: ../../library/asyncio-task.rst:770 msgid "" "Return the current deadline, or ``None`` if the current deadline is not set." msgstr "" -#: ../../library/asyncio-task.rst:727 +#: ../../library/asyncio-task.rst:775 msgid "Reschedule the timeout." msgstr "" -#: ../../library/asyncio-task.rst:731 +#: ../../library/asyncio-task.rst:779 msgid "Return whether the context manager has exceeded its deadline (expired)." msgstr "" -#: ../../library/asyncio-task.rst:751 +#: ../../library/asyncio-task.rst:784 +msgid "" +"async def main():\n" +" try:\n" +" # We do not know the timeout when starting, so we pass ``None``.\n" +" async with asyncio.timeout(None) as cm:\n" +" # We know the timeout now, so we reschedule it.\n" +" new_deadline = get_running_loop().time() + 10\n" +" cm.reschedule(new_deadline)\n" +"\n" +" await long_running_task()\n" +" except TimeoutError:\n" +" pass\n" +"\n" +" if cm.expired():\n" +" print(\"Looks like we haven't finished on time.\")" +msgstr "" + +#: ../../library/asyncio-task.rst:799 msgid "Timeout context managers can be safely nested." msgstr "" -#: ../../library/asyncio-task.rst:757 +#: ../../library/asyncio-task.rst:805 msgid "" "Similar to :func:`asyncio.timeout`, except *when* is the absolute time to " "stop waiting, or ``None``." msgstr "" -#: ../../library/asyncio-task.rst:777 +#: ../../library/asyncio-task.rst:810 +msgid "" +"async def main():\n" +" loop = get_running_loop()\n" +" deadline = loop.time() + 20\n" +" try:\n" +" async with asyncio.timeout_at(deadline):\n" +" await long_running_task()\n" +" except TimeoutError:\n" +" print(\"The long operation timed out, but we've handled it.\")\n" +"\n" +" print(\"This statement will run regardless.\")" +msgstr "" + +#: ../../library/asyncio-task.rst:826 msgid "" "Wait for the *aw* :ref:`awaitable ` to complete with a " "timeout." @@ -856,7 +1199,7 @@ msgstr "" "Espera o :ref:`aguardável ` *aw* concluir sem " "ultrapassar o tempo limite \"timeout\"." -#: ../../library/asyncio-task.rst:782 +#: ../../library/asyncio-task.rst:831 msgid "" "*timeout* can either be ``None`` or a float or int number of seconds to wait " "for. If *timeout* is ``None``, block until the future completes." @@ -865,12 +1208,12 @@ msgstr "" "segundos para aguardar. Se *timeout* é ``None``, aguarda até o future " "encerrar." -#: ../../library/asyncio-task.rst:786 +#: ../../library/asyncio-task.rst:835 msgid "" "If a timeout occurs, it cancels the task and raises :exc:`TimeoutError`." msgstr "" -#: ../../library/asyncio-task.rst:789 +#: ../../library/asyncio-task.rst:838 msgid "" "To avoid the task :meth:`cancellation `, wrap it in :func:" "`shield`." @@ -878,7 +1221,7 @@ msgstr "" "Para evitar o :meth:`cancelamento ` da tarefa, envolva-a com :" "func:`shield`." -#: ../../library/asyncio-task.rst:792 +#: ../../library/asyncio-task.rst:841 msgid "" "The function will wait until the future is actually cancelled, so the total " "wait time may exceed the *timeout*. If an exception happens during " @@ -888,44 +1231,69 @@ msgstr "" "total de espera pode exceder o tempo limite *timeout*. Se uma exceção " "ocorrer durante o cancelamento, ela será propagada." -#: ../../library/asyncio-task.rst:796 +#: ../../library/asyncio-task.rst:845 msgid "If the wait is cancelled, the future *aw* is also cancelled." msgstr "Se ele for cancelado, o future *aw* também é cancelado." -#: ../../library/asyncio-task.rst:820 +#: ../../library/asyncio-task.rst:851 +msgid "" +"async def eternity():\n" +" # Sleep for one hour\n" +" await asyncio.sleep(3600)\n" +" print('yay!')\n" +"\n" +"async def main():\n" +" # Wait for at most 1 second\n" +" try:\n" +" await asyncio.wait_for(eternity(), timeout=1.0)\n" +" except TimeoutError:\n" +" print('timeout!')\n" +"\n" +"asyncio.run(main())\n" +"\n" +"# Expected output:\n" +"#\n" +"# timeout!" +msgstr "" + +#: ../../library/asyncio-task.rst:869 msgid "" "When *aw* is cancelled due to a timeout, ``wait_for`` waits for *aw* to be " "cancelled. Previously, it raised :exc:`TimeoutError` immediately." msgstr "" -#: ../../library/asyncio-task.rst:828 +#: ../../library/asyncio-task.rst:877 msgid "Raises :exc:`TimeoutError` instead of :exc:`asyncio.TimeoutError`." msgstr "" -#: ../../library/asyncio-task.rst:833 +#: ../../library/asyncio-task.rst:882 msgid "Waiting Primitives" msgstr "Primitivas de Espera" -#: ../../library/asyncio-task.rst:837 +#: ../../library/asyncio-task.rst:887 msgid "" "Run :class:`~asyncio.Future` and :class:`~asyncio.Task` instances in the " "*aws* iterable concurrently and block until the condition specified by " "*return_when*." msgstr "" -#: ../../library/asyncio-task.rst:841 +#: ../../library/asyncio-task.rst:891 msgid "The *aws* iterable must not be empty." msgstr "O iterável *aws* não deve ser vazio." -#: ../../library/asyncio-task.rst:843 +#: ../../library/asyncio-task.rst:893 msgid "Returns two sets of Tasks/Futures: ``(done, pending)``." msgstr "Retorna dois conjuntos de Tarefas/Futuros: ``(done, pending)``." -#: ../../library/asyncio-task.rst:845 +#: ../../library/asyncio-task.rst:895 msgid "Usage::" msgstr "Uso::" -#: ../../library/asyncio-task.rst:849 +#: ../../library/asyncio-task.rst:897 +msgid "done, pending = await asyncio.wait(aws)" +msgstr "" + +#: ../../library/asyncio-task.rst:899 msgid "" "*timeout* (a float or int), if specified, can be used to control the maximum " "number of seconds to wait before returning." @@ -933,14 +1301,14 @@ msgstr "" "*timeout* (um ponto flutuante ou inteiro), se especificado, pode ser usado " "para controlar o número máximo de segundos para aguardar antes de retornar." -#: ../../library/asyncio-task.rst:852 +#: ../../library/asyncio-task.rst:902 msgid "" "Note that this function does not raise :exc:`TimeoutError`. Futures or Tasks " "that aren't done when the timeout occurs are simply returned in the second " "set." msgstr "" -#: ../../library/asyncio-task.rst:856 +#: ../../library/asyncio-task.rst:906 msgid "" "*return_when* indicates when this function should return. It must be one of " "the following constants:" @@ -948,32 +1316,32 @@ msgstr "" "*return_when* indica quando esta função deve retornar. Ele deve ser uma das " "seguintes constantes:" -#: ../../library/asyncio-task.rst:862 +#: ../../library/asyncio-task.rst:912 msgid "Constant" msgstr "Constante" -#: ../../library/asyncio-task.rst:863 +#: ../../library/asyncio-task.rst:913 msgid "Description" msgstr "Descrição" -#: ../../library/asyncio-task.rst:866 +#: ../../library/asyncio-task.rst:916 msgid "The function will return when any future finishes or is cancelled." msgstr "" "A função irá retornar quando qualquer futuro terminar ou for cancelado." -#: ../../library/asyncio-task.rst:869 +#: ../../library/asyncio-task.rst:919 msgid "" "The function will return when any future finishes by raising an exception. " "If no future raises an exception then it is equivalent to :const:" "`ALL_COMPLETED`." msgstr "" -#: ../../library/asyncio-task.rst:874 +#: ../../library/asyncio-task.rst:924 msgid "The function will return when all futures finish or are cancelled." msgstr "" "A função irá retornar quando todos os futuros encerrarem ou forem cancelados." -#: ../../library/asyncio-task.rst:876 +#: ../../library/asyncio-task.rst:926 msgid "" "Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the futures " "when a timeout occurs." @@ -981,22 +1349,22 @@ msgstr "" "Diferente de :func:`~asyncio.wait_for`, ``wait()`` não cancela os futuros " "quando um tempo limite é atingido." -#: ../../library/asyncio-task.rst:882 +#: ../../library/asyncio-task.rst:932 msgid "Passing coroutine objects to ``wait()`` directly is forbidden." msgstr "" -#: ../../library/asyncio-task.rst:885 ../../library/asyncio-task.rst:943 +#: ../../library/asyncio-task.rst:935 ../../library/asyncio-task.rst:993 msgid "Added support for generators yielding tasks." msgstr "" -#: ../../library/asyncio-task.rst:891 +#: ../../library/asyncio-task.rst:941 msgid "" "Run :ref:`awaitable objects ` in the *aws* iterable " "concurrently. The returned object can be iterated to obtain the results of " "the awaitables as they finish." msgstr "" -#: ../../library/asyncio-task.rst:895 +#: ../../library/asyncio-task.rst:945 msgid "" "The object returned by ``as_completed()`` can be iterated as an :term:" "`asynchronous iterator` or a plain :term:`iterator`. When asynchronous " @@ -1005,27 +1373,57 @@ msgid "" "tasks with their results. Example::" msgstr "" -#: ../../library/asyncio-task.rst:915 +#: ../../library/asyncio-task.rst:951 +msgid "" +"ipv4_connect = create_task(open_connection(\"127.0.0.1\", 80))\n" +"ipv6_connect = create_task(open_connection(\"::1\", 80))\n" +"tasks = [ipv4_connect, ipv6_connect]\n" +"\n" +"async for earliest_connect in as_completed(tasks):\n" +" # earliest_connect is done. The result can be obtained by\n" +" # awaiting it or calling earliest_connect.result()\n" +" reader, writer = await earliest_connect\n" +"\n" +" if earliest_connect is ipv6_connect:\n" +" print(\"IPv6 connection established.\")\n" +" else:\n" +" print(\"IPv4 connection established.\")" +msgstr "" + +#: ../../library/asyncio-task.rst:965 msgid "" "During asynchronous iteration, implicitly-created tasks will be yielded for " "supplied awaitables that aren't tasks or futures." msgstr "" -#: ../../library/asyncio-task.rst:918 +#: ../../library/asyncio-task.rst:968 msgid "" "When used as a plain iterator, each iteration yields a new coroutine that " "returns the result or raises the exception of the next completed awaitable. " "This pattern is compatible with Python versions older than 3.13::" msgstr "" -#: ../../library/asyncio-task.rst:932 +#: ../../library/asyncio-task.rst:972 +msgid "" +"ipv4_connect = create_task(open_connection(\"127.0.0.1\", 80))\n" +"ipv6_connect = create_task(open_connection(\"::1\", 80))\n" +"tasks = [ipv4_connect, ipv6_connect]\n" +"\n" +"for next_connect in as_completed(tasks):\n" +" # next_connect is not one of the original task objects. It must be\n" +" # awaited to obtain the result value or raise the exception of the\n" +" # awaitable that finishes next.\n" +" reader, writer = await next_connect" +msgstr "" + +#: ../../library/asyncio-task.rst:982 msgid "" "A :exc:`TimeoutError` is raised if the timeout occurs before all awaitables " "are done. This is raised by the ``async for`` loop during asynchronous " "iteration or by the coroutines yielded during plain iteration." msgstr "" -#: ../../library/asyncio-task.rst:939 +#: ../../library/asyncio-task.rst:989 msgid "" "Deprecation warning is emitted if not all awaitable objects in the *aws* " "iterable are Future-like objects and there is no running event loop." @@ -1034,21 +1432,21 @@ msgstr "" "iterável *aws* forem objetos similar a Futuro, e não existe nenhum laço de " "eventos em execução." -#: ../../library/asyncio-task.rst:946 +#: ../../library/asyncio-task.rst:996 msgid "" "The result can now be used as either an :term:`asynchronous iterator` or as " "a plain :term:`iterator` (previously it was only a plain iterator)." msgstr "" -#: ../../library/asyncio-task.rst:952 +#: ../../library/asyncio-task.rst:1002 msgid "Running in Threads" msgstr "Executando em Threads" -#: ../../library/asyncio-task.rst:956 +#: ../../library/asyncio-task.rst:1007 msgid "Asynchronously run function *func* in a separate thread." msgstr "Executa a função *func* assincronamente em uma thread separada." -#: ../../library/asyncio-task.rst:958 +#: ../../library/asyncio-task.rst:1009 msgid "" "Any \\*args and \\*\\*kwargs supplied for this function are directly passed " "to *func*. Also, the current :class:`contextvars.Context` is propagated, " @@ -1060,21 +1458,50 @@ msgstr "" "propagado, permitindo que variáveis de contexto da thread do laço de eventos " "sejam acessadas na thread separada." -#: ../../library/asyncio-task.rst:963 +#: ../../library/asyncio-task.rst:1014 msgid "" "Return a coroutine that can be awaited to get the eventual result of *func*." msgstr "" "Retorna uma corrotina que pode ser aguardada para obter o resultado eventual " "de *func*." -#: ../../library/asyncio-task.rst:965 +#: ../../library/asyncio-task.rst:1016 msgid "" "This coroutine function is primarily intended to be used for executing IO-" "bound functions/methods that would otherwise block the event loop if they " "were run in the main thread. For example::" msgstr "" -#: ../../library/asyncio-task.rst:995 +#: ../../library/asyncio-task.rst:1020 +msgid "" +"def blocking_io():\n" +" print(f\"start blocking_io at {time.strftime('%X')}\")\n" +" # Note that time.sleep() can be replaced with any blocking\n" +" # IO-bound operation, such as file operations.\n" +" time.sleep(1)\n" +" print(f\"blocking_io complete at {time.strftime('%X')}\")\n" +"\n" +"async def main():\n" +" print(f\"started main at {time.strftime('%X')}\")\n" +"\n" +" await asyncio.gather(\n" +" asyncio.to_thread(blocking_io),\n" +" asyncio.sleep(1))\n" +"\n" +" print(f\"finished main at {time.strftime('%X')}\")\n" +"\n" +"\n" +"asyncio.run(main())\n" +"\n" +"# Expected output:\n" +"#\n" +"# started main at 19:50:53\n" +"# start blocking_io at 19:50:53\n" +"# blocking_io complete at 19:50:54\n" +"# finished main at 19:50:54" +msgstr "" + +#: ../../library/asyncio-task.rst:1046 msgid "" "Directly calling ``blocking_io()`` in any coroutine would block the event " "loop for its duration, resulting in an additional 1 second of run time. " @@ -1086,7 +1513,7 @@ msgstr "" "tempo de execução. Ao invés disso, ao utilizar ``asyncio.to_thread()``, nós " "podemos executá-la em uma thread separada sem bloquear o laço de eventos." -#: ../../library/asyncio-task.rst:1002 +#: ../../library/asyncio-task.rst:1053 msgid "" "Due to the :term:`GIL`, ``asyncio.to_thread()`` can typically only be used " "to make IO-bound functions non-blocking. However, for extension modules that " @@ -1099,16 +1526,16 @@ msgstr "" "Python que não tem um, ``asyncio.to_thread()`` também pode ser usado para " "funções vinculadas à CPU." -#: ../../library/asyncio-task.rst:1011 +#: ../../library/asyncio-task.rst:1062 msgid "Scheduling From Other Threads" msgstr "Agendando a partir de outras Threads" -#: ../../library/asyncio-task.rst:1015 +#: ../../library/asyncio-task.rst:1066 msgid "Submit a coroutine to the given event loop. Thread-safe." msgstr "" "Envia uma corrotina para o laço de eventos fornecido. Seguro para thread." -#: ../../library/asyncio-task.rst:1017 +#: ../../library/asyncio-task.rst:1068 msgid "" "Return a :class:`concurrent.futures.Future` to wait for the result from " "another OS thread." @@ -1116,7 +1543,7 @@ msgstr "" "Retorna um :class:`concurrent.futures.Future` para aguardar pelo resultado " "de outra thread do sistema operacional." -#: ../../library/asyncio-task.rst:1020 +#: ../../library/asyncio-task.rst:1071 msgid "" "This function is meant to be called from a different OS thread than the one " "where the event loop is running. Example::" @@ -1124,7 +1551,19 @@ msgstr "" "Esta função destina-se a ser chamada partir de uma thread diferente do " "sistema operacional, da qual o laço de eventos está executando. Exemplo::" -#: ../../library/asyncio-task.rst:1032 +#: ../../library/asyncio-task.rst:1074 +msgid "" +"# Create a coroutine\n" +"coro = asyncio.sleep(1, result=3)\n" +"\n" +"# Submit the coroutine to a given loop\n" +"future = asyncio.run_coroutine_threadsafe(coro, loop)\n" +"\n" +"# Wait for the result with an optional timeout argument\n" +"assert future.result(timeout) == 3" +msgstr "" + +#: ../../library/asyncio-task.rst:1083 msgid "" "If an exception is raised in the coroutine, the returned Future will be " "notified. It can also be used to cancel the task in the event loop::" @@ -1133,7 +1572,20 @@ msgstr "" "notificado. Isso também pode ser usado para cancelar a tarefa no laço de " "eventos::" -#: ../../library/asyncio-task.rst:1046 +#: ../../library/asyncio-task.rst:1087 +msgid "" +"try:\n" +" result = future.result(timeout)\n" +"except TimeoutError:\n" +" print('The coroutine took too long, cancelling the task...')\n" +" future.cancel()\n" +"except Exception as exc:\n" +" print(f'The coroutine raised an exception: {exc!r}')\n" +"else:\n" +" print(f'The coroutine returned: {result!r}')" +msgstr "" + +#: ../../library/asyncio-task.rst:1097 msgid "" "See the :ref:`concurrency and multithreading ` " "section of the documentation." @@ -1141,7 +1593,7 @@ msgstr "" "Veja a seção :ref:`concorrência e multithreading ` " "da documentação." -#: ../../library/asyncio-task.rst:1049 +#: ../../library/asyncio-task.rst:1100 msgid "" "Unlike other asyncio functions this function requires the *loop* argument to " "be passed explicitly." @@ -1149,11 +1601,11 @@ msgstr "" "Ao contrário de outras funções asyncio, esta função requer que o argumento " "*loop* seja passado explicitamente." -#: ../../library/asyncio-task.rst:1056 +#: ../../library/asyncio-task.rst:1107 msgid "Introspection" msgstr "Introspecção" -#: ../../library/asyncio-task.rst:1061 +#: ../../library/asyncio-task.rst:1112 msgid "" "Return the currently running :class:`Task` instance, or ``None`` if no task " "is running." @@ -1161,7 +1613,7 @@ msgstr "" "Retorna a instância :class:`Task` atualmente em execução, ou ``None`` se " "nenhuma tarefa estiver executando." -#: ../../library/asyncio-task.rst:1064 +#: ../../library/asyncio-task.rst:1115 msgid "" "If *loop* is ``None`` :func:`get_running_loop` is used to get the current " "loop." @@ -1169,13 +1621,13 @@ msgstr "" "Se *loop* for ``None``, então :func:`get_running_loop` é usado para obter o " "laço atual." -#: ../../library/asyncio-task.rst:1072 +#: ../../library/asyncio-task.rst:1123 msgid "Return a set of not yet finished :class:`Task` objects run by the loop." msgstr "" "Retorna um conjunto de objetos :class:`Task` ainda não concluídos a serem " "executados pelo laço." -#: ../../library/asyncio-task.rst:1075 +#: ../../library/asyncio-task.rst:1126 msgid "" "If *loop* is ``None``, :func:`get_running_loop` is used for getting current " "loop." @@ -1183,15 +1635,15 @@ msgstr "" "Se *loop* for ``None``, então :func:`get_running_loop` é usado para obter o " "laço atual." -#: ../../library/asyncio-task.rst:1083 +#: ../../library/asyncio-task.rst:1134 msgid "Return ``True`` if *obj* is a coroutine object." msgstr "" -#: ../../library/asyncio-task.rst:1089 +#: ../../library/asyncio-task.rst:1140 msgid "Task Object" msgstr "Objeto Task" -#: ../../library/asyncio-task.rst:1093 +#: ../../library/asyncio-task.rst:1144 msgid "" "A :class:`Future-like ` object that runs a Python :ref:`coroutine " "`. Not thread-safe." @@ -1199,7 +1651,7 @@ msgstr "" "Um objeto :class:`similar a Futuro ` que executa uma :ref:`corrotina " "` Python. Não é seguro para thread." -#: ../../library/asyncio-task.rst:1096 +#: ../../library/asyncio-task.rst:1147 msgid "" "Tasks are used to run coroutines in event loops. If a coroutine awaits on a " "Future, the Task suspends the execution of the coroutine and waits for the " @@ -1211,7 +1663,7 @@ msgstr "" "aguarda a conclusão do Futuro. Quando o Futuro é *concluído*, a execução da " "corrotina contida é retomada." -#: ../../library/asyncio-task.rst:1102 +#: ../../library/asyncio-task.rst:1153 msgid "" "Event loops use cooperative scheduling: an event loop runs one Task at a " "time. While a Task awaits for the completion of a Future, the event loop " @@ -1222,7 +1674,7 @@ msgstr "" "laço de eventos executa outras Tarefas, funções de retorno, ou executa " "operações de IO." -#: ../../library/asyncio-task.rst:1107 +#: ../../library/asyncio-task.rst:1158 msgid "" "Use the high-level :func:`asyncio.create_task` function to create Tasks, or " "the low-level :meth:`loop.create_task` or :func:`ensure_future` functions. " @@ -1232,7 +1684,7 @@ msgstr "" "ou as funções de baixo nível :meth:`loop.create_task` ou :func:" "`ensure_future`. Instanciação manual de Tarefas é desencorajado." -#: ../../library/asyncio-task.rst:1112 +#: ../../library/asyncio-task.rst:1163 msgid "" "To cancel a running Task use the :meth:`cancel` method. Calling it will " "cause the Task to throw a :exc:`CancelledError` exception into the wrapped " @@ -1244,7 +1696,7 @@ msgstr "" "da corrotina contida. Se a corrotina estiver esperando por um objeto Future " "durante o cancelamento, o objeto Future será cancelado." -#: ../../library/asyncio-task.rst:1117 +#: ../../library/asyncio-task.rst:1168 msgid "" ":meth:`cancelled` can be used to check if the Task was cancelled. The method " "returns ``True`` if the wrapped coroutine did not suppress the :exc:" @@ -1254,7 +1706,7 @@ msgstr "" "método retorna ``True`` se a corrotina envolta não suprimiu a exceção :exc:" "`CancelledError` e foi na verdade cancelada." -#: ../../library/asyncio-task.rst:1122 +#: ../../library/asyncio-task.rst:1173 msgid "" ":class:`asyncio.Task` inherits from :class:`Future` all of its APIs except :" "meth:`Future.set_result` and :meth:`Future.set_exception`." @@ -1262,7 +1714,7 @@ msgstr "" ":class:`asyncio.Task` herda de :class:`Future` todas as suas APIs exceto :" "meth:`Future.set_result` e :meth:`Future.set_exception`." -#: ../../library/asyncio-task.rst:1126 +#: ../../library/asyncio-task.rst:1177 msgid "" "An optional keyword-only *context* argument allows specifying a custom :" "class:`contextvars.Context` for the *coro* to run in. If no *context* is " @@ -1270,7 +1722,7 @@ msgid "" "in the copied context." msgstr "" -#: ../../library/asyncio-task.rst:1131 +#: ../../library/asyncio-task.rst:1182 msgid "" "An optional keyword-only *eager_start* argument allows eagerly starting the " "execution of the :class:`asyncio.Task` at task creation time. If set to " @@ -1280,11 +1732,11 @@ msgid "" "eagerly and will skip scheduling to the event loop." msgstr "" -#: ../../library/asyncio-task.rst:1138 +#: ../../library/asyncio-task.rst:1189 msgid "Added support for the :mod:`contextvars` module." msgstr "Adicionado suporte para o módulo :mod:`contextvars`." -#: ../../library/asyncio-task.rst:1144 +#: ../../library/asyncio-task.rst:1195 msgid "" "Deprecation warning is emitted if *loop* is not specified and there is no " "running event loop." @@ -1292,15 +1744,15 @@ msgstr "" "Aviso de descontinuidade é emitido se *loop* não é especificado, e não " "existe nenhum laço de eventos em execução." -#: ../../library/asyncio-task.rst:1151 +#: ../../library/asyncio-task.rst:1202 msgid "Added the *eager_start* parameter." msgstr "" -#: ../../library/asyncio-task.rst:1156 +#: ../../library/asyncio-task.rst:1207 msgid "Return ``True`` if the Task is *done*." msgstr "Retorna ``True`` se a Tarefa estiver *concluída*." -#: ../../library/asyncio-task.rst:1158 +#: ../../library/asyncio-task.rst:1209 msgid "" "A Task is *done* when the wrapped coroutine either returned a value, raised " "an exception, or the Task was cancelled." @@ -1308,11 +1760,11 @@ msgstr "" "Uma Tarefa está *concluída* quando a corrotina contida retornou um valor, ou " "levantou uma exceção, ou a Tarefa foi cancelada." -#: ../../library/asyncio-task.rst:1163 +#: ../../library/asyncio-task.rst:1214 msgid "Return the result of the Task." msgstr "Retorna o resultado da Tarefa." -#: ../../library/asyncio-task.rst:1165 +#: ../../library/asyncio-task.rst:1216 msgid "" "If the Task is *done*, the result of the wrapped coroutine is returned (or " "if the coroutine raised an exception, that exception is re-raised.)" @@ -1321,7 +1773,7 @@ msgstr "" "retornado (ou se a corrotina levantou uma exceção, essa exceção é re-" "levantada.)" -#: ../../library/asyncio-task.rst:1169 ../../library/asyncio-task.rst:1183 +#: ../../library/asyncio-task.rst:1220 ../../library/asyncio-task.rst:1234 msgid "" "If the Task has been *cancelled*, this method raises a :exc:`CancelledError` " "exception." @@ -1329,17 +1781,17 @@ msgstr "" "Se a Tarefa foi *cancelada*, este método levanta uma exceção :exc:" "`CancelledError`." -#: ../../library/asyncio-task.rst:1172 +#: ../../library/asyncio-task.rst:1223 msgid "" "If the Task's result isn't yet available, this method raises an :exc:" "`InvalidStateError` exception." msgstr "" -#: ../../library/asyncio-task.rst:1177 +#: ../../library/asyncio-task.rst:1228 msgid "Return the exception of the Task." msgstr "Retorna a exceção de uma Tarefa." -#: ../../library/asyncio-task.rst:1179 +#: ../../library/asyncio-task.rst:1230 msgid "" "If the wrapped coroutine raised an exception that exception is returned. If " "the wrapped coroutine returned normally this method returns ``None``." @@ -1347,7 +1799,7 @@ msgstr "" "Se a corrotina contida levantou uma exceção, essa exceção é retornada. Se a " "corrotina contida retornou normalmente, este método retorna ``None``." -#: ../../library/asyncio-task.rst:1186 +#: ../../library/asyncio-task.rst:1237 msgid "" "If the Task isn't *done* yet, this method raises an :exc:`InvalidStateError` " "exception." @@ -1355,29 +1807,29 @@ msgstr "" "Se a Tarefa não estiver *concluída* ainda, este método levanta uma exceção :" "exc:`InvalidStateError`." -#: ../../library/asyncio-task.rst:1191 +#: ../../library/asyncio-task.rst:1242 msgid "Add a callback to be run when the Task is *done*." msgstr "" "Adiciona uma função de retorno para ser executada quando a Tarefa estiver " "*concluída*." -#: ../../library/asyncio-task.rst:1193 ../../library/asyncio-task.rst:1202 +#: ../../library/asyncio-task.rst:1244 ../../library/asyncio-task.rst:1253 msgid "This method should only be used in low-level callback-based code." msgstr "" "Este método deve ser usado apenas em código de baixo nível baseado em " "funções de retorno." -#: ../../library/asyncio-task.rst:1195 +#: ../../library/asyncio-task.rst:1246 msgid "" "See the documentation of :meth:`Future.add_done_callback` for more details." msgstr "" "Veja a documentação para :meth:`Future.add_done_callback` para mais detalhes." -#: ../../library/asyncio-task.rst:1200 +#: ../../library/asyncio-task.rst:1251 msgid "Remove *callback* from the callbacks list." msgstr "Remove *callback* da lista de funções de retorno." -#: ../../library/asyncio-task.rst:1204 +#: ../../library/asyncio-task.rst:1255 msgid "" "See the documentation of :meth:`Future.remove_done_callback` for more " "details." @@ -1385,11 +1837,11 @@ msgstr "" "Veja a documentação do método :meth:`Future.remove_done_callback` para mais " "detalhes." -#: ../../library/asyncio-task.rst:1209 +#: ../../library/asyncio-task.rst:1260 msgid "Return the list of stack frames for this Task." msgstr "Retorna a lista de frames da pilha para esta Tarefa." -#: ../../library/asyncio-task.rst:1211 +#: ../../library/asyncio-task.rst:1262 msgid "" "If the wrapped coroutine is not done, this returns the stack where it is " "suspended. If the coroutine has completed successfully or was cancelled, " @@ -1401,16 +1853,16 @@ msgstr "" "isto retorna uma lista vazia. Se a corrotina foi terminada por uma exceção, " "isto retorna a lista de frames do traceback (situação da pilha de execução)." -#: ../../library/asyncio-task.rst:1217 +#: ../../library/asyncio-task.rst:1268 msgid "The frames are always ordered from oldest to newest." msgstr "" "Os quadros são sempre ordenados dos mais antigos para os mais recentes." -#: ../../library/asyncio-task.rst:1219 +#: ../../library/asyncio-task.rst:1270 msgid "Only one stack frame is returned for a suspended coroutine." msgstr "Apenas um frame da pilha é retornado para uma corrotina suspensa." -#: ../../library/asyncio-task.rst:1221 +#: ../../library/asyncio-task.rst:1272 msgid "" "The optional *limit* argument sets the maximum number of frames to return; " "by default all available frames are returned. The ordering of the returned " @@ -1426,11 +1878,11 @@ msgstr "" "traceback são retornados. (Isso combina com o comportamento do módulo " "traceback.)" -#: ../../library/asyncio-task.rst:1230 +#: ../../library/asyncio-task.rst:1281 msgid "Print the stack or traceback for this Task." msgstr "Exibe a pilha ou situação da pilha de execução para esta Tarefa." -#: ../../library/asyncio-task.rst:1232 +#: ../../library/asyncio-task.rst:1283 msgid "" "This produces output similar to that of the traceback module for the frames " "retrieved by :meth:`get_stack`." @@ -1438,40 +1890,40 @@ msgstr "" "Isto produz uma saída similar a do módulo traceback para frames recuperados " "por :meth:`get_stack`." -#: ../../library/asyncio-task.rst:1235 +#: ../../library/asyncio-task.rst:1286 msgid "The *limit* argument is passed to :meth:`get_stack` directly." msgstr "O argumento *limit* é passado para :meth:`get_stack` diretamente." -#: ../../library/asyncio-task.rst:1237 +#: ../../library/asyncio-task.rst:1288 msgid "" "The *file* argument is an I/O stream to which the output is written; by " "default output is written to :data:`sys.stdout`." msgstr "" -#: ../../library/asyncio-task.rst:1242 +#: ../../library/asyncio-task.rst:1293 msgid "Return the coroutine object wrapped by the :class:`Task`." msgstr "Retorna o objeto corrotina contido pela :class:`Task`." -#: ../../library/asyncio-task.rst:1246 +#: ../../library/asyncio-task.rst:1297 msgid "" "This will return ``None`` for Tasks which have already completed eagerly. " "See the :ref:`Eager Task Factory `." msgstr "" -#: ../../library/asyncio-task.rst:1253 +#: ../../library/asyncio-task.rst:1304 msgid "Newly added eager task execution means result may be ``None``." msgstr "" -#: ../../library/asyncio-task.rst:1257 +#: ../../library/asyncio-task.rst:1308 msgid "" "Return the :class:`contextvars.Context` object associated with the task." msgstr "" -#: ../../library/asyncio-task.rst:1264 +#: ../../library/asyncio-task.rst:1315 msgid "Return the name of the Task." msgstr "Retorna o nome da Tarefa." -#: ../../library/asyncio-task.rst:1266 +#: ../../library/asyncio-task.rst:1317 msgid "" "If no name has been explicitly assigned to the Task, the default asyncio " "Task implementation generates a default name during instantiation." @@ -1479,18 +1931,18 @@ msgstr "" "Se nenhum nome foi explicitamente designado para a Tarefa, a implementação " "padrão asyncio da classe Task gera um nome padrão durante a instanciação." -#: ../../library/asyncio-task.rst:1274 +#: ../../library/asyncio-task.rst:1325 msgid "Set the name of the Task." msgstr "Define o nome da Tarefa." -#: ../../library/asyncio-task.rst:1276 +#: ../../library/asyncio-task.rst:1327 msgid "" "The *value* argument can be any object, which is then converted to a string." msgstr "" "O argumento *value* pode ser qualquer objeto, o qual é então convertido para " "uma string." -#: ../../library/asyncio-task.rst:1279 +#: ../../library/asyncio-task.rst:1330 msgid "" "In the default Task implementation, the name will be visible in the :func:" "`repr` output of a task object." @@ -1498,19 +1950,23 @@ msgstr "" "Na implementação padrão da Tarefa, o nome será visível na :func:`repr` de " "saída de um objeto task." -#: ../../library/asyncio-task.rst:1286 +#: ../../library/asyncio-task.rst:1337 msgid "Request the Task to be cancelled." msgstr "Solicita o cancelamento da Tarefa." -#: ../../library/asyncio-task.rst:1288 +#: ../../library/asyncio-task.rst:1339 +msgid "" +"If the Task is already *done* or *cancelled*, return ``False``, otherwise, " +"return ``True``." +msgstr "" + +#: ../../library/asyncio-task.rst:1342 msgid "" -"This arranges for a :exc:`CancelledError` exception to be thrown into the " -"wrapped coroutine on the next cycle of the event loop." +"The method arranges for a :exc:`CancelledError` exception to be thrown into " +"the wrapped coroutine on the next cycle of the event loop." msgstr "" -"Isto prepara para uma exceção :exc:`CancelledError` ser lançada na corrotina " -"contida no próximo ciclo do laço de eventos." -#: ../../library/asyncio-task.rst:1291 +#: ../../library/asyncio-task.rst:1345 msgid "" "The coroutine then has a chance to clean up or even deny the request by " "suppressing the exception with a :keyword:`try` ... ... ``except " @@ -1522,15 +1978,15 @@ msgid "" "addition to catching the exception." msgstr "" -#: ../../library/asyncio-task.rst:1301 +#: ../../library/asyncio-task.rst:1355 msgid "Added the *msg* parameter." msgstr "Adicionado o parâmetro *msg*." -#: ../../library/asyncio-task.rst:1304 +#: ../../library/asyncio-task.rst:1358 msgid "The ``msg`` parameter is propagated from cancelled task to its awaiter." msgstr "" -#: ../../library/asyncio-task.rst:1309 +#: ../../library/asyncio-task.rst:1363 msgid "" "The following example illustrates how coroutines can intercept the " "cancellation request::" @@ -1538,11 +1994,48 @@ msgstr "" "O seguinte exemplo ilustra como corrotinas podem interceptar o cancelamento " "de requisições::" -#: ../../library/asyncio-task.rst:1348 +#: ../../library/asyncio-task.rst:1366 +msgid "" +"async def cancel_me():\n" +" print('cancel_me(): before sleep')\n" +"\n" +" try:\n" +" # Wait for 1 hour\n" +" await asyncio.sleep(3600)\n" +" except asyncio.CancelledError:\n" +" print('cancel_me(): cancel sleep')\n" +" raise\n" +" finally:\n" +" print('cancel_me(): after sleep')\n" +"\n" +"async def main():\n" +" # Create a \"cancel_me\" Task\n" +" task = asyncio.create_task(cancel_me())\n" +"\n" +" # Wait for 1 second\n" +" await asyncio.sleep(1)\n" +"\n" +" task.cancel()\n" +" try:\n" +" await task\n" +" except asyncio.CancelledError:\n" +" print(\"main(): cancel_me is cancelled now\")\n" +"\n" +"asyncio.run(main())\n" +"\n" +"# Expected output:\n" +"#\n" +"# cancel_me(): before sleep\n" +"# cancel_me(): cancel sleep\n" +"# cancel_me(): after sleep\n" +"# main(): cancel_me is cancelled now" +msgstr "" + +#: ../../library/asyncio-task.rst:1402 msgid "Return ``True`` if the Task is *cancelled*." msgstr "Retorna ``True`` se a Tarefa for *cancelada*." -#: ../../library/asyncio-task.rst:1350 +#: ../../library/asyncio-task.rst:1404 msgid "" "The Task is *cancelled* when the cancellation was requested with :meth:" "`cancel` and the wrapped coroutine propagated the :exc:`CancelledError` " @@ -1552,21 +2045,21 @@ msgstr "" "`cancel` e a corrotina contida propagou a exceção :exc:`CancelledError` " "gerada nela." -#: ../../library/asyncio-task.rst:1356 +#: ../../library/asyncio-task.rst:1410 msgid "Decrement the count of cancellation requests to this Task." msgstr "" -#: ../../library/asyncio-task.rst:1358 +#: ../../library/asyncio-task.rst:1412 msgid "Returns the remaining number of cancellation requests." msgstr "" -#: ../../library/asyncio-task.rst:1360 +#: ../../library/asyncio-task.rst:1414 msgid "" "Note that once execution of a cancelled task completed, further calls to :" "meth:`uncancel` are ineffective." msgstr "" -#: ../../library/asyncio-task.rst:1365 +#: ../../library/asyncio-task.rst:1419 msgid "" "This method is used by asyncio's internals and isn't expected to be used by " "end-user code. In particular, if a Task gets successfully uncancelled, this " @@ -1575,7 +2068,21 @@ msgid "" "respective structured block. For example::" msgstr "" -#: ../../library/asyncio-task.rst:1383 +#: ../../library/asyncio-task.rst:1426 +msgid "" +"async def make_request_with_timeout():\n" +" try:\n" +" async with asyncio.timeout(1):\n" +" # Structured block affected by the timeout:\n" +" await make_request()\n" +" await make_another_request()\n" +" except TimeoutError:\n" +" log(\"There was a timeout\")\n" +" # Outer code not affected by the timeout:\n" +" await unrelated_code()" +msgstr "" + +#: ../../library/asyncio-task.rst:1437 msgid "" "While the block with ``make_request()`` and ``make_another_request()`` might " "get cancelled due to the timeout, ``unrelated_code()`` should continue " @@ -1584,14 +2091,14 @@ msgid "" "similar fashion." msgstr "" -#: ../../library/asyncio-task.rst:1389 +#: ../../library/asyncio-task.rst:1443 msgid "" "If end-user code is, for some reason, suppressing cancellation by catching :" "exc:`CancelledError`, it needs to call this method to remove the " "cancellation state." msgstr "" -#: ../../library/asyncio-task.rst:1393 +#: ../../library/asyncio-task.rst:1447 msgid "" "When this method decrements the cancellation count to zero, the method " "checks if a previous :meth:`cancel` call had arranged for :exc:" @@ -1600,17 +2107,17 @@ msgid "" "``_must_cancel`` flag)." msgstr "" -#: ../../library/asyncio-task.rst:1399 +#: ../../library/asyncio-task.rst:1453 msgid "Changed to rescind pending cancellation requests upon reaching zero." msgstr "" -#: ../../library/asyncio-task.rst:1404 +#: ../../library/asyncio-task.rst:1458 msgid "" "Return the number of pending cancellation requests to this Task, i.e., the " "number of calls to :meth:`cancel` less the number of :meth:`uncancel` calls." msgstr "" -#: ../../library/asyncio-task.rst:1408 +#: ../../library/asyncio-task.rst:1462 msgid "" "Note that if this number is greater than zero but the Task is still " "executing, :meth:`cancelled` will still return ``False``. This is because " @@ -1619,7 +2126,7 @@ msgid "" "to zero." msgstr "" -#: ../../library/asyncio-task.rst:1414 +#: ../../library/asyncio-task.rst:1468 msgid "" "This method is used by asyncio's internals and isn't expected to be used by " "end-user code. See :meth:`uncancel` for more details." diff --git a/library/asyncio.po b/library/asyncio.po index 3504b2617..0a011c2ea 100644 --- a/library/asyncio.po +++ b/library/asyncio.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Lilian Corrêa , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:55+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -46,6 +43,26 @@ msgstr ":mod:`!asyncio` --- E/S assíncrona" msgid "Hello World!" msgstr "Olá Mundo!" +#: ../../library/asyncio.rst:13 +msgid "" +"import asyncio\n" +"\n" +"async def main():\n" +" print('Hello ...')\n" +" await asyncio.sleep(1)\n" +" print('... World!')\n" +"\n" +"asyncio.run(main())" +msgstr "" +"import asyncio\n" +"\n" +"async def main():\n" +" print('Olá ...')\n" +" await asyncio.sleep(1)\n" +" print('... Mundo!')\n" +"\n" +"asyncio.run(main())" + #: ../../library/asyncio.rst:22 msgid "" "asyncio is a library to write **concurrent** code using the **async/await** " @@ -137,8 +154,8 @@ msgstr "" "chamadas e codificar com a sintaxe de async/await." #: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +msgid "Availability" +msgstr "Disponibilidade" #: ../../includes/wasm-notavail.rst:5 msgid "" @@ -156,8 +173,27 @@ msgstr "REPL de asyncio" msgid "" "You can experiment with an ``asyncio`` concurrent context in the :term:" "`REPL`:" +msgstr "Você pode experimentar um contexto atual ``asyncio`` no :term:`REPL`:" + +#: ../../library/asyncio.rst:67 +msgid "" +"$ python -m asyncio\n" +"asyncio REPL ...\n" +"Use \"await\" directly instead of \"asyncio.run()\".\n" +"Type \"help\", \"copyright\", \"credits\" or \"license\" for more " +"information.\n" +">>> import asyncio\n" +">>> await asyncio.sleep(10, result='hello')\n" +"'hello'" msgstr "" -"Você pode experimentar um contexto concorrente ``asyncio`` no :term:`REPL`:" +"$ python -m asyncio\n" +"asyncio REPL ...\n" +"Use \"await\" directly instead of \"asyncio.run()\".\n" +"Type \"help\", \"copyright\", \"credits\" or \"license\" for more " +"information.\n" +">>> import asyncio\n" +">>> await asyncio.sleep(10, result='hello')\n" +"'hello'" #: ../../library/asyncio.rst:77 msgid "" diff --git a/library/asyncore.po b/library/asyncore.po new file mode 100644 index 000000000..bad2afa9b --- /dev/null +++ b/library/asyncore.po @@ -0,0 +1,50 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../library/asyncore.rst:2 +msgid ":mod:`!asyncore` --- Asynchronous socket handler" +msgstr ":mod:`!asyncore` --- Manipulador de socket assíncrono" + +#: ../../library/asyncore.rst:10 +msgid "" +"This module is no longer part of the Python standard library. It was :ref:" +"`removed in Python 3.12 ` after being deprecated in " +"Python 3.6. The removal was decided in :pep:`594`." +msgstr "" +"Este módulo não faz mais parte da biblioteca padrão do Python. Ele foi :ref:" +"`removido no Python 3.12 ` após ser descontinuado no " +"Python 3.6. A remoção foi decidida na :pep:`594`." + +#: ../../library/asyncore.rst:14 +msgid "Applications should use the :mod:`asyncio` module instead." +msgstr "As aplicações devem usar o módulo :mod:`asyncio` em vez disso." + +#: ../../library/asyncore.rst:16 +msgid "" +"The last version of Python that provided the :mod:`!asyncore` module was " +"`Python 3.11 `_." +msgstr "" +"A última versão do Python que forneceu o módulo :mod:`!asyncore` foi o " +"`Python 3.11 `_." diff --git a/library/atexit.po b/library/atexit.po index 59ccd2a67..cab6a23ea 100644 --- a/library/atexit.po +++ b/library/atexit.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:55+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -95,7 +94,7 @@ msgstr "" "chamado ou a execução do módulo principal for concluída), todas as funções " "registradas serão chamadas por último, pela primeira ordem. A suposição é " "que os módulos de nível inferior normalmente serão importados antes dos " -"módulos de nível superior e, portanto, devem ser limpos posteriormente." +"módulos de nível mais alto e, portanto, devem ser limpos posteriormente." #: ../../library/atexit.rst:43 msgid "" @@ -183,6 +182,44 @@ msgstr "" "valor atualizado do contador quando o programa termina, sem depender que a " "aplicação faça uma chamada explícita nesse módulo na finalização. ::" +#: ../../library/atexit.rst:89 +msgid "" +"try:\n" +" with open('counterfile') as infile:\n" +" _count = int(infile.read())\n" +"except FileNotFoundError:\n" +" _count = 0\n" +"\n" +"def incrcounter(n):\n" +" global _count\n" +" _count = _count + n\n" +"\n" +"def savecounter():\n" +" with open('counterfile', 'w') as outfile:\n" +" outfile.write('%d' % _count)\n" +"\n" +"import atexit\n" +"\n" +"atexit.register(savecounter)" +msgstr "" +"try:\n" +" with open('counterfile') as infile:\n" +" _count = int(infile.read())\n" +"except FileNotFoundError:\n" +" _count = 0\n" +"\n" +"def incrcounter(n):\n" +" global _count\n" +" _count = _count + n\n" +"\n" +"def savecounter():\n" +" with open('counterfile', 'w') as outfile:\n" +" outfile.write('%d' % _count)\n" +"\n" +"import atexit\n" +"\n" +"atexit.register(savecounter)" + #: ../../library/atexit.rst:107 msgid "" "Positional and keyword arguments may also be passed to :func:`register` to " @@ -192,10 +229,44 @@ msgstr "" "para :func:`register` para ser passada para a função registrada quando é " "chamada ::" +#: ../../library/atexit.rst:110 +msgid "" +"def goodbye(name, adjective):\n" +" print('Goodbye %s, it was %s to meet you.' % (name, adjective))\n" +"\n" +"import atexit\n" +"\n" +"atexit.register(goodbye, 'Donny', 'nice')\n" +"# or:\n" +"atexit.register(goodbye, adjective='nice', name='Donny')" +msgstr "" +"def goodbye(name, adjective):\n" +" print('Goodbye %s, it was %s to meet you.' % (name, adjective))\n" +"\n" +"import atexit\n" +"\n" +"atexit.register(goodbye, 'Donny', 'nice')\n" +"# ou:\n" +"atexit.register(goodbye, adjective='nice', name='Donny')" + #: ../../library/atexit.rst:119 msgid "Usage as a :term:`decorator`::" msgstr "Utilizado como um :term:`decorador`::" +#: ../../library/atexit.rst:121 +msgid "" +"import atexit\n" +"\n" +"@atexit.register\n" +"def goodbye():\n" +" print('You are now leaving the Python sector.')" +msgstr "" +"import atexit\n" +"\n" +"@atexit.register\n" +"def goodbye():\n" +" print('You are now leaving the Python sector.')" + #: ../../library/atexit.rst:127 msgid "This only works with functions that can be called without arguments." msgstr "Isso só funciona com funções que podem ser invocadas sem argumentos." diff --git a/library/audioop.po b/library/audioop.po new file mode 100644 index 000000000..5d6329dc2 --- /dev/null +++ b/library/audioop.po @@ -0,0 +1,46 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../library/audioop.rst:2 +msgid ":mod:`!audioop` --- Manipulate raw audio data" +msgstr ":mod:`!audioop` --- Manipulando dados de áudio original" + +#: ../../library/audioop.rst:10 +msgid "" +"This module is no longer part of the Python standard library. It was :ref:" +"`removed in Python 3.13 ` after being deprecated in " +"Python 3.11. The removal was decided in :pep:`594`." +msgstr "" +"Este módulo não faz mais parte da biblioteca padrão do Python. Ele foi :ref:" +"`removido no Python 3.13 ` após ser descontinuado no " +"Python 3.11. A remoção foi decidida na :pep:`594`." + +#: ../../library/audioop.rst:14 +msgid "" +"The last version of Python that provided the :mod:`!audioop` module was " +"`Python 3.12 `_." +msgstr "" +"A última versão do Python que forneceu o módulo :mod:`!audioop` foi o " +"`Python 3.12 `_." diff --git a/library/audit_events.po b/library/audit_events.po index 19610be1e..a680b023c 100644 --- a/library/audit_events.po +++ b/library/audit_events.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2023 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 00:55+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/base64.po b/library/base64.po index ee0b56485..de2d498d2 100644 --- a/library/base64.po +++ b/library/base64.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Bonifacio de Oliveira , 2021 -# Augusta Carla Klug , 2021 -# Claudio Rogerio Carvalho Filho , 2023 -# Rafael Fontenelle , 2023 -# Vitor Buxbaum Orlandi, 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:55+0000\n" -"Last-Translator: Vitor Buxbaum Orlandi, 2023\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -39,31 +34,14 @@ msgstr "**Código-fonte:** :source:`Lib/base64.py`" #: ../../library/base64.rst:16 msgid "" "This module provides functions for encoding binary data to printable ASCII " -"characters and decoding such encodings back to binary data. It provides " -"encoding and decoding functions for the encodings specified in :rfc:`4648`, " -"which defines the Base16, Base32, and Base64 algorithms, and for the de-" -"facto standard Ascii85 and Base85 encodings." +"characters and decoding such encodings back to binary data. This includes " +"the :ref:`encodings specified in ` :rfc:`4648` (Base64, " +"Base32 and Base16) and the non-standard :ref:`Base85 encodings `." msgstr "" -"Este módulo fornece funções para codificar dados binários em caracteres " -"ASCII imprimíveis e decodificar essas codificações de volta para dados " -"binários. Ele fornece funções de codificação e decodificação para as " -"codificações especificadas em :rfc:`4648`, que define os algoritmos Base16, " -"Base32 e Base64, e para as codificações padrão de fato Ascii85 e Base85." #: ../../library/base64.rst:22 msgid "" -"The :rfc:`4648` encodings are suitable for encoding binary data so that it " -"can be safely sent by email, used as parts of URLs, or included as part of " -"an HTTP POST request. The encoding algorithm is not the same as the :" -"program:`uuencode` program." -msgstr "" -"As codificações :rfc:`4648` são adequadas para codificar dados binários para " -"que possam ser enviados com segurança por e-mail, usados como parte de URLs " -"ou incluídos como parte de uma solicitação HTTP POST. O algoritmo de " -"codificação não é o mesmo do programa :program:`uuencode`." - -#: ../../library/base64.rst:27 -msgid "" "There are two interfaces provided by this module. The modern interface " "supports encoding :term:`bytes-like objects ` to ASCII :" "class:`bytes`, and decoding :term:`bytes-like objects ` " @@ -77,23 +55,17 @@ msgstr "" "`bytes`. Ambos os alfabetos de base 64 definidos em :rfc:`4648` (normal e " "seguro para URL e sistema de arquivos) são suportados." -#: ../../library/base64.rst:33 +#: ../../library/base64.rst:28 msgid "" -"The legacy interface does not support decoding from strings, but it does " -"provide functions for encoding and decoding to and from :term:`file objects " -"`. It only supports the Base64 standard alphabet, and it adds " -"newlines every 76 characters as per :rfc:`2045`. Note that if you are " -"looking for :rfc:`2045` support you probably want to be looking at the :mod:" -"`email` package instead." +"The :ref:`legacy interface ` does not support decoding from " +"strings, but it does provide functions for encoding and decoding to and " +"from :term:`file objects `. It only supports the Base64 " +"standard alphabet, and it adds newlines every 76 characters as per :rfc:" +"`2045`. Note that if you are looking for :rfc:`2045` support you probably " +"want to be looking at the :mod:`email` package instead." msgstr "" -"A interface legada não oferece suporte a decodificação de strings, mas " -"fornece funções para codificação e decodificação de e para :term:`objetos " -"arquivo `. Ele oferece suporte a apenas o alfabeto padrão " -"Base64 e adiciona novas linhas a cada 76 caracteres conforme :rfc:`2045`. " -"Note que se você estiver procurando por suporte para :rfc:`2045` você " -"provavelmente vai querer conferir o pacote :mod:`email`." -#: ../../library/base64.rst:41 +#: ../../library/base64.rst:36 msgid "" "ASCII-only Unicode strings are now accepted by the decoding functions of the " "modern interface." @@ -101,7 +73,7 @@ msgstr "" "Strings Unicode exclusivamente ASCII agora são aceitas pelas funções de " "decodificação da interface moderna." -#: ../../library/base64.rst:45 +#: ../../library/base64.rst:40 msgid "" "Any :term:`bytes-like objects ` are now accepted by all " "encoding and decoding functions in this module. Ascii85/Base85 support " @@ -111,19 +83,26 @@ msgstr "" "aceitos por todas as funções de codificação e decodificação neste módulo. " "Adicionado suporte a ASCII85/Base85." -#: ../../library/base64.rst:49 -msgid "The modern interface provides:" -msgstr "A interface moderna oferece:" +#: ../../library/base64.rst:48 +msgid "RFC 4648 Encodings" +msgstr "" -#: ../../library/base64.rst:53 +#: ../../library/base64.rst:50 +msgid "" +"The :rfc:`4648` encodings are suitable for encoding binary data so that it " +"can be safely sent by email, used as parts of URLs, or included as part of " +"an HTTP POST request." +msgstr "" + +#: ../../library/base64.rst:56 msgid "" "Encode the :term:`bytes-like object` *s* using Base64 and return the " "encoded :class:`bytes`." msgstr "" -"Codifica o :term:`objeto bytes ou similar ` *s* usando " -"Base64 e retorna o :class:`bytes` codificado." +"Codifica o :term:`objeto bytes ou similar` *s* usando Base64 e retorna o :" +"class:`bytes` codificado." -#: ../../library/base64.rst:56 +#: ../../library/base64.rst:59 msgid "" "Optional *altchars* must be a :term:`bytes-like object` of length 2 which " "specifies an alternative alphabet for the ``+`` and ``/`` characters. This " @@ -132,34 +111,34 @@ msgid "" "used." msgstr "" -#: ../../library/base64.rst:61 +#: ../../library/base64.rst:64 msgid "" "May assert or raise a :exc:`ValueError` if the length of *altchars* is not " "2. Raises a :exc:`TypeError` if *altchars* is not a :term:`bytes-like " "object`." msgstr "" -#: ../../library/base64.rst:67 +#: ../../library/base64.rst:70 msgid "" "Decode the Base64 encoded :term:`bytes-like object` or ASCII string *s* and " "return the decoded :class:`bytes`." msgstr "" -"Decodifica o :term:`objeto bytes ou similar ` ou string " -"ASCII *s* codificada em Base64 e retorna o :class:`bytes` decodificado." +"Decodifica o :term:`objeto bytes ou similar` ou string ASCII *s* codificada " +"em Base64 e retorna o :class:`bytes` decodificado." -#: ../../library/base64.rst:70 +#: ../../library/base64.rst:73 msgid "" "Optional *altchars* must be a :term:`bytes-like object` or ASCII string of " "length 2 which specifies the alternative alphabet used instead of the ``+`` " "and ``/`` characters." msgstr "" -#: ../../library/base64.rst:74 +#: ../../library/base64.rst:77 msgid "" "A :exc:`binascii.Error` exception is raised if *s* is incorrectly padded." msgstr "" -#: ../../library/base64.rst:77 +#: ../../library/base64.rst:80 msgid "" "If *validate* is ``False`` (the default), characters that are neither in the " "normal base-64 alphabet nor the alternative alphabet are discarded prior to " @@ -167,30 +146,30 @@ msgid "" "in the input result in a :exc:`binascii.Error`." msgstr "" -#: ../../library/base64.rst:83 +#: ../../library/base64.rst:86 msgid "" "For more information about the strict base64 check, see :func:`binascii." "a2b_base64`" msgstr "" -#: ../../library/base64.rst:85 +#: ../../library/base64.rst:88 msgid "" "May assert or raise a :exc:`ValueError` if the length of *altchars* is not 2." msgstr "" -#: ../../library/base64.rst:89 +#: ../../library/base64.rst:92 msgid "" "Encode :term:`bytes-like object` *s* using the standard Base64 alphabet and " "return the encoded :class:`bytes`." msgstr "" -#: ../../library/base64.rst:95 +#: ../../library/base64.rst:98 msgid "" "Decode :term:`bytes-like object` or ASCII string *s* using the standard " "Base64 alphabet and return the decoded :class:`bytes`." msgstr "" -#: ../../library/base64.rst:101 +#: ../../library/base64.rst:104 msgid "" "Encode :term:`bytes-like object` *s* using the URL- and filesystem-safe " "alphabet, which substitutes ``-`` instead of ``+`` and ``_`` instead of ``/" @@ -198,7 +177,7 @@ msgid "" "The result can still contain ``=``." msgstr "" -#: ../../library/base64.rst:110 +#: ../../library/base64.rst:113 msgid "" "Decode :term:`bytes-like object` or ASCII string *s* using the URL- and " "filesystem-safe alphabet, which substitutes ``-`` instead of ``+`` and ``_`` " @@ -206,19 +185,19 @@ msgid "" "class:`bytes`." msgstr "" -#: ../../library/base64.rst:119 +#: ../../library/base64.rst:122 msgid "" "Encode the :term:`bytes-like object` *s* using Base32 and return the " "encoded :class:`bytes`." msgstr "" -#: ../../library/base64.rst:125 +#: ../../library/base64.rst:128 msgid "" "Decode the Base32 encoded :term:`bytes-like object` or ASCII string *s* and " "return the decoded :class:`bytes`." msgstr "" -#: ../../library/base64.rst:128 ../../library/base64.rst:176 +#: ../../library/base64.rst:131 ../../library/base64.rst:179 msgid "" "Optional *casefold* is a flag specifying whether a lowercase alphabet is " "acceptable as input. For security purposes, the default is ``False``." @@ -226,7 +205,7 @@ msgstr "" "*casefold* opcional é uma flag especificando se um alfabeto minúsculo é " "aceitável como entrada. Por razões de segurança, o padrão é ``False``." -#: ../../library/base64.rst:132 +#: ../../library/base64.rst:135 msgid "" ":rfc:`4648` allows for optional mapping of the digit 0 (zero) to the letter " "O (oh), and for optional mapping of the digit 1 (one) to either the letter I " @@ -237,25 +216,25 @@ msgid "" "input." msgstr "" -#: ../../library/base64.rst:139 ../../library/base64.rst:180 +#: ../../library/base64.rst:142 ../../library/base64.rst:183 msgid "" "A :exc:`binascii.Error` is raised if *s* is incorrectly padded or if there " "are non-alphabet characters present in the input." msgstr "" -#: ../../library/base64.rst:146 +#: ../../library/base64.rst:149 msgid "" "Similar to :func:`b32encode` but uses the Extended Hex Alphabet, as defined " "in :rfc:`4648`." msgstr "" -#: ../../library/base64.rst:154 +#: ../../library/base64.rst:157 msgid "" "Similar to :func:`b32decode` but uses the Extended Hex Alphabet, as defined " "in :rfc:`4648`." msgstr "" -#: ../../library/base64.rst:157 +#: ../../library/base64.rst:160 msgid "" "This version does not allow the digit 0 (zero) to the letter O (oh) and " "digit 1 (one) to either the letter I (eye) or letter L (el) mappings, all " @@ -263,64 +242,108 @@ msgid "" "interchangeable." msgstr "" -#: ../../library/base64.rst:167 +#: ../../library/base64.rst:170 msgid "" "Encode the :term:`bytes-like object` *s* using Base16 and return the " "encoded :class:`bytes`." msgstr "" -#: ../../library/base64.rst:173 +#: ../../library/base64.rst:176 msgid "" "Decode the Base16 encoded :term:`bytes-like object` or ASCII string *s* and " "return the decoded :class:`bytes`." msgstr "" -#: ../../library/base64.rst:187 +#: ../../library/base64.rst:190 +msgid "Base85 Encodings" +msgstr "" + +#: ../../library/base64.rst:192 +msgid "" +"Base85 encoding is not formally specified but rather a de facto standard, " +"thus different systems perform the encoding differently." +msgstr "" + +#: ../../library/base64.rst:195 +msgid "" +"The :func:`a85encode` and :func:`b85encode` functions in this module are two " +"implementations of the de facto standard. You should call the function with " +"the Base85 implementation used by the software you intend to work with." +msgstr "" + +#: ../../library/base64.rst:199 +msgid "" +"The two functions present in this module differ in how they handle the " +"following:" +msgstr "" + +#: ../../library/base64.rst:201 +msgid "Whether to include enclosing ``<~`` and ``~>`` markers" +msgstr "" + +#: ../../library/base64.rst:202 +msgid "Whether to include newline characters" +msgstr "" + +#: ../../library/base64.rst:203 +msgid "The set of ASCII characters used for encoding" +msgstr "" + +#: ../../library/base64.rst:204 +msgid "Handling of null bytes" +msgstr "" + +#: ../../library/base64.rst:206 +msgid "" +"Refer to the documentation of the individual functions for more information." +msgstr "" + +#: ../../library/base64.rst:210 msgid "" "Encode the :term:`bytes-like object` *b* using Ascii85 and return the " "encoded :class:`bytes`." msgstr "" -#: ../../library/base64.rst:190 +#: ../../library/base64.rst:213 msgid "" "*foldspaces* is an optional flag that uses the special short sequence 'y' " "instead of 4 consecutive spaces (ASCII 0x20) as supported by 'btoa'. This " "feature is not supported by the \"standard\" Ascii85 encoding." msgstr "" -#: ../../library/base64.rst:194 +#: ../../library/base64.rst:217 msgid "" "*wrapcol* controls whether the output should have newline (``b'\\n'``) " "characters added to it. If this is non-zero, each output line will be at " "most this many characters long, excluding the trailing newline." msgstr "" -#: ../../library/base64.rst:198 +#: ../../library/base64.rst:221 msgid "" "*pad* controls whether the input is padded to a multiple of 4 before " "encoding. Note that the ``btoa`` implementation always pads." msgstr "" -#: ../../library/base64.rst:201 +#: ../../library/base64.rst:224 msgid "" "*adobe* controls whether the encoded byte sequence is framed with ``<~`` and " "``~>``, which is used by the Adobe implementation." msgstr "" -#: ../../library/base64.rst:209 +#: ../../library/base64.rst:232 msgid "" "Decode the Ascii85 encoded :term:`bytes-like object` or ASCII string *b* and " "return the decoded :class:`bytes`." msgstr "" -#: ../../library/base64.rst:212 +#: ../../library/base64.rst:235 msgid "" "*foldspaces* is a flag that specifies whether the 'y' short sequence should " "be accepted as shorthand for 4 consecutive spaces (ASCII 0x20). This feature " "is not supported by the \"standard\" Ascii85 encoding." msgstr "" -#: ../../library/base64.rst:216 +#: ../../library/base64.rst:239 msgid "" "*adobe* controls whether the input sequence is in Adobe Ascii85 format (i.e. " "is framed with <~ and ~>)." @@ -328,7 +351,7 @@ msgstr "" "*adobe* controla se a entrada está no formato Adobe Ascii85 (ou seja, " "cercada por <~ e ~>)." -#: ../../library/base64.rst:219 +#: ../../library/base64.rst:242 msgid "" "*ignorechars* should be a :term:`bytes-like object` or ASCII string " "containing characters to ignore from the input. This should only contain " @@ -336,44 +359,44 @@ msgid "" "ASCII." msgstr "" -#: ../../library/base64.rst:229 +#: ../../library/base64.rst:252 msgid "" "Encode the :term:`bytes-like object` *b* using base85 (as used in e.g. git-" "style binary diffs) and return the encoded :class:`bytes`." msgstr "" -#: ../../library/base64.rst:232 +#: ../../library/base64.rst:255 msgid "" "If *pad* is true, the input is padded with ``b'\\0'`` so its length is a " "multiple of 4 bytes before encoding." msgstr "" -#: ../../library/base64.rst:240 +#: ../../library/base64.rst:263 msgid "" "Decode the base85-encoded :term:`bytes-like object` or ASCII string *b* and " "return the decoded :class:`bytes`. Padding is implicitly removed, if " "necessary." msgstr "" -#: ../../library/base64.rst:249 +#: ../../library/base64.rst:272 msgid "" "Encode the :term:`bytes-like object` *s* using Z85 (as used in ZeroMQ) and " "return the encoded :class:`bytes`. See `Z85 specification `_ for more information." msgstr "" -#: ../../library/base64.rst:258 +#: ../../library/base64.rst:281 msgid "" "Decode the Z85-encoded :term:`bytes-like object` or ASCII string *s* and " "return the decoded :class:`bytes`. See `Z85 specification `_ for more information." msgstr "" -#: ../../library/base64.rst:265 -msgid "The legacy interface:" -msgstr "A interface legada:" +#: ../../library/base64.rst:291 +msgid "Legacy Interface" +msgstr "" -#: ../../library/base64.rst:269 +#: ../../library/base64.rst:295 msgid "" "Decode the contents of the binary *input* file and write the resulting " "binary data to the *output* file. *input* and *output* must be :term:`file " @@ -381,13 +404,13 @@ msgid "" "returns an empty bytes object." msgstr "" -#: ../../library/base64.rst:277 +#: ../../library/base64.rst:303 msgid "" "Decode the :term:`bytes-like object` *s*, which must contain one or more " "lines of base64 encoded data, and return the decoded :class:`bytes`." msgstr "" -#: ../../library/base64.rst:285 +#: ../../library/base64.rst:311 msgid "" "Encode the contents of the binary *input* file and write the resulting " "base64 encoded data to the *output* file. *input* and *output* must be :term:" @@ -397,7 +420,7 @@ msgid "" "the output always ends with a newline, as per :rfc:`2045` (MIME)." msgstr "" -#: ../../library/base64.rst:295 +#: ../../library/base64.rst:321 msgid "" "Encode the :term:`bytes-like object` *s*, which can contain arbitrary binary " "data, and return :class:`bytes` containing the base64-encoded data, with " @@ -405,40 +428,40 @@ msgid "" "that there is a trailing newline, as per :rfc:`2045` (MIME)." msgstr "" -#: ../../library/base64.rst:303 +#: ../../library/base64.rst:329 msgid "An example usage of the module:" msgstr "Um exemplo de uso do módulo:" -#: ../../library/base64.rst:316 +#: ../../library/base64.rst:342 msgid "Security Considerations" msgstr "Considerações de Segurança" -#: ../../library/base64.rst:318 +#: ../../library/base64.rst:344 msgid "" "A new security considerations section was added to :rfc:`4648` (section 12); " "it's recommended to review the security section for any code deployed to " "production." msgstr "" -#: ../../library/base64.rst:323 +#: ../../library/base64.rst:349 msgid "Module :mod:`binascii`" msgstr "Módulo :mod:`binascii`" -#: ../../library/base64.rst:324 +#: ../../library/base64.rst:350 msgid "" "Support module containing ASCII-to-binary and binary-to-ASCII conversions." msgstr "" "Módulo de suporte contendo conversões ASCII para binário e binário para " "ASCII." -#: ../../library/base64.rst:326 +#: ../../library/base64.rst:352 msgid "" ":rfc:`1521` - MIME (Multipurpose Internet Mail Extensions) Part One: " "Mechanisms for Specifying and Describing the Format of Internet Message " "Bodies" msgstr "" -#: ../../library/base64.rst:327 +#: ../../library/base64.rst:353 msgid "" "Section 5.2, \"Base64 Content-Transfer-Encoding,\" provides the definition " "of the base64 encoding." diff --git a/library/bdb.po b/library/bdb.po index fe5967215..16c10c643 100644 --- a/library/bdb.po +++ b/library/bdb.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:55+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -41,7 +39,7 @@ msgstr "" #: ../../library/bdb.rst:14 msgid "The following exception is defined:" -msgstr "" +msgstr "A seguinte exceção é definida:" #: ../../library/bdb.rst:18 msgid "Exception raised by the :class:`Bdb` class for quitting the debugger." diff --git a/library/binary.po b/library/binary.po index e0e98befa..d21ff1867 100644 --- a/library/binary.po +++ b/library/binary.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:56+0000\n" -"Last-Translator: Claudio Rogerio Carvalho Filho , " -"2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/binascii.po b/library/binascii.po index 5b90c97a3..50bd1203a 100644 --- a/library/binascii.po +++ b/library/binascii.po @@ -1,34 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Vitor Buxbaum Orlandi, 2024 -# i17obot , 2024 -# Claudio Rogerio Carvalho Filho , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-14 17:56+0000\n" -"PO-Revision-Date: 2021-06-28 00:56+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/binascii.rst:2 msgid ":mod:`!binascii` --- Convert between binary and ASCII" -msgstr "" +msgstr ":mod:`!binascii` --- Converte entre binário e ASCII" #: ../../library/binascii.rst:13 msgid "" @@ -38,6 +35,12 @@ msgid "" "instead. The :mod:`binascii` module contains low-level functions written in " "C for greater speed that are used by the higher-level modules." msgstr "" +"O módulo :mod:`binascii` contém vários métodos para converter entre binário " +"e várias representações binárias codificadas em ASCII. Normalmente, você não " +"usará essas funções diretamente, mas usará módulos invólucros como :mod:" +"`base64` em vez disso. O módulo :mod:`binascii` contém funções de baixo " +"nível escritas em C para maior velocidade que são usadas pelos módulos de " +"nível mais alto." #: ../../library/binascii.rst:22 msgid "" @@ -46,14 +49,20 @@ msgid "" "(such as :class:`bytes`, :class:`bytearray` and other objects that support " "the buffer protocol)." msgstr "" +"Funções ``a2b_*`` aceitam strings Unicode contendo apenas caracteres ASCII. " +"Outras funções aceitam apenas :term:`objetos bytes ou similar ` (como :class:`bytes`, :class:`bytearray` e outros objetos que " +"suportam o protocolo buffer)." #: ../../library/binascii.rst:27 msgid "ASCII-only unicode strings are now accepted by the ``a2b_*`` functions." msgstr "" +"Strings unicode exclusivamente ASCII agora são aceitas pelas funções " +"``a2b_*``." #: ../../library/binascii.rst:31 msgid "The :mod:`binascii` module defines the following functions:" -msgstr "" +msgstr "O módulo :mod:`binascii` define as seguintes funções:" #: ../../library/binascii.rst:36 msgid "" @@ -61,6 +70,9 @@ msgid "" "data. Lines normally contain 45 (binary) bytes, except for the last line. " "Line data may be followed by whitespace." msgstr "" +"Converte uma única linha de dados uuencoded de volta para binário e retorna " +"os dados binários. As linhas normalmente contêm 45 bytes (binários), exceto " +"a última linha. Os dados da linha podem ser seguidos por espaços em branco." #: ../../library/binascii.rst:43 msgid "" @@ -69,6 +81,10 @@ msgid "" "most 45. If *backtick* is true, zeros are represented by ``'`'`` instead of " "spaces." msgstr "" +"Converte dados binários para uma linha de caracteres ASCII, o valor de " +"retorno é a linha convertida, incluindo um caractere de nova linha. O " +"comprimento de *data* deve ser no máximo 45. Se *backtick* for true, zeros " +"são representados por ``'`'`` em vez de espaços." #: ../../library/binascii.rst:47 msgid "Added the *backtick* parameter." @@ -79,16 +95,20 @@ msgid "" "Convert a block of base64 data back to binary and return the binary data. " "More than one line may be passed at a time." msgstr "" +"Converte um bloco de dados base64 de volta para binário e retorna os dados " +"binários. Mais de uma linha pode ser passada por vez." #: ../../library/binascii.rst:56 msgid "" "If *strict_mode* is true, only valid base64 data will be converted. Invalid " "base64 data will raise :exc:`binascii.Error`." msgstr "" +"Se *strict_mode* for true, somente dados base64 válidos serão convertidos. " +"Dados base64 inválidos levantarão :exc:`binascii.Error`." #: ../../library/binascii.rst:59 msgid "Valid base64:" -msgstr "" +msgstr "base64 válido:" #: ../../library/binascii.rst:61 msgid "Conforms to :rfc:`3548`." @@ -96,21 +116,23 @@ msgstr "Em conformidade com :rfc:`3548`." #: ../../library/binascii.rst:62 msgid "Contains only characters from the base64 alphabet." -msgstr "" +msgstr "Contém apenas caracteres do alfabeto base64." #: ../../library/binascii.rst:63 msgid "" "Contains no excess data after padding (including excess padding, newlines, " "etc.)." msgstr "" +"Não contém dados excedentes após o preenchimento (incluindo excesso de " +"preenchimento, novas linhas, etc.)." #: ../../library/binascii.rst:64 msgid "Does not start with a padding." -msgstr "" +msgstr "Não começa com um preenchimento." #: ../../library/binascii.rst:66 msgid "Added the *strict_mode* parameter." -msgstr "" +msgstr "Adicionado o parâmetro *strict_mode*." #: ../../library/binascii.rst:72 msgid "" @@ -118,6 +140,10 @@ msgid "" "return value is the converted line, including a newline char if *newline* is " "true. The output of this function conforms to :rfc:`3548`." msgstr "" +"Converte dados binários para uma linha de caracteres ASCII em codificação " +"base64. O valor de retorno é a linha convertida, incluindo um caractere de " +"nova linha se *newline* for verdadeiro. A saída desta função está em " +"conformidade com :rfc:`3548`." #: ../../library/binascii.rst:76 msgid "Added the *newline* parameter." @@ -160,6 +186,15 @@ msgid "" "algorithm. Use as follows::" msgstr "" +#: ../../library/binascii.rst:116 +msgid "" +"print(binascii.crc32(b\"hello world\"))\n" +"# Or, in two pieces:\n" +"crc = binascii.crc32(b\"hello\")\n" +"crc = binascii.crc32(b\" world\", crc)\n" +"print('crc32 = {:#010x}'.format(crc))" +msgstr "" + #: ../../library/binascii.rst:122 msgid "The result is always unsigned." msgstr "O resultado é sempre sem sinal." diff --git a/library/bisect.po b/library/bisect.po index ade841d2f..f19cf73c5 100644 --- a/library/bisect.po +++ b/library/bisect.po @@ -1,32 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:56+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/bisect.rst:2 msgid ":mod:`!bisect` --- Array bisection algorithm" -msgstr "" +msgstr ":mod:`!bisect` --- Algoritmo de bisseção de vetor" #: ../../library/bisect.rst:10 msgid "**Source code:** :source:`Lib/bisect.py`" @@ -54,6 +53,13 @@ msgid "" "functions only call the :meth:`~object.__lt__` method and will return an " "insertion point between values in an array." msgstr "" +"O módulo é chamado de :mod:`bisect` porque usa um algoritmo básico de " +"bisseção para fazer seu trabalho. Ao contrário de outras ferramentas de " +"bisseção que buscam um valor específico, as funções neste módulo são " +"projetadas para localizar um ponto de inserção. Da mesma forma, as funções " +"nunca chamam um método :meth:`~object.__eq__` para determinar se um valor " +"foi encontrado. Em vez disso, as funções apenas chamam o método :meth:" +"`~object.__lt__` e retornarão um ponto de inserção entre valores em um vetor." #: ../../library/bisect.rst:29 msgid "The following functions are provided:" @@ -143,6 +149,10 @@ msgid "" "insertion point. Next, it runs the :meth:`!insert` method on *a* to insert " "*x* at the appropriate position to maintain sort order." msgstr "" +"Esta função primeiro executa :py:func:`~bisect.bisect_left` para localizar " +"um ponto de inserção. Em seguida, ele executa o método :meth:`!insert` em " +"*a* para inserir *x* na posição apropriada para manter a ordem de " +"classificação." #: ../../library/bisect.rst:79 ../../library/bisect.rst:99 msgid "" @@ -158,6 +168,8 @@ msgid "" "Keep in mind that the *O*\\ (log *n*) search is dominated by the slow *O*\\ " "(*n*) insertion step." msgstr "" +"Tenha em mente que a busca *O*\\ (log *n*) é dominada pelo etapa de inserção " +"lenta O(n)." #: ../../library/bisect.rst:92 msgid "" @@ -173,6 +185,10 @@ msgid "" "insertion point. Next, it runs the :meth:`!insert` method on *a* to insert " "*x* at the appropriate position to maintain sort order." msgstr "" +"Esta função primeiro executa :py:func:`~bisect.bisect_right` para localizar " +"um ponto de inserção. Em seguida, ele executa o método :meth:`!insert` em " +"*a* para inserir *x* na posição apropriada para manter a ordem de " +"classificação." #: ../../library/bisect.rst:110 msgid "Performance Notes" @@ -199,6 +215,8 @@ msgid "" "The *insort()* functions are *O*\\ (*n*) because the logarithmic search step " "is dominated by the linear time insertion step." msgstr "" +"As funções *insort()* são *O*\\ (*n*) porque a etapa de busca logarítmica é " +"dominada pela etapa de inserção de tempo linear." #: ../../library/bisect.rst:121 msgid "" @@ -210,6 +228,14 @@ msgid "" "searching an array of precomputed keys to locate the insertion point (as " "shown in the examples section below)." msgstr "" +"As funções de busca são stateless e descartam os resultados da função chave " +"depois que são usadas. Consequentemente, se as funções de busca forem usadas " +"em um laço, a função chave pode ser chamada repetidamente nos mesmos " +"elementos do vetor. Se a função chave não for rápida, considere envolvê-la " +"com :py:func:`functools.cache` para evitar cálculos duplicados. Como " +"alternativa, considere buscar um vetor de chaves pré-calculadas para " +"localizar o ponto de inserção (conforme mostrado na seção de exemplos " +"abaixo)." #: ../../library/bisect.rst:131 msgid "" @@ -217,6 +243,9 @@ msgid "" "high performance module that uses *bisect* to managed sorted collections of " "data." msgstr "" +"`Sorted Collections `_ é um " +"módulo de alto desempenho que usa bisseção para gerenciar coleções de dados " +"classificadas." #: ../../library/bisect.rst:135 msgid "" @@ -226,10 +255,15 @@ msgid "" "keys are precomputed to save unnecessary calls to the key function during " "searches." msgstr "" +"A `receita de SortedCollection `_ usa bisseção para construir uma classe de coleção " +"completa com métodos de busca diretos e suporte para uma função chave. As " +"chaves são pré-calculadas para economizar em chamadas desnecessárias para a " +"função chave durante as buscas." #: ../../library/bisect.rst:143 msgid "Searching Sorted Lists" -msgstr "Pesquisando em listas ordenadas" +msgstr "Buscando em listas ordenadas" #: ../../library/bisect.rst:145 msgid "" @@ -238,6 +272,82 @@ msgid "" "five functions show how to transform them into the standard lookups for " "sorted lists::" msgstr "" +"As `funções de bisseção`_ acima são úteis para encontrar pontos de inserção, " +"mas podem ser complicadas ou difíceis de usar para tarefas comuns de busca. " +"As cinco funções a seguir mostram como transformá-las nas buscas padrão para " +"listas ordenadas::" + +#: ../../library/bisect.rst:150 +msgid "" +"def index(a, x):\n" +" 'Locate the leftmost value exactly equal to x'\n" +" i = bisect_left(a, x)\n" +" if i != len(a) and a[i] == x:\n" +" return i\n" +" raise ValueError\n" +"\n" +"def find_lt(a, x):\n" +" 'Find rightmost value less than x'\n" +" i = bisect_left(a, x)\n" +" if i:\n" +" return a[i-1]\n" +" raise ValueError\n" +"\n" +"def find_le(a, x):\n" +" 'Find rightmost value less than or equal to x'\n" +" i = bisect_right(a, x)\n" +" if i:\n" +" return a[i-1]\n" +" raise ValueError\n" +"\n" +"def find_gt(a, x):\n" +" 'Find leftmost value greater than x'\n" +" i = bisect_right(a, x)\n" +" if i != len(a):\n" +" return a[i]\n" +" raise ValueError\n" +"\n" +"def find_ge(a, x):\n" +" 'Find leftmost item greater than or equal to x'\n" +" i = bisect_left(a, x)\n" +" if i != len(a):\n" +" return a[i]\n" +" raise ValueError" +msgstr "" +"def index(a, x):\n" +" 'Encontra o valor mais à esquerda exatamente igual a x'\n" +" i = bisect_left(a, x)\n" +" if i != len(a) and a[i] == x:\n" +" return i\n" +" raise ValueError\n" +"\n" +"def find_lt(a, x):\n" +" 'Encontra o valor mais à direita menor que x'\n" +" i = bisect_left(a, x)\n" +" if i:\n" +" return a[i-1]\n" +" raise ValueError\n" +"\n" +"def find_le(a, x):\n" +" 'Encontra o valor mais à direita menor ou igual a x'\n" +" i = bisect_right(a, x)\n" +" if i:\n" +" return a[i-1]\n" +" raise ValueError\n" +"\n" +"def find_gt(a, x):\n" +" 'Encontra o valor mais à esquerda maior que x'\n" +" i = bisect_right(a, x)\n" +" if i != len(a):\n" +" return a[i]\n" +" raise ValueError\n" +"\n" +"def find_ge(a, x):\n" +" 'Encontra o item mais à esquerda maior ou igual a x'\n" +" i = bisect_left(a, x)\n" +" if i != len(a):\n" +" return a[i]\n" +" raise ValueError" #: ../../library/bisect.rst:187 msgid "Examples" @@ -250,6 +360,27 @@ msgid "" "grade for an exam score (say) based on a set of ordered numeric breakpoints: " "90 and up is an 'A', 80 to 89 is a 'B', and so on::" msgstr "" +"A função :py:func:`~bisect.bisect` pode ser útil para buscas em tabelas " +"numéricas. Este exemplo usa :py:func:`~bisect.bisect` para buscar uma nota " +"em letra para uma pontuação de exame (digamos) com base em um conjunto de " +"pontos de interrupção numéricos ordenados: 90 e acima é um \"A\", 80 a 89 é " +"um \"B\" e por aí vai::" + +#: ../../library/bisect.rst:196 +msgid "" +">>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):\n" +"... i = bisect(breakpoints, score)\n" +"... return grades[i]\n" +"...\n" +">>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]\n" +"['F', 'A', 'C', 'C', 'B', 'A', 'A']" +msgstr "" +">>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):\n" +"... i = bisect(breakpoints, score)\n" +"... return grades[i]\n" +"...\n" +">>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]\n" +"['F', 'A', 'C', 'C', 'B', 'A', 'A']" #: ../../library/bisect.rst:203 msgid "" @@ -257,9 +388,103 @@ msgid "" "work with lists of tuples. The *key* argument can serve to extract the " "field used for ordering records in a table::" msgstr "" +"As funções :py:func:`~bisect.bisect` e :py:func:`~bisect.insort` também " +"funcionam com listas de tuplas. O argumento *key* pode servir para extrair o " +"campo usado para ordenar registros em uma tabela::" + +#: ../../library/bisect.rst:207 +msgid "" +">>> from collections import namedtuple\n" +">>> from operator import attrgetter\n" +">>> from bisect import bisect, insort\n" +">>> from pprint import pprint\n" +"\n" +">>> Movie = namedtuple('Movie', ('name', 'released', 'director'))\n" +"\n" +">>> movies = [\n" +"... Movie('Jaws', 1975, 'Spielberg'),\n" +"... Movie('Titanic', 1997, 'Cameron'),\n" +"... Movie('The Birds', 1963, 'Hitchcock'),\n" +"... Movie('Aliens', 1986, 'Cameron')\n" +"... ]\n" +"\n" +">>> # Find the first movie released after 1960\n" +">>> by_year = attrgetter('released')\n" +">>> movies.sort(key=by_year)\n" +">>> movies[bisect(movies, 1960, key=by_year)]\n" +"Movie(name='The Birds', released=1963, director='Hitchcock')\n" +"\n" +">>> # Insert a movie while maintaining sort order\n" +">>> romance = Movie('Love Story', 1970, 'Hiller')\n" +">>> insort(movies, romance, key=by_year)\n" +">>> pprint(movies)\n" +"[Movie(name='The Birds', released=1963, director='Hitchcock'),\n" +" Movie(name='Love Story', released=1970, director='Hiller'),\n" +" Movie(name='Jaws', released=1975, director='Spielberg'),\n" +" Movie(name='Aliens', released=1986, director='Cameron'),\n" +" Movie(name='Titanic', released=1997, director='Cameron')]" +msgstr "" +">>> from collections import namedtuple\n" +">>> from operator import attrgetter\n" +">>> from bisect import bisect, insort\n" +">>> from pprint import pprint\n" +"\n" +">>> Movie = namedtuple('Movie', ('name', 'released', 'director'))\n" +"\n" +">>> movies = [\n" +"... Movie('Jaws', 1975, 'Spielberg'),\n" +"... Movie('Titanic', 1997, 'Cameron'),\n" +"... Movie('The Birds', 1963, 'Hitchcock'),\n" +"... Movie('Aliens', 1986, 'Cameron')\n" +"... ]\n" +"\n" +">>> # Encontra o primeiro filme lançado após 1960\n" +">>> by_year = attrgetter('released')\n" +">>> movies.sort(key=by_year)\n" +">>> movies[bisect(movies, 1960, key=by_year)]\n" +"Movie(name='The Birds', released=1963, director='Hitchcock')\n" +"\n" +">>> # Insere um filme enquanto mantém a ordem de classificação\n" +">>> romance = Movie('Love Story', 1970, 'Hiller')\n" +">>> insort(movies, romance, key=by_year)\n" +">>> pprint(movies)\n" +"[Movie(name='The Birds', released=1963, director='Hitchcock'),\n" +" Movie(name='Love Story', released=1970, director='Hiller'),\n" +" Movie(name='Jaws', released=1975, director='Spielberg'),\n" +" Movie(name='Aliens', released=1986, director='Cameron'),\n" +" Movie(name='Titanic', released=1997, director='Cameron')]" #: ../../library/bisect.rst:237 msgid "" "If the key function is expensive, it is possible to avoid repeated function " "calls by searching a list of precomputed keys to find the index of a record::" msgstr "" +"Se a função chave for custosa, é possível evitar chamadas de função " +"repetidas buscando uma lista de chaves pré-calculadas para encontrar o " +"índice de um registro::" + +#: ../../library/bisect.rst:240 +msgid "" +">>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]\n" +">>> data.sort(key=lambda r: r[1]) # Or use operator.itemgetter(1).\n" +">>> keys = [r[1] for r in data] # Precompute a list of keys.\n" +">>> data[bisect_left(keys, 0)]\n" +"('black', 0)\n" +">>> data[bisect_left(keys, 1)]\n" +"('blue', 1)\n" +">>> data[bisect_left(keys, 5)]\n" +"('red', 5)\n" +">>> data[bisect_left(keys, 8)]\n" +"('yellow', 8)" +msgstr "" +">>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]\n" +">>> data.sort(key=lambda r: r[1]) # Ou use operator.itemgetter(1).\n" +">>> keys = [r[1] for r in data] # Pré-calcula uma lista de chaves.\n" +">>> data[bisect_left(keys, 0)]\n" +"('black', 0)\n" +">>> data[bisect_left(keys, 1)]\n" +"('blue', 1)\n" +">>> data[bisect_left(keys, 5)]\n" +"('red', 5)\n" +">>> data[bisect_left(keys, 8)]\n" +"('yellow', 8)" diff --git a/library/builtins.po b/library/builtins.po index 086547320..2e4e1cd1d 100644 --- a/library/builtins.po +++ b/library/builtins.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:56+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -31,15 +31,13 @@ msgstr ":mod:`!builtins` --- Objetos embutidos" msgid "" "This module provides direct access to all 'built-in' identifiers of Python; " "for example, ``builtins.open`` is the full name for the built-in function :" -"func:`open`. See :ref:`built-in-funcs` and :ref:`built-in-consts` for " -"documentation." +"func:`open`." msgstr "" "Este módulo fornece acesso direto a todos os identificadores embutidos do " "Python; Por exemplo, ``builtins.open`` é o nome completo para a função " -"embutida :func:`open`. Veja :ref:`built-in-funcs` e :ref:`built-in-consts` " -"para documentação." +"embutida :func:`open`." -#: ../../library/builtins.rst:15 +#: ../../library/builtins.rst:12 msgid "" "This module is not normally accessed explicitly by most applications, but " "can be useful in modules that provide objects with the same name as a built-" @@ -54,7 +52,44 @@ msgstr "" "func:`open` que envolve o embutido :func:`open`, este módulo pode ser usado " "diretamente::" -#: ../../library/builtins.rst:38 +#: ../../library/builtins.rst:18 +msgid "" +"import builtins\n" +"\n" +"def open(path):\n" +" f = builtins.open(path, 'r')\n" +" return UpperCaser(f)\n" +"\n" +"class UpperCaser:\n" +" '''Wrapper around a file that converts output to uppercase.'''\n" +"\n" +" def __init__(self, f):\n" +" self._f = f\n" +"\n" +" def read(self, count=-1):\n" +" return self._f.read(count).upper()\n" +"\n" +" # ..." +msgstr "" +"import builtins\n" +"\n" +"def open(path):\n" +" f = builtins.open(path, 'r')\n" +" return UpperCaser(f)\n" +"\n" +"class UpperCaser:\n" +" '''Envoltório em volta de um arquivo que converte saída para " +"maiúsculo.'''\n" +"\n" +" def __init__(self, f):\n" +" self._f = f\n" +"\n" +" def read(self, count=-1):\n" +" return self._f.read(count).upper()\n" +"\n" +" # ..." + +#: ../../library/builtins.rst:35 msgid "" "As an implementation detail, most modules have the name ``__builtins__`` " "made available as part of their globals. The value of ``__builtins__`` is " @@ -67,3 +102,19 @@ msgstr "" "``__builtins__`` normalmente, este é o módulo ou o valor desse módulo :attr:" "`~object.__dict__` atributo. Uma vez que este é um detalhe de implementação, " "ele não pode ser usado por implementações alternativas do Python." + +#: ../../library/builtins.rst:43 +msgid ":ref:`built-in-consts`" +msgstr ":ref:`built-in-consts`" + +#: ../../library/builtins.rst:44 +msgid ":ref:`bltin-exceptions`" +msgstr ":ref:`bltin-exceptions`" + +#: ../../library/builtins.rst:45 +msgid ":ref:`built-in-funcs`" +msgstr ":ref:`built-in-funcs`" + +#: ../../library/builtins.rst:46 +msgid ":ref:`bltin-types`" +msgstr ":ref:`bltin-types`" diff --git a/library/bz2.po b/library/bz2.po index 0573f1143..af9af84f1 100644 --- a/library/bz2.po +++ b/library/bz2.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:56+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -224,9 +223,9 @@ msgid "" "*filename*)." msgstr "" "Enquanto chamar :meth:`peek` não altera a posição do arquivo de :class:" -"`BZ2File`, pode alterar a posição do objeto de arquivo subjacente (por " -"exemplo, se o :class:`BZ2File` foi construído passando um objeto de arquivo " -"para *filename*)." +"`BZ2File`, pode alterar a posição do objeto arquivo subjacente (por exemplo, " +"se o :class:`BZ2File` foi construído passando um objeto arquivo para " +"*filename*)." #: ../../library/bz2.rst:111 msgid "Return the file descriptor for the underlying file." @@ -410,8 +409,8 @@ msgid "" "to :meth:`decompress`. The returned data should be concatenated with the " "output of any previous calls to :meth:`decompress`." msgstr "" -"Descompacta dados *data* (um :term:`objeto bytes ou similar `), retornando dados não compactados como bytes. Alguns dos *data* " +"Descomprime dados *data* (um :term:`objeto bytes ou similar `), retornando dados não comprimidos como bytes. Alguns dos *data* " "podem ser armazenados em buffer internamente, para uso em chamadas " "posteriores para :meth:`decompress`. Os dados retornados devem ser " "concatenados com a saída de qualquer chamada anterior para :meth:" @@ -426,7 +425,7 @@ msgid "" "``b''`` to obtain more of the output." msgstr "" "Se *max_length* for não negativo, retornará no máximo *max_length* bytes de " -"dados descompactados. Se este limite for atingido e mais saída puder ser " +"dados descomprimidos. Se este limite for atingido e mais saída puder ser " "produzida, o atributo :attr:`~.needs_input` será definido como ``False``. " "Neste caso, a próxima chamada para :meth:`~.decompress` pode fornecer *data* " "como ``b''`` para obter mais saída." @@ -437,7 +436,7 @@ msgid "" "was less than *max_length* bytes, or because *max_length* was negative), " "the :attr:`~.needs_input` attribute will be set to ``True``." msgstr "" -"Se todos os dados de entrada foram descompactados e retornados (seja porque " +"Se todos os dados de entrada foram descomprimidos e retornados (seja porque " "era menor que *max_length* bytes, ou porque *max_length* era negativo), o " "atributo :attr:`~.needs_input` será definido como ``True`` ." @@ -447,7 +446,7 @@ msgid "" "exc:`EOFError`. Any data found after the end of the stream is ignored and " "saved in the :attr:`~.unused_data` attribute." msgstr "" -"A tentativa de descompactar os dados após o final do fluxo ser atingido gera " +"A tentativa de descomprimir os dados após o final do fluxo ser atingido gera " "um :exc:`EOFError`. Quaisquer dados encontrados após o final do fluxo são " "ignorados e salvos no atributo :attr:`~.unused_data`." @@ -461,7 +460,7 @@ msgstr "``True`` se o marcador de fim de fluxo foi atingido." #: ../../library/bz2.rst:275 msgid "Data found after the end of the compressed stream." -msgstr "Dados encontrados após o término do fluxo compactado." +msgstr "Dados encontrados após o término do fluxo comprimido." #: ../../library/bz2.rst:277 msgid "" @@ -477,7 +476,7 @@ msgid "" "data before requiring new uncompressed input." msgstr "" "``False`` se o método :meth:`.decompress` puder fornecer mais dados " -"descompactados antes de exigir uma nova entrada descompactada." +"descomprimidos antes de exigir uma nova entrada não comprimida." #: ../../library/bz2.rst:289 msgid "One-shot (de)compression" @@ -485,8 +484,7 @@ msgstr "(De)compressão de uma só vez (one-shot)" #: ../../library/bz2.rst:293 msgid "Compress *data*, a :term:`bytes-like object `." -msgstr "" -"Compacta *data*, um :term:`objeto bytes ou similar `." +msgstr "Compacta *data*, um :term:`objeto bytes ou similar`." #: ../../library/bz2.rst:298 msgid "For incremental compression, use a :class:`BZ2Compressor` instead." @@ -494,8 +492,7 @@ msgstr "Para compressão incremental, use um :class:`BZ2Compressor`." #: ../../library/bz2.rst:303 msgid "Decompress *data*, a :term:`bytes-like object `." -msgstr "" -"Descompacta *data*, um :term:`objeto bytes ou similar `." +msgstr "Descompacta *data*, um :term:`objeto bytes ou similar`." #: ../../library/bz2.rst:305 msgid "" diff --git a/library/calendar.po b/library/calendar.po index 686997e8a..bd0d6808a 100644 --- a/library/calendar.po +++ b/library/calendar.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# i17obot , 2023 -# Daniel Moura, 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 00:56+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-10 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -47,8 +44,8 @@ msgstr "" "Este módulo permite que você exiba calendários como o programa Unix :program:" "`cal`, e fornece funções adicionais úteis relacionadas ao calendário. Por " "padrão, esses calendários têm a segunda-feira como o primeiro dia da semana, " -"e Domingo como o último (a convenção Europeia). Use :func:`setfirstweekday` " -"para colocar o primeiro dia da semana como Domingo (6) ou para qualquer " +"e domingo como o último (a convenção europeia). Use :func:`setfirstweekday` " +"para colocar o primeiro dia da semana como domingo (6) ou para qualquer " "outro dia da semana. Parâmetros que especificam datas são dados como " "inteiros. Para funcionalidade relacionada, veja também os módulos :mod:" "`datetime` e :mod:`time`." @@ -92,20 +89,51 @@ msgstr "" "nenhuma formatação por si mesma. Esse é o trabalho das subclasses." #: ../../library/calendar.rst:41 -msgid ":class:`Calendar` instances have the following methods:" -msgstr "Instâncias de :class:`Calendar` possuem os seguintes métodos:" +msgid ":class:`Calendar` instances have the following methods and attributes:" +msgstr "Instâncias de :class:`Calendar` têm os seguintes métodos e atributos:" #: ../../library/calendar.rst:45 +msgid "The first weekday as an integer (0--6)." +msgstr "O primeiro dia da semana como um inteiro (0--6)." + +#: ../../library/calendar.rst:47 +msgid "" +"This property can also be set and read using :meth:`~Calendar." +"setfirstweekday` and :meth:`~Calendar.getfirstweekday` respectively." +msgstr "" +"Esta propriedade também pode ser definida e lida usando :meth:`~Calendar." +"setfirstweekday` e :meth:`~Calendar.getfirstweekday` respectivamente." + +#: ../../library/calendar.rst:53 +msgid "Return an :class:`int` for the current first weekday (0--6)." +msgstr "Retorna um :class:`int` para o primeiro dia da semana atual (0-6)." + +#: ../../library/calendar.rst:55 +msgid "Identical to reading the :attr:`~Calendar.firstweekday` property." +msgstr "Idêntico à leitura da propriedade :attr:`~Calendar.firstweekday`." + +#: ../../library/calendar.rst:59 +msgid "" +"Set the first weekday to *firstweekday*, passed as an :class:`int` (0--6)" +msgstr "" +"Define o primeiro dia da semana como *firstweekday*, passado como :class:" +"`int` (0--6)" + +#: ../../library/calendar.rst:61 +msgid "Identical to setting the :attr:`~Calendar.firstweekday` property." +msgstr "Idêntico à definição da propriedade :attr:`~Calendar.firstweekday`." + +#: ../../library/calendar.rst:65 msgid "" "Return an iterator for the week day numbers that will be used for one week. " "The first value from the iterator will be the same as the value of the :attr:" -"`firstweekday` property." +"`~Calendar.firstweekday` property." msgstr "" "Retorna um iterador para os números dos dias da semana que serão usados em " "uma semana. O primeiro valor do iterador será o mesmo que o valor da " -"propriedade :attr:`firstweekday`." +"propriedade :attr:`~Calendar.firstweekday`." -#: ../../library/calendar.rst:52 +#: ../../library/calendar.rst:72 msgid "" "Return an iterator for the month *month* (1--12) in the year *year*. This " "iterator will return all days (as :class:`datetime.date` objects) for the " @@ -117,7 +145,7 @@ msgstr "" "todos os dias antes do início do mês ou após o final do mês que são " "necessários para obter uma semana completa." -#: ../../library/calendar.rst:60 +#: ../../library/calendar.rst:80 msgid "" "Return an iterator for the month *month* in the year *year* similar to :meth:" "`itermonthdates`, but not restricted by the :class:`datetime.date` range. " @@ -129,19 +157,19 @@ msgstr "" "Os dias retornados serão simplesmente os números dos dias do mês. Para os " "dias fora do mês especificado, o número do dia será ``0``." -#: ../../library/calendar.rst:68 +#: ../../library/calendar.rst:88 msgid "" "Return an iterator for the month *month* in the year *year* similar to :meth:" "`itermonthdates`, but not restricted by the :class:`datetime.date` range. " "Days returned will be tuples consisting of a day of the month number and a " "week day number." msgstr "" -"Retorna um iterador para o mês *month* no ano year semelhante a :meth:" +"Retorna um iterador para o mês *month* no ano *year* semelhante a :meth:" "`itermonthdates`, mas não restrito pelo intervalo de :class:`datetime.date`. " "Os dias retornados serão tuplas consistindo de um número de dia do mês e um " "número de dia da semana." -#: ../../library/calendar.rst:76 +#: ../../library/calendar.rst:96 msgid "" "Return an iterator for the month *month* in the year *year* similar to :meth:" "`itermonthdates`, but not restricted by the :class:`datetime.date` range. " @@ -153,7 +181,7 @@ msgstr "" "Os dias retornados serão tuplas consistindo de números de um ano, um mês e " "um dia do mês." -#: ../../library/calendar.rst:86 +#: ../../library/calendar.rst:106 msgid "" "Return an iterator for the month *month* in the year *year* similar to :meth:" "`itermonthdates`, but not restricted by the :class:`datetime.date` range. " @@ -165,7 +193,7 @@ msgstr "" "Os dias retornados serão tuplas consistindo de números de um ano, um mês, um " "dia do mês e um dia da semana." -#: ../../library/calendar.rst:96 +#: ../../library/calendar.rst:116 msgid "" "Return a list of the weeks in the month *month* of the *year* as full " "weeks. Weeks are lists of seven :class:`datetime.date` objects." @@ -173,24 +201,24 @@ msgstr "" "Retorna uma lista das semanas do mês *month* do *year* como semanas " "completas. As semanas são listas de sete objetos :class:`datetime.date`." -#: ../../library/calendar.rst:102 +#: ../../library/calendar.rst:122 msgid "" "Return a list of the weeks in the month *month* of the *year* as full " "weeks. Weeks are lists of seven tuples of day numbers and weekday numbers." msgstr "" -"Retorna uma lista das semanas do mês *month* do *year* como semanas " +"Retorna uma lista das semanas do mês *month* do ano *year* como semanas " "completas. As semanas são listas de sete tuplas de números dias e de dias de " "semanas." -#: ../../library/calendar.rst:109 +#: ../../library/calendar.rst:129 msgid "" "Return a list of the weeks in the month *month* of the *year* as full " "weeks. Weeks are lists of seven day numbers." msgstr "" -"Retorna uma lista das semanas do mês *month* do *year* como semanas " -"completas. As semanas são listas de números de 7 dias." +"Retorna uma lista das semanas do mês *month* do ano *year* como semanas " +"completas. As semanas são listas de números de sete dias." -#: ../../library/calendar.rst:115 +#: ../../library/calendar.rst:135 msgid "" "Return the data for the specified year ready for formatting. The return " "value is a list of month rows. Each month row contains up to *width* months " @@ -202,29 +230,80 @@ msgstr "" "meses (padrão é 3). Cada mês contém entre 4 e 6 semanas, e cada semana " "contém 1--7 dias. Os dias são objetos :class:`datetime.date`." -#: ../../library/calendar.rst:123 +#: ../../library/calendar.rst:143 msgid "" "Return the data for the specified year ready for formatting (similar to :" "meth:`yeardatescalendar`). Entries in the week lists are tuples of day " "numbers and weekday numbers. Day numbers outside this month are zero." msgstr "" +"Retorna os dados para o ano especificado prontos para formatação (semelhante " +"a :meth:`yeardatescalendar`). Entradas nas listas semanais são tuplas de " +"números de dias e números de dias de semana. Números de dias fora deste mês " +"são zero." -#: ../../library/calendar.rst:130 +#: ../../library/calendar.rst:150 msgid "" "Return the data for the specified year ready for formatting (similar to :" "meth:`yeardatescalendar`). Entries in the week lists are day numbers. Day " "numbers outside this month are zero." msgstr "" +"Retorna a data para o ano especificado prontos para formatação (semelhante " +"a :meth:`yeardatescalendar`). Entradas nas listas de semanas são números de " +"dias. Números de dias fora deste mês são zero." -#: ../../library/calendar.rst:137 +#: ../../library/calendar.rst:157 msgid "This class can be used to generate plain text calendars." -msgstr "" +msgstr "Esta classe pode ser usada para gerar texto plano para calendários." -#: ../../library/calendar.rst:139 +#: ../../library/calendar.rst:159 msgid ":class:`TextCalendar` instances have the following methods:" +msgstr "Instâncias de :class:`TextCalendar` têm os seguintes métodos:" + +#: ../../library/calendar.rst:164 +msgid "" +"Return a string representing a single day formatted with the given *width*. " +"If *theday* is ``0``, return a string of spaces of the specified width, " +"representing an empty day. The *weekday* parameter is unused." msgstr "" +"Retorna uma string representando um único dia formatado com a largura " +"fornecida em *width*. Se *theday* for ``0``, retorna uma string de espaços " +"da largura especificada, representando um dia vazio. O parâmetro *weekday* " +"não é usado." -#: ../../library/calendar.rst:143 +#: ../../library/calendar.rst:171 +msgid "" +"Return a single week in a string with no newline. If *w* is provided, it " +"specifies the width of the date columns, which are centered. Depends on the " +"first weekday as specified in the constructor or set by the :meth:" +"`setfirstweekday` method." +msgstr "" +"Retorna uma única semana em uma string sem nova linha. Se *w* for " +"providenciado, isto especifica a largura das colunas de data, que são " +"centrais. Dependendo do primeiro dia da semana conforme especificado no " +"construtor ou configurado pelo método :meth:`setfirstweekday`." + +#: ../../library/calendar.rst:178 +msgid "" +"Return a string representing the name of a single weekday formatted to the " +"specified *width*. The *weekday* parameter is an integer representing the " +"day of the week, where ``0`` is Monday and ``6`` is Sunday." +msgstr "" +"Retorna uma string representando o nome de um único dia da semana formatado " +"para a largura especificada em *width*. O parâmetro *weekday* é um inteiro " +"representando o dia da semana, onde ``0`` é segunda-feira e ``6`` é domingo." + +#: ../../library/calendar.rst:184 +msgid "" +"Return a string containing the header row of weekday names, formatted with " +"the given *width* for each column. The names depend on the locale settings " +"and are padded to the specified width." +msgstr "" +"Retorna uma string contendo a linha de cabeçalho dos nomes dos dias da " +"semana, formatada com a largura fornecida por *width* para cada coluna. Os " +"nomes dependem das configurações de localidade e são preenchidos até a " +"largura especificada." + +#: ../../library/calendar.rst:190 msgid "" "Return a month's calendar in a multi-line string. If *w* is provided, it " "specifies the width of the date columns, which are centered. If *l* is " @@ -232,12 +311,30 @@ msgid "" "the first weekday as specified in the constructor or set by the :meth:" "`setfirstweekday` method." msgstr "" +"Retorna o calendário do mês em uma string multilinha. Se *w* for " +"providenciado, isto especifica a largura das colunas de data, que são " +"centrais. Se *l* for dado, este especifica o número de linhas que cada " +"semana vai usar. Dependendo do primeiro dia da semana conforme especificado " +"no construtor ou configurado pelo método :meth:`setfirstweekday`." -#: ../../library/calendar.rst:152 +#: ../../library/calendar.rst:198 +msgid "" +"Return a string representing the month's name centered within the specified " +"*width*. If *withyear* is ``True``, include the year in the output. The " +"*theyear* and *themonth* parameters specify the year and month for the name " +"to be formatted respectively." +msgstr "" +"Retorna uma string representando o nome do mês centralizado dentro da " +"largura especificada em *width*. Se *withyear* for ``True``, inclui o ano na " +"saída. Os parâmetros *theyear* e *themonth* especificam o ano e o mês para o " +"nome a ser formatado, respectivamente." + +#: ../../library/calendar.rst:205 msgid "Print a month's calendar as returned by :meth:`formatmonth`." msgstr "" +"Imprime um calendário do mês conforme retornado pelo :meth:`formatmonth`." -#: ../../library/calendar.rst:157 +#: ../../library/calendar.rst:210 msgid "" "Return a *m*-column calendar for an entire year as a multi-line string. " "Optional parameters *w*, *l*, and *c* are for date column width, lines per " @@ -246,33 +343,47 @@ msgid "" "`setfirstweekday` method. The earliest year for which a calendar can be " "generated is platform-dependent." msgstr "" +"Retorna um calendário com *m* colunas para um ano inteiro conforme uma " +"string multilinha. Parâmetros opcionais *w*, *l* e *c* definem a largura da " +"coluna data, linhas por semana e números de espaços entre as colunas dos " +"meses, respectivamente. Depende do primeiro dia da semana conforme " +"especificado no construtor ou definido pelo método :meth:`setfirstweekday`. " +"O ano mais novo para o qual o calendário pode ser gerado depende da " +"plataforma." -#: ../../library/calendar.rst:167 +#: ../../library/calendar.rst:220 msgid "" "Print the calendar for an entire year as returned by :meth:`formatyear`." msgstr "" +"Imprime o calendário para um ano inteiro conforme retornado por :meth:" +"`formatyear`." -#: ../../library/calendar.rst:172 +#: ../../library/calendar.rst:225 msgid "This class can be used to generate HTML calendars." -msgstr "" +msgstr "Esta classse pode ser usada para gerar calendários HTML." -#: ../../library/calendar.rst:175 +#: ../../library/calendar.rst:228 msgid ":class:`!HTMLCalendar` instances have the following methods:" -msgstr "" +msgstr "Instâncias de :class:`!HTMLCalendar` têm os seguintes métodos:" -#: ../../library/calendar.rst:179 +#: ../../library/calendar.rst:232 msgid "" "Return a month's calendar as an HTML table. If *withyear* is true the year " "will be included in the header, otherwise just the month name will be used." msgstr "" +"Retorna um calendário do mês como uma tabela HTML. Se *withyear* for " +"verdadeiro, o ano será incluído no cabeçalho, senão apenas o nome do mês " +"será utilizado." -#: ../../library/calendar.rst:186 +#: ../../library/calendar.rst:239 msgid "" "Return a year's calendar as an HTML table. *width* (defaulting to 3) " "specifies the number of months per row." msgstr "" +"Retorna um calendário do ano como uma tabela HTML. *width* (padronizada para " +"3) especifica o número de meses por linha." -#: ../../library/calendar.rst:192 +#: ../../library/calendar.rst:245 msgid "" "Return a year's calendar as a complete HTML page. *width* (defaulting to 3) " "specifies the number of months per row. *css* is the name for the cascading " @@ -280,176 +391,284 @@ msgid "" "be used. *encoding* specifies the encoding to be used for the output " "(defaulting to the system default encoding)." msgstr "" +"Retorna o calendário de um ano como uma página HTML completa. *width* " +"(padrão 3) especifica o número de meses por linha. *css* é o nome da folha " +"de estilo em cascata a ser usada. :const:`None` pode ser passado se nenhuma " +"folha de estilo deve ser usada. *encoding* especifica a codificação a ser " +"usada para a saída (padrão para a codificação padrão do sistema)." -#: ../../library/calendar.rst:201 +#: ../../library/calendar.rst:254 msgid "" "Return a month name as an HTML table row. If *withyear* is true the year " "will be included in the row, otherwise just the month name will be used." msgstr "" +"Retorna um nome de mês como uma linha de tabela HTML. Se *withyear* for " +"verdadeiro, o ano será incluído na linha, senão apenas o nome do mês será " +"utilizado." -#: ../../library/calendar.rst:206 +#: ../../library/calendar.rst:259 msgid "" ":class:`!HTMLCalendar` has the following attributes you can override to " "customize the CSS classes used by the calendar:" msgstr "" +":class:`!HTMLCalendar` tem os seguintes atributos que você pode substituir " +"para personalizar as classes CSS usadas pelo calendário:" -#: ../../library/calendar.rst:211 +#: ../../library/calendar.rst:264 msgid "" "A list of CSS classes used for each weekday. The default class list is::" msgstr "" +"Uma lista de classes CSS usadas para cada dia da semana. A lista de classes " +"padrão é::" + +#: ../../library/calendar.rst:266 +msgid "" +"cssclasses = [\"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\", \"sun\"]" +msgstr "" +"cssclasses = [\"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\", \"sun\"]" -#: ../../library/calendar.rst:215 +#: ../../library/calendar.rst:268 msgid "more styles can be added for each day::" +msgstr "mais estilos podem ser adicionados para cada dia::" + +#: ../../library/calendar.rst:270 +msgid "" +"cssclasses = [\"mon text-bold\", \"tue\", \"wed\", \"thu\", \"fri\", " +"\"sat\", \"sun red\"]" msgstr "" +"cssclasses = [\"mon text-bold\", \"tue\", \"wed\", \"thu\", \"fri\", " +"\"sat\", \"sun red\"]" -#: ../../library/calendar.rst:219 +#: ../../library/calendar.rst:272 msgid "Note that the length of this list must be seven items." -msgstr "" +msgstr "Observe que o comprimento desta lista deve ser de sete itens." -#: ../../library/calendar.rst:224 +#: ../../library/calendar.rst:277 msgid "The CSS class for a weekday occurring in the previous or coming month." msgstr "" +"A classe CSS para um dia da semana que ocorre no mês anterior ou seguinte." -#: ../../library/calendar.rst:231 +#: ../../library/calendar.rst:284 msgid "" "A list of CSS classes used for weekday names in the header row. The default " "is the same as :attr:`cssclasses`." msgstr "" +"Uma lista de classes CSS usadas para nomes de dias da semana na linha de " +"cabeçalho. O padrão é o mesmo que :attr:`cssclasses`." -#: ../../library/calendar.rst:239 +#: ../../library/calendar.rst:292 msgid "" "The month's head CSS class (used by :meth:`formatmonthname`). The default " "value is ``\"month\"``." msgstr "" +"A classe CSS principal do mês (usada por :meth:`formatmonthname`). O valor " +"padrão é ``\"month\"``." -#: ../../library/calendar.rst:247 +#: ../../library/calendar.rst:300 msgid "" "The CSS class for the whole month's table (used by :meth:`formatmonth`). The " "default value is ``\"month\"``." msgstr "" +"A classe CSS para a tabela do mês inteiro (usada por :meth:`formatmonth`). O " +"valor padrão é ``\"month\"``." -#: ../../library/calendar.rst:255 +#: ../../library/calendar.rst:308 msgid "" "The CSS class for the whole year's table of tables (used by :meth:" "`formatyear`). The default value is ``\"year\"``." msgstr "" +"A classe CSS para a tabela de tabelas do ano inteiro (usada por :meth:" +"`formatyear`). O valor padrão é ``\"year\"``." -#: ../../library/calendar.rst:263 +#: ../../library/calendar.rst:316 msgid "" "The CSS class for the table head for the whole year (used by :meth:" "`formatyear`). The default value is ``\"year\"``." msgstr "" +"A classe CSS para o cabeçalho da tabela para o ano inteiro (usado por :meth:" +"`formatyear`). O valor padrão é ``\"year\"``." -#: ../../library/calendar.rst:269 +#: ../../library/calendar.rst:322 msgid "" "Note that although the naming for the above described class attributes is " "singular (e.g. ``cssclass_month`` ``cssclass_noday``), one can replace the " "single CSS class with a space separated list of CSS classes, for example::" msgstr "" +"Observe que, embora a nomenclatura dos atributos de classe descritos acima " +"seja singular (por exemplo, ``cssclass_month`` ``cssclass_noday``), é " +"possível substituir a única classe CSS por uma lista de classes CSS " +"separadas por espaços, por exemplo:" + +#: ../../library/calendar.rst:326 +msgid "\"text-bold text-red\"" +msgstr "\"text-bold text-red\"" -#: ../../library/calendar.rst:275 +#: ../../library/calendar.rst:328 msgid "Here is an example how :class:`!HTMLCalendar` can be customized::" msgstr "" +"Aqui está um exemplo de como :class:`!HTMLCalendar` pode ser personalizado::" -#: ../../library/calendar.rst:287 +#: ../../library/calendar.rst:330 +msgid "" +"class CustomHTMLCal(calendar.HTMLCalendar):\n" +" cssclasses = [style + \" text-nowrap\" for style in\n" +" calendar.HTMLCalendar.cssclasses]\n" +" cssclass_month_head = \"text-center month-head\"\n" +" cssclass_month = \"text-center month\"\n" +" cssclass_year = \"text-italic lead\"" +msgstr "" +"class CustomHTMLCal(calendar.HTMLCalendar):\n" +" cssclasses = [style + \" text-nowrap\" for style in\n" +" calendar.HTMLCalendar.cssclasses]\n" +" cssclass_month_head = \"text-center month-head\"\n" +" cssclass_month = \"text-center month\"\n" +" cssclass_year = \"text-italic lead\"" + +#: ../../library/calendar.rst:340 msgid "" "This subclass of :class:`TextCalendar` can be passed a locale name in the " "constructor and will return month and weekday names in the specified locale." msgstr "" +"Esta subclasse de :class:`TextCalendar` pode receber um nome de localidade " +"no construtor e retornará nomes de meses e dias da semana na localidade " +"especificada." -#: ../../library/calendar.rst:293 +#: ../../library/calendar.rst:346 msgid "" "This subclass of :class:`HTMLCalendar` can be passed a locale name in the " "constructor and will return month and weekday names in the specified locale." msgstr "" +"Esta subclasse de :class:`HTMLCalendar` pode receber um nome de localidade " +"no construtor e retornará nomes de meses e dias da semana na localidade " +"especificada." -#: ../../library/calendar.rst:299 +#: ../../library/calendar.rst:352 msgid "" "The constructor, :meth:`!formatweekday` and :meth:`!formatmonthname` methods " "of these two classes temporarily change the ``LC_TIME`` locale to the given " "*locale*. Because the current locale is a process-wide setting, they are not " "thread-safe." msgstr "" +"Os métodos construtores :meth:`!formatweekday` e :meth:`!formatmonthname` " +"dessas duas classes alteram temporariamente a localidade ``LC_TIME`` para o " +"*locale* fornecido. Como a localidade atual é uma configuração de todo o " +"processo, eles não são seguros para threads." -#: ../../library/calendar.rst:305 +#: ../../library/calendar.rst:358 msgid "For simple text calendars this module provides the following functions." msgstr "" -"Para simples calendários de texto, este módulo fornece as seguintes funções." +"Para calendários de texto simples, este módulo fornece as seguintes funções." -#: ../../library/calendar.rst:309 +#: ../../library/calendar.rst:362 msgid "" "Sets the weekday (``0`` is Monday, ``6`` is Sunday) to start each week. The " "values :const:`MONDAY`, :const:`TUESDAY`, :const:`WEDNESDAY`, :const:" "`THURSDAY`, :const:`FRIDAY`, :const:`SATURDAY`, and :const:`SUNDAY` are " "provided for convenience. For example, to set the first weekday to Sunday::" msgstr "" +"Define o dia da semana (``0`` é segunda-feira, ``6`` é domingo) para começar " +"cada semana. Os valores :const:`MONDAY`, :const:`TUESDAY`, :const:" +"`WEDNESDAY`, :const:`THURSDAY`, :const:`FRIDAY`, :const:`SATURDAY` e :const:" +"`SUNDAY` são fornecidos para conveniência. Por exemplo, para definir o " +"primeiro dia da semana como domingo::" -#: ../../library/calendar.rst:320 +#: ../../library/calendar.rst:367 +msgid "" +"import calendar\n" +"calendar.setfirstweekday(calendar.SUNDAY)" +msgstr "" +"import calendar\n" +"calendar.setfirstweekday(calendar.SUNDAY)" + +#: ../../library/calendar.rst:373 msgid "Returns the current setting for the weekday to start each week." msgstr "" +"Retorna a configuração atual para o dia da semana que inicia cada semana." -#: ../../library/calendar.rst:325 +#: ../../library/calendar.rst:378 msgid "" "Returns :const:`True` if *year* is a leap year, otherwise :const:`False`." msgstr "" +"Retorna :const:`True` se *year* for um ano bissexto, caso contrário, :const:" +"`False`." -#: ../../library/calendar.rst:330 +#: ../../library/calendar.rst:383 msgid "" "Returns the number of leap years in the range from *y1* to *y2* (exclusive), " "where *y1* and *y2* are years." msgstr "" +"Retorna o número de anos bissextos no intervalo de *y1* a *y2* (exclusivo), " +"onde *y1* e *y2* são anos." -#: ../../library/calendar.rst:333 +#: ../../library/calendar.rst:386 msgid "This function works for ranges spanning a century change." msgstr "" +"Esta função funciona para intervalos que abrangem uma mudança de século." -#: ../../library/calendar.rst:338 +#: ../../library/calendar.rst:391 msgid "" "Returns the day of the week (``0`` is Monday) for *year* (``1970``--...), " "*month* (``1``--``12``), *day* (``1``--``31``)." msgstr "" +"Retorna o dia da semana (``0`` é segunda-feira) para *year* (``1970``--...), " +"*month* (``1``--``12``), *day* (``1``--``31``)." -#: ../../library/calendar.rst:344 +#: ../../library/calendar.rst:397 msgid "" "Return a header containing abbreviated weekday names. *n* specifies the " "width in characters for one weekday." msgstr "" +"Retorna um cabeçalho contendo nomes abreviados de dias da semana. *n* " +"especifica a largura em caracteres para um dia da semana." -#: ../../library/calendar.rst:350 +#: ../../library/calendar.rst:403 msgid "" "Returns weekday of first day of the month and number of days in month, for " "the specified *year* and *month*." msgstr "" +"Retorna o dia da semana do primeiro dia do mês e o número de dias do mês, " +"para o *year* e *month* especificados." -#: ../../library/calendar.rst:356 +#: ../../library/calendar.rst:409 msgid "" "Returns a matrix representing a month's calendar. Each row represents a " "week; days outside of the month are represented by zeros. Each week begins " "with Monday unless set by :func:`setfirstweekday`." msgstr "" +"Retorna uma matriz representando o calendário de um mês. Cada linha " +"representa uma semana; dias fora do mês são representados por zeros. Cada " +"semana começa com segunda-feira, a menos que seja definida por :func:" +"`setfirstweekday`." -#: ../../library/calendar.rst:363 +#: ../../library/calendar.rst:416 msgid "Prints a month's calendar as returned by :func:`month`." -msgstr "" +msgstr "Imprime um calendário do mês conforme retornado pelo :func:`month`." -#: ../../library/calendar.rst:368 +#: ../../library/calendar.rst:421 msgid "" "Returns a month's calendar in a multi-line string using the :meth:" "`~TextCalendar.formatmonth` of the :class:`TextCalendar` class." msgstr "" +"Retorna o calendário de um mês em uma string de várias linhas usando :meth:" +"`~TextCalendar.formatmonth` da classe :class:`TextCalendar`." -#: ../../library/calendar.rst:374 +#: ../../library/calendar.rst:427 msgid "" "Prints the calendar for an entire year as returned by :func:`calendar`." msgstr "" +"Imprime o calendário para um ano inteiro conforme retornado por :func:" +"`calendar`." -#: ../../library/calendar.rst:379 +#: ../../library/calendar.rst:432 msgid "" "Returns a 3-column calendar for an entire year as a multi-line string using " "the :meth:`~TextCalendar.formatyear` of the :class:`TextCalendar` class." msgstr "" +"Retorna um calendário de 3 colunas para um ano inteiro como uma string de " +"várias linhas usando :meth:`~TextCalendar.formatyear` da classe :class:" +"`TextCalendar`." -#: ../../library/calendar.rst:385 +#: ../../library/calendar.rst:438 msgid "" "An unrelated but handy function that takes a time tuple such as returned by " "the :func:`~time.gmtime` function in the :mod:`time` module, and returns the " @@ -457,188 +676,328 @@ msgid "" "encoding. In fact, :func:`time.gmtime` and :func:`timegm` are each others' " "inverse." msgstr "" +"Uma função não relacionada, mas útil, que pega uma tupla de tempo, como a " +"retornada pela função :func:`~time.gmtime` no módulo :mod:`time`, e retorna " +"o valor de registro de data e hora Unix correspondente, persumindo uma época " +"de 1970 e a codificação POSIX. Na verdade, :func:`time.gmtime` e :func:" +"`timegm` são inversos um do outro." -#: ../../library/calendar.rst:392 +#: ../../library/calendar.rst:445 msgid "The :mod:`calendar` module exports the following data attributes:" -msgstr "" +msgstr "O módulo :mod:`calendar` exporta os seguintes atributos de dados:" -#: ../../library/calendar.rst:396 -msgid "An array that represents the days of the week in the current locale." +#: ../../library/calendar.rst:449 +msgid "" +"A sequence that represents the days of the week in the current locale, where " +"Monday is day number 0." msgstr "" +"Uma sequência que representa os dias da semana no local atual, onde Monday é " +"o dia número 0." -#: ../../library/calendar.rst:401 +#: ../../library/calendar.rst:459 msgid "" -"An array that represents the abbreviated days of the week in the current " -"locale." +"A sequence that represents the abbreviated days of the week in the current " +"locale, where Mon is day number 0." msgstr "" +"Uma sequência que representa os dias abreviados da semana no local atual, " +"onde Mon é o dia número 0." -#: ../../library/calendar.rst:412 +#: ../../library/calendar.rst:474 msgid "" "Aliases for the days of the week, where ``MONDAY`` is ``0`` and ``SUNDAY`` " "is ``6``." msgstr "" +"Apelidos para os dias da semana, onde ``MONDAY`` é ``0`` e ``SUNDAY`` é " +"``6``." -#: ../../library/calendar.rst:420 +#: ../../library/calendar.rst:482 msgid "" "Enumeration defining days of the week as integer constants. The members of " "this enumeration are exported to the module scope as :data:`MONDAY` through :" "data:`SUNDAY`." msgstr "" +"Enumeração que define os dias da semana como constantes inteiras. Os membros " +"dessa enumeração são exportados para o escopo do módulo como :data:`MONDAY` " +"até :data:`SUNDAY`." -#: ../../library/calendar.rst:429 +#: ../../library/calendar.rst:491 msgid "" -"An array that represents the months of the year in the current locale. This " -"follows normal convention of January being month number 1, so it has a " -"length of 13 and ``month_name[0]`` is the empty string." +"A sequence that represents the months of the year in the current locale. " +"This follows normal convention of January being month number 1, so it has a " +"length of 13 and ``month_name[0]`` is the empty string." msgstr "" +"Uma sequência que representa os meses do ano na localidade atual. Isso segue " +"a convenção normal de janeiro sendo o mês número 1, então tem um comprimento " +"de 13 e ``month_name[0]`` é a string vazia." -#: ../../library/calendar.rst:436 +#: ../../library/calendar.rst:502 msgid "" -"An array that represents the abbreviated months of the year in the current " +"A sequence that represents the abbreviated months of the year in the current " "locale. This follows normal convention of January being month number 1, so " "it has a length of 13 and ``month_abbr[0]`` is the empty string." msgstr "" +"Uma sequência que representa os meses abreviados do ano na localidade atual. " +"Isso segue a convenção normal de janeiro sendo o mês número 1, então tem um " +"comprimento de 13 e ``month_abbr[0]`` é a string vazia." -#: ../../library/calendar.rst:454 +#: ../../library/calendar.rst:523 msgid "" "Aliases for the months of the year, where ``JANUARY`` is ``1`` and " "``DECEMBER`` is ``12``." msgstr "" +"Apelidos para os meses do ano, onde ``JANUARY`` é ``1`` e ``DECEMBER`` é " +"``12``." -#: ../../library/calendar.rst:462 +#: ../../library/calendar.rst:531 msgid "" "Enumeration defining months of the year as integer constants. The members of " "this enumeration are exported to the module scope as :data:`JANUARY` " "through :data:`DECEMBER`." msgstr "" +"Enumeração que define os meses do ano como constantes inteiras. Os membros " +"dessa enumeração são exportados para o escopo do módulo como :data:`JANUARY` " +"até :data:`DECEMBER`." -#: ../../library/calendar.rst:469 +#: ../../library/calendar.rst:538 msgid "The :mod:`calendar` module defines the following exceptions:" -msgstr "" +msgstr "O módulo :mod:`calendar` define as seguintes exceções:" -#: ../../library/calendar.rst:473 +#: ../../library/calendar.rst:542 msgid "" "A subclass of :exc:`ValueError`, raised when the given month number is " "outside of the range 1-12 (inclusive)." msgstr "" +"Uma subclasse de :exc:`ValueError`, levantada quando o número do mês " +"fornecido está fora do intervalo de 1 a 12 (inclusive)." -#: ../../library/calendar.rst:478 +#: ../../library/calendar.rst:547 msgid "The invalid month number." -msgstr "" +msgstr "O número de meses inválidos." -#: ../../library/calendar.rst:483 +#: ../../library/calendar.rst:552 msgid "" "A subclass of :exc:`ValueError`, raised when the given weekday number is " "outside of the range 0-6 (inclusive)." msgstr "" +"Uma subclasse de :exc:`ValueError`, levantada quando o número do dia da " +"semana fornecido está fora do intervalo de 0 a 6 (inclusive)." -#: ../../library/calendar.rst:488 +#: ../../library/calendar.rst:557 msgid "The invalid weekday number." -msgstr "" +msgstr "O número de dias da semana inválidos." -#: ../../library/calendar.rst:493 +#: ../../library/calendar.rst:562 msgid "Module :mod:`datetime`" msgstr "Módulo :mod:`datetime`" -#: ../../library/calendar.rst:494 +#: ../../library/calendar.rst:563 msgid "" "Object-oriented interface to dates and times with similar functionality to " "the :mod:`time` module." msgstr "" +"Interface orientada a objetos para datas e horas com funcionalidade " +"semelhante ao módulo :mod:`time`." -#: ../../library/calendar.rst:497 +#: ../../library/calendar.rst:566 msgid "Module :mod:`time`" msgstr "Módulo :mod:`time`" -#: ../../library/calendar.rst:498 +#: ../../library/calendar.rst:567 msgid "Low-level time related functions." -msgstr "" +msgstr "Funções de baixo nível relacionadas ao tempo." -#: ../../library/calendar.rst:504 +#: ../../library/calendar.rst:573 msgid "Command-Line Usage" -msgstr "Uso da linha de comando" +msgstr "Uso na linha de comando" -#: ../../library/calendar.rst:508 +#: ../../library/calendar.rst:577 msgid "" "The :mod:`calendar` module can be executed as a script from the command line " "to interactively print a calendar." msgstr "" +"O módulo :mod:`calendar` pode ser executado como um script na linha de " +"comando para exibir interativamente um calendário." -#: ../../library/calendar.rst:518 -msgid "For example, to print a calendar for the year 2000:" +#: ../../library/calendar.rst:580 +msgid "" +"python -m calendar [-h] [-L LOCALE] [-e ENCODING] [-t {text,html}]\n" +" [-w WIDTH] [-l LINES] [-s SPACING] [-m MONTHS] [-c CSS]\n" +" [-f FIRST_WEEKDAY] [year] [month]" msgstr "" +"python -m calendar [-h] [-L LOCALE] [-e ENCODING] [-t {text,html}]\n" +" [-w WIDTH] [-l LINES] [-s SPACING] [-m MONTHS] [-c CSS]\n" +" [-f FIRST_WEEKDAY] [year] [month]" -#: ../../library/calendar.rst:561 +#: ../../library/calendar.rst:587 +msgid "For example, to print a calendar for the year 2000:" +msgstr "Por exemplo, para exibir um calendário para o ano 2000:" + +#: ../../library/calendar.rst:589 +msgid "" +"$ python -m calendar 2000\n" +" 2000\n" +"\n" +" January February March\n" +"Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n" +" 1 2 1 2 3 4 5 6 1 2 3 4 5\n" +" 3 4 5 6 7 8 9 7 8 9 10 11 12 13 6 7 8 9 10 11 12\n" +"10 11 12 13 14 15 16 14 15 16 17 18 19 20 13 14 15 16 17 18 19\n" +"17 18 19 20 21 22 23 21 22 23 24 25 26 27 20 21 22 23 24 25 26\n" +"24 25 26 27 28 29 30 28 29 27 28 29 30 31\n" +"31\n" +"\n" +" April May June\n" +"Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n" +" 1 2 1 2 3 4 5 6 7 1 2 3 4\n" +" 3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11\n" +"10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18\n" +"17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25\n" +"24 25 26 27 28 29 30 29 30 31 26 27 28 29 30\n" +"\n" +" July August September\n" +"Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n" +" 1 2 1 2 3 4 5 6 1 2 3\n" +" 3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10\n" +"10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17\n" +"17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24\n" +"24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30\n" +"31\n" +"\n" +" October November December\n" +"Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n" +" 1 1 2 3 4 5 1 2 3\n" +" 2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10\n" +" 9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17\n" +"16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24\n" +"23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31\n" +"30 31" +msgstr "" +"$ python -m calendar 2000\n" +" 2000\n" +"\n" +" January February March\n" +"Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n" +" 1 2 1 2 3 4 5 6 1 2 3 4 5\n" +" 3 4 5 6 7 8 9 7 8 9 10 11 12 13 6 7 8 9 10 11 12\n" +"10 11 12 13 14 15 16 14 15 16 17 18 19 20 13 14 15 16 17 18 19\n" +"17 18 19 20 21 22 23 21 22 23 24 25 26 27 20 21 22 23 24 25 26\n" +"24 25 26 27 28 29 30 28 29 27 28 29 30 31\n" +"31\n" +"\n" +" April May June\n" +"Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n" +" 1 2 1 2 3 4 5 6 7 1 2 3 4\n" +" 3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11\n" +"10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18\n" +"17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25\n" +"24 25 26 27 28 29 30 29 30 31 26 27 28 29 30\n" +"\n" +" July August September\n" +"Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n" +" 1 2 1 2 3 4 5 6 1 2 3\n" +" 3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10\n" +"10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17\n" +"17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24\n" +"24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30\n" +"31\n" +"\n" +" October November December\n" +"Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n" +" 1 1 2 3 4 5 1 2 3\n" +" 2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10\n" +" 9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17\n" +"16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24\n" +"23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31\n" +"30 31" + +#: ../../library/calendar.rst:630 msgid "The following options are accepted:" msgstr "As seguintes opções são aceitas:" -#: ../../library/calendar.rst:568 +#: ../../library/calendar.rst:637 msgid "Show the help message and exit." msgstr "Mostra a mensagem de ajuda e sai." -#: ../../library/calendar.rst:573 +#: ../../library/calendar.rst:642 msgid "The locale to use for month and weekday names. Defaults to English." msgstr "" +"A localidade a ser usada para nomes de meses e dias da semana. O padrão é " +"inglês." -#: ../../library/calendar.rst:579 +#: ../../library/calendar.rst:648 msgid "" "The encoding to use for output. :option:`--encoding` is required if :option:" "`--locale` is set." msgstr "" +"A codificação a ser usada para saída. :option:`--encoding` é necessário se :" +"option:`--locale` estiver definido." -#: ../../library/calendar.rst:585 +#: ../../library/calendar.rst:654 msgid "Print the calendar to the terminal as text, or as an HTML document." -msgstr "" +msgstr "Exibe o calendário no terminal como texto ou como um documento HTML." -#: ../../library/calendar.rst:591 +#: ../../library/calendar.rst:660 msgid "" "The weekday to start each week. Must be a number between 0 (Monday) and 6 " "(Sunday). Defaults to 0." msgstr "" +"O dia da semana para começar cada semana. Deve ser um número entre 0 " +"(segunda-feira) e 6 (domingo). O padrão é 0." -#: ../../library/calendar.rst:599 +#: ../../library/calendar.rst:668 msgid "The year to print the calendar for. Defaults to the current year." -msgstr "" +msgstr "O ano para exibir o calendário. O padrão é o ano atual." -#: ../../library/calendar.rst:605 +#: ../../library/calendar.rst:674 msgid "" "The month of the specified :option:`year` to print the calendar for. Must be " "a number between 1 and 12, and may only be used in text mode. Defaults to " "printing a calendar for the full year." msgstr "" +"O mês do :option:`year` especificado para exibir o calendário. Deve ser um " +"número entre 1 e 12 e pode ser usado somente no modo texto. O padrão é " +"exibir um calendário para o ano inteiro." -#: ../../library/calendar.rst:611 +#: ../../library/calendar.rst:680 msgid "*Text-mode options:*" -msgstr "" +msgstr "*Opções de modo texto:*" -#: ../../library/calendar.rst:615 +#: ../../library/calendar.rst:684 msgid "" "The width of the date column in terminal columns. The date is printed " "centred in the column. Any value lower than 2 is ignored. Defaults to 2." msgstr "" +"A largura da coluna de data em colunas terminais. A data é exibida " +"centralizada na coluna. Qualquer valor menor que 2 é ignorado. O padrão é 2." -#: ../../library/calendar.rst:623 +#: ../../library/calendar.rst:692 msgid "" "The number of lines for each week in terminal rows. The date is printed top-" "aligned. Any value lower than 1 is ignored. Defaults to 1." msgstr "" +"O número de linhas para cada semana em linhas terminais. A data é exibida " +"alinhada no topo. Qualquer valor menor que 1 é ignorado. O padrão é 1." -#: ../../library/calendar.rst:631 +#: ../../library/calendar.rst:700 msgid "" "The space between months in columns. Any value lower than 2 is ignored. " "Defaults to 6." msgstr "" +"O espaço entre os meses em colunas. Qualquer valor menor que 2 é ignorado. O " +"padrão é 6." -#: ../../library/calendar.rst:638 +#: ../../library/calendar.rst:707 msgid "The number of months printed per row. Defaults to 3." -msgstr "" +msgstr "O número de meses exibidos por linha. O padrão é 3." -#: ../../library/calendar.rst:642 +#: ../../library/calendar.rst:711 msgid "*HTML-mode options:*" -msgstr "" +msgstr "*Opções de modo HTML:*" -#: ../../library/calendar.rst:646 +#: ../../library/calendar.rst:715 msgid "" "The path of a CSS stylesheet to use for the calendar. This must either be " "relative to the generated HTML, or an absolute HTTP or ``file:///`` URL." msgstr "" +"O caminho de uma folha de estilo CSS a ser usada para o calendário. Isso " +"deve ser relativo ao HTML gerado ou um HTTP absoluto ou URL ``file:///``." diff --git a/library/cgi.po b/library/cgi.po new file mode 100644 index 000000000..5cfc8f4b7 --- /dev/null +++ b/library/cgi.po @@ -0,0 +1,56 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../library/cgi.rst:2 +msgid ":mod:`!cgi` --- Common Gateway Interface support" +msgstr ":mod:`!cgi` --- Suporte a Common Gateway Interface" + +#: ../../library/cgi.rst:10 +msgid "" +"This module is no longer part of the Python standard library. It was :ref:" +"`removed in Python 3.13 ` after being deprecated in " +"Python 3.11. The removal was decided in :pep:`594`." +msgstr "" +"Este módulo não faz mais parte da biblioteca padrão do Python. Ele foi :ref:" +"`removido no Python 3.13 ` após ser descontinuado no " +"Python 3.11. A remoção foi decidida na :pep:`594`." + +#: ../../library/cgi.rst:14 +msgid "" +"A fork of the module on PyPI can be used instead: :pypi:`legacy-cgi`. This " +"is a copy of the cgi module, no longer maintained or supported by the core " +"Python team." +msgstr "" +"Um fork do módulo no PyPI pode ser usado em vez disso: :pypi:`legacy-cgi`. " +"Esta é uma cópia do módulo cgi, não mais mantido ou suportado pela equipe " +"core do Python." + +#: ../../library/cgi.rst:18 +msgid "" +"The last version of Python that provided the :mod:`!cgi` module was `Python " +"3.12 `_." +msgstr "" +"A última versão do Python que forneceu o módulo :mod:`!cgi` foi o `Python " +"3.12 `_." diff --git a/library/cgitb.po b/library/cgitb.po new file mode 100644 index 000000000..8626c9287 --- /dev/null +++ b/library/cgitb.po @@ -0,0 +1,56 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../library/cgitb.rst:2 +msgid ":mod:`!cgitb` --- Traceback manager for CGI scripts" +msgstr ":mod:`!cgitb` --- Gerenciador de traceback para scripts de CGI" + +#: ../../library/cgitb.rst:10 +msgid "" +"This module is no longer part of the Python standard library. It was :ref:" +"`removed in Python 3.13 ` after being deprecated in " +"Python 3.11. The removal was decided in :pep:`594`." +msgstr "" +"Este módulo não faz mais parte da biblioteca padrão do Python. Ele foi :ref:" +"`removido no Python 3.13 ` após ser descontinuado no " +"Python 3.11. A remoção foi decidida na :pep:`594`." + +#: ../../library/cgitb.rst:14 +msgid "" +"A fork of the module on PyPI can now be used instead: :pypi:`legacy-cgi`. " +"This is a copy of the cgi module, no longer maintained or supported by the " +"core Python team." +msgstr "" +"Um fork do módulo no PyPI agora pode ser usado em vez disso: :pypi:`legacy-" +"cgi`. Esta é uma cópia do módulo cgi, não mais mantido ou suportado pela " +"equipe core do Python." + +#: ../../library/cgitb.rst:18 +msgid "" +"The last version of Python that provided the :mod:`!cgitb` module was " +"`Python 3.12 `_." +msgstr "" +"A última versão do Python que forneceu o módulo :mod:`!cgitb` foi o `Python " +"3.12 `_." diff --git a/library/chunk.po b/library/chunk.po new file mode 100644 index 000000000..e43003203 --- /dev/null +++ b/library/chunk.po @@ -0,0 +1,46 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../library/chunk.rst:2 +msgid ":mod:`!chunk` --- Read IFF chunked data" +msgstr ":mod:`!chunk` --- Lê dados em blocos IFF" + +#: ../../library/chunk.rst:10 +msgid "" +"This module is no longer part of the Python standard library. It was :ref:" +"`removed in Python 3.13 ` after being deprecated in " +"Python 3.11. The removal was decided in :pep:`594`." +msgstr "" +"Este módulo não faz mais parte da biblioteca padrão do Python. Ele foi :ref:" +"`removido no Python 3.13 ` após ser descontinuado no " +"Python 3.11. A remoção foi decidida na :pep:`594`." + +#: ../../library/chunk.rst:14 +msgid "" +"The last version of Python that provided the :mod:`!chunk` module was " +"`Python 3.12 `_." +msgstr "" +"A última versão do Python que forneceu o módulo :mod:`!chunk` foi o `Python " +"3.12 `_." diff --git a/library/cmath.po b/library/cmath.po index db45b7044..c68097b35 100644 --- a/library/cmath.po +++ b/library/cmath.po @@ -1,29 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Marco Rougeth , 2023 -# Rafael Fontenelle , 2024 -# Pedro Fonini, 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-21 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:56+0000\n" -"Last-Translator: Pedro Fonini, 2024\n" +"POT-Creation-Date: 2025-04-11 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -45,7 +41,7 @@ msgstr "" "funções neste módulo aceitam inteiros, números de ponto flutuante ou números " "complexos como argumentos. Eles também aceitarão qualquer objeto Python que " "tenha um método :meth:`~object.__complex__` ou :meth:`~object.__float__`: " -"esses métodos são usados ​​para converter o objeto em um número complexo ou de " +"esses métodos são usados para converter o objeto em um número complexo ou de " "ponto flutuante, respectivamente, e a função é então aplicada ao resultado " "da conversão." @@ -81,6 +77,14 @@ msgstr "" "tratado como se estivesse *abaixo* do corte de ramificação, e assim dá um " "resultado no eixo imaginário negativo::" +#: ../../library/cmath.rst:31 +msgid "" +">>> cmath.sqrt(complex(-2.0, -0.0))\n" +"-1.4142135623730951j" +msgstr "" +">>> cmath.sqrt(complex(-2.0, -0.0))\n" +"-1.4142135623730951j" + #: ../../library/cmath.rst:34 msgid "" "But an argument of ``complex(-2.0, 0.0)`` is treated as though it lies above " @@ -89,11 +93,283 @@ msgstr "" "Mas um argumento de ``complex(-2.0, 0.0)`` é tratado como se estivesse acima " "do corte de ramificação::" +#: ../../library/cmath.rst:37 +msgid "" +">>> cmath.sqrt(complex(-2.0, 0.0))\n" +"1.4142135623730951j" +msgstr "" +">>> cmath.sqrt(complex(-2.0, 0.0))\n" +"1.4142135623730951j" + #: ../../library/cmath.rst:42 +msgid "**Conversions to and from polar coordinates**" +msgstr "**Conversões de e para coordenadas polares**" + +#: ../../library/cmath.rst:44 +msgid ":func:`phase(z) `" +msgstr ":func:`phase(z) `" + +#: ../../library/cmath.rst:44 +msgid "Return the phase of *z*" +msgstr "Retorna a fase de *z*" + +#: ../../library/cmath.rst:45 +msgid ":func:`polar(z) `" +msgstr ":func:`polar(z) `" + +#: ../../library/cmath.rst:45 +msgid "Return the representation of *z* in polar coordinates" +msgstr "Retorna a representação de *z* em coordenadas polares" + +#: ../../library/cmath.rst:46 +msgid ":func:`rect(r, phi) `" +msgstr ":func:`rect(r, phi) `" + +#: ../../library/cmath.rst:46 +msgid "Return the complex number *z* with polar coordinates *r* and *phi*" +msgstr "Retorna o número complexo *z* com coordenadas polares *r* e *phi*" + +#: ../../library/cmath.rst:48 +msgid "**Power and logarithmic functions**" +msgstr "**Funções de potência e logarítmicas**" + +#: ../../library/cmath.rst:50 +msgid ":func:`exp(z) `" +msgstr ":func:`exp(z) `" + +#: ../../library/cmath.rst:50 +msgid "Return *e* raised to the power *z*" +msgstr "Retorna *e* elevado à potência *z*" + +#: ../../library/cmath.rst:51 +msgid ":func:`log(z[, base]) `" +msgstr ":func:`log(z[, base]) `" + +#: ../../library/cmath.rst:51 +msgid "Return the logarithm of *z* to the given *base* (*e* by default)" +msgstr "Retorna o logaritmo de *z* para a *base* fornecida (*e* por padrão)" + +#: ../../library/cmath.rst:52 +msgid ":func:`log10(z) `" +msgstr ":func:`log10(z) `" + +#: ../../library/cmath.rst:52 +msgid "Return the base-10 logarithm of *z*" +msgstr "Retorna o logaritmo de base 10 de *z*" + +#: ../../library/cmath.rst:53 +msgid ":func:`sqrt(z) `" +msgstr ":func:`sqrt(z) `" + +#: ../../library/cmath.rst:53 +msgid "Return the square root of *z*" +msgstr "Retorna a raiz quadrada de *z*" + +#: ../../library/cmath.rst:55 +msgid "**Trigonometric functions**" +msgstr "**Funções trigonométricas**" + +#: ../../library/cmath.rst:57 +msgid ":func:`acos(z) `" +msgstr ":func:`acos(z) `" + +#: ../../library/cmath.rst:57 +msgid "Return the arc cosine of *z*" +msgstr "Retorna o arco cosseno de *z*" + +#: ../../library/cmath.rst:58 +msgid ":func:`asin(z) `" +msgstr ":func:`asin(z) `" + +#: ../../library/cmath.rst:58 +msgid "Return the arc sine of *z*" +msgstr "Retorna o arco seno de *z*" + +#: ../../library/cmath.rst:59 +msgid ":func:`atan(z) `" +msgstr ":func:`atan(z) `" + +#: ../../library/cmath.rst:59 +msgid "Return the arc tangent of *z*" +msgstr "Retorna o arco tangente de *z*" + +#: ../../library/cmath.rst:60 +msgid ":func:`cos(z) `" +msgstr ":func:`cos(z) `" + +#: ../../library/cmath.rst:60 +msgid "Return the cosine of *z*" +msgstr "Retorna o cosseno de *z*" + +#: ../../library/cmath.rst:61 +msgid ":func:`sin(z) `" +msgstr ":func:`sin(z) `" + +#: ../../library/cmath.rst:61 +msgid "Return the sine of *z*" +msgstr "Retorna o seno de *z*" + +#: ../../library/cmath.rst:62 +msgid ":func:`tan(z) `" +msgstr ":func:`tan(z) `" + +#: ../../library/cmath.rst:62 +msgid "Return the tangent of *z*" +msgstr "Retorna a tangente de *z*" + +#: ../../library/cmath.rst:64 +msgid "**Hyperbolic functions**" +msgstr "**Funções hiperbólicas**" + +#: ../../library/cmath.rst:66 +msgid ":func:`acosh(z) `" +msgstr ":func:`acosh(z) `" + +#: ../../library/cmath.rst:66 +msgid "Return the inverse hyperbolic cosine of *z*" +msgstr "Retorna o cosseno hiperbólico inverso de *z*" + +#: ../../library/cmath.rst:67 +msgid ":func:`asinh(z) `" +msgstr ":func:`asinh(z) `" + +#: ../../library/cmath.rst:67 +msgid "Return the inverse hyperbolic sine of *z*" +msgstr "Retorna o seno hiperbólico inverso de *z*" + +#: ../../library/cmath.rst:68 +msgid ":func:`atanh(z) `" +msgstr ":func:`atanh(z) `" + +#: ../../library/cmath.rst:68 +msgid "Return the inverse hyperbolic tangent of *z*" +msgstr "Retorna a tangente hiperbólica inversa de *z*" + +#: ../../library/cmath.rst:69 +msgid ":func:`cosh(z) `" +msgstr ":func:`cosh(z) `" + +#: ../../library/cmath.rst:69 +msgid "Return the hyperbolic cosine of *z*" +msgstr "Retorna o cosseno hiperbólico de *z*" + +#: ../../library/cmath.rst:70 +msgid ":func:`sinh(z) `" +msgstr ":func:`sinh(z) `" + +#: ../../library/cmath.rst:70 +msgid "Return the hyperbolic sine of *z*" +msgstr "Retorna o seno hiperbólico de *z*" + +#: ../../library/cmath.rst:71 +msgid ":func:`tanh(z) `" +msgstr ":func:`tanh(z) `" + +#: ../../library/cmath.rst:71 +msgid "Return the hyperbolic tangent of *z*" +msgstr "Retorna a tangente hiperbólica de *z*" + +#: ../../library/cmath.rst:73 +msgid "**Classification functions**" +msgstr "**Funções de classificação**" + +#: ../../library/cmath.rst:75 +msgid ":func:`isfinite(z) `" +msgstr ":func:`isfinite(z) `" + +#: ../../library/cmath.rst:75 +msgid "Check if all components of *z* are finite" +msgstr "Verifica se todos os componentes de *z* são finitos" + +#: ../../library/cmath.rst:76 +msgid ":func:`isinf(z) `" +msgstr ":func:`isinf(z) `" + +#: ../../library/cmath.rst:76 +msgid "Check if any component of *z* is infinite" +msgstr "Verifica se algum componente de *z* é infinito" + +#: ../../library/cmath.rst:77 +msgid ":func:`isnan(z) `" +msgstr ":func:`isnan(z) `" + +#: ../../library/cmath.rst:77 +msgid "Check if any component of *z* is a NaN" +msgstr "Verifica se algum componente de *z* é NaN" + +#: ../../library/cmath.rst:78 +msgid ":func:`isclose(a, b, *, rel_tol, abs_tol) `" +msgstr ":func:`isclose(a, b, *, rel_tol, abs_tol) `" + +#: ../../library/cmath.rst:78 +msgid "Check if the values *a* and *b* are close to each other" +msgstr "Verifica se os valores *a* e *b* estão próximos um do outro" + +#: ../../library/cmath.rst:80 +msgid "**Constants**" +msgstr "**Constantes**" + +#: ../../library/cmath.rst:82 +msgid ":data:`pi`" +msgstr ":data:`pi`" + +#: ../../library/cmath.rst:82 +msgid "*π* = 3.141592..." +msgstr "*π* = 3.141592..." + +#: ../../library/cmath.rst:83 +msgid ":data:`e`" +msgstr ":data:`e`" + +#: ../../library/cmath.rst:83 +msgid "*e* = 2.718281..." +msgstr "*e* = 2.718281..." + +#: ../../library/cmath.rst:84 +msgid ":data:`tau`" +msgstr ":data:`tau`" + +#: ../../library/cmath.rst:84 +msgid "*τ* = 2\\ *π* = 6.283185..." +msgstr "*τ* = 2\\ *π* = 6.283185..." + +#: ../../library/cmath.rst:85 +msgid ":data:`inf`" +msgstr ":data:`inf`" + +#: ../../library/cmath.rst:85 +msgid "Positive infinity" +msgstr "Infinito positivo" + +#: ../../library/cmath.rst:86 +msgid ":data:`infj`" +msgstr ":data:`infj`" + +#: ../../library/cmath.rst:86 +msgid "Pure imaginary infinity" +msgstr "Infinito imaginário puro" + +#: ../../library/cmath.rst:87 +msgid ":data:`nan`" +msgstr ":data:`nan`" + +#: ../../library/cmath.rst:87 +msgid "\"Not a number\" (NaN)" +msgstr "\"Not a number\" (NaN)" + +#: ../../library/cmath.rst:88 +msgid ":data:`nanj`" +msgstr ":data:`nanj`" + +#: ../../library/cmath.rst:88 +msgid "Pure imaginary NaN" +msgstr "NaN imaginário puro" + +#: ../../library/cmath.rst:93 msgid "Conversions to and from polar coordinates" msgstr "Conversões de e para coordenadas polares" -#: ../../library/cmath.rst:44 +#: ../../library/cmath.rst:95 msgid "" "A Python complex number ``z`` is stored internally using *rectangular* or " "*Cartesian* coordinates. It is completely determined by its *real part* ``z." @@ -103,7 +379,7 @@ msgstr "" "*retangulares* ou *cartesianas*. É completamente determinado por sua *parte " "real* ``z.real`` e sua *parte imaginária* ``z.imag``." -#: ../../library/cmath.rst:48 +#: ../../library/cmath.rst:99 msgid "" "*Polar coordinates* give an alternative way to represent a complex number. " "In polar coordinates, a complex number *z* is defined by the modulus *r* and " @@ -118,7 +394,7 @@ msgstr "" "*z* à origem, enquanto a fase *phi* é o ângulo anti-horário, medido em " "radianos, do eixo x positivo ao segmento de reta que une a origem a *z*." -#: ../../library/cmath.rst:55 +#: ../../library/cmath.rst:106 msgid "" "The following functions can be used to convert from the native rectangular " "coordinates to polar coordinates and back." @@ -126,200 +402,212 @@ msgstr "" "As funções a seguir podem ser usadas para converter coordenadas retangulares " "nativas em coordenadas polares e vice-versa." -#: ../../library/cmath.rst:60 +#: ../../library/cmath.rst:111 msgid "" -"Return the phase of *x* (also known as the *argument* of *x*), as a float. " -"``phase(x)`` is equivalent to ``math.atan2(x.imag, x.real)``. The result " +"Return the phase of *z* (also known as the *argument* of *z*), as a float. " +"``phase(z)`` is equivalent to ``math.atan2(z.imag, z.real)``. The result " "lies in the range [-\\ *π*, *π*], and the branch cut for this operation lies " "along the negative real axis. The sign of the result is the same as the " -"sign of ``x.imag``, even when ``x.imag`` is zero::" +"sign of ``z.imag``, even when ``z.imag`` is zero::" +msgstr "" +"Retorna a fase de *z* (também conhecido como *argumento* de *z*), como um " +"ponto flutuante. ``phase(z)`` equivale a ``math.atan2(z.imag, z.real)``. O " +"resultado está no intervalo [-\\ *π*, *π*], e o corte de ramificação para " +"esta operação está ao longo do eixo real negativo. O sinal do resultado é " +"igual ao sinal de ``z.imag``, mesmo quando ``z.imag`` é zero::" + +#: ../../library/cmath.rst:117 +msgid "" +">>> phase(complex(-1.0, 0.0))\n" +"3.141592653589793\n" +">>> phase(complex(-1.0, -0.0))\n" +"-3.141592653589793" msgstr "" -"Retorna a fase de *x* (também conhecido como *argumento* de *x*), como um " -"ponto flutuante. ``phase(x)`` é equivalente a ``math.atan2(x.imag, x." -"real)``. O resultado está no intervalo [-\\ *π*, *π*], e o corte de " -"ramificação para esta operação está ao longo do eixo real negativo. O sinal " -"do resultado é igual ao sinal de ``x.imag``, mesmo quando ``x.imag`` é zero::" +">>> phase(complex(-1.0, 0.0))\n" +"3.141592653589793\n" +">>> phase(complex(-1.0, -0.0))\n" +"-3.141592653589793" -#: ../../library/cmath.rst:74 +#: ../../library/cmath.rst:125 msgid "" -"The modulus (absolute value) of a complex number *x* can be computed using " +"The modulus (absolute value) of a complex number *z* can be computed using " "the built-in :func:`abs` function. There is no separate :mod:`cmath` module " "function for this operation." msgstr "" -"O módulo (valor absoluto) de um número complexo *x* pode ser calculado " +"O módulo (valor absoluto) de um número complexo *z* pode ser calculado " "usando a função embutida :func:`abs`. Não há função do módulo :mod:`cmath` " "separada para esta operação." -#: ../../library/cmath.rst:81 +#: ../../library/cmath.rst:132 msgid "" -"Return the representation of *x* in polar coordinates. Returns a pair ``(r, " -"phi)`` where *r* is the modulus of *x* and phi is the phase of *x*. " -"``polar(x)`` is equivalent to ``(abs(x), phase(x))``." +"Return the representation of *z* in polar coordinates. Returns a pair ``(r, " +"phi)`` where *r* is the modulus of *z* and *phi* is the phase of *z*. " +"``polar(z)`` is equivalent to ``(abs(z), phase(z))``." msgstr "" -"Retorna a representação de *x* em coordenadas polares. Retorna um par ``(r, " -"phi)`` onde *r* é o módulo de *x* e phi é a fase de *x*. ``polar(x)`` é " -"equivalente a ``(abs(x), phase(x))``." +"Retorna a representação de *z* em coordenadas polares. Retorna um par ``(r, " +"phi)`` onde *r* é o módulo de *z* e phi é a fase de *z*. ``polar(z)`` " +"equivale a ``(abs(z), phase(z))``." -#: ../../library/cmath.rst:89 +#: ../../library/cmath.rst:140 msgid "" -"Return the complex number *x* with polar coordinates *r* and *phi*. " +"Return the complex number *z* with polar coordinates *r* and *phi*. " "Equivalent to ``complex(r * math.cos(phi), r * math.sin(phi))``." msgstr "" -"Retorna o número complexo *x* com coordenadas polares *r* e *phi*. " -"Equivalente a ``complex(r * math.cos(phi), r * math.sin(phi))``." +"Retorna o número complexo *z* com coordenadas polares *r* e *phi*. Equivale " +"a ``complex(r * math.cos(phi), r * math.sin(phi))``." -#: ../../library/cmath.rst:94 +#: ../../library/cmath.rst:145 msgid "Power and logarithmic functions" msgstr "Funções de potência e logarítmicas" -#: ../../library/cmath.rst:98 +#: ../../library/cmath.rst:149 msgid "" -"Return *e* raised to the power *x*, where *e* is the base of natural " +"Return *e* raised to the power *z*, where *e* is the base of natural " "logarithms." msgstr "" -"Retorna *e* elevado à potência *x*, onde *e* é a base de logaritmos naturais." +"Retorna *e* elevado à potência *z*, onde *e* é a base de logaritmos naturais." -#: ../../library/cmath.rst:104 +#: ../../library/cmath.rst:155 msgid "" -"Returns the logarithm of *x* to the given *base*. If the *base* is not " -"specified, returns the natural logarithm of *x*. There is one branch cut, " +"Return the logarithm of *z* to the given *base*. If the *base* is not " +"specified, returns the natural logarithm of *z*. There is one branch cut, " "from 0 along the negative real axis to -∞." msgstr "" -"Retorna o logaritmo de *x* para a *base* fornecida. Se a *base* não for " -"especificada, retorna o logaritmo natural de *x*. Há um corte de " +"Retorna o logaritmo de *z* para a *base* fornecida. Se a *base* não for " +"especificada, retorna o logaritmo natural de *z*. Há um corte de " "ramificação, de 0 ao longo do eixo real negativo até -∞." -#: ../../library/cmath.rst:111 +#: ../../library/cmath.rst:162 msgid "" -"Return the base-10 logarithm of *x*. This has the same branch cut as :func:" +"Return the base-10 logarithm of *z*. This has the same branch cut as :func:" "`log`." msgstr "" -"Retorna o logaritmo de *x* na base 10. Este tem o mesmo corte de ramificação " +"Retorna o logaritmo de *z* na base 10. Este tem o mesmo corte de ramificação " "que :func:`log`." -#: ../../library/cmath.rst:117 +#: ../../library/cmath.rst:168 msgid "" -"Return the square root of *x*. This has the same branch cut as :func:`log`." +"Return the square root of *z*. This has the same branch cut as :func:`log`." msgstr "" -"Retorna a raiz quadrada de *x*. Este tem o mesmo corte de ramificação que :" +"Retorna a raiz quadrada de *z*. Este tem o mesmo corte de ramificação que :" "func:`log`." -#: ../../library/cmath.rst:121 +#: ../../library/cmath.rst:172 msgid "Trigonometric functions" msgstr "Funções trigonométricas" -#: ../../library/cmath.rst:125 +#: ../../library/cmath.rst:176 msgid "" -"Return the arc cosine of *x*. There are two branch cuts: One extends right " +"Return the arc cosine of *z*. There are two branch cuts: One extends right " "from 1 along the real axis to ∞. The other extends left from -1 along the " "real axis to -∞." msgstr "" -"Retorna o arco cosseno de *x*. Existem dois cortes de ramificação: um se " +"Retorna o arco cosseno de *z*. Existem dois cortes de ramificação: um se " "estende desde 1 ao longo do eixo real até ∞. O outro se estende para a " "esquerda de -1 ao longo do eixo real até -∞." -#: ../../library/cmath.rst:132 +#: ../../library/cmath.rst:183 msgid "" -"Return the arc sine of *x*. This has the same branch cuts as :func:`acos`." +"Return the arc sine of *z*. This has the same branch cuts as :func:`acos`." msgstr "" -"Retorna o arco seno de *x*. Tem os mesmos cortes de ramificação que :func:" +"Retorna o arco seno de *z*. Tem os mesmos cortes de ramificação que :func:" "`acos`." -#: ../../library/cmath.rst:137 +#: ../../library/cmath.rst:188 msgid "" -"Return the arc tangent of *x*. There are two branch cuts: One extends from " +"Return the arc tangent of *z*. There are two branch cuts: One extends from " "``1j`` along the imaginary axis to ``∞j``. The other extends from ``-1j`` " "along the imaginary axis to ``-∞j``." msgstr "" -"Retorna o arco tangente de *x*. Existem dois cortes de ramificação: Um se " +"Retorna o arco tangente de *z*. Existem dois cortes de ramificação: Um se " "estende de ``1j`` ao longo do eixo imaginário até ``∞j``. O outro se estende " "de ``-1j`` ao longo do eixo imaginário até ``-∞j``." -#: ../../library/cmath.rst:144 -msgid "Return the cosine of *x*." -msgstr "Retorna o cosseno de *x*." +#: ../../library/cmath.rst:195 +msgid "Return the cosine of *z*." +msgstr "Retorna o cosseno de *z*." -#: ../../library/cmath.rst:149 -msgid "Return the sine of *x*." -msgstr "Retorna o seno de *x*." +#: ../../library/cmath.rst:200 +msgid "Return the sine of *z*." +msgstr "Retorna o seno de *z*." -#: ../../library/cmath.rst:154 -msgid "Return the tangent of *x*." -msgstr "Retorna a tangente de *x*." +#: ../../library/cmath.rst:205 +msgid "Return the tangent of *z*." +msgstr "Retorna a tangente de *z*." -#: ../../library/cmath.rst:158 +#: ../../library/cmath.rst:209 msgid "Hyperbolic functions" msgstr "Funções hiperbólicas" -#: ../../library/cmath.rst:162 +#: ../../library/cmath.rst:213 msgid "" -"Return the inverse hyperbolic cosine of *x*. There is one branch cut, " +"Return the inverse hyperbolic cosine of *z*. There is one branch cut, " "extending left from 1 along the real axis to -∞." msgstr "" -"Retorna o cosseno hiperbólico inverso de *x*. Há um corte de ramificação, " +"Retorna o cosseno hiperbólico inverso de *z*. Há um corte de ramificação, " "estendendo-se para a esquerda de 1 ao longo do eixo real até -∞." -#: ../../library/cmath.rst:168 +#: ../../library/cmath.rst:219 msgid "" -"Return the inverse hyperbolic sine of *x*. There are two branch cuts: One " +"Return the inverse hyperbolic sine of *z*. There are two branch cuts: One " "extends from ``1j`` along the imaginary axis to ``∞j``. The other extends " "from ``-1j`` along the imaginary axis to ``-∞j``." msgstr "" -"Retorna o seno hiperbólico inverso de *x*. Existem dois cortes de " +"Retorna o seno hiperbólico inverso de *z*. Existem dois cortes de " "ramificação: Um se estende de ``1j`` ao longo do eixo imaginário até ``∞j``. " "O outro se estende de ``-1j`` ao longo do eixo imaginário até ``-∞j``." -#: ../../library/cmath.rst:175 +#: ../../library/cmath.rst:226 msgid "" -"Return the inverse hyperbolic tangent of *x*. There are two branch cuts: One " +"Return the inverse hyperbolic tangent of *z*. There are two branch cuts: One " "extends from ``1`` along the real axis to ``∞``. The other extends from " "``-1`` along the real axis to ``-∞``." msgstr "" -"Retorna a tangente hiperbólica inversa de *x*. Existem dois cortes de " +"Retorna a tangente hiperbólica inversa de *z*. Existem dois cortes de " "ramificação: Um se estende de ``1`` ao longo do eixo real até ``∞``. O outro " "se estende de ``-1`` ao longo do eixo real até ``-∞``." -#: ../../library/cmath.rst:182 -msgid "Return the hyperbolic cosine of *x*." -msgstr "Retorna o cosseno hiperbólico de *x*." +#: ../../library/cmath.rst:233 +msgid "Return the hyperbolic cosine of *z*." +msgstr "Retorna o cosseno hiperbólico de *z*." -#: ../../library/cmath.rst:187 -msgid "Return the hyperbolic sine of *x*." -msgstr "Retorna o seno hiperbólico de *x*." +#: ../../library/cmath.rst:238 +msgid "Return the hyperbolic sine of *z*." +msgstr "Retorna o seno hiperbólico de *z*." -#: ../../library/cmath.rst:192 -msgid "Return the hyperbolic tangent of *x*." -msgstr "Retorna a tangente hiperbólica de *x*." +#: ../../library/cmath.rst:243 +msgid "Return the hyperbolic tangent of *z*." +msgstr "Retorna a tangente hiperbólica de *z*." -#: ../../library/cmath.rst:196 +#: ../../library/cmath.rst:247 msgid "Classification functions" msgstr "Funções de classificação" -#: ../../library/cmath.rst:200 +#: ../../library/cmath.rst:251 msgid "" -"Return ``True`` if both the real and imaginary parts of *x* are finite, and " +"Return ``True`` if both the real and imaginary parts of *z* are finite, and " "``False`` otherwise." msgstr "" -"Retorna ``True`` se ambas as partes real e imaginária de *x* forem finitas, " +"Retorna ``True`` se ambas as partes real e imaginária de *z* forem finitas, " "e ``False`` caso contrário." -#: ../../library/cmath.rst:208 +#: ../../library/cmath.rst:259 msgid "" -"Return ``True`` if either the real or the imaginary part of *x* is an " +"Return ``True`` if either the real or the imaginary part of *z* is an " "infinity, and ``False`` otherwise." msgstr "" -"Retorna ``True`` se ou a parte real ou a imaginária de *x* for infinita, e " +"Retorna ``True`` se ou a parte real ou a imaginária de *z* for infinita, e " "``False`` caso contrário." -#: ../../library/cmath.rst:214 +#: ../../library/cmath.rst:265 msgid "" -"Return ``True`` if either the real or the imaginary part of *x* is a NaN, " +"Return ``True`` if either the real or the imaginary part of *z* is a NaN, " "and ``False`` otherwise." msgstr "" -"Retorna ``True`` se ou a parte real ou a imaginária de *x* for NaN, e " +"Retorna ``True`` se ou a parte real ou a imaginária de *z* for NaN, e " "``False`` caso contrário." -#: ../../library/cmath.rst:220 +#: ../../library/cmath.rst:271 msgid "" "Return ``True`` if the values *a* and *b* are close to each other and " "``False`` otherwise." @@ -327,45 +615,46 @@ msgstr "" "Retorna ``True`` se os valores *a* e *b* estiverem próximos e ``False`` caso " "contrário." -#: ../../library/cmath.rst:223 +#: ../../library/cmath.rst:274 msgid "" "Whether or not two values are considered close is determined according to " -"given absolute and relative tolerances." +"given absolute and relative tolerances. If no errors occur, the result will " +"be: ``abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)``." msgstr "" -"Se dois valores são ou não considerados próximos, é determinado de acordo " -"com as tolerâncias absoluta e relativa fornecidas." +"Se dois valores são considerados próximos ou não é determinado de acordo com " +"tolerâncias absolutas e relativas fornecidas. Se nenhum erro ocorrer, o " +"resultado será: ``abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)``." -#: ../../library/cmath.rst:226 +#: ../../library/cmath.rst:278 msgid "" "*rel_tol* is the relative tolerance -- it is the maximum allowed difference " "between *a* and *b*, relative to the larger absolute value of *a* or *b*. " "For example, to set a tolerance of 5%, pass ``rel_tol=0.05``. The default " "tolerance is ``1e-09``, which assures that the two values are the same " -"within about 9 decimal digits. *rel_tol* must be greater than zero." +"within about 9 decimal digits. *rel_tol* must be nonnegative and less than " +"``1.0``." msgstr "" "*rel_tol* é a tolerância relativa -- é a diferença máxima permitida entre " "*a* e *b*, em relação ao maior valor absoluto de *a* ou *b*. Por exemplo, " "para definir uma tolerância de 5%, passe ``rel_tol=0.05``. A tolerância " "padrão é ``1e-09``, o que garante que os dois valores sejam iguais em cerca " -"de 9 dígitos decimais. *rel_tol* deve ser maior que zero." +"de 9 dígitos decimais. *rel_tol* deve ser não negativo e menor que ``1.0``." -#: ../../library/cmath.rst:232 +#: ../../library/cmath.rst:285 msgid "" -"*abs_tol* is the minimum absolute tolerance -- useful for comparisons near " -"zero. *abs_tol* must be at least zero." +"*abs_tol* is the absolute tolerance; it defaults to ``0.0`` and it must be " +"nonnegative. When comparing ``x`` to ``0.0``, ``isclose(x, 0)`` is computed " +"as ``abs(x) <= rel_tol * abs(x)``, which is ``False`` for any ``x`` and " +"rel_tol less than ``1.0``. So add an appropriate positive abs_tol argument " +"to the call." msgstr "" -"*abs_tol* é a tolerância absoluta mínima -- útil para comparações próximas a " -"zero. *abs_tol* deve ser pelo menos zero." +"*abs_tol* é a tolerância absoluta; o padrão é ``0.0`` e deve ser não " +"negativo. Ao comparar ``x`` com ``0.0``, ``isclose(x, 0)`` é computado como " +"``abs(x) <= rel_tol * abs(x)``, que é ``False`` para qualquer ``x`` e " +"rel_tol menor que ``1.0``. Então adicione um argumento abs_tol positivo " +"apropriado à chamada." -#: ../../library/cmath.rst:235 -msgid "" -"If no errors occur, the result will be: ``abs(a-b) <= max(rel_tol * " -"max(abs(a), abs(b)), abs_tol)``." -msgstr "" -"Se nenhum erro ocorrer, o resultado será: ``abs(a-b) <= max(rel_tol * " -"max(abs(a), abs(b)), abs_tol)``." - -#: ../../library/cmath.rst:238 +#: ../../library/cmath.rst:291 msgid "" "The IEEE 754 special values of ``NaN``, ``inf``, and ``-inf`` will be " "handled according to IEEE rules. Specifically, ``NaN`` is not considered " @@ -377,55 +666,55 @@ msgstr "" "considerado próximo a qualquer outro valor, incluindo ``NaN``. ``inf`` e ``-" "inf`` são considerados apenas próximos a si mesmos." -#: ../../library/cmath.rst:247 +#: ../../library/cmath.rst:300 msgid ":pep:`485` -- A function for testing approximate equality" msgstr ":pep:`485` -- Uma função para testar igualdade aproximada" -#: ../../library/cmath.rst:251 +#: ../../library/cmath.rst:304 msgid "Constants" msgstr "Constantes" -#: ../../library/cmath.rst:255 +#: ../../library/cmath.rst:308 msgid "The mathematical constant *π*, as a float." msgstr "A constante matemática *π*, como um ponto flutuante." -#: ../../library/cmath.rst:260 +#: ../../library/cmath.rst:313 msgid "The mathematical constant *e*, as a float." msgstr "A constante matemática *e*, como um ponto flutuante." -#: ../../library/cmath.rst:265 +#: ../../library/cmath.rst:318 msgid "The mathematical constant *τ*, as a float." msgstr "A constante matemática *τ*, como um ponto flutuante." -#: ../../library/cmath.rst:272 +#: ../../library/cmath.rst:325 msgid "Floating-point positive infinity. Equivalent to ``float('inf')``." -msgstr "Infinito positivo de ponto flutuante. Equivalente a ``float('inf')``." +msgstr "Infinito positivo de ponto flutuante. Equivale a ``float('inf')``." -#: ../../library/cmath.rst:279 +#: ../../library/cmath.rst:332 msgid "" "Complex number with zero real part and positive infinity imaginary part. " "Equivalent to ``complex(0.0, float('inf'))``." msgstr "" "Número complexo com parte real zero e parte imaginária infinita positiva. " -"Equivalente a ``complex(0.0, float('inf'))``." +"Equivale a ``complex(0.0, float('inf'))``." -#: ../../library/cmath.rst:287 +#: ../../library/cmath.rst:340 msgid "" "A floating-point \"not a number\" (NaN) value. Equivalent to " "``float('nan')``." msgstr "" -"Um valor de ponto flutuante \"não um número\" (NaN). Equivalente a " +"Um valor de ponto flutuante \"não um número\" (NaN). Equivale a " "``float('nan')``." -#: ../../library/cmath.rst:295 +#: ../../library/cmath.rst:348 msgid "" "Complex number with zero real part and NaN imaginary part. Equivalent to " "``complex(0.0, float('nan'))``." msgstr "" -"Número complexo com parte real zero e parte imaginária NaN. Equivalente a " +"Número complexo com parte real zero e parte imaginária NaN. Equivale a " "``complex(0.0, float('nan'))``." -#: ../../library/cmath.rst:303 +#: ../../library/cmath.rst:356 msgid "" "Note that the selection of functions is similar, but not identical, to that " "in module :mod:`math`. The reason for having two modules is that some users " @@ -438,13 +727,13 @@ msgid "" msgstr "" "Observe que a seleção de funções é semelhante, mas não idêntica, àquela no " "módulo :mod:`math`. A razão para ter dois módulos é que alguns usuários não " -"estão interessados ​​em números complexos e talvez nem saibam o que são. Eles " +"estão interessados em números complexos e talvez nem saibam o que são. Eles " "preferem que ``math.sqrt(-1)`` gere uma exceção do que retorne um número " "complexo. Observe também que as funções definidas em :mod:`cmath` sempre " "retornam um número complexo, mesmo que a resposta possa ser expressa como um " "número real (nesse caso o número complexo tem uma parte imaginária de zero)." -#: ../../library/cmath.rst:311 +#: ../../library/cmath.rst:364 msgid "" "A note on branch cuts: They are curves along which the given function fails " "to be continuous. They are a necessary feature of many complex functions. " @@ -458,11 +747,11 @@ msgstr "" "dada não é contínua. Eles são um recurso necessário de muitas funções " "complexas. Presume-se que se você precisar calcular com funções complexas, " "você entenderá sobre cortes de ramificação. Consulte quase qualquer livro " -"(não muito elementar) sobre variáveis ​​complexas para obter esclarecimento. " +"(não muito elementar) sobre variáveis complexas para obter esclarecimento. " "Para informações sobre a escolha adequada dos cortes de ramificação para " "fins numéricos, uma boa referência deve ser a seguinte:" -#: ../../library/cmath.rst:321 +#: ../../library/cmath.rst:374 msgid "" "Kahan, W: Branch cuts for complex elementary functions; or, Much ado about " "nothing's sign bit. In Iserles, A., and Powell, M. (eds.), The state of the " @@ -472,10 +761,10 @@ msgstr "" "nothing's sign bit. Em Iserles, A. e Powell, M. (eds.), The state of the " "art in numerical analysis. Clarendon Press (1987) pp165--211." -#: ../../library/cmath.rst:301 +#: ../../library/cmath.rst:354 msgid "module" msgstr "módulo" -#: ../../library/cmath.rst:301 +#: ../../library/cmath.rst:354 msgid "math" msgstr "math" diff --git a/library/cmd.po b/library/cmd.po index c5c87d21d..44507d01c 100644 --- a/library/cmd.po +++ b/library/cmd.po @@ -1,33 +1,32 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 -# Rafael Fontenelle , 2023 -# Adorilson Bezerra , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 02:33+0000\n" -"PO-Revision-Date: 2021-06-28 00:56+0000\n" -"Last-Translator: Adorilson Bezerra , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/cmd.rst:2 msgid ":mod:`!cmd` --- Support for line-oriented command interpreters" msgstr "" +":mod:`!cmd` --- Suporte para interpretadores de comando orientado a linhas" #: ../../library/cmd.rst:9 msgid "**Source code:** :source:`Lib/cmd.py`" @@ -40,6 +39,10 @@ msgid "" "administrative tools, and prototypes that will later be wrapped in a more " "sophisticated interface." msgstr "" +"A classe :class:`Cmd` fornece um framework simples para escrever " +"interpretadores de comando orientados a linhas. Eles são frequentemente " +"úteis para melhorar testes, ferramentas administrativas e protótipos que " +"mais tarde serão encapsulados em uma interface mais sofisticada." #: ../../library/cmd.rst:20 msgid "" @@ -49,6 +52,11 @@ msgid "" "yourself in order to inherit :class:`Cmd`'s methods and encapsulate action " "methods." msgstr "" +"Uma instância de :class:`Cmd` ou instância de sua subclasse é um framework " +"de interpretador orientado a linhas. Não há um bom motivo para instanciar :" +"class:`Cmd` em si; em vez disso, ele é útil como uma superclasse de uma " +"classe de interpretador que você mesmo define para herdar os métodos de :" +"class:`Cmd` e encapsular métodos de ação." #: ../../library/cmd.rst:25 msgid "" @@ -57,6 +65,10 @@ msgid "" "`None` and :mod:`readline` is available, command completion is done " "automatically." msgstr "" +"O argumento opcional *completekey* é o nome :mod:`readline` de uma chave de " +"conclusão; o padrão é :kbd:`Tab`. Se *completekey* não for :const:`None` e :" +"mod:`readline` estiver disponível, a conclusão do comando será feita " +"automaticamente." #: ../../library/cmd.rst:29 msgid "" @@ -66,6 +78,11 @@ msgid "" "``'tab'``. Note that other values are not treated this way, and might only " "work with a specific backend." msgstr "" +"O padrão, ``'tab'``, é tratado especialmente, de modo que se refere à tecla :" +"kbd:`Tab` em cada :data:`readline.backend`. Especificamente, se :data:" +"`readline.backend` for ``editline``, ``Cmd`` usará ``'^I'`` em vez de " +"``'tab'``. Observe que outros valores não são tratados dessa forma e podem " +"funcionar apenas com um backend específico." #: ../../library/cmd.rst:36 msgid "" @@ -74,6 +91,10 @@ msgid "" "and output. If not specified, they will default to :data:`sys.stdin` and :" "data:`sys.stdout`." msgstr "" +"Os argumentos opcionais *stdin* e *stdout* especificam os objetos arquivo de " +"entrada e saída que a instância Cmd ou instância de sua subclasse usará para " +"entrada e saída. Se não forem especificados, eles serão padronizados para :" +"data:`sys.stdin` e :data:`sys.stdout`." #: ../../library/cmd.rst:41 msgid "" @@ -81,10 +102,13 @@ msgid "" "attr:`use_rawinput` attribute to ``False``, otherwise *stdin* will be " "ignored." msgstr "" +"Se você quiser que um determinado *stdin* seja usado, certifique-se de " +"definir o atributo :attr:`use_rawinput` da instância como ``False``, caso " +"contrário, *stdin* será ignorado." #: ../../library/cmd.rst:45 msgid "``completekey='tab'`` is replaced by ``'^I'`` for ``editline``." -msgstr "" +msgstr "``completekey='tab'`` é substituído por ``'^I'`` para ``editline``." #: ../../library/cmd.rst:52 msgid "Cmd Objects" @@ -92,7 +116,7 @@ msgstr "Objetos Cmd" #: ../../library/cmd.rst:54 msgid "A :class:`Cmd` instance has the following methods:" -msgstr "" +msgstr "Uma instância :class:`Cmd` tem os seguintes métodos:" #: ../../library/cmd.rst:59 msgid "" @@ -100,12 +124,17 @@ msgid "" "received input, and dispatch to action methods, passing them the remainder " "of the line as argument." msgstr "" +"Emite um prompt repetidamente, aceite a entrada, analise um prefixo inicial " +"da entrada recebida e despache para métodos de ação, passando a eles o " +"restante da linha como argumento." #: ../../library/cmd.rst:63 msgid "" "The optional argument is a banner or intro string to be issued before the " "first prompt (this overrides the :attr:`intro` class attribute)." msgstr "" +"O argumento opcional é um banner ou uma string de introdução a ser emitida " +"antes do primeiro prompt (isso substitui o atributo de classe :attr:`intro`)." #: ../../library/cmd.rst:66 msgid "" @@ -115,10 +144,16 @@ msgid "" "`Control-F` moves the cursor to the right non-destructively, :kbd:`Control-" "B` moves the cursor to the left non-destructively, etc.)." msgstr "" +"Se o módulo :mod:`readline` for carregado, a entrada vai herdar " +"automaticamente a edição de lista de histórico semelhante a :program:`bash` " +"(por exemplo, :kbd:`Control-P` retorna ao último comando, :kbd:`Control-N` " +"avança para o próximo, :kbd:`Control-F` move o cursor para a direita de " +"forma não destrutiva, :kbd:`Control-B` move o cursor para a esquerda de " +"forma não destrutiva, etc.)." #: ../../library/cmd.rst:72 msgid "An end-of-file on input is passed back as the string ``'EOF'``." -msgstr "" +msgstr "Um fim de arquivo na entrada é retornado como a string ``'EOF'``." #: ../../library/cmd.rst:78 msgid "" @@ -128,6 +163,12 @@ msgid "" "another special case, a line beginning with the character ``'!'`` is " "dispatched to the method :meth:`!do_shell` (if such a method is defined)." msgstr "" +"Uma instância de interpretador reconhecerá um comando chamado ``foo`` se e " +"somente se ele tiver um método :meth:`!do_foo`. Como um caso especial, uma " +"linha começando com o caractere ``'?'`` é despachada para o método :meth:" +"`do_help`. Como outro caso especial, uma linha começando com o caractere " +"``'!'`` é despachada para o método :meth:`!do_shell` (se tal método for " +"definido)." #: ../../library/cmd.rst:84 msgid "" @@ -135,6 +176,9 @@ msgid "" "value. The *stop* argument to :meth:`postcmd` is the return value from the " "command's corresponding :meth:`!do_\\*` method." msgstr "" +"Este método retornará quando o método :meth:`postcmd` retornar um valor " +"true. O argumento *stop* para :meth:`postcmd` é o valor de retorno do " +"método :meth:`!do_\\*` correspondente do comando." #: ../../library/cmd.rst:88 msgid "" @@ -147,6 +191,15 @@ msgid "" "could be used to provide different completion depending upon which position " "the argument is in." msgstr "" +"Se o autocompletamento estiver habilitado, os comandos serão completados " +"automaticamente, e o autocompletamento dos argumentos dos comandos será " +"feito chamando :meth:`!complete_foo` com os argumentos *text*, *line*, " +"*begidx* e *endidx*. *text* é o prefixo da string que estamos tentando " +"corresponder: todas as correspondências retornadas devem começar com ele. " +"*line* é a linha de entrada atual com os espaços em branco iniciais " +"removidos, *begidx* e *endidx* são os índices inicial e final do texto de " +"prefixo, que podem ser usados para fornecer diferentes autocompletamentos " +"dependendo da posição em que o argumento está." #: ../../library/cmd.rst:99 msgid "" @@ -158,6 +211,13 @@ msgid "" "help_\\*` methods or commands that have docstrings), and also lists any " "undocumented commands." msgstr "" +"Todas as subclasses de :class:`Cmd` herdam um :meth:`!do_help` predefinido. " +"Este método, chamado com um argumento ``'bar'``, invoca o método " +"correspondente :meth:`!help_bar`, e se este não estiver presente, imprime a " +"docstring de :meth:`!do_bar`, se disponível. Sem argumento, :meth:`!do_help` " +"lista todos os tópicos de ajuda disponíveis (isto é, todos os comandos com " +"métodos :meth:`!help_\\*` correspondentes ou comandos que têm docstrings), e " +"também lista quaisquer comandos não documentados." #: ../../library/cmd.rst:110 msgid "" @@ -169,24 +229,40 @@ msgid "" "command *str*, the return value of that method is returned, otherwise the " "return value from the :meth:`default` method is returned." msgstr "" +"Interpreta o argumento como se tivesse sido digitado em resposta ao prompt. " +"Isso pode ser substituído, mas normalmente não precisa ser; veja os métodos :" +"meth:`precmd` e :meth:`postcmd` para ganchos de execução úteis. O valor de " +"retorno é um sinalizador que indica se a interpretação de comandos pelo " +"interpretador deve parar. Se houver um método :meth:`!do_\\*` para o comando " +"*str*, o valor de retorno desse método é retornado, caso contrário, o valor " +"de retorno do método :meth:`default` é retornado." #: ../../library/cmd.rst:121 msgid "" "Method called when an empty line is entered in response to the prompt. If " "this method is not overridden, it repeats the last nonempty command entered." msgstr "" +"Método chamado quando uma linha vazia é inserida em resposta ao prompt. Se " +"esse método não for substituído, ele repete o último comando não vazio " +"inserido." #: ../../library/cmd.rst:127 msgid "" "Method called on an input line when the command prefix is not recognized. If " "this method is not overridden, it prints an error message and returns." msgstr "" +"Método chamado em uma linha de entrada quando o prefixo do comando não é " +"reconhecido. Se esse método não for substituído, ele imprime uma mensagem de " +"erro e retorna." #: ../../library/cmd.rst:133 msgid "" "Method called to complete an input line when no command-specific :meth:`!" "complete_\\*` method is available. By default, it returns an empty list." msgstr "" +"Método chamado para completar uma linha de entrada quando nenhum método :" +"meth:`!complete_\\*` especificado pelo comando está disponível. Por padrão, " +"ele retorna uma lista vazia." #: ../../library/cmd.rst:139 msgid "" @@ -194,6 +270,9 @@ msgid "" "column is only as wide as necessary. Columns are separated by two spaces for " "readability." msgstr "" +"Método chamado para exibir uma lista de strings como um conjunto compacto de " +"colunas. Cada coluna tem apenas a largura necessária. As colunas são " +"separadas por dois espaços para legibilidade." #: ../../library/cmd.rst:146 msgid "" @@ -204,6 +283,12 @@ msgid "" "the :meth:`precmd` implementation may re-write the command or simply return " "*line* unchanged." msgstr "" +"Método gancho executado logo antes da linha de comando *line* ser " +"interpretada, mas depois que o prompt de entrada é gerado e emitido. Este " +"método é um stub em :class:`Cmd`; ele existe para ser substituído por " +"subclasses. O valor de retorno é usado como o comando que será executado " +"pelo método :meth:`onecmd`; a implementação :meth:`precmd` pode reescrever o " +"comando ou simplesmente retornar *line* inalterado." #: ../../library/cmd.rst:156 msgid "" @@ -215,35 +300,51 @@ msgid "" "this method will be used as the new value for the internal flag which " "corresponds to *stop*; returning false will cause interpretation to continue." msgstr "" +"Método gancho executado logo após o término do despacho de um comando. Este " +"método é um stub em :class:`Cmd`; ele existe para ser substituído por " +"subclasses. *line* é a linha de comando que foi executada, e *stop* é um " +"sinalizador que indica se a execução será encerrada após a chamada para :" +"meth:`postcmd`; este será o valor de retorno do método :meth:`onecmd`. O " +"valor de retorno deste método será usado como o novo valor para o " +"sinalizador interno que corresponde a *stop*; retornar false fará com que a " +"interpretação continue." #: ../../library/cmd.rst:167 msgid "" "Hook method executed once when :meth:`cmdloop` is called. This method is a " "stub in :class:`Cmd`; it exists to be overridden by subclasses." msgstr "" +"Método gancho executado uma vez quando :meth:`cmdloop` é chamado. Este " +"método é um stub em :class:`Cmd`; ele existe para ser substituído por " +"subclasses." #: ../../library/cmd.rst:173 msgid "" "Hook method executed once when :meth:`cmdloop` is about to return. This " "method is a stub in :class:`Cmd`; it exists to be overridden by subclasses." msgstr "" +"Método gancho executado uma vez quando :meth:`cmdloop` está para ser " +"retornado. Este método é um stub em :class:`Cmd`; ele existe para ser " +"substituído por subclasses." #: ../../library/cmd.rst:177 msgid "" "Instances of :class:`Cmd` subclasses have some public instance variables:" msgstr "" +"Instâncias das subclasses :class:`Cmd` têm algumas variáveis de instância " +"públicas:" #: ../../library/cmd.rst:181 msgid "The prompt issued to solicit input." -msgstr "" +msgstr "O prompt emitido para solicitar informações." #: ../../library/cmd.rst:186 msgid "The string of characters accepted for the command prefix." -msgstr "" +msgstr "A sequência de caracteres aceita para o prefixo do comando." #: ../../library/cmd.rst:191 msgid "The last nonempty command prefix seen." -msgstr "" +msgstr "O último prefixo de comando não vazio visto." #: ../../library/cmd.rst:196 msgid "" @@ -251,17 +352,25 @@ msgid "" "`cmdloop` when new input is needed; if it is nonempty, its elements will be " "processed in order, as if entered at the prompt." msgstr "" +"Uma lista de linhas de entrada enfileiradas. A lista cmdqueue é verificada " +"em :meth:`cmdloop` quando uma nova entrada é necessária; se não estiver " +"vazia, seus elementos serão processados em ordem, como se tivessem sido " +"inseridos no prompt." #: ../../library/cmd.rst:203 msgid "" "A string to issue as an intro or banner. May be overridden by giving the :" "meth:`cmdloop` method an argument." msgstr "" +"Uma string para emitir como uma introdução ou banner. Pode ser substituída " +"dando ao método :meth:`cmdloop` um argumento." #: ../../library/cmd.rst:209 msgid "" "The header to issue if the help output has a section for documented commands." msgstr "" +"O cabeçalho a ser emitido se a saída de ajuda tiver uma seção para comandos " +"documentados." #: ../../library/cmd.rst:214 msgid "" @@ -269,6 +378,9 @@ msgid "" "topics (that is, there are :meth:`!help_\\*` methods without corresponding :" "meth:`!do_\\*` methods)." msgstr "" +"O cabeçalho a ser emitido se a saída de ajuda tiver uma seção para tópicos " +"de ajuda diversos (ou seja, há métodos :meth:`!help_\\*` sem métodos :meth:`!" +"do_\\*` correspondentes)." #: ../../library/cmd.rst:221 msgid "" @@ -276,12 +388,18 @@ msgid "" "commands (that is, there are :meth:`!do_\\*` methods without corresponding :" "meth:`!help_\\*` methods)." msgstr "" +"O cabeçalho a ser emitido se a saída de ajuda tiver uma seção para comandos " +"não documentados (ou seja, houver métodos :meth:`!do_\\*` sem métodos :meth:" +"`!help_\\*` correspondentes)." #: ../../library/cmd.rst:228 msgid "" "The character used to draw separator lines under the help-message headers. " "If empty, no ruler line is drawn. It defaults to ``'='``." msgstr "" +"O caractere usado para desenhar linhas separadoras sob os cabeçalhos de " +"mensagem de ajuda. Se estiver vazio, nenhuma linha de régua será desenhada. " +"O padrão é ``'='``." #: ../../library/cmd.rst:234 msgid "" @@ -292,6 +410,12 @@ msgid "" "the interpreter will automatically support :program:`Emacs`\\ -like line " "editing and command-history keystrokes.)" msgstr "" +"Um sinalizador, com padrão true. Se true, :meth:`cmdloop` usa :func:`input` " +"para exibir um prompt e ler o próximo comando; se false, :data:`sys.stdout." +"write() ` e :data:`sys.stdin.readline() ` são usados. " +"(Isso significa que ao importar :mod:`readline`, em sistemas que o suportam, " +"o interpretador suportará automaticamente edição de linha no estilo :program:" +"`Emacs` e pressionamentos de teclas de histórico de comando.)" #: ../../library/cmd.rst:244 msgid "Cmd Example" @@ -302,12 +426,16 @@ msgid "" "The :mod:`cmd` module is mainly useful for building custom shells that let a " "user work with a program interactively." msgstr "" +"O módulo :mod:`cmd` é útil principalmente para criar shells personalizados " +"que permitem ao usuário trabalhar com um programa interativamente." #: ../../library/cmd.rst:251 msgid "" "This section presents a simple example of how to build a shell around a few " "of the commands in the :mod:`turtle` module." msgstr "" +"Esta seção apresenta um exemplo simples de como construir um shell em torno " +"de alguns dos comandos do módulo :mod:`turtle`." #: ../../library/cmd.rst:254 msgid "" @@ -316,6 +444,10 @@ msgid "" "converted to a number and dispatched to the turtle module. The docstring is " "used in the help utility provided by the shell." msgstr "" +"Comandos básicos do turtle, como :meth:`~turtle.forward`, são adicionados a " +"uma subclasse de :class:`Cmd` com o método chamado :meth:`!do_forward`. O " +"argumento é convertido em um número e despachado para o módulo turtle. A " +"docstring é usada no utilitário de ajuda fornecido pelo shell." #: ../../library/cmd.rst:259 msgid "" @@ -325,6 +457,167 @@ msgid "" "do_playback` method reads the file and adds the recorded commands to the :" "attr:`~Cmd.cmdqueue` for immediate playback::" msgstr "" +"O exemplo também inclui um recurso básico de gravação e reprodução " +"implementado com o método :meth:`~Cmd.precmd` que é responsável por " +"converter a entrada para minúsculas e gravar os comandos em um arquivo. O " +"método :meth:`!do_playback` lê o arquivo e adiciona os comandos gravados ao :" +"attr:`~Cmd.cmdqueue` para reprodução imediata::" + +#: ../../library/cmd.rst:265 +msgid "" +"import cmd, sys\n" +"from turtle import *\n" +"\n" +"class TurtleShell(cmd.Cmd):\n" +" intro = 'Welcome to the turtle shell. Type help or ? to list commands." +"\\n'\n" +" prompt = '(turtle) '\n" +" file = None\n" +"\n" +" # ----- basic turtle commands -----\n" +" def do_forward(self, arg):\n" +" 'Move the turtle forward by the specified distance: FORWARD 10'\n" +" forward(*parse(arg))\n" +" def do_right(self, arg):\n" +" 'Turn turtle right by given number of degrees: RIGHT 20'\n" +" right(*parse(arg))\n" +" def do_left(self, arg):\n" +" 'Turn turtle left by given number of degrees: LEFT 90'\n" +" left(*parse(arg))\n" +" def do_goto(self, arg):\n" +" 'Move turtle to an absolute position with changing orientation. " +"GOTO 100 200'\n" +" goto(*parse(arg))\n" +" def do_home(self, arg):\n" +" 'Return turtle to the home position: HOME'\n" +" home()\n" +" def do_circle(self, arg):\n" +" 'Draw circle with given radius an options extent and steps: CIRCLE " +"50'\n" +" circle(*parse(arg))\n" +" def do_position(self, arg):\n" +" 'Print the current turtle position: POSITION'\n" +" print('Current position is %d %d\\n' % position())\n" +" def do_heading(self, arg):\n" +" 'Print the current turtle heading in degrees: HEADING'\n" +" print('Current heading is %d\\n' % (heading(),))\n" +" def do_color(self, arg):\n" +" 'Set the color: COLOR BLUE'\n" +" color(arg.lower())\n" +" def do_undo(self, arg):\n" +" 'Undo (repeatedly) the last turtle action(s): UNDO'\n" +" def do_reset(self, arg):\n" +" 'Clear the screen and return turtle to center: RESET'\n" +" reset()\n" +" def do_bye(self, arg):\n" +" 'Stop recording, close the turtle window, and exit: BYE'\n" +" print('Thank you for using Turtle')\n" +" self.close()\n" +" bye()\n" +" return True\n" +"\n" +" # ----- record and playback -----\n" +" def do_record(self, arg):\n" +" 'Save future commands to filename: RECORD rose.cmd'\n" +" self.file = open(arg, 'w')\n" +" def do_playback(self, arg):\n" +" 'Playback commands from a file: PLAYBACK rose.cmd'\n" +" self.close()\n" +" with open(arg) as f:\n" +" self.cmdqueue.extend(f.read().splitlines())\n" +" def precmd(self, line):\n" +" line = line.lower()\n" +" if self.file and 'playback' not in line:\n" +" print(line, file=self.file)\n" +" return line\n" +" def close(self):\n" +" if self.file:\n" +" self.file.close()\n" +" self.file = None\n" +"\n" +"def parse(arg):\n" +" 'Convert a series of zero or more numbers to an argument tuple'\n" +" return tuple(map(int, arg.split()))\n" +"\n" +"if __name__ == '__main__':\n" +" TurtleShell().cmdloop()" +msgstr "" +"import cmd, sys\n" +"from turtle import *\n" +"\n" +"class TurtleShell(cmd.Cmd):\n" +" intro = 'Welcome to the turtle shell. Type help or ? to list commands." +"\\n'\n" +" prompt = '(turtle) '\n" +" file = None\n" +"\n" +" # ----- comandos básicos do turtle -----\n" +" def do_forward(self, arg):\n" +" 'Move the turtle forward by the specified distance: FORWARD 10'\n" +" forward(*parse(arg))\n" +" def do_right(self, arg):\n" +" 'Turn turtle right by given number of degrees: RIGHT 20'\n" +" right(*parse(arg))\n" +" def do_left(self, arg):\n" +" 'Turn turtle left by given number of degrees: LEFT 90'\n" +" left(*parse(arg))\n" +" def do_goto(self, arg):\n" +" 'Move turtle to an absolute position with changing orientation. " +"GOTO 100 200'\n" +" goto(*parse(arg))\n" +" def do_home(self, arg):\n" +" 'Return turtle to the home position: HOME'\n" +" home()\n" +" def do_circle(self, arg):\n" +" 'Draw circle with given radius an options extent and steps: CIRCLE " +"50'\n" +" circle(*parse(arg))\n" +" def do_position(self, arg):\n" +" 'Print the current turtle position: POSITION'\n" +" print('Current position is %d %d\\n' % position())\n" +" def do_heading(self, arg):\n" +" 'Print the current turtle heading in degrees: HEADING'\n" +" print('Current heading is %d\\n' % (heading(),))\n" +" def do_color(self, arg):\n" +" 'Set the color: COLOR BLUE'\n" +" color(arg.lower())\n" +" def do_undo(self, arg):\n" +" 'Undo (repeatedly) the last turtle action(s): UNDO'\n" +" def do_reset(self, arg):\n" +" 'Clear the screen and return turtle to center: RESET'\n" +" reset()\n" +" def do_bye(self, arg):\n" +" 'Stop recording, close the turtle window, and exit: BYE'\n" +" print('Thank you for using Turtle')\n" +" self.close()\n" +" bye()\n" +" return True\n" +"\n" +" # ----- registra e reproduz -----\n" +" def do_record(self, arg):\n" +" 'Save future commands to filename: RECORD rose.cmd'\n" +" self.file = open(arg, 'w')\n" +" def do_playback(self, arg):\n" +" 'Playback commands from a file: PLAYBACK rose.cmd'\n" +" self.close()\n" +" with open(arg) as f:\n" +" self.cmdqueue.extend(f.read().splitlines())\n" +" def precmd(self, line):\n" +" line = line.lower()\n" +" if self.file and 'playback' not in line:\n" +" print(line, file=self.file)\n" +" return line\n" +" def close(self):\n" +" if self.file:\n" +" self.file.close()\n" +" self.file = None\n" +"\n" +"def parse(arg):\n" +" 'Convert a series of zero or more numbers to an argument tuple'\n" +" return tuple(map(int, arg.split()))\n" +"\n" +"if __name__ == '__main__':\n" +" TurtleShell().cmdloop()" #: ../../library/cmd.rst:340 msgid "" @@ -332,6 +625,127 @@ msgid "" "using blank lines to repeat commands, and the simple record and playback " "facility:" msgstr "" +"Aqui está uma sessão de exemplo com o shell do turtle mostrando as funções " +"de ajuda, usando linhas em branco para repetir comandos e o recurso simples " +"de gravação e reprodução:" + +#: ../../library/cmd.rst:343 +msgid "" +"Welcome to the turtle shell. Type help or ? to list commands.\n" +"\n" +"(turtle) ?\n" +"\n" +"Documented commands (type help ):\n" +"========================================\n" +"bye color goto home playback record right\n" +"circle forward heading left position reset undo\n" +"\n" +"(turtle) help forward\n" +"Move the turtle forward by the specified distance: FORWARD 10\n" +"(turtle) record spiral.cmd\n" +"(turtle) position\n" +"Current position is 0 0\n" +"\n" +"(turtle) heading\n" +"Current heading is 0\n" +"\n" +"(turtle) reset\n" +"(turtle) circle 20\n" +"(turtle) right 30\n" +"(turtle) circle 40\n" +"(turtle) right 30\n" +"(turtle) circle 60\n" +"(turtle) right 30\n" +"(turtle) circle 80\n" +"(turtle) right 30\n" +"(turtle) circle 100\n" +"(turtle) right 30\n" +"(turtle) circle 120\n" +"(turtle) right 30\n" +"(turtle) circle 120\n" +"(turtle) heading\n" +"Current heading is 180\n" +"\n" +"(turtle) forward 100\n" +"(turtle)\n" +"(turtle) right 90\n" +"(turtle) forward 100\n" +"(turtle)\n" +"(turtle) right 90\n" +"(turtle) forward 400\n" +"(turtle) right 90\n" +"(turtle) forward 500\n" +"(turtle) right 90\n" +"(turtle) forward 400\n" +"(turtle) right 90\n" +"(turtle) forward 300\n" +"(turtle) playback spiral.cmd\n" +"Current position is 0 0\n" +"\n" +"Current heading is 0\n" +"\n" +"Current heading is 180\n" +"\n" +"(turtle) bye\n" +"Thank you for using Turtle" +msgstr "" +"Welcome to the turtle shell. Type help or ? to list commands.\n" +"\n" +"(turtle) ?\n" +"\n" +"Documented commands (type help ):\n" +"========================================\n" +"bye color goto home playback record right\n" +"circle forward heading left position reset undo\n" +"\n" +"(turtle) help forward\n" +"Move the turtle forward by the specified distance: FORWARD 10\n" +"(turtle) record spiral.cmd\n" +"(turtle) position\n" +"Current position is 0 0\n" +"\n" +"(turtle) heading\n" +"Current heading is 0\n" +"\n" +"(turtle) reset\n" +"(turtle) circle 20\n" +"(turtle) right 30\n" +"(turtle) circle 40\n" +"(turtle) right 30\n" +"(turtle) circle 60\n" +"(turtle) right 30\n" +"(turtle) circle 80\n" +"(turtle) right 30\n" +"(turtle) circle 100\n" +"(turtle) right 30\n" +"(turtle) circle 120\n" +"(turtle) right 30\n" +"(turtle) circle 120\n" +"(turtle) heading\n" +"Current heading is 180\n" +"\n" +"(turtle) forward 100\n" +"(turtle)\n" +"(turtle) right 90\n" +"(turtle) forward 100\n" +"(turtle)\n" +"(turtle) right 90\n" +"(turtle) forward 400\n" +"(turtle) right 90\n" +"(turtle) forward 500\n" +"(turtle) right 90\n" +"(turtle) forward 400\n" +"(turtle) right 90\n" +"(turtle) forward 300\n" +"(turtle) playback spiral.cmd\n" +"Current position is 0 0\n" +"\n" +"Current heading is 0\n" +"\n" +"Current heading is 180\n" +"\n" +"(turtle) bye\n" +"Thank you for using Turtle" #: ../../library/cmd.rst:74 msgid "? (question mark)" @@ -339,7 +753,7 @@ msgstr "? (interrogação)" #: ../../library/cmd.rst:74 msgid "in a command interpreter" -msgstr "" +msgstr "em um interpretador de comandos" #: ../../library/cmd.rst:74 msgid "! (exclamation)" diff --git a/library/cmdline.po b/library/cmdline.po index 3def8e9fd..0a857b70c 100644 --- a/library/cmdline.po +++ b/library/cmdline.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2023-10-13 14:16+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-08 03:57+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -68,8 +68,8 @@ msgid ":ref:`dis `" msgstr ":ref:`dis `" #: ../../library/cmdline.rst:16 -msgid ":mod:`doctest`" -msgstr ":mod:`doctest`" +msgid ":ref:`doctest `" +msgstr ":ref:`doctest `" #: ../../library/cmdline.rst:17 msgid ":mod:`!encodings.rot_13`" @@ -128,8 +128,8 @@ msgid ":ref:`pickletools `" msgstr ":ref:`pickletools `" #: ../../library/cmdline.rst:31 -msgid ":mod:`platform`" -msgstr ":mod:`platform`" +msgid ":ref:`platform `" +msgstr ":ref:`platform `" #: ../../library/cmdline.rst:32 msgid ":mod:`poplib`" @@ -176,62 +176,66 @@ msgid ":ref:`sqlite3 `" msgstr ":ref:`sqlite3 `" #: ../../library/cmdline.rst:43 +msgid ":ref:`symtable `" +msgstr ":ref:`symtable `" + +#: ../../library/cmdline.rst:44 msgid ":ref:`sysconfig `" msgstr ":ref:`sysconfig `" -#: ../../library/cmdline.rst:44 +#: ../../library/cmdline.rst:45 msgid ":mod:`tabnanny`" msgstr ":mod:`tabnanny`" -#: ../../library/cmdline.rst:45 +#: ../../library/cmdline.rst:46 msgid ":ref:`tarfile `" msgstr ":ref:`tarfile `" -#: ../../library/cmdline.rst:46 +#: ../../library/cmdline.rst:47 msgid ":mod:`!this`" msgstr ":mod:`!this`" -#: ../../library/cmdline.rst:47 +#: ../../library/cmdline.rst:48 msgid ":ref:`timeit `" msgstr ":ref:`timeit `" -#: ../../library/cmdline.rst:48 +#: ../../library/cmdline.rst:49 msgid ":ref:`tokenize `" msgstr ":ref:`tokenize `" -#: ../../library/cmdline.rst:49 +#: ../../library/cmdline.rst:50 msgid ":ref:`trace `" msgstr ":ref:`trace `" -#: ../../library/cmdline.rst:50 +#: ../../library/cmdline.rst:51 msgid ":mod:`turtledemo`" msgstr ":mod:`turtledemo`" -#: ../../library/cmdline.rst:51 +#: ../../library/cmdline.rst:52 msgid ":ref:`unittest `" msgstr ":ref:`unittest `" -#: ../../library/cmdline.rst:52 +#: ../../library/cmdline.rst:53 msgid ":ref:`uuid `" msgstr ":ref:`uuid `" -#: ../../library/cmdline.rst:53 +#: ../../library/cmdline.rst:54 msgid ":mod:`venv`" msgstr ":mod:`venv`" -#: ../../library/cmdline.rst:54 +#: ../../library/cmdline.rst:55 msgid ":mod:`webbrowser`" msgstr ":mod:`webbrowser`" -#: ../../library/cmdline.rst:55 +#: ../../library/cmdline.rst:56 msgid ":ref:`zipapp `" msgstr ":ref:`zipapp `" -#: ../../library/cmdline.rst:56 +#: ../../library/cmdline.rst:57 msgid ":ref:`zipfile `" msgstr ":ref:`zipfile `" -#: ../../library/cmdline.rst:58 +#: ../../library/cmdline.rst:59 msgid "See also the :ref:`Python command-line interface `." msgstr "" "Consulte também a :ref:`interface de linha de comando do Python , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../library/cmdlinelibs.rst:5 +msgid "Command Line Interface Libraries" +msgstr "Bibliotecas de interface de linha de comando" + +#: ../../library/cmdlinelibs.rst:7 +msgid "" +"The modules described in this chapter assist with implementing command line " +"and terminal interfaces for applications." +msgstr "" +"Os módulos descritos neste capítulo ajudam a implementar as interfaces de " +"linha de comando e de terminal para aplicações." + +#: ../../library/cmdlinelibs.rst:10 +msgid "Here's an overview:" +msgstr "Veja aqui uma visão geral:" diff --git a/library/code.po b/library/code.po index f09168e64..6ef0f84f0 100644 --- a/library/code.po +++ b/library/code.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-28 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:56+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -60,7 +59,15 @@ msgstr "" "recém-criado com a chave ``'__name__'`` definida com ``'__console__'`` e a " "chave ``'__doc__'`` definida com ``None``." -#: ../../library/code.rst:28 +#: ../../library/code.rst:25 +msgid "" +"Note that functions and classes objects created under an :class:`!" +"InteractiveInterpreter` instance will belong to the namespace specified by " +"*locals*. They are only pickleable if *locals* is the namespace of an " +"existing module." +msgstr "" + +#: ../../library/code.rst:34 msgid "" "Closely emulate the behavior of the interactive Python interpreter. This " "class builds on :class:`InteractiveInterpreter` and adds prompting using the " @@ -74,11 +81,11 @@ msgstr "" "entrada. Se *local_exit* for verdadeiro, ``exit()`` e ``quit()`` no console " "não levantarão :exc:`SystemExit`, mas retornarão ao código de chamada." -#: ../../library/code.rst:34 ../../library/code.rst:52 +#: ../../library/code.rst:40 ../../library/code.rst:58 msgid "Added *local_exit* parameter." msgstr "Adicionado o parâmetro *local_exit*." -#: ../../library/code.rst:39 +#: ../../library/code.rst:45 msgid "" "Convenience function to run a read-eval-print loop. This creates a new " "instance of :class:`InteractiveConsole` and sets *readfunc* to be used as " @@ -98,14 +105,14 @@ msgstr "" "para o laço do interpretador. Se *local_exit* for fornecido, ele será " "passado para o construtor :class:`InteractiveConsole`. O método :meth:" "`~InteractiveConsole.interact` da instância é então executado com *banner* e " -"*exitmsg* passados ​​como banner e mensagem de saída a serem usados, se " +"*exitmsg* passados como banner e mensagem de saída a serem usados, se " "fornecidos. O objeto console é descartado após o uso." -#: ../../library/code.rst:49 +#: ../../library/code.rst:55 msgid "Added *exitmsg* parameter." msgstr "Parâmetro adicionado *exitmsg*." -#: ../../library/code.rst:57 +#: ../../library/code.rst:63 msgid "" "This function is useful for programs that want to emulate Python's " "interpreter main loop (a.k.a. the read-eval-print loop). The tricky part is " @@ -121,7 +128,7 @@ msgstr "" "comando completo ou um erro de sintaxe). Esta função *quase* sempre toma a " "mesma decisão que o laço principal do interpretador real." -#: ../../library/code.rst:64 +#: ../../library/code.rst:70 msgid "" "*source* is the source string; *filename* is the optional filename from " "which source was read, defaulting to ``''``; and *symbol* is the " @@ -133,7 +140,7 @@ msgstr "" "opcional de início da gramática, que deve ser ``'single'`` (o padrão), " "``'eval'`` ou ``'exec'``." -#: ../../library/code.rst:69 +#: ../../library/code.rst:75 msgid "" "Returns a code object (the same as ``compile(source, filename, symbol)``) if " "the command is complete and valid; ``None`` if the command is incomplete; " @@ -147,11 +154,11 @@ msgstr "" "contém um erro de sintaxe, ou levanta :exc:`OverflowError` ou :exc:" "`ValueError` se o comando contiver um literal inválido." -#: ../../library/code.rst:79 +#: ../../library/code.rst:85 msgid "Interactive Interpreter Objects" msgstr "Objetos de interpretador interativo" -#: ../../library/code.rst:84 +#: ../../library/code.rst:90 msgid "" "Compile and run some source in the interpreter. Arguments are the same as " "for :func:`compile_command`; the default for *filename* is ``''``, " @@ -161,7 +168,7 @@ msgstr "" "de :func:`compile_command`; o padrão para *filename* é ``''``, e para " "*symbol* é ``'single'``. Uma de várias coisas pode acontecer:" -#: ../../library/code.rst:88 +#: ../../library/code.rst:94 msgid "" "The input is incorrect; :func:`compile_command` raised an exception (:exc:" "`SyntaxError` or :exc:`OverflowError`). A syntax traceback will be printed " @@ -173,7 +180,7 @@ msgstr "" "impresso chamando o método :meth:`showsyntaxerror`. :meth:`runsource` " "retorna ``False``." -#: ../../library/code.rst:93 +#: ../../library/code.rst:99 msgid "" "The input is incomplete, and more input is required; :func:`compile_command` " "returned ``None``. :meth:`runsource` returns ``True``." @@ -181,7 +188,7 @@ msgstr "" "A entrada está incompleta e são necessárias mais entradas; :func:" "`compile_command` retornou ``None``. :meth:`runsource` retorna ``True``." -#: ../../library/code.rst:96 +#: ../../library/code.rst:102 msgid "" "The input is complete; :func:`compile_command` returned a code object. The " "code is executed by calling the :meth:`runcode` (which also handles run-time " @@ -193,7 +200,7 @@ msgstr "" "de tempo de execução, exceto :exc:`SystemExit`). :meth:`runsource` retorna " "``False``." -#: ../../library/code.rst:100 +#: ../../library/code.rst:106 msgid "" "The return value can be used to decide whether to use ``sys.ps1`` or ``sys." "ps2`` to prompt the next line." @@ -201,7 +208,7 @@ msgstr "" "O valor de retorno pode ser usado para decidir se usar ``sys.ps1`` ou ``sys." "ps2`` para solicitar a próxima linha." -#: ../../library/code.rst:106 +#: ../../library/code.rst:112 msgid "" "Execute a code object. When an exception occurs, :meth:`showtraceback` is " "called to display a traceback. All exceptions are caught except :exc:" @@ -211,7 +218,7 @@ msgstr "" "chamado para exibir um traceback. Todas as exceções são capturadas, exceto :" "exc:`SystemExit`, que pode ser propagada." -#: ../../library/code.rst:110 +#: ../../library/code.rst:116 msgid "" "A note about :exc:`KeyboardInterrupt`: this exception may occur elsewhere in " "this code, and may not always be caught. The caller should be prepared to " @@ -221,7 +228,7 @@ msgstr "" "outro lugar neste código e nem sempre pode ser detectada. O chamador deve " "estar preparado para lidar com isso." -#: ../../library/code.rst:117 +#: ../../library/code.rst:123 msgid "" "Display the syntax error that just occurred. This does not display a stack " "trace because there isn't one for syntax errors. If *filename* is given, it " @@ -236,7 +243,7 @@ msgstr "" "sempre usa ``''`` ao ler uma string. A saída é escrita pelo método :" "meth:`write`." -#: ../../library/code.rst:126 +#: ../../library/code.rst:132 msgid "" "Display the exception that just occurred. We remove the first stack item " "because it is within the interpreter object implementation. The output is " @@ -246,7 +253,7 @@ msgstr "" "porque ele está dentro da implementação do objeto interpretador. A saída é " "escrita pelo método :meth:`write`." -#: ../../library/code.rst:130 +#: ../../library/code.rst:136 msgid "" "The full chained traceback is displayed instead of just the primary " "traceback." @@ -254,7 +261,7 @@ msgstr "" "O traceback encadeado completo é exibido em vez de apenas o traceback " "primário." -#: ../../library/code.rst:136 +#: ../../library/code.rst:142 msgid "" "Write a string to the standard error stream (``sys.stderr``). Derived " "classes should override this to provide the appropriate output handling as " @@ -264,11 +271,11 @@ msgstr "" "derivadas devem substituir isso para fornecer o tratamento de saída " "apropriado conforme necessário." -#: ../../library/code.rst:143 +#: ../../library/code.rst:149 msgid "Interactive Console Objects" msgstr "Objetos de console Interativo" -#: ../../library/code.rst:145 +#: ../../library/code.rst:151 msgid "" "The :class:`InteractiveConsole` class is a subclass of :class:" "`InteractiveInterpreter`, and so offers all the methods of the interpreter " @@ -278,7 +285,7 @@ msgstr "" "`InteractiveInterpreter` e, portanto, oferece todos os métodos dos objetos " "interpretadores, bem como as seguintes adições." -#: ../../library/code.rst:152 +#: ../../library/code.rst:158 msgid "" "Closely emulate the interactive Python console. The optional *banner* " "argument specify the banner to print before the first interaction; by " @@ -294,7 +301,7 @@ msgstr "" "entre parênteses (para não confundir isso com o interpretador real -- já que " "está tão próximo!)." -#: ../../library/code.rst:158 +#: ../../library/code.rst:164 msgid "" "The optional *exitmsg* argument specifies an exit message printed when " "exiting. Pass the empty string to suppress the exit message. If *exitmsg* is " @@ -304,15 +311,15 @@ msgstr "" "sair. Passe a string vazia para suprimir a mensagem de saída. Se *exitmsg* " "não for fornecido ou ``None``, uma mensagem padrão será impressa." -#: ../../library/code.rst:162 +#: ../../library/code.rst:168 msgid "To suppress printing any banner, pass an empty string." msgstr "Para suprimir a impressão de qualquer banner, passe uma string vazia." -#: ../../library/code.rst:165 +#: ../../library/code.rst:171 msgid "Print an exit message when exiting." msgstr "Imprime uma mensagem de saída ao sair." -#: ../../library/code.rst:171 +#: ../../library/code.rst:177 msgid "" "Push a line of source text to the interpreter. The line should not have a " "trailing newline; it may have internal newlines. The line is appended to a " @@ -334,11 +341,11 @@ msgstr "" "``True`` se mais entrada for necessária, ``False`` se a linha foi tratada de " "alguma forma (isto é o mesmo que :meth:`!runsource`)." -#: ../../library/code.rst:183 +#: ../../library/code.rst:189 msgid "Remove any unhandled source text from the input buffer." msgstr "Remove qualquer texto fonte não tratado do buffer de entrada." -#: ../../library/code.rst:188 +#: ../../library/code.rst:194 msgid "" "Write a prompt and read a line. The returned line does not include the " "trailing newline. When the user enters the EOF key sequence, :exc:" diff --git a/library/codecs.po b/library/codecs.po index 3869d84f1..9f514eced 100644 --- a/library/codecs.po +++ b/library/codecs.po @@ -1,32 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Welington Carlos , 2021 -# i17obot , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Marco Rougeth , 2022 -# Victor Matheus Castro , 2023 -# Rafael Fontenelle , 2023 -# Adorilson Bezerra , 2023 -# Vitor Buxbaum Orlandi, 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 02:33+0000\n" -"PO-Revision-Date: 2021-06-28 00:56+0000\n" -"Last-Translator: Vitor Buxbaum Orlandi, 2023\n" +"POT-Creation-Date: 2025-04-18 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -1552,7 +1545,7 @@ msgstr "855, IBM855" #: ../../library/codecs.rst:1106 ../../library/codecs.rst:1154 #: ../../library/codecs.rst:1219 ../../library/codecs.rst:1256 -msgid "Bulgarian, Byelorussian, Macedonian, Russian, Serbian" +msgid "Belarusian, Bulgarian, Macedonian, Russian, Serbian" msgstr "" #: ../../library/codecs.rst:1109 @@ -2664,8 +2657,8 @@ msgid "This module implements the ANSI codepage (CP_ACP)." msgstr "" #: ../../library/codecs.rst:1542 -msgid ":ref:`Availability `: Windows." -msgstr ":ref:`Disponibilidade `: Windows." +msgid "Availability" +msgstr "Disponibilidade" #: ../../library/codecs.rst:1544 msgid "" diff --git a/library/codeop.po b/library/codeop.po index ef5619620..36082e5a3 100644 --- a/library/codeop.po +++ b/library/codeop.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:56+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/collections.abc.po b/library/collections.abc.po index 70d449b92..4ad4c262c 100644 --- a/library/collections.abc.po +++ b/library/collections.abc.po @@ -1,34 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Vinícius Muniz de Melo , 2021 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-19 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 00:56+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-28 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/collections.abc.rst:2 msgid ":mod:`!collections.abc` --- Abstract Base Classes for Containers" -msgstr "" +msgstr ":mod:`!collections.abc` --- Classes Base Abstratas para Contêineres" #: ../../library/collections.abc.rst:10 msgid "Formerly, this module was part of the :mod:`collections` module." @@ -45,30 +42,107 @@ msgid "" "for example, whether it is :term:`hashable` or whether it is a :term:" "`mapping`." msgstr "" +"Esse módulo fornece :term:`classes base abstratas ` que " +"podem ser usadas para testar se uma classe fornece uma interface específica; " +"por exemplo, se é :term:`hasheável` ou se é um :term:`mapeamento`." #: ../../library/collections.abc.rst:27 msgid "" "An :func:`issubclass` or :func:`isinstance` test for an interface works in " "one of three ways." msgstr "" +"Um teste :func:`issubclass` ou :func:`isinstance` para uma interface " +"funciona em uma das três formas." #: ../../library/collections.abc.rst:30 msgid "" -"1) A newly written class can inherit directly from one of the abstract base " +"A newly written class can inherit directly from one of the abstract base " "classes. The class must supply the required abstract methods. The " "remaining mixin methods come from inheritance and can be overridden if " "desired. Other methods may be added as needed:" msgstr "" +"Uma classe recém-escrita pode herdar diretamente de uma das classes base " +"abstratas. A classe deve fornecer os métodos abstratos necessários. Os " +"métodos mixin restantes vêm da herança e podem ser substituídos se desejado. " +"Outros métodos podem ser adicionados conforme necessário:" + +#: ../../library/collections.abc.rst:35 +msgid "" +"class C(Sequence): # Direct inheritance\n" +" def __init__(self): ... # Extra method not required by the " +"ABC\n" +" def __getitem__(self, index): ... # Required abstract method\n" +" def __len__(self): ... # Required abstract method\n" +" def count(self, value): ... # Optionally override a mixin method" +msgstr "" +"class C(Sequence): # Herança direta\n" +" def __init__(self): ... # Método extra não exigido pela ABC\n" +" def __getitem__(self, index): ... # Método abstrato exigido\n" +" def __len__(self): ... # Método abstrato exigido\n" +" def count(self, value): ... # Opcionalmente substitui um método " +"mixin" + +#: ../../library/collections.abc.rst:43 +msgid "" +">>> issubclass(C, Sequence)\n" +"True\n" +">>> isinstance(C(), Sequence)\n" +"True" +msgstr "" +">>> issubclass(C, Sequence)\n" +"True\n" +">>> isinstance(C(), Sequence)\n" +"True" #: ../../library/collections.abc.rst:50 msgid "" -"2) Existing classes and built-in classes can be registered as \"virtual " +"Existing classes and built-in classes can be registered as \"virtual " "subclasses\" of the ABCs. Those classes should define the full API " "including all of the abstract methods and all of the mixin methods. This " "lets users rely on :func:`issubclass` or :func:`isinstance` tests to " "determine whether the full interface is supported. The exception to this " "rule is for methods that are automatically inferred from the rest of the API:" msgstr "" +"Classes existentes e classes embutidas podem ser registradas como " +"\"subclasses virtuais\" dos ABCs. Essas classes devem definir a API " +"completa, incluindo todos os métodos abstratos e todos os métodos mixin. " +"Isso permite que os usuários confiem nos testes :func:`issubclass` ou :func:" +"`isinstance` para determinar se a interface completa é suportada. A exceção " +"a essa regra é para métodos que são automaticamente inferidos do restante da " +"API:" + +#: ../../library/collections.abc.rst:58 +msgid "" +"class D: # No inheritance\n" +" def __init__(self): ... # Extra method not required by the " +"ABC\n" +" def __getitem__(self, index): ... # Abstract method\n" +" def __len__(self): ... # Abstract method\n" +" def count(self, value): ... # Mixin method\n" +" def index(self, value): ... # Mixin method\n" +"\n" +"Sequence.register(D) # Register instead of inherit" +msgstr "" +"class D: # Sem herança\n" +" def __init__(self): ... # Método extra exigido pela ABC\n" +" def __getitem__(self, index): ... # Método abstrato\n" +" def __len__(self): ... # Método abstrato\n" +" def count(self, value): ... # Método mixin\n" +" def index(self, value): ... # Método mixin\n" +"\n" +"Sequence.register(D) # Registra ao invés de herdar" + +#: ../../library/collections.abc.rst:69 +msgid "" +">>> issubclass(D, Sequence)\n" +"True\n" +">>> isinstance(D(), Sequence)\n" +"True" +msgstr "" +">>> issubclass(D, Sequence)\n" +"True\n" +">>> isinstance(D(), Sequence)\n" +"True" #: ../../library/collections.abc.rst:76 msgid "" @@ -78,14 +152,43 @@ msgid "" "`reversed` function automatically fall back to using ``__getitem__`` and " "``__len__``." msgstr "" +"Neste exemplo, a classe :class:`!D` não precisa definir ``__contains__``, " +"``__iter__`` e ``__reversed__`` porque o :ref:`operador in `, a " +"lógica :term:`iteration ` e a função :func:`reversed` retornam " +"automaticamente para o uso de ``__getitem__`` e ``__len__``." #: ../../library/collections.abc.rst:82 msgid "" -"3) Some simple interfaces are directly recognizable by the presence of the " +"Some simple interfaces are directly recognizable by the presence of the " "required methods (unless those methods have been set to :const:`None`):" msgstr "" +"Algumas interfaces simples são diretamente reconhecíveis pela presença dos " +"métodos necessários (a menos que esses métodos tenham sido definidos como :" +"const:`None`):" -#: ../../library/collections.abc.rst:99 +#: ../../library/collections.abc.rst:85 +msgid "" +"class E:\n" +" def __iter__(self): ...\n" +" def __next__(self): ..." +msgstr "" +"class E:\n" +" def __iter__(self): ...\n" +" def __next__(self): ..." + +#: ../../library/collections.abc.rst:91 +msgid "" +">>> issubclass(E, Iterable)\n" +"True\n" +">>> isinstance(E(), Iterable)\n" +"True" +msgstr "" +">>> issubclass(E, Iterable)\n" +"True\n" +">>> isinstance(E(), Iterable)\n" +"True" + +#: ../../library/collections.abc.rst:98 msgid "" "Complex interfaces do not support this last technique because an interface " "is more than just the presence of method names. Interfaces specify " @@ -94,186 +197,198 @@ msgid "" "class supplies ``__getitem__``, ``__len__``, and ``__iter__`` is " "insufficient for distinguishing a :class:`Sequence` from a :class:`Mapping`." msgstr "" +"Interfaces complexas não oferecem suporte a esta última técnica porque uma " +"interface é mais do que apenas a presença de nomes de métodos. Interfaces " +"especificam semântica e relacionamentos entre métodos que não podem ser " +"inferidos somente da presença de nomes de métodos específicos. Por exemplo, " +"saber que uma classe fornece ``__getitem__``, ``__len__`` e ``__iter__`` é " +"insuficiente para distinguir uma :class:`Sequence` de uma :class:`Mapping`." -#: ../../library/collections.abc.rst:107 +#: ../../library/collections.abc.rst:106 msgid "" "These abstract classes now support ``[]``. See :ref:`types-genericalias` " "and :pep:`585`." msgstr "" +"Essas classes abstratas agora oferecem suporte a ``[]``. Veja :ref:`types-" +"genericalias` e :pep:`585`." -#: ../../library/collections.abc.rst:114 +#: ../../library/collections.abc.rst:113 msgid "Collections Abstract Base Classes" msgstr "Classes Base Abstratas de Coleções" -#: ../../library/collections.abc.rst:116 +#: ../../library/collections.abc.rst:115 msgid "" "The collections module offers the following :term:`ABCs `:" msgstr "" "O módulo de coleções oferece o seguinte :term:`ABCs `:" -#: ../../library/collections.abc.rst:121 +#: ../../library/collections.abc.rst:120 msgid "ABC" msgstr "ABC" -#: ../../library/collections.abc.rst:121 +#: ../../library/collections.abc.rst:120 msgid "Inherits from" msgstr "Herda de" -#: ../../library/collections.abc.rst:121 +#: ../../library/collections.abc.rst:120 msgid "Abstract Methods" -msgstr "Métodos Abstratos" +msgstr "Métodos abstratos" -#: ../../library/collections.abc.rst:121 +#: ../../library/collections.abc.rst:120 msgid "Mixin Methods" -msgstr "Métodos Mixin" +msgstr "Métodos mixin" -#: ../../library/collections.abc.rst:123 +#: ../../library/collections.abc.rst:122 msgid ":class:`Container` [1]_" msgstr ":class:`Container` [1]_" -#: ../../library/collections.abc.rst:123 +#: ../../library/collections.abc.rst:122 msgid "``__contains__``" msgstr "``__contains__``" -#: ../../library/collections.abc.rst:124 +#: ../../library/collections.abc.rst:123 msgid ":class:`Hashable` [1]_" msgstr ":class:`Hashable` [1]_" -#: ../../library/collections.abc.rst:124 +#: ../../library/collections.abc.rst:123 msgid "``__hash__``" msgstr "``__hash__``" -#: ../../library/collections.abc.rst:125 +#: ../../library/collections.abc.rst:124 msgid ":class:`Iterable` [1]_ [2]_" msgstr ":class:`Iterable` [1]_ [2]_" -#: ../../library/collections.abc.rst:125 ../../library/collections.abc.rst:126 +#: ../../library/collections.abc.rst:124 ../../library/collections.abc.rst:125 msgid "``__iter__``" msgstr "``__iter__``" -#: ../../library/collections.abc.rst:126 +#: ../../library/collections.abc.rst:125 msgid ":class:`Iterator` [1]_" msgstr ":class:`Iterator` [1]_" -#: ../../library/collections.abc.rst:126 ../../library/collections.abc.rst:127 +#: ../../library/collections.abc.rst:125 ../../library/collections.abc.rst:126 msgid ":class:`Iterable`" msgstr ":class:`Iterable`" -#: ../../library/collections.abc.rst:126 +#: ../../library/collections.abc.rst:125 msgid "``__next__``" msgstr "``__next__``" -#: ../../library/collections.abc.rst:127 +#: ../../library/collections.abc.rst:126 msgid ":class:`Reversible` [1]_" msgstr ":class:`Reversible` [1]_" -#: ../../library/collections.abc.rst:127 +#: ../../library/collections.abc.rst:126 msgid "``__reversed__``" msgstr "``__reversed__``" -#: ../../library/collections.abc.rst:128 +#: ../../library/collections.abc.rst:127 msgid ":class:`Generator` [1]_" msgstr ":class:`Generator` [1]_" -#: ../../library/collections.abc.rst:128 +#: ../../library/collections.abc.rst:127 msgid ":class:`Iterator`" msgstr ":class:`Iterator`" -#: ../../library/collections.abc.rst:128 ../../library/collections.abc.rst:176 +#: ../../library/collections.abc.rst:127 ../../library/collections.abc.rst:176 msgid "``send``, ``throw``" msgstr "``send``, ``throw``" -#: ../../library/collections.abc.rst:128 +#: ../../library/collections.abc.rst:127 msgid "``close``, ``__iter__``, ``__next__``" msgstr "``close``, ``__iter__``, ``__next__``" -#: ../../library/collections.abc.rst:129 +#: ../../library/collections.abc.rst:128 msgid ":class:`Sized` [1]_" msgstr ":class:`Sized` [1]_" -#: ../../library/collections.abc.rst:129 ../../library/collections.abc.rst:168 +#: ../../library/collections.abc.rst:128 msgid "``__len__``" msgstr "``__len__``" -#: ../../library/collections.abc.rst:130 +#: ../../library/collections.abc.rst:129 msgid ":class:`Callable` [1]_" msgstr ":class:`Callable` [1]_" -#: ../../library/collections.abc.rst:130 +#: ../../library/collections.abc.rst:129 msgid "``__call__``" msgstr "``__call__``" -#: ../../library/collections.abc.rst:131 +#: ../../library/collections.abc.rst:130 msgid ":class:`Collection` [1]_" msgstr ":class:`Collection` [1]_" -#: ../../library/collections.abc.rst:131 +#: ../../library/collections.abc.rst:130 msgid ":class:`Sized`, :class:`Iterable`, :class:`Container`" msgstr ":class:`Sized`, :class:`Iterable`, :class:`Container`" -#: ../../library/collections.abc.rst:131 ../../library/collections.abc.rst:147 +#: ../../library/collections.abc.rst:130 ../../library/collections.abc.rst:146 msgid "``__contains__``, ``__iter__``, ``__len__``" msgstr "``__contains__``, ``__iter__``, ``__len__``" -#: ../../library/collections.abc.rst:135 ../../library/collections.abc.rst:138 -#: ../../library/collections.abc.rst:144 +#: ../../library/collections.abc.rst:134 ../../library/collections.abc.rst:137 +#: ../../library/collections.abc.rst:143 msgid ":class:`Sequence`" msgstr ":class:`Sequence`" -#: ../../library/collections.abc.rst:135 +#: ../../library/collections.abc.rst:134 msgid ":class:`Reversible`, :class:`Collection`" msgstr ":class:`Reversible`, :class:`Collection`" -#: ../../library/collections.abc.rst:135 ../../library/collections.abc.rst:144 +#: ../../library/collections.abc.rst:134 ../../library/collections.abc.rst:143 msgid "``__getitem__``, ``__len__``" msgstr "``__getitem__``, ``__len__``" -#: ../../library/collections.abc.rst:135 +#: ../../library/collections.abc.rst:134 msgid "" "``__contains__``, ``__iter__``, ``__reversed__``, ``index``, and ``count``" msgstr "" "``__contains__``, ``__iter__``, ``__reversed__``, ``index``, and ``count``" -#: ../../library/collections.abc.rst:138 +#: ../../library/collections.abc.rst:137 msgid ":class:`MutableSequence`" msgstr ":class:`MutableSequence`" -#: ../../library/collections.abc.rst:138 +#: ../../library/collections.abc.rst:137 msgid "" "``__getitem__``, ``__setitem__``, ``__delitem__``, ``__len__``, ``insert``" msgstr "" "``__getitem__``, ``__setitem__``, ``__delitem__``, ``__len__``, ``insert``" -#: ../../library/collections.abc.rst:138 +#: ../../library/collections.abc.rst:137 msgid "" "Inherited :class:`Sequence` methods and ``append``, ``clear``, ``reverse``, " "``extend``, ``pop``, ``remove``, and ``__iadd__``" msgstr "" +"Herdados métodos de :class:`Sequence` e ``append``, ``clear``, ``reverse``, " +"``extend``, ``pop``, ``remove`` e ``__iadd__``" -#: ../../library/collections.abc.rst:144 +#: ../../library/collections.abc.rst:143 msgid ":class:`ByteString`" msgstr ":class:`ByteString`" -#: ../../library/collections.abc.rst:144 +#: ../../library/collections.abc.rst:143 msgid "Inherited :class:`Sequence` methods" -msgstr "Herdado :class:`Sequence` métodos" +msgstr "Herdados métodos de :class:`Sequence`" -#: ../../library/collections.abc.rst:147 ../../library/collections.abc.rst:151 +#: ../../library/collections.abc.rst:146 ../../library/collections.abc.rst:151 msgid ":class:`Set`" msgstr ":class:`Set`" -#: ../../library/collections.abc.rst:147 ../../library/collections.abc.rst:157 +#: ../../library/collections.abc.rst:146 ../../library/collections.abc.rst:157 msgid ":class:`Collection`" msgstr ":class:`Collection`" -#: ../../library/collections.abc.rst:147 +#: ../../library/collections.abc.rst:146 msgid "" "``__le__``, ``__lt__``, ``__eq__``, ``__ne__``, ``__gt__``, ``__ge__``, " -"``__and__``, ``__or__``, ``__sub__``, ``__xor__``, and ``isdisjoint``" +"``__and__``, ``__or__``, ``__sub__``, ``__rsub__``, ``__xor__``, " +"``__rxor__`` and ``isdisjoint``" msgstr "" "``__le__``, ``__lt__``, ``__eq__``, ``__ne__``, ``__gt__``, ``__ge__``, " -"``__and__``, ``__or__``, ``__sub__``, ``__xor__``, e ``isdisjoint``" +"``__and__``, ``__or__``, ``__sub__``, ``__rsub__``, ``__xor__``, " +"``__rxor__`` e ``isdisjoint``" #: ../../library/collections.abc.rst:151 msgid ":class:`MutableSet`" @@ -333,6 +448,10 @@ msgstr ":class:`MappingView`" msgid ":class:`Sized`" msgstr ":class:`Sized`" +#: ../../library/collections.abc.rst:168 +msgid "``__init__``, ``__len__`` and ``__repr__``" +msgstr "``__init__``, ``__len__`` e ``__repr__``" + #: ../../library/collections.abc.rst:169 msgid ":class:`ItemsView`" msgstr ":class:`ItemsView`" @@ -433,6 +552,11 @@ msgid "" "set to :const:`None`. This only works for simple interfaces. More complex " "interfaces require registration or direct subclassing." msgstr "" +"Essas ABCs substituem :meth:`~abc.ABCMeta.__subclasshook__` para dar suporte " +"ao teste de uma interface verificando se os métodos necessários estão " +"presentes e não foram definidos como :const:`None`. Isso só funciona para " +"interfaces simples. Interfaces mais complexas exigem registro ou " +"subclassificação direta." #: ../../library/collections.abc.rst:192 msgid "" @@ -442,32 +566,45 @@ msgid "" "method. The only reliable way to determine whether an object is :term:" "`iterable` is to call ``iter(obj)``." msgstr "" +"A verificação ``isinstance(obj, Iterable)`` detecta classes que são " +"registradas como :class:`Iterable` ou que possuem um método :meth:" +"`~container.__iter__`, mas que não detecta classes que iteram com o método :" +"meth:`~object.__getitem__`. A única maneira confiável de determinar se um " +"objeto é :term:`iterável` é chamar ``iter(obj)``." #: ../../library/collections.abc.rst:200 msgid "Collections Abstract Base Classes -- Detailed Descriptions" -msgstr "" +msgstr "Classes Base Abstrata de Coleções -- Descrições Detalhadas" #: ../../library/collections.abc.rst:205 msgid "ABC for classes that provide the :meth:`~object.__contains__` method." -msgstr "" +msgstr "ABC para classes que fornecem o método :meth:`~object.__contains__`." #: ../../library/collections.abc.rst:209 msgid "ABC for classes that provide the :meth:`~object.__hash__` method." -msgstr "" +msgstr "ABC para classes que fornecem o método :meth:`~object.__hash__`." #: ../../library/collections.abc.rst:213 msgid "ABC for classes that provide the :meth:`~object.__len__` method." -msgstr "" +msgstr "ABC para classes que fornecem o método :meth:`~object.__len__`." #: ../../library/collections.abc.rst:217 msgid "ABC for classes that provide the :meth:`~object.__call__` method." +msgstr "ABC para classes que fornecem o método :meth:`~object.__call__`." + +#: ../../library/collections.abc.rst:219 +msgid "" +"See :ref:`annotating-callables` for details on how to use :class:`!Callable` " +"in type annotations." msgstr "" +"Veja :ref:`annotating-callables` para detalhes sobre como usar :class:`!" +"Callable` em anotações de tipos." -#: ../../library/collections.abc.rst:221 +#: ../../library/collections.abc.rst:224 msgid "ABC for classes that provide the :meth:`~container.__iter__` method." -msgstr "" +msgstr "ABC para classes que fornecem o método :meth:`~container.__iter__`." -#: ../../library/collections.abc.rst:223 +#: ../../library/collections.abc.rst:226 msgid "" "Checking ``isinstance(obj, Iterable)`` detects classes that are registered " "as :class:`Iterable` or that have an :meth:`~container.__iter__` method, but " @@ -475,12 +612,17 @@ msgid "" "method. The only reliable way to determine whether an object is :term:" "`iterable` is to call ``iter(obj)``." msgstr "" +"A verificação ``isinstance(obj, Iterable)`` detecta classes que são " +"registradas como :class:`Iterable` ou que possuem um método :meth:" +"`~container.__iter__`, mas que não detecta classes que iteram com o método :" +"meth:`~object.__getitem__`. A única maneira confiável de determinar se um " +"objeto é :term:`iterável` é chamar ``iter(obj)``." -#: ../../library/collections.abc.rst:232 +#: ../../library/collections.abc.rst:235 msgid "ABC for sized iterable container classes." msgstr "ABC para classes de contêiner iterável de tamanho." -#: ../../library/collections.abc.rst:238 +#: ../../library/collections.abc.rst:241 msgid "" "ABC for classes that provide the :meth:`~iterator.__iter__` and :meth:" "`~iterator.__next__` methods. See also the definition of :term:`iterator`." @@ -489,25 +631,39 @@ msgstr "" "métodos :meth:`~iterator.__next__`. Veja também a definição de :term:" "`iterator`." -#: ../../library/collections.abc.rst:244 +#: ../../library/collections.abc.rst:247 msgid "" "ABC for iterable classes that also provide the :meth:`~object.__reversed__` " "method." msgstr "" +"ABC para classes iteráveis que também fornecem o método :meth:`~object." +"__reversed__`." -#: ../../library/collections.abc.rst:251 +#: ../../library/collections.abc.rst:254 msgid "" "ABC for :term:`generator` classes that implement the protocol defined in :" "pep:`342` that extends :term:`iterators ` with the :meth:" "`~generator.send`, :meth:`~generator.throw` and :meth:`~generator.close` " "methods." msgstr "" +"ABC para classes :term:`geradores ` que implementam o protocolo " +"definido em :pep:`342` que estende os :term:`iteradores ` com os " +"métodos :meth:`~generator.send`, :meth:`~generator.throw` e :meth:" +"`~generator.close`." -#: ../../library/collections.abc.rst:262 +#: ../../library/collections.abc.rst:259 +msgid "" +"See :ref:`annotating-generators-and-coroutines` for details on using :class:" +"`!Generator` in type annotations." +msgstr "" +"Consulte :ref:`annotating-generators-and-coroutines` para obter detalhes " +"sobre como usar :class:`!Generator` em anotações de tipos." + +#: ../../library/collections.abc.rst:268 msgid "ABCs for read-only and mutable :term:`sequences `." msgstr "ABCs para :term:`sequências ` somente de leitura e mutáveis." -#: ../../library/collections.abc.rst:264 +#: ../../library/collections.abc.rst:270 msgid "" "Implementation note: Some of the mixin methods, such as :meth:`~container." "__iter__`, :meth:`~object.__reversed__` and :meth:`index`, make repeated " @@ -517,42 +673,57 @@ msgid "" "method is linear (as it would be with a linked list), the mixins will have " "quadratic performance and will likely need to be overridden." msgstr "" +"Nota de implementação: Alguns dos métodos mixin, como :meth:`~container." +"__iter__`, :meth:`~object.__reversed__` e :meth:`index`, fazem chamadas " +"repetidas para o método subjacente :meth:`~object.__getitem__`. " +"Consequentemente, se :meth:`~object.__getitem__` for implementado com " +"velocidade de acesso constante, os métodos mixin terão desempenho linear; no " +"entanto se o método subjacente for linear (como seria com uma lista " +"encadeada), os mixins terão desempenho quadrático e provavelmente precisará " +"ser substituído." -#: ../../library/collections.abc.rst:273 +#: ../../library/collections.abc.rst:279 msgid "The index() method added support for *stop* and *start* arguments." msgstr "" "O método index() adicionou suporte para os argumentos *stop* e *start*." -#: ../../library/collections.abc.rst:277 +#: ../../library/collections.abc.rst:283 msgid "" "The :class:`ByteString` ABC has been deprecated. For use in typing, prefer a " "union, like ``bytes | bytearray``, or :class:`collections.abc.Buffer`. For " "use as an ABC, prefer :class:`Sequence` or :class:`collections.abc.Buffer`." msgstr "" +"A ABC :class:`ByteString` foi descontinuada. Para uso em tipagem, prefira " +"uma união, como ``bytes | bytearray``, ou :class:`collections.abc.Buffer`. " +"Para uso como uma ABC, prefira :class:`Sequence` ou :class:`collections.abc." +"Buffer`." -#: ../../library/collections.abc.rst:286 +#: ../../library/collections.abc.rst:292 msgid "ABCs for read-only and mutable :ref:`sets `." -msgstr "" +msgstr "ABCs para :ref:`conjuntos ` somente leitura e mutáveis." -#: ../../library/collections.abc.rst:291 +#: ../../library/collections.abc.rst:297 msgid "ABCs for read-only and mutable :term:`mappings `." msgstr "ABCs para somente leitura e mutável :term:`mappings `." -#: ../../library/collections.abc.rst:298 +#: ../../library/collections.abc.rst:304 msgid "" "ABCs for mapping, items, keys, and values :term:`views `." msgstr "" "ABCs para mapeamento, itens, chaves e valores :term:`views `." -#: ../../library/collections.abc.rst:302 +#: ../../library/collections.abc.rst:308 msgid "" "ABC for :term:`awaitable` objects, which can be used in :keyword:`await` " "expressions. Custom implementations must provide the :meth:`~object." "__await__` method." msgstr "" +"ABC para objetos :term:`aguardáveis `, que podem ser usados em " +"expressões de :keyword:`await`. Implementações personalizadas devem fornecer " +"o método :meth:`~object.__await__`." -#: ../../library/collections.abc.rst:306 +#: ../../library/collections.abc.rst:312 msgid "" ":term:`Coroutine ` objects and instances of the :class:" "`~collections.abc.Coroutine` ABC are all instances of this ABC." @@ -560,7 +731,7 @@ msgstr "" "Objetos e instâncias de :term:`corrotina ` da ABC :class:" "`~collections.abc.Coroutine` são todas instâncias dessa ABC." -#: ../../library/collections.abc.rst:310 +#: ../../library/collections.abc.rst:316 msgid "" "In CPython, generator-based coroutines (:term:`generators ` " "decorated with :func:`@types.coroutine `) are *awaitables*, " @@ -568,8 +739,13 @@ msgid "" "``isinstance(gencoro, Awaitable)`` for them will return ``False``. Use :func:" "`inspect.isawaitable` to detect them." msgstr "" +"No CPython, as corrotinas baseados em gerador (:term:`geradores ` " +"decorados com :func:`@types.coroutine `) são *aguardáveis*, " +"embora não possuam o método :meth:`~object.__await__`. Usar " +"``isinstance(gencoro, Awaitable)`` para eles retornará ``False``. Use :func:" +"`inspect.isawaitable` para detectá-los." -#: ../../library/collections.abc.rst:320 +#: ../../library/collections.abc.rst:326 msgid "" "ABC for :term:`coroutine` compatible classes. These implement the following " "methods, defined in :ref:`coroutine-objects`: :meth:`~coroutine.send`, :meth:" @@ -577,8 +753,13 @@ msgid "" "must also implement :meth:`~object.__await__`. All :class:`Coroutine` " "instances are also instances of :class:`Awaitable`." msgstr "" +"ABC para classes compatíveis com :term:`corrotina`. Eles implementam os " +"seguintes métodos, definidos em :ref:`coroutine-objects`: :meth:`~coroutine." +"send`, :meth:`~coroutine.throw`, e :meth:`~coroutine.close`. Implementações " +"personalizadas também devem implementar :meth:`~object.__await__`. Todas as " +"instâncias :class:`Coroutine` também são instâncias de :class:`Awaitable`." -#: ../../library/collections.abc.rst:328 +#: ../../library/collections.abc.rst:334 msgid "" "In CPython, generator-based coroutines (:term:`generators ` " "decorated with :func:`@types.coroutine `) are *awaitables*, " @@ -586,14 +767,31 @@ msgid "" "``isinstance(gencoro, Coroutine)`` for them will return ``False``. Use :func:" "`inspect.isawaitable` to detect them." msgstr "" +"No CPython, as corrotinas baseados em gerador (:term:`geradores ` " +"decorados com :func:`@types.coroutine `) são *aguardáveis*, " +"embora não possuam o método :meth:`~object.__await__`. Usar " +"``isinstance(gencoro, Coroutine)`` para eles retornará ``False``. Use :func:" +"`inspect.isawaitable` para detectá-los." -#: ../../library/collections.abc.rst:338 +#: ../../library/collections.abc.rst:340 +msgid "" +"See :ref:`annotating-generators-and-coroutines` for details on using :class:" +"`!Coroutine` in type annotations. The variance and order of type parameters " +"correspond to those of :class:`Generator`." +msgstr "" +"Consulte :ref:`annotating-generators-and-coroutines` para obter detalhes " +"sobre como usar :class:`!Coroutine` em anotações de tipos. A variância e a " +"ordem dos parâmetros de tipo correspondem às de :class:`Generator`." + +#: ../../library/collections.abc.rst:349 msgid "" "ABC for classes that provide an ``__aiter__`` method. See also the " "definition of :term:`asynchronous iterable`." msgstr "" +"ABC para classes que fornecem um método ``__aiter__``. Veja também a " +"definição de :term:`iterável assíncrono`." -#: ../../library/collections.abc.rst:345 +#: ../../library/collections.abc.rst:356 msgid "" "ABC for classes that provide ``__aiter__`` and ``__anext__`` methods. See " "also the definition of :term:`asynchronous iterator`." @@ -601,29 +799,53 @@ msgstr "" "ABC para classes que fornecem os métodos ``__aiter__`` e ``__anext__``. Veja " "também a definição de :term:`iterador assíncrono`." -#: ../../library/collections.abc.rst:352 +#: ../../library/collections.abc.rst:363 msgid "" "ABC for :term:`asynchronous generator` classes that implement the protocol " "defined in :pep:`525` and :pep:`492`." msgstr "" +"ABC para classes de :term:`gerador assíncrono` que implementam o protocolo " +"definido em :pep:`525` e :pep:`492`." + +#: ../../library/collections.abc.rst:366 +msgid "" +"See :ref:`annotating-generators-and-coroutines` for details on using :class:" +"`!AsyncGenerator` in type annotations." +msgstr "" +"Consulte :ref:`annotating-generators-and-coroutines` para obter detalhes " +"sobre como usar :class:`!AsyncGenerator` em anotações de tipos." -#: ../../library/collections.abc.rst:359 +#: ../../library/collections.abc.rst:373 msgid "" "ABC for classes that provide the :meth:`~object.__buffer__` method, " "implementing the :ref:`buffer protocol `. See :pep:`688`." msgstr "" +"ABC para classes que fornecem o método :meth:`~object.__buffer__`, " +"implementando o :ref:`protocolo buffer `. Veja :pep:`688`." -#: ../../library/collections.abc.rst:365 +#: ../../library/collections.abc.rst:379 msgid "Examples and Recipes" msgstr "Exemplos e receitas" -#: ../../library/collections.abc.rst:367 +#: ../../library/collections.abc.rst:381 msgid "" "ABCs allow us to ask classes or instances if they provide particular " "functionality, for example::" msgstr "" +"ABCs nos permitem perguntar a classes ou instâncias se elas fornecem " +"funcionalidades específicas, por exemplo::" + +#: ../../library/collections.abc.rst:384 +msgid "" +"size = None\n" +"if isinstance(myvar, collections.abc.Sized):\n" +" size = len(myvar)" +msgstr "" +"size = None\n" +"if isinstance(myvar, collections.abc.Sized):\n" +" size = len(myvar)" -#: ../../library/collections.abc.rst:374 +#: ../../library/collections.abc.rst:388 msgid "" "Several of the ABCs are also useful as mixins that make it easier to develop " "classes supporting container APIs. For example, to write a class supporting " @@ -632,12 +854,66 @@ msgid "" "__iter__`, and :meth:`~object.__len__`. The ABC supplies the remaining " "methods such as :meth:`!__and__` and :meth:`~frozenset.isdisjoint`::" msgstr "" +"Vários ABCs também são também úteis como mixins que facilitam o " +"desenvolvimento de classes que suportam APIs de contêiner. Por exemplo, para " +"escrever uma classe que suporte toda a API :class:`Set` , é necessário " +"fornecer apenas os três métodos abstratos subjacentes: :meth:`~object." +"__contains__`, :meth:`~container.__iter__`, e :meth:`~object.__len__`. O ABC " +"fornece os métodos restantes, como :meth:`!__and__` e :meth:`~frozenset." +"isdisjoint`::" + +#: ../../library/collections.abc.rst:395 +msgid "" +"class ListBasedSet(collections.abc.Set):\n" +" ''' Alternate set implementation favoring space over speed\n" +" and not requiring the set elements to be hashable. '''\n" +" def __init__(self, iterable):\n" +" self.elements = lst = []\n" +" for value in iterable:\n" +" if value not in lst:\n" +" lst.append(value)\n" +"\n" +" def __iter__(self):\n" +" return iter(self.elements)\n" +"\n" +" def __contains__(self, value):\n" +" return value in self.elements\n" +"\n" +" def __len__(self):\n" +" return len(self.elements)\n" +"\n" +"s1 = ListBasedSet('abcdef')\n" +"s2 = ListBasedSet('defghi')\n" +"overlap = s1 & s2 # The __and__() method is supported " +"automatically" +msgstr "" +"class ListBasedSet(collections.abc.Set):\n" +" ''' Alternate set implementation favoring space over speed\n" +" and not requiring the set elements to be hashable. '''\n" +" def __init__(self, iterable):\n" +" self.elements = lst = []\n" +" for value in iterable:\n" +" if value not in lst:\n" +" lst.append(value)\n" +"\n" +" def __iter__(self):\n" +" return iter(self.elements)\n" +"\n" +" def __contains__(self, value):\n" +" return value in self.elements\n" +"\n" +" def __len__(self):\n" +" return len(self.elements)\n" +"\n" +"s1 = ListBasedSet('abcdef')\n" +"s2 = ListBasedSet('defghi')\n" +"overlap = s1 & s2 # O método __and__() é automaticamente suportado" -#: ../../library/collections.abc.rst:403 +#: ../../library/collections.abc.rst:417 msgid "Notes on using :class:`Set` and :class:`MutableSet` as a mixin:" msgstr "Notas sobre o uso de :class:`Set` e :class:`MutableSet` como um mixin:" -#: ../../library/collections.abc.rst:406 +#: ../../library/collections.abc.rst:420 msgid "" "Since some set operations create new sets, the default mixin methods need a " "way to create new instances from an :term:`iterable`. The class constructor " @@ -649,15 +925,28 @@ msgid "" "classmethod or regular method that can construct new instances from an " "iterable argument." msgstr "" +"Como algumas operações de conjunto criam novos conjuntos, os métodos de " +"mixin padrão precisam de uma maneira de criar novas instâncias a partir de " +"um :term:`iterável`. Supõe-se que a classe construtor tenha uma assinatura " +"no formato ``ClassName(iterable)``. Essa suposição é fatorada em um :class:" +"`classmethod` interno chamado :meth:`!_from_iterable` que chama " +"``cls(iterable)`` para produzir um novo conjunto. Se o mixin :class:`Set` " +"estiver sendo usado em uma classe com uma assinatura de construtor " +"diferente, você precisará substituir :meth:`!_from_iterable` por um método " +"de classe ou um método regular que possa construir novas instâncias a partir " +"de um argumento iterável." -#: ../../library/collections.abc.rst:417 +#: ../../library/collections.abc.rst:431 msgid "" "To override the comparisons (presumably for speed, as the semantics are " "fixed), redefine :meth:`~object.__le__` and :meth:`~object.__ge__`, then the " "other operations will automatically follow suit." msgstr "" +"Para substituir as comparações (presumivelmente para velocidade, já que a " +"semântica é fixa), redefina :meth:`~object.__le__` e :meth:`~object.__ge__`, " +"então as outras operações seguirão o exemplo automaticamente." -#: ../../library/collections.abc.rst:423 +#: ../../library/collections.abc.rst:437 msgid "" "The :class:`Set` mixin provides a :meth:`!_hash` method to compute a hash " "value for the set; however, :meth:`~object.__hash__` is not defined because " @@ -665,8 +954,14 @@ msgid "" "using mixins, inherit from both :meth:`Set` and :meth:`Hashable`, then " "define ``__hash__ = Set._hash``." msgstr "" +"O mixin :class:`Set` fornece um método :meth:`!_hash` para calcular um valor " +"de hash para o conjunto; no entanto, :meth:`~object.__hash__` não é definido " +"porque nem todos os conjuntos são :term:`hasheáveis ` ou " +"imutáveis. Para adicionar hasheabilidade em conjuntos usando mixin, herde de " +"ambos :meth:`Set` e :meth:`Hashable`, e então defina ``__hash__ = Set." +"_hash``." -#: ../../library/collections.abc.rst:431 +#: ../../library/collections.abc.rst:445 msgid "" "`OrderedSet recipe `_ for an " "example built on :class:`MutableSet`." @@ -674,7 +969,7 @@ msgstr "" "`OrderedSet receita `_ para um " "exemplo baseado em :class:`MutableSet`." -#: ../../library/collections.abc.rst:434 +#: ../../library/collections.abc.rst:448 msgid "For more about ABCs, see the :mod:`abc` module and :pep:`3119`." msgstr "" "Para mais informações sobre ABCs, consulte o módulo :mod:`abc` e :pep:`3119`." diff --git a/library/collections.po b/library/collections.po index afcf4ddc4..01ad44e14 100644 --- a/library/collections.po +++ b/library/collections.po @@ -1,34 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Welington Carlos , 2021 -# Alexandre B A Villares, 2021 -# Vitor Buxbaum Orlandi, 2021 -# João Porfirio, 2022 -# Hildeberto Abreu Magalhães , 2022 -# Jader Oliveira, 2022 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:56+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-03-07 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -215,7 +206,7 @@ msgid "" "which mappings are searched. The list should always contain at least one " "mapping." msgstr "" -"Uma lista de mapeamentos atualizáveis ​​pelo usuário. A lista é ordenada desde " +"Uma lista de mapeamentos atualizáveis pelo usuário. A lista é ordenada desde " "o primeiro pesquisado até a última pesquisado. É o único estado armazenado e " "pode ser modificado para alterar quais mapeamentos são pesquisados. A lista " "deve sempre conter pelo menos um mapeamento." @@ -271,6 +262,18 @@ msgstr "" "Observe, a ordem de iteração de um :class:`ChainMap` é determinada pela " "varredura dos mapeamentos do último ao primeiro::" +#: ../../library/collections.rst:105 +msgid "" +">>> baseline = {'music': 'bach', 'art': 'rembrandt'}\n" +">>> adjustments = {'art': 'van gogh', 'opera': 'carmen'}\n" +">>> list(ChainMap(adjustments, baseline))\n" +"['music', 'art', 'opera']" +msgstr "" +">>> baseline = {'music': 'bach', 'art': 'rembrandt'}\n" +">>> adjustments = {'art': 'van gogh', 'opera': 'carmen'}\n" +">>> list(ChainMap(adjustments, baseline))\n" +"['music', 'art', 'opera']" + #: ../../library/collections.rst:110 msgid "" "This gives the same ordering as a series of :meth:`dict.update` calls " @@ -279,6 +282,18 @@ msgstr "" "Isso dá a mesma ordem de uma série de chamadas de :meth:`dict.update` " "começando com o último mapeamento::" +#: ../../library/collections.rst:113 +msgid "" +">>> combined = baseline.copy()\n" +">>> combined.update(adjustments)\n" +">>> list(combined)\n" +"['music', 'art', 'opera']" +msgstr "" +">>> combined = baseline.copy()\n" +">>> combined.update(adjustments)\n" +">>> list(combined)\n" +"['music', 'art', 'opera']" + #: ../../library/collections.rst:118 msgid "Added support for ``|`` and ``|=`` operators, specified in :pep:`584`." msgstr "" @@ -344,6 +359,14 @@ msgstr "" msgid "Example of simulating Python's internal lookup chain::" msgstr "Exemplo de simulação da cadeia de busca interna do Python::" +#: ../../library/collections.rst:153 +msgid "" +"import builtins\n" +"pylookup = ChainMap(locals(), globals(), vars(builtins))" +msgstr "" +"import builtins\n" +"pylookup = ChainMap(locals(), globals(), vars(builtins))" + #: ../../library/collections.rst:156 msgid "" "Example of letting user specified command-line arguments take precedence " @@ -354,6 +377,38 @@ msgstr "" "pelo usuário tenham precedência sobre as variáveis de ambiente que, por sua " "vez, têm precedência sobre os valores padrão::" +#: ../../library/collections.rst:159 +msgid "" +"import os, argparse\n" +"\n" +"defaults = {'color': 'red', 'user': 'guest'}\n" +"\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument('-u', '--user')\n" +"parser.add_argument('-c', '--color')\n" +"namespace = parser.parse_args()\n" +"command_line_args = {k: v for k, v in vars(namespace).items() if v is not " +"None}\n" +"\n" +"combined = ChainMap(command_line_args, os.environ, defaults)\n" +"print(combined['color'])\n" +"print(combined['user'])" +msgstr "" +"import os, argparse\n" +"\n" +"defaults = {'color': 'red', 'user': 'guest'}\n" +"\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument('-u', '--user')\n" +"parser.add_argument('-c', '--color')\n" +"namespace = parser.parse_args()\n" +"command_line_args = {k: v for k, v in vars(namespace).items() if v is not " +"None}\n" +"\n" +"combined = ChainMap(command_line_args, os.environ, defaults)\n" +"print(combined['color'])\n" +"print(combined['user'])" + #: ../../library/collections.rst:173 msgid "" "Example patterns for using the :class:`ChainMap` class to simulate nested " @@ -362,6 +417,43 @@ msgstr "" "Padrões de exemplo para utilização da classe :class:`ChainMap` para simular " "contextos aninhados::" +#: ../../library/collections.rst:176 +msgid "" +"c = ChainMap() # Create root context\n" +"d = c.new_child() # Create nested child context\n" +"e = c.new_child() # Child of c, independent from d\n" +"e.maps[0] # Current context dictionary -- like Python's " +"locals()\n" +"e.maps[-1] # Root context -- like Python's globals()\n" +"e.parents # Enclosing context chain -- like Python's nonlocals\n" +"\n" +"d['x'] = 1 # Set value in current context\n" +"d['x'] # Get first key in the chain of contexts\n" +"del d['x'] # Delete from current context\n" +"list(d) # All nested values\n" +"k in d # Check all nested values\n" +"len(d) # Number of nested values\n" +"d.items() # All nested items\n" +"dict(d) # Flatten into a regular dictionary" +msgstr "" +"c = ChainMap() # Cria o contexto raiz\n" +"d = c.new_child() # Cria um contexto filho aninhado\n" +"e = c.new_child() # Filho de c, independente de d\n" +"e.maps[0] # Dicionário do contexto atual -- como locals() do " +"Python\n" +"e.maps[-1] # Contexto raiz -- como globals() do Python\n" +"e.parents # Envolvendo cadeia de contexto -- como os nonlocals " +"do Python\n" +"\n" +"d['x'] = 1 # Define valor no contexto atual\n" +"d['x'] # Obtém a primeira chave na cadeia de contextos\n" +"del d['x'] # Exclui do contexto atual\n" +"list(d) # Todos os valores aninhados\n" +"k in d # Verifica todos os valores aninhados\n" +"len(d) # Número de valores aninhados\n" +"d.items() # Todos os itens aninhados\n" +"dict(d) # Achata em um dicionário comum" + #: ../../library/collections.rst:192 msgid "" "The :class:`ChainMap` class only makes updates (writes and deletions) to the " @@ -374,6 +466,61 @@ msgstr "" "cadeia. Contudo, se há o desejo de escritas e remoções profundas, é fácil " "fazer uma subclasse que atualiza chaves encontradas mais a fundo na cadeia::" +#: ../../library/collections.rst:197 +msgid "" +"class DeepChainMap(ChainMap):\n" +" 'Variant of ChainMap that allows direct updates to inner scopes'\n" +"\n" +" def __setitem__(self, key, value):\n" +" for mapping in self.maps:\n" +" if key in mapping:\n" +" mapping[key] = value\n" +" return\n" +" self.maps[0][key] = value\n" +"\n" +" def __delitem__(self, key):\n" +" for mapping in self.maps:\n" +" if key in mapping:\n" +" del mapping[key]\n" +" return\n" +" raise KeyError(key)\n" +"\n" +">>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': " +"'yellow'})\n" +">>> d['lion'] = 'orange' # update an existing key two levels down\n" +">>> d['snake'] = 'red' # new keys get added to the topmost dict\n" +">>> del d['elephant'] # remove an existing key one level down\n" +">>> d # display result\n" +"DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})" +msgstr "" +"class DeepChainMap(ChainMap):\n" +" 'Variant of ChainMap that allows direct updates to inner scopes'\n" +"\n" +" def __setitem__(self, key, value):\n" +" for mapping in self.maps:\n" +" if key in mapping:\n" +" mapping[key] = value\n" +" return\n" +" self.maps[0][key] = value\n" +"\n" +" def __delitem__(self, key):\n" +" for mapping in self.maps:\n" +" if key in mapping:\n" +" del mapping[key]\n" +" return\n" +" raise KeyError(key)\n" +"\n" +">>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': " +"'yellow'})\n" +">>> d['lion'] = 'orange' # atualiza uma chave existente dois níveis " +"abaixo\n" +">>> d['snake'] = 'red' # novas chaves são adicionadas ao dict mais " +"acima\n" +">>> del d['elephant'] # remove uma chave existente um nível " +"abaixo\n" +">>> d # exibe o resultado\n" +"DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})" + #: ../../library/collections.rst:223 msgid ":class:`Counter` objects" msgstr "Objetos :class:`Counter`" @@ -386,6 +533,38 @@ msgstr "" "Uma ferramenta de contagem é fornecida para apoiar contas rápidas e " "convenientes. Por exemplo::" +#: ../../library/collections.rst:228 +msgid "" +">>> # Tally occurrences of words in a list\n" +">>> cnt = Counter()\n" +">>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:\n" +"... cnt[word] += 1\n" +"...\n" +">>> cnt\n" +"Counter({'blue': 3, 'red': 2, 'green': 1})\n" +"\n" +">>> # Find the ten most common words in Hamlet\n" +">>> import re\n" +">>> words = re.findall(r'\\w+', open('hamlet.txt').read().lower())\n" +">>> Counter(words).most_common(10)\n" +"[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),\n" +" ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]" +msgstr "" +">>> # Conta ocorrências de palavras em uma lista\n" +">>> cnt = Counter()\n" +">>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:\n" +"... cnt[word] += 1\n" +"...\n" +">>> cnt\n" +"Counter({'blue': 3, 'red': 2, 'green': 1})\n" +"\n" +">>> # Encontra as dez palavras mais comuns em Hamlet\n" +">>> import re\n" +">>> words = re.findall(r'\\w+', open('hamlet.txt').read().lower())\n" +">>> Counter(words).most_common(10)\n" +"[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),\n" +" ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]" + #: ../../library/collections.rst:245 msgid "" "A :class:`Counter` is a :class:`dict` subclass for counting :term:`hashable` " @@ -544,6 +723,29 @@ msgstr "" msgid "Common patterns for working with :class:`Counter` objects::" msgstr "Padrões comuns para trabalhar com objetos :class:`Counter`::" +#: ../../library/collections.rst:356 +msgid "" +"c.total() # total of all counts\n" +"c.clear() # reset all counts\n" +"list(c) # list unique elements\n" +"set(c) # convert to a set\n" +"dict(c) # convert to a regular dictionary\n" +"c.items() # access the (elem, cnt) pairs\n" +"Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs\n" +"c.most_common()[:-n-1:-1] # n least common elements\n" +"+c # remove zero and negative counts" +msgstr "" +"c.total() # total de todas as contagens\n" +"c.clear() # redefine todas as contagens\n" +"list(c) # lista elementos únicos\n" +"set(c) # converte para um conjunto\n" +"dict(c) # converte para um dicionário comum\n" +"c.items() # acessa os pares (elem, cnt)\n" +"Counter(dict(list_of_pairs)) # converte de uma lista de pares (elem, " +"cnt)\n" +"c.most_common()[:-n-1:-1] # n últimos elementos comuns\n" +"+c # remove zero e contagens negativas" + #: ../../library/collections.rst:366 msgid "" "Several mathematical operations are provided for combining :class:`Counter` " @@ -563,6 +765,40 @@ msgstr "" "contagens assinadas, mas a saída vai excluir resultados com contagens de " "zero ou menos." +#: ../../library/collections.rst:374 +msgid "" +">>> c = Counter(a=3, b=1)\n" +">>> d = Counter(a=1, b=2)\n" +">>> c + d # add two counters together: c[x] + d[x]\n" +"Counter({'a': 4, 'b': 3})\n" +">>> c - d # subtract (keeping only positive counts)\n" +"Counter({'a': 2})\n" +">>> c & d # intersection: min(c[x], d[x])\n" +"Counter({'a': 1, 'b': 1})\n" +">>> c | d # union: max(c[x], d[x])\n" +"Counter({'a': 3, 'b': 2})\n" +">>> c == d # equality: c[x] == d[x]\n" +"False\n" +">>> c <= d # inclusion: c[x] <= d[x]\n" +"False" +msgstr "" +">>> c = Counter(a=3, b=1)\n" +">>> d = Counter(a=1, b=2)\n" +">>> c + d # adiciona dois contadores juntos: c[x] + " +"d[x]\n" +"Counter({'a': 4, 'b': 3})\n" +">>> c - d # subtrai (mantendo apenas contagens " +"positivas)\n" +"Counter({'a': 2})\n" +">>> c & d # interseção: min(c[x], d[x])\n" +"Counter({'a': 1, 'b': 1})\n" +">>> c | d # união: max(c[x], d[x])\n" +"Counter({'a': 3, 'b': 2})\n" +">>> c == d # igualdade: c[x] == d[x]\n" +"False\n" +">>> c <= d # inclusão: c[x] <= d[x]\n" +"False" + #: ../../library/collections.rst:391 msgid "" "Unary addition and subtraction are shortcuts for adding an empty counter or " @@ -687,6 +923,12 @@ msgstr "" "um determinado conjunto de elementos, consulte :func:`itertools." "combinations_with_replacement`::" +#: ../../library/collections.rst:447 +msgid "" +"map(Counter, combinations_with_replacement('ABC', 2)) # --> AA AB AC BB BC CC" +msgstr "" +"map(Counter, combinations_with_replacement('ABC', 2)) # --> AA AB AC BB BC CC" + #: ../../library/collections.rst:451 msgid ":class:`deque` objects" msgstr "Objetos :class:`deque`" @@ -893,6 +1135,120 @@ msgstr "" msgid "Example:" msgstr "Exemplo:" +#: ../../library/collections.rst:596 +msgid "" +">>> from collections import deque\n" +">>> d = deque('ghi') # make a new deque with three items\n" +">>> for elem in d: # iterate over the deque's elements\n" +"... print(elem.upper())\n" +"G\n" +"H\n" +"I\n" +"\n" +">>> d.append('j') # add a new entry to the right side\n" +">>> d.appendleft('f') # add a new entry to the left side\n" +">>> d # show the representation of the deque\n" +"deque(['f', 'g', 'h', 'i', 'j'])\n" +"\n" +">>> d.pop() # return and remove the rightmost item\n" +"'j'\n" +">>> d.popleft() # return and remove the leftmost item\n" +"'f'\n" +">>> list(d) # list the contents of the deque\n" +"['g', 'h', 'i']\n" +">>> d[0] # peek at leftmost item\n" +"'g'\n" +">>> d[-1] # peek at rightmost item\n" +"'i'\n" +"\n" +">>> list(reversed(d)) # list the contents of a deque in " +"reverse\n" +"['i', 'h', 'g']\n" +">>> 'h' in d # search the deque\n" +"True\n" +">>> d.extend('jkl') # add multiple elements at once\n" +">>> d\n" +"deque(['g', 'h', 'i', 'j', 'k', 'l'])\n" +">>> d.rotate(1) # right rotation\n" +">>> d\n" +"deque(['l', 'g', 'h', 'i', 'j', 'k'])\n" +">>> d.rotate(-1) # left rotation\n" +">>> d\n" +"deque(['g', 'h', 'i', 'j', 'k', 'l'])\n" +"\n" +">>> deque(reversed(d)) # make a new deque in reverse order\n" +"deque(['l', 'k', 'j', 'i', 'h', 'g'])\n" +">>> d.clear() # empty the deque\n" +">>> d.pop() # cannot pop from an empty deque\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in -toplevel-\n" +" d.pop()\n" +"IndexError: pop from an empty deque\n" +"\n" +">>> d.extendleft('abc') # extendleft() reverses the input " +"order\n" +">>> d\n" +"deque(['c', 'b', 'a'])" +msgstr "" +">>> from collections import deque\n" +">>> d = deque('ghi') # torna um novo deque com três itens\n" +">>> for elem in d: # itera os elementos do deque\n" +"... print(elem.upper())\n" +"G\n" +"H\n" +"I\n" +"\n" +">>> d.append('j') # adiciona uma nova entrada ao lado " +"direito\n" +">>> d.appendleft('f') # adiciona uma nova entrada ao lado " +"esquerdo\n" +">>> d # mostra a representação do deque\n" +"deque(['f', 'g', 'h', 'i', 'j'])\n" +"\n" +">>> d.pop() # retorna e remove o item mais à " +"direita\n" +"'j'\n" +">>> d.popleft() # retorna e remove o item mais à " +"esquerda\n" +"'f'\n" +">>> list(d) # lista o conteúdo do deque\n" +"['g', 'h', 'i']\n" +">>> d[0] # exibe o item mais à esquerda\n" +"'g'\n" +">>> d[-1] # exibe o item mais à direita\n" +"'i'\n" +"\n" +">>> list(reversed(d)) # lista o conteúdo de um deque ao " +"inverso\n" +"['i', 'h', 'g']\n" +">>> 'h' in d # pesquisa no deque\n" +"True\n" +">>> d.extend('jkl') # adiciona vários elementos de uma só " +"vez\n" +">>> d\n" +"deque(['g', 'h', 'i', 'j', 'k', 'l'])\n" +">>> d.rotate(1) # rotação para direita\n" +">>> d\n" +"deque(['l', 'g', 'h', 'i', 'j', 'k'])\n" +">>> d.rotate(-1) # rotação para esquerda\n" +">>> d\n" +"deque(['g', 'h', 'i', 'j', 'k', 'l'])\n" +"\n" +">>> deque(reversed(d)) # cria um novo deque na ordem inversa\n" +"deque(['l', 'k', 'j', 'i', 'h', 'g'])\n" +">>> d.clear() # esvazia o deque\n" +">>> d.pop() # não é possível retirar um item de um " +"deque vazio\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in -toplevel-\n" +" d.pop()\n" +"IndexError: pop from an empty deque\n" +"\n" +">>> d.extendleft('abc') # extendleft() inverte a ordem da " +"entrada\n" +">>> d\n" +"deque(['c', 'b', 'a'])" + #: ../../library/collections.rst:651 msgid ":class:`deque` Recipes" msgstr "Receitas de :class:`deque`" @@ -909,6 +1265,18 @@ msgstr "" "Deques de comprimento limitado fornecem funcionalidade semelhante ao filtro " "``tail`` em Unix::" +#: ../../library/collections.rst:658 +msgid "" +"def tail(filename, n=10):\n" +" 'Return the last n lines of a file'\n" +" with open(filename) as f:\n" +" return deque(f, n)" +msgstr "" +"def tail(filename, n=10):\n" +" 'Return the last n lines of a file'\n" +" with open(filename) as f:\n" +" return deque(f, n)" + #: ../../library/collections.rst:663 msgid "" "Another approach to using deques is to maintain a sequence of recently added " @@ -917,6 +1285,32 @@ msgstr "" "Outra abordagem para usar deques é manter uma sequência de elementos " "adicionados recentemente, acrescentando à direita e clicando à esquerda::" +#: ../../library/collections.rst:666 +msgid "" +"def moving_average(iterable, n=3):\n" +" # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0\n" +" # https://en.wikipedia.org/wiki/Moving_average\n" +" it = iter(iterable)\n" +" d = deque(itertools.islice(it, n-1))\n" +" d.appendleft(0)\n" +" s = sum(d)\n" +" for elem in it:\n" +" s += elem - d.popleft()\n" +" d.append(elem)\n" +" yield s / n" +msgstr "" +"def moving_average(iterable, n=3):\n" +" # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0\n" +" # https://en.wikipedia.org/wiki/Moving_average\n" +" it = iter(iterable)\n" +" d = deque(itertools.islice(it, n-1))\n" +" d.appendleft(0)\n" +" s = sum(d)\n" +" for elem in it:\n" +" s += elem - d.popleft()\n" +" d.append(elem)\n" +" yield s / n" + #: ../../library/collections.rst:678 msgid "" "A `round-robin scheduler A D E B F C\"\n" +" iterators = deque(map(iter, iterables))\n" +" while iterators:\n" +" try:\n" +" while True:\n" +" yield next(iterators[0])\n" +" iterators.rotate(-1)\n" +" except StopIteration:\n" +" # Remove an exhausted iterator.\n" +" iterators.popleft()" +msgstr "" +"def roundrobin(*iterables):\n" +" \"roundrobin('ABC', 'D', 'EF') --> A D E B F C\"\n" +" iterators = deque(map(iter, iterables))\n" +" while iterators:\n" +" try:\n" +" while True:\n" +" yield next(iterators[0])\n" +" iterators.rotate(-1)\n" +" except StopIteration:\n" +" # Remove um iterador esgotado.\n" +" iterators.popleft()" + #: ../../library/collections.rst:697 msgid "" "The :meth:`~deque.rotate` method provides a way to implement :class:`deque` " @@ -944,6 +1364,18 @@ msgstr "" "pura de ``del d[n]`` depende do método ``rotate()`` para posicionar os " "elementos a serem retirados::" +#: ../../library/collections.rst:701 +msgid "" +"def delete_nth(d, n):\n" +" d.rotate(-n)\n" +" d.popleft()\n" +" d.rotate(n)" +msgstr "" +"def delete_nth(d, n):\n" +" d.rotate(-n)\n" +" d.popleft()\n" +" d.rotate(n)" + #: ../../library/collections.rst:706 msgid "" "To implement :class:`deque` slicing, use a similar approach applying :meth:" @@ -986,7 +1418,7 @@ msgid "" msgstr "" "O primeiro argumento fornece o valor inicial para o atributo :attr:" "`default_factory`; o padrão é ``None``. Todos os argumentos restantes são " -"tratados da mesma forma como se fossem passados ​​para o construtor :class:" +"tratados da mesma forma como se fossem passados para o construtor :class:" "`dict`, incluindo argumentos nomeados." #: ../../library/collections.rst:731 @@ -1037,14 +1469,14 @@ msgstr "" #: ../../library/collections.rst:750 msgid "" "Note that :meth:`__missing__` is *not* called for any operations besides :" -"meth:`~object.__getitem__`. This means that :meth:`get` will, like normal " -"dictionaries, return ``None`` as a default rather than using :attr:" +"meth:`~object.__getitem__`. This means that :meth:`~dict.get` will, like " +"normal dictionaries, return ``None`` as a default rather than using :attr:" "`default_factory`." msgstr "" "Observe que :meth:`__missing__` *não* é chamado para nenhuma operação além " -"de :meth:`~object.__getitem__`. Isso significa que :meth:`get` irá, como " -"dicionários normais, retornar ``None`` como padrão ao invés de usar :attr:" -"`default_factory`." +"de :meth:`~object.__getitem__`. Isso significa que :meth:`~dict.get` irá, " +"como dicionários normais, retornar ``None`` como padrão ao invés de usar :" +"attr:`default_factory`." #: ../../library/collections.rst:756 msgid ":class:`defaultdict` objects support the following instance variable:" @@ -1061,7 +1493,7 @@ msgstr "" "partir do primeiro argumento para o construtor, se presente, ou para " "``None``, se ausente." -#: ../../library/collections.rst:765 ../../library/collections.rst:1188 +#: ../../library/collections.rst:765 ../../library/collections.rst:1192 msgid "" "Added merge (``|``) and update (``|=``) operators, specified in :pep:`584`." msgstr "" @@ -1084,21 +1516,21 @@ msgstr "" msgid "" "When each key is encountered for the first time, it is not already in the " "mapping; so an entry is automatically created using the :attr:`~defaultdict." -"default_factory` function which returns an empty :class:`list`. The :meth:" -"`list.append` operation then attaches the value to the new list. When keys " +"default_factory` function which returns an empty :class:`list`. The :meth:`!" +"list.append` operation then attaches the value to the new list. When keys " "are encountered again, the look-up proceeds normally (returning the list for " -"that key) and the :meth:`list.append` operation adds another value to the " +"that key) and the :meth:`!list.append` operation adds another value to the " "list. This technique is simpler and faster than an equivalent technique " "using :meth:`dict.setdefault`:" msgstr "" "Quando cada chave é encontrada pela primeira vez, ela ainda não está no " "mapeamento; então uma entrada é criada automaticamente usando a função :attr:" "`~defaultdict.default_factory` que retorna uma :class:`list` vazia. A " -"operação :meth:`list.append` então anexa o valor à nova lista. Quando as " +"operação :meth:`!list.append` então anexa o valor à nova lista. Quando as " "chaves são encontradas novamente, a pesquisa prossegue normalmente " -"(retornando a lista daquela chave) e a operação :meth:`list.append` adiciona " -"outro valor à lista. Esta técnica é mais simples e rápida que uma técnica " -"equivalente usando :meth:`dict.setdefault`:" +"(retornando a lista daquela chave) e a operação :meth:`!list.append` " +"adiciona outro valor à lista. Esta técnica é mais simples e rápida que uma " +"técnica equivalente usando :meth:`dict.setdefault`:" #: ../../library/collections.rst:799 msgid "" @@ -1163,17 +1595,18 @@ msgid "" "Returns a new tuple subclass named *typename*. The new subclass is used to " "create tuple-like objects that have fields accessible by attribute lookup as " "well as being indexable and iterable. Instances of the subclass also have a " -"helpful docstring (with typename and field_names) and a helpful :meth:" -"`__repr__` method which lists the tuple contents in a ``name=value`` format." +"helpful docstring (with *typename* and *field_names*) and a helpful :meth:" +"`~object.__repr__` method which lists the tuple contents in a ``name=value`` " +"format." msgstr "" "Retorna uma nova subclasse de tupla chamada *typename*. A nova subclasse é " -"usada para criar objetos semelhantes a tuplas que possuem campos acessíveis " -"por pesquisa de atributos, além de serem indexáveis ​​e iteráveis. As " -"instâncias da subclasse também possuem uma docstring útil (com typename e " -"field_names) e um método útil :meth:`__repr__` que lista o conteúdo da tupla " -"em um formato ``nome=valor``." +"usada para criar objetos tupla ou similar que possuem campos acessíveis por " +"pesquisa de atributos, além de serem indexáveis e iteráveis. As instâncias " +"da subclasse também possuem uma docstring útil (com *typename* e " +"*field_names*) e um método útil :meth:`~object.__repr__` que lista o " +"conteúdo da tupla em um formato ``nome=valor``." -#: ../../library/collections.rst:855 +#: ../../library/collections.rst:856 msgid "" "The *field_names* are a sequence of strings such as ``['x', 'y']``. " "Alternatively, *field_names* can be a single string with each fieldname " @@ -1184,7 +1617,7 @@ msgstr "" "campo separado por espaços em branco e/ou vírgulas como, por exemplo, ``'x " "y'`` ou ``'x, y'``." -#: ../../library/collections.rst:859 +#: ../../library/collections.rst:860 msgid "" "Any valid Python identifier may be used for a fieldname except for names " "starting with an underscore. Valid identifiers consist of letters, digits, " @@ -1197,7 +1630,7 @@ msgstr "" "sublinhado e não podem ser uma :mod:`keyword` como *class*, *for*, *return*, " "*global*, *pass* ou *raise*." -#: ../../library/collections.rst:865 +#: ../../library/collections.rst:866 msgid "" "If *rename* is true, invalid fieldnames are automatically replaced with " "positional names. For example, ``['abc', 'def', 'ghi', 'abc']`` is " @@ -1209,7 +1642,7 @@ msgstr "" "'abc']`` é convertido para ``['abc', '_1', 'ghi', '_3']``, eliminando a " "palavra reservada ``def`` e o nome de campo duplicado ``abc``." -#: ../../library/collections.rst:870 +#: ../../library/collections.rst:871 msgid "" "*defaults* can be ``None`` or an :term:`iterable` of default values. Since " "fields with a default value must come after any fields without a default, " @@ -1225,15 +1658,15 @@ msgstr "" "então ``x`` será um argumento obrigatório, ``y`` será o padrão ``1``, e " "``z`` será o padrão ``2``." -#: ../../library/collections.rst:877 +#: ../../library/collections.rst:878 msgid "" -"If *module* is defined, the ``__module__`` attribute of the named tuple is " -"set to that value." +"If *module* is defined, the :attr:`~type.__module__` attribute of the named " +"tuple is set to that value." msgstr "" -"Se *module* for definido, o atributo ``__module__`` da tupla nomeada será " -"definido com esse valor." +"Se *module* for definido, o atributo :attr:`~type.__module__` da tupla " +"nomeada será definido com esse valor." -#: ../../library/collections.rst:880 +#: ../../library/collections.rst:881 msgid "" "Named tuple instances do not have per-instance dictionaries, so they are " "lightweight and require no more memory than regular tuples." @@ -1241,7 +1674,7 @@ msgstr "" "As instâncias de tuplas nomeadas não possuem dicionários por instância, " "portanto são leves e não requerem mais memória do que as tuplas normais." -#: ../../library/collections.rst:883 +#: ../../library/collections.rst:884 msgid "" "To support pickling, the named tuple class should be assigned to a variable " "that matches *typename*." @@ -1249,11 +1682,11 @@ msgstr "" "Para prover suporte para a serialização com pickle, a classe de tupla " "nomeada deve ser atribuída a uma variável que corresponda a *typename*." -#: ../../library/collections.rst:886 +#: ../../library/collections.rst:887 msgid "Added support for *rename*." msgstr "Adicionado suporte a *rename*." -#: ../../library/collections.rst:889 +#: ../../library/collections.rst:890 msgid "" "The *verbose* and *rename* parameters became :ref:`keyword-only arguments " "`." @@ -1261,21 +1694,53 @@ msgstr "" "Os parâmetros *verbose* e *rename* tornaram-se :ref:`argumentos somente-" "nomeados `." -#: ../../library/collections.rst:893 +#: ../../library/collections.rst:894 msgid "Added the *module* parameter." msgstr "Adicionado o parâmetro *module*." -#: ../../library/collections.rst:896 -msgid "Removed the *verbose* parameter and the :attr:`_source` attribute." -msgstr "Removido o parâmetro *verbose* e o atributo :attr:`_source`" - -#: ../../library/collections.rst:899 -msgid "" -"Added the *defaults* parameter and the :attr:`_field_defaults` attribute." -msgstr "" -"Adicionado o parâmetro *defaults* e o atributo :attr:`_field_defaults`." - -#: ../../library/collections.rst:919 +#: ../../library/collections.rst:897 +msgid "Removed the *verbose* parameter and the :attr:`!_source` attribute." +msgstr "Removido o parâmetro *verbose* e o atributo :attr:`!_source`." + +#: ../../library/collections.rst:900 +msgid "" +"Added the *defaults* parameter and the :attr:`~somenamedtuple." +"_field_defaults` attribute." +msgstr "" +"Adicionado o parâmetro *defaults* e o atributo :attr:`~somenamedtuple." +"_field_defaults`." + +#: ../../library/collections.rst:904 +msgid "" +">>> # Basic example\n" +">>> Point = namedtuple('Point', ['x', 'y'])\n" +">>> p = Point(11, y=22) # instantiate with positional or keyword " +"arguments\n" +">>> p[0] + p[1] # indexable like the plain tuple (11, 22)\n" +"33\n" +">>> x, y = p # unpack like a regular tuple\n" +">>> x, y\n" +"(11, 22)\n" +">>> p.x + p.y # fields also accessible by name\n" +"33\n" +">>> p # readable __repr__ with a name=value style\n" +"Point(x=11, y=22)" +msgstr "" +">>> # Exemplo básico\n" +">>> Point = namedtuple('Point', ['x', 'y'])\n" +">>> p = Point(11, y=22) # instancia com argumentos nomeados ou " +"posicionais\n" +">>> p[0] + p[1] # indexável como a tupla plana (11, 22)\n" +"33\n" +">>> x, y = p # desempacota como uma tupla normal\n" +">>> x, y\n" +"(11, 22)\n" +">>> p.x + p.y # campos também acessíveis pelo nome\n" +"33\n" +">>> p # __repr__ legível com o estilo nome=valor\n" +"Point(x=11, y=22)" + +#: ../../library/collections.rst:920 msgid "" "Named tuples are especially useful for assigning field names to result " "tuples returned by the :mod:`csv` or :mod:`sqlite3` modules::" @@ -1283,7 +1748,41 @@ msgstr "" "Tuplas nomeadas são especialmente úteis para atribuir nomes de campos a " "tuplas de resultados retornadas pelos módulos :mod:`csv` ou :mod:`sqlite3`::" -#: ../../library/collections.rst:935 +#: ../../library/collections.rst:923 +msgid "" +"EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, " +"paygrade')\n" +"\n" +"import csv\n" +"for emp in map(EmployeeRecord._make, csv.reader(open(\"employees.csv\", " +"\"rb\"))):\n" +" print(emp.name, emp.title)\n" +"\n" +"import sqlite3\n" +"conn = sqlite3.connect('/companydata')\n" +"cursor = conn.cursor()\n" +"cursor.execute('SELECT name, age, title, department, paygrade FROM " +"employees')\n" +"for emp in map(EmployeeRecord._make, cursor.fetchall()):\n" +" print(emp.name, emp.title)" +msgstr "" +"EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, " +"paygrade')\n" +"\n" +"import csv\n" +"for emp in map(EmployeeRecord._make, csv.reader(open(\"employees.csv\", " +"\"rb\"))):\n" +" print(emp.name, emp.title)\n" +"\n" +"import sqlite3\n" +"conn = sqlite3.connect('/companydata')\n" +"cursor = conn.cursor()\n" +"cursor.execute('SELECT name, age, title, department, paygrade FROM " +"employees')\n" +"for emp in map(EmployeeRecord._make, cursor.fetchall()):\n" +" print(emp.name, emp.title)" + +#: ../../library/collections.rst:936 msgid "" "In addition to the methods inherited from tuples, named tuples support three " "additional methods and two attributes. To prevent conflicts with field " @@ -1293,14 +1792,24 @@ msgstr "" "três métodos adicionais e dois atributos. Para evitar conflitos com nomes de " "campos, os nomes de métodos e atributos começam com um sublinhado." -#: ../../library/collections.rst:941 +#: ../../library/collections.rst:942 msgid "" "Class method that makes a new instance from an existing sequence or iterable." msgstr "" "Método de classe que cria uma nova instância a partir de uma sequência " "existente ou iterável." -#: ../../library/collections.rst:951 +#: ../../library/collections.rst:944 +msgid "" +">>> t = [11, 22]\n" +">>> Point._make(t)\n" +"Point(x=11, y=22)" +msgstr "" +">>> t = [11, 22]\n" +">>> Point._make(t)\n" +"Point(x=11, y=22)" + +#: ../../library/collections.rst:952 msgid "" "Return a new :class:`dict` which maps field names to their corresponding " "values:" @@ -1308,11 +1817,21 @@ msgstr "" "Retorna um novo :class:`dict` que mapeia nomes de campo para seus " "respectivos valores:" -#: ../../library/collections.rst:960 +#: ../../library/collections.rst:955 +msgid "" +">>> p = Point(x=11, y=22)\n" +">>> p._asdict()\n" +"{'x': 11, 'y': 22}" +msgstr "" +">>> p = Point(x=11, y=22)\n" +">>> p._asdict()\n" +"{'x': 11, 'y': 22}" + +#: ../../library/collections.rst:961 msgid "Returns an :class:`OrderedDict` instead of a regular :class:`dict`." msgstr "Retorna um :class:`OrderedDict` em vez de um :class:`dict` normal." -#: ../../library/collections.rst:963 +#: ../../library/collections.rst:964 msgid "" "Returns a regular :class:`dict` instead of an :class:`OrderedDict`. As of " "Python 3.7, regular dicts are guaranteed to be ordered. If the extra " @@ -1325,7 +1844,7 @@ msgstr "" "sugerida é converter o resultado para o tipo desejado: ``OrderedDict(nt." "_asdict())``." -#: ../../library/collections.rst:972 +#: ../../library/collections.rst:973 msgid "" "Return a new instance of the named tuple replacing specified fields with new " "values::" @@ -1333,14 +1852,32 @@ msgstr "" "Retorna uma nova instância da tupla nomeada substituindo os campos " "especificados por novos valores::" -#: ../../library/collections.rst:982 +#: ../../library/collections.rst:976 +msgid "" +">>> p = Point(x=11, y=22)\n" +">>> p._replace(x=33)\n" +"Point(x=33, y=22)\n" +"\n" +">>> for partnum, record in inventory.items():\n" +"... inventory[partnum] = record._replace(price=newprices[partnum], " +"timestamp=time.now())" +msgstr "" +">>> p = Point(x=11, y=22)\n" +">>> p._replace(x=33)\n" +"Point(x=33, y=22)\n" +"\n" +">>> for partnum, record in inventory.items():\n" +"... inventory[partnum] = record._replace(price=newprices[partnum], " +"timestamp=time.now())" + +#: ../../library/collections.rst:983 msgid "" "Named tuples are also supported by generic function :func:`copy.replace`." msgstr "" "Tuplas nomeadas também são suportados pela função genérica :func:`copy." "replace`." -#: ../../library/collections.rst:984 +#: ../../library/collections.rst:985 msgid "" "Raise :exc:`TypeError` instead of :exc:`ValueError` for invalid keyword " "arguments." @@ -1348,7 +1885,7 @@ msgstr "" "Levanta :exc:`TypeError` em vez de :exc:`ValueError` para argumentos " "nomeados inválidos." -#: ../../library/collections.rst:990 +#: ../../library/collections.rst:991 msgid "" "Tuple of strings listing the field names. Useful for introspection and for " "creating new named tuple types from existing named tuples." @@ -1356,11 +1893,43 @@ msgstr "" "Tupla de strings listando os nomes dos campos. Útil para introspecção e para " "criar novos tipos de tuplas nomeadas a partir de tuplas nomeadas existentes." -#: ../../library/collections.rst:1005 +#: ../../library/collections.rst:994 +msgid "" +">>> p._fields # view the field names\n" +"('x', 'y')\n" +"\n" +">>> Color = namedtuple('Color', 'red green blue')\n" +">>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)\n" +">>> Pixel(11, 22, 128, 255, 0)\n" +"Pixel(x=11, y=22, red=128, green=255, blue=0)" +msgstr "" +">>> p._fields # exibe os nomes de campos\n" +"('x', 'y')\n" +"\n" +">>> Color = namedtuple('Color', 'red green blue')\n" +">>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)\n" +">>> Pixel(11, 22, 128, 255, 0)\n" +"Pixel(x=11, y=22, red=128, green=255, blue=0)" + +#: ../../library/collections.rst:1006 msgid "Dictionary mapping field names to default values." msgstr "Dicionário mapeando nomes de campos para valores padrão." -#: ../../library/collections.rst:1015 +#: ../../library/collections.rst:1008 +msgid "" +">>> Account = namedtuple('Account', ['type', 'balance'], defaults=[0])\n" +">>> Account._field_defaults\n" +"{'balance': 0}\n" +">>> Account('premium')\n" +"Account(type='premium', balance=0)" +msgstr "" +">>> Account = namedtuple('Account', ['type', 'balance'], defaults=[0])\n" +">>> Account._field_defaults\n" +"{'balance': 0}\n" +">>> Account('premium')\n" +"Account(type='premium', balance=0)" + +#: ../../library/collections.rst:1016 msgid "" "To retrieve a field whose name is stored in a string, use the :func:" "`getattr` function:" @@ -1368,7 +1937,7 @@ msgstr "" "Para recuperar um campo cujo nome está armazenado em uma string, use a " "função :func:`getattr`:" -#: ../../library/collections.rst:1021 +#: ../../library/collections.rst:1022 msgid "" "To convert a dictionary to a named tuple, use the double-star-operator (as " "described in :ref:`tut-unpacking-arguments`):" @@ -1376,7 +1945,7 @@ msgstr "" "Para converter um dicionário em uma tupla nomeada, use o operador estrela " "dupla (conforme descrito em :ref:`tut-unpacking-arguments`):" -#: ../../library/collections.rst:1028 +#: ../../library/collections.rst:1029 msgid "" "Since a named tuple is a regular Python class, it is easy to add or change " "functionality with a subclass. Here is how to add a calculated field and a " @@ -1386,7 +1955,37 @@ msgstr "" "alterar funcionalidades com uma subclasse. Veja como adicionar um campo " "calculado e um formato de impressão de largura fixa:" -#: ../../library/collections.rst:1047 +#: ../../library/collections.rst:1033 +msgid "" +">>> class Point(namedtuple('Point', ['x', 'y'])):\n" +"... __slots__ = ()\n" +"... @property\n" +"... def hypot(self):\n" +"... return (self.x ** 2 + self.y ** 2) ** 0.5\n" +"... def __str__(self):\n" +"... return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, " +"self.hypot)\n" +"\n" +">>> for p in Point(3, 4), Point(14, 5/7):\n" +"... print(p)\n" +"Point: x= 3.000 y= 4.000 hypot= 5.000\n" +"Point: x=14.000 y= 0.714 hypot=14.018" +msgstr "" +">>> class Point(namedtuple('Point', ['x', 'y'])):\n" +"... __slots__ = ()\n" +"... @property\n" +"... def hypot(self):\n" +"... return (self.x ** 2 + self.y ** 2) ** 0.5\n" +"... def __str__(self):\n" +"... return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, " +"self.hypot)\n" +"\n" +">>> for p in Point(3, 4), Point(14, 5/7):\n" +"... print(p)\n" +"Point: x= 3.000 y= 4.000 hypot= 5.000\n" +"Point: x=14.000 y= 0.714 hypot=14.018" + +#: ../../library/collections.rst:1048 msgid "" "The subclass shown above sets ``__slots__`` to an empty tuple. This helps " "keep memory requirements low by preventing the creation of instance " @@ -1396,7 +1995,7 @@ msgstr "" "ajuda a manter baixos os requisitos de memória, evitando a criação de " "dicionários de instância." -#: ../../library/collections.rst:1050 +#: ../../library/collections.rst:1051 msgid "" "Subclassing is not useful for adding new, stored fields. Instead, simply " "create a new named tuple type from the :attr:`~somenamedtuple._fields` " @@ -1406,7 +2005,7 @@ msgstr "" "Em vez disso, simplesmente crie um novo tipo de tupla nomeado a partir do " "atributo :attr:`~somenamedtuple._fields`:" -#: ../../library/collections.rst:1055 +#: ../../library/collections.rst:1056 msgid "" "Docstrings can be customized by making direct assignments to the ``__doc__`` " "fields:" @@ -1414,11 +2013,11 @@ msgstr "" "Docstrings podem ser personalizados fazendo atribuições diretas aos campos " "``__doc__``:" -#: ../../library/collections.rst:1064 +#: ../../library/collections.rst:1065 msgid "Property docstrings became writeable." msgstr "Os docstrings de propriedade tornaram-se graváveis." -#: ../../library/collections.rst:1069 +#: ../../library/collections.rst:1070 msgid "" "See :class:`typing.NamedTuple` for a way to add type hints for named " "tuples. It also provides an elegant notation using the :keyword:`class` " @@ -1428,7 +2027,19 @@ msgstr "" "para tuplas nomeadas. Ele também fornece uma notação elegante usando a " "palavra reservada :keyword:`class`::" -#: ../../library/collections.rst:1078 +#: ../../library/collections.rst:1074 +msgid "" +"class Component(NamedTuple):\n" +" part_number: int\n" +" weight: float\n" +" description: Optional[str] = None" +msgstr "" +"class Component(NamedTuple):\n" +" part_number: int\n" +" weight: float\n" +" description: Optional[str] = None" + +#: ../../library/collections.rst:1079 msgid "" "See :meth:`types.SimpleNamespace` for a mutable namespace based on an " "underlying dictionary instead of a tuple." @@ -1436,7 +2047,7 @@ msgstr "" "Veja :meth:`types.SimpleNamespace` para um espaço de nomes mutável baseado " "em um dicionário subjacente em vez de uma tupla." -#: ../../library/collections.rst:1081 +#: ../../library/collections.rst:1082 msgid "" "The :mod:`dataclasses` module provides a decorator and functions for " "automatically adding generated special methods to user-defined classes." @@ -1444,11 +2055,11 @@ msgstr "" "O módulo :mod:`dataclasses` fornece um decorador e funções para adicionar " "automaticamente métodos especiais gerados a classes definidas pelo usuário." -#: ../../library/collections.rst:1086 +#: ../../library/collections.rst:1087 msgid ":class:`OrderedDict` objects" msgstr "Objetos :class:`OrderedDict`" -#: ../../library/collections.rst:1088 +#: ../../library/collections.rst:1089 msgid "" "Ordered dictionaries are just like regular dictionaries but have some extra " "capabilities relating to ordering operations. They have become less " @@ -1461,11 +2072,11 @@ msgstr "" "lembrar a ordem de inserção (esse novo comportamento foi garantido no Python " "3.7)." -#: ../../library/collections.rst:1094 +#: ../../library/collections.rst:1095 msgid "Some differences from :class:`dict` still remain:" msgstr "Algumas diferenças de :class:`dict` ainda permanecem:" -#: ../../library/collections.rst:1096 +#: ../../library/collections.rst:1097 msgid "" "The regular :class:`dict` was designed to be very good at mapping " "operations. Tracking insertion order was secondary." @@ -1473,7 +2084,7 @@ msgstr "" "O :class:`dict` regular foi projetado para ser muito bom em operações de " "mapeamento. O rastreamento do pedido de inserção era secundário." -#: ../../library/collections.rst:1099 +#: ../../library/collections.rst:1100 msgid "" "The :class:`OrderedDict` was designed to be good at reordering operations. " "Space efficiency, iteration speed, and the performance of update operations " @@ -1483,7 +2094,7 @@ msgstr "" "reordenação. A eficiência de espaço, a velocidade de iteração e o desempenho " "das operações de atualização eram secundários." -#: ../../library/collections.rst:1103 +#: ../../library/collections.rst:1104 msgid "" "The :class:`OrderedDict` algorithm can handle frequent reordering operations " "better than :class:`dict`. As shown in the recipes below, this makes it " @@ -1493,14 +2104,14 @@ msgstr "" "frequentes melhor do que :class:`dict`. Conforme mostrado nas receitas " "abaixo, isso o torna adequado para implementar vários tipos de caches LRU." -#: ../../library/collections.rst:1107 +#: ../../library/collections.rst:1108 msgid "" "The equality operation for :class:`OrderedDict` checks for matching order." msgstr "" "A operação de igualdade para :class:`OrderedDict` verifica a ordem " "correspondente." -#: ../../library/collections.rst:1109 +#: ../../library/collections.rst:1110 msgid "" "A regular :class:`dict` can emulate the order sensitive equality test with " "``p == q and all(k1 == k2 for k1, k2 in zip(p, q))``." @@ -1508,16 +2119,17 @@ msgstr "" "Um :class:`dict` regular pode emular o teste de igualdade sensível à ordem " "com ``p == q and all(k1 == k2 for k1, k2 in zip(p, q))``." -#: ../../library/collections.rst:1112 +#: ../../library/collections.rst:1113 msgid "" -"The :meth:`popitem` method of :class:`OrderedDict` has a different " -"signature. It accepts an optional argument to specify which item is popped." +"The :meth:`~OrderedDict.popitem` method of :class:`OrderedDict` has a " +"different signature. It accepts an optional argument to specify which item " +"is popped." msgstr "" -"O método :meth:`popitem` de :class:`OrderedDict` tem uma assinatura " -"diferente. Ele aceita um argumento opcional para especificar qual item será " -"exibido." +"O método :meth:`~OrderedDict.popitem` de :class:`OrderedDict` tem uma " +"assinatura diferente. Ele aceita um argumento opcional para especificar qual " +"item será exibido." -#: ../../library/collections.rst:1115 +#: ../../library/collections.rst:1116 msgid "" "A regular :class:`dict` can emulate OrderedDict's ``od.popitem(last=True)`` " "with ``d.popitem()`` which is guaranteed to pop the rightmost (last) item." @@ -1526,7 +2138,7 @@ msgstr "" "OrderedDict com ``d.popitem()`` que é garantido para exibir o (último) item " "mais à direita." -#: ../../library/collections.rst:1118 +#: ../../library/collections.rst:1119 msgid "" "A regular :class:`dict` can emulate OrderedDict's ``od.popitem(last=False)`` " "with ``(k := next(iter(d)), d.pop(k))`` which will return and remove the " @@ -1536,15 +2148,15 @@ msgstr "" "OrderedDict com ``(k := next(iter(d)), d.pop(k))`` que retornará e remova o " "item mais à esquerda (primeiro), se existir." -#: ../../library/collections.rst:1122 +#: ../../library/collections.rst:1123 msgid "" -":class:`OrderedDict` has a :meth:`move_to_end` method to efficiently " -"reposition an element to an endpoint." +":class:`OrderedDict` has a :meth:`~OrderedDict.move_to_end` method to " +"efficiently reposition an element to an endpoint." msgstr "" -":class:`OrderedDict` possui um método :meth:`move_to_end` para reposicionar " -"eficientemente um elemento em um endpoint." +":class:`OrderedDict` possui um método :meth:`~OrderedDict.move_to_end` para " +"reposicionar eficientemente um elemento em um endpoint." -#: ../../library/collections.rst:1125 +#: ../../library/collections.rst:1126 msgid "" "A regular :class:`dict` can emulate OrderedDict's ``od.move_to_end(k, " "last=True)`` with ``d[k] = d.pop(k)`` which will move the key and its " @@ -1554,7 +2166,7 @@ msgstr "" "OrderedDict com ``d[k] = d.pop(k)`` que moverá a chave e seu valor associado " "para a posição mais à direita (última)." -#: ../../library/collections.rst:1129 +#: ../../library/collections.rst:1130 msgid "" "A regular :class:`dict` does not have an efficient equivalent for " "OrderedDict's ``od.move_to_end(k, last=False)`` which moves the key and its " @@ -1564,12 +2176,14 @@ msgstr "" "move_to_end(k, last=False)`` do OrderedDict, que move a chave e seu valor " "associado para a posição mais à esquerda (primeira)." -#: ../../library/collections.rst:1133 -msgid "Until Python 3.8, :class:`dict` lacked a :meth:`__reversed__` method." +#: ../../library/collections.rst:1134 +msgid "" +"Until Python 3.8, :class:`dict` lacked a :meth:`~object.__reversed__` method." msgstr "" -"Até o Python 3.8, :class:`dict` não tinha um método :meth:`__reversed__`." +"Até o Python 3.8, :class:`dict` não tinha um método :meth:`~object." +"__reversed__`." -#: ../../library/collections.rst:1138 +#: ../../library/collections.rst:1139 msgid "" "Return an instance of a :class:`dict` subclass that has methods specialized " "for rearranging dictionary order." @@ -1577,7 +2191,7 @@ msgstr "" "Retorna uma instância de uma subclasse :class:`dict` que possui métodos " "especializados para reorganizar a ordem do dicionário." -#: ../../library/collections.rst:1145 +#: ../../library/collections.rst:1146 msgid "" "The :meth:`popitem` method for ordered dictionaries returns and removes a " "(key, value) pair. The pairs are returned in :abbr:`LIFO (last-in, first-" @@ -1589,7 +2203,7 @@ msgstr "" "entrar, primeiro a sair)` se *last* for verdadeiro ou na ordem :abbr:`FIFO " "(primeiro a entrar, primeiro a sair)` se for falso." -#: ../../library/collections.rst:1152 +#: ../../library/collections.rst:1153 msgid "" "Move an existing *key* to either end of an ordered dictionary. The item is " "moved to the right end if *last* is true (the default) or to the beginning " @@ -1600,7 +2214,25 @@ msgstr "" "verdadeiro (o padrão) ou para o início se *último* for falso. Levanta :exc:" "`KeyError` se a *key* não existir:" -#: ../../library/collections.rst:1169 +#: ../../library/collections.rst:1158 +msgid "" +">>> d = OrderedDict.fromkeys('abcde')\n" +">>> d.move_to_end('b')\n" +">>> ''.join(d)\n" +"'acdeb'\n" +">>> d.move_to_end('b', last=False)\n" +">>> ''.join(d)\n" +"'bacde'" +msgstr "" +">>> d = OrderedDict.fromkeys('abcde')\n" +">>> d.move_to_end('b')\n" +">>> ''.join(d)\n" +"'acdeb'\n" +">>> d.move_to_end('b', last=False)\n" +">>> ''.join(d)\n" +"'bacde'" + +#: ../../library/collections.rst:1170 msgid "" "In addition to the usual mapping methods, ordered dictionaries also support " "reverse iteration using :func:`reversed`." @@ -1608,23 +2240,28 @@ msgstr "" "Além dos métodos usuais de mapeamento, dicionários ordenados também oferecem " "suporte a iteração reversa usando a função :func:`reversed`." -#: ../../library/collections.rst:1172 +#: ../../library/collections.rst:1175 msgid "" "Equality tests between :class:`OrderedDict` objects are order-sensitive and " -"are implemented as ``list(od1.items())==list(od2.items())``. Equality tests " -"between :class:`OrderedDict` objects and other :class:`~collections.abc." -"Mapping` objects are order-insensitive like regular dictionaries. This " -"allows :class:`OrderedDict` objects to be substituted anywhere a regular " -"dictionary is used." +"are roughly equivalent to ``list(od1.items())==list(od2.items())``." msgstr "" "Testes de igualdade entre objetos :class:`OrderedDict` são sensíveis à ordem " -"e são implementados como ``list(od1.items())==list(od2.items())``. Testes de " -"igualdade entre objetos :class:`OrderedDict` e outros objetos :class:" -"`~collections.abc.Mapping` são insensíveis à ordem como dicionários " +"e são aproximadamente equivalentes a ``list(od1.items())==list(od2." +"items())``." + +#: ../../library/collections.rst:1178 +msgid "" +"Equality tests between :class:`OrderedDict` objects and other :class:" +"`~collections.abc.Mapping` objects are order-insensitive like regular " +"dictionaries. This allows :class:`OrderedDict` objects to be substituted " +"anywhere a regular dictionary is used." +msgstr "" +"Testes de igualdade entre objetos :class:`OrderedDict` e outros objetos :" +"class:`~collections.abc.Mapping` não diferenciam a ordem como dicionários " "regulares. Isso permite que objetos :class:`OrderedDict` sejam substituídos " "em qualquer lugar que um dicionário regular seja usado." -#: ../../library/collections.rst:1179 +#: ../../library/collections.rst:1183 msgid "" "The items, keys, and values :term:`views ` of :class:" "`OrderedDict` now support reverse iteration using :func:`reversed`." @@ -1633,19 +2270,21 @@ msgstr "" "`OrderedDict` agora oferecem suporte a iteração reversa usando :func:" "`reversed`." -#: ../../library/collections.rst:1183 +#: ../../library/collections.rst:1187 msgid "" "With the acceptance of :pep:`468`, order is retained for keyword arguments " -"passed to the :class:`OrderedDict` constructor and its :meth:`update` method." +"passed to the :class:`OrderedDict` constructor and its :meth:`~dict.update` " +"method." msgstr "" "Com a aceitação da :pep:`468`, a ordem é mantida para argumentos nomeados " -"passados ​​para o construtor :class:`OrderedDict` e seu método :meth:`update`." +"passados para o construtor :class:`OrderedDict` e seu método :meth:`~dict." +"update`." -#: ../../library/collections.rst:1193 +#: ../../library/collections.rst:1197 msgid ":class:`OrderedDict` Examples and Recipes" msgstr "Exemplos e receitas de :class:`OrderedDict`" -#: ../../library/collections.rst:1195 +#: ../../library/collections.rst:1199 msgid "" "It is straightforward to create an ordered dictionary variant that remembers " "the order the keys were *last* inserted. If a new entry overwrites an " @@ -1657,7 +2296,23 @@ msgstr "" "substituir uma entrada existente, a posição de inserção original será " "alterada e movida para o final::" -#: ../../library/collections.rst:1207 +#: ../../library/collections.rst:1204 +msgid "" +"class LastUpdatedOrderedDict(OrderedDict):\n" +" 'Store items in the order the keys were last added'\n" +"\n" +" def __setitem__(self, key, value):\n" +" super().__setitem__(key, value)\n" +" self.move_to_end(key)" +msgstr "" +"class LastUpdatedOrderedDict(OrderedDict):\n" +" 'Store items in the order the keys were last added'\n" +"\n" +" def __setitem__(self, key, value):\n" +" super().__setitem__(key, value)\n" +" self.move_to_end(key)" + +#: ../../library/collections.rst:1211 msgid "" "An :class:`OrderedDict` would also be useful for implementing variants of :" "func:`functools.lru_cache`:" @@ -1665,11 +2320,133 @@ msgstr "" "Um :class:`OrderedDict` também seria útil para implementar variantes de :" "func:`functools.lru_cache`:" -#: ../../library/collections.rst:1306 +#: ../../library/collections.rst:1214 +msgid "" +"from collections import OrderedDict\n" +"from time import time\n" +"\n" +"class TimeBoundedLRU:\n" +" \"LRU Cache that invalidates and refreshes old entries.\"\n" +"\n" +" def __init__(self, func, maxsize=128, maxage=30):\n" +" self.cache = OrderedDict() # { args : (timestamp, result)}\n" +" self.func = func\n" +" self.maxsize = maxsize\n" +" self.maxage = maxage\n" +"\n" +" def __call__(self, *args):\n" +" if args in self.cache:\n" +" self.cache.move_to_end(args)\n" +" timestamp, result = self.cache[args]\n" +" if time() - timestamp <= self.maxage:\n" +" return result\n" +" result = self.func(*args)\n" +" self.cache[args] = time(), result\n" +" if len(self.cache) > self.maxsize:\n" +" self.cache.popitem(last=False)\n" +" return result" +msgstr "" +"from collections import OrderedDict\n" +"from time import time\n" +"\n" +"class TimeBoundedLRU:\n" +" \"LRU Cache that invalidates and refreshes old entries.\"\n" +"\n" +" def __init__(self, func, maxsize=128, maxage=30):\n" +" self.cache = OrderedDict() # { args : (timestamp, result)}\n" +" self.func = func\n" +" self.maxsize = maxsize\n" +" self.maxage = maxage\n" +"\n" +" def __call__(self, *args):\n" +" if args in self.cache:\n" +" self.cache.move_to_end(args)\n" +" timestamp, result = self.cache[args]\n" +" if time() - timestamp <= self.maxage:\n" +" return result\n" +" result = self.func(*args)\n" +" self.cache[args] = time(), result\n" +" if len(self.cache) > self.maxsize:\n" +" self.cache.popitem(last=False)\n" +" return result" + +#: ../../library/collections.rst:1241 +msgid "" +"class MultiHitLRUCache:\n" +" \"\"\" LRU cache that defers caching a result until\n" +" it has been requested multiple times.\n" +"\n" +" To avoid flushing the LRU cache with one-time requests,\n" +" we don't cache until a request has been made more than once.\n" +"\n" +" \"\"\"\n" +"\n" +" def __init__(self, func, maxsize=128, maxrequests=4096, cache_after=1):\n" +" self.requests = OrderedDict() # { uncached_key : request_count }\n" +" self.cache = OrderedDict() # { cached_key : function_result }\n" +" self.func = func\n" +" self.maxrequests = maxrequests # max number of uncached requests\n" +" self.maxsize = maxsize # max number of stored return " +"values\n" +" self.cache_after = cache_after\n" +"\n" +" def __call__(self, *args):\n" +" if args in self.cache:\n" +" self.cache.move_to_end(args)\n" +" return self.cache[args]\n" +" result = self.func(*args)\n" +" self.requests[args] = self.requests.get(args, 0) + 1\n" +" if self.requests[args] <= self.cache_after:\n" +" self.requests.move_to_end(args)\n" +" if len(self.requests) > self.maxrequests:\n" +" self.requests.popitem(last=False)\n" +" else:\n" +" self.requests.pop(args, None)\n" +" self.cache[args] = result\n" +" if len(self.cache) > self.maxsize:\n" +" self.cache.popitem(last=False)\n" +" return result" +msgstr "" +"class MultiHitLRUCache:\n" +" \"\"\" LRU cache that defers caching a result until\n" +" it has been requested multiple times.\n" +"\n" +" To avoid flushing the LRU cache with one-time requests,\n" +" we don't cache until a request has been made more than once.\n" +"\n" +" \"\"\"\n" +"\n" +" def __init__(self, func, maxsize=128, maxrequests=4096, cache_after=1):\n" +" self.requests = OrderedDict() # { uncached_key : request_count }\n" +" self.cache = OrderedDict() # { cached_key : function_result }\n" +" self.func = func\n" +" self.maxrequests = maxrequests # max number of uncached requests\n" +" self.maxsize = maxsize # max number of stored return " +"values\n" +" self.cache_after = cache_after\n" +"\n" +" def __call__(self, *args):\n" +" if args in self.cache:\n" +" self.cache.move_to_end(args)\n" +" return self.cache[args]\n" +" result = self.func(*args)\n" +" self.requests[args] = self.requests.get(args, 0) + 1\n" +" if self.requests[args] <= self.cache_after:\n" +" self.requests.move_to_end(args)\n" +" if len(self.requests) > self.maxrequests:\n" +" self.requests.popitem(last=False)\n" +" else:\n" +" self.requests.pop(args, None)\n" +" self.cache[args] = result\n" +" if len(self.cache) > self.maxsize:\n" +" self.cache.popitem(last=False)\n" +" return result" + +#: ../../library/collections.rst:1310 msgid ":class:`UserDict` objects" msgstr "Objetos :class:`UserDict`" -#: ../../library/collections.rst:1308 +#: ../../library/collections.rst:1312 msgid "" "The class, :class:`UserDict` acts as a wrapper around dictionary objects. " "The need for this class has been partially supplanted by the ability to " @@ -1682,7 +2459,7 @@ msgstr "" "essa classe pode ser mais fácil de trabalhar porque o dicionário subjacente " "é acessível como um atributo." -#: ../../library/collections.rst:1316 +#: ../../library/collections.rst:1320 msgid "" "Class that simulates a dictionary. The instance's contents are kept in a " "regular dictionary, which is accessible via the :attr:`data` attribute of :" @@ -1696,7 +2473,7 @@ msgstr "" "inicializado com seu conteúdo; observe que a referência a *initialdata* não " "será mantida, permitindo sua utilização para outros fins." -#: ../../library/collections.rst:1322 +#: ../../library/collections.rst:1326 msgid "" "In addition to supporting the methods and operations of mappings, :class:" "`UserDict` instances provide the following attribute:" @@ -1704,18 +2481,18 @@ msgstr "" "Além de prover suporte aos métodos e operações de mapeamentos, as " "instâncias :class:`UserDict` fornecem o seguinte atributo:" -#: ../../library/collections.rst:1327 +#: ../../library/collections.rst:1331 msgid "" "A real dictionary used to store the contents of the :class:`UserDict` class." msgstr "" "Um dicionário real usado para armazenar o conteúdo da classe :class:" "`UserDict`." -#: ../../library/collections.rst:1333 +#: ../../library/collections.rst:1337 msgid ":class:`UserList` objects" msgstr "Objetos :class:`UserList`" -#: ../../library/collections.rst:1335 +#: ../../library/collections.rst:1339 msgid "" "This class acts as a wrapper around list objects. It is a useful base class " "for your own list-like classes which can inherit from them and override " @@ -1727,7 +2504,7 @@ msgstr "" "herdar delas e substituir métodos existentes ou adicionar novos. Desta " "forma, é possível adicionar novos comportamentos às listas." -#: ../../library/collections.rst:1340 +#: ../../library/collections.rst:1344 msgid "" "The need for this class has been partially supplanted by the ability to " "subclass directly from :class:`list`; however, this class can be easier to " @@ -1738,7 +2515,7 @@ msgstr "" "fácil trabalhar com essa classe porque a lista subjacente pode ser acessada " "como um atributo." -#: ../../library/collections.rst:1346 +#: ../../library/collections.rst:1350 msgid "" "Class that simulates a list. The instance's contents are kept in a regular " "list, which is accessible via the :attr:`data` attribute of :class:" @@ -1752,7 +2529,7 @@ msgstr "" "cópia de *list*, padronizando a lista vazia ``[]``. *list* pode ser qualquer " "iterável, por exemplo, uma lista Python real ou um objeto :class:`UserList`." -#: ../../library/collections.rst:1352 +#: ../../library/collections.rst:1356 msgid "" "In addition to supporting the methods and operations of mutable sequences, :" "class:`UserList` instances provide the following attribute:" @@ -1760,7 +2537,7 @@ msgstr "" "Além de prover suporte aos métodos e operações de sequências mutáveis, as " "instâncias :class:`UserList` fornecem o seguinte atributo:" -#: ../../library/collections.rst:1357 +#: ../../library/collections.rst:1361 msgid "" "A real :class:`list` object used to store the contents of the :class:" "`UserList` class." @@ -1768,7 +2545,7 @@ msgstr "" "Um objeto :class:`list` real usado para armazenar o conteúdo da classe :" "class:`UserList`." -#: ../../library/collections.rst:1360 +#: ../../library/collections.rst:1364 msgid "" "**Subclassing requirements:** Subclasses of :class:`UserList` are expected " "to offer a constructor which can be called with either no arguments or one " @@ -1784,7 +2561,7 @@ msgstr "" "construtor pode ser chamado com um único parâmetro, que é um objeto de " "sequência usado como fonte de dados." -#: ../../library/collections.rst:1367 +#: ../../library/collections.rst:1371 msgid "" "If a derived class does not wish to comply with this requirement, all of the " "special methods supported by this class will need to be overridden; please " @@ -1796,11 +2573,11 @@ msgstr "" "consulte as fontes para obter informações sobre os métodos que precisam ser " "fornecidos nesse caso." -#: ../../library/collections.rst:1373 +#: ../../library/collections.rst:1377 msgid ":class:`UserString` objects" msgstr "Objetos :class:`UserString`" -#: ../../library/collections.rst:1375 +#: ../../library/collections.rst:1379 msgid "" "The class, :class:`UserString` acts as a wrapper around string objects. The " "need for this class has been partially supplanted by the ability to subclass " @@ -1813,7 +2590,7 @@ msgstr "" "classe pode ser mais fácil de trabalhar porque a string subjacente é " "acessível como um atributo." -#: ../../library/collections.rst:1383 +#: ../../library/collections.rst:1387 msgid "" "Class that simulates a string object. The instance's content is kept in a " "regular string object, which is accessible via the :attr:`data` attribute " @@ -1827,7 +2604,7 @@ msgstr "" "definido como uma cópia de *seq*. O argumento *seq* pode ser qualquer objeto " "que possa ser convertido em uma string usando a função embutida :func:`str`." -#: ../../library/collections.rst:1390 +#: ../../library/collections.rst:1394 msgid "" "In addition to supporting the methods and operations of strings, :class:" "`UserString` instances provide the following attribute:" @@ -1835,7 +2612,7 @@ msgstr "" "Além de prover suporte aos métodos e operações de strings, as instâncias :" "class:`UserString` fornecem o seguinte atributo:" -#: ../../library/collections.rst:1395 +#: ../../library/collections.rst:1399 msgid "" "A real :class:`str` object used to store the contents of the :class:" "`UserString` class." @@ -1843,7 +2620,7 @@ msgstr "" "Um objeto :class:`str` real usado para armazenar o conteúdo da classe :class:" "`UserString`." -#: ../../library/collections.rst:1398 +#: ../../library/collections.rst:1402 msgid "" "New methods ``__getnewargs__``, ``__rmod__``, ``casefold``, ``format_map``, " "``isprintable``, and ``maketrans``." diff --git a/library/colorsys.po b/library/colorsys.po index aa2e97fd5..5a5b8ce69 100644 --- a/library/colorsys.po +++ b/library/colorsys.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Italo Penaforte , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 00:57+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -92,3 +91,17 @@ msgstr "Converte a cor de coordenadas HSV para coordenadas RGB." #: ../../library/colorsys.rst:59 msgid "Example::" msgstr "Exemplo::" + +#: ../../library/colorsys.rst:61 +msgid "" +">>> import colorsys\n" +">>> colorsys.rgb_to_hsv(0.2, 0.4, 0.4)\n" +"(0.5, 0.5, 0.4)\n" +">>> colorsys.hsv_to_rgb(0.5, 0.5, 0.4)\n" +"(0.2, 0.4, 0.4)" +msgstr "" +">>> import colorsys\n" +">>> colorsys.rgb_to_hsv(0.2, 0.4, 0.4)\n" +"(0.5, 0.5, 0.4)\n" +">>> colorsys.hsv_to_rgb(0.5, 0.5, 0.4)\n" +"(0.2, 0.4, 0.4)" diff --git a/library/compileall.po b/library/compileall.po index 9f203052c..bd72b8695 100644 --- a/library/compileall.po +++ b/library/compileall.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:57+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -48,8 +47,8 @@ msgstr "" "gravação nos diretórios da biblioteca." #: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +msgid "Availability" +msgstr "Disponibilidade" #: ../../includes/wasm-notavail.rst:5 msgid "" @@ -173,10 +172,10 @@ msgstr "" #: ../../library/compileall.rst:92 msgid "" "Use *N* workers to compile the files within the given directory. If ``0`` is " -"used, then the result of :func:`os.process_cpu_count()` will be used." +"used, then the result of :func:`os.process_cpu_count` will be used." msgstr "" -"Use *N* workers para compilar os arquivos dentro do diretório especificado. " -"Se ``0`` for usado, o resultado de :func:`os.process_cpu_count()` será usado." +"Usa *N* workers para compilar os arquivos dentro do diretório especificado. " +"Se ``0`` for usado, o resultado de :func:`os.process_cpu_count` será usado." #: ../../library/compileall.rst:98 msgid "" @@ -543,6 +542,32 @@ msgstr "" "Para forçar uma recompilação de todos os arquivos :file:`.py` no " "subdiretório :file:`Lib/` e todos os seus subdiretórios::" +#: ../../library/compileall.rst:326 +msgid "" +"import compileall\n" +"\n" +"compileall.compile_dir('Lib/', force=True)\n" +"\n" +"# Perform same compilation, excluding files in .svn directories.\n" +"import re\n" +"compileall.compile_dir('Lib/', rx=re.compile(r'[/\\\\][.]svn'), force=True)\n" +"\n" +"# pathlib.Path objects can also be used.\n" +"import pathlib\n" +"compileall.compile_dir(pathlib.Path('Lib/'), force=True)" +msgstr "" +"import compileall\n" +"\n" +"compileall.compile_dir('Lib/', force=True)\n" +"\n" +"# Efetua a mesma compilação, excluindo arquivos em diretórios .svn.\n" +"import re\n" +"compileall.compile_dir('Lib/', rx=re.compile(r'[/\\\\][.]svn'), force=True)\n" +"\n" +"# Objetos pathlib.Path também podem ser usados.\n" +"import pathlib\n" +"compileall.compile_dir(pathlib.Path('Lib/'), force=True)" + #: ../../library/compileall.rst:340 msgid "Module :mod:`py_compile`" msgstr "Módulo :mod:`py_compile`" diff --git a/library/concurrency.po b/library/concurrency.po index e4df7e60d..733917117 100644 --- a/library/concurrency.po +++ b/library/concurrency.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Hildeberto Abreu Magalhães , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:57+0000\n" -"Last-Translator: Hildeberto Abreu Magalhães , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/concurrent.futures.po b/library/concurrent.futures.po index e03f2deb0..62749ab83 100644 --- a/library/concurrent.futures.po +++ b/library/concurrent.futures.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Vinicius Gubiani Ferreira , 2021 -# i17obot , 2021 -# Danilo Lima , 2021 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:57+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -56,8 +50,8 @@ msgid "" msgstr "" #: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +msgid "Availability" +msgstr "Disponibilidade" #: ../../includes/wasm-notavail.rst:5 msgid "" @@ -84,6 +78,13 @@ msgid "" "callable. ::" msgstr "" +#: ../../library/concurrent.futures.rst:38 +msgid "" +"with ThreadPoolExecutor(max_workers=1) as executor:\n" +" future = executor.submit(pow, 323, 1235)\n" +" print(future.result())" +msgstr "" + #: ../../library/concurrent.futures.rst:44 msgid "Similar to :func:`map(fn, *iterables) ` except:" msgstr "" @@ -167,6 +168,16 @@ msgid "" "meth:`Executor.shutdown` were called with *wait* set to ``True``)::" msgstr "" +#: ../../library/concurrent.futures.rst:100 +msgid "" +"import shutil\n" +"with ThreadPoolExecutor(max_workers=4) as e:\n" +" e.submit(shutil.copy, 'src1.txt', 'dest1.txt')\n" +" e.submit(shutil.copy, 'src2.txt', 'dest2.txt')\n" +" e.submit(shutil.copy, 'src3.txt', 'dest3.txt')\n" +" e.submit(shutil.copy, 'src4.txt', 'dest4.txt')" +msgstr "" + #: ../../library/concurrent.futures.rst:107 msgid "Added *cancel_futures*." msgstr "Adicionado *cancel_futures*." @@ -187,10 +198,41 @@ msgid "" "waits on the results of another :class:`Future`. For example::" msgstr "" +#: ../../library/concurrent.futures.rst:120 +msgid "" +"import time\n" +"def wait_on_b():\n" +" time.sleep(5)\n" +" print(b.result()) # b will never complete because it is waiting on a.\n" +" return 5\n" +"\n" +"def wait_on_a():\n" +" time.sleep(5)\n" +" print(a.result()) # a will never complete because it is waiting on b.\n" +" return 6\n" +"\n" +"\n" +"executor = ThreadPoolExecutor(max_workers=2)\n" +"a = executor.submit(wait_on_b)\n" +"b = executor.submit(wait_on_a)" +msgstr "" + #: ../../library/concurrent.futures.rst:136 msgid "And::" msgstr "" +#: ../../library/concurrent.futures.rst:138 +msgid "" +"def wait_on_future():\n" +" f = executor.submit(pow, 5, 2)\n" +" # This will never complete because there is only one worker thread and\n" +" # it is executing this function.\n" +" print(f.result())\n" +"\n" +"executor = ThreadPoolExecutor(max_workers=1)\n" +"executor.submit(wait_on_future)" +msgstr "" + #: ../../library/concurrent.futures.rst:150 msgid "" "An :class:`Executor` subclass that uses a pool of at most *max_workers* " @@ -261,6 +303,37 @@ msgstr "" msgid "ThreadPoolExecutor Example" msgstr "Exemplo de ThreadPoolExecutor" +#: ../../library/concurrent.futures.rst:202 +msgid "" +"import concurrent.futures\n" +"import urllib.request\n" +"\n" +"URLS = ['http://www.foxnews.com/',\n" +" 'http://www.cnn.com/',\n" +" 'http://europe.wsj.com/',\n" +" 'http://www.bbc.co.uk/',\n" +" 'http://nonexistent-subdomain.python.org/']\n" +"\n" +"# Retrieve a single page and report the URL and contents\n" +"def load_url(url, timeout):\n" +" with urllib.request.urlopen(url, timeout=timeout) as conn:\n" +" return conn.read()\n" +"\n" +"# We can use a with statement to ensure threads are cleaned up promptly\n" +"with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:\n" +" # Start the load operations and mark each future with its URL\n" +" future_to_url = {executor.submit(load_url, url, 60): url for url in " +"URLS}\n" +" for future in concurrent.futures.as_completed(future_to_url):\n" +" url = future_to_url[future]\n" +" try:\n" +" data = future.result()\n" +" except Exception as exc:\n" +" print('%r generated an exception: %s' % (url, exc))\n" +" else:\n" +" print('%r page is %d bytes' % (url, len(data)))" +msgstr "" + #: ../../library/concurrent.futures.rst:231 msgid "ProcessPoolExecutor" msgstr "```ProcessPoolExecutor```" @@ -371,6 +444,42 @@ msgstr "" msgid "ProcessPoolExecutor Example" msgstr "" +#: ../../library/concurrent.futures.rst:319 +msgid "" +"import concurrent.futures\n" +"import math\n" +"\n" +"PRIMES = [\n" +" 112272535095293,\n" +" 112582705942171,\n" +" 112272535095293,\n" +" 115280095190773,\n" +" 115797848077099,\n" +" 1099726899285419]\n" +"\n" +"def is_prime(n):\n" +" if n < 2:\n" +" return False\n" +" if n == 2:\n" +" return True\n" +" if n % 2 == 0:\n" +" return False\n" +"\n" +" sqrt_n = int(math.floor(math.sqrt(n)))\n" +" for i in range(3, sqrt_n + 1, 2):\n" +" if n % i == 0:\n" +" return False\n" +" return True\n" +"\n" +"def main():\n" +" with concurrent.futures.ProcessPoolExecutor() as executor:\n" +" for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):\n" +" print('%d is prime: %s' % (number, prime))\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" + #: ../../library/concurrent.futures.rst:354 msgid "Future Objects" msgstr "" diff --git a/library/concurrent.po b/library/concurrent.po index d1890a4c6..3095081ed 100644 --- a/library/concurrent.po +++ b/library/concurrent.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:57+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/configparser.po b/library/configparser.po index 8728f605e..f84018d03 100644 --- a/library/configparser.po +++ b/library/configparser.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Leticia Portella , 2021 -# i17obot , 2021 -# Vitor Buxbaum Orlandi, 2023 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:57+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -55,8 +50,8 @@ msgid "" "This library does *not* interpret or write the value-type prefixes used in " "the Windows Registry extended version of INI syntax." msgstr "" -"Esta biblioteca *não* interpreta ou escreve os prefixos de tipo de valor " -"usados ​​na versão estendida do Registro do Windows da sintaxe INI." +"Esta biblioteca *não* interpreta nem escreve os prefixos de tipo de valor " +"usados na versão estendida do Registro do Windows da sintaxe INI." #: ../../library/configparser.rst:36 msgid "Module :mod:`tomllib`" @@ -95,15 +90,43 @@ msgstr "" "O módulo ``json`` implementa um subconjunto de sintaxe JavaScript que às " "vezes é usado para configuração, mas não suporta comentários." -#: ../../library/configparser.rst:60 +#: ../../library/configparser.rst:61 msgid "Quick Start" msgstr "Início rápido" -#: ../../library/configparser.rst:62 +#: ../../library/configparser.rst:63 msgid "Let's take a very basic configuration file that looks like this:" msgstr "Vamos pegar um arquivo de configuração bem básico parecido com este:" -#: ../../library/configparser.rst:79 +#: ../../library/configparser.rst:65 +msgid "" +"[DEFAULT]\n" +"ServerAliveInterval = 45\n" +"Compression = yes\n" +"CompressionLevel = 9\n" +"ForwardX11 = yes\n" +"\n" +"[forge.example]\n" +"User = hg\n" +"\n" +"[topsecret.server.example]\n" +"Port = 50022\n" +"ForwardX11 = no" +msgstr "" +"[DEFAULT]\n" +"ServerAliveInterval = 45\n" +"Compression = yes\n" +"CompressionLevel = 9\n" +"ForwardX11 = yes\n" +"\n" +"[forge.example]\n" +"User = hg\n" +"\n" +"[topsecret.server.example]\n" +"Port = 50022\n" +"ForwardX11 = no" + +#: ../../library/configparser.rst:80 msgid "" "The structure of INI files is described `in the following section " "<#supported-ini-file-structure>`_. Essentially, the file consists of " @@ -117,7 +140,41 @@ msgstr "" "escrever tais arquivos. Vamos começar criando o arquivo de configuração " "acima programaticamente." -#: ../../library/configparser.rst:103 +#: ../../library/configparser.rst:86 +msgid "" +">>> import configparser\n" +">>> config = configparser.ConfigParser()\n" +">>> config['DEFAULT'] = {'ServerAliveInterval': '45',\n" +"... 'Compression': 'yes',\n" +"... 'CompressionLevel': '9'}\n" +">>> config['forge.example'] = {}\n" +">>> config['forge.example']['User'] = 'hg'\n" +">>> config['topsecret.server.example'] = {}\n" +">>> topsecret = config['topsecret.server.example']\n" +">>> topsecret['Port'] = '50022' # mutates the parser\n" +">>> topsecret['ForwardX11'] = 'no' # same here\n" +">>> config['DEFAULT']['ForwardX11'] = 'yes'\n" +">>> with open('example.ini', 'w') as configfile:\n" +"... config.write(configfile)\n" +"..." +msgstr "" +">>> import configparser\n" +">>> config = configparser.ConfigParser()\n" +">>> config['DEFAULT'] = {'ServerAliveInterval': '45',\n" +"... 'Compression': 'yes',\n" +"... 'CompressionLevel': '9'}\n" +">>> config['forge.example'] = {}\n" +">>> config['forge.example']['User'] = 'hg'\n" +">>> config['topsecret.server.example'] = {}\n" +">>> topsecret = config['topsecret.server.example']\n" +">>> topsecret['Port'] = '50022' # mutates the parser\n" +">>> topsecret['ForwardX11'] = 'no' # same here\n" +">>> config['DEFAULT']['ForwardX11'] = 'yes'\n" +">>> with open('example.ini', 'w') as configfile:\n" +"... config.write(configfile)\n" +"..." + +#: ../../library/configparser.rst:104 msgid "" "As you can see, we can treat a config parser much like a dictionary. There " "are differences, `outlined later <#mapping-protocol-access>`_, but the " @@ -128,7 +185,7 @@ msgstr "" "protocol-access>`_, mas o comportamento é muito próximo do que você " "esperaria de um dicionário." -#: ../../library/configparser.rst:107 +#: ../../library/configparser.rst:108 msgid "" "Now that we have created and saved a configuration file, let's read it back " "and explore the data it holds." @@ -136,7 +193,69 @@ msgstr "" "Agora que criamos e salvamos um arquivo de configuração, vamos lê-lo e " "explorar os dados que ele contém." -#: ../../library/configparser.rst:142 +#: ../../library/configparser.rst:111 +msgid "" +">>> config = configparser.ConfigParser()\n" +">>> config.sections()\n" +"[]\n" +">>> config.read('example.ini')\n" +"['example.ini']\n" +">>> config.sections()\n" +"['forge.example', 'topsecret.server.example']\n" +">>> 'forge.example' in config\n" +"True\n" +">>> 'python.org' in config\n" +"False\n" +">>> config['forge.example']['User']\n" +"'hg'\n" +">>> config['DEFAULT']['Compression']\n" +"'yes'\n" +">>> topsecret = config['topsecret.server.example']\n" +">>> topsecret['ForwardX11']\n" +"'no'\n" +">>> topsecret['Port']\n" +"'50022'\n" +">>> for key in config['forge.example']:\n" +"... print(key)\n" +"user\n" +"compressionlevel\n" +"serveraliveinterval\n" +"compression\n" +"forwardx11\n" +">>> config['forge.example']['ForwardX11']\n" +"'yes'" +msgstr "" +">>> config = configparser.ConfigParser()\n" +">>> config.sections()\n" +"[]\n" +">>> config.read('example.ini')\n" +"['example.ini']\n" +">>> config.sections()\n" +"['forge.example', 'topsecret.server.example']\n" +">>> 'forge.example' in config\n" +"True\n" +">>> 'python.org' in config\n" +"False\n" +">>> config['forge.example']['User']\n" +"'hg'\n" +">>> config['DEFAULT']['Compression']\n" +"'yes'\n" +">>> topsecret = config['topsecret.server.example']\n" +">>> topsecret['ForwardX11']\n" +"'no'\n" +">>> topsecret['Port']\n" +"'50022'\n" +">>> for key in config['forge.example']:\n" +"... print(key)\n" +"user\n" +"compressionlevel\n" +"serveraliveinterval\n" +"compression\n" +"forwardx11\n" +">>> config['forge.example']['ForwardX11']\n" +"'yes'" + +#: ../../library/configparser.rst:143 msgid "" "As we can see above, the API is pretty straightforward. The only bit of " "magic involves the ``DEFAULT`` section which provides default values for all " @@ -148,7 +267,7 @@ msgstr "" "[1]_. Observe também que as chaves nas seções não diferenciam maiúsculas de " "minúsculas e são armazenadas em letras minúsculas [1]_." -#: ../../library/configparser.rst:147 ../../library/configparser.rst:992 +#: ../../library/configparser.rst:148 ../../library/configparser.rst:1003 msgid "" "It is possible to read several configurations into a single :class:" "`ConfigParser`, where the most recently added configuration has the highest " @@ -164,19 +283,51 @@ msgstr "" "exemplo a seguir lê um arquivo chamado ``override.ini``, que irá substituir " "chaves repetidas do arquivo ``example.ini``." -#: ../../library/configparser.rst:173 +#: ../../library/configparser.rst:155 ../../library/configparser.rst:1010 +msgid "" +"[DEFAULT]\n" +"ServerAliveInterval = -1" +msgstr "" +"[DEFAULT]\n" +"ServerAliveInterval = -1" + +#: ../../library/configparser.rst:160 ../../library/configparser.rst:1015 +msgid "" +">>> config_override = configparser.ConfigParser()\n" +">>> config_override['DEFAULT'] = {'ServerAliveInterval': '-1'}\n" +">>> with open('override.ini', 'w') as configfile:\n" +"... config_override.write(configfile)\n" +"...\n" +">>> config_override = configparser.ConfigParser()\n" +">>> config_override.read(['example.ini', 'override.ini'])\n" +"['example.ini', 'override.ini']\n" +">>> print(config_override.get('DEFAULT', 'ServerAliveInterval'))\n" +"-1" +msgstr "" +">>> config_override = configparser.ConfigParser()\n" +">>> config_override['DEFAULT'] = {'ServerAliveInterval': '-1'}\n" +">>> with open('override.ini', 'w') as configfile:\n" +"... config_override.write(configfile)\n" +"...\n" +">>> config_override = configparser.ConfigParser()\n" +">>> config_override.read(['example.ini', 'override.ini'])\n" +"['example.ini', 'override.ini']\n" +">>> print(config_override.get('DEFAULT', 'ServerAliveInterval'))\n" +"-1" + +#: ../../library/configparser.rst:174 msgid "" "This behaviour is equivalent to a :meth:`ConfigParser.read` call with " "several files passed to the *filenames* parameter." msgstr "" "Este comportamento é equivalente a uma chamada :meth:`ConfigParser.read` com " -"vários arquivos passados ​​para o parâmetro *filenames*." +"vários arquivos passados para o parâmetro *filenames*." -#: ../../library/configparser.rst:178 +#: ../../library/configparser.rst:179 msgid "Supported Datatypes" msgstr "Tipos de dados suportados" -#: ../../library/configparser.rst:180 +#: ../../library/configparser.rst:181 msgid "" "Config parsers do not guess datatypes of values in configuration files, " "always storing them internally as strings. This means that if you need " @@ -187,7 +338,19 @@ msgstr "" "como strings. Isso significa que se você precisar de outros tipos de dados, " "deverá converter por conta própria:" -#: ../../library/configparser.rst:191 +#: ../../library/configparser.rst:185 +msgid "" +">>> int(topsecret['Port'])\n" +"50022\n" +">>> float(topsecret['CompressionLevel'])\n" +"9.0" +msgstr "" +">>> int(topsecret['Port'])\n" +"50022\n" +">>> float(topsecret['CompressionLevel'])\n" +"9.0" + +#: ../../library/configparser.rst:192 msgid "" "Since this task is so common, config parsers provide a range of handy getter " "methods to handle integers, floats and booleans. The last one is the most " @@ -207,7 +370,23 @@ msgstr "" "booleanos de ``'yes'``/``'no'``, ``'on'``/``'off'``, ``'true'`` /``'false'`` " "e ``'1'``/``'0'`` [1]_. Por exemplo:" -#: ../../library/configparser.rst:208 +#: ../../library/configparser.rst:200 +msgid "" +">>> topsecret.getboolean('ForwardX11')\n" +"False\n" +">>> config['forge.example'].getboolean('ForwardX11')\n" +"True\n" +">>> config.getboolean('forge.example', 'Compression')\n" +"True" +msgstr "" +">>> topsecret.getboolean('ForwardX11')\n" +"False\n" +">>> config['forge.example'].getboolean('ForwardX11')\n" +"True\n" +">>> config.getboolean('forge.example', 'Compression')\n" +"True" + +#: ../../library/configparser.rst:209 msgid "" "Apart from :meth:`~ConfigParser.getboolean`, config parsers also provide " "equivalent :meth:`~ConfigParser.getint` and :meth:`~ConfigParser.getfloat` " @@ -219,11 +398,11 @@ msgstr "" "`~ConfigParser.getfloat` equivalentes. Você pode registrar seus próprios " "conversores e personalizar os fornecidos. [1]_" -#: ../../library/configparser.rst:214 +#: ../../library/configparser.rst:215 msgid "Fallback Values" msgstr "Valores reservas" -#: ../../library/configparser.rst:216 +#: ../../library/configparser.rst:217 msgid "" "As with a dictionary, you can use a section's :meth:`~ConfigParser.get` " "method to provide fallback values:" @@ -231,7 +410,25 @@ msgstr "" "Assim como acontece com um dicionário, você pode usar o método :meth:" "`~ConfigParser.get` de uma seção para fornecer valores reservas (fallback):" -#: ../../library/configparser.rst:229 +#: ../../library/configparser.rst:220 +msgid "" +">>> topsecret.get('Port')\n" +"'50022'\n" +">>> topsecret.get('CompressionLevel')\n" +"'9'\n" +">>> topsecret.get('Cipher')\n" +">>> topsecret.get('Cipher', '3des-cbc')\n" +"'3des-cbc'" +msgstr "" +">>> topsecret.get('Port')\n" +"'50022'\n" +">>> topsecret.get('CompressionLevel')\n" +"'9'\n" +">>> topsecret.get('Cipher')\n" +">>> topsecret.get('Cipher', '3des-cbc')\n" +"'3des-cbc'" + +#: ../../library/configparser.rst:230 msgid "" "Please note that default values have precedence over fallback values. For " "instance, in our example the ``'CompressionLevel'`` key was specified only " @@ -245,7 +442,15 @@ msgstr "" "``'topsecret.server.example'``, sempre obteremos o padrão, mesmo se " "especificarmos um substituto:" -#: ../../library/configparser.rst:240 +#: ../../library/configparser.rst:236 +msgid "" +">>> topsecret.get('CompressionLevel', '3')\n" +"'9'" +msgstr "" +">>> topsecret.get('CompressionLevel', '3')\n" +"'9'" + +#: ../../library/configparser.rst:241 msgid "" "One more thing to be aware of is that the parser-level :meth:`~ConfigParser." "get` method provides a custom, more complex interface, maintained for " @@ -258,7 +463,17 @@ msgstr "" "valor substituto pode ser fornecido através do argumento somente-nomeado " "``fallback``:" -#: ../../library/configparser.rst:251 +#: ../../library/configparser.rst:246 +msgid "" +">>> config.get('forge.example', 'monster',\n" +"... fallback='No such things as monsters')\n" +"'No such things as monsters'" +msgstr "" +">>> config.get('forge.example', 'monster',\n" +"... fallback='No such things as monsters')\n" +"'No such things as monsters'" + +#: ../../library/configparser.rst:252 msgid "" "The same ``fallback`` argument can be used with the :meth:`~ConfigParser." "getint`, :meth:`~ConfigParser.getfloat` and :meth:`~ConfigParser.getboolean` " @@ -268,11 +483,29 @@ msgstr "" "`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat` e :meth:" "`~ConfigParser.getboolean`, por exemplo:" -#: ../../library/configparser.rst:267 +#: ../../library/configparser.rst:256 +msgid "" +">>> 'BatchMode' in topsecret\n" +"False\n" +">>> topsecret.getboolean('BatchMode', fallback=True)\n" +"True\n" +">>> config['DEFAULT']['BatchMode'] = 'no'\n" +">>> topsecret.getboolean('BatchMode', fallback=True)\n" +"False" +msgstr "" +">>> 'BatchMode' in topsecret\n" +"False\n" +">>> topsecret.getboolean('BatchMode', fallback=True)\n" +"True\n" +">>> config['DEFAULT']['BatchMode'] = 'no'\n" +">>> topsecret.getboolean('BatchMode', fallback=True)\n" +"False" + +#: ../../library/configparser.rst:268 msgid "Supported INI File Structure" msgstr "Estrutura dos arquivos INI" -#: ../../library/configparser.rst:269 +#: ../../library/configparser.rst:270 msgid "" "A configuration file consists of sections, each led by a ``[section]`` " "header, followed by key/value entries separated by a specific string (``=`` " @@ -296,7 +529,7 @@ msgstr "" "Dependendo do modo do analisador sintático, as linhas em branco podem ser " "tratadas como partes de valores multilinhas ou ignoradas." -#: ../../library/configparser.rst:279 +#: ../../library/configparser.rst:280 msgid "" "By default, a valid section name can be any string that does not contain '\\" "\\n'. To change this, see :attr:`ConfigParser.SECTCRE`." @@ -304,7 +537,7 @@ msgstr "" "Por padrão, um nome de seção válido pode ser qualquer string que não " "contenha '\\\\n'. Para alterar isso, consulte :attr:`ConfigParser.SECTCRE`." -#: ../../library/configparser.rst:282 +#: ../../library/configparser.rst:283 msgid "" "The first section name may be omitted if the parser is configured to allow " "an unnamed top level section with ``allow_unnamed_section=True``. In this " @@ -316,7 +549,7 @@ msgstr "" "``allow_unnamed_section=True``. Neste caso, as chaves/valores podem ser " "recuperadas por :const:`UNNAMED_SECTION` como em ``config[UNNAMED_SECTION]``." -#: ../../library/configparser.rst:287 +#: ../../library/configparser.rst:288 msgid "" "Configuration files may include comments, prefixed by specific characters " "(``#`` and ``;`` by default [1]_). Comments may appear on their own on an " @@ -326,15 +559,102 @@ msgstr "" "caracteres específicos (``#`` e ``;`` por padrão [1]_). Os comentários podem " "aparecer sozinhos em uma linha vazia, possivelmente identados. [1]_" -#: ../../library/configparser.rst:291 ../../library/configparser.rst:375 +#: ../../library/configparser.rst:292 ../../library/configparser.rst:376 msgid "For example:" msgstr "Por exemplo:" -#: ../../library/configparser.rst:341 +#: ../../library/configparser.rst:294 +msgid "" +"[Simple Values]\n" +"key=value\n" +"spaces in keys=allowed\n" +"spaces in values=allowed as well\n" +"spaces around the delimiter = obviously\n" +"you can also use : to delimit keys from values\n" +"\n" +"[All Values Are Strings]\n" +"values like this: 1000000\n" +"or this: 3.14159265359\n" +"are they treated as numbers? : no\n" +"integers, floats and booleans are held as: strings\n" +"can use the API to get converted values directly: true\n" +"\n" +"[Multiline Values]\n" +"chorus: I'm a lumberjack, and I'm okay\n" +" I sleep all night and I work all day\n" +"\n" +"[No Values]\n" +"key_without_value\n" +"empty string value here =\n" +"\n" +"[You can use comments]\n" +"# like this\n" +"; or this\n" +"\n" +"# By default only in an empty line.\n" +"# Inline comments can be harmful because they prevent users\n" +"# from using the delimiting characters as parts of values.\n" +"# That being said, this can be customized.\n" +"\n" +" [Sections Can Be Indented]\n" +" can_values_be_as_well = True\n" +" does_that_mean_anything_special = False\n" +" purpose = formatting for readability\n" +" multiline_values = are\n" +" handled just fine as\n" +" long as they are indented\n" +" deeper than the first line\n" +" of a value\n" +" # Did I mention we can indent comments, too?" +msgstr "" +"[Valores Simples]\n" +"chave=valor\n" +"espaços nas chaves=permitidos\n" +"espaços nos valores=permitidos também\n" +"espaços em volta do delimitador = obviamente\n" +"você também pode usar : para delimitar chaves de valores\n" +"\n" +"[Todos Valores São Strings]\n" +"valores como este: 1000000\n" +"ou este: 3.14159265359\n" +"são tratados como números? : não\n" +"inteiros, pontos flutuantes e booleanos são considerados: strings\n" +"pode usar a API para obter valores convertidos diretamente: verdadeiro\n" +"\n" +"[Valores multilinha]\n" +"chorus: Eu sou um lenhador e estou bem\n" +" Durmo a noite toda e trabalho o dia inteiro\n" +"\n" +"[Sem valores]\n" +"chave_sem_valor\n" +"valor string vazia aqui =\n" +"\n" +"[Você pode usar comentários]\n" +"# como este\n" +"; ou este\n" +"\n" +"# Por padrão, apenas em uma linha vazia.\n" +"# Comentários em linha podem ser prejudiciais porque eles\n" +"# impedem os usuários de usar os caracteres delimitadores\n" +"# como partes dos valores.\n" +"# Isto posto, isso pode ser personalizado.\n" +"\n" +" [Seções Podem Ser Indentadas]\n" +" podem_ser_valores_também = True\n" +" isso_significa_algo_especial = False\n" +" propósito = formatação para legibilidade\n" +" valores_multilinha = são\n" +" tratados sem problemas desde\n" +" que eles estejam indentados\n" +" mais profundamente do que a\n" +" primeira linha de um valor\n" +" # Mencionamos que também podemos indentar comentários?" + +#: ../../library/configparser.rst:342 msgid "Unnamed Sections" msgstr "Seções não nomeadas" -#: ../../library/configparser.rst:343 +#: ../../library/configparser.rst:344 msgid "" "The name of the first section (or unique) may be omitted and values " "retrieved by the :const:`UNNAMED_SECTION` attribute." @@ -342,21 +662,45 @@ msgstr "" "O nome da primeira seção (ou único) pode ser omitido e os valores " "recuperados pelo atributo :const:`UNNAMED_SECTION`." -#: ../../library/configparser.rst:360 +#: ../../library/configparser.rst:347 +msgid "" +">>> config = \"\"\"\n" +"... option = value\n" +"...\n" +"... [ Section 2 ]\n" +"... another = val\n" +"... \"\"\"\n" +">>> unnamed = configparser.ConfigParser(allow_unnamed_section=True)\n" +">>> unnamed.read_string(config)\n" +">>> unnamed.get(configparser.UNNAMED_SECTION, 'option')\n" +"'value'" +msgstr "" +">>> config = \"\"\"\n" +"... option = value\n" +"...\n" +"... [ Section 2 ]\n" +"... another = val\n" +"... \"\"\"\n" +">>> unnamed = configparser.ConfigParser(allow_unnamed_section=True)\n" +">>> unnamed.read_string(config)\n" +">>> unnamed.get(configparser.UNNAMED_SECTION, 'option')\n" +"'value'" + +#: ../../library/configparser.rst:361 msgid "Interpolation of values" msgstr "Interpolação de valores" -#: ../../library/configparser.rst:362 +#: ../../library/configparser.rst:363 msgid "" "On top of the core functionality, :class:`ConfigParser` supports " "interpolation. This means values can be preprocessed before returning them " "from ``get()`` calls." msgstr "" "Além da funcionalidade principal, :class:`ConfigParser` oferece suporte a " -"interpolação. Isso significa que os valores podem ser pré-processados ​​antes " +"interpolação. Isso significa que os valores podem ser pré-processados antes " "de retorná-los das chamadas ``get()``." -#: ../../library/configparser.rst:370 +#: ../../library/configparser.rst:371 msgid "" "The default implementation used by :class:`ConfigParser`. It enables values " "to contain format strings which refer to other values in the same section, " @@ -368,7 +712,29 @@ msgstr "" "mesma seção ou valores na seção padrão especial [1]_. Valores padrão " "adicionais podem ser fornecidos na inicialização." -#: ../../library/configparser.rst:388 +#: ../../library/configparser.rst:378 +msgid "" +"[Paths]\n" +"home_dir: /Users\n" +"my_dir: %(home_dir)s/lumberjack\n" +"my_pictures: %(my_dir)s/Pictures\n" +"\n" +"[Escape]\n" +"# use a %% to escape the % sign (% is the only character that needs to be " +"escaped):\n" +"gain: 80%%" +msgstr "" +"[Paths]\n" +"home_dir: /Users\n" +"my_dir: %(home_dir)s/lumberjack\n" +"my_pictures: %(my_dir)s/Pictures\n" +"\n" +"[Escape]\n" +"# use um %% para escapar o sinal de % (% é o único caractere que precisa ser " +"escapado):\n" +"gain: 80%%" + +#: ../../library/configparser.rst:389 msgid "" "In the example above, :class:`ConfigParser` with *interpolation* set to " "``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of " @@ -384,7 +750,7 @@ msgstr "" "portanto as chaves usadas na cadeia de referências não precisam ser " "especificadas em nenhuma ordem específica no arquivo de configuração." -#: ../../library/configparser.rst:395 +#: ../../library/configparser.rst:396 msgid "" "With ``interpolation`` set to ``None``, the parser would simply return " "``%(my_dir)s/Pictures`` as the value of ``my_pictures`` and ``%(home_dir)s/" @@ -394,7 +760,7 @@ msgstr "" "simplesmente retornaria ``%(my_dir)s/Pictures`` como o valor de " "``my_pictures`` e ``%(home_dir)s/lumberjack`` como o valor de ``my_dir``." -#: ../../library/configparser.rst:403 +#: ../../library/configparser.rst:404 msgid "" "An alternative handler for interpolation which implements a more advanced " "syntax, used for instance in ``zc.buildout``. Extended interpolation is " @@ -410,7 +776,7 @@ msgstr "" "``section:`` for omitida, a interpolação será padronizada para a seção atual " "(e possivelmente para os valores padrão da seção especial)." -#: ../../library/configparser.rst:410 +#: ../../library/configparser.rst:411 msgid "" "For example, the configuration specified above with basic interpolation, " "would look like this with extended interpolation:" @@ -418,15 +784,73 @@ msgstr "" "Por exemplo, a configuração especificada acima com interpolação básica " "ficaria assim com interpolação estendida:" -#: ../../library/configparser.rst:424 +#: ../../library/configparser.rst:414 +msgid "" +"[Paths]\n" +"home_dir: /Users\n" +"my_dir: ${home_dir}/lumberjack\n" +"my_pictures: ${my_dir}/Pictures\n" +"\n" +"[Escape]\n" +"# use a $$ to escape the $ sign ($ is the only character that needs to be " +"escaped):\n" +"cost: $$80" +msgstr "" +"[Paths]\n" +"home_dir: /Users\n" +"my_dir: ${home_dir}/lumberjack\n" +"my_pictures: ${my_dir}/Pictures\n" +"\n" +"[Escape]\n" +"# use a $$ para escapar o sinal de $ ($ é o único caractere que precisa ser " +"escapado):\n" +"cost: $$80" + +#: ../../library/configparser.rst:425 msgid "Values from other sections can be fetched as well:" msgstr "Valores de outras seções também podem ser obtidos:" -#: ../../library/configparser.rst:446 +#: ../../library/configparser.rst:427 +msgid "" +"[Common]\n" +"home_dir: /Users\n" +"library_dir: /Library\n" +"system_dir: /System\n" +"macports_dir: /opt/local\n" +"\n" +"[Frameworks]\n" +"Python: 3.2\n" +"path: ${Common:system_dir}/Library/Frameworks/\n" +"\n" +"[Arthur]\n" +"nickname: Two Sheds\n" +"last_name: Jackson\n" +"my_dir: ${Common:home_dir}/twosheds\n" +"my_pictures: ${my_dir}/Pictures\n" +"python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}" +msgstr "" +"[Common]\n" +"home_dir: /Users\n" +"library_dir: /Library\n" +"system_dir: /System\n" +"macports_dir: /opt/local\n" +"\n" +"[Frameworks]\n" +"Python: 3.2\n" +"path: ${Common:system_dir}/Library/Frameworks/\n" +"\n" +"[Arthur]\n" +"nickname: Two Sheds\n" +"last_name: Jackson\n" +"my_dir: ${Common:home_dir}/twosheds\n" +"my_pictures: ${my_dir}/Pictures\n" +"python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}" + +#: ../../library/configparser.rst:447 msgid "Mapping Protocol Access" msgstr "Acesso através do protocolo de mapeamento" -#: ../../library/configparser.rst:450 +#: ../../library/configparser.rst:451 msgid "" "Mapping protocol access is a generic name for functionality that enables " "using custom objects as if they were dictionaries. In case of :mod:" @@ -438,7 +862,7 @@ msgstr "" "dicionários. No caso de :mod:`configparser`, a implementação da interface de " "mapeamento está usando a notação ``parser['section']['option']``." -#: ../../library/configparser.rst:455 +#: ../../library/configparser.rst:456 msgid "" "``parser['section']`` in particular returns a proxy for the section's data " "in the parser. This means that the values are not copied but they are taken " @@ -453,7 +877,7 @@ msgstr "" "intermediário de seção, eles são, na verdade, modificados no analisador " "sintático original." -#: ../../library/configparser.rst:461 +#: ../../library/configparser.rst:462 msgid "" ":mod:`configparser` objects behave as close to actual dictionaries as " "possible. The mapping interface is complete and adheres to the :class:" @@ -465,7 +889,7 @@ msgstr "" "`~collections.abc.MutableMapping`. No entanto, existem algumas diferenças " "que devem ser levadas em consideração:" -#: ../../library/configparser.rst:466 +#: ../../library/configparser.rst:467 msgid "" "By default, all keys in sections are accessible in a case-insensitive manner " "[1]_. E.g. ``for option in parser[\"section\"]`` yields only " @@ -480,7 +904,15 @@ msgstr "" "padrão. Ao mesmo tempo, para uma seção que contém a chave ``'a'``, ambas as " "expressões retornam ``True``::" -#: ../../library/configparser.rst:474 +#: ../../library/configparser.rst:472 +msgid "" +"\"a\" in parser[\"section\"]\n" +"\"A\" in parser[\"section\"]" +msgstr "" +"\"a\" in parser[\"section\"]\n" +"\"A\" in parser[\"section\"]" + +#: ../../library/configparser.rst:475 msgid "" "All sections include ``DEFAULTSECT`` values as well which means that ``." "clear()`` on a section may not leave the section visibly empty. This is " @@ -496,23 +928,23 @@ msgstr "" "exclusão fará com que o valor padrão fique visível novamente. Tentar excluir " "um valor padrão causa um :exc:`KeyError`." -#: ../../library/configparser.rst:481 +#: ../../library/configparser.rst:482 msgid "``DEFAULTSECT`` cannot be removed from the parser:" msgstr "``DEFAULTSECT`` não pode ser removido do analisador sintático:" -#: ../../library/configparser.rst:483 +#: ../../library/configparser.rst:484 msgid "trying to delete it raises :exc:`ValueError`," msgstr "tentar excluí-lo levanta :exc:`ValueError`," -#: ../../library/configparser.rst:485 +#: ../../library/configparser.rst:486 msgid "``parser.clear()`` leaves it intact," msgstr "``parser.clear()`` deixa-o intacto," -#: ../../library/configparser.rst:487 +#: ../../library/configparser.rst:488 msgid "``parser.popitem()`` never returns it." msgstr "``parser.popitem()`` nunca o retorna." -#: ../../library/configparser.rst:489 +#: ../../library/configparser.rst:490 msgid "" "``parser.get(section, option, **kwargs)`` - the second argument is **not** a " "fallback value. Note however that the section-level ``get()`` methods are " @@ -523,7 +955,7 @@ msgstr "" "seção são compatíveis tanto com o protocolo de mapeamento quanto com a API " "clássica do configparser." -#: ../../library/configparser.rst:493 +#: ../../library/configparser.rst:494 msgid "" "``parser.items()`` is compatible with the mapping protocol (returns a list " "of *section_name*, *section_proxy* pairs including the DEFAULTSECT). " @@ -539,7 +971,7 @@ msgstr "" "*option*, *value* para uma ``section`` especificada, com todas as " "interpolações expandidas (a menos que ``raw=True`` seja fornecido)." -#: ../../library/configparser.rst:500 +#: ../../library/configparser.rst:501 msgid "" "The mapping protocol is implemented on top of the existing legacy API so " "that subclasses overriding the original interface still should have mappings " @@ -549,11 +981,11 @@ msgstr "" "que as subclasses que substituem a interface original ainda tenham " "mapeamentos funcionando conforme o esperado." -#: ../../library/configparser.rst:506 +#: ../../library/configparser.rst:507 msgid "Customizing Parser Behaviour" msgstr "Personalizando o comportamento do analisador sintático" -#: ../../library/configparser.rst:508 +#: ../../library/configparser.rst:509 msgid "" "There are nearly as many INI format variants as there are applications using " "it. :mod:`configparser` goes a long way to provide support for the largest " @@ -567,7 +999,7 @@ msgstr "" "funcionalidade padrão é determinada principalmente pelo histórico e é muito " "provável que você queira personalizar alguns dos recursos." -#: ../../library/configparser.rst:514 +#: ../../library/configparser.rst:515 msgid "" "The most common way to change the way a specific config parser works is to " "use the :meth:`!__init__` options:" @@ -575,11 +1007,11 @@ msgstr "" "A maneira mais comum de alterar a forma como um analisador sintático de " "configuração específico funciona é usar as opções :meth:`!__init__`:" -#: ../../library/configparser.rst:517 +#: ../../library/configparser.rst:518 msgid "*defaults*, default value: ``None``" msgstr "*defaults*, valor padrão: ``None``" -#: ../../library/configparser.rst:519 +#: ../../library/configparser.rst:520 msgid "" "This option accepts a dictionary of key-value pairs which will be initially " "put in the ``DEFAULT`` section. This makes for an elegant way to support " @@ -591,7 +1023,7 @@ msgstr "" "suporte a arquivos de configuração concisos que não especificam valores " "iguais ao padrão documentado." -#: ../../library/configparser.rst:524 +#: ../../library/configparser.rst:525 msgid "" "Hint: if you want to specify default values for a specific section, use :" "meth:`~ConfigParser.read_dict` before you read the actual file." @@ -599,11 +1031,11 @@ msgstr "" "Dica: se você deseja especificar valores padrão para uma seção específica, " "use :meth:`~ConfigParser.read_dict` antes de ler o arquivo real." -#: ../../library/configparser.rst:527 +#: ../../library/configparser.rst:528 msgid "*dict_type*, default value: :class:`dict`" msgstr "*dict_type*, valor padrão: :class:`dict`" -#: ../../library/configparser.rst:529 +#: ../../library/configparser.rst:530 msgid "" "This option has a major impact on how the mapping protocol will behave and " "how the written configuration files look. With the standard dictionary, " @@ -615,7 +1047,7 @@ msgstr "" "padrão, cada seção é armazenada na ordem em que foram adicionadas ao " "analisador sintático. O mesmo vale para opções dentro das seções." -#: ../../library/configparser.rst:534 +#: ../../library/configparser.rst:535 msgid "" "An alternative dictionary type can be used for example to sort sections and " "options on write-back." @@ -623,7 +1055,7 @@ msgstr "" "Um tipo de dicionário alternativo pode ser usado, por exemplo, para ordenar " "as seções e opções ao fazer *write-back*." -#: ../../library/configparser.rst:537 +#: ../../library/configparser.rst:538 msgid "" "Please note: there are ways to add a set of key-value pairs in a single " "operation. When you use a regular dictionary in those operations, the order " @@ -633,11 +1065,45 @@ msgstr "" "chave em uma única operação. Quando você usa um dicionário regular nessas " "operações, a classificação das chaves será ordenada. Por exemplo:" -#: ../../library/configparser.rst:559 +#: ../../library/configparser.rst:542 +msgid "" +">>> parser = configparser.ConfigParser()\n" +">>> parser.read_dict({'section1': {'key1': 'value1',\n" +"... 'key2': 'value2',\n" +"... 'key3': 'value3'},\n" +"... 'section2': {'keyA': 'valueA',\n" +"... 'keyB': 'valueB',\n" +"... 'keyC': 'valueC'},\n" +"... 'section3': {'foo': 'x',\n" +"... 'bar': 'y',\n" +"... 'baz': 'z'}\n" +"... })\n" +">>> parser.sections()\n" +"['section1', 'section2', 'section3']\n" +">>> [option for option in parser['section3']]\n" +"['foo', 'bar', 'baz']" +msgstr "" +">>> parser = configparser.ConfigParser()\n" +">>> parser.read_dict({'seção1': {'chave1': 'valor1',\n" +"... 'chave2': 'valor2',\n" +"... 'chave3': 'valor3'},\n" +"... 'seção2': {'chaveA': 'valorA',\n" +"... 'chaveB': 'valorB',\n" +"... 'chaveC': 'valorC'},\n" +"... 'seção3': {'foo': 'x',\n" +"... 'bar': 'y',\n" +"... 'baz': 'z'}\n" +"... })\n" +">>> parser.sections()\n" +"['seção1', 'seção2', 'seção3']\n" +">>> [option for option in parser['seção3']]\n" +"['foo', 'bar', 'baz']" + +#: ../../library/configparser.rst:560 msgid "*allow_no_value*, default value: ``False``" msgstr "*allow_no_value*, valor padrão: ``False``" -#: ../../library/configparser.rst:561 +#: ../../library/configparser.rst:562 msgid "" "Some configuration files are known to include settings without values, but " "which otherwise conform to the syntax supported by :mod:`configparser`. The " @@ -649,11 +1115,69 @@ msgstr "" "suportada por :mod:`configparser`. O parâmetro *allow_no_value* para o " "construtor pode ser usado para indicar que tais valores devem ser aceitos:" -#: ../../library/configparser.rst:596 +#: ../../library/configparser.rst:567 +msgid "" +">>> import configparser\n" +"\n" +">>> sample_config = \"\"\"\n" +"... [mysqld]\n" +"... user = mysql\n" +"... pid-file = /var/run/mysqld/mysqld.pid\n" +"... skip-external-locking\n" +"... old_passwords = 1\n" +"... skip-bdb\n" +"... # we don't need ACID today\n" +"... skip-innodb\n" +"... \"\"\"\n" +">>> config = configparser.ConfigParser(allow_no_value=True)\n" +">>> config.read_string(sample_config)\n" +"\n" +">>> # Settings with values are treated as before:\n" +">>> config[\"mysqld\"][\"user\"]\n" +"'mysql'\n" +"\n" +">>> # Settings without values provide None:\n" +">>> config[\"mysqld\"][\"skip-bdb\"]\n" +"\n" +">>> # Settings which aren't specified still raise an error:\n" +">>> config[\"mysqld\"][\"does-not-exist\"]\n" +"Traceback (most recent call last):\n" +" ...\n" +"KeyError: 'does-not-exist'" +msgstr "" +">>> import configparser\n" +"\n" +">>> sample_config = \"\"\"\n" +"... [mysqld]\n" +"... user = mysql\n" +"... pid-file = /var/run/mysqld/mysqld.pid\n" +"... skip-external-locking\n" +"... old_passwords = 1\n" +"... skip-bdb\n" +"... # não precisamos de ACID hoje\n" +"... skip-innodb\n" +"... \"\"\"\n" +">>> config = configparser.ConfigParser(allow_no_value=True)\n" +">>> config.read_string(sample_config)\n" +"\n" +">>> # Configurações com valores são tratados como antes:\n" +">>> config[\"mysqld\"][\"user\"]\n" +"'mysql'\n" +"\n" +">>> # Configurações sem valores fornecem None:\n" +">>> config[\"mysqld\"][\"skip-bdb\"]\n" +"\n" +">>> # Configurações que não são especificadas ainda levantam um erro:\n" +">>> config[\"mysqld\"][\"não-existe\"]\n" +"Traceback (most recent call last):\n" +" ...\n" +"KeyError: 'não-existe'" + +#: ../../library/configparser.rst:597 msgid "*delimiters*, default value: ``('=', ':')``" msgstr "*delimiters*, valor padrão: ``('=', ':')``" -#: ../../library/configparser.rst:598 +#: ../../library/configparser.rst:599 msgid "" "Delimiters are substrings that delimit keys from values within a section. " "The first occurrence of a delimiting substring on a line is considered a " @@ -664,7 +1188,7 @@ msgstr "" "considerada um delimitador. Isso significa que os valores (mas não as " "chaves) podem conter os delimitadores." -#: ../../library/configparser.rst:602 +#: ../../library/configparser.rst:603 msgid "" "See also the *space_around_delimiters* argument to :meth:`ConfigParser." "write`." @@ -672,15 +1196,15 @@ msgstr "" "Veja também o argumento *space_around_delimiters* para :meth:`ConfigParser." "write`." -#: ../../library/configparser.rst:605 +#: ../../library/configparser.rst:606 msgid "*comment_prefixes*, default value: ``('#', ';')``" msgstr "*comment_prefixes*, valor padrão: ``('#', ';')``" -#: ../../library/configparser.rst:607 +#: ../../library/configparser.rst:608 msgid "*inline_comment_prefixes*, default value: ``None``" msgstr "*inline_comment_prefixes*, valor padrão: ``None``" -#: ../../library/configparser.rst:609 +#: ../../library/configparser.rst:610 msgid "" "Comment prefixes are strings that indicate the start of a valid comment " "within a config file. *comment_prefixes* are used only on otherwise empty " @@ -690,14 +1214,14 @@ msgid "" "used as prefixes for whole line comments." msgstr "" "Prefixos de comentários são strings que indicam o início de um comentário " -"válido em um arquivo de configuração. *comment_prefixes* são usados ​​apenas " +"válido em um arquivo de configuração. *comment_prefixes* são usados apenas " "em linhas vazias (opcionalmente indentadas), enquanto " "*inline_comment_prefixes* pode ser usado após cada valor válido (por " "exemplo, nomes de seções, opções e linhas vazias também). Por padrão, os " -"comentários embutidos estão desabilitados e ``'#'`` e ``';'`` são usados ​​" +"comentários embutidos estão desabilitados e ``'#'`` e ``';'`` são usados " "como prefixos para comentários de linha inteira." -#: ../../library/configparser.rst:616 +#: ../../library/configparser.rst:617 msgid "" "In previous versions of :mod:`configparser` behaviour matched " "``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``." @@ -705,7 +1229,7 @@ msgstr "" "Nas versões anteriores do :mod:`configparser`, o comportamento correspondia " "a ``comment_prefixes=('#',';')`` e ``inline_comment_prefixes=(';',)``." -#: ../../library/configparser.rst:620 +#: ../../library/configparser.rst:621 msgid "" "Please note that config parsers don't support escaping of comment prefixes " "so using *inline_comment_prefixes* may prevent users from specifying option " @@ -717,16 +1241,96 @@ msgstr "" "Observe que os analisadores sintáticos de configuração não oferecem suporte " "a escape de prefixos de comentários, portanto, usar " "*inline_comment_prefixes* pode impedir que os usuários especifiquem valores " -"de opção com caracteres usados ​​como prefixos de comentários. Em caso de " +"de opção com caracteres usados como prefixos de comentários. Em caso de " "dúvida, evite definir *inline_comment_prefixes*. Em qualquer circunstância, " "a única maneira de armazenar caracteres de prefixo de comentário no início " "de uma linha em valores multilinha é interpolar o prefixo, por exemplo::" -#: ../../library/configparser.rst:666 +#: ../../library/configparser.rst:628 +msgid "" +">>> from configparser import ConfigParser, ExtendedInterpolation\n" +">>> parser = ConfigParser(interpolation=ExtendedInterpolation())\n" +">>> # the default BasicInterpolation could be used as well\n" +">>> parser.read_string(\"\"\"\n" +"... [DEFAULT]\n" +"... hash = #\n" +"...\n" +"... [hashes]\n" +"... shebang =\n" +"... ${hash}!/usr/bin/env python\n" +"... ${hash} -*- coding: utf-8 -*-\n" +"...\n" +"... extensions =\n" +"... enabled_extension\n" +"... another_extension\n" +"... #disabled_by_comment\n" +"... yet_another_extension\n" +"...\n" +"... interpolation not necessary = if # is not at line start\n" +"... even in multiline values = line #1\n" +"... line #2\n" +"... line #3\n" +"... \"\"\")\n" +">>> print(parser['hashes']['shebang'])\n" +"\n" +"#!/usr/bin/env python\n" +"# -*- coding: utf-8 -*-\n" +">>> print(parser['hashes']['extensions'])\n" +"\n" +"enabled_extension\n" +"another_extension\n" +"yet_another_extension\n" +">>> print(parser['hashes']['interpolation not necessary'])\n" +"if # is not at line start\n" +">>> print(parser['hashes']['even in multiline values'])\n" +"line #1\n" +"line #2\n" +"line #3" +msgstr "" +">>> from configparser import ConfigParser, ExtendedInterpolation\n" +">>> parser = ConfigParser(interpolation=ExtendedInterpolation())\n" +">>> # a BasicInterpolation padrão poderia ser usada também\n" +">>> parser.read_string(\"\"\"\n" +"... [DEFAULT]\n" +"... hash = #\n" +"...\n" +"... [hashes]\n" +"... shebang =\n" +"... ${hash}!/usr/bin/env python\n" +"... ${hash} -*- coding: utf-8 -*-\n" +"...\n" +"... extensões =\n" +"... extensão_habilitada\n" +"... outra_extensão\n" +"... #desabilitada_por_comentário\n" +"... e_mais_uma_extensão\n" +"...\n" +"... interpolação não necessária = se # não estiver no início da linha\n" +"... mesmo em valores multilinha = linha #1\n" +"... linha #2\n" +"... linha #3\n" +"... \"\"\")\n" +">>> print(parser['hashes']['shebang'])\n" +"\n" +"#!/usr/bin/env python\n" +"# -*- coding: utf-8 -*-\n" +">>> print(parser['hashes']['extensões'])\n" +"\n" +"extensão_habilitada\n" +"outra_extensão\n" +"e_mais_uma_extensão\n" +">>> print(parser['hashes']['interpolação não necessária'])\n" +"se # não estiver no início da linha\n" +">>> print(parser['hashes']['mesmo em valores multilinha'])\n" +"linha #1\n" +"linha #2\n" +"linha #3" + +#: ../../library/configparser.rst:667 msgid "*strict*, default value: ``True``" msgstr "*strict*, valor padrão: ``True``" -#: ../../library/configparser.rst:668 +#: ../../library/configparser.rst:669 msgid "" "When set to ``True``, the parser will not allow for any section or option " "duplicates while reading from a single source (using :meth:`~ConfigParser." @@ -739,7 +1343,7 @@ msgstr "" "`~ConfigParser.read_dict`). Recomenda-se usar analisadores sintáticos " "estritos em novas aplicações." -#: ../../library/configparser.rst:673 +#: ../../library/configparser.rst:674 msgid "" "In previous versions of :mod:`configparser` behaviour matched " "``strict=False``." @@ -747,11 +1351,11 @@ msgstr "" "Nas versões anteriores do :mod:`configparser`, o comportamento correspondia " "a ``strict=False``." -#: ../../library/configparser.rst:677 +#: ../../library/configparser.rst:678 msgid "*empty_lines_in_values*, default value: ``True``" msgstr "*empty_lines_in_values*, valor padrão: ``True``" -#: ../../library/configparser.rst:679 +#: ../../library/configparser.rst:680 msgid "" "In config parsers, values can span multiple lines as long as they are " "indented more than the key that holds them. By default parsers also let " @@ -768,7 +1372,21 @@ msgstr "" "arquivos de configuração ficam grandes e complexos, é fácil para o usuário " "perder o controle da estrutura do arquivo. Tomemos por exemplo:" -#: ../../library/configparser.rst:694 +#: ../../library/configparser.rst:687 +msgid "" +"[Section]\n" +"key = multiline\n" +" value with a gotcha\n" +"\n" +" this = is still a part of the multiline value of 'key'" +msgstr "" +"[Seção]\n" +"chave = multilinha\n" +" valor com uma pegadinha\n" +"\n" +" esta = ainda é parte do valor multilinha de 'chave'" + +#: ../../library/configparser.rst:695 msgid "" "This can be especially problematic for the user to see if she's using a " "proportional font to edit the file. That is why when your application does " @@ -782,7 +1400,7 @@ msgstr "" "proibi-los. Isso fará com que as linhas vazias dividam as chaves sempre. No " "exemplo acima, seriam produzidas duas chaves, ``key`` e ``this``." -#: ../../library/configparser.rst:700 +#: ../../library/configparser.rst:701 msgid "" "*default_section*, default value: ``configparser.DEFAULTSECT`` (that is: " "``\"DEFAULT\"``)" @@ -790,7 +1408,7 @@ msgstr "" "*default_section*, valor padrão: ``configparser.DEFAULTSECT`` (isto é: " "``\"DEFAULT\"``)" -#: ../../library/configparser.rst:703 +#: ../../library/configparser.rst:704 msgid "" "The convention of allowing a special section of default values for other " "sections or interpolation purposes is a powerful concept of this library, " @@ -814,11 +1432,11 @@ msgstr "" "atributo ``parser_instance.default_section`` e pode ser modificado em tempo " "de execução (ou seja, para converter arquivos de um formato para outro)." -#: ../../library/configparser.rst:714 +#: ../../library/configparser.rst:715 msgid "*interpolation*, default value: ``configparser.BasicInterpolation``" msgstr "*interpolation*, valor padrão: ``configparser.BasicInterpolation``" -#: ../../library/configparser.rst:716 +#: ../../library/configparser.rst:717 msgid "" "Interpolation behaviour may be customized by providing a custom handler " "through the *interpolation* argument. ``None`` can be used to turn off " @@ -835,11 +1453,11 @@ msgstr "" "<#interpolation-of-values>`_. :class:`RawConfigParser` tem um valor padrão " "de ``None``." -#: ../../library/configparser.rst:723 +#: ../../library/configparser.rst:724 msgid "*converters*, default value: not set" msgstr "*converters*, valor padrão: não definido" -#: ../../library/configparser.rst:725 +#: ../../library/configparser.rst:726 msgid "" "Config parsers provide option value getters that perform type conversion. " "By default :meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat`, " @@ -864,7 +1482,7 @@ msgstr "" "getdecimal('section', 'key', fallback=0)`` e ``parser_instance['section']." "getdecimal('key', 0)``." -#: ../../library/configparser.rst:736 +#: ../../library/configparser.rst:737 msgid "" "If the converter needs to access the state of the parser, it can be " "implemented as a method on a config parser subclass. If the name of this " @@ -877,7 +1495,7 @@ msgstr "" "disponível em todos os intermediários de seção, na forma compatível com dict " "(veja o exemplo ``getdecimal()`` acima)." -#: ../../library/configparser.rst:741 +#: ../../library/configparser.rst:742 msgid "" "More advanced customization may be achieved by overriding default values of " "these parser attributes. The defaults are defined on the classes, so they " @@ -888,7 +1506,7 @@ msgstr "" "nas classes, portanto podem ser substituídos por subclasses ou por " "atribuição de atributos." -#: ../../library/configparser.rst:747 +#: ../../library/configparser.rst:748 msgid "" "By default when using :meth:`~ConfigParser.getboolean`, config parsers " "consider the following values ``True``: ``'1'``, ``'yes'``, ``'true'``, " @@ -903,7 +1521,29 @@ msgstr "" "especificando um dicionário personalizado de strings e seus resultados " "booleanos. Por exemplo:" -#: ../../library/configparser.rst:765 +#: ../../library/configparser.rst:754 +msgid "" +">>> custom = configparser.ConfigParser()\n" +">>> custom['section1'] = {'funky': 'nope'}\n" +">>> custom['section1'].getboolean('funky')\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: Not a boolean: nope\n" +">>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}\n" +">>> custom['section1'].getboolean('funky')\n" +"False" +msgstr "" +">>> custom = configparser.ConfigParser()\n" +">>> custom['seção1'] = {'funky': 'nope'}\n" +">>> custom['seção1'].getboolean('funky')\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: Not a boolean: nope\n" +">>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}\n" +">>> custom['seção1'].getboolean('funky')\n" +"False" + +#: ../../library/configparser.rst:766 msgid "" "Other typical Boolean pairs include ``accept``/``reject`` or ``enabled``/" "``disabled``." @@ -911,7 +1551,7 @@ msgstr "" "Outros pares booleanos típicos incluem ``accept``/``reject`` ou ``enabled``/" "``disabled``." -#: ../../library/configparser.rst:771 +#: ../../library/configparser.rst:772 msgid "" "This method transforms option names on every read, get, or set operation. " "The default converts the name to lowercase. This also means that when a " @@ -924,7 +1564,51 @@ msgstr "" "estarão em letras minúsculas. Substitua esse método se for inadequado. Por " "exemplo:" -#: ../../library/configparser.rst:801 +#: ../../library/configparser.rst:778 +msgid "" +">>> config = \"\"\"\n" +"... [Section1]\n" +"... Key = Value\n" +"...\n" +"... [Section2]\n" +"... AnotherKey = Value\n" +"... \"\"\"\n" +">>> typical = configparser.ConfigParser()\n" +">>> typical.read_string(config)\n" +">>> list(typical['Section1'].keys())\n" +"['key']\n" +">>> list(typical['Section2'].keys())\n" +"['anotherkey']\n" +">>> custom = configparser.RawConfigParser()\n" +">>> custom.optionxform = lambda option: option\n" +">>> custom.read_string(config)\n" +">>> list(custom['Section1'].keys())\n" +"['Key']\n" +">>> list(custom['Section2'].keys())\n" +"['AnotherKey']" +msgstr "" +">>> config = \"\"\"\n" +"... [Seção1]\n" +"... Chave = Valor\n" +"...\n" +"... [Seção2]\n" +"... OutraChave = Valor\n" +"... \"\"\"\n" +">>> typical = configparser.ConfigParser()\n" +">>> typical.read_string(config)\n" +">>> list(typical['Seção1'].keys())\n" +"['chave']\n" +">>> list(typical['Seção2'].keys())\n" +"['outrachave']\n" +">>> custom = configparser.RawConfigParser()\n" +">>> custom.optionxform = lambda option: option\n" +">>> custom.read_string(config)\n" +">>> list(custom['Seção1'].keys())\n" +"['Chave']\n" +">>> list(custom['Seção2'].keys())\n" +"['OutraChave']" + +#: ../../library/configparser.rst:802 msgid "" "The optionxform function transforms option names to a canonical form. This " "should be an idempotent function: if the name is already in canonical form, " @@ -934,7 +1618,7 @@ msgstr "" "deve ser uma função idempotente: se o nome já estiver na forma canônica, " "deverá ser retornado inalterado." -#: ../../library/configparser.rst:808 +#: ../../library/configparser.rst:809 msgid "" "A compiled regular expression used to parse section headers. The default " "matches ``[section]`` to the name ``\"section\"``. Whitespace is considered " @@ -948,7 +1632,45 @@ msgstr "" "lido como uma seção de nome ``\" larch \"``. Substitua esse atributo se " "for inadequado. Por exemplo:" -#: ../../library/configparser.rst:836 +#: ../../library/configparser.rst:815 +msgid "" +">>> import re\n" +">>> config = \"\"\"\n" +"... [Section 1]\n" +"... option = value\n" +"...\n" +"... [ Section 2 ]\n" +"... another = val\n" +"... \"\"\"\n" +">>> typical = configparser.ConfigParser()\n" +">>> typical.read_string(config)\n" +">>> typical.sections()\n" +"['Section 1', ' Section 2 ']\n" +">>> custom = configparser.ConfigParser()\n" +">>> custom.SECTCRE = re.compile(r\"\\[ *(?P
[^]]+?) *\\]\")\n" +">>> custom.read_string(config)\n" +">>> custom.sections()\n" +"['Section 1', 'Section 2']" +msgstr "" +">>> import re\n" +">>> config = \"\"\"\n" +"... [Seção 1]\n" +"... opção = valor\n" +"...\n" +"... [ Seção 2 ]\n" +"... outro = valor\n" +"... \"\"\"\n" +">>> typical = configparser.ConfigParser()\n" +">>> typical.read_string(config)\n" +">>> typical.sections()\n" +"['Seção 1', ' Seção 2 ']\n" +">>> custom = configparser.ConfigParser()\n" +">>> custom.SECTCRE = re.compile(r\"\\[ *(?P
[^]]+?) *\\]\")\n" +">>> custom.read_string(config)\n" +">>> custom.sections()\n" +"['Seção 1', 'Seção 2']" + +#: ../../library/configparser.rst:837 msgid "" "While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing " "option lines, it's not recommended to override it because that would " @@ -958,11 +1680,11 @@ msgstr "" "reconhecer linhas de opção, não é recomendado substituí-lo porque isso " "interferiria nas opções do construtor *allow_no_value* e *delimiters*." -#: ../../library/configparser.rst:842 +#: ../../library/configparser.rst:843 msgid "Legacy API Examples" msgstr "Exemplos de APIs legadas" -#: ../../library/configparser.rst:844 +#: ../../library/configparser.rst:845 msgid "" "Mainly because of backwards compatibility concerns, :mod:`configparser` " "provides also a legacy API with explicit ``get``/``set`` methods. While " @@ -977,32 +1699,200 @@ msgstr "" "A API legada é às vezes mais avançada, de baixo nível e totalmente " "contraintuitiva." -#: ../../library/configparser.rst:850 +#: ../../library/configparser.rst:851 msgid "An example of writing to a configuration file::" msgstr "Um exemplo de escrita em um arquivo de configuração::" -#: ../../library/configparser.rst:873 +#: ../../library/configparser.rst:853 +msgid "" +"import configparser\n" +"\n" +"config = configparser.RawConfigParser()\n" +"\n" +"# Please note that using RawConfigParser's set functions, you can assign\n" +"# non-string values to keys internally, but will receive an error when\n" +"# attempting to write to a file or when you get it in non-raw mode. Setting\n" +"# values using the mapping protocol or ConfigParser's set() does not allow\n" +"# such assignments to take place.\n" +"config.add_section('Section1')\n" +"config.set('Section1', 'an_int', '15')\n" +"config.set('Section1', 'a_bool', 'true')\n" +"config.set('Section1', 'a_float', '3.1415')\n" +"config.set('Section1', 'baz', 'fun')\n" +"config.set('Section1', 'bar', 'Python')\n" +"config.set('Section1', 'foo', '%(bar)s is %(baz)s!')\n" +"\n" +"# Writing our configuration file to 'example.cfg'\n" +"with open('example.cfg', 'w') as configfile:\n" +" config.write(configfile)" +msgstr "" +"import configparser\n" +"\n" +"config = configparser.RawConfigParser()\n" +"\n" +"# Observe que usando as funções set do RawConfigParser, você pode atribuir\n" +"# valores não string a chaves internamente, mas receberá um erro ao tentar\n" +"# gravar em um arquivo ou quando obtê-lo em modo não bruta. Definir valores\n" +"# usando o protocolo de mapeamento ou set() do ConfigParser não permite que\n" +"# tais atribuições ocorram.\n" +"config.add_section('Seção1')\n" +"config.set('Seção1', 'an_int', '15')\n" +"config.set('Seção1', 'a_bool', 'true')\n" +"config.set('Seção1', 'a_float', '3.1415')\n" +"config.set('Seção1', 'baz', 'divertido')\n" +"config.set('Seção1', 'bar', 'Python')\n" +"config.set('Seção1', 'foo', '%(bar)s é %(baz)s!')\n" +"\n" +"# Escrevendo nosso arquivo de configuração em 'example.cfg'\n" +"with open('example.cfg', 'w') as configfile:\n" +" config.write(configfile)" + +#: ../../library/configparser.rst:874 msgid "An example of reading the configuration file again::" msgstr "Um exemplo de leitura do arquivo de configuração novamente::" -#: ../../library/configparser.rst:891 +#: ../../library/configparser.rst:876 +msgid "" +"import configparser\n" +"\n" +"config = configparser.RawConfigParser()\n" +"config.read('example.cfg')\n" +"\n" +"# getfloat() raises an exception if the value is not a float\n" +"# getint() and getboolean() also do this for their respective types\n" +"a_float = config.getfloat('Section1', 'a_float')\n" +"an_int = config.getint('Section1', 'an_int')\n" +"print(a_float + an_int)\n" +"\n" +"# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.\n" +"# This is because we are using a RawConfigParser().\n" +"if config.getboolean('Section1', 'a_bool'):\n" +" print(config.get('Section1', 'foo'))" +msgstr "" +"import configparser\n" +"\n" +"config = configparser.RawConfigParser()\n" +"config.read('example.cfg')\n" +"\n" +"# getfloat() levanta uma exceção se o valor não for um ponto flutuante\n" +"# getint() e getboolean() também fazem isso para seus respectivos tipos\n" +"a_float = config.getfloat('Seção1', 'a_float')\n" +"an_int = config.getint('Seção1', 'an_int')\n" +"print(a_float + an_int)\n" +"\n" +"# Note que a próxima saída não interpola '%(bar)s' ou '%(baz)s'.\n" +"# Isso ocorre porque estamos usando RawConfigParser().\n" +"if config.getboolean('Seção1', 'a_bool'):\n" +" print(config.get('Seção1', 'foo'))" + +#: ../../library/configparser.rst:892 msgid "To get interpolation, use :class:`ConfigParser`::" msgstr "Para obter interpolação, use :class:`ConfigParser`::" -#: ../../library/configparser.rst:924 +#: ../../library/configparser.rst:894 +msgid "" +"import configparser\n" +"\n" +"cfg = configparser.ConfigParser()\n" +"cfg.read('example.cfg')\n" +"\n" +"# Set the optional *raw* argument of get() to True if you wish to disable\n" +"# interpolation in a single get operation.\n" +"print(cfg.get('Section1', 'foo', raw=False)) # -> \"Python is fun!\"\n" +"print(cfg.get('Section1', 'foo', raw=True)) # -> \"%(bar)s is %(baz)s!\"\n" +"\n" +"# The optional *vars* argument is a dict with members that will take\n" +"# precedence in interpolation.\n" +"print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',\n" +" 'baz': 'evil'}))\n" +"\n" +"# The optional *fallback* argument can be used to provide a fallback value\n" +"print(cfg.get('Section1', 'foo'))\n" +" # -> \"Python is fun!\"\n" +"\n" +"print(cfg.get('Section1', 'foo', fallback='Monty is not.'))\n" +" # -> \"Python is fun!\"\n" +"\n" +"print(cfg.get('Section1', 'monster', fallback='No such things as " +"monsters.'))\n" +" # -> \"No such things as monsters.\"\n" +"\n" +"# A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError\n" +"# but we can also use:\n" +"\n" +"print(cfg.get('Section1', 'monster', fallback=None))\n" +" # -> None" +msgstr "" +"import configparser\n" +"\n" +"cfg = configparser.ConfigParser()\n" +"cfg.read('example.cfg')\n" +"\n" +"# Defina o argumento *raw* opcional de get() para True se você quiser " +"desabilitar\n" +"# interpolação em uma única operação de get.\n" +"print(cfg.get('Seção1', 'foo', raw=False)) # -> \"Python é divertido!\"\n" +"print(cfg.get('Seção1', 'foo', raw=True)) # -> \"%(bar)s é %(baz)s!\"\n" +"\n" +"# O argumento opcional *vars* é um dicionário com membros que vão aceitar\n" +"# precedência na interpolação.\n" +"print(cfg.get('Seção1', 'foo', vars={'bar': 'Documentação',\n" +" 'baz': 'maligna'}))\n" +"\n" +"# The optional *fallback* argument can be used to provide a fallback value\n" +"print(cfg.get('Seção1', 'foo'))\n" +" # -> \"Python é divertido!\"\n" +"\n" +"print(cfg.get('Seção1', 'foo', fallback='Monty não é.'))\n" +" # -> \"Python é divertido!\"\n" +"\n" +"print(cfg.get('Seção1', 'monstro', fallback='Não existem monstros.'))\n" +" # -> \"Não existem monstros.\"\n" +"\n" +"# Um print(cfg.get('Seção1', 'monster')) levantaria NoOptionError,\n" +"# mas nós também podemos usar:\n" +"\n" +"print(cfg.get('Seção1', 'mosntro', fallback=None))\n" +" # -> None" + +#: ../../library/configparser.rst:925 msgid "" "Default values are available in both types of ConfigParsers. They are used " "in interpolation if an option used is not defined elsewhere. ::" msgstr "" "Os valores padrão estão disponíveis em ambos os tipos de ConfigParsers. Eles " -"são usados ​​em interpolação se uma opção usada não estiver definida em outro " +"são usados em interpolação se uma opção usada não estiver definida em outro " "lugar. ::" -#: ../../library/configparser.rst:942 +#: ../../library/configparser.rst:928 +msgid "" +"import configparser\n" +"\n" +"# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each\n" +"config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})\n" +"config.read('example.cfg')\n" +"\n" +"print(config.get('Section1', 'foo')) # -> \"Python is fun!\"\n" +"config.remove_option('Section1', 'bar')\n" +"config.remove_option('Section1', 'baz')\n" +"print(config.get('Section1', 'foo')) # -> \"Life is hard!\"" +msgstr "" +"import configparser\n" +"\n" +"# Nova instância com 'bar' e 'baz' padrão para 'A vida' e 'difícil' cada\n" +"config = configparser.ConfigParser({'bar': 'A vida', 'baz': 'difícil'})\n" +"config.read('example.cfg')\n" +"\n" +"print(config.get('Seção1', 'foo')) # -> \"Python é divertido!\"\n" +"config.remove_option('Seção1', 'bar')\n" +"config.remove_option('Seção1', 'baz')\n" +"print(config.get('Seção1', 'foo')) # -> \"A vida é difícil!\"" + +#: ../../library/configparser.rst:943 msgid "ConfigParser Objects" msgstr "Objetos ConfigParser" -#: ../../library/configparser.rst:946 +#: ../../library/configparser.rst:953 msgid "" "The main configuration parser. When *defaults* is given, it is initialized " "into the dictionary of intrinsic defaults. When *dict_type* is given, it " @@ -1015,7 +1905,7 @@ msgstr "" "para a lista de seções, para as opções dentro de uma seção e para os valores " "padrão." -#: ../../library/configparser.rst:951 +#: ../../library/configparser.rst:958 msgid "" "When *delimiters* is given, it is used as the set of substrings that divide " "keys from values. When *comment_prefixes* is given, it will be used as the " @@ -1023,14 +1913,14 @@ msgid "" "can be indented. When *inline_comment_prefixes* is given, it will be used " "as the set of substrings that prefix comments in non-empty lines." msgstr "" -"Quando *delimitadores* são fornecidos, eles são usados ​​como o conjunto de " +"Quando *delimiters* são fornecidos, eles são usados como o conjunto de " "substrings que dividem chaves de valores. Quando *comment_prefixes* for " "fornecido, ele será usado como o conjunto de substrings que prefixam " "comentários em linhas vazias. Os comentários podem ser indentados. Quando " "*inline_comment_prefixes* for fornecido, ele será usado como o conjunto de " "substrings que prefixam comentários em linhas não vazias." -#: ../../library/configparser.rst:957 +#: ../../library/configparser.rst:964 msgid "" "When *strict* is ``True`` (the default), the parser won't allow for any " "section or option duplicates while reading from a single source (file, " @@ -1053,7 +1943,7 @@ msgstr "" "mantido para estes é ``None`` e eles são serializados sem o delimitador " "final." -#: ../../library/configparser.rst:967 +#: ../../library/configparser.rst:974 msgid "" "When *default_section* is given, it specifies the name for the special " "section holding default values for other sections and interpolation purposes " @@ -1070,7 +1960,7 @@ msgstr "" "analisado, mas será usado ao escrever configurações analisadas em um novo " "arquivo de configuração." -#: ../../library/configparser.rst:974 +#: ../../library/configparser.rst:981 msgid "" "Interpolation behaviour may be customized by providing a custom handler " "through the *interpolation* argument. ``None`` can be used to turn off " @@ -1085,7 +1975,7 @@ msgstr "" "``zc.buildout``. Mais sobre o assunto na `seção de documentação dedicada " "<#interpolation-of-values>`_." -#: ../../library/configparser.rst:980 +#: ../../library/configparser.rst:987 msgid "" "All option names used in interpolation will be passed through the :meth:" "`optionxform` method just like any other option name reference. For " @@ -1093,31 +1983,41 @@ msgid "" "converts option names to lower case), the values ``foo %(bar)s`` and ``foo " "%(BAR)s`` are equivalent." msgstr "" -"Todos os nomes de opções usados ​​na interpolação serão passados ​​através do " +"Todos os nomes de opções usados na interpolação serão passados através do " "método :meth:`optionxform` assim como qualquer outra referência de nome de " "opção. Por exemplo, usando a implementação padrão de :meth:`optionxform` " "(que converte nomes de opções para letras minúsculas), os valores ``foo " "%(bar)s`` e ``foo %(BAR)s`` são equivalentes." -#: ../../library/configparser.rst:986 +#: ../../library/configparser.rst:993 msgid "" "When *converters* is given, it should be a dictionary where each key " "represents the name of a type converter and each value is a callable " "implementing the conversion from string to the desired datatype. Every " -"converter gets its own corresponding :meth:`!get*()` method on the parser " +"converter gets its own corresponding :meth:`!get*` method on the parser " "object and section proxies." msgstr "" -"Quando *conversers* é fornecido, deve ser um dicionário onde cada chave " +"Quando *converters* é fornecido, deve ser um dicionário onde cada chave " "representa o nome de um conversor de tipo e cada valor é um chamável " "implementando a conversão de string para o tipo de dados desejado. Cada " -"conversor obtém seu próprio método :meth:`!get*()` correspondente no objeto " +"conversor obtém seu próprio método :meth:`!get*` correspondente no objeto " "analisador sintático e nos intermediários de seção." -#: ../../library/configparser.rst:1017 +#: ../../library/configparser.rst:999 +msgid "" +"When *allow_unnamed_section* is ``True`` (default: ``False``), the first " +"section name can be omitted. See the `\"Unnamed Sections\" section <#unnamed-" +"sections>`_." +msgstr "" +"Quando *allow_unnamed_section* é ``True`` (padrão: ``False``), o primeiro " +"nome da seção pode ser omitido. Veja a seção `\"Seções não nomeadas\" " +"<#unnamed-sections>`_." + +#: ../../library/configparser.rst:1028 msgid "The default *dict_type* is :class:`collections.OrderedDict`." msgstr "O padrão *dict_type* é :class:`collections.OrderedDict`." -#: ../../library/configparser.rst:1020 +#: ../../library/configparser.rst:1031 ../../library/configparser.rst:1320 msgid "" "*allow_no_value*, *delimiters*, *comment_prefixes*, *strict*, " "*empty_lines_in_values*, *default_section* and *interpolation* were added." @@ -1126,21 +2026,21 @@ msgstr "" "*empty_lines_in_values*, *default_section* e *interpolation* foram " "adicionados." -#: ../../library/configparser.rst:1025 +#: ../../library/configparser.rst:1036 ../../library/configparser.rst:1325 msgid "The *converters* argument was added." msgstr "O argumento *converters* foi adicionado." -#: ../../library/configparser.rst:1028 +#: ../../library/configparser.rst:1039 msgid "" -"The *defaults* argument is read with :meth:`read_dict()`, providing " -"consistent behavior across the parser: non-string keys and values are " -"implicitly converted to strings." +"The *defaults* argument is read with :meth:`read_dict`, providing consistent " +"behavior across the parser: non-string keys and values are implicitly " +"converted to strings." msgstr "" -"O argumento *defaults* é lido com :meth:`read_dict()`, fornecendo um " +"O argumento *defaults* é lido com :meth:`read_dict`, fornecendo um " "comportamento consistente em todo o analisador: chaves e valores que não são " "de string são convertidos implicitamente em strings." -#: ../../library/configparser.rst:1033 ../../library/configparser.rst:1305 +#: ../../library/configparser.rst:1044 ../../library/configparser.rst:1328 msgid "" "The default *dict_type* is :class:`dict`, since it now preserves insertion " "order." @@ -1148,7 +2048,7 @@ msgstr "" "O *dict_type* padrão é :class:`dict`, pois agora preserva a ordem de " "inserção." -#: ../../library/configparser.rst:1037 +#: ../../library/configparser.rst:1048 msgid "" "Raise a :exc:`MultilineContinuationError` when *allow_no_value* is ``True``, " "and a key without a value is continued with an indented line." @@ -1156,11 +2056,15 @@ msgstr "" "Levanta :exc:`MultilineContinuationError` quando *allow_no_value* for " "``True``, e uma chave sem valor continua com uma linha indentada." -#: ../../library/configparser.rst:1043 +#: ../../library/configparser.rst:1052 ../../library/configparser.rst:1332 +msgid "The *allow_unnamed_section* argument was added." +msgstr "O argumento *allow_unnamed_section* foi adicionado." + +#: ../../library/configparser.rst:1057 msgid "Return a dictionary containing the instance-wide defaults." msgstr "Retorna um dicionário contendo os padrões de toda a instância." -#: ../../library/configparser.rst:1048 +#: ../../library/configparser.rst:1062 msgid "" "Return a list of the sections available; the *default section* is not " "included in the list." @@ -1168,7 +2072,7 @@ msgstr "" "Retorna uma lista das seções disponíveis; a *seção padrão* não está incluída " "na lista." -#: ../../library/configparser.rst:1054 +#: ../../library/configparser.rst:1068 msgid "" "Add a section named *section* to the instance. If a section by the given " "name already exists, :exc:`DuplicateSectionError` is raised. If the " @@ -1180,11 +2084,11 @@ msgstr "" "da *seção padrão* for passado, :exc:`ValueError` será levantada. O nome da " "seção deve ser uma string; caso contrário, :exc:`TypeError` será levantada." -#: ../../library/configparser.rst:1059 +#: ../../library/configparser.rst:1073 msgid "Non-string section names raise :exc:`TypeError`." msgstr "Nomes de seções sem string levantam :exc:`TypeError`." -#: ../../library/configparser.rst:1065 +#: ../../library/configparser.rst:1079 msgid "" "Indicates whether the named *section* is present in the configuration. The " "*default section* is not acknowledged." @@ -1192,11 +2096,11 @@ msgstr "" "Indica se a *section* nomeada está presente na configuração. A *seção " "padrão* não é reconhecida." -#: ../../library/configparser.rst:1071 +#: ../../library/configparser.rst:1085 msgid "Return a list of options available in the specified *section*." msgstr "Retorna uma lista de opções disponíveis na *section* especificada." -#: ../../library/configparser.rst:1076 +#: ../../library/configparser.rst:1090 msgid "" "If the given *section* exists, and contains the given *option*, return :" "const:`True`; otherwise return :const:`False`. If the specified *section* " @@ -1206,15 +2110,15 @@ msgstr "" "const:`True`; caso contrário, retorna :const:`False`. Se a *section* " "especificada for :const:`None` ou uma string vazia, DEFAULT será presumido." -#: ../../library/configparser.rst:1083 +#: ../../library/configparser.rst:1097 msgid "" "Attempt to read and parse an iterable of filenames, returning a list of " "filenames which were successfully parsed." msgstr "" "Tenta ler e analisar um iterável de nomes de arquivos, retornando uma lista " -"de nomes de arquivos que foram analisados ​​com sucesso." +"de nomes de arquivos que foram analisados com sucesso." -#: ../../library/configparser.rst:1086 +#: ../../library/configparser.rst:1100 msgid "" "If *filenames* is a string, a :class:`bytes` object or a :term:`path-like " "object`, it is treated as a single filename. If a file named in *filenames* " @@ -1233,7 +2137,7 @@ msgstr "" "sistema) e todos os arquivos de configuração existentes no iterável serão " "lidos." -#: ../../library/configparser.rst:1095 +#: ../../library/configparser.rst:1109 msgid "" "If none of the named files exist, the :class:`ConfigParser` instance will " "contain an empty dataset. An application which requires initial values to " @@ -1246,7 +2150,23 @@ msgstr "" "necessários usando :meth:`read_file` antes de chamar :meth:`read` para " "quaisquer arquivos opcionais::" -#: ../../library/configparser.rst:1108 +#: ../../library/configparser.rst:1115 +msgid "" +"import configparser, os\n" +"\n" +"config = configparser.ConfigParser()\n" +"config.read_file(open('defaults.cfg'))\n" +"config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],\n" +" encoding='cp1250')" +msgstr "" +"import configparser, os\n" +"\n" +"config = configparser.ConfigParser()\n" +"config.read_file(open('defaults.cfg'))\n" +"config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],\n" +" encoding='cp1250')" + +#: ../../library/configparser.rst:1122 msgid "" "Added the *encoding* parameter. Previously, all files were read using the " "default encoding for :func:`open`." @@ -1254,15 +2174,15 @@ msgstr "" "Adicionado o parâmetro *encoding*. Anteriormente, todos os arquivos eram " "lidos usando a codificação padrão para :func:`open`." -#: ../../library/configparser.rst:1112 +#: ../../library/configparser.rst:1126 msgid "The *filenames* parameter accepts a :term:`path-like object`." msgstr "O parâmetro *filenames* aceita um :term:`objeto caminho ou similar`." -#: ../../library/configparser.rst:1115 +#: ../../library/configparser.rst:1129 msgid "The *filenames* parameter accepts a :class:`bytes` object." msgstr "O parâmetro *filenames* aceita um objeto :class:`bytes`." -#: ../../library/configparser.rst:1121 +#: ../../library/configparser.rst:1135 msgid "" "Read and parse configuration data from *f* which must be an iterable " "yielding Unicode strings (for example files opened in text mode)." @@ -1270,7 +2190,7 @@ msgstr "" "Lê e analisa dados de configuração de *f* que devem ser iteráveis, " "produzindo strings Unicode (por exemplo, arquivos abertos em modo texto)." -#: ../../library/configparser.rst:1124 +#: ../../library/configparser.rst:1138 msgid "" "Optional argument *source* specifies the name of the file being read. If " "not given and *f* has a :attr:`!name` attribute, that is used for *source*; " @@ -1280,15 +2200,15 @@ msgstr "" "lido. Se não for fornecido e *f* tiver um atributo :attr:`!name`, que é " "usado para *source*; o padrão é ``''``." -#: ../../library/configparser.rst:1128 +#: ../../library/configparser.rst:1142 msgid "Replaces :meth:`!readfp`." msgstr "Substitui :meth:`!readfp`." -#: ../../library/configparser.rst:1133 +#: ../../library/configparser.rst:1147 msgid "Parse configuration data from a string." msgstr "Analisa dados de configuração de uma string." -#: ../../library/configparser.rst:1135 +#: ../../library/configparser.rst:1149 msgid "" "Optional argument *source* specifies a context-specific name of the string " "passed. If not given, ``''`` is used. This should commonly be a " @@ -1298,7 +2218,7 @@ msgstr "" "string passada. Se não for fornecido, ``''`` será usado. Geralmente " "deve ser um caminho do sistema de arquivos ou uma URL." -#: ../../library/configparser.rst:1144 +#: ../../library/configparser.rst:1158 msgid "" "Load configuration from any object that provides a dict-like ``items()`` " "method. Keys are section names, values are dictionaries with keys and " @@ -1312,7 +2232,7 @@ msgstr "" "usado preservar a ordem, as seções e suas chaves serão adicionadas em ordem. " "Os valores são convertidos automaticamente em strings." -#: ../../library/configparser.rst:1150 +#: ../../library/configparser.rst:1164 msgid "" "Optional argument *source* specifies a context-specific name of the " "dictionary passed. If not given, ```` is used." @@ -1320,13 +2240,13 @@ msgstr "" "O argumento opcional *source* especifica um nome específico do contexto do " "dicionário passado. Se não for fornecido, ```` será usado." -#: ../../library/configparser.rst:1153 +#: ../../library/configparser.rst:1167 msgid "This method can be used to copy state between parsers." msgstr "" "Este método pode ser usado para copiar o estado entre analisadores " "sintáticos." -#: ../../library/configparser.rst:1160 +#: ../../library/configparser.rst:1174 msgid "" "Get an *option* value for the named *section*. If *vars* is provided, it " "must be a dictionary. The *option* is looked up in *vars* (if provided), " @@ -1340,7 +2260,7 @@ msgstr "" "encontrada e *fallback* for fornecido, ele será usado como um valor " "alternativo. ``None`` pode ser fornecido como um valor *fallback*." -#: ../../library/configparser.rst:1166 +#: ../../library/configparser.rst:1180 msgid "" "All the ``'%'`` interpolations are expanded in the return values, unless the " "*raw* argument is true. Values for interpolation keys are looked up in the " @@ -1350,7 +2270,7 @@ msgstr "" "menos que o argumento *raw* seja verdadeiro. Os valores das chaves de " "interpolação são consultados da mesma maneira que a opção." -#: ../../library/configparser.rst:1170 +#: ../../library/configparser.rst:1184 msgid "" "Arguments *raw*, *vars* and *fallback* are keyword only to protect users " "from trying to use the third argument as the *fallback* fallback (especially " @@ -1360,7 +2280,7 @@ msgstr "" "proteger os usuários de tentarem usar o terceiro argumento como substituto " "*fallback* (especialmente ao usar o protocolo de mapeamento)." -#: ../../library/configparser.rst:1178 +#: ../../library/configparser.rst:1192 msgid "" "A convenience method which coerces the *option* in the specified *section* " "to an integer. See :meth:`get` for explanation of *raw*, *vars* and " @@ -1370,7 +2290,7 @@ msgstr "" "um número inteiro. Veja :meth:`get` para explicação de *raw*, *vars* e " "*fallback*." -#: ../../library/configparser.rst:1185 +#: ../../library/configparser.rst:1199 msgid "" "A convenience method which coerces the *option* in the specified *section* " "to a floating-point number. See :meth:`get` for explanation of *raw*, " @@ -1380,7 +2300,7 @@ msgstr "" "um número de ponto flutuante. Veja :meth:`get` para explicação de *raw*, " "*vars* e *fallback*." -#: ../../library/configparser.rst:1192 +#: ../../library/configparser.rst:1206 msgid "" "A convenience method which coerces the *option* in the specified *section* " "to a Boolean value. Note that the accepted values for the option are " @@ -1400,7 +2320,7 @@ msgstr "" "levante :exc:`ValueError`. Veja :meth:`get` para explicação de *raw*, *vars* " "e *fallback*." -#: ../../library/configparser.rst:1205 +#: ../../library/configparser.rst:1219 msgid "" "When *section* is not given, return a list of *section_name*, " "*section_proxy* pairs, including DEFAULTSECT." @@ -1408,7 +2328,7 @@ msgstr "" "Quando *section* não é fornecido, retorna uma lista de pares *section_name*, " "*section_proxy*, incluindo DEFAULTSECT." -#: ../../library/configparser.rst:1208 +#: ../../library/configparser.rst:1222 msgid "" "Otherwise, return a list of *name*, *value* pairs for the options in the " "given *section*. Optional arguments have the same meaning as for the :meth:" @@ -1418,17 +2338,17 @@ msgstr "" "*section* fornecida. Argumentos opcionais têm o mesmo significado do método :" "meth:`get`." -#: ../../library/configparser.rst:1212 +#: ../../library/configparser.rst:1226 msgid "" "Items present in *vars* no longer appear in the result. The previous " "behaviour mixed actual parser options with variables provided for " "interpolation." msgstr "" "Os itens presentes em *vars* não aparecem mais no resultado. O comportamento " -"anterior misturava opções reais do analisador sintático com variáveis ​​" +"anterior misturava opções reais do analisador sintático com variáveis " "fornecidas para interpolação." -#: ../../library/configparser.rst:1220 +#: ../../library/configparser.rst:1234 msgid "" "If the given section exists, set the given option to the specified value; " "otherwise raise :exc:`NoSectionError`. *option* and *value* must be " @@ -1438,7 +2358,7 @@ msgstr "" "especificado; caso contrário, levanta :exc:`NoSectionError`. *option* e " "*value* devem ser strings; caso contrário, :exc:`TypeError` será levantada." -#: ../../library/configparser.rst:1227 +#: ../../library/configparser.rst:1241 msgid "" "Write a representation of the configuration to the specified :term:`file " "object`, which must be opened in text mode (accepting strings). This " @@ -1452,7 +2372,7 @@ msgstr "" "*space_around_delimiters* for verdadeiro, os delimitadores entre chaves e " "valores serão envoltos por espaços." -#: ../../library/configparser.rst:1235 +#: ../../library/configparser.rst:1249 msgid "" "Comments in the original configuration file are not preserved when writing " "the configuration back. What is considered a comment, depends on the given " @@ -1462,7 +2382,7 @@ msgstr "" "escrever a configuração. O que é considerado um comentário depende dos " "valores fornecidos para *comment_prefix* e *inline_comment_prefix*." -#: ../../library/configparser.rst:1243 +#: ../../library/configparser.rst:1257 msgid "" "Remove the specified *option* from the specified *section*. If the section " "does not exist, raise :exc:`NoSectionError`. If the option existed to be " @@ -1472,7 +2392,7 @@ msgstr "" "existir, levanta :exc:`NoSectionError`. Se existisse a opção de ser " "removida, retorna :const:`True`; caso contrário, retorna :const:`False`." -#: ../../library/configparser.rst:1251 +#: ../../library/configparser.rst:1265 msgid "" "Remove the specified *section* from the configuration. If the section in " "fact existed, return ``True``. Otherwise return ``False``." @@ -1480,7 +2400,7 @@ msgstr "" "Remove a *section* especificada da configuração. Se a seção de fato existiu, " "retorna ``True``. Caso contrário, retorna ``False``." -#: ../../library/configparser.rst:1257 +#: ../../library/configparser.rst:1271 msgid "" "Transforms the option name *option* as found in an input file or as passed " "in by client code to the form that should be used in the internal " @@ -1495,7 +2415,7 @@ msgstr "" "cliente pode definir um atributo com esse nome nas instâncias para afetar " "esse comportamento." -#: ../../library/configparser.rst:1263 +#: ../../library/configparser.rst:1277 msgid "" "You don't need to subclass the parser to use this method, you can also set " "it on an instance, to a function that takes a string argument and returns a " @@ -1508,7 +2428,15 @@ msgstr "" "por exemplo, faria com que sejam diferenciadas as letras maiúsculas das " "minúsculas nos nomes das opções::" -#: ../../library/configparser.rst:1271 +#: ../../library/configparser.rst:1282 +msgid "" +"cfgparser = ConfigParser()\n" +"cfgparser.optionxform = str" +msgstr "" +"cfgparser = ConfigParser()\n" +"cfgparser.optionxform = str" + +#: ../../library/configparser.rst:1285 msgid "" "Note that when reading configuration files, whitespace around the option " "names is stripped before :meth:`optionxform` is called." @@ -1516,7 +2444,7 @@ msgstr "" "Observe que ao ler arquivos de configuração, os espaços em branco ao redor " "dos nomes das opções são removidos antes de :meth:`optionxform` ser chamado." -#: ../../library/configparser.rst:1277 +#: ../../library/configparser.rst:1291 msgid "" "A special object representing a section name used to reference the unnamed " "section (see :ref:`unnamed-sections`)." @@ -1524,7 +2452,7 @@ msgstr "" "Um objeto especial que representa um nome de seção usado para referenciar a " "seção sem nome (veja :ref:`unnamed-sections`)." -#: ../../library/configparser.rst:1282 +#: ../../library/configparser.rst:1296 msgid "" "The maximum depth for recursive interpolation for :meth:`~configparser." "ConfigParser.get` when the *raw* parameter is false. This is relevant only " @@ -1534,11 +2462,11 @@ msgstr "" "ConfigParser.get` quando o parâmetro *raw* é falso. Isso é relevante apenas " "quando a *interpolation* padrão é usada." -#: ../../library/configparser.rst:1290 +#: ../../library/configparser.rst:1304 msgid "RawConfigParser Objects" msgstr "Objetos RawConfigParser" -#: ../../library/configparser.rst:1300 +#: ../../library/configparser.rst:1315 msgid "" "Legacy variant of the :class:`ConfigParser`. It has interpolation disabled " "by default and allows for non-string section names, option names, and values " @@ -1550,7 +2478,7 @@ msgstr "" "opções e valores através de seus métodos inseguros ``add_section`` e " "``set``, bem como o tratamento de argumentos nomeados legados ``defaults=`` ." -#: ../../library/configparser.rst:1310 +#: ../../library/configparser.rst:1336 msgid "" "Consider using :class:`ConfigParser` instead which checks types of the " "values to be stored internally. If you don't want interpolation, you can " @@ -1560,7 +2488,7 @@ msgstr "" "serem armazenados internamente. Se você não quiser interpolação, você pode " "usar ``ConfigParser(interpolation=None)``." -#: ../../library/configparser.rst:1317 +#: ../../library/configparser.rst:1343 msgid "" "Add a section named *section* to the instance. If a section by the given " "name already exists, :exc:`DuplicateSectionError` is raised. If the " @@ -1570,7 +2498,7 @@ msgstr "" "com o nome fornecido, :exc:`DuplicateSectionError` será levantada. Se o nome " "da *seção padrão* for passado, :exc:`ValueError` será levantada." -#: ../../library/configparser.rst:1321 +#: ../../library/configparser.rst:1347 msgid "" "Type of *section* is not checked which lets users create non-string named " "sections. This behaviour is unsupported and may cause internal errors." @@ -1579,7 +2507,7 @@ msgstr "" "seções nomeadas sem string. Este comportamento não é compatível e pode " "causar erros internos." -#: ../../library/configparser.rst:1327 +#: ../../library/configparser.rst:1353 msgid "" "If the given section exists, set the given option to the specified value; " "otherwise raise :exc:`NoSectionError`. While it is possible to use :class:" @@ -1595,7 +2523,7 @@ msgstr "" "valores não-string, funcionalidade completa (incluindo interpolação e saída " "para arquivos) só pode ser alcançado usando valores de string." -#: ../../library/configparser.rst:1334 +#: ../../library/configparser.rst:1360 msgid "" "This method lets users assign non-string values to keys internally. This " "behaviour is unsupported and will cause errors when attempting to write to a " @@ -1607,19 +2535,19 @@ msgstr "" "escrever em um arquivo ou obtê-lo no modo não bruto. **Use a API do " "protocolo de mapeamento** que não permite que tais atribuições ocorram." -#: ../../library/configparser.rst:1341 +#: ../../library/configparser.rst:1367 msgid "Exceptions" msgstr "Exceções" -#: ../../library/configparser.rst:1345 +#: ../../library/configparser.rst:1371 msgid "Base class for all other :mod:`configparser` exceptions." msgstr "Classe base para todas as outras exceções do :mod:`configparser`." -#: ../../library/configparser.rst:1350 +#: ../../library/configparser.rst:1376 msgid "Exception raised when a specified section is not found." msgstr "Exceção levantada quando uma seção especificada não é encontrada." -#: ../../library/configparser.rst:1355 +#: ../../library/configparser.rst:1381 msgid "" "Exception raised if :meth:`~ConfigParser.add_section` is called with the " "name of a section that is already present or in strict parsers when a " @@ -1630,7 +2558,7 @@ msgstr "" "estritos quando uma seção for encontrada mais de uma vez em um único arquivo " "de entrada, string ou dicionário." -#: ../../library/configparser.rst:1359 +#: ../../library/configparser.rst:1385 msgid "" "Added the optional *source* and *lineno* attributes and parameters to :meth:" "`!__init__`." @@ -1638,7 +2566,7 @@ msgstr "" "Adicionados os atributos e parâmetros opcionais *source* e *lineno* a :meth:" "`!__init__`." -#: ../../library/configparser.rst:1366 +#: ../../library/configparser.rst:1392 msgid "" "Exception raised by strict parsers if a single option appears twice during " "reading from a single file, string or dictionary. This catches misspellings " @@ -1652,7 +2580,7 @@ msgstr "" "pode ter duas chaves representando a mesma chave de configuração que não " "diferencia maiúsculas de minúsculas." -#: ../../library/configparser.rst:1374 +#: ../../library/configparser.rst:1400 msgid "" "Exception raised when a specified option is not found in the specified " "section." @@ -1660,7 +2588,7 @@ msgstr "" "Exceção levantada quando uma opção especificada não é encontrada na seção " "especificada." -#: ../../library/configparser.rst:1380 +#: ../../library/configparser.rst:1406 msgid "" "Base class for exceptions raised when problems occur performing string " "interpolation." @@ -1668,7 +2596,7 @@ msgstr "" "Classe base para exceções levantadas quando ocorrem problemas ao executar a " "interpolação de strings." -#: ../../library/configparser.rst:1386 +#: ../../library/configparser.rst:1412 msgid "" "Exception raised when string interpolation cannot be completed because the " "number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of :" @@ -1678,7 +2606,7 @@ msgstr "" "porque o número de iterações excede :const:`MAX_INTERPOLATION_DEPTH`. " "Subclasse de :exc:`InterpolationError`." -#: ../../library/configparser.rst:1393 +#: ../../library/configparser.rst:1419 msgid "" "Exception raised when an option referenced from a value does not exist. " "Subclass of :exc:`InterpolationError`." @@ -1686,7 +2614,7 @@ msgstr "" "Exceção levantada quando uma opção referenciada a partir de um valor não " "existe. Subclasse de :exc:`InterpolationError`." -#: ../../library/configparser.rst:1399 +#: ../../library/configparser.rst:1425 msgid "" "Exception raised when the source text into which substitutions are made does " "not conform to the required syntax. Subclass of :exc:`InterpolationError`." @@ -1695,7 +2623,7 @@ msgstr "" "não está em conformidade com a sintaxe exigida. Subclasse de :exc:" "`InterpolationError`." -#: ../../library/configparser.rst:1405 +#: ../../library/configparser.rst:1431 msgid "" "Exception raised when attempting to parse a file which has no section " "headers." @@ -1703,11 +2631,11 @@ msgstr "" "Exceção levantada ao tentar analisar um arquivo que não possui cabeçalhos de " "seção." -#: ../../library/configparser.rst:1411 +#: ../../library/configparser.rst:1437 msgid "Exception raised when errors occur attempting to parse a file." msgstr "Exceção levantada quando ocorrem erros ao tentar analisar um arquivo." -#: ../../library/configparser.rst:1413 +#: ../../library/configparser.rst:1439 msgid "" "The ``filename`` attribute and :meth:`!__init__` constructor argument were " "removed. They have been available using the name ``source`` since 3.2." @@ -1715,7 +2643,7 @@ msgstr "" "O atributo ``filename`` e o argumento do construtor :meth:`!__init__` foram " "removidos. Eles estiveram disponíveis usando o nome ``source`` desde 3.2." -#: ../../library/configparser.rst:1419 +#: ../../library/configparser.rst:1445 msgid "" "Exception raised when a key without a corresponding value is continued with " "an indented line." @@ -1723,11 +2651,11 @@ msgstr "" "Exceção levantada quando uma chave sem valor correspondente continua com uma " "linha indentada." -#: ../../library/configparser.rst:1425 +#: ../../library/configparser.rst:1451 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../library/configparser.rst:1426 +#: ../../library/configparser.rst:1452 msgid "" "Config parsers allow for heavy customization. If you are interested in " "changing the behaviour outlined by the footnote reference, consult the " @@ -1758,14 +2686,14 @@ msgstr "arquivo ini" msgid "Windows ini file" msgstr "arquivo ini do Windows" -#: ../../library/configparser.rst:366 +#: ../../library/configparser.rst:367 msgid "% (percent)" msgstr "% (porcentagem)" -#: ../../library/configparser.rst:366 ../../library/configparser.rst:399 +#: ../../library/configparser.rst:367 ../../library/configparser.rst:400 msgid "interpolation in configuration files" msgstr "interpolação em arquivos de configuração" -#: ../../library/configparser.rst:399 +#: ../../library/configparser.rst:400 msgid "$ (dollar)" msgstr "$ (dólar)" diff --git a/library/constants.po b/library/constants.po index 53a92f892..78d5c5b95 100644 --- a/library/constants.po +++ b/library/constants.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Sheila Gomes , 2021 -# Gabriel Crispino , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:57+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-03-07 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -108,15 +106,16 @@ msgstr "" #: ../../library/constants.rst:51 msgid "" -"``NotImplementedError`` and :data:`!NotImplemented` are not interchangeable, " -"even though they have similar names and purposes. See :exc:" -"`NotImplementedError` for details on when to use it." +":data:`!NotImplemented` and :exc:`!NotImplementedError` are not " +"interchangeable. This constant should only be used as described above; see :" +"exc:`NotImplementedError` for details on correct usage of the exception." msgstr "" -"``NotImplementedError`` e :data:`!NotImplemented` não são intercambiáveis, " -"mesmo que tenham nomes e propósitos similares. Veja :exc:" -"`NotImplementedError` para detalhes e casos de uso." +":data:`!NotImplemented` e :exc:`!NotImplementedError` não são " +"intercambiáveis. Esta constante deve ser usada somente conforme descrito " +"acima; veja :exc:`NotImplementedError` para detalhes sobre o uso correto da " +"exceção." -#: ../../library/constants.rst:55 +#: ../../library/constants.rst:56 msgid "" "Evaluating :data:`!NotImplemented` in a boolean context is deprecated. While " "it currently evaluates as true, it will emit a :exc:`DeprecationWarning`. It " @@ -127,7 +126,7 @@ msgstr "" "um :exc:`DeprecationWarning`. Ele levantará uma :exc:`TypeError` em uma " "versão futura do Python." -#: ../../library/constants.rst:64 +#: ../../library/constants.rst:65 msgid "" "The same as the ellipsis literal \"``...``\". Special value used mostly in " "conjunction with extended slicing syntax for user-defined container data " @@ -139,7 +138,7 @@ msgstr "" "dados de contêiner definidos pelo usuário. ``Ellipsis`` é a única instância " "do tipo :data:`types.EllipsisType`." -#: ../../library/constants.rst:71 +#: ../../library/constants.rst:72 msgid "" "This constant is true if Python was not started with an :option:`-O` option. " "See also the :keyword:`assert` statement." @@ -147,7 +146,7 @@ msgstr "" "Esta constante é verdadeira se o Python não foi iniciado com uma opção :" "option:`-O`. Veja também a instrução :keyword:`assert`." -#: ../../library/constants.rst:77 +#: ../../library/constants.rst:78 msgid "" "The names :data:`None`, :data:`False`, :data:`True` and :data:`__debug__` " "cannot be reassigned (assignments to them, even as an attribute name, raise :" @@ -158,11 +157,11 @@ msgstr "" "levantam :exc:`SyntaxError` ), para que possam ser consideradas " "\"verdadeiras\" constantes." -#: ../../library/constants.rst:83 +#: ../../library/constants.rst:86 msgid "Constants added by the :mod:`site` module" msgstr "Constantes adicionadas pelo módulo :mod:`site`" -#: ../../library/constants.rst:85 +#: ../../library/constants.rst:88 msgid "" "The :mod:`site` module (which is imported automatically during startup, " "except if the :option:`-S` command-line option is given) adds several " @@ -175,7 +174,7 @@ msgstr "" "úteis para o console do interpretador interativo e não devem ser usados em " "programas." -#: ../../library/constants.rst:93 +#: ../../library/constants.rst:96 msgid "" "Objects that when printed, print a message like \"Use quit() or Ctrl-D (i.e. " "EOF) to exit\", and when called, raise :exc:`SystemExit` with the specified " @@ -185,7 +184,17 @@ msgstr "" "Ctrl-D (i.e. EOF) to exit\" e, quando chamados, levantam :exc:`SystemExit` " "com o código de saída especificado." -#: ../../library/constants.rst:100 +#: ../../library/constants.rst:103 +msgid "" +"Object that when printed, prints the message \"Type help() for interactive " +"help, or help(object) for help about object.\", and when called, acts as " +"described :func:`elsewhere `." +msgstr "" +"Objeto que, quando impresso, imprime a mensagem \"Type help() for " +"interactive help, or help(object) for help about object.\", e quando " +"chamado, age conforme descrito em :func:`outro lugar `." + +#: ../../library/constants.rst:110 msgid "" "Objects that when printed or called, print the text of copyright or credits, " "respectively." @@ -193,7 +202,7 @@ msgstr "" "Objetos que ao serem impressos ou chamados, imprimem o texto dos direitos " "autorais ou créditos, respectivamente." -#: ../../library/constants.rst:105 +#: ../../library/constants.rst:115 msgid "" "Object that when printed, prints the message \"Type license() to see the " "full license text\", and when called, displays the full license text in a " @@ -203,10 +212,10 @@ msgstr "" "full license text\" e, quando chamado, exibe o texto completo da licença de " "maneira semelhante a um paginador (uma tela por vez)." -#: ../../library/constants.rst:61 +#: ../../library/constants.rst:62 msgid "..." msgstr "..." -#: ../../library/constants.rst:61 +#: ../../library/constants.rst:62 msgid "ellipsis literal" msgstr "reticências literais" diff --git a/library/contextlib.po b/library/contextlib.po index d9470b687..0f50ade41 100644 --- a/library/contextlib.po +++ b/library/contextlib.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-26 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:57+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-04-11 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -30,6 +27,8 @@ msgstr "" msgid "" ":mod:`!contextlib` --- Utilities for :keyword:`!with`\\ -statement contexts" msgstr "" +":mod:`!contextlib` --- Utilitários para contextos da instrução :keyword:`!" +"with`" #: ../../library/contextlib.rst:7 msgid "**Source code:** :source:`Lib/contextlib.py`" @@ -41,6 +40,9 @@ msgid "" "`with` statement. For more information see also :ref:`typecontextmanager` " "and :ref:`context-managers`." msgstr "" +"Este módulo fornece utilitários para tarefas comuns envolvendo a instrução :" +"keyword:`with`. Para mais informações, veja também :ref:`typecontextmanager` " +"e :ref:`context-managers`." #: ../../library/contextlib.rst:17 msgid "Utilities" @@ -48,7 +50,7 @@ msgstr "Utilitários" #: ../../library/contextlib.rst:19 msgid "Functions and classes provided:" -msgstr "" +msgstr "Funções e classes fornecidas:" #: ../../library/contextlib.rst:23 msgid "" @@ -58,6 +60,11 @@ msgid "" "__exit__` is an abstract method which by default returns ``None``. See also " "the definition of :ref:`typecontextmanager`." msgstr "" +"Uma :term:`classe base abstrata` para classes que implementam :meth:`object." +"__enter__` e :meth:`object.__exit__`. Uma implementação padrão para :meth:" +"`object.__enter__` é fornecida, que retorna ``self``, enquanto :meth:`object." +"__exit__` é um método abstrato que, por padrão, retorna ``None``. Veja " +"também a definição de :ref:`typecontextmanager`." #: ../../library/contextlib.rst:34 msgid "" @@ -67,6 +74,11 @@ msgid "" "__aexit__` is an abstract method which by default returns ``None``. See also " "the definition of :ref:`async-context-managers`." msgstr "" +"Uma :term:`classe base abstrata` para classes que implementam :meth:`object." +"__aenter__` e :meth:`object.__aexit__`. Uma implementação padrão para :meth:" +"`object.__aenter__` é fornecida, que retorna ``self``, enquanto :meth:" +"`object.__aexit__` é um método abstrato que, por padrão, retorna ``None``. " +"Veja também a definição de :ref:`async-context-managers`" #: ../../library/contextlib.rst:46 msgid "" @@ -75,13 +87,17 @@ msgid "" "create a class or separate :meth:`~object.__enter__` and :meth:`~object." "__exit__` methods." msgstr "" +"Esta função é um :term:`decorador` que pode ser usado para definir uma " +"função de fábrica para gerenciadores de contexto de instrução :keyword:" +"`with`, sem precisar criar uma classe ou separar os métodos :meth:`~object." +"__enter__` e :meth:`~object.__exit__`." #: ../../library/contextlib.rst:50 msgid "" "While many objects natively support use in with statements, sometimes a " "resource needs to be managed that isn't a context manager in its own right, " "and doesn't implement a ``close()`` method for use with ``contextlib." -"closing``" +"closing``." msgstr "" #: ../../library/contextlib.rst:54 @@ -89,10 +105,48 @@ msgid "" "An abstract example would be the following to ensure correct resource " "management::" msgstr "" +"Um exemplo abstrato seria o seguinte para garantir o gerenciamento correto " +"dos recursos:" + +#: ../../library/contextlib.rst:57 +msgid "" +"from contextlib import contextmanager\n" +"\n" +"@contextmanager\n" +"def managed_resource(*args, **kwds):\n" +" # Code to acquire resource, e.g.:\n" +" resource = acquire_resource(*args, **kwds)\n" +" try:\n" +" yield resource\n" +" finally:\n" +" # Code to release resource, e.g.:\n" +" release_resource(resource)" +msgstr "" +"from contextlib import contextmanager\n" +"\n" +"@contextmanager\n" +"def managed_resource(*args, **kwds):\n" +" # Códigopara obter recursos como, por exemplo:\n" +" resource = acquire_resource(*args, **kwds)\n" +" try:\n" +" yield resource\n" +" finally:\n" +" # Código para liberar recursos como, por exemplo:\n" +" release_resource(resource)" #: ../../library/contextlib.rst:69 msgid "The function can then be used like this::" +msgstr "A função pode, então, ser usada da seguinte forma::" + +#: ../../library/contextlib.rst:71 +msgid "" +">>> with managed_resource(timeout=3600) as resource:\n" +"... # Resource is released at the end of this block,\n" +"... # even if code in the block raises an exception" msgstr "" +">>> with managed_resource(timeout=3600) as resource:\n" +"... # O recurso é liberado no final deste bloco,\n" +"... # mesmo que o código no bloco levante uma exceção" #: ../../library/contextlib.rst:75 msgid "" @@ -100,6 +154,10 @@ msgid "" "called. This iterator must yield exactly one value, which will be bound to " "the targets in the :keyword:`with` statement's :keyword:`!as` clause, if any." msgstr "" +"A função que está sendo decorada deve retornar um iterador :term:`gerador` " +"quando chamada. Este iterador deve produzir exatamente um valor, que será " +"vinculado aos alvos na cláusula :keyword:`!as` da instrução :keyword:`with`, " +"se houver." #: ../../library/contextlib.rst:79 msgid "" @@ -116,6 +174,18 @@ msgid "" "handled, and execution will resume with the statement immediately following " "the :keyword:`!with` statement." msgstr "" +"No ponto em que o gerador é produzido, o bloco aninhado na instrução :" +"keyword:`with` é executado. O gerador é então retomado após o bloco ser " +"encerrado. Se uma exceção não tratada ocorrer no bloco, ela será levantada " +"novamente dentro do gerador no ponto em que a produção ocorreu. Assim, você " +"pode usar uma instrução :keyword:`try`...\\ :keyword:`except`...\\ :keyword:" +"`finally` para capturar o erro (se houver), ou garantir que alguma limpeza " +"ocorra. Se uma exceção for capturada apenas para registrá-la ou para " +"executar alguma ação (em vez de suprimi-la completamente), o gerador deve " +"levantar novamente essa exceção. Caso contrário, o gerenciador de contexto " +"do gerador indicará à instrução :keyword:`!with` que a exceção foi tratada, " +"e a execução será retomada com a instrução imediatamente após a instrução :" +"keyword:`!with`." #: ../../library/contextlib.rst:91 msgid "" @@ -127,16 +197,25 @@ msgid "" "that context managers support multiple invocations in order to be used as " "decorators)." msgstr "" +":func:`contextmanager` usa :class:`ContextDecorator` para que os " +"gerenciadores de contexto que ela cria possam ser usados como decoradores, " +"bem como em instruções :keyword:`with`. Quando usada como um decorador, uma " +"nova instância do gerador é implicitamente criada em cada chamada de função " +"(isso permite que os gerenciadores de contexto criados por :func:" +"`contextmanager` atendam ao requisito de que os gerenciadores de contexto " +"ofereçam suporte a múltiplas invocações para serem usados como decoradores)." #: ../../library/contextlib.rst:98 msgid "Use of :class:`ContextDecorator`." -msgstr "" +msgstr "Uso de :class:`ContextDecorator`." #: ../../library/contextlib.rst:104 msgid "" "Similar to :func:`~contextlib.contextmanager`, but creates an :ref:" "`asynchronous context manager `." msgstr "" +"Semelhante a :func:`~contextlib.contextmanager`, mas cria um :ref:" +"`gerenciador de contexto assíncrono `." #: ../../library/contextlib.rst:107 msgid "" @@ -146,16 +225,85 @@ msgid "" "and :meth:`~object.__aexit__` methods. It must be applied to an :term:" "`asynchronous generator` function." msgstr "" +"Esta função é um :term:`decorador` que pode ser usado para definir uma " +"função de fábrica para gerenciadores de contexto assíncronos de instrução :" +"keyword:`async with`, sem precisar criar uma classe ou separar os métodos :" +"meth:`~object.__aenter__` e :meth:`~object.__aexit__`. Ela deve ser aplicada " +"a uma função que atua como :term:`gerador assíncrono`." #: ../../library/contextlib.rst:113 msgid "A simple example::" msgstr "Um exemplo simples::" +#: ../../library/contextlib.rst:115 +msgid "" +"from contextlib import asynccontextmanager\n" +"\n" +"@asynccontextmanager\n" +"async def get_connection():\n" +" conn = await acquire_db_connection()\n" +" try:\n" +" yield conn\n" +" finally:\n" +" await release_db_connection(conn)\n" +"\n" +"async def get_all_users():\n" +" async with get_connection() as conn:\n" +" return conn.query('SELECT ...')" +msgstr "" +"from contextlib import asynccontextmanager\n" +"\n" +"@asynccontextmanager\n" +"async def get_connection():\n" +" conn = await acquire_db_connection()\n" +" try:\n" +" yield conn\n" +" finally:\n" +" await release_db_connection(conn)\n" +"\n" +"async def get_all_users():\n" +" async with get_connection() as conn:\n" +" return conn.query('SELECT ...')" + #: ../../library/contextlib.rst:131 msgid "" "Context managers defined with :func:`asynccontextmanager` can be used either " "as decorators or with :keyword:`async with` statements::" msgstr "" +"Gerenciadores de contexto definidos com :func:`asynccontextmanager` podem " +"ser usados como decoradores ou com instruções :keyword:`async with`::" + +#: ../../library/contextlib.rst:134 +msgid "" +"import time\n" +"from contextlib import asynccontextmanager\n" +"\n" +"@asynccontextmanager\n" +"async def timeit():\n" +" now = time.monotonic()\n" +" try:\n" +" yield\n" +" finally:\n" +" print(f'it took {time.monotonic() - now}s to run')\n" +"\n" +"@timeit()\n" +"async def main():\n" +" # ... async code ..." +msgstr "" +"import time\n" +"from contextlib import asynccontextmanager\n" +"\n" +"@asynccontextmanager\n" +"async def timeit():\n" +" now = time.monotonic()\n" +" try:\n" +" yield\n" +" finally:\n" +" print(f'it took {time.monotonic() - now}s to run')\n" +"\n" +"@timeit()\n" +"async def main():\n" +" # ... código do async ..." #: ../../library/contextlib.rst:149 msgid "" @@ -164,28 +312,75 @@ msgid "" "created by :func:`asynccontextmanager` to meet the requirement that context " "managers support multiple invocations in order to be used as decorators." msgstr "" +"Quando usada como um decorador, uma nova instância do gerador é " +"implicitamente criada em cada chamada de função. Isso permite que os " +"gerenciadores de contexto criados por :func:`asynccontextmanager` atendam ao " +"requisito de que os gerenciadores de contexto ofereçam suporte a múltiplas " +"invocações para serem usados como decoradores." #: ../../library/contextlib.rst:154 msgid "" "Async context managers created with :func:`asynccontextmanager` can be used " "as decorators." msgstr "" +"Gerenciadores de contexto assíncronos criados com :func:" +"`asynccontextmanager` podem ser usados como decoradores." #: ../../library/contextlib.rst:161 msgid "" "Return a context manager that closes *thing* upon completion of the block. " "This is basically equivalent to::" msgstr "" +"Retorna um gerenciador de contexto que fecha *thing* após a conclusão do " +"bloco. Isso basicamente equivale a::" + +#: ../../library/contextlib.rst:164 +msgid "" +"from contextlib import contextmanager\n" +"\n" +"@contextmanager\n" +"def closing(thing):\n" +" try:\n" +" yield thing\n" +" finally:\n" +" thing.close()" +msgstr "" +"from contextlib import contextmanager\n" +"\n" +"@contextmanager\n" +"def closing(thing):\n" +" try:\n" +" yield thing\n" +" finally:\n" +" thing.close()" #: ../../library/contextlib.rst:173 msgid "And lets you write code like this::" +msgstr "E permite que você escreva código como isso:" + +#: ../../library/contextlib.rst:175 +msgid "" +"from contextlib import closing\n" +"from urllib.request import urlopen\n" +"\n" +"with closing(urlopen('https://www.python.org')) as page:\n" +" for line in page:\n" +" print(line)" msgstr "" +"from contextlib import closing\n" +"from urllib.request import urlopen\n" +"\n" +"with closing(urlopen('https://www.python.org')) as page:\n" +" for line in page:\n" +" print(line)" #: ../../library/contextlib.rst:182 msgid "" "without needing to explicitly close ``page``. Even if an error occurs, " "``page.close()`` will be called when the :keyword:`with` block is exited." msgstr "" +"sem precisar fechar explicitamente ``page``. Mesmo se ocorrer um erro, " +"``page.close()`` será chamado quando o bloco :keyword:`with` for encerrado." #: ../../library/contextlib.rst:187 msgid "" @@ -195,12 +390,40 @@ msgid "" "context managers. This example is purely for illustration purposes, as :func:" "`~urllib.request.urlopen` would normally be used in a context manager." msgstr "" +"A maioria dos tipos que gerenciam recursos suporta o protocolo de :term:" +"`gerenciador de contexto`, que fecha *thing* ao sair da declaração :keyword:" +"`with`. Como tal, :func:`!closing` é mais útil para tipos de terceiros que " +"não oferecem suporte a gerenciadores de contexto. Este exemplo é puramente " +"para fins ilustrativos, pois :func:`~urllib.request.urlopen` normalmente " +"seria usado em um gerenciador de contexto." #: ../../library/contextlib.rst:196 msgid "" "Return an async context manager that calls the ``aclose()`` method of " "*thing* upon completion of the block. This is basically equivalent to::" msgstr "" +"Retorna um gerenciador de contexto async que chama o método ``aclose()`` de " +"*thing* após a conclusão do bloco. Isso basicamente equivale a::" + +#: ../../library/contextlib.rst:199 +msgid "" +"from contextlib import asynccontextmanager\n" +"\n" +"@asynccontextmanager\n" +"async def aclosing(thing):\n" +" try:\n" +" yield thing\n" +" finally:\n" +" await thing.aclose()" +msgstr "" +"from contextlib import asynccontextmanager\n" +"\n" +"@asynccontextmanager\n" +"async def aclosing(thing):\n" +" try:\n" +" yield thing\n" +" finally:\n" +" await thing.aclose()" #: ../../library/contextlib.rst:208 msgid "" @@ -208,6 +431,25 @@ msgid "" "generators when they happen to exit early by :keyword:`break` or an " "exception. For example::" msgstr "" +"De forma significativa, ``aclosing()`` oferece suporte a limpeza " +"determinística de geradores assíncronos quando eles são encerrados mais cedo " +"por :keyword:`break` ou uma exceção. Por exemplo::" + +#: ../../library/contextlib.rst:212 +msgid "" +"from contextlib import aclosing\n" +"\n" +"async with aclosing(my_generator()) as values:\n" +" async for value in values:\n" +" if value == 42:\n" +" break" +msgstr "" +"from contextlib import aclosing\n" +"\n" +"async with aclosing(my_generator()) as values:\n" +" async for value in values:\n" +" if value == 42:\n" +" break" #: ../../library/contextlib.rst:219 msgid "" @@ -216,6 +458,10 @@ msgid "" "work as expected, and the exit code isn't run after the lifetime of some " "task it depends on)." msgstr "" +"Esse padrão garante que o código de saída assíncrono do gerador seja " +"executado no mesmo contexto que suas iterações (para que exceções e " +"variáveis de contexto funcionem conforme o esperado, e o código de saída não " +"seja executado após o tempo de vida de alguma tarefa da qual ele depende)." #: ../../library/contextlib.rst:231 msgid "" @@ -223,20 +469,96 @@ msgid "" "otherwise does nothing. It is intended to be used as a stand-in for an " "optional context manager, for example::" msgstr "" +"Retorna um gerenciador de contexto que retorna *enter_result* de " +"``__enter__``, mas não faz nada de outra forma. Ele foi criado para ser " +"usado como um substituto para um gerenciador de contexto opcional, por " +"exemplo::" + +#: ../../library/contextlib.rst:235 +msgid "" +"def myfunction(arg, ignore_exceptions=False):\n" +" if ignore_exceptions:\n" +" # Use suppress to ignore all exceptions.\n" +" cm = contextlib.suppress(Exception)\n" +" else:\n" +" # Do not ignore any exceptions, cm has no effect.\n" +" cm = contextlib.nullcontext()\n" +" with cm:\n" +" # Do something" +msgstr "" +"def myfunction(arg, ignore_exceptions=False):\n" +" if ignore_exceptions:\n" +" # Usa suppress para ignorar todas as exceções.\n" +" cm = contextlib.suppress(Exception)\n" +" else:\n" +" # Não ignora quaisquer exceções, cm não tem efeito.\n" +" cm = contextlib.nullcontext()\n" +" with cm:\n" +" # Faz algo" #: ../../library/contextlib.rst:245 msgid "An example using *enter_result*::" -msgstr "" +msgstr "Um exemplo usando *enter_result*::" + +#: ../../library/contextlib.rst:247 +msgid "" +"def process_file(file_or_path):\n" +" if isinstance(file_or_path, str):\n" +" # If string, open file\n" +" cm = open(file_or_path)\n" +" else:\n" +" # Caller is responsible for closing file\n" +" cm = nullcontext(file_or_path)\n" +"\n" +" with cm as file:\n" +" # Perform processing on the file" +msgstr "" +"def process_file(file_or_path):\n" +" if isinstance(file_or_path, str):\n" +" # Se for uma string, abre o arquivo\n" +" cm = open(file_or_path)\n" +" else:\n" +" # O chamador é responsável por fechar o arquivo\n" +" cm = nullcontext(file_or_path)\n" +"\n" +" with cm as file:\n" +" # Efetua um processamento no arquivo" #: ../../library/contextlib.rst:258 msgid "" "It can also be used as a stand-in for :ref:`asynchronous context managers " "`::" msgstr "" +"Também pode ser usado como um substituto para :ref:`gerenciadores de " +"contexto assíncronos `::" + +#: ../../library/contextlib.rst:261 +msgid "" +"async def send_http(session=None):\n" +" if not session:\n" +" # If no http session, create it with aiohttp\n" +" cm = aiohttp.ClientSession()\n" +" else:\n" +" # Caller is responsible for closing the session\n" +" cm = nullcontext(session)\n" +"\n" +" async with cm as session:\n" +" # Send http requests with session" +msgstr "" +"async def send_http(session=None):\n" +" if not session:\n" +" # Se houver nenhuma sessão http, cria-a com aiohttp\n" +" cm = aiohttp.ClientSession()\n" +" else:\n" +" # O chamador é responsável por fechar a sessão\n" +" cm = nullcontext(session)\n" +"\n" +" async with cm as session:\n" +" # Envia requisições http com sessão" #: ../../library/contextlib.rst:274 msgid ":term:`asynchronous context manager` support was added." -msgstr "" +msgstr "Suporte a :term:`gerenciador de contexto assíncrono` foi adicionado." #: ../../library/contextlib.rst:281 msgid "" @@ -245,6 +567,10 @@ msgid "" "execution with the first statement following the end of the :keyword:`!with` " "statement." msgstr "" +"Retorna um gerenciador de contexto que suprime qualquer uma das exceções " +"especificadas se elas ocorrerem no corpo de uma instrução :keyword:`!with` e " +"então retoma a execução com a primeira instrução após o final da instrução :" +"keyword:`!with`." #: ../../library/contextlib.rst:286 msgid "" @@ -253,19 +579,63 @@ msgid "" "silently continuing with program execution is known to be the right thing to " "do." msgstr "" +"Como qualquer outro mecanismo que suprime completamente exceções, este " +"gerenciador de contexto deve ser usado apenas para cobrir erros muito " +"específicos, onde continuar silenciosamente com a execução do programa é " +"considerado a coisa certa a fazer." #: ../../library/contextlib.rst:291 msgid "For example::" msgstr "Por exemplo::" +#: ../../library/contextlib.rst:293 +msgid "" +"from contextlib import suppress\n" +"\n" +"with suppress(FileNotFoundError):\n" +" os.remove('somefile.tmp')\n" +"\n" +"with suppress(FileNotFoundError):\n" +" os.remove('someotherfile.tmp')" +msgstr "" +"from contextlib import suppress\n" +"\n" +"with suppress(FileNotFoundError):\n" +" os.remove('algumarquivo.tmp')\n" +"\n" +"with suppress(FileNotFoundError):\n" +" os.remove('outroarquivo.tmp')" + #: ../../library/contextlib.rst:301 msgid "This code is equivalent to::" -msgstr "" +msgstr "Este código equivale a::" + +#: ../../library/contextlib.rst:303 +msgid "" +"try:\n" +" os.remove('somefile.tmp')\n" +"except FileNotFoundError:\n" +" pass\n" +"\n" +"try:\n" +" os.remove('someotherfile.tmp')\n" +"except FileNotFoundError:\n" +" pass" +msgstr "" +"try:\n" +" os.remove('algumarquivo.tmp')\n" +"except FileNotFoundError:\n" +" pass\n" +"\n" +"try:\n" +" os.remove('outroarquivo.tmp')\n" +"except FileNotFoundError:\n" +" pass" #: ../../library/contextlib.rst:313 ../../library/contextlib.rst:362 #: ../../library/contextlib.rst:372 ../../library/contextlib.rst:389 msgid "This context manager is :ref:`reentrant `." -msgstr "" +msgstr "O gerenciador de contexto é :ref:`reentrante `." #: ../../library/contextlib.rst:315 msgid "" @@ -275,6 +645,11 @@ msgid "" "group which is created using the original group's :meth:`~BaseExceptionGroup." "derive` method." msgstr "" +"Se o código dentro do bloco :keyword:`!with` levantar uma exceção :exc:" +"`BaseExceptionGroup`, exceções suprimidas são removidas do grupo. Quaisquer " +"exceções do grupo que não forem suprimidas são levantadas novamente em um " +"novo grupo que é criado usando o método :meth:`~BaseExceptionGroup.derive` " +"do grupo original." #: ../../library/contextlib.rst:323 msgid "" @@ -303,16 +678,36 @@ msgid "" "`with` statement::" msgstr "" +#: ../../library/contextlib.rst:341 +msgid "" +"with redirect_stdout(io.StringIO()) as f:\n" +" help(pow)\n" +"s = f.getvalue()" +msgstr "" + #: ../../library/contextlib.rst:345 msgid "" "To send the output of :func:`help` to a file on disk, redirect the output to " "a regular file::" msgstr "" +#: ../../library/contextlib.rst:348 +msgid "" +"with open('help.txt', 'w') as f:\n" +" with redirect_stdout(f):\n" +" help(pow)" +msgstr "" + #: ../../library/contextlib.rst:352 msgid "To send the output of :func:`help` to *sys.stderr*::" msgstr "" +#: ../../library/contextlib.rst:354 +msgid "" +"with redirect_stdout(sys.stderr):\n" +" help(pow)" +msgstr "" + #: ../../library/contextlib.rst:357 msgid "" "Note that the global side effect on :data:`sys.stdout` means that this " @@ -365,19 +760,66 @@ msgstr "" msgid "Example of ``ContextDecorator``::" msgstr "" +#: ../../library/contextlib.rst:407 +msgid "" +"from contextlib import ContextDecorator\n" +"\n" +"class mycontext(ContextDecorator):\n" +" def __enter__(self):\n" +" print('Starting')\n" +" return self\n" +"\n" +" def __exit__(self, *exc):\n" +" print('Finishing')\n" +" return False" +msgstr "" + #: ../../library/contextlib.rst:418 ../../library/contextlib.rst:490 msgid "The class can then be used like this::" msgstr "" +#: ../../library/contextlib.rst:420 +msgid "" +">>> @mycontext()\n" +"... def function():\n" +"... print('The bit in the middle')\n" +"...\n" +">>> function()\n" +"Starting\n" +"The bit in the middle\n" +"Finishing\n" +"\n" +">>> with mycontext():\n" +"... print('The bit in the middle')\n" +"...\n" +"Starting\n" +"The bit in the middle\n" +"Finishing" +msgstr "" + #: ../../library/contextlib.rst:436 msgid "" "This change is just syntactic sugar for any construct of the following form::" msgstr "" +#: ../../library/contextlib.rst:438 +msgid "" +"def f():\n" +" with cm():\n" +" # Do stuff" +msgstr "" + #: ../../library/contextlib.rst:442 msgid "``ContextDecorator`` lets you instead write::" msgstr "" +#: ../../library/contextlib.rst:444 +msgid "" +"@cm()\n" +"def f():\n" +" # Do stuff" +msgstr "" + #: ../../library/contextlib.rst:448 msgid "" "It makes it clear that the ``cm`` applies to the whole function, rather than " @@ -390,6 +832,18 @@ msgid "" "using ``ContextDecorator`` as a mixin class::" msgstr "" +#: ../../library/contextlib.rst:454 +msgid "" +"from contextlib import ContextDecorator\n" +"\n" +"class mycontext(ContextBaseClass, ContextDecorator):\n" +" def __enter__(self):\n" +" return self\n" +"\n" +" def __exit__(self, *exc):\n" +" return False" +msgstr "" + #: ../../library/contextlib.rst:464 msgid "" "As the decorated function must be able to be called multiple times, the " @@ -407,6 +861,42 @@ msgstr "" msgid "Example of ``AsyncContextDecorator``::" msgstr "" +#: ../../library/contextlib.rst:478 +msgid "" +"from asyncio import run\n" +"from contextlib import AsyncContextDecorator\n" +"\n" +"class mycontext(AsyncContextDecorator):\n" +" async def __aenter__(self):\n" +" print('Starting')\n" +" return self\n" +"\n" +" async def __aexit__(self, *exc):\n" +" print('Finishing')\n" +" return False" +msgstr "" + +#: ../../library/contextlib.rst:492 +msgid "" +">>> @mycontext()\n" +"... async def function():\n" +"... print('The bit in the middle')\n" +"...\n" +">>> run(function())\n" +"Starting\n" +"The bit in the middle\n" +"Finishing\n" +"\n" +">>> async def function():\n" +"... async with mycontext():\n" +"... print('The bit in the middle')\n" +"...\n" +">>> run(function())\n" +"Starting\n" +"The bit in the middle\n" +"Finishing" +msgstr "" + #: ../../library/contextlib.rst:515 msgid "" "A context manager that is designed to make it easy to programmatically " @@ -420,6 +910,15 @@ msgid "" "as follows::" msgstr "" +#: ../../library/contextlib.rst:522 +msgid "" +"with ExitStack() as stack:\n" +" files = [stack.enter_context(open(fname)) for fname in filenames]\n" +" # All opened files will automatically be closed at the end of\n" +" # the with statement, even if attempts to open files later\n" +" # in the list raise an exception" +msgstr "" + #: ../../library/contextlib.rst:528 msgid "" "The :meth:`~object.__enter__` method returns the :class:`ExitStack` " @@ -542,6 +1041,18 @@ msgid "" "operation as follows::" msgstr "" +#: ../../library/contextlib.rst:606 +msgid "" +"with ExitStack() as stack:\n" +" files = [stack.enter_context(open(fname)) for fname in filenames]\n" +" # Hold onto the close method, but don't call it yet.\n" +" close_files = stack.pop_all().close\n" +" # If opening any file fails, all previously opened files will be\n" +" # closed automatically. If all files are opened successfully,\n" +" # they will remain open even after the with statement ends.\n" +" # close_files() can then be invoked explicitly to close them all." +msgstr "" + #: ../../library/contextlib.rst:617 msgid "" "Immediately unwinds the callback stack, invoking callbacks in the reverse " @@ -562,51 +1073,61 @@ msgid "" "be used instead." msgstr "" -#: ../../library/contextlib.rst:634 +#: ../../library/contextlib.rst:635 msgid "" "Similar to :meth:`ExitStack.enter_context` but expects an asynchronous " "context manager." msgstr "" -#: ../../library/contextlib.rst:637 +#: ../../library/contextlib.rst:638 msgid "" "Raises :exc:`TypeError` instead of :exc:`AttributeError` if *cm* is not an " "asynchronous context manager." msgstr "" -#: ../../library/contextlib.rst:643 +#: ../../library/contextlib.rst:644 msgid "" "Similar to :meth:`ExitStack.push` but expects either an asynchronous context " "manager or a coroutine function." msgstr "" -#: ../../library/contextlib.rst:648 +#: ../../library/contextlib.rst:649 msgid "Similar to :meth:`ExitStack.callback` but expects a coroutine function." msgstr "" -#: ../../library/contextlib.rst:652 +#: ../../library/contextlib.rst:654 msgid "Similar to :meth:`ExitStack.close` but properly handles awaitables." msgstr "" -#: ../../library/contextlib.rst:654 +#: ../../library/contextlib.rst:656 msgid "Continuing the example for :func:`asynccontextmanager`::" msgstr "" -#: ../../library/contextlib.rst:666 +#: ../../library/contextlib.rst:658 +msgid "" +"async with AsyncExitStack() as stack:\n" +" connections = [await stack.enter_async_context(get_connection())\n" +" for i in range(5)]\n" +" # All opened connections will automatically be released at the end of\n" +" # the async with statement, even if attempts to open a connection\n" +" # later in the list raise an exception." +msgstr "" + +#: ../../library/contextlib.rst:668 msgid "Examples and Recipes" msgstr "Exemplos e receitas" -#: ../../library/contextlib.rst:668 +#: ../../library/contextlib.rst:670 msgid "" "This section describes some examples and recipes for making effective use of " "the tools provided by :mod:`contextlib`." msgstr "" -#: ../../library/contextlib.rst:673 +#: ../../library/contextlib.rst:675 msgid "Supporting a variable number of context managers" msgstr "" -#: ../../library/contextlib.rst:675 +#: ../../library/contextlib.rst:677 msgid "" "The primary use case for :class:`ExitStack` is the one given in the class " "documentation: supporting a variable number of context managers and other " @@ -616,18 +1137,29 @@ msgid "" "of the context managers being optional::" msgstr "" -#: ../../library/contextlib.rst:690 +#: ../../library/contextlib.rst:684 +msgid "" +"with ExitStack() as stack:\n" +" for resource in resources:\n" +" stack.enter_context(resource)\n" +" if need_special_resource():\n" +" special = acquire_special_resource()\n" +" stack.callback(release_special_resource, special)\n" +" # Perform operations that use the acquired resources" +msgstr "" + +#: ../../library/contextlib.rst:692 msgid "" "As shown, :class:`ExitStack` also makes it quite easy to use :keyword:`with` " "statements to manage arbitrary resources that don't natively support the " "context management protocol." msgstr "" -#: ../../library/contextlib.rst:696 +#: ../../library/contextlib.rst:698 msgid "Catching exceptions from ``__enter__`` methods" msgstr "" -#: ../../library/contextlib.rst:698 +#: ../../library/contextlib.rst:700 msgid "" "It is occasionally desirable to catch exceptions from an ``__enter__`` " "method implementation, *without* inadvertently catching exceptions from the :" @@ -636,7 +1168,19 @@ msgid "" "be separated slightly in order to allow this::" msgstr "" -#: ../../library/contextlib.rst:713 +#: ../../library/contextlib.rst:706 +msgid "" +"stack = ExitStack()\n" +"try:\n" +" x = stack.enter_context(cm)\n" +"except Exception:\n" +" # handle __enter__ exception\n" +"else:\n" +" with stack:\n" +" # Handle normal case" +msgstr "" + +#: ../../library/contextlib.rst:715 msgid "" "Actually needing to do this is likely to indicate that the underlying API " "should be providing a direct resource management interface for use with :" @@ -647,29 +1191,67 @@ msgid "" "`with` statement." msgstr "" -#: ../../library/contextlib.rst:723 +#: ../../library/contextlib.rst:725 msgid "Cleaning up in an ``__enter__`` implementation" msgstr "" -#: ../../library/contextlib.rst:725 +#: ../../library/contextlib.rst:727 msgid "" "As noted in the documentation of :meth:`ExitStack.push`, this method can be " "useful in cleaning up an already allocated resource if later steps in the :" "meth:`~object.__enter__` implementation fail." msgstr "" -#: ../../library/contextlib.rst:729 +#: ../../library/contextlib.rst:731 msgid "" "Here's an example of doing this for a context manager that accepts resource " "acquisition and release functions, along with an optional validation " "function, and maps them to the context management protocol::" msgstr "" -#: ../../library/contextlib.rst:769 -msgid "Replacing any use of ``try-finally`` and flag variables" +#: ../../library/contextlib.rst:735 +msgid "" +"from contextlib import contextmanager, AbstractContextManager, ExitStack\n" +"\n" +"class ResourceManager(AbstractContextManager):\n" +"\n" +" def __init__(self, acquire_resource, release_resource, " +"check_resource_ok=None):\n" +" self.acquire_resource = acquire_resource\n" +" self.release_resource = release_resource\n" +" if check_resource_ok is None:\n" +" def check_resource_ok(resource):\n" +" return True\n" +" self.check_resource_ok = check_resource_ok\n" +"\n" +" @contextmanager\n" +" def _cleanup_on_error(self):\n" +" with ExitStack() as stack:\n" +" stack.push(self)\n" +" yield\n" +" # The validation check passed and didn't raise an exception\n" +" # Accordingly, we want to keep the resource, and pass it\n" +" # back to our caller\n" +" stack.pop_all()\n" +"\n" +" def __enter__(self):\n" +" resource = self.acquire_resource()\n" +" with self._cleanup_on_error():\n" +" if not self.check_resource_ok(resource):\n" +" msg = \"Failed validation for {!r}\"\n" +" raise RuntimeError(msg.format(resource))\n" +" return resource\n" +"\n" +" def __exit__(self, *exc_details):\n" +" # We don't need to duplicate any of our resource release logic\n" +" self.release_resource()" msgstr "" #: ../../library/contextlib.rst:771 +msgid "Replacing any use of ``try-finally`` and flag variables" +msgstr "" + +#: ../../library/contextlib.rst:773 msgid "" "A pattern you will sometimes see is a ``try-finally`` statement with a flag " "variable to indicate whether or not the body of the ``finally`` clause " @@ -677,57 +1259,115 @@ msgid "" "by using an ``except`` clause instead), it looks something like this::" msgstr "" -#: ../../library/contextlib.rst:785 +#: ../../library/contextlib.rst:778 +msgid "" +"cleanup_needed = True\n" +"try:\n" +" result = perform_operation()\n" +" if result:\n" +" cleanup_needed = False\n" +"finally:\n" +" if cleanup_needed:\n" +" cleanup_resources()" +msgstr "" + +#: ../../library/contextlib.rst:787 msgid "" "As with any ``try`` statement based code, this can cause problems for " "development and review, because the setup code and the cleanup code can end " "up being separated by arbitrarily long sections of code." msgstr "" -#: ../../library/contextlib.rst:789 +#: ../../library/contextlib.rst:791 msgid "" ":class:`ExitStack` makes it possible to instead register a callback for " "execution at the end of a ``with`` statement, and then later decide to skip " "executing that callback::" msgstr "" -#: ../../library/contextlib.rst:801 +#: ../../library/contextlib.rst:795 +msgid "" +"from contextlib import ExitStack\n" +"\n" +"with ExitStack() as stack:\n" +" stack.callback(cleanup_resources)\n" +" result = perform_operation()\n" +" if result:\n" +" stack.pop_all()" +msgstr "" + +#: ../../library/contextlib.rst:803 msgid "" "This allows the intended cleanup behaviour to be made explicit up front, " "rather than requiring a separate flag variable." msgstr "" -#: ../../library/contextlib.rst:804 +#: ../../library/contextlib.rst:806 msgid "" "If a particular application uses this pattern a lot, it can be simplified " "even further by means of a small helper class::" msgstr "" -#: ../../library/contextlib.rst:822 +#: ../../library/contextlib.rst:809 +msgid "" +"from contextlib import ExitStack\n" +"\n" +"class Callback(ExitStack):\n" +" def __init__(self, callback, /, *args, **kwds):\n" +" super().__init__()\n" +" self.callback(callback, *args, **kwds)\n" +"\n" +" def cancel(self):\n" +" self.pop_all()\n" +"\n" +"with Callback(cleanup_resources) as cb:\n" +" result = perform_operation()\n" +" if result:\n" +" cb.cancel()" +msgstr "" + +#: ../../library/contextlib.rst:824 msgid "" "If the resource cleanup isn't already neatly bundled into a standalone " "function, then it is still possible to use the decorator form of :meth:" "`ExitStack.callback` to declare the resource cleanup in advance::" msgstr "" -#: ../../library/contextlib.rst:837 +#: ../../library/contextlib.rst:829 +msgid "" +"from contextlib import ExitStack\n" +"\n" +"with ExitStack() as stack:\n" +" @stack.callback\n" +" def cleanup_resources():\n" +" ...\n" +" result = perform_operation()\n" +" if result:\n" +" stack.pop_all()" +msgstr "" + +#: ../../library/contextlib.rst:839 msgid "" "Due to the way the decorator protocol works, a callback function declared " "this way cannot take any parameters. Instead, any resources to be released " "must be accessed as closure variables." msgstr "" +"Devido à maneira como o protocolo decorador funciona, uma função de retorno " +"de chamada declarada dessa forma não pode receber nenhum parâmetro. Em vez " +"disso, quaisquer recursos a serem liberados devem ser acessados como " +"variáveis de clausura." -#: ../../library/contextlib.rst:843 +#: ../../library/contextlib.rst:845 msgid "Using a context manager as a function decorator" msgstr "" -#: ../../library/contextlib.rst:845 +#: ../../library/contextlib.rst:847 msgid "" ":class:`ContextDecorator` makes it possible to use a context manager in both " "an ordinary ``with`` statement and also as a function decorator." msgstr "" -#: ../../library/contextlib.rst:848 +#: ../../library/contextlib.rst:850 msgid "" "For example, it is sometimes useful to wrap functions or groups of " "statements with a logger that can track the time of entry and time of exit. " @@ -736,15 +1376,48 @@ msgid "" "in a single definition::" msgstr "" -#: ../../library/contextlib.rst:869 +#: ../../library/contextlib.rst:856 +msgid "" +"from contextlib import ContextDecorator\n" +"import logging\n" +"\n" +"logging.basicConfig(level=logging.INFO)\n" +"\n" +"class track_entry_and_exit(ContextDecorator):\n" +" def __init__(self, name):\n" +" self.name = name\n" +"\n" +" def __enter__(self):\n" +" logging.info('Entering: %s', self.name)\n" +"\n" +" def __exit__(self, exc_type, exc, exc_tb):\n" +" logging.info('Exiting: %s', self.name)" +msgstr "" + +#: ../../library/contextlib.rst:871 msgid "Instances of this class can be used as both a context manager::" msgstr "" -#: ../../library/contextlib.rst:875 +#: ../../library/contextlib.rst:873 +msgid "" +"with track_entry_and_exit('widget loader'):\n" +" print('Some time consuming activity goes here')\n" +" load_widget()" +msgstr "" + +#: ../../library/contextlib.rst:877 msgid "And also as a function decorator::" msgstr "" -#: ../../library/contextlib.rst:882 +#: ../../library/contextlib.rst:879 +msgid "" +"@track_entry_and_exit('widget loader')\n" +"def activity():\n" +" print('Some time consuming activity goes here')\n" +" load_widget()" +msgstr "" + +#: ../../library/contextlib.rst:884 msgid "" "Note that there is one additional limitation when using context managers as " "function decorators: there's no way to access the return value of :meth:" @@ -752,11 +1425,11 @@ msgid "" "use an explicit ``with`` statement." msgstr "" -#: ../../library/contextlib.rst:889 +#: ../../library/contextlib.rst:891 msgid ":pep:`343` - The \"with\" statement" msgstr ":pep:`343` - A instrução \"with\"" -#: ../../library/contextlib.rst:890 +#: ../../library/contextlib.rst:892 msgid "" "The specification, background, and examples for the Python :keyword:`with` " "statement." @@ -764,11 +1437,11 @@ msgstr "" "A especificação, o histórico e os exemplos para a instrução Python :keyword:" "`with`." -#: ../../library/contextlib.rst:896 +#: ../../library/contextlib.rst:898 msgid "Single use, reusable and reentrant context managers" msgstr "" -#: ../../library/contextlib.rst:898 +#: ../../library/contextlib.rst:900 msgid "" "Most context managers are written in a way that means they can only be used " "effectively in a :keyword:`with` statement once. These single use context " @@ -776,32 +1449,55 @@ msgid "" "them a second time will trigger an exception or otherwise not work correctly." msgstr "" -#: ../../library/contextlib.rst:904 +#: ../../library/contextlib.rst:906 msgid "" "This common limitation means that it is generally advisable to create " "context managers directly in the header of the :keyword:`with` statement " "where they are used (as shown in all of the usage examples above)." msgstr "" -#: ../../library/contextlib.rst:908 +#: ../../library/contextlib.rst:910 msgid "" "Files are an example of effectively single use context managers, since the " "first :keyword:`with` statement will close the file, preventing any further " "IO operations using that file object." msgstr "" -#: ../../library/contextlib.rst:912 +#: ../../library/contextlib.rst:914 msgid "" "Context managers created using :func:`contextmanager` are also single use " "context managers, and will complain about the underlying generator failing " "to yield if an attempt is made to use them a second time::" msgstr "" -#: ../../library/contextlib.rst:940 -msgid "Reentrant context managers" +#: ../../library/contextlib.rst:918 +msgid "" +">>> from contextlib import contextmanager\n" +">>> @contextmanager\n" +"... def singleuse():\n" +"... print(\"Before\")\n" +"... yield\n" +"... print(\"After\")\n" +"...\n" +">>> cm = singleuse()\n" +">>> with cm:\n" +"... pass\n" +"...\n" +"Before\n" +"After\n" +">>> with cm:\n" +"... pass\n" +"...\n" +"Traceback (most recent call last):\n" +" ...\n" +"RuntimeError: generator didn't yield" msgstr "" #: ../../library/contextlib.rst:942 +msgid "Reentrant context managers" +msgstr "" + +#: ../../library/contextlib.rst:944 msgid "" "More sophisticated context managers may be \"reentrant\". These context " "managers can not only be used in multiple :keyword:`with` statements, but " @@ -809,21 +1505,39 @@ msgid "" "the same context manager." msgstr "" -#: ../../library/contextlib.rst:947 +#: ../../library/contextlib.rst:949 msgid "" ":class:`threading.RLock` is an example of a reentrant context manager, as " "are :func:`suppress`, :func:`redirect_stdout`, and :func:`chdir`. Here's a " "very simple example of reentrant use::" msgstr "" -#: ../../library/contextlib.rst:966 +#: ../../library/contextlib.rst:953 +msgid "" +">>> from contextlib import redirect_stdout\n" +">>> from io import StringIO\n" +">>> stream = StringIO()\n" +">>> write_to_stream = redirect_stdout(stream)\n" +">>> with write_to_stream:\n" +"... print(\"This is written to the stream rather than stdout\")\n" +"... with write_to_stream:\n" +"... print(\"This is also written to the stream\")\n" +"...\n" +">>> print(\"This is written directly to stdout\")\n" +"This is written directly to stdout\n" +">>> print(stream.getvalue())\n" +"This is written to the stream rather than stdout\n" +"This is also written to the stream" +msgstr "" + +#: ../../library/contextlib.rst:968 msgid "" "Real world examples of reentrancy are more likely to involve multiple " "functions calling each other and hence be far more complicated than this " "example." msgstr "" -#: ../../library/contextlib.rst:970 +#: ../../library/contextlib.rst:972 msgid "" "Note also that being reentrant is *not* the same thing as being thread " "safe. :func:`redirect_stdout`, for example, is definitely not thread safe, " @@ -831,11 +1545,11 @@ msgid "" "stdout` to a different stream." msgstr "" -#: ../../library/contextlib.rst:979 +#: ../../library/contextlib.rst:981 msgid "Reusable context managers" msgstr "Gerenciadores de contexto reutilizáveis" -#: ../../library/contextlib.rst:981 +#: ../../library/contextlib.rst:983 msgid "" "Distinct from both single use and reentrant context managers are " "\"reusable\" context managers (or, to be completely explicit, \"reusable, " @@ -845,21 +1559,50 @@ msgid "" "manager instance has already been used in a containing with statement." msgstr "" -#: ../../library/contextlib.rst:988 +#: ../../library/contextlib.rst:990 msgid "" ":class:`threading.Lock` is an example of a reusable, but not reentrant, " "context manager (for a reentrant lock, it is necessary to use :class:" "`threading.RLock` instead)." msgstr "" -#: ../../library/contextlib.rst:992 +#: ../../library/contextlib.rst:994 msgid "" "Another example of a reusable, but not reentrant, context manager is :class:" "`ExitStack`, as it invokes *all* currently registered callbacks when leaving " "any with statement, regardless of where those callbacks were added::" msgstr "" -#: ../../library/contextlib.rst:1023 +#: ../../library/contextlib.rst:999 +msgid "" +">>> from contextlib import ExitStack\n" +">>> stack = ExitStack()\n" +">>> with stack:\n" +"... stack.callback(print, \"Callback: from first context\")\n" +"... print(\"Leaving first context\")\n" +"...\n" +"Leaving first context\n" +"Callback: from first context\n" +">>> with stack:\n" +"... stack.callback(print, \"Callback: from second context\")\n" +"... print(\"Leaving second context\")\n" +"...\n" +"Leaving second context\n" +"Callback: from second context\n" +">>> with stack:\n" +"... stack.callback(print, \"Callback: from outer context\")\n" +"... with stack:\n" +"... stack.callback(print, \"Callback: from inner context\")\n" +"... print(\"Leaving inner context\")\n" +"... print(\"Leaving outer context\")\n" +"...\n" +"Leaving inner context\n" +"Callback: from inner context\n" +"Callback: from outer context\n" +"Leaving outer context" +msgstr "" + +#: ../../library/contextlib.rst:1025 msgid "" "As the output from the example shows, reusing a single stack object across " "multiple with statements works correctly, but attempting to nest them will " @@ -867,8 +1610,24 @@ msgid "" "which is unlikely to be desirable behaviour." msgstr "" -#: ../../library/contextlib.rst:1028 +#: ../../library/contextlib.rst:1030 msgid "" "Using separate :class:`ExitStack` instances instead of reusing a single " "instance avoids that problem::" msgstr "" + +#: ../../library/contextlib.rst:1033 +msgid "" +">>> from contextlib import ExitStack\n" +">>> with ExitStack() as outer_stack:\n" +"... outer_stack.callback(print, \"Callback: from outer context\")\n" +"... with ExitStack() as inner_stack:\n" +"... inner_stack.callback(print, \"Callback: from inner context\")\n" +"... print(\"Leaving inner context\")\n" +"... print(\"Leaving outer context\")\n" +"...\n" +"Leaving inner context\n" +"Callback: from inner context\n" +"Leaving outer context\n" +"Callback: from outer context" +msgstr "" diff --git a/library/contextvars.po b/library/contextvars.po index 96d6cb68e..2292135c3 100644 --- a/library/contextvars.po +++ b/library/contextvars.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 00:57+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -47,12 +44,12 @@ msgstr "" #: ../../library/contextvars.rst:17 msgid "" "Context managers that have state should use Context Variables instead of :" -"func:`threading.local()` to prevent their state from bleeding to other code " +"func:`threading.local` to prevent their state from bleeding to other code " "unexpectedly, when used in concurrent code." msgstr "" "Os gerenciadores de contexto que possuem estado devem usar Variáveis de " -"Contexto ao invés de :func:`threading.local()` para evitar que seu estado " -"vaze para outro código inesperadamente, quando usado em código concorrente." +"Contexto ao invés de :func:`threading.local` para evitar que seu estado vaze " +"para outro código inesperadamente, quando usado em código concorrente." #: ../../library/contextvars.rst:21 msgid "See also :pep:`567` for additional details." @@ -68,6 +65,10 @@ msgstr "" "Esta classe é usada para declarar uma nova variável de contexto, como, por " "exemplo::" +#: ../../library/contextvars.rst:33 +msgid "var: ContextVar[int] = ContextVar('var', default=42)" +msgstr "var: ContextVar[int] = ContextVar('var', default=42)" + #: ../../library/contextvars.rst:35 msgid "" "The required *name* parameter is used for introspection and debug purposes." @@ -161,6 +162,26 @@ msgstr "" msgid "For example::" msgstr "Por exemplo::" +#: ../../library/contextvars.rst:87 +msgid "" +"var = ContextVar('var')\n" +"\n" +"token = var.set('new value')\n" +"# code that uses 'var'; var.get() returns 'new value'.\n" +"var.reset(token)\n" +"\n" +"# After the reset call the var has no value again, so\n" +"# var.get() would raise a LookupError." +msgstr "" +"var = ContextVar('var')\n" +"\n" +"token = var.set('novo valor')\n" +"# código que usa 'var'; var.get() retorna 'novo valor'.\n" +"var.reset(token)\n" +"\n" +"# Após uma chamada de redefinição, var não tem mais valor,\n" +"# então var.get() levantaria uma exceção LookupError." + #: ../../library/contextvars.rst:99 msgid "" "*Token* objects are returned by the :meth:`ContextVar.set` method. They can " @@ -209,6 +230,14 @@ msgstr "" "O trecho a seguir obtém uma cópia do contexto atual e imprime todas as " "variáveis e seus valores que são definidos nele::" +#: ../../library/contextvars.rst:131 +msgid "" +"ctx: Context = copy_context()\n" +"print(list(ctx.items()))" +msgstr "" +"ctx: Context = copy_context()\n" +"print(list(ctx.items()))" + #: ../../library/contextvars.rst:134 msgid "" "The function has an *O*\\ (1) complexity, i.e. works equally fast for " @@ -233,52 +262,165 @@ msgstr "" #: ../../library/contextvars.rst:147 msgid "" -"Every thread will have a different top-level :class:`~contextvars.Context` " -"object. This means that a :class:`ContextVar` object behaves in a similar " -"fashion to :func:`threading.local()` when values are assigned in different " -"threads." +"Each thread has its own effective stack of :class:`!Context` objects. The :" +"term:`current context` is the :class:`!Context` object at the top of the " +"current thread's stack. All :class:`!Context` objects in the stacks are " +"considered to be *entered*." msgstr "" -"Cada thread terá um objeto :class:`~contextvars.Context` de nível superior " -"diferente. Isso significa que um objeto :class:`ContextVar` se comporta de " -"maneira semelhante a :func:`threading.local()` quando valores são atribuídos " -"em diferentes threads." +"Cada thread tem sua própria pilha efetiva de objetos :class:`!Context`. O :" +"term:`contexto atual` é o objeto :class:`!Context` no topo da pilha da " +"thread atual. Todos os objetos :class:`!Context` nas pilhas são considerados " +"como *inseridos*." #: ../../library/contextvars.rst:152 -msgid "Context implements the :class:`collections.abc.Mapping` interface." -msgstr "Context implementa a interface :class:`collections.abc.Mapping`." +msgid "" +"*Entering* a context, which can be done by calling its :meth:`~Context.run` " +"method, makes the context the current context by pushing it onto the top of " +"the current thread's context stack." +msgstr "" +"*Inserir* um contexto, o que pode ser feito chamando seu método :meth:" +"`~Context.run`, torna o contexto o contexto atual, colocando-o no topo da " +"pilha de contexto da thread atual." #: ../../library/contextvars.rst:156 msgid "" -"Execute ``callable(*args, **kwargs)`` code in the context object the *run* " -"method is called on. Return the result of the execution or propagate an " -"exception if one occurred." +"*Exiting* from the current context, which can be done by returning from the " +"callback passed to the :meth:`~Context.run` method, restores the current " +"context to what it was before the context was entered by popping the context " +"off the top of the context stack." msgstr "" -"Executa o código ``callable(*args, **kwargs)`` no objeto contexto em que o " -"método *run* é chamado. Retorna o resultado da execução ou propaga uma " -"exceção, se ocorrer." +"*Sair* do contexto atual, o que pode ser feito retornando do retorno de " +"chamada passado para o método :meth:`~Context.run`, restaura o contexto " +"atual para o que era antes de o contexto ser inserido, retirando o contexto " +"do topo da pilha de contextos." -#: ../../library/contextvars.rst:160 +#: ../../library/contextvars.rst:161 msgid "" -"Any changes to any context variables that *callable* makes will be contained " -"in the context object::" +"Since each thread has its own context stack, :class:`ContextVar` objects " +"behave in a similar fashion to :func:`threading.local` when values are " +"assigned in different threads." msgstr "" -"Quaisquer mudanças em quaisquer variáveis de contexto que *callable* faça " -"estarão contidas no objeto de contexto::" +"Como cada thread tem sua própria pilha de contexto, os objetos :class:" +"`ContextVar` se comportam de maneira semelhante a :func:`threading.local` " +"quando valores são atribuídos em threads diferentes." -#: ../../library/contextvars.rst:189 +#: ../../library/contextvars.rst:165 msgid "" -"The method raises a :exc:`RuntimeError` when called on the same context " -"object from more than one OS thread, or when called recursively." +"Attempting to enter an already entered context, including contexts entered " +"in other threads, raises a :exc:`RuntimeError`." +msgstr "" +"Tentar entrar em um contexto já inserido, incluindo contextos inseridos em " +"outras threads, levanta uma exceção :exc:`RuntimeError`." + +#: ../../library/contextvars.rst:168 +msgid "After exiting a context, it can later be re-entered (from any thread)." msgstr "" -"O método levanta uma :exc:`RuntimeError` quando chamado no mesmo objeto de " -"contexto de mais de uma thread do sistema operacional, ou quando chamado " -"recursivamente." +"Após sair de um contexto, ele pode ser acessado novamente (de qualquer " +"thread)." -#: ../../library/contextvars.rst:195 +#: ../../library/contextvars.rst:170 +msgid "" +"Any changes to :class:`ContextVar` values via the :meth:`ContextVar.set` " +"method are recorded in the current context. The :meth:`ContextVar.get` " +"method returns the value associated with the current context. Exiting a " +"context effectively reverts any changes made to context variables while the " +"context was entered (if needed, the values can be restored by re-entering " +"the context)." +msgstr "" +"Quaisquer alterações nos valores de :class:`ContextVar` por meio do método :" +"meth:`ContextVar.set` são registradas no contexto atual. O método :meth:" +"`ContextVar.get` retorna o valor associado ao contexto atual. Sair de um " +"contexto efetivamente reverte quaisquer alterações feitas nas variáveis de " +"contexto enquanto o contexto foi inserido (se necessário, os valores podem " +"ser restaurados ao inserir novamente o contexto)." + +#: ../../library/contextvars.rst:177 +msgid "Context implements the :class:`collections.abc.Mapping` interface." +msgstr "Context implementa a interface :class:`collections.abc.Mapping`." + +#: ../../library/contextvars.rst:181 +msgid "" +"Enters the Context, executes ``callable(*args, **kwargs)``, then exits the " +"Context. Returns *callable*'s return value, or propagates an exception if " +"one occurred." +msgstr "" +"Entra no Context, executa ``callable(*args, **kwargs)`` e sai do Context. " +"Retorna o valor de retorno de *callable* ou propaga uma exceção, se ocorrer " +"uma." + +#: ../../library/contextvars.rst:185 +msgid "Example:" +msgstr "Exemplo:" + +#: ../../library/contextvars.rst:187 +msgid "" +"import contextvars\n" +"\n" +"var = contextvars.ContextVar('var')\n" +"var.set('spam')\n" +"print(var.get()) # 'spam'\n" +"\n" +"ctx = contextvars.copy_context()\n" +"\n" +"def main():\n" +" # 'var' was set to 'spam' before\n" +" # calling 'copy_context()' and 'ctx.run(main)', so:\n" +" print(var.get()) # 'spam'\n" +" print(ctx[var]) # 'spam'\n" +"\n" +" var.set('ham')\n" +"\n" +" # Now, after setting 'var' to 'ham':\n" +" print(var.get()) # 'ham'\n" +" print(ctx[var]) # 'ham'\n" +"\n" +"# Any changes that the 'main' function makes to 'var'\n" +"# will be contained in 'ctx'.\n" +"ctx.run(main)\n" +"\n" +"# The 'main()' function was run in the 'ctx' context,\n" +"# so changes to 'var' are contained in it:\n" +"print(ctx[var]) # 'ham'\n" +"\n" +"# However, outside of 'ctx', 'var' is still set to 'spam':\n" +"print(var.get()) # 'spam'" +msgstr "" +"import contextvars\n" +"\n" +"var = contextvars.ContextVar('var')\n" +"var.set('spam')\n" +"print(var.get()) # 'spam'\n" +"\n" +"ctx = contextvars.copy_context()\n" +"\n" +"def main():\n" +" # 'var' foi definida para 'spam' antes de\n" +" # chamar 'copy_context()' e 'ctx.run(main)', então:\n" +" print(var.get()) # 'spam'\n" +" print(ctx[var]) # 'spam'\n" +"\n" +" var.set('ham')\n" +"\n" +" # Agora, após definir 'var' para 'ham':\n" +" print(var.get()) # 'ham'\n" +" print(ctx[var]) # 'ham'\n" +"\n" +"# Qualquer alteração que a função 'main' feitas a 'var'\n" +"# serão contidos em 'ctx'.\n" +"ctx.run(main)\n" +"\n" +"# A função 'main()' era executada no contexto 'ctx',\n" +"# então alterações a 'var' são contidas nele:\n" +"print(ctx[var]) # 'ham'\n" +"\n" +"# No entanto, fora de 'ctx', 'var' ainda está definida para 'spam':\n" +"print(var.get()) # 'spam'" + +#: ../../library/contextvars.rst:233 msgid "Return a shallow copy of the context object." msgstr "Retorna uma cópia rasa do objeto contexto." -#: ../../library/contextvars.rst:199 +#: ../../library/contextvars.rst:237 msgid "" "Return ``True`` if the *context* has a value for *var* set; return ``False`` " "otherwise." @@ -286,7 +428,7 @@ msgstr "" "Retorna ``True`` se *context* tem uma variável para *var* definida; do " "contrário, retorna ``False``." -#: ../../library/contextvars.rst:204 +#: ../../library/contextvars.rst:242 msgid "" "Return the value of the *var* :class:`ContextVar` variable. If the variable " "is not set in the context object, a :exc:`KeyError` is raised." @@ -294,7 +436,7 @@ msgstr "" "Retorna o valor da variável :class:`ContextVar` *var*. Se a variável não for " "definida no objeto contexto, uma :exc:`KeyError` é levantada." -#: ../../library/contextvars.rst:210 +#: ../../library/contextvars.rst:248 msgid "" "Return the value for *var* if *var* has the value in the context object. " "Return *default* otherwise. If *default* is not given, return ``None``." @@ -303,24 +445,24 @@ msgstr "" "contrário, retorna *default*. Se *default* não for fornecido, retorna " "``None``." -#: ../../library/contextvars.rst:216 +#: ../../library/contextvars.rst:254 msgid "Return an iterator over the variables stored in the context object." msgstr "Retorna um iterador sobre as variáveis armazenadas no objeto contexto." -#: ../../library/contextvars.rst:221 +#: ../../library/contextvars.rst:259 msgid "Return the number of variables set in the context object." msgstr "Retorna o número das variáveis definidas no objeto contexto." -#: ../../library/contextvars.rst:225 +#: ../../library/contextvars.rst:263 msgid "Return a list of all variables in the context object." msgstr "Retorna uma lista de todas as variáveis no objeto contexto." -#: ../../library/contextvars.rst:229 +#: ../../library/contextvars.rst:267 msgid "Return a list of all variables' values in the context object." msgstr "" "Retorna uma lista dos valores de todas as variáveis no objeto contexto." -#: ../../library/contextvars.rst:234 +#: ../../library/contextvars.rst:272 msgid "" "Return a list of 2-tuples containing all variables and their values in the " "context object." @@ -328,11 +470,11 @@ msgstr "" "Retorna uma lista de tuplas de 2 elementos contendo todas as variáveis e " "seus valores no objeto contexto." -#: ../../library/contextvars.rst:239 +#: ../../library/contextvars.rst:277 msgid "asyncio support" msgstr "Suporte a asyncio" -#: ../../library/contextvars.rst:241 +#: ../../library/contextvars.rst:279 msgid "" "Context variables are natively supported in :mod:`asyncio` and are ready to " "be used without any extra configuration. For example, here is a simple echo " @@ -344,3 +486,90 @@ msgstr "" "está um servidor simples de eco, que usa uma variável de contexto para " "disponibilizar o endereço de um cliente remoto na Task que lida com esse " "cliente::" + +#: ../../library/contextvars.rst:285 +msgid "" +"import asyncio\n" +"import contextvars\n" +"\n" +"client_addr_var = contextvars.ContextVar('client_addr')\n" +"\n" +"def render_goodbye():\n" +" # The address of the currently handled client can be accessed\n" +" # without passing it explicitly to this function.\n" +"\n" +" client_addr = client_addr_var.get()\n" +" return f'Good bye, client @ {client_addr}\\r\\n'.encode()\n" +"\n" +"async def handle_request(reader, writer):\n" +" addr = writer.transport.get_extra_info('socket').getpeername()\n" +" client_addr_var.set(addr)\n" +"\n" +" # In any code that we call is now possible to get\n" +" # client's address by calling 'client_addr_var.get()'.\n" +"\n" +" while True:\n" +" line = await reader.readline()\n" +" print(line)\n" +" if not line.strip():\n" +" break\n" +"\n" +" writer.write(b'HTTP/1.1 200 OK\\r\\n') # status line\n" +" writer.write(b'\\r\\n') # headers\n" +" writer.write(render_goodbye()) # body\n" +" writer.close()\n" +"\n" +"async def main():\n" +" srv = await asyncio.start_server(\n" +" handle_request, '127.0.0.1', 8081)\n" +"\n" +" async with srv:\n" +" await srv.serve_forever()\n" +"\n" +"asyncio.run(main())\n" +"\n" +"# To test it you can use telnet or curl:\n" +"# telnet 127.0.0.1 8081\n" +"# curl 127.0.0.1:8081" +msgstr "" +"import asyncio\n" +"import contextvars\n" +"\n" +"client_addr_var = contextvars.ContextVar('client_addr')\n" +"\n" +"def render_goodbye():\n" +" # O endereço do cliente atualmente manipulado pode ser acessado\n" +" # sem passá-lo explicitamente para esta função.\n" +"\n" +" client_addr = client_addr_var.get()\n" +" return f'Good bye, client @ {client_addr}\\r\\n'.encode()\n" +"\n" +"async def handle_request(reader, writer):\n" +" addr = writer.transport.get_extra_info('socket').getpeername()\n" +" client_addr_var.set(addr)\n" +"\n" +" # Em qualquer código que chamamos agora é possível obter\n" +" # o endereço do cliente chamando 'client_addr_var.get()'.\n" +" while True:\n" +" line = await reader.readline()\n" +" print(line)\n" +" if not line.strip():\n" +" break\n" +"\n" +" writer.write(b'HTTP/1.1 200 OK\\r\\n') # linha de status\n" +" writer.write(b'\\r\\n') # cabeçalhos\n" +" writer.write(render_goodbye()) # corpo\n" +" writer.close()\n" +"\n" +"async def main():\n" +" srv = await asyncio.start_server(\n" +" handle_request, '127.0.0.1', 8081)\n" +"\n" +" async with srv:\n" +" await srv.serve_forever()\n" +"\n" +"asyncio.run(main())\n" +"\n" +"# Para testá-lo, você pode usar telnet ou curl:\n" +"# telnet 127.0.0.1 8081\n" +"# curl 127.0.0.1:8081" diff --git a/library/copy.po b/library/copy.po index d8acabab1..c324f21af 100644 --- a/library/copy.po +++ b/library/copy.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 -# Marco Rougeth , 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:03+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -43,7 +40,7 @@ msgid "" "operations (explained below)." msgstr "" "As instruções de atribuição no Python não copiam objetos, elas criam " -"ligações entre um destino e um objeto. Para coleções que são mutáveis ​​ou " +"ligações entre um destino e um objeto. Para coleções que são mutáveis ou " "contêm itens mutáveis, às vezes é necessária uma cópia para que seja " "possível alterar uma cópia sem alterar a outra. Este módulo fornece " "operações genéricas de cópia profunda e rasa (explicadas abaixo)." @@ -239,7 +236,7 @@ msgid "" "Discussion of the special methods used to support object state retrieval and " "restoration." msgstr "" -"Discussão dos métodos especiais usados ​​para dar suporte à recuperação e " +"Discussão dos métodos especiais usados para dar suporte à recuperação e " "restauração do estado do objeto." #: ../../library/copy.rst:79 diff --git a/library/copyreg.po b/library/copyreg.po index 3ae3cc4c0..41ae2b602 100644 --- a/library/copyreg.po +++ b/library/copyreg.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# And Past , 2021 -# Marco Rougeth , 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:03+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/crypt.po b/library/crypt.po new file mode 100644 index 000000000..ab3e6a95c --- /dev/null +++ b/library/crypt.po @@ -0,0 +1,58 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../library/crypt.rst:2 +msgid ":mod:`!crypt` --- Function to check Unix passwords" +msgstr ":mod:`!crypt` --- Função para verificar senhas Unix" + +#: ../../library/crypt.rst:10 +msgid "" +"This module is no longer part of the Python standard library. It was :ref:" +"`removed in Python 3.13 ` after being deprecated in " +"Python 3.11. The removal was decided in :pep:`594`." +msgstr "" +"Este módulo não faz mais parte da biblioteca padrão do Python. Ele foi :ref:" +"`removido no Python 3.13 ` após ser descontinuado no " +"Python 3.11. A remoção foi decidida na :pep:`594`." + +#: ../../library/crypt.rst:14 +msgid "" +"Applications can use the :mod:`hashlib` module from the standard library. " +"Other possible replacements are third-party libraries from PyPI: :pypi:" +"`legacycrypt`, :pypi:`bcrypt`, :pypi:`argon2-cffi`, or :pypi:`passlib`. " +"These are not supported or maintained by the Python core team." +msgstr "" +"As aplicações podem usar o módulo :mod:`hashlib` da biblioteca padrão. " +"Outras possíveis substituições são bibliotecas de terceiros do PyPI: :pypi:" +"`legacycrypt`, :pypi:`bcrypt`, :pypi:`argon2-cffi` ou :pypi:`passlib`. Elas " +"não são suportadas ou mantidas pela equipe core do Python." + +#: ../../library/crypt.rst:19 +msgid "" +"The last version of Python that provided the :mod:`!crypt` module was " +"`Python 3.12 `_." +msgstr "" +"A última versão do Python que forneceu o módulo :mod:`!crypt` foi o `Python " +"3.12 `_." diff --git a/library/crypto.po b/library/crypto.po index 632b871c1..ebc86d609 100644 --- a/library/crypto.po +++ b/library/crypto.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:03+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/csv.po b/library/csv.po index 8a835f3df..98725ff48 100644 --- a/library/csv.po +++ b/library/csv.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# i17obot , 2021 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:03+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -88,7 +85,7 @@ msgstr "" #: ../../library/csv.rst:41 msgid ":pep:`305` - CSV File API" -msgstr ":pep:`305` - API de arquivo CSV" +msgstr ":pep:`305` - CSV File API" #: ../../library/csv.rst:42 msgid "The Python Enhancement Proposal which proposed this addition to Python." @@ -116,10 +113,10 @@ msgid "" "parameters in the current dialect. For full details about the dialect and " "formatting parameters, see section :ref:`csv-fmt-params`." msgstr "" -"Retorna um :ref:`objeto leitor ` que irá iterar sobre as " +"Retorna um :ref:`objeto leitor ` que irá iterar sobre as " "linhas no *csvfile* fornecido. Um csvfile deve ser um iterável de strings, " -"cada uma no formato csv definido pelo leitor. Um csvfile é muito comumente " -"um objeto similar a arquivo ou uma lista. Se *csvfile* for um objeto de " +"cada uma no formato csv definido pelo leitor. Um csvfile é muito comumente " +"um objeto similar a arquivo ou uma lista. Se *csvfile* for um objeto " "arquivo, ele deverá ser aberto com ``newline=''``. [1]_ Pode ser fornecido " "um parâmetro opcional *dialect*, usado para definir um conjunto de " "parâmetros específicos para um dialeto CSV específico. Pode ser uma " @@ -146,6 +143,24 @@ msgstr "" msgid "A short usage example::" msgstr "Um pequeno exemplo de uso::" +#: ../../library/csv.rst:78 +msgid "" +">>> import csv\n" +">>> with open('eggs.csv', newline='') as csvfile:\n" +"... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')\n" +"... for row in spamreader:\n" +"... print(', '.join(row))\n" +"Spam, Spam, Spam, Spam, Spam, Baked Beans\n" +"Spam, Lovely Spam, Wonderful Spam" +msgstr "" +">>> import csv\n" +">>> with open('eggs.csv', newline='') as csvfile:\n" +"... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')\n" +"... for row in spamreader:\n" +"... print(', '.join(row))\n" +"Spam, Spam, Spam, Spam, Spam, Baked Beans\n" +"Spam, Lovely Spam, Wonderful Spam" + #: ../../library/csv.rst:89 msgid "" "Return a writer object responsible for converting the user's data into " @@ -183,6 +198,22 @@ msgstr "" "retornados de uma chamada ``cursor.fetch*``. Todos os outros dados que não " "são de strings são codificados com :func:`str` antes de serem escritos." +#: ../../library/csv.rst:108 +msgid "" +"import csv\n" +"with open('eggs.csv', 'w', newline='') as csvfile:\n" +" spamwriter = csv.writer(csvfile, delimiter=' ',\n" +" quotechar='|', quoting=csv.QUOTE_MINIMAL)\n" +" spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])\n" +" spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])" +msgstr "" +"import csv\n" +"with open('eggs.csv', 'w', newline='') as csvfile:\n" +" spamwriter = csv.writer(csvfile, delimiter=' ',\n" +" quotechar='|', quoting=csv.QUOTE_MINIMAL)\n" +" spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])\n" +" spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])" + #: ../../library/csv.rst:118 msgid "" "Associate *dialect* with *name*. *name* must be a string. The dialect can " @@ -295,6 +326,32 @@ msgstr "Linhas retornadas agora são do tipo :class:`OrderedDict`." msgid "Returned rows are now of type :class:`dict`." msgstr "As linhas retornadas agora são do tipo :class:`dict`." +#: ../../library/csv.rst:183 +msgid "" +">>> import csv\n" +">>> with open('names.csv', newline='') as csvfile:\n" +"... reader = csv.DictReader(csvfile)\n" +"... for row in reader:\n" +"... print(row['first_name'], row['last_name'])\n" +"...\n" +"Eric Idle\n" +"John Cleese\n" +"\n" +">>> print(row)\n" +"{'first_name': 'John', 'last_name': 'Cleese'}" +msgstr "" +">>> import csv\n" +">>> with open('names.csv', newline='') as csvfile:\n" +"... reader = csv.DictReader(csvfile)\n" +"... for row in reader:\n" +"... print(row['first_name'], row['last_name'])\n" +"...\n" +"Eric Idle\n" +"John Cleese\n" +"\n" +">>> print(row)\n" +"{'first_name': 'John', 'last_name': 'Cleese'}" + #: ../../library/csv.rst:199 msgid "" "Create an object which operates like a regular writer but maps dictionaries " @@ -332,6 +389,30 @@ msgstr "" "Observe que, diferentemente da classe :class:`DictReader`, o parâmetro " "*fieldnames* da classe :class:`DictWriter` não é opcional." +#: ../../library/csv.rst:221 +msgid "" +"import csv\n" +"\n" +"with open('names.csv', 'w', newline='') as csvfile:\n" +" fieldnames = ['first_name', 'last_name']\n" +" writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n" +"\n" +" writer.writeheader()\n" +" writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})\n" +" writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})\n" +" writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})" +msgstr "" +"import csv\n" +"\n" +"with open('names.csv', 'w', newline='') as csvfile:\n" +" fieldnames = ['first_name', 'last_name']\n" +" writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n" +"\n" +" writer.writeheader()\n" +" writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})\n" +" writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})\n" +" writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})" + #: ../../library/csv.rst:235 msgid "" "The :class:`Dialect` class is a container class whose attributes contain " @@ -358,6 +439,18 @@ msgstr "" "class:`writer` específicas através de suas funções inicializadoras " "(``__init__``) como esta::" +#: ../../library/csv.rst:245 +msgid "" +"import csv\n" +"\n" +"with open('students.csv', 'w', newline='') as csvfile:\n" +" writer = csv.writer(csvfile, dialect='unix')" +msgstr "" +"import csv\n" +"\n" +"with open('students.csv', 'w', newline='') as csvfile:\n" +" writer = csv.writer(csvfile, dialect='unix')" + #: ../../library/csv.rst:253 msgid "" "The :class:`excel` class defines the usual properties of an Excel-generated " @@ -451,6 +544,20 @@ msgstr "" msgid "An example for :class:`Sniffer` use::" msgstr "Um exemplo para uso de :class:`Sniffer`::" +#: ../../library/csv.rst:307 +msgid "" +"with open('example.csv', newline='') as csvfile:\n" +" dialect = csv.Sniffer().sniff(csvfile.read(1024))\n" +" csvfile.seek(0)\n" +" reader = csv.reader(csvfile, dialect)\n" +" # ... process CSV file contents here ..." +msgstr "" +"with open('example.csv', newline='') as csvfile:\n" +" dialect = csv.Sniffer().sniff(csvfile.read(1024))\n" +" csvfile.seek(0)\n" +" reader = csv.reader(csvfile, dialect)\n" +" # ... processa conteúdo do arquivo CSV aqui ..." + #: ../../library/csv.rst:316 msgid "The :mod:`csv` module defines the following constants:" msgstr "O módulo :mod:`csv` define as seguintes constantes:" @@ -821,14 +928,54 @@ msgstr "Exemplos" msgid "The simplest example of reading a CSV file::" msgstr "O exemplo mais simples de leitura de um arquivo CSV::" +#: ../../library/csv.rst:554 +msgid "" +"import csv\n" +"with open('some.csv', newline='') as f:\n" +" reader = csv.reader(f)\n" +" for row in reader:\n" +" print(row)" +msgstr "" +"import csv\n" +"with open('some.csv', newline='') as f:\n" +" reader = csv.reader(f)\n" +" for row in reader:\n" +" print(row)" + #: ../../library/csv.rst:560 msgid "Reading a file with an alternate format::" msgstr "Lendo um arquivo com um formato alternativo::" +#: ../../library/csv.rst:562 +msgid "" +"import csv\n" +"with open('passwd', newline='') as f:\n" +" reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)\n" +" for row in reader:\n" +" print(row)" +msgstr "" +"import csv\n" +"with open('passwd', newline='') as f:\n" +" reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)\n" +" for row in reader:\n" +" print(row)" + #: ../../library/csv.rst:568 msgid "The corresponding simplest possible writing example is::" msgstr "O exemplo de escrita possível mais simples possível é::" +#: ../../library/csv.rst:570 +msgid "" +"import csv\n" +"with open('some.csv', 'w', newline='') as f:\n" +" writer = csv.writer(f)\n" +" writer.writerows(someiterable)" +msgstr "" +"import csv\n" +"with open('some.csv', 'w', newline='') as f:\n" +" writer = csv.writer(f)\n" +" writer.writerows(someiterable)" + #: ../../library/csv.rst:575 msgid "" "Since :func:`open` is used to open a CSV file for reading, the file will by " @@ -841,6 +988,20 @@ msgstr "" "sistema (consulte :func:`locale.getencoding`). Para decodificar um arquivo " "usando uma codificação diferente, use o argumento ``encoding`` do open::" +#: ../../library/csv.rst:580 +msgid "" +"import csv\n" +"with open('some.csv', newline='', encoding='utf-8') as f:\n" +" reader = csv.reader(f)\n" +" for row in reader:\n" +" print(row)" +msgstr "" +"import csv\n" +"with open('some.csv', newline='', encoding='utf-8') as f:\n" +" reader = csv.reader(f)\n" +" for row in reader:\n" +" print(row)" + #: ../../library/csv.rst:586 msgid "" "The same applies to writing in something other than the system default " @@ -853,6 +1014,18 @@ msgstr "" msgid "Registering a new dialect::" msgstr "Registrando um novo dialeto::" +#: ../../library/csv.rst:591 +msgid "" +"import csv\n" +"csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)\n" +"with open('passwd', newline='') as f:\n" +" reader = csv.reader(f, 'unixpwd')" +msgstr "" +"import csv\n" +"csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)\n" +"with open('passwd', newline='') as f:\n" +" reader = csv.reader(f, 'unixpwd')" + #: ../../library/csv.rst:596 msgid "" "A slightly more advanced use of the reader --- catching and reporting " @@ -860,6 +1033,28 @@ msgid "" msgstr "" "Um uso um pouco mais avançado do leitor --- capturando e relatando erros::" +#: ../../library/csv.rst:598 +msgid "" +"import csv, sys\n" +"filename = 'some.csv'\n" +"with open(filename, newline='') as f:\n" +" reader = csv.reader(f)\n" +" try:\n" +" for row in reader:\n" +" print(row)\n" +" except csv.Error as e:\n" +" sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))" +msgstr "" +"import csv, sys\n" +"filename = 'some.csv'\n" +"with open(filename, newline='') as f:\n" +" reader = csv.reader(f)\n" +" try:\n" +" for row in reader:\n" +" print(row)\n" +" except csv.Error as e:\n" +" sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))" + #: ../../library/csv.rst:608 msgid "" "And while the module doesn't directly support parsing strings, it can easily " @@ -868,6 +1063,16 @@ msgstr "" "E embora o módulo não tenha suporte diretamente à análise sintática de " "strings, isso pode ser feito facilmente::" +#: ../../library/csv.rst:611 +msgid "" +"import csv\n" +"for row in csv.reader(['one,two,three']):\n" +" print(row)" +msgstr "" +"import csv\n" +"for row in csv.reader(['one,two,three']):\n" +" print(row)" + #: ../../library/csv.rst:617 msgid "Footnotes" msgstr "Notas de rodapé" diff --git a/library/ctypes.po b/library/ctypes.po index 470d95046..cf162892b 100644 --- a/library/ctypes.po +++ b/library/ctypes.po @@ -1,38 +1,35 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 -# Claudio Rogerio Carvalho Filho , 2023 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:03+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/ctypes.rst:2 msgid ":mod:`!ctypes` --- A foreign function library for Python" -msgstr "" +msgstr ":mod:`!ctypes` --- Uma biblioteca de funções externas para Python" #: ../../library/ctypes.rst:9 msgid "**Source code:** :source:`Lib/ctypes`" -msgstr "" +msgstr "**Código-fonte:** :source:`Lib/ctypes`" #: ../../library/ctypes.rst:13 msgid "" @@ -55,6 +52,10 @@ msgid "" "they actually work. Since some code samples behave differently under Linux, " "Windows, or macOS, they contain doctest directives in comments." msgstr "" +"Nota: Os exemplos de código neste tutorial usam :mod:`doctest` para garantir " +"que eles realmente funcionem. Como algumas amostras de código se comportam " +"de maneira diferente no Linux, Windows ou macOS, elas contêm diretrizes de " +"doctest nos comentários." #: ../../library/ctypes.rst:27 msgid "" @@ -63,16 +64,23 @@ msgid "" "`c_long`. So, you should not be confused if :class:`c_long` is printed if " "you would expect :class:`c_int` --- they are actually the same type." msgstr "" +"Nota: Alguns exemplos de código fazem referência ao tipo ctypes :class:" +"`c_int`. Em plataformas onde ``sizeof(long) == sizeof(int)`` é um apelido " +"para :class:`c_long`. Então, você não deve ficar confuso se :class:`c_long` " +"for impresso se você esperaria :class:`c_int` --- eles são, na verdade, o " +"mesmo tipo." #: ../../library/ctypes.rst:35 msgid "Loading dynamic link libraries" -msgstr "" +msgstr "Carregando bibliotecas de links dinâmicos" #: ../../library/ctypes.rst:37 msgid "" ":mod:`ctypes` exports the *cdll*, and on Windows *windll* and *oledll* " "objects, for loading dynamic link libraries." msgstr "" +":mod:`ctypes` exporta o *cdll* e, no Windows, os objetos *windll* e *oledll* " +"para carregar bibliotecas de vínculo dinâmico." #: ../../library/ctypes.rst:40 msgid "" @@ -84,23 +92,47 @@ msgid "" "The error code is used to automatically raise an :class:`OSError` exception " "when the function call fails." msgstr "" +"Você carrega bibliotecas acessando-as como atributos desses objetos. *cdll* " +"carrega bibliotecas que exportam funções usando a convenção de chamada " +"padrão ``cdecl``, enquanto bibliotecas *windll* chamam funções usando a " +"convenção de chamada ``stdcall``. *oledll* também usa a convenção de chamada " +"``stdcall`` e assume que as funções retornam um código de erro do Windows :c:" +"type:`!HRESULT`. O código de erro é usado para levantar automaticamente uma " +"exceção :class:`OSError` quando a chamada da função falha." #: ../../library/ctypes.rst:48 msgid "" "Windows errors used to raise :exc:`WindowsError`, which is now an alias of :" "exc:`OSError`." msgstr "" +"Erros do Windows costumavam levantar :exc:`WindowsError`, que agora é um " +"apelido de :exc:`OSError`." #: ../../library/ctypes.rst:53 msgid "" "Here are some examples for Windows. Note that ``msvcrt`` is the MS standard " -"C library containing most standard C functions, and uses the cdecl calling " -"convention::" +"C library containing most standard C functions, and uses the ``cdecl`` " +"calling convention::" +msgstr "" +"Veja alguns exemplos para Windows. Note que ``msvcrt`` é a biblioteca C " +"padrão da MS que contém a maioria das funções C padrão e usa a convenção de " +"chamada ``cdecl``::" + +#: ../../library/ctypes.rst:57 +msgid "" +">>> from ctypes import *\n" +">>> print(windll.kernel32)\n" +"\n" +">>> print(cdll.msvcrt)\n" +"\n" +">>> libc = cdll.msvcrt\n" +">>>" msgstr "" #: ../../library/ctypes.rst:65 msgid "Windows appends the usual ``.dll`` file suffix automatically." msgstr "" +"O Windows acrescenta automaticamente o sufixo de arquivo ``.dll`` usual." #: ../../library/ctypes.rst:68 msgid "" @@ -109,6 +141,10 @@ msgid "" "used by Python. Where possible, use native Python functionality, or else " "import and use the ``msvcrt`` module." msgstr "" +"Acessar a biblioteca padrão C por meio de ``cdll.msvcrt`` usará uma versão " +"desatualizada da biblioteca que pode ser incompatível com a que está sendo " +"usada pelo Python. Onde possível, use a funcionalidade nativa do Python ou " +"então importe e use o módulo ``msvcrt``." #: ../../library/ctypes.rst:73 msgid "" @@ -118,15 +154,45 @@ msgid "" "should be used, or you should load the library by creating an instance of " "CDLL by calling the constructor::" msgstr "" +"No Linux, é necessário especificar o nome do arquivo *incluindo* a extensão " +"para carregar uma biblioteca, então o acesso de atributo não pode ser usado " +"para carregar bibliotecas. O método :meth:`~LibraryLoader.LoadLibrary` dos " +"carregadores de dll deve ser usado, ou você deve carregar a biblioteca " +"criando uma instância de CDLL chamando o construtor::" + +#: ../../library/ctypes.rst:79 +msgid "" +">>> cdll.LoadLibrary(\"libc.so.6\")\n" +"\n" +">>> libc = CDLL(\"libc.so.6\")\n" +">>> libc\n" +"\n" +">>>" +msgstr "" #: ../../library/ctypes.rst:92 msgid "Accessing functions from loaded dlls" -msgstr "" +msgstr "Acessando funções de dlls carregadas" #: ../../library/ctypes.rst:94 msgid "Functions are accessed as attributes of dll objects::" msgstr "Funções são acessadas como atributos de objetos dll::" +#: ../../library/ctypes.rst:96 +msgid "" +">>> libc.printf\n" +"<_FuncPtr object at 0x...>\n" +">>> print(windll.kernel32.GetModuleHandleA)\n" +"<_FuncPtr object at 0x...>\n" +">>> print(windll.kernel32.MyOwnFunction)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" File \"ctypes.py\", line 239, in __getattr__\n" +" func = _StdcallFuncPtr(name, self)\n" +"AttributeError: function 'MyOwnFunction' not found\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:108 msgid "" "Note that win32 system dlls like ``kernel32`` and ``user32`` often export " @@ -138,6 +204,14 @@ msgid "" "``GetModuleHandle`` depending on whether UNICODE is defined or not::" msgstr "" +#: ../../library/ctypes.rst:116 +msgid "" +"/* ANSI version */\n" +"HMODULE GetModuleHandleA(LPCSTR lpModuleName);\n" +"/* UNICODE version */\n" +"HMODULE GetModuleHandleW(LPCWSTR lpModuleName);" +msgstr "" + #: ../../library/ctypes.rst:121 msgid "" "*windll* does not try to select one of them by magic, you must access the " @@ -152,12 +226,35 @@ msgid "" "`getattr` to retrieve the function::" msgstr "" +#: ../../library/ctypes.rst:129 +msgid "" +">>> getattr(cdll.msvcrt, \"??2@YAPAXI@Z\")\n" +"<_FuncPtr object at 0x...>\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:133 msgid "" "On Windows, some dlls export functions not by name but by ordinal. These " "functions can be accessed by indexing the dll object with the ordinal " "number::" msgstr "" +"No Windows, algumas dlls exportam funções não por nome, mas por ordinal. " +"Essas funções podem ser acessadas indexando o objeto dll com o número " +"ordinal::" + +#: ../../library/ctypes.rst:136 +msgid "" +">>> cdll.kernel32[1]\n" +"<_FuncPtr object at 0x...>\n" +">>> cdll.kernel32[0]\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" File \"ctypes.py\", line 310, in __getitem__\n" +" func = _StdcallFuncPtr(name, self)\n" +"AttributeError: function ordinal 0 not found\n" +">>>" +msgstr "" #: ../../library/ctypes.rst:150 msgid "Calling functions" @@ -170,6 +267,12 @@ msgid "" "random integer::" msgstr "" +#: ../../library/ctypes.rst:155 +msgid "" +">>> print(libc.rand())\n" +"1804289383" +msgstr "" + #: ../../library/ctypes.rst:158 msgid "" "On Windows, you can call the ``GetModuleHandleA()`` function, which returns " @@ -177,12 +280,36 @@ msgid "" "``NULL`` pointer)::" msgstr "" +#: ../../library/ctypes.rst:161 +msgid "" +">>> print(hex(windll.kernel32.GetModuleHandleA(None)))\n" +"0x1d000000\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:165 msgid "" ":exc:`ValueError` is raised when you call an ``stdcall`` function with the " "``cdecl`` calling convention, or vice versa::" msgstr "" +#: ../../library/ctypes.rst:168 +msgid "" +">>> cdll.kernel32.GetModuleHandleA(None)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: Procedure probably called with not enough arguments (4 bytes " +"missing)\n" +">>>\n" +"\n" +">>> windll.msvcrt.printf(b\"spam\")\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: Procedure probably called with too many arguments (4 bytes in " +"excess)\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:180 msgid "" "To find out the correct calling convention you have to look into the C " @@ -196,6 +323,15 @@ msgid "" "with invalid argument values::" msgstr "" +#: ../../library/ctypes.rst:187 +msgid "" +">>> windll.kernel32.GetModuleHandleA(32)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"OSError: exception: access violation reading 0x00000020\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:193 msgid "" "There are, however, enough ways to crash Python with :mod:`ctypes`, so you " @@ -221,9 +357,9 @@ msgid "" "learn more about :mod:`ctypes` data types." msgstr "" -#: ../../library/ctypes.rst:212 ../../library/ctypes.rst:2203 +#: ../../library/ctypes.rst:212 ../../library/ctypes.rst:2242 msgid "Fundamental data types" -msgstr "" +msgstr "Tipos de dados fundamentais" #: ../../library/ctypes.rst:214 msgid ":mod:`ctypes` defines a number of primitive C compatible data types:" @@ -235,11 +371,11 @@ msgstr "Tipo ctypes" #: ../../library/ctypes.rst:217 msgid "C type" -msgstr "Tipo C" +msgstr "Tipo em C" #: ../../library/ctypes.rst:217 msgid "Python type" -msgstr "Tipo Python" +msgstr "Tipo em Python" #: ../../library/ctypes.rst:219 msgid ":class:`c_bool`" @@ -353,7 +489,7 @@ msgstr ":class:`c_longlong`" #: ../../library/ctypes.rst:241 msgid ":c:expr:`__int64` or :c:expr:`long long`" -msgstr "" +msgstr ":c:expr:`__int64` ou :c:expr:`long long`" #: ../../library/ctypes.rst:243 msgid ":class:`c_ulonglong`" @@ -361,7 +497,7 @@ msgstr ":class:`c_ulonglong`" #: ../../library/ctypes.rst:243 msgid ":c:expr:`unsigned __int64` or :c:expr:`unsigned long long`" -msgstr "" +msgstr ":c:expr:`unsigned __int64` ou :c:expr:`unsigned long long`" #: ../../library/ctypes.rst:246 msgid ":class:`c_size_t`" @@ -377,7 +513,7 @@ msgstr ":class:`c_ssize_t`" #: ../../library/ctypes.rst:248 msgid ":c:type:`ssize_t` or :c:expr:`Py_ssize_t`" -msgstr "" +msgstr ":c:type:`ssize_t` ou :c:expr:`Py_ssize_t`" #: ../../library/ctypes.rst:251 msgid ":class:`c_time_t`" @@ -398,7 +534,7 @@ msgstr ":c:expr:`float`" #: ../../library/ctypes.rst:253 ../../library/ctypes.rst:255 #: ../../library/ctypes.rst:257 msgid "float" -msgstr "float" +msgstr "ponto flutuante" #: ../../library/ctypes.rst:255 msgid ":class:`c_double`" @@ -422,11 +558,11 @@ msgstr ":class:`c_char_p`" #: ../../library/ctypes.rst:259 msgid ":c:expr:`char *` (NUL terminated)" -msgstr "" +msgstr ":c:expr:`char *` (finalizado com NUL)" #: ../../library/ctypes.rst:259 msgid "bytes object or ``None``" -msgstr "bytes object ou ``None``" +msgstr "objeto bytes ou ``None``" #: ../../library/ctypes.rst:261 msgid ":class:`c_wchar_p`" @@ -434,7 +570,7 @@ msgstr ":class:`c_wchar_p`" #: ../../library/ctypes.rst:261 msgid ":c:expr:`wchar_t *` (NUL terminated)" -msgstr "" +msgstr ":c:expr:`wchar_t *` (finalizado com NUL)" #: ../../library/ctypes.rst:261 msgid "string or ``None``" @@ -462,17 +598,59 @@ msgid "" "of the correct type and value::" msgstr "" +#: ../../library/ctypes.rst:272 +msgid "" +">>> c_int()\n" +"c_long(0)\n" +">>> c_wchar_p(\"Hello, World\")\n" +"c_wchar_p(140018365411392)\n" +">>> c_ushort(-3)\n" +"c_ushort(65533)\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:280 msgid "" "Since these types are mutable, their value can also be changed afterwards::" msgstr "" +#: ../../library/ctypes.rst:282 +msgid "" +">>> i = c_int(42)\n" +">>> print(i)\n" +"c_long(42)\n" +">>> print(i.value)\n" +"42\n" +">>> i.value = -99\n" +">>> print(i.value)\n" +"-99\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:292 msgid "" "Assigning a new value to instances of the pointer types :class:`c_char_p`, :" "class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they " "point to, *not the contents* of the memory block (of course not, because " -"Python bytes objects are immutable)::" +"Python string objects are immutable)::" +msgstr "" + +#: ../../library/ctypes.rst:297 +msgid "" +">>> s = \"Hello, World\"\n" +">>> c_s = c_wchar_p(s)\n" +">>> print(c_s)\n" +"c_wchar_p(139966785747344)\n" +">>> print(c_s.value)\n" +"Hello World\n" +">>> c_s.value = \"Hi, there\"\n" +">>> print(c_s) # the memory location has changed\n" +"c_wchar_p(139966783348904)\n" +">>> print(c_s.value)\n" +"Hi, there\n" +">>> print(s) # first object is unchanged\n" +"Hello, World\n" +">>>" msgstr "" #: ../../library/ctypes.rst:312 @@ -485,6 +663,28 @@ msgid "" "``value`` property::" msgstr "" +#: ../../library/ctypes.rst:319 +msgid "" +">>> from ctypes import *\n" +">>> p = create_string_buffer(3) # create a 3 byte buffer, " +"initialized to NUL bytes\n" +">>> print(sizeof(p), repr(p.raw))\n" +"3 b'\\x00\\x00\\x00'\n" +">>> p = create_string_buffer(b\"Hello\") # create a buffer containing a " +"NUL terminated string\n" +">>> print(sizeof(p), repr(p.raw))\n" +"6 b'Hello\\x00'\n" +">>> print(repr(p.value))\n" +"b'Hello'\n" +">>> p = create_string_buffer(b\"Hello\", 10) # create a 10 byte buffer\n" +">>> print(sizeof(p), repr(p.raw))\n" +"10 b'Hello\\x00\\x00\\x00\\x00\\x00'\n" +">>> p.value = b\"Hi\"\n" +">>> print(sizeof(p), repr(p.raw))\n" +"10 b'Hi\\x00lo\\x00\\x00\\x00\\x00\\x00'\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:336 msgid "" "The :func:`create_string_buffer` function replaces the old :func:`!c_buffer` " @@ -504,6 +704,26 @@ msgid "" "from within *IDLE* or *PythonWin*::" msgstr "" +#: ../../library/ctypes.rst:351 +msgid "" +">>> printf = libc.printf\n" +">>> printf(b\"Hello, %s\\n\", b\"World!\")\n" +"Hello, World!\n" +"14\n" +">>> printf(b\"Hello, %S\\n\", \"World!\")\n" +"Hello, World!\n" +"14\n" +">>> printf(b\"%d bottles of beer\\n\", 42)\n" +"42 bottles of beer\n" +"19\n" +">>> printf(b\"%f bottles of beer\\n\", 42.5)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ctypes.ArgumentError: argument 2: TypeError: Don't know how to convert " +"parameter 2\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:367 msgid "" "As has been mentioned before, all Python types except integers, strings, and " @@ -511,9 +731,17 @@ msgid "" "so that they can be converted to the required C data type::" msgstr "" +#: ../../library/ctypes.rst:371 +msgid "" +">>> printf(b\"An int %d, a double %f\\n\", 1234, c_double(3.14))\n" +"An int 1234, a double 3.140000\n" +"31\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:379 msgid "Calling variadic functions" -msgstr "" +msgstr "Chamando funções variadas" #: ../../library/ctypes.rst:381 msgid "" @@ -526,14 +754,18 @@ msgstr "" #: ../../library/ctypes.rst:386 msgid "" -"On those platforms it is required to specify the :attr:`~_FuncPtr.argtypes` " +"On those platforms it is required to specify the :attr:`~_CFuncPtr.argtypes` " "attribute for the regular, non-variadic, function arguments:" msgstr "" +#: ../../library/ctypes.rst:389 +msgid "libc.printf.argtypes = [ctypes.c_char_p]" +msgstr "" + #: ../../library/ctypes.rst:393 msgid "" "Because specifying the attribute does not inhibit portability it is advised " -"to always specify :attr:`~_FuncPtr.argtypes` for all variadic functions." +"to always specify :attr:`~_CFuncPtr.argtypes` for all variadic functions." msgstr "" #: ../../library/ctypes.rst:400 @@ -549,6 +781,19 @@ msgid "" "or an object with an :attr:`!_as_parameter_` attribute::" msgstr "" +#: ../../library/ctypes.rst:408 +msgid "" +">>> class Bottles:\n" +"... def __init__(self, number):\n" +"... self._as_parameter_ = number\n" +"...\n" +">>> bottles = Bottles(42)\n" +">>> printf(b\"%d bottles of beer\\n\", bottles)\n" +"42 bottles of beer\n" +"19\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:418 msgid "" "If you don't want to store the instance's data in the :attr:`!" @@ -563,18 +808,27 @@ msgstr "" #: ../../library/ctypes.rst:428 msgid "" "It is possible to specify the required argument types of functions exported " -"from DLLs by setting the :attr:`~_FuncPtr.argtypes` attribute." +"from DLLs by setting the :attr:`~_CFuncPtr.argtypes` attribute." msgstr "" #: ../../library/ctypes.rst:431 msgid "" -":attr:`~_FuncPtr.argtypes` must be a sequence of C data types (the :func:`!" +":attr:`~_CFuncPtr.argtypes` must be a sequence of C data types (the :func:`!" "printf` function is probably not a good example here, because it takes a " "variable number and different types of parameters depending on the format " "string, on the other hand this is quite handy to experiment with this " "feature)::" msgstr "" +#: ../../library/ctypes.rst:436 +msgid "" +">>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]\n" +">>> printf(b\"String '%s', Int %d, Double %f\\n\", b\"Hi\", 10, 2.2)\n" +"String 'Hi', Int 10, Double 2.200000\n" +"37\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:442 msgid "" "Specifying a format protects against incompatible argument types (just as a " @@ -582,11 +836,24 @@ msgid "" "types::" msgstr "" +#: ../../library/ctypes.rst:445 +msgid "" +">>> printf(b\"%d %d %d\", 1, 2, 3)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ctypes.ArgumentError: argument 2: TypeError: 'int' object cannot be " +"interpreted as ctypes.c_char_p\n" +">>> printf(b\"%s %d %f\\n\", b\"X\", 2, 3)\n" +"X 2 3.000000\n" +"13\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:454 msgid "" "If you have defined your own classes which you pass to function calls, you " "have to implement a :meth:`~_CData.from_param` class method for them to be " -"able to use them in the :attr:`~_FuncPtr.argtypes` sequence. The :meth:" +"able to use them in the :attr:`~_CFuncPtr.argtypes` sequence. The :meth:" "`~_CData.from_param` class method receives the Python object passed to the " "function call, it should do a typecheck or whatever is needed to make sure " "this object is acceptable, and then return the object itself, its :attr:`!" @@ -603,7 +870,7 @@ msgstr "Tipos de Retorno" #: ../../library/ctypes.rst:478 msgid "" "By default functions are assumed to return the C :c:expr:`int` type. Other " -"return types can be specified by setting the :attr:`~_FuncPtr.restype` " +"return types can be specified by setting the :attr:`~_CFuncPtr.restype` " "attribute of the function object." msgstr "" @@ -614,8 +881,16 @@ msgid "" "expr:`int`, you should specify the :attr:`!restype` attribute::" msgstr "" +#: ../../library/ctypes.rst:486 +msgid ">>> libc.time.restype = c_time_t" +msgstr "" + #: ../../library/ctypes.rst:488 -msgid "The argument types can be specified using :attr:`~_FuncPtr.argtypes`::" +msgid "The argument types can be specified using :attr:`~_CFuncPtr.argtypes`::" +msgstr "" + +#: ../../library/ctypes.rst:490 +msgid ">>> libc.time.argtypes = (POINTER(c_time_t),)" msgstr "" #: ../../library/ctypes.rst:492 @@ -624,27 +899,83 @@ msgid "" "``None``::" msgstr "" +#: ../../library/ctypes.rst:494 +msgid "" +">>> print(libc.time(None))\n" +"1150640792" +msgstr "" + #: ../../library/ctypes.rst:497 msgid "" "Here is a more advanced example, it uses the :func:`!strchr` function, which " "expects a string pointer and a char, and returns a pointer to a string::" msgstr "" +#: ../../library/ctypes.rst:500 +msgid "" +">>> strchr = libc.strchr\n" +">>> strchr(b\"abcdef\", ord(\"d\"))\n" +"8059983\n" +">>> strchr.restype = c_char_p # c_char_p is a pointer to a string\n" +">>> strchr(b\"abcdef\", ord(\"d\"))\n" +"b'def'\n" +">>> print(strchr(b\"abcdef\", ord(\"x\")))\n" +"None\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:510 msgid "" "If you want to avoid the :func:`ord(\"x\") ` calls above, you can set " -"the :attr:`~_FuncPtr.argtypes` attribute, and the second argument will be " +"the :attr:`~_CFuncPtr.argtypes` attribute, and the second argument will be " "converted from a single character Python bytes object into a C char:" msgstr "" +#: ../../library/ctypes.rst:514 +msgid "" +">>> strchr.restype = c_char_p\n" +">>> strchr.argtypes = [c_char_p, c_char]\n" +">>> strchr(b\"abcdef\", b\"d\")\n" +"b'def'\n" +">>> strchr(b\"abcdef\", b\"def\")\n" +"Traceback (most recent call last):\n" +"ctypes.ArgumentError: argument 2: TypeError: one character bytes, bytearray " +"or integer expected\n" +">>> print(strchr(b\"abcdef\", b\"x\"))\n" +"None\n" +">>> strchr(b\"abcdef\", b\"d\")\n" +"b'def'\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:529 msgid "" "You can also use a callable Python object (a function or a class for " -"example) as the :attr:`~_FuncPtr.restype` attribute, if the foreign function " -"returns an integer. The callable will be called with the *integer* the C " -"function returns, and the result of this call will be used as the result of " -"your function call. This is useful to check for error return values and " -"automatically raise an exception::" +"example) as the :attr:`~_CFuncPtr.restype` attribute, if the foreign " +"function returns an integer. The callable will be called with the *integer* " +"the C function returns, and the result of this call will be used as the " +"result of your function call. This is useful to check for error return " +"values and automatically raise an exception::" +msgstr "" + +#: ../../library/ctypes.rst:535 +msgid "" +">>> GetModuleHandle = windll.kernel32.GetModuleHandleA\n" +">>> def ValidHandle(value):\n" +"... if value == 0:\n" +"... raise WinError()\n" +"... return value\n" +"...\n" +">>>\n" +">>> GetModuleHandle.restype = ValidHandle\n" +">>> GetModuleHandle(None)\n" +"486539264\n" +">>> GetModuleHandle(\"something silly\")\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" File \"\", line 3, in ValidHandle\n" +"OSError: [Errno 126] The specified module could not be found.\n" +">>>" msgstr "" #: ../../library/ctypes.rst:552 @@ -658,13 +989,13 @@ msgstr "" #: ../../library/ctypes.rst:557 msgid "" "Please note that a much more powerful error checking mechanism is available " -"through the :attr:`~_FuncPtr.errcheck` attribute; see the reference manual " +"through the :attr:`~_CFuncPtr.errcheck` attribute; see the reference manual " "for details." msgstr "" #: ../../library/ctypes.rst:565 msgid "Passing pointers (or: passing parameters by reference)" -msgstr "" +msgstr "Passando ponteiros (ou: passando parâmetros por referência)" #: ../../library/ctypes.rst:567 msgid "" @@ -683,9 +1014,24 @@ msgid "" "you don't need the pointer object in Python itself::" msgstr "" +#: ../../library/ctypes.rst:577 +msgid "" +">>> i = c_int()\n" +">>> f = c_float()\n" +">>> s = create_string_buffer(b'\\000' * 32)\n" +">>> print(i.value, f.value, repr(s.value))\n" +"0 0.0 b''\n" +">>> libc.sscanf(b\"1 3.14 Hello\", b\"%d %f %s\",\n" +"... byref(i), byref(f), s)\n" +"3\n" +">>> print(i.value, f.value, repr(s.value))\n" +"1 3.1400001049 b'Hello'\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:593 msgid "Structures and unions" -msgstr "" +msgstr "Estruturas e uniões" #: ../../library/ctypes.rst:595 msgid "" @@ -709,6 +1055,26 @@ msgid "" "constructor::" msgstr "" +#: ../../library/ctypes.rst:606 +msgid "" +">>> from ctypes import *\n" +">>> class POINT(Structure):\n" +"... _fields_ = [(\"x\", c_int),\n" +"... (\"y\", c_int)]\n" +"...\n" +">>> point = POINT(10, 20)\n" +">>> print(point.x, point.y)\n" +"10 20\n" +">>> point = POINT(y=5)\n" +">>> print(point.x, point.y)\n" +"0 5\n" +">>> POINT(1, 2, 3)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: too many initializers\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:623 msgid "" "You can, however, build much more complicated structures. A structure can " @@ -721,18 +1087,47 @@ msgid "" "*lowerright*::" msgstr "" +#: ../../library/ctypes.rst:629 +msgid "" +">>> class RECT(Structure):\n" +"... _fields_ = [(\"upperleft\", POINT),\n" +"... (\"lowerright\", POINT)]\n" +"...\n" +">>> rc = RECT(point)\n" +">>> print(rc.upperleft.x, rc.upperleft.y)\n" +"0 5\n" +">>> print(rc.lowerright.x, rc.lowerright.y)\n" +"0 0\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:640 msgid "" "Nested structures can also be initialized in the constructor in several " "ways::" msgstr "" +#: ../../library/ctypes.rst:642 +msgid "" +">>> r = RECT(POINT(1, 2), POINT(3, 4))\n" +">>> r = RECT((1, 2), (3, 4))" +msgstr "" + #: ../../library/ctypes.rst:645 msgid "" "Field :term:`descriptor`\\s can be retrieved from the *class*, they are " "useful for debugging because they can provide useful information::" msgstr "" +#: ../../library/ctypes.rst:648 +msgid "" +">>> print(POINT.x)\n" +"\n" +">>> print(POINT.y)\n" +"\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:659 msgid "" ":mod:`ctypes` does not support passing unions or structures with bit-fields " @@ -754,7 +1149,7 @@ msgid "" "the fields. This is what ``#pragma pack(n)`` also does in MSVC. It is also " "possible to set a minimum alignment for how the subclass itself is packed in " "the same way ``#pragma align(n)`` works in MSVC. This can be achieved by " -"specifying a ::attr:`~Structure._align_` class attribute in the subclass " +"specifying a :attr:`~Structure._align_` class attribute in the subclass " "definition." msgstr "" @@ -778,6 +1173,19 @@ msgid "" "the third item in the :attr:`~Structure._fields_` tuples::" msgstr "" +#: ../../library/ctypes.rst:693 +msgid "" +">>> class Int(Structure):\n" +"... _fields_ = [(\"first_16\", c_int, 16),\n" +"... (\"second_16\", c_int, 16)]\n" +"...\n" +">>> print(Int.first_16)\n" +"\n" +">>> print(Int.second_16)\n" +"\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:707 msgid "Arrays" msgstr "Arrays" @@ -794,16 +1202,43 @@ msgid "" "a positive integer::" msgstr "" +#: ../../library/ctypes.rst:714 +msgid "TenPointsArrayType = POINT * 10" +msgstr "" + #: ../../library/ctypes.rst:716 msgid "" "Here is an example of a somewhat artificial data type, a structure " "containing 4 POINTs among other stuff::" msgstr "" +#: ../../library/ctypes.rst:719 +msgid "" +">>> from ctypes import *\n" +">>> class POINT(Structure):\n" +"... _fields_ = (\"x\", c_int), (\"y\", c_int)\n" +"...\n" +">>> class MyStruct(Structure):\n" +"... _fields_ = [(\"a\", c_int),\n" +"... (\"b\", c_float),\n" +"... (\"point_array\", POINT * 4)]\n" +">>>\n" +">>> print(len(MyStruct().point_array))\n" +"4\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:732 msgid "Instances are created in the usual way, by calling the class::" msgstr "" +#: ../../library/ctypes.rst:734 +msgid "" +"arr = TenPointsArrayType()\n" +"for pt in arr:\n" +" print(pt.x, pt.y)" +msgstr "" + #: ../../library/ctypes.rst:738 msgid "" "The above code print a series of ``0 0`` lines, because the array contents " @@ -814,6 +1249,19 @@ msgstr "" msgid "Initializers of the correct type can also be specified::" msgstr "" +#: ../../library/ctypes.rst:743 +msgid "" +">>> from ctypes import *\n" +">>> TenIntegers = c_int * 10\n" +">>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n" +">>> print(ii)\n" +"\n" +">>> for i in ii: print(i, end=\" \")\n" +"...\n" +"1 2 3 4 5 6 7 8 9 10\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:757 msgid "Pointers" msgstr "Ponteiros" @@ -824,18 +1272,42 @@ msgid "" "mod:`ctypes` type::" msgstr "" +#: ../../library/ctypes.rst:762 +msgid "" +">>> from ctypes import *\n" +">>> i = c_int(42)\n" +">>> pi = pointer(i)\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:767 msgid "" "Pointer instances have a :attr:`~_Pointer.contents` attribute which returns " "the object to which the pointer points, the ``i`` object above::" msgstr "" +#: ../../library/ctypes.rst:770 +msgid "" +">>> pi.contents\n" +"c_long(42)\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:774 msgid "" "Note that :mod:`ctypes` does not have OOR (original object return), it " "constructs a new, equivalent object each time you retrieve an attribute::" msgstr "" +#: ../../library/ctypes.rst:777 +msgid "" +">>> pi.contents is i\n" +"False\n" +">>> pi.contents is pi.contents\n" +"False\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:783 msgid "" "Assigning another :class:`c_int` instance to the pointer's contents " @@ -843,14 +1315,40 @@ msgid "" "is stored::" msgstr "" +#: ../../library/ctypes.rst:786 +msgid "" +">>> i = c_int(99)\n" +">>> pi.contents = i\n" +">>> pi.contents\n" +"c_long(99)\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:795 msgid "Pointer instances can also be indexed with integers::" msgstr "" +#: ../../library/ctypes.rst:797 +msgid "" +">>> pi[0]\n" +"99\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:801 msgid "Assigning to an integer index changes the pointed to value::" msgstr "" +#: ../../library/ctypes.rst:803 +msgid "" +">>> print(i)\n" +"c_long(99)\n" +">>> pi[0] = 22\n" +">>> print(i)\n" +"c_long(22)\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:810 msgid "" "It is also possible to use indexes different from 0, but you must know what " @@ -868,18 +1366,55 @@ msgid "" "returns a new type::" msgstr "" +#: ../../library/ctypes.rst:821 +msgid "" +">>> PI = POINTER(c_int)\n" +">>> PI\n" +"\n" +">>> PI(42)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: expected c_long instead of int\n" +">>> PI(c_int(42))\n" +"\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:832 msgid "" "Calling the pointer type without an argument creates a ``NULL`` pointer. " "``NULL`` pointers have a ``False`` boolean value::" msgstr "" +#: ../../library/ctypes.rst:835 +msgid "" +">>> null_ptr = POINTER(c_int)()\n" +">>> print(bool(null_ptr))\n" +"False\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:840 msgid "" ":mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but " "dereferencing invalid non-\\ ``NULL`` pointers would crash Python)::" msgstr "" +#: ../../library/ctypes.rst:843 +msgid "" +">>> null_ptr[0]\n" +"Traceback (most recent call last):\n" +" ....\n" +"ValueError: NULL pointer access\n" +">>>\n" +"\n" +">>> null_ptr[0] = 1234\n" +"Traceback (most recent call last):\n" +" ....\n" +"ValueError: NULL pointer access\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:859 msgid "Type conversions" msgstr "Conversão de Tipos" @@ -887,7 +1422,7 @@ msgstr "Conversão de Tipos" #: ../../library/ctypes.rst:861 msgid "" "Usually, ctypes does strict type checking. This means, if you have " -"``POINTER(c_int)`` in the :attr:`~_FuncPtr.argtypes` list of a function or " +"``POINTER(c_int)`` in the :attr:`~_CFuncPtr.argtypes` list of a function or " "as the type of a member field in a structure definition, only instances of " "exactly the same type are accepted. There are some exceptions to this rule, " "where ctypes accepts other objects. For example, you can pass compatible " @@ -895,10 +1430,27 @@ msgid "" "ctypes accepts an array of c_int::" msgstr "" +#: ../../library/ctypes.rst:868 +msgid "" +">>> class Bar(Structure):\n" +"... _fields_ = [(\"count\", c_int), (\"values\", POINTER(c_int))]\n" +"...\n" +">>> bar = Bar()\n" +">>> bar.values = (c_int * 3)(1, 2, 3)\n" +">>> bar.count = 3\n" +">>> for i in range(bar.count):\n" +"... print(bar.values[i])\n" +"...\n" +"1\n" +"2\n" +"3\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:882 msgid "" "In addition, if a function argument is explicitly declared to be a pointer " -"type (such as ``POINTER(c_int)``) in :attr:`~_FuncPtr.argtypes`, an object " +"type (such as ``POINTER(c_int)``) in :attr:`~_CFuncPtr.argtypes`, an object " "of the pointed type (``c_int`` in this case) can be passed to the function. " "ctypes will apply the required :func:`byref` conversion in this case " "automatically." @@ -908,6 +1460,12 @@ msgstr "" msgid "To set a POINTER type field to ``NULL``, you can assign ``None``::" msgstr "" +#: ../../library/ctypes.rst:889 +msgid "" +">>> bar.values = None\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:894 msgid "" "Sometimes you have instances of incompatible types. In C, you can cast one " @@ -917,6 +1475,16 @@ msgid "" "``values`` field, but not instances of other types::" msgstr "" +#: ../../library/ctypes.rst:900 +msgid "" +">>> bar.values = (c_byte * 4)()\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long " +"instance\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:906 msgid "For these cases, the :func:`cast` function is handy." msgstr "" @@ -930,12 +1498,29 @@ msgid "" "references the same memory block as the first argument::" msgstr "" +#: ../../library/ctypes.rst:914 +msgid "" +">>> a = (c_byte * 4)()\n" +">>> cast(a, POINTER(c_int))\n" +"\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:919 msgid "" "So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` " "the structure::" msgstr "" +#: ../../library/ctypes.rst:922 +msgid "" +">>> bar = Bar()\n" +">>> bar.values = cast((c_byte * 4)(), POINTER(c_int))\n" +">>> print(bar.values[0])\n" +"0\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:932 msgid "Incomplete Types" msgstr "Tipos Incompletos" @@ -947,12 +1532,35 @@ msgid "" "defined later::" msgstr "" +#: ../../library/ctypes.rst:938 +msgid "" +"struct cell; /* forward declaration */\n" +"\n" +"struct cell {\n" +" char *name;\n" +" struct cell *next;\n" +"};" +msgstr "" + #: ../../library/ctypes.rst:945 msgid "" "The straightforward translation into ctypes code would be this, but it does " "not work::" msgstr "" +#: ../../library/ctypes.rst:948 +msgid "" +">>> class cell(Structure):\n" +"... _fields_ = [(\"name\", c_char_p),\n" +"... (\"next\", POINTER(cell))]\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" File \"\", line 2, in cell\n" +"NameError: name 'cell' is not defined\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:958 msgid "" "because the new ``class cell`` is not available in the class statement " @@ -960,12 +1568,40 @@ msgid "" "`~Structure._fields_` attribute later, after the class statement::" msgstr "" +#: ../../library/ctypes.rst:962 +msgid "" +">>> from ctypes import *\n" +">>> class cell(Structure):\n" +"... pass\n" +"...\n" +">>> cell._fields_ = [(\"name\", c_char_p),\n" +"... (\"next\", POINTER(cell))]\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:970 msgid "" "Let's try it. We create two instances of ``cell``, and let them point to " "each other, and finally follow the pointer chain a few times::" msgstr "" +#: ../../library/ctypes.rst:973 +msgid "" +">>> c1 = cell()\n" +">>> c1.name = b\"foo\"\n" +">>> c2 = cell()\n" +">>> c2.name = b\"bar\"\n" +">>> c1.next = pointer(c2)\n" +">>> c2.next = pointer(c1)\n" +">>> p = c1\n" +">>> for i in range(8):\n" +"... print(p.name, end=\" \")\n" +"... p = p.next[0]\n" +"...\n" +"foo bar foo bar foo bar foo bar\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:991 msgid "Callback functions" msgstr "Funções Callbacks" @@ -1005,6 +1641,15 @@ msgid "" "function. :c:func:`!qsort` will be used to sort an array of integers::" msgstr "" +#: ../../library/ctypes.rst:1013 +msgid "" +">>> IntArray5 = c_int * 5\n" +">>> ia = IntArray5(5, 1, 7, 33, 99)\n" +">>> qsort = libc.qsort\n" +">>> qsort.restype = None\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:1019 msgid "" ":func:`!qsort` must be called with a pointer to the data to sort, the number " @@ -1021,30 +1666,97 @@ msgid "" "integer. First we create the ``type`` for the callback function::" msgstr "" +#: ../../library/ctypes.rst:1028 +msgid "" +">>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:1031 msgid "" "To get started, here is a simple callback that shows the values it gets " "passed::" msgstr "" +#: ../../library/ctypes.rst:1034 +msgid "" +">>> def py_cmp_func(a, b):\n" +"... print(\"py_cmp_func\", a[0], b[0])\n" +"... return 0\n" +"...\n" +">>> cmp_func = CMPFUNC(py_cmp_func)\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:1041 msgid "The result::" msgstr "O resultado::" +#: ../../library/ctypes.rst:1043 +msgid "" +">>> qsort(ia, len(ia), sizeof(c_int), cmp_func)\n" +"py_cmp_func 5 1\n" +"py_cmp_func 33 99\n" +"py_cmp_func 7 33\n" +"py_cmp_func 5 7\n" +"py_cmp_func 1 7\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:1051 msgid "Now we can actually compare the two items and return a useful result::" msgstr "" +#: ../../library/ctypes.rst:1053 +msgid "" +">>> def py_cmp_func(a, b):\n" +"... print(\"py_cmp_func\", a[0], b[0])\n" +"... return a[0] - b[0]\n" +"...\n" +">>>\n" +">>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func))\n" +"py_cmp_func 5 1\n" +"py_cmp_func 33 99\n" +"py_cmp_func 7 33\n" +"py_cmp_func 1 7\n" +"py_cmp_func 5 7\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:1066 msgid "As we can easily check, our array is sorted now::" msgstr "" +#: ../../library/ctypes.rst:1068 +msgid "" +">>> for i in ia: print(i, end=\" \")\n" +"...\n" +"1 5 7 33 99\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:1073 msgid "" "The function factories can be used as decorator factories, so we may as well " "write::" msgstr "" +#: ../../library/ctypes.rst:1076 +msgid "" +">>> @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))\n" +"... def py_cmp_func(a, b):\n" +"... print(\"py_cmp_func\", a[0], b[0])\n" +"... return a[0] - b[0]\n" +"...\n" +">>> qsort(ia, len(ia), sizeof(c_int), py_cmp_func)\n" +"py_cmp_func 5 1\n" +"py_cmp_func 33 99\n" +"py_cmp_func 7 33\n" +"py_cmp_func 1 7\n" +"py_cmp_func 5 7\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:1091 msgid "" "Make sure you keep references to :func:`CFUNCTYPE` objects as long as they " @@ -1080,6 +1792,13 @@ msgid "" "to the Python C api::" msgstr "" +#: ../../library/ctypes.rst:1115 +msgid "" +">>> version = ctypes.c_int.in_dll(ctypes.pythonapi, \"Py_Version\")\n" +">>> print(hex(version.value))\n" +"0x30c00a0" +msgstr "" + #: ../../library/ctypes.rst:1119 msgid "" "An extended example which also demonstrates the use of pointers accesses " @@ -1110,12 +1829,33 @@ msgid "" "example size, we show only how this table can be read with :mod:`ctypes`::" msgstr "" +#: ../../library/ctypes.rst:1132 +msgid "" +">>> from ctypes import *\n" +">>>\n" +">>> class struct_frozen(Structure):\n" +"... _fields_ = [(\"name\", c_char_p),\n" +"... (\"code\", POINTER(c_ubyte)),\n" +"... (\"size\", c_int),\n" +"... (\"get_code\", POINTER(c_ubyte)), # Function pointer\n" +"... ]\n" +"...\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:1143 msgid "" "We have defined the :c:struct:`_frozen` data type, so we can get the pointer " "to the table::" msgstr "" +#: ../../library/ctypes.rst:1146 +msgid "" +">>> FrozenTable = POINTER(struct_frozen)\n" +">>> table = FrozenTable.in_dll(pythonapi, \"_PyImport_FrozenBootstrap\")\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:1150 msgid "" "Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, " @@ -1125,6 +1865,19 @@ msgid "" "the loop when we hit the ``NULL`` entry::" msgstr "" +#: ../../library/ctypes.rst:1156 +msgid "" +">>> for item in table:\n" +"... if item.name is None:\n" +"... break\n" +"... print(item.name.decode(\"ascii\"), item.size)\n" +"...\n" +"_frozen_importlib 31764\n" +"_frozen_importlib_external 41499\n" +"zipimport 12345\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:1166 msgid "" "The fact that standard Python has a frozen module and a frozen package " @@ -1146,12 +1899,41 @@ msgstr "" msgid "Consider the following example::" msgstr "" +#: ../../library/ctypes.rst:1181 +msgid "" +">>> from ctypes import *\n" +">>> class POINT(Structure):\n" +"... _fields_ = (\"x\", c_int), (\"y\", c_int)\n" +"...\n" +">>> class RECT(Structure):\n" +"... _fields_ = (\"a\", POINT), (\"b\", POINT)\n" +"...\n" +">>> p1 = POINT(1, 2)\n" +">>> p2 = POINT(3, 4)\n" +">>> rc = RECT(p1, p2)\n" +">>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)\n" +"1 2 3 4\n" +">>> # now swap the two points\n" +">>> rc.a, rc.b = rc.b, rc.a\n" +">>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)\n" +"3 4 3 4\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:1199 msgid "" "Hm. We certainly expected the last statement to print ``3 4 1 2``. What " "happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::" msgstr "" +#: ../../library/ctypes.rst:1202 +msgid "" +">>> temp0, temp1 = rc.b, rc.a\n" +">>> rc.a = temp0\n" +">>> rc.b = temp1\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:1207 msgid "" "Note that ``temp0`` and ``temp1`` are objects still using the internal " @@ -1174,6 +1956,17 @@ msgid "" "this::" msgstr "" +#: ../../library/ctypes.rst:1219 +msgid "" +">>> s = c_char_p()\n" +">>> s.value = b\"abc def ghi\"\n" +">>> s.value\n" +"b'abc def ghi'\n" +">>> s.value is s.value\n" +"False\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:1229 msgid "" "Objects instantiated from :class:`c_char_p` can only have their value set to " @@ -1207,6 +2000,23 @@ msgid "" "objects type, a :exc:`ValueError` is raised if this is tried::" msgstr "" +#: ../../library/ctypes.rst:1252 +msgid "" +">>> short_array = (c_short * 4)()\n" +">>> print(sizeof(short_array))\n" +"8\n" +">>> resize(short_array, 4)\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: minimum size is 8\n" +">>> resize(short_array, 32)\n" +">>> sizeof(short_array)\n" +"32\n" +">>> sizeof(type(short_array))\n" +"8\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:1266 msgid "" "This is nice and fine, but how would one access the additional elements " @@ -1214,6 +2024,17 @@ msgid "" "we get errors accessing other elements::" msgstr "" +#: ../../library/ctypes.rst:1270 +msgid "" +">>> short_array[:]\n" +"[0, 0, 0, 0]\n" +">>> short_array[7]\n" +"Traceback (most recent call last):\n" +" ...\n" +"IndexError: invalid index\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:1278 msgid "" "Another way to use variable-sized data types with :mod:`ctypes` is to use " @@ -1258,7 +2079,7 @@ msgid "" "If no library can be found, returns ``None``." msgstr "" -#: ../../library/ctypes.rst:1316 ../../library/ctypes.rst:1977 +#: ../../library/ctypes.rst:1316 ../../library/ctypes.rst:2002 msgid "The exact functionality is system dependent." msgstr "" @@ -1278,7 +2099,19 @@ msgstr "" #: ../../library/ctypes.rst:1326 msgid "Here are some examples::" -msgstr "Aqui estão alguns exemplos::" +msgstr "Veja alguns exemplos::" + +#: ../../library/ctypes.rst:1328 +msgid "" +">>> from ctypes.util import find_library\n" +">>> find_library(\"m\")\n" +"'libm.so.6'\n" +">>> find_library(\"c\")\n" +"'libc.so.6'\n" +">>> find_library(\"bz2\")\n" +"'libbz2.so.1.0'\n" +">>>" +msgstr "" #: ../../library/ctypes.rst:1337 msgid "" @@ -1287,6 +2120,20 @@ msgid "" "pathname if successful::" msgstr "" +#: ../../library/ctypes.rst:1341 +msgid "" +">>> from ctypes.util import find_library\n" +">>> find_library(\"c\")\n" +"'/usr/lib/libc.dylib'\n" +">>> find_library(\"m\")\n" +"'/usr/lib/libm.dylib'\n" +">>> find_library(\"bz2\")\n" +"'/usr/lib/libbz2.dylib'\n" +">>> find_library(\"AGL\")\n" +"'/System/Library/Frameworks/AGL.framework/AGL'\n" +">>>" +msgstr "" + #: ../../library/ctypes.rst:1352 msgid "" "On Windows, :func:`~ctypes.util.find_library` searches along the system " @@ -1332,8 +2179,8 @@ msgid "" "determine which one is not found using Windows debugging and tracing tools." msgstr "" -#: ../../library/ctypes.rst:1388 ../../library/ctypes.rst:1411 -#: ../../library/ctypes.rst:1422 ../../library/ctypes.rst:1439 +#: ../../library/ctypes.rst:1388 ../../library/ctypes.rst:1413 +#: ../../library/ctypes.rst:1426 ../../library/ctypes.rst:1444 msgid "The *name* parameter can now be a :term:`path-like object`." msgstr "" @@ -1345,34 +2192,44 @@ msgstr "" #: ../../library/ctypes.rst:1398 msgid "" -"Windows only: Instances of this class represent loaded shared libraries, " -"functions in these libraries use the ``stdcall`` calling convention, and are " -"assumed to return the windows specific :class:`HRESULT` code. :class:" -"`HRESULT` values contain information specifying whether the function call " -"failed or succeeded, together with additional error code. If the return " -"value signals a failure, an :class:`OSError` is automatically raised." +"Instances of this class represent loaded shared libraries, functions in " +"these libraries use the ``stdcall`` calling convention, and are assumed to " +"return the windows specific :class:`HRESULT` code. :class:`HRESULT` values " +"contain information specifying whether the function call failed or " +"succeeded, together with additional error code. If the return value signals " +"a failure, an :class:`OSError` is automatically raised." msgstr "" -#: ../../library/ctypes.rst:1405 +#: ../../library/ctypes.rst:1405 ../../library/ctypes.rst:1422 +#: ../../library/ctypes.rst:1566 ../../library/ctypes.rst:1574 +#: ../../library/ctypes.rst:1751 ../../library/ctypes.rst:1982 +#: ../../library/ctypes.rst:1991 ../../library/ctypes.rst:2016 +#: ../../library/ctypes.rst:2025 ../../library/ctypes.rst:2034 +#: ../../library/ctypes.rst:2049 ../../library/ctypes.rst:2106 +#: ../../library/ctypes.rst:2134 ../../library/ctypes.rst:2478 +msgid "Availability" +msgstr "Disponibilidade" + +#: ../../library/ctypes.rst:1407 msgid "" ":exc:`WindowsError` used to be raised, which is now an alias of :exc:" "`OSError`." msgstr "" -#: ../../library/ctypes.rst:1416 +#: ../../library/ctypes.rst:1418 msgid "" -"Windows only: Instances of this class represent loaded shared libraries, " -"functions in these libraries use the ``stdcall`` calling convention, and are " -"assumed to return :c:expr:`int` by default." +"Instances of this class represent loaded shared libraries, functions in " +"these libraries use the ``stdcall`` calling convention, and are assumed to " +"return :c:expr:`int` by default." msgstr "" -#: ../../library/ctypes.rst:1424 +#: ../../library/ctypes.rst:1429 msgid "" "The Python :term:`global interpreter lock` is released before calling any " "function exported by these libraries, and reacquired afterwards." msgstr "" -#: ../../library/ctypes.rst:1430 +#: ../../library/ctypes.rst:1435 msgid "" "Instances of this class behave like :class:`CDLL` instances, except that the " "Python GIL is *not* released during the function call, and after the " @@ -1380,11 +2237,11 @@ msgid "" "set, a Python exception is raised." msgstr "" -#: ../../library/ctypes.rst:1435 +#: ../../library/ctypes.rst:1440 msgid "Thus, this is only useful to call Python C api functions directly." msgstr "" -#: ../../library/ctypes.rst:1441 +#: ../../library/ctypes.rst:1446 msgid "" "All these classes can be instantiated by calling them with at least one " "argument, the pathname of the shared library. If you have an existing " @@ -1394,7 +2251,7 @@ msgid "" "the process, and to get a handle to it." msgstr "" -#: ../../library/ctypes.rst:1448 +#: ../../library/ctypes.rst:1453 msgid "" "The *mode* parameter can be used to specify how the library is loaded. For " "details, consult the :manpage:`dlopen(3)` manpage. On Windows, *mode* is " @@ -1402,7 +2259,7 @@ msgid "" "configurable." msgstr "" -#: ../../library/ctypes.rst:1453 +#: ../../library/ctypes.rst:1458 msgid "" "The *use_errno* parameter, when set to true, enables a ctypes mechanism that " "allows accessing the system :data:`errno` error number in a safe way. :mod:" @@ -1412,14 +2269,14 @@ msgid "" "private copy, the same happens immediately after the function call." msgstr "" -#: ../../library/ctypes.rst:1460 +#: ../../library/ctypes.rst:1465 msgid "" "The function :func:`ctypes.get_errno` returns the value of the ctypes " "private copy, and the function :func:`ctypes.set_errno` changes the ctypes " "private copy to a new value and returns the former value." msgstr "" -#: ../../library/ctypes.rst:1464 +#: ../../library/ctypes.rst:1469 msgid "" "The *use_last_error* parameter, when set to true, enables the same mechanism " "for the Windows error code which is managed by the :func:`GetLastError` and :" @@ -1428,7 +2285,7 @@ msgid "" "private copy of the windows error code." msgstr "" -#: ../../library/ctypes.rst:1470 +#: ../../library/ctypes.rst:1475 msgid "" "The *winmode* parameter is used on Windows to specify how the library is " "loaded (since *mode* is ignored). It takes any value that is valid for the " @@ -1438,29 +2295,29 @@ msgid "" "ensure the correct library and dependencies are loaded." msgstr "" -#: ../../library/ctypes.rst:1477 +#: ../../library/ctypes.rst:1482 msgid "Added *winmode* parameter." msgstr "" -#: ../../library/ctypes.rst:1484 +#: ../../library/ctypes.rst:1489 msgid "" "Flag to use as *mode* parameter. On platforms where this flag is not " "available, it is defined as the integer zero." msgstr "" -#: ../../library/ctypes.rst:1491 +#: ../../library/ctypes.rst:1496 msgid "" "Flag to use as *mode* parameter. On platforms where this is not available, " "it is the same as *RTLD_GLOBAL*." msgstr "" -#: ../../library/ctypes.rst:1498 +#: ../../library/ctypes.rst:1503 msgid "" "The default mode which is used to load shared libraries. On OSX 10.3, this " "is *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*." msgstr "" -#: ../../library/ctypes.rst:1501 +#: ../../library/ctypes.rst:1506 msgid "" "Instances of these classes have no public methods. Functions exported by " "the shared library can be accessed as attributes or by index. Please note " @@ -1469,21 +2326,31 @@ msgid "" "other hand, accessing it through an index returns a new object each time::" msgstr "" -#: ../../library/ctypes.rst:1514 +#: ../../library/ctypes.rst:1512 +msgid "" +">>> from ctypes import CDLL\n" +">>> libc = CDLL(\"libc.so.6\") # On Linux\n" +">>> libc.time == libc.time\n" +"True\n" +">>> libc['time'] == libc['time']\n" +"False" +msgstr "" + +#: ../../library/ctypes.rst:1519 msgid "" "The following public attributes are available, their name starts with an " "underscore to not clash with exported function names:" msgstr "" -#: ../../library/ctypes.rst:1520 +#: ../../library/ctypes.rst:1525 msgid "The system handle used to access the library." msgstr "" -#: ../../library/ctypes.rst:1525 +#: ../../library/ctypes.rst:1530 msgid "The name of the library passed in the constructor." msgstr "" -#: ../../library/ctypes.rst:1527 +#: ../../library/ctypes.rst:1532 msgid "" "Shared libraries can also be loaded by using one of the prefabricated " "objects, which are instances of the :class:`LibraryLoader` class, either by " @@ -1491,13 +2358,13 @@ msgid "" "library as attribute of the loader instance." msgstr "" -#: ../../library/ctypes.rst:1535 +#: ../../library/ctypes.rst:1540 msgid "" "Class which loads shared libraries. *dlltype* should be one of the :class:" "`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types." msgstr "" -#: ../../library/ctypes.rst:1538 +#: ../../library/ctypes.rst:1543 msgid "" ":meth:`!__getattr__` has special behavior: It allows loading a shared " "library by accessing it as attribute of a library loader instance. The " @@ -1505,39 +2372,39 @@ msgid "" "each time." msgstr "" -#: ../../library/ctypes.rst:1544 +#: ../../library/ctypes.rst:1549 msgid "" "Load a shared library into the process and return it. This method always " "returns a new instance of the library." msgstr "" -#: ../../library/ctypes.rst:1548 +#: ../../library/ctypes.rst:1553 msgid "These prefabricated library loaders are available:" msgstr "" -#: ../../library/ctypes.rst:1553 +#: ../../library/ctypes.rst:1558 msgid "Creates :class:`CDLL` instances." msgstr "" -#: ../../library/ctypes.rst:1559 -msgid "Windows only: Creates :class:`WinDLL` instances." +#: ../../library/ctypes.rst:1564 +msgid "Creates :class:`WinDLL` instances." msgstr "" -#: ../../library/ctypes.rst:1565 -msgid "Windows only: Creates :class:`OleDLL` instances." +#: ../../library/ctypes.rst:1572 +msgid "Creates :class:`OleDLL` instances." msgstr "" -#: ../../library/ctypes.rst:1571 +#: ../../library/ctypes.rst:1580 msgid "Creates :class:`PyDLL` instances." msgstr "" -#: ../../library/ctypes.rst:1574 +#: ../../library/ctypes.rst:1583 msgid "" "For accessing the C Python api directly, a ready-to-use Python shared " "library object is available:" msgstr "" -#: ../../library/ctypes.rst:1580 +#: ../../library/ctypes.rst:1589 msgid "" "An instance of :class:`PyDLL` that exposes Python C API functions as " "attributes. Note that all these functions are assumed to return C :c:expr:" @@ -1545,7 +2412,7 @@ msgid "" "correct :attr:`!restype` attribute to use these functions." msgstr "" -#: ../../library/ctypes.rst:1585 ../../library/ctypes.rst:1587 +#: ../../library/ctypes.rst:1594 ../../library/ctypes.rst:1596 msgid "" "Loading a library through any of these objects raises an :ref:`auditing " "event ` ``ctypes.dlopen`` with string argument ``name``, the name " @@ -1555,56 +2422,72 @@ msgstr "" "ref:`evento de auditoria ` ``ctypes.dlopen`` com o argumento " "string ``name``, o nome usado para carregar a biblioteca." -#: ../../library/ctypes.rst:1591 ../../library/ctypes.rst:1593 +#: ../../library/ctypes.rst:1600 ../../library/ctypes.rst:1602 msgid "" "Accessing a function on a loaded library raises an auditing event ``ctypes." "dlsym`` with arguments ``library`` (the library object) and ``name`` (the " "symbol's name as a string or integer)." msgstr "" -#: ../../library/ctypes.rst:1597 ../../library/ctypes.rst:1599 +#: ../../library/ctypes.rst:1606 ../../library/ctypes.rst:1608 msgid "" "In cases when only the library handle is available rather than the object, " "accessing a function raises an auditing event ``ctypes.dlsym/handle`` with " "arguments ``handle`` (the raw library handle) and ``name``." msgstr "" -#: ../../library/ctypes.rst:1606 +#: ../../library/ctypes.rst:1615 msgid "Foreign functions" msgstr "" -#: ../../library/ctypes.rst:1608 +#: ../../library/ctypes.rst:1617 msgid "" "As explained in the previous section, foreign functions can be accessed as " "attributes of loaded shared libraries. The function objects created in this " "way by default accept any number of arguments, accept any ctypes data " "instances as arguments, and return the default result type specified by the " -"library loader. They are instances of a private class:" +"library loader." msgstr "" -#: ../../library/ctypes.rst:1617 +#: ../../library/ctypes.rst:1622 +msgid "" +"They are instances of a private local class :class:`!_FuncPtr` (not exposed " +"in :mod:`!ctypes`) which inherits from the private :class:`_CFuncPtr` class:" +msgstr "" + +#: ../../library/ctypes.rst:1625 +msgid "" +">>> import ctypes\n" +">>> lib = ctypes.CDLL(None)\n" +">>> issubclass(lib._FuncPtr, ctypes._CFuncPtr)\n" +"True\n" +">>> lib._FuncPtr is ctypes._CFuncPtr\n" +"False" +msgstr "" + +#: ../../library/ctypes.rst:1636 msgid "Base class for C callable foreign functions." msgstr "" -#: ../../library/ctypes.rst:1619 +#: ../../library/ctypes.rst:1638 msgid "" "Instances of foreign functions are also C compatible data types; they " "represent C function pointers." msgstr "" -#: ../../library/ctypes.rst:1622 +#: ../../library/ctypes.rst:1641 msgid "" "This behavior can be customized by assigning to special attributes of the " "foreign function object." msgstr "" -#: ../../library/ctypes.rst:1627 +#: ../../library/ctypes.rst:1646 msgid "" "Assign a ctypes type to specify the result type of the foreign function. Use " "``None`` for :c:expr:`void`, a function not returning anything." msgstr "" -#: ../../library/ctypes.rst:1630 +#: ../../library/ctypes.rst:1649 msgid "" "It is possible to assign a callable Python object that is not a ctypes type, " "in this case the function is assumed to return a C :c:expr:`int`, and the " @@ -1614,7 +2497,7 @@ msgid "" "callable to the :attr:`errcheck` attribute." msgstr "" -#: ../../library/ctypes.rst:1639 +#: ../../library/ctypes.rst:1658 msgid "" "Assign a tuple of ctypes types to specify the argument types that the " "function accepts. Functions using the ``stdcall`` calling convention can " @@ -1623,7 +2506,7 @@ msgid "" "unspecified arguments as well." msgstr "" -#: ../../library/ctypes.rst:1645 +#: ../../library/ctypes.rst:1664 msgid "" "When a foreign function is called, each actual argument is passed to the :" "meth:`~_CData.from_param` class method of the items in the :attr:`argtypes` " @@ -1633,7 +2516,7 @@ msgid "" "object using ctypes conversion rules." msgstr "" -#: ../../library/ctypes.rst:1652 +#: ../../library/ctypes.rst:1671 msgid "" "New: It is now possible to put items in argtypes which are not ctypes types, " "but each item must have a :meth:`~_CData.from_param` method which returns a " @@ -1641,44 +2524,44 @@ msgid "" "defining adapters that can adapt custom objects as function parameters." msgstr "" -#: ../../library/ctypes.rst:1659 +#: ../../library/ctypes.rst:1678 msgid "" "Assign a Python function or another callable to this attribute. The callable " "will be called with three or more arguments:" msgstr "" -#: ../../library/ctypes.rst:1666 +#: ../../library/ctypes.rst:1685 msgid "" "*result* is what the foreign function returns, as specified by the :attr:`!" "restype` attribute." msgstr "" -#: ../../library/ctypes.rst:1669 +#: ../../library/ctypes.rst:1688 msgid "" "*func* is the foreign function object itself, this allows reusing the same " "callable object to check or post process the results of several functions." msgstr "" -#: ../../library/ctypes.rst:1673 +#: ../../library/ctypes.rst:1692 msgid "" "*arguments* is a tuple containing the parameters originally passed to the " "function call, this allows specializing the behavior on the arguments used." msgstr "" -#: ../../library/ctypes.rst:1677 +#: ../../library/ctypes.rst:1696 msgid "" "The object that this function returns will be returned from the foreign " "function call, but it can also check the result value and raise an exception " "if the foreign function call failed." msgstr "" -#: ../../library/ctypes.rst:1684 +#: ../../library/ctypes.rst:1703 msgid "" "This exception is raised when a foreign function call cannot convert one of " "the passed arguments." msgstr "" -#: ../../library/ctypes.rst:1688 ../../library/ctypes.rst:1690 +#: ../../library/ctypes.rst:1707 ../../library/ctypes.rst:1709 msgid "" "On Windows, when a foreign function call raises a system exception (for " "example, due to an access violation), it will be captured and replaced with " @@ -1687,18 +2570,18 @@ msgid "" "hook to replace the exception with its own." msgstr "" -#: ../../library/ctypes.rst:1696 ../../library/ctypes.rst:1698 +#: ../../library/ctypes.rst:1715 ../../library/ctypes.rst:1717 msgid "" "Some ways to invoke foreign function calls may raise an auditing event " "``ctypes.call_function`` with arguments ``function pointer`` and " "``arguments``." msgstr "" -#: ../../library/ctypes.rst:1704 +#: ../../library/ctypes.rst:1723 msgid "Function prototypes" msgstr "" -#: ../../library/ctypes.rst:1706 +#: ../../library/ctypes.rst:1725 msgid "" "Foreign functions can also be created by instantiating function prototypes. " "Function prototypes are similar to function prototypes in C; they describe a " @@ -1709,7 +2592,7 @@ msgid "" "``@wrapper`` syntax. See :ref:`ctypes-callback-functions` for examples." msgstr "" -#: ../../library/ctypes.rst:1717 +#: ../../library/ctypes.rst:1736 msgid "" "The returned function prototype creates functions that use the standard C " "calling convention. The function will release the GIL during the call. If " @@ -1718,37 +2601,37 @@ msgid "" "after the call; *use_last_error* does the same for the Windows error code." msgstr "" -#: ../../library/ctypes.rst:1727 +#: ../../library/ctypes.rst:1746 msgid "" -"Windows only: The returned function prototype creates functions that use the " -"``stdcall`` calling convention. The function will release the GIL during " -"the call. *use_errno* and *use_last_error* have the same meaning as above." +"The returned function prototype creates functions that use the ``stdcall`` " +"calling convention. The function will release the GIL during the call. " +"*use_errno* and *use_last_error* have the same meaning as above." msgstr "" -#: ../../library/ctypes.rst:1735 +#: ../../library/ctypes.rst:1756 msgid "" "The returned function prototype creates functions that use the Python " "calling convention. The function will *not* release the GIL during the call." msgstr "" -#: ../../library/ctypes.rst:1738 +#: ../../library/ctypes.rst:1759 msgid "" "Function prototypes created by these factory functions can be instantiated " "in different ways, depending on the type and number of the parameters in the " "call:" msgstr "" -#: ../../library/ctypes.rst:1745 +#: ../../library/ctypes.rst:1766 msgid "" "Returns a foreign function at the specified address which must be an integer." msgstr "" -#: ../../library/ctypes.rst:1752 +#: ../../library/ctypes.rst:1773 msgid "" "Create a C callable function (a callback function) from a Python *callable*." msgstr "" -#: ../../library/ctypes.rst:1759 +#: ../../library/ctypes.rst:1780 msgid "" "Returns a foreign function exported by a shared library. *func_spec* must be " "a 2-tuple ``(name_or_ordinal, library)``. The first item is the name of the " @@ -1756,7 +2639,7 @@ msgid "" "small integer. The second item is the shared library instance." msgstr "" -#: ../../library/ctypes.rst:1769 +#: ../../library/ctypes.rst:1790 msgid "" "Returns a foreign function that will call a COM method. *vtbl_index* is the " "index into the virtual function table, a small non-negative integer. *name* " @@ -1764,87 +2647,114 @@ msgid "" "identifier which is used in extended error reporting." msgstr "" -#: ../../library/ctypes.rst:1774 +#: ../../library/ctypes.rst:1795 msgid "" "COM methods use a special calling convention: They require a pointer to the " "COM interface as first argument, in addition to those parameters that are " "specified in the :attr:`!argtypes` tuple." msgstr "" -#: ../../library/ctypes.rst:1778 +#: ../../library/ctypes.rst:1799 msgid "" "The optional *paramflags* parameter creates foreign function wrappers with " "much more functionality than the features described above." msgstr "" -#: ../../library/ctypes.rst:1781 +#: ../../library/ctypes.rst:1802 msgid "" -"*paramflags* must be a tuple of the same length as :attr:`~_FuncPtr." +"*paramflags* must be a tuple of the same length as :attr:`~_CFuncPtr." "argtypes`." msgstr "" -#: ../../library/ctypes.rst:1783 +#: ../../library/ctypes.rst:1804 msgid "" "Each item in this tuple contains further information about a parameter, it " "must be a tuple containing one, two, or three items." msgstr "" -#: ../../library/ctypes.rst:1786 +#: ../../library/ctypes.rst:1807 msgid "" "The first item is an integer containing a combination of direction flags for " "the parameter:" msgstr "" -#: ../../library/ctypes.rst:1789 +#: ../../library/ctypes.rst:1810 msgid "1" msgstr "1" -#: ../../library/ctypes.rst:1790 +#: ../../library/ctypes.rst:1811 msgid "Specifies an input parameter to the function." msgstr "" -#: ../../library/ctypes.rst:1792 +#: ../../library/ctypes.rst:1813 msgid "2" msgstr "2" -#: ../../library/ctypes.rst:1793 +#: ../../library/ctypes.rst:1814 msgid "Output parameter. The foreign function fills in a value." msgstr "" -#: ../../library/ctypes.rst:1795 +#: ../../library/ctypes.rst:1816 msgid "4" msgstr "4" -#: ../../library/ctypes.rst:1796 +#: ../../library/ctypes.rst:1817 msgid "Input parameter which defaults to the integer zero." msgstr "" -#: ../../library/ctypes.rst:1798 +#: ../../library/ctypes.rst:1819 msgid "" "The optional second item is the parameter name as string. If this is " "specified, the foreign function can be called with named parameters." msgstr "" -#: ../../library/ctypes.rst:1801 +#: ../../library/ctypes.rst:1822 msgid "The optional third item is the default value for this parameter." msgstr "" -#: ../../library/ctypes.rst:1804 +#: ../../library/ctypes.rst:1825 msgid "" "The following example demonstrates how to wrap the Windows ``MessageBoxW`` " "function so that it supports default parameters and named arguments. The C " "declaration from the windows header file is this::" msgstr "" -#: ../../library/ctypes.rst:1815 ../../library/ctypes.rst:1838 +#: ../../library/ctypes.rst:1829 +msgid "" +"WINUSERAPI int WINAPI\n" +"MessageBoxW(\n" +" HWND hWnd,\n" +" LPCWSTR lpText,\n" +" LPCWSTR lpCaption,\n" +" UINT uType);" +msgstr "" + +#: ../../library/ctypes.rst:1836 ../../library/ctypes.rst:1859 msgid "Here is the wrapping with :mod:`ctypes`::" msgstr "" -#: ../../library/ctypes.rst:1823 +#: ../../library/ctypes.rst:1838 +msgid "" +">>> from ctypes import c_int, WINFUNCTYPE, windll\n" +">>> from ctypes.wintypes import HWND, LPCWSTR, UINT\n" +">>> prototype = WINFUNCTYPE(c_int, HWND, LPCWSTR, LPCWSTR, UINT)\n" +">>> paramflags = (1, \"hwnd\", 0), (1, \"text\", \"Hi\"), (1, \"caption\", " +"\"Hello from ctypes\"), (1, \"flags\", 0)\n" +">>> MessageBox = prototype((\"MessageBoxW\", windll.user32), paramflags)" +msgstr "" + +#: ../../library/ctypes.rst:1844 msgid "The ``MessageBox`` foreign function can now be called in these ways::" msgstr "" -#: ../../library/ctypes.rst:1829 +#: ../../library/ctypes.rst:1846 +msgid "" +">>> MessageBox()\n" +">>> MessageBox(text=\"Spam, spam, spam\")\n" +">>> MessageBox(flags=2, text=\"foo bar\")" +msgstr "" + +#: ../../library/ctypes.rst:1850 msgid "" "A second example demonstrates output parameters. The win32 " "``GetWindowRect`` function retrieves the dimensions of a specified window by " @@ -1852,7 +2762,26 @@ msgid "" "the C declaration::" msgstr "" -#: ../../library/ctypes.rst:1847 +#: ../../library/ctypes.rst:1854 +msgid "" +"WINUSERAPI BOOL WINAPI\n" +"GetWindowRect(\n" +" HWND hWnd,\n" +" LPRECT lpRect);" +msgstr "" + +#: ../../library/ctypes.rst:1861 +msgid "" +">>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError\n" +">>> from ctypes.wintypes import BOOL, HWND, RECT\n" +">>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))\n" +">>> paramflags = (1, \"hwnd\"), (2, \"lprect\")\n" +">>> GetWindowRect = prototype((\"GetWindowRect\", windll.user32), " +"paramflags)\n" +">>>" +msgstr "" + +#: ../../library/ctypes.rst:1868 msgid "" "Functions with output parameters will automatically return the output " "parameter value if there is a single one, or a tuple containing the output " @@ -1860,35 +2789,58 @@ msgid "" "now returns a RECT instance, when called." msgstr "" -#: ../../library/ctypes.rst:1852 +#: ../../library/ctypes.rst:1873 msgid "" -"Output parameters can be combined with the :attr:`~_FuncPtr.errcheck` " +"Output parameters can be combined with the :attr:`~_CFuncPtr.errcheck` " "protocol to do further output processing and error checking. The win32 " "``GetWindowRect`` api function returns a ``BOOL`` to signal success or " "failure, so this function could do the error checking, and raises an " "exception when the api call failed::" msgstr "" -#: ../../library/ctypes.rst:1865 +#: ../../library/ctypes.rst:1878 +msgid "" +">>> def errcheck(result, func, args):\n" +"... if not result:\n" +"... raise WinError()\n" +"... return args\n" +"...\n" +">>> GetWindowRect.errcheck = errcheck\n" +">>>" +msgstr "" + +#: ../../library/ctypes.rst:1886 msgid "" -"If the :attr:`~_FuncPtr.errcheck` function returns the argument tuple it " +"If the :attr:`~_CFuncPtr.errcheck` function returns the argument tuple it " "receives unchanged, :mod:`ctypes` continues the normal processing it does on " "the output parameters. If you want to return a tuple of window coordinates " "instead of a ``RECT`` instance, you can retrieve the fields in the function " "and return them instead, the normal processing will no longer take place::" msgstr "" -#: ../../library/ctypes.rst:1884 +#: ../../library/ctypes.rst:1892 +msgid "" +">>> def errcheck(result, func, args):\n" +"... if not result:\n" +"... raise WinError()\n" +"... rc = args[1]\n" +"... return rc.left, rc.top, rc.bottom, rc.right\n" +"...\n" +">>> GetWindowRect.errcheck = errcheck\n" +">>>" +msgstr "" + +#: ../../library/ctypes.rst:1905 msgid "Utility functions" msgstr "Funções utilitárias" -#: ../../library/ctypes.rst:1888 +#: ../../library/ctypes.rst:1909 msgid "" "Returns the address of the memory buffer as integer. *obj* must be an " "instance of a ctypes type." msgstr "" -#: ../../library/ctypes.rst:1891 +#: ../../library/ctypes.rst:1912 msgid "" "Raises an :ref:`auditing event ` ``ctypes.addressof`` with " "argument ``obj``." @@ -1896,30 +2848,34 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes.addressof`` com o " "argumento ``obj``." -#: ../../library/ctypes.rst:1896 +#: ../../library/ctypes.rst:1917 msgid "" "Returns the alignment requirements of a ctypes type. *obj_or_type* must be a " "ctypes type or instance." msgstr "" -#: ../../library/ctypes.rst:1902 +#: ../../library/ctypes.rst:1923 msgid "" "Returns a light-weight pointer to *obj*, which must be an instance of a " "ctypes type. *offset* defaults to zero, and must be an integer that will be " "added to the internal pointer value." msgstr "" -#: ../../library/ctypes.rst:1906 +#: ../../library/ctypes.rst:1927 msgid "``byref(obj, offset)`` corresponds to this C code::" msgstr "" -#: ../../library/ctypes.rst:1910 +#: ../../library/ctypes.rst:1929 +msgid "(((char *)&obj) + offset)" +msgstr "" + +#: ../../library/ctypes.rst:1931 msgid "" "The returned object can only be used as a foreign function call parameter. " "It behaves similar to ``pointer(obj)``, but the construction is a lot faster." msgstr "" -#: ../../library/ctypes.rst:1916 +#: ../../library/ctypes.rst:1937 msgid "" "This function is similar to the cast operator in C. It returns a new " "instance of *type* which points to the same memory block as *obj*. *type* " @@ -1927,19 +2883,19 @@ msgid "" "as a pointer." msgstr "" -#: ../../library/ctypes.rst:1924 +#: ../../library/ctypes.rst:1945 msgid "" "This function creates a mutable character buffer. The returned object is a " "ctypes array of :class:`c_char`." msgstr "" -#: ../../library/ctypes.rst:1927 +#: ../../library/ctypes.rst:1948 msgid "" "*init_or_size* must be an integer which specifies the size of the array, or " "a bytes object which will be used to initialize the array items." msgstr "" -#: ../../library/ctypes.rst:1930 +#: ../../library/ctypes.rst:1951 msgid "" "If a bytes object is specified as first argument, the buffer is made one " "item larger than its length so that the last element in the array is a NUL " @@ -1948,7 +2904,7 @@ msgid "" "not be used." msgstr "" -#: ../../library/ctypes.rst:1935 +#: ../../library/ctypes.rst:1956 msgid "" "Raises an :ref:`auditing event ` ``ctypes.create_string_buffer`` " "with arguments ``init``, ``size``." @@ -1956,19 +2912,19 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes." "create_string_buffer`` com os argumentos ``init``, ``size``." -#: ../../library/ctypes.rst:1940 +#: ../../library/ctypes.rst:1961 msgid "" "This function creates a mutable unicode character buffer. The returned " "object is a ctypes array of :class:`c_wchar`." msgstr "" -#: ../../library/ctypes.rst:1943 +#: ../../library/ctypes.rst:1964 msgid "" "*init_or_size* must be an integer which specifies the size of the array, or " "a string which will be used to initialize the array items." msgstr "" -#: ../../library/ctypes.rst:1946 +#: ../../library/ctypes.rst:1967 msgid "" "If a string is specified as first argument, the buffer is made one item " "larger than the length of the string so that the last element in the array " @@ -1977,7 +2933,7 @@ msgid "" "should not be used." msgstr "" -#: ../../library/ctypes.rst:1952 +#: ../../library/ctypes.rst:1973 msgid "" "Raises an :ref:`auditing event ` ``ctypes.create_unicode_buffer`` " "with arguments ``init``, ``size``." @@ -1985,21 +2941,21 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes." "create_unicode_buffer`` com os argumentos ``init``, ``size``." -#: ../../library/ctypes.rst:1957 +#: ../../library/ctypes.rst:1978 msgid "" -"Windows only: This function is a hook which allows implementing in-process " -"COM servers with ctypes. It is called from the DllCanUnloadNow function " -"that the _ctypes extension dll exports." +"This function is a hook which allows implementing in-process COM servers " +"with ctypes. It is called from the DllCanUnloadNow function that the " +"_ctypes extension dll exports." msgstr "" -#: ../../library/ctypes.rst:1964 +#: ../../library/ctypes.rst:1987 msgid "" -"Windows only: This function is a hook which allows implementing in-process " -"COM servers with ctypes. It is called from the DllGetClassObject function " -"that the ``_ctypes`` extension dll exports." +"This function is a hook which allows implementing in-process COM servers " +"with ctypes. It is called from the DllGetClassObject function that the " +"``_ctypes`` extension dll exports." msgstr "" -#: ../../library/ctypes.rst:1972 +#: ../../library/ctypes.rst:1997 msgid "" "Try to find a library and return a pathname. *name* is the library name " "without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version " @@ -2007,41 +2963,41 @@ msgid "" "If no library can be found, returns ``None``." msgstr "" -#: ../../library/ctypes.rst:1983 +#: ../../library/ctypes.rst:2008 msgid "" -"Windows only: return the filename of the VC runtime library used by Python, " -"and by the extension modules. If the name of the library cannot be " -"determined, ``None`` is returned." +"Returns the filename of the VC runtime library used by Python, and by the " +"extension modules. If the name of the library cannot be determined, " +"``None`` is returned." msgstr "" -#: ../../library/ctypes.rst:1987 +#: ../../library/ctypes.rst:2012 msgid "" "If you need to free memory, for example, allocated by an extension module " "with a call to the ``free(void *)``, it is important that you use the " "function in the same library that allocated the memory." msgstr "" -#: ../../library/ctypes.rst:1994 +#: ../../library/ctypes.rst:2021 msgid "" -"Windows only: Returns a textual description of the error code *code*. If no " -"error code is specified, the last error code is used by calling the Windows " -"api function GetLastError." +"Returns a textual description of the error code *code*. If no error code is " +"specified, the last error code is used by calling the Windows api function " +"GetLastError." msgstr "" -#: ../../library/ctypes.rst:2001 +#: ../../library/ctypes.rst:2030 msgid "" -"Windows only: Returns the last error code set by Windows in the calling " -"thread. This function calls the Windows ``GetLastError()`` function " -"directly, it does not return the ctypes-private copy of the error code." +"Returns the last error code set by Windows in the calling thread. This " +"function calls the Windows ``GetLastError()`` function directly, it does not " +"return the ctypes-private copy of the error code." msgstr "" -#: ../../library/ctypes.rst:2007 +#: ../../library/ctypes.rst:2039 msgid "" "Returns the current value of the ctypes-private copy of the system :data:" "`errno` variable in the calling thread." msgstr "" -#: ../../library/ctypes.rst:2010 +#: ../../library/ctypes.rst:2042 msgid "" "Raises an :ref:`auditing event ` ``ctypes.get_errno`` with no " "arguments." @@ -2049,13 +3005,13 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes.get_errno`` sem " "argumentos." -#: ../../library/ctypes.rst:2014 +#: ../../library/ctypes.rst:2046 msgid "" -"Windows only: returns the current value of the ctypes-private copy of the " -"system :data:`!LastError` variable in the calling thread." +"Returns the current value of the ctypes-private copy of the system :data:`!" +"LastError` variable in the calling thread." msgstr "" -#: ../../library/ctypes.rst:2017 +#: ../../library/ctypes.rst:2051 msgid "" "Raises an :ref:`auditing event ` ``ctypes.get_last_error`` with no " "arguments." @@ -2063,40 +3019,40 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes.get_last_error`` " "sem argumentos." -#: ../../library/ctypes.rst:2021 +#: ../../library/ctypes.rst:2056 msgid "" "Same as the standard C memmove library function: copies *count* bytes from " "*src* to *dst*. *dst* and *src* must be integers or ctypes instances that " "can be converted to pointers." msgstr "" -#: ../../library/ctypes.rst:2028 +#: ../../library/ctypes.rst:2063 msgid "" "Same as the standard C memset library function: fills the memory block at " "address *dst* with *count* bytes of value *c*. *dst* must be an integer " "specifying an address, or a ctypes instance." msgstr "" -#: ../../library/ctypes.rst:2035 +#: ../../library/ctypes.rst:2070 msgid "" "Create and return a new ctypes pointer type. Pointer types are cached and " "reused internally, so calling this function repeatedly is cheap. *type* must " "be a ctypes type." msgstr "" -#: ../../library/ctypes.rst:2042 +#: ../../library/ctypes.rst:2077 msgid "" "Create a new pointer instance, pointing to *obj*. The returned object is of " "the type ``POINTER(type(obj))``." msgstr "" -#: ../../library/ctypes.rst:2045 +#: ../../library/ctypes.rst:2080 msgid "" "Note: If you just want to pass a pointer to an object to a foreign function " "call, you should use ``byref(obj)`` which is much faster." msgstr "" -#: ../../library/ctypes.rst:2051 +#: ../../library/ctypes.rst:2086 msgid "" "This function resizes the internal memory buffer of *obj*, which must be an " "instance of a ctypes type. It is not possible to make the buffer smaller " @@ -2104,13 +3060,13 @@ msgid "" "but it is possible to enlarge the buffer." msgstr "" -#: ../../library/ctypes.rst:2059 +#: ../../library/ctypes.rst:2094 msgid "" "Set the current value of the ctypes-private copy of the system :data:`errno` " "variable in the calling thread to *value* and return the previous value." msgstr "" -#: ../../library/ctypes.rst:2062 +#: ../../library/ctypes.rst:2097 msgid "" "Raises an :ref:`auditing event ` ``ctypes.set_errno`` with " "argument ``errno``." @@ -2118,14 +3074,14 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes.set_errno`` com o " "argumento ``errno``." -#: ../../library/ctypes.rst:2067 +#: ../../library/ctypes.rst:2102 msgid "" -"Windows only: set the current value of the ctypes-private copy of the " -"system :data:`!LastError` variable in the calling thread to *value* and " -"return the previous value." +"Sets the current value of the ctypes-private copy of the system :data:`!" +"LastError` variable in the calling thread to *value* and return the previous " +"value." msgstr "" -#: ../../library/ctypes.rst:2071 +#: ../../library/ctypes.rst:2108 msgid "" "Raises an :ref:`auditing event ` ``ctypes.set_last_error`` with " "argument ``error``." @@ -2133,19 +3089,19 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes.set_last_error`` " "com o argumento ``error``." -#: ../../library/ctypes.rst:2076 +#: ../../library/ctypes.rst:2113 msgid "" "Returns the size in bytes of a ctypes type or instance memory buffer. Does " "the same as the C ``sizeof`` operator." msgstr "" -#: ../../library/ctypes.rst:2082 +#: ../../library/ctypes.rst:2119 msgid "" "Return the byte string at *void \\*ptr*. If *size* is specified, it is used " "as size, otherwise the string is assumed to be zero-terminated." msgstr "" -#: ../../library/ctypes.rst:2086 +#: ../../library/ctypes.rst:2123 msgid "" "Raises an :ref:`auditing event ` ``ctypes.string_at`` with " "arguments ``ptr``, ``size``." @@ -2153,29 +3109,28 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes.string_at`` com os " "argumentos ``ptr``, ``size``." -#: ../../library/ctypes.rst:2091 +#: ../../library/ctypes.rst:2128 msgid "" -"Windows only: this function is probably the worst-named thing in ctypes. It " -"creates an instance of :exc:`OSError`. If *code* is not specified, " -"``GetLastError`` is called to determine the error code. If *descr* is not " -"specified, :func:`FormatError` is called to get a textual description of the " -"error." +"This function is probably the worst-named thing in ctypes. It creates an " +"instance of :exc:`OSError`. If *code* is not specified, ``GetLastError`` is " +"called to determine the error code. If *descr* is not specified, :func:" +"`FormatError` is called to get a textual description of the error." msgstr "" -#: ../../library/ctypes.rst:2097 +#: ../../library/ctypes.rst:2136 msgid "" "An instance of :exc:`WindowsError` used to be created, which is now an alias " "of :exc:`OSError`." msgstr "" -#: ../../library/ctypes.rst:2104 +#: ../../library/ctypes.rst:2143 msgid "" "Return the wide-character string at *void \\*ptr*. If *size* is specified, " "it is used as the number of characters of the string, otherwise the string " "is assumed to be zero-terminated." msgstr "" -#: ../../library/ctypes.rst:2109 +#: ../../library/ctypes.rst:2148 msgid "" "Raises an :ref:`auditing event ` ``ctypes.wstring_at`` with " "arguments ``ptr``, ``size``." @@ -2183,11 +3138,11 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes.wstring_at`` com " "os argumentos ``ptr``, ``size``." -#: ../../library/ctypes.rst:2115 +#: ../../library/ctypes.rst:2154 msgid "Data types" msgstr "" -#: ../../library/ctypes.rst:2120 +#: ../../library/ctypes.rst:2159 msgid "" "This non-public class is the common base class of all ctypes data types. " "Among other things, all ctypes type instances contain a memory block that " @@ -2197,13 +3152,13 @@ msgid "" "alive in case the memory block contains pointers." msgstr "" -#: ../../library/ctypes.rst:2127 +#: ../../library/ctypes.rst:2166 msgid "" "Common methods of ctypes data types, these are all class methods (to be " "exact, they are methods of the :term:`metaclass`):" msgstr "" -#: ../../library/ctypes.rst:2132 +#: ../../library/ctypes.rst:2171 msgid "" "This method returns a ctypes instance that shares the buffer of the *source* " "object. The *source* object must support the writeable buffer interface. " @@ -2212,7 +3167,7 @@ msgid "" "exc:`ValueError` is raised." msgstr "" -#: ../../library/ctypes.rst:2138 ../../library/ctypes.rst:2148 +#: ../../library/ctypes.rst:2177 ../../library/ctypes.rst:2187 msgid "" "Raises an :ref:`auditing event ` ``ctypes.cdata/buffer`` with " "arguments ``pointer``, ``size``, ``offset``." @@ -2220,7 +3175,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes.cdata/buffer`` com " "os argumentos ``pointer``, ``size``, ``offset``." -#: ../../library/ctypes.rst:2142 +#: ../../library/ctypes.rst:2181 msgid "" "This method creates a ctypes instance, copying the buffer from the *source* " "object buffer which must be readable. The optional *offset* parameter " @@ -2228,13 +3183,13 @@ msgid "" "If the source buffer is not large enough a :exc:`ValueError` is raised." msgstr "" -#: ../../library/ctypes.rst:2152 +#: ../../library/ctypes.rst:2191 msgid "" "This method returns a ctypes type instance using the memory specified by " "*address* which must be an integer." msgstr "" -#: ../../library/ctypes.rst:2155 ../../library/ctypes.rst:2157 +#: ../../library/ctypes.rst:2194 ../../library/ctypes.rst:2196 msgid "" "This method, and others that indirectly call this method, raises an :ref:" "`auditing event ` ``ctypes.cdata`` with argument ``address``." @@ -2243,33 +3198,33 @@ msgstr "" "`evento de auditoria ` ``ctypes.cdata`` com o argumento " "``address``." -#: ../../library/ctypes.rst:2163 +#: ../../library/ctypes.rst:2202 msgid "" "This method adapts *obj* to a ctypes type. It is called with the actual " "object used in a foreign function call when the type is present in the " -"foreign function's :attr:`~_FuncPtr.argtypes` tuple; it must return an " +"foreign function's :attr:`~_CFuncPtr.argtypes` tuple; it must return an " "object that can be used as a function call parameter." msgstr "" -#: ../../library/ctypes.rst:2168 +#: ../../library/ctypes.rst:2207 msgid "" "All ctypes data types have a default implementation of this classmethod that " "normally returns *obj* if that is an instance of the type. Some types " "accept other objects as well." msgstr "" -#: ../../library/ctypes.rst:2174 +#: ../../library/ctypes.rst:2213 msgid "" "This method returns a ctypes type instance exported by a shared library. " "*name* is the name of the symbol that exports the data, *library* is the " "loaded shared library." msgstr "" -#: ../../library/ctypes.rst:2178 +#: ../../library/ctypes.rst:2217 msgid "Common instance variables of ctypes data types:" msgstr "" -#: ../../library/ctypes.rst:2182 +#: ../../library/ctypes.rst:2221 msgid "" "Sometimes ctypes data instances do not own the memory block they contain, " "instead they share part of the memory block of a base object. The :attr:" @@ -2277,13 +3232,13 @@ msgid "" "block." msgstr "" -#: ../../library/ctypes.rst:2189 +#: ../../library/ctypes.rst:2228 msgid "" "This read-only variable is true when the ctypes data instance has allocated " "the memory block itself, false otherwise." msgstr "" -#: ../../library/ctypes.rst:2194 +#: ../../library/ctypes.rst:2233 msgid "" "This member is either ``None`` or a dictionary containing Python objects " "that need to be kept alive so that the memory block contents is kept valid. " @@ -2291,7 +3246,7 @@ msgid "" "dictionary." msgstr "" -#: ../../library/ctypes.rst:2207 +#: ../../library/ctypes.rst:2246 msgid "" "This non-public class is the base class of all fundamental ctypes data " "types. It is mentioned here because it contains the common attributes of the " @@ -2300,11 +3255,11 @@ msgid "" "types that are not and do not contain pointers can now be pickled." msgstr "" -#: ../../library/ctypes.rst:2213 +#: ../../library/ctypes.rst:2252 msgid "Instances have a single attribute:" msgstr "" -#: ../../library/ctypes.rst:2217 +#: ../../library/ctypes.rst:2256 msgid "" "This attribute contains the actual value of the instance. For integer and " "pointer types, it is an integer, for character types, it is a single " @@ -2312,7 +3267,7 @@ msgid "" "bytes object or string." msgstr "" -#: ../../library/ctypes.rst:2222 +#: ../../library/ctypes.rst:2261 msgid "" "When the ``value`` attribute is retrieved from a ctypes instance, usually a " "new object is returned each time. :mod:`ctypes` does *not* implement " @@ -2320,17 +3275,17 @@ msgid "" "true for all other ctypes object instances." msgstr "" -#: ../../library/ctypes.rst:2228 +#: ../../library/ctypes.rst:2267 msgid "" "Fundamental data types, when returned as foreign function call results, or, " "for example, by retrieving structure field members or array items, are " "transparently converted to native Python types. In other words, if a " -"foreign function has a :attr:`~_FuncPtr.restype` of :class:`c_char_p`, you " +"foreign function has a :attr:`~_CFuncPtr.restype` of :class:`c_char_p`, you " "will always receive a Python bytes object, *not* a :class:`c_char_p` " "instance." msgstr "" -#: ../../library/ctypes.rst:2236 +#: ../../library/ctypes.rst:2275 msgid "" "Subclasses of fundamental data types do *not* inherit this behavior. So, if " "a foreign functions :attr:`!restype` is a subclass of :class:`c_void_p`, you " @@ -2338,25 +3293,25 @@ msgid "" "you can get the value of the pointer by accessing the ``value`` attribute." msgstr "" -#: ../../library/ctypes.rst:2241 +#: ../../library/ctypes.rst:2280 msgid "These are the fundamental ctypes data types:" msgstr "" -#: ../../library/ctypes.rst:2245 +#: ../../library/ctypes.rst:2284 msgid "" "Represents the C :c:expr:`signed char` datatype, and interprets the value as " "small integer. The constructor accepts an optional integer initializer; no " "overflow checking is done." msgstr "" -#: ../../library/ctypes.rst:2252 +#: ../../library/ctypes.rst:2291 msgid "" "Represents the C :c:expr:`char` datatype, and interprets the value as a " "single character. The constructor accepts an optional string initializer, " "the length of the string must be exactly one character." msgstr "" -#: ../../library/ctypes.rst:2259 +#: ../../library/ctypes.rst:2298 msgid "" "Represents the C :c:expr:`char *` datatype when it points to a zero-" "terminated string. For a general character pointer that may also point to " @@ -2364,182 +3319,182 @@ msgid "" "integer address, or a bytes object." msgstr "" -#: ../../library/ctypes.rst:2267 +#: ../../library/ctypes.rst:2306 msgid "" "Represents the C :c:expr:`double` datatype. The constructor accepts an " "optional float initializer." msgstr "" -#: ../../library/ctypes.rst:2273 +#: ../../library/ctypes.rst:2312 msgid "" "Represents the C :c:expr:`long double` datatype. The constructor accepts an " "optional float initializer. On platforms where ``sizeof(long double) == " "sizeof(double)`` it is an alias to :class:`c_double`." msgstr "" -#: ../../library/ctypes.rst:2279 +#: ../../library/ctypes.rst:2318 msgid "" "Represents the C :c:expr:`float` datatype. The constructor accepts an " "optional float initializer." msgstr "" -#: ../../library/ctypes.rst:2285 +#: ../../library/ctypes.rst:2324 msgid "" "Represents the C :c:expr:`signed int` datatype. The constructor accepts an " "optional integer initializer; no overflow checking is done. On platforms " "where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`." msgstr "" -#: ../../library/ctypes.rst:2292 +#: ../../library/ctypes.rst:2331 msgid "" "Represents the C 8-bit :c:expr:`signed int` datatype. Usually an alias for :" "class:`c_byte`." msgstr "" -#: ../../library/ctypes.rst:2298 +#: ../../library/ctypes.rst:2337 msgid "" "Represents the C 16-bit :c:expr:`signed int` datatype. Usually an alias " "for :class:`c_short`." msgstr "" -#: ../../library/ctypes.rst:2304 +#: ../../library/ctypes.rst:2343 msgid "" "Represents the C 32-bit :c:expr:`signed int` datatype. Usually an alias " "for :class:`c_int`." msgstr "" -#: ../../library/ctypes.rst:2310 +#: ../../library/ctypes.rst:2349 msgid "" "Represents the C 64-bit :c:expr:`signed int` datatype. Usually an alias " "for :class:`c_longlong`." msgstr "" -#: ../../library/ctypes.rst:2316 +#: ../../library/ctypes.rst:2355 msgid "" "Represents the C :c:expr:`signed long` datatype. The constructor accepts an " "optional integer initializer; no overflow checking is done." msgstr "" -#: ../../library/ctypes.rst:2322 +#: ../../library/ctypes.rst:2361 msgid "" "Represents the C :c:expr:`signed long long` datatype. The constructor " "accepts an optional integer initializer; no overflow checking is done." msgstr "" -#: ../../library/ctypes.rst:2328 +#: ../../library/ctypes.rst:2367 msgid "" "Represents the C :c:expr:`signed short` datatype. The constructor accepts " "an optional integer initializer; no overflow checking is done." msgstr "" -#: ../../library/ctypes.rst:2334 +#: ../../library/ctypes.rst:2373 msgid "Represents the C :c:type:`size_t` datatype." msgstr "" -#: ../../library/ctypes.rst:2339 +#: ../../library/ctypes.rst:2378 msgid "Represents the C :c:type:`ssize_t` datatype." msgstr "" -#: ../../library/ctypes.rst:2346 +#: ../../library/ctypes.rst:2385 msgid "Represents the C :c:type:`time_t` datatype." msgstr "" -#: ../../library/ctypes.rst:2353 +#: ../../library/ctypes.rst:2392 msgid "" "Represents the C :c:expr:`unsigned char` datatype, it interprets the value " "as small integer. The constructor accepts an optional integer initializer; " "no overflow checking is done." msgstr "" -#: ../../library/ctypes.rst:2360 +#: ../../library/ctypes.rst:2399 msgid "" "Represents the C :c:expr:`unsigned int` datatype. The constructor accepts " "an optional integer initializer; no overflow checking is done. On platforms " "where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`." msgstr "" -#: ../../library/ctypes.rst:2367 +#: ../../library/ctypes.rst:2406 msgid "" "Represents the C 8-bit :c:expr:`unsigned int` datatype. Usually an alias " "for :class:`c_ubyte`." msgstr "" -#: ../../library/ctypes.rst:2373 +#: ../../library/ctypes.rst:2412 msgid "" "Represents the C 16-bit :c:expr:`unsigned int` datatype. Usually an alias " "for :class:`c_ushort`." msgstr "" -#: ../../library/ctypes.rst:2379 +#: ../../library/ctypes.rst:2418 msgid "" "Represents the C 32-bit :c:expr:`unsigned int` datatype. Usually an alias " "for :class:`c_uint`." msgstr "" -#: ../../library/ctypes.rst:2385 +#: ../../library/ctypes.rst:2424 msgid "" "Represents the C 64-bit :c:expr:`unsigned int` datatype. Usually an alias " "for :class:`c_ulonglong`." msgstr "" -#: ../../library/ctypes.rst:2391 +#: ../../library/ctypes.rst:2430 msgid "" "Represents the C :c:expr:`unsigned long` datatype. The constructor accepts " "an optional integer initializer; no overflow checking is done." msgstr "" -#: ../../library/ctypes.rst:2397 +#: ../../library/ctypes.rst:2436 msgid "" "Represents the C :c:expr:`unsigned long long` datatype. The constructor " "accepts an optional integer initializer; no overflow checking is done." msgstr "" -#: ../../library/ctypes.rst:2403 +#: ../../library/ctypes.rst:2442 msgid "" "Represents the C :c:expr:`unsigned short` datatype. The constructor accepts " "an optional integer initializer; no overflow checking is done." msgstr "" -#: ../../library/ctypes.rst:2409 +#: ../../library/ctypes.rst:2448 msgid "" "Represents the C :c:expr:`void *` type. The value is represented as " "integer. The constructor accepts an optional integer initializer." msgstr "" -#: ../../library/ctypes.rst:2415 +#: ../../library/ctypes.rst:2454 msgid "" "Represents the C :c:type:`wchar_t` datatype, and interprets the value as a " "single character unicode string. The constructor accepts an optional string " "initializer, the length of the string must be exactly one character." msgstr "" -#: ../../library/ctypes.rst:2422 +#: ../../library/ctypes.rst:2461 msgid "" "Represents the C :c:expr:`wchar_t *` datatype, which must be a pointer to a " "zero-terminated wide character string. The constructor accepts an integer " "address, or a string." msgstr "" -#: ../../library/ctypes.rst:2429 +#: ../../library/ctypes.rst:2468 msgid "" "Represent the C :c:expr:`bool` datatype (more accurately, :c:expr:`_Bool` " "from C99). Its value can be ``True`` or ``False``, and the constructor " "accepts any object that has a truth value." msgstr "" -#: ../../library/ctypes.rst:2436 +#: ../../library/ctypes.rst:2475 msgid "" -"Windows only: Represents a :c:type:`!HRESULT` value, which contains success " -"or error information for a function or method call." +"Represents a :c:type:`!HRESULT` value, which contains success or error " +"information for a function or method call." msgstr "" -#: ../../library/ctypes.rst:2442 +#: ../../library/ctypes.rst:2483 msgid "" "Represents the C :c:expr:`PyObject *` datatype. Calling this without an " "argument creates a ``NULL`` :c:expr:`PyObject *` pointer." msgstr "" -#: ../../library/ctypes.rst:2445 +#: ../../library/ctypes.rst:2486 msgid "" "The :mod:`!ctypes.wintypes` module provides quite some other Windows " "specific data types, for example :c:type:`!HWND`, :c:type:`!WPARAM`, or :c:" @@ -2547,41 +3502,41 @@ msgid "" "are also defined." msgstr "" -#: ../../library/ctypes.rst:2453 +#: ../../library/ctypes.rst:2494 msgid "Structured data types" msgstr "" -#: ../../library/ctypes.rst:2458 +#: ../../library/ctypes.rst:2499 msgid "Abstract base class for unions in native byte order." msgstr "" -#: ../../library/ctypes.rst:2463 +#: ../../library/ctypes.rst:2504 msgid "Abstract base class for unions in *big endian* byte order." msgstr "" -#: ../../library/ctypes.rst:2469 +#: ../../library/ctypes.rst:2510 msgid "Abstract base class for unions in *little endian* byte order." msgstr "" -#: ../../library/ctypes.rst:2475 +#: ../../library/ctypes.rst:2516 msgid "Abstract base class for structures in *big endian* byte order." msgstr "" -#: ../../library/ctypes.rst:2480 +#: ../../library/ctypes.rst:2521 msgid "Abstract base class for structures in *little endian* byte order." msgstr "" -#: ../../library/ctypes.rst:2482 +#: ../../library/ctypes.rst:2523 msgid "" "Structures and unions with non-native byte order cannot contain pointer type " "fields, or any other data types containing pointer type fields." msgstr "" -#: ../../library/ctypes.rst:2488 +#: ../../library/ctypes.rst:2529 msgid "Abstract base class for structures in *native* byte order." msgstr "" -#: ../../library/ctypes.rst:2490 +#: ../../library/ctypes.rst:2531 msgid "" "Concrete structure and union types must be created by subclassing one of " "these types, and at least define a :attr:`_fields_` class variable. :mod:" @@ -2589,34 +3544,43 @@ msgid "" "the fields by direct attribute accesses. These are the" msgstr "" -#: ../../library/ctypes.rst:2498 +#: ../../library/ctypes.rst:2539 msgid "" "A sequence defining the structure fields. The items must be 2-tuples or 3-" "tuples. The first item is the name of the field, the second item specifies " "the type of the field; it can be any ctypes data type." msgstr "" -#: ../../library/ctypes.rst:2502 +#: ../../library/ctypes.rst:2543 msgid "" "For integer type fields like :class:`c_int`, a third optional item can be " "given. It must be a small positive integer defining the bit width of the " "field." msgstr "" -#: ../../library/ctypes.rst:2506 +#: ../../library/ctypes.rst:2547 msgid "" "Field names must be unique within one structure or union. This is not " "checked, only one field can be accessed when names are repeated." msgstr "" -#: ../../library/ctypes.rst:2509 +#: ../../library/ctypes.rst:2550 msgid "" "It is possible to define the :attr:`_fields_` class variable *after* the " "class statement that defines the Structure subclass, this allows creating " "data types that directly or indirectly reference themselves::" msgstr "" -#: ../../library/ctypes.rst:2519 +#: ../../library/ctypes.rst:2554 +msgid "" +"class List(Structure):\n" +" pass\n" +"List._fields_ = [(\"pnext\", POINTER(List)),\n" +" ...\n" +" ]" +msgstr "" + +#: ../../library/ctypes.rst:2560 msgid "" "The :attr:`_fields_` class variable must, however, be defined before the " "type is first used (an instance is created, :func:`sizeof` is called on it, " @@ -2624,14 +3588,14 @@ msgid "" "raise an AttributeError." msgstr "" -#: ../../library/ctypes.rst:2524 +#: ../../library/ctypes.rst:2565 msgid "" "It is possible to define sub-subclasses of structure types, they inherit the " "fields of the base class plus the :attr:`_fields_` defined in the sub-" "subclass, if any." msgstr "" -#: ../../library/ctypes.rst:2531 +#: ../../library/ctypes.rst:2572 msgid "" "An optional small integer that allows overriding the alignment of structure " "fields in the instance. :attr:`_pack_` must already be defined when :attr:" @@ -2639,21 +3603,21 @@ msgid "" "attribute to 0 is the same as not setting it at all." msgstr "" -#: ../../library/ctypes.rst:2539 +#: ../../library/ctypes.rst:2580 msgid "" "An optional small integer that allows overriding the alignment of the " "structure when being packed or unpacked to/from memory. Setting this " "attribute to 0 is the same as not setting it at all." msgstr "" -#: ../../library/ctypes.rst:2545 +#: ../../library/ctypes.rst:2588 msgid "" "An optional sequence that lists the names of unnamed (anonymous) fields. :" "attr:`_anonymous_` must be already defined when :attr:`_fields_` is " "assigned, otherwise it will have no effect." msgstr "" -#: ../../library/ctypes.rst:2549 +#: ../../library/ctypes.rst:2592 msgid "" "The fields listed in this variable must be structure or union type fields. :" "mod:`ctypes` will create descriptors in the structure type that allows " @@ -2661,11 +3625,24 @@ msgid "" "structure or union field." msgstr "" -#: ../../library/ctypes.rst:2554 +#: ../../library/ctypes.rst:2597 msgid "Here is an example type (Windows)::" msgstr "" -#: ../../library/ctypes.rst:2567 +#: ../../library/ctypes.rst:2599 +msgid "" +"class _U(Union):\n" +" _fields_ = [(\"lptdesc\", POINTER(TYPEDESC)),\n" +" (\"lpadesc\", POINTER(ARRAYDESC)),\n" +" (\"hreftype\", HREFTYPE)]\n" +"\n" +"class TYPEDESC(Structure):\n" +" _anonymous_ = (\"u\",)\n" +" _fields_ = [(\"u\", _U),\n" +" (\"vt\", VARTYPE)]" +msgstr "" + +#: ../../library/ctypes.rst:2610 msgid "" "The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field " "specifies which one of the union fields is valid. Since the ``u`` field is " @@ -2675,7 +3652,15 @@ msgid "" "temporary union instance::" msgstr "" -#: ../../library/ctypes.rst:2579 +#: ../../library/ctypes.rst:2617 +msgid "" +"td = TYPEDESC()\n" +"td.vt = VT_PTR\n" +"td.lptdesc = POINTER(some_type)\n" +"td.u.lptdesc = POINTER(some_type)" +msgstr "" + +#: ../../library/ctypes.rst:2622 msgid "" "It is possible to define sub-subclasses of structures, they inherit the " "fields of the base class. If the subclass definition has a separate :attr:" @@ -2683,7 +3668,7 @@ msgid "" "of the base class." msgstr "" -#: ../../library/ctypes.rst:2584 +#: ../../library/ctypes.rst:2627 msgid "" "Structure and union constructors accept both positional and keyword " "arguments. Positional arguments are used to initialize member fields in the " @@ -2693,15 +3678,15 @@ msgid "" "names not present in :attr:`_fields_`." msgstr "" -#: ../../library/ctypes.rst:2595 +#: ../../library/ctypes.rst:2638 msgid "Arrays and pointers" msgstr "" -#: ../../library/ctypes.rst:2599 +#: ../../library/ctypes.rst:2642 msgid "Abstract base class for arrays." msgstr "" -#: ../../library/ctypes.rst:2601 +#: ../../library/ctypes.rst:2644 msgid "" "The recommended way to create concrete array types is by multiplying any :" "mod:`ctypes` data type with a non-negative integer. Alternatively, you can " @@ -2711,46 +3696,46 @@ msgid "" "an :class:`Array`." msgstr "" -#: ../../library/ctypes.rst:2611 +#: ../../library/ctypes.rst:2654 msgid "" "A positive integer specifying the number of elements in the array. Out-of-" "range subscripts result in an :exc:`IndexError`. Will be returned by :func:" "`len`." msgstr "" -#: ../../library/ctypes.rst:2618 +#: ../../library/ctypes.rst:2661 msgid "Specifies the type of each element in the array." msgstr "" -#: ../../library/ctypes.rst:2621 +#: ../../library/ctypes.rst:2664 msgid "" "Array subclass constructors accept positional arguments, used to initialize " "the elements in order." msgstr "" -#: ../../library/ctypes.rst:2626 +#: ../../library/ctypes.rst:2669 msgid "" "Create an array. Equivalent to ``type * length``, where *type* is a :mod:" "`ctypes` data type and *length* an integer." msgstr "" -#: ../../library/ctypes.rst:2630 +#: ../../library/ctypes.rst:2673 msgid "" "This function is :term:`soft deprecated` in favor of multiplication. There " "are no plans to remove it." msgstr "" -#: ../../library/ctypes.rst:2636 +#: ../../library/ctypes.rst:2679 msgid "Private, abstract base class for pointers." msgstr "" -#: ../../library/ctypes.rst:2638 +#: ../../library/ctypes.rst:2681 msgid "" "Concrete pointer types are created by calling :func:`POINTER` with the type " "that will be pointed to; this is done automatically by :func:`pointer`." msgstr "" -#: ../../library/ctypes.rst:2642 +#: ../../library/ctypes.rst:2685 msgid "" "If a pointer points to an array, its elements can be read and written using " "standard subscript and slice accesses. Pointer objects have no size, so :" @@ -2759,11 +3744,11 @@ msgid "" "probably crash with an access violation (if you're lucky)." msgstr "" -#: ../../library/ctypes.rst:2652 +#: ../../library/ctypes.rst:2695 msgid "Specifies the type pointed to." msgstr "" -#: ../../library/ctypes.rst:2656 +#: ../../library/ctypes.rst:2699 msgid "" "Returns the object to which to pointer points. Assigning to this attribute " "changes the pointer to point to the assigned object." diff --git a/library/curses.ascii.po b/library/curses.ascii.po index 95c626c12..d5d0c6362 100644 --- a/library/curses.ascii.po +++ b/library/curses.ascii.po @@ -1,39 +1,35 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Welington Carlos , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2023 -# Adorilson Bezerra , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:03+0000\n" -"Last-Translator: Adorilson Bezerra , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/curses.ascii.rst:2 msgid ":mod:`!curses.ascii` --- Utilities for ASCII characters" -msgstr "" +msgstr ":mod:`!curses.ascii` --- Utilitários para caracteres ASCII" #: ../../library/curses.ascii.rst:10 msgid "**Source code:** :source:`Lib/curses/ascii.py`" -msgstr "" +msgstr "**Código-fonte:** :source:`Lib/curses/ascii.py`" #: ../../library/curses.ascii.rst:14 msgid "" @@ -41,6 +37,10 @@ msgid "" "and functions to test membership in various ASCII character classes. The " "constants supplied are names for control characters as follows:" msgstr "" +"O módulo :mod:`curses.ascii` fornece constantes de nome para caracteres " +"ASCII e funções para testar associação em várias classes de caracteres " +"ASCII. As constantes fornecidas são nomes para caracteres de controle, como " +"detalhado a seguir:" #: ../../library/curses.ascii.rst:19 msgid "Name" @@ -52,135 +52,139 @@ msgstr "Significado" #: ../../library/curses.ascii.rst:23 msgid "Start of heading, console interrupt" -msgstr "" +msgstr "Início do cabeçalho, interrupção do console" #: ../../library/curses.ascii.rst:25 msgid "Start of text" -msgstr "" +msgstr "Início de texto" #: ../../library/curses.ascii.rst:27 msgid "End of text" -msgstr "" +msgstr "Fim de texto" #: ../../library/curses.ascii.rst:29 msgid "End of transmission" -msgstr "" +msgstr "Fim de transmissão" #: ../../library/curses.ascii.rst:31 msgid "Enquiry, goes with :const:`ACK` flow control" -msgstr "" +msgstr "Consulta, segue com controle de fluxo :const:`ACK`" #: ../../library/curses.ascii.rst:33 msgid "Acknowledgement" -msgstr "" +msgstr "Confirmação" #: ../../library/curses.ascii.rst:35 msgid "Bell" -msgstr "" +msgstr "Campainha" #: ../../library/curses.ascii.rst:37 msgid "Backspace" -msgstr "" +msgstr "Backspace" #: ../../library/curses.ascii.rst:39 msgid "Tab" -msgstr "" +msgstr "Tabulação" #: ../../library/curses.ascii.rst:41 msgid "Alias for :const:`TAB`: \"Horizontal tab\"" -msgstr "" +msgstr "Apelido para :const:`TAB`: \"Tabulação horizontal\"" #: ../../library/curses.ascii.rst:43 msgid "Line feed" -msgstr "" +msgstr "Alimentação de linha ou *line feed*" #: ../../library/curses.ascii.rst:45 msgid "Alias for :const:`LF`: \"New line\"" -msgstr "" +msgstr "Apelido para :const:`LF`: \"Nova linha\"" #: ../../library/curses.ascii.rst:47 msgid "Vertical tab" -msgstr "" +msgstr "Tabulação vertical" #: ../../library/curses.ascii.rst:49 msgid "Form feed" -msgstr "" +msgstr "Alimentação de formulário ou *form feed*" #: ../../library/curses.ascii.rst:51 msgid "Carriage return" -msgstr "" +msgstr "Retorno de carro ou *carriage return*" #: ../../library/curses.ascii.rst:53 msgid "Shift-out, begin alternate character set" msgstr "" +"Deslocamento para fora ou *shift-out*, inicia um conjunto de caracteres " +"alternativo" #: ../../library/curses.ascii.rst:55 msgid "Shift-in, resume default character set" msgstr "" +"Deslocamento para dentro ou *shift-in*, retoma o conjunto de caracteres " +"padrão" #: ../../library/curses.ascii.rst:57 msgid "Data-link escape" -msgstr "" +msgstr "Escape de conexão ou *data-link escape*" #: ../../library/curses.ascii.rst:59 msgid "XON, for flow control" -msgstr "" +msgstr "XON, para controle de fluxo" #: ../../library/curses.ascii.rst:61 msgid "Device control 2, block-mode flow control" -msgstr "" +msgstr "Controle de dispositivo 2, control de fluxo em modo bloco" #: ../../library/curses.ascii.rst:63 msgid "XOFF, for flow control" -msgstr "" +msgstr "XOFF, para controle de fluxo" #: ../../library/curses.ascii.rst:65 msgid "Device control 4" -msgstr "" +msgstr "Controle de dispositivo 4" #: ../../library/curses.ascii.rst:67 msgid "Negative acknowledgement" -msgstr "" +msgstr "Confirmação negativa" #: ../../library/curses.ascii.rst:69 msgid "Synchronous idle" -msgstr "" +msgstr "Estado ocioso síncrono" #: ../../library/curses.ascii.rst:71 msgid "End transmission block" -msgstr "" +msgstr "Bloco de fim de transmissão" #: ../../library/curses.ascii.rst:73 msgid "Cancel" -msgstr "" +msgstr "Cancelar" #: ../../library/curses.ascii.rst:75 msgid "End of medium" -msgstr "" +msgstr "Fim de mídia" #: ../../library/curses.ascii.rst:77 msgid "Substitute" -msgstr "" +msgstr "Substituir" #: ../../library/curses.ascii.rst:79 msgid "Escape" -msgstr "" +msgstr "Escapar" #: ../../library/curses.ascii.rst:81 msgid "File separator" -msgstr "" +msgstr "Separador de arquivos" #: ../../library/curses.ascii.rst:83 msgid "Group separator" -msgstr "" +msgstr "Separador de grupos" #: ../../library/curses.ascii.rst:85 msgid "Record separator, block-mode terminator" -msgstr "" +msgstr "Separador de registros, terminador de modo bloco" #: ../../library/curses.ascii.rst:87 msgid "Unit separator" -msgstr "Separador de Unidade" +msgstr "Separador de unidades" #: ../../library/curses.ascii.rst:89 msgid "Space" @@ -188,7 +192,7 @@ msgstr "Espaço" #: ../../library/curses.ascii.rst:91 msgid "Delete" -msgstr "Delete" +msgstr "Excluir" #: ../../library/curses.ascii.rst:94 msgid "" @@ -196,85 +200,108 @@ msgid "" "The mnemonics derive from teleprinter conventions that predate digital " "computers." msgstr "" +"Note que muitos deles têm pouca significância prática no uso moderno. Os " +"mnemônicos derivam de convenções de teleimpressoras que antecedem os " +"computadores digitais." #: ../../library/curses.ascii.rst:97 msgid "" "The module supplies the following functions, patterned on those in the " "standard C library:" msgstr "" +"O módulo fornece as seguintes funções, baseadas nas da biblioteca C padrão:" #: ../../library/curses.ascii.rst:103 msgid "" "Checks for an ASCII alphanumeric character; it is equivalent to ``isalpha(c) " "or isdigit(c)``." msgstr "" +"Verifica se há um caractere alfanumérico ASCII; equivale a ``isalpha(c) or " +"isdigit(c)``." #: ../../library/curses.ascii.rst:109 msgid "" "Checks for an ASCII alphabetic character; it is equivalent to ``isupper(c) " "or islower(c)``." msgstr "" +"Verifica se há um caractere alfabético ASCII; equivale a ``isupper(c) or " +"islower(c)``." #: ../../library/curses.ascii.rst:115 msgid "Checks for a character value that fits in the 7-bit ASCII set." msgstr "" +"Verifica se há um valor de caractere que se encaixa no conjunto ASCII de 7 " +"bits." #: ../../library/curses.ascii.rst:120 msgid "Checks for an ASCII whitespace character; space or horizontal tab." msgstr "" +"Verifica se há um caractere de espaço em branco ASCII; espaço ou tabulação " +"horizontal." #: ../../library/curses.ascii.rst:125 msgid "" "Checks for an ASCII control character (in the range 0x00 to 0x1f or 0x7f)." msgstr "" +"Verifica se há um caractere de controle ASCII (no intervalo de 0x00 a 0x1f " +"ou 0x7f)." #: ../../library/curses.ascii.rst:130 msgid "" "Checks for an ASCII decimal digit, ``'0'`` through ``'9'``. This is " "equivalent to ``c in string.digits``." msgstr "" +"Verifica se há um dígito decimal ASCII, ``'0'`` a ``'9'``. Isso equivale a " +"``c in string.digits``." #: ../../library/curses.ascii.rst:136 msgid "Checks for ASCII any printable character except space." -msgstr "" +msgstr "Verifica se há algum caractere ASCII imprimível, exceto espaço." #: ../../library/curses.ascii.rst:141 msgid "Checks for an ASCII lower-case character." -msgstr "" +msgstr "Verifica se há um caractere ASCII minúsculo." #: ../../library/curses.ascii.rst:146 msgid "Checks for any ASCII printable character including space." -msgstr "" +msgstr "Verifica se há algum caractere ASCII imprimível, incluindo espaço." #: ../../library/curses.ascii.rst:151 msgid "" "Checks for any printable ASCII character which is not a space or an " "alphanumeric character." msgstr "" +"Verifica se há algum caractere ASCII imprimível que não seja um espaço ou um " +"caractere alfanumérico." #: ../../library/curses.ascii.rst:157 msgid "" "Checks for ASCII white-space characters; space, line feed, carriage return, " "form feed, horizontal tab, vertical tab." msgstr "" +"Verifica caracteres de espaço em branco ASCII; espaço, quebra de linha, " +"retorno de carro, quebra de página, tabulação horizontal, tabulação vertical." #: ../../library/curses.ascii.rst:163 msgid "Checks for an ASCII uppercase letter." -msgstr "" +msgstr "Verifica se há uma letra maiúscula ASCII." #: ../../library/curses.ascii.rst:168 msgid "" "Checks for an ASCII hexadecimal digit. This is equivalent to ``c in string." "hexdigits``." msgstr "" +"Verifica se há um dígito hexadecimal ASCII. Isso equivale a ``c in string." +"hexdigits``." #: ../../library/curses.ascii.rst:174 msgid "Checks for an ASCII control character (ordinal values 0 to 31)." msgstr "" +"Verifica se há um caractere de controle ASCII (valores ordinais de 0 a 31)." #: ../../library/curses.ascii.rst:179 msgid "Checks for a non-ASCII character (ordinal values 0x80 and above)." -msgstr "" +msgstr "Verifica se há um caractere não ASCII (valores ordinais 0x80 e acima)." #: ../../library/curses.ascii.rst:181 msgid "" @@ -282,6 +309,9 @@ msgid "" "argument is a string, it is first converted using the built-in function :" "func:`ord`." msgstr "" +"Essas funções aceitam números inteiros ou strings de caracteres únicos; " +"quando o argumento é uma string, ele é primeiro convertido usando a função " +"embutida :func:`ord`." #: ../../library/curses.ascii.rst:184 msgid "" @@ -289,34 +319,45 @@ msgid "" "character of the string you pass in; they do not actually know anything " "about the host machine's character encoding." msgstr "" +"Observe que todas essas funções verificam valores de bits ordinais derivados " +"do caractere da string que você passa; elas não sabem nada sobre a " +"codificação de caracteres da máquina host." #: ../../library/curses.ascii.rst:188 msgid "" "The following two functions take either a single-character string or integer " "byte value; they return a value of the same type." msgstr "" +"As duas funções a seguir aceitam uma string de caractere único ou um valor " +"de byte inteiro; elas retornam um valor do mesmo tipo." #: ../../library/curses.ascii.rst:194 msgid "Return the ASCII value corresponding to the low 7 bits of *c*." -msgstr "" +msgstr "Retorna o valor ASCII correspondente aos 7 bits mais baixos de *c*." #: ../../library/curses.ascii.rst:199 msgid "" "Return the control character corresponding to the given character (the " "character bit value is bitwise-anded with 0x1f)." msgstr "" +"Retorna o caractere de controle correspondente ao caractere fornecido (é " +"feito um E bit a bit com 0x1f sobre o valor do bit do caractere)." #: ../../library/curses.ascii.rst:205 msgid "" "Return the 8-bit character corresponding to the given ASCII character (the " "character bit value is bitwise-ored with 0x80)." msgstr "" +"Retorna o caractere de 8 vits correspondente ao caractere ASCII fornecido (é " +"feito um OU bit a bit com 0x80 sobre o valor do bit do caractere)." #: ../../library/curses.ascii.rst:208 msgid "" "The following function takes either a single-character string or integer " "value; it returns a string." msgstr "" +"A função a seguir aceita uma string de um único caractere ou um valor " +"inteiro; ela retorna uma string." #: ../../library/curses.ascii.rst:218 msgid "" @@ -328,6 +369,13 @@ msgid "" "(0x80) set, the meta bit is stripped, the preceding rules applied, and " "``'!'`` prepended to the result." msgstr "" +"Retorna uma representação de string do caractere ASCII *c*. Se *c* for " +"imprimível, essa string é o próprio caractere. Se o caractere for um " +"caractere de controle (0x00--0x1f), a string consiste em um acento " +"circunflexo (``'^'``) seguido pela letra maiúscula correspondente. Se o " +"caractere for de exclusão ASCII (0x7f), a string é ``'^?'``. Se o caractere " +"tiver seu metabit (0x80) definido, o metabit é removido, as regras " +"precedentes são aplicadas e ``'!'`` é adicionado ao resultado." #: ../../library/curses.ascii.rst:228 msgid "" @@ -335,6 +383,9 @@ msgid "" "two ASCII control characters from 0 (NUL) to 0x1f (US), in order, plus the " "mnemonic ``SP`` for the space character." msgstr "" +"Um vetor de strings de 33 elementos que contém os mnemônicos ASCII para os " +"trinta e dois caracteres de controle ASCII de 0 (NUL) a 0x1f (US), em ordem, " +"mais o mnemônico ``SP`` para o caractere de espaço." #: ../../library/curses.ascii.rst:212 msgid "^ (caret)" @@ -342,7 +393,7 @@ msgstr "^ (circunflexo)" #: ../../library/curses.ascii.rst:212 msgid "in curses module" -msgstr "" +msgstr "no módulo curses" #: ../../library/curses.ascii.rst:212 msgid "! (exclamation)" diff --git a/library/curses.panel.po b/library/curses.panel.po index 4ac3ae233..d206dd290 100644 --- a/library/curses.panel.po +++ b/library/curses.panel.po @@ -1,33 +1,32 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Cássio Nomura , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:03+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/curses.panel.rst:2 msgid ":mod:`!curses.panel` --- A panel stack extension for curses" msgstr "" +":mod:`!curses.panel` --- Uma extensão de pilha de painéis para o curses" #: ../../library/curses.panel.rst:11 msgid "" @@ -35,6 +34,10 @@ msgid "" "on top of each other, and only the visible portions of each window will be " "displayed. Panels can be added, moved up or down in the stack, and removed." msgstr "" +"Painéis são janelas com o recurso adicional de profundidade, então eles " +"podem ser empilhados uns sobre os outros, e somente as partes visíveis de " +"cada janela serão exibidas. Painéis podem ser adicionados, movidos para cima " +"ou para baixo na pilha, e removidos." #: ../../library/curses.panel.rst:19 msgid "Functions" @@ -42,7 +45,7 @@ msgstr "Funções" #: ../../library/curses.panel.rst:21 msgid "The module :mod:`curses.panel` defines the following functions:" -msgstr "" +msgstr "O módulo :mod:`curses.panel` define as seguintes funções:" #: ../../library/curses.panel.rst:26 msgid "Returns the bottom panel in the panel stack." @@ -55,20 +58,26 @@ msgid "" "you don't, the panel object is garbage collected and removed from the panel " "stack." msgstr "" +"Retorna um objeto painel, associando-o à janela fornecida *win*. Esteja " +"ciente de que você precisa manter o objeto painel retornado referenciado " +"explicitamente. Se não fizer isso, o objeto painel será coletado como lixo e " +"removido da pilha de painéis." #: ../../library/curses.panel.rst:38 msgid "Returns the top panel in the panel stack." -msgstr "" +msgstr "Retorna o painel superior da pilha de painéis." #: ../../library/curses.panel.rst:43 msgid "" "Updates the virtual screen after changes in the panel stack. This does not " "call :func:`curses.doupdate`, so you'll have to do this yourself." msgstr "" +"Atualiza a tela virtual após alterações na pilha de painéis. Isso não chama :" +"func:`curses.doupdate`, então você terá que fazer isso sozinho." #: ../../library/curses.panel.rst:50 msgid "Panel Objects" -msgstr "Objetos Panel" +msgstr "Objetos painel" #: ../../library/curses.panel.rst:52 msgid "" @@ -77,14 +86,18 @@ msgid "" "determines the content, while the panel methods are responsible for the " "window's depth in the panel stack." msgstr "" +"Objetos painel, como retornados por :func:`new_panel` acima, são janelas com " +"uma ordem de empilhamento. Há sempre uma janela associada a um painel que " +"determina o conteúdo, enquanto os métodos de painel são responsáveis pela " +"profundidade da janela na pilha de painéis." #: ../../library/curses.panel.rst:57 msgid "Panel objects have the following methods:" -msgstr "Objetos Panel possuem os seguintes métodos:" +msgstr "Objetos painel possuem os seguintes métodos:" #: ../../library/curses.panel.rst:62 msgid "Returns the panel above the current panel." -msgstr "" +msgstr "Retorna o painel acima do painel atual." #: ../../library/curses.panel.rst:67 msgid "Returns the panel below the current panel." @@ -92,40 +105,47 @@ msgstr "Retorna o painel abaixo do painel atual." #: ../../library/curses.panel.rst:72 msgid "Push the panel to the bottom of the stack." -msgstr "" +msgstr "Insere o painel para o fundo da pilha." #: ../../library/curses.panel.rst:77 msgid "" "Returns ``True`` if the panel is hidden (not visible), ``False`` otherwise." msgstr "" +"Retorna ``True`` se o painel estiver oculto (não visível), ``False`` caso " +"contrário." #: ../../library/curses.panel.rst:82 msgid "" "Hide the panel. This does not delete the object, it just makes the window on " "screen invisible." msgstr "" +"Oculta o painel. Isso não exclui o objeto, apenas torna a janela invisível " +"na tela." #: ../../library/curses.panel.rst:88 msgid "Move the panel to the screen coordinates ``(y, x)``." -msgstr "" +msgstr "Move o painel para as coordenadas ``(y, x)`` da tela." #: ../../library/curses.panel.rst:93 msgid "Change the window associated with the panel to the window *win*." -msgstr "" +msgstr "Altera a janela associada ao painel para a janela *win*." #: ../../library/curses.panel.rst:98 msgid "" "Set the panel's user pointer to *obj*. This is used to associate an " "arbitrary piece of data with the panel, and can be any Python object." msgstr "" +"Define o ponteiro do usuário do painel para *obj*. Isso é usado para " +"associar um pedaço arbitrário de dados ao painel, e pode ser qualquer objeto " +"Python." #: ../../library/curses.panel.rst:104 msgid "Display the panel (which might have been hidden)." -msgstr "" +msgstr "Exibe o painel (que pode estar oculto)." #: ../../library/curses.panel.rst:109 msgid "Push panel to the top of the stack." -msgstr "" +msgstr "Insere o painel para o topo da pilha." #: ../../library/curses.panel.rst:114 msgid "" @@ -135,4 +155,4 @@ msgstr "" #: ../../library/curses.panel.rst:119 msgid "Returns the window object associated with the panel." -msgstr "" +msgstr "Retorna o objeto de janela associado ao painel." diff --git a/library/curses.po b/library/curses.po index 6c20bce03..2aeb429d4 100644 --- a/library/curses.po +++ b/library/curses.po @@ -1,34 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Danilo Lima , 2021 -# Risaffi , 2021 -# Welington Carlos , 2021 -# i17obot , 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# (Douglas da Silva) , 2021 -# Vitor Buxbaum Orlandi, 2023 -# Leandro Cavalcante Damascena , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:03+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -58,21 +49,17 @@ msgid "" "curses library hosted on Linux and the BSD variants of Unix." msgstr "" -#: ../../includes/wasm-ios-notavail.rst:3 -msgid ":ref:`Availability `: not WASI, not iOS." -msgstr ":ref:`Disponibilidade `: não WASI, não iOS." +#: ../../includes/wasm-mobile-notavail.rst:3 +msgid "Availability" +msgstr "Disponibilidade" -#: ../../includes/wasm-ios-notavail.rst:5 +#: ../../includes/wasm-mobile-notavail.rst:5 msgid "" -"This module does not work or is not available on WebAssembly platforms, or " -"on iOS. See :ref:`wasm-availability` for more information on WASM " -"availability; see :ref:`iOS-availability` for more information on iOS " -"availability." +"This module is not supported on :ref:`mobile platforms ` or :ref:`WebAssembly platforms `." msgstr "" -"Este módulo não funciona ou não está disponível nas plataformas WebAssembly " -"ou iOS. Veja :ref:`wasm-availability` para mais informações sobre a " -"disponibilidade no WASM; veja :ref:`iOS-availability` para mais informações " -"sobre a disponibilidade no iOS." +"Este módulo não tem suporte em :ref:`plataformas móveis ` ou :ref:`plataformas WebAssembly `." #: ../../library/curses.rst:28 msgid "" @@ -1829,7 +1816,7 @@ msgstr "" #: ../../library/curses.rst:1514 msgid "Cancel" -msgstr "" +msgstr "Cancelar" #: ../../library/curses.rst:1516 msgid "Close" diff --git a/library/custominterp.po b/library/custominterp.po index 2ccd372fe..169168306 100644 --- a/library/custominterp.po +++ b/library/custominterp.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:03+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/dataclasses.po b/library/dataclasses.po index 7e3c0767e..4eee1024a 100644 --- a/library/dataclasses.po +++ b/library/dataclasses.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Vinícius Muniz de Melo , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:03+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-04-18 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -56,10 +51,34 @@ msgstr "" "Variáveis-membro a serem usadas nesses métodos gerados são definidas usando " "as anotações de tipo da :pep:`526`. Por exemplo, esse código::" +#: ../../library/dataclasses.rst:22 +msgid "" +"from dataclasses import dataclass\n" +"\n" +"@dataclass\n" +"class InventoryItem:\n" +" \"\"\"Class for keeping track of an item in inventory.\"\"\"\n" +" name: str\n" +" unit_price: float\n" +" quantity_on_hand: int = 0\n" +"\n" +" def total_cost(self) -> float:\n" +" return self.unit_price * self.quantity_on_hand" +msgstr "" + #: ../../library/dataclasses.rst:34 msgid "will add, among other things, a :meth:`!__init__` that looks like::" msgstr "adicionará, entre outras coisas, um :meth:`!__init__` como esse::" +#: ../../library/dataclasses.rst:36 +msgid "" +"def __init__(self, name: str, unit_price: float, quantity_on_hand: int = " +"0):\n" +" self.name = name\n" +" self.unit_price = unit_price\n" +" self.quantity_on_hand = quantity_on_hand" +msgstr "" + #: ../../library/dataclasses.rst:41 msgid "" "Note that this method is automatically added to the class: it is not " @@ -124,6 +143,23 @@ msgstr "" "parâmetros, ele age como se tivesse os valores padrão documentados nessa " "assinatura. Ou seja, esses três usos de ``@dataclass`` são equivalentes::" +#: ../../library/dataclasses.rst:74 +msgid "" +"@dataclass\n" +"class C:\n" +" ...\n" +"\n" +"@dataclass()\n" +"class C:\n" +" ...\n" +"\n" +"@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, " +"frozen=False,\n" +" match_args=True, kw_only=False, slots=False, weakref_slot=False)\n" +"class C:\n" +" ..." +msgstr "" + #: ../../library/dataclasses.rst:87 msgid "The parameters to ``@dataclass`` are:" msgstr "Os parâmetros do ``@dataclass`` são:" @@ -214,20 +250,13 @@ msgstr "" #: ../../library/dataclasses.rst:127 msgid "" -":meth:`!__hash__` is used by built-in :meth:`hash()`, and when objects are " +":meth:`!__hash__` is used by built-in :meth:`hash`, and when objects are " "added to hashed collections such as dictionaries and sets. Having a :meth:`!" "__hash__` implies that instances of the class are immutable. Mutability is a " "complicated property that depends on the programmer's intent, the existence " "and behavior of :meth:`!__eq__`, and the values of the *eq* and *frozen* " "flags in the ``@dataclass`` decorator." msgstr "" -":meth:`!__hash__` é usado para prover o método embutido :meth:`hash()`, e " -"quando objetos são adicionados a coleções do tipo dicionário ou conjunto. " -"Ter um método :meth:`!__hash__` implica que instâncias da classe serão " -"imutáveis. Mutabilidade é uma propriedade complicada, que depende da " -"intenção do programador, da existência e comportamento do método :meth:`!" -"__eq__`, e dos valores dos parâmetros *eq* e *frozen* no decorador " -"``@dataclass``." #: ../../library/dataclasses.rst:134 msgid "" @@ -305,16 +334,12 @@ msgstr "" #: ../../library/dataclasses.rst:165 msgid "" "*match_args*: If true (the default is ``True``), the :attr:`~object." -"__match_args__` tuple will be created from the list of parameters to the " -"generated :meth:`~object.__init__` method (even if :meth:`!__init__` is not " -"generated, see above). If false, or if :attr:`!__match_args__` is already " -"defined in the class, then :attr:`!__match_args__` will not be generated." +"__match_args__` tuple will be created from the list of non keyword-only " +"parameters to the generated :meth:`~object.__init__` method (even if :meth:`!" +"__init__` is not generated, see above). If false, or if :attr:`!" +"__match_args__` is already defined in the class, then :attr:`!" +"__match_args__` will not be generated." msgstr "" -"*match_args*: Se verdadeiro (o padrão é ``True``), a tupla :attr:`~object." -"__match_args__` será criada a partir da lista de parâmetros para o método :" -"meth:`~object.__init__` gerado (mesmo se :meth:`!__init__` não for gerado, " -"veja acima). Se falso, ou se :attr:`!__match_args__` já estiver definido na " -"classe, então :attr:`!__match_args__` não será gerado." #: ../../library/dataclasses.rst:174 msgid "" @@ -322,31 +347,39 @@ msgid "" "marked as keyword-only. If a field is marked as keyword-only, then the only " "effect is that the :meth:`~object.__init__` parameter generated from a " "keyword-only field must be specified with a keyword when :meth:`!__init__` " -"is called. There is no effect on any other aspect of dataclasses. See the :" -"term:`parameter` glossary entry for details. Also see the :const:`KW_ONLY` " -"section." +"is called. See the :term:`parameter` glossary entry for details. Also see " +"the :const:`KW_ONLY` section." msgstr "" -"*kw_only*: Se verdadeiro (o valor padrão é ``False``), então todos os campos " -"serão marcados como somente-nomeado. Se um campo for marcado como somente-" -"nomeado, então o único efeito é que o parâmetro :meth:`~object.__init__` " -"gerado a partir de um campo somente-nomeado deve ser especificado com um " -"campo quando :meth:`!__init__` é chamado. Não há efeito em nenhum outro " -"aspecto das classes de dados. Veja a entrada :term:`parâmetro` do glossário " -"para detalhes. Veja também a seção :const:`KW_ONLY`." -#: ../../library/dataclasses.rst:185 +#: ../../library/dataclasses.rst:182 +msgid "Keyword-only fields are not included in :attr:`!__match_args__`." +msgstr "" + +#: ../../library/dataclasses.rst:186 msgid "" "*slots*: If true (the default is ``False``), :attr:`~object.__slots__` " "attribute will be generated and new class will be returned instead of the " "original one. If :attr:`!__slots__` is already defined in the class, then :" -"exc:`TypeError` is raised. Calling no-arg :func:`super` in dataclasses using " -"``slots=True`` will result in the following exception being raised: " -"``TypeError: super(type, obj): obj must be an instance or subtype of type``. " -"The two-arg :func:`super` is a valid workaround. See :gh:`90562` for full " -"details." +"exc:`TypeError` is raised." msgstr "" -#: ../../library/dataclasses.rst:195 +#: ../../library/dataclasses.rst:192 +msgid "" +"Calling no-arg :func:`super` in dataclasses using ``slots=True`` will result " +"in the following exception being raised: ``TypeError: super(type, obj): obj " +"must be an instance or subtype of type``. The two-arg :func:`super` is a " +"valid workaround. See :gh:`90562` for full details." +msgstr "" + +#: ../../library/dataclasses.rst:199 +msgid "" +"Passing parameters to a base class :meth:`~object.__init_subclass__` when " +"using ``slots=True`` will result in a :exc:`TypeError`. Either use " +"``__init_subclass__`` with no parameters or use default values as a " +"workaround. See :gh:`91126` for full details." +msgstr "" + +#: ../../library/dataclasses.rst:207 msgid "" "If a field name is already included in the :attr:`!__slots__` of a base " "class, it will not be included in the generated :attr:`!__slots__` to " @@ -356,15 +389,15 @@ msgid "" "`!__slots__` may be any iterable, but *not* an iterator." msgstr "" -#: ../../library/dataclasses.rst:205 +#: ../../library/dataclasses.rst:217 msgid "" "*weakref_slot*: If true (the default is ``False``), add a slot named " -"\"__weakref__\", which is required to make an instance weakref-able. It is " -"an error to specify ``weakref_slot=True`` without also specifying " -"``slots=True``." +"\"__weakref__\", which is required to make an instance :func:`weakref-able " +"`. It is an error to specify ``weakref_slot=True`` without also " +"specifying ``slots=True``." msgstr "" -#: ../../library/dataclasses.rst:212 +#: ../../library/dataclasses.rst:225 msgid "" "``field``\\s may optionally specify a default value, using normal Python " "syntax::" @@ -372,13 +405,25 @@ msgstr "" "``field``\\s pode opcionalmente especificar um valor padrão, usando sintaxe " "Python normal::" -#: ../../library/dataclasses.rst:220 +#: ../../library/dataclasses.rst:228 +msgid "" +"@dataclass\n" +"class C:\n" +" a: int # 'a' has no default value\n" +" b: int = 0 # assign a default value for 'b'" +msgstr "" + +#: ../../library/dataclasses.rst:233 msgid "" "In this example, both :attr:`!a` and :attr:`!b` will be included in the " "added :meth:`~object.__init__` method, which will be defined as::" msgstr "" -#: ../../library/dataclasses.rst:225 +#: ../../library/dataclasses.rst:236 +msgid "def __init__(self, a: int, b: int = 0):" +msgstr "" + +#: ../../library/dataclasses.rst:238 msgid "" ":exc:`TypeError` will be raised if a field without a default value follows a " "field with a default value. This is true whether this occurs in a single " @@ -388,7 +433,7 @@ msgstr "" "após um campo com valor padrão. Isso é verdadeiro se ocorrer numa classe " "simples, ou como resultado de uma herança de classe." -#: ../../library/dataclasses.rst:231 +#: ../../library/dataclasses.rst:244 msgid "" "For common and simple use cases, no other functionality is required. There " "are, however, some dataclass features that require additional per-field " @@ -397,7 +442,17 @@ msgid "" "function. For example::" msgstr "" -#: ../../library/dataclasses.rst:244 +#: ../../library/dataclasses.rst:250 +msgid "" +"@dataclass\n" +"class C:\n" +" mylist: list[int] = field(default_factory=list)\n" +"\n" +"c = C()\n" +"c.mylist += [1, 2, 3]" +msgstr "" + +#: ../../library/dataclasses.rst:257 msgid "" "As shown above, the :const:`MISSING` value is a sentinel object used to " "detect if some parameters are provided by the user. This sentinel is used " @@ -410,18 +465,18 @@ msgstr "" "com um significado distinto. Nenhum código deve usar diretamente o valor :" "const:`MISSING`." -#: ../../library/dataclasses.rst:249 +#: ../../library/dataclasses.rst:262 msgid "The parameters to :func:`!field` are:" msgstr "" -#: ../../library/dataclasses.rst:251 +#: ../../library/dataclasses.rst:264 msgid "" "*default*: If provided, this will be the default value for this field. This " "is needed because the :func:`!field` call itself replaces the normal " "position of the default value." msgstr "" -#: ../../library/dataclasses.rst:255 +#: ../../library/dataclasses.rst:268 msgid "" "*default_factory*: If provided, it must be a zero-argument callable that " "will be called when a default value is needed for this field. Among other " @@ -430,28 +485,30 @@ msgid "" "*default_factory*." msgstr "" -#: ../../library/dataclasses.rst:261 +#: ../../library/dataclasses.rst:274 msgid "" "*init*: If true (the default), this field is included as a parameter to the " "generated :meth:`~object.__init__` method." msgstr "" -#: ../../library/dataclasses.rst:264 +#: ../../library/dataclasses.rst:277 msgid "" "*repr*: If true (the default), this field is included in the string returned " "by the generated :meth:`~object.__repr__` method." msgstr "" -#: ../../library/dataclasses.rst:267 +#: ../../library/dataclasses.rst:280 msgid "" "*hash*: This can be a bool or ``None``. If true, this field is included in " -"the generated :meth:`~object.__hash__` method. If ``None`` (the default), " -"use the value of *compare*: this would normally be the expected behavior. A " -"field should be considered in the hash if it's used for comparisons. " -"Setting this value to anything other than ``None`` is discouraged." +"the generated :meth:`~object.__hash__` method. If false, this field is " +"excluded from the generated :meth:`~object.__hash__`. If ``None`` (the " +"default), use the value of *compare*: this would normally be the expected " +"behavior, since a field should be included in the hash if it's used for " +"comparisons. Setting this value to anything other than ``None`` is " +"discouraged." msgstr "" -#: ../../library/dataclasses.rst:274 +#: ../../library/dataclasses.rst:288 msgid "" "One possible reason to set ``hash=False`` but ``compare=True`` would be if a " "field is expensive to compute a hash value for, that field is needed for " @@ -465,14 +522,14 @@ msgstr "" "de hash do tipo. Mesmo que um campo seja excluído do hash, ele ainda será " "usado para comparações." -#: ../../library/dataclasses.rst:280 +#: ../../library/dataclasses.rst:294 msgid "" "*compare*: If true (the default), this field is included in the generated " "equality and comparison methods (:meth:`~object.__eq__`, :meth:`~object." "__gt__`, et al.)." msgstr "" -#: ../../library/dataclasses.rst:284 +#: ../../library/dataclasses.rst:298 msgid "" "*metadata*: This can be a mapping or ``None``. ``None`` is treated as an " "empty dict. This value is wrapped in :func:`~types.MappingProxyType` to " @@ -482,13 +539,17 @@ msgid "" "namespace in the metadata." msgstr "" -#: ../../library/dataclasses.rst:292 +#: ../../library/dataclasses.rst:306 msgid "" "*kw_only*: If true, this field will be marked as keyword-only. This is used " "when the generated :meth:`~object.__init__` method's parameters are computed." msgstr "" -#: ../../library/dataclasses.rst:298 +#: ../../library/dataclasses.rst:310 +msgid "Keyword-only fields are also not included in :attr:`!__match_args__`." +msgstr "" + +#: ../../library/dataclasses.rst:314 msgid "" "If the default value of a field is specified by a call to :func:`!field`, " "then the class attribute for this field will be replaced by the specified " @@ -499,14 +560,24 @@ msgid "" "specified. For example, after::" msgstr "" -#: ../../library/dataclasses.rst:314 +#: ../../library/dataclasses.rst:323 +msgid "" +"@dataclass\n" +"class C:\n" +" x: int\n" +" y: int = field(repr=False)\n" +" z: int = field(repr=False, default=10)\n" +" t: int = 20" +msgstr "" + +#: ../../library/dataclasses.rst:330 msgid "" "The class attribute :attr:`!C.z` will be ``10``, the class attribute :attr:`!" "C.t` will be ``20``, and the class attributes :attr:`!C.x` and :attr:`!C.y` " "will not be set." msgstr "" -#: ../../library/dataclasses.rst:320 +#: ../../library/dataclasses.rst:336 msgid "" ":class:`!Field` objects describe each defined field. These objects are " "created internally, and are returned by the :func:`fields` module-level " @@ -514,22 +585,22 @@ msgid "" "directly. Its documented attributes are:" msgstr "" -#: ../../library/dataclasses.rst:325 +#: ../../library/dataclasses.rst:341 msgid ":attr:`!name`: The name of the field." msgstr "" -#: ../../library/dataclasses.rst:326 +#: ../../library/dataclasses.rst:342 msgid ":attr:`!type`: The type of the field." msgstr "" -#: ../../library/dataclasses.rst:327 +#: ../../library/dataclasses.rst:343 msgid "" ":attr:`!default`, :attr:`!default_factory`, :attr:`!init`, :attr:`!repr`, :" "attr:`!hash`, :attr:`!compare`, :attr:`!metadata`, and :attr:`!kw_only` have " "the identical meaning and values as they do in the :func:`field` function." msgstr "" -#: ../../library/dataclasses.rst:331 +#: ../../library/dataclasses.rst:347 msgid "" "Other attributes may exist, but they are private and must not be inspected " "or relied on." @@ -537,7 +608,16 @@ msgstr "" "Outros atributos podem existir, mas são privados e não devem ser " "inspecionados ou confiáveis." -#: ../../library/dataclasses.rst:336 +#: ../../library/dataclasses.rst:352 +msgid "" +"``InitVar[T]`` type annotations describe variables that are :ref:`init-only " +"`. Fields annotated with :class:`!InitVar` " +"are considered pseudo-fields, and thus are neither returned by the :func:" +"`fields` function nor used in any way except adding them as parameters to :" +"meth:`~object.__init__` and an optional :meth:`__post_init__`." +msgstr "" + +#: ../../library/dataclasses.rst:361 msgid "" "Returns a tuple of :class:`Field` objects that define the fields for this " "dataclass. Accepts either a dataclass, or an instance of a dataclass. " @@ -550,7 +630,7 @@ msgstr "" "instância de uma. Não retorna pseudocampos que são ``ClassVar`` ou " "``InitVar``." -#: ../../library/dataclasses.rst:343 +#: ../../library/dataclasses.rst:368 msgid "" "Converts the dataclass *obj* to a dict (by using the factory function " "*dict_factory*). Each dataclass is converted to a dict of its fields, as " @@ -558,21 +638,43 @@ msgid "" "into. Other objects are copied with :func:`copy.deepcopy`." msgstr "" -#: ../../library/dataclasses.rst:349 +#: ../../library/dataclasses.rst:374 msgid "Example of using :func:`!asdict` on nested dataclasses::" msgstr "" -#: ../../library/dataclasses.rst:366 ../../library/dataclasses.rst:386 +#: ../../library/dataclasses.rst:376 +msgid "" +"@dataclass\n" +"class Point:\n" +" x: int\n" +" y: int\n" +"\n" +"@dataclass\n" +"class C:\n" +" mylist: list[Point]\n" +"\n" +"p = Point(10, 20)\n" +"assert asdict(p) == {'x': 10, 'y': 20}\n" +"\n" +"c = C([Point(0, 0), Point(10, 4)])\n" +"assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}" +msgstr "" + +#: ../../library/dataclasses.rst:391 ../../library/dataclasses.rst:411 msgid "To create a shallow copy, the following workaround may be used::" msgstr "" "Para criar uma cópia rasa, a seguinte solução alternativa pode ser usada::" -#: ../../library/dataclasses.rst:370 +#: ../../library/dataclasses.rst:393 +msgid "{field.name: getattr(obj, field.name) for field in fields(obj)}" +msgstr "" + +#: ../../library/dataclasses.rst:395 msgid "" ":func:`!asdict` raises :exc:`TypeError` if *obj* is not a dataclass instance." msgstr "" -#: ../../library/dataclasses.rst:375 +#: ../../library/dataclasses.rst:400 msgid "" "Converts the dataclass *obj* to a tuple (by using the factory function " "*tuple_factory*). Each dataclass is converted to a tuple of its field " @@ -580,17 +682,27 @@ msgid "" "objects are copied with :func:`copy.deepcopy`." msgstr "" -#: ../../library/dataclasses.rst:381 +#: ../../library/dataclasses.rst:406 msgid "Continuing from the previous example::" msgstr "Continuando a partir do exemplo anterior::" -#: ../../library/dataclasses.rst:390 +#: ../../library/dataclasses.rst:408 +msgid "" +"assert astuple(p) == (10, 20)\n" +"assert astuple(c) == ([(0, 0), (10, 4)],)" +msgstr "" + +#: ../../library/dataclasses.rst:413 +msgid "tuple(getattr(obj, field.name) for field in dataclasses.fields(obj))" +msgstr "" + +#: ../../library/dataclasses.rst:415 msgid "" ":func:`!astuple` raises :exc:`TypeError` if *obj* is not a dataclass " "instance." msgstr "" -#: ../../library/dataclasses.rst:395 +#: ../../library/dataclasses.rst:420 msgid "" "Creates a new dataclass with name *cls_name*, fields as defined in *fields*, " "base classes as given in *bases*, and initialized with a namespace as given " @@ -602,13 +714,13 @@ msgid "" "`@dataclass `." msgstr "" -#: ../../library/dataclasses.rst:405 +#: ../../library/dataclasses.rst:430 msgid "" "If *module* is defined, the :attr:`!__module__` attribute of the dataclass " "is set to that value. By default, it is set to the module name of the caller." msgstr "" -#: ../../library/dataclasses.rst:409 +#: ../../library/dataclasses.rst:434 msgid "" "This function is not strictly required, because any Python mechanism for " "creating a new class with :attr:`!__annotations__` can then apply the :func:" @@ -616,11 +728,32 @@ msgid "" "This function is provided as a convenience. For example::" msgstr "" -#: ../../library/dataclasses.rst:421 +#: ../../library/dataclasses.rst:440 +msgid "" +"C = make_dataclass('C',\n" +" [('x', int),\n" +" 'y',\n" +" ('z', int, field(default=5))],\n" +" namespace={'add_one': lambda self: self.x + 1})" +msgstr "" + +#: ../../library/dataclasses.rst:446 msgid "Is equivalent to::" msgstr "É equivalente a::" -#: ../../library/dataclasses.rst:434 +#: ../../library/dataclasses.rst:448 +msgid "" +"@dataclass\n" +"class C:\n" +" x: int\n" +" y: 'typing.Any'\n" +" z: int = 5\n" +"\n" +" def add_one(self):\n" +" return self.x + 1" +msgstr "" + +#: ../../library/dataclasses.rst:459 msgid "" "Creates a new object of the same type as *obj*, replacing fields with values " "from *changes*. If *obj* is not a Data Class, raises :exc:`TypeError`. If " @@ -628,27 +761,27 @@ msgid "" "`TypeError`." msgstr "" -#: ../../library/dataclasses.rst:439 +#: ../../library/dataclasses.rst:464 msgid "" "The newly returned object is created by calling the :meth:`~object.__init__` " "method of the dataclass. This ensures that :meth:`__post_init__`, if " "present, is also called." msgstr "" -#: ../../library/dataclasses.rst:443 +#: ../../library/dataclasses.rst:468 msgid "" "Init-only variables without default values, if any exist, must be specified " "on the call to :func:`!replace` so that they can be passed to :meth:`!" "__init__` and :meth:`__post_init__`." msgstr "" -#: ../../library/dataclasses.rst:447 +#: ../../library/dataclasses.rst:472 msgid "" "It is an error for *changes* to contain any fields that are defined as " "having ``init=False``. A :exc:`ValueError` will be raised in this case." msgstr "" -#: ../../library/dataclasses.rst:451 +#: ../../library/dataclasses.rst:476 msgid "" "Be forewarned about how ``init=False`` fields work during a call to :func:`!" "replace`. They are not copied from the source object, but rather are " @@ -659,19 +792,19 @@ msgid "" "instance copying." msgstr "" -#: ../../library/dataclasses.rst:460 +#: ../../library/dataclasses.rst:485 msgid "" "Dataclass instances are also supported by generic function :func:`copy." "replace`." msgstr "" -#: ../../library/dataclasses.rst:464 +#: ../../library/dataclasses.rst:489 msgid "" "Return ``True`` if its parameter is a dataclass (including subclasses of a " "dataclass) or an instance of one, otherwise return ``False``." msgstr "" -#: ../../library/dataclasses.rst:467 +#: ../../library/dataclasses.rst:492 msgid "" "If you need to know if a class is an instance of a dataclass (and not a " "dataclass itself), then add a further check for ``not isinstance(obj, " @@ -681,11 +814,17 @@ msgstr "" "dataclass de fato), então adicione uma verificação para ``not " "isinstance(obj, type)``::" -#: ../../library/dataclasses.rst:476 +#: ../../library/dataclasses.rst:496 +msgid "" +"def is_dataclass_instance(obj):\n" +" return is_dataclass(obj) and not isinstance(obj, type)" +msgstr "" + +#: ../../library/dataclasses.rst:501 msgid "A sentinel value signifying a missing default or default_factory." msgstr "" -#: ../../library/dataclasses.rst:480 +#: ../../library/dataclasses.rst:505 msgid "" "A sentinel value used as a type annotation. Any fields after a pseudo-field " "with the type of :const:`!KW_ONLY` are marked as keyword-only fields. Note " @@ -696,30 +835,42 @@ msgid "" "the class is instantiated." msgstr "" -#: ../../library/dataclasses.rst:489 +#: ../../library/dataclasses.rst:514 msgid "" "In this example, the fields ``y`` and ``z`` will be marked as keyword-only " "fields::" msgstr "" -#: ../../library/dataclasses.rst:500 +#: ../../library/dataclasses.rst:516 +msgid "" +"@dataclass\n" +"class Point:\n" +" x: float\n" +" _: KW_ONLY\n" +" y: float\n" +" z: float\n" +"\n" +"p = Point(0, y=1.5, z=2.0)" +msgstr "" + +#: ../../library/dataclasses.rst:525 msgid "" "In a single dataclass, it is an error to specify more than one field whose " "type is :const:`!KW_ONLY`." msgstr "" -#: ../../library/dataclasses.rst:507 +#: ../../library/dataclasses.rst:532 msgid "" "Raised when an implicitly defined :meth:`~object.__setattr__` or :meth:" "`~object.__delattr__` is called on a dataclass which was defined with " "``frozen=True``. It is a subclass of :exc:`AttributeError`." msgstr "" -#: ../../library/dataclasses.rst:514 +#: ../../library/dataclasses.rst:539 msgid "Post-init processing" msgstr "Processamento pós-inicialização" -#: ../../library/dataclasses.rst:518 +#: ../../library/dataclasses.rst:543 msgid "" "When defined on the class, it will be called by the generated :meth:`~object." "__init__`, normally as :meth:`!self.__post_init__`. However, if any " @@ -729,13 +880,25 @@ msgid "" "automatically be called." msgstr "" -#: ../../library/dataclasses.rst:525 +#: ../../library/dataclasses.rst:550 msgid "" "Among other uses, this allows for initializing field values that depend on " "one or more other fields. For example::" msgstr "" -#: ../../library/dataclasses.rst:537 +#: ../../library/dataclasses.rst:553 +msgid "" +"@dataclass\n" +"class C:\n" +" a: float\n" +" b: float\n" +" c: float = field(init=False)\n" +"\n" +" def __post_init__(self):\n" +" self.c = self.a + self.b" +msgstr "" + +#: ../../library/dataclasses.rst:562 msgid "" "The :meth:`~object.__init__` method generated by :func:`@dataclass " "` does not call base class :meth:`!__init__` methods. If the base " @@ -743,25 +906,40 @@ msgid "" "call this method in a :meth:`__post_init__` method::" msgstr "" -#: ../../library/dataclasses.rst:554 +#: ../../library/dataclasses.rst:567 +msgid "" +"class Rectangle:\n" +" def __init__(self, height, width):\n" +" self.height = height\n" +" self.width = width\n" +"\n" +"@dataclass\n" +"class Square(Rectangle):\n" +" side: float\n" +"\n" +" def __post_init__(self):\n" +" super().__init__(self.side, self.side)" +msgstr "" + +#: ../../library/dataclasses.rst:579 msgid "" "Note, however, that in general the dataclass-generated :meth:`!__init__` " "methods don't need to be called, since the derived dataclass will take care " "of initializing all fields of any base class that is a dataclass itself." msgstr "" -#: ../../library/dataclasses.rst:558 +#: ../../library/dataclasses.rst:583 msgid "" "See the section below on init-only variables for ways to pass parameters to :" "meth:`!__post_init__`. Also see the warning about how :func:`replace` " "handles ``init=False`` fields." msgstr "" -#: ../../library/dataclasses.rst:565 +#: ../../library/dataclasses.rst:590 msgid "Class variables" msgstr "Variáveis de classe" -#: ../../library/dataclasses.rst:567 +#: ../../library/dataclasses.rst:592 msgid "" "One of the few places where :func:`@dataclass ` actually inspects " "the type of a field is to determine if a field is a class variable as " @@ -772,16 +950,16 @@ msgid "" "`fields` function." msgstr "" -#: ../../library/dataclasses.rst:578 +#: ../../library/dataclasses.rst:603 msgid "Init-only variables" msgstr "Variáveis de inicialização apenas" -#: ../../library/dataclasses.rst:580 +#: ../../library/dataclasses.rst:605 msgid "" "Another place where :func:`@dataclass ` inspects a type " "annotation is to determine if a field is an init-only variable. It does " -"this by seeing if the type of a field is of type ``dataclasses.InitVar``. " -"If a field is an ``InitVar``, it is considered a pseudo-field called an init-" +"this by seeing if the type of a field is of type :class:`InitVar`. If a " +"field is an :class:`InitVar`, it is considered a pseudo-field called an init-" "only field. As it is not a true field, it is not returned by the module-" "level :func:`fields` function. Init-only fields are added as parameters to " "the generated :meth:`~object.__init__` method, and are passed to the " @@ -789,23 +967,38 @@ msgid "" "dataclasses." msgstr "" -#: ../../library/dataclasses.rst:590 +#: ../../library/dataclasses.rst:615 msgid "" "For example, suppose a field will be initialized from a database, if a value " "is not provided when creating the class::" msgstr "" -#: ../../library/dataclasses.rst:605 +#: ../../library/dataclasses.rst:618 +msgid "" +"@dataclass\n" +"class C:\n" +" i: int\n" +" j: int | None = None\n" +" database: InitVar[DatabaseType | None] = None\n" +"\n" +" def __post_init__(self, database):\n" +" if self.j is None and database is not None:\n" +" self.j = database.lookup('j')\n" +"\n" +"c = C(10, database=my_database)" +msgstr "" + +#: ../../library/dataclasses.rst:630 msgid "" "In this case, :func:`fields` will return :class:`Field` objects for :attr:`!" "i` and :attr:`!j`, but not for :attr:`!database`." msgstr "" -#: ../../library/dataclasses.rst:611 +#: ../../library/dataclasses.rst:636 msgid "Frozen instances" msgstr "" -#: ../../library/dataclasses.rst:613 +#: ../../library/dataclasses.rst:638 msgid "" "It is not possible to create truly immutable Python objects. However, by " "passing ``frozen=True`` to the :func:`@dataclass ` decorator you " @@ -814,18 +1007,18 @@ msgid "" "methods will raise a :exc:`FrozenInstanceError` when invoked." msgstr "" -#: ../../library/dataclasses.rst:619 +#: ../../library/dataclasses.rst:644 msgid "" "There is a tiny performance penalty when using ``frozen=True``: :meth:" "`~object.__init__` cannot use simple assignment to initialize fields, and " "must use :meth:`!object.__setattr__`." msgstr "" -#: ../../library/dataclasses.rst:628 +#: ../../library/dataclasses.rst:653 msgid "Inheritance" msgstr "Herança" -#: ../../library/dataclasses.rst:630 +#: ../../library/dataclasses.rst:655 msgid "" "When the dataclass is being created by the :func:`@dataclass ` " "decorator, it looks through all of the class's base classes in reverse MRO " @@ -837,24 +1030,41 @@ msgid "" "order, derived classes override base classes. An example::" msgstr "" -#: ../../library/dataclasses.rst:650 +#: ../../library/dataclasses.rst:665 +msgid "" +"@dataclass\n" +"class Base:\n" +" x: Any = 15.0\n" +" y: int = 0\n" +"\n" +"@dataclass\n" +"class C(Base):\n" +" z: int = 10\n" +" x: int = 15" +msgstr "" + +#: ../../library/dataclasses.rst:675 msgid "" "The final list of fields is, in order, :attr:`!x`, :attr:`!y`, :attr:`!z`. " "The final type of :attr:`!x` is :class:`int`, as specified in class :class:`!" "C`." msgstr "" -#: ../../library/dataclasses.rst:653 +#: ../../library/dataclasses.rst:678 msgid "" "The generated :meth:`~object.__init__` method for :class:`!C` will look " "like::" msgstr "" -#: ../../library/dataclasses.rst:658 +#: ../../library/dataclasses.rst:680 +msgid "def __init__(self, x: int = 15, y: int = 0, z: int = 10):" +msgstr "" + +#: ../../library/dataclasses.rst:683 msgid "Re-ordering of keyword-only parameters in :meth:`!__init__`" msgstr "" -#: ../../library/dataclasses.rst:660 +#: ../../library/dataclasses.rst:685 msgid "" "After the parameters needed for :meth:`~object.__init__` are computed, any " "keyword-only parameters are moved to come after all regular (non-keyword-" @@ -862,42 +1072,67 @@ msgid "" "implemented in Python: they must come after non-keyword-only parameters." msgstr "" -#: ../../library/dataclasses.rst:666 +#: ../../library/dataclasses.rst:691 msgid "" "In this example, :attr:`!Base.y`, :attr:`!Base.w`, and :attr:`!D.t` are " "keyword-only fields, and :attr:`!Base.x` and :attr:`!D.z` are regular " "fields::" msgstr "" -#: ../../library/dataclasses.rst:681 +#: ../../library/dataclasses.rst:694 +msgid "" +"@dataclass\n" +"class Base:\n" +" x: Any = 15.0\n" +" _: KW_ONLY\n" +" y: int = 0\n" +" w: int = 1\n" +"\n" +"@dataclass\n" +"class D(Base):\n" +" z: int = 10\n" +" t: int = field(kw_only=True, default=0)" +msgstr "" + +#: ../../library/dataclasses.rst:706 msgid "The generated :meth:`!__init__` method for :class:`!D` will look like::" msgstr "" -#: ../../library/dataclasses.rst:685 +#: ../../library/dataclasses.rst:708 +msgid "" +"def __init__(self, x: Any = 15.0, z: int = 10, *, y: int = 0, w: int = 1, t: " +"int = 0):" +msgstr "" + +#: ../../library/dataclasses.rst:710 msgid "" "Note that the parameters have been re-ordered from how they appear in the " "list of fields: parameters derived from regular fields are followed by " "parameters derived from keyword-only fields." msgstr "" -#: ../../library/dataclasses.rst:689 +#: ../../library/dataclasses.rst:714 msgid "" "The relative ordering of keyword-only parameters is maintained in the re-" "ordered :meth:`!__init__` parameter list." msgstr "" -#: ../../library/dataclasses.rst:694 +#: ../../library/dataclasses.rst:719 msgid "Default factory functions" msgstr "Funções padrão de fábrica" -#: ../../library/dataclasses.rst:696 +#: ../../library/dataclasses.rst:721 msgid "" "If a :func:`field` specifies a *default_factory*, it is called with zero " "arguments when a default value for the field is needed. For example, to " "create a new instance of a list, use::" msgstr "" -#: ../../library/dataclasses.rst:702 +#: ../../library/dataclasses.rst:725 +msgid "mylist: list = field(default_factory=list)" +msgstr "" + +#: ../../library/dataclasses.rst:727 msgid "" "If a field is excluded from :meth:`~object.__init__` (using ``init=False``) " "and the field also specifies *default_factory*, then the default factory " @@ -906,31 +1141,67 @@ msgid "" "initial value." msgstr "" -#: ../../library/dataclasses.rst:709 +#: ../../library/dataclasses.rst:734 msgid "Mutable default values" msgstr "Valores padrão mutáveis" -#: ../../library/dataclasses.rst:711 +#: ../../library/dataclasses.rst:736 msgid "" "Python stores default member variable values in class attributes. Consider " "this example, not using dataclasses::" msgstr "" -#: ../../library/dataclasses.rst:726 +#: ../../library/dataclasses.rst:739 +msgid "" +"class C:\n" +" x = []\n" +" def add(self, element):\n" +" self.x.append(element)\n" +"\n" +"o1 = C()\n" +"o2 = C()\n" +"o1.add(1)\n" +"o2.add(2)\n" +"assert o1.x == [1, 2]\n" +"assert o1.x is o2.x" +msgstr "" + +#: ../../library/dataclasses.rst:751 msgid "" "Note that the two instances of class :class:`!C` share the same class " "variable :attr:`!x`, as expected." msgstr "" -#: ../../library/dataclasses.rst:729 +#: ../../library/dataclasses.rst:754 msgid "Using dataclasses, *if* this code was valid::" msgstr "Usando dataclasses, *se* este código fosse válido::" -#: ../../library/dataclasses.rst:737 +#: ../../library/dataclasses.rst:756 +msgid "" +"@dataclass\n" +"class D:\n" +" x: list = [] # This code raises ValueError\n" +" def add(self, element):\n" +" self.x.append(element)" +msgstr "" + +#: ../../library/dataclasses.rst:762 msgid "it would generate code similar to::" msgstr "Geraria código similar a::" -#: ../../library/dataclasses.rst:748 +#: ../../library/dataclasses.rst:764 +msgid "" +"class D:\n" +" x = []\n" +" def __init__(self, x=x):\n" +" self.x = x\n" +" def add(self, element):\n" +" self.x.append(element)\n" +"\n" +"assert D().x is D().x" +msgstr "" + +#: ../../library/dataclasses.rst:773 msgid "" "This has the same issue as the original example using class :class:`!C`. " "That is, two instances of class :class:`!D` that do not specify a value for :" @@ -943,44 +1214,53 @@ msgid "" "partial solution, but it does protect against many common errors." msgstr "" -#: ../../library/dataclasses.rst:759 +#: ../../library/dataclasses.rst:784 msgid "" "Using default factory functions is a way to create new instances of mutable " "types as default values for fields::" msgstr "" -#: ../../library/dataclasses.rst:768 +#: ../../library/dataclasses.rst:787 +msgid "" +"@dataclass\n" +"class D:\n" +" x: list = field(default_factory=list)\n" +"\n" +"assert D().x is not D().x" +msgstr "" + +#: ../../library/dataclasses.rst:793 msgid "" "Instead of looking for and disallowing objects of type :class:`list`, :class:" "`dict`, or :class:`set`, unhashable objects are now not allowed as default " "values. Unhashability is used to approximate mutability." msgstr "" -#: ../../library/dataclasses.rst:775 +#: ../../library/dataclasses.rst:800 msgid "Descriptor-typed fields" msgstr "" -#: ../../library/dataclasses.rst:777 +#: ../../library/dataclasses.rst:802 msgid "" "Fields that are assigned :ref:`descriptor objects ` as their " "default value have the following special behaviors:" msgstr "" -#: ../../library/dataclasses.rst:780 +#: ../../library/dataclasses.rst:805 msgid "" "The value for the field passed to the dataclass's :meth:`~object.__init__` " "method is passed to the descriptor's :meth:`~object.__set__` method rather " "than overwriting the descriptor object." msgstr "" -#: ../../library/dataclasses.rst:784 +#: ../../library/dataclasses.rst:809 msgid "" "Similarly, when getting or setting the field, the descriptor's :meth:" "`~object.__get__` or :meth:`!__set__` method is called rather than returning " "or overwriting the descriptor object." msgstr "" -#: ../../library/dataclasses.rst:788 +#: ../../library/dataclasses.rst:813 msgid "" "To determine whether a field contains a default value, :func:`@dataclass " "` will call the descriptor's :meth:`!__get__` method using its " @@ -992,6 +1272,35 @@ msgstr "" #: ../../library/dataclasses.rst:823 msgid "" +"class IntConversionDescriptor:\n" +" def __init__(self, *, default):\n" +" self._default = default\n" +"\n" +" def __set_name__(self, owner, name):\n" +" self._name = \"_\" + name\n" +"\n" +" def __get__(self, obj, type):\n" +" if obj is None:\n" +" return self._default\n" +"\n" +" return getattr(obj, self._name, self._default)\n" +"\n" +" def __set__(self, obj, value):\n" +" setattr(obj, self._name, int(value))\n" +"\n" +"@dataclass\n" +"class InventoryItem:\n" +" quantity_on_hand: IntConversionDescriptor = " +"IntConversionDescriptor(default=100)\n" +"\n" +"i = InventoryItem()\n" +"print(i.quantity_on_hand) # 100\n" +"i.quantity_on_hand = 2.5 # calls __set__ with 2.5\n" +"print(i.quantity_on_hand) # 2" +msgstr "" + +#: ../../library/dataclasses.rst:848 +msgid "" "Note that if a field is annotated with a descriptor type, but is not " "assigned a descriptor object as its default value, the field will act like a " "normal field." diff --git a/library/datatypes.po b/library/datatypes.po index 20c88e334..04a5b4fd0 100644 --- a/library/datatypes.po +++ b/library/datatypes.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Raphael Mendonça, 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:04+0000\n" -"Last-Translator: Raphael Mendonça, 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/datetime.po b/library/datetime.po index c40d8c0d2..8560a8124 100644 --- a/library/datetime.po +++ b/library/datetime.po @@ -1,42 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# mvpetri , 2021 -# Danielle Farias , 2021 -# 2c4b5a73177ea5ea1d3324f10df471a7_b8aeba7 <7df8a60bac356f3b148ac94f3c2796f6_834576>, 2021 -# Welington Carlos , 2021 -# Julia Rizza , 2021 -# Marco Rougeth , 2021 -# Italo Penaforte , 2021 -# And Past , 2021 -# (Douglas da Silva) , 2021 -# Misael borges , 2021 -# Vinícius Muniz de Melo , 2021 -# Vinicius Gubiani Ferreira , 2021 -# i17obot , 2021 -# yyyyyyyan , 2021 -# Claudio Rogerio Carvalho Filho , 2024 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 01:04+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-16 14:58+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -127,6 +110,8 @@ msgid "" "Date and time objects may be categorized as \"aware\" or \"naive\" depending " "on whether or not they include time zone information." msgstr "" +"Objetos de data e hora podem ser categorizados como \"consciente\" ou " +"\"ingênuo\" dependendo se eles incluem ou não informação sobre fuso horário." #: ../../library/datetime.rst:53 msgid "" @@ -152,6 +137,13 @@ msgid "" "objects are easy to understand and to work with, at the cost of ignoring " "some aspects of reality." msgstr "" +"Um objeto **ingênuo** não contém informações suficientes para se localizar " +"inequivocamente em relação a outros objetos de data/hora. Se um objeto " +"ingênuo representa o Coordinated Universal Time (UTC), a hora local, ou a " +"hora em algum outro fuso horário, isso depende exclusivamente do programa, " +"assim como é tarefa do programa decidir se um número específico representa " +"metros, milhas ou massa. Objetos ingênuos são fáceis de entender e " +"trabalhar, com o custo de ignorar alguns aspectos da realidade." #: ../../library/datetime.rst:66 msgid "" @@ -179,6 +171,14 @@ msgid "" "across the world are more political than rational, change frequently, and " "there is no standard suitable for every application aside from UTC." msgstr "" +"Somente uma classe concreta :class:`tzinfo`, a classe :class:`timezone`, é " +"fornecida pelo módulo :mod:`!datetime`. A classe :class:`!timezone` pode " +"representar fusos horários simples com diferenças fixas do UTC, como o " +"próprio UTC, ou os fusos horários norte-americanos EST e EDT. O suporte a " +"fusos horários em níveis mais detalhados depende da aplicação. As regras " +"para ajuste de tempo em todo o mundo são mais políticas do que racionais, " +"mudam com frequência e não há um padrão adequado para todas as aplicações " +"além da UTC." #: ../../library/datetime.rst:81 msgid "Constants" @@ -207,6 +207,7 @@ msgstr "" #: ../../library/datetime.rst:98 msgid "Alias for the UTC time zone singleton :attr:`datetime.timezone.utc`." msgstr "" +"Apelido para o singleton de fuso horário UTC :attr:`datetime.timezone.utc`." #: ../../library/datetime.rst:103 msgid "Available Types" @@ -280,6 +281,24 @@ msgstr "Objetos desse tipo são imutáveis." msgid "Subclass relationships::" msgstr "Relacionamentos de subclasse::" +#: ../../library/datetime.rst:157 +msgid "" +"object\n" +" timedelta\n" +" tzinfo\n" +" timezone\n" +" time\n" +" date\n" +" datetime" +msgstr "" +"object\n" +" timedelta\n" +" tzinfo\n" +" timezone\n" +" time\n" +" date\n" +" datetime" + #: ../../library/datetime.rst:166 msgid "Common Properties" msgstr "Propriedades Comuns" @@ -324,9 +343,10 @@ msgstr "" "ou ingênuo." #: ../../library/datetime.rst:183 -msgid "A :class:`.datetime` object *d* is aware if both of the following hold:" +msgid "" +"A :class:`.datetime` object ``d`` is aware if both of the following hold:" msgstr "" -"O objeto :class:`.datetime` *d* é consciente se ambos os seguintes itens " +"O objeto :class:`.datetime` ``d`` é consciente se ambos os seguintes itens " "forem verdadeiros:" #: ../../library/datetime.rst:185 @@ -338,13 +358,13 @@ msgid "``d.tzinfo.utcoffset(d)`` does not return ``None``" msgstr "``d.tzinfo.utcoffset(d)`` não retorna ``None``" #: ../../library/datetime.rst:188 -msgid "Otherwise, *d* is naive." -msgstr "Caso contrário, *d* é ingênuo." +msgid "Otherwise, ``d`` is naive." +msgstr "Caso contrário, ``d`` é ingênuo." #: ../../library/datetime.rst:190 -msgid "A :class:`.time` object *t* is aware if both of the following hold:" +msgid "A :class:`.time` object ``t`` is aware if both of the following hold:" msgstr "" -"O objeto :class:`.time` *t* é consciente, se os seguintes itens são " +"O objeto :class:`.time` ``t`` é consciente, se os seguintes itens são " "verdadeiros:" #: ../../library/datetime.rst:192 @@ -356,8 +376,8 @@ msgid "``t.tzinfo.utcoffset(None)`` does not return ``None``." msgstr "``t.tzinfo.utcoffset(None)`` não retorna ``None``." #: ../../library/datetime.rst:195 -msgid "Otherwise, *t* is naive." -msgstr "Caso contrário, *t* é ingênuo." +msgid "Otherwise, ``t`` is naive." +msgstr "Caso contrário, ``t`` é ingênuo." #: ../../library/datetime.rst:197 msgid "" @@ -441,6 +461,36 @@ msgstr "" "*seconds* e *microseconds* são \"mesclados\" e normalizados nos três " "atributos resultantes::" +#: ../../library/datetime.rst:232 +msgid "" +">>> from datetime import timedelta\n" +">>> delta = timedelta(\n" +"... days=50,\n" +"... seconds=27,\n" +"... microseconds=10,\n" +"... milliseconds=29000,\n" +"... minutes=5,\n" +"... hours=8,\n" +"... weeks=2\n" +"... )\n" +">>> # Only days, seconds, and microseconds remain\n" +">>> delta\n" +"datetime.timedelta(days=64, seconds=29156, microseconds=10)" +msgstr "" +">>> from datetime import timedelta\n" +">>> delta = timedelta(\n" +"... days=50,\n" +"... seconds=27,\n" +"... microseconds=10,\n" +"... milliseconds=29000,\n" +"... minutes=5,\n" +"... hours=8,\n" +"... weeks=2\n" +"... )\n" +">>> # sá restam dias, segundos e microssegundos\n" +">>> delta\n" +"datetime.timedelta(days=64, seconds=29156, microseconds=10)" + #: ../../library/datetime.rst:246 msgid "" "If any argument is a float and there are fractional microseconds, the " @@ -472,17 +522,61 @@ msgstr "" "Observe que a normalização de valores negativos pode ser surpreendente a " "princípio. Por exemplo::" -#: ../../library/datetime.rst:265 ../../library/datetime.rst:546 -#: ../../library/datetime.rst:1102 ../../library/datetime.rst:1740 -#: ../../library/datetime.rst:2345 +#: ../../library/datetime.rst:259 +msgid "" +">>> from datetime import timedelta\n" +">>> d = timedelta(microseconds=-1)\n" +">>> (d.days, d.seconds, d.microseconds)\n" +"(-1, 86399, 999999)" +msgstr "" +">>> from datetime import timedelta\n" +">>> d = timedelta(microseconds=-1)\n" +">>> (d.days, d.seconds, d.microseconds)\n" +"(-1, 86399, 999999)" + +#: ../../library/datetime.rst:264 +msgid "" +"Since the string representation of :class:`!timedelta` objects can be " +"confusing, use the following recipe to produce a more readable format:" +msgstr "" +"Como a representação de string dos objetos :class:`!timedelta` pode ser " +"confusa, use a seguinte receita para produzir um formato mais legível:" + +#: ../../library/datetime.rst:267 +msgid "" +">>> def pretty_timedelta(td):\n" +"... if td.days >= 0:\n" +"... return str(td)\n" +"... return f'-({-td!s})'\n" +"...\n" +">>> d = timedelta(hours=-1)\n" +">>> str(d) # not human-friendly\n" +"'-1 day, 23:00:00'\n" +">>> pretty_timedelta(d)\n" +"'-(1:00:00)'" +msgstr "" +">>> def pretty_timedelta(td):\n" +"... if td.days >= 0:\n" +"... return str(td)\n" +"... return f'-({-td!s})'\n" +"...\n" +">>> d = timedelta(hours=-1)\n" +">>> str(d) # not human-friendly\n" +"'-1 day, 23:00:00'\n" +">>> pretty_timedelta(d)\n" +"'-(1:00:00)'" + +#: ../../library/datetime.rst:281 ../../library/datetime.rst:582 +#: ../../library/datetime.rst:1142 ../../library/datetime.rst:1780 +#: ../../library/datetime.rst:2385 msgid "Class attributes:" msgstr "Atributos de classe:" -#: ../../library/datetime.rst:269 +#: ../../library/datetime.rst:285 msgid "The most negative :class:`timedelta` object, ``timedelta(-999999999)``." msgstr "O mais negativo objeto :class:`timedelta`, ``timedelta(-999999999)``." -#: ../../library/datetime.rst:274 +#: ../../library/datetime.rst:290 msgid "" "The most positive :class:`timedelta` object, ``timedelta(days=999999999, " "hours=23, minutes=59, seconds=59, microseconds=999999)``." @@ -490,7 +584,7 @@ msgstr "" "O mais positivo objeto :class:`timedelta`, ``timedelta(days=999999999, " "hours=23, minutes=59, seconds=59, microseconds=999999)``." -#: ../../library/datetime.rst:280 +#: ../../library/datetime.rst:296 msgid "" "The smallest possible difference between non-equal :class:`timedelta` " "objects, ``timedelta(microseconds=1)``." @@ -498,7 +592,7 @@ msgstr "" "A menor diferença possível entre objetos não iguais :class:`timedelta`, " "``timedelta(microseconds=1)``." -#: ../../library/datetime.rst:283 +#: ../../library/datetime.rst:299 msgid "" "Note that, because of normalization, ``timedelta.max`` is greater than ``-" "timedelta.min``. ``-timedelta.max`` is not representable as a :class:" @@ -508,63 +602,69 @@ msgstr "" "timedelta.min``. ``-timedelta.max`` não é representável como um objeto :" "class:`timedelta`." -#: ../../library/datetime.rst:286 ../../library/datetime.rst:564 -#: ../../library/datetime.rst:1122 ../../library/datetime.rst:1760 +#: ../../library/datetime.rst:303 ../../library/datetime.rst:600 +#: ../../library/datetime.rst:1162 ../../library/datetime.rst:1800 msgid "Instance attributes (read-only):" msgstr "Atributos de instância (somente leitura):" -#: ../../library/datetime.rst:289 -msgid "Attribute" -msgstr "Atributo" - -#: ../../library/datetime.rst:289 -msgid "Value" -msgstr "Valor" +#: ../../library/datetime.rst:307 +msgid "Between -999,999,999 and 999,999,999 inclusive." +msgstr "Entre -999.999.999 e 999.999.999 inclusive" -#: ../../library/datetime.rst:291 -msgid "``days``" -msgstr "``days``" +#: ../../library/datetime.rst:312 +msgid "Between 0 and 86,399 inclusive." +msgstr "Entre 0 e 86.399 inclusive." -#: ../../library/datetime.rst:291 -msgid "Between -999999999 and 999999999 inclusive" -msgstr "Entre -999999999 e 999999999 inclusive" - -#: ../../library/datetime.rst:293 -msgid "``seconds``" -msgstr "``seconds``" - -#: ../../library/datetime.rst:293 -msgid "Between 0 and 86399 inclusive" -msgstr "Entre 0 e 86399 inclusive" - -#: ../../library/datetime.rst:295 -msgid "``microseconds``" -msgstr "``microseconds``" - -#: ../../library/datetime.rst:295 -msgid "Between 0 and 999999 inclusive" -msgstr "Entre 0 e 999999 inclusive" +#: ../../library/datetime.rst:316 +msgid "" +"It is a somewhat common bug for code to unintentionally use this attribute " +"when it is actually intended to get a :meth:`~timedelta.total_seconds` value " +"instead:" +msgstr "" +"É um bug relativamente comum utilizar este atributo de forma não intencional " +"quando, na verdade, o objetivo é obter o valor de :meth:`~timedelta." +"total_seconds`:" -#: ../../library/datetime.rst:298 ../../library/datetime.rst:581 -#: ../../library/datetime.rst:1175 +#: ../../library/datetime.rst:320 +msgid "" +">>> from datetime import timedelta\n" +">>> duration = timedelta(seconds=11235813)\n" +">>> duration.days, duration.seconds\n" +"(130, 3813)\n" +">>> duration.total_seconds()\n" +"11235813.0" +msgstr "" +">>> from datetime import timedelta\n" +">>> duration = timedelta(seconds=11235813)\n" +">>> duration.days, duration.seconds\n" +"(130, 3813)\n" +">>> duration.total_seconds()\n" +"11235813.0" + +#: ../../library/datetime.rst:331 +msgid "Between 0 and 999,999 inclusive." +msgstr "Entre 0 e 999.999 inclusive." + +#: ../../library/datetime.rst:334 ../../library/datetime.rst:617 +#: ../../library/datetime.rst:1215 msgid "Supported operations:" msgstr "Operações suportadas:" -#: ../../library/datetime.rst:303 ../../library/datetime.rst:584 -#: ../../library/datetime.rst:1178 +#: ../../library/datetime.rst:339 ../../library/datetime.rst:620 +#: ../../library/datetime.rst:1218 msgid "Operation" msgstr "Operação" -#: ../../library/datetime.rst:303 ../../library/datetime.rst:584 -#: ../../library/datetime.rst:1178 +#: ../../library/datetime.rst:339 ../../library/datetime.rst:620 +#: ../../library/datetime.rst:1218 msgid "Result" msgstr "Resultado" -#: ../../library/datetime.rst:305 +#: ../../library/datetime.rst:341 msgid "``t1 = t2 + t3``" msgstr "``t1 = t2 + t3``" -#: ../../library/datetime.rst:305 +#: ../../library/datetime.rst:341 msgid "" "Sum of ``t2`` and ``t3``. Afterwards ``t1 - t2 == t3`` and ``t1 - t3 == t2`` " "are true. (1)" @@ -572,11 +672,11 @@ msgstr "" "Soma de ``t2`` e ``t3``. Depois ``t1 - t2 == t3`` e ``t1 - t3 == t2`` são " "verdadeiros. (1)" -#: ../../library/datetime.rst:309 +#: ../../library/datetime.rst:345 msgid "``t1 = t2 - t3``" msgstr "``t1 = t2 - t3``" -#: ../../library/datetime.rst:309 +#: ../../library/datetime.rst:345 msgid "" "Difference of ``t2`` and ``t3``. Afterwards ``t1 == t2 - t3`` and ``t2 == " "t1 + t3`` are true. (1)(6)" @@ -584,11 +684,11 @@ msgstr "" "Diferença de ``t2`` e ``t3``. Depois ``t1 == t2 - t3`` e ``t2 == t1 + t3`` " "são verdadeiros (1)(6)" -#: ../../library/datetime.rst:313 +#: ../../library/datetime.rst:349 msgid "``t1 = t2 * i or t1 = i * t2``" msgstr "``t1 = t2 * i or t1 = i * t2``" -#: ../../library/datetime.rst:313 +#: ../../library/datetime.rst:349 msgid "" "Delta multiplied by an integer. Afterwards ``t1 // i == t2`` is true, " "provided ``i != 0``." @@ -596,15 +696,15 @@ msgstr "" "Delta multiplicado por um número inteiro. Depois ``t1 // i == t2`` é " "verdadeiro, desde que ``i != 0``." -#: ../../library/datetime.rst:317 +#: ../../library/datetime.rst:353 msgid "In general, ``t1 * i == t1 * (i-1) + t1`` is true. (1)" msgstr "Em geral, ``t1 * i == t1 * (i-1) + t1`` é verdadeiro. (1)" -#: ../../library/datetime.rst:320 +#: ../../library/datetime.rst:356 msgid "``t1 = t2 * f or t1 = f * t2``" msgstr "``t1 = t2 * f or t1 = f * t2``" -#: ../../library/datetime.rst:320 +#: ../../library/datetime.rst:356 msgid "" "Delta multiplied by a float. The result is rounded to the nearest multiple " "of timedelta.resolution using round-half-to-even." @@ -613,11 +713,11 @@ msgstr "" "para o múltiplo mais próximo de timedelta.resolution usando a metade da " "metade para o par." -#: ../../library/datetime.rst:324 +#: ../../library/datetime.rst:360 msgid "``f = t2 / t3``" msgstr "``f = t2 / t3``" -#: ../../library/datetime.rst:324 +#: ../../library/datetime.rst:360 msgid "" "Division (3) of overall duration ``t2`` by interval unit ``t3``. Returns a :" "class:`float` object." @@ -625,11 +725,11 @@ msgstr "" "Divisão (3) da duração total ``t2`` por unidade de intervalo ``t3``. Retorna " "um objeto :class:`float`." -#: ../../library/datetime.rst:328 +#: ../../library/datetime.rst:364 msgid "``t1 = t2 / f or t1 = t2 / i``" msgstr "``t1 = t2 / f or t1 = t2 / i``" -#: ../../library/datetime.rst:328 +#: ../../library/datetime.rst:364 msgid "" "Delta divided by a float or an int. The result is rounded to the nearest " "multiple of timedelta.resolution using round-half-to-even." @@ -638,11 +738,11 @@ msgstr "" "múltiplo mais próximo de timedelta.resolution usando a metade da metade para " "o par." -#: ../../library/datetime.rst:332 +#: ../../library/datetime.rst:368 msgid "``t1 = t2 // i`` or ``t1 = t2 // t3``" msgstr "``t1 = t2 // i`` ou ``t1 = t2 // t3``" -#: ../../library/datetime.rst:332 +#: ../../library/datetime.rst:368 msgid "" "The floor is computed and the remainder (if any) is thrown away. In the " "second case, an integer is returned. (3)" @@ -650,51 +750,51 @@ msgstr "" "O piso é calculado e o restante (se houver) é jogado fora. No segundo caso, " "um número inteiro é retornado. (3)" -#: ../../library/datetime.rst:336 +#: ../../library/datetime.rst:372 msgid "``t1 = t2 % t3``" msgstr "``t1 = t2 % t3``" -#: ../../library/datetime.rst:336 +#: ../../library/datetime.rst:372 msgid "The remainder is computed as a :class:`timedelta` object. (3)" msgstr "O restante é calculado como um objeto :class:`timedelta`. (3)" -#: ../../library/datetime.rst:339 +#: ../../library/datetime.rst:375 msgid "``q, r = divmod(t1, t2)``" msgstr "``q, r = divmod(t1, t2)``" -#: ../../library/datetime.rst:339 +#: ../../library/datetime.rst:375 msgid "" "Computes the quotient and the remainder: ``q = t1 // t2`` (3) and ``r = t1 % " -"t2``. q is an integer and r is a :class:`timedelta` object." +"t2``. ``q`` is an integer and ``r`` is a :class:`timedelta` object." msgstr "" -"Calcula o quociente e o restante: ``q = t1 // t2`` (3) e ``r = t1 % t2``. q " -"é um número inteiro e r é um objeto :class:`timedelta`." +"Calcula o quociente e o resto: ``q = t1 // t2`` (3) e ``r = t1 % t2``. ``q`` " +"é um inteiro e ``r`` é um objeto :class:`timedelta`." -#: ../../library/datetime.rst:344 +#: ../../library/datetime.rst:380 msgid "``+t1``" msgstr "``+t1``" -#: ../../library/datetime.rst:344 +#: ../../library/datetime.rst:380 msgid "Returns a :class:`timedelta` object with the same value. (2)" msgstr "Retorna um objeto :class:`timedelta` com o mesmo valor. (2)" -#: ../../library/datetime.rst:347 +#: ../../library/datetime.rst:383 msgid "``-t1``" msgstr "``-t1``" -#: ../../library/datetime.rst:347 +#: ../../library/datetime.rst:383 msgid "" -"Equivalent to ``timedelta(-t1.days, -t1.seconds*, -t1.microseconds)``, and " -"to ``t1 * -1``. (1)(4)" +"Equivalent to ``timedelta(-t1.days, -t1.seconds, -t1.microseconds)``, and to " +"``t1 * -1``. (1)(4)" msgstr "" -"Equivalente a ``timedelta(-t1.days, -t1.seconds*, -t1.microseconds)`` e a " +"Equivalente a ``timedelta(-t1.days, -t1.seconds, -t1.microseconds)`` e a " "``t1 * -1``. (1)(4)" -#: ../../library/datetime.rst:351 +#: ../../library/datetime.rst:387 msgid "``abs(t)``" msgstr "``abs(t)``" -#: ../../library/datetime.rst:351 +#: ../../library/datetime.rst:387 msgid "" "Equivalent to ``+t`` when ``t.days >= 0``, and to ``-t`` when ``t.days < " "0``. (2)" @@ -702,11 +802,11 @@ msgstr "" "Equivalente a ``+t`` quando ``t.days >= 0`` e a ``-t`` quando ``t.days < " "0``. (2)" -#: ../../library/datetime.rst:354 +#: ../../library/datetime.rst:390 msgid "``str(t)``" msgstr "``str(t)``" -#: ../../library/datetime.rst:354 +#: ../../library/datetime.rst:390 msgid "" "Returns a string in the form ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D is " "negative for negative ``t``. (5)" @@ -714,11 +814,11 @@ msgstr "" "Retorna uma string no formato ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, onde D é " "negativo para ``t`` negativo. (5)" -#: ../../library/datetime.rst:358 +#: ../../library/datetime.rst:394 msgid "``repr(t)``" msgstr "``repr(t)``" -#: ../../library/datetime.rst:358 +#: ../../library/datetime.rst:394 msgid "" "Returns a string representation of the :class:`timedelta` object as a " "constructor call with canonical attribute values." @@ -726,29 +826,29 @@ msgstr "" "Retorna uma representação em string do objeto :class:`timedelta` como uma " "chamada do construtor com valores de atributos canônicos." -#: ../../library/datetime.rst:364 ../../library/datetime.rst:603 -#: ../../library/datetime.rst:2576 +#: ../../library/datetime.rst:400 ../../library/datetime.rst:639 +#: ../../library/datetime.rst:2616 msgid "Notes:" msgstr "Notas:" -#: ../../library/datetime.rst:367 +#: ../../library/datetime.rst:403 msgid "This is exact but may overflow." msgstr "Isso é exato, mas pode transbordar." -#: ../../library/datetime.rst:370 +#: ../../library/datetime.rst:406 msgid "This is exact and cannot overflow." msgstr "Isso é exato e não pode transbordar." -#: ../../library/datetime.rst:373 +#: ../../library/datetime.rst:409 msgid "Division by zero raises :exc:`ZeroDivisionError`." msgstr "A divisão por zero levanta :exc:`ZeroDivisionError`." -#: ../../library/datetime.rst:376 +#: ../../library/datetime.rst:412 msgid "``-timedelta.max`` is not representable as a :class:`timedelta` object." msgstr "" "``-timedelta.max`` não é representável como um objeto :class:`timedelta`." -#: ../../library/datetime.rst:379 +#: ../../library/datetime.rst:415 msgid "" "String representations of :class:`timedelta` objects are normalized " "similarly to their internal representation. This leads to somewhat unusual " @@ -758,7 +858,19 @@ msgstr "" "de maneira semelhante à sua representação interna. Isso leva a resultados um " "tanto incomuns para timedeltas negativos. Por exemplo::" -#: ../../library/datetime.rst:389 +#: ../../library/datetime.rst:419 +msgid "" +">>> timedelta(hours=-5)\n" +"datetime.timedelta(days=-1, seconds=68400)\n" +">>> print(_)\n" +"-1 day, 19:00:00" +msgstr "" +">>> timedelta(hours=-5)\n" +"datetime.timedelta(days=-1, seconds=68400)\n" +">>> print(_)\n" +"-1 day, 19:00:00" + +#: ../../library/datetime.rst:425 msgid "" "The expression ``t2 - t3`` will always be equal to the expression ``t2 + (-" "t3)`` except when t3 is equal to ``timedelta.max``; in that case the former " @@ -768,7 +880,7 @@ msgstr "" "quando t3 for igual a ``timedelta.max``; nesse caso, o primeiro produzirá um " "resultado enquanto o último transbordará." -#: ../../library/datetime.rst:393 +#: ../../library/datetime.rst:429 msgid "" "In addition to the operations listed above, :class:`timedelta` objects " "support certain additions and subtractions with :class:`date` and :class:`." @@ -778,7 +890,7 @@ msgstr "" "certas adições e subtrações com os objetos :class:`date` e :class:`." "datetime` (veja abaixo)." -#: ../../library/datetime.rst:397 +#: ../../library/datetime.rst:433 msgid "" "Floor division and true division of a :class:`timedelta` object by another :" "class:`timedelta` object are now supported, as are remainder operations and " @@ -791,12 +903,12 @@ msgstr "" "multiplicação de um objeto :class:`timedelta` por um objeto :class:`float` " "agora são suportadas." -#: ../../library/datetime.rst:403 +#: ../../library/datetime.rst:439 msgid ":class:`timedelta` objects support equality and order comparisons." msgstr "" "Objetos :class:`timedelta` dão suporte a comparações de igualdade e ordem." -#: ../../library/datetime.rst:405 +#: ../../library/datetime.rst:441 msgid "" "In Boolean contexts, a :class:`timedelta` object is considered to be true if " "and only if it isn't equal to ``timedelta(0)``." @@ -804,12 +916,12 @@ msgstr "" "Em contexto booleano, um objeto :class:`timedelta` é considerado verdadeiro " "se, e somente se, não for igual a ``timedelta(0)``." -#: ../../library/datetime.rst:408 ../../library/datetime.rst:645 -#: ../../library/datetime.rst:1265 ../../library/datetime.rst:1867 +#: ../../library/datetime.rst:444 ../../library/datetime.rst:681 +#: ../../library/datetime.rst:1305 ../../library/datetime.rst:1907 msgid "Instance methods:" msgstr "Métodos de instância:" -#: ../../library/datetime.rst:412 +#: ../../library/datetime.rst:448 msgid "" "Return the total number of seconds contained in the duration. Equivalent to " "``td / timedelta(seconds=1)``. For interval units other than seconds, use " @@ -820,7 +932,7 @@ msgstr "" "use a forma de divisão diretamente (por exemplo ``td / " "timedelta(microseconds=1)``)." -#: ../../library/datetime.rst:416 +#: ../../library/datetime.rst:452 msgid "" "Note that for very large time intervals (greater than 270 years on most " "platforms) this method will lose microsecond accuracy." @@ -828,23 +940,75 @@ msgstr "" "Observe que, em intervalos de tempo muito grandes (mais de 270 anos na " "maioria das plataformas), esse método perde a precisão de microssegundos." -#: ../../library/datetime.rst:422 +#: ../../library/datetime.rst:458 msgid "Examples of usage: :class:`timedelta`" msgstr "Exemplos de uso: :class:`.timedelta`" -#: ../../library/datetime.rst:424 +#: ../../library/datetime.rst:460 msgid "An additional example of normalization::" msgstr "Um exemplo adicional de normalização::" -#: ../../library/datetime.rst:436 +#: ../../library/datetime.rst:462 +msgid "" +">>> # Components of another_year add up to exactly 365 days\n" +">>> from datetime import timedelta\n" +">>> year = timedelta(days=365)\n" +">>> another_year = timedelta(weeks=40, days=84, hours=23,\n" +"... minutes=50, seconds=600)\n" +">>> year == another_year\n" +"True\n" +">>> year.total_seconds()\n" +"31536000.0" +msgstr "" +">>> # Os componentes de outro_ano somam exatamente 365 dias\n" +">>> from datetime import timedelta\n" +">>> year = timedelta(days=365)\n" +">>> outro_ano = timedelta(weeks=40, days=84, hours=23,\n" +"... minutes=50, seconds=600)\n" +">>> year == outro_ano\n" +"True\n" +">>> year.total_seconds()\n" +"31536000.0" + +#: ../../library/datetime.rst:472 msgid "Examples of :class:`timedelta` arithmetic::" msgstr "Exemplos de aritmética com :class:`timedelta`::" -#: ../../library/datetime.rst:455 +#: ../../library/datetime.rst:474 +msgid "" +">>> from datetime import timedelta\n" +">>> year = timedelta(days=365)\n" +">>> ten_years = 10 * year\n" +">>> ten_years\n" +"datetime.timedelta(days=3650)\n" +">>> ten_years.days // 365\n" +"10\n" +">>> nine_years = ten_years - year\n" +">>> nine_years\n" +"datetime.timedelta(days=3285)\n" +">>> three_years = nine_years // 3\n" +">>> three_years, three_years.days // 365\n" +"(datetime.timedelta(days=1095), 3)" +msgstr "" +">>> from datetime import timedelta\n" +">>> ano = timedelta(days=365)\n" +">>> dez_anos = 10 * ano\n" +">>> dez_anos\n" +"datetime.timedelta(days=3650)\n" +">>> dez_anos.days // 365\n" +"10\n" +">>> nove_anos = dez_anos - ano\n" +">>> nove_anos\n" +"datetime.timedelta(days=3285)\n" +">>> três_anos = nove_anos // 3\n" +">>> três_anos, três_anos.days // 365\n" +"(datetime.timedelta(days=1095), 3)" + +#: ../../library/datetime.rst:491 msgid ":class:`date` Objects" msgstr "Objetos :class:`date`" -#: ../../library/datetime.rst:457 +#: ../../library/datetime.rst:493 msgid "" "A :class:`date` object represents a date (year, month and day) in an " "idealized calendar, the current Gregorian calendar indefinitely extended in " @@ -854,7 +1018,7 @@ msgstr "" "idealizado, o atual calendário Gregoriano estendido indefinidamente em ambas " "as direções." -#: ../../library/datetime.rst:461 +#: ../../library/datetime.rst:497 msgid "" "January 1 of year 1 is called day number 1, January 2 of year 1 is called " "day number 2, and so on. [#]_" @@ -862,7 +1026,7 @@ msgstr "" "1º de janeiro do ano 1 é chamado de dia número 1, 2º de janeiro do ano 1 é " "chamado de dia número 2, e assim por diante. [#]_" -#: ../../library/datetime.rst:466 +#: ../../library/datetime.rst:502 msgid "" "All arguments are required. Arguments must be integers, in the following " "ranges:" @@ -870,38 +1034,38 @@ msgstr "" "Todos os argumentos são obrigatórios. Os argumentos devem ser números " "inteiros, nos seguintes intervalos:" -#: ../../library/datetime.rst:469 +#: ../../library/datetime.rst:505 msgid "``MINYEAR <= year <= MAXYEAR``" msgstr "``MINYEAR <= year <= MAXYEAR``" -#: ../../library/datetime.rst:470 +#: ../../library/datetime.rst:506 msgid "``1 <= month <= 12``" msgstr "``1 <= month <= 12``" -#: ../../library/datetime.rst:471 +#: ../../library/datetime.rst:507 msgid "``1 <= day <= number of days in the given month and year``" msgstr "``1 <= day <= número de dias no mês e ano fornecidos``" -#: ../../library/datetime.rst:473 ../../library/datetime.rst:863 +#: ../../library/datetime.rst:509 ../../library/datetime.rst:899 msgid "" "If an argument outside those ranges is given, :exc:`ValueError` is raised." msgstr "" "Se um argumento fora desses intervalos for fornecido, a exceção :exc:" "`ValueError` é levantada." -#: ../../library/datetime.rst:476 ../../library/datetime.rst:868 +#: ../../library/datetime.rst:512 ../../library/datetime.rst:904 msgid "Other constructors, all class methods:" msgstr "Outros construtores, todos os métodos de classe." -#: ../../library/datetime.rst:480 +#: ../../library/datetime.rst:516 msgid "Return the current local date." msgstr "Retorna a data local atual." -#: ../../library/datetime.rst:482 +#: ../../library/datetime.rst:518 msgid "This is equivalent to ``date.fromtimestamp(time.time())``." msgstr "Isso é equivalente a ``date.fromtimestamp(time.time())``." -#: ../../library/datetime.rst:486 +#: ../../library/datetime.rst:522 msgid "" "Return the local date corresponding to the POSIX timestamp, such as is " "returned by :func:`time.time`." @@ -909,7 +1073,7 @@ msgstr "" "Retorna a data local correspondente ao registro de data e hora do POSIX, " "como é retornado por :func:`time.time`." -#: ../../library/datetime.rst:489 +#: ../../library/datetime.rst:525 msgid "" "This may raise :exc:`OverflowError`, if the timestamp is out of the range of " "values supported by the platform C :c:func:`localtime` function, and :exc:" @@ -926,7 +1090,7 @@ msgstr "" "registro de data e hora, os segundos bissextos são ignorados por :meth:" "`fromtimestamp`." -#: ../../library/datetime.rst:496 +#: ../../library/datetime.rst:532 msgid "" "Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp is " "out of the range of values supported by the platform C :c:func:`localtime` " @@ -938,7 +1102,7 @@ msgstr "" "C :c:func:`localtime` função. Levanta :exc:`OSError` ao invés de :exc:" "`ValueError` em falha de :c:func:`localtime` ." -#: ../../library/datetime.rst:505 +#: ../../library/datetime.rst:541 msgid "" "Return the date corresponding to the proleptic Gregorian ordinal, where " "January 1 of year 1 has ordinal 1." @@ -946,16 +1110,16 @@ msgstr "" "Retorna a data correspondente ao ordinal proléptico gregoriano, considerando " "que 1º de janeiro do ano 1 tem o ordinal 1." -#: ../../library/datetime.rst:508 +#: ../../library/datetime.rst:544 msgid "" ":exc:`ValueError` is raised unless ``1 <= ordinal <= date.max.toordinal()``. " -"For any date *d*, ``date.fromordinal(d.toordinal()) == d``." +"For any date ``d``, ``date.fromordinal(d.toordinal()) == d``." msgstr "" -":exc:`ValueError` é levantado, a menos que ``1 <= ordinal <= date.max." -"toordinal()``. Para qualquer data *d*, ``date.fromordinal(d.toordinal()) == " -"d``." +":exc:`ValueError` é levantado a menos que ``1 <= ordinal <= date.max." +"toordinal()``. Para qualquer data ``d``, ``date.fromordinal(d.toordinal()) " +"== d``." -#: ../../library/datetime.rst:515 +#: ../../library/datetime.rst:551 msgid "" "Return a :class:`date` corresponding to a *date_string* given in any valid " "ISO 8601 format, with the following exceptions:" @@ -963,14 +1127,14 @@ msgstr "" "Retorna um :class:`date` correspondendo a *date_string* dada em qualquer " "formato válido de ISO 8601, com as seguintes exceções:" -#: ../../library/datetime.rst:518 ../../library/datetime.rst:1024 +#: ../../library/datetime.rst:554 ../../library/datetime.rst:1064 msgid "" "Reduced precision dates are not currently supported (``YYYY-MM``, ``YYYY``)." msgstr "" "Datas de precisão reduzida não são atualmente suportadas (``YYYY-MM``, " "``YYYY``)." -#: ../../library/datetime.rst:520 ../../library/datetime.rst:1026 +#: ../../library/datetime.rst:556 ../../library/datetime.rst:1066 msgid "" "Extended date representations are not currently supported (``±YYYYYY-MM-" "DD``)." @@ -978,21 +1142,39 @@ msgstr "" "Representações de data estendidas não são atualmente suportadas (``±YYYYYY-" "MM-DD``)." -#: ../../library/datetime.rst:522 ../../library/datetime.rst:1028 +#: ../../library/datetime.rst:558 ../../library/datetime.rst:1068 msgid "Ordinal dates are not currently supported (``YYYY-OOO``)." msgstr "Atualmente, as datas ordinais não são suportadas (``YYYY-OOO``)." -#: ../../library/datetime.rst:524 ../../library/datetime.rst:1030 -#: ../../library/datetime.rst:1496 +#: ../../library/datetime.rst:560 ../../library/datetime.rst:1070 +#: ../../library/datetime.rst:1536 msgid "Examples::" msgstr "Exemplos::" -#: ../../library/datetime.rst:535 +#: ../../library/datetime.rst:562 +msgid "" +">>> from datetime import date\n" +">>> date.fromisoformat('2019-12-04')\n" +"datetime.date(2019, 12, 4)\n" +">>> date.fromisoformat('20191204')\n" +"datetime.date(2019, 12, 4)\n" +">>> date.fromisoformat('2021-W01-1')\n" +"datetime.date(2021, 1, 4)" +msgstr "" +">>> from datetime import date\n" +">>> date.fromisoformat('2019-12-04')\n" +"datetime.date(2019, 12, 4)\n" +">>> date.fromisoformat('20191204')\n" +"datetime.date(2019, 12, 4)\n" +">>> date.fromisoformat('2021-W01-1')\n" +"datetime.date(2021, 1, 4)" + +#: ../../library/datetime.rst:571 msgid "Previously, this method only supported the format ``YYYY-MM-DD``." msgstr "" "Anteriormente, este método tinha suporte apenas ao formato ``YYYY-MM-DD``." -#: ../../library/datetime.rst:540 +#: ../../library/datetime.rst:576 msgid "" "Return a :class:`date` corresponding to the ISO calendar date specified by " "year, week and day. This is the inverse of the function :meth:`date." @@ -1002,15 +1184,15 @@ msgstr "" "especificada por year, week e day. Esta é o inverso da função :meth:`date." "isocalendar`." -#: ../../library/datetime.rst:550 +#: ../../library/datetime.rst:586 msgid "The earliest representable date, ``date(MINYEAR, 1, 1)``." msgstr "A data representável mais antiga, ``date(MINYEAR, 1, 1)``." -#: ../../library/datetime.rst:555 +#: ../../library/datetime.rst:591 msgid "The latest representable date, ``date(MAXYEAR, 12, 31)``." msgstr "A data representável mais tardia, ``date(MAXYEAR, 12, 31)``." -#: ../../library/datetime.rst:560 +#: ../../library/datetime.rst:596 msgid "" "The smallest possible difference between non-equal date objects, " "``timedelta(days=1)``." @@ -1018,39 +1200,39 @@ msgstr "" "A menor diferença possível entre objetos date não iguais, " "``timedelta(days=1)``." -#: ../../library/datetime.rst:568 ../../library/datetime.rst:1126 +#: ../../library/datetime.rst:604 ../../library/datetime.rst:1166 msgid "Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive." msgstr "Entre :const:`MINYEAR` e :const:`MAXYEAR` incluindo extremos." -#: ../../library/datetime.rst:573 ../../library/datetime.rst:1131 +#: ../../library/datetime.rst:609 ../../library/datetime.rst:1171 msgid "Between 1 and 12 inclusive." msgstr "Entre 1 e 12 incluindo extremos." -#: ../../library/datetime.rst:578 ../../library/datetime.rst:1136 +#: ../../library/datetime.rst:614 ../../library/datetime.rst:1176 msgid "Between 1 and the number of days in the given month of the given year." msgstr "Entre 1 e o número de dias no mês especificado do ano especificado." -#: ../../library/datetime.rst:586 +#: ../../library/datetime.rst:622 msgid "``date2 = date1 + timedelta``" msgstr "``date2 = date1 + timedelta``" -#: ../../library/datetime.rst:586 +#: ../../library/datetime.rst:622 msgid "``date2`` will be ``timedelta.days`` days after ``date1``. (1)" msgstr "``date2`` terá ``timedelta.days`` dias após ``date1``. (1)" -#: ../../library/datetime.rst:589 +#: ../../library/datetime.rst:625 msgid "``date2 = date1 - timedelta``" msgstr "``date2 = date1 - timedelta``" -#: ../../library/datetime.rst:589 +#: ../../library/datetime.rst:625 msgid "Computes ``date2`` such that ``date2 + timedelta == date1``. (2)" msgstr "Calcula ``date2`` de modo que ``date2 + timedelta == date1``. (2)" -#: ../../library/datetime.rst:592 +#: ../../library/datetime.rst:628 msgid "``timedelta = date1 - date2``" msgstr "``timedelta = date1 - date2``" -#: ../../library/datetime.rst:592 ../../library/datetime.rst:1184 +#: ../../library/datetime.rst:628 ../../library/datetime.rst:1224 msgid "\\(3)" msgstr "\\(3)" @@ -1062,7 +1244,7 @@ msgstr "``date1 == date2``" msgid "``date1 != date2``" msgstr "``date1 != date2``" -#: ../../library/datetime.rst:594 ../../library/datetime.rst:1186 +#: ../../library/datetime.rst:630 ../../library/datetime.rst:1226 msgid "Equality comparison. (4)" msgstr "Comparação de igualdade. (4)" @@ -1082,11 +1264,11 @@ msgstr "``date1 <= date2``" msgid "``date1 >= date2``" msgstr "``date1 >= date2``" -#: ../../library/datetime.rst:597 ../../library/datetime.rst:1189 +#: ../../library/datetime.rst:633 ../../library/datetime.rst:1229 msgid "Order comparison. (5)" msgstr "Comparação de ordem. (5)" -#: ../../library/datetime.rst:606 +#: ../../library/datetime.rst:642 msgid "" "*date2* is moved forward in time if ``timedelta.days > 0``, or backward if " "``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``. " @@ -1100,11 +1282,11 @@ msgstr "" "exceção :exc:`OverflowError` é levantada se ``date2.year`` for menor que :" "const:`MINYEAR` ou maior que :const:`MAXYEAR`." -#: ../../library/datetime.rst:613 +#: ../../library/datetime.rst:649 msgid "``timedelta.seconds`` and ``timedelta.microseconds`` are ignored." msgstr "``timedelta.seconds`` e ``timedelta.microseconds`` são ignoradas." -#: ../../library/datetime.rst:616 +#: ../../library/datetime.rst:652 msgid "" "This is exact, and cannot overflow. ``timedelta.seconds`` and ``timedelta." "microseconds`` are 0, and ``date2 + timedelta == date1`` after." @@ -1112,11 +1294,11 @@ msgstr "" "Isso é exato e não pode estourar. ``timedelta.seconds`` e ``timedelta." "microseconds`` são 0, e ``date2 + timedelta == date1`` depois." -#: ../../library/datetime.rst:620 +#: ../../library/datetime.rst:656 msgid ":class:`date` objects are equal if they represent the same date." msgstr "Objetos :class:`date` são iguais se representam a mesma data." -#: ../../library/datetime.rst:622 +#: ../../library/datetime.rst:658 msgid "" ":class:`!date` objects that are not also :class:`.datetime` instances are " "never equal to :class:`!datetime` objects, even if they represent the same " @@ -1126,7 +1308,7 @@ msgstr "" "nunca são iguais a objetos :class:`!datetime`, mesmo que representem a mesma " "data." -#: ../../library/datetime.rst:627 +#: ../../library/datetime.rst:663 msgid "" "*date1* is considered less than *date2* when *date1* precedes *date2* in " "time. In other words, ``date1 < date2`` if and only if ``date1.toordinal() < " @@ -1136,7 +1318,7 @@ msgstr "" "tempo. Em outras palavras, ``date1 < date2`` se e somente se ``date1." "toordinal() < date2.toordinal()``." -#: ../../library/datetime.rst:631 +#: ../../library/datetime.rst:667 msgid "" "Order comparison between a :class:`!date` object that is not also a :class:`." "datetime` instance and a :class:`!datetime` object raises :exc:`TypeError`." @@ -1145,7 +1327,7 @@ msgstr "" "instância :class:`.datetime` e um objeto :class:`!datetime` levanta :exc:" "`TypeError`." -#: ../../library/datetime.rst:635 ../../library/datetime.rst:1257 +#: ../../library/datetime.rst:671 ../../library/datetime.rst:1297 msgid "" "Comparison between :class:`.datetime` object and an instance of the :class:" "`date` subclass that is not a :class:`!datetime` subclass no longer converts " @@ -1159,33 +1341,45 @@ msgstr "" "comportamento padrão pode ser alterado substituindo os métodos especiais de " "comparação nas subclasses." -#: ../../library/datetime.rst:643 +#: ../../library/datetime.rst:679 msgid "" "In Boolean contexts, all :class:`date` objects are considered to be true." msgstr "" "Em contextos booleanos, todo objeto :class:`date` é considerado verdadeiro." -#: ../../library/datetime.rst:649 +#: ../../library/datetime.rst:685 msgid "" -"Return a date with the same value, except for those parameters given new " -"values by whichever keyword arguments are specified." +"Return a new :class:`date` object with the same values, but with specified " +"parameters updated." msgstr "" -"Retorna uma data com o mesmo valor, exceto por aqueles parâmetros que " -"receberam novos valores, por quaisquer argumentos nomeados especificados." +"Retorna um novo objeto :class:`date` com os mesmos valores, mas com os " +"parâmetros especificados atualizados." -#: ../../library/datetime.rst:652 ../../library/datetime.rst:1913 +#: ../../library/datetime.rst:688 ../../library/datetime.rst:1953 msgid "Example::" msgstr "Exemplo::" -#: ../../library/datetime.rst:659 +#: ../../library/datetime.rst:690 msgid "" -":class:`date` objects are also supported by generic function :func:`copy." -"replace`." +">>> from datetime import date\n" +">>> d = date(2002, 12, 31)\n" +">>> d.replace(day=26)\n" +"datetime.date(2002, 12, 26)" msgstr "" -"Objetos :class:`date` também são suportados pela função genérica :func:`copy." -"replace`." +">>> from datetime import date\n" +">>> d = date(2002, 12, 31)\n" +">>> d.replace(day=26)\n" +"datetime.date(2002, 12, 26)" + +#: ../../library/datetime.rst:695 +msgid "" +"The generic function :func:`copy.replace` also supports :class:`date` " +"objects." +msgstr "" +"A função genérica :func:`copy.replace` também oferece suporte a objetos :" +"class:`date`." -#: ../../library/datetime.rst:665 ../../library/datetime.rst:1381 +#: ../../library/datetime.rst:701 ../../library/datetime.rst:1421 msgid "" "Return a :class:`time.struct_time` such as returned by :func:`time." "localtime`." @@ -1193,16 +1387,22 @@ msgstr "" "Retorna uma :class:`time.struct_time` tal como retornado por :func:`time." "localtime`." -#: ../../library/datetime.rst:667 +#: ../../library/datetime.rst:703 msgid "The hours, minutes and seconds are 0, and the DST flag is -1." msgstr "" "As horas, minutos e segundos são 0, e o sinalizador de horário de verão é -1." -#: ../../library/datetime.rst:669 ../../library/datetime.rst:1383 +#: ../../library/datetime.rst:705 ../../library/datetime.rst:1423 msgid "``d.timetuple()`` is equivalent to::" msgstr "``d.timetuple()`` é equivalente a::" -#: ../../library/datetime.rst:673 +#: ../../library/datetime.rst:707 +msgid "" +"time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))" +msgstr "" +"time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))" + +#: ../../library/datetime.rst:709 msgid "" "where ``yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the " "day number within the current year starting with 1 for January 1st." @@ -1210,17 +1410,17 @@ msgstr "" "sendo ``yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` o número " "do dia no ano atual, começando com 1 para 1º de janeiro." -#: ../../library/datetime.rst:679 +#: ../../library/datetime.rst:715 msgid "" "Return the proleptic Gregorian ordinal of the date, where January 1 of year " -"1 has ordinal 1. For any :class:`date` object *d*, ``date.fromordinal(d." +"1 has ordinal 1. For any :class:`date` object ``d``, ``date.fromordinal(d." "toordinal()) == d``." msgstr "" "Retorna o ordinal proléptico gregoriano da data, considerando que 1º de " -"janeiro do ano 1 tem o ordinal 1. Para qualquer objeto :class:`date` *d*, " +"janeiro do ano 1 tem o ordinal 1. Para qualquer objeto :class:`date` ``d``, " "``date.fromordinal(d.toordinal()) == d``." -#: ../../library/datetime.rst:686 +#: ../../library/datetime.rst:722 msgid "" "Return the day of the week as an integer, where Monday is 0 and Sunday is 6. " "For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also :" @@ -1230,7 +1430,7 @@ msgstr "" "exemplo, ``date(2002, 12, 4).weekday() == 2``, uma Quarta-feira. Veja " "também :meth:`isoweekday`." -#: ../../library/datetime.rst:693 +#: ../../library/datetime.rst:729 msgid "" "Return the day of the week as an integer, where Monday is 1 and Sunday is 7. " "For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also :" @@ -1240,7 +1440,7 @@ msgstr "" "exemplo, ``date(2002, 12, 4).isoweekday() == 3``, uma Quarta-feira. Veja " "também :meth:`weekday`, :meth:`isocalendar`." -#: ../../library/datetime.rst:700 +#: ../../library/datetime.rst:736 msgid "" "Return a :term:`named tuple` object with three components: ``year``, " "``week`` and ``weekday``." @@ -1248,14 +1448,14 @@ msgstr "" "Retorna um objeto :term:`tupla nomeada ` com três componentes: " "``year``, ``week`` e ``weekday``." -#: ../../library/datetime.rst:703 +#: ../../library/datetime.rst:739 msgid "" "The ISO calendar is a widely used variant of the Gregorian calendar. [#]_" msgstr "" "O calendário ISO é uma variação amplamente usada do calendário gregoriano. " "[#]_" -#: ../../library/datetime.rst:705 +#: ../../library/datetime.rst:741 msgid "" "The ISO year consists of 52 or 53 full weeks, and where a week starts on a " "Monday and ends on a Sunday. The first week of an ISO year is the first " @@ -1269,7 +1469,7 @@ msgstr "" "feira. Isso é chamado de semana número 1, e o ano ISO dessa quinta-feira é o " "mesmo que o seu ano Gregoriano." -#: ../../library/datetime.rst:710 +#: ../../library/datetime.rst:746 msgid "" "For example, 2004 begins on a Thursday, so the first week of ISO year 2004 " "begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004::" @@ -1278,30 +1478,68 @@ msgstr "" "ISO 2004 começa na segunda-feira, 29 de dezembro de 2003, e termina no " "domingo, 4 de janeiro de 2004::" -#: ../../library/datetime.rst:719 +#: ../../library/datetime.rst:749 +msgid "" +">>> from datetime import date\n" +">>> date(2003, 12, 29).isocalendar()\n" +"datetime.IsoCalendarDate(year=2004, week=1, weekday=1)\n" +">>> date(2004, 1, 4).isocalendar()\n" +"datetime.IsoCalendarDate(year=2004, week=1, weekday=7)" +msgstr "" +">>> from datetime import date\n" +">>> date(2003, 12, 29).isocalendar()\n" +"datetime.IsoCalendarDate(year=2004, week=1, weekday=1)\n" +">>> date(2004, 1, 4).isocalendar()\n" +"datetime.IsoCalendarDate(year=2004, week=1, weekday=7)" + +#: ../../library/datetime.rst:755 msgid "Result changed from a tuple to a :term:`named tuple`." msgstr "" "Resultado alterado de uma tupla para uma :term:`tupla nomeada `." -#: ../../library/datetime.rst:724 +#: ../../library/datetime.rst:760 msgid "" "Return a string representing the date in ISO 8601 format, ``YYYY-MM-DD``::" msgstr "" "Retorna uma string representando a data no formato ISO 8601, ``YYYY-MM-DD``::" -#: ../../library/datetime.rst:732 -msgid "For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``." -msgstr "Para uma data *d*, ``str(d)`` é equivalente a ``d.isoformat()``." +#: ../../library/datetime.rst:762 +msgid "" +">>> from datetime import date\n" +">>> date(2002, 12, 4).isoformat()\n" +"'2002-12-04'" +msgstr "" +">>> from datetime import date\n" +">>> date(2002, 12, 4).isoformat()\n" +"'2002-12-04'" -#: ../../library/datetime.rst:737 +#: ../../library/datetime.rst:768 +msgid "For a date ``d``, ``str(d)`` is equivalent to ``d.isoformat()``." +msgstr "Para um data ``d``, ``str(d)`` é equivalente a ``d.isoformat()``." + +#: ../../library/datetime.rst:773 msgid "Return a string representing the date::" msgstr "Retorna uma string representando a data::" -#: ../../library/datetime.rst:743 ../../library/datetime.rst:1567 +#: ../../library/datetime.rst:775 +msgid "" +">>> from datetime import date\n" +">>> date(2002, 12, 4).ctime()\n" +"'Wed Dec 4 00:00:00 2002'" +msgstr "" +">>> from datetime import date\n" +">>> date(2002, 12, 4).ctime()\n" +"'Wed Dec 4 00:00:00 2002'" + +#: ../../library/datetime.rst:779 ../../library/datetime.rst:1607 msgid "``d.ctime()`` is equivalent to::" msgstr "``d.ctime()`` é equivalente a::" -#: ../../library/datetime.rst:747 +#: ../../library/datetime.rst:781 ../../library/datetime.rst:1609 +msgid "time.ctime(time.mktime(d.timetuple()))" +msgstr "time.ctime(time.mktime(d.timetuple()))" + +#: ../../library/datetime.rst:783 msgid "" "on platforms where the native C :c:func:`ctime` function (which :func:`time." "ctime` invokes, but which :meth:`date.ctime` does not invoke) conforms to " @@ -1311,7 +1549,7 @@ msgstr "" "função :func:`time.ctime`, mas não pelo método :meth:`.date.ctime`) se " "conforma com o padrão C." -#: ../../library/datetime.rst:754 +#: ../../library/datetime.rst:790 msgid "" "Return a string representing the date, controlled by an explicit format " "string. Format codes referring to hours, minutes or seconds will see 0 " @@ -1323,7 +1561,7 @@ msgstr "" "segundos irão ver valores 0. Veja também :ref:`strftime-strptime-behavior` " "e :meth:`date.isoformat`." -#: ../../library/datetime.rst:761 +#: ../../library/datetime.rst:797 msgid "" "Same as :meth:`.date.strftime`. This makes it possible to specify a format " "string for a :class:`.date` object in :ref:`formatted string literals ` e ao usar :meth:`str.format`. Veja também :" "ref:`strftime-strptime-behavior` e :meth:`date.isoformat`." -#: ../../library/datetime.rst:767 +#: ../../library/datetime.rst:803 msgid "Examples of Usage: :class:`date`" msgstr "Exemplos de uso: :class:`.date`" -#: ../../library/datetime.rst:769 +#: ../../library/datetime.rst:805 msgid "Example of counting days to an event::" msgstr "Exemplo de contagem de dias para um evento::" -#: ../../library/datetime.rst:788 +#: ../../library/datetime.rst:807 +msgid "" +">>> import time\n" +">>> from datetime import date\n" +">>> today = date.today()\n" +">>> today\n" +"datetime.date(2007, 12, 5)\n" +">>> today == date.fromtimestamp(time.time())\n" +"True\n" +">>> my_birthday = date(today.year, 6, 24)\n" +">>> if my_birthday < today:\n" +"... my_birthday = my_birthday.replace(year=today.year + 1)\n" +"...\n" +">>> my_birthday\n" +"datetime.date(2008, 6, 24)\n" +">>> time_to_birthday = abs(my_birthday - today)\n" +">>> time_to_birthday.days\n" +"202" +msgstr "" +">>> import time\n" +">>> from datetime import date\n" +">>> hoje = date.today()\n" +">>> hoje\n" +"datetime.date(2007, 12, 5)\n" +">>> hoje == date.fromtimestamp(time.time())\n" +"True\n" +">>> meu_aniversário = date(hoje.year, 6, 24)\n" +">>> if meu_aniversário < hoje:\n" +"... meu_aniversário = meu_aniversário.replace(year=hoje.year + 1)\n" +"...\n" +">>> meu_aniversário\n" +"datetime.date(2008, 6, 24)\n" +">>> tempo_até_aniversário = abs(meu_aniversário - hoje)\n" +">>> tempo_até_aniversário.days\n" +"202" + +#: ../../library/datetime.rst:824 msgid "More examples of working with :class:`date`:" msgstr "Mais exemplos de uso da classe :class:`.date`:" -#: ../../library/datetime.rst:837 +#: ../../library/datetime.rst:826 +msgid "" +">>> from datetime import date\n" +">>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001\n" +">>> d\n" +"datetime.date(2002, 3, 11)\n" +"\n" +">>> # Methods related to formatting string output\n" +">>> d.isoformat()\n" +"'2002-03-11'\n" +">>> d.strftime(\"%d/%m/%y\")\n" +"'11/03/02'\n" +">>> d.strftime(\"%A %d. %B %Y\")\n" +"'Monday 11. March 2002'\n" +">>> d.ctime()\n" +"'Mon Mar 11 00:00:00 2002'\n" +">>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, \"day\", \"month\")\n" +"'The day is 11, the month is March.'\n" +"\n" +">>> # Methods for to extracting 'components' under different calendars\n" +">>> t = d.timetuple()\n" +">>> for i in t:\n" +"... print(i)\n" +"2002 # year\n" +"3 # month\n" +"11 # day\n" +"0\n" +"0\n" +"0\n" +"0 # weekday (0 = Monday)\n" +"70 # 70th day in the year\n" +"-1\n" +">>> ic = d.isocalendar()\n" +">>> for i in ic:\n" +"... print(i)\n" +"2002 # ISO year\n" +"11 # ISO week number\n" +"1 # ISO day number ( 1 = Monday )\n" +"\n" +">>> # A date object is immutable; all operations produce a new object\n" +">>> d.replace(year=2005)\n" +"datetime.date(2005, 3, 11)" +msgstr "" +">>> from datetime import date\n" +">>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001\n" +">>> d\n" +"datetime.date(2002, 3, 11)\n" +"\n" +">>> # Methods related to formatting string output\n" +">>> d.isoformat()\n" +"'2002-03-11'\n" +">>> d.strftime(\"%d/%m/%y\")\n" +"'11/03/02'\n" +">>> d.strftime(\"%A %d. %B %Y\")\n" +"'Monday 11. March 2002'\n" +">>> d.ctime()\n" +"'Mon Mar 11 00:00:00 2002'\n" +">>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, \"day\", \"month\")\n" +"'The day is 11, the month is March.'\n" +"\n" +">>> # Methods for to extracting 'components' under different calendars\n" +">>> t = d.timetuple()\n" +">>> for i in t:\n" +"... print(i)\n" +"2002 # year\n" +"3 # month\n" +"11 # day\n" +"0\n" +"0\n" +"0\n" +"0 # weekday (0 = Monday)\n" +"70 # 70th day in the year\n" +"-1\n" +">>> ic = d.isocalendar()\n" +">>> for i in ic:\n" +"... print(i)\n" +"2002 # ISO year\n" +"11 # ISO week number\n" +"1 # ISO day number ( 1 = Monday )\n" +"\n" +">>> # A date object is immutable; all operations produce a new object\n" +">>> d.replace(year=2005)\n" +"datetime.date(2005, 3, 11)" + +#: ../../library/datetime.rst:873 msgid ":class:`.datetime` Objects" msgstr "Objetos :class:`.datetime`" -#: ../../library/datetime.rst:839 +#: ../../library/datetime.rst:875 msgid "" "A :class:`.datetime` object is a single object containing all the " "information from a :class:`date` object and a :class:`.time` object." @@ -1359,7 +1717,7 @@ msgstr "" "Um objeto :class:`.datetime` é um único objeto contendo todas as informações " "de um objeto :class:`.date` e um objeto :class:`.time`." -#: ../../library/datetime.rst:842 +#: ../../library/datetime.rst:878 msgid "" "Like a :class:`date` object, :class:`.datetime` assumes the current " "Gregorian calendar extended in both directions; like a :class:`.time` " @@ -1371,11 +1729,11 @@ msgstr "" "class:`.time`, :class:`.datetime` presume que existem exatamente 3600\\*24 " "segundos em cada dia." -#: ../../library/datetime.rst:846 +#: ../../library/datetime.rst:882 msgid "Constructor:" msgstr "Construtor:" -#: ../../library/datetime.rst:850 +#: ../../library/datetime.rst:886 msgid "" "The *year*, *month* and *day* arguments are required. *tzinfo* may be " "``None``, or an instance of a :class:`tzinfo` subclass. The remaining " @@ -1385,56 +1743,62 @@ msgstr "" "``None``, ou uma instância de subclasse de :class:`tzinfo`. Os argumentos " "remanescentes devem ser inteiros nos seguintes intervalos:" -#: ../../library/datetime.rst:854 +#: ../../library/datetime.rst:890 msgid "``MINYEAR <= year <= MAXYEAR``," msgstr "``MINYEAR <= year <= MAXYEAR``," -#: ../../library/datetime.rst:855 +#: ../../library/datetime.rst:891 msgid "``1 <= month <= 12``," msgstr "``1 <= month <= 12``," -#: ../../library/datetime.rst:856 +#: ../../library/datetime.rst:892 msgid "``1 <= day <= number of days in the given month and year``," msgstr "``1 <= day <= número de dias no mês e ano fornecidos``," -#: ../../library/datetime.rst:857 ../../library/datetime.rst:1731 +#: ../../library/datetime.rst:893 ../../library/datetime.rst:1771 msgid "``0 <= hour < 24``," msgstr "``0 <= hour < 24``," -#: ../../library/datetime.rst:858 ../../library/datetime.rst:1732 +#: ../../library/datetime.rst:894 ../../library/datetime.rst:1772 msgid "``0 <= minute < 60``," msgstr "``0 <= minute < 60``," -#: ../../library/datetime.rst:859 ../../library/datetime.rst:1733 +#: ../../library/datetime.rst:895 ../../library/datetime.rst:1773 msgid "``0 <= second < 60``," msgstr "``0 <= second < 60``," -#: ../../library/datetime.rst:860 ../../library/datetime.rst:1734 +#: ../../library/datetime.rst:896 ../../library/datetime.rst:1774 msgid "``0 <= microsecond < 1000000``," msgstr "``0 <= microsecond < 1000000``," -#: ../../library/datetime.rst:861 ../../library/datetime.rst:1735 +#: ../../library/datetime.rst:897 ../../library/datetime.rst:1775 msgid "``fold in [0, 1]``." msgstr "``fold in [0, 1]``." -#: ../../library/datetime.rst:865 ../../library/datetime.rst:1302 -#: ../../library/datetime.rst:1880 +#: ../../library/datetime.rst:901 ../../library/datetime.rst:1342 +#: ../../library/datetime.rst:1920 msgid "Added the *fold* parameter." msgstr "Adicionado o parâmetro *fold*." -#: ../../library/datetime.rst:872 +#: ../../library/datetime.rst:908 msgid "Return the current local date and time, with :attr:`.tzinfo` ``None``." msgstr "" +"Retorna a data e hora local atual, com o atributo :attr:`.tzinfo` definido " +"para ``None``." -#: ../../library/datetime.rst:874 +#: ../../library/datetime.rst:910 msgid "Equivalent to::" msgstr "Equivalente a::" -#: ../../library/datetime.rst:878 +#: ../../library/datetime.rst:912 +msgid "datetime.fromtimestamp(time.time())" +msgstr "datetime.fromtimestamp(time.time())" + +#: ../../library/datetime.rst:914 msgid "See also :meth:`now`, :meth:`fromtimestamp`." msgstr "Veja também :meth:`now`, :meth:`fromtimestamp`." -#: ../../library/datetime.rst:880 +#: ../../library/datetime.rst:916 msgid "" "This method is functionally equivalent to :meth:`now`, but without a ``tz`` " "parameter." @@ -1442,11 +1806,11 @@ msgstr "" "Este método é funcionalmente equivalente a :meth:`now`, mas sem um parâmetro " "``tz``." -#: ../../library/datetime.rst:885 +#: ../../library/datetime.rst:921 msgid "Return the current local date and time." msgstr "Retorna a data e hora local atual." -#: ../../library/datetime.rst:887 +#: ../../library/datetime.rst:923 msgid "" "If optional argument *tz* is ``None`` or not specified, this is like :meth:" "`today`, but, if possible, supplies more precision than can be gotten from " @@ -1459,7 +1823,7 @@ msgstr "" "exemplo, isto pode ser possível em plataformas que fornecem a função C :c:" "func:`gettimeofday`)." -#: ../../library/datetime.rst:893 +#: ../../library/datetime.rst:929 msgid "" "If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` " "subclass, and the current date and time are converted to *tz*’s time zone." @@ -1468,15 +1832,23 @@ msgstr "" "class:`tzinfo`, e a data e hora local atual são convertidas para o fuso " "horário de *tz*." -#: ../../library/datetime.rst:896 +#: ../../library/datetime.rst:932 msgid "This function is preferred over :meth:`today` and :meth:`utcnow`." msgstr "Esta função é preferida ao invés de :meth:`today` e :meth:`utcnow`." -#: ../../library/datetime.rst:901 +#: ../../library/datetime.rst:936 +msgid "" +"Subsequent calls to :meth:`!datetime.now` may return the same instant " +"depending on the precision of the underlying clock." +msgstr "" +"Chamadas subsequentes para :meth:`!datetime.now` podem retornar o mesmo " +"instante, dependendo da precisão do relógio subjacente." + +#: ../../library/datetime.rst:941 msgid "Return the current UTC date and time, with :attr:`.tzinfo` ``None``." msgstr "Retorna a data e hora atual em UTC, com :attr:`.tzinfo` como ``None``." -#: ../../library/datetime.rst:903 +#: ../../library/datetime.rst:943 msgid "" "This is like :meth:`now`, but returns the current UTC date and time, as a " "naive :class:`.datetime` object. An aware current UTC datetime can be " @@ -1486,7 +1858,7 @@ msgstr "" "um objeto :class:`.datetime` ingênuo. Um datetime UTC consciente pode ser " "obtido chamando ``datetime.now(timezone.utc)``. Veja também :meth:`now`." -#: ../../library/datetime.rst:909 +#: ../../library/datetime.rst:949 msgid "" "Because naive ``datetime`` objects are treated by many ``datetime`` methods " "as local times, it is preferred to use aware datetimes to represent times in " @@ -1499,11 +1871,11 @@ msgstr "" "recomendada para criar um objeto representando a hora local em UTC é " "chamando ``datetime.now(timezone.utc)``." -#: ../../library/datetime.rst:916 -msgid "Use :meth:`datetime.now` with :attr:`UTC` instead." -msgstr "Use :meth:`datetime.now` com :attr:`UTC`." +#: ../../library/datetime.rst:956 +msgid "Use :meth:`datetime.now` with :const:`UTC` instead." +msgstr "Use :meth:`datetime.now` com :const:`UTC`." -#: ../../library/datetime.rst:921 +#: ../../library/datetime.rst:961 msgid "" "Return the local date and time corresponding to the POSIX timestamp, such as " "is returned by :func:`time.time`. If optional argument *tz* is ``None`` or " @@ -1516,7 +1888,7 @@ msgstr "" "data e hora local da plataforma, e o objeto :class:`.datetime` retornado é " "ingênuo." -#: ../../library/datetime.rst:926 +#: ../../library/datetime.rst:966 msgid "" "If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` " "subclass, and the timestamp is converted to *tz*’s time zone." @@ -1525,7 +1897,7 @@ msgstr "" "class:`tzinfo`, e o registro de data e hora é convertido para o fuso horário " "de *tz*." -#: ../../library/datetime.rst:929 +#: ../../library/datetime.rst:969 msgid "" ":meth:`fromtimestamp` may raise :exc:`OverflowError`, if the timestamp is " "out of the range of values supported by the platform C :c:func:`localtime` " @@ -1548,7 +1920,7 @@ msgstr "" "apresentam objetos :class:`.datetime` idênticos. Este método é preferido " "sobre :meth:`utcfromtimestamp`." -#: ../../library/datetime.rst:940 +#: ../../library/datetime.rst:980 msgid "" "Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp is " "out of the range of values supported by the platform C :c:func:`localtime` " @@ -1561,12 +1933,12 @@ msgstr "" "exc:`OSError` ao invés de :exc:`ValueError` em falhas de :c:func:`localtime` " "ou :c:func:`gmtime`." -#: ../../library/datetime.rst:947 +#: ../../library/datetime.rst:987 msgid ":meth:`fromtimestamp` may return instances with :attr:`.fold` set to 1." msgstr "" ":meth:`fromtimestamp` pode retornar instâncias com :attr:`.fold` igual a 1." -#: ../../library/datetime.rst:952 +#: ../../library/datetime.rst:992 msgid "" "Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, " "with :attr:`.tzinfo` ``None``. (The resulting object is naive.)" @@ -1575,7 +1947,7 @@ msgstr "" "POSIX, com :attr:`.tzinfo` setado para ``None``. (O objeto resultante é " "ingênuo.)" -#: ../../library/datetime.rst:955 +#: ../../library/datetime.rst:995 msgid "" "This may raise :exc:`OverflowError`, if the timestamp is out of the range of " "values supported by the platform C :c:func:`gmtime` function, and :exc:" @@ -1587,20 +1959,30 @@ msgstr "" "`gmtime` da plataforma, e em caso de falha :exc:`OSError` em :c:func:" "`gmtime`. É comum que isso seja restrito a anos de 1970 a 2038." -#: ../../library/datetime.rst:960 +#: ../../library/datetime.rst:1000 msgid "To get an aware :class:`.datetime` object, call :meth:`fromtimestamp`::" msgstr "" "Para conseguir um objeto :class:`.datetime` consciente, chame :meth:" "`fromtimestamp`::" -#: ../../library/datetime.rst:964 +#: ../../library/datetime.rst:1002 +msgid "datetime.fromtimestamp(timestamp, timezone.utc)" +msgstr "datetime.fromtimestamp(timestamp, timezone.utc)" + +#: ../../library/datetime.rst:1004 msgid "" "On the POSIX compliant platforms, it is equivalent to the following " "expression::" msgstr "" "Nas plataformas compatíveis com POSIX, é equivalente à seguinte expressão::" -#: ../../library/datetime.rst:969 +#: ../../library/datetime.rst:1007 +msgid "" +"datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)" +msgstr "" +"datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)" + +#: ../../library/datetime.rst:1009 msgid "" "except the latter formula always supports the full years range: between :" "const:`MINYEAR` and :const:`MAXYEAR` inclusive." @@ -1608,7 +1990,7 @@ msgstr "" "com a exceção de que a última fórmula sempre dá suporte ao intervalo " "completo de anos: entre :const:`MINYEAR` e :const:`MAXYEAR` inclusive." -#: ../../library/datetime.rst:974 +#: ../../library/datetime.rst:1014 msgid "" "Because naive ``datetime`` objects are treated by many ``datetime`` methods " "as local times, it is preferred to use aware datetimes to represent times in " @@ -1623,7 +2005,7 @@ msgstr "" "específico em UTC é chamando ``datetime.fromtimestamp(timestamp, tz=timezone." "utc)``." -#: ../../library/datetime.rst:980 +#: ../../library/datetime.rst:1020 msgid "" "Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp is " "out of the range of values supported by the platform C :c:func:`gmtime` " @@ -1635,11 +2017,11 @@ msgstr "" "func:`gmtime` da plataforma. Levanta :exc:`OSError` ao invés de :exc:" "`ValueError` em caso de falha :c:func:`gmtime`." -#: ../../library/datetime.rst:988 -msgid "Use :meth:`datetime.fromtimestamp` with :attr:`UTC` instead." -msgstr "Use :meth:`datetime.fromtimestamp` com :attr:`UTC`." +#: ../../library/datetime.rst:1028 +msgid "Use :meth:`datetime.fromtimestamp` with :const:`UTC` instead." +msgstr "Use :meth:`datetime.fromtimestamp` com :const:`UTC`." -#: ../../library/datetime.rst:993 +#: ../../library/datetime.rst:1033 msgid "" "Return the :class:`.datetime` corresponding to the proleptic Gregorian " "ordinal, where January 1 of year 1 has ordinal 1. :exc:`ValueError` is " @@ -1653,7 +2035,7 @@ msgstr "" "horas, minutos, segundos e micro segundos do resultado são todos 0, e :attr:" "`.tzinfo` é ``None``." -#: ../../library/datetime.rst:1001 +#: ../../library/datetime.rst:1041 msgid "" "Return a new :class:`.datetime` object whose date components are equal to " "the given :class:`date` object's, and whose time components are equal to the " @@ -1671,19 +2053,19 @@ msgstr "" "*time* é usado. Se o argumento *date* é um objeto :class:`.datetime`, seus " "componentes de hora e atributos :attr:`.tzinfo` são ignorados." -#: ../../library/datetime.rst:1009 +#: ../../library/datetime.rst:1049 msgid "" -"For any :class:`.datetime` object *d*, ``d == datetime.combine(d.date(), d." +"For any :class:`.datetime` object ``d``, ``d == datetime.combine(d.date(), d." "time(), d.tzinfo)``." msgstr "" -"Para qualquer objeto :class:`.datetime` *d*, ``d == datetime.combine(d." +"Para qualquer objeto :class:`.datetime` ``d``, ``d == datetime.combine(d." "date(), d.time(), d.tzinfo)``." -#: ../../library/datetime.rst:1012 +#: ../../library/datetime.rst:1052 msgid "Added the *tzinfo* argument." msgstr "Adicionado o argumento *tzinfo*." -#: ../../library/datetime.rst:1018 +#: ../../library/datetime.rst:1058 msgid "" "Return a :class:`.datetime` corresponding to a *date_string* in any valid " "ISO 8601 format, with the following exceptions:" @@ -1691,28 +2073,74 @@ msgstr "" "Retorna um :class:`.datetime` correspondendo a *date_string* em qualquer " "formato válido de ISO 8601, com as seguintes exceções:" -#: ../../library/datetime.rst:1021 ../../library/datetime.rst:1831 +#: ../../library/datetime.rst:1061 ../../library/datetime.rst:1871 msgid "Time zone offsets may have fractional seconds." msgstr "Os deslocamentos de fuso horário podem ter segundos fracionários." -#: ../../library/datetime.rst:1022 +#: ../../library/datetime.rst:1062 msgid "The ``T`` separator may be replaced by any single unicode character." msgstr "" "O separador ``T`` pode ser substituído por qualquer caractere unicode único." -#: ../../library/datetime.rst:1023 ../../library/datetime.rst:1836 +#: ../../library/datetime.rst:1063 ../../library/datetime.rst:1876 msgid "Fractional hours and minutes are not supported." msgstr "Horas e minutos fracionários não são suportados." -#: ../../library/datetime.rst:1054 +#: ../../library/datetime.rst:1072 +msgid "" +">>> from datetime import datetime\n" +">>> datetime.fromisoformat('2011-11-04')\n" +"datetime.datetime(2011, 11, 4, 0, 0)\n" +">>> datetime.fromisoformat('20111104')\n" +"datetime.datetime(2011, 11, 4, 0, 0)\n" +">>> datetime.fromisoformat('2011-11-04T00:05:23')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23)\n" +">>> datetime.fromisoformat('2011-11-04T00:05:23Z')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone.utc)\n" +">>> datetime.fromisoformat('20111104T000523')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23)\n" +">>> datetime.fromisoformat('2011-W01-2T00:05:23.283')\n" +"datetime.datetime(2011, 1, 4, 0, 5, 23, 283000)\n" +">>> datetime.fromisoformat('2011-11-04 00:05:23.283')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23, 283000)\n" +">>> datetime.fromisoformat('2011-11-04 00:05:23.283+00:00')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone." +"utc)\n" +">>> datetime.fromisoformat('2011-11-04T00:05:23+04:00')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23,\n" +" tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))" +msgstr "" +">>> from datetime import datetime\n" +">>> datetime.fromisoformat('2011-11-04')\n" +"datetime.datetime(2011, 11, 4, 0, 0)\n" +">>> datetime.fromisoformat('20111104')\n" +"datetime.datetime(2011, 11, 4, 0, 0)\n" +">>> datetime.fromisoformat('2011-11-04T00:05:23')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23)\n" +">>> datetime.fromisoformat('2011-11-04T00:05:23Z')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone.utc)\n" +">>> datetime.fromisoformat('20111104T000523')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23)\n" +">>> datetime.fromisoformat('2011-W01-2T00:05:23.283')\n" +"datetime.datetime(2011, 1, 4, 0, 5, 23, 283000)\n" +">>> datetime.fromisoformat('2011-11-04 00:05:23.283')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23, 283000)\n" +">>> datetime.fromisoformat('2011-11-04 00:05:23.283+00:00')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone." +"utc)\n" +">>> datetime.fromisoformat('2011-11-04T00:05:23+04:00')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23,\n" +" tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))" + +#: ../../library/datetime.rst:1094 msgid "" "Previously, this method only supported formats that could be emitted by :" -"meth:`date.isoformat()` or :meth:`datetime.isoformat()`." +"meth:`date.isoformat` or :meth:`datetime.isoformat`." msgstr "" "Anteriormente, este método suportava apenas formatos que podiam ser emitidos " -"por :meth:`date.isoformat()` ou :meth:`datetime.isoformat()`." +"por :meth:`date.isoformat` ou :meth:`datetime.isoformat`." -#: ../../library/datetime.rst:1061 +#: ../../library/datetime.rst:1101 msgid "" "Return a :class:`.datetime` corresponding to the ISO calendar date specified " "by year, week and day. The non-date components of the datetime are populated " @@ -1724,7 +2152,7 @@ msgstr "" "são preenchidos normalmente com seus valores padrões. Isso é o inverso da " "função :meth:`datetime.isocalendar`." -#: ../../library/datetime.rst:1070 +#: ../../library/datetime.rst:1110 msgid "" "Return a :class:`.datetime` corresponding to *date_string*, parsed according " "to *format*." @@ -1732,13 +2160,19 @@ msgstr "" "Retorna um :class:`.datetime` correspondente ao *date_string*, analisado de " "acordo com *format*." -#: ../../library/datetime.rst:1073 +#: ../../library/datetime.rst:1113 msgid "" "If *format* does not contain microseconds or time zone information, this is " "equivalent to::" msgstr "" +"Se *format* não contiver microssegundos ou informações de fuso horário, isso " +"é equivalente a::" -#: ../../library/datetime.rst:1077 +#: ../../library/datetime.rst:1115 ../../library/datetime.rst:2596 +msgid "datetime(*(time.strptime(date_string, format)[0:6]))" +msgstr "datetime(*(time.strptime(date_string, format)[0:6]))" + +#: ../../library/datetime.rst:1117 msgid "" ":exc:`ValueError` is raised if the date_string and format can't be parsed " "by :func:`time.strptime` or if it returns a value which isn't a time tuple. " @@ -1750,7 +2184,7 @@ msgstr "" "não é uma tupla temporal. Veja também :ref:`strftime-strptime-behavior` e :" "meth:`datetime.fromisoformat`." -#: ../../library/datetime.rst:1084 +#: ../../library/datetime.rst:1124 msgid "" "If *format* specifies a day of month without a year a :exc:" "`DeprecationWarning` is now emitted. This is to avoid a quadrennial leap " @@ -1760,8 +2194,32 @@ msgid "" "include a year in your *format*. If parsing *date_string* values that do " "not have a year, explicitly add a year that is a leap year before parsing:" msgstr "" - -#: ../../library/datetime.rst:1106 +"Se *format* especificar um dia do mês sem um ano, um :exc:" +"`DeprecationWarning` agora é emitido. Isso é para evitar um bug de ano " +"bissexto quadrienal no código que busca analisar apenas um mês e dia, pois o " +"ano padrão usado na ausência de um no formato não é um ano bissexto. Esses " +"valores de *format* podem gerar um erro a partir do Python 3.15. A solução " +"alternativa é sempre incluir um ano em seu *format*. Se estiver analisando " +"valores de *date_string* que não têm um ano, adicione explicitamente um ano " +"que seja um ano bissexto antes da análise:" + +#: ../../library/datetime.rst:1133 +msgid "" +">>> from datetime import datetime\n" +">>> date_string = \"02/29\"\n" +">>> when = datetime.strptime(f\"{date_string};1984\", \"%m/%d;%Y\") # " +"Avoids leap year bug.\n" +">>> when.strftime(\"%B %d\")\n" +"'February 29'" +msgstr "" +">>> from datetime import datetime\n" +">>> date_string = \"02/29\"\n" +">>> when = datetime.strptime(f\"{date_string};1984\", \"%m/%d;%Y\") # " +"Avoids leap year bug.\n" +">>> when.strftime(\"%B %d\")\n" +"'February 29'" + +#: ../../library/datetime.rst:1146 msgid "" "The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1, " "tzinfo=None)``." @@ -1769,7 +2227,7 @@ msgstr "" "O primeiro :class:`.datetime` representável, ``datetime(MINYEAR, 1, 1, " "tzinfo=None)``." -#: ../../library/datetime.rst:1112 +#: ../../library/datetime.rst:1152 msgid "" "The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, " "59, 59, 999999, tzinfo=None)``." @@ -1777,7 +2235,7 @@ msgstr "" "O último :class:`.datetime` representável, ``datetime(MAXYEAR, 12, 31, 23, " "59, 59, 999999, tzinfo=None)``." -#: ../../library/datetime.rst:1118 +#: ../../library/datetime.rst:1158 msgid "" "The smallest possible difference between non-equal :class:`.datetime` " "objects, ``timedelta(microseconds=1)``." @@ -1785,20 +2243,20 @@ msgstr "" "A menor diferença possível entre objetos :class:`.datetime` diferentes, " "``timedelta(microseconds=1)``." -#: ../../library/datetime.rst:1141 ../../library/datetime.rst:1764 +#: ../../library/datetime.rst:1181 ../../library/datetime.rst:1804 msgid "In ``range(24)``." msgstr "No intervalo ``range(24)``." -#: ../../library/datetime.rst:1146 ../../library/datetime.rst:1151 -#: ../../library/datetime.rst:1769 ../../library/datetime.rst:1774 +#: ../../library/datetime.rst:1186 ../../library/datetime.rst:1191 +#: ../../library/datetime.rst:1809 ../../library/datetime.rst:1814 msgid "In ``range(60)``." msgstr "No intervalo ``range(60)``." -#: ../../library/datetime.rst:1156 ../../library/datetime.rst:1779 +#: ../../library/datetime.rst:1196 ../../library/datetime.rst:1819 msgid "In ``range(1000000)``." msgstr "No intervalo ``range(1000000)``." -#: ../../library/datetime.rst:1161 +#: ../../library/datetime.rst:1201 msgid "" "The object passed as the *tzinfo* argument to the :class:`.datetime` " "constructor, or ``None`` if none was passed." @@ -1806,7 +2264,7 @@ msgstr "" "O objeto passado como o argumento *tzinfo* do construtor :class:`.datetime`, " "ou ``None`` se nada foi passado." -#: ../../library/datetime.rst:1167 ../../library/datetime.rst:1790 +#: ../../library/datetime.rst:1207 ../../library/datetime.rst:1830 msgid "" "In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. " "(A repeated interval occurs when clocks are rolled back at the end of " @@ -1815,27 +2273,33 @@ msgid "" "respectively, the earlier and later of the two moments with the same wall " "time representation." msgstr "" +"Entre ``[0, 1]``. Usado para desambiguar tempos reais durante um intervalo " +"repetido. (Um intervalo repetido ocorre quando relógios são atrasados ao " +"final do horário de verão ou quando a diferença UTC para o fuso horário " +"atual é reduzida por razões políticas.) Os valores 0 e 1 representam, " +"respectivamente, o primeiro e o segundo dos dois momentos com a mesma " +"representação de tempo real." -#: ../../library/datetime.rst:1180 +#: ../../library/datetime.rst:1220 msgid "``datetime2 = datetime1 + timedelta``" msgstr "``datetime2 = datetime1 + timedelta``" -#: ../../library/datetime.rst:1180 ../../library/datetime.rst:2403 -#: ../../library/datetime.rst:2408 ../../library/datetime.rst:2420 -#: ../../library/datetime.rst:2425 ../../library/datetime.rst:2485 -#: ../../library/datetime.rst:2490 ../../library/datetime.rst:2494 +#: ../../library/datetime.rst:1220 ../../library/datetime.rst:2443 +#: ../../library/datetime.rst:2448 ../../library/datetime.rst:2460 +#: ../../library/datetime.rst:2465 ../../library/datetime.rst:2525 +#: ../../library/datetime.rst:2530 ../../library/datetime.rst:2534 msgid "\\(1)" msgstr "\\(1)" -#: ../../library/datetime.rst:1182 +#: ../../library/datetime.rst:1222 msgid "``datetime2 = datetime1 - timedelta``" msgstr "``datetime2 = datetime1 - timedelta``" -#: ../../library/datetime.rst:1182 ../../library/datetime.rst:2436 +#: ../../library/datetime.rst:1222 ../../library/datetime.rst:2476 msgid "\\(2)" msgstr "\\(2)" -#: ../../library/datetime.rst:1184 +#: ../../library/datetime.rst:1224 msgid "``timedelta = datetime1 - datetime2``" msgstr "``timedelta = datetime1 - datetime2``" @@ -1863,7 +2327,7 @@ msgstr "``datetime1 <= datetime2``" msgid "``datetime1 >= datetime2``" msgstr "``datetime1 >= datetime2``" -#: ../../library/datetime.rst:1196 +#: ../../library/datetime.rst:1236 msgid "" "``datetime2`` is a duration of ``timedelta`` removed from ``datetime1``, " "moving forward in time if ``timedelta.days > 0``, or backward if ``timedelta." @@ -1873,16 +2337,28 @@ msgid "" "`MINYEAR` or larger than :const:`MAXYEAR`. Note that no time zone " "adjustments are done even if the input is an aware object." msgstr "" +"``datetime2`` representa a duração de ``timedelta`` removido de " +"``datetime1``, movendo o tempo para frente se ``timedelta.days > 0``, ou " +"para trás se ``timedelta.days < 0``. O resultado tem o mesmo atributo :attr:" +"`~.datetime.tzinfo` que o datetime de entrada, e ``datetime2 - datetime1 == " +"timedelta`` após. :exc:`OverflowError` é levantada se ``datetime2.year`` " +"fosse menor que :const:`MINYEAR` ou maior que :const:`MAXYEAR`. Perceba que " +"nenhum ajuste no fuso horário é feito mesmo se a entrada é um objeto " +"consciente disso." -#: ../../library/datetime.rst:1205 +#: ../../library/datetime.rst:1245 msgid "" "Computes the ``datetime2`` such that ``datetime2 + timedelta == datetime1``. " "As for addition, the result has the same :attr:`~.datetime.tzinfo` attribute " "as the input datetime, and no time zone adjustments are done even if the " "input is aware." msgstr "" +"Computa o ``datetime2`` tal que ``datetime2 + timedelta == datetime1``. " +"Assim como para adição, o resultado tem o mesmo atributo :attr:`~.datetime." +"tzinfo` que datetime de entrada, e nenhum ajuste de fuso horário é feito " +"mesmo que a entrada seja consciente disso." -#: ../../library/datetime.rst:1210 +#: ../../library/datetime.rst:1250 msgid "" "Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined " "only if both operands are naive, or if both are aware. If one is aware and " @@ -1892,33 +2368,34 @@ msgstr "" "apenas se ambos os operandos são ingênuos, ou se ambos são conscientes. Se " "um deles é consciente e o outro é ingênuo, :exc:`TypeError` é levantado." -#: ../../library/datetime.rst:1214 +#: ../../library/datetime.rst:1254 msgid "" "If both are naive, or both are aware and have the same :attr:`~.datetime." "tzinfo` attribute, the :attr:`~.datetime.tzinfo` attributes are ignored, and " -"the result is a :class:`timedelta` object *t* such that ``datetime2 + t == " +"the result is a :class:`timedelta` object ``t`` such that ``datetime2 + t == " "datetime1``. No time zone adjustments are done in this case." msgstr "" -"Se ambos são ingênuos, ou ambos são conscientes e tem o mesmo atributo :attr:" -"`~.datetime.tzinfo`, os atributos :attr:`~.datetime.tzinfo` são ignorados, e " -"o resultado é um objeto *t* do tipo :class:`timedelta`, tal que ``datetime2 " -"+ t == datetime1``. Nenhum ajuste de fuso horário é feito neste caso." +"Se ambos são ingênuos, ou ambos são conscientes e tiverem o mesmo atributo :" +"attr:`~.datetime.tzinfo`, os atributos :attr:`~.datetime.tzinfo` são " +"ignorados, e o resultado é um objeto ``t`` do tipo :class:`timedelta`, tal " +"que ``datetime2 + t == datetime1``. Nenhum ajuste de fuso horário é feito " +"neste caso." -#: ../../library/datetime.rst:1219 +#: ../../library/datetime.rst:1259 msgid "" "If both are aware and have different :attr:`~.datetime.tzinfo` attributes, " -"``a-b`` acts as if *a* and *b* were first converted to naive UTC datetimes. " -"The result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b." +"``a-b`` acts as if ``a`` and ``b`` were first converted to naive UTC " +"datetimes. The result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b." "replace(tzinfo=None) - b.utcoffset())`` except that the implementation never " "overflows." msgstr "" "Se ambas são conscientes e têm atributos :attr:`~.datetime.tzinfo` " -"diferentes, ``a-b`` age como se *a* e *b* foram primeiro convertidas para " -"datetimes ingênuas em UTC. O resultado é ``(a.replace(tzinfo=None) - a." -"utcoffset()) - (b.replace(tzinfo=None) - b.utcoffset())`` exceto que a a " -"implementação nunca ultrapassa o limite." +"diferentes, ``a-b`` age como se ``a`` e ``b`` tivessem sido primeiro " +"convertidos para datetimes ingênuas em UTC. O resultado é ``(a." +"replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) - b." +"utcoffset())`` exceto que a implementação nunca estoura." -#: ../../library/datetime.rst:1225 +#: ../../library/datetime.rst:1265 msgid "" ":class:`.datetime` objects are equal if they represent the same date and " "time, taking into account the time zone." @@ -1926,11 +2403,11 @@ msgstr "" "Objetos :class:`.datetime` são iguais se representarem a mesma data e hora, " "levando em consideração o fuso horário." -#: ../../library/datetime.rst:1228 +#: ../../library/datetime.rst:1268 msgid "Naive and aware :class:`!datetime` objects are never equal." -msgstr "" +msgstr "Objetos :class:`!datetime` ingênuos e conscientes nunca são iguais." -#: ../../library/datetime.rst:1230 +#: ../../library/datetime.rst:1270 msgid "" "If both comparands are aware, and have the same :attr:`!tzinfo` attribute, " "the :attr:`!tzinfo` and :attr:`~.datetime.fold` attributes are ignored and " @@ -1940,20 +2417,32 @@ msgid "" "implementation never overflows. :class:`!datetime` instances in a repeated " "interval are never equal to :class:`!datetime` instances in other time zone." msgstr "" +"Se ambos os comparandos forem conscientes e tiverem o mesmo atributo :attr:`!" +"tzinfo`, os atributos :attr:`!tzinfo` e :attr:`~.datetime.fold` serão " +"ignorados e os datetimes base serão comparados. Se ambos os comparandos " +"forem conscientes e tiverem atributos :attr:`~.datetime.tzinfo` diferentes, " +"a comparação atua como se os comparandos fossem primeiro convertidos para " +"datetimes UTC, exceto que a implementação nunca estoura. Instâncias :class:`!" +"datetime` em um intervalo repetido nunca são iguais a instâncias :class:`!" +"datetime` em outro fuso horário." -#: ../../library/datetime.rst:1240 +#: ../../library/datetime.rst:1280 msgid "" "*datetime1* is considered less than *datetime2* when *datetime1* precedes " "*datetime2* in time, taking into account the time zone." msgstr "" +"*datetime1* é considerado menor que *datetime2* quando *datetime1* precede " +"*datetime2* no tempo. levando em consideração o fuso horário." -#: ../../library/datetime.rst:1243 +#: ../../library/datetime.rst:1283 msgid "" "Order comparison between naive and aware :class:`.datetime` objects raises :" "exc:`TypeError`." msgstr "" +"A comparação de ordens entre objetos :class:`.datetime` ingênuos e " +"conscientes levanta :exc:`TypeError`." -#: ../../library/datetime.rst:1246 +#: ../../library/datetime.rst:1286 msgid "" "If both comparands are aware, and have the same :attr:`!tzinfo` attribute, " "the :attr:`!tzinfo` and :attr:`~.datetime.fold` attributes are ignored and " @@ -1962,8 +2451,14 @@ msgid "" "comparands were first converted to UTC datetimes except that the " "implementation never overflows." msgstr "" +"Se ambos os comparandos forem conscientes e tiverem o mesmo atributo :attr:`!" +"tzinfo`, os atributos :attr:`!tzinfo` e :attr:`~.datetime.fold` serão " +"ignorados e os datetimes base serão comparados. Se ambos os comparandos " +"forem conscientes e tiverem atributos :attr:`~.datetime.tzinfo` diferentes, " +"a comparação atua como se os comparandos fossem primeiro convertidos para " +"datetimes UTC, exceto que a implementação nunca estoura." -#: ../../library/datetime.rst:1253 +#: ../../library/datetime.rst:1293 msgid "" "Equality comparisons between aware and naive :class:`.datetime` instances " "don't raise :exc:`TypeError`." @@ -1971,11 +2466,11 @@ msgstr "" "Comparações de igualdade entre instâncias de :class:`.datetime` conscientes " "e nativas não levantam :exc:`TypeError`." -#: ../../library/datetime.rst:1269 +#: ../../library/datetime.rst:1309 msgid "Return :class:`date` object with same year, month and day." msgstr "Retorna um objeto :class:`date` com o mesmo ano, mês e dia." -#: ../../library/datetime.rst:1274 +#: ../../library/datetime.rst:1314 msgid "" "Return :class:`.time` object with same hour, minute, second, microsecond and " "fold. :attr:`.tzinfo` is ``None``. See also method :meth:`timetz`." @@ -1984,11 +2479,11 @@ msgstr "" "microssegundo e fold. O atributo :attr:`.tzinfo` é ``None``. Veja também o " "método :meth:`.timetz`." -#: ../../library/datetime.rst:1277 ../../library/datetime.rst:1286 +#: ../../library/datetime.rst:1317 ../../library/datetime.rst:1326 msgid "The fold value is copied to the returned :class:`.time` object." msgstr "O valor fold é copiado para o objeto :class:`.time` retornado." -#: ../../library/datetime.rst:1283 +#: ../../library/datetime.rst:1323 msgid "" "Return :class:`.time` object with same hour, minute, second, microsecond, " "fold, and tzinfo attributes. See also method :meth:`time`." @@ -1996,26 +2491,27 @@ msgstr "" "Retorna um objeto :class:`.time` com os mesmos atributos de hora, minuto, " "segundo, microssegundo, fold e tzinfo. Veja também o método :meth:`time`." -#: ../../library/datetime.rst:1294 +#: ../../library/datetime.rst:1334 msgid "" -"Return a datetime with the same attributes, except for those attributes " -"given new values by whichever keyword arguments are specified. Note that " -"``tzinfo=None`` can be specified to create a naive datetime from an aware " -"datetime with no conversion of date and time data." +"Return a new :class:`datetime` object with the same attributes, but with " +"specified parameters updated. Note that ``tzinfo=None`` can be specified to " +"create a naive datetime from an aware datetime with no conversion of date " +"and time data." msgstr "" -"Retorna um datetime com os mesmos atributos, exceto para aqueles atributos " -"que receberam novos valores por quaisquer argumentos nomeados que foram " -"especificados. Perceba que ``tzinfo=None`` pode ser especificado para criar " -"um datetime ingênuo a partir de um datetime consciente, sem conversão de " -"dados da data ou hora." +"Retorna um novo objeto :class:`datetime` com os mesmos atributos, mas com os " +"parâmetros especificados atualizados. Perceba que ``tzinfo=None`` pode ser " +"especificado para criar um datetime ingênuo a partir de um datetime " +"consciente, sem conversão de dados da data ou hora." -#: ../../library/datetime.rst:1299 +#: ../../library/datetime.rst:1339 msgid "" ":class:`.datetime` objects are also supported by generic function :func:" "`copy.replace`." msgstr "" +"Objetos :class:`.datetime` também são suportados pela função genérica :func:" +"`copy.replace`." -#: ../../library/datetime.rst:1308 +#: ../../library/datetime.rst:1348 msgid "" "Return a :class:`.datetime` object with new :attr:`.tzinfo` attribute *tz*, " "adjusting the date and time data so the result is the same UTC time as " @@ -2025,22 +2521,31 @@ msgstr "" "definido por *tz*, ajustando a data e hora de forma que o resultado seja o " "mesmo horário UTC que *self*, mas na hora local de *tz*." -#: ../../library/datetime.rst:1312 +#: ../../library/datetime.rst:1352 msgid "" "If provided, *tz* must be an instance of a :class:`tzinfo` subclass, and " "its :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. If " "*self* is naive, it is presumed to represent time in the system time zone." msgstr "" +"Se fornecido, *tz* deve ser uma instância de uma subclasse :class:`tzinfo`, " +"e seus métodos :meth:`utcoffset` e :meth:`dst` não devem retornar ``None``. " +"Se *self* for ingênuo, é presumido que ele representa o tempo no fuso " +"horário do sistema." -#: ../../library/datetime.rst:1316 +#: ../../library/datetime.rst:1356 msgid "" "If called without arguments (or with ``tz=None``) the system local time zone " "is assumed for the target time zone. The ``.tzinfo`` attribute of the " "converted datetime instance will be set to an instance of :class:`timezone` " "with the zone name and offset obtained from the OS." msgstr "" +"Se for chamado sem argumentos (ou com ``tz=None``) o fuso horário do sistema " +"local é presumido como o fuso horário desejado. O atributo ``.tzinfo`` da " +"instância datetime convertida será definido para uma instância de :class:" +"`timezone` com o nome da zona e um deslocamento obtido a partir do sistema " +"operacional." -#: ../../library/datetime.rst:1321 +#: ../../library/datetime.rst:1361 msgid "" "If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no " "adjustment of date or time data is performed. Else the result is local time " @@ -2048,8 +2553,14 @@ msgid "" "``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will have the same " "date and time data as ``dt - dt.utcoffset()``." msgstr "" +"Se ``self.tzinfo`` for *tz*, ``self.astimezone(tz)`` é igual a *self*: " +"nenhum ajuste nos dados de data ou hora é realizado. Caso contrário o " +"resultado é a hora local no fuso horário *tz*, representando a mesma hora " +"UTC que *self*: depois ``astz = dt.astimezone(tz)``, ``astz - astz." +"utcoffset()`` terá os mesmos dados de data e hora que ``dt - dt." +"utcoffset()``." -#: ../../library/datetime.rst:1327 +#: ../../library/datetime.rst:1367 msgid "" "If you merely want to attach a :class:`timezone` object *tz* to a datetime " "*dt* without adjustment of date and time data, use ``dt." @@ -2057,8 +2568,13 @@ msgid "" "object from an aware datetime *dt* without conversion of date and time data, " "use ``dt.replace(tzinfo=None)``." msgstr "" +"Se você quer meramente anexar um objeto :class:`timezone` *tz* a um datetime " +"*dt* sem ajustes de dados de data e hora, use ``dt.replace(tzinfo=tz)``. Se " +"você meramente quer remover o objeto :class:`!timezone` de um datetime " +"consciente *dt* sem conversão de dados de data e hora, use ``dt." +"replace(tzinfo=None)``." -#: ../../library/datetime.rst:1332 +#: ../../library/datetime.rst:1372 msgid "" "Note that the default :meth:`tzinfo.fromutc` method can be overridden in a :" "class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`. " @@ -2069,11 +2585,29 @@ msgstr "" "`astimezone`. Ignorando erros de letras maiúsculas/minúsculas, :meth:" "`astimezone` funciona como::" -#: ../../library/datetime.rst:1344 +#: ../../library/datetime.rst:1376 +msgid "" +"def astimezone(self, tz):\n" +" if self.tzinfo is tz:\n" +" return self\n" +" # Convert self to UTC, and attach the new timezone object.\n" +" utc = (self - self.utcoffset()).replace(tzinfo=tz)\n" +" # Convert from UTC to tz's local time.\n" +" return tz.fromutc(utc)" +msgstr "" +"def astimezone(self, tz):\n" +" if self.tzinfo is tz:\n" +" return self\n" +" # Converte self para UTC e anexa o novo objeto timezone.\n" +" utc = (self - self.utcoffset()).replace(tzinfo=tz)\n" +" # Converte o horário local de UTC para tz.\n" +" return tz.fromutc(utc)" + +#: ../../library/datetime.rst:1384 msgid "*tz* now can be omitted." msgstr "*tz* agora pode ser omitido." -#: ../../library/datetime.rst:1347 +#: ../../library/datetime.rst:1387 msgid "" "The :meth:`astimezone` method can now be called on naive instances that are " "presumed to represent system local time." @@ -2081,7 +2615,7 @@ msgstr "" "O método :meth:`astimezone` agora pode ser chamado em instâncias ingênuas " "que presumidamente representam a hora local do sistema." -#: ../../library/datetime.rst:1354 +#: ../../library/datetime.rst:1394 msgid "" "If :attr:`.tzinfo` is ``None``, returns ``None``, else returns ``self.tzinfo." "utcoffset(self)``, and raises an exception if the latter doesn't return " @@ -2092,13 +2626,13 @@ msgstr "" "retornar ``None`` ou um objeto :class:`timedelta` com magnitude menor que um " "dia." -#: ../../library/datetime.rst:1358 ../../library/datetime.rst:1953 -#: ../../library/datetime.rst:2060 ../../library/datetime.rst:2305 -#: ../../library/datetime.rst:2317 ../../library/datetime.rst:2629 +#: ../../library/datetime.rst:1398 ../../library/datetime.rst:1993 +#: ../../library/datetime.rst:2100 ../../library/datetime.rst:2345 +#: ../../library/datetime.rst:2357 ../../library/datetime.rst:2669 msgid "The UTC offset is not restricted to a whole number of minutes." msgstr "A diferença UTC não é restrita a um número completo de minutos." -#: ../../library/datetime.rst:1364 +#: ../../library/datetime.rst:1404 msgid "" "If :attr:`.tzinfo` is ``None``, returns ``None``, else returns ``self.tzinfo." "dst(self)``, and raises an exception if the latter doesn't return ``None`` " @@ -2108,14 +2642,14 @@ msgstr "" "``self.tzinfo.dst(self)``, e levanta uma exceção se o segundo não retornar " "``None`` ou um objeto :class:`timedelta` com magnitude menor que um dia." -#: ../../library/datetime.rst:1368 ../../library/datetime.rst:1963 -#: ../../library/datetime.rst:2114 +#: ../../library/datetime.rst:1408 ../../library/datetime.rst:2003 +#: ../../library/datetime.rst:2154 msgid "The DST offset is not restricted to a whole number of minutes." msgstr "" "A diferença de horário de verão não é restrita a um número completo de " "minutos." -#: ../../library/datetime.rst:1374 +#: ../../library/datetime.rst:1414 msgid "" "If :attr:`.tzinfo` is ``None``, returns ``None``, else returns ``self.tzinfo." "tzname(self)``, raises an exception if the latter doesn't return ``None`` or " @@ -2125,7 +2659,17 @@ msgstr "" "``self.tzinfo.tzname(self)``, levanta uma exceção se o segundo não retornar " "``None`` ou um objeto string." -#: ../../library/datetime.rst:1389 +#: ../../library/datetime.rst:1425 +msgid "" +"time.struct_time((d.year, d.month, d.day,\n" +" d.hour, d.minute, d.second,\n" +" d.weekday(), yday, dst))" +msgstr "" +"time.struct_time((d.year, d.month, d.day,\n" +" d.hour, d.minute, d.second,\n" +" d.weekday(), yday, dst))" + +#: ../../library/datetime.rst:1429 msgid "" "where ``yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the " "day number within the current year starting with 1 for January 1st. The :" @@ -2135,25 +2679,41 @@ msgid "" "non-zero value, :attr:`!tm_isdst` is set to 1; else :attr:`!tm_isdst` is set " "to 0." msgstr "" +"onde ``yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` é o " +"número de dias dentro do ano atual, começando com 1 para 1º de janeiro. O " +"sinalizador :attr:`~time.struct_time.tm_isdst` do resultado é definido " +"conforme o método :meth:`dst`: :attr:`.tzinfo` é ``None`` ou :meth:`dst` " +"retorna ``None``, :attr:`!tm_isdst` é definido para ``-1``; caso contrário " +"se :meth:`dst` retornar um valor diferente de zero, :attr:`!tm_isdst` é " +"definido para 1; caso contrário :attr:`!tm_isdst` é definido para 0." -#: ../../library/datetime.rst:1400 +#: ../../library/datetime.rst:1440 msgid "" -"If :class:`.datetime` instance *d* is naive, this is the same as ``d." +"If :class:`.datetime` instance ``d`` is naive, this is the same as ``d." "timetuple()`` except that :attr:`~.time.struct_time.tm_isdst` is forced to 0 " "regardless of what ``d.dst()`` returns. DST is never in effect for a UTC " "time." msgstr "" +"Se a instância :class:`.datetime` ``d`` é ingênua, isto é o mesmo que ``d." +"timetuple()``, exceto que :attr:`~.time.struct_time.tm_isdst` é forçado para " +"0, independentemente do que ``d.dst()`` retornar. O horário de verão nunca é " +"afetado por um horário UTC." -#: ../../library/datetime.rst:1404 +#: ../../library/datetime.rst:1444 msgid "" -"If *d* is aware, *d* is normalized to UTC time, by subtracting ``d." +"If ``d`` is aware, ``d`` is normalized to UTC time, by subtracting ``d." "utcoffset()``, and a :class:`time.struct_time` for the normalized time is " "returned. :attr:`!tm_isdst` is forced to 0. Note that an :exc:" "`OverflowError` may be raised if ``d.year`` was ``MINYEAR`` or ``MAXYEAR`` " "and UTC adjustment spills over a year boundary." msgstr "" +"Se ``d`` é consciente, ``d`` é normalizado para horário UTC, subtraindo ``d." +"utcoffset()``, e um :class:`time.struct_time` para o horário normalizado é " +"retornado. :attr:`!tm_isdst` é forçado para 0. Observe que uma exceção :exc:" +"`OverflowError` pode ser levantada se ``d.year`` for ``MINYEAR`` ou " +"``MAXYEAR`` e os ajustes UTC ultrapassar o limite de um ano." -#: ../../library/datetime.rst:1413 +#: ../../library/datetime.rst:1453 msgid "" "Because naive ``datetime`` objects are treated by many ``datetime`` methods " "as local times, it is preferred to use aware datetimes to represent times in " @@ -2170,7 +2730,7 @@ msgstr "" "para torná-lo consciente, ponto no qual você pode usar :meth:`.datetime." "timetuple`." -#: ../../library/datetime.rst:1422 +#: ../../library/datetime.rst:1462 msgid "" "Return the proleptic Gregorian ordinal of the date. The same as ``self." "date().toordinal()``." @@ -2178,7 +2738,7 @@ msgstr "" "Retorna o ordinal proléptico gregoriano da data. o mesmo que ``self.date()." "toordinal()``." -#: ../../library/datetime.rst:1427 +#: ../../library/datetime.rst:1467 msgid "" "Return POSIX timestamp corresponding to the :class:`.datetime` instance. The " "return value is a :class:`float` similar to that returned by :func:`time." @@ -2188,7 +2748,7 @@ msgstr "" "datetime`. O valor de retorno é um :class:`float` similar aquele retornado " "por :func:`time.time`." -#: ../../library/datetime.rst:1431 +#: ../../library/datetime.rst:1471 msgid "" "Naive :class:`.datetime` instances are assumed to represent local time and " "this method relies on the platform C :c:func:`mktime` function to perform " @@ -2204,14 +2764,18 @@ msgstr "" "levantar :exc:`OverflowError` ou :exc:`OSError` para horários longe no " "passado ou longe no futuro." -#: ../../library/datetime.rst:1438 +#: ../../library/datetime.rst:1478 msgid "" "For aware :class:`.datetime` instances, the return value is computed as::" msgstr "" "Para instâncias conscientes de :class:`.datetime`, o valor retornado é " "computado como::" -#: ../../library/datetime.rst:1445 +#: ../../library/datetime.rst:1481 +msgid "(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()" +msgstr "(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()" + +#: ../../library/datetime.rst:1485 msgid "" "The :meth:`timestamp` method uses the :attr:`.fold` attribute to " "disambiguate the times during a repeated interval." @@ -2219,19 +2783,32 @@ msgstr "" "O método :meth:`timestamp` usa o atributo :attr:`.fold` para desambiguar os " "tempos durante um intervalo repetido." -#: ../../library/datetime.rst:1451 +#: ../../library/datetime.rst:1491 msgid "" "There is no method to obtain the POSIX timestamp directly from a naive :" "class:`.datetime` instance representing UTC time. If your application uses " "this convention and your system time zone is not set to UTC, you can obtain " "the POSIX timestamp by supplying ``tzinfo=timezone.utc``::" msgstr "" +"Não existe método para obter o timestamp POSIX diretamente de uma instância :" +"class:`.datetime` ingênua representando tempo em UTC. Se a sua aplicação usa " +"esta convenção e o fuso horário do seu sistema não está setado para UTC, " +"você pode obter o registro de data e hora POSIX fornecendo ``tzinfo=timezone." +"utc``::" -#: ../../library/datetime.rst:1459 +#: ../../library/datetime.rst:1497 +msgid "timestamp = dt.replace(tzinfo=timezone.utc).timestamp()" +msgstr "timestamp = dt.replace(tzinfo=timezone.utc).timestamp()" + +#: ../../library/datetime.rst:1499 msgid "or by calculating the timestamp directly::" msgstr "ou calculando o registro de data e hora diretamente::" -#: ../../library/datetime.rst:1465 +#: ../../library/datetime.rst:1501 +msgid "timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)" +msgstr "timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)" + +#: ../../library/datetime.rst:1505 msgid "" "Return the day of the week as an integer, where Monday is 0 and Sunday is 6. " "The same as ``self.date().weekday()``. See also :meth:`isoweekday`." @@ -2239,7 +2816,7 @@ msgstr "" "Retorna o dia da semana como um inteiro, em que segunda-feira é 0 e domingo " "é 6. O mesmo que ``self.date().weekday()``. Veja também :meth:`isoweekday`." -#: ../../library/datetime.rst:1471 +#: ../../library/datetime.rst:1511 msgid "" "Return the day of the week as an integer, where Monday is 1 and Sunday is 7. " "The same as ``self.date().isoweekday()``. See also :meth:`weekday`, :meth:" @@ -2249,7 +2826,7 @@ msgstr "" "é 7. O mesmo que ``self.date().isoweekday()``. Veja também :meth:`weekday`, :" "meth:`isocalendar`." -#: ../../library/datetime.rst:1478 +#: ../../library/datetime.rst:1518 msgid "" "Return a :term:`named tuple` with three components: ``year``, ``week`` and " "``weekday``. The same as ``self.date().isocalendar()``." @@ -2257,19 +2834,19 @@ msgstr "" "Retorna uma :term:`tupla nomeada ` com três componentes: " "``year``, ``week`` e ``weekday``. O mesmo que ``self.date().isocalendar()``." -#: ../../library/datetime.rst:1484 +#: ../../library/datetime.rst:1524 msgid "Return a string representing the date and time in ISO 8601 format:" msgstr "Retorna uma string representando a data e o tempo no formato ISO 8601:" -#: ../../library/datetime.rst:1486 +#: ../../library/datetime.rst:1526 msgid "``YYYY-MM-DDTHH:MM:SS.ffffff``, if :attr:`microsecond` is not 0" msgstr "``YYYY-MM-DDTHH:MM:SS.ffffff``, se :attr:`microsecond` não é 0" -#: ../../library/datetime.rst:1487 +#: ../../library/datetime.rst:1527 msgid "``YYYY-MM-DDTHH:MM:SS``, if :attr:`microsecond` is 0" msgstr "``YYYY-MM-DDTHH:MM:SS``, se :attr:`microsecond` é 0" -#: ../../library/datetime.rst:1489 +#: ../../library/datetime.rst:1529 msgid "" "If :meth:`utcoffset` does not return ``None``, a string is appended, giving " "the UTC offset:" @@ -2277,7 +2854,7 @@ msgstr "" "Se :meth:`utcoffset` não retorna ``None``, uma string é adicionada com a " "diferença UTC:" -#: ../../library/datetime.rst:1492 +#: ../../library/datetime.rst:1532 msgid "" "``YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond` " "is not 0" @@ -2285,13 +2862,27 @@ msgstr "" "``YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]``, se :attr:`microsecond` " "não é 0" -#: ../../library/datetime.rst:1494 +#: ../../library/datetime.rst:1534 msgid "" "``YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond` is 0" msgstr "" "``YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]]``, se :attr:`microsecond` é 0" -#: ../../library/datetime.rst:1504 +#: ../../library/datetime.rst:1538 +msgid "" +">>> from datetime import datetime, timezone\n" +">>> datetime(2019, 5, 18, 15, 17, 8, 132263).isoformat()\n" +"'2019-05-18T15:17:08.132263'\n" +">>> datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat()\n" +"'2019-05-18T15:17:00+00:00'" +msgstr "" +">>> from datetime import datetime, timezone\n" +">>> datetime(2019, 5, 18, 15, 17, 8, 132263).isoformat()\n" +"'2019-05-18T15:17:08.132263'\n" +">>> datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat()\n" +"'2019-05-18T15:17:00+00:00'" + +#: ../../library/datetime.rst:1544 msgid "" "The optional argument *sep* (default ``'T'``) is a one-character separator, " "placed between the date and time portions of the result. For example::" @@ -2299,7 +2890,32 @@ msgstr "" "O argumento opcional *sep* (por padrão, ``'T'``) é um separador de caractere " "único, colocado entre as porções de data e tempo do resultado. Por exemplo::" -#: ../../library/datetime.rst:1518 ../../library/datetime.rst:1893 +#: ../../library/datetime.rst:1547 +msgid "" +">>> from datetime import tzinfo, timedelta, datetime\n" +">>> class TZ(tzinfo):\n" +"... \"\"\"A time zone with an arbitrary, constant -06:39 offset.\"\"\"\n" +"... def utcoffset(self, dt):\n" +"... return timedelta(hours=-6, minutes=-39)\n" +"...\n" +">>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')\n" +"'2002-12-25 00:00:00-06:39'\n" +">>> datetime(2009, 11, 27, microsecond=100, tzinfo=TZ()).isoformat()\n" +"'2009-11-27T00:00:00.000100-06:39'" +msgstr "" +">>> from datetime import tzinfo, timedelta, datetime\n" +">>> class TZ(tzinfo):\n" +"... \"\"\"Um fuso horário com uma posição arbitrária constante de -06:39." +"\"\"\"\n" +"... def utcoffset(self, dt):\n" +"... return timedelta(hours=-6, minutes=-39)\n" +"...\n" +">>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')\n" +"'2002-12-25 00:00:00-06:39'\n" +">>> datetime(2009, 11, 27, microsecond=100, tzinfo=TZ()).isoformat()\n" +"'2009-11-27T00:00:00.000100-06:39'" + +#: ../../library/datetime.rst:1558 ../../library/datetime.rst:1933 msgid "" "The optional argument *timespec* specifies the number of additional " "components of the time to include (the default is ``'auto'``). It can be one " @@ -2309,7 +2925,7 @@ msgstr "" "adicionais do tempo a incluir (o padrão é ``'auto'``). Pode ser uma das " "seguintes strings:" -#: ../../library/datetime.rst:1522 ../../library/datetime.rst:1897 +#: ../../library/datetime.rst:1562 ../../library/datetime.rst:1937 msgid "" "``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0, same as " "``'microseconds'`` otherwise." @@ -2317,20 +2933,20 @@ msgstr "" "``'auto'``: O mesmo que ``'seconds'`` se :attr:`microsecond` é 0, o mesmo " "que ``'microseconds'`` caso contrário." -#: ../../library/datetime.rst:1524 ../../library/datetime.rst:1899 +#: ../../library/datetime.rst:1564 ../../library/datetime.rst:1939 msgid "``'hours'``: Include the :attr:`hour` in the two-digit ``HH`` format." msgstr "" "``'hours'``: Inclui o atributo :attr:`hour` no formato de dois dígitos " "``HH``." -#: ../../library/datetime.rst:1525 ../../library/datetime.rst:1900 +#: ../../library/datetime.rst:1565 ../../library/datetime.rst:1940 msgid "" "``'minutes'``: Include :attr:`hour` and :attr:`minute` in ``HH:MM`` format." msgstr "" "``'minutes'``: Inclui os atributos :attr:`hour` e :attr:`minute` no formato " "``HH:MM``." -#: ../../library/datetime.rst:1526 ../../library/datetime.rst:1901 +#: ../../library/datetime.rst:1566 ../../library/datetime.rst:1941 msgid "" "``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second` in " "``HH:MM:SS`` format." @@ -2338,7 +2954,7 @@ msgstr "" "``'seconds'``: Inclui os atributos :attr:`hour`, :attr:`minute` e :attr:" "`second` no formato ``HH:MM:SS``." -#: ../../library/datetime.rst:1528 ../../library/datetime.rst:1903 +#: ../../library/datetime.rst:1568 ../../library/datetime.rst:1943 msgid "" "``'milliseconds'``: Include full time, but truncate fractional second part " "to milliseconds. ``HH:MM:SS.sss`` format." @@ -2346,38 +2962,64 @@ msgstr "" "``'milliseconds'``: Inclui o tempo completo, mas trunca a parte fracional " "dos segundos em milissegundos. Formato ``HH:MM:SS.sss``." -#: ../../library/datetime.rst:1530 ../../library/datetime.rst:1905 +#: ../../library/datetime.rst:1570 ../../library/datetime.rst:1945 msgid "``'microseconds'``: Include full time in ``HH:MM:SS.ffffff`` format." msgstr "" "``'microseconds'``: Inclui o tempo completo no formato ``HH:MM:SS.ffffff``." -#: ../../library/datetime.rst:1534 ../../library/datetime.rst:1909 +#: ../../library/datetime.rst:1574 ../../library/datetime.rst:1949 msgid "Excluded time components are truncated, not rounded." msgstr "Componentes do tempo excluídos são truncados, não arredondados." -#: ../../library/datetime.rst:1536 +#: ../../library/datetime.rst:1576 msgid ":exc:`ValueError` will be raised on an invalid *timespec* argument::" msgstr "" "A exceção :exc:`ValueError` vai ser levantada no caso de um argumento " "*timespec* inválido::" -#: ../../library/datetime.rst:1546 ../../library/datetime.rst:1924 -msgid "Added the *timespec* parameter." +#: ../../library/datetime.rst:1579 +msgid "" +">>> from datetime import datetime\n" +">>> datetime.now().isoformat(timespec='minutes')\n" +"'2002-12-25T00:00'\n" +">>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)\n" +">>> dt.isoformat(timespec='microseconds')\n" +"'2015-01-01T12:30:59.000000'" msgstr "" +">>> from datetime import datetime\n" +">>> datetime.now().isoformat(timespec='minutes')\n" +"'2002-12-25T00:00'\n" +">>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)\n" +">>> dt.isoformat(timespec='microseconds')\n" +"'2015-01-01T12:30:59.000000'" -#: ../../library/datetime.rst:1552 +#: ../../library/datetime.rst:1586 ../../library/datetime.rst:1964 +msgid "Added the *timespec* parameter." +msgstr "Adicionado o parâmetro *timespec*." + +#: ../../library/datetime.rst:1592 msgid "" -"For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to ``d." +"For a :class:`.datetime` instance ``d``, ``str(d)`` is equivalent to ``d." "isoformat(' ')``." msgstr "" -"Para uma instância :class:`.datetime` *d*, ``str(d)`` é equivalente a ``d." +"Para uma instância :class:`.datetime` ``d``, ``str(d)`` é equivalente a ``d." "isoformat(' ')``." -#: ../../library/datetime.rst:1558 +#: ../../library/datetime.rst:1598 msgid "Return a string representing the date and time::" msgstr "Retorna uma string representando a data e hora::" -#: ../../library/datetime.rst:1564 +#: ../../library/datetime.rst:1600 +msgid "" +">>> from datetime import datetime\n" +">>> datetime(2002, 12, 4, 20, 30, 40).ctime()\n" +"'Wed Dec 4 20:30:40 2002'" +msgstr "" +">>> from datetime import datetime\n" +">>> datetime(2002, 12, 4, 20, 30, 40).ctime()\n" +"'Wed Dec 4 20:30:40 2002'" + +#: ../../library/datetime.rst:1604 msgid "" "The output string will *not* include time zone information, regardless of " "whether the input is aware or naive." @@ -2385,7 +3027,7 @@ msgstr "" "A string de saída *não* irá incluir informações de fuso horário, " "independente de a entrada ser consciente ou ingênua." -#: ../../library/datetime.rst:1571 +#: ../../library/datetime.rst:1611 msgid "" "on platforms where the native C :c:func:`ctime` function (which :func:`time." "ctime` invokes, but which :meth:`datetime.ctime` does not invoke) conforms " @@ -2395,7 +3037,7 @@ msgstr "" "ctime` invoca, mas a qual :meth:`datetime.ctime` não invoca) conforma com o " "padrão C." -#: ../../library/datetime.rst:1578 +#: ../../library/datetime.rst:1618 msgid "" "Return a string representing the date and time, controlled by an explicit " "format string. See also :ref:`strftime-strptime-behavior` and :meth:" @@ -2405,7 +3047,7 @@ msgstr "" "com formato explícito. Veja também :ref:`strftime-strptime-behavior` e :meth:" "`datetime.isoformat`." -#: ../../library/datetime.rst:1585 +#: ../../library/datetime.rst:1625 msgid "" "Same as :meth:`.datetime.strftime`. This makes it possible to specify a " "format string for a :class:`.datetime` object in :ref:`formatted string " @@ -2417,15 +3059,120 @@ msgstr "" "string formatados ` e ao usar :meth:`str.format`. Veja também :" "ref:`strftime-strptime-behavior` e :meth:`datetime.isoformat`." -#: ../../library/datetime.rst:1592 +#: ../../library/datetime.rst:1632 msgid "Examples of Usage: :class:`.datetime`" msgstr "Exemplos de uso: :class:`.datetime`" -#: ../../library/datetime.rst:1594 +#: ../../library/datetime.rst:1634 msgid "Examples of working with :class:`.datetime` objects:" -msgstr "" - -#: ../../library/datetime.rst:1647 +msgstr "Exemplos para trabalhar com objetos :class:`.datetime`:" + +#: ../../library/datetime.rst:1636 +msgid "" +">>> from datetime import datetime, date, time, timezone\n" +"\n" +">>> # Using datetime.combine()\n" +">>> d = date(2005, 7, 14)\n" +">>> t = time(12, 30)\n" +">>> datetime.combine(d, t)\n" +"datetime.datetime(2005, 7, 14, 12, 30)\n" +"\n" +">>> # Using datetime.now()\n" +">>> datetime.now()\n" +"datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1\n" +">>> datetime.now(timezone.utc)\n" +"datetime.datetime(2007, 12, 6, 15, 29, 43, 79060, tzinfo=datetime.timezone." +"utc)\n" +"\n" +">>> # Using datetime.strptime()\n" +">>> dt = datetime.strptime(\"21/11/06 16:30\", \"%d/%m/%y %H:%M\")\n" +">>> dt\n" +"datetime.datetime(2006, 11, 21, 16, 30)\n" +"\n" +">>> # Using datetime.timetuple() to get tuple of all attributes\n" +">>> tt = dt.timetuple()\n" +">>> for it in tt:\n" +"... print(it)\n" +"...\n" +"2006 # year\n" +"11 # month\n" +"21 # day\n" +"16 # hour\n" +"30 # minute\n" +"0 # second\n" +"1 # weekday (0 = Monday)\n" +"325 # number of days since 1st January\n" +"-1 # dst - method tzinfo.dst() returned None\n" +"\n" +">>> # Date in ISO format\n" +">>> ic = dt.isocalendar()\n" +">>> for it in ic:\n" +"... print(it)\n" +"...\n" +"2006 # ISO year\n" +"47 # ISO week\n" +"2 # ISO weekday\n" +"\n" +">>> # Formatting a datetime\n" +">>> dt.strftime(\"%A, %d. %B %Y %I:%M%p\")\n" +"'Tuesday, 21. November 2006 04:30PM'\n" +">>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'." +"format(dt, \"day\", \"month\", \"time\")\n" +"'The day is 21, the month is November, the time is 04:30PM.'" +msgstr "" +">>> from datetime import datetime, date, time, timezone\n" +"\n" +">>> # Usando datetime.combine()\n" +">>> d = date(2005, 7, 14)\n" +">>> t = time(12, 30)\n" +">>> datetime.combine(d, t)\n" +"datetime.datetime(2005, 7, 14, 12, 30)\n" +"\n" +">>> # Usando datetime.now()\n" +">>> datetime.now()\n" +"datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1\n" +">>> datetime.now(timezone.utc)\n" +"datetime.datetime(2007, 12, 6, 15, 29, 43, 79060, tzinfo=datetime.timezone." +"utc)\n" +"\n" +">>> # Usando datetime.strptime()\n" +">>> dt = datetime.strptime(\"21/11/06 16:30\", \"%d/%m/%y %H:%M\")\n" +">>> dt\n" +"datetime.datetime(2006, 11, 21, 16, 30)\n" +"\n" +">>> # Usando datetime.timetuple() para obter uma tupla de todos os " +"atributos\n" +">>> tt = dt.timetuple()\n" +">>> for it in tt:\n" +"... print(it)\n" +"...\n" +"2006 # ano\n" +"11 # mês\n" +"21 # dia\n" +"16 # hora\n" +"30 # minuto\n" +"0 # segundo\n" +"1 # dia da semana (0 = Segunda-feira)\n" +"325 # número de dias desde 1º de janeiro\n" +"-1 # dst - método tzinfo.dst() retornou None\n" +"\n" +">>> # Data em formato ISO\n" +">>> ic = dt.isocalendar()\n" +">>> for it in ic:\n" +"... print(it)\n" +"...\n" +"2006 # ano ISO\n" +"47 # semana ISO\n" +"2 # dia da semana ISO\n" +"\n" +">>> # Formatando um datetime\n" +">>> dt.strftime(\"%A, %d. %B %Y %I:%M%p\")\n" +"'Tuesday, 21. November 2006 04:30PM'\n" +">>> 'O {1} é {0:%d}, o {2} é {0:%B}, a {3} é {0:%I:%M%p}.'.format(dt, " +"\"dia\", \"mês\", \"hora\")\n" +"'O dia é 21, o mês é November, a hora é 04:30PM.'" + +#: ../../library/datetime.rst:1687 msgid "" "The example below defines a :class:`tzinfo` subclass capturing time zone " "information for Kabul, Afghanistan, which used +4 UTC until 1945 and then " @@ -2435,21 +3182,160 @@ msgstr "" "de fuso horário para Kabul, Afeganistão, o qual usou +4 UTC até 1945 e " "depois +4:30 UTC após esse período::" -#: ../../library/datetime.rst:1694 +#: ../../library/datetime.rst:1691 +msgid "" +"from datetime import timedelta, datetime, tzinfo, timezone\n" +"\n" +"class KabulTz(tzinfo):\n" +" # Kabul used +4 until 1945, when they moved to +4:30\n" +" UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc)\n" +"\n" +" def utcoffset(self, dt):\n" +" if dt.year < 1945:\n" +" return timedelta(hours=4)\n" +" elif (1945, 1, 1, 0, 0) <= dt.timetuple()[:5] < (1945, 1, 1, 0, " +"30):\n" +" # An ambiguous (\"imaginary\") half-hour range representing\n" +" # a 'fold' in time due to the shift from +4 to +4:30.\n" +" # If dt falls in the imaginary range, use fold to decide how\n" +" # to resolve. See PEP495.\n" +" return timedelta(hours=4, minutes=(30 if dt.fold else 0))\n" +" else:\n" +" return timedelta(hours=4, minutes=30)\n" +"\n" +" def fromutc(self, dt):\n" +" # Follow same validations as in datetime.tzinfo\n" +" if not isinstance(dt, datetime):\n" +" raise TypeError(\"fromutc() requires a datetime argument\")\n" +" if dt.tzinfo is not self:\n" +" raise ValueError(\"dt.tzinfo is not self\")\n" +"\n" +" # A custom implementation is required for fromutc as\n" +" # the input to this function is a datetime with utc values\n" +" # but with a tzinfo set to self.\n" +" # See datetime.astimezone or fromtimestamp.\n" +" if dt.replace(tzinfo=timezone.utc) >= self.UTC_MOVE_DATE:\n" +" return dt + timedelta(hours=4, minutes=30)\n" +" else:\n" +" return dt + timedelta(hours=4)\n" +"\n" +" def dst(self, dt):\n" +" # Kabul does not observe daylight saving time.\n" +" return timedelta(0)\n" +"\n" +" def tzname(self, dt):\n" +" if dt >= self.UTC_MOVE_DATE:\n" +" return \"+04:30\"\n" +" return \"+04\"" +msgstr "" +"from datetime import timedelta, datetime, tzinfo, timezone\n" +"\n" +"class KabulTz(tzinfo):\n" +" # Kabul usou +4 até 1945, quando eles moveram para +4:30\n" +" UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc)\n" +"\n" +" def utcoffset(self, dt):\n" +" if dt.year < 1945:\n" +" return timedelta(hours=4)\n" +" elif (1945, 1, 1, 0, 0) <= dt.timetuple()[:5] < (1945, 1, 1, 0, " +"30):\n" +" # Um intervalo de meia hora ambíguo (\"imaginário\") " +"representando\n" +" # um 'fold' no tempo por causa da troca de +4 para +4:30.\n" +" # Se dt cair no intervalo imaginário, usa a fold para decidir " +"como\n" +" # para resolver. Veja PEP495.\n" +" return timedelta(hours=4, minutes=(30 if dt.fold else 0))\n" +" else:\n" +" return timedelta(hours=4, minutes=30)\n" +"\n" +" def fromutc(self, dt):\n" +" # Segue as mesmas validações como em datetime.tzinfo\n" +" if not isinstance(dt, datetime):\n" +" raise TypeError(\"fromutc() requer um argumento datetime\")\n" +" if dt.tzinfo is not self:\n" +" raise ValueError(\"dt.tzinfo não é self\")\n" +"\n" +" # Uma implementação personalizada é necessária para fromutc\n" +" # como a entrada para esta função é um datetime com valores utc\n" +" # mas com um tzinfo definido para self.\n" +" # Veja datetime.astimezone ou fromtimestamp.\n" +" if dt.replace(tzinfo=timezone.utc) >= self.UTC_MOVE_DATE:\n" +" return dt + timedelta(hours=4, minutes=30)\n" +" else:\n" +" return dt + timedelta(hours=4)\n" +"\n" +" def dst(self, dt):\n" +" # Kabul não tem horário de verão.\n" +" return timedelta(0)\n" +"\n" +" def tzname(self, dt):\n" +" if dt >= self.UTC_MOVE_DATE:\n" +" return \"+04:30\"\n" +" return \"+04\"" + +#: ../../library/datetime.rst:1734 msgid "Usage of ``KabulTz`` from above::" msgstr "Uso de ``KabulTz`` mostrado acima::" -#: ../../library/datetime.rst:1720 +#: ../../library/datetime.rst:1736 +msgid "" +">>> tz1 = KabulTz()\n" +"\n" +">>> # Datetime before the change\n" +">>> dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1)\n" +">>> print(dt1.utcoffset())\n" +"4:00:00\n" +"\n" +">>> # Datetime after the change\n" +">>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1)\n" +">>> print(dt2.utcoffset())\n" +"4:30:00\n" +"\n" +">>> # Convert datetime to another time zone\n" +">>> dt3 = dt2.astimezone(timezone.utc)\n" +">>> dt3\n" +"datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc)\n" +">>> dt2\n" +"datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz())\n" +">>> dt2 == dt3\n" +"True" +msgstr "" +">>> tz1 = KabulTz()\n" +"\n" +">>> # Datetime antes da alteração\n" +">>> dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1)\n" +">>> print(dt1.utcoffset())\n" +"4:00:00\n" +"\n" +">>> # Datetime após a alteração\n" +">>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1)\n" +">>> print(dt2.utcoffset())\n" +"4:30:00\n" +"\n" +">>> # Converte datetime para outro fuso horário\n" +">>> dt3 = dt2.astimezone(timezone.utc)\n" +">>> dt3\n" +"datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc)\n" +">>> dt2\n" +"datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz())\n" +">>> dt2 == dt3\n" +"True" + +#: ../../library/datetime.rst:1760 msgid ":class:`.time` Objects" msgstr "Objetos :class:`.time`" -#: ../../library/datetime.rst:1722 +#: ../../library/datetime.rst:1762 msgid "" "A :class:`.time` object represents a (local) time of day, independent of any " "particular day, and subject to adjustment via a :class:`tzinfo` object." msgstr "" +"Um objeto :class:`.time` representa a hora (local) do dia, independente de " +"qualquer dia em particular, e sujeito a ajustes através de um objeto :class:" +"`tzinfo`." -#: ../../library/datetime.rst:1727 +#: ../../library/datetime.rst:1767 msgid "" "All arguments are optional. *tzinfo* may be ``None``, or an instance of a :" "class:`tzinfo` subclass. The remaining arguments must be integers in the " @@ -2459,24 +3345,27 @@ msgstr "" "instância de uma subclasse de :class:`tzinfo`. Os argumentos remanescentes " "devem ser inteiros nos seguintes intervalos:" -#: ../../library/datetime.rst:1737 +#: ../../library/datetime.rst:1777 msgid "" "If an argument outside those ranges is given, :exc:`ValueError` is raised. " "All default to 0 except *tzinfo*, which defaults to ``None``." msgstr "" +"Se um argumento fora desses intervalos é fornecido, :exc:`ValueError` é " +"levantada. Todos tem como padrão o valor 0 exceto *tzinfo*, o qual tem o " +"valor padrão ``None``." -#: ../../library/datetime.rst:1745 +#: ../../library/datetime.rst:1785 msgid "The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``." msgstr "" "O :class:`.time` mais cedo que pode ser representado, ``time(0, 0, 0, 0)``." -#: ../../library/datetime.rst:1750 +#: ../../library/datetime.rst:1790 msgid "The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``." msgstr "" "O :class:`.time` mais tardio que pode ser representado, ``time(23, 59, 59, " "999999)``." -#: ../../library/datetime.rst:1755 +#: ../../library/datetime.rst:1795 msgid "" "The smallest possible difference between non-equal :class:`.time` objects, " "``timedelta(microseconds=1)``, although note that arithmetic on :class:`." @@ -2486,7 +3375,7 @@ msgstr "" "``timedelta(microseconds=1)``, embora perceba que aritmética sobre objetos :" "class:`.time` não é suportada." -#: ../../library/datetime.rst:1784 +#: ../../library/datetime.rst:1824 msgid "" "The object passed as the tzinfo argument to the :class:`.time` constructor, " "or ``None`` if none was passed." @@ -2494,19 +3383,25 @@ msgstr "" "O objeto passado como argumento tzinfo para o construtor da classe :class:`." "time`, ou ``None`` se nada foi passado." -#: ../../library/datetime.rst:1798 +#: ../../library/datetime.rst:1838 msgid "" -":class:`.time` objects support equality and order comparisons, where *a* is " -"considered less than *b* when *a* precedes *b* in time." +":class:`.time` objects support equality and order comparisons, where ``a`` " +"is considered less than ``b`` when ``a`` precedes ``b`` in time." msgstr "" +"Objetos :class:`.time` oferecem suporte para comparações de igualdade e " +"ordem, onde ``a`` é considerado menor que ``b`` quando ``a`` precede ``b`` " +"no tempo." -#: ../../library/datetime.rst:1801 +#: ../../library/datetime.rst:1841 msgid "" "Naive and aware :class:`!time` objects are never equal. Order comparison " "between naive and aware :class:`!time` objects raises :exc:`TypeError`." msgstr "" +"Objetos :class:`!time` ingênuos e conscientes nunca são iguais. A comparação " +"de ordem entre objetos :class:`!time` ingênuos e conscientes levanta :exc:" +"`TypeError`." -#: ../../library/datetime.rst:1805 +#: ../../library/datetime.rst:1845 msgid "" "If both comparands are aware, and have the same :attr:`~.time.tzinfo` " "attribute, the :attr:`!tzinfo` and :attr:`!fold` attributes are ignored and " @@ -2514,21 +3409,28 @@ msgid "" "different :attr:`!tzinfo` attributes, the comparands are first adjusted by " "subtracting their UTC offsets (obtained from ``self.utcoffset()``)." msgstr "" +"Se ambos os comparandos são conscientes, e tem o mesmo atributo :attr:`~." +"time.tzinfo`, os atributos :attr:`!tzinfo` e :attr:`!fold` são ignorados e " +"os tempos base são comparados. Se ambos os comparandos são conscientes e tem " +"atributos :attr:`!tzinfo` diferentes, os comparandos são primeiro ajustados " +"subtraindo sua diferença em UTC (obtida através de ``self.utcoffset()``)." -#: ../../library/datetime.rst:1811 +#: ../../library/datetime.rst:1851 msgid "" "Equality comparisons between aware and naive :class:`.time` instances don't " "raise :exc:`TypeError`." msgstr "" +"Comparações de igualdade entre instâncias de :class:`.time` conscientes e " +"nativas não levantam :exc:`TypeError`." -#: ../../library/datetime.rst:1815 +#: ../../library/datetime.rst:1855 msgid "" "In Boolean contexts, a :class:`.time` object is always considered to be true." msgstr "" "Em contextos Booleanos, um objeto :class:`.time` é sempre considerado como " "verdadeiro." -#: ../../library/datetime.rst:1817 +#: ../../library/datetime.rst:1857 msgid "" "Before Python 3.5, a :class:`.time` object was considered to be false if it " "represented midnight in UTC. This behavior was considered obscure and error-" @@ -2540,11 +3442,11 @@ msgstr "" "suscetível a erros, e foi removido no Python 3.5. Veja :issue:`13936` para " "todos os detalhes." -#: ../../library/datetime.rst:1824 +#: ../../library/datetime.rst:1864 msgid "Other constructor:" msgstr "Outro construtor:" -#: ../../library/datetime.rst:1828 +#: ../../library/datetime.rst:1868 msgid "" "Return a :class:`.time` corresponding to a *time_string* in any valid ISO " "8601 format, with the following exceptions:" @@ -2552,7 +3454,7 @@ msgstr "" "Retorna um :class:`.time` correspondendo a *time_string* em qualquer formato " "válido de ISO 8601, com as seguintes exceções:" -#: ../../library/datetime.rst:1832 +#: ../../library/datetime.rst:1872 msgid "" "The leading ``T``, normally required in cases where there may be ambiguity " "between a date and a time, is not required." @@ -2560,7 +3462,7 @@ msgstr "" "O ``T`` inicial, normalmente exigido nos casos em que pode haver ambiguidade " "entre uma data e uma hora, não é necessário." -#: ../../library/datetime.rst:1834 +#: ../../library/datetime.rst:1874 msgid "" "Fractional seconds may have any number of digits (anything beyond 6 will be " "truncated)." @@ -2568,51 +3470,92 @@ msgstr "" "Segundos fracionários podem ter qualquer número de dígitos (algo além de 6 " "será truncado)." -#: ../../library/datetime.rst:1838 +#: ../../library/datetime.rst:1878 msgid "Examples:" msgstr "Exemplos:" -#: ../../library/datetime.rst:1862 +#: ../../library/datetime.rst:1880 +msgid "" +">>> from datetime import time\n" +">>> time.fromisoformat('04:23:01')\n" +"datetime.time(4, 23, 1)\n" +">>> time.fromisoformat('T04:23:01')\n" +"datetime.time(4, 23, 1)\n" +">>> time.fromisoformat('T042301')\n" +"datetime.time(4, 23, 1)\n" +">>> time.fromisoformat('04:23:01.000384')\n" +"datetime.time(4, 23, 1, 384)\n" +">>> time.fromisoformat('04:23:01,000384')\n" +"datetime.time(4, 23, 1, 384)\n" +">>> time.fromisoformat('04:23:01+04:00')\n" +"datetime.time(4, 23, 1, tzinfo=datetime.timezone(datetime." +"timedelta(seconds=14400)))\n" +">>> time.fromisoformat('04:23:01Z')\n" +"datetime.time(4, 23, 1, tzinfo=datetime.timezone.utc)\n" +">>> time.fromisoformat('04:23:01+00:00')\n" +"datetime.time(4, 23, 1, tzinfo=datetime.timezone.utc)" +msgstr "" +">>> from datetime import time\n" +">>> time.fromisoformat('04:23:01')\n" +"datetime.time(4, 23, 1)\n" +">>> time.fromisoformat('T04:23:01')\n" +"datetime.time(4, 23, 1)\n" +">>> time.fromisoformat('T042301')\n" +"datetime.time(4, 23, 1)\n" +">>> time.fromisoformat('04:23:01.000384')\n" +"datetime.time(4, 23, 1, 384)\n" +">>> time.fromisoformat('04:23:01,000384')\n" +"datetime.time(4, 23, 1, 384)\n" +">>> time.fromisoformat('04:23:01+04:00')\n" +"datetime.time(4, 23, 1, tzinfo=datetime.timezone(datetime." +"timedelta(seconds=14400)))\n" +">>> time.fromisoformat('04:23:01Z')\n" +"datetime.time(4, 23, 1, tzinfo=datetime.timezone.utc)\n" +">>> time.fromisoformat('04:23:01+00:00')\n" +"datetime.time(4, 23, 1, tzinfo=datetime.timezone.utc)" + +#: ../../library/datetime.rst:1902 msgid "" "Previously, this method only supported formats that could be emitted by :" -"meth:`time.isoformat()`." +"meth:`time.isoformat`." msgstr "" "Anteriormente, este método suportava apenas formatos que podiam ser emitidos " -"por :meth:`time.isoformat()`." +"por :meth:`time.isoformat`." -#: ../../library/datetime.rst:1872 +#: ../../library/datetime.rst:1912 msgid "" -"Return a :class:`.time` with the same value, except for those attributes " -"given new values by whichever keyword arguments are specified. Note that " -"``tzinfo=None`` can be specified to create a naive :class:`.time` from an " -"aware :class:`.time`, without conversion of the time data." +"Return a new :class:`.time` with the same values, but with specified " +"parameters updated. Note that ``tzinfo=None`` can be specified to create a " +"naive :class:`.time` from an aware :class:`.time`, without conversion of the " +"time data." msgstr "" -"Retorna um :class:`.time` com o mesmo valor, exceto para aqueles atributos " -"que receberam novos valores através de quaisquer argumentos nomeados que " -"foram especificados. Perceba que ``tzinfo=None`` pode ser especificado para " -"criar um :class:`.time` ingênuo a partir de um :class:`.time` consciente, " -"sem conversão de dados do horário." +"Retorna um novo :class:`.time` com os mesmos valores, mas com os parâmetros " +"especificados atualizados. Perceba que ``tzinfo=None`` pode ser especificado " +"para criar um :class:`.time` ingênuo a partir de um :class:`.time` " +"consciente, sem conversão de dados do tempo." -#: ../../library/datetime.rst:1877 +#: ../../library/datetime.rst:1917 msgid "" ":class:`.time` objects are also supported by generic function :func:`copy." "replace`." msgstr "" +"Objetos :class:`.time` também são suportados pela função genérica :func:" +"`copy.replace`." -#: ../../library/datetime.rst:1886 +#: ../../library/datetime.rst:1926 msgid "Return a string representing the time in ISO 8601 format, one of:" msgstr "" "Retorna uma string representando a hora em formato ISO 8601, um destes:" -#: ../../library/datetime.rst:1888 +#: ../../library/datetime.rst:1928 msgid "``HH:MM:SS.ffffff``, if :attr:`microsecond` is not 0" msgstr "``HH:MM:SS.ffffff``, se :attr:`microsecond` não é 0" -#: ../../library/datetime.rst:1889 +#: ../../library/datetime.rst:1929 msgid "``HH:MM:SS``, if :attr:`microsecond` is 0" msgstr "``HH:MM:SS``, se :attr:`microsecond` é 0" -#: ../../library/datetime.rst:1890 +#: ../../library/datetime.rst:1930 msgid "" "``HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]``, if :meth:`utcoffset` does not " "return ``None``" @@ -2620,7 +3563,7 @@ msgstr "" "``HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]``, se :meth:`utcoffset` não retorna " "``None``" -#: ../../library/datetime.rst:1891 +#: ../../library/datetime.rst:1931 msgid "" "``HH:MM:SS+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond` is 0 and :meth:" "`utcoffset` does not return ``None``" @@ -2628,15 +3571,37 @@ msgstr "" "``HH:MM:SS+HH:MM[:SS[.ffffff]]``, se :attr:`microsecond` é 0 e :meth:" "`utcoffset` não retorna ``None``" -#: ../../library/datetime.rst:1911 +#: ../../library/datetime.rst:1951 msgid ":exc:`ValueError` will be raised on an invalid *timespec* argument." msgstr ":exc:`ValueError` será levantado com um argumento *timespec* inválido." -#: ../../library/datetime.rst:1930 -msgid "For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``." -msgstr "Para um tempo *t*, ``str(t)`` é equivalente a ``t.isoformat()``." +#: ../../library/datetime.rst:1955 +msgid "" +">>> from datetime import time\n" +">>> time(hour=12, minute=34, second=56, microsecond=123456)." +"isoformat(timespec='minutes')\n" +"'12:34'\n" +">>> dt = time(hour=12, minute=34, second=56, microsecond=0)\n" +">>> dt.isoformat(timespec='microseconds')\n" +"'12:34:56.000000'\n" +">>> dt.isoformat(timespec='auto')\n" +"'12:34:56'" +msgstr "" +">>> from datetime import time\n" +">>> time(hour=12, minute=34, second=56, microsecond=123456)." +"isoformat(timespec='minutes')\n" +"'12:34'\n" +">>> dt = time(hour=12, minute=34, second=56, microsecond=0)\n" +">>> dt.isoformat(timespec='microseconds')\n" +"'12:34:56.000000'\n" +">>> dt.isoformat(timespec='auto')\n" +"'12:34:56'" + +#: ../../library/datetime.rst:1970 +msgid "For a time ``t``, ``str(t)`` is equivalent to ``t.isoformat()``." +msgstr "Para um tempo ``t``, ``str(t)`` é equivalente a ``t.isoformat()``." -#: ../../library/datetime.rst:1935 +#: ../../library/datetime.rst:1975 msgid "" "Return a string representing the time, controlled by an explicit format " "string. See also :ref:`strftime-strptime-behavior` and :meth:`time." @@ -2646,7 +3611,7 @@ msgstr "" "formato explícito. Veja também :ref:`strftime-strptime-behavior` e :meth:" "`time.isoformat`." -#: ../../library/datetime.rst:1941 +#: ../../library/datetime.rst:1981 msgid "" "Same as :meth:`.time.strftime`. This makes it possible to specify a format " "string for a :class:`.time` object in :ref:`formatted string literals ` e ao usar :meth:`str.format`. Veja também :" "ref:`strftime-strptime-behavior` e :meth:`time.isoformat`." -#: ../../library/datetime.rst:1949 +#: ../../library/datetime.rst:1989 msgid "" "If :attr:`.tzinfo` is ``None``, returns ``None``, else returns ``self.tzinfo." "utcoffset(None)``, and raises an exception if the latter doesn't return " @@ -2669,7 +3634,7 @@ msgstr "" "retornar ``None`` ou um objeto :class:`timedelta` com magnitude menor que um " "dia." -#: ../../library/datetime.rst:1959 +#: ../../library/datetime.rst:1999 msgid "" "If :attr:`.tzinfo` is ``None``, returns ``None``, else returns ``self.tzinfo." "dst(None)``, and raises an exception if the latter doesn't return ``None``, " @@ -2679,7 +3644,7 @@ msgstr "" "``self.tzinfo.dst(None)``, e levanta uma exceção se o segundo não retornar " "``None``, ou um objeto :class:`timedelta` com magnitude menor que um dia." -#: ../../library/datetime.rst:1968 +#: ../../library/datetime.rst:2008 msgid "" "If :attr:`.tzinfo` is ``None``, returns ``None``, else returns ``self.tzinfo." "tzname(None)``, or raises an exception if the latter doesn't return ``None`` " @@ -2689,19 +3654,71 @@ msgstr "" "``self.tzinfo.tzname(None)``, ou levanta uma exceção se o último caso não " "retornar ``None`` ou um objeto string." -#: ../../library/datetime.rst:1973 +#: ../../library/datetime.rst:2013 msgid "Examples of Usage: :class:`.time`" msgstr "Exemplos de uso: :class:`.time`" -#: ../../library/datetime.rst:1975 +#: ../../library/datetime.rst:2015 msgid "Examples of working with a :class:`.time` object::" msgstr "Exemplos para trabalhar com um objeto :class:`.time`::" -#: ../../library/datetime.rst:2006 +#: ../../library/datetime.rst:2017 +msgid "" +">>> from datetime import time, tzinfo, timedelta\n" +">>> class TZ1(tzinfo):\n" +"... def utcoffset(self, dt):\n" +"... return timedelta(hours=1)\n" +"... def dst(self, dt):\n" +"... return timedelta(0)\n" +"... def tzname(self,dt):\n" +"... return \"+01:00\"\n" +"... def __repr__(self):\n" +"... return f\"{self.__class__.__name__}()\"\n" +"...\n" +">>> t = time(12, 10, 30, tzinfo=TZ1())\n" +">>> t\n" +"datetime.time(12, 10, 30, tzinfo=TZ1())\n" +">>> t.isoformat()\n" +"'12:10:30+01:00'\n" +">>> t.dst()\n" +"datetime.timedelta(0)\n" +">>> t.tzname()\n" +"'+01:00'\n" +">>> t.strftime(\"%H:%M:%S %Z\")\n" +"'12:10:30 +01:00'\n" +">>> 'The {} is {:%H:%M}.'.format(\"time\", t)\n" +"'The time is 12:10.'" +msgstr "" +">>> from datetime import time, tzinfo, timedelta\n" +">>> class TZ1(tzinfo):\n" +"... def utcoffset(self, dt):\n" +"... return timedelta(hours=1)\n" +"... def dst(self, dt):\n" +"... return timedelta(0)\n" +"... def tzname(self,dt):\n" +"... return \"+01:00\"\n" +"... def __repr__(self):\n" +"... return f\"{self.__class__.__name__}()\"\n" +"...\n" +">>> t = time(12, 10, 30, tzinfo=TZ1())\n" +">>> t\n" +"datetime.time(12, 10, 30, tzinfo=TZ1())\n" +">>> t.isoformat()\n" +"'12:10:30+01:00'\n" +">>> t.dst()\n" +"datetime.timedelta(0)\n" +">>> t.tzname()\n" +"'+01:00'\n" +">>> t.strftime(\"%H:%M:%S %Z\")\n" +"'12:10:30 +01:00'\n" +">>> 'A {} é {:%H:%M}.'.format(\"hora\", t)\n" +"'A hora é 12:10.'" + +#: ../../library/datetime.rst:2046 msgid ":class:`tzinfo` Objects" msgstr "Objetos :class:`tzinfo`" -#: ../../library/datetime.rst:2010 +#: ../../library/datetime.rst:2050 msgid "" "This is an abstract base class, meaning that this class should not be " "instantiated directly. Define a subclass of :class:`tzinfo` to capture " @@ -2711,7 +3728,7 @@ msgstr "" "ser instanciada diretamente. Defina uma subclasse de :class:`tzinfo` para " "capturar informações sobre um fuso horário em particular." -#: ../../library/datetime.rst:2014 +#: ../../library/datetime.rst:2054 msgid "" "An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the " "constructors for :class:`.datetime` and :class:`.time` objects. The latter " @@ -2727,7 +3744,7 @@ msgstr "" "partir de UTC, o nome do fuso horário, e diferença de horário em horário de " "verão, todos relativos ao objeto date ou time passado para eles." -#: ../../library/datetime.rst:2020 +#: ../../library/datetime.rst:2060 msgid "" "You need to derive a concrete subclass, and (at least) supply " "implementations of the standard :class:`tzinfo` methods needed by the :class:" @@ -2736,23 +3753,39 @@ msgid "" "represent time zones with fixed offset from UTC such as UTC itself or North " "American EST and EDT." msgstr "" +"Você precisa derivar uma subclasse concreta, e (pelo menos) fornecer " +"implementações dos métodos padrões de :class:`tzinfo` necessários pelos " +"métodos :class:`.datetime` que você usa. O módulo :mod:`!datetime` fornece :" +"class:`timezone`, uma subclasse concreta simples de :class:`tzinfo`, que " +"pode representar fusos horários com diferença fixa a partir de UTC, tais " +"como o próprio UTC, ou EST (Eastern Standard Time ou Horário padrão " +"oriental) e EDT (Eastern Daylight Time ou Horário de verão oriental) na " +"América do Norte." -#: ../../library/datetime.rst:2027 +#: ../../library/datetime.rst:2067 msgid "" "Special requirement for pickling: A :class:`tzinfo` subclass must have an :" "meth:`~object.__init__` method that can be called with no arguments, " "otherwise it can be pickled but possibly not unpickled again. This is a " "technical requirement that may be relaxed in the future." msgstr "" +"Requisito especial para preservação: uma subclasse :class:`tzinfo` deve ter " +"um método :meth:`~object.__init__` que pode ser chamado sem nenhum " +"argumento, caso contrário ele pode ser conservado, mas não alterado " +"novamente. Isso é um requisito técnico que pode ser relaxado no futuro." -#: ../../library/datetime.rst:2033 +#: ../../library/datetime.rst:2073 msgid "" "A concrete subclass of :class:`tzinfo` may need to implement the following " "methods. Exactly which methods are needed depends on the uses made of aware :" "mod:`!datetime` objects. If in doubt, simply implement all of them." msgstr "" +"Uma subclasse concreta de :class:`tzinfo` pode precisar implementar os " +"seguintes métodos. Exatamente quais métodos são necessários depende do uso " +"feito de objetos :mod:`!datetime` conscientes. Se estiver em dúvida, " +"simplesmente implemente todos eles." -#: ../../library/datetime.rst:2040 +#: ../../library/datetime.rst:2080 msgid "" "Return offset of local time from UTC, as a :class:`timedelta` object that is " "positive east of UTC. If local time is west of UTC, this should be negative." @@ -2761,7 +3794,7 @@ msgstr "" "`timedelta`, que é positivo a leste do UTC. Se a hora local está a oeste do " "UTC, isto deve ser negativo." -#: ../../library/datetime.rst:2043 +#: ../../library/datetime.rst:2083 msgid "" "This represents the *total* offset from UTC; for example, if a :class:" "`tzinfo` object represents both time zone and DST adjustments, :meth:" @@ -2780,7 +3813,15 @@ msgstr "" "deve ser menor que um dia). A maior parte das implementações de :meth:" "`utcoffset` irá provavelmente parecer com um destes dois::" -#: ../../library/datetime.rst:2054 +#: ../../library/datetime.rst:2091 +msgid "" +"return CONSTANT # fixed-offset class\n" +"return CONSTANT + self.dst(dt) # daylight-aware class" +msgstr "" +"return CONSTANT # classe de posição fixa\n" +"return CONSTANT + self.dst(dt) # classe consciente de horário de verão" + +#: ../../library/datetime.rst:2094 msgid "" "If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return " "``None`` either." @@ -2788,7 +3829,7 @@ msgstr "" "Se :meth:`utcoffset` não retorna ``None``, :meth:`dst` também não deve " "retornar ``None``." -#: ../../library/datetime.rst:2057 +#: ../../library/datetime.rst:2097 msgid "" "The default implementation of :meth:`utcoffset` raises :exc:" "`NotImplementedError`." @@ -2796,7 +3837,7 @@ msgstr "" "A implementação padrão de :meth:`utcoffset` levanta :exc:" "`NotImplementedError`." -#: ../../library/datetime.rst:2066 +#: ../../library/datetime.rst:2106 msgid "" "Return the daylight saving time (DST) adjustment, as a :class:`timedelta` " "object or ``None`` if DST information isn't known." @@ -2805,7 +3846,7 @@ msgstr "" "um objeto :class:`timedelta` ou ``None`` se informação para o horário de " "verão é desconhecida." -#: ../../library/datetime.rst:2070 +#: ../../library/datetime.rst:2110 msgid "" "Return ``timedelta(0)`` if DST is not in effect. If DST is in effect, return " "the offset as a :class:`timedelta` object (see :meth:`utcoffset` for " @@ -2817,8 +3858,19 @@ msgid "" "tm_isdst` flag should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` " "to account for DST changes when crossing time zones." msgstr "" +"Retorna ``timedelta(0)`` se o horário de verão não estiver ativo. Se o " +"horário de verão estiver ativo, retorna a diferença como um objeto :class:" +"`timedelta` (veja :meth:`utcoffset` para detalhes). Perceba que a diferença " +"do horário de verão, se aplicável, já foi adicionada a diferença UTC " +"retornada por :meth:`utcoffset`, então não existe necessidade de consultar :" +"meth:`dst` a não ser que você esteja interessado em obter a informação de " +"horário de verão separadamente. Por exemplo, :meth:`datetime.timetuple` " +"chama o método :meth:`dst` do seu atributo :attr:`~.datetime.tzinfo` para " +"determinar como o flag :attr:`~time.struct_time.tm_isdst` deve ser definido, " +"e :meth:`tzinfo.fromutc` chama :meth:`dst` para contabilizar as mudanças de " +"horário de verão quando ocorrem mudanças de fuso horário." -#: ../../library/datetime.rst:2080 +#: ../../library/datetime.rst:2120 msgid "" "An instance *tz* of a :class:`tzinfo` subclass that models both standard and " "daylight times must be consistent in this sense:" @@ -2826,11 +3878,11 @@ msgstr "" "Uma instância *tz* de uma subclasse :class:`tzinfo` que modela tanto horário " "padrão quanto horário de verão deve ser consistente neste sentido:" -#: ../../library/datetime.rst:2083 +#: ../../library/datetime.rst:2123 msgid "``tz.utcoffset(dt) - tz.dst(dt)``" msgstr "``tz.utcoffset(dt) - tz.dst(dt)``" -#: ../../library/datetime.rst:2085 +#: ../../library/datetime.rst:2125 msgid "" "must return the same result for every :class:`.datetime` *dt* with ``dt." "tzinfo == tz``. For sane :class:`tzinfo` subclasses, this expression yields " @@ -2842,8 +3894,17 @@ msgid "" "of :meth:`tzinfo.fromutc` to work correctly with :meth:`~.datetime." "astimezone` regardless." msgstr "" +"deve retornar o mesmo resultado para cada :class:`.datetime` *dt* com ``dt." +"tzinfo == tz`` para subclasses :class:`tzinfo` sãs, esta expressão produz a " +"\"diferença padrão\" do fuso horário, a qual não deve depender de data ou " +"hora, mas apenas de localização geográfica. A implementação de :meth:" +"`datetime.astimezone` depende disso, mas não pode detectar violações; é " +"responsabilidade do programador garantir isso. Se uma subclasse :class:" +"`tzinfo` não pode garantir isso, ele pode ser capaz de substituir a " +"implementação padrão de :meth:`tzinfo.fromutc` para funcionar corretamente " +"com :meth:`~.datetime.astimezone` independente disso." -#: ../../library/datetime.rst:2094 +#: ../../library/datetime.rst:2134 msgid "" "Most implementations of :meth:`dst` will probably look like one of these " "two::" @@ -2851,17 +3912,49 @@ msgstr "" "Maior parte das implementações de :meth:`dst` provavelmente irá parecer com " "um destes dois::" -#: ../../library/datetime.rst:2100 +#: ../../library/datetime.rst:2136 +msgid "" +"def dst(self, dt):\n" +" # a fixed-offset class: doesn't account for DST\n" +" return timedelta(0)" +msgstr "" +"def dst(self, dt):\n" +" # uma classe de posição fixa: não levam em conta DST\n" +" return timedelta(0)" + +#: ../../library/datetime.rst:2140 msgid "or::" msgstr "ou::" -#: ../../library/datetime.rst:2112 +#: ../../library/datetime.rst:2142 +msgid "" +"def dst(self, dt):\n" +" # Code to set dston and dstoff to the time zone's DST\n" +" # transition times based on the input dt.year, and expressed\n" +" # in standard local time.\n" +"\n" +" if dston <= dt.replace(tzinfo=None) < dstoff:\n" +" return timedelta(hours=1)\n" +" else:\n" +" return timedelta(0)" +msgstr "" +"def dst(self, dt):\n" +" # Código para definir dston e dstoff para os horários\n" +" # de transição do horário de versão com base\n" +" # no dt.year de entrada e expresso no horário local padrão.\n" +"\n" +" if dston <= dt.replace(tzinfo=None) < dstoff:\n" +" return timedelta(hours=1)\n" +" else:\n" +" return timedelta(0)" + +#: ../../library/datetime.rst:2152 msgid "" "The default implementation of :meth:`dst` raises :exc:`NotImplementedError`." msgstr "" "A implementação padrão de :meth:`dst` levanta :exc:`NotImplementedError`." -#: ../../library/datetime.rst:2120 +#: ../../library/datetime.rst:2160 msgid "" "Return the time zone name corresponding to the :class:`.datetime` object " "*dt*, as a string. Nothing about string names is defined by the :mod:`!" @@ -2874,15 +3967,26 @@ msgid "" "specific value of *dt* passed, especially if the :class:`tzinfo` class is " "accounting for daylight time." msgstr "" +"Retorna o nome do fuso horário correspondente ao objeto :class:`.datetime` " +"*dt*, como uma string. Nada sobre nomes de strings é definido pelo módulo :" +"mod:`!datetime`, e não há nenhuma exigência de que signifique algo em " +"particular. Por exemplo, ``\"GMT\"``, ``\"UTC\"``, ``\"-500\"``, " +"``\"-5:00\"``, ``\"EDT\"``, ``\"US/Eastern\"``, ``\"America/New York\"`` são " +"todas respostas válidas. Retorna ``None`` se um nome de string não for " +"conhecido. Observe que este é um método em vez de uma string fixa, " +"principalmente porque algumas subclasses :class:`tzinfo` desejarão retornar " +"nomes diferentes dependendo do valor específico de *dt* passado, " +"especialmente se a classe :class:`tzinfo` estiver contabilizando o horário " +"de verão." -#: ../../library/datetime.rst:2130 +#: ../../library/datetime.rst:2170 msgid "" "The default implementation of :meth:`tzname` raises :exc:" "`NotImplementedError`." msgstr "" "A implementação padrão de :meth:`tzname` levanta :exc:`NotImplementedError`." -#: ../../library/datetime.rst:2133 +#: ../../library/datetime.rst:2173 msgid "" "These methods are called by a :class:`.datetime` or :class:`.time` object, " "in response to their methods of the same names. A :class:`.datetime` object " @@ -2898,7 +4002,7 @@ msgstr "" "portanto estar preparados para aceitar um argumento *dt* com valor ``None``, " "ou uma classe :class:`.datetime`." -#: ../../library/datetime.rst:2139 +#: ../../library/datetime.rst:2179 msgid "" "When ``None`` is passed, it's up to the class designer to decide the best " "response. For example, returning ``None`` is appropriate if the class wishes " @@ -2913,7 +4017,7 @@ msgstr "" "UTC padrão, como não existe outra convenção para descobrir a diferença " "padrão." -#: ../../library/datetime.rst:2145 +#: ../../library/datetime.rst:2185 msgid "" "When a :class:`.datetime` object is passed in response to a :class:`." "datetime` method, ``dt.tzinfo`` is the same object as *self*. :class:" @@ -2922,16 +4026,22 @@ msgid "" "*dt* as being in local time, and not need worry about objects in other time " "zones." msgstr "" +"Quando um objeto :class:`.datetime` é passado em resposta a um método :class:" +"`.datetime`, ``dt.tzinfo`` é o mesmo objeto que *self*. Os métodos :class:" +"`tzinfo` podem confiar nisso, a menos que o código do usuário chame métodos :" +"class:`tzinfo` diretamente. A intenção é que os métodos :class:`tzinfo` " +"interpretem *dt* como estando no horário local, e não precisem se preocupar " +"com objetos em outros fusos horários." -#: ../../library/datetime.rst:2151 +#: ../../library/datetime.rst:2191 msgid "" "There is one more :class:`tzinfo` method that a subclass may wish to " "override:" msgstr "" -"Exste mais um método :class:`tzinfo` que uma subclasse pode querer " -"substituir:" +"Existe mais um método :class:`tzinfo` que uma subclasse pode desejar " +"substituição:" -#: ../../library/datetime.rst:2156 +#: ../../library/datetime.rst:2196 msgid "" "This is called from the default :meth:`datetime.astimezone` implementation. " "When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time " @@ -2939,8 +4049,14 @@ msgid "" "`fromutc` is to adjust the date and time data, returning an equivalent " "datetime in *self*'s local time." msgstr "" +"Isto é chamado a partir do padrão implementação de :meth:`datetime." +"astimezone`. Quando chamado a partir dele, ``dt.tzinfo`` é *self*, e os " +"dados de data e hora de *dt* devem ser vistos como expressando um Horário " +"Universal Coordenado (UTC). O propósito de :meth:`fromutc` é ajustar os " +"dados de data e hora, retornando um *datetime* equivalente na hora local de " +"*self*." -#: ../../library/datetime.rst:2162 +#: ../../library/datetime.rst:2202 msgid "" "Most :class:`tzinfo` subclasses should be able to inherit the default :meth:" "`fromutc` implementation without problems. It's strong enough to handle " @@ -2954,8 +4070,20 @@ msgid "" "want if the result is one of the hours straddling the moment the standard " "offset changes." msgstr "" - -#: ../../library/datetime.rst:2173 +"A maioria das subclasses de :class:`tzinfo` deve ser capaz de herdar a " +"implementação padrão de :meth:`fromutc` sem problemas. Ela é robusta o " +"suficiente para lidar com fusos horários de deslocamento fixo, e fusos " +"horários que contabilizam tanto o horário padrão quanto o horário de verão, " +"sendo que este último é tratado mesmo que os horários de transição do " +"horário de verão sejam diferentes em anos distintos. Um exemplo de fuso " +"horário que a implementação padrão de :meth:`fromutc` pode não lidar " +"corretamente em todos os casos é aquele onde o deslocamento padrão (de UTC) " +"depende da data e hora específicas passadas, o que pode acontecer por razões " +"políticas. As implementações padrão de :meth:`~.datetime.astimezone` e :meth:" +"`fromutc` podem não produzir o resultado desejado se o resultado estiver " +"entre as horas que abrangem o momento em que o deslocamento padrão muda." + +#: ../../library/datetime.rst:2213 msgid "" "Skipping code for error cases, the default :meth:`fromutc` implementation " "acts like::" @@ -2963,7 +4091,39 @@ msgstr "" "Ignorando o código para casos de erros, a implementação padrão :meth:" "`fromutc` funciona como::" -#: ../../library/datetime.rst:2191 +#: ../../library/datetime.rst:2216 +msgid "" +"def fromutc(self, dt):\n" +" # raise ValueError error if dt.tzinfo is not self\n" +" dtoff = dt.utcoffset()\n" +" dtdst = dt.dst()\n" +" # raise ValueError if dtoff is None or dtdst is None\n" +" delta = dtoff - dtdst # this is self's standard offset\n" +" if delta:\n" +" dt += delta # convert to standard local time\n" +" dtdst = dt.dst()\n" +" # raise ValueError if dtdst is None\n" +" if dtdst:\n" +" return dt + dtdst\n" +" else:\n" +" return dt" +msgstr "" +"def fromutc(self, dt):\n" +" # levanta o erro ValueError se dt.tzinfo não é o self\n" +" dtoff = dt.utcoffset()\n" +" dtdst = dt.dst()\n" +" # levanta ValueError se dtoff é None ou dtdst é None\n" +" delta = dtoff - dtdst # este é o deslocamento padrão do self\n" +" if delta:\n" +" dt += delta # converter para hora local padrão\n" +" dtdst = dt.dst()\n" +" # levanta ValueError se dtdst é None\n" +" if dtdst:\n" +" return dt + dtdst\n" +" else:\n" +" return dt" + +#: ../../library/datetime.rst:2231 msgid "" "In the following :download:`tzinfo_examples.py <../includes/tzinfo_examples." "py>` file there are some examples of :class:`tzinfo` classes:" @@ -2971,7 +4131,369 @@ msgstr "" "No seguinte arquivo :download:`tzinfo_examples.py <../includes/" "tzinfo_examples.py>` existem alguns exemplos de classes :class:`tzinfo`:" -#: ../../library/datetime.rst:2197 +#: ../../library/datetime.rst:2235 +msgid "" +"from datetime import tzinfo, timedelta, datetime\n" +"\n" +"ZERO = timedelta(0)\n" +"HOUR = timedelta(hours=1)\n" +"SECOND = timedelta(seconds=1)\n" +"\n" +"# A class capturing the platform's idea of local time.\n" +"# (May result in wrong values on historical times in\n" +"# timezones where UTC offset and/or the DST rules had\n" +"# changed in the past.)\n" +"import time as _time\n" +"\n" +"STDOFFSET = timedelta(seconds = -_time.timezone)\n" +"if _time.daylight:\n" +" DSTOFFSET = timedelta(seconds = -_time.altzone)\n" +"else:\n" +" DSTOFFSET = STDOFFSET\n" +"\n" +"DSTDIFF = DSTOFFSET - STDOFFSET\n" +"\n" +"class LocalTimezone(tzinfo):\n" +"\n" +" def fromutc(self, dt):\n" +" assert dt.tzinfo is self\n" +" stamp = (dt - datetime(1970, 1, 1, tzinfo=self)) // SECOND\n" +" args = _time.localtime(stamp)[:6]\n" +" dst_diff = DSTDIFF // SECOND\n" +" # Detect fold\n" +" fold = (args == _time.localtime(stamp - dst_diff))\n" +" return datetime(*args, microsecond=dt.microsecond,\n" +" tzinfo=self, fold=fold)\n" +"\n" +" def utcoffset(self, dt):\n" +" if self._isdst(dt):\n" +" return DSTOFFSET\n" +" else:\n" +" return STDOFFSET\n" +"\n" +" def dst(self, dt):\n" +" if self._isdst(dt):\n" +" return DSTDIFF\n" +" else:\n" +" return ZERO\n" +"\n" +" def tzname(self, dt):\n" +" return _time.tzname[self._isdst(dt)]\n" +"\n" +" def _isdst(self, dt):\n" +" tt = (dt.year, dt.month, dt.day,\n" +" dt.hour, dt.minute, dt.second,\n" +" dt.weekday(), 0, 0)\n" +" stamp = _time.mktime(tt)\n" +" tt = _time.localtime(stamp)\n" +" return tt.tm_isdst > 0\n" +"\n" +"Local = LocalTimezone()\n" +"\n" +"\n" +"# A complete implementation of current DST rules for major US time zones.\n" +"\n" +"def first_sunday_on_or_after(dt):\n" +" days_to_go = 6 - dt.weekday()\n" +" if days_to_go:\n" +" dt += timedelta(days_to_go)\n" +" return dt\n" +"\n" +"\n" +"# US DST Rules\n" +"#\n" +"# This is a simplified (i.e., wrong for a few cases) set of rules for US\n" +"# DST start and end times. For a complete and up-to-date set of DST rules\n" +"# and timezone definitions, visit the Olson Database (or try pytz):\n" +"# http://www.twinsun.com/tz/tz-link.htm\n" +"# https://sourceforge.net/projects/pytz/ (might not be up-to-date)\n" +"#\n" +"# In the US, since 2007, DST starts at 2am (standard time) on the second\n" +"# Sunday in March, which is the first Sunday on or after Mar 8.\n" +"DSTSTART_2007 = datetime(1, 3, 8, 2)\n" +"# and ends at 2am (DST time) on the first Sunday of Nov.\n" +"DSTEND_2007 = datetime(1, 11, 1, 2)\n" +"# From 1987 to 2006, DST used to start at 2am (standard time) on the first\n" +"# Sunday in April and to end at 2am (DST time) on the last\n" +"# Sunday of October, which is the first Sunday on or after Oct 25.\n" +"DSTSTART_1987_2006 = datetime(1, 4, 1, 2)\n" +"DSTEND_1987_2006 = datetime(1, 10, 25, 2)\n" +"# From 1967 to 1986, DST used to start at 2am (standard time) on the last\n" +"# Sunday in April (the one on or after April 24) and to end at 2am (DST " +"time)\n" +"# on the last Sunday of October, which is the first Sunday\n" +"# on or after Oct 25.\n" +"DSTSTART_1967_1986 = datetime(1, 4, 24, 2)\n" +"DSTEND_1967_1986 = DSTEND_1987_2006\n" +"\n" +"def us_dst_range(year):\n" +" # Find start and end times for US DST. For years before 1967, return\n" +" # start = end for no DST.\n" +" if 2006 < year:\n" +" dststart, dstend = DSTSTART_2007, DSTEND_2007\n" +" elif 1986 < year < 2007:\n" +" dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006\n" +" elif 1966 < year < 1987:\n" +" dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986\n" +" else:\n" +" return (datetime(year, 1, 1), ) * 2\n" +"\n" +" start = first_sunday_on_or_after(dststart.replace(year=year))\n" +" end = first_sunday_on_or_after(dstend.replace(year=year))\n" +" return start, end\n" +"\n" +"\n" +"class USTimeZone(tzinfo):\n" +"\n" +" def __init__(self, hours, reprname, stdname, dstname):\n" +" self.stdoffset = timedelta(hours=hours)\n" +" self.reprname = reprname\n" +" self.stdname = stdname\n" +" self.dstname = dstname\n" +"\n" +" def __repr__(self):\n" +" return self.reprname\n" +"\n" +" def tzname(self, dt):\n" +" if self.dst(dt):\n" +" return self.dstname\n" +" else:\n" +" return self.stdname\n" +"\n" +" def utcoffset(self, dt):\n" +" return self.stdoffset + self.dst(dt)\n" +"\n" +" def dst(self, dt):\n" +" if dt is None or dt.tzinfo is None:\n" +" # An exception may be sensible here, in one or both cases.\n" +" # It depends on how you want to treat them. The default\n" +" # fromutc() implementation (called by the default astimezone()\n" +" # implementation) passes a datetime with dt.tzinfo is self.\n" +" return ZERO\n" +" assert dt.tzinfo is self\n" +" start, end = us_dst_range(dt.year)\n" +" # Can't compare naive to aware objects, so strip the timezone from\n" +" # dt first.\n" +" dt = dt.replace(tzinfo=None)\n" +" if start + HOUR <= dt < end - HOUR:\n" +" # DST is in effect.\n" +" return HOUR\n" +" if end - HOUR <= dt < end:\n" +" # Fold (an ambiguous hour): use dt.fold to disambiguate.\n" +" return ZERO if dt.fold else HOUR\n" +" if start <= dt < start + HOUR:\n" +" # Gap (a non-existent hour): reverse the fold rule.\n" +" return HOUR if dt.fold else ZERO\n" +" # DST is off.\n" +" return ZERO\n" +"\n" +" def fromutc(self, dt):\n" +" assert dt.tzinfo is self\n" +" start, end = us_dst_range(dt.year)\n" +" start = start.replace(tzinfo=self)\n" +" end = end.replace(tzinfo=self)\n" +" std_time = dt + self.stdoffset\n" +" dst_time = std_time + HOUR\n" +" if end <= dst_time < end + HOUR:\n" +" # Repeated hour\n" +" return std_time.replace(fold=1)\n" +" if std_time < start or dst_time >= end:\n" +" # Standard time\n" +" return std_time\n" +" if start <= std_time < end - HOUR:\n" +" # Daylight saving time\n" +" return dst_time\n" +"\n" +"\n" +"Eastern = USTimeZone(-5, \"Eastern\", \"EST\", \"EDT\")\n" +"Central = USTimeZone(-6, \"Central\", \"CST\", \"CDT\")\n" +"Mountain = USTimeZone(-7, \"Mountain\", \"MST\", \"MDT\")\n" +"Pacific = USTimeZone(-8, \"Pacific\", \"PST\", \"PDT\")\n" +msgstr "" +"from datetime import tzinfo, timedelta, datetime\n" +"\n" +"ZERO = timedelta(0)\n" +"HOUR = timedelta(hours=1)\n" +"SECOND = timedelta(seconds=1)\n" +"\n" +"# Uma classe que captura a ideia da plataforma sobre o horário local.\n" +"# (Pode resultar em valores errados em horários históricos em fusos " +"horários\n" +"# onde o deslocamento UTC e/ou as regras de horário de verão\n" +"# foram alteradas no passado.)\n" +"import time as _time\n" +"\n" +"STDOFFSET = timedelta(seconds = -_time.timezone)\n" +"if _time.daylight:\n" +" DSTOFFSET = timedelta(seconds = -_time.altzone)\n" +"else:\n" +" DSTOFFSET = STDOFFSET\n" +"\n" +"DSTDIFF = DSTOFFSET - STDOFFSET\n" +"\n" +"class LocalTimezone(tzinfo):\n" +"\n" +" def fromutc(self, dt):\n" +" assert dt.tzinfo is self\n" +" stamp = (dt - datetime(1970, 1, 1, tzinfo=self)) // SECOND\n" +" args = _time.localtime(stamp)[:6]\n" +" dst_diff = DSTDIFF // SECOND\n" +" # Detect fold\n" +" fold = (args == _time.localtime(stamp - dst_diff))\n" +" return datetime(*args, microsecond=dt.microsecond,\n" +" tzinfo=self, fold=fold)\n" +"\n" +" def utcoffset(self, dt):\n" +" if self._isdst(dt):\n" +" return DSTOFFSET\n" +" else:\n" +" return STDOFFSET\n" +"\n" +" def dst(self, dt):\n" +" if self._isdst(dt):\n" +" return DSTDIFF\n" +" else:\n" +" return ZERO\n" +"\n" +" def tzname(self, dt):\n" +" return _time.tzname[self._isdst(dt)]\n" +"\n" +" def _isdst(self, dt):\n" +" tt = (dt.year, dt.month, dt.day,\n" +" dt.hour, dt.minute, dt.second,\n" +" dt.weekday(), 0, 0)\n" +" stamp = _time.mktime(tt)\n" +" tt = _time.localtime(stamp)\n" +" return tt.tm_isdst > 0\n" +"\n" +"Local = LocalTimezone()\n" +"\n" +"\n" +"# Uma implementação completa das regras atuais do horário de verão para os " +"principais fusos horários dos EUA.\n" +"\n" +"def first_sunday_on_or_after(dt):\n" +" days_to_go = 6 - dt.weekday()\n" +" if days_to_go:\n" +" dt += timedelta(days_to_go)\n" +" return dt\n" +"\n" +"\n" +"# Regras do horário de verão dos EUA\n" +"#\n" +"# Este é um conjunto simplificado (ou seja, incorreto em alguns casos)\n" +"# de regras para os horários de início e término do horário de verão dos " +"EUA.\n" +"# Para um conjunto completo e atualizado de regras de horário de verão\n" +"# e definições de fuso horário, visite o Olson Database (ou tente pytz):\n" +"# http://www.twinsun.com/tz/tz-link.htm\n" +"# https://sourceforge.net/projects/pytz/ (pode não estar atualizado)\n" +"#\n" +"# Nos EUA, desde 2007, o horário de verão começa às 2h (horário padrão) no\n" +"# segundo domingo de março, que é o primeiro domingo em ou após 8 de março.\n" +"DSTSTART_2007 = datetime(1, 3, 8, 2)\n" +"# e termina às 2h (horário de verão) no primeiro domingo de novembro.\n" +"DSTEND_2007 = datetime(1, 11, 1, 2)\n" +"# De 1987 a 2006, o horário de verão costumava começar às 2h\n" +"# (horário padrão) no primeiro domingo de abril e terminar às 2h\n" +"# (horário de verão) no último Domingo de outubro, que é o primeiro\n" +"# domingo em ou após 25 de outubro.\n" +"DSTSTART_1987_2006 = datetime(1, 4, 1, 2)\n" +"DSTEND_1987_2006 = datetime(1, 10, 25, 2)\n" +"# De 1967 a 1986, o horário de verão costumava começar às 2h\n" +"# (horário padrão) no último domingo de abril (aquele em ou após\n" +"# 24 de abril) e terminar às 2h (horário de verão) no último domingo\n" +"# de outubro, que é o primeiro domingo em ou após 25 de outubro.\n" +"DSTSTART_1967_1986 = datetime(1, 4, 24, 2)\n" +"DSTEND_1967_1986 = DSTEND_1987_2006\n" +"\n" +"def us_dst_range(year):\n" +" # Encontra os horários de início e fim do horário de verão dos EUA.\n" +" # Para anos anteriores a 1967, retorne start = end para nenhum horário\n" +" # de verão.\n" +" if 2006 < year:\n" +" dststart, dstend = DSTSTART_2007, DSTEND_2007\n" +" elif 1986 < year < 2007:\n" +" dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006\n" +" elif 1966 < year < 1987:\n" +" dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986\n" +" else:\n" +" return (datetime(year, 1, 1), ) * 2\n" +"\n" +" start = first_sunday_on_or_after(dststart.replace(year=year))\n" +" end = first_sunday_on_or_after(dstend.replace(year=year))\n" +" return start, end\n" +"\n" +"\n" +"class USTimeZone(tzinfo):\n" +"\n" +" def __init__(self, hours, reprname, stdname, dstname):\n" +" self.stdoffset = timedelta(hours=hours)\n" +" self.reprname = reprname\n" +" self.stdname = stdname\n" +" self.dstname = dstname\n" +"\n" +" def __repr__(self):\n" +" return self.reprname\n" +"\n" +" def tzname(self, dt):\n" +" if self.dst(dt):\n" +" return self.dstname\n" +" else:\n" +" return self.stdname\n" +"\n" +" def utcoffset(self, dt):\n" +" return self.stdoffset + self.dst(dt)\n" +"\n" +" def dst(self, dt):\n" +" if dt is None or dt.tzinfo is None:\n" +" # Uma exceção pode ser sensata aqui, em um ou ambos os casos.\n" +" # Depende de como você quer tratá-las. A implementação padrão\n" +" # fromutc() (chamada pela implementação padrão astimezone()) " +"passa\n" +" # um datetime com dt.tzinfo é self.\n" +" return ZERO\n" +" assert dt.tzinfo is self\n" +" start, end = us_dst_range(dt.year)\n" +" # Não é possível comparar objetos ingênuos com objetos conscientes,\n" +" # então retira o fuso horário de dt primeiro.\n" +" dt = dt.replace(tzinfo=None)\n" +" if start + HOUR <= dt < end - HOUR:\n" +" # Horário de verão está em vigor.\n" +" return HOUR\n" +" if end - HOUR <= dt < end:\n" +" # Fold (uma hora ambígua): usa dt.fold para desambiguar.\n" +" return ZERO if dt.fold else HOUR\n" +" if start <= dt < start + HOUR:\n" +" # Intervalo (uma hora inexistente): inverta a regra da dobra.\n" +" return HOUR if dt.fold else ZERO\n" +" # DST is off.\n" +" return ZERO\n" +"\n" +" def fromutc(self, dt):\n" +" assert dt.tzinfo is self\n" +" start, end = us_dst_range(dt.year)\n" +" start = start.replace(tzinfo=self)\n" +" end = end.replace(tzinfo=self)\n" +" std_time = dt + self.stdoffset\n" +" dst_time = std_time + HOUR\n" +" if end <= dst_time < end + HOUR:\n" +" # Hora repetida\n" +" return std_time.replace(fold=1)\n" +" if std_time < start or dst_time >= end:\n" +" # Horário padrão\n" +" return std_time\n" +" if start <= std_time < end - HOUR:\n" +" # Horário de verão\n" +" return dst_time\n" +"\n" +"\n" +"Eastern = USTimeZone(-5, \"Eastern\", \"EST\", \"EDT\")\n" +"Central = USTimeZone(-6, \"Central\", \"CST\", \"CDT\")\n" +"Mountain = USTimeZone(-7, \"Mountain\", \"MST\", \"MDT\")\n" +"Pacific = USTimeZone(-8, \"Pacific\", \"PST\", \"PDT\")\n" + +#: ../../library/datetime.rst:2237 msgid "" "Note that there are unavoidable subtleties twice per year in a :class:" "`tzinfo` subclass accounting for both standard and daylight time, at the DST " @@ -2987,7 +4509,25 @@ msgstr "" "termina no minuto posterior a 1:59 (EDT, horário de verão) no primeiro " "domingo de Novembro::" -#: ../../library/datetime.rst:2211 +#: ../../library/datetime.rst:2243 +msgid "" +" UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM\n" +" EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM\n" +" EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM\n" +"\n" +"start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM\n" +"\n" +" end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM" +msgstr "" +" UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM\n" +" EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM\n" +" EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM\n" +"\n" +"start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM\n" +"\n" +" end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM" + +#: ../../library/datetime.rst:2251 msgid "" "When DST starts (the \"start\" line), the local wall clock leaps from 1:59 " "to 3:00. A wall time of the form 2:MM doesn't really make sense on that day, " @@ -3002,7 +4542,35 @@ msgstr "" "começar. Por exemplo, na primavera de transição para frente em 2016, nós " "tivemos::" -#: ../../library/datetime.rst:2230 +#: ../../library/datetime.rst:2256 +msgid "" +">>> from datetime import datetime, timezone\n" +">>> from tzinfo_examples import HOUR, Eastern\n" +">>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)\n" +">>> for i in range(4):\n" +"... u = u0 + i*HOUR\n" +"... t = u.astimezone(Eastern)\n" +"... print(u.time(), 'UTC =', t.time(), t.tzname())\n" +"...\n" +"05:00:00 UTC = 00:00:00 EST\n" +"06:00:00 UTC = 01:00:00 EST\n" +"07:00:00 UTC = 03:00:00 EDT\n" +"08:00:00 UTC = 04:00:00 EDT" +msgstr "" +">>> from datetime import datetime, timezone\n" +">>> from tzinfo_examples import HOUR, Eastern\n" +">>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)\n" +">>> for i in range(4):\n" +"... u = u0 + i*HOUR\n" +"... t = u.astimezone(Eastern)\n" +"... print(u.time(), 'UTC =', t.time(), t.tzname())\n" +"...\n" +"05:00:00 UTC = 00:00:00 EST\n" +"06:00:00 UTC = 01:00:00 EST\n" +"07:00:00 UTC = 03:00:00 EDT\n" +"08:00:00 UTC = 04:00:00 EDT" + +#: ../../library/datetime.rst:2270 msgid "" "When DST ends (the \"end\" line), there's a potentially worse problem: " "there's an hour that can't be spelled unambiguously in local wall time: the " @@ -3016,14 +4584,54 @@ msgid "" "attribute set to 0 and the later times have it set to 1. For example, at the " "Fall back transition of 2016, we get::" msgstr "" - -#: ../../library/datetime.rst:2252 +"Quando o horário de verão termina (a linha \"end\"), há um problema " +"potencialmente pior: existe uma hora que não pode ser expressa de forma " +"inequívoca no horário local: a última hora do horário de verão. No fuso " +"Eastern, isso corresponde a horários no formato 5:MM UTC no dia em que o " +"horário de verão termina. O relógio de parede local salta de 1:59 (horário " +"de verão) para 1:00 (horário padrão) novamente. Horários locais no formato 1:" +"MM são ambíguos. :meth:`~.datetime.astimezone` imita o comportamento do " +"relógio local mapeando então duas horas UTC adjacentes para a mesma hora " +"local. No exemplo do fuso Eastern, horários UTC no formato 5:MM e 6:MM ambos " +"se transformam em 1:MM quando convertidos para o fuso Eastern, mas os " +"horários anteriores têm o atributo :attr:`~.datetime.fold` definido como 0 e " +"os horários posteriores têm o atributo definido como 1. Por exemplo, na " +"transição de retorno de 2016, obtemos::" + +#: ../../library/datetime.rst:2281 +msgid "" +">>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)\n" +">>> for i in range(4):\n" +"... u = u0 + i*HOUR\n" +"... t = u.astimezone(Eastern)\n" +"... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)\n" +"...\n" +"04:00:00 UTC = 00:00:00 EDT 0\n" +"05:00:00 UTC = 01:00:00 EDT 0\n" +"06:00:00 UTC = 01:00:00 EST 1\n" +"07:00:00 UTC = 02:00:00 EST 0" +msgstr "" +">>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)\n" +">>> for i in range(4):\n" +"... u = u0 + i*HOUR\n" +"... t = u.astimezone(Eastern)\n" +"... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)\n" +"...\n" +"04:00:00 UTC = 00:00:00 EDT 0\n" +"05:00:00 UTC = 01:00:00 EDT 0\n" +"06:00:00 UTC = 01:00:00 EST 1\n" +"07:00:00 UTC = 02:00:00 EST 0" + +#: ../../library/datetime.rst:2292 msgid "" "Note that the :class:`.datetime` instances that differ only by the value of " "the :attr:`~.datetime.fold` attribute are considered equal in comparisons." msgstr "" +"Observe que as instâncias de :class:`.datetime` que diferem apenas pelo " +"valor do atributo :attr:`~.datetime.fold` são consideradas iguais nas " +"comparações." -#: ../../library/datetime.rst:2255 +#: ../../library/datetime.rst:2295 msgid "" "Applications that can't bear wall-time ambiguities should explicitly check " "the value of the :attr:`~.datetime.fold` attribute or avoid using hybrid :" @@ -3032,29 +4640,41 @@ msgid "" "class representing only EST (fixed offset -5 hours), or only EDT (fixed " "offset -4 hours))." msgstr "" +"Aplicações que não suportam ambiguidades de tempo devem verificar " +"explicitamente o valor do atributo :attr:`~.datetime.fold` ou evitar " +"utilizar subclasses híbridas :class:`tzinfo`; não há ambiguidades ao usar :" +"class:`timezone` ou qualquer outra subclasse :class:`tzinfo` de deslocamento " +"fixo (como uma classe que representa apenas EST (deslocamento fixo de -5 " +"horas) ou apenas EDT (deslocamento fixo de -4 horas))." -#: ../../library/datetime.rst:2263 +#: ../../library/datetime.rst:2303 msgid ":mod:`zoneinfo`" msgstr ":mod:`zoneinfo`" -#: ../../library/datetime.rst:2264 +#: ../../library/datetime.rst:2304 msgid "" "The :mod:`!datetime` module has a basic :class:`timezone` class (for " "handling arbitrary fixed offsets from UTC) and its :attr:`timezone.utc` " "attribute (a UTC :class:`!timezone` instance)." msgstr "" +"O módulo :mod:`!datetime` possui uma classe básica :class:`timezone` (para " +"lidar com deslocamentos fixos arbitrários do UTC) e seu atributo :attr:" +"`timezone.utc` (uma instância UTC :class:`!timezone` )." -#: ../../library/datetime.rst:2268 +#: ../../library/datetime.rst:2308 msgid "" "``zoneinfo`` brings the *IANA time zone database* (also known as the Olson " "database) to Python, and its usage is recommended." msgstr "" +"``zoneinfo`` traz o *banco de dados de fuso horário IANA* (também conhecido " +"como banco de dados Olson) para Python, e seu uso é recomendado." -#: ../../library/datetime.rst:2271 +#: ../../library/datetime.rst:2311 msgid "`IANA time zone database `_" msgstr "" +"`Banco de dados de fuso horário da IANA `_" -#: ../../library/datetime.rst:2272 +#: ../../library/datetime.rst:2312 msgid "" "The Time Zone Database (often called tz, tzdata or zoneinfo) contains code " "and data that represent the history of local time for many representative " @@ -3068,24 +4688,31 @@ msgstr "" "periodicamente para refletir mudanças feitas por corpos políticos para " "limites de fuso horário, diferenças UTC, e regras de horário de verão." -#: ../../library/datetime.rst:2282 +#: ../../library/datetime.rst:2322 msgid ":class:`timezone` Objects" msgstr "Objetos :class:`timezone`" -#: ../../library/datetime.rst:2284 +#: ../../library/datetime.rst:2324 msgid "" "The :class:`timezone` class is a subclass of :class:`tzinfo`, each instance " "of which represents a time zone defined by a fixed offset from UTC." msgstr "" +"A classe :class:`timezone` é uma subclasse de :class:`tzinfo`, cada " +"instância da qual representa um fuso horário definido por um deslocamento " +"fixo do UTC." -#: ../../library/datetime.rst:2288 +#: ../../library/datetime.rst:2328 msgid "" "Objects of this class cannot be used to represent time zone information in " "the locations where different offsets are used in different days of the year " "or where historical changes have been made to civil time." msgstr "" +"Objetos desta classe não podem ser usados para representar informações de " +"fuso horário em locais onde diferentes deslocamentos são usados em " +"diferentes dias do ano ou onde mudanças históricas foram feitas no horário " +"civil." -#: ../../library/datetime.rst:2295 +#: ../../library/datetime.rst:2335 msgid "" "The *offset* argument must be specified as a :class:`timedelta` object " "representing the difference between the local time and UTC. It must be " @@ -3097,7 +4724,7 @@ msgstr "" "estritamente entre ``-timedelta(hours=24)`` e ``timedelta(hous=24)``, caso " "contrário a exceção :exc:`ValueError` será provocada." -#: ../../library/datetime.rst:2300 +#: ../../library/datetime.rst:2340 msgid "" "The *name* argument is optional. If specified it must be a string that will " "be used as the value returned by the :meth:`datetime.tzname` method." @@ -3105,7 +4732,7 @@ msgstr "" "O argumento *name* é opcional. Se especificado, deve ser uma string que será " "usada como o valor retornado pelo método :meth:`datetime.tzname`." -#: ../../library/datetime.rst:2311 ../../library/datetime.rst:2322 +#: ../../library/datetime.rst:2351 ../../library/datetime.rst:2362 msgid "" "Return the fixed value specified when the :class:`timezone` instance is " "constructed." @@ -3113,7 +4740,7 @@ msgstr "" "Retorna o valor fixo especificado quando a instância :class:`timezone` é " "construída." -#: ../../library/datetime.rst:2314 +#: ../../library/datetime.rst:2354 msgid "" "The *dt* argument is ignored. The return value is a :class:`timedelta` " "instance equal to the difference between the local time and UTC." @@ -3121,7 +4748,7 @@ msgstr "" "O argumento *dt* é ignorado. O valor de retorno é uma instância :class:" "`timedelta` equivalente à diferença entre o tempo local e o UTC." -#: ../../library/datetime.rst:2325 +#: ../../library/datetime.rst:2365 msgid "" "If *name* is not provided in the constructor, the name returned by " "``tzname(dt)`` is generated from the value of the ``offset`` as follows. If " @@ -3135,7 +4762,7 @@ msgstr "" "``UTC±HH:MM``, na qual ± é o sinal do ``offset``, HH e MM são dois dígitos " "de ``offset.hours`` e ``offset.minutes`` respectivamente." -#: ../../library/datetime.rst:2331 +#: ../../library/datetime.rst:2371 msgid "" "Name generated from ``offset=timedelta(0)`` is now plain ``'UTC'``, not " "``'UTC+00:00'``." @@ -3143,11 +4770,11 @@ msgstr "" "Nome gerado de ``offset=timedelta(0)`` é agora simplesmente ``'UTC'``, não " "``'UTC+00:00'``." -#: ../../library/datetime.rst:2338 +#: ../../library/datetime.rst:2378 msgid "Always returns ``None``." msgstr "Sempre retorna ``None``." -#: ../../library/datetime.rst:2342 +#: ../../library/datetime.rst:2382 msgid "" "Return ``dt + offset``. The *dt* argument must be an aware :class:`." "datetime` instance, with ``tzinfo`` set to ``self``." @@ -3155,15 +4782,16 @@ msgstr "" "Retorna ``dt + offset``. O argumento *dt* deve ser uma instância :class:`." "datetime` consciente, com ``tzinfo`` definida para ``self``." -#: ../../library/datetime.rst:2349 +#: ../../library/datetime.rst:2389 msgid "The UTC time zone, ``timezone(timedelta(0))``." -msgstr "" +msgstr "O fuso horário UTC, ``timezone(timedelta(0))``." -#: ../../library/datetime.rst:2358 +#: ../../library/datetime.rst:2398 msgid ":meth:`~.datetime.strftime` and :meth:`~.datetime.strptime` Behavior" msgstr "" +"Comportamento de :meth:`~.datetime.strftime` e :meth:`~.datetime.strptime`" -#: ../../library/datetime.rst:2360 +#: ../../library/datetime.rst:2400 msgid "" ":class:`date`, :class:`.datetime`, and :class:`.time` objects all support a " "``strftime(format)`` method, to create a string representing the time under " @@ -3173,7 +4801,7 @@ msgstr "" "suporte ao método ``strftime(format)``, para criar uma string representando " "o tempo sob o controle de uma string de formatação explícita." -#: ../../library/datetime.rst:2364 +#: ../../library/datetime.rst:2404 msgid "" "Conversely, the :meth:`datetime.strptime` class method creates a :class:`." "datetime` object from a string representing a date and time and a " @@ -3183,77 +4811,80 @@ msgstr "" "class:`.datetime` a partir de uma string representando a data e a hora e uma " "string de formatação correspondente." -#: ../../library/datetime.rst:2368 +#: ../../library/datetime.rst:2408 msgid "" "The table below provides a high-level comparison of :meth:`~.datetime." "strftime` versus :meth:`~.datetime.strptime`:" msgstr "" +"A tabela abaixo fornece uma comparação de alto nível entre :meth:`~.datetime." +"strftime` e :meth:`~.datetime.strptime`:" -#: ../../library/datetime.rst:2372 +#: ../../library/datetime.rst:2412 msgid "``strftime``" msgstr "``strftime``" -#: ../../library/datetime.rst:2372 +#: ../../library/datetime.rst:2412 msgid "``strptime``" msgstr "``strptime``" -#: ../../library/datetime.rst:2374 +#: ../../library/datetime.rst:2414 msgid "Usage" msgstr "Uso" -#: ../../library/datetime.rst:2374 +#: ../../library/datetime.rst:2414 msgid "Convert object to a string according to a given format" msgstr "Converte objeto para uma string conforme um formato fornecido" -#: ../../library/datetime.rst:2374 +#: ../../library/datetime.rst:2414 msgid "" "Parse a string into a :class:`.datetime` object given a corresponding format" msgstr "" "Interpreta uma string como um objeto :class:`.datetime` dado um formato " "correspondente" -#: ../../library/datetime.rst:2376 +#: ../../library/datetime.rst:2416 msgid "Type of method" msgstr "Tipo de método" -#: ../../library/datetime.rst:2376 +#: ../../library/datetime.rst:2416 msgid "Instance method" msgstr "Método de instância" -#: ../../library/datetime.rst:2376 +#: ../../library/datetime.rst:2416 msgid "Class method" msgstr "Método de classe" -#: ../../library/datetime.rst:2378 +#: ../../library/datetime.rst:2418 msgid "Method of" msgstr "Método de" -#: ../../library/datetime.rst:2378 +#: ../../library/datetime.rst:2418 msgid ":class:`date`; :class:`.datetime`; :class:`.time`" msgstr ":class:`date`; :class:`.datetime`; :class:`.time`" -#: ../../library/datetime.rst:2378 +#: ../../library/datetime.rst:2418 msgid ":class:`.datetime`" msgstr ":class:`.datetime`" -#: ../../library/datetime.rst:2380 +#: ../../library/datetime.rst:2420 msgid "Signature" msgstr "Assinatura" -#: ../../library/datetime.rst:2380 +#: ../../library/datetime.rst:2420 msgid "``strftime(format)``" msgstr "``strftime(format)``" -#: ../../library/datetime.rst:2380 +#: ../../library/datetime.rst:2420 msgid "``strptime(date_string, format)``" msgstr "``strptime(date_string, format)``" -#: ../../library/datetime.rst:2387 +#: ../../library/datetime.rst:2427 msgid "" ":meth:`~.datetime.strftime` and :meth:`~.datetime.strptime` Format Codes" msgstr "" +"Códigos de formato :meth:`~.datetime.strftime` e :meth:`~.datetime.strptime`" -#: ../../library/datetime.rst:2389 +#: ../../library/datetime.rst:2429 msgid "" "These methods accept format codes that can be used to parse and format " "dates::" @@ -3261,7 +4892,21 @@ msgstr "" "Esses métodos aceitam códigos de formato que podem ser usados para analisar " "e formatar datas::" -#: ../../library/datetime.rst:2397 +#: ../../library/datetime.rst:2431 +msgid "" +">>> datetime.strptime('31/01/22 23:59:59.999999',\n" +"... '%d/%m/%y %H:%M:%S.%f')\n" +"datetime.datetime(2022, 1, 31, 23, 59, 59, 999999)\n" +">>> _.strftime('%a %d %b %Y, %I:%M%p')\n" +"'Mon 31 Jan 2022, 11:59PM'" +msgstr "" +">>> datetime.strptime('31/01/22 23:59:59.999999',\n" +"... '%d/%m/%y %H:%M:%S.%f')\n" +"datetime.datetime(2022, 1, 31, 23, 59, 59, 999999)\n" +">>> _.strftime('%a %d %b %Y, %I:%M%p')\n" +"'Mon 31 Jan 2022, 11:59PM'" + +#: ../../library/datetime.rst:2437 msgid "" "The following is a list of all the format codes that the 1989 C standard " "requires, and these work on all platforms with a standard C implementation." @@ -3270,27 +4915,27 @@ msgstr "" "C de 1989 requer, e eles funcionam em todas as plataformas com implementação " "padrão C." -#: ../../library/datetime.rst:2401 ../../library/datetime.rst:2504 +#: ../../library/datetime.rst:2441 ../../library/datetime.rst:2544 msgid "Directive" msgstr "Diretiva" -#: ../../library/datetime.rst:2401 ../../library/datetime.rst:2504 +#: ../../library/datetime.rst:2441 ../../library/datetime.rst:2544 msgid "Meaning" msgstr "Significado" -#: ../../library/datetime.rst:2401 ../../library/datetime.rst:2504 +#: ../../library/datetime.rst:2441 ../../library/datetime.rst:2544 msgid "Example" msgstr "Exemplo" -#: ../../library/datetime.rst:2401 ../../library/datetime.rst:2504 +#: ../../library/datetime.rst:2441 ../../library/datetime.rst:2544 msgid "Notes" msgstr "Notas" -#: ../../library/datetime.rst:2403 +#: ../../library/datetime.rst:2443 msgid "``%a``" msgstr "``%a``" -#: ../../library/datetime.rst:2403 +#: ../../library/datetime.rst:2443 msgid "Weekday as locale's abbreviated name." msgstr "Dias da semana como nomes abreviados da localidade." @@ -3302,11 +4947,11 @@ msgstr "Sun, Mon, ..., Sat (en_US);" msgid "So, Mo, ..., Sa (de_DE)" msgstr "So, Mo, ..., Sa (de_DE)" -#: ../../library/datetime.rst:2408 +#: ../../library/datetime.rst:2448 msgid "``%A``" msgstr "``%A``" -#: ../../library/datetime.rst:2408 +#: ../../library/datetime.rst:2448 msgid "Weekday as locale's full name." msgstr "Dia da semana como nome completo da localidade." @@ -3318,42 +4963,42 @@ msgstr "Sunday, Monday, ..., Saturday (en_US);" msgid "Sonntag, Montag, ..., Samstag (de_DE)" msgstr "Sonntag, Montag, ..., Samstag (de_DE)" -#: ../../library/datetime.rst:2413 +#: ../../library/datetime.rst:2453 msgid "``%w``" msgstr "``%w``" -#: ../../library/datetime.rst:2413 +#: ../../library/datetime.rst:2453 msgid "Weekday as a decimal number, where 0 is Sunday and 6 is Saturday." msgstr "Dia da semana como um número decimal, onde 0 é domingo e 6 é sábado." -#: ../../library/datetime.rst:2413 +#: ../../library/datetime.rst:2453 msgid "0, 1, ..., 6" msgstr "0, 1, ..., 6" -#: ../../library/datetime.rst:2417 +#: ../../library/datetime.rst:2457 msgid "``%d``" msgstr "``%d``" -#: ../../library/datetime.rst:2417 +#: ../../library/datetime.rst:2457 msgid "Day of the month as a zero-padded decimal number." msgstr "Dia do mês como um número decimal com zeros a esquerda." -#: ../../library/datetime.rst:2417 +#: ../../library/datetime.rst:2457 msgid "01, 02, ..., 31" msgstr "01, 02, ..., 31" -#: ../../library/datetime.rst:2417 ../../library/datetime.rst:2430 -#: ../../library/datetime.rst:2433 ../../library/datetime.rst:2439 -#: ../../library/datetime.rst:2442 ../../library/datetime.rst:2448 -#: ../../library/datetime.rst:2466 +#: ../../library/datetime.rst:2457 ../../library/datetime.rst:2470 +#: ../../library/datetime.rst:2473 ../../library/datetime.rst:2479 +#: ../../library/datetime.rst:2482 ../../library/datetime.rst:2488 +#: ../../library/datetime.rst:2506 msgid "\\(9)" msgstr "\\(9)" -#: ../../library/datetime.rst:2420 +#: ../../library/datetime.rst:2460 msgid "``%b``" msgstr "``%b``" -#: ../../library/datetime.rst:2420 +#: ../../library/datetime.rst:2460 msgid "Month as locale's abbreviated name." msgstr "Mês como nome da localidade abreviado." @@ -3365,11 +5010,11 @@ msgstr "Jan, Feb, ..., Dec (en_US);" msgid "Jan, Feb, ..., Dez (de_DE)" msgstr "Jan, Feb, ..., Dez (de_DE)" -#: ../../library/datetime.rst:2425 +#: ../../library/datetime.rst:2465 msgid "``%B``" msgstr "``%B``" -#: ../../library/datetime.rst:2425 +#: ../../library/datetime.rst:2465 msgid "Month as locale's full name." msgstr "Mês como nome completo da localidade." @@ -3381,69 +5026,69 @@ msgstr "January, February, ..., December (en_US);" msgid "Januar, Februar, ..., Dezember (de_DE)" msgstr "janeiro, fevereiro, ..., dezembro (pt_BR)" -#: ../../library/datetime.rst:2430 +#: ../../library/datetime.rst:2470 msgid "``%m``" msgstr "``%m``" -#: ../../library/datetime.rst:2430 +#: ../../library/datetime.rst:2470 msgid "Month as a zero-padded decimal number." msgstr "Mês como um número decimal com zeros a esquerda." -#: ../../library/datetime.rst:2430 ../../library/datetime.rst:2442 +#: ../../library/datetime.rst:2470 ../../library/datetime.rst:2482 msgid "01, 02, ..., 12" msgstr "01, 02, ..., 12" -#: ../../library/datetime.rst:2433 +#: ../../library/datetime.rst:2473 msgid "``%y``" msgstr "``%y``" -#: ../../library/datetime.rst:2433 +#: ../../library/datetime.rst:2473 msgid "Year without century as a zero-padded decimal number." msgstr "Ano sem século como um número decimal com zeros a esquerda." -#: ../../library/datetime.rst:2433 +#: ../../library/datetime.rst:2473 msgid "00, 01, ..., 99" msgstr "00, 01, ..., 99" -#: ../../library/datetime.rst:2436 +#: ../../library/datetime.rst:2476 msgid "``%Y``" msgstr "``%Y``" -#: ../../library/datetime.rst:2436 +#: ../../library/datetime.rst:2476 msgid "Year with century as a decimal number." msgstr "Ano com século como um número decimal." -#: ../../library/datetime.rst:2436 ../../library/datetime.rst:2506 +#: ../../library/datetime.rst:2476 ../../library/datetime.rst:2546 msgid "0001, 0002, ..., 2013, 2014, ..., 9998, 9999" msgstr "0001, 0002, ..., 2013, 2014, ..., 9998, 9999" -#: ../../library/datetime.rst:2439 +#: ../../library/datetime.rst:2479 msgid "``%H``" msgstr "``%H``" -#: ../../library/datetime.rst:2439 +#: ../../library/datetime.rst:2479 msgid "Hour (24-hour clock) as a zero-padded decimal number." msgstr "" "Hora (relógio de 24 horas) como um número decimal com zeros a esquerda." -#: ../../library/datetime.rst:2439 +#: ../../library/datetime.rst:2479 msgid "00, 01, ..., 23" msgstr "00, 01, ..., 23" -#: ../../library/datetime.rst:2442 +#: ../../library/datetime.rst:2482 msgid "``%I``" msgstr "``%I``" -#: ../../library/datetime.rst:2442 +#: ../../library/datetime.rst:2482 msgid "Hour (12-hour clock) as a zero-padded decimal number." msgstr "" "Hora (relógio de 12 horas) como um número decimal com zeros a esquerda." -#: ../../library/datetime.rst:2445 +#: ../../library/datetime.rst:2485 msgid "``%p``" msgstr "``%p``" -#: ../../library/datetime.rst:2445 +#: ../../library/datetime.rst:2485 msgid "Locale's equivalent of either AM or PM." msgstr "Equivalente da localidade a AM ou PM." @@ -3455,57 +5100,57 @@ msgstr "AM, PM (en_US);" msgid "am, pm (de_DE)" msgstr "am, pm (de_DE)" -#: ../../library/datetime.rst:2445 +#: ../../library/datetime.rst:2485 msgid "\\(1), \\(3)" msgstr "\\(1), \\(3)" -#: ../../library/datetime.rst:2448 +#: ../../library/datetime.rst:2488 msgid "``%M``" msgstr "``%M``" -#: ../../library/datetime.rst:2448 +#: ../../library/datetime.rst:2488 msgid "Minute as a zero-padded decimal number." msgstr "Minutos como um número decimal, com zeros a esquerda." -#: ../../library/datetime.rst:2448 ../../library/datetime.rst:2451 +#: ../../library/datetime.rst:2488 ../../library/datetime.rst:2491 msgid "00, 01, ..., 59" msgstr "00, 01, ..., 59" -#: ../../library/datetime.rst:2451 +#: ../../library/datetime.rst:2491 msgid "``%S``" msgstr "``%S``" -#: ../../library/datetime.rst:2451 +#: ../../library/datetime.rst:2491 msgid "Second as a zero-padded decimal number." msgstr "Segundos como um número decimal, com zeros a esquerda." -#: ../../library/datetime.rst:2451 +#: ../../library/datetime.rst:2491 msgid "\\(4), \\(9)" msgstr "\\(4), \\(9)" -#: ../../library/datetime.rst:2454 +#: ../../library/datetime.rst:2494 msgid "``%f``" msgstr "``%f``" -#: ../../library/datetime.rst:2454 +#: ../../library/datetime.rst:2494 msgid "Microsecond as a decimal number, zero-padded to 6 digits." msgstr "" "Microssegundos como um número decimal, com zeros à esquerda até completar 6 " "dígitos." -#: ../../library/datetime.rst:2454 +#: ../../library/datetime.rst:2494 msgid "000000, 000001, ..., 999999" msgstr "000000, 000001, ..., 999999" -#: ../../library/datetime.rst:2454 +#: ../../library/datetime.rst:2494 msgid "\\(5)" msgstr "\\(5)" -#: ../../library/datetime.rst:2458 ../../library/datetime.rst:2617 +#: ../../library/datetime.rst:2498 ../../library/datetime.rst:2657 msgid "``%z``" msgstr "``%z``" -#: ../../library/datetime.rst:2458 +#: ../../library/datetime.rst:2498 msgid "" "UTC offset in the form ``±HHMM[SS[.ffffff]]`` (empty string if the object is " "naive)." @@ -3513,44 +5158,44 @@ msgstr "" "Diferença UTC no formato ``±HHMM[SS[.ffffff]]`` (string vazia se o objeto é " "ingênuo)." -#: ../../library/datetime.rst:2458 +#: ../../library/datetime.rst:2498 msgid "(empty), +0000, -0400, +1030, +063415, -030712.345216" msgstr "(vazio), +0000, -0400, +1030, +063415, -030712.345216" -#: ../../library/datetime.rst:2458 ../../library/datetime.rst:2463 -#: ../../library/datetime.rst:2520 +#: ../../library/datetime.rst:2498 ../../library/datetime.rst:2503 +#: ../../library/datetime.rst:2560 msgid "\\(6)" msgstr "\\(6)" -#: ../../library/datetime.rst:2463 ../../library/datetime.rst:2643 +#: ../../library/datetime.rst:2503 ../../library/datetime.rst:2683 msgid "``%Z``" msgstr "``%Z``" -#: ../../library/datetime.rst:2463 +#: ../../library/datetime.rst:2503 msgid "Time zone name (empty string if the object is naive)." msgstr "Nome do fuso horário (string vazia se o objeto é ingênuo)." -#: ../../library/datetime.rst:2463 +#: ../../library/datetime.rst:2503 msgid "(empty), UTC, GMT" msgstr "(vazio), UTC, GMT" -#: ../../library/datetime.rst:2466 +#: ../../library/datetime.rst:2506 msgid "``%j``" msgstr "``%j``" -#: ../../library/datetime.rst:2466 +#: ../../library/datetime.rst:2506 msgid "Day of the year as a zero-padded decimal number." msgstr "Dia do ano como um número decimal, com zeros a esquerda." -#: ../../library/datetime.rst:2466 +#: ../../library/datetime.rst:2506 msgid "001, 002, ..., 366" msgstr "001, 002, ..., 366" -#: ../../library/datetime.rst:2469 +#: ../../library/datetime.rst:2509 msgid "``%U``" msgstr "``%U``" -#: ../../library/datetime.rst:2469 +#: ../../library/datetime.rst:2509 msgid "" "Week number of the year (Sunday as the first day of the week) as a zero-" "padded decimal number. All days in a new year preceding the first Sunday are " @@ -3560,19 +5205,19 @@ msgstr "" "número decimal, com zeros a esquerda. Todos os dias em um ano novo " "precedendo o primeiro domingo são considerados como estando na semana 0." -#: ../../library/datetime.rst:2469 ../../library/datetime.rst:2477 +#: ../../library/datetime.rst:2509 ../../library/datetime.rst:2517 msgid "00, 01, ..., 53" msgstr "00, 01, ..., 53" -#: ../../library/datetime.rst:2469 ../../library/datetime.rst:2477 +#: ../../library/datetime.rst:2509 ../../library/datetime.rst:2517 msgid "\\(7), \\(9)" msgstr "\\(7), \\(9)" -#: ../../library/datetime.rst:2477 +#: ../../library/datetime.rst:2517 msgid "``%W``" msgstr "``%W``" -#: ../../library/datetime.rst:2477 +#: ../../library/datetime.rst:2517 msgid "" "Week number of the year (Monday as the first day of the week) as a zero-" "padded decimal number. All days in a new year preceding the first Monday are " @@ -3583,11 +5228,11 @@ msgstr "" "precedendo a primeira segunda-feira são considerados como estando na semana " "0." -#: ../../library/datetime.rst:2485 +#: ../../library/datetime.rst:2525 msgid "``%c``" msgstr "``%c``" -#: ../../library/datetime.rst:2485 +#: ../../library/datetime.rst:2525 msgid "Locale's appropriate date and time representation." msgstr "Representação de data e hora apropriada da localidade." @@ -3599,11 +5244,11 @@ msgstr "Tue Aug 16 21:30:00 1988 (en_US);" msgid "Di 16 Aug 21:30:00 1988 (de_DE)" msgstr "Di 16 Aug 21:30:00 1988 (de_DE)" -#: ../../library/datetime.rst:2490 +#: ../../library/datetime.rst:2530 msgid "``%x``" msgstr "``%x``" -#: ../../library/datetime.rst:2490 +#: ../../library/datetime.rst:2530 msgid "Locale's appropriate date representation." msgstr "Representação de data apropriada de localidade." @@ -3619,11 +5264,11 @@ msgstr "08/16/1988 (en_US);" msgid "16.08.1988 (de_DE)" msgstr "16.08.1988 (de_DE)" -#: ../../library/datetime.rst:2494 +#: ../../library/datetime.rst:2534 msgid "``%X``" msgstr "``%X``" -#: ../../library/datetime.rst:2494 +#: ../../library/datetime.rst:2534 msgid "Locale's appropriate time representation." msgstr "Representação de hora apropriada da localidade." @@ -3635,19 +5280,19 @@ msgstr "21:30:00 (en_US);" msgid "21:30:00 (de_DE)" msgstr "21:30:00 (de_DE)" -#: ../../library/datetime.rst:2497 +#: ../../library/datetime.rst:2537 msgid "``%%``" msgstr "``%%``" -#: ../../library/datetime.rst:2497 +#: ../../library/datetime.rst:2537 msgid "A literal ``'%'`` character." msgstr "Um caractere literal ``'%'``." -#: ../../library/datetime.rst:2497 +#: ../../library/datetime.rst:2537 msgid "%" msgstr "%" -#: ../../library/datetime.rst:2500 +#: ../../library/datetime.rst:2540 msgid "" "Several additional directives not required by the C89 standard are included " "for convenience. These parameters all correspond to ISO 8601 date values." @@ -3656,11 +5301,11 @@ msgstr "" "para conveniência. Estes parâmetros todos correspondem a valores de datas na " "ISO 8601." -#: ../../library/datetime.rst:2506 +#: ../../library/datetime.rst:2546 msgid "``%G``" msgstr "``%G``" -#: ../../library/datetime.rst:2506 +#: ../../library/datetime.rst:2546 msgid "" "ISO 8601 year with century representing the year that contains the greater " "part of the ISO week (``%V``)." @@ -3668,27 +5313,27 @@ msgstr "" "Ano ISO 8601 com o século representando o ano que a maior parte da semana " "ISO (``%V``)." -#: ../../library/datetime.rst:2506 +#: ../../library/datetime.rst:2546 msgid "\\(8)" msgstr "\\(8)" -#: ../../library/datetime.rst:2511 +#: ../../library/datetime.rst:2551 msgid "``%u``" msgstr "``%u``" -#: ../../library/datetime.rst:2511 +#: ../../library/datetime.rst:2551 msgid "ISO 8601 weekday as a decimal number where 1 is Monday." msgstr "Dia de semana ISO 8601 como um número decimal onde 1 é segunda-feira." -#: ../../library/datetime.rst:2511 +#: ../../library/datetime.rst:2551 msgid "1, 2, ..., 7" msgstr "1, 2, ..., 7" -#: ../../library/datetime.rst:2514 +#: ../../library/datetime.rst:2554 msgid "``%V``" msgstr "``%V``" -#: ../../library/datetime.rst:2514 +#: ../../library/datetime.rst:2554 msgid "" "ISO 8601 week as a decimal number with Monday as the first day of the week. " "Week 01 is the week containing Jan 4." @@ -3696,19 +5341,19 @@ msgstr "" "Semana ISO 8601 como um número decimal, com segunda-feira como o primeiro " "dia da semana. A semana 01 é a semana contendo o dia 4 de Janeiro." -#: ../../library/datetime.rst:2514 +#: ../../library/datetime.rst:2554 msgid "01, 02, ..., 53" msgstr "01, 02, ..., 53" -#: ../../library/datetime.rst:2514 +#: ../../library/datetime.rst:2554 msgid "\\(8), \\(9)" msgstr "\\(8), \\(9)" -#: ../../library/datetime.rst:2520 ../../library/datetime.rst:2639 +#: ../../library/datetime.rst:2560 ../../library/datetime.rst:2679 msgid "``%:z``" msgstr "``%:z``" -#: ../../library/datetime.rst:2520 +#: ../../library/datetime.rst:2560 msgid "" "UTC offset in the form ``±HH:MM[:SS[.ffffff]]`` (empty string if the object " "is naive)." @@ -3716,11 +5361,11 @@ msgstr "" "Diferença UTC no formato ``±HH:MM[:SS[.ffffff]]`` (string vazia se o objeto " "é ingênuo)." -#: ../../library/datetime.rst:2520 +#: ../../library/datetime.rst:2560 msgid "(empty), +00:00, -04:00, +10:30, +06:34:15, -03:07:12.345216" msgstr "(vazio), +00:00, -04:00, +10:30, +06:34:15, -03:07:12.345216" -#: ../../library/datetime.rst:2526 +#: ../../library/datetime.rst:2566 msgid "" "These may not be available on all platforms when used with the :meth:`~." "datetime.strftime` method. The ISO 8601 year and ISO 8601 week directives " @@ -3728,8 +5373,13 @@ msgid "" "Calling :meth:`~.datetime.strptime` with incomplete or ambiguous ISO 8601 " "directives will raise a :exc:`ValueError`." msgstr "" +"Eles podem não estar disponíveis em todas as plataformas quando usados com o " +"método :meth:`~.datetime.strftime`. As diretivas de ano e semana da ISO 8601 " +"e ISO 8601 não são intercambiáveis com as diretivas ano e número da semana " +"acima. Chamar :meth:`~.datetime.strptime` com diretivas ISO 8601 incompletas " +"ou ambíguas levantará um :exc:`ValueError`." -#: ../../library/datetime.rst:2531 +#: ../../library/datetime.rst:2571 msgid "" "The full set of format codes supported varies across platforms, because " "Python calls the platform C library's :c:func:`strftime` function, and " @@ -3738,59 +5388,81 @@ msgid "" "documentation. There are also differences between platforms in handling of " "unsupported format specifiers." msgstr "" +"O conjunto completo de códigos de formato suportados varia entre as " +"plataformas, porque o Python chama a função :c:func:`strftime` da biblioteca " +"C da plataforma, e variações de plataforma são comuns. Para ver o conjunto " +"completo de códigos de formato suportados em sua plataforma, consulte a " +"documentação :manpage:`strftime(3)`. Também existem diferenças entre " +"plataformas no tratamento de especificadores de formato não suportados." -#: ../../library/datetime.rst:2537 +#: ../../library/datetime.rst:2577 msgid "``%G``, ``%u`` and ``%V`` were added." msgstr "``%G``, ``%u`` e ``%V`` foram adicionados." -#: ../../library/datetime.rst:2540 +#: ../../library/datetime.rst:2580 msgid "``%:z`` was added." msgstr "``%:z`` foi adicionado." -#: ../../library/datetime.rst:2544 +#: ../../library/datetime.rst:2584 msgid "Technical Detail" msgstr "Detalhes técnicos" -#: ../../library/datetime.rst:2546 +#: ../../library/datetime.rst:2586 msgid "" "Broadly speaking, ``d.strftime(fmt)`` acts like the :mod:`time` module's " "``time.strftime(fmt, d.timetuple())`` although not all objects support a :" "meth:`~date.timetuple` method." msgstr "" +"Em termos gerais, ``d.strftime(fmt)`` age como ``time.strftime(fmt, d." +"timetuple())`` do módulo :mod:`time`, embora nem todos os objetos suportem " +"um método :meth:`~date.timetuple`." -#: ../../library/datetime.rst:2550 +#: ../../library/datetime.rst:2590 msgid "" "For the :meth:`.datetime.strptime` class method, the default value is " "``1900-01-01T00:00:00.000``: any components not specified in the format " "string will be pulled from the default value. [#]_" msgstr "" +"Para o método de classe :meth:`.datetime.strptime`, o valor padrão é " +"``1900-01-01T00:00:00.000``: quaisquer componentes não especificados na " +"string de formato serão extraídos do valor padrão. [#]_" -#: ../../library/datetime.rst:2554 +#: ../../library/datetime.rst:2594 msgid "Using ``datetime.strptime(date_string, format)`` is equivalent to::" msgstr "Usar ``datetime.strptime(date_string, format)`` é equivalente a::" -#: ../../library/datetime.rst:2558 +#: ../../library/datetime.rst:2598 msgid "" "except when the format includes sub-second components or time zone offset " "information, which are supported in ``datetime.strptime`` but are discarded " "by ``time.strptime``." msgstr "" +"exceto quando o formato inclui componentes de sub-segundos ou informações de " +"deslocamento de fuso horário, que são suportados em ``datetime.strptime`` " +"mas são descartados por ``time.strptime``." -#: ../../library/datetime.rst:2562 +#: ../../library/datetime.rst:2602 msgid "" "For :class:`.time` objects, the format codes for year, month, and day should " "not be used, as :class:`!time` objects have no such values. If they're used " "anyway, 1900 is substituted for the year, and 1 for the month and day." msgstr "" +"Para objetos :class:`.time`, os códigos de formato para ano, mês e dia não " +"devem ser usados, pois objetos :class:`!time` não têm tais valores. Se forem " +"usados de qualquer forma, o ano é substituído por 1900, e o mês e dia por 1." -#: ../../library/datetime.rst:2566 +#: ../../library/datetime.rst:2606 msgid "" "For :class:`date` objects, the format codes for hours, minutes, seconds, and " "microseconds should not be used, as :class:`date` objects have no such " "values. If they're used anyway, 0 is substituted for them." msgstr "" +"Para objetos :class:`date`, os códigos de formato para horas, minutos, " +"segundos e microssegundos não devem ser usados, pois objetos :class:`date` " +"não têm tais valores. Se forem usados de qualquer forma, são substituídos " +"por 0." -#: ../../library/datetime.rst:2570 +#: ../../library/datetime.rst:2610 msgid "" "For the same reason, handling of format strings containing Unicode code " "points that can't be represented in the charset of the current locale is " @@ -3798,14 +5470,14 @@ msgid "" "intact in the output, while on others ``strftime`` may raise :exc:" "`UnicodeError` or return an empty string instead." msgstr "" -"Pela mesma razão, o tratamento de formatação de strings contendo pontos de " +"Pela mesma razão, o tratamento de formato de strings contendo pontos de " "código Unicode que não podem ser representados no conjunto de caracteres da " "localidade atual também é dependente da plataforma. Em algumas plataformas, " "tais pontos de código são preservados intactos na saída, enquanto em outros " "``strftime`` pode levantar :exc:`UnicodeError` ou retornar uma string vazia " "ao invés." -#: ../../library/datetime.rst:2579 +#: ../../library/datetime.rst:2619 msgid "" "Because the format depends on the current locale, care should be taken when " "making assumptions about the output value. Field orderings will vary (for " @@ -3817,46 +5489,62 @@ msgstr "" "exemplo, \"mês/dia/ano\" versus \"dia/mês/ano\") e a saída pode conter " "caracteres não ASCII." -#: ../../library/datetime.rst:2585 +#: ../../library/datetime.rst:2625 msgid "" "The :meth:`~.datetime.strptime` method can parse years in the full [1, 9999] " "range, but years < 1000 must be zero-filled to 4-digit width." msgstr "" +"O método :meth:`~.datetime.strptime` pode analisar anos no intervalo " +"completo de [1, 9999], mas anos < 1000 devem ser preenchidos com zeros até " +"uma largura de 4 dígitos." -#: ../../library/datetime.rst:2588 +#: ../../library/datetime.rst:2628 msgid "" "In previous versions, :meth:`~.datetime.strftime` method was restricted to " "years >= 1900." msgstr "" +"Em versões anteriores, o método :meth:`~.datetime.strftime` era limitado a " +"anos >= 1900." -#: ../../library/datetime.rst:2592 +#: ../../library/datetime.rst:2632 msgid "" "In version 3.2, :meth:`~.datetime.strftime` method was restricted to years " ">= 1000." msgstr "" +"Na versão 3.2, o método :meth:`~.datetime.strftime` era limitado a anos >= " +"1000." -#: ../../library/datetime.rst:2597 +#: ../../library/datetime.rst:2637 msgid "" "When used with the :meth:`~.datetime.strptime` method, the ``%p`` directive " "only affects the output hour field if the ``%I`` directive is used to parse " "the hour." msgstr "" +"Quando usado com o método :meth:`~.datetime.strptime`, a diretiva ``%p`` " +"afeta somente o campo de hora de saída se a diretiva ``%I`` for usada para " +"analisar a hora." -#: ../../library/datetime.rst:2601 +#: ../../library/datetime.rst:2641 msgid "" "Unlike the :mod:`time` module, the :mod:`!datetime` module does not support " "leap seconds." msgstr "" +"Ao contrário do módulo :mod:`time`, o módulo :mod:`!datetime` não oferece " +"suporte para segundos intercalares." -#: ../../library/datetime.rst:2605 +#: ../../library/datetime.rst:2645 msgid "" "When used with the :meth:`~.datetime.strptime` method, the ``%f`` directive " "accepts from one to six digits and zero pads on the right. ``%f`` is an " "extension to the set of format characters in the C standard (but implemented " "separately in datetime objects, and therefore always available)." msgstr "" +"Quando usado com o método :meth:`~.datetime.strptime`, a diretiva ``%f`` " +"aceita de um a seis dígitos e zeros à direita. ``%f`` é uma extensão do " +"conjunto de caracteres de formato no padrão do C (mas implementado " +"separadamente em objetos datetime e, portanto, sempre disponível)." -#: ../../library/datetime.rst:2612 +#: ../../library/datetime.rst:2652 msgid "" "For a naive object, the ``%z``, ``%:z`` and ``%Z`` format codes are replaced " "by empty strings." @@ -3864,11 +5552,11 @@ msgstr "" "Para um objeto ingênuo, os códigos de formatação ``%z``, ``%:z`` e ``%Z`` " "são substituídos por strings vazias." -#: ../../library/datetime.rst:2615 +#: ../../library/datetime.rst:2655 msgid "For an aware object:" msgstr "Para um objeto consciente:" -#: ../../library/datetime.rst:2618 +#: ../../library/datetime.rst:2658 msgid "" ":meth:`~.datetime.utcoffset` is transformed into a string of the form " "``±HHMM[SS[.ffffff]]``, where ``HH`` is a 2-digit string giving the number " @@ -3881,8 +5569,19 @@ msgid "" "datetime.utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is " "replaced with the string ``'-0330'``." msgstr "" +":meth:`~.datetime.utcoffset` é transformado em uma string do formato " +"``±HHMM[SS[.ffffff]]``, onde ``HH`` é uma string de 2 dígitos que fornece o " +"número de horas de deslocamento UTC, ``MM`` é uma string de 2 dígitos que " +"fornece o número de minutos de deslocamento UTC, ``SS`` é uma string de 2 " +"dígitos que fornece o número de segundos de deslocamento UTC e ``ffffff`` é " +"uma string de 6 dígitos que fornece o número de microssegundos de " +"deslocamento UTC. A parte ``ffffff`` é omitida quando o deslocamento é um " +"número inteiro de segundos e tanto a parte ``ffffff`` quanto a parte ``SS`` " +"são omitidas quando o deslocamento é um número inteiro de minutos. Por " +"exemplo, se :meth:`~.datetime.utcoffset` retornar ``timedelta(hours=-3, " +"minutes=-30)``, ``%z`` será substituído pela string ``'-0330'``." -#: ../../library/datetime.rst:2632 +#: ../../library/datetime.rst:2672 msgid "" "When the ``%z`` directive is provided to the :meth:`~.datetime.strptime` " "method, the UTC offsets can have a colon as a separator between hours, " @@ -3890,8 +5589,13 @@ msgid "" "offset of one hour. In addition, providing ``'Z'`` is identical to " "``'+00:00'``." msgstr "" +"Quando a diretiva ``%z`` é fornecida ao método :meth:`~.datetime.strptime`, " +"os deslocamentos UTC podem ter dois pontos como separador entre horas, " +"minutos e segundos. Por exemplo, ``'+01:00:00'`` será analisado como um " +"deslocamento de uma hora. Além disso, fornecer ``'Z'`` é idêntico a " +"``'+00:00'``." -#: ../../library/datetime.rst:2640 +#: ../../library/datetime.rst:2680 msgid "" "Behaves exactly as ``%z``, but has a colon separator added between hours, " "minutes and seconds." @@ -3899,26 +5603,29 @@ msgstr "" "Comporta-se exatamente como ``%z``, mas possui um separador de dois pontos " "adicionado entre horas, minutos e segundos." -#: ../../library/datetime.rst:2644 +#: ../../library/datetime.rst:2684 msgid "" "In :meth:`~.datetime.strftime`, ``%Z`` is replaced by an empty string if :" "meth:`~.datetime.tzname` returns ``None``; otherwise ``%Z`` is replaced by " "the returned value, which must be a string." msgstr "" +"Em :meth:`~.datetime.strftime`, ``%Z`` é substituído por uma string vazia " +"se :meth:`~.datetime.tzname` retornar ``None``; caso contrário, ``%Z`` é " +"substituído pelo valor retornado, que deve ser uma string." -#: ../../library/datetime.rst:2648 +#: ../../library/datetime.rst:2688 msgid ":meth:`~.datetime.strptime` only accepts certain values for ``%Z``:" -msgstr "" +msgstr ":meth:`~.datetime.strptime` aceita apenas certos valores para ``%Z``:" -#: ../../library/datetime.rst:2650 +#: ../../library/datetime.rst:2690 msgid "any value in ``time.tzname`` for your machine's locale" msgstr "qualquer valor em ``time.tzname`` para a localidade da sua máquina" -#: ../../library/datetime.rst:2651 +#: ../../library/datetime.rst:2691 msgid "the hard-coded values ``UTC`` and ``GMT``" msgstr "os valores codificados ``UTC`` e ``GMT``" -#: ../../library/datetime.rst:2653 +#: ../../library/datetime.rst:2693 msgid "" "So someone living in Japan may have ``JST``, ``UTC``, and ``GMT`` as valid " "values, but probably not ``EST``. It will raise ``ValueError`` for invalid " @@ -3928,37 +5635,50 @@ msgstr "" "valores válidos, mas provavelmente não ``EST``. Isso levantará " "``ValueError`` para valores inválidos." -#: ../../library/datetime.rst:2657 +#: ../../library/datetime.rst:2697 msgid "" "When the ``%z`` directive is provided to the :meth:`~.datetime.strptime` " "method, an aware :class:`.datetime` object will be produced. The ``tzinfo`` " "of the result will be set to a :class:`timezone` instance." msgstr "" +"Quando a diretiva ``%z`` é fornecida ao método :meth:`~.datetime.strptime`, " +"um objeto :class:`.datetime` consciente será produzido. O ``tzinfo`` do " +"resultado será definido para uma instância :class:`timezone`." -#: ../../library/datetime.rst:2663 +#: ../../library/datetime.rst:2703 msgid "" "When used with the :meth:`~.datetime.strptime` method, ``%U`` and ``%W`` are " "only used in calculations when the day of the week and the calendar year " "(``%Y``) are specified." msgstr "" +"Quando utilizados com o método :meth:`~.datetime.strptime`, ``%U`` e ``%W`` " +"são usados somente em cálculos quando o dia da semana e o ano (``%Y``) são " +"especificados." -#: ../../library/datetime.rst:2668 +#: ../../library/datetime.rst:2708 msgid "" "Similar to ``%U`` and ``%W``, ``%V`` is only used in calculations when the " "day of the week and the ISO year (``%G``) are specified in a :meth:`~." "datetime.strptime` format string. Also note that ``%G`` and ``%Y`` are not " "interchangeable." msgstr "" +"Semelhante a ``%U`` e ``%W``, ``%V`` é usado apenas em cálculos quando o dia " +"da semana e o ano ISO (``%G``) são especificados em um formato de string :" +"meth:`~.datetime.strptime`. Observe também que ``%G`` e ``%Y`` não são " +"intercambiáveis." -#: ../../library/datetime.rst:2674 +#: ../../library/datetime.rst:2714 msgid "" "When used with the :meth:`~.datetime.strptime` method, the leading zero is " "optional for formats ``%d``, ``%m``, ``%H``, ``%I``, ``%M``, ``%S``, " "``%j``, ``%U``, ``%W``, and ``%V``. Format ``%y`` does require a leading " "zero." msgstr "" +"Quando usado com o método :meth:`~.datetime.strptime`, o zero à esquerda é " +"opcional para os formatos ``%d``, ``%m``, ``%H``, ``%I``, ``%M``, ``%S``, " +"``%j``, ``%U``, ``%W`` e ``%V``. O formato ``%y`` requer um zero à esquerda." -#: ../../library/datetime.rst:2679 +#: ../../library/datetime.rst:2719 msgid "" "When parsing a month and day using :meth:`~.datetime.strptime`, always " "include a year in the format. If the value you need to parse lacks a year, " @@ -3966,24 +5686,46 @@ msgid "" "exception when it encounters leap day because the default year used by the " "parser is not a leap year. Users run into this bug every four years..." msgstr "" +"Ao analisar um mês e dia usando :meth:`~.datetime.strptime`, sempre inclua " +"um ano no formato. Se o valor que você precisa analisar não possui um ano, " +"adicione um ano bissexto fictício de forma explícita. Caso contrário, seu " +"código levantará uma exceção ao encontrar o dia bissexto, porque o ano " +"padrão usado pelo analisador sintático não é um ano bissexto. Os usuários " +"encontram esse bug a cada quatro anos..." -#: ../../library/datetime.rst:2691 +#: ../../library/datetime.rst:2725 +msgid "" +">>> month_day = \"02/29\"\n" +">>> datetime.strptime(f\"{month_day};1984\", \"%m/%d;%Y\") # No leap year " +"bug.\n" +"datetime.datetime(1984, 2, 29, 0, 0)" +msgstr "" +">>> month_day = \"02/29\"\n" +">>> datetime.strptime(f\"{month_day};1984\", \"%m/%d;%Y\") # Sem bug de ano " +"bissexto.\n" +"datetime.datetime(1984, 2, 29, 0, 0)" + +#: ../../library/datetime.rst:2731 msgid "" ":meth:`~.datetime.strptime` calls using a format string containing a day of " "month without a year now emit a :exc:`DeprecationWarning`. In 3.15 or later " "we may change this into an error or change the default year to a leap year. " "See :gh:`70647`." msgstr "" +"Chamadas ao método :meth:`~.datetime.strptime` usando uma string de formato " +"contendo um dia do mês sem um ano agora emitem um :exc:`DeprecationWarning`. " +"Na versão 3.15 ou posterior, podemos mudar isso para um erro ou mudar o ano " +"padrão para um ano bissexto. Consulte :gh:`70647`." -#: ../../library/datetime.rst:2698 +#: ../../library/datetime.rst:2738 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../library/datetime.rst:2699 +#: ../../library/datetime.rst:2739 msgid "If, that is, we ignore the effects of Relativity" msgstr "Se, isto é, nós ignoramos os efeitos da Relatividade" -#: ../../library/datetime.rst:2701 +#: ../../library/datetime.rst:2741 msgid "" "This matches the definition of the \"proleptic Gregorian\" calendar in " "Dershowitz and Reingold's book *Calendrical Calculations*, where it's the " @@ -3997,7 +5739,7 @@ msgstr "" "conversão entre ordinais proléptico Gregoriano e muitos outros sistemas de " "calendário." -#: ../../library/datetime.rst:2707 +#: ../../library/datetime.rst:2747 msgid "" "See R. H. van Gent's `guide to the mathematics of the ISO 8601 calendar " "`_ de R. H. van Gent para uma boa explicação." -#: ../../library/datetime.rst:2711 +#: ../../library/datetime.rst:2751 msgid "" "Passing ``datetime.strptime('Feb 29', '%b %d')`` will fail since 1900 is not " "a leap year." msgstr "" +"Passar ``datetime.strptime('Feb 29', '%b %d')`` irá falhar porque 1900 não é " +"um ano bissexto." -#: ../../library/datetime.rst:2352 +#: ../../library/datetime.rst:2392 msgid "% (percent)" msgstr "% (porcentagem)" -#: ../../library/datetime.rst:2352 +#: ../../library/datetime.rst:2392 msgid "datetime format" msgstr "datetime, formato" diff --git a/library/dbm.po b/library/dbm.po index a6ceebce0..3e3ca9f9f 100644 --- a/library/dbm.po +++ b/library/dbm.po @@ -1,32 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 01:04+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-14 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/dbm.rst:2 msgid ":mod:`!dbm` --- Interfaces to Unix \"databases\"" -msgstr "" +msgstr ":mod:`!dbm` --- Interfaces para \"banco de dados\" Unix" #: ../../library/dbm.rst:7 msgid "**Source code:** :source:`Lib/dbm/__init__.py`" @@ -35,18 +34,19 @@ msgstr "**Código-fonte:** :source:`Lib/dbm/__init__.py`" #: ../../library/dbm.rst:11 msgid ":mod:`dbm` is a generic interface to variants of the DBM database:" msgstr "" +":mod:`dbm` é uma interface genérica para variantes do banco de dados DBM:" #: ../../library/dbm.rst:13 msgid ":mod:`dbm.sqlite3`" -msgstr "" +msgstr ":mod:`dbm.sqlite3`" #: ../../library/dbm.rst:14 msgid ":mod:`dbm.gnu`" -msgstr "" +msgstr ":mod:`dbm.gnu`" #: ../../library/dbm.rst:15 msgid ":mod:`dbm.ndbm`" -msgstr "" +msgstr ":mod:`dbm.ndbm`" #: ../../library/dbm.rst:17 msgid "" @@ -54,123 +54,131 @@ msgid "" "in module :mod:`dbm.dumb` will be used. There is a `third party interface " "`_ to the Oracle Berkeley DB." msgstr "" +"Se nenhum desses módulos estiverem instalados, a implementação lenta, mas " +"simples, no módulo :mod:`dbm.dumb` será usada. Há uma `interface de " +"terceiros `_ para o Oracle " +"Berkeley DB." -#: ../../includes/wasm-ios-notavail.rst:3 -msgid ":ref:`Availability `: not WASI, not iOS." -msgstr ":ref:`Disponibilidade `: não WAS, não iOS." - -#: ../../includes/wasm-ios-notavail.rst:5 -msgid "" -"This module does not work or is not available on WebAssembly platforms, or " -"on iOS. See :ref:`wasm-availability` for more information on WASM " -"availability; see :ref:`iOS-availability` for more information on iOS " -"availability." -msgstr "" -"Este módulo não funciona ou não está disponível nas plataformas WebAssembly " -"ou iOS. Veja :ref:`wasm-availability` para mais informações sobre a " -"disponibilidade no WASM; veja :ref:`iOS-availability` para mais informações " -"sobre a disponibilidade no iOS." - -#: ../../library/dbm.rst:26 +#: ../../library/dbm.rst:24 msgid "" "A tuple containing the exceptions that can be raised by each of the " "supported modules, with a unique exception also named :exc:`dbm.error` as " "the first item --- the latter is used when :exc:`dbm.error` is raised." msgstr "" +"Uma tupla contendo as exceções que podem ser levantadas por cada um dos " +"módulos suportados, com a única exceção também chamada :exc:`dbm.error` como " +"o primeiro item --- o último é usado quando :exc:`dbm.error` é levantada." -#: ../../library/dbm.rst:33 +#: ../../library/dbm.rst:31 msgid "" "This function attempts to guess which of the several simple database modules " "available --- :mod:`dbm.sqlite3`, :mod:`dbm.gnu`, :mod:`dbm.ndbm`, or :mod:" "`dbm.dumb` --- should be used to open a given file." msgstr "" +"Esta função tenta adivinhar qual dos vários módulos de banco de dados " +"simples disponíveis --- :mod:`dbm.sqlite3`, :mod:`dbm.gnu`, :mod:`dbm.ndbm` " +"ou :mod:`dbm.dumb` --- deve ser usado para abrir o arquivo fornecido." -#: ../../library/dbm.rst:37 +#: ../../library/dbm.rst:35 msgid "Return one of the following values:" -msgstr "" +msgstr "Retorna um dos seguintes valores:" -#: ../../library/dbm.rst:39 +#: ../../library/dbm.rst:37 msgid "" "``None`` if the file can't be opened because it's unreadable or doesn't exist" msgstr "" +"``None`` se o arquivo não puder ser aberto porque está ilegível ou não existe" -#: ../../library/dbm.rst:40 +#: ../../library/dbm.rst:38 msgid "the empty string (``''``) if the file's format can't be guessed" msgstr "" +"a string vazia (``''``) se o formato do arquivo não puder ser adivinhado" -#: ../../library/dbm.rst:41 +#: ../../library/dbm.rst:39 msgid "" "a string containing the required module name, such as ``'dbm.ndbm'`` or " "``'dbm.gnu'``" msgstr "" +"uma string contendo o nome do módulo necessário, tal como ``'dbm.ndbm'`` ou " +"``'dbm.gnu'``" -#: ../../library/dbm.rst:43 ../../library/dbm.rst:248 ../../library/dbm.rst:444 +#: ../../library/dbm.rst:41 ../../library/dbm.rst:250 ../../library/dbm.rst:448 msgid "*filename* accepts a :term:`path-like object`." -msgstr "" +msgstr "*filename* aceita um :term:`objeto caminho ou similar`." -#: ../../library/dbm.rst:67 +#: ../../library/dbm.rst:65 msgid "Open a database and return the corresponding database object." msgstr "" +"Abre um banco de dados e retorna o objeto banco de dados correspondendo." #: ../../library/dbm.rst:0 msgid "Parameters" msgstr "Parâmetros" -#: ../../library/dbm.rst:69 +#: ../../library/dbm.rst:67 msgid "" "The database file to open. If the database file already exists, the :func:" "`whichdb` function is used to determine its type and the appropriate module " "is used; if it does not exist, the first submodule listed above that can be " "imported is used." msgstr "" +"O arquivo de banco de dados para abrir. Se o arquivo de banco de dados já " +"existe, a função :func:`whichdb` é usada para determinar seu tipo e o módulo " +"apropriado é usado; se ele não existir, o primeiro submódulo listado acima " +"que pode ser importado é usado." -#: ../../library/dbm.rst:70 ../../library/dbm.rst:220 +#: ../../library/dbm.rst:68 ../../library/dbm.rst:222 msgid "The database file to open." -msgstr "" +msgstr "O arquivo de banco de dados para abrir." -#: ../../library/dbm.rst:72 +#: ../../library/dbm.rst:70 msgid "" "If the database file already exists, the :func:`whichdb` function is used to " "determine its type and the appropriate module is used; if it does not exist, " "the first submodule listed above that can be imported is used." msgstr "" +"Se o arquivo de banco de dados já existe, a função :func:`whichdb` é usada " +"para determinar seu tipo e o módulo apropriado é usado; se ele não existir, " +"o primeiro submódulo listado acima que pode ser importado é usado." -#: ../../library/dbm.rst:77 ../../library/dbm.rst:178 ../../library/dbm.rst:349 +#: ../../library/dbm.rst:75 ../../library/dbm.rst:178 ../../library/dbm.rst:353 msgid "" "* ``'r'`` (default): |flag_r| * ``'w'``: |flag_w| * ``'c'``: |flag_c| * " "``'n'``: |flag_n|" msgstr "" +"* ``'r'`` (padrão): |flag_r| * ``'w'``: |flag_w| * ``'c'``: |flag_c| * " +"``'n'``: |flag_n|" -#: ../../library/dbm.rst:78 ../../library/dbm.rst:180 ../../library/dbm.rst:225 -#: ../../library/dbm.rst:350 +#: ../../library/dbm.rst:76 ../../library/dbm.rst:180 ../../library/dbm.rst:227 +#: ../../library/dbm.rst:354 msgid "``'r'`` (default): |flag_r|" -msgstr "" +msgstr "``'r'`` (padrão): |flag_r|" -#: ../../library/dbm.rst:79 ../../library/dbm.rst:181 ../../library/dbm.rst:226 -#: ../../library/dbm.rst:351 ../../library/dbm.rst:425 +#: ../../library/dbm.rst:77 ../../library/dbm.rst:181 ../../library/dbm.rst:228 +#: ../../library/dbm.rst:355 ../../library/dbm.rst:429 msgid "``'w'``: |flag_w|" -msgstr "" +msgstr "``'w'``: |flag_w|" -#: ../../library/dbm.rst:80 ../../library/dbm.rst:182 ../../library/dbm.rst:227 -#: ../../library/dbm.rst:352 +#: ../../library/dbm.rst:78 ../../library/dbm.rst:182 ../../library/dbm.rst:229 +#: ../../library/dbm.rst:356 msgid "``'c'``: |flag_c|" -msgstr "" +msgstr "``'c'``: |flag_c|" -#: ../../library/dbm.rst:81 ../../library/dbm.rst:183 ../../library/dbm.rst:228 -#: ../../library/dbm.rst:353 ../../library/dbm.rst:427 +#: ../../library/dbm.rst:79 ../../library/dbm.rst:183 ../../library/dbm.rst:230 +#: ../../library/dbm.rst:357 ../../library/dbm.rst:431 msgid "``'n'``: |flag_n|" -msgstr "" +msgstr "``'n'``: |flag_n|" -#: ../../library/dbm.rst:83 ../../library/dbm.rst:242 ../../library/dbm.rst:355 -#: ../../library/dbm.rst:429 +#: ../../library/dbm.rst:81 ../../library/dbm.rst:244 ../../library/dbm.rst:359 +#: ../../library/dbm.rst:433 msgid "|mode_param_doc|" -msgstr "" +msgstr "|mode_param_doc|" -#: ../../library/dbm.rst:86 +#: ../../library/dbm.rst:84 msgid "*file* accepts a :term:`path-like object`." -msgstr "" +msgstr "*file* aceita um :term:`objeto caminho ou similar`." -#: ../../library/dbm.rst:89 +#: ../../library/dbm.rst:87 msgid "" "The object returned by :func:`~dbm.open` supports the same basic " "functionality as a :class:`dict`; keys and their corresponding values can be " @@ -178,71 +186,155 @@ msgid "" "`!keys` method are available, as well as :meth:`!get` and :meth:`!" "setdefault` methods." msgstr "" +"O objeto retornado por :func:`~dbm.open` oferece suporte à mesma " +"funcionalidade básica que um :class:`dict`; chaves e seus valores " +"correspondentes podem ser armazenados, obtidos e excluídos, e o operador :" +"keyword:`in` e o método :meth:`!keys` estão disponíveis, bem como métodos :" +"meth:`!get` e :meth:`!setdefault`." -#: ../../library/dbm.rst:94 +#: ../../library/dbm.rst:92 msgid "" "Key and values are always stored as :class:`bytes`. This means that when " "strings are used they are implicitly converted to the default encoding " "before being stored." msgstr "" +"Chaves e valores são sempre armazenados como :class:`bytes`. Isso significa " +"que quando strings são usadas, elas são implicitamente convertidas para a " +"codificação padrão antes de serem armazenadas." -#: ../../library/dbm.rst:98 +#: ../../library/dbm.rst:96 msgid "" "These objects also support being used in a :keyword:`with` statement, which " "will automatically close them when done." msgstr "" +"Estes objetos também oferecem suporte a serem usados em uma instrução :" +"keyword:`with`, que vai fechá-los automaticamente quando estiver concluída." -#: ../../library/dbm.rst:101 +#: ../../library/dbm.rst:99 msgid "" ":meth:`!get` and :meth:`!setdefault` methods are now available for all :mod:" "`dbm` backends." msgstr "" +"O métodos :meth:`!get` e :meth:`!setdefault` estão agora disponíveis para " +"todos os backends do :mod:`dbm`." -#: ../../library/dbm.rst:105 +#: ../../library/dbm.rst:103 msgid "" "Added native support for the context management protocol to the objects " "returned by :func:`~dbm.open`." msgstr "" +"Adicionado suporte nativo para o protocolo de gerenciamento de contexto para " +"os objetos retornados por :func:`~dbm.open`." -#: ../../library/dbm.rst:109 +#: ../../library/dbm.rst:107 msgid "" "Deleting a key from a read-only database raises a database module specific " "exception instead of :exc:`KeyError`." msgstr "" +"Excluir uma chave de um banco de dados somente leitura levanta uma exceção " +"de banco de dados específica do módulo em vez de :exc:`KeyError`." -#: ../../library/dbm.rst:113 +#: ../../library/dbm.rst:111 msgid "" "The following example records some hostnames and a corresponding title, and " "then prints out the contents of the database::" msgstr "" - -#: ../../library/dbm.rst:143 +"Os seguintes exemplos registram alguns hostnames e um título correspondente, " +"e então exibe o conteúdo do banco de dados::" + +#: ../../library/dbm.rst:114 +msgid "" +"import dbm\n" +"\n" +"# Open database, creating it if necessary.\n" +"with dbm.open('cache', 'c') as db:\n" +"\n" +" # Record some values\n" +" db[b'hello'] = b'there'\n" +" db['www.python.org'] = 'Python Website'\n" +" db['www.cnn.com'] = 'Cable News Network'\n" +"\n" +" # Note that the keys are considered bytes now.\n" +" assert db[b'www.python.org'] == b'Python Website'\n" +" # Notice how the value is now in bytes.\n" +" assert db['www.cnn.com'] == b'Cable News Network'\n" +"\n" +" # Often-used methods of the dict interface work too.\n" +" print(db.get('python.org', b'not present'))\n" +"\n" +" # Storing a non-string key or value will raise an exception (most\n" +" # likely a TypeError).\n" +" db['www.yahoo.com'] = 4\n" +"\n" +"# db is automatically closed when leaving the with statement." +msgstr "" +"import dbm\n" +"\n" +"# Abre o banco de dados, criando-o se necessário.\n" +"with dbm.open('cache', 'c') as db:\n" +"\n" +" # Registra alguns valores\n" +" db[b'hello'] = b'there'\n" +" db['www.python.org'] = 'Python Website'\n" +" db['www.cnn.com'] = 'Cable News Network'\n" +"\n" +" # Note que as chaves são consideradas bytes agora.\n" +" assert db[b'www.python.org'] == b'Python Website'\n" +" # Observe como o valor é agora em bytes.\n" +" assert db['www.cnn.com'] == b'Cable News Network'\n" +"\n" +" # Métodos geralmente usados da interface dict funcionam também.\n" +" print(db.get('python.org', b'not present'))\n" +"\n" +" # Armazenar uma chave não-string ou valor vai levantar uma exceção\n" +" # (provavelmente uma TypeError).\n" +" db['www.yahoo.com'] = 4\n" +"\n" +"# db é automaticamente fechado a sair da instrução with." + +#: ../../library/dbm.rst:141 msgid "Module :mod:`shelve`" msgstr "Módulo :mod:`shelve`" -#: ../../library/dbm.rst:144 +#: ../../library/dbm.rst:142 msgid "Persistence module which stores non-string data." -msgstr "" +msgstr "Módulo persistente que armazena dados não-string." -#: ../../library/dbm.rst:147 +#: ../../library/dbm.rst:145 msgid "The individual submodules are described in the following sections." -msgstr "" +msgstr "Os submódulos individuais são descritos nas seções a seguir." -#: ../../library/dbm.rst:150 +#: ../../library/dbm.rst:148 msgid ":mod:`dbm.sqlite3` --- SQLite backend for dbm" -msgstr "" +msgstr ":mod:`dbm.sqlite3` --- Backend de SQLite para dbm" -#: ../../library/dbm.rst:158 +#: ../../library/dbm.rst:156 msgid "**Source code:** :source:`Lib/dbm/sqlite3.py`" -msgstr "" +msgstr "**Código-fonte:** :source:`Lib/dbm/sqlite3.py`" -#: ../../library/dbm.rst:162 +#: ../../library/dbm.rst:160 msgid "" "This module uses the standard library :mod:`sqlite3` module to provide an " "SQLite backend for the :mod:`dbm` module. The files created by :mod:`dbm." "sqlite3` can thus be opened by :mod:`sqlite3`, or any other SQLite browser, " "including the SQLite CLI." msgstr "" +"Este módulo usa o módulo da biblioteca padrão :mod:`sqlite3` para fornecer " +"um backend de SQLite para o módulo :mod:`dbm`. Os arquivos criados por :mod:" +"`dbm.sqlite3` podem então ser abertos por :mod:`sqlite3` ou quaisquer outros " +"navegadores de SQLite, incluindo CLI do SQLite." + +#: ../../includes/wasm-mobile-notavail.rst:3 ../../includes/wasm-notavail.rst:3 +msgid "Availability" +msgstr "Disponibilidade" + +#: ../../includes/wasm-notavail.rst:5 +msgid "" +"This module does not work or is not available on WebAssembly. See :ref:`wasm-" +"availability` for more information." +msgstr "" +"Este módulo não funciona ou não está disponível em WebAssembly. Veja :ref:" +"`wasm-availability` para mais informações." #: ../../library/dbm.rst:169 msgid "" @@ -250,24 +342,30 @@ msgid "" "implements a :meth:`!close` method, and supports a \"closing\" context " "manager via the :keyword:`with` keyword." msgstr "" +"Abre um banco de dados de SQLite. O objeto retornado se comporta como um :" +"term:`mapeamento`, implementa um método :meth:`!close` e oferece suporte um " +"gerenciador de contexto de \"fechamento\" via a palavra reservada :keyword:" +"`with`." #: ../../library/dbm.rst:174 msgid "The path to the database to be opened." -msgstr "" +msgstr "O caminho para o banco de dados a ser aberta." #: ../../library/dbm.rst:185 msgid "" "The Unix file access mode of the file (default: octal ``0o666``), used only " "when the database has to be created." msgstr "" +"O modo de acesso a arquivos do Unix do arquivo (padrão: octal ``0o666``), " +"usado apenas quando o banco de dados tem que ser criado." #: ../../library/dbm.rst:191 msgid ":mod:`dbm.gnu` --- GNU database manager" -msgstr "" +msgstr ":mod:`dbm.gnu` --- Gerenciador de banco de dados do GNU" #: ../../library/dbm.rst:197 msgid "**Source code:** :source:`Lib/dbm/gnu.py`" -msgstr "" +msgstr "**Código-fonte:** :source:`Lib/dbm/gnu.py`" #: ../../library/dbm.rst:201 msgid "" @@ -275,25 +373,41 @@ msgid "" "dbm)` library, similar to the :mod:`dbm.ndbm` module, but with additional " "functionality like crash tolerance." msgstr "" +"O módulo :mod:`dbm.gnu` fornece uma interface para a biblioteca :abbr:`GDBM " +"(GNU dbm)`, semelhante ao módulo :mod:`dbm.ndbm`, mas com funcionalidades " +"adicionais, como tolerância a falhas." -#: ../../library/dbm.rst:207 ../../library/dbm.rst:319 +#: ../../library/dbm.rst:207 ../../library/dbm.rst:321 msgid "" "The file formats created by :mod:`dbm.gnu` and :mod:`dbm.ndbm` are " "incompatible and can not be used interchangeably." msgstr "" +"Os formatos de arquivo criados por :mod:`dbm.gnu` e :mod:`dbm.ndbm` são " +"incompatíveis e não podem ser usados de forma intercambiável." + +#: ../../includes/wasm-mobile-notavail.rst:5 +msgid "" +"This module is not supported on :ref:`mobile platforms ` or :ref:`WebAssembly platforms `." +msgstr "" +"Este módulo não tem suporte em :ref:`plataformas móveis ` ou :ref:`plataformas WebAssembly `." -#: ../../library/dbm.rst:212 +#: ../../library/dbm.rst:214 msgid "" "Raised on :mod:`dbm.gnu`-specific errors, such as I/O errors. :exc:" "`KeyError` is raised for general mapping errors like specifying an incorrect " "key." msgstr "" +"Levantada em erros específicos do :mod:`dbm.gnu`, como erros de E/S. :exc:" +"`KeyError` é levantada para erros gerais de mapeamento, como especificar uma " +"chave incorreta." -#: ../../library/dbm.rst:218 +#: ../../library/dbm.rst:220 msgid "Open a GDBM database and return a :class:`!gdbm` object." -msgstr "" +msgstr "Abre um banco de dados GDBM e retorna um objeto :class:`!gdbm`." -#: ../../library/dbm.rst:224 +#: ../../library/dbm.rst:226 msgid "" "* ``'r'`` (default): |flag_r| * ``'w'``: |flag_w| * ``'c'``: |flag_c| * " "``'n'``: |flag_n| The following additional characters may be appended to " @@ -304,72 +418,114 @@ msgid "" "versions of GDBM. See the :data:`open_flags` member for a list of supported " "flag characters." msgstr "" +"* ``'r'`` (padrão): |flag_r| * ``'w'``: |flag_w| * ``'c'``: |flag_c| * " +"``'n'``: |flag_n| Os seguintes caracteres adicionais podem ser anexados para " +"controlar como o banco de dados é aberto: * ``'f'``: Abre o banco de dados " +"no modo rápido. As gravações no banco de dados não serão sincronizadas. * " +"``'s'``: Modo sincronizado. As alterações no banco de dados serão gravadas " +"imediatamente no arquivo. * ``'u'``: Não trava o banco de dados. Nem todos " +"os sinalizadores são válidos para todas as versões do GDBM. Consulte o " +"membro :data:`open_flags` para obter uma lista de caracteres de " +"sinalizadores suportados." -#: ../../library/dbm.rst:230 +#: ../../library/dbm.rst:232 msgid "" "The following additional characters may be appended to control how the " "database is opened:" msgstr "" +"Os seguintes caracteres adicionais podem ser acrescentados para controlar " +"como o banco de dados é aberto:" -#: ../../library/dbm.rst:233 +#: ../../library/dbm.rst:235 msgid "" "``'f'``: Open the database in fast mode. Writes to the database will not be " "synchronized." msgstr "" +"``'f'``: Abre o banco de dados em modo rápido. As gravações no banco de " +"dados não serão sincronizadas." -#: ../../library/dbm.rst:235 +#: ../../library/dbm.rst:237 msgid "" "``'s'``: Synchronized mode. Changes to the database will be written " "immediately to the file." msgstr "" +"``'s'``: Modo sincronizado. Alterações no banco de dados serão gravadas " +"imediatamente no arquivo." -#: ../../library/dbm.rst:237 +#: ../../library/dbm.rst:239 msgid "``'u'``: Do not lock database." -msgstr "" +msgstr "``'u'``: Não trava o banco de dados." -#: ../../library/dbm.rst:239 +#: ../../library/dbm.rst:241 msgid "" "Not all flags are valid for all versions of GDBM. See the :data:`open_flags` " "member for a list of supported flag characters." msgstr "" +"Nem todos os sinalizadores são válidos para todas as versões do GDBM. Veja o " +"membro :data:`open_flags` para uma lista de caracteres de sinalizadores " +"suportados." #: ../../library/dbm.rst:0 msgid "Raises" -msgstr "" +msgstr "Levanta" -#: ../../library/dbm.rst:245 +#: ../../library/dbm.rst:247 msgid "If an invalid *flag* argument is passed." -msgstr "" +msgstr "Se um argumento *flag* inválido for passado." -#: ../../library/dbm.rst:253 +#: ../../library/dbm.rst:255 msgid "" "A string of characters the *flag* parameter of :meth:`~dbm.gnu.open` " "supports." msgstr "" +"Uma sequência de caracteres que o parâmetro *flag* de :meth:`~dbm.gnu.open` " +"suporta." -#: ../../library/dbm.rst:255 +#: ../../library/dbm.rst:257 msgid "" ":class:`!gdbm` objects behave similar to :term:`mappings `, but :" "meth:`!items` and :meth:`!values` methods are not supported. The following " "methods are also provided:" msgstr "" +"Os objetos :class:`!gdbm` se comportam de forma semelhante a :term:" +"`mapeamentos `, mas os métodos :meth:`!items` e :meth:`!values` não " +"são suportados. Os seguintes métodos também são fornecidos:" -#: ../../library/dbm.rst:261 +#: ../../library/dbm.rst:263 msgid "" "It's possible to loop over every key in the database using this method and " "the :meth:`nextkey` method. The traversal is ordered by GDBM's internal " "hash values, and won't be sorted by the key values. This method returns the " "starting key." msgstr "" +"É possível fazer um laço em cada chave no banco de dados usando este método " +"e o método :meth:`nextkey`. A travessia é ordenada pelos valores de hash " +"internos do GDBM e não será classificada pelos valores de chave. Este método " +"retorna a chave inicial." -#: ../../library/dbm.rst:268 +#: ../../library/dbm.rst:270 msgid "" "Returns the key that follows *key* in the traversal. The following code " "prints every key in the database ``db``, without having to create a list in " "memory that contains them all::" msgstr "" +"Retorna a chave que segue *key* na travessia. O código a seguir imprime cada " +"chave no banco de dados ``db``, sem precisar criar uma lista na memória que " +"contenha todas elas::" + +#: ../../library/dbm.rst:274 +msgid "" +"k = db.firstkey()\n" +"while k is not None:\n" +" print(k)\n" +" k = db.nextkey(k)" +msgstr "" +"k = db.firstkey()\n" +"while k is not None:\n" +" print(k)\n" +" k = db.nextkey(k)" -#: ../../library/dbm.rst:279 +#: ../../library/dbm.rst:281 msgid "" "If you have carried out a lot of deletions and would like to shrink the " "space used by the GDBM file, this routine will reorganize the database. :" @@ -377,194 +533,249 @@ msgid "" "by using this reorganization; otherwise, deleted file space will be kept and " "reused as new (key, value) pairs are added." msgstr "" +"Se você realizou muitas exclusões e gostaria de reduzir o espaço usado pelo " +"arquivo GDBM, esta rotina reorganizará o banco de dados. Objetos :class:`!" +"gdbm` não reduzirão o tamanho de um arquivo de banco de dados, exceto usando " +"esta reorganização; caso contrário, o espaço de arquivo excluído será " +"mantido e reutilizado à medida que novos pares (chave, valor) forem " +"adicionados." -#: ../../library/dbm.rst:287 +#: ../../library/dbm.rst:289 msgid "" "When the database has been opened in fast mode, this method forces any " "unwritten data to be written to the disk." msgstr "" +"Quando o banco de dados é aberto no modo rápido, esse método força a " +"gravação de todos os dados não gravados no disco." -#: ../../library/dbm.rst:292 +#: ../../library/dbm.rst:294 msgid "Close the GDBM database." -msgstr "" +msgstr "Fecha o banco de dados GDBM." -#: ../../library/dbm.rst:296 +#: ../../library/dbm.rst:298 msgid "Remove all items from the GDBM database." -msgstr "" +msgstr "Remove todos os itens do banco de dados GDBM." -#: ../../library/dbm.rst:302 +#: ../../library/dbm.rst:304 msgid ":mod:`dbm.ndbm` --- New Database Manager" -msgstr "" +msgstr ":mod:`dbm.ndbm` --- New Database Manager" -#: ../../library/dbm.rst:308 +#: ../../library/dbm.rst:310 msgid "**Source code:** :source:`Lib/dbm/ndbm.py`" -msgstr "" +msgstr "**Código-fonte:** :source:`Lib/dbm/ndbm.py`" -#: ../../library/dbm.rst:312 +#: ../../library/dbm.rst:314 msgid "" "The :mod:`dbm.ndbm` module provides an interface to the :abbr:`NDBM (New " "Database Manager)` library. This module can be used with the \"classic\" " "NDBM interface or the :abbr:`GDBM (GNU dbm)` compatibility interface." msgstr "" +"O módulo :mod:`dbm.ndbm` fornece uma interface para a biblioteca :abbr:`NDBM " +"(New Database Manager)`. Este módulo pode ser usado com a interface NDBM " +"\"clássica\" ou a interface de compatibilidade :abbr:`GDBM (GNU dbm)`." -#: ../../library/dbm.rst:324 +#: ../../library/dbm.rst:326 msgid "" "The NDBM library shipped as part of macOS has an undocumented limitation on " "the size of values, which can result in corrupted database files when " "storing values larger than this limit. Reading such corrupted files can " "result in a hard crash (segmentation fault)." msgstr "" +"A biblioteca NDBM enviada como parte do macOS tem uma limitação não " +"documentada no tamanho dos valores, o que pode resultar em arquivos de banco " +"de dados corrompidos ao armazenar valores maiores que esse limite. Ler esses " +"arquivos corrompidos pode resultar em uma falha grave (falha de segmentação)." -#: ../../library/dbm.rst:331 +#: ../../library/dbm.rst:335 msgid "" "Raised on :mod:`dbm.ndbm`-specific errors, such as I/O errors. :exc:" "`KeyError` is raised for general mapping errors like specifying an incorrect " "key." msgstr "" +"Levantada em erros específicos de :mod:`dbm.ndbm`, como erros de E/S. :exc:" +"`KeyError` é levantada para erros gerais de mapeamento, como especificar uma " +"chave incorreta." -#: ../../library/dbm.rst:337 +#: ../../library/dbm.rst:341 msgid "Name of the NDBM implementation library used." -msgstr "" +msgstr "Nome da biblioteca de implementação NDBM usada." -#: ../../library/dbm.rst:342 +#: ../../library/dbm.rst:346 msgid "Open an NDBM database and return an :class:`!ndbm` object." -msgstr "" +msgstr "Abre um banco de dados NDBM e retorna um objeto :class:`!ndbm`." -#: ../../library/dbm.rst:344 +#: ../../library/dbm.rst:348 msgid "" "The basename of the database file (without the :file:`.dir` or :file:`.pag` " "extensions)." msgstr "" +"O nome base do arquivo de banco de dados (sem as extensões :file:`.dir` ou :" +"file:`.pag`)." -#: ../../library/dbm.rst:358 +#: ../../library/dbm.rst:362 msgid "" ":class:`!ndbm` objects behave similar to :term:`mappings `, but :" "meth:`!items` and :meth:`!values` methods are not supported. The following " "methods are also provided:" msgstr "" +"Os objetos :class:`!ndbm` se comportam de forma semelhante a :term:" +"`mapeamentos `, mas os métodos :meth:`!items` e :meth:`!values` não " +"são suportados. Os seguintes métodos também são fornecidos:" -#: ../../library/dbm.rst:362 +#: ../../library/dbm.rst:366 msgid "Accepts :term:`path-like object` for filename." msgstr "Aceita um :term:`objeto caminho ou similar` como nome de arquivo." -#: ../../library/dbm.rst:367 +#: ../../library/dbm.rst:371 msgid "Close the NDBM database." -msgstr "" +msgstr "Fecha o banco de dados NDBM." -#: ../../library/dbm.rst:371 +#: ../../library/dbm.rst:375 msgid "Remove all items from the NDBM database." -msgstr "" +msgstr "Remove todos os itens do banco de dados NDBM." -#: ../../library/dbm.rst:377 +#: ../../library/dbm.rst:381 msgid ":mod:`dbm.dumb` --- Portable DBM implementation" -msgstr "" +msgstr ":mod:`dbm.dumb` --- Implementação portátil do DBM" -#: ../../library/dbm.rst:382 +#: ../../library/dbm.rst:386 msgid "**Source code:** :source:`Lib/dbm/dumb.py`" -msgstr "" +msgstr "**Código-fonte:** :source:`Lib/dbm/dumb.py`" -#: ../../library/dbm.rst:388 +#: ../../library/dbm.rst:392 msgid "" "The :mod:`dbm.dumb` module is intended as a last resort fallback for the :" "mod:`dbm` module when a more robust module is not available. The :mod:`dbm." "dumb` module is not written for speed and is not nearly as heavily used as " "the other database modules." msgstr "" +"O módulo :mod:`dbm.dumb` é pensado como um último recurso alternativo para o " +"módulo :mod:`dbm` quando um módulo mais robusto não está disponível. O " +"módulo :mod:`dbm.dumb` não é escrito para velocidade e não é tão usado " +"quanto os outros módulos de banco de dados." -#: ../../library/dbm.rst:395 +#: ../../library/dbm.rst:399 msgid "" "The :mod:`dbm.dumb` module provides a persistent :class:`dict`-like " "interface which is written entirely in Python. Unlike other :mod:`dbm` " "backends, such as :mod:`dbm.gnu`, no external library is required." msgstr "" +"O módulo :mod:`dbm.dumb` fornece uma interface persistente do tipo :class:" +"`dict` que é escrita inteiramente em Python. Ao contrário de outros " +"backends :mod:`dbm`, como :mod:`dbm.gnu`, nenhuma biblioteca externa é " +"necessária." -#: ../../library/dbm.rst:400 +#: ../../library/dbm.rst:404 msgid "The :mod:`!dbm.dumb` module defines the following:" -msgstr "" +msgstr "O módulo :mod:`!dbm.dumb` define o seguinte:" -#: ../../library/dbm.rst:404 +#: ../../library/dbm.rst:408 msgid "" "Raised on :mod:`dbm.dumb`-specific errors, such as I/O errors. :exc:" "`KeyError` is raised for general mapping errors like specifying an incorrect " "key." msgstr "" +"Levantada em erros específicos de :mod:`dbm.dumb`, como erros de E/S. :exc:" +"`KeyError` é levantada para erros gerais de mapeamento, como especificar uma " +"chave incorreta." -#: ../../library/dbm.rst:410 +#: ../../library/dbm.rst:414 msgid "" "Open a :mod:`!dbm.dumb` database. The returned database object behaves " "similar to a :term:`mapping`, in addition to providing :meth:`~dumbdbm.sync` " "and :meth:`~dumbdbm.close` methods." msgstr "" +"Abre um banco de dados :mod:`!dbm.dumb`. O objeto banco de dados retornado " +"se comporta de forma semelhante a um :term:`mapeamento`, além de fornecer os " +"métodos :meth:`~dumbdbm.sync` e :meth:`~dumbdbm.close`." -#: ../../library/dbm.rst:415 +#: ../../library/dbm.rst:419 msgid "" "The basename of the database file (without extensions). A new database " "creates the following files: - :file:`{filename}.dat` - :file:`{filename}." "dir`" msgstr "" +"O nome base do arquivo do banco de dados (sem extensões). Um novo banco de " +"dados cria os seguintes arquivos: - :file:`{filename}.dat` - :file:" +"`{filename}.dir`" -#: ../../library/dbm.rst:416 +#: ../../library/dbm.rst:420 msgid "" "The basename of the database file (without extensions). A new database " "creates the following files:" msgstr "" +"O nome base do arquivo do banco de dados (sem extensões). Um novo banco de " +"dados cria os seguintes arquivos:" -#: ../../library/dbm.rst:419 +#: ../../library/dbm.rst:423 msgid ":file:`{filename}.dat`" -msgstr "" +msgstr ":file:`{filename}.dat`" -#: ../../library/dbm.rst:420 +#: ../../library/dbm.rst:424 msgid ":file:`{filename}.dir`" -msgstr "" +msgstr ":file:`{filename}.dir`" -#: ../../library/dbm.rst:423 +#: ../../library/dbm.rst:427 msgid "" "* ``'r'``: |flag_r| * ``'w'``: |flag_w| * ``'c'`` (default): |flag_c| * " "``'n'``: |flag_n|" msgstr "" +"* ``'r'``: |flag_r| * ``'w'``: |flag_w| * ``'c'`` (padrão): |flag_c| * " +"``'n'``: |flag_n|" -#: ../../library/dbm.rst:424 +#: ../../library/dbm.rst:428 msgid "``'r'``: |flag_r|" -msgstr "" +msgstr "``'r'``: |flag_r|" -#: ../../library/dbm.rst:426 +#: ../../library/dbm.rst:430 msgid "``'c'`` (default): |flag_c|" -msgstr "" +msgstr "``'c'`` (padrão): |flag_c|" -#: ../../library/dbm.rst:433 +#: ../../library/dbm.rst:437 msgid "" "It is possible to crash the Python interpreter when loading a database with " "a sufficiently large/complex entry due to stack depth limitations in " "Python's AST compiler." msgstr "" +"É possível travar o interpretador Python ao carregar um banco de dados com " +"uma entrada suficientemente grande/complexa devido a limitações de " +"profundidade de pilha no compilador AST do Python." -#: ../../library/dbm.rst:437 +#: ../../library/dbm.rst:441 msgid "" ":func:`~dbm.dumb.open` always creates a new database when *flag* is ``'n'``." msgstr "" +":func:`~dbm.dumb.open` sempre cria um novo banco de dados quando *flag* é " +"``'n'``." -#: ../../library/dbm.rst:440 +#: ../../library/dbm.rst:444 msgid "" "A database opened read-only if *flag* is ``'r'``. A database is not created " "if it does not exist if *flag* is ``'r'`` or ``'w'``." msgstr "" +"Um banco de dados aberto somente leitura se *flag* for ``'r'``. Um banco de " +"dados não é criado se não existir se *flag* for ``'r'`` ou ``'w'``." -#: ../../library/dbm.rst:447 +#: ../../library/dbm.rst:451 msgid "" "In addition to the methods provided by the :class:`collections.abc." "MutableMapping` class, the following methods are provided:" msgstr "" +"Além dos métodos fornecidos pela classe :class:`collections.abc." +"MutableMapping`, os seguintes métodos são fornecidos:" -#: ../../library/dbm.rst:453 +#: ../../library/dbm.rst:457 msgid "" "Synchronize the on-disk directory and data files. This method is called by " -"the :meth:`Shelve.sync` method." +"the :meth:`shelve.Shelf.sync` method." msgstr "" +"Sincroniza o diretório no disco e os arquivos de dados. Este método é " +"chamado pelo método :meth:`shelve.Shelf.sync`." -#: ../../library/dbm.rst:458 +#: ../../library/dbm.rst:462 msgid "Close the database." -msgstr "" +msgstr "Fecha o banco de dados." -#: ../../library/dbm.rst:384 +#: ../../library/dbm.rst:388 msgid "databases" -msgstr "" +msgstr "bancos de dados" diff --git a/library/debug.po b/library/debug.po index fb948bd30..87e84d32c 100644 --- a/library/debug.po +++ b/library/debug.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Hildeberto Abreu Magalhães , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:04+0000\n" -"Last-Translator: Hildeberto Abreu Magalhães , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/decimal.po b/library/decimal.po index 703ebbb05..4f64a30c2 100644 --- a/library/decimal.po +++ b/library/decimal.po @@ -1,29 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Vitor Buxbaum Orlandi, 2023 -# Claudio Rogerio Carvalho Filho , 2024 -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 01:04+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -220,8 +216,8 @@ msgstr "" "Arithmetic Specification `_." #: ../../library/decimal.rst:125 -msgid "Quick-start Tutorial" -msgstr "Tutorial de início rápido" +msgid "Quick-start tutorial" +msgstr "" #: ../../library/decimal.rst:127 msgid "" @@ -233,6 +229,24 @@ msgstr "" "atual com :func:`getcontext` e, se necessário, definir novos valores para " "precisão, arredondamento ou armadilhas ativados::" +#: ../../library/decimal.rst:131 +msgid "" +">>> from decimal import *\n" +">>> getcontext()\n" +"Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,\n" +" capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,\n" +" InvalidOperation])\n" +"\n" +">>> getcontext().prec = 7 # Set a new precision" +msgstr "" +">>> from decimal import *\n" +">>> getcontext()\n" +"Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,\n" +" capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,\n" +" InvalidOperation])\n" +"\n" +">>> getcontext().prec = 7 # Define uma nova precisão" + #: ../../library/decimal.rst:139 msgid "" "Decimal instances can be constructed from integers, strings, floats, or " @@ -248,6 +262,44 @@ msgstr "" "como ``NaN``, que significa \"Não é um número\", ``Infinity`` positivo e " "negativo e ``-0``::" +#: ../../library/decimal.rst:145 +msgid "" +">>> getcontext().prec = 28\n" +">>> Decimal(10)\n" +"Decimal('10')\n" +">>> Decimal('3.14')\n" +"Decimal('3.14')\n" +">>> Decimal(3.14)\n" +"Decimal('3.140000000000000124344978758017532527446746826171875')\n" +">>> Decimal((0, (3, 1, 4), -2))\n" +"Decimal('3.14')\n" +">>> Decimal(str(2.0 ** 0.5))\n" +"Decimal('1.4142135623730951')\n" +">>> Decimal(2) ** Decimal('0.5')\n" +"Decimal('1.414213562373095048801688724')\n" +">>> Decimal('NaN')\n" +"Decimal('NaN')\n" +">>> Decimal('-Infinity')\n" +"Decimal('-Infinity')" +msgstr "" +">>> getcontext().prec = 28\n" +">>> Decimal(10)\n" +"Decimal('10')\n" +">>> Decimal('3.14')\n" +"Decimal('3.14')\n" +">>> Decimal(3.14)\n" +"Decimal('3.140000000000000124344978758017532527446746826171875')\n" +">>> Decimal((0, (3, 1, 4), -2))\n" +"Decimal('3.14')\n" +">>> Decimal(str(2.0 ** 0.5))\n" +"Decimal('1.4142135623730951')\n" +">>> Decimal(2) ** Decimal('0.5')\n" +"Decimal('1.414213562373095048801688724')\n" +">>> Decimal('NaN')\n" +"Decimal('NaN')\n" +">>> Decimal('-Infinity')\n" +"Decimal('-Infinity')" + #: ../../library/decimal.rst:163 msgid "" "If the :exc:`FloatOperation` signal is trapped, accidental mixing of " @@ -258,6 +310,34 @@ msgstr "" "acidental de decimais e pontos flutuantes em construtores ou comparações de " "ordenação levanta uma exceção::" +#: ../../library/decimal.rst:167 +msgid "" +">>> c = getcontext()\n" +">>> c.traps[FloatOperation] = True\n" +">>> Decimal(3.14)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"decimal.FloatOperation: []\n" +">>> Decimal('3.5') < 3.7\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"decimal.FloatOperation: []\n" +">>> Decimal('3.5') == 3.5\n" +"True" +msgstr "" +">>> c = getcontext()\n" +">>> c.traps[FloatOperation] = True\n" +">>> Decimal(3.14)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"decimal.FloatOperation: []\n" +">>> Decimal('3.5') < 3.7\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"decimal.FloatOperation: []\n" +">>> Decimal('3.5') == 3.5\n" +"True" + #: ../../library/decimal.rst:182 msgid "" "The significance of a new Decimal is determined solely by the number of " @@ -268,6 +348,30 @@ msgstr "" "inseridos. A precisão e o arredondamento do contexto só entram em jogo " "durante operações aritméticas." +#: ../../library/decimal.rst:186 +msgid "" +">>> getcontext().prec = 6\n" +">>> Decimal('3.0')\n" +"Decimal('3.0')\n" +">>> Decimal('3.1415926535')\n" +"Decimal('3.1415926535')\n" +">>> Decimal('3.1415926535') + Decimal('2.7182818285')\n" +"Decimal('5.85987')\n" +">>> getcontext().rounding = ROUND_UP\n" +">>> Decimal('3.1415926535') + Decimal('2.7182818285')\n" +"Decimal('5.85988')" +msgstr "" +">>> getcontext().prec = 6\n" +">>> Decimal('3.0')\n" +"Decimal('3.0')\n" +">>> Decimal('3.1415926535')\n" +"Decimal('3.1415926535')\n" +">>> Decimal('3.1415926535') + Decimal('2.7182818285')\n" +"Decimal('5.85987')\n" +">>> getcontext().rounding = ROUND_UP\n" +">>> Decimal('3.1415926535') + Decimal('2.7182818285')\n" +"Decimal('5.85988')" + #: ../../library/decimal.rst:199 msgid "" "If the internal limits of the C version are exceeded, constructing a decimal " @@ -276,6 +380,18 @@ msgstr "" "Se os limites internos da versão C forem excedidos, a construção de um " "decimal levanta :class:`InvalidOperation`::" +#: ../../library/decimal.rst:202 +msgid "" +">>> Decimal(\"1e9999999999999999999\")\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"decimal.InvalidOperation: []" +msgstr "" +">>> Decimal(\"1e9999999999999999999\")\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"decimal.InvalidOperation: []" + #: ../../library/decimal.rst:209 msgid "" "Decimals interact well with much of the rest of Python. Here is a small " @@ -284,6 +400,60 @@ msgstr "" "Os decimais interagem bem com grande parte do resto do Python. Aqui está um " "pequeno circo voador de ponto flutuante decimal:" +#: ../../library/decimal.rst:212 +msgid "" +">>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))\n" +">>> max(data)\n" +"Decimal('9.25')\n" +">>> min(data)\n" +"Decimal('0.03')\n" +">>> sorted(data)\n" +"[Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),\n" +" Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]\n" +">>> sum(data)\n" +"Decimal('19.29')\n" +">>> a,b,c = data[:3]\n" +">>> str(a)\n" +"'1.34'\n" +">>> float(a)\n" +"1.34\n" +">>> round(a, 1)\n" +"Decimal('1.3')\n" +">>> int(a)\n" +"1\n" +">>> a * 5\n" +"Decimal('6.70')\n" +">>> a * b\n" +"Decimal('2.5058')\n" +">>> c % a\n" +"Decimal('0.77')" +msgstr "" +">>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))\n" +">>> max(data)\n" +"Decimal('9.25')\n" +">>> min(data)\n" +"Decimal('0.03')\n" +">>> sorted(data)\n" +"[Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),\n" +" Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]\n" +">>> sum(data)\n" +"Decimal('19.29')\n" +">>> a,b,c = data[:3]\n" +">>> str(a)\n" +"'1.34'\n" +">>> float(a)\n" +"1.34\n" +">>> round(a, 1)\n" +"Decimal('1.3')\n" +">>> int(a)\n" +"1\n" +">>> a * 5\n" +"Decimal('6.70')\n" +">>> a * b\n" +"Decimal('2.5058')\n" +">>> c % a\n" +"Decimal('0.77')" + #: ../../library/decimal.rst:241 msgid "And some mathematical functions are also available to Decimal:" msgstr "E algumas funções matemáticas também estão disponíveis no Decimal:" @@ -330,6 +500,50 @@ msgstr "" "primeiro é especialmente útil para depuração porque muitas das armadilhas " "estão ativadas:" +#: ../../library/decimal.rst:275 +msgid "" +">>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)\n" +">>> setcontext(myothercontext)\n" +">>> Decimal(1) / Decimal(7)\n" +"Decimal('0.142857142857142857142857142857142857142857142857142857142857')\n" +"\n" +">>> ExtendedContext\n" +"Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,\n" +" capitals=1, clamp=0, flags=[], traps=[])\n" +">>> setcontext(ExtendedContext)\n" +">>> Decimal(1) / Decimal(7)\n" +"Decimal('0.142857143')\n" +">>> Decimal(42) / Decimal(0)\n" +"Decimal('Infinity')\n" +"\n" +">>> setcontext(BasicContext)\n" +">>> Decimal(42) / Decimal(0)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in -toplevel-\n" +" Decimal(42) / Decimal(0)\n" +"DivisionByZero: x / 0" +msgstr "" +">>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)\n" +">>> setcontext(myothercontext)\n" +">>> Decimal(1) / Decimal(7)\n" +"Decimal('0.142857142857142857142857142857142857142857142857142857142857')\n" +"\n" +">>> ExtendedContext\n" +"Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,\n" +" capitals=1, clamp=0, flags=[], traps=[])\n" +">>> setcontext(ExtendedContext)\n" +">>> Decimal(1) / Decimal(7)\n" +"Decimal('0.142857143')\n" +">>> Decimal(42) / Decimal(0)\n" +"Decimal('Infinity')\n" +"\n" +">>> setcontext(BasicContext)\n" +">>> Decimal(42) / Decimal(0)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in -toplevel-\n" +" Decimal(42) / Decimal(0)\n" +"DivisionByZero: x / 0" + #: ../../library/decimal.rst:299 msgid "" "Contexts also have signal flags for monitoring exceptional conditions " @@ -343,6 +557,24 @@ msgstr "" "sinalizadores antes de cada conjunto de cálculos monitorados usando o " "método :meth:`~Context.clear_flags`. ::" +#: ../../library/decimal.rst:304 +msgid "" +">>> setcontext(ExtendedContext)\n" +">>> getcontext().clear_flags()\n" +">>> Decimal(355) / Decimal(113)\n" +"Decimal('3.14159292')\n" +">>> getcontext()\n" +"Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,\n" +" capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])" +msgstr "" +">>> setcontext(ExtendedContext)\n" +">>> getcontext().clear_flags()\n" +">>> Decimal(355) / Decimal(113)\n" +"Decimal('3.14159292')\n" +">>> getcontext()\n" +"Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,\n" +" capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])" + #: ../../library/decimal.rst:312 msgid "" "The *flags* entry shows that the rational approximation to pi was rounded " @@ -361,6 +593,28 @@ msgstr "" "As armadilhas individuais são definidas usando o dicionário no atributo :" "attr:`~Context.traps` de um contexto:" +#: ../../library/decimal.rst:319 +msgid "" +">>> setcontext(ExtendedContext)\n" +">>> Decimal(1) / Decimal(0)\n" +"Decimal('Infinity')\n" +">>> getcontext().traps[DivisionByZero] = 1\n" +">>> Decimal(1) / Decimal(0)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in -toplevel-\n" +" Decimal(1) / Decimal(0)\n" +"DivisionByZero: x / 0" +msgstr "" +">>> setcontext(ExtendedContext)\n" +">>> Decimal(1) / Decimal(0)\n" +"Decimal('Infinity')\n" +">>> getcontext().traps[DivisionByZero] = 1\n" +">>> Decimal(1) / Decimal(0)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in -toplevel-\n" +" Decimal(1) / Decimal(0)\n" +"DivisionByZero: x / 0" + #: ../../library/decimal.rst:331 msgid "" "Most programs adjust the current context only once, at the beginning of the " @@ -398,19 +652,49 @@ msgstr "" "espaço em branco à esquerda e à direita, bem como sublinhados em toda parte, " "serem removidos::" +#: ../../library/decimal.rst:355 +msgid "" +"sign ::= '+' | '-'\n" +"digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | " +"'9'\n" +"indicator ::= 'e' | 'E'\n" +"digits ::= digit [digit]...\n" +"decimal-part ::= digits '.' [digits] | ['.'] digits\n" +"exponent-part ::= indicator [sign] digits\n" +"infinity ::= 'Infinity' | 'Inf'\n" +"nan ::= 'NaN' [digits] | 'sNaN' [digits]\n" +"numeric-value ::= decimal-part [exponent-part] | infinity\n" +"numeric-string ::= [sign] numeric-value | [sign] nan" +msgstr "" +"sign ::= '+' | '-'\n" +"digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | " +"'9'\n" +"indicator ::= 'e' | 'E'\n" +"digits ::= digit [digit]...\n" +"decimal-part ::= digits '.' [digits] | ['.'] digits\n" +"exponent-part ::= indicator [sign] digits\n" +"infinity ::= 'Infinity' | 'Inf'\n" +"nan ::= 'NaN' [digits] | 'sNaN' [digits]\n" +"numeric-value ::= decimal-part [exponent-part] | infinity\n" +"numeric-string ::= [sign] numeric-value | [sign] nan" + #: ../../library/decimal.rst:366 msgid "" "Other Unicode decimal digits are also permitted where ``digit`` appears " "above. These include decimal digits from various other alphabets (for " "example, Arabic-Indic and Devanāgarī digits) along with the fullwidth digits " -"``'\\uff10'`` through ``'\\uff19'``." +"``'\\uff10'`` through ``'\\uff19'``. Case is not significant, so, for " +"example, ``inf``, ``Inf``, ``INFINITY``, and ``iNfINity`` are all acceptable " +"spellings for positive infinity." msgstr "" "Outros dígitos decimais Unicode também são permitidos onde ``digit`` aparece " "acima. Isso inclui dígitos decimais de vários outros alfabetos (por exemplo, " "dígitos em árabes-índicos e devanágaris), além dos dígitos de largura total " -"``'\\uff10'`` a ``'\\uff19'``." +"``'\\uff10'`` a ``'\\uff19'``. A capitalização não é significativa, então, " +"por exemplo, ``inf``, ``Inf``, ``INFINITY`` e ``iNfINity`` são todas grafias " +"aceitáveis ​​para infinito positivo." -#: ../../library/decimal.rst:371 +#: ../../library/decimal.rst:373 msgid "" "If *value* is a :class:`tuple`, it should have three components, a sign " "(``0`` for positive or ``1`` for negative), a :class:`tuple` of digits, and " @@ -422,7 +706,7 @@ msgstr "" "um expoente inteiro. Por exemplo, ``Decimal((0, (1, 4, 1, 4), -3))`` returna " "``Decimal('1.414')``." -#: ../../library/decimal.rst:376 +#: ../../library/decimal.rst:378 msgid "" "If *value* is a :class:`float`, the binary floating-point value is " "losslessly converted to its exact decimal equivalent. This conversion can " @@ -436,7 +720,7 @@ msgstr "" "``Decimal(float('1.1'))`` converte para " "``Decimal('1.100000000000000088817841970012523233890533447265625')``." -#: ../../library/decimal.rst:382 +#: ../../library/decimal.rst:384 msgid "" "The *context* precision does not affect how many digits are stored. That is " "determined exclusively by the number of digits in *value*. For example, " @@ -448,7 +732,7 @@ msgstr "" "``Decimal('3.00000')`` registra todos os cinco zeros, mesmo que a precisão " "do contexto seja apenas três." -#: ../../library/decimal.rst:387 +#: ../../library/decimal.rst:389 msgid "" "The purpose of the *context* argument is determining what to do if *value* " "is a malformed string. If the context traps :const:`InvalidOperation`, an " @@ -460,18 +744,18 @@ msgstr "" "exceção será levantada; caso contrário, o construtor retornará um novo " "decimal com o valor de ``NaN``." -#: ../../library/decimal.rst:392 +#: ../../library/decimal.rst:394 msgid "Once constructed, :class:`Decimal` objects are immutable." msgstr "Uma vez construídos, objetos de :class:`Decimal` são imutáveis." -#: ../../library/decimal.rst:394 +#: ../../library/decimal.rst:396 msgid "" "The argument to the constructor is now permitted to be a :class:`float` " "instance." msgstr "" "O argumento para o construtor agora pode ser uma instância de :class:`float`." -#: ../../library/decimal.rst:398 +#: ../../library/decimal.rst:400 msgid "" ":class:`float` arguments raise an exception if the :exc:`FloatOperation` " "trap is set. By default the trap is off." @@ -479,7 +763,7 @@ msgstr "" "Os argumentos de :class:`float` levantam uma exceção se a armadilha :exc:" "`FloatOperation` estiver definida. Por padrão, a armadilha está desativada." -#: ../../library/decimal.rst:402 +#: ../../library/decimal.rst:404 msgid "" "Underscores are allowed for grouping, as with integral and floating-point " "literals in code." @@ -487,7 +771,7 @@ msgstr "" "Sublinhados são permitidos para agrupamento, como nos literais de ponto " "flutuante e integral no código." -#: ../../library/decimal.rst:406 +#: ../../library/decimal.rst:408 msgid "" "Decimal floating-point objects share many properties with the other built-in " "numeric types such as :class:`float` and :class:`int`. All of the usual " @@ -504,7 +788,7 @@ msgstr "" "classificados e convertidos a outro tipo (como :class:`float` ou :class:" "`int`)." -#: ../../library/decimal.rst:413 +#: ../../library/decimal.rst:415 msgid "" "There are some small differences between arithmetic on Decimal objects and " "arithmetic on integers and floats. When the remainder operator ``%`` is " @@ -516,7 +800,19 @@ msgstr "" "``%`` é aplicado a objetos decimais, o sinal do resultado é o sinal do " "*dividend* em vez do sinal do divisor::" -#: ../../library/decimal.rst:423 +#: ../../library/decimal.rst:420 +msgid "" +">>> (-7) % 4\n" +"1\n" +">>> Decimal(-7) % Decimal(4)\n" +"Decimal('-3')" +msgstr "" +">>> (-7) % 4\n" +"1\n" +">>> Decimal(-7) % Decimal(4)\n" +"Decimal('-3')" + +#: ../../library/decimal.rst:425 msgid "" "The integer division operator ``//`` behaves analogously, returning the " "integer part of the true quotient (truncating towards zero) rather than its " @@ -527,7 +823,19 @@ msgstr "" "zero) em vez de seu resto, de modo a preservar a identidade usual ``x == " "(x // y) * y + x % y``::" -#: ../../library/decimal.rst:432 +#: ../../library/decimal.rst:429 +msgid "" +">>> -7 // 4\n" +"-2\n" +">>> Decimal(-7) // Decimal(4)\n" +"Decimal('-1')" +msgstr "" +">>> -7 // 4\n" +"-2\n" +">>> Decimal(-7) // Decimal(4)\n" +"Decimal('-1')" + +#: ../../library/decimal.rst:434 msgid "" "The ``%`` and ``//`` operators implement the ``remainder`` and ``divide-" "integer`` operations (respectively) as described in the specification." @@ -535,7 +843,7 @@ msgstr "" "Os operadores ``%`` e ``//`` implementam as operações de ``remainder`` e " "``divide-integer`` (respectivamente) como descrito na especificação." -#: ../../library/decimal.rst:436 +#: ../../library/decimal.rst:438 msgid "" "Decimal objects cannot generally be combined with floats or instances of :" "class:`fractions.Fraction` in arithmetic operations: an attempt to add a :" @@ -553,7 +861,7 @@ msgstr "" "``x`` com outro número ``y``. Isso evita resultados confusos ao fazer " "comparações de igualdade entre números de tipos diferentes." -#: ../../library/decimal.rst:444 +#: ../../library/decimal.rst:446 msgid "" "Mixed-type comparisons between :class:`Decimal` instances and other numeric " "types are now fully supported." @@ -561,7 +869,7 @@ msgstr "" "As comparações de tipos mistos entre instâncias de :class:`Decimal` e outros " "tipos numéricos agora são totalmente suportadas." -#: ../../library/decimal.rst:448 +#: ../../library/decimal.rst:450 msgid "" "In addition to the standard numeric properties, decimal floating-point " "objects also have a number of specialized methods:" @@ -569,7 +877,7 @@ msgstr "" "Além das propriedades numéricas padrões, os objetos de ponto flutuante " "decimal também possuem vários métodos especializados:" -#: ../../library/decimal.rst:454 +#: ../../library/decimal.rst:456 msgid "" "Return the adjusted exponent after shifting out the coefficient's rightmost " "digits until only the lead digit remains: ``Decimal('321e+5').adjusted()`` " @@ -581,7 +889,7 @@ msgstr "" "adjusted()`` retorna sete. Usado para determinar a posição do dígito mais " "significativo em relação ao ponto decimal." -#: ../../library/decimal.rst:461 +#: ../../library/decimal.rst:463 msgid "" "Return a pair ``(n, d)`` of integers that represent the given :class:" "`Decimal` instance as a fraction, in lowest terms and with a positive " @@ -591,14 +899,22 @@ msgstr "" "dada :class:`Decimal` como uma fração, nos termos mais baixos e com um " "denominador positivo::" -#: ../../library/decimal.rst:468 +#: ../../library/decimal.rst:467 +msgid "" +">>> Decimal('-3.14').as_integer_ratio()\n" +"(-157, 50)" +msgstr "" +">>> Decimal('-3.14').as_integer_ratio()\n" +"(-157, 50)" + +#: ../../library/decimal.rst:470 msgid "" "The conversion is exact. Raise OverflowError on infinities and ValueError " "on NaNs." msgstr "" "A conversão é exata. Levanta OverflowError em infinitos e ValueError em NaNs." -#: ../../library/decimal.rst:475 +#: ../../library/decimal.rst:477 msgid "" "Return a :term:`named tuple` representation of the number: " "``DecimalTuple(sign, digits, exponent)``." @@ -606,7 +922,7 @@ msgstr "" "Retorna uma representação de :term:`tupla nomeada ` do número: " "``DecimalTuple(sign, digits, exponent)``." -#: ../../library/decimal.rst:481 +#: ../../library/decimal.rst:483 msgid "" "Return the canonical encoding of the argument. Currently, the encoding of " "a :class:`Decimal` instance is always canonical, so this operation returns " @@ -616,7 +932,7 @@ msgstr "" "uma instância de :class:`Decimal` é sempre canônica, portanto, esta operação " "retorna seu argumento inalterado." -#: ../../library/decimal.rst:487 +#: ../../library/decimal.rst:489 msgid "" "Compare the values of two Decimal instances. :meth:`compare` returns a " "Decimal instance, and if either operand is a NaN then the result is a NaN::" @@ -625,7 +941,19 @@ msgstr "" "instância decimal, e se qualquer operando for um NaN, o resultado será um " "NaN::" -#: ../../library/decimal.rst:498 +#: ../../library/decimal.rst:493 +msgid "" +"a or b is a NaN ==> Decimal('NaN')\n" +"a < b ==> Decimal('-1')\n" +"a == b ==> Decimal('0')\n" +"a > b ==> Decimal('1')" +msgstr "" +"a or b is a NaN ==> Decimal('NaN')\n" +"a < b ==> Decimal('-1')\n" +"a == b ==> Decimal('0')\n" +"a > b ==> Decimal('1')" + +#: ../../library/decimal.rst:500 msgid "" "This operation is identical to the :meth:`compare` method, except that all " "NaNs signal. That is, if neither operand is a signaling NaN then any quiet " @@ -635,7 +963,7 @@ msgstr "" "sinalizam. Ou seja, se nenhum operando for um NaN sinalizador, qualquer " "operando NaN silencioso será tratado como se fosse um NaN sinalizador." -#: ../../library/decimal.rst:504 +#: ../../library/decimal.rst:506 msgid "" "Compare two operands using their abstract representation rather than their " "numerical value. Similar to the :meth:`compare` method, but the result " @@ -649,7 +977,7 @@ msgstr "" "`Decimal` com o mesmo valor numérico, mas diferentes representações, se " "comparam desiguais nesta ordem:" -#: ../../library/decimal.rst:513 +#: ../../library/decimal.rst:515 msgid "" "Quiet and signaling NaNs are also included in the total ordering. The " "result of this function is ``Decimal('0')`` if both operands have the same " @@ -665,8 +993,8 @@ msgstr "" "maior na ordem total que o segundo operando. Veja a especificação para " "detalhes da ordem total." -#: ../../library/decimal.rst:520 ../../library/decimal.rst:531 -#: ../../library/decimal.rst:559 ../../library/decimal.rst:846 +#: ../../library/decimal.rst:522 ../../library/decimal.rst:533 +#: ../../library/decimal.rst:561 ../../library/decimal.rst:848 msgid "" "This operation is unaffected by context and is quiet: no flags are changed " "and no rounding is performed. As an exception, the C version may raise " @@ -677,7 +1005,7 @@ msgstr "" "pode levantar InvalidOperation se o segundo operando não puder ser " "convertido exatamente." -#: ../../library/decimal.rst:526 +#: ../../library/decimal.rst:528 msgid "" "Compare two operands using their abstract representation rather than their " "value as in :meth:`compare_total`, but ignoring the sign of each operand. " @@ -689,7 +1017,7 @@ msgstr "" "operando. ``x.compare_total_mag(y)`` é equivalente a ``x.copy_abs()." "compare_total(y.copy_abs())``." -#: ../../library/decimal.rst:537 +#: ../../library/decimal.rst:539 msgid "" "Just returns self, this method is only to comply with the Decimal " "Specification." @@ -697,7 +1025,7 @@ msgstr "" "Apenas retorna a si próprio, sendo esse método apenas para atender à " "Especificação de Decimal." -#: ../../library/decimal.rst:542 +#: ../../library/decimal.rst:544 msgid "" "Return the absolute value of the argument. This operation is unaffected by " "the context and is quiet: no flags are changed and no rounding is performed." @@ -706,7 +1034,7 @@ msgstr "" "contexto e é silenciosa: nenhum sinalizador é alterado e nenhum " "arredondamento é executado." -#: ../../library/decimal.rst:548 +#: ../../library/decimal.rst:550 msgid "" "Return the negation of the argument. This operation is unaffected by the " "context and is quiet: no flags are changed and no rounding is performed." @@ -715,7 +1043,7 @@ msgstr "" "é silenciosa: nenhum sinalizador é alterado e nenhum arredondamento é " "executado." -#: ../../library/decimal.rst:553 +#: ../../library/decimal.rst:555 msgid "" "Return a copy of the first operand with the sign set to be the same as the " "sign of the second operand. For example:" @@ -723,7 +1051,7 @@ msgstr "" "Retorna uma cópia do primeiro operando com o sinal definido para ser o mesmo " "que o sinal do segundo operando. Por exemplo:" -#: ../../library/decimal.rst:565 +#: ../../library/decimal.rst:567 msgid "" "Return the value of the (natural) exponential function ``e**x`` at the given " "number. The result is correctly rounded using the :const:`ROUND_HALF_EVEN` " @@ -733,7 +1061,7 @@ msgstr "" "especificado. O resultado é arredondado corretamente usando o modo de " "arredondamento :const:`ROUND_HALF_EVEN`." -#: ../../library/decimal.rst:576 +#: ../../library/decimal.rst:578 msgid "" "Alternative constructor that only accepts instances of :class:`float` or :" "class:`int`." @@ -741,7 +1069,7 @@ msgstr "" "Construtor alternativo que aceita apenas instâncias de :class:`float` ou :" "class:`int`." -#: ../../library/decimal.rst:579 +#: ../../library/decimal.rst:581 msgid "" "Note ``Decimal.from_float(0.1)`` is not the same as ``Decimal('0.1')``. " "Since 0.1 is not exactly representable in binary floating point, the value " @@ -755,7 +1083,7 @@ msgstr "" "próximo que é ``0x1.999999999999ap-4``.; Esse valor equivalente em decimal é " "``0.1000000000000000055511151231257827021181583404541015625``." -#: ../../library/decimal.rst:585 +#: ../../library/decimal.rst:587 msgid "" "From Python 3.2 onwards, a :class:`Decimal` instance can also be constructed " "directly from a :class:`float`." @@ -763,7 +1091,27 @@ msgstr "" "A partir do Python 3.2 em diante, uma instância de :class:`Decimal` também " "pode ser construída diretamente a partir de um :class:`float`." -#: ../../library/decimal.rst:603 +#: ../../library/decimal.rst:590 +msgid "" +">>> Decimal.from_float(0.1)\n" +"Decimal('0.1000000000000000055511151231257827021181583404541015625')\n" +">>> Decimal.from_float(float('nan'))\n" +"Decimal('NaN')\n" +">>> Decimal.from_float(float('inf'))\n" +"Decimal('Infinity')\n" +">>> Decimal.from_float(float('-inf'))\n" +"Decimal('-Infinity')" +msgstr "" +">>> Decimal.from_float(0.1)\n" +"Decimal('0.1000000000000000055511151231257827021181583404541015625')\n" +">>> Decimal.from_float(float('nan'))\n" +"Decimal('NaN')\n" +">>> Decimal.from_float(float('inf'))\n" +"Decimal('Infinity')\n" +">>> Decimal.from_float(float('-inf'))\n" +"Decimal('-Infinity')" + +#: ../../library/decimal.rst:605 msgid "" "Fused multiply-add. Return self*other+third with no rounding of the " "intermediate product self*other." @@ -771,7 +1119,7 @@ msgstr "" "Multiplicação e adição fundidos. Retorna self*other+third sem arredondamento " "do produto intermediário self*other." -#: ../../library/decimal.rst:611 +#: ../../library/decimal.rst:613 msgid "" "Return :const:`True` if the argument is canonical and :const:`False` " "otherwise. Currently, a :class:`Decimal` instance is always canonical, so " @@ -781,7 +1129,7 @@ msgstr "" "contrário. Atualmente, uma instância de :class:`Decimal` é sempre canônica, " "portanto, esta operação sempre retorna :const:`True`." -#: ../../library/decimal.rst:617 +#: ../../library/decimal.rst:619 msgid "" "Return :const:`True` if the argument is a finite number, and :const:`False` " "if the argument is an infinity or a NaN." @@ -789,7 +1137,7 @@ msgstr "" "Retorna :const:`True` se o argumento for um número finito e :const:`False` " "se o argumento for um infinito ou um NaN." -#: ../../library/decimal.rst:622 +#: ../../library/decimal.rst:624 msgid "" "Return :const:`True` if the argument is either positive or negative infinity " "and :const:`False` otherwise." @@ -797,7 +1145,7 @@ msgstr "" "Retorna :const:`True` se o argumento for infinito positivo ou negativo e :" "const:`False` caso contrário." -#: ../../library/decimal.rst:627 +#: ../../library/decimal.rst:629 msgid "" "Return :const:`True` if the argument is a (quiet or signaling) NaN and :" "const:`False` otherwise." @@ -805,7 +1153,7 @@ msgstr "" "Retorna :const:`True` se o argumento for NaN (silencioso ou sinalizador) e :" "const:`False` caso contrário." -#: ../../library/decimal.rst:632 +#: ../../library/decimal.rst:634 msgid "" "Return :const:`True` if the argument is a *normal* finite number. Return :" "const:`False` if the argument is zero, subnormal, infinite or a NaN." @@ -813,7 +1161,7 @@ msgstr "" "Retorna :const:`True` se o argumento for um número finito *normal*. Retorna :" "const:`False` se o argumento for zero, subnormal, infinito ou NaN." -#: ../../library/decimal.rst:637 +#: ../../library/decimal.rst:639 msgid "" "Return :const:`True` if the argument is a quiet NaN, and :const:`False` " "otherwise." @@ -821,7 +1169,7 @@ msgstr "" "Retorna :const:`True` se o argumento for um NaN silencioso, e :const:`False` " "caso contrário." -#: ../../library/decimal.rst:642 +#: ../../library/decimal.rst:644 msgid "" "Return :const:`True` if the argument has a negative sign and :const:`False` " "otherwise. Note that zeros and NaNs can both carry signs." @@ -829,7 +1177,7 @@ msgstr "" "Retorna :const:`True` se o argumento tiver um sinal negativo e :const:" "`False` caso contrário. Observe que zeros e NaNs podem carregar sinais." -#: ../../library/decimal.rst:647 +#: ../../library/decimal.rst:649 msgid "" "Return :const:`True` if the argument is a signaling NaN and :const:`False` " "otherwise." @@ -837,7 +1185,7 @@ msgstr "" "Retorna :const:`True` se o argumento for um sinal NaN e :const:`False` caso " "contrário." -#: ../../library/decimal.rst:652 +#: ../../library/decimal.rst:654 msgid "" "Return :const:`True` if the argument is subnormal, and :const:`False` " "otherwise." @@ -845,7 +1193,7 @@ msgstr "" "Retorna :const:`True` se o argumento for subnormal e :const:`False` caso " "contrário." -#: ../../library/decimal.rst:657 +#: ../../library/decimal.rst:659 msgid "" "Return :const:`True` if the argument is a (positive or negative) zero and :" "const:`False` otherwise." @@ -853,7 +1201,7 @@ msgstr "" "Retorna :const:`True` se o argumento for um zero (positivo ou negativo) e :" "const:`False` caso contrário." -#: ../../library/decimal.rst:662 +#: ../../library/decimal.rst:664 msgid "" "Return the natural (base e) logarithm of the operand. The result is " "correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode." @@ -861,7 +1209,7 @@ msgstr "" "Retorna o logaritmo (base e) natural do operando. O resultado é arredondado " "corretamente usando o modo de arredondamento :const:`ROUND_HALF_EVEN`." -#: ../../library/decimal.rst:667 +#: ../../library/decimal.rst:669 msgid "" "Return the base ten logarithm of the operand. The result is correctly " "rounded using the :const:`ROUND_HALF_EVEN` rounding mode." @@ -869,7 +1217,7 @@ msgstr "" "Retorna o logaritmo da base dez do operando. O resultado é arredondado " "corretamente usando o modo de arredondamento :const:`ROUND_HALF_EVEN`." -#: ../../library/decimal.rst:672 +#: ../../library/decimal.rst:674 msgid "" "For a nonzero number, return the adjusted exponent of its operand as a :" "class:`Decimal` instance. If the operand is a zero then ``Decimal('-" @@ -882,7 +1230,7 @@ msgstr "" "é levantado. Se o operando for um infinito, ``Decimal('Infinity')`` será " "retornado." -#: ../../library/decimal.rst:680 +#: ../../library/decimal.rst:682 msgid "" ":meth:`logical_and` is a logical operation which takes two *logical " "operands* (see :ref:`logical_operands_label`). The result is the digit-wise " @@ -892,7 +1240,7 @@ msgstr "" "(consulte :ref:`logical_operands_label`). O resultado é o ``and`` dígito a " "dígito dos dois operandos." -#: ../../library/decimal.rst:686 +#: ../../library/decimal.rst:688 msgid "" ":meth:`logical_invert` is a logical operation. The result is the digit-wise " "inversion of the operand." @@ -900,7 +1248,7 @@ msgstr "" ":meth:`logical_invert` é uma operação lógica. O resultado é a inversão " "dígito a dígito do operando." -#: ../../library/decimal.rst:691 +#: ../../library/decimal.rst:693 msgid "" ":meth:`logical_or` is a logical operation which takes two *logical operands* " "(see :ref:`logical_operands_label`). The result is the digit-wise ``or`` of " @@ -910,7 +1258,7 @@ msgstr "" "(consulte :ref:`logical_operands_label`). O resultado é o ``or`` dígito a " "dígito dos dois operandos." -#: ../../library/decimal.rst:697 +#: ../../library/decimal.rst:699 msgid "" ":meth:`logical_xor` is a logical operation which takes two *logical " "operands* (see :ref:`logical_operands_label`). The result is the digit-wise " @@ -920,7 +1268,7 @@ msgstr "" "(consulte :ref:`logical_operands_label`). O resultado é o \"ou exclusivo\" " "dígito a dígito ou dos dois operandos." -#: ../../library/decimal.rst:703 +#: ../../library/decimal.rst:705 msgid "" "Like ``max(self, other)`` except that the context rounding rule is applied " "before returning and that ``NaN`` values are either signaled or ignored " @@ -930,7 +1278,7 @@ msgstr "" "é aplicada antes de retornar e que os valores ``NaN`` são sinalizados ou " "ignorados (dependendo do contexto e se estão sinalizando ou silenciosos)." -#: ../../library/decimal.rst:710 +#: ../../library/decimal.rst:712 msgid "" "Similar to the :meth:`.max` method, but the comparison is done using the " "absolute values of the operands." @@ -938,7 +1286,7 @@ msgstr "" "Semelhante ao método :meth:`.max`, mas a comparação é feita usando os " "valores absolutos dos operandos." -#: ../../library/decimal.rst:715 +#: ../../library/decimal.rst:717 msgid "" "Like ``min(self, other)`` except that the context rounding rule is applied " "before returning and that ``NaN`` values are either signaled or ignored " @@ -948,7 +1296,7 @@ msgstr "" "é aplicada antes de retornar e que os valores ``NaN`` são sinalizados ou " "ignorados (dependendo do contexto e se estão sinalizando ou silenciosos)." -#: ../../library/decimal.rst:722 +#: ../../library/decimal.rst:724 msgid "" "Similar to the :meth:`.min` method, but the comparison is done using the " "absolute values of the operands." @@ -956,7 +1304,7 @@ msgstr "" "Semelhante ao método :meth:`.min`, mas a comparação é feita usando os " "valores absolutos dos operandos." -#: ../../library/decimal.rst:727 +#: ../../library/decimal.rst:729 msgid "" "Return the largest number representable in the given context (or in the " "current thread's context if no context is given) that is smaller than the " @@ -966,7 +1314,7 @@ msgstr "" "atual da thread, se nenhum contexto for fornecido) que seja menor que o " "operando especificado." -#: ../../library/decimal.rst:733 +#: ../../library/decimal.rst:735 msgid "" "Return the smallest number representable in the given context (or in the " "current thread's context if no context is given) that is larger than the " @@ -976,7 +1324,7 @@ msgstr "" "atual da thread, se nenhum contexto for fornecido) que seja maior que o " "operando fornecido." -#: ../../library/decimal.rst:739 +#: ../../library/decimal.rst:741 msgid "" "If the two operands are unequal, return the number closest to the first " "operand in the direction of the second operand. If both operands are " @@ -988,7 +1336,7 @@ msgstr "" "numericamente iguais, retorna uma cópia do primeiro operando com o sinal " "configurado para ser o mesmo que o sinal do segundo operando." -#: ../../library/decimal.rst:746 +#: ../../library/decimal.rst:748 msgid "" "Used for producing canonical values of an equivalence class within either " "the current context or the specified context." @@ -996,7 +1344,7 @@ msgstr "" "Usado para produzir valores canônicos de uma classe de equivalência no " "contexto atual ou no contexto especificado." -#: ../../library/decimal.rst:749 +#: ../../library/decimal.rst:751 msgid "" "This has the same semantics as the unary plus operation, except that if the " "final result is finite it is reduced to its simplest form, with all trailing " @@ -1013,7 +1361,7 @@ msgstr "" "coeficiente é zero), o expoente é definido como 0. Em todos os casos, o " "sinal permanece inalterado. ." -#: ../../library/decimal.rst:756 +#: ../../library/decimal.rst:758 msgid "" "For example, ``Decimal('32.100')`` and ``Decimal('0.321000e+2')`` both " "normalize to the equivalent value ``Decimal('32.1')``." @@ -1021,13 +1369,13 @@ msgstr "" "Por exemplo, ``Decimal('32.100')`` e ``Decimal('0.321000e+2')`` ambos " "normalizam para o valor equivalente ``Decimal('32.1')``." -#: ../../library/decimal.rst:759 +#: ../../library/decimal.rst:761 msgid "Note that rounding is applied *before* reducing to simplest form." msgstr "" "Observe que o arredondamento é aplicado *antes* de reduzir para a forma mais " "simples." -#: ../../library/decimal.rst:761 +#: ../../library/decimal.rst:763 msgid "" "In the latest versions of the specification, this operation is also known as " "``reduce``." @@ -1035,7 +1383,7 @@ msgstr "" "Nas versões mais recentes da especificação, esta operação também é conhecida " "como ``reduce``." -#: ../../library/decimal.rst:766 +#: ../../library/decimal.rst:768 msgid "" "Return a string describing the *class* of the operand. The returned value " "is one of the following ten strings." @@ -1043,52 +1391,52 @@ msgstr "" "Retorna uma string descrevendo a *classe* do operando. O valor retornado é " "uma das dez sequências a seguir." -#: ../../library/decimal.rst:769 +#: ../../library/decimal.rst:771 msgid "``\"-Infinity\"``, indicating that the operand is negative infinity." msgstr "``\"-Infinity\"``, indicando que o operando é infinito negativo." -#: ../../library/decimal.rst:770 +#: ../../library/decimal.rst:772 msgid "" "``\"-Normal\"``, indicating that the operand is a negative normal number." msgstr "``\"-Normal\"``, indicando que o operando é um número normal negativo." -#: ../../library/decimal.rst:771 +#: ../../library/decimal.rst:773 msgid "" "``\"-Subnormal\"``, indicating that the operand is negative and subnormal." msgstr "``\"-Subnormal\"``, indicando que o operando é negativo e subnormal." -#: ../../library/decimal.rst:772 +#: ../../library/decimal.rst:774 msgid "``\"-Zero\"``, indicating that the operand is a negative zero." msgstr "``\"-Zero\"``, indicando que o operando é um zero negativo." -#: ../../library/decimal.rst:773 +#: ../../library/decimal.rst:775 msgid "``\"+Zero\"``, indicating that the operand is a positive zero." msgstr "``\"+Zero\"``, indicando que o operando é um zero positivo." -#: ../../library/decimal.rst:774 +#: ../../library/decimal.rst:776 msgid "" "``\"+Subnormal\"``, indicating that the operand is positive and subnormal." msgstr "``\"+Subnormal\"``, indicando que o operando é positivo e subnormal." -#: ../../library/decimal.rst:775 +#: ../../library/decimal.rst:777 msgid "" "``\"+Normal\"``, indicating that the operand is a positive normal number." msgstr "``\"+Normal\"``, indicando que o operando é um número normal positivo." -#: ../../library/decimal.rst:776 +#: ../../library/decimal.rst:778 msgid "``\"+Infinity\"``, indicating that the operand is positive infinity." msgstr "``\"+Infinity\"``, indicando que o operando é infinito positivo." -#: ../../library/decimal.rst:777 +#: ../../library/decimal.rst:779 msgid "``\"NaN\"``, indicating that the operand is a quiet NaN (Not a Number)." msgstr "" "``\"NaN\"``, indicando que o operando é um NaN (\"Not a Number\") silencioso." -#: ../../library/decimal.rst:778 +#: ../../library/decimal.rst:780 msgid "``\"sNaN\"``, indicating that the operand is a signaling NaN." msgstr "``\"sNaN\"``, indicando que o operando é um NaN sinalizador." -#: ../../library/decimal.rst:782 +#: ../../library/decimal.rst:784 msgid "" "Return a value equal to the first operand after rounding and having the " "exponent of the second operand." @@ -1096,7 +1444,7 @@ msgstr "" "Retorna um valor igual ao primeiro operando após o arredondamento e com o " "expoente do segundo operando." -#: ../../library/decimal.rst:788 +#: ../../library/decimal.rst:790 msgid "" "Unlike other operations, if the length of the coefficient after the quantize " "operation would be greater than precision, then an :const:`InvalidOperation` " @@ -1109,7 +1457,7 @@ msgstr "" "condição de erro, o expoente quantizado é sempre igual ao do operando do " "lado direito." -#: ../../library/decimal.rst:794 +#: ../../library/decimal.rst:796 msgid "" "Also unlike other operations, quantize never signals Underflow, even if the " "result is subnormal and inexact." @@ -1117,7 +1465,7 @@ msgstr "" "Também, diferentemente de outras operações, a quantização nunca sinaliza " "Underflow, mesmo que o resultado seja subnormal e inexato." -#: ../../library/decimal.rst:797 +#: ../../library/decimal.rst:799 msgid "" "If the exponent of the second operand is larger than that of the first then " "rounding may be necessary. In this case, the rounding mode is determined by " @@ -1131,7 +1479,7 @@ msgstr "" "``context`` fornecido; se nenhum argumento for fornecido, o modo de " "arredondamento do contexto da thread atual será usado." -#: ../../library/decimal.rst:803 +#: ../../library/decimal.rst:805 msgid "" "An error is returned whenever the resulting exponent is greater than :attr:" "`~Context.Emax` or less than :meth:`~Context.Etiny`." @@ -1139,7 +1487,7 @@ msgstr "" "Um erro é retornado sempre que o expoente resultante for maior que :attr:" "`~Context.Emax` ou menor que :meth:`~Context.Etiny`." -#: ../../library/decimal.rst:808 +#: ../../library/decimal.rst:810 msgid "" "Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal` class " "does all its arithmetic. Included for compatibility with the specification." @@ -1147,7 +1495,7 @@ msgstr "" "Retorna ``Decimal(10)``, a raiz (base) na qual a classe :class:`Decimal` faz " "toda a sua aritmética. Incluído para compatibilidade com a especificação." -#: ../../library/decimal.rst:814 +#: ../../library/decimal.rst:816 msgid "" "Return the remainder from dividing *self* by *other*. This differs from " "``self % other`` in that the sign of the remainder is chosen so as to " @@ -1162,11 +1510,11 @@ msgstr "" "se dois números inteiros estiverem igualmente próximos, o par será é " "escolhido." -#: ../../library/decimal.rst:821 +#: ../../library/decimal.rst:823 msgid "If the result is zero then its sign will be the sign of *self*." msgstr "Se o resultado for zero, seu sinal será o sinal de *self*." -#: ../../library/decimal.rst:832 +#: ../../library/decimal.rst:834 msgid "" "Return the result of rotating the digits of the first operand by an amount " "specified by the second operand. The second operand must be an integer in " @@ -1187,14 +1535,14 @@ msgstr "" "comprimento, se necessário. O sinal e o expoente do primeiro operando não " "são alterados." -#: ../../library/decimal.rst:843 +#: ../../library/decimal.rst:845 msgid "" "Test whether self and other have the same exponent or whether both are " "``NaN``." msgstr "" "Testa se \"self\" e \"other\" têm o mesmo expoente ou se ambos são ``NaN``." -#: ../../library/decimal.rst:852 +#: ../../library/decimal.rst:854 msgid "" "Return the first operand with exponent adjusted by the second. Equivalently, " "return the first operand multiplied by ``10**other``. The second operand " @@ -1204,7 +1552,7 @@ msgstr "" "forma, retorna o primeiro operando multiplicado por ``10**other``. O segundo " "operando deve ser um número inteiro." -#: ../../library/decimal.rst:858 +#: ../../library/decimal.rst:860 msgid "" "Return the result of shifting the digits of the first operand by an amount " "specified by the second operand. The second operand must be an integer in " @@ -1223,18 +1571,18 @@ msgstr "" "coeficiente são zeros. O sinal e o expoente do primeiro operando não são " "alterados." -#: ../../library/decimal.rst:868 +#: ../../library/decimal.rst:870 msgid "Return the square root of the argument to full precision." msgstr "Retorna a raiz quadrada do argumento para a precisão total." -#: ../../library/decimal.rst:873 ../../library/decimal.rst:1510 +#: ../../library/decimal.rst:875 ../../library/decimal.rst:1524 msgid "" "Convert to a string, using engineering notation if an exponent is needed." msgstr "" "Converte em uma string, usando notação de engenharia, se for necessário um " "expoente." -#: ../../library/decimal.rst:875 ../../library/decimal.rst:1512 +#: ../../library/decimal.rst:877 ../../library/decimal.rst:1526 msgid "" "Engineering notation has an exponent which is a multiple of 3. This can " "leave up to 3 digits to the left of the decimal place and may require the " @@ -1244,13 +1592,13 @@ msgstr "" "deixar até 3 dígitos à esquerda da casa decimal e pode exigir a adição de um " "ou dois zeros à direita." -#: ../../library/decimal.rst:879 +#: ../../library/decimal.rst:881 msgid "" "For example, this converts ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``." msgstr "" "Por exemplo, isso converte ``Decimal('123E+1')`` para ``Decimal('1.23E+3')``." -#: ../../library/decimal.rst:883 +#: ../../library/decimal.rst:885 msgid "" "Identical to the :meth:`to_integral_value` method. The ``to_integral`` name " "has been kept for compatibility with older versions." @@ -1258,7 +1606,7 @@ msgstr "" "Idêntico ao método :meth:`to_integral_value`. O nome ``to_integral`` foi " "mantido para compatibilidade com versões mais antigas." -#: ../../library/decimal.rst:888 +#: ../../library/decimal.rst:890 msgid "" "Round to the nearest integer, signaling :const:`Inexact` or :const:`Rounded` " "as appropriate if rounding occurs. The rounding mode is determined by the " @@ -1271,7 +1619,7 @@ msgstr "" "fornecido, ou pelo ``context`` especificado. Se nenhum parâmetro for " "fornecido, o modo de arredondamento do contexto atual será usado." -#: ../../library/decimal.rst:896 +#: ../../library/decimal.rst:898 msgid "" "Round to the nearest integer without signaling :const:`Inexact` or :const:" "`Rounded`. If given, applies *rounding*; otherwise, uses the rounding " @@ -1281,12 +1629,12 @@ msgstr "" "ou :const:`Rounding`. Se fornecido, aplica *rounding*; caso contrário, usa o " "método de arredondamento no *context* especificado ou no contexto atual." -#: ../../library/decimal.rst:900 +#: ../../library/decimal.rst:902 msgid "Decimal numbers can be rounded using the :func:`.round` function:" msgstr "" "Os números decimais podem ser arredondados usando a função :func:`.round`:" -#: ../../library/decimal.rst:905 +#: ../../library/decimal.rst:907 msgid "" "If *ndigits* is not given or ``None``, returns the nearest :class:`int` to " "*number*, rounding ties to even, and ignoring the rounding mode of the :" @@ -1299,7 +1647,7 @@ msgstr "" "*number* for um infinito ou :exc:`ValueError` se for um NaN (silencioso ou " "de sinalização)." -#: ../../library/decimal.rst:911 +#: ../../library/decimal.rst:913 msgid "" "If *ndigits* is an :class:`int`, the context's rounding mode is respected " "and a :class:`Decimal` representing *number* rounded to the nearest multiple " @@ -1320,7 +1668,7 @@ msgstr "" "quantização for maior que a precisão do contexto atual. Em outras palavras, " "para os situações comuns:" -#: ../../library/decimal.rst:921 +#: ../../library/decimal.rst:923 msgid "" "if *ndigits* is positive, return *number* rounded to *ndigits* decimal " "places;" @@ -1328,13 +1676,13 @@ msgstr "" "se *ndigits* for positivo, retorna *number* arredondado para *ndigits* casas " "decimais;" -#: ../../library/decimal.rst:923 +#: ../../library/decimal.rst:925 msgid "if *ndigits* is zero, return *number* rounded to the nearest integer;" msgstr "" "se *ndigits* for zero, retorna *number* arredondado para o número inteiro " "mais próximo;" -#: ../../library/decimal.rst:924 +#: ../../library/decimal.rst:926 msgid "" "if *ndigits* is negative, return *number* rounded to the nearest multiple of " "``10**abs(ndigits)``." @@ -1342,15 +1690,43 @@ msgstr "" "se *ndigits* for negativo, retorna *number* arredondado para o múltiplo mais " "próximo de ``10**abs(ndigits)``." -#: ../../library/decimal.rst:927 +#: ../../library/decimal.rst:929 msgid "For example::" msgstr "Por exemplo::" -#: ../../library/decimal.rst:946 +#: ../../library/decimal.rst:931 +msgid "" +">>> from decimal import Decimal, getcontext, ROUND_DOWN\n" +">>> getcontext().rounding = ROUND_DOWN\n" +">>> round(Decimal('3.75')) # context rounding ignored\n" +"4\n" +">>> round(Decimal('3.5')) # round-ties-to-even\n" +"4\n" +">>> round(Decimal('3.75'), 0) # uses the context rounding\n" +"Decimal('3')\n" +">>> round(Decimal('3.75'), 1)\n" +"Decimal('3.7')\n" +">>> round(Decimal('3.75'), -1)\n" +"Decimal('0E+1')" +msgstr "" +">>> from decimal import Decimal, getcontext, ROUND_DOWN\n" +">>> getcontext().rounding = ROUND_DOWN\n" +">>> round(Decimal('3.75')) # arredondamento de contexto ignorado\n" +"4\n" +">>> round(Decimal('3.5')) # arredondamento para par mais próximo\n" +"4\n" +">>> round(Decimal('3.75'), 0) # usa o arredondamento de contexto\n" +"Decimal('3')\n" +">>> round(Decimal('3.75'), 1)\n" +"Decimal('3.7')\n" +">>> round(Decimal('3.75'), -1)\n" +"Decimal('0E+1')" + +#: ../../library/decimal.rst:948 msgid "Logical operands" msgstr "Operandos lógicos" -#: ../../library/decimal.rst:948 +#: ../../library/decimal.rst:950 msgid "" "The :meth:`~Decimal.logical_and`, :meth:`~Decimal.logical_invert`, :meth:" "`~Decimal.logical_or`, and :meth:`~Decimal.logical_xor` methods expect their " @@ -1364,11 +1740,11 @@ msgstr "" "de :class:`Decimal` cujo expoente e sinal são zero e cujos dígitos são todos " "``0`` ou ``1``." -#: ../../library/decimal.rst:960 +#: ../../library/decimal.rst:962 msgid "Context objects" msgstr "Objetos de contexto" -#: ../../library/decimal.rst:962 +#: ../../library/decimal.rst:964 msgid "" "Contexts are environments for arithmetic operations. They govern precision, " "set rules for rounding, determine which signals are treated as exceptions, " @@ -1378,7 +1754,7 @@ msgstr "" "precisão, estabelecem regras para arredondamento, determinam quais sinais " "são tratados como exceções e limitam o intervalo dos expoentes." -#: ../../library/decimal.rst:966 +#: ../../library/decimal.rst:968 msgid "" "Each thread has its own current context which is accessed or changed using " "the :func:`getcontext` and :func:`setcontext` functions:" @@ -1386,15 +1762,15 @@ msgstr "" "Cada thread possui seu próprio contexto atual que é acessado ou alterado " "usando as funções :func:`getcontext` e :func:`setcontext`:" -#: ../../library/decimal.rst:972 +#: ../../library/decimal.rst:974 msgid "Return the current context for the active thread." msgstr "Retorna o contexto atual para a thread ativa." -#: ../../library/decimal.rst:977 +#: ../../library/decimal.rst:979 msgid "Set the current context for the active thread to *c*." msgstr "Define o contexto atual para a thread ativa como *C*." -#: ../../library/decimal.rst:979 +#: ../../library/decimal.rst:981 msgid "" "You can also use the :keyword:`with` statement and the :func:`localcontext` " "function to temporarily change the active context." @@ -1402,7 +1778,7 @@ msgstr "" "Você também pode usar a instrução :keyword:`with` e a função :func:" "`localcontext` para alterar temporariamente o contexto ativo." -#: ../../library/decimal.rst:984 +#: ../../library/decimal.rst:986 msgid "" "Return a context manager that will set the current context for the active " "thread to a copy of *ctx* on entry to the with-statement and restore the " @@ -1416,7 +1792,7 @@ msgstr "" "contexto for especificado, uma cópia do contexto atual será usada. O " "argumento *kwargs* é usado para definir os atributos do novo contexto." -#: ../../library/decimal.rst:990 +#: ../../library/decimal.rst:992 msgid "" "For example, the following code sets the current decimal precision to 42 " "places, performs a calculation, and then automatically restores the previous " @@ -1425,11 +1801,41 @@ msgstr "" "Por exemplo, o código a seguir define a precisão decimal atual para 42 " "casas, executa um cálculo e restaura automaticamente o contexto anterior::" -#: ../../library/decimal.rst:1000 +#: ../../library/decimal.rst:995 +msgid "" +"from decimal import localcontext\n" +"\n" +"with localcontext() as ctx:\n" +" ctx.prec = 42 # Perform a high precision calculation\n" +" s = calculate_something()\n" +"s = +s # Round the final result back to the default precision" +msgstr "" +"from decimal import localcontext\n" +"\n" +"with localcontext() as ctx:\n" +" ctx.prec = 42 # Efetua um cálculo de alta precisão\n" +" s = calculate_something()\n" +"s = +s # Arredonda o resultado final de volta para a precisão padrão" + +#: ../../library/decimal.rst:1002 msgid "Using keyword arguments, the code would be the following::" msgstr "Usando argumentos nomeados, o código seria o seguinte::" -#: ../../library/decimal.rst:1008 +#: ../../library/decimal.rst:1004 +msgid "" +"from decimal import localcontext\n" +"\n" +"with localcontext(prec=42) as ctx:\n" +" s = calculate_something()\n" +"s = +s" +msgstr "" +"from decimal import localcontext\n" +"\n" +"with localcontext(prec=42) as ctx:\n" +" s = calculate_something()\n" +"s = +s" + +#: ../../library/decimal.rst:1010 msgid "" "Raises :exc:`TypeError` if *kwargs* supplies an attribute that :class:" "`Context` doesn't support. Raises either :exc:`TypeError` or :exc:" @@ -1439,7 +1845,7 @@ msgstr "" "`Context` não oferecer suporte. Levanta :exc:`TypeError` ou :exc:" "`ValueError` se *kwargs* fornecer um valor inválido para um atributo." -#: ../../library/decimal.rst:1012 +#: ../../library/decimal.rst:1014 msgid "" ":meth:`localcontext` now supports setting context attributes through the use " "of keyword arguments." @@ -1447,7 +1853,7 @@ msgstr "" ":meth:`localcontext` agora tem suporte à configuração de atributos de " "contexto através do uso de argumentos nomeados." -#: ../../library/decimal.rst:1015 +#: ../../library/decimal.rst:1017 msgid "" "New contexts can also be created using the :class:`Context` constructor " "described below. In addition, the module provides three pre-made contexts:" @@ -1456,7 +1862,7 @@ msgstr "" "`Context` descrito abaixo. Além disso, o módulo fornece três contextos pré-" "criados::" -#: ../../library/decimal.rst:1021 +#: ../../library/decimal.rst:1023 msgid "" "This is a standard context defined by the General Decimal Arithmetic " "Specification. Precision is set to nine. Rounding is set to :const:" @@ -1470,14 +1876,14 @@ msgstr "" "armadilhas estão ativadas (tratadas como exceções), exceto por :const:" "`Inexact`, :const:`Rounded` e :const:`Subnormal`." -#: ../../library/decimal.rst:1027 +#: ../../library/decimal.rst:1029 msgid "" "Because many of the traps are enabled, this context is useful for debugging." msgstr "" "Como muitas das armadilhas estão ativadas, esse contexto é útil para " "depuração." -#: ../../library/decimal.rst:1032 +#: ../../library/decimal.rst:1034 msgid "" "This is a standard context defined by the General Decimal Arithmetic " "Specification. Precision is set to nine. Rounding is set to :const:" @@ -1490,7 +1896,7 @@ msgstr "" "armadilha está ativada (de forma que exceções não são levantadas durante os " "cálculos)." -#: ../../library/decimal.rst:1037 +#: ../../library/decimal.rst:1039 msgid "" "Because the traps are disabled, this context is useful for applications that " "prefer to have result value of ``NaN`` or ``Infinity`` instead of raising " @@ -1502,7 +1908,7 @@ msgstr "" "levantar exceções. Isso permite que uma aplicação conclua uma execução na " "presença de condições que interromperiam o programa." -#: ../../library/decimal.rst:1045 +#: ../../library/decimal.rst:1047 msgid "" "This context is used by the :class:`Context` constructor as a prototype for " "new contexts. Changing a field (such a precision) has the effect of " @@ -1514,7 +1920,7 @@ msgstr "" "alterar o padrão para novos contextos criados pelo construtor :class:" "`Context`." -#: ../../library/decimal.rst:1049 +#: ../../library/decimal.rst:1051 msgid "" "This context is most useful in multi-threaded environments. Changing one of " "the fields before threads are started has the effect of setting system-wide " @@ -1527,7 +1933,7 @@ msgstr "" "threads, pois exigiria sincronização de threads para evitar condições de " "corrida." -#: ../../library/decimal.rst:1054 +#: ../../library/decimal.rst:1056 msgid "" "In single threaded environments, it is preferable to not use this context at " "all. Instead, simply create contexts explicitly as described below." @@ -1535,7 +1941,7 @@ msgstr "" "Em ambientes de thread única, é preferível não usar esse contexto. Em vez " "disso, basta criar contextos explicitamente, conforme descrito abaixo." -#: ../../library/decimal.rst:1057 +#: ../../library/decimal.rst:1059 msgid "" "The default values are :attr:`Context.prec`\\ =\\ ``28``, :attr:`Context." "rounding`\\ =\\ :const:`ROUND_HALF_EVEN`, and enabled traps for :class:" @@ -1545,7 +1951,7 @@ msgstr "" "rounding`\\ =\\ :const:`ROUND_HALF_EVEN` e armadilhas ativadas para :class:" "`Overflow`, :class:`InvalidOperation` e :class:`DivisionByZero`." -#: ../../library/decimal.rst:1062 +#: ../../library/decimal.rst:1064 msgid "" "In addition to the three supplied contexts, new contexts can be created with " "the :class:`Context` constructor." @@ -1553,7 +1959,7 @@ msgstr "" "Além dos três contextos fornecidos, novos contextos podem ser criados com o " "construtor :class:`Context`." -#: ../../library/decimal.rst:1068 +#: ../../library/decimal.rst:1070 msgid "" "Creates a new context. If a field is not specified or is :const:`None`, the " "default values are copied from the :const:`DefaultContext`. If the *flags* " @@ -1564,84 +1970,66 @@ msgstr "" "campo *flags* não for especificado ou for :const:`None`, todos os " "sinalizadores serão limpados." -#: ../../library/decimal.rst:1072 +#: ../../library/decimal.rst:1076 msgid "" -"*prec* is an integer in the range [``1``, :const:`MAX_PREC`] that sets the " -"precision for arithmetic operations in the context." +"An integer in the range [``1``, :const:`MAX_PREC`] that sets the precision " +"for arithmetic operations in the context." msgstr "" -"*prec* é um número inteiro no intervalo [``1``, :const:`MAX_PREC`] que " -"define a precisão das operações aritméticas no contexto." -#: ../../library/decimal.rst:1075 +#: ../../library/decimal.rst:1081 +msgid "One of the constants listed in the section `Rounding Modes`_." +msgstr "" + +#: ../../library/decimal.rst:1086 msgid "" -"The *rounding* option is one of the constants listed in the section " -"`Rounding Modes`_." +"Lists of any signals to be set. Generally, new contexts should only set " +"traps and leave the flags clear." msgstr "" -"A opção *rounding* é uma das constantes listadas na seção `Modos de " -"arredondamento`_." -#: ../../library/decimal.rst:1078 +#: ../../library/decimal.rst:1092 msgid "" -"The *traps* and *flags* fields list any signals to be set. Generally, new " -"contexts should only set traps and leave the flags clear." +"Integers specifying the outer limits allowable for exponents. *Emin* must be " +"in the range [:const:`MIN_EMIN`, ``0``], *Emax* in the range [``0``, :const:" +"`MAX_EMAX`]." msgstr "" -"Os campos *traps* e *flags* listam todos os sinais a serem configurados. " -"Geralmente, novos contextos devem apenas definir armadilhas e deixar os " -"sinalizadores limpos." -#: ../../library/decimal.rst:1081 +#: ../../library/decimal.rst:1098 msgid "" -"The *Emin* and *Emax* fields are integers specifying the outer limits " -"allowable for exponents. *Emin* must be in the range [:const:`MIN_EMIN`, " -"``0``], *Emax* in the range [``0``, :const:`MAX_EMAX`]." -msgstr "" -"Os campos *Emin* e *Emax* são números inteiros que especificam os limites " -"externos permitidos para expoentes. *Emin* deve estar no intervalo [:const:" -"`MIN_EMIN`, ``0``], *Emax* no intervalo [``0``, :const:`MAX_EMAX`]." - -#: ../../library/decimal.rst:1085 -msgid "" -"The *capitals* field is either ``0`` or ``1`` (the default). If set to " -"``1``, exponents are printed with a capital ``E``; otherwise, a lowercase " -"``e`` is used: ``Decimal('6.02e+23')``." -msgstr "" -"O campo *capitals* é ``0`` ou ``1`` (o padrão). Se definido como ``1``, os " -"expoentes serão impressos com um ``E`` maiúsculo; caso contrário, um ``e`` " -"minúscula é usado: ``Decimal('6.02e+23')``." - -#: ../../library/decimal.rst:1089 -msgid "" -"The *clamp* field is either ``0`` (the default) or ``1``. If set to ``1``, " -"the exponent ``e`` of a :class:`Decimal` instance representable in this " -"context is strictly limited to the range ``Emin - prec + 1 <= e <= Emax - " -"prec + 1``. If *clamp* is ``0`` then a weaker condition holds: the adjusted " -"exponent of the :class:`Decimal` instance is at most :attr:`~Context.Emax`. " -"When *clamp* is ``1``, a large normal number will, where possible, have its " -"exponent reduced and a corresponding number of zeros added to its " -"coefficient, in order to fit the exponent constraints; this preserves the " -"value of the number but loses information about significant trailing zeros. " -"For example::" -msgstr "" -"O campo *clamp* é ``0`` (o padrão) ou ``1``. Se definido como ``1``, o " -"expoente ``e`` de uma instância de :class:`Decimal` representável nesse " -"contexto é estritamente limitado ao intervalo ``Emin - prec + 1 <= e <= Emax " -"- prec + 1``. Se *clamp* for ``0``, uma condição mais fraca será mantida: o " -"expoente ajustado da instância de :class:`Decimal` é no máximo :attr:" -"`~Context.Emax`. Quando *clamp* é ``1``, um grande número normal terá, " -"sempre que possível, seu expoente reduzido e um número correspondente de " -"zeros adicionado ao seu coeficiente, para ajustar as restrições do expoente; " -"isso preserva o valor do número, mas perde informações sobre zeros à direita " -"significativos. Por exemplo::" +"Either ``0`` or ``1`` (the default). If set to ``1``, exponents are printed " +"with a capital ``E``; otherwise, a lowercase ``e`` is used: " +"``Decimal('6.02e+23')``." +msgstr "" #: ../../library/decimal.rst:1104 msgid "" +"Either ``0`` (the default) or ``1``. If set to ``1``, the exponent ``e`` of " +"a :class:`Decimal` instance representable in this context is strictly " +"limited to the range ``Emin - prec + 1 <= e <= Emax - prec + 1``. If *clamp* " +"is ``0`` then a weaker condition holds: the adjusted exponent of the :class:" +"`Decimal` instance is at most :attr:`~Context.Emax`. When *clamp* is ``1``, " +"a large normal number will, where possible, have its exponent reduced and a " +"corresponding number of zeros added to its coefficient, in order to fit the " +"exponent constraints; this preserves the value of the number but loses " +"information about significant trailing zeros. For example::" +msgstr "" + +#: ../../library/decimal.rst:1115 +msgid "" +">>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')\n" +"Decimal('1.23000E+999')" +msgstr "" +">>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')\n" +"Decimal('1.23000E+999')" + +#: ../../library/decimal.rst:1118 +msgid "" "A *clamp* value of ``1`` allows compatibility with the fixed-width decimal " "interchange formats specified in IEEE 754." msgstr "" "Um valor de *clamp* de ``1`` permite compatibilidade com os formatos de " "intercâmbio decimal de largura fixa especificados na IEEE 754." -#: ../../library/decimal.rst:1107 +#: ../../library/decimal.rst:1121 msgid "" "The :class:`Context` class defines several general purpose methods as well " "as a large number of methods for doing arithmetic directly in a given " @@ -1663,23 +2051,23 @@ msgstr "" "de :class:`Context` aceita um número inteiro do Python (uma instância de :" "class:`int`) em qualquer lugar em que uma instância de Decimal seja aceita." -#: ../../library/decimal.rst:1120 +#: ../../library/decimal.rst:1134 msgid "Resets all of the flags to ``0``." msgstr "Redefine todos os sinalizadores para ``0``." -#: ../../library/decimal.rst:1124 +#: ../../library/decimal.rst:1138 msgid "Resets all of the traps to ``0``." msgstr "Redefine todas as armadilhas para ``0``." -#: ../../library/decimal.rst:1130 +#: ../../library/decimal.rst:1144 msgid "Return a duplicate of the context." msgstr "Retorna uma duplicata do contexto." -#: ../../library/decimal.rst:1134 +#: ../../library/decimal.rst:1148 msgid "Return a copy of the Decimal instance num." msgstr "Retorna uma cópia da instância de Decimal *num*." -#: ../../library/decimal.rst:1138 +#: ../../library/decimal.rst:1152 msgid "" "Creates a new Decimal instance from *num* but using *self* as context. " "Unlike the :class:`Decimal` constructor, the context precision, rounding " @@ -1690,7 +2078,7 @@ msgstr "" "contexto, o método de arredondamento, os sinalizadores e as armadilhas são " "aplicadas à conversão." -#: ../../library/decimal.rst:1142 +#: ../../library/decimal.rst:1156 msgid "" "This is useful because constants are often given to a greater precision than " "is needed by the application. Another benefit is that rounding immediately " @@ -1704,7 +2092,21 @@ msgstr "" "da precisão atual. No exemplo a seguir, o uso de entradas não arredondadas " "significa que adicionar zero a uma soma pode alterar o resultado:" -#: ../../library/decimal.rst:1156 +#: ../../library/decimal.rst:1162 +msgid "" +">>> getcontext().prec = 3\n" +">>> Decimal('3.4445') + Decimal('1.0023')\n" +"Decimal('4.45')\n" +">>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')\n" +"Decimal('4.44')" +msgstr "" +">>> getcontext().prec = 3\n" +">>> Decimal('3.4445') + Decimal('1.0023')\n" +"Decimal('4.45')\n" +">>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')\n" +"Decimal('4.44')" + +#: ../../library/decimal.rst:1170 msgid "" "This method implements the to-number operation of the IBM specification. If " "the argument is a string, no leading or trailing whitespace or underscores " @@ -1714,7 +2116,7 @@ msgstr "" "argumento for uma string, nenhum espaço em branco à esquerda ou à direita ou " "sublinhado serão permitidos." -#: ../../library/decimal.rst:1162 +#: ../../library/decimal.rst:1176 msgid "" "Creates a new Decimal instance from a float *f* but rounding using *self* as " "the context. Unlike the :meth:`Decimal.from_float` class method, the " @@ -1726,7 +2128,27 @@ msgstr "" "classe :meth:`Decimal.from_float`, a precisão do contexto, o método de " "arredondamento, os sinalizadores e as armadilhas são aplicados à conversão." -#: ../../library/decimal.rst:1182 +#: ../../library/decimal.rst:1181 +msgid "" +">>> context = Context(prec=5, rounding=ROUND_DOWN)\n" +">>> context.create_decimal_from_float(math.pi)\n" +"Decimal('3.1415')\n" +">>> context = Context(prec=5, traps=[Inexact])\n" +">>> context.create_decimal_from_float(math.pi)\n" +"Traceback (most recent call last):\n" +" ...\n" +"decimal.Inexact: None" +msgstr "" +">>> context = Context(prec=5, rounding=ROUND_DOWN)\n" +">>> context.create_decimal_from_float(math.pi)\n" +"Decimal('3.1415')\n" +">>> context = Context(prec=5, traps=[Inexact])\n" +">>> context.create_decimal_from_float(math.pi)\n" +"Traceback (most recent call last):\n" +" ...\n" +"decimal.Inexact: None" + +#: ../../library/decimal.rst:1196 msgid "" "Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent " "value for subnormal results. When underflow occurs, the exponent is set to :" @@ -1736,11 +2158,11 @@ msgstr "" "expoente para resultados subnormais. Quando ocorre o estouro negativo, o " "expoente é definido como :const:`Etiny`." -#: ../../library/decimal.rst:1188 +#: ../../library/decimal.rst:1202 msgid "Returns a value equal to ``Emax - prec + 1``." msgstr "Retorna um valor igual a ``Emax - prec + 1``." -#: ../../library/decimal.rst:1190 +#: ../../library/decimal.rst:1204 msgid "" "The usual approach to working with decimals is to create :class:`Decimal` " "instances and then apply arithmetic operations which take place within the " @@ -1755,191 +2177,191 @@ msgstr "" "para calcular dentro de um contexto específico. Os métodos são semelhantes " "aos da classe :class:`Decimal` e são contados apenas brevemente aqui." -#: ../../library/decimal.rst:1200 +#: ../../library/decimal.rst:1214 msgid "Returns the absolute value of *x*." msgstr "Retorna o valor absoluto de *x*." -#: ../../library/decimal.rst:1205 +#: ../../library/decimal.rst:1219 msgid "Return the sum of *x* and *y*." msgstr "Retorna a soma de *x* e *y*." -#: ../../library/decimal.rst:1210 +#: ../../library/decimal.rst:1224 msgid "Returns the same Decimal object *x*." msgstr "Retorna o mesmo objeto de Decimal *x*." -#: ../../library/decimal.rst:1215 +#: ../../library/decimal.rst:1229 msgid "Compares *x* and *y* numerically." msgstr "Compara *x* e *y* numericamente." -#: ../../library/decimal.rst:1220 +#: ../../library/decimal.rst:1234 msgid "Compares the values of the two operands numerically." msgstr "Compara os valores dos dois operandos numericamente." -#: ../../library/decimal.rst:1225 +#: ../../library/decimal.rst:1239 msgid "Compares two operands using their abstract representation." msgstr "Compara dois operandos usando sua representação abstrata." -#: ../../library/decimal.rst:1230 +#: ../../library/decimal.rst:1244 msgid "" "Compares two operands using their abstract representation, ignoring sign." msgstr "" "Compara dois operandos usando sua representação abstrata, ignorando o sinal." -#: ../../library/decimal.rst:1235 +#: ../../library/decimal.rst:1249 msgid "Returns a copy of *x* with the sign set to 0." msgstr "Retorna uma cópia de *x* com o sinal definido para 0." -#: ../../library/decimal.rst:1240 +#: ../../library/decimal.rst:1254 msgid "Returns a copy of *x* with the sign inverted." msgstr "Retorna uma cópia de *x* com o sinal invertido." -#: ../../library/decimal.rst:1245 +#: ../../library/decimal.rst:1259 msgid "Copies the sign from *y* to *x*." msgstr "Copia o sinal de *y* para *x*." -#: ../../library/decimal.rst:1250 +#: ../../library/decimal.rst:1264 msgid "Return *x* divided by *y*." msgstr "Retorna *x* dividido por *y*." -#: ../../library/decimal.rst:1255 +#: ../../library/decimal.rst:1269 msgid "Return *x* divided by *y*, truncated to an integer." msgstr "Retorna *x* dividido por *y*, truncado para um inteiro." -#: ../../library/decimal.rst:1260 +#: ../../library/decimal.rst:1274 msgid "Divides two numbers and returns the integer part of the result." msgstr "Divide dois números e retorna a parte inteira do resultado." -#: ../../library/decimal.rst:1265 +#: ../../library/decimal.rst:1279 msgid "Returns ``e ** x``." msgstr "Retorna ``e ** x``." -#: ../../library/decimal.rst:1270 +#: ../../library/decimal.rst:1284 msgid "Returns *x* multiplied by *y*, plus *z*." msgstr "Retorna *x* multiplicado por *y*, mais *z*." -#: ../../library/decimal.rst:1275 +#: ../../library/decimal.rst:1289 msgid "Returns ``True`` if *x* is canonical; otherwise returns ``False``." msgstr "" "Retorna ``True`` se *x* for canonical; caso contrário, retorna ``False``." -#: ../../library/decimal.rst:1280 +#: ../../library/decimal.rst:1294 msgid "Returns ``True`` if *x* is finite; otherwise returns ``False``." msgstr "Retorna ``True`` se *x* for finito; caso contrário, retorna ``False``." -#: ../../library/decimal.rst:1285 +#: ../../library/decimal.rst:1299 msgid "Returns ``True`` if *x* is infinite; otherwise returns ``False``." msgstr "" "Retorna ``True`` se *x* for infinito; caso contrário, retorna ``False``." -#: ../../library/decimal.rst:1290 +#: ../../library/decimal.rst:1304 msgid "Returns ``True`` if *x* is a qNaN or sNaN; otherwise returns ``False``." msgstr "" "Retorna ``True`` se *x* for qNaN ou sNaN; caso contrário, retorna ``False``." -#: ../../library/decimal.rst:1295 +#: ../../library/decimal.rst:1309 msgid "" "Returns ``True`` if *x* is a normal number; otherwise returns ``False``." msgstr "" "Retorna ``True`` se *x* for um número normal; caso contrário, retorna " "``False``." -#: ../../library/decimal.rst:1300 +#: ../../library/decimal.rst:1314 msgid "Returns ``True`` if *x* is a quiet NaN; otherwise returns ``False``." msgstr "" "Retorna ``True`` se *x* for um NaN silencioso; caso contrário, retorna " "``False``." -#: ../../library/decimal.rst:1305 +#: ../../library/decimal.rst:1319 msgid "Returns ``True`` if *x* is negative; otherwise returns ``False``." msgstr "" "Retorna ``True`` se *x* for negativo; caso contrário, retorna ``False``." -#: ../../library/decimal.rst:1310 +#: ../../library/decimal.rst:1324 msgid "" "Returns ``True`` if *x* is a signaling NaN; otherwise returns ``False``." msgstr "" "Retorna ``True`` se *x* for um NaN sinalizador; caso contrário, retorna " "``False``." -#: ../../library/decimal.rst:1315 +#: ../../library/decimal.rst:1329 msgid "Returns ``True`` if *x* is subnormal; otherwise returns ``False``." msgstr "" "Retorna ``True`` se *x* for subnormal; caso contrário, retorna ``False``." -#: ../../library/decimal.rst:1320 +#: ../../library/decimal.rst:1334 msgid "Returns ``True`` if *x* is a zero; otherwise returns ``False``." msgstr "Retorna ``True`` se *x* for zero; caso contrário, retorna ``False``." -#: ../../library/decimal.rst:1325 +#: ../../library/decimal.rst:1339 msgid "Returns the natural (base e) logarithm of *x*." msgstr "Retorna o logaritmo natural (base e) de *x*." -#: ../../library/decimal.rst:1330 +#: ../../library/decimal.rst:1344 msgid "Returns the base 10 logarithm of *x*." msgstr "Retorna o logaritmo de base 10 de *x*." -#: ../../library/decimal.rst:1335 +#: ../../library/decimal.rst:1349 msgid "Returns the exponent of the magnitude of the operand's MSD." msgstr "Retorna o expoente da magnitude do MSD do operando." -#: ../../library/decimal.rst:1340 +#: ../../library/decimal.rst:1354 msgid "Applies the logical operation *and* between each operand's digits." msgstr "Aplica a operação lógica *e* entre cada dígito do operando." -#: ../../library/decimal.rst:1345 +#: ../../library/decimal.rst:1359 msgid "Invert all the digits in *x*." msgstr "Inverte todos os dígitos em *x*." -#: ../../library/decimal.rst:1350 +#: ../../library/decimal.rst:1364 msgid "Applies the logical operation *or* between each operand's digits." msgstr "Aplica a operação lógica *ou* entre cada dígito do operando." -#: ../../library/decimal.rst:1355 +#: ../../library/decimal.rst:1369 msgid "Applies the logical operation *xor* between each operand's digits." msgstr "Aplica a operação lógica *ou exclusivo* entre cada dígito do operando." -#: ../../library/decimal.rst:1360 +#: ../../library/decimal.rst:1374 msgid "Compares two values numerically and returns the maximum." msgstr "Compara dois valores numericamente e retorna o máximo." -#: ../../library/decimal.rst:1365 ../../library/decimal.rst:1375 +#: ../../library/decimal.rst:1379 ../../library/decimal.rst:1389 msgid "Compares the values numerically with their sign ignored." msgstr "Compara dois valores numericamente com seu sinal ignorado." -#: ../../library/decimal.rst:1370 +#: ../../library/decimal.rst:1384 msgid "Compares two values numerically and returns the minimum." msgstr "Compara dois valores numericamente e retorna o mínimo." -#: ../../library/decimal.rst:1380 +#: ../../library/decimal.rst:1394 msgid "Minus corresponds to the unary prefix minus operator in Python." msgstr "" "Minus corresponde ao operador de subtração de prefixo unário no Python." -#: ../../library/decimal.rst:1385 +#: ../../library/decimal.rst:1399 msgid "Return the product of *x* and *y*." msgstr "Retorna o produto de *x* e *y*." -#: ../../library/decimal.rst:1390 +#: ../../library/decimal.rst:1404 msgid "Returns the largest representable number smaller than *x*." msgstr "Retorna o maior número representável menor que *x*." -#: ../../library/decimal.rst:1395 +#: ../../library/decimal.rst:1409 msgid "Returns the smallest representable number larger than *x*." msgstr "Retorna o menor número representável maior que *x*." -#: ../../library/decimal.rst:1400 +#: ../../library/decimal.rst:1414 msgid "Returns the number closest to *x*, in direction towards *y*." msgstr "Retorna o número mais próximo a *x*, em direção a *y*." -#: ../../library/decimal.rst:1405 +#: ../../library/decimal.rst:1419 msgid "Reduces *x* to its simplest form." msgstr "Reduz *x* para sua forma mais simples." -#: ../../library/decimal.rst:1410 +#: ../../library/decimal.rst:1424 msgid "Returns an indication of the class of *x*." msgstr "Retorna uma indicação da classe de *x*." -#: ../../library/decimal.rst:1415 +#: ../../library/decimal.rst:1429 msgid "" "Plus corresponds to the unary prefix plus operator in Python. This " "operation applies the context precision and rounding, so it is *not* an " @@ -1949,13 +2371,13 @@ msgstr "" "operação aplica a precisão e o arredondamento do contexto, portanto *não* é " "uma operação de identidade." -#: ../../library/decimal.rst:1422 +#: ../../library/decimal.rst:1436 msgid "Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given." msgstr "" "Retorna ``x`` à potência de ``y``, com a redução de módulo ``modulo`` se " "fornecido." -#: ../../library/decimal.rst:1424 +#: ../../library/decimal.rst:1438 msgid "" "With two arguments, compute ``x**y``. If ``x`` is negative then ``y`` must " "be integral. The result will be inexact unless ``y`` is integral and the " @@ -1969,7 +2391,7 @@ msgstr "" "dígitos. O modo de arredondamento do contexto é usado. Os resultados são " "sempre arredondados corretamente na versão Python." -#: ../../library/decimal.rst:1430 +#: ../../library/decimal.rst:1444 msgid "" "``Decimal(0) ** Decimal(0)`` results in ``InvalidOperation``, and if " "``InvalidOperation`` is not trapped, then results in ``Decimal('NaN')``." @@ -1977,7 +2399,7 @@ msgstr "" "``Decimal(0) ** Decimal(0)`` resulta em ``InvalidOperation``, e se " "``InvalidOperation`` não for capturado, resulta em ``Decimal('NaN')``." -#: ../../library/decimal.rst:1433 +#: ../../library/decimal.rst:1447 msgid "" "The C module computes :meth:`power` in terms of the correctly rounded :meth:" "`exp` and :meth:`ln` functions. The result is well-defined but only \"almost " @@ -1987,7 +2409,7 @@ msgstr "" "arredondadas :meth:`exp` e :meth:`ln`. O resultado é bem definido, mas " "apenas \"quase sempre corretamente arredondado\"." -#: ../../library/decimal.rst:1438 +#: ../../library/decimal.rst:1452 msgid "" "With three arguments, compute ``(x**y) % modulo``. For the three argument " "form, the following restrictions on the arguments hold:" @@ -1995,24 +2417,24 @@ msgstr "" "Com três argumentos, calcula ``(x**y) % modulo``. Para o formulário de três " "argumentos, as seguintes restrições nos argumentos são válidas:" -#: ../../library/decimal.rst:1441 +#: ../../library/decimal.rst:1455 msgid "all three arguments must be integral" msgstr "todos os três argumentos devem ser inteiros" -#: ../../library/decimal.rst:1442 +#: ../../library/decimal.rst:1456 msgid "``y`` must be nonnegative" msgstr "``y`` não pode ser negativo" -#: ../../library/decimal.rst:1443 +#: ../../library/decimal.rst:1457 msgid "at least one of ``x`` or ``y`` must be nonzero" msgstr "pelo menos um de ``x`` ou ``y`` não pode ser negativo" -#: ../../library/decimal.rst:1444 +#: ../../library/decimal.rst:1458 msgid "``modulo`` must be nonzero and have at most 'precision' digits" msgstr "" "``modulo`` não pode ser zero e deve ter pelo menos \"precisão\" dígitos" -#: ../../library/decimal.rst:1446 +#: ../../library/decimal.rst:1460 msgid "" "The value resulting from ``Context.power(x, y, modulo)`` is equal to the " "value that would be obtained by computing ``(x**y) % modulo`` with unbounded " @@ -2026,19 +2448,19 @@ msgstr "" "independentemente dos expoentes de ``x``, ``y`` e ``modulo``. O resultado é " "sempre exato." -#: ../../library/decimal.rst:1456 +#: ../../library/decimal.rst:1470 msgid "Returns a value equal to *x* (rounded), having the exponent of *y*." msgstr "Retorna um valor igual a *x* (arredondado), com o expoente de *y*." -#: ../../library/decimal.rst:1461 +#: ../../library/decimal.rst:1475 msgid "Just returns 10, as this is Decimal, :)" msgstr "Só retorna 10, já que isso é Decimal, :)" -#: ../../library/decimal.rst:1466 +#: ../../library/decimal.rst:1480 msgid "Returns the remainder from integer division." msgstr "Retorna o resto da divisão inteira." -#: ../../library/decimal.rst:1468 +#: ../../library/decimal.rst:1482 msgid "" "The sign of the result, if non-zero, is the same as that of the original " "dividend." @@ -2046,7 +2468,7 @@ msgstr "" "O sinal do resultado, se diferente de zero, é o mesmo que o do dividendo " "original." -#: ../../library/decimal.rst:1474 +#: ../../library/decimal.rst:1488 msgid "" "Returns ``x - y * n``, where *n* is the integer nearest the exact value of " "``x / y`` (if the result is 0 then its sign will be the sign of *x*)." @@ -2054,43 +2476,43 @@ msgstr "" "Retorna ``x - y * n``, onde *n* é o número inteiro mais próximo do valor " "exato de ``x / y`` (se o resultado for 0, seu sinal será o sinal de *x*)." -#: ../../library/decimal.rst:1480 +#: ../../library/decimal.rst:1494 msgid "Returns a rotated copy of *x*, *y* times." msgstr "Retorna uma cópia re de *x*, *y* vezes." -#: ../../library/decimal.rst:1485 +#: ../../library/decimal.rst:1499 msgid "Returns ``True`` if the two operands have the same exponent." msgstr "Retorna ``True`` se os dois operandos tiverem o mesmo expoente." -#: ../../library/decimal.rst:1490 +#: ../../library/decimal.rst:1504 msgid "Returns the first operand after adding the second value its exp." msgstr "Retorna o primeiro operando após adicionar o segundo valor seu exp." -#: ../../library/decimal.rst:1495 +#: ../../library/decimal.rst:1509 msgid "Returns a shifted copy of *x*, *y* times." msgstr "Retorna uma cópia deslocada de *x*, *y* vezes." -#: ../../library/decimal.rst:1500 +#: ../../library/decimal.rst:1514 msgid "Square root of a non-negative number to context precision." msgstr "Raiz quadrada de um número não negativo para precisão do contexto." -#: ../../library/decimal.rst:1505 +#: ../../library/decimal.rst:1519 msgid "Return the difference between *x* and *y*." msgstr "Retorna a diferença entre *x* e *y*." -#: ../../library/decimal.rst:1519 +#: ../../library/decimal.rst:1533 msgid "Rounds to an integer." msgstr "Arredonda para um número inteiro." -#: ../../library/decimal.rst:1524 +#: ../../library/decimal.rst:1538 msgid "Converts a number to a string using scientific notation." msgstr "Converte um número em uma string usando notação científica." -#: ../../library/decimal.rst:1531 +#: ../../library/decimal.rst:1545 msgid "Constants" msgstr "Constantes" -#: ../../library/decimal.rst:1533 +#: ../../library/decimal.rst:1547 msgid "" "The constants in this section are only relevant for the C module. They are " "also included in the pure Python version for compatibility." @@ -2098,45 +2520,45 @@ msgstr "" "As constantes nesta seção são relevantes apenas para o módulo C. Eles também " "estão incluídos na versão pura do Python para compatibilidade." -#: ../../library/decimal.rst:1537 +#: ../../library/decimal.rst:1551 msgid "32-bit" msgstr "32 bits" -#: ../../library/decimal.rst:1537 +#: ../../library/decimal.rst:1551 msgid "64-bit" msgstr "64 bits" -#: ../../library/decimal.rst:1539 ../../library/decimal.rst:1541 +#: ../../library/decimal.rst:1553 ../../library/decimal.rst:1555 msgid "``425000000``" msgstr "``425000000``" -#: ../../library/decimal.rst:1539 ../../library/decimal.rst:1541 +#: ../../library/decimal.rst:1553 ../../library/decimal.rst:1555 msgid "``999999999999999999``" msgstr "``999999999999999999``" -#: ../../library/decimal.rst:1543 +#: ../../library/decimal.rst:1557 msgid "``-425000000``" msgstr "``-425000000``" -#: ../../library/decimal.rst:1543 +#: ../../library/decimal.rst:1557 msgid "``-999999999999999999``" msgstr "``-999999999999999999``" -#: ../../library/decimal.rst:1545 +#: ../../library/decimal.rst:1559 msgid "``-849999999``" msgstr "``-849999999``" -#: ../../library/decimal.rst:1545 +#: ../../library/decimal.rst:1559 msgid "``-1999999999999999997``" msgstr "``-1999999999999999997``" -#: ../../library/decimal.rst:1551 +#: ../../library/decimal.rst:1565 msgid "" "The value is ``True``. Deprecated, because Python now always has threads." msgstr "" "O valor é ``True``. Descontinuado porque o Python agora sempre tem threads." -#: ../../library/decimal.rst:1557 +#: ../../library/decimal.rst:1571 msgid "" "The default value is ``True``. If Python is :option:`configured using the --" "without-decimal-contextvar option <--without-decimal-contextvar>`, the C " @@ -2150,41 +2572,41 @@ msgstr "" "será ``False``. Isso é um pouco mais rápido em alguns cenários de contexto " "aninhados." -#: ../../library/decimal.rst:1566 +#: ../../library/decimal.rst:1580 msgid "Rounding modes" msgstr "Modos de arredondamento" -#: ../../library/decimal.rst:1570 +#: ../../library/decimal.rst:1584 msgid "Round towards ``Infinity``." msgstr "Arredonda para ``Infinity``." -#: ../../library/decimal.rst:1574 +#: ../../library/decimal.rst:1588 msgid "Round towards zero." msgstr "Arredonda para zero." -#: ../../library/decimal.rst:1578 +#: ../../library/decimal.rst:1592 msgid "Round towards ``-Infinity``." msgstr "Arredonda para ``-Infinity``." -#: ../../library/decimal.rst:1582 +#: ../../library/decimal.rst:1596 msgid "Round to nearest with ties going towards zero." msgstr "Arrendonda para o mais próximo com empates tendendo a zero." -#: ../../library/decimal.rst:1586 +#: ../../library/decimal.rst:1600 msgid "Round to nearest with ties going to nearest even integer." msgstr "" "Arredonda para o mais próximo com empates indo para o mais próximo inteiro " "par." -#: ../../library/decimal.rst:1590 +#: ../../library/decimal.rst:1604 msgid "Round to nearest with ties going away from zero." msgstr "Arrendonda para o mais próximo com empates se afastando de zero." -#: ../../library/decimal.rst:1594 +#: ../../library/decimal.rst:1608 msgid "Round away from zero." msgstr "Arredonda se afastando de zero." -#: ../../library/decimal.rst:1598 +#: ../../library/decimal.rst:1612 msgid "" "Round away from zero if last digit after rounding towards zero would have " "been 0 or 5; otherwise round towards zero." @@ -2192,11 +2614,11 @@ msgstr "" "Arredonda se afastando de zero se o último dígito após o arredondamento para " "zero fosse 0 ou 5; caso contrário, arredonda para zero." -#: ../../library/decimal.rst:1605 +#: ../../library/decimal.rst:1619 msgid "Signals" msgstr "Sinais" -#: ../../library/decimal.rst:1607 +#: ../../library/decimal.rst:1621 msgid "" "Signals represent conditions that arise during computation. Each corresponds " "to one context flag and one context trap enabler." @@ -2205,7 +2627,7 @@ msgstr "" "corresponde a um sinalizador de contexto e um ativador de armadilha de " "contexto." -#: ../../library/decimal.rst:1610 +#: ../../library/decimal.rst:1624 msgid "" "The context flag is set whenever the condition is encountered. After the " "computation, flags may be checked for informational purposes (for instance, " @@ -2218,7 +2640,7 @@ msgstr "" "de verificar os sinalizadores, certifique-se de limpar todos os " "sinalizadores antes de iniciar o próximo cálculo." -#: ../../library/decimal.rst:1615 +#: ../../library/decimal.rst:1629 msgid "" "If the context's trap enabler is set for the signal, then the condition " "causes a Python exception to be raised. For example, if the :class:" @@ -2230,11 +2652,11 @@ msgstr "" "armadilha :class:`DivisionByZero` for configurada, uma exceção :exc:" "`DivisionByZero` será levantada ao encontrar a condição." -#: ../../library/decimal.rst:1623 +#: ../../library/decimal.rst:1637 msgid "Altered an exponent to fit representation constraints." msgstr "Altera um expoente para ajustar as restrições de representação." -#: ../../library/decimal.rst:1625 +#: ../../library/decimal.rst:1639 msgid "" "Typically, clamping occurs when an exponent falls outside the context's :" "attr:`~Context.Emin` and :attr:`~Context.Emax` limits. If possible, the " @@ -2244,16 +2666,16 @@ msgstr "" "contexto :attr:`~Context.Emin` e :attr:`~Context.Emax`. Se possível, o " "expoente é reduzido para caber adicionando zeros ao coeficiente." -#: ../../library/decimal.rst:1632 +#: ../../library/decimal.rst:1646 msgid "Base class for other signals and a subclass of :exc:`ArithmeticError`." msgstr "" "Classe base para outros sinais e uma subclasse de :exc:`ArithmeticError`." -#: ../../library/decimal.rst:1637 +#: ../../library/decimal.rst:1651 msgid "Signals the division of a non-infinite number by zero." msgstr "Sinaliza a divisão de um número não infinito por zero." -#: ../../library/decimal.rst:1639 +#: ../../library/decimal.rst:1653 msgid "" "Can occur with division, modulo division, or when raising a number to a " "negative power. If this signal is not trapped, returns ``Infinity`` or ``-" @@ -2263,11 +2685,11 @@ msgstr "" "potência negativa. Se este sinal não for capturado, retornará ``Infinity`` " "ou ``-Infinity`` com o sinal determinado pelas entradas do cálculo." -#: ../../library/decimal.rst:1646 +#: ../../library/decimal.rst:1660 msgid "Indicates that rounding occurred and the result is not exact." msgstr "Indica que o arredondamento ocorreu e o resultado não é exato." -#: ../../library/decimal.rst:1648 +#: ../../library/decimal.rst:1662 msgid "" "Signals when non-zero digits were discarded during rounding. The rounded " "result is returned. The signal flag or trap is used to detect when results " @@ -2277,11 +2699,11 @@ msgstr "" "arredondamento. O resultado arredondado é retornado. O sinalizador ou " "armadilha de sinal é usado para detectar quando os resultados são inexatos." -#: ../../library/decimal.rst:1655 +#: ../../library/decimal.rst:1669 msgid "An invalid operation was performed." msgstr "Uma operação inválida foi realizada." -#: ../../library/decimal.rst:1657 +#: ../../library/decimal.rst:1671 msgid "" "Indicates that an operation was requested that does not make sense. If not " "trapped, returns ``NaN``. Possible causes include::" @@ -2289,11 +2711,33 @@ msgstr "" "Indica que uma operação foi solicitada que não faz sentido. Se não for " "capturado, retorna ``NaN``. As possíveis causas incluem::" -#: ../../library/decimal.rst:1673 +#: ../../library/decimal.rst:1674 +msgid "" +"Infinity - Infinity\n" +"0 * Infinity\n" +"Infinity / Infinity\n" +"x % 0\n" +"Infinity % x\n" +"sqrt(-x) and x > 0\n" +"0 ** 0\n" +"x ** (non-integer)\n" +"x ** Infinity" +msgstr "" +"Infinity - Infinity\n" +"0 * Infinity\n" +"Infinity / Infinity\n" +"x % 0\n" +"Infinity % x\n" +"sqrt(-x) and x > 0\n" +"0 ** 0\n" +"x ** (non-integer)\n" +"x ** Infinity" + +#: ../../library/decimal.rst:1687 msgid "Numerical overflow." msgstr "Estouro numérico." -#: ../../library/decimal.rst:1675 +#: ../../library/decimal.rst:1689 msgid "" "Indicates the exponent is larger than :attr:`Context.Emax` after rounding " "has occurred. If not trapped, the result depends on the rounding mode, " @@ -2307,13 +2751,13 @@ msgstr "" "ou arredondando para fora para ``Infinity``. Nos dois casos, :class:" "`Inexact` e :class:`Rounded` também são sinalizados." -#: ../../library/decimal.rst:1684 +#: ../../library/decimal.rst:1698 msgid "Rounding occurred though possibly no information was lost." msgstr "" "O arredondamento ocorreu, embora possivelmente nenhuma informação tenha sido " "perdida." -#: ../../library/decimal.rst:1686 +#: ../../library/decimal.rst:1700 msgid "" "Signaled whenever rounding discards digits; even if those digits are zero " "(such as rounding ``5.00`` to ``5.0``). If not trapped, returns the result " @@ -2324,12 +2768,12 @@ msgstr "" "capturado, retorna o resultado inalterado. Este sinal é usado para detectar " "a perda de dígitos significativos." -#: ../../library/decimal.rst:1694 +#: ../../library/decimal.rst:1708 msgid "Exponent was lower than :attr:`~Context.Emin` prior to rounding." msgstr "" "O expoente foi menor que :attr:`~Context.Emin` antes do arredondamento." -#: ../../library/decimal.rst:1696 +#: ../../library/decimal.rst:1710 msgid "" "Occurs when an operation result is subnormal (the exponent is too small). If " "not trapped, returns the result unchanged." @@ -2337,11 +2781,11 @@ msgstr "" "Ocorre quando um resultado da operação é subnormal (o expoente é muito " "pequeno). Se não for capturado, retorna o resultado inalterado." -#: ../../library/decimal.rst:1702 +#: ../../library/decimal.rst:1716 msgid "Numerical underflow with result rounded to zero." msgstr "Estouro negativo numérico com resultado arredondado para zero." -#: ../../library/decimal.rst:1704 +#: ../../library/decimal.rst:1718 msgid "" "Occurs when a subnormal result is pushed to zero by rounding. :class:" "`Inexact` and :class:`Subnormal` are also signaled." @@ -2349,13 +2793,13 @@ msgstr "" "Ocorre quando um resultado subnormal é empurrado para zero arredondando. :" "class:`Inexact` e :class:`Subnormal` também são sinalizados." -#: ../../library/decimal.rst:1710 +#: ../../library/decimal.rst:1724 msgid "Enable stricter semantics for mixing floats and Decimals." msgstr "" "Ativa semânticas mais rigorosas para misturar objetos de float com de " "Decimal." -#: ../../library/decimal.rst:1712 +#: ../../library/decimal.rst:1726 msgid "" "If the signal is not trapped (default), mixing floats and Decimals is " "permitted in the :class:`~decimal.Decimal` constructor, :meth:`~decimal." @@ -2374,7 +2818,7 @@ msgstr "" "meth:`~decimal.Decimal.from_float` ou :meth:`~decimal.Context." "create_decimal_from_float` não definem o sinalizador." -#: ../../library/decimal.rst:1720 +#: ../../library/decimal.rst:1734 msgid "" "Otherwise (the signal is trapped), only equality comparisons and explicit " "conversions are silent. All other mixed operations raise :exc:" @@ -2384,19 +2828,45 @@ msgstr "" "conversões explícitas são silenciosas. Todas as outras operações mistas " "levantam :exc:`FloatOperation`." -#: ../../library/decimal.rst:1724 +#: ../../library/decimal.rst:1738 msgid "The following table summarizes the hierarchy of signals::" msgstr "A tabela a seguir resume a hierarquia de sinais::" -#: ../../library/decimal.rst:1745 -msgid "Floating-Point Notes" -msgstr "Observações sobre ponto flutuante" - -#: ../../library/decimal.rst:1749 +#: ../../library/decimal.rst:1740 +msgid "" +"exceptions.ArithmeticError(exceptions.Exception)\n" +" DecimalException\n" +" Clamped\n" +" DivisionByZero(DecimalException, exceptions.ZeroDivisionError)\n" +" Inexact\n" +" Overflow(Inexact, Rounded)\n" +" Underflow(Inexact, Rounded, Subnormal)\n" +" InvalidOperation\n" +" Rounded\n" +" Subnormal\n" +" FloatOperation(DecimalException, exceptions.TypeError)" +msgstr "" +"exceptions.ArithmeticError(exceptions.Exception)\n" +" DecimalException\n" +" Clamped\n" +" DivisionByZero(DecimalException, exceptions.ZeroDivisionError)\n" +" Inexact\n" +" Overflow(Inexact, Rounded)\n" +" Underflow(Inexact, Rounded, Subnormal)\n" +" InvalidOperation\n" +" Rounded\n" +" Subnormal\n" +" FloatOperation(DecimalException, exceptions.TypeError)" + +#: ../../library/decimal.rst:1759 +msgid "Floating-point notes" +msgstr "" + +#: ../../library/decimal.rst:1763 msgid "Mitigating round-off error with increased precision" msgstr "Atenuando o erro de arredondamento com maior precisão" -#: ../../library/decimal.rst:1751 +#: ../../library/decimal.rst:1765 msgid "" "The use of decimal floating point eliminates decimal representation error " "(making it possible to represent ``0.1`` exactly); however, some operations " @@ -2408,7 +2878,7 @@ msgstr "" "operações ainda podem sofrer erros de arredondamento quando dígitos " "diferentes de zero excederem a precisão fixa." -#: ../../library/decimal.rst:1755 +#: ../../library/decimal.rst:1769 msgid "" "The effects of round-off error can be amplified by the addition or " "subtraction of nearly offsetting quantities resulting in loss of " @@ -2422,7 +2892,41 @@ msgstr "" "de ponto flutuante arredondado com precisão insuficiente causa a quebra das " "propriedades associativas e distributivas da adição:" -#: ../../library/decimal.rst:1779 +#: ../../library/decimal.rst:1775 +msgid "" +"# Examples from Seminumerical Algorithms, Section 4.2.2.\n" +">>> from decimal import Decimal, getcontext\n" +">>> getcontext().prec = 8\n" +"\n" +">>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')\n" +">>> (u + v) + w\n" +"Decimal('9.5111111')\n" +">>> u + (v + w)\n" +"Decimal('10')\n" +"\n" +">>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')\n" +">>> (u*v) + (u*w)\n" +"Decimal('0.01')\n" +">>> u * (v+w)\n" +"Decimal('0.0060000')" +msgstr "" +"# exemplos de Seminumerical Algorithms, Section 4.2.2.\n" +">>> from decimal import Decimal, getcontext\n" +">>> getcontext().prec = 8\n" +"\n" +">>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')\n" +">>> (u + v) + w\n" +"Decimal('9.5111111')\n" +">>> u + (v + w)\n" +"Decimal('10')\n" +"\n" +">>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')\n" +">>> (u*v) + (u*w)\n" +"Decimal('0.01')\n" +">>> u * (v+w)\n" +"Decimal('0.0060000')" + +#: ../../library/decimal.rst:1793 msgid "" "The :mod:`decimal` module makes it possible to restore the identities by " "expanding the precision sufficiently to avoid loss of significance:" @@ -2430,11 +2934,39 @@ msgstr "" "O módulo :mod:`decimal` permite restaurar as identidades expandindo a " "precisão o suficiente para evitar perda de significância:" -#: ../../library/decimal.rst:1799 +#: ../../library/decimal.rst:1796 +msgid "" +">>> getcontext().prec = 20\n" +">>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')\n" +">>> (u + v) + w\n" +"Decimal('9.51111111')\n" +">>> u + (v + w)\n" +"Decimal('9.51111111')\n" +">>>\n" +">>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')\n" +">>> (u*v) + (u*w)\n" +"Decimal('0.0060000')\n" +">>> u * (v+w)\n" +"Decimal('0.0060000')" +msgstr "" +">>> getcontext().prec = 20\n" +">>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')\n" +">>> (u + v) + w\n" +"Decimal('9.51111111')\n" +">>> u + (v + w)\n" +"Decimal('9.51111111')\n" +">>>\n" +">>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')\n" +">>> (u*v) + (u*w)\n" +"Decimal('0.0060000')\n" +">>> u * (v+w)\n" +"Decimal('0.0060000')" + +#: ../../library/decimal.rst:1813 msgid "Special values" msgstr "Valores especiais" -#: ../../library/decimal.rst:1801 +#: ../../library/decimal.rst:1815 msgid "" "The number system for the :mod:`decimal` module provides special values " "including ``NaN``, ``sNaN``, ``-Infinity``, ``Infinity``, and two zeros, " @@ -2444,7 +2976,7 @@ msgstr "" "incluindo ``NaN``, ``sNaN``, ``-Infinity``, ``Infinity``, e dois zeros, " "``+0`` e ``-0``." -#: ../../library/decimal.rst:1805 +#: ../../library/decimal.rst:1819 msgid "" "Infinities can be constructed directly with: ``Decimal('Infinity')``. Also, " "they can arise from dividing by zero when the :exc:`DivisionByZero` signal " @@ -2458,7 +2990,7 @@ msgstr "" "`Overflow` não é capturado, o infinito pode resultar do arredondamento além " "dos limites do maior número representável." -#: ../../library/decimal.rst:1810 +#: ../../library/decimal.rst:1824 msgid "" "The infinities are signed (affine) and can be used in arithmetic operations " "where they get treated as very large, indeterminate numbers. For instance, " @@ -2469,7 +3001,7 @@ msgstr "" "Por exemplo, adicionar uma constante ao infinito fornece outro resultado " "infinito." -#: ../../library/decimal.rst:1814 +#: ../../library/decimal.rst:1828 msgid "" "Some operations are indeterminate and return ``NaN``, or if the :exc:" "`InvalidOperation` signal is trapped, raise an exception. For example, " @@ -2488,7 +3020,7 @@ msgstr "" "permite que o cálculo continue enquanto sinaliza resultados específicos como " "inválidos." -#: ../../library/decimal.rst:1822 +#: ../../library/decimal.rst:1836 msgid "" "A variant is ``sNaN`` which signals rather than remaining quiet after every " "operation. This is a useful return value when an invalid result needs to " @@ -2498,7 +3030,7 @@ msgstr "" "cada operação. Esse é um valor de retorno útil quando um resultado inválido " "precisa interromper um cálculo para tratamento especial." -#: ../../library/decimal.rst:1826 +#: ../../library/decimal.rst:1840 msgid "" "The behavior of Python's comparison operators can be a little surprising " "where a ``NaN`` is involved. A test for equality where one of the operands " @@ -2529,7 +3061,7 @@ msgstr "" "com os padrões, use os métodos :meth:`~Decimal.compare` e :meth:`~Decimal." "compare_signal`." -#: ../../library/decimal.rst:1839 +#: ../../library/decimal.rst:1853 msgid "" "The signed zeros can result from calculations that underflow. They keep the " "sign that would have resulted if the calculation had been carried out to " @@ -2541,7 +3073,7 @@ msgstr "" "precisão. Como sua magnitude é zero, os zeros positivos e negativos são " "tratados como iguais e seu sinal é informacional." -#: ../../library/decimal.rst:1844 +#: ../../library/decimal.rst:1858 msgid "" "In addition to the two signed zeros which are distinct yet equal, there are " "various representations of zero with differing precisions yet equivalent in " @@ -2555,11 +3087,11 @@ msgstr "" "acostumado a representações de ponto flutuante normalizadas, não é " "imediatamente óbvio que o seguinte cálculo retorne um valor igual a zero:" -#: ../../library/decimal.rst:1859 +#: ../../library/decimal.rst:1873 msgid "Working with threads" msgstr "Trabalhando com threads" -#: ../../library/decimal.rst:1861 +#: ../../library/decimal.rst:1875 msgid "" "The :func:`getcontext` function accesses a different :class:`Context` object " "for each thread. Having separate thread contexts means that threads may " @@ -2571,7 +3103,7 @@ msgstr "" "podem fazer alterações (como ``getcontext().prec=10``) sem interferir em " "outras threads." -#: ../../library/decimal.rst:1865 +#: ../../library/decimal.rst:1879 msgid "" "Likewise, the :func:`setcontext` function automatically assigns its target " "to the current thread." @@ -2579,7 +3111,7 @@ msgstr "" "Da mesma forma, a função :func:`setcontext` atribui automaticamente seu alvo " "à thread atual." -#: ../../library/decimal.rst:1868 +#: ../../library/decimal.rst:1882 msgid "" "If :func:`setcontext` has not been called before :func:`getcontext`, then :" "func:`getcontext` will automatically create a new context for use in the " @@ -2589,7 +3121,7 @@ msgstr "" "então :func:`getcontext` criará automaticamente um novo contexto para uso na " "thread atual." -#: ../../library/decimal.rst:1872 +#: ../../library/decimal.rst:1886 msgid "" "The new context is copied from a prototype context called *DefaultContext*. " "To control the defaults so that each thread will use the same values " @@ -2604,11 +3136,40 @@ msgstr "" "condição de corrida entre as threads chamando :func:`getcontext`. Por " "exemplo::" -#: ../../library/decimal.rst:1897 +#: ../../library/decimal.rst:1892 +msgid "" +"# Set applicationwide defaults for all threads about to be launched\n" +"DefaultContext.prec = 12\n" +"DefaultContext.rounding = ROUND_DOWN\n" +"DefaultContext.traps = ExtendedContext.traps.copy()\n" +"DefaultContext.traps[InvalidOperation] = 1\n" +"setcontext(DefaultContext)\n" +"\n" +"# Afterwards, the threads can be started\n" +"t1.start()\n" +"t2.start()\n" +"t3.start()\n" +" . . ." +msgstr "" +"# Define padrões para todo a aplicação para todas as threads prestes a serem " +"iniciadas\n" +"DefaultContext.prec = 12\n" +"DefaultContext.rounding = ROUND_DOWN\n" +"DefaultContext.traps = ExtendedContext.traps.copy()\n" +"DefaultContext.traps[InvalidOperation] = 1\n" +"setcontext(DefaultContext)\n" +"\n" +"# Depois, as threads podem ser iniciadas\n" +"t1.start()\n" +"t2.start()\n" +"t3.start()\n" +" . . ." + +#: ../../library/decimal.rst:1911 msgid "Recipes" msgstr "Receitas" -#: ../../library/decimal.rst:1899 +#: ../../library/decimal.rst:1913 msgid "" "Here are a few recipes that serve as utility functions and that demonstrate " "ways to work with the :class:`Decimal` class::" @@ -2616,11 +3177,314 @@ msgstr "" "Aqui estão algumas receitas que servem como funções utilitárias e que " "demonstram maneiras de trabalhar com a classe :class:`Decimal`::" -#: ../../library/decimal.rst:2054 +#: ../../library/decimal.rst:1916 +msgid "" +"def moneyfmt(value, places=2, curr='', sep=',', dp='.',\n" +" pos='', neg='-', trailneg=''):\n" +" \"\"\"Convert Decimal to a money formatted string.\n" +"\n" +" places: required number of places after the decimal point\n" +" curr: optional currency symbol before the sign (may be blank)\n" +" sep: optional grouping separator (comma, period, space, or blank)\n" +" dp: decimal point indicator (comma or period)\n" +" only specify as blank when places is zero\n" +" pos: optional sign for positive numbers: '+', space or blank\n" +" neg: optional sign for negative numbers: '-', '(', space or blank\n" +" trailneg:optional trailing minus indicator: '-', ')', space or blank\n" +"\n" +" >>> d = Decimal('-1234567.8901')\n" +" >>> moneyfmt(d, curr='$')\n" +" '-$1,234,567.89'\n" +" >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')\n" +" '1.234.568-'\n" +" >>> moneyfmt(d, curr='$', neg='(', trailneg=')')\n" +" '($1,234,567.89)'\n" +" >>> moneyfmt(Decimal(123456789), sep=' ')\n" +" '123 456 789.00'\n" +" >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')\n" +" '<0.02>'\n" +"\n" +" \"\"\"\n" +" q = Decimal(10) ** -places # 2 places --> '0.01'\n" +" sign, digits, exp = value.quantize(q).as_tuple()\n" +" result = []\n" +" digits = list(map(str, digits))\n" +" build, next = result.append, digits.pop\n" +" if sign:\n" +" build(trailneg)\n" +" for i in range(places):\n" +" build(next() if digits else '0')\n" +" if places:\n" +" build(dp)\n" +" if not digits:\n" +" build('0')\n" +" i = 0\n" +" while digits:\n" +" build(next())\n" +" i += 1\n" +" if i == 3 and digits:\n" +" i = 0\n" +" build(sep)\n" +" build(curr)\n" +" build(neg if sign else pos)\n" +" return ''.join(reversed(result))\n" +"\n" +"def pi():\n" +" \"\"\"Compute Pi to the current precision.\n" +"\n" +" >>> print(pi())\n" +" 3.141592653589793238462643383\n" +"\n" +" \"\"\"\n" +" getcontext().prec += 2 # extra digits for intermediate steps\n" +" three = Decimal(3) # substitute \"three=3.0\" for regular floats\n" +" lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24\n" +" while s != lasts:\n" +" lasts = s\n" +" n, na = n+na, na+8\n" +" d, da = d+da, da+32\n" +" t = (t * n) / d\n" +" s += t\n" +" getcontext().prec -= 2\n" +" return +s # unary plus applies the new precision\n" +"\n" +"def exp(x):\n" +" \"\"\"Return e raised to the power of x. Result type matches input " +"type.\n" +"\n" +" >>> print(exp(Decimal(1)))\n" +" 2.718281828459045235360287471\n" +" >>> print(exp(Decimal(2)))\n" +" 7.389056098930650227230427461\n" +" >>> print(exp(2.0))\n" +" 7.38905609893\n" +" >>> print(exp(2+0j))\n" +" (7.38905609893+0j)\n" +"\n" +" \"\"\"\n" +" getcontext().prec += 2\n" +" i, lasts, s, fact, num = 0, 0, 1, 1, 1\n" +" while s != lasts:\n" +" lasts = s\n" +" i += 1\n" +" fact *= i\n" +" num *= x\n" +" s += num / fact\n" +" getcontext().prec -= 2\n" +" return +s\n" +"\n" +"def cos(x):\n" +" \"\"\"Return the cosine of x as measured in radians.\n" +"\n" +" The Taylor series approximation works best for a small value of x.\n" +" For larger values, first compute x = x % (2 * pi).\n" +"\n" +" >>> print(cos(Decimal('0.5')))\n" +" 0.8775825618903727161162815826\n" +" >>> print(cos(0.5))\n" +" 0.87758256189\n" +" >>> print(cos(0.5+0j))\n" +" (0.87758256189+0j)\n" +"\n" +" \"\"\"\n" +" getcontext().prec += 2\n" +" i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1\n" +" while s != lasts:\n" +" lasts = s\n" +" i += 2\n" +" fact *= i * (i-1)\n" +" num *= x * x\n" +" sign *= -1\n" +" s += num / fact * sign\n" +" getcontext().prec -= 2\n" +" return +s\n" +"\n" +"def sin(x):\n" +" \"\"\"Return the sine of x as measured in radians.\n" +"\n" +" The Taylor series approximation works best for a small value of x.\n" +" For larger values, first compute x = x % (2 * pi).\n" +"\n" +" >>> print(sin(Decimal('0.5')))\n" +" 0.4794255386042030002732879352\n" +" >>> print(sin(0.5))\n" +" 0.479425538604\n" +" >>> print(sin(0.5+0j))\n" +" (0.479425538604+0j)\n" +"\n" +" \"\"\"\n" +" getcontext().prec += 2\n" +" i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1\n" +" while s != lasts:\n" +" lasts = s\n" +" i += 2\n" +" fact *= i * (i-1)\n" +" num *= x * x\n" +" sign *= -1\n" +" s += num / fact * sign\n" +" getcontext().prec -= 2\n" +" return +s" +msgstr "" +"def moneyfmt(value, places=2, curr='', sep=',', dp='.',\n" +" pos='', neg='-', trailneg=''):\n" +" \"\"\"Converte Decimal para uma string formatada de moead.\n" +"\n" +" places: número obrigatório de casas após o ponto decimal\n" +" curr: símbolo de moeda opcional antes do sinal (pode estar em " +"branco)\n" +" sep: separador de agrupamento opcional (vírgula, ponto, espaço ou " +"espaço em branco)\n" +" dp: indicador de ponto decimal (vírgula ou ponto)\n" +" especificar como espaço em branco somente quando places for " +"zero\n" +" pos: sinal opcional para números positivos: '+', espaço ou espaço em " +"branco\n" +" neg: sinal opcional para números negativos: '-', '(', espaço ou " +"espaço em branco\n" +" trailneg:indicador de menos final opcional: '-', ')', espaço ou espaço " +"em branco\n" +"\n" +" >>> d = Decimal('-1234567.8901')\n" +" >>> moneyfmt(d, curr='$')\n" +" '-$1,234,567.89'\n" +" >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')\n" +" '1.234.568-'\n" +" >>> moneyfmt(d, curr='$', neg='(', trailneg=')')\n" +" '($1,234,567.89)'\n" +" >>> moneyfmt(Decimal(123456789), sep=' ')\n" +" '123 456 789.00'\n" +" >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')\n" +" '<0.02>'\n" +"\n" +" \"\"\"\n" +" q = Decimal(10) ** -places # 2 casas --> '0.01'\n" +" sign, digits, exp = value.quantize(q).as_tuple()\n" +" result = []\n" +" digits = list(map(str, digits))\n" +" build, next = result.append, digits.pop\n" +" if sign:\n" +" build(trailneg)\n" +" for i in range(places):\n" +" build(next() if digits else '0')\n" +" if places:\n" +" build(dp)\n" +" if not digits:\n" +" build('0')\n" +" i = 0\n" +" while digits:\n" +" build(next())\n" +" i += 1\n" +" if i == 3 and digits:\n" +" i = 0\n" +" build(sep)\n" +" build(curr)\n" +" build(neg if sign else pos)\n" +" return ''.join(reversed(result))\n" +"\n" +"def pi():\n" +" \"\"\"Compute Pi to the current precision.\n" +"\n" +" >>> print(pi())\n" +" 3.141592653589793238462643383\n" +"\n" +" \"\"\"\n" +" getcontext().prec += 2 # dígitos extras para casas intermediárias\n" +" three = Decimal(3) # substitui \"three=3.0\" para pontos flutuantes " +"regulares\n" +" lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24\n" +" while s != lasts:\n" +" lasts = s\n" +" n, na = n+na, na+8\n" +" d, da = d+da, da+32\n" +" t = (t * n) / d\n" +" s += t\n" +" getcontext().prec -= 2\n" +" return +s # unário com mais aplica a nova precisão\n" +"\n" +"def exp(x):\n" +" \"\"\"Retorna e elevado à potência de x. O tipo de resultado corresponde " +"ao tipo de entrada.\n" +"\n" +" >>> print(exp(Decimal(1)))\n" +" 2.718281828459045235360287471\n" +" >>> print(exp(Decimal(2)))\n" +" 7.389056098930650227230427461\n" +" >>> print(exp(2.0))\n" +" 7.38905609893\n" +" >>> print(exp(2+0j))\n" +" (7.38905609893+0j)\n" +"\n" +" \"\"\"\n" +" getcontext().prec += 2\n" +" i, lasts, s, fact, num = 0, 0, 1, 1, 1\n" +" while s != lasts:\n" +" lasts = s\n" +" i += 1\n" +" fact *= i\n" +" num *= x\n" +" s += num / fact\n" +" getcontext().prec -= 2\n" +" return +s\n" +"\n" +"def cos(x):\n" +" \"\"\"Retorna o cosseno de x medido em radianos.\n" +"\n" +" A aproximação da série de Taylor funciona melhor para um valor pequeno " +"de x.\n" +" Para valores maiores, primeiro calcule x = x % (2 * pi).\n" +"\n" +" >>> print(cos(Decimal('0.5')))\n" +" 0.8775825618903727161162815826\n" +" >>> print(cos(0.5))\n" +" 0.87758256189\n" +" >>> print(cos(0.5+0j))\n" +" (0.87758256189+0j)\n" +"\n" +" \"\"\"\n" +" getcontext().prec += 2\n" +" i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1\n" +" while s != lasts:\n" +" lasts = s\n" +" i += 2\n" +" fact *= i * (i-1)\n" +" num *= x * x\n" +" sign *= -1\n" +" s += num / fact * sign\n" +" getcontext().prec -= 2\n" +" return +s\n" +"\n" +"def sin(x):\n" +" \"\"\"Retorna o seno de x medido em radianos.\n" +"\n" +" A aproximação da série de Taylor funciona melhor para um valor pequeno " +"de x.\n" +" Para valores maiores, primeiro calcule x = x % (2 * pi).\n" +"\n" +" >>> print(sin(Decimal('0.5')))\n" +" 0.4794255386042030002732879352\n" +" >>> print(sin(0.5))\n" +" 0.479425538604\n" +" >>> print(sin(0.5+0j))\n" +" (0.479425538604+0j)\n" +"\n" +" \"\"\"\n" +" getcontext().prec += 2\n" +" i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1\n" +" while s != lasts:\n" +" lasts = s\n" +" i += 2\n" +" fact *= i * (i-1)\n" +" num *= x * x\n" +" sign *= -1\n" +" s += num / fact * sign\n" +" getcontext().prec -= 2\n" +" return +s" + +#: ../../library/decimal.rst:2068 msgid "Decimal FAQ" -msgstr "Perguntas frequentes sobre Decimal" +msgstr "FAQ sobre Decimal" -#: ../../library/decimal.rst:2056 +#: ../../library/decimal.rst:2070 msgid "" "Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way " "to minimize typing when using the interactive interpreter?" @@ -2628,11 +3492,11 @@ msgstr "" "P. É complicado digitar ``decimal.Decimal('1234.5')``. Existe uma maneira de " "minimizar a digitação ao usar o interpretador interativo?" -#: ../../library/decimal.rst:2059 +#: ../../library/decimal.rst:2073 msgid "A. Some users abbreviate the constructor to just a single letter:" msgstr "R. Alguns usuários abreviam o construtor para apenas uma única letra:" -#: ../../library/decimal.rst:2065 +#: ../../library/decimal.rst:2079 msgid "" "Q. In a fixed-point application with two decimal places, some inputs have " "many places and need to be rounded. Others are not supposed to have excess " @@ -2642,7 +3506,7 @@ msgstr "" "têm muitas casas e precisam ser arredondadas. Outros não devem ter dígitos " "em excesso e precisam ser validados. Quais métodos devem ser usados?" -#: ../../library/decimal.rst:2069 +#: ../../library/decimal.rst:2083 msgid "" "A. The :meth:`~Decimal.quantize` method rounds to a fixed number of decimal " "places. If the :const:`Inexact` trap is set, it is also useful for " @@ -2652,7 +3516,7 @@ msgstr "" "decimais. Se a armadilha :const:`Inexact` estiver configurada, também será " "útil para validação:" -#: ../../library/decimal.rst:2087 +#: ../../library/decimal.rst:2101 msgid "" "Q. Once I have valid two place inputs, how do I maintain that invariant " "throughout an application?" @@ -2660,7 +3524,7 @@ msgstr "" "P. Assim que eu tiver entradas de duas casas válidas, como mantenho essa " "invariante em uma aplicação?" -#: ../../library/decimal.rst:2090 +#: ../../library/decimal.rst:2104 msgid "" "A. Some operations like addition, subtraction, and multiplication by an " "integer will automatically preserve fixed point. Others operations, like " @@ -2672,7 +3536,7 @@ msgstr "" "divisão e multiplicação não inteira, alteram o número de casas decimais e " "precisam ser seguidas com uma etapa :meth:`~Decimal.quantize`:" -#: ../../library/decimal.rst:2108 +#: ../../library/decimal.rst:2122 msgid "" "In developing fixed-point applications, it is convenient to define functions " "to handle the :meth:`~Decimal.quantize` step:" @@ -2680,7 +3544,7 @@ msgstr "" "No desenvolvimento de aplicações de ponto fixo, é conveniente definir " "funções para manipular a etapa :meth:`~Decimal.quantize`:" -#: ../../library/decimal.rst:2122 +#: ../../library/decimal.rst:2136 msgid "" "Q. There are many ways to express the same value. The numbers ``200``, " "``200.000``, ``2E2``, and ``.02E+4`` all have the same value at various " @@ -2692,7 +3556,7 @@ msgstr "" "precisões. Existe uma maneira de transformá-los em um único valor canônico " "reconhecível?" -#: ../../library/decimal.rst:2127 +#: ../../library/decimal.rst:2141 msgid "" "A. The :meth:`~Decimal.normalize` method maps all equivalent values to a " "single representative:" @@ -2700,11 +3564,11 @@ msgstr "" "R. O método :meth:`~Decimal.normalize` mapeia todos os valores equivalentes " "para um único representativo:" -#: ../../library/decimal.rst:2134 +#: ../../library/decimal.rst:2148 msgid "Q. When does rounding occur in a computation?" msgstr "P. Quando ocorre o arredondamento em um cálculo?" -#: ../../library/decimal.rst:2136 +#: ../../library/decimal.rst:2150 msgid "" "A. It occurs *after* the computation. The philosophy of the decimal " "specification is that numbers are considered exact and are created " @@ -2719,7 +3583,33 @@ msgstr "" "de cálculo com essas entradas exatas e, em seguida, o arredondamento (ou " "outras operações de contexto) é aplicado ao *resultado* do cálculo::" -#: ../../library/decimal.rst:2154 +#: ../../library/decimal.rst:2157 +msgid "" +">>> getcontext().prec = 5\n" +">>> pi = Decimal('3.1415926535') # More than 5 digits\n" +">>> pi # All digits are retained\n" +"Decimal('3.1415926535')\n" +">>> pi + 0 # Rounded after an addition\n" +"Decimal('3.1416')\n" +">>> pi - Decimal('0.00005') # Subtract unrounded numbers, then round\n" +"Decimal('3.1415')\n" +">>> pi + 0 - Decimal('0.00005'). # Intermediate values are rounded\n" +"Decimal('3.1416')" +msgstr "" +">>> getcontext().prec = 5\n" +">>> pi = Decimal('3.1415926535') # Mais de 5 dígitos\n" +">>> pi # Todos os dígitos são retidos\n" +"Decimal('3.1415926535')\n" +">>> pi + 0 # Arredondado após uma adição\n" +"Decimal('3.1416')\n" +">>> pi - Decimal('0.00005') # Subtrai números não arredondados e " +"depois arredonda\n" +"Decimal('3.1415')\n" +">>> pi + 0 - Decimal('0.00005'). # Os valores intermediários são " +"arredondados\n" +"Decimal('3.1416')" + +#: ../../library/decimal.rst:2168 msgid "" "Q. Some decimal values always print with exponential notation. Is there a " "way to get a non-exponential representation?" @@ -2727,7 +3617,7 @@ msgstr "" "P. Alguns valores decimais sempre são exibidas com notação exponencial. " "Existe uma maneira de obter uma representação não exponencial?" -#: ../../library/decimal.rst:2157 +#: ../../library/decimal.rst:2171 msgid "" "A. For some values, exponential notation is the only way to express the " "number of significant places in the coefficient. For example, expressing " @@ -2739,7 +3629,7 @@ msgstr "" "``5.0E+3`` como ``5000`` mantém o valor constante, mas não pode mostrar a " "significância de duas casa do original." -#: ../../library/decimal.rst:2162 +#: ../../library/decimal.rst:2176 msgid "" "If an application does not care about tracking significance, it is easy to " "remove the exponent and trailing zeroes, losing significance, but keeping " @@ -2749,12 +3639,12 @@ msgstr "" "remover o expoente e os zeros à direita, perdendo a significância, mas " "mantendo o valor inalterado:" -#: ../../library/decimal.rst:2172 +#: ../../library/decimal.rst:2186 msgid "Q. Is there a way to convert a regular float to a :class:`Decimal`?" msgstr "" "P. Existe uma maneira de converter um float comum em um :class:`Decimal`?" -#: ../../library/decimal.rst:2174 +#: ../../library/decimal.rst:2188 msgid "" "A. Yes, any binary floating-point number can be exactly expressed as a " "Decimal though an exact conversion may take more precision than intuition " @@ -2764,7 +3654,15 @@ msgstr "" "exatamente como um Decimal, embora uma conversão exata possa exigir mais " "precisão do que a intuição sugere:" -#: ../../library/decimal.rst:2183 +#: ../../library/decimal.rst:2192 +msgid "" +">>> Decimal(math.pi)\n" +"Decimal('3.141592653589793115997963468544185161590576171875')" +msgstr "" +">>> Decimal(math.pi)\n" +"Decimal('3.141592653589793115997963468544185161590576171875')" + +#: ../../library/decimal.rst:2197 msgid "" "Q. Within a complex calculation, how can I make sure that I haven't gotten a " "spurious result because of insufficient precision or rounding anomalies." @@ -2773,7 +3671,7 @@ msgstr "" "resultado falso devido à precisão insuficiente ou a anomalias de " "arredondamento." -#: ../../library/decimal.rst:2186 +#: ../../library/decimal.rst:2200 msgid "" "A. The decimal module makes it easy to test results. A best practice is to " "re-run calculations using greater precision and with various rounding modes. " @@ -2786,7 +3684,7 @@ msgstr "" "insuficiente, problemas no modo de arredondamento, entradas mal " "condicionadas ou um algoritmo numericamente instável." -#: ../../library/decimal.rst:2191 +#: ../../library/decimal.rst:2205 msgid "" "Q. I noticed that context precision is applied to the results of operations " "but not to the inputs. Is there anything to watch out for when mixing " @@ -2796,7 +3694,7 @@ msgstr "" "mas não às entradas. Há algo a observar ao misturar valores de diferentes " "precisões?" -#: ../../library/decimal.rst:2195 +#: ../../library/decimal.rst:2209 msgid "" "A. Yes. The principle is that all values are considered to be exact and so " "is the arithmetic on those values. Only the results are rounded. The " @@ -2810,7 +3708,21 @@ msgstr "" "desvantagem é que os resultados podem parecer estranhos se você esquecer que " "as entradas não foram arredondadas:" -#: ../../library/decimal.rst:2208 +#: ../../library/decimal.rst:2214 +msgid "" +">>> getcontext().prec = 3\n" +">>> Decimal('3.104') + Decimal('2.104')\n" +"Decimal('5.21')\n" +">>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')\n" +"Decimal('5.20')" +msgstr "" +">>> getcontext().prec = 3\n" +">>> Decimal('3.104') + Decimal('2.104')\n" +"Decimal('5.21')\n" +">>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')\n" +"Decimal('5.20')" + +#: ../../library/decimal.rst:2222 msgid "" "The solution is either to increase precision or to force rounding of inputs " "using the unary plus operation:" @@ -2818,7 +3730,17 @@ msgstr "" "A solução é aumentar a precisão ou forçar o arredondamento das entradas " "usando a operação unária de mais:" -#: ../../library/decimal.rst:2217 +#: ../../library/decimal.rst:2225 +msgid "" +">>> getcontext().prec = 3\n" +">>> +Decimal('1.23456789') # unary plus triggers rounding\n" +"Decimal('1.23')" +msgstr "" +">>> getcontext().prec = 3\n" +">>> +Decimal('1.23456789') # unary plus triggers rounding\n" +"Decimal('1.23')" + +#: ../../library/decimal.rst:2231 msgid "" "Alternatively, inputs can be rounded upon creation using the :meth:`Context." "create_decimal` method:" @@ -2826,11 +3748,11 @@ msgstr "" "Como alternativa, as entradas podem ser arredondadas na criação usando o " "método :meth:`Context.create_decimal`:" -#: ../../library/decimal.rst:2223 +#: ../../library/decimal.rst:2237 msgid "Q. Is the CPython implementation fast for large numbers?" msgstr "P. A implementação do CPython é rápida para números grandes?" -#: ../../library/decimal.rst:2225 +#: ../../library/decimal.rst:2239 msgid "" "A. Yes. In the CPython and PyPy3 implementations, the C/CFFI versions of " "the decimal module integrate the high speed `libmpdec `_ para " "números muito grandes." -#: ../../library/decimal.rst:2235 +#: ../../library/decimal.rst:2249 msgid "" "The context must be adapted for exact arbitrary precision arithmetic. :attr:" "`~Context.Emin` and :attr:`~Context.Emax` should always be set to the " @@ -2864,7 +3786,7 @@ msgstr "" "configurados com os valores máximos, :attr:`~Context.clamp` deve sempre ser " "0 (o padrão). A configuração de :attr:`~Context.prec` requer alguns cuidados." -#: ../../library/decimal.rst:2239 +#: ../../library/decimal.rst:2253 msgid "" "The easiest approach for trying out bignum arithmetic is to use the maximum " "value for :attr:`~Context.prec` as well [#]_::" @@ -2872,15 +3794,39 @@ msgstr "" "A abordagem mais fácil para testar a aritmética do bignum é usar o valor " "máximo para :attr:`~Context.prec` também [#]_::" -#: ../../library/decimal.rst:2248 +#: ../../library/decimal.rst:2256 +msgid "" +">>> setcontext(Context(prec=MAX_PREC, Emax=MAX_EMAX, Emin=MIN_EMIN))\n" +">>> x = Decimal(2) ** 256\n" +">>> x / 128\n" +"Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312')" +msgstr "" +">>> setcontext(Context(prec=MAX_PREC, Emax=MAX_EMAX, Emin=MIN_EMIN))\n" +">>> x = Decimal(2) ** 256\n" +">>> x / 128\n" +"Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312')" + +#: ../../library/decimal.rst:2262 msgid "" -"For inexact results, :attr:`MAX_PREC` is far too large on 64-bit platforms " +"For inexact results, :const:`MAX_PREC` is far too large on 64-bit platforms " "and the available memory will be insufficient::" msgstr "" -"Para resultados inexatos, :attr:`MAX_PREC` é muito grande em plataformas de " +"Para resultados inexatos, :const:`MAX_PREC` é muito grande em plataformas de " "64 bits e a memória disponível será insuficiente::" -#: ../../library/decimal.rst:2256 +#: ../../library/decimal.rst:2265 +msgid "" +">>> Decimal(1) / 3\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"MemoryError" +msgstr "" +">>> Decimal(1) / 3\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"MemoryError" + +#: ../../library/decimal.rst:2270 msgid "" "On systems with overallocation (e.g. Linux), a more sophisticated approach " "is to adjust :attr:`~Context.prec` to the amount of available RAM. Suppose " @@ -2892,7 +3838,52 @@ msgstr "" "Suponha que você tenha 8 GB de RAM e espere 10 operandos simultâneos usando " "no máximo 500 MB cada::" -#: ../../library/decimal.rst:2280 +#: ../../library/decimal.rst:2274 +msgid "" +">>> import sys\n" +">>>\n" +">>> # Maximum number of digits for a single operand using 500MB in 8-byte " +"words\n" +">>> # with 19 digits per word (4-byte and 9 digits for the 32-bit build):\n" +">>> maxdigits = 19 * ((500 * 1024**2) // 8)\n" +">>>\n" +">>> # Check that this works:\n" +">>> c = Context(prec=maxdigits, Emax=MAX_EMAX, Emin=MIN_EMIN)\n" +">>> c.traps[Inexact] = True\n" +">>> setcontext(c)\n" +">>>\n" +">>> # Fill the available precision with nines:\n" +">>> x = Decimal(0).logical_invert() * 9\n" +">>> sys.getsizeof(x)\n" +"524288112\n" +">>> x + 2\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" decimal.Inexact: []" +msgstr "" +">>> import sys\n" +">>>\n" +">>> # Número máximo de dígitos para um único operando usando 500 MB\n" +">>> # em palavras de 8 bytes com 19 dígitos por palavra (4 bytes e 9 " +"dígitos\n" +">>> # para a construção de 32 bits):\n" +">>> maxdigits = 19 * ((500 * 1024**2) // 8)\n" +">>>\n" +">>> # Confere que isso funciona:\n" +">>> c = Context(prec=maxdigits, Emax=MAX_EMAX, Emin=MIN_EMIN)\n" +">>> c.traps[Inexact] = True\n" +">>> setcontext(c)\n" +">>>\n" +">>> # Preenche a precisão disponível com noves:\n" +">>> x = Decimal(0).logical_invert() * 9\n" +">>> sys.getsizeof(x)\n" +"524288112\n" +">>> x + 2\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" decimal.Inexact: []" + +#: ../../library/decimal.rst:2294 msgid "" "In general (and especially on systems without overallocation), it is " "recommended to estimate even tighter bounds and set the :attr:`Inexact` trap " @@ -2902,7 +3893,7 @@ msgstr "" "estimar limites ainda mais apertados e definir a armadilha :attr:`Inexact` " "se for esperado que todos os cálculos sejam mais precisos." -#: ../../library/decimal.rst:2289 +#: ../../library/decimal.rst:2303 msgid "" "This approach now works for all exact results except for non-integer powers." msgstr "" diff --git a/library/development.po b/library/development.po index 2bf5bab61..d4c52cb75 100644 --- a/library/development.po +++ b/library/development.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:04+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/devmode.po b/library/devmode.po index 179f1f90b..6ad27ffae 100644 --- a/library/devmode.po +++ b/library/devmode.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# a76d6fb6142d7607ab0526dcbddb02d7_7bf0da0 <3b5fb0f281c8dfb4c0170f2ee2a6cfcf_843623>, 2021 -# Rafael Fontenelle , 2023 -# Vitor Buxbaum Orlandi, 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:04+0000\n" -"Last-Translator: Vitor Buxbaum Orlandi, 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -66,6 +64,12 @@ msgstr "" "A ativação do Modo de Desenvolvimento do Python é semelhante ao comando a " "seguir, mas com efeitos adicionais descritos abaixo::" +#: ../../library/devmode.rst:24 +msgid "" +"PYTHONMALLOC=debug PYTHONASYNCIODEBUG=1 python -W default -X faulthandler" +msgstr "" +"PYTHONMALLOC=debug PYTHONASYNCIODEBUG=1 python -W default -X faulthandler" + #: ../../library/devmode.rst:26 msgid "Effects of the Python Development Mode:" msgstr "Efeitos do Modo de Desenvolvimento do Python:" @@ -294,6 +298,30 @@ msgstr "" "Exemplo de um script que conta o número de linhas do arquivo texto " "especificado na linha de comando::" +#: ../../library/devmode.rst:116 +msgid "" +"import sys\n" +"\n" +"def main():\n" +" fp = open(sys.argv[1])\n" +" nlines = len(fp.readlines())\n" +" print(nlines)\n" +" # The file is closed implicitly\n" +"\n" +"if __name__ == \"__main__\":\n" +" main()" +msgstr "" +"import sys\n" +"\n" +"def main():\n" +" fp = open(sys.argv[1])\n" +" nlines = len(fp.readlines())\n" +" print(nlines)\n" +" # O arquivo é fechado implicitamente\n" +"\n" +"if __name__ == \"__main__\":\n" +" main()" + #: ../../library/devmode.rst:127 msgid "" "The script does not close the file explicitly. By default, Python does not " @@ -302,6 +330,14 @@ msgstr "" "O script não fecha o arquivo explicitamente. Por padrão, o Python não emite " "nenhum aviso. Exemplo usando README.txt, que possui 269 linhas:" +#: ../../library/devmode.rst:130 +msgid "" +"$ python script.py README.txt\n" +"269" +msgstr "" +"$ python script.py README.txt\n" +"269" + #: ../../library/devmode.rst:135 msgid "" "Enabling the Python Development Mode displays a :exc:`ResourceWarning` " @@ -310,6 +346,22 @@ msgstr "" "A ativação do Modo de Desenvolvimento do Python exibe um aviso :exc:" "`ResourceWarning`:" +#: ../../library/devmode.rst:137 +msgid "" +"$ python -X dev script.py README.txt\n" +"269\n" +"script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='README." +"rst' mode='r' encoding='UTF-8'>\n" +" main()\n" +"ResourceWarning: Enable tracemalloc to get the object allocation traceback" +msgstr "" +"$ python -X dev script.py README.txt\n" +"269\n" +"script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='README." +"rst' mode='r' encoding='UTF-8'>\n" +" main()\n" +"ResourceWarning: Enable tracemalloc to get the object allocation traceback" + #: ../../library/devmode.rst:145 msgid "" "In addition, enabling :mod:`tracemalloc` shows the line where the file was " @@ -318,6 +370,30 @@ msgstr "" "Além disso, ativar :mod:`tracemalloc` mostra a linha em que o arquivo foi " "aberto:" +#: ../../library/devmode.rst:148 +msgid "" +"$ python -X dev -X tracemalloc=5 script.py README.rst\n" +"269\n" +"script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='README." +"rst' mode='r' encoding='UTF-8'>\n" +" main()\n" +"Object allocated at (most recent call last):\n" +" File \"script.py\", lineno 10\n" +" main()\n" +" File \"script.py\", lineno 4\n" +" fp = open(sys.argv[1])" +msgstr "" +"$ python -X dev -X tracemalloc=5 script.py README.rst\n" +"269\n" +"script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='README." +"rst' mode='r' encoding='UTF-8'>\n" +" main()\n" +"Object allocated at (most recent call last):\n" +" File \"script.py\", lineno 10\n" +" main()\n" +" File \"script.py\", lineno 4\n" +" fp = open(sys.argv[1])" + #: ../../library/devmode.rst:160 msgid "" "The fix is to close explicitly the file. Example using a context manager::" @@ -325,6 +401,20 @@ msgstr "" "A correção é fechar explicitamente o arquivo. Exemplo usando um gerenciador " "de contexto::" +#: ../../library/devmode.rst:162 +msgid "" +"def main():\n" +" # Close the file explicitly when exiting the with block\n" +" with open(sys.argv[1]) as fp:\n" +" nlines = len(fp.readlines())\n" +" print(nlines)" +msgstr "" +"def main():\n" +" # Fecha o arquivo explicitamente ao sair do bloco with\n" +" with open(sys.argv[1]) as fp:\n" +" nlines = len(fp.readlines())\n" +" print(nlines)" + #: ../../library/devmode.rst:168 msgid "" "Not closing a resource explicitly can leave a resource open for way longer " @@ -345,10 +435,42 @@ msgstr "Exemplo de erro de descritor de arquivo inválido" msgid "Script displaying the first line of itself::" msgstr "Script exibindo sua própria primeira linha::" +#: ../../library/devmode.rst:179 +msgid "" +"import os\n" +"\n" +"def main():\n" +" fp = open(__file__)\n" +" firstline = fp.readline()\n" +" print(firstline.rstrip())\n" +" os.close(fp.fileno())\n" +" # The file is closed implicitly\n" +"\n" +"main()" +msgstr "" +"import os\n" +"\n" +"def main():\n" +" fp = open(__file__)\n" +" firstline = fp.readline()\n" +" print(firstline.rstrip())\n" +" os.close(fp.fileno())\n" +" # O arquivo é fechado explicitamente\n" +"\n" +"main()" + #: ../../library/devmode.rst:190 msgid "By default, Python does not emit any warning:" msgstr "Por padrão, o Python não emite qualquer aviso:" +#: ../../library/devmode.rst:192 +msgid "" +"$ python script.py\n" +"import os" +msgstr "" +"$ python script.py\n" +"import os" + #: ../../library/devmode.rst:197 msgid "" "The Python Development Mode shows a :exc:`ResourceWarning` and logs a \"Bad " @@ -357,6 +479,34 @@ msgstr "" "O Modo de Desenvolvimento do Python mostra uma :exc:`ResourceWarning` e " "registra um erro \"Bad file descriptor\" ao finalizar o objeto arquivo:" +#: ../../library/devmode.rst:200 +msgid "" +"$ python -X dev script.py\n" +"import os\n" +"script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='script." +"py' mode='r' encoding='UTF-8'>\n" +" main()\n" +"ResourceWarning: Enable tracemalloc to get the object allocation traceback\n" +"Exception ignored in: <_io.TextIOWrapper name='script.py' mode='r' " +"encoding='UTF-8'>\n" +"Traceback (most recent call last):\n" +" File \"script.py\", line 10, in \n" +" main()\n" +"OSError: [Errno 9] Bad file descriptor" +msgstr "" +"$ python -X dev script.py\n" +"import os\n" +"script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='script." +"py' mode='r' encoding='UTF-8'>\n" +" main()\n" +"ResourceWarning: Enable tracemalloc to get the object allocation traceback\n" +"Exception ignored in: <_io.TextIOWrapper name='script.py' mode='r' " +"encoding='UTF-8'>\n" +"Traceback (most recent call last):\n" +" File \"script.py\", line 10, in \n" +" main()\n" +"OSError: [Errno 9] Bad file descriptor" + #: ../../library/devmode.rst:213 msgid "" "``os.close(fp.fileno())`` closes the file descriptor. When the file object " diff --git a/library/dialog.po b/library/dialog.po index e9d714812..a68cebff2 100644 --- a/library/dialog.po +++ b/library/dialog.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# João Porfirio, 2021 -# Rafael Fontenelle , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 01:04+0000\n" -"Last-Translator: Rafael Fontenelle , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -101,7 +100,7 @@ msgid "" msgstr "" "As seguintes classes e funções fornecem janelas de diálogo de arquivo que " "combinam uma aparência nativa com opções de configuração para personalizar o " -"comportamento. Os seguintes argumentos nomeados são aplicáveis ​​às classes e " +"comportamento. Os seguintes argumentos nomeados são aplicáveis às classes e " "funções listado abaixo:" #: ../../library/dialog.rst:0 diff --git a/library/difflib.po b/library/difflib.po index bf6284ead..8e136a97b 100644 --- a/library/difflib.po +++ b/library/difflib.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Marco Rougeth , 2021 -# Welington Carlos , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Marcos Wenneton Araújo , 2021 -# i17obot , 2021 -# Vitor Buxbaum Orlandi, 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:04+0000\n" -"Last-Translator: Vitor Buxbaum Orlandi, 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -444,6 +438,10 @@ msgid "" "ignored. For example, pass::" msgstr "" +#: ../../library/difflib.rst:375 +msgid "lambda x: x in \" \\t\"" +msgstr "" + #: ../../library/difflib.rst:377 msgid "" "if you're comparing lines as sequences of characters, and don't want to " @@ -566,6 +564,13 @@ msgid "" "triples always describe non-adjacent equal blocks." msgstr "" +#: ../../library/difflib.rst:479 +msgid "" +">>> s = SequenceMatcher(None, \"abxcd\", \"abcd\")\n" +">>> s.get_matching_blocks()\n" +"[Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]" +msgstr "" + #: ../../library/difflib.rst:488 msgid "" "Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is " @@ -620,6 +625,21 @@ msgstr "" msgid "For example::" msgstr "Por exemplo::" +#: ../../library/difflib.rst:514 +msgid "" +">>> a = \"qabxcd\"\n" +">>> b = \"abycdf\"\n" +">>> s = SequenceMatcher(None, a, b)\n" +">>> for tag, i1, i2, j1, j2 in s.get_opcodes():\n" +"... print('{:7} a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format(\n" +"... tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2]))\n" +"delete a[0:1] --> b[0:0] 'q' --> ''\n" +"equal a[1:3] --> b[0:2] 'ab' --> 'ab'\n" +"replace a[3:4] --> b[2:3] 'x' --> 'y'\n" +"equal a[4:6] --> b[3:5] 'cd' --> 'cd'\n" +"insert a[6:6] --> b[5:6] '' --> 'f'" +msgstr "" + #: ../../library/difflib.rst:529 msgid "Return a :term:`generator` of groups with up to *n* lines of context." msgstr "" @@ -660,6 +680,14 @@ msgid "" "arguments. For instance::" msgstr "" +#: ../../library/difflib.rst:557 +msgid "" +">>> SequenceMatcher(None, 'tide', 'diet').ratio()\n" +"0.25\n" +">>> SequenceMatcher(None, 'diet', 'tide').ratio()\n" +"0.5" +msgstr "" + #: ../../library/difflib.rst:565 msgid "Return an upper bound on :meth:`ratio` relatively quickly." msgstr "" @@ -834,6 +862,73 @@ msgid "" "This example shows how to use difflib to create a ``diff``-like utility." msgstr "" +#: ../../library/difflib.rst:761 +msgid "" +"\"\"\" Command line interface to difflib.py providing diffs in four " +"formats:\n" +"\n" +"* ndiff: lists every line and highlights interline changes.\n" +"* context: highlights clusters of changes in a before/after format.\n" +"* unified: highlights clusters of changes in an inline format.\n" +"* html: generates side by side comparison with change highlights.\n" +"\n" +"\"\"\"\n" +"\n" +"import sys, os, difflib, argparse\n" +"from datetime import datetime, timezone\n" +"\n" +"def file_mtime(path):\n" +" t = datetime.fromtimestamp(os.stat(path).st_mtime,\n" +" timezone.utc)\n" +" return t.astimezone().isoformat()\n" +"\n" +"def main():\n" +"\n" +" parser = argparse.ArgumentParser()\n" +" parser.add_argument('-c', action='store_true', default=False,\n" +" help='Produce a context format diff (default)')\n" +" parser.add_argument('-u', action='store_true', default=False,\n" +" help='Produce a unified format diff')\n" +" parser.add_argument('-m', action='store_true', default=False,\n" +" help='Produce HTML side by side diff '\n" +" '(can use -c and -l in conjunction)')\n" +" parser.add_argument('-n', action='store_true', default=False,\n" +" help='Produce a ndiff format diff')\n" +" parser.add_argument('-l', '--lines', type=int, default=3,\n" +" help='Set number of context lines (default 3)')\n" +" parser.add_argument('fromfile')\n" +" parser.add_argument('tofile')\n" +" options = parser.parse_args()\n" +"\n" +" n = options.lines\n" +" fromfile = options.fromfile\n" +" tofile = options.tofile\n" +"\n" +" fromdate = file_mtime(fromfile)\n" +" todate = file_mtime(tofile)\n" +" with open(fromfile) as ff:\n" +" fromlines = ff.readlines()\n" +" with open(tofile) as tf:\n" +" tolines = tf.readlines()\n" +"\n" +" if options.u:\n" +" diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, " +"fromdate, todate, n=n)\n" +" elif options.n:\n" +" diff = difflib.ndiff(fromlines, tolines)\n" +" elif options.m:\n" +" diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile," +"tofile,context=options.c,numlines=n)\n" +" else:\n" +" diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, " +"fromdate, todate, n=n)\n" +"\n" +" sys.stdout.writelines(diff)\n" +"\n" +"if __name__ == '__main__':\n" +" main()\n" +msgstr "" + #: ../../library/difflib.rst:764 msgid "ndiff example" msgstr "" @@ -841,3 +936,120 @@ msgstr "" #: ../../library/difflib.rst:766 msgid "This example shows how to use :func:`difflib.ndiff`." msgstr "" + +#: ../../library/difflib.rst:768 +msgid "" +"\"\"\"ndiff [-q] file1 file2\n" +" or\n" +"ndiff (-r1 | -r2) < ndiff_output > file1_or_file2\n" +"\n" +"Print a human-friendly file difference report to stdout. Both inter-\n" +"and intra-line differences are noted. In the second form, recreate file1\n" +"(-r1) or file2 (-r2) on stdout, from an ndiff report on stdin.\n" +"\n" +"In the first form, if -q (\"quiet\") is not specified, the first two lines\n" +"of output are\n" +"\n" +"-: file1\n" +"+: file2\n" +"\n" +"Each remaining line begins with a two-letter code:\n" +"\n" +" \"- \" line unique to file1\n" +" \"+ \" line unique to file2\n" +" \" \" line common to both files\n" +" \"? \" line not present in either input file\n" +"\n" +"Lines beginning with \"? \" attempt to guide the eye to intraline\n" +"differences, and were not present in either input file. These lines can be\n" +"confusing if the source files contain tab characters.\n" +"\n" +"The first file can be recovered by retaining only lines that begin with\n" +"\" \" or \"- \", and deleting those 2-character prefixes; use ndiff with -" +"r1.\n" +"\n" +"The second file can be recovered similarly, but by retaining only \" \" " +"and\n" +"\"+ \" lines; use ndiff with -r2; or, on Unix, the second file can be\n" +"recovered by piping the output through\n" +"\n" +" sed -n '/^[+ ] /s/^..//p'\n" +"\"\"\"\n" +"\n" +"__version__ = 1, 7, 0\n" +"\n" +"import difflib, sys\n" +"\n" +"def fail(msg):\n" +" out = sys.stderr.write\n" +" out(msg + \"\\n\\n\")\n" +" out(__doc__)\n" +" return 0\n" +"\n" +"# open a file & return the file object; gripe and return 0 if it\n" +"# couldn't be opened\n" +"def fopen(fname):\n" +" try:\n" +" return open(fname)\n" +" except IOError as detail:\n" +" return fail(\"couldn't open \" + fname + \": \" + str(detail))\n" +"\n" +"# open two files & spray the diff to stdout; return false iff a problem\n" +"def fcompare(f1name, f2name):\n" +" f1 = fopen(f1name)\n" +" f2 = fopen(f2name)\n" +" if not f1 or not f2:\n" +" return 0\n" +"\n" +" a = f1.readlines(); f1.close()\n" +" b = f2.readlines(); f2.close()\n" +" for line in difflib.ndiff(a, b):\n" +" print(line, end=' ')\n" +"\n" +" return 1\n" +"\n" +"# crack args (sys.argv[1:] is normal) & compare;\n" +"# return false iff a problem\n" +"\n" +"def main(args):\n" +" import getopt\n" +" try:\n" +" opts, args = getopt.getopt(args, \"qr:\")\n" +" except getopt.error as detail:\n" +" return fail(str(detail))\n" +" noisy = 1\n" +" qseen = rseen = 0\n" +" for opt, val in opts:\n" +" if opt == \"-q\":\n" +" qseen = 1\n" +" noisy = 0\n" +" elif opt == \"-r\":\n" +" rseen = 1\n" +" whichfile = val\n" +" if qseen and rseen:\n" +" return fail(\"can't specify both -q and -r\")\n" +" if rseen:\n" +" if args:\n" +" return fail(\"no args allowed with -r option\")\n" +" if whichfile in (\"1\", \"2\"):\n" +" restore(whichfile)\n" +" return 1\n" +" return fail(\"-r value must be 1 or 2\")\n" +" if len(args) != 2:\n" +" return fail(\"need 2 filename args\")\n" +" f1name, f2name = args\n" +" if noisy:\n" +" print('-:', f1name)\n" +" print('+:', f2name)\n" +" return fcompare(f1name, f2name)\n" +"\n" +"# read ndiff output from stdin, and print file1 (which=='1') or\n" +"# file2 (which=='2') to stdout\n" +"\n" +"def restore(which):\n" +" restored = difflib.restore(sys.stdin.readlines(), which)\n" +" sys.stdout.writelines(restored)\n" +"\n" +"if __name__ == '__main__':\n" +" main(sys.argv[1:])\n" +msgstr "" diff --git a/library/dis.po b/library/dis.po index a7f9ba35d..b3b1ef479 100644 --- a/library/dis.po +++ b/library/dis.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 -# Marco Rougeth , 2022 -# Danilo Lima , 2023 -# Vitor Buxbaum Orlandi, 2023 -# Pedro Fonini, 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:04+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-04-25 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -126,6 +121,14 @@ msgstr "" msgid "Example: Given the function :func:`!myfunc`::" msgstr "Exemplo: Dada a função :func:`!myfunc`::" +#: ../../library/dis.rst:61 +msgid "" +"def myfunc(alist):\n" +" return len(alist)" +msgstr "" +"def myfunc(alist):\n" +" return len(alist)" + #: ../../library/dis.rst:64 msgid "" "the following command can be used to display the disassembly of :func:`!" @@ -134,6 +137,24 @@ msgstr "" "o comando a seguir pode ser usado para mostrar a desconstrução de :func:`!" "myfunc`:" +#: ../../library/dis.rst:67 +msgid "" +">>> dis.dis(myfunc)\n" +" 2 RESUME 0\n" +"\n" +" 3 LOAD_GLOBAL 1 (len + NULL)\n" +" LOAD_FAST 0 (alist)\n" +" CALL 1\n" +" RETURN_VALUE" +msgstr "" +">>> dis.dis(myfunc)\n" +" 2 RESUME 0\n" +"\n" +" 3 LOAD_GLOBAL 1 (len + NULL)\n" +" LOAD_FAST 0 (alist)\n" +" CALL 1\n" +" RETURN_VALUE" + #: ../../library/dis.rst:77 msgid "(The \"2\" is a line number)." msgstr "(O \"2\" é o número da linha)." @@ -147,6 +168,10 @@ msgid "The :mod:`dis` module can be invoked as a script from the command line:" msgstr "" "O módulo :mod:`dis` pode ser invocado como um script na linha de comando:" +#: ../../library/dis.rst:86 +msgid "python -m dis [-h] [-C] [-O] [infile]" +msgstr "python -m dis [-h] [-C] [-O] [infile]" + #: ../../library/dis.rst:90 msgid "The following options are accepted:" msgstr "As seguintes opções são aceitas:" @@ -159,11 +184,11 @@ msgstr "Exibe o modo de uso e sai." msgid "Show inline caches." msgstr "Mostra caches em linha" -#: ../../library/dis.rst:104 +#: ../../library/dis.rst:106 msgid "Show offsets of instructions." msgstr "Mostra os deslocamentos das instruções" -#: ../../library/dis.rst:106 +#: ../../library/dis.rst:110 msgid "" "If :file:`infile` is specified, its disassembled code will be written to " "stdout. Otherwise, disassembly is performed on compiled source code received " @@ -173,11 +198,11 @@ msgstr "" "stdout. Caso contrário, será feito o desmonte da compilação do código-fonte " "recebido do stdin." -#: ../../library/dis.rst:110 +#: ../../library/dis.rst:114 msgid "Bytecode analysis" msgstr "Análise de bytecode" -#: ../../library/dis.rst:114 +#: ../../library/dis.rst:118 msgid "" "The bytecode analysis API allows pieces of Python code to be wrapped in a :" "class:`Bytecode` object that provides easy access to details of the compiled " @@ -187,7 +212,7 @@ msgstr "" "encapsuladas em um objeto :class:`Bytecode` que facilite o acesso aos " "detalhes do código compilado." -#: ../../library/dis.rst:121 +#: ../../library/dis.rst:125 msgid "" "Analyse the bytecode corresponding to a function, generator, asynchronous " "generator, coroutine, method, string of source code, or a code object (as " @@ -197,7 +222,7 @@ msgstr "" "assíncrono, uma corrotina, um método, uma string de código-fonte, ou um " "objeto de código (conforme retornado por :func:`compile`)." -#: ../../library/dis.rst:125 +#: ../../library/dis.rst:129 msgid "" "This is a convenience wrapper around many of the functions listed below, " "most notably :func:`get_instructions`, as iterating over a :class:`Bytecode` " @@ -208,7 +233,7 @@ msgstr "" "sobre sobre uma instância de :class:`Bytecode` produz operações bytecode " "como instâncias de :class:`Instruction`." -#: ../../library/dis.rst:129 ../../library/dis.rst:326 +#: ../../library/dis.rst:133 ../../library/dis.rst:330 msgid "" "If *first_line* is not ``None``, it indicates the line number that should be " "reported for the first source line in the disassembled code. Otherwise, the " @@ -220,7 +245,7 @@ msgstr "" "contrário, a informação de linha de código-fonte (se houver) é extraída " "diretamente da desconstrução do objeto de código." -#: ../../library/dis.rst:134 +#: ../../library/dis.rst:138 msgid "" "If *current_offset* is not ``None``, it refers to an instruction offset in " "the disassembled code. Setting this means :meth:`.dis` will display a " @@ -230,7 +255,7 @@ msgstr "" "código desconstruído. Definir este argumento significa que o :meth:`.dis` " "vai mostrar um marcador de \"instrução atual\" sobre o opcode especificado." -#: ../../library/dis.rst:138 +#: ../../library/dis.rst:142 msgid "" "If *show_caches* is ``True``, :meth:`.dis` will display inline cache entries " "used by the interpreter to specialize the bytecode." @@ -238,7 +263,7 @@ msgstr "" "Se *show_caches* for ``True``, o :meth:`.dis` vai exibir entradas de cache " "em linha usadas pelo interpretador para especializar o bytecode." -#: ../../library/dis.rst:141 +#: ../../library/dis.rst:145 msgid "" "If *adaptive* is ``True``, :meth:`.dis` will display specialized bytecode " "that may be different from the original bytecode." @@ -246,7 +271,7 @@ msgstr "" "Se *adaptive* for ``True``, o :meth:`.dis` vai exibir bytecode especializado " "que pode ser diferente do bytecode original." -#: ../../library/dis.rst:144 +#: ../../library/dis.rst:148 msgid "" "If *show_offsets* is ``True``, :meth:`.dis` will include instruction offsets " "in the output." @@ -254,7 +279,7 @@ msgstr "" "Se *show_offsets* for ``True``, o :meth:`.dis` vai incluir deslocamentos em " "instruções na saída." -#: ../../library/dis.rst:149 +#: ../../library/dis.rst:153 msgid "" "Construct a :class:`Bytecode` instance from the given traceback, setting " "*current_offset* to the instruction responsible for the exception." @@ -263,16 +288,16 @@ msgstr "" "definindo *current_offset* apontando para a instrução responsável pela " "exceção." -#: ../../library/dis.rst:154 +#: ../../library/dis.rst:158 msgid "The compiled code object." msgstr "O objeto de código compilado." -#: ../../library/dis.rst:158 +#: ../../library/dis.rst:162 msgid "The first source line of the code object (if available)" msgstr "" "A primeira linha de código-fonte do objeto de código (caso disponível)." -#: ../../library/dis.rst:162 +#: ../../library/dis.rst:166 msgid "" "Return a formatted view of the bytecode operations (the same as printed by :" "func:`dis.dis`, but returned as a multi-line string)." @@ -281,7 +306,7 @@ msgstr "" "seriam impressas pela :func:`dis.dis`, mas retornadas como uma string " "multilinha)." -#: ../../library/dis.rst:167 +#: ../../library/dis.rst:171 msgid "" "Return a formatted multi-line string with detailed information about the " "code object, like :func:`code_info`." @@ -289,27 +314,49 @@ msgstr "" "Retorna uma string multilinha formatada com informação detalhada sobre o " "objeto de código, como :func:`code_info`." -#: ../../library/dis.rst:170 ../../library/dis.rst:210 -#: ../../library/dis.rst:262 +#: ../../library/dis.rst:174 ../../library/dis.rst:214 +#: ../../library/dis.rst:266 msgid "This can now handle coroutine and asynchronous generator objects." msgstr "" "Este método agora lida com objetos de corrotina e de gerador assíncrono." -#: ../../library/dis.rst:173 ../../library/dis.rst:265 -#: ../../library/dis.rst:282 ../../library/dis.rst:312 -#: ../../library/dis.rst:335 +#: ../../library/dis.rst:177 ../../library/dis.rst:269 +#: ../../library/dis.rst:286 ../../library/dis.rst:316 +#: ../../library/dis.rst:339 msgid "Added the *show_caches* and *adaptive* parameters." msgstr "Adicionados os parâmetros *show_caches* e *adaptive*." -#: ../../library/dis.rst:176 +#: ../../library/dis.rst:180 msgid "Example:" msgstr "Exemplo:" -#: ../../library/dis.rst:192 +#: ../../library/dis.rst:182 +msgid "" +">>> bytecode = dis.Bytecode(myfunc)\n" +">>> for instr in bytecode:\n" +"... print(instr.opname)\n" +"...\n" +"RESUME\n" +"LOAD_GLOBAL\n" +"LOAD_FAST\n" +"CALL\n" +"RETURN_VALUE" +msgstr "" +">>> bytecode = dis.Bytecode(myfunc)\n" +">>> for instr in bytecode:\n" +"... print(instr.opname)\n" +"...\n" +"RESUME\n" +"LOAD_GLOBAL\n" +"LOAD_FAST\n" +"CALL\n" +"RETURN_VALUE" + +#: ../../library/dis.rst:196 msgid "Analysis functions" msgstr "Funções de análise" -#: ../../library/dis.rst:194 +#: ../../library/dis.rst:198 msgid "" "The :mod:`dis` module also defines the following analysis functions that " "convert the input directly to the desired output. They can be useful if only " @@ -321,7 +368,7 @@ msgstr "" "uma única operação está sendo feita, de forma que o objeto de análise " "intermediário não é útil:" -#: ../../library/dis.rst:200 +#: ../../library/dis.rst:204 msgid "" "Return a formatted multi-line string with detailed code object information " "for the supplied function, generator, asynchronous generator, coroutine, " @@ -331,7 +378,7 @@ msgstr "" "objeto de código correspondente à função, gerador, gerador assíncrono, " "corrotina, método, string de código-fonte ou objeto de código fornecido." -#: ../../library/dis.rst:204 +#: ../../library/dis.rst:208 msgid "" "Note that the exact contents of code info strings are highly implementation " "dependent and they may change arbitrarily across Python VMs or Python " @@ -341,7 +388,7 @@ msgstr "" "altamente dependentes da implementação e podem mudar de forma arbitrária " "através de VMs Python ou lançamentos do Python." -#: ../../library/dis.rst:216 +#: ../../library/dis.rst:220 msgid "" "Print detailed code object information for the supplied function, method, " "source code string or code object to *file* (or ``sys.stdout`` if *file* is " @@ -351,7 +398,7 @@ msgstr "" "especificado) informações detalhadas sobre o objeto de código correspondente " "à função, método, string de código-fonte fornecido." -#: ../../library/dis.rst:220 +#: ../../library/dis.rst:224 msgid "" "This is a convenient shorthand for ``print(code_info(x), file=file)``, " "intended for interactive exploration at the interpreter prompt." @@ -359,12 +406,12 @@ msgstr "" "Este é um atalho conveniente para ``print(code_info(x), file=file)``, " "destinado à exploração interativa no prompt do interpretador." -#: ../../library/dis.rst:225 ../../library/dis.rst:256 -#: ../../library/dis.rst:279 ../../library/dis.rst:309 +#: ../../library/dis.rst:229 ../../library/dis.rst:260 +#: ../../library/dis.rst:283 ../../library/dis.rst:313 msgid "Added *file* parameter." msgstr "Adicionado o parâmetro *file*." -#: ../../library/dis.rst:231 +#: ../../library/dis.rst:235 msgid "" "Disassemble the *x* object. *x* can denote either a module, a class, a " "method, a function, a generator, an asynchronous generator, a coroutine, a " @@ -393,8 +440,8 @@ msgstr "" "embutida :func:`compile` antes de serem desmontadas. Se nenhum objeto for " "fornecido, o último traceback é desmontado." -#: ../../library/dis.rst:244 ../../library/dis.rst:276 -#: ../../library/dis.rst:306 +#: ../../library/dis.rst:248 ../../library/dis.rst:280 +#: ../../library/dis.rst:310 msgid "" "The disassembly is written as text to the supplied *file* argument if " "provided and to ``sys.stdout`` otherwise." @@ -402,7 +449,7 @@ msgstr "" "O resultado é escrito como texto no arquivo *file* caso tenha sido fornecido " "como argumento, ou para ``sys.stdout`` caso contrário." -#: ../../library/dis.rst:247 +#: ../../library/dis.rst:251 msgid "" "The maximal depth of recursion is limited by *depth* unless it is ``None``. " "``depth=0`` means no recursion." @@ -410,7 +457,7 @@ msgstr "" "A profundidade máxima de recursão é limitada por *depth* a menos que seja " "``None``. ``depth=0`` significa não fazer recursão." -#: ../../library/dis.rst:250 +#: ../../library/dis.rst:254 msgid "" "If *show_caches* is ``True``, this function will display inline cache " "entries used by the interpreter to specialize the bytecode." @@ -418,7 +465,7 @@ msgstr "" "Se *show_caches* for ``True``, essa função vai exibir entradas de cache em " "linha usadas pelo interpretador para especializar o bytecode." -#: ../../library/dis.rst:253 +#: ../../library/dis.rst:257 msgid "" "If *adaptive* is ``True``, this function will display specialized bytecode " "that may be different from the original bytecode." @@ -426,12 +473,12 @@ msgstr "" "Se *adaptive* for ``True``, essa função vai exibir bytecode especializado " "que pode ser diferente do bytecode original." -#: ../../library/dis.rst:259 +#: ../../library/dis.rst:263 msgid "Implemented recursive disassembling and added *depth* parameter." msgstr "" "Foi implementada a desmontagem recursiva, e adicionado o parâmetro *depth*." -#: ../../library/dis.rst:272 +#: ../../library/dis.rst:276 msgid "" "Disassemble the top-of-stack function of a traceback, using the last " "traceback if none was passed. The instruction causing the exception is " @@ -441,11 +488,11 @@ msgstr "" "traceback caso nenhum tenha sido passado. A instrução que causou a exceção " "é indicada." -#: ../../library/dis.rst:285 ../../library/dis.rst:315 +#: ../../library/dis.rst:289 ../../library/dis.rst:319 msgid "Added the *show_offsets* parameter." msgstr "Foi adicionado o parâmetro *show_offsets*." -#: ../../library/dis.rst:292 +#: ../../library/dis.rst:296 msgid "" "Disassemble a code object, indicating the last instruction if *lasti* was " "provided. The output is divided in the following columns:" @@ -453,35 +500,35 @@ msgstr "" "Desmonta um objeto de código, indicando a última instrução se *lasti* tiver " "sido fornecido. A saída é dividida em colunas da seguinte forma:" -#: ../../library/dis.rst:295 +#: ../../library/dis.rst:299 msgid "the line number, for the first instruction of each line" msgstr "o número da linha, para a primeira instrução de cada linha" -#: ../../library/dis.rst:296 +#: ../../library/dis.rst:300 msgid "the current instruction, indicated as ``-->``," msgstr "a instrução atual, indicada por ``-->``," -#: ../../library/dis.rst:297 +#: ../../library/dis.rst:301 msgid "a labelled instruction, indicated with ``>>``," msgstr "um rótulo da instrução, indicado com ``>>``," -#: ../../library/dis.rst:298 +#: ../../library/dis.rst:302 msgid "the address of the instruction," msgstr "o endereço da instrução" -#: ../../library/dis.rst:299 +#: ../../library/dis.rst:303 msgid "the operation code name," msgstr "o nome do código da operação," -#: ../../library/dis.rst:300 +#: ../../library/dis.rst:304 msgid "operation parameters, and" msgstr "os parâmetros da operação, e" -#: ../../library/dis.rst:301 +#: ../../library/dis.rst:305 msgid "interpretation of the parameters in parentheses." msgstr "a interpretação dos parâmetros, em parênteses." -#: ../../library/dis.rst:303 +#: ../../library/dis.rst:307 msgid "" "The parameter interpretation recognizes local and global variable names, " "constant values, branch targets, and compare operators." @@ -490,7 +537,7 @@ msgstr "" "globais, valores de constantes, alvos de ramificações, e operadores de " "comparação." -#: ../../library/dis.rst:320 +#: ../../library/dis.rst:324 msgid "" "Return an iterator over the instructions in the supplied function, method, " "source code string or code object." @@ -498,7 +545,7 @@ msgstr "" "Retorna um iterador sobre as instruções na função, método, string de código-" "fonte ou objeto de código fornecido." -#: ../../library/dis.rst:323 +#: ../../library/dis.rst:327 msgid "" "The iterator generates a series of :class:`Instruction` named tuples giving " "the details of each operation in the supplied code." @@ -506,11 +553,11 @@ msgstr "" "O iterador gera uma série de tuplas nomeadas :class:`Instruction` contendo " "detalhes de cada operação no código fornecido." -#: ../../library/dis.rst:331 +#: ../../library/dis.rst:335 msgid "The *adaptive* parameter works as it does in :func:`dis`." msgstr "O parâmetro *adaptive* funciona assim como na função :func:`dis`." -#: ../../library/dis.rst:338 +#: ../../library/dis.rst:342 msgid "" "The *show_caches* parameter is deprecated and has no effect. The iterator " "generates the :class:`Instruction` instances with the *cache_info* field " @@ -522,7 +569,7 @@ msgstr "" "populado (independentemente do valor de *show_caches*) e não gera mais items " "separados para as entradas de cache." -#: ../../library/dis.rst:346 +#: ../../library/dis.rst:350 msgid "" "This generator function uses the :meth:`~codeobject.co_lines` method of the :" "ref:`code object ` *code* to find the offsets which are starts " @@ -534,12 +581,12 @@ msgstr "" "correspondem aos inícios de cada linha do código-fonte. Elas são geradas em " "pares ``(offset, lineno)``." -#: ../../library/dis.rst:351 +#: ../../library/dis.rst:355 msgid "Line numbers can be decreasing. Before, they were always increasing." msgstr "" "Números de linhas podem ser decrescentes. Antes, eles eram sempre crescentes." -#: ../../library/dis.rst:354 +#: ../../library/dis.rst:358 msgid "" "The :pep:`626` :meth:`~codeobject.co_lines` method is used instead of the :" "attr:`~codeobject.co_firstlineno` and :attr:`~codeobject.co_lnotab` " @@ -549,14 +596,14 @@ msgstr "" "atributos :attr:`~codeobject.co_firstlineno` e :attr:`~codeobject.co_lnotab` " "do :ref:`objeto de código `." -#: ../../library/dis.rst:359 +#: ../../library/dis.rst:363 msgid "" "Line numbers can be ``None`` for bytecode that does not map to source lines." msgstr "" "Números de linha podem ser ``None`` para bytecode que não corresponde a um " "código-fonte." -#: ../../library/dis.rst:365 +#: ../../library/dis.rst:369 msgid "" "Detect all offsets in the raw compiled bytecode string *code* which are jump " "targets, and return a list of these offsets." @@ -564,11 +611,11 @@ msgstr "" "Detecta todas as posições na string de bytecode compilado bruto *code* que " "são alvos de pulos, e as retorna em uma lista." -#: ../../library/dis.rst:371 +#: ../../library/dis.rst:375 msgid "Compute the stack effect of *opcode* with argument *oparg*." msgstr "Calcula o efeito que o *opcode* com argumento *oparg* tem na pilha." -#: ../../library/dis.rst:373 +#: ../../library/dis.rst:377 msgid "" "If the code has a jump target and *jump* is ``True``, :func:`~stack_effect` " "will return the stack effect of jumping. If *jump* is ``False``, it will " @@ -581,11 +628,11 @@ msgstr "" "*jump* for ``None`` (o padrão), vai retornar o efeito máximo na pilha dentre " "os dois casos." -#: ../../library/dis.rst:380 +#: ../../library/dis.rst:384 msgid "Added *jump* parameter." msgstr "Adicionado o parâmetro *jump*." -#: ../../library/dis.rst:383 +#: ../../library/dis.rst:387 msgid "" "If ``oparg`` is omitted (or ``None``), the stack effect is now returned for " "``oparg=0``. Previously this was an error for opcodes that use their arg. It " @@ -597,11 +644,11 @@ msgstr "" "o seu argumento. Além disso, agora não é mais um erro passar um inteiro como " "``oparg`` quando o ``opcode`` não o usa; o ``oparg`` nesse caso é ignorado." -#: ../../library/dis.rst:393 +#: ../../library/dis.rst:397 msgid "Python Bytecode Instructions" msgstr "Instruções em bytecode do Python" -#: ../../library/dis.rst:395 +#: ../../library/dis.rst:399 msgid "" "The :func:`get_instructions` function and :class:`Bytecode` class provide " "details of bytecode instructions as :class:`Instruction` instances:" @@ -609,11 +656,11 @@ msgstr "" "A função :func:`get_instructions` e a classe :class:`Bytecode` fornecem " "detalhes de instruções de bytecode como instâncias de :class:`Instruction`:" -#: ../../library/dis.rst:400 +#: ../../library/dis.rst:404 msgid "Details for a bytecode operation" msgstr "Detalhes de uma operação em bytecode" -#: ../../library/dis.rst:404 +#: ../../library/dis.rst:408 msgid "" "numeric code for operation, corresponding to the opcode values listed below " "and the bytecode values in the :ref:`opcode_collections`." @@ -621,11 +668,11 @@ msgstr "" "código numérico da operação, correspondendo aos valores dos opcodes listados " "abaixo e aos valores dos bytecodes nas :ref:`opcode_collections`." -#: ../../library/dis.rst:410 +#: ../../library/dis.rst:414 msgid "human readable name for operation" msgstr "nome legível por humanos para a operação" -#: ../../library/dis.rst:415 +#: ../../library/dis.rst:419 msgid "" "numeric code for the base operation if operation is specialized; otherwise " "equal to :data:`opcode`" @@ -633,7 +680,7 @@ msgstr "" "código numérico para a operação base caso a operação seja especializada; " "caso contrário, igual ao :data:`opcode`" -#: ../../library/dis.rst:421 +#: ../../library/dis.rst:425 msgid "" "human readable name for the base operation if operation is specialized; " "otherwise equal to :data:`opname`" @@ -641,20 +688,20 @@ msgstr "" "nome legível por humanos para a operação base caso a operação seja " "especializada; caso contrário, igual ao :data:`opname`" -#: ../../library/dis.rst:427 +#: ../../library/dis.rst:431 msgid "numeric argument to operation (if any), otherwise ``None``" msgstr "" "argumento numérico para a operação (se houver), caso contrário ``None``" -#: ../../library/dis.rst:431 +#: ../../library/dis.rst:435 msgid "alias for :data:`arg`" msgstr "apelido para :data:`arg`" -#: ../../library/dis.rst:435 +#: ../../library/dis.rst:439 msgid "resolved arg value (if any), otherwise ``None``" msgstr "valor resolvido do argumento (se houver), caso contrário ``None``" -#: ../../library/dis.rst:440 +#: ../../library/dis.rst:444 msgid "" "human readable description of operation argument (if any), otherwise an " "empty string." @@ -662,11 +709,11 @@ msgstr "" "descrição legível por humanos do argumento da operação (se houver), caso " "contrário uma string vazia." -#: ../../library/dis.rst:446 +#: ../../library/dis.rst:450 msgid "start index of operation within bytecode sequence" msgstr "índice de início da operação dentro da sequência de bytecodes" -#: ../../library/dis.rst:451 +#: ../../library/dis.rst:455 msgid "" "start index of operation within bytecode sequence, including prefixed " "``EXTENDED_ARG`` operations if present; otherwise equal to :data:`offset`" @@ -675,29 +722,29 @@ msgstr "" "operações de ``EXTENDED_ARG`` prefixadas, caso presentes; caso contrário, " "igual a :data:`offset`" -#: ../../library/dis.rst:457 +#: ../../library/dis.rst:461 msgid "start index of the cache entries following the operation" msgstr "índice de início das entradas de cache que seguem a operação" -#: ../../library/dis.rst:462 +#: ../../library/dis.rst:466 msgid "end index of the cache entries following the operation" msgstr "índice de fim das entradas de cache que seguem a operação" -#: ../../library/dis.rst:467 +#: ../../library/dis.rst:471 msgid "``True`` if this opcode starts a source line, otherwise ``False``" msgstr "``True`` se esse opcode inicia uma linha, ``False`` caso contrário" -#: ../../library/dis.rst:472 +#: ../../library/dis.rst:476 msgid "" "source line number associated with this opcode (if any), otherwise ``None``" msgstr "" "linha de código-fonte associada a esse opcode (se houver), senão ``None``" -#: ../../library/dis.rst:477 +#: ../../library/dis.rst:481 msgid "``True`` if other code jumps to here, otherwise ``False``" msgstr "``True`` se algum outro código pula para cá, senão ``False``" -#: ../../library/dis.rst:482 +#: ../../library/dis.rst:486 msgid "" "bytecode index of the jump target if this is a jump operation, otherwise " "``None``" @@ -705,7 +752,7 @@ msgstr "" "índice do bytecode que é alvo do pulo caso essa seja uma operação de pulo, " "caso contrário ``None``" -#: ../../library/dis.rst:488 +#: ../../library/dis.rst:492 msgid "" ":class:`dis.Positions` object holding the start and end locations that are " "covered by this instruction." @@ -713,15 +760,23 @@ msgstr "" "objeto :class:`dis.Positions` contendo os pontos de início e fim cobertos " "por esta instrução." -#: ../../library/dis.rst:503 +#: ../../library/dis.rst:497 +msgid "" +"Information about the cache entries of this instruction, as triplets of the " +"form ``(name, size, data)``, where the ``name`` and ``size`` describe the " +"cache format and data is the contents of the cache. ``cache_info`` is " +"``None`` if the instruction does not have caches." +msgstr "" + +#: ../../library/dis.rst:507 msgid "Field ``positions`` is added." msgstr "Adicionado o campo ``positions``." -#: ../../library/dis.rst:507 +#: ../../library/dis.rst:511 msgid "Changed field ``starts_line``." msgstr "Alterado o campo ``starts_line``." -#: ../../library/dis.rst:509 +#: ../../library/dis.rst:513 msgid "" "Added fields ``start_offset``, ``cache_offset``, ``end_offset``, " "``baseopname``, ``baseopcode``, ``jump_target``, ``oparg``, ``line_number`` " @@ -731,23 +786,23 @@ msgstr "" "``baseopname``, ``baseopcode``, ``jump_target``, ``oparg``, ``line_number`` " "e ``cache_info``." -#: ../../library/dis.rst:516 +#: ../../library/dis.rst:520 msgid "" "In case the information is not available, some fields might be ``None``." msgstr "" "Caso a informação não esteja disponível, alguns campos podem ser ``None``." -#: ../../library/dis.rst:526 +#: ../../library/dis.rst:530 msgid "" "The Python compiler currently generates the following bytecode instructions." msgstr "" "O compilador de Python atualmente gera as seguintes instruções de bytecode." -#: ../../library/dis.rst:529 +#: ../../library/dis.rst:533 msgid "**General instructions**" msgstr "**Instruções gerais**" -#: ../../library/dis.rst:531 +#: ../../library/dis.rst:535 msgid "" "In the following, We will refer to the interpreter stack as ``STACK`` and " "describe operations on it as if it was a Python list. The top of the stack " @@ -757,7 +812,7 @@ msgstr "" "e vamos descrever operações nela como se ela fosse uma lista do Python. " "Nessa linguagem, ``STACK[-1]`` é o topo da pilha." -#: ../../library/dis.rst:537 +#: ../../library/dis.rst:541 msgid "" "Do nothing code. Used as a placeholder by the bytecode optimizer, and to " "generate line tracing events." @@ -765,11 +820,15 @@ msgstr "" "Código para não fazer nada. Usado como espaço reservado pelo otimizador de " "bytecode, e para gerar eventos de rastreamento de linha." -#: ../../library/dis.rst:543 +#: ../../library/dis.rst:547 msgid "Removes the top-of-stack item::" msgstr "Remove o item no topo da pilha::" -#: ../../library/dis.rst:550 +#: ../../library/dis.rst:549 +msgid "STACK.pop()" +msgstr "" + +#: ../../library/dis.rst:554 msgid "" "Removes the top-of-stack item. Equivalent to ``POP_TOP``. Used to clean up " "at the end of loops, hence the name." @@ -777,12 +836,12 @@ msgstr "" "Remove o item no topo da pilha. Equivalente a ``POP_TOP``. Usado como " "limpeza ao final de laços, o que explica o nome." -#: ../../library/dis.rst:559 +#: ../../library/dis.rst:563 msgid "Implements ``del STACK[-2]``. Used to clean up when a generator exits." msgstr "" "Implementa ``del STACK[-2]``. Usado como limpeza quando um gerador termina." -#: ../../library/dis.rst:567 +#: ../../library/dis.rst:571 msgid "" "Push the i-th item to the top of the stack without removing it from its " "original location::" @@ -790,11 +849,21 @@ msgstr "" "Coloca o i-ésimo item no topo da pilha sem removê-lo da sua posição " "original::" -#: ../../library/dis.rst:578 +#: ../../library/dis.rst:574 +msgid "" +"assert i > 0\n" +"STACK.append(STACK[-i])" +msgstr "" + +#: ../../library/dis.rst:582 msgid "Swap the top of the stack with the i-th element::" msgstr "Troca o topo da pilha de lugar com o i-ésimo elemento." -#: ../../library/dis.rst:587 +#: ../../library/dis.rst:584 +msgid "STACK[-i], STACK[-1] = STACK[-1], STACK[-i]" +msgstr "" + +#: ../../library/dis.rst:591 msgid "" "Rather than being an actual instruction, this opcode is used to mark extra " "space for the interpreter to cache useful data directly in the bytecode " @@ -806,7 +875,7 @@ msgstr "" "próprio bytecode. É escondido automaticamente por todas as utilidades do " "``dis``, mas pode ser visualizado com ``show_caches=True``." -#: ../../library/dis.rst:592 +#: ../../library/dis.rst:596 msgid "" "Logically, this space is part of the preceding instruction. Many opcodes " "expect to be followed by an exact number of caches, and will instruct the " @@ -816,7 +885,7 @@ msgstr "" "Muitos opcodes esperam ser seguidos por um número exato de caches, e " "instruem o interpretador a pulá-los em tempo de execução." -#: ../../library/dis.rst:596 +#: ../../library/dis.rst:600 msgid "" "Populated caches can look like arbitrary instructions, so great care should " "be taken when reading or modifying raw, adaptive bytecode containing " @@ -826,11 +895,11 @@ msgstr "" "ou modificar bytecode adaptativo bruto contendo dados \"quickened\" requer " "muito cuidado." -#: ../../library/dis.rst:603 +#: ../../library/dis.rst:607 msgid "**Unary operations**" msgstr "**Operações unárias**" -#: ../../library/dis.rst:605 +#: ../../library/dis.rst:609 msgid "" "Unary operations take the top of the stack, apply the operation, and push " "the result back on the stack." @@ -838,30 +907,30 @@ msgstr "" "Operações unárias tiram o topo da pilha, aplicam a operação, e põem o " "resultado de volta na pilha." -#: ../../library/dis.rst:611 +#: ../../library/dis.rst:615 msgid "Implements ``STACK[-1] = -STACK[-1]``." msgstr "Implementa ``STACK[-1] = -STACK[-1]``." -#: ../../library/dis.rst:616 +#: ../../library/dis.rst:620 msgid "Implements ``STACK[-1] = not STACK[-1]``." msgstr "Implementa ``STACK[-1] = not STACK[-1]``." -#: ../../library/dis.rst:618 ../../library/dis.rst:1313 -#: ../../library/dis.rst:1329 +#: ../../library/dis.rst:622 ../../library/dis.rst:1318 +#: ../../library/dis.rst:1334 msgid "This instruction now requires an exact :class:`bool` operand." msgstr "" "Essa instrução agora requer que o operando seja exatamente do tipo :class:" "`bool`." -#: ../../library/dis.rst:624 +#: ../../library/dis.rst:628 msgid "Implements ``STACK[-1] = ~STACK[-1]``." msgstr "Implementa ``STACK[-1] = ~STACK[-1]``." -#: ../../library/dis.rst:629 +#: ../../library/dis.rst:633 msgid "Implements ``STACK[-1] = iter(STACK[-1])``." msgstr "Implementa ``STACK[-1] = iter(STACK[-1])``." -#: ../../library/dis.rst:634 +#: ../../library/dis.rst:638 msgid "" "If ``STACK[-1]`` is a :term:`generator iterator` or :term:`coroutine` object " "it is left as is. Otherwise, implements ``STACK[-1] = iter(STACK[-1])``." @@ -870,15 +939,15 @@ msgstr "" "`corrotina`, nada acontece. Caso contrário, implementa ``STACK[-1] = " "iter(STACK[-1])``." -#: ../../library/dis.rst:642 +#: ../../library/dis.rst:646 msgid "Implements ``STACK[-1] = bool(STACK[-1])``." msgstr "Implementa ``STACK[-1] = bool(STACK[-1])``." -#: ../../library/dis.rst:647 +#: ../../library/dis.rst:651 msgid "**Binary and in-place operations**" msgstr "**Operações binárias e internas**" -#: ../../library/dis.rst:649 +#: ../../library/dis.rst:653 msgid "" "Binary operations remove the top two items from the stack (``STACK[-1]`` and " "``STACK[-2]``). They perform the operation, then put the result back on the " @@ -888,7 +957,7 @@ msgstr "" "``STACK[-2]``). A operação é realizada, e o resultado é colocado de volta na " "pilha." -#: ../../library/dis.rst:652 +#: ../../library/dis.rst:656 msgid "" "In-place operations are like binary operations, but the operation is done in-" "place when ``STACK[-2]`` supports it, and the resulting ``STACK[-1]`` may be " @@ -898,28 +967,74 @@ msgstr "" "feita internamente caso suportado por ``STACK[-2]``, e o ``STACK[-1]`` " "resultante pode ser (mas não necessariamente é) o ``STACK[-2]`` original." -#: ../../library/dis.rst:659 +#: ../../library/dis.rst:663 msgid "" "Implements the binary and in-place operators (depending on the value of " "*op*)::" msgstr "" "Implementa os operadores binários e locais (depende do valor de *op*)::" -#: ../../library/dis.rst:671 ../../library/dis.rst:680 -#: ../../library/dis.rst:690 ../../library/dis.rst:698 -#: ../../library/dis.rst:710 ../../library/dis.rst:798 -#: ../../library/dis.rst:808 ../../library/dis.rst:818 -#: ../../library/dis.rst:1041 ../../library/dis.rst:1052 -#: ../../library/dis.rst:1156 ../../library/dis.rst:1168 -#: ../../library/dis.rst:1180 +#: ../../library/dis.rst:666 +msgid "" +"rhs = STACK.pop()\n" +"lhs = STACK.pop()\n" +"STACK.append(lhs op rhs)" +msgstr "" + +#: ../../library/dis.rst:675 ../../library/dis.rst:684 +#: ../../library/dis.rst:694 ../../library/dis.rst:702 +#: ../../library/dis.rst:714 ../../library/dis.rst:802 +#: ../../library/dis.rst:812 ../../library/dis.rst:822 +#: ../../library/dis.rst:1046 ../../library/dis.rst:1057 +#: ../../library/dis.rst:1161 ../../library/dis.rst:1173 +#: ../../library/dis.rst:1185 msgid "Implements::" msgstr "Implementa::" -#: ../../library/dis.rst:721 +#: ../../library/dis.rst:677 +msgid "" +"key = STACK.pop()\n" +"container = STACK.pop()\n" +"STACK.append(container[key])" +msgstr "" + +#: ../../library/dis.rst:686 +msgid "" +"key = STACK.pop()\n" +"container = STACK.pop()\n" +"value = STACK.pop()\n" +"container[key] = value" +msgstr "" + +#: ../../library/dis.rst:696 +msgid "" +"key = STACK.pop()\n" +"container = STACK.pop()\n" +"del container[key]" +msgstr "" + +#: ../../library/dis.rst:704 +msgid "" +"end = STACK.pop()\n" +"start = STACK.pop()\n" +"container = STACK.pop()\n" +"STACK.append(container[start:end])" +msgstr "" + +#: ../../library/dis.rst:716 +msgid "" +"end = STACK.pop()\n" +"start = STACK.pop()\n" +"container = STACK.pop()\n" +"values = STACK.pop()\n" +"container[start:end] = value" +msgstr "" + +#: ../../library/dis.rst:725 msgid "**Coroutine opcodes**" msgstr "**Opcodes para corrotinas**" -#: ../../library/dis.rst:725 +#: ../../library/dis.rst:729 msgid "" "Implements ``STACK[-1] = get_awaitable(STACK[-1])``, where " "``get_awaitable(o)`` returns ``o`` if ``o`` is a coroutine object or a " @@ -931,34 +1046,34 @@ msgstr "" "gerador com o sinalizador :data:`~inspect.CO_ITERABLE_COROUTINE`, ou então " "resolve ``o.__await__``." -#: ../../library/dis.rst:730 +#: ../../library/dis.rst:734 msgid "" "If the ``where`` operand is nonzero, it indicates where the instruction " "occurs:" msgstr "" "Se o operando ``where`` não for zero, ele indica onde a instrução ocorre:" -#: ../../library/dis.rst:733 +#: ../../library/dis.rst:737 msgid "``1``: After a call to ``__aenter__``" msgstr "``1``: Após uma chamada a ``__aenter__``" -#: ../../library/dis.rst:734 +#: ../../library/dis.rst:738 msgid "``2``: After a call to ``__aexit__``" msgstr "``2``: Após uma chamada a ``__aexit__``" -#: ../../library/dis.rst:738 +#: ../../library/dis.rst:742 msgid "Previously, this instruction did not have an oparg." msgstr "Anteriormente, esta instrução não tinha um oparg." -#: ../../library/dis.rst:744 +#: ../../library/dis.rst:748 msgid "Implements ``STACK[-1] = STACK[-1].__aiter__()``." msgstr "Implementa ``STACK[-1] = STACK[-1].__aiter__()``." -#: ../../library/dis.rst:747 +#: ../../library/dis.rst:751 msgid "Returning awaitable objects from ``__aiter__`` is no longer supported." msgstr "Não é mais aceitado que o ``__aiter__`` retorne objetos aguardáveis." -#: ../../library/dis.rst:754 +#: ../../library/dis.rst:758 msgid "" "Implement ``STACK.append(get_awaitable(STACK[-1].__anext__()))`` to the " "stack. See ``GET_AWAITABLE`` for details about ``get_awaitable``." @@ -966,7 +1081,7 @@ msgstr "" "Implementa ``STACK.append(get_awaitable(STACK[-1].__anext__()))``. Veja " "``GET_AWAITABLE`` para o significado de ``get_awaitable``." -#: ../../library/dis.rst:762 +#: ../../library/dis.rst:766 msgid "" "Terminates an :keyword:`async for` loop. Handles an exception raised when " "awaiting a next item. The stack contains the async iterable in ``STACK[-2]`` " @@ -978,15 +1093,15 @@ msgstr "" "exceção levantada em ``STACK[-1]``. Ambos são retirados. Se a exceção não " "for :exc:`StopAsyncIteration`, ela é re-levantada." -#: ../../library/dis.rst:769 ../../library/dis.rst:877 -#: ../../library/dis.rst:888 +#: ../../library/dis.rst:773 ../../library/dis.rst:881 +#: ../../library/dis.rst:892 msgid "" "Exception representation on the stack now consist of one, not three, items." msgstr "" "A representação da exceção na pilha consiste agora de um item, ao invés de " "três." -#: ../../library/dis.rst:775 +#: ../../library/dis.rst:779 msgid "" "Handles an exception raised during a :meth:`~generator.throw` or :meth:" "`~generator.close` call through the current frame. If ``STACK[-1]`` is an " @@ -998,7 +1113,7 @@ msgstr "" "uma instância de :exc:`StopIteration`, remove três valores da pilha e põe de " "volta o seu membro ``value``. Caso contrário, re-levanta ``STACK[-1]``." -#: ../../library/dis.rst:785 +#: ../../library/dis.rst:789 msgid "" "Resolves ``__aenter__`` and ``__aexit__`` from ``STACK[-1]``. Pushes " "``__aexit__`` and result of ``__aenter__()`` to the stack::" @@ -1006,23 +1121,46 @@ msgstr "" "Resolve os métodos especiais ``__aenter__`` e ``__aexit__`` de " "``STACK[-1]``. Põe na pilha ``__aexit__`` e o resultado de ``__aenter__()``::" -#: ../../library/dis.rst:794 +#: ../../library/dis.rst:792 +msgid "STACK.extend((__aexit__, __aenter__())" +msgstr "" + +#: ../../library/dis.rst:798 msgid "**Miscellaneous opcodes**" msgstr "**Opcodes genéricos**" -#: ../../library/dis.rst:803 +#: ../../library/dis.rst:804 +msgid "" +"item = STACK.pop()\n" +"set.add(STACK[-i], item)" +msgstr "" + +#: ../../library/dis.rst:807 msgid "Used to implement set comprehensions." msgstr "Usado para implementar compreensões de conjuntos." -#: ../../library/dis.rst:813 +#: ../../library/dis.rst:814 +msgid "" +"item = STACK.pop()\n" +"list.append(STACK[-i], item)" +msgstr "" + +#: ../../library/dis.rst:817 msgid "Used to implement list comprehensions." msgstr "Usado para implementar compreensões de lista." #: ../../library/dis.rst:824 +msgid "" +"value = STACK.pop()\n" +"key = STACK.pop()\n" +"dict.__setitem__(STACK[-i], key, value)" +msgstr "" + +#: ../../library/dis.rst:828 msgid "Used to implement dict comprehensions." msgstr "Usado para implementar compreensões de dicionário." -#: ../../library/dis.rst:827 +#: ../../library/dis.rst:831 msgid "" "Map value is ``STACK[-1]`` and map key is ``STACK[-2]``. Before, those were " "reversed." @@ -1030,7 +1168,7 @@ msgstr "" "O valor do mapa é ``STACK[-1]``, e a sua chave, ``STACK[-2]``. Antes, eles " "estavam ao contrário." -#: ../../library/dis.rst:831 +#: ../../library/dis.rst:835 msgid "" "For all of the :opcode:`SET_ADD`, :opcode:`LIST_APPEND` and :opcode:" "`MAP_ADD` instructions, while the added value or key/value pair is popped " @@ -1042,23 +1180,23 @@ msgstr "" "contêiner continua na pilha para que ele esteja disponível para as iterações " "seguintes do laço." -#: ../../library/dis.rst:839 +#: ../../library/dis.rst:843 msgid "Returns with ``STACK[-1]`` to the caller of the function." msgstr "Retorna ``STACK[-1]`` para quem chamou a função." -#: ../../library/dis.rst:844 +#: ../../library/dis.rst:848 msgid "Returns with ``co_consts[consti]`` to the caller of the function." msgstr "Retorna ``co_consts[consti]`` para quem chamou a função." -#: ../../library/dis.rst:851 +#: ../../library/dis.rst:855 msgid "Yields ``STACK.pop()`` from a :term:`generator`." msgstr "Gera ``STACK.pop()`` a partir de um :term:`gerador`." -#: ../../library/dis.rst:853 +#: ../../library/dis.rst:857 msgid "oparg set to be the stack depth." msgstr "oparg definido como sendo a profundidade da pilha." -#: ../../library/dis.rst:856 +#: ../../library/dis.rst:860 msgid "" "oparg set to be the exception block depth, for efficient closing of " "generators." @@ -1066,7 +1204,7 @@ msgstr "" "oparg definido como sendo a profundidade do bloco exception, para o " "fechamento eficiente de geradores." -#: ../../library/dis.rst:859 +#: ../../library/dis.rst:863 msgid "" "oparg is ``1`` if this instruction is part of a yield-from or await, and " "``0`` otherwise." @@ -1074,7 +1212,7 @@ msgstr "" "oparg é ``1`` caso esta instrução seja parte de um yield-from ou await, e " "``0`` caso contrário." -#: ../../library/dis.rst:865 +#: ../../library/dis.rst:869 msgid "" "Checks whether ``__annotations__`` is defined in ``locals()``, if not it is " "set up to an empty ``dict``. This opcode is only emitted if a class or " @@ -1086,14 +1224,14 @@ msgstr "" "somente se o corpo de uma classe ou módulo contém :term:`anotações de " "variáveis ` estaticamente." -#: ../../library/dis.rst:875 +#: ../../library/dis.rst:879 msgid "" "Pops a value from the stack, which is used to restore the exception state." msgstr "" "Remove o valor no topo da pilha, o qual é usado para restaurar o estado de " "exceção." -#: ../../library/dis.rst:882 +#: ../../library/dis.rst:886 msgid "" "Re-raises the exception currently on top of the stack. If oparg is non-zero, " "pops an additional value from the stack which is used to set :attr:`~frame." @@ -1103,7 +1241,7 @@ msgstr "" "zero, remove um valor adicional do topo da pilha, o qual é atribuído ao :" "attr:`~frame.f_lasti`` do quadro atual." -#: ../../library/dis.rst:893 +#: ../../library/dis.rst:897 msgid "" "Pops a value from the stack. Pushes the current exception to the top of the " "stack. Pushes the value originally popped back to the stack. Used in " @@ -1113,7 +1251,7 @@ msgstr "" "de volta no topo da pilha o valor que foi removido inicialmente. Usado em " "tratadores de exceções." -#: ../../library/dis.rst:901 +#: ../../library/dis.rst:905 msgid "" "Performs exception matching for ``except``. Tests whether the ``STACK[-2]`` " "is an exception matching ``STACK[-1]``. Pops ``STACK[-1]`` and pushes the " @@ -1123,7 +1261,7 @@ msgstr "" "é uma exceção que corresponde a ``STACK[-1]``. Remove ``STACK[-1]`` do topo " "da pilha, e põe no seu lugar o resultado booleano do teste." -#: ../../library/dis.rst:909 +#: ../../library/dis.rst:913 msgid "" "Performs exception matching for ``except*``. Applies ``split(STACK[-1])`` on " "the exception group representing ``STACK[-2]``." @@ -1131,7 +1269,7 @@ msgstr "" "Verifica correspondências de exceções em ``except*``. Aplica " "``split(STACK[-1])`` no grupo de exceções que representa ``STACK[-2]``." -#: ../../library/dis.rst:912 +#: ../../library/dis.rst:916 msgid "" "In case of a match, pops two items from the stack and pushes the non-" "matching subgroup (``None`` in case of full match) followed by the matching " @@ -1144,7 +1282,7 @@ msgstr "" "Quando não há correspondência nenhuma, remove um item (o tipo da " "correspondêcia) e põe ``None`` no seu lugar." -#: ../../library/dis.rst:921 +#: ../../library/dis.rst:925 msgid "" "Calls the function in position 4 on the stack with arguments (type, val, tb) " "representing the exception at the top of the stack. Used to implement the " @@ -1156,7 +1294,7 @@ msgstr "" "``context_manager.__exit__(*exc_info())`` quando uma exceção ocorreu em uma " "instrução :keyword:`with`." -#: ../../library/dis.rst:928 +#: ../../library/dis.rst:932 msgid "" "The ``__exit__`` function is in position 4 of the stack rather than 7. " "Exception representation on the stack now consist of one, not three, items." @@ -1164,7 +1302,7 @@ msgstr "" "A função ``__exit__`` fica agora na posição 4 pilha, ao invés da 7. A " "representação da exceção pilha consiste agora de um item, não três." -#: ../../library/dis.rst:935 +#: ../../library/dis.rst:939 msgid "" "Pushes :exc:`AssertionError` onto the stack. Used by the :keyword:`assert` " "statement." @@ -1172,7 +1310,7 @@ msgstr "" "Põe :exc:`AssertionError` no topo da pilha. Usado pela instrução :keyword:" "`assert`." -#: ../../library/dis.rst:943 +#: ../../library/dis.rst:947 msgid "" "Pushes :func:`!builtins.__build_class__` onto the stack. It is later called " "to construct a class." @@ -1180,7 +1318,7 @@ msgstr "" "Põe a função :func:`!builtins.__build_class__` no topo da pilha. Ela será " "chamada posteriormente para construir uma classe." -#: ../../library/dis.rst:949 +#: ../../library/dis.rst:953 msgid "" "This opcode performs several operations before a with block starts. First, " "it loads :meth:`~object.__exit__` from the context manager and pushes it " @@ -1194,11 +1332,13 @@ msgstr "" "`WITH_EXCEPT_START`. Então, o método :meth:`~object.__enter__` é chamado. " "Por fim, o resultado do ``__enter__()`` é posto no topo da pilha." -#: ../../library/dis.rst:960 -msgid "Perform ``STACK.append(len(STACK[-1]))``." -msgstr "Realiza ``STACK.append(len(STACK[-1]))``." +#: ../../library/dis.rst:964 +msgid "" +"Perform ``STACK.append(len(STACK[-1]))``. Used in :keyword:`match` " +"statements where comparison with structure of pattern is needed." +msgstr "" -#: ../../library/dis.rst:967 +#: ../../library/dis.rst:972 msgid "" "If ``STACK[-1]`` is an instance of :class:`collections.abc.Mapping` (or, " "more technically: if it has the :c:macro:`Py_TPFLAGS_MAPPING` flag set in " @@ -1210,7 +1350,7 @@ msgstr "" "definido no seu :c:member:`~PyTypeObject.tp_flags`), põe ``True`` no topo da " "pilha. Caso contrário, põe ``False``." -#: ../../library/dis.rst:977 +#: ../../library/dis.rst:982 msgid "" "If ``STACK[-1]`` is an instance of :class:`collections.abc.Sequence` and is " "*not* an instance of :class:`str`/:class:`bytes`/:class:`bytearray` (or, " @@ -1224,7 +1364,7 @@ msgstr "" "`Py_TPFLAGS_SEQUENCE` definido no seu :c:member:`~PyTypeObject.tp_flags`), " "põe ``True`` no topo da pilha. Caso contrário, põe ``False``." -#: ../../library/dis.rst:987 +#: ../../library/dis.rst:992 msgid "" "``STACK[-1]`` is a tuple of mapping keys, and ``STACK[-2]`` is the match " "subject. If ``STACK[-2]`` contains all of the keys in ``STACK[-1]``, push a :" @@ -1235,7 +1375,7 @@ msgstr "" "``STACK[-1]``, põe no topo da pilha um :class:`tuple` contendo os valores " "correspondentes. Caso contrário, põe ``None``." -#: ../../library/dis.rst:993 ../../library/dis.rst:1664 +#: ../../library/dis.rst:998 ../../library/dis.rst:1684 msgid "" "Previously, this instruction also pushed a boolean value indicating success " "(``True``) or failure (``False``)." @@ -1243,7 +1383,7 @@ msgstr "" "Anteriormente, essa instrução também colocava na pilha um valor booleano " "indicando sucesso (``True``) ou falha (``False``)." -#: ../../library/dis.rst:1000 +#: ../../library/dis.rst:1005 msgid "" "Implements ``name = STACK.pop()``. *namei* is the index of *name* in the " "attribute :attr:`~codeobject.co_names` of the :ref:`code object `." @@ -1263,7 +1403,7 @@ msgstr "" "Implementa ``del name``, onde *namei* é o índice no atributo :attr:" "`~codeobject.co_names` do :ref:`objeto de código `." -#: ../../library/dis.rst:1013 +#: ../../library/dis.rst:1018 msgid "" "Unpacks ``STACK[-1]`` into *count* individual values, which are put onto the " "stack right-to-left. Require there to be exactly *count* values.::" @@ -1272,7 +1412,13 @@ msgstr "" "postos na pilha da direita para a esquerda. Requer que haja exatamente " "*count* valores::" -#: ../../library/dis.rst:1022 +#: ../../library/dis.rst:1021 +msgid "" +"assert(len(STACK[-1]) == count)\n" +"STACK.extend(STACK.pop()[:-count-1:-1])" +msgstr "" + +#: ../../library/dis.rst:1027 msgid "" "Implements assignment with a starred target: Unpacks an iterable in " "``STACK[-1]`` into individual values, where the total number of values can " @@ -1284,13 +1430,13 @@ msgstr "" "que itens no iterável: um dos novos valores será a lista de todos os itens " "que sobraram." -#: ../../library/dis.rst:1027 +#: ../../library/dis.rst:1032 msgid "The number of values before and after the list value is limited to 255." msgstr "" "A quantidade de valores antes e após o valor que será a lista é limitada a " "255." -#: ../../library/dis.rst:1029 +#: ../../library/dis.rst:1034 msgid "" "The number of values before the list value is encoded in the argument of the " "opcode. The number of values after the list if any is encoded using an " @@ -1305,7 +1451,7 @@ msgstr "" "valores antes do valor lista, e o byte \"de cima\" de *counts*, a quantidade " "após." -#: ../../library/dis.rst:1035 +#: ../../library/dis.rst:1040 msgid "" "The extracted values are put onto the stack right-to-left, i.e. ``a, *b, c = " "d`` will be stored after execution as ``STACK.extend((a, b, c))``." @@ -1314,7 +1460,14 @@ msgstr "" "seja, após executar ``a, *b, c = d`` os valores serão armazenados como " "``STACK.extend((a, b, c))``." -#: ../../library/dis.rst:1047 +#: ../../library/dis.rst:1048 +msgid "" +"obj = STACK.pop()\n" +"value = STACK.pop()\n" +"obj.name = value" +msgstr "" + +#: ../../library/dis.rst:1052 msgid "" "where *namei* is the index of name in :attr:`~codeobject.co_names` of the :" "ref:`code object `." @@ -1322,7 +1475,13 @@ msgstr "" "onde *namei* é o índice do nome no :attr:`~codeobject.co_names` do :ref:" "`objeto de código `." -#: ../../library/dis.rst:1057 +#: ../../library/dis.rst:1059 +msgid "" +"obj = STACK.pop()\n" +"del obj.name" +msgstr "" + +#: ../../library/dis.rst:1062 msgid "" "where *namei* is the index of name into :attr:`~codeobject.co_names` of the :" "ref:`code object `." @@ -1330,21 +1489,21 @@ msgstr "" "onde *namei* é o índice do nome no :attr:`~codeobject.co_names` do :ref:" "`objeto de código `." -#: ../../library/dis.rst:1063 +#: ../../library/dis.rst:1068 msgid "Works as :opcode:`STORE_NAME`, but stores the name as a global." msgstr "" "Funciona como o :opcode:`STORE_NAME`, mas o nome é armazenado com um nome " "global." -#: ../../library/dis.rst:1068 +#: ../../library/dis.rst:1073 msgid "Works as :opcode:`DELETE_NAME`, but deletes a global name." msgstr "Funciona como o :opcode:`DELETE_NAME`, mas deleta um nome global." -#: ../../library/dis.rst:1073 +#: ../../library/dis.rst:1078 msgid "Pushes ``co_consts[consti]`` onto the stack." msgstr "Põe ``co_consts[consti]`` no topo da pilha." -#: ../../library/dis.rst:1078 +#: ../../library/dis.rst:1083 msgid "" "Pushes the value associated with ``co_names[namei]`` onto the stack. The " "name is looked up within the locals, then the globals, then the builtins." @@ -1352,14 +1511,14 @@ msgstr "" "Põe no topo da pilha o valor associado a ``co_names[namei]``. O nome é " "procurado nos locais, nos globais, e então nos embutidos." -#: ../../library/dis.rst:1084 +#: ../../library/dis.rst:1089 msgid "" "Pushes a reference to the locals dictionary onto the stack. This is used to " "prepare namespace dictionaries for :opcode:`LOAD_FROM_DICT_OR_DEREF` and :" "opcode:`LOAD_FROM_DICT_OR_GLOBALS`." msgstr "" -#: ../../library/dis.rst:1093 +#: ../../library/dis.rst:1098 msgid "" "Pops a mapping off the stack and looks up the value for ``co_names[namei]``. " "If the name is not found there, looks it up in the globals and then the " @@ -1368,69 +1527,98 @@ msgid "" "bodies." msgstr "" -#: ../../library/dis.rst:1104 +#: ../../library/dis.rst:1109 msgid "" "Creates a tuple consuming *count* items from the stack, and pushes the " "resulting tuple onto the stack::" msgstr "" -#: ../../library/dis.rst:1118 -msgid "Works as :opcode:`BUILD_TUPLE`, but creates a list." +#: ../../library/dis.rst:1112 +msgid "" +"if count == 0:\n" +" value = ()\n" +"else:\n" +" value = tuple(STACK[-count:])\n" +" STACK = STACK[:-count]\n" +"\n" +"STACK.append(value)" msgstr "" #: ../../library/dis.rst:1123 -msgid "Works as :opcode:`BUILD_TUPLE`, but creates a set." +msgid "Works as :opcode:`BUILD_TUPLE`, but creates a list." msgstr "" #: ../../library/dis.rst:1128 +msgid "Works as :opcode:`BUILD_TUPLE`, but creates a set." +msgstr "" + +#: ../../library/dis.rst:1133 msgid "" "Pushes a new dictionary object onto the stack. Pops ``2 * count`` items so " "that the dictionary holds *count* entries: ``{..., STACK[-4]: STACK[-3], " "STACK[-2]: STACK[-1]}``." msgstr "" -#: ../../library/dis.rst:1132 +#: ../../library/dis.rst:1137 msgid "" "The dictionary is created from stack items instead of creating an empty " "dictionary pre-sized to hold *count* items." msgstr "" -#: ../../library/dis.rst:1139 +#: ../../library/dis.rst:1144 msgid "" "The version of :opcode:`BUILD_MAP` specialized for constant keys. Pops the " "top element on the stack which contains a tuple of keys, then starting from " "``STACK[-2]``, pops *count* values to form values in the built dictionary." msgstr "" -#: ../../library/dis.rst:1148 +#: ../../library/dis.rst:1153 msgid "" "Concatenates *count* strings from the stack and pushes the resulting string " "onto the stack." msgstr "" -#: ../../library/dis.rst:1161 +#: ../../library/dis.rst:1163 +msgid "" +"seq = STACK.pop()\n" +"list.extend(STACK[-i], seq)" +msgstr "" + +#: ../../library/dis.rst:1166 msgid "Used to build lists." msgstr "" -#: ../../library/dis.rst:1173 +#: ../../library/dis.rst:1175 +msgid "" +"seq = STACK.pop()\n" +"set.update(STACK[-i], seq)" +msgstr "" + +#: ../../library/dis.rst:1178 msgid "Used to build sets." msgstr "" -#: ../../library/dis.rst:1185 +#: ../../library/dis.rst:1187 +msgid "" +"map = STACK.pop()\n" +"dict.update(STACK[-i], map)" +msgstr "" + +#: ../../library/dis.rst:1190 msgid "Used to build dicts." msgstr "" -#: ../../library/dis.rst:1192 +#: ../../library/dis.rst:1197 msgid "Like :opcode:`DICT_UPDATE` but raises an exception for duplicate keys." msgstr "" -#: ../../library/dis.rst:1199 +#: ../../library/dis.rst:1204 msgid "" "If the low bit of ``namei`` is not set, this replaces ``STACK[-1]`` with " "``getattr(STACK[-1], co_names[namei>>1])``." msgstr "" -#: ../../library/dis.rst:1202 +#: ../../library/dis.rst:1207 msgid "" "If the low bit of ``namei`` is set, this will attempt to load a method named " "``co_names[namei>>1]`` from the ``STACK[-1]`` object. ``STACK[-1]`` is " @@ -1442,76 +1630,76 @@ msgid "" "pushed." msgstr "" -#: ../../library/dis.rst:1211 +#: ../../library/dis.rst:1216 msgid "" "If the low bit of ``namei`` is set, then a ``NULL`` or ``self`` is pushed to " "the stack before the attribute or unbound method respectively." msgstr "" -#: ../../library/dis.rst:1218 +#: ../../library/dis.rst:1223 msgid "" "This opcode implements :func:`super`, both in its zero-argument and two-" "argument forms (e.g. ``super().method()``, ``super().attr`` and ``super(cls, " "self).method()``, ``super(cls, self).attr``)." msgstr "" -#: ../../library/dis.rst:1222 +#: ../../library/dis.rst:1227 msgid "It pops three values from the stack (from top of stack down):" msgstr "" -#: ../../library/dis.rst:1224 +#: ../../library/dis.rst:1229 msgid "``self``: the first argument to the current method" msgstr "" -#: ../../library/dis.rst:1225 +#: ../../library/dis.rst:1230 msgid "``cls``: the class within which the current method was defined" msgstr "" -#: ../../library/dis.rst:1226 +#: ../../library/dis.rst:1231 msgid "the global ``super``" msgstr "" -#: ../../library/dis.rst:1228 +#: ../../library/dis.rst:1233 msgid "" "With respect to its argument, it works similarly to :opcode:`LOAD_ATTR`, " "except that ``namei`` is shifted left by 2 bits instead of 1." msgstr "" -#: ../../library/dis.rst:1231 +#: ../../library/dis.rst:1236 msgid "" "The low bit of ``namei`` signals to attempt a method load, as with :opcode:" "`LOAD_ATTR`, which results in pushing ``NULL`` and the loaded method. When " "it is unset a single value is pushed to the stack." msgstr "" -#: ../../library/dis.rst:1235 +#: ../../library/dis.rst:1240 msgid "" "The second-low bit of ``namei``, if set, means that this was a two-argument " "call to :func:`super` (unset means zero-argument)." msgstr "" -#: ../../library/dis.rst:1243 +#: ../../library/dis.rst:1248 msgid "" "Performs a Boolean operation. The operation name can be found in " "``cmp_op[opname >> 5]``. If the fifth-lowest bit of ``opname`` is set " "(``opname & 16``), the result should be coerced to ``bool``." msgstr "" -#: ../../library/dis.rst:1247 +#: ../../library/dis.rst:1252 msgid "" "The fifth-lowest bit of the oparg now indicates a forced conversion to :" "class:`bool`." msgstr "" -#: ../../library/dis.rst:1254 +#: ../../library/dis.rst:1259 msgid "Performs ``is`` comparison, or ``is not`` if ``invert`` is 1." msgstr "" -#: ../../library/dis.rst:1261 +#: ../../library/dis.rst:1266 msgid "Performs ``in`` comparison, or ``not in`` if ``invert`` is 1." msgstr "" -#: ../../library/dis.rst:1268 +#: ../../library/dis.rst:1273 msgid "" "Imports the module ``co_names[namei]``. ``STACK[-1]`` and ``STACK[-2]`` are " "popped and provide the *fromlist* and *level* arguments of :func:" @@ -1520,68 +1708,62 @@ msgid "" "opcode:`STORE_FAST` instruction modifies the namespace." msgstr "" -#: ../../library/dis.rst:1276 +#: ../../library/dis.rst:1281 msgid "" "Loads the attribute ``co_names[namei]`` from the module found in " "``STACK[-1]``. The resulting object is pushed onto the stack, to be " "subsequently stored by a :opcode:`STORE_FAST` instruction." msgstr "" -#: ../../library/dis.rst:1283 +#: ../../library/dis.rst:1288 msgid "Increments bytecode counter by *delta*." msgstr "" -#: ../../library/dis.rst:1288 +#: ../../library/dis.rst:1293 msgid "Decrements bytecode counter by *delta*. Checks for interrupts." msgstr "" -#: ../../library/dis.rst:1295 +#: ../../library/dis.rst:1300 msgid "Decrements bytecode counter by *delta*. Does not check for interrupts." msgstr "" -#: ../../library/dis.rst:1302 +#: ../../library/dis.rst:1307 msgid "" "If ``STACK[-1]`` is true, increments the bytecode counter by *delta*. " "``STACK[-1]`` is popped." msgstr "" -#: ../../library/dis.rst:1305 ../../library/dis.rst:1321 +#: ../../library/dis.rst:1310 ../../library/dis.rst:1326 msgid "" "The oparg is now a relative delta rather than an absolute target. This " "opcode is a pseudo-instruction, replaced in final bytecode by the directed " "versions (forward/backward)." msgstr "" -#: ../../library/dis.rst:1310 ../../library/dis.rst:1326 -#: ../../library/dis.rst:1342 ../../library/dis.rst:1356 +#: ../../library/dis.rst:1315 ../../library/dis.rst:1331 +#: ../../library/dis.rst:1344 ../../library/dis.rst:1355 msgid "This is no longer a pseudo-instruction." msgstr "" -#: ../../library/dis.rst:1318 +#: ../../library/dis.rst:1323 msgid "" "If ``STACK[-1]`` is false, increments the bytecode counter by *delta*. " "``STACK[-1]`` is popped." msgstr "" -#: ../../library/dis.rst:1334 +#: ../../library/dis.rst:1339 msgid "" "If ``STACK[-1]`` is not ``None``, increments the bytecode counter by " "*delta*. ``STACK[-1]`` is popped." msgstr "" -#: ../../library/dis.rst:1337 ../../library/dis.rst:1351 -msgid "" -"This opcode is a pseudo-instruction, replaced in final bytecode by the " -"directed versions (forward/backward)." -msgstr "" - -#: ../../library/dis.rst:1348 +#: ../../library/dis.rst:1350 msgid "" "If ``STACK[-1]`` is ``None``, increments the bytecode counter by *delta*. " "``STACK[-1]`` is popped." msgstr "" -#: ../../library/dis.rst:1361 +#: ../../library/dis.rst:1360 msgid "" "``STACK[-1]`` is an :term:`iterator`. Call its :meth:`~iterator.__next__` " "method. If this yields a new value, push it on the stack (leaving the " @@ -1589,186 +1771,210 @@ msgid "" "code counter is incremented by *delta*." msgstr "" -#: ../../library/dis.rst:1366 +#: ../../library/dis.rst:1365 msgid "Up until 3.11 the iterator was popped when it was exhausted." msgstr "" -#: ../../library/dis.rst:1371 +#: ../../library/dis.rst:1370 msgid "Loads the global named ``co_names[namei>>1]`` onto the stack." msgstr "" -#: ../../library/dis.rst:1373 +#: ../../library/dis.rst:1372 msgid "" "If the low bit of ``namei`` is set, then a ``NULL`` is pushed to the stack " "before the global variable." msgstr "" -#: ../../library/dis.rst:1379 +#: ../../library/dis.rst:1378 msgid "" "Pushes a reference to the local ``co_varnames[var_num]`` onto the stack." msgstr "" -#: ../../library/dis.rst:1381 +#: ../../library/dis.rst:1380 msgid "" "This opcode is now only used in situations where the local variable is " "guaranteed to be initialized. It cannot raise :exc:`UnboundLocalError`." msgstr "" -#: ../../library/dis.rst:1387 +#: ../../library/dis.rst:1386 +msgid "" +"Pushes references to ``co_varnames[var_nums >> 4]`` and " +"``co_varnames[var_nums & 15]`` onto the stack." +msgstr "" + +#: ../../library/dis.rst:1393 msgid "" "Pushes a reference to the local ``co_varnames[var_num]`` onto the stack, " "raising an :exc:`UnboundLocalError` if the local variable has not been " "initialized." msgstr "" -#: ../../library/dis.rst:1395 +#: ../../library/dis.rst:1401 msgid "" "Pushes a reference to the local ``co_varnames[var_num]`` onto the stack (or " "pushes ``NULL`` onto the stack if the local variable has not been " "initialized) and sets ``co_varnames[var_num]`` to ``NULL``." msgstr "" -#: ../../library/dis.rst:1403 +#: ../../library/dis.rst:1409 msgid "Stores ``STACK.pop()`` into the local ``co_varnames[var_num]``." msgstr "" -#: ../../library/dis.rst:1408 +#: ../../library/dis.rst:1413 +msgid "" +"Stores ``STACK[-1]`` into ``co_varnames[var_nums >> 4]`` and ``STACK[-2]`` " +"into ``co_varnames[var_nums & 15]``." +msgstr "" + +#: ../../library/dis.rst:1420 +msgid "" +"Stores ``STACK.pop()`` into the local ``co_varnames[var_nums >> 4]`` and " +"pushes a reference to the local ``co_varnames[var_nums & 15]`` onto the " +"stack." +msgstr "" + +#: ../../library/dis.rst:1428 msgid "Deletes local ``co_varnames[var_num]``." msgstr "" -#: ../../library/dis.rst:1413 +#: ../../library/dis.rst:1433 msgid "" "Creates a new cell in slot ``i``. If that slot is nonempty then that value " "is stored into the new cell." msgstr "" -#: ../../library/dis.rst:1421 +#: ../../library/dis.rst:1441 msgid "" "Loads the cell contained in slot ``i`` of the \"fast locals\" storage. " "Pushes a reference to the object the cell contains on the stack." msgstr "" -#: ../../library/dis.rst:1424 ../../library/dis.rst:1446 -#: ../../library/dis.rst:1457 +#: ../../library/dis.rst:1444 ../../library/dis.rst:1466 +#: ../../library/dis.rst:1477 msgid "" "``i`` is no longer offset by the length of :attr:`~codeobject.co_varnames`." msgstr "" -#: ../../library/dis.rst:1430 +#: ../../library/dis.rst:1450 msgid "" "Pops a mapping off the stack and looks up the name associated with slot " "``i`` of the \"fast locals\" storage in this mapping. If the name is not " "found there, loads it from the cell contained in slot ``i``, similar to :" -"opcode:`LOAD_DEREF`. This is used for loading free variables in class bodies " -"(which previously used :opcode:`!LOAD_CLASSDEREF`) and in :ref:`annotation " -"scopes ` within class bodies." +"opcode:`LOAD_DEREF`. This is used for loading :term:`closure variables " +"` in class bodies (which previously used :opcode:`!" +"LOAD_CLASSDEREF`) and in :ref:`annotation scopes ` within " +"class bodies." msgstr "" -#: ../../library/dis.rst:1443 +#: ../../library/dis.rst:1463 msgid "" "Stores ``STACK.pop()`` into the cell contained in slot ``i`` of the \"fast " "locals\" storage." msgstr "" -#: ../../library/dis.rst:1452 +#: ../../library/dis.rst:1472 msgid "" "Empties the cell contained in slot ``i`` of the \"fast locals\" storage. " "Used by the :keyword:`del` statement." msgstr "" -#: ../../library/dis.rst:1463 +#: ../../library/dis.rst:1483 msgid "" -"Copies the ``n`` free variables from the closure into the frame. Removes the " -"need for special code on the caller's side when calling closures." +"Copies the ``n`` :term:`free (closure) variables ` from " +"the closure into the frame. Removes the need for special code on the " +"caller's side when calling closures." msgstr "" +"Copia as ``n`` :term:`variáveis livres (de clausura) ` do " +"fechamento para o quadro. Remove a necessidade de código especial do lado do " +"chamador ao chamar closures." -#: ../../library/dis.rst:1472 +#: ../../library/dis.rst:1492 msgid "" "Raises an exception using one of the 3 forms of the ``raise`` statement, " "depending on the value of *argc*:" msgstr "" -#: ../../library/dis.rst:1475 +#: ../../library/dis.rst:1495 msgid "0: ``raise`` (re-raise previous exception)" msgstr "" -#: ../../library/dis.rst:1476 +#: ../../library/dis.rst:1496 msgid "" "1: ``raise STACK[-1]`` (raise exception instance or type at ``STACK[-1]``)" msgstr "" -#: ../../library/dis.rst:1477 +#: ../../library/dis.rst:1497 msgid "" "2: ``raise STACK[-2] from STACK[-1]`` (raise exception instance or type at " "``STACK[-2]`` with ``__cause__`` set to ``STACK[-1]``)" msgstr "" -#: ../../library/dis.rst:1483 +#: ../../library/dis.rst:1503 msgid "" "Calls a callable object with the number of arguments specified by ``argc``. " "On the stack are (in ascending order):" msgstr "" -#: ../../library/dis.rst:1486 ../../library/dis.rst:1510 +#: ../../library/dis.rst:1506 ../../library/dis.rst:1530 msgid "The callable" msgstr "" -#: ../../library/dis.rst:1487 ../../library/dis.rst:1511 +#: ../../library/dis.rst:1507 ../../library/dis.rst:1531 msgid "``self`` or ``NULL``" msgstr "" -#: ../../library/dis.rst:1488 ../../library/dis.rst:1512 +#: ../../library/dis.rst:1508 ../../library/dis.rst:1532 msgid "The remaining positional arguments" msgstr "" -#: ../../library/dis.rst:1490 +#: ../../library/dis.rst:1510 msgid "``argc`` is the total of the positional arguments, excluding ``self``." msgstr "" -#: ../../library/dis.rst:1492 +#: ../../library/dis.rst:1512 msgid "" "``CALL`` pops all arguments and the callable object off the stack, calls the " "callable object with those arguments, and pushes the return value returned " "by the callable object." msgstr "" -#: ../../library/dis.rst:1498 +#: ../../library/dis.rst:1518 msgid "The callable now always appears at the same position on the stack." msgstr "" -#: ../../library/dis.rst:1501 +#: ../../library/dis.rst:1521 msgid "Calls with keyword arguments are now handled by :opcode:`CALL_KW`." msgstr "" -#: ../../library/dis.rst:1507 +#: ../../library/dis.rst:1527 msgid "" "Calls a callable object with the number of arguments specified by ``argc``, " "including one or more named arguments. On the stack are (in ascending order):" msgstr "" -#: ../../library/dis.rst:1513 +#: ../../library/dis.rst:1533 msgid "The named arguments" msgstr "" -#: ../../library/dis.rst:1514 +#: ../../library/dis.rst:1534 msgid "A :class:`tuple` of keyword argument names" msgstr "" -#: ../../library/dis.rst:1516 +#: ../../library/dis.rst:1536 msgid "" "``argc`` is the total of the positional and named arguments, excluding " "``self``. The length of the tuple of keyword argument names is the number of " "named arguments." msgstr "" -#: ../../library/dis.rst:1519 +#: ../../library/dis.rst:1539 msgid "" "``CALL_KW`` pops all arguments, the keyword names, and the callable object " "off the stack, calls the callable object with those arguments, and pushes " "the return value returned by the callable object." msgstr "" -#: ../../library/dis.rst:1528 +#: ../../library/dis.rst:1548 msgid "" "Calls a callable object with variable set of positional and keyword " "arguments. If the lowest bit of *flags* is set, the top of the stack " @@ -1780,33 +1986,33 @@ msgid "" "arguments, and pushes the return value returned by the callable object." msgstr "" -#: ../../library/dis.rst:1543 +#: ../../library/dis.rst:1563 msgid "" "Pushes a ``NULL`` to the stack. Used in the call sequence to match the " "``NULL`` pushed by :opcode:`LOAD_METHOD` for non-method calls." msgstr "" -#: ../../library/dis.rst:1552 +#: ../../library/dis.rst:1572 msgid "" "Pushes a new function object on the stack built from the code object at " -"``STACK[1]``." +"``STACK[-1]``." msgstr "" -#: ../../library/dis.rst:1554 +#: ../../library/dis.rst:1574 msgid "Flag value ``0x04`` is a tuple of strings instead of dictionary" msgstr "" -#: ../../library/dis.rst:1557 +#: ../../library/dis.rst:1577 msgid "Qualified name at ``STACK[-1]`` was removed." msgstr "" -#: ../../library/dis.rst:1560 +#: ../../library/dis.rst:1580 msgid "" "Extra function attributes on the stack, signaled by oparg flags, were " "removed. They now use :opcode:`SET_FUNCTION_ATTRIBUTE`." msgstr "" -#: ../../library/dis.rst:1567 +#: ../../library/dis.rst:1587 msgid "" "Sets an attribute on a function object. Expects the function at " "``STACK[-1]`` and the attribute value to set at ``STACK[-2]``; consumes both " @@ -1814,39 +2020,54 @@ msgid "" "attribute to set:" msgstr "" -#: ../../library/dis.rst:1571 +#: ../../library/dis.rst:1591 msgid "" "``0x01`` a tuple of default values for positional-only and positional-or-" "keyword parameters in positional order" msgstr "" -#: ../../library/dis.rst:1573 +#: ../../library/dis.rst:1593 msgid "``0x02`` a dictionary of keyword-only parameters' default values" msgstr "" -#: ../../library/dis.rst:1574 +#: ../../library/dis.rst:1594 msgid "``0x04`` a tuple of strings containing parameters' annotations" msgstr "" -#: ../../library/dis.rst:1575 +#: ../../library/dis.rst:1595 msgid "``0x08`` a tuple containing cells for free variables, making a closure" msgstr "" -#: ../../library/dis.rst:1584 +#: ../../library/dis.rst:1604 msgid "" "Pushes a slice object on the stack. *argc* must be 2 or 3. If it is 2, " "implements::" msgstr "" -#: ../../library/dis.rst:1590 +#: ../../library/dis.rst:1606 +msgid "" +"end = STACK.pop()\n" +"start = STACK.pop()\n" +"STACK.append(slice(start, end))" +msgstr "" + +#: ../../library/dis.rst:1610 msgid "if it is 3, implements::" msgstr "" -#: ../../library/dis.rst:1597 +#: ../../library/dis.rst:1612 +msgid "" +"step = STACK.pop()\n" +"end = STACK.pop()\n" +"start = STACK.pop()\n" +"STACK.append(slice(start, end, step))" +msgstr "" + +#: ../../library/dis.rst:1617 msgid "See the :func:`slice` built-in function for more information." msgstr "" -#: ../../library/dis.rst:1602 +#: ../../library/dis.rst:1622 msgid "" "Prefixes any opcode which has an argument too big to fit into the default " "one byte. *ext* holds an additional byte which act as higher bits in the " @@ -1854,43 +2075,65 @@ msgid "" "allowed, forming an argument from two-byte to four-byte." msgstr "" -#: ../../library/dis.rst:1610 +#: ../../library/dis.rst:1630 msgid "Convert value to a string, depending on ``oparg``::" msgstr "" -#: ../../library/dis.rst:1616 +#: ../../library/dis.rst:1632 +msgid "" +"value = STACK.pop()\n" +"result = func(value)\n" +"STACK.append(result)" +msgstr "" + +#: ../../library/dis.rst:1636 msgid "``oparg == 1``: call :func:`str` on *value*" msgstr "" -#: ../../library/dis.rst:1617 +#: ../../library/dis.rst:1637 msgid "``oparg == 2``: call :func:`repr` on *value*" msgstr "" -#: ../../library/dis.rst:1618 +#: ../../library/dis.rst:1638 msgid "``oparg == 3``: call :func:`ascii` on *value*" msgstr "" -#: ../../library/dis.rst:1620 ../../library/dis.rst:1633 -#: ../../library/dis.rst:1646 -msgid "Used for implementing formatted literal strings (f-strings)." +#: ../../library/dis.rst:1640 ../../library/dis.rst:1653 +#: ../../library/dis.rst:1666 +msgid "Used for implementing formatted string literals (f-strings)." msgstr "" -#: ../../library/dis.rst:1627 +#: ../../library/dis.rst:1647 msgid "Formats the value on top of stack::" msgstr "" -#: ../../library/dis.rst:1639 +#: ../../library/dis.rst:1649 +msgid "" +"value = STACK.pop()\n" +"result = value.__format__(\"\")\n" +"STACK.append(result)" +msgstr "" + +#: ../../library/dis.rst:1659 msgid "Formats the given value with the given format spec::" msgstr "" -#: ../../library/dis.rst:1653 +#: ../../library/dis.rst:1661 +msgid "" +"spec = STACK.pop()\n" +"value = STACK.pop()\n" +"result = value.__format__(spec)\n" +"STACK.append(result)" +msgstr "" + +#: ../../library/dis.rst:1673 msgid "" "``STACK[-1]`` is a tuple of keyword attribute names, ``STACK[-2]`` is the " "class being matched against, and ``STACK[-3]`` is the match subject. " "*count* is the number of positional sub-patterns." msgstr "" -#: ../../library/dis.rst:1657 +#: ../../library/dis.rst:1677 msgid "" "Pop ``STACK[-1]``, ``STACK[-2]``, and ``STACK[-3]``. If ``STACK[-3]`` is an " "instance of ``STACK[-2]`` and has the positional and keyword attributes " @@ -1898,273 +2141,281 @@ msgid "" "Otherwise, push ``None``." msgstr "" -#: ../../library/dis.rst:1671 +#: ../../library/dis.rst:1691 msgid "A no-op. Performs internal tracing, debugging and optimization checks." msgstr "" -#: ../../library/dis.rst:1673 +#: ../../library/dis.rst:1693 msgid "" "The ``context`` oparand consists of two parts. The lowest two bits indicate " "where the ``RESUME`` occurs:" msgstr "" -#: ../../library/dis.rst:1676 +#: ../../library/dis.rst:1696 msgid "" "``0`` The start of a function, which is neither a generator, coroutine nor " "an async generator" msgstr "" -#: ../../library/dis.rst:1678 +#: ../../library/dis.rst:1698 msgid "``1`` After a ``yield`` expression" msgstr "``1`` Depois de uma expressão ``yield``" -#: ../../library/dis.rst:1679 +#: ../../library/dis.rst:1699 msgid "``2`` After a ``yield from`` expression" msgstr "" -#: ../../library/dis.rst:1680 +#: ../../library/dis.rst:1700 msgid "``3`` After an ``await`` expression" msgstr "``3`` Depois de uma expressão ``await``" -#: ../../library/dis.rst:1682 +#: ../../library/dis.rst:1702 msgid "" "The next bit is ``1`` if the RESUME is at except-depth ``1``, and ``0`` " "otherwise." msgstr "" -#: ../../library/dis.rst:1687 +#: ../../library/dis.rst:1707 msgid "The oparg value changed to include information about except-depth" msgstr "" -#: ../../library/dis.rst:1693 +#: ../../library/dis.rst:1713 msgid "" "Create a generator, coroutine, or async generator from the current frame. " "Used as first opcode of in code object for the above mentioned callables. " "Clear the current frame and return the newly created generator." msgstr "" -#: ../../library/dis.rst:1702 +#: ../../library/dis.rst:1722 msgid "" "Equivalent to ``STACK[-1] = STACK[-2].send(STACK[-1])``. Used in ``yield " "from`` and ``await`` statements." msgstr "" -#: ../../library/dis.rst:1705 +#: ../../library/dis.rst:1725 msgid "" "If the call raises :exc:`StopIteration`, pop the top value from the stack, " "push the exception's ``value`` attribute, and increment the bytecode counter " "by *delta*." msgstr "" -#: ../../library/dis.rst:1714 +#: ../../library/dis.rst:1734 msgid "" "This is not really an opcode. It identifies the dividing line between " "opcodes in the range [0,255] which don't use their argument and those that " "do (``< HAVE_ARGUMENT`` and ``>= HAVE_ARGUMENT``, respectively)." msgstr "" -#: ../../library/dis.rst:1718 +#: ../../library/dis.rst:1738 msgid "" "If your application uses pseudo instructions or specialized instructions, " "use the :data:`hasarg` collection instead." msgstr "" -#: ../../library/dis.rst:1721 +#: ../../library/dis.rst:1741 msgid "" "Now every instruction has an argument, but opcodes ``< HAVE_ARGUMENT`` " "ignore it. Before, only opcodes ``>= HAVE_ARGUMENT`` had an argument." msgstr "" -#: ../../library/dis.rst:1725 +#: ../../library/dis.rst:1745 msgid "" "Pseudo instructions were added to the :mod:`dis` module, and for them it is " "not true that comparison with ``HAVE_ARGUMENT`` indicates whether they use " "their arg." msgstr "" -#: ../../library/dis.rst:1730 +#: ../../library/dis.rst:1750 msgid "Use :data:`hasarg` instead." msgstr "" -#: ../../library/dis.rst:1735 +#: ../../library/dis.rst:1755 msgid "" "Calls an intrinsic function with one argument. Passes ``STACK[-1]`` as the " "argument and sets ``STACK[-1]`` to the result. Used to implement " "functionality that is not performance critical." msgstr "" -#: ../../library/dis.rst:1739 ../../library/dis.rst:1793 +#: ../../library/dis.rst:1759 ../../library/dis.rst:1813 msgid "The operand determines which intrinsic function is called:" msgstr "" -#: ../../library/dis.rst:1742 ../../library/dis.rst:1796 +#: ../../library/dis.rst:1762 ../../library/dis.rst:1816 msgid "Operand" msgstr "" -#: ../../library/dis.rst:1742 ../../library/dis.rst:1796 +#: ../../library/dis.rst:1762 ../../library/dis.rst:1816 msgid "Description" msgstr "Descrição" -#: ../../library/dis.rst:1744 +#: ../../library/dis.rst:1764 msgid "``INTRINSIC_1_INVALID``" msgstr "``INTRINSIC_1_INVALID``" -#: ../../library/dis.rst:1744 ../../library/dis.rst:1798 +#: ../../library/dis.rst:1764 ../../library/dis.rst:1818 msgid "Not valid" msgstr "" -#: ../../library/dis.rst:1746 +#: ../../library/dis.rst:1766 msgid "``INTRINSIC_PRINT``" msgstr "``INTRINSIC_PRINT``" -#: ../../library/dis.rst:1746 +#: ../../library/dis.rst:1766 msgid "Prints the argument to standard out. Used in the REPL." msgstr "" -#: ../../library/dis.rst:1749 +#: ../../library/dis.rst:1769 msgid "``INTRINSIC_IMPORT_STAR``" msgstr "``INTRINSIC_IMPORT_STAR``" -#: ../../library/dis.rst:1749 +#: ../../library/dis.rst:1769 msgid "Performs ``import *`` for the named module." msgstr "" -#: ../../library/dis.rst:1752 +#: ../../library/dis.rst:1772 msgid "``INTRINSIC_STOPITERATION_ERROR``" msgstr "``INTRINSIC_STOPITERATION_ERROR``" -#: ../../library/dis.rst:1752 +#: ../../library/dis.rst:1772 msgid "Extracts the return value from a ``StopIteration`` exception." msgstr "" -#: ../../library/dis.rst:1755 +#: ../../library/dis.rst:1775 msgid "``INTRINSIC_ASYNC_GEN_WRAP``" msgstr "``INTRINSIC_ASYNC_GEN_WRAP``" -#: ../../library/dis.rst:1755 +#: ../../library/dis.rst:1775 msgid "Wraps an async generator value" msgstr "" -#: ../../library/dis.rst:1757 +#: ../../library/dis.rst:1777 msgid "``INTRINSIC_UNARY_POSITIVE``" msgstr "``INTRINSIC_UNARY_POSITIVE``" -#: ../../library/dis.rst:1757 +#: ../../library/dis.rst:1777 msgid "Performs the unary ``+`` operation" msgstr "" -#: ../../library/dis.rst:1760 +#: ../../library/dis.rst:1780 msgid "``INTRINSIC_LIST_TO_TUPLE``" msgstr "``INTRINSIC_LIST_TO_TUPLE``" -#: ../../library/dis.rst:1760 +#: ../../library/dis.rst:1780 msgid "Converts a list to a tuple" msgstr "" -#: ../../library/dis.rst:1762 +#: ../../library/dis.rst:1782 msgid "``INTRINSIC_TYPEVAR``" msgstr "``INTRINSIC_TYPEVAR``" -#: ../../library/dis.rst:1762 +#: ../../library/dis.rst:1782 msgid "Creates a :class:`typing.TypeVar`" msgstr "Cria um :class:`typing.TypeVar`" -#: ../../library/dis.rst:1764 +#: ../../library/dis.rst:1784 msgid "``INTRINSIC_PARAMSPEC``" msgstr "``INTRINSIC_PARAMSPEC``" -#: ../../library/dis.rst:1764 +#: ../../library/dis.rst:1784 msgid "Creates a :class:`typing.ParamSpec`" msgstr "Cria um :class:`typing.ParamSpec`" -#: ../../library/dis.rst:1767 +#: ../../library/dis.rst:1787 msgid "``INTRINSIC_TYPEVARTUPLE``" msgstr "``INTRINSIC_TYPEVARTUPLE``" -#: ../../library/dis.rst:1767 +#: ../../library/dis.rst:1787 msgid "Creates a :class:`typing.TypeVarTuple`" msgstr "Cria um :class:`typing.TypeVarTuple`" -#: ../../library/dis.rst:1770 +#: ../../library/dis.rst:1790 msgid "``INTRINSIC_SUBSCRIPT_GENERIC``" msgstr "``INTRINSIC_SUBSCRIPT_GENERIC``" -#: ../../library/dis.rst:1770 +#: ../../library/dis.rst:1790 msgid "Returns :class:`typing.Generic` subscripted with the argument" msgstr "" -#: ../../library/dis.rst:1773 +#: ../../library/dis.rst:1793 msgid "``INTRINSIC_TYPEALIAS``" msgstr "``INTRINSIC_TYPEALIAS``" -#: ../../library/dis.rst:1773 +#: ../../library/dis.rst:1793 msgid "" "Creates a :class:`typing.TypeAliasType`; used in the :keyword:`type` " "statement. The argument is a tuple of the type alias's name, type " "parameters, and value." msgstr "" -#: ../../library/dis.rst:1785 +#: ../../library/dis.rst:1805 msgid "" "Calls an intrinsic function with two arguments. Used to implement " "functionality that is not performance critical::" msgstr "" -#: ../../library/dis.rst:1798 +#: ../../library/dis.rst:1808 +msgid "" +"arg2 = STACK.pop()\n" +"arg1 = STACK.pop()\n" +"result = intrinsic2(arg1, arg2)\n" +"STACK.append(result)" +msgstr "" + +#: ../../library/dis.rst:1818 msgid "``INTRINSIC_2_INVALID``" msgstr "``INTRINSIC_2_INVALID``" -#: ../../library/dis.rst:1800 +#: ../../library/dis.rst:1820 msgid "``INTRINSIC_PREP_RERAISE_STAR``" msgstr "``INTRINSIC_PREP_RERAISE_STAR``" -#: ../../library/dis.rst:1800 +#: ../../library/dis.rst:1820 msgid "Calculates the :exc:`ExceptionGroup` to raise from a ``try-except*``." msgstr "" -#: ../../library/dis.rst:1804 +#: ../../library/dis.rst:1824 msgid "``INTRINSIC_TYPEVAR_WITH_BOUND``" msgstr "``INTRINSIC_TYPEVAR_WITH_BOUND``" -#: ../../library/dis.rst:1804 +#: ../../library/dis.rst:1824 msgid "Creates a :class:`typing.TypeVar` with a bound." msgstr "" -#: ../../library/dis.rst:1807 +#: ../../library/dis.rst:1827 msgid "``INTRINSIC_TYPEVAR_WITH_CONSTRAINTS``" msgstr "``INTRINSIC_TYPEVAR_WITH_CONSTRAINTS``" -#: ../../library/dis.rst:1807 +#: ../../library/dis.rst:1827 msgid "Creates a :class:`typing.TypeVar` with constraints." msgstr "" -#: ../../library/dis.rst:1811 +#: ../../library/dis.rst:1831 msgid "``INTRINSIC_SET_FUNCTION_TYPE_PARAMS``" msgstr "``INTRINSIC_SET_FUNCTION_TYPE_PARAMS``" -#: ../../library/dis.rst:1811 +#: ../../library/dis.rst:1831 msgid "Sets the ``__type_params__`` attribute of a function." msgstr "" -#: ../../library/dis.rst:1818 +#: ../../library/dis.rst:1838 msgid "**Pseudo-instructions**" msgstr "" -#: ../../library/dis.rst:1820 +#: ../../library/dis.rst:1840 msgid "" "These opcodes do not appear in Python bytecode. They are used by the " "compiler but are replaced by real opcodes or removed before bytecode is " "generated." msgstr "" -#: ../../library/dis.rst:1825 +#: ../../library/dis.rst:1845 msgid "" "Set up an exception handler for the following code block. If an exception " "occurs, the value stack level is restored to its current state and control " "is transferred to the exception handler at ``target``." msgstr "" -#: ../../library/dis.rst:1832 +#: ../../library/dis.rst:1852 msgid "" "Like ``SETUP_FINALLY``, but in case of an exception also pushes the last " "instruction (``lasti``) to the stack so that ``RERAISE`` can restore it. If " @@ -2173,138 +2424,139 @@ msgid "" "exception handler at ``target``." msgstr "" -#: ../../library/dis.rst:1841 +#: ../../library/dis.rst:1861 msgid "" "Like ``SETUP_CLEANUP``, but in case of an exception one more item is popped " "from the stack before control is transferred to the exception handler at " "``target``." msgstr "" -#: ../../library/dis.rst:1845 +#: ../../library/dis.rst:1865 msgid "" "This variant is used in :keyword:`with` and :keyword:`async with` " "constructs, which push the return value of the context manager's :meth:" "`~object.__enter__` or :meth:`~object.__aenter__` to the stack." msgstr "" -#: ../../library/dis.rst:1852 +#: ../../library/dis.rst:1872 msgid "" "Marks the end of the code block associated with the last ``SETUP_FINALLY``, " "``SETUP_CLEANUP`` or ``SETUP_WITH``." msgstr "" -#: ../../library/dis.rst:1858 +#: ../../library/dis.rst:1878 msgid "" "Undirected relative jump instructions which are replaced by their directed " "(forward/backward) counterparts by the assembler." msgstr "" -#: ../../library/dis.rst:1863 +#: ../../library/dis.rst:1883 msgid "" "Pushes a reference to the cell contained in slot ``i`` of the \"fast " "locals\" storage." msgstr "" -#: ../../library/dis.rst:1866 +#: ../../library/dis.rst:1886 msgid "" "Note that ``LOAD_CLOSURE`` is replaced with ``LOAD_FAST`` in the assembler." msgstr "" -#: ../../library/dis.rst:1868 +#: ../../library/dis.rst:1888 msgid "This opcode is now a pseudo-instruction." msgstr "" -#: ../../library/dis.rst:1874 +#: ../../library/dis.rst:1894 msgid "" "Optimized unbound method lookup. Emitted as a ``LOAD_ATTR`` opcode with a " "flag set in the arg." msgstr "" -#: ../../library/dis.rst:1881 +#: ../../library/dis.rst:1901 msgid "Opcode collections" msgstr "" -#: ../../library/dis.rst:1883 +#: ../../library/dis.rst:1903 msgid "" "These collections are provided for automatic introspection of bytecode " "instructions:" msgstr "" -#: ../../library/dis.rst:1886 +#: ../../library/dis.rst:1906 msgid "" "The collections now contain pseudo instructions and instrumented " "instructions as well. These are opcodes with values ``>= MIN_PSEUDO_OPCODE`` " "and ``>= MIN_INSTRUMENTED_OPCODE``." msgstr "" -#: ../../library/dis.rst:1893 +#: ../../library/dis.rst:1913 msgid "Sequence of operation names, indexable using the bytecode." msgstr "" -#: ../../library/dis.rst:1898 +#: ../../library/dis.rst:1918 msgid "Dictionary mapping operation names to bytecodes." msgstr "" -#: ../../library/dis.rst:1903 +#: ../../library/dis.rst:1923 msgid "Sequence of all compare operation names." msgstr "" -#: ../../library/dis.rst:1908 +#: ../../library/dis.rst:1928 msgid "Sequence of bytecodes that use their argument." msgstr "" -#: ../../library/dis.rst:1915 +#: ../../library/dis.rst:1935 msgid "Sequence of bytecodes that access a constant." msgstr "" -#: ../../library/dis.rst:1920 +#: ../../library/dis.rst:1940 msgid "" -"Sequence of bytecodes that access a free variable. 'free' in this context " -"refers to names in the current scope that are referenced by inner scopes or " -"names in outer scopes that are referenced from this scope. It does *not* " -"include references to global or builtin scopes." +"Sequence of bytecodes that access a :term:`free (closure) variable `. 'free' in this context refers to names in the current scope that " +"are referenced by inner scopes or names in outer scopes that are referenced " +"from this scope. It does *not* include references to global or builtin " +"scopes." msgstr "" -#: ../../library/dis.rst:1928 +#: ../../library/dis.rst:1948 msgid "Sequence of bytecodes that access an attribute by name." msgstr "" -#: ../../library/dis.rst:1933 +#: ../../library/dis.rst:1953 msgid "Sequence of bytecodes that have a jump target. All jumps are relative." msgstr "" -#: ../../library/dis.rst:1940 +#: ../../library/dis.rst:1960 msgid "Sequence of bytecodes that access a local variable." msgstr "" -#: ../../library/dis.rst:1945 +#: ../../library/dis.rst:1965 msgid "Sequence of bytecodes of Boolean operations." msgstr "" -#: ../../library/dis.rst:1949 +#: ../../library/dis.rst:1969 msgid "Sequence of bytecodes that set an exception handler." msgstr "" -#: ../../library/dis.rst:1956 +#: ../../library/dis.rst:1976 msgid "Sequence of bytecodes that have a relative jump target." msgstr "" -#: ../../library/dis.rst:1958 +#: ../../library/dis.rst:1978 msgid "All jumps are now relative. Use :data:`hasjump`." msgstr "" -#: ../../library/dis.rst:1964 +#: ../../library/dis.rst:1984 msgid "Sequence of bytecodes that have an absolute jump target." msgstr "" -#: ../../library/dis.rst:1966 +#: ../../library/dis.rst:1986 msgid "All jumps are now relative. This list is empty." msgstr "" -#: ../../library/dis.rst:1582 +#: ../../library/dis.rst:1602 msgid "built-in function" msgstr "função embutida" -#: ../../library/dis.rst:1582 +#: ../../library/dis.rst:1602 msgid "slice" msgstr "fatia" diff --git a/library/distribution.po b/library/distribution.po index 625079528..04a00870c 100644 --- a/library/distribution.po +++ b/library/distribution.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:04+0000\n" -"Last-Translator: Rafael Fontenelle , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/distutils.po b/library/distutils.po new file mode 100644 index 000000000..8edbcb220 --- /dev/null +++ b/library/distutils.po @@ -0,0 +1,49 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../library/distutils.rst:2 +msgid ":mod:`!distutils` --- Building and installing Python modules" +msgstr ":mod:`!distutils` --- Criação e instalação de módulos do Python" + +#: ../../library/distutils.rst:10 +msgid "" +"This module is no longer part of the Python standard library. It was :ref:" +"`removed in Python 3.12 ` after being " +"deprecated in Python 3.10. The removal was decided in :pep:`632`, which has " +"`migration advice `_." +msgstr "" +"Este módulo não faz mais parte da biblioteca padrão do Python. Ele foi :ref:" +"`removido no Python 3.12 ` após ser " +"descontinuado no Python 3.10. A remoção foi decidida na :pep:`632`, a qual " +"tem um `conselho de migração `_." + +#: ../../library/distutils.rst:16 +msgid "" +"The last version of Python that provided the :mod:`!distutils` module was " +"`Python 3.11 `_." +msgstr "" +"A última versão do Python que forneceu o módulo :mod:`!distutils` foi o " +"`Python 3.11 `_." diff --git a/library/doctest.po b/library/doctest.po index 081b18f0f..8703550ce 100644 --- a/library/doctest.po +++ b/library/doctest.po @@ -1,37 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Marques , 2021 -# Raphael Mendonça, 2023 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 02:33+0000\n" -"PO-Revision-Date: 2021-06-28 01:04+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-03-21 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/doctest.rst:2 msgid ":mod:`!doctest` --- Test interactive Python examples" -msgstr "" +msgstr ":mod:`!doctest` --- Teste exemplos interativos de Python" #: ../../library/doctest.rst:12 msgid "**Source code:** :source:`Lib/doctest.py`" @@ -80,6 +74,118 @@ msgstr "" msgid "Here's a complete but small example module::" msgstr "Aqui temos um pequeno exemplo, porém, completo::" +#: ../../library/doctest.rst:33 +msgid "" +"\"\"\"\n" +"This is the \"example\" module.\n" +"\n" +"The example module supplies one function, factorial(). For example,\n" +"\n" +">>> factorial(5)\n" +"120\n" +"\"\"\"\n" +"\n" +"def factorial(n):\n" +" \"\"\"Return the factorial of n, an exact integer >= 0.\n" +"\n" +" >>> [factorial(n) for n in range(6)]\n" +" [1, 1, 2, 6, 24, 120]\n" +" >>> factorial(30)\n" +" 265252859812191058636308480000000\n" +" >>> factorial(-1)\n" +" Traceback (most recent call last):\n" +" ...\n" +" ValueError: n must be >= 0\n" +"\n" +" Factorials of floats are OK, but the float must be an exact integer:\n" +" >>> factorial(30.1)\n" +" Traceback (most recent call last):\n" +" ...\n" +" ValueError: n must be exact integer\n" +" >>> factorial(30.0)\n" +" 265252859812191058636308480000000\n" +"\n" +" It must also not be ridiculously large:\n" +" >>> factorial(1e100)\n" +" Traceback (most recent call last):\n" +" ...\n" +" OverflowError: n too large\n" +" \"\"\"\n" +"\n" +" import math\n" +" if not n >= 0:\n" +" raise ValueError(\"n must be >= 0\")\n" +" if math.floor(n) != n:\n" +" raise ValueError(\"n must be exact integer\")\n" +" if n+1 == n: # catch a value like 1e300\n" +" raise OverflowError(\"n too large\")\n" +" result = 1\n" +" factor = 2\n" +" while factor <= n:\n" +" result *= factor\n" +" factor += 1\n" +" return result\n" +"\n" +"\n" +"if __name__ == \"__main__\":\n" +" import doctest\n" +" doctest.testmod()" +msgstr "" +"\"\"\"\n" +"This is the \"example\" module.\n" +"\n" +"The example module supplies one function, factorial(). For example,\n" +"\n" +">>> factorial(5)\n" +"120\n" +"\"\"\"\n" +"\n" +"def factorial(n):\n" +" \"\"\"Return the factorial of n, an exact integer >= 0.\n" +"\n" +" >>> [factorial(n) for n in range(6)]\n" +" [1, 1, 2, 6, 24, 120]\n" +" >>> factorial(30)\n" +" 265252859812191058636308480000000\n" +" >>> factorial(-1)\n" +" Traceback (most recent call last):\n" +" ...\n" +" ValueError: n must be >= 0\n" +"\n" +" Factorials of floats are OK, but the float must be an exact integer:\n" +" >>> factorial(30.1)\n" +" Traceback (most recent call last):\n" +" ...\n" +" ValueError: n must be exact integer\n" +" >>> factorial(30.0)\n" +" 265252859812191058636308480000000\n" +"\n" +" It must also not be ridiculously large:\n" +" >>> factorial(1e100)\n" +" Traceback (most recent call last):\n" +" ...\n" +" OverflowError: n too large\n" +" \"\"\"\n" +"\n" +" import math\n" +" if not n >= 0:\n" +" raise ValueError(\"n must be >= 0\")\n" +" if math.floor(n) != n:\n" +" raise ValueError(\"n must be exact integer\")\n" +" if n+1 == n: # catch a value like 1e300\n" +" raise OverflowError(\"n too large\")\n" +" result = 1\n" +" factor = 2\n" +" while factor <= n:\n" +" result *= factor\n" +" factor += 1\n" +" return result\n" +"\n" +"\n" +"if __name__ == \"__main__\":\n" +" import doctest\n" +" doctest.testmod()" + #: ../../library/doctest.rst:88 msgid "" "If you run :file:`example.py` directly from the command line, :mod:`doctest` " @@ -88,6 +194,14 @@ msgstr "" "Se executar diretamente :file:`example.py` desde a linha de comando, :mod:" "`doctest` a mágica funcionará:" +#: ../../library/doctest.rst:91 +msgid "" +"$ python example.py\n" +"$" +msgstr "" +"$ python example.py\n" +"$" + #: ../../library/doctest.rst:96 msgid "" "There's no output! That's normal, and it means all the examples worked. " @@ -99,10 +213,68 @@ msgstr "" "mod:`doctest` imprimirá um registro detalhado do que está sendo testando " "imprimindo ainda um resumo no final:" +#: ../../library/doctest.rst:100 +msgid "" +"$ python example.py -v\n" +"Trying:\n" +" factorial(5)\n" +"Expecting:\n" +" 120\n" +"ok\n" +"Trying:\n" +" [factorial(n) for n in range(6)]\n" +"Expecting:\n" +" [1, 1, 2, 6, 24, 120]\n" +"ok" +msgstr "" +"$ python example.py -v\n" +"Trying:\n" +" factorial(5)\n" +"Expecting:\n" +" 120\n" +"ok\n" +"Trying:\n" +" [factorial(n) for n in range(6)]\n" +"Expecting:\n" +" [1, 1, 2, 6, 24, 120]\n" +"ok" + #: ../../library/doctest.rst:114 msgid "And so on, eventually ending with:" msgstr "E assim por diante, eventualmente terminando com:" +#: ../../library/doctest.rst:116 +msgid "" +"Trying:\n" +" factorial(1e100)\n" +"Expecting:\n" +" Traceback (most recent call last):\n" +" ...\n" +" OverflowError: n too large\n" +"ok\n" +"2 items passed all tests:\n" +" 1 test in __main__\n" +" 6 tests in __main__.factorial\n" +"7 tests in 2 items.\n" +"7 passed.\n" +"Test passed.\n" +"$" +msgstr "" +"Trying:\n" +" factorial(1e100)\n" +"Expecting:\n" +" Traceback (most recent call last):\n" +" ...\n" +" OverflowError: n too large\n" +"ok\n" +"2 items passed all tests:\n" +" 1 test in __main__\n" +" 6 tests in __main__.factorial\n" +"7 tests in 2 items.\n" +"7 passed.\n" +"Test passed.\n" +"$" + #: ../../library/doctest.rst:133 msgid "" "That's all you need to know to start making productive use of :mod:" @@ -130,6 +302,16 @@ msgstr "" "a maneira como você continuará fazendo isso) é encerrar cada módulo :mod:`!" "M` com::" +#: ../../library/doctest.rst:148 +msgid "" +"if __name__ == \"__main__\":\n" +" import doctest\n" +" doctest.testmod()" +msgstr "" +"if __name__ == \"__main__\":\n" +" import doctest\n" +" doctest.testmod()" + #: ../../library/doctest.rst:152 msgid ":mod:`!doctest` then examines docstrings in module :mod:`!M`." msgstr ":mod:`!doctest` e então examine a docstrings no módulo :mod:`!M`." @@ -142,6 +324,10 @@ msgstr "" "Executar o módulo como um script faz com que os exemplos nas docstrings " "sejam executados e verificados::" +#: ../../library/doctest.rst:157 +msgid "python M.py" +msgstr "python M.py" + #: ../../library/doctest.rst:159 msgid "" "This won't display anything unless an example fails, in which case the " @@ -158,6 +344,10 @@ msgstr "" msgid "Run it with the ``-v`` switch instead::" msgstr "Ao invés disso, execute agora com a opção ``-v``::" +#: ../../library/doctest.rst:166 +msgid "python M.py -v" +msgstr "python M.py -v" + #: ../../library/doctest.rst:168 msgid "" "and a detailed report of all examples tried is printed to standard output, " @@ -180,25 +370,11 @@ msgstr "" #: ../../library/doctest.rst:176 msgid "" -"There is also a command line shortcut for running :func:`testmod`. You can " -"instruct the Python interpreter to run the doctest module directly from the " -"standard library and pass the module name(s) on the command line::" -msgstr "" -"Há também um atalho de linha de comando para executar :func:`testmod`. Você " -"pode instruir o interpretador Python a executar o módulo doctest diretamente " -"da biblioteca padrão e passar o(s) nome(s) do módulo na linha de comando:" - -#: ../../library/doctest.rst:182 -msgid "" -"This will import :file:`example.py` as a standalone module and run :func:" -"`testmod` on it. Note that this may not work correctly if the file is part " -"of a package and imports other submodules from that package." +"There is also a command line shortcut for running :func:`testmod`, see " +"section :ref:`doctest-cli`." msgstr "" -"Isso importará :file:`example.py` como um módulo independente e executará :" -"func:`testmod` nele. Observe que isso pode não funcionar corretamente se o " -"arquivo fizer parte de um pacote e importar outros submódulos desse pacote." -#: ../../library/doctest.rst:186 +#: ../../library/doctest.rst:179 msgid "" "For more information on :func:`testmod`, see section :ref:`doctest-basic-" "api`." @@ -206,11 +382,11 @@ msgstr "" "Para mais informações sobre :func:`testmod`, veja a seção :ref:`doctest-" "basic-api`." -#: ../../library/doctest.rst:192 +#: ../../library/doctest.rst:185 msgid "Simple Usage: Checking Examples in a Text File" msgstr "Utilização comum: Verificando exemplos em um arquivo texto" -#: ../../library/doctest.rst:194 +#: ../../library/doctest.rst:187 msgid "" "Another simple application of doctest is testing interactive examples in a " "text file. This can be done with the :func:`testfile` function::" @@ -218,7 +394,15 @@ msgstr "" "Outra aplicação simples do doctest é testar exemplos interativos em um " "arquivo texto. Isso pode ser feito com a função :func:`testfile`::" -#: ../../library/doctest.rst:200 +#: ../../library/doctest.rst:190 +msgid "" +"import doctest\n" +"doctest.testfile(\"example.txt\")" +msgstr "" +"import doctest\n" +"doctest.testfile(\"example.txt\")" + +#: ../../library/doctest.rst:193 msgid "" "That short script executes and verifies any interactive Python examples " "contained in the file :file:`example.txt`. The file content is treated as " @@ -231,7 +415,41 @@ msgstr "" "conter um programa Python! Por exemplo, talvez :file:`example.txt` contenha " "isto:" -#: ../../library/doctest.rst:223 +#: ../../library/doctest.rst:198 +msgid "" +"The ``example`` module\n" +"======================\n" +"\n" +"Using ``factorial``\n" +"-------------------\n" +"\n" +"This is an example text file in reStructuredText format. First import\n" +"``factorial`` from the ``example`` module:\n" +"\n" +" >>> from example import factorial\n" +"\n" +"Now use it:\n" +"\n" +" >>> factorial(6)\n" +" 120" +msgstr "" +"The ``example`` module\n" +"======================\n" +"\n" +"Using ``factorial``\n" +"-------------------\n" +"\n" +"This is an example text file in reStructuredText format. First import\n" +"``factorial`` from the ``example`` module:\n" +"\n" +" >>> from example import factorial\n" +"\n" +"Now use it:\n" +"\n" +" >>> factorial(6)\n" +" 120" + +#: ../../library/doctest.rst:216 msgid "" "Running ``doctest.testfile(\"example.txt\")`` then finds the error in this " "documentation::" @@ -239,7 +457,25 @@ msgstr "" "Executar ``doctest.testfile(\"example.txt\")`` então encontra o erro nesta " "documentação::" -#: ../../library/doctest.rst:234 +#: ../../library/doctest.rst:219 +msgid "" +"File \"./example.txt\", line 14, in example.txt\n" +"Failed example:\n" +" factorial(6)\n" +"Expected:\n" +" 120\n" +"Got:\n" +" 720" +msgstr "" +"File \"./example.txt\", line 14, in example.txt\n" +"Failed example:\n" +" factorial(6)\n" +"Expected:\n" +" 120\n" +"Got:\n" +" 720" + +#: ../../library/doctest.rst:227 msgid "" "As with :func:`testmod`, :func:`testfile` won't display anything unless an " "example fails. If an example does fail, then the failing example(s) and the " @@ -251,7 +487,7 @@ msgstr "" "a(s) causa(s) da(s) falha(s) são impressos em stdout, usando o mesmo formato " "que :func:`testmod`." -#: ../../library/doctest.rst:239 +#: ../../library/doctest.rst:232 msgid "" "By default, :func:`testfile` looks for files in the calling module's " "directory. See section :ref:`doctest-basic-api` for a description of the " @@ -263,7 +499,7 @@ msgstr "" "argumentos opcionais que podem ser usados para dizer para procurar por " "arquivos em outros locais." -#: ../../library/doctest.rst:243 +#: ../../library/doctest.rst:236 msgid "" "Like :func:`testmod`, :func:`testfile`'s verbosity can be set with the ``-" "v`` command-line switch or with the optional keyword argument *verbose*." @@ -272,26 +508,13 @@ msgstr "" "definida com a opção de linha de comando ``-v`` ou com o argumento nomeado " "opcional *verbose*." -#: ../../library/doctest.rst:247 -msgid "" -"There is also a command line shortcut for running :func:`testfile`. You can " -"instruct the Python interpreter to run the doctest module directly from the " -"standard library and pass the file name(s) on the command line::" -msgstr "" -"Há também um atalho de linha de comando para executar :func:`testfile`. Você " -"pode instruir o interpretador Python a executar o módulo doctest diretamente " -"da biblioteca padrão e passar o(s) nome(s) do(s) arquivo(s) na linha de " -"comando::" - -#: ../../library/doctest.rst:253 +#: ../../library/doctest.rst:240 msgid "" -"Because the file name does not end with :file:`.py`, :mod:`doctest` infers " -"that it must be run with :func:`testfile`, not :func:`testmod`." +"There is also a command line shortcut for running :func:`testfile`, see " +"section :ref:`doctest-cli`." msgstr "" -"Como o nome do arquivo não termina com :file:`.py`, :mod:`doctest` infere " -"que ele deve ser executado com :func:`testfile`, não :func:`testmod`." -#: ../../library/doctest.rst:256 +#: ../../library/doctest.rst:243 msgid "" "For more information on :func:`testfile`, see section :ref:`doctest-basic-" "api`." @@ -299,11 +522,61 @@ msgstr "" "Para maiores informações em :func:`testfile`, veja a seção :ref:`doctest-" "basic-api`." -#: ../../library/doctest.rst:262 +#: ../../library/doctest.rst:249 +msgid "Command-line Usage" +msgstr "" + +#: ../../library/doctest.rst:251 +msgid "" +"The :mod:`doctest` module can be invoked as a script from the command line:" +msgstr "" + +#: ../../library/doctest.rst:253 +msgid "python -m doctest [-v] [-o OPTION] [-f] file [file ...]" +msgstr "" + +#: ../../library/doctest.rst:261 +msgid "" +"Detailed report of all examples tried is printed to standard output, along " +"with assorted summaries at the end::" +msgstr "" + +#: ../../library/doctest.rst:264 +msgid "python -m doctest -v example.py" +msgstr "python -m doctest -v example.py" + +#: ../../library/doctest.rst:266 +msgid "" +"This will import :file:`example.py` as a standalone module and run :func:" +"`testmod` on it. Note that this may not work correctly if the file is part " +"of a package and imports other submodules from that package." +msgstr "" + +#: ../../library/doctest.rst:270 +msgid "" +"If the file name does not end with :file:`.py`, :mod:`!doctest` infers that " +"it must be run with :func:`testfile` instead::" +msgstr "" + +#: ../../library/doctest.rst:273 +msgid "python -m doctest -v example.txt" +msgstr "python -m doctest -v example.txt" + +#: ../../library/doctest.rst:277 +msgid "" +"Option flags control various aspects of doctest's behavior, see section :ref:" +"`doctest-options`." +msgstr "" + +#: ../../library/doctest.rst:284 +msgid "This is shorthand for ``-o FAIL_FAST``." +msgstr "" + +#: ../../library/doctest.rst:292 msgid "How It Works" msgstr "Como ele funciona" -#: ../../library/doctest.rst:264 +#: ../../library/doctest.rst:294 msgid "" "This section examines in detail how doctest works: which docstrings it looks " "at, how it finds interactive examples, what execution context it uses, how " @@ -320,11 +593,11 @@ msgstr "" "sobre como realmente executar o doctest nesses exemplos, consulte as seções " "a seguir." -#: ../../library/doctest.rst:275 +#: ../../library/doctest.rst:305 msgid "Which Docstrings Are Examined?" msgstr "Quais docstrings são examinadas?" -#: ../../library/doctest.rst:277 +#: ../../library/doctest.rst:307 msgid "" "The module docstring, and all function, class and method docstrings are " "searched. Objects imported into the module are not searched." @@ -332,7 +605,7 @@ msgstr "" "A docstring do módulo e todas as docstrings de funções, classes e métodos " "são pesquisadas. Os objetos importados para o módulo não são pesquisados." -#: ../../library/doctest.rst:280 +#: ../../library/doctest.rst:310 msgid "" "In addition, there are cases when you want tests to be part of a module but " "not part of the help text, which requires that the tests not be included in " @@ -354,12 +627,34 @@ msgstr "" "strings são tratadas como se fossem docstrings. Na saída, uma chave ``K`` em " "``M.__test__`` aparece com o nome ``M.__test__.K``." -#: ../../library/doctest.rst:289 +#: ../../library/doctest.rst:319 msgid "For example, place this block of code at the top of :file:`example.py`:" msgstr "" "Por exemplo, coloque este bloco de código no topo de :file:`example.py`:" -#: ../../library/doctest.rst:303 +#: ../../library/doctest.rst:321 +msgid "" +"__test__ = {\n" +" 'numbers': \"\"\"\n" +">>> factorial(6)\n" +"720\n" +"\n" +">>> [factorial(n) for n in range(6)]\n" +"[1, 1, 2, 6, 24, 120]\n" +"\"\"\"\n" +"}" +msgstr "" +"__test__ = {\n" +" 'numbers': \"\"\"\n" +">>> factorial(6)\n" +"720\n" +"\n" +">>> [factorial(n) for n in range(6)]\n" +"[1, 1, 2, 6, 24, 120]\n" +"\"\"\"\n" +"}" + +#: ../../library/doctest.rst:333 msgid "" "The value of ``example.__test__[\"numbers\"]`` will be treated as a " "docstring and all the tests inside it will be run. It is important to note " @@ -373,7 +668,7 @@ msgstr "" "mod:`!doctest` pesquisa recursivamente em busca de docstrings, que são então " "escaneados em busca de testes." -#: ../../library/doctest.rst:309 +#: ../../library/doctest.rst:339 msgid "" "Any classes found are recursively searched similarly, to test docstrings in " "their contained methods and nested classes." @@ -382,11 +677,11 @@ msgstr "" "semelhante, para testar docstrings em seus métodos contidos e classes " "aninhadas." -#: ../../library/doctest.rst:316 +#: ../../library/doctest.rst:346 msgid "How are Docstring Examples Recognized?" msgstr "Como os exemplos de docstrings são reconhecidos?" -#: ../../library/doctest.rst:318 +#: ../../library/doctest.rst:348 msgid "" "In most cases a copy-and-paste of an interactive console session works fine, " "but doctest isn't trying to do an exact emulation of any specific Python " @@ -396,7 +691,41 @@ msgstr "" "funciona bem, mas o doctest não está tentando fazer uma emulação exata de " "qualquer shell Python específico." -#: ../../library/doctest.rst:343 +#: ../../library/doctest.rst:353 +msgid "" +">>> # comments are ignored\n" +">>> x = 12\n" +">>> x\n" +"12\n" +">>> if x == 13:\n" +"... print(\"yes\")\n" +"... else:\n" +"... print(\"no\")\n" +"... print(\"NO\")\n" +"... print(\"NO!!!\")\n" +"...\n" +"no\n" +"NO\n" +"NO!!!\n" +">>>" +msgstr "" +">>> # comentários são ignorados\n" +">>> x = 12\n" +">>> x\n" +"12\n" +">>> if x == 13:\n" +"... print(\"yes\")\n" +"... else:\n" +"... print(\"no\")\n" +"... print(\"NO\")\n" +"... print(\"NO!!!\")\n" +"...\n" +"no\n" +"NO\n" +"NO!!!\n" +">>>" + +#: ../../library/doctest.rst:373 msgid "" "Any expected output must immediately follow the final ``'>>> '`` or ``'... " "'`` line containing the code, and the expected output (if any) extends to " @@ -406,11 +735,11 @@ msgstr "" "ou ``'... '`` contendo o código, e a saída esperada (se houver) se estende " "até a próxima ``'>>> '`` ou linha com apenas espaços em branco." -#: ../../library/doctest.rst:347 +#: ../../library/doctest.rst:377 msgid "The fine print:" msgstr "A saída formatada:" -#: ../../library/doctest.rst:349 +#: ../../library/doctest.rst:379 msgid "" "Expected output cannot contain an all-whitespace line, since such a line is " "taken to signal the end of expected output. If expected output does contain " @@ -422,7 +751,7 @@ msgstr "" "esperada contiver uma linha vazia, coloque ```` em seu exemplo " "doctest em cada local onde uma linha em branco é esperada." -#: ../../library/doctest.rst:354 +#: ../../library/doctest.rst:384 msgid "" "All hard tab characters are expanded to spaces, using 8-column tab stops. " "Tabs in output generated by the tested code are not modified. Because any " @@ -449,7 +778,7 @@ msgstr "" "para lidar com guias escrevendo uma classe :class:`DocTestParser` " "personalizada." -#: ../../library/doctest.rst:366 +#: ../../library/doctest.rst:396 msgid "" "Output to stdout is captured, but not output to stderr (exception tracebacks " "are captured via a different means)." @@ -457,7 +786,7 @@ msgstr "" "A saída para stdout é capturada, mas não para stderr (os tracebacks de " "exceção são capturados por um meio diferente)." -#: ../../library/doctest.rst:369 +#: ../../library/doctest.rst:399 msgid "" "If you continue a line via backslashing in an interactive session, or for " "any other reason use a backslash, you should use a raw docstring, which will " @@ -468,7 +797,21 @@ msgstr "" "deverá usar uma docstring bruta, que preservará suas barras invertidas " "exatamente como você as digita::" -#: ../../library/doctest.rst:379 +#: ../../library/doctest.rst:403 +msgid "" +">>> def f(x):\n" +"... r'''Backslashes in a raw docstring: m\\n'''\n" +"...\n" +">>> print(f.__doc__)\n" +"Backslashes in a raw docstring: m\\n" +msgstr "" +">>> def f(x):\n" +"... r'''Backslashes in a raw docstring: m\\n'''\n" +"...\n" +">>> print(f.__doc__)\n" +"Backslashes in a raw docstring: m\\n" + +#: ../../library/doctest.rst:409 msgid "" "Otherwise, the backslash will be interpreted as part of the string. For " "example, the ``\\n`` above would be interpreted as a newline character. " @@ -480,11 +823,37 @@ msgstr "" "linha. Alternativamente, você pode duplicar cada barra invertida na versão " "doctest (e não usar uma string bruta)::" -#: ../../library/doctest.rst:389 +#: ../../library/doctest.rst:413 +msgid "" +">>> def f(x):\n" +"... '''Backslashes in a raw docstring: m\\\\n'''\n" +"...\n" +">>> print(f.__doc__)\n" +"Backslashes in a raw docstring: m\\n" +msgstr "" +">>> def f(x):\n" +"... '''Backslashes in a raw docstring: m\\\\n'''\n" +"...\n" +">>> print(f.__doc__)\n" +"Backslashes in a raw docstring: m\\n" + +#: ../../library/doctest.rst:419 msgid "The starting column doesn't matter::" msgstr "A coluna inicial não importa::" -#: ../../library/doctest.rst:396 +#: ../../library/doctest.rst:421 +msgid "" +">>> assert \"Easy!\"\n" +" >>> import math\n" +" >>> math.floor(1.9)\n" +" 1" +msgstr "" +">>> assert \"Easy!\"\n" +" >>> import math\n" +" >>> math.floor(1.9)\n" +" 1" + +#: ../../library/doctest.rst:426 msgid "" "and as many leading whitespace characters are stripped from the expected " "output as appeared in the initial ``'>>> '`` line that started the example." @@ -493,11 +862,11 @@ msgstr "" "esperada quantos apareceram na linha inicial ``'>>> '`` que iniciou o " "exemplo." -#: ../../library/doctest.rst:403 +#: ../../library/doctest.rst:433 msgid "What's the Execution Context?" msgstr "Qual é o contexto de execução?" -#: ../../library/doctest.rst:405 +#: ../../library/doctest.rst:435 msgid "" "By default, each time :mod:`doctest` finds a docstring to test, it uses a " "*shallow copy* of :mod:`!M`'s globals, so that running tests doesn't change " @@ -516,7 +885,7 @@ msgstr "" "anteriormente na docstring que está sendo executada. Os exemplos não podem " "ver nomes definidos em outras docstrings." -#: ../../library/doctest.rst:413 +#: ../../library/doctest.rst:443 msgid "" "You can force use of your own dict as the execution context by passing " "``globs=your_dict`` to :func:`testmod` or :func:`testfile` instead." @@ -524,11 +893,11 @@ msgstr "" "Você pode forçar o uso de seu próprio dicionário como contexto de execução " "passando ``globs=seu_dicionario`` para :func:`testmod` ou :func:`testfile`." -#: ../../library/doctest.rst:420 +#: ../../library/doctest.rst:450 msgid "What About Exceptions?" msgstr "E quanto às exceções?" -#: ../../library/doctest.rst:422 +#: ../../library/doctest.rst:452 msgid "" "No problem, provided that the traceback is the only output produced by the " "example: just paste in the traceback. [#]_ Since tracebacks contain details " @@ -542,31 +911,51 @@ msgstr "" "arquivos e números de linha), este é um caso em que o doctest trabalha duro " "para ser flexível no que aceita." -#: ../../library/doctest.rst:428 +#: ../../library/doctest.rst:458 msgid "Simple example::" msgstr "Exemplo simples::" -#: ../../library/doctest.rst:435 +#: ../../library/doctest.rst:460 +msgid "" +">>> [1, 2, 3].remove(42)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: list.remove(x): x not in list" +msgstr "" +">>> [1, 2, 3].remove(42)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: list.remove(x): x not in list" + +#: ../../library/doctest.rst:465 msgid "" "That doctest succeeds if :exc:`ValueError` is raised, with the ``list." "remove(x): x not in list`` detail as shown." msgstr "" +"Esse doctest será bem-sucedido se :exc:`ValueError` for levantada, com o " +"detalhe ``list.remove(x): x not in list``, conforme mostrado." -#: ../../library/doctest.rst:438 +#: ../../library/doctest.rst:468 msgid "" "The expected output for an exception must start with a traceback header, " "which may be either of the following two lines, indented the same as the " "first line of the example::" msgstr "" -#: ../../library/doctest.rst:445 +#: ../../library/doctest.rst:472 +msgid "" +"Traceback (most recent call last):\n" +"Traceback (innermost last):" +msgstr "" + +#: ../../library/doctest.rst:475 msgid "" "The traceback header is followed by an optional traceback stack, whose " "contents are ignored by doctest. The traceback stack is typically omitted, " "or copied verbatim from an interactive session." msgstr "" -#: ../../library/doctest.rst:449 +#: ../../library/doctest.rst:479 msgid "" "The traceback stack is followed by the most interesting part: the line(s) " "containing the exception type and detail. This is usually the last line of " @@ -574,20 +963,40 @@ msgid "" "multi-line detail::" msgstr "" -#: ../../library/doctest.rst:461 +#: ../../library/doctest.rst:484 +msgid "" +">>> raise ValueError('multi\\n line\\ndetail')\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: multi\n" +" line\n" +"detail" +msgstr "" + +#: ../../library/doctest.rst:491 msgid "" "The last three lines (starting with :exc:`ValueError`) are compared against " "the exception's type and detail, and the rest are ignored." msgstr "" -#: ../../library/doctest.rst:464 +#: ../../library/doctest.rst:494 msgid "" "Best practice is to omit the traceback stack, unless it adds significant " "documentation value to the example. So the last example is probably better " "as::" msgstr "" -#: ../../library/doctest.rst:474 +#: ../../library/doctest.rst:497 +msgid "" +">>> raise ValueError('multi\\n line\\ndetail')\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: multi\n" +" line\n" +"detail" +msgstr "" + +#: ../../library/doctest.rst:504 msgid "" "Note that tracebacks are treated very specially. In particular, in the " "rewritten example, the use of ``...`` is independent of doctest's :const:" @@ -596,11 +1005,11 @@ msgid "" "transcript of a Monty Python skit." msgstr "" -#: ../../library/doctest.rst:480 +#: ../../library/doctest.rst:510 msgid "Some details you should read once, but won't need to remember:" msgstr "" -#: ../../library/doctest.rst:482 +#: ../../library/doctest.rst:512 msgid "" "Doctest can't guess whether your expected output came from an exception " "traceback or from ordinary printing. So, e.g., an example that expects " @@ -610,7 +1019,7 @@ msgid "" "create real problems." msgstr "" -#: ../../library/doctest.rst:489 +#: ../../library/doctest.rst:519 msgid "" "Each line of the traceback stack (if present) must be indented further than " "the first line of the example, *or* start with a non-alphanumeric character. " @@ -619,14 +1028,14 @@ msgid "" "course this does the right thing for genuine tracebacks." msgstr "" -#: ../../library/doctest.rst:495 +#: ../../library/doctest.rst:525 msgid "" "When the :const:`IGNORE_EXCEPTION_DETAIL` doctest option is specified, " "everything following the leftmost colon and any module information in the " "exception name is ignored." msgstr "" -#: ../../library/doctest.rst:499 +#: ../../library/doctest.rst:529 msgid "" "The interactive shell omits the traceback header line for some :exc:" "`SyntaxError`\\ s. But doctest uses the traceback header line to " @@ -635,13 +1044,22 @@ msgid "" "need to manually add the traceback header line to your test example." msgstr "" -#: ../../library/doctest.rst:507 +#: ../../library/doctest.rst:537 msgid "" "For some exceptions, Python displays the position of the error using ``^`` " "markers and tildes::" msgstr "" -#: ../../library/doctest.rst:516 +#: ../../library/doctest.rst:540 +msgid "" +">>> 1 + None\n" +" File \"\", line 1\n" +" 1 + None\n" +" ~~^~~~~~\n" +"TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'" +msgstr "" + +#: ../../library/doctest.rst:546 msgid "" "Since the lines showing the position of the error come before the exception " "type and detail, they are not checked by doctest. For example, the " @@ -649,11 +1067,20 @@ msgid "" "location::" msgstr "" -#: ../../library/doctest.rst:531 +#: ../../library/doctest.rst:550 +msgid "" +">>> 1 + None\n" +" File \"\", line 1\n" +" 1 + None\n" +" ^~~~~~~~\n" +"TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'" +msgstr "" + +#: ../../library/doctest.rst:561 msgid "Option Flags" msgstr "Flags opcionais" -#: ../../library/doctest.rst:533 +#: ../../library/doctest.rst:563 msgid "" "A number of option flags control various aspects of doctest's behavior. " "Symbolic names for the flags are supplied as module constants, which can be :" @@ -663,17 +1090,13 @@ msgid "" "option." msgstr "" -#: ../../library/doctest.rst:539 -msgid "The ``-o`` command line option." -msgstr "" - -#: ../../library/doctest.rst:542 +#: ../../library/doctest.rst:569 msgid "" "The first group of options define test semantics, controlling aspects of how " "doctest decides whether actual output matches an example's expected output:" msgstr "" -#: ../../library/doctest.rst:548 +#: ../../library/doctest.rst:575 msgid "" "By default, if an expected output block contains just ``1``, an actual " "output block containing just ``1`` or just ``True`` is considered to be a " @@ -685,7 +1108,7 @@ msgid "" "not for several years." msgstr "" -#: ../../library/doctest.rst:560 +#: ../../library/doctest.rst:587 msgid "" "By default, if an expected output block contains a line containing only the " "string ````, then that line will match a blank line in the actual " @@ -694,7 +1117,7 @@ msgid "" "`DONT_ACCEPT_BLANKLINE` is specified, this substitution is not allowed." msgstr "" -#: ../../library/doctest.rst:569 +#: ../../library/doctest.rst:596 msgid "" "When specified, all sequences of whitespace (blanks and newlines) are " "treated as equal. Any sequence of whitespace within the expected output " @@ -704,7 +1127,7 @@ msgid "" "across multiple lines in your source." msgstr "" -#: ../../library/doctest.rst:580 +#: ../../library/doctest.rst:607 msgid "" "When specified, an ellipsis marker (``...``) in the expected output can " "match any substring in the actual output. This includes substrings that " @@ -713,14 +1136,14 @@ msgid "" "matched too much!\" surprises that ``.*`` is prone to in regular expressions." msgstr "" -#: ../../library/doctest.rst:589 +#: ../../library/doctest.rst:616 msgid "" "When specified, doctests expecting exceptions pass so long as an exception " "of the expected type is raised, even if the details (message and fully " "qualified exception name) don't match." msgstr "" -#: ../../library/doctest.rst:593 +#: ../../library/doctest.rst:620 msgid "" "For example, an example expecting ``ValueError: 42`` will pass if the actual " "exception raised is ``ValueError: 3*14``, but will fail if, say, a :exc:" @@ -730,20 +1153,35 @@ msgid "" "these variations will work with the flag specified:" msgstr "" -#: ../../library/doctest.rst:615 +#: ../../library/doctest.rst:628 +msgid "" +">>> raise Exception('message')\n" +"Traceback (most recent call last):\n" +"Exception: message\n" +"\n" +">>> raise Exception('message')\n" +"Traceback (most recent call last):\n" +"builtins.Exception: message\n" +"\n" +">>> raise Exception('message')\n" +"Traceback (most recent call last):\n" +"__main__.Exception: message" +msgstr "" + +#: ../../library/doctest.rst:642 msgid "" "Note that :const:`ELLIPSIS` can also be used to ignore the details of the " "exception message, but such a test may still fail based on whether the " "module name is present or matches exactly." msgstr "" -#: ../../library/doctest.rst:619 +#: ../../library/doctest.rst:646 msgid "" ":const:`IGNORE_EXCEPTION_DETAIL` now also ignores any information relating " "to the module containing the exception under test." msgstr "" -#: ../../library/doctest.rst:626 +#: ../../library/doctest.rst:653 msgid "" "When specified, do not run the example at all. This can be useful in " "contexts where doctest examples serve as both documentation and test cases, " @@ -752,32 +1190,32 @@ msgid "" "might depend on resources which would be unavailable to the test driver." msgstr "" -#: ../../library/doctest.rst:632 +#: ../../library/doctest.rst:659 msgid "" "The SKIP flag can also be used for temporarily \"commenting out\" examples." msgstr "" -#: ../../library/doctest.rst:637 +#: ../../library/doctest.rst:664 msgid "A bitmask or'ing together all the comparison flags above." msgstr "" -#: ../../library/doctest.rst:639 +#: ../../library/doctest.rst:666 msgid "The second group of options controls how test failures are reported:" msgstr "" -#: ../../library/doctest.rst:644 +#: ../../library/doctest.rst:671 msgid "" "When specified, failures that involve multi-line expected and actual outputs " "are displayed using a unified diff." msgstr "" -#: ../../library/doctest.rst:650 +#: ../../library/doctest.rst:677 msgid "" "When specified, failures that involve multi-line expected and actual outputs " "will be displayed using a context diff." msgstr "" -#: ../../library/doctest.rst:656 +#: ../../library/doctest.rst:683 msgid "" "When specified, differences are computed by ``difflib.Differ``, using the " "same algorithm as the popular :file:`ndiff.py` utility. This is the only " @@ -787,7 +1225,7 @@ msgid "" "mismatching column positions." msgstr "" -#: ../../library/doctest.rst:665 +#: ../../library/doctest.rst:692 msgid "" "When specified, display the first failing example in each doctest, but " "suppress output for all remaining examples. This will prevent doctest from " @@ -798,7 +1236,7 @@ msgid "" "of failures reported; only the output is suppressed." msgstr "" -#: ../../library/doctest.rst:676 +#: ../../library/doctest.rst:703 msgid "" "When specified, exit after the first failing example and don't attempt to " "run the remaining examples. Thus, the number of failures reported will be at " @@ -806,23 +1244,17 @@ msgid "" "first failure won't even produce debugging output." msgstr "" -#: ../../library/doctest.rst:681 -msgid "" -"The doctest command line accepts the option ``-f`` as a shorthand for ``-o " -"FAIL_FAST``." -msgstr "" - -#: ../../library/doctest.rst:689 +#: ../../library/doctest.rst:711 msgid "A bitmask or'ing together all the reporting flags above." msgstr "" -#: ../../library/doctest.rst:692 +#: ../../library/doctest.rst:714 msgid "" "There is also a way to register new option flag names, though this isn't " "useful unless you intend to extend :mod:`doctest` internals via subclassing:" msgstr "" -#: ../../library/doctest.rst:698 +#: ../../library/doctest.rst:720 msgid "" "Create a new option flag with a given name, and return the new flag's " "integer value. :func:`register_optionflag` can be used when subclassing :" @@ -831,35 +1263,46 @@ msgid "" "be called using the following idiom::" msgstr "" -#: ../../library/doctest.rst:714 +#: ../../library/doctest.rst:726 +msgid "MY_FLAG = register_optionflag('MY_FLAG')" +msgstr "" + +#: ../../library/doctest.rst:736 msgid "Directives" msgstr "" -#: ../../library/doctest.rst:716 +#: ../../library/doctest.rst:738 msgid "" "Doctest directives may be used to modify the :ref:`option flags ` for an individual example. Doctest directives are special Python " "comments following an example's source code:" msgstr "" -#: ../../library/doctest.rst:727 +#: ../../library/doctest.rst:749 msgid "" "Whitespace is not allowed between the ``+`` or ``-`` and the directive " "option name. The directive option name can be any of the option flag names " "explained above." msgstr "" -#: ../../library/doctest.rst:731 +#: ../../library/doctest.rst:753 msgid "" "An example's doctest directives modify doctest's behavior for that single " "example. Use ``+`` to enable the named behavior, or ``-`` to disable it." msgstr "" -#: ../../library/doctest.rst:734 +#: ../../library/doctest.rst:756 msgid "For example, this test passes:" msgstr "Por exemplo, este teste é aprovado:" -#: ../../library/doctest.rst:743 +#: ../../library/doctest.rst:758 +msgid "" +">>> print(list(range(20))) # doctest: +NORMALIZE_WHITESPACE\n" +"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n" +"10, 11, 12, 13, 14, 15, 16, 17, 18, 19]" +msgstr "" + +#: ../../library/doctest.rst:765 msgid "" "Without the directive it would fail, both because the actual output doesn't " "have two blanks before the single-digit list elements, and because the " @@ -867,26 +1310,52 @@ msgid "" "a directive to do so:" msgstr "" -#: ../../library/doctest.rst:754 +#: ../../library/doctest.rst:770 +msgid "" +">>> print(list(range(20))) # doctest: +ELLIPSIS\n" +"[0, 1, ..., 18, 19]" +msgstr "" + +#: ../../library/doctest.rst:776 msgid "" "Multiple directives can be used on a single physical line, separated by " "commas:" msgstr "" -#: ../../library/doctest.rst:763 +#: ../../library/doctest.rst:779 +msgid "" +">>> print(list(range(20))) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE\n" +"[0, 1, ..., 18, 19]" +msgstr "" + +#: ../../library/doctest.rst:785 msgid "" "If multiple directive comments are used for a single example, then they are " "combined:" msgstr "" -#: ../../library/doctest.rst:773 +#: ../../library/doctest.rst:788 +msgid "" +">>> print(list(range(20))) # doctest: +ELLIPSIS\n" +"... # doctest: +NORMALIZE_WHITESPACE\n" +"[0, 1, ..., 18, 19]" +msgstr "" + +#: ../../library/doctest.rst:795 msgid "" "As the previous example shows, you can add ``...`` lines to your example " "containing only directives. This can be useful when an example is too long " "for a directive to comfortably fit on the same line:" msgstr "" -#: ../../library/doctest.rst:784 +#: ../../library/doctest.rst:799 +msgid "" +">>> print(list(range(5)) + list(range(10, 20)) + list(range(30, 40)))\n" +"... # doctest: +ELLIPSIS\n" +"[0, ..., 4, 10, ..., 19, 30, ..., 39]" +msgstr "" + +#: ../../library/doctest.rst:806 msgid "" "Note that since all options are disabled by default, and directives apply " "only to the example they appear in, enabling options (via ``+`` in a " @@ -896,11 +1365,11 @@ msgid "" "be useful." msgstr "" -#: ../../library/doctest.rst:794 +#: ../../library/doctest.rst:816 msgid "Warnings" msgstr "Avisos" -#: ../../library/doctest.rst:796 +#: ../../library/doctest.rst:818 msgid "" ":mod:`doctest` is serious about requiring exact matches in expected output. " "If even a single character doesn't match, the test fails. This will " @@ -910,51 +1379,101 @@ msgid "" "test like ::" msgstr "" -#: ../../library/doctest.rst:805 +#: ../../library/doctest.rst:824 +msgid "" +">>> foo()\n" +"{\"spam\", \"eggs\"}" +msgstr "" + +#: ../../library/doctest.rst:827 msgid "is vulnerable! One workaround is to do ::" msgstr "" -#: ../../library/doctest.rst:810 +#: ../../library/doctest.rst:829 +msgid "" +">>> foo() == {\"spam\", \"eggs\"}\n" +"True" +msgstr "" + +#: ../../library/doctest.rst:832 msgid "instead. Another is to do ::" msgstr "" -#: ../../library/doctest.rst:816 +#: ../../library/doctest.rst:834 +msgid "" +">>> d = sorted(foo())\n" +">>> d\n" +"['eggs', 'spam']" +msgstr "" + +#: ../../library/doctest.rst:838 msgid "There are others, but you get the idea." msgstr "" -#: ../../library/doctest.rst:818 +#: ../../library/doctest.rst:840 msgid "Another bad idea is to print things that embed an object address, like" msgstr "" -#: ../../library/doctest.rst:828 +#: ../../library/doctest.rst:842 +msgid "" +">>> id(1.0) # certain to fail some of the time\n" +"7948648\n" +">>> class C: pass\n" +">>> C() # the default repr() for instances embeds an address\n" +"" +msgstr "" + +#: ../../library/doctest.rst:850 msgid "" "The :const:`ELLIPSIS` directive gives a nice approach for the last example:" msgstr "" -#: ../../library/doctest.rst:836 +#: ../../library/doctest.rst:852 +msgid "" +">>> C() # doctest: +ELLIPSIS\n" +"" +msgstr "" + +#: ../../library/doctest.rst:858 msgid "" "Floating-point numbers are also subject to small output variations across " "platforms, because Python defers to the platform C library for float " "formatting, and C libraries vary widely in quality here. ::" msgstr "" -#: ../../library/doctest.rst:847 +#: ../../library/doctest.rst:862 +msgid "" +">>> 1./7 # risky\n" +"0.14285714285714285\n" +">>> print(1./7) # safer\n" +"0.142857142857\n" +">>> print(round(1./7, 6)) # much safer\n" +"0.142857" +msgstr "" + +#: ../../library/doctest.rst:869 msgid "" "Numbers of the form ``I/2.**J`` are safe across all platforms, and I often " "contrive doctest examples to produce numbers of that form::" msgstr "" -#: ../../library/doctest.rst:853 +#: ../../library/doctest.rst:872 +msgid "" +">>> 3./4 # utterly safe\n" +"0.75" +msgstr "" + +#: ../../library/doctest.rst:875 msgid "" "Simple fractions are also easier for people to understand, and that makes " "for better documentation." msgstr "" -#: ../../library/doctest.rst:860 +#: ../../library/doctest.rst:882 msgid "Basic API" msgstr "" -#: ../../library/doctest.rst:862 +#: ../../library/doctest.rst:884 msgid "" "The functions :func:`testmod` and :func:`testfile` provide a simple " "interface to doctest that should be sufficient for most basic uses. For a " @@ -962,25 +1481,25 @@ msgid "" "simple-testmod` and :ref:`doctest-simple-testfile`." msgstr "" -#: ../../library/doctest.rst:870 +#: ../../library/doctest.rst:892 msgid "" "All arguments except *filename* are optional, and should be specified in " "keyword form." msgstr "" -#: ../../library/doctest.rst:873 +#: ../../library/doctest.rst:895 msgid "" "Test examples in the file named *filename*. Return ``(failure_count, " "test_count)``." msgstr "" -#: ../../library/doctest.rst:876 +#: ../../library/doctest.rst:898 msgid "" "Optional argument *module_relative* specifies how the filename should be " "interpreted:" msgstr "" -#: ../../library/doctest.rst:879 +#: ../../library/doctest.rst:901 msgid "" "If *module_relative* is ``True`` (the default), then *filename* specifies an " "OS-independent module-relative path. By default, this path is relative to " @@ -990,20 +1509,20 @@ msgid "" "absolute path (i.e., it may not begin with ``/``)." msgstr "" -#: ../../library/doctest.rst:886 +#: ../../library/doctest.rst:908 msgid "" "If *module_relative* is ``False``, then *filename* specifies an OS-specific " "path. The path may be absolute or relative; relative paths are resolved " "with respect to the current working directory." msgstr "" -#: ../../library/doctest.rst:890 +#: ../../library/doctest.rst:912 msgid "" "Optional argument *name* gives the name of the test; by default, or if " "``None``, ``os.path.basename(filename)`` is used." msgstr "" -#: ../../library/doctest.rst:893 +#: ../../library/doctest.rst:915 msgid "" "Optional argument *package* is a Python package or the name of a Python " "package whose directory should be used as the base directory for a module-" @@ -1012,7 +1531,7 @@ msgid "" "is an error to specify *package* if *module_relative* is ``False``." msgstr "" -#: ../../library/doctest.rst:899 +#: ../../library/doctest.rst:921 msgid "" "Optional argument *globs* gives a dict to be used as the globals when " "executing examples. A new shallow copy of this dict is created for the " @@ -1020,7 +1539,7 @@ msgid "" "``None``, a new empty dict is used." msgstr "" -#: ../../library/doctest.rst:904 +#: ../../library/doctest.rst:926 msgid "" "Optional argument *extraglobs* gives a dict merged into the globals used to " "execute examples. This works like :meth:`dict.update`: if *globs* and " @@ -1033,27 +1552,27 @@ msgid "" "tested." msgstr "" -#: ../../library/doctest.rst:913 +#: ../../library/doctest.rst:935 msgid "" "Optional argument *verbose* prints lots of stuff if true, and prints only " "failures if false; by default, or if ``None``, it's true if and only if ``'-" "v'`` is in ``sys.argv``." msgstr "" -#: ../../library/doctest.rst:917 +#: ../../library/doctest.rst:939 msgid "" "Optional argument *report* prints a summary at the end when true, else " "prints nothing at the end. In verbose mode, the summary is detailed, else " "the summary is very brief (in fact, empty if all tests passed)." msgstr "" -#: ../../library/doctest.rst:921 +#: ../../library/doctest.rst:943 msgid "" "Optional argument *optionflags* (default value 0) takes the :ref:`bitwise OR " "` of option flags. See section :ref:`doctest-options`." msgstr "" -#: ../../library/doctest.rst:925 +#: ../../library/doctest.rst:947 msgid "" "Optional argument *raise_on_error* defaults to false. If true, an exception " "is raised upon the first failure or unexpected exception in an example. " @@ -1061,33 +1580,33 @@ msgid "" "continue running examples." msgstr "" -#: ../../library/doctest.rst:930 ../../library/doctest.rst:1072 +#: ../../library/doctest.rst:952 ../../library/doctest.rst:1094 msgid "" "Optional argument *parser* specifies a :class:`DocTestParser` (or subclass) " "that should be used to extract tests from the files. It defaults to a " "normal parser (i.e., ``DocTestParser()``)." msgstr "" -#: ../../library/doctest.rst:934 ../../library/doctest.rst:1076 +#: ../../library/doctest.rst:956 ../../library/doctest.rst:1098 msgid "" "Optional argument *encoding* specifies an encoding that should be used to " "convert the file to unicode." msgstr "" -#: ../../library/doctest.rst:940 +#: ../../library/doctest.rst:962 msgid "" "All arguments are optional, and all except for *m* should be specified in " "keyword form." msgstr "" -#: ../../library/doctest.rst:943 +#: ../../library/doctest.rst:965 msgid "" "Test examples in docstrings in functions and classes reachable from module " "*m* (or module :mod:`__main__` if *m* is not supplied or is ``None``), " "starting with ``m.__doc__``." msgstr "" -#: ../../library/doctest.rst:947 +#: ../../library/doctest.rst:969 msgid "" "Also test examples reachable from dict ``m.__test__``, if it exists. ``m." "__test__`` maps names (strings) to functions, classes and strings; function " @@ -1095,22 +1614,22 @@ msgid "" "directly, as if they were docstrings." msgstr "" -#: ../../library/doctest.rst:952 +#: ../../library/doctest.rst:974 msgid "" "Only docstrings attached to objects belonging to module *m* are searched." msgstr "" -#: ../../library/doctest.rst:954 +#: ../../library/doctest.rst:976 msgid "Return ``(failure_count, test_count)``." msgstr "" -#: ../../library/doctest.rst:956 +#: ../../library/doctest.rst:978 msgid "" "Optional argument *name* gives the name of the module; by default, or if " "``None``, ``m.__name__`` is used." msgstr "" -#: ../../library/doctest.rst:959 +#: ../../library/doctest.rst:981 msgid "" "Optional argument *exclude_empty* defaults to false. If true, objects for " "which no doctests are found are excluded from consideration. The default is " @@ -1121,39 +1640,39 @@ msgid "" "defaults to true." msgstr "" -#: ../../library/doctest.rst:967 +#: ../../library/doctest.rst:989 msgid "" "Optional arguments *extraglobs*, *verbose*, *report*, *optionflags*, " "*raise_on_error*, and *globs* are the same as for function :func:`testfile` " "above, except that *globs* defaults to ``m.__dict__``." msgstr "" -#: ../../library/doctest.rst:974 +#: ../../library/doctest.rst:996 msgid "" "Test examples associated with object *f*; for example, *f* may be a string, " "a module, a function, or a class object." msgstr "" -#: ../../library/doctest.rst:977 +#: ../../library/doctest.rst:999 msgid "" "A shallow copy of dictionary argument *globs* is used for the execution " "context." msgstr "" -#: ../../library/doctest.rst:979 +#: ../../library/doctest.rst:1001 msgid "" "Optional argument *name* is used in failure messages, and defaults to " "``\"NoName\"``." msgstr "" -#: ../../library/doctest.rst:982 +#: ../../library/doctest.rst:1004 msgid "" "If optional argument *verbose* is true, output is generated even if there " "are no failures. By default, output is generated only in case of an example " "failure." msgstr "" -#: ../../library/doctest.rst:985 +#: ../../library/doctest.rst:1007 msgid "" "Optional argument *compileflags* gives the set of flags that should be used " "by the Python compiler when running the examples. By default, or if " @@ -1161,16 +1680,16 @@ msgid "" "found in *globs*." msgstr "" -#: ../../library/doctest.rst:989 +#: ../../library/doctest.rst:1011 msgid "" "Optional argument *optionflags* works as for function :func:`testfile` above." msgstr "" -#: ../../library/doctest.rst:995 +#: ../../library/doctest.rst:1017 msgid "Unittest API" msgstr "API do Unittest" -#: ../../library/doctest.rst:997 +#: ../../library/doctest.rst:1019 msgid "" "As your collection of doctest'ed modules grows, you'll want a way to run all " "their doctests systematically. :mod:`doctest` provides two functions that " @@ -1180,19 +1699,30 @@ msgid "" "your test module::" msgstr "" -#: ../../library/doctest.rst:1011 +#: ../../library/doctest.rst:1025 +msgid "" +"import unittest\n" +"import doctest\n" +"import my_module_with_doctests\n" +"\n" +"def load_tests(loader, tests, ignore):\n" +" tests.addTests(doctest.DocTestSuite(my_module_with_doctests))\n" +" return tests" +msgstr "" + +#: ../../library/doctest.rst:1033 msgid "" "There are two main functions for creating :class:`unittest.TestSuite` " "instances from text files and modules with doctests:" msgstr "" -#: ../../library/doctest.rst:1017 +#: ../../library/doctest.rst:1039 msgid "" "Convert doctest tests from one or more text files to a :class:`unittest." "TestSuite`." msgstr "" -#: ../../library/doctest.rst:1020 +#: ../../library/doctest.rst:1042 msgid "" "The returned :class:`unittest.TestSuite` is to be run by the unittest " "framework and runs the interactive examples in each file. If an example in " @@ -1203,21 +1733,21 @@ msgid "" "marked as skipped." msgstr "" -#: ../../library/doctest.rst:1027 +#: ../../library/doctest.rst:1049 msgid "Pass one or more paths (as strings) to text files to be examined." msgstr "" -#: ../../library/doctest.rst:1029 +#: ../../library/doctest.rst:1051 msgid "Options may be provided as keyword arguments:" msgstr "" -#: ../../library/doctest.rst:1031 +#: ../../library/doctest.rst:1053 msgid "" "Optional argument *module_relative* specifies how the filenames in *paths* " "should be interpreted:" msgstr "" -#: ../../library/doctest.rst:1034 +#: ../../library/doctest.rst:1056 msgid "" "If *module_relative* is ``True`` (the default), then each filename in " "*paths* specifies an OS-independent module-relative path. By default, this " @@ -1228,14 +1758,14 @@ msgid "" "``)." msgstr "" -#: ../../library/doctest.rst:1042 +#: ../../library/doctest.rst:1064 msgid "" "If *module_relative* is ``False``, then each filename in *paths* specifies " "an OS-specific path. The path may be absolute or relative; relative paths " "are resolved with respect to the current working directory." msgstr "" -#: ../../library/doctest.rst:1046 +#: ../../library/doctest.rst:1068 msgid "" "Optional argument *package* is a Python package or the name of a Python " "package whose directory should be used as the base directory for module-" @@ -1245,7 +1775,7 @@ msgid "" "``False``." msgstr "" -#: ../../library/doctest.rst:1053 +#: ../../library/doctest.rst:1075 msgid "" "Optional argument *setUp* specifies a set-up function for the test suite. " "This is called before running the tests in each file. The *setUp* function " @@ -1253,7 +1783,7 @@ msgid "" "test globals as the *globs* attribute of the test passed." msgstr "" -#: ../../library/doctest.rst:1058 +#: ../../library/doctest.rst:1080 msgid "" "Optional argument *tearDown* specifies a tear-down function for the test " "suite. This is called after running the tests in each file. The *tearDown* " @@ -1261,14 +1791,14 @@ msgid "" "access the test globals as the *globs* attribute of the test passed." msgstr "" -#: ../../library/doctest.rst:1063 ../../library/doctest.rst:1098 +#: ../../library/doctest.rst:1085 ../../library/doctest.rst:1120 msgid "" "Optional argument *globs* is a dictionary containing the initial global " "variables for the tests. A new copy of this dictionary is created for each " "test. By default, *globs* is a new empty dictionary." msgstr "" -#: ../../library/doctest.rst:1067 +#: ../../library/doctest.rst:1089 msgid "" "Optional argument *optionflags* specifies the default doctest options for " "the tests, created by or-ing together individual option flags. See section :" @@ -1276,17 +1806,17 @@ msgid "" "for a better way to set reporting options." msgstr "" -#: ../../library/doctest.rst:1079 +#: ../../library/doctest.rst:1101 msgid "" "The global ``__file__`` is added to the globals provided to doctests loaded " "from a text file using :func:`DocFileSuite`." msgstr "" -#: ../../library/doctest.rst:1085 +#: ../../library/doctest.rst:1107 msgid "Convert doctest tests for a module to a :class:`unittest.TestSuite`." msgstr "" -#: ../../library/doctest.rst:1087 +#: ../../library/doctest.rst:1109 msgid "" "The returned :class:`unittest.TestSuite` is to be run by the unittest " "framework and runs each doctest in the module. If any of the doctests fail, " @@ -1296,42 +1826,42 @@ msgid "" "skipped, then the synthesized unit test is also marked as skipped." msgstr "" -#: ../../library/doctest.rst:1094 +#: ../../library/doctest.rst:1116 msgid "" "Optional argument *module* provides the module to be tested. It can be a " "module object or a (possibly dotted) module name. If not specified, the " "module calling this function is used." msgstr "" -#: ../../library/doctest.rst:1102 +#: ../../library/doctest.rst:1124 msgid "" "Optional argument *extraglobs* specifies an extra set of global variables, " "which is merged into *globs*. By default, no extra globals are used." msgstr "" -#: ../../library/doctest.rst:1105 +#: ../../library/doctest.rst:1127 msgid "" "Optional argument *test_finder* is the :class:`DocTestFinder` object (or a " "drop-in replacement) that is used to extract doctests from the module." msgstr "" -#: ../../library/doctest.rst:1108 +#: ../../library/doctest.rst:1130 msgid "" "Optional arguments *setUp*, *tearDown*, and *optionflags* are the same as " "for function :func:`DocFileSuite` above." msgstr "" -#: ../../library/doctest.rst:1111 +#: ../../library/doctest.rst:1133 msgid "This function uses the same search technique as :func:`testmod`." msgstr "" -#: ../../library/doctest.rst:1113 +#: ../../library/doctest.rst:1135 msgid "" ":func:`DocTestSuite` returns an empty :class:`unittest.TestSuite` if " "*module* contains no docstrings instead of raising :exc:`ValueError`." msgstr "" -#: ../../library/doctest.rst:1119 +#: ../../library/doctest.rst:1141 msgid "" "When doctests which have been converted to unit tests by :func:" "`DocFileSuite` or :func:`DocTestSuite` fail, this exception is raised " @@ -1339,7 +1869,7 @@ msgid "" "approximate) line number." msgstr "" -#: ../../library/doctest.rst:1123 +#: ../../library/doctest.rst:1145 msgid "" "Under the covers, :func:`DocTestSuite` creates a :class:`unittest.TestSuite` " "out of :class:`!doctest.DocTestCase` instances, and :class:`!DocTestCase` is " @@ -1348,14 +1878,14 @@ msgid "" "questions about the exact details of :mod:`unittest` integration." msgstr "" -#: ../../library/doctest.rst:1129 +#: ../../library/doctest.rst:1151 msgid "" "Similarly, :func:`DocFileSuite` creates a :class:`unittest.TestSuite` out " "of :class:`!doctest.DocFileCase` instances, and :class:`!DocFileCase` is a " "subclass of :class:`!DocTestCase`." msgstr "" -#: ../../library/doctest.rst:1133 +#: ../../library/doctest.rst:1155 msgid "" "So both ways of creating a :class:`unittest.TestSuite` run instances of :" "class:`!DocTestCase`. This is important for a subtle reason: when you run :" @@ -1368,23 +1898,23 @@ msgid "" "through :mod:`unittest` to :mod:`doctest` test runners." msgstr "" -#: ../../library/doctest.rst:1143 +#: ../../library/doctest.rst:1165 msgid "" "For this reason, :mod:`doctest` also supports a notion of :mod:`doctest` " "reporting flags specific to :mod:`unittest` support, via this function:" msgstr "" -#: ../../library/doctest.rst:1149 +#: ../../library/doctest.rst:1171 msgid "Set the :mod:`doctest` reporting flags to use." msgstr "" -#: ../../library/doctest.rst:1151 +#: ../../library/doctest.rst:1173 msgid "" "Argument *flags* takes the :ref:`bitwise OR ` of option flags. See " "section :ref:`doctest-options`. Only \"reporting flags\" can be used." msgstr "" -#: ../../library/doctest.rst:1154 +#: ../../library/doctest.rst:1176 msgid "" "This is a module-global setting, and affects all future doctests run by " "module :mod:`unittest`: the :meth:`!runTest` method of :class:`!" @@ -1398,17 +1928,17 @@ msgid "" "`!doctest`'s :mod:`unittest` reporting flags are ignored." msgstr "" -#: ../../library/doctest.rst:1165 +#: ../../library/doctest.rst:1187 msgid "" "The value of the :mod:`unittest` reporting flags in effect before the " "function was called is returned by the function." msgstr "" -#: ../../library/doctest.rst:1172 +#: ../../library/doctest.rst:1194 msgid "Advanced API" msgstr "" -#: ../../library/doctest.rst:1174 +#: ../../library/doctest.rst:1196 msgid "" "The basic API is a simple wrapper that's intended to make doctest easy to " "use. It is fairly flexible, and should meet most users' needs; however, if " @@ -1416,85 +1946,97 @@ msgid "" "doctest's capabilities, then you should use the advanced API." msgstr "" -#: ../../library/doctest.rst:1179 +#: ../../library/doctest.rst:1201 msgid "" "The advanced API revolves around two container classes, which are used to " "store the interactive examples extracted from doctest cases:" msgstr "" -#: ../../library/doctest.rst:1182 +#: ../../library/doctest.rst:1204 msgid "" ":class:`Example`: A single Python :term:`statement`, paired with its " "expected output." msgstr "" -#: ../../library/doctest.rst:1185 +#: ../../library/doctest.rst:1207 msgid "" ":class:`DocTest`: A collection of :class:`Example`\\ s, typically extracted " "from a single docstring or text file." msgstr "" -#: ../../library/doctest.rst:1188 +#: ../../library/doctest.rst:1210 msgid "" "Additional processing classes are defined to find, parse, and run, and check " "doctest examples:" msgstr "" -#: ../../library/doctest.rst:1191 +#: ../../library/doctest.rst:1213 msgid "" ":class:`DocTestFinder`: Finds all docstrings in a given module, and uses a :" "class:`DocTestParser` to create a :class:`DocTest` from every docstring that " "contains interactive examples." msgstr "" -#: ../../library/doctest.rst:1195 +#: ../../library/doctest.rst:1217 msgid "" ":class:`DocTestParser`: Creates a :class:`DocTest` object from a string " "(such as an object's docstring)." msgstr "" -#: ../../library/doctest.rst:1198 +#: ../../library/doctest.rst:1220 msgid "" ":class:`DocTestRunner`: Executes the examples in a :class:`DocTest`, and " "uses an :class:`OutputChecker` to verify their output." msgstr "" -#: ../../library/doctest.rst:1201 +#: ../../library/doctest.rst:1223 msgid "" ":class:`OutputChecker`: Compares the actual output from a doctest example " "with the expected output, and decides whether they match." msgstr "" -#: ../../library/doctest.rst:1204 +#: ../../library/doctest.rst:1226 msgid "" "The relationships among these processing classes are summarized in the " "following diagram::" msgstr "" -#: ../../library/doctest.rst:1220 +#: ../../library/doctest.rst:1229 +msgid "" +" list of:\n" +"+------+ +---------+\n" +"|module| --DocTestFinder-> | DocTest | --DocTestRunner-> results\n" +"+------+ | ^ +---------+ | ^ (printed)\n" +" | | | Example | | |\n" +" v | | ... | v |\n" +" DocTestParser | Example | OutputChecker\n" +" +---------+" +msgstr "" + +#: ../../library/doctest.rst:1242 msgid "DocTest Objects" msgstr "" -#: ../../library/doctest.rst:1225 +#: ../../library/doctest.rst:1247 msgid "" "A collection of doctest examples that should be run in a single namespace. " "The constructor arguments are used to initialize the attributes of the same " "names." msgstr "" -#: ../../library/doctest.rst:1229 +#: ../../library/doctest.rst:1251 msgid "" ":class:`DocTest` defines the following attributes. They are initialized by " "the constructor, and should not be modified directly." msgstr "" -#: ../../library/doctest.rst:1235 +#: ../../library/doctest.rst:1257 msgid "" "A list of :class:`Example` objects encoding the individual interactive " "Python examples that should be run by this test." msgstr "" -#: ../../library/doctest.rst:1241 +#: ../../library/doctest.rst:1263 msgid "" "The namespace (aka globals) that the examples should be run in. This is a " "dictionary mapping names to values. Any changes to the namespace made by " @@ -1502,57 +2044,57 @@ msgid "" "`globs` after the test is run." msgstr "" -#: ../../library/doctest.rst:1249 +#: ../../library/doctest.rst:1271 msgid "" "A string name identifying the :class:`DocTest`. Typically, this is the name " "of the object or file that the test was extracted from." msgstr "" -#: ../../library/doctest.rst:1255 +#: ../../library/doctest.rst:1277 msgid "" "The name of the file that this :class:`DocTest` was extracted from; or " "``None`` if the filename is unknown, or if the :class:`DocTest` was not " "extracted from a file." msgstr "" -#: ../../library/doctest.rst:1262 +#: ../../library/doctest.rst:1284 msgid "" "The line number within :attr:`filename` where this :class:`DocTest` begins, " "or ``None`` if the line number is unavailable. This line number is zero-" "based with respect to the beginning of the file." msgstr "" -#: ../../library/doctest.rst:1269 +#: ../../library/doctest.rst:1291 msgid "" "The string that the test was extracted from, or ``None`` if the string is " "unavailable, or if the test was not extracted from a string." msgstr "" -#: ../../library/doctest.rst:1276 +#: ../../library/doctest.rst:1298 msgid "Example Objects" msgstr "" -#: ../../library/doctest.rst:1281 +#: ../../library/doctest.rst:1303 msgid "" "A single interactive example, consisting of a Python statement and its " "expected output. The constructor arguments are used to initialize the " "attributes of the same names." msgstr "" -#: ../../library/doctest.rst:1286 +#: ../../library/doctest.rst:1308 msgid "" ":class:`Example` defines the following attributes. They are initialized by " "the constructor, and should not be modified directly." msgstr "" -#: ../../library/doctest.rst:1292 +#: ../../library/doctest.rst:1314 msgid "" "A string containing the example's source code. This source code consists of " "a single Python statement, and always ends with a newline; the constructor " "adds a newline when necessary." msgstr "" -#: ../../library/doctest.rst:1299 +#: ../../library/doctest.rst:1321 msgid "" "The expected output from running the example's source code (either from " "stdout, or a traceback in case of exception). :attr:`want` ends with a " @@ -1560,7 +2102,7 @@ msgid "" "The constructor adds a newline when necessary." msgstr "" -#: ../../library/doctest.rst:1307 +#: ../../library/doctest.rst:1329 msgid "" "The exception message generated by the example, if the example is expected " "to generate an exception; or ``None`` if it is not expected to generate an " @@ -1569,20 +2111,20 @@ msgid "" "unless it's ``None``. The constructor adds a newline if needed." msgstr "" -#: ../../library/doctest.rst:1316 +#: ../../library/doctest.rst:1338 msgid "" "The line number within the string containing this example where the example " "begins. This line number is zero-based with respect to the beginning of the " "containing string." msgstr "" -#: ../../library/doctest.rst:1323 +#: ../../library/doctest.rst:1345 msgid "" "The example's indentation in the containing string, i.e., the number of " "space characters that precede the example's first prompt." msgstr "" -#: ../../library/doctest.rst:1329 +#: ../../library/doctest.rst:1351 msgid "" "A dictionary mapping from option flags to ``True`` or ``False``, which is " "used to override default options for this example. Any option flags not " @@ -1591,11 +2133,11 @@ msgid "" "default, no options are set." msgstr "" -#: ../../library/doctest.rst:1339 +#: ../../library/doctest.rst:1361 msgid "DocTestFinder objects" msgstr "" -#: ../../library/doctest.rst:1344 +#: ../../library/doctest.rst:1366 msgid "" "A processing class used to extract the :class:`DocTest`\\ s that are " "relevant to a given object, from its docstring and the docstrings of its " @@ -1603,48 +2145,48 @@ msgid "" "classes, functions, methods, staticmethods, classmethods, and properties." msgstr "" -#: ../../library/doctest.rst:1349 +#: ../../library/doctest.rst:1371 msgid "" "The optional argument *verbose* can be used to display the objects searched " "by the finder. It defaults to ``False`` (no output)." msgstr "" -#: ../../library/doctest.rst:1352 +#: ../../library/doctest.rst:1374 msgid "" "The optional argument *parser* specifies the :class:`DocTestParser` object " "(or a drop-in replacement) that is used to extract doctests from docstrings." msgstr "" -#: ../../library/doctest.rst:1355 +#: ../../library/doctest.rst:1377 msgid "" "If the optional argument *recurse* is false, then :meth:`DocTestFinder.find` " "will only examine the given object, and not any contained objects." msgstr "" -#: ../../library/doctest.rst:1358 +#: ../../library/doctest.rst:1380 msgid "" "If the optional argument *exclude_empty* is false, then :meth:`DocTestFinder." "find` will include tests for objects with empty docstrings." msgstr "" -#: ../../library/doctest.rst:1362 +#: ../../library/doctest.rst:1384 msgid ":class:`DocTestFinder` defines the following method:" msgstr "" -#: ../../library/doctest.rst:1367 +#: ../../library/doctest.rst:1389 msgid "" "Return a list of the :class:`DocTest`\\ s that are defined by *obj*'s " "docstring, or by any of its contained objects' docstrings." msgstr "" -#: ../../library/doctest.rst:1370 +#: ../../library/doctest.rst:1392 msgid "" "The optional argument *name* specifies the object's name; this name will be " "used to construct names for the returned :class:`DocTest`\\ s. If *name* is " "not specified, then ``obj.__name__`` is used." msgstr "" -#: ../../library/doctest.rst:1374 +#: ../../library/doctest.rst:1396 msgid "" "The optional parameter *module* is the module that contains the given " "object. If the module is not specified or is ``None``, then the test finder " @@ -1652,26 +2194,26 @@ msgid "" "module is used:" msgstr "" -#: ../../library/doctest.rst:1378 +#: ../../library/doctest.rst:1400 msgid "As a default namespace, if *globs* is not specified." msgstr "" -#: ../../library/doctest.rst:1380 +#: ../../library/doctest.rst:1402 msgid "" "To prevent the DocTestFinder from extracting DocTests from objects that are " "imported from other modules. (Contained objects with modules other than " "*module* are ignored.)" msgstr "" -#: ../../library/doctest.rst:1384 +#: ../../library/doctest.rst:1406 msgid "To find the name of the file containing the object." msgstr "" -#: ../../library/doctest.rst:1386 +#: ../../library/doctest.rst:1408 msgid "To help find the line number of the object within its file." msgstr "" -#: ../../library/doctest.rst:1388 +#: ../../library/doctest.rst:1410 msgid "" "If *module* is ``False``, no attempt to find the module will be made. This " "is obscure, of use mostly in testing doctest itself: if *module* is " @@ -1680,7 +2222,7 @@ msgid "" "contained objects will (recursively) be searched for doctests." msgstr "" -#: ../../library/doctest.rst:1394 +#: ../../library/doctest.rst:1416 msgid "" "The globals for each :class:`DocTest` is formed by combining *globs* and " "*extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new " @@ -1690,34 +2232,34 @@ msgid "" "defaults to ``{}``." msgstr "" -#: ../../library/doctest.rst:1405 +#: ../../library/doctest.rst:1427 msgid "DocTestParser objects" msgstr "" -#: ../../library/doctest.rst:1410 +#: ../../library/doctest.rst:1432 msgid "" "A processing class used to extract interactive examples from a string, and " "use them to create a :class:`DocTest` object." msgstr "" -#: ../../library/doctest.rst:1414 +#: ../../library/doctest.rst:1436 msgid ":class:`DocTestParser` defines the following methods:" msgstr "" -#: ../../library/doctest.rst:1419 +#: ../../library/doctest.rst:1441 msgid "" "Extract all doctest examples from the given string, and collect them into a :" "class:`DocTest` object." msgstr "" -#: ../../library/doctest.rst:1422 +#: ../../library/doctest.rst:1444 msgid "" "*globs*, *name*, *filename*, and *lineno* are attributes for the new :class:" "`DocTest` object. See the documentation for :class:`DocTest` for more " "information." msgstr "" -#: ../../library/doctest.rst:1429 +#: ../../library/doctest.rst:1451 msgid "" "Extract all doctest examples from the given string, and return them as a " "list of :class:`Example` objects. Line numbers are 0-based. The optional " @@ -1725,7 +2267,7 @@ msgid "" "error messages." msgstr "" -#: ../../library/doctest.rst:1436 +#: ../../library/doctest.rst:1458 msgid "" "Divide the given string into examples and intervening text, and return them " "as a list of alternating :class:`Example`\\ s and strings. Line numbers for " @@ -1733,33 +2275,33 @@ msgid "" "name identifying this string, and is only used for error messages." msgstr "" -#: ../../library/doctest.rst:1443 +#: ../../library/doctest.rst:1465 msgid "TestResults objects" msgstr "" -#: ../../library/doctest.rst:1450 +#: ../../library/doctest.rst:1472 msgid "Number of failed tests." msgstr "" -#: ../../library/doctest.rst:1454 +#: ../../library/doctest.rst:1476 msgid "Number of attempted tests." msgstr "" -#: ../../library/doctest.rst:1458 +#: ../../library/doctest.rst:1480 msgid "Number of skipped tests." msgstr "" -#: ../../library/doctest.rst:1466 +#: ../../library/doctest.rst:1488 msgid "DocTestRunner objects" msgstr "" -#: ../../library/doctest.rst:1471 +#: ../../library/doctest.rst:1493 msgid "" "A processing class used to execute and verify the interactive examples in a :" "class:`DocTest`." msgstr "" -#: ../../library/doctest.rst:1474 +#: ../../library/doctest.rst:1496 msgid "" "The comparison between expected outputs and actual outputs is done by an :" "class:`OutputChecker`. This comparison may be customized with a number of " @@ -1769,7 +2311,7 @@ msgid "" "constructor." msgstr "" -#: ../../library/doctest.rst:1480 +#: ../../library/doctest.rst:1502 msgid "" "The test runner's display output can be controlled in two ways. First, an " "output function can be passed to :meth:`run`; this function will be called " @@ -1780,14 +2322,14 @@ msgid "" "`report_unexpected_exception`, and :meth:`report_failure`." msgstr "" -#: ../../library/doctest.rst:1488 +#: ../../library/doctest.rst:1510 msgid "" "The optional keyword argument *checker* specifies the :class:`OutputChecker` " "object (or drop-in replacement) that should be used to compare the expected " "outputs to the actual outputs of doctest examples." msgstr "" -#: ../../library/doctest.rst:1492 +#: ../../library/doctest.rst:1514 msgid "" "The optional keyword argument *verbose* controls the :class:" "`DocTestRunner`'s verbosity. If *verbose* is ``True``, then information is " @@ -1796,14 +2338,14 @@ msgid "" "verbose output is used iff the command-line switch ``-v`` is used." msgstr "" -#: ../../library/doctest.rst:1498 +#: ../../library/doctest.rst:1520 msgid "" "The optional keyword argument *optionflags* can be used to control how the " "test runner compares expected output to actual output, and how it displays " "failures. For more information, see section :ref:`doctest-options`." msgstr "" -#: ../../library/doctest.rst:1502 +#: ../../library/doctest.rst:1524 msgid "" "The test runner accumulates statistics. The aggregated number of attempted, " "failed and skipped examples is also available via the :attr:`tries`, :attr:" @@ -1811,53 +2353,53 @@ msgid "" "`summarize` methods return a :class:`TestResults` instance." msgstr "" -#: ../../library/doctest.rst:1507 +#: ../../library/doctest.rst:1529 msgid ":class:`DocTestRunner` defines the following methods:" msgstr "" -#: ../../library/doctest.rst:1512 +#: ../../library/doctest.rst:1534 msgid "" "Report that the test runner is about to process the given example. This " "method is provided to allow subclasses of :class:`DocTestRunner` to " "customize their output; it should not be called directly." msgstr "" -#: ../../library/doctest.rst:1516 +#: ../../library/doctest.rst:1538 msgid "" "*example* is the example about to be processed. *test* is the test " "*containing example*. *out* is the output function that was passed to :meth:" "`DocTestRunner.run`." msgstr "" -#: ../../library/doctest.rst:1523 +#: ../../library/doctest.rst:1545 msgid "" "Report that the given example ran successfully. This method is provided to " "allow subclasses of :class:`DocTestRunner` to customize their output; it " "should not be called directly." msgstr "" -#: ../../library/doctest.rst:1527 ../../library/doctest.rst:1538 +#: ../../library/doctest.rst:1549 ../../library/doctest.rst:1560 msgid "" "*example* is the example about to be processed. *got* is the actual output " "from the example. *test* is the test containing *example*. *out* is the " "output function that was passed to :meth:`DocTestRunner.run`." msgstr "" -#: ../../library/doctest.rst:1534 +#: ../../library/doctest.rst:1556 msgid "" "Report that the given example failed. This method is provided to allow " "subclasses of :class:`DocTestRunner` to customize their output; it should " "not be called directly." msgstr "" -#: ../../library/doctest.rst:1545 +#: ../../library/doctest.rst:1567 msgid "" "Report that the given example raised an unexpected exception. This method is " "provided to allow subclasses of :class:`DocTestRunner` to customize their " "output; it should not be called directly." msgstr "" -#: ../../library/doctest.rst:1549 +#: ../../library/doctest.rst:1571 msgid "" "*example* is the example about to be processed. *exc_info* is a tuple " "containing information about the unexpected exception (as returned by :func:" @@ -1865,14 +2407,14 @@ msgid "" "output function that was passed to :meth:`DocTestRunner.run`." msgstr "" -#: ../../library/doctest.rst:1557 +#: ../../library/doctest.rst:1579 msgid "" "Run the examples in *test* (a :class:`DocTest` object), and display the " "results using the writer function *out*. Return a :class:`TestResults` " "instance." msgstr "" -#: ../../library/doctest.rst:1561 +#: ../../library/doctest.rst:1583 msgid "" "The examples are run in the namespace ``test.globs``. If *clear_globs* is " "true (the default), then this namespace will be cleared after the test runs, " @@ -1880,54 +2422,54 @@ msgid "" "after the test completes, then use *clear_globs=False*." msgstr "" -#: ../../library/doctest.rst:1566 +#: ../../library/doctest.rst:1588 msgid "" "*compileflags* gives the set of flags that should be used by the Python " "compiler when running the examples. If not specified, then it will default " "to the set of future-import flags that apply to *globs*." msgstr "" -#: ../../library/doctest.rst:1570 +#: ../../library/doctest.rst:1592 msgid "" "The output of each example is checked using the :class:`DocTestRunner`'s " "output checker, and the results are formatted by the :meth:`!DocTestRunner." "report_\\*` methods." msgstr "" -#: ../../library/doctest.rst:1577 +#: ../../library/doctest.rst:1599 msgid "" "Print a summary of all the test cases that have been run by this " "DocTestRunner, and return a :class:`TestResults` instance." msgstr "" -#: ../../library/doctest.rst:1580 +#: ../../library/doctest.rst:1602 msgid "" "The optional *verbose* argument controls how detailed the summary is. If " "the verbosity is not specified, then the :class:`DocTestRunner`'s verbosity " "is used." msgstr "" -#: ../../library/doctest.rst:1584 +#: ../../library/doctest.rst:1606 msgid ":class:`DocTestParser` has the following attributes:" msgstr "" -#: ../../library/doctest.rst:1588 +#: ../../library/doctest.rst:1610 msgid "Number of attempted examples." msgstr "" -#: ../../library/doctest.rst:1592 +#: ../../library/doctest.rst:1614 msgid "Number of failed examples." msgstr "" -#: ../../library/doctest.rst:1596 +#: ../../library/doctest.rst:1618 msgid "Number of skipped examples." msgstr "" -#: ../../library/doctest.rst:1604 +#: ../../library/doctest.rst:1626 msgid "OutputChecker objects" msgstr "" -#: ../../library/doctest.rst:1609 +#: ../../library/doctest.rst:1631 msgid "" "A class used to check the whether the actual output from a doctest example " "matches the expected output. :class:`OutputChecker` defines two methods: :" @@ -1936,11 +2478,11 @@ msgid "" "string describing the differences between two outputs." msgstr "" -#: ../../library/doctest.rst:1616 +#: ../../library/doctest.rst:1638 msgid ":class:`OutputChecker` defines the following methods:" msgstr ":class:`OutputChecker` define os seguintes métodos:" -#: ../../library/doctest.rst:1620 +#: ../../library/doctest.rst:1642 msgid "" "Return ``True`` iff the actual output from an example (*got*) matches the " "expected output (*want*). These strings are always considered to match if " @@ -1949,28 +2491,28 @@ msgid "" "`doctest-options` for more information about option flags." msgstr "" -#: ../../library/doctest.rst:1629 +#: ../../library/doctest.rst:1651 msgid "" "Return a string describing the differences between the expected output for a " "given example (*example*) and the actual output (*got*). *optionflags* is " "the set of option flags used to compare *want* and *got*." msgstr "" -#: ../../library/doctest.rst:1637 +#: ../../library/doctest.rst:1659 msgid "Debugging" msgstr "Depuração" -#: ../../library/doctest.rst:1639 +#: ../../library/doctest.rst:1661 msgid "Doctest provides several mechanisms for debugging doctest examples:" msgstr "" -#: ../../library/doctest.rst:1641 +#: ../../library/doctest.rst:1663 msgid "" "Several functions convert doctests to executable Python programs, which can " "be run under the Python debugger, :mod:`pdb`." msgstr "" -#: ../../library/doctest.rst:1644 +#: ../../library/doctest.rst:1666 msgid "" "The :class:`DebugRunner` class is a subclass of :class:`DocTestRunner` that " "raises an exception for the first failing example, containing information " @@ -1978,13 +2520,13 @@ msgid "" "debugging on the example." msgstr "" -#: ../../library/doctest.rst:1649 +#: ../../library/doctest.rst:1671 msgid "" "The :mod:`unittest` cases generated by :func:`DocTestSuite` support the :" "meth:`debug` method defined by :class:`unittest.TestCase`." msgstr "" -#: ../../library/doctest.rst:1652 +#: ../../library/doctest.rst:1674 msgid "" "You can add a call to :func:`pdb.set_trace` in a doctest example, and you'll " "drop into the Python debugger when that line is executed. Then you can " @@ -1992,21 +2534,67 @@ msgid "" "`a.py` contains just this module docstring::" msgstr "" -#: ../../library/doctest.rst:1667 +#: ../../library/doctest.rst:1679 +msgid "" +"\"\"\"\n" +">>> def f(x):\n" +"... g(x*2)\n" +">>> def g(x):\n" +"... print(x+3)\n" +"... import pdb; pdb.set_trace()\n" +">>> f(3)\n" +"9\n" +"\"\"\"" +msgstr "" + +#: ../../library/doctest.rst:1689 msgid "Then an interactive Python session may look like this::" msgstr "" -#: ../../library/doctest.rst:1700 +#: ../../library/doctest.rst:1691 +msgid "" +">>> import a, doctest\n" +">>> doctest.testmod(a)\n" +"--Return--\n" +"> (3)g()->None\n" +"-> import pdb; pdb.set_trace()\n" +"(Pdb) list\n" +" 1 def g(x):\n" +" 2 print(x+3)\n" +" 3 -> import pdb; pdb.set_trace()\n" +"[EOF]\n" +"(Pdb) p x\n" +"6\n" +"(Pdb) step\n" +"--Return--\n" +"> (2)f()->None\n" +"-> g(x*2)\n" +"(Pdb) list\n" +" 1 def f(x):\n" +" 2 -> g(x*2)\n" +"[EOF]\n" +"(Pdb) p x\n" +"3\n" +"(Pdb) step\n" +"--Return--\n" +"> (1)?()->None\n" +"-> f(3)\n" +"(Pdb) cont\n" +"(0, 3)\n" +">>>" +msgstr "" + +#: ../../library/doctest.rst:1722 msgid "" "Functions that convert doctests to Python code, and possibly run the " "synthesized code under the debugger:" msgstr "" -#: ../../library/doctest.rst:1706 +#: ../../library/doctest.rst:1728 msgid "Convert text with examples to a script." msgstr "" -#: ../../library/doctest.rst:1708 +#: ../../library/doctest.rst:1730 msgid "" "Argument *s* is a string containing doctest examples. The string is " "converted to a Python script, where doctest examples in *s* are converted to " @@ -2014,22 +2602,46 @@ msgid "" "generated script is returned as a string. For example, ::" msgstr "" -#: ../../library/doctest.rst:1723 +#: ../../library/doctest.rst:1735 +msgid "" +"import doctest\n" +"print(doctest.script_from_examples(r\"\"\"\n" +" Set x and y to 1 and 2.\n" +" >>> x, y = 1, 2\n" +"\n" +" Print their sum:\n" +" >>> print(x+y)\n" +" 3\n" +"\"\"\"))" +msgstr "" + +#: ../../library/doctest.rst:1745 msgid "displays::" msgstr "" -#: ../../library/doctest.rst:1733 +#: ../../library/doctest.rst:1747 +msgid "" +"# Set x and y to 1 and 2.\n" +"x, y = 1, 2\n" +"#\n" +"# Print their sum:\n" +"print(x+y)\n" +"# Expected:\n" +"## 3" +msgstr "" + +#: ../../library/doctest.rst:1755 msgid "" "This function is used internally by other functions (see below), but can " "also be useful when you want to transform an interactive Python session into " "a Python script." msgstr "" -#: ../../library/doctest.rst:1740 +#: ../../library/doctest.rst:1762 msgid "Convert the doctest for an object to a script." msgstr "" -#: ../../library/doctest.rst:1742 +#: ../../library/doctest.rst:1764 msgid "" "Argument *module* is a module object, or dotted name of a module, containing " "the object whose doctests are of interest. Argument *name* is the name " @@ -2039,17 +2651,23 @@ msgid "" "module :file:`a.py` contains a top-level function :func:`!f`, then ::" msgstr "" -#: ../../library/doctest.rst:1752 +#: ../../library/doctest.rst:1771 +msgid "" +"import a, doctest\n" +"print(doctest.testsource(a, \"a.f\"))" +msgstr "" + +#: ../../library/doctest.rst:1774 msgid "" "prints a script version of function :func:`!f`'s docstring, with doctests " "converted to code, and the rest placed in comments." msgstr "" -#: ../../library/doctest.rst:1758 +#: ../../library/doctest.rst:1780 msgid "Debug the doctests for an object." msgstr "" -#: ../../library/doctest.rst:1760 +#: ../../library/doctest.rst:1782 msgid "" "The *module* and *name* arguments are the same as for function :func:" "`testsource` above. The synthesized Python script for the named object's " @@ -2057,13 +2675,13 @@ msgid "" "the control of the Python debugger, :mod:`pdb`." msgstr "" -#: ../../library/doctest.rst:1765 +#: ../../library/doctest.rst:1787 msgid "" "A shallow copy of ``module.__dict__`` is used for both local and global " "execution context." msgstr "" -#: ../../library/doctest.rst:1768 +#: ../../library/doctest.rst:1790 msgid "" "Optional argument *pm* controls whether post-mortem debugging is used. If " "*pm* has a true value, the script file is run directly, and the debugger " @@ -2075,30 +2693,30 @@ msgid "" "to :func:`pdb.run`." msgstr "" -#: ../../library/doctest.rst:1779 +#: ../../library/doctest.rst:1801 msgid "Debug the doctests in a string." msgstr "" -#: ../../library/doctest.rst:1781 +#: ../../library/doctest.rst:1803 msgid "" "This is like function :func:`debug` above, except that a string containing " "doctest examples is specified directly, via the *src* argument." msgstr "" -#: ../../library/doctest.rst:1784 +#: ../../library/doctest.rst:1806 msgid "" "Optional argument *pm* has the same meaning as in function :func:`debug` " "above." msgstr "" -#: ../../library/doctest.rst:1786 +#: ../../library/doctest.rst:1808 msgid "" "Optional argument *globs* gives a dictionary to use as both local and global " "execution context. If not specified, or ``None``, an empty dictionary is " "used. If specified, a shallow copy of the dictionary is used." msgstr "" -#: ../../library/doctest.rst:1791 +#: ../../library/doctest.rst:1813 msgid "" "The :class:`DebugRunner` class, and the special exceptions it may raise, are " "of most interest to testing framework authors, and will only be sketched " @@ -2106,7 +2724,7 @@ msgid "" "(which is a doctest!) for more details:" msgstr "" -#: ../../library/doctest.rst:1799 +#: ../../library/doctest.rst:1821 msgid "" "A subclass of :class:`DocTestRunner` that raises an exception as soon as a " "failure is encountered. If an unexpected exception occurs, an :exc:" @@ -2116,89 +2734,89 @@ msgid "" "the actual output." msgstr "" -#: ../../library/doctest.rst:1806 +#: ../../library/doctest.rst:1828 msgid "" "For information about the constructor parameters and methods, see the " "documentation for :class:`DocTestRunner` in section :ref:`doctest-advanced-" "api`." msgstr "" -#: ../../library/doctest.rst:1809 +#: ../../library/doctest.rst:1831 msgid "" "There are two exceptions that may be raised by :class:`DebugRunner` " "instances:" msgstr "" -#: ../../library/doctest.rst:1814 +#: ../../library/doctest.rst:1836 msgid "" "An exception raised by :class:`DocTestRunner` to signal that a doctest " "example's actual output did not match its expected output. The constructor " "arguments are used to initialize the attributes of the same names." msgstr "" -#: ../../library/doctest.rst:1818 +#: ../../library/doctest.rst:1840 msgid ":exc:`DocTestFailure` defines the following attributes:" msgstr "" -#: ../../library/doctest.rst:1823 ../../library/doctest.rst:1847 +#: ../../library/doctest.rst:1845 ../../library/doctest.rst:1869 msgid "The :class:`DocTest` object that was being run when the example failed." msgstr "" -#: ../../library/doctest.rst:1828 ../../library/doctest.rst:1852 +#: ../../library/doctest.rst:1850 ../../library/doctest.rst:1874 msgid "The :class:`Example` that failed." msgstr "" -#: ../../library/doctest.rst:1833 +#: ../../library/doctest.rst:1855 msgid "The example's actual output." msgstr "" -#: ../../library/doctest.rst:1838 +#: ../../library/doctest.rst:1860 msgid "" "An exception raised by :class:`DocTestRunner` to signal that a doctest " "example raised an unexpected exception. The constructor arguments are used " "to initialize the attributes of the same names." msgstr "" -#: ../../library/doctest.rst:1842 +#: ../../library/doctest.rst:1864 msgid ":exc:`UnexpectedException` defines the following attributes:" msgstr ":exc:`UnexpectedException` define os seguintes atributos:" -#: ../../library/doctest.rst:1857 +#: ../../library/doctest.rst:1879 msgid "" "A tuple containing information about the unexpected exception, as returned " "by :func:`sys.exc_info`." msgstr "" -#: ../../library/doctest.rst:1864 +#: ../../library/doctest.rst:1886 msgid "Soapbox" msgstr "" -#: ../../library/doctest.rst:1866 +#: ../../library/doctest.rst:1888 msgid "" "As mentioned in the introduction, :mod:`doctest` has grown to have three " "primary uses:" msgstr "" -#: ../../library/doctest.rst:1869 +#: ../../library/doctest.rst:1891 msgid "Checking examples in docstrings." msgstr "" -#: ../../library/doctest.rst:1871 +#: ../../library/doctest.rst:1893 msgid "Regression testing." msgstr "" -#: ../../library/doctest.rst:1873 +#: ../../library/doctest.rst:1895 msgid "Executable documentation / literate testing." msgstr "" -#: ../../library/doctest.rst:1875 +#: ../../library/doctest.rst:1897 msgid "" "These uses have different requirements, and it is important to distinguish " "them. In particular, filling your docstrings with obscure test cases makes " "for bad documentation." msgstr "" -#: ../../library/doctest.rst:1879 +#: ../../library/doctest.rst:1901 msgid "" "When writing a docstring, choose docstring examples with care. There's an " "art to this that needs to be learned---it may not be natural at first. " @@ -2210,7 +2828,7 @@ msgid "" "\"harmless\" change." msgstr "" -#: ../../library/doctest.rst:1887 +#: ../../library/doctest.rst:1909 msgid "" "Doctest also makes an excellent tool for regression testing, especially if " "you don't skimp on explanatory text. By interleaving prose and examples, it " @@ -2231,13 +2849,13 @@ msgid "" "different results, blurring the distinction between testing and explaining." msgstr "" -#: ../../library/doctest.rst:1905 +#: ../../library/doctest.rst:1927 msgid "" "Regression testing is best confined to dedicated objects or files. There " "are several options for organizing tests:" msgstr "" -#: ../../library/doctest.rst:1908 +#: ../../library/doctest.rst:1930 msgid "" "Write text files containing test cases as interactive examples, and test the " "files using :func:`testfile` or :func:`DocFileSuite`. This is recommended, " @@ -2245,7 +2863,7 @@ msgid "" "doctest." msgstr "" -#: ../../library/doctest.rst:1913 +#: ../../library/doctest.rst:1935 msgid "" "Define functions named ``_regrtest_topic`` that consist of single " "docstrings, containing test cases for the named topics. These functions can " @@ -2253,13 +2871,13 @@ msgid "" "test file." msgstr "" -#: ../../library/doctest.rst:1917 +#: ../../library/doctest.rst:1939 msgid "" "Define a ``__test__`` dictionary mapping from regression test topics to " "docstrings containing test cases." msgstr "" -#: ../../library/doctest.rst:1920 +#: ../../library/doctest.rst:1942 msgid "" "When you have placed your tests in a module, the module can itself be the " "test runner. When a test fails, you can arrange for your test runner to re-" @@ -2267,53 +2885,71 @@ msgid "" "example of such a test runner::" msgstr "" -#: ../../library/doctest.rst:1942 +#: ../../library/doctest.rst:1947 +msgid "" +"if __name__ == '__main__':\n" +" import doctest\n" +" flags = doctest.REPORT_NDIFF|doctest.FAIL_FAST\n" +" if len(sys.argv) > 1:\n" +" name = sys.argv[1]\n" +" if name in globals():\n" +" obj = globals()[name]\n" +" else:\n" +" obj = __test__[name]\n" +" doctest.run_docstring_examples(obj, globals(), name=name,\n" +" optionflags=flags)\n" +" else:\n" +" fail, total = doctest.testmod(optionflags=flags)\n" +" print(f\"{fail} failures out of {total} tests\")" +msgstr "" + +#: ../../library/doctest.rst:1964 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../library/doctest.rst:1943 +#: ../../library/doctest.rst:1965 msgid "" "Examples containing both expected output and an exception are not supported. " "Trying to guess where one ends and the other begins is too error-prone, and " "that also makes for a confusing test." msgstr "" -#: ../../library/doctest.rst:339 +#: ../../library/doctest.rst:369 msgid ">>>" msgstr ">>>" -#: ../../library/doctest.rst:339 +#: ../../library/doctest.rst:369 msgid "interpreter prompt" -msgstr "" +msgstr "prompt do interpretador" -#: ../../library/doctest.rst:339 ../../library/doctest.rst:577 +#: ../../library/doctest.rst:369 ../../library/doctest.rst:604 msgid "..." msgstr "..." -#: ../../library/doctest.rst:505 +#: ../../library/doctest.rst:535 msgid "^ (caret)" msgstr "^ (circunflexo)" -#: ../../library/doctest.rst:505 +#: ../../library/doctest.rst:535 msgid "marker" msgstr "" -#: ../../library/doctest.rst:557 +#: ../../library/doctest.rst:584 msgid "" msgstr "" -#: ../../library/doctest.rst:577 ../../library/doctest.rst:707 +#: ../../library/doctest.rst:604 ../../library/doctest.rst:729 msgid "in doctests" msgstr "" -#: ../../library/doctest.rst:707 +#: ../../library/doctest.rst:729 msgid "# (hash)" msgstr "# (cerquilha)" -#: ../../library/doctest.rst:707 +#: ../../library/doctest.rst:729 msgid "+ (plus)" msgstr "+ (mais)" -#: ../../library/doctest.rst:707 +#: ../../library/doctest.rst:729 msgid "- (minus)" msgstr "- (menos)" diff --git a/library/email.charset.po b/library/email.charset.po index b7dd7e376..19441edeb 100644 --- a/library/email.charset.po +++ b/library/email.charset.po @@ -1,31 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:04+0000\n" -"Last-Translator: Rafael Fontenelle , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/email.charset.rst:2 msgid ":mod:`!email.charset`: Representing character sets" -msgstr "" +msgstr ":mod:`!email.charset`: Representando conjuntos de caracteres" #: ../../library/email.charset.rst:7 msgid "**Source code:** :source:`Lib/email/charset.py`" @@ -36,12 +36,14 @@ msgid "" "This module is part of the legacy (``Compat32``) email API. In the new API " "only the aliases table is used." msgstr "" +"Este módulo faz parte da API de e-mail legada (``Compat32``). Na nova API, " +"apenas a tabela de apelidos é usada." #: ../../library/email.charset.rst:14 msgid "" "The remaining text in this section is the original documentation of the " "module." -msgstr "" +msgstr "O texto restante nesta seção é a documentação original do módulo." #: ../../library/email.charset.rst:16 msgid "" @@ -51,14 +53,19 @@ msgid "" "Instances of :class:`Charset` are used in several other modules within the :" "mod:`email` package." msgstr "" +"Este módulo fornece uma classe :class:`Charset` para representar conjuntos " +"de caracteres e conversões de conjuntos de caracteres em mensagens de e-" +"mail, bem como um registro de conjuntos de caracteres e vários métodos " +"práticos para manipular esse registro. Instâncias de :class:`Charset` são " +"usadas em vários outros módulos do pacote :mod:`email`." #: ../../library/email.charset.rst:22 msgid "Import this class from the :mod:`email.charset` module." -msgstr "" +msgstr "Importa esta classe do módulo :mod:`email.charset`." #: ../../library/email.charset.rst:27 msgid "Map character sets to their email properties." -msgstr "" +msgstr "Mapeia conjuntos de caracteres para suas propriedades de e-mail." #: ../../library/email.charset.rst:29 msgid "" @@ -68,6 +75,12 @@ msgid "" "codecs. Given a character set, it will do its best to provide information " "on how to use that character set in an email message in an RFC-compliant way." msgstr "" +"Esta classe fornece informações sobre os requisitos impostos ao e-mail para " +"um conjunto de caracteres específico. Também fornece rotinas práticas para " +"conversão entre conjuntos de caracteres, considerando a disponibilidade dos " +"codecs aplicáveis. Dado um conjunto de caracteres, ela fará o possível para " +"fornecer informações sobre como usá-lo em uma mensagem de e-mail de forma " +"compatível com RFC." #: ../../library/email.charset.rst:35 msgid "" @@ -75,6 +88,9 @@ msgid "" "used in email headers or bodies. Certain character sets must be converted " "outright, and are not allowed in email." msgstr "" +"Certos conjuntos de caracteres devem ser codificados com quoted-printable ou " +"base64 quando usados ​​em cabeçalhos ou corpos de e-mail. Certos conjuntos de " +"caracteres devem ser convertidos diretamente e não são permitidos em e-mails." #: ../../library/email.charset.rst:39 msgid "" @@ -88,10 +104,21 @@ msgid "" "with base64, bodies will not be encoded, but output text will be converted " "from the ``euc-jp`` character set to the ``iso-2022-jp`` character set." msgstr "" +"O *input_charset* opcional é descrito abaixo; ele é sempre convertido para " +"letras minúsculas. Após ser normalizado por apelido, ele também é usado como " +"uma consulta no registro de conjuntos de caracteres para descobrir a " +"codificação do cabeçalho, a codificação do corpo e o codec de conversão de " +"saída a serem usados ​​para o conjunto de caracteres. Por exemplo, se " +"*input_charset* for ``iso-8859-1``, os cabeçalhos e corpos serão codificados " +"usando quoted-printable e nenhum codec de conversão de saída será " +"necessário. Se *input_charset* for ``euc-jp``, os cabeçalhos serão " +"codificados em base64, os corpos não serão codificados, mas o texto de saída " +"será convertido do conjunto de caracteres ``euc-jp`` para o conjunto de " +"caracteres ``iso-2022-jp``." #: ../../library/email.charset.rst:49 msgid ":class:`Charset` instances have the following data attributes:" -msgstr "" +msgstr "Instâncias :class:`Charset` têm os seguintes atributos de dados:" #: ../../library/email.charset.rst:53 msgid "" @@ -99,6 +126,9 @@ msgid "" "*official* email names (e.g. ``latin_1`` is converted to ``iso-8859-1``). " "Defaults to 7-bit ``us-ascii``." msgstr "" +"O conjunto de caracteres inicial especificado. Apelidos comuns são " +"convertidos em seus nomes de e-mail *oficiais* (por exemplo, ``latin_1`` é " +"convertido para ``iso-8859-1``). O padrão é ``us-ascii`` de 7 bits." #: ../../library/email.charset.rst:60 msgid "" @@ -107,6 +137,11 @@ msgid "" "``charset.BASE64`` (for base64 encoding), or ``charset.SHORTEST`` for the " "shortest of QP or BASE64 encoding. Otherwise, it will be ``None``." msgstr "" +"Se o conjunto de caracteres precisar ser codificado antes de ser usado em um " +"cabeçalho de e-mail, este atributo será definido como ``charset.QP`` (para " +"quoted-printable), ``charset.BASE64`` (para codificação base64) ou ``charset." +"SHORTEST`` para a codificação mais curta entre QP ou BASE64. Caso contrário, " +"será ``None``." #: ../../library/email.charset.rst:69 msgid "" @@ -114,6 +149,9 @@ msgid "" "body, which indeed may be different than the header encoding. ``charset." "SHORTEST`` is not allowed for *body_encoding*." msgstr "" +"O mesmo que *header_encoding*, mas descreve a codificação do corpo da " +"mensagem de e-mail, que pode ser diferente da codificação do cabeçalho. " +"``charset.SHORTEST`` não é permitido para *body_encoding*." #: ../../library/email.charset.rst:76 msgid "" @@ -122,6 +160,10 @@ msgid "" "will contain the name of the character set output will be converted to. " "Otherwise, it will be ``None``." msgstr "" +"Alguns conjuntos de caracteres precisam ser convertidos antes de serem " +"usados ​​em cabeçalhos ou corpos de e-mail. Se *input_charset* for um deles, " +"este atributo conterá o nome do conjunto de caracteres para o qual a saída " +"será convertida. Caso contrário, será ``None``." #: ../../library/email.charset.rst:84 msgid "" @@ -129,6 +171,8 @@ msgid "" "Unicode. If no conversion codec is necessary, this attribute will be " "``None``." msgstr "" +"O nome do codec Python usado para converter o *input_charset* para Unicode. " +"Se nenhum codec de conversão for necessário, este atributo será ``None``." #: ../../library/email.charset.rst:91 msgid "" @@ -136,14 +180,19 @@ msgid "" "*output_charset*. If no conversion codec is necessary, this attribute will " "have the same value as the *input_codec*." msgstr "" +"O nome do codec Python usado para converter Unicode para o *output_charset*. " +"Se nenhum codec de conversão for necessário, este atributo terá o mesmo " +"valor que o *input_codec*." #: ../../library/email.charset.rst:96 msgid ":class:`Charset` instances also have the following methods:" -msgstr "" +msgstr "Instâncias :class:`Charset` também têm os seguintes métodos:" #: ../../library/email.charset.rst:100 msgid "Return the content transfer encoding used for body encoding." msgstr "" +"Retorna a codificação de transferência de conteúdo usada para codificação do " +"corpo." #: ../../library/email.charset.rst:102 msgid "" @@ -153,6 +202,11 @@ msgid "" "function should then set the :mailheader:`Content-Transfer-Encoding` header " "itself to whatever is appropriate." msgstr "" +"Esta é a string ``quoted-printable`` ou ``base64``, dependendo da " +"codificação usada, ou é uma função, caso em que você deve chamar a função " +"com um único argumento, sendo o objeto Message codificado. A função deve " +"então definir o próprio cabeçalho :mailheader:`Content-Transfer-Encoding` " +"com o valor apropriado." #: ../../library/email.charset.rst:108 msgid "" @@ -160,30 +214,37 @@ msgid "" "returns the string ``base64`` if *body_encoding* is ``BASE64``, and returns " "the string ``7bit`` otherwise." msgstr "" +"Retorna a string ``quoted-printable`` se *body_encoding* for ``QP``, retorna " +"a string ``base64`` se *body_encoding* for ``BASE64`` e retorna a string " +"``7bit`` caso contrário." #: ../../library/email.charset.rst:115 msgid "Return the output character set." -msgstr "" +msgstr "Retorna o conjunto de caracteres de saída." #: ../../library/email.charset.rst:117 msgid "" "This is the *output_charset* attribute if that is not ``None``, otherwise it " "is *input_charset*." msgstr "" +"Este é o atributo *output_charset* se não for ``None``, caso contrário, é " +"*input_charset*." #: ../../library/email.charset.rst:123 msgid "Header-encode the string *string*." -msgstr "" +msgstr "Codifica o cabeçalho com a string *string*." #: ../../library/email.charset.rst:125 msgid "" "The type of encoding (base64 or quoted-printable) will be based on the " "*header_encoding* attribute." msgstr "" +"O tipo de codificação (base64 ou quoted-printable) será baseado no atributo " +"*header_encoding*." #: ../../library/email.charset.rst:131 msgid "Header-encode a *string* by converting it first to bytes." -msgstr "" +msgstr "Codifica um cabeçalho de uma *string* convertendo-a primeiro em bytes." #: ../../library/email.charset.rst:133 msgid "" @@ -192,56 +253,75 @@ msgid "" "iterator: each element returned from this iterator will provide the next " "maximum line length." msgstr "" +"Isso é semelhante a :meth:`header_encode`, exceto que a string é ajustada " +"aos comprimentos máximos de linha, conforme fornecido pelo argumento " +"*maxlengths*, que deve ser um iterador: cada elemento retornado deste " +"iterador fornecerá o próximo comprimento máximo de linha." #: ../../library/email.charset.rst:141 msgid "Body-encode the string *string*." -msgstr "" +msgstr "Codifica o corpo com a string *string*." #: ../../library/email.charset.rst:143 msgid "" "The type of encoding (base64 or quoted-printable) will be based on the " "*body_encoding* attribute." msgstr "" +"O tipo de codificação (base64 ou quoted-printable) será baseado no atributo " +"*body_encoding*." #: ../../library/email.charset.rst:146 msgid "" "The :class:`Charset` class also provides a number of methods to support " "standard operations and built-in functions." msgstr "" +"A classe :class:`Charset` também fornece vários métodos para dar suporte a " +"operações padrão e funções embutidas." #: ../../library/email.charset.rst:152 msgid "" "Returns *input_charset* as a string coerced to lower case. :meth:`!__repr__` " "is an alias for :meth:`!__str__`." msgstr "" +"Retorna *input_charset* como uma string convertida para minúsculas. :meth:`!" +"__repr__` é um apelido para :meth:`!__str__`." #: ../../library/email.charset.rst:158 msgid "" "This method allows you to compare two :class:`Charset` instances for " "equality." msgstr "" +"Este método permite que você compare duas instâncias :class:`Charset` para " +"verificar a igualdade." #: ../../library/email.charset.rst:164 msgid "" "This method allows you to compare two :class:`Charset` instances for " "inequality." msgstr "" +"Este método permite que você compare duas instâncias :class:`Charset` para " +"verificar a desigualdade." #: ../../library/email.charset.rst:167 msgid "" "The :mod:`email.charset` module also provides the following functions for " "adding new entries to the global character set, alias, and codec registries:" msgstr "" +"O módulo :mod:`email.charset` também fornece as seguintes funções para " +"adicionar novas entradas ao conjunto global de caracteres, apelidos e " +"registros de codec:" #: ../../library/email.charset.rst:173 msgid "Add character properties to the global registry." -msgstr "" +msgstr "Adiciona propriedades de caracteres ao registro global." #: ../../library/email.charset.rst:175 msgid "" "*charset* is the input character set, and must be the canonical name of a " "character set." msgstr "" +"*charset* é o conjunto de caracteres de entrada e deve ser o nome canônico " +"de um conjunto de caracteres." #: ../../library/email.charset.rst:178 msgid "" @@ -251,6 +331,11 @@ msgid "" "encoding. ``SHORTEST`` is only valid for *header_enc*. The default is " "``None`` for no encoding." msgstr "" +"*header_enc* e *body_enc* opcionais são ``charset.QP`` para quoted-" +"printable, ``charset.BASE64`` para codificação base64, ``charset.SHORTEST`` " +"para a codificação mais curta entre quoted-printable ou base64, ou ``None`` " +"para nenhuma codificação. ``SHORTEST`` é válido apenas para *header_enc*. O " +"padrão é ``None`` para nenhuma codificação." #: ../../library/email.charset.rst:184 msgid "" @@ -259,6 +344,11 @@ msgid "" "charset when the method :meth:`Charset.convert` is called. The default is " "to output in the same character set as the input." msgstr "" +"*output_charset* opcional é o conjunto de caracteres que a saída deve " +"conter. As conversões prosseguirão do conjunto de caracteres de entrada para " +"Unicode e para o conjunto de caracteres de saída quando o método :meth:" +"`Charset.convert` for chamado. O padrão é gerar a saída no mesmo conjunto de " +"caracteres da entrada." #: ../../library/email.charset.rst:189 msgid "" @@ -267,30 +357,43 @@ msgid "" "codecs the module does not know about. See the :mod:`codecs` module's " "documentation for more information." msgstr "" +"Tanto *input_charset* quanto *output_charset* devem ter entradas de codec " +"Unicode no mapeamento de conjunto de caracteres para codec do módulo; use :" +"func:`add_codec` para adicionar codecs que o módulo não conhece. Consulte a " +"documentação do módulo :mod:`codecs` para obter mais informações." #: ../../library/email.charset.rst:194 msgid "" "The global character set registry is kept in the module global dictionary " "``CHARSETS``." msgstr "" +"O registro do conjunto de caracteres global é mantido no dicionário global " +"do módulo ``CHARSETS``." #: ../../library/email.charset.rst:200 msgid "" "Add a character set alias. *alias* is the alias name, e.g. ``latin-1``. " "*canonical* is the character set's canonical name, e.g. ``iso-8859-1``." msgstr "" +"Adicione um apelido para o conjunto de caracteres. *alias* é o nome do " +"alias, por exemplo, ``latin-1``. *canonical* é o nome canônico do conjunto " +"de caracteres, por exemplo, ``iso-8859-1``." #: ../../library/email.charset.rst:203 msgid "" "The global charset alias registry is kept in the module global dictionary " "``ALIASES``." msgstr "" +"O registro global de apelido de conjunto de caracteres é mantido no " +"dicionário global do módulo ``ALIASES``." #: ../../library/email.charset.rst:209 msgid "" "Add a codec that map characters in the given character set to and from " "Unicode." msgstr "" +"Adiciona um codec que mapeia caracteres no conjunto de caracteres fornecido " +"para e a partir do Unicode." #: ../../library/email.charset.rst:211 msgid "" @@ -298,3 +401,6 @@ msgid "" "of a Python codec, as appropriate for the second argument to the :class:" "`str`'s :meth:`~str.encode` method." msgstr "" +"*charset* é o nome canônico de um conjunto de caracteres. *codecname* é o " +"nome de um codec Python, conforme apropriado para o segundo argumento do " +"método :meth:`~str.encode` do :class:`str`." diff --git a/library/email.compat32-message.po b/library/email.compat32-message.po index 9ceb94f3f..849b57edb 100644 --- a/library/email.compat32-message.po +++ b/library/email.compat32-message.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# i17obot , 2021 -# Vitor Buxbaum Orlandi, 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-26 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:04+0000\n" -"Last-Translator: Vitor Buxbaum Orlandi, 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -138,6 +136,16 @@ msgid "" "method directly. For example::" msgstr "" +#: ../../library/email.compat32-message.rst:91 +msgid "" +"from io import StringIO\n" +"from email.generator import Generator\n" +"fp = StringIO()\n" +"g = Generator(fp, mangle_from_=True, maxheaderlen=60)\n" +"g.flatten(msg)\n" +"text = fp.getvalue()" +msgstr "" + #: ../../library/email.compat32-message.rst:98 msgid "" "If the message object contains binary data that is not encoded according to " @@ -152,7 +160,7 @@ msgstr "" #: ../../library/email.compat32-message.rst:108 msgid "" -"Equivalent to :meth:`.as_string()`. Allows ``str(msg)`` to produce a string " +"Equivalent to :meth:`.as_string`. Allows ``str(msg)`` to produce a string " "containing the formatted message." msgstr "" @@ -176,9 +184,19 @@ msgid "" "flatten` method directly. For example::" msgstr "" +#: ../../library/email.compat32-message.rst:134 +msgid "" +"from io import BytesIO\n" +"from email.generator import BytesGenerator\n" +"fp = BytesIO()\n" +"g = BytesGenerator(fp, mangle_from_=True, maxheaderlen=60)\n" +"g.flatten(msg)\n" +"text = fp.getvalue()" +msgstr "" + #: ../../library/email.compat32-message.rst:146 msgid "" -"Equivalent to :meth:`.as_bytes()`. Allows ``bytes(msg)`` to produce a bytes " +"Equivalent to :meth:`.as_bytes`. Allows ``bytes(msg)`` to produce a bytes " "object containing the formatted message." msgstr "" @@ -380,6 +398,12 @@ msgid "" "Used for the ``in`` operator, e.g.::" msgstr "" +#: ../../library/email.compat32-message.rst:316 +msgid "" +"if 'message-id' in myMessage:\n" +" print('Message-ID:', myMessage['message-id'])" +msgstr "" + #: ../../library/email.compat32-message.rst:322 msgid "" "Return the value of the named header field. *name* should not include the " @@ -408,6 +432,12 @@ msgid "" "present in the message with field name *name*, delete the field first, e.g.::" msgstr "" +#: ../../library/email.compat32-message.rst:341 +msgid "" +"del msg['subject']\n" +"msg['subject'] = 'Python roolz!'" +msgstr "" + #: ../../library/email.compat32-message.rst:347 msgid "" "Delete all occurrences of the field with name *name* from the message's " @@ -476,18 +506,37 @@ msgstr "" msgid "Here's an example::" msgstr "Aqui está um exemplo::" +#: ../../library/email.compat32-message.rst:407 +msgid "msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')" +msgstr "" + #: ../../library/email.compat32-message.rst:409 msgid "This will add a header that looks like ::" msgstr "" +#: ../../library/email.compat32-message.rst:411 +msgid "Content-Disposition: attachment; filename=\"bud.gif\"" +msgstr "Content-Disposition: attachment; filename=\"bud.gif\"" + #: ../../library/email.compat32-message.rst:413 msgid "An example with non-ASCII characters::" msgstr "Um exemplo com caracteres não-ASCII::" +#: ../../library/email.compat32-message.rst:415 +msgid "" +"msg.add_header('Content-Disposition', 'attachment',\n" +" filename=('iso-8859-1', '', 'Fußballer.ppt'))" +msgstr "" + #: ../../library/email.compat32-message.rst:418 msgid "Which produces ::" msgstr "Que produz ::" +#: ../../library/email.compat32-message.rst:420 +msgid "" +"Content-Disposition: attachment; filename*=\"iso-8859-1''Fu%DFballer.ppt\"" +msgstr "" + #: ../../library/email.compat32-message.rst:425 msgid "" "Replace a header. Replace the first header found in the message that " @@ -599,6 +648,12 @@ msgid "" "value is a tuple, or the original string unquoted if it isn't. For example::" msgstr "" +#: ../../library/email.compat32-message.rst:519 +msgid "" +"rawparam = msg.get_param('foo')\n" +"param = email.utils.collapse_rfc2231_value(rawparam)" +msgstr "" + #: ../../library/email.compat32-message.rst:522 msgid "" "In any case, the parameter value (either the returned string, or the " @@ -766,6 +821,19 @@ msgid "" "message structure:" msgstr "" +#: ../../library/email.compat32-message.rst:674 +msgid "" +">>> for part in msg.walk():\n" +"... print(part.get_content_type())\n" +"multipart/report\n" +"text/plain\n" +"message/delivery-status\n" +"text/plain\n" +"text/plain\n" +"message/rfc822\n" +"text/plain" +msgstr "" + #: ../../library/email.compat32-message.rst:686 msgid "" "``walk`` iterates over the subparts of any part where :meth:`is_multipart` " @@ -774,6 +842,28 @@ msgid "" "``_structure`` debug helper function:" msgstr "" +#: ../../library/email.compat32-message.rst:692 +msgid "" +">>> for part in msg.walk():\n" +"... print(part.get_content_maintype() == 'multipart',\n" +"... part.is_multipart())\n" +"True True\n" +"False False\n" +"False True\n" +"False False\n" +"False False\n" +"False True\n" +"False False\n" +">>> _structure(msg)\n" +"multipart/report\n" +" text/plain\n" +" message/delivery-status\n" +" text/plain\n" +" text/plain\n" +" message/rfc822\n" +" text/plain" +msgstr "" + #: ../../library/email.compat32-message.rst:713 msgid "" "Here the ``message`` parts are not ``multiparts``, but they do contain " diff --git a/library/email.contentmanager.po b/library/email.contentmanager.po index 1723f84d2..39c5410ca 100644 --- a/library/email.contentmanager.po +++ b/library/email.contentmanager.po @@ -1,32 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:04+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-01-24 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/email.contentmanager.rst:2 msgid ":mod:`!email.contentmanager`: Managing MIME Content" -msgstr "" +msgstr ":mod:`!email.contentmanager`: Gerenciando conteúdo MIME" #: ../../library/email.contentmanager.rst:10 msgid "**Source code:** :source:`Lib/email/contentmanager.py`" @@ -42,6 +41,10 @@ msgid "" "to register converters between MIME content and other representations, as " "well as the ``get_content`` and ``set_content`` dispatch methods." msgstr "" +"Classe base para gerenciadores de conteúdo. Fornece os mecanismos de " +"registro padrão para registrar conversores entre conteúdo MIME e outras " +"representações, bem como os métodos de despacho ``get_content`` e " +"``set_content``." #: ../../library/email.contentmanager.rst:26 msgid "" @@ -50,16 +53,23 @@ msgid "" "the call. The expectation is that the handler will extract the payload from " "*msg* and return an object that encodes information about the extracted data." msgstr "" +"Procura uma função manipuladora baseada no ``mimetype`` de *msg* (veja o " +"próximo parágrafo), chama-a, passando por todos os argumentos, e retorna o " +"resultado da chamada. A expectativa é que a função manipuladora extraia o " +"payload de *msg* e retorne um objeto que codifique informações sobre os " +"dados extraídos." #: ../../library/email.contentmanager.rst:32 msgid "" "To find the handler, look for the following keys in the registry, stopping " "with the first one found:" msgstr "" +"Para encontrar o manipulador, procura as seguintes chaves no registro, " +"parando na primeira encontrada:" #: ../../library/email.contentmanager.rst:35 msgid "the string representing the full MIME type (``maintype/subtype``)" -msgstr "" +msgstr "a string que representa o tipo MIME completo (``maintype/subtype``)" #: ../../library/email.contentmanager.rst:36 msgid "the string representing the ``maintype``" @@ -104,46 +114,46 @@ msgid "" msgstr "" #: ../../library/email.contentmanager.rst:61 -msgid "the type's qualname (``typ.__qualname__``)" +msgid "the type's :attr:`qualname ` (``typ.__qualname__``)" msgstr "" #: ../../library/email.contentmanager.rst:62 -msgid "the type's name (``typ.__name__``)." +msgid "the type's :attr:`name ` (``typ.__name__``)." msgstr "" #: ../../library/email.contentmanager.rst:64 msgid "" "If none of the above match, repeat all of the checks above for each of the " -"types in the :term:`MRO` (``typ.__mro__``). Finally, if no other key yields " -"a handler, check for a handler for the key ``None``. If there is no handler " -"for ``None``, raise a :exc:`KeyError` for the fully qualified name of the " -"type." +"types in the :term:`MRO` (:attr:`typ.__mro__ `). Finally, if " +"no other key yields a handler, check for a handler for the key ``None``. If " +"there is no handler for ``None``, raise a :exc:`KeyError` for the fully " +"qualified name of the type." msgstr "" -#: ../../library/email.contentmanager.rst:70 +#: ../../library/email.contentmanager.rst:71 msgid "" "Also add a :mailheader:`MIME-Version` header if one is not present (see " "also :class:`.MIMEPart`)." msgstr "" -#: ../../library/email.contentmanager.rst:76 +#: ../../library/email.contentmanager.rst:77 msgid "" "Record the function *handler* as the handler for *key*. For the possible " "values of *key*, see :meth:`get_content`." msgstr "" -#: ../../library/email.contentmanager.rst:82 +#: ../../library/email.contentmanager.rst:83 msgid "" "Record *handler* as the function to call when an object of a type matching " "*typekey* is passed to :meth:`set_content`. For the possible values of " "*typekey*, see :meth:`set_content`." msgstr "" -#: ../../library/email.contentmanager.rst:88 +#: ../../library/email.contentmanager.rst:89 msgid "Content Manager Instances" msgstr "" -#: ../../library/email.contentmanager.rst:90 +#: ../../library/email.contentmanager.rst:91 msgid "" "Currently the email package provides only one concrete content manager, :" "data:`raw_data_manager`, although more may be added in the future. :data:" @@ -151,7 +161,7 @@ msgid "" "provided by :attr:`~email.policy.EmailPolicy` and its derivatives." msgstr "" -#: ../../library/email.contentmanager.rst:99 +#: ../../library/email.contentmanager.rst:100 msgid "" "This content manager provides only a minimum interface beyond that provided " "by :class:`~email.message.Message` itself: it deals only with text, raw " @@ -164,7 +174,7 @@ msgid "" "simplifying the creation of multipart messages." msgstr "" -#: ../../library/email.contentmanager.rst:111 +#: ../../library/email.contentmanager.rst:112 msgid "" "Return the payload of the part as either a string (for ``text`` parts), an :" "class:`~email.message.EmailMessage` object (for ``message/rfc822`` parts), " @@ -174,28 +184,28 @@ msgid "" "to unicode. The default error handler is ``replace``." msgstr "" -#: ../../library/email.contentmanager.rst:130 +#: ../../library/email.contentmanager.rst:131 msgid "Add headers and payload to *msg*:" msgstr "Adicione headers e payload à *msg*:" -#: ../../library/email.contentmanager.rst:132 +#: ../../library/email.contentmanager.rst:133 msgid "" "Add a :mailheader:`Content-Type` header with a ``maintype/subtype`` value." msgstr "" -#: ../../library/email.contentmanager.rst:135 +#: ../../library/email.contentmanager.rst:136 msgid "" "For ``str``, set the MIME ``maintype`` to ``text``, and set the subtype to " "*subtype* if it is specified, or ``plain`` if it is not." msgstr "" -#: ../../library/email.contentmanager.rst:137 +#: ../../library/email.contentmanager.rst:138 msgid "" "For ``bytes``, use the specified *maintype* and *subtype*, or raise a :exc:" "`TypeError` if they are not specified." msgstr "" -#: ../../library/email.contentmanager.rst:139 +#: ../../library/email.contentmanager.rst:140 msgid "" "For :class:`~email.message.EmailMessage` objects, set the maintype to " "``message``, and set the subtype to *subtype* if it is specified or " @@ -203,7 +213,7 @@ msgid "" "(``bytes`` objects must be used to construct ``message/partial`` parts)." msgstr "" -#: ../../library/email.contentmanager.rst:145 +#: ../../library/email.contentmanager.rst:146 msgid "" "If *charset* is provided (which is valid only for ``str``), encode the " "string to bytes using the specified character set. The default is " @@ -211,7 +221,7 @@ msgid "" "charset name, use the standard charset instead." msgstr "" -#: ../../library/email.contentmanager.rst:150 +#: ../../library/email.contentmanager.rst:151 msgid "" "If *cte* is set, encode the payload using the specified content transfer " "encoding, and set the :mailheader:`Content-Transfer-Encoding` header to that " @@ -221,13 +231,22 @@ msgid "" "that contains non-ASCII values), raise a :exc:`ValueError`." msgstr "" -#: ../../library/email.contentmanager.rst:158 +#: ../../library/email.contentmanager.rst:159 msgid "" "For ``str`` objects, if *cte* is not set use heuristics to determine the " -"most compact encoding." +"most compact encoding. Prior to encoding, :meth:`str.splitlines` is used to " +"normalize all line boundaries, ensuring that each line of the payload is " +"terminated by the current policy's :data:`~email.policy.Policy.linesep` " +"property (even if the original string did not end with one)." msgstr "" -#: ../../library/email.contentmanager.rst:160 +#: ../../library/email.contentmanager.rst:165 +msgid "" +"For ``bytes`` objects, *cte* is taken to be base64 if not set, and the " +"aforementioned newline translation is not performed." +msgstr "" + +#: ../../library/email.contentmanager.rst:167 msgid "" "For :class:`~email.message.EmailMessage`, per :rfc:`2046`, raise an error if " "a *cte* of ``quoted-printable`` or ``base64`` is requested for *subtype* " @@ -236,14 +255,14 @@ msgid "" "For all other values of *subtype*, use ``7bit``." msgstr "" -#: ../../library/email.contentmanager.rst:167 +#: ../../library/email.contentmanager.rst:174 msgid "" "A *cte* of ``binary`` does not actually work correctly yet. The " "``EmailMessage`` object as modified by ``set_content`` is correct, but :" "class:`~email.generator.BytesGenerator` does not serialize it correctly." msgstr "" -#: ../../library/email.contentmanager.rst:172 +#: ../../library/email.contentmanager.rst:179 msgid "" "If *disposition* is set, use it as the value of the :mailheader:`Content-" "Disposition` header. If not specified, and *filename* is specified, add the " @@ -252,37 +271,37 @@ msgid "" "values for *disposition* are ``attachment`` and ``inline``." msgstr "" -#: ../../library/email.contentmanager.rst:179 +#: ../../library/email.contentmanager.rst:186 msgid "" "If *filename* is specified, use it as the value of the ``filename`` " "parameter of the :mailheader:`Content-Disposition` header." msgstr "" -#: ../../library/email.contentmanager.rst:182 +#: ../../library/email.contentmanager.rst:189 msgid "" "If *cid* is specified, add a :mailheader:`Content-ID` header with *cid* as " "its value." msgstr "" -#: ../../library/email.contentmanager.rst:185 +#: ../../library/email.contentmanager.rst:192 msgid "" "If *params* is specified, iterate its ``items`` method and use the resulting " "``(key, value)`` pairs to set additional parameters on the :mailheader:" "`Content-Type` header." msgstr "" -#: ../../library/email.contentmanager.rst:189 +#: ../../library/email.contentmanager.rst:196 msgid "" "If *headers* is specified and is a list of strings of the form ``headername: " "headervalue`` or a list of ``header`` objects (distinguished from strings by " "having a ``name`` attribute), add the headers to *msg*." msgstr "" -#: ../../library/email.contentmanager.rst:196 +#: ../../library/email.contentmanager.rst:203 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../library/email.contentmanager.rst:197 +#: ../../library/email.contentmanager.rst:204 msgid "" "Originally added in 3.4 as a :term:`provisional module `" msgstr "" diff --git a/library/email.encoders.po b/library/email.encoders.po index e4bb39c0b..d6c574a37 100644 --- a/library/email.encoders.po +++ b/library/email.encoders.po @@ -1,31 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:04+0000\n" -"Last-Translator: Rafael Fontenelle , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/email.encoders.rst:2 msgid ":mod:`!email.encoders`: Encoders" -msgstr "" +msgstr ":mod:`!email.encoders`: Codificadores" #: ../../library/email.encoders.rst:7 msgid "**Source code:** :source:`Lib/email/encoders.py`" @@ -37,6 +37,9 @@ msgid "" "the functionality is provided by the *cte* parameter of the :meth:`~email." "message.EmailMessage.set_content` method." msgstr "" +"Este módulo faz parte da API legada de e-mail (``Compat32``). Na nova API, a " +"funcionalidade é fornecida pelo parâmetro *cte* do método :meth:`~email." +"message.EmailMessage.set_content`." #: ../../library/email.encoders.rst:15 msgid "" @@ -45,12 +48,16 @@ msgid "" "sets the content type and CTE header using the *_subtype* and *_charset* " "values passed during the instantiation of that class." msgstr "" +"Este módulo está descontinuado no Python 3. As funções fornecidas aqui não " +"devem ser chamadas explicitamente, pois a classe :class:`~email.mime.text." +"MIMEText` define o tipo de conteúdo e o cabeçalho CTE usando os valores " +"*_subtype* e *_charset* passados durante a instanciação dessa classe." #: ../../library/email.encoders.rst:20 msgid "" "The remaining text in this section is the original documentation of the " "module." -msgstr "" +msgstr "O texto restante nesta seção é a documentação original do módulo." #: ../../library/email.encoders.rst:22 msgid "" @@ -59,6 +66,11 @@ msgid "" "servers. This is especially true for :mimetype:`image/\\*` and :mimetype:" "`text/\\*` type messages containing binary data." msgstr "" +"Ao criar objetos :class:`~email.message.Message` do zero, você " +"frequentemente precisa codificar as cargas úteis para transporte por meio de " +"servidores de e-mail compatíveis. Isso é especialmente verdadeiro para " +"mensagens do tipo :mimetype:`image/\\*` e :mimetype:`text/\\*` contendo " +"dados binários." #: ../../library/email.encoders.rst:27 msgid "" @@ -71,6 +83,15 @@ msgid "" "They should also set the :mailheader:`Content-Transfer-Encoding` header as " "appropriate." msgstr "" +"O pacote :mod:`email` fornece alguns codificadores convenientes em seu " +"módulo :mod:`~email.encoders`. Esses codificadores são realmente usados " +"pelos construtores de classe :class:`~email.mime.audio.MIMEAudio` e :class:" +"`~email.mime.image.MIMEImage` para fornecer codificações padrão. Todas as " +"funções de codificador recebem exatamente um argumento, o objeto de mensagem " +"a ser codificado. Eles geralmente extraem a carga útil, codificam-na e " +"redefinem a carga útil para esse valor recém-codificado. Eles também devem " +"definir o cabeçalho :mailheader:`Content-Transfer-Encoding` conforme " +"apropriado." #: ../../library/email.encoders.rst:35 msgid "" @@ -78,10 +99,13 @@ msgid "" "must be applied to individual subparts instead, and will raise a :exc:" "`TypeError` if passed a message whose type is multipart." msgstr "" +"Observe que essas funções não são significativas para uma mensagem " +"multiparte. Elas devem ser aplicadas a subpartes individuais, e levantarão " +"um :exc:`TypeError` se for passada uma mensagem cujo tipo seja multiparte." #: ../../library/email.encoders.rst:39 msgid "Here are the encoding functions provided:" -msgstr "" +msgstr "Aqui estão as funções de codificação fornecidas:" #: ../../library/email.encoders.rst:44 msgid "" @@ -90,6 +114,10 @@ msgid "" "good encoding to use when most of your payload is normal printable data, but " "contains a few unprintable characters." msgstr "" +"Codifica a carga útil em formato quoted-printable e define o cabeçalho :" +"mailheader:`Content-Transfer-Encoding` como ``quoted-printable`` [#]_. Esta " +"é uma boa codificação para usar quando a maior parte da sua carga útil é de " +"dados imprimíveis normais, mas contém alguns caracteres não imprimíveis." #: ../../library/email.encoders.rst:52 msgid "" @@ -99,6 +127,11 @@ msgid "" "form than quoted-printable. The drawback of base64 encoding is that it " "renders the text non-human readable." msgstr "" +"Codifica a carga útil em formato base64 e define o cabeçalho :mailheader:" +"`Content-Transfer-Encoding` para ``base64``. Esta é uma boa codificação para " +"usar quando a maior parte da sua carga útil é de dados não imprimíveis, pois " +"é um formato mais compacto do que quoted-printable. A desvantagem da " +"codificação base64 é que ela torna o texto não legível por humanos." #: ../../library/email.encoders.rst:61 msgid "" @@ -106,12 +139,17 @@ msgid "" "mailheader:`Content-Transfer-Encoding` header to either ``7bit`` or ``8bit`` " "as appropriate, based on the payload data." msgstr "" +"Na verdade, isso não modifica a carga útil da mensagem, mas define o " +"cabeçalho :mailheader:`Content-Transfer-Encoding` para ``7bit`` ou ``8bit``, " +"conforme apropriado, com base nos dados da carga útil." #: ../../library/email.encoders.rst:68 msgid "" "This does nothing; it doesn't even set the :mailheader:`Content-Transfer-" "Encoding` header." msgstr "" +"Isso não faz nada; nem mesmo define o cabeçalho :mailheader:`Content-" +"Transfer-Encoding`." #: ../../library/email.encoders.rst:72 msgid "Footnotes" @@ -122,3 +160,5 @@ msgid "" "Note that encoding with :meth:`encode_quopri` also encodes all tabs and " "space characters in the data." msgstr "" +"Observe que a codificação com :meth:`encode_quopri` também codifica todos os " +"caracteres de tabulação e espaço nos dados." diff --git a/library/email.errors.po b/library/email.errors.po index 308b3ac2f..724901ab9 100644 --- a/library/email.errors.po +++ b/library/email.errors.po @@ -1,32 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Flávio Neves, 2022 -# Rafael Fontenelle , 2022 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: Rafael Fontenelle , 2022\n" +"POT-Creation-Date: 2025-03-07 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/email.errors.rst:2 msgid ":mod:`!email.errors`: Exception and Defect classes" -msgstr "" +msgstr ":mod:`!email.errors`: Classes de Exceção e Defeito." #: ../../library/email.errors.rst:7 msgid "**Source code:** :source:`Lib/email/errors.py`" @@ -77,40 +76,31 @@ msgstr "Descontinuado e não mais usado." #: ../../library/email.errors.rst:48 msgid "" -"Raised when a payload is added to a :class:`~email.message.Message` object " -"using :meth:`add_payload`, but the payload is already a scalar and the " -"message's :mailheader:`Content-Type` main type is not either :mimetype:" -"`multipart` or missing. :exc:`MultipartConversionError` multiply inherits " -"from :exc:`MessageError` and the built-in :exc:`TypeError`." -msgstr "" - -#: ../../library/email.errors.rst:54 -msgid "" -"Since :meth:`Message.add_payload` is deprecated, this exception is rarely " -"raised in practice. However the exception may also be raised if the :meth:" -"`~email.message.Message.attach` method is called on an instance of a class " -"derived from :class:`~email.mime.nonmultipart.MIMENonMultipart` (e.g. :class:" -"`~email.mime.image.MIMEImage`)." +"Raised if the :meth:`~email.message.Message.attach` method is called on an " +"instance of a class derived from :class:`~email.mime.nonmultipart." +"MIMENonMultipart` (e.g. :class:`~email.mime.image.MIMEImage`). :exc:" +"`MultipartConversionError` multiply inherits from :exc:`MessageError` and " +"the built-in :exc:`TypeError`." msgstr "" -#: ../../library/email.errors.rst:64 +#: ../../library/email.errors.rst:58 msgid "" "Raised when an error occurs when the :mod:`~email.generator` outputs headers." msgstr "" -#: ../../library/email.errors.rst:70 +#: ../../library/email.errors.rst:64 msgid "" "This is the base class for all defects found when parsing email messages. It " "is derived from :exc:`ValueError`." msgstr "" -#: ../../library/email.errors.rst:75 +#: ../../library/email.errors.rst:69 msgid "" "This is the base class for all defects found when parsing email headers. It " "is derived from :exc:`MessageDefect`." msgstr "" -#: ../../library/email.errors.rst:78 +#: ../../library/email.errors.rst:72 msgid "" "Here is the list of the defects that the :class:`~email.parser.FeedParser` " "can find while parsing messages. Note that the defects are added to the " @@ -120,90 +110,84 @@ msgid "" "not." msgstr "" -#: ../../library/email.errors.rst:84 +#: ../../library/email.errors.rst:78 msgid "" "All defect classes are subclassed from :class:`email.errors.MessageDefect`." msgstr "" -#: ../../library/email.errors.rst:86 +#: ../../library/email.errors.rst:82 msgid "" -":class:`NoBoundaryInMultipartDefect` -- A message claimed to be a multipart, " -"but had no :mimetype:`boundary` parameter." +"A message claimed to be a multipart, but had no :mimetype:`boundary` " +"parameter." msgstr "" -#: ../../library/email.errors.rst:89 +#: ../../library/email.errors.rst:87 msgid "" -":class:`StartBoundaryNotFoundDefect` -- The start boundary claimed in the :" -"mailheader:`Content-Type` header was never found." +"The start boundary claimed in the :mailheader:`Content-Type` header was " +"never found." msgstr "" #: ../../library/email.errors.rst:92 msgid "" -":class:`CloseBoundaryNotFoundDefect` -- A start boundary was found, but no " -"corresponding close boundary was ever found." +"A start boundary was found, but no corresponding close boundary was ever " +"found." msgstr "" -#: ../../library/email.errors.rst:97 -msgid "" -":class:`FirstHeaderLineIsContinuationDefect` -- The message had a " -"continuation line as its first header line." +#: ../../library/email.errors.rst:99 +msgid "The message had a continuation line as its first header line." msgstr "" -#: ../../library/email.errors.rst:100 -msgid "" -":class:`MisplacedEnvelopeHeaderDefect` - A \"Unix From\" header was found in " -"the middle of a header block." +#: ../../library/email.errors.rst:103 +msgid "A \"Unix From\" header was found in the middle of a header block." msgstr "" -#: ../../library/email.errors.rst:103 +#: ../../library/email.errors.rst:107 msgid "" -":class:`MissingHeaderBodySeparatorDefect` - A line was found while parsing " -"headers that had no leading white space but contained no ':'. Parsing " -"continues assuming that the line represents the first line of the body." +"A line was found while parsing headers that had no leading white space but " +"contained no ':'. Parsing continues assuming that the line represents the " +"first line of the body." msgstr "" -#: ../../library/email.errors.rst:109 +#: ../../library/email.errors.rst:115 msgid "" -":class:`MalformedHeaderDefect` -- A header was found that was missing a " -"colon, or was otherwise malformed." +"A header was found that was missing a colon, or was otherwise malformed." msgstr "" -#: ../../library/email.errors.rst:112 +#: ../../library/email.errors.rst:117 msgid "This defect has not been used for several Python versions." msgstr "" -#: ../../library/email.errors.rst:115 +#: ../../library/email.errors.rst:122 msgid "" -":class:`MultipartInvariantViolationDefect` -- A message claimed to be a :" -"mimetype:`multipart`, but no subparts were found. Note that when a message " -"has this defect, its :meth:`~email.message.Message.is_multipart` method may " -"return ``False`` even though its content type claims to be :mimetype:" -"`multipart`." +"A message claimed to be a :mimetype:`multipart`, but no subparts were found. " +"Note that when a message has this defect, its :meth:`~email.message.Message." +"is_multipart` method may return ``False`` even though its content type " +"claims to be :mimetype:`multipart`." msgstr "" -#: ../../library/email.errors.rst:120 +#: ../../library/email.errors.rst:129 msgid "" -":class:`InvalidBase64PaddingDefect` -- When decoding a block of base64 " -"encoded bytes, the padding was not correct. Enough padding is added to " -"perform the decode, but the resulting decoded bytes may be invalid." +"When decoding a block of base64 encoded bytes, the padding was not correct. " +"Enough padding is added to perform the decode, but the resulting decoded " +"bytes may be invalid." msgstr "" -#: ../../library/email.errors.rst:124 +#: ../../library/email.errors.rst:135 msgid "" -":class:`InvalidBase64CharactersDefect` -- When decoding a block of base64 " -"encoded bytes, characters outside the base64 alphabet were encountered. The " -"characters are ignored, but the resulting decoded bytes may be invalid." +"When decoding a block of base64 encoded bytes, characters outside the base64 " +"alphabet were encountered. The characters are ignored, but the resulting " +"decoded bytes may be invalid." msgstr "" -#: ../../library/email.errors.rst:128 +#: ../../library/email.errors.rst:141 msgid "" -":class:`InvalidBase64LengthDefect` -- When decoding a block of base64 " -"encoded bytes, the number of non-padding base64 characters was invalid (1 " -"more than a multiple of 4). The encoded block was kept as-is." +"When decoding a block of base64 encoded bytes, the number of non-padding " +"base64 characters was invalid (1 more than a multiple of 4). The encoded " +"block was kept as-is." msgstr "" -#: ../../library/email.errors.rst:132 +#: ../../library/email.errors.rst:147 msgid "" -":class:`InvalidDateDefect` -- When decoding an invalid or unparsable date " -"field. The original value is kept as-is." +"When decoding an invalid or unparsable date field. The original value is " +"kept as-is." msgstr "" diff --git a/library/email.examples.po b/library/email.examples.po index e03703666..f022fa8cd 100644 --- a/library/email.examples.po +++ b/library/email.examples.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-04-11 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -45,6 +44,55 @@ msgstr "" "Primeiro, vamos ver como criar e enviar uma mensagem de texto simples (tanto " "o conteúdo do texto quanto os endereços podem conter caracteres Unicode):" +#: ../../library/email.examples.rst:12 +msgid "" +"# Import smtplib for the actual sending function\n" +"import smtplib\n" +"\n" +"# Import the email modules we'll need\n" +"from email.message import EmailMessage\n" +"\n" +"# Open the plain text file whose name is in textfile for reading.\n" +"with open(textfile) as fp:\n" +" # Create a text/plain message\n" +" msg = EmailMessage()\n" +" msg.set_content(fp.read())\n" +"\n" +"# me == the sender's email address\n" +"# you == the recipient's email address\n" +"msg['Subject'] = f'The contents of {textfile}'\n" +"msg['From'] = me\n" +"msg['To'] = you\n" +"\n" +"# Send the message via our own SMTP server.\n" +"s = smtplib.SMTP('localhost')\n" +"s.send_message(msg)\n" +"s.quit()\n" +msgstr "" +"# Importa smtplib para a função de envio\n" +"import smtplib\n" +"\n" +"# Importa os módulos de email que precisamos\n" +"from email.message import EmailMessage\n" +"\n" +"# Abre o arquivo de texto simples cujo nome está em arquivo texto para " +"leitura.\n" +"with open(textfile) as fp:\n" +" # Create a text/plain message\n" +" msg = EmailMessage()\n" +" msg.set_content(fp.read())\n" +"\n" +"# me == o endereço de e-mail do remetente\n" +"# you == o endereço de e-mail do destinatário\n" +"msg['Subject'] = f'The contents of {textfile}'\n" +"msg['From'] = me\n" +"msg['To'] = you\n" +"\n" +"# Envia a mensagem via nosso próprio servidor SMTP.\n" +"s = smtplib.SMTP('localhost')\n" +"s.send_message(msg)\n" +"s.quit()\n" + #: ../../library/email.examples.rst:15 msgid "" "Parsing :rfc:`822` headers can easily be done by the using the classes from " @@ -53,6 +101,62 @@ msgstr "" "A análise dos cabeçalhos :rfc:`822` pode ser feita facilmente usando as " "classes do módulo :mod:`~email.parser`:" +#: ../../library/email.examples.rst:18 +msgid "" +"# Import the email modules we'll need\n" +"#from email.parser import BytesParser\n" +"from email.parser import Parser\n" +"from email.policy import default\n" +"\n" +"# If the e-mail headers are in a file, uncomment these two lines:\n" +"# with open(messagefile, 'rb') as fp:\n" +"# headers = BytesParser(policy=default).parse(fp)\n" +"\n" +"# Or for parsing headers in a string (this is an uncommon operation), use:\n" +"headers = Parser(policy=default).parsestr(\n" +" 'From: Foo Bar \\n'\n" +" 'To: \\n'\n" +" 'Subject: Test message\\n'\n" +" '\\n'\n" +" 'Body would go here\\n')\n" +"\n" +"# Now the header items can be accessed as a dictionary:\n" +"print('To: {}'.format(headers['to']))\n" +"print('From: {}'.format(headers['from']))\n" +"print('Subject: {}'.format(headers['subject']))\n" +"\n" +"# You can also access the parts of the addresses:\n" +"print('Recipient username: {}'.format(headers['to'].addresses[0].username))\n" +"print('Sender name: {}'.format(headers['from'].addresses[0].display_name))\n" +msgstr "" +"# Importa os módulos de email que precisamos\n" +"#from email.parser import BytesParser\n" +"from email.parser import Parser\n" +"from email.policy import default\n" +"\n" +"# Se os cabeçalhos de e-mal estão em um arquivo, descomente essas duas " +"linhas:\n" +"# with open(messagefile, 'rb') as fp:\n" +"# headers = BytesParser(policy=default).parse(fp)\n" +"\n" +"# Ou para análise de cabeçalhos em uma string (essa é uma operação comum), " +"use:\n" +"headers = Parser(policy=default).parsestr(\n" +" 'From: Foo Bar \\n'\n" +" 'To: \\n'\n" +" 'Subject: Test message\\n'\n" +" '\\n'\n" +" 'Body would go here\\n')\n" +"\n" +"# Agora os itens de cabeçalho podem ser acessadas como um dicionário:\n" +"print('To: {}'.format(headers['to']))\n" +"print('From: {}'.format(headers['from']))\n" +"print('Subject: {}'.format(headers['subject']))\n" +"\n" +"# Você também pode acessar as partes dos endereços:\n" +"print('Recipient username: {}'.format(headers['to'].addresses[0].username))\n" +"print('Sender name: {}'.format(headers['from'].addresses[0].display_name))\n" + #: ../../library/email.examples.rst:21 msgid "" "Here's an example of how to send a MIME message containing a bunch of family " @@ -61,6 +165,62 @@ msgstr "" "Aqui está um exemplo de como enviar uma mensagem MIME contendo várias fotos " "de família que podem estar em um diretório:" +#: ../../library/email.examples.rst:24 +msgid "" +"# Import smtplib for the actual sending function.\n" +"import smtplib\n" +"\n" +"# Here are the email package modules we'll need.\n" +"from email.message import EmailMessage\n" +"\n" +"# Create the container email message.\n" +"msg = EmailMessage()\n" +"msg['Subject'] = 'Our family reunion'\n" +"# me == the sender's email address\n" +"# family = the list of all recipients' email addresses\n" +"msg['From'] = me\n" +"msg['To'] = ', '.join(family)\n" +"msg.preamble = 'You will not see this in a MIME-aware mail reader.\\n'\n" +"\n" +"# Open the files in binary mode. You can also omit the subtype\n" +"# if you want MIMEImage to guess it.\n" +"for file in pngfiles:\n" +" with open(file, 'rb') as fp:\n" +" img_data = fp.read()\n" +" msg.add_attachment(img_data, maintype='image',\n" +" subtype='png')\n" +"\n" +"# Send the email via our own SMTP server.\n" +"with smtplib.SMTP('localhost') as s:\n" +" s.send_message(msg)\n" +msgstr "" +"# Importa smtplib para a função de envio.\n" +"import smtplib\n" +"\n" +"# Aqui estão os módulos de pacotes de e-mail que precisamos.\n" +"from email.message import EmailMessage\n" +"\n" +"# Cria a contêiner da mensagem de e-mail.\n" +"msg = EmailMessage()\n" +"msg['Subject'] = 'Our family reunion'\n" +"# me == o endereço de e-mail do remetente\n" +"# family = a lista dos endereços de e-mail de todos os destinatários\n" +"msg['From'] = me\n" +"msg['To'] = ', '.join(family)\n" +"msg.preamble = 'You will not see this in a MIME-aware mail reader.\\n'\n" +"\n" +"# Abre os arquivos no modo binário. Você também pode omitir\n" +"# o subtipo se você quiser que MIMEImage adivinhe.\n" +"for file in pngfiles:\n" +" with open(file, 'rb') as fp:\n" +" img_data = fp.read()\n" +" msg.add_attachment(img_data, maintype='image',\n" +" subtype='png')\n" +"\n" +"# Envia o e-mail por meio de nosso próprio servidor SMTP.\n" +"with smtplib.SMTP('localhost') as s:\n" +" s.send_message(msg)\n" + #: ../../library/email.examples.rst:27 msgid "" "Here's an example of how to send the entire contents of a directory as an " @@ -69,6 +229,177 @@ msgstr "" "Aqui está um exemplo de como enviar todo o conteúdo de um diretório como uma " "mensagem de e-mail: [1]_" +#: ../../library/email.examples.rst:30 +msgid "" +"#!/usr/bin/env python3\n" +"\n" +"\"\"\"Send the contents of a directory as a MIME message.\"\"\"\n" +"\n" +"import os\n" +"import smtplib\n" +"# For guessing MIME type based on file name extension\n" +"import mimetypes\n" +"\n" +"from argparse import ArgumentParser\n" +"\n" +"from email.message import EmailMessage\n" +"from email.policy import SMTP\n" +"\n" +"\n" +"def main():\n" +" parser = ArgumentParser(description=\"\"\"\\\n" +"Send the contents of a directory as a MIME message.\n" +"Unless the -o option is given, the email is sent by forwarding to your " +"local\n" +"SMTP server, which then does the normal delivery process. Your local " +"machine\n" +"must be running an SMTP server.\n" +"\"\"\")\n" +" parser.add_argument('-d', '--directory',\n" +" help=\"\"\"Mail the contents of the specified " +"directory,\n" +" otherwise use the current directory. Only the " +"regular\n" +" files in the directory are sent, and we don't " +"recurse to\n" +" subdirectories.\"\"\")\n" +" parser.add_argument('-o', '--output',\n" +" metavar='FILE',\n" +" help=\"\"\"Print the composed message to FILE " +"instead of\n" +" sending the message to the SMTP server.\"\"\")\n" +" parser.add_argument('-s', '--sender', required=True,\n" +" help='The value of the From: header (required)')\n" +" parser.add_argument('-r', '--recipient', required=True,\n" +" action='append', metavar='RECIPIENT',\n" +" default=[], dest='recipients',\n" +" help='A To: header value (at least one required)')\n" +" args = parser.parse_args()\n" +" directory = args.directory\n" +" if not directory:\n" +" directory = '.'\n" +" # Create the message\n" +" msg = EmailMessage()\n" +" msg['Subject'] = f'Contents of directory {os.path.abspath(directory)}'\n" +" msg['To'] = ', '.join(args.recipients)\n" +" msg['From'] = args.sender\n" +" msg.preamble = 'You will not see this in a MIME-aware mail reader.\\n'\n" +"\n" +" for filename in os.listdir(directory):\n" +" path = os.path.join(directory, filename)\n" +" if not os.path.isfile(path):\n" +" continue\n" +" # Guess the content type based on the file's extension. Encoding\n" +" # will be ignored, although we should check for simple things like\n" +" # gzip'd or compressed files.\n" +" ctype, encoding = mimetypes.guess_file_type(path)\n" +" if ctype is None or encoding is not None:\n" +" # No guess could be made, or the file is encoded (compressed), " +"so\n" +" # use a generic bag-of-bits type.\n" +" ctype = 'application/octet-stream'\n" +" maintype, subtype = ctype.split('/', 1)\n" +" with open(path, 'rb') as fp:\n" +" msg.add_attachment(fp.read(),\n" +" maintype=maintype,\n" +" subtype=subtype,\n" +" filename=filename)\n" +" # Now send or store the message\n" +" if args.output:\n" +" with open(args.output, 'wb') as fp:\n" +" fp.write(msg.as_bytes(policy=SMTP))\n" +" else:\n" +" with smtplib.SMTP('localhost') as s:\n" +" s.send_message(msg)\n" +"\n" +"\n" +"if __name__ == '__main__':\n" +" main()\n" +msgstr "" +"#!/usr/bin/env python3\n" +"\n" +"\"\"\"Envia o conteúdo de um diretório como uma mensagem MIME.\"\"\"\n" +"\n" +"import os\n" +"import smtplib\n" +"# Para adivinhar o tipo MIME com base na extensão do nome do arquivo\n" +"import mimetypes\n" +"\n" +"from argparse import ArgumentParser\n" +"\n" +"from email.message import EmailMessage\n" +"from email.policy import SMTP\n" +"\n" +"\n" +"def main():\n" +" parser = ArgumentParser(description=\"\"\"\\\n" +"Envia o conteúdo de um diretório como uma mensagem MIME.\n" +"A menos que a opção -o seja informada, o e-mail será enviado por\n" +"meio de encaminhamento para o seu servidor SMTP local, que então\n" +"realiza o processo de entrega normal. Sua máquina local deve estar\n" +"executando um servidor SMTP.\n" +"\"\"\")\n" +" parser.add_argument('-d', '--directory',\n" +" help=\"\"\"Mail the contents of the specified " +"directory,\n" +" otherwise use the current directory. Only the " +"regular\n" +" files in the directory are sent, and we don't " +"recurse to\n" +" subdirectories.\"\"\")\n" +" parser.add_argument('-o', '--output',\n" +" metavar='FILE',\n" +" help=\"\"\"Print the composed message to FILE " +"instead of\n" +" sending the message to the SMTP server.\"\"\")\n" +" parser.add_argument('-s', '--sender', required=True,\n" +" help='The value of the From: header (required)')\n" +" parser.add_argument('-r', '--recipient', required=True,\n" +" action='append', metavar='RECIPIENT',\n" +" default=[], dest='recipients',\n" +" help='A To: header value (at least one required)')\n" +" args = parser.parse_args()\n" +" directory = args.directory\n" +" if not directory:\n" +" directory = '.'\n" +" # Cria a mensagem\n" +" msg = EmailMessage()\n" +" msg['Subject'] = f'Contents of directory {os.path.abspath(directory)}'\n" +" msg['To'] = ', '.join(args.recipients)\n" +" msg['From'] = args.sender\n" +" msg.preamble = 'You will not see this in a MIME-aware mail reader.\\n'\n" +"\n" +" for filename in os.listdir(directory):\n" +" path = os.path.join(directory, filename)\n" +" if not os.path.isfile(path):\n" +" continue\n" +" # Adivinhe o tipo de conteúdo com base na extensão do arquivo.\n" +" # A codificação será ignorada, embora devamos verificar coisas\n" +" # simples como arquivos compactados ou compactados com gzip.\n" +" ctype, encoding = mimetypes.guess_file_type(path)\n" +" if ctype is None or encoding is not None:\n" +" # Não foi possível fazer nenhuma suposição, ou o arquivo está\n" +" # codificado (compactado), então use um tipo genérico de\n" +" # conjunto de bits.\n" +" ctype = 'application/octet-stream'\n" +" maintype, subtype = ctype.split('/', 1)\n" +" with open(path, 'rb') as fp:\n" +" msg.add_attachment(fp.read(),\n" +" maintype=maintype,\n" +" subtype=subtype,\n" +" filename=filename)\n" +" # Agora envia ou armazena a mensagem\n" +" if args.output:\n" +" with open(args.output, 'wb') as fp:\n" +" fp.write(msg.as_bytes(policy=SMTP))\n" +" else:\n" +" with smtplib.SMTP('localhost') as s:\n" +" s.send_message(msg)\n" +"\n" +"\n" +"if __name__ == '__main__':\n" +" main()\n" + #: ../../library/email.examples.rst:33 msgid "" "Here's an example of how to unpack a MIME message like the one above, into a " @@ -77,6 +408,119 @@ msgstr "" "Aqui está um exemplo de como desempacotar uma mensagem MIME, como a acima, " "para um diretório de arquivos:" +#: ../../library/email.examples.rst:36 +msgid "" +"#!/usr/bin/env python3\n" +"\n" +"\"\"\"Unpack a MIME message into a directory of files.\"\"\"\n" +"\n" +"import os\n" +"import email\n" +"import mimetypes\n" +"\n" +"from email.policy import default\n" +"\n" +"from argparse import ArgumentParser\n" +"\n" +"\n" +"def main():\n" +" parser = ArgumentParser(description=\"\"\"\\\n" +"Unpack a MIME message into a directory of files.\n" +"\"\"\")\n" +" parser.add_argument('-d', '--directory', required=True,\n" +" help=\"\"\"Unpack the MIME message into the named\n" +" directory, which will be created if it doesn't " +"already\n" +" exist.\"\"\")\n" +" parser.add_argument('msgfile')\n" +" args = parser.parse_args()\n" +"\n" +" with open(args.msgfile, 'rb') as fp:\n" +" msg = email.message_from_binary_file(fp, policy=default)\n" +"\n" +" try:\n" +" os.mkdir(args.directory)\n" +" except FileExistsError:\n" +" pass\n" +"\n" +" counter = 1\n" +" for part in msg.walk():\n" +" # multipart/* are just containers\n" +" if part.get_content_maintype() == 'multipart':\n" +" continue\n" +" # Applications should really sanitize the given filename so that an\n" +" # email message can't be used to overwrite important files\n" +" filename = part.get_filename()\n" +" if not filename:\n" +" ext = mimetypes.guess_extension(part.get_content_type())\n" +" if not ext:\n" +" # Use a generic bag-of-bits extension\n" +" ext = '.bin'\n" +" filename = f'part-{counter:03d}{ext}'\n" +" counter += 1\n" +" with open(os.path.join(args.directory, filename), 'wb') as fp:\n" +" fp.write(part.get_payload(decode=True))\n" +"\n" +"\n" +"if __name__ == '__main__':\n" +" main()\n" +msgstr "" +"#!/usr/bin/env python3\n" +"\n" +"\"\"\"Desempacota uma mensagem MIME em um diretório de arquivos.\"\"\"\n" +"\n" +"import os\n" +"import email\n" +"import mimetypes\n" +"\n" +"from email.policy import default\n" +"\n" +"from argparse import ArgumentParser\n" +"\n" +"\n" +"def main():\n" +" parser = ArgumentParser(description=\"\"\"\\\n" +"Desempacota uma mensagem MIME em um diretório de arquivos.\n" +"\"\"\")\n" +" parser.add_argument('-d', '--directory', required=True,\n" +" help=\"\"\"Unpack the MIME message into the named\n" +" directory, which will be created if it doesn't " +"already\n" +" exist.\"\"\")\n" +" parser.add_argument('msgfile')\n" +" args = parser.parse_args()\n" +"\n" +" with open(args.msgfile, 'rb') as fp:\n" +" msg = email.message_from_binary_file(fp, policy=default)\n" +"\n" +" try:\n" +" os.mkdir(args.directory)\n" +" except FileExistsError:\n" +" pass\n" +"\n" +" counter = 1\n" +" for part in msg.walk():\n" +" # multipart/* são apenas contêineres\n" +" if part.get_content_maintype() == 'multipart':\n" +" continue\n" +" # Os aplicativos realmente devem higienizar o nome de arquivo\n" +" # fornecido para que uma mensagem de e-mail não possa ser\n" +" # usada para substituir arquivos importantes\n" +" filename = part.get_filename()\n" +" if not filename:\n" +" ext = mimetypes.guess_extension(part.get_content_type())\n" +" if not ext:\n" +" # Usa uma extensão genérica de conjunto de bits\n" +" ext = '.bin'\n" +" filename = f'part-{counter:03d}{ext}'\n" +" counter += 1\n" +" with open(os.path.join(args.directory, filename), 'wb') as fp:\n" +" fp.write(part.get_payload(decode=True))\n" +"\n" +"\n" +"if __name__ == '__main__':\n" +" main()\n" + #: ../../library/email.examples.rst:39 msgid "" "Here's an example of how to create an HTML message with an alternative plain " @@ -89,6 +533,126 @@ msgstr "" "interessantes, incluímos uma imagem relacionada na parte html e salvamos uma " "cópia do que vamos enviar para o disco, assim como enviamos." +#: ../../library/email.examples.rst:44 +msgid "" +"#!/usr/bin/env python3\n" +"\n" +"import smtplib\n" +"\n" +"from email.message import EmailMessage\n" +"from email.headerregistry import Address\n" +"from email.utils import make_msgid\n" +"\n" +"# Create the base text message.\n" +"msg = EmailMessage()\n" +"msg['Subject'] = \"Pourquoi pas des asperges pour ce midi ?\"\n" +"msg['From'] = Address(\"Pepé Le Pew\", \"pepe\", \"example.com\")\n" +"msg['To'] = (Address(\"Penelope Pussycat\", \"penelope\", \"example.com\"),\n" +" Address(\"Fabrette Pussycat\", \"fabrette\", \"example.com\"))\n" +"msg.set_content(\"\"\"\\\n" +"Salut!\n" +"\n" +"Cette recette [1] sera sûrement un très bon repas.\n" +"\n" +"[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718\n" +"\n" +"--Pepé\n" +"\"\"\")\n" +"\n" +"# Add the html version. This converts the message into a multipart/" +"alternative\n" +"# container, with the original text message as the first part and the new " +"html\n" +"# message as the second part.\n" +"asparagus_cid = make_msgid()\n" +"msg.add_alternative(\"\"\"\\\n" +"\n" +" \n" +" \n" +"

Salut!

\n" +"

Cette\n" +" \n" +" recette\n" +" sera sûrement un très bon repas.\n" +"

\n" +" \n" +" \n" +"\n" +"\"\"\".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')\n" +"# note that we needed to peel the <> off the msgid for use in the html.\n" +"\n" +"# Now add the related image to the html part.\n" +"with open(\"roasted-asparagus.jpg\", 'rb') as img:\n" +" msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',\n" +" cid=asparagus_cid)\n" +"\n" +"# Make a local copy of what we are going to send.\n" +"with open('outgoing.msg', 'wb') as f:\n" +" f.write(bytes(msg))\n" +"\n" +"# Send the message via local SMTP server.\n" +"with smtplib.SMTP('localhost') as s:\n" +" s.send_message(msg)\n" +msgstr "" +"#!/usr/bin/env python3\n" +"\n" +"import smtplib\n" +"\n" +"from email.message import EmailMessage\n" +"from email.headerregistry import Address\n" +"from email.utils import make_msgid\n" +"\n" +"# Cria a mensagem texto base.\n" +"msg = EmailMessage()\n" +"msg['Subject'] = \"Pourquoi pas des asperges pour ce midi ?\"\n" +"msg['From'] = Address(\"Pepé Le Pew\", \"pepe\", \"example.com\")\n" +"msg['To'] = (Address(\"Penelope Pussycat\", \"penelope\", \"example.com\"),\n" +" Address(\"Fabrette Pussycat\", \"fabrette\", \"example.com\"))\n" +"msg.set_content(\"\"\"\\\n" +"Salut!\n" +"\n" +"Cette recette [1] sera sûrement un très bon repas.\n" +"\n" +"[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718\n" +"\n" +"--Pepé\n" +"\"\"\")\n" +"\n" +"# Adiciona a versão HTML. Isso converte a mensagem em um contêiner\n" +"# multiparte/alternativo, com a mensagem de texto original como a primeira\n" +"# parte e a nova mensagem HTML como a segunda parte.\n" +"asparagus_cid = make_msgid()\n" +"msg.add_alternative(\"\"\"\\\n" +"\n" +" \n" +" \n" +"

Salut!

\n" +"

Cette\n" +" \n" +" recette\n" +" sera sûrement un très bon repas.\n" +"

\n" +" \n" +" \n" +"\n" +"\"\"\".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')\n" +"# observe que precisamos remover o <> do msgid para usar no html.\n" +"\n" +"# Agora adiciona a imagem relacionada à parte html.\n" +"with open(\"roasted-asparagus.jpg\", 'rb') as img:\n" +" msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',\n" +" cid=asparagus_cid)\n" +"\n" +"# Agora adiciona a imagem relacionada à parte html.\n" +"with open('outgoing.msg', 'wb') as f:\n" +" f.write(bytes(msg))\n" +"\n" +"# Envia a mensagem via servidor SMTP local.\n" +"with smtplib.SMTP('localhost') as s:\n" +" s.send_message(msg)\n" + #: ../../library/email.examples.rst:47 msgid "" "If we were sent the message from the last example, here is one way we could " @@ -97,10 +661,121 @@ msgstr "" "Se nos fosse enviada a mensagem do último exemplo, aqui está uma maneira de " "processá-la:" +#: ../../library/email.examples.rst:50 +msgid "" +"import os\n" +"import sys\n" +"import tempfile\n" +"import mimetypes\n" +"import webbrowser\n" +"\n" +"# Import the email modules we'll need\n" +"from email import policy\n" +"from email.parser import BytesParser\n" +"\n" +"\n" +"def magic_html_parser(html_text, partfiles):\n" +" \"\"\"Return safety-sanitized html linked to partfiles.\n" +"\n" +" Rewrite the href=\"cid:....\" attributes to point to the filenames in " +"partfiles.\n" +" Though not trivial, this should be possible using html.parser.\n" +" \"\"\"\n" +" raise NotImplementedError(\"Add the magic needed\")\n" +"\n" +"\n" +"# In a real program you'd get the filename from the arguments.\n" +"with open('outgoing.msg', 'rb') as fp:\n" +" msg = BytesParser(policy=policy.default).parse(fp)\n" +"\n" +"# Now the header items can be accessed as a dictionary, and any non-ASCII " +"will\n" +"# be converted to unicode:\n" +"print('To:', msg['to'])\n" +"print('From:', msg['from'])\n" +"print('Subject:', msg['subject'])\n" +"\n" +"# If we want to print a preview of the message content, we can extract " +"whatever\n" +"# the least formatted payload is and print the first three lines. Of " +"course,\n" +"# if the message has no plain text part printing the first three lines of " +"html\n" +"# is probably useless, but this is just a conceptual example.\n" +"simplest = msg.get_body(preferencelist=('plain', 'html'))\n" +"print()\n" +"print(''.join(simplest.get_content().splitlines(keepends=True)[:3]))\n" +"\n" +"ans = input(\"View full message?\")\n" +"if ans.lower()[0] == 'n':\n" +" sys.exit()\n" +"\n" +"# We can extract the richest alternative in order to display it:\n" +"richest = msg.get_body()\n" +"partfiles = {}\n" +"if richest['content-type'].maintype == 'text':\n" +" if richest['content-type'].subtype == 'plain':\n" +" for line in richest.get_content().splitlines():\n" +" print(line)\n" +" sys.exit()\n" +" elif richest['content-type'].subtype == 'html':\n" +" body = richest\n" +" else:\n" +" print(\"Don't know how to display {}\".format(richest." +"get_content_type()))\n" +" sys.exit()\n" +"elif richest['content-type'].content_type == 'multipart/related':\n" +" body = richest.get_body(preferencelist=('html'))\n" +" for part in richest.iter_attachments():\n" +" fn = part.get_filename()\n" +" if fn:\n" +" extension = os.path.splitext(part.get_filename())[1]\n" +" else:\n" +" extension = mimetypes.guess_extension(part.get_content_type())\n" +" with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as " +"f:\n" +" f.write(part.get_content())\n" +" # again strip the <> to go from email form of cid to html form.\n" +" partfiles[part['content-id'][1:-1]] = f.name\n" +"else:\n" +" print(\"Don't know how to display {}\".format(richest." +"get_content_type()))\n" +" sys.exit()\n" +"with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:\n" +" f.write(magic_html_parser(body.get_content(), partfiles))\n" +"webbrowser.open(f.name)\n" +"os.remove(f.name)\n" +"for fn in partfiles.values():\n" +" os.remove(fn)\n" +"\n" +"# Of course, there are lots of email messages that could break this simple\n" +"# minded program, but it will handle the most common ones.\n" +msgstr "" + #: ../../library/email.examples.rst:52 msgid "Up to the prompt, the output from the above is:" msgstr "Até o prompt, a saída do comando acima é:" +#: ../../library/email.examples.rst:54 +msgid "" +"To: Penelope Pussycat , Fabrette Pussycat " +"\n" +"From: Pepé Le Pew \n" +"Subject: Pourquoi pas des asperges pour ce midi ?\n" +"\n" +"Salut!\n" +"\n" +"Cette recette [1] sera sûrement un très bon repas." +msgstr "" +"To: Penelope Pussycat , Fabrette Pussycat " +"\n" +"From: Pepé Le Pew \n" +"Subject: Pourquoi pas des asperges pour ce midi ?\n" +"\n" +"Salut!\n" +"\n" +"Cette recette [1] sera sûrement un très bon repas." + #: ../../library/email.examples.rst:66 msgid "Footnotes" msgstr "Notas de rodapé" diff --git a/library/email.generator.po b/library/email.generator.po index 884b1a9cd..d48805058 100644 --- a/library/email.generator.po +++ b/library/email.generator.po @@ -1,31 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 02:33+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: Rafael Fontenelle , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/email.generator.rst:2 msgid ":mod:`!email.generator`: Generating MIME documents" -msgstr "" +msgstr ":mod:`!email.generator`: Geração de documentos MIME" #: ../../library/email.generator.rst:7 msgid "**Source code:** :source:`Lib/email/generator.py`" @@ -40,6 +40,12 @@ msgid "" "structure and producing a serialized representation is the job of the " "generator classes." msgstr "" +"Uma das tarefas mais comuns é gerar a versão plana (serializada) da mensagem " +"de e-mail representada por uma estrutura de objeto de mensagem. Você " +"precisará fazer isso se quiser enviar sua mensagem via :meth:`smtplib.SMTP." +"sendmail` ou exibir a mensagem no console. A tarefa das classes geradoras é " +"pegar uma estrutura de objeto de mensagem e produzir uma representação " +"serializada." #: ../../library/email.generator.rst:18 msgid "" @@ -57,6 +63,19 @@ msgid "" "changes to the :class:`~email.message.EmailMessage` object as defaults are " "filled in.)" msgstr "" +"Assim como no módulo :mod:`email.parser`, você não está limitado à " +"funcionalidade do gerador integrado; você mesmo pode criar um do zero. No " +"entanto, o gerador integrado sabe como gerar a maioria dos e-mails em " +"conformidade com os padrões, deve lidar perfeitamente com mensagens de e-" +"mail MIME e não MIME e foi projetado para que as operações de análise e " +"geração orientadas a bytes sejam inversas, presumindo que a mesma :mod:" +"`~email.policy` não transformadora seja usada para ambas. Ou seja, analisar " +"o fluxo de bytes serializado por meio da classe :class:`~email.parser." +"BytesParser` e, em seguida, regenerar o fluxo de bytes serializado usando :" +"class:`BytesGenerator` deve produzir uma saída idêntica à entrada [#]_. (Por " +"outro lado, usar o gerador em um :class:`~email.message.EmailMessage` " +"construído pelo programa pode resultar em alterações no objeto :class:" +"`~email.message.EmailMessage` à medida que os padrões são preenchidos.)" #: ../../library/email.generator.rst:32 msgid "" @@ -67,6 +86,13 @@ msgid "" "Content Transfer Encoding techniques for encoding email messages for " "transport over channels that are not \"8 bit clean\"." msgstr "" +"A classe :class:`Generator` pode ser usada para simplificar uma mensagem em " +"uma representação serializada de texto (em oposição a binária), mas como o " +"Unicode não pode representar dados binários diretamente, a mensagem é " +"necessariamente transformada em algo que contém apenas caracteres ASCII, " +"usando as técnicas de codificação de transferência de conteúdo RFC de e-mail " +"padrão para codificar mensagens de e-mail para transporte em canais que não " +"são \"limpos de 8 bits\"." #: ../../library/email.generator.rst:39 msgid "" @@ -74,6 +100,9 @@ msgid "" "`Generator` disables header folding for message parts of type ``multipart/" "signed`` and all subparts." msgstr "" +"Para acomodar o processamento reproduzível de mensagens assinadas por " +"SMIME, :class:`Generator` desabilita a dobragem de cabeçalho para partes de " +"mensagens do tipo ``multipart/signed`` e todas as subpartes." #: ../../library/email.generator.rst:47 msgid "" @@ -82,6 +111,11 @@ msgid "" "to the :meth:`write` method, to the :term:`file-like object` *outfp*. " "*outfp* must support a ``write`` method that accepts binary data." msgstr "" +"Retorna um objeto :class:`BytesGenerator` que gravará qualquer mensagem " +"fornecida ao método :meth:`flatten`, ou qualquer texto codificado " +"surrogateescape fornecido ao método :meth:`write`, no :term:`objeto arquivo " +"ou similar` *outfp*. *outfp* deve oferecer suporte a um método ``write`` que " +"aceite dados binários." #: ../../library/email.generator.rst:52 ../../library/email.generator.rst:153 msgid "" @@ -95,6 +129,15 @@ msgid "" "`WHY THE CONTENT-LENGTH FORMAT IS BAD `_)." msgstr "" +"Se o *mangle_from_* opcional for ``True``, coloca um caractere ``>`` na " +"frente de qualquer linha no corpo que comece com a string exata ``\"From " +"\"``, ou seja, ``From`` seguido por um espaço no início de uma linha. " +"*mangle_from_* assume por padrão o valor da configuração :attr:`~email." +"policy.Policy.mangle_from_` da *policy* (que é ``True`` para a política :" +"data:`~email.policy.compat32` e ``False`` para todas as outras). " +"*mangle_from_* deve ser usado quando as mensagens são armazenadas no formato " +"mbox do Unix (consulte :mod:`mailbox` e `WHY THE CONTENT-LENGTH FORMAT IS " +"BAD `_)." #: ../../library/email.generator.rst:62 ../../library/email.generator.rst:163 msgid "" @@ -103,6 +146,10 @@ msgid "" "*manheaderlen* is ``None`` (the default), wrap headers and other message " "lines according to the *policy* settings." msgstr "" +"Se *maxheaderlen* não for ``None``, redobra quaisquer linhas de cabeçalho " +"maiores que *maxheaderlen* ou, se for ``0``, não redobra nenhum cabeçalho. " +"Se *manheaderlen* for ``None`` (o padrão), redobra os cabeçalhos e outras " +"linhas de mensagem de acordo com as configurações da *policy*." #: ../../library/email.generator.rst:67 ../../library/email.generator.rst:168 msgid "" @@ -112,16 +159,24 @@ msgid "" "object passed to ``flatten`` to control the message generation. See :mod:" "`email.policy` for details on what *policy* controls." msgstr "" +"Se *policy* for especificado, usa essa política para controlar a geração de " +"mensagens. Se *policy* for ``None`` (o padrão), usa a política associada ao " +"objeto :class:`~email.message.Message` ou :class:`~email.message." +"EmailMessage` passado para ``flatten`` para controlar a geração de " +"mensagens. Consulte :mod:`email.policy` para obter detalhes sobre o que " +"*policy* controla." #: ../../library/email.generator.rst:75 ../../library/email.generator.rst:174 msgid "Added the *policy* keyword." -msgstr "" +msgstr "Adicionada o argumento nomeado *policy*." #: ../../library/email.generator.rst:77 ../../library/email.generator.rst:176 msgid "" "The default behavior of the *mangle_from_* and *maxheaderlen* parameters is " "to follow the policy." msgstr "" +"O comportamento padrão dos parâmetros *mangle_from_* e *maxheaderlen* é " +"seguir a política." #: ../../library/email.generator.rst:83 msgid "" @@ -129,6 +184,9 @@ msgid "" "*msg* to the output file specified when the :class:`BytesGenerator` instance " "was created." msgstr "" +"Exibe a representação textual da estrutura do objeto de mensagem com raiz em " +"*msg* no arquivo de saída especificado quando a instância :class:" +"`BytesGenerator` foi criada." #: ../../library/email.generator.rst:87 msgid "" @@ -145,6 +203,19 @@ msgid "" "bytes in headers using the MIME ``unknown-8bit`` character set, thus " "rendering them RFC-compliant." msgstr "" +"Se a opção :mod:`~email.policy` :attr:`~email.policy.Policy.cte_type` for " +"``8bit`` (o padrão), copia todos os cabeçalhos da mensagem original " +"analisada que não tenham sido modificados para a saída, com todos os bytes " +"com o bit mais alto definido reproduzidos como no original, e preserva a :" +"mailheader:`Content-Transfer-Encoding` não ASCII de quaisquer partes do " +"corpo que os contenham. Se ``cte_type`` for ``7bit``, converte os bytes com " +"o bit mais alto definido, conforme necessário, usando uma :mailheader:" +"`Content-Transfer-Encoding` compatível com ASCII. Ou seja, transforma partes " +"com :mailheader:`Content-Transfer-Encoding` não ASCII (:mailheader:`Content-" +"Transfer-Encoding: 8bit`) em um :mailheader:`Content-Transfer-Encoding` " +"compatível com ASCII e codifica bytes não ASCII inválidos para RFC em " +"cabeçalhos usando o conjunto de caracteres MIME ``unknown-8bit``, tornando-" +"os compatíveis com RFC." #: ../../library/email.generator.rst:104 ../../library/email.generator.rst:197 msgid "" @@ -154,6 +225,12 @@ msgid "" "header, craft a standard one. The default is ``False``. Note that for " "subparts, no envelope header is ever printed." msgstr "" +"Se *unixfrom* for ``True``, exibe o delimitador de cabeçalho de envelope " +"usado pelo formato de caixa de correio Unix (consulte :mod:`mailbox`) antes " +"do primeiro dos cabeçalhos :rfc:`5322` do objeto de mensagem raiz. Se o " +"objeto raiz não tiver cabeçalho de envelope, crie um padrão. O padrão é " +"``False``. Observe que, para subpartes, nenhum cabeçalho de envelope é " +"exibido." #: ../../library/email.generator.rst:110 ../../library/email.generator.rst:203 msgid "" @@ -161,12 +238,17 @@ msgid "" "the lines of the flattened message. If *linesep* is ``None`` (the default), " "use the value specified in the *policy*." msgstr "" +"Se *linesep* não for ``None``, usa-o como caractere separador entre todas as " +"linhas da mensagem simplificada. Se *linesep* for ``None`` (o padrão), usa o " +"valor especificado na *policy*." #: ../../library/email.generator.rst:119 msgid "" "Return an independent clone of this :class:`BytesGenerator` instance with " "the exact same option settings, and *fp* as the new *outfp*." msgstr "" +"Retorna um clone independente desta instância :class:`BytesGenerator` com " +"exatamente as mesmas configurações de opção e *fp* como o novo *outfp*." #: ../../library/email.generator.rst:125 msgid "" @@ -174,6 +256,9 @@ msgid "" "handler, and pass it to the *write* method of the *outfp* passed to the :" "class:`BytesGenerator`'s constructor." msgstr "" +"Codifica *s* usando o codec ``ASCII`` e o tratador de erros " +"``surrogateescape`` e passa-o para o método *write* do *outfp* passado ao " +"construtor :class:`BytesGenerator`." #: ../../library/email.generator.rst:130 msgid "" @@ -183,6 +268,11 @@ msgid "" "of a serialized binary representation of a message object. For more detail, " "see :mod:`email.message`." msgstr "" +"Para facilitar, :class:`~email.message.EmailMessage` fornece os métodos :" +"meth:`~email.message.EmailMessage.as_bytes` e ``bytes(aMessage)`` (também " +"conhecidos como :meth:`~email.message.EmailMessage.__bytes__`), que " +"simplificam a geração de uma representação binária serializada de um objeto " +"de mensagem. Para mais detalhes, consulte :mod:`email.message`." #: ../../library/email.generator.rst:137 msgid "" @@ -194,6 +284,14 @@ msgid "" "not \"8 bit clean\". In other words, most applications will want to be " "using :class:`BytesGenerator`, and not :class:`Generator`." msgstr "" +"Como strings não podem representar dados binários, a classe :class:" +"`Generator` deve converter quaisquer dados binários em qualquer mensagem que " +"ela nivele para um formato compatível com ASCII, convertendo-os para um :" +"mailheader:`Content-Transfer_Encoding` compatível com ASCII. Usando a " +"terminologia dos RFCs de e-mail, você pode pensar nisso como :class:" +"`Generator` serializando para um fluxo de E/S que não é \"limpo em 8 bits\". " +"Em outras palavras, a maioria das aplicações usará :class:`BytesGenerator`, " +"e não :class:`Generator`." #: ../../library/email.generator.rst:148 msgid "" @@ -202,6 +300,10 @@ msgid "" "method, to the :term:`file-like object` *outfp*. *outfp* must support a " "``write`` method that accepts string data." msgstr "" +"Retorna um objeto :class:`Generator` que gravará qualquer mensagem fornecida " +"ao método :meth:`flatten`, ou qualquer texto fornecido ao método :meth:" +"`write`, no :term:`objeto arquivo ou similar` *outfp*. *outfp* deve oferecer " +"suporte a um método ``write`` que aceite dados string." #: ../../library/email.generator.rst:182 msgid "" @@ -209,6 +311,9 @@ msgid "" "*msg* to the output file specified when the :class:`Generator` instance was " "created." msgstr "" +"Exibe a representação textual da estrutura do objeto de mensagem com raiz em " +"*msg* no arquivo de saída especificado quando a instância :class:`Generator` " +"foi criada." #: ../../library/email.generator.rst:186 msgid "" @@ -222,18 +327,32 @@ msgid "" "Encoding`, and encode RFC-invalid non-ASCII bytes in headers using the MIME " "``unknown-8bit`` character set, thus rendering them RFC-compliant." msgstr "" +"Se a opção :mod:`~email.policy` :attr:`~email.policy.Policy.cte_type` for " +"``8bit``, gera a mensagem como se a opção estivesse definida como ``7bit``. " +"(Isso é necessário porque strings não podem representar bytes não ASCII.) " +"Converte quaisquer bytes com o bit mais alto definido, conforme necessário, " +"usando uma :mailheader:`Content-Transfer-Encoding` compatível com ASCII. Ou " +"seja, transforma partes com :mailheader:`Content-Transfer-Encoding` não " +"ASCII (:mailheader:`Content-Transfer-Encoding: 8bit`) em um :mailheader:" +"`Content-Transfer-Encoding` compatível com ASCII e codifica bytes não ASCII " +"inválidos para RFC em cabeçalhos usando o conjunto de caracteres MIME " +"``unknown-8bit``, tornando-os compatíveis com RFC." #: ../../library/email.generator.rst:209 msgid "" "Added support for re-encoding ``8bit`` message bodies, and the *linesep* " "argument." msgstr "" +"Adicionado suporte para recodificação de corpos de mensagens ``8bit`` e o " +"argumento *linesep*." #: ../../library/email.generator.rst:216 msgid "" "Return an independent clone of this :class:`Generator` instance with the " "exact same options, and *fp* as the new *outfp*." msgstr "" +"Retorna um clone independente desta instância :class:`Generator` com " +"exatamente as mesmas opções e *fp* como o novo *outfp*." #: ../../library/email.generator.rst:222 msgid "" @@ -241,6 +360,9 @@ msgid "" "`Generator`'s constructor. This provides just enough file-like API for :" "class:`Generator` instances to be used in the :func:`print` function." msgstr "" +"Escreve *s* no método *write* do *outfp* passado ao construtor de :class:" +"`Generator`. Isso fornece API arquivo ou similar suficiente para que " +"instâncias de :class:`Generator` sejam usadas na função :func:`print`." #: ../../library/email.generator.rst:228 msgid "" @@ -250,6 +372,11 @@ msgid "" "of a formatted string representation of a message object. For more detail, " "see :mod:`email.message`." msgstr "" +"Para facilitar, :class:`~email.message.EmailMessage` fornece os métodos :" +"meth:`~email.message.EmailMessage.as_string` e ``str(aMessage)`` (também " +"conhecidos como :meth:`~email.message.EmailMessage.__str__`), que " +"simplificam a geração de uma representação de string formatada de um objeto " +"de mensagem. Para mais detalhes, consulte :mod:`email.message`." #: ../../library/email.generator.rst:235 msgid "" @@ -259,6 +386,11 @@ msgid "" "represented in the output stream by a string derived from a template filled " "in with information about the part." msgstr "" +"O módulo :mod:`email.generator` também fornece uma classe derivada, :class:" +"`DecodedGenerator`, que é como a classe base :class:`Generator`, exceto que " +"as partes não- :mimetype:`text` não são serializadas, mas são representadas " +"no fluxo de saída por uma string derivada de um modelo preenchido com " +"informações sobre a parte." #: ../../library/email.generator.rst:244 msgid "" @@ -269,54 +401,66 @@ msgid "" "*fmt* using information from the part and print the resulting filled-in " "string." msgstr "" +"Age como :class:`Generator`, exceto que para qualquer subparte da mensagem " +"passada para :meth:`Generator.flatten`, se a subparte for do tipo principal :" +"mimetype:`text`, exibe a carga decodificada da subparte e, se o tipo " +"principal não for :mimetype:`text`, em vez de exibi-la, preenche a string " +"*fmt* usando informações da parte e exibe a string preenchida resultante." #: ../../library/email.generator.rst:251 msgid "" "To fill in *fmt*, execute ``fmt % part_info``, where ``part_info`` is a " "dictionary composed of the following keys and values:" msgstr "" +"Para preencher *fmt*, executa ``fmt % part_info``, onde ``part_info`` é um " +"dicionário composto pelas seguintes chaves e valores:" #: ../../library/email.generator.rst:254 msgid "``type`` -- Full MIME type of the non-\\ :mimetype:`text` part" -msgstr "" +msgstr "``type`` -- Tipo MIME completo da parte não-\\ :mimetype:`text`" #: ../../library/email.generator.rst:256 msgid "``maintype`` -- Main MIME type of the non-\\ :mimetype:`text` part" -msgstr "" +msgstr "``maintype`` -- Tipo MIME principal da parte não-\\ :mimetype:`text`" #: ../../library/email.generator.rst:258 msgid "``subtype`` -- Sub-MIME type of the non-\\ :mimetype:`text` part" -msgstr "" +msgstr "``subtype`` -- Tipo sub-MIME da parte não-\\ :mimetype:`text`" #: ../../library/email.generator.rst:260 msgid "``filename`` -- Filename of the non-\\ :mimetype:`text` part" -msgstr "" +msgstr "``filename`` -- Nome de arquivo da parte não-\\ :mimetype:`text`" #: ../../library/email.generator.rst:262 msgid "" "``description`` -- Description associated with the non-\\ :mimetype:`text` " "part" -msgstr "" +msgstr "``description`` -- Descrição associada à parte não-\\ :mimetype:`text`" #: ../../library/email.generator.rst:264 msgid "" "``encoding`` -- Content transfer encoding of the non-\\ :mimetype:`text` part" msgstr "" +"``encoding`` -- Codificação de transferência de conteúdo da parte não-\\ :" +"mimetype:`text`" #: ../../library/email.generator.rst:266 msgid "If *fmt* is ``None``, use the following default *fmt*:" -msgstr "" +msgstr "Se *fmt* for ``None``, usa o seguinte *fmt* padrão:" #: ../../library/email.generator.rst:268 msgid "" "\"[Non-text (%(type)s) part of message omitted, filename %(filename)s]\"" msgstr "" +"\"[Non-text (%(type)s) part of message omitted, filename %(filename)s]\"" #: ../../library/email.generator.rst:270 msgid "" "Optional *_mangle_from_* and *maxheaderlen* are as with the :class:" "`Generator` base class." msgstr "" +"Os opcionais *_mangle_from_* e *maxheaderlen* são como os da classe base :" +"class:`Generator`." #: ../../library/email.generator.rst:275 msgid "Footnotes" @@ -333,3 +477,11 @@ msgid "" "parsing error recovery. It is a goal to fix these latter edge cases when " "possible." msgstr "" +"Esta instrução presume que você usa a configuração apropriada para " +"``unixfrom`` e que não haja configurações :mod:`email.policy` que exijam " +"ajustes automáticos (por exemplo, :attr:`~email.policy.EmailPolicy." +"refold_source` deve ser ``none``, que *não* é o padrão). Também não é 100% " +"verdadeiro, pois, se a mensagem não estiver em conformidade com os padrões " +"RFC, ocasionalmente informações sobre o texto original exato são perdidas " +"durante a recuperação de erros de análise. O objetivo é corrigir esses " +"últimos casos extremos sempre que possível." diff --git a/library/email.header.po b/library/email.header.po index eab645da1..7af9bb15e 100644 --- a/library/email.header.po +++ b/library/email.header.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-14 17:56+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -46,7 +45,7 @@ msgstr "" msgid "" "The remaining text in this section is the original documentation of the " "module." -msgstr "" +msgstr "O texto restante nesta seção é a documentação original do módulo." #: ../../library/email.header.rst:19 msgid "" @@ -79,6 +78,17 @@ msgid "" "header` module. For example::" msgstr "" +#: ../../library/email.header.rst:40 +msgid "" +">>> from email.message import Message\n" +">>> from email.header import Header\n" +">>> msg = Message()\n" +">>> h = Header('p\\xf6stal', 'iso-8859-1')\n" +">>> msg['Subject'] = h\n" +">>> msg.as_string()\n" +"'Subject: =?iso-8859-1?q?p=F6stal?=\\n\\n'" +msgstr "" + #: ../../library/email.header.rst:50 msgid "" "Notice here how we wanted the :mailheader:`Subject` field to contain a non-" @@ -273,6 +283,13 @@ msgstr "" msgid "Here's an example::" msgstr "Aqui está um exemplo::" +#: ../../library/email.header.rst:188 +msgid "" +">>> from email.header import decode_header\n" +">>> decode_header('=?iso-8859-1?q?p=F6stal?=')\n" +"[(b'p\\xf6stal', 'iso-8859-1')]" +msgstr "" + #: ../../library/email.header.rst:195 msgid "" "Create a :class:`Header` instance from a sequence of pairs as returned by :" diff --git a/library/email.headerregistry.po b/library/email.headerregistry.po index b1a5a3d01..f7572d3af 100644 --- a/library/email.headerregistry.po +++ b/library/email.headerregistry.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -131,6 +129,10 @@ msgid "" "method is called as follows::" msgstr "" +#: ../../library/email.headerregistry.rst:94 +msgid "parse(string, kwds)" +msgstr "" + #: ../../library/email.headerregistry.rst:96 msgid "" "``kwds`` is a dictionary containing one pre-initialized key, ``defects``. " @@ -152,6 +154,13 @@ msgid "" "``BaseHeader`` itself. Such an ``init`` method should look like this::" msgstr "" +#: ../../library/email.headerregistry.rst:110 +msgid "" +"def init(self, /, *args, **kw):\n" +" self._myattr = kw.pop('myattr')\n" +" super().init(*args, **kw)" +msgstr "" + #: ../../library/email.headerregistry.rst:114 msgid "" "That is, anything extra that the specialized class puts in to the ``kwds`` " @@ -215,6 +224,10 @@ msgid "" "``datetime`` according to the :rfc:`5322` rules; that is, it is set to::" msgstr "" +#: ../../library/email.headerregistry.rst:163 +msgid "email.utils.format_datetime(self.datetime)" +msgstr "" + #: ../../library/email.headerregistry.rst:165 msgid "" "When creating a ``DateHeader``, *value* may be :class:`~datetime.datetime` " @@ -222,6 +235,10 @@ msgid "" "does what one would expect::" msgstr "" +#: ../../library/email.headerregistry.rst:169 +msgid "msg['Date'] = datetime(2011, 7, 15, 21)" +msgstr "" + #: ../../library/email.headerregistry.rst:171 msgid "" "Because this is a naive ``datetime`` it will be interpreted as a UTC " @@ -230,6 +247,10 @@ msgid "" "mod:`~email.utils` module::" msgstr "" +#: ../../library/email.headerregistry.rst:176 +msgid "msg['Date'] = utils.localtime()" +msgstr "" + #: ../../library/email.headerregistry.rst:178 msgid "" "This example sets the date header to the current time and date using the " @@ -374,7 +395,7 @@ msgid "" "class. When *use_default_map* is ``True`` (the default), the standard " "mapping of header names to classes is copied in to the registry during " "initialization. *base_class* is always the last class in the generated " -"class's ``__bases__`` list." +"class's :class:`~type.__bases__` list." msgstr "" #: ../../library/email.headerregistry.rst:322 @@ -555,10 +576,18 @@ msgid "" "address is::" msgstr "" +#: ../../library/email.headerregistry.rst:380 +msgid "[display_name] " +msgstr "" + #: ../../library/email.headerregistry.rst:382 msgid "or::" msgstr "ou::" +#: ../../library/email.headerregistry.rst:384 +msgid "username@domain" +msgstr "" + #: ../../library/email.headerregistry.rst:386 msgid "" "where each part must conform to specific syntax rules spelled out in :rfc:" @@ -616,6 +645,10 @@ msgid "" "address group is::" msgstr "" +#: ../../library/email.headerregistry.rst:432 +msgid "display_name: [address-list];" +msgstr "" + #: ../../library/email.headerregistry.rst:434 msgid "" "As a convenience for processing lists of addresses that consist of a mixture " diff --git a/library/email.iterators.po b/library/email.iterators.po index 23c4bd612..ffdd74b51 100644 --- a/library/email.iterators.po +++ b/library/email.iterators.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -40,8 +40,8 @@ msgid "" msgstr "" "A iteração sobre uma árvore de objetos de mensagem é bastante fácil com o " "método :meth:`Message.walk `. O módulo :mod:" -"`email.iterators` fornece algumas iterações úteis de nível superior sobre as " -"árvores de objetos de mensagens." +"`email.iterators` fornece algumas iterações úteis de nível mais alto sobre " +"as árvores de objetos de mensagens." #: ../../library/email.iterators.rst:19 msgid "" @@ -110,6 +110,44 @@ msgstr "" "Imprime uma representação recuada dos tipos de conteúdo da estrutura do " "objeto de mensagem. Por exemplo:" +#: ../../library/email.iterators.rst:57 +msgid "" +">>> msg = email.message_from_file(somefile)\n" +">>> _structure(msg)\n" +"multipart/mixed\n" +" text/plain\n" +" text/plain\n" +" multipart/digest\n" +" message/rfc822\n" +" text/plain\n" +" message/rfc822\n" +" text/plain\n" +" message/rfc822\n" +" text/plain\n" +" message/rfc822\n" +" text/plain\n" +" message/rfc822\n" +" text/plain\n" +" text/plain" +msgstr "" +">>> msg = email.message_from_file(algum_arquivo)\n" +">>> _structure(msg)\n" +"multipart/mixed\n" +" text/plain\n" +" text/plain\n" +" multipart/digest\n" +" message/rfc822\n" +" text/plain\n" +" message/rfc822\n" +" text/plain\n" +" message/rfc822\n" +" text/plain\n" +" message/rfc822\n" +" text/plain\n" +" message/rfc822\n" +" text/plain\n" +" text/plain" + #: ../../library/email.iterators.rst:81 msgid "" "Optional *fp* is a file-like object to print the output to. It must be " diff --git a/library/email.message.po b/library/email.message.po index f1496fb04..95ef1f550 100644 --- a/library/email.message.po +++ b/library/email.message.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -171,7 +170,7 @@ msgstr "" #: ../../library/email.message.rst:127 msgid "" -"Equivalent to :meth:`.as_bytes()`. Allows ``bytes(msg)`` to produce a bytes " +"Equivalent to :meth:`.as_bytes`. Allows ``bytes(msg)`` to produce a bytes " "object containing the serialized message." msgstr "" @@ -236,6 +235,12 @@ msgid "" "Used for the ``in`` operator. For example::" msgstr "" +#: ../../library/email.message.rst:185 +msgid "" +"if 'message-id' in myMessage:\n" +" print('Message-ID:', myMessage['message-id'])" +msgstr "" + #: ../../library/email.message.rst:191 msgid "" "Return the value of the named header field. *name* does not include the " @@ -270,6 +275,12 @@ msgid "" "present in the message with field name *name*, delete the field first, e.g.::" msgstr "" +#: ../../library/email.message.rst:213 +msgid "" +"del msg['subject']\n" +"msg['subject'] = 'Python roolz!'" +msgstr "" + #: ../../library/email.message.rst:216 msgid "" "If the :mod:`policy ` defines certain headers to be unique (as " @@ -353,14 +364,28 @@ msgstr "" msgid "Here is an example::" msgstr "Aqui está um exemplo::" +#: ../../library/email.message.rst:289 +msgid "msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')" +msgstr "" + #: ../../library/email.message.rst:291 msgid "This will add a header that looks like ::" msgstr "" +#: ../../library/email.message.rst:293 +msgid "Content-Disposition: attachment; filename=\"bud.gif\"" +msgstr "Content-Disposition: attachment; filename=\"bud.gif\"" + #: ../../library/email.message.rst:295 msgid "An example of the extended interface with non-ASCII characters::" msgstr "" +#: ../../library/email.message.rst:297 +msgid "" +"msg.add_header('Content-Disposition', 'attachment',\n" +" filename=('iso-8859-1', '', 'Fußballer.ppt'))" +msgstr "" + #: ../../library/email.message.rst:303 msgid "" "Replace a header. Replace the first header found in the message that " @@ -568,6 +593,19 @@ msgid "" "message structure:" msgstr "" +#: ../../library/email.message.rst:491 +msgid "" +">>> for part in msg.walk():\n" +"... print(part.get_content_type())\n" +"multipart/report\n" +"text/plain\n" +"message/delivery-status\n" +"text/plain\n" +"text/plain\n" +"message/rfc822\n" +"text/plain" +msgstr "" + #: ../../library/email.message.rst:503 msgid "" "``walk`` iterates over the subparts of any part where :meth:`is_multipart` " @@ -576,6 +614,29 @@ msgid "" "``_structure`` debug helper function:" msgstr "" +#: ../../library/email.message.rst:509 +msgid "" +">>> from email.iterators import _structure\n" +">>> for part in msg.walk():\n" +"... print(part.get_content_maintype() == 'multipart',\n" +"... part.is_multipart())\n" +"True True\n" +"False False\n" +"False True\n" +"False False\n" +"False False\n" +"False True\n" +"False False\n" +">>> _structure(msg)\n" +"multipart/report\n" +" text/plain\n" +" message/delivery-status\n" +" text/plain\n" +" text/plain\n" +" message/rfc822\n" +" text/plain" +msgstr "" + #: ../../library/email.message.rst:531 msgid "" "Here the ``message`` parts are not ``multiparts``, but they do contain " diff --git a/library/email.mime.po b/library/email.mime.po index 1530211f4..82a87694f 100644 --- a/library/email.mime.po +++ b/library/email.mime.po @@ -1,31 +1,32 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: Rafael Fontenelle , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/email.mime.rst:2 msgid ":mod:`!email.mime`: Creating email and MIME objects from scratch" msgstr "" +":mod:`!email.mime`:mod:`email.mime`: Criando e-mail e objetos MIME do zero" #: ../../library/email.mime.rst:7 msgid "**Source code:** :source:`Lib/email/mime/`" @@ -54,13 +55,13 @@ msgid "" "convenient interface for slicing-and-dicing MIME messages." msgstr "" "Normalmente, você obtém uma estrutura de objeto de mensagem passando um " -"arquivo ou algum texto para um analisador, que analisa o texto e retorna o " -"objeto de mensagem raiz. No entanto, você também pode criar uma estrutura de " -"mensagem completa do zero, ou até objetos individuais de :class:`~email." -"message.Message` manualmente. De fato, você também pode pegar uma estrutura " -"existente e adicionar novos objetos :class:`~email.message.Message`, movê-" -"los, etc. Isso cria uma interface muito conveniente para fatiar e cortar " -"dados de mensagens MIME." +"arquivo ou algum texto para um analisador sintático, que analisa o texto e " +"retorna o objeto de mensagem raiz. No entanto, você também pode criar uma " +"estrutura de mensagem completa do zero, ou até objetos individuais de :class:" +"`~email.message.Message` manualmente. De fato, você também pode pegar uma " +"estrutura existente e adicionar novos objetos :class:`~email.message." +"Message`, movê-los, etc. Isso cria uma interface muito conveniente para " +"fatiar e cortar dados de mensagens MIME." #: ../../library/email.mime.rst:24 msgid "" @@ -213,6 +214,9 @@ msgid "" "from the keyword arguments, or passed into the *_params* argument, which is " "a keyword dictionary." msgstr "" +"Parâmetros adicionais para o cabeçalho :mailheader:`Content-Type` são " +"retirados dos argumentos nomeados ou passados para o argumento *_params*, " +"que é um dicionário." #: ../../library/email.mime.rst:113 msgid "Module: :mod:`email.mime.application`" @@ -226,6 +230,11 @@ msgid "" "application data. Optional *_subtype* specifies the MIME subtype and " "defaults to :mimetype:`octet-stream`." msgstr "" +"Uma subclasse de :class:`~email.mime.nonmultipart.MIMENonMultipart`, a " +"classe :class:`MIMEApplication` é usada para representar objetos de mensagem " +"MIME do tipo principal :mimetype:`application`. *_data* contém os bytes para " +"os dados brutos da aplicação. O *_subtype* opcional especifica o subtipo " +"MIME e o padrão é :mimetype:`octet-stream`." #: ../../library/email.mime.rst:121 msgid "" @@ -267,6 +276,15 @@ msgid "" "argument. If the minor type could not be guessed and *_subtype* was not " "given, then :exc:`TypeError` is raised." msgstr "" +"Uma subclasse de :class:`~email.mime.nonmultipart.MIMENonMultipart`, a " +"classe :class:`MIMEAudio` é usada para criar objetos de mensagem MIME do " +"tipo principal :mimetype:`audio`. *_audiodata* contpem os bytes para os " +"dados brutos de áudio. Se esses dados puderem ser decodificados como au, " +"wav, aiff ou aifc, então o subtipo será automaticamente incluído no " +"cabeçalho :mailheader:`Content-Type`. Caso contrário, você pode especificar " +"explicitamente o subtipo de áudio por meio do argumento *_subtype*. Se o " +"tipo menor não pôde ser adivinhado e *_subtype* não foi fornecido, então um " +"exceção :exc:`TypeError` é levantada." #: ../../library/email.mime.rst:155 msgid "" @@ -304,6 +322,16 @@ msgid "" "the minor type could not be guessed and *_subtype* was not given, then :exc:" "`TypeError` is raised." msgstr "" +"Uma subclasse de :class:`~email.mime.nonmultipart.MIMENonMultipart`, a " +"classe :class:`MIMEImage` é usada para criar objetos de mensagem MIME do " +"tipo principal :mimetype:`image`. *_imagedata* contém os bytes para os dados " +"de imagem bruta. Se esse tipo de dados puder ser detectado (jpeg, png, gif, " +"tiff, rgb, pbm, pgm, ppm, rast, xbm, bmp, webp e exr tentados), então o " +"subtipo será automaticamente incluído no cabeçalho :mailheader:`Content-" +"Type`. Caso contrário, você pode especificar explicitamente o subtipo de " +"imagem por meio do argumento *_subtype*. Se o tipo secundário não puder ser " +"adivinhado e *_subtype* não for fornecido, então :exc:`TypeError` será " +"levantada." #: ../../library/email.mime.rst:190 msgid "" @@ -316,16 +344,27 @@ msgid "" "object as necessary. The default encoding is base64. See the :mod:`email." "encoders` module for a list of the built-in encoders." msgstr "" +"O *_encoder* opcional é um chamável (ou seja, função) que executará a " +"codificação real dos dados de imagem para transporte. Esse chamável requer " +"um argumento, que é a instância :class:`MIMEImage`. Ele deve usar :meth:" +"`~email.message.Message.get_payload` e :meth:`~email.message.Message." +"set_payload` para alterar a carga útil para a forma codificada. Também deve " +"adicionar :mailheader:`Content-Transfer-Encoding` ou outros cabeçalhos ao " +"objeto de mensagem, conforme necessário. A codificação padrão é base64. Veja " +"o módulo :mod:`email.encoders` para obter uma lista dos codificadores " +"embutidos." #: ../../library/email.mime.rst:202 msgid "" "*_params* are passed straight through to the :class:`~email.mime.base." "MIMEBase` constructor." msgstr "" +"*_params* são passados diretamente para o construtor :class:`~email.mime." +"base.MIMEBase`." #: ../../library/email.mime.rst:212 msgid "Module: :mod:`email.mime.message`" -msgstr "" +msgstr "Módulo: :mod:`email.mime.message`" #: ../../library/email.mime.rst:214 msgid "" @@ -335,12 +374,19 @@ msgid "" "class:`~email.message.Message` (or a subclass thereof), otherwise a :exc:" "`TypeError` is raised." msgstr "" +"Uma subclasse de :class:`~email.mime.nonmultipart.MIMENonMultipart`, a " +"classe :class:`MIMEMessage` é usada para criar objetos MIME do tipo " +"principal :mimetype:`message`. *_msg* é usado como carga útil e deve ser uma " +"instância da classe :class:`~email.message.Message` (ou uma subclasse dela), " +"caso contrário, uma :exc:`TypeError` é levantada." #: ../../library/email.mime.rst:220 msgid "" "Optional *_subtype* sets the subtype of the message; it defaults to :" "mimetype:`rfc822`." msgstr "" +"O opcional *_subtype* define o subtipo da mensagem; o padrão é :mimetype:" +"`rfc822`." #: ../../library/email.mime.rst:232 msgid "Module: :mod:`email.mime.text`" @@ -358,6 +404,15 @@ msgid "" "*_charset* parameter accepts either a string or a :class:`~email.charset." "Charset` instance." msgstr "" +"Uma subclasse de :class:`~email.mime.nonmultipart.MIMENonMultipart`, a " +"classe :class:`MIMEText` é usada para criar objetos MIME do tipo principal :" +"mimetype:`text`. *_text* é a string para a carga útil. *_subtype* é o tipo " +"secundário e o padrão é :mimetype:`plain`. *_charset* é o conjunto de " +"caracteres do texto e é passado como um argumento para o construtor :class:" +"`~email.mime.nonmultipart.MIMENonMultipart`; o padrão é ``us-ascii`` se a " +"string contiver apenas pontos de código ``ascii`` e ``utf-8`` caso " +"contrário. O parâmetro *_charset* aceita uma string ou uma instância :class:" +"`~email.charset.Charset`." #: ../../library/email.mime.rst:244 msgid "" @@ -371,7 +426,18 @@ msgid "" "encode the new payload (and add a new :mailheader:`Content-Transfer-" "Encoding` header)." msgstr "" +"A menos que o argumento *_charset* seja explicitamente definido como " +"``None``, o objeto MIMEText criado terá um cabeçalho :mailheader:`Content-" +"Type` com um parâmetro ``charset`` e um cabeçalho :mailheader:`Content-" +"Transfer-Encoding`. Isso significa que uma chamada ``set_payload`` " +"subsequente não resultará em uma carga útil codificada, mesmo se um charset " +"for passado no comando ``set_payload``. Você pode \"redefinir\" esse " +"comportamento excluindo o cabeçalho ``Content-Transfer-Encoding``, após o " +"qual uma chamada ``set_payload`` codificará automaticamente a nova carga " +"útil (e adicionará um novo cabeçalho :mailheader:`Content-Transfer-" +"Encoding`)." #: ../../library/email.mime.rst:256 msgid "*_charset* also accepts :class:`~email.charset.Charset` instances." msgstr "" +"*_charset* também aceita instâncias de :class:`~email.charset.Charset`." diff --git a/library/email.parser.po b/library/email.parser.po index fbf270e62..5b536e754 100644 --- a/library/email.parser.po +++ b/library/email.parser.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -142,7 +141,7 @@ msgstr "" #: ../../library/email.parser.rst:94 ../../library/email.parser.rst:122 msgid "Added the *policy* keyword." -msgstr "" +msgstr "Adicionada o argumento nomeado *policy*." #: ../../library/email.parser.rst:95 msgid "*_factory* defaults to the policy ``message_factory``." @@ -333,6 +332,12 @@ msgid "" "interactive Python prompt::" msgstr "" +#: ../../library/email.parser.rst:286 +msgid "" +">>> import email\n" +">>> msg = email.message_from_bytes(myBytes)" +msgstr "" + #: ../../library/email.parser.rst:291 msgid "Additional notes" msgstr "" diff --git a/library/email.po b/library/email.po index d744069c4..b605028ad 100644 --- a/library/email.po +++ b/library/email.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Biagioni de Fazio , 2021 -# Rodrigo Neres , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/email.policy.po b/library/email.policy.po index 92ea01fe7..1554b438c 100644 --- a/library/email.policy.po +++ b/library/email.policy.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-10 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -130,6 +127,22 @@ msgid "" "system:" msgstr "" +#: ../../library/email.policy.rst:92 +msgid "" +">>> from email import message_from_binary_file\n" +">>> from email.generator import BytesGenerator\n" +">>> from email import policy\n" +">>> from subprocess import Popen, PIPE\n" +">>> with open('mymsg.txt', 'rb') as f:\n" +"... msg = message_from_binary_file(f, policy=policy.default)\n" +"...\n" +">>> p = Popen(['sendmail', msg['To'].addresses[0]], stdin=PIPE)\n" +">>> g = BytesGenerator(p.stdin, policy=msg.policy.clone(linesep='\\r\\n'))\n" +">>> g.flatten(msg)\n" +">>> p.stdin.close()\n" +">>> rc = p.wait()" +msgstr "" + #: ../../library/email.policy.rst:114 msgid "" "Here we are telling :class:`~email.generator.BytesGenerator` to use the RFC " @@ -147,6 +160,14 @@ msgid "" "line separators for the platform on which it is running::" msgstr "" +#: ../../library/email.policy.rst:125 +msgid "" +">>> import os\n" +">>> with open('converted.txt', 'wb') as f:\n" +"... f.write(msg.as_bytes(policy=msg.policy.clone(linesep=os.linesep)))\n" +"17" +msgstr "" + #: ../../library/email.policy.rst:130 msgid "" "Policy objects can also be combined using the addition operator, producing a " @@ -154,12 +175,31 @@ msgid "" "the summed objects::" msgstr "" +#: ../../library/email.policy.rst:134 +msgid "" +">>> compat_SMTP = policy.compat32.clone(linesep='\\r\\n')\n" +">>> compat_strict = policy.compat32.clone(raise_on_defect=True)\n" +">>> compat_strict_SMTP = compat_SMTP + compat_strict" +msgstr "" + #: ../../library/email.policy.rst:138 msgid "" "This operation is not commutative; that is, the order in which the objects " "are added matters. To illustrate::" msgstr "" +#: ../../library/email.policy.rst:141 +msgid "" +">>> policy100 = policy.compat32.clone(max_line_length=100)\n" +">>> policy80 = policy.compat32.clone(max_line_length=80)\n" +">>> apolicy = policy100 + policy80\n" +">>> apolicy.max_line_length\n" +"80\n" +">>> apolicy = policy80 + policy100\n" +">>> apolicy.max_line_length\n" +"100" +msgstr "" + #: ../../library/email.policy.rst:153 msgid "" "This is the :term:`abstract base class` for all policy classes. It provides " @@ -294,7 +334,7 @@ msgstr "" #: ../../library/email.policy.rst:268 msgid "" "Handle a *defect* found on *obj*. When the email package calls this method, " -"*defect* will always be a subclass of :class:`~email.errors.Defect`." +"*defect* will always be a subclass of :class:`~email.errors.MessageDefect`." msgstr "" #: ../../library/email.policy.rst:272 @@ -307,7 +347,7 @@ msgstr "" #: ../../library/email.policy.rst:279 msgid "" "Register a *defect* on *obj*. In the email package, *defect* will always be " -"a subclass of :class:`~email.errors.Defect`." +"a subclass of :class:`~email.errors.MessageDefect`." msgstr "" #: ../../library/email.policy.rst:282 @@ -652,6 +692,10 @@ msgid "" "strict by writing::" msgstr "" +#: ../../library/email.policy.rst:571 +msgid "somepolicy + policy.strict" +msgstr "" + #: ../../library/email.policy.rst:574 msgid "" "With all of these :class:`EmailPolicies <.EmailPolicy>`, the effective API " diff --git a/library/email.utils.po b/library/email.utils.po index 6ef629c9a..68532aa7e 100644 --- a/library/email.utils.po +++ b/library/email.utils.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Sheila Gomes , 2021 -# Italo Penaforte , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -182,6 +180,24 @@ msgstr "" "Aqui está um exemplo simples que recebe todos os destinatários de uma " "mensagem::" +#: ../../library/email.utils.rst:100 +msgid "" +"from email.utils import getaddresses\n" +"\n" +"tos = msg.get_all('to', [])\n" +"ccs = msg.get_all('cc', [])\n" +"resent_tos = msg.get_all('resent-to', [])\n" +"resent_ccs = msg.get_all('resent-cc', [])\n" +"all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)" +msgstr "" +"from email.utils import getaddresses\n" +"\n" +"tos = msg.get_all('to', [])\n" +"ccs = msg.get_all('cc', [])\n" +"resent_tos = msg.get_all('resent-to', [])\n" +"resent_ccs = msg.get_all('resent-cc', [])\n" +"all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)" + #: ../../library/email.utils.rst:114 msgid "" "Attempts to parse a date according to the rules in :rfc:`2822`. however, " @@ -258,6 +274,10 @@ msgstr "" msgid "Returns a date string as per :rfc:`2822`, e.g.::" msgstr "Retorna uma string de data conforme :rfc:`2822`. Por exemplo::" +#: ../../library/email.utils.rst:160 +msgid "Fri, 09 Nov 2001 01:08:47 -0000" +msgstr "Fri, 09 Nov 2001 01:08:47 -0000" + #: ../../library/email.utils.rst:162 msgid "" "Optional *timeval* if given is a floating-point time value as accepted by :" diff --git a/library/ensurepip.po b/library/ensurepip.po index f79a94f40..c43900383 100644 --- a/library/ensurepip.po +++ b/library/ensurepip.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -84,38 +83,38 @@ msgstr ":pep:`453`: Inicialização explícita de pip em instalações Python" msgid "The original rationale and specification for this module." msgstr "A justificativa e especificação originais para este módulo." -#: ../../includes/wasm-ios-notavail.rst:3 -msgid ":ref:`Availability `: not WASI, not iOS." -msgstr ":ref:`Disponibilidade `: não WAS, não iOS." +#: ../../includes/wasm-mobile-notavail.rst:3 +msgid "Availability" +msgstr "Disponibilidade" -#: ../../includes/wasm-ios-notavail.rst:5 +#: ../../includes/wasm-mobile-notavail.rst:5 msgid "" -"This module does not work or is not available on WebAssembly platforms, or " -"on iOS. See :ref:`wasm-availability` for more information on WASM " -"availability; see :ref:`iOS-availability` for more information on iOS " -"availability." +"This module is not supported on :ref:`mobile platforms ` or :ref:`WebAssembly platforms `." msgstr "" -"Este módulo não funciona ou não está disponível nas plataformas WebAssembly " -"ou iOS. Veja :ref:`wasm-availability` para mais informações sobre a " -"disponibilidade no WASM; veja :ref:`iOS-availability` para mais informações " -"sobre a disponibilidade no iOS." +"Este módulo não tem suporte em :ref:`plataformas móveis ` ou :ref:`plataformas WebAssembly `." #: ../../library/ensurepip.rst:44 msgid "Command line interface" msgstr "Interface de linha de comando" -#: ../../library/ensurepip.rst:46 +#: ../../library/ensurepip.rst:48 msgid "" "The command line interface is invoked using the interpreter's ``-m`` switch." msgstr "" "A interface da linha de comando é chamada usando a opção ``-m`` do " "interpretador." -#: ../../library/ensurepip.rst:48 +#: ../../library/ensurepip.rst:50 msgid "The simplest possible invocation is::" msgstr "A invocação mais simples possível é::" #: ../../library/ensurepip.rst:52 +msgid "python -m ensurepip" +msgstr "python -m ensurepip" + +#: ../../library/ensurepip.rst:54 msgid "" "This invocation will install ``pip`` if it is not already installed, but " "otherwise does nothing. To ensure the installed version of ``pip`` is at " @@ -128,6 +127,10 @@ msgstr "" "opção ``--upgrade``::" #: ../../library/ensurepip.rst:59 +msgid "python -m ensurepip --upgrade" +msgstr "python -m ensurepip --upgrade" + +#: ../../library/ensurepip.rst:61 msgid "" "By default, ``pip`` is installed into the current virtual environment (if " "one is active) or into the system site packages (if there is no active " @@ -139,27 +142,27 @@ msgstr "" "ativo). O local da instalação pode ser controlado através de duas opções " "adicionais de linha de comando:" -#: ../../library/ensurepip.rst:64 +#: ../../library/ensurepip.rst:68 msgid "" -":samp:`--root {dir}`: Installs ``pip`` relative to the given root directory " -"rather than the root of the currently active virtual environment (if any) or " -"the default root for the current Python installation." +"Installs ``pip`` relative to the given root directory rather than the root " +"of the currently active virtual environment (if any) or the default root for " +"the current Python installation." msgstr "" -":samp:`--root {dir}`: Instala ``pip`` em relação ao diretório raiz " -"fornecido, em vez da raiz do ambiente virtual atualmente ativo (se houver) " -"ou a raiz padrão da instalação atual do Python." +"Instala ``pip`` em relação ao diretório raiz fornecido, em vez da raiz do " +"ambiente virtual atualmente ativo (se houver) ou a raiz padrão da instalação " +"atual do Python." -#: ../../library/ensurepip.rst:67 +#: ../../library/ensurepip.rst:74 msgid "" -"``--user``: Installs ``pip`` into the user site packages directory rather " -"than globally for the current Python installation (this option is not " -"permitted inside an active virtual environment)." +"Installs ``pip`` into the user site packages directory rather than globally " +"for the current Python installation (this option is not permitted inside an " +"active virtual environment)." msgstr "" -"``--user``: Instala ``pip`` no diretório de pacotes do site do usuário em " -"vez de globalmente para a instalação atual do Python (essa opção não é " -"permitida dentro de um ambiente virtual ativo)." +"Instala ``pip`` no diretório de pacotes do site do usuário em vez de " +"globalmente para a instalação atual do Python (essa opção não é permitida " +"dentro de um ambiente virtual ativo)." -#: ../../library/ensurepip.rst:71 +#: ../../library/ensurepip.rst:78 msgid "" "By default, the scripts ``pipX`` and ``pipX.Y`` will be installed (where X.Y " "stands for the version of Python used to invoke ``ensurepip``). The scripts " @@ -170,36 +173,36 @@ msgstr "" "instalados podem ser controlados através de duas opções adicionais de linha " "de comando:" -#: ../../library/ensurepip.rst:76 +#: ../../library/ensurepip.rst:85 msgid "" -"``--altinstall``: if an alternate installation is requested, the ``pipX`` " -"script will *not* be installed." +"If an alternate installation is requested, the ``pipX`` script will *not* be " +"installed." msgstr "" -"``--altinstall``: se uma instalação alternativa for solicitada, o script " -"``pipX`` *não* será instalado." +"Se uma instalação alternativa for solicitada, o script ``pipX`` *não* será " +"instalado." -#: ../../library/ensurepip.rst:79 +#: ../../library/ensurepip.rst:90 msgid "" -"``--default-pip``: if a \"default pip\" installation is requested, the " -"``pip`` script will be installed in addition to the two regular scripts." +"If a \"default pip\" installation is requested, the ``pip`` script will be " +"installed in addition to the two regular scripts." msgstr "" -"``--default-pip``: se uma instalação \"pip padrão\" for solicitada, o script " -"``pip`` será instalado junto com os dois scripts comuns." +"Se uma instalação \"pip padrão\" for solicitada, o script ``pip`` será " +"instalado junto com os dois scripts comuns." -#: ../../library/ensurepip.rst:82 +#: ../../library/ensurepip.rst:93 msgid "" "Providing both of the script selection options will trigger an exception." msgstr "Fornecer as duas opções de seleção de script acionará uma exceção." -#: ../../library/ensurepip.rst:86 +#: ../../library/ensurepip.rst:96 msgid "Module API" msgstr "API do módulo" -#: ../../library/ensurepip.rst:88 +#: ../../library/ensurepip.rst:98 msgid ":mod:`ensurepip` exposes two functions for programmatic use:" msgstr "O :mod:`ensurepip` expõe duas funções para uso programático:" -#: ../../library/ensurepip.rst:92 +#: ../../library/ensurepip.rst:102 msgid "" "Returns a string specifying the available version of pip that will be " "installed when bootstrapping an environment." @@ -207,11 +210,11 @@ msgstr "" "Retorna uma string que especifica a versão disponível do pip que será " "instalado ao inicializar um ambiente." -#: ../../library/ensurepip.rst:99 +#: ../../library/ensurepip.rst:109 msgid "Bootstraps ``pip`` into the current or designated environment." msgstr "Inicializa ``pip`` no ambiente atual ou designado." -#: ../../library/ensurepip.rst:101 +#: ../../library/ensurepip.rst:111 msgid "" "*root* specifies an alternative root directory to install relative to. If " "*root* is ``None``, then installation uses the default install location for " @@ -221,7 +224,7 @@ msgstr "" "Se *root* for ``None``, a instalação utilizará o local de instalação padrão " "para o ambiente atual." -#: ../../library/ensurepip.rst:105 +#: ../../library/ensurepip.rst:115 msgid "" "*upgrade* indicates whether or not to upgrade an existing installation of an " "earlier version of ``pip`` to the available version." @@ -229,7 +232,7 @@ msgstr "" "*upgrade* indica se deve ou não atualizar uma instalação existente de uma " "versão anterior do ``pip`` para a versão disponível." -#: ../../library/ensurepip.rst:108 +#: ../../library/ensurepip.rst:118 msgid "" "*user* indicates whether to use the user scheme rather than installing " "globally." @@ -237,7 +240,7 @@ msgstr "" "*user* indica se é necessário usar o esquema do usuário em vez de instalar " "globalmente." -#: ../../library/ensurepip.rst:111 +#: ../../library/ensurepip.rst:121 msgid "" "By default, the scripts ``pipX`` and ``pipX.Y`` will be installed (where X.Y " "stands for the current version of Python)." @@ -245,11 +248,11 @@ msgstr "" "Por padrão, os scripts ``pipX`` e ``pipX.Y`` serão instalados (onde X.Y " "significa a versão atual do Python)." -#: ../../library/ensurepip.rst:114 +#: ../../library/ensurepip.rst:124 msgid "If *altinstall* is set, then ``pipX`` will *not* be installed." msgstr "Se *altinstall* estiver definido, o ``pipX`` *não* será instalado." -#: ../../library/ensurepip.rst:116 +#: ../../library/ensurepip.rst:126 msgid "" "If *default_pip* is set, then ``pip`` will be installed in addition to the " "two regular scripts." @@ -257,12 +260,12 @@ msgstr "" "Se *default_pip* estiver definido, o ``pip`` será instalado além dos dois " "scripts comuns." -#: ../../library/ensurepip.rst:119 +#: ../../library/ensurepip.rst:129 msgid "" "Setting both *altinstall* and *default_pip* will trigger :exc:`ValueError`." msgstr "Definir *altinstall* e *default_pip* acionará :exc:`ValueError`." -#: ../../library/ensurepip.rst:122 +#: ../../library/ensurepip.rst:132 msgid "" "*verbosity* controls the level of output to :data:`sys.stdout` from the " "bootstrapping operation." @@ -270,7 +273,7 @@ msgstr "" "*verbosity* controla o nível de saída para :data:`sys.stdout` da operação de " "inicialização." -#: ../../library/ensurepip.rst:125 +#: ../../library/ensurepip.rst:135 msgid "" "Raises an :ref:`auditing event ` ``ensurepip.bootstrap`` with " "argument ``root``." @@ -278,7 +281,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ensurepip.bootstrap`` com " "o argumento ``root``." -#: ../../library/ensurepip.rst:129 +#: ../../library/ensurepip.rst:139 msgid "" "The bootstrapping process has side effects on both ``sys.path`` and ``os." "environ``. Invoking the command line interface in a subprocess instead " @@ -288,7 +291,7 @@ msgstr "" "environ``. Invocar a interface da linha de comando em um subprocesso permite " "que esses efeitos colaterais sejam evitados." -#: ../../library/ensurepip.rst:135 +#: ../../library/ensurepip.rst:145 msgid "" "The bootstrapping process may install additional modules required by " "``pip``, but other software should not assume those dependencies will always " diff --git a/library/enum.po b/library/enum.po index d79d596b6..91b7b76fe 100644 --- a/library/enum.po +++ b/library/enum.po @@ -1,35 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Hildeberto Abreu Magalhães , 2022 -# Raphael Mendonça, 2022 -# Misael borges , 2022 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/enum.rst:2 msgid ":mod:`!enum` --- Support for enumerations" -msgstr "" +msgstr ":mod:`!enum` --- Suporte a enumerações" #: ../../library/enum.rst:14 msgid "**Source code:** :source:`Lib/enum.py`" @@ -40,48 +36,77 @@ msgid "" "This page contains the API reference information. For tutorial information " "and discussion of more advanced topics, see" msgstr "" -"Esta página contêm informação de referência da API. Para informação tutorial " -"e discussão de tópicos mais avançados, consulte" +"Esta página contêm informação de referência da API. Para tutorial e " +"discussão de tópicos mais avançados, consulte" #: ../../library/enum.rst:21 msgid ":ref:`Basic Tutorial `" -msgstr "" +msgstr ":ref:`Tutorial básico `" #: ../../library/enum.rst:22 msgid ":ref:`Advanced Tutorial `" -msgstr "" +msgstr ":ref:`Tutorial avançado `" #: ../../library/enum.rst:23 msgid ":ref:`Enum Cookbook `" -msgstr "" +msgstr ":ref:`Livro de receitas de enum `" #: ../../library/enum.rst:27 msgid "An enumeration:" -msgstr "" +msgstr "Uma enumeração:" #: ../../library/enum.rst:29 msgid "is a set of symbolic names (members) bound to unique values" msgstr "" +"é um conjunto de nomes simbólicos (membros) vinculados a valores únicos" #: ../../library/enum.rst:30 msgid "" "can be iterated over to return its canonical (i.e. non-alias) members in " "definition order" msgstr "" +"pode ser iterado para retornar seus membros canônicos (ou seja, não " +"incluindo apelidos) na ordem de definição" #: ../../library/enum.rst:32 msgid "uses *call* syntax to return members by value" -msgstr "" +msgstr "usa a sintaxe *call* para retornar membros por valor" #: ../../library/enum.rst:33 msgid "uses *index* syntax to return members by name" -msgstr "" +msgstr "usa a sintaxe *index* para retornar membros por nome" #: ../../library/enum.rst:35 msgid "" "Enumerations are created either by using :keyword:`class` syntax, or by " "using function-call syntax::" msgstr "" +"As enumerações são criadas usando a sintaxe de :keyword:`class` ou usando a " +"sintaxe de chamada de função::" + +#: ../../library/enum.rst:38 +msgid "" +">>> from enum import Enum\n" +"\n" +">>> # class syntax\n" +">>> class Color(Enum):\n" +"... RED = 1\n" +"... GREEN = 2\n" +"... BLUE = 3\n" +"\n" +">>> # functional syntax\n" +">>> Color = Enum('Color', [('RED', 1), ('GREEN', 2), ('BLUE', 3)])" +msgstr "" +">>> from enum import Enum\n" +"\n" +">>> # sintaxe de classe\n" +">>> class Color(Enum):\n" +"... RED = 1\n" +"... GREEN = 2\n" +"... BLUE = 3\n" +"\n" +">>> # sintaxe funcional\n" +">>> Color = Enum('Color', [('RED', 1), ('GREEN', 2), ('BLUE', 3)])" #: ../../library/enum.rst:49 msgid "" @@ -89,26 +114,33 @@ msgid "" "not normal Python classes. See :ref:`How are Enums different? ` for more details." msgstr "" +"Embora possamos usar a sintaxe :keyword:`class` para criar Enums, Enums não " +"são classes Python normais. Veja :ref:`Como Enums são diferentes? ` para mais detalhes." #: ../../library/enum.rst:53 msgid "Nomenclature" -msgstr "" +msgstr "Nomenclatura" #: ../../library/enum.rst:55 msgid "The class :class:`!Color` is an *enumeration* (or *enum*)" -msgstr "" +msgstr "A classe :class:`!Color` é uma *enumeração* (ou *enum*)" #: ../../library/enum.rst:56 msgid "" "The attributes :attr:`!Color.RED`, :attr:`!Color.GREEN`, etc., are " "*enumeration members* (or *members*) and are functionally constants." msgstr "" +"Os atributos :attr:`!Color.RED`, :attr:`!Color.GREEN`, etc., são *membros de " +"enumeração* (ou *membros*) e são constantes funcionalmente." #: ../../library/enum.rst:58 msgid "" "The enum members have *names* and *values* (the name of :attr:`!Color.RED` " "is ``RED``, the value of :attr:`!Color.BLUE` is ``3``, etc.)" msgstr "" +"Os membros enum têm *nomes* e *valores* (o nome de :attr:`!Color.RED` é " +"``RED``, o valor de :attr:`!Color.BLUE` é ``3``, etc.)" #: ../../library/enum.rst:65 msgid "Module Contents" @@ -116,53 +148,59 @@ msgstr "Conteúdo do módulo" #: ../../library/enum.rst:67 msgid ":class:`EnumType`" -msgstr "" +msgstr ":class:`EnumType`" #: ../../library/enum.rst:69 msgid "The ``type`` for Enum and its subclasses." -msgstr "" +msgstr "O ``type`` para Enum e suas subclasses." #: ../../library/enum.rst:71 msgid ":class:`Enum`" -msgstr "" +msgstr ":class:`Enum`" #: ../../library/enum.rst:73 msgid "Base class for creating enumerated constants." -msgstr "" +msgstr "Classe base para criação de constantes enumeradas." #: ../../library/enum.rst:75 msgid ":class:`IntEnum`" -msgstr "" +msgstr ":class:`IntEnum`" #: ../../library/enum.rst:77 msgid "" "Base class for creating enumerated constants that are also subclasses of :" "class:`int`. (`Notes`_)" msgstr "" +"Classe base para criar constantes enumeradas que também são subclasses de :" +"class:`int`. (`Notas`_)" #: ../../library/enum.rst:80 msgid ":class:`StrEnum`" -msgstr "" +msgstr ":class:`StrEnum`" #: ../../library/enum.rst:82 msgid "" "Base class for creating enumerated constants that are also subclasses of :" "class:`str`. (`Notes`_)" msgstr "" +"Classe base para criar constantes enumeradas que também são subclasses de :" +"class:`str`. (`Notas`_)" #: ../../library/enum.rst:85 msgid ":class:`Flag`" -msgstr "" +msgstr ":class:`Flag`" #: ../../library/enum.rst:87 msgid "" "Base class for creating enumerated constants that can be combined using the " "bitwise operations without losing their :class:`Flag` membership." msgstr "" +"Classe base para criar constantes enumeradas que podem ser combinadas usando " +"operações bit a bit sem perder sua associação :class:`Flag`." #: ../../library/enum.rst:90 msgid ":class:`IntFlag`" -msgstr "" +msgstr ":class:`IntFlag`" #: ../../library/enum.rst:92 msgid "" @@ -170,20 +208,25 @@ msgid "" "bitwise operators without losing their :class:`IntFlag` membership. :class:" "`IntFlag` members are also subclasses of :class:`int`. (`Notes`_)" msgstr "" +"Classe base para criar constantes enumeradas que podem ser combinadas usando " +"operadores bit a bit sem perder sua associação :class:`IntFlag`. Membros de :" +"class:`IntFlag` também são subclasses de :class:`int`. (`Notas`_)" #: ../../library/enum.rst:96 msgid ":class:`ReprEnum`" -msgstr "" +msgstr ":class:`ReprEnum`" #: ../../library/enum.rst:98 msgid "" "Used by :class:`IntEnum`, :class:`StrEnum`, and :class:`IntFlag` to keep " "the :class:`str() ` of the mixed-in type." msgstr "" +"Usado por :class:`IntEnum`, :class:`StrEnum` e :class:`IntFlag` para manter " +"o :class:`str() ` do tipo misto." #: ../../library/enum.rst:101 msgid ":class:`EnumCheck`" -msgstr "" +msgstr ":class:`EnumCheck`" #: ../../library/enum.rst:103 msgid "" @@ -191,10 +234,13 @@ msgid "" "``UNIQUE``, for use with :func:`verify` to ensure various constraints are " "met by a given enumeration." msgstr "" +"Uma enumeração com os valores ``CONTINUOUS``, ``NAMED_FLAGS`` e ``UNIQUE``, " +"para uso com :func:`verify` para garantir que várias restrições sejam " +"atendidas por uma determinada enumeração." #: ../../library/enum.rst:107 msgid ":class:`FlagBoundary`" -msgstr "" +msgstr ":class:`FlagBoundary`" #: ../../library/enum.rst:109 msgid "" @@ -202,117 +248,157 @@ msgid "" "``KEEP`` which allows for more fine-grained control over how invalid values " "are dealt with in an enumeration." msgstr "" +"Uma enumeração com os valores ``STRICT``, ``CONFORM``, ``EJECT`` e ``KEEP`` " +"que permite um controle mais refinado sobre como valores inválidos são " +"tratados em uma enumeração." #: ../../library/enum.rst:113 -msgid ":class:`auto`" -msgstr "" +msgid ":class:`EnumDict`" +msgstr ":class:`EnumDict`" #: ../../library/enum.rst:115 +msgid "A subclass of :class:`dict` for use when subclassing :class:`EnumType`." +msgstr "" +"Uma subclasse de :class:`dict` para uso ao criar subclasse de :class:" +"`EnumType`." + +#: ../../library/enum.rst:117 +msgid ":class:`auto`" +msgstr ":class:`auto`" + +#: ../../library/enum.rst:119 msgid "" "Instances are replaced with an appropriate value for Enum members. :class:" "`StrEnum` defaults to the lower-cased version of the member name, while " "other Enums default to 1 and increase from there." msgstr "" +"As instâncias são substituídas por um valor apropriado para membros Enum. :" +"class:`StrEnum` assume como padrão a versão em minúsculas do nome do membro, " +"enquanto outros Enums assumem como padrão 1 e aumentam a partir daí." -#: ../../library/enum.rst:119 +#: ../../library/enum.rst:123 msgid ":func:`~enum.property`" -msgstr "" +msgstr ":func:`~enum.property`" -#: ../../library/enum.rst:121 +#: ../../library/enum.rst:125 msgid "" "Allows :class:`Enum` members to have attributes without conflicting with " "member names. The ``value`` and ``name`` attributes are implemented this " "way." msgstr "" +"Permite que membros :class:`Enum` tenham atributos sem conflitar com nomes " +"de membros. Os atributos ``value`` e ``name`` são implementados dessa forma." -#: ../../library/enum.rst:125 +#: ../../library/enum.rst:129 msgid ":func:`unique`" -msgstr "" +msgstr ":func:`unique`" -#: ../../library/enum.rst:127 +#: ../../library/enum.rst:131 msgid "" "Enum class decorator that ensures only one name is bound to any one value." msgstr "" +"Decorador de classe Enum que garante que apenas um nome seja vinculado a " +"cada valor." -#: ../../library/enum.rst:129 +#: ../../library/enum.rst:133 msgid ":func:`verify`" -msgstr "" +msgstr ":func:`verify`" -#: ../../library/enum.rst:131 +#: ../../library/enum.rst:135 msgid "" "Enum class decorator that checks user-selectable constraints on an " "enumeration." msgstr "" +"Decorador de classe Enum que verifica restrições selecionáveis pelo usuário " +"em uma enumeração." -#: ../../library/enum.rst:134 +#: ../../library/enum.rst:138 msgid ":func:`member`" -msgstr "" +msgstr ":func:`member`" -#: ../../library/enum.rst:136 +#: ../../library/enum.rst:140 msgid "Make ``obj`` a member. Can be used as a decorator." -msgstr "" +msgstr "Torna ``obj`` um membro. Pode ser usado como um decorador." -#: ../../library/enum.rst:138 +#: ../../library/enum.rst:142 msgid ":func:`nonmember`" -msgstr "" +msgstr ":func:`nonmember`" -#: ../../library/enum.rst:140 +#: ../../library/enum.rst:144 msgid "Do not make ``obj`` a member. Can be used as a decorator." -msgstr "" +msgstr "Não torna ``obj`` um membro. Pode ser usado como um decorador." -#: ../../library/enum.rst:142 +#: ../../library/enum.rst:146 msgid ":func:`global_enum`" -msgstr "" +msgstr ":func:`global_enum`" -#: ../../library/enum.rst:144 +#: ../../library/enum.rst:148 msgid "" "Modify the :class:`str() ` and :func:`repr` of an enum to show its " "members as belonging to the module instead of its class, and export the enum " "members to the global namespace." msgstr "" +"Modifica :class:`str() ` e :func:`repr` de uma enumeração para mostrar " +"seus membros como pertencentes ao módulo em vez de sua classe, e exporta os " +"membros da enumeração para o espaço de nomes global." -#: ../../library/enum.rst:148 +#: ../../library/enum.rst:152 msgid ":func:`show_flag_values`" -msgstr "" +msgstr ":func:`show_flag_values`" -#: ../../library/enum.rst:150 +#: ../../library/enum.rst:154 msgid "Return a list of all power-of-two integers contained in a flag." msgstr "" +"Retorna uma lista de todos os inteiros de potência de dois contidos em um " +"sinalizador." -#: ../../library/enum.rst:153 +#: ../../library/enum.rst:157 msgid "``Flag``, ``IntFlag``, ``auto``" -msgstr "" +msgstr "``Flag``, ``IntFlag``, ``auto``" -#: ../../library/enum.rst:154 +#: ../../library/enum.rst:158 msgid "" "``StrEnum``, ``EnumCheck``, ``ReprEnum``, ``FlagBoundary``, ``property``, " "``member``, ``nonmember``, ``global_enum``, ``show_flag_values``" msgstr "" +"``StrEnum``, ``EnumCheck``, ``ReprEnum``, ``FlagBoundary``, ``property``, " +"``member``, ``nonmember``, ``global_enum``, ``show_flag_values``" #: ../../library/enum.rst:159 +msgid "``EnumDict``" +msgstr "``EnumDict``" + +#: ../../library/enum.rst:164 msgid "Data Types" msgstr "Tipos de Dados" -#: ../../library/enum.rst:164 +#: ../../library/enum.rst:169 msgid "" "*EnumType* is the :term:`metaclass` for *enum* enumerations. It is possible " "to subclass *EnumType* -- see :ref:`Subclassing EnumType ` for details." msgstr "" +"*EnumType* é a :term:`metaclasse` para enumerações *enum*. É possível criar " +"subclasse de *EnumType* -- veja :ref:`Criando subclasses de EnumType " +"` para detalhes." -#: ../../library/enum.rst:168 +#: ../../library/enum.rst:173 msgid "" "``EnumType`` is responsible for setting the correct :meth:`!__repr__`, :meth:" "`!__str__`, :meth:`!__format__`, and :meth:`!__reduce__` methods on the " "final *enum*, as well as creating the enum members, properly handling " "duplicates, providing iteration over the enum class, etc." msgstr "" +"``EnumType`` é responsável por definir os métodos :meth:`!__repr__`, :meth:`!" +"__str__`, :meth:`!__format__` e :meth:`!__reduce__` corretos no *enum* " +"final, bem como criar os membros do enum, manipular adequadamente as " +"duplicatas, fornecer iteração sobre a classe do enum, etc." -#: ../../library/enum.rst:175 +#: ../../library/enum.rst:180 msgid "This method is called in two different ways:" msgstr "" -#: ../../library/enum.rst:177 +#: ../../library/enum.rst:182 msgid "to look up an existing member:" msgstr "" @@ -320,25 +406,25 @@ msgstr "" msgid "cls" msgstr "" -#: ../../library/enum.rst:179 ../../library/enum.rst:185 +#: ../../library/enum.rst:184 ../../library/enum.rst:190 msgid "The enum class being called." msgstr "" #: ../../library/enum.rst:0 msgid "value" -msgstr "value" +msgstr "valor" -#: ../../library/enum.rst:180 +#: ../../library/enum.rst:185 msgid "The value to lookup." msgstr "" -#: ../../library/enum.rst:182 +#: ../../library/enum.rst:187 msgid "" "to use the ``cls`` enum to create a new enum (only if the existing enum does " "not have any members):" msgstr "" -#: ../../library/enum.rst:186 +#: ../../library/enum.rst:191 msgid "The name of the new Enum to create." msgstr "" @@ -346,7 +432,7 @@ msgstr "" msgid "names" msgstr "nomes" -#: ../../library/enum.rst:187 +#: ../../library/enum.rst:192 msgid "The names/values of the members for the new Enum." msgstr "" @@ -354,7 +440,7 @@ msgstr "" msgid "module" msgstr "módulo" -#: ../../library/enum.rst:188 +#: ../../library/enum.rst:193 msgid "The name of the module the new Enum is created in." msgstr "" @@ -362,7 +448,7 @@ msgstr "" msgid "qualname" msgstr "qualname" -#: ../../library/enum.rst:189 +#: ../../library/enum.rst:194 msgid "The actual location in the module where this Enum can be found." msgstr "" @@ -370,7 +456,7 @@ msgstr "" msgid "type" msgstr "tipo" -#: ../../library/enum.rst:190 +#: ../../library/enum.rst:195 msgid "A mix-in type for the new Enum." msgstr "" @@ -378,7 +464,7 @@ msgstr "" msgid "start" msgstr "start" -#: ../../library/enum.rst:191 +#: ../../library/enum.rst:196 msgid "The first integer value for the Enum (used by :class:`auto`)." msgstr "" @@ -386,22 +472,31 @@ msgstr "" msgid "boundary" msgstr "" -#: ../../library/enum.rst:192 +#: ../../library/enum.rst:197 msgid "" "How to handle out-of-range values from bit operations (:class:`Flag` only)." msgstr "" -#: ../../library/enum.rst:196 +#: ../../library/enum.rst:201 msgid "Returns ``True`` if member belongs to the ``cls``::" msgstr "" -#: ../../library/enum.rst:206 +#: ../../library/enum.rst:203 +msgid "" +">>> some_var = Color.RED\n" +">>> some_var in Color\n" +"True\n" +">>> Color.RED.value in Color\n" +"True" +msgstr "" + +#: ../../library/enum.rst:211 msgid "" "Before Python 3.12, a ``TypeError`` is raised if a non-Enum-member is used " "in a containment check." msgstr "" -#: ../../library/enum.rst:211 +#: ../../library/enum.rst:216 msgid "" "Returns ``['__class__', '__doc__', '__members__', '__module__']`` and the " "names of the members in *cls*::" @@ -409,72 +504,116 @@ msgstr "" #: ../../library/enum.rst:219 msgid "" +">>> dir(Color)\n" +"['BLUE', 'GREEN', 'RED', '__class__', '__contains__', '__doc__', " +"'__getitem__', '__init_subclass__', '__iter__', '__len__', '__members__', " +"'__module__', '__name__', '__qualname__']" +msgstr "" + +#: ../../library/enum.rst:224 +msgid "" "Returns the Enum member in *cls* matching *name*, or raises a :exc:" "`KeyError`::" msgstr "" #: ../../library/enum.rst:226 +msgid "" +">>> Color['BLUE']\n" +"" +msgstr "" + +#: ../../library/enum.rst:231 msgid "Returns each member in *cls* in definition order::" msgstr "" #: ../../library/enum.rst:233 +msgid "" +">>> list(Color)\n" +"[, , ]" +msgstr "" + +#: ../../library/enum.rst:238 msgid "Returns the number of member in *cls*::" msgstr "" #: ../../library/enum.rst:240 +msgid "" +">>> len(Color)\n" +"3" +msgstr "" + +#: ../../library/enum.rst:245 msgid "Returns a mapping of every enum name to its member, including aliases" msgstr "" -#: ../../library/enum.rst:244 +#: ../../library/enum.rst:249 msgid "Returns each member in *cls* in reverse definition order::" msgstr "" #: ../../library/enum.rst:251 msgid "" +">>> list(reversed(Color))\n" +"[, , ]" +msgstr "" + +#: ../../library/enum.rst:256 +msgid "" "Adds a new name as an alias to an existing member. Raises a :exc:" "`NameError` if the name is already assigned to a different member." msgstr "" -#: ../../library/enum.rst:256 +#: ../../library/enum.rst:261 msgid "" "Adds a new value as an alias to an existing member. Raises a :exc:" "`ValueError` if the value is already linked with a different member." msgstr "" -#: ../../library/enum.rst:261 +#: ../../library/enum.rst:266 msgid "" "Before 3.11 ``EnumType`` was called ``EnumMeta``, which is still available " "as an alias." msgstr "" -#: ../../library/enum.rst:266 +#: ../../library/enum.rst:271 msgid "*Enum* is the base class for all *enum* enumerations." msgstr "" -#: ../../library/enum.rst:270 +#: ../../library/enum.rst:275 msgid "The name used to define the ``Enum`` member::" msgstr "" #: ../../library/enum.rst:277 +msgid "" +">>> Color.BLUE.name\n" +"'BLUE'" +msgstr "" + +#: ../../library/enum.rst:282 msgid "The value given to the ``Enum`` member::" msgstr "" -#: ../../library/enum.rst:282 ../../library/enum.rst:302 +#: ../../library/enum.rst:284 +msgid "" +">>> Color.RED.value\n" +"1" +msgstr "" + +#: ../../library/enum.rst:287 ../../library/enum.rst:307 msgid "Value of the member, can be set in :meth:`~Enum.__new__`." msgstr "" -#: ../../library/enum.rst:284 +#: ../../library/enum.rst:289 msgid "Enum member values" msgstr "" -#: ../../library/enum.rst:286 +#: ../../library/enum.rst:291 msgid "" "Member values can be anything: :class:`int`, :class:`str`, etc. If the " "exact value is unimportant you may use :class:`auto` instances and an " "appropriate value will be chosen for you. See :class:`auto` for the details." msgstr "" -#: ../../library/enum.rst:291 +#: ../../library/enum.rst:296 msgid "" "While mutable/unhashable values, such as :class:`dict`, :class:`list` or a " "mutable :class:`~dataclasses.dataclass`, can be used, they will have a " @@ -482,44 +621,64 @@ msgid "" "mutable/unhashable values in the enum." msgstr "" -#: ../../library/enum.rst:298 +#: ../../library/enum.rst:303 msgid "Name of the member." msgstr "" -#: ../../library/enum.rst:306 +#: ../../library/enum.rst:311 msgid "" "No longer used, kept for backward compatibility. (class attribute, removed " "during class creation)." msgstr "" -#: ../../library/enum.rst:311 +#: ../../library/enum.rst:316 msgid "" "``_ignore_`` is only used during creation and is removed from the " "enumeration once creation is complete." msgstr "" -#: ../../library/enum.rst:314 +#: ../../library/enum.rst:319 msgid "" "``_ignore_`` is a list of names that will not become members, and whose " "names will also be removed from the completed enumeration. See :ref:" "`TimePeriod ` for an example." msgstr "" -#: ../../library/enum.rst:320 +#: ../../library/enum.rst:325 msgid "" "Returns ``['__class__', '__doc__', '__module__', 'name', 'value']`` and any " "public methods defined on *self.__class__*::" msgstr "" +#: ../../library/enum.rst:328 +msgid "" +">>> from datetime import date\n" +">>> class Weekday(Enum):\n" +"... MONDAY = 1\n" +"... TUESDAY = 2\n" +"... WEDNESDAY = 3\n" +"... THURSDAY = 4\n" +"... FRIDAY = 5\n" +"... SATURDAY = 6\n" +"... SUNDAY = 7\n" +"... @classmethod\n" +"... def today(cls):\n" +"... print('today is %s' % cls(date.today().isoweekday()).name)\n" +"...\n" +">>> dir(Weekday.SATURDAY)\n" +"['__class__', '__doc__', '__eq__', '__hash__', '__module__', 'name', " +"'today', 'value']" +msgstr "" + #: ../../library/enum.rst:0 msgid "name" msgstr "nome" -#: ../../library/enum.rst:341 +#: ../../library/enum.rst:346 msgid "The name of the member being defined (e.g. 'RED')." msgstr "" -#: ../../library/enum.rst:342 +#: ../../library/enum.rst:347 msgid "The start value for the Enum; the default is 1." msgstr "" @@ -527,7 +686,7 @@ msgstr "" msgid "count" msgstr "" -#: ../../library/enum.rst:343 +#: ../../library/enum.rst:348 msgid "The number of members currently defined, not including this one." msgstr "" @@ -535,87 +694,164 @@ msgstr "" msgid "last_values" msgstr "" -#: ../../library/enum.rst:344 +#: ../../library/enum.rst:349 msgid "A list of the previous values." msgstr "" -#: ../../library/enum.rst:346 +#: ../../library/enum.rst:351 msgid "" "A *staticmethod* that is used to determine the next value returned by :class:" "`auto`::" msgstr "" -#: ../../library/enum.rst:362 +#: ../../library/enum.rst:354 +msgid "" +">>> from enum import auto\n" +">>> class PowersOfThree(Enum):\n" +"... @staticmethod\n" +"... def _generate_next_value_(name, start, count, last_values):\n" +"... return 3 ** (count + 1)\n" +"... FIRST = auto()\n" +"... SECOND = auto()\n" +"...\n" +">>> PowersOfThree.SECOND.value\n" +"9" +msgstr "" + +#: ../../library/enum.rst:367 msgid "" "By default, does nothing. If multiple values are given in the member " "assignment, those values become separate arguments to ``__init__``; e.g." msgstr "" -#: ../../library/enum.rst:369 +#: ../../library/enum.rst:374 msgid "" "``Weekday.__init__()`` would be called as ``Weekday.__init__(self, 1, " "'Mon')``" msgstr "" -#: ../../library/enum.rst:373 +#: ../../library/enum.rst:378 msgid "" "A *classmethod* that is used to further configure subsequent subclasses. By " "default, does nothing." msgstr "" -#: ../../library/enum.rst:378 +#: ../../library/enum.rst:383 msgid "" "A *classmethod* for looking up values not found in *cls*. By default it " "does nothing, but can be overridden to implement custom search behavior::" msgstr "" -#: ../../library/enum.rst:400 +#: ../../library/enum.rst:386 +msgid "" +">>> from enum import StrEnum\n" +">>> class Build(StrEnum):\n" +"... DEBUG = auto()\n" +"... OPTIMIZED = auto()\n" +"... @classmethod\n" +"... def _missing_(cls, value):\n" +"... value = value.lower()\n" +"... for member in cls:\n" +"... if member.value == value:\n" +"... return member\n" +"... return None\n" +"...\n" +">>> Build.DEBUG.value\n" +"'debug'\n" +">>> Build('deBUG')\n" +"" +msgstr "" + +#: ../../library/enum.rst:405 msgid "" "By default, doesn't exist. If specified, either in the enum class " "definition or in a mixin class (such as ``int``), all values given in the " "member assignment will be passed; e.g." msgstr "" -#: ../../library/enum.rst:408 +#: ../../library/enum.rst:413 msgid "" "results in the call ``int('1a', 16)`` and a value of ``26`` for the member." msgstr "" -#: ../../library/enum.rst:412 +#: ../../library/enum.rst:417 msgid "" "When writing a custom ``__new__``, do not use ``super().__new__`` -- call " "the appropriate ``__new__`` instead." msgstr "" -#: ../../library/enum.rst:417 +#: ../../library/enum.rst:422 msgid "" "Returns the string used for *repr()* calls. By default, returns the *Enum* " "name, member name, and value, but can be overridden::" msgstr "" -#: ../../library/enum.rst:433 +#: ../../library/enum.rst:425 +msgid "" +">>> class OtherStyle(Enum):\n" +"... ALTERNATE = auto()\n" +"... OTHER = auto()\n" +"... SOMETHING_ELSE = auto()\n" +"... def __repr__(self):\n" +"... cls_name = self.__class__.__name__\n" +"... return f'{cls_name}.{self.name}'\n" +"...\n" +">>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f\"{OtherStyle." +"ALTERNATE}\"\n" +"(OtherStyle.ALTERNATE, 'OtherStyle.ALTERNATE', 'OtherStyle.ALTERNATE')" +msgstr "" + +#: ../../library/enum.rst:438 msgid "" "Returns the string used for *str()* calls. By default, returns the *Enum* " "name and member name, but can be overridden::" msgstr "" -#: ../../library/enum.rst:448 +#: ../../library/enum.rst:441 +msgid "" +">>> class OtherStyle(Enum):\n" +"... ALTERNATE = auto()\n" +"... OTHER = auto()\n" +"... SOMETHING_ELSE = auto()\n" +"... def __str__(self):\n" +"... return f'{self.name}'\n" +"...\n" +">>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f\"{OtherStyle." +"ALTERNATE}\"\n" +"(, 'ALTERNATE', 'ALTERNATE')" +msgstr "" + +#: ../../library/enum.rst:453 msgid "" "Returns the string used for *format()* and *f-string* calls. By default, " "returns :meth:`__str__` return value, but can be overridden::" msgstr "" -#: ../../library/enum.rst:463 +#: ../../library/enum.rst:456 +msgid "" +">>> class OtherStyle(Enum):\n" +"... ALTERNATE = auto()\n" +"... OTHER = auto()\n" +"... SOMETHING_ELSE = auto()\n" +"... def __format__(self, spec):\n" +"... return f'{self.name}'\n" +"...\n" +">>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f\"{OtherStyle." +"ALTERNATE}\"\n" +"(, 'OtherStyle.ALTERNATE', 'ALTERNATE')" +msgstr "" + +#: ../../library/enum.rst:468 msgid "" "Using :class:`auto` with :class:`Enum` results in integers of increasing " "value, starting with ``1``." msgstr "" -#: ../../library/enum.rst:466 +#: ../../library/enum.rst:471 msgid "Added :ref:`enum-dataclass-support`" msgstr "" -#: ../../library/enum.rst:471 +#: ../../library/enum.rst:476 msgid "" "*IntEnum* is the same as :class:`Enum`, but its members are also integers " "and can be used anywhere that an integer can be used. If any integer " @@ -623,20 +859,20 @@ msgid "" "its enumeration status." msgstr "" -#: ../../library/enum.rst:492 +#: ../../library/enum.rst:497 msgid "" "Using :class:`auto` with :class:`IntEnum` results in integers of increasing " "value, starting with ``1``." msgstr "" -#: ../../library/enum.rst:495 +#: ../../library/enum.rst:500 msgid "" ":meth:`~object.__str__` is now :meth:`!int.__str__` to better support the " "*replacement of existing constants* use-case. :meth:`~object.__format__` was " "already :meth:`!int.__format__` for that same reason." msgstr "" -#: ../../library/enum.rst:502 +#: ../../library/enum.rst:507 msgid "" "``StrEnum`` is the same as :class:`Enum`, but its members are also strings " "and can be used in most of the same places that a string can be used. The " @@ -644,7 +880,7 @@ msgid "" "not part of the enumeration." msgstr "" -#: ../../library/enum.rst:508 +#: ../../library/enum.rst:513 msgid "" "There are places in the stdlib that check for an exact :class:`str` instead " "of a :class:`str` subclass (i.e. ``type(unknown) == str`` instead of " @@ -652,309 +888,498 @@ msgid "" "``str(StrEnum.member)``." msgstr "" -#: ../../library/enum.rst:515 +#: ../../library/enum.rst:520 msgid "" "Using :class:`auto` with :class:`StrEnum` results in the lower-cased member " "name as the value." msgstr "" -#: ../../library/enum.rst:520 +#: ../../library/enum.rst:525 msgid "" ":meth:`~object.__str__` is :meth:`!str.__str__` to better support the " "*replacement of existing constants* use-case. :meth:`~object.__format__` is " "likewise :meth:`!str.__format__` for that same reason." msgstr "" -#: ../../library/enum.rst:528 +#: ../../library/enum.rst:533 msgid "" "``Flag`` is the same as :class:`Enum`, but its members support the bitwise " "operators ``&`` (*AND*), ``|`` (*OR*), ``^`` (*XOR*), and ``~`` (*INVERT*); " "the results of those operations are (aliases of) members of the enumeration." msgstr "" -#: ../../library/enum.rst:534 +#: ../../library/enum.rst:539 msgid "Returns *True* if value is in self::" msgstr "" -#: ../../library/enum.rst:555 +#: ../../library/enum.rst:541 +msgid "" +">>> from enum import Flag, auto\n" +">>> class Color(Flag):\n" +"... RED = auto()\n" +"... GREEN = auto()\n" +"... BLUE = auto()\n" +"...\n" +">>> purple = Color.RED | Color.BLUE\n" +">>> white = Color.RED | Color.GREEN | Color.BLUE\n" +">>> Color.GREEN in purple\n" +"False\n" +">>> Color.GREEN in white\n" +"True\n" +">>> purple in white\n" +"True\n" +">>> white in purple\n" +"False" +msgstr "" + +#: ../../library/enum.rst:560 msgid "Returns all contained non-alias members::" msgstr "" -#: ../../library/enum.rst:566 +#: ../../library/enum.rst:562 +msgid "" +">>> list(Color.RED)\n" +"[]\n" +">>> list(purple)\n" +"[, ]" +msgstr "" + +#: ../../library/enum.rst:571 msgid "Returns number of members in flag::" msgstr "" -#: ../../library/enum.rst:577 +#: ../../library/enum.rst:573 +msgid "" +">>> len(Color.GREEN)\n" +"1\n" +">>> len(white)\n" +"3" +msgstr "" + +#: ../../library/enum.rst:582 msgid "Returns *True* if any members in flag, *False* otherwise::" msgstr "" -#: ../../library/enum.rst:589 +#: ../../library/enum.rst:584 +msgid "" +">>> bool(Color.GREEN)\n" +"True\n" +">>> bool(white)\n" +"True\n" +">>> black = Color(0)\n" +">>> bool(black)\n" +"False" +msgstr "" + +#: ../../library/enum.rst:594 msgid "Returns current flag binary or'ed with other::" msgstr "" #: ../../library/enum.rst:596 +msgid "" +">>> Color.RED | Color.GREEN\n" +"" +msgstr "" + +#: ../../library/enum.rst:601 msgid "Returns current flag binary and'ed with other::" msgstr "" -#: ../../library/enum.rst:605 +#: ../../library/enum.rst:603 +msgid "" +">>> purple & white\n" +"\n" +">>> purple & Color.GREEN\n" +"" +msgstr "" + +#: ../../library/enum.rst:610 msgid "Returns current flag binary xor'ed with other::" msgstr "" -#: ../../library/enum.rst:614 +#: ../../library/enum.rst:612 +msgid "" +">>> purple ^ white\n" +"\n" +">>> purple ^ Color.GREEN\n" +"" +msgstr "" + +#: ../../library/enum.rst:619 msgid "Returns all the flags in *type(self)* that are not in *self*::" msgstr "" -#: ../../library/enum.rst:625 +#: ../../library/enum.rst:621 +msgid "" +">>> ~white\n" +"\n" +">>> ~purple\n" +"\n" +">>> ~Color.RED\n" +"" +msgstr "" + +#: ../../library/enum.rst:630 msgid "" "Function used to format any remaining unnamed numeric values. Default is " "the value's repr; common choices are :func:`hex` and :func:`oct`." msgstr "" -#: ../../library/enum.rst:630 +#: ../../library/enum.rst:635 msgid "" "Using :class:`auto` with :class:`Flag` results in integers that are powers " "of two, starting with ``1``." msgstr "" -#: ../../library/enum.rst:633 +#: ../../library/enum.rst:638 msgid "The *repr()* of zero-valued flags has changed. It is now::" msgstr "" -#: ../../library/enum.rst:641 +#: ../../library/enum.rst:646 msgid "" "``IntFlag`` is the same as :class:`Flag`, but its members are also integers " "and can be used anywhere that an integer can be used." msgstr "" -#: ../../library/enum.rst:655 +#: ../../library/enum.rst:660 msgid "" "If any integer operation is performed with an *IntFlag* member, the result " "is not an *IntFlag*::" msgstr "" -#: ../../library/enum.rst:661 +#: ../../library/enum.rst:663 +msgid "" +">>> Color.RED + 2\n" +"3" +msgstr "" + +#: ../../library/enum.rst:666 msgid "If a :class:`Flag` operation is performed with an *IntFlag* member and:" msgstr "" -#: ../../library/enum.rst:663 +#: ../../library/enum.rst:668 msgid "the result is a valid *IntFlag*: an *IntFlag* is returned" msgstr "" -#: ../../library/enum.rst:664 +#: ../../library/enum.rst:669 msgid "" "the result is not a valid *IntFlag*: the result depends on the :class:" "`FlagBoundary` setting" msgstr "" -#: ../../library/enum.rst:666 -msgid "" -"The :func:`repr()` of unnamed zero-valued flags has changed. It is now:" +#: ../../library/enum.rst:671 +msgid "The :func:`repr` of unnamed zero-valued flags has changed. It is now:" msgstr "" -#: ../../library/enum.rst:673 +#: ../../library/enum.rst:678 msgid "" "Using :class:`auto` with :class:`IntFlag` results in integers that are " "powers of two, starting with ``1``." msgstr "" -#: ../../library/enum.rst:678 +#: ../../library/enum.rst:683 msgid "" ":meth:`~object.__str__` is now :meth:`!int.__str__` to better support the " "*replacement of existing constants* use-case. :meth:`~object.__format__` " "was already :meth:`!int.__format__` for that same reason." msgstr "" -#: ../../library/enum.rst:682 +#: ../../library/enum.rst:687 msgid "" "Inversion of an :class:`!IntFlag` now returns a positive value that is the " "union of all flags not in the given flag, rather than a negative value. This " "matches the existing :class:`Flag` behavior." msgstr "" -#: ../../library/enum.rst:688 +#: ../../library/enum.rst:693 msgid "" ":class:`!ReprEnum` uses the :meth:`repr() ` of :class:`Enum`, " "but the :class:`str() ` of the mixed-in data type:" msgstr "" -#: ../../library/enum.rst:691 +#: ../../library/enum.rst:696 msgid ":meth:`!int.__str__` for :class:`IntEnum` and :class:`IntFlag`" msgstr "" -#: ../../library/enum.rst:692 +#: ../../library/enum.rst:697 msgid ":meth:`!str.__str__` for :class:`StrEnum`" msgstr "" -#: ../../library/enum.rst:694 +#: ../../library/enum.rst:699 msgid "" "Inherit from :class:`!ReprEnum` to keep the :class:`str() ` / :func:" "`format` of the mixed-in data type instead of using the :class:`Enum`-" "default :meth:`str() `." msgstr "" -#: ../../library/enum.rst:703 +#: ../../library/enum.rst:708 msgid "" "*EnumCheck* contains the options used by the :func:`verify` decorator to " "ensure various constraints; failed constraints result in a :exc:`ValueError`." msgstr "" -#: ../../library/enum.rst:708 +#: ../../library/enum.rst:713 msgid "Ensure that each value has only one name::" msgstr "" -#: ../../library/enum.rst:724 +#: ../../library/enum.rst:715 +msgid "" +">>> from enum import Enum, verify, UNIQUE\n" +">>> @verify(UNIQUE)\n" +"... class Color(Enum):\n" +"... RED = 1\n" +"... GREEN = 2\n" +"... BLUE = 3\n" +"... CRIMSON = 1\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: aliases found in : CRIMSON -> RED" +msgstr "" + +#: ../../library/enum.rst:729 msgid "" "Ensure that there are no missing values between the lowest-valued member and " "the highest-valued member::" msgstr "" -#: ../../library/enum.rst:739 +#: ../../library/enum.rst:732 +msgid "" +">>> from enum import Enum, verify, CONTINUOUS\n" +">>> @verify(CONTINUOUS)\n" +"... class Color(Enum):\n" +"... RED = 1\n" +"... GREEN = 2\n" +"... BLUE = 5\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: invalid enum 'Color': missing values 3, 4" +msgstr "" + +#: ../../library/enum.rst:744 msgid "" "Ensure that any flag groups/masks contain only named flags -- useful when " "values are specified instead of being generated by :func:`auto`::" msgstr "" -#: ../../library/enum.rst:756 +#: ../../library/enum.rst:747 +msgid "" +">>> from enum import Flag, verify, NAMED_FLAGS\n" +">>> @verify(NAMED_FLAGS)\n" +"... class Color(Flag):\n" +"... RED = 1\n" +"... GREEN = 2\n" +"... BLUE = 4\n" +"... WHITE = 15\n" +"... NEON = 31\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: invalid Flag 'Color': aliases WHITE and NEON are missing " +"combined values of 0x18 [use enum.show_flag_values(value) for details]" +msgstr "" + +#: ../../library/enum.rst:761 msgid "" "CONTINUOUS and NAMED_FLAGS are designed to work with integer-valued members." msgstr "" -#: ../../library/enum.rst:762 +#: ../../library/enum.rst:767 msgid "" "``FlagBoundary`` controls how out-of-range values are handled in :class:" "`Flag` and its subclasses." msgstr "" -#: ../../library/enum.rst:767 +#: ../../library/enum.rst:772 msgid "" "Out-of-range values cause a :exc:`ValueError` to be raised. This is the " "default for :class:`Flag`::" msgstr "" -#: ../../library/enum.rst:785 +#: ../../library/enum.rst:775 +msgid "" +">>> from enum import Flag, STRICT, auto\n" +">>> class StrictFlag(Flag, boundary=STRICT):\n" +"... RED = auto()\n" +"... GREEN = auto()\n" +"... BLUE = auto()\n" +"...\n" +">>> StrictFlag(2**2 + 2**4)\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: invalid value 20\n" +" given 0b0 10100\n" +" allowed 0b0 00111" +msgstr "" + +#: ../../library/enum.rst:790 msgid "" "Out-of-range values have invalid values removed, leaving a valid :class:" "`Flag` value::" msgstr "" -#: ../../library/enum.rst:799 +#: ../../library/enum.rst:793 +msgid "" +">>> from enum import Flag, CONFORM, auto\n" +">>> class ConformFlag(Flag, boundary=CONFORM):\n" +"... RED = auto()\n" +"... GREEN = auto()\n" +"... BLUE = auto()\n" +"...\n" +">>> ConformFlag(2**2 + 2**4)\n" +"" +msgstr "" + +#: ../../library/enum.rst:804 msgid "" "Out-of-range values lose their :class:`Flag` membership and revert to :class:" "`int`." msgstr "" -#: ../../library/enum.rst:812 +#: ../../library/enum.rst:817 msgid "" "Out-of-range values are kept, and the :class:`Flag` membership is kept. This " "is the default for :class:`IntFlag`::" msgstr "" -#: ../../library/enum.rst:829 +#: ../../library/enum.rst:820 +msgid "" +">>> from enum import Flag, KEEP, auto\n" +">>> class KeepFlag(Flag, boundary=KEEP):\n" +"... RED = auto()\n" +"... GREEN = auto()\n" +"... BLUE = auto()\n" +"...\n" +">>> KeepFlag(2**2 + 2**4)\n" +"" +msgstr "" + +#: ../../library/enum.rst:833 +msgid "" +"*EnumDict* is a subclass of :class:`dict` that is used as the namespace for " +"defining enum classes (see :ref:`prepare`). It is exposed to allow " +"subclasses of :class:`EnumType` with advanced behavior like having multiple " +"values per member. It should be called with the name of the enum class being " +"created, otherwise private names and internal classes will not be handled " +"correctly." +msgstr "" + +#: ../../library/enum.rst:840 +msgid "" +"Note that only the :class:`~collections.abc.MutableMapping` interface (:meth:" +"`~object.__setitem__` and :meth:`~dict.update`) is overridden. It may be " +"possible to bypass the checks using other :class:`!dict` operations like :" +"meth:`|= `." +msgstr "" + +#: ../../library/enum.rst:847 +msgid "A list of member names." +msgstr "" + +#: ../../library/enum.rst:854 msgid "Supported ``__dunder__`` names" msgstr "Nomes ``__dunder__`` suportados" -#: ../../library/enum.rst:831 +#: ../../library/enum.rst:856 msgid "" ":attr:`~EnumType.__members__` is a read-only ordered mapping of " "``member_name``:``member`` items. It is only available on the class." msgstr "" -#: ../../library/enum.rst:834 +#: ../../library/enum.rst:859 msgid "" ":meth:`~Enum.__new__`, if specified, must create and return the enum " "members; it is also a very good idea to set the member's :attr:`!_value_` " "appropriately. Once all the members are created it is no longer used." msgstr "" -#: ../../library/enum.rst:840 +#: ../../library/enum.rst:865 msgid "Supported ``_sunder_`` names" msgstr "Nomes ``_sunder_`` suportados" -#: ../../library/enum.rst:842 +#: ../../library/enum.rst:867 msgid "" ":meth:`~EnumType._add_alias_` -- adds a new name as an alias to an existing " "member." msgstr "" -#: ../../library/enum.rst:844 +#: ../../library/enum.rst:869 msgid "" ":meth:`~EnumType._add_value_alias_` -- adds a new value as an alias to an " "existing member." msgstr "" -#: ../../library/enum.rst:846 +#: ../../library/enum.rst:871 msgid ":attr:`~Enum._name_` -- name of the member" msgstr "" -#: ../../library/enum.rst:847 +#: ../../library/enum.rst:872 msgid ":attr:`~Enum._value_` -- value of the member; can be set in ``__new__``" msgstr "" -#: ../../library/enum.rst:848 +#: ../../library/enum.rst:873 msgid "" ":meth:`~Enum._missing_` -- a lookup function used when a value is not found; " "may be overridden" msgstr "" -#: ../../library/enum.rst:850 +#: ../../library/enum.rst:875 msgid "" ":attr:`~Enum._ignore_` -- a list of names, either as a :class:`list` or a :" "class:`str`, that will not be transformed into members, and will be removed " "from the final class" msgstr "" -#: ../../library/enum.rst:853 +#: ../../library/enum.rst:878 msgid "" ":attr:`~Enum._order_` -- no longer used, kept for backward compatibility " "(class attribute, removed during class creation)" msgstr "" -#: ../../library/enum.rst:855 +#: ../../library/enum.rst:880 msgid "" ":meth:`~Enum._generate_next_value_` -- used to get an appropriate value for " "an enum member; may be overridden" msgstr "" -#: ../../library/enum.rst:860 +#: ../../library/enum.rst:885 msgid "" "For standard :class:`Enum` classes the next value chosen is the highest " "value seen incremented by one." msgstr "" -#: ../../library/enum.rst:863 +#: ../../library/enum.rst:888 msgid "" "For :class:`Flag` classes the next value chosen will be the next highest " "power-of-two." msgstr "" -#: ../../library/enum.rst:866 +#: ../../library/enum.rst:891 msgid "" "While ``_sunder_`` names are generally reserved for the further development " "of the :class:`Enum` class and can not be used, some are explicitly allowed:" msgstr "" -#: ../../library/enum.rst:869 +#: ../../library/enum.rst:894 msgid "" "``_repr_*`` (e.g. ``_repr_html_``), as used in `IPython's rich display`_" msgstr "" -#: ../../library/enum.rst:871 +#: ../../library/enum.rst:896 msgid "``_missing_``, ``_order_``, ``_generate_next_value_``" msgstr "``_missing_``, ``_order_``, ``_generate_next_value_``" -#: ../../library/enum.rst:872 +#: ../../library/enum.rst:897 msgid "``_ignore_``" msgstr "``_ignore_``" -#: ../../library/enum.rst:873 +#: ../../library/enum.rst:898 msgid "``_add_alias_``, ``_add_value_alias_``, ``_repr_*``" msgstr "" -#: ../../library/enum.rst:879 +#: ../../library/enum.rst:904 msgid "Utilities and Decorators" msgstr "" -#: ../../library/enum.rst:883 +#: ../../library/enum.rst:908 msgid "" "*auto* can be used in place of a value. If used, the *Enum* machinery will " "call an :class:`Enum`'s :meth:`~Enum._generate_next_value_` to get an " @@ -965,54 +1390,54 @@ msgid "" "name. Care must be taken if mixing *auto()* with manually specified values." msgstr "" -#: ../../library/enum.rst:891 +#: ../../library/enum.rst:916 msgid "" "*auto* instances are only resolved when at the top level of an assignment:" msgstr "" -#: ../../library/enum.rst:893 +#: ../../library/enum.rst:918 msgid "``FIRST = auto()`` will work (auto() is replaced with ``1``);" msgstr "" -#: ../../library/enum.rst:894 +#: ../../library/enum.rst:919 msgid "" "``SECOND = auto(), -2`` will work (auto is replaced with ``2``, so ``2, -2`` " "is used to create the ``SECOND`` enum member;" msgstr "" -#: ../../library/enum.rst:896 +#: ../../library/enum.rst:921 msgid "" "``THREE = [auto(), -3]`` will *not* work (``, -3`` is used to " "create the ``THREE`` enum member)" msgstr "" -#: ../../library/enum.rst:901 +#: ../../library/enum.rst:926 msgid "" "In prior versions, ``auto()`` had to be the only thing on the assignment " "line to work properly." msgstr "" -#: ../../library/enum.rst:904 +#: ../../library/enum.rst:929 msgid "" "``_generate_next_value_`` can be overridden to customize the values used by " "*auto*." msgstr "" -#: ../../library/enum.rst:907 +#: ../../library/enum.rst:932 msgid "" "in 3.13 the default ``_generate_next_value_`` will always return the highest " "member value incremented by 1, and will fail if any member is an " "incompatible type." msgstr "" -#: ../../library/enum.rst:913 +#: ../../library/enum.rst:938 msgid "" "A decorator similar to the built-in *property*, but specifically for " "enumerations. It allows member attributes to have the same names as members " "themselves." msgstr "" -#: ../../library/enum.rst:917 +#: ../../library/enum.rst:942 msgid "" "the *property* and the member must be defined in separate classes; for " "example, the *value* and *name* attributes are defined in the *Enum* class, " @@ -1020,29 +1445,44 @@ msgid "" "``name``." msgstr "" -#: ../../library/enum.rst:926 +#: ../../library/enum.rst:951 msgid "" "A :keyword:`class` decorator specifically for enumerations. It searches an " "enumeration's :attr:`~EnumType.__members__`, gathering any aliases it finds; " "if any are found :exc:`ValueError` is raised with the details::" msgstr "" -#: ../../library/enum.rst:944 +#: ../../library/enum.rst:955 +msgid "" +">>> from enum import Enum, unique\n" +">>> @unique\n" +"... class Mistake(Enum):\n" +"... ONE = 1\n" +"... TWO = 2\n" +"... THREE = 3\n" +"... FOUR = 3\n" +"...\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: duplicate values found in : FOUR -> THREE" +msgstr "" + +#: ../../library/enum.rst:969 msgid "" "A :keyword:`class` decorator specifically for enumerations. Members from :" "class:`EnumCheck` are used to specify which constraints should be checked on " "the decorated enumeration." msgstr "" -#: ../../library/enum.rst:952 +#: ../../library/enum.rst:977 msgid "A decorator for use in enums: its target will become a member." msgstr "" -#: ../../library/enum.rst:958 +#: ../../library/enum.rst:983 msgid "A decorator for use in enums: its target will not become a member." msgstr "" -#: ../../library/enum.rst:964 +#: ../../library/enum.rst:989 msgid "" "A decorator to change the :class:`str() ` and :func:`repr` of an enum " "to show its members as belonging to the module instead of its class. Should " @@ -1050,40 +1490,54 @@ msgid "" "namespace (see :class:`re.RegexFlag` for an example)." msgstr "" -#: ../../library/enum.rst:974 +#: ../../library/enum.rst:998 msgid "Return a list of all power-of-two integers contained in a flag *value*." msgstr "" -#: ../../library/enum.rst:981 +#: ../../library/enum.rst:1006 msgid "Notes" msgstr "Notas" -#: ../../library/enum.rst:983 +#: ../../library/enum.rst:1008 msgid ":class:`IntEnum`, :class:`StrEnum`, and :class:`IntFlag`" msgstr "" -#: ../../library/enum.rst:985 +#: ../../library/enum.rst:1010 msgid "" "These three enum types are designed to be drop-in replacements for existing " "integer- and string-based values; as such, they have extra limitations:" msgstr "" -#: ../../library/enum.rst:988 +#: ../../library/enum.rst:1013 msgid "``__str__`` uses the value and not the name of the enum member" msgstr "" -#: ../../library/enum.rst:990 +#: ../../library/enum.rst:1015 msgid "" "``__format__``, because it uses ``__str__``, will also use the value of the " "enum member instead of its name" msgstr "" -#: ../../library/enum.rst:993 +#: ../../library/enum.rst:1018 msgid "" "If you do not need/want those limitations, you can either create your own " "base class by mixing in the ``int`` or ``str`` type yourself::" msgstr "" -#: ../../library/enum.rst:1000 +#: ../../library/enum.rst:1021 +msgid "" +">>> from enum import Enum\n" +">>> class MyIntEnum(int, Enum):\n" +"... pass" +msgstr "" + +#: ../../library/enum.rst:1025 msgid "or you can reassign the appropriate :meth:`str`, etc., in your enum::" msgstr "" + +#: ../../library/enum.rst:1027 +msgid "" +">>> from enum import Enum, IntEnum\n" +">>> class MyIntEnum(IntEnum):\n" +"... __str__ = Enum.__str__" +msgstr "" diff --git a/library/errno.po b/library/errno.po index 76ebfc447..21ac702c0 100644 --- a/library/errno.po +++ b/library/errno.po @@ -1,33 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2022 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: Rafael Fontenelle , 2022\n" +"POT-Creation-Date: 2025-01-31 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/errno.rst:2 msgid ":mod:`!errno` --- Standard errno system symbols" -msgstr "" +msgstr ":mod:`!errno` --- Símbolos padrão do sistema errno" #: ../../library/errno.rst:9 msgid "" @@ -36,6 +34,9 @@ msgid "" "are borrowed from :file:`linux/include/errno.h`, which should be all-" "inclusive." msgstr "" +"Este módulo disponibiliza símbolos de sistema padrão ``errno``. O valor de " +"cada símbolo é o valor inteiro correspondente. Os nomes e descrições são " +"emprestados de :file:`linux/include/errno.h`, que deve ser tudo inclusivo." #: ../../library/errno.rst:17 msgid "" @@ -43,12 +44,17 @@ msgid "" "the underlying system. For instance, ``errno.errorcode[errno.EPERM]`` maps " "to ``'EPERM'``." msgstr "" +"Dicionário que fornece um mapeamento do valor errno para o nome da string no " +"sistema subjacente. Por exemplo, ``errno.errorcode[errno.EPERM]`` mapeia " +"para ``'EPERM'``." #: ../../library/errno.rst:21 msgid "" "To translate a numeric error code to an error message, use :func:`os." "strerror`." msgstr "" +"Para traduzir um código de erro numérico em uma mensagem de erro, use :func:" +"`os.strerror`." #: ../../library/errno.rst:23 msgid "" @@ -56,79 +62,95 @@ msgid "" "not defined by the module. The specific list of defined symbols is " "available as ``errno.errorcode.keys()``. Symbols available can include:" msgstr "" +"Da lista a seguir, símbolos que não são usados na plataforma atual não são " +"definidos pelo módulo. A lista específica de símbolos definidos está " +"disponível como ``errno.errorcode.keys()``. Os símbolos disponíveis podem " +"incluir:" #: ../../library/errno.rst:30 msgid "" "Operation not permitted. This error is mapped to the exception :exc:" "`PermissionError`." msgstr "" +"Operação não permitida. Este erro é mapeado para a exceção :exc:" +"`PermissionError`." #: ../../library/errno.rst:36 msgid "" "No such file or directory. This error is mapped to the exception :exc:" "`FileNotFoundError`." msgstr "" +"Arquivo ou diretório inexistente. Este erro é mapeado para a exceção :exc:" +"`FileNotFoundError`." #: ../../library/errno.rst:42 msgid "" "No such process. This error is mapped to the exception :exc:" "`ProcessLookupError`." msgstr "" +"Processo inexistente. Este erro é mapeado para a exceção :exc:" +"`ProcessLookupError`." #: ../../library/errno.rst:48 msgid "" "Interrupted system call. This error is mapped to the exception :exc:" "`InterruptedError`." msgstr "" +"Chamada de sistema interrompida. Este erro é mapeado para a exceção :exc:" +"`InterruptedError`." #: ../../library/errno.rst:54 msgid "I/O error" -msgstr "" +msgstr "Erro de E/S" #: ../../library/errno.rst:59 msgid "No such device or address" -msgstr "" +msgstr "Endereço ou dispositivo inexistente" #: ../../library/errno.rst:64 msgid "Arg list too long" -msgstr "" +msgstr "Lista de argumentos muito longa" #: ../../library/errno.rst:69 msgid "Exec format error" -msgstr "" +msgstr "Erro no formato exec" #: ../../library/errno.rst:74 msgid "Bad file number" -msgstr "" +msgstr "Descritor de arquivo inválido" #: ../../library/errno.rst:79 msgid "" "No child processes. This error is mapped to the exception :exc:" "`ChildProcessError`." msgstr "" +"Não há processos filhos. Este erro é mapeado para a exceção :exc:" +"`ChildProcessError`." #: ../../library/errno.rst:85 msgid "" "Try again. This error is mapped to the exception :exc:`BlockingIOError`." msgstr "" +"Tente novamente. Este erro é mapeado para a exceção :exc:`BlockingIOError`." #: ../../library/errno.rst:90 msgid "Out of memory" -msgstr "" +msgstr "Memória insuficiente" #: ../../library/errno.rst:95 msgid "" "Permission denied. This error is mapped to the exception :exc:" "`PermissionError`." msgstr "" +"Permissão negada. Este erro é mapeado para a exceção :exc:`PermissionError`." #: ../../library/errno.rst:101 msgid "Bad address" -msgstr "" +msgstr "Endereço inválido" #: ../../library/errno.rst:106 msgid "Block device required" -msgstr "" +msgstr "Dispositivo de bloco requerido" #: ../../library/errno.rst:111 msgid "Device or resource busy" @@ -138,38 +160,42 @@ msgstr "Dispositivo ou recurso ocupado" msgid "" "File exists. This error is mapped to the exception :exc:`FileExistsError`." msgstr "" +"Arquivo existe. Este erro é mapeado para a exceção :exc:`FileExistsError`." #: ../../library/errno.rst:122 msgid "Cross-device link" -msgstr "" +msgstr "Link entre dispositivos inválido" #: ../../library/errno.rst:127 msgid "No such device" -msgstr "" +msgstr "Dispositivo inexistente" #: ../../library/errno.rst:132 msgid "" "Not a directory. This error is mapped to the exception :exc:" "`NotADirectoryError`." msgstr "" +"Não é um diretório. Este erro é mapeado para a exceção :exc:" +"`NotADirectoryError`." #: ../../library/errno.rst:138 msgid "" "Is a directory. This error is mapped to the exception :exc:" "`IsADirectoryError`." msgstr "" +"É um diretório. Este erro é mapeado para a exceção :exc:`IsADirectoryError`." #: ../../library/errno.rst:144 msgid "Invalid argument" -msgstr "" +msgstr "Argumento inválido" #: ../../library/errno.rst:149 msgid "File table overflow" -msgstr "" +msgstr "Estouro de tabela de arquivos" #: ../../library/errno.rst:154 msgid "Too many open files" -msgstr "" +msgstr "Muitos arquivos abertos" #: ../../library/errno.rst:159 msgid "Not a typewriter" @@ -177,162 +203,165 @@ msgstr "" #: ../../library/errno.rst:164 msgid "Text file busy" -msgstr "" +msgstr "Arquivo texto ocupado" #: ../../library/errno.rst:169 msgid "File too large" -msgstr "" +msgstr "Arquivo muito grande" #: ../../library/errno.rst:174 msgid "No space left on device" -msgstr "" +msgstr "Não há espaço disponível no dispositivo" #: ../../library/errno.rst:179 msgid "Illegal seek" -msgstr "" +msgstr "Procura ilegal" #: ../../library/errno.rst:184 msgid "Read-only file system" -msgstr "" +msgstr "Sistema de arquivos de somente leitura" #: ../../library/errno.rst:189 msgid "Too many links" -msgstr "" +msgstr "Muitos links" #: ../../library/errno.rst:194 msgid "" "Broken pipe. This error is mapped to the exception :exc:`BrokenPipeError`." msgstr "" +"Pipe quebrado. Este erro é mapeado para a exceção :exc:`BrokenPipeError`." #: ../../library/errno.rst:200 msgid "Math argument out of domain of func" -msgstr "" +msgstr "Argumento matemático fora do domínio da função" #: ../../library/errno.rst:205 msgid "Math result not representable" -msgstr "" +msgstr "Resultado matemático não representável" #: ../../library/errno.rst:210 msgid "Resource deadlock would occur" -msgstr "" +msgstr "Ocorreria um impasse (deadlock) de recursos" #: ../../library/errno.rst:215 msgid "File name too long" -msgstr "" +msgstr "Nome de arquivo muito longo" #: ../../library/errno.rst:220 msgid "No record locks available" -msgstr "" +msgstr "Nenhuma trava de registro disponível" #: ../../library/errno.rst:225 msgid "Function not implemented" -msgstr "" +msgstr "Função não implementada" #: ../../library/errno.rst:230 msgid "Directory not empty" -msgstr "" +msgstr "Diretório não vazio" #: ../../library/errno.rst:235 msgid "Too many symbolic links encountered" -msgstr "" +msgstr "Foram encontrados muitos links simbólicos" #: ../../library/errno.rst:240 msgid "" "Operation would block. This error is mapped to the exception :exc:" "`BlockingIOError`." msgstr "" +"Operation causaria bloqueio. Este erro é mapeado para a exceção :exc:" +"`BlockingIOError`." #: ../../library/errno.rst:246 msgid "No message of desired type" -msgstr "" +msgstr "Nenhuma mensagem do tipo desejado" #: ../../library/errno.rst:251 msgid "Identifier removed" -msgstr "" +msgstr "Identificador removido" #: ../../library/errno.rst:256 msgid "Channel number out of range" -msgstr "" +msgstr "Número do canal fora do intervalo" #: ../../library/errno.rst:261 msgid "Level 2 not synchronized" -msgstr "" +msgstr "Não sincronizado nível 2" #: ../../library/errno.rst:266 msgid "Level 3 halted" -msgstr "" +msgstr "Parada de sistema nível 3" #: ../../library/errno.rst:271 msgid "Level 3 reset" -msgstr "" +msgstr "Reinicialização nível 3" #: ../../library/errno.rst:276 msgid "Link number out of range" -msgstr "" +msgstr "Número de link fora da faixa" #: ../../library/errno.rst:281 msgid "Protocol driver not attached" -msgstr "" +msgstr "Driver de protocolo não anexado" #: ../../library/errno.rst:286 msgid "No CSI structure available" -msgstr "" +msgstr "Não há estrutura CSI disponível" #: ../../library/errno.rst:291 msgid "Level 2 halted" -msgstr "" +msgstr "Parada de sistema nível 2" #: ../../library/errno.rst:296 msgid "Invalid exchange" -msgstr "" +msgstr "Troca inválida" #: ../../library/errno.rst:301 msgid "Invalid request descriptor" -msgstr "" +msgstr "Descritor de requisição inválido" #: ../../library/errno.rst:306 msgid "Exchange full" -msgstr "" +msgstr "Troca completa" #: ../../library/errno.rst:311 msgid "No anode" -msgstr "" +msgstr "Sem anode" #: ../../library/errno.rst:316 msgid "Invalid request code" -msgstr "" +msgstr "Código de requisição inválido" #: ../../library/errno.rst:321 msgid "Invalid slot" -msgstr "" +msgstr "Slot inválido" #: ../../library/errno.rst:326 msgid "File locking deadlock error" -msgstr "" +msgstr "Erro de impasse em travamento de arquivo" #: ../../library/errno.rst:331 msgid "Bad font file format" -msgstr "" +msgstr "Formato inválido do arquivo de fonte" #: ../../library/errno.rst:336 msgid "Device not a stream" -msgstr "" +msgstr "Dispositivo não é um stream" #: ../../library/errno.rst:341 msgid "No data available" -msgstr "" +msgstr "Não há dados disponíveis" #: ../../library/errno.rst:346 msgid "Timer expired" -msgstr "" +msgstr "Temporizador expirado" #: ../../library/errno.rst:351 msgid "Out of streams resources" -msgstr "" +msgstr "Sem recursos de streams" #: ../../library/errno.rst:356 msgid "Machine is not on the network" -msgstr "" +msgstr "A máquina não está na rede" #: ../../library/errno.rst:361 msgid "Package not installed" @@ -344,11 +373,11 @@ msgstr "O objeto é remoto" #: ../../library/errno.rst:371 msgid "Link has been severed" -msgstr "" +msgstr "A conexão foi rompida" #: ../../library/errno.rst:376 msgid "Advertise error" -msgstr "" +msgstr "Erro de anúncio" #: ../../library/errno.rst:381 msgid "Srmount error" @@ -356,7 +385,7 @@ msgstr "Erro Srmount" #: ../../library/errno.rst:386 msgid "Communication error on send" -msgstr "" +msgstr "Erro de comunicação ao enviar" #: ../../library/errno.rst:391 msgid "Protocol error" @@ -364,155 +393,159 @@ msgstr "Erro de Protocolo" #: ../../library/errno.rst:396 msgid "Multihop attempted" -msgstr "" +msgstr "Tentativa de hops múltiplos" #: ../../library/errno.rst:401 msgid "RFS specific error" -msgstr "" +msgstr "Erro específico de RFS" #: ../../library/errno.rst:406 msgid "Not a data message" -msgstr "" +msgstr "Não é uma mensagem de dados" #: ../../library/errno.rst:411 msgid "Value too large for defined data type" -msgstr "" +msgstr "Valor muito grande para o tipo de dados definido" #: ../../library/errno.rst:416 msgid "Name not unique on network" -msgstr "" +msgstr "O nome não é único na rede" #: ../../library/errno.rst:421 msgid "File descriptor in bad state" -msgstr "" +msgstr "Descritor de arquivo em mal estado" #: ../../library/errno.rst:426 msgid "Remote address changed" -msgstr "" +msgstr "Endereço remoto mudou" #: ../../library/errno.rst:431 msgid "Can not access a needed shared library" -msgstr "" +msgstr "Não é possível acessar uma biblioteca compartilhada necessária" #: ../../library/errno.rst:436 msgid "Accessing a corrupted shared library" -msgstr "" +msgstr "Acessando uma biblioteca compartilhado corrompida" #: ../../library/errno.rst:441 msgid ".lib section in a.out corrupted" -msgstr "" +msgstr "Seção .lib corrompida em a.out" #: ../../library/errno.rst:446 msgid "Attempting to link in too many shared libraries" -msgstr "" +msgstr "Tentando ligar em muitas bibliotecas compartilhadas" #: ../../library/errno.rst:451 msgid "Cannot exec a shared library directly" -msgstr "" +msgstr "Não é possível executar uma biblioteca compartilhada diretamente" #: ../../library/errno.rst:456 msgid "Illegal byte sequence" -msgstr "" +msgstr "Sequência de bytes ilegal" #: ../../library/errno.rst:461 msgid "Interrupted system call should be restarted" -msgstr "" +msgstr "Chamada de sistema interrompida deve ser reiniciada" #: ../../library/errno.rst:466 msgid "Streams pipe error" -msgstr "" +msgstr "Erro de fluxos de pipe" #: ../../library/errno.rst:471 msgid "Too many users" -msgstr "" +msgstr "Muitos usuários" #: ../../library/errno.rst:476 msgid "Socket operation on non-socket" -msgstr "" +msgstr "Operação socket em um arquivo não-socket" #: ../../library/errno.rst:481 msgid "Destination address required" -msgstr "" +msgstr "Endereço de destino necessário" #: ../../library/errno.rst:486 msgid "Message too long" -msgstr "" +msgstr "Mensagem muito longa" #: ../../library/errno.rst:491 msgid "Protocol wrong type for socket" -msgstr "" +msgstr "Tipo errado de protocolo para socket" #: ../../library/errno.rst:496 msgid "Protocol not available" -msgstr "" +msgstr "Protocolo não disponível" #: ../../library/errno.rst:501 msgid "Protocol not supported" -msgstr "" +msgstr "Protocolo sem suporte" #: ../../library/errno.rst:506 msgid "Socket type not supported" -msgstr "" +msgstr "Tipo socket sem suporte" #: ../../library/errno.rst:511 msgid "Operation not supported on transport endpoint" -msgstr "" +msgstr "Operação sem suporte na extremidade do transporte" #: ../../library/errno.rst:516 msgid "Operation not supported" -msgstr "" +msgstr "Operação sem suporte" #: ../../library/errno.rst:523 msgid "Protocol family not supported" -msgstr "" +msgstr "Família de protocolo sem suporte" #: ../../library/errno.rst:528 msgid "Address family not supported by protocol" -msgstr "" +msgstr "Família de endereços sem suporte pelo protocolo" #: ../../library/errno.rst:533 msgid "Address already in use" -msgstr "" +msgstr "Endereço já em uso" #: ../../library/errno.rst:538 msgid "Cannot assign requested address" -msgstr "" +msgstr "Não é possível acessar o endereço requisitado" #: ../../library/errno.rst:543 msgid "Network is down" -msgstr "" +msgstr "A rede não responde" #: ../../library/errno.rst:548 msgid "Network is unreachable" -msgstr "" +msgstr "A rede está fora de alcance" #: ../../library/errno.rst:553 msgid "Network dropped connection because of reset" -msgstr "" +msgstr "A rede desconectou-se ao reiniciar" #: ../../library/errno.rst:558 msgid "" "Software caused connection abort. This error is mapped to the exception :exc:" "`ConnectionAbortedError`." msgstr "" +"O software causou a interrupção da conexão. Este erro é mapeado para a " +"exceção :exc:`ConnectionAbortedError`." #: ../../library/errno.rst:564 msgid "" "Connection reset by peer. This error is mapped to the exception :exc:" "`ConnectionResetError`." msgstr "" +"Conexão fechada pela outra ponta. Este erro é mapeado para a exceção :exc:" +"`ConnectionResetError`." #: ../../library/errno.rst:570 msgid "No buffer space available" -msgstr "" +msgstr "Não há espaço de buffer disponível" #: ../../library/errno.rst:575 msgid "Transport endpoint is already connected" -msgstr "" +msgstr "A extremidade do transporte já está conectada" #: ../../library/errno.rst:580 msgid "Transport endpoint is not connected" -msgstr "" +msgstr "A extremidade do transporte não está conectada" #: ../../library/errno.rst:585 msgid "" @@ -588,24 +621,128 @@ msgstr "" msgid "Interface output queue is full" msgstr "" -#: ../../library/errno.rst:670 +#: ../../library/errno.rst:671 +msgid "No medium found" +msgstr "" + +#: ../../library/errno.rst:676 +msgid "Wrong medium type" +msgstr "" + +#: ../../library/errno.rst:681 +msgid "Required key not available" +msgstr "" + +#: ../../library/errno.rst:686 +msgid "Key has expired" +msgstr "" + +#: ../../library/errno.rst:691 +msgid "Key has been revoked" +msgstr "" + +#: ../../library/errno.rst:696 +msgid "Key was rejected by service" +msgstr "" + +#: ../../library/errno.rst:701 +msgid "Operation not possible due to RF-kill" +msgstr "" + +#: ../../library/errno.rst:706 +msgid "Locked lock was unmapped" +msgstr "" + +#: ../../library/errno.rst:711 +msgid "Facility is not active" +msgstr "" + +#: ../../library/errno.rst:716 +msgid "Authentication error" +msgstr "" + +#: ../../library/errno.rst:723 +msgid "Bad CPU type in executable" +msgstr "" + +#: ../../library/errno.rst:730 +msgid "Bad executable (or shared library)" +msgstr "" + +#: ../../library/errno.rst:737 +msgid "Malformed Mach-o file" +msgstr "" + +#: ../../library/errno.rst:744 +msgid "Device error" +msgstr "" + +#: ../../library/errno.rst:751 +msgid "Inappropriate file type or format" +msgstr "" + +#: ../../library/errno.rst:758 +msgid "Need authenticator" +msgstr "" + +#: ../../library/errno.rst:765 +msgid "Attribute not found" +msgstr "" + +#: ../../library/errno.rst:772 +msgid "Policy not found" +msgstr "" + +#: ../../library/errno.rst:779 +msgid "Too many processes" +msgstr "" + +#: ../../library/errno.rst:786 +msgid "Bad procedure for program" +msgstr "" + +#: ../../library/errno.rst:793 +msgid "Program version wrong" +msgstr "" + +#: ../../library/errno.rst:800 +msgid "RPC prog. not avail" +msgstr "" + +#: ../../library/errno.rst:807 +msgid "Device power is off" +msgstr "" + +#: ../../library/errno.rst:814 +msgid "RPC struct is bad" +msgstr "" + +#: ../../library/errno.rst:821 +msgid "RPC version wrong" +msgstr "" + +#: ../../library/errno.rst:828 +msgid "Shared library version mismatch" +msgstr "" + +#: ../../library/errno.rst:835 msgid "" "Capabilities insufficient. This error is mapped to the exception :exc:" "`PermissionError`." msgstr "" -#: ../../library/errno.rst:673 -msgid ":ref:`Availability `: WASI, FreeBSD" -msgstr ":ref:`Disponibilidade `: WASI, FreeBSD" +#: ../../library/errno.rst:838 +msgid "Availability" +msgstr "Disponibilidade" -#: ../../library/errno.rst:680 +#: ../../library/errno.rst:845 msgid "Operation canceled" msgstr "" -#: ../../library/errno.rst:687 +#: ../../library/errno.rst:852 msgid "Owner died" msgstr "" -#: ../../library/errno.rst:694 +#: ../../library/errno.rst:859 msgid "State not recoverable" msgstr "" diff --git a/library/exceptions.po b/library/exceptions.po index 84132061c..af6614cad 100644 --- a/library/exceptions.po +++ b/library/exceptions.po @@ -1,32 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2021 -# guilhermegouw , 2021 -# Vinicius Gubiani Ferreira , 2023 -# Marco Rougeth , 2023 -# Patricia Mortada, 2023 -# Leandro Cavalcante Damascena , 2024 -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-20 00:52+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-03-07 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -129,6 +122,10 @@ msgstr "" "Esse contexto implícito da exceção pode ser complementado com uma causa " "explícita usando :keyword:`!from` com :keyword:`raise`::" +#: ../../library/exceptions.rst:63 +msgid "raise new_exc from original_exc" +msgstr "raise new_exc from original_exc" + #: ../../library/exceptions.rst:65 msgid "" "The expression following :keyword:`from` must be an exception or " @@ -266,6 +263,20 @@ msgstr "" "traceback de ``SomeException`` original se tivéssemos permitido que ele se " "propagasse para o chamador. ::" +#: ../../library/exceptions.rst:135 +msgid "" +"try:\n" +" ...\n" +"except SomeException:\n" +" tb = sys.exception().__traceback__\n" +" raise OtherException(...).with_traceback(tb)" +msgstr "" +"try:\n" +" ...\n" +"except SomeException:\n" +" tb = sys.exception().__traceback__\n" +" raise OtherException(...).with_traceback(tb)" + #: ../../library/exceptions.rst:143 msgid "" "A writable field that holds the :ref:`traceback object ` " @@ -548,15 +559,16 @@ msgstr "" #: ../../library/exceptions.rst:338 msgid "" -"``NotImplementedError`` and :data:`NotImplemented` are not interchangeable, " -"even though they have similar names and purposes. See :data:`!" -"NotImplemented` for details on when to use it." +":exc:`!NotImplementedError` and :data:`!NotImplemented` are not " +"interchangeable. This exception should only be used as described above; see :" +"data:`NotImplemented` for details on correct usage of the built-in constant." msgstr "" -"``NotImplementedError`` e :data:`NotImplemented` não são intercambiáveis, " -"mesmo que tenham nomes e propósitos similares. Veja :data:`!NotImplemented` " -"para detalhes e casos de uso." +":exc:`!NotImplementedError` e :data:`!NotImplemented` não são " +"intercambiáveis. Esta exceção deve ser usada somente conforme descrito " +"acima; veja :data:`NotImplemented` para detalhes sobre o uso correto da " +"constante embutida." -#: ../../library/exceptions.rst:347 +#: ../../library/exceptions.rst:349 msgid "" "This exception is raised when a system function returns a system-related " "error, including I/O failures such as \"file not found\" or \"disk " @@ -567,7 +579,7 @@ msgstr "" "ou \"disk full\" (não para tipos de argumentos não permitidos ou outro erro " "acessório)." -#: ../../library/exceptions.rst:351 +#: ../../library/exceptions.rst:353 msgid "" "The second form of the constructor sets the corresponding attributes, " "described below. The attributes default to :const:`None` if not specified. " @@ -581,7 +593,7 @@ msgstr "" "argumentos são passados, o atributo :attr:`~BaseException.args` contêm " "somente uma tupla de 2 elementos, os dois primeiros argumentos do construtor." -#: ../../library/exceptions.rst:357 +#: ../../library/exceptions.rst:359 msgid "" "The constructor often actually returns a subclass of :exc:`OSError`, as " "described in `OS exceptions`_ below. The particular subclass depends on the " @@ -595,11 +607,11 @@ msgstr "" "construção direta ou por meio de um apelido de :exc:`OSError`, e não é " "herdado na criação de subclasses." -#: ../../library/exceptions.rst:365 +#: ../../library/exceptions.rst:367 msgid "A numeric error code from the C variable :c:data:`errno`." msgstr "Um código de erro numérico da variável C :c:data:`errno`." -#: ../../library/exceptions.rst:369 +#: ../../library/exceptions.rst:371 msgid "" "Under Windows, this gives you the native Windows error code. The :attr:`." "errno` attribute is then an approximate translation, in POSIX terms, of that " @@ -609,7 +621,7 @@ msgstr "" "attr:`.errno` é então uma tradução aproximada, em termos POSIX, desse código " "de erro nativo." -#: ../../library/exceptions.rst:373 +#: ../../library/exceptions.rst:375 msgid "" "Under Windows, if the *winerror* constructor argument is an integer, the :" "attr:`.errno` attribute is determined from the Windows error code, and the " @@ -621,7 +633,7 @@ msgstr "" "e o argumento *errno* é ignorado. Em outras plataformas, o argumento " "*winerror* é ignorado e o atributo :attr:`winerror` não existe." -#: ../../library/exceptions.rst:381 +#: ../../library/exceptions.rst:383 msgid "" "The corresponding error message, as provided by the operating system. It is " "formatted by the C functions :c:func:`perror` under POSIX, and :c:func:" @@ -631,7 +643,7 @@ msgstr "" "operacional. É formatada pelas funções C :c:func:`perror` no POSIX e :c:func:" "`FormatMessage` no Windows." -#: ../../library/exceptions.rst:389 +#: ../../library/exceptions.rst:391 msgid "" "For exceptions that involve a file system path (such as :func:`open` or :" "func:`os.unlink`), :attr:`filename` is the file name passed to the function. " @@ -645,7 +657,7 @@ msgstr "" "arquivos (como :func:`os.rename`), :attr:`filename2` corresponde ao segundo " "nome de arquivo passado para a função." -#: ../../library/exceptions.rst:396 +#: ../../library/exceptions.rst:398 msgid "" ":exc:`EnvironmentError`, :exc:`IOError`, :exc:`WindowsError`, :exc:`socket." "error`, :exc:`select.error` and :exc:`mmap.error` have been merged into :exc:" @@ -655,7 +667,7 @@ msgstr "" "error`, :exc:`select.error` e :exc:`mmap.error` foram fundidos em :exc:" "`OSError`, e o construtor pode retornar uma subclasse." -#: ../../library/exceptions.rst:402 +#: ../../library/exceptions.rst:404 msgid "" "The :attr:`filename` attribute is now the original file name passed to the " "function, instead of the name encoded to or decoded from the :term:" @@ -667,7 +679,7 @@ msgstr "" "erros e codificação do sistema de arquivos`. Além disso, o argumento e o " "atributo de construtor *filename2* foi adicionado." -#: ../../library/exceptions.rst:411 +#: ../../library/exceptions.rst:413 msgid "" "Raised when the result of an arithmetic operation is too large to be " "represented. This cannot occur for integers (which would rather raise :exc:" @@ -684,7 +696,7 @@ msgstr "" "exceção de ponto flutuante em C, a maioria das operações de ponto flutuante " "não são verificadas." -#: ../../library/exceptions.rst:421 +#: ../../library/exceptions.rst:423 msgid "" "This exception is derived from :exc:`RuntimeError`. It is raised when an " "operation is blocked during interpreter shutdown also known as :term:`Python " @@ -694,7 +706,7 @@ msgstr "" "operação é bloqueada durante o encerramento do interpretador e também " "conhecido como :term:`finalização do Python `." -#: ../../library/exceptions.rst:425 +#: ../../library/exceptions.rst:427 msgid "" "Examples of operations which can be blocked with a :exc:" "`PythonFinalizationError` during the Python finalization:" @@ -702,23 +714,23 @@ msgstr "" "Exemplos de operações que podem ser bloqueadas com um :exc:" "`PythonFinalizationError` durante a finalização do Python:" -#: ../../library/exceptions.rst:428 +#: ../../library/exceptions.rst:430 msgid "Creating a new Python thread." msgstr "Criação de uma nova thread no Python." -#: ../../library/exceptions.rst:429 +#: ../../library/exceptions.rst:431 msgid ":func:`os.fork`." msgstr ":func:`os.fork`." -#: ../../library/exceptions.rst:431 +#: ../../library/exceptions.rst:433 msgid "See also the :func:`sys.is_finalizing` function." msgstr "Veja também a função :func:`sys.is_finalizing`." -#: ../../library/exceptions.rst:433 ../../library/exceptions.rst:443 +#: ../../library/exceptions.rst:435 ../../library/exceptions.rst:445 msgid "Previously, a plain :exc:`RuntimeError` was raised." msgstr "Anteriormente, uma :exc:`RuntimeError` simples era levantada." -#: ../../library/exceptions.rst:439 +#: ../../library/exceptions.rst:441 msgid "" "This exception is derived from :exc:`RuntimeError`. It is raised when the " "interpreter detects that the maximum recursion depth (see :func:`sys." @@ -728,7 +740,7 @@ msgstr "" "interpretador detecta que a profundidade máxima de recursão (veja :func:`sys." "getrecursionlimit`) foi excedida." -#: ../../library/exceptions.rst:449 +#: ../../library/exceptions.rst:451 msgid "" "This exception is raised when a weak reference proxy, created by the :func:" "`weakref.proxy` function, is used to access an attribute of the referent " @@ -740,7 +752,7 @@ msgstr "" "referente após ter sido coletado como lixo. Para mais informações sobre " "referências fracas, veja o módulo :mod:`weakref`." -#: ../../library/exceptions.rst:457 +#: ../../library/exceptions.rst:459 msgid "" "Raised when an error is detected that doesn't fall in any of the other " "categories. The associated value is a string indicating what precisely went " @@ -750,7 +762,7 @@ msgstr "" "categorias. O valor associado é uma string indicando o que precisamente deu " "errado." -#: ../../library/exceptions.rst:464 +#: ../../library/exceptions.rst:466 msgid "" "Raised by built-in function :func:`next` and an :term:`iterator`\\'s :meth:" "`~iterator.__next__` method to signal that there are no further items " @@ -760,7 +772,7 @@ msgstr "" "__next__` de um :term:`iterador` para sinalizar que não há mais itens " "produzidos pelo iterador." -#: ../../library/exceptions.rst:470 +#: ../../library/exceptions.rst:472 msgid "" "The exception object has a single attribute :attr:`!value`, which is given " "as an argument when constructing the exception, and defaults to :const:" @@ -769,7 +781,7 @@ msgstr "" "O objeto exceção tem um único atributo :attr:`!value`, que é fornecido como " "um argumento ao construir a exceção, e o padrão é :const:`None`." -#: ../../library/exceptions.rst:474 +#: ../../library/exceptions.rst:476 msgid "" "When a :term:`generator` or :term:`coroutine` function returns, a new :exc:" "`StopIteration` instance is raised, and the value returned by the function " @@ -780,7 +792,7 @@ msgstr "" "pela função é usado como o parâmetro :attr:`value` para o construtor da " "exceção." -#: ../../library/exceptions.rst:479 +#: ../../library/exceptions.rst:481 msgid "" "If a generator code directly or indirectly raises :exc:`StopIteration`, it " "is converted into a :exc:`RuntimeError` (retaining the :exc:`StopIteration` " @@ -790,7 +802,7 @@ msgstr "" "ele é convertido em uma :exc:`RuntimeError` (mantendo o :exc:`StopIteration` " "como a nova causa da exceção)." -#: ../../library/exceptions.rst:483 +#: ../../library/exceptions.rst:485 msgid "" "Added ``value`` attribute and the ability for generator functions to use it " "to return a value." @@ -798,7 +810,7 @@ msgstr "" "Adicionado o atributo ``value`` e a capacidade das funções geradoras de usá-" "lo para retornar um valor." -#: ../../library/exceptions.rst:487 +#: ../../library/exceptions.rst:489 msgid "" "Introduced the RuntimeError transformation via ``from __future__ import " "generator_stop``, see :pep:`479`." @@ -806,7 +818,7 @@ msgstr "" "Introduzida a transformação RuntimeError via ``from __future__ import " "generator_stop``, consulte :pep:`479`." -#: ../../library/exceptions.rst:491 +#: ../../library/exceptions.rst:493 msgid "" "Enable :pep:`479` for all code by default: a :exc:`StopIteration` error " "raised in a generator is transformed into a :exc:`RuntimeError`." @@ -815,7 +827,7 @@ msgstr "" "`StopIteration` levantado em um gerador é transformado em uma :exc:" "`RuntimeError`." -#: ../../library/exceptions.rst:497 +#: ../../library/exceptions.rst:499 msgid "" "Must be raised by :meth:`~object.__anext__` method of an :term:`asynchronous " "iterator` object to stop the iteration." @@ -823,7 +835,7 @@ msgstr "" "Deve ser levantada pelo método :meth:`~object.__anext__` de um objeto :term:" "`iterador assíncrono` para parar a iteração." -#: ../../library/exceptions.rst:504 +#: ../../library/exceptions.rst:506 msgid "" "Raised when the parser encounters a syntax error. This may occur in an :" "keyword:`import` statement, in a call to the built-in functions :func:" @@ -835,7 +847,7 @@ msgstr "" "func:`compile`, :func:`exec` ou :func:`eval`, ou ao ler o script inicial ou " "entrada padrão (também interativamente)." -#: ../../library/exceptions.rst:510 +#: ../../library/exceptions.rst:512 msgid "" "The :func:`str` of the exception instance returns only the error message. " "Details is a tuple whose members are also available as separate attributes." @@ -844,11 +856,11 @@ msgstr "" "erro. Detalhes é uma tupla cujos membros também estão disponíveis como " "atributos separados." -#: ../../library/exceptions.rst:515 +#: ../../library/exceptions.rst:517 msgid "The name of the file the syntax error occurred in." msgstr "O nome do arquivo em que ocorreu o erro de sintaxe." -#: ../../library/exceptions.rst:519 +#: ../../library/exceptions.rst:521 msgid "" "Which line number in the file the error occurred in. This is 1-indexed: the " "first line in the file has a ``lineno`` of 1." @@ -856,7 +868,7 @@ msgstr "" "Em qual número de linha no arquivo o erro ocorreu. Este é indexado em 1: a " "primeira linha no arquivo tem um ``lineno`` de 1." -#: ../../library/exceptions.rst:524 +#: ../../library/exceptions.rst:526 msgid "" "The column in the line where the error occurred. This is 1-indexed: the " "first character in the line has an ``offset`` of 1." @@ -864,11 +876,11 @@ msgstr "" "A coluna da linha em que ocorreu o erro. Este é indexado em 1: o primeiro " "caractere na linha tem um ``offset`` de 1." -#: ../../library/exceptions.rst:529 +#: ../../library/exceptions.rst:531 msgid "The source code text involved in the error." msgstr "O texto do código-fonte envolvido no erro." -#: ../../library/exceptions.rst:533 +#: ../../library/exceptions.rst:535 msgid "" "Which line number in the file the error occurred ends in. This is 1-indexed: " "the first line in the file has a ``lineno`` of 1." @@ -876,7 +888,7 @@ msgstr "" "Em qual número de linha no arquivo o erro ocorrido termina. Este é indexado " "em 1: a primeira linha no arquivo tem um ``lineno`` de 1." -#: ../../library/exceptions.rst:538 +#: ../../library/exceptions.rst:540 msgid "" "The column in the end line where the error occurred finishes. This is 1-" "indexed: the first character in the line has an ``offset`` of 1." @@ -884,7 +896,7 @@ msgstr "" "A coluna da linha final em que erro ocorrido finaliza Este é indexado em 1: " "o primeiro caractere na linha tem um ``offset`` de 1." -#: ../../library/exceptions.rst:541 +#: ../../library/exceptions.rst:543 msgid "" "For errors in f-string fields, the message is prefixed by \"f-string: \" and " "the offsets are offsets in a text constructed from the replacement " @@ -897,11 +909,11 @@ msgstr "" "resulta neste atributo de argumentos: ('f-string: ...', ('', 1, 2, '(a " "b)\\n', 1, 5))." -#: ../../library/exceptions.rst:546 +#: ../../library/exceptions.rst:548 msgid "Added the :attr:`end_lineno` and :attr:`end_offset` attributes." msgstr "Adicionado os atributos :attr:`end_lineno` e :attr:`end_offset`." -#: ../../library/exceptions.rst:551 +#: ../../library/exceptions.rst:553 msgid "" "Base class for syntax errors related to incorrect indentation. This is a " "subclass of :exc:`SyntaxError`." @@ -909,7 +921,7 @@ msgstr "" "Classe base para erros de sintaxe relacionados a indentação incorreta. Esta " "é uma subclasse de :exc:`SyntaxError`." -#: ../../library/exceptions.rst:557 +#: ../../library/exceptions.rst:559 msgid "" "Raised when indentation contains an inconsistent use of tabs and spaces. " "This is a subclass of :exc:`IndentationError`." @@ -917,32 +929,38 @@ msgstr "" "Levantada quando o indentação contém um uso inconsistente de tabulações e " "espaços. Esta é uma subclasse de :exc:`IndentationError`." -#: ../../library/exceptions.rst:563 +#: ../../library/exceptions.rst:565 msgid "" "Raised when the interpreter finds an internal error, but the situation does " "not look so serious to cause it to abandon all hope. The associated value is " -"a string indicating what went wrong (in low-level terms)." +"a string indicating what went wrong (in low-level terms). In :term:" +"`CPython`, this could be raised by incorrectly using Python's C API, such as " +"returning a ``NULL`` value without an exception set." msgstr "" "Levantada quando o interpretador encontra um erro interno, mas a situação " "não parece tão grave para fazer com que perca todas as esperanças. O valor " "associado é uma string que indica o que deu errado (em termos de baixo " -"nível)." +"nível). Em :term:`CPython`, isso pode ser causado pelo uso incorreto da API " +"C do Python, como retornar um valor ``NULL`` sem um conjunto de exceções." -#: ../../library/exceptions.rst:567 +#: ../../library/exceptions.rst:571 msgid "" -"You should report this to the author or maintainer of your Python " -"interpreter. Be sure to report the version of the Python interpreter (``sys." -"version``; it is also printed at the start of an interactive Python " -"session), the exact error message (the exception's associated value) and if " -"possible the source of the program that triggered the error." +"If you're confident that this exception wasn't your fault, or the fault of a " +"package you're using, you should report this to the author or maintainer of " +"your Python interpreter. Be sure to report the version of the Python " +"interpreter (``sys.version``; it is also printed at the start of an " +"interactive Python session), the exact error message (the exception's " +"associated value) and if possible the source of the program that triggered " +"the error." msgstr "" -"Você deve relatar isso ao autor ou mantenedor do seu interpretador Python. " -"Certifique-se de relatar a versão do interpretador Python (``sys.version``; " -"também é impresso no início de uma sessão Python interativa), a mensagem de " -"erro exata (o valor associado da exceção) e se possível a fonte do programa " -"que acionou o erro." +"Se você tem certeza de que essa exceção não foi culpa sua ou de um pacote " +"que você está usando, você deve relatar isso ao autor ou mantenedor do seu " +"interpretador Python. Certifique-se de relatar a versão do interpretador " +"Python (``sys.version``; também é impresso no início de uma sessão Python " +"interativa), a mensagem de erro exata (o valor associado da exceção) e se " +"possível a fonte do programa que acionou o erro." -#: ../../library/exceptions.rst:576 +#: ../../library/exceptions.rst:582 msgid "" "This exception is raised by the :func:`sys.exit` function. It inherits " "from :exc:`BaseException` instead of :exc:`Exception` so that it is not " @@ -966,7 +984,7 @@ msgstr "" "`exit`); se for ``None``, o status de saída é zero; se tiver outro tipo " "(como uma string), o valor do objeto é exibido e o status de saída é um." -#: ../../library/exceptions.rst:587 +#: ../../library/exceptions.rst:593 msgid "" "A call to :func:`sys.exit` is translated into an exception so that clean-up " "handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be " @@ -982,7 +1000,7 @@ msgstr "" "pode ser usada se for absolutamente necessário sair imediatamente (por " "exemplo, no processo filho após uma chamada para :func:`os.fork`)." -#: ../../library/exceptions.rst:596 +#: ../../library/exceptions.rst:602 msgid "" "The exit status or error message that is passed to the constructor. " "(Defaults to ``None``.)" @@ -990,7 +1008,7 @@ msgstr "" "O status de saída ou mensagem de erro transmitida ao construtor. (O padrão é " "``None``.)" -#: ../../library/exceptions.rst:602 +#: ../../library/exceptions.rst:608 msgid "" "Raised when an operation or function is applied to an object of " "inappropriate type. The associated value is a string giving details about " @@ -1000,7 +1018,7 @@ msgstr "" "inadequado. O valor associado é uma string que fornece detalhes sobre a " "incompatibilidade de tipo." -#: ../../library/exceptions.rst:605 +#: ../../library/exceptions.rst:611 msgid "" "This exception may be raised by user code to indicate that an attempted " "operation on an object is not supported, and is not meant to be. If an " @@ -1013,7 +1031,7 @@ msgstr "" "implementação, :exc:`NotImplementedError` é a exceção apropriada a ser " "levantada." -#: ../../library/exceptions.rst:610 +#: ../../library/exceptions.rst:616 msgid "" "Passing arguments of the wrong type (e.g. passing a :class:`list` when an :" "class:`int` is expected) should result in a :exc:`TypeError`, but passing " @@ -1025,7 +1043,7 @@ msgstr "" "mas passar argumentos com o valor errado (por exemplo, um número fora " "limites esperados) deve resultar em uma :exc:`ValueError`." -#: ../../library/exceptions.rst:617 +#: ../../library/exceptions.rst:623 msgid "" "Raised when a reference is made to a local variable in a function or method, " "but no value has been bound to that variable. This is a subclass of :exc:" @@ -1035,7 +1053,7 @@ msgstr "" "ou método, mas nenhum valor foi vinculado a essa variável. Esta é uma " "subclasse de :exc:`NameError`." -#: ../../library/exceptions.rst:624 +#: ../../library/exceptions.rst:630 msgid "" "Raised when a Unicode-related encoding or decoding error occurs. It is a " "subclass of :exc:`ValueError`." @@ -1043,7 +1061,7 @@ msgstr "" "Levantada quando ocorre um erro de codificação ou decodificação relacionado " "ao Unicode. É uma subclasse de :exc:`ValueError`." -#: ../../library/exceptions.rst:627 +#: ../../library/exceptions.rst:633 msgid "" ":exc:`UnicodeError` has attributes that describe the encoding or decoding " "error. For example, ``err.object[err.start:err.end]`` gives the particular " @@ -1053,27 +1071,27 @@ msgstr "" "decodificação. Por exemplo, ``err.object[err.start:err.end]`` fornece a " "entrada inválida específica na qual o codec falhou." -#: ../../library/exceptions.rst:633 +#: ../../library/exceptions.rst:639 msgid "The name of the encoding that raised the error." msgstr "O nome da codificação que levantou o erro." -#: ../../library/exceptions.rst:637 +#: ../../library/exceptions.rst:643 msgid "A string describing the specific codec error." msgstr "Uma string que descreve o erro de codec específico." -#: ../../library/exceptions.rst:641 +#: ../../library/exceptions.rst:647 msgid "The object the codec was attempting to encode or decode." msgstr "O objeto que o codec estava tentando codificar ou decodificar." -#: ../../library/exceptions.rst:645 +#: ../../library/exceptions.rst:651 msgid "The first index of invalid data in :attr:`object`." msgstr "O primeiro índice de dados inválidos em :attr:`object`." -#: ../../library/exceptions.rst:649 +#: ../../library/exceptions.rst:655 msgid "The index after the last invalid data in :attr:`object`." msgstr "O índice após os últimos dados inválidos em :attr:`object`." -#: ../../library/exceptions.rst:654 +#: ../../library/exceptions.rst:660 msgid "" "Raised when a Unicode-related error occurs during encoding. It is a " "subclass of :exc:`UnicodeError`." @@ -1081,7 +1099,7 @@ msgstr "" "Levantada quando ocorre um erro relacionado ao Unicode durante a " "codificação. É uma subclasse de :exc:`UnicodeError`." -#: ../../library/exceptions.rst:660 +#: ../../library/exceptions.rst:666 msgid "" "Raised when a Unicode-related error occurs during decoding. It is a " "subclass of :exc:`UnicodeError`." @@ -1089,7 +1107,7 @@ msgstr "" "Levantada quando ocorre um erro relacionado ao Unicode durante a " "decodificação. É uma subclasse de :exc:`UnicodeError`." -#: ../../library/exceptions.rst:666 +#: ../../library/exceptions.rst:672 msgid "" "Raised when a Unicode-related error occurs during translating. It is a " "subclass of :exc:`UnicodeError`." @@ -1097,7 +1115,7 @@ msgstr "" "Levantada quando ocorre um erro relacionado ao Unicode durante a tradução. É " "uma subclasse de :exc:`UnicodeError`." -#: ../../library/exceptions.rst:672 +#: ../../library/exceptions.rst:678 msgid "" "Raised when an operation or function receives an argument that has the right " "type but an inappropriate value, and the situation is not described by a " @@ -1107,7 +1125,7 @@ msgstr "" "certo, mas um valor inadequado, e a situação não é descrita por uma exceção " "mais precisa, como :exc:`IndexError`." -#: ../../library/exceptions.rst:679 +#: ../../library/exceptions.rst:685 msgid "" "Raised when the second argument of a division or modulo operation is zero. " "The associated value is a string indicating the type of the operands and the " @@ -1117,7 +1135,7 @@ msgstr "" "zero. O valor associado é uma string que indica o tipo dos operandos e a " "operação." -#: ../../library/exceptions.rst:684 +#: ../../library/exceptions.rst:690 msgid "" "The following exceptions are kept for compatibility with previous versions; " "starting from Python 3.3, they are aliases of :exc:`OSError`." @@ -1125,15 +1143,15 @@ msgstr "" "As seguintes exceções são mantidas para compatibilidade com versões " "anteriores; a partir do Python 3.3, eles são apelidos de :exc:`OSError`." -#: ../../library/exceptions.rst:693 +#: ../../library/exceptions.rst:699 msgid "Only available on Windows." msgstr "Disponível apenas no Windows." -#: ../../library/exceptions.rst:697 +#: ../../library/exceptions.rst:703 msgid "OS exceptions" msgstr "Exceções de sistema operacional" -#: ../../library/exceptions.rst:699 +#: ../../library/exceptions.rst:705 msgid "" "The following exceptions are subclasses of :exc:`OSError`, they get raised " "depending on the system error code." @@ -1141,7 +1159,7 @@ msgstr "" "As seguintes exceções são subclasses de :exc:`OSError`, elas são levantadas " "dependendo do código de erro do sistema." -#: ../../library/exceptions.rst:704 +#: ../../library/exceptions.rst:710 msgid "" "Raised when an operation would block on an object (e.g. socket) set for non-" "blocking operation. Corresponds to :c:data:`errno` :py:const:`~errno." @@ -1153,7 +1171,7 @@ msgstr "" "`~errno.EAGAIN`, :py:const:`~errno.EALREADY`, :py:const:`~errno.EWOULDBLOCK` " "e :py:const:`~errno.EINPROGRESS`." -#: ../../library/exceptions.rst:709 +#: ../../library/exceptions.rst:715 msgid "" "In addition to those of :exc:`OSError`, :exc:`BlockingIOError` can have one " "more attribute:" @@ -1161,7 +1179,7 @@ msgstr "" "Além daquelas de :exc:`OSError`, :exc:`BlockingIOError` pode ter mais um " "atributo:" -#: ../../library/exceptions.rst:714 +#: ../../library/exceptions.rst:720 msgid "" "An integer containing the number of characters written to the stream before " "it blocked. This attribute is available when using the buffered I/O classes " @@ -1171,7 +1189,7 @@ msgstr "" "bloqueado. Este atributo está disponível ao usar as classes de E/S em buffer " "do módulo :mod:`io`." -#: ../../library/exceptions.rst:720 +#: ../../library/exceptions.rst:726 msgid "" "Raised when an operation on a child process failed. Corresponds to :c:data:" "`errno` :py:const:`~errno.ECHILD`." @@ -1179,11 +1197,11 @@ msgstr "" "Levantada quando uma operação em um processo filho falha. Corresponde a :c:" "data:`errno` :py:const:`~errno.ECHILD`." -#: ../../library/exceptions.rst:725 +#: ../../library/exceptions.rst:731 msgid "A base class for connection-related issues." msgstr "Uma classe base para problemas relacionados à conexão." -#: ../../library/exceptions.rst:727 +#: ../../library/exceptions.rst:733 msgid "" "Subclasses are :exc:`BrokenPipeError`, :exc:`ConnectionAbortedError`, :exc:" "`ConnectionRefusedError` and :exc:`ConnectionResetError`." @@ -1191,7 +1209,7 @@ msgstr "" "Suas subclasses são :exc:`BrokenPipeError`, :exc:`ConnectionAbortedError`, :" "exc:`ConnectionRefusedError` e :exc:`ConnectionResetError`." -#: ../../library/exceptions.rst:732 +#: ../../library/exceptions.rst:738 msgid "" "A subclass of :exc:`ConnectionError`, raised when trying to write on a pipe " "while the other end has been closed, or trying to write on a socket which " @@ -1203,7 +1221,7 @@ msgstr "" "escrever em um soquete que foi desligado para escrita. Corresponde a :c:" "data:`errno` :py:const:`~errno.EPIPE` e :py:const:`~errno.ESHUTDOWN`." -#: ../../library/exceptions.rst:739 +#: ../../library/exceptions.rst:745 msgid "" "A subclass of :exc:`ConnectionError`, raised when a connection attempt is " "aborted by the peer. Corresponds to :c:data:`errno` :py:const:`~errno." @@ -1213,7 +1231,7 @@ msgstr "" "conexão é cancelada pelo par. Corresponde a :c:data:`errno` :py:const:" "`~errno.ECONNABORTED`." -#: ../../library/exceptions.rst:745 +#: ../../library/exceptions.rst:751 msgid "" "A subclass of :exc:`ConnectionError`, raised when a connection attempt is " "refused by the peer. Corresponds to :c:data:`errno` :py:const:`~errno." @@ -1223,7 +1241,7 @@ msgstr "" "conexão é recusada pelo par. Corresponde a :c:data:`errno` :py:const:`~errno." "ECONNREFUSED`." -#: ../../library/exceptions.rst:751 +#: ../../library/exceptions.rst:757 msgid "" "A subclass of :exc:`ConnectionError`, raised when a connection is reset by " "the peer. Corresponds to :c:data:`errno` :py:const:`~errno.ECONNRESET`." @@ -1232,7 +1250,7 @@ msgstr "" "redefinida pelo par. Corresponde a :c:data:`errno` :py:const:`~errno." "ECONNRESET`." -#: ../../library/exceptions.rst:757 +#: ../../library/exceptions.rst:763 msgid "" "Raised when trying to create a file or directory which already exists. " "Corresponds to :c:data:`errno` :py:const:`~errno.EEXIST`." @@ -1240,7 +1258,7 @@ msgstr "" "Levantada ao tentar criar um arquivo ou diretório que já existe. Corresponde " "a :c:data:`errno` :py:const:`~errno.EEXIST`." -#: ../../library/exceptions.rst:762 +#: ../../library/exceptions.rst:768 msgid "" "Raised when a file or directory is requested but doesn't exist. Corresponds " "to :c:data:`errno` :py:const:`~errno.ENOENT`." @@ -1248,7 +1266,7 @@ msgstr "" "Levantada quando um arquivo ou diretório é solicitado, mas não existe. " "Corresponde a :c:data:`errno` :py:const:`~errno.ENOENT`." -#: ../../library/exceptions.rst:767 +#: ../../library/exceptions.rst:773 msgid "" "Raised when a system call is interrupted by an incoming signal. Corresponds " "to :c:data:`errno` :py:const:`~errno.EINTR`." @@ -1256,7 +1274,7 @@ msgstr "" "Levantada quando uma chamada do sistema é interrompida por um sinal de " "entrada. Corresponde a :c:data:`errno` :py:const:`~errno.EINTR`." -#: ../../library/exceptions.rst:770 +#: ../../library/exceptions.rst:776 msgid "" "Python now retries system calls when a syscall is interrupted by a signal, " "except if the signal handler raises an exception (see :pep:`475` for the " @@ -1267,7 +1285,7 @@ msgstr "" "(veja :pep:`475` para a justificativa), em vez de levantar :exc:" "`InterruptedError`." -#: ../../library/exceptions.rst:777 +#: ../../library/exceptions.rst:783 msgid "" "Raised when a file operation (such as :func:`os.remove`) is requested on a " "directory. Corresponds to :c:data:`errno` :py:const:`~errno.EISDIR`." @@ -1276,7 +1294,7 @@ msgstr "" "solicitada em um diretório. Corresponde a :c:data:`errno` :py:const:`~errno." "EISDIR`." -#: ../../library/exceptions.rst:783 +#: ../../library/exceptions.rst:789 msgid "" "Raised when a directory operation (such as :func:`os.listdir`) is requested " "on something which is not a directory. On most POSIX platforms, it may also " @@ -1290,7 +1308,7 @@ msgstr "" "arquivo não pertencente ao diretório como se fosse um diretório. Corresponde " "a :c:data:`errno` :py:const:`~errno.ENOTDIR`." -#: ../../library/exceptions.rst:791 +#: ../../library/exceptions.rst:797 msgid "" "Raised when trying to run an operation without the adequate access rights - " "for example filesystem permissions. Corresponds to :c:data:`errno` :py:const:" @@ -1302,7 +1320,7 @@ msgstr "" "data:`errno` :py:const:`~errno.EACCES`, :py:const:`~errno.EPERM`, e :py:" "const:`~errno.ENOTCAPABLE`." -#: ../../library/exceptions.rst:796 +#: ../../library/exceptions.rst:802 msgid "" "WASI's :py:const:`~errno.ENOTCAPABLE` is now mapped to :exc:" "`PermissionError`." @@ -1310,7 +1328,7 @@ msgstr "" ":py:const:`~errno.ENOTCAPABLE` do WASI agora é mapeado para :exc:" "`PermissionError`." -#: ../../library/exceptions.rst:802 +#: ../../library/exceptions.rst:808 msgid "" "Raised when a given process doesn't exist. Corresponds to :c:data:`errno` :" "py:const:`~errno.ESRCH`." @@ -1318,7 +1336,7 @@ msgstr "" "Levantada quando um determinado processo não existe. Corresponde a :c:data:" "`errno` :py:const:`~errno.ESRCH`." -#: ../../library/exceptions.rst:807 +#: ../../library/exceptions.rst:813 msgid "" "Raised when a system function timed out at the system level. Corresponds to :" "c:data:`errno` :py:const:`~errno.ETIMEDOUT`." @@ -1326,19 +1344,19 @@ msgstr "" "Levantada quando uma função do sistema expirou no nível do sistema. " "Corresponde a :c:data:`errno` :py:const:`~errno.ETIMEDOUT`." -#: ../../library/exceptions.rst:810 +#: ../../library/exceptions.rst:816 msgid "All the above :exc:`OSError` subclasses were added." msgstr "Todas as subclasses de :exc:`OSError` acima foram adicionadas." -#: ../../library/exceptions.rst:816 +#: ../../library/exceptions.rst:822 msgid ":pep:`3151` - Reworking the OS and IO exception hierarchy" msgstr ":pep:`3151` - Reworking the OS and IO exception hierarchy" -#: ../../library/exceptions.rst:822 +#: ../../library/exceptions.rst:828 msgid "Warnings" msgstr "Avisos" -#: ../../library/exceptions.rst:824 +#: ../../library/exceptions.rst:830 msgid "" "The following exceptions are used as warning categories; see the :ref:" "`warning-categories` documentation for more details." @@ -1346,15 +1364,15 @@ msgstr "" "As seguintes exceções são usadas como categorias de aviso; veja a " "documentação de :ref:`warning-categories` para mais detalhes." -#: ../../library/exceptions.rst:829 +#: ../../library/exceptions.rst:835 msgid "Base class for warning categories." msgstr "Classe base para categorias de aviso." -#: ../../library/exceptions.rst:834 +#: ../../library/exceptions.rst:840 msgid "Base class for warnings generated by user code." msgstr "Classe base para avisos gerados pelo código do usuário." -#: ../../library/exceptions.rst:839 +#: ../../library/exceptions.rst:845 msgid "" "Base class for warnings about deprecated features when those warnings are " "intended for other Python developers." @@ -1362,7 +1380,7 @@ msgstr "" "Classe base para avisos sobre recursos descontinuados quando esses avisos se " "destinam a outros desenvolvedores Python." -#: ../../library/exceptions.rst:842 +#: ../../library/exceptions.rst:848 msgid "" "Ignored by the default warning filters, except in the ``__main__`` module (:" "pep:`565`). Enabling the :ref:`Python Development Mode ` shows this " @@ -1372,11 +1390,11 @@ msgstr "" "`565`). Habilitar o :ref:`Modo de Desenvolvimento do Python ` " "mostra este aviso." -#: ../../library/exceptions.rst:846 ../../library/exceptions.rst:862 +#: ../../library/exceptions.rst:852 ../../library/exceptions.rst:868 msgid "The deprecation policy is described in :pep:`387`." msgstr "A política de descontinuação está descrita na :pep:`387`." -#: ../../library/exceptions.rst:851 +#: ../../library/exceptions.rst:857 msgid "" "Base class for warnings about features which are obsolete and expected to be " "deprecated in the future, but are not deprecated at the moment." @@ -1384,7 +1402,7 @@ msgstr "" "Classe base para avisos sobre recursos que foram descontinuados e devem ser " "descontinuados no futuro, mas não foram descontinuados ainda." -#: ../../library/exceptions.rst:855 +#: ../../library/exceptions.rst:861 msgid "" "This class is rarely used as emitting a warning about a possible upcoming " "deprecation is unusual, and :exc:`DeprecationWarning` is preferred for " @@ -1394,8 +1412,8 @@ msgstr "" "descontinuação futura, é incomum, e :exc:`DeprecationWarning` é preferível " "para descontinuações já ativas." -#: ../../library/exceptions.rst:859 ../../library/exceptions.rst:885 -#: ../../library/exceptions.rst:912 +#: ../../library/exceptions.rst:865 ../../library/exceptions.rst:891 +#: ../../library/exceptions.rst:918 msgid "" "Ignored by the default warning filters. Enabling the :ref:`Python " "Development Mode ` shows this warning." @@ -1403,16 +1421,16 @@ msgstr "" "Ignorado pelos filtros de aviso padrão. Habilitar o :ref:`Modo de " "Desenvolvimento do Python ` mostra este aviso." -#: ../../library/exceptions.rst:867 +#: ../../library/exceptions.rst:873 msgid "Base class for warnings about dubious syntax." msgstr "Classe base para avisos sobre sintaxe duvidosa." -#: ../../library/exceptions.rst:872 +#: ../../library/exceptions.rst:878 msgid "Base class for warnings about dubious runtime behavior." msgstr "" "Classe base para avisos sobre comportamento duvidoso de tempo de execução." -#: ../../library/exceptions.rst:877 +#: ../../library/exceptions.rst:883 msgid "" "Base class for warnings about deprecated features when those warnings are " "intended for end users of applications that are written in Python." @@ -1420,38 +1438,38 @@ msgstr "" "Classe base para avisos sobre recursos descontinuados quando esses avisos se " "destinam a usuários finais de aplicações escritas em Python." -#: ../../library/exceptions.rst:883 +#: ../../library/exceptions.rst:889 msgid "Base class for warnings about probable mistakes in module imports." msgstr "" "Classe base para avisos sobre prováveis erros na importação de módulos." -#: ../../library/exceptions.rst:891 +#: ../../library/exceptions.rst:897 msgid "Base class for warnings related to Unicode." msgstr "Classe base para avisos relacionados a Unicode." -#: ../../library/exceptions.rst:896 +#: ../../library/exceptions.rst:902 msgid "Base class for warnings related to encodings." msgstr "Classe base para avisos relacionados a codificações." -#: ../../library/exceptions.rst:898 +#: ../../library/exceptions.rst:904 msgid "See :ref:`io-encoding-warning` for details." msgstr "Veja :ref:`io-encoding-warning` para detalhes." -#: ../../library/exceptions.rst:905 +#: ../../library/exceptions.rst:911 msgid "" "Base class for warnings related to :class:`bytes` and :class:`bytearray`." msgstr "" "Classe base para avisos relacionados a :class:`bytes` e :class:`bytearray`." -#: ../../library/exceptions.rst:910 +#: ../../library/exceptions.rst:916 msgid "Base class for warnings related to resource usage." msgstr "Classe base para avisos relacionados a uso de recursos." -#: ../../library/exceptions.rst:921 +#: ../../library/exceptions.rst:927 msgid "Exception groups" msgstr "Grupos de exceções" -#: ../../library/exceptions.rst:923 +#: ../../library/exceptions.rst:929 msgid "" "The following are used when it is necessary to raise multiple unrelated " "exceptions. They are part of the exception hierarchy so they can be handled " @@ -1465,7 +1483,7 @@ msgstr "" "disso, eles são reconhecidos por :keyword:`except*`, que " "corresponde a seus subgrupos com base nos tipos de exceções contidas." -#: ../../library/exceptions.rst:932 +#: ../../library/exceptions.rst:938 msgid "" "Both of these exception types wrap the exceptions in the sequence ``excs``. " "The ``msg`` parameter must be a string. The difference between the two " @@ -1483,7 +1501,7 @@ msgstr "" "``except Exception`` capture um :exc:`ExceptionGroup` mas não :exc:" "`BaseExceptionGroup`." -#: ../../library/exceptions.rst:940 +#: ../../library/exceptions.rst:946 msgid "" "The :exc:`BaseExceptionGroup` constructor returns an :exc:`ExceptionGroup` " "rather than a :exc:`BaseExceptionGroup` if all contained exceptions are :exc:" @@ -1498,12 +1516,12 @@ msgstr "" "levanta :exc:`TypeError` se qualquer exceção contida não for uma subclasse " "de :exc:`Exception`." -#: ../../library/exceptions.rst:949 +#: ../../library/exceptions.rst:955 msgid "The ``msg`` argument to the constructor. This is a read-only attribute." msgstr "" "O argumento ``msg`` para o construtor. Este é um atributo somente leitura." -#: ../../library/exceptions.rst:953 +#: ../../library/exceptions.rst:959 msgid "" "A tuple of the exceptions in the ``excs`` sequence given to the constructor. " "This is a read-only attribute." @@ -1511,7 +1529,7 @@ msgstr "" "Uma tupla de exceções na sequência ``excs`` dada ao construtor. Este é um " "atributo somente leitura." -#: ../../library/exceptions.rst:958 +#: ../../library/exceptions.rst:964 msgid "" "Returns an exception group that contains only the exceptions from the " "current group that match *condition*, or ``None`` if the result is empty." @@ -1520,7 +1538,7 @@ msgstr "" "que correspondem à condição *condition* ou ``None`` se o resultado estiver " "vazio." -#: ../../library/exceptions.rst:961 +#: ../../library/exceptions.rst:967 msgid "" "The condition can be an exception type or tuple of exception types, in which " "case each exception is checked for a match using the same check that is used " @@ -1535,7 +1553,7 @@ msgstr "" "único argumento e retorna verdadeiro para a exceção que deve estar no " "subgrupo." -#: ../../library/exceptions.rst:967 +#: ../../library/exceptions.rst:973 msgid "" "The nesting structure of the current exception is preserved in the result, " "as are the values of its :attr:`message`, :attr:`~BaseException." @@ -1549,7 +1567,7 @@ msgstr "" "__context__` e :attr:`~BaseException.__notes__`. Grupos aninhados vazios são " "omitidos do resultado." -#: ../../library/exceptions.rst:974 +#: ../../library/exceptions.rst:980 msgid "" "The condition is checked for all exceptions in the nested exception group, " "including the top-level and any nested exception groups. If the condition is " @@ -1560,12 +1578,12 @@ msgstr "" "aninhadas. Se a condição for verdadeira para tal grupo de exceções, ela será " "incluída no resultado por completo." -#: ../../library/exceptions.rst:978 +#: ../../library/exceptions.rst:984 msgid "``condition`` can be any callable which is not a type object." msgstr "" "``condition`` pode ser qualquer chamável que não seja um objeto de tipo." -#: ../../library/exceptions.rst:983 +#: ../../library/exceptions.rst:989 msgid "" "Like :meth:`subgroup`, but returns the pair ``(match, rest)`` where " "``match`` is ``subgroup(condition)`` and ``rest`` is the remaining non-" @@ -1574,7 +1592,7 @@ msgstr "" "Como :meth:`subgroup`, mas retorna o par ``(match, rest)`` onde ``match`` é " "``subgroup(condition)`` e ``rest`` é a parte restante não correspondente." -#: ../../library/exceptions.rst:989 +#: ../../library/exceptions.rst:995 msgid "" "Returns an exception group with the same :attr:`message`, but which wraps " "the exceptions in ``excs``." @@ -1582,7 +1600,7 @@ msgstr "" "Retorna um grupo de exceções com o mesmo :attr:`message`, mas que agrupa as " "exceções em ``excs``." -#: ../../library/exceptions.rst:992 +#: ../../library/exceptions.rst:998 msgid "" "This method is used by :meth:`subgroup` and :meth:`split`, which are used in " "various contexts to break up an exception group. A subclass needs to " @@ -1594,7 +1612,7 @@ msgstr "" "substituí-la para fazer com que :meth:`subgroup` e :meth:`split` retorne " "instâncias da subclasse em vez de :exc:`ExceptionGroup`." -#: ../../library/exceptions.rst:998 +#: ../../library/exceptions.rst:1004 msgid "" ":meth:`subgroup` and :meth:`split` copy the :attr:`~BaseException." "__traceback__`, :attr:`~BaseException.__cause__`, :attr:`~BaseException." @@ -1608,7 +1626,61 @@ msgstr "" "original para o retornado por :meth:`derive`, então esses campos não " "precisam ser atualizados por :meth:`derive`. ::" -#: ../../library/exceptions.rst:1031 +#: ../../library/exceptions.rst:1011 +msgid "" +">>> class MyGroup(ExceptionGroup):\n" +"... def derive(self, excs):\n" +"... return MyGroup(self.message, excs)\n" +"...\n" +">>> e = MyGroup(\"eg\", [ValueError(1), TypeError(2)])\n" +">>> e.add_note(\"a note\")\n" +">>> e.__context__ = Exception(\"context\")\n" +">>> e.__cause__ = Exception(\"cause\")\n" +">>> try:\n" +"... raise e\n" +"... except Exception as e:\n" +"... exc = e\n" +"...\n" +">>> match, rest = exc.split(ValueError)\n" +">>> exc, exc.__context__, exc.__cause__, exc.__notes__\n" +"(MyGroup('eg', [ValueError(1), TypeError(2)]), Exception('context'), " +"Exception('cause'), ['a note'])\n" +">>> match, match.__context__, match.__cause__, match.__notes__\n" +"(MyGroup('eg', [ValueError(1)]), Exception('context'), Exception('cause'), " +"['a note'])\n" +">>> rest, rest.__context__, rest.__cause__, rest.__notes__\n" +"(MyGroup('eg', [TypeError(2)]), Exception('context'), Exception('cause'), " +"['a note'])\n" +">>> exc.__traceback__ is match.__traceback__ is rest.__traceback__\n" +"True" +msgstr "" +">>> class MyGroup(ExceptionGroup):\n" +"... def derive(self, excs):\n" +"... return MyGroup(self.message, excs)\n" +"...\n" +">>> e = MyGroup(\"eg\", [ValueError(1), TypeError(2)])\n" +">>> e.add_note(\"a note\")\n" +">>> e.__context__ = Exception(\"context\")\n" +">>> e.__cause__ = Exception(\"cause\")\n" +">>> try:\n" +"... raise e\n" +"... except Exception as e:\n" +"... exc = e\n" +"...\n" +">>> match, rest = exc.split(ValueError)\n" +">>> exc, exc.__context__, exc.__cause__, exc.__notes__\n" +"(MyGroup('eg', [ValueError(1), TypeError(2)]), Exception('context'), " +"Exception('cause'), ['a note'])\n" +">>> match, match.__context__, match.__cause__, match.__notes__\n" +"(MyGroup('eg', [ValueError(1)]), Exception('context'), Exception('cause'), " +"['a note'])\n" +">>> rest, rest.__context__, rest.__cause__, rest.__notes__\n" +"(MyGroup('eg', [TypeError(2)]), Exception('context'), Exception('cause'), " +"['a note'])\n" +">>> exc.__traceback__ is match.__traceback__ is rest.__traceback__\n" +"True" + +#: ../../library/exceptions.rst:1037 msgid "" "Note that :exc:`BaseExceptionGroup` defines :meth:`~object.__new__`, so " "subclasses that need a different constructor signature need to override that " @@ -1622,7 +1694,27 @@ msgstr "" "seguinte define uma subclasse de grupo de exceções que aceita um exit_code e " "constrói a mensagem do grupo a partir dele. ::" -#: ../../library/exceptions.rst:1046 +#: ../../library/exceptions.rst:1043 +msgid "" +"class Errors(ExceptionGroup):\n" +" def __new__(cls, errors, exit_code):\n" +" self = super().__new__(Errors, f\"exit code: {exit_code}\", errors)\n" +" self.exit_code = exit_code\n" +" return self\n" +"\n" +" def derive(self, excs):\n" +" return Errors(excs, self.exit_code)" +msgstr "" +"class Errors(ExceptionGroup):\n" +" def __new__(cls, errors, exit_code):\n" +" self = super().__new__(Errors, f\"exit code: {exit_code}\", errors)\n" +" self.exit_code = exit_code\n" +" return self\n" +"\n" +" def derive(self, excs):\n" +" return Errors(excs, self.exit_code)" + +#: ../../library/exceptions.rst:1052 msgid "" "Like :exc:`ExceptionGroup`, any subclass of :exc:`BaseExceptionGroup` which " "is also a subclass of :exc:`Exception` can only wrap instances of :exc:" @@ -1632,14 +1724,154 @@ msgstr "" "que também é uma subclasse de :exc:`Exception` só pode agrupar instâncias " "de :exc:`Exception`." -#: ../../library/exceptions.rst:1054 +#: ../../library/exceptions.rst:1060 msgid "Exception hierarchy" msgstr "Hierarquia das exceções" -#: ../../library/exceptions.rst:1056 +#: ../../library/exceptions.rst:1062 msgid "The class hierarchy for built-in exceptions is:" msgstr "A hierarquia de classes para exceções embutidas é:" +#: ../../library/exceptions.rst:1064 +msgid "" +"BaseException\n" +" ├── BaseExceptionGroup\n" +" ├── GeneratorExit\n" +" ├── KeyboardInterrupt\n" +" ├── SystemExit\n" +" └── Exception\n" +" ├── ArithmeticError\n" +" │ ├── FloatingPointError\n" +" │ ├── OverflowError\n" +" │ └── ZeroDivisionError\n" +" ├── AssertionError\n" +" ├── AttributeError\n" +" ├── BufferError\n" +" ├── EOFError\n" +" ├── ExceptionGroup [BaseExceptionGroup]\n" +" ├── ImportError\n" +" │ └── ModuleNotFoundError\n" +" ├── LookupError\n" +" │ ├── IndexError\n" +" │ └── KeyError\n" +" ├── MemoryError\n" +" ├── NameError\n" +" │ └── UnboundLocalError\n" +" ├── OSError\n" +" │ ├── BlockingIOError\n" +" │ ├── ChildProcessError\n" +" │ ├── ConnectionError\n" +" │ │ ├── BrokenPipeError\n" +" │ │ ├── ConnectionAbortedError\n" +" │ │ ├── ConnectionRefusedError\n" +" │ │ └── ConnectionResetError\n" +" │ ├── FileExistsError\n" +" │ ├── FileNotFoundError\n" +" │ ├── InterruptedError\n" +" │ ├── IsADirectoryError\n" +" │ ├── NotADirectoryError\n" +" │ ├── PermissionError\n" +" │ ├── ProcessLookupError\n" +" │ └── TimeoutError\n" +" ├── ReferenceError\n" +" ├── RuntimeError\n" +" │ ├── NotImplementedError\n" +" │ ├── PythonFinalizationError\n" +" │ └── RecursionError\n" +" ├── StopAsyncIteration\n" +" ├── StopIteration\n" +" ├── SyntaxError\n" +" │ └── IndentationError\n" +" │ └── TabError\n" +" ├── SystemError\n" +" ├── TypeError\n" +" ├── ValueError\n" +" │ └── UnicodeError\n" +" │ ├── UnicodeDecodeError\n" +" │ ├── UnicodeEncodeError\n" +" │ └── UnicodeTranslateError\n" +" └── Warning\n" +" ├── BytesWarning\n" +" ├── DeprecationWarning\n" +" ├── EncodingWarning\n" +" ├── FutureWarning\n" +" ├── ImportWarning\n" +" ├── PendingDeprecationWarning\n" +" ├── ResourceWarning\n" +" ├── RuntimeWarning\n" +" ├── SyntaxWarning\n" +" ├── UnicodeWarning\n" +" └── UserWarning\n" +msgstr "" +"BaseException\n" +" ├── BaseExceptionGroup\n" +" ├── GeneratorExit\n" +" ├── KeyboardInterrupt\n" +" ├── SystemExit\n" +" └── Exception\n" +" ├── ArithmeticError\n" +" │ ├── FloatingPointError\n" +" │ ├── OverflowError\n" +" │ └── ZeroDivisionError\n" +" ├── AssertionError\n" +" ├── AttributeError\n" +" ├── BufferError\n" +" ├── EOFError\n" +" ├── ExceptionGroup [BaseExceptionGroup]\n" +" ├── ImportError\n" +" │ └── ModuleNotFoundError\n" +" ├── LookupError\n" +" │ ├── IndexError\n" +" │ └── KeyError\n" +" ├── MemoryError\n" +" ├── NameError\n" +" │ └── UnboundLocalError\n" +" ├── OSError\n" +" │ ├── BlockingIOError\n" +" │ ├── ChildProcessError\n" +" │ ├── ConnectionError\n" +" │ │ ├── BrokenPipeError\n" +" │ │ ├── ConnectionAbortedError\n" +" │ │ ├── ConnectionRefusedError\n" +" │ │ └── ConnectionResetError\n" +" │ ├── FileExistsError\n" +" │ ├── FileNotFoundError\n" +" │ ├── InterruptedError\n" +" │ ├── IsADirectoryError\n" +" │ ├── NotADirectoryError\n" +" │ ├── PermissionError\n" +" │ ├── ProcessLookupError\n" +" │ └── TimeoutError\n" +" ├── ReferenceError\n" +" ├── RuntimeError\n" +" │ ├── NotImplementedError\n" +" │ ├── PythonFinalizationError\n" +" │ └── RecursionError\n" +" ├── StopAsyncIteration\n" +" ├── StopIteration\n" +" ├── SyntaxError\n" +" │ └── IndentationError\n" +" │ └── TabError\n" +" ├── SystemError\n" +" ├── TypeError\n" +" ├── ValueError\n" +" │ └── UnicodeError\n" +" │ ├── UnicodeDecodeError\n" +" │ ├── UnicodeEncodeError\n" +" │ └── UnicodeTranslateError\n" +" └── Warning\n" +" ├── BytesWarning\n" +" ├── DeprecationWarning\n" +" ├── EncodingWarning\n" +" ├── FutureWarning\n" +" ├── ImportWarning\n" +" ├── PendingDeprecationWarning\n" +" ├── ResourceWarning\n" +" ├── RuntimeWarning\n" +" ├── SyntaxWarning\n" +" ├── UnicodeWarning\n" +" └── UserWarning\n" + #: ../../library/exceptions.rst:6 ../../library/exceptions.rst:17 #: ../../library/exceptions.rst:196 msgid "statement" @@ -1681,10 +1913,10 @@ msgstr "__suppress_context__ (atributo de exceção)" msgid "assert" msgstr "assert" -#: ../../library/exceptions.rst:345 +#: ../../library/exceptions.rst:347 msgid "module" msgstr "módulo" -#: ../../library/exceptions.rst:345 +#: ../../library/exceptions.rst:347 msgid "errno" msgstr "errno" diff --git a/library/faulthandler.po b/library/faulthandler.po index dff6c2206..8f819096b 100644 --- a/library/faulthandler.po +++ b/library/faulthandler.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# And Past , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:05+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -262,3 +260,20 @@ msgid "" "Example of a segmentation fault on Linux with and without enabling the fault " "handler:" msgstr "" + +#: ../../library/faulthandler.rst:178 +msgid "" +"$ python -c \"import ctypes; ctypes.string_at(0)\"\n" +"Segmentation fault\n" +"\n" +"$ python -q -X faulthandler\n" +">>> import ctypes\n" +">>> ctypes.string_at(0)\n" +"Fatal Python error: Segmentation fault\n" +"\n" +"Current thread 0x00007fb899f39700 (most recent call first):\n" +" File \"/home/python/cpython/Lib/ctypes/__init__.py\", line 486 in " +"string_at\n" +" File \"\", line 1 in \n" +"Segmentation fault" +msgstr "" diff --git a/library/fcntl.po b/library/fcntl.po index e4448d527..b51821f68 100644 --- a/library/fcntl.po +++ b/library/fcntl.po @@ -1,32 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-04-25 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/fcntl.rst:2 msgid ":mod:`!fcntl` --- The ``fcntl`` and ``ioctl`` system calls" -msgstr "" +msgstr ":mod:`!fcntl` --- as chamadas de sistema ``fcntl`` e ``ioctl``" #: ../../library/fcntl.rst:16 msgid "" @@ -35,10 +34,14 @@ msgid "" "manpage:`fcntl(2)` and :manpage:`ioctl(2)` Unix manual pages for full " "details." msgstr "" +"Este módulo executa o controle de arquivos e de E/S em descritores de " +"arquivos. É uma interface para as rotinas :c:func:`fcntl` e :c:func:`ioctl` " +"do Unix. Veja as páginas de manual do Unix :manpage:`fcntl(2)` e :manpage:" +"`ioctl(2)` para mais detalhes." #: ../../library/fcntl.rst:21 -msgid ":ref:`Availability `: Unix, not WASI." -msgstr ":ref:`Disponibilidade `: Unix, não WASI." +msgid "Availability" +msgstr "Disponibilidade" #: ../../library/fcntl.rst:23 msgid "" @@ -48,12 +51,19 @@ msgid "" "itself, which provides a :meth:`~io.IOBase.fileno` that returns a genuine " "file descriptor." msgstr "" +"Todas as funções neste módulo recebem um descritor de arquivo *fd* como seu " +"primeiro argumento. Este pode ser um descritor de arquivo inteiro, como " +"retornado por ``sys.stdin.fileno()``, ou um objeto :class:`io.IOBase`, como " +"o próprio ``sys.stdin``, que fornece um :meth:`~io.IOBase.fileno` que " +"retorna um descritor de arquivo genuíno." #: ../../library/fcntl.rst:29 msgid "" "Operations in this module used to raise an :exc:`IOError` where they now " "raise an :exc:`OSError`." msgstr "" +"As operações neste módulo costumavam levantar um :exc:`IOError`, mas agora " +"levantam um :exc:`OSError`." #: ../../library/fcntl.rst:33 msgid "" @@ -61,6 +71,9 @@ msgid "" "``F_SEAL_*`` constants for sealing of :func:`os.memfd_create` file " "descriptors." msgstr "" +"O módulo :mod:`!fcntl` agora contém constantes ``F_ADD_SEALS``, " +"``F_GET_SEALS`` e ``F_SEAL_*`` para selar descritores de arquivo :func:`os." +"memfd_create`." #: ../../library/fcntl.rst:38 msgid "" @@ -70,6 +83,11 @@ msgid "" "``F_OFD_SETLKW`` constants, which are used when working with open file " "description locks." msgstr "" +"No macOS, o módulo :mod:`!fcntl` expõe a constante ``F_GETPATH``, que obtém " +"o caminho de um arquivo de um descritor de arquivo. No Linux(>=3.15), o " +"módulo :mod:`!fcntl` expõe as constantes ``F_OFD_GETLK``, ``F_OFD_SETLK`` e " +"``F_OFD_SETLKW``, que são usadas ao trabalhar com travas de descrição de " +"arquivo aberto." #: ../../library/fcntl.rst:45 msgid "" @@ -77,6 +95,9 @@ msgid "" "and ``F_SETPIPE_SZ`` constants, which allow to check and modify a pipe's " "size respectively." msgstr "" +"No Linux >= 2.6.11, o módulo :mod:`!fcntl` expõe as constantes " +"``F_GETPIPE_SZ`` e ``F_SETPIPE_SZ``, que permitem verificar e modificar o " +"tamanho de um encadeamento, respectivamente." #: ../../library/fcntl.rst:50 msgid "" @@ -84,6 +105,9 @@ msgid "" "``F_DUP2FD_CLOEXEC`` constants, which allow to duplicate a file descriptor, " "the latter setting ``FD_CLOEXEC`` flag in addition." msgstr "" +"No FreeBSD, o módulo :mod:`!fcntl` expõe as constantes ``F_DUP2FD`` e " +"``F_DUP2FD_CLOEXEC``, que permitem duplicar um descritor de arquivo, sendo " +"que esta última define também o sinalizador ``FD_CLOEXEC``." #: ../../library/fcntl.rst:55 msgid "" @@ -92,6 +116,11 @@ msgid "" "another file by reflinking on some filesystems (e.g., btrfs, OCFS2, and " "XFS). This behavior is commonly referred to as \"copy-on-write\"." msgstr "" +"No Linux >= 4.5, o módulo :mod:`fcntl` expõe as constantes ``FICLONE`` e " +"``FICLONERANGE``, que permitem compartilhar alguns dados de um arquivo com " +"outro arquivo por meio de reflinking em alguns sistemas de arquivos (por " +"exemplo, btrfs, OCFS2 e XFS). Esse comportamento é comumente chamado de " +"\"copy-on-write\"." #: ../../library/fcntl.rst:61 msgid "" @@ -113,6 +142,23 @@ msgid "" "macOS and NetBSD, the :mod:`!fcntl` module exposes the ``F_GETNOSIGPIPE`` " "and ``F_SETNOSIGPIPE`` constant." msgstr "" +"No Linux >= 2.6.32, o módulo :mod:`!fcntl` expõe as constantes " +"``F_GETOWN_EX``, ``F_SETOWN_EX``, ``F_OWNER_TID``, ``F_OWNER_PID``, " +"``F_OWNER_PGRP``, que permitem direcionar sinais de disponibilidade de E/S " +"para uma thread, processo ou grupo de processos específico. No Linux >= " +"4.13, o módulo :mod:`!fcntl` expõe as constantes ``F_GET_RW_HINT``, " +"``F_SET_RW_HINT``, ``F_GET_FILE_RW_HINT``, ``F_SET_FILE_RW_HINT`` e " +"``RWH_WRITE_LIFE_*``, que permitem informar o kernel sobre o tempo de vida " +"relativo esperado de gravações em um determinado nó-i ou por meio de uma " +"descrição de arquivo aberto específica. No Linux >= 5.1 e NetBSD, o módulo :" +"mod:`!fcntl` expõe a constante ``F_SEAL_FUTURE_WRITE`` para uso com as " +"operações ``F_ADD_SEALS`` e ``F_GET_SEALS``. No FreeBSD, o módulo :mod:`!" +"fcntl` expõe as constantes ``F_READAHEAD``, ``F_ISUNIONSTACK`` e " +"``F_KINFO``. No macOS e FreeBSD, o módulo :mod:`!fcntl` expõe a constante " +"``F_RDAHEAD``. No NetBSD e AIX, o módulo :mod:`!fcntl` expõe a constante " +"``F_CLOSEM``. No NetBSD, o módulo :mod:`!fcntl` expõe a constante " +"``F_MAXFD``. No macOS e no NetBSD, o módulo :mod:`!fcntl` expõe as " +"constantes ``F_GETNOSIGPIPE`` e ``F_SETNOSIGPIPE``." #: ../../library/fcntl.rst:82 msgid "The module defines the following functions:" @@ -124,24 +170,67 @@ msgid "" "a :meth:`~io.IOBase.fileno` method are accepted as well). The values used " "for *cmd* are operating system dependent, and are available as constants in " "the :mod:`fcntl` module, using the same names as used in the relevant C " -"header files. The argument *arg* can either be an integer value, or a :class:" -"`bytes` object. With an integer value, the return value of this function is " -"the integer return value of the C :c:func:`fcntl` call. When the argument " -"is bytes it represents a binary structure, e.g. created by :func:`struct." -"pack`. The binary data is copied to a buffer whose address is passed to the " -"C :c:func:`fcntl` call. The return value after a successful call is the " -"contents of the buffer, converted to a :class:`bytes` object. The length of " -"the returned object will be the same as the length of the *arg* argument. " -"This is limited to 1024 bytes. If the information returned in the buffer by " -"the operating system is larger than 1024 bytes, this is most likely to " -"result in a segmentation violation or a more subtle data corruption." -msgstr "" - -#: ../../library/fcntl.rst:104 +"header files. The argument *arg* can either be an integer value, a :class:" +"`bytes` object, or a string. The type and size of *arg* must match the type " +"and size of the argument of the operation as specified in the relevant C " +"documentation." +msgstr "" +"Executa a operação *cmd* no descritor de arquivo *fd* (objetos arquivo que " +"fornecem um método :meth:`~io.IOBase.fileno` também são aceitos). Os valores " +"usados ​​para *cmd* dependem do sistema operacional e estão disponíveis como " +"constantes no módulo :mod:`fcntl`, usando os mesmos nomes usados ​​nos " +"arquivos de cabeçalho C relevantes. O argumento *arg* pode ser um valor " +"inteiro, um objeto :class:`bytes` ou uma string. O tipo e o tamanho de *arg* " +"devem corresponder ao tipo e ao tamanho do argumento da operação, conforme " +"especificado na documentação C relevante." + +#: ../../library/fcntl.rst:96 +msgid "" +"When *arg* is an integer, the function returns the integer return value of " +"the C :c:func:`fcntl` call." +msgstr "" +"Quando *arg* é um inteiro, a função retorna o valor de retorno inteiro da " +"chamada C :c:func:`fcntl`." + +#: ../../library/fcntl.rst:99 +msgid "" +"When the argument is bytes, it represents a binary structure, for example, " +"created by :func:`struct.pack`. A string value is encoded to binary using " +"the UTF-8 encoding. The binary data is copied to a buffer whose address is " +"passed to the C :c:func:`fcntl` call. The return value after a successful " +"call is the contents of the buffer, converted to a :class:`bytes` object. " +"The length of the returned object will be the same as the length of the " +"*arg* argument. This is limited to 1024 bytes." +msgstr "" +"Quando o argumento é bytes, ele representa uma estrutura binária, por " +"exemplo, criada por :func:`struct.pack`. Um valor de string é codificado em " +"binário usando a codificação UTF-8. Os dados binários são copiados para um " +"buffer cujo endereço é passado para a chamada :c:func:`fcntl` em C. O valor " +"de retorno após uma chamada bem-sucedida é o conteúdo do buffer, convertido " +"em um objeto :class:`bytes`. O comprimento do objeto retornado será igual ao " +"comprimento do argumento *arg*. Este é limitado a 1024 bytes." + +#: ../../library/fcntl.rst:108 msgid "If the :c:func:`fcntl` call fails, an :exc:`OSError` is raised." msgstr "" +"Se a chamada a :c:func:`fcntl` falhar, um exceção :exc:`OSError` é levantada." + +#: ../../library/fcntl.rst:111 +msgid "" +"If the type or the size of *arg* does not match the type or size of the " +"argument of the operation (for example, if an integer is passed when a " +"pointer is expected, or the information returned in the buffer by the " +"operating system is larger than 1024 bytes), this is most likely to result " +"in a segmentation violation or a more subtle data corruption." +msgstr "" +"Se o tipo ou o tamanho de *arg* não corresponder ao tipo ou tamanho do " +"argumento da operação (por exemplo, se um inteiro for passado quando um " +"ponteiro for esperado, ou se as informações retornadas no buffer pelo " +"sistema operacional forem maiores que 1024 bytes), é mais provável que isso " +"resulte em uma violação de segmentação ou em uma corrupção de dados mais " +"sutil." -#: ../../library/fcntl.rst:106 +#: ../../library/fcntl.rst:118 msgid "" "Raises an :ref:`auditing event ` ``fcntl.fcntl`` with arguments " "``fd``, ``cmd``, ``arg``." @@ -149,68 +238,119 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``fcntl.fcntl`` com os " "argumentos ``fd``, ``cmd``, ``arg``." -#: ../../library/fcntl.rst:111 +#: ../../library/fcntl.rst:123 msgid "" "This function is identical to the :func:`~fcntl.fcntl` function, except that " "the argument handling is even more complicated." msgstr "" +"Esta função é idêntica à função :func:`~fcntl.fcntl`, exceto que o " +"tratamento de argumentos é ainda mais complicado." -#: ../../library/fcntl.rst:114 +#: ../../library/fcntl.rst:126 msgid "" -"The *request* parameter is limited to values that can fit in 32-bits. " -"Additional constants of interest for use as the *request* argument can be " -"found in the :mod:`termios` module, under the same names as used in the " -"relevant C header files." +"The *request* parameter is limited to values that can fit in 32-bits or 64-" +"bits, depending on the platform. Additional constants of interest for use as " +"the *request* argument can be found in the :mod:`termios` module, under the " +"same names as used in the relevant C header files." msgstr "" +"O parâmetro *request* é limitado a valores que cabem em 32 ou 64 bits, " +"dependendo da plataforma. Constantes adicionais de interesse para uso como " +"argumento *request* podem ser encontradas no módulo :mod:`termios`, com os " +"mesmos nomes usados ​​nos arquivos de cabeçalho C relevantes." -#: ../../library/fcntl.rst:119 +#: ../../library/fcntl.rst:132 msgid "" -"The parameter *arg* can be one of an integer, an object supporting the read-" -"only buffer interface (like :class:`bytes`) or an object supporting the read-" -"write buffer interface (like :class:`bytearray`)." +"The parameter *arg* can be an integer, a :term:`bytes-like object`, or a " +"string. The type and size of *arg* must match the type and size of the " +"argument of the operation as specified in the relevant C documentation." msgstr "" +"O parâmetro *arg* pode ser um inteiro, um :term:`objeto bytes ou similar` ou " +"uma string. O tipo e o tamanho de *arg* devem corresponder ao tipo e ao " +"tamanho do argumento da operação, conforme especificado na documentação C " +"relevante." -#: ../../library/fcntl.rst:123 +#: ../../library/fcntl.rst:137 msgid "" -"In all but the last case, behaviour is as for the :func:`~fcntl.fcntl` " -"function." +"If *arg* does not support the read-write buffer interface or the " +"*mutate_flag* is false, behavior is as for the :func:`~fcntl.fcntl` function." msgstr "" +"Se *arg* não oferecer suporte à interface de buffer de leitura e escrita ou " +"o *mutate_flag* for falso, o comportamento será o mesmo da função :func:" +"`~fcntl.fcntl`." -#: ../../library/fcntl.rst:126 +#: ../../library/fcntl.rst:141 msgid "" -"If a mutable buffer is passed, then the behaviour is determined by the value " -"of the *mutate_flag* parameter." +"If *arg* supports the read-write buffer interface (like :class:`bytearray`) " +"and *mutate_flag* is true (the default), then the buffer is (in effect) " +"passed to the underlying :c:func:`!ioctl` system call, the latter's return " +"code is passed back to the calling Python, and the buffer's new contents " +"reflect the action of the :c:func:`ioctl`. This is a slight simplification, " +"because if the supplied buffer is less than 1024 bytes long it is first " +"copied into a static buffer 1024 bytes long which is then passed to :func:" +"`ioctl` and copied back into the supplied buffer." msgstr "" +"Se *arg* oferece suporte à interface de buffer de leitura e escrita (como :" +"class:`bytearray`) e *mutate_flag* for true (o padrão), o buffer será (na " +"prática) passado para a chamada de sistema subjacente :c:func:`!ioctl`, o " +"código de retorno desta última será passado de volta para o Python que fez a " +"chamada, e o novo conteúdo do buffer refletirá a ação de :c:func:`ioctl`. " +"Esta é uma pequena simplificação, pois se o buffer fornecido tiver menos de " +"1024 bytes, ele será primeiro copiado para um buffer estático de 1024 bytes, " +"que será então passado para :func:`ioctl` e copiado de volta para o buffer " +"fornecido." -#: ../../library/fcntl.rst:129 +#: ../../library/fcntl.rst:150 msgid "" -"If it is false, the buffer's mutability is ignored and behaviour is as for a " -"read-only buffer, except that the 1024 byte limit mentioned above is avoided " -"-- so long as the buffer you pass is at least as long as what the operating " -"system wants to put there, things should work." +"If the :c:func:`ioctl` call fails, an :exc:`OSError` exception is raised." msgstr "" +"Se a chamada a :c:func:`ioctl` falhar, uma exceção :exc:`OSError` é " +"levantada." -#: ../../library/fcntl.rst:134 +#: ../../library/fcntl.rst:153 msgid "" -"If *mutate_flag* is true (the default), then the buffer is (in effect) " -"passed to the underlying :func:`ioctl` system call, the latter's return code " -"is passed back to the calling Python, and the buffer's new contents reflect " -"the action of the :func:`ioctl`. This is a slight simplification, because " -"if the supplied buffer is less than 1024 bytes long it is first copied into " -"a static buffer 1024 bytes long which is then passed to :func:`ioctl` and " -"copied back into the supplied buffer." +"If the type or size of *arg* does not match the type or size of the " +"operation's argument (for example, if an integer is passed when a pointer is " +"expected, or the information returned in the buffer by the operating system " +"is larger than 1024 bytes, or the size of the mutable bytes-like object is " +"too small), this is most likely to result in a segmentation violation or a " +"more subtle data corruption." msgstr "" +"Se o tipo ou o tamanho de *arg* não corresponder ao tipo ou tamanho do " +"argumento da operação (por exemplo, se um inteiro for passado quando um " +"ponteiro for esperado, ou se as informações retornadas no buffer pelo " +"sistema operacional forem maiores que 1024 bytes ou o tamanho do objeto byte " +"ou similar mutável é pequeno demais), é mais provável que isso resulte em " +"uma violação de segmentação ou em uma corrupção de dados mais sutil." -#: ../../library/fcntl.rst:142 -msgid "" -"If the :c:func:`ioctl` call fails, an :exc:`OSError` exception is raised." -msgstr "" - -#: ../../library/fcntl.rst:144 +#: ../../library/fcntl.rst:161 msgid "An example::" msgstr "Um exemplo::" -#: ../../library/fcntl.rst:157 +#: ../../library/fcntl.rst:163 +msgid "" +">>> import array, fcntl, struct, termios, os\n" +">>> os.getpgrp()\n" +"13341\n" +">>> struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, \" \"))[0]\n" +"13341\n" +">>> buf = array.array('h', [0])\n" +">>> fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1)\n" +"0\n" +">>> buf\n" +"array('h', [13341])" +msgstr "" +">>> import array, fcntl, struct, termios, os\n" +">>> os.getpgrp()\n" +"13341\n" +">>> struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, \" \"))[0]\n" +"13341\n" +">>> buf = array.array('h', [0])\n" +">>> fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1)\n" +"0\n" +">>> buf\n" +"array('h', [13341])" + +#: ../../library/fcntl.rst:174 msgid "" "Raises an :ref:`auditing event ` ``fcntl.ioctl`` with arguments " "``fd``, ``request``, ``arg``." @@ -218,20 +358,26 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``fcntl.ioctl`` com os " "argumentos ``fd``, ``request``, ``arg``." -#: ../../library/fcntl.rst:162 +#: ../../library/fcntl.rst:179 msgid "" "Perform the lock operation *operation* on file descriptor *fd* (file objects " "providing a :meth:`~io.IOBase.fileno` method are accepted as well). See the " "Unix manual :manpage:`flock(2)` for details. (On some systems, this " "function is emulated using :c:func:`fcntl`.)" msgstr "" +"Executa a operação de trava *operation* no descritor de arquivo *fd* " +"(objetos arquivo que fornecem um método :meth:`~io.IOBase.fileno` também são " +"aceitos). Consulte o manual do Unix :manpage:`flock(2)` para obter detalhes. " +"(Em alguns sistemas, esta função é emulada usando :c:func:`fcntl`.)" -#: ../../library/fcntl.rst:167 +#: ../../library/fcntl.rst:184 msgid "" "If the :c:func:`flock` call fails, an :exc:`OSError` exception is raised." msgstr "" +"Se a chamada :c:func:`flock` falhar, uma exceção :exc:`OSError` será " +"levantada." -#: ../../library/fcntl.rst:169 +#: ../../library/fcntl.rst:186 msgid "" "Raises an :ref:`auditing event ` ``fcntl.flock`` with arguments " "``fd``, ``operation``." @@ -239,33 +385,39 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``fcntl.flock`` com os " "argumentos ``fd`` e ``operation``." -#: ../../library/fcntl.rst:174 +#: ../../library/fcntl.rst:191 msgid "" "This is essentially a wrapper around the :func:`~fcntl.fcntl` locking calls. " "*fd* is the file descriptor (file objects providing a :meth:`~io.IOBase." "fileno` method are accepted as well) of the file to lock or unlock, and " "*cmd* is one of the following values:" msgstr "" +"Este é essencialmente um invólucro em torno das chamadas de trava :func:" +"`~fcntl.fcntl`. *fd* é o descritor de arquivo (objetos arquivo que fornecem " +"um método :meth:`~io.IOBase.fileno` também são aceitos) do arquivo para " +"travar ou destravar, e *cmd* é um dos seguintes valores:" -#: ../../library/fcntl.rst:181 +#: ../../library/fcntl.rst:198 msgid "Release an existing lock." -msgstr "" +msgstr "Libera uma trava existente." -#: ../../library/fcntl.rst:185 +#: ../../library/fcntl.rst:202 msgid "Acquire a shared lock." -msgstr "" +msgstr "Adquire uma trava compartilhada." -#: ../../library/fcntl.rst:189 +#: ../../library/fcntl.rst:206 msgid "Acquire an exclusive lock." -msgstr "" +msgstr "Adquire uma trava exclusiva." -#: ../../library/fcntl.rst:193 +#: ../../library/fcntl.rst:210 msgid "" "Bitwise OR with any of the other three ``LOCK_*`` constants to make the " "request non-blocking." msgstr "" +"Aplica OU (OR) bit a bit com qualquer uma das outras três constantes " +"``LOCK_*`` para tornar a solicitação não bloqueante." -#: ../../library/fcntl.rst:196 +#: ../../library/fcntl.rst:213 msgid "" "If :const:`!LOCK_NB` is used and the lock cannot be acquired, an :exc:" "`OSError` will be raised and the exception will have an *errno* attribute " @@ -274,34 +426,46 @@ msgid "" "systems, :const:`!LOCK_EX` can only be used if the file descriptor refers to " "a file opened for writing." msgstr "" +"Se :const:`!LOCK_NB` for usado e a trava não puder ser obtido, uma exceção :" +"exc:`OSError` será levantada e terá um atributo *errno* definido como :const:" +"`~errno.EACCES` ou :const:`~errno.EAGAIN` (dependendo do sistema " +"operacional; para portabilidade, verifique ambos os valores). Em pelo menos " +"alguns sistemas, :const:`!LOCK_EX` só pode ser usado se o descritor de " +"arquivo se referir a um arquivo aberto para escrita." -#: ../../library/fcntl.rst:203 +#: ../../library/fcntl.rst:220 msgid "" "*len* is the number of bytes to lock, *start* is the byte offset at which " "the lock starts, relative to *whence*, and *whence* is as with :func:`io." "IOBase.seek`, specifically:" msgstr "" +"*len* é o número de bytes para travar, *start* é o deslocamento de bytes em " +"que a trava começa, em relação a *whence*, e *whence* é como em :func:`io." +"IOBase.seek`, especificamente:" -#: ../../library/fcntl.rst:207 +#: ../../library/fcntl.rst:224 msgid "``0`` -- relative to the start of the file (:const:`os.SEEK_SET`)" -msgstr "" +msgstr "``0`` -- relativo ao início do arquivo (:const:`os.SEEK_SET`)" -#: ../../library/fcntl.rst:208 +#: ../../library/fcntl.rst:225 msgid "``1`` -- relative to the current buffer position (:const:`os.SEEK_CUR`)" -msgstr "" +msgstr "``1`` -- relativo à posição atual do buffer (:const:`os.SEEK_CUR`)" -#: ../../library/fcntl.rst:209 +#: ../../library/fcntl.rst:226 msgid "``2`` -- relative to the end of the file (:const:`os.SEEK_END`)" -msgstr "" +msgstr "``2`` -- relativo ao fim do arquivo (:const:`os.SEEK_END`)" -#: ../../library/fcntl.rst:211 +#: ../../library/fcntl.rst:228 msgid "" "The default for *start* is 0, which means to start at the beginning of the " "file. The default for *len* is 0 which means to lock to the end of the " "file. The default for *whence* is also 0." msgstr "" +"O padrão para *start* é 0, o que significa iniciar no início do arquivo. O " +"padrão para *len* é 0, o que significa travar no final do arquivo. O padrão " +"para *whence* também é 0." -#: ../../library/fcntl.rst:215 +#: ../../library/fcntl.rst:232 msgid "" "Raises an :ref:`auditing event ` ``fcntl.lockf`` with arguments " "``fd``, ``cmd``, ``len``, ``start``, ``whence``." @@ -309,28 +473,53 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``fcntl.lockf`` com os " "argumentos ``fd``, ``cmd``, ``len``, ``start``, ``whence``." -#: ../../library/fcntl.rst:217 +#: ../../library/fcntl.rst:234 msgid "Examples (all on a SVR4 compliant system)::" +msgstr "Exemplos (todos em um sistema compatível com SVR4)::" + +#: ../../library/fcntl.rst:236 +msgid "" +"import struct, fcntl, os\n" +"\n" +"f = open(...)\n" +"rv = fcntl.fcntl(f, fcntl.F_SETFL, os.O_NDELAY)\n" +"\n" +"lockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)\n" +"rv = fcntl.fcntl(f, fcntl.F_SETLKW, lockdata)" msgstr "" +"import struct, fcntl, os\n" +"\n" +"f = open(...)\n" +"rv = fcntl.fcntl(f, fcntl.F_SETFL, os.O_NDELAY)\n" +"\n" +"lockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)\n" +"rv = fcntl.fcntl(f, fcntl.F_SETLKW, lockdata)" -#: ../../library/fcntl.rst:227 +#: ../../library/fcntl.rst:244 msgid "" "Note that in the first example the return value variable *rv* will hold an " "integer value; in the second example it will hold a :class:`bytes` object. " "The structure lay-out for the *lockdata* variable is system dependent --- " "therefore using the :func:`flock` call may be better." msgstr "" +"Observe que, no primeiro exemplo, a variável de valor de retorno *rv* " +"conterá um valor inteiro; no segundo exemplo, ela conterá um objeto :class:" +"`bytes`. O layout da estrutura da variável *lockdata* depende do sistema --- " +"portanto, usar a chamada :func:`flock` pode ser melhor." -#: ../../library/fcntl.rst:235 +#: ../../library/fcntl.rst:252 msgid "Module :mod:`os`" msgstr "Módulo :mod:`os`" -#: ../../library/fcntl.rst:236 +#: ../../library/fcntl.rst:253 msgid "" "If the locking flags :const:`~os.O_SHLOCK` and :const:`~os.O_EXLOCK` are " "present in the :mod:`os` module (on BSD only), the :func:`os.open` function " "provides an alternative to the :func:`lockf` and :func:`flock` functions." msgstr "" +"Se os sinalizadores de trava :const:`~os.O_SHLOCK` e :const:`~os.O_EXLOCK` " +"estiverem presentes no módulo :mod:`os` (somente no BSD), a função :func:`os." +"open` fornece uma alternativa às funções :func:`lockf` e :func:`flock`." #: ../../library/fcntl.rst:10 msgid "UNIX" @@ -338,7 +527,7 @@ msgstr "UNIX" #: ../../library/fcntl.rst:10 msgid "file control" -msgstr "" +msgstr "controle de arquivo" #: ../../library/fcntl.rst:10 msgid "I/O control" diff --git a/library/filecmp.po b/library/filecmp.po index fefd2abea..82d8641a2 100644 --- a/library/filecmp.po +++ b/library/filecmp.po @@ -1,32 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 02:33+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/filecmp.rst:2 msgid ":mod:`!filecmp` --- File and Directory Comparisons" -msgstr "" +msgstr ":mod:`!filecmp` --- Comparações de arquivos e diretórios" #: ../../library/filecmp.rst:9 msgid "**Source code:** :source:`Lib/filecmp.py`" @@ -38,16 +37,21 @@ msgid "" "directories, with various optional time/correctness trade-offs. For " "comparing files, see also the :mod:`difflib` module." msgstr "" +"O módulo :mod:`filecmp` define funções para comparar arquivos e diretórios, " +"com várias compensações opcionais de tempo/correção. Para comparar arquivos, " +"veja também o módulo :mod:`difflib`." #: ../../library/filecmp.rst:17 msgid "The :mod:`filecmp` module defines the following functions:" -msgstr "" +msgstr "O módulo :mod:`filecmp` define as seguintes funções:" #: ../../library/filecmp.rst:22 msgid "" "Compare the files named *f1* and *f2*, returning ``True`` if they seem " "equal, ``False`` otherwise." msgstr "" +"Compara os arquivos chamados *f1* e *f2*, retornando ``True`` se eles " +"parecerem iguais, ``False`` caso contrário." #: ../../library/filecmp.rst:25 msgid "" @@ -55,18 +59,25 @@ msgid "" "and modification time) of both files are identical, the files are taken to " "be equal." msgstr "" +"Se *shallow* for verdadeiro e as assinaturas de :func:`os.stat` (tipo de " +"arquivo, tamanho e hora de modificação) de ambos os arquivos forem " +"idênticas, os arquivos serão considerados iguais." #: ../../library/filecmp.rst:29 msgid "" "Otherwise, the files are treated as different if their sizes or contents " "differ." msgstr "" +"Caso contrário, os arquivos serão tratados como diferentes se seus tamanhos " +"ou conteúdos forem diferentes." #: ../../library/filecmp.rst:31 msgid "" "Note that no external programs are called from this function, giving it " "portability and efficiency." msgstr "" +"Observe que nenhum programa externo é chamado a partir desta função, o que " +"lhe confere portabilidade e eficiência." #: ../../library/filecmp.rst:34 msgid "" @@ -74,12 +85,17 @@ msgid "" "entries invalidated if the :func:`os.stat` information for the file " "changes. The entire cache may be cleared using :func:`clear_cache`." msgstr "" +"Esta função usa um cache para comparações passadas e os resultados, com " +"entradas de cache invalidadas se as informações de :func:`os.stat` para o " +"arquivo mudarem. O cache inteiro pode ser limpo usando :func:`clear_cache`." #: ../../library/filecmp.rst:41 msgid "" "Compare the files in the two directories *dir1* and *dir2* whose names are " "given by *common*." msgstr "" +"Compara os arquivos nos dois diretórios *dir1* e *dir2* cujos nomes são " +"dados por *common*." #: ../../library/filecmp.rst:44 msgid "" @@ -90,12 +106,20 @@ msgid "" "directories, the user lacks permission to read them or if the comparison " "could not be done for some other reason." msgstr "" +"Retorna três listas de nomes de arquivos: *match*, *mismatch*, *errors*. " +"*match* contém a lista de arquivos que correspondem, *mismatch* contém os " +"nomes daqueles que não correspondem e *errors* lista os nomes dos arquivos " +"que não puderam ser comparados. Os arquivos são listados em *errors* se não " +"existirem em um dos diretórios, o usuário não tiver permissão para lê-los ou " +"se a comparação não puder ser feita por algum outro motivo." #: ../../library/filecmp.rst:51 msgid "" "The *shallow* parameter has the same meaning and default value as for :func:" "`filecmp.cmp`." msgstr "" +"O parâmetro *shallow* tem o mesmo significado e valor padrão que :func:" +"`filecmp.cmp`." #: ../../library/filecmp.rst:54 msgid "" @@ -103,6 +127,9 @@ msgid "" "``b/c`` and ``a/d/e`` with ``b/d/e``. ``'c'`` and ``'d/e'`` will each be in " "one of the three returned lists." msgstr "" +"Por exemplo, ``cmpfiles('a', 'b', ['c', 'd/e'])`` comparará ``a/c`` com ``b/" +"c`` e ``a/d/e`` com ``b/d/e``. ``'c'`` e ``'d/e'`` estarão cada um em uma " +"das três listas retornadas." #: ../../library/filecmp.rst:61 msgid "" @@ -110,6 +137,9 @@ msgid "" "after it is modified that it is within the mtime resolution of the " "underlying filesystem." msgstr "" +"Limpa o cache do filecmp. Isso pode ser útil se um arquivo for comparado tão " +"rapidamente após ser modificado que ele esteja dentro da resolução de mtime " +"do sistema de arquivos subjacente." #: ../../library/filecmp.rst:71 msgid "The :class:`dircmp` class" @@ -122,35 +152,43 @@ msgid "" "`filecmp.DEFAULT_IGNORES`. *hide* is a list of names to hide, and defaults " "to ``[os.curdir, os.pardir]``." msgstr "" +"Constrói um novo objeto de comparação de diretórios para comparar os " +"diretórios *a* e *b*. *ignore* é uma lista de nomes a serem ignorados e o " +"padrão é :const:`filecmp.DEFAULT_IGNORES`. *hide* é uma lista de nomes a " +"serem ocultados e o padrão é ``[os.curdir, os.pardir]``." #: ../../library/filecmp.rst:80 msgid "" "The :class:`dircmp` class compares files by doing *shallow* comparisons as " "described for :func:`filecmp.cmp` by default using the *shallow* parameter." msgstr "" +"A classe :class:`dircmp` compara arquivos fazendo comparações rasas, isto é, " +"*shallow* conforme descrito para :func:`filecmp.cmp` por padrão usando o " +"parâmetro *shallow*." #: ../../library/filecmp.rst:86 msgid "Added the *shallow* parameter." -msgstr "" +msgstr "Adicionado o parâmetro *shallow*." #: ../../library/filecmp.rst:88 msgid "The :class:`dircmp` class provides the following methods:" -msgstr "" +msgstr "A classe :class:`dircmp` fornece os seguintes métodos:" #: ../../library/filecmp.rst:92 msgid "Print (to :data:`sys.stdout`) a comparison between *a* and *b*." -msgstr "" +msgstr "Exibe (para :data:`sys.stdout`) uma comparação entre *a* e *b*." #: ../../library/filecmp.rst:96 msgid "" "Print a comparison between *a* and *b* and common immediate subdirectories." -msgstr "" +msgstr "Exibe uma comparação entre *a* e *b* e subdiretórios imediatos comuns." #: ../../library/filecmp.rst:101 msgid "" "Print a comparison between *a* and *b* and common subdirectories " "(recursively)." msgstr "" +"Exibe uma comparação entre *a* e *b* e subdiretórios comuns (recursivamente)." #: ../../library/filecmp.rst:104 msgid "" @@ -158,6 +196,9 @@ msgid "" "be used to get various bits of information about the directory trees being " "compared." msgstr "" +"A classe :class:`dircmp` oferece uma série de atributos interessantes que " +"podem ser usados para obter várias informações sobre as árvores de " +"diretórios que estão sendo comparadas." #: ../../library/filecmp.rst:108 msgid "" @@ -165,38 +206,41 @@ msgid "" "lazily, so there is no speed penalty if only those attributes which are " "lightweight to compute are used." msgstr "" +"Observe que, por meio dos ganchos :meth:`~object.__getattr__`, todos os " +"atributos são computados preguiçosamente, portanto, não há perda de " +"velocidade se apenas os atributos que são leves para computar forem usados." #: ../../library/filecmp.rst:115 msgid "The directory *a*." -msgstr "" +msgstr "O diretório *a*." #: ../../library/filecmp.rst:120 msgid "The directory *b*." -msgstr "" +msgstr "O diretório *b*." #: ../../library/filecmp.rst:125 msgid "Files and subdirectories in *a*, filtered by *hide* and *ignore*." -msgstr "" +msgstr "Arquivos e subdiretórios em *a*, filtrados por *hide* e *ignore*." #: ../../library/filecmp.rst:130 msgid "Files and subdirectories in *b*, filtered by *hide* and *ignore*." -msgstr "" +msgstr "Arquivos e subdiretórios em *b*, filtrados por *hide* e *ignore*." #: ../../library/filecmp.rst:135 msgid "Files and subdirectories in both *a* and *b*." -msgstr "" +msgstr "Arquivos e subdiretórios em *a* e *b*." #: ../../library/filecmp.rst:140 msgid "Files and subdirectories only in *a*." -msgstr "" +msgstr "Arquivos e subdiretórios em apenas *a*." #: ../../library/filecmp.rst:145 msgid "Files and subdirectories only in *b*." -msgstr "" +msgstr "Arquivos e subdiretórios em apenas *b*." #: ../../library/filecmp.rst:150 msgid "Subdirectories in both *a* and *b*." -msgstr "" +msgstr "Subdiretórios em *a* e *b*." #: ../../library/filecmp.rst:155 msgid "Files in both *a* and *b*." @@ -207,22 +251,28 @@ msgid "" "Names in both *a* and *b*, such that the type differs between the " "directories, or names for which :func:`os.stat` reports an error." msgstr "" +"Nomes em *a* e *b*, de modo que o tipo difere entre os diretórios, ou nomes " +"para os quais :func:`os.stat` relata um erro." #: ../../library/filecmp.rst:166 msgid "" "Files which are identical in both *a* and *b*, using the class's file " "comparison operator." msgstr "" +"Arquivos que são idênticos em *a* e *b*, usando o operador de comparação de " +"arquivos da classe." #: ../../library/filecmp.rst:172 msgid "" "Files which are in both *a* and *b*, whose contents differ according to the " "class's file comparison operator." msgstr "" +"Arquivos que estão em *a* e *b*, cujos conteúdos diferem de acordo com o " +"operador de comparação de arquivos da classe." #: ../../library/filecmp.rst:178 msgid "Files which are in both *a* and *b*, but could not be compared." -msgstr "" +msgstr "Arquivos que estão em *a* e *b*, mas não puderam ser comparados." #: ../../library/filecmp.rst:183 msgid "" @@ -230,19 +280,52 @@ msgid "" "instances (or MyDirCmp instances if this instance is of type MyDirCmp, a " "subclass of :class:`dircmp`)." msgstr "" +"Um dicionário que mapeia nomes em :attr:`common_dirs` para instâncias :class:" +"`dircmp` (ou instâncias MyDirCmp se esta instância for do tipo MyDirCmp, uma " +"subclasse de :class:`dircmp`)." #: ../../library/filecmp.rst:187 msgid "" "Previously entries were always :class:`dircmp` instances. Now entries are " "the same type as *self*, if *self* is a subclass of :class:`dircmp`." msgstr "" +"Anteriormente, as entradas eram sempre instâncias de :class:`dircmp`. Agora, " +"as entradas são do mesmo tipo que *self*, se *self* for uma subclasse de :" +"class:`dircmp`." #: ../../library/filecmp.rst:196 msgid "List of directories ignored by :class:`dircmp` by default." -msgstr "" +msgstr "Lista de diretórios ignorados por :class:`dircmp` por padrão." #: ../../library/filecmp.rst:199 msgid "" "Here is a simplified example of using the ``subdirs`` attribute to search " "recursively through two directories to show common different files::" msgstr "" +"Aqui está um exemplo simplificado do uso do atributo ``subdirs`` para " +"pesquisar recursivamente em dois diretórios para mostrar arquivos diferentes " +"em comum:" + +#: ../../library/filecmp.rst:202 +msgid "" +">>> from filecmp import dircmp\n" +">>> def print_diff_files(dcmp):\n" +"... for name in dcmp.diff_files:\n" +"... print(\"diff_file %s found in %s and %s\" % (name, dcmp.left,\n" +"... dcmp.right))\n" +"... for sub_dcmp in dcmp.subdirs.values():\n" +"... print_diff_files(sub_dcmp)\n" +"...\n" +">>> dcmp = dircmp('dir1', 'dir2')\n" +">>> print_diff_files(dcmp)" +msgstr "" +">>> from filecmp import dircmp\n" +">>> def print_diff_files(dcmp):\n" +"... for name in dcmp.diff_files:\n" +"... print(\"diff_file %s found in %s and %s\" % (name, dcmp.left,\n" +"... dcmp.right))\n" +"... for sub_dcmp in dcmp.subdirs.values():\n" +"... print_diff_files(sub_dcmp)\n" +"...\n" +">>> dcmp = dircmp('dir1', 'dir2')\n" +">>> print_diff_files(dcmp)" diff --git a/library/fileformats.po b/library/fileformats.po index 7738bb04a..935582b5a 100644 --- a/library/fileformats.po +++ b/library/fileformats.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Erick Simões , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: Erick Simões , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/fileinput.po b/library/fileinput.po index 296a7b8f9..17f07d538 100644 --- a/library/fileinput.po +++ b/library/fileinput.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-05 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -47,6 +46,16 @@ msgstr "" msgid "The typical use is::" msgstr "O uso típico é::" +#: ../../library/fileinput.rst:20 +msgid "" +"import fileinput\n" +"for line in fileinput.input(encoding=\"utf-8\"):\n" +" process(line)" +msgstr "" +"import fileinput\n" +"for line in fileinput.input(encoding=\"utf-8\"):\n" +" process(line)" + #: ../../library/fileinput.rst:24 msgid "" "This iterates over the lines of all files listed in ``sys.argv[1:]``, " @@ -123,7 +132,7 @@ msgstr "" "abertura através do parâmetro *openhook* para :func:`fileinput.input` ou :" "func:`FileInput`. O gancho deve ser uma função que recebe dois argumentos, " "*filename* e *mode*, e retorna um objeto arquivo ou similar aberto de " -"acordo. Se *encoding* e/ou *errors* forem especificados, eles serão passados ​​" +"acordo. Se *encoding* e/ou *errors* forem especificados, eles serão passados " "para o gancho como argumentos nomeados adicionais. Este módulo fornece um :" "func:`hook_compressed` para oferece suporte a arquivos compactados." @@ -140,7 +149,7 @@ msgid "" msgstr "" "Cria uma instância da classe :class:`FileInput`. A instância será usada como " "estado global para as funções deste módulo e também será retornada para uso " -"durante a iteração. Os parâmetros desta função serão passados ​​para o " +"durante a iteração. Os parâmetros desta função serão passados para o " "construtor da classe :class:`FileInput`." #: ../../library/fileinput.rst:66 @@ -153,6 +162,18 @@ msgstr "" "contexto na instrução :keyword:`with`. Neste exemplo, *input* é fechado após " "a saída da instrução :keyword:`!with`, mesmo se ocorrer uma exceção::" +#: ../../library/fileinput.rst:70 +msgid "" +"with fileinput.input(files=('spam.txt', 'eggs.txt'), encoding=\"utf-8\") as " +"f:\n" +" for line in f:\n" +" process(line)" +msgstr "" +"with fileinput.input(files=('spam.txt', 'eggs.txt'), encoding=\"utf-8\") as " +"f:\n" +" for line in f:\n" +" process(line)" + #: ../../library/fileinput.rst:74 ../../library/fileinput.rst:170 msgid "Can be used as a context manager." msgstr "Pode ser usado como gerenciador de contexto." @@ -301,7 +322,7 @@ msgid "" "You can specify *encoding* and *errors* that is passed to :func:`open` or " "*openhook*." msgstr "" -"Você pode especificar *encoding* e *errors* que são passados ​​para :func:" +"Você pode especificar *encoding* e *errors* que são passados para :func:" "`open` ou *openhook*." #: ../../library/fileinput.rst:163 @@ -314,6 +335,14 @@ msgstr "" "contexto na instrução :keyword:`with`. Neste exemplo, *input* é fechado após " "a saída da instrução :keyword:`!with`, mesmo se ocorrer uma exceção::" +#: ../../library/fileinput.rst:167 +msgid "" +"with FileInput(files=('spam.txt', 'eggs.txt')) as input:\n" +" process(input)" +msgstr "" +"with FileInput(files=('spam.txt', 'eggs.txt')) as input:\n" +" process(input)" + #: ../../library/fileinput.rst:173 msgid "The keyword parameter *mode* and *openhook* are now keyword-only." msgstr "Os parâmetros nomeados *mode* e *openhook* agora são somente-nomeados." @@ -372,7 +401,7 @@ msgid "" "The *encoding* and *errors* values are passed to :class:`io.TextIOWrapper` " "for compressed files and open for normal files." msgstr "" -"Os valores *encoding* e *errors* são passados ​​para :class:`io.TextIOWrapper` " +"Os valores *encoding* e *errors* são passados para :class:`io.TextIOWrapper` " "para arquivos compactados e abertos para arquivos normais." #: ../../library/fileinput.rst:208 diff --git a/library/filesys.po b/library/filesys.po index 305b98641..b28b2c5e3 100644 --- a/library/filesys.po +++ b/library/filesys.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Claudio Rogerio Carvalho Filho , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: Claudio Rogerio Carvalho Filho , " -"2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -41,11 +39,11 @@ msgstr "" "arquivos, manipular o caminhos de forma multiplataforma e para criar " "arquivos temporários. A lista completa de módulos neste capítulo é:" -#: ../../library/filesys.rst:29 +#: ../../library/filesys.rst:28 msgid "Module :mod:`os`" msgstr "Módulo :mod:`os`" -#: ../../library/filesys.rst:30 +#: ../../library/filesys.rst:29 msgid "" "Operating system interfaces, including functions to work with files at a " "lower level than Python :term:`file objects `." @@ -54,11 +52,11 @@ msgstr "" "arquivos num nível inferior a :term:`objetos arquivos ` do " "Python." -#: ../../library/filesys.rst:33 +#: ../../library/filesys.rst:32 msgid "Module :mod:`io`" msgstr "Módulo :mod:`io`" -#: ../../library/filesys.rst:34 +#: ../../library/filesys.rst:33 msgid "" "Python's built-in I/O library, including both abstract classes and some " "concrete classes such as file I/O." @@ -66,10 +64,10 @@ msgstr "" "A biblioteca embutida de E/S do Python, incluindo as classes abstratas e " "algumas classes concretas, como E/S de arquivos." -#: ../../library/filesys.rst:37 +#: ../../library/filesys.rst:36 msgid "Built-in function :func:`open`" msgstr "Função embutida :func:`open`" -#: ../../library/filesys.rst:38 +#: ../../library/filesys.rst:37 msgid "The standard way to open files for reading and writing with Python." msgstr "A maneira padrão de abrir arquivos para ler e escrever em Python." diff --git a/library/fnmatch.po b/library/fnmatch.po index 0f5ddfc9e..9c7a9ac36 100644 --- a/library/fnmatch.po +++ b/library/fnmatch.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Welington Carlos , 2021 -# i17obot , 2021 -# Claudio Rogerio Carvalho Filho , 2023 -# Marco Rougeth , 2023 -# Adorilson Bezerra , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-17 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -111,15 +106,29 @@ msgstr "" #: ../../library/fnmatch.rst:49 msgid "" -"Also note that :func:`functools.lru_cache` with the *maxsize* of 32768 is " -"used to cache the compiled regex patterns in the following functions: :func:" -"`fnmatch`, :func:`fnmatchcase`, :func:`.filter`." +"Unless stated otherwise, \"filename string\" and \"pattern string\" either " +"refer to :class:`str` or ``ISO-8859-1`` encoded :class:`bytes` objects. Note " +"that the functions documented below do not allow to mix a :class:`!bytes` " +"pattern with a :class:`!str` filename, and vice-versa." msgstr "" -"Observe também que :func:`functools.lru_cache` com *maxsize* de 32768 é " -"usado para armazenar em cache os padrões de regex compilados nas seguintes " -"funções: :func:`fnmatch`, :func:`fnmatchcase`, :func:`.filter`." +"A menos que indicado de outra forma, \"string de nome de arquivo\" e " +"\"string de padrão\" referem-se a objetos :class:`str` ou :class:`bytes` " +"codificados em ``ISO-8859-1``. Observe que as funções documentadas abaixo " +"não permitem misturar um padrão :class:`!bytes` com um nome de arquivo :" +"class:`!str` e vice-versa." -#: ../../library/fnmatch.rst:55 +#: ../../library/fnmatch.rst:54 +msgid "" +"Finally, note that :func:`functools.lru_cache` with a *maxsize* of 32768 is " +"used to cache the (typed) compiled regex patterns in the following " +"functions: :func:`fnmatch`, :func:`fnmatchcase`, :func:`.filter`." +msgstr "" +"Finalmente, observe também que :func:`functools.lru_cache` com um *maxsize* " +"de 32768 é usado para armazenar em cache os padrões de regex compilados " +"(tipados) nas seguintes funções: :func:`fnmatch`, :func:`fnmatchcase`, :func:" +"`.filter`." + +#: ../../library/fnmatch.rst:61 msgid "" "Test whether the filename string *name* matches the pattern string *pat*, " "returning ``True`` or ``False``. Both parameters are case-normalized using :" @@ -134,7 +143,7 @@ msgstr "" "entre maiúsculas e minúsculas, independentemente de ser padrão para o " "sistema operacional." -#: ../../library/fnmatch.rst:61 +#: ../../library/fnmatch.rst:67 msgid "" "This example will print all file names in the current directory with the " "extension ``.txt``::" @@ -142,7 +151,23 @@ msgstr "" "Este exemplo vai exibir todos os nomes de arquivos no diretório atual com a " "extensão ``.txt``::" -#: ../../library/fnmatch.rst:74 +#: ../../library/fnmatch.rst:70 +msgid "" +"import fnmatch\n" +"import os\n" +"\n" +"for file in os.listdir('.'):\n" +" if fnmatch.fnmatch(file, '*.txt'):\n" +" print(file)" +msgstr "" +"import fnmatch\n" +"import os\n" +"\n" +"for arquivo in os.listdir('.'):\n" +" if fnmatch.fnmatch(arquivo, '*.txt'):\n" +" print(arquivo)" + +#: ../../library/fnmatch.rst:80 msgid "" "Test whether the filename string *name* matches the pattern string *pat*, " "returning ``True`` or ``False``; the comparison is case-sensitive and does " @@ -152,33 +177,34 @@ msgstr "" "*pat*, retornando ``True`` ou ``False``; a comparação diferencia maiúsculas " "de minúsculas e não se aplica a :func:`os.path.normcase`." -#: ../../library/fnmatch.rst:81 +#: ../../library/fnmatch.rst:87 msgid "" -"Construct a list from those elements of the :term:`iterable` *names* that " -"match pattern *pat*. It is the same as ``[n for n in names if fnmatch(n, " -"pat)]``, but implemented more efficiently." +"Construct a list from those elements of the :term:`iterable` of filename " +"strings *names* that match the pattern string *pat*. It is the same as ``[n " +"for n in names if fnmatch(n, pat)]``, but implemented more efficiently." msgstr "" -"Constrói uma lista a partir daqueles elementos do :term:`iterável` *names* " -"que correspondem ao padrão *pat*. É o mesmo que ``[n for n in names if " -"fnmatch(n, pat)]``, mas implementado com mais eficiência." +"Constrói uma lista a partir daqueles elementos do :term:`iterável` de " +"strings de nome de arquivo *names* que correspondem à string de padrão " +"*pat*. É o mesmo que ``[n for n in names if fnmatch(n, pat)]``, mas " +"implementado com mais eficiência." -#: ../../library/fnmatch.rst:89 +#: ../../library/fnmatch.rst:95 msgid "" "Return the shell-style pattern *pat* converted to a regular expression for " -"using with :func:`re.match`." +"using with :func:`re.match`. The pattern is expected to be a :class:`str`." msgstr "" "Retorna o padrão *pat* no estilo shell convertido em uma expressão regular " -"para usar com :func:`re.match`." +"para usar com :func:`re.match`. O padrão é esperado ser um :class:`str`." -#: ../../library/fnmatch.rst:92 +#: ../../library/fnmatch.rst:98 msgid "Example:" msgstr "Exemplo:" -#: ../../library/fnmatch.rst:106 +#: ../../library/fnmatch.rst:112 msgid "Module :mod:`glob`" msgstr "Módulo :mod:`glob`" -#: ../../library/fnmatch.rst:107 +#: ../../library/fnmatch.rst:113 msgid "Unix shell-style path expansion." msgstr "Expansão de caminho no estilo shell do Unix." diff --git a/library/fractions.po b/library/fractions.po index 643c8ff7d..8cc344889 100644 --- a/library/fractions.po +++ b/library/fractions.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -78,6 +78,10 @@ msgstr "" "`limit_denominator` abaixo.) A última versão do construtor espera uma " "instância de string ou unicode. A forma usual para esta instância é::" +#: ../../library/fractions.rst:41 +msgid "[sign] numerator ['/' denominator]" +msgstr "[sinal] numerador ['/' denominador]" + #: ../../library/fractions.rst:43 msgid "" "where the optional ``sign`` may be either '+' or '-' and ``numerator`` and " @@ -90,12 +94,64 @@ msgid "" msgstr "" "onde o ``sign`` opcional pode ser '+' ou '-' e ``numerator`` e " "``denominator`` (se presente) são strings de dígitos decimais (sublinhados " -"podem ser usados ​​para delimitar dígitos como com literais integrais no " +"podem ser usados para delimitar dígitos como com literais integrais no " "código). Além disso, qualquer string que represente um valor finito e seja " "aceita pelo construtor :class:`float` também é aceita pelo construtor :class:" "`Fraction`. Em qualquer forma, a string de entrada também pode ter espaços " "em branco à esquerda e/ou à direita. Aqui estão alguns exemplos::" +#: ../../library/fractions.rst:52 +msgid "" +">>> from fractions import Fraction\n" +">>> Fraction(16, -10)\n" +"Fraction(-8, 5)\n" +">>> Fraction(123)\n" +"Fraction(123, 1)\n" +">>> Fraction()\n" +"Fraction(0, 1)\n" +">>> Fraction('3/7')\n" +"Fraction(3, 7)\n" +">>> Fraction(' -3/7 ')\n" +"Fraction(-3, 7)\n" +">>> Fraction('1.414213 \\t\\n')\n" +"Fraction(1414213, 1000000)\n" +">>> Fraction('-.125')\n" +"Fraction(-1, 8)\n" +">>> Fraction('7e-6')\n" +"Fraction(7, 1000000)\n" +">>> Fraction(2.25)\n" +"Fraction(9, 4)\n" +">>> Fraction(1.1)\n" +"Fraction(2476979795053773, 2251799813685248)\n" +">>> from decimal import Decimal\n" +">>> Fraction(Decimal('1.1'))\n" +"Fraction(11, 10)" +msgstr "" +">>> from fractions import Fraction\n" +">>> Fraction(16, -10)\n" +"Fraction(-8, 5)\n" +">>> Fraction(123)\n" +"Fraction(123, 1)\n" +">>> Fraction()\n" +"Fraction(0, 1)\n" +">>> Fraction('3/7')\n" +"Fraction(3, 7)\n" +">>> Fraction(' -3/7 ')\n" +"Fraction(-3, 7)\n" +">>> Fraction('1.414213 \\t\\n')\n" +"Fraction(1414213, 1000000)\n" +">>> Fraction('-.125')\n" +"Fraction(-1, 8)\n" +">>> Fraction('7e-6')\n" +"Fraction(7, 1000000)\n" +">>> Fraction(2.25)\n" +"Fraction(9, 4)\n" +">>> Fraction(1.1)\n" +"Fraction(2476979795053773, 2251799813685248)\n" +">>> from decimal import Decimal\n" +">>> Fraction(Decimal('1.1'))\n" +"Fraction(11, 10)" + #: ../../library/fractions.rst:78 msgid "" "The :class:`Fraction` class inherits from the abstract base class :class:" @@ -318,6 +374,46 @@ msgstr "" msgid "Here are some examples::" msgstr "Veja alguns exemplos::" +#: ../../library/fractions.rst:229 +msgid "" +">>> from fractions import Fraction\n" +">>> format(Fraction(103993, 33102), '_')\n" +"'103_993/33_102'\n" +">>> format(Fraction(1, 7), '.^+10')\n" +"'...+1/7...'\n" +">>> format(Fraction(3, 1), '')\n" +"'3'\n" +">>> format(Fraction(3, 1), '#')\n" +"'3/1'\n" +">>> format(Fraction(1, 7), '.40g')\n" +"'0.1428571428571428571428571428571428571429'\n" +">>> format(Fraction('1234567.855'), '_.2f')\n" +"'1_234_567.86'\n" +">>> f\"{Fraction(355, 113):*>20.6e}\"\n" +"'********3.141593e+00'\n" +">>> old_price, new_price = 499, 672\n" +">>> \"{:.2%} price increase\".format(Fraction(new_price, old_price) - 1)\n" +"'34.67% price increase'" +msgstr "" +">>> from fractions import Fraction\n" +">>> format(Fraction(103993, 33102), '_')\n" +"'103_993/33_102'\n" +">>> format(Fraction(1, 7), '.^+10')\n" +"'...+1/7...'\n" +">>> format(Fraction(3, 1), '')\n" +"'3'\n" +">>> format(Fraction(3, 1), '#')\n" +"'3/1'\n" +">>> format(Fraction(1, 7), '.40g')\n" +"'0.1428571428571428571428571428571428571429'\n" +">>> format(Fraction('1234567.855'), '_.2f')\n" +"'1_234_567.86'\n" +">>> f\"{Fraction(355, 113):*>20.6e}\"\n" +"'********3.141593e+00'\n" +">>> old_price, new_price = 499, 672\n" +">>> \"{:.2%} price increase\".format(Fraction(new_price, old_price) - 1)\n" +"'34.67% price increase'" + #: ../../library/fractions.rst:251 msgid "Module :mod:`numbers`" msgstr "Módulo :mod:`numbers`" diff --git a/library/frameworks.po b/library/frameworks.po index d4d7ce813..be76ed833 100644 --- a/library/frameworks.po +++ b/library/frameworks.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Claudio Rogerio Carvalho Filho , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: Claudio Rogerio Carvalho Filho , " -"2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/ftplib.po b/library/ftplib.po index 0e7129bc4..13313e4a8 100644 --- a/library/ftplib.po +++ b/library/ftplib.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2024 -# Claudio Rogerio Carvalho Filho , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -48,8 +46,8 @@ msgid "The default encoding is UTF-8, following :rfc:`2640`." msgstr "" #: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +msgid "Availability" +msgstr "Disponibilidade" #: ../../includes/wasm-notavail.rst:5 msgid "" @@ -63,6 +61,28 @@ msgstr "" msgid "Here's a sample session using the :mod:`ftplib` module::" msgstr "" +#: ../../library/ftplib.rst:28 +msgid "" +">>> from ftplib import FTP\n" +">>> ftp = FTP('ftp.us.debian.org') # connect to host, default port\n" +">>> ftp.login() # user anonymous, passwd anonymous@\n" +"'230 Login successful.'\n" +">>> ftp.cwd('debian') # change into \"debian\" directory\n" +"'250 Directory successfully changed.'\n" +">>> ftp.retrlines('LIST') # list directory contents\n" +"-rw-rw-r-- 1 1176 1176 1063 Jun 15 10:18 README\n" +"...\n" +"drwxr-sr-x 5 1176 1176 4096 Dec 19 2000 pool\n" +"drwxr-sr-x 4 1176 1176 4096 Nov 17 2008 project\n" +"drwxr-xr-x 3 1176 1176 4096 Oct 10 2012 tools\n" +"'226 Directory send OK.'\n" +">>> with open('README', 'wb') as fp:\n" +">>> ftp.retrbinary('RETR README', fp.write)\n" +"'226 Transfer complete.'\n" +">>> ftp.quit()\n" +"'221 Goodbye.'" +msgstr "" + #: ../../library/ftplib.rst:51 msgid "Reference" msgstr "Referência" @@ -491,12 +511,29 @@ msgstr "" #: ../../library/ftplib.rst:511 msgid "The deprecated *keyfile* and *certfile* parameters have been removed." -msgstr "" +msgstr "Os parâmetros depreciados *keyfile* e *certfile* foram removidos." #: ../../library/ftplib.rst:514 msgid "Here's a sample session using the :class:`FTP_TLS` class::" msgstr "" +#: ../../library/ftplib.rst:516 +msgid "" +">>> ftps = FTP_TLS('ftp.pureftpd.org')\n" +">>> ftps.login()\n" +"'230 Anonymous user logged in'\n" +">>> ftps.prot_p()\n" +"'200 Data protection level set to \"private\"'\n" +">>> ftps.nlst()\n" +"['6jack', 'OpenBSD', 'antilink', 'blogbench', 'bsdcam', 'clockspeed', " +"'djbdns-jedi', 'docs', 'eaccelerator-jedi', 'favicon.ico', 'francotone', " +"'fugu', 'ignore', 'libpuzzle', 'metalog', 'minidentd', 'misc', 'mysql-udf-" +"global-user-variables', 'php-jenkins-hash', 'php-skein-hash', 'php-webdav', " +"'phpaudit', 'phpbench', 'pincaster', 'ping', 'posto', 'pub', 'public', " +"'public_keys', 'pure-ftpd', 'qscan', 'qtc', 'sharedance', 'skycache', " +"'sound', 'tmp', 'ucarp']" +msgstr "" + #: ../../library/ftplib.rst:524 msgid "" ":class:`!FTP_TLS` class inherits from :class:`FTP`, defining these " diff --git a/library/functional.po b/library/functional.po index 3de66ec5e..1c810244c 100644 --- a/library/functional.po +++ b/library/functional.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/functions.po b/library/functions.po index ebb71cdcb..9e5ac8a20 100644 --- a/library/functions.po +++ b/library/functions.po @@ -1,39 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Misael borges , 2021 -# Welington Carlos , 2021 -# Italo Penaforte , 2021 -# VERUSKA RODRIGUES DA SILVA , 2021 -# felipe caridade fernandes , 2021 -# (Douglas da Silva) , 2021 -# Katyanna Moura , 2021 -# João Porfirio, 2021 -# Vinicius Gubiani Ferreira , 2023 -# i17obot , 2024 -# Marco Rougeth , 2024 -# Claudio Rogerio Carvalho Filho , 2024 -# Pedro Fonini, 2024 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -446,6 +432,20 @@ msgstr "" "Retorna ``True`` se todos os elementos de *iterable* são verdadeiros (ou se " "*iterable* estiver vazio). Equivalente a::" +#: ../../library/functions.rst:79 +msgid "" +"def all(iterable):\n" +" for element in iterable:\n" +" if not element:\n" +" return False\n" +" return True" +msgstr "" +"def all(iterable):\n" +" for elemento in iterable:\n" +" if not elemento:\n" +" return False\n" +" return True" + #: ../../library/functions.rst:89 msgid "" "When awaited, return the next item from the given :term:`asynchronous " @@ -482,6 +482,20 @@ msgstr "" "Retorna ``True`` se algum elemento de *iterable* for verdadeiro. Se " "*iterable* estiver vazio, retorna ``False``. Equivalente a::" +#: ../../library/functions.rst:107 +msgid "" +"def any(iterable):\n" +" for element in iterable:\n" +" if element:\n" +" return True\n" +" return False" +msgstr "" +"def any(iterable):\n" +" for elemento in iterable:\n" +" if elemento:\n" +" return True\n" +" return False" + #: ../../library/functions.rst:116 msgid "" "As :func:`repr`, return a string containing a printable representation of an " @@ -514,8 +528,8 @@ msgstr "" "Se o prefixo \"0b\" é desejado ou não, você pode usar uma das seguintes " "maneiras." -#: ../../library/functions.rst:141 ../../library/functions.rst:929 -#: ../../library/functions.rst:1308 +#: ../../library/functions.rst:141 ../../library/functions.rst:942 +#: ../../library/functions.rst:1323 msgid "See also :func:`format` for more information." msgstr "Veja também :func:`format` para mais informações." @@ -535,7 +549,7 @@ msgstr "" "`typesnumeric`). Ela não pode ser usada para criar outra subclasse. Suas " "únicas instâncias são ``False`` e ``True`` (veja :ref:`typebool`)." -#: ../../library/functions.rst:156 ../../library/functions.rst:794 +#: ../../library/functions.rst:156 ../../library/functions.rst:807 msgid "The parameter is now positional-only." msgstr "O parâmetro agora é somente-posicional" @@ -543,7 +557,7 @@ msgstr "O parâmetro agora é somente-posicional" msgid "" "This function drops you into the debugger at the call site. Specifically, " "it calls :func:`sys.breakpointhook`, passing ``args`` and ``kws`` straight " -"through. By default, ``sys.breakpointhook()`` calls :func:`pdb.set_trace()` " +"through. By default, ``sys.breakpointhook()`` calls :func:`pdb.set_trace` " "expecting no arguments. In this case, it is purely a convenience function " "so you don't have to explicitly import :mod:`pdb` or type as much code to " "enter the debugger. However, :func:`sys.breakpointhook` can be set to some " @@ -554,8 +568,8 @@ msgstr "" "Esta função coloca você no depurador no local da chamada. Especificamente, " "ela chama :func:`sys.breakpointhook`, passando ``args`` e ``kws`` " "diretamente. Por padrão, ``sys.breakpointhook()`` chama :func:`pdb." -"set_trace()` não esperando nenhum argumento. Neste caso, isso é puramente " -"uma função de conveniência para você não precisar importar :mod:`pdb` " +"set_trace` não esperando nenhum argumento. Neste caso, isso é puramente uma " +"função de conveniência para você não precisar importar :mod:`pdb` " "explicitamente ou digitar mais código para entrar no depurador. Contudo, :" "func:`sys.breakpointhook` pode ser configurado para alguma outra função e :" "func:`breakpoint` irá automaticamente chamá-la, permitindo você ir para o " @@ -736,6 +750,16 @@ msgstr "" "exatamente como um método de instância recebe a instância. Para declarar um " "método de classe, faça dessa forma::" +#: ../../library/functions.rst:265 +msgid "" +"class C:\n" +" @classmethod\n" +" def f(cls, arg1, arg2): ..." +msgstr "" +"class C:\n" +" @classmethod\n" +" def f(cls, arg1, arg2): ..." + #: ../../library/functions.rst:269 msgid "" "The ``@classmethod`` form is a function :term:`decorator` -- see :ref:" @@ -776,15 +800,17 @@ msgstr "" #: ../../library/functions.rst:285 msgid "" -"Class methods now inherit the method attributes (``__module__``, " -"``__name__``, ``__qualname__``, ``__doc__`` and ``__annotations__``) and " -"have a new ``__wrapped__`` attribute." +"Class methods now inherit the method attributes (:attr:`~function." +"__module__`, :attr:`~function.__name__`, :attr:`~function.__qualname__`, :" +"attr:`~function.__doc__` and :attr:`~function.__annotations__`) and have a " +"new ``__wrapped__`` attribute." msgstr "" -"Métodos de classe agora herdam os atributos do método (``__module__``, " -"``__name__``, ``__qualname__``, ``__doc__`` e ``__annotations__``) e têm um " -"novo atributo ``__wrapped__``." +"Métodos de classe agora herdam os atributos do método (:attr:`~function." +"__module__`, :attr:`~function.__name__`, :attr:`~function.__qualname__`, :" +"attr:`~function.__doc__` e :attr:`~function.__annotations__`) e têm um novo " +"atributo ``__wrapped__``." -#: ../../library/functions.rst:290 +#: ../../library/functions.rst:292 msgid "" "Class methods can no longer wrap other :term:`descriptors ` such " "as :func:`property`." @@ -792,7 +818,7 @@ msgstr "" "Métodos de classe não podem mais envolver outros :term:`descritores " "` tal como :func:`property`." -#: ../../library/functions.rst:297 +#: ../../library/functions.rst:299 msgid "" "Compile the *source* into a code or AST object. Code objects can be " "executed by :func:`exec` or :func:`eval`. *source* can either be a normal " @@ -804,7 +830,7 @@ msgstr "" "string normal, uma string byte, ou um objeto AST. Consulte a documentação do " "módulo :mod:`ast` para saber como trabalhar com objetos AST." -#: ../../library/functions.rst:302 +#: ../../library/functions.rst:304 msgid "" "The *filename* argument should give the file from which the code was read; " "pass some recognizable value if it wasn't read from a file (``''`` " @@ -814,7 +840,7 @@ msgstr "" "algum valor reconhecível se isso não foi lido de um arquivo (``''`` " "é comumente usado)." -#: ../../library/functions.rst:306 +#: ../../library/functions.rst:308 msgid "" "The *mode* argument specifies what kind of code must be compiled; it can be " "``'exec'`` if *source* consists of a sequence of statements, ``'eval'`` if " @@ -828,7 +854,7 @@ msgstr "" "de uma única instrução interativa (neste último caso, instruções que são " "avaliadas para alguma coisa diferente de ``None`` serão exibidas)." -#: ../../library/functions.rst:312 +#: ../../library/functions.rst:314 msgid "" "The optional arguments *flags* and *dont_inherit* control which :ref:" "`compiler options ` should be activated and which :ref:" @@ -853,7 +879,7 @@ msgstr "" "-- os sinalizadores (recursos futuros e opções do compilador) no código " "circundante são ignorados." -#: ../../library/functions.rst:323 +#: ../../library/functions.rst:325 msgid "" "Compiler options and future statements are specified by bits which can be " "bitwise ORed together to specify multiple options. The bitfield required to " @@ -870,7 +896,7 @@ msgstr "" "`Sinalizadores de compilador ` podem ser encontrados no " "módulo :mod:`ast`, com o prefixo ``PyCF_``." -#: ../../library/functions.rst:331 +#: ../../library/functions.rst:333 msgid "" "The argument *optimize* specifies the optimization level of the compiler; " "the default value of ``-1`` selects the optimization level of the " @@ -885,7 +911,7 @@ msgstr "" "``__debug__`` é falso) ou ``2`` (strings de documentação também são " "removidas)." -#: ../../library/functions.rst:337 +#: ../../library/functions.rst:339 msgid "" "This function raises :exc:`SyntaxError` if the compiled source is invalid, " "and :exc:`ValueError` if the source contains null bytes." @@ -893,7 +919,7 @@ msgstr "" "Essa função levanta :exc:`SyntaxError` se o código para compilar é inválido, " "e :exc:`ValueError` se o código contém bytes nulos." -#: ../../library/functions.rst:340 +#: ../../library/functions.rst:342 msgid "" "If you want to parse Python code into its AST representation, see :func:`ast." "parse`." @@ -901,7 +927,7 @@ msgstr "" "Se você quer analisar código Python em sua representação AST, veja :func:" "`ast.parse`." -#: ../../library/functions.rst:343 ../../library/functions.rst:345 +#: ../../library/functions.rst:345 ../../library/functions.rst:347 msgid "" "Raises an :ref:`auditing event ` ``compile`` with arguments " "``source`` and ``filename``. This event may also be raised by implicit " @@ -911,7 +937,7 @@ msgstr "" "argumentos ``source``, ``filename``. Esse evento pode também ser levantando " "por uma compilação implícita." -#: ../../library/functions.rst:351 +#: ../../library/functions.rst:353 msgid "" "When compiling a string with multi-line code in ``'single'`` or ``'eval'`` " "mode, input must be terminated by at least one newline character. This is " @@ -923,7 +949,7 @@ msgstr "" "linhas. Isso é para facilitar a detecção de instruções completas e " "incompletas no módulo :mod:`code`." -#: ../../library/functions.rst:358 +#: ../../library/functions.rst:360 msgid "" "It is possible to crash the Python interpreter with a sufficiently large/" "complex string when compiling to an AST object due to stack depth " @@ -933,7 +959,7 @@ msgstr "" "grande/complexa ao compilar para um objeto AST, devido limitações do tamanho " "da pilha no compilador AST do Python." -#: ../../library/functions.rst:362 +#: ../../library/functions.rst:364 msgid "" "Allowed use of Windows and Mac newlines. Also, input in ``'exec'`` mode " "does not have to end in a newline anymore. Added the *optimize* parameter." @@ -942,7 +968,7 @@ msgstr "" "disso, em modo ``'exec'`` a entrada não precisa mais terminar com uma nova " "linha. Também foi adicionado o parâmetro *optimize*." -#: ../../library/functions.rst:366 +#: ../../library/functions.rst:368 msgid "" "Previously, :exc:`TypeError` was raised when null bytes were encountered in " "*source*." @@ -950,7 +976,7 @@ msgstr "" "Anteriormente, :exc:`TypeError` era levantada quando havia bytes nulos em " "*source*." -#: ../../library/functions.rst:370 +#: ../../library/functions.rst:372 msgid "" "``ast.PyCF_ALLOW_TOP_LEVEL_AWAIT`` can now be passed in flags to enable " "support for top-level ``await``, ``async for``, and ``async with``." @@ -959,7 +985,7 @@ msgstr "" "habilitar o suporte em nível superior a ``await``, ``async for``, e ``async " "with``." -#: ../../library/functions.rst:379 +#: ../../library/functions.rst:381 msgid "" "Convert a single string or number to a complex number, or create a complex " "number from real and imaginary parts." @@ -967,12 +993,48 @@ msgstr "" "Converte uma única string ou número para um número complexo, ou cria um " "número complexo a partir de partes real e imaginária." -#: ../../library/functions.rst:382 ../../library/functions.rst:739 -#: ../../library/functions.rst:985 +#: ../../library/functions.rst:384 ../../library/functions.rst:752 +#: ../../library/functions.rst:998 msgid "Examples:" msgstr "Exemplos:" -#: ../../library/functions.rst:403 +#: ../../library/functions.rst:386 +msgid "" +">>> complex('+1.23')\n" +"(1.23+0j)\n" +">>> complex('-4.5j')\n" +"-4.5j\n" +">>> complex('-1.23+4.5j')\n" +"(-1.23+4.5j)\n" +">>> complex('\\t( -1.23+4.5J )\\n')\n" +"(-1.23+4.5j)\n" +">>> complex('-Infinity+NaNj')\n" +"(-inf+nanj)\n" +">>> complex(1.23)\n" +"(1.23+0j)\n" +">>> complex(imag=-4.5)\n" +"-4.5j\n" +">>> complex(-1.23, 4.5)\n" +"(-1.23+4.5j)" +msgstr "" +">>> complex('+1.23')\n" +"(1.23+0j)\n" +">>> complex('-4.5j')\n" +"-4.5j\n" +">>> complex('-1.23+4.5j')\n" +"(-1.23+4.5j)\n" +">>> complex('\\t( -1.23+4.5J )\\n')\n" +"(-1.23+4.5j)\n" +">>> complex('-Infinity+NaNj')\n" +"(-inf+nanj)\n" +">>> complex(1.23)\n" +"(1.23+0j)\n" +">>> complex(imag=-4.5)\n" +"-4.5j\n" +">>> complex(-1.23, 4.5)\n" +"(-1.23+4.5j)" + +#: ../../library/functions.rst:405 msgid "" "If the argument is a string, it must contain either a real part (in the same " "format as for :func:`float`) or an imaginary part (in the same format but " @@ -999,7 +1061,7 @@ msgstr "" "conforme a regra de produção :token:`~float:complexvalue` da gramática a " "seguir:" -#: ../../library/functions.rst:422 +#: ../../library/functions.rst:424 msgid "" "If the argument is a number, the constructor serves as a numeric conversion " "like :class:`int` and :class:`float`. For a general Python object ``x``, " @@ -1015,7 +1077,7 @@ msgstr "" "`~object.__float__`. Se :meth:`!__float__` não está definido então a chamada " "é, novamente, repassada para :meth:`~object.__index__`." -#: ../../library/functions.rst:431 +#: ../../library/functions.rst:433 msgid "" "If two arguments are provided or keyword arguments are used, each argument " "may be any numeric type (including complex). If both arguments are real " @@ -1034,21 +1096,21 @@ msgstr "" "for um número real, somente a sua parte real é usada nas expressões " "anteriores." -#: ../../library/functions.rst:441 +#: ../../library/functions.rst:443 msgid "If all arguments are omitted, returns ``0j``." msgstr "Se todos os argumentos forem omitidos, retorna ``0j``." -#: ../../library/functions.rst:443 +#: ../../library/functions.rst:445 msgid "The complex type is described in :ref:`typesnumeric`." msgstr "O tipo complexo está descrito em :ref:`typesnumeric`." -#: ../../library/functions.rst:445 ../../library/functions.rst:791 -#: ../../library/functions.rst:1034 +#: ../../library/functions.rst:447 ../../library/functions.rst:804 +#: ../../library/functions.rst:1047 msgid "Grouping digits with underscores as in code literals is allowed." msgstr "" "Agrupar dígitos com sublinhados como em literais de código é permitido." -#: ../../library/functions.rst:448 +#: ../../library/functions.rst:450 msgid "" "Falls back to :meth:`~object.__index__` if :meth:`~object.__complex__` and :" "meth:`~object.__float__` are not defined." @@ -1056,7 +1118,7 @@ msgstr "" "Chamadas para :meth:`~object.__index__` se :meth:`~object.__complex__` e :" "meth:`~object.__float__` não estão definidas." -#: ../../library/functions.rst:455 +#: ../../library/functions.rst:457 msgid "" "This is a relative of :func:`setattr`. The arguments are an object and a " "string. The string must be the name of one of the object's attributes. The " @@ -1070,7 +1132,7 @@ msgstr "" "exemplo, ``delattr(x, 'foobar')`` é equivalente a ``del x.foobar``. *name* " "não precisa ser um identificador Python (veja :func:`setattr`)." -#: ../../library/functions.rst:468 +#: ../../library/functions.rst:470 msgid "" "Create a new dictionary. The :class:`dict` object is the dictionary class. " "See :class:`dict` and :ref:`typesmapping` for documentation about this class." @@ -1078,7 +1140,7 @@ msgstr "" "Cria um novo dicionário. O objeto :class:`dict` é a classe do dicionário. " "Veja :class:`dict` e :ref:`typesmapping` para documentação sobre esta classe." -#: ../../library/functions.rst:471 +#: ../../library/functions.rst:473 msgid "" "For other containers see the built-in :class:`list`, :class:`set`, and :" "class:`tuple` classes, as well as the :mod:`collections` module." @@ -1086,7 +1148,7 @@ msgstr "" "Para outros contêineres, consulte as classes embutidas :class:`list`, :class:" "`set` e :class:`tuple`, bem como o módulo :mod:`collections`." -#: ../../library/functions.rst:478 +#: ../../library/functions.rst:480 msgid "" "Without arguments, return the list of names in the current local scope. " "With an argument, attempt to return a list of valid attributes for that " @@ -1095,7 +1157,7 @@ msgstr "" "Sem argumentos, devolve a lista de nomes no escopo local atual. Com um " "argumento, tentará devolver uma lista de atributos válidos para esse objeto." -#: ../../library/functions.rst:481 +#: ../../library/functions.rst:483 msgid "" "If the object has a method named :meth:`~object.__dir__`, this method will " "be called and must return the list of attributes. This allows objects that " @@ -1109,7 +1171,7 @@ msgstr "" "func:`~object.__getattribute__` personalizem a maneira como :func:`dir` " "relata seus atributos." -#: ../../library/functions.rst:488 +#: ../../library/functions.rst:490 msgid "" "If the object does not provide :meth:`~object.__dir__`, the function tries " "its best to gather information from the object's :attr:`~object.__dict__` " @@ -1123,7 +1185,7 @@ msgstr "" "necessariamente completa e pode ser imprecisa quando o objeto possui um :" "func:`~object.__getattr__` personalizado." -#: ../../library/functions.rst:494 +#: ../../library/functions.rst:496 msgid "" "The default :func:`dir` mechanism behaves differently with different types " "of objects, as it attempts to produce the most relevant, rather than " @@ -1133,7 +1195,7 @@ msgstr "" "diferentes tipos de objetos, pois tenta produzir as informações mais " "relevantes e não completas:" -#: ../../library/functions.rst:498 +#: ../../library/functions.rst:500 msgid "" "If the object is a module object, the list contains the names of the " "module's attributes." @@ -1141,7 +1203,7 @@ msgstr "" "Se o objeto for um objeto de módulo, a lista conterá os nomes dos atributos " "do módulo." -#: ../../library/functions.rst:501 +#: ../../library/functions.rst:503 msgid "" "If the object is a type or class object, the list contains the names of its " "attributes, and recursively of the attributes of its bases." @@ -1149,7 +1211,7 @@ msgstr "" "Se o objeto for um objeto de tipo ou classe, a lista conterá os nomes de " "seus atributos e recursivamente os atributos de suas bases." -#: ../../library/functions.rst:504 +#: ../../library/functions.rst:506 msgid "" "Otherwise, the list contains the object's attributes' names, the names of " "its class's attributes, and recursively of the attributes of its class's " @@ -1159,11 +1221,11 @@ msgstr "" "dos atributos da classe e recursivamente os atributos das classes base da " "classe." -#: ../../library/functions.rst:508 +#: ../../library/functions.rst:510 msgid "The resulting list is sorted alphabetically. For example:" msgstr "A lista resultante é alfabeticamente ordenada. Por exemplo:" -#: ../../library/functions.rst:528 +#: ../../library/functions.rst:530 msgid "" "Because :func:`dir` is supplied primarily as a convenience for use at an " "interactive prompt, it tries to supply an interesting set of names more than " @@ -1178,7 +1240,7 @@ msgstr "" "lançamentos. Por exemplo, os atributos de metaclasse não estão na lista de " "resultados quando o argumento é uma classe." -#: ../../library/functions.rst:538 +#: ../../library/functions.rst:540 msgid "" "Take two (non-complex) numbers as arguments and return a pair of numbers " "consisting of their quotient and remainder when using integer division. " @@ -1198,7 +1260,7 @@ msgstr "" "qualquer caso, ``q * b + a % b`` está muito próximo de *a*, se ``a % b`` é " "diferente de zero, tem o mesmo sinal que *b* e ``0 <= abs(a % b) < abs(b)``." -#: ../../library/functions.rst:550 +#: ../../library/functions.rst:552 msgid "" "Return an enumerate object. *iterable* must be a sequence, an :term:" "`iterator`, or some other object which supports iteration. The :meth:" @@ -1212,23 +1274,37 @@ msgstr "" "tupla contendo uma contagem (a partir de *start*, cujo padrão é 0) e os " "valores obtidos na iteração sobre *iterable*." -#: ../../library/functions.rst:562 +#: ../../library/functions.rst:564 msgid "Equivalent to::" msgstr "Equivalente a::" +#: ../../library/functions.rst:566 +msgid "" +"def enumerate(iterable, start=0):\n" +" n = start\n" +" for elem in iterable:\n" +" yield n, elem\n" +" n += 1" +msgstr "" +"def enumerate(iterable, start=0):\n" +" n = start\n" +" for elem in iterable:\n" +" yield n, elem\n" +" n += 1" + #: ../../library/functions.rst:0 msgid "Parameters" msgstr "Parâmetros" -#: ../../library/functions.rst:574 +#: ../../library/functions.rst:576 msgid "A Python expression." msgstr "Uma expressão Python." -#: ../../library/functions.rst:578 +#: ../../library/functions.rst:580 msgid "The global namespace (default: ``None``)." msgstr "O espaço de nomes global (por padrão, ``None``)." -#: ../../library/functions.rst:582 +#: ../../library/functions.rst:584 msgid "The local namespace (default: ``None``)." msgstr "O espaço de nomes local (por padrão, ``None``)." @@ -1236,7 +1312,7 @@ msgstr "O espaço de nomes local (por padrão, ``None``)." msgid "Returns" msgstr "Retorna" -#: ../../library/functions.rst:586 +#: ../../library/functions.rst:588 msgid "The result of the evaluated expression." msgstr "O resultado da expressão avaliada." @@ -1244,11 +1320,19 @@ msgstr "O resultado da expressão avaliada." msgid "raises" msgstr "levanta" -#: ../../library/functions.rst:587 +#: ../../library/functions.rst:589 msgid "Syntax errors are reported as exceptions." msgstr "Erros de sintaxe são reportados como exceções." -#: ../../library/functions.rst:589 +#: ../../library/functions.rst:593 ../../library/functions.rst:654 +msgid "" +"This function executes arbitrary code. Calling it with user-supplied input " +"may lead to security vulnerabilities." +msgstr "" +"Esta função executa código arbitrário. Chamá-la com entrada fornecida pelo " +"usuário pode levar a vulnerabilidades de segurança." + +#: ../../library/functions.rst:596 msgid "" "The *expression* argument is parsed and evaluated as a Python expression " "(technically speaking, a condition list) using the *globals* and *locals* " @@ -1282,11 +1366,11 @@ msgstr "" "eles já forem referenciados pelo escopo que está chamando :func:`eval` (por " "exemplo, via uma instrução :keyword:`nonlocal`)." -#: ../../library/functions.rst:605 +#: ../../library/functions.rst:612 msgid "Example:" msgstr "Exemplo:" -#: ../../library/functions.rst:611 +#: ../../library/functions.rst:618 msgid "" "This function can also be used to execute arbitrary code objects (such as " "those created by :func:`compile`). In this case, pass a code object instead " @@ -1298,7 +1382,7 @@ msgstr "" "vez de uma string. Se o objeto código foi compilado com ``'exec'`` como o " "argumento *mode*, o valor de retorno de :func:`eval` será ``None``." -#: ../../library/functions.rst:616 +#: ../../library/functions.rst:623 msgid "" "Hints: dynamic execution of statements is supported by the :func:`exec` " "function. The :func:`globals` and :func:`locals` functions return the " @@ -1310,7 +1394,7 @@ msgstr "" "global e local atual, respectivamente, o que pode ser útil para ser usado " "por :func:`eval` ou :func:`exec`." -#: ../../library/functions.rst:621 +#: ../../library/functions.rst:628 msgid "" "If the given source is a string, then leading and trailing spaces and tabs " "are stripped." @@ -1318,7 +1402,7 @@ msgstr "" "Se a fonte fornecida for uma string, os espaços e tabulações à esquerda ou à " "direita serão removidos." -#: ../../library/functions.rst:624 +#: ../../library/functions.rst:631 msgid "" "See :func:`ast.literal_eval` for a function that can safely evaluate strings " "with expressions containing only literals." @@ -1326,8 +1410,8 @@ msgstr "" "Veja :func:`ast.literal_eval` para uma função que pode avaliar com segurança " "strings com expressões contendo apenas literais." -#: ../../library/functions.rst:627 ../../library/functions.rst:629 -#: ../../library/functions.rst:683 ../../library/functions.rst:685 +#: ../../library/functions.rst:634 ../../library/functions.rst:636 +#: ../../library/functions.rst:696 ../../library/functions.rst:698 msgid "" "Raises an :ref:`auditing event ` ``exec`` with the code object as " "the argument. Code compilation events may also be raised." @@ -1336,13 +1420,13 @@ msgstr "" "objeto como argumento. Eventos de compilação de código também podem ser " "levantados." -#: ../../library/functions.rst:634 ../../library/functions.rst:705 +#: ../../library/functions.rst:641 ../../library/functions.rst:718 msgid "The *globals* and *locals* arguments can now be passed as keywords." msgstr "" "Os argumentos *globals* e *locals* podem agora ser passados como argumentos " "nomeados." -#: ../../library/functions.rst:638 ../../library/functions.rst:709 +#: ../../library/functions.rst:645 ../../library/functions.rst:722 msgid "" "The semantics of the default *locals* namespace have been adjusted as " "described for the :func:`locals` builtin." @@ -1350,7 +1434,7 @@ msgstr "" "A forma de uso do espaço de nomes *locals* padrão foi ajustado conforme " "descrito na função embutida :func:`locals`." -#: ../../library/functions.rst:645 +#: ../../library/functions.rst:657 msgid "" "This function supports dynamic execution of Python code. *source* must be " "either a string or a code object. If it is a string, the string is parsed " @@ -1374,7 +1458,7 @@ msgstr "" "código passado para a função :func:`exec` . O valor de retorno é sempre " "``None``." -#: ../../library/functions.rst:656 +#: ../../library/functions.rst:668 msgid "" "In all cases, if the optional parts are omitted, the code is executed in the " "current scope. If only *globals* is provided, it must be a dictionary (and " @@ -1393,7 +1477,7 @@ msgstr "" "mapeamento. Lembre que no nível de módulo, globais e locais são o mesmo " "dicionário." -#: ../../library/functions.rst:666 +#: ../../library/functions.rst:678 msgid "" "When ``exec`` gets two separate objects as *globals* and *locals*, the code " "will be executed as if it were embedded in a class definition. This means " @@ -1408,7 +1492,7 @@ msgstr "" "escopo mais externo (pois, em uma definição de classe, tais variáveis seriam " "tratadas como variáveis de classe)." -#: ../../library/functions.rst:672 +#: ../../library/functions.rst:684 msgid "" "If the *globals* dictionary does not contain a value for the key " "``__builtins__``, a reference to the dictionary of the built-in module :mod:" @@ -1422,19 +1506,20 @@ msgstr "" "disponíveis para o código executado é inserindo seu próprio ``__builtins__`` " "dicionário em *globals* antes de passar para :func:`exec`." -#: ../../library/functions.rst:678 +#: ../../library/functions.rst:690 msgid "" "The *closure* argument specifies a closure--a tuple of cellvars. It's only " -"valid when the *object* is a code object containing free variables. The " -"length of the tuple must exactly match the number of free variables " -"referenced by the code object." +"valid when the *object* is a code object containing :term:`free (closure) " +"variables `. The length of the tuple must exactly match " +"the length of the code object's :attr:`~codeobject.co_freevars` attribute." msgstr "" -"O argumento *closure* especifica um encerramento -- uma tupla de cellvars. " -"Só é válido quando o *objeto* é um objeto código contendo variáveis livres. " -"O comprimento da tupla deve corresponder exatamente ao número de variáveis " -"livres referenciadas pelo objeto código." +"O argumento *closure* especifica uma clausura -- uma tupla de cellvars. Só é " +"válido quando o *objeto* é um objeto código contendo :term:`variáveis livres " +"(de clausura) `. O comprimento da tupla deve corresponder " +"exatamente ao comprimento do atributo :attr:`~codeobject.co_freevars` do " +"objeto código." -#: ../../library/functions.rst:690 +#: ../../library/functions.rst:703 msgid "" "The built-in functions :func:`globals` and :func:`locals` return the current " "global and local namespace, respectively, which may be useful to pass around " @@ -1444,7 +1529,7 @@ msgstr "" "nomes global e local, respectivamente, o que pode ser útil para passar " "adiante e usar como segundo ou terceiro argumento para :func:`exec`." -#: ../../library/functions.rst:696 +#: ../../library/functions.rst:709 msgid "" "The default *locals* act as described for function :func:`locals` below. " "Pass an explicit *locals* dictionary if you need to see effects of the code " @@ -1454,11 +1539,11 @@ msgstr "" "você precisa ver efeitos do código em *locals* depois da função :func:`exec` " "retornar passe um dicionário *locals* explícito." -#: ../../library/functions.rst:700 +#: ../../library/functions.rst:713 msgid "Added the *closure* parameter." msgstr "Adicionado o parâmetro *closure*." -#: ../../library/functions.rst:715 +#: ../../library/functions.rst:728 msgid "" "Construct an iterator from those elements of *iterable* for which *function* " "is true. *iterable* may be either a sequence, a container which supports " @@ -1471,7 +1556,7 @@ msgstr "" "identidade será usada, isto é, todos os elementos de *iterable* que são " "falsos são removidos." -#: ../../library/functions.rst:721 +#: ../../library/functions.rst:734 msgid "" "Note that ``filter(function, iterable)`` is equivalent to the generator " "expression ``(item for item in iterable if function(item))`` if function is " @@ -1483,7 +1568,7 @@ msgstr "" "``None`` e ``(item for item in iterable if item)`` se *function* for " "``None``." -#: ../../library/functions.rst:726 +#: ../../library/functions.rst:739 msgid "" "See :func:`itertools.filterfalse` for the complementary function that " "returns elements of *iterable* for which *function* is false." @@ -1491,7 +1576,7 @@ msgstr "" "Veja :func:`itertools.filterfalse` para a função complementar que devolve " "elementos de *iterable* para os quais *function* é falso." -#: ../../library/functions.rst:737 +#: ../../library/functions.rst:750 msgid "Return a floating-point number constructed from a number or a string." msgstr "" "Retorna um número de ponto flutuante construído a partir de um número ou " @@ -1499,6 +1584,30 @@ msgstr "" #: ../../library/functions.rst:754 msgid "" +">>> float('+1.23')\n" +"1.23\n" +">>> float(' -12345\\n')\n" +"-12345.0\n" +">>> float('1e-003')\n" +"0.001\n" +">>> float('+1E6')\n" +"1000000.0\n" +">>> float('-Infinity')\n" +"-inf" +msgstr "" +">>> float('+1.23')\n" +"1.23\n" +">>> float(' -12345\\n')\n" +"-12345.0\n" +">>> float('1e-003')\n" +"0.001\n" +">>> float('+1E6')\n" +"1000000.0\n" +">>> float('-Infinity')\n" +"-inf" + +#: ../../library/functions.rst:767 +msgid "" "If the argument is a string, it should contain a decimal number, optionally " "preceded by a sign, and optionally embedded in whitespace. The optional " "sign may be ``'+'`` or ``'-'``; a ``'+'`` sign has no effect on the value " @@ -1516,7 +1625,7 @@ msgstr "" "`~float:floatvalue` na seguinte gramática, depois que os espaços em branco " "iniciais e finais forem removidos:" -#: ../../library/functions.rst:775 +#: ../../library/functions.rst:788 msgid "" "Case is not significant, so, for example, \"inf\", \"Inf\", \"INFINITY\", " "and \"iNfINity\" are all acceptable spellings for positive infinity." @@ -1525,7 +1634,7 @@ msgstr "" "\"INFINITY\" e \"iNfINity\" são todas grafias aceitáveis para o infinito " "positivo." -#: ../../library/functions.rst:778 +#: ../../library/functions.rst:791 msgid "" "Otherwise, if the argument is an integer or a floating-point number, a " "floating-point number with the same value (within Python's floating-point " @@ -1537,7 +1646,7 @@ msgstr "" "flutuante de Python) é retornado. Se o argumento está fora do intervalo de " "um ponto flutuante Python, uma exceção :exc:`OverflowError` será lançada." -#: ../../library/functions.rst:783 +#: ../../library/functions.rst:796 msgid "" "For a general Python object ``x``, ``float(x)`` delegates to ``x." "__float__()``. If :meth:`~object.__float__` is not defined then it falls " @@ -1547,15 +1656,15 @@ msgstr "" "__float__()``. Se :meth:`~object.__float__` não estiver definido, então ele " "delega para o método :meth:`~object.__index__`." -#: ../../library/functions.rst:787 +#: ../../library/functions.rst:800 msgid "If no argument is given, ``0.0`` is returned." msgstr "Se nenhum argumento for fornecido, será retornado ``0.0``." -#: ../../library/functions.rst:789 +#: ../../library/functions.rst:802 msgid "The float type is described in :ref:`typesnumeric`." msgstr "O tipo float é descrito em :ref:`typesnumeric`." -#: ../../library/functions.rst:797 +#: ../../library/functions.rst:810 msgid "" "Falls back to :meth:`~object.__index__` if :meth:`~object.__float__` is not " "defined." @@ -1563,7 +1672,7 @@ msgstr "" "Chamada para :meth:`~object.__index__` se :meth:`~object.__float__` não está " "definido." -#: ../../library/functions.rst:807 +#: ../../library/functions.rst:820 msgid "" "Convert a *value* to a \"formatted\" representation, as controlled by " "*format_spec*. The interpretation of *format_spec* will depend on the type " @@ -1575,7 +1684,7 @@ msgstr "" "argumento *value*; no entanto há uma sintaxe de formatação padrão usada pela " "maioria dos tipos embutidos: :ref:`formatspec`." -#: ../../library/functions.rst:812 +#: ../../library/functions.rst:825 msgid "" "The default *format_spec* is an empty string which usually gives the same " "effect as calling :func:`str(value) `." @@ -1583,7 +1692,7 @@ msgstr "" "O *format_spec* padrão é uma string vazia que geralmente produz o mesmo " "efeito que chamar :func:`str(value) `." -#: ../../library/functions.rst:815 +#: ../../library/functions.rst:828 msgid "" "A call to ``format(value, format_spec)`` is translated to ``type(value)." "__format__(value, format_spec)`` which bypasses the instance dictionary when " @@ -1599,7 +1708,7 @@ msgstr "" "*format_spec* não estiver vazio, ou se o *format_spec* ou o valor de retorno " "não forem strings." -#: ../../library/functions.rst:822 +#: ../../library/functions.rst:835 msgid "" "``object().__format__(format_spec)`` raises :exc:`TypeError` if " "*format_spec* is not an empty string." @@ -1607,7 +1716,7 @@ msgstr "" "``object().__format__(format_spec)`` levanta um :exc:`TypeError` se " "*format_spec* não for uma string vazia." -#: ../../library/functions.rst:831 +#: ../../library/functions.rst:844 msgid "" "Return a new :class:`frozenset` object, optionally with elements taken from " "*iterable*. ``frozenset`` is a built-in class. See :class:`frozenset` and :" @@ -1617,7 +1726,7 @@ msgstr "" "obtidos de *iterable*. ``frozenset`` é uma classe embutida. Veja :class:" "`frozenset` e :ref:`types-set` para documentação sobre essas classes." -#: ../../library/functions.rst:835 +#: ../../library/functions.rst:848 msgid "" "For other containers see the built-in :class:`set`, :class:`list`, :class:" "`tuple`, and :class:`dict` classes, as well as the :mod:`collections` module." @@ -1626,7 +1735,7 @@ msgstr "" "`list`, :class:`tuple`, e :class:`dict`, assim como o módulo :mod:" "`collections`." -#: ../../library/functions.rst:843 +#: ../../library/functions.rst:856 msgid "" "Return the value of the named attribute of *object*. *name* must be a " "string. If the string is the name of one of the object's attributes, the " @@ -1642,7 +1751,7 @@ msgstr "" "fornecido, caso contrário a exceção :exc:`AttributeError` é levantada. " "*name* não precisa ser um identificador Python (veja :func:`setattr`)." -#: ../../library/functions.rst:852 +#: ../../library/functions.rst:865 msgid "" "Since :ref:`private name mangling ` happens at " "compilation time, one must manually mangle a private attribute's (attributes " @@ -1654,7 +1763,7 @@ msgstr "" "atributo privado (atributos com dois sublinhados à esquerda) para recuperá-" "lo com :func:`getattr`." -#: ../../library/functions.rst:860 +#: ../../library/functions.rst:873 msgid "" "Return the dictionary implementing the current module namespace. For code " "within functions, this is set when the function is defined and remains the " @@ -1664,7 +1773,7 @@ msgstr "" "código dentro de funções, isso é definido quando a função é definida e " "permanece o mesmo, independentemente de onde a função é chamada." -#: ../../library/functions.rst:867 +#: ../../library/functions.rst:880 msgid "" "The arguments are an object and a string. The result is ``True`` if the " "string is the name of one of the object's attributes, ``False`` if not. " @@ -1676,7 +1785,7 @@ msgstr "" "implementado chamando ``getattr(object, name)`` e vendo se levanta um :exc:" "`AttributeError` ou não.)" -#: ../../library/functions.rst:875 +#: ../../library/functions.rst:888 msgid "" "Return the hash value of the object (if it has one). Hash values are " "integers. They are used to quickly compare dictionary keys during a " @@ -1689,7 +1798,7 @@ msgstr "" "comparados são iguais, possuem o mesmo valor hash (mesmo que eles sejam de " "tipos diferentes, como é o caso de 1 e 1.0)." -#: ../../library/functions.rst:882 +#: ../../library/functions.rst:895 msgid "" "For objects with custom :meth:`~object.__hash__` methods, note that :func:" "`hash` truncates the return value based on the bit width of the host machine." @@ -1698,7 +1807,7 @@ msgstr "" "atento que :func:`hash` trunca o valor devolvido baseado no comprimento de " "bits da máquina hospedeira." -#: ../../library/functions.rst:889 +#: ../../library/functions.rst:902 msgid "" "Invoke the built-in help system. (This function is intended for interactive " "use.) If no argument is given, the interactive help system starts on the " @@ -1715,7 +1824,7 @@ msgstr "" "console. Se o argumento é qualquer outro tipo de objeto, uma página de ajuda " "para o objeto é gerada." -#: ../../library/functions.rst:896 +#: ../../library/functions.rst:909 msgid "" "Note that if a slash(/) appears in the parameter list of a function when " "invoking :func:`help`, it means that the parameters prior to the slash are " @@ -1727,13 +1836,13 @@ msgstr "" "barra são apenas posicionais. Para mais informações, veja :ref:`a entrada no " "FAQ sobre parâmetros somente-posicionais `." -#: ../../library/functions.rst:901 +#: ../../library/functions.rst:914 msgid "" "This function is added to the built-in namespace by the :mod:`site` module." msgstr "" "Esta função é adicionada ao espaço de nomes embutido pelo módulo :mod:`site`." -#: ../../library/functions.rst:903 +#: ../../library/functions.rst:916 msgid "" "Changes to :mod:`pydoc` and :mod:`inspect` mean that the reported signatures " "for callables are now more comprehensive and consistent." @@ -1741,7 +1850,7 @@ msgstr "" "Mudanças em :mod:`pydoc` e :mod:`inspect` significam que as assinaturas " "reportadas para chamáveis agora são mais compreensíveis e consistentes." -#: ../../library/functions.rst:910 +#: ../../library/functions.rst:923 msgid "" "Convert an integer number to a lowercase hexadecimal string prefixed with " "\"0x\". If *x* is not a Python :class:`int` object, it has to define an :" @@ -1752,7 +1861,7 @@ msgstr "" "tem que definir um método :meth:`~object.__index__` que retorne um inteiro. " "Alguns exemplos:" -#: ../../library/functions.rst:919 +#: ../../library/functions.rst:932 msgid "" "If you want to convert an integer number to an uppercase or lower " "hexadecimal string with prefix or not, you can use either of the following " @@ -1762,7 +1871,7 @@ msgstr "" "letras maiúsculas ou minúsculas, com prefixo ou sem, você pode usar qualquer " "uma das seguintes maneiras:" -#: ../../library/functions.rst:931 +#: ../../library/functions.rst:944 msgid "" "See also :func:`int` for converting a hexadecimal string to an integer using " "a base of 16." @@ -1770,7 +1879,7 @@ msgstr "" "Veja também :func:`int` para converter uma string hexadecimal para um " "inteiro usando a base 16." -#: ../../library/functions.rst:936 +#: ../../library/functions.rst:949 msgid "" "To obtain a hexadecimal string representation for a float, use the :meth:" "`float.hex` method." @@ -1778,7 +1887,7 @@ msgstr "" "Para obter uma string hexadecimal de um ponto flutuante, use o método :meth:" "`float.hex`." -#: ../../library/functions.rst:942 +#: ../../library/functions.rst:955 msgid "" "Return the \"identity\" of an object. This is an integer which is " "guaranteed to be unique and constant for this object during its lifetime. " @@ -1790,11 +1899,11 @@ msgstr "" "vida. Dois objetos com ciclos de vida não sobrepostos podem ter o mesmo " "valor para :func:`id`." -#: ../../library/functions.rst:947 +#: ../../library/functions.rst:960 msgid "This is the address of the object in memory." msgstr "Este é o endereço do objeto na memória." -#: ../../library/functions.rst:949 +#: ../../library/functions.rst:962 msgid "" "Raises an :ref:`auditing event ` ``builtins.id`` with argument " "``id``." @@ -1802,7 +1911,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``builtins.id`` com o " "argumento ``id``." -#: ../../library/functions.rst:955 +#: ../../library/functions.rst:968 msgid "" "If the *prompt* argument is present, it is written to standard output " "without a trailing newline. The function then reads a line from input, " @@ -1815,7 +1924,19 @@ msgstr "" "final), e devolve isso. Quando o final do arquivo (EOF / end-of-file) é " "encontrado, um erro :exc:`EOFError` é levantado. Exemplo::" -#: ../../library/functions.rst:965 +#: ../../library/functions.rst:973 +msgid "" +">>> s = input('--> ')\n" +"--> Monty Python's Flying Circus\n" +">>> s\n" +"\"Monty Python's Flying Circus\"" +msgstr "" +">>> s = input('--> ')\n" +"--> Monty Python's Flying Circus\n" +">>> s\n" +"\"Monty Python's Flying Circus\"" + +#: ../../library/functions.rst:978 msgid "" "If the :mod:`readline` module was loaded, then :func:`input` will use it to " "provide elaborate line editing and history features." @@ -1823,7 +1944,7 @@ msgstr "" "Se o módulo :mod:`readline` foi carregado, então :func:`input` usará ele " "para prover edição de linhas elaboradas e funcionalidades de histórico." -#: ../../library/functions.rst:968 ../../library/functions.rst:970 +#: ../../library/functions.rst:981 ../../library/functions.rst:983 msgid "" "Raises an :ref:`auditing event ` ``builtins.input`` with argument " "``prompt`` before reading input" @@ -1831,7 +1952,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``builtins.input`` com " "argumento ``prompt`` antes de ler a entrada." -#: ../../library/functions.rst:973 ../../library/functions.rst:975 +#: ../../library/functions.rst:986 ../../library/functions.rst:988 msgid "" "Raises an :ref:`auditing event ` ``builtins.input/result`` with " "the result after successfully reading input." @@ -1839,7 +1960,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``builtins.input/result`` " "com o resultado depois de ler a entrada com sucesso." -#: ../../library/functions.rst:982 +#: ../../library/functions.rst:995 msgid "" "Return an integer object constructed from a number or a string, or return " "``0`` if no arguments are given." @@ -1847,7 +1968,35 @@ msgstr "" "Retorna um objeto do tipo inteiro construído a partir de um número ou " "string, ou retorna ``0`` caso nenhum argumento seja passado." -#: ../../library/functions.rst:1002 +#: ../../library/functions.rst:1000 +msgid "" +">>> int(123.45)\n" +"123\n" +">>> int('123')\n" +"123\n" +">>> int(' -12_345\\n')\n" +"-12345\n" +">>> int('FACE', 16)\n" +"64206\n" +">>> int('0xface', 0)\n" +"64206\n" +">>> int('01110011', base=2)\n" +"115" +msgstr "" +">>> int(123.45)\n" +"123\n" +">>> int('123')\n" +"123\n" +">>> int(' -12_345\\n')\n" +"-12345\n" +">>> int('FACE', 16)\n" +"64206\n" +">>> int('0xface', 0)\n" +"64206\n" +">>> int('01110011', base=2)\n" +"115" + +#: ../../library/functions.rst:1015 msgid "" "If the argument defines :meth:`~object.__int__`, ``int(x)`` returns ``x." "__int__()``. If the argument defines :meth:`~object.__index__`, it returns " @@ -1861,7 +2010,7 @@ msgstr "" "`~object.__trunc__`, então ele retorna ``x.__trunc__()``. Para números de " "ponto flutuante, isto trunca o número na direção do zero." -#: ../../library/functions.rst:1008 +#: ../../library/functions.rst:1021 msgid "" "If the argument is not a number or if *base* is given, then it must be a " "string, :class:`bytes`, or :class:`bytearray` instance representing an " @@ -1876,7 +2025,7 @@ msgstr "" "esquerda, estar entre espaços em branco e ter sublinhados simples " "intercalados entre os dígitos." -#: ../../library/functions.rst:1014 +#: ../../library/functions.rst:1027 msgid "" "A base-n integer string contains digits, each representing a value from 0 to " "n-1. The values 0--9 can be represented by any Unicode decimal digit. The " @@ -1901,11 +2050,11 @@ msgstr "" "permite zeros à esquerda: ``int('010', 0)`` não é válido, enquanto " "``int('010')`` e ``int('010', 8)`` são." -#: ../../library/functions.rst:1025 +#: ../../library/functions.rst:1038 msgid "The integer type is described in :ref:`typesnumeric`." msgstr "O tipo inteiro está descrito em :ref:`typesnumeric`." -#: ../../library/functions.rst:1027 +#: ../../library/functions.rst:1040 msgid "" "If *base* is not an instance of :class:`int` and the *base* object has a :" "meth:`base.__index__ ` method, that method is called to " @@ -1918,11 +2067,11 @@ msgstr "" "`base.__int__ ` ao invés de :meth:`base.__index__ `." -#: ../../library/functions.rst:1037 +#: ../../library/functions.rst:1050 msgid "The first parameter is now positional-only." msgstr "O primeiro parâmetro agora é somente-posicional." -#: ../../library/functions.rst:1040 +#: ../../library/functions.rst:1053 msgid "" "Falls back to :meth:`~object.__index__` if :meth:`~object.__int__` is not " "defined." @@ -1930,11 +2079,11 @@ msgstr "" "Chamada para :meth:`~object.__index__` se :meth:`~object.__int__` não está " "definido." -#: ../../library/functions.rst:1043 +#: ../../library/functions.rst:1056 msgid "The delegation to :meth:`~object.__trunc__` is deprecated." msgstr "A delegação de :meth:`~object.__trunc__` foi descontinuada." -#: ../../library/functions.rst:1046 +#: ../../library/functions.rst:1059 msgid "" ":class:`int` string inputs and string representations can be limited to help " "avoid denial of service attacks. A :exc:`ValueError` is raised when the " @@ -1950,7 +2099,7 @@ msgstr "" "uma string excede o limite. Consulte a documentação sobre :ref:`limitação de " "comprimento de conversão de string em inteiro `." -#: ../../library/functions.rst:1056 +#: ../../library/functions.rst:1069 msgid "" "Return ``True`` if the *object* argument is an instance of the *classinfo* " "argument, or of a (direct, indirect, or :term:`virtual `) of *classinfo*. A class is considered a " @@ -1993,7 +2142,7 @@ msgstr "" "*classinfo*. Em qualquer outro caso, é levantada uma exceção :exc:" "`TypeError`." -#: ../../library/functions.rst:1088 +#: ../../library/functions.rst:1101 msgid "" "Return an :term:`iterator` object. The first argument is interpreted very " "differently depending on the presence of the second argument. Without a " @@ -2021,11 +2170,11 @@ msgstr "" "devolvido é igual a *sentinel*, então :exc:`StopIteration` será levantado, " "caso contrário o valor será devolvido." -#: ../../library/functions.rst:1102 +#: ../../library/functions.rst:1115 msgid "See also :ref:`typeiter`." msgstr "Veja também :ref:`typeiter`." -#: ../../library/functions.rst:1104 +#: ../../library/functions.rst:1117 msgid "" "One useful application of the second form of :func:`iter` is to build a " "block-reader. For example, reading fixed-width blocks from a binary database " @@ -2035,7 +2184,19 @@ msgstr "" "bloco de leitura. Por exemplo, ler blocos de comprimento fixo de um arquivo " "binário de banco de dados até que o final do arquivo seja atingido::" -#: ../../library/functions.rst:1116 +#: ../../library/functions.rst:1121 +msgid "" +"from functools import partial\n" +"with open('mydata.db', 'rb') as f:\n" +" for block in iter(partial(f.read, 64), b''):\n" +" process_block(block)" +msgstr "" +"from functools import partial\n" +"with open('meusdados.db', 'rb') as f:\n" +" for bloco in iter(partial(f.read, 64), b''):\n" +" process_block(bloco)" + +#: ../../library/functions.rst:1129 msgid "" "Return the length (the number of items) of an object. The argument may be a " "sequence (such as a string, bytes, tuple, list, or range) or a collection " @@ -2045,7 +2206,7 @@ msgstr "" "uma sequência (tal como uma string, bytes, tupla, lista, ou um intervalo) ou " "uma coleção (tal como um dicionário, conjunto, ou conjunto imutável)." -#: ../../library/functions.rst:1122 +#: ../../library/functions.rst:1135 msgid "" "``len`` raises :exc:`OverflowError` on lengths larger than :data:`sys." "maxsize`, such as :class:`range(2 ** 100) `." @@ -2053,7 +2214,7 @@ msgstr "" "``len`` levanta :exc:`OverflowError` em tamanhos maiores que :data:`sys." "maxsize`, tal como :class:`range(2 ** 100) `." -#: ../../library/functions.rst:1131 +#: ../../library/functions.rst:1144 msgid "" "Rather than being a function, :class:`list` is actually a mutable sequence " "type, as documented in :ref:`typesseq-list` and :ref:`typesseq`." @@ -2061,7 +2222,7 @@ msgstr "" "Ao invés de ser uma função, :class:`list` é na verdade um tipo de sequência " "mutável, conforme documentado em :ref:`typesseq-list` e :ref:`typesseq`." -#: ../../library/functions.rst:1137 +#: ../../library/functions.rst:1150 msgid "" "Return a mapping object representing the current local symbol table, with " "variable names as the keys, and their currently bound references as the " @@ -2071,7 +2232,7 @@ msgstr "" "com nomes de variáveis como as chaves, e as referências às quais cada " "variável está atrelada no momento como os valores." -#: ../../library/functions.rst:1141 +#: ../../library/functions.rst:1154 msgid "" "At module scope, as well as when using :func:`exec` or :func:`eval` with a " "single namespace, this function returns the same namespace as :func:" @@ -2081,7 +2242,7 @@ msgstr "" "`eval` com um único espaço de nomes, esta função retorna o mesmo espaço de " "nomes que :func:`globals`." -#: ../../library/functions.rst:1145 +#: ../../library/functions.rst:1158 msgid "" "At class scope, it returns the namespace that will be passed to the " "metaclass constructor." @@ -2089,7 +2250,7 @@ msgstr "" "Em um escopo de classe, ela retorna o espaço de nomes que será passado para " "o construtor da metaclasse." -#: ../../library/functions.rst:1148 +#: ../../library/functions.rst:1161 msgid "" "When using ``exec()`` or ``eval()`` with separate local and global " "arguments, it returns the local namespace passed in to the function call." @@ -2097,7 +2258,7 @@ msgstr "" "Quando usando ``exec()`` ou ``eval()`` com argumentos de espaço local e " "global distintos, ela retorna o espaço de nomes local passado na chamada." -#: ../../library/functions.rst:1151 +#: ../../library/functions.rst:1164 msgid "" "In all of the above cases, each call to ``locals()`` in a given frame of " "execution will return the *same* mapping object. Changes made through the " @@ -2113,7 +2274,7 @@ msgstr "" "reatribuir ou deletar variáveis locais afetará imediatamente o conteúdo do " "objeto de mapeamento retornado." -#: ../../library/functions.rst:1158 +#: ../../library/functions.rst:1171 msgid "" "In an :term:`optimized scope` (including functions, generators, and " "coroutines), each call to ``locals()`` instead returns a fresh dictionary " @@ -2134,7 +2295,7 @@ msgstr "" "células com referências não-locais *não* afeta o conteúdo dos dicionários " "que já foram retornados." -#: ../../library/functions.rst:1167 +#: ../../library/functions.rst:1180 msgid "" "Calling ``locals()`` as part of a comprehension in a function, generator, or " "coroutine is equivalent to calling it in the containing scope, except that " @@ -2148,7 +2309,7 @@ msgstr "" "compreensão serão incluídas. Em outros escopos, essa função se comporta como " "se a compreensão estivesse executando como uma função aninhada." -#: ../../library/functions.rst:1173 +#: ../../library/functions.rst:1186 msgid "" "Calling ``locals()`` as part of a generator expression is equivalent to " "calling it in a nested generator function." @@ -2156,7 +2317,7 @@ msgstr "" "Chamar a função ``locals()`` como parte de uma expressão geradora é " "equivalente a chamá-la em uma função geradora aninhada." -#: ../../library/functions.rst:1176 +#: ../../library/functions.rst:1189 msgid "" "The behaviour of ``locals()`` in a comprehension has been updated as " "described in :pep:`709`." @@ -2164,7 +2325,7 @@ msgstr "" "O comportamento de ``locals()`` em uma compreensão foi atualizado conforme " "descrito na :pep:`709`." -#: ../../library/functions.rst:1180 +#: ../../library/functions.rst:1193 msgid "" "As part of :pep:`667`, the semantics of mutating the mapping objects " "returned from this function are now defined. The behavior in :term:" @@ -2178,7 +2339,7 @@ msgstr "" "de estar definido, o comportamento em outros escopos não foi modificado em " "relação aos comportamentos em versões passadas." -#: ../../library/functions.rst:1190 +#: ../../library/functions.rst:1203 msgid "" "Return an iterator that applies *function* to every item of *iterable*, " "yielding the results. If additional *iterables* arguments are passed, " @@ -2195,14 +2356,14 @@ msgstr "" "parâmetros de entrada da função já estão organizados em tuplas, veja :func:" "`itertools.starmap`\\." -#: ../../library/functions.rst:1202 +#: ../../library/functions.rst:1215 msgid "" "Return the largest item in an iterable or the largest of two or more " "arguments." msgstr "" "Devolve o maior item em um iterável ou o maior de dois ou mais argumentos." -#: ../../library/functions.rst:1205 +#: ../../library/functions.rst:1218 msgid "" "If one positional argument is provided, it should be an :term:`iterable`. " "The largest item in the iterable is returned. If two or more positional " @@ -2212,7 +2373,7 @@ msgstr "" "maior item no iterável é retornado. Se dois ou mais argumentos posicionais " "são fornecidos, o maior dos argumentos posicionais é devolvido." -#: ../../library/functions.rst:1210 ../../library/functions.rst:1248 +#: ../../library/functions.rst:1223 ../../library/functions.rst:1261 msgid "" "There are two optional keyword-only arguments. The *key* argument specifies " "a one-argument ordering function like that used for :meth:`list.sort`. The " @@ -2227,7 +2388,7 @@ msgstr "" "vazio, e *default* não foi fornecido, uma exceção :exc:`ValueError` é " "levantada." -#: ../../library/functions.rst:1216 +#: ../../library/functions.rst:1229 msgid "" "If multiple items are maximal, the function returns the first one " "encountered. This is consistent with other sort-stability preserving tools " @@ -2239,15 +2400,15 @@ msgstr "" "estabilidade, tais como ``sorted(iterable, key=keyfunc, reverse=True)[0]`` e " "``heapq.nlargest(1, iterable, key=keyfunc)``." -#: ../../library/functions.rst:1221 ../../library/functions.rst:1259 +#: ../../library/functions.rst:1234 ../../library/functions.rst:1272 msgid "Added the *default* keyword-only parameter." msgstr "Adicionado o parâmetro *default* somente-nomeado." -#: ../../library/functions.rst:1224 ../../library/functions.rst:1262 +#: ../../library/functions.rst:1237 ../../library/functions.rst:1275 msgid "The *key* can be ``None``." msgstr "O valor de *key* pode ser ``None``." -#: ../../library/functions.rst:1232 +#: ../../library/functions.rst:1245 msgid "" "Return a \"memory view\" object created from the given argument. See :ref:" "`typememoryview` for more information." @@ -2255,14 +2416,14 @@ msgstr "" "Devolve um objeto de \"visão da memória\" criado a partir do argumento " "fornecido. Veja :ref:`typememoryview` para mais informações." -#: ../../library/functions.rst:1240 +#: ../../library/functions.rst:1253 msgid "" "Return the smallest item in an iterable or the smallest of two or more " "arguments." msgstr "" "Devolve o menor item de um iterável ou o menor de dois ou mais argumentos." -#: ../../library/functions.rst:1243 +#: ../../library/functions.rst:1256 msgid "" "If one positional argument is provided, it should be an :term:`iterable`. " "The smallest item in the iterable is returned. If two or more positional " @@ -2272,7 +2433,7 @@ msgstr "" "menor item no iterável é devolvido. Se dois ou mais argumentos posicionais " "são fornecidos, o menor dos argumentos posicionais é devolvido." -#: ../../library/functions.rst:1254 +#: ../../library/functions.rst:1267 msgid "" "If multiple items are minimal, the function returns the first one " "encountered. This is consistent with other sort-stability preserving tools " @@ -2284,7 +2445,7 @@ msgstr "" "estabilidade, tais como ``sorted(iterable, key=keyfunc)[0]`` e ``heapq." "nsmallest(1, iterable, key=keyfunc)``." -#: ../../library/functions.rst:1269 +#: ../../library/functions.rst:1282 msgid "" "Retrieve the next item from the :term:`iterator` by calling its :meth:" "`~iterator.__next__` method. If *default* is given, it is returned if the " @@ -2295,26 +2456,28 @@ msgstr "" "iterável tenha sido percorrido por completo, caso contrário :exc:" "`StopIteration` é levantada." -#: ../../library/functions.rst:1276 +#: ../../library/functions.rst:1289 msgid "" -"Return a new featureless object. :class:`object` is a base for all classes. " -"It has methods that are common to all instances of Python classes. This " -"function does not accept any arguments." +"This is the ultimate base class of all other classes. It has methods that " +"are common to all instances of Python classes. When the constructor is " +"called, it returns a new featureless object. The constructor does not accept " +"any arguments." msgstr "" -"Devolve um novo objeto sem funcionalidades. :class:`object` é a classe base " -"para todas as classes. Ela tem os métodos que são comuns para todas as " -"instâncias de classes Python. Esta função não aceita nenhum argumento." +"Esta é a classe base definitiva de todas as outras classes. Ela tem métodos " +"que são comuns a todas as instâncias de classes Python. Quando o construtor " +"é chamado, ele retorna um novo objeto sem características. O construtor não " +"aceita nenhum argumento." -#: ../../library/functions.rst:1282 +#: ../../library/functions.rst:1296 msgid "" -":class:`object` does *not* have a :attr:`~object.__dict__`, so you can't " -"assign arbitrary attributes to an instance of the :class:`object` class." +":class:`object` instances do *not* have :attr:`~object.__dict__` attributes, " +"so you can't assign arbitrary attributes to an instance of :class:`object`." msgstr "" -":class:`object` *não* tem um atributo :attr:`~object.__dict__`, então você " -"não consegue definir atributos arbitrários para uma instância da classe :" -"class:`object`." +"Instâncias de :class:`object` *não* têm atributos :attr:`~object.__dict__`, " +"então você não pode atribuir atributos arbitrários a uma instância de :class:" +"`object`." -#: ../../library/functions.rst:1288 +#: ../../library/functions.rst:1303 msgid "" "Convert an integer number to an octal string prefixed with \"0o\". The " "result is a valid Python expression. If *x* is not a Python :class:`int` " @@ -2326,7 +2489,7 @@ msgstr "" "class:`int` Python, ele tem que definir um método :meth:`~object.__index__` " "que devolve um inteiro. Por exemplo:" -#: ../../library/functions.rst:1298 +#: ../../library/functions.rst:1313 msgid "" "If you want to convert an integer number to an octal string either with the " "prefix \"0o\" or not, you can use either of the following ways." @@ -2334,7 +2497,7 @@ msgstr "" "Se você quiser converter um número inteiro para uma string octal, com o " "prefixo \"0o\" ou não, você pode usar qualquer uma das formas a seguir." -#: ../../library/functions.rst:1315 +#: ../../library/functions.rst:1330 msgid "" "Open *file* and return a corresponding :term:`file object`. If the file " "cannot be opened, an :exc:`OSError` is raised. See :ref:`tut-files` for more " @@ -2344,7 +2507,7 @@ msgstr "" "não puder ser aberto, uma :exc:`OSError` é levantada. Veja :ref:`tut-files` " "para mais exemplos de como usar esta função." -#: ../../library/functions.rst:1319 +#: ../../library/functions.rst:1334 msgid "" "*file* is a :term:`path-like object` giving the pathname (absolute or " "relative to the current working directory) of the file to be opened or an " @@ -2358,7 +2521,7 @@ msgstr "" "arquivo é fornecido, ele é fechado quando o objeto de I/O retornado é " "fechado, a não ser que *closefd* esteja marcado como ``False``)." -#: ../../library/functions.rst:1325 +#: ../../library/functions.rst:1340 msgid "" "*mode* is an optional string that specifies the mode in which the file is " "opened. It defaults to ``'r'`` which means open for reading in text mode. " @@ -2367,7 +2530,7 @@ msgid "" "(which on *some* Unix systems, means that *all* writes append to the end of " "the file regardless of the current seek position). In text mode, if " "*encoding* is not specified the encoding used is platform-dependent: :func:" -"`locale.getencoding()` is called to get the current locale encoding. (For " +"`locale.getencoding` is called to get the current locale encoding. (For " "reading and writing raw bytes use binary mode and leave *encoding* " "unspecified.) The available modes are:" msgstr "" @@ -2378,77 +2541,77 @@ msgstr "" "anexar (o qual em *alguns* sistemas Unix, significa que *todas* as escritas " "anexam ao final do arquivo independentemente da posição de busca atual). No " "modo texto, se *encoding* não for especificada, a codificação usada depende " -"da plataforma: :func:`locale.getencoding()` é chamada para obter a " -"codificação da localidade atual (Para ler e escrever bytes diretamente, use " -"o modo binário e não especifique *encoding*). Os modos disponíveis são:" +"da plataforma: :func:`locale.getencoding` é chamada para obter a codificação " +"da localidade atual (Para ler e escrever bytes diretamente, use o modo " +"binário e não especifique *encoding*). Os modos disponíveis são:" -#: ../../library/functions.rst:1342 +#: ../../library/functions.rst:1357 msgid "Character" msgstr "Caractere" -#: ../../library/functions.rst:1342 +#: ../../library/functions.rst:1357 msgid "Meaning" msgstr "Significado" -#: ../../library/functions.rst:1344 +#: ../../library/functions.rst:1359 msgid "``'r'``" msgstr "``'r'``" -#: ../../library/functions.rst:1344 +#: ../../library/functions.rst:1359 msgid "open for reading (default)" msgstr "abre para leitura (padrão)" -#: ../../library/functions.rst:1345 +#: ../../library/functions.rst:1360 msgid "``'w'``" msgstr "``'w'``" -#: ../../library/functions.rst:1345 +#: ../../library/functions.rst:1360 msgid "open for writing, truncating the file first" msgstr "" "abre para escrita, truncando o arquivo primeiro (removendo tudo o que " "estiver contido no mesmo)" -#: ../../library/functions.rst:1346 +#: ../../library/functions.rst:1361 msgid "``'x'``" msgstr "``'x'``" -#: ../../library/functions.rst:1346 +#: ../../library/functions.rst:1361 msgid "open for exclusive creation, failing if the file already exists" msgstr "abre para criação exclusiva, falhando caso o arquivo exista" -#: ../../library/functions.rst:1347 +#: ../../library/functions.rst:1362 msgid "``'a'``" msgstr "``'a'``" -#: ../../library/functions.rst:1347 +#: ../../library/functions.rst:1362 msgid "open for writing, appending to the end of file if it exists" msgstr "abre para escrita, anexando ao final do arquivo caso o mesmo exista" -#: ../../library/functions.rst:1348 +#: ../../library/functions.rst:1363 msgid "``'b'``" msgstr "``'b'``" -#: ../../library/functions.rst:1348 ../../library/functions.rst:1492 +#: ../../library/functions.rst:1363 ../../library/functions.rst:1507 msgid "binary mode" msgstr "modo binário" -#: ../../library/functions.rst:1349 +#: ../../library/functions.rst:1364 msgid "``'t'``" msgstr "``'t'``" -#: ../../library/functions.rst:1349 +#: ../../library/functions.rst:1364 msgid "text mode (default)" msgstr "modo texto (padrão)" -#: ../../library/functions.rst:1350 +#: ../../library/functions.rst:1365 msgid "``'+'``" msgstr "``'+'``" -#: ../../library/functions.rst:1350 +#: ../../library/functions.rst:1365 msgid "open for updating (reading and writing)" msgstr "aberto para atualização (leitura e escrita)" -#: ../../library/functions.rst:1353 +#: ../../library/functions.rst:1368 msgid "" "The default mode is ``'r'`` (open for reading text, a synonym of ``'rt'``). " "Modes ``'w+'`` and ``'w+b'`` open and truncate the file. Modes ``'r+'`` and " @@ -2458,7 +2621,7 @@ msgstr "" "``'rt'``). Modos ``'w+'`` e ``'w+b'`` abrem e truncam o arquivo. Modos " "``'r+'`` e ``'r+b'`` abrem o arquivo sem truncar o mesmo." -#: ../../library/functions.rst:1357 +#: ../../library/functions.rst:1372 msgid "" "As mentioned in the :ref:`io-overview`, Python distinguishes between binary " "and text I/O. Files opened in binary mode (including ``'b'`` in the *mode* " @@ -2477,7 +2640,7 @@ msgstr "" "dependente da plataforma, ou usando a codificação definida em *encoding* se " "fornecida." -#: ../../library/functions.rst:1367 +#: ../../library/functions.rst:1382 msgid "" "Python doesn't depend on the underlying operating system's notion of text " "files; all the processing is done by Python itself, and is therefore " @@ -2487,7 +2650,7 @@ msgstr "" "texto; todo processamento é feito pelo próprio Python, e é então " "independente de plataforma." -#: ../../library/functions.rst:1371 +#: ../../library/functions.rst:1386 msgid "" "*buffering* is an optional integer used to set the buffering policy. Pass 0 " "to switch buffering off (only allowed in binary mode), 1 to select line " @@ -2511,7 +2674,7 @@ msgstr "" "*buffering* é fornecido, a política de buffering padrão funciona da seguinte " "forma:" -#: ../../library/functions.rst:1381 +#: ../../library/functions.rst:1396 msgid "" "Binary files are buffered in fixed-size chunks; the size of the buffer is " "chosen using a heuristic trying to determine the underlying device's \"block " @@ -2524,7 +2687,7 @@ msgstr "" "caso não consiga. Em muitos sistemas, o buffer possuirá tipicamente 4096 ou " "8192 bytes de comprimento." -#: ../../library/functions.rst:1386 +#: ../../library/functions.rst:1401 msgid "" "\"Interactive\" text files (files for which :meth:`~io.IOBase.isatty` " "returns ``True``) use line buffering. Other text files use the policy " @@ -2534,7 +2697,7 @@ msgstr "" "isatty` retornam ``True``) usam buffering de linha. Outros arquivos de texto " "usam a política descrita acima para arquivos binários." -#: ../../library/functions.rst:1390 +#: ../../library/functions.rst:1405 msgid "" "*encoding* is the name of the encoding used to decode or encode the file. " "This should only be used in text mode. The default encoding is platform " @@ -2548,7 +2711,7 @@ msgstr "" "mas qualquer :term:`codificador de texto` suportado pelo Python pode ser " "usada. Veja o módulo :mod:`codecs` para a lista de codificações suportadas." -#: ../../library/functions.rst:1396 +#: ../../library/functions.rst:1411 msgid "" "*errors* is an optional string that specifies how encoding and decoding " "errors are to be handled—this cannot be used in binary mode. A variety of " @@ -2563,7 +2726,7 @@ msgstr "" "tratamento de erro registrado com :func:`codecs.register_error` também é " "válido. Os nomes padrões incluem:" -#: ../../library/functions.rst:1404 +#: ../../library/functions.rst:1419 msgid "" "``'strict'`` to raise a :exc:`ValueError` exception if there is an encoding " "error. The default value of ``None`` has the same effect." @@ -2571,7 +2734,7 @@ msgstr "" "``'strict'`` para levantar uma exceção :exc:`ValueError` se existir um erro " "de codificação. O valor padrão ``None`` tem o mesmo efeito." -#: ../../library/functions.rst:1408 +#: ../../library/functions.rst:1423 msgid "" "``'ignore'`` ignores errors. Note that ignoring encoding errors can lead to " "data loss." @@ -2579,7 +2742,7 @@ msgstr "" "``'ignore'`` ignora erros. Note que ignorar erros de código pode levar à " "perda de dados." -#: ../../library/functions.rst:1411 +#: ../../library/functions.rst:1426 msgid "" "``'replace'`` causes a replacement marker (such as ``'?'``) to be inserted " "where there is malformed data." @@ -2587,7 +2750,7 @@ msgstr "" "``'replace'`` faz um marcador de substituição (tal como ``'?'``) ser " "inserido onde existem dados malformados." -#: ../../library/functions.rst:1414 +#: ../../library/functions.rst:1429 msgid "" "``'surrogateescape'`` will represent any incorrect bytes as low surrogate " "code units ranging from U+DC80 to U+DCFF. These surrogate code units will " @@ -2601,7 +2764,7 @@ msgstr "" "erros for usado ao gravar dados. Isso é útil para processar arquivos em uma " "codificação desconhecida." -#: ../../library/functions.rst:1421 +#: ../../library/functions.rst:1436 msgid "" "``'xmlcharrefreplace'`` is only supported when writing to a file. Characters " "not supported by the encoding are replaced with the appropriate XML " @@ -2611,7 +2774,7 @@ msgstr "" "caracteres não suportados pela codificação são substituídos pela referência " "de caracteres XML apropriada :samp:`&#{nnn};`." -#: ../../library/functions.rst:1425 +#: ../../library/functions.rst:1440 msgid "" "``'backslashreplace'`` replaces malformed data by Python's backslashed " "escape sequences." @@ -2619,7 +2782,7 @@ msgstr "" "``'backslashreplace'`` substitui dados malformados pela sequência de escape " "utilizando contrabarra do Python." -#: ../../library/functions.rst:1428 +#: ../../library/functions.rst:1443 msgid "" "``'namereplace'`` (also only supported when writing) replaces unsupported " "characters with ``\\N{...}`` escape sequences." @@ -2627,7 +2790,7 @@ msgstr "" "``'namereplace'`` (também é suportado somente quando estiver escrevendo) " "substitui caractere não suportados com sequências de escape ``\\N{...}``." -#: ../../library/functions.rst:1436 +#: ../../library/functions.rst:1451 msgid "" "*newline* determines how to parse newline characters from the stream. It can " "be ``None``, ``''``, ``'\\n'``, ``'\\r'``, and ``'\\r\\n'``. It works as " @@ -2637,7 +2800,7 @@ msgstr "" "pode ser ``None``, ``''``, ``'\\n'``, ``'\\r'`` e ``'\\r\\n'``. Ele funciona " "da seguinte forma:" -#: ../../library/functions.rst:1440 +#: ../../library/functions.rst:1455 msgid "" "When reading input from the stream, if *newline* is ``None``, universal " "newlines mode is enabled. Lines in the input can end in ``'\\n'``, " @@ -2656,7 +2819,7 @@ msgstr "" "apenas pela string especificada e a finalização da linha é retornada ao " "chamador sem tradução." -#: ../../library/functions.rst:1448 +#: ../../library/functions.rst:1463 msgid "" "When writing output to the stream, if *newline* is ``None``, any ``'\\n'`` " "characters written are translated to the system default line separator, :" @@ -2670,7 +2833,7 @@ msgstr "" "tradução ocorrerá. Se *newline* for um dos outros valores legais, qualquer " "caractere ``'\\n'`` escrito será traduzido para a string especificada." -#: ../../library/functions.rst:1454 +#: ../../library/functions.rst:1469 msgid "" "If *closefd* is ``False`` and a file descriptor rather than a filename was " "given, the underlying file descriptor will be kept open when the file is " @@ -2682,7 +2845,7 @@ msgstr "" "quando o arquivo for fechado. Se um nome de arquivo for fornecido *closefd* " "deve ser ``True`` (o padrão), caso contrário, um erro será levantado." -#: ../../library/functions.rst:1459 +#: ../../library/functions.rst:1474 msgid "" "A custom opener can be used by passing a callable as *opener*. The " "underlying file descriptor for the file object is then obtained by calling " @@ -2696,11 +2859,11 @@ msgstr "" "arquivo aberto (passando :mod:`os.open` como *opener* resulta em " "funcionalidade semelhante à passagem de ``None``)." -#: ../../library/functions.rst:1465 +#: ../../library/functions.rst:1480 msgid "The newly created file is :ref:`non-inheritable `." msgstr "O arquivo recém-criado é :ref:`non-inheritable `." -#: ../../library/functions.rst:1467 +#: ../../library/functions.rst:1482 msgid "" "The following example uses the :ref:`dir_fd ` parameter of the :func:" "`os.open` function to open a file relative to a given directory::" @@ -2708,7 +2871,29 @@ msgstr "" "O exemplo a seguir usa o parâmetro :ref:`dir_fd ` da função :func:" "`os.open` para abrir um arquivo relativo a um determinado diretório::" -#: ../../library/functions.rst:1480 +#: ../../library/functions.rst:1485 +msgid "" +">>> import os\n" +">>> dir_fd = os.open('somedir', os.O_RDONLY)\n" +">>> def opener(path, flags):\n" +"... return os.open(path, flags, dir_fd=dir_fd)\n" +"...\n" +">>> with open('spamspam.txt', 'w', opener=opener) as f:\n" +"... print('This will be written to somedir/spamspam.txt', file=f)\n" +"...\n" +">>> os.close(dir_fd) # don't leak a file descriptor" +msgstr "" +">>> import os\n" +">>> dir_fd = os.open('algum_dir', os.O_RDONLY)\n" +">>> def opener(path, flags):\n" +"... return os.open(path, flags, dir_fd=dir_fd)\n" +"...\n" +">>> with open('spamspam.txt', 'w', opener=opener) as f:\n" +"... print('Isso será escrito para algum_dir/spamspam.txt', file=f)\n" +"...\n" +">>> os.close(dir_fd) # não deixe vazar um descritor de arquivo" + +#: ../../library/functions.rst:1495 msgid "" "The type of :term:`file object` returned by the :func:`open` function " "depends on the mode. When :func:`open` is used to open a file in a text " @@ -2735,7 +2920,7 @@ msgstr "" "bruto, uma subclasse de :class:`io.RawIOBase`, :class:`io.FileIO`, é " "retornado." -#: ../../library/functions.rst:1501 +#: ../../library/functions.rst:1516 msgid "" "See also the file handling modules, such as :mod:`fileinput`, :mod:`io` " "(where :func:`open` is declared), :mod:`os`, :mod:`os.path`, :mod:" @@ -2745,7 +2930,7 @@ msgstr "" "`fileinput`, :mod:`io` (onde :func:`open` é declarado), :mod:`os`, :mod:`os." "path`, :mod:`tempfile` e :mod:`shutil`." -#: ../../library/functions.rst:1505 +#: ../../library/functions.rst:1520 msgid "" "Raises an :ref:`auditing event ` ``open`` with arguments ``path``, " "``mode``, ``flags``." @@ -2753,7 +2938,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``open`` com os argumentos " "``path``, ``mode``, ``flags``." -#: ../../library/functions.rst:1507 +#: ../../library/functions.rst:1522 msgid "" "The ``mode`` and ``flags`` arguments may have been modified or inferred from " "the original call." @@ -2761,21 +2946,21 @@ msgstr "" "Os argumentos ``mode`` e ``flags`` podem ter sido modificados ou inferidos a " "partir da chamada original." -#: ../../library/functions.rst:1512 +#: ../../library/functions.rst:1527 msgid "The *opener* parameter was added." msgstr "O parâmetro *opener* foi adicionado." -#: ../../library/functions.rst:1513 +#: ../../library/functions.rst:1528 msgid "The ``'x'`` mode was added." msgstr "O modo ``'x'`` foi adicionado." -#: ../../library/functions.rst:1514 +#: ../../library/functions.rst:1529 msgid ":exc:`IOError` used to be raised, it is now an alias of :exc:`OSError`." msgstr "" -":exc:`IOError` costumava ser levantado, agora ele é um codinome para :exc:" +":exc:`IOError` costumava ser levantada, agora ela é um apelido para :exc:" "`OSError`." -#: ../../library/functions.rst:1515 +#: ../../library/functions.rst:1530 msgid "" ":exc:`FileExistsError` is now raised if the file opened in exclusive " "creation mode (``'x'``) already exists." @@ -2783,11 +2968,11 @@ msgstr "" ":exc:`FileExistsError` agora é levantado se o arquivo aberto no modo de " "criação exclusivo (``'x'``) já existir." -#: ../../library/functions.rst:1520 +#: ../../library/functions.rst:1535 msgid "The file is now non-inheritable." msgstr "O arquivo agora é não herdável." -#: ../../library/functions.rst:1524 +#: ../../library/functions.rst:1539 msgid "" "If the system call is interrupted and the signal handler does not raise an " "exception, the function now retries the system call instead of raising an :" @@ -2798,16 +2983,16 @@ msgstr "" "levantar uma exceção :exc:`InterruptedError` (consulte :pep:`475` para " "entender a justificativa)." -#: ../../library/functions.rst:1527 +#: ../../library/functions.rst:1542 msgid "The ``'namereplace'`` error handler was added." msgstr "O tratador de erros ``'namereplace'`` foi adicionado." -#: ../../library/functions.rst:1531 +#: ../../library/functions.rst:1546 msgid "Support added to accept objects implementing :class:`os.PathLike`." msgstr "" "Suporte adicionado para aceitar objetos implementados :class:`os.PathLike`." -#: ../../library/functions.rst:1532 +#: ../../library/functions.rst:1547 msgid "" "On Windows, opening a console buffer may return a subclass of :class:`io." "RawIOBase` other than :class:`io.FileIO`." @@ -2815,11 +3000,11 @@ msgstr "" "No Windows, a abertura de um buffer do console pode retornar uma subclasse " "de :class:`io.RawIOBase` que não seja :class:`io.FileIO`." -#: ../../library/functions.rst:1535 +#: ../../library/functions.rst:1550 msgid "The ``'U'`` mode has been removed." msgstr "O modo ``'U'`` foi removido." -#: ../../library/functions.rst:1540 +#: ../../library/functions.rst:1555 msgid "" "Given a string representing one Unicode character, return an integer " "representing the Unicode code point of that character. For example, " @@ -2831,7 +3016,7 @@ msgstr "" "exemplo, ``ord('a')`` retorna o número inteiro ``97`` e ``ord('€')`` (sinal " "do Euro) retorna ``8364``. Este é o inverso de :func:`chr`." -#: ../../library/functions.rst:1548 +#: ../../library/functions.rst:1563 msgid "" "Return *base* to the power *exp*; if *mod* is present, return *base* to the " "power *exp*, modulo *mod* (computed more efficiently than ``pow(base, exp) % " @@ -2843,7 +3028,7 @@ msgstr "" "``pow(base, exp) % mod``). A forma de dois argumentos ``pow(base, exp)`` é " "equivalente a usar o operador de potência: ``base**exp``." -#: ../../library/functions.rst:1553 +#: ../../library/functions.rst:1568 msgid "" "The arguments must have numeric types. With mixed operand types, the " "coercion rules for binary arithmetic operators apply. For :class:`int` " @@ -2870,7 +3055,7 @@ msgstr "" "com um expoente integral, um resultado de ponto flutuante é retornado. Por " "exemplo, ``pow(-9, 2.0)`` retorna ``81.0``." -#: ../../library/functions.rst:1565 +#: ../../library/functions.rst:1580 msgid "" "For :class:`int` operands *base* and *exp*, if *mod* is present, *mod* must " "also be of integer type and *mod* must be nonzero. If *mod* is present and " @@ -2884,12 +3069,24 @@ msgstr "" "para *mod*. Nesse caso, ``pow(inv_base, -exp, mod)`` é retornado, onde " "*inv_base* é um inverso ao *base* módulo *mod*." -#: ../../library/functions.rst:1571 +#: ../../library/functions.rst:1586 msgid "Here's an example of computing an inverse for ``38`` modulo ``97``::" msgstr "" "Aqui está um exemplo de computação de um inverso para ``38`` módulo ``97``::" -#: ../../library/functions.rst:1578 +#: ../../library/functions.rst:1588 +msgid "" +">>> pow(38, -1, mod=97)\n" +"23\n" +">>> 23 * 38 % 97 == 1\n" +"True" +msgstr "" +">>> pow(38, -1, mod=97)\n" +"23\n" +">>> 23 * 38 % 97 == 1\n" +"True" + +#: ../../library/functions.rst:1593 msgid "" "For :class:`int` operands, the three-argument form of ``pow`` now allows the " "second argument to be negative, permitting computation of modular inverses." @@ -2898,14 +3095,14 @@ msgstr "" "permite que o segundo argumento seja negativo, permitindo o cálculo de " "inversos modulares." -#: ../../library/functions.rst:1583 +#: ../../library/functions.rst:1598 msgid "" "Allow keyword arguments. Formerly, only positional arguments were supported." msgstr "" "Permite argumentos de palavra reservada. Anteriormente, apenas argumentos " "posicionais eram suportados." -#: ../../library/functions.rst:1590 +#: ../../library/functions.rst:1605 msgid "" "Print *objects* to the text stream *file*, separated by *sep* and followed " "by *end*. *sep*, *end*, *file*, and *flush*, if present, must be given as " @@ -2915,7 +3112,7 @@ msgstr "" "por *end*. *sep*, *end*, *file* e *flush*, se houver, devem ser fornecidos " "como argumentos nomeados." -#: ../../library/functions.rst:1594 +#: ../../library/functions.rst:1609 msgid "" "All non-keyword arguments are converted to strings like :func:`str` does and " "written to the stream, separated by *sep* and followed by *end*. Both *sep* " @@ -2929,7 +3126,7 @@ msgstr "" "que significa usar os valores padrão. Se nenhum *object* for fornecido, :" "func:`print` escreverá apenas *end*." -#: ../../library/functions.rst:1600 +#: ../../library/functions.rst:1615 msgid "" "The *file* argument must be an object with a ``write(string)`` method; if it " "is not present or ``None``, :data:`sys.stdout` will be used. Since printed " @@ -2939,10 +3136,10 @@ msgstr "" "O argumento *file* deve ser um objeto com um método ``write(string)``; se " "ele não estiver presente ou ``None``, então :data:`sys.stdout` será usado. " "Como argumentos exibidos no console são convertidos para strings de texto, :" -"func:`print` não pode ser usado com objetos de arquivo em modo binário. Para " +"func:`print` não pode ser usado com objetos arquivo em modo binário. Para " "esses casos, use ``file.write(...)`` ao invés." -#: ../../library/functions.rst:1605 +#: ../../library/functions.rst:1620 msgid "" "Output buffering is usually determined by *file*. However, if *flush* is " "true, the stream is forcibly flushed." @@ -2950,15 +3147,15 @@ msgstr "" "O buffer de saída geralmente é determinado por *arquivo*. No entanto, se " "*flush* for verdadeiro, o fluxo será descarregado à força." -#: ../../library/functions.rst:1609 +#: ../../library/functions.rst:1624 msgid "Added the *flush* keyword argument." msgstr "Adicionado o argumento nomeado *flush*." -#: ../../library/functions.rst:1615 +#: ../../library/functions.rst:1630 msgid "Return a property attribute." msgstr "Retorna um atributo de propriedade." -#: ../../library/functions.rst:1617 +#: ../../library/functions.rst:1632 msgid "" "*fget* is a function for getting an attribute value. *fset* is a function " "for setting an attribute value. *fdel* is a function for deleting an " @@ -2968,19 +3165,51 @@ msgstr "" "para definir um valor para um atributo. *fdel* é uma função para deletar um " "valor de um atributo. E *doc* cria um docstring para um atributo." -#: ../../library/functions.rst:1621 +#: ../../library/functions.rst:1636 msgid "A typical use is to define a managed attribute ``x``::" msgstr "Um uso comum é para definir um atributo gerenciável ``x``::" #: ../../library/functions.rst:1638 msgid "" +"class C:\n" +" def __init__(self):\n" +" self._x = None\n" +"\n" +" def getx(self):\n" +" return self._x\n" +"\n" +" def setx(self, value):\n" +" self._x = value\n" +"\n" +" def delx(self):\n" +" del self._x\n" +"\n" +" x = property(getx, setx, delx, \"I'm the 'x' property.\")" +msgstr "" +"class C:\n" +" def __init__(self):\n" +" self._x = None\n" +"\n" +" def getx(self):\n" +" return self._x\n" +"\n" +" def setx(self, valor):\n" +" self._x = valor\n" +"\n" +" def delx(self):\n" +" del self._x\n" +"\n" +" x = property(getx, setx, delx, \"Eu sou a propriedade de 'x'.\")" + +#: ../../library/functions.rst:1653 +msgid "" "If *c* is an instance of *C*, ``c.x`` will invoke the getter, ``c.x = " "value`` will invoke the setter, and ``del c.x`` the deleter." msgstr "" "Se *c* é uma instância de *C*, ``c.x`` irá invocar o método getter, ``c.x = " -"value`` irá invocar o método setter, e ``del c.x`` o método deleter." +"valor`` irá invocar o método setter, e ``del c.x`` o método deleter." -#: ../../library/functions.rst:1641 +#: ../../library/functions.rst:1656 msgid "" "If given, *doc* will be the docstring of the property attribute. Otherwise, " "the property will copy *fget*'s docstring (if it exists). This makes it " @@ -2992,7 +3221,27 @@ msgstr "" "torna possível criar facilmente propriedades apenas para leitura usando :" "func:`property` como um :term:`decorador`::" -#: ../../library/functions.rst:1654 +#: ../../library/functions.rst:1660 +msgid "" +"class Parrot:\n" +" def __init__(self):\n" +" self._voltage = 100000\n" +"\n" +" @property\n" +" def voltage(self):\n" +" \"\"\"Get the current voltage.\"\"\"\n" +" return self._voltage" +msgstr "" +"class Parrot:\n" +" def __init__(self):\n" +" self._voltagem = 100000\n" +"\n" +" @property\n" +" def voltagem(self):\n" +" \"\"\"Obtém a voltagem atual.\"\"\"\n" +" return self._voltagem" + +#: ../../library/functions.rst:1669 msgid "" "The ``@property`` decorator turns the :meth:`!voltage` method into a " "\"getter\" for a read-only attribute with the same name, and it sets the " @@ -3002,7 +3251,7 @@ msgstr "" "\"getter\" para um atributo somente leitura com o mesmo nome, e define a " "docstring de *voltage* para \"Get the current voltage.\"" -#: ../../library/functions.rst:1662 +#: ../../library/functions.rst:1677 msgid "" "A property object has ``getter``, ``setter``, and ``deleter`` methods usable " "as decorators that create a copy of the property with the corresponding " @@ -3014,7 +3263,43 @@ msgstr "" "correspondente a função definida para a função com decorador. Isso é " "explicado melhor com um exemplo::" -#: ../../library/functions.rst:1686 +#: ../../library/functions.rst:1682 +msgid "" +"class C:\n" +" def __init__(self):\n" +" self._x = None\n" +"\n" +" @property\n" +" def x(self):\n" +" \"\"\"I'm the 'x' property.\"\"\"\n" +" return self._x\n" +"\n" +" @x.setter\n" +" def x(self, value):\n" +" self._x = value\n" +"\n" +" @x.deleter\n" +" def x(self):\n" +" del self._x" +msgstr "" +"class C:\n" +" def __init__(self):\n" +" self._x = None\n" +"\n" +" @property\n" +" def x(self):\n" +" \"\"\"Sou a propriedade de 'x'.\"\"\"\n" +" return self._x\n" +"\n" +" @x.setter\n" +" def x(self, value):\n" +" self._x = value\n" +"\n" +" @x.deleter\n" +" def x(self):\n" +" del self._x" + +#: ../../library/functions.rst:1701 msgid "" "This code is exactly equivalent to the first example. Be sure to give the " "additional functions the same name as the original property (``x`` in this " @@ -3024,7 +3309,7 @@ msgstr "" "nas funções adicionais usar o mesmo nome que a property original (``x`` " "neste caso)." -#: ../../library/functions.rst:1690 +#: ../../library/functions.rst:1705 msgid "" "The returned property object also has the attributes ``fget``, ``fset``, and " "``fdel`` corresponding to the constructor arguments." @@ -3032,11 +3317,19 @@ msgstr "" "O objeto property retornado também tem os atributos ``fget``, ``fset``, e " "``fdel`` correspondendo aos argumentos do construtor." -#: ../../library/functions.rst:1693 +#: ../../library/functions.rst:1708 msgid "The docstrings of property objects are now writeable." msgstr "Agora é possível escrever nas docstrings de objetos property." -#: ../../library/functions.rst:1702 +#: ../../library/functions.rst:1713 +msgid "" +"Attribute holding the name of the property. The name of the property can be " +"changed at runtime." +msgstr "" +"Atributo que contém o nome da propriedade. O nome da propriedade pode ser " +"alterado em tempo de execução." + +#: ../../library/functions.rst:1724 msgid "" "Rather than being a function, :class:`range` is actually an immutable " "sequence type, as documented in :ref:`typesseq-range` and :ref:`typesseq`." @@ -3044,7 +3337,7 @@ msgstr "" "Em vez de ser uma função, :class:`range` é realmente um tipo de sequência " "imutável, conforme documentado em :ref:`typesseq-range` e :ref:`typesseq`." -#: ../../library/functions.rst:1708 +#: ../../library/functions.rst:1730 msgid "" "Return a string containing a printable representation of an object. For " "many types, this function makes an attempt to return a string that would " @@ -3066,12 +3359,30 @@ msgstr "" "Se :func:`sys.displayhook` não estiver acessível, esta função vai levantar :" "exc:`RuntimeError`." -#: ../../library/functions.rst:1719 +#: ../../library/functions.rst:1741 msgid "This class has a custom representation that can be evaluated::" msgstr "" "Esta classe possui uma representação personalizada que pode ser executada::" -#: ../../library/functions.rst:1732 +#: ../../library/functions.rst:1743 +msgid "" +"class Person:\n" +" def __init__(self, name, age):\n" +" self.name = name\n" +" self.age = age\n" +"\n" +" def __repr__(self):\n" +" return f\"Person('{self.name}', {self.age})\"" +msgstr "" +"class Pessoa:\n" +" def __init__(self, nome, idade):\n" +" self.name = nome\n" +" self.age = idade\n" +"\n" +" def __repr__(self):\n" +" return f\"Pessoa('{self.nome}', {self.idade})\"" + +#: ../../library/functions.rst:1754 msgid "" "Return a reverse :term:`iterator`. *seq* must be an object which has a :" "meth:`~object.__reversed__` method or supports the sequence protocol (the :" @@ -3083,7 +3394,7 @@ msgstr "" "sequência (o método :meth:`~object.__len__` e o método :meth:`~object." "__getitem__` com argumentos inteiros começando em ``0``)." -#: ../../library/functions.rst:1740 +#: ../../library/functions.rst:1762 msgid "" "Return *number* rounded to *ndigits* precision after the decimal point. If " "*ndigits* is omitted or is ``None``, it returns the nearest integer to its " @@ -3093,7 +3404,7 @@ msgstr "" "Se *ndigits* for omitido ou for ``None``, ele retornará o número inteiro " "mais próximo de sua entrada." -#: ../../library/functions.rst:1744 +#: ../../library/functions.rst:1766 msgid "" "For the built-in types supporting :func:`round`, values are rounded to the " "closest multiple of 10 to the power minus *ndigits*; if two multiples are " @@ -3112,7 +3423,7 @@ msgstr "" "inteiro se *ndigits* for omitido ou ``None``. Caso contrário, o valor de " "retorno tem o mesmo tipo que *number*." -#: ../../library/functions.rst:1753 +#: ../../library/functions.rst:1775 msgid "" "For a general Python object ``number``, ``round`` delegates to ``number." "__round__``." @@ -3120,7 +3431,7 @@ msgstr "" "Para um objeto Python geral ``number``, ``round`` delega para ``number." "__round__``." -#: ../../library/functions.rst:1758 +#: ../../library/functions.rst:1780 msgid "" "The behavior of :func:`round` for floats can be surprising: for example, " "``round(2.675, 2)`` gives ``2.67`` instead of the expected ``2.68``. This is " @@ -3134,7 +3445,7 @@ msgstr "" "das frações decimais não pode ser representada exatamente como um ponto " "flutuante. Veja :ref:`tut-fp-issues` para mais informações." -#: ../../library/functions.rst:1770 +#: ../../library/functions.rst:1792 msgid "" "Return a new :class:`set` object, optionally with elements taken from " "*iterable*. ``set`` is a built-in class. See :class:`set` and :ref:`types-" @@ -3144,7 +3455,7 @@ msgstr "" "de *iterable*. ``set`` é uma classe embutida. Veja :class:`set` e :ref:" "`types-set` para documentação sobre esta classe." -#: ../../library/functions.rst:1774 +#: ../../library/functions.rst:1796 msgid "" "For other containers see the built-in :class:`frozenset`, :class:`list`, :" "class:`tuple`, and :class:`dict` classes, as well as the :mod:`collections` " @@ -3154,7 +3465,7 @@ msgstr "" "class:`list`, :class:`tuple` e :class:`dict`, bem como o módulo :mod:" "`collections`." -#: ../../library/functions.rst:1781 +#: ../../library/functions.rst:1803 msgid "" "This is the counterpart of :func:`getattr`. The arguments are an object, a " "string, and an arbitrary value. The string may name an existing attribute " @@ -3168,7 +3479,7 @@ msgstr "" "permita. Por exemplo, ``setattr(x, 'foobar', 123)`` é equivalente a ``x." "foobar = 123``." -#: ../../library/functions.rst:1787 +#: ../../library/functions.rst:1809 msgid "" "*name* need not be a Python identifier as defined in :ref:`identifiers` " "unless the object chooses to enforce that, for example in a custom :meth:" @@ -3183,7 +3494,7 @@ msgstr "" "usando a notação de ponto, mas pode ser acessado através de :func:`getattr` " "etc." -#: ../../library/functions.rst:1795 +#: ../../library/functions.rst:1817 msgid "" "Since :ref:`private name mangling ` happens at " "compilation time, one must manually mangle a private attribute's (attributes " @@ -3194,7 +3505,7 @@ msgstr "" "atributo privado (atributos com dois sublinhados à esquerda) para defini-lo " "com :func:`setattr`." -#: ../../library/functions.rst:1804 +#: ../../library/functions.rst:1826 msgid "" "Return a :term:`slice` object representing the set of indices specified by " "``range(start, stop, step)``. The *start* and *step* arguments default to " @@ -3204,7 +3515,7 @@ msgstr "" "especificados por ``range(start, stop, step)``. Os argumentos *start* e " "*step* têm o padrão ``None``." -#: ../../library/functions.rst:1812 +#: ../../library/functions.rst:1834 msgid "" "Slice objects have read-only data attributes :attr:`!start`, :attr:`!stop`, " "and :attr:`!step` which merely return the argument values (or their " @@ -3216,7 +3527,7 @@ msgstr "" "(ou seus padrões). Eles não possuem outra funcionalidade explícita; no " "entanto, eles são usados pelo NumPy e outros pacotes de terceiros." -#: ../../library/functions.rst:1817 +#: ../../library/functions.rst:1839 msgid "" "Slice objects are also generated when extended indexing syntax is used. For " "example: ``a[start:stop:step]`` or ``a[start:stop, i]``. See :func:" @@ -3227,7 +3538,7 @@ msgstr "" "func:`itertools.islice` para uma versão alternativa que retorna um :term:" "`iterador`." -#: ../../library/functions.rst:1822 +#: ../../library/functions.rst:1844 msgid "" "Slice objects are now :term:`hashable` (provided :attr:`~slice.start`, :attr:" "`~slice.stop`, and :attr:`~slice.step` are hashable)." @@ -3235,18 +3546,18 @@ msgstr "" "Os objetos slice agora são :term:`hasheáveis ` (desde que :attr:" "`~slice.start`, :attr:`~slice.stop` e :attr:`~slice.step` sejam hasheáveis)." -#: ../../library/functions.rst:1828 +#: ../../library/functions.rst:1850 msgid "Return a new sorted list from the items in *iterable*." msgstr "Retorna uma nova lista classificada dos itens em *iterable*." -#: ../../library/functions.rst:1830 +#: ../../library/functions.rst:1852 msgid "" "Has two optional arguments which must be specified as keyword arguments." msgstr "" "Possui dois argumentos opcionais que devem ser especificados como argumentos " "nomeados." -#: ../../library/functions.rst:1832 +#: ../../library/functions.rst:1854 msgid "" "*key* specifies a function of one argument that is used to extract a " "comparison key from each element in *iterable* (for example, ``key=str." @@ -3256,7 +3567,7 @@ msgstr "" "comparação de cada elemento em *iterable* (por exemplo, ``key=str.lower``). " "O valor padrão é ``None`` (compara os elementos diretamente)." -#: ../../library/functions.rst:1836 +#: ../../library/functions.rst:1858 msgid "" "*reverse* is a boolean value. If set to ``True``, then the list elements " "are sorted as if each comparison were reversed." @@ -3265,7 +3576,7 @@ msgstr "" "elementos da lista são classificados como se cada comparação estivesse " "invertida." -#: ../../library/functions.rst:1839 +#: ../../library/functions.rst:1861 msgid "" "Use :func:`functools.cmp_to_key` to convert an old-style *cmp* function to a " "*key* function." @@ -3273,7 +3584,7 @@ msgstr "" "Usa :func:`functools.cmp_to_key` para converter a função das antigas *cmp* " "para uma função *key*." -#: ../../library/functions.rst:1842 +#: ../../library/functions.rst:1864 msgid "" "The built-in :func:`sorted` function is guaranteed to be stable. A sort is " "stable if it guarantees not to change the relative order of elements that " @@ -3285,7 +3596,7 @@ msgstr "" "comparam da mesma forma --- isso é útil para ordenar em várias passagens " "(por exemplo, ordenar por departamento e depois por nível de salário)." -#: ../../library/functions.rst:1847 +#: ../../library/functions.rst:1869 msgid "" "The sort algorithm uses only ``<`` comparisons between items. While " "defining an :meth:`~object.__lt__` method will suffice for sorting, :PEP:`8` " @@ -3305,18 +3616,18 @@ msgstr "" "comparações também ajuda a evitar confusão para comparações de tipo misto " "que podem chamar refletido o método :meth:`~object.__gt__`." -#: ../../library/functions.rst:1856 +#: ../../library/functions.rst:1878 msgid "" "For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`." msgstr "" "Para exemplos de classificação e um breve tutorial de classificação, veja :" "ref:`sortinghowto`." -#: ../../library/functions.rst:1860 +#: ../../library/functions.rst:1882 msgid "Transform a method into a static method." msgstr "Transforma um método em método estático." -#: ../../library/functions.rst:1862 +#: ../../library/functions.rst:1884 msgid "" "A static method does not receive an implicit first argument. To declare a " "static method, use this idiom::" @@ -3324,7 +3635,17 @@ msgstr "" "Um método estático não recebe um primeiro argumento implícito. Para declarar " "um método estático, use este idioma::" -#: ../../library/functions.rst:1869 +#: ../../library/functions.rst:1887 +msgid "" +"class C:\n" +" @staticmethod\n" +" def f(arg1, arg2, argN): ..." +msgstr "" +"class C:\n" +" @staticmethod\n" +" def f(arg1, arg2, argN): ..." + +#: ../../library/functions.rst:1891 msgid "" "The ``@staticmethod`` form is a function :term:`decorator` -- see :ref:" "`function` for details." @@ -3332,7 +3653,7 @@ msgstr "" "A forma ``@staticmethod`` é uma função de :term:`decorador` -- veja :ref:" "`function` para detalhes." -#: ../../library/functions.rst:1872 +#: ../../library/functions.rst:1894 msgid "" "A static method can be called either on the class (such as ``C.f()``) or on " "an instance (such as ``C().f()``). Moreover, the static method :term:" @@ -3344,7 +3665,7 @@ msgstr "" "estático também é um chamável, então ele pode ser usado na definição de " "classe (como ``f()``)." -#: ../../library/functions.rst:1877 +#: ../../library/functions.rst:1899 msgid "" "Static methods in Python are similar to those found in Java or C++. Also, " "see :func:`classmethod` for a variant that is useful for creating alternate " @@ -3354,7 +3675,7 @@ msgstr "" "+. Veja também :func:`classmethod` para uma variante útil na criação de " "construtores de classe alternativos." -#: ../../library/functions.rst:1881 +#: ../../library/functions.rst:1903 msgid "" "Like all decorators, it is also possible to call ``staticmethod`` as a " "regular function and do something with its result. This is needed in some " @@ -3368,28 +3689,44 @@ msgstr "" "corpo de classe e deseja evitar a transformação automática em método de " "instância. Para esses casos, use este idioma::" -#: ../../library/functions.rst:1893 +#: ../../library/functions.rst:1909 +msgid "" +"def regular_function():\n" +" ...\n" +"\n" +"class C:\n" +" method = staticmethod(regular_function)" +msgstr "" +"def função_comum():\n" +" ...\n" +"\n" +"class C:\n" +" método = staticmethod(função_comum)" + +#: ../../library/functions.rst:1915 msgid "For more information on static methods, see :ref:`types`." msgstr "Para mais informações sobre métodos estáticos, consulte :ref:`types`." -#: ../../library/functions.rst:1895 +#: ../../library/functions.rst:1917 msgid "" -"Static methods now inherit the method attributes (``__module__``, " -"``__name__``, ``__qualname__``, ``__doc__`` and ``__annotations__``), have a " -"new ``__wrapped__`` attribute, and are now callable as regular functions." +"Static methods now inherit the method attributes (:attr:`~function." +"__module__`, :attr:`~function.__name__`, :attr:`~function.__qualname__`, :" +"attr:`~function.__doc__` and :attr:`~function.__annotations__`), have a new " +"``__wrapped__`` attribute, and are now callable as regular functions." msgstr "" -"Métodos estáticos agora herdam os atributos do método (``__module__``, " -"``__name__``, ``__qualname__``, ``__doc__`` e ``__annotations__``), têm um " -"novo atributo ``__wrapped__`` e agora são chamáveis como funções regulares." +"Métodos estáticos agora herdam os atributos do método (:attr:`~function." +"__module__`, :attr:`~function.__name__`, :attr:`~function.__qualname__`, :" +"attr:`~function.__doc__` e :attr:`~function.__annotations__`), têm um novo " +"atributo ``__wrapped__`` e são agora chamáveis como funções regulares." -#: ../../library/functions.rst:1910 +#: ../../library/functions.rst:1933 msgid "" "Return a :class:`str` version of *object*. See :func:`str` for details." msgstr "" "Retorna uma versão :class:`str` de *object*. Consulte :func:`str` para " "detalhes." -#: ../../library/functions.rst:1912 +#: ../../library/functions.rst:1935 msgid "" "``str`` is the built-in string :term:`class`. For general information about " "strings, see :ref:`textseq`." @@ -3397,7 +3734,7 @@ msgstr "" "``str`` é uma :term:`classe` de string embutida. Para informações gerais " "sobre strings, consulte :ref:`textseq`." -#: ../../library/functions.rst:1918 +#: ../../library/functions.rst:1941 msgid "" "Sums *start* and the items of an *iterable* from left to right and returns " "the total. The *iterable*'s items are normally numbers, and the start value " @@ -3407,7 +3744,7 @@ msgstr "" "retornam o total. Os itens do *iterable* são normalmente números e o valor " "inicial não pode ser uma string." -#: ../../library/functions.rst:1922 +#: ../../library/functions.rst:1945 msgid "" "For some use cases, there are good alternatives to :func:`sum`. The " "preferred, fast way to concatenate a sequence of strings is by calling ``''." @@ -3421,11 +3758,11 @@ msgstr "" "precisão estendida, consulte :func:`math.fsum`. Para concatenar uma série de " "iteráveis, considere usar :func:`itertools.chain`." -#: ../../library/functions.rst:1928 +#: ../../library/functions.rst:1951 msgid "The *start* parameter can be specified as a keyword argument." msgstr "O parâmetro *start* pode ser especificado como um argumento nomeado." -#: ../../library/functions.rst:1931 +#: ../../library/functions.rst:1954 msgid "" "Summation of floats switched to an algorithm that gives higher accuracy and " "better commutativity on most builds." @@ -3433,7 +3770,7 @@ msgstr "" "A soma dos pontos flutuantes foi alterada para um algoritmo que oferece " "maior precisão e melhor comutatividade na maioria das compilações." -#: ../../library/functions.rst:1938 +#: ../../library/functions.rst:1961 msgid "" "Return a proxy object that delegates method calls to a parent or sibling " "class of *type*. This is useful for accessing inherited methods that have " @@ -3443,7 +3780,7 @@ msgstr "" "irmão do *type*. Isso é útil para acessar métodos herdados que foram " "substituídos em uma classe." -#: ../../library/functions.rst:1942 +#: ../../library/functions.rst:1965 msgid "" "The *object_or_type* determines the :term:`method resolution order` to be " "searched. The search starts from the class right after the *type*." @@ -3451,29 +3788,29 @@ msgstr "" "O *object_or_type* determina a :term:`ordem de resolução de métodos` a ser " "pesquisada. A pesquisa inicia a partir da classe logo após o *type*." -#: ../../library/functions.rst:1946 +#: ../../library/functions.rst:1969 msgid "" -"For example, if :attr:`~class.__mro__` of *object_or_type* is ``D -> B -> C -" +"For example, if :attr:`~type.__mro__` of *object_or_type* is ``D -> B -> C -" "> A -> object`` and the value of *type* is ``B``, then :func:`super` " "searches ``C -> A -> object``." msgstr "" -"Por exemplo, se :attr:`~class.__mro__` de *object_or_type* é ``D -> B -> C -" -"> A -> object`` e o valor de *type* é ``B``, então :func:`super` procura por " +"Por exemplo, se :attr:`~type.__mro__` de *object_or_type* é ``D -> B -> C -> " +"A -> object`` e o valor de *type* é ``B``, então :func:`super` procura por " "``C -> A -> object``." -#: ../../library/functions.rst:1950 +#: ../../library/functions.rst:1973 msgid "" -"The :attr:`~class.__mro__` attribute of the *object_or_type* lists the " -"method resolution search order used by both :func:`getattr` and :func:" -"`super`. The attribute is dynamic and can change whenever the inheritance " -"hierarchy is updated." +"The :attr:`~type.__mro__` attribute of the class corresponding to " +"*object_or_type* lists the method resolution search order used by both :func:" +"`getattr` and :func:`super`. The attribute is dynamic and can change " +"whenever the inheritance hierarchy is updated." msgstr "" -"O atributo :attr:`~class.__mro__` do *object_or_type* lista a ordem de " -"pesquisa de resolução de método usada por :func:`getattr` e :func:`super`. O " -"atributo é dinâmico e pode mudar sempre que a hierarquia da herança é " -"atualizada." +"O atributo :attr:`~type.__mro__` da classe correspondente ao " +"*object_or_type* lista a ordem de pesquisa de resolução de método usada por :" +"func:`getattr` e :func:`super`. O atributo é dinâmico e pode mudar sempre " +"que a hierarquia da herança é atualizada." -#: ../../library/functions.rst:1955 +#: ../../library/functions.rst:1978 msgid "" "If the second argument is omitted, the super object returned is unbound. If " "the second argument is an object, ``isinstance(obj, type)`` must be true. " @@ -3485,7 +3822,7 @@ msgstr "" "verdadeiro. Se o segundo argumento é um tipo, ``issubclass(type2, type)`` " "deve ser verdadeiro (isto é útil para classmethods)." -#: ../../library/functions.rst:1960 +#: ../../library/functions.rst:1983 msgid "" "When called directly within an ordinary method of a class, both arguments " "may be omitted (\"zero-argument :func:`!super`\"). In this case, *type* will " @@ -3502,7 +3839,7 @@ msgstr "" "esperado em funções aninhadas, incluindo expressões geradoras, que criam " "funções aninhadas implicitamente.)" -#: ../../library/functions.rst:1967 +#: ../../library/functions.rst:1990 msgid "" "There are two typical use cases for *super*. In a class hierarchy with " "single inheritance, *super* can be used to refer to parent classes without " @@ -3510,11 +3847,11 @@ msgid "" "closely parallels the use of *super* in other programming languages." msgstr "" "Existem dois casos de uso típicos para *super*. Em uma hierarquia de classes " -"com herança única, *super* pode ser usado para se referir a classes-pai sem " +"com herança única, *super* pode ser usado para se referir a classes base sem " "nomeá-las explicitamente, tornando o código mais sustentável. Esse uso é " "paralelo ao uso de *super* em outras linguagens de programação." -#: ../../library/functions.rst:1972 +#: ../../library/functions.rst:1995 msgid "" "The second use case is to support cooperative multiple inheritance in a " "dynamic execution environment. This use case is unique to Python and is not " @@ -3537,12 +3874,24 @@ msgstr "" "e porque essa ordem pode incluir classes de irmãos desconhecidas antes do " "tempo de execução)." -#: ../../library/functions.rst:1982 +#: ../../library/functions.rst:2005 msgid "For both use cases, a typical superclass call looks like this::" msgstr "" "Nos dois casos de uso, uma chamada típica de superclasse se parece com isso::" -#: ../../library/functions.rst:1989 +#: ../../library/functions.rst:2007 +msgid "" +"class C(B):\n" +" def method(self, arg):\n" +" super().method(arg) # This does the same thing as:\n" +" # super(C, self).method(arg)" +msgstr "" +"class C(B):\n" +" def método(self, arg):\n" +" super().método(arg) # Isso faz o mesmo que:\n" +" # super(C, self).método(arg)" + +#: ../../library/functions.rst:2012 msgid "" "In addition to method lookups, :func:`super` also works for attribute " "lookups. One possible use case for this is calling :term:`descriptors " @@ -3552,7 +3901,7 @@ msgstr "" "de atributo. Um possível caso de uso para isso é chamar :term:`descritores " "` em uma classe pai ou irmã." -#: ../../library/functions.rst:1993 +#: ../../library/functions.rst:2016 msgid "" "Note that :func:`super` is implemented as part of the binding process for " "explicit dotted attribute lookups such as ``super().__getitem__(name)``. It " @@ -3569,7 +3918,7 @@ msgstr "" "definida para procuras implícitas usando instruções ou operadores como " "``super()[name]``." -#: ../../library/functions.rst:2001 +#: ../../library/functions.rst:2024 msgid "" "Also note that, aside from the zero argument form, :func:`super` is not " "limited to use inside methods. The two argument form specifies the " @@ -3586,7 +3935,7 @@ msgstr "" "corretamente a classe que está sendo definida, além de acessar a instância " "atual para métodos comuns." -#: ../../library/functions.rst:2008 +#: ../../library/functions.rst:2031 msgid "" "For practical suggestions on how to design cooperative classes using :func:" "`super`, see `guide to using super() `_." -#: ../../library/functions.rst:2018 +#: ../../library/functions.rst:2041 msgid "" "Rather than being a function, :class:`tuple` is actually an immutable " "sequence type, as documented in :ref:`typesseq-tuple` and :ref:`typesseq`." @@ -3604,17 +3953,17 @@ msgstr "" "Ao invés de ser uma função, :class:`tuple` é na verdade um tipo de sequência " "imutável, conforme documentado em :ref:`typesseq-tuple` e :ref:`typesseq`." -#: ../../library/functions.rst:2027 +#: ../../library/functions.rst:2050 msgid "" "With one argument, return the type of an *object*. The return value is a " "type object and generally the same object as returned by :attr:`object." -"__class__ `." +"__class__`." msgstr "" "Com um argumento, retorna o tipo de um *object*. O valor de retorno é um " "tipo de objeto e geralmente o mesmo objeto retornado por :attr:`object." -"__class__ `." +"__class__`." -#: ../../library/functions.rst:2031 +#: ../../library/functions.rst:2054 msgid "" "The :func:`isinstance` built-in function is recommended for testing the type " "of an object, because it takes subclasses into account." @@ -3622,33 +3971,45 @@ msgstr "" "A função embutida :func:`isinstance` é recomendada para testar o tipo de um " "objeto, porque ela leva sub-classes em consideração." -#: ../../library/functions.rst:2035 +#: ../../library/functions.rst:2057 msgid "" "With three arguments, return a new type object. This is essentially a " "dynamic form of the :keyword:`class` statement. The *name* string is the " -"class name and becomes the :attr:`~definition.__name__` attribute. The " -"*bases* tuple contains the base classes and becomes the :attr:`~class." -"__bases__` attribute; if empty, :class:`object`, the ultimate base of all " -"classes, is added. The *dict* dictionary contains attribute and method " -"definitions for the class body; it may be copied or wrapped before becoming " -"the :attr:`~object.__dict__` attribute. The following two statements create " -"identical :class:`type` objects:" +"class name and becomes the :attr:`~type.__name__` attribute. The *bases* " +"tuple contains the base classes and becomes the :attr:`~type.__bases__` " +"attribute; if empty, :class:`object`, the ultimate base of all classes, is " +"added. The *dict* dictionary contains attribute and method definitions for " +"the class body; it may be copied or wrapped before becoming the :attr:`~type." +"__dict__` attribute. The following two statements create identical :class:`!" +"type` objects:" msgstr "" "Com três argumentos, retorna um novo objeto type. Esta é essencialmente a " "forma dinâmica da instrução :keyword:`class`. A string *name* é o nome da " -"classe e se torna o atributo :attr:`~definition.__name__`. A tupla *bases* " -"contém as classes bases e se torna o atributo :attr:`~class.__bases__`; se " -"vazio, :class:`object`, a base final de todas as classes é adicionada. O " -"dicionário *dict* contém definições de atributo e método para o corpo da " -"classe; ele pode ser copiado ou envolto antes de se tornar o atributo :attr:" -"`~object.__dict__`. As duas instruções a seguir criam objetos :class:`type` " +"classe e se torna o atributo :attr:`~type.__name__`. A tupla *bases* contém " +"as classes bases e se torna o atributo :attr:`~type.__bases__`; se vazio, :" +"class:`object`, a base final de todas as classes é adicionada. O dicionário " +"*dict* contém definições de atributo e método para o corpo da classe; ele " +"pode ser copiado ou envolto antes de se tornar o atributo :attr:`~type." +"__dict__`. As duas instruções a seguir criam objetos :class:`!type` " "idênticos:" -#: ../../library/functions.rst:2050 -msgid "See also :ref:`bltin-type-objects`." -msgstr "Veja também :ref:`bltin-type-objects`." +#: ../../library/functions.rst:2072 +msgid "See also:" +msgstr "Veja também:" -#: ../../library/functions.rst:2052 +#: ../../library/functions.rst:2074 +msgid "" +":ref:`Documentation on attributes and methods on classes `." +msgstr "" +":ref:`Documentação sobre atributos e métodos em classes `." + +#: ../../library/functions.rst:2075 +msgid ":ref:`bltin-type-objects`" +msgstr ":ref:`bltin-type-objects`" + +#: ../../library/functions.rst:2077 msgid "" "Keyword arguments provided to the three argument form are passed to the " "appropriate metaclass machinery (usually :meth:`~object.__init_subclass__`) " @@ -3660,44 +4021,43 @@ msgstr "" "__init_subclass__`) da mesma forma que palavras-chave em uma definição de " "classe (além de *metaclasse*) fariam." -#: ../../library/functions.rst:2057 +#: ../../library/functions.rst:2082 msgid "See also :ref:`class-customization`." msgstr "Veja também :ref:`class-customization`." -#: ../../library/functions.rst:2059 +#: ../../library/functions.rst:2084 msgid "" -"Subclasses of :class:`type` which don't override ``type.__new__`` may no " +"Subclasses of :class:`!type` which don't override ``type.__new__`` may no " "longer use the one-argument form to get the type of an object." msgstr "" -"Subclasses de :class:`type` que não fazem sobrecarga de ``type.__new__`` não " -"podem mais usar a forma com apenas um argumento para obter o tipo de um " -"objeto." +"Subclasses de :class:`!type` que não substituem ``type.__new__`` não podem " +"mais usar a forma com apenas um argumento para obter o tipo de um objeto." -#: ../../library/functions.rst:2066 +#: ../../library/functions.rst:2091 msgid "" "Return the :attr:`~object.__dict__` attribute for a module, class, instance, " -"or any other object with a :attr:`~object.__dict__` attribute." +"or any other object with a :attr:`!__dict__` attribute." msgstr "" "Retorna o atributo :attr:`~object.__dict__` para um módulo, classe, " -"instância, or qualquer outro objeto com um atributo :attr:`~object.__dict__`." +"instância, or qualquer outro objeto com um atributo :attr:`!__dict__`." -#: ../../library/functions.rst:2069 +#: ../../library/functions.rst:2094 msgid "" "Objects such as modules and instances have an updateable :attr:`~object." "__dict__` attribute; however, other objects may have write restrictions on " -"their :attr:`~object.__dict__` attributes (for example, classes use a :class:" -"`types.MappingProxyType` to prevent direct dictionary updates)." +"their :attr:`!__dict__` attributes (for example, classes use a :class:`types." +"MappingProxyType` to prevent direct dictionary updates)." msgstr "" "Objetos como modelos e instâncias têm um atributo atualizável :attr:`~object." "__dict__`; porém, outros projetos podem ter restrições de escrita em seus " -"atributos :attr:`~object.__dict__` (por exemplo, classes usam um :class:" -"`types.MappingProxyType` para prevenir atualizações diretas a dicionário)." +"atributos :attr:`!__dict__` (por exemplo, classes usam um :class:`types." +"MappingProxyType` para prevenir atualizações diretas a dicionário)." -#: ../../library/functions.rst:2074 +#: ../../library/functions.rst:2099 msgid "Without an argument, :func:`vars` acts like :func:`locals`." msgstr "Sem nenhum argumento, :func:`vars` age como :func:`locals`." -#: ../../library/functions.rst:2076 +#: ../../library/functions.rst:2101 msgid "" "A :exc:`TypeError` exception is raised if an object is specified but it " "doesn't have a :attr:`~object.__dict__` attribute (for example, if its class " @@ -3707,7 +4067,7 @@ msgstr "" "ela não tem um atributo :attr:`~object.__dict__` (por exemplo, se sua classe " "define o atributo :attr:`~object.__slots__`)." -#: ../../library/functions.rst:2082 +#: ../../library/functions.rst:2107 msgid "" "The result of calling this function without an argument has been updated as " "described for the :func:`locals` builtin." @@ -3715,7 +4075,7 @@ msgstr "" "O resultado de chamar esta função sem um argumento foi atualizado conforme " "descrito na embutida :func:`locals`." -#: ../../library/functions.rst:2088 +#: ../../library/functions.rst:2113 msgid "" "Iterate over several iterables in parallel, producing tuples with an item " "from each one." @@ -3723,11 +4083,28 @@ msgstr "" "Itera sobre vários iteráveis em paralelo, produzindo tuplas com um item de " "cada um." -#: ../../library/functions.rst:2091 +#: ../../library/functions.rst:2116 msgid "Example::" msgstr "Exemplo::" -#: ../../library/functions.rst:2100 +#: ../../library/functions.rst:2118 +msgid "" +">>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):\n" +"... print(item)\n" +"...\n" +"(1, 'sugar')\n" +"(2, 'spice')\n" +"(3, 'everything nice')" +msgstr "" +">>> for item in zip([1, 2, 3], ['açúcar', 'tempero', 'tudo que há de " +"bom']):\n" +"... print(item)\n" +"...\n" +"(1, 'açúcar')\n" +"(2, 'tempero')\n" +"(3, 'tudo que há de bom')" + +#: ../../library/functions.rst:2125 msgid "" "More formally: :func:`zip` returns an iterator of tuples, where the *i*-th " "tuple contains the *i*-th element from each of the argument iterables." @@ -3736,7 +4113,7 @@ msgstr "" "ésima tupla contém o *i*-ésimo elemento de cada um dos iteráveis do " "argumento." -#: ../../library/functions.rst:2103 +#: ../../library/functions.rst:2128 msgid "" "Another way to think of :func:`zip` is that it turns rows into columns, and " "columns into rows. This is similar to `transposing a matrix `_." -#: ../../library/functions.rst:2107 +#: ../../library/functions.rst:2132 msgid "" ":func:`zip` is lazy: The elements won't be processed until the iterable is " "iterated on, e.g. by a :keyword:`!for` loop or by wrapping in a :class:" @@ -3756,7 +4133,7 @@ msgstr "" "iterável seja iterado. Por exemplo, por um loop :keyword:`!for` ou por um :" "class:`list`." -#: ../../library/functions.rst:2111 +#: ../../library/functions.rst:2136 msgid "" "One thing to consider is that the iterables passed to :func:`zip` could have " "different lengths; sometimes by design, and sometimes because of a bug in " @@ -3768,7 +4145,7 @@ msgstr "" "bug no código que preparou esses iteráveis. Python oferece três abordagens " "diferentes para lidar com esse problema:" -#: ../../library/functions.rst:2116 +#: ../../library/functions.rst:2141 msgid "" "By default, :func:`zip` stops when the shortest iterable is exhausted. It " "will ignore the remaining items in the longer iterables, cutting off the " @@ -3778,7 +4155,15 @@ msgstr "" "ignorar os itens restantes nos iteráveis mais longos, cortando o resultado " "para o comprimento do iterável mais curto::" -#: ../../library/functions.rst:2123 +#: ../../library/functions.rst:2145 +msgid "" +">>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum']))\n" +"[(0, 'fee'), (1, 'fi'), (2, 'fo')]" +msgstr "" +">>> list(zip(range(3), ['fi', 'fa', 'fo', 'fum']))\n" +"[(0, 'fi'), (1, 'fa'), (2, 'fo')]" + +#: ../../library/functions.rst:2148 msgid "" ":func:`zip` is often used in cases where the iterables are assumed to be of " "equal length. In such cases, it's recommended to use the ``strict=True`` " @@ -3788,7 +4173,15 @@ msgstr "" "considerados de tamanho igual. Nesses casos, é recomendado usar a opção " "``strict=True``. Sua saída é a mesma do :func:`zip`:: normal" -#: ../../library/functions.rst:2130 +#: ../../library/functions.rst:2152 +msgid "" +">>> list(zip(('a', 'b', 'c'), (1, 2, 3), strict=True))\n" +"[('a', 1), ('b', 2), ('c', 3)]" +msgstr "" +">>> list(zip(('a', 'b', 'c'), (1, 2, 3), strict=True))\n" +"[('a', 1), ('b', 2), ('c', 3)]" + +#: ../../library/functions.rst:2155 msgid "" "Unlike the default behavior, it raises a :exc:`ValueError` if one iterable " "is exhausted before the others:" @@ -3796,7 +4189,7 @@ msgstr "" "Ao contrário do comportamento padrão, ele levanta uma exceção :exc:" "`ValueError` se um iterável for esgotado antes dos outros:" -#: ../../library/functions.rst:2148 +#: ../../library/functions.rst:2173 msgid "" "Without the ``strict=True`` argument, any bug that results in iterables of " "different lengths will be silenced, possibly manifesting as a hard-to-find " @@ -3806,7 +4199,7 @@ msgstr "" "diferentes comprimentos será silenciado, possivelmente se manifestando como " "um bug difícil de encontrar em outra parte do programa." -#: ../../library/functions.rst:2152 +#: ../../library/functions.rst:2177 msgid "" "Shorter iterables can be padded with a constant value to make all the " "iterables have the same length. This is done by :func:`itertools." @@ -3816,7 +4209,7 @@ msgstr "" "fazer com que todos os iteráveis tenham o mesmo comprimento. Isso é feito " "por :func:`itertools.zip_longest`." -#: ../../library/functions.rst:2156 +#: ../../library/functions.rst:2181 msgid "" "Edge cases: With a single iterable argument, :func:`zip` returns an iterator " "of 1-tuples. With no arguments, it returns an empty iterator." @@ -3824,11 +4217,11 @@ msgstr "" "Casos extremos: Com um único argumento iterável, :func:`zip` retorna um " "iterador de tuplas de um elemento. Sem argumentos, retorna um iterador vazio." -#: ../../library/functions.rst:2159 +#: ../../library/functions.rst:2184 msgid "Tips and tricks:" msgstr "Dicas e truques:" -#: ../../library/functions.rst:2161 +#: ../../library/functions.rst:2186 msgid "" "The left-to-right evaluation order of the iterables is guaranteed. This " "makes possible an idiom for clustering a data series into n-length groups " @@ -3843,7 +4236,7 @@ msgstr "" "de chamadas ``n`` para o iterador. Isso tem o efeito de dividir a entrada em " "pedaços de n comprimentos." -#: ../../library/functions.rst:2167 +#: ../../library/functions.rst:2192 msgid "" ":func:`zip` in conjunction with the ``*`` operator can be used to unzip a " "list::" @@ -3851,11 +4244,29 @@ msgstr "" ":func:`zip` em conjunto com o operador ``*`` pode ser usado para " "descompactar uma lista::" -#: ../../library/functions.rst:2178 +#: ../../library/functions.rst:2195 +msgid "" +">>> x = [1, 2, 3]\n" +">>> y = [4, 5, 6]\n" +">>> list(zip(x, y))\n" +"[(1, 4), (2, 5), (3, 6)]\n" +">>> x2, y2 = zip(*zip(x, y))\n" +">>> x == list(x2) and y == list(y2)\n" +"True" +msgstr "" +">>> x = [1, 2, 3]\n" +">>> y = [4, 5, 6]\n" +">>> list(zip(x, y))\n" +"[(1, 4), (2, 5), (3, 6)]\n" +">>> x2, y2 = zip(*zip(x, y))\n" +">>> x == list(x2) and y == list(y2)\n" +"True" + +#: ../../library/functions.rst:2203 msgid "Added the ``strict`` argument." msgstr "Adicionado o argumento ``strict``." -#: ../../library/functions.rst:2190 +#: ../../library/functions.rst:2215 msgid "" "This is an advanced function that is not needed in everyday Python " "programming, unlike :func:`importlib.import_module`." @@ -3863,7 +4274,7 @@ msgstr "" "Esta é uma função avançada que não é necessária na programação diária do " "Python, ao contrário de :func:`importlib.import_module`." -#: ../../library/functions.rst:2193 +#: ../../library/functions.rst:2218 msgid "" "This function is invoked by the :keyword:`import` statement. It can be " "replaced (by importing the :mod:`builtins` module and assigning to " @@ -3883,7 +4294,7 @@ msgstr "" "importação padrão esteja em uso. O uso direto de :func:`__import__` também é " "desencorajado em favor de :func:`importlib.import_module`." -#: ../../library/functions.rst:2202 +#: ../../library/functions.rst:2227 msgid "" "The function imports the module *name*, potentially using the given " "*globals* and *locals* to determine how to interpret the name in a package " @@ -3899,7 +4310,7 @@ msgstr "" "seu argumento *locals* e usa seus *globals* apenas para determinar o " "contexto do pacote da instrução :keyword:`import`." -#: ../../library/functions.rst:2209 +#: ../../library/functions.rst:2234 msgid "" "*level* specifies whether to use absolute or relative imports. ``0`` (the " "default) means only perform absolute imports. Positive values for *level* " @@ -3913,31 +4324,39 @@ msgstr "" "pesquisados em relação ao diretório do módulo que chama :func:`__import__` " "(consulte :pep:`328` para obter detalhes)." -#: ../../library/functions.rst:2215 +#: ../../library/functions.rst:2240 msgid "" "When the *name* variable is of the form ``package.module``, normally, the " "top-level package (the name up till the first dot) is returned, *not* the " "module named by *name*. However, when a non-empty *fromlist* argument is " "given, the module named by *name* is returned." msgstr "" -"Quando a variável *name* está no formato ``package.module``, normalmente, o " +"Quando a variável *name* está no formato ``pacote.módulo``, normalmente, o " "pacote de nível superior (o nome até o primeiro ponto) é retornado, *não* o " "módulo nomeado por *name*. No entanto, quando um argumento *fromlist* não " "vazio é fornecido, o módulo nomeado por *name* é retornado." -#: ../../library/functions.rst:2220 +#: ../../library/functions.rst:2245 msgid "" "For example, the statement ``import spam`` results in bytecode resembling " "the following code::" msgstr "" -"Por exemplo, a instrução ``importar spam`` resulta em bytecode semelhante ao " +"Por exemplo, a instrução ``import spam`` resulta em bytecode semelhante ao " "seguinte código::" -#: ../../library/functions.rst:2225 +#: ../../library/functions.rst:2248 +msgid "spam = __import__('spam', globals(), locals(), [], 0)" +msgstr "spam = __import__('spam', globals(), locals(), [], 0)" + +#: ../../library/functions.rst:2250 msgid "The statement ``import spam.ham`` results in this call::" -msgstr "A instrução ``import spam.ham`` resulta nesta chamada::" +msgstr "A instrução ``import spam.presunto`` resulta nesta chamada::" -#: ../../library/functions.rst:2229 +#: ../../library/functions.rst:2252 +msgid "spam = __import__('spam.ham', globals(), locals(), [], 0)" +msgstr "spam = __import__('spam.presunto', globals(), locals(), [], 0)" + +#: ../../library/functions.rst:2254 msgid "" "Note how :func:`__import__` returns the toplevel module here because this is " "the object that is bound to a name by the :keyword:`import` statement." @@ -3945,15 +4364,26 @@ msgstr "" "Observe como :func:`__import__` retorna o módulo de nível superior aqui, " "porque este é o objeto vinculado a um nome pela instrução :keyword:`import`." -#: ../../library/functions.rst:2232 +#: ../../library/functions.rst:2257 msgid "" "On the other hand, the statement ``from spam.ham import eggs, sausage as " "saus`` results in ::" msgstr "" -"Por outro lado, a instrução ``from spam.ham import eggs, sausage as saus`` " -"resulta em ::" +"Por outro lado, a instrução ``from spam.presunto import ovos, salsicha as " +"sals`` resulta em ::" + +#: ../../library/functions.rst:2260 +msgid "" +"_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)\n" +"eggs = _temp.eggs\n" +"saus = _temp.sausage" +msgstr "" +"_temp = __import__('spam.presunto', globals(), locals(), ['ovos', " +"'salsicha'], 0)\n" +"ovos = _temp.ovos\n" +"sals = _temp.salsicha" -#: ../../library/functions.rst:2239 +#: ../../library/functions.rst:2264 msgid "" "Here, the ``spam.ham`` module is returned from :func:`__import__`. From " "this object, the names to import are retrieved and assigned to their " @@ -3963,7 +4393,7 @@ msgstr "" "desse objeto, os nomes a serem importados são recuperados e atribuídos aos " "seus respectivos nomes." -#: ../../library/functions.rst:2243 +#: ../../library/functions.rst:2268 msgid "" "If you simply want to import a module (potentially within a package) by " "name, use :func:`importlib.import_module`." @@ -3971,7 +4401,7 @@ msgstr "" "Se você simplesmente deseja importar um módulo (potencialmente dentro de um " "pacote) pelo nome, use :func:`importlib.import_module`." -#: ../../library/functions.rst:2246 +#: ../../library/functions.rst:2271 msgid "" "Negative values for *level* are no longer supported (which also changes the " "default value to 0)." @@ -3979,7 +4409,7 @@ msgstr "" "Valores negativos para *level* não são mais suportados (o que também altera " "o valor padrão para 0)." -#: ../../library/functions.rst:2250 +#: ../../library/functions.rst:2275 msgid "" "When the command line options :option:`-E` or :option:`-I` are being used, " "the environment variable :envvar:`PYTHONCASEOK` is now ignored." @@ -3987,11 +4417,11 @@ msgstr "" "Quando as opções de linha de comando :option:`-E` ou :option:`-I` estão " "sendo usadas, a variável de ambiente :envvar:`PYTHONCASEOK` é agora ignorada." -#: ../../library/functions.rst:2255 +#: ../../library/functions.rst:2280 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../library/functions.rst:2256 +#: ../../library/functions.rst:2281 msgid "" "Note that the parser only accepts the Unix-style end of line convention. If " "you are reading the code from a file, make sure to use newline conversion " @@ -4005,106 +4435,106 @@ msgstr "" msgid "Boolean" msgstr "Booleano" -#: ../../library/functions.rst:154 ../../library/functions.rst:2025 +#: ../../library/functions.rst:154 ../../library/functions.rst:2048 msgid "type" msgstr "tipo" -#: ../../library/functions.rst:641 +#: ../../library/functions.rst:648 msgid "built-in function" msgstr "função embutida" -#: ../../library/functions.rst:641 +#: ../../library/functions.rst:648 msgid "exec" msgstr "exec" -#: ../../library/functions.rst:733 +#: ../../library/functions.rst:746 msgid "NaN" msgstr "NaN" -#: ../../library/functions.rst:733 +#: ../../library/functions.rst:746 msgid "Infinity" -msgstr "Infinito" +msgstr "Infinity" -#: ../../library/functions.rst:801 +#: ../../library/functions.rst:814 msgid "__format__" msgstr "__format__" -#: ../../library/functions.rst:801 ../../library/functions.rst:1902 +#: ../../library/functions.rst:814 ../../library/functions.rst:1925 msgid "string" msgstr "string" -#: ../../library/functions.rst:801 +#: ../../library/functions.rst:814 msgid "format() (built-in function)" msgstr "format() (função embutida)" -#: ../../library/functions.rst:1310 +#: ../../library/functions.rst:1325 msgid "file object" msgstr "objeto arquivo" -#: ../../library/functions.rst:1310 ../../library/functions.rst:1431 +#: ../../library/functions.rst:1325 ../../library/functions.rst:1446 msgid "open() built-in function" msgstr "função embutida open()" -#: ../../library/functions.rst:1338 +#: ../../library/functions.rst:1353 msgid "file" msgstr "arquivo" -#: ../../library/functions.rst:1338 +#: ../../library/functions.rst:1353 msgid "modes" msgstr "modos" -#: ../../library/functions.rst:1431 +#: ../../library/functions.rst:1446 msgid "universal newlines" msgstr "novas linhas universais" -#: ../../library/functions.rst:1492 +#: ../../library/functions.rst:1507 msgid "line-buffered I/O" msgstr "E/S com buffer de linha" -#: ../../library/functions.rst:1492 +#: ../../library/functions.rst:1507 msgid "unbuffered I/O" msgstr "E/S sem buffer" -#: ../../library/functions.rst:1492 +#: ../../library/functions.rst:1507 msgid "buffer size, I/O" msgstr "buffer, tamanho, E/S" -#: ../../library/functions.rst:1492 +#: ../../library/functions.rst:1507 msgid "I/O control" msgstr "controle de E/S" -#: ../../library/functions.rst:1492 +#: ../../library/functions.rst:1507 msgid "buffering" msgstr "buffering" -#: ../../library/functions.rst:1492 +#: ../../library/functions.rst:1507 msgid "text mode" msgstr "texto, modo" -#: ../../library/functions.rst:1492 ../../library/functions.rst:2184 +#: ../../library/functions.rst:1507 ../../library/functions.rst:2209 msgid "module" msgstr "módulo" -#: ../../library/functions.rst:1492 +#: ../../library/functions.rst:1507 msgid "sys" msgstr "sys" -#: ../../library/functions.rst:1902 +#: ../../library/functions.rst:1925 msgid "str() (built-in function)" msgstr "str() (função embutida)" -#: ../../library/functions.rst:2025 +#: ../../library/functions.rst:2048 msgid "object" msgstr "objeto" -#: ../../library/functions.rst:2184 +#: ../../library/functions.rst:2209 msgid "statement" msgstr "instrução" -#: ../../library/functions.rst:2184 +#: ../../library/functions.rst:2209 msgid "import" -msgstr "importação" +msgstr "import" -#: ../../library/functions.rst:2184 +#: ../../library/functions.rst:2209 msgid "builtins" msgstr "builtins" diff --git a/library/functools.po b/library/functools.po index d9f791c79..3b31d94ab 100644 --- a/library/functools.po +++ b/library/functools.po @@ -1,29 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Italo Penaforte , 2021 -# Adorilson Bezerra , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -63,18 +59,30 @@ msgstr "" msgid "" "Returns the same as ``lru_cache(maxsize=None)``, creating a thin wrapper " "around a dictionary lookup for the function arguments. Because it never " -"needs to evict old values, this is smaller and faster than :func:" -"`lru_cache()` with a size limit." +"needs to evict old values, this is smaller and faster than :func:`lru_cache` " +"with a size limit." msgstr "" -"Retorna o mesmo que ``lru_cache(maxsize=None)``, criando um invólucro fino " -"em torno de uma pesquisa de dicionário para os argumentos da função. Como " -"nunca precisa remover valores antigos, isso é menor e mais rápido do que :" -"func:`lru_cache()` com um limite de tamanho." #: ../../library/functools.rst:39 ../../library/functools.rst:291 msgid "For example::" msgstr "Por exemplo::" +#: ../../library/functools.rst:41 +msgid "" +"@cache\n" +"def factorial(n):\n" +" return n * factorial(n-1) if n else 1\n" +"\n" +">>> factorial(10) # no previously cached result, makes 11 recursive " +"calls\n" +"3628800\n" +">>> factorial(5) # just looks up cached value result\n" +"120\n" +">>> factorial(12) # makes two new recursive calls, the other 10 are " +"cached\n" +"479001600" +msgstr "" + #: ../../library/functools.rst:52 ../../library/functools.rst:158 msgid "" "The cache is threadsafe so that the wrapped function can be used in multiple " @@ -107,6 +115,18 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" +#: ../../library/functools.rst:72 +msgid "" +"class DataSet:\n" +"\n" +" def __init__(self, sequence_of_numbers):\n" +" self._data = tuple(sequence_of_numbers)\n" +"\n" +" @cached_property\n" +" def stdev(self):\n" +" return statistics.stdev(self._data)" +msgstr "" + #: ../../library/functools.rst:81 msgid "" "The mechanics of :func:`cached_property` are somewhat different from :func:" @@ -200,6 +220,11 @@ msgid "" "one argument and returns another value to be used as the sort key." msgstr "" +#: ../../library/functools.rst:144 +msgid "" +"sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order" +msgstr "" + #: ../../library/functools.rst:146 msgid "" "For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`." @@ -241,6 +266,13 @@ msgstr "" "decorador *lru_cache* seja aplicado diretamente a uma função do usuário, " "deixando *maxsize* em seu valor padrão de 128::" +#: ../../library/functools.rst:178 +msgid "" +"@lru_cache\n" +"def count_vowels(sentence):\n" +" return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')" +msgstr "" + #: ../../library/functools.rst:182 msgid "" "If *maxsize* is set to ``None``, the LRU feature is disabled and the cache " @@ -315,19 +347,12 @@ msgstr "" #: ../../library/functools.rst:220 msgid "" "An `LRU (least recently used) cache `_ works best when the " +"Cache_replacement_policies#Least_Recently_Used_(LRU)>`_ works best when the " "most recent calls are the best predictors of upcoming calls (for example, " "the most popular articles on a news server tend to change each day). The " "cache's size limit assures that the cache does not grow without bound on " "long-running processes such as web servers." msgstr "" -"Um cache `LRU (menos usado recentemente) `_ funciona melhor " -"quando as chamadas mais recentes são os melhores preditores de chamadas " -"futuras (por exemplo, os artigos mais populares em um servidor de notícias " -"tendem a mudar a cada dia). O limite de tamanho do cache garante que o cache " -"não cresça sem limites em processos de longa execução, como servidores da " -"web." #: ../../library/functools.rst:227 msgid "" @@ -342,6 +367,26 @@ msgstr "" msgid "Example of an LRU cache for static web content::" msgstr "Exemplo de um cache LRU para conteúdo web estático::" +#: ../../library/functools.rst:235 +msgid "" +"@lru_cache(maxsize=32)\n" +"def get_pep(num):\n" +" 'Retrieve text of a Python Enhancement Proposal'\n" +" resource = f'https://peps.python.org/pep-{num:04d}'\n" +" try:\n" +" with urllib.request.urlopen(resource) as s:\n" +" return s.read()\n" +" except urllib.error.HTTPError:\n" +" return 'Not Found'\n" +"\n" +">>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:\n" +"... pep = get_pep(n)\n" +"... print(n, len(pep))\n" +"\n" +">>> get_pep.cache_info()\n" +"CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)" +msgstr "" + #: ../../library/functools.rst:252 msgid "" "Example of efficiently computing `Fibonacci numbers `_ " "técnica::" +#: ../../library/functools.rst:258 +msgid "" +"@lru_cache(maxsize=None)\n" +"def fib(n):\n" +" if n < 2:\n" +" return n\n" +" return fib(n-1) + fib(n-2)\n" +"\n" +">>> [fib(n) for n in range(16)]\n" +"[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]\n" +"\n" +">>> fib.cache_info()\n" +"CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)" +msgstr "" + #: ../../library/functools.rst:272 msgid "Added the *typed* option." msgstr "Adicionada a opção *typed*." @@ -379,6 +439,25 @@ msgid "" "method." msgstr "" +#: ../../library/functools.rst:293 +msgid "" +"@total_ordering\n" +"class Student:\n" +" def _is_valid_operand(self, other):\n" +" return (hasattr(other, \"lastname\") and\n" +" hasattr(other, \"firstname\"))\n" +" def __eq__(self, other):\n" +" if not self._is_valid_operand(other):\n" +" return NotImplemented\n" +" return ((self.lastname.lower(), self.firstname.lower()) ==\n" +" (other.lastname.lower(), other.firstname.lower()))\n" +" def __lt__(self, other):\n" +" if not self._is_valid_operand(other):\n" +" return NotImplemented\n" +" return ((self.lastname.lower(), self.firstname.lower()) <\n" +" (other.lastname.lower(), other.firstname.lower()))" +msgstr "" + #: ../../library/functools.rst:311 msgid "" "While this decorator makes it easy to create well behaved totally ordered " @@ -411,6 +490,18 @@ msgid "" "extend and override *keywords*. Roughly equivalent to::" msgstr "" +#: ../../library/functools.rst:340 +msgid "" +"def partial(func, /, *args, **keywords):\n" +" def newfunc(*fargs, **fkeywords):\n" +" newkeywords = {**keywords, **fkeywords}\n" +" return func(*args, *fargs, **newkeywords)\n" +" newfunc.func = func\n" +" newfunc.args = args\n" +" newfunc.keywords = keywords\n" +" return newfunc" +msgstr "" + #: ../../library/functools.rst:349 msgid "" "The :func:`partial` is used for partial function application which " @@ -451,6 +542,27 @@ msgid "" "`partialmethod` constructor." msgstr "" +#: ../../library/functools.rst:385 +msgid "" +">>> class Cell:\n" +"... def __init__(self):\n" +"... self._alive = False\n" +"... @property\n" +"... def alive(self):\n" +"... return self._alive\n" +"... def set_state(self, state):\n" +"... self._alive = bool(state)\n" +"... set_alive = partialmethod(set_state, True)\n" +"... set_dead = partialmethod(set_state, False)\n" +"...\n" +">>> c = Cell()\n" +">>> c.alive\n" +"False\n" +">>> c.set_alive()\n" +">>> c.alive\n" +"True" +msgstr "" + #: ../../library/functools.rst:408 msgid "" "Apply *function* of two arguments cumulatively to the items of *iterable*, " @@ -468,6 +580,21 @@ msgstr "" msgid "Roughly equivalent to::" msgstr "Aproximadamente equivalente a::" +#: ../../library/functools.rst:419 +msgid "" +"initial_missing = object()\n" +"\n" +"def reduce(function, iterable, initial=initial_missing, /):\n" +" it = iter(iterable)\n" +" if initial is initial_missing:\n" +" value = next(it)\n" +" else:\n" +" value = initial\n" +" for element in it:\n" +" value = function(value, element)\n" +" return value" +msgstr "" + #: ../../library/functools.rst:431 msgid "" "See :func:`itertools.accumulate` for an iterator that yields all " @@ -487,6 +614,16 @@ msgid "" "dispatch happens on the type of the first argument::" msgstr "" +#: ../../library/functools.rst:443 +msgid "" +">>> from functools import singledispatch\n" +">>> @singledispatch\n" +"... def fun(arg, verbose=False):\n" +"... if verbose:\n" +"... print(\"Let me just say,\", end=\" \")\n" +"... print(arg)" +msgstr "" + #: ../../library/functools.rst:450 msgid "" "To add overloaded implementations to the function, use the :func:`register` " @@ -495,36 +632,147 @@ msgid "" "first argument automatically::" msgstr "" +#: ../../library/functools.rst:455 +msgid "" +">>> @fun.register\n" +"... def _(arg: int, verbose=False):\n" +"... if verbose:\n" +"... print(\"Strength in numbers, eh?\", end=\" \")\n" +"... print(arg)\n" +"...\n" +">>> @fun.register\n" +"... def _(arg: list, verbose=False):\n" +"... if verbose:\n" +"... print(\"Enumerate this:\")\n" +"... for i, elem in enumerate(arg):\n" +"... print(i, elem)" +msgstr "" + #: ../../library/functools.rst:468 msgid ":data:`types.UnionType` and :data:`typing.Union` can also be used::" msgstr "" +#: ../../library/functools.rst:470 +msgid "" +">>> @fun.register\n" +"... def _(arg: int | float, verbose=False):\n" +"... if verbose:\n" +"... print(\"Strength in numbers, eh?\", end=\" \")\n" +"... print(arg)\n" +"...\n" +">>> from typing import Union\n" +">>> @fun.register\n" +"... def _(arg: Union[list, set], verbose=False):\n" +"... if verbose:\n" +"... print(\"Enumerate this:\")\n" +"... for i, elem in enumerate(arg):\n" +"... print(i, elem)\n" +"..." +msgstr "" + #: ../../library/functools.rst:485 msgid "" "For code which doesn't use type annotations, the appropriate type argument " "can be passed explicitly to the decorator itself::" msgstr "" -#: ../../library/functools.rst:496 +#: ../../library/functools.rst:488 +msgid "" +">>> @fun.register(complex)\n" +"... def _(arg, verbose=False):\n" +"... if verbose:\n" +"... print(\"Better than complicated.\", end=\" \")\n" +"... print(arg.real, arg.imag)\n" +"..." +msgstr "" + +#: ../../library/functools.rst:495 +msgid "" +"For code that dispatches on a collections type (e.g., ``list``), but wants " +"to typehint the items of the collection (e.g., ``list[int]``), the dispatch " +"type should be passed explicitly to the decorator itself with the typehint " +"going into the function definition::" +msgstr "" + +#: ../../library/functools.rst:500 +msgid "" +">>> @fun.register(list)\n" +"... def _(arg: list[int], verbose=False):\n" +"... if verbose:\n" +"... print(\"Enumerate this:\")\n" +"... for i, elem in enumerate(arg):\n" +"... print(i, elem)" +msgstr "" + +#: ../../library/functools.rst:509 +msgid "" +"At runtime the function will dispatch on an instance of a list regardless of " +"the type contained within the list i.e. ``[1,2,3]`` will be dispatched the " +"same as ``[\"foo\", \"bar\", \"baz\"]``. The annotation provided in this " +"example is for static type checkers only and has no runtime impact." +msgstr "" + +#: ../../library/functools.rst:515 msgid "" "To enable registering :term:`lambdas` and pre-existing functions, " "the :func:`register` attribute can also be used in a functional form::" msgstr "" -#: ../../library/functools.rst:504 +#: ../../library/functools.rst:518 +msgid "" +">>> def nothing(arg, verbose=False):\n" +"... print(\"Nothing.\")\n" +"...\n" +">>> fun.register(type(None), nothing)" +msgstr "" + +#: ../../library/functools.rst:523 msgid "" "The :func:`register` attribute returns the undecorated function. This " "enables decorator stacking, :mod:`pickling`, and the creation of " "unit tests for each variant independently::" msgstr "" -#: ../../library/functools.rst:518 +#: ../../library/functools.rst:527 +msgid "" +">>> @fun.register(float)\n" +"... @fun.register(Decimal)\n" +"... def fun_num(arg, verbose=False):\n" +"... if verbose:\n" +"... print(\"Half of your number:\", end=\" \")\n" +"... print(arg / 2)\n" +"...\n" +">>> fun_num is fun\n" +"False" +msgstr "" + +#: ../../library/functools.rst:537 msgid "" "When called, the generic function dispatches on the type of the first " "argument::" msgstr "" -#: ../../library/functools.rst:538 +#: ../../library/functools.rst:540 +msgid "" +">>> fun(\"Hello, world.\")\n" +"Hello, world.\n" +">>> fun(\"test.\", verbose=True)\n" +"Let me just say, test.\n" +">>> fun(42, verbose=True)\n" +"Strength in numbers, eh? 42\n" +">>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)\n" +"Enumerate this:\n" +"0 spam\n" +"1 spam\n" +"2 eggs\n" +"3 spam\n" +">>> fun(None)\n" +"Nothing.\n" +">>> fun(1.23)\n" +"0.615" +msgstr "" + +#: ../../library/functools.rst:557 msgid "" "Where there is no registered implementation for a specific type, its method " "resolution order is used to find a more generic implementation. The original " @@ -533,42 +781,76 @@ msgid "" "found." msgstr "" -#: ../../library/functools.rst:544 +#: ../../library/functools.rst:563 msgid "" "If an implementation is registered to an :term:`abstract base class`, " "virtual subclasses of the base class will be dispatched to that " "implementation::" msgstr "" -#: ../../library/functools.rst:559 +#: ../../library/functools.rst:567 +msgid "" +">>> from collections.abc import Mapping\n" +">>> @fun.register\n" +"... def _(arg: Mapping, verbose=False):\n" +"... if verbose:\n" +"... print(\"Keys & Values\")\n" +"... for key, value in arg.items():\n" +"... print(key, \"=>\", value)\n" +"...\n" +">>> fun({\"a\": \"b\"})\n" +"a => b" +msgstr "" + +#: ../../library/functools.rst:578 msgid "" "To check which implementation the generic function will choose for a given " "type, use the ``dispatch()`` attribute::" msgstr "" -#: ../../library/functools.rst:567 +#: ../../library/functools.rst:581 +msgid "" +">>> fun.dispatch(float)\n" +"\n" +">>> fun.dispatch(dict) # note: default implementation\n" +"" +msgstr "" + +#: ../../library/functools.rst:586 msgid "" "To access all registered implementations, use the read-only ``registry`` " "attribute::" msgstr "" -#: ../../library/functools.rst:581 +#: ../../library/functools.rst:589 +msgid "" +">>> fun.registry.keys()\n" +"dict_keys([, , ,\n" +" , ,\n" +" ])\n" +">>> fun.registry[float]\n" +"\n" +">>> fun.registry[object]\n" +"" +msgstr "" + +#: ../../library/functools.rst:600 msgid "The :func:`register` attribute now supports using type annotations." msgstr "" -#: ../../library/functools.rst:584 +#: ../../library/functools.rst:603 msgid "" "The :func:`register` attribute now supports :data:`types.UnionType` and :" "data:`typing.Union` as type annotations." msgstr "" -#: ../../library/functools.rst:591 +#: ../../library/functools.rst:610 msgid "" "Transform a method into a :term:`single-dispatch ` :term:" "`generic function`." msgstr "" -#: ../../library/functools.rst:594 +#: ../../library/functools.rst:613 msgid "" "To define a generic method, decorate it with the ``@singledispatchmethod`` " "decorator. When defining a function using ``@singledispatchmethod``, note " @@ -576,7 +858,23 @@ msgid "" "argument::" msgstr "" -#: ../../library/functools.rst:612 +#: ../../library/functools.rst:618 +msgid "" +"class Negator:\n" +" @singledispatchmethod\n" +" def neg(self, arg):\n" +" raise NotImplementedError(\"Cannot negate a\")\n" +"\n" +" @neg.register\n" +" def _(self, arg: int):\n" +" return -arg\n" +"\n" +" @neg.register\n" +" def _(self, arg: bool):\n" +" return not arg" +msgstr "" + +#: ../../library/functools.rst:631 msgid "" "``@singledispatchmethod`` supports nesting with other decorators such as :" "func:`@classmethod`. Note that to allow for ``dispatcher." @@ -585,14 +883,33 @@ msgid "" "rather than an instance of the class::" msgstr "" -#: ../../library/functools.rst:634 +#: ../../library/functools.rst:637 +msgid "" +"class Negator:\n" +" @singledispatchmethod\n" +" @classmethod\n" +" def neg(cls, arg):\n" +" raise NotImplementedError(\"Cannot negate a\")\n" +"\n" +" @neg.register\n" +" @classmethod\n" +" def _(cls, arg: int):\n" +" return -arg\n" +"\n" +" @neg.register\n" +" @classmethod\n" +" def _(cls, arg: bool):\n" +" return not arg" +msgstr "" + +#: ../../library/functools.rst:653 msgid "" "The same pattern can be used for other similar decorators: :func:" "`@staticmethod`, :func:`@abstractmethod`, " "and others." msgstr "" -#: ../../library/functools.rst:643 +#: ../../library/functools.rst:662 msgid "" "Update a *wrapper* function to look like the *wrapped* function. The " "optional arguments are tuples to specify which attributes of the original " @@ -600,13 +917,15 @@ msgid "" "function and which attributes of the wrapper function are updated with the " "corresponding attributes from the original function. The default values for " "these arguments are the module level constants ``WRAPPER_ASSIGNMENTS`` " -"(which assigns to the wrapper function's ``__module__``, ``__name__``, " -"``__qualname__``, ``__annotations__``, ``__type_params__``, and ``__doc__``, " -"the documentation string) and ``WRAPPER_UPDATES`` (which updates the wrapper " -"function's ``__dict__``, i.e. the instance dictionary)." +"(which assigns to the wrapper function's :attr:`~function.__module__`, :attr:" +"`~function.__name__`, :attr:`~function.__qualname__`, :attr:`~function." +"__annotations__`, :attr:`~function.__type_params__`, and :attr:`~function." +"__doc__`, the documentation string) and ``WRAPPER_UPDATES`` (which updates " +"the wrapper function's :attr:`~function.__dict__`, i.e. the instance " +"dictionary)." msgstr "" -#: ../../library/functools.rst:654 +#: ../../library/functools.rst:674 msgid "" "To allow access to the original function for introspection and other " "purposes (e.g. bypassing a caching decorator such as :func:`lru_cache`), " @@ -614,7 +933,7 @@ msgid "" "that refers to the function being wrapped." msgstr "" -#: ../../library/functools.rst:659 +#: ../../library/functools.rst:679 msgid "" "The main intended use for this function is in :term:`decorator` functions " "which wrap the decorated function and return the wrapper. If the wrapper " @@ -623,7 +942,7 @@ msgid "" "is typically less than helpful." msgstr "" -#: ../../library/functools.rst:665 +#: ../../library/functools.rst:685 msgid "" ":func:`update_wrapper` may be used with callables other than functions. Any " "attributes named in *assigned* or *updated* that are missing from the object " @@ -632,25 +951,26 @@ msgid "" "wrapper function itself is missing any attributes named in *updated*." msgstr "" -#: ../../library/functools.rst:671 +#: ../../library/functools.rst:691 msgid "" -"The ``__wrapped__`` attribute is now automatically added. The " -"``__annotations__`` attribute is now copied by default. Missing attributes " -"no longer trigger an :exc:`AttributeError`." +"The ``__wrapped__`` attribute is now automatically added. The :attr:" +"`~function.__annotations__` attribute is now copied by default. Missing " +"attributes no longer trigger an :exc:`AttributeError`." msgstr "" -#: ../../library/functools.rst:676 +#: ../../library/functools.rst:696 msgid "" "The ``__wrapped__`` attribute now always refers to the wrapped function, " "even if that function defined a ``__wrapped__`` attribute. (see :issue:" "`17482`)" msgstr "" -#: ../../library/functools.rst:681 -msgid "The ``__type_params__`` attribute is now copied by default." +#: ../../library/functools.rst:701 +msgid "" +"The :attr:`~function.__type_params__` attribute is now copied by default." msgstr "" -#: ../../library/functools.rst:687 +#: ../../library/functools.rst:707 msgid "" "This is a convenience function for invoking :func:`update_wrapper` as a " "function decorator when defining a wrapper function. It is equivalent to " @@ -658,47 +978,72 @@ msgid "" "updated=updated)``. For example::" msgstr "" -#: ../../library/functools.rst:713 +#: ../../library/functools.rst:712 +msgid "" +">>> from functools import wraps\n" +">>> def my_decorator(f):\n" +"... @wraps(f)\n" +"... def wrapper(*args, **kwds):\n" +"... print('Calling decorated function')\n" +"... return f(*args, **kwds)\n" +"... return wrapper\n" +"...\n" +">>> @my_decorator\n" +"... def example():\n" +"... \"\"\"Docstring\"\"\"\n" +"... print('Called example function')\n" +"...\n" +">>> example()\n" +"Calling decorated function\n" +"Called example function\n" +">>> example.__name__\n" +"'example'\n" +">>> example.__doc__\n" +"'Docstring'" +msgstr "" + +#: ../../library/functools.rst:733 msgid "" "Without the use of this decorator factory, the name of the example function " "would have been ``'wrapper'``, and the docstring of the original :func:" "`example` would have been lost." msgstr "" -#: ../../library/functools.rst:721 +#: ../../library/functools.rst:741 msgid ":class:`partial` Objects" msgstr "Objetos :class:`partial`" -#: ../../library/functools.rst:723 +#: ../../library/functools.rst:743 msgid "" ":class:`partial` objects are callable objects created by :func:`partial`. " "They have three read-only attributes:" msgstr "" -#: ../../library/functools.rst:729 +#: ../../library/functools.rst:749 msgid "" "A callable object or function. Calls to the :class:`partial` object will be " "forwarded to :attr:`func` with new arguments and keywords." msgstr "" -#: ../../library/functools.rst:735 +#: ../../library/functools.rst:755 msgid "" "The leftmost positional arguments that will be prepended to the positional " "arguments provided to a :class:`partial` object call." msgstr "" -#: ../../library/functools.rst:741 +#: ../../library/functools.rst:761 msgid "" "The keyword arguments that will be supplied when the :class:`partial` object " "is called." msgstr "" -#: ../../library/functools.rst:744 +#: ../../library/functools.rst:764 msgid "" -":class:`partial` objects are like :class:`function` objects in that they are " -"callable, weak referenceable, and can have attributes. There are some " -"important differences. For instance, the :attr:`~definition.__name__` and :" -"attr:`__doc__` attributes are not created automatically. Also, :class:" -"`partial` objects defined in classes behave like static methods and do not " -"transform into bound methods during instance attribute look-up." +":class:`partial` objects are like :ref:`function objects ` in that they are callable, weak referenceable, and can have " +"attributes. There are some important differences. For instance, the :attr:" +"`~function.__name__` and :attr:`function.__doc__` attributes are not created " +"automatically. Also, :class:`partial` objects defined in classes behave " +"like static methods and do not transform into bound methods during instance " +"attribute look-up." msgstr "" diff --git a/library/gc.po b/library/gc.po index 3495210a7..a2913d40d 100644 --- a/library/gc.po +++ b/library/gc.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -72,13 +72,13 @@ msgstr "Retorna ``True`` se a coleta automática estiver habilitada." msgid "" "With no arguments, run a full collection. The optional argument " "*generation* may be an integer specifying which generation to collect (from " -"0 to 2). A :exc:`ValueError` is raised if the generation number is " -"invalid. The sum of collected objects and uncollectable objects is returned." +"0 to 2). A :exc:`ValueError` is raised if the generation number is invalid. " +"The sum of collected objects and uncollectable objects is returned." msgstr "" "Sem argumentos, execute uma coleta completa. O argumento opcional " "*generation* pode ser um inteiro especificando qual geração coletar (de 0 a " "2). Uma exceção :exc:`ValueError` é levantada se o número de geração for " -"inválido. A soma dos objetos coletados e dos objetos incoletáveis ​​é " +"inválido. A soma dos objetos coletados e dos objetos incoletáveis é " "retornada." #: ../../library/gc.rst:48 @@ -316,6 +316,34 @@ msgstr "" "de lixo de instâncias simples (por exemplo, dicts contendo apenas chaves e " "valores atômicos)::" +#: ../../library/gc.rst:173 +msgid "" +">>> gc.is_tracked(0)\n" +"False\n" +">>> gc.is_tracked(\"a\")\n" +"False\n" +">>> gc.is_tracked([])\n" +"True\n" +">>> gc.is_tracked({})\n" +"False\n" +">>> gc.is_tracked({\"a\": 1})\n" +"False\n" +">>> gc.is_tracked({\"a\": []})\n" +"True" +msgstr "" +">>> gc.is_tracked(0)\n" +"False\n" +">>> gc.is_tracked(\"a\")\n" +"False\n" +">>> gc.is_tracked([])\n" +"True\n" +">>> gc.is_tracked({})\n" +"False\n" +">>> gc.is_tracked({\"a\": 1})\n" +"False\n" +">>> gc.is_tracked({\"a\": []})\n" +"True" + #: ../../library/gc.rst:191 msgid "" "Returns ``True`` if the given object has been finalized by the garbage " @@ -324,6 +352,34 @@ msgstr "" "Retorna ``True`` se o objeto fornecido foi finalizado pelo coletor de lixo, " "``False`` caso contrário. ::" +#: ../../library/gc.rst:194 +msgid "" +">>> x = None\n" +">>> class Lazarus:\n" +"... def __del__(self):\n" +"... global x\n" +"... x = self\n" +"...\n" +">>> lazarus = Lazarus()\n" +">>> gc.is_finalized(lazarus)\n" +"False\n" +">>> del lazarus\n" +">>> gc.is_finalized(x)\n" +"True" +msgstr "" +">>> x = None\n" +">>> class Lazarus:\n" +"... def __del__(self):\n" +"... global x\n" +"... x = self\n" +"...\n" +">>> lazarus = Lazarus()\n" +">>> gc.is_finalized(lazarus)\n" +"False\n" +">>> del lazarus\n" +">>> gc.is_finalized(x)\n" +"True" + #: ../../library/gc.rst:212 msgid "" "Freeze all the objects tracked by the garbage collector; move them to a " diff --git a/library/getopt.po b/library/getopt.po index 383134a27..77fb82d28 100644 --- a/library/getopt.po +++ b/library/getopt.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -34,29 +33,21 @@ msgstr "" msgid "**Source code:** :source:`Lib/getopt.py`" msgstr "**Código-fonte:** :source:`Lib/getopt.py`" -#: ../../library/getopt.rst:10 -msgid "" -"The :mod:`getopt` module is :term:`soft deprecated` and will not be " -"developed further; development will continue with the :mod:`argparse` module." -msgstr "" -"O módulo :mod:`getopt` está :term:`suavemente descontinuado` e não será mais " -"desenvolvido; o desenvolvimento continuará com o módulo :mod:`argparse`." - -#: ../../library/getopt.rst:17 +#: ../../library/getopt.rst:12 msgid "" -"The :mod:`getopt` module is a parser for command line options whose API is " -"designed to be familiar to users of the C :c:func:`!getopt` function. Users " -"who are unfamiliar with the C :c:func:`!getopt` function or who would like " -"to write less code and get better help and error messages should consider " -"using the :mod:`argparse` module instead." +"This module is considered feature complete. A more declarative and " +"extensible alternative to this API is provided in the :mod:`optparse` " +"module. Further functional enhancements for command line parameter " +"processing are provided either as third party modules on PyPI, or else as " +"features in the :mod:`argparse` module." msgstr "" -"O módulo :mod:`getopt` é um analisador sintático para opções de linha de " -"comando cuja API é projetada para ser familiar aos usuários da função C :c:" -"func:`!getopt`. Os usuários que não estão familiarizados com a função C :c:" -"func:`!getopt` ou que gostariam de escrever menos código e obter mensagens " -"de ajuda e de erro melhores devem considerar o uso do módulo :mod:`argparse`." +"Este módulo é considerado completo em recursos. Uma alternativa mais " +"declarativa e extensível para esta API é fornecida no módulo :mod:" +"`optparse`. Outros aprimoramentos funcionais para processamento de " +"parâmetros de linha de comando são fornecidos como módulos de terceiros no " +"PyPI ou como recursos no módulo :mod:`argparse`." -#: ../../library/getopt.rst:25 +#: ../../library/getopt.rst:20 msgid "" "This module helps scripts to parse the command line arguments in ``sys." "argv``. It supports the same conventions as the Unix :c:func:`!getopt` " @@ -70,11 +61,27 @@ msgstr "" "e '``--``'). Longas opções semelhantes às suportadas pelo software GNU " "também podem ser usadas por meio de um terceiro argumento opcional." -#: ../../library/getopt.rst:31 +#: ../../library/getopt.rst:26 +msgid "" +"Users who are unfamiliar with the Unix :c:func:`!getopt` function should " +"consider using the :mod:`argparse` module instead. Users who are familiar " +"with the Unix :c:func:`!getopt` function, but would like to get equivalent " +"behavior while writing less code and getting better help and error messages " +"should consider using the :mod:`optparse` module. See :ref:`choosing-an-" +"argument-parser` for additional details." +msgstr "" +"Usuários que não estão familiarizados com a função Unix :c:func:`!getopt` " +"devem considerar usar o módulo :mod:`argparse` em vez disso. Usuários que " +"estão familiarizados com a função Unix :c:func:`!getopt`, mas gostariam de " +"obter um comportamento equivalente enquanto escrevem menos código e obtêm " +"melhor ajuda e mensagens de erro devem considerar usar o módulo :mod:" +"`optparse`. Veja :ref:`choosing-an-argument-parser` para detalhes adicionais." + +#: ../../library/getopt.rst:33 msgid "This module provides two functions and an exception:" msgstr "Este módulo fornece duas funções e uma exceção:" -#: ../../library/getopt.rst:37 +#: ../../library/getopt.rst:39 msgid "" "Parses command line options and parameter list. *args* is the argument list " "to be parsed, without the leading reference to the running program. " @@ -90,7 +97,7 @@ msgstr "" "requerem um argumento seguido por dois pontos (``':'``; ou seja, o mesmo " "formato que Unix :c:func:`!getopt` usa)." -#: ../../library/getopt.rst:45 +#: ../../library/getopt.rst:47 msgid "" "Unlike GNU :c:func:`!getopt`, after a non-option argument, all further " "arguments are considered also non-options. This is similar to the way non-" @@ -100,7 +107,7 @@ msgstr "" "argumentos adicionais são considerados também sem opção. Isso é semelhante à " "maneira como os sistemas Unix não GNU funcionam." -#: ../../library/getopt.rst:49 +#: ../../library/getopt.rst:51 msgid "" "*longopts*, if specified, must be a list of strings with the names of the " "long options which should be supported. The leading ``'--'`` characters " @@ -125,7 +132,7 @@ msgstr "" "f`` não corresponderá exclusivamente, então :exc:`GetoptError` será " "levantada." -#: ../../library/getopt.rst:60 +#: ../../library/getopt.rst:62 msgid "" "The return value consists of two elements: the first is a list of ``(option, " "value)`` pairs; the second is the list of program arguments left after the " @@ -148,7 +155,7 @@ msgstr "" "ordem em que foram encontradas, permitindo assim múltiplas ocorrências. " "Opções longas e curtas podem ser misturadas." -#: ../../library/getopt.rst:73 +#: ../../library/getopt.rst:75 msgid "" "This function works like :func:`getopt`, except that GNU style scanning mode " "is used by default. This means that option and non-option arguments may be " @@ -160,7 +167,7 @@ msgstr "" "e não opção podem ser misturados. A função :func:`getopt` interrompe o " "processamento das opções assim que um argumento não opcional é encontrado." -#: ../../library/getopt.rst:78 +#: ../../library/getopt.rst:80 msgid "" "If the first character of the option string is ``'+'``, or if the " "environment variable :envvar:`!POSIXLY_CORRECT` is set, then option " @@ -170,7 +177,7 @@ msgstr "" "ambiente :envvar:`!POSIXLY_CORRECT` estiver definida, então o processamento " "da opção para assim que um argumento não opcional for encontrado." -#: ../../library/getopt.rst:85 +#: ../../library/getopt.rst:87 msgid "" "This is raised when an unrecognized option is found in the argument list or " "when an option requiring an argument is given none. The argument to the " @@ -189,38 +196,216 @@ msgstr "" "opção específica à qual a exceção se relaciona, :attr:`!opt` é uma string " "vazia." -#: ../../library/getopt.rst:96 +#: ../../library/getopt.rst:98 msgid "Alias for :exc:`GetoptError`; for backward compatibility." msgstr "Apelido para :exc:`GetoptError`; para compatibilidade reversa." -#: ../../library/getopt.rst:98 +#: ../../library/getopt.rst:100 msgid "An example using only Unix style options:" msgstr "Um exemplo usando apenas opções de estilo Unix:" -#: ../../library/getopt.rst:110 +#: ../../library/getopt.rst:102 +msgid "" +">>> import getopt\n" +">>> args = '-a -b -cfoo -d bar a1 a2'.split()\n" +">>> args\n" +"['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']\n" +">>> optlist, args = getopt.getopt(args, 'abc:d:')\n" +">>> optlist\n" +"[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]\n" +">>> args\n" +"['a1', 'a2']" +msgstr "" +">>> import getopt\n" +">>> args = '-a -b -cfoo -d bar a1 a2'.split()\n" +">>> args\n" +"['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']\n" +">>> optlist, args = getopt.getopt(args, 'abc:d:')\n" +">>> optlist\n" +"[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]\n" +">>> args\n" +"['a1', 'a2']" + +#: ../../library/getopt.rst:114 msgid "Using long option names is equally easy:" msgstr "Usar nomes de opções longos é igualmente fácil:" -#: ../../library/getopt.rst:123 -msgid "In a script, typical usage is something like this::" -msgstr "Em um script, o uso típico é algo assim::" +#: ../../library/getopt.rst:116 +msgid "" +">>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'\n" +">>> args = s.split()\n" +">>> args\n" +"['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', " +"'a2']\n" +">>> optlist, args = getopt.getopt(args, 'x', [\n" +"... 'condition=', 'output-file=', 'testing'])\n" +">>> optlist\n" +"[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-" +"x', '')]\n" +">>> args\n" +"['a1', 'a2']" +msgstr "" +">>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'\n" +">>> args = s.split()\n" +">>> args\n" +"['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', " +"'a2']\n" +">>> optlist, args = getopt.getopt(args, 'x', [\n" +"... 'condition=', 'output-file=', 'testing'])\n" +">>> optlist\n" +"[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-" +"x', '')]\n" +">>> args\n" +"['a1', 'a2']" -#: ../../library/getopt.rst:152 +#: ../../library/getopt.rst:129 +msgid "In a script, typical usage is something like this:" +msgstr "Em um script, o uso típico é algo assim:" + +#: ../../library/getopt.rst:131 +msgid "" +"import getopt, sys\n" +"\n" +"def main():\n" +" try:\n" +" opts, args = getopt.getopt(sys.argv[1:], \"ho:v\", [\"help\", " +"\"output=\"])\n" +" except getopt.GetoptError as err:\n" +" # print help information and exit:\n" +" print(err) # will print something like \"option -a not " +"recognized\"\n" +" usage()\n" +" sys.exit(2)\n" +" output = None\n" +" verbose = False\n" +" for o, a in opts:\n" +" if o == \"-v\":\n" +" verbose = True\n" +" elif o in (\"-h\", \"--help\"):\n" +" usage()\n" +" sys.exit()\n" +" elif o in (\"-o\", \"--output\"):\n" +" output = a\n" +" else:\n" +" assert False, \"unhandled option\"\n" +" process(args, output=output, verbose=verbose)\n" +"\n" +"if __name__ == \"__main__\":\n" +" main()" +msgstr "" +"import getopt, sys\n" +"\n" +"def main():\n" +" try:\n" +" opts, args = getopt.getopt(sys.argv[1:], \"ho:v\", [\"help\", " +"\"output=\"])\n" +" except getopt.GetoptError as err:\n" +" # print help information and exit:\n" +" print(err) # will print something like \"option -a not " +"recognized\"\n" +" usage()\n" +" sys.exit(2)\n" +" output = None\n" +" verbose = False\n" +" for o, a in opts:\n" +" if o == \"-v\":\n" +" verbose = True\n" +" elif o in (\"-h\", \"--help\"):\n" +" usage()\n" +" sys.exit()\n" +" elif o in (\"-o\", \"--output\"):\n" +" output = a\n" +" else:\n" +" assert False, \"unhandled option\"\n" +" process(args, output=output, verbose=verbose)\n" +"\n" +"if __name__ == \"__main__\":\n" +" main()" + +#: ../../library/getopt.rst:160 msgid "" "Note that an equivalent command line interface could be produced with less " "code and more informative help and error messages by using the :mod:" -"`argparse` module::" +"`optparse` module:" msgstr "" "Observe que uma interface de linha de comando equivalente pode ser produzida " "com menos código e mais mensagens de erro de ajuda e erro informativas " -"usando o módulo :mod:`argparse`::" +"usando o módulo :mod:`optparse`:" + +#: ../../library/getopt.rst:163 +msgid "" +"import optparse\n" +"\n" +"if __name__ == '__main__':\n" +" parser = optparse.OptionParser()\n" +" parser.add_option('-o', '--output')\n" +" parser.add_option('-v', dest='verbose', action='store_true')\n" +" opts, args = parser.parse_args()\n" +" process(args, output=opts.output, verbose=opts.verbose)" +msgstr "" +"import optparse\n" +"\n" +"if __name__ == '__main__':\n" +" parser = optparse.OptionParser()\n" +" parser.add_option('-o', '--output')\n" +" parser.add_option('-v', dest='verbose', action='store_true')\n" +" opts, args = parser.parse_args()\n" +" process(args, output=opts.output, verbose=opts.verbose)" + +#: ../../library/getopt.rst:174 +msgid "" +"A roughly equivalent command line interface for this case can also be " +"produced by using the :mod:`argparse` module:" +msgstr "" +"Uma interface de linha de comando aproximadamente equivalente para este caso " +"também pode ser produzida usando o módulo :mod:`argparse`:" + +#: ../../library/getopt.rst:177 +msgid "" +"import argparse\n" +"\n" +"if __name__ == '__main__':\n" +" parser = argparse.ArgumentParser()\n" +" parser.add_argument('-o', '--output')\n" +" parser.add_argument('-v', dest='verbose', action='store_true')\n" +" parser.add_argument('rest', nargs='*')\n" +" args = parser.parse_args()\n" +" process(args.rest, output=args.output, verbose=args.verbose)" +msgstr "" +"import argparse\n" +"\n" +"if __name__ == '__main__':\n" +" parser = argparse.ArgumentParser()\n" +" parser.add_argument('-o', '--output')\n" +" parser.add_argument('-v', dest='verbose', action='store_true')\n" +" parser.add_argument('rest', nargs='*')\n" +" args = parser.parse_args()\n" +" process(args.rest, output=args.output, verbose=args.verbose)" + +#: ../../library/getopt.rst:189 +msgid "" +"See :ref:`choosing-an-argument-parser` for details on how the ``argparse`` " +"version of this code differs in behaviour from the ``optparse`` (and " +"``getopt``) version." +msgstr "" +"Veja :ref:`choosing-an-argument-parser` para detalhes sobre como a versão " +"``argparse`` deste código difere em comportamento da versão ``optparse`` (e " +"``getopt``)." + +#: ../../library/getopt.rst:195 +msgid "Module :mod:`optparse`" +msgstr "Módulo :mod:`optparse`" + +#: ../../library/getopt.rst:196 +msgid "Declarative command line option parsing." +msgstr "Análise de opções de linha de comando declarativa." -#: ../../library/getopt.rst:167 +#: ../../library/getopt.rst:198 msgid "Module :mod:`argparse`" msgstr "Módulo :mod:`argparse`" -#: ../../library/getopt.rst:168 -msgid "Alternative command line option and argument parsing library." +#: ../../library/getopt.rst:199 +msgid "More opinionated command line option and argument parsing library." msgstr "" -"Alternativa de opção de linha de comando e biblioteca de análise de " -"argumento." +"Opção de linha de comando e biblioteca de análise de argumentos mais " +"opinativa." diff --git a/library/getpass.po b/library/getpass.po index 9c00902a5..98833996f 100644 --- a/library/getpass.po +++ b/library/getpass.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -32,8 +32,8 @@ msgid "**Source code:** :source:`Lib/getpass.py`" msgstr "**Código-fonte:** :source:`Lib/getpass.py`" #: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +msgid "Availability" +msgstr "Disponibilidade" #: ../../includes/wasm-notavail.rst:5 msgid "" @@ -107,10 +107,8 @@ msgstr "" "exceção :exc:`OSError` é levantada." #: ../../library/getpass.rst:52 -msgid "" -"In general, this function should be preferred over :func:`os.getlogin()`." -msgstr "" -"Em geral, esta função deve ter preferência sobre :func:`os.getlogin()`." +msgid "In general, this function should be preferred over :func:`os.getlogin`." +msgstr "Em geral, esta função deve ter preferência sobre :func:`os.getlogin`." #: ../../library/getpass.rst:54 msgid "Previously, various exceptions beyond just :exc:`OSError` were raised." diff --git a/library/gettext.po b/library/gettext.po index 68b9a662a..f821e776e 100644 --- a/library/gettext.po +++ b/library/gettext.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Victor Matheus Castro , 2021 -# Vinicius Gubiani Ferreira , 2023 -# Rafael Fontenelle , 2023 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -191,6 +188,23 @@ msgstr "" msgid "Here's an example of typical usage for this API::" msgstr "Aqui está um exemplo de uso típico para esta API::" +#: ../../library/gettext.rst:106 +msgid "" +"import gettext\n" +"gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')\n" +"gettext.textdomain('myapplication')\n" +"_ = gettext.gettext\n" +"# ...\n" +"print(_('This is a translatable string.'))" +msgstr "" +"import gettext\n" +"gettext.bindtextdomain('minhaaplicacao', '/caminho/para/diretório/do/meu/" +"idioma')\n" +"gettext.textdomain('minhaaplicacao')\n" +"_ = gettext.gettext\n" +"# ...\n" +"print(_('Esta é uma string traduzível.'))" + #: ../../library/gettext.rst:115 msgid "Class-based API" msgstr "API baseada em classe" @@ -309,7 +323,7 @@ msgstr "" #: ../../library/gettext.rst:169 msgid ":exc:`IOError` used to be raised, it is now an alias of :exc:`OSError`." msgstr "" -":exc:`IOError` costumava ser levantado, agora ele é um codinome para :exc:" +":exc:`IOError` costumava ser levantada, agora ela é um apelido para :exc:" "`OSError`." #: ../../library/gettext.rst:172 @@ -344,6 +358,10 @@ msgstr "" "em sua aplicação, envolvendo-as em uma chamada para a função :func:`!_`, " "assim::" +#: ../../library/gettext.rst:187 +msgid "print(_('This string will be translated.'))" +msgstr "print(_('Esta string será traduzida.'))" + #: ../../library/gettext.rst:189 msgid "" "For convenience, you want the :func:`!_` function to be installed in " @@ -467,8 +485,8 @@ msgid "" "This method installs :meth:`.gettext` into the built-in namespace, binding " "it to ``_``." msgstr "" -"Este método instala :meth:`.gettext` no espaço de nomes embutido, vinculando-" -"o a ``_``." +"Este método instala :meth:`.gettext` no espaço de nomes embutido, ligando-o " +"a ``_``." #: ../../library/gettext.rst:274 msgid "" @@ -496,6 +514,16 @@ msgstr "" "os módulos localizados nunca devem instalar :func:`!_`. Em vez disso, eles " "devem usar este código para disponibilizar :func:`!_` para seu módulo::" +#: ../../library/gettext.rst:285 +msgid "" +"import gettext\n" +"t = gettext.translation('mymodule', ...)\n" +"_ = t.gettext" +msgstr "" +"import gettext\n" +"t = gettext.translation('meumódulo', ...)\n" +"_ = t.gettext" + #: ../../library/gettext.rst:289 msgid "" "This puts :func:`!_` only in the module's global namespace and so only " @@ -623,6 +651,22 @@ msgstr "" msgid "Here is an example::" msgstr "Aqui está um exemplo::" +#: ../../library/gettext.rst:350 +msgid "" +"n = len(os.listdir('.'))\n" +"cat = GNUTranslations(somefile)\n" +"message = cat.ngettext(\n" +" 'There is %(num)d file in this directory',\n" +" 'There are %(num)d files in this directory',\n" +" n) % {'num': n}" +msgstr "" +"n = len(os.listdir('.'))\n" +"cat = GNUTranslations(somefile)\n" +"message = cat.ngettext(\n" +" 'There is %(num)d file in this directory',\n" +" 'There are %(num)d files in this directory',\n" +" n) % {'num': n}" + #: ../../library/gettext.rst:360 msgid "" "Look up the *context* and *message* id in the catalog and return the " @@ -685,6 +729,18 @@ msgstr "" "O GNOME usa uma versão do módulo :mod:`gettext` de James Henstridge, mas " "esta versão tem uma API um pouco diferente. Seu uso documentado foi::" +#: ../../library/gettext.rst:399 +msgid "" +"import gettext\n" +"cat = gettext.Catalog(domain, localedir)\n" +"_ = cat.gettext\n" +"print(_('hello world'))" +msgstr "" +"import gettext\n" +"cat = gettext.Catalog(domain, localedir)\n" +"_ = cat.gettext\n" +"print(_('hello world'))" + #: ../../library/gettext.rst:404 msgid "" "For compatibility with this older module, the function :func:`!Catalog` is " @@ -758,15 +814,27 @@ msgstr "" "envolvendo-a em ``_('...')`` --- isto é, uma chamada para a função :func:`_ " "`. Por exemplo::" +#: ../../library/gettext.rst:434 +msgid "" +"filename = 'mylog.txt'\n" +"message = _('writing a log message')\n" +"with open(filename, 'w') as fp:\n" +" fp.write(message)" +msgstr "" +"filename = 'meulog.txt'\n" +"message = _('escrevendo uma mensagem de log')\n" +"with open(filename, 'w') as fp:\n" +" fp.write(message)" + #: ../../library/gettext.rst:439 msgid "" "In this example, the string ``'writing a log message'`` is marked as a " "candidate for translation, while the strings ``'mylog.txt'`` and ``'w'`` are " "not." msgstr "" -"Neste exemplo, a string ``'writing a log message'`` está marcada como um " -"candidato para tradução, enquanto as strings ``'mylog.txt'`` e ``'w'`` não " -"estão." +"Neste exemplo, a string ``'escrevendo uma mensagem de log'`` está marcada " +"como um candidato para tradução, enquanto as strings ``'meulog.txt'`` e " +"``'w'`` não estão." #: ../../library/gettext.rst:442 msgid "" @@ -880,6 +948,16 @@ msgstr "" "formato GNU :program:`gettext`. Aqui está o que você colocaria sobre o seu " "módulo::" +#: ../../library/gettext.rst:496 +msgid "" +"import gettext\n" +"t = gettext.translation('spam', '/usr/share/locale')\n" +"_ = t.gettext" +msgstr "" +"import gettext\n" +"t = gettext.translation('spam', '/usr/share/locale')\n" +"_ = t.gettext" + #: ../../library/gettext.rst:502 msgid "Localizing your application" msgstr "Localizando sua aplicação" @@ -905,6 +983,14 @@ msgstr "" "No caso simples, você precisa adicionar apenas o seguinte código ao arquivo " "do driver principal da sua aplicação::" +#: ../../library/gettext.rst:512 +msgid "" +"import gettext\n" +"gettext.install('myapplication')" +msgstr "" +"import gettext\n" +"gettext.install('minhaaplicacao')" + #: ../../library/gettext.rst:515 msgid "" "If you need to set the locale directory, you can pass it into the :func:" @@ -913,6 +999,14 @@ msgstr "" "Se você precisar definir o diretório da localidade, poderá passá-lo para a " "função :func:`install`::" +#: ../../library/gettext.rst:518 +msgid "" +"import gettext\n" +"gettext.install('myapplication', '/usr/share/locale')" +msgstr "" +"import gettext\n" +"gettext.install('minhaaplicacao', '/usr/share/locale')" + #: ../../library/gettext.rst:523 msgid "Changing languages on the fly" msgstr "Alterando os idiomas durante o uso" @@ -927,6 +1021,38 @@ msgstr "" "convém criar várias instâncias de tradução e alternar entre elas " "explicitamente, assim::" +#: ../../library/gettext.rst:529 +msgid "" +"import gettext\n" +"\n" +"lang1 = gettext.translation('myapplication', languages=['en'])\n" +"lang2 = gettext.translation('myapplication', languages=['fr'])\n" +"lang3 = gettext.translation('myapplication', languages=['de'])\n" +"\n" +"# start by using language1\n" +"lang1.install()\n" +"\n" +"# ... time goes by, user selects language 2\n" +"lang2.install()\n" +"\n" +"# ... more time goes by, user selects language 3\n" +"lang3.install()" +msgstr "" +"import gettext\n" +"\n" +"lang1 = gettext.translation('minhaaplicacao', languages=['en'])\n" +"lang2 = gettext.translation('minhaaplicacao', languages=['fr'])\n" +"lang3 = gettext.translation('minhaaplicacao', languages=['de'])\n" +"\n" +"# começa usando o idioma 1\n" +"lang1.install()\n" +"\n" +"# ... o tempo passa, o usuário seleciona o idioma 2\n" +"lang2.install()\n" +"\n" +"# ... mais tempo passa, o usuário seleciona o idioma 3\n" +"lang3.install()" + #: ../../library/gettext.rst:546 msgid "Deferred translations" msgstr "Traduções adiadas" @@ -941,6 +1067,26 @@ msgstr "" "codificadas. Ocasionalmente, no entanto, é necessário marcar strings para " "tradução, mas adiar a tradução real até mais tarde. Um exemplo clássico é::" +#: ../../library/gettext.rst:552 +msgid "" +"animals = ['mollusk',\n" +" 'albatross',\n" +" 'rat',\n" +" 'penguin',\n" +" 'python', ]\n" +"# ...\n" +"for a in animals:\n" +" print(a)" +msgstr "" +"animals = ['mollusk',\n" +" 'albatross',\n" +" 'rat',\n" +" 'penguin',\n" +" 'python', ]\n" +"# ...\n" +"for a in animals:\n" +" print(a)" + #: ../../library/gettext.rst:561 msgid "" "Here, you want to mark the strings in the ``animals`` list as being " @@ -954,6 +1100,36 @@ msgstr "" msgid "Here is one way you can handle this situation::" msgstr "Aqui está uma maneira de lidar com esta situação::" +#: ../../library/gettext.rst:567 +msgid "" +"def _(message): return message\n" +"\n" +"animals = [_('mollusk'),\n" +" _('albatross'),\n" +" _('rat'),\n" +" _('penguin'),\n" +" _('python'), ]\n" +"\n" +"del _\n" +"\n" +"# ...\n" +"for a in animals:\n" +" print(_(a))" +msgstr "" +"def _(message): return message\n" +"\n" +"animals = [_('mollusk'),\n" +" _('albatross'),\n" +" _('rat'),\n" +" _('penguin'),\n" +" _('python'), ]\n" +"\n" +"del _\n" +"\n" +"# ...\n" +"for a in animals:\n" +" print(_(a))" + #: ../../library/gettext.rst:581 msgid "" "This works because the dummy definition of :func:`!_` simply returns the " @@ -982,6 +1158,32 @@ msgstr "" msgid "Another way to handle this is with the following example::" msgstr "Outra maneira de lidar com isso é com o seguinte exemplo::" +#: ../../library/gettext.rst:593 +msgid "" +"def N_(message): return message\n" +"\n" +"animals = [N_('mollusk'),\n" +" N_('albatross'),\n" +" N_('rat'),\n" +" N_('penguin'),\n" +" N_('python'), ]\n" +"\n" +"# ...\n" +"for a in animals:\n" +" print(_(a))" +msgstr "" +"def N_(message): return message\n" +"\n" +"animals = [N_('mollusk'),\n" +" N_('albatross'),\n" +" N_('rat'),\n" +" N_('penguin'),\n" +" N_('python'), ]\n" +"\n" +"# ...\n" +"for a in animals:\n" +" print(_(a))" + #: ../../library/gettext.rst:605 msgid "" "In this case, you are marking translatable strings with the function :func:`!" @@ -1075,7 +1277,7 @@ msgstr "Consulte a nota de rodapé para a :func:`bindtextdomain` acima." #: ../../library/gettext.rst:56 msgid "_ (underscore)" -msgstr "_ (underscore)" +msgstr "_ (sublinhado)" #: ../../library/gettext.rst:56 msgid "gettext" diff --git a/library/glob.po b/library/glob.po index 88bd4e855..d50a12f15 100644 --- a/library/glob.po +++ b/library/glob.po @@ -1,29 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Sheila Gomes , 2021 -# Adorilson Bezerra , 2023 -# Raphael Mendonça, 2024 -# Claudio Rogerio Carvalho Filho , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -278,6 +274,32 @@ msgstr "" "arquivo :file:`3.txt`. :func:`glob` produzirá os seguintes resultados. " "Observe como todos os componentes principais do caminho são preservados. ::" +#: ../../library/glob.rst:173 +msgid "" +">>> import glob\n" +">>> glob.glob('./[0-9].*')\n" +"['./1.gif', './2.txt']\n" +">>> glob.glob('*.gif')\n" +"['1.gif', 'card.gif']\n" +">>> glob.glob('?.gif')\n" +"['1.gif']\n" +">>> glob.glob('**/*.txt', recursive=True)\n" +"['2.txt', 'sub/3.txt']\n" +">>> glob.glob('./**/', recursive=True)\n" +"['./', './sub/']" +msgstr "" +">>> import glob\n" +">>> glob.glob('./[0-9].*')\n" +"['./1.gif', './2.txt']\n" +">>> glob.glob('*.gif')\n" +"['1.gif', 'card.gif']\n" +">>> glob.glob('?.gif')\n" +"['1.gif']\n" +">>> glob.glob('**/*.txt', recursive=True)\n" +"['2.txt', 'sub/3.txt']\n" +">>> glob.glob('./**/', recursive=True)\n" +"['./', './sub/']" + #: ../../library/glob.rst:185 msgid "" "If the directory contains files starting with ``.`` they won't be matched by " @@ -288,6 +310,20 @@ msgstr "" "correspondidos por padrão. Por exemplo, considere um diretório contendo :" "file:`card.gif` e :file:`.card.gif` ::" +#: ../../library/glob.rst:189 +msgid "" +">>> import glob\n" +">>> glob.glob('*.gif')\n" +"['card.gif']\n" +">>> glob.glob('.c*')\n" +"['.card.gif']" +msgstr "" +">>> import glob\n" +">>> glob.glob('*.gif')\n" +"['card.gif']\n" +">>> glob.glob('.c*')\n" +"['.card.gif']" + #: ../../library/glob.rst:196 msgid "" "The :mod:`fnmatch` module offers shell-style filename (not path) expansion." diff --git a/library/graphlib.po b/library/graphlib.po index 6dd7f3dbe..0a22020d0 100644 --- a/library/graphlib.po +++ b/library/graphlib.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2021 -# Leticia Portella , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:06+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -124,6 +122,18 @@ msgstr "" "nenhum paralelismo esteja envolvido, o método de conveniência :meth:" "`TopologicalSorter.static_order` pode ser usado diretamente:" +#: ../../library/graphlib.rst:53 +msgid "" +">>> graph = {\"D\": {\"B\", \"C\"}, \"C\": {\"A\"}, \"B\": {\"A\"}}\n" +">>> ts = TopologicalSorter(graph)\n" +">>> tuple(ts.static_order())\n" +"('A', 'C', 'B', 'D')" +msgstr "" +">>> graph = {\"D\": {\"B\", \"C\"}, \"C\": {\"A\"}, \"B\": {\"A\"}}\n" +">>> ts = TopologicalSorter(graph)\n" +">>> tuple(ts.static_order())\n" +"('A', 'C', 'B', 'D')" + #: ../../library/graphlib.rst:60 msgid "" "The class is designed to easily support parallel processing of the nodes as " @@ -132,6 +142,53 @@ msgstr "" "A classe foi projetada para suportar facilmente o processamento paralelo dos " "nós à medida que eles se tornam prontos. Por exemplo::" +#: ../../library/graphlib.rst:63 +msgid "" +"topological_sorter = TopologicalSorter()\n" +"\n" +"# Add nodes to 'topological_sorter'...\n" +"\n" +"topological_sorter.prepare()\n" +"while topological_sorter.is_active():\n" +" for node in topological_sorter.get_ready():\n" +" # Worker threads or processes take nodes to work on off the\n" +" # 'task_queue' queue.\n" +" task_queue.put(node)\n" +"\n" +" # When the work for a node is done, workers put the node in\n" +" # 'finalized_tasks_queue' so we can get more nodes to work on.\n" +" # The definition of 'is_active()' guarantees that, at this point, at\n" +" # least one node has been placed on 'task_queue' that hasn't yet\n" +" # been passed to 'done()', so this blocking 'get()' must (eventually)\n" +" # succeed. After calling 'done()', we loop back to call 'get_ready()'\n" +" # again, so put newly freed nodes on 'task_queue' as soon as\n" +" # logically possible.\n" +" node = finalized_tasks_queue.get()\n" +" topological_sorter.done(node)" +msgstr "" +"topological_sorter = TopologicalSorter()\n" +"\n" +"# Adiciona nodos para 'topological_sorter'...\n" +"\n" +"topological_sorter.prepare()\n" +"while topological_sorter.is_active():\n" +" for node in topological_sorter.get_ready():\n" +" # Processos ou threads de workers obtém nós para\n" +" # trabalhar na fila 'task_queue'.\n" +" task_queue.put(node)\n" +"\n" +" # Quando o trabalho para um nó é feito, os workers colocam o\n" +" # nó em 'finalized_tasks_queue' para que possamos obter mais\n" +" # nós para trabalhar. A definição de 'is_active()' garante que,\n" +" # neste ponto, pelo menos um nó foi colocado em 'task_queue'\n" +" # que ainda não foi passado para 'done()', então este 'get()' de\n" +" # bloqueio deve (eventualmente) ter sucesso. Depois de chamar\n" +" # 'done()', fazemos um laço de volta para chamar 'get_ready()'\n" +" # novamente, então colocamos nós recém-liberados em\n" +" # 'task_queue' o mais rápido possível.\n" +" node = finalized_tasks_queue.get()\n" +" topological_sorter.done(node)" + #: ../../library/graphlib.rst:87 msgid "" "Add a new node and its predecessors to the graph. Both the *node* and all " @@ -206,10 +263,26 @@ msgstr "" "O método :meth:`~object.__bool__` desta classe adia para essa função, então, " "em vez de::" +#: ../../library/graphlib.rst:121 +msgid "" +"if ts.is_active():\n" +" ..." +msgstr "" +"if ts.is_active():\n" +" ..." + #: ../../library/graphlib.rst:124 msgid "it is possible to simply do::" msgstr "é possível simplesmente fazer::" +#: ../../library/graphlib.rst:126 +msgid "" +"if ts:\n" +" ..." +msgstr "" +"if ts:\n" +" ..." + #: ../../library/graphlib.rst:129 ../../library/graphlib.rst:152 msgid "" "Raises :exc:`ValueError` if called without calling :meth:`~TopologicalSorter." @@ -269,6 +342,22 @@ msgstr "" "`~TopologicalSorter.done` não devem ser chamados. Este método é equivalente " "a::" +#: ../../library/graphlib.rst:162 +msgid "" +"def static_order(self):\n" +" self.prepare()\n" +" while self.is_active():\n" +" node_group = self.get_ready()\n" +" yield from node_group\n" +" self.done(*node_group)" +msgstr "" +"def static_order(self):\n" +" self.prepare()\n" +" while self.is_active():\n" +" node_group = self.get_ready()\n" +" yield from node_group\n" +" self.done(*node_group)" + #: ../../library/graphlib.rst:169 msgid "" "The particular order that is returned may depend on the specific order in " @@ -277,6 +366,32 @@ msgstr "" "A ordem específica retornada pode depender da ordem específica em que os " "itens foram inseridos no grafo. Por exemplo:" +#: ../../library/graphlib.rst:172 +msgid "" +">>> ts = TopologicalSorter()\n" +">>> ts.add(3, 2, 1)\n" +">>> ts.add(1, 0)\n" +">>> print([*ts.static_order()])\n" +"[2, 0, 1, 3]\n" +"\n" +">>> ts2 = TopologicalSorter()\n" +">>> ts2.add(1, 0)\n" +">>> ts2.add(3, 2, 1)\n" +">>> print([*ts2.static_order()])\n" +"[0, 2, 1, 3]" +msgstr "" +">>> ts = TopologicalSorter()\n" +">>> ts.add(3, 2, 1)\n" +">>> ts.add(1, 0)\n" +">>> print([*ts.static_order()])\n" +"[2, 0, 1, 3]\n" +"\n" +">>> ts2 = TopologicalSorter()\n" +">>> ts2.add(1, 0)\n" +">>> ts2.add(3, 2, 1)\n" +">>> print([*ts2.static_order()])\n" +"[0, 2, 1, 3]" + #: ../../library/graphlib.rst:186 msgid "" "This is due to the fact that \"0\" and \"2\" are in the same level in the " diff --git a/library/grp.po b/library/grp.po index 5b0ff9d7d..c23c0efee 100644 --- a/library/grp.po +++ b/library/grp.po @@ -1,46 +1,43 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Welington Carlos , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Marciel Leal , 2021 -# i17obot , 2021 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:07+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/grp.rst:2 msgid ":mod:`!grp` --- The group database" -msgstr "" +msgstr ":mod:`!grp` --- O banco de dados de grupos" #: ../../library/grp.rst:10 msgid "" "This module provides access to the Unix group database. It is available on " "all Unix versions." msgstr "" +"Este módulo fornece acesso ao banco de dados de grupos Unix. Ele está " +"disponível em todas as versões do Unix." #: ../../library/grp.rst:13 -msgid ":ref:`Availability `: Unix, not WASI, not iOS." -msgstr ":ref:`Disponibilidade `: Unix, não WASI, não iOS." +msgid "Availability" +msgstr "Disponibilidade" #: ../../library/grp.rst:15 msgid "" @@ -48,6 +45,9 @@ msgid "" "correspond to the members of the ``group`` structure (Attribute field below, " "see ````):" msgstr "" +"As entradas do banco de dados de grupos são relatadas como um objeto tupla " +"ou similar, cujos atributos correspondem aos membros da estrutura ``group`` " +"(campo Atributo abaixo, consulte ````):" #: ../../library/grp.rst:20 msgid "Index" @@ -83,7 +83,7 @@ msgstr "gr_passwd" #: ../../library/grp.rst:24 msgid "the (encrypted) group password; often empty" -msgstr "" +msgstr "a senha do grupo (criptografada); geralmente vazia" #: ../../library/grp.rst:27 msgid "2" @@ -91,7 +91,7 @@ msgstr "2" #: ../../library/grp.rst:27 msgid "gr_gid" -msgstr "" +msgstr "gr_gid" #: ../../library/grp.rst:27 msgid "the numerical group ID" @@ -107,7 +107,7 @@ msgstr "gr_mem" #: ../../library/grp.rst:29 msgid "all the group member's user names" -msgstr "" +msgstr "todos os nomes de usuários dos membros do grupo" #: ../../library/grp.rst:33 msgid "" @@ -119,6 +119,13 @@ msgid "" "reference and may not be accessible via :func:`getgrnam` or :func:" "`getgrgid`.)" msgstr "" +"O gid é um inteiro, nome e senha são strings, e a lista de membros é uma " +"lista de strings. (Observe que a maioria dos usuários não são listados " +"explicitamente como membros do grupo em que estão, de acordo com o banco de " +"dados de senhas. Verifique ambos os bancos de dados para obter informações " +"completas sobre associação. Observe também que um ``gr_name`` que começa com " +"``+`` ou ``-`` provavelmente é uma referência YP/NIS e pode não ser " +"acessível via :func:`getgrnam` ou :func:`getgrgid`.)" #: ../../library/grp.rst:40 msgid "It defines the following items:" @@ -129,21 +136,31 @@ msgid "" "Return the group database entry for the given numeric group ID. :exc:" "`KeyError` is raised if the entry asked for cannot be found." msgstr "" +"Retorna a entrada do banco de dados de grupos para o ID do grupo numérico " +"fornecido. :exc:`KeyError` é levantada se a entrada solicitada não puder ser " +"encontrada." #: ../../library/grp.rst:48 msgid "" ":exc:`TypeError` is raised for non-integer arguments like floats or strings." msgstr "" +":exc:`TypeError` é levantada para argumentos não inteiros, como pontos " +"flutuantes ou strings." #: ../../library/grp.rst:53 msgid "" "Return the group database entry for the given group name. :exc:`KeyError` is " "raised if the entry asked for cannot be found." msgstr "" +"Retorna a entrada do banco de dados de grupos para o nome do grupo " +"fornecido. :exc:`KeyError` é levantada se a entrada solicitada não puder ser " +"encontrada." #: ../../library/grp.rst:59 msgid "Return a list of all available group entries, in arbitrary order." msgstr "" +"Retorna uma lista de todas as entradas de grupo disponíveis, em ordem " +"arbitrária." #: ../../library/grp.rst:64 msgid "Module :mod:`pwd`" @@ -151,4 +168,4 @@ msgstr "Módulo :mod:`pwd`" #: ../../library/grp.rst:65 msgid "An interface to the user database, similar to this." -msgstr "" +msgstr "Uma interface para o banco de dados de usuários, semelhante a esta." diff --git a/library/gzip.po b/library/gzip.po index 56d64afc9..5c70ebcde 100644 --- a/library/gzip.po +++ b/library/gzip.po @@ -1,34 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Adorilson Bezerra , 2021 -# Christian Janiake , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-20 06:40+0000\n" -"PO-Revision-Date: 2021-06-28 01:07+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-04-25 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/gzip.rst:2 msgid ":mod:`!gzip` --- Support for :program:`gzip` files" -msgstr "" +msgstr ":mod:`!gzip` --- Suporte para arquivos :program:`gzip`" #: ../../library/gzip.rst:7 msgid "**Source code:** :source:`Lib/gzip.py`" @@ -39,10 +36,12 @@ msgid "" "This module provides a simple interface to compress and decompress files " "just like the GNU programs :program:`gzip` and :program:`gunzip` would." msgstr "" +"Esse módulo disponibiliza uma interface simples para comprimir e extrair " +"arquivos como os programas GNU :program:`gzip` e :program:`gunzip` fazem." #: ../../library/gzip.rst:14 msgid "The data compression is provided by the :mod:`zlib` module." -msgstr "" +msgstr "A compressão de dados é realizada pelo módulo :mod:`zlib`." #: ../../library/gzip.rst:16 msgid "" @@ -52,6 +51,11 @@ msgid "" "files, automatically compressing or decompressing the data so that it looks " "like an ordinary :term:`file object`." msgstr "" +"O módulo :mod:`gzip` fornece a classe :class:`GzipFile`, bem como as funções " +"de conveniência :func:`.open`, :func:`compress` e :func:`decompress`. A " +"classe :class:`GzipFile` lê e grava arquivos no formato :program:`gzip`, " +"compactando ou descompactando automaticamente os dados para que se pareçam " +"com um :term:`objeto arquivo` comum." #: ../../library/gzip.rst:22 msgid "" @@ -59,6 +63,10 @@ msgid "" "`gzip` and :program:`gunzip` programs, such as those produced by :program:" "`compress` and :program:`pack`, are not supported by this module." msgstr "" +"Observe que formatos de arquivo adicionais que podem ser descompactados " +"pelos programas :program:`gzip` e :program:`gunzip`, como aqueles produzidos " +"por :program:`compress` e :program:`pack`, não são suportados por este " +"módulo." #: ../../library/gzip.rst:26 msgid "The module defines the following items:" @@ -69,12 +77,16 @@ msgid "" "Open a gzip-compressed file in binary or text mode, returning a :term:`file " "object`." msgstr "" +"Abre um arquivo comprimido com gzip em modo binário ou texto, retornando :" +"term:`file object`." #: ../../library/gzip.rst:34 msgid "" "The *filename* argument can be an actual filename (a :class:`str` or :class:" "`bytes` object), or an existing file object to read from or write to." msgstr "" +"O argumento *filename* pode ser um nome de arquivo real (um objeto :class:" +"`str` ou :class:`bytes`), ou um objeto arquivo existente para ler ou gravar." #: ../../library/gzip.rst:37 msgid "" @@ -82,12 +94,18 @@ msgid "" "``'w'``, ``'wb'``, ``'x'`` or ``'xb'`` for binary mode, or ``'rt'``, " "``'at'``, ``'wt'``, or ``'xt'`` for text mode. The default is ``'rb'``." msgstr "" +"O argumento *mode* pode ser qualquer um de ``'r'``, ``'rb'``, ``'a'``, " +"``'ab'``, ``'w'``, ``'wb'``, ``'x'`` ou ``'xb'`` para modo binário, ou " +"``'rt'``, ``'at'``, ``'wt'`` ou ``'xt'`` para modo texto. O padrão é " +"``'rb'``." #: ../../library/gzip.rst:41 msgid "" "The *compresslevel* argument is an integer from 0 to 9, as for the :class:" "`GzipFile` constructor." msgstr "" +"O argumento *compresslevel* é um inteiro de 0 a 9, como para o construtor " +"de :class:`GzipFile`." #: ../../library/gzip.rst:44 msgid "" @@ -95,6 +113,9 @@ msgid "" "constructor: ``GzipFile(filename, mode, compresslevel)``. In this case, the " "*encoding*, *errors* and *newline* arguments must not be provided." msgstr "" +"Para o modo binário, esta função equivale ao construtor de :class:" +"`GzipFile`: ``GzipFile(filename, mode, compresslevel)``. Neste caso, os " +"argumentos *encoding*, *errors* e *newline* não devem ser fornecidos." #: ../../library/gzip.rst:48 msgid "" @@ -102,18 +123,23 @@ msgid "" "class:`io.TextIOWrapper` instance with the specified encoding, error " "handling behavior, and line ending(s)." msgstr "" +"Para o modo texto, um objeto :class:`GzipFile` é criado e encapsulado em uma " +"instância :class:`io.TextIOWrapper` com a codificação especificada, " +"comportamento de tratamento de erros e final(is) de linha." #: ../../library/gzip.rst:52 msgid "" "Added support for *filename* being a file object, support for text mode, and " "the *encoding*, *errors* and *newline* arguments." msgstr "" +"Adicionado suporte para *filename* ser um objeto arquivo, suporte para modo " +"texto e os argumentos *encoding*, *errors* e *newline*." #: ../../library/gzip.rst:56 msgid "Added support for the ``'x'``, ``'xb'`` and ``'xt'`` modes." -msgstr "" +msgstr "Adicionado suporte para os modos ``'x'``, ``'xb'`` e ``'xt'``." -#: ../../library/gzip.rst:59 ../../library/gzip.rst:175 +#: ../../library/gzip.rst:59 ../../library/gzip.rst:173 msgid "Accepts a :term:`path-like object`." msgstr "Aceita um :term:`objeto caminho ou similar`." @@ -123,6 +149,9 @@ msgid "" "`OSError`. :exc:`EOFError` and :exc:`zlib.error` can also be raised for " "invalid gzip files." msgstr "" +"Uma exceção levantada para arquivos gzip inválidos. Herda de :exc:" +"`OSError`. :exc:`EOFError` e :exc:`zlib.error` também podem ser levantadas " +"para arquivos gzip inválidos." #: ../../library/gzip.rst:72 msgid "" @@ -131,6 +160,10 @@ msgid "" "IOBase.truncate` method. At least one of *fileobj* and *filename* must be " "given a non-trivial value." msgstr "" +"Construtor para a classe :class:`GzipFile`, que simula a maioria dos métodos " +"de um :term:`objeto arquivo`, com exceção do método :meth:`~io.IOBase." +"truncate`. Pelo menos um dos métodos *fileobj* e *filename* deve receber um " +"valor não trivial." #: ../../library/gzip.rst:77 msgid "" @@ -139,6 +172,10 @@ msgid "" "It defaults to ``None``, in which case *filename* is opened to provide a " "file object." msgstr "" +"A nova instância de classe é baseada em *fileobj*, que pode ser um arquivo " +"comum, um objeto :class:`io.BytesIO` ou qualquer outro objeto que simule um " +"arquivo. O padrão é ``None``, caso em que *filename* é aberto para fornecer " +"um objeto arquivo." #: ../../library/gzip.rst:82 msgid "" @@ -148,6 +185,11 @@ msgid "" "*fileobj*, if discernible; otherwise, it defaults to the empty string, and " "in this case the original filename is not included in the header." msgstr "" +"Quando *fileobj* não é ``None``, o argumento *filename* é usado apenas para " +"ser incluído no cabeçalho do arquivo :program:`gzip`, que pode incluir o " +"nome original do arquivo descompactado. O padrão é o nome de arquivo " +"*fileobj*, se discernível; caso contrário, o padrão é a string vazia e, " +"neste caso, o nome original do arquivo não é incluído no cabeçalho." #: ../../library/gzip.rst:88 msgid "" @@ -158,6 +200,12 @@ msgid "" "*fileobj* will not be used. It is better to always specify *mode* for " "writing." msgstr "" +"O argumento *mode* pode ser qualquer um dos seguintes: ``'r'``, ``'rb'``, " +"``'a'``, ``'ab'``, ``'w'``, ``'wb'``, ``'x'`` ou ``'xb'``, dependendo se o " +"arquivo será lido ou escrito. O padrão é o modo de *fileobj*, se " +"discernível; caso contrário, o padrão é ``'rb'``. Em versões futuras do " +"Python, o modo de *fileobj* não será usado. É melhor sempre especificar " +"*mode* para escrita." #: ../../library/gzip.rst:94 msgid "" @@ -165,6 +213,9 @@ msgid "" "file in text mode, use :func:`.open` (or wrap your :class:`GzipFile` with " "an :class:`io.TextIOWrapper`)." msgstr "" +"Observe que o arquivo é sempre aberto em modo binário. Para abrir um arquivo " +"compactado em modo texto, use :func:`.open` (ou envolva seu :class:" +"`GzipFile` com um :class:`io.TextIOWrapper`)." #: ../../library/gzip.rst:98 msgid "" @@ -173,6 +224,10 @@ msgid "" "compression, and ``9`` is slowest and produces the most compression. ``0`` " "is no compression. The default is ``9``." msgstr "" +"O argumento *compresslevel* é um inteiro de ``0`` a ``9`` que controla o " +"nível de compressão; ``1`` é o mais rápido e produz a menor compressão, e " +"``9`` é o mais lento e produz a maior compressão. ``0`` significa sem " +"compressão. O padrão é ``9``." #: ../../library/gzip.rst:103 msgid "" @@ -181,11 +236,17 @@ msgid "" "*mtime* is omitted or ``None``, the current time is used. Use *mtime* = 0 to " "generate a compressed stream that does not depend on creation time." msgstr "" +"O argumento opcional *mtime* é o registro de data e hora solicitado pelo " +"gzip. O horário está no formato Unix, ou seja, segundos desde 00:00:00 UTC, " +"1º de janeiro de 1970. Se *mtime* for omitido ou definido como ``None``, o " +"horário atual será usado. Use *mtime* = 0 para gerar um fluxo compactado que " +"não depende do horário de criação." #: ../../library/gzip.rst:108 msgid "" "See below for the :attr:`mtime` attribute that is set when decompressing." msgstr "" +"Veja abaixo o atributo :attr:`mtime` que é definido durante a descompactação." #: ../../library/gzip.rst:110 msgid "" @@ -195,6 +256,12 @@ msgid "" "writing as *fileobj*, and retrieve the resulting memory buffer using the :" "class:`io.BytesIO` object's :meth:`~io.BytesIO.getvalue` method." msgstr "" +"Chamar o método :meth:`!close` de um objeto :class:`GzipFile` não fecha " +"*fileobj*, pois você pode querer adicionar mais material após os dados " +"compactados. Isso também permite que você passe um objeto :class:`io." +"BytesIO` aberto para escrita como *fileobj* e recupere o buffer de memória " +"resultante usando o método :meth:`~io.BytesIO.getvalue` do objeto :class:`io." +"BytesIO`." #: ../../library/gzip.rst:116 msgid "" @@ -202,97 +269,125 @@ msgid "" "including iteration and the :keyword:`with` statement. Only the :meth:`~io." "IOBase.truncate` method isn't implemented." msgstr "" +":class:`GzipFile` suporta a interface :class:`io.BufferedIOBase`, incluindo " +"iteração e a instrução :keyword:`with`. Apenas o método :meth:`~io.IOBase." +"truncate` não é implementado." #: ../../library/gzip.rst:120 msgid ":class:`GzipFile` also provides the following method and attribute:" msgstr "" +":class:`GzipFile` também disponibiliza os seguintes métodos e atributos:" #: ../../library/gzip.rst:124 msgid "" -"Read *n* uncompressed bytes without advancing the file position. At most one " -"single read on the compressed stream is done to satisfy the call. The " -"number of bytes returned may be more or less than requested." +"Read *n* uncompressed bytes without advancing the file position. The number " +"of bytes returned may be more or less than requested." msgstr "" +"Lê *n* bytes não compactados sem avançar a posição do arquivo. O número de " +"bytes retornados pode ser maior ou menor que o solicitado." -#: ../../library/gzip.rst:129 +#: ../../library/gzip.rst:127 msgid "" "While calling :meth:`peek` does not change the file position of the :class:" "`GzipFile`, it may change the position of the underlying file object (e.g. " "if the :class:`GzipFile` was constructed with the *fileobj* parameter)." msgstr "" +"Embora chamar :meth:`peek` não altere a posição do arquivo :class:" +"`GzipFile`, ele pode alterar a posição do objeto arquivo subjacente (por " +"exemplo, se o :class:`GzipFile` foi construído com o parâmetro *fileobj*)." -#: ../../library/gzip.rst:138 +#: ../../library/gzip.rst:136 msgid "``'rb'`` for reading and ``'wb'`` for writing." msgstr "``'rb'`` para leitura e ``'wb'`` para escrita." -#: ../../library/gzip.rst:140 +#: ../../library/gzip.rst:138 msgid "In previous versions it was an integer ``1`` or ``2``." -msgstr "" +msgstr "Em versões anteriores era um inteiro ``1`` ou ``2``." -#: ../../library/gzip.rst:145 +#: ../../library/gzip.rst:143 msgid "" "When decompressing, this attribute is set to the last timestamp in the most " "recently read header. It is an integer, holding the number of seconds since " "the Unix epoch (00:00:00 UTC, January 1, 1970). The initial value before " "reading any headers is ``None``." msgstr "" +"Ao descompactar, este atributo é definido como o último registro de data e " +"hora no cabeçalho lido mais recentemente. É um inteiro que contém o número " +"de segundos desde a era Unix (00:00:00 UTC, 1º de janeiro de 1970). O valor " +"inicial antes da leitura de qualquer cabeçalho é ``None``." -#: ../../library/gzip.rst:152 +#: ../../library/gzip.rst:150 msgid "" "The path to the gzip file on disk, as a :class:`str` or :class:`bytes`. " "Equivalent to the output of :func:`os.fspath` on the original input path, " "with no other normalization, resolution or expansion." msgstr "" +"O caminho para o arquivo gzip no disco, como :class:`str` ou :class:`bytes`. " +"Equivalente à saída de :func:`os.fspath` no caminho de entrada original, sem " +"nenhuma outra normalização, resolução ou expansão." -#: ../../library/gzip.rst:156 +#: ../../library/gzip.rst:154 msgid "" "Support for the :keyword:`with` statement was added, along with the *mtime* " "constructor argument and :attr:`mtime` attribute." msgstr "" +"Foi adicionado suporte para a instrução :keyword:`with`, juntamente com o " +"argumento do construtor *mtime* e o atributo :attr:`mtime`." -#: ../../library/gzip.rst:160 +#: ../../library/gzip.rst:158 msgid "Support for zero-padded and unseekable files was added." msgstr "" +"Foi adicionado suporte para arquivos preenchidos com zeros e não " +"pesquisáveis." -#: ../../library/gzip.rst:163 +#: ../../library/gzip.rst:161 msgid "The :meth:`io.BufferedIOBase.read1` method is now implemented." -msgstr "" +msgstr "O método :meth:`io.BufferedIOBase.read1` agora está implementado." -#: ../../library/gzip.rst:166 +#: ../../library/gzip.rst:164 msgid "Added support for the ``'x'`` and ``'xb'`` modes." -msgstr "" +msgstr "Adicionado suporte para os modos ``'x'`` e ``'xb'``." -#: ../../library/gzip.rst:169 +#: ../../library/gzip.rst:167 msgid "" "Added support for writing arbitrary :term:`bytes-like objects `. The :meth:`~io.BufferedIOBase.read` method now accepts an argument " "of ``None``." msgstr "" +"Adicionado suporte para escrever :term:`objetos bytes ou similares ` arbitrários. O método :meth:`~io.BufferedIOBase.read` agora " +"aceita o argumento ``None``." -#: ../../library/gzip.rst:178 +#: ../../library/gzip.rst:176 msgid "" "Opening :class:`GzipFile` for writing without specifying the *mode* argument " "is deprecated." msgstr "" +"Abrir :class:`GzipFile` para escrita sem especificar o argumento *mode* está " +"descontinuado." -#: ../../library/gzip.rst:182 +#: ../../library/gzip.rst:180 msgid "" "Remove the ``filename`` attribute, use the :attr:`~GzipFile.name` attribute " "instead." msgstr "" +"Remove o atributo ``filename`` e usa o atributo :attr:`~GzipFile.name`." -#: ../../library/gzip.rst:189 +#: ../../library/gzip.rst:187 msgid "" "Compress the *data*, returning a :class:`bytes` object containing the " "compressed data. *compresslevel* and *mtime* have the same meaning as in " "the :class:`GzipFile` constructor above." msgstr "" +"Compacta *data*, retornando um objeto :class:`bytes` contendo os dados " +"compactados. *compresslevel* e *mtime* têm o mesmo significado que no " +"construtor de :class:`GzipFile` acima." -#: ../../library/gzip.rst:194 +#: ../../library/gzip.rst:192 msgid "Added the *mtime* parameter for reproducible output." -msgstr "" +msgstr "Adicionado o parâmetro *mtime* para saída reproduzível." -#: ../../library/gzip.rst:196 +#: ../../library/gzip.rst:194 msgid "" "Speed is improved by compressing all data at once instead of in a streamed " "fashion. Calls with *mtime* set to ``0`` are delegated to :func:`zlib." @@ -300,14 +395,22 @@ msgid "" "header \"OS\" byte value other than 255 \"unknown\" as supplied by the " "underlying zlib implementation." msgstr "" +"A velocidade é melhorada pela compactação de todos os dados de uma só vez, " +"em vez de em fluxo contínuo. Chamadas com *mtime* definido como ``0`` são " +"delegadas a :func:`zlib.compress` para maior velocidade. Nessa situação, a " +"saída pode conter um valor de byte \"OS\" no cabeçalho gzip diferente de 255 " +"\"unknown\", conforme fornecido pela implementação subjacente do zlib." -#: ../../library/gzip.rst:203 +#: ../../library/gzip.rst:201 msgid "" "The gzip header OS byte is guaranteed to be set to 255 when this function is " "used as was the case in 3.10 and earlier." msgstr "" +"O byte do cabeçalho gzip do sistema operacional tem a garantia de ser " +"definido como 255 quando esta função é usada, como era o caso na versão 3.10 " +"e anteriores." -#: ../../library/gzip.rst:209 +#: ../../library/gzip.rst:207 msgid "" "Decompress the *data*, returning a :class:`bytes` object containing the " "uncompressed data. This function is capable of decompressing multi-member " @@ -315,83 +418,151 @@ msgid "" "certain to contain only one member the :func:`zlib.decompress` function with " "*wbits* set to 31 is faster." msgstr "" +"Descompacta *data*, retornando um objeto :class:`bytes` contendo os dados " +"descompactados. Esta função é capaz de descompactar dados de gzip de vários " +"membros (vários blocos gzip concatenados). Quando é certo que os dados " +"contêm apenas um membro, a função :func:`zlib.decompress` com *wbits* " +"definido como 31 é mais rápida." -#: ../../library/gzip.rst:216 +#: ../../library/gzip.rst:214 msgid "" "Speed is improved by decompressing members at once in memory instead of in a " "streamed fashion." msgstr "" +"A velocidade é melhorada ao descompactar os membros de uma só vez na " +"memória, em vez de fazê-lo de forma contínua." -#: ../../library/gzip.rst:223 +#: ../../library/gzip.rst:221 msgid "Examples of usage" msgstr "Exemplos de uso" -#: ../../library/gzip.rst:225 +#: ../../library/gzip.rst:223 msgid "Example of how to read a compressed file::" +msgstr "Exemplo de como ler um arquivo comprimido::" + +#: ../../library/gzip.rst:225 +msgid "" +"import gzip\n" +"with gzip.open('/home/joe/file.txt.gz', 'rb') as f:\n" +" file_content = f.read()" msgstr "" +"import gzip\n" +"with gzip.open('/home/joe/arquivo.txt.gz', 'rb') as f:\n" +" file_content = f.read()" -#: ../../library/gzip.rst:231 +#: ../../library/gzip.rst:229 msgid "Example of how to create a compressed GZIP file::" +msgstr "Exemplo de como criar um arquivo comprimido com GZIP::" + +#: ../../library/gzip.rst:231 +msgid "" +"import gzip\n" +"content = b\"Lots of content here\"\n" +"with gzip.open('/home/joe/file.txt.gz', 'wb') as f:\n" +" f.write(content)" msgstr "" +"import gzip\n" +"content = b\"Muito conteúdo aqui\"\n" +"with gzip.open('/home/joe/arquivo.txt.gz', 'wb') as f:\n" +" f.write(content)" -#: ../../library/gzip.rst:238 +#: ../../library/gzip.rst:236 msgid "Example of how to GZIP compress an existing file::" +msgstr "Exemplo de como comprimir um arquivo existente com GZIP::" + +#: ../../library/gzip.rst:238 +msgid "" +"import gzip\n" +"import shutil\n" +"with open('/home/joe/file.txt', 'rb') as f_in:\n" +" with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:\n" +" shutil.copyfileobj(f_in, f_out)" msgstr "" +"import gzip\n" +"import shutil\n" +"with open('/home/joe/arquivo.txt', 'rb') as f_in:\n" +" with gzip.open('/home/joe/arquivo.txt.gz', 'wb') as f_out:\n" +" shutil.copyfileobj(f_in, f_out)" -#: ../../library/gzip.rst:246 +#: ../../library/gzip.rst:244 msgid "Example of how to GZIP compress a binary string::" +msgstr "Exemplo de como comprimir uma string binária com compressão GZIP::" + +#: ../../library/gzip.rst:246 +msgid "" +"import gzip\n" +"s_in = b\"Lots of content here\"\n" +"s_out = gzip.compress(s_in)" msgstr "" +"import gzip\n" +"s_in = b\"Muito conteúdo aqui\"\n" +"s_out = gzip.compress(s_in)" -#: ../../library/gzip.rst:254 +#: ../../library/gzip.rst:252 msgid "Module :mod:`zlib`" msgstr "Módulo :mod:`zlib`" -#: ../../library/gzip.rst:255 +#: ../../library/gzip.rst:253 msgid "" "The basic data compression module needed to support the :program:`gzip` file " "format." msgstr "" +"O módulo básico de compactação de dados necessário para dar suporte ao " +"formato de arquivo do :program:`gzip`." -#: ../../library/gzip.rst:264 +#: ../../library/gzip.rst:256 +msgid "" +"In case gzip (de)compression is a bottleneck, the `python-isal`_ package " +"speeds up (de)compression with a mostly compatible API." +msgstr "" +"Caso a (des)compressão do gzip seja um gargalo, o pacote `python-isal`_ " +"acelera a (des)compressão com uma API quase sempre compatível." + +#: ../../library/gzip.rst:266 msgid "Command Line Interface" msgstr "Interface de linha de comando" -#: ../../library/gzip.rst:266 +#: ../../library/gzip.rst:268 msgid "" "The :mod:`gzip` module provides a simple command line interface to compress " "or decompress files." msgstr "" +"O módulo :mod:`gzip` fornece uma interface de linha de comando simples para " +"compactar ou descompactar arquivos." -#: ../../library/gzip.rst:269 +#: ../../library/gzip.rst:271 msgid "Once executed the :mod:`gzip` module keeps the input file(s)." msgstr "" +"Uma vez executado, o módulo :mod:`gzip` mantém o(s) arquivo(s) de entrada." -#: ../../library/gzip.rst:273 +#: ../../library/gzip.rst:275 msgid "" "Add a new command line interface with a usage. By default, when you will " "execute the CLI, the default compression level is 6." msgstr "" +"Adiciona uma nova interface de linha de comando com um mensagem de uso. Por " +"padrão, ao executar a CLI, o nível de compactação padrão é 6." -#: ../../library/gzip.rst:277 +#: ../../library/gzip.rst:279 msgid "Command line options" msgstr "Opções da linha de comando" -#: ../../library/gzip.rst:281 +#: ../../library/gzip.rst:283 msgid "If *file* is not specified, read from :data:`sys.stdin`." -msgstr "" +msgstr "Se o *arquivo* não for especificado, ler de :data:`sys.stdin`" -#: ../../library/gzip.rst:285 +#: ../../library/gzip.rst:287 msgid "Indicates the fastest compression method (less compression)." -msgstr "" +msgstr "Indica o método mais rápido de compressão (menor compressão)" -#: ../../library/gzip.rst:289 +#: ../../library/gzip.rst:291 msgid "Indicates the slowest compression method (best compression)." -msgstr "" +msgstr "Indica o método mais lento de compressão (melhor compressão)." -#: ../../library/gzip.rst:293 +#: ../../library/gzip.rst:295 msgid "Decompress the given file." msgstr "Descompacta o arquivo dado." -#: ../../library/gzip.rst:297 +#: ../../library/gzip.rst:299 msgid "Show the help message." msgstr "Exibe a mensagem de ajuda." diff --git a/library/hashlib.po b/library/hashlib.po index 2e4f98588..930ad35f9 100644 --- a/library/hashlib.po +++ b/library/hashlib.po @@ -1,36 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Raphael Mendonça, 2021 -# i17obot , 2021 -# Marco Rougeth , 2022 -# Claudio Rogerio Carvalho Filho , 2023 -# Vinicius Gubiani Ferreira , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:07+0000\n" -"Last-Translator: Vinicius Gubiani Ferreira , 2023\n" +"POT-Creation-Date: 2025-04-25 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/hashlib.rst:2 msgid ":mod:`!hashlib` --- Secure hashes and message digests" -msgstr "" +msgstr ":mod:`!hashlib` --- resumos de mensagens e hashes seguros" #: ../../library/hashlib.rst:10 msgid "**Source code:** :source:`Lib/hashlib.py`" @@ -38,26 +33,31 @@ msgstr "**Código-fonte:** :source:`Lib/hashlib.py`" #: ../../library/hashlib.rst:23 msgid "" -"This module implements a common interface to many different secure hash and " -"message digest algorithms. Included are the FIPS secure hash algorithms " -"SHA1, SHA224, SHA256, SHA384, SHA512, (defined in `the FIPS 180-4 " -"standard`_), the SHA-3 series (defined in `the FIPS 202 standard`_) as well " -"as RSA's MD5 algorithm (defined in internet :rfc:`1321`). The terms " -"\"secure hash\" and \"message digest\" are interchangeable. Older " -"algorithms were called message digests. The modern term is secure hash." +"This module implements a common interface to many different hash algorithms. " +"Included are the FIPS secure hash algorithms SHA224, SHA256, SHA384, SHA512, " +"(defined in `the FIPS 180-4 standard`_), the SHA-3 series (defined in `the " +"FIPS 202 standard`_) as well as the legacy algorithms SHA1 (`formerly part " +"of FIPS`_) and the MD5 algorithm (defined in internet :rfc:`1321`)." msgstr "" +"Este módulo implementa uma interface comum para diversos algoritmos de hash. " +"Estão incluídos os algoritmos de hash seguros FIPS SHA224, SHA256, SHA384 e " +"SHA512 (definidos no `padrão FIPS 180-4`_), a série SHA-3 (definida no " +"`padrão FIPS 202`_), bem como os algoritmos legados SHA1 (`anteriormente " +"parte do FIPS`_) e o algoritmo MD5 (definido em internet :rfc:`1321`)." -#: ../../library/hashlib.rst:33 +#: ../../library/hashlib.rst:31 msgid "" "If you want the adler32 or crc32 hash functions, they are available in the :" "mod:`zlib` module." msgstr "" +"Se você quiser as funções de hash adler32 ou crc32, elas estão disponíveis " +"no módulo :mod:`zlib`." -#: ../../library/hashlib.rst:40 +#: ../../library/hashlib.rst:38 msgid "Hash algorithms" -msgstr "" +msgstr "Algoritmos de hash" -#: ../../library/hashlib.rst:42 +#: ../../library/hashlib.rst:40 msgid "" "There is one constructor method named for each type of :dfn:`hash`. All " "return a hash object with the same simple interface. For example: use :func:" @@ -68,15 +68,26 @@ msgid "" "using the :meth:`digest()` or :meth:`hexdigest()` methods." msgstr "" +"Há um método construtor nomeado para cada tipo de :dfn:`hash`. Todos " +"retornam um objeto hash com a mesma interface simples. Por exemplo: use :" +"func:`sha256` para criar um objeto hash SHA-256. Agora você pode alimentar " +"este objeto com :term:`objetos bytes ou similar ` " +"(normalmente :class:`bytes`) usando o método :meth:`update`. A " +"qualquer momento, você pode solicitar o :dfn:`digest` da concatenação dos " +"dados alimentados até o momento usando os métodos :meth:`digest()` ou :meth:`hexdigest()`." -#: ../../library/hashlib.rst:50 +#: ../../library/hashlib.rst:48 msgid "" "To allow multithreading, the Python :term:`GIL` is released while computing " "a hash supplied more than 2047 bytes of data at once in its constructor or :" "meth:`.update` method." msgstr "" +"Para permitir multithreading, a :term:`GIL` do Python é liberada ao calcular " +"um hash fornecido com mais de 2047 bytes de dados de uma só vez em seu " +"construtor ou método :meth:`.update`." -#: ../../library/hashlib.rst:57 +#: ../../library/hashlib.rst:55 msgid "" "Constructors for hash algorithms that are always present in this module are :" "func:`sha1`, :func:`sha224`, :func:`sha256`, :func:`sha384`, :func:" @@ -86,30 +97,49 @@ msgid "" "missing or blocked if you are using a rare \"FIPS compliant\" build of " "Python. These correspond to :data:`algorithms_guaranteed`." msgstr "" +"Os construtores para algoritmos de hash sempre presentes neste módulo são :" +"func:`sha1`, :func:`sha224`, :func:`sha256`, :func:`sha384`, :func:" +"`sha512`, :func:`sha3_224`, :func:`sha3_256`, :func:`sha3_384`, :func:" +"`sha3_512`, :func:`shake_128`, :func:`shake_256`, :func:`blake2b` e :func:" +"`blake2s`. :func:`md5` normalmente também está disponível, embora possa " +"estar ausente ou bloqueado se você estiver usando uma construção rara do " +"Python \"compatível com FIPS\". Eles correspondem a :data:" +"`algorithms_guaranteed`." -#: ../../library/hashlib.rst:65 +#: ../../library/hashlib.rst:63 msgid "" "Additional algorithms may also be available if your Python distribution's :" "mod:`hashlib` was linked against a build of OpenSSL that provides others. " "Others *are not guaranteed available* on all installations and will only be " "accessible by name via :func:`new`. See :data:`algorithms_available`." msgstr "" +"Algoritmos adicionais também podem estar disponíveis se o :mod:`hashlib` da " +"sua distribuição Python tiver sido vinculado a uma construção do OpenSSL que " +"forneça outros algoritmos. Outros *não têm garantia de disponibilidade* em " +"todas as instalações e só serão acessíveis pelo nome via :func:`new`. " +"Consulte :data:`algorithms_available`." -#: ../../library/hashlib.rst:72 +#: ../../library/hashlib.rst:70 msgid "" "Some algorithms have known hash collision weaknesses (including MD5 and " "SHA1). Refer to `Attacks on cryptographic hash algorithms`_ and the `hashlib-" "seealso`_ section at the end of this document." msgstr "" +"Alguns algoritmos apresentam vulnerabilidades conhecidas em colisões de hash " +"(incluindo MD5 e SHA1). Consulte `Ataques a algoritmos de hash " +"criptográficos`_ e a seção `hashlib-seealso`_ no final deste documento." -#: ../../library/hashlib.rst:76 +#: ../../library/hashlib.rst:74 msgid "" "SHA3 (Keccak) and SHAKE constructors :func:`sha3_224`, :func:`sha3_256`, :" "func:`sha3_384`, :func:`sha3_512`, :func:`shake_128`, :func:`shake_256` were " "added. :func:`blake2b` and :func:`blake2s` were added." msgstr "" +"Os construtores SHA3 (Keccak) e SHAKE :func:`sha3_224`, :func:`sha3_256`, :" +"func:`sha3_384`, :func:`sha3_512`, :func:`shake_128`, :func:`shake_256` " +"foram adicionados. :func:`blake2b` e :func:`blake2s` foram adicionados." -#: ../../library/hashlib.rst:84 +#: ../../library/hashlib.rst:82 msgid "" "All hashlib constructors take a keyword-only argument *usedforsecurity* with " "default value ``True``. A false value allows the use of insecure and blocked " @@ -117,71 +147,116 @@ msgid "" "hashing algorithm is not used in a security context, e.g. as a non-" "cryptographic one-way compression function." msgstr "" +"Todos os construtores de hashlib aceitam um argumento somente-nomeado " +"*usedforsecurity* com o valor padrão ``True``. Um valor falso permite o uso " +"de algoritmos de hash inseguros e bloqueados em ambientes restritos. " +"``False`` indica que o algoritmo de hash não é usado em um contexto de " +"segurança, por exemplo, como uma função de compressão unidirecional não " +"criptográfica." -#: ../../library/hashlib.rst:91 +#: ../../library/hashlib.rst:89 msgid "Hashlib now uses SHA3 and SHAKE from OpenSSL if it provides it." -msgstr "" +msgstr "O hashlib agora usa SHA3 e SHAKE do OpenSSL, se ele os fornecer." -#: ../../library/hashlib.rst:94 +#: ../../library/hashlib.rst:92 msgid "" "For any of the MD5, SHA1, SHA2, or SHA3 algorithms that the linked OpenSSL " "does not provide we fall back to a verified implementation from the `HACL\\* " "project`_." msgstr "" +"Para qualquer um dos algoritmos MD5, SHA1, SHA2 ou SHA3 que o OpenSSL " +"vinculado não fornece, recorremos a uma implementação verificada do `projeto " +"HACL\\*`_." -#: ../../library/hashlib.rst:100 +#: ../../library/hashlib.rst:98 msgid "Usage" msgstr "Uso" -#: ../../library/hashlib.rst:102 +#: ../../library/hashlib.rst:100 msgid "" "To obtain the digest of the byte string ``b\"Nobody inspects the spammish " "repetition\"``::" msgstr "" +"Para obter o resumo da string de bytes ``b\"Nobody inspects the spammish " +"repetition\"``::" -#: ../../library/hashlib.rst:114 +#: ../../library/hashlib.rst:103 +msgid "" +">>> import hashlib\n" +">>> m = hashlib.sha256()\n" +">>> m.update(b\"Nobody inspects\")\n" +">>> m.update(b\" the spammish repetition\")\n" +">>> m.digest()\n" +"b'\\x03\\x1e\\xdd}Ae\\x15\\x93\\xc5\\xfe\\\\" +"\\x00o\\xa5u+7\\xfd\\xdf\\xf7\\xbcN\\x84:" +"\\xa6\\xaf\\x0c\\x95\\x0fK\\x94\\x06'\n" +">>> m.hexdigest()\n" +"'031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406'" +msgstr "" +">>> import hashlib\n" +">>> m = hashlib.sha256()\n" +">>> m.update(b\"Nobody inspects\")\n" +">>> m.update(b\" the spammish repetition\")\n" +">>> m.digest()\n" +"b'\\x03\\x1e\\xdd}Ae\\x15\\x93\\xc5\\xfe\\\\" +"\\x00o\\xa5u+7\\xfd\\xdf\\xf7\\xbcN\\x84:" +"\\xa6\\xaf\\x0c\\x95\\x0fK\\x94\\x06'\n" +">>> m.hexdigest()\n" +"'031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406'" + +#: ../../library/hashlib.rst:112 msgid "More condensed:" -msgstr "" +msgstr "Mais condensado:" -#: ../../library/hashlib.rst:120 +#: ../../library/hashlib.rst:118 msgid "Constructors" -msgstr "" +msgstr "Construtores" -#: ../../library/hashlib.rst:124 +#: ../../library/hashlib.rst:122 msgid "" "Is a generic constructor that takes the string *name* of the desired " "algorithm as its first parameter. It also exists to allow access to the " "above listed hashes as well as any other algorithms that your OpenSSL " "library may offer." msgstr "" +"É um construtor genérico que recebe a string *name* do algoritmo desejado " +"como seu primeiro parâmetro. Ele também existe para permitir acesso aos " +"hashes listados acima, bem como a quaisquer outros algoritmos que sua " +"biblioteca OpenSSL possa oferecer." -#: ../../library/hashlib.rst:129 +#: ../../library/hashlib.rst:127 msgid "Using :func:`new` with an algorithm name:" -msgstr "" +msgstr "Usando :func:`new` com um nome de algoritmo:" -#: ../../library/hashlib.rst:148 +#: ../../library/hashlib.rst:146 msgid "" "Named constructors such as these are faster than passing an algorithm name " "to :func:`new`." msgstr "" +"Construtores nomeados como esses são mais rápidos do que passar um nome de " +"algoritmo para :func:`new`." -#: ../../library/hashlib.rst:152 +#: ../../library/hashlib.rst:150 msgid "Attributes" -msgstr "" +msgstr "Atributos" -#: ../../library/hashlib.rst:154 +#: ../../library/hashlib.rst:152 msgid "Hashlib provides the following constant module attributes:" -msgstr "" +msgstr "O hashlib fornece os seguintes atributos de módulo constantes:" -#: ../../library/hashlib.rst:158 +#: ../../library/hashlib.rst:156 msgid "" "A set containing the names of the hash algorithms guaranteed to be supported " "by this module on all platforms. Note that 'md5' is in this list despite " "some upstream vendors offering an odd \"FIPS compliant\" Python build that " "excludes it." msgstr "" +"Um conjunto contendo os nomes dos algoritmos de hash com suporte garantido " +"por este módulo em todas as plataformas. Observe que \"md5\" está nesta " +"lista, apesar de alguns fornecedores originais oferecerem uma estranha " +"construção Python \"compatível com FIPS\" que o exclui." -#: ../../library/hashlib.rst:167 +#: ../../library/hashlib.rst:165 msgid "" "A set containing the names of the hash algorithms that are available in the " "running Python interpreter. These names will be recognized when passed to :" @@ -189,144 +264,208 @@ msgid "" "same algorithm may appear multiple times in this set under different names " "(thanks to OpenSSL)." msgstr "" +"Um conjunto contendo os nomes dos algoritmos de hash disponíveis no " +"interpretador Python em execução. Esses nomes serão reconhecidos quando " +"passados ​​para :func:`new`. :attr:`algorithms_guaranteed` sempre será um " +"subconjunto. O mesmo algoritmo pode aparecer várias vezes neste conjunto com " +"nomes diferentes (graças ao OpenSSL)." -#: ../../library/hashlib.rst:176 +#: ../../library/hashlib.rst:174 msgid "Hash Objects" -msgstr "" +msgstr "Objetos hash" -#: ../../library/hashlib.rst:178 +#: ../../library/hashlib.rst:176 msgid "" "The following values are provided as constant attributes of the hash objects " "returned by the constructors:" msgstr "" +"Os seguintes valores são fornecidos como atributos constantes dos objetos " +"hash retornados pelos construtores:" -#: ../../library/hashlib.rst:183 +#: ../../library/hashlib.rst:181 msgid "The size of the resulting hash in bytes." -msgstr "" +msgstr "O tamanho do hash resultante em bytes." -#: ../../library/hashlib.rst:187 +#: ../../library/hashlib.rst:185 msgid "The internal block size of the hash algorithm in bytes." -msgstr "" +msgstr "O tamanho do bloco interna do algoritmo de hash em bytes." -#: ../../library/hashlib.rst:189 +#: ../../library/hashlib.rst:187 msgid "A hash object has the following attributes:" -msgstr "" +msgstr "Um objeto hash tem os seguintes atributos:" -#: ../../library/hashlib.rst:193 +#: ../../library/hashlib.rst:191 msgid "" "The canonical name of this hash, always lowercase and always suitable as a " "parameter to :func:`new` to create another hash of this type." msgstr "" +"O nome canônico deste hash, sempre em minúsculas e sempre adequado como " +"parâmetro para :func:`new` para criar outro hash deste tipo." -#: ../../library/hashlib.rst:196 +#: ../../library/hashlib.rst:194 msgid "" "The name attribute has been present in CPython since its inception, but " "until Python 3.4 was not formally specified, so may not exist on some " "platforms." msgstr "" +"O atributo name está presente no CPython desde o seu início, mas até o " +"Python 3.4 não era especificado formalmente, então pode não existir em " +"algumas plataformas." -#: ../../library/hashlib.rst:201 +#: ../../library/hashlib.rst:199 msgid "A hash object has the following methods:" -msgstr "" +msgstr "Um objeto hash tem os seguintes métodos:" -#: ../../library/hashlib.rst:206 +#: ../../library/hashlib.rst:204 msgid "" "Update the hash object with the :term:`bytes-like object`. Repeated calls " "are equivalent to a single call with the concatenation of all the arguments: " "``m.update(a); m.update(b)`` is equivalent to ``m.update(a+b)``." msgstr "" +"Atualiza o objeto hash com o :term:`objeto bytes ou similar`. Chamadas " +"repetidas são equivalentes a uma única chamada com a concatenação de todos " +"os argumentos: ``m.update(a); m.update(b)`` é equivalente a ``m." +"update(a+b)``." -#: ../../library/hashlib.rst:214 +#: ../../library/hashlib.rst:212 msgid "" "Return the digest of the data passed to the :meth:`update` method so far. " "This is a bytes object of size :attr:`digest_size` which may contain bytes " "in the whole range from 0 to 255." msgstr "" +"Retorna o resumo dos dados passados ​​ao método :meth:`update` até o momento. " +"Este é um objeto bytes de tamanho :attr:`digest_size` que pode conter bytes " +"em todo o intervalo de 0 a 255." -#: ../../library/hashlib.rst:221 +#: ../../library/hashlib.rst:219 msgid "" "Like :meth:`digest` except the digest is returned as a string object of " "double length, containing only hexadecimal digits. This may be used to " "exchange the value safely in email or other non-binary environments." msgstr "" +"Similar a :meth:`digest`, exceto que o resumo é retornado como um objeto " +"string de comprimento duplo, contendo apenas dígitos hexadecimais. Isso pode " +"ser usado para trocar o valor com segurança em e-mails ou outros ambientes " +"não binários." -#: ../../library/hashlib.rst:228 +#: ../../library/hashlib.rst:226 msgid "" "Return a copy (\"clone\") of the hash object. This can be used to " "efficiently compute the digests of data sharing a common initial substring." msgstr "" +"Retorna uma cópia (\"clone\") do objeto hash. Isso pode ser usado para " +"calcular com eficiência os resumos de dados que compartilham uma substring " +"inicial comum." -#: ../../library/hashlib.rst:233 +#: ../../library/hashlib.rst:231 msgid "SHAKE variable length digests" -msgstr "" +msgstr "Resumos de comprimento variável de SHAKE" -#: ../../library/hashlib.rst:238 +#: ../../library/hashlib.rst:236 msgid "" "The :func:`shake_128` and :func:`shake_256` algorithms provide variable " "length digests with length_in_bits//2 up to 128 or 256 bits of security. As " "such, their digest methods require a length. Maximum length is not limited " "by the SHAKE algorithm." msgstr "" +"Os algoritmos :func:`shake_128` e :func:`shake_256` fornecem resumos de " +"comprimento variável com length_in_bits//2 de até 128 ou 256 bits de " +"segurança. Portanto, seus métodos de resumo exigem um comprimento. O " +"comprimento máximo não é limitado pelo algoritmo SHAKE." -#: ../../library/hashlib.rst:245 +#: ../../library/hashlib.rst:243 msgid "" "Return the digest of the data passed to the :meth:`~hash.update` method so " "far. This is a bytes object of size *length* which may contain bytes in the " "whole range from 0 to 255." msgstr "" +"Retorna o resumo dos dados passados ​​ao método :meth:`~hash.update` até o " +"momento. Este é um objeto bytes de tamanho *length* que pode conter bytes em " +"todo o intervalo de 0 a 255." -#: ../../library/hashlib.rst:252 +#: ../../library/hashlib.rst:250 msgid "" "Like :meth:`digest` except the digest is returned as a string object of " "double length, containing only hexadecimal digits. This may be used to " "exchange the value in email or other non-binary environments." msgstr "" +"Similar a :meth:`digest`, exceto que o resumo é retornado como um objeto " +"string de comprimento duplo, contendo apenas dígitos hexadecimais. Isso pode " +"ser usado para trocar o valor em e-mails ou outros ambientes não binários." -#: ../../library/hashlib.rst:256 +#: ../../library/hashlib.rst:254 msgid "Example use:" -msgstr "" +msgstr "Exemplo de uso:" -#: ../../library/hashlib.rst:263 +#: ../../library/hashlib.rst:261 msgid "File hashing" -msgstr "" +msgstr "Hash de arquivo" -#: ../../library/hashlib.rst:265 +#: ../../library/hashlib.rst:263 msgid "" "The hashlib module provides a helper function for efficient hashing of a " "file or file-like object." msgstr "" +"O módulo hashlib fornece uma função auxiliar para hash eficiente de um " +"objeto arquivo ou similar." -#: ../../library/hashlib.rst:270 +#: ../../library/hashlib.rst:268 msgid "" "Return a digest object that has been updated with contents of file object." msgstr "" +"Retorna um objeto resumo que foi atualizado com o conteúdo do objeto arquivo." -#: ../../library/hashlib.rst:272 +#: ../../library/hashlib.rst:270 msgid "" "*fileobj* must be a file-like object opened for reading in binary mode. It " "accepts file objects from builtin :func:`open`, :class:`~io.BytesIO` " "instances, SocketIO objects from :meth:`socket.socket.makefile`, and " -"similar. The function may bypass Python's I/O and use the file descriptor " -"from :meth:`~io.IOBase.fileno` directly. *fileobj* must be assumed to be in " -"an unknown state after this function returns or raises. It is up to the " -"caller to close *fileobj*." +"similar. *fileobj* must be opened in blocking mode, otherwise a :exc:" +"`BlockingIOError` may be raised." +msgstr "" +"*fileobj* deve ser um objeto arquivo ou similar aberto para leitura em modo " +"binário. Ele aceita objetos arquivo da :func:`open` embutida, instâncias de :" +"class:`~io.BytesIO`, objetos SocketIO de :meth:`socket.socket.makefile` e " +"similares. *fileobj* deve ser aberto em modo bloqueante, caso contrário, uma " +"exceção :exc:`BlockingIOError` pode ser levantada." + +#: ../../library/hashlib.rst:276 +msgid "" +"The function may bypass Python's I/O and use the file descriptor from :meth:" +"`~io.IOBase.fileno` directly. *fileobj* must be assumed to be in an unknown " +"state after this function returns or raises. It is up to the caller to close " +"*fileobj*." msgstr "" +"A função pode ignorar a E/S do Python e usar o descritor de arquivo de :meth:" +"`~io.IOBase.fileno` diretamente. *fileobj* deve ser presumido como sendo um " +"estado desconhecido após o retorno ou o levantamento desta função. Cabe a " +"quem a chamou fechar *fileobj*." -#: ../../library/hashlib.rst:280 +#: ../../library/hashlib.rst:281 msgid "" "*digest* must either be a hash algorithm name as a *str*, a hash " "constructor, or a callable that returns a hash object." msgstr "" +"*digest* deve ser um nome de algoritmo de hash como *str*, um construtor de " +"hash ou um chamável que retorna um objeto de hash." -#: ../../library/hashlib.rst:283 +#: ../../library/hashlib.rst:284 msgid "Example:" msgstr "Exemplo:" -#: ../../library/hashlib.rst:306 -msgid "Key derivation" +#: ../../library/hashlib.rst:305 +msgid "" +"Now raises a :exc:`BlockingIOError` if the file is opened in blocking mode. " +"Previously, spurious null bytes were added to the digest." msgstr "" +"Agora levanta uma :exc:`BlockingIOError` se o arquivo for aberto em modo " +"bloqueante. Anteriormente, bytes nulos espúrios eram adicionados ao resumo." + +#: ../../library/hashlib.rst:311 +msgid "Key derivation" +msgstr "Derivação de chave" -#: ../../library/hashlib.rst:308 +#: ../../library/hashlib.rst:313 msgid "" "Key derivation and key stretching algorithms are designed for secure " "password hashing. Naive algorithms such as ``sha1(password)`` are not " @@ -334,14 +473,21 @@ msgid "" "be tunable, slow, and include a `salt `_." msgstr "" +"Algoritmos de alongamento de chave e derivação de chave são projetados para " +"criar hashes de senhas seguros. Algoritmos ingênuos como ``sha1(password)`` " +"não são resistentes a ataques de força bruta. Uma boa função de hashing de " +"senhas deve ser ajustável, lenta e incluir um `salt `_." -#: ../../library/hashlib.rst:316 +#: ../../library/hashlib.rst:321 msgid "" "The function provides PKCS#5 password-based key derivation function 2. It " "uses HMAC as pseudorandom function." msgstr "" +"A função fornece a função 2 de derivação de chave baseada em senha PKCS#5. " +"Ela usa HMAC como função pseudoaleatória." -#: ../../library/hashlib.rst:319 +#: ../../library/hashlib.rst:324 msgid "" "The string *hash_name* is the desired name of the hash digest algorithm for " "HMAC, e.g. 'sha1' or 'sha256'. *password* and *salt* are interpreted as " @@ -349,8 +495,13 @@ msgid "" "sensible length (e.g. 1024). *salt* should be about 16 or more bytes from a " "proper source, e.g. :func:`os.urandom`." msgstr "" +"A string *hash_name* é o nome desejado do algoritmo de resumo de hash para " +"HMAC, por exemplo, 'sha1' ou 'sha256'. *password* e *salt* são interpretados " +"como buffers de bytes. Aplicações e bibliotecas devem limitar *password* a " +"um comprimento razoável (por exemplo, 1024). *salt* deve ter cerca de 16 " +"bytes ou mais de uma fonte adequada, por exemplo, :func:`os.urandom`." -#: ../../library/hashlib.rst:325 +#: ../../library/hashlib.rst:330 msgid "" "The number of *iterations* should be chosen based on the hash algorithm and " "computing power. As of 2022, hundreds of thousands of iterations of SHA-256 " @@ -358,170 +509,196 @@ msgid "" "your application, read *Appendix A.2.2* of NIST-SP-800-132_. The answers on " "the `stackexchange pbkdf2 iterations question`_ explain in detail." msgstr "" +"O número de *iterations* deve ser escolhido com base no algoritmo de hash e " +"no poder computacional. A partir de 2022, centenas de milhares de iterações " +"do SHA-256 são sugeridas. Para entender por que e como escolher o que é " +"melhor para sua aplicação, leia o *Appendix A.2.2* do NIST-SP-800-132_. As " +"respostas à `pergunta sobre iterações de pbkdf2 no StackExchange`_ explicam " +"em detalhes." -#: ../../library/hashlib.rst:331 +#: ../../library/hashlib.rst:336 msgid "" "*dklen* is the length of the derived key in bytes. If *dklen* is ``None`` " "then the digest size of the hash algorithm *hash_name* is used, e.g. 64 for " "SHA-512." msgstr "" +"*dklen* é o comprimento da chave derivada em bytes. Se *dklen* for ``None``, " +"o tamanho do resumo do algoritmo de hash *hash_name* será usado, por " +"exemplo, 64 para SHA-512." -#: ../../library/hashlib.rst:340 +#: ../../library/hashlib.rst:345 msgid "Function only available when Python is compiled with OpenSSL." -msgstr "" +msgstr "Função disponível somente quando Python é compilado com OpenSSL." -#: ../../library/hashlib.rst:344 +#: ../../library/hashlib.rst:349 msgid "" "Function now only available when Python is built with OpenSSL. The slow pure " "Python implementation has been removed." msgstr "" +"Função agora disponível apenas quando o Python é criado com OpenSSL. A " +"implementação lenta do Python puro foi removida." -#: ../../library/hashlib.rst:350 +#: ../../library/hashlib.rst:355 msgid "" "The function provides scrypt password-based key derivation function as " "defined in :rfc:`7914`." msgstr "" +"A função fornece a função de derivação de chave baseada em senha scrypt, " +"conforme definido em :rfc:`7914`." -#: ../../library/hashlib.rst:353 +#: ../../library/hashlib.rst:358 msgid "" "*password* and *salt* must be :term:`bytes-like objects `. Applications and libraries should limit *password* to a sensible " "length (e.g. 1024). *salt* should be about 16 or more bytes from a proper " "source, e.g. :func:`os.urandom`." msgstr "" +"*password* e *salt* devem ser :term:`objetos bytes ou similar `. Aplicações e bibliotecas devem limitar *password* a um tamanho " +"razoável (por exemplo, 1024). *salt* deve ter cerca de 16 bytes ou mais de " +"uma fonte adequada, por exemplo, :func:`os.urandom`." -#: ../../library/hashlib.rst:358 +#: ../../library/hashlib.rst:363 msgid "" "*n* is the CPU/Memory cost factor, *r* the block size, *p* parallelization " "factor and *maxmem* limits memory (OpenSSL 1.1.0 defaults to 32 MiB). " "*dklen* is the length of the derived key in bytes." msgstr "" +"*n* é o fator de custo de CPU/memória, *r* o tamanho do bloco, *p* o fator " +"de paralelismo e *maxmem* limita a memória (o padrão do OpenSSL 1.1.0 é 32 " +"MiB). *dklen* é o comprimento da chave derivada em bytes." -#: ../../library/hashlib.rst:368 +#: ../../library/hashlib.rst:373 msgid "BLAKE2" -msgstr "" +msgstr "BLAKE2" -#: ../../library/hashlib.rst:375 +#: ../../library/hashlib.rst:380 msgid "" "BLAKE2_ is a cryptographic hash function defined in :rfc:`7693` that comes " "in two flavors:" msgstr "" +"BLAKE2_ é uma função hash criptográfica definida em :rfc:`7693` que vem em " +"dois sabores:" -#: ../../library/hashlib.rst:378 +#: ../../library/hashlib.rst:383 msgid "" "**BLAKE2b**, optimized for 64-bit platforms and produces digests of any size " "between 1 and 64 bytes," msgstr "" +"**BLAKE2b**, otimizado para plataformas de 64 bits e produz resumos de " +"qualquer tamanho entre 1 e 64 bytes," -#: ../../library/hashlib.rst:381 +#: ../../library/hashlib.rst:386 msgid "" "**BLAKE2s**, optimized for 8- to 32-bit platforms and produces digests of " "any size between 1 and 32 bytes." msgstr "" +"**BLAKE2s**, otimizado para plataformas de 8 a 32 bits e produz resumos de " +"qualquer tamanho entre 1 e 32 bytes." -#: ../../library/hashlib.rst:384 +#: ../../library/hashlib.rst:389 msgid "" "BLAKE2 supports **keyed mode** (a faster and simpler replacement for HMAC_), " "**salted hashing**, **personalization**, and **tree hashing**." msgstr "" -#: ../../library/hashlib.rst:387 +#: ../../library/hashlib.rst:392 msgid "" "Hash objects from this module follow the API of standard library's :mod:" "`hashlib` objects." msgstr "" -#: ../../library/hashlib.rst:392 +#: ../../library/hashlib.rst:397 msgid "Creating hash objects" msgstr "" -#: ../../library/hashlib.rst:394 +#: ../../library/hashlib.rst:399 msgid "New hash objects are created by calling constructor functions:" msgstr "" -#: ../../library/hashlib.rst:408 +#: ../../library/hashlib.rst:413 msgid "" "These functions return the corresponding hash objects for calculating " "BLAKE2b or BLAKE2s. They optionally take these general parameters:" msgstr "" -#: ../../library/hashlib.rst:411 +#: ../../library/hashlib.rst:416 msgid "" "*data*: initial chunk of data to hash, which must be :term:`bytes-like " "object`. It can be passed only as positional argument." msgstr "" -#: ../../library/hashlib.rst:414 +#: ../../library/hashlib.rst:419 msgid "*digest_size*: size of output digest in bytes." msgstr "" -#: ../../library/hashlib.rst:416 +#: ../../library/hashlib.rst:421 msgid "" "*key*: key for keyed hashing (up to 64 bytes for BLAKE2b, up to 32 bytes for " "BLAKE2s)." msgstr "" -#: ../../library/hashlib.rst:419 +#: ../../library/hashlib.rst:424 msgid "" "*salt*: salt for randomized hashing (up to 16 bytes for BLAKE2b, up to 8 " "bytes for BLAKE2s)." msgstr "" -#: ../../library/hashlib.rst:422 +#: ../../library/hashlib.rst:427 msgid "" "*person*: personalization string (up to 16 bytes for BLAKE2b, up to 8 bytes " "for BLAKE2s)." msgstr "" -#: ../../library/hashlib.rst:425 +#: ../../library/hashlib.rst:430 msgid "The following table shows limits for general parameters (in bytes):" msgstr "" -#: ../../library/hashlib.rst:428 +#: ../../library/hashlib.rst:433 msgid "Hash" msgstr "" -#: ../../library/hashlib.rst:428 +#: ../../library/hashlib.rst:433 msgid "digest_size" msgstr "digest_size" -#: ../../library/hashlib.rst:428 +#: ../../library/hashlib.rst:433 msgid "len(key)" msgstr "" -#: ../../library/hashlib.rst:428 +#: ../../library/hashlib.rst:433 msgid "len(salt)" msgstr "" -#: ../../library/hashlib.rst:428 +#: ../../library/hashlib.rst:433 msgid "len(person)" msgstr "" -#: ../../library/hashlib.rst:430 +#: ../../library/hashlib.rst:435 msgid "BLAKE2b" msgstr "" -#: ../../library/hashlib.rst:430 +#: ../../library/hashlib.rst:435 msgid "64" msgstr "" -#: ../../library/hashlib.rst:430 +#: ../../library/hashlib.rst:435 msgid "16" msgstr "" -#: ../../library/hashlib.rst:431 +#: ../../library/hashlib.rst:436 msgid "BLAKE2s" msgstr "" -#: ../../library/hashlib.rst:431 +#: ../../library/hashlib.rst:436 msgid "32" msgstr "32" -#: ../../library/hashlib.rst:431 +#: ../../library/hashlib.rst:436 msgid "8" msgstr "8" -#: ../../library/hashlib.rst:436 +#: ../../library/hashlib.rst:441 msgid "" "BLAKE2 specification defines constant lengths for salt and personalization " "parameters, however, for convenience, this implementation accepts byte " @@ -531,94 +708,94 @@ msgid "" "the case for *key*.)" msgstr "" -#: ../../library/hashlib.rst:443 +#: ../../library/hashlib.rst:448 msgid "These sizes are available as module `constants`_ described below." msgstr "" -#: ../../library/hashlib.rst:445 +#: ../../library/hashlib.rst:450 msgid "" "Constructor functions also accept the following tree hashing parameters:" msgstr "" -#: ../../library/hashlib.rst:447 +#: ../../library/hashlib.rst:452 msgid "*fanout*: fanout (0 to 255, 0 if unlimited, 1 in sequential mode)." msgstr "" -#: ../../library/hashlib.rst:449 +#: ../../library/hashlib.rst:454 msgid "" "*depth*: maximal depth of tree (1 to 255, 255 if unlimited, 1 in sequential " "mode)." msgstr "" -#: ../../library/hashlib.rst:452 +#: ../../library/hashlib.rst:457 msgid "" "*leaf_size*: maximal byte length of leaf (0 to ``2**32-1``, 0 if unlimited " "or in sequential mode)." msgstr "" -#: ../../library/hashlib.rst:455 +#: ../../library/hashlib.rst:460 msgid "" "*node_offset*: node offset (0 to ``2**64-1`` for BLAKE2b, 0 to ``2**48-1`` " "for BLAKE2s, 0 for the first, leftmost, leaf, or in sequential mode)." msgstr "" -#: ../../library/hashlib.rst:458 +#: ../../library/hashlib.rst:463 msgid "" "*node_depth*: node depth (0 to 255, 0 for leaves, or in sequential mode)." msgstr "" -#: ../../library/hashlib.rst:460 +#: ../../library/hashlib.rst:465 msgid "" "*inner_size*: inner digest size (0 to 64 for BLAKE2b, 0 to 32 for BLAKE2s, 0 " "in sequential mode)." msgstr "" -#: ../../library/hashlib.rst:463 +#: ../../library/hashlib.rst:468 msgid "" "*last_node*: boolean indicating whether the processed node is the last one " "(``False`` for sequential mode)." msgstr "" -#: ../../library/hashlib.rst:466 +#: ../../library/hashlib.rst:471 msgid "Explanation of tree mode parameters." msgstr "" -#: ../../library/hashlib.rst:470 +#: ../../library/hashlib.rst:475 msgid "" "See section 2.10 in `BLAKE2 specification `_ for comprehensive review of tree hashing." msgstr "" -#: ../../library/hashlib.rst:476 +#: ../../library/hashlib.rst:481 msgid "Constants" msgstr "Constantes" -#: ../../library/hashlib.rst:481 +#: ../../library/hashlib.rst:486 msgid "Salt length (maximum length accepted by constructors)." msgstr "" -#: ../../library/hashlib.rst:487 +#: ../../library/hashlib.rst:492 msgid "" "Personalization string length (maximum length accepted by constructors)." msgstr "" -#: ../../library/hashlib.rst:493 +#: ../../library/hashlib.rst:498 msgid "Maximum key size." msgstr "" -#: ../../library/hashlib.rst:499 +#: ../../library/hashlib.rst:504 msgid "Maximum digest size that the hash function can output." msgstr "" -#: ../../library/hashlib.rst:503 +#: ../../library/hashlib.rst:508 msgid "Examples" msgstr "Exemplos" -#: ../../library/hashlib.rst:506 +#: ../../library/hashlib.rst:511 msgid "Simple hashing" msgstr "" -#: ../../library/hashlib.rst:508 +#: ../../library/hashlib.rst:513 msgid "" "To calculate hash of some data, you should first construct a hash object by " "calling the appropriate constructor function (:func:`blake2b` or :func:" @@ -627,41 +804,41 @@ msgid "" "`~hash.digest` (or :meth:`~hash.hexdigest` for hex-encoded string)." msgstr "" -#: ../../library/hashlib.rst:521 +#: ../../library/hashlib.rst:526 msgid "" "As a shortcut, you can pass the first chunk of data to update directly to " "the constructor as the positional argument:" msgstr "" -#: ../../library/hashlib.rst:528 +#: ../../library/hashlib.rst:533 msgid "" "You can call :meth:`hash.update` as many times as you need to iteratively " "update the hash:" msgstr "" -#: ../../library/hashlib.rst:542 +#: ../../library/hashlib.rst:547 msgid "Using different digest sizes" msgstr "" -#: ../../library/hashlib.rst:544 +#: ../../library/hashlib.rst:549 msgid "" "BLAKE2 has configurable size of digests up to 64 bytes for BLAKE2b and up to " "32 bytes for BLAKE2s. For example, to replace SHA-1 with BLAKE2b without " "changing the size of output, we can tell BLAKE2b to produce 20-byte digests:" msgstr "" -#: ../../library/hashlib.rst:558 +#: ../../library/hashlib.rst:563 msgid "" "Hash objects with different digest sizes have completely different outputs " "(shorter hashes are *not* prefixes of longer hashes); BLAKE2b and BLAKE2s " "produce different outputs even if the output length is the same:" msgstr "" -#: ../../library/hashlib.rst:574 +#: ../../library/hashlib.rst:579 msgid "Keyed hashing" msgstr "" -#: ../../library/hashlib.rst:576 +#: ../../library/hashlib.rst:581 msgid "" "Keyed hashing can be used for authentication as a faster and simpler " "replacement for `Hash-based message authentication code >> from hashlib import blake2b\n" +">>> h = blake2b(key=b'pseudorandom key', digest_size=16)\n" +">>> h.update(b'message data')\n" +">>> h.hexdigest()\n" +"'3d363ff7401e02026f4a4687d4863ced'" +msgstr "" + +#: ../../library/hashlib.rst:597 msgid "" "As a practical example, a web application can symmetrically sign cookies " "sent to users and later verify them to make sure they weren't tampered with::" msgstr "" -#: ../../library/hashlib.rst:621 +#: ../../library/hashlib.rst:600 +msgid "" +">>> from hashlib import blake2b\n" +">>> from hmac import compare_digest\n" +">>>\n" +">>> SECRET_KEY = b'pseudorandomly generated server secret key'\n" +">>> AUTH_SIZE = 16\n" +">>>\n" +">>> def sign(cookie):\n" +"... h = blake2b(digest_size=AUTH_SIZE, key=SECRET_KEY)\n" +"... h.update(cookie)\n" +"... return h.hexdigest().encode('utf-8')\n" +">>>\n" +">>> def verify(cookie, sig):\n" +"... good_sig = sign(cookie)\n" +"... return compare_digest(good_sig, sig)\n" +">>>\n" +">>> cookie = b'user-alice'\n" +">>> sig = sign(cookie)\n" +">>> print(\"{0},{1}\".format(cookie.decode('utf-8'), sig))\n" +"user-alice,b'43b3c982cf697e0c5ab22172d1ca7421'\n" +">>> verify(cookie, sig)\n" +"True\n" +">>> verify(b'user-bob', sig)\n" +"False\n" +">>> verify(cookie, b'0102030405060708090a0b0c0d0e0f00')\n" +"False" +msgstr "" + +#: ../../library/hashlib.rst:626 msgid "" "Even though there's a native keyed hashing mode, BLAKE2 can, of course, be " "used in HMAC construction with :mod:`hmac` module::" msgstr "" -#: ../../library/hashlib.rst:632 +#: ../../library/hashlib.rst:629 +msgid "" +">>> import hmac, hashlib\n" +">>> m = hmac.new(b'secret key', digestmod=hashlib.blake2s)\n" +">>> m.update(b'message')\n" +">>> m.hexdigest()\n" +"'e3c8102868d28b5ff85fc35dda07329970d1a01e273c37481326fe0c861c8142'" +msgstr "" + +#: ../../library/hashlib.rst:637 msgid "Randomized hashing" msgstr "" -#: ../../library/hashlib.rst:634 +#: ../../library/hashlib.rst:639 msgid "" "By setting *salt* parameter users can introduce randomization to the hash " "function. Randomized hashing is useful for protecting against collision " "attacks on the hash function used in digital signatures." msgstr "" -#: ../../library/hashlib.rst:638 +#: ../../library/hashlib.rst:643 msgid "" "Randomized hashing is designed for situations where one party, the message " "preparer, generates all or part of a message to be signed by a second party, " @@ -719,19 +943,19 @@ msgid "" "when all portions of the message are prepared by the signer." msgstr "" -#: ../../library/hashlib.rst:657 +#: ../../library/hashlib.rst:662 msgid "" "(`NIST SP-800-106 \"Randomized Hashing for Digital Signatures\" `_)" +"csrc.nist.gov/pubs/sp/800/106/final>`_)" msgstr "" -#: ../../library/hashlib.rst:660 +#: ../../library/hashlib.rst:665 msgid "" "In BLAKE2 the salt is processed as a one-time input to the hash function " "during initialization, rather than as an input to each compression function." msgstr "" -#: ../../library/hashlib.rst:665 +#: ../../library/hashlib.rst:670 msgid "" "*Salted hashing* (or just hashing) with BLAKE2 or any other general-purpose " "cryptographic hash function, such as SHA-256, is not suitable for hashing " @@ -739,18 +963,18 @@ msgid "" "information." msgstr "" -#: ../../library/hashlib.rst:688 +#: ../../library/hashlib.rst:693 msgid "Personalization" msgstr "" -#: ../../library/hashlib.rst:690 +#: ../../library/hashlib.rst:695 msgid "" "Sometimes it is useful to force hash function to produce different digests " "for the same input for different purposes. Quoting the authors of the Skein " "hash function:" msgstr "" -#: ../../library/hashlib.rst:694 +#: ../../library/hashlib.rst:699 msgid "" "We recommend that all application designers seriously consider doing this; " "we have seen many protocols where a hash that is computed in one part of the " @@ -760,41 +984,92 @@ msgid "" "hash function used in the protocol summarily stops this type of attack." msgstr "" -#: ../../library/hashlib.rst:701 +#: ../../library/hashlib.rst:706 msgid "" "(`The Skein Hash Function Family `_, p. 21)" msgstr "" -#: ../../library/hashlib.rst:705 +#: ../../library/hashlib.rst:710 msgid "BLAKE2 can be personalized by passing bytes to the *person* argument::" msgstr "" -#: ../../library/hashlib.rst:719 +#: ../../library/hashlib.rst:712 +msgid "" +">>> from hashlib import blake2b\n" +">>> FILES_HASH_PERSON = b'MyApp Files Hash'\n" +">>> BLOCK_HASH_PERSON = b'MyApp Block Hash'\n" +">>> h = blake2b(digest_size=32, person=FILES_HASH_PERSON)\n" +">>> h.update(b'the same content')\n" +">>> h.hexdigest()\n" +"'20d9cd024d4fb086aae819a1432dd2466de12947831b75c5a30cf2676095d3b4'\n" +">>> h = blake2b(digest_size=32, person=BLOCK_HASH_PERSON)\n" +">>> h.update(b'the same content')\n" +">>> h.hexdigest()\n" +"'cf68fb5761b9c44e7878bfb2c4c9aea52264a80b75005e65619778de59f383a3'" +msgstr "" + +#: ../../library/hashlib.rst:724 msgid "" "Personalization together with the keyed mode can also be used to derive " "different keys from a single one." msgstr "" -#: ../../library/hashlib.rst:733 +#: ../../library/hashlib.rst:738 msgid "Tree mode" msgstr "Modo árvore" -#: ../../library/hashlib.rst:735 +#: ../../library/hashlib.rst:740 msgid "Here's an example of hashing a minimal tree with two leaf nodes::" msgstr "" -#: ../../library/hashlib.rst:741 +#: ../../library/hashlib.rst:742 +msgid "" +" 10\n" +" / \\\n" +"00 01" +msgstr "" + +#: ../../library/hashlib.rst:746 msgid "" "This example uses 64-byte internal digests, and returns the 32-byte final " "digest::" msgstr "" -#: ../../library/hashlib.rst:771 +#: ../../library/hashlib.rst:749 +msgid "" +">>> from hashlib import blake2b\n" +">>>\n" +">>> FANOUT = 2\n" +">>> DEPTH = 2\n" +">>> LEAF_SIZE = 4096\n" +">>> INNER_SIZE = 64\n" +">>>\n" +">>> buf = bytearray(6000)\n" +">>>\n" +">>> # Left leaf\n" +"... h00 = blake2b(buf[0:LEAF_SIZE], fanout=FANOUT, depth=DEPTH,\n" +"... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,\n" +"... node_offset=0, node_depth=0, last_node=False)\n" +">>> # Right leaf\n" +"... h01 = blake2b(buf[LEAF_SIZE:], fanout=FANOUT, depth=DEPTH,\n" +"... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,\n" +"... node_offset=1, node_depth=0, last_node=True)\n" +">>> # Root node\n" +"... h10 = blake2b(digest_size=32, fanout=FANOUT, depth=DEPTH,\n" +"... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,\n" +"... node_offset=0, node_depth=1, last_node=True)\n" +">>> h10.update(h00.digest())\n" +">>> h10.update(h01.digest())\n" +">>> h10.hexdigest()\n" +"'3ad2a9b37c6070e374c7a8c508fe20ca86b6ed54e286e93a0318e95e881db5aa'" +msgstr "" + +#: ../../library/hashlib.rst:776 msgid "Credits" msgstr "" -#: ../../library/hashlib.rst:773 +#: ../../library/hashlib.rst:778 msgid "" "BLAKE2_ was designed by *Jean-Philippe Aumasson*, *Samuel Neves*, *Zooko " "Wilcox-O'Hearn*, and *Christian Winnerlein* based on SHA-3_ finalist BLAKE_ " @@ -802,118 +1077,118 @@ msgid "" "*Raphael C.-W. Phan*." msgstr "" -#: ../../library/hashlib.rst:778 +#: ../../library/hashlib.rst:783 msgid "" "It uses core algorithm from ChaCha_ cipher designed by *Daniel J. " "Bernstein*." msgstr "" -#: ../../library/hashlib.rst:780 +#: ../../library/hashlib.rst:785 msgid "" "The stdlib implementation is based on pyblake2_ module. It was written by " "*Dmitry Chestnykh* based on C implementation written by *Samuel Neves*. The " "documentation was copied from pyblake2_ and written by *Dmitry Chestnykh*." msgstr "" -#: ../../library/hashlib.rst:784 +#: ../../library/hashlib.rst:789 msgid "The C code was partly rewritten for Python by *Christian Heimes*." msgstr "" -#: ../../library/hashlib.rst:786 +#: ../../library/hashlib.rst:791 msgid "" "The following public domain dedication applies for both C hash function " "implementation, extension code, and this documentation:" msgstr "" -#: ../../library/hashlib.rst:789 +#: ../../library/hashlib.rst:794 msgid "" "To the extent possible under law, the author(s) have dedicated all copyright " "and related and neighboring rights to this software to the public domain " "worldwide. This software is distributed without any warranty." msgstr "" -#: ../../library/hashlib.rst:793 +#: ../../library/hashlib.rst:798 msgid "" "You should have received a copy of the CC0 Public Domain Dedication along " "with this software. If not, see https://creativecommons.org/publicdomain/" "zero/1.0/." msgstr "" -#: ../../library/hashlib.rst:797 +#: ../../library/hashlib.rst:802 msgid "" "The following people have helped with development or contributed their " "changes to the project and the public domain according to the Creative " "Commons Public Domain Dedication 1.0 Universal:" msgstr "" -#: ../../library/hashlib.rst:801 +#: ../../library/hashlib.rst:806 msgid "*Alexandr Sokolovskiy*" msgstr "" -#: ../../library/hashlib.rst:821 +#: ../../library/hashlib.rst:827 msgid "Module :mod:`hmac`" msgstr "" -#: ../../library/hashlib.rst:822 +#: ../../library/hashlib.rst:828 msgid "A module to generate message authentication codes using hashes." msgstr "" -#: ../../library/hashlib.rst:824 +#: ../../library/hashlib.rst:830 msgid "Module :mod:`base64`" msgstr "Módulo :mod:`base64`" -#: ../../library/hashlib.rst:825 +#: ../../library/hashlib.rst:831 msgid "Another way to encode binary hashes for non-binary environments." msgstr "" -#: ../../library/hashlib.rst:827 +#: ../../library/hashlib.rst:833 msgid "https://nvlpubs.nist.gov/nistpubs/fips/nist.fips.180-4.pdf" msgstr "" -#: ../../library/hashlib.rst:828 +#: ../../library/hashlib.rst:834 msgid "The FIPS 180-4 publication on Secure Hash Algorithms." msgstr "" -#: ../../library/hashlib.rst:830 -msgid "https://csrc.nist.gov/publications/detail/fips/202/final" +#: ../../library/hashlib.rst:836 +msgid "https://csrc.nist.gov/pubs/fips/202/final" msgstr "" -#: ../../library/hashlib.rst:831 +#: ../../library/hashlib.rst:837 msgid "The FIPS 202 publication on the SHA-3 Standard." msgstr "" -#: ../../library/hashlib.rst:833 +#: ../../library/hashlib.rst:839 msgid "https://www.blake2.net/" msgstr "" -#: ../../library/hashlib.rst:834 +#: ../../library/hashlib.rst:840 msgid "Official BLAKE2 website." msgstr "" -#: ../../library/hashlib.rst:836 +#: ../../library/hashlib.rst:842 msgid "https://en.wikipedia.org/wiki/Cryptographic_hash_function" msgstr "" -#: ../../library/hashlib.rst:837 +#: ../../library/hashlib.rst:843 msgid "" "Wikipedia article with information on which algorithms have known issues and " "what that means regarding their use." msgstr "" -#: ../../library/hashlib.rst:840 +#: ../../library/hashlib.rst:846 msgid "https://www.ietf.org/rfc/rfc8018.txt" msgstr "" -#: ../../library/hashlib.rst:841 +#: ../../library/hashlib.rst:847 msgid "PKCS #5: Password-Based Cryptography Specification Version 2.1" msgstr "" -#: ../../library/hashlib.rst:843 +#: ../../library/hashlib.rst:849 msgid "" "https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf" msgstr "" -#: ../../library/hashlib.rst:844 +#: ../../library/hashlib.rst:850 msgid "NIST Recommendation for Password-Based Key Derivation." msgstr "" @@ -927,14 +1202,14 @@ msgid "" "Shake, Blake2" msgstr "" -#: ../../library/hashlib.rst:55 +#: ../../library/hashlib.rst:53 msgid "OpenSSL" msgstr "OpenSSL" -#: ../../library/hashlib.rst:55 +#: ../../library/hashlib.rst:53 msgid "(use in module hashlib)" msgstr "" -#: ../../library/hashlib.rst:372 +#: ../../library/hashlib.rst:377 msgid "blake2b, blake2s" -msgstr "" +msgstr "blake2b, blake2s" diff --git a/library/heapq.po b/library/heapq.po index b717c8d32..ff4fb5ac1 100644 --- a/library/heapq.po +++ b/library/heapq.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-05 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 01:07+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -281,6 +280,26 @@ msgstr "" "implementado colocando todos os valores em um heap e, em seguida, retirando " "os menores valores, um de cada vez::" +#: ../../library/heapq.rst:144 +msgid "" +">>> def heapsort(iterable):\n" +"... h = []\n" +"... for value in iterable:\n" +"... heappush(h, value)\n" +"... return [heappop(h) for i in range(len(h))]\n" +"...\n" +">>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])\n" +"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" +msgstr "" +">>> def heapsort(iterable):\n" +"... h = []\n" +"... for value in iterable:\n" +"... heappush(h, value)\n" +"... return [heappop(h) for i in range(len(h))]\n" +"...\n" +">>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])\n" +"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" + #: ../../library/heapq.rst:153 msgid "" "This is similar to ``sorted(iterable)``, but unlike :func:`sorted`, this " @@ -298,6 +317,24 @@ msgstr "" "comparação (como prioridades de tarefas) juntamente com o registro principal " "que está sendo rastreado::" +#: ../../library/heapq.rst:159 +msgid "" +">>> h = []\n" +">>> heappush(h, (5, 'write code'))\n" +">>> heappush(h, (7, 'release product'))\n" +">>> heappush(h, (1, 'write spec'))\n" +">>> heappush(h, (3, 'create tests'))\n" +">>> heappop(h)\n" +"(1, 'write spec')" +msgstr "" +">>> h = []\n" +">>> heappush(h, (5, 'write code'))\n" +">>> heappush(h, (7, 'release product'))\n" +">>> heappush(h, (1, 'write spec'))\n" +">>> heappush(h, (3, 'create tests'))\n" +">>> heappop(h)\n" +"(1, 'write spec')" + #: ../../library/heapq.rst:169 msgid "Priority Queue Implementation Notes" msgstr "Notas de implementação da fila de prioridade" @@ -368,6 +405,24 @@ msgstr "" "Outra solução para o problema de tarefas não comparáveis é criar uma classe " "wrapper que ignore o item da tarefa e compare apenas o campo de prioridade:" +#: ../../library/heapq.rst:195 +msgid "" +"from dataclasses import dataclass, field\n" +"from typing import Any\n" +"\n" +"@dataclass(order=True)\n" +"class PrioritizedItem:\n" +" priority: int\n" +" item: Any=field(compare=False)" +msgstr "" +"from dataclasses import dataclass, field\n" +"from typing import Any\n" +"\n" +"@dataclass(order=True)\n" +"class PrioritizedItem:\n" +" priority: int\n" +" item: Any=field(compare=False)" + #: ../../library/heapq.rst:203 msgid "" "The remaining challenges revolve around finding a pending task and making " @@ -389,6 +444,67 @@ msgstr "" "entrada como removida e adicionar uma nova entrada com a prioridade " "revisada::" +#: ../../library/heapq.rst:211 +msgid "" +"pq = [] # list of entries arranged in a heap\n" +"entry_finder = {} # mapping of tasks to entries\n" +"REMOVED = '' # placeholder for a removed task\n" +"counter = itertools.count() # unique sequence count\n" +"\n" +"def add_task(task, priority=0):\n" +" 'Add a new task or update the priority of an existing task'\n" +" if task in entry_finder:\n" +" remove_task(task)\n" +" count = next(counter)\n" +" entry = [priority, count, task]\n" +" entry_finder[task] = entry\n" +" heappush(pq, entry)\n" +"\n" +"def remove_task(task):\n" +" 'Mark an existing task as REMOVED. Raise KeyError if not found.'\n" +" entry = entry_finder.pop(task)\n" +" entry[-1] = REMOVED\n" +"\n" +"def pop_task():\n" +" 'Remove and return the lowest priority task. Raise KeyError if empty.'\n" +" while pq:\n" +" priority, count, task = heappop(pq)\n" +" if task is not REMOVED:\n" +" del entry_finder[task]\n" +" return task\n" +" raise KeyError('pop from an empty priority queue')" +msgstr "" +"pq = [] # lista de entradas organizadas em uma heap\n" +"entry_finder = {} # mapeamentos de tarefas para entradas\n" +"REMOVED = '' # espaço reservado para uma tarefa removida\n" +"counter = itertools.count() # contagem de sequência única\n" +"\n" +"def add_task(task, priority=0):\n" +" 'Adiciona uma nova tarefa ou atualiza a prioridade de uma tarefa " +"existente'\n" +" if task in entry_finder:\n" +" remove_task(task)\n" +" count = next(counter)\n" +" entry = [priority, count, task]\n" +" entry_finder[task] = entry\n" +" heappush(pq, entry)\n" +"\n" +"def remove_task(task):\n" +" 'Marca uma tarefa existente com REMOVED (removida). Levanta KeyError se " +"não encontrada.'\n" +" entry = entry_finder.pop(task)\n" +" entry[-1] = REMOVED\n" +"\n" +"def pop_task():\n" +" 'Remove e retorna a tarefa de mais baixa prioridade. Levanta KeyError se " +"vazio.'\n" +" while pq:\n" +" priority, count, task = heappop(pq)\n" +" if task is not REMOVED:\n" +" del entry_finder[task]\n" +" return task\n" +" raise KeyError('pop from an empty priority queue')" + #: ../../library/heapq.rst:241 msgid "Theory" msgstr "Teoria" @@ -413,6 +529,28 @@ msgstr "" "O estranho invariante acima pretende ser uma representação de memória " "eficiente para um torneio. Os números abaixo são *k*, não ``a[k]``::" +#: ../../library/heapq.rst:251 +msgid "" +" 0\n" +"\n" +" 1 2\n" +"\n" +" 3 4 5 6\n" +"\n" +" 7 8 9 10 11 12 13 14\n" +"\n" +"15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30" +msgstr "" +" 0\n" +"\n" +" 1 2\n" +"\n" +" 3 4 5 6\n" +"\n" +" 7 8 9 10 11 12 13 14\n" +"\n" +"15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30" + #: ../../library/heapq.rst:261 msgid "" "In the tree above, each cell *k* is topping ``2*k+1`` and ``2*k+2``. In a " diff --git a/library/hmac.po b/library/hmac.po index a03334ae8..4cdf8a294 100644 --- a/library/hmac.po +++ b/library/hmac.po @@ -1,32 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:07+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/hmac.rst:2 msgid ":mod:`!hmac` --- Keyed-Hashing for Message Authentication" -msgstr "" +msgstr ":mod:`!hmac` --- Código de autenticação de mensagem com chave hash" #: ../../library/hmac.rst:10 msgid "**Source code:** :source:`Lib/hmac.py`" @@ -35,6 +34,8 @@ msgstr "**Código-fonte:** :source:`Lib/hmac.py`" #: ../../library/hmac.rst:14 msgid "This module implements the HMAC algorithm as described by :rfc:`2104`." msgstr "" +"Este módulo implementa o algoritmo HMAC, abreviação de *hash-based message " +"authentication code*, conforme descrito por :rfc:`2104`." #: ../../library/hmac.rst:19 msgid "" @@ -44,6 +45,11 @@ msgid "" "object to use. It may be any name suitable to :func:`hashlib.new`. Despite " "its argument position, it is required." msgstr "" +"Retorna um novo objeto hmac. *key* é um objeto bytes ou bytearray que " +"fornece a chave secreta. Se *msg* estiver presente, a chamada de método " +"``update(msg)`` é feita. *digestmod* é o nome do resumo, construtor do " +"resumo ou módulo para o objeto HMAC usar. Pode ser qualquer nome adequado " +"para :func:`hashlib.new`. Apesar da posição do argumento, é obrigatório." #: ../../library/hmac.rst:25 msgid "" @@ -51,12 +57,17 @@ msgid "" "of any type supported by :mod:`hashlib`. Parameter *digestmod* can be the " "name of a hash algorithm." msgstr "" +"O parâmetro *key* pode ser um objeto bytes ou bytearray. O parâmetro *msg* " +"pode ser de qualquer tipo suportado por :mod:`hashlib`. O parâmetro " +"*digestmod* pode ser o nome de um algoritmo hash." #: ../../library/hmac.rst:30 msgid "" "The *digestmod* argument is now required. Pass it as a keyword argument to " "avoid awkwardness when you do not have an initial *msg*." msgstr "" +"O argumento *digestmod* agora é obrigatório. Passe-o como um argumento " +"nomeado para evitar constrangimentos quando você não tiver uma *msg* inicial." #: ../../library/hmac.rst:37 msgid "" @@ -66,6 +77,11 @@ msgid "" "The parameters *key*, *msg*, and *digest* have the same meaning as in :func:" "`~hmac.new`." msgstr "" +"Retorna o resumo de *msg* para o segredo *key* e *digest* fornecidos. A " +"função equivale a ``HMAC(key, msg, digest).digest()``, mas usa uma " +"implementação C otimizada ou inline, que é mais rápida para mensagens que " +"cabem na memória. Os parâmetros *key*, *msg* e *digest* têm o mesmo " +"significado que em :func:`~hmac.new`." #: ../../library/hmac.rst:43 msgid "" @@ -73,10 +89,13 @@ msgid "" "when *digest* is a string and name of a digest algorithm, which is supported " "by OpenSSL." msgstr "" +"Detalhe da implementação do CPython: a implementação otimizada do C é usada " +"somente quando *digest* é uma string e o nome de um algoritmo de resumo, que " +"é suportado pelo OpenSSL." #: ../../library/hmac.rst:50 msgid "An HMAC object has the following methods:" -msgstr "" +msgstr "Um objeto HMAC tem os seguintes métodos:" #: ../../library/hmac.rst:54 msgid "" @@ -84,10 +103,14 @@ msgid "" "single call with the concatenation of all the arguments: ``m.update(a); m." "update(b)`` is equivalent to ``m.update(a + b)``." msgstr "" +"Atualiza o objeto hmac com *msg*. Chamadas repetidas são equivalentes a uma " +"única chamada com a concatenação de todos os argumentos: ``m.update(a); m." +"update(b)`` equivale a ``m.update(a + b)``." #: ../../library/hmac.rst:58 msgid "Parameter *msg* can be of any type supported by :mod:`hashlib`." msgstr "" +"O parâmetro *msg* pode ser de qualquer tipo suportado por :mod:`hashlib`." #: ../../library/hmac.rst:64 msgid "" @@ -96,6 +119,10 @@ msgid "" "given to the constructor. It may contain non-ASCII bytes, including NUL " "bytes." msgstr "" +"Retorna o resumo dos bytes passados para o método :meth:`update` até o " +"momento. Este objeto bytes terá o mesmo comprimento que o *digest_size* do " +"resumo dado ao construtor. Ele pode conter bytes não-ASCII, incluindo bytes " +"NUL." #: ../../library/hmac.rst:71 msgid "" @@ -104,6 +131,10 @@ msgid "" "`compare_digest` function instead of the ``==`` operator to reduce the " "vulnerability to timing attacks." msgstr "" +"Ao comparar a saída de :meth:`digest` com um resumo fornecido externamente " +"durante uma rotina de verificação, é recomendável usar a função :func:" +"`compare_digest` em vez do operador ``==`` para reduzir a vulnerabilidade a " +"ataques de temporização." #: ../../library/hmac.rst:79 msgid "" @@ -111,6 +142,10 @@ msgid "" "length containing only hexadecimal digits. This may be used to exchange the " "value safely in email or other non-binary environments." msgstr "" +"Como :meth:`digest` exceto que o resumo é retornado como uma string com o " +"dobro do comprimento contendo apenas dígitos hexadecimais. Isso pode ser " +"usado para trocar o valor com segurança em e-mail ou outros ambientes não " +"binários." #: ../../library/hmac.rst:85 msgid "" @@ -119,6 +154,10 @@ msgid "" "`compare_digest` function instead of the ``==`` operator to reduce the " "vulnerability to timing attacks." msgstr "" +"Ao comparar a saída de :meth:`hexdigest` com um resumo fornecido " +"externamente durante uma rotina de verificação, é recomendável usar a " +"função :func:`compare_digest` em vez do operador ``==`` para reduzir a " +"vulnerabilidade a ataques de temporização." #: ../../library/hmac.rst:93 msgid "" @@ -126,28 +165,35 @@ msgid "" "efficiently compute the digests of strings that share a common initial " "substring." msgstr "" +"Retorna uma cópia (\"clone\") do objeto hmac. Isso pode ser usado para " +"calcular eficientemente os resumos de strings que compartilham uma substring " +"inicial comum." #: ../../library/hmac.rst:97 msgid "A hash object has the following attributes:" -msgstr "" +msgstr "Um objeto hash tem os seguintes atributos:" #: ../../library/hmac.rst:101 msgid "The size of the resulting HMAC digest in bytes." -msgstr "" +msgstr "O tamanho do resumo HMAC resultante em bytes." #: ../../library/hmac.rst:105 msgid "The internal block size of the hash algorithm in bytes." -msgstr "" +msgstr "O tamanho do bloco interna do algoritmo de hash em bytes." #: ../../library/hmac.rst:111 msgid "The canonical name of this HMAC, always lowercase, e.g. ``hmac-md5``." msgstr "" +"O nome canônico deste HMAC, sempre em letras minúsculas, por exemplo, ``hmac-" +"md5``." #: ../../library/hmac.rst:116 msgid "" "Removed the undocumented attributes ``HMAC.digest_cons``, ``HMAC.inner``, " "and ``HMAC.outer``." msgstr "" +"Foram removidos os atributos não documentados ``HMAC.digest_cons``, ``HMAC." +"inner`` e ``HMAC.outer``." #: ../../library/hmac.rst:120 msgid "This module also provides the following helper function:" @@ -161,6 +207,11 @@ msgid "" "either :class:`str` (ASCII only, as e.g. returned by :meth:`HMAC." "hexdigest`), or a :term:`bytes-like object`." msgstr "" +"Retorna ``a == b``. Esta função usa uma abordagem projetada para evitar " +"análise de tempo evitando comportamento de curto-circuito baseado em " +"conteúdo, tornando-a apropriada para criptografia. *a* e *b* devem ser ambos " +"do mesmo tipo: :class:`str` (somente ASCII, como, por exemplo, retornado " +"por :meth:`HMAC.hexdigest`), ou um :term:`objeto bytes ou similar`." #: ../../library/hmac.rst:132 msgid "" @@ -168,11 +219,15 @@ msgid "" "attack could theoretically reveal information about the types and lengths of " "*a* and *b*—but not their values." msgstr "" +"Se *a* e *b* tiverem comprimentos diferentes, ou se ocorrer um erro, um " +"ataque de temporização poderia teoricamente revelar informações sobre os " +"tipos e comprimentos de *a* e *b*, mas não seus valores." #: ../../library/hmac.rst:140 msgid "" "The function uses OpenSSL's ``CRYPTO_memcmp()`` internally when available." msgstr "" +"A função usa ``CRYPTO_memcmp()`` do OpenSSL internamente quando disponível." #: ../../library/hmac.rst:146 msgid "Module :mod:`hashlib`" @@ -180,4 +235,4 @@ msgstr "Módulo :mod:`hashlib`" #: ../../library/hmac.rst:147 msgid "The Python module providing secure hash functions." -msgstr "" +msgstr "O módulo Python que fornece funções hash seguras." diff --git a/library/html.entities.po b/library/html.entities.po index ded49adba..a0ab75044 100644 --- a/library/html.entities.po +++ b/library/html.entities.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:07+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/html.parser.po b/library/html.parser.po index 2e1fce47a..7e9377945 100644 --- a/library/html.parser.po +++ b/library/html.parser.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-02 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:07+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-08 03:57+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -81,29 +80,64 @@ msgstr "" msgid "" "As a basic example, below is a simple HTML parser that uses the :class:" "`HTMLParser` class to print out start tags, end tags, and data as they are " -"encountered::" +"encountered:" +msgstr "" + +#: ../../library/html.parser.rst:48 +msgid "" +"from html.parser import HTMLParser\n" +"\n" +"class MyHTMLParser(HTMLParser):\n" +" def handle_starttag(self, tag, attrs):\n" +" print(\"Encountered a start tag:\", tag)\n" +"\n" +" def handle_endtag(self, tag):\n" +" print(\"Encountered an end tag :\", tag)\n" +"\n" +" def handle_data(self, data):\n" +" print(\"Encountered some data :\", data)\n" +"\n" +"parser = MyHTMLParser()\n" +"parser.feed('Test'\n" +" '

Parse me!

')" msgstr "" -#: ../../library/html.parser.rst:64 +#: ../../library/html.parser.rst:66 msgid "The output will then be:" msgstr "" -#: ../../library/html.parser.rst:83 -msgid ":class:`.HTMLParser` Methods" +#: ../../library/html.parser.rst:68 +msgid "" +"Encountered a start tag: html\n" +"Encountered a start tag: head\n" +"Encountered a start tag: title\n" +"Encountered some data : Test\n" +"Encountered an end tag : title\n" +"Encountered an end tag : head\n" +"Encountered a start tag: body\n" +"Encountered a start tag: h1\n" +"Encountered some data : Parse me!\n" +"Encountered an end tag : h1\n" +"Encountered an end tag : body\n" +"Encountered an end tag : html" msgstr "" #: ../../library/html.parser.rst:85 +msgid ":class:`.HTMLParser` Methods" +msgstr "" + +#: ../../library/html.parser.rst:87 msgid ":class:`HTMLParser` instances have the following methods:" msgstr "" -#: ../../library/html.parser.rst:90 +#: ../../library/html.parser.rst:92 msgid "" "Feed some text to the parser. It is processed insofar as it consists of " "complete elements; incomplete data is buffered until more data is fed or :" "meth:`close` is called. *data* must be :class:`str`." msgstr "" -#: ../../library/html.parser.rst:97 +#: ../../library/html.parser.rst:99 msgid "" "Force processing of all buffered data as if it were followed by an end-of-" "file mark. This method may be redefined by a derived class to define " @@ -111,17 +145,17 @@ msgid "" "should always call the :class:`HTMLParser` base class method :meth:`close`." msgstr "" -#: ../../library/html.parser.rst:105 +#: ../../library/html.parser.rst:107 msgid "" "Reset the instance. Loses all unprocessed data. This is called implicitly " "at instantiation time." msgstr "" -#: ../../library/html.parser.rst:111 +#: ../../library/html.parser.rst:113 msgid "Return current line number and offset." msgstr "" -#: ../../library/html.parser.rst:116 +#: ../../library/html.parser.rst:118 msgid "" "Return the text of the most recently opened start tag. This should not " "normally be needed for structured processing, but may be useful in dealing " @@ -129,7 +163,7 @@ msgid "" "(whitespace between attributes can be preserved, etc.)." msgstr "" -#: ../../library/html.parser.rst:122 +#: ../../library/html.parser.rst:124 msgid "" "The following methods are called when data or markup elements are " "encountered and they are meant to be overridden in a subclass. The base " @@ -137,13 +171,13 @@ msgid "" "handle_startendtag`):" msgstr "" -#: ../../library/html.parser.rst:129 +#: ../../library/html.parser.rst:131 msgid "" "This method is called to handle the start tag of an element (e.g. ``
``)." msgstr "" -#: ../../library/html.parser.rst:131 +#: ../../library/html.parser.rst:133 msgid "" "The *tag* argument is the name of the tag converted to lower case. The " "*attrs* argument is a list of ``(name, value)`` pairs containing the " @@ -152,29 +186,29 @@ msgid "" "character and entity references have been replaced." msgstr "" -#: ../../library/html.parser.rst:137 +#: ../../library/html.parser.rst:139 msgid "" "For instance, for the tag ````, this method " "would be called as ``handle_starttag('a', [('href', 'https://www.cwi." "nl/')])``." msgstr "" -#: ../../library/html.parser.rst:140 +#: ../../library/html.parser.rst:142 msgid "" "All entity references from :mod:`html.entities` are replaced in the " "attribute values." msgstr "" -#: ../../library/html.parser.rst:146 +#: ../../library/html.parser.rst:148 msgid "" "This method is called to handle the end tag of an element (e.g. ``
``)." msgstr "" -#: ../../library/html.parser.rst:148 +#: ../../library/html.parser.rst:150 msgid "The *tag* argument is the name of the tag converted to lower case." msgstr "" -#: ../../library/html.parser.rst:153 +#: ../../library/html.parser.rst:155 msgid "" "Similar to :meth:`handle_starttag`, but called when the parser encounters an " "XHTML-style empty tag (````). This method may be overridden by " @@ -183,20 +217,20 @@ msgid "" "`handle_endtag`." msgstr "" -#: ../../library/html.parser.rst:161 +#: ../../library/html.parser.rst:163 msgid "" "This method is called to process arbitrary data (e.g. text nodes and the " "content of ```` and ````)." msgstr "" -#: ../../library/html.parser.rst:167 +#: ../../library/html.parser.rst:169 msgid "" "This method is called to process a named character reference of the form " "``&name;`` (e.g. ``>``), where *name* is a general entity reference (e.g. " "``'gt'``). This method is never called if *convert_charrefs* is ``True``." msgstr "" -#: ../../library/html.parser.rst:175 +#: ../../library/html.parser.rst:177 msgid "" "This method is called to process decimal and hexadecimal numeric character " "references of the form :samp:`&#{NNN};` and :samp:`&#x{NNN};`. For example, " @@ -205,19 +239,19 @@ msgid "" "This method is never called if *convert_charrefs* is ``True``." msgstr "" -#: ../../library/html.parser.rst:184 +#: ../../library/html.parser.rst:186 msgid "" "This method is called when a comment is encountered (e.g. ```` will cause this method to be " "called with the argument ``' comment '``." msgstr "" -#: ../../library/html.parser.rst:189 +#: ../../library/html.parser.rst:191 msgid "" "The content of Internet Explorer conditional comments (condcoms) will also " "be sent to this method, so, for ``'\n" +"... '')\n" +"Comment : a comment\n" +"Comment : [if IE 9]>IE-specific content'``)::" +"correct char (note: these 3 references are all equivalent to ``'>'``):" msgstr "" -#: ../../library/html.parser.rst:318 +#: ../../library/html.parser.rst:325 +msgid "" +">>> parser = MyHTMLParser()\n" +">>> parser.feed('>>>')\n" +"Data : >>>\n" +"\n" +">>> parser = MyHTMLParser(convert_charrefs=False)\n" +">>> parser.feed('>>>')\n" +"Named ent: >\n" +"Num ent : >\n" +"Num ent : >" +msgstr "" + +#: ../../library/html.parser.rst:337 msgid "" "Feeding incomplete chunks to :meth:`~HTMLParser.feed` works, but :meth:" "`~HTMLParser.handle_data` might be called more than once (unless " -"*convert_charrefs* is set to ``True``)::" +"*convert_charrefs* is set to ``True``):" +msgstr "" + +#: ../../library/html.parser.rst:341 +msgid "" +">>> for chunk in ['buff', 'ered', ' text']:\n" +"... parser.feed(chunk)\n" +"...\n" +"Start tag: span\n" +"Data : buff\n" +"Data : ered\n" +"Data : text\n" +"End tag : span" msgstr "" -#: ../../library/html.parser.rst:331 -msgid "Parsing invalid HTML (e.g. unquoted attributes) also works::" +#: ../../library/html.parser.rst:352 +msgid "Parsing invalid HTML (e.g. unquoted attributes) also works:" +msgstr "" + +#: ../../library/html.parser.rst:354 +msgid "" +">>> parser.feed('

tag soup

')\n" +"Start tag: p\n" +"Start tag: a\n" +" attr: ('class', 'link')\n" +" attr: ('href', '#main')\n" +"Data : tag soup\n" +"End tag : p\n" +"End tag : a" msgstr "" #: ../../library/html.parser.rst:9 diff --git a/library/html.po b/library/html.po index ef9a9791f..1bc909975 100644 --- a/library/html.po +++ b/library/html.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Marcelo Bitencourt , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:07+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/http.client.po b/library/http.client.po index c42d9e9b5..2e28351bd 100644 --- a/library/http.client.po +++ b/library/http.client.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Marcos Wenneton Araújo , 2021 -# i17obot , 2021 -# Marco Rougeth , 2023 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:07+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:09+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -58,8 +53,8 @@ msgstr "" "SSL (através do módulo :mod:`ssl`)." #: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +msgid "Availability" +msgstr "Disponibilidade" #: ../../includes/wasm-notavail.rst:5 msgid "" @@ -95,6 +90,14 @@ msgstr "" "Por exemplo, todas as seguintes chamadas criam instâncias que conectam ao " "servidor com o mesmo host e porta::" +#: ../../library/http.client.rst:54 +msgid "" +">>> h1 = http.client.HTTPConnection('www.python.org')\n" +">>> h2 = http.client.HTTPConnection('www.python.org:80')\n" +">>> h3 = http.client.HTTPConnection('www.python.org', 80)\n" +">>> h4 = http.client.HTTPConnection('www.python.org', 80, timeout=10)" +msgstr "" + #: ../../library/http.client.rst:59 msgid "*source_address* was added." msgstr "*source_address* foi adicionado." @@ -354,17 +357,17 @@ msgid "" "iterable is exhausted." msgstr "" "Se *body* é especificado, os dados especificados são mandados depois que os " -"cabeçalhos estão prontos. Pode ser um :class:`str`, um :term:`objeto byte ou " -"similar `, um :term:`objeto arquivo ` " +"cabeçalhos estão prontos. Pode ser um :class:`str`, um :term:`objeto bytes " +"ou similar `, um :term:`objeto arquivo ` " "aberto, ou um iterável de :class:`bytes`. Se *body* é uma string, ele é " -"codificado como ISO-8859-1, o padrão para HTTP. Se é um objeto do tipo byte, " -"os bytes são enviados como estão. Se é um :term:`objeto arquivo `, o conteúdo do arquivo é enviado; este objeto arquivo deve suportar " +"codificado como ISO-8859-1, o padrão para HTTP. Se é um objeto bytes ou " +"similar, os bytes são enviados como estão. Se é um :term:`objeto arquivo`, o " +"conteúdo do arquivo é enviado; este objeto arquivo deve oferecer suporte a " "pelo menos o método ``read()``. Se o objeto arquivo é uma instância de :" "class:`io.TextIOBase`, os dados retornados pelo método ``read()`` será " "codificado como ISO-8859-1, de outra forma os dados retornados por " "``read()`` são enviados como estão. Se *body* é um iterável, os elementos do " -"iterável são enviados até os mesmo se esgotar." +"iterável são enviados até o iterável se esgotar." #: ../../library/http.client.rst:274 msgid "" @@ -401,6 +404,17 @@ msgid "" "For example, to perform a ``GET`` request to ``https://docs.python.org/3/``::" msgstr "" +#: ../../library/http.client.rst:299 +msgid "" +">>> import http.client\n" +">>> host = \"docs.python.org\"\n" +">>> conn = http.client.HTTPSConnection(host)\n" +">>> conn.request(\"GET\", \"/3/\", headers={\"Host\": host})\n" +">>> response = conn.getresponse()\n" +">>> print(response.status, response.reason)\n" +"200 OK" +msgstr "" + #: ../../library/http.client.rst:308 msgid "" "Chunked transfer encoding has been added to the HTTP protocol version 1.1. " @@ -488,6 +502,14 @@ msgid "" "the :meth:`~HTTPConnection.set_tunnel` method::" msgstr "" +#: ../../library/http.client.rst:374 +msgid "" +">>> import http.client\n" +">>> conn = http.client.HTTPSConnection(\"localhost\", 8080)\n" +">>> conn.set_tunnel(\"www.python.org\")\n" +">>> conn.request(\"HEAD\",\"/index.html\")" +msgstr "" + #: ../../library/http.client.rst:381 msgid "" "HTTP CONNECT tunnelling requests use protocol HTTP/1.1, upgraded from " @@ -705,16 +727,76 @@ msgstr "Exemplos" msgid "Here is an example session that uses the ``GET`` method::" msgstr "" +#: ../../library/http.client.rst:573 +msgid "" +">>> import http.client\n" +">>> conn = http.client.HTTPSConnection(\"www.python.org\")\n" +">>> conn.request(\"GET\", \"/\")\n" +">>> r1 = conn.getresponse()\n" +">>> print(r1.status, r1.reason)\n" +"200 OK\n" +">>> data1 = r1.read() # This will return entire content.\n" +">>> # The following example demonstrates reading data in chunks.\n" +">>> conn.request(\"GET\", \"/\")\n" +">>> r1 = conn.getresponse()\n" +">>> while chunk := r1.read(200):\n" +"... print(repr(chunk))\n" +"b'\\n'\n" +">>> print(aRepr.repr(example))\n" +"[\n" +"-->1,\n" +"-->'spam',\n" +"-->{\n" +"-->-->'a': 2,\n" +"-->-->'b': 'spam eggs',\n" +"-->-->'c': {\n" +"-->-->-->3: 4.5,\n" +"-->-->-->6: [],\n" +"-->-->},\n" +"-->},\n" +"-->'ham',\n" +"]" +msgstr "" +">>> aRepr.indent = '-->'\n" +">>> print(aRepr.repr(example))\n" +"[\n" +"-->1,\n" +"-->'spam',\n" +"-->{\n" +"-->-->'a': 2,\n" +"-->-->'b': 'spam eggs',\n" +"-->-->'c': {\n" +"-->-->-->3: 4.5,\n" +"-->-->-->6: [],\n" +"-->-->},\n" +"-->},\n" +"-->'ham',\n" +"]" #: ../../library/reprlib.rst:183 msgid "" "Setting :attr:`~Repr.indent` to a positive integer value behaves as if it " "was set to a string with that number of spaces:" msgstr "" +"Definir :attr:`~Repr.indent` como um valor inteiro positivo se comporta como " +"se fosse definido como uma string com esse número de espaços:" + +#: ../../library/reprlib.rst:186 +msgid "" +">>> aRepr.indent = 4\n" +">>> print(aRepr.repr(example))\n" +"[\n" +" 1,\n" +" 'spam',\n" +" {\n" +" 'a': 2,\n" +" 'b': 'spam eggs',\n" +" 'c': {\n" +" 3: 4.5,\n" +" 6: [],\n" +" },\n" +" },\n" +" 'ham',\n" +"]" +msgstr "" +">>> aRepr.indent = 4\n" +">>> print(aRepr.repr(example))\n" +"[\n" +" 1,\n" +" 'spam',\n" +" {\n" +" 'a': 2,\n" +" 'b': 'spam eggs',\n" +" 'c': {\n" +" 3: 4.5,\n" +" 6: [],\n" +" },\n" +" },\n" +" 'ham',\n" +"]" #: ../../library/reprlib.rst:209 msgid "" "The equivalent to the built-in :func:`repr` that uses the formatting imposed " "by the instance." msgstr "" +"O equivalente ao :func:`repr` embutido que usa a formatação imposta pela " +"instância." #: ../../library/reprlib.rst:215 msgid "" @@ -195,6 +356,11 @@ msgid "" "formatting, with ``level - 1`` for the value of *level* in the recursive " "call." msgstr "" +"Implementação recursiva usada por :meth:`.repr`. Esta usa o tipo de *obj* " +"para determinar qual método de formatação chamar, passando *obj* e *level*. " +"Os métodos específicos de tipo devem chamar :meth:`repr1` para realizar a " +"formatação recursiva, com ``level - 1`` para o valor de *level* na chamada " +"recursiva." #: ../../library/reprlib.rst:224 msgid "" @@ -204,10 +370,16 @@ msgid "" "meth:`repr1`. Type-specific methods which need to recursively format a value " "should call ``self.repr1(subobj, level - 1)``." msgstr "" +"Métodos de formatação para tipos específicos são implementados como métodos " +"com um nome baseado no nome do tipo. No nome do método, **TYPE** é " +"substituído por ``'_'.join(type(obj).__name__.split())``. O despacho para " +"esses métodos é tratado por :meth:`repr1`. Métodos específicos de tipo que " +"precisam formatar um valor recursivamente devem chamar ``self.repr1(subobj, " +"level - 1)``." #: ../../library/reprlib.rst:234 msgid "Subclassing Repr Objects" -msgstr "" +msgstr "Estendendo objetos Repr" #: ../../library/reprlib.rst:236 msgid "" @@ -216,6 +388,42 @@ msgid "" "modify the handling of types already supported. This example shows how " "special support for file objects could be added:" msgstr "" +"O uso de despacho dinâmico por :meth:`Repr.repr1` permite que subclasses de :" +"class:`Repr` adicionem suporte para tipos de objetos embutidos adicionais ou " +"modifiquem o tratamento de tipos já suportados. Este exemplo mostra como " +"suporte especial para objetos arquivo pode ser adicionado:" + +#: ../../library/reprlib.rst:241 +msgid "" +"import reprlib\n" +"import sys\n" +"\n" +"class MyRepr(reprlib.Repr):\n" +"\n" +" def repr_TextIOWrapper(self, obj, level):\n" +" if obj.name in {'', '', ''}:\n" +" return obj.name\n" +" return repr(obj)\n" +"\n" +"aRepr = MyRepr()\n" +"print(aRepr.repr(sys.stdin)) # prints ''" +msgstr "" +"import reprlib\n" +"import sys\n" +"\n" +"class MyRepr(reprlib.Repr):\n" +"\n" +" def repr_TextIOWrapper(self, obj, level):\n" +" if obj.name in {'', '', ''}:\n" +" return obj.name\n" +" return repr(obj)\n" +"\n" +"aRepr = MyRepr()\n" +"print(aRepr.repr(sys.stdin)) # exibe ''" + +#: ../../library/reprlib.rst:256 +msgid "" +msgstr "" #: ../../library/reprlib.rst:65 msgid "..." diff --git a/library/resource.po b/library/resource.po index 54e27aa39..77b197054 100644 --- a/library/resource.po +++ b/library/resource.po @@ -1,54 +1,63 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Welington Carlos , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:12+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/resource.rst:2 msgid ":mod:`!resource` --- Resource usage information" -msgstr "" +msgstr ":mod:`!resource` --- Informação de uso de recursos" #: ../../library/resource.rst:13 msgid "" "This module provides basic mechanisms for measuring and controlling system " "resources utilized by a program." msgstr "" +"Este módulo fornece mecanismos básicos para medir e controlar os recursos do " +"sistema usados por um programa." -#: ../../library/resource.rst:16 -msgid ":ref:`Availability `: Unix, not WASI." -msgstr ":ref:`Disponibilidade `: Unix, não WASI." +#: ../../library/resource.rst:16 ../../library/resource.rst:104 +#: ../../library/resource.rst:180 ../../library/resource.rst:192 +#: ../../library/resource.rst:201 ../../library/resource.rst:210 +#: ../../library/resource.rst:220 ../../library/resource.rst:229 +#: ../../library/resource.rst:239 ../../library/resource.rst:252 +#: ../../library/resource.rst:260 ../../library/resource.rst:268 +msgid "Availability" +msgstr "Disponibilidade" #: ../../library/resource.rst:18 msgid "" "Symbolic constants are used to specify particular system resources and to " "request usage information about either the current process or its children." msgstr "" +"Constantes simbólicas são usadas para especificar recursos específicos do " +"sistema e para solicitar informações de uso sobre o processo atual ou seus " +"filhos." #: ../../library/resource.rst:21 msgid "An :exc:`OSError` is raised on syscall failure." msgstr "" +"Uma exceção :exc:`OSError` é levantada em caso de falha de chamada de " +"sistema." #: ../../library/resource.rst:26 msgid "A deprecated alias of :exc:`OSError`." @@ -62,7 +71,7 @@ msgstr "" #: ../../library/resource.rst:33 msgid "Resource Limits" -msgstr "" +msgstr "Limites de recursos" #: ../../library/resource.rst:35 msgid "" @@ -74,6 +83,13 @@ msgid "" "soft limit, but not raised. (Only processes with the effective UID of the " "super-user can raise a hard limit.)" msgstr "" +"O uso de recursos pode ser limitado usando a função :func:`setrlimit` " +"descrita abaixo. Cada recurso é controlado por um par de limites: um limite " +"suave e um limite rígido. O limite suave é o limite atual e pode ser " +"reduzido ou aumentado por um processo ao longo do tempo. O limite suave " +"nunca pode exceder o limite rígido. O limite rígido pode ser reduzido para " +"qualquer valor maior que o limite suave, mas não aumentado. (Somente " +"processos com o UID efetivo do superusuário podem aumentar um limite rígido.)" #: ../../library/resource.rst:43 msgid "" @@ -83,10 +99,15 @@ msgid "" "resources which cannot be checked or controlled by the operating system are " "not defined in this module for those platforms." msgstr "" +"Os recursos específicos que podem ser limitados dependem do sistema. Eles " +"são descritos na página man :manpage:`getrlimit(2)`. Os recursos listados " +"abaixo são suportados quando o sistema operacional subjacente os suporta; " +"recursos que não podem ser verificados ou controlados pelo sistema " +"operacional não são definidos neste módulo para essas plataformas." #: ../../library/resource.rst:52 msgid "Constant used to represent the limit for an unlimited resource." -msgstr "" +msgstr "Constante usada para representar o limite de um recurso ilimitado." #: ../../library/resource.rst:57 msgid "" @@ -94,6 +115,10 @@ msgid "" "*resource*. Raises :exc:`ValueError` if an invalid resource is specified, " "or :exc:`error` if the underlying system call fails unexpectedly." msgstr "" +"Retorna uma tupla ``(suave, rígido)`` com os limites soft e hard atuais de " +"*resource*. Levanta :exc:`ValueError` se um recurso inválido for " +"especificado, ou :exc:`error` se a chamada do sistema subjacente falhar " +"inesperadamente." #: ../../library/resource.rst:64 msgid "" @@ -102,6 +127,10 @@ msgid "" "of :data:`~resource.RLIM_INFINITY` can be used to request a limit that is " "unlimited." msgstr "" +"Define novos limites de consumo de *resource*. O argumento *limits* deve ser " +"uma tupla ``(suave, rígido)`` de dois inteiros descrevendo os novos limites. " +"Um valor de :data:`~resource.RLIM_INFINITY` pode ser usado para solicitar um " +"limite ilimitado." #: ../../library/resource.rst:69 msgid "" @@ -113,16 +142,26 @@ msgid "" "any valid limit value, including unlimited, but :exc:`ValueError` will still " "be raised if the requested limit exceeds the system imposed limit." msgstr "" +"Levanta :exc:`ValueError` se um recurso inválido for especificado, se o novo " +"limite suave exceder o limite rígido ou se um processo tentar aumentar seu " +"limite rígido. Especificar um limite de :data:`~resource.RLIM_INFINITY` " +"quando o limite rígido ou do sistema para esse recurso não for ilimitado " +"resultará em uma exceção :exc:`ValueError`. Um processo com o UID efetivo de " +"superusuário pode solicitar qualquer valor limite válido, incluindo " +"ilimitado, mas :exc:`ValueError` ainda será levantada se o limite solicitado " +"exceder o limite imposto pelo sistema." #: ../../library/resource.rst:78 msgid "" "``setrlimit`` may also raise :exc:`error` if the underlying system call " "fails." msgstr "" +"``setrlimit`` também pode levantar :exc:`error` se a chamada do sistema " +"subjacente falhar." #: ../../library/resource.rst:81 msgid "VxWorks only supports setting :data:`RLIMIT_NOFILE`." -msgstr "" +msgstr "VxWorks só oferece suporte a definir :data:`RLIMIT_NOFILE`." #: ../../library/resource.rst:83 msgid "" @@ -140,6 +179,10 @@ msgid "" "*limits* have the same meaning as in :func:`setrlimit`, except that *limits* " "is optional." msgstr "" +"Combina :func:`setrlimit` e :func:`getrlimit` em uma única função e permite " +"obter e definir os limites de recursos de um processo arbitrário. Se *pid* " +"for 0, a chamada se aplica ao processo atual. *resource* e *limits* têm o " +"mesmo significado que em :func:`setrlimit`, exceto que *limits* é opcional." #: ../../library/resource.rst:94 msgid "" @@ -147,6 +190,9 @@ msgid "" "process *pid*. When *limits* is given the *resource* limit of the process is " "set and the former resource limit is returned." msgstr "" +"Quando *limits* não é fornecido, a função retorna o limite de *resource* do " +"processo *pid*. Quando *limits* é fornecido, o limite de *resource* do " +"processo é definido e o limite de recurso anterior é retornado." #: ../../library/resource.rst:98 msgid "" @@ -154,6 +200,9 @@ msgid "" "`PermissionError` when the user doesn't have ``CAP_SYS_RESOURCE`` for the " "process." msgstr "" +"Levanta :exc:`ProcessLookupError` quando *pid* não pode ser encontrado e :" +"exc:`PermissionError` quando o usuário não tem ``CAP_SYS_RESOURCE`` para o " +"processo." #: ../../library/resource.rst:102 msgid "" @@ -163,17 +212,15 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``resource.prlimit`` com os " "argumentos ``pid``, ``resource``, ``limits``." -#: ../../library/resource.rst:104 -msgid ":ref:`Availability `: Linux >= 2.6.36 with glibc >= 2.13." -msgstr "" -":ref:`Disponibilidade `: Linux >= 2.6.36 com glibc >= 2.13." - #: ../../library/resource.rst:109 msgid "" "These symbols define resources whose consumption can be controlled using " "the :func:`setrlimit` and :func:`getrlimit` functions described below. The " "values of these symbols are exactly the constants used by C programs." msgstr "" +"Esses símbolos definem recursos cujo consumo pode ser controlado usando as " +"funções :func:`setrlimit` e :func:`getrlimit` descritas abaixo. Os valores " +"desses símbolos são exatamente as constantes usadas por programas em C." #: ../../library/resource.rst:113 msgid "" @@ -183,6 +230,11 @@ msgid "" "--- symbols not defined for a platform will not be available from this " "module on that platform." msgstr "" +"A página man do Unix para :manpage:`getrlimit(2)` lista os recursos " +"disponíveis. Observe que nem todos os sistemas usam o mesmo símbolo ou o " +"mesmo valor para denotar o mesmo recurso. Este módulo não tenta mascarar " +"diferenças de plataforma --- símbolos não definidos para uma plataforma não " +"estarão disponíveis neste módulo para essa plataforma." #: ../../library/resource.rst:122 msgid "" @@ -190,6 +242,10 @@ msgid "" "create. This may result in the creation of a partial core file if a larger " "core would be required to contain the entire process image." msgstr "" +"O tamanho máximo (em bytes) de um arquivo de núcleo (core file) que o " +"processo atual pode criar. Isso pode resultar na criação de um arquivo de " +"núcleo parcial se um núcleo maior for necessário para conter a imagem " +"completa do processo." #: ../../library/resource.rst:129 msgid "" @@ -198,89 +254,90 @@ msgid "" "(See the :mod:`signal` module documentation for information about how to " "catch this signal and do something useful, e.g. flush open files to disk.)" msgstr "" +"O tempo máximo de processador (em segundos) que um processo pode usar. Se " +"esse limite for excedido, um sinal :const:`SIGXCPU` é enviado ao processo. " +"(Consulte a documentação do módulo :mod:`signal` para obter informações " +"sobre como capturar esse sinal e fazer algo útil, por exemplo, liberar " +"arquivos abertos no disco.)" #: ../../library/resource.rst:137 msgid "The maximum size of a file which the process may create." -msgstr "" +msgstr "O tamanho máximo de um arquivo que o processo pode criar." #: ../../library/resource.rst:142 msgid "The maximum size (in bytes) of the process's heap." -msgstr "" +msgstr "O tamanho máximo (em bytes) da heap do processo." #: ../../library/resource.rst:147 msgid "" "The maximum size (in bytes) of the call stack for the current process. This " "only affects the stack of the main thread in a multi-threaded process." msgstr "" +"O tamanho máximo (em bytes) da pilha de chamadas para o processo atual. Isso " +"afeta apenas a pilha da thread principal em um processo multithread." #: ../../library/resource.rst:153 msgid "" "The maximum resident set size that should be made available to the process." msgstr "" +"O tamanho máximo do conjunto de residentes que deve ser disponibilizado para " +"o processo." #: ../../library/resource.rst:158 msgid "The maximum number of processes the current process may create." -msgstr "" +msgstr "O número máximo de processos que o processo atual pode criar." #: ../../library/resource.rst:163 msgid "The maximum number of open file descriptors for the current process." msgstr "" +"O número máximo de descritores de arquivo abertos para o processo atual." #: ../../library/resource.rst:168 msgid "The BSD name for :const:`RLIMIT_NOFILE`." -msgstr "" +msgstr "O nome BSD para :const:`RLIMIT_NOFILE`." #: ../../library/resource.rst:173 msgid "The maximum address space which may be locked in memory." -msgstr "" +msgstr "O espaço máximo de endereço que pode ser travado na memória." #: ../../library/resource.rst:178 msgid "The largest area of mapped memory which the process may occupy." -msgstr "" - -#: ../../library/resource.rst:180 ../../library/resource.rst:268 -msgid ":ref:`Availability `: FreeBSD >= 11." -msgstr ":ref:`Disponibilidade `: FreeBSD >= 11." +msgstr "A maior área de memória mapeada que o processo pode ocupar." #: ../../library/resource.rst:185 msgid "" "The maximum area (in bytes) of address space which may be taken by the " "process." msgstr "" +"A área máxima (em bytes) de espaço de endereço que pode ser ocupada pelo " +"processo." #: ../../library/resource.rst:190 msgid "The number of bytes that can be allocated for POSIX message queues." msgstr "" - -#: ../../library/resource.rst:192 ../../library/resource.rst:229 -msgid ":ref:`Availability `: Linux >= 2.6.8." -msgstr ":ref:`Disponibilidade `: Linux >= 2.6.8." +"O número de bytes que podem ser alocados para filas de mensagens POSIX." #: ../../library/resource.rst:199 msgid "The ceiling for the process's nice level (calculated as 20 - rlim_cur)." msgstr "" - -#: ../../library/resource.rst:201 ../../library/resource.rst:210 -msgid ":ref:`Availability `: Linux >= 2.6.12." -msgstr ":ref:`Disponibilidade `: Linux >= 2.6.12." +"O teto para o nível agradável do processo (calculado como 20 - rlim_cur)." #: ../../library/resource.rst:208 msgid "The ceiling of the real-time priority." -msgstr "" +msgstr "O teto da prioridade em tempo real." #: ../../library/resource.rst:217 msgid "" "The time limit (in microseconds) on CPU time that a process can spend under " "real-time scheduling without making a blocking syscall." msgstr "" - -#: ../../library/resource.rst:220 -msgid ":ref:`Availability `: Linux >= 2.6.25." -msgstr ":ref:`Disponibilidade `: Linux >= 2.6.25." +"O limite de tempo (em microssegundos) no tempo de CPU que um processo pode " +"gastar sob agendamento em tempo real sem fazer uma chamada de sistema de " +"bloqueio." #: ../../library/resource.rst:227 msgid "The number of signals which the process may queue." -msgstr "" +msgstr "O número de sinais que o processo pode enfileirar." #: ../../library/resource.rst:235 msgid "" @@ -288,11 +345,9 @@ msgid "" "limits the amount of network memory, and hence the amount of mbufs, that " "this user may hold at any time." msgstr "" - -#: ../../library/resource.rst:239 ../../library/resource.rst:252 -#: ../../library/resource.rst:260 -msgid ":ref:`Availability `: FreeBSD." -msgstr ":ref:`Disponibilidade `: FreeBSD." +"O tamanho máximo (em bytes) de uso do buffer de soquete para este usuário. " +"Isso limita a quantidade de memória de rede e, portanto, a quantidade de " +"mbufs que este usuário pode armazenar a qualquer momento." #: ../../library/resource.rst:245 msgid "" @@ -302,22 +357,29 @@ msgid "" "org/cgi/man.cgi?query=tuning&sektion=7>`__ for a complete description of " "this sysctl." msgstr "" +"O tamanho máximo (em bytes) do espaço de swap que pode ser reservado ou " +"utilizado por todos os processos deste ID de usuário. Este limite é aplicado " +"somente se o bit 1 do sysctl vm.overcommit estiver definido. Consulte " +"`tuning(7) `__ " +"para uma descrição completa deste sysctl." #: ../../library/resource.rst:258 msgid "The maximum number of pseudo-terminals created by this user id." -msgstr "" +msgstr "O número máximo de pseudoterminais criados por este ID de usuário." #: ../../library/resource.rst:266 msgid "The maximum number of kqueues this user id is allowed to create." msgstr "" +"O número máximo de kqueues que esse ID de usuário tem permissão para criar." #: ../../library/resource.rst:273 msgid "Resource Usage" -msgstr "" +msgstr "Uso de recursos" #: ../../library/resource.rst:275 msgid "These functions are used to retrieve resource usage information:" msgstr "" +"Essas funções são usadas para recuperar informações de uso de recursos:" #: ../../library/resource.rst:280 msgid "" @@ -326,11 +388,41 @@ msgid "" "parameter. The *who* parameter should be specified using one of the :const:" "`!RUSAGE_\\*` constants described below." msgstr "" +"Esta função retorna um objeto que descreve os recursos consumidos pelo " +"processo atual ou seus filhos, conforme especificado pelo parâmetro *who*. O " +"parâmetro *who* deve ser especificado usando uma das constantes :const:`!" +"RUSAGE_\\*` descritas abaixo." #: ../../library/resource.rst:285 msgid "A simple example::" msgstr "Um exemplo simples::" +#: ../../library/resource.rst:287 +msgid "" +"from resource import *\n" +"import time\n" +"\n" +"# a non CPU-bound task\n" +"time.sleep(3)\n" +"print(getrusage(RUSAGE_SELF))\n" +"\n" +"# a CPU-bound task\n" +"for i in range(10 ** 8):\n" +" _ = 1 + 1\n" +"print(getrusage(RUSAGE_SELF))" +msgstr "" +"from resource import *\n" +"import time\n" +"\n" +"# uma tarefa não vinculada à CPU\n" +"time.sleep(3)\n" +"print(getrusage(RUSAGE_SELF))\n" +"\n" +"# uma tarefa vinculada à CPU\n" +"for i in range(10 ** 8):\n" +" _ = 1 + 1\n" +"print(getrusage(RUSAGE_SELF))" + #: ../../library/resource.rst:299 msgid "" "The fields of the return value each describe how a particular system " @@ -339,12 +431,19 @@ msgid "" "dependent on the clock tick internal, e.g. the amount of memory the process " "is using." msgstr "" +"Os campos do valor de retorno descrevem como um recurso específico do " +"sistema foi utilizado, por exemplo, a quantidade de tempo gasto em execução " +"no modo de usuário ou o número de vezes que o processo foi trocado da " +"memória principal. Alguns valores dependem do tique do relógio interno, por " +"exemplo, a quantidade de memória que o processo está usando." #: ../../library/resource.rst:304 msgid "" "For backward compatibility, the return value is also accessible as a tuple " "of 16 elements." msgstr "" +"Para retrocompatibilidade, o valor de retorno também pode ser acessado como " +"uma tupla de 16 elementos." #: ../../library/resource.rst:307 msgid "" @@ -355,6 +454,12 @@ msgid "" "`getrusage(2)` man page for detailed information about these values. A brief " "summary is presented here:" msgstr "" +"Os campos :attr:`ru_utime` e :attr:`ru_stime` do valor de retorno são " +"valores de ponto flutuante que representam o tempo gasto na execução no modo " +"usuário e o tempo gasto na execução no modo sistema, respectivamente. Os " +"valores restantes são inteiros. Consulte a página man :manpage:" +"`getrusage(2)` para obter informações detalhadas sobre esses valores. Um " +"breve resumo é apresentado aqui:" #: ../../library/resource.rst:314 msgid "Index" @@ -366,7 +471,7 @@ msgstr "Campo" #: ../../library/resource.rst:314 msgid "Resource" -msgstr "" +msgstr "Recurso" #: ../../library/resource.rst:316 msgid "``0``" @@ -378,7 +483,7 @@ msgstr ":attr:`ru_utime`" #: ../../library/resource.rst:316 msgid "time in user mode (float seconds)" -msgstr "" +msgstr "tempo no modo de usuário (segundos em pontos flutuantes)" #: ../../library/resource.rst:318 msgid "``1``" @@ -390,7 +495,7 @@ msgstr ":attr:`ru_stime`" #: ../../library/resource.rst:318 msgid "time in system mode (float seconds)" -msgstr "" +msgstr "tempo no modo de sistema (segundos em pontos flutuantes)" #: ../../library/resource.rst:320 msgid "``2``" @@ -402,7 +507,7 @@ msgstr ":attr:`ru_maxrss`" #: ../../library/resource.rst:320 msgid "maximum resident set size" -msgstr "" +msgstr "tamanho máximo do conjunto residente" #: ../../library/resource.rst:322 msgid "``3``" @@ -414,7 +519,7 @@ msgstr ":attr:`ru_ixrss`" #: ../../library/resource.rst:322 msgid "shared memory size" -msgstr "" +msgstr "tamanho da memória compartilhada" #: ../../library/resource.rst:324 msgid "``4``" @@ -426,7 +531,7 @@ msgstr ":attr:`ru_idrss`" #: ../../library/resource.rst:324 msgid "unshared memory size" -msgstr "" +msgstr "tamanho da memória não compartilhada" #: ../../library/resource.rst:326 msgid "``5``" @@ -438,7 +543,7 @@ msgstr ":attr:`ru_isrss`" #: ../../library/resource.rst:326 msgid "unshared stack size" -msgstr "" +msgstr "tamanho da pilha não compartilhada" #: ../../library/resource.rst:328 msgid "``6``" @@ -450,7 +555,7 @@ msgstr ":attr:`ru_minflt`" #: ../../library/resource.rst:328 msgid "page faults not requiring I/O" -msgstr "" +msgstr "falhas de página que não requerem E/S" #: ../../library/resource.rst:330 msgid "``7``" @@ -462,7 +567,7 @@ msgstr ":attr:`ru_majflt`" #: ../../library/resource.rst:330 msgid "page faults requiring I/O" -msgstr "" +msgstr "falhas de página que requerem E/S" #: ../../library/resource.rst:332 msgid "``8``" @@ -474,7 +579,7 @@ msgstr ":attr:`ru_nswap`" #: ../../library/resource.rst:332 msgid "number of swap outs" -msgstr "" +msgstr "número de trocas para a memórias de swap" #: ../../library/resource.rst:334 msgid "``9``" @@ -486,7 +591,7 @@ msgstr ":attr:`ru_inblock`" #: ../../library/resource.rst:334 msgid "block input operations" -msgstr "" +msgstr "operações de entrada de bloco" #: ../../library/resource.rst:336 msgid "``10``" @@ -498,7 +603,7 @@ msgstr ":attr:`ru_oublock`" #: ../../library/resource.rst:336 msgid "block output operations" -msgstr "" +msgstr "operações de saída de bloco" #: ../../library/resource.rst:338 msgid "``11``" @@ -510,7 +615,7 @@ msgstr ":attr:`ru_msgsnd`" #: ../../library/resource.rst:338 msgid "messages sent" -msgstr "" +msgstr "mensagens enviadas" #: ../../library/resource.rst:340 msgid "``12``" @@ -522,7 +627,7 @@ msgstr ":attr:`ru_msgrcv`" #: ../../library/resource.rst:340 msgid "messages received" -msgstr "" +msgstr "mensagens recebidas" #: ../../library/resource.rst:342 msgid "``13``" @@ -534,7 +639,7 @@ msgstr ":attr:`ru_nsignals`" #: ../../library/resource.rst:342 msgid "signals received" -msgstr "" +msgstr "sinais recebidos" #: ../../library/resource.rst:344 msgid "``14``" @@ -546,7 +651,7 @@ msgstr ":attr:`ru_nvcsw`" #: ../../library/resource.rst:344 msgid "voluntary context switches" -msgstr "" +msgstr "trocas voluntárias de contexto" #: ../../library/resource.rst:346 msgid "``15``" @@ -558,7 +663,7 @@ msgstr ":attr:`ru_nivcsw`" #: ../../library/resource.rst:346 msgid "involuntary context switches" -msgstr "" +msgstr "trocas involuntárias de contexto" #: ../../library/resource.rst:349 msgid "" @@ -566,12 +671,17 @@ msgid "" "is specified. It may also raise :exc:`error` exception in unusual " "circumstances." msgstr "" +"Esta função levantará uma :exc:`ValueError` se um parâmetro *who* inválido " +"for especificado. Também pode levantar uma exceção :exc:`error` em " +"circunstâncias incomuns." #: ../../library/resource.rst:355 msgid "" "Returns the number of bytes in a system page. (This need not be the same as " "the hardware page size.)" msgstr "" +"Retorna o número de bytes em uma página do sistema. (Não precisa ser o mesmo " +"que o tamanho da página de hardware.)" #: ../../library/resource.rst:358 msgid "" @@ -579,27 +689,40 @@ msgid "" "`getrusage` function to specify which processes information should be " "provided for." msgstr "" +"Os seguintes símbolos :const:`!RUSAGE_\\*` são passados ​​para a função :func:" +"`getrusage` para especificar quais informações de processos devem ser " +"fornecidas." #: ../../library/resource.rst:364 msgid "" "Pass to :func:`getrusage` to request resources consumed by the calling " "process, which is the sum of resources used by all threads in the process." msgstr "" +"Passeapara :func:`getrusage` para solicitar recursos consumidos pelo " +"processo de chamada, que é a soma dos recursos usados ​​por todas as threads " +"no processo." #: ../../library/resource.rst:370 msgid "" "Pass to :func:`getrusage` to request resources consumed by child processes " "of the calling process which have been terminated and waited for." msgstr "" +"Passa para :func:`getrusage` para solicitar recursos consumidos por " +"processos filhos do processo de chamada que foram encerrados e aguardados." #: ../../library/resource.rst:376 msgid "" "Pass to :func:`getrusage` to request resources consumed by both the current " "process and child processes. May not be available on all systems." msgstr "" +"Passa para :func:`getrusage` para solicitar recursos consumidos pelo " +"processo atual e pelos processos filhos. Pode não estar disponível em todos " +"os sistemas." #: ../../library/resource.rst:382 msgid "" "Pass to :func:`getrusage` to request resources consumed by the current " "thread. May not be available on all systems." msgstr "" +"Passa para :func:`getrusage` para solicitar recursos consumidos pela thread " +"atual. Pode não estar disponível em todos os sistemas." diff --git a/library/rlcompleter.po b/library/rlcompleter.po index be384d2fe..38de3099a 100644 --- a/library/rlcompleter.po +++ b/library/rlcompleter.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Italo Penaforte , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:12+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -60,6 +59,30 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" +#: ../../library/rlcompleter.rst:24 +msgid "" +">>> import rlcompleter\n" +">>> import readline\n" +">>> readline.parse_and_bind(\"tab: complete\")\n" +">>> readline. \n" +"readline.__doc__ readline.get_line_buffer( readline." +"read_init_file(\n" +"readline.__file__ readline.insert_text( readline." +"set_completer(\n" +"readline.__name__ readline.parse_and_bind(\n" +">>> readline." +msgstr "" +">>> import rlcompleter\n" +">>> import readline\n" +">>> readline.parse_and_bind(\"tab: complete\")\n" +">>> readline. \n" +"readline.__doc__ readline.get_line_buffer( readline." +"read_init_file(\n" +"readline.__file__ readline.insert_text( readline." +"set_completer(\n" +"readline.__name__ readline.parse_and_bind(\n" +">>> readline." + #: ../../library/rlcompleter.rst:33 msgid "" "The :mod:`!rlcompleter` module is designed for use with Python's :ref:" diff --git a/library/runpy.po b/library/runpy.po index ae43a0d87..c072478f9 100644 --- a/library/runpy.po +++ b/library/runpy.po @@ -1,33 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hemílio Lauro , 2021 -# Marco Rougeth , 2023 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 02:33+0000\n" -"PO-Revision-Date: 2021-06-28 01:12+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/runpy.rst:2 msgid ":mod:`!runpy` --- Locating and executing Python modules" -msgstr "" +msgstr ":mod:`!runpy` --- Localizando e executando módulos Python" #: ../../library/runpy.rst:9 msgid "**Source code:** :source:`Lib/runpy.py`" @@ -79,6 +77,10 @@ msgid "" "import mechanism (refer to :pep:`302` for details) and then executed in a " "fresh module namespace." msgstr "" +"Executa o código do módulo especificado e retorna o dicionário de globals do " +"módulo resultante. O código do módulo é localizado primeiro usando o " +"mecanismo de importação padrão (consulte :pep:`302` para detalhes) e então " +"executado em um novo espaço de nomes de módulo." #: ../../library/runpy.rst:40 msgid "" @@ -87,6 +89,10 @@ msgid "" "imported and the :mod:`__main__` submodule within that package is then " "executed and the resulting module globals dictionary returned." msgstr "" +"O argumento *mod_name* deve ser um nome de módulo absoluto. Se o nome do " +"módulo se referir a um pacote ao invés de um módulo normal, então esse " +"pacote é importado e o submódulo :mod:`__main__` dentro desse pacote é então " +"executado e o dicionário global do módulo resultante retornado." #: ../../library/runpy.rst:46 msgid "" @@ -96,6 +102,11 @@ msgid "" "defined in *init_globals*, those definitions are overridden by :func:" "`run_module`." msgstr "" +"O argumento opcional de dicionário *init_globals* pode ser usado para " +"preencher previamente o dicionário global do módulo antes do código ser " +"executado. *init_globals* não será modificado. Se qualquer uma das variáveis " +"globais especiais abaixo for definida em *init_globals*, estas definições " +"serão substituídas por :func:`run_module`." #: ../../library/runpy.rst:52 ../../library/runpy.rst:127 msgid "" @@ -105,6 +116,11 @@ msgid "" "set of variables - other variables may be set implicitly as an interpreter " "implementation detail.)" msgstr "" +"As variáveis globais especiais ``__name__``, ``__spec__``, ``__file__``, " +"``__cached__``, ``__loader__`` e ``__package__`` são definidas no dicionário " +"global antes que o código do módulo seja executado (Observe que este é um " +"conjunto mínimo de variáveis - outras variáveis podem ser definidas " +"implicitamente como um detalhe de implementação do interpretador)." #: ../../library/runpy.rst:58 msgid "" @@ -122,6 +138,9 @@ msgid "" "(that is, ``__spec__.name`` will always be *mod_name* or ``mod_name + '." "__main__'``, never *run_name*)." msgstr "" +"``__spec__`` será definido adequadamente para o módulo *efetivamente* " +"importado (isto é, ``__spec__.name`` vai sempre ser *mod_name* ou ``mod_name " +"+ '.__main__'``, nunca *run_name*)." #: ../../library/runpy.rst:66 msgid "" @@ -129,8 +148,7 @@ msgid "" "`set as normal ` based on the module spec." msgstr "" "``__file__``, ``__cached__``, ``__loader__`` e ``__package__`` são :ref:" -"`definidos como normal ` com base na especificação do " -"módulo." +"`definidos como normal ` com base no spec de módulo." #: ../../library/runpy.rst:69 msgid "" @@ -154,6 +172,10 @@ msgid "" "arguments. It is recommended that the ``sys`` module be left alone when " "invoking this function from threaded code." msgstr "" +"Note que esta manipulação de :mod:`sys` não é segura para thread. Outras " +"threads podem ver o módulo parcialmente inicializado, bem como a lista " +"alterada de argumentos. É recomendado que o módulo ``sys`` seja deixado " +"sozinho ao invocar esta função a partir do código encadeado." #: ../../library/runpy.rst:81 msgid "" @@ -166,6 +188,8 @@ msgstr "" msgid "" "Added ability to execute packages by looking for a :mod:`__main__` submodule." msgstr "" +"Adicionada capacidade de executar pacotes procurando por um submódulo :mod:" +"`__main__`." #: ../../library/runpy.rst:87 msgid "Added ``__cached__`` global variable (see :pep:`3147`)." @@ -178,10 +202,10 @@ msgid "" "well as ensuring the real module name is always accessible as ``__spec__." "name``." msgstr "" -"Atualizado para aproveitar o recurso de especificação do módulo adicionado " -"por :pep:`451`. Isso permite que ``__cached__`` seja configurado " -"corretamente para módulos executados desta forma, assim como garante que o " -"nome real do módulo esteja sempre acessível como ``__spec__.name``." +"Atualizado para aproveitar o recurso de spec de módulo adicionado por :pep:" +"`451`. Isso permite que ``__cached__`` seja configurado corretamente para " +"módulos executados desta forma, assim como garante que o nome real do módulo " +"esteja sempre acessível como ``__spec__.name``." #: ../../library/runpy.rst:96 msgid "" @@ -200,6 +224,12 @@ msgid "" "bytecode file or a valid :data:`sys.path` entry containing a :mod:`__main__` " "module (e.g. a zipfile containing a top-level :file:`__main__.py` file)." msgstr "" +"Executa o código no local do sistema de arquivos nomeado e retorna o " +"dicionário de globals do módulo resultante. Assim como um nome de script " +"fornecido à linha de comando CPython, *file_path* pode se referir a um " +"arquivo fonte Python, um arquivo compilado em bytecode ou uma entrada válida " +"de :data:`sys.path` contendo um módulo :mod:`__main__` (por exemplo, um " +"arquivo zip contendo um arquivo de nível superior :file:`__main__.py`)." #: ../../library/runpy.rst:113 msgid "" @@ -211,6 +241,13 @@ msgid "" "existing ``__main__`` entry located elsewhere on ``sys.path`` if there is no " "such module at the specified location." msgstr "" +"Para um script simples, o código especificado é simplesmente executado em um " +"novo espaço de nomes de módulo. Para uma entrada válida :data:`sys.path` " +"(normalmente um arquivo zip ou diretório), a entrada é primeiro adicionada " +"ao início de ``sys.path``. A função então procura e executa um módulo :mod:" +"`__main__` usando o caminho atualizado. Observe que não há proteção especial " +"contra invocar uma entrada ``__main__`` existente localizada em outro lugar " +"em ``sys.path`` se não houver tal módulo no local especificado." #: ../../library/runpy.rst:121 msgid "" @@ -220,6 +257,11 @@ msgid "" "defined in *init_globals*, those definitions are overridden by :func:" "`run_path`." msgstr "" +"O argumento opcional de dicionário *init_globals* pode ser usado para " +"preencher previamente o dicionário de globals do módulo antes do código ser " +"executado. *init_globals* não será modificado. Se qualquer uma das variáveis " +"globais especiais abaixo for definida em *init_globals*, estas definições " +"serão substituídas por :func:`run_path`." #: ../../library/runpy.rst:133 msgid "" @@ -236,6 +278,10 @@ msgid "" "``__spec__``, ``__cached__``, ``__loader__`` and ``__package__`` will all be " "set to :const:`None`." msgstr "" +"Se *file_path* fizer referência diretamente a um arquivo de script (seja " +"como fonte ou como bytecode pré-compilado), então ``__file__`` será definido " +"para *file_path* e ``__spec__``, ``__cached__``, ``__loader__`` e " +"``__package__`` serão todos definidos como :const:`None`." #: ../../library/runpy.rst:141 msgid "" @@ -245,6 +291,11 @@ msgid "" "``__file__``, ``__cached__``, ``__loader__`` and ``__package__`` will be :" "ref:`set as normal ` based on the module spec." msgstr "" +"Se *file_path* for uma referência a uma entrada válida de :data:`sys.path`, " +"então ``__spec__`` será definido apropriadamente para o módulo :mod:" +"`__main__` importado (ou seja, ``__spec__.name`` sempre será ``__main__``). " +"``__file__``, ``__cached__``, ``__loader__`` e ``__package__`` serão :ref:" +"`definidos como normal ` com base no spec de módulo." #: ../../library/runpy.rst:147 msgid "" @@ -255,6 +306,12 @@ msgid "" "modifications to items in :mod:`sys` are reverted before the function " "returns." msgstr "" +"Várias alterações também são feitas no módulo :mod:`sys`. Primeiramente, :" +"data:`sys.path` pode ser alterado conforme descrito acima. ``sys.argv[0]`` é " +"atualizado com o valor de *file_path* e ``sys.modules[__name__]`` é " +"atualizado com um objeto de módulo temporário para o módulo que está sendo " +"executado. Todas as modificações em itens em :mod:`sys` são revertidas antes " +"que a função retorne." #: ../../library/runpy.rst:154 msgid "" @@ -264,6 +321,12 @@ msgid "" "still apply, use of this function in threaded code should be either " "serialised with the import lock or delegated to a separate process." msgstr "" +"Note que, diferentemente de :func:`run_module`, as alterações feitas em :mod:" +"`sys` não são opcionais nesta função, pois esses ajustes são essenciais para " +"permitir a execução das entradas do :data:`sys.path`. Como as limitações de " +"segurança de threads ainda se aplicam, o uso dessa função no código " +"encadeado deve ser serializado com a trava de importação ou delegado a um " +"processo separado." #: ../../library/runpy.rst:161 msgid "" @@ -280,6 +343,10 @@ msgid "" "``__main__`` is imported from a valid :data:`sys.path` entry rather than " "being executed directly." msgstr "" +"Atualizado para aproveitar o recurso de spec de módulo adicionado por :pep:" +"`451`. Isso permite que ``__cached__`` seja definido corretamente no caso em " +"que ``__main__`` é importado de uma entrada :data:`sys.path` válida em vez " +"de ser executado diretamente." #: ../../library/runpy.rst:172 msgid "" diff --git a/library/sched.po b/library/sched.po index 95039df38..b9c125530 100644 --- a/library/sched.po +++ b/library/sched.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Italo Penaforte , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:12+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -64,6 +62,37 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" +#: ../../library/sched.rst:38 +msgid "" +">>> import sched, time\n" +">>> s = sched.scheduler(time.time, time.sleep)\n" +">>> def print_time(a='default'):\n" +"... print(\"From print_time\", time.time(), a)\n" +"...\n" +">>> def print_some_times():\n" +"... print(time.time())\n" +"... s.enter(10, 1, print_time)\n" +"... s.enter(5, 2, print_time, argument=('positional',))\n" +"... # despite having higher priority, 'keyword' runs after 'positional' " +"as enter() is relative\n" +"... s.enter(5, 1, print_time, kwargs={'a': 'keyword'})\n" +"... s.enterabs(1_650_000_000, 10, print_time, argument=(\"first " +"enterabs\",))\n" +"... s.enterabs(1_650_000_000, 5, print_time, argument=(\"second " +"enterabs\",))\n" +"... s.run()\n" +"... print(time.time())\n" +"...\n" +">>> print_some_times()\n" +"1652342830.3640375\n" +"From print_time 1652342830.3642538 second enterabs\n" +"From print_time 1652342830.3643398 first enterabs\n" +"From print_time 1652342835.3694863 positional\n" +"From print_time 1652342835.3696074 keyword\n" +"From print_time 1652342840.369612 default\n" +"1652342840.3697174" +msgstr "" + #: ../../library/sched.rst:67 msgid "Scheduler Objects" msgstr "Objetos Scheduler" diff --git a/library/secrets.po b/library/secrets.po index f127a9049..00ee33726 100644 --- a/library/secrets.po +++ b/library/secrets.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 01:12+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -90,8 +88,8 @@ msgid "Return a random int in the range [0, *exclusive_upper_bound*)." msgstr "Retorna um int aleatório no intervalo [0, *exclusive_upper_bound*)." #: ../../library/secrets.rst:55 -msgid "Return an int with *k* random bits." -msgstr "Retorna um int com *k* bits aleatórios." +msgid "Return a non-negative int with *k* random bits." +msgstr "Retorna um int não negativo com *k* bits aleatórios." #: ../../library/secrets.rst:59 msgid "Generating tokens" @@ -115,6 +113,14 @@ msgstr "" "Retorna uma string de byte aleatória contendo *nbytes* número de bytes. Se " "*nbytes* for ``None`` ou não fornecido, um padrão razoável é usado." +#: ../../library/secrets.rst:71 +msgid "" +">>> token_bytes(16)\n" +"b'\\xebr\\x17D*t\\xae\\xd4\\xe3S\\xb6\\xe2\\xebP1\\x8b'" +msgstr "" +">>> token_bytes(16)\n" +"b'\\xebr\\x17D*t\\xae\\xd4\\xe3S\\xb6\\xe2\\xebP1\\x8b'" + #: ../../library/secrets.rst:79 msgid "" "Return a random text string, in hexadecimal. The string has *nbytes* random " @@ -125,6 +131,14 @@ msgstr "" "bytes aleatórios, cada byte convertido em dois dígitos hexadecimais. Se " "*nbytes* for ``None`` ou não fornecido, um padrão razoável é usado." +#: ../../library/secrets.rst:83 +msgid "" +">>> token_hex(16)\n" +"'f9bf78b9a18ce6d46a0cd2b0b86df9da'" +msgstr "" +">>> token_hex(16)\n" +"'f9bf78b9a18ce6d46a0cd2b0b86df9da'" + #: ../../library/secrets.rst:90 msgid "" "Return a random URL-safe text string, containing *nbytes* random bytes. The " @@ -137,6 +151,14 @@ msgstr "" "byte resulta em aproximadamente 1,3 caracteres. Se *nbytes* for ``None`` ou " "não fornecido, um padrão razoável é usado." +#: ../../library/secrets.rst:95 +msgid "" +">>> token_urlsafe(16)\n" +"'Drmhze6EPcv0fN_81Bj-nA'" +msgstr "" +">>> token_urlsafe(16)\n" +"'Drmhze6EPcv0fN_81Bj-nA'" + #: ../../library/secrets.rst:102 msgid "How many bytes should tokens use?" msgstr "Quantos bytes os tokens devem usar?" @@ -222,6 +244,18 @@ msgstr "" msgid "Generate an eight-character alphanumeric password:" msgstr "Gerar uma senha alfanumérica de oito caracteres:" +#: ../../library/secrets.rst:147 +msgid "" +"import string\n" +"import secrets\n" +"alphabet = string.ascii_letters + string.digits\n" +"password = ''.join(secrets.choice(alphabet) for i in range(8))" +msgstr "" +"import string\n" +"import secrets\n" +"alphabet = string.ascii_letters + string.digits\n" +"password = ''.join(secrets.choice(alphabet) for i in range(8))" + #: ../../library/secrets.rst:157 msgid "" "Applications should not :cwe:`store passwords in a recoverable format " @@ -241,10 +275,48 @@ msgstr "" "Gerar uma senha alfanumérica de dez caracteres com pelo menos um caractere " "minúsculo, pelo menos um caractere maiúsculo e pelo menos três dígitos:" +#: ../../library/secrets.rst:167 +msgid "" +"import string\n" +"import secrets\n" +"alphabet = string.ascii_letters + string.digits\n" +"while True:\n" +" password = ''.join(secrets.choice(alphabet) for i in range(10))\n" +" if (any(c.islower() for c in password)\n" +" and any(c.isupper() for c in password)\n" +" and sum(c.isdigit() for c in password) >= 3):\n" +" break" +msgstr "" +"import string\n" +"import secrets\n" +"alphabet = string.ascii_letters + string.digits\n" +"while True:\n" +" password = ''.join(secrets.choice(alphabet) for i in range(10))\n" +" if (any(c.islower() for c in password)\n" +" and any(c.isupper() for c in password)\n" +" and sum(c.isdigit() for c in password) >= 3):\n" +" break" + #: ../../library/secrets.rst:180 msgid "Generate an `XKCD-style passphrase `_:" msgstr "Gerar uma senha longa do estilo `XKCD `_:" +#: ../../library/secrets.rst:182 +msgid "" +"import secrets\n" +"# On standard Linux systems, use a convenient dictionary file.\n" +"# Other platforms may need to provide their own word-list.\n" +"with open('/usr/share/dict/words') as f:\n" +" words = [word.strip() for word in f]\n" +" password = ' '.join(secrets.choice(words) for i in range(4))" +msgstr "" +"import secrets\n" +"# Em sistemas Linux padrão, use um arquivo de dicionário conveniente.\n" +"# Outras plataformas podem precisar fornecer sua própria lista de palavras.\n" +"with open('/usr/share/dict/words') as f:\n" +" words = [word.strip() for word in f]\n" +" password = ' '.join(secrets.choice(words) for i in range(4))" + #: ../../library/secrets.rst:192 msgid "" "Generate a hard-to-guess temporary URL containing a security token suitable " @@ -252,3 +324,11 @@ msgid "" msgstr "" "Gerar uma URL temporária difícil de adivinhação contendo um token de " "segurança adequado para aplicativos de recuperação de senha:" + +#: ../../library/secrets.rst:195 +msgid "" +"import secrets\n" +"url = 'https://example.com/reset=' + secrets.token_urlsafe()" +msgstr "" +"import secrets\n" +"url = 'https://example.com/reset=' + secrets.token_urlsafe()" diff --git a/library/security_warnings.po b/library/security_warnings.po index ce51f2d9b..a6576008f 100644 --- a/library/security_warnings.po +++ b/library/security_warnings.po @@ -1,31 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 02:33+0000\n" -"PO-Revision-Date: 2021-08-10 13:22+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/security_warnings.rst:6 msgid "Security Considerations" -msgstr "Considerações de segurança" +msgstr "Considerações de Segurança" #: ../../library/security_warnings.rst:8 msgid "The following modules have specific security considerations:" diff --git a/library/select.po b/library/select.po index afbb29474..7538c6f1a 100644 --- a/library/select.po +++ b/library/select.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Welington Carlos , 2021 -# Sheila Gomes , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Hemílio Lauro , 2021 -# Marco Rougeth , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-02 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:12+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -64,9 +58,9 @@ msgstr "" "usuários são encorajados a usar o módulo :mod:`selectors` em vez disso, a " "menos que queiram controle preciso sobre as primitivas de nível de SO usadas." -#: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +#: ../../library/select.rst:177 ../../includes/wasm-notavail.rst:3 +msgid "Availability" +msgstr "Disponibilidade" #: ../../includes/wasm-notavail.rst:5 msgid "" @@ -270,10 +264,6 @@ msgstr "" msgid "This value is guaranteed by POSIX to be at least 512." msgstr "" -#: ../../library/select.rst:177 -msgid ":ref:`Availability `: Unix" -msgstr ":ref:`Disponibilidade `: Unix" - #: ../../library/select.rst:185 msgid "``/dev/poll`` Polling Objects" msgstr "" @@ -1041,7 +1031,7 @@ msgstr "" #: ../../library/select.rst:141 msgid "popen() (in module os)" -msgstr "" +msgstr "popen() (no módulo os)" #: ../../library/select.rst:154 msgid "WinSock" diff --git a/library/selectors.po b/library/selectors.po index b26f893d8..09b0f44d5 100644 --- a/library/selectors.po +++ b/library/selectors.po @@ -1,32 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Marco Rougeth , 2021 -# Welington Carlos , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Ruan Aragão , 2021 -# Hemílio Lauro , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:12+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-28 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -83,8 +76,8 @@ msgid "Low-level I/O multiplexing module." msgstr "" #: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +msgid "Availability" +msgstr "Disponibilidade" #: ../../includes/wasm-notavail.rst:5 msgid "" @@ -102,6 +95,16 @@ msgstr "Classes" msgid "Classes hierarchy::" msgstr "" +#: ../../library/selectors.rst:48 +msgid "" +"BaseSelector\n" +"+-- SelectSelector\n" +"+-- PollSelector\n" +"+-- EpollSelector\n" +"+-- DevpollSelector\n" +"+-- KqueueSelector" +msgstr "" + #: ../../library/selectors.rst:56 msgid "" "In the following, *events* is a bitwise mask indicating which I/O events " @@ -163,36 +166,36 @@ msgid "" "implementations support the :term:`context manager` protocol." msgstr "" -#: ../../library/selectors.rst:108 +#: ../../library/selectors.rst:109 msgid "Register a file object for selection, monitoring it for I/O events." msgstr "" "Registra um objeto arquivo para seleção, monitorando-o para eventos de I/O" -#: ../../library/selectors.rst:110 +#: ../../library/selectors.rst:111 msgid "" "*fileobj* is the file object to monitor. It may either be an integer file " "descriptor or an object with a ``fileno()`` method. *events* is a bitwise " "mask of events to monitor. *data* is an opaque object." msgstr "" -#: ../../library/selectors.rst:115 +#: ../../library/selectors.rst:116 msgid "" "This returns a new :class:`SelectorKey` instance, or raises a :exc:" "`ValueError` in case of invalid event mask or file descriptor, or :exc:" "`KeyError` if the file object is already registered." msgstr "" -#: ../../library/selectors.rst:121 +#: ../../library/selectors.rst:123 msgid "" "Unregister a file object from selection, removing it from monitoring. A file " "object shall be unregistered prior to being closed." msgstr "" -#: ../../library/selectors.rst:124 +#: ../../library/selectors.rst:126 msgid "*fileobj* must be a file object previously registered." msgstr "" -#: ../../library/selectors.rst:126 +#: ../../library/selectors.rst:128 msgid "" "This returns the associated :class:`SelectorKey` instance, or raises a :exc:" "`KeyError` if *fileobj* is not registered. It will raise :exc:`ValueError` " @@ -200,30 +203,30 @@ msgid "" "``fileno()`` method has an invalid return value)." msgstr "" -#: ../../library/selectors.rst:133 +#: ../../library/selectors.rst:135 msgid "Change a registered file object's monitored events or attached data." msgstr "" -#: ../../library/selectors.rst:135 +#: ../../library/selectors.rst:137 msgid "" "This is equivalent to ``BaseSelector.unregister(fileobj)`` followed by " "``BaseSelector.register(fileobj, events, data)``, except that it can be " "implemented more efficiently." msgstr "" -#: ../../library/selectors.rst:139 +#: ../../library/selectors.rst:141 msgid "" "This returns a new :class:`SelectorKey` instance, or raises a :exc:" "`ValueError` in case of invalid event mask or file descriptor, or :exc:" "`KeyError` if the file object is not registered." msgstr "" -#: ../../library/selectors.rst:145 +#: ../../library/selectors.rst:148 msgid "" "Wait until some registered file objects become ready, or the timeout expires." msgstr "" -#: ../../library/selectors.rst:148 +#: ../../library/selectors.rst:151 msgid "" "If ``timeout > 0``, this specifies the maximum wait time, in seconds. If " "``timeout <= 0``, the call won't block, and will report the currently ready " @@ -231,26 +234,26 @@ msgid "" "monitored file object becomes ready." msgstr "" -#: ../../library/selectors.rst:154 +#: ../../library/selectors.rst:157 msgid "" "This returns a list of ``(key, events)`` tuples, one for each ready file " "object." msgstr "" -#: ../../library/selectors.rst:157 +#: ../../library/selectors.rst:160 msgid "" "*key* is the :class:`SelectorKey` instance corresponding to a ready file " "object. *events* is a bitmask of events ready on this file object." msgstr "" -#: ../../library/selectors.rst:162 +#: ../../library/selectors.rst:165 msgid "" "This method can return before any file object becomes ready or the timeout " "has elapsed if the current process receives a signal: in this case, an empty " "list will be returned." msgstr "" -#: ../../library/selectors.rst:166 +#: ../../library/selectors.rst:169 msgid "" "The selector is now retried with a recomputed timeout when interrupted by a " "signal if the signal handler did not raise an exception (see :pep:`475` for " @@ -258,85 +261,121 @@ msgid "" "timeout." msgstr "" -#: ../../library/selectors.rst:174 +#: ../../library/selectors.rst:177 msgid "Close the selector." msgstr "" -#: ../../library/selectors.rst:176 +#: ../../library/selectors.rst:179 msgid "" "This must be called to make sure that any underlying resource is freed. The " "selector shall not be used once it has been closed." msgstr "" -#: ../../library/selectors.rst:181 +#: ../../library/selectors.rst:184 msgid "Return the key associated with a registered file object." msgstr "" -#: ../../library/selectors.rst:183 +#: ../../library/selectors.rst:186 msgid "" "This returns the :class:`SelectorKey` instance associated to this file " "object, or raises :exc:`KeyError` if the file object is not registered." msgstr "" -#: ../../library/selectors.rst:188 +#: ../../library/selectors.rst:192 msgid "Return a mapping of file objects to selector keys." msgstr "" -#: ../../library/selectors.rst:190 +#: ../../library/selectors.rst:194 msgid "" "This returns a :class:`~collections.abc.Mapping` instance mapping registered " "file objects to their associated :class:`SelectorKey` instance." msgstr "" -#: ../../library/selectors.rst:197 +#: ../../library/selectors.rst:201 msgid "" "The default selector class, using the most efficient implementation " "available on the current platform. This should be the default choice for " "most users." msgstr "" -#: ../../library/selectors.rst:204 +#: ../../library/selectors.rst:208 msgid ":func:`select.select`-based selector." msgstr "" -#: ../../library/selectors.rst:209 +#: ../../library/selectors.rst:213 msgid ":func:`select.poll`-based selector." msgstr "" -#: ../../library/selectors.rst:214 +#: ../../library/selectors.rst:218 msgid ":func:`select.epoll`-based selector." msgstr "" -#: ../../library/selectors.rst:218 +#: ../../library/selectors.rst:222 msgid "" "This returns the file descriptor used by the underlying :func:`select.epoll` " "object." msgstr "" -#: ../../library/selectors.rst:223 +#: ../../library/selectors.rst:227 msgid ":func:`select.devpoll`-based selector." msgstr "" -#: ../../library/selectors.rst:227 +#: ../../library/selectors.rst:231 msgid "" "This returns the file descriptor used by the underlying :func:`select." "devpoll` object." msgstr "" -#: ../../library/selectors.rst:234 +#: ../../library/selectors.rst:238 msgid ":func:`select.kqueue`-based selector." msgstr "" -#: ../../library/selectors.rst:238 +#: ../../library/selectors.rst:242 msgid "" "This returns the file descriptor used by the underlying :func:`select." "kqueue` object." msgstr "" -#: ../../library/selectors.rst:243 +#: ../../library/selectors.rst:247 msgid "Examples" msgstr "Exemplos" -#: ../../library/selectors.rst:245 +#: ../../library/selectors.rst:249 msgid "Here is a simple echo server implementation::" msgstr "" + +#: ../../library/selectors.rst:251 +msgid "" +"import selectors\n" +"import socket\n" +"\n" +"sel = selectors.DefaultSelector()\n" +"\n" +"def accept(sock, mask):\n" +" conn, addr = sock.accept() # Should be ready\n" +" print('accepted', conn, 'from', addr)\n" +" conn.setblocking(False)\n" +" sel.register(conn, selectors.EVENT_READ, read)\n" +"\n" +"def read(conn, mask):\n" +" data = conn.recv(1000) # Should be ready\n" +" if data:\n" +" print('echoing', repr(data), 'to', conn)\n" +" conn.send(data) # Hope it won't block\n" +" else:\n" +" print('closing', conn)\n" +" sel.unregister(conn)\n" +" conn.close()\n" +"\n" +"sock = socket.socket()\n" +"sock.bind(('localhost', 1234))\n" +"sock.listen(100)\n" +"sock.setblocking(False)\n" +"sel.register(sock, selectors.EVENT_READ, accept)\n" +"\n" +"while True:\n" +" events = sel.select()\n" +" for key, mask in events:\n" +" callback = key.data\n" +" callback(key.fileobj, mask)" +msgstr "" diff --git a/library/shelve.po b/library/shelve.po index 953b7610a..45cbc7d17 100644 --- a/library/shelve.po +++ b/library/shelve.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# And Past , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2022 -# Marco Rougeth , 2023 -# Claudio Rogerio Carvalho Filho , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:12+0000\n" -"Last-Translator: Claudio Rogerio Carvalho Filho , " -"2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -94,6 +89,12 @@ msgid "" "`shelve.open` as a context manager::" msgstr "" +#: ../../library/shelve.rst:57 +msgid "" +"with shelve.open('spam') as db:\n" +" db['eggs'] = 'eggs'" +msgstr "" + #: ../../library/shelve.rst:64 msgid "" "Because the :mod:`shelve` module is backed by :mod:`pickle`, it is insecure " @@ -242,6 +243,39 @@ msgid "" "object)::" msgstr "" +#: ../../library/shelve.rst:185 +msgid "" +"import shelve\n" +"\n" +"d = shelve.open(filename) # open -- file may get suffix added by low-level\n" +" # library\n" +"\n" +"d[key] = data # store data at key (overwrites old data if\n" +" # using an existing key)\n" +"data = d[key] # retrieve a COPY of data at key (raise KeyError\n" +" # if no such key)\n" +"del d[key] # delete data stored at key (raises KeyError\n" +" # if no such key)\n" +"\n" +"flag = key in d # true if the key exists\n" +"klist = list(d.keys()) # a list of all existing keys (slow!)\n" +"\n" +"# as d was opened WITHOUT writeback=True, beware:\n" +"d['xx'] = [0, 1, 2] # this works as expected, but...\n" +"d['xx'].append(3) # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]!\n" +"\n" +"# having opened d without writeback=True, you need to code carefully:\n" +"temp = d['xx'] # extracts the copy\n" +"temp.append(5) # mutates the copy\n" +"d['xx'] = temp # stores the copy right back, to persist it\n" +"\n" +"# or, d=shelve.open(filename,writeback=True) would let you just code\n" +"# d['xx'].append(5) and have it work as expected, BUT it would also\n" +"# consume more memory and make the d.close() operation slower.\n" +"\n" +"d.close() # close it" +msgstr "" + #: ../../library/shelve.rst:218 msgid "Module :mod:`dbm`" msgstr "Módulo :mod:`dbm`" @@ -268,8 +302,8 @@ msgstr "pickle" #: ../../library/shelve.rst:97 msgid "dbm.ndbm" -msgstr "" +msgstr "dbm.ndbm" #: ../../library/shelve.rst:97 msgid "dbm.gnu" -msgstr "" +msgstr "dbm.gnu" diff --git a/library/shlex.po b/library/shlex.po index 5df1c5837..76b52dbc5 100644 --- a/library/shlex.po +++ b/library/shlex.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:13+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -484,6 +483,21 @@ msgid "" "following snippet:" msgstr "" +#: ../../library/shlex.rst:412 +msgid "" +">>> import shlex\n" +">>> text = \"a && b; c && d || e; f >'abc'; (def \\\"ghi\\\")\"\n" +">>> s = shlex.shlex(text, posix=True)\n" +">>> s.whitespace_split = True\n" +">>> list(s)\n" +"['a', '&&', 'b;', 'c', '&&', 'd', '||', 'e;', 'f', '>abc;', '(def', 'ghi)']\n" +">>> s = shlex.shlex(text, posix=True, punctuation_chars=True)\n" +">>> s.whitespace_split = True\n" +">>> list(s)\n" +"['a', '&&', 'b', ';', 'c', '&&', 'd', '||', 'e', ';', 'f', '>', 'abc', ';',\n" +"'(', 'def', 'ghi', ')']" +msgstr "" + #: ../../library/shlex.rst:427 msgid "" "Of course, tokens will be returned which are not valid for shells, and " @@ -497,6 +511,14 @@ msgid "" "used to determine which characters constitute punctuation. For example::" msgstr "" +#: ../../library/shlex.rst:434 +msgid "" +">>> import shlex\n" +">>> s = shlex.shlex(\"a && b || c\", punctuation_chars=\"|\")\n" +">>> list(s)\n" +"['a', '&', '&', 'b', '||', 'c']" +msgstr "" + #: ../../library/shlex.rst:439 msgid "" "When ``punctuation_chars`` is specified, the :attr:`~shlex.wordchars` " @@ -505,6 +527,15 @@ msgid "" "line arguments (e.g. ``--color=auto``). Hence::" msgstr "" +#: ../../library/shlex.rst:444 +msgid "" +">>> import shlex\n" +">>> s = shlex.shlex('~/a && b-c --color=auto || d *.py?',\n" +"... punctuation_chars=True)\n" +">>> list(s)\n" +"['~/a', '&&', 'b-c', '--color=auto', '||', 'd', '*.py?']" +msgstr "" + #: ../../library/shlex.rst:450 msgid "" "However, to match the shell as closely as possible, it is recommended to " diff --git a/library/shutil.po b/library/shutil.po index 224525cef..2e875068d 100644 --- a/library/shutil.po +++ b/library/shutil.po @@ -1,33 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:13+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-16 14:58+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/shutil.rst:2 msgid ":mod:`!shutil` --- High-level file operations" -msgstr "" +msgstr ":mod:`!shutil` --- Operações de arquivo de alto nível" #: ../../library/shutil.rst:10 msgid "**Source code:** :source:`Lib/shutil.py`" @@ -82,6 +80,14 @@ msgid "" "file position of the *fsrc* object is not 0, only the contents from the " "current file position to the end of the file will be copied." msgstr "" +"Copia o conteúdo do :term:`objeto arquivo ou similar ` *fsrc* " +"para o objeto arquivo ou similar *fdst*. O número inteiro *length*, se " +"fornecido, é o tamanho do buffer. Em particular, um valor negativo *length* " +"significa copiar os dados sem repetir os dados de origem em pedaços; por " +"padrão, os dados são lidos em pedaços para evitar o consumo descontrolado de " +"memória. Observe que, se a posição atual do arquivo do objeto *fsrc* não for " +"0, apenas o conteúdo da posição atual do arquivo até o final do arquivo será " +"copiado." #: ../../library/shutil.rst:53 msgid "" @@ -90,6 +96,10 @@ msgid "" "are :term:`path-like objects ` or path names given as " "strings." msgstr "" +"Copia o conteúdo (sem metadados) do arquivo chamado *src* para um arquivo " +"chamado *dst* e retorna *dst* da maneira mais eficiente possível. *src* e " +"*dst* são :term:`objetos caminho ou similar ` ou nomes de " +"caminhos dados como strings." #: ../../library/shutil.rst:57 msgid "" @@ -179,6 +189,15 @@ msgid "" "links on the local platform, and it is asked to do so, it will do nothing " "and return." msgstr "" +"Copia os bits de permissão de *src* para *dst*. O conteúdo do arquivo, o " +"proprietário e o grupo não são afetados. *src* e *dst* são :term:`objetos " +"caminho ou similar ` ou nomes de caminhos dados como " +"strings. Se *follow_symlinks* for falso e *src* e *dst* forem links " +"simbólicos, :func:`copymode` tentará modificar o modo do *dst* (e não o " +"arquivo para o qual ele aponta). Essa funcionalidade não está disponível em " +"todas as plataformas; veja :func:`copystat` para mais informações. Se :func:" +"`copymode` não puder modificar links simbólicos na plataforma local, e for " +"solicitado a fazê-lo, não fará nada e retornará." #: ../../library/shutil.rst:106 ../../library/shutil.rst:179 msgid "" @@ -200,6 +219,12 @@ msgid "" "are unaffected. *src* and *dst* are :term:`path-like objects ` or path names given as strings." msgstr "" +"Copia os bits de permissão, hora do último acesso, hora da última " +"modificação e sinalizadores de *src* para *dst*. No Linux, :func:`copystat` " +"também copia os \"atributos estendidos\" sempre que possível. O conteúdo do " +"arquivo, o proprietário e o grupo não são afetados. *src* e *dst* são :term:" +"`objetos caminho ou similar ` ou nomes de caminhos dados " +"como strings." #: ../../library/shutil.rst:119 msgid "" @@ -287,6 +312,11 @@ msgid "" "filename from *src*. If *dst* specifies a file that already exists, it will " "be replaced. Returns the path to the newly created file." msgstr "" +"Copia o arquivo *src* para o arquivo ou diretório *dst*. *src* e *dst* devem " +"ser :term:`objetos arquivo ou similares ` ou strings. Se " +"*dst* especificar um diretório, o arquivo será copiado para *dst* usando o " +"nome de arquivo base de *src*. Se *dst* especifica um arquivo que já existe, " +"ele será substituído. Retorna o caminho para o arquivo recém-criado." #: ../../library/shutil.rst:166 msgid "" @@ -335,6 +365,13 @@ msgid "" "unavailable, :func:`copy2` will preserve all the metadata it can; :func:" "`copy2` never raises an exception because it cannot preserve file metadata." msgstr "" +"Quando *follow_symlinks* for falso e *src* for um link simbólico, :func:" +"`copy2` tenta copiar todos os metadados do link simbólico *src* para o link " +"simbólico *dst* recém-criado. No entanto, essa funcionalidade não está " +"disponível em todas as plataformas. Nas plataformas em que algumas ou todas " +"essas funcionalidades não estão disponíveis, :func:`copy2` preservará todos " +"os metadados que puder; :func:`copy2` nunca levanta uma exceção porque não " +"pode preservar os metadados do arquivo." #: ../../library/shutil.rst:204 msgid "" @@ -373,6 +410,10 @@ msgid "" "named *dst* and return the destination directory. All intermediate " "directories needed to contain *dst* will also be created by default." msgstr "" +"Copia recursivamente uma árvore de diretórios inteira com raiz em *src* para " +"um diretório chamado *dst* e retorna o diretório de destino. Todos os " +"diretórios intermediários necessários para conter *dst* também serão criados " +"por padrão." #: ../../library/shutil.rst:237 msgid "" @@ -404,6 +445,12 @@ msgid "" "exception. Notice that this option has no effect on platforms that don't " "support :func:`os.symlink`." msgstr "" +"Quando *symlinks* for falso, se o arquivo apontado pelo link simbólico não " +"existir, uma exceção será adicionada na lista de erros levantada em uma " +"exceção :exc:`Error` no final do processo de cópia. Você pode definir o " +"sinalizador opcional *ignore_dangling_symlinks* como true se desejar " +"silenciar esta exceção. Observe que esta opção não tem efeito em plataformas " +"que não possuem suporte a :func:`os.symlink`." #: ../../library/shutil.rst:252 msgid "" @@ -455,6 +502,11 @@ msgid "" "within the *dst* tree will be overwritten by corresponding files from the " "*src* tree." msgstr "" +"Se *dirs_exist_ok* for false (o padrão) e *dst* já existir, uma :exc:" +"`FileExistsError` será levantada. Se *dirs_exist_ok* for true, a operação de " +"cópia continuará se encontrar diretórios existentes, e os arquivos dentro da " +"árvore *dst* serão sobrescritos pelos arquivos correspondentes da árvore " +"*src*." #: ../../library/shutil.rst:275 msgid "" @@ -470,6 +522,9 @@ msgid "" "function. Added the *ignore_dangling_symlinks* argument to silence dangling " "symlinks errors when *symlinks* is false." msgstr "" +"Adicionado o argumento *copy_function* para poder fornecer uma função de " +"cópia personalizada. Adicionado o argumento *ignore_dangling_symlinks* para " +"silenciar erros de links simbólicos quando *symlinks* for falso." #: ../../library/shutil.rst:283 msgid "Copy metadata when *symlinks* is false. Now returns *dst*." @@ -477,7 +532,7 @@ msgstr "Copia metadados quando *symlinks* for falso. Agora, retorna *dst*." #: ../../library/shutil.rst:292 msgid "Added the *dirs_exist_ok* parameter." -msgstr "" +msgstr "Adicionado o parâmetro *dirs_exist_ok*." #: ../../library/shutil.rst:299 msgid "" @@ -487,6 +542,12 @@ msgid "" "handled by calling a handler specified by *onexc* or *onerror* or, if both " "are omitted, exceptions are propagated to the caller." msgstr "" +"Exclui uma árvore de diretório inteira; *path* deve apontar para um " +"diretório (mas não um link simbólico para um diretório). Se *ignore_errors* " +"for verdadeiro, os erros resultantes de remoções com falha serão ignorados; " +"se falso ou omitido, tais erros são tratados chamando um manipulador " +"especificado por *onexc* ou *onerror* ou, se ambos forem omitidos, exceções " +"são propagadas para o chamador." #: ../../library/shutil.rst:305 msgid "" @@ -520,6 +581,8 @@ msgid "" "If *onexc* is provided, it must be a callable that accepts three parameters: " "*function*, *path*, and *excinfo*." msgstr "" +"Se *onexc* for fornecido, deve ser um chamável que aceite três parâmetros: " +"*function*, *path*, e *excinfo*." #: ../../library/shutil.rst:321 msgid "" @@ -529,12 +592,19 @@ msgid "" "*excinfo*, is the exception that was raised. Exceptions raised by *onexc* " "will not be caught." msgstr "" +"O primeiro parâmetro, *function*, é a função que levantou a exceção; depende " +"da plataforma e da implementação. O segundo parâmetro, *path*, será o nome " +"do caminho passado para a *função*. O terceiro parâmetro, *excinfo*, é a " +"exceção que foi levantada. Exceções levantadas por *onexc* não serão " +"capturadas." #: ../../library/shutil.rst:327 msgid "" "The deprecated *onerror* is similar to *onexc*, except that the third " "parameter it receives is the tuple returned from :func:`sys.exc_info`." msgstr "" +"O descontinuado *onerror* é semelhante ao *onexc*, exceto que o terceiro " +"parâmetro que ele recebe é a tupla retornada de :func:`sys.exc_info`." #: ../../library/shutil.rst:330 msgid "" @@ -567,7 +637,7 @@ msgstr "Adicionado o parâmetro *dir_fd*." #: ../../library/shutil.rst:343 msgid "Added the *onexc* parameter, deprecated *onerror*." -msgstr "" +msgstr "Adicionado o parâmetro *onexc*, descontinuado *onerror*." #: ../../library/shutil.rst:346 msgid "" @@ -575,6 +645,9 @@ msgid "" "the top-level path. Exceptions other than :exc:`OSError` and subclasses of :" "exc:`!OSError` are now always propagated to the caller." msgstr "" +":func:`!rmtree` agora ignora exceções :exc:`FileNotFoundError` para todos, " +"exceto o caminho de nível superior. Exceções diferentes de :exc:`OSError` e " +"subclasses de :exc:`!OSError` agora são sempre propagadas para o chamador." #: ../../library/shutil.rst:354 msgid "" @@ -592,6 +665,8 @@ msgid "" "Recursively move a file or directory (*src*) to another location and return " "the destination." msgstr "" +"Move recursivamente um arquivo ou diretório (*src*) para outro local e " +"retorna ao destino." #: ../../library/shutil.rst:366 msgid "" @@ -599,12 +674,17 @@ msgid "" "moved inside that directory. The destination path in that directory must not " "already exist." msgstr "" +"Se *dst* for um diretório existente ou um symlink para um diretório, então " +"*src* é movido para dentro desse diretório. O caminho de destino nesse " +"diretório não deve existir ainda." #: ../../library/shutil.rst:370 msgid "" "If *dst* already exists but is not a directory, it may be overwritten " "depending on :func:`os.rename` semantics." msgstr "" +"Se *dst* já existir, mas não for um diretório, ele poderá ser substituído " +"dependendo da semântica de :func:`os.rename`." #: ../../library/shutil.rst:373 msgid "" @@ -613,6 +693,11 @@ msgid "" "and then removed. In case of symlinks, a new symlink pointing to the target " "of *src* will be created as the destination and *src* will be removed." msgstr "" +"Se o destino está no sistema de arquivos atual, então :func:`os.rename` é " +"usado. Caso contrário, *src* é copiado para o destino usando *copy_function* " +"e depois removido. No caso de links simbólicos, um novo link simbólico " +"apontando para o destino de *src* será criado como o destino e *src* serão " +"removidos." #: ../../library/shutil.rst:378 msgid "" @@ -624,6 +709,14 @@ msgid "" "*copy_function* allows the move to succeed when it is not possible to also " "copy the metadata, at the expense of not copying any of the metadata." msgstr "" +"Se *copy_function* for fornecido, deve ser um chamável que leva dois " +"argumentos *src* e a destinação, e será usado para copiar *src* para a " +"destinação se :func:`os.rename` não puder ser usado. Se a fonte for um " +"diretório, :func:`copytree` é chamado, passando *copy_function*. A " +"*copy_function* padrão é :func:`copy2`. Usar :func:`~shutil.copy` como " +"*copy_function* permite que a movimentação seja bem-sucedida quando não é " +"possível copiar também os metadados, às custas de não copiar nenhum dos " +"metadados." #: ../../library/shutil.rst:386 msgid "" @@ -667,14 +760,18 @@ msgid "" "filesystem partition. On those platforms, CPython doesn't attempt to " "retrieve disk usage information from non-mounted filesystems." msgstr "" +"Em sistemas de arquivos Unix, *path* deve apontar para um caminho dentro de " +"uma partição de sistema de arquivos **montada**. Nessas plataformas, o " +"CPython não tenta recuperar informações de uso de disco de sistemas de " +"arquivos não montados." #: ../../library/shutil.rst:419 msgid "On Windows, *path* can now be a file or directory." msgstr "No Windows, *path* pode agora ser um arquivo ou diretório." -#: ../../library/shutil.rst:422 -msgid ":ref:`Availability `: Unix, Windows." -msgstr ":ref:`Disponibilidade `: Unix, Windows." +#: ../../library/shutil.rst:422 ../../library/shutil.rst:436 +msgid "Availability" +msgstr "Disponibilidade" #: ../../library/shutil.rst:427 msgid "Change owner *user* and/or *group* of the given *path*." @@ -700,13 +797,9 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``shutil.chown`` com os " "argumentos ``path``, ``user``, ``group``." -#: ../../library/shutil.rst:436 -msgid ":ref:`Availability `: Unix." -msgstr ":ref:`Disponibilidade `: Unix." - #: ../../library/shutil.rst:440 msgid "Added *dir_fd* and *follow_symlinks* parameters." -msgstr "" +msgstr "Adicionados os parâmetros *dir_fd* e *follow_symlinks*." #: ../../library/shutil.rst:446 msgid "" @@ -721,15 +814,32 @@ msgid "" "*mode* is a permission mask passed to :func:`os.access`, by default " "determining if the file exists and is executable." msgstr "" +"*mode* é uma máscara de permissão passada para :func:`os.access`, por padrão " +"determinando se o arquivo existe e é executável." #: ../../library/shutil.rst:452 msgid "" -"*path* is a \"``PATH`` string\" specifying the lookup directory list. When " -"no *path* is specified, the results of :func:`os.environ` are used, " -"returning either the \"PATH\" value or a fallback of :data:`os.defpath`." +"*path* is a \"``PATH`` string\" specifying the directories to look in, " +"delimited by :data:`os.pathsep`. When no *path* is specified, the :envvar:" +"`PATH` environment variable is read from :data:`os.environ`, falling back " +"to :data:`os.defpath` if it is not set." +msgstr "" +"*path* é uma \"string ``PATH``\" que especifica os diretórios a serem " +"procurados, delimitados por :data:`os.pathsep`. Quando nenhum *path* é " +"especificado, a variável de ambiente :envvar:`PATH` é lida de :data:`os." +"environ`, retornando para :data:`os.defpath` se não estiver definida." + +#: ../../library/shutil.rst:457 +msgid "" +"If *cmd* contains a directory component, :func:`!which` only checks the " +"specified path directly and does not search the directories listed in *path* " +"or in the system's :envvar:`PATH` environment variable." msgstr "" +"Se *cmd* contiver um componente de diretório, :func:`!which` verificará " +"apenas o caminho especificado diretamente e não pesquisará os diretórios " +"listados em *path* ou na variável de ambiente :envvar:`PATH` do sistema." -#: ../../library/shutil.rst:456 +#: ../../library/shutil.rst:461 msgid "" "On Windows, the current directory is prepended to the *path* if *mode* does " "not include ``os.X_OK``. When the *mode* does include ``os.X_OK``, the " @@ -738,31 +848,60 @@ msgid "" "consulting the current working directory for executables: set the " "environment variable ``NoDefaultCurrentDirectoryInExePath``." msgstr "" +"No Windows, o diretório atual é prefixado ao *path* se o *mode* não incluir " +"``os.X_OK``. Quando o *mode* inclui ``os.X_OK``, a API do Windows " +"``NeedCurrentDirectoryForExePathW`` será consultada para determinar se o " +"diretório atual deve ser prefixado ao *path*. Para evitar consultar o " +"diretório de trabalho atual para executáveis: defina a variável de ambiente " +"``NoDefaultCurrentDirectoryInExePath``." + +#: ../../library/shutil.rst:468 +msgid "" +"Also on Windows, the :envvar:`PATHEXT` environment variable is used to " +"resolve commands that may not already include an extension. For example, if " +"you call ``shutil.which(\"python\")``, :func:`which` will search ``PATHEXT`` " +"to know that it should look for ``python.exe`` within the *path* " +"directories. For example, on Windows::" +msgstr "" +"Também no Windows, a variável de ambiente :envvar:`PATHEXT` é usada para " +"resolver comandos que podem não incluir uma extensão. Por exemplo, se você " +"chamar ``shutil.which(\"python\")``, :func:`which` pesquisará ``PATHEXT`` " +"para saber que deve procurar por ``python.exe`` dentro dos diretórios " +"*path*. Por exemplo, no Windows::" -#: ../../library/shutil.rst:463 +#: ../../library/shutil.rst:474 msgid "" -"Also on Windows, the ``PATHEXT`` variable is used to resolve commands that " -"may not already include an extension. For example, if you call ``shutil." -"which(\"python\")``, :func:`which` will search ``PATHEXT`` to know that it " -"should look for ``python.exe`` within the *path* directories. For example, " -"on Windows::" +">>> shutil.which(\"python\")\n" +"'C:\\\\Python33\\\\python.EXE'" msgstr "" +">>> shutil.which(\"python\")\n" +"'C:\\\\Python33\\\\python.EXE'" -#: ../../library/shutil.rst:472 +#: ../../library/shutil.rst:477 msgid "" "This is also applied when *cmd* is a path that contains a directory " "component::" msgstr "" +"Isso também se aplica quando *cmd* é um caminho que contém um componente de " +"diretório::" #: ../../library/shutil.rst:480 msgid "" +">>> shutil.which(\"C:\\\\Python33\\\\python\")\n" +"'C:\\\\Python33\\\\python.EXE'" +msgstr "" +">>> shutil.which(\"C:\\\\Python33\\\\python\")\n" +"'C:\\\\Python33\\\\python.EXE'" + +#: ../../library/shutil.rst:485 +msgid "" "The :class:`bytes` type is now accepted. If *cmd* type is :class:`bytes`, " "the result type is also :class:`bytes`." msgstr "" "O tipo :class:`bytes` é agora aceitado. Se o tipo de *cmd* é :class:`bytes`, " "o tipo resultante também é :class:`bytes`." -#: ../../library/shutil.rst:484 +#: ../../library/shutil.rst:489 msgid "" "On Windows, the current directory is no longer prepended to the search path " "if *mode* includes ``os.X_OK`` and WinAPI " @@ -772,15 +911,15 @@ msgid "" "extension that is in ``PATHEXT``; and filenames that have no extension can " "now be found." msgstr "" +"No Windows, o diretório atual não é mais adicionado ao caminho de pesquisa " +"se *mode* incluir ``os.X_OK`` e WinAPI " +"``NeedCurrentDirectoryForExePathW(cmd)`` for falso, caso contrário, o " +"diretório atual será adicionado mesmo se já estiver no caminho de pesquisa; " +"``PATHEXT`` agora é usado mesmo quando *cmd* inclui um componente de " +"diretório ou termina com uma extensão que está em ``PATHEXT``; e nomes de " +"arquivos que não têm extensão agora podem ser encontrados." -#: ../../library/shutil.rst:493 -msgid "" -"On Windows, if *mode* includes ``os.X_OK``, executables with an extension in " -"``PATHEXT`` will be preferred over executables without a matching extension. " -"This brings behavior closer to that of Python 3.11." -msgstr "" - -#: ../../library/shutil.rst:501 +#: ../../library/shutil.rst:500 msgid "" "This exception collects exceptions that are raised during a multi-file " "operation. For :func:`copytree`, the exception argument is a list of 3-" @@ -790,11 +929,11 @@ msgstr "" "vários arquivos. Para :func:`copytree`, o argumento de exceção é uma lista " "de tuplas de 3 elementos (*srcname*, *dstname*, *exception*)." -#: ../../library/shutil.rst:508 +#: ../../library/shutil.rst:507 msgid "Platform-dependent efficient copy operations" msgstr "Operações de cópia eficientes dependentes da plataforma" -#: ../../library/shutil.rst:510 +#: ../../library/shutil.rst:509 msgid "" "Starting from Python 3.8, all functions involving a file copy (:func:" "`copyfile`, :func:`~shutil.copy`, :func:`copy2`, :func:`copytree`, and :func:" @@ -811,17 +950,17 @@ msgstr "" "do kernel, evitando o uso de buffers de espaço de usuário em Python como em " "\"``outfd.write(infd.read())``\"." -#: ../../library/shutil.rst:518 +#: ../../library/shutil.rst:517 msgid "On macOS `fcopyfile`_ is used to copy the file content (not metadata)." msgstr "" "No macOS, `fcopyfile`_ é usado para copiar o conteúdo do arquivo (não " "metadados)." -#: ../../library/shutil.rst:520 +#: ../../library/shutil.rst:519 msgid "On Linux :func:`os.sendfile` is used." msgstr "No Linux, :func:`os.sendfile` é usado." -#: ../../library/shutil.rst:522 +#: ../../library/shutil.rst:521 msgid "" "On Windows :func:`shutil.copyfile` uses a bigger default buffer size (1 MiB " "instead of 64 KiB) and a :func:`memoryview`-based variant of :func:`shutil." @@ -831,7 +970,7 @@ msgstr "" "MiB ao invés de 64 KiB) e uma variante de :func:`shutil.copyfileobj` baseada " "em :func:`memoryview` é usada." -#: ../../library/shutil.rst:526 +#: ../../library/shutil.rst:525 msgid "" "If the fast-copy operation fails and no data was written in the destination " "file then shutil will silently fallback on using less efficient :func:" @@ -841,15 +980,25 @@ msgstr "" "destino, o shutil irá silenciosamente voltar a usar a função menos " "eficiente :func:`copyfileobj` internamente." -#: ../../library/shutil.rst:535 +#: ../../library/shutil.rst:534 msgid "copytree example" msgstr "Exemplo de copytree" -#: ../../library/shutil.rst:537 +#: ../../library/shutil.rst:536 msgid "An example that uses the :func:`ignore_patterns` helper::" +msgstr "Um exemplo que usa o auxiliar :func:`ignore_patterns`::" + +#: ../../library/shutil.rst:538 +msgid "" +"from shutil import copytree, ignore_patterns\n" +"\n" +"copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))" msgstr "" +"from shutil import copytree, ignore_patterns\n" +"\n" +"copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))" -#: ../../library/shutil.rst:543 +#: ../../library/shutil.rst:542 msgid "" "This will copy everything except ``.pyc`` files and files or directories " "whose name starts with ``tmp``." @@ -857,33 +1006,79 @@ msgstr "" "Isso irá copiar tudo, exceto os arquivos ``.pyc`` e arquivos ou diretórios " "cujo nome começa com ``tmp``." -#: ../../library/shutil.rst:546 +#: ../../library/shutil.rst:545 msgid "Another example that uses the *ignore* argument to add a logging call::" msgstr "" "Outro exemplo que usa o argumento *ignore* para adicionar uma chamada de " "registro::" -#: ../../library/shutil.rst:561 +#: ../../library/shutil.rst:547 +msgid "" +"from shutil import copytree\n" +"import logging\n" +"\n" +"def _logpath(path, names):\n" +" logging.info('Working in %s', path)\n" +" return [] # nothing will be ignored\n" +"\n" +"copytree(source, destination, ignore=_logpath)" +msgstr "" +"from shutil import copytree\n" +"import logging\n" +"\n" +"def _logpath(path, names):\n" +" logging.info('Working in %s', path)\n" +" return [] # nada será ignorado\n" +"\n" +"copytree(source, destination, ignore=_logpath)" + +#: ../../library/shutil.rst:560 msgid "rmtree example" msgstr "exemplo rmtree" -#: ../../library/shutil.rst:563 +#: ../../library/shutil.rst:562 msgid "" "This example shows how to remove a directory tree on Windows where some of " "the files have their read-only bit set. It uses the onexc callback to clear " "the readonly bit and reattempt the remove. Any subsequent failure will " "propagate. ::" msgstr "" - -#: ../../library/shutil.rst:581 +"Este exemplo mostra como remover uma árvore de diretório no Windows onde " +"alguns dos arquivos têm seu conjunto de bits somente leitura. Ele usa a " +"função de retorno onexc para limpar o bit somente leitura e tentar remover " +"novamente. Qualquer falha subsequente se propagará. ::" + +#: ../../library/shutil.rst:567 +msgid "" +"import os, stat\n" +"import shutil\n" +"\n" +"def remove_readonly(func, path, _):\n" +" \"Clear the readonly bit and reattempt the removal\"\n" +" os.chmod(path, stat.S_IWRITE)\n" +" func(path)\n" +"\n" +"shutil.rmtree(directory, onexc=remove_readonly)" +msgstr "" +"import os, stat\n" +"import shutil\n" +"\n" +"def remove_readonly(func, path, _):\n" +" \"Clear the readonly bit and reattempt the removal\"\n" +" os.chmod(path, stat.S_IWRITE)\n" +" func(path)\n" +"\n" +"shutil.rmtree(directory, onexc=remove_readonly)" + +#: ../../library/shutil.rst:580 msgid "Archiving operations" msgstr "Operações de arquivamento" -#: ../../library/shutil.rst:585 +#: ../../library/shutil.rst:584 msgid "Added support for the *xztar* format." msgstr "Adicionado suporte ao formato *xztar*." -#: ../../library/shutil.rst:589 +#: ../../library/shutil.rst:588 msgid "" "High-level utilities to create and read compressed and archived files are " "also provided. They rely on the :mod:`zipfile` and :mod:`tarfile` modules." @@ -892,25 +1087,31 @@ msgstr "" "também são fornecidos. Eles contam com os módulos :mod:`zipfile` e :mod:" "`tarfile`." -#: ../../library/shutil.rst:594 +#: ../../library/shutil.rst:593 msgid "Create an archive file (such as zip or tar) and return its name." msgstr "Cria um arquivo compactado (como zip ou tar) e retorna seu nome." -#: ../../library/shutil.rst:596 +#: ../../library/shutil.rst:595 msgid "" "*base_name* is the name of the file to create, including the path, minus any " "format-specific extension." msgstr "" +"*base_name* é o nome do arquivo a ser criado, incluindo o caminho, menos " +"qualquer extensão específica do formato." -#: ../../library/shutil.rst:599 +#: ../../library/shutil.rst:598 msgid "" "*format* is the archive format: one of \"zip\" (if the :mod:`zlib` module is " "available), \"tar\", \"gztar\" (if the :mod:`zlib` module is available), " "\"bztar\" (if the :mod:`bz2` module is available), or \"xztar\" (if the :mod:" "`lzma` module is available)." msgstr "" +"*format* é o formato do arquivo: um de \"zip\" (se o módulo :mod:`zlib` " +"estiver disponível), \"tar\", \"gztar\" (se o módulo :mod:`zlib` estiver " +"disponível), \"bztar\" (se o módulo :mod:`bz2` estiver disponível) ou " +"\"xztar\" (se o módulo :mod:`lzma` estiver disponível)." -#: ../../library/shutil.rst:604 +#: ../../library/shutil.rst:603 msgid "" "*root_dir* is a directory that will be the root directory of the archive, " "all paths in the archive will be relative to it; for example, we typically " @@ -920,7 +1121,7 @@ msgstr "" "caminhos no arquivo serão relativos a ele; por exemplo, normalmente chdir em " "*root_dir* antes de criar o arquivo." -#: ../../library/shutil.rst:608 +#: ../../library/shutil.rst:607 msgid "" "*base_dir* is the directory where we start archiving from; i.e. *base_dir* " "will be the common prefix of all files and directories in the archive. " @@ -933,11 +1134,11 @@ msgstr "" "`shutil-archiving-example-with-basedir` para como usar *base_dir* e " "*root_dir* juntos." -#: ../../library/shutil.rst:614 +#: ../../library/shutil.rst:613 msgid "*root_dir* and *base_dir* both default to the current directory." msgstr "*root_dir* e *base_dir* têm com padrão o diretório atual." -#: ../../library/shutil.rst:616 +#: ../../library/shutil.rst:615 msgid "" "If *dry_run* is true, no archive is created, but the operations that would " "be executed are logged to *logger*." @@ -945,7 +1146,7 @@ msgstr "" "Se *dry_run* for verdadeiro, nenhum arquivo é criado, mas as operações que " "seriam executadas são registradas no *logger*." -#: ../../library/shutil.rst:619 +#: ../../library/shutil.rst:618 msgid "" "*owner* and *group* are used when creating a tar archive. By default, uses " "the current owner and group." @@ -953,7 +1154,7 @@ msgstr "" "*owner* e *group* são usados ao criar um arquivo tar. Por padrão, usa o " "proprietário e grupo atuais." -#: ../../library/shutil.rst:622 +#: ../../library/shutil.rst:621 msgid "" "*logger* must be an object compatible with :pep:`282`, usually an instance " "of :class:`logging.Logger`." @@ -961,11 +1162,11 @@ msgstr "" "*logger* deve ser um objeto compatível com a :pep:`282`, geralmente uma " "instância de :class:`logging.Logger`." -#: ../../library/shutil.rst:625 +#: ../../library/shutil.rst:624 msgid "The *verbose* argument is unused and deprecated." msgstr "O argumento *verbose* não é usado e foi descontinuado." -#: ../../library/shutil.rst:627 +#: ../../library/shutil.rst:626 msgid "" "Raises an :ref:`auditing event ` ``shutil.make_archive`` with " "arguments ``base_name``, ``format``, ``root_dir``, ``base_dir``." @@ -973,15 +1174,19 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``shutil.make_archive`` com " "os argumentos ``base_name``, ``format``, ``root_dir``, ``base_dir``." -#: ../../library/shutil.rst:631 +#: ../../library/shutil.rst:630 msgid "" "This function is not thread-safe when custom archivers registered with :func:" "`register_archive_format` do not support the *root_dir* argument. In this " "case it temporarily changes the current working directory of the process to " "*root_dir* to perform archiving." msgstr "" +"Esta função não é segura para thread quando arquivadores personalizados " +"registrados com :func:`register_archive_format` não suportam o argumento " +"*root_dir*. Neste caso, ele altera temporariamente o diretório de trabalho " +"atual do processo para *root_dir* para executar o arquivamento." -#: ../../library/shutil.rst:637 +#: ../../library/shutil.rst:636 msgid "" "The modern pax (POSIX.1-2001) format is now used instead of the legacy GNU " "format for archives created with ``format=\"tar\"``." @@ -989,13 +1194,15 @@ msgstr "" "O formato pax moderno (POSIX.1-2001) agora é usado em vez do formato GNU " "legado para arquivos criados com ``format=\"tar\"``." -#: ../../library/shutil.rst:641 +#: ../../library/shutil.rst:640 msgid "" "This function is now made thread-safe during creation of standard ``.zip`` " "and tar archives." msgstr "" +"Esta função agora é segura para thread durante a criação de arquivos ``." +"zip`` e tar padrão." -#: ../../library/shutil.rst:647 +#: ../../library/shutil.rst:646 msgid "" "Return a list of supported formats for archiving. Each element of the " "returned sequence is a tuple ``(name, description)``." @@ -1003,40 +1210,40 @@ msgstr "" "Retorna uma lista de formatos suportados para arquivamento. Cada elemento da " "sequência retornada é uma tupla ``(nome, descrição)``." -#: ../../library/shutil.rst:650 ../../library/shutil.rst:761 +#: ../../library/shutil.rst:649 ../../library/shutil.rst:760 msgid "By default :mod:`shutil` provides these formats:" msgstr "Por padrão, :mod:`shutil` fornece estes formatos:" -#: ../../library/shutil.rst:652 +#: ../../library/shutil.rst:651 msgid "*zip*: ZIP file (if the :mod:`zlib` module is available)." msgstr "*zip*: arquivo ZIP (se o módulo :mod:`zlib` estiver disponível)." -#: ../../library/shutil.rst:653 +#: ../../library/shutil.rst:652 msgid "" "*tar*: Uncompressed tar file. Uses POSIX.1-2001 pax format for new archives." msgstr "" "*tar*: Arquivo tar não compactado. Usa o formato POSIX.1-2001 pax para novos " "arquivos." -#: ../../library/shutil.rst:654 ../../library/shutil.rst:766 +#: ../../library/shutil.rst:653 ../../library/shutil.rst:765 msgid "*gztar*: gzip'ed tar-file (if the :mod:`zlib` module is available)." msgstr "" "*gztar*: arquivo tar compactado com gzip (se o módulo :mod:`zlib` estiver " "disponível)." -#: ../../library/shutil.rst:655 ../../library/shutil.rst:767 +#: ../../library/shutil.rst:654 ../../library/shutil.rst:766 msgid "*bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available)." msgstr "" "*bztar*: arquivo tar compactado com bzip2 (se o módulo :mod:`bz2` estiver " "disponível)." -#: ../../library/shutil.rst:656 ../../library/shutil.rst:768 +#: ../../library/shutil.rst:655 ../../library/shutil.rst:767 msgid "*xztar*: xz'ed tar-file (if the :mod:`lzma` module is available)." msgstr "" "*xztar*: Arquivo tar compactado com xz (se o módulo :mod:`lzma` estiver " "disponível)." -#: ../../library/shutil.rst:658 +#: ../../library/shutil.rst:657 msgid "" "You can register new formats or provide your own archiver for any existing " "formats, by using :func:`register_archive_format`." @@ -1044,11 +1251,11 @@ msgstr "" "Você pode registrar novos formatos ou fornecer seu próprio arquivador para " "quaisquer formatos existentes, usando :func:`register_archive_format`." -#: ../../library/shutil.rst:664 +#: ../../library/shutil.rst:663 msgid "Register an archiver for the format *name*." msgstr "Registra um arquivador para o formato *name*." -#: ../../library/shutil.rst:666 +#: ../../library/shutil.rst:665 msgid "" "*function* is the callable that will be used to unpack archives. The " "callable will receive the *base_name* of the file to create, followed by the " @@ -1059,10 +1266,10 @@ msgstr "" "*function* é o chamável que será usado para desempacotar arquivos. O " "chamável receberá o *base_name* do arquivo a ser criado, seguido pelo " "*base_dir* (cujo padrão é :data:`os.curdir`) para iniciar o arquivamento. " -"Outros argumentos são passados ​​como argumentos nomeados *owner*, *group*, " +"Outros argumentos são passados como argumentos nomeados *owner*, *group*, " "*dry_run* e *logger* (como passado em :func:`make_archive`)." -#: ../../library/shutil.rst:672 +#: ../../library/shutil.rst:671 msgid "" "If *function* has the custom attribute ``function.supports_root_dir`` set to " "``True``, the *root_dir* argument is passed as a keyword argument. Otherwise " @@ -1070,17 +1277,22 @@ msgid "" "*root_dir* before calling *function*. In this case :func:`make_archive` is " "not thread-safe." msgstr "" +"Se *function* tiver o atributo personalizado ``function.supports_root_dir`` " +"definido como ``True``, o argumento *root_dir* será passado como um " +"argumento nomeado. Caso contrário, o diretório de trabalho atual do processo " +"será temporariamente alterado para *root_dir* antes de chamar *function*. " +"Nesse caso, :func:`make_archive` não é segura para thread." -#: ../../library/shutil.rst:678 +#: ../../library/shutil.rst:677 msgid "" "If given, *extra_args* is a sequence of ``(name, value)`` pairs that will be " "used as extra keywords arguments when the archiver callable is used." msgstr "" "Se fornecido, *extra_args* é uma sequência de pares ``(nome, valor)`` que " -"serão usados ​​como argumentos nomeados extras quando o arquivador chamável " +"serão usados como argumentos nomeados extras quando o arquivador chamável " "for usado." -#: ../../library/shutil.rst:681 +#: ../../library/shutil.rst:680 msgid "" "*description* is used by :func:`get_archive_formats` which returns the list " "of archivers. Defaults to an empty string." @@ -1088,19 +1300,19 @@ msgstr "" "*description* é usado por :func:`get_archive_formats` que retorna a lista de " "arquivadores. O padrão é uma string vazia." -#: ../../library/shutil.rst:684 +#: ../../library/shutil.rst:683 msgid "Added support for functions supporting the *root_dir* argument." -msgstr "" +msgstr "Adicionado suporte para funções que suportam o argumento *root_dir*." -#: ../../library/shutil.rst:690 +#: ../../library/shutil.rst:689 msgid "Remove the archive format *name* from the list of supported formats." msgstr "Remove o formato de arquivo *name* da lista de formatos suportados." -#: ../../library/shutil.rst:695 +#: ../../library/shutil.rst:694 msgid "Unpack an archive. *filename* is the full path of the archive." msgstr "Desempacota um arquivo. *filename* é o caminho completo do arquivo." -#: ../../library/shutil.rst:697 +#: ../../library/shutil.rst:696 msgid "" "*extract_dir* is the name of the target directory where the archive is " "unpacked. If not provided, the current working directory is used." @@ -1109,7 +1321,7 @@ msgstr "" "desempacotado. Se não for fornecido, o diretório de trabalho atual será " "usado." -#: ../../library/shutil.rst:700 +#: ../../library/shutil.rst:699 msgid "" "*format* is the archive format: one of \"zip\", \"tar\", \"gztar\", " "\"bztar\", or \"xztar\". Or any other format registered with :func:" @@ -1124,7 +1336,7 @@ msgstr "" "para essa extensão. Caso nenhum seja encontrado, uma :exc:`ValueError` é " "levantada." -#: ../../library/shutil.rst:707 +#: ../../library/shutil.rst:706 msgid "" "The keyword-only *filter* argument is passed to the underlying unpacking " "function. For zip files, *filter* is not accepted. For tar files, it is " @@ -1133,8 +1345,14 @@ msgid "" "details.) The ``'data'`` filter will become the default for tar files in " "Python 3.14." msgstr "" +"O argumento somente-nomeado *filter* é passado para a função de " +"desempacotamento subjacente. Para arquivos zip, *filter* não é aceito. Para " +"arquivos tar, é recomendado defini-lo como ``'data'``, a menos que esteja " +"usando recursos específicos para tar e sistemas de arquivos do tipo UNIX. " +"(Veja :ref:`tarfile-extraction-filter` para detalhes.) O filtro ``'data'`` " +"se tornará o padrão para arquivos tar no Python 3.14." -#: ../../library/shutil.rst:715 +#: ../../library/shutil.rst:714 msgid "" "Raises an :ref:`auditing event ` ``shutil.unpack_archive`` with " "arguments ``filename``, ``extract_dir``, ``format``." @@ -1142,25 +1360,29 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``shutil.unpack_archive`` " "com os argumentos ``filename``, ``extract_dir``, ``format``." -#: ../../library/shutil.rst:719 +#: ../../library/shutil.rst:718 msgid "" "Never extract archives from untrusted sources without prior inspection. It " "is possible that files are created outside of the path specified in the " "*extract_dir* argument, e.g. members that have absolute filenames starting " "with \"/\" or filenames with two dots \"..\"." msgstr "" +"Nunca extrai arquivos de fontes não confiáveis sem inspeção prévia. É " +"possível que arquivos sejam criados fora do caminho especificado no " +"argumento *extract_dir*, por exemplo, membros que têm nomes de arquivo " +"absolutos começando com \"/\" ou nomes de arquivo com dois pontos \"..\"." -#: ../../library/shutil.rst:724 +#: ../../library/shutil.rst:723 msgid "Accepts a :term:`path-like object` for *filename* and *extract_dir*." msgstr "" "Aceita um :term:`objeto caminho ou similar ` para " "*filename* e *extract_dir*." -#: ../../library/shutil.rst:727 +#: ../../library/shutil.rst:726 msgid "Added the *filter* argument." -msgstr "" +msgstr "Adicionado o argumento *filter*." -#: ../../library/shutil.rst:732 +#: ../../library/shutil.rst:731 msgid "" "Registers an unpack format. *name* is the name of the format and " "*extensions* is a list of extensions corresponding to the format, like ``." @@ -1170,34 +1392,42 @@ msgstr "" "*extensions* é uma lista de extensões correspondentes ao formato, como ``." "zip`` para arquivos Zip." -#: ../../library/shutil.rst:736 +#: ../../library/shutil.rst:735 msgid "" "*function* is the callable that will be used to unpack archives. The " "callable will receive:" msgstr "" +"*function* é o chamável que será usado para desempacotar arquivos. O " +"chamável receberá:" -#: ../../library/shutil.rst:739 +#: ../../library/shutil.rst:738 msgid "the path of the archive, as a positional argument;" -msgstr "" +msgstr "o caminho do arquivo, como argumento posicional;" -#: ../../library/shutil.rst:740 +#: ../../library/shutil.rst:739 msgid "" "the directory the archive must be extracted to, as a positional argument;" msgstr "" +"o diretório para o qual o arquivo deve ser extraído, como um argumento " +"posicional;" -#: ../../library/shutil.rst:741 +#: ../../library/shutil.rst:740 msgid "" "possibly a *filter* keyword argument, if it was given to :func:" "`unpack_archive`;" msgstr "" +"possivelmente um argumento nomeado *filter*, se foi dado a :func:" +"`unpack_archive`;" -#: ../../library/shutil.rst:743 +#: ../../library/shutil.rst:742 msgid "" "additional keyword arguments, specified by *extra_args* as a sequence of " "``(name, value)`` tuples." msgstr "" +"argumentos nomeados adicionais, especificados por *extra_args* como uma " +"sequência de tuplas ``(nome, valor)``." -#: ../../library/shutil.rst:746 +#: ../../library/shutil.rst:745 msgid "" "*description* can be provided to describe the format, and will be returned " "by the :func:`get_unpack_formats` function." @@ -1205,13 +1435,13 @@ msgstr "" "*description* pode ser fornecido para descrever o formato e será devolvido " "pela função :func:`get_unpack_formats`." -#: ../../library/shutil.rst:752 +#: ../../library/shutil.rst:751 msgid "Unregister an unpack format. *name* is the name of the format." msgstr "" "Cancela o registro de um formato de desempacotamento. *name* é o nome do " "formato." -#: ../../library/shutil.rst:757 +#: ../../library/shutil.rst:756 msgid "" "Return a list of all registered formats for unpacking. Each element of the " "returned sequence is a tuple ``(name, extensions, description)``." @@ -1220,7 +1450,7 @@ msgstr "" "Cada elemento da sequência retornada é uma tupla ``(name, extensions, " "description)``." -#: ../../library/shutil.rst:763 +#: ../../library/shutil.rst:762 msgid "" "*zip*: ZIP file (unpacking compressed files works only if the corresponding " "module is available)." @@ -1228,11 +1458,11 @@ msgstr "" "*zip*: arquivo ZIP (desempacotar arquivos compactados funciona apenas se o " "módulo correspondente estiver disponível)." -#: ../../library/shutil.rst:765 +#: ../../library/shutil.rst:764 msgid "*tar*: uncompressed tar file." msgstr "*tar*: arquivo tar não comprimido." -#: ../../library/shutil.rst:770 +#: ../../library/shutil.rst:769 msgid "" "You can register new formats or provide your own unpacker for any existing " "formats, by using :func:`register_unpack_format`." @@ -1240,11 +1470,11 @@ msgstr "" "Você pode registrar novos formatos ou fornecer seu próprio desempacotador " "para quaisquer formatos existentes, usando :func:`register_unpack_format`." -#: ../../library/shutil.rst:777 +#: ../../library/shutil.rst:776 msgid "Archiving example" msgstr "Exemplo de arquivo" -#: ../../library/shutil.rst:779 +#: ../../library/shutil.rst:778 msgid "" "In this example, we create a gzip'ed tar-file archive containing all files " "found in the :file:`.ssh` directory of the user::" @@ -1252,15 +1482,53 @@ msgstr "" "Neste exemplo, criamos um arquivo tar compactado com gzip contendo todos os " "arquivos encontrados no diretório :file:`.ssh` do usuário::" -#: ../../library/shutil.rst:789 +#: ../../library/shutil.rst:781 +msgid "" +">>> from shutil import make_archive\n" +">>> import os\n" +">>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))\n" +">>> root_dir = os.path.expanduser(os.path.join('~', '.ssh'))\n" +">>> make_archive(archive_name, 'gztar', root_dir)\n" +"'/Users/tarek/myarchive.tar.gz'" +msgstr "" +">>> from shutil import make_archive\n" +">>> import os\n" +">>> archive_name = os.path.expanduser(os.path.join('~', 'meuarquivo'))\n" +">>> root_dir = os.path.expanduser(os.path.join('~', '.ssh'))\n" +">>> make_archive(archive_name, 'gztar', root_dir)\n" +"'/Users/tarek/meuarquivo.tar.gz'" + +#: ../../library/shutil.rst:788 msgid "The resulting archive contains:" msgstr "O arquivo resultante contém:" -#: ../../library/shutil.rst:807 +#: ../../library/shutil.rst:790 +msgid "" +"$ tar -tzvf /Users/tarek/myarchive.tar.gz\n" +"drwx------ tarek/staff 0 2010-02-01 16:23:40 ./\n" +"-rw-r--r-- tarek/staff 609 2008-06-09 13:26:54 ./authorized_keys\n" +"-rwxr-xr-x tarek/staff 65 2008-06-09 13:26:54 ./config\n" +"-rwx------ tarek/staff 668 2008-06-09 13:26:54 ./id_dsa\n" +"-rwxr-xr-x tarek/staff 609 2008-06-09 13:26:54 ./id_dsa.pub\n" +"-rw------- tarek/staff 1675 2008-06-09 13:26:54 ./id_rsa\n" +"-rw-r--r-- tarek/staff 397 2008-06-09 13:26:54 ./id_rsa.pub\n" +"-rw-r--r-- tarek/staff 37192 2010-02-06 18:23:10 ./known_hosts" +msgstr "" +"$ tar -tzvf /Users/tarek/meuarquivo.tar.gz\n" +"drwx------ tarek/staff 0 2010-02-01 16:23:40 ./\n" +"-rw-r--r-- tarek/staff 609 2008-06-09 13:26:54 ./authorized_keys\n" +"-rwxr-xr-x tarek/staff 65 2008-06-09 13:26:54 ./config\n" +"-rwx------ tarek/staff 668 2008-06-09 13:26:54 ./id_dsa\n" +"-rwxr-xr-x tarek/staff 609 2008-06-09 13:26:54 ./id_dsa.pub\n" +"-rw------- tarek/staff 1675 2008-06-09 13:26:54 ./id_rsa\n" +"-rw-r--r-- tarek/staff 397 2008-06-09 13:26:54 ./id_rsa.pub\n" +"-rw-r--r-- tarek/staff 37192 2010-02-06 18:23:10 ./known_hosts" + +#: ../../library/shutil.rst:806 msgid "Archiving example with *base_dir*" msgstr "Exemplo de arquivamento com *base_dir*" -#: ../../library/shutil.rst:809 +#: ../../library/shutil.rst:808 msgid "" "In this example, similar to the `one above `_, we " "show how to use :func:`make_archive`, but this time with the usage of " @@ -1270,7 +1538,25 @@ msgstr "" "como usar :func:`make_archive`, mas desta vez com o uso de *base_dir*. Agora " "temos a seguinte estrutura de diretório:" -#: ../../library/shutil.rst:823 +#: ../../library/shutil.rst:812 +msgid "" +"$ tree tmp\n" +"tmp\n" +"└── root\n" +" └── structure\n" +" ├── content\n" +" └── please_add.txt\n" +" └── do_not_add.txt" +msgstr "" +"$ tree tmp\n" +"tmp\n" +"└── root\n" +" └── estrutura\n" +" ├── conteudo\n" +" └── por_favor_adicionar.txt\n" +" └── nao_adicionar.txt" + +#: ../../library/shutil.rst:822 msgid "" "In the final archive, :file:`please_add.txt` should be included, but :file:" "`do_not_add.txt` should not. Therefore we use the following::" @@ -1278,19 +1564,53 @@ msgstr "" "No arquivo final, :file:`please_add.txt` deve ser incluído, mas :file:" "`do_not_add.txt` não deve. Portanto, usamos o seguinte::" -#: ../../library/shutil.rst:837 +#: ../../library/shutil.rst:825 +msgid "" +">>> from shutil import make_archive\n" +">>> import os\n" +">>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))\n" +">>> make_archive(\n" +"... archive_name,\n" +"... 'tar',\n" +"... root_dir='tmp/root',\n" +"... base_dir='structure/content',\n" +"... )\n" +"'/Users/tarek/my_archive.tar'" +msgstr "" +">>> from shutil import make_archive\n" +">>> import os\n" +">>> archive_name = os.path.expanduser(os.path.join('~', 'meuarquivo'))\n" +">>> make_archive(\n" +"... archive_name,\n" +"... 'tar',\n" +"... root_dir='tmp/root',\n" +"... base_dir='estrutura/conteudo',\n" +"... )\n" +"'/Users/tarek/meuarquivo.tar'" + +#: ../../library/shutil.rst:836 msgid "Listing the files in the resulting archive gives us:" msgstr "Listar os arquivos no arquivo resultante nos dá:" -#: ../../library/shutil.rst:847 +#: ../../library/shutil.rst:838 +msgid "" +"$ python -m tarfile -l /Users/tarek/myarchive.tar\n" +"structure/content/\n" +"structure/content/please_add.txt" +msgstr "" +"$ python -m tarfile -l /Users/tarek/meuarquivo.tar\n" +"estrutura/conteudo/\n" +"estrutura/conteudo/por_favor_adicionar.txt" + +#: ../../library/shutil.rst:846 msgid "Querying the size of the output terminal" msgstr "Consultando o tamanho do terminal de saída" -#: ../../library/shutil.rst:851 +#: ../../library/shutil.rst:850 msgid "Get the size of the terminal window." msgstr "Obtém o tamanho da janela do terminal." -#: ../../library/shutil.rst:853 +#: ../../library/shutil.rst:852 msgid "" "For each of the two dimensions, the environment variable, ``COLUMNS`` and " "``LINES`` respectively, is checked. If the variable is defined and the value " @@ -1300,7 +1620,7 @@ msgstr "" "``LINES`` respectivamente, é verificada. Se a variável estiver definida e o " "valor for um número inteiro positivo, ela será usada." -#: ../../library/shutil.rst:857 +#: ../../library/shutil.rst:856 msgid "" "When ``COLUMNS`` or ``LINES`` is not defined, which is the common case, the " "terminal connected to :data:`sys.__stdout__` is queried by invoking :func:" @@ -1310,7 +1630,7 @@ msgstr "" "terminal conectado a :data:`sys.__stdout__` é consultado invocando :func:`os." "get_terminal_size`." -#: ../../library/shutil.rst:861 +#: ../../library/shutil.rst:860 msgid "" "If the terminal size cannot be successfully queried, either because the " "system doesn't support querying, or because we are not connected to a " @@ -1324,12 +1644,12 @@ msgstr "" "``fallback`` é ``(80, 24)``, que é o tamanho padrão usado por muitos " "emuladores de terminal." -#: ../../library/shutil.rst:867 +#: ../../library/shutil.rst:866 msgid "The value returned is a named tuple of type :class:`os.terminal_size`." msgstr "" "O valor retornado é uma tupla nomeada do tipo :class:`os.terminal_size`." -#: ../../library/shutil.rst:869 +#: ../../library/shutil.rst:868 msgid "" "See also: The Single UNIX Specification, Version 2, `Other Environment " "Variables`_." @@ -1337,11 +1657,13 @@ msgstr "" "Veja também: The Single UNIX Specification, Versão 2, `Other Environment " "Variables`_." -#: ../../library/shutil.rst:874 +#: ../../library/shutil.rst:873 msgid "" "The ``fallback`` values are also used if :func:`os.get_terminal_size` " "returns zeroes." msgstr "" +"Os valores ``fallback`` também são usados se :func:`os.get_terminal_size` " +"retornar zeros." #: ../../library/shutil.rst:12 msgid "file" @@ -1349,11 +1671,11 @@ msgstr "arquivo" #: ../../library/shutil.rst:12 msgid "copying" -msgstr "" +msgstr "cópia" #: ../../library/shutil.rst:12 msgid "copying files" -msgstr "" +msgstr "cópia de arquivos" #: ../../library/shutil.rst:297 msgid "directory" diff --git a/library/signal.po b/library/signal.po index a7925165f..ba19801f4 100644 --- a/library/signal.po +++ b/library/signal.po @@ -1,32 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Alexandre B A Villares, 2021 -# Renan Lopes , 2021 -# i17obot , 2021 -# mvpetri , 2022 -# Raphael Mendonça, 2022 -# Elvis da Silva de Menezes , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:13+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-04-18 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -40,7 +33,8 @@ msgstr "**Código-fonte:** :source:`Lib/signal.py`" #: ../../library/signal.rst:11 msgid "This module provides mechanisms to use signal handlers in Python." -msgstr "Este módulo fornece mecanismos para usar signal handlers em Python" +msgstr "" +"Este módulo fornece mecanismos para usar manipuladores de sinal em Python." #: ../../library/signal.rst:15 msgid "General rules" @@ -55,6 +49,12 @@ msgid "" "translated into a :exc:`KeyboardInterrupt` exception if the parent process " "has not changed it." msgstr "" +"A função :func:`signal.signal` permite definir manipuladores personalizados " +"a serem executados quando um sinal é recebido. Um pequeno número de " +"manipuladores padrão são instalados: :const:`SIGPIPE` é ignorado (então " +"erros de gravação em encadeamentos e sockets podem ser relatados como " +"exceções comuns do Python) e :const:`SIGINT` é traduzido em uma exceção :exc:" +"`KeyboardInterrupt` se o processo pai não a tiver alterado." #: ../../library/signal.rst:24 msgid "" @@ -63,6 +63,10 @@ msgid "" "underlying implementation), with the exception of the handler for :const:" "`SIGCHLD`, which follows the underlying implementation." msgstr "" +"Um manipulador para um sinal específico, uma vez definido, permanece " +"instalado até ser explicitamente redefinido (o Python emula a interface de " +"estilo BSD independentemente da implementação subjacente), com exceção do " +"manipulador para :const:`SIGCHLD`, que segue a implementação subjacente." #: ../../library/signal.rst:29 msgid "" @@ -70,10 +74,13 @@ msgid "" "differently. Several functions and signals are not available on these " "platforms." msgstr "" +"Em plataformas WebAssembly, os sinais são emulados e, portanto, se comportam " +"de forma diferente. Várias funções e sinais não estão disponíveis nessas " +"plataformas." #: ../../library/signal.rst:34 msgid "Execution of Python signal handlers" -msgstr "" +msgstr "Execução de manipuladores de sinais Python" #: ../../library/signal.rst:36 msgid "" @@ -83,6 +90,11 @@ msgid "" "handler at a later point(for example at the next :term:`bytecode` " "instruction). This has consequences:" msgstr "" +"Um manipulador de sinal Python não é executado dentro do manipulador de " +"sinal de baixo nível (C). Em vez disso, o manipulador de sinal de baixo " +"nível define um sinalizador que diz à :term:`máquina virtual` para executar " +"o manipulador de sinal Python correspondente em um ponto posterior (por " +"exemplo, na próxima instrução :term:`bytecode`). Isso tem consequências:" #: ../../library/signal.rst:42 msgid "" @@ -93,6 +105,12 @@ msgid "" "onwards, you can use the :mod:`faulthandler` module to report on synchronous " "errors." msgstr "" +"Faz pouco sentido capturar erros síncronos como :const:`SIGFPE` ou :const:" +"`SIGSEGV` que são causados por uma operação inválida no código C. O Python " +"retornará do manipulador de sinais para o código C, o que provavelmente " +"levantará o mesmo sinal novamente, fazendo com que o Python aparentemente " +"trave. Do Python 3.3 em diante, você pode usar o módulo :mod:`faulthandler` " +"para relatar erros síncronos." #: ../../library/signal.rst:49 msgid "" @@ -101,6 +119,11 @@ msgid "" "arbitrary amount of time, regardless of any signals received. The Python " "signal handlers will be called when the calculation finishes." msgstr "" +"Um cálculo de longa duração implementado puramente em C (como " +"correspondência de expressão regular em um grande corpo de texto) pode ser " +"executado ininterruptamente por um período de tempo arbitrário, " +"independentemente de quaisquer sinais recebidos. Os manipuladores de sinal " +"do Python serão chamados quando o cálculo terminar." #: ../../library/signal.rst:54 msgid "" @@ -108,10 +131,13 @@ msgid "" "the main thread. See the :ref:`note below ` for a " "discussion." msgstr "" +"Se o manipulador levantar uma exceção, ela será levantada \"do nada\" na " +"thread principal. Veja a :ref:`nota abaixo ` para " +"uma discussão." #: ../../library/signal.rst:62 msgid "Signals and threads" -msgstr "" +msgstr "Sinais e threads" #: ../../library/signal.rst:64 msgid "" @@ -121,12 +147,19 @@ msgid "" "You can use the synchronization primitives from the :mod:`threading` module " "instead." msgstr "" +"Os manipuladores de sinais Python são sempre executados na thread principal " +"do Python do interpretador principal, mesmo se o sinal foi recebido em outra " +"thread. Isso significa que os sinais não podem ser usados como um meio de " +"comunicação entre threads. Você pode usar as primitivas de sincronização do " +"módulo :mod:`threading` em vez disso." #: ../../library/signal.rst:69 msgid "" "Besides, only the main thread of the main interpreter is allowed to set a " "new signal handler." msgstr "" +"Além disso, somente a thread principal do interpretador principal tem " +"permissão para definir um novo manipulador de sinal." #: ../../library/signal.rst:73 msgid "Module contents" @@ -142,51 +175,68 @@ msgid "" "`sigwait` functions return human-readable :class:`enums ` as :" "class:`Signals` objects." msgstr "" +"As constantes relacionadas a sinal (SIG*), manipulador (:const:`SIG_DFL`, :" +"const:`SIG_IGN`) e sigmask (:const:`SIG_BLOCK`, :const:`SIG_UNBLOCK`, :const:" +"`SIG_SETMASK`) listadas abaixo foram transformadas em :class:`enums ` (:class:`Signals`, :class:`Handlers` e :class:`Sigmasks` " +"respectivamente). As funções :func:`getsignal`, :func:`pthread_sigmask`, :" +"func:`sigpending` e :func:`sigwait` retornam :class:`enums ` " +"legíveis por humanos como objetos :class:`Signals`." #: ../../library/signal.rst:85 msgid "The signal module defines three enums:" -msgstr "" +msgstr "O módulo de sinal define três enumerações:" #: ../../library/signal.rst:89 msgid "" ":class:`enum.IntEnum` collection of SIG* constants and the CTRL_* constants." msgstr "" +"Coleção de :class:`enum.IntEnum` de constantes SIG* e constantes CTRL_*." #: ../../library/signal.rst:95 msgid "" ":class:`enum.IntEnum` collection the constants :const:`SIG_DFL` and :const:" "`SIG_IGN`." msgstr "" +"Coleção de :class:`enum.IntEnum` das constantes :const:`SIG_DFL` e :const:" +"`SIG_IGN`." #: ../../library/signal.rst:101 msgid "" ":class:`enum.IntEnum` collection the constants :const:`SIG_BLOCK`, :const:" "`SIG_UNBLOCK` and :const:`SIG_SETMASK`." msgstr "" +"Coleção de :class:`enum.IntEnum` das constantes :const:`SIG_BLOCK`, :const:" +"`SIG_UNBLOCK` e :const:`SIG_SETMASK`." #: ../../library/signal.rst:103 ../../library/signal.rst:136 -#: ../../library/signal.rst:148 ../../library/signal.rst:154 +#: ../../library/signal.rst:142 ../../library/signal.rst:148 +#: ../../library/signal.rst:154 ../../library/signal.rst:160 #: ../../library/signal.rst:166 ../../library/signal.rst:180 #: ../../library/signal.rst:198 ../../library/signal.rst:206 -#: ../../library/signal.rst:232 ../../library/signal.rst:238 -#: ../../library/signal.rst:244 ../../library/signal.rst:351 -#: ../../library/signal.rst:390 ../../library/signal.rst:437 +#: ../../library/signal.rst:217 ../../library/signal.rst:232 +#: ../../library/signal.rst:238 ../../library/signal.rst:244 +#: ../../library/signal.rst:262 ../../library/signal.rst:272 +#: ../../library/signal.rst:351 ../../library/signal.rst:390 +#: ../../library/signal.rst:414 ../../library/signal.rst:437 #: ../../library/signal.rst:471 ../../library/signal.rst:501 -#: ../../library/signal.rst:508 ../../library/signal.rst:561 -#: ../../library/signal.rst:603 ../../library/signal.rst:618 -#: ../../library/signal.rst:644 ../../library/signal.rst:664 -msgid ":ref:`Availability `: Unix." -msgstr ":ref:`Disponibilidade `: Unix." +#: ../../library/signal.rst:508 ../../library/signal.rst:563 +#: ../../library/signal.rst:605 ../../library/signal.rst:620 +#: ../../library/signal.rst:646 ../../library/signal.rst:666 +msgid "Availability" +msgstr "Disponibilidade" #: ../../library/signal.rst:105 ../../library/signal.rst:473 msgid "" "See the man page :manpage:`sigprocmask(2)` and :manpage:`pthread_sigmask(3)` " "for further information." msgstr "" +"Veja a página man :manpage:`sigprocmask(2)` e :manpage:`pthread_sigmask(3)` " +"para mais informações." #: ../../library/signal.rst:111 msgid "The variables defined in the :mod:`signal` module are:" -msgstr "" +msgstr "As variáveis definidas no módulo :mod:`signal` são:" #: ../../library/signal.rst:116 msgid "" @@ -195,64 +245,65 @@ msgid "" "default action for :const:`SIGQUIT` is to dump core and exit, while the " "default action for :const:`SIGCHLD` is to simply ignore it." msgstr "" +"Esta é uma das duas opções de manipulação de sinal padrão; ela simplesmente " +"executará a função padrão para o sinal. Por exemplo, na maioria dos " +"sistemas, a ação padrão para :const:`SIGQUIT` é despejar o núcleo e sair, " +"enquanto a ação padrão para :const:`SIGCHLD` é simplesmente ignorá-lo." #: ../../library/signal.rst:124 msgid "" "This is another standard signal handler, which will simply ignore the given " "signal." msgstr "" +"Este é outro manipulador de sinal padrão, que simplesmente ignorará o sinal " +"fornecido." #: ../../library/signal.rst:130 msgid "Abort signal from :manpage:`abort(3)`." -msgstr "" +msgstr "Sinal de abortar de :manpage:`abort(3)`." #: ../../library/signal.rst:134 msgid "Timer signal from :manpage:`alarm(2)`." -msgstr "" +msgstr "Sinal do temporizador de :manpage:`alarm(2)`." #: ../../library/signal.rst:140 msgid "Interrupt from keyboard (CTRL + BREAK)." -msgstr "" - -#: ../../library/signal.rst:142 ../../library/signal.rst:262 -#: ../../library/signal.rst:272 -msgid ":ref:`Availability `: Windows." -msgstr ":ref:`Disponibilidade `: Windows." +msgstr "Interrupção do teclado (CTRL + BREAK)." #: ../../library/signal.rst:146 msgid "Bus error (bad memory access)." -msgstr "" +msgstr "Erro de barramento (acesso incorreto à memória)." #: ../../library/signal.rst:152 msgid "Child process stopped or terminated." -msgstr "" +msgstr "Processo filho interrompido ou encerrado." #: ../../library/signal.rst:158 msgid "Alias to :data:`SIGCHLD`." -msgstr "" - -#: ../../library/signal.rst:160 -msgid ":ref:`Availability `: not macOS." -msgstr "" +msgstr "Apelido para :data:`SIGCHLD`." #: ../../library/signal.rst:164 msgid "Continue the process if it is currently stopped" -msgstr "" +msgstr "Continua o processo se ele estiver parado no momento" #: ../../library/signal.rst:170 msgid "Floating-point exception. For example, division by zero." -msgstr "" +msgstr "Exceção de ponto flutuante. Por exemplo, divisão por zero." #: ../../library/signal.rst:173 msgid "" ":exc:`ZeroDivisionError` is raised when the second argument of a division or " "modulo operation is zero." msgstr "" +":exc:`ZeroDivisionError` é levatanda quando o segundo argumento de uma " +"operação de divisão ou módulo é zero." #: ../../library/signal.rst:178 msgid "" "Hangup detected on controlling terminal or death of controlling process." msgstr "" +"Travamento detectado no terminal de controle ou morte do processo de " +"controle." #: ../../library/signal.rst:184 msgid "Illegal instruction." @@ -260,63 +311,63 @@ msgstr "Instrução ilegal." #: ../../library/signal.rst:188 msgid "Interrupt from keyboard (CTRL + C)." -msgstr "" +msgstr "Interrupção do teclado (CTRL + C)." #: ../../library/signal.rst:190 msgid "Default action is to raise :exc:`KeyboardInterrupt`." -msgstr "" +msgstr "A ação padrão é levantar :exc:`KeyboardInterrupt`." #: ../../library/signal.rst:194 msgid "Kill signal." -msgstr "" +msgstr "Sinal de matar." #: ../../library/signal.rst:196 msgid "It cannot be caught, blocked, or ignored." -msgstr "" +msgstr "Ele não pode ser capturado, bloqueado ou ignorado." #: ../../library/signal.rst:202 msgid "Broken pipe: write to pipe with no readers." -msgstr "" +msgstr "Encadeamento quebrado: escreve no encadeamento sem leitores." #: ../../library/signal.rst:204 msgid "Default action is to ignore the signal." -msgstr "" +msgstr "A ação padrão é ignorar o sinal." #: ../../library/signal.rst:210 msgid "Segmentation fault: invalid memory reference." -msgstr "" +msgstr "Falha de segmentação: referência de memória inválida." #: ../../library/signal.rst:214 msgid "" "Stack fault on coprocessor. The Linux kernel does not raise this signal: it " "can only be raised in user space." msgstr "" - -#: ../../library/signal.rst:217 -msgid ":ref:`Availability `: Linux." -msgstr ":ref:`Disponibilidade `: Linux." +"Falha de pilha no coprocessador. O kernel Linux não levanta esse sinal: ele " +"só pode ser emitido no espaço do usuário." #: ../../library/signal.rst:219 msgid "" "On architectures where the signal is available. See the man page :manpage:" "`signal(7)` for further information." msgstr "" +"Em arquiteturas onde o sinal está disponível. Veja a página man :manpage:" +"`signal(7)` para mais informações." #: ../../library/signal.rst:226 msgid "Termination signal." -msgstr "" +msgstr "Sinal de encerramento." #: ../../library/signal.rst:230 msgid "User-defined signal 1." -msgstr "" +msgstr "Sinal definido pelo usuário 1." #: ../../library/signal.rst:236 msgid "User-defined signal 2." -msgstr "" +msgstr "Sinal definido pelo usuário 2." #: ../../library/signal.rst:242 msgid "Window resize signal." -msgstr "" +msgstr "Sinal de redimensionamento do Windows." #: ../../library/signal.rst:248 msgid "" @@ -328,36 +379,54 @@ msgid "" "`signal(7)`). Note that not all systems define the same set of signal names; " "only those names defined by the system are defined by this module." msgstr "" +"Todos os números de sinal são definidos simbolicamente. Por exemplo, o sinal " +"de desligamento é definido como :const:`signal.SIGHUP`; os nomes das " +"variáveis ​​são idênticos aos usados ​​em programas C, como encontrados em " +"````. A página man do Unix para ':c:func:`signal`' lista os sinais " +"existentes (em alguns sistemas, é :manpage:`signal(2)`, em outros, a lista " +"está em :manpage:`signal(7)`). Observe que nem todos os sistemas definem o " +"mesmo conjunto de nomes de sinais; apenas os nomes definidos pelo sistema " +"são definidos por este módulo." #: ../../library/signal.rst:259 msgid "" "The signal corresponding to the :kbd:`Ctrl+C` keystroke event. This signal " "can only be used with :func:`os.kill`." msgstr "" +"O sinal correspondente ao evento de pressionamento de tecla :kbd:`Ctrl+C`. " +"Este sinal só pode ser usado com :func:`os.kill`." #: ../../library/signal.rst:269 msgid "" "The signal corresponding to the :kbd:`Ctrl+Break` keystroke event. This " "signal can only be used with :func:`os.kill`." msgstr "" +"O sinal correspondente ao evento de pressionamento de tecla :kbd:" +"`Ctrl+Break`. Este sinal só pode ser usado com :func:`os.kill`." #: ../../library/signal.rst:279 msgid "" "One more than the number of the highest signal number. Use :func:" "`valid_signals` to get valid signal numbers." msgstr "" +"Um a mais que o número do sinal mais alto. Use :func:`valid_signals` para " +"obter números de sinais válidos." #: ../../library/signal.rst:285 msgid "" "Decrements interval timer in real time, and delivers :const:`SIGALRM` upon " "expiration." msgstr "" +"Diminui o intervalo do temporizador em tempo real e entrega :const:`SIGALRM` " +"ao expirar." #: ../../library/signal.rst:291 msgid "" "Decrements interval timer only when the process is executing, and delivers " "SIGVTALRM upon expiration." msgstr "" +"Diminui o intervalo do temporizador somente quando o processo está em " +"execução e entrega SIGVTALRM após a expiração." #: ../../library/signal.rst:297 msgid "" @@ -366,28 +435,39 @@ msgid "" "timer is usually used to profile the time spent by the application in user " "and kernel space. SIGPROF is delivered upon expiration." msgstr "" +"Diminui o temporizador de intervalo tanto quando o processo é executado " +"quanto quando o sistema está executando em nome do processo. Juntamente com " +"o ITIMER_VIRTUAL, este temporizador é geralmente usado para criar um perfil " +"do tempo gasto pelo aplicativo nos espaços do usuário e do kernel. O SIGPROF " +"é fornecido após a expiração." #: ../../library/signal.rst:305 msgid "" "A possible value for the *how* parameter to :func:`pthread_sigmask` " "indicating that signals are to be blocked." msgstr "" +"Um possível valor para o parâmetro *how* para :func:`pthread_sigmask` " +"indicando que os sinais devem ser bloqueados." #: ../../library/signal.rst:312 msgid "" "A possible value for the *how* parameter to :func:`pthread_sigmask` " "indicating that signals are to be unblocked." msgstr "" +"Um possível valor para o parâmetro *how* para :func:`pthread_sigmask` " +"indicando que os sinais devem ser desbloqueados." #: ../../library/signal.rst:319 msgid "" "A possible value for the *how* parameter to :func:`pthread_sigmask` " "indicating that the signal mask is to be replaced." msgstr "" +"Um possível valor para o parâmetro *how* para :func:`pthread_sigmask` " +"indicando que a máscara de sinal deve ser substituída." #: ../../library/signal.rst:325 msgid "The :mod:`signal` module defines one exception:" -msgstr "" +msgstr "O módulo :mod:`signal` define uma exceção:" #: ../../library/signal.rst:329 msgid "" @@ -396,16 +476,22 @@ msgid "" "or a negative time is passed to :func:`setitimer`. This error is a subtype " "of :exc:`OSError`." msgstr "" +"Levantada para sinalizar um erro da implementação subjacente de :func:" +"`setitimer` ou :func:`getitimer`. Espere este erro se um temporizador de " +"intervalo inválido ou um tempo negativo for passado para :func:`setitimer`. " +"Este erro é um subtipo de :exc:`OSError`." #: ../../library/signal.rst:334 msgid "" "This error used to be a subtype of :exc:`IOError`, which is now an alias of :" "exc:`OSError`." msgstr "" +"Este erro costumava ser um subtipo de :exc:`IOError`, que agora é um apelido " +"de :exc:`OSError`." #: ../../library/signal.rst:339 msgid "The :mod:`signal` module defines the following functions:" -msgstr "" +msgstr "O módulo :mod:`signal` define as seguintes funções:" #: ../../library/signal.rst:344 msgid "" @@ -417,10 +503,17 @@ msgid "" "alarm is canceled. If the return value is zero, no alarm is currently " "scheduled." msgstr "" +"Se *time* for diferente de zero, esta função solicita que um sinal :const:" +"`SIGALRM` seja enviado ao processo em *time* segundos. Qualquer alarme " +"previamente agendado será cancelado (apenas um alarme pode ser agendado por " +"vez). O valor retornado será o número de segundos antes de qualquer alarme " +"previamente configurado ter sido emitido. Se *time* for zero, nenhum alarme " +"será agendado e qualquer alarme agendado será cancelado. Se o valor " +"retornado for zero, nenhum alarme será agendado no momento." #: ../../library/signal.rst:353 msgid "See the man page :manpage:`alarm(2)` for further information." -msgstr "" +msgstr "Veja a página man :manpage:`alarm(2)` para mais informações." #: ../../library/signal.rst:358 msgid "" @@ -432,6 +525,13 @@ msgid "" "previously in use, and ``None`` means that the previous signal handler was " "not installed from Python." msgstr "" +"Retorna o manipulador de sinal atual para o sinal *signalnum*. O valor " +"retornado pode ser um objeto Python invocável ou um dos valores especiais :" +"const:`signal.SIG_IGN`, :const:`signal.SIG_DFL` ou :const:`None`. Aqui, :" +"const:`signal.SIG_IGN` significa que o sinal foi ignorado anteriormente, :" +"const:`signal.SIG_DFL` significa que a maneira padrão de manipular o sinal " +"estava em uso anteriormente e ``None`` significa que o manipulador de sinal " +"anterior não foi instalado a partir do Python." #: ../../library/signal.rst:369 msgid "" @@ -439,6 +539,9 @@ msgid "" "const:`SIGINT`. Returns :const:`None` if *signalnum* has no description. " "Raises :exc:`ValueError` if *signalnum* is invalid." msgstr "" +"Retorna a descrição do sinal *signalnum*, como \"Interrupt\" para :const:" +"`SIGINT`. Retorna :const:`None` se *signalnum* não tiver descrição. Levanta :" +"exc:`ValueError` se *signalnum* for inválido." #: ../../library/signal.rst:378 msgid "" @@ -446,26 +549,33 @@ msgid "" "than ``range(1, NSIG)`` if some signals are reserved by the system for " "internal use." msgstr "" +"Retorna o conjunto de números de sinais válidos nesta plataforma. Pode ser " +"menor que ``range(1, NSIG)`` se alguns sinais forem reservados pelo sistema " +"para uso interno." #: ../../library/signal.rst:387 msgid "" "Cause the process to sleep until a signal is received; the appropriate " "handler will then be called. Returns nothing." msgstr "" +"Faz o processo hibernar até que um sinal seja recebido; o manipulador " +"apropriado será então chamado. Não retorna nada." #: ../../library/signal.rst:392 msgid "See the man page :manpage:`signal(2)` for further information." -msgstr "" +msgstr "Veja a página man :manpage:`signal(2)` para mais informações." #: ../../library/signal.rst:394 msgid "" "See also :func:`sigwait`, :func:`sigwaitinfo`, :func:`sigtimedwait` and :" "func:`sigpending`." msgstr "" +"veja também :func:`sigwait`, :func:`sigwaitinfo`, :func:`sigtimedwait` e :" +"func:`sigpending`." #: ../../library/signal.rst:400 msgid "Sends a signal to the calling process. Returns nothing." -msgstr "" +msgstr "Envia um sinal para o processo de chamada. Não retorna nada." #: ../../library/signal.rst:407 msgid "" @@ -474,14 +584,15 @@ msgid "" "``None``. The *flags* argument is provided for future extensions; no flag " "values are currently defined." msgstr "" +"Envia o sinal *sig* para o processo referenciado pelo descritor de arquivo " +"*pidfd*. Atualmente, o Python não suporta o parâmetro *siginfo*; ele deve " +"ser ``None``. O argumento *flags* é fornecido para futuras extensões; nenhum " +"valor de sinalizador está definido no momento." #: ../../library/signal.rst:412 msgid "See the :manpage:`pidfd_send_signal(2)` man page for more information." msgstr "" - -#: ../../library/signal.rst:414 -msgid ":ref:`Availability `: Linux >= 5.1" -msgstr ":ref:`Disponibilidade `: Linux >= 5.1" +"Veja a página man :manpage:`pidfd_send_signal(2)` para mais informações." #: ../../library/signal.rst:420 msgid "" @@ -493,19 +604,33 @@ msgid "" "point of sending a signal to a particular Python thread would be to force a " "running system call to fail with :exc:`InterruptedError`." msgstr "" +"Envia o sinal *signalnum* para a thread *thread_id*, outra thread no mesmo " +"processo que a chamadora. A thread alvo pode estar executando qualquer " +"código (Python ou não). No entanto, se a thread alvo estiver executando o " +"interpretador Python, os manipuladores de sinal Python serão :ref:" +"`executados pela thread principal do interpretador principal `. Portanto, o único objetivo de enviar um sinal para uma thread " +"Python específica seria forçar uma chamada de sistema em execução a falhar " +"com :exc:`InterruptedError`." #: ../../library/signal.rst:428 msgid "" -"Use :func:`threading.get_ident()` or the :attr:`~threading.Thread.ident` " +"Use :func:`threading.get_ident` or the :attr:`~threading.Thread.ident` " "attribute of :class:`threading.Thread` objects to get a suitable value for " "*thread_id*." msgstr "" +"Utilize a :func:`threading.get_ident` ou o atributo :attr:`~threading.Thread." +"ident` dos objetos :class:`threading.Thread` para obter um valor adequado " +"para *thread_id*." #: ../../library/signal.rst:432 msgid "" "If *signalnum* is 0, then no signal is sent, but error checking is still " "performed; this can be used to check if the target thread is still running." msgstr "" +"Se *signalnum* for 0, nenhum sinal será enviado, mas a verificação de erros " +"ainda será realizada; isso pode ser usado para verificar se a thread de " +"destino ainda está em execução." #: ../../library/signal.rst:435 msgid "" @@ -517,11 +642,11 @@ msgstr "" #: ../../library/signal.rst:439 msgid "See the man page :manpage:`pthread_kill(3)` for further information." -msgstr "" +msgstr "Veja a página man :manpage:`pthread_kill(3)` para mais informações." #: ../../library/signal.rst:441 msgid "See also :func:`os.kill`." -msgstr "" +msgstr "Veja também :func:`os.kill`." #: ../../library/signal.rst:448 msgid "" @@ -529,17 +654,22 @@ msgid "" "is the set of signals whose delivery is currently blocked for the caller. " "Return the old signal mask as a set of signals." msgstr "" +"Busca e/ou altera a máscara de sinal da thread chamadora. A máscara de sinal " +"é o conjunto de sinais cuja entrega está atualmente bloqueada para o " +"chamador. Retorna a máscara de sinal antiga como um conjunto de sinais." #: ../../library/signal.rst:452 msgid "" "The behavior of the call is dependent on the value of *how*, as follows." -msgstr "" +msgstr "O comportamento da chamada depende do valor de *how*, como segue." #: ../../library/signal.rst:454 msgid "" ":data:`SIG_BLOCK`: The set of blocked signals is the union of the current " "set and the *mask* argument." msgstr "" +":data:`SIG_BLOCK`: O conjunto de sinais bloqueados é a união do conjunto " +"atual e do argumento *mask*." #: ../../library/signal.rst:456 msgid "" @@ -547,12 +677,17 @@ msgid "" "of blocked signals. It is permissible to attempt to unblock a signal which " "is not blocked." msgstr "" +":data:`SIG_UNBLOCK`: Os sinais em *mask* são removidos do conjunto atual de " +"sinais bloqueados. É permitido tentar desbloquear um sinal que não esteja " +"bloqueado." #: ../../library/signal.rst:459 msgid "" ":data:`SIG_SETMASK`: The set of blocked signals is set to the *mask* " "argument." msgstr "" +":data:`SIG_SETMASK`: O conjunto de sinais bloqueados é definido como o " +"argumento *mask*." #: ../../library/signal.rst:462 msgid "" @@ -560,16 +695,21 @@ msgid "" "`signal.SIGTERM`}). Use :func:`~signal.valid_signals` for a full mask " "including all signals." msgstr "" +"*mask* é um conjunto de números de sinais (ex.: {:const:`signal.SIGINT`, :" +"const:`signal.SIGTERM`}). Use :func:`~signal.valid_signals` para uma máscara " +"completa, incluindo todos os sinais." #: ../../library/signal.rst:466 msgid "" "For example, ``signal.pthread_sigmask(signal.SIG_BLOCK, [])`` reads the " "signal mask of the calling thread." msgstr "" +"Por exemplo, ``signal.pthread_sigmask(signal.SIG_BLOCK, [])`` lê a máscara " +"de sinal da thread de chamada." #: ../../library/signal.rst:469 msgid ":data:`SIGKILL` and :data:`SIGSTOP` cannot be blocked." -msgstr "" +msgstr ":data:`SIGKILL` e :data:`SIGSTOP` não podem ser bloqueados." #: ../../library/signal.rst:476 msgid "See also :func:`pause`, :func:`sigpending` and :func:`sigwait`." @@ -584,6 +724,12 @@ msgid "" "interval timer specified by *which* can be cleared by setting *seconds* to " "zero." msgstr "" +"Define o temporizador de intervalo fornecido (um dos seguintes: :const:" +"`signal.ITIMER_REAL`, :const:`signal.ITIMER_VIRTUAL` ou :const:`signal." +"ITIMER_PROF`) especificado por *which* para disparar após *seconds* (float é " +"aceito, diferente de :func:`alarm`) e, depois disso, a cada *interval* " +"segundos (se *interval* for diferente de zero). O temporizador de intervalo " +"especificado por *which* pode ser zerado definindo *seconds* como zero." #: ../../library/signal.rst:490 msgid "" @@ -592,53 +738,80 @@ msgid "" "deliver :const:`SIGALRM`, :const:`signal.ITIMER_VIRTUAL` sends :const:" "`SIGVTALRM`, and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`." msgstr "" +"Quando um temporizador de intervalo dispara, um sinal é enviado ao processo. " +"O sinal enviado depende do temporizador utilizado; :const:`signal." +"ITIMER_REAL` enviará :const:`SIGALRM`, :const:`signal.ITIMER_VIRTUAL` " +"enviará :const:`SIGVTALRM` e :const:`signal.ITIMER_PROF` enviará :const:" +"`SIGPROF`." #: ../../library/signal.rst:496 msgid "The old values are returned as a tuple: (delay, interval)." -msgstr "" +msgstr "Os valores antigos são retornados como uma tupla: (atraso, intervalo)." #: ../../library/signal.rst:498 msgid "" "Attempting to pass an invalid interval timer will cause an :exc:" "`ItimerError`." msgstr "" +"Tentar passar um intervalo de tempo inválido causará uma :exc:`ItimerError`." #: ../../library/signal.rst:506 msgid "Returns current value of a given interval timer specified by *which*." msgstr "" +"Retorna o valor atual de um intervalo de tempo especificado por *which*." #: ../../library/signal.rst:513 msgid "" -"Set the wakeup file descriptor to *fd*. When a signal is received, the " -"signal number is written as a single byte into the fd. This can be used by " -"a library to wakeup a poll or select call, allowing the signal to be fully " -"processed." +"Set the wakeup file descriptor to *fd*. When a signal your program has " +"registered a signal handler for is received, the signal number is written as " +"a single byte into the fd. If you haven't registered a signal handler for " +"the signals you care about, then nothing will be written to the wakeup fd. " +"This can be used by a library to wakeup a poll or select call, allowing the " +"signal to be fully processed." msgstr "" +"Define o descritor de arquivo de ativação como *fd*. Quando um sinal para o " +"qual seu programa registrou um manipulador de sinais é recebido, o número do " +"sinal é escrito como um único byte no fd. Se você não registrou um " +"manipulador de sinais para os sinais de seu interesse, nada será escrito no " +"fd de ativação. Isso pode ser usado por uma biblioteca para ativar uma " +"chamada de poll ou seleção, permitindo que o sinal seja totalmente " +"processado." -#: ../../library/signal.rst:518 +#: ../../library/signal.rst:520 msgid "" "The old wakeup fd is returned (or -1 if file descriptor wakeup was not " "enabled). If *fd* is -1, file descriptor wakeup is disabled. If not -1, " "*fd* must be non-blocking. It is up to the library to remove any bytes from " "*fd* before calling poll or select again." msgstr "" +"O antigo fd de ativação é retornado (ou -1 se a ativação do descritor de " +"arquivo não estava habilitada). Se *fd* for -1, a ativação do descritor de " +"arquivo está desabilitada. Se não for -1, *fd* deve ser não bloqueante. Cabe " +"à biblioteca remover quaisquer bytes de *fd* antes de chamar poll ou select " +"novamente." -#: ../../library/signal.rst:523 ../../library/signal.rst:578 +#: ../../library/signal.rst:525 ../../library/signal.rst:580 msgid "" "When threads are enabled, this function can only be called from :ref:`the " "main thread of the main interpreter `; attempting to " "call it from other threads will cause a :exc:`ValueError` exception to be " "raised." msgstr "" +"Quando threads estão habilitadas, esta função só pode ser chamada da :ref:" +"`thread principal do interpretador principal `; tentar " +"chamá-la de outras threads levantará uma exceção :exc:`ValueError`." -#: ../../library/signal.rst:528 +#: ../../library/signal.rst:530 msgid "" "There are two common ways to use this function. In both approaches, you use " "the fd to wake up when a signal arrives, but then they differ in how they " "determine *which* signal or signals have arrived." msgstr "" +"Há duas maneiras comuns de usar esta função. Em ambas as abordagens, você " +"usa o fd para despertar quando um sinal chega, mas elas diferem na forma " +"como determinam *which* sinal ou sinais chegaram." -#: ../../library/signal.rst:533 +#: ../../library/signal.rst:535 msgid "" "In the first approach, we read the data out of the fd's buffer, and the byte " "values give you the signal numbers. This is simple, but in rare cases it can " @@ -648,8 +821,15 @@ msgid "" "you should set ``warn_on_full_buffer=True``, which will at least cause a " "warning to be printed to stderr when signals are lost." msgstr "" +"Na primeira abordagem, lemos os dados do buffer do fd, e os valores dos " +"bytes fornecem os números dos sinais. Isso é simples, mas em casos raros " +"pode apresentar um problema: geralmente, o fd terá um espaço de buffer " +"limitado e, se muitos sinais chegarem muito rápido, o buffer pode ficar " +"cheio e alguns sinais podem ser perdidos. Se você usar essa abordagem, " +"defina ``warn_on_full_buffer=True``, o que pelo menos fará com que um aviso " +"seja impresso no stderr quando os sinais forem perdidos." -#: ../../library/signal.rst:542 +#: ../../library/signal.rst:544 msgid "" "In the second approach, we use the wakeup fd *only* for wakeups, and ignore " "the actual byte values. In this case, all we care about is whether the fd's " @@ -658,34 +838,47 @@ msgid "" "``warn_on_full_buffer=False``, so that your users are not confused by " "spurious warning messages." msgstr "" +"Na segunda abordagem, usamos o fd de ativação *apenas* para ativações e " +"ignoramos os valores de bytes reais. Nesse caso, tudo o que importa é se o " +"buffer do fd está vazio ou não; um buffer cheio não indica nenhum problema. " +"Se você usar essa abordagem, defina ``warn_on_full_buffer=False`` para que " +"seus usuários não sejam confundidos por mensagens de aviso falsas." -#: ../../library/signal.rst:549 +#: ../../library/signal.rst:551 msgid "On Windows, the function now also supports socket handles." msgstr "No Windows, a função agora também suporta manipuladores de socket." -#: ../../library/signal.rst:552 +#: ../../library/signal.rst:554 msgid "Added ``warn_on_full_buffer`` parameter." -msgstr "" +msgstr "Adiciona o parâmetro ``warn_on_full_buffer``." -#: ../../library/signal.rst:557 +#: ../../library/signal.rst:559 msgid "" "Change system call restart behaviour: if *flag* is :const:`False`, system " "calls will be restarted when interrupted by signal *signalnum*, otherwise " "system calls will be interrupted. Returns nothing." msgstr "" +"Altera o comportamento de reinicialização de chamadas de sistema: se *flag* " +"for :const:`False`, as chamadas de sistema serão reiniciadas quando " +"interrompidas pelo sinal *signalnum*; caso contrário, as chamadas de sistema " +"serão interrompidas. Não retorna nada." -#: ../../library/signal.rst:563 +#: ../../library/signal.rst:565 msgid "See the man page :manpage:`siginterrupt(3)` for further information." -msgstr "" +msgstr "Veja a página man :manpage:`siginterrupt(3)` para mais informações." -#: ../../library/signal.rst:565 +#: ../../library/signal.rst:567 msgid "" "Note that installing a signal handler with :func:`signal` will reset the " "restart behaviour to interruptible by implicitly calling :c:func:`!" "siginterrupt` with a true *flag* value for the given signal." msgstr "" +"Observe que a instalação de um manipulador de sinal com :func:`signal` " +"redefinirá o comportamento de reinicialização para interrompível ao chamar " +"implicitamente :c:func:`!siginterrupt` com *flag* contendo valor verdadeiro " +"para o sinal fornecido." -#: ../../library/signal.rst:572 +#: ../../library/signal.rst:574 msgid "" "Set the handler for signal *signalnum* to the function *handler*. *handler* " "can be a callable Python object taking two arguments (see below), or one of " @@ -694,16 +887,26 @@ msgid "" "`getsignal` above). (See the Unix man page :manpage:`signal(2)` for further " "information.)" msgstr "" +"Define o manipulador do sinal *signalnum* para a função *handler*. *handler* " +"pode ser um objeto Python invocável que recebe dois argumentos (veja " +"abaixo), ou um dos valores especiais :const:`signal.SIG_IGN` ou :const:" +"`signal.SIG_DFL`. O manipulador de sinal anterior será retornado (veja a " +"descrição de :func:`getsignal` acima). (Consulte a página man do Unix :" +"manpage:`signal(2)` para mais informações.)" -#: ../../library/signal.rst:583 +#: ../../library/signal.rst:585 msgid "" "The *handler* is called with two arguments: the signal number and the " "current stack frame (``None`` or a frame object; for a description of frame " "objects, see the :ref:`description in the type hierarchy ` or " "see the attribute descriptions in the :mod:`inspect` module)." msgstr "" +"O *handler* é chamado com dois argumentos: o número do sinal e o quadro de " +"pilha atual (``None`` ou um objeto quadro; para uma descrição dos objetos " +"quadro, consulte a :ref:`descrição na hierarquia de tipo ` ou " +"consulte as descrições de atributo no módulo :mod:`inspect`)." -#: ../../library/signal.rst:588 +#: ../../library/signal.rst:590 msgid "" "On Windows, :func:`signal` can only be called with :const:`SIGABRT`, :const:" "`SIGFPE`, :const:`SIGILL`, :const:`SIGINT`, :const:`SIGSEGV`, :const:" @@ -712,41 +915,56 @@ msgid "" "an :exc:`AttributeError` will be raised if a signal name is not defined as " "``SIG*`` module level constant." msgstr "" +"No Windows, :func:`signal` só pode ser chamado com :const:`SIGABRT`, :const:" +"`SIGFPE`, :const:`SIGILL`, :const:`SIGINT`, :const:`SIGSEGV`, :const:" +"`SIGTERM` ou :const:`SIGBREAK`. Uma exceção :exc:`ValueError` será levantada " +"em qualquer outro caso. Observe que nem todos os sistemas definem o mesmo " +"conjunto de nomes de sinais; uma exceção :exc:`AttributeError` será " +"levantada se um nome de sinal não for definido como constante de nível de " +"módulo ``SIG*``." -#: ../../library/signal.rst:599 +#: ../../library/signal.rst:601 msgid "" "Examine the set of signals that are pending for delivery to the calling " "thread (i.e., the signals which have been raised while blocked). Return the " "set of the pending signals." msgstr "" +"Examine o conjunto de sinais pendentes para entrega ao thread de chamada (ou " +"seja, os sinais que foram gerados enquanto bloqueados). Retorne o conjunto " +"de sinais pendentes." -#: ../../library/signal.rst:605 +#: ../../library/signal.rst:607 msgid "See the man page :manpage:`sigpending(2)` for further information." -msgstr "" +msgstr "Veja a página man :manpage:`sigpending(2)` para mais informações." -#: ../../library/signal.rst:607 +#: ../../library/signal.rst:609 msgid "See also :func:`pause`, :func:`pthread_sigmask` and :func:`sigwait`." msgstr "Veja também :func:`pause`, :func:`pthread_sigmask` e :func:`sigwait`." -#: ../../library/signal.rst:614 +#: ../../library/signal.rst:616 msgid "" "Suspend execution of the calling thread until the delivery of one of the " "signals specified in the signal set *sigset*. The function accepts the " "signal (removes it from the pending list of signals), and returns the signal " "number." msgstr "" +"Suspende a execução do thread de chamada até a entrega de um dos sinais " +"especificados no conjunto de sinais *sigset*. A função aceita o sinal " +"(remove-o da lista de sinais pendentes) e retorna o número do sinal." -#: ../../library/signal.rst:620 +#: ../../library/signal.rst:622 msgid "See the man page :manpage:`sigwait(3)` for further information." -msgstr "" +msgstr "Veja a página man :manpage:`sigwait(3)` para mais informações." -#: ../../library/signal.rst:622 +#: ../../library/signal.rst:624 msgid "" "See also :func:`pause`, :func:`pthread_sigmask`, :func:`sigpending`, :func:" "`sigwaitinfo` and :func:`sigtimedwait`." msgstr "" +"Veja também :func:`pause`, :func:`pthread_sigmask`, :func:`sigpending`, :" +"func:`sigwaitinfo` e :func:`sigtimedwait`." -#: ../../library/signal.rst:630 +#: ../../library/signal.rst:632 msgid "" "Suspend execution of the calling thread until the delivery of one of the " "signals specified in the signal set *sigset*. The function accepts the " @@ -756,57 +974,78 @@ msgid "" "handler is not called for the delivered signal. The function raises an :exc:" "`InterruptedError` if it is interrupted by a signal that is not in *sigset*." msgstr "" +"Suspende a execução da thread chamadora até a entrega de um dos sinais " +"especificados no conjunto de sinais *sigset*. A função aceita o sinal e o " +"remove da lista de sinais pendentes. Se um dos sinais em *sigset* já estiver " +"pendente para a thread chamadora, a função retornará imediatamente com " +"informações sobre esse sinal. O manipulador de sinais não é chamado para o " +"sinal entregue. A função levanta :exc:`InterruptedError` se for interrompida " +"por um sinal que não esteja em *sigset*." -#: ../../library/signal.rst:639 +#: ../../library/signal.rst:641 msgid "" "The return value is an object representing the data contained in the :c:type:" "`siginfo_t` structure, namely: :attr:`si_signo`, :attr:`si_code`, :attr:" "`si_errno`, :attr:`si_pid`, :attr:`si_uid`, :attr:`si_status`, :attr:" "`si_band`." msgstr "" +"O valor de retorno é um objeto que representa os dados contidos na estrutura " +"de :c:type:`siginfo_t`, a saber: :attr:`si_signo`, :attr:`si_code`, :attr:" +"`si_errno`, :attr:`si_pid`, :attr:`si_uid`, :attr:`si_status`, :attr:" +"`si_band`." -#: ../../library/signal.rst:646 +#: ../../library/signal.rst:648 msgid "See the man page :manpage:`sigwaitinfo(2)` for further information." -msgstr "" +msgstr "Veja a página man :manpage:`sigwaitinfo(2)` para mais informações." -#: ../../library/signal.rst:648 +#: ../../library/signal.rst:650 msgid "See also :func:`pause`, :func:`sigwait` and :func:`sigtimedwait`." -msgstr "" +msgstr "Veja também :func:`pause`, :func:`sigwait` e :func:`sigtimedwait`." -#: ../../library/signal.rst:652 +#: ../../library/signal.rst:654 msgid "" "The function is now retried if interrupted by a signal not in *sigset* and " "the signal handler does not raise an exception (see :pep:`475` for the " "rationale)." msgstr "" +"A função agora é tentada novamente se interrompida por um sinal que não " +"esteja em *sigset* e o manipulador de sinal não levanta uma exceção (veja :" +"pep:`475` para a justificativa)." -#: ../../library/signal.rst:660 +#: ../../library/signal.rst:662 msgid "" "Like :func:`sigwaitinfo`, but takes an additional *timeout* argument " "specifying a timeout. If *timeout* is specified as ``0``, a poll is " "performed. Returns :const:`None` if a timeout occurs." msgstr "" +"Semelhante a :func:`sigwaitinfo`, mas recebe um argumento *timeout* " +"adicional que especifica um tempo limite. Se *timeout* for especificado como " +"``0``, uma consulta será realizada. Retorna :const:`None` se ocorrer um " +"tempo limite." -#: ../../library/signal.rst:666 +#: ../../library/signal.rst:668 msgid "See the man page :manpage:`sigtimedwait(2)` for further information." -msgstr "" +msgstr "Veja a página man :manpage:`sigtimedwait(2)` para mais informações." -#: ../../library/signal.rst:668 +#: ../../library/signal.rst:670 msgid "See also :func:`pause`, :func:`sigwait` and :func:`sigwaitinfo`." -msgstr "" +msgstr "Veja também :func:`pause`, :func:`sigwait` e :func:`sigwaitinfo`." -#: ../../library/signal.rst:672 +#: ../../library/signal.rst:674 msgid "" "The function is now retried with the recomputed *timeout* if interrupted by " "a signal not in *sigset* and the signal handler does not raise an exception " "(see :pep:`475` for the rationale)." msgstr "" +"A função agora é tentada novamente com o *timeout* recalculado se " +"interrompida por um sinal que não esteja em *sigset* e o manipulador de " +"sinal não levanta uma exceção (veja :pep:`475` para a justificativa)." -#: ../../library/signal.rst:681 +#: ../../library/signal.rst:683 msgid "Examples" msgstr "Exemplos" -#: ../../library/signal.rst:683 +#: ../../library/signal.rst:685 msgid "" "Here is a minimal example program. It uses the :func:`alarm` function to " "limit the time spent waiting to open a file; this is useful if the file is " @@ -815,12 +1054,53 @@ msgid "" "alarm before opening the file; if the operation takes too long, the alarm " "signal will be sent, and the handler raises an exception. ::" msgstr "" +"Aqui está um programa de exemplo mínimo. Ele usa a função :func:`alarm` para " +"limitar o tempo gasto esperando para abrir um arquivo; isso é útil se o " +"arquivo for para um dispositivo serial que pode não estar ligado, o que " +"normalmente faria com que o :func:`os.open` travasse indefinidamente. A " +"solução é definir um alarme de 5 segundos antes de abrir o arquivo; se a " +"operação demorar muito, o sinal de alarme será enviado e o manipulador " +"levantará uma exceção. ::" + +#: ../../library/signal.rst:692 +msgid "" +"import signal, os\n" +"\n" +"def handler(signum, frame):\n" +" signame = signal.Signals(signum).name\n" +" print(f'Signal handler called with signal {signame} ({signum})')\n" +" raise OSError(\"Couldn't open device!\")\n" +"\n" +"# Set the signal handler and a 5-second alarm\n" +"signal.signal(signal.SIGALRM, handler)\n" +"signal.alarm(5)\n" +"\n" +"# This open() may hang indefinitely\n" +"fd = os.open('/dev/ttyS0', os.O_RDWR)\n" +"\n" +"signal.alarm(0) # Disable the alarm" +msgstr "" +"import signal, os\n" +"\n" +"def handler(signum, frame):\n" +" signame = signal.Signals(signum).name\n" +" print(f'Signal handler called with signal {signame} ({signum})')\n" +" raise OSError(\"Couldn't open device!\")\n" +"\n" +"# Define o manipulador de sinal e um alarme de 5 segundos\n" +"signal.signal(signal.SIGALRM, handler)\n" +"signal.alarm(5)\n" +"\n" +"# Este open() pode travar indefinidamente\n" +"fd = os.open('/dev/ttyS0', os.O_RDWR)\n" +"\n" +"signal.alarm(0) # Desabilita o alarme" -#: ../../library/signal.rst:707 +#: ../../library/signal.rst:709 msgid "Note on SIGPIPE" -msgstr "" +msgstr "Nota sobre SIGPIPE" -#: ../../library/signal.rst:709 +#: ../../library/signal.rst:711 msgid "" "Piping output of your program to tools like :manpage:`head(1)` will cause a :" "const:`SIGPIPE` signal to be sent to your process when the receiver of its " @@ -828,20 +1108,76 @@ msgid "" "`BrokenPipeError: [Errno 32] Broken pipe`. To handle this case, wrap your " "entry point to catch this exception as follows::" msgstr "" - -#: ../../library/signal.rst:736 +"Canalizar a saída do seu programa para ferramentas como :manpage:`head(1)` " +"fará com que um sinal :const:`SIGPIPE` seja enviado ao seu processo quando o " +"receptor da saída padrão fechar antes do tempo. Isso resulta em uma exceção " +"como :code:`BrokenPipeError: [Errno 32] Broken pipe`. Para lidar com esse " +"caso, envolva seu ponto de entrada para capturar essa exceção da seguinte " +"maneira:" + +#: ../../library/signal.rst:717 +msgid "" +"import os\n" +"import sys\n" +"\n" +"def main():\n" +" try:\n" +" # simulate large output (your code replaces this loop)\n" +" for x in range(10000):\n" +" print(\"y\")\n" +" # flush output here to force SIGPIPE to be triggered\n" +" # while inside this try block.\n" +" sys.stdout.flush()\n" +" except BrokenPipeError:\n" +" # Python flushes standard streams on exit; redirect remaining " +"output\n" +" # to devnull to avoid another BrokenPipeError at shutdown\n" +" devnull = os.open(os.devnull, os.O_WRONLY)\n" +" os.dup2(devnull, sys.stdout.fileno())\n" +" sys.exit(1) # Python exits with error code 1 on EPIPE\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" +"import os\n" +"import sys\n" +"\n" +"def main():\n" +" try:\n" +" # simula uma saída grande (seu código substitui este loop)\n" +" for x in range(10000):\n" +" print(\"y\")\n" +" # limpa a saída aqui para forçar o acionamento do SIGPIPE\n" +" # enquanto estiver dentro deste bloco try.\n" +" sys.stdout.flush()\n" +" except BrokenPipeError:\n" +" # Python libera fluxos padrão na saída; redireciona a saída " +"restante\n" +" # para devnull para evitar outro BrokenPipeError no desligamento\n" +" devnull = os.open(os.devnull, os.O_WRONLY)\n" +" os.dup2(devnull, sys.stdout.fileno())\n" +" sys.exit(1) # Python exits with error code 1 on EPIPE\n" +"\n" +"if __name__ == '__main__':\n" +" main()" + +#: ../../library/signal.rst:738 msgid "" "Do not set :const:`SIGPIPE`'s disposition to :const:`SIG_DFL` in order to " "avoid :exc:`BrokenPipeError`. Doing that would cause your program to exit " "unexpectedly whenever any socket connection is interrupted while your " "program is still writing to it." msgstr "" +"Não defina a disposição de :const:`SIGPIPE` como :const:`SIG_DFL` para " +"evitar :exc:`BrokenPipeError`. Isso faria com que seu programa encerrasse " +"inesperadamente sempre que qualquer conexão de soquete fosse interrompida " +"enquanto o programa ainda estivesse escrevendo nele." -#: ../../library/signal.rst:745 +#: ../../library/signal.rst:747 msgid "Note on Signal Handlers and Exceptions" -msgstr "" +msgstr "Nota sobre manipuladores de sinais e exceções" -#: ../../library/signal.rst:747 +#: ../../library/signal.rst:749 msgid "" "If a signal handler raises an exception, the exception will be propagated to " "the main thread and may be raised after any :term:`bytecode` instruction. " @@ -851,12 +1187,52 @@ msgid "" "exception resulting from a signal handler) may on rare occasions put the " "program in an unexpected state." msgstr "" +"Se um manipulador de sinais levantar uma exceção, a exceção será propagada " +"para a thread principal e poderá ser levantada após qualquer instrução :term:" +"`bytecode`. Mais notavelmente, uma :exc:`KeyboardInterrupt` pode aparecer a " +"qualquer momento durante a execução. A maioria dos códigos Python, incluindo " +"a biblioteca padrão, não pode ser robusta contra isso, e, portanto, uma :exc:" +"`KeyboardInterrupt` (ou qualquer outra exceção resultante de um manipulador " +"de sinais) pode, em raras ocasiões, colocar o programa em um estado " +"inesperado." -#: ../../library/signal.rst:754 +#: ../../library/signal.rst:756 msgid "To illustrate this issue, consider the following code::" -msgstr "" - -#: ../../library/signal.rst:771 +msgstr "Para ilustrar esse problema, considere o seguinte código:" + +#: ../../library/signal.rst:758 +msgid "" +"class SpamContext:\n" +" def __init__(self):\n" +" self.lock = threading.Lock()\n" +"\n" +" def __enter__(self):\n" +" # If KeyboardInterrupt occurs here, everything is fine\n" +" self.lock.acquire()\n" +" # If KeyboardInterrupt occurs here, __exit__ will not be called\n" +" ...\n" +" # KeyboardInterrupt could occur just before the function returns\n" +"\n" +" def __exit__(self, exc_type, exc_val, exc_tb):\n" +" ...\n" +" self.lock.release()" +msgstr "" +"class SpamContext:\n" +" def __init__(self):\n" +" self.lock = threading.Lock()\n" +"\n" +" def __enter__(self):\n" +" # Se ocorrer KeyboardInterrupt aqui, está tudo bem\n" +" self.lock.acquire()\n" +" # Se KeyboardInterrupt ocorrer aqui, __exit__ não será chamado\n" +" ...\n" +" # KeyboardInterrupt pode ocorrer logo antes do retorno da função\n" +"\n" +" def __exit__(self, exc_type, exc_val, exc_tb):\n" +" ...\n" +" self.lock.release()" + +#: ../../library/signal.rst:773 msgid "" "For many programs, especially those that merely want to exit on :exc:" "`KeyboardInterrupt`, this is not a problem, but applications that are " @@ -866,3 +1242,72 @@ msgid "" "own :const:`SIGINT` handler. Below is an example of an HTTP server that " "avoids :exc:`KeyboardInterrupt`::" msgstr "" +"Para muitos programas, especialmente aqueles que simplesmente desejam " +"encerrar em :exc:`KeyboardInterrupt`, isso não é um problema, mas aplicações " +"complexos ou que exigem alta confiabilidade devem evitar levantar exceções " +"de manipuladores de sinal. Eles também devem evitar capturar :exc:" +"`KeyboardInterrupt` como forma de encerrar o programa sem problemas. Em vez " +"disso, devem instalar seu próprio manipulador :const:`SIGINT`. Abaixo está " +"um exemplo de um servidor HTTP que evita :exc:`KeyboardInterrupt`::" + +#: ../../library/signal.rst:781 +msgid "" +"import signal\n" +"import socket\n" +"from selectors import DefaultSelector, EVENT_READ\n" +"from http.server import HTTPServer, SimpleHTTPRequestHandler\n" +"\n" +"interrupt_read, interrupt_write = socket.socketpair()\n" +"\n" +"def handler(signum, frame):\n" +" print('Signal handler called with signal', signum)\n" +" interrupt_write.send(b'\\0')\n" +"signal.signal(signal.SIGINT, handler)\n" +"\n" +"def serve_forever(httpd):\n" +" sel = DefaultSelector()\n" +" sel.register(interrupt_read, EVENT_READ)\n" +" sel.register(httpd, EVENT_READ)\n" +"\n" +" while True:\n" +" for key, _ in sel.select():\n" +" if key.fileobj == interrupt_read:\n" +" interrupt_read.recv(1)\n" +" return\n" +" if key.fileobj == httpd:\n" +" httpd.handle_request()\n" +"\n" +"print(\"Serving on port 8000\")\n" +"httpd = HTTPServer(('', 8000), SimpleHTTPRequestHandler)\n" +"serve_forever(httpd)\n" +"print(\"Shutdown...\")" +msgstr "" +"import signal\n" +"import socket\n" +"from selectors import DefaultSelector, EVENT_READ\n" +"from http.server import HTTPServer, SimpleHTTPRequestHandler\n" +"\n" +"interrupt_read, interrupt_write = socket.socketpair()\n" +"\n" +"def handler(signum, frame):\n" +" print('Signal handler called with signal', signum)\n" +" interrupt_write.send(b'\\0')\n" +"signal.signal(signal.SIGINT, handler)\n" +"\n" +"def serve_forever(httpd):\n" +" sel = DefaultSelector()\n" +" sel.register(interrupt_read, EVENT_READ)\n" +" sel.register(httpd, EVENT_READ)\n" +"\n" +" while True:\n" +" for key, _ in sel.select():\n" +" if key.fileobj == interrupt_read:\n" +" interrupt_read.recv(1)\n" +" return\n" +" if key.fileobj == httpd:\n" +" httpd.handle_request()\n" +"\n" +"print(\"Serving on port 8000\")\n" +"httpd = HTTPServer(('', 8000), SimpleHTTPRequestHandler)\n" +"serve_forever(httpd)\n" +"print(\"Shutdown...\")" diff --git a/library/site.po b/library/site.po index 2741125ce..fdeb6376d 100644 --- a/library/site.po +++ b/library/site.po @@ -1,35 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Adorilson Bezerra , 2021 -# i17obot , 2021 -# Marco Rougeth , 2023 -# Vinicius Gubiani Ferreira , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:13+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-07 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/site.rst:2 msgid ":mod:`!site` --- Site-specific configuration hook" -msgstr "" +msgstr ":mod:`!site` --- Gancho de configuração específico do site" #: ../../library/site.rst:7 msgid "**Source code:** :source:`Lib/site.py`" @@ -47,14 +43,23 @@ msgstr "" #: ../../library/site.rst:18 msgid "" -"Importing this module will append site-specific paths to the module search " -"path and add a few builtins, unless :option:`-S` was used. In that case, " -"this module can be safely imported with no automatic modifications to the " -"module search path or additions to the builtins. To explicitly trigger the " -"usual site-specific additions, call the :func:`main` function." -msgstr "" - -#: ../../library/site.rst:24 +"Importing this module normally appends site-specific paths to the module " +"search path and adds :ref:`callables `, including :func:`help` " +"to the built-in namespace. However, Python startup option :option:`-S` " +"blocks this and this module can be safely imported with no automatic " +"modifications to the module search path or additions to the builtins. To " +"explicitly trigger the usual site-specific additions, call the :func:`main` " +"function." +msgstr "" +"A importação deste módulo normalmente anexa caminhos específicos do site ao " +"caminho de pesquisa de módulos e adiciona :ref:`chamáveis `, " +"incluindo :func:`help` ao espaço de nomes embutido. No entanto, a opção de " +"inicialização do Python :option:`-S` bloqueia isso e este módulo pode ser " +"importado com segurança sem modificações automáticas no caminho de pesquisa " +"de módulos ou adições aos módulos embutidos. Para acionar explicitamente as " +"adições usuais específicas do site, chame a função :func:`main`." + +#: ../../library/site.rst:25 msgid "" "Importing the module used to trigger paths manipulation even when using :" "option:`-S`." @@ -62,7 +67,7 @@ msgstr "" "A importação do módulo usado para acionar a manipulação de caminhos, mesmo " "ao usar :option:`-S`." -#: ../../library/site.rst:31 +#: ../../library/site.rst:32 msgid "" "It starts by constructing up to four directories from a head and a tail " "part. For the head part, it uses ``sys.prefix`` and ``sys.exec_prefix``; " @@ -70,24 +75,37 @@ msgid "" "then :file:`lib/site-packages` (on Windows) or :file:`lib/python{X.Y[t]}/" "site-packages` (on Unix and macOS). (The optional suffix \"t\" indicates " "the :term:`free threading` build, and is appended if ``\"t\"`` is present in " -"the :attr:`sys.abiflags` constant.) For each of the distinct head-tail " +"the :data:`sys.abiflags` constant.) For each of the distinct head-tail " "combinations, it sees if it refers to an existing directory, and if so, adds " "it to ``sys.path`` and also inspects the newly added path for configuration " "files." msgstr "" - -#: ../../library/site.rst:43 +"Ele começa construindo até quatro diretórios a partir de uma parte no início " +"e uma no final. Para a parte no início, ele usa ``sys.prefix`` e ``sys." +"exec_prefix``; inícios vazios são ignorados. Para a parte no final, ele usa " +"a string vazia e então :file:`lib/site-packages` (no Windows) ou :file:`lib/" +"python{X.Y[t]}/site-packages` (no Unix e macOS). (O sufixo opcional \"t\" " +"indica a construção de :term:`threads livres` e é anexado se ``\"t\"`` " +"estiver presente na constante :data:`sys.abiflags`.) Para cada uma das " +"combinações distintas início-fim, ele vê se se refere a um diretório " +"existente e, se sim, adiciona-o a ``sys.path`` e também inspeciona o caminho " +"recém-adicionado para arquivos de configuração." + +#: ../../library/site.rst:44 msgid "Support for the \"site-python\" directory has been removed." msgstr "Suporte para o diretório \"site-python\" foi removido." -#: ../../library/site.rst:46 +#: ../../library/site.rst:47 msgid "" "On Unix, :term:`Free threading ` Python installations are " "identified by the \"t\" suffix in the version-specific directory name, such " "as :file:`lib/python3.13t/`." msgstr "" +"No Unix, as instalações do Python :term:`threads livres ` " +"são identificadas pelo sufixo \"t\" no nome do diretório específico da " +"versão, como :file:`lib/python3.13t/`." -#: ../../library/site.rst:51 +#: ../../library/site.rst:52 msgid "" "If a file named \"pyvenv.cfg\" exists one directory above sys.executable, " "sys.prefix and sys.exec_prefix are set to that directory and it is also " @@ -108,7 +126,7 @@ msgstr "" "prefixos no nível do sistema não serão pesquisados quanto ao site-packages; " "caso contrário, eles irão." -#: ../../library/site.rst:64 +#: ../../library/site.rst:65 msgid "" "A path configuration file is a file whose name has the form :file:`{name}." "pth` and exists in one of the four directories mentioned above; its contents " @@ -128,7 +146,7 @@ msgstr "" "iniciadas com ``#`` são ignoradas. Linhas iniciadas com ``import`` (seguidas " "de espaço ou tabulação) são executadas." -#: ../../library/site.rst:74 +#: ../../library/site.rst:75 msgid "" "An executable line in a :file:`.pth` file is run at every Python startup, " "regardless of whether a particular module is actually going to be used. Its " @@ -142,20 +160,22 @@ msgstr "" "Uma linha executável em um arquivo :file:`.pth` é executada a cada " "inicialização do Python, independentemente de um módulo em particular ser " "realmente usado. Seu impacto deve, portanto, ser reduzido ao mínimo. O " -"objetivo principal das linhas executáveis ​​é tornar o(s) módulo(s) " +"objetivo principal das linhas executáveis é tornar o(s) módulo(s) " "correspondente(s) importável (carregar ganchos de importação de terceiros, " "ajustar :envvar:`PATH` etc). Qualquer outra inicialização deve ser feita na " "importação real de um módulo, se e quando isso acontecer. Limitar um " "fragmento de código a uma única linha é uma medida deliberada para " "desencorajar colocar qualquer coisa mais complexa aqui." -#: ../../library/site.rst:85 +#: ../../library/site.rst:86 msgid "" "The :file:`.pth` files are now decoded by UTF-8 at first and then by the :" "term:`locale encoding` if it fails." msgstr "" +"Os arquivos :file:`.pth` agora são decodificados primeiro por UTF-8 e depois " +"pela :term:`codificação da localidade` se falhar." -#: ../../library/site.rst:93 +#: ../../library/site.rst:94 msgid "" "For example, suppose ``sys.prefix`` and ``sys.exec_prefix`` are set to :file:" "`/usr/local`. The Python X.Y library is then installed in :file:`/usr/local/" @@ -172,11 +192,35 @@ msgstr "" "configuração, :file:`foo.pth` e :file:`bar.pth`. Presuma que :file:`foo." "pth` contém o seguinte::" -#: ../../library/site.rst:107 +#: ../../library/site.rst:102 +msgid "" +"# foo package configuration\n" +"\n" +"foo\n" +"bar\n" +"bletch" +msgstr "" +"# configuração do pacote foo\n" +"\n" +"foo\n" +"bar\n" +"bletch" + +#: ../../library/site.rst:108 msgid "and :file:`bar.pth` contains::" msgstr "e que :file:`bar.pth` contém::" -#: ../../library/site.rst:113 +#: ../../library/site.rst:110 +msgid "" +"# bar package configuration\n" +"\n" +"bar" +msgstr "" +"# configuração do pacote bar\n" +"\n" +"bar" + +#: ../../library/site.rst:114 msgid "" "Then the following version-specific directories are added to ``sys.path``, " "in this order::" @@ -184,7 +228,15 @@ msgstr "" "Em seguida, os seguintes diretórios específicos da versão são adicionados a " "``sys.path``, nesta ordem::" -#: ../../library/site.rst:119 +#: ../../library/site.rst:117 +msgid "" +"/usr/local/lib/pythonX.Y/site-packages/bar\n" +"/usr/local/lib/pythonX.Y/site-packages/foo" +msgstr "" +"/usr/local/lib/pythonX.Y/site-packages/bar\n" +"/usr/local/lib/pythonX.Y/site-packages/foo" + +#: ../../library/site.rst:120 msgid "" "Note that :file:`bletch` is omitted because it doesn't exist; the :file:" "`bar` directory precedes the :file:`foo` directory because :file:`bar.pth` " @@ -196,11 +248,11 @@ msgstr "" "alfabética antes de :file:`foo.pth`; e :file:`spam` é omitido porque não é " "mencionado em nenhum dos arquivos de configuração de caminho." -#: ../../library/site.rst:125 +#: ../../library/site.rst:126 msgid ":mod:`sitecustomize`" -msgstr "" +msgstr ":mod:`sitecustomize`" -#: ../../library/site.rst:129 +#: ../../library/site.rst:130 msgid "" "After these path manipulations, an attempt is made to import a module named :" "mod:`sitecustomize`, which can perform arbitrary site-specific " @@ -213,12 +265,23 @@ msgid "" "`sitecustomize` is ignored. Any other exception causes a silent and perhaps " "mysterious failure of the process." msgstr "" - -#: ../../library/site.rst:141 +"Após essas manipulações de caminho, é feita uma tentativa de importar um " +"módulo chamado :mod:`sitecustomize`, que pode executar personalizações " +"arbitrárias específicas do site. Ele é normalmente criado por um " +"administrador de sistema no diretório site-packages. Se essa importação " +"falhar com uma :exc:`ImportError` ou sua exceção de subclasse, e o atributo :" +"attr:`~ImportError.name` da exceção for igual a ``'sitecustomize'``, ele " +"será ignorado silenciosamente. Se o Python for iniciado sem fluxos de saída " +"disponíveis, como com :file:`pythonw.exe` no Windows (que é usado por padrão " +"para iniciar o IDLE), a tentativa de saída de :mod:`sitecustomize` será " +"ignorada. Qualquer outra exceção causa uma falha silenciosa e talvez " +"misteriosa do processo." + +#: ../../library/site.rst:142 msgid ":mod:`usercustomize`" -msgstr "" +msgstr ":mod:`usercustomize`" -#: ../../library/site.rst:145 +#: ../../library/site.rst:146 msgid "" "After this, an attempt is made to import a module named :mod:" "`usercustomize`, which can perform arbitrary user-specific customizations, " @@ -229,19 +292,31 @@ msgid "" "`~ImportError.name` attribute equals to ``'usercustomize'``, it is silently " "ignored." msgstr "" +"Depois disso, é feita uma tentativa de importar um módulo chamado :mod:" +"`usercustomize`, que pode executar personalizações arbitrárias específicas " +"do usuário, se :data:`~site.ENABLE_USER_SITE` for true. Este arquivo deve " +"ser criado no diretório site-packages de usuário (veja abaixo), que faz " +"parte de ``sys.path`` a menos que seja desabilitado por :option:`-s`. Se " +"esta importação falhar com um :exc:`ImportError` ou sua exceção de " +"subclasse, e o atributo :attr:`~ImportError.name` da exceção for igual a " +"``'usercustomize'``, ele será ignorado silenciosamente." -#: ../../library/site.rst:153 +#: ../../library/site.rst:154 msgid "" "Note that for some non-Unix systems, ``sys.prefix`` and ``sys.exec_prefix`` " "are empty, and the path manipulations are skipped; however the import of :" "mod:`sitecustomize` and :mod:`usercustomize` is still attempted." msgstr "" +"Observe que, para alguns sistemas não Unix, ``sys.prefix`` e ``sys." +"exec_prefix`` estão vazios, e as manipulações de caminho são ignoradas; no " +"entanto, a importação de :mod:`sitecustomize` e :mod:`usercustomize` ainda é " +"tentada." -#: ../../library/site.rst:162 +#: ../../library/site.rst:163 msgid "Readline configuration" msgstr "Configuração Readline" -#: ../../library/site.rst:164 +#: ../../library/site.rst:165 msgid "" "On systems that support :mod:`readline`, this module will also import and " "configure the :mod:`rlcompleter` module, if Python is started in :ref:" @@ -252,20 +327,28 @@ msgid "" "`sitecustomize` or :mod:`usercustomize` module or your :envvar:" "`PYTHONSTARTUP` file." msgstr "" +"Em sistemas que oferecem suporte a :mod:`readline`, este módulo também " +"importará e configurará o módulo :mod:`rlcompleter`, se o Python for " +"iniciado em :ref:`modo interativo ` e sem a opção :option:`-" +"S`. O comportamento padrão é habilitar tab-completion e usar :file:`~/." +"python_history` como o arquivo de salvamento do histórico. Para desabilitá-" +"lo, exclua (ou substitua) o atributo :data:`sys.__interactivehook__` no seu " +"módulo :mod:`sitecustomize` ou :mod:`usercustomize` ou no seu arquivo :" +"envvar:`PYTHONSTARTUP`." -#: ../../library/site.rst:173 +#: ../../library/site.rst:174 msgid "Activation of rlcompleter and history was made automatic." -msgstr "" +msgstr "A ativação do rlcompleter e do histórico foi feita automaticamente." -#: ../../library/site.rst:178 +#: ../../library/site.rst:179 msgid "Module contents" msgstr "Conteúdo do módulo" -#: ../../library/site.rst:182 +#: ../../library/site.rst:183 msgid "A list of prefixes for site-packages directories." -msgstr "" +msgstr "Uma lista de prefixos para diretórios site-package." -#: ../../library/site.rst:187 +#: ../../library/site.rst:188 msgid "" "Flag showing the status of the user site-packages directory. ``True`` means " "that it is enabled and was added to ``sys.path``. ``False`` means that it " @@ -273,8 +356,14 @@ msgid "" "`PYTHONNOUSERSITE`). ``None`` means it was disabled for security reasons " "(mismatch between user or group id and effective id) or by an administrator." msgstr "" +"Sinalizador mostrando o status do diretório site-packages do usuário. " +"``True`` significa que ele está habilitado e foi adicionado a ``sys.path``. " +"``False`` significa que ele foi desabilitado por solicitação do usuário " +"(com :option:`-s` ou :envvar:`PYTHONNOUSERSITE`). ``None`` significa que ele " +"foi desabilitado por motivos de segurança (incompatibilidade entre o ID do " +"usuário ou grupo e o ID efetivo) ou por um administrador." -#: ../../library/site.rst:197 +#: ../../library/site.rst:198 msgid "" "Path to the user site-packages for the running Python. Can be ``None`` if :" "func:`getusersitepackages` hasn't been called yet. Default value is :file:" @@ -285,8 +374,16 @@ msgid "" "build. This directory is a site directory, which means that :file:`.pth` " "files in it will be processed." msgstr "" +"Caminho para o usuário site-packages para o Python em execução. Pode ser " +"``None`` se :func:`getusersitepackages` ainda não tiver sido chamado. O " +"valor padrão é :file:`~/.local/lib/python{X.Y}[t]/site-packages` para " +"construções UNIX e macOS não-framework, :file:`~/Library/Python/{X.Y}/lib/" +"python/site-packages` para construções macOS framework e :file:`{%APPDATA%}\\" +"\\Python\\\\Python{XY}\\\\site-packages` no Windows. O \"t\" opcional indica " +"a construção de threads livres. Este diretório é um diretório de site, o que " +"significa que os arquivos :file:`.pth` nele serão processados." -#: ../../library/site.rst:209 +#: ../../library/site.rst:210 msgid "" "Path to the base directory for the user site-packages. Can be ``None`` if :" "func:`getuserbase` hasn't been called yet. Default value is :file:`~/." @@ -296,90 +393,134 @@ msgid "" "scripts, data files, Python modules, etc. for the :ref:`user installation " "scheme `. See also :envvar:`PYTHONUSERBASE`." msgstr "" +"Caminho para o diretório base para os pacotes do site do usuário. Pode ser " +"``None`` se :func:`getuserbase` ainda não tiver sido chamado. O valor padrão " +"é :file:`~/.local` para construções não-framework UNIX e macOS, :file:`~/" +"Library/Python/{X.Y}` para construções de framework macOS e :file:" +"`{%APPDATA%}\\\\Python` para Windows. Este valor é usado para calcular os " +"diretórios de instalação para scripts, arquivos de dados, módulos Python, " +"etc. para o :ref:`esquema de instalação de usuário `. " +"Veja também :envvar:`PYTHONUSERBASE`." -#: ../../library/site.rst:221 +#: ../../library/site.rst:222 msgid "" "Adds all the standard site-specific directories to the module search path. " "This function is called automatically when this module is imported, unless " "the Python interpreter was started with the :option:`-S` flag." msgstr "" +"Adiciona todos os diretórios padrão específicos do site ao caminho de " +"pesquisa de módulos. Esta função é chamada automaticamente quando este " +"módulo é importado, a menos que o interpretador Python tenha sido iniciado " +"com o sinalizador :option:`-S`." -#: ../../library/site.rst:225 +#: ../../library/site.rst:226 msgid "This function used to be called unconditionally." -msgstr "" +msgstr "Esta função costumava ser chamada incondicionalmente." -#: ../../library/site.rst:231 +#: ../../library/site.rst:232 msgid "" "Add a directory to sys.path and process its :file:`.pth` files. Typically " "used in :mod:`sitecustomize` or :mod:`usercustomize` (see above)." msgstr "" +"Adiciona um diretório a sys.path e processa seus arquivos :file:`.pth`. " +"Normalmente usado em :mod:`sitecustomize` ou :mod:`usercustomize` (veja " +"acima)." -#: ../../library/site.rst:237 +#: ../../library/site.rst:238 msgid "Return a list containing all global site-packages directories." msgstr "" +"Retorna uma lista contendo todos os diretórios globais de pacotes de sites." -#: ../../library/site.rst:244 +#: ../../library/site.rst:245 msgid "" "Return the path of the user base directory, :data:`USER_BASE`. If it is not " "initialized yet, this function will also set it, respecting :envvar:" "`PYTHONUSERBASE`." msgstr "" +"Retorna o caminho do diretório base do usuário, :data:`USER_BASE`. Se ele " +"ainda não foi inicializado, esta função também o definirá, respeitando :" +"envvar:`PYTHONUSERBASE`." -#: ../../library/site.rst:253 +#: ../../library/site.rst:254 msgid "" "Return the path of the user-specific site-packages directory, :data:" "`USER_SITE`. If it is not initialized yet, this function will also set it, " "respecting :data:`USER_BASE`. To determine if the user-specific site-" "packages was added to ``sys.path`` :data:`ENABLE_USER_SITE` should be used." msgstr "" +"Retorna o caminho do diretório site-packages específico do usuário, :data:" +"`USER_SITE`. Se ele ainda não foi inicializado, esta função também o " +"definirá, respeitando :data:`USER_BASE`. Para determinar se o site-packages " +"específico do usuário foi adicionado a ``sys.path``, :data:" +"`ENABLE_USER_SITE` deve ser usado." -#: ../../library/site.rst:265 +#: ../../library/site.rst:266 msgid "Command Line Interface" msgstr "Interface de linha de comando" -#: ../../library/site.rst:269 +#: ../../library/site.rst:270 msgid "" "The :mod:`site` module also provides a way to get the user directories from " "the command line:" msgstr "" +"O módulo :mod:`site` também fornece uma maneira de obter os diretórios do " +"usuário a partir da linha de comando:" + +#: ../../library/site.rst:273 +msgid "" +"$ python -m site --user-site\n" +"/home/user/.local/lib/python3.11/site-packages" +msgstr "" +"$ python -m site --user-site\n" +"/home/user/.local/lib/python3.11/site-packages" -#: ../../library/site.rst:277 +#: ../../library/site.rst:278 msgid "" "If it is called without arguments, it will print the contents of :data:`sys." "path` on the standard output, followed by the value of :data:`USER_BASE` and " "whether the directory exists, then the same thing for :data:`USER_SITE`, and " "finally the value of :data:`ENABLE_USER_SITE`." msgstr "" +"Se for chamado sem argumentos, ele vai exibir o conteúdo de :data:`sys.path` " +"na saída padrão, seguido pelo valor de :data:`USER_BASE` e se o diretório " +"existe, depois o mesmo para :data:`USER_SITE` e, finalmente, o valor de :" +"data:`ENABLE_USER_SITE`." -#: ../../library/site.rst:284 +#: ../../library/site.rst:285 msgid "Print the path to the user base directory." -msgstr "" +msgstr "Exibe o caminho para o diretório base do usuário." -#: ../../library/site.rst:288 +#: ../../library/site.rst:289 msgid "Print the path to the user site-packages directory." -msgstr "" +msgstr "Exibe o caminho para o diretório site-packages do usuário." -#: ../../library/site.rst:290 +#: ../../library/site.rst:291 msgid "" "If both options are given, user base and user site will be printed (always " "in this order), separated by :data:`os.pathsep`." msgstr "" +"Se ambas as opções forem fornecidas, a base do usuário e o site do usuário " +"serão exibidos (sempre nesta ordem), separados por :data:`os.pathsep`." -#: ../../library/site.rst:293 +#: ../../library/site.rst:294 msgid "" "If any option is given, the script will exit with one of these values: ``0`` " "if the user site-packages directory is enabled, ``1`` if it was disabled by " "the user, ``2`` if it is disabled for security reasons or by an " "administrator, and a value greater than 2 if there is an error." msgstr "" +"Se qualquer opção for fornecida, o script sairá com um destes valores: ``0`` " +"se o diretório site-packages do usuário estiver habilitado, ``1`` se ele foi " +"desabilitado pelo usuário, ``2`` se ele foi desabilitado por motivos de " +"segurança ou por um administrador, e um valor maior que 2 se houver um erro." -#: ../../library/site.rst:300 +#: ../../library/site.rst:301 msgid ":pep:`370` -- Per user site-packages directory" msgstr ":pep:`370` -- Diretório site-packages por usuário." -#: ../../library/site.rst:301 +#: ../../library/site.rst:302 msgid ":ref:`sys-path-init` -- The initialization of :data:`sys.path`." -msgstr "" +msgstr ":ref:`sys-path-init` -- A inicialização de :data:`sys.path`." #: ../../library/site.rst:16 msgid "module" @@ -389,42 +530,42 @@ msgstr "módulo" msgid "search" msgstr "pesquisa" -#: ../../library/site.rst:16 ../../library/site.rst:89 +#: ../../library/site.rst:16 ../../library/site.rst:90 msgid "path" msgstr "caminho" -#: ../../library/site.rst:28 +#: ../../library/site.rst:29 msgid "site-packages" -msgstr "" +msgstr "site-packages" -#: ../../library/site.rst:28 +#: ../../library/site.rst:29 msgid "directory" msgstr "diretório" -#: ../../library/site.rst:60 +#: ../../library/site.rst:61 msgid "# (hash)" msgstr "# (cerquilha)" -#: ../../library/site.rst:60 +#: ../../library/site.rst:61 msgid "comment" msgstr "comentário" -#: ../../library/site.rst:60 +#: ../../library/site.rst:61 msgid "statement" msgstr "instrução" -#: ../../library/site.rst:60 +#: ../../library/site.rst:61 msgid "import" -msgstr "importação" +msgstr "import" -#: ../../library/site.rst:89 +#: ../../library/site.rst:90 msgid "package" msgstr "pacote" -#: ../../library/site.rst:89 +#: ../../library/site.rst:90 msgid "configuration" msgstr "configuração" -#: ../../library/site.rst:89 +#: ../../library/site.rst:90 msgid "file" msgstr "arquivo" diff --git a/library/smtpd.po b/library/smtpd.po new file mode 100644 index 000000000..8903d53f6 --- /dev/null +++ b/library/smtpd.po @@ -0,0 +1,54 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../library/smtpd.rst:2 +msgid ":mod:`!smtpd` --- SMTP Server" +msgstr ":mod:`!smtpd` --- Serviços SMTP" + +#: ../../library/smtpd.rst:10 +msgid "" +"This module is no longer part of the Python standard library. It was :ref:" +"`removed in Python 3.12 ` after being deprecated in " +"Python 3.6. The removal was decided in :pep:`594`." +msgstr "" +"Este módulo não faz mais parte da biblioteca padrão do Python. Ele foi :ref:" +"`removido no Python 3.12 ` após ser descontinuado no " +"Python 3.6. A remoção foi decidida na :pep:`594`." + +#: ../../library/smtpd.rst:14 +msgid "" +"A possible replacement is the third-party :pypi:`aiosmtpd` library. This " +"library is not maintained or supported by the Python core team." +msgstr "" +"Uma possível substituição é a biblioteca de terceiros :pypi:`aiosmtpd`. Esta " +"biblioteca não é mantida ou susportada pela equipe principal do Python." + +#: ../../library/smtpd.rst:17 +msgid "" +"The last version of Python that provided the :mod:`!smtpd` module was " +"`Python 3.11 `_." +msgstr "" +"A última versão do Python que forneceu o módulo :mod:`!smtpd` foi o `Python " +"3.11 `_." diff --git a/library/smtplib.po b/library/smtplib.po index 503e2d1bb..1a250fc90 100644 --- a/library/smtplib.po +++ b/library/smtplib.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:13+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-14 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -43,8 +40,8 @@ msgid "" msgstr "" #: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +msgid "Availability" +msgstr "Disponibilidade" #: ../../includes/wasm-notavail.rst:5 msgid "" @@ -87,6 +84,16 @@ msgid "" "keyword:`!with` statement exits. E.g.::" msgstr "" +#: ../../library/smtplib.rst:52 +msgid "" +">>> from smtplib import SMTP\n" +">>> with SMTP(\"domain.org\") as smtp:\n" +"... smtp.noop()\n" +"...\n" +"(250, b'Ok')\n" +">>>" +msgstr "" + #: ../../library/smtplib.rst:59 ../../library/smtplib.rst:61 msgid "" "All commands will raise an :ref:`auditing event ` ``smtplib.SMTP." @@ -104,7 +111,7 @@ msgstr "" #: ../../library/smtplib.rst:71 msgid "The SMTPUTF8 extension (:rfc:`6531`) is now supported." -msgstr "" +msgstr "A extensão SMTPUTF8 ( :rfc:`6531` ) é suportada agora." #: ../../library/smtplib.rst:74 msgid "" @@ -132,7 +139,7 @@ msgstr "*context* foi adicionado." #: ../../library/smtplib.rst:95 msgid "The *source_address* argument was added." -msgstr "" +msgstr "O argumento *source_address* foi adicionado." #: ../../library/smtplib.rst:98 msgid "" @@ -148,7 +155,7 @@ msgstr "" #: ../../library/smtplib.rst:107 ../../library/smtplib.rst:403 msgid "The deprecated *keyfile* and *certfile* parameters have been removed." -msgstr "" +msgstr "Os parâmetros depreciados *keyfile* e *certfile* foram removidos." #: ../../library/smtplib.rst:113 msgid "" @@ -169,7 +176,7 @@ msgstr "" #: ../../library/smtplib.rst:124 msgid "The optional *timeout* parameter was added." -msgstr "" +msgstr "O parâmetro opcional *timeout* foi adicionado." #: ../../library/smtplib.rst:128 msgid "A nice selection of exceptions is defined as well:" @@ -216,15 +223,15 @@ msgstr "" #: ../../library/smtplib.rst:171 msgid "The SMTP server refused to accept the message data." -msgstr "" +msgstr "O servidor SMTP recusou aceitar o dados da mensagem." #: ../../library/smtplib.rst:176 msgid "Error occurred during establishment of a connection with the server." -msgstr "" +msgstr "Ocorreu um erro ao estabelecer uma conexão com o servidor." #: ../../library/smtplib.rst:181 msgid "The server refused our ``HELO`` message." -msgstr "" +msgstr "O servidor recusou sua mensagem ``HELO``." #: ../../library/smtplib.rst:186 msgid "The command or option attempted is not supported by the server." @@ -388,7 +395,7 @@ msgstr "" #: ../../library/smtplib.rst:307 msgid "Many sites disable SMTP ``VRFY`` in order to foil spammers." -msgstr "" +msgstr "Muitos servidores desabilitam o SMTP ``VRFY`` para despistar spammers." #: ../../library/smtplib.rst:312 msgid "" @@ -405,7 +412,7 @@ msgstr ":exc:`SMTPAuthenticationError`" #: ../../library/smtplib.rst:322 msgid "The server didn't accept the username/password combination." -msgstr "" +msgstr "O servidor não aceitou a combinação de usuário/senha." #: ../../library/smtplib.rst:324 ../../library/smtplib.rst:409 #: ../../library/smtplib.rst:485 @@ -464,6 +471,10 @@ msgid "" "*authobject* must be a callable object taking an optional single argument::" msgstr "" +#: ../../library/smtplib.rst:356 +msgid "data = authobject(challenge=None)" +msgstr "" + #: ../../library/smtplib.rst:358 msgid "" "If optional keyword argument *initial_response_ok* is true, ``authobject()`` " @@ -530,7 +541,7 @@ msgstr "" #: ../../library/smtplib.rst:410 msgid "The server does not support the STARTTLS extension." -msgstr "" +msgstr "O servidor não da suporte a extensão STARTTLS." #: ../../library/smtplib.rst:412 msgid ":exc:`RuntimeError`" @@ -607,7 +618,7 @@ msgstr "" #: ../../library/smtplib.rst:467 msgid "This method may raise the following exceptions:" -msgstr "" +msgstr "Esse método deve levantar as seguintes exceções:" #: ../../library/smtplib.rst:469 msgid ":exc:`SMTPRecipientsRefused`" @@ -627,7 +638,7 @@ msgstr ":exc:`SMTPSenderRefused`" #: ../../library/smtplib.rst:479 msgid "The server didn't accept the *from_addr*." -msgstr "" +msgstr "O servidor não aceita o *from_addr*." #: ../../library/smtplib.rst:481 msgid ":exc:`SMTPDataError`" @@ -692,11 +703,11 @@ msgid "" "and *to_addrs*, ``send_message`` does not transmit any :mailheader:`Bcc` or :" "mailheader:`Resent-Bcc` headers that may appear in *msg*. If any of the " "addresses in *from_addr* and *to_addrs* contain non-ASCII characters and the " -"server does not advertise ``SMTPUTF8`` support, an :exc:`SMTPNotSupported` " -"error is raised. Otherwise the ``Message`` is serialized with a clone of " -"its :mod:`~email.policy` with the :attr:`~email.policy.EmailPolicy.utf8` " -"attribute set to ``True``, and ``SMTPUTF8`` and ``BODY=8BITMIME`` are added " -"to *mail_options*." +"server does not advertise ``SMTPUTF8`` support, an :exc:" +"`SMTPNotSupportedError` is raised. Otherwise the ``Message`` is serialized " +"with a clone of its :mod:`~email.policy` with the :attr:`~email.policy." +"EmailPolicy.utf8` attribute set to ``True``, and ``SMTPUTF8`` and " +"``BODY=8BITMIME`` are added to *mail_options*." msgstr "" #: ../../library/smtplib.rst:534 @@ -731,6 +742,36 @@ msgid "" "headers explicitly::" msgstr "" +#: ../../library/smtplib.rst:561 +msgid "" +"import smtplib\n" +"\n" +"def prompt(title):\n" +" return input(title).strip()\n" +"\n" +"from_addr = prompt(\"From: \")\n" +"to_addrs = prompt(\"To: \").split()\n" +"print(\"Enter message, end with ^D (Unix) or ^Z (Windows):\")\n" +"\n" +"# Add the From: and To: headers at the start!\n" +"lines = [f\"From: {from_addr}\", f\"To: {', '.join(to_addrs)}\", \"\"]\n" +"while True:\n" +" try:\n" +" line = input()\n" +" except EOFError:\n" +" break\n" +" else:\n" +" lines.append(line)\n" +"\n" +"msg = \"\\r\\n\".join(lines)\n" +"print(\"Message length is\", len(msg))\n" +"\n" +"server = smtplib.SMTP(\"localhost\")\n" +"server.set_debuglevel(1)\n" +"server.sendmail(from_addr, to_addrs, msg)\n" +"server.quit()" +msgstr "" + #: ../../library/smtplib.rst:590 msgid "" "In general, you will want to use the :mod:`email` package's features to " diff --git a/library/sndhdr.po b/library/sndhdr.po new file mode 100644 index 000000000..d4fad9cb9 --- /dev/null +++ b/library/sndhdr.po @@ -0,0 +1,56 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../library/sndhdr.rst:2 +msgid ":mod:`!sndhdr` --- Determine type of sound file" +msgstr ":mod:`!sndhdr` --- Determina o tipo de arquivos de som" + +#: ../../library/sndhdr.rst:10 +msgid "" +"This module is no longer part of the Python standard library. It was :ref:" +"`removed in Python 3.13 ` after being deprecated in " +"Python 3.11. The removal was decided in :pep:`594`." +msgstr "" +"Este módulo não faz mais parte da biblioteca padrão do Python. Ele foi :ref:" +"`removido no Python 3.13 ` após ser descontinuado no " +"Python 3.11. A remoção foi decidida na :pep:`594`." + +#: ../../library/sndhdr.rst:14 +msgid "" +"Possible replacements are third-party modules from PyPI: :pypi:`filetype`, :" +"pypi:`puremagic`, or :pypi:`python-magic`. These are not supported or " +"maintained by the Python core team." +msgstr "" +"Possíveis substituições são módulos de terceiros do PyPI: :pypi:`filetype`, :" +"pypi:`puremagic` ou :pypi:`python-magic`. Eles não são suportadoss ou " +"mantidos pela equipe principal do Python." + +#: ../../library/sndhdr.rst:18 +msgid "" +"The last version of Python that provided the :mod:`!sndhdr` module was " +"`Python 3.12 `_." +msgstr "" +"A última versão do Python que forneceu o módulo :mod:`!sndhdr` foi o `Python " +"3.12 `_." diff --git a/library/socket.po b/library/socket.po index 6e24a9aab..d2004daad 100644 --- a/library/socket.po +++ b/library/socket.po @@ -1,43 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Leticia Portella , 2021 -# Italo Penaforte , 2021 -# And Past , 2021 -# felipe caridade fernandes , 2021 -# Marcos Wenneton Araújo , 2021 -# Marcone G , 2021 -# Augusta Carla Klug , 2021 -# i17obot , 2021 -# yyyyyyyan , 2021 -# Marco Rougeth , 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# mvpetri , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:13+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-04-25 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/socket.rst:2 msgid ":mod:`!socket` --- Low-level networking interface" -msgstr "" +msgstr ":mod:`!socket` --- Interface de rede de baixo nível" #: ../../library/socket.rst:7 msgid "**Source code:** :source:`Lib/socket.py`" @@ -61,17 +49,37 @@ msgstr "" "Algum comportamento pode depender da plataforma, pois as chamadas são feitas " "para as APIs de soquete do sistema operacional." -#: ../../library/socket.rst:987 ../../library/socket.rst:1003 -#: ../../library/socket.rst:1016 ../../library/socket.rst:1031 -#: ../../library/socket.rst:1048 ../../library/socket.rst:1059 -#: ../../library/socket.rst:1070 ../../library/socket.rst:1081 -#: ../../library/socket.rst:1405 ../../library/socket.rst:1452 -#: ../../library/socket.rst:1466 ../../library/socket.rst:1486 -#: ../../library/socket.rst:1533 ../../library/socket.rst:1578 -#: ../../library/socket.rst:1962 ../../library/socket.rst:1972 -#: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +#: ../../library/socket.rst:176 ../../library/socket.rst:186 +#: ../../library/socket.rst:214 ../../library/socket.rst:221 +#: ../../library/socket.rst:238 ../../library/socket.rst:388 +#: ../../library/socket.rst:466 ../../library/socket.rst:483 +#: ../../library/socket.rst:498 ../../library/socket.rst:509 +#: ../../library/socket.rst:518 ../../library/socket.rst:527 +#: ../../library/socket.rst:538 ../../library/socket.rst:550 +#: ../../library/socket.rst:561 ../../library/socket.rst:574 +#: ../../library/socket.rst:602 ../../library/socket.rst:614 +#: ../../library/socket.rst:620 ../../library/socket.rst:650 +#: ../../library/socket.rst:665 ../../library/socket.rst:674 +#: ../../library/socket.rst:691 ../../library/socket.rst:706 +#: ../../library/socket.rst:716 ../../library/socket.rst:905 +#: ../../library/socket.rst:1030 ../../library/socket.rst:1046 +#: ../../library/socket.rst:1059 ../../library/socket.rst:1074 +#: ../../library/socket.rst:1091 ../../library/socket.rst:1102 +#: ../../library/socket.rst:1113 ../../library/socket.rst:1124 +#: ../../library/socket.rst:1213 ../../library/socket.rst:1233 +#: ../../library/socket.rst:1259 ../../library/socket.rst:1282 +#: ../../library/socket.rst:1311 ../../library/socket.rst:1322 +#: ../../library/socket.rst:1349 ../../library/socket.rst:1366 +#: ../../library/socket.rst:1383 ../../library/socket.rst:1397 +#: ../../library/socket.rst:1448 ../../library/socket.rst:1495 +#: ../../library/socket.rst:1509 ../../library/socket.rst:1529 +#: ../../library/socket.rst:1576 ../../library/socket.rst:1621 +#: ../../library/socket.rst:1746 ../../library/socket.rst:1790 +#: ../../library/socket.rst:1898 ../../library/socket.rst:1916 +#: ../../library/socket.rst:2000 ../../library/socket.rst:2010 +#: ../../library/socket.rst:2022 ../../includes/wasm-notavail.rst:3 +msgid "Availability" +msgstr "Disponibilidade" #: ../../includes/wasm-notavail.rst:5 msgid "" @@ -91,6 +99,14 @@ msgid "" "meth:`write` operations on Python files, buffer allocation on receive " "operations is automatic, and buffer length is implicit on send operations." msgstr "" +"A interface Python é uma transliteração direta da chamada de sistema e " +"interface de biblioteca de soquetes do Unix para o estilo orientado a " +"objetos do Python: a função :func:`~socket.socket` retorna um :dfn:`objeto " +"socket` cujos métodos implementam as diversas chamadas de sistema de " +"soquetes. Os tipos de parâmetro são consideravelmente de nível mais alto que " +"os da interface em C: assim como as operações :meth:`read` e :meth:`write` " +"em arquivos Python, a alocação de buffer em operações de recebimento é " +"automática, e o comprimento do buffer é implícito em operações de envio." #: ../../library/socket.rst:35 msgid "Module :mod:`socketserver`" @@ -98,15 +114,15 @@ msgstr "Módulo :mod:`socketserver`" #: ../../library/socket.rst:36 msgid "Classes that simplify writing network servers." -msgstr "" +msgstr "Classes que simplificam a escrita de servidores de rede." #: ../../library/socket.rst:38 msgid "Module :mod:`ssl`" -msgstr "" +msgstr "Módulo :mod:`ssl`" #: ../../library/socket.rst:39 msgid "A TLS/SSL wrapper for socket objects." -msgstr "" +msgstr "Um invólucro de TLS/SSL para objetos socket." #: ../../library/socket.rst:43 msgid "Socket families" @@ -126,6 +142,10 @@ msgid "" "selected based on the address family specified when the socket object was " "created. Socket addresses are represented as follows:" msgstr "" +"O formato de endereço requerido por um objeto socket em particular é " +"selecionado automaticamente com base na família de endereços especificada " +"quando o objeto socket foi criado. Endereços de socket são representados da " +"seguinte forma:" #: ../../library/socket.rst:52 msgid "" @@ -138,14 +158,23 @@ msgid "" "deal with both types of address. A string or bytes-like object can be used " "for either type of address when passing it as an argument." msgstr "" +"O endereço de um socket :const:`AF_UNIX` vinculado a um nó do sistema de " +"arquivos é representado como uma string, usando a codificação do sistema de " +"arquivos e o tratador de erros ``'surrogateescape'`` (veja :pep:`383`). Um " +"endereço no espaço de nomes abstrato do Linux é retornado como um :term:" +"`objeto bytes ou similar` com um byte nulo inicial; observe que os sockets " +"neste espaço de nomes podem se comunicar com sockets normais do sistema de " +"arquivos, então programas destinados a rodar no Linux podem precisar lidar " +"com ambos os tipos de endereço. Uma string ou um objeto bytes ou similar " +"pode ser usado para qualquer tipo de endereço ao passá-lo como um argumento." #: ../../library/socket.rst:62 msgid "" "Previously, :const:`AF_UNIX` socket paths were assumed to use UTF-8 encoding." msgstr "" -#: ../../library/socket.rst:66 ../../library/socket.rst:1153 -#: ../../library/socket.rst:1195 ../../library/socket.rst:1956 +#: ../../library/socket.rst:66 ../../library/socket.rst:1196 +#: ../../library/socket.rst:1238 ../../library/socket.rst:1994 msgid "Writable :term:`bytes-like object` is now accepted." msgstr "" @@ -278,133 +307,132 @@ msgid "" msgstr "" #: ../../library/socket.rst:146 +msgid ":const:`BTPROTO_HCI` accepts a format that depends on your OS." +msgstr "" + +#: ../../library/socket.rst:148 +msgid "" +"On Linux it accepts a tuple ``(device_id,)`` where ``device_id`` is an " +"integer specifying the number of the Bluetooth device." +msgstr "" + +#: ../../library/socket.rst:150 msgid "" -":const:`BTPROTO_HCI` accepts ``(device_id,)`` where ``device_id`` is either " -"an integer or a string with the Bluetooth address of the interface. (This " -"depends on your OS; NetBSD and DragonFlyBSD expect a Bluetooth address while " -"everything else expects an integer.)" +"On FreeBSD, NetBSD and DragonFly BSD it accepts ``bdaddr`` where ``bdaddr`` " +"is the Bluetooth address as a string." msgstr "" -#: ../../library/socket.rst:151 +#: ../../library/socket.rst:153 msgid "NetBSD and DragonFlyBSD support added." msgstr "" -#: ../../library/socket.rst:154 -msgid "" -":const:`BTPROTO_SCO` accepts ``bdaddr`` where ``bdaddr`` is a :class:`bytes` " -"object containing the Bluetooth address in a string format. (ex. " -"``b'12:23:34:45:56:67'``) This protocol is not supported under FreeBSD." +#: ../../library/socket.rst:156 +msgid "FreeBSD support added." msgstr "" #: ../../library/socket.rst:159 msgid "" +":const:`BTPROTO_SCO` accepts ``bdaddr`` where ``bdaddr`` is the Bluetooth " +"address as a string or a :class:`bytes` object. (ex. ``'12:23:34:45:56:67'`` " +"or ``b'12:23:34:45:56:67'``) This protocol is not supported under FreeBSD." +msgstr "" + +#: ../../library/socket.rst:164 +msgid "" ":const:`AF_ALG` is a Linux-only socket based interface to Kernel " "cryptography. An algorithm socket is configured with a tuple of two to four " "elements ``(type, name [, feat [, mask]])``, where:" msgstr "" -#: ../../library/socket.rst:163 +#: ../../library/socket.rst:168 msgid "" "*type* is the algorithm type as string, e.g. ``aead``, ``hash``, " "``skcipher`` or ``rng``." msgstr "" -#: ../../library/socket.rst:166 +#: ../../library/socket.rst:171 msgid "" "*name* is the algorithm name and operation mode as string, e.g. ``sha256``, " "``hmac(sha256)``, ``cbc(aes)`` or ``drbg_nopr_ctr_aes256``." msgstr "" -#: ../../library/socket.rst:169 +#: ../../library/socket.rst:174 msgid "*feat* and *mask* are unsigned 32bit integers." msgstr "" -#: ../../library/socket.rst:171 ../../library/socket.rst:594 -#: ../../library/socket.rst:1878 -msgid ":ref:`Availability `: Linux >= 2.6.38." -msgstr ":ref:`Disponibilidade `: Linux >= 2.6.38." - -#: ../../library/socket.rst:173 +#: ../../library/socket.rst:178 msgid "Some algorithm types require more recent Kernels." msgstr "" -#: ../../library/socket.rst:177 +#: ../../library/socket.rst:182 msgid "" ":const:`AF_VSOCK` allows communication between virtual machines and their " "hosts. The sockets are represented as a ``(CID, port)`` tuple where the " "context ID or CID and port are integers." msgstr "" -#: ../../library/socket.rst:181 ../../library/socket.rst:667 -msgid ":ref:`Availability `: Linux >= 3.9" -msgstr ":ref:`Disponibilidade `: Linux >= 3.9" - -#: ../../library/socket.rst:183 +#: ../../library/socket.rst:188 msgid "See :manpage:`vsock(7)`" msgstr "" -#: ../../library/socket.rst:187 +#: ../../library/socket.rst:192 msgid "" ":const:`AF_PACKET` is a low-level interface directly to network devices. The " "addresses are represented by the tuple ``(ifname, proto[, pkttype[, hatype[, " "addr]]])`` where:" msgstr "" -#: ../../library/socket.rst:191 +#: ../../library/socket.rst:196 msgid "*ifname* - String specifying the device name." msgstr "" -#: ../../library/socket.rst:192 +#: ../../library/socket.rst:197 msgid "" "*proto* - The Ethernet protocol number. May be :data:`ETH_P_ALL` to capture " "all protocols, one of the :ref:`ETHERTYPE_* constants ` or any other Ethernet protocol number." msgstr "" -#: ../../library/socket.rst:196 +#: ../../library/socket.rst:201 msgid "*pkttype* - Optional integer specifying the packet type:" msgstr "" -#: ../../library/socket.rst:198 +#: ../../library/socket.rst:203 msgid "``PACKET_HOST`` (the default) - Packet addressed to the local host." msgstr "" -#: ../../library/socket.rst:199 +#: ../../library/socket.rst:204 msgid "``PACKET_BROADCAST`` - Physical-layer broadcast packet." msgstr "" -#: ../../library/socket.rst:200 +#: ../../library/socket.rst:205 msgid "" "``PACKET_MULTICAST`` - Packet sent to a physical-layer multicast address." msgstr "" -#: ../../library/socket.rst:201 +#: ../../library/socket.rst:206 msgid "" "``PACKET_OTHERHOST`` - Packet to some other host that has been caught by a " "device driver in promiscuous mode." msgstr "" -#: ../../library/socket.rst:203 +#: ../../library/socket.rst:208 msgid "" "``PACKET_OUTGOING`` - Packet originating from the local host that is looped " "back to a packet socket." msgstr "" -#: ../../library/socket.rst:205 +#: ../../library/socket.rst:210 msgid "*hatype* - Optional integer specifying the ARP hardware address type." msgstr "" -#: ../../library/socket.rst:206 +#: ../../library/socket.rst:211 msgid "" "*addr* - Optional bytes-like object specifying the hardware physical " "address, whose interpretation depends on the device." msgstr "" -#: ../../library/socket.rst:209 ../../library/socket.rst:542 -msgid ":ref:`Availability `: Linux >= 2.2." -msgstr ":ref:`Disponibilidade `: Linux >= 2.2." - -#: ../../library/socket.rst:211 +#: ../../library/socket.rst:216 msgid "" ":const:`AF_QIPCRTR` is a Linux-only socket based interface for communicating " "with services running on co-processors in Qualcomm platforms. The address " @@ -412,11 +440,7 @@ msgid "" "*port* are non-negative integers." msgstr "" -#: ../../library/socket.rst:216 ../../library/socket.rst:643 -msgid ":ref:`Availability `: Linux >= 4.7." -msgstr ":ref:`Disponibilidade `: Linux >= 4.7." - -#: ../../library/socket.rst:220 +#: ../../library/socket.rst:225 msgid "" ":const:`IPPROTO_UDPLITE` is a variant of UDP which allows you to specify " "what portion of a packet is covered with the checksum. It adds two socket " @@ -427,19 +451,14 @@ msgid "" "of their data. In both cases ``length`` should be in ``range(8, 2**16, 8)``." msgstr "" -#: ../../library/socket.rst:229 +#: ../../library/socket.rst:234 msgid "" "Such a socket should be constructed with ``socket(AF_INET, SOCK_DGRAM, " "IPPROTO_UDPLITE)`` for IPv4 or ``socket(AF_INET6, SOCK_DGRAM, " "IPPROTO_UDPLITE)`` for IPv6." msgstr "" -#: ../../library/socket.rst:233 -msgid ":ref:`Availability `: Linux >= 2.6.20, FreeBSD >= 10.1" -msgstr "" -":ref:`Disponibilidade `: Linux >= 2.6.20, FreeBSD >= 10.1" - -#: ../../library/socket.rst:237 +#: ../../library/socket.rst:242 msgid "" ":const:`AF_HYPERV` is a Windows-only socket based interface for " "communicating with Hyper-V hosts and guests. The address family is " @@ -447,49 +466,49 @@ msgid "" "``service_id`` are UUID strings." msgstr "" -#: ../../library/socket.rst:242 +#: ../../library/socket.rst:247 msgid "" "The ``vm_id`` is the virtual machine identifier or a set of known VMID " "values if the target is not a specific virtual machine. Known VMID constants " "defined on ``socket`` are:" msgstr "" -#: ../../library/socket.rst:246 +#: ../../library/socket.rst:251 msgid "``HV_GUID_ZERO``" msgstr "" -#: ../../library/socket.rst:247 +#: ../../library/socket.rst:252 msgid "``HV_GUID_BROADCAST``" msgstr "" -#: ../../library/socket.rst:248 +#: ../../library/socket.rst:253 msgid "" "``HV_GUID_WILDCARD`` - Used to bind on itself and accept connections from " "all partitions." msgstr "" -#: ../../library/socket.rst:250 +#: ../../library/socket.rst:255 msgid "" "``HV_GUID_CHILDREN`` - Used to bind on itself and accept connection from " "child partitions." msgstr "" -#: ../../library/socket.rst:252 +#: ../../library/socket.rst:257 msgid "``HV_GUID_LOOPBACK`` - Used as a target to itself." msgstr "" -#: ../../library/socket.rst:253 +#: ../../library/socket.rst:258 msgid "" "``HV_GUID_PARENT`` - When used as a bind accepts connection from the parent " "partition. When used as an address target it will connect to the parent " "partition." msgstr "" -#: ../../library/socket.rst:256 +#: ../../library/socket.rst:261 msgid "The ``service_id`` is the service identifier of the registered service." msgstr "" -#: ../../library/socket.rst:260 +#: ../../library/socket.rst:265 msgid "" "If you use a hostname in the *host* portion of IPv4/v6 socket address, the " "program may show a nondeterministic behavior, as Python uses the first " @@ -499,43 +518,43 @@ msgid "" "deterministic behavior use a numeric address in *host* portion." msgstr "" -#: ../../library/socket.rst:267 +#: ../../library/socket.rst:272 msgid "" "All errors raise exceptions. The normal exceptions for invalid argument " "types and out-of-memory conditions can be raised. Errors related to socket " "or address semantics raise :exc:`OSError` or one of its subclasses." msgstr "" -#: ../../library/socket.rst:272 +#: ../../library/socket.rst:277 msgid "" "Non-blocking mode is supported through :meth:`~socket.setblocking`. A " "generalization of this based on timeouts is supported through :meth:`~socket." "settimeout`." msgstr "" -#: ../../library/socket.rst:278 +#: ../../library/socket.rst:283 msgid "Module contents" msgstr "Conteúdo do módulo" -#: ../../library/socket.rst:280 +#: ../../library/socket.rst:285 msgid "The module :mod:`socket` exports the following elements." msgstr "" -#: ../../library/socket.rst:284 +#: ../../library/socket.rst:289 msgid "Exceptions" msgstr "Exceções" -#: ../../library/socket.rst:288 +#: ../../library/socket.rst:293 msgid "A deprecated alias of :exc:`OSError`." msgstr "Um apelido descontinuado de :exc:`OSError`." -#: ../../library/socket.rst:290 +#: ../../library/socket.rst:295 msgid "Following :pep:`3151`, this class was made an alias of :exc:`OSError`." msgstr "" "Seguindo a :pep:`3151`, esta classe foi transformada em um apelido de :exc:" "`OSError`." -#: ../../library/socket.rst:296 +#: ../../library/socket.rst:301 msgid "" "A subclass of :exc:`OSError`, this exception is raised for address-related " "errors, i.e. for functions that use *h_errno* in the POSIX C API, including :" @@ -545,12 +564,12 @@ msgid "" "description of *h_errno*, as returned by the :c:func:`hstrerror` C function." msgstr "" -#: ../../library/socket.rst:304 ../../library/socket.rst:317 -#: ../../library/socket.rst:330 +#: ../../library/socket.rst:309 ../../library/socket.rst:322 +#: ../../library/socket.rst:335 msgid "This class was made a subclass of :exc:`OSError`." msgstr "" -#: ../../library/socket.rst:309 +#: ../../library/socket.rst:314 msgid "" "A subclass of :exc:`OSError`, this exception is raised for address-related " "errors by :func:`getaddrinfo` and :func:`getnameinfo`. The accompanying " @@ -560,11 +579,11 @@ msgid "" "match one of the :const:`!EAI_\\*` constants defined in this module." msgstr "" -#: ../../library/socket.rst:322 +#: ../../library/socket.rst:327 msgid "A deprecated alias of :exc:`TimeoutError`." msgstr "" -#: ../../library/socket.rst:324 +#: ../../library/socket.rst:329 msgid "" "A subclass of :exc:`OSError`, this exception is raised when a timeout occurs " "on a socket which has had timeouts enabled via a prior call to :meth:" @@ -573,21 +592,21 @@ msgid "" "currently always \"timed out\"." msgstr "" -#: ../../library/socket.rst:333 +#: ../../library/socket.rst:338 msgid "This class was made an alias of :exc:`TimeoutError`." msgstr "Esta classe foi feita como um apelido de :exc:`TimeoutError`." -#: ../../library/socket.rst:338 +#: ../../library/socket.rst:343 msgid "Constants" msgstr "Constantes" -#: ../../library/socket.rst:340 +#: ../../library/socket.rst:345 msgid "" "The AF_* and SOCK_* constants are now :class:`AddressFamily` and :class:" "`SocketKind` :class:`.IntEnum` collections." msgstr "" -#: ../../library/socket.rst:349 +#: ../../library/socket.rst:354 msgid "" "These constants represent the address (and protocol) families, used for the " "first argument to :func:`~socket.socket`. If the :const:`AF_UNIX` constant " @@ -595,14 +614,14 @@ msgid "" "available depending on the system." msgstr "" -#: ../../library/socket.rst:356 +#: ../../library/socket.rst:361 msgid "" ":const:`AF_UNSPEC` means that :func:`getaddrinfo` should return socket " "addresses for any address family (either IPv4, IPv6, or any other) that can " "be used." msgstr "" -#: ../../library/socket.rst:366 +#: ../../library/socket.rst:371 msgid "" "These constants represent the socket types, used for the second argument to :" "func:`~socket.socket`. More constants may be available depending on the " @@ -610,24 +629,20 @@ msgid "" "generally useful.)" msgstr "" -#: ../../library/socket.rst:374 +#: ../../library/socket.rst:379 msgid "" "These two constants, if defined, can be combined with the socket types and " "allow you to set some flags atomically (thus avoiding possible race " "conditions and the need for separate calls)." msgstr "" -#: ../../library/socket.rst:380 +#: ../../library/socket.rst:385 msgid "" "`Secure File Descriptor Handling `_ for a more thorough explanation." msgstr "" -#: ../../library/socket.rst:383 -msgid ":ref:`Availability `: Linux >= 2.6.27." -msgstr ":ref:`Disponibilidade `: Linux >= 2.6.27." - -#: ../../library/socket.rst:404 +#: ../../library/socket.rst:409 msgid "" "Many constants of these forms, documented in the Unix documentation on " "sockets and/or the IP protocol, are also defined in the socket module. They " @@ -637,41 +652,41 @@ msgid "" "symbols, default values are provided." msgstr "" -#: ../../library/socket.rst:411 +#: ../../library/socket.rst:416 msgid "" "``SO_DOMAIN``, ``SO_PROTOCOL``, ``SO_PEERSEC``, ``SO_PASSSEC``, " "``TCP_USER_TIMEOUT``, ``TCP_CONGESTION`` were added." msgstr "" -#: ../../library/socket.rst:415 +#: ../../library/socket.rst:420 msgid "" "On Windows, ``TCP_FASTOPEN``, ``TCP_KEEPCNT`` appear if run-time Windows " "supports." msgstr "" -#: ../../library/socket.rst:419 +#: ../../library/socket.rst:424 msgid "``TCP_NOTSENT_LOWAT`` was added." msgstr "" -#: ../../library/socket.rst:422 +#: ../../library/socket.rst:427 msgid "" "On Windows, ``TCP_KEEPIDLE``, ``TCP_KEEPINTVL`` appear if run-time Windows " "supports." msgstr "" -#: ../../library/socket.rst:425 +#: ../../library/socket.rst:430 msgid "" "``IP_RECVTOS`` was added. Added ``TCP_KEEPALIVE``. On MacOS this constant " "can be used in the same way that ``TCP_KEEPIDLE`` is used on Linux." msgstr "" -#: ../../library/socket.rst:430 +#: ../../library/socket.rst:435 msgid "" "Added ``TCP_CONNECTION_INFO``. On MacOS this constant can be used in the " "same way that ``TCP_INFO`` is used on Linux and BSD." msgstr "" -#: ../../library/socket.rst:434 +#: ../../library/socket.rst:439 msgid "" "Added ``SO_RTABLE`` and ``SO_USER_COOKIE``. On OpenBSD and FreeBSD " "respectively those constants can be used in the same way that ``SO_MARK`` is " @@ -687,173 +702,137 @@ msgid "" "``IP_DROP_SOURCE_MEMBERSHIP``." msgstr "" -#: ../../library/socket.rst:448 +#: ../../library/socket.rst:453 msgid "" "Added ``SO_BINDTOIFINDEX``. On Linux this constant can be used in the same " "way that ``SO_BINDTODEVICE`` is used, but with the index of a network " "interface instead of its name." msgstr "" -#: ../../library/socket.rst:458 ../../library/socket.rst:539 -#: ../../library/socket.rst:563 +#: ../../library/socket.rst:463 ../../library/socket.rst:547 +#: ../../library/socket.rst:571 msgid "" "Many constants of these forms, documented in the Linux documentation, are " "also defined in the socket module." msgstr "" -#: ../../library/socket.rst:461 -msgid ":ref:`Availability `: Linux >= 2.6.25, NetBSD >= 8." -msgstr ":ref:`Disponibilidade `: Linux >= 2.6.25, NetBSD >= 8." - -#: ../../library/socket.rst:465 +#: ../../library/socket.rst:470 msgid "NetBSD support was added." msgstr "" -#: ../../library/socket.rst:471 +#: ../../library/socket.rst:473 +msgid "Restored missing ``CAN_RAW_ERR_FILTER`` on Linux." +msgstr "" + +#: ../../library/socket.rst:479 msgid "" "CAN_BCM, in the CAN protocol family, is the broadcast manager (BCM) " "protocol. Broadcast manager constants, documented in the Linux " "documentation, are also defined in the socket module." msgstr "" -#: ../../library/socket.rst:475 ../../library/socket.rst:510 -msgid ":ref:`Availability `: Linux >= 2.6.25." -msgstr ":ref:`Disponibilidade `: Linux >= 2.6.25." - -#: ../../library/socket.rst:478 +#: ../../library/socket.rst:486 msgid "" "The :data:`CAN_BCM_CAN_FD_FRAME` flag is only available on Linux >= 4.8." msgstr "" -#: ../../library/socket.rst:484 +#: ../../library/socket.rst:492 msgid "" "Enables CAN FD support in a CAN_RAW socket. This is disabled by default. " "This allows your application to send both CAN and CAN FD frames; however, " "you must accept both CAN and CAN FD frames when reading from the socket." msgstr "" -#: ../../library/socket.rst:488 ../../library/socket.rst:499 +#: ../../library/socket.rst:496 ../../library/socket.rst:507 msgid "This constant is documented in the Linux documentation." msgstr "" -#: ../../library/socket.rst:490 -msgid ":ref:`Availability `: Linux >= 3.6." -msgstr ":ref:`Disponibilidade `: Linux >= 3.6." - -#: ../../library/socket.rst:496 +#: ../../library/socket.rst:504 msgid "" "Joins the applied CAN filters such that only CAN frames that match all given " "CAN filters are passed to user space." msgstr "" -#: ../../library/socket.rst:501 -msgid ":ref:`Availability `: Linux >= 4.1." -msgstr ":ref:`Disponibilidade `: Linux >= 4.1." - -#: ../../library/socket.rst:507 +#: ../../library/socket.rst:515 msgid "" "CAN_ISOTP, in the CAN protocol family, is the ISO-TP (ISO 15765-2) protocol. " "ISO-TP constants, documented in the Linux documentation." msgstr "" -#: ../../library/socket.rst:516 +#: ../../library/socket.rst:524 msgid "" "CAN_J1939, in the CAN protocol family, is the SAE J1939 protocol. J1939 " "constants, documented in the Linux documentation." msgstr "" -#: ../../library/socket.rst:519 -msgid ":ref:`Availability `: Linux >= 5.4." -msgstr ":ref:`Disponibilidade `: Linux >= 5.4." - -#: ../../library/socket.rst:527 +#: ../../library/socket.rst:535 msgid "" "These two constants, documented in the FreeBSD divert(4) manual page, are " "also defined in the socket module." msgstr "" -#: ../../library/socket.rst:530 -msgid ":ref:`Availability `: FreeBSD >= 14.0." -msgstr "" - -#: ../../library/socket.rst:547 +#: ../../library/socket.rst:555 msgid "" ":data:`!ETH_P_ALL` can be used in the :class:`~socket.socket` constructor as " "*proto* for the :const:`AF_PACKET` family in order to capture every packet, " "regardless of protocol." msgstr "" -#: ../../library/socket.rst:551 +#: ../../library/socket.rst:559 msgid "For more information, see the :manpage:`packet(7)` manpage." msgstr "" -#: ../../library/socket.rst:553 -msgid ":ref:`Availability `: Linux." -msgstr ":ref:`Disponibilidade `: Linux." - -#: ../../library/socket.rst:566 -msgid ":ref:`Availability `: Linux >= 2.6.30." -msgstr ":ref:`Disponibilidade `: Linux >= 2.6.30." - -#: ../../library/socket.rst:576 +#: ../../library/socket.rst:584 msgid "" "Constants for Windows' WSAIoctl(). The constants are used as arguments to " "the :meth:`~socket.socket.ioctl` method of socket objects." msgstr "" -#: ../../library/socket.rst:579 ../../library/socket.rst:1568 +#: ../../library/socket.rst:587 ../../library/socket.rst:1611 msgid "``SIO_LOOPBACK_FAST_PATH`` was added." msgstr "" -#: ../../library/socket.rst:585 +#: ../../library/socket.rst:593 msgid "" "TIPC related constants, matching the ones exported by the C socket API. See " "the TIPC documentation for more information." msgstr "" -#: ../../library/socket.rst:592 +#: ../../library/socket.rst:600 msgid "Constants for Linux Kernel cryptography." msgstr "" -#: ../../library/socket.rst:604 +#: ../../library/socket.rst:612 msgid "Constants for Linux host/guest communication." msgstr "" -#: ../../library/socket.rst:606 -msgid ":ref:`Availability `: Linux >= 4.8." -msgstr ":ref:`Disponibilidade `: Linux >= 4.8." - -#: ../../library/socket.rst:612 -msgid ":ref:`Availability `: BSD, macOS." -msgstr ":ref:`Disponibilidade `: BSD, macOS." - -#: ../../library/socket.rst:618 +#: ../../library/socket.rst:626 msgid "" "This constant contains a boolean value which indicates if IPv6 is supported " "on this platform." msgstr "" -#: ../../library/socket.rst:624 +#: ../../library/socket.rst:632 msgid "" "These are string constants containing Bluetooth addresses with special " "meanings. For example, :const:`BDADDR_ANY` can be used to indicate any " "address when specifying the binding socket with :const:`BTPROTO_RFCOMM`." msgstr "" -#: ../../library/socket.rst:633 +#: ../../library/socket.rst:641 msgid "" -"For use with :const:`BTPROTO_HCI`. :const:`HCI_FILTER` is not available for " -"NetBSD or DragonFlyBSD. :const:`HCI_TIME_STAMP` and :const:`HCI_DATA_DIR` " -"are not available for FreeBSD, NetBSD, or DragonFlyBSD." +"For use with :const:`BTPROTO_HCI`. :const:`!HCI_FILTER` is only available on " +"Linux and FreeBSD. :const:`!HCI_TIME_STAMP` and :const:`!HCI_DATA_DIR` are " +"only available on Linux." msgstr "" -#: ../../library/socket.rst:640 +#: ../../library/socket.rst:647 msgid "" "Constant for Qualcomm's IPC router protocol, used to communicate with " "service providing remote processors." msgstr "" -#: ../../library/socket.rst:649 +#: ../../library/socket.rst:656 msgid "" "LOCAL_CREDS and LOCAL_CREDS_PERSISTENT can be used with SOCK_DGRAM, " "SOCK_STREAM sockets, equivalent to Linux/DragonFlyBSD SO_PASSCRED, while " @@ -862,49 +841,42 @@ msgid "" "message type." msgstr "" -#: ../../library/socket.rst:658 -msgid ":ref:`Availability `: FreeBSD." -msgstr ":ref:`Disponibilidade `: FreeBSD." - -#: ../../library/socket.rst:662 +#: ../../library/socket.rst:669 msgid "" "Constant to optimize CPU locality, to be used in conjunction with :data:" "`SO_REUSEPORT`." msgstr "" -#: ../../library/socket.rst:682 +#: ../../library/socket.rst:689 msgid "Constants for Windows Hyper-V sockets for host/guest communications." msgstr "" -#: ../../library/socket.rst:684 ../../library/socket.rst:891 -#: ../../library/socket.rst:1984 -msgid ":ref:`Availability `: Windows." -msgstr ":ref:`Disponibilidade `: Windows." - -#: ../../library/socket.rst:695 +#: ../../library/socket.rst:702 msgid "" "`IEEE 802.3 protocol number `_. constants." msgstr "" -#: ../../library/socket.rst:699 -msgid ":ref:`Availability `: Linux, FreeBSD, macOS." +#: ../../library/socket.rst:714 +msgid "" +"These constants are used by the :meth:`~socket.socket.shutdown` method of " +"socket objects." msgstr "" -#: ../../library/socket.rst:705 +#: ../../library/socket.rst:719 msgid "Functions" msgstr "Funções" -#: ../../library/socket.rst:708 +#: ../../library/socket.rst:722 msgid "Creating sockets" msgstr "Criação de sockets" -#: ../../library/socket.rst:710 +#: ../../library/socket.rst:724 msgid "" "The following functions all create :ref:`socket objects `." msgstr "" -#: ../../library/socket.rst:715 +#: ../../library/socket.rst:729 msgid "" "Create a new socket using the given address family, socket type and protocol " "number. The address family should be :const:`AF_INET` (the default), :const:" @@ -917,7 +889,7 @@ msgid "" "`CAN_J1939`." msgstr "" -#: ../../library/socket.rst:725 +#: ../../library/socket.rst:739 msgid "" "If *fileno* is specified, the values for *family*, *type*, and *proto* are " "auto-detected from the specified file descriptor. Auto-detection can be " @@ -925,15 +897,15 @@ msgid "" "arguments. This only affects how Python represents e.g. the return value " "of :meth:`socket.getpeername` but not the actual OS resource. Unlike :func:" "`socket.fromfd`, *fileno* will return the same socket and not a duplicate. " -"This may help close a detached socket using :meth:`socket.close()`." +"This may help close a detached socket using :meth:`socket.close`." msgstr "" -#: ../../library/socket.rst:734 ../../library/socket.rst:880 -#: ../../library/socket.rst:1387 ../../library/socket.rst:1481 +#: ../../library/socket.rst:748 ../../library/socket.rst:894 +#: ../../library/socket.rst:1430 ../../library/socket.rst:1524 msgid "The newly created socket is :ref:`non-inheritable `." msgstr "" -#: ../../library/socket.rst:736 +#: ../../library/socket.rst:750 msgid "" "Raises an :ref:`auditing event ` ``socket.__new__`` with arguments " "``self``, ``family``, ``type``, ``protocol``." @@ -941,44 +913,51 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``socket.__new__`` com os " "argumentos ``self``, ``family``, ``type``, ``protocol``." -#: ../../library/socket.rst:738 +#: ../../library/socket.rst:752 msgid "The AF_CAN family was added. The AF_RDS family was added." msgstr "" -#: ../../library/socket.rst:742 +#: ../../library/socket.rst:756 msgid "The CAN_BCM protocol was added." msgstr "" -#: ../../library/socket.rst:745 ../../library/socket.rst:882 +#: ../../library/socket.rst:759 ../../library/socket.rst:896 msgid "The returned socket is now non-inheritable." msgstr "" -#: ../../library/socket.rst:748 +#: ../../library/socket.rst:762 msgid "The CAN_ISOTP protocol was added." msgstr "" -#: ../../library/socket.rst:751 +#: ../../library/socket.rst:765 msgid "" "When :const:`SOCK_NONBLOCK` or :const:`SOCK_CLOEXEC` bit flags are applied " "to *type* they are cleared, and :attr:`socket.type` will not reflect them. " "They are still passed to the underlying system ``socket()`` call. Therefore," msgstr "" -#: ../../library/socket.rst:763 +#: ../../library/socket.rst:773 +msgid "" +"sock = socket.socket(\n" +" socket.AF_INET,\n" +" socket.SOCK_STREAM | socket.SOCK_NONBLOCK)" +msgstr "" + +#: ../../library/socket.rst:777 msgid "" "will still create a non-blocking socket on OSes that support " "``SOCK_NONBLOCK``, but ``sock.type`` will be set to ``socket.SOCK_STREAM``." msgstr "" -#: ../../library/socket.rst:767 +#: ../../library/socket.rst:781 msgid "The CAN_J1939 protocol was added." msgstr "" -#: ../../library/socket.rst:770 +#: ../../library/socket.rst:784 msgid "The IPPROTO_MPTCP protocol was added." msgstr "" -#: ../../library/socket.rst:775 +#: ../../library/socket.rst:789 msgid "" "Build a pair of connected socket objects using the given address family, " "socket type, and protocol number. Address family, socket type, and protocol " @@ -987,25 +966,25 @@ msgid "" "default is :const:`AF_INET`." msgstr "" -#: ../../library/socket.rst:780 +#: ../../library/socket.rst:794 msgid "The newly created sockets are :ref:`non-inheritable `." msgstr "" -#: ../../library/socket.rst:782 +#: ../../library/socket.rst:796 msgid "" "The returned socket objects now support the whole socket API, rather than a " "subset." msgstr "" -#: ../../library/socket.rst:786 +#: ../../library/socket.rst:800 msgid "The returned sockets are now non-inheritable." msgstr "" -#: ../../library/socket.rst:789 +#: ../../library/socket.rst:803 msgid "Windows support added." msgstr "" -#: ../../library/socket.rst:795 +#: ../../library/socket.rst:809 msgid "" "Connect to a TCP service listening on the internet *address* (a 2-tuple " "``(host, port)``), and return the socket object. This is a higher-level " @@ -1016,21 +995,21 @@ msgid "" "IPv4 and IPv6." msgstr "" -#: ../../library/socket.rst:803 +#: ../../library/socket.rst:817 msgid "" "Passing the optional *timeout* parameter will set the timeout on the socket " "instance before attempting to connect. If no *timeout* is supplied, the " "global default timeout setting returned by :func:`getdefaulttimeout` is used." msgstr "" -#: ../../library/socket.rst:808 +#: ../../library/socket.rst:822 msgid "" "If supplied, *source_address* must be a 2-tuple ``(host, port)`` for the " "socket to bind to as its source address before connecting. If host or port " "are '' or 0 respectively the OS default behavior will be used." msgstr "" -#: ../../library/socket.rst:812 +#: ../../library/socket.rst:826 msgid "" "When a connection cannot be created, an exception is raised. By default, it " "is the exception from the last address in the list. If *all_errors* is " @@ -1038,21 +1017,21 @@ msgid "" "attempts." msgstr "" -#: ../../library/socket.rst:817 +#: ../../library/socket.rst:831 msgid "*source_address* was added." msgstr "*source_address* foi adicionado." -#: ../../library/socket.rst:820 +#: ../../library/socket.rst:834 msgid "*all_errors* was added." msgstr "" -#: ../../library/socket.rst:826 +#: ../../library/socket.rst:840 msgid "" "Convenience function which creates a TCP socket bound to *address* (a 2-" "tuple ``(host, port)``) and returns the socket object." msgstr "" -#: ../../library/socket.rst:829 +#: ../../library/socket.rst:843 msgid "" "*family* should be either :data:`AF_INET` or :data:`AF_INET6`. *backlog* is " "the queue size passed to :meth:`socket.listen`; if not specified , a default " @@ -1060,33 +1039,45 @@ msgid "" "`SO_REUSEPORT` socket option." msgstr "" -#: ../../library/socket.rst:834 +#: ../../library/socket.rst:848 +msgid "" +"If *dualstack_ipv6* is true, *family* is :data:`AF_INET6` and the platform " +"supports it the socket will be able to accept both IPv4 and IPv6 " +"connections, else it will raise :exc:`ValueError`. Most POSIX platforms and " +"Windows are supposed to support this functionality. When this functionality " +"is enabled the address returned by :meth:`socket.getpeername` when an IPv4 " +"connection occurs will be an IPv6 address represented as an IPv4-mapped IPv6 " +"address. If *dualstack_ipv6* is false it will explicitly disable this " +"functionality on platforms that enable it by default (e.g. Linux). This " +"parameter can be used in conjunction with :func:`has_dualstack_ipv6`:" +msgstr "" + +#: ../../library/socket.rst:861 msgid "" -"If *dualstack_ipv6* is true and the platform supports it the socket will be " -"able to accept both IPv4 and IPv6 connections, else it will raise :exc:" -"`ValueError`. Most POSIX platforms and Windows are supposed to support this " -"functionality. When this functionality is enabled the address returned by :" -"meth:`socket.getpeername` when an IPv4 connection occurs will be an IPv6 " -"address represented as an IPv4-mapped IPv6 address. If *dualstack_ipv6* is " -"false it will explicitly disable this functionality on platforms that enable " -"it by default (e.g. Linux). This parameter can be used in conjunction with :" -"func:`has_dualstack_ipv6`:" +"import socket\n" +"\n" +"addr = (\"\", 8080) # all interfaces, port 8080\n" +"if socket.has_dualstack_ipv6():\n" +" s = socket.create_server(addr, family=socket.AF_INET6, " +"dualstack_ipv6=True)\n" +"else:\n" +" s = socket.create_server(addr)" msgstr "" -#: ../../library/socket.rst:856 +#: ../../library/socket.rst:870 msgid "" "On POSIX platforms the :data:`SO_REUSEADDR` socket option is set in order to " "immediately reuse previous sockets which were bound on the same *address* " "and remained in TIME_WAIT state." msgstr "" -#: ../../library/socket.rst:864 +#: ../../library/socket.rst:878 msgid "" "Return ``True`` if the platform supports creating a TCP socket which can " "handle both IPv4 and IPv6 connections." msgstr "" -#: ../../library/socket.rst:871 +#: ../../library/socket.rst:885 msgid "" "Duplicate the file descriptor *fd* (an integer as returned by a file " "object's :meth:`~io.IOBase.fileno` method) and build a socket object from " @@ -1099,34 +1090,39 @@ msgid "" "daemon). The socket is assumed to be in blocking mode." msgstr "" -#: ../../library/socket.rst:888 +#: ../../library/socket.rst:902 msgid "" "Instantiate a socket from data obtained from the :meth:`socket.share` " "method. The socket is assumed to be in blocking mode." msgstr "" -#: ../../library/socket.rst:898 +#: ../../library/socket.rst:912 msgid "" "This is a Python type object that represents the socket object type. It is " "the same as ``type(socket(...))``." msgstr "" -#: ../../library/socket.rst:903 +#: ../../library/socket.rst:917 msgid "Other functions" msgstr "Outras funções" -#: ../../library/socket.rst:905 +#: ../../library/socket.rst:919 msgid "The :mod:`socket` module also offers various network-related services:" msgstr "" -#: ../../library/socket.rst:910 +#: ../../library/socket.rst:924 msgid "" "Close a socket file descriptor. This is like :func:`os.close`, but for " "sockets. On some platforms (most noticeable Windows) :func:`os.close` does " "not work for socket file descriptors." msgstr "" -#: ../../library/socket.rst:918 +#: ../../library/socket.rst:932 +msgid "" +"This function wraps the C function ``getaddrinfo`` of the underlying system." +msgstr "" + +#: ../../library/socket.rst:934 msgid "" "Translate the *host*/*port* argument into a sequence of 5-tuples that " "contain all the necessary arguments for creating a socket connected to that " @@ -1136,26 +1132,31 @@ msgid "" "and *port*, you can pass ``NULL`` to the underlying C API." msgstr "" -#: ../../library/socket.rst:925 +#: ../../library/socket.rst:941 msgid "" "The *family*, *type* and *proto* arguments can be optionally specified in " -"order to narrow the list of addresses returned. Passing zero as a value for " -"each of these arguments selects the full range of results. The *flags* " -"argument can be one or several of the ``AI_*`` constants, and will influence " -"how results are computed and returned. For example, :const:`AI_NUMERICHOST` " -"will disable domain name resolution and will raise an error if *host* is a " -"domain name." +"order to provide options and limit the list of addresses returned. Pass " +"their default values (:data:`AF_UNSPEC`, 0, and 0, respectively) to not " +"limit the results. See the note below for details." +msgstr "" + +#: ../../library/socket.rst:946 +msgid "" +"The *flags* argument can be one or several of the ``AI_*`` constants, and " +"will influence how results are computed and returned. For example, :const:" +"`AI_NUMERICHOST` will disable domain name resolution and will raise an error " +"if *host* is a domain name." msgstr "" -#: ../../library/socket.rst:933 +#: ../../library/socket.rst:951 msgid "The function returns a list of 5-tuples with the following structure:" msgstr "" -#: ../../library/socket.rst:935 +#: ../../library/socket.rst:953 msgid "``(family, type, proto, canonname, sockaddr)``" msgstr "" -#: ../../library/socket.rst:937 +#: ../../library/socket.rst:955 msgid "" "In these tuples, *family*, *type*, *proto* are all integers and are meant to " "be passed to the :func:`~socket.socket` function. *canonname* will be a " @@ -1167,7 +1168,39 @@ msgid "" "`AF_INET6`), and is meant to be passed to the :meth:`socket.connect` method." msgstr "" -#: ../../library/socket.rst:947 +#: ../../library/socket.rst:967 +msgid "" +"If you intend to use results from :func:`!getaddrinfo` to create a socket " +"(rather than, for example, retrieve *canonname*), consider limiting the " +"results by *type* (e.g. :data:`SOCK_STREAM` or :data:`SOCK_DGRAM`) and/or " +"*proto* (e.g. :data:`IPPROTO_TCP` or :data:`IPPROTO_UDP`) that your " +"application can handle." +msgstr "" + +#: ../../library/socket.rst:973 +msgid "" +"The behavior with default values of *family*, *type*, *proto* and *flags* is " +"system-specific." +msgstr "" + +#: ../../library/socket.rst:976 +msgid "" +"Many systems (for example, most Linux configurations) will return a sorted " +"list of all matching addresses. These addresses should generally be tried in " +"order until a connection succeeds (possibly tried in parallel, for example, " +"using a `Happy Eyeballs`_ algorithm). In these cases, limiting the *type* " +"and/or *proto* can help eliminate unsuccessful or unusable connection " +"attempts." +msgstr "" + +#: ../../library/socket.rst:983 +msgid "" +"Some systems will, however, only return a single address. (For example, this " +"was reported on Solaris and AIX configurations.) On these systems, limiting " +"the *type* and/or *proto* helps ensure that this address is usable." +msgstr "" + +#: ../../library/socket.rst:988 msgid "" "Raises an :ref:`auditing event ` ``socket.getaddrinfo`` with " "arguments ``host``, ``port``, ``family``, ``type``, ``protocol``." @@ -1175,24 +1208,33 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``socket.getaddrinfo`` com " "os argumentos ``host``, ``port``, ``family``, ``type``, ``protocol``." -#: ../../library/socket.rst:949 +#: ../../library/socket.rst:990 msgid "" "The following example fetches address information for a hypothetical TCP " "connection to ``example.org`` on port 80 (results may differ on your system " "if IPv6 isn't enabled)::" msgstr "" -#: ../../library/socket.rst:959 +#: ../../library/socket.rst:994 +msgid "" +">>> socket.getaddrinfo(\"example.org\", 80, proto=socket.IPPROTO_TCP)\n" +"[(socket.AF_INET6, socket.SOCK_STREAM,\n" +" 6, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)),\n" +" (socket.AF_INET, socket.SOCK_STREAM,\n" +" 6, '', ('93.184.216.34', 80))]" +msgstr "" + +#: ../../library/socket.rst:1000 msgid "parameters can now be passed using keyword arguments." msgstr "" -#: ../../library/socket.rst:962 +#: ../../library/socket.rst:1003 msgid "" "for IPv6 multicast addresses, string representing an address will not " "contain ``%scope_id`` part." msgstr "" -#: ../../library/socket.rst:968 +#: ../../library/socket.rst:1011 msgid "" "Return a fully qualified domain name for *name*. If *name* is omitted or " "empty, it is interpreted as the local host. To find the fully qualified " @@ -1203,7 +1245,7 @@ msgid "" "``'0.0.0.0'``, the hostname from :func:`gethostname` is returned." msgstr "" -#: ../../library/socket.rst:979 +#: ../../library/socket.rst:1022 msgid "" "Translate a host name to IPv4 address format. The IPv4 address is returned " "as a string, such as ``'100.50.200.5'``. If the host name is an IPv4 " @@ -1213,7 +1255,7 @@ msgid "" "stack support." msgstr "" -#: ../../library/socket.rst:985 ../../library/socket.rst:1001 +#: ../../library/socket.rst:1028 ../../library/socket.rst:1044 msgid "" "Raises an :ref:`auditing event ` ``socket.gethostbyname`` with " "argument ``hostname``." @@ -1221,7 +1263,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``socket.gethostbyname`` " "com o argumento ``hostname``." -#: ../../library/socket.rst:992 +#: ../../library/socket.rst:1035 msgid "" "Translate a host name to IPv4 address format, extended interface. Return a 3-" "tuple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the host's " @@ -1233,13 +1275,13 @@ msgid "" "stack support." msgstr "" -#: ../../library/socket.rst:1008 +#: ../../library/socket.rst:1051 msgid "" "Return a string containing the hostname of the machine where the Python " "interpreter is currently executing." msgstr "" -#: ../../library/socket.rst:1011 +#: ../../library/socket.rst:1054 msgid "" "Raises an :ref:`auditing event ` ``socket.gethostname`` with no " "arguments." @@ -1247,13 +1289,13 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``socket.gethostname`` sem " "argumentos." -#: ../../library/socket.rst:1013 +#: ../../library/socket.rst:1056 msgid "" "Note: :func:`gethostname` doesn't always return the fully qualified domain " "name; use :func:`getfqdn` for that." msgstr "" -#: ../../library/socket.rst:1021 +#: ../../library/socket.rst:1064 msgid "" "Return a 3-tuple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is " "the primary host name responding to the given *ip_address*, *aliaslist* is a " @@ -1264,7 +1306,7 @@ msgid "" "`gethostbyaddr` supports both IPv4 and IPv6." msgstr "" -#: ../../library/socket.rst:1029 +#: ../../library/socket.rst:1072 msgid "" "Raises an :ref:`auditing event ` ``socket.gethostbyaddr`` with " "argument ``ip_address``." @@ -1272,7 +1314,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``socket.gethostbyaddr`` " "com o argumento ``ip_address``." -#: ../../library/socket.rst:1036 +#: ../../library/socket.rst:1079 msgid "" "Translate a socket address *sockaddr* into a 2-tuple ``(host, port)``. " "Depending on the settings of *flags*, the result can contain a fully " @@ -1280,18 +1322,18 @@ msgid "" "Similarly, *port* can contain a string port name or a numeric port number." msgstr "" -#: ../../library/socket.rst:1041 +#: ../../library/socket.rst:1084 msgid "" "For IPv6 addresses, ``%scope_id`` is appended to the host part if *sockaddr* " "contains meaningful *scope_id*. Usually this happens for multicast addresses." msgstr "" -#: ../../library/socket.rst:1044 +#: ../../library/socket.rst:1087 msgid "" "For more information about *flags* you can consult :manpage:`getnameinfo(3)`." msgstr "" -#: ../../library/socket.rst:1046 +#: ../../library/socket.rst:1089 msgid "" "Raises an :ref:`auditing event ` ``socket.getnameinfo`` with " "argument ``sockaddr``." @@ -1299,7 +1341,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``socket.getnameinfo`` com " "o argumento ``sockaddr``." -#: ../../library/socket.rst:1053 +#: ../../library/socket.rst:1096 msgid "" "Translate an internet protocol name (for example, ``'icmp'``) to a constant " "suitable for passing as the (optional) third argument to the :func:`~socket." @@ -1308,14 +1350,14 @@ msgid "" "is chosen automatically if the protocol is omitted or zero." msgstr "" -#: ../../library/socket.rst:1064 +#: ../../library/socket.rst:1107 msgid "" "Translate an internet service name and protocol name to a port number for " "that service. The optional protocol name, if given, should be ``'tcp'`` or " "``'udp'``, otherwise any protocol will match." msgstr "" -#: ../../library/socket.rst:1068 +#: ../../library/socket.rst:1111 msgid "" "Raises an :ref:`auditing event ` ``socket.getservbyname`` with " "arguments ``servicename``, ``protocolname``." @@ -1323,14 +1365,14 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``socket.getservbyname`` " "com os argumentos ``servicename``, ``protocolname``." -#: ../../library/socket.rst:1075 +#: ../../library/socket.rst:1118 msgid "" "Translate an internet port number and protocol name to a service name for " "that service. The optional protocol name, if given, should be ``'tcp'`` or " "``'udp'``, otherwise any protocol will match." msgstr "" -#: ../../library/socket.rst:1079 +#: ../../library/socket.rst:1122 msgid "" "Raises an :ref:`auditing event ` ``socket.getservbyport`` with " "arguments ``port``, ``protocolname``." @@ -1338,40 +1380,40 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``socket.getservbyport`` " "com os argumentos ``port`` e ``protocolname``." -#: ../../library/socket.rst:1086 +#: ../../library/socket.rst:1129 msgid "" "Convert 32-bit positive integers from network to host byte order. On " "machines where the host byte order is the same as network byte order, this " "is a no-op; otherwise, it performs a 4-byte swap operation." msgstr "" -#: ../../library/socket.rst:1093 +#: ../../library/socket.rst:1136 msgid "" "Convert 16-bit positive integers from network to host byte order. On " "machines where the host byte order is the same as network byte order, this " "is a no-op; otherwise, it performs a 2-byte swap operation." msgstr "" -#: ../../library/socket.rst:1097 ../../library/socket.rst:1115 +#: ../../library/socket.rst:1140 ../../library/socket.rst:1158 msgid "" "Raises :exc:`OverflowError` if *x* does not fit in a 16-bit unsigned integer." msgstr "" -#: ../../library/socket.rst:1104 +#: ../../library/socket.rst:1147 msgid "" "Convert 32-bit positive integers from host to network byte order. On " "machines where the host byte order is the same as network byte order, this " "is a no-op; otherwise, it performs a 4-byte swap operation." msgstr "" -#: ../../library/socket.rst:1111 +#: ../../library/socket.rst:1154 msgid "" "Convert 16-bit positive integers from host to network byte order. On " "machines where the host byte order is the same as network byte order, this " "is a no-op; otherwise, it performs a 2-byte swap operation." msgstr "" -#: ../../library/socket.rst:1122 +#: ../../library/socket.rst:1165 msgid "" "Convert an IPv4 address from dotted-quad string format (for example, " "'123.45.67.89') to 32-bit packed binary format, as a bytes object four " @@ -1380,26 +1422,26 @@ msgid "" "which is the C type for the 32-bit packed binary this function returns." msgstr "" -#: ../../library/socket.rst:1128 +#: ../../library/socket.rst:1171 msgid "" ":func:`inet_aton` also accepts strings with less than three dots; see the " "Unix manual page :manpage:`inet(3)` for details." msgstr "" -#: ../../library/socket.rst:1131 +#: ../../library/socket.rst:1174 msgid "" "If the IPv4 address string passed to this function is invalid, :exc:" "`OSError` will be raised. Note that exactly what is valid depends on the " "underlying C implementation of :c:func:`inet_aton`." msgstr "" -#: ../../library/socket.rst:1135 +#: ../../library/socket.rst:1178 msgid "" ":func:`inet_aton` does not support IPv6, and :func:`inet_pton` should be " "used instead for IPv4/v6 dual stack support." msgstr "" -#: ../../library/socket.rst:1141 +#: ../../library/socket.rst:1184 msgid "" "Convert a 32-bit packed IPv4 address (a :term:`bytes-like object` four bytes " "in length) to its standard dotted-quad string representation (for example, " @@ -1409,7 +1451,7 @@ msgid "" "argument." msgstr "" -#: ../../library/socket.rst:1148 +#: ../../library/socket.rst:1191 msgid "" "If the byte sequence passed to this function is not exactly 4 bytes in " "length, :exc:`OSError` will be raised. :func:`inet_ntoa` does not support " @@ -1417,7 +1459,7 @@ msgid "" "support." msgstr "" -#: ../../library/socket.rst:1159 +#: ../../library/socket.rst:1202 msgid "" "Convert an IP address from its family-specific string format to a packed, " "binary format. :func:`inet_pton` is useful when a library or network " @@ -1425,7 +1467,7 @@ msgid "" "`inet_aton`) or :c:struct:`in6_addr`." msgstr "" -#: ../../library/socket.rst:1164 +#: ../../library/socket.rst:1207 msgid "" "Supported values for *address_family* are currently :const:`AF_INET` and :" "const:`AF_INET6`. If the IP address string *ip_string* is invalid, :exc:" @@ -1434,15 +1476,11 @@ msgid "" "`inet_pton`." msgstr "" -#: ../../library/socket.rst:1170 ../../library/socket.rst:1190 -msgid ":ref:`Availability `: Unix, Windows." -msgstr ":ref:`Disponibilidade `: Unix, Windows." - -#: ../../library/socket.rst:1172 ../../library/socket.rst:1192 +#: ../../library/socket.rst:1215 ../../library/socket.rst:1235 msgid "Windows support added" msgstr "Suporte para Windows adicionado." -#: ../../library/socket.rst:1178 +#: ../../library/socket.rst:1221 msgid "" "Convert a packed IP address (a :term:`bytes-like object` of some number of " "bytes) to its standard, family-specific string representation (for example, " @@ -1451,7 +1489,7 @@ msgid "" "(similar to :func:`inet_ntoa`) or :c:struct:`in6_addr`." msgstr "" -#: ../../library/socket.rst:1185 +#: ../../library/socket.rst:1228 msgid "" "Supported values for *address_family* are currently :const:`AF_INET` and :" "const:`AF_INET6`. If the bytes object *packed_ip* is not the correct length " @@ -1459,7 +1497,7 @@ msgid "" "`OSError` is raised for errors from the call to :func:`inet_ntop`." msgstr "" -#: ../../library/socket.rst:1207 +#: ../../library/socket.rst:1250 msgid "" "Return the total length, without trailing padding, of an ancillary data item " "with associated data of the given *length*. This value can often be used as " @@ -1470,17 +1508,12 @@ msgid "" "the permissible range of values." msgstr "" -#: ../../library/socket.rst:1216 ../../library/socket.rst:1239 -#: ../../library/socket.rst:1860 -msgid ":ref:`Availability `: Unix, not WASI." -msgstr ":ref:`Disponibilidade `: Unix, não WASI." - -#: ../../library/socket.rst:1218 ../../library/socket.rst:1710 -#: ../../library/socket.rst:1754 ../../library/socket.rst:1862 +#: ../../library/socket.rst:1261 ../../library/socket.rst:1748 +#: ../../library/socket.rst:1792 ../../library/socket.rst:1900 msgid "Most Unix platforms." msgstr "" -#: ../../library/socket.rst:1225 +#: ../../library/socket.rst:1268 msgid "" "Return the buffer size needed for :meth:`~socket.recvmsg` to receive an " "ancillary data item with associated data of the given *length*, along with " @@ -1490,7 +1523,7 @@ msgid "" "values." msgstr "" -#: ../../library/socket.rst:1233 +#: ../../library/socket.rst:1276 msgid "" "Note that some systems might support ancillary data without providing this " "function. Also note that setting the buffer size using the results of this " @@ -1498,31 +1531,31 @@ msgid "" "received, since additional data may be able to fit into the padding area." msgstr "" -#: ../../library/socket.rst:1241 +#: ../../library/socket.rst:1284 msgid "most Unix platforms." msgstr "" -#: ../../library/socket.rst:1248 +#: ../../library/socket.rst:1291 msgid "" "Return the default timeout in seconds (float) for new socket objects. A " "value of ``None`` indicates that new socket objects have no timeout. When " "the socket module is first imported, the default is ``None``." msgstr "" -#: ../../library/socket.rst:1255 +#: ../../library/socket.rst:1298 msgid "" "Set the default timeout in seconds (float) for new socket objects. When the " "socket module is first imported, the default is ``None``. See :meth:" "`~socket.settimeout` for possible values and their respective meanings." msgstr "" -#: ../../library/socket.rst:1263 +#: ../../library/socket.rst:1306 msgid "" "Set the machine's hostname to *name*. This will raise an :exc:`OSError` if " "you don't have enough rights." msgstr "" -#: ../../library/socket.rst:1266 +#: ../../library/socket.rst:1309 msgid "" "Raises an :ref:`auditing event ` ``socket.sethostname`` with " "argument ``name``." @@ -1530,113 +1563,102 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``socket.sethostname`` com " "o argumento ``name``." -#: ../../library/socket.rst:1268 ../../library/socket.rst:1708 -#: ../../library/socket.rst:1752 -msgid ":ref:`Availability `: Unix." -msgstr ":ref:`Disponibilidade `: Unix." - -#: ../../library/socket.rst:1275 +#: ../../library/socket.rst:1318 msgid "" "Return a list of network interface information (index int, name string) " "tuples. :exc:`OSError` if the system call fails." msgstr "" -#: ../../library/socket.rst:1279 ../../library/socket.rst:1306 -#: ../../library/socket.rst:1323 ../../library/socket.rst:1340 -#: ../../library/socket.rst:1354 -msgid ":ref:`Availability `: Unix, Windows, not WASI." -msgstr ":ref:`Disponibilidade `: Unix, Windows, não WASI." - -#: ../../library/socket.rst:1283 ../../library/socket.rst:1310 -#: ../../library/socket.rst:1327 +#: ../../library/socket.rst:1326 ../../library/socket.rst:1353 +#: ../../library/socket.rst:1370 msgid "Windows support was added." msgstr "Suporte ao Windows foi adicionado." -#: ../../library/socket.rst:1288 +#: ../../library/socket.rst:1331 msgid "" "On Windows network interfaces have different names in different contexts " "(all names are examples):" msgstr "" -#: ../../library/socket.rst:1291 +#: ../../library/socket.rst:1334 msgid "UUID: ``{FB605B73-AAC2-49A6-9A2F-25416AEA0573}``" msgstr "" -#: ../../library/socket.rst:1292 +#: ../../library/socket.rst:1335 msgid "name: ``ethernet_32770``" msgstr "" -#: ../../library/socket.rst:1293 +#: ../../library/socket.rst:1336 msgid "friendly name: ``vEthernet (nat)``" msgstr "" -#: ../../library/socket.rst:1294 +#: ../../library/socket.rst:1337 msgid "description: ``Hyper-V Virtual Ethernet Adapter``" msgstr "" -#: ../../library/socket.rst:1296 +#: ../../library/socket.rst:1339 msgid "" "This function returns names of the second form from the list, " "``ethernet_32770`` in this example case." msgstr "" -#: ../../library/socket.rst:1302 +#: ../../library/socket.rst:1345 msgid "" "Return a network interface index number corresponding to an interface name. :" "exc:`OSError` if no interface with the given name exists." msgstr "" -#: ../../library/socket.rst:1314 ../../library/socket.rst:1331 +#: ../../library/socket.rst:1357 ../../library/socket.rst:1374 msgid "\"Interface name\" is a name as documented in :func:`if_nameindex`." msgstr "" -#: ../../library/socket.rst:1319 +#: ../../library/socket.rst:1362 msgid "" "Return a network interface name corresponding to an interface index number. :" "exc:`OSError` if no interface with the given index exists." msgstr "" -#: ../../library/socket.rst:1336 +#: ../../library/socket.rst:1379 msgid "" "Send the list of file descriptors *fds* over an :const:`AF_UNIX` socket " "*sock*. The *fds* parameter is a sequence of file descriptors. Consult :meth:" "`~socket.sendmsg` for the documentation of these parameters." msgstr "" -#: ../../library/socket.rst:1342 ../../library/socket.rst:1356 +#: ../../library/socket.rst:1385 ../../library/socket.rst:1399 msgid "" "Unix platforms supporting :meth:`~socket.sendmsg` and :const:`SCM_RIGHTS` " "mechanism." msgstr "" -#: ../../library/socket.rst:1350 +#: ../../library/socket.rst:1393 msgid "" "Receive up to *maxfds* file descriptors from an :const:`AF_UNIX` socket " "*sock*. Return ``(msg, list(fds), flags, addr)``. Consult :meth:`~socket." "recvmsg` for the documentation of these parameters." msgstr "" -#: ../../library/socket.rst:1363 +#: ../../library/socket.rst:1406 msgid "Any truncated integers at the end of the list of file descriptors." msgstr "" -#: ../../library/socket.rst:1369 +#: ../../library/socket.rst:1412 msgid "Socket Objects" msgstr "" -#: ../../library/socket.rst:1371 +#: ../../library/socket.rst:1414 msgid "" "Socket objects have the following methods. Except for :meth:`~socket." "makefile`, these correspond to Unix system calls applicable to sockets." msgstr "" -#: ../../library/socket.rst:1375 +#: ../../library/socket.rst:1418 msgid "" "Support for the :term:`context manager` protocol was added. Exiting the " "context manager is equivalent to calling :meth:`~socket.close`." msgstr "" -#: ../../library/socket.rst:1382 +#: ../../library/socket.rst:1425 msgid "" "Accept a connection. The socket must be bound to an address and listening " "for connections. The return value is a pair ``(conn, address)`` where *conn* " @@ -1645,27 +1667,27 @@ msgid "" "connection." msgstr "" -#: ../../library/socket.rst:1389 ../../library/socket.rst:1483 +#: ../../library/socket.rst:1432 ../../library/socket.rst:1526 msgid "The socket is now non-inheritable." msgstr "" -#: ../../library/socket.rst:1392 ../../library/socket.rst:1623 -#: ../../library/socket.rst:1637 ../../library/socket.rst:1714 -#: ../../library/socket.rst:1787 ../../library/socket.rst:1806 -#: ../../library/socket.rst:1823 ../../library/socket.rst:1868 +#: ../../library/socket.rst:1435 ../../library/socket.rst:1661 +#: ../../library/socket.rst:1675 ../../library/socket.rst:1752 +#: ../../library/socket.rst:1825 ../../library/socket.rst:1844 +#: ../../library/socket.rst:1861 ../../library/socket.rst:1906 msgid "" "If the system call is interrupted and the signal handler does not raise an " "exception, the method now retries the system call instead of raising an :exc:" "`InterruptedError` exception (see :pep:`475` for the rationale)." msgstr "" -#: ../../library/socket.rst:1400 +#: ../../library/socket.rst:1443 msgid "" "Bind the socket to *address*. The socket must not already be bound. (The " "format of *address* depends on the address family --- see above.)" msgstr "" -#: ../../library/socket.rst:1403 +#: ../../library/socket.rst:1446 msgid "" "Raises an :ref:`auditing event ` ``socket.bind`` with arguments " "``self``, ``address``." @@ -1673,43 +1695,42 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``socket.bind`` com os " "argumentos ``self``, ``address``." -#: ../../library/socket.rst:1410 +#: ../../library/socket.rst:1453 msgid "" "Mark the socket closed. The underlying system resource (e.g. a file " -"descriptor) is also closed when all file objects from :meth:`makefile()` are " +"descriptor) is also closed when all file objects from :meth:`makefile` are " "closed. Once that happens, all future operations on the socket object will " "fail. The remote end will receive no more data (after queued data is " "flushed)." msgstr "" -#: ../../library/socket.rst:1416 +#: ../../library/socket.rst:1459 msgid "" "Sockets are automatically closed when they are garbage-collected, but it is " "recommended to :meth:`close` them explicitly, or to use a :keyword:`with` " "statement around them." msgstr "" -#: ../../library/socket.rst:1420 +#: ../../library/socket.rst:1463 msgid "" ":exc:`OSError` is now raised if an error occurs when the underlying :c:func:" "`close` call is made." msgstr "" -#: ../../library/socket.rst:1426 +#: ../../library/socket.rst:1469 msgid "" -":meth:`close()` releases the resource associated with a connection but does " +":meth:`close` releases the resource associated with a connection but does " "not necessarily close the connection immediately. If you want to close the " -"connection in a timely fashion, call :meth:`shutdown()` before :meth:" -"`close()`." +"connection in a timely fashion, call :meth:`shutdown` before :meth:`close`." msgstr "" -#: ../../library/socket.rst:1434 +#: ../../library/socket.rst:1477 msgid "" "Connect to a remote socket at *address*. (The format of *address* depends on " "the address family --- see above.)" msgstr "" -#: ../../library/socket.rst:1437 +#: ../../library/socket.rst:1480 msgid "" "If the connection is interrupted by a signal, the method waits until the " "connection completes, or raise a :exc:`TimeoutError` on timeout, if the " @@ -1719,7 +1740,7 @@ msgid "" "(or the exception raised by the signal handler)." msgstr "" -#: ../../library/socket.rst:1444 ../../library/socket.rst:1464 +#: ../../library/socket.rst:1487 ../../library/socket.rst:1507 msgid "" "Raises an :ref:`auditing event ` ``socket.connect`` with arguments " "``self``, ``address``." @@ -1727,7 +1748,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``socket.connect`` com os " "argumentos ``self``, ``address``." -#: ../../library/socket.rst:1446 +#: ../../library/socket.rst:1489 msgid "" "The method now waits until the connection completes instead of raising an :" "exc:`InterruptedError` exception if the connection is interrupted by a " @@ -1735,7 +1756,7 @@ msgid "" "blocking or has a timeout (see the :pep:`475` for the rationale)." msgstr "" -#: ../../library/socket.rst:1457 +#: ../../library/socket.rst:1500 msgid "" "Like ``connect(address)``, but return an error indicator instead of raising " "an exception for errors returned by the C-level :c:func:`connect` call " @@ -1745,38 +1766,38 @@ msgid "" "asynchronous connects." msgstr "" -#: ../../library/socket.rst:1470 +#: ../../library/socket.rst:1513 msgid "" "Put the socket object into closed state without actually closing the " "underlying file descriptor. The file descriptor is returned, and can be " "reused for other purposes." msgstr "" -#: ../../library/socket.rst:1479 +#: ../../library/socket.rst:1522 msgid "Duplicate the socket." msgstr "" -#: ../../library/socket.rst:1491 +#: ../../library/socket.rst:1534 msgid "" "Return the socket's file descriptor (a small integer), or -1 on failure. " "This is useful with :func:`select.select`." msgstr "" -#: ../../library/socket.rst:1494 +#: ../../library/socket.rst:1537 msgid "" "Under Windows the small integer returned by this method cannot be used where " "a file descriptor can be used (such as :func:`os.fdopen`). Unix does not " "have this limitation." msgstr "" -#: ../../library/socket.rst:1500 +#: ../../library/socket.rst:1543 msgid "" "Get the :ref:`inheritable flag ` of the socket's file " "descriptor or socket's handle: ``True`` if the socket can be inherited in " "child processes, ``False`` if it cannot." msgstr "" -#: ../../library/socket.rst:1509 +#: ../../library/socket.rst:1552 msgid "" "Return the remote address to which the socket is connected. This is useful " "to find out the port number of a remote IPv4/v6 socket, for instance. (The " @@ -1784,14 +1805,14 @@ msgid "" "above.) On some systems this function is not supported." msgstr "" -#: ../../library/socket.rst:1517 +#: ../../library/socket.rst:1560 msgid "" "Return the socket's own address. This is useful to find out the port number " "of an IPv4/v6 socket, for instance. (The format of the address returned " "depends on the address family --- see above.)" msgstr "" -#: ../../library/socket.rst:1524 +#: ../../library/socket.rst:1567 msgid "" "Return the value of the given socket option (see the Unix man page :manpage:" "`getsockopt(2)`). The needed symbolic constants (:ref:`SO_\\* etc. `_ for more information." msgstr "" -#: ../../library/socket.rst:1562 +#: ../../library/socket.rst:1605 msgid "" "On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl` " "functions may be used; they accept a socket object as their first argument." msgstr "" -#: ../../library/socket.rst:1565 +#: ../../library/socket.rst:1608 msgid "" "Currently only the following control codes are supported: ``SIO_RCVALL``, " "``SIO_KEEPALIVE_VALS``, and ``SIO_LOOPBACK_FAST_PATH``." msgstr "" -#: ../../library/socket.rst:1573 +#: ../../library/socket.rst:1616 msgid "" "Enable a server to accept connections. If *backlog* is specified, it must " "be at least 0 (if it is lower, it is set to 0); it specifies the number of " @@ -1855,11 +1876,11 @@ msgid "" "connections. If not specified, a default reasonable value is chosen." msgstr "" -#: ../../library/socket.rst:1580 +#: ../../library/socket.rst:1623 msgid "The *backlog* parameter is now optional." msgstr "" -#: ../../library/socket.rst:1589 +#: ../../library/socket.rst:1632 msgid "" "Return a :term:`file object` associated with the socket. The exact returned " "type depends on the arguments given to :meth:`makefile`. These arguments " @@ -1868,28 +1889,28 @@ msgid "" "``'b'``, or a combination of those." msgstr "" -#: ../../library/socket.rst:1595 +#: ../../library/socket.rst:1638 msgid "" "The socket must be in blocking mode; it can have a timeout, but the file " "object's internal buffer may end up in an inconsistent state if a timeout " "occurs." msgstr "" -#: ../../library/socket.rst:1599 +#: ../../library/socket.rst:1642 msgid "" "Closing the file object returned by :meth:`makefile` won't close the " "original socket unless all other file objects have been closed and :meth:" "`socket.close` has been called on the socket object." msgstr "" -#: ../../library/socket.rst:1605 +#: ../../library/socket.rst:1648 msgid "" "On Windows, the file-like object created by :meth:`makefile` cannot be used " "where a file object with a file descriptor is expected, such as the stream " "arguments of :meth:`subprocess.Popen`." msgstr "" -#: ../../library/socket.rst:1612 +#: ../../library/socket.rst:1655 msgid "" "Receive data from the socket. The return value is a bytes object " "representing the data received. The maximum amount of data to be received " @@ -1899,13 +1920,7 @@ msgid "" "zero." msgstr "" -#: ../../library/socket.rst:1620 -msgid "" -"For best match with hardware and network realities, the value of *bufsize* " -"should be a relatively small power of 2, for example, 4096." -msgstr "" - -#: ../../library/socket.rst:1631 +#: ../../library/socket.rst:1669 msgid "" "Receive data from the socket. The return value is a pair ``(bytes, " "address)`` where *bytes* is a bytes object representing the data received " @@ -1915,14 +1930,14 @@ msgid "" "address family --- see above.)" msgstr "" -#: ../../library/socket.rst:1642 +#: ../../library/socket.rst:1680 msgid "" "For multicast IPv6 address, first item of *address* does not contain " "``%scope_id`` part anymore. In order to get full IPv6 address use :func:" "`getnameinfo`." msgstr "" -#: ../../library/socket.rst:1649 +#: ../../library/socket.rst:1687 msgid "" "Receive normal data (up to *bufsize* bytes) and ancillary data from the " "socket. The *ancbufsize* argument sets the size in bytes of the internal " @@ -1933,7 +1948,7 @@ msgid "" "*flags* argument defaults to 0 and has the same meaning as for :meth:`recv`." msgstr "" -#: ../../library/socket.rst:1659 +#: ../../library/socket.rst:1697 msgid "" "The return value is a 4-tuple: ``(data, ancdata, msg_flags, address)``. The " "*data* item is a :class:`bytes` object holding the non-ancillary data " @@ -1948,7 +1963,7 @@ msgid "" "socket, if available; otherwise, its value is unspecified." msgstr "" -#: ../../library/socket.rst:1673 +#: ../../library/socket.rst:1711 msgid "" "On some systems, :meth:`sendmsg` and :meth:`recvmsg` can be used to pass " "file descriptors between processes over an :const:`AF_UNIX` socket. When " @@ -1961,7 +1976,7 @@ msgid "" "descriptors received via this mechanism." msgstr "" -#: ../../library/socket.rst:1684 +#: ../../library/socket.rst:1722 msgid "" "Some systems do not indicate the truncated length of ancillary data items " "which have been only partially received. If an item appears to extend " @@ -1970,7 +1985,7 @@ msgid "" "provided it has not been truncated before the start of its associated data." msgstr "" -#: ../../library/socket.rst:1691 +#: ../../library/socket.rst:1729 msgid "" "On systems which support the :const:`SCM_RIGHTS` mechanism, the following " "function will receive up to *maxfds* file descriptors, returning the message " @@ -1979,7 +1994,24 @@ msgid "" "meth:`sendmsg`. ::" msgstr "" -#: ../../library/socket.rst:1722 +#: ../../library/socket.rst:1735 +msgid "" +"import socket, array\n" +"\n" +"def recv_fds(sock, msglen, maxfds):\n" +" fds = array.array(\"i\") # Array of ints\n" +" msg, ancdata, flags, addr = sock.recvmsg(msglen, socket.CMSG_LEN(maxfds " +"* fds.itemsize))\n" +" for cmsg_level, cmsg_type, cmsg_data in ancdata:\n" +" if cmsg_level == socket.SOL_SOCKET and cmsg_type == socket." +"SCM_RIGHTS:\n" +" # Append data, ignoring any truncated integers at the end.\n" +" fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds." +"itemsize)])\n" +" return msg, list(fds)" +msgstr "" + +#: ../../library/socket.rst:1760 msgid "" "Receive normal data and ancillary data from the socket, behaving as :meth:" "`recvmsg` would, but scatter the non-ancillary data into a series of buffers " @@ -1992,7 +2024,7 @@ msgid "" "arguments have the same meaning as for :meth:`recvmsg`." msgstr "" -#: ../../library/socket.rst:1733 +#: ../../library/socket.rst:1771 msgid "" "The return value is a 4-tuple: ``(nbytes, ancdata, msg_flags, address)``, " "where *nbytes* is the total number of bytes of non-ancillary data written " @@ -2000,11 +2032,26 @@ msgid "" "for :meth:`recvmsg`." msgstr "" -#: ../../library/socket.rst:1738 +#: ../../library/socket.rst:1776 msgid "Example::" msgstr "Exemplo::" -#: ../../library/socket.rst:1761 +#: ../../library/socket.rst:1778 +msgid "" +">>> import socket\n" +">>> s1, s2 = socket.socketpair()\n" +">>> b1 = bytearray(b'----')\n" +">>> b2 = bytearray(b'0123456789')\n" +">>> b3 = bytearray(b'--------------')\n" +">>> s1.send(b'Mary had a little lamb')\n" +"22\n" +">>> s2.recvmsg_into([b1, memoryview(b2)[2:9], b3])\n" +"(22, [], 0, None)\n" +">>> [b1, b2, b3]\n" +"[bytearray(b'Mary'), bytearray(b'01 had a 9'), bytearray(b'little lamb---')]" +msgstr "" + +#: ../../library/socket.rst:1799 msgid "" "Receive data from the socket, writing it into *buffer* instead of creating a " "new bytestring. The return value is a pair ``(nbytes, address)`` where " @@ -2014,7 +2061,7 @@ msgid "" "format of *address* depends on the address family --- see above.)" msgstr "" -#: ../../library/socket.rst:1771 +#: ../../library/socket.rst:1809 msgid "" "Receive up to *nbytes* bytes from the socket, storing the data into a buffer " "rather than creating a new bytestring. If *nbytes* is not specified (or 0), " @@ -2023,7 +2070,7 @@ msgid "" "of the optional argument *flags*; it defaults to zero." msgstr "" -#: ../../library/socket.rst:1780 +#: ../../library/socket.rst:1818 msgid "" "Send data to the socket. The socket must be connected to a remote socket. " "The optional *flags* argument has the same meaning as for :meth:`recv` " @@ -2033,7 +2080,7 @@ msgid "" "data. For further information on this topic, consult the :ref:`socket-howto`." msgstr "" -#: ../../library/socket.rst:1795 +#: ../../library/socket.rst:1833 msgid "" "Send data to the socket. The socket must be connected to a remote socket. " "The optional *flags* argument has the same meaning as for :meth:`recv` " @@ -2043,13 +2090,13 @@ msgid "" "to determine how much data, if any, was successfully sent." msgstr "" -#: ../../library/socket.rst:1802 +#: ../../library/socket.rst:1840 msgid "" "The socket timeout is no longer reset each time data is sent successfully. " "The socket timeout is now the maximum total duration to send all data." msgstr "" -#: ../../library/socket.rst:1815 +#: ../../library/socket.rst:1853 msgid "" "Send data to the socket. The socket should not be connected to a remote " "socket, since the destination socket is specified by *address*. The " @@ -2058,7 +2105,7 @@ msgid "" "address family --- see above.)" msgstr "" -#: ../../library/socket.rst:1821 +#: ../../library/socket.rst:1859 msgid "" "Raises an :ref:`auditing event ` ``socket.sendto`` with arguments " "``self``, ``address``." @@ -2066,7 +2113,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``socket.sendto`` com os " "argumentos ``self``, ``address``." -#: ../../library/socket.rst:1831 +#: ../../library/socket.rst:1869 msgid "" "Send normal and ancillary data to the socket, gathering the non-ancillary " "data from a series of buffers and concatenating it into a single message. " @@ -2086,14 +2133,23 @@ msgid "" "bytes of non-ancillary data sent." msgstr "" -#: ../../library/socket.rst:1851 +#: ../../library/socket.rst:1889 msgid "" "The following function sends the list of file descriptors *fds* over an :" "const:`AF_UNIX` socket, on systems which support the :const:`SCM_RIGHTS` " "mechanism. See also :meth:`recvmsg`. ::" msgstr "" -#: ../../library/socket.rst:1864 +#: ../../library/socket.rst:1893 +msgid "" +"import socket, array\n" +"\n" +"def send_fds(sock, msg, fds):\n" +" return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array." +"array(\"i\", fds))])" +msgstr "" + +#: ../../library/socket.rst:1902 msgid "" "Raises an :ref:`auditing event ` ``socket.sendmsg`` with arguments " "``self``, ``address``." @@ -2101,14 +2157,14 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``socket.sendmsg`` com os " "argumentos ``self``, ``address``." -#: ../../library/socket.rst:1875 +#: ../../library/socket.rst:1913 msgid "" "Specialized version of :meth:`~socket.sendmsg` for :const:`AF_ALG` socket. " "Set mode, IV, AEAD associated data length and flags for :const:`AF_ALG` " "socket." msgstr "" -#: ../../library/socket.rst:1884 +#: ../../library/socket.rst:1922 msgid "" "Send a file until EOF is reached by using high-performance :mod:`os." "sendfile` and return the total number of bytes which were sent. *file* must " @@ -2122,38 +2178,38 @@ msgid "" "be of :const:`SOCK_STREAM` type. Non-blocking sockets are not supported." msgstr "" -#: ../../library/socket.rst:1900 +#: ../../library/socket.rst:1938 msgid "" "Set the :ref:`inheritable flag ` of the socket's file " "descriptor or socket's handle." msgstr "" -#: ../../library/socket.rst:1908 +#: ../../library/socket.rst:1946 msgid "" "Set blocking or non-blocking mode of the socket: if *flag* is false, the " "socket is set to non-blocking, else to blocking mode." msgstr "" -#: ../../library/socket.rst:1911 +#: ../../library/socket.rst:1949 msgid "" "This method is a shorthand for certain :meth:`~socket.settimeout` calls:" msgstr "" -#: ../../library/socket.rst:1913 +#: ../../library/socket.rst:1951 msgid "``sock.setblocking(True)`` is equivalent to ``sock.settimeout(None)``" msgstr "" -#: ../../library/socket.rst:1915 +#: ../../library/socket.rst:1953 msgid "``sock.setblocking(False)`` is equivalent to ``sock.settimeout(0.0)``" msgstr "" -#: ../../library/socket.rst:1917 +#: ../../library/socket.rst:1955 msgid "" "The method no longer applies :const:`SOCK_NONBLOCK` flag on :attr:`socket." "type`." msgstr "" -#: ../../library/socket.rst:1924 +#: ../../library/socket.rst:1962 msgid "" "Set a timeout on blocking socket operations. The *value* argument can be a " "nonnegative floating-point number expressing seconds, or ``None``. If a non-" @@ -2163,19 +2219,19 @@ msgid "" "blocking mode. If ``None`` is given, the socket is put in blocking mode." msgstr "" -#: ../../library/socket.rst:1931 +#: ../../library/socket.rst:1969 msgid "" "For further information, please consult the :ref:`notes on socket timeouts " "`." msgstr "" -#: ../../library/socket.rst:1933 +#: ../../library/socket.rst:1971 msgid "" "The method no longer toggles :const:`SOCK_NONBLOCK` flag on :attr:`socket." "type`." msgstr "" -#: ../../library/socket.rst:1946 +#: ../../library/socket.rst:1984 msgid "" "Set the value of the given socket option (see the Unix manual page :manpage:" "`setsockopt(2)`). The needed symbolic constants are defined in this module " @@ -2188,11 +2244,11 @@ msgid "" "C function with ``optval=NULL`` and ``optlen=optlen``." msgstr "" -#: ../../library/socket.rst:1959 +#: ../../library/socket.rst:1997 msgid "setsockopt(level, optname, None, optlen: int) form added." msgstr "" -#: ../../library/socket.rst:1967 +#: ../../library/socket.rst:2005 msgid "" "Shut down one or both halves of the connection. If *how* is :const:" "`SHUT_RD`, further receives are disallowed. If *how* is :const:`SHUT_WR`, " @@ -2200,7 +2256,7 @@ msgid "" "and receives are disallowed." msgstr "" -#: ../../library/socket.rst:1977 +#: ../../library/socket.rst:2015 msgid "" "Duplicate a socket and prepare it for sharing with a target process. The " "target process must be provided with *process_id*. The resulting bytes " @@ -2211,35 +2267,35 @@ msgid "" "process." msgstr "" -#: ../../library/socket.rst:1989 +#: ../../library/socket.rst:2027 msgid "" "Note that there are no methods :meth:`read` or :meth:`write`; use :meth:" "`~socket.recv` and :meth:`~socket.send` without *flags* argument instead." msgstr "" -#: ../../library/socket.rst:1992 +#: ../../library/socket.rst:2030 msgid "" "Socket objects also have these (read-only) attributes that correspond to the " "values given to the :class:`~socket.socket` constructor." msgstr "" -#: ../../library/socket.rst:1998 +#: ../../library/socket.rst:2036 msgid "The socket family." msgstr "" -#: ../../library/socket.rst:2003 +#: ../../library/socket.rst:2041 msgid "The socket type." msgstr "" -#: ../../library/socket.rst:2008 +#: ../../library/socket.rst:2046 msgid "The socket protocol." msgstr "" -#: ../../library/socket.rst:2015 +#: ../../library/socket.rst:2053 msgid "Notes on socket timeouts" msgstr "Notas sobre tempo limite de soquete" -#: ../../library/socket.rst:2017 +#: ../../library/socket.rst:2055 msgid "" "A socket object can be in one of three modes: blocking, non-blocking, or " "timeout. Sockets are by default always created in blocking mode, but this " @@ -2249,13 +2305,13 @@ msgstr "" "tempo limite. Por padrão, os soquetes sempre são criados no modo de " "bloqueio, mas isso pode ser alterado chamando :func:`setdefaulttimeout`." -#: ../../library/socket.rst:2021 +#: ../../library/socket.rst:2059 msgid "" "In *blocking mode*, operations block until complete or the system returns an " "error (such as connection timed out)." msgstr "" -#: ../../library/socket.rst:2024 +#: ../../library/socket.rst:2062 msgid "" "In *non-blocking mode*, operations fail (with an error that is unfortunately " "system-dependent) if they cannot be completed immediately: functions from " @@ -2263,27 +2319,27 @@ msgid "" "available for reading or writing." msgstr "" -#: ../../library/socket.rst:2029 +#: ../../library/socket.rst:2067 msgid "" "In *timeout mode*, operations fail if they cannot be completed within the " "timeout specified for the socket (they raise a :exc:`timeout` exception) or " "if the system returns an error." msgstr "" -#: ../../library/socket.rst:2034 +#: ../../library/socket.rst:2072 msgid "" "At the operating system level, sockets in *timeout mode* are internally set " "in non-blocking mode. Also, the blocking and timeout modes are shared " "between file descriptors and socket objects that refer to the same network " "endpoint. This implementation detail can have visible consequences if e.g. " -"you decide to use the :meth:`~socket.fileno()` of a socket." +"you decide to use the :meth:`~socket.fileno` of a socket." msgstr "" -#: ../../library/socket.rst:2041 +#: ../../library/socket.rst:2079 msgid "Timeouts and the ``connect`` method" msgstr "" -#: ../../library/socket.rst:2043 +#: ../../library/socket.rst:2081 msgid "" "The :meth:`~socket.connect` operation is also subject to the timeout " "setting, and in general it is recommended to call :meth:`~socket.settimeout` " @@ -2293,24 +2349,24 @@ msgid "" "setting." msgstr "" -#: ../../library/socket.rst:2051 +#: ../../library/socket.rst:2089 msgid "Timeouts and the ``accept`` method" msgstr "" -#: ../../library/socket.rst:2053 +#: ../../library/socket.rst:2091 msgid "" "If :func:`getdefaulttimeout` is not :const:`None`, sockets returned by the :" "meth:`~socket.accept` method inherit that timeout. Otherwise, the behaviour " "depends on settings of the listening socket:" msgstr "" -#: ../../library/socket.rst:2057 +#: ../../library/socket.rst:2095 msgid "" "if the listening socket is in *blocking mode* or in *timeout mode*, the " "socket returned by :meth:`~socket.accept` is in *blocking mode*;" msgstr "" -#: ../../library/socket.rst:2060 +#: ../../library/socket.rst:2098 msgid "" "if the listening socket is in *non-blocking mode*, whether the socket " "returned by :meth:`~socket.accept` is in blocking or non-blocking mode is " @@ -2318,11 +2374,11 @@ msgid "" "it is recommended you manually override this setting." msgstr "" -#: ../../library/socket.rst:2069 +#: ../../library/socket.rst:2107 msgid "Example" msgstr "Exemplo" -#: ../../library/socket.rst:2071 +#: ../../library/socket.rst:2109 msgid "" "Here are four minimal example programs using the TCP/IP protocol: a server " "that echoes all data that it receives back (servicing only one client), and " @@ -2335,11 +2391,44 @@ msgid "" "on the new socket returned by :meth:`~socket.accept`." msgstr "" -#: ../../library/socket.rst:2081 +#: ../../library/socket.rst:2119 msgid "The first two examples support IPv4 only. ::" msgstr "" -#: ../../library/socket.rst:2112 +#: ../../library/socket.rst:2121 +msgid "" +"# Echo server program\n" +"import socket\n" +"\n" +"HOST = '' # Symbolic name meaning all available interfaces\n" +"PORT = 50007 # Arbitrary non-privileged port\n" +"with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n" +" s.bind((HOST, PORT))\n" +" s.listen(1)\n" +" conn, addr = s.accept()\n" +" with conn:\n" +" print('Connected by', addr)\n" +" while True:\n" +" data = conn.recv(1024)\n" +" if not data: break\n" +" conn.sendall(data)" +msgstr "" + +#: ../../library/socket.rst:2139 +msgid "" +"# Echo client program\n" +"import socket\n" +"\n" +"HOST = 'daring.cwi.nl' # The remote host\n" +"PORT = 50007 # The same port as used by the server\n" +"with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n" +" s.connect((HOST, PORT))\n" +" s.sendall(b'Hello, world')\n" +" data = s.recv(1024)\n" +"print('Received', repr(data))" +msgstr "" + +#: ../../library/socket.rst:2150 msgid "" "The next two examples are identical to the above two, but support both IPv4 " "and IPv6. The server side will listen to the first address family available " @@ -2349,75 +2438,226 @@ msgid "" "resolution, and sends traffic to the first one connected successfully. ::" msgstr "" -#: ../../library/socket.rst:2184 +#: ../../library/socket.rst:2157 +msgid "" +"# Echo server program\n" +"import socket\n" +"import sys\n" +"\n" +"HOST = None # Symbolic name meaning all available interfaces\n" +"PORT = 50007 # Arbitrary non-privileged port\n" +"s = None\n" +"for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,\n" +" socket.SOCK_STREAM, 0, socket.AI_PASSIVE):\n" +" af, socktype, proto, canonname, sa = res\n" +" try:\n" +" s = socket.socket(af, socktype, proto)\n" +" except OSError as msg:\n" +" s = None\n" +" continue\n" +" try:\n" +" s.bind(sa)\n" +" s.listen(1)\n" +" except OSError as msg:\n" +" s.close()\n" +" s = None\n" +" continue\n" +" break\n" +"if s is None:\n" +" print('could not open socket')\n" +" sys.exit(1)\n" +"conn, addr = s.accept()\n" +"with conn:\n" +" print('Connected by', addr)\n" +" while True:\n" +" data = conn.recv(1024)\n" +" if not data: break\n" +" conn.send(data)" +msgstr "" + +#: ../../library/socket.rst:2193 +msgid "" +"# Echo client program\n" +"import socket\n" +"import sys\n" +"\n" +"HOST = 'daring.cwi.nl' # The remote host\n" +"PORT = 50007 # The same port as used by the server\n" +"s = None\n" +"for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket." +"SOCK_STREAM):\n" +" af, socktype, proto, canonname, sa = res\n" +" try:\n" +" s = socket.socket(af, socktype, proto)\n" +" except OSError as msg:\n" +" s = None\n" +" continue\n" +" try:\n" +" s.connect(sa)\n" +" except OSError as msg:\n" +" s.close()\n" +" s = None\n" +" continue\n" +" break\n" +"if s is None:\n" +" print('could not open socket')\n" +" sys.exit(1)\n" +"with s:\n" +" s.sendall(b'Hello, world')\n" +" data = s.recv(1024)\n" +"print('Received', repr(data))" +msgstr "" + +#: ../../library/socket.rst:2222 msgid "" "The next example shows how to write a very simple network sniffer with raw " "sockets on Windows. The example requires administrator privileges to modify " "the interface::" msgstr "" -#: ../../library/socket.rst:2209 +#: ../../library/socket.rst:2226 +msgid "" +"import socket\n" +"\n" +"# the public network interface\n" +"HOST = socket.gethostbyname(socket.gethostname())\n" +"\n" +"# create a raw socket and bind it to the public interface\n" +"s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)\n" +"s.bind((HOST, 0))\n" +"\n" +"# Include IP headers\n" +"s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)\n" +"\n" +"# receive all packets\n" +"s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)\n" +"\n" +"# receive a packet\n" +"print(s.recvfrom(65565))\n" +"\n" +"# disabled promiscuous mode\n" +"s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)" +msgstr "" + +#: ../../library/socket.rst:2247 msgid "" "The next example shows how to use the socket interface to communicate to a " "CAN network using the raw socket protocol. To use CAN with the broadcast " "manager protocol instead, open a socket with::" msgstr "" -#: ../../library/socket.rst:2215 +#: ../../library/socket.rst:2251 +msgid "socket.socket(socket.AF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM)" +msgstr "" + +#: ../../library/socket.rst:2253 msgid "" "After binding (:const:`CAN_RAW`) or connecting (:const:`CAN_BCM`) the " "socket, you can use the :meth:`socket.send` and :meth:`socket.recv` " "operations (and their counterparts) on the socket object as usual." msgstr "" -#: ../../library/socket.rst:2219 +#: ../../library/socket.rst:2257 msgid "This last example might require special privileges::" msgstr "" #: ../../library/socket.rst:2259 msgid "" +"import socket\n" +"import struct\n" +"\n" +"\n" +"# CAN frame packing/unpacking (see 'struct can_frame' in )\n" +"\n" +"can_frame_fmt = \"=IB3x8s\"\n" +"can_frame_size = struct.calcsize(can_frame_fmt)\n" +"\n" +"def build_can_frame(can_id, data):\n" +" can_dlc = len(data)\n" +" data = data.ljust(8, b'\\x00')\n" +" return struct.pack(can_frame_fmt, can_id, can_dlc, data)\n" +"\n" +"def dissect_can_frame(frame):\n" +" can_id, can_dlc, data = struct.unpack(can_frame_fmt, frame)\n" +" return (can_id, can_dlc, data[:can_dlc])\n" +"\n" +"\n" +"# create a raw socket and bind it to the 'vcan0' interface\n" +"s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)\n" +"s.bind(('vcan0',))\n" +"\n" +"while True:\n" +" cf, addr = s.recvfrom(can_frame_size)\n" +"\n" +" print('Received: can_id=%x, can_dlc=%x, data=%s' % " +"dissect_can_frame(cf))\n" +"\n" +" try:\n" +" s.send(cf)\n" +" except OSError:\n" +" print('Error sending CAN frame')\n" +"\n" +" try:\n" +" s.send(build_can_frame(0x01, b'\\x01\\x02\\x03'))\n" +" except OSError:\n" +" print('Error sending CAN frame')" +msgstr "" + +#: ../../library/socket.rst:2297 +msgid "" "Running an example several times with too small delay between executions, " "could lead to this error::" msgstr "" -#: ../../library/socket.rst:2264 +#: ../../library/socket.rst:2300 +msgid "OSError: [Errno 98] Address already in use" +msgstr "" + +#: ../../library/socket.rst:2302 msgid "" "This is because the previous execution has left the socket in a " "``TIME_WAIT`` state, and can't be immediately reused." msgstr "" -#: ../../library/socket.rst:2267 +#: ../../library/socket.rst:2305 msgid "" "There is a :mod:`socket` flag to set, in order to prevent this, :const:" "`socket.SO_REUSEADDR`::" msgstr "" -#: ../../library/socket.rst:2274 +#: ../../library/socket.rst:2308 +msgid "" +"s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" +"s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n" +"s.bind((HOST, PORT))" +msgstr "" + +#: ../../library/socket.rst:2312 msgid "" "the :data:`SO_REUSEADDR` flag tells the kernel to reuse a local socket in " "``TIME_WAIT`` state, without waiting for its natural timeout to expire." msgstr "" -#: ../../library/socket.rst:2280 +#: ../../library/socket.rst:2318 msgid "" "For an introduction to socket programming (in C), see the following papers:" msgstr "" "Para uma introdução à programação de socket (em C), veja os seguintes " "artigos:" -#: ../../library/socket.rst:2282 +#: ../../library/socket.rst:2320 msgid "" "*An Introductory 4.3BSD Interprocess Communication Tutorial*, by Stuart " "Sechrest" msgstr "" -#: ../../library/socket.rst:2284 +#: ../../library/socket.rst:2322 msgid "" "*An Advanced 4.3BSD Interprocess Communication Tutorial*, by Samuel J. " "Leffler et al," msgstr "" -#: ../../library/socket.rst:2287 +#: ../../library/socket.rst:2325 msgid "" "both in the UNIX Programmer's Manual, Supplementary Documents 1 (sections " "PS1:7 and PS1:8). The platform-specific reference material for the various " @@ -2436,18 +2676,18 @@ msgstr "objeto" msgid "socket" msgstr "socket" -#: ../../library/socket.rst:1587 +#: ../../library/socket.rst:1630 msgid "I/O control" msgstr "controle de E/S" -#: ../../library/socket.rst:1587 +#: ../../library/socket.rst:1630 msgid "buffering" msgstr "buffering" -#: ../../library/socket.rst:1944 +#: ../../library/socket.rst:1982 msgid "module" msgstr "módulo" -#: ../../library/socket.rst:1944 +#: ../../library/socket.rst:1982 msgid "struct" msgstr "struct" diff --git a/library/socketserver.po b/library/socketserver.po index 4440251d9..5fee56e41 100644 --- a/library/socketserver.po +++ b/library/socketserver.po @@ -1,35 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Sheila Gomes , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:13+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-14 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/socketserver.rst:2 msgid ":mod:`!socketserver` --- A framework for network servers" -msgstr "" +msgstr ":mod:`!socketserver` --- Um framework para servidores de rede" #: ../../library/socketserver.rst:7 msgid "**Source code:** :source:`Lib/socketserver.py`" @@ -40,10 +36,12 @@ msgid "" "The :mod:`socketserver` module simplifies the task of writing network " "servers." msgstr "" +"O módulo :mod:`socketserver` simplifica a tarefa de escrever servidores de " +"rede." #: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +msgid "Availability" +msgstr "Disponibilidade" #: ../../includes/wasm-notavail.rst:5 msgid "" @@ -55,7 +53,7 @@ msgstr "" #: ../../library/socketserver.rst:15 msgid "There are four basic concrete server classes:" -msgstr "" +msgstr "Existem quatro classes básicas de servidores concretos:" #: ../../library/socketserver.rst:20 msgid "" @@ -65,6 +63,11 @@ msgid "" "and :meth:`~BaseServer.server_activate`. The other parameters are passed to " "the :class:`BaseServer` base class." msgstr "" +"Isso usa o protocolo TCP da internet, que fornece fluxos contínuos de dados " +"entre o cliente e o servidor. Se *bind_and_activate* for true, o construtor " +"tenta automaticamente invocar :meth:`~BaseServer.server_bind` e :meth:" +"`~BaseServer.server_activate`. Os outros parâmetros são passados para a " +"classe base :class:`BaseServer`." #: ../../library/socketserver.rst:30 msgid "" @@ -72,6 +75,9 @@ msgid "" "arrive out of order or be lost while in transit. The parameters are the " "same as for :class:`TCPServer`." msgstr "" +"Isso usa datagramas, que são pacotes discretos de informações que podem " +"chegar fora de ordem ou ser perdidos durante o trânsito. Os parâmetros são " +"os mesmos de :class:`TCPServer`." #: ../../library/socketserver.rst:38 msgid "" @@ -79,6 +85,9 @@ msgid "" "but use Unix domain sockets; they're not available on non-Unix platforms. " "The parameters are the same as for :class:`TCPServer`." msgstr "" +"Essas classes usadas com menos frequência são semelhantes às classes TCP e " +"UDP, mas usam soquetes de domínio Unix; elas não estão disponíveis em " +"plataformas não Unix. Os parâmetros são os mesmos de :class:`TCPServer`." #: ../../library/socketserver.rst:44 msgid "" @@ -112,6 +121,17 @@ msgid "" "meth:`~BaseServer.server_close` to close the socket (unless you used a :" "keyword:`!with` statement)." msgstr "" +"Criar um servidor requer várias etapas. Primeiro, você deve criar uma classe " +"de manipulador de solicitação estendendo a classe :class:" +"`BaseRequestHandler` e substituindo seu método :meth:`~BaseRequestHandler." +"handle`; esse método processará as solicitações recebidas. Segundo, você " +"deve instanciar uma das classes de servidor, passando a ela o endereço do " +"servidor e a classe de manipulador de solicitação. É recomendável usar o " +"servidor em uma instrução :keyword:`with`. Em seguida, chame o método :meth:" +"`~BaseServer.handle_request` ou :meth:`~BaseServer.serve_forever` do objeto " +"do servidor para processar uma ou muitas solicitações. Finalmente, chame :" +"meth:`~BaseServer.server_close` para fechar o soquete (a menos que você " +"tenha usado uma instrução :keyword:`!with`)." #: ../../library/socketserver.rst:64 msgid "" @@ -124,22 +144,64 @@ msgid "" "meaning that Python will not exit until all threads created by :class:" "`ThreadingMixIn` have exited." msgstr "" +"Ao herdar de :class:`ThreadingMixIn` para comportamento de conexão em " +"threads, você deve declarar explicitamente como quer que suas threads se " +"comportem em um desligamento abrupto. A classe :class:`ThreadingMixIn` " +"define um atributo *daemon_threads*, que indica se o servidor deve ou não " +"esperar pelo término da thread. Você deve definir o sinalizador " +"explicitamente se quiser que as threads se comportem de forma autônoma; o " +"padrão é :const:`False`, o que significa que o Python não sairá até que " +"todas as threads criadas por :class:`ThreadingMixIn` tenham sido encerradas." #: ../../library/socketserver.rst:73 msgid "" "Server classes have the same external methods and attributes, no matter what " "network protocol they use." msgstr "" +"As classes de servidor têm os mesmos métodos e atributos externos, não " +"importa qual protocolo de rede eles usam." #: ../../library/socketserver.rst:78 msgid "Server Creation Notes" -msgstr "" +msgstr "Notas sobre criação do servidor" #: ../../library/socketserver.rst:80 msgid "" "There are five classes in an inheritance diagram, four of which represent " "synchronous servers of four types::" msgstr "" +"Existem cinco classes em um diagrama de herança, quatro das quais " +"representam servidores síncronos de quatro tipos:" + +#: ../../library/socketserver.rst:83 +msgid "" +"+------------+\n" +"| BaseServer |\n" +"+------------+\n" +" |\n" +" v\n" +"+-----------+ +------------------+\n" +"| TCPServer |------->| UnixStreamServer |\n" +"+-----------+ +------------------+\n" +" |\n" +" v\n" +"+-----------+ +--------------------+\n" +"| UDPServer |------->| UnixDatagramServer |\n" +"+-----------+ +--------------------+" +msgstr "" +"+------------+\n" +"| BaseServer |\n" +"+------------+\n" +" |\n" +" v\n" +"+-----------+ +------------------+\n" +"| TCPServer |------->| UnixStreamServer |\n" +"+-----------+ +------------------+\n" +" |\n" +" v\n" +"+-----------+ +--------------------+\n" +"| UDPServer |------->| UnixDatagramServer |\n" +"+-----------+ +--------------------+" #: ../../library/socketserver.rst:97 msgid "" @@ -147,6 +209,9 @@ msgid "" "from :class:`UnixStreamServer` --- the only difference between an IP and a " "Unix server is the address family." msgstr "" +"Observe que :class:`UnixDatagramServer` deriva de :class:`UDPServer`, não " +"de :class:`UnixStreamServer` --- a única diferença entre um IP e um servidor " +"Unix é a família de endereços." #: ../../library/socketserver.rst:105 msgid "" @@ -154,6 +219,17 @@ msgid "" "these mix-in classes. For instance, :class:`ThreadingUDPServer` is created " "as follows::" msgstr "" +"Versões de fork e threads de cada tipo de servidor podem ser criadas usando " +"essas classes mix-in. Por exemplo, :class:`ThreadingUDPServer` é criado da " +"seguinte forma::" + +#: ../../library/socketserver.rst:109 +msgid "" +"class ThreadingUDPServer(ThreadingMixIn, UDPServer):\n" +" pass" +msgstr "" +"class ThreadingUDPServer(ThreadingMixIn, UDPServer):\n" +" pass" #: ../../library/socketserver.rst:112 msgid "" @@ -161,12 +237,18 @@ msgid "" "`UDPServer`. Setting the various attributes also changes the behavior of " "the underlying server mechanism." msgstr "" +"A classe mix-in vem primeiro, pois ela substitui um método definido em :" +"class:`UDPServer`. Definir os vários atributos também altera o comportamento " +"do mecanismo de servidor subjacente." #: ../../library/socketserver.rst:116 msgid "" ":class:`ForkingMixIn` and the Forking classes mentioned below are only " "available on POSIX platforms that support :func:`~os.fork`." msgstr "" +":class:`ForkingMixIn` e as classes Forking mencionadas abaixo estão " +"disponíveis apenas em plataformas POSIX que oferecem suporte a :func:`~os." +"fork`." #: ../../library/socketserver.rst:121 msgid "" @@ -174,6 +256,9 @@ msgid "" "child processes complete, except if :attr:`block_on_close` attribute is " "``False``." msgstr "" +":meth:`ForkingMixIn.server_close ` aguarda até que " +"todos os processos filho sejam concluídos, exceto se o atributo :attr:" +"`block_on_close` for ``False``." #: ../../library/socketserver.rst:125 msgid "" @@ -181,6 +266,9 @@ msgid "" "all non-daemon threads complete, except if :attr:`block_on_close` attribute " "is ``False``." msgstr "" +":meth:`ThreadingMixIn.server_close ` aguarda até " +"que todos as threads não daemon sejam concluídos, exceto se o atributo :attr:" +"`block_on_close` for ``False``." #: ../../library/socketserver.rst:131 msgid "" @@ -188,6 +276,9 @@ msgid "" "`ThreadingMixIn.daemon_threads ` to ``True`` to not wait " "until threads complete." msgstr "" +"Para :class:`ThreadingMixIn`, use threads como daemon definindo :data:" +"`ThreadingMixIn.daemon_threads ` como ``True`` para não " +"esperar até que as threads sejam concluídas." #: ../../library/socketserver.rst:137 msgid "" @@ -197,16 +288,23 @@ msgid "" "`ForkingMixIn.block_on_close ` class attribute to opt-in for " "the pre-3.7 behaviour." msgstr "" +":meth:`ForkingMixIn.server_close ` e :meth:" +"`ThreadingMixIn.server_close ` agora esperam até " +"que todos os processos filhos e threads não daemon sejam concluídos. " +"Adicione um novo atributo de classe :attr:`ForkingMixIn.block_on_close " +"` para optar pelo comportamento pré-3.7." #: ../../library/socketserver.rst:153 msgid "These classes are pre-defined using the mix-in classes." -msgstr "" +msgstr "Essas classes são predefinidas usando as classes mix-in." #: ../../library/socketserver.rst:155 msgid "" "The ``ForkingUnixStreamServer`` and ``ForkingUnixDatagramServer`` classes " "were added." msgstr "" +"As classes ``ForkingUnixStreamServer`` e ``ForkingUnixDatagramServer`` foram " +"adicionadas." #: ../../library/socketserver.rst:159 msgid "" @@ -218,6 +316,13 @@ msgid "" "by using the handler subclasses :class:`StreamRequestHandler` or :class:" "`DatagramRequestHandler`." msgstr "" +"Para implementar um serviço, você deve derivar uma classe de :class:" +"`BaseRequestHandler` e redefinir seu método :meth:`~BaseRequestHandler." +"handle`. Você pode então executar várias versões do serviço combinando uma " +"das classes de servidor com sua classe de manipulador de solicitação. A " +"classe de manipulador de solicitação deve ser diferente para serviços de " +"datagrama ou fluxo. Isso pode ser ocultado usando as subclasses de " +"manipulador :class:`StreamRequestHandler` ou :class:`DatagramRequestHandler`." #: ../../library/socketserver.rst:167 msgid "" @@ -228,6 +333,13 @@ msgid "" "each child. In this case, you can use a threading server, but you will " "probably have to use locks to protect the integrity of the shared data." msgstr "" +"Claro, você ainda tem que usar sua cabeça! Por exemplo, não faz sentido usar " +"um servidor de Forking se o serviço contém estado na memória que pode ser " +"modificado por diferentes solicitações, já que as modificações no processo " +"filho nunca atingiriam o estado inicial mantido no processo pai e passado " +"para cada filho. Neste caso, você pode usar um servidor de Threading, mas " +"provavelmente terá que usar travas para proteger a integridade dos dados " +"compartilhados." #: ../../library/socketserver.rst:174 msgid "" @@ -238,6 +350,12 @@ msgid "" "all the data it has requested. Here a threading or forking server is " "appropriate." msgstr "" +"Por outro lado, se você estiver construindo um servidor HTTP onde todos os " +"dados são armazenados externamente (por exemplo, no sistema de arquivos), " +"uma classe síncrona essencialmente tornará o serviço \"surdo\" enquanto uma " +"solicitação estiver sendo manipulada -- o que pode ser por um tempo muito " +"longo se um cliente for lento para receber todos os dados que solicitou. " +"Aqui, um servidor de Threading ou Forking é apropriado." #: ../../library/socketserver.rst:180 msgid "" @@ -247,6 +365,11 @@ msgid "" "doing an explicit fork in the request handler class :meth:" "`~BaseRequestHandler.handle` method." msgstr "" +"Em alguns casos, pode ser apropriado processar parte de uma solicitação de " +"forma síncrona, mas terminar o processamento em um filho bifurcado " +"dependendo dos dados da solicitação. Isso pode ser implementado usando um " +"servidor síncrono e fazendo uma bifurcação explícita no método da classe do " +"manipulador de solicitações :meth:`~BaseRequestHandler.handle`." #: ../../library/socketserver.rst:185 msgid "" @@ -259,6 +382,14 @@ msgid "" "client can potentially be connected for a long time (if threads or " "subprocesses cannot be used)." msgstr "" +"Outra abordagem para lidar com múltiplas requisições simultâneas em um " +"ambiente que não oferece suporte a threads nem :func:`~os.fork` (ou onde " +"estes são muito caros ou inapropriados para o serviço) é manter uma tabela " +"explícita de requisições parcialmente finalizadas e usar :mod:`selectors` " +"para decidir em qual requisição trabalhar em seguida (ou se deve lidar com " +"uma nova requisição recebida). Isto é particularmente importante para " +"serviços de fluxo onde cada cliente pode potencialmente ficar conectado por " +"um longo tempo (se threads ou subprocessos não puderem ser usados)." #: ../../library/socketserver.rst:198 msgid "Server Objects" @@ -271,6 +402,10 @@ msgid "" "done in subclasses. The two parameters are stored in the respective :attr:" "`server_address` and :attr:`RequestHandlerClass` attributes." msgstr "" +"Esta é a superclasse de todos os objetos Server no módulo. Ela define a " +"interface, dada abaixo, mas não implementa a maioria dos métodos, o que é " +"feito em subclasses. Os dois parâmetros são armazenados nos respectivos " +"atributos :attr:`server_address` e :attr:`RequestHandlerClass`." #: ../../library/socketserver.rst:210 msgid "" @@ -278,6 +413,9 @@ msgid "" "listening. This function is most commonly passed to :mod:`selectors`, to " "allow monitoring multiple servers in the same process." msgstr "" +"Retorna um descritor de arquivo inteiro para o soquete no qual o servidor " +"está escutando. Esta função é mais comumente passada para :mod:`selectors`, " +"para permitir o monitoramento de múltiplos servidores no mesmo processo." #: ../../library/socketserver.rst:217 msgid "" @@ -289,6 +427,13 @@ msgid "" "attr:`timeout` seconds, :meth:`handle_timeout` will be called and :meth:" "`handle_request` will return." msgstr "" +"Processa uma única solicitação. Esta função chama os seguintes métodos em " +"ordem: :meth:`get_request`, :meth:`verify_request` e :meth:" +"`process_request`. Se o método :meth:`~BaseRequestHandler.handle` fornecido " +"pelo usuário da classe manipuladora levantar uma exceção, o método :meth:" +"`handle_error` do servidor será chamado. Se nenhuma solicitação for recebida " +"dentro de :attr:`timeout` segundos, :meth:`handle_timeout` será chamado e :" +"meth:`handle_request` retornará." #: ../../library/socketserver.rst:229 msgid "" @@ -299,10 +444,16 @@ msgid "" "example, the :class:`ForkingMixIn` class uses :meth:`service_actions` to " "clean up zombie child processes." msgstr "" +"Manipula solicitações até uma solicitação explícita :meth:`shutdown`. Sonda " +"para desligamento a cada *poll_interval* segundos. Ignora o atributo :attr:" +"`timeout`. Ele também chama :meth:`service_actions`, que pode ser usado por " +"uma subclasse ou mixin para fornecer ações específicas para um determinado " +"serviço. Por exemplo, a classe :class:`ForkingMixIn` usa :meth:" +"`service_actions` para limpar processos filhos zumbis." #: ../../library/socketserver.rst:237 msgid "Added ``service_actions`` call to the ``serve_forever`` method." -msgstr "" +msgstr "Adicionada chamada ``service_actions`` ao método ``serve_forever``." #: ../../library/socketserver.rst:243 msgid "" @@ -310,6 +461,9 @@ msgid "" "overridden by subclasses or mixin classes to perform actions specific to a " "given service, such as cleanup actions." msgstr "" +"Isso é chamado no laço :meth:`serve_forever`. Este método pode ser " +"substituído por subclasses ou classes mixin para executar ações específicas " +"para um determinado serviço, como ações de limpeza." #: ../../library/socketserver.rst:251 msgid "" @@ -317,24 +471,38 @@ msgid "" "`shutdown` must be called while :meth:`serve_forever` is running in a " "different thread otherwise it will deadlock." msgstr "" +"Diz ao laço :meth:`serve_forever` para parar e esperar até que isso " +"aconteça. :meth:`shutdown` deve ser chamado enquanto :meth:`serve_forever` " +"estiver em execução em um thread diferente, caso contrário, ocorrerá um " +"impasse." #: ../../library/socketserver.rst:258 msgid "Clean up the server. May be overridden." -msgstr "" +msgstr "Limpa o servidor. Pode ser substituído." #: ../../library/socketserver.rst:263 msgid "" -"The family of protocols to which the server's socket belongs. Common " -"examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`." +"The family of protocols to which the server's socket belongs. Common " +"examples are :const:`socket.AF_INET`, :const:`socket.AF_INET6`, and :const:" +"`socket.AF_UNIX`. Subclass the TCP or UDP server classes in this module " +"with class attribute ``address_family = AF_INET6`` set if you want IPv6 " +"server classes." msgstr "" +"A família de protocolos à qual o soquete do servidor pertence. Exemplos " +"comuns são :const:`socket.AF_INET`, :const:`socket.AF_INET6` e :const:" +"`socket.AF_UNIX`. Subclasse as classes de servidor TCP ou UDP neste módulo " +"com o atributo de classe ``address_family = AF_INET6`` definido se você " +"quiser classes de servidor IPv6." -#: ../../library/socketserver.rst:269 +#: ../../library/socketserver.rst:272 msgid "" "The user-provided request handler class; an instance of this class is " "created for each request." msgstr "" +"A classe de manipulador de solicitações fornecida pelo usuário; uma " +"instância dessa classe é criada para cada solicitação." -#: ../../library/socketserver.rst:275 +#: ../../library/socketserver.rst:278 msgid "" "The address on which the server is listening. The format of addresses " "varies depending on the protocol family; see the documentation for the :mod:" @@ -342,23 +510,31 @@ msgid "" "containing a string giving the address, and an integer port number: " "``('127.0.0.1', 80)``, for example." msgstr "" +"O endereço no qual o servidor está escutando. O formato dos endereços varia " +"dependendo da família do protocolo; veja a documentação do módulo :mod:" +"`socket` para detalhes. Para protocolos de internet, esta é uma tupla " +"contendo uma string dando o endereço e um número de porta inteiro: " +"``('127.0.0.1', 80)``, por exemplo." -#: ../../library/socketserver.rst:284 +#: ../../library/socketserver.rst:287 msgid "" "The socket object on which the server will listen for incoming requests." msgstr "O objeto soquete no qual o servidor ouve para solicitações recebidas." -#: ../../library/socketserver.rst:287 +#: ../../library/socketserver.rst:290 msgid "The server classes support the following class variables:" msgstr "" +"As classes de servidor oferecem suporte às seguintes variáveis de classe:" -#: ../../library/socketserver.rst:293 +#: ../../library/socketserver.rst:296 msgid "" "Whether the server will allow the reuse of an address. This defaults to :" "const:`False`, and can be set in subclasses to change the policy." msgstr "" +"Se o servidor permitirá a reutilização de um endereço. O padrão é :const:" +"`False`, e pode ser definido em subclasses para alterar a política." -#: ../../library/socketserver.rst:299 +#: ../../library/socketserver.rst:302 msgid "" "The size of the request queue. If it takes a long time to process a single " "request, any requests that arrive while the server is busy are placed into a " @@ -366,53 +542,78 @@ msgid "" "further requests from clients will get a \"Connection denied\" error. The " "default value is usually 5, but this can be overridden by subclasses." msgstr "" +"O tamanho da fila de requisições. Se levar muito tempo para processar uma " +"única requisição, todas as requisições que chegarem enquanto o servidor " +"estiver ocupado serão colocadas em uma fila, até :attr:`request_queue_size` " +"requisições. Quando a fila estiver cheia, outras requisições de clientes " +"receberão um erro \"Conexão negada\". O valor padrão é geralmente 5, mas " +"isso pode ser substituído por subclasses." -#: ../../library/socketserver.rst:308 +#: ../../library/socketserver.rst:311 msgid "" "The type of socket used by the server; :const:`socket.SOCK_STREAM` and :" "const:`socket.SOCK_DGRAM` are two common values." msgstr "" +"O tipo de soquete usado pelo servidor; :const:`socket.SOCK_STREAM` e :const:" +"`socket.SOCK_DGRAM` são dois valores comuns." -#: ../../library/socketserver.rst:314 +#: ../../library/socketserver.rst:317 msgid "" "Timeout duration, measured in seconds, or :const:`None` if no timeout is " "desired. If :meth:`handle_request` receives no incoming requests within the " "timeout period, the :meth:`handle_timeout` method is called." msgstr "" +"Duração do tempo limite, medida em segundos, ou :const:`None` se nenhum " +"tempo limite for desejado. Se :meth:`handle_request` não receber nenhuma " +"requisição de entrada dentro do período de tempo limite, o método :meth:" +"`handle_timeout` será chamado." -#: ../../library/socketserver.rst:319 +#: ../../library/socketserver.rst:322 msgid "" "There are various server methods that can be overridden by subclasses of " "base server classes like :class:`TCPServer`; these methods aren't useful to " "external users of the server object." msgstr "" +"Existem vários métodos de servidor que podem ser substituídos por subclasses " +"de classes de servidor base, como :class:`TCPServer`; esses métodos não são " +"úteis para usuários externos do objeto de servidor." -#: ../../library/socketserver.rst:328 +#: ../../library/socketserver.rst:331 msgid "" "Actually processes the request by instantiating :attr:`RequestHandlerClass` " "and calling its :meth:`~BaseRequestHandler.handle` method." msgstr "" +"Na verdade, processa a solicitação instanciando :attr:`RequestHandlerClass` " +"e chamando seu método :meth:`~BaseRequestHandler.handle`." -#: ../../library/socketserver.rst:334 +#: ../../library/socketserver.rst:337 msgid "" "Must accept a request from the socket, and return a 2-tuple containing the " "*new* socket object to be used to communicate with the client, and the " "client's address." msgstr "" +"Deve aceitar uma solicitação do soquete e retornar uma tupla de 2 elementos " +"contendo o *novo* objeto de soquete a ser usado para se comunicar com o " +"cliente e o endereço do cliente." -#: ../../library/socketserver.rst:341 +#: ../../library/socketserver.rst:344 msgid "" "This function is called if the :meth:`~BaseRequestHandler.handle` method of " "a :attr:`RequestHandlerClass` instance raises an exception. The default " "action is to print the traceback to standard error and continue handling " "further requests." msgstr "" +"Esta função é chamada se o método :meth:`~BaseRequestHandler.handle` de uma " +"instância :attr:`RequestHandlerClass` levanta uma exceção. A ação padrão é " +"exibir o traceback para erro padrão e continuar manipulando solicitações " +"futuras." -#: ../../library/socketserver.rst:346 +#: ../../library/socketserver.rst:349 msgid "Now only called for exceptions derived from the :exc:`Exception` class." msgstr "" +"Agora é chamada apenas para exceções derivadas da classe :exc:`Exception`." -#: ../../library/socketserver.rst:353 +#: ../../library/socketserver.rst:356 msgid "" "This function is called when the :attr:`timeout` attribute has been set to a " "value other than :const:`None` and the timeout period has passed with no " @@ -420,61 +621,88 @@ msgid "" "collect the status of any child processes that have exited, while in " "threading servers this method does nothing." msgstr "" +"Esta função é chamada quando o atributo :attr:`timeout` foi definido para um " +"valor diferente de :const:`None` e o período de timeout passou sem que " +"nenhuma solicitação tenha sido recebida. A ação padrão para servidores de " +"bifurcação é coletar o status de quaisquer processos filhos que tenham " +"saído, enquanto em servidores de threading esse método não faz nada." -#: ../../library/socketserver.rst:362 +#: ../../library/socketserver.rst:365 msgid "" "Calls :meth:`finish_request` to create an instance of the :attr:" "`RequestHandlerClass`. If desired, this function can create a new process " "or thread to handle the request; the :class:`ForkingMixIn` and :class:" "`ThreadingMixIn` classes do this." msgstr "" +"Chama :meth:`finish_request` para criar uma instância de :attr:" +"`RequestHandlerClass`. Se desejado, esta função pode criar um novo processo " +"ou thread para manipular a solicitação; as classes :class:`ForkingMixIn` e :" +"class:`ThreadingMixIn` fazem isso." -#: ../../library/socketserver.rst:374 +#: ../../library/socketserver.rst:377 msgid "" "Called by the server's constructor to activate the server. The default " "behavior for a TCP server just invokes :meth:`~socket.socket.listen` on the " "server's socket. May be overridden." msgstr "" +"Chamado pelo construtor do servidor para ativar o servidor. O comportamento " +"padrão para um servidor TCP apenas invoca :meth:`~socket.socket.listen` no " +"soquete do servidor. Pode ser substituído." -#: ../../library/socketserver.rst:381 +#: ../../library/socketserver.rst:384 msgid "" "Called by the server's constructor to bind the socket to the desired " "address. May be overridden." msgstr "" +"Chamada pelo construtor do servidor para vincular o soquete ao endereço " +"desejado. Pode ser substituída." -#: ../../library/socketserver.rst:387 +#: ../../library/socketserver.rst:390 msgid "" "Must return a Boolean value; if the value is :const:`True`, the request will " "be processed, and if it's :const:`False`, the request will be denied. This " "function can be overridden to implement access controls for a server. The " "default implementation always returns :const:`True`." msgstr "" +"Deve retornar um valor booleano; se o valor for :const:`True`, a solicitação " +"será processada, e se for :const:`False`, a solicitação será negada. Esta " +"função pode ser substituída para implementar controles de acesso para um " +"servidor. A implementação padrão sempre retorna :const:`True`." -#: ../../library/socketserver.rst:393 +#: ../../library/socketserver.rst:396 msgid "" "Support for the :term:`context manager` protocol was added. Exiting the " "context manager is equivalent to calling :meth:`server_close`." msgstr "" +"Foi adicionado suporte para o protocolo :term:`gerenciador de contexto`. " +"Sair do gerenciador de contexto é equivalente a chamar :meth:`server_close`." -#: ../../library/socketserver.rst:399 +#: ../../library/socketserver.rst:402 msgid "Request Handler Objects" -msgstr "" +msgstr "Objetos manipulador de requisições" -#: ../../library/socketserver.rst:403 +#: ../../library/socketserver.rst:406 msgid "" "This is the superclass of all request handler objects. It defines the " "interface, given below. A concrete request handler subclass must define a " "new :meth:`handle` method, and can override any of the other methods. A new " "instance of the subclass is created for each request." msgstr "" +"Esta é a superclasse de todos os objetos manipulador de requisições. Ela " +"define a interface, dada abaixo. Uma subclasse concreta do manipulador de " +"requisições deve definir um novo método :meth:`handle` e pode substituir " +"qualquer um dos outros métodos. Uma nova instância da subclasse é criada " +"para cada requisição." -#: ../../library/socketserver.rst:412 +#: ../../library/socketserver.rst:415 msgid "" "Called before the :meth:`handle` method to perform any initialization " "actions required. The default implementation does nothing." msgstr "" +"Chamada antes do método :meth:`handle` para executar quaisquer ações de " +"inicialização necessárias. A implementação padrão não faz nada." -#: ../../library/socketserver.rst:418 +#: ../../library/socketserver.rst:421 msgid "" "This function must do all the work required to service a request. The " "default implementation does nothing. Several instance attributes are " @@ -482,131 +710,534 @@ msgid "" "address as :attr:`client_address`; and the server instance as :attr:" "`server`, in case it needs access to per-server information." msgstr "" +"Esta função deve fazer todo o trabalho necessário para atender a uma " +"solicitação. A implementação padrão não faz nada. Vários atributos de " +"instância estão disponíveis para ela; a solicitação está disponível como :" +"attr:`request`; o endereço do cliente como :attr:`client_address`; e a " +"instância do servidor como :attr:`server`, caso precise de acesso a " +"informações por servidor." -#: ../../library/socketserver.rst:424 +#: ../../library/socketserver.rst:427 msgid "" "The type of :attr:`request` is different for datagram or stream services. " "For stream services, :attr:`request` is a socket object; for datagram " "services, :attr:`request` is a pair of string and socket." msgstr "" +"O tipo de :attr:`request` é diferente para serviços de datagrama ou fluxo. " +"Para serviços de fluxo, :attr:`request` é um objeto soquete; para serviços " +"de datagrama, :attr:`request` é um par de string e soquete." -#: ../../library/socketserver.rst:431 +#: ../../library/socketserver.rst:434 msgid "" "Called after the :meth:`handle` method to perform any clean-up actions " "required. The default implementation does nothing. If :meth:`setup` raises " "an exception, this function will not be called." msgstr "" +"Chamada após o método :meth:`handle` para executar quaisquer ações de " +"limpeza necessárias. A implementação padrão não faz nada. Se :meth:`setup` " +"levanta uma exceção, esta função não será chamada." -#: ../../library/socketserver.rst:438 +#: ../../library/socketserver.rst:441 msgid "" "The *new* :class:`socket.socket` object to be used to communicate with the " "client." msgstr "" +"O *novo* objeto :class:`socket.socket` a ser usado para se comunicar com o " +"cliente." -#: ../../library/socketserver.rst:444 +#: ../../library/socketserver.rst:447 msgid "Client address returned by :meth:`BaseServer.get_request`." -msgstr "" +msgstr "Endereço do cliente retornado por :meth:`BaseServer.get_request`." -#: ../../library/socketserver.rst:449 +#: ../../library/socketserver.rst:452 msgid ":class:`BaseServer` object used for handling the request." -msgstr "" +msgstr "Objeto :class:`BaseServer` usado para manipular a solicitação." -#: ../../library/socketserver.rst:455 +#: ../../library/socketserver.rst:458 msgid "" "These :class:`BaseRequestHandler` subclasses override the :meth:" "`~BaseRequestHandler.setup` and :meth:`~BaseRequestHandler.finish` methods, " "and provide :attr:`rfile` and :attr:`wfile` attributes." msgstr "" +"Essas subclasses :class:`BaseRequestHandler` substituem os métodos :meth:" +"`~BaseRequestHandler.setup` e :meth:`~BaseRequestHandler.finish` e fornecem " +"os atributos :attr:`rfile` e :attr:`wfile`." -#: ../../library/socketserver.rst:461 +#: ../../library/socketserver.rst:464 msgid "" "A file object from which receives the request is read. Support the :class:" "`io.BufferedIOBase` readable interface." msgstr "" +"Um objeto arquivo do qual recebe a solicitação é lido. Oferece suporte à " +"interface legível :class:`io.BufferedIOBase`." -#: ../../library/socketserver.rst:466 +#: ../../library/socketserver.rst:469 msgid "" "A file object to which the reply is written. Support the :class:`io." "BufferedIOBase` writable interface" msgstr "" +"Um objeto arquivo no qual a resposta é escrita. Oferece suporte à interface " +"gravável :class:`io.BufferedIOBase`" -#: ../../library/socketserver.rst:470 +#: ../../library/socketserver.rst:473 msgid "" ":attr:`wfile` also supports the :class:`io.BufferedIOBase` writable " "interface." msgstr "" +":attr:`wfile` também oferece suporte à interface gravável :class:`io." +"BufferedIOBase`." -#: ../../library/socketserver.rst:476 +#: ../../library/socketserver.rst:479 msgid "Examples" msgstr "Exemplos" -#: ../../library/socketserver.rst:479 +#: ../../library/socketserver.rst:482 msgid ":class:`socketserver.TCPServer` Example" -msgstr "" +msgstr "Exemplo de :class:`socketserver.TCPServer`" -#: ../../library/socketserver.rst:481 ../../library/socketserver.rst:581 +#: ../../library/socketserver.rst:484 ../../library/socketserver.rst:595 msgid "This is the server side::" -msgstr "" - -#: ../../library/socketserver.rst:511 +msgstr "Este é o lado do servidor::" + +#: ../../library/socketserver.rst:486 +msgid "" +"import socketserver\n" +"\n" +"class MyTCPHandler(socketserver.BaseRequestHandler):\n" +" \"\"\"\n" +" The request handler class for our server.\n" +"\n" +" It is instantiated once per connection to the server, and must\n" +" override the handle() method to implement communication to the\n" +" client.\n" +" \"\"\"\n" +"\n" +" def handle(self):\n" +" # self.request is the TCP socket connected to the client\n" +" pieces = [b'']\n" +" total = 0\n" +" while b'\\n' not in pieces[-1] and total < 10_000:\n" +" pieces.append(self.request.recv(2000))\n" +" total += len(pieces[-1])\n" +" self.data = b''.join(pieces)\n" +" print(f\"Received from {self.client_address[0]}:\")\n" +" print(self.data.decode(\"utf-8\"))\n" +" # just send back the same data, but upper-cased\n" +" self.request.sendall(self.data.upper())\n" +" # after we return, the socket will be closed.\n" +"\n" +"if __name__ == \"__main__\":\n" +" HOST, PORT = \"localhost\", 9999\n" +"\n" +" # Create the server, binding to localhost on port 9999\n" +" with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:\n" +" # Activate the server; this will keep running until you\n" +" # interrupt the program with Ctrl-C\n" +" server.serve_forever()" +msgstr "" +"import socketserver\n" +"\n" +"class MyTCPHandler(socketserver.BaseRequestHandler):\n" +" \"\"\"\n" +" A classe de manipulador de solicitação para nosso servidor.\n" +"\n" +" Ela é instanciada uma vez por conexão com o servidor e deve\n" +" substituir o método handle() para implementar a comunicação\n" +" com o cliente.\n" +" \"\"\"\n" +"\n" +" def handle(self):\n" +" # self.request é o soquete TCP conectado ao cliente\n" +" pieces = [b'']\n" +" total = 0\n" +" while b'\\n' not in pieces[-1] and total < 10_000:\n" +" pieces.append(self.request.recv(2000))\n" +" total += len(pieces[-1])\n" +" self.data = b''.join(pieces)\n" +" print(f\"Received from {self.client_address[0]}:\")\n" +" print(self.data.decode(\"utf-8\"))\n" +" # só envia de volta os mesmos dados, mas em caixa alta\n" +" self.request.sendall(self.data.upper())\n" +" # após retornarmos, o soquete será fechado.\n" +"\n" +"if __name__ == \"__main__\":\n" +" HOST, PORT = \"localhost\", 9999\n" +"\n" +" # Cria o servidor, ligando-o ao localhost na porta 9999\n" +" with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:\n" +" # Ativa o servidor; isso vai mantê-lo em execução até você\n" +" # interromper o programa com Ctrl-C\n" +" server.serve_forever()" + +#: ../../library/socketserver.rst:520 msgid "" "An alternative request handler class that makes use of streams (file-like " "objects that simplify communication by providing the standard file " "interface)::" msgstr "" - -#: ../../library/socketserver.rst:526 +"Uma classe de manipulador de solicitações alternativa que faz uso de fluxos " +"(objetos arquivo ou similar que simplificam a comunicação ao fornecer a " +"interface de arquivo padrão)::" + +#: ../../library/socketserver.rst:523 +msgid "" +"class MyTCPHandler(socketserver.StreamRequestHandler):\n" +"\n" +" def handle(self):\n" +" # self.rfile is a file-like object created by the handler.\n" +" # We can now use e.g. readline() instead of raw recv() calls.\n" +" # We limit ourselves to 10000 bytes to avoid abuse by the sender.\n" +" self.data = self.rfile.readline(10000).rstrip()\n" +" print(f\"{self.client_address[0]} wrote:\")\n" +" print(self.data.decode(\"utf-8\"))\n" +" # Likewise, self.wfile is a file-like object used to write back\n" +" # to the client\n" +" self.wfile.write(self.data.upper())" +msgstr "" +"class MyTCPHandler(socketserver.StreamRequestHandler):\n" +"\n" +" def handle(self):\n" +" # self.rfile é um objeto arquivo ou similar criado pelo " +"manipulador.\n" +" # Agora podemos usar, por exemplo, readline() em vez de chamadas\n" +" # brutas a recv().\n" +" # Nos limitamos a 10000 bytes para evitar abuso pelo remetente.\n" +" self.data = self.rfile.readline(10000).rstrip()\n" +" print(f\"{self.client_address[0]} wrote:\")\n" +" print(self.data.decode(\"utf-8\"))\n" +" # Da mesma forma, self.wfile é um objeto arquivo ou similar para\n" +" # escrever de volta para o cliente\n" +" self.wfile.write(self.data.upper())" + +#: ../../library/socketserver.rst:536 msgid "" "The difference is that the ``readline()`` call in the second handler will " "call ``recv()`` multiple times until it encounters a newline character, " -"while the single ``recv()`` call in the first handler will just return what " -"has been received so far from the client's ``sendall()`` call (typically all " -"of it, but this is not guaranteed by the TCP protocol)." -msgstr "" - -#: ../../library/socketserver.rst:533 ../../library/socketserver.rst:605 +"while the the first handler had to use a ``recv()`` loop to accumulate data " +"until a newline itself. If it had just used a single ``recv()`` without the " +"loop it would just have returned what has been received so far from the " +"client. TCP is stream based: data arrives in the order it was sent, but " +"there no correlation between client ``send()`` or ``sendall()`` calls and " +"the number of ``recv()`` calls on the server required to receive it." +msgstr "" +"A diferença é que a chamada ``readline()`` no segundo manipulador chamará " +"``recv()`` várias vezes até encontrar um caractere de nova linha, enquanto o " +"primeiro manipulador teve que usar um laço ``recv()`` para acumular dados " +"até uma nova linha. Se tivesse usado apenas um único ``recv()`` sem o laço, " +"ele teria retornado apenas o que foi recebido até agora do cliente. O TCP é " +"baseado em fluxo: os dados chegam na ordem em que foram enviados, mas não há " +"correlação entre as chamadas ``send()`` ou ``sendall()`` do cliente e o " +"número de chamadas ``recv()`` no servidor necessárias para recebê-los." + +#: ../../library/socketserver.rst:546 ../../library/socketserver.rst:619 msgid "This is the client side::" -msgstr "" - -#: ../../library/socketserver.rst:554 ../../library/socketserver.rst:680 +msgstr "Este é o lado do cliente::" + +#: ../../library/socketserver.rst:548 +msgid "" +"import socket\n" +"import sys\n" +"\n" +"HOST, PORT = \"localhost\", 9999\n" +"data = \" \".join(sys.argv[1:])\n" +"\n" +"# Create a socket (SOCK_STREAM means a TCP socket)\n" +"with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n" +" # Connect to server and send data\n" +" sock.connect((HOST, PORT))\n" +" sock.sendall(bytes(data, \"utf-8\"))\n" +" sock.sendall(b\"\\n\")\n" +"\n" +" # Receive data from the server and shut down\n" +" received = str(sock.recv(1024), \"utf-8\")\n" +"\n" +"print(\"Sent: \", data)\n" +"print(\"Received:\", received)" +msgstr "" +"import socket\n" +"import sys\n" +"\n" +"HOST, PORT = \"localhost\", 9999\n" +"data = \" \".join(sys.argv[1:])\n" +"\n" +"# Cria um soquete (SOCK_STREAM significa um soquete TCP)\n" +"with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n" +" # Conecta a um servidor e envia dados\n" +" sock.connect((HOST, PORT))\n" +" sock.sendall(bytes(data, \"utf-8\"))\n" +" sock.sendall(b\"\\n\")\n" +"\n" +" # Recebe dados do servidor e desliga\n" +" received = str(sock.recv(1024), \"utf-8\")\n" +"\n" +"print(\"Sent: \", data)\n" +"print(\"Received:\", received)" + +#: ../../library/socketserver.rst:568 ../../library/socketserver.rst:694 msgid "The output of the example should look something like this:" -msgstr "" +msgstr "A saída do exemplo deve se parecer com algo como isso:" -#: ../../library/socketserver.rst:556 +#: ../../library/socketserver.rst:570 msgid "Server:" +msgstr "Servidor:" + +#: ../../library/socketserver.rst:572 +msgid "" +"$ python TCPServer.py\n" +"127.0.0.1 wrote:\n" +"b'hello world with TCP'\n" +"127.0.0.1 wrote:\n" +"b'python is nice'" msgstr "" +"$ python TCPServer.py\n" +"127.0.0.1 wrote:\n" +"b'hello world with TCP'\n" +"127.0.0.1 wrote:\n" +"b'python is nice'" -#: ../../library/socketserver.rst:566 +#: ../../library/socketserver.rst:580 msgid "Client:" msgstr "Cliente:" -#: ../../library/socketserver.rst:579 +#: ../../library/socketserver.rst:582 +msgid "" +"$ python TCPClient.py hello world with TCP\n" +"Sent: hello world with TCP\n" +"Received: HELLO WORLD WITH TCP\n" +"$ python TCPClient.py python is nice\n" +"Sent: python is nice\n" +"Received: PYTHON IS NICE" +msgstr "" +"$ python TCPClient.py hello world with TCP\n" +"Sent: hello world with TCP\n" +"Received: HELLO WORLD WITH TCP\n" +"$ python TCPClient.py python is nice\n" +"Sent: python is nice\n" +"Received: PYTHON IS NICE" + +#: ../../library/socketserver.rst:593 msgid ":class:`socketserver.UDPServer` Example" msgstr "Exemplo :class:`socketserver.UDPServer`" -#: ../../library/socketserver.rst:624 +#: ../../library/socketserver.rst:597 +msgid "" +"import socketserver\n" +"\n" +"class MyUDPHandler(socketserver.BaseRequestHandler):\n" +" \"\"\"\n" +" This class works similar to the TCP handler class, except that\n" +" self.request consists of a pair of data and client socket, and since\n" +" there is no connection the client address must be given explicitly\n" +" when sending data back via sendto().\n" +" \"\"\"\n" +"\n" +" def handle(self):\n" +" data = self.request[0].strip()\n" +" socket = self.request[1]\n" +" print(f\"{self.client_address[0]} wrote:\")\n" +" print(data)\n" +" socket.sendto(data.upper(), self.client_address)\n" +"\n" +"if __name__ == \"__main__\":\n" +" HOST, PORT = \"localhost\", 9999\n" +" with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server:\n" +" server.serve_forever()" +msgstr "" +"import socketserver\n" +"\n" +"class MyUDPHandler(socketserver.BaseRequestHandler):\n" +" \"\"\"\n" +" Esta classe funciona de forma semelhante à classe do manipulador TCP,\n" +" exceto que self.request consiste em um par de dados e soquete do " +"cliente\n" +" e, como não há conexão, o endereço do cliente deve ser fornecido\n" +" explicitamente ao enviar dados de volta via sendto().\n" +" \"\"\"\n" +"\n" +" def handle(self):\n" +" data = self.request[0].strip()\n" +" socket = self.request[1]\n" +" print(f\"{self.client_address[0]} wrote:\")\n" +" print(data)\n" +" socket.sendto(data.upper(), self.client_address)\n" +"\n" +"if __name__ == \"__main__\":\n" +" HOST, PORT = \"localhost\", 9999\n" +" with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server:\n" +" server.serve_forever()" + +#: ../../library/socketserver.rst:621 +msgid "" +"import socket\n" +"import sys\n" +"\n" +"HOST, PORT = \"localhost\", 9999\n" +"data = \" \".join(sys.argv[1:])\n" +"\n" +"# SOCK_DGRAM is the socket type to use for UDP sockets\n" +"sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n" +"\n" +"# As you can see, there is no connect() call; UDP has no connections.\n" +"# Instead, data is directly sent to the recipient via sendto().\n" +"sock.sendto(bytes(data + \"\\n\", \"utf-8\"), (HOST, PORT))\n" +"received = str(sock.recv(1024), \"utf-8\")\n" +"\n" +"print(\"Sent: \", data)\n" +"print(\"Received:\", received)" +msgstr "" +"import socket\n" +"import sys\n" +"\n" +"HOST, PORT = \"localhost\", 9999\n" +"data = \" \".join(sys.argv[1:])\n" +"\n" +"# SOCK_DGRAM é o tipo de soquete para usar para soquetes UDP\n" +"sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n" +"\n" +"# Como você pode ver, não há uma chamada connect(); UDP não tem conexão.\n" +"# Em vez disso, dados são enviados diretamente para o destinatário via " +"sendto().\n" +"sock.sendto(bytes(data + \"\\n\", \"utf-8\"), (HOST, PORT))\n" +"received = str(sock.recv(1024), \"utf-8\")\n" +"\n" +"print(\"Sent: \", data)\n" +"print(\"Received:\", received)" + +#: ../../library/socketserver.rst:638 msgid "" "The output of the example should look exactly like for the TCP server " "example." msgstr "" +"A saída do exemplo deve ser exatamente igual à do exemplo do servidor TCP." -#: ../../library/socketserver.rst:628 +#: ../../library/socketserver.rst:642 msgid "Asynchronous Mixins" -msgstr "" +msgstr "Mixins assíncronos" -#: ../../library/socketserver.rst:630 +#: ../../library/socketserver.rst:644 msgid "" "To build asynchronous handlers, use the :class:`ThreadingMixIn` and :class:" "`ForkingMixIn` classes." msgstr "" +"Para construir manipuladores assíncronos, use as classes :class:" +"`ThreadingMixIn` e :class:`ForkingMixIn`." -#: ../../library/socketserver.rst:633 +#: ../../library/socketserver.rst:647 msgid "An example for the :class:`ThreadingMixIn` class::" -msgstr "" - -#: ../../library/socketserver.rst:691 +msgstr "Um exemplo para a classe :class:`ThreadingMixIn`::" + +#: ../../library/socketserver.rst:649 +msgid "" +"import socket\n" +"import threading\n" +"import socketserver\n" +"\n" +"class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):\n" +"\n" +" def handle(self):\n" +" data = str(self.request.recv(1024), 'ascii')\n" +" cur_thread = threading.current_thread()\n" +" response = bytes(\"{}: {}\".format(cur_thread.name, data), 'ascii')\n" +" self.request.sendall(response)\n" +"\n" +"class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver." +"TCPServer):\n" +" pass\n" +"\n" +"def client(ip, port, message):\n" +" with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n" +" sock.connect((ip, port))\n" +" sock.sendall(bytes(message, 'ascii'))\n" +" response = str(sock.recv(1024), 'ascii')\n" +" print(\"Received: {}\".format(response))\n" +"\n" +"if __name__ == \"__main__\":\n" +" # Port 0 means to select an arbitrary unused port\n" +" HOST, PORT = \"localhost\", 0\n" +"\n" +" server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)\n" +" with server:\n" +" ip, port = server.server_address\n" +"\n" +" # Start a thread with the server -- that thread will then start one\n" +" # more thread for each request\n" +" server_thread = threading.Thread(target=server.serve_forever)\n" +" # Exit the server thread when the main thread terminates\n" +" server_thread.daemon = True\n" +" server_thread.start()\n" +" print(\"Server loop running in thread:\", server_thread.name)\n" +"\n" +" client(ip, port, \"Hello World 1\")\n" +" client(ip, port, \"Hello World 2\")\n" +" client(ip, port, \"Hello World 3\")\n" +"\n" +" server.shutdown()" +msgstr "" +"import socket\n" +"import threading\n" +"import socketserver\n" +"\n" +"class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):\n" +"\n" +" def handle(self):\n" +" data = str(self.request.recv(1024), 'ascii')\n" +" cur_thread = threading.current_thread()\n" +" response = bytes(\"{}: {}\".format(cur_thread.name, data), 'ascii')\n" +" self.request.sendall(response)\n" +"\n" +"class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver." +"TCPServer):\n" +" pass\n" +"\n" +"def client(ip, port, message):\n" +" with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n" +" sock.connect((ip, port))\n" +" sock.sendall(bytes(message, 'ascii'))\n" +" response = str(sock.recv(1024), 'ascii')\n" +" print(\"Received: {}\".format(response))\n" +"\n" +"if __name__ == \"__main__\":\n" +" # Porta 0 significa selecionar uma porta não usada arbitrária\n" +" HOST, PORT = \"localhost\", 0\n" +"\n" +" server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)\n" +" with server:\n" +" ip, port = server.server_address\n" +"\n" +" # Inicia uma thread com o servidor -- essa thread vai então\n" +" # iniciar mais um thread para cada requisição\n" +" server_thread = threading.Thread(target=server.serve_forever)\n" +" # Sai da thread do servidor quando a thread principal é encerrada\n" +" server_thread.daemon = True\n" +" server_thread.start()\n" +" print(\"Server loop running in thread:\", server_thread.name)\n" +"\n" +" client(ip, port, \"Hello World 1\")\n" +" client(ip, port, \"Hello World 2\")\n" +" client(ip, port, \"Hello World 3\")\n" +"\n" +" server.shutdown()" + +#: ../../library/socketserver.rst:696 +msgid "" +"$ python ThreadedTCPServer.py\n" +"Server loop running in thread: Thread-1\n" +"Received: Thread-2: Hello World 1\n" +"Received: Thread-3: Hello World 2\n" +"Received: Thread-4: Hello World 3" +msgstr "" +"$ python ThreadedTCPServer.py\n" +"Server loop running in thread: Thread-1\n" +"Received: Thread-2: Hello World 1\n" +"Received: Thread-3: Hello World 2\n" +"Received: Thread-4: Hello World 3" + +#: ../../library/socketserver.rst:705 msgid "" "The :class:`ForkingMixIn` class is used in the same way, except that the " "server will spawn a new process for each request. Available only on POSIX " "platforms that support :func:`~os.fork`." msgstr "" +"A classe :class:`ForkingMixIn` é usada da mesma forma, exceto que o servidor " +"gerará um novo processo para cada solicitação. Disponível apenas em " +"plataformas POSIX que oferecem suporte a :func:`~os.fork`." diff --git a/library/spwd.po b/library/spwd.po new file mode 100644 index 000000000..b55d6030c --- /dev/null +++ b/library/spwd.po @@ -0,0 +1,54 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../library/spwd.rst:2 +msgid ":mod:`!spwd` --- The shadow password database" +msgstr ":mod:`!spwd` --- O banco de dados de senhas shadow" + +#: ../../library/spwd.rst:10 +msgid "" +"This module is no longer part of the Python standard library. It was :ref:" +"`removed in Python 3.13 ` after being deprecated in " +"Python 3.11. The removal was decided in :pep:`594`." +msgstr "" +"Este módulo não faz mais parte da biblioteca padrão do Python. Ele foi :ref:" +"`removido no Python 3.13 ` após ser descontinuado no " +"Python 3.11. A remoção foi decidida na :pep:`594`." + +#: ../../library/spwd.rst:14 +msgid "" +"A possible replacement is the third-party library :pypi:`python-pam`. This " +"library is not supported or maintained by the Python core team." +msgstr "" +"Uma possível substituição é a biblioteca de terceiros :pypi:`python-pam`. " +"Esta biblioteca não é suportada ou mantida pela equipe principal do Python." + +#: ../../library/spwd.rst:17 +msgid "" +"The last version of Python that provided the :mod:`!spwd` module was `Python " +"3.12 `_." +msgstr "" +"A última versão do Python que forneceu o módulo :mod:`!spwd` foi o `Python " +"3.12 `_." diff --git a/library/sqlite3.po b/library/sqlite3.po index 8d83beddc..c364aad91 100644 --- a/library/sqlite3.po +++ b/library/sqlite3.po @@ -1,41 +1,33 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Leticia Portella , 2021 -# Marco Rougeth , 2021 -# And Past , 2022 -# (Douglas da Silva) , 2022 -# Claudio Rogerio Carvalho Filho , 2022 -# Rodrigo Cândido, 2022 -# Adorilson Bezerra , 2023 -# i17obot , 2024 -# Leandro Cavalcante Damascena , 2024 -# Pedro Fonini, 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:13+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-03-21 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/sqlite3.rst:2 msgid ":mod:`!sqlite3` --- DB-API 2.0 interface for SQLite databases" msgstr "" +":mod:`!sqlite3` ---- interface DB-API 2.0 interface para bancos de dados " +"SQLite" #: ../../library/sqlite3.rst:9 msgid "**Source code:** :source:`Lib/sqlite3/`" @@ -54,7 +46,7 @@ msgstr "" "disco que não requer um processo de servidor separado e permite acessar o " "banco de dados usando uma variante não padrão da linguagem de consulta SQL. " "Algumas aplicações podem usar SQLite para armazenamento interno de dados. " -"Também é possível prototipar uma aplicação usando SQLite e, em seguida, " +"Também é possível prototipar um aplicativo usando SQLite e, em seguida, " "portar o código para um banco de dados maior, como PostgreSQL ou Oracle." #: ../../library/sqlite3.rst:32 @@ -63,6 +55,9 @@ msgid "" "SQL interface compliant with the DB-API 2.0 specification described by :pep:" "`249`, and requires SQLite 3.15.2 or newer." msgstr "" +"O módulo :mod:`!sqlite3` foi escrito por Gerhard Häring. Ele oferece uma " +"interface SQL compatível com a especificação DB-API 2.0 descrita pela :pep:" +"`249` e requer o SQLite 3.15.2 ou o mais recente." #: ../../library/sqlite3.rst:36 msgid "This document includes four main sections:" @@ -148,6 +143,14 @@ msgstr "" "`tutorial.db` no diretório de trabalho atual, criando-o implicitamente se " "ele não existir:" +#: ../../library/sqlite3.rst:81 +msgid "" +"import sqlite3\n" +"con = sqlite3.connect(\"tutorial.db\")" +msgstr "" +"import sqlite3\n" +"con = sqlite3.connect(\"tutorial.db\")" + #: ../../library/sqlite3.rst:86 msgid "" "The returned :class:`Connection` object ``con`` represents the connection to " @@ -166,6 +169,10 @@ msgstr "" "precisaremos usar um cursor de banco de dados. Chame :meth:`con.cursor() " "` para criar o :class:`Cursor`:" +#: ../../library/sqlite3.rst:93 +msgid "cur = con.cursor()" +msgstr "cur = con.cursor()" + #: ../../library/sqlite3.rst:97 msgid "" "Now that we've got a database connection and a cursor, we can create a " @@ -183,6 +190,10 @@ msgstr "" "instrução ``CREATE TABLE`` chamando :meth:`cur.execute(...) `:" +#: ../../library/sqlite3.rst:106 +msgid "cur.execute(\"CREATE TABLE movie(title, year, score)\")" +msgstr "cur.execute(\"CREATE TABLE movie(title, year, score)\")" + #: ../../library/sqlite3.rst:113 msgid "" "We can verify that the new table has been created by querying the " @@ -199,15 +210,36 @@ msgstr "" "atribua o resultado a ``res`` e chame :meth:`res.fetchone() ` para buscar a linha resultante:" +#: ../../library/sqlite3.rst:121 +msgid "" +">>> res = cur.execute(\"SELECT name FROM sqlite_master\")\n" +">>> res.fetchone()\n" +"('movie',)" +msgstr "" +">>> res = cur.execute(\"SELECT name FROM sqlite_master\")\n" +">>> res.fetchone()\n" +"('movie',)" + #: ../../library/sqlite3.rst:127 msgid "" "We can see that the table has been created, as the query returns a :class:" "`tuple` containing the table's name. If we query ``sqlite_master`` for a non-" -"existent table ``spam``, :meth:`!res.fetchone()` will return ``None``:" +"existent table ``spam``, :meth:`!res.fetchone` will return ``None``:" msgstr "" -"Podemos ver que a tabela foi criada, pois a consulta retorna uma :class:" -"`tuple` contendo o nome da tabela. Se consultarmos ``sqlite_master`` por uma " -"tabela inexistente ``spam``, :meth:`!res.fetchone()` retornará ``None``:" +"Podemos ver que a tabela foi criada, pois a consulta retorna :class:`tuple` " +"contendo o nome da tabela. Se fizermos uma consulta ``sqlite_master`` para " +"uma tabela inexistente ``spam``, :meth:`!res.fetchone` ela retornará " +"``None``:" + +#: ../../library/sqlite3.rst:132 +msgid "" +">>> res = cur.execute(\"SELECT name FROM sqlite_master WHERE name='spam'\")\n" +">>> res.fetchone() is None\n" +"True" +msgstr "" +">>> res = cur.execute(\"SELECT name FROM sqlite_master WHERE name='spam'\")\n" +">>> res.fetchone() is None\n" +"True" #: ../../library/sqlite3.rst:138 msgid "" @@ -219,6 +251,20 @@ msgstr "" "uma instrução ``INSERT``, mais uma vez chamando :meth:`cur.execute(...) " "`:" +#: ../../library/sqlite3.rst:142 +msgid "" +"cur.execute(\"\"\"\n" +" INSERT INTO movie VALUES\n" +" ('Monty Python and the Holy Grail', 1975, 8.2),\n" +" ('And Now for Something Completely Different', 1971, 7.5)\n" +"\"\"\")" +msgstr "" +"cur.execute(\"\"\"\n" +" INSERT INTO movie VALUES\n" +" ('Monty Python and the Holy Grail', 1975, 8.2),\n" +" ('And Now for Something Completely Different', 1971, 7.5)\n" +"\"\"\")" + #: ../../library/sqlite3.rst:150 msgid "" "The ``INSERT`` statement implicitly opens a transaction, which needs to be " @@ -231,6 +277,10 @@ msgstr "" "`sqlite3-controlling-transactions` para detalhes). Chame :meth:`con.commit() " "` no objeto de conexão para confirmar a transação:" +#: ../../library/sqlite3.rst:156 +msgid "con.commit()" +msgstr "con.commit()" + #: ../../library/sqlite3.rst:160 msgid "" "We can verify that the data was inserted correctly by executing a ``SELECT`` " @@ -243,6 +293,16 @@ msgstr "" "execute>` para atribuir o resultado a ``res`` e chame :meth:`res.fetchall() " "` para retornar todas as linhas resultantes." +#: ../../library/sqlite3.rst:166 +msgid "" +">>> res = cur.execute(\"SELECT score FROM movie\")\n" +">>> res.fetchall()\n" +"[(8.2,), (7.5,)]" +msgstr "" +">>> res = cur.execute(\"SELECT score FROM movie\")\n" +">>> res.fetchall()\n" +"[(8.2,), (7.5,)]" + #: ../../library/sqlite3.rst:172 msgid "" "The result is a :class:`list` of two :class:`!tuple`\\s, one per row, each " @@ -259,6 +319,24 @@ msgstr "" "Agora, insira mais três linhas chamando :meth:`cur.executemany(...) `:" +#: ../../library/sqlite3.rst:178 +msgid "" +"data = [\n" +" (\"Monty Python Live at the Hollywood Bowl\", 1982, 7.9),\n" +" (\"Monty Python's The Meaning of Life\", 1983, 7.5),\n" +" (\"Monty Python's Life of Brian\", 1979, 8.0),\n" +"]\n" +"cur.executemany(\"INSERT INTO movie VALUES(?, ?, ?)\", data)\n" +"con.commit() # Remember to commit the transaction after executing INSERT." +msgstr "" +"data = [\n" +" (\"Monty Python Live at the Hollywood Bowl\", 1982, 7.9),\n" +" (\"Monty Python's The Meaning of Life\", 1983, 7.5),\n" +" (\"Monty Python's Life of Brian\", 1979, 8.0),\n" +"]\n" +"cur.executemany(\"INSERT INTO movie VALUES(?, ?, ?)\", data)\n" +"con.commit() # Lembre-sede executar a transação após o INSERT." + #: ../../library/sqlite3.rst:188 msgid "" "Notice that ``?`` placeholders are used to bind ``data`` to the query. " @@ -280,6 +358,26 @@ msgstr "" "Podemos verificar que as novas linhas foram inseridas executando uma " "consulta ``SELECT``, desta vez iterando sobre os resultados da consulta." +#: ../../library/sqlite3.rst:198 +msgid "" +">>> for row in cur.execute(\"SELECT year, title FROM movie ORDER BY " +"year\"):\n" +"... print(row)\n" +"(1971, 'And Now for Something Completely Different')\n" +"(1975, 'Monty Python and the Holy Grail')\n" +"(1979, \"Monty Python's Life of Brian\")\n" +"(1982, 'Monty Python Live at the Hollywood Bowl')\n" +"(1983, \"Monty Python's The Meaning of Life\")" +msgstr "" +">>> for row in cur.execute(\"SELECT year, title FROM movie ORDER BY " +"year\"):\n" +"... print(row)\n" +"(1971, 'And Now for Something Completely Different')\n" +"(1975, 'Monty Python and the Holy Grail')\n" +"(1979, \"Monty Python's Life of Brian\")\n" +"(1982, 'Monty Python Live at the Hollywood Bowl')\n" +"(1983, \"Monty Python's The Meaning of Life\")" + #: ../../library/sqlite3.rst:208 msgid "" "Each row is a two-item :class:`tuple` of ``(year, title)``, matching the " @@ -298,6 +396,32 @@ msgstr "" "meth:`con.close() ` para fechar a conexão existente, abrir " "uma nova, criar um novo cursor e, em seguida, consultar o banco de dados." +#: ../../library/sqlite3.rst:216 +msgid "" +">>> con.close()\n" +">>> new_con = sqlite3.connect(\"tutorial.db\")\n" +">>> new_cur = new_con.cursor()\n" +">>> res = new_cur.execute(\"SELECT title, year FROM movie ORDER BY score " +"DESC\")\n" +">>> title, year = res.fetchone()\n" +">>> print(f'The highest scoring Monty Python movie is {title!r}, released in " +"{year}')\n" +"The highest scoring Monty Python movie is 'Monty Python and the Holy Grail', " +"released in 1975\n" +">>> new_con.close()" +msgstr "" +">>> con.close()\n" +">>> new_con = sqlite3.connect(\"tutorial.db\")\n" +">>> new_cur = new_con.cursor()\n" +">>> res = new_cur.execute(\"SELECT title, year FROM movie ORDER BY score " +"DESC\")\n" +">>> title, year = res.fetchone()\n" +">>> print(f'The highest scoring Monty Python movie is {title!r}, released in " +"{year}')\n" +"The highest scoring Monty Python movie is 'Monty Python and the Holy Grail', " +"released in 1975\n" +">>> new_con.close()" + #: ../../library/sqlite3.rst:227 msgid "" "You've now created an SQLite database using the :mod:`!sqlite3` module, " @@ -322,7 +446,7 @@ msgstr ":ref:`sqlite3-adapters`" msgid ":ref:`sqlite3-converters`" msgstr ":ref:`sqlite3-converters`" -#: ../../library/sqlite3.rst:244 ../../library/sqlite3.rst:616 +#: ../../library/sqlite3.rst:244 ../../library/sqlite3.rst:618 msgid ":ref:`sqlite3-connection-context-manager`" msgstr ":ref:`sqlite3-connection-context-manager`" @@ -343,11 +467,11 @@ msgstr "Referência" #: ../../library/sqlite3.rst:260 msgid "Module functions" -msgstr "" +msgstr "Funções do módulo" #: ../../library/sqlite3.rst:268 msgid "Open a connection to an SQLite database." -msgstr "" +msgstr "Abra uma conexão com um banco de dados SQLite." #: ../../library/sqlite3.rst:0 msgid "Parameters" @@ -359,6 +483,9 @@ msgid "" "create an `SQLite database existing only in memory `_, and open a connection to it." msgstr "" +"O caminho para o arquivo do banco de dados a ser aberto. Você pode passar " +"``\":memory:\"`` para criar um banco de dados `SQLite que existirá apenas na " +"memória `_, e abrir uma conexão com ele." #: ../../library/sqlite3.rst:277 msgid "" @@ -367,6 +494,10 @@ msgid "" "transaction to modify a table, that table will be locked until the " "transaction is committed. Default five seconds." msgstr "" +"Quantos segundos a conexão deve aguardar antes de levantar uma exceção :exc:" +"`OperationalError` quando uma tabela estiver bloqueada. Se outra conexão " +"abrir uma transação para modificar uma tabela, essa tabela permanecerá " +"bloqueada até que a transação seja confirmada. O padrão é cinco segundos." #: ../../library/sqlite3.rst:284 msgid "" @@ -375,13 +506,10 @@ msgid "" "converters registered with :func:`register_converter`. Set it to any " "combination (using ``|``, bitwise or) of :const:`PARSE_DECLTYPES` and :const:" "`PARSE_COLNAMES` to enable this. Column names takes precedence over declared " -"types if both flags are set. Types cannot be detected for generated fields " -"(for example ``max(data)``), even when the *detect_types* parameter is set; :" -"class:`str` will be returned instead. By default (``0``), type detection is " -"disabled." +"types if both flags are set. By default (``0``), type detection is disabled." msgstr "" -#: ../../library/sqlite3.rst:298 +#: ../../library/sqlite3.rst:295 msgid "" "Control legacy transaction handling behaviour. See :attr:`Connection." "isolation_level` and :ref:`sqlite3-transaction-control-isolation-level` for " @@ -391,7 +519,7 @@ msgid "" "`~sqlite3.LEGACY_TRANSACTION_CONTROL` (the default)." msgstr "" -#: ../../library/sqlite3.rst:308 +#: ../../library/sqlite3.rst:305 msgid "" "If ``True`` (default), :exc:`ProgrammingError` will be raised if the " "database connection is used by a thread other than the one that created it. " @@ -400,19 +528,19 @@ msgid "" "See :attr:`threadsafety` for more information." msgstr "" -#: ../../library/sqlite3.rst:317 +#: ../../library/sqlite3.rst:314 msgid "" "A custom subclass of :class:`Connection` to create the connection with, if " "not the default :class:`Connection` class." msgstr "" -#: ../../library/sqlite3.rst:321 +#: ../../library/sqlite3.rst:318 msgid "" "The number of statements that :mod:`!sqlite3` should internally cache for " "this connection, to avoid parsing overhead. By default, 128 statements." msgstr "" -#: ../../library/sqlite3.rst:326 +#: ../../library/sqlite3.rst:323 msgid "" "If set to ``True``, *database* is interpreted as a :abbr:`URI (Uniform " "Resource Identifier)` with a file path and an optional query string. The " @@ -421,7 +549,7 @@ msgid "" "various :ref:`sqlite3-uri-tricks`." msgstr "" -#: ../../library/sqlite3.rst:335 +#: ../../library/sqlite3.rst:332 msgid "" "Control :pep:`249` transaction handling behaviour. See :attr:`Connection." "autocommit` and :ref:`sqlite3-transaction-control-autocommit` for more " @@ -434,7 +562,7 @@ msgstr "" msgid "Return type" msgstr "" -#: ../../library/sqlite3.rst:346 +#: ../../library/sqlite3.rst:343 msgid "" "Raises an :ref:`auditing event ` ``sqlite3.connect`` with argument " "``database``." @@ -442,7 +570,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``sqlite3.connect`` com o " "argumento ``database``." -#: ../../library/sqlite3.rst:347 +#: ../../library/sqlite3.rst:344 msgid "" "Raises an :ref:`auditing event ` ``sqlite3.connect/handle`` with " "argument ``connection_handle``." @@ -450,31 +578,31 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``sqlite3.connect/handle`` " "com o argumento ``connection_handle``." -#: ../../library/sqlite3.rst:349 +#: ../../library/sqlite3.rst:346 msgid "Added the *uri* parameter." msgstr "Adicionado o parâmetro *uri*." -#: ../../library/sqlite3.rst:352 +#: ../../library/sqlite3.rst:349 msgid "" "*database* can now also be a :term:`path-like object`, not only a string." msgstr "" -#: ../../library/sqlite3.rst:355 +#: ../../library/sqlite3.rst:352 msgid "Added the ``sqlite3.connect/handle`` auditing event." msgstr "" -#: ../../library/sqlite3.rst:358 +#: ../../library/sqlite3.rst:355 msgid "Added the *autocommit* parameter." msgstr "" -#: ../../library/sqlite3.rst:361 +#: ../../library/sqlite3.rst:358 msgid "" "Positional use of the parameters *timeout*, *detect_types*, " "*isolation_level*, *check_same_thread*, *factory*, *cached_statements*, and " "*uri* is deprecated. They will become keyword-only parameters in Python 3.15." msgstr "" -#: ../../library/sqlite3.rst:369 +#: ../../library/sqlite3.rst:366 msgid "" "Return ``True`` if the string *statement* appears to contain one or more " "complete SQL statements. No syntactic verification or parsing of any kind is " @@ -482,24 +610,32 @@ msgid "" "and the statement is terminated by a semicolon." msgstr "" -#: ../../library/sqlite3.rst:375 +#: ../../library/sqlite3.rst:372 msgid "For example:" msgstr "Por exemplo:" -#: ../../library/sqlite3.rst:384 +#: ../../library/sqlite3.rst:374 +msgid "" +">>> sqlite3.complete_statement(\"SELECT foo FROM bar;\")\n" +"True\n" +">>> sqlite3.complete_statement(\"SELECT foo\")\n" +"False" +msgstr "" + +#: ../../library/sqlite3.rst:381 msgid "" "This function may be useful during command-line input to determine if the " "entered text seems to form a complete SQL statement, or if additional input " "is needed before calling :meth:`~Cursor.execute`." msgstr "" -#: ../../library/sqlite3.rst:388 +#: ../../library/sqlite3.rst:385 msgid "" "See :func:`!runsource` in :source:`Lib/sqlite3/__main__.py` for real-world " "use." msgstr "" -#: ../../library/sqlite3.rst:393 +#: ../../library/sqlite3.rst:390 msgid "" "Enable or disable callback tracebacks. By default you will not get any " "tracebacks in user-defined functions, aggregates, converters, authorizer " @@ -508,14 +644,14 @@ msgid "" "on :data:`sys.stderr`. Use ``False`` to disable the feature again." msgstr "" -#: ../../library/sqlite3.rst:402 +#: ../../library/sqlite3.rst:399 msgid "" "Errors in user-defined function callbacks are logged as unraisable " "exceptions. Use an :func:`unraisable hook handler ` for " "introspection of the failed callback." msgstr "" -#: ../../library/sqlite3.rst:408 +#: ../../library/sqlite3.rst:405 msgid "" "Register an *adapter* :term:`callable` to adapt the Python type *type* into " "an SQLite type. The adapter is called with a Python object of type *type* as " @@ -523,7 +659,7 @@ msgid "" "natively understands `." msgstr "" -#: ../../library/sqlite3.rst:416 +#: ../../library/sqlite3.rst:413 msgid "" "Register the *converter* :term:`callable` to convert SQLite objects of type " "*typename* into a Python object of a specific type. The converter is invoked " @@ -533,101 +669,122 @@ msgid "" "type detection works." msgstr "" -#: ../../library/sqlite3.rst:424 +#: ../../library/sqlite3.rst:421 msgid "" "Note: *typename* and the name of the type in your query are matched case-" "insensitively." msgstr "" -#: ../../library/sqlite3.rst:431 +#: ../../library/sqlite3.rst:428 msgid "Module constants" msgstr "Constantes do módulo" -#: ../../library/sqlite3.rst:435 +#: ../../library/sqlite3.rst:432 msgid "" "Set :attr:`~Connection.autocommit` to this constant to select old style (pre-" "Python 3.12) transaction control behaviour. See :ref:`sqlite3-transaction-" "control-isolation-level` for more information." msgstr "" -#: ../../library/sqlite3.rst:441 +#: ../../library/sqlite3.rst:438 msgid "" "Pass this flag value to the *detect_types* parameter of :func:`connect` to " -"look up a converter function by using the type name, parsed from the query " -"column name, as the converter dictionary key. The type name must be wrapped " -"in square brackets (``[]``)." +"look up a converter function using the declared types for each column. The " +"types are declared when the database table is created. :mod:`!sqlite3` will " +"look up a converter function using the first word of the declared type as " +"the converter dictionary key. For example:" msgstr "" -#: ../../library/sqlite3.rst:451 +#: ../../library/sqlite3.rst:446 msgid "" -"This flag may be combined with :const:`PARSE_DECLTYPES` using the ``|`` " +"CREATE TABLE test(\n" +" i integer primary key, ! will look up a converter named \"integer\"\n" +" p point, ! will look up a converter named \"point\"\n" +" n number(10) ! will look up a converter named \"number\"\n" +" )" +msgstr "" + +#: ../../library/sqlite3.rst:454 +msgid "" +"This flag may be combined with :const:`PARSE_COLNAMES` using the ``|`` " "(bitwise or) operator." msgstr "" -#: ../../library/sqlite3.rst:456 +#: ../../library/sqlite3.rst:459 +msgid "" +"Generated fields (for example ``MAX(p)``) are returned as :class:`str`. Use :" +"const:`!PARSE_COLNAMES` to enforce types for such queries." +msgstr "" + +#: ../../library/sqlite3.rst:464 msgid "" "Pass this flag value to the *detect_types* parameter of :func:`connect` to " -"look up a converter function using the declared types for each column. The " -"types are declared when the database table is created. :mod:`!sqlite3` will " -"look up a converter function using the first word of the declared type as " -"the converter dictionary key. For example:" +"look up a converter function by using the type name, parsed from the query " +"column name, as the converter dictionary key. The query column name must be " +"wrapped in double quotes (``\"``) and the type name must be wrapped in " +"square brackets (``[]``)." msgstr "" -#: ../../library/sqlite3.rst:472 +#: ../../library/sqlite3.rst:471 msgid "" -"This flag may be combined with :const:`PARSE_COLNAMES` using the ``|`` " +"SELECT MAX(p) as \"p [point]\" FROM test; ! will look up converter \"point\"" +msgstr "" + +#: ../../library/sqlite3.rst:475 +msgid "" +"This flag may be combined with :const:`PARSE_DECLTYPES` using the ``|`` " "(bitwise or) operator." msgstr "" -#: ../../library/sqlite3.rst:479 +#: ../../library/sqlite3.rst:482 msgid "" "Flags that should be returned by the *authorizer_callback* :term:`callable` " "passed to :meth:`Connection.set_authorizer`, to indicate whether:" msgstr "" -#: ../../library/sqlite3.rst:482 +#: ../../library/sqlite3.rst:485 msgid "Access is allowed (:const:`!SQLITE_OK`)," msgstr "" -#: ../../library/sqlite3.rst:483 +#: ../../library/sqlite3.rst:486 msgid "" "The SQL statement should be aborted with an error (:const:`!SQLITE_DENY`)" msgstr "" -#: ../../library/sqlite3.rst:484 +#: ../../library/sqlite3.rst:487 msgid "" "The column should be treated as a ``NULL`` value (:const:`!SQLITE_IGNORE`)" msgstr "" -#: ../../library/sqlite3.rst:488 +#: ../../library/sqlite3.rst:491 msgid "" "String constant stating the supported DB-API level. Required by the DB-API. " "Hard-coded to ``\"2.0\"``." msgstr "" -#: ../../library/sqlite3.rst:493 +#: ../../library/sqlite3.rst:496 msgid "" "String constant stating the type of parameter marker formatting expected by " "the :mod:`!sqlite3` module. Required by the DB-API. Hard-coded to " "``\"qmark\"``." msgstr "" -#: ../../library/sqlite3.rst:499 +#: ../../library/sqlite3.rst:502 msgid "The ``named`` DB-API parameter style is also supported." msgstr "" -#: ../../library/sqlite3.rst:503 +#: ../../library/sqlite3.rst:506 msgid "" "Version number of the runtime SQLite library as a :class:`string `." msgstr "" -#: ../../library/sqlite3.rst:507 +#: ../../library/sqlite3.rst:510 msgid "" "Version number of the runtime SQLite library as a :class:`tuple` of :class:" "`integers `." msgstr "" -#: ../../library/sqlite3.rst:512 +#: ../../library/sqlite3.rst:515 msgid "" "Integer constant required by the DB-API 2.0, stating the level of thread " "safety the :mod:`!sqlite3` module supports. This attribute is set based on " @@ -635,206 +792,206 @@ msgid "" "underlying SQLite library is compiled with. The SQLite threading modes are:" msgstr "" -#: ../../library/sqlite3.rst:517 +#: ../../library/sqlite3.rst:520 msgid "" "**Single-thread**: In this mode, all mutexes are disabled and SQLite is " "unsafe to use in more than a single thread at once." msgstr "" -#: ../../library/sqlite3.rst:519 +#: ../../library/sqlite3.rst:522 msgid "" "**Multi-thread**: In this mode, SQLite can be safely used by multiple " "threads provided that no single database connection is used simultaneously " "in two or more threads." msgstr "" -#: ../../library/sqlite3.rst:522 +#: ../../library/sqlite3.rst:525 msgid "" "**Serialized**: In serialized mode, SQLite can be safely used by multiple " "threads with no restriction." msgstr "" -#: ../../library/sqlite3.rst:525 +#: ../../library/sqlite3.rst:528 msgid "" "The mappings from SQLite threading modes to DB-API 2.0 threadsafety levels " "are as follows:" msgstr "" -#: ../../library/sqlite3.rst:529 +#: ../../library/sqlite3.rst:532 msgid "SQLite threading mode" msgstr "" -#: ../../library/sqlite3.rst:529 -msgid "`threadsafety`_" +#: ../../library/sqlite3.rst:532 +msgid ":pep:`threadsafety <0249#threadsafety>`" msgstr "" -#: ../../library/sqlite3.rst:529 +#: ../../library/sqlite3.rst:532 msgid "`SQLITE_THREADSAFE`_" msgstr "" -#: ../../library/sqlite3.rst:529 +#: ../../library/sqlite3.rst:532 msgid "DB-API 2.0 meaning" msgstr "" -#: ../../library/sqlite3.rst:532 +#: ../../library/sqlite3.rst:535 msgid "single-thread" msgstr "" -#: ../../library/sqlite3.rst:532 +#: ../../library/sqlite3.rst:535 msgid "0" msgstr "0" -#: ../../library/sqlite3.rst:532 +#: ../../library/sqlite3.rst:535 msgid "Threads may not share the module" msgstr "" -#: ../../library/sqlite3.rst:535 +#: ../../library/sqlite3.rst:538 msgid "multi-thread" msgstr "" -#: ../../library/sqlite3.rst:535 ../../library/sqlite3.rst:538 +#: ../../library/sqlite3.rst:538 ../../library/sqlite3.rst:541 msgid "1" msgstr "1" -#: ../../library/sqlite3.rst:535 +#: ../../library/sqlite3.rst:538 msgid "2" msgstr "2" -#: ../../library/sqlite3.rst:535 +#: ../../library/sqlite3.rst:538 msgid "Threads may share the module, but not connections" msgstr "" -#: ../../library/sqlite3.rst:538 +#: ../../library/sqlite3.rst:541 msgid "serialized" msgstr "" -#: ../../library/sqlite3.rst:538 +#: ../../library/sqlite3.rst:541 msgid "3" msgstr "3" -#: ../../library/sqlite3.rst:538 +#: ../../library/sqlite3.rst:541 msgid "Threads may share the module, connections and cursors" msgstr "" -#: ../../library/sqlite3.rst:545 +#: ../../library/sqlite3.rst:547 msgid "Set *threadsafety* dynamically instead of hard-coding it to ``1``." msgstr "" -#: ../../library/sqlite3.rst:550 +#: ../../library/sqlite3.rst:552 msgid "" "Version number of this module as a :class:`string `. This is not the " "version of the SQLite library." msgstr "" -#: ../../library/sqlite3.rst:553 ../../library/sqlite3.rst:563 +#: ../../library/sqlite3.rst:555 ../../library/sqlite3.rst:565 msgid "" "This constant used to reflect the version number of the ``pysqlite`` " "package, a third-party library which used to upstream changes to :mod:`!" "sqlite3`. Today, it carries no meaning or practical value." msgstr "" -#: ../../library/sqlite3.rst:560 +#: ../../library/sqlite3.rst:562 msgid "" "Version number of this module as a :class:`tuple` of :class:`integers " "`. This is not the version of the SQLite library." msgstr "" -#: ../../library/sqlite3.rst:587 +#: ../../library/sqlite3.rst:589 msgid "" "These constants are used for the :meth:`Connection.setconfig` and :meth:" "`~Connection.getconfig` methods." msgstr "" -#: ../../library/sqlite3.rst:590 +#: ../../library/sqlite3.rst:592 msgid "" "The availability of these constants varies depending on the version of " "SQLite Python was compiled with." msgstr "" -#: ../../library/sqlite3.rst:597 +#: ../../library/sqlite3.rst:599 msgid "https://www.sqlite.org/c3ref/c_dbconfig_defensive.html" msgstr "" -#: ../../library/sqlite3.rst:598 +#: ../../library/sqlite3.rst:600 msgid "SQLite docs: Database Connection Configuration Options" msgstr "" -#: ../../library/sqlite3.rst:604 +#: ../../library/sqlite3.rst:606 msgid "Connection objects" msgstr "" -#: ../../library/sqlite3.rst:608 +#: ../../library/sqlite3.rst:610 msgid "" "Each open SQLite database is represented by a ``Connection`` object, which " "is created using :func:`sqlite3.connect`. Their main purpose is creating :" "class:`Cursor` objects, and :ref:`sqlite3-controlling-transactions`." msgstr "" -#: ../../library/sqlite3.rst:615 +#: ../../library/sqlite3.rst:617 msgid ":ref:`sqlite3-connection-shortcuts`" msgstr "" -#: ../../library/sqlite3.rst:621 +#: ../../library/sqlite3.rst:623 msgid "" "A :exc:`ResourceWarning` is emitted if :meth:`close` is not called before a :" "class:`!Connection` object is deleted." msgstr "" -#: ../../library/sqlite3.rst:624 +#: ../../library/sqlite3.rst:626 msgid "An SQLite database connection has the following attributes and methods:" msgstr "" -#: ../../library/sqlite3.rst:628 +#: ../../library/sqlite3.rst:630 msgid "" "Create and return a :class:`Cursor` object. The cursor method accepts a " "single optional parameter *factory*. If supplied, this must be a :term:" "`callable` returning an instance of :class:`Cursor` or its subclasses." msgstr "" -#: ../../library/sqlite3.rst:635 +#: ../../library/sqlite3.rst:637 msgid "" "Open a :class:`Blob` handle to an existing :abbr:`BLOB (Binary Large " "OBject)`." msgstr "" -#: ../../library/sqlite3.rst:638 +#: ../../library/sqlite3.rst:640 msgid "The name of the table where the blob is located." msgstr "" -#: ../../library/sqlite3.rst:641 +#: ../../library/sqlite3.rst:643 msgid "The name of the column where the blob is located." msgstr "" -#: ../../library/sqlite3.rst:644 +#: ../../library/sqlite3.rst:646 msgid "The name of the row where the blob is located." msgstr "" -#: ../../library/sqlite3.rst:647 +#: ../../library/sqlite3.rst:649 msgid "" "Set to ``True`` if the blob should be opened without write permissions. " "Defaults to ``False``." msgstr "" -#: ../../library/sqlite3.rst:652 +#: ../../library/sqlite3.rst:654 msgid "" "The name of the database where the blob is located. Defaults to ``\"main\"``." msgstr "" #: ../../library/sqlite3.rst:0 msgid "Raises" -msgstr "" +msgstr "Levanta" -#: ../../library/sqlite3.rst:656 +#: ../../library/sqlite3.rst:658 msgid "When trying to open a blob in a ``WITHOUT ROWID`` table." msgstr "" -#: ../../library/sqlite3.rst:663 +#: ../../library/sqlite3.rst:665 msgid "" "The blob size cannot be changed using the :class:`Blob` class. Use the SQL " "function ``zeroblob`` to create a blob with a fixed size." msgstr "" -#: ../../library/sqlite3.rst:670 +#: ../../library/sqlite3.rst:672 msgid "" "Commit any pending transaction to the database. If :attr:`autocommit` is " "``True``, or there is no open transaction, this method does nothing. If :" @@ -842,7 +999,7 @@ msgid "" "pending transaction was committed by this method." msgstr "" -#: ../../library/sqlite3.rst:678 +#: ../../library/sqlite3.rst:680 msgid "" "Roll back to the start of any pending transaction. If :attr:`autocommit` is " "``True``, or there is no open transaction, this method does nothing. If :" @@ -850,7 +1007,7 @@ msgid "" "pending transaction was rolled back by this method." msgstr "" -#: ../../library/sqlite3.rst:686 +#: ../../library/sqlite3.rst:688 msgid "" "Close the database connection. If :attr:`autocommit` is ``False``, any " "pending transaction is implicitly rolled back. If :attr:`!autocommit` is " @@ -859,83 +1016,96 @@ msgid "" "losing pending changes." msgstr "" -#: ../../library/sqlite3.rst:696 +#: ../../library/sqlite3.rst:698 msgid "" "Create a new :class:`Cursor` object and call :meth:`~Cursor.execute` on it " "with the given *sql* and *parameters*. Return the new cursor object." msgstr "" -#: ../../library/sqlite3.rst:702 +#: ../../library/sqlite3.rst:704 msgid "" "Create a new :class:`Cursor` object and call :meth:`~Cursor.executemany` on " "it with the given *sql* and *parameters*. Return the new cursor object." msgstr "" -#: ../../library/sqlite3.rst:708 +#: ../../library/sqlite3.rst:710 msgid "" "Create a new :class:`Cursor` object and call :meth:`~Cursor.executescript` " "on it with the given *sql_script*. Return the new cursor object." msgstr "" -#: ../../library/sqlite3.rst:714 +#: ../../library/sqlite3.rst:716 msgid "Create or remove a user-defined SQL function." msgstr "" -#: ../../library/sqlite3.rst:716 +#: ../../library/sqlite3.rst:718 msgid "The name of the SQL function." msgstr "O nome da função SQL." -#: ../../library/sqlite3.rst:719 +#: ../../library/sqlite3.rst:721 msgid "" "The number of arguments the SQL function can accept. If ``-1``, it may take " "any number of arguments." msgstr "" -#: ../../library/sqlite3.rst:723 +#: ../../library/sqlite3.rst:725 msgid "" "A :term:`callable` that is called when the SQL function is invoked. The " "callable must return :ref:`a type natively supported by SQLite `. Set to ``None`` to remove an existing SQL function." msgstr "" -#: ../../library/sqlite3.rst:730 +#: ../../library/sqlite3.rst:732 msgid "" "If ``True``, the created SQL function is marked as `deterministic `_, which allows SQLite to perform additional " "optimizations." msgstr "" -#: ../../library/sqlite3.rst:735 +#: ../../library/sqlite3.rst:737 msgid "Added the *deterministic* parameter." msgstr "" -#: ../../library/sqlite3.rst:738 ../../library/sqlite3.rst:782 -#: ../../library/sqlite3.rst:850 ../../library/sqlite3.rst:1129 -#: ../../library/sqlite3.rst:1551 ../../library/sqlite3.rst:1594 +#: ../../library/sqlite3.rst:740 ../../library/sqlite3.rst:784 +#: ../../library/sqlite3.rst:852 ../../library/sqlite3.rst:1131 +#: ../../library/sqlite3.rst:1553 ../../library/sqlite3.rst:1596 msgid "Example:" msgstr "Exemplo:" -#: ../../library/sqlite3.rst:754 +#: ../../library/sqlite3.rst:742 +msgid "" +">>> import hashlib\n" +">>> def md5sum(t):\n" +"... return hashlib.md5(t).hexdigest()\n" +">>> con = sqlite3.connect(\":memory:\")\n" +">>> con.create_function(\"md5\", 1, md5sum)\n" +">>> for row in con.execute(\"SELECT md5(?)\", (b\"foo\",)):\n" +"... print(row)\n" +"('acbd18db4cc2f85cedef654fccc4a4d8',)\n" +">>> con.close()" +msgstr "" + +#: ../../library/sqlite3.rst:756 msgid "" "Passing *name*, *narg*, and *func* as keyword arguments is deprecated. These " "parameters will become positional-only in Python 3.15." msgstr "" -#: ../../library/sqlite3.rst:760 +#: ../../library/sqlite3.rst:762 msgid "Create or remove a user-defined SQL aggregate function." msgstr "" -#: ../../library/sqlite3.rst:762 +#: ../../library/sqlite3.rst:764 msgid "The name of the SQL aggregate function." msgstr "" -#: ../../library/sqlite3.rst:765 +#: ../../library/sqlite3.rst:767 msgid "" "The number of arguments the SQL aggregate function can accept. If ``-1``, it " "may take any number of arguments." msgstr "" -#: ../../library/sqlite3.rst:769 +#: ../../library/sqlite3.rst:771 msgid "" "A class must implement the following methods: * ``step()``: Add a row to " "the aggregate. * ``finalize()``: Return the final result of the aggregate " @@ -944,51 +1114,74 @@ msgid "" "*n_arg*. Set to ``None`` to remove an existing SQL aggregate function." msgstr "" -#: ../../library/sqlite3.rst:770 +#: ../../library/sqlite3.rst:772 msgid "A class must implement the following methods:" msgstr "Uma classe deve implementar os seguintes métodos:" -#: ../../library/sqlite3.rst:772 +#: ../../library/sqlite3.rst:774 msgid "``step()``: Add a row to the aggregate." msgstr "" -#: ../../library/sqlite3.rst:773 ../../library/sqlite3.rst:834 +#: ../../library/sqlite3.rst:775 ../../library/sqlite3.rst:836 msgid "" "``finalize()``: Return the final result of the aggregate as :ref:`a type " "natively supported by SQLite `." msgstr "" -#: ../../library/sqlite3.rst:776 +#: ../../library/sqlite3.rst:778 msgid "" "The number of arguments that the ``step()`` method must accept is controlled " "by *n_arg*." msgstr "" -#: ../../library/sqlite3.rst:779 +#: ../../library/sqlite3.rst:781 msgid "Set to ``None`` to remove an existing SQL aggregate function." msgstr "" -#: ../../library/sqlite3.rst:813 +#: ../../library/sqlite3.rst:786 +msgid "" +"class MySum:\n" +" def __init__(self):\n" +" self.count = 0\n" +"\n" +" def step(self, value):\n" +" self.count += value\n" +"\n" +" def finalize(self):\n" +" return self.count\n" +"\n" +"con = sqlite3.connect(\":memory:\")\n" +"con.create_aggregate(\"mysum\", 1, MySum)\n" +"cur = con.execute(\"CREATE TABLE test(i)\")\n" +"cur.execute(\"INSERT INTO test(i) VALUES(1)\")\n" +"cur.execute(\"INSERT INTO test(i) VALUES(2)\")\n" +"cur.execute(\"SELECT mysum(i) FROM test\")\n" +"print(cur.fetchone()[0])\n" +"\n" +"con.close()" +msgstr "" + +#: ../../library/sqlite3.rst:815 msgid "" "Passing *name*, *n_arg*, and *aggregate_class* as keyword arguments is " "deprecated. These parameters will become positional-only in Python 3.15." msgstr "" -#: ../../library/sqlite3.rst:819 +#: ../../library/sqlite3.rst:821 msgid "Create or remove a user-defined aggregate window function." msgstr "" -#: ../../library/sqlite3.rst:821 +#: ../../library/sqlite3.rst:823 msgid "The name of the SQL aggregate window function to create or remove." msgstr "" -#: ../../library/sqlite3.rst:824 +#: ../../library/sqlite3.rst:826 msgid "" "The number of arguments the SQL aggregate window function can accept. If " "``-1``, it may take any number of arguments." msgstr "" -#: ../../library/sqlite3.rst:828 +#: ../../library/sqlite3.rst:830 msgid "" "A class that must implement the following methods: * ``step()``: Add a row " "to the current window. * ``value()``: Return the current value of the " @@ -1000,79 +1193,148 @@ msgid "" "function." msgstr "" -#: ../../library/sqlite3.rst:829 +#: ../../library/sqlite3.rst:831 msgid "A class that must implement the following methods:" msgstr "Uma classe que deve implementar os seguintes métodos:" -#: ../../library/sqlite3.rst:831 +#: ../../library/sqlite3.rst:833 msgid "``step()``: Add a row to the current window." msgstr "" -#: ../../library/sqlite3.rst:832 +#: ../../library/sqlite3.rst:834 msgid "``value()``: Return the current value of the aggregate." msgstr "" -#: ../../library/sqlite3.rst:833 +#: ../../library/sqlite3.rst:835 msgid "``inverse()``: Remove a row from the current window." msgstr "" -#: ../../library/sqlite3.rst:837 +#: ../../library/sqlite3.rst:839 msgid "" "The number of arguments that the ``step()`` and ``value()`` methods must " "accept is controlled by *num_params*." msgstr "" -#: ../../library/sqlite3.rst:840 +#: ../../library/sqlite3.rst:842 msgid "Set to ``None`` to remove an existing SQL aggregate window function." msgstr "" -#: ../../library/sqlite3.rst:842 +#: ../../library/sqlite3.rst:844 msgid "" "If used with a version of SQLite older than 3.25.0, which does not support " "aggregate window functions." msgstr "" -#: ../../library/sqlite3.rst:906 +#: ../../library/sqlite3.rst:854 +msgid "" +"# Example taken from https://www.sqlite.org/windowfunctions.html#udfwinfunc\n" +"class WindowSumInt:\n" +" def __init__(self):\n" +" self.count = 0\n" +"\n" +" def step(self, value):\n" +" \"\"\"Add a row to the current window.\"\"\"\n" +" self.count += value\n" +"\n" +" def value(self):\n" +" \"\"\"Return the current value of the aggregate.\"\"\"\n" +" return self.count\n" +"\n" +" def inverse(self, value):\n" +" \"\"\"Remove a row from the current window.\"\"\"\n" +" self.count -= value\n" +"\n" +" def finalize(self):\n" +" \"\"\"Return the final value of the aggregate.\n" +"\n" +" Any clean-up actions should be placed here.\n" +" \"\"\"\n" +" return self.count\n" +"\n" +"\n" +"con = sqlite3.connect(\":memory:\")\n" +"cur = con.execute(\"CREATE TABLE test(x, y)\")\n" +"values = [\n" +" (\"a\", 4),\n" +" (\"b\", 5),\n" +" (\"c\", 3),\n" +" (\"d\", 8),\n" +" (\"e\", 1),\n" +"]\n" +"cur.executemany(\"INSERT INTO test VALUES(?, ?)\", values)\n" +"con.create_window_function(\"sumint\", 1, WindowSumInt)\n" +"cur.execute(\"\"\"\n" +" SELECT x, sumint(y) OVER (\n" +" ORDER BY x ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING\n" +" ) AS sum_y\n" +" FROM test ORDER BY x\n" +"\"\"\")\n" +"print(cur.fetchall())\n" +"con.close()" +msgstr "" + +#: ../../library/sqlite3.rst:908 msgid "" "Create a collation named *name* using the collating function *callable*. " "*callable* is passed two :class:`string ` arguments, and it should " "return an :class:`integer `:" msgstr "" -#: ../../library/sqlite3.rst:910 +#: ../../library/sqlite3.rst:912 msgid "``1`` if the first is ordered higher than the second" msgstr "" -#: ../../library/sqlite3.rst:911 +#: ../../library/sqlite3.rst:913 msgid "``-1`` if the first is ordered lower than the second" msgstr "" -#: ../../library/sqlite3.rst:912 +#: ../../library/sqlite3.rst:914 msgid "``0`` if they are ordered equal" msgstr "" -#: ../../library/sqlite3.rst:914 +#: ../../library/sqlite3.rst:916 msgid "The following example shows a reverse sorting collation:" msgstr "" -#: ../../library/sqlite3.rst:942 -msgid "Remove a collation function by setting *callable* to ``None``." +#: ../../library/sqlite3.rst:918 +msgid "" +"def collate_reverse(string1, string2):\n" +" if string1 == string2:\n" +" return 0\n" +" elif string1 < string2:\n" +" return 1\n" +" else:\n" +" return -1\n" +"\n" +"con = sqlite3.connect(\":memory:\")\n" +"con.create_collation(\"reverse\", collate_reverse)\n" +"\n" +"cur = con.execute(\"CREATE TABLE test(x)\")\n" +"cur.executemany(\"INSERT INTO test(x) VALUES(?)\", [(\"a\",), (\"b\",)])\n" +"cur.execute(\"SELECT x FROM test ORDER BY x COLLATE reverse\")\n" +"for row in cur:\n" +" print(row)\n" +"con.close()" msgstr "" #: ../../library/sqlite3.rst:944 +msgid "Remove a collation function by setting *callable* to ``None``." +msgstr "" + +#: ../../library/sqlite3.rst:946 msgid "" "The collation name can contain any Unicode character. Earlier, only ASCII " "characters were allowed." msgstr "" -#: ../../library/sqlite3.rst:951 +#: ../../library/sqlite3.rst:953 msgid "" "Call this method from a different thread to abort any queries that might be " "executing on the connection. Aborted queries will raise an :exc:" "`OperationalError`." msgstr "" -#: ../../library/sqlite3.rst:958 +#: ../../library/sqlite3.rst:960 msgid "" "Register :term:`callable` *authorizer_callback* to be invoked for each " "attempt to access a column of a table in the database. The callback should " @@ -1081,7 +1343,7 @@ msgid "" "underlying SQLite library." msgstr "" -#: ../../library/sqlite3.rst:965 +#: ../../library/sqlite3.rst:967 msgid "" "The first argument to the callback signifies what kind of operation is to be " "authorized. The second and third argument will be arguments or ``None`` " @@ -1091,7 +1353,7 @@ msgid "" "attempt or ``None`` if this access attempt is directly from input SQL code." msgstr "" -#: ../../library/sqlite3.rst:972 +#: ../../library/sqlite3.rst:974 msgid "" "Please consult the SQLite documentation about the possible values for the " "first argument and the meaning of the second and third argument depending on " @@ -1099,21 +1361,21 @@ msgid "" "module." msgstr "" -#: ../../library/sqlite3.rst:976 +#: ../../library/sqlite3.rst:978 msgid "Passing ``None`` as *authorizer_callback* will disable the authorizer." msgstr "" -#: ../../library/sqlite3.rst:978 +#: ../../library/sqlite3.rst:980 msgid "Added support for disabling the authorizer using ``None``." msgstr "" -#: ../../library/sqlite3.rst:981 +#: ../../library/sqlite3.rst:983 msgid "" "Passing *authorizer_callback* as a keyword argument is deprecated. The " "parameter will become positional-only in Python 3.15." msgstr "" -#: ../../library/sqlite3.rst:988 +#: ../../library/sqlite3.rst:990 msgid "" "Register :term:`callable` *progress_handler* to be invoked for every *n* " "instructions of the SQLite virtual machine. This is useful if you want to " @@ -1121,32 +1383,32 @@ msgid "" "a GUI." msgstr "" -#: ../../library/sqlite3.rst:993 +#: ../../library/sqlite3.rst:995 msgid "" "If you want to clear any previously installed progress handler, call the " "method with ``None`` for *progress_handler*." msgstr "" -#: ../../library/sqlite3.rst:996 +#: ../../library/sqlite3.rst:998 msgid "" "Returning a non-zero value from the handler function will terminate the " "currently executing query and cause it to raise a :exc:`DatabaseError` " "exception." msgstr "" -#: ../../library/sqlite3.rst:1000 +#: ../../library/sqlite3.rst:1002 msgid "" "Passing *progress_handler* as a keyword argument is deprecated. The " "parameter will become positional-only in Python 3.15." msgstr "" -#: ../../library/sqlite3.rst:1007 +#: ../../library/sqlite3.rst:1009 msgid "" "Register :term:`callable` *trace_callback* to be invoked for each SQL " "statement that is actually executed by the SQLite backend." msgstr "" -#: ../../library/sqlite3.rst:1010 +#: ../../library/sqlite3.rst:1012 msgid "" "The only argument passed to the callback is the statement (as :class:`str`) " "that is being executed. The return value of the callback is ignored. Note " @@ -1156,24 +1418,24 @@ msgid "" "execution of triggers defined in the current database." msgstr "" -#: ../../library/sqlite3.rst:1018 +#: ../../library/sqlite3.rst:1020 msgid "Passing ``None`` as *trace_callback* will disable the trace callback." msgstr "" -#: ../../library/sqlite3.rst:1021 +#: ../../library/sqlite3.rst:1023 msgid "" "Exceptions raised in the trace callback are not propagated. As a development " "and debugging aid, use :meth:`~sqlite3.enable_callback_tracebacks` to enable " "printing tracebacks from exceptions raised in the trace callback." msgstr "" -#: ../../library/sqlite3.rst:1028 +#: ../../library/sqlite3.rst:1030 msgid "" "Passing *trace_callback* as a keyword argument is deprecated. The parameter " "will become positional-only in Python 3.15." msgstr "" -#: ../../library/sqlite3.rst:1035 +#: ../../library/sqlite3.rst:1037 msgid "" "Enable the SQLite engine to load SQLite extensions from shared libraries if " "*enabled* is ``True``; else, disallow loading SQLite extensions. SQLite " @@ -1182,7 +1444,7 @@ msgid "" "distributed with SQLite." msgstr "" -#: ../../library/sqlite3.rst:1044 +#: ../../library/sqlite3.rst:1046 msgid "" "The :mod:`!sqlite3` module is not built with loadable extension support by " "default, because some platforms (notably macOS) have SQLite libraries which " @@ -1191,7 +1453,7 @@ msgid "" "program:`configure`." msgstr "" -#: ../../library/sqlite3.rst:1051 +#: ../../library/sqlite3.rst:1053 msgid "" "Raises an :ref:`auditing event ` ``sqlite3.enable_load_extension`` " "with arguments ``connection``, ``enabled``." @@ -1199,28 +1461,58 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``sqlite3." "enable_load_extension`` com os argumentos ``connection``, ``enabled``." -#: ../../library/sqlite3.rst:1055 +#: ../../library/sqlite3.rst:1057 msgid "Added the ``sqlite3.enable_load_extension`` auditing event." msgstr "" -#: ../../library/sqlite3.rst:1087 +#: ../../library/sqlite3.rst:1063 +msgid "" +"con.enable_load_extension(True)\n" +"\n" +"# Load the fulltext search extension\n" +"con.execute(\"select load_extension('./fts3.so')\")\n" +"\n" +"# alternatively you can load the extension using an API call:\n" +"# con.load_extension(\"./fts3.so\")\n" +"\n" +"# disable extension loading again\n" +"con.enable_load_extension(False)\n" +"\n" +"# example from SQLite wiki\n" +"con.execute(\"CREATE VIRTUAL TABLE recipe USING fts3(name, ingredients)\")\n" +"con.executescript(\"\"\"\n" +" INSERT INTO recipe (name, ingredients) VALUES('broccoli stew', 'broccoli " +"peppers cheese tomatoes');\n" +" INSERT INTO recipe (name, ingredients) VALUES('pumpkin stew', 'pumpkin " +"onions garlic celery');\n" +" INSERT INTO recipe (name, ingredients) VALUES('broccoli pie', 'broccoli " +"cheese onions flour');\n" +" INSERT INTO recipe (name, ingredients) VALUES('pumpkin pie', 'pumpkin " +"sugar flour butter');\n" +" \"\"\")\n" +"for row in con.execute(\"SELECT rowid, name, ingredients FROM recipe WHERE " +"name MATCH 'pie'\"):\n" +" print(row)" +msgstr "" + +#: ../../library/sqlite3.rst:1089 msgid "" "Load an SQLite extension from a shared library. Enable extension loading " "with :meth:`enable_load_extension` before calling this method." msgstr "" -#: ../../library/sqlite3.rst:1091 +#: ../../library/sqlite3.rst:1093 msgid "The path to the SQLite extension." msgstr "" -#: ../../library/sqlite3.rst:1095 +#: ../../library/sqlite3.rst:1097 msgid "" "Entry point name. If ``None`` (the default), SQLite will come up with an " "entry point name of its own; see the SQLite docs `Loading an Extension`_ for " "details." msgstr "" -#: ../../library/sqlite3.rst:1104 +#: ../../library/sqlite3.rst:1106 msgid "" "Raises an :ref:`auditing event ` ``sqlite3.load_extension`` with " "arguments ``connection``, ``path``." @@ -1228,57 +1520,67 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``sqlite3.load_extension`` " "com os argumentos ``connection``, ``path``." -#: ../../library/sqlite3.rst:1108 +#: ../../library/sqlite3.rst:1110 msgid "Added the ``sqlite3.load_extension`` auditing event." msgstr "" -#: ../../library/sqlite3.rst:1111 +#: ../../library/sqlite3.rst:1113 msgid "Added the *entrypoint* parameter." msgstr "" -#: ../../library/sqlite3.rst:1118 +#: ../../library/sqlite3.rst:1120 msgid "" "Return an :term:`iterator` to dump the database as SQL source code. Useful " "when saving an in-memory database for later restoration. Similar to the ``." "dump`` command in the :program:`sqlite3` shell." msgstr "" -#: ../../library/sqlite3.rst:1122 +#: ../../library/sqlite3.rst:1124 msgid "" "An optional ``LIKE`` pattern for database objects to dump, e.g. " "``prefix_%``. If ``None`` (the default), all database objects will be " "included." msgstr "" -#: ../../library/sqlite3.rst:1142 ../../library/sqlite3.rst:1216 -msgid ":ref:`sqlite3-howto-encoding`" +#: ../../library/sqlite3.rst:1133 +msgid "" +"# Convert file example.db to SQL dump file dump.sql\n" +"con = sqlite3.connect('example.db')\n" +"with open('dump.sql', 'w') as f:\n" +" for line in con.iterdump():\n" +" f.write('%s\\n' % line)\n" +"con.close()" msgstr "" -#: ../../library/sqlite3.rst:1144 +#: ../../library/sqlite3.rst:1144 ../../library/sqlite3.rst:1218 +msgid ":ref:`sqlite3-howto-encoding`" +msgstr ":ref:`sqlite3-howto-encoding`" + +#: ../../library/sqlite3.rst:1146 msgid "Added the *filter* parameter." msgstr "Adicionado o parâmetro *filter*." -#: ../../library/sqlite3.rst:1149 +#: ../../library/sqlite3.rst:1151 msgid "Create a backup of an SQLite database." msgstr "" -#: ../../library/sqlite3.rst:1151 +#: ../../library/sqlite3.rst:1153 msgid "" "Works even if the database is being accessed by other clients or " "concurrently by the same connection." msgstr "" -#: ../../library/sqlite3.rst:1154 +#: ../../library/sqlite3.rst:1156 msgid "The database connection to save the backup to." msgstr "" -#: ../../library/sqlite3.rst:1157 +#: ../../library/sqlite3.rst:1159 msgid "" "The number of pages to copy at a time. If equal to or less than ``0``, the " "entire database is copied in a single step. Defaults to ``-1``." msgstr "" -#: ../../library/sqlite3.rst:1163 +#: ../../library/sqlite3.rst:1165 msgid "" "If set to a :term:`callable`, it is invoked with three integer arguments for " "every backup iteration: the *status* of the last iteration, the *remaining* " @@ -1286,46 +1588,74 @@ msgid "" "Defaults to ``None``." msgstr "" -#: ../../library/sqlite3.rst:1172 +#: ../../library/sqlite3.rst:1174 msgid "" "The name of the database to back up. Either ``\"main\"`` (the default) for " "the main database, ``\"temp\"`` for the temporary database, or the name of a " "custom database as attached using the ``ATTACH DATABASE`` SQL statement." msgstr "" -#: ../../library/sqlite3.rst:1179 +#: ../../library/sqlite3.rst:1181 msgid "" "The number of seconds to sleep between successive attempts to back up " "remaining pages." msgstr "" -#: ../../library/sqlite3.rst:1183 +#: ../../library/sqlite3.rst:1185 msgid "Example 1, copy an existing database into another:" msgstr "" -#: ../../library/sqlite3.rst:1202 +#: ../../library/sqlite3.rst:1187 +msgid "" +"def progress(status, remaining, total):\n" +" print(f'Copied {total-remaining} of {total} pages...')\n" +"\n" +"src = sqlite3.connect('example.db')\n" +"dst = sqlite3.connect('backup.db')\n" +"with dst:\n" +" src.backup(dst, pages=1, progress=progress)\n" +"dst.close()\n" +"src.close()" +msgstr "" + +#: ../../library/sqlite3.rst:1204 msgid "Example 2, copy an existing database into a transient copy:" msgstr "" -#: ../../library/sqlite3.rst:1220 -msgid "Get a connection runtime limit." +#: ../../library/sqlite3.rst:1206 +msgid "" +"src = sqlite3.connect('example.db')\n" +"dst = sqlite3.connect(':memory:')\n" +"src.backup(dst)\n" +"dst.close()\n" +"src.close()" msgstr "" #: ../../library/sqlite3.rst:1222 +msgid "Get a connection runtime limit." +msgstr "" + +#: ../../library/sqlite3.rst:1224 msgid "The `SQLite limit category`_ to be queried." msgstr "" -#: ../../library/sqlite3.rst:1227 ../../library/sqlite3.rst:1264 +#: ../../library/sqlite3.rst:1229 ../../library/sqlite3.rst:1266 msgid "If *category* is not recognised by the underlying SQLite library." msgstr "" -#: ../../library/sqlite3.rst:1230 +#: ../../library/sqlite3.rst:1232 msgid "" "Example, query the maximum length of an SQL statement for :class:" "`Connection` ``con`` (the default is 1000000000):" msgstr "" -#: ../../library/sqlite3.rst:1250 +#: ../../library/sqlite3.rst:1242 +msgid "" +">>> con.getlimit(sqlite3.SQLITE_LIMIT_SQL_LENGTH)\n" +"1000000000" +msgstr "" + +#: ../../library/sqlite3.rst:1252 msgid "" "Set a connection runtime limit. Attempts to increase a limit above its hard " "upper bound are silently truncated to the hard upper bound. Regardless of " @@ -1333,40 +1663,48 @@ msgid "" "returned." msgstr "" -#: ../../library/sqlite3.rst:1255 +#: ../../library/sqlite3.rst:1257 msgid "The `SQLite limit category`_ to be set." msgstr "" -#: ../../library/sqlite3.rst:1258 +#: ../../library/sqlite3.rst:1260 msgid "" "The value of the new limit. If negative, the current limit is unchanged." msgstr "" -#: ../../library/sqlite3.rst:1267 +#: ../../library/sqlite3.rst:1269 msgid "" "Example, limit the number of attached databases to 1 for :class:`Connection` " "``con`` (the default limit is 10):" msgstr "" -#: ../../library/sqlite3.rst:1288 +#: ../../library/sqlite3.rst:1272 +msgid "" +">>> con.setlimit(sqlite3.SQLITE_LIMIT_ATTACHED, 1)\n" +"10\n" +">>> con.getlimit(sqlite3.SQLITE_LIMIT_ATTACHED)\n" +"1" +msgstr "" + +#: ../../library/sqlite3.rst:1290 msgid "Query a boolean connection configuration option." msgstr "" -#: ../../library/sqlite3.rst:1290 ../../library/sqlite3.rst:1301 +#: ../../library/sqlite3.rst:1292 ../../library/sqlite3.rst:1303 msgid "A :ref:`SQLITE_DBCONFIG code `." msgstr "" -#: ../../library/sqlite3.rst:1299 +#: ../../library/sqlite3.rst:1301 msgid "Set a boolean connection configuration option." msgstr "" -#: ../../library/sqlite3.rst:1304 +#: ../../library/sqlite3.rst:1306 msgid "" "``True`` if the configuration option should be enabled (default); ``False`` " "if it should be disabled." msgstr "" -#: ../../library/sqlite3.rst:1312 +#: ../../library/sqlite3.rst:1314 msgid "" "Serialize a database into a :class:`bytes` object. For an ordinary on-disk " "database file, the serialization is just a copy of the disk file. For an in-" @@ -1375,17 +1713,17 @@ msgid "" "backed up to disk." msgstr "" -#: ../../library/sqlite3.rst:1318 +#: ../../library/sqlite3.rst:1320 msgid "The database name to be serialized. Defaults to ``\"main\"``." msgstr "" -#: ../../library/sqlite3.rst:1326 +#: ../../library/sqlite3.rst:1328 msgid "" "This method is only available if the underlying SQLite library has the " "serialize API." msgstr "" -#: ../../library/sqlite3.rst:1334 +#: ../../library/sqlite3.rst:1336 msgid "" "Deserialize a :meth:`serialized ` database into a :class:" "`Connection`. This method causes the database connection to disconnect from " @@ -1393,96 +1731,96 @@ msgid "" "serialization contained in *data*." msgstr "" -#: ../../library/sqlite3.rst:1340 +#: ../../library/sqlite3.rst:1342 msgid "A serialized database." msgstr "" -#: ../../library/sqlite3.rst:1343 +#: ../../library/sqlite3.rst:1345 msgid "The database name to deserialize into. Defaults to ``\"main\"``." msgstr "" -#: ../../library/sqlite3.rst:1347 +#: ../../library/sqlite3.rst:1349 msgid "" "If the database connection is currently involved in a read transaction or a " "backup operation." msgstr "" -#: ../../library/sqlite3.rst:1351 +#: ../../library/sqlite3.rst:1353 msgid "If *data* does not contain a valid SQLite database." msgstr "" -#: ../../library/sqlite3.rst:1354 +#: ../../library/sqlite3.rst:1356 msgid "If :func:`len(data) ` is larger than ``2**63 - 1``." msgstr "" -#: ../../library/sqlite3.rst:1359 +#: ../../library/sqlite3.rst:1361 msgid "" "This method is only available if the underlying SQLite library has the " "deserialize API." msgstr "" -#: ../../library/sqlite3.rst:1366 +#: ../../library/sqlite3.rst:1368 msgid "" "This attribute controls :pep:`249`-compliant transaction behaviour. :attr:`!" "autocommit` has three allowed values:" msgstr "" -#: ../../library/sqlite3.rst:1369 +#: ../../library/sqlite3.rst:1371 msgid "" "``False``: Select :pep:`249`-compliant transaction behaviour, implying that :" "mod:`!sqlite3` ensures a transaction is always open. Use :meth:`commit` and :" "meth:`rollback` to close transactions." msgstr "" -#: ../../library/sqlite3.rst:1373 +#: ../../library/sqlite3.rst:1375 msgid "This is the recommended value of :attr:`!autocommit`." msgstr "" -#: ../../library/sqlite3.rst:1375 +#: ../../library/sqlite3.rst:1377 msgid "" "``True``: Use SQLite's `autocommit mode`_. :meth:`commit` and :meth:" "`rollback` have no effect in this mode." msgstr "" -#: ../../library/sqlite3.rst:1378 +#: ../../library/sqlite3.rst:1380 msgid "" ":data:`LEGACY_TRANSACTION_CONTROL`: Pre-Python 3.12 (non-:pep:`249`-" "compliant) transaction control. See :attr:`isolation_level` for more details." msgstr "" -#: ../../library/sqlite3.rst:1382 +#: ../../library/sqlite3.rst:1384 msgid "This is currently the default value of :attr:`!autocommit`." msgstr "" -#: ../../library/sqlite3.rst:1384 +#: ../../library/sqlite3.rst:1386 msgid "" "Changing :attr:`!autocommit` to ``False`` will open a new transaction, and " "changing it to ``True`` will commit any pending transaction." msgstr "" -#: ../../library/sqlite3.rst:1387 +#: ../../library/sqlite3.rst:1389 msgid "See :ref:`sqlite3-transaction-control-autocommit` for more details." msgstr "" -#: ../../library/sqlite3.rst:1391 +#: ../../library/sqlite3.rst:1393 msgid "" "The :attr:`isolation_level` attribute has no effect unless :attr:" "`autocommit` is :data:`LEGACY_TRANSACTION_CONTROL`." msgstr "" -#: ../../library/sqlite3.rst:1398 +#: ../../library/sqlite3.rst:1400 msgid "" "This read-only attribute corresponds to the low-level SQLite `autocommit " "mode`_." msgstr "" -#: ../../library/sqlite3.rst:1401 +#: ../../library/sqlite3.rst:1403 msgid "" "``True`` if a transaction is active (there are uncommitted changes), " "``False`` otherwise." msgstr "" -#: ../../library/sqlite3.rst:1408 +#: ../../library/sqlite3.rst:1410 msgid "" "Controls the :ref:`legacy transaction handling mode ` of :mod:`!sqlite3`. If set to ``None``, " @@ -1492,13 +1830,13 @@ msgid "" "` is performed." msgstr "" -#: ../../library/sqlite3.rst:1416 +#: ../../library/sqlite3.rst:1418 msgid "" "If not overridden by the *isolation_level* parameter of :func:`connect`, the " "default is ``\"\"``, which is an alias for ``\"DEFERRED\"``." msgstr "" -#: ../../library/sqlite3.rst:1421 +#: ../../library/sqlite3.rst:1423 msgid "" "Using :attr:`autocommit` to control transaction handling is recommended over " "using :attr:`!isolation_level`. :attr:`!isolation_level` has no effect " @@ -1506,7 +1844,7 @@ msgid "" "default)." msgstr "" -#: ../../library/sqlite3.rst:1428 +#: ../../library/sqlite3.rst:1430 msgid "" "The initial :attr:`~Cursor.row_factory` for :class:`Cursor` objects created " "from this connection. Assigning to this attribute does not affect the :attr:" @@ -1515,33 +1853,33 @@ msgid "" "`tuple`." msgstr "" -#: ../../library/sqlite3.rst:1435 ../../library/sqlite3.rst:1721 -#: ../../library/sqlite3.rst:1744 +#: ../../library/sqlite3.rst:1437 ../../library/sqlite3.rst:1723 +#: ../../library/sqlite3.rst:1746 msgid "See :ref:`sqlite3-howto-row-factory` for more details." -msgstr "" +msgstr "Consulte :ref:`sqlite3-howto-row-factory` para mais detalhes." -#: ../../library/sqlite3.rst:1439 +#: ../../library/sqlite3.rst:1441 msgid "" "A :term:`callable` that accepts a :class:`bytes` parameter and returns a " "text representation of it. The callable is invoked for SQLite values with " "the ``TEXT`` data type. By default, this attribute is set to :class:`str`." msgstr "" -#: ../../library/sqlite3.rst:1444 +#: ../../library/sqlite3.rst:1446 msgid "See :ref:`sqlite3-howto-encoding` for more details." -msgstr "" +msgstr "Consulte :ref:`sqlite3-howto-encoding` para mais detalhes." -#: ../../library/sqlite3.rst:1448 +#: ../../library/sqlite3.rst:1450 msgid "" "Return the total number of database rows that have been modified, inserted, " "or deleted since the database connection was opened." msgstr "" -#: ../../library/sqlite3.rst:1455 +#: ../../library/sqlite3.rst:1457 msgid "Cursor objects" msgstr "" -#: ../../library/sqlite3.rst:1457 +#: ../../library/sqlite3.rst:1459 msgid "" "A ``Cursor`` object represents a `database cursor`_ which is used to execute " "SQL statements, and manage the context of a fetch operation. Cursors are " @@ -1549,39 +1887,45 @@ msgid "" "`connection shortcut methods `." msgstr "" -#: ../../library/sqlite3.rst:1464 +#: ../../library/sqlite3.rst:1466 msgid "" "Cursor objects are :term:`iterators `, meaning that if you :meth:" "`~Cursor.execute` a ``SELECT`` query, you can simply iterate over the cursor " "to fetch the resulting rows:" msgstr "" -#: ../../library/sqlite3.rst:1489 +#: ../../library/sqlite3.rst:1477 +msgid "" +"for row in cur.execute(\"SELECT t FROM data\"):\n" +" print(row)" +msgstr "" + +#: ../../library/sqlite3.rst:1491 msgid "A :class:`Cursor` instance has the following attributes and methods." msgstr "" -#: ../../library/sqlite3.rst:1496 +#: ../../library/sqlite3.rst:1498 msgid "" "Execute a single SQL statement, optionally binding Python values using :ref:" "`placeholders `." msgstr "" -#: ../../library/sqlite3.rst:1500 +#: ../../library/sqlite3.rst:1502 msgid "A single SQL statement." msgstr "" -#: ../../library/sqlite3.rst:1503 +#: ../../library/sqlite3.rst:1505 msgid "" "Python values to bind to placeholders in *sql*. A :class:`!dict` if named " "placeholders are used. A :term:`!sequence` if unnamed placeholders are used. " "See :ref:`sqlite3-placeholders`." msgstr "" -#: ../../library/sqlite3.rst:1510 +#: ../../library/sqlite3.rst:1512 msgid "If *sql* contains more than one SQL statement." msgstr "" -#: ../../library/sqlite3.rst:1513 +#: ../../library/sqlite3.rst:1515 msgid "" "If :attr:`~Connection.autocommit` is :data:`LEGACY_TRANSACTION_CONTROL`, :" "attr:`~Connection.isolation_level` is not ``None``, *sql* is an ``INSERT``, " @@ -1589,7 +1933,7 @@ msgid "" "transaction, a transaction is implicitly opened before executing *sql*." msgstr "" -#: ../../library/sqlite3.rst:1522 +#: ../../library/sqlite3.rst:1524 msgid "" ":exc:`DeprecationWarning` is emitted if :ref:`named placeholders ` are used and *parameters* is a sequence instead of a :class:" @@ -1597,43 +1941,53 @@ msgid "" "instead." msgstr "" -#: ../../library/sqlite3.rst:1528 +#: ../../library/sqlite3.rst:1530 msgid "Use :meth:`executescript` to execute multiple SQL statements." msgstr "" -#: ../../library/sqlite3.rst:1532 +#: ../../library/sqlite3.rst:1534 msgid "" "For every item in *parameters*, repeatedly execute the :ref:`parameterized " "` :abbr:`DML (Data Manipulation Language)` SQL " "statement *sql*." msgstr "" -#: ../../library/sqlite3.rst:1536 +#: ../../library/sqlite3.rst:1538 msgid "Uses the same implicit transaction handling as :meth:`~Cursor.execute`." msgstr "" -#: ../../library/sqlite3.rst:1538 +#: ../../library/sqlite3.rst:1540 msgid "A single SQL DML statement." msgstr "" -#: ../../library/sqlite3.rst:1541 +#: ../../library/sqlite3.rst:1543 msgid "" "An :term:`!iterable` of parameters to bind with the placeholders in *sql*. " "See :ref:`sqlite3-placeholders`." msgstr "" -#: ../../library/sqlite3.rst:1547 +#: ../../library/sqlite3.rst:1549 msgid "" "If *sql* contains more than one SQL statement, or is not a DML statement." msgstr "" -#: ../../library/sqlite3.rst:1568 +#: ../../library/sqlite3.rst:1555 +msgid "" +"rows = [\n" +" (\"row1\",),\n" +" (\"row2\",),\n" +"]\n" +"# cur is an sqlite3.Cursor object\n" +"cur.executemany(\"INSERT INTO data VALUES(?)\", rows)" +msgstr "" + +#: ../../library/sqlite3.rst:1570 msgid "" "Any resulting rows are discarded, including DML statements with `RETURNING " "clauses`_." msgstr "" -#: ../../library/sqlite3.rst:1575 +#: ../../library/sqlite3.rst:1577 msgid "" ":exc:`DeprecationWarning` is emitted if :ref:`named placeholders ` are used and the items in *parameters* are sequences instead " @@ -1641,7 +1995,7 @@ msgid "" "be raised instead." msgstr "" -#: ../../library/sqlite3.rst:1584 +#: ../../library/sqlite3.rst:1586 msgid "" "Execute the SQL statements in *sql_script*. If the :attr:`~Connection." "autocommit` is :data:`LEGACY_TRANSACTION_CONTROL` and there is a pending " @@ -1650,24 +2004,36 @@ msgid "" "added to *sql_script*." msgstr "" -#: ../../library/sqlite3.rst:1592 +#: ../../library/sqlite3.rst:1594 msgid "*sql_script* must be a :class:`string `." msgstr "" -#: ../../library/sqlite3.rst:1609 +#: ../../library/sqlite3.rst:1598 +msgid "" +"# cur is an sqlite3.Cursor object\n" +"cur.executescript(\"\"\"\n" +" BEGIN;\n" +" CREATE TABLE person(firstname, lastname, age);\n" +" CREATE TABLE book(title, author, published);\n" +" CREATE TABLE publisher(name, address);\n" +" COMMIT;\n" +"\"\"\")" +msgstr "" + +#: ../../library/sqlite3.rst:1611 msgid "" "If :attr:`~Cursor.row_factory` is ``None``, return the next row query result " "set as a :class:`tuple`. Else, pass it to the row factory and return its " "result. Return ``None`` if no more data is available." msgstr "" -#: ../../library/sqlite3.rst:1617 +#: ../../library/sqlite3.rst:1619 msgid "" "Return the next set of rows of a query result as a :class:`list`. Return an " "empty list if no more rows are available." msgstr "" -#: ../../library/sqlite3.rst:1620 +#: ../../library/sqlite3.rst:1622 msgid "" "The number of rows to fetch per call is specified by the *size* parameter. " "If *size* is not given, :attr:`arraysize` determines the number of rows to " @@ -1675,7 +2041,7 @@ msgid "" "available are returned." msgstr "" -#: ../../library/sqlite3.rst:1626 +#: ../../library/sqlite3.rst:1628 msgid "" "Note there are performance considerations involved with the *size* " "parameter. For optimal performance, it is usually best to use the arraysize " @@ -1683,36 +2049,36 @@ msgid "" "the same value from one :meth:`fetchmany` call to the next." msgstr "" -#: ../../library/sqlite3.rst:1633 +#: ../../library/sqlite3.rst:1635 msgid "" "Return all (remaining) rows of a query result as a :class:`list`. Return an " "empty list if no rows are available. Note that the :attr:`arraysize` " "attribute can affect the performance of this operation." msgstr "" -#: ../../library/sqlite3.rst:1640 +#: ../../library/sqlite3.rst:1642 msgid "Close the cursor now (rather than whenever ``__del__`` is called)." msgstr "" -#: ../../library/sqlite3.rst:1642 +#: ../../library/sqlite3.rst:1644 msgid "" "The cursor will be unusable from this point forward; a :exc:" "`ProgrammingError` exception will be raised if any operation is attempted " "with the cursor." msgstr "" -#: ../../library/sqlite3.rst:1647 ../../library/sqlite3.rst:1651 +#: ../../library/sqlite3.rst:1649 ../../library/sqlite3.rst:1653 msgid "Required by the DB-API. Does nothing in :mod:`!sqlite3`." msgstr "" -#: ../../library/sqlite3.rst:1655 +#: ../../library/sqlite3.rst:1657 msgid "" "Read/write attribute that controls the number of rows returned by :meth:" "`fetchmany`. The default value is 1 which means a single row would be " "fetched per call." msgstr "" -#: ../../library/sqlite3.rst:1660 +#: ../../library/sqlite3.rst:1662 msgid "" "Read-only attribute that provides the SQLite database :class:`Connection` " "belonging to the cursor. A :class:`Cursor` object created by calling :meth:" @@ -1720,18 +2086,27 @@ msgid "" "that refers to *con*:" msgstr "" -#: ../../library/sqlite3.rst:1675 +#: ../../library/sqlite3.rst:1667 +msgid "" +">>> con = sqlite3.connect(\":memory:\")\n" +">>> cur = con.cursor()\n" +">>> cur.connection == con\n" +"True\n" +">>> con.close()" +msgstr "" + +#: ../../library/sqlite3.rst:1677 msgid "" "Read-only attribute that provides the column names of the last query. To " "remain compatible with the Python DB API, it returns a 7-tuple for each " "column where the last six items of each tuple are ``None``." msgstr "" -#: ../../library/sqlite3.rst:1679 +#: ../../library/sqlite3.rst:1681 msgid "It is set for ``SELECT`` statements without any matching rows as well." msgstr "" -#: ../../library/sqlite3.rst:1683 +#: ../../library/sqlite3.rst:1685 msgid "" "Read-only attribute that provides the row id of the last inserted row. It is " "only updated after successful ``INSERT`` or ``REPLACE`` statements using " @@ -1741,15 +2116,15 @@ msgid "" "``None``." msgstr "" -#: ../../library/sqlite3.rst:1691 +#: ../../library/sqlite3.rst:1693 msgid "Inserts into ``WITHOUT ROWID`` tables are not recorded." msgstr "" -#: ../../library/sqlite3.rst:1693 +#: ../../library/sqlite3.rst:1695 msgid "Added support for the ``REPLACE`` statement." msgstr "" -#: ../../library/sqlite3.rst:1698 +#: ../../library/sqlite3.rst:1700 msgid "" "Read-only attribute that provides the number of modified rows for " "``INSERT``, ``UPDATE``, ``DELETE``, and ``REPLACE`` statements; is ``-1`` " @@ -1759,7 +2134,7 @@ msgid "" "resulting rows must be fetched in order for :attr:`!rowcount` to be updated." msgstr "" -#: ../../library/sqlite3.rst:1709 +#: ../../library/sqlite3.rst:1711 msgid "" "Control how a row fetched from this :class:`!Cursor` is represented. If " "``None``, a row is represented as a :class:`tuple`. Can be set to the " @@ -1768,18 +2143,18 @@ msgid "" "and returns a custom object representing an SQLite row." msgstr "" -#: ../../library/sqlite3.rst:1716 +#: ../../library/sqlite3.rst:1718 msgid "" "Defaults to what :attr:`Connection.row_factory` was set to when the :class:`!" "Cursor` was created. Assigning to this attribute does not affect :attr:" "`Connection.row_factory` of the parent connection." msgstr "" -#: ../../library/sqlite3.rst:1732 +#: ../../library/sqlite3.rst:1734 msgid "Row objects" msgstr "" -#: ../../library/sqlite3.rst:1736 +#: ../../library/sqlite3.rst:1738 msgid "" "A :class:`!Row` instance serves as a highly optimized :attr:`~Connection." "row_factory` for :class:`Connection` objects. It supports iteration, " @@ -1787,28 +2162,28 @@ msgid "" "index." msgstr "" -#: ../../library/sqlite3.rst:1741 +#: ../../library/sqlite3.rst:1743 msgid "" "Two :class:`!Row` objects compare equal if they have identical column names " "and values." msgstr "" -#: ../../library/sqlite3.rst:1748 +#: ../../library/sqlite3.rst:1750 msgid "" "Return a :class:`list` of column names as :class:`strings `. " "Immediately after a query, it is the first member of each tuple in :attr:" "`Cursor.description`." msgstr "" -#: ../../library/sqlite3.rst:1752 +#: ../../library/sqlite3.rst:1754 msgid "Added support of slicing." msgstr "" -#: ../../library/sqlite3.rst:1759 +#: ../../library/sqlite3.rst:1761 msgid "Blob objects" msgstr "" -#: ../../library/sqlite3.rst:1765 +#: ../../library/sqlite3.rst:1767 msgid "" "A :class:`Blob` instance is a :term:`file-like object` that can read and " "write data in an SQLite :abbr:`BLOB (Binary Large OBject)`. Call :func:" @@ -1816,24 +2191,46 @@ msgid "" "and :term:`slices ` for direct access to the blob data." msgstr "" -#: ../../library/sqlite3.rst:1770 +#: ../../library/sqlite3.rst:1772 msgid "" "Use the :class:`Blob` as a :term:`context manager` to ensure that the blob " "handle is closed after use." msgstr "" -#: ../../library/sqlite3.rst:1801 -msgid "Close the blob." +#: ../../library/sqlite3.rst:1775 +msgid "" +"con = sqlite3.connect(\":memory:\")\n" +"con.execute(\"CREATE TABLE test(blob_col blob)\")\n" +"con.execute(\"INSERT INTO test(blob_col) VALUES(zeroblob(13))\")\n" +"\n" +"# Write to our blob, using two write operations:\n" +"with con.blobopen(\"test\", \"blob_col\", 1) as blob:\n" +" blob.write(b\"hello, \")\n" +" blob.write(b\"world.\")\n" +" # Modify the first and last bytes of our blob\n" +" blob[0] = ord(\"H\")\n" +" blob[-1] = ord(\"!\")\n" +"\n" +"# Read the contents of our blob\n" +"with con.blobopen(\"test\", \"blob_col\", 1) as blob:\n" +" greeting = blob.read()\n" +"\n" +"print(greeting) # outputs \"b'Hello, world!'\"\n" +"con.close()" msgstr "" #: ../../library/sqlite3.rst:1803 +msgid "Close the blob." +msgstr "" + +#: ../../library/sqlite3.rst:1805 msgid "" "The blob will be unusable from this point onward. An :class:`~sqlite3." "Error` (or subclass) exception will be raised if any further operation is " "attempted with the blob." msgstr "" -#: ../../library/sqlite3.rst:1809 +#: ../../library/sqlite3.rst:1811 msgid "" "Read *length* bytes of data from the blob at the current offset position. If " "the end of the blob is reached, the data up to :abbr:`EOF (End of File)` " @@ -1841,18 +2238,18 @@ msgid "" "`~Blob.read` will read until the end of the blob." msgstr "" -#: ../../library/sqlite3.rst:1817 +#: ../../library/sqlite3.rst:1819 msgid "" "Write *data* to the blob at the current offset. This function cannot change " "the blob length. Writing beyond the end of the blob will raise :exc:" "`ValueError`." msgstr "" -#: ../../library/sqlite3.rst:1823 +#: ../../library/sqlite3.rst:1825 msgid "Return the current access position of the blob." msgstr "" -#: ../../library/sqlite3.rst:1827 +#: ../../library/sqlite3.rst:1829 msgid "" "Set the current access position of the blob to *offset*. The *origin* " "argument defaults to :const:`os.SEEK_SET` (absolute blob positioning). Other " @@ -1860,26 +2257,26 @@ msgid "" "position) and :const:`os.SEEK_END` (seek relative to the blob’s end)." msgstr "" -#: ../../library/sqlite3.rst:1835 +#: ../../library/sqlite3.rst:1837 msgid "PrepareProtocol objects" msgstr "" -#: ../../library/sqlite3.rst:1839 +#: ../../library/sqlite3.rst:1841 msgid "" "The PrepareProtocol type's single purpose is to act as a :pep:`246` style " "adaption protocol for objects that can :ref:`adapt themselves ` to :ref:`native SQLite types `." msgstr "" -#: ../../library/sqlite3.rst:1847 +#: ../../library/sqlite3.rst:1849 msgid "Exceptions" msgstr "Exceções" -#: ../../library/sqlite3.rst:1849 +#: ../../library/sqlite3.rst:1851 msgid "The exception hierarchy is defined by the DB-API 2.0 (:pep:`249`)." msgstr "" -#: ../../library/sqlite3.rst:1853 +#: ../../library/sqlite3.rst:1855 msgid "" "This exception is not currently raised by the :mod:`!sqlite3` module, but " "may be raised by applications using :mod:`!sqlite3`, for example if a user-" @@ -1887,39 +2284,39 @@ msgid "" "of :exc:`Exception`." msgstr "" -#: ../../library/sqlite3.rst:1860 +#: ../../library/sqlite3.rst:1862 msgid "" "The base class of the other exceptions in this module. Use this to catch all " "errors with one single :keyword:`except` statement. ``Error`` is a subclass " "of :exc:`Exception`." msgstr "" -#: ../../library/sqlite3.rst:1864 +#: ../../library/sqlite3.rst:1866 msgid "" "If the exception originated from within the SQLite library, the following " "two attributes are added to the exception:" msgstr "" -#: ../../library/sqlite3.rst:1869 +#: ../../library/sqlite3.rst:1871 msgid "" "The numeric error code from the `SQLite API `_" msgstr "" -#: ../../library/sqlite3.rst:1876 +#: ../../library/sqlite3.rst:1878 msgid "" "The symbolic name of the numeric error code from the `SQLite API `_" msgstr "" -#: ../../library/sqlite3.rst:1883 +#: ../../library/sqlite3.rst:1885 msgid "" "Exception raised for misuse of the low-level SQLite C API. In other words, " "if this exception is raised, it probably indicates a bug in the :mod:`!" "sqlite3` module. ``InterfaceError`` is a subclass of :exc:`Error`." msgstr "" -#: ../../library/sqlite3.rst:1890 +#: ../../library/sqlite3.rst:1892 msgid "" "Exception raised for errors that are related to the database. This serves as " "the base exception for several types of database errors. It is only raised " @@ -1927,14 +2324,14 @@ msgid "" "subclass of :exc:`Error`." msgstr "" -#: ../../library/sqlite3.rst:1897 +#: ../../library/sqlite3.rst:1899 msgid "" "Exception raised for errors caused by problems with the processed data, like " "numeric values out of range, and strings which are too long. ``DataError`` " "is a subclass of :exc:`DatabaseError`." msgstr "" -#: ../../library/sqlite3.rst:1903 +#: ../../library/sqlite3.rst:1905 msgid "" "Exception raised for errors that are related to the database's operation, " "and not necessarily under the control of the programmer. For example, the " @@ -1942,20 +2339,20 @@ msgid "" "``OperationalError`` is a subclass of :exc:`DatabaseError`." msgstr "" -#: ../../library/sqlite3.rst:1911 +#: ../../library/sqlite3.rst:1913 msgid "" "Exception raised when the relational integrity of the database is affected, " "e.g. a foreign key check fails. It is a subclass of :exc:`DatabaseError`." msgstr "" -#: ../../library/sqlite3.rst:1916 +#: ../../library/sqlite3.rst:1918 msgid "" "Exception raised when SQLite encounters an internal error. If this is " "raised, it may indicate that there is a problem with the runtime SQLite " "library. ``InternalError`` is a subclass of :exc:`DatabaseError`." msgstr "" -#: ../../library/sqlite3.rst:1923 +#: ../../library/sqlite3.rst:1925 msgid "" "Exception raised for :mod:`!sqlite3` API programming errors, for example " "supplying the wrong number of bindings to a query, or trying to operate on a " @@ -1963,7 +2360,7 @@ msgid "" "`DatabaseError`." msgstr "" -#: ../../library/sqlite3.rst:1930 +#: ../../library/sqlite3.rst:1932 msgid "" "Exception raised in case a method or database API is not supported by the " "underlying SQLite library. For example, setting *deterministic* to ``True`` " @@ -1972,78 +2369,78 @@ msgid "" "subclass of :exc:`DatabaseError`." msgstr "" -#: ../../library/sqlite3.rst:1940 +#: ../../library/sqlite3.rst:1942 msgid "SQLite and Python types" msgstr "" -#: ../../library/sqlite3.rst:1942 +#: ../../library/sqlite3.rst:1944 msgid "" "SQLite natively supports the following types: ``NULL``, ``INTEGER``, " "``REAL``, ``TEXT``, ``BLOB``." msgstr "" -#: ../../library/sqlite3.rst:1945 +#: ../../library/sqlite3.rst:1947 msgid "" "The following Python types can thus be sent to SQLite without any problem:" msgstr "" -#: ../../library/sqlite3.rst:1948 ../../library/sqlite3.rst:1965 +#: ../../library/sqlite3.rst:1950 ../../library/sqlite3.rst:1967 msgid "Python type" -msgstr "Tipo Python" +msgstr "Tipo em Python" -#: ../../library/sqlite3.rst:1948 ../../library/sqlite3.rst:1965 +#: ../../library/sqlite3.rst:1950 ../../library/sqlite3.rst:1967 msgid "SQLite type" -msgstr "Tipo SQLite" +msgstr "Tipo em SQLite" -#: ../../library/sqlite3.rst:1950 ../../library/sqlite3.rst:1967 +#: ../../library/sqlite3.rst:1952 ../../library/sqlite3.rst:1969 msgid "``None``" msgstr "``None``" -#: ../../library/sqlite3.rst:1950 ../../library/sqlite3.rst:1967 +#: ../../library/sqlite3.rst:1952 ../../library/sqlite3.rst:1969 msgid "``NULL``" msgstr "``NULL``" -#: ../../library/sqlite3.rst:1952 ../../library/sqlite3.rst:1969 +#: ../../library/sqlite3.rst:1954 ../../library/sqlite3.rst:1971 msgid ":class:`int`" msgstr ":class:`int`" -#: ../../library/sqlite3.rst:1952 ../../library/sqlite3.rst:1969 +#: ../../library/sqlite3.rst:1954 ../../library/sqlite3.rst:1971 msgid "``INTEGER``" msgstr "``INTEGER``" -#: ../../library/sqlite3.rst:1954 ../../library/sqlite3.rst:1971 +#: ../../library/sqlite3.rst:1956 ../../library/sqlite3.rst:1973 msgid ":class:`float`" msgstr ":class:`float`" -#: ../../library/sqlite3.rst:1954 ../../library/sqlite3.rst:1971 +#: ../../library/sqlite3.rst:1956 ../../library/sqlite3.rst:1973 msgid "``REAL``" msgstr "``REAL``" -#: ../../library/sqlite3.rst:1956 +#: ../../library/sqlite3.rst:1958 msgid ":class:`str`" msgstr ":class:`str`" -#: ../../library/sqlite3.rst:1956 ../../library/sqlite3.rst:1973 +#: ../../library/sqlite3.rst:1958 ../../library/sqlite3.rst:1975 msgid "``TEXT``" msgstr "``TEXT``" -#: ../../library/sqlite3.rst:1958 ../../library/sqlite3.rst:1976 +#: ../../library/sqlite3.rst:1960 ../../library/sqlite3.rst:1978 msgid ":class:`bytes`" msgstr ":class:`bytes`" -#: ../../library/sqlite3.rst:1958 ../../library/sqlite3.rst:1976 +#: ../../library/sqlite3.rst:1960 ../../library/sqlite3.rst:1978 msgid "``BLOB``" msgstr "``BLOB``" -#: ../../library/sqlite3.rst:1962 +#: ../../library/sqlite3.rst:1964 msgid "This is how SQLite types are converted to Python types by default:" msgstr "" -#: ../../library/sqlite3.rst:1973 +#: ../../library/sqlite3.rst:1975 msgid "depends on :attr:`~Connection.text_factory`, :class:`str` by default" msgstr "" -#: ../../library/sqlite3.rst:1979 +#: ../../library/sqlite3.rst:1981 msgid "" "The type system of the :mod:`!sqlite3` module is extensible in two ways: you " "can store additional Python types in an SQLite database via :ref:`object " @@ -2052,47 +2449,47 @@ msgid "" "converters>`." msgstr "" -#: ../../library/sqlite3.rst:1989 +#: ../../library/sqlite3.rst:1991 msgid "Default adapters and converters (deprecated)" msgstr "" -#: ../../library/sqlite3.rst:1993 +#: ../../library/sqlite3.rst:1995 msgid "" "The default adapters and converters are deprecated as of Python 3.12. " "Instead, use the :ref:`sqlite3-adapter-converter-recipes` and tailor them to " "your needs." msgstr "" -#: ../../library/sqlite3.rst:1997 +#: ../../library/sqlite3.rst:1999 msgid "The deprecated default adapters and converters consist of:" msgstr "" -#: ../../library/sqlite3.rst:1999 +#: ../../library/sqlite3.rst:2001 msgid "" "An adapter for :class:`datetime.date` objects to :class:`strings ` in " "`ISO 8601`_ format." msgstr "" -#: ../../library/sqlite3.rst:2001 +#: ../../library/sqlite3.rst:2003 msgid "" "An adapter for :class:`datetime.datetime` objects to strings in ISO 8601 " "format." msgstr "" -#: ../../library/sqlite3.rst:2003 +#: ../../library/sqlite3.rst:2005 msgid "" "A converter for :ref:`declared ` \"date\" types to :" "class:`datetime.date` objects." msgstr "" -#: ../../library/sqlite3.rst:2005 +#: ../../library/sqlite3.rst:2007 msgid "" "A converter for declared \"timestamp\" types to :class:`datetime.datetime` " "objects. Fractional parts will be truncated to 6 digits (microsecond " "precision)." msgstr "" -#: ../../library/sqlite3.rst:2011 +#: ../../library/sqlite3.rst:2013 msgid "" "The default \"timestamp\" converter ignores UTC offsets in the database and " "always returns a naive :class:`datetime.datetime` object. To preserve UTC " @@ -2100,11 +2497,11 @@ msgid "" "offset-aware converter with :func:`register_converter`." msgstr "" -#: ../../library/sqlite3.rst:2024 +#: ../../library/sqlite3.rst:2026 msgid "Command-line interface" msgstr "Interface de linha de comando" -#: ../../library/sqlite3.rst:2026 +#: ../../library/sqlite3.rst:2028 msgid "" "The :mod:`!sqlite3` module can be invoked as a script, using the " "interpreter's :option:`-m` switch, in order to provide a simple SQLite " @@ -2112,26 +2509,30 @@ msgid "" msgstr "" #: ../../library/sqlite3.rst:2033 +msgid "python -m sqlite3 [-h] [-v] [filename] [sql]" +msgstr "" + +#: ../../library/sqlite3.rst:2035 msgid "Type ``.quit`` or CTRL-D to exit the shell." msgstr "" -#: ../../library/sqlite3.rst:2039 +#: ../../library/sqlite3.rst:2041 msgid "Print CLI help." msgstr "" -#: ../../library/sqlite3.rst:2043 +#: ../../library/sqlite3.rst:2045 msgid "Print underlying SQLite library version." msgstr "" -#: ../../library/sqlite3.rst:2051 +#: ../../library/sqlite3.rst:2053 msgid "How-to guides" msgstr "Guias de como fazer" -#: ../../library/sqlite3.rst:2056 +#: ../../library/sqlite3.rst:2058 msgid "How to use placeholders to bind values in SQL queries" msgstr "" -#: ../../library/sqlite3.rst:2058 +#: ../../library/sqlite3.rst:2060 msgid "" "SQL operations usually need to use values from Python variables. However, " "beware of using Python's string operations to assemble queries, as they are " @@ -2139,7 +2540,18 @@ msgid "" "close the single quote and inject ``OR TRUE`` to select all rows::" msgstr "" -#: ../../library/sqlite3.rst:2071 +#: ../../library/sqlite3.rst:2065 +msgid "" +">>> # Never do this -- insecure!\n" +">>> symbol = input()\n" +"' OR TRUE; --\n" +">>> sql = \"SELECT * FROM stocks WHERE symbol = '%s'\" % symbol\n" +">>> print(sql)\n" +"SELECT * FROM stocks WHERE symbol = '' OR TRUE; --'\n" +">>> cur.execute(sql)" +msgstr "" + +#: ../../library/sqlite3.rst:2073 msgid "" "Instead, use the DB-API's parameter substitution. To insert a variable into " "a query string, use a placeholder in the string, and substitute the actual " @@ -2147,7 +2559,7 @@ msgid "" "second argument of the cursor's :meth:`~Cursor.execute` method." msgstr "" -#: ../../library/sqlite3.rst:2076 +#: ../../library/sqlite3.rst:2078 msgid "" "An SQL statement may use one of two kinds of placeholders: question marks " "(qmark style) or named placeholders (named style). For the qmark style, " @@ -2158,24 +2570,45 @@ msgid "" "ignored. Here's an example of both styles:" msgstr "" -#: ../../library/sqlite3.rst:2114 +#: ../../library/sqlite3.rst:2089 +msgid "" +"con = sqlite3.connect(\":memory:\")\n" +"cur = con.execute(\"CREATE TABLE lang(name, first_appeared)\")\n" +"\n" +"# This is the named style used with executemany():\n" +"data = (\n" +" {\"name\": \"C\", \"year\": 1972},\n" +" {\"name\": \"Fortran\", \"year\": 1957},\n" +" {\"name\": \"Python\", \"year\": 1991},\n" +" {\"name\": \"Go\", \"year\": 2009},\n" +")\n" +"cur.executemany(\"INSERT INTO lang VALUES(:name, :year)\", data)\n" +"\n" +"# This is the qmark style used in a SELECT query:\n" +"params = (1972,)\n" +"cur.execute(\"SELECT * FROM lang WHERE first_appeared = ?\", params)\n" +"print(cur.fetchall())\n" +"con.close()" +msgstr "" + +#: ../../library/sqlite3.rst:2116 msgid "" ":pep:`249` numeric placeholders are *not* supported. If used, they will be " "interpreted as named placeholders." msgstr "" -#: ../../library/sqlite3.rst:2121 +#: ../../library/sqlite3.rst:2123 msgid "How to adapt custom Python types to SQLite values" msgstr "" -#: ../../library/sqlite3.rst:2123 +#: ../../library/sqlite3.rst:2125 msgid "" "SQLite supports only a limited set of data types natively. To store custom " "Python types in SQLite databases, *adapt* them to one of the :ref:`Python " "types SQLite natively understands `." msgstr "" -#: ../../library/sqlite3.rst:2127 +#: ../../library/sqlite3.rst:2129 msgid "" "There are two ways to adapt Python objects to SQLite types: letting your " "object adapt itself, or using an *adapter callable*. The latter will take " @@ -2185,11 +2618,11 @@ msgid "" "custom adapter functions." msgstr "" -#: ../../library/sqlite3.rst:2139 +#: ../../library/sqlite3.rst:2141 msgid "How to write adaptable objects" msgstr "" -#: ../../library/sqlite3.rst:2141 +#: ../../library/sqlite3.rst:2143 msgid "" "Suppose we have a :class:`!Point` class that represents a pair of " "coordinates, ``x`` and ``y``, in a Cartesian coordinate system. The " @@ -2199,84 +2632,208 @@ msgid "" "object passed to *protocol* will be of type :class:`PrepareProtocol`." msgstr "" -#: ../../library/sqlite3.rst:2173 -msgid "How to register adapter callables" +#: ../../library/sqlite3.rst:2151 +msgid "" +"class Point:\n" +" def __init__(self, x, y):\n" +" self.x, self.y = x, y\n" +"\n" +" def __conform__(self, protocol):\n" +" if protocol is sqlite3.PrepareProtocol:\n" +" return f\"{self.x};{self.y}\"\n" +"\n" +"con = sqlite3.connect(\":memory:\")\n" +"cur = con.cursor()\n" +"\n" +"cur.execute(\"SELECT ?\", (Point(4.0, -3.2),))\n" +"print(cur.fetchone()[0])\n" +"con.close()" msgstr "" #: ../../library/sqlite3.rst:2175 +msgid "How to register adapter callables" +msgstr "" + +#: ../../library/sqlite3.rst:2177 msgid "" "The other possibility is to create a function that converts the Python " "object to an SQLite-compatible type. This function can then be registered " "using :func:`register_adapter`." msgstr "" -#: ../../library/sqlite3.rst:2206 -msgid "How to convert SQLite values to custom Python types" +#: ../../library/sqlite3.rst:2181 +msgid "" +"class Point:\n" +" def __init__(self, x, y):\n" +" self.x, self.y = x, y\n" +"\n" +"def adapt_point(point):\n" +" return f\"{point.x};{point.y}\"\n" +"\n" +"sqlite3.register_adapter(Point, adapt_point)\n" +"\n" +"con = sqlite3.connect(\":memory:\")\n" +"cur = con.cursor()\n" +"\n" +"cur.execute(\"SELECT ?\", (Point(1.0, 2.5),))\n" +"print(cur.fetchone()[0])\n" +"con.close()" msgstr "" #: ../../library/sqlite3.rst:2208 +msgid "How to convert SQLite values to custom Python types" +msgstr "" + +#: ../../library/sqlite3.rst:2210 msgid "" "Writing an adapter lets you convert *from* custom Python types *to* SQLite " "values. To be able to convert *from* SQLite values *to* custom Python types, " "we use *converters*." msgstr "" -#: ../../library/sqlite3.rst:2213 +#: ../../library/sqlite3.rst:2215 msgid "" "Let's go back to the :class:`!Point` class. We stored the x and y " "coordinates separated via semicolons as strings in SQLite." msgstr "" -#: ../../library/sqlite3.rst:2216 +#: ../../library/sqlite3.rst:2218 msgid "" "First, we'll define a converter function that accepts the string as a " "parameter and constructs a :class:`!Point` object from it." msgstr "" -#: ../../library/sqlite3.rst:2221 +#: ../../library/sqlite3.rst:2223 msgid "" "Converter functions are **always** passed a :class:`bytes` object, no matter " "the underlying SQLite data type." msgstr "" -#: ../../library/sqlite3.rst:2230 +#: ../../library/sqlite3.rst:2226 +msgid "" +"def convert_point(s):\n" +" x, y = map(float, s.split(b\";\"))\n" +" return Point(x, y)" +msgstr "" + +#: ../../library/sqlite3.rst:2232 msgid "" "We now need to tell :mod:`!sqlite3` when it should convert a given SQLite " "value. This is done when connecting to a database, using the *detect_types* " "parameter of :func:`connect`. There are three options:" msgstr "" -#: ../../library/sqlite3.rst:2234 +#: ../../library/sqlite3.rst:2236 msgid "Implicit: set *detect_types* to :const:`PARSE_DECLTYPES`" msgstr "" -#: ../../library/sqlite3.rst:2235 +#: ../../library/sqlite3.rst:2237 msgid "Explicit: set *detect_types* to :const:`PARSE_COLNAMES`" msgstr "" -#: ../../library/sqlite3.rst:2236 +#: ../../library/sqlite3.rst:2238 msgid "" "Both: set *detect_types* to ``sqlite3.PARSE_DECLTYPES | sqlite3." "PARSE_COLNAMES``. Column names take precedence over declared types." msgstr "" -#: ../../library/sqlite3.rst:2240 +#: ../../library/sqlite3.rst:2242 msgid "The following example illustrates the implicit and explicit approaches:" msgstr "" -#: ../../library/sqlite3.rst:2293 -msgid "Adapter and converter recipes" +#: ../../library/sqlite3.rst:2244 +msgid "" +"class Point:\n" +" def __init__(self, x, y):\n" +" self.x, self.y = x, y\n" +"\n" +" def __repr__(self):\n" +" return f\"Point({self.x}, {self.y})\"\n" +"\n" +"def adapt_point(point):\n" +" return f\"{point.x};{point.y}\"\n" +"\n" +"def convert_point(s):\n" +" x, y = list(map(float, s.split(b\";\")))\n" +" return Point(x, y)\n" +"\n" +"# Register the adapter and converter\n" +"sqlite3.register_adapter(Point, adapt_point)\n" +"sqlite3.register_converter(\"point\", convert_point)\n" +"\n" +"# 1) Parse using declared types\n" +"p = Point(4.0, -3.2)\n" +"con = sqlite3.connect(\":memory:\", detect_types=sqlite3.PARSE_DECLTYPES)\n" +"cur = con.execute(\"CREATE TABLE test(p point)\")\n" +"\n" +"cur.execute(\"INSERT INTO test(p) VALUES(?)\", (p,))\n" +"cur.execute(\"SELECT p FROM test\")\n" +"print(\"with declared types:\", cur.fetchone()[0])\n" +"cur.close()\n" +"con.close()\n" +"\n" +"# 2) Parse using column names\n" +"con = sqlite3.connect(\":memory:\", detect_types=sqlite3.PARSE_COLNAMES)\n" +"cur = con.execute(\"CREATE TABLE test(p)\")\n" +"\n" +"cur.execute(\"INSERT INTO test(p) VALUES(?)\", (p,))\n" +"cur.execute('SELECT p AS \"p [point]\" FROM test')\n" +"print(\"with column names:\", cur.fetchone()[0])\n" +"cur.close()\n" +"con.close()" msgstr "" #: ../../library/sqlite3.rst:2295 +msgid "Adapter and converter recipes" +msgstr "" + +#: ../../library/sqlite3.rst:2297 msgid "This section shows recipes for common adapters and converters." msgstr "" -#: ../../library/sqlite3.rst:2357 -msgid "How to use connection shortcut methods" +#: ../../library/sqlite3.rst:2299 +msgid "" +"import datetime\n" +"import sqlite3\n" +"\n" +"def adapt_date_iso(val):\n" +" \"\"\"Adapt datetime.date to ISO 8601 date.\"\"\"\n" +" return val.isoformat()\n" +"\n" +"def adapt_datetime_iso(val):\n" +" \"\"\"Adapt datetime.datetime to timezone-naive ISO 8601 date.\"\"\"\n" +" return val.isoformat()\n" +"\n" +"def adapt_datetime_epoch(val):\n" +" \"\"\"Adapt datetime.datetime to Unix timestamp.\"\"\"\n" +" return int(val.timestamp())\n" +"\n" +"sqlite3.register_adapter(datetime.date, adapt_date_iso)\n" +"sqlite3.register_adapter(datetime.datetime, adapt_datetime_iso)\n" +"sqlite3.register_adapter(datetime.datetime, adapt_datetime_epoch)\n" +"\n" +"def convert_date(val):\n" +" \"\"\"Convert ISO 8601 date to datetime.date object.\"\"\"\n" +" return datetime.date.fromisoformat(val.decode())\n" +"\n" +"def convert_datetime(val):\n" +" \"\"\"Convert ISO 8601 datetime to datetime.datetime object.\"\"\"\n" +" return datetime.datetime.fromisoformat(val.decode())\n" +"\n" +"def convert_timestamp(val):\n" +" \"\"\"Convert Unix epoch timestamp to datetime.datetime object.\"\"\"\n" +" return datetime.datetime.fromtimestamp(int(val))\n" +"\n" +"sqlite3.register_converter(\"date\", convert_date)\n" +"sqlite3.register_converter(\"datetime\", convert_datetime)\n" +"sqlite3.register_converter(\"timestamp\", convert_timestamp)" msgstr "" #: ../../library/sqlite3.rst:2359 +msgid "How to use connection shortcut methods" +msgstr "" + +#: ../../library/sqlite3.rst:2361 msgid "" "Using the :meth:`~Connection.execute`, :meth:`~Connection.executemany`, and :" "meth:`~Connection.executescript` methods of the :class:`Connection` class, " @@ -2288,11 +2845,35 @@ msgid "" "object." msgstr "" -#: ../../library/sqlite3.rst:2400 -msgid "How to use the connection context manager" +#: ../../library/sqlite3.rst:2370 +msgid "" +"# Create and fill the table.\n" +"con = sqlite3.connect(\":memory:\")\n" +"con.execute(\"CREATE TABLE lang(name, first_appeared)\")\n" +"data = [\n" +" (\"C++\", 1985),\n" +" (\"Objective-C\", 1984),\n" +"]\n" +"con.executemany(\"INSERT INTO lang(name, first_appeared) VALUES(?, ?)\", " +"data)\n" +"\n" +"# Print the table contents\n" +"for row in con.execute(\"SELECT name, first_appeared FROM lang\"):\n" +" print(row)\n" +"\n" +"print(\"I just deleted\", con.execute(\"DELETE FROM lang\").rowcount, " +"\"rows\")\n" +"\n" +"# close() is not a shortcut method and it's not called automatically;\n" +"# the connection object should be closed manually\n" +"con.close()" msgstr "" #: ../../library/sqlite3.rst:2402 +msgid "How to use the connection context manager" +msgstr "" + +#: ../../library/sqlite3.rst:2404 msgid "" "A :class:`Connection` object can be used as a context manager that " "automatically commits or rolls back open transactions when leaving the body " @@ -2304,60 +2885,115 @@ msgid "" "rolling back." msgstr "" -#: ../../library/sqlite3.rst:2413 +#: ../../library/sqlite3.rst:2415 msgid "" "If there is no open transaction upon leaving the body of the ``with`` " "statement, or if :attr:`~Connection.autocommit` is ``True``, the context " "manager does nothing." msgstr "" -#: ../../library/sqlite3.rst:2418 +#: ../../library/sqlite3.rst:2420 msgid "" "The context manager neither implicitly opens a new transaction nor closes " "the connection. If you need a closing context manager, consider using :meth:" "`contextlib.closing`." msgstr "" -#: ../../library/sqlite3.rst:2452 -msgid "How to work with SQLite URIs" +#: ../../library/sqlite3.rst:2424 +msgid "" +"con = sqlite3.connect(\":memory:\")\n" +"con.execute(\"CREATE TABLE lang(id INTEGER PRIMARY KEY, name VARCHAR " +"UNIQUE)\")\n" +"\n" +"# Successful, con.commit() is called automatically afterwards\n" +"with con:\n" +" con.execute(\"INSERT INTO lang(name) VALUES(?)\", (\"Python\",))\n" +"\n" +"# con.rollback() is called after the with block finishes with an exception,\n" +"# the exception is still raised and must be caught\n" +"try:\n" +" with con:\n" +" con.execute(\"INSERT INTO lang(name) VALUES(?)\", (\"Python\",))\n" +"except sqlite3.IntegrityError:\n" +" print(\"couldn't add Python twice\")\n" +"\n" +"# Connection object used as context manager only commits or rollbacks " +"transactions,\n" +"# so the connection object should be closed manually\n" +"con.close()" msgstr "" #: ../../library/sqlite3.rst:2454 -msgid "Some useful URI tricks include:" +msgid "How to work with SQLite URIs" msgstr "" #: ../../library/sqlite3.rst:2456 +msgid "Some useful URI tricks include:" +msgstr "" + +#: ../../library/sqlite3.rst:2458 msgid "Open a database in read-only mode:" msgstr "" -#: ../../library/sqlite3.rst:2465 +#: ../../library/sqlite3.rst:2460 +msgid "" +">>> con = sqlite3.connect(\"file:tutorial.db?mode=ro\", uri=True)\n" +">>> con.execute(\"CREATE TABLE readonly(data)\")\n" +"Traceback (most recent call last):\n" +"OperationalError: attempt to write a readonly database\n" +">>> con.close()" +msgstr "" + +#: ../../library/sqlite3.rst:2468 msgid "" "Do not implicitly create a new database file if it does not already exist; " "will raise :exc:`~sqlite3.OperationalError` if unable to create a new file:" msgstr "" -#: ../../library/sqlite3.rst:2475 +#: ../../library/sqlite3.rst:2471 +msgid "" +">>> con = sqlite3.connect(\"file:nosuchdb.db?mode=rw\", uri=True)\n" +"Traceback (most recent call last):\n" +"OperationalError: unable to open database file" +msgstr "" + +#: ../../library/sqlite3.rst:2478 msgid "Create a shared named in-memory database:" msgstr "" -#: ../../library/sqlite3.rst:2491 +#: ../../library/sqlite3.rst:2480 +msgid "" +"db = \"file:mem1?mode=memory&cache=shared\"\n" +"con1 = sqlite3.connect(db, uri=True)\n" +"con2 = sqlite3.connect(db, uri=True)\n" +"with con1:\n" +" con1.execute(\"CREATE TABLE shared(data)\")\n" +" con1.execute(\"INSERT INTO shared VALUES(28)\")\n" +"res = con2.execute(\"SELECT data FROM shared\")\n" +"assert res.fetchone() == (28,)\n" +"\n" +"con1.close()\n" +"con2.close()" +msgstr "" + +#: ../../library/sqlite3.rst:2494 msgid "" "More information about this feature, including a list of parameters, can be " "found in the `SQLite URI documentation`_." msgstr "" -#: ../../library/sqlite3.rst:2500 +#: ../../library/sqlite3.rst:2503 msgid "How to create and use row factories" msgstr "" -#: ../../library/sqlite3.rst:2502 +#: ../../library/sqlite3.rst:2505 msgid "" "By default, :mod:`!sqlite3` represents each row as a :class:`tuple`. If a :" "class:`!tuple` does not suit your needs, you can use the :class:`sqlite3." "Row` class or a custom :attr:`~Cursor.row_factory`." msgstr "" -#: ../../library/sqlite3.rst:2507 +#: ../../library/sqlite3.rst:2510 msgid "" "While :attr:`!row_factory` exists as an attribute both on the :class:" "`Cursor` and the :class:`Connection`, it is recommended to set :class:" @@ -2365,7 +3001,7 @@ msgid "" "use the same row factory." msgstr "" -#: ../../library/sqlite3.rst:2512 +#: ../../library/sqlite3.rst:2515 msgid "" ":class:`!Row` provides indexed and case-insensitive named access to columns, " "with minimal memory overhead and performance impact over a :class:`!tuple`. " @@ -2373,11 +3009,32 @@ msgid "" "attribute:" msgstr "" -#: ../../library/sqlite3.rst:2522 +#: ../../library/sqlite3.rst:2520 +msgid "" +">>> con = sqlite3.connect(\":memory:\")\n" +">>> con.row_factory = sqlite3.Row" +msgstr "" + +#: ../../library/sqlite3.rst:2525 msgid "Queries now return :class:`!Row` objects:" msgstr "" -#: ../../library/sqlite3.rst:2540 +#: ../../library/sqlite3.rst:2527 +msgid "" +">>> res = con.execute(\"SELECT 'Earth' AS name, 6378 AS radius\")\n" +">>> row = res.fetchone()\n" +">>> row.keys()\n" +"['name', 'radius']\n" +">>> row[0] # Access by index.\n" +"'Earth'\n" +">>> row[\"name\"] # Access by name.\n" +"'Earth'\n" +">>> row[\"RADIUS\"] # Column names are case-insensitive.\n" +"6378\n" +">>> con.close()" +msgstr "" + +#: ../../library/sqlite3.rst:2543 msgid "" "The ``FROM`` clause can be omitted in the ``SELECT`` statement, as in the " "above example. In such cases, SQLite returns a single row with columns " @@ -2385,37 +3042,79 @@ msgid "" "alias``." msgstr "" -#: ../../library/sqlite3.rst:2545 +#: ../../library/sqlite3.rst:2548 msgid "" "You can create a custom :attr:`~Cursor.row_factory` that returns each row as " "a :class:`dict`, with column names mapped to values:" msgstr "" -#: ../../library/sqlite3.rst:2554 +#: ../../library/sqlite3.rst:2551 +msgid "" +"def dict_factory(cursor, row):\n" +" fields = [column[0] for column in cursor.description]\n" +" return {key: value for key, value in zip(fields, row)}" +msgstr "" + +#: ../../library/sqlite3.rst:2557 msgid "" "Using it, queries now return a :class:`!dict` instead of a :class:`!tuple`:" msgstr "" -#: ../../library/sqlite3.rst:2565 +#: ../../library/sqlite3.rst:2559 +msgid "" +">>> con = sqlite3.connect(\":memory:\")\n" +">>> con.row_factory = dict_factory\n" +">>> for row in con.execute(\"SELECT 1 AS a, 2 AS b\"):\n" +"... print(row)\n" +"{'a': 1, 'b': 2}\n" +">>> con.close()" +msgstr "" + +#: ../../library/sqlite3.rst:2568 msgid "The following row factory returns a :term:`named tuple`:" msgstr "" -#: ../../library/sqlite3.rst:2576 +#: ../../library/sqlite3.rst:2570 +msgid "" +"from collections import namedtuple\n" +"\n" +"def namedtuple_factory(cursor, row):\n" +" fields = [column[0] for column in cursor.description]\n" +" cls = namedtuple(\"Row\", fields)\n" +" return cls._make(row)" +msgstr "" + +#: ../../library/sqlite3.rst:2579 msgid ":func:`!namedtuple_factory` can be used as follows:" msgstr "" -#: ../../library/sqlite3.rst:2592 +#: ../../library/sqlite3.rst:2581 +msgid "" +">>> con = sqlite3.connect(\":memory:\")\n" +">>> con.row_factory = namedtuple_factory\n" +">>> cur = con.execute(\"SELECT 1 AS a, 2 AS b\")\n" +">>> row = cur.fetchone()\n" +">>> row\n" +"Row(a=1, b=2)\n" +">>> row[0] # Indexed access.\n" +"1\n" +">>> row.b # Attribute access.\n" +"2\n" +">>> con.close()" +msgstr "" + +#: ../../library/sqlite3.rst:2595 msgid "" "With some adjustments, the above recipe can be adapted to use a :class:" "`~dataclasses.dataclass`, or any other custom class, instead of a :class:" "`~collections.namedtuple`." msgstr "" -#: ../../library/sqlite3.rst:2600 +#: ../../library/sqlite3.rst:2603 msgid "How to handle non-UTF-8 text encodings" msgstr "" -#: ../../library/sqlite3.rst:2602 +#: ../../library/sqlite3.rst:2605 msgid "" "By default, :mod:`!sqlite3` uses :class:`str` to adapt SQLite values with " "the ``TEXT`` data type. This works well for UTF-8 encoded text, but it might " @@ -2423,7 +3122,7 @@ msgid "" "`~Connection.text_factory` to handle such cases." msgstr "" -#: ../../library/sqlite3.rst:2608 +#: ../../library/sqlite3.rst:2611 msgid "" "Because of SQLite's `flexible typing`_, it is not uncommon to encounter " "table columns with the ``TEXT`` data type containing non-UTF-8 encodings, or " @@ -2434,31 +3133,39 @@ msgid "" "text using this :attr:`~Connection.text_factory`:" msgstr "" -#: ../../library/sqlite3.rst:2621 +#: ../../library/sqlite3.rst:2620 +msgid "con.text_factory = lambda data: str(data, encoding=\"latin2\")" +msgstr "" + +#: ../../library/sqlite3.rst:2624 msgid "" "For invalid UTF-8 or arbitrary data in stored in ``TEXT`` table columns, you " "can use the following technique, borrowed from the :ref:`unicode-howto`:" msgstr "" -#: ../../library/sqlite3.rst:2630 +#: ../../library/sqlite3.rst:2627 +msgid "con.text_factory = lambda data: str(data, errors=\"surrogateescape\")" +msgstr "" + +#: ../../library/sqlite3.rst:2633 msgid "" "The :mod:`!sqlite3` module API does not support strings containing " "surrogates." msgstr "" -#: ../../library/sqlite3.rst:2635 +#: ../../library/sqlite3.rst:2638 msgid ":ref:`unicode-howto`" msgstr ":ref:`unicode-howto`" -#: ../../library/sqlite3.rst:2641 +#: ../../library/sqlite3.rst:2644 msgid "Explanation" msgstr "Explicação" -#: ../../library/sqlite3.rst:2647 +#: ../../library/sqlite3.rst:2650 msgid "Transaction control" msgstr "Controle de transações" -#: ../../library/sqlite3.rst:2649 +#: ../../library/sqlite3.rst:2652 msgid "" ":mod:`!sqlite3` offers multiple methods of controlling whether, when and how " "database transactions are opened and closed. :ref:`sqlite3-transaction-" @@ -2470,11 +3177,11 @@ msgstr "" "transaction-control-autocommit` é recomendado, enquanto :ref:`sqlite3-" "transaction-control-isolation-level` mantém o comportamento pré-Python 3.12." -#: ../../library/sqlite3.rst:2658 +#: ../../library/sqlite3.rst:2661 msgid "Transaction control via the ``autocommit`` attribute" msgstr "Controle de transações através do atributo ``autocommit``" -#: ../../library/sqlite3.rst:2660 +#: ../../library/sqlite3.rst:2663 msgid "" "The recommended way of controlling transaction behaviour is through the :" "attr:`Connection.autocommit` attribute, which should preferably be set using " @@ -2484,7 +3191,7 @@ msgstr "" "atributo :attr:`Connection.autocommit`, que deve ser preferencialmente " "definido usando o parâmetro *autocommit* de :func:`connect`." -#: ../../library/sqlite3.rst:2665 +#: ../../library/sqlite3.rst:2668 msgid "" "It is suggested to set *autocommit* to ``False``, which implies :pep:`249`-" "compliant transaction control. This means:" @@ -2492,7 +3199,7 @@ msgstr "" "É sugerido definir *autocommit* como ``False``, o que implica controle de " "transação compatível com a :pep:`249`. Isso significa:" -#: ../../library/sqlite3.rst:2669 +#: ../../library/sqlite3.rst:2672 msgid "" ":mod:`!sqlite3` ensures that a transaction is always open, so :func:" "`connect`, :meth:`Connection.commit`, and :meth:`Connection.rollback` will " @@ -2506,16 +3213,16 @@ msgstr "" "para as duas últimas). :mod:`!sqlite3` usa instruções ``BEGIN DEFERRED`` ao " "abrir transações." -#: ../../library/sqlite3.rst:2674 +#: ../../library/sqlite3.rst:2677 msgid "Transactions should be committed explicitly using :meth:`!commit`." msgstr "Transações devem ser executadas explicitamente usando :meth:`!commit`." -#: ../../library/sqlite3.rst:2675 +#: ../../library/sqlite3.rst:2678 msgid "Transactions should be rolled back explicitly using :meth:`!rollback`." msgstr "" "Transações devem ser revertidas explicitamente usando :meth:`!rollback`." -#: ../../library/sqlite3.rst:2676 +#: ../../library/sqlite3.rst:2679 msgid "" "An implicit rollback is performed if the database is :meth:`~Connection." "close`-ed with pending changes." @@ -2523,7 +3230,7 @@ msgstr "" "Uma reversão implícita é executada se o banco de dados estiver em estado :" "meth:`~Connection.close` com alterações pendentes." -#: ../../library/sqlite3.rst:2679 +#: ../../library/sqlite3.rst:2682 msgid "" "Set *autocommit* to ``True`` to enable SQLite's `autocommit mode`_. In this " "mode, :meth:`Connection.commit` and :meth:`Connection.rollback` have no " @@ -2538,7 +3245,7 @@ msgstr "" "`Connection.in_transaction` para consultar o modo de confirmação automática " "do SQLite de baixo nível." -#: ../../library/sqlite3.rst:2687 +#: ../../library/sqlite3.rst:2690 msgid "" "Set *autocommit* to :data:`LEGACY_TRANSACTION_CONTROL` to leave transaction " "control behaviour to the :attr:`Connection.isolation_level` attribute. See :" @@ -2549,11 +3256,11 @@ msgstr "" "isolation_level`. Veja :ref:`sqlite3-transaction-control-isolation-level` " "para mais informações." -#: ../../library/sqlite3.rst:2696 +#: ../../library/sqlite3.rst:2699 msgid "Transaction control via the ``isolation_level`` attribute" msgstr "Controle de transação através do atributo ``isolation_level``" -#: ../../library/sqlite3.rst:2700 +#: ../../library/sqlite3.rst:2703 msgid "" "The recommended way of controlling transactions is via the :attr:" "`~Connection.autocommit` attribute. See :ref:`sqlite3-transaction-control-" @@ -2562,7 +3269,7 @@ msgstr "" "A forma recomendada de controlar transações é através do atributo :attr:" "`~Connection.autocommit`. Veja :ref:`sqlite3-transaction-control-autocommit`." -#: ../../library/sqlite3.rst:2704 +#: ../../library/sqlite3.rst:2707 msgid "" "If :attr:`Connection.autocommit` is set to :data:" "`LEGACY_TRANSACTION_CONTROL` (the default), transaction behaviour is " @@ -2574,7 +3281,7 @@ msgstr "" "controlado usando o atributo :attr:`Connection.isolation_level`. Caso " "contrário, :attr:`!isolation_level` não tem efeito." -#: ../../library/sqlite3.rst:2710 +#: ../../library/sqlite3.rst:2713 msgid "" "If the connection attribute :attr:`~Connection.isolation_level` is not " "``None``, new transactions are implicitly opened before :meth:`~Cursor." @@ -2598,7 +3305,7 @@ msgstr "" "de instruções ``BEGIN`` do :mod:`!sqlite3` são executadas implicitamente -- " "através do atributo :attr:`~Connection.isolation_level`." -#: ../../library/sqlite3.rst:2723 +#: ../../library/sqlite3.rst:2726 msgid "" "If :attr:`~Connection.isolation_level` is set to ``None``, no transactions " "are implicitly opened at all. This leaves the underlying SQLite library in " @@ -2614,7 +3321,7 @@ msgstr "" "modo de autocommit da biblioteca SQLite subjacente pode ser consultado " "usando o atributo :attr:`~Connection.in_transaction`." -#: ../../library/sqlite3.rst:2731 +#: ../../library/sqlite3.rst:2734 msgid "" "The :meth:`~Cursor.executescript` method implicitly commits any pending " "transaction before execution of the given SQL script, regardless of the " @@ -2624,7 +3331,7 @@ msgstr "" "transação pendente antes da execução do script SQL fornecido, " "independentemente do valor de :attr:`~Connection.isolation_level`." -#: ../../library/sqlite3.rst:2735 +#: ../../library/sqlite3.rst:2738 msgid "" ":mod:`!sqlite3` used to implicitly commit an open transaction before DDL " "statements. This is no longer the case." @@ -2632,7 +3339,7 @@ msgstr "" ":mod:`!sqlite3` costumava fazer commit de forma implícita de uma transação " "aberta antes das instruções DDL. Este não é mais o caso." -#: ../../library/sqlite3.rst:2739 +#: ../../library/sqlite3.rst:2742 msgid "" "The recommended way of controlling transactions is now via the :attr:" "`~Connection.autocommit` attribute." @@ -2640,14 +3347,14 @@ msgstr "" "A forma recomendada de controlar transações agora é através do atributo :" "attr:`~Connection.autocommit`." -#: ../../library/sqlite3.rst:1491 +#: ../../library/sqlite3.rst:1493 msgid "? (question mark)" msgstr "? (interrogação)" -#: ../../library/sqlite3.rst:1491 ../../library/sqlite3.rst:1492 +#: ../../library/sqlite3.rst:1493 ../../library/sqlite3.rst:1494 msgid "in SQL statements" msgstr "em instruções SQL" -#: ../../library/sqlite3.rst:1492 +#: ../../library/sqlite3.rst:1494 msgid ": (colon)" msgstr ": (dois pontos)" diff --git a/library/ssl.po b/library/ssl.po index f66d2fd1e..0e9aab291 100644 --- a/library/ssl.po +++ b/library/ssl.po @@ -1,39 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Leticia Portella , 2021 -# Italo Penaforte , 2021 -# felipe caridade fernandes , 2021 -# Raphael Mendonça, 2021 -# Marco Rougeth , 2021 -# Rafael Biagioni de Fazio , 2021 -# Claudio Rogerio Carvalho Filho , 2023 -# i17obot , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:13+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/ssl.rst:2 msgid ":mod:`!ssl` --- TLS/SSL wrapper for socket objects" -msgstr "" +msgstr ":mod:`!ssl` --- Invólucro de TLS/SSL para objetos socket" #: ../../library/ssl.rst:10 msgid "**Source code:** :source:`Lib/ssl.py`" @@ -48,6 +40,13 @@ msgid "" "and probably additional platforms, as long as OpenSSL is installed on that " "platform." msgstr "" +"Este módulo fornece acesso à criptografia Transport Layer Security " +"(frequentemente conhecida como \"Secure Sockets Layer\") e aos recursos de " +"autenticação de pares para sockets de rede, tanto do lado do cliente quanto " +"do lado do servidor. Este módulo usa a biblioteca OpenSSL. Ela está " +"disponível em todos os sistemas Unix modernos, Windows, macOS e " +"provavelmente plataformas adicionais, desde que o OpenSSL esteja instalado " +"nessa plataforma." #: ../../library/ssl.rst:26 msgid "" @@ -56,6 +55,10 @@ msgid "" "cause variations in behavior. For example, TLSv1.3 comes with OpenSSL " "version 1.1.1." msgstr "" +"Alguns comportamentos podem depender da plataforma, já que chamadas são " +"feitas para as APIs de socket do sistema operacional. A versão instalada do " +"OpenSSL também pode causar variações no comportamento. Por exemplo, o " +"TLSv1.3 vem com a versão 1.1.1 do OpenSSL." #: ../../library/ssl.rst:32 msgid "" @@ -63,10 +66,14 @@ msgid "" "lead to a false sense of security, as the default settings of the ssl module " "are not necessarily appropriate for your application." msgstr "" +"Não use este módulo sem ler o :ref:`ssl-security`. Fazer isso pode levar a " +"uma falsa sensação de segurança, pois as configurações padrão do módulo ssl " +"não são necessariamente apropriadas para sua aplicação." +#: ../../library/ssl.rst:454 ../../library/ssl.rst:469 #: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +msgid "Availability" +msgstr "Disponibilidade" #: ../../includes/wasm-notavail.rst:5 msgid "" @@ -82,6 +89,9 @@ msgid "" "more general information about TLS, SSL, and certificates, the reader is " "referred to the documents in the \"See Also\" section at the bottom." msgstr "" +"Esta seção documenta os objetos e funções no módulo ``ssl``; para obter mais " +"informações gerais sobre TLS, SSL e certificados, o leitor pode consultar os " +"documentos na seção \"Consulte também\" na parte inferior." #: ../../library/ssl.rst:42 msgid "" @@ -94,6 +104,13 @@ msgid "" "`get_verified_chain`, :meth:`get_unverified_chain` which retrieves " "certificate chain." msgstr "" +"Este módulo fornece uma classe, :class:`ssl.SSLSocket`, que é derivada do " +"tipo :class:`socket.socket`, e fornece um wrapper semelhante a um socket que " +"também criptografa e descriptografa os dados que passam pelo socket com SSL. " +"Ele suporta métodos adicionais como :meth:`getpeercert`, que recupera o " +"certificado do outro lado da conexão, :meth:`cipher`, que recupera a cifra " +"sendo usada para a conexão segura ou :meth:`get_verified_chain`, :meth:" +"`get_unverified_chain` que recupera a cadeia de certificados." #: ../../library/ssl.rst:51 msgid "" @@ -101,35 +118,44 @@ msgid "" "manage settings and certificates, which can then be inherited by SSL sockets " "created through the :meth:`SSLContext.wrap_socket` method." msgstr "" +"Para aplicações mais sofisticadas, a classe :class:`ssl.SSLContext` ajuda a " +"gerenciar configurações e certificados, que podem ser herdados por soquetes " +"SSL criados por meio do método :meth:`SSLContext.wrap_socket`." #: ../../library/ssl.rst:55 msgid "Updated to support linking with OpenSSL 1.1.0" -msgstr "" +msgstr "Atualizado para oferecer suporte à vinculação com OpenSSL 1.1.0" #: ../../library/ssl.rst:60 msgid "" "OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported. In " "the future the ssl module will require at least OpenSSL 1.0.2 or 1.1.0." msgstr "" +"OpenSSL 0.9.8, 1.0.0 e 1.0.1 estão descontinuado e não são mais suportados. " +"No futuro, o módulo ssl exigirá pelo menos OpenSSL 1.0.2 ou 1.1.0." #: ../../library/ssl.rst:66 msgid "" ":pep:`644` has been implemented. The ssl module requires OpenSSL 1.1.1 or " "newer." msgstr "" +":pep:`644` foi implementado. O módulo ssl requer OpenSSL 1.1.1 ou mais " +"recente." #: ../../library/ssl.rst:69 msgid "" "Use of deprecated constants and functions result in deprecation warnings." msgstr "" +"O uso de constantes e funções descontinuados resulta em avisos de " +"descontinuação." #: ../../library/ssl.rst:73 msgid "Functions, Constants, and Exceptions" -msgstr "" +msgstr "Funções, constantes e exceções." #: ../../library/ssl.rst:77 msgid "Socket creation" -msgstr "" +msgstr "Criação de socket" #: ../../library/ssl.rst:79 msgid "" @@ -137,22 +163,91 @@ msgid "" "wrap_socket` method. The helper function :func:`create_default_context` " "returns a new context with secure default settings." msgstr "" +"Instâncias de :class:`SSLSocket` devem ser criadas usando o método :meth:" +"`SSLContext.wrap_socket`. A função auxiliar :func:`create_default_context` " +"retorna um novo contexto com configurações padrão seguras." #: ../../library/ssl.rst:84 msgid "Client socket example with default context and IPv4/IPv6 dual stack::" msgstr "" +"Exemplo de soquete de cliente com contexto padrão e pilha dupla IPv4/IPv6::" + +#: ../../library/ssl.rst:86 +msgid "" +"import socket\n" +"import ssl\n" +"\n" +"hostname = 'www.python.org'\n" +"context = ssl.create_default_context()\n" +"\n" +"with socket.create_connection((hostname, 443)) as sock:\n" +" with context.wrap_socket(sock, server_hostname=hostname) as ssock:\n" +" print(ssock.version())" +msgstr "" +"import socket\n" +"import ssl\n" +"\n" +"hostname = 'www.python.org'\n" +"context = ssl.create_default_context()\n" +"\n" +"with socket.create_connection((hostname, 443)) as sock:\n" +" with context.wrap_socket(sock, server_hostname=hostname) as ssock:\n" +" print(ssock.version())" #: ../../library/ssl.rst:97 msgid "Client socket example with custom context and IPv4::" -msgstr "" +msgstr "Exemplo de soquete de cliente com contexto personalizado e IPv4::" + +#: ../../library/ssl.rst:99 +msgid "" +"hostname = 'www.python.org'\n" +"# PROTOCOL_TLS_CLIENT requires valid cert chain and hostname\n" +"context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\n" +"context.load_verify_locations('path/to/cabundle.pem')\n" +"\n" +"with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:\n" +" with context.wrap_socket(sock, server_hostname=hostname) as ssock:\n" +" print(ssock.version())" +msgstr "" +"hostname = 'www.python.org'\n" +"# PROTOCOL_TLS_CLIENT requer hostname e cadeia de certificados\n" +"context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\n" +"context.load_verify_locations('path/to/cabundle.pem')\n" +"\n" +"with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:\n" +" with context.wrap_socket(sock, server_hostname=hostname) as ssock:\n" +" print(ssock.version())" #: ../../library/ssl.rst:109 msgid "Server socket example listening on localhost IPv4::" -msgstr "" +msgstr "Exemplo de soquete de servidor escutando no localhost IPv4::" + +#: ../../library/ssl.rst:111 +msgid "" +"context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\n" +"context.load_cert_chain('/path/to/certchain.pem', '/path/to/private.key')\n" +"\n" +"with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:\n" +" sock.bind(('127.0.0.1', 8443))\n" +" sock.listen(5)\n" +" with context.wrap_socket(sock, server_side=True) as ssock:\n" +" conn, addr = ssock.accept()\n" +" ..." +msgstr "" +"context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\n" +"context.load_cert_chain('/caminho/para/cadeia-certicado.pem', '/caminho/para/" +"privado.key')\n" +"\n" +"with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:\n" +" sock.bind(('127.0.0.1', 8443))\n" +" sock.listen(5)\n" +" with context.wrap_socket(sock, server_side=True) as ssock:\n" +" conn, addr = ssock.accept()\n" +" ..." #: ../../library/ssl.rst:123 msgid "Context creation" -msgstr "" +msgstr "Criação de contexto" #: ../../library/ssl.rst:125 msgid "" @@ -228,6 +323,12 @@ msgid "" "still allow SSL 3.0 connections you can re-enable them using::" msgstr "" +#: ../../library/ssl.rst:178 +msgid "" +"ctx = ssl.create_default_context(Purpose.CLIENT_AUTH)\n" +"ctx.options &= ~ssl.OP_NO_SSLv3" +msgstr "" + #: ../../library/ssl.rst:182 msgid "" "This context enables :data:`VERIFY_X509_STRICT` by default, which may reject " @@ -236,6 +337,12 @@ msgid "" "recommended, you can do so using::" msgstr "" +#: ../../library/ssl.rst:187 +msgid "" +"ctx = ssl.create_default_context()\n" +"ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT" +msgstr "" + #: ../../library/ssl.rst:194 msgid "RC4 was dropped from the default cipher string." msgstr "" @@ -412,6 +519,17 @@ msgstr "" msgid "Here's an example:" msgstr "" +#: ../../library/ssl.rst:367 +msgid "" +">>> import ssl\n" +">>> timestamp = ssl.cert_time_to_seconds(\"Jan 5 09:34:43 2018 GMT\")\n" +">>> timestamp\n" +"1515144883\n" +">>> from datetime import datetime\n" +">>> print(datetime.utcfromtimestamp(timestamp))\n" +"2018-01-05 09:34:43" +msgstr "" + #: ../../library/ssl.rst:377 msgid "\"notBefore\" or \"notAfter\" dates must use GMT (:rfc:`5280`)." msgstr "" @@ -523,9 +641,12 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" -#: ../../library/ssl.rst:454 ../../library/ssl.rst:469 -msgid ":ref:`Availability `: Windows." -msgstr ":ref:`Disponibilidade `: Windows." +#: ../../library/ssl.rst:450 +msgid "" +">>> ssl.enum_certificates(\"CA\")\n" +"[(b'data...', 'x509_asn', {'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'}),\n" +" (b'data...', 'x509_asn', True)]" +msgstr "" #: ../../library/ssl.rst:460 msgid "" @@ -983,16 +1104,36 @@ msgstr "" msgid "The version string of the OpenSSL library loaded by the interpreter::" msgstr "" +#: ../../library/ssl.rst:948 +msgid "" +">>> ssl.OPENSSL_VERSION\n" +"'OpenSSL 1.0.2k 26 Jan 2017'" +msgstr "" + #: ../../library/ssl.rst:955 msgid "" "A tuple of five integers representing version information about the OpenSSL " "library::" msgstr "" +#: ../../library/ssl.rst:958 +msgid "" +">>> ssl.OPENSSL_VERSION_INFO\n" +"(1, 0, 2, 11, 15)" +msgstr "" + #: ../../library/ssl.rst:965 msgid "The raw version number of the OpenSSL library, as a single integer::" msgstr "" +#: ../../library/ssl.rst:967 +msgid "" +">>> ssl.OPENSSL_VERSION_NUMBER\n" +"268443839\n" +">>> hex(ssl.OPENSSL_VERSION_NUMBER)\n" +"'0x100020bf'" +msgstr "" + #: ../../library/ssl.rst:978 msgid "" "Alert Descriptions from :rfc:`5246` and others. The `IANA TLS Alert Registry " @@ -1063,78 +1204,72 @@ msgid "SSL sockets provide the following methods of :ref:`socket-objects`:" msgstr "" #: ../../library/ssl.rst:1052 -msgid ":meth:`~socket.socket.accept()`" -msgstr ":meth:`~socket.socket.accept()`" +msgid ":meth:`~socket.socket.accept`" +msgstr "" #: ../../library/ssl.rst:1053 -msgid ":meth:`~socket.socket.bind()`" -msgstr ":meth:`~socket.socket.bind()`" +msgid ":meth:`~socket.socket.bind`" +msgstr "" #: ../../library/ssl.rst:1054 -msgid ":meth:`~socket.socket.close()`" -msgstr ":meth:`~socket.socket.close()`" +msgid ":meth:`~socket.socket.close`" +msgstr "" #: ../../library/ssl.rst:1055 -msgid ":meth:`~socket.socket.connect()`" -msgstr ":meth:`~socket.socket.connect()`" +msgid ":meth:`~socket.socket.connect`" +msgstr "" #: ../../library/ssl.rst:1056 -msgid ":meth:`~socket.socket.detach()`" -msgstr ":meth:`~socket.socket.detach()`" +msgid ":meth:`~socket.socket.detach`" +msgstr "" #: ../../library/ssl.rst:1057 -msgid ":meth:`~socket.socket.fileno()`" -msgstr ":meth:`~socket.socket.fileno()`" +msgid ":meth:`~socket.socket.fileno`" +msgstr "" #: ../../library/ssl.rst:1058 -msgid "" -":meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()`" +msgid ":meth:`~socket.socket.getpeername`, :meth:`~socket.socket.getsockname`" msgstr "" -":meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()`" #: ../../library/ssl.rst:1059 -msgid "" -":meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()`" +msgid ":meth:`~socket.socket.getsockopt`, :meth:`~socket.socket.setsockopt`" msgstr "" -":meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()`" #: ../../library/ssl.rst:1060 msgid "" -":meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`, :" -"meth:`~socket.socket.setblocking()`" +":meth:`~socket.socket.gettimeout`, :meth:`~socket.socket.settimeout`, :meth:" +"`~socket.socket.setblocking`" msgstr "" -":meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`, :" -"meth:`~socket.socket.setblocking()`" #: ../../library/ssl.rst:1062 -msgid ":meth:`~socket.socket.listen()`" -msgstr ":meth:`~socket.socket.listen()`" +msgid ":meth:`~socket.socket.listen`" +msgstr "" #: ../../library/ssl.rst:1063 -msgid ":meth:`~socket.socket.makefile()`" -msgstr ":meth:`~socket.socket.makefile()`" +msgid ":meth:`~socket.socket.makefile`" +msgstr "" #: ../../library/ssl.rst:1064 msgid "" -":meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()` (but " -"passing a non-zero ``flags`` argument is not allowed)" +":meth:`~socket.socket.recv`, :meth:`~socket.socket.recv_into` (but passing a " +"non-zero ``flags`` argument is not allowed)" msgstr "" #: ../../library/ssl.rst:1066 msgid "" -":meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with the " -"same limitation)" +":meth:`~socket.socket.send`, :meth:`~socket.socket.sendall` (with the same " +"limitation)" msgstr "" #: ../../library/ssl.rst:1068 msgid "" -":meth:`~socket.socket.sendfile()` (but :mod:`os.sendfile` will be used for " -"plain-text sockets only, else :meth:`~socket.socket.send()` will be used)" +":meth:`~socket.socket.sendfile` (but :mod:`os.sendfile` will be used for " +"plain-text sockets only, else :meth:`~socket.socket.send` will be used)" msgstr "" #: ../../library/ssl.rst:1070 -msgid ":meth:`~socket.socket.shutdown()`" -msgstr ":meth:`~socket.socket.shutdown()`" +msgid ":meth:`~socket.socket.shutdown`" +msgstr "" #: ../../library/ssl.rst:1072 msgid "" @@ -1310,6 +1445,29 @@ msgid "" "value pairs. Here is a real-world example::" msgstr "" +#: ../../library/ssl.rst:1194 +msgid "" +"{'issuer': ((('countryName', 'IL'),),\n" +" (('organizationName', 'StartCom Ltd.'),),\n" +" (('organizationalUnitName',\n" +" 'Secure Digital Certificate Signing'),),\n" +" (('commonName',\n" +" 'StartCom Class 2 Primary Intermediate Server CA'),)),\n" +" 'notAfter': 'Nov 22 08:15:19 2013 GMT',\n" +" 'notBefore': 'Nov 21 03:09:52 2011 GMT',\n" +" 'serialNumber': '95F0',\n" +" 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),),\n" +" (('countryName', 'US'),),\n" +" (('stateOrProvinceName', 'California'),),\n" +" (('localityName', 'San Francisco'),),\n" +" (('organizationName', 'Electronic Frontier Foundation, " +"Inc.'),),\n" +" (('commonName', '*.eff.org'),),\n" +" (('emailAddress', 'hostmaster@eff.org'),)),\n" +" 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),\n" +" 'version': 3}" +msgstr "" + #: ../../library/ssl.rst:1213 msgid "" "If the ``binary_form`` parameter is :const:`True`, and a certificate was " @@ -1696,6 +1854,12 @@ msgstr "" msgid "Example for a context with one CA cert and one other cert::" msgstr "" +#: ../../library/ssl.rst:1499 +msgid "" +">>> context.cert_store_stats()\n" +"{'crl': 0, 'x509_ca': 1, 'x509': 2}" +msgstr "" + #: ../../library/ssl.rst:1507 msgid "" "Load a private key and the corresponding certificate. The *certfile* string " @@ -1779,8 +1943,7 @@ msgstr "" msgid "" "The *capath* string, if present, is the path to a directory containing " "several CA certificates in PEM format, following an `OpenSSL specific layout " -"`_." +"`_." msgstr "" #: ../../library/ssl.rst:1571 @@ -1817,6 +1980,37 @@ msgid "" "meth:`SSLContext.set_ciphers`." msgstr "" +#: ../../library/ssl.rst:1601 +msgid "" +">>> ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n" +">>> ctx.set_ciphers('ECDHE+AESGCM:!ECDSA')\n" +">>> ctx.get_ciphers()\n" +"[{'aead': True,\n" +" 'alg_bits': 256,\n" +" 'auth': 'auth-rsa',\n" +" 'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA '\n" +" 'Enc=AESGCM(256) Mac=AEAD',\n" +" 'digest': None,\n" +" 'id': 50380848,\n" +" 'kea': 'kx-ecdhe',\n" +" 'name': 'ECDHE-RSA-AES256-GCM-SHA384',\n" +" 'protocol': 'TLSv1.2',\n" +" 'strength_bits': 256,\n" +" 'symmetric': 'aes-256-gcm'},\n" +" {'aead': True,\n" +" 'alg_bits': 128,\n" +" 'auth': 'auth-rsa',\n" +" 'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA '\n" +" 'Enc=AESGCM(128) Mac=AEAD',\n" +" 'digest': None,\n" +" 'id': 50380847,\n" +" 'kea': 'kx-ecdhe',\n" +" 'name': 'ECDHE-RSA-AES128-GCM-SHA256',\n" +" 'protocol': 'TLSv1.2',\n" +" 'strength_bits': 128,\n" +" 'symmetric': 'aes-128-gcm'}]" +msgstr "" + #: ../../library/ssl.rst:1633 msgid "" "Load a set of default \"certification authority\" (CA) certificates from a " @@ -1830,10 +2024,10 @@ msgstr "" #: ../../library/ssl.rst:1642 msgid "" "Set the available ciphers for sockets created with this context. It should " -"be a string in the `OpenSSL cipher list format `_. If no cipher can be selected (because " -"compile-time options or other configuration forbids use of all the specified " -"ciphers), an :class:`SSLError` will be raised." +"be a string in the `OpenSSL cipher list format `_. If no cipher can be selected (because compile-time " +"options or other configuration forbids use of all the specified ciphers), " +"an :class:`SSLError` will be raised." msgstr "" #: ../../library/ssl.rst:1650 @@ -2127,9 +2321,16 @@ msgstr "" msgid "" "Get statistics about the SSL sessions created or managed by this context. A " "dictionary is returned which maps the names of each `piece of information " -"`_ to " -"their numeric values. For example, here is the total number of hits and " -"misses in the session cache since the context was created::" +"`_ to their " +"numeric values. For example, here is the total number of hits and misses in " +"the session cache since the context was created::" +msgstr "" + +#: ../../library/ssl.rst:1881 +msgid "" +">>> stats = context.session_stats()\n" +">>> stats['hits'], stats['misses']\n" +"(0, 0)" msgstr "" #: ../../library/ssl.rst:1887 @@ -2145,6 +2346,20 @@ msgid "" "With other protocols, hostname checking must be enabled explicitly." msgstr "" +#: ../../library/ssl.rst:1900 +msgid "" +"import socket, ssl\n" +"\n" +"context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)\n" +"context.verify_mode = ssl.CERT_REQUIRED\n" +"context.check_hostname = True\n" +"context.load_default_certs()\n" +"\n" +"s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" +"ssl_sock = context.wrap_socket(s, server_hostname='www.verisign.com')\n" +"ssl_sock.connect(('www.verisign.com', 443))" +msgstr "" + #: ../../library/ssl.rst:1915 msgid "" ":attr:`~SSLContext.verify_mode` is now automatically changed to :data:" @@ -2166,8 +2381,8 @@ msgstr "" msgid "" "A :class:`TLSVersion` enum member representing the highest supported TLS " "version. The value defaults to :attr:`TLSVersion.MAXIMUM_SUPPORTED`. The " -"attribute is read-only for protocols other than :attr:`PROTOCOL_TLS`, :attr:" -"`PROTOCOL_TLS_CLIENT`, and :attr:`PROTOCOL_TLS_SERVER`." +"attribute is read-only for protocols other than :const:`PROTOCOL_TLS`, :" +"const:`PROTOCOL_TLS_CLIENT`, and :const:`PROTOCOL_TLS_SERVER`." msgstr "" #: ../../library/ssl.rst:1937 @@ -2188,7 +2403,7 @@ msgstr "" #: ../../library/ssl.rst:1957 msgid "" -"Control the number of TLS 1.3 session tickets of a :attr:" +"Control the number of TLS 1.3 session tickets of a :const:" "`PROTOCOL_TLS_SERVER` context. The setting has no impact on TLS 1.0 to 1.2 " "connections." msgstr "" @@ -2254,9 +2469,9 @@ msgstr "" #: ../../library/ssl.rst:2019 msgid "" -"An integer representing the `security level `_ for the context. This " -"attribute is read-only." +"An integer representing the `security level `_ for the context. This attribute is read-" +"only." msgstr "" #: ../../library/ssl.rst:2027 @@ -2324,6 +2539,27 @@ msgstr "" msgid "Example usage::" msgstr "Exemplo de uso::" +#: ../../library/ssl.rst:2077 +msgid "" +"context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\n" +"context.check_hostname = False\n" +"context.verify_mode = ssl.CERT_NONE\n" +"context.maximum_version = ssl.TLSVersion.TLSv1_2\n" +"context.set_ciphers('PSK')\n" +"\n" +"# A simple lambda:\n" +"psk = bytes.fromhex('c0ffee')\n" +"context.set_psk_client_callback(lambda hint: (None, psk))\n" +"\n" +"# A table using the hint from the server:\n" +"psk_table = { 'ServerId_1': bytes.fromhex('c0ffee'),\n" +" 'ServerId_2': bytes.fromhex('facade')\n" +"}\n" +"def callback(hint):\n" +" return 'ClientId_1', psk_table.get(hint, b'')\n" +"context.set_psk_client_callback(callback)" +msgstr "" + #: ../../library/ssl.rst:2095 ../../library/ssl.rst:2140 msgid "" "This method will raise :exc:`NotImplementedError` if :data:`HAS_PSK` is " @@ -2357,6 +2593,25 @@ msgid "" "When using TLS 1.3 the ``identity_hint`` parameter is not sent to the client." msgstr "" +#: ../../library/ssl.rst:2124 +msgid "" +"context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\n" +"context.maximum_version = ssl.TLSVersion.TLSv1_2\n" +"context.set_ciphers('PSK')\n" +"\n" +"# A simple lambda:\n" +"psk = bytes.fromhex('c0ffee')\n" +"context.set_psk_server_callback(lambda identity: psk)\n" +"\n" +"# A table using the identity of the client:\n" +"psk_table = { 'ClientId_1': bytes.fromhex('c0ffee'),\n" +" 'ClientId_2': bytes.fromhex('facade')\n" +"}\n" +"def callback(identity):\n" +" return psk_table.get(identity, b'')\n" +"context.set_psk_server_callback(callback, 'ServerId_1')" +msgstr "" + #: ../../library/ssl.rst:2152 msgid "Certificates" msgstr "Certificados" @@ -2406,6 +2661,13 @@ msgid "" "header line and a footer line::" msgstr "" +#: ../../library/ssl.rst:2186 +msgid "" +"-----BEGIN CERTIFICATE-----\n" +"... (certificate in base64 PEM encoding) ...\n" +"-----END CERTIFICATE-----" +msgstr "" + #: ../../library/ssl.rst:2191 msgid "Certificate chains" msgstr "" @@ -2426,6 +2688,19 @@ msgid "" "agency which issued the certification authority's certificate::" msgstr "" +#: ../../library/ssl.rst:2206 +msgid "" +"-----BEGIN CERTIFICATE-----\n" +"... (certificate for your server)...\n" +"-----END CERTIFICATE-----\n" +"-----BEGIN CERTIFICATE-----\n" +"... (the certificate for the CA)...\n" +"-----END CERTIFICATE-----\n" +"-----BEGIN CERTIFICATE-----\n" +"... (the root certificate for the CA's issuer)...\n" +"-----END CERTIFICATE-----" +msgstr "" + #: ../../library/ssl.rst:2217 msgid "CA certificates" msgstr "" @@ -2454,6 +2729,16 @@ msgid "" "should come before the first certificate in the certificate chain::" msgstr "" +#: ../../library/ssl.rst:2236 +msgid "" +"-----BEGIN RSA PRIVATE KEY-----\n" +"... (private key in base64 encoding) ...\n" +"-----END RSA PRIVATE KEY-----\n" +"-----BEGIN CERTIFICATE-----\n" +"... (certificate in base64 PEM encoding) ...\n" +"-----END CERTIFICATE-----" +msgstr "" + #: ../../library/ssl.rst:2244 msgid "Self-signed certificates" msgstr "" @@ -2468,6 +2753,32 @@ msgid "" "package, using something like the following::" msgstr "" +#: ../../library/ssl.rst:2253 +msgid "" +"% openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem\n" +"Generating a 1024 bit RSA private key\n" +".......++++++\n" +".............................++++++\n" +"writing new private key to 'cert.pem'\n" +"-----\n" +"You are about to be asked to enter information that will be incorporated\n" +"into your certificate request.\n" +"What you are about to enter is what is called a Distinguished Name or a DN.\n" +"There are quite a few fields but you can leave some blank\n" +"For some fields there will be a default value,\n" +"If you enter '.', the field will be left blank.\n" +"-----\n" +"Country Name (2 letter code) [AU]:US\n" +"State or Province Name (full name) [Some-State]:MyState\n" +"Locality Name (eg, city) []:Some City\n" +"Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, " +"Inc.\n" +"Organizational Unit Name (eg, section) []:My Group\n" +"Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com\n" +"Email Address []:ops@myserver.mygroup.myorganization.com\n" +"%" +msgstr "" + #: ../../library/ssl.rst:2275 msgid "" "The disadvantage of a self-signed certificate is that it is its own root " @@ -2489,6 +2800,16 @@ msgid "" "should use the following idiom::" msgstr "" +#: ../../library/ssl.rst:2289 +msgid "" +"try:\n" +" import ssl\n" +"except ImportError:\n" +" pass\n" +"else:\n" +" ... # do something that requires SSL support" +msgstr "" + #: ../../library/ssl.rst:2297 msgid "Client-side operation" msgstr "" @@ -2499,12 +2820,22 @@ msgid "" "for client sockets, including automatic certificate verification::" msgstr "" +#: ../../library/ssl.rst:2302 +msgid ">>> context = ssl.create_default_context()" +msgstr "" + #: ../../library/ssl.rst:2304 msgid "" "If you prefer to tune security settings yourself, you might create a context " "from scratch (but beware that you might not get the settings right)::" msgstr "" +#: ../../library/ssl.rst:2308 +msgid "" +">>> context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\n" +">>> context.load_verify_locations(\"/etc/ssl/certs/ca-bundle.crt\")" +msgstr "" + #: ../../library/ssl.rst:2311 msgid "" "(this snippet assumes your operating system places a bundle of all CA " @@ -2529,22 +2860,103 @@ msgid "" "properties like validity and identity of the hostname::" msgstr "" +#: ../../library/ssl.rst:2326 +msgid "" +">>> conn = context.wrap_socket(socket.socket(socket.AF_INET),\n" +"... server_hostname=\"www.python.org\")\n" +">>> conn.connect((\"www.python.org\", 443))" +msgstr "" + #: ../../library/ssl.rst:2330 msgid "You may then fetch the certificate::" msgstr "" +#: ../../library/ssl.rst:2332 +msgid ">>> cert = conn.getpeercert()" +msgstr "" + #: ../../library/ssl.rst:2334 msgid "" "Visual inspection shows that the certificate does identify the desired " "service (that is, the HTTPS host ``www.python.org``)::" msgstr "" +#: ../../library/ssl.rst:2337 +msgid "" +">>> pprint.pprint(cert)\n" +"{'OCSP': ('http://ocsp.digicert.com',),\n" +" 'caIssuers': ('http://cacerts.digicert.com/" +"DigiCertSHA2ExtendedValidationServerCA.crt',),\n" +" 'crlDistributionPoints': ('http://crl3.digicert.com/sha2-ev-server-g1." +"crl',\n" +" 'http://crl4.digicert.com/sha2-ev-server-g1." +"crl'),\n" +" 'issuer': ((('countryName', 'US'),),\n" +" (('organizationName', 'DigiCert Inc'),),\n" +" (('organizationalUnitName', 'www.digicert.com'),),\n" +" (('commonName', 'DigiCert SHA2 Extended Validation Server " +"CA'),)),\n" +" 'notAfter': 'Sep 9 12:00:00 2016 GMT',\n" +" 'notBefore': 'Sep 5 00:00:00 2014 GMT',\n" +" 'serialNumber': '01BB6F00122B177F36CAB49CEA8B6B26',\n" +" 'subject': ((('businessCategory', 'Private Organization'),),\n" +" (('1.3.6.1.4.1.311.60.2.1.3', 'US'),),\n" +" (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),\n" +" (('serialNumber', '3359300'),),\n" +" (('streetAddress', '16 Allen Rd'),),\n" +" (('postalCode', '03894-4801'),),\n" +" (('countryName', 'US'),),\n" +" (('stateOrProvinceName', 'NH'),),\n" +" (('localityName', 'Wolfeboro'),),\n" +" (('organizationName', 'Python Software Foundation'),),\n" +" (('commonName', 'www.python.org'),)),\n" +" 'subjectAltName': (('DNS', 'www.python.org'),\n" +" ('DNS', 'python.org'),\n" +" ('DNS', 'pypi.org'),\n" +" ('DNS', 'docs.python.org'),\n" +" ('DNS', 'testpypi.org'),\n" +" ('DNS', 'bugs.python.org'),\n" +" ('DNS', 'wiki.python.org'),\n" +" ('DNS', 'hg.python.org'),\n" +" ('DNS', 'mail.python.org'),\n" +" ('DNS', 'packaging.python.org'),\n" +" ('DNS', 'pythonhosted.org'),\n" +" ('DNS', 'www.pythonhosted.org'),\n" +" ('DNS', 'test.pythonhosted.org'),\n" +" ('DNS', 'us.pycon.org'),\n" +" ('DNS', 'id.python.org')),\n" +" 'version': 3}" +msgstr "" + #: ../../library/ssl.rst:2377 msgid "" "Now the SSL channel is established and the certificate verified, you can " "proceed to talk with the server::" msgstr "" +#: ../../library/ssl.rst:2380 +msgid "" +">>> conn.sendall(b\"HEAD / HTTP/1.0\\r\\nHost: linuxfr.org\\r\\n\\r\\n\")\n" +">>> pprint.pprint(conn.recv(1024).split(b\"\\r\\n\"))\n" +"[b'HTTP/1.1 200 OK',\n" +" b'Date: Sat, 18 Oct 2014 18:27:20 GMT',\n" +" b'Server: nginx',\n" +" b'Content-Type: text/html; charset=utf-8',\n" +" b'X-Frame-Options: SAMEORIGIN',\n" +" b'Content-Length: 45679',\n" +" b'Accept-Ranges: bytes',\n" +" b'Via: 1.1 varnish',\n" +" b'Age: 2188',\n" +" b'X-Served-By: cache-lcy1134-LCY',\n" +" b'X-Cache: HIT',\n" +" b'X-Cache-Hits: 11',\n" +" b'Vary: Cookie',\n" +" b'Strict-Transport-Security: max-age=63072000; includeSubDomains',\n" +" b'Connection: close',\n" +" b'',\n" +" b'']" +msgstr "" + #: ../../library/ssl.rst:2404 msgid "Server-side operation" msgstr "" @@ -2558,6 +2970,18 @@ msgid "" "start waiting for clients to connect::" msgstr "" +#: ../../library/ssl.rst:2412 +msgid "" +"import socket, ssl\n" +"\n" +"context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n" +"context.load_cert_chain(certfile=\"mycertfile\", keyfile=\"mykeyfile\")\n" +"\n" +"bindsocket = socket.socket()\n" +"bindsocket.bind(('myaddr.example.com', 10023))\n" +"bindsocket.listen(5)" +msgstr "" + #: ../../library/ssl.rst:2421 msgid "" "When a client connects, you'll call :meth:`accept` on the socket to get the " @@ -2565,12 +2989,38 @@ msgid "" "wrap_socket` method to create a server-side SSL socket for the connection::" msgstr "" +#: ../../library/ssl.rst:2425 +msgid "" +"while True:\n" +" newsocket, fromaddr = bindsocket.accept()\n" +" connstream = context.wrap_socket(newsocket, server_side=True)\n" +" try:\n" +" deal_with_client(connstream)\n" +" finally:\n" +" connstream.shutdown(socket.SHUT_RDWR)\n" +" connstream.close()" +msgstr "" + #: ../../library/ssl.rst:2434 msgid "" "Then you'll read data from the ``connstream`` and do something with it till " "you are finished with the client (or the client is finished with you)::" msgstr "" +#: ../../library/ssl.rst:2437 +msgid "" +"def deal_with_client(connstream):\n" +" data = connstream.recv(1024)\n" +" # empty data means the client is finished with us\n" +" while data:\n" +" if not do_something(connstream, data):\n" +" # we'll assume do_something returns False\n" +" # when we're finished with client\n" +" break\n" +" data = connstream.recv(1024)\n" +" # finished with client" +msgstr "" + #: ../../library/ssl.rst:2448 msgid "" "And go back to listening for new client connections (of course, a real " @@ -2641,13 +3091,26 @@ msgid "" "readiness::" msgstr "" +#: ../../library/ssl.rst:2499 +msgid "" +"while True:\n" +" try:\n" +" sock.do_handshake()\n" +" break\n" +" except ssl.SSLWantReadError:\n" +" select.select([sock], [], [])\n" +" except ssl.SSLWantWriteError:\n" +" select.select([], [sock], [])" +msgstr "" + #: ../../library/ssl.rst:2510 msgid "" "The :mod:`asyncio` module supports :ref:`non-blocking SSL sockets ` and provides a higher level API. It polls for events using " -"the :mod:`selectors` module and handles :exc:`SSLWantWriteError`, :exc:" -"`SSLWantReadError` and :exc:`BlockingIOError` exceptions. It runs the SSL " -"handshake asynchronously as well." +"nonblocking>` and provides a higher level :ref:`Streams API `. It polls for events using the :mod:`selectors` module and " +"handles :exc:`SSLWantWriteError`, :exc:`SSLWantReadError` and :exc:" +"`BlockingIOError` exceptions. It runs the SSL handshake asynchronously as " +"well." msgstr "" #: ../../library/ssl.rst:2519 @@ -2938,6 +3401,15 @@ msgid "" "create a trusted, secure connection to a SMTP server::" msgstr "" +#: ../../library/ssl.rst:2691 +msgid "" +">>> import ssl, smtplib\n" +">>> smtp = smtplib.SMTP(\"mail.python.org\", port=587)\n" +">>> context = ssl.create_default_context()\n" +">>> smtp.starttls(context=context)\n" +"(220, b'2.0.0 Ready to start TLS')" +msgstr "" + #: ../../library/ssl.rst:2697 msgid "" "If a client certificate is needed for the connection, it can be added with :" @@ -3002,6 +3474,13 @@ msgid "" "by default." msgstr "" +#: ../../library/ssl.rst:2743 +msgid "" +">>> client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\n" +">>> client_context.minimum_version = ssl.TLSVersion.TLSv1_3\n" +">>> client_context.maximum_version = ssl.TLSVersion.TLSv1_3" +msgstr "" + #: ../../library/ssl.rst:2748 msgid "" "The SSL context created above will only allow TLSv1.3 and later (if " @@ -3021,10 +3500,10 @@ msgid "" "`SSLContext.set_ciphers` method. Starting from Python 3.2.3, the ssl module " "disables certain weak ciphers by default, but you may want to further " "restrict the cipher choice. Be sure to read OpenSSL's documentation about " -"the `cipher list format `_. If you want to check which ciphers are enabled " -"by a given cipher list, use :meth:`SSLContext.get_ciphers` or the ``openssl " -"ciphers`` command on your system." +"the `cipher list format `_. If you want to check which ciphers are enabled by a given " +"cipher list, use :meth:`SSLContext.get_ciphers` or the ``openssl ciphers`` " +"command on your system." msgstr "" #: ../../library/ssl.rst:2768 diff --git a/library/stat.po b/library/stat.po index 4de6f0055..6cdad8d3d 100644 --- a/library/stat.po +++ b/library/stat.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Ana Carolina Gomes, 2024 -# Italo Penaforte , 2024 -# i17obot , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:13+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -149,6 +146,60 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" +#: ../../library/stat.rst:103 +msgid "" +"import os, sys\n" +"from stat import *\n" +"\n" +"def walktree(top, callback):\n" +" '''recursively descend the directory tree rooted at top,\n" +" calling the callback function for each regular file'''\n" +"\n" +" for f in os.listdir(top):\n" +" pathname = os.path.join(top, f)\n" +" mode = os.lstat(pathname).st_mode\n" +" if S_ISDIR(mode):\n" +" # It's a directory, recurse into it\n" +" walktree(pathname, callback)\n" +" elif S_ISREG(mode):\n" +" # It's a file, call the callback function\n" +" callback(pathname)\n" +" else:\n" +" # Unknown file type, print a message\n" +" print('Skipping %s' % pathname)\n" +"\n" +"def visitfile(file):\n" +" print('visiting', file)\n" +"\n" +"if __name__ == '__main__':\n" +" walktree(sys.argv[1], visitfile)" +msgstr "" +"import os, sys\n" +"from stat import *\n" +"\n" +"def walktree(top, callback):\n" +" '''desce recursivamente a árvore de diretórios com raiz no topo,\n" +" chamando a função de retorno de chamada para cada arquivo regular'''\n" +"\n" +" for f in os.listdir(top):\n" +" pathname = os.path.join(top, f)\n" +" mode = os.lstat(pathname).st_mode\n" +" if S_ISDIR(mode):\n" +" # É um diretório, percorre recursivamente nele\n" +" walktree(pathname, callback)\n" +" elif S_ISREG(mode):\n" +" # É um arquivo, chama a função de retorno\n" +" callback(pathname)\n" +" else:\n" +" # Tipo de arquivo desconhecido, imprime uma mensagem\n" +" print('Pulando %s' % pathname)\n" +"\n" +"def visitfile(file):\n" +" print('visitando, file)\n" +"\n" +"if __name__ == '__main__':\n" +" walktree(sys.argv[1], visitfile)" + #: ../../library/stat.rst:129 msgid "" "An additional utility function is provided to convert a file's mode in a " @@ -172,7 +223,7 @@ msgid "" "All the variables below are simply symbolic indexes into the 10-tuple " "returned by :func:`os.stat`, :func:`os.fstat` or :func:`os.lstat`." msgstr "" -"Todas as variáveis ​​abaixo são simplesmente índices simbólicos nas 10 tuplas " +"Todas as variáveis abaixo são simplesmente índices simbólicos nas 10 tuplas " "retornadas por :func:`os.stat`, :func:`os.fstat` ou :func:`os.lstat`." #: ../../library/stat.rst:149 @@ -249,7 +300,7 @@ msgstr "" #: ../../library/stat.rst:207 msgid "The variables below define the flags used in the :data:`ST_MODE` field." msgstr "" -"As variáveis ​​abaixo definem os sinalizadores utilizadas no campo :data:" +"As variáveis abaixo definem os sinalizadores utilizadas no campo :data:" "`ST_MODE`." #: ../../library/stat.rst:209 @@ -313,7 +364,7 @@ msgid "" "The following flags can also be used in the *mode* argument of :func:`os." "chmod`:" msgstr "" -"Os seguintes sinalizadores também podem ser usados ​​no argumento *mode* de :" +"Os seguintes sinalizadores também podem ser usados no argumento *mode* de :" "func:`os.chmod`:" #: ../../library/stat.rst:266 @@ -424,7 +475,7 @@ msgid "" "The following flags can be used in the *flags* argument of :func:`os." "chflags`:" msgstr "" -"Os seguintes sinalizadores podem ser usados ​​no argumento *flags* de :func:" +"Os seguintes sinalizadores podem ser usados no argumento *flags* de :func:" "`os.chflags`:" #: ../../library/stat.rst:355 @@ -469,19 +520,19 @@ msgstr "O arquivo não deve ser exibido em uma GUI (macOS 10.5+)." #: ../../library/stat.rst:401 msgid "All super-user changeable flags" -msgstr "Todos os sinalizadores mutáveis ​​de superusuário" +msgstr "Todos os sinalizadores mutáveis de superusuário" #: ../../library/stat.rst:407 msgid "All super-user supported flags" -msgstr "Todos os sinalizadores válidos ​de superusuário" +msgstr "Todos os sinalizadores válidos de superusuário" #: ../../library/stat.rst:409 ../../library/stat.rst:417 -msgid ":ref:`Availability `: macOS" -msgstr ":ref:`Disponibilidade `: macOS" +msgid "Availability" +msgstr "Disponibilidade" #: ../../library/stat.rst:415 msgid "All super-user read-only synthetic flags" -msgstr "Todos os sinalizadores sintéticos de somente leitura ​de superusuário" +msgstr "Todos os sinalizadores sintéticos de somente leitura de superusuário" #: ../../library/stat.rst:423 msgid "The file may be archived." diff --git a/library/statistics.po b/library/statistics.po index 2a8f397ef..75975157e 100644 --- a/library/statistics.po +++ b/library/statistics.po @@ -1,33 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Felipe Rodrigues , 2021 -# Leticia Portella , 2021 -# Adorilson Bezerra , 2021 -# Melissa Weber Mendonça , 2021 -# i17obot , 2021 -# Gabriel Aparecido Fonseca , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-26 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:13+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -97,6 +89,48 @@ msgstr "" "``median_grouped()``, ``mode()``, ``multimode()`` e ``quantiles()``. Os " "valores ``NaN`` devem ser removidos antes de chamar estas funções::" +#: ../../library/statistics.rst:47 +msgid "" +">>> from statistics import median\n" +">>> from math import isnan\n" +">>> from itertools import filterfalse\n" +"\n" +">>> data = [20.7, float('NaN'),19.2, 18.3, float('NaN'), 14.4]\n" +">>> sorted(data) # This has surprising behavior\n" +"[20.7, nan, 14.4, 18.3, 19.2, nan]\n" +">>> median(data) # This result is unexpected\n" +"16.35\n" +"\n" +">>> sum(map(isnan, data)) # Number of missing values\n" +"2\n" +">>> clean = list(filterfalse(isnan, data)) # Strip NaN values\n" +">>> clean\n" +"[20.7, 19.2, 18.3, 14.4]\n" +">>> sorted(clean) # Sorting now works as expected\n" +"[14.4, 18.3, 19.2, 20.7]\n" +">>> median(clean) # This result is now well defined\n" +"18.75" +msgstr "" +">>> from statistics import median\n" +">>> from math import isnan\n" +">>> from itertools import filterfalse\n" +"\n" +">>> data = [20.7, float('NaN'),19.2, 18.3, float('NaN'), 14.4]\n" +">>> sorted(data) # Isso tem um comportamento surpreendente\n" +"[20.7, nan, 14.4, 18.3, 19.2, nan]\n" +">>> median(data) # Este resultado é inesperado\n" +"16.35\n" +"\n" +">>> sum(map(isnan, data)) # Número de valores em falta\n" +"2\n" +">>> clean = list(filterfalse(isnan, data)) # Remove valores NaN\n" +">>> clean\n" +"[20.7, 19.2, 18.3, 14.4]\n" +">>> sorted(clean) # A classificação agora funciona como esperado\n" +"[14.4, 18.3, 19.2, 20.7]\n" +">>> median(clean) # Este resultado é agora bem definido\n" +"18.75" + #: ../../library/statistics.rst:69 msgid "Averages and measures of central location" msgstr "Médias e medidas de valor central" @@ -331,6 +365,34 @@ msgstr "" msgid "Some examples of use:" msgstr "Alguns exemplos de uso:" +#: ../../library/statistics.rst:134 +msgid "" +">>> mean([1, 2, 3, 4, 4])\n" +"2.8\n" +">>> mean([-1.0, 2.5, 3.25, 5.75])\n" +"2.625\n" +"\n" +">>> from fractions import Fraction as F\n" +">>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])\n" +"Fraction(13, 21)\n" +"\n" +">>> from decimal import Decimal as D\n" +">>> mean([D(\"0.5\"), D(\"0.75\"), D(\"0.625\"), D(\"0.375\")])\n" +"Decimal('0.5625')" +msgstr "" +">>> mean([1, 2, 3, 4, 4])\n" +"2.8\n" +">>> mean([-1.0, 2.5, 3.25, 5.75])\n" +"2.625\n" +"\n" +">>> from fractions import Fraction as F\n" +">>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])\n" +"Fraction(13, 21)\n" +"\n" +">>> from decimal import Decimal as D\n" +">>> mean([D(\"0.5\"), D(\"0.75\"), D(\"0.625\"), D(\"0.375\")])\n" +"Decimal('0.5625')" + #: ../../library/statistics.rst:151 msgid "" "The mean is strongly affected by `outliers >> fmean([3.5, 4.0, 5.25])\n" +"4.25" +msgstr "" +">>> fmean([3.5, 4.0, 5.25])\n" +"4.25" + #: ../../library/statistics.rst:177 msgid "" "Optional weighting is supported. For example, a professor assigns a grade " @@ -385,6 +455,18 @@ msgstr "" "nota para um curso ponderando questionários em 20%, trabalhos de casa em " "20%, um exame de meio de período em 30% e um exame final em 30%:" +#: ../../library/statistics.rst:181 +msgid "" +">>> grades = [85, 92, 83, 91]\n" +">>> weights = [0.20, 0.20, 0.30, 0.30]\n" +">>> fmean(grades, weights)\n" +"87.6" +msgstr "" +">>> grades = [85, 92, 83, 91]\n" +">>> weights = [0.20, 0.20, 0.30, 0.30]\n" +">>> fmean(grades, weights)\n" +"87.6" + #: ../../library/statistics.rst:188 msgid "" "If *weights* is supplied, it must be the same length as the *data* or a :exc:" @@ -430,6 +512,14 @@ msgstr "" "Nenhum esforço especial é feito para alcançar resultados exatos. (Mas, isso " "pode mudar no futuro)." +#: ../../library/statistics.rst:212 +msgid "" +">>> round(geometric_mean([54, 24, 36]), 1)\n" +"36.0" +msgstr "" +">>> round(geometric_mean([54, 24, 36]), 1)\n" +"36.0" + #: ../../library/statistics.rst:222 msgid "" "Return the harmonic mean of *data*, a sequence or iterable of real-valued " @@ -470,6 +560,14 @@ msgstr "" "Suponha que um carro viaje 10 km a 40 km/h, e em seguida viaje mais 10 km a " "60 km/h. Qual é a velocidade média?" +#: ../../library/statistics.rst:238 +msgid "" +">>> harmonic_mean([40, 60])\n" +"48.0" +msgstr "" +">>> harmonic_mean([40, 60])\n" +"48.0" + #: ../../library/statistics.rst:243 msgid "" "Suppose a car travels 40 km/hr for 5 km, and when traffic clears, speeds-up " @@ -480,6 +578,14 @@ msgstr "" "acelera para 60 km/h pelos 30 km restantes da viagem. Qual é a velocidade " "média?" +#: ../../library/statistics.rst:247 +msgid "" +">>> harmonic_mean([40, 60], weights=[5, 30])\n" +"56.0" +msgstr "" +">>> harmonic_mean([40, 60], weights=[5, 30])\n" +"56.0" + #: ../../library/statistics.rst:252 msgid "" ":exc:`StatisticsError` is raised if *data* is empty, any element is less " @@ -584,10 +690,22 @@ msgstr "" "gerar e plotar uma função de densidade de probabilidade estimada a partir de " "uma pequena amostra:" +#: ../../library/statistics.rst:300 +msgid "" +">>> sample = [-2.1, -1.3, -0.4, 1.9, 5.1, 6.2]\n" +">>> f_hat = kde(sample, h=1.5)\n" +">>> xarr = [i/100 for i in range(-750, 1100)]\n" +">>> yarr = [f_hat(x) for x in xarr]" +msgstr "" +">>> sample = [-2.1, -1.3, -0.4, 1.9, 5.1, 6.2]\n" +">>> f_hat = kde(sample, h=1.5)\n" +">>> xarr = [i/100 for i in range(-750, 1100)]\n" +">>> yarr = [f_hat(x) for x in xarr]" + #: ../../library/statistics.rst:307 msgid "The points in ``xarr`` and ``yarr`` can be used to make a PDF plot:" msgstr "" -"Os pontos em ``xarr`` e ``yarr`` podem ser usados ​​para fazer um gráfico PDF:" +"Os pontos em ``xarr`` e ``yarr`` podem ser usados para fazer um gráfico PDF:" #: ../../library/statistics.rst:309 msgid "Scatter plot of the estimated probability density function." @@ -643,6 +761,14 @@ msgstr "" "valores discrepantes. Quando a quantidade de pontos de dados for ímpar, o " "valor de meio é retornado:" +#: ../../library/statistics.rst:349 +msgid "" +">>> median([1, 3, 5])\n" +"3" +msgstr "" +">>> median([1, 3, 5])\n" +"3" + #: ../../library/statistics.rst:354 msgid "" "When the number of data points is even, the median is interpolated by taking " @@ -651,6 +777,14 @@ msgstr "" "Quando o número de elementos for par, a mediana é calculada tomando-se a " "média entre os dois valores no meio:" +#: ../../library/statistics.rst:357 +msgid "" +">>> median([1, 3, 5, 7])\n" +"4.0" +msgstr "" +">>> median([1, 3, 5, 7])\n" +"4.0" + #: ../../library/statistics.rst:362 msgid "" "This is suited for when your data is discrete, and you don't mind that the " @@ -688,6 +822,18 @@ msgstr "" "de elementos for ímpar, o valor intermediário é retornado. Se houver um " "número par de elementos, o menor entre os dois valores centrais é retornado." +#: ../../library/statistics.rst:378 +msgid "" +">>> median_low([1, 3, 5])\n" +"3\n" +">>> median_low([1, 3, 5, 7])\n" +"3" +msgstr "" +">>> median_low([1, 3, 5])\n" +"3\n" +">>> median_low([1, 3, 5, 7])\n" +"3" + #: ../../library/statistics.rst:385 msgid "" "Use the low median when your data are discrete and you prefer the median to " @@ -716,6 +862,18 @@ msgstr "" "de elementos for ímpar, o valor intermediário é retornado. Se houver um " "número par de elementos, o maior entre os dois valores centrais é retornado." +#: ../../library/statistics.rst:398 +msgid "" +">>> median_high([1, 3, 5])\n" +"3\n" +">>> median_high([1, 3, 5, 7])\n" +"5" +msgstr "" +">>> median_high([1, 3, 5])\n" +"3\n" +">>> median_high([1, 3, 5, 7])\n" +"5" + #: ../../library/statistics.rst:405 msgid "" "Use the high median when your data are discrete and you prefer the median to " @@ -740,10 +898,12 @@ msgid "" "The *data* can be any iterable of numeric data with each value being exactly " "the midpoint of a bin. At least one value must be present." msgstr "" +"*data* pode ser qualquer iterável de dados numéricos com cada valor sendo " +"exatamente o ponto médio de um bin. Pelo menos um valor deve estar presente." #: ../../library/statistics.rst:418 msgid "The *interval* is the width of each bin." -msgstr "" +msgstr "*interval* é a largura de cada compartimento." #: ../../library/statistics.rst:420 msgid "" @@ -755,6 +915,28 @@ msgstr "" "etários consecutivos de dez anos, com cada grupo sendo representado pelos " "pontos médios de cinco anos dos intervalos:" +#: ../../library/statistics.rst:424 +msgid "" +">>> from collections import Counter\n" +">>> demographics = Counter({\n" +"... 25: 172, # 20 to 30 years old\n" +"... 35: 484, # 30 to 40 years old\n" +"... 45: 387, # 40 to 50 years old\n" +"... 55: 22, # 50 to 60 years old\n" +"... 65: 6, # 60 to 70 years old\n" +"... })\n" +"..." +msgstr "" +">>> from collections import Counter\n" +">>> demographics = Counter({\n" +"... 25: 172, # 20 to 30 years old\n" +"... 35: 484, # 30 to 40 years old\n" +"... 45: 387, # 40 to 50 years old\n" +"... 55: 22, # 50 to 60 years old\n" +"... 65: 6, # 60 to 70 years old\n" +"... })\n" +"..." + #: ../../library/statistics.rst:436 msgid "" "The 50th percentile (median) is the 536th person out of the 1071 member " @@ -775,6 +957,20 @@ msgstr "" "os 484 membros dessa faixa etária estão distribuídos uniformemente entre 30 " "e 40. Para isso, usamos :func:`median_grouped`:" +#: ../../library/statistics.rst:445 +msgid "" +">>> data = list(demographics.elements())\n" +">>> median(data)\n" +"35\n" +">>> round(median_grouped(data, interval=10), 1)\n" +"37.5" +msgstr "" +">>> data = list(demographics.elements())\n" +">>> median(data)\n" +"35\n" +">>> round(median_grouped(data, interval=10), 1)\n" +"37.5" + #: ../../library/statistics.rst:453 msgid "" "The caller is responsible for making sure the data points are separated by " @@ -823,6 +1019,14 @@ msgstr "" "``mode`` presume que os dados são discretos e retorna um único valor. Esse é " "o tratamento padrão do conceito de moda normalmente ensinado nas escolas:" +#: ../../library/statistics.rst:475 +msgid "" +">>> mode([1, 1, 2, 3, 3, 3, 3, 4])\n" +"3" +msgstr "" +">>> mode([1, 1, 2, 3, 3, 3, 3, 4])\n" +"3" + #: ../../library/statistics.rst:480 msgid "" "The mode is unique in that it is the only statistic in this package that " @@ -831,6 +1035,16 @@ msgstr "" "A moda é única no sentido que é a única medida estatística nesse módulo que " "também se aplica a dados nominais (não-numéricos):" +#: ../../library/statistics.rst:483 +msgid "" +">>> mode([\"red\", \"blue\", \"blue\", \"red\", \"green\", \"red\", " +"\"red\"])\n" +"'red'" +msgstr "" +">>> mode([\"red\", \"blue\", \"blue\", \"red\", \"green\", \"red\", " +"\"red\"])\n" +"'red'" + #: ../../library/statistics.rst:488 msgid "" "Only hashable inputs are supported. To handle type :class:`set`, consider " @@ -839,7 +1053,7 @@ msgid "" "slower quadratic algorithm that only depends on equality tests: ``max(data, " "key=data.count)``." msgstr "" -"Somente entradas hasheáveis ​​são suportadas. Para manipular o tipo :class:" +"Somente entradas hasheáveis são suportadas. Para manipular o tipo :class:" "`set`, considere fazer a conversão para :class:`frozenset`. Para manipular o " "tipo :class:`list`, considere fazer a conversão para :class:`tuple`. Para " "entradas mistas ou aninhadas, considere usar este algoritmo quadrático mais " @@ -865,6 +1079,18 @@ msgstr "" "encontrados em *data*. Irá retornar mais do que um resultado se houver " "múltiplas modas ou uma lista vazia se *data* for vazio." +#: ../../library/statistics.rst:506 +msgid "" +">>> multimode('aabbbbccddddeeffffgg')\n" +"['b', 'd', 'f']\n" +">>> multimode('')\n" +"[]" +msgstr "" +">>> multimode('aabbbbccddddeeffffgg')\n" +"['b', 'd', 'f']\n" +">>> multimode('')\n" +"[]" + #: ../../library/statistics.rst:518 msgid "" "Return the population standard deviation (the square root of the population " @@ -873,6 +1099,14 @@ msgstr "" "Retorna o desvio padrão populacional (a raiz quadrada da variância " "populacional). Veja os argumentos e outros detalhes em :func:`pvariance`." +#: ../../library/statistics.rst:521 +msgid "" +">>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])\n" +"0.986893273527251" +msgstr "" +">>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])\n" +"0.986893273527251" + #: ../../library/statistics.rst:529 msgid "" "Return the population variance of *data*, a non-empty sequence or iterable " @@ -919,6 +1153,16 @@ msgstr "Levanta :exc:`StatisticsError` se *data* for vazio." msgid "Examples:" msgstr "Exemplos:" +#: ../../library/statistics.rst:548 +msgid "" +">>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]\n" +">>> pvariance(data)\n" +"1.25" +msgstr "" +">>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]\n" +">>> pvariance(data)\n" +"1.25" + #: ../../library/statistics.rst:554 msgid "" "If you have already calculated the mean of your data, you can pass it as the " @@ -927,10 +1171,40 @@ msgstr "" "Se você já calculou a média dos seus dados, você pode passar o valor no " "segundo argumento opcional *mu* para evitar recálculos:" +#: ../../library/statistics.rst:557 +msgid "" +">>> mu = mean(data)\n" +">>> pvariance(data, mu)\n" +"1.25" +msgstr "" +">>> mu = mean(data)\n" +">>> pvariance(data, mu)\n" +"1.25" + #: ../../library/statistics.rst:563 msgid "Decimals and Fractions are supported:" msgstr "Decimais e frações são suportadas:" +#: ../../library/statistics.rst:565 +msgid "" +">>> from decimal import Decimal as D\n" +">>> pvariance([D(\"27.5\"), D(\"30.25\"), D(\"30.25\"), D(\"34.5\"), " +"D(\"41.75\")])\n" +"Decimal('24.815')\n" +"\n" +">>> from fractions import Fraction as F\n" +">>> pvariance([F(1, 4), F(5, 4), F(1, 2)])\n" +"Fraction(13, 72)" +msgstr "" +">>> from decimal import Decimal as D\n" +">>> pvariance([D(\"27.5\"), D(\"30.25\"), D(\"30.25\"), D(\"34.5\"), " +"D(\"41.75\")])\n" +"Decimal('24.815')\n" +"\n" +">>> from fractions import Fraction as F\n" +">>> pvariance([F(1, 4), F(5, 4), F(1, 2)])\n" +"Fraction(13, 72)" + #: ../../library/statistics.rst:577 msgid "" "When called with the entire population, this gives the population variance " @@ -964,6 +1238,14 @@ msgstr "" "Retorna o desvio padrão amostral (a raiz quadrada da variância amostral). " "Veja :func:`variance` para argumentos e outros detalhes." +#: ../../library/statistics.rst:593 +msgid "" +">>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])\n" +"1.0810874155219827" +msgstr "" +">>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])\n" +"1.0810874155219827" + #: ../../library/statistics.rst:601 msgid "" "Return the sample variance of *data*, an iterable of at least two real-" @@ -984,6 +1266,9 @@ msgid "" "mean of *data*. If it is missing or ``None`` (the default), the mean is " "automatically calculated." msgstr "" +"Se o segundo argumento opcional *xbar* for dado, ele deve a média *sample* " +"de *data*. Se ele não estiver presente ou for ``None`` (valor padrão), a " +"média é automaticamente calculada." #: ../../library/statistics.rst:611 msgid "" @@ -999,11 +1284,33 @@ msgstr "" "Levanta a exceção :exc:`StatisticsError` se *data* tiver menos do que dois " "valores." +#: ../../library/statistics.rst:618 +msgid "" +">>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]\n" +">>> variance(data)\n" +"1.3720238095238095" +msgstr "" +">>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]\n" +">>> variance(data)\n" +"1.3720238095238095" + #: ../../library/statistics.rst:624 msgid "" "If you have already calculated the sample mean of your data, you can pass it " "as the optional second argument *xbar* to avoid recalculation:" msgstr "" +"Se você já calculou a média amostral dos seus dados, você pode passar o " +"valor no segundo argumento opcional *xbar* para evitar recálculos:" + +#: ../../library/statistics.rst:627 +msgid "" +">>> m = mean(data)\n" +">>> variance(data, m)\n" +"1.3720238095238095" +msgstr "" +">>> m = mean(data)\n" +">>> variance(data, m)\n" +"1.3720238095238095" #: ../../library/statistics.rst:633 msgid "" @@ -1019,6 +1326,26 @@ msgstr "" msgid "Decimal and Fraction values are supported:" msgstr "Decimais e frações são suportados." +#: ../../library/statistics.rst:639 +msgid "" +">>> from decimal import Decimal as D\n" +">>> variance([D(\"27.5\"), D(\"30.25\"), D(\"30.25\"), D(\"34.5\"), " +"D(\"41.75\")])\n" +"Decimal('31.01875')\n" +"\n" +">>> from fractions import Fraction as F\n" +">>> variance([F(1, 6), F(1, 2), F(5, 3)])\n" +"Fraction(67, 108)" +msgstr "" +">>> from decimal import Decimal as D\n" +">>> variance([D(\"27.5\"), D(\"30.25\"), D(\"30.25\"), D(\"34.5\"), " +"D(\"41.75\")])\n" +"Decimal('31.01875')\n" +"\n" +">>> from fractions import Fraction as F\n" +">>> variance([F(1, 6), F(1, 2), F(5, 3)])\n" +"Fraction(67, 108)" + #: ../../library/statistics.rst:651 msgid "" "This is the sample variance s² with Bessel's correction, also known as " @@ -1068,6 +1395,10 @@ msgid "" "results, the number of data points in *data* should be larger than *n*. " "Raises :exc:`StatisticsError` if there is not at least one data point." msgstr "" +"*data* pode ser qualquer iterável contendo dados amostrais. Para resultados " +"significativos, a quantidade de dados em *data* deve ser maior do que *n*. " +"Levanta a exceção :exc:`StatisticsError` se não houver pelo menos um ponto " +"de dados." #: ../../library/statistics.rst:674 msgid "" @@ -1124,24 +1455,74 @@ msgstr "" "- 1) / (m - 1)``. Dados 11 valores, o método os ordena e atribui a eles os " "seguintes percentis: 0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%, 100%." +#: ../../library/statistics.rst:699 +msgid "" +"# Decile cut points for empirically sampled data\n" +">>> data = [105, 129, 87, 86, 111, 111, 89, 81, 108, 92, 110,\n" +"... 100, 75, 105, 103, 109, 76, 119, 99, 91, 103, 129,\n" +"... 106, 101, 84, 111, 74, 87, 86, 103, 103, 106, 86,\n" +"... 111, 75, 87, 102, 121, 111, 88, 89, 101, 106, 95,\n" +"... 103, 107, 101, 81, 109, 104]\n" +">>> [round(q, 1) for q in quantiles(data, n=10)]\n" +"[81.0, 86.2, 89.0, 99.4, 102.5, 103.6, 106.0, 109.8, 111.0]" +msgstr "" +"# Pontos de corte de decil para dados amostrados empiricamente\n" +">>> data = [105, 129, 87, 86, 111, 111, 89, 81, 108, 92, 110,\n" +"... 100, 75, 105, 103, 109, 76, 119, 99, 91, 103, 129,\n" +"... 106, 101, 84, 111, 74, 87, 86, 103, 103, 106, 86,\n" +"... 111, 75, 87, 102, 121, 111, 88, 89, 101, 106, 95,\n" +"... 103, 107, 101, 81, 109, 104]\n" +">>> [round(q, 1) for q in quantiles(data, n=10)]\n" +"[81.0, 86.2, 89.0, 99.4, 102.5, 103.6, 106.0, 109.8, 111.0]" + #: ../../library/statistics.rst:712 msgid "" "No longer raises an exception for an input with only a single data point. " "This allows quantile estimates to be built up one sample point at a time " "becoming gradually more refined with each new data point." msgstr "" +"Não levanta mais uma exceção para uma entrada com apenas um único ponto de " +"dados. Isso permite que estimativas de quantil sejam construídas um ponto de " +"amostra por vez, tornando-se gradualmente mais refinadas com cada novo ponto " +"de dados." #: ../../library/statistics.rst:719 msgid "" "Return the sample covariance of two inputs *x* and *y*. Covariance is a " "measure of the joint variability of two inputs." msgstr "" +"Retorna a covariância da amostra de duas entradas *x* e *y*. Covariância é " +"uma medida da variabilidade conjunta de duas entradas." #: ../../library/statistics.rst:722 msgid "" "Both inputs must be of the same length (no less than two), otherwise :exc:" "`StatisticsError` is raised." msgstr "" +"Ambas as entradas devem ter o mesmo comprimento (não menos que dois), caso " +"contrário, :exc:`StatisticsError` será levantada." + +#: ../../library/statistics.rst:727 +msgid "" +">>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n" +">>> y = [1, 2, 3, 1, 2, 3, 1, 2, 3]\n" +">>> covariance(x, y)\n" +"0.75\n" +">>> z = [9, 8, 7, 6, 5, 4, 3, 2, 1]\n" +">>> covariance(x, z)\n" +"-7.5\n" +">>> covariance(z, x)\n" +"-7.5" +msgstr "" +">>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n" +">>> y = [1, 2, 3, 1, 2, 3, 1, 2, 3]\n" +">>> covariance(x, y)\n" +"0.75\n" +">>> z = [9, 8, 7, 6, 5, 4, 3, 2, 1]\n" +">>> covariance(x, z)\n" +"-7.5\n" +">>> covariance(z, x)\n" +"-7.5" #: ../../library/statistics.rst:743 msgid "" @@ -1150,6 +1531,10 @@ msgid "" "coefficient *r* takes values between -1 and +1. It measures the strength and " "direction of a linear relationship." msgstr "" +"Retorna o `coeficiente de correlação de Pearson `_ para duas entradas. O coeficiente de " +"correlação de Pearson *r* assume valores entre -1 e +1. Ele mede a força e a " +"direção de uma relação linear." #: ../../library/statistics.rst:749 msgid "" @@ -1159,6 +1544,12 @@ msgid "" "equal values receive the same rank. The resulting coefficient measures the " "strength of a monotonic relationship." msgstr "" +"Se *method* for \"ranked\", calcula `coeficiente de correlação de " +"classificação de Spearman `_ para duas entradas. Os dados " +"são substituídos por classificações. Os empates são calculados em média para " +"que valores iguais recebam a mesma classificação. O coeficiente resultante " +"mede a força de um relacionamento monotônico." #: ../../library/statistics.rst:755 msgid "" @@ -1166,22 +1557,78 @@ msgid "" "continuous data that doesn't meet the linear proportion requirement for " "Pearson's correlation coefficient." msgstr "" +"O coeficiente de correlação de Spearman é apropriado para dados ordinais ou " +"para dados contínuos que não atendem ao requisito de proporção linear para o " +"coeficiente de correlação de Pearson." #: ../../library/statistics.rst:759 msgid "" "Both inputs must be of the same length (no less than two), and need not to " "be constant, otherwise :exc:`StatisticsError` is raised." msgstr "" +"Ambas as entradas devem ter o mesmo comprimento (não menos que dois) e não " +"precisam ser constantes, caso contrário, :exc:`StatisticsError` será " +"levantada." #: ../../library/statistics.rst:762 msgid "" "Example with `Kepler's laws of planetary motion `_:" msgstr "" +"Exemplo com `leis de Kepler do movimento planetário `_:" + +#: ../../library/statistics.rst:765 +msgid "" +">>> # Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune\n" +">>> orbital_period = [88, 225, 365, 687, 4331, 10_756, 30_687, 60_190] # " +"days\n" +">>> dist_from_sun = [58, 108, 150, 228, 778, 1_400, 2_900, 4_500] # million " +"km\n" +"\n" +">>> # Show that a perfect monotonic relationship exists\n" +">>> correlation(orbital_period, dist_from_sun, method='ranked')\n" +"1.0\n" +"\n" +">>> # Observe that a linear relationship is imperfect\n" +">>> round(correlation(orbital_period, dist_from_sun), 4)\n" +"0.9882\n" +"\n" +">>> # Demonstrate Kepler's third law: There is a linear correlation\n" +">>> # between the square of the orbital period and the cube of the\n" +">>> # distance from the sun.\n" +">>> period_squared = [p * p for p in orbital_period]\n" +">>> dist_cubed = [d * d * d for d in dist_from_sun]\n" +">>> round(correlation(period_squared, dist_cubed), 4)\n" +"1.0" +msgstr "" +">>> # Mercúrio, Venus, Terra, Marte, Jupiter, Saturno, Urano e Netuno\n" +">>> orbital_period = [88, 225, 365, 687, 4331, 10_756, 30_687, 60_190] # " +"dias\n" +">>> dist_from_sun = [58, 108, 150, 228, 778, 1_400, 2_900, 4_500] # milhões " +"de km\n" +"\n" +">>> # Mostra que existe uma perfeita relação monótona\n" +">>> correlation(orbital_period, dist_from_sun, method='ranked')\n" +"1.0\n" +"\n" +">>> # Observe que uma relação linear é imperfeita\n" +">>> round(correlation(orbital_period, dist_from_sun), 4)\n" +"0.9882\n" +"\n" +">>> # Demonstra a terceira lei de Kepler: Há uma correlação linear\n" +">>> # entre o quadrado do período orbital e o cubo da\n" +">>> # distância a partir do sol.\n" +">>> period_squared = [p * p for p in orbital_period]\n" +">>> dist_cubed = [d * d * d for d in dist_from_sun]\n" +">>> round(correlation(period_squared, dist_cubed), 4)\n" +"1.0" #: ../../library/statistics.rst:789 msgid "Added support for Spearman's rank correlation coefficient." msgstr "" +"Adicionado suporte para o coeficiente de correlação de classificação de " +"Spearman." #: ../../library/statistics.rst:794 msgid "" @@ -1191,10 +1638,15 @@ msgid "" "between an independent variable *x* and a dependent variable *y* in terms of " "this linear function:" msgstr "" +"Retorna a inclinação e a interceptação dos parâmetros de `regressão linear " +"simples `_ estimados " +"usando mínimos quadrados ordinários. A regressão linear simples descreve a " +"relação entre uma variável independente *x* e uma variável dependente *y* em " +"termos desta função linear:" #: ../../library/statistics.rst:800 msgid "*y = slope \\* x + intercept + noise*" -msgstr "" +msgstr "*y = slope \\* x + intercept + noise*" #: ../../library/statistics.rst:802 msgid "" @@ -1203,6 +1655,10 @@ msgid "" "explained by the linear regression (it is equal to the difference between " "predicted and actual values of the dependent variable)." msgstr "" +"onde ``slope`` e ``intercept`` são os parâmetros de regressão que são " +"estimados, e ``noise`` representa a variabilidade dos dados que não foi " +"explicada pela regressão linear (é igual à diferença entre os valores " +"previstos e reais da variável dependente)." #: ../../library/statistics.rst:808 msgid "" @@ -1210,6 +1666,9 @@ msgid "" "independent variable *x* cannot be constant; otherwise a :exc:" "`StatisticsError` is raised." msgstr "" +"Ambas as entradas devem ter o mesmo comprimento (não menos que dois) e a " +"variável independente *x* não pode ser constante; caso contrário, um :exc:" +"`StatisticsError` será levantada." #: ../../library/statistics.rst:812 msgid "" @@ -1218,6 +1677,24 @@ msgid "" "cumulative number of Monty Python films that would have been produced by " "2019 assuming that they had kept the pace." msgstr "" +"Por exemplo, podemos usar as `datas de lançamento dos filmes do Monty Python " +"`_ para prever o número " +"cumulativo de filmes do Monty Python que teriam sido produzidos até 2019, " +"supondo que eles tivessem mantido o ritmo." + +#: ../../library/statistics.rst:818 +msgid "" +">>> year = [1971, 1975, 1979, 1982, 1983]\n" +">>> films_total = [1, 2, 3, 4, 5]\n" +">>> slope, intercept = linear_regression(year, films_total)\n" +">>> round(slope * 2019 + intercept)\n" +"16" +msgstr "" +">>> year = [1971, 1975, 1979, 1982, 1983]\n" +">>> films_total = [1, 2, 3, 4, 5]\n" +">>> slope, intercept = linear_regression(year, films_total)\n" +">>> round(slope * 2019 + intercept)\n" +"16" #: ../../library/statistics.rst:826 msgid "" @@ -1226,10 +1703,14 @@ msgid "" "line passing through the origin. Since the *intercept* will always be 0.0, " "the underlying linear function simplifies to:" msgstr "" +"Se *proportional* for verdadeiro, a variável independente *x* e a variável " +"dependente *y* são assumidas como diretamente proporcionais. Os dados são " +"ajustados a uma linha que passa pela origem. Como o *intercept* sempre será " +"0,0, a função linear subjacente simplifica para:" #: ../../library/statistics.rst:832 msgid "*y = slope \\* x + noise*" -msgstr "" +msgstr "*y = slope \\* x + noise*" #: ../../library/statistics.rst:834 msgid "" @@ -1237,10 +1718,41 @@ msgid "" "model based on major planets can predict the orbital distances for dwarf " "planets:" msgstr "" +"Continuando o exemplo de :func:`correlation`, vamos ver o quão bem um modelo " +"baseado em planetas principais pode prever as distâncias orbitais de " +"planetas anões:" + +#: ../../library/statistics.rst:838 +msgid "" +">>> model = linear_regression(period_squared, dist_cubed, " +"proportional=True)\n" +">>> slope = model.slope\n" +"\n" +">>> # Dwarf planets: Pluto, Eris, Makemake, Haumea, Ceres\n" +">>> orbital_periods = [90_560, 204_199, 111_845, 103_410, 1_680] # days\n" +">>> predicted_dist = [math.cbrt(slope * (p * p)) for p in orbital_periods]\n" +">>> list(map(round, predicted_dist))\n" +"[5912, 10166, 6806, 6459, 414]\n" +"\n" +">>> [5_906, 10_152, 6_796, 6_450, 414] # actual distance in million km\n" +"[5906, 10152, 6796, 6450, 414]" +msgstr "" +">>> model = linear_regression(period_squared, dist_cubed, " +"proportional=True)\n" +">>> slope = model.slope\n" +"\n" +">>> # Planetas anões: Pluto, Eris, Makemake, Haumea, Ceres\n" +">>> orbital_periods = [90_560, 204_199, 111_845, 103_410, 1_680] # dias\n" +">>> predicted_dist = [math.cbrt(slope * (p * p)) for p in orbital_periods]\n" +">>> list(map(round, predicted_dist))\n" +"[5912, 10166, 6806, 6459, 414]\n" +"\n" +">>> [5_906, 10_152, 6_796, 6_450, 414] # distância real em milhões de km\n" +"[5906, 10152, 6796, 6450, 414]" #: ../../library/statistics.rst:854 msgid "Added support for *proportional*." -msgstr "" +msgstr "Adicionado suporte a *proportional*." #: ../../library/statistics.rst:858 msgid "Exceptions" @@ -1268,8 +1780,8 @@ msgid "" msgstr "" ":class:`NormalDist` é uma ferramenta para criar e manipular distribuições " "normais de uma `variável aleatória `_. É uma classe que trata a média e o desvio " -"padrão das medições de dados como uma entidade única." +"Variável_aleatória>`_. É uma classe que trata a média e o desvio padrão das " +"medições de dados como uma entidade única." #: ../../library/statistics.rst:876 msgid "" @@ -1288,9 +1800,8 @@ msgid "" "`standard deviation `_." msgstr "" "Retorna um novo objeto *NormalDist* onde *mu* representa a `média aritmética " -"`_ e *sigma* " -"representa o `desvio padrão `_." +"`_ e *sigma* representa o " +"`desvio padrão `_." #: ../../library/statistics.rst:887 msgid "If *sigma* is negative, raises :exc:`StatisticsError`." @@ -1302,7 +1813,7 @@ msgid "" "Arithmetic_mean>`_ of a normal distribution." msgstr "" "Uma propriedade somente leitura para a `média aritmética `_ de uma distribuição normal." +"wikipedia.org/wiki/Média_aritmética>`_ de uma distribuição normal." #: ../../library/statistics.rst:897 msgid "" @@ -1310,7 +1821,7 @@ msgid "" "Median>`_ of a normal distribution." msgstr "" "Uma propriedade somente leitura para a `mediana `_ de uma distribuição normal." +"wiki/Mediana_(estatística)>`_ de uma distribuição normal." #: ../../library/statistics.rst:903 msgid "" @@ -1318,7 +1829,7 @@ msgid "" "Mode_(statistics)>`_ of a normal distribution." msgstr "" "Uma propriedade somente leitura para a `moda `_ de uma distribuição normal." +"Moda_(estatística)>`_ de uma distribuição normal." #: ../../library/statistics.rst:909 msgid "" @@ -1326,7 +1837,7 @@ msgid "" "wiki/Standard_deviation>`_ of a normal distribution." msgstr "" "Uma propriedade somente leitura para o `desvio padrão `_ de uma distribuição normal." +"org/wiki/Desvio_padrão>`_ de uma distribuição normal." #: ../../library/statistics.rst:915 msgid "" @@ -1335,8 +1846,8 @@ msgid "" "deviation." msgstr "" "Uma propriedade somente leitura para a `variância `_ de uma distribuição normal. Igual ao quadrado do " -"desvio padrão." +"wiki/Variáncia>`_ de uma distribuição normal. Igual ao quadrado do desvio " +"padrão." #: ../../library/statistics.rst:921 msgid "" @@ -1383,6 +1894,8 @@ msgid "" "Switched to a faster algorithm. To reproduce samples from previous " "versions, use :func:`random.seed` and :func:`random.gauss`." msgstr "" +"Alterado para um algoritmo mais rápido. Para reproduzir amostras de versões " +"anteriores, use :func:`random.seed` e :func:`random.gauss`." #: ../../library/statistics.rst:946 msgid "" @@ -1392,10 +1905,9 @@ msgid "" "the limit of the ratio ``P(x <= X < x+dx) / dx`` as *dx* approaches zero." msgstr "" "Usando uma `função densidade de probabilidade (fdp) `_, calcula a probabilidade relativa que " -"uma variável aleatória *X* estará perto do valor dado *x*. Matematicamente, " -"é o limite da razão ``P(x <= X < x+dx) / dx`` quando *dx* se aproxima de " -"zero." +"org/wiki/Função_densidade>`_, calcula a probabilidade relativa que uma " +"variável aleatória *X* estará perto do valor dado *x*. Matematicamente, é o " +"limite da razão ``P(x <= X < x+dx) / dx`` quando *dx* se aproxima de zero." #: ../../library/statistics.rst:952 msgid "" @@ -1404,6 +1916,10 @@ msgid "" "\"density\"). Since the likelihood is relative to other points, its value " "can be greater than ``1.0``." msgstr "" +"A probabilidade relativa é calculada como a probabilidade de uma amostra " +"ocorrer em um intervalo estreito dividida pela largura do intervalo (daí a " +"palavra \"densidade\"). Como a probabilidade é relativa a outros pontos, seu " +"valor pode ser maior que ``1.0``." #: ../../library/statistics.rst:959 msgid "" @@ -1413,9 +1929,9 @@ msgid "" "is written ``P(X <= x)``." msgstr "" "Usando uma `função distribuição acumulada (fda) `_, calcula a " -"probabilidade de que uma variável aleatória *X* seja menor ou igual a *x*. " -"Matematicamente, é representada da seguinte maneira: ``P(X <= x)``." +"wiki/Função_distribuição_acumulada>`_, calcula a probabilidade de que uma " +"variável aleatória *X* seja menor ou igual a *x*. Matematicamente, é " +"representada da seguinte maneira: ``P(X <= x)``." #: ../../library/statistics.rst:966 msgid "" @@ -1425,6 +1941,11 @@ msgid "" "statisticshowto.datasciencecentral.com/inverse-distribution-function/>`_ " "function. Mathematically, it is written ``x : P(X <= x) = p``." msgstr "" +"Calcula a função distribuição acumulada inversa, também conhecida como " +"`função quantil `_ ou o `função ponto " +"percentual `_. " +"Matematicamente, é representada como ``x : P(X <= x) = p``." #: ../../library/statistics.rst:972 msgid "" @@ -1487,6 +2008,16 @@ msgstr "" "e divisão por uma constante. Essas operações são usadas para translação e " "dimensionamento. Por exemplo:" +#: ../../library/statistics.rst:1007 +msgid "" +">>> temperature_february = NormalDist(5, 2.5) # Celsius\n" +">>> temperature_february * (9/5) + 32 # Fahrenheit\n" +"NormalDist(mu=41.0, sigma=4.5)" +msgstr "" +">>> temperature_february = NormalDist(5, 2.5) # Celsius\n" +">>> temperature_february * (9/5) + 32 # Fahrenheit\n" +"NormalDist(mu=41.0, sigma=4.5)" + #: ../../library/statistics.rst:1013 msgid "" "Dividing a constant by an instance of :class:`NormalDist` is not supported " @@ -1509,13 +2040,31 @@ msgstr "" "Sum_of_normally_distributed_random_variables>`_ representadas como " "instâncias de :class:`NormalDist`. Por exemplo:" +#: ../../library/statistics.rst:1022 +msgid "" +">>> birth_weights = NormalDist.from_samples([2.5, 3.1, 2.1, 2.4, 2.7, 3.5])\n" +">>> drug_effects = NormalDist(0.4, 0.15)\n" +">>> combined = birth_weights + drug_effects\n" +">>> round(combined.mean, 1)\n" +"3.1\n" +">>> round(combined.stdev, 1)\n" +"0.5" +msgstr "" +">>> birth_weights = NormalDist.from_samples([2.5, 3.1, 2.1, 2.4, 2.7, 3.5])\n" +">>> drug_effects = NormalDist(0.4, 0.15)\n" +">>> combined = birth_weights + drug_effects\n" +">>> round(combined.mean, 1)\n" +"3.1\n" +">>> round(combined.stdev, 1)\n" +"0.5" + #: ../../library/statistics.rst:1036 msgid "Examples and Recipes" msgstr "Exemplos e receitas" #: ../../library/statistics.rst:1040 msgid "Classic probability problems" -msgstr "" +msgstr "Problemas clássicos de probabilidade" #: ../../library/statistics.rst:1042 msgid ":class:`NormalDist` readily solves classic probability problems." @@ -1536,6 +2085,18 @@ msgstr "" "195, determine o percentual de alunos com pontuações de teste entre 1100 e " "1200, após arredondar para o número inteiro mais próximo:" +#: ../../library/statistics.rst:1050 +msgid "" +">>> sat = NormalDist(1060, 195)\n" +">>> fraction = sat.cdf(1200 + 0.5) - sat.cdf(1100 - 0.5)\n" +">>> round(fraction * 100.0, 1)\n" +"18.4" +msgstr "" +">>> sat = NormalDist(1060, 195)\n" +">>> fraction = sat.cdf(1200 + 0.5) - sat.cdf(1100 - 0.5)\n" +">>> round(fraction * 100.0, 1)\n" +"18.4" + #: ../../library/statistics.rst:1057 msgid "" "Find the `quartiles `_ and `deciles " @@ -1544,9 +2105,21 @@ msgstr "" "Encontrar os `quartis `_ e `decis " "`_ para as pontuações SAT:" +#: ../../library/statistics.rst:1060 +msgid "" +">>> list(map(round, sat.quantiles()))\n" +"[928, 1060, 1192]\n" +">>> list(map(round, sat.quantiles(n=10)))\n" +"[810, 896, 958, 1011, 1060, 1109, 1162, 1224, 1310]" +msgstr "" +">>> list(map(round, sat.quantiles()))\n" +"[928, 1060, 1192]\n" +">>> list(map(round, sat.quantiles(n=10)))\n" +"[810, 896, 958, 1011, 1060, 1109, 1162, 1224, 1310]" + #: ../../library/statistics.rst:1069 msgid "Monte Carlo inputs for simulations" -msgstr "" +msgstr "Entradas de Monte Carlo para simulações" #: ../../library/statistics.rst:1071 msgid "" @@ -1554,10 +2127,36 @@ msgid "" "analytically, :class:`NormalDist` can generate input samples for a `Monte " "Carlo simulation `_:" msgstr "" +"Para estimar a distribuição de um modelo que não seja fácil de resolver " +"analiticamente, :class:`NormalDist` pode gerar amostras de entrada para uma " +"`simulação Monte Carlo `_:" + +#: ../../library/statistics.rst:1075 +msgid "" +">>> def model(x, y, z):\n" +"... return (3*x + 7*x*y - 5*y) / (11 * z)\n" +"...\n" +">>> n = 100_000\n" +">>> X = NormalDist(10, 2.5).samples(n, seed=3652260728)\n" +">>> Y = NormalDist(15, 1.75).samples(n, seed=4582495471)\n" +">>> Z = NormalDist(50, 1.25).samples(n, seed=6582483453)\n" +">>> quantiles(map(model, X, Y, Z))\n" +"[1.4591308524824727, 1.8035946855390597, 2.175091447274739]" +msgstr "" +">>> def model(x, y, z):\n" +"... return (3*x + 7*x*y - 5*y) / (11 * z)\n" +"...\n" +">>> n = 100_000\n" +">>> X = NormalDist(10, 2.5).samples(n, seed=3652260728)\n" +">>> Y = NormalDist(15, 1.75).samples(n, seed=4582495471)\n" +">>> Z = NormalDist(50, 1.25).samples(n, seed=6582483453)\n" +">>> quantiles(map(model, X, Y, Z))\n" +"[1.4591308524824727, 1.8035946855390597, 2.175091447274739]" #: ../../library/statistics.rst:1088 msgid "Approximating binomial distributions" -msgstr "" +msgstr "Aproximação de distribuições binomiais" #: ../../library/statistics.rst:1090 msgid "" @@ -1565,6 +2164,10 @@ msgid "" "`_ when the sample " "size is large and when the probability of a successful trial is near 50%." msgstr "" +"As distribuições normais podem ser usadas para aproximar `distribuições " +"binomiais `_ quando " +"o tamanho da amostra é grande e quando a probabilidade de um teste bem-" +"sucedido é próximo a 50%." #: ../../library/statistics.rst:1095 msgid "" @@ -1581,9 +2184,53 @@ msgstr "" "tenham mudado, qual é a probabilidade da sala de Python permanecer dentro de " "seus limites de capacidade?" +#: ../../library/statistics.rst:1101 +msgid "" +">>> n = 750 # Sample size\n" +">>> p = 0.65 # Preference for Python\n" +">>> q = 1.0 - p # Preference for Ruby\n" +">>> k = 500 # Room capacity\n" +"\n" +">>> # Approximation using the cumulative normal distribution\n" +">>> from math import sqrt\n" +">>> round(NormalDist(mu=n*p, sigma=sqrt(n*p*q)).cdf(k + 0.5), 4)\n" +"0.8402\n" +"\n" +">>> # Exact solution using the cumulative binomial distribution\n" +">>> from math import comb, fsum\n" +">>> round(fsum(comb(n, r) * p**r * q**(n-r) for r in range(k+1)), 4)\n" +"0.8402\n" +"\n" +">>> # Approximation using a simulation\n" +">>> from random import seed, binomialvariate\n" +">>> seed(8675309)\n" +">>> mean(binomialvariate(n, p) <= k for i in range(10_000))\n" +"0.8406" +msgstr "" +">>> n = 750 # Tamanho da amostra\n" +">>> p = 0.65 # Preferência para Python\n" +">>> q = 1.0 - p # Preferência para Ruby\n" +">>> k = 500 # Capacidade\n" +"\n" +">>> # Aproximação usando a distribuição normal cumulativa\n" +">>> from math import sqrt\n" +">>> round(NormalDist(mu=n*p, sigma=sqrt(n*p*q)).cdf(k + 0.5), 4)\n" +"0.8402\n" +"\n" +">>> # Solução exata usando a distribuição binomial cumulativa\n" +">>> from math import comb, fsum\n" +">>> round(fsum(comb(n, r) * p**r * q**(n-r) for r in range(k+1)), 4)\n" +"0.8402\n" +"\n" +">>> # Aproximação usando uma simulação\n" +">>> from random import seed, binomialvariate\n" +">>> seed(8675309)\n" +">>> mean(binomialvariate(n, p) <= k for i in range(10_000))\n" +"0.8406" + #: ../../library/statistics.rst:1126 msgid "Naive bayesian classifier" -msgstr "" +msgstr "Classificador bayesiano ingênuo" #: ../../library/statistics.rst:1128 msgid "Normal distributions commonly arise in machine learning problems." @@ -1598,6 +2245,11 @@ msgid "" "challenge is to predict a person's gender from measurements of normally " "distributed features including height, weight, and foot size." msgstr "" +"A Wikipedia tem um `bom exemplo de um Classificador Bayesiano Ingênuo " +"`_. O desafio é prever o sexo " +"de uma pessoa a partir de medidas de características normalmente " +"distribuídas, incluindo altura, peso e tamanho do pé." #: ../../library/statistics.rst:1135 msgid "" @@ -1609,6 +2261,22 @@ msgstr "" "pessoas. As medidas são consideradas normalmente distribuídas, então " "resumimos os dados com :class:`NormalDist`:" +#: ../../library/statistics.rst:1139 +msgid "" +">>> height_male = NormalDist.from_samples([6, 5.92, 5.58, 5.92])\n" +">>> height_female = NormalDist.from_samples([5, 5.5, 5.42, 5.75])\n" +">>> weight_male = NormalDist.from_samples([180, 190, 170, 165])\n" +">>> weight_female = NormalDist.from_samples([100, 150, 130, 150])\n" +">>> foot_size_male = NormalDist.from_samples([12, 11, 12, 10])\n" +">>> foot_size_female = NormalDist.from_samples([6, 8, 7, 9])" +msgstr "" +">>> height_male = NormalDist.from_samples([6, 5.92, 5.58, 5.92])\n" +">>> height_female = NormalDist.from_samples([5, 5.5, 5.42, 5.75])\n" +">>> weight_male = NormalDist.from_samples([180, 190, 170, 165])\n" +">>> weight_female = NormalDist.from_samples([100, 150, 130, 150])\n" +">>> foot_size_male = NormalDist.from_samples([12, 11, 12, 10])\n" +">>> foot_size_female = NormalDist.from_samples([6, 8, 7, 9])" + #: ../../library/statistics.rst:1148 msgid "" "Next, we encounter a new person whose feature measurements are known but " @@ -1617,6 +2285,16 @@ msgstr "" "Em seguida, encontramos uma nova pessoa cujas características de medidas são " "conhecidas, mas cujo gênero é desconhecido:" +#: ../../library/statistics.rst:1151 +msgid "" +">>> ht = 6.0 # height\n" +">>> wt = 130 # weight\n" +">>> fs = 8 # foot size" +msgstr "" +">>> ht = 6.0 # altura\n" +">>> wt = 130 # peso\n" +">>> fs = 8 # tamanho do pé" + #: ../../library/statistics.rst:1157 msgid "" "Starting with a 50% `prior probability `_ de ser homem ou mulher, calculamos a " +"Começando com uma `probabilidade a priori `_ de 50% de ser homem ou mulher, calculamos a " "posteriori como a priori vezes o produto das probabilidade para as " "características de medidas dado o gênero:" +#: ../../library/statistics.rst:1162 +msgid "" +">>> prior_male = 0.5\n" +">>> prior_female = 0.5\n" +">>> posterior_male = (prior_male * height_male.pdf(ht) *\n" +"... weight_male.pdf(wt) * foot_size_male.pdf(fs))\n" +"\n" +">>> posterior_female = (prior_female * height_female.pdf(ht) *\n" +"... weight_female.pdf(wt) * foot_size_female.pdf(fs))" +msgstr "" +">>> prior_male = 0.5\n" +">>> prior_female = 0.5\n" +">>> posterior_male = (prior_male * height_male.pdf(ht) *\n" +"... weight_male.pdf(wt) * foot_size_male.pdf(fs))\n" +"\n" +">>> posterior_female = (prior_female * height_female.pdf(ht) *\n" +"... weight_female.pdf(wt) * foot_size_female.pdf(fs))" + #: ../../library/statistics.rst:1172 msgid "" "The final prediction goes to the largest posterior. This is known as the " @@ -1638,3 +2334,11 @@ msgstr "" "A previsão final vai para a probabilidade posterior maior. Isso é conhecido " "como `máximo a posteriori `_ ou MAP:" + +#: ../../library/statistics.rst:1176 +msgid "" +">>> 'male' if posterior_male > posterior_female else 'female'\n" +"'female'" +msgstr "" +">>> 'male' if posterior_male > posterior_female else 'female'\n" +"'female'" diff --git a/library/stdtypes.po b/library/stdtypes.po index 0edfe37cb..b3fa348b3 100644 --- a/library/stdtypes.po +++ b/library/stdtypes.po @@ -1,43 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# i17obot , 2021 -# Welington Carlos , 2021 -# Tiago Henrique , 2021 -# (Douglas da Silva) , 2021 -# Misael borges , 2021 -# Danilo Lima , 2021 -# Italo Penaforte , 2022 -# Julia Rizza , 2023 -# Vinicius Gubiani Ferreira , 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# Marco Rougeth , 2023 -# felipe caridade fernandes , 2023 -# Ricardo Cappellano , 2023 -# Patricia Mortada, 2023 -# Lucas Gonçalves Cordeiro , 2023 -# Leandro Cavalcante Damascena , 2024 -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:13+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -166,8 +148,8 @@ msgstr "Resultado" #: ../../library/stdtypes.rst:86 ../../library/stdtypes.rst:276 #: ../../library/stdtypes.rst:416 ../../library/stdtypes.rst:965 -#: ../../library/stdtypes.rst:1170 ../../library/stdtypes.rst:2432 -#: ../../library/stdtypes.rst:3651 +#: ../../library/stdtypes.rst:1170 ../../library/stdtypes.rst:2606 +#: ../../library/stdtypes.rst:3825 msgid "Notes" msgstr "Notas" @@ -181,7 +163,7 @@ msgstr "se *x* é true, então *x*, do contrário *y*" #: ../../library/stdtypes.rst:88 ../../library/stdtypes.rst:967 #: ../../library/stdtypes.rst:970 ../../library/stdtypes.rst:1181 -#: ../../library/stdtypes.rst:2438 ../../library/stdtypes.rst:3657 +#: ../../library/stdtypes.rst:2612 ../../library/stdtypes.rst:3831 msgid "\\(1)" msgstr "\\(1)" @@ -195,8 +177,8 @@ msgstr "se *x* é falso, então *x*, do contrário *y*" #: ../../library/stdtypes.rst:91 ../../library/stdtypes.rst:289 #: ../../library/stdtypes.rst:309 ../../library/stdtypes.rst:1209 -#: ../../library/stdtypes.rst:2442 ../../library/stdtypes.rst:2444 -#: ../../library/stdtypes.rst:3661 ../../library/stdtypes.rst:3663 +#: ../../library/stdtypes.rst:2616 ../../library/stdtypes.rst:2618 +#: ../../library/stdtypes.rst:3835 ../../library/stdtypes.rst:3837 msgid "\\(2)" msgstr "\\(2)" @@ -209,18 +191,18 @@ msgid "if *x* is false, then ``True``, else ``False``" msgstr "se *x* é falso, então ``True``, caso contrário ``False``" #: ../../library/stdtypes.rst:94 ../../library/stdtypes.rst:979 -#: ../../library/stdtypes.rst:1212 ../../library/stdtypes.rst:2446 -#: ../../library/stdtypes.rst:2448 ../../library/stdtypes.rst:2450 -#: ../../library/stdtypes.rst:2452 ../../library/stdtypes.rst:3665 -#: ../../library/stdtypes.rst:3667 ../../library/stdtypes.rst:3669 -#: ../../library/stdtypes.rst:3671 +#: ../../library/stdtypes.rst:1212 ../../library/stdtypes.rst:2620 +#: ../../library/stdtypes.rst:2622 ../../library/stdtypes.rst:2624 +#: ../../library/stdtypes.rst:2626 ../../library/stdtypes.rst:3839 +#: ../../library/stdtypes.rst:3841 ../../library/stdtypes.rst:3843 +#: ../../library/stdtypes.rst:3845 msgid "\\(3)" msgstr "\\(3)" #: ../../library/stdtypes.rst:103 ../../library/stdtypes.rst:320 #: ../../library/stdtypes.rst:434 ../../library/stdtypes.rst:1016 -#: ../../library/stdtypes.rst:1221 ../../library/stdtypes.rst:2478 -#: ../../library/stdtypes.rst:3701 +#: ../../library/stdtypes.rst:1221 ../../library/stdtypes.rst:2652 +#: ../../library/stdtypes.rst:3875 msgid "Notes:" msgstr "Notas:" @@ -272,9 +254,9 @@ msgstr "" msgid "This table summarizes the comparison operations:" msgstr "Esta tabela resume as operações de comparação:" -#: ../../library/stdtypes.rst:144 ../../library/stdtypes.rst:2409 -#: ../../library/stdtypes.rst:2432 ../../library/stdtypes.rst:3628 -#: ../../library/stdtypes.rst:3651 +#: ../../library/stdtypes.rst:144 ../../library/stdtypes.rst:2438 +#: ../../library/stdtypes.rst:2583 ../../library/stdtypes.rst:2606 +#: ../../library/stdtypes.rst:3802 ../../library/stdtypes.rst:3825 msgid "Meaning" msgstr "Significado" @@ -614,7 +596,7 @@ msgstr "" "padrão zero." #: ../../library/stdtypes.rst:302 ../../library/stdtypes.rst:1202 -#: ../../library/stdtypes.rst:2440 ../../library/stdtypes.rst:3688 +#: ../../library/stdtypes.rst:2614 ../../library/stdtypes.rst:3862 msgid "\\(6)" msgstr "\\(6)" @@ -652,9 +634,9 @@ msgstr "*x* elevado a *y*" #: ../../library/stdtypes.rst:311 ../../library/stdtypes.rst:313 #: ../../library/stdtypes.rst:1191 ../../library/stdtypes.rst:1194 -#: ../../library/stdtypes.rst:2465 ../../library/stdtypes.rst:2468 -#: ../../library/stdtypes.rst:2471 ../../library/stdtypes.rst:3684 -#: ../../library/stdtypes.rst:3691 +#: ../../library/stdtypes.rst:2639 ../../library/stdtypes.rst:2642 +#: ../../library/stdtypes.rst:2645 ../../library/stdtypes.rst:3858 +#: ../../library/stdtypes.rst:3865 msgid "\\(5)" msgstr "\\(5)" @@ -829,8 +811,8 @@ msgstr ":dfn:`ou` bit a bit de *x* e *y*" #: ../../library/stdtypes.rst:418 ../../library/stdtypes.rst:421 #: ../../library/stdtypes.rst:424 ../../library/stdtypes.rst:1216 -#: ../../library/stdtypes.rst:2454 ../../library/stdtypes.rst:2458 -#: ../../library/stdtypes.rst:3673 ../../library/stdtypes.rst:3677 +#: ../../library/stdtypes.rst:2628 ../../library/stdtypes.rst:2632 +#: ../../library/stdtypes.rst:3847 ../../library/stdtypes.rst:3851 msgid "\\(4)" msgstr "\\(4)" @@ -935,6 +917,20 @@ msgstr "" "Retorna o número de bits necessários para representar um inteiro em binário, " "excluindo o sinal e entrelinha zeros::" +#: ../../library/stdtypes.rst:463 +msgid "" +">>> n = -37\n" +">>> bin(n)\n" +"'-0b100101'\n" +">>> n.bit_length()\n" +"6" +msgstr "" +">>> n = -37\n" +">>> bin(n)\n" +"'-0b100101'\n" +">>> n.bit_length()\n" +"6" + #: ../../library/stdtypes.rst:469 msgid "" "More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the unique " @@ -954,6 +950,18 @@ msgstr "" msgid "Equivalent to::" msgstr "Equivalente a::" +#: ../../library/stdtypes.rst:477 +msgid "" +"def bit_length(self):\n" +" s = bin(self) # binary representation: bin(-37) --> '-0b100101'\n" +" s = s.lstrip('-0b') # remove leading zeros and minus sign\n" +" return len(s) # len('100101') --> 6" +msgstr "" +"def bit_length(self):\n" +" s = bin(self) # representação binária: bin(-37) --> '-0b100101'\n" +" s = s.lstrip('-0b') # remove zeros no início e sinal negativo\n" +" return len(s) # len('100101') --> 6" + #: ../../library/stdtypes.rst:486 msgid "" "Return the number of ones in the binary representation of the absolute value " @@ -962,6 +970,32 @@ msgstr "" "Retorna o número de unidades na representação binária do valor absoluto do " "inteiro. Isso também é conhecido como contagem da população. Exemplo::" +#: ../../library/stdtypes.rst:490 +msgid "" +">>> n = 19\n" +">>> bin(n)\n" +"'0b10011'\n" +">>> n.bit_count()\n" +"3\n" +">>> (-n).bit_count()\n" +"3" +msgstr "" +">>> n = 19\n" +">>> bin(n)\n" +"'0b10011'\n" +">>> n.bit_count()\n" +"3\n" +">>> (-n).bit_count()\n" +"3" + +#: ../../library/stdtypes.rst:500 +msgid "" +"def bit_count(self):\n" +" return bin(self).count(\"1\")" +msgstr "" +"def bit_count(self):\n" +" return bin(self).count(\"1\")" + #: ../../library/stdtypes.rst:507 msgid "Return an array of bytes representing an integer." msgstr "Retorna um vetor de bytes representando um inteiro." @@ -1008,6 +1042,14 @@ msgstr "" "Os valores padrão podem ser usados para transformar convenientemente um " "inteiro em um objeto de byte único::" +#: ../../library/stdtypes.rst:537 +msgid "" +">>> (65).to_bytes()\n" +"b'A'" +msgstr "" +">>> (65).to_bytes()\n" +"b'A'" + #: ../../library/stdtypes.rst:540 msgid "" "However, when using the default arguments, don't try to convert a value " @@ -1016,6 +1058,28 @@ msgstr "" "No entanto, ao usar os argumentos padrão, não tente converter um valor maior " "que 255 ou você obterá um :exc:`OverflowError`." +#: ../../library/stdtypes.rst:545 +msgid "" +"def to_bytes(n, length=1, byteorder='big', signed=False):\n" +" if byteorder == 'little':\n" +" order = range(length)\n" +" elif byteorder == 'big':\n" +" order = reversed(range(length))\n" +" else:\n" +" raise ValueError(\"byteorder must be either 'little' or 'big'\")\n" +"\n" +" return bytes((n >> i*8) & 0xff for i in order)" +msgstr "" +"def to_bytes(n, length=1, byteorder='big', signed=False):\n" +" if byteorder == 'little':\n" +" order = range(length)\n" +" elif byteorder == 'big':\n" +" order = reversed(range(length))\n" +" else:\n" +" raise ValueError(\"byteorder must be either 'little' or 'big'\")\n" +"\n" +" return bytes((n >> i*8) & 0xff for i in order)" + #: ../../library/stdtypes.rst:556 msgid "Added default argument values for ``length`` and ``byteorder``." msgstr "" @@ -1030,7 +1094,7 @@ msgid "" "The argument *bytes* must either be a :term:`bytes-like object` or an " "iterable producing bytes." msgstr "" -"O argumento *bytes* precisa ou ser um :term:`objeto byte ou similar ` ou um iterador produzindo bytes." #: ../../library/stdtypes.rst:577 @@ -1057,9 +1121,39 @@ msgstr "" "O argumento *signed* indica quando o complemento de dois é usado para " "representar o inteiro." +#: ../../library/stdtypes.rst:589 +msgid "" +"def from_bytes(bytes, byteorder='big', signed=False):\n" +" if byteorder == 'little':\n" +" little_ordered = list(bytes)\n" +" elif byteorder == 'big':\n" +" little_ordered = list(reversed(bytes))\n" +" else:\n" +" raise ValueError(\"byteorder must be either 'little' or 'big'\")\n" +"\n" +" n = sum(b << i*8 for i, b in enumerate(little_ordered))\n" +" if signed and little_ordered and (little_ordered[-1] & 0x80):\n" +" n -= 1 << 8*len(little_ordered)\n" +"\n" +" return n" +msgstr "" +"def from_bytes(bytes, byteorder='big', signed=False):\n" +" if byteorder == 'little':\n" +" little_ordered = list(bytes)\n" +" elif byteorder == 'big':\n" +" little_ordered = list(reversed(bytes))\n" +" else:\n" +" raise ValueError(\"byteorder must be either 'little' or 'big'\")\n" +"\n" +" n = sum(b << i*8 for i, b in enumerate(little_ordered))\n" +" if signed and little_ordered and (little_ordered[-1] & 0x80):\n" +" n -= 1 << 8*len(little_ordered)\n" +"\n" +" return n" + #: ../../library/stdtypes.rst:604 msgid "Added default argument value for ``byteorder``." -msgstr "Adicionados valor de argumento padrão para ``byteorder``." +msgstr "Adicionado valor de argumento padrão para ``byteorder``." #: ../../library/stdtypes.rst:609 msgid "" @@ -1111,6 +1205,18 @@ msgstr "" "Retorna ``True`` se a instância do float for finita com o valor integral e " "``False``, caso contrário::" +#: ../../library/stdtypes.rst:640 +msgid "" +">>> (-2.0).is_integer()\n" +"True\n" +">>> (3.2).is_integer()\n" +"False" +msgstr "" +">>> (-2.0).is_integer()\n" +"True\n" +">>> (3.2).is_integer()\n" +"False" + #: ../../library/stdtypes.rst:645 msgid "" "Two methods support conversion to and from hexadecimal strings. Since " @@ -1159,6 +1265,10 @@ msgstr "" msgid "A hexadecimal string takes the form::" msgstr "Uma string hexadecimal toma a forma::" +#: ../../library/stdtypes.rst:674 +msgid "[sign] ['0x'] integer ['.' fraction] ['p' exponent]" +msgstr "[sign] ['0x'] integer ['.' fraction] ['p' exponent]" + #: ../../library/stdtypes.rst:676 msgid "" "where the optional ``sign`` may by either ``+`` or ``-``, ``integer`` and " @@ -1195,6 +1305,14 @@ msgstr "" "string hexadecimal ``0x3.a7p10`` representa o número de ponto flutuante ``(3 " "+ 10./16 + 7./16**2) * 2.0**10`` ou ``3740.0``::" +#: ../../library/stdtypes.rst:695 +msgid "" +">>> float.fromhex('0x3.a7p10')\n" +"3740.0" +msgstr "" +">>> float.fromhex('0x3.a7p10')\n" +"3740.0" + #: ../../library/stdtypes.rst:699 msgid "" "Applying the reverse conversion to ``3740.0`` gives a different hexadecimal " @@ -1203,6 +1321,14 @@ msgstr "" "Aplicando a conversão inversa a ``3740.0`` retorna uma string hexadecimal " "diferente representada pelo mesmo número::" +#: ../../library/stdtypes.rst:702 +msgid "" +">>> float.hex(3740.0)\n" +"'0x1.d380000000000p+11'" +msgstr "" +">>> float.hex(3740.0)\n" +"'0x1.d380000000000p+11'" + #: ../../library/stdtypes.rst:709 msgid "Hashing of numeric types" msgstr "Hashing de tipos numéricos" @@ -1312,6 +1438,106 @@ msgstr "" "Python, equivalentes ao hash embutido, para calcular o hash de números " "racionais, :class:`float` ou :class:`complex`::" +#: ../../library/stdtypes.rst:761 +msgid "" +"import sys, math\n" +"\n" +"def hash_fraction(m, n):\n" +" \"\"\"Compute the hash of a rational number m / n.\n" +"\n" +" Assumes m and n are integers, with n positive.\n" +" Equivalent to hash(fractions.Fraction(m, n)).\n" +"\n" +" \"\"\"\n" +" P = sys.hash_info.modulus\n" +" # Remove common factors of P. (Unnecessary if m and n already " +"coprime.)\n" +" while m % P == n % P == 0:\n" +" m, n = m // P, n // P\n" +"\n" +" if n % P == 0:\n" +" hash_value = sys.hash_info.inf\n" +" else:\n" +" # Fermat's Little Theorem: pow(n, P-1, P) is 1, so\n" +" # pow(n, P-2, P) gives the inverse of n modulo P.\n" +" hash_value = (abs(m) % P) * pow(n, P - 2, P) % P\n" +" if m < 0:\n" +" hash_value = -hash_value\n" +" if hash_value == -1:\n" +" hash_value = -2\n" +" return hash_value\n" +"\n" +"def hash_float(x):\n" +" \"\"\"Compute the hash of a float x.\"\"\"\n" +"\n" +" if math.isnan(x):\n" +" return object.__hash__(x)\n" +" elif math.isinf(x):\n" +" return sys.hash_info.inf if x > 0 else -sys.hash_info.inf\n" +" else:\n" +" return hash_fraction(*x.as_integer_ratio())\n" +"\n" +"def hash_complex(z):\n" +" \"\"\"Compute the hash of a complex number z.\"\"\"\n" +"\n" +" hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z." +"imag)\n" +" # do a signed reduction modulo 2**sys.hash_info.width\n" +" M = 2**(sys.hash_info.width - 1)\n" +" hash_value = (hash_value & (M - 1)) - (hash_value & M)\n" +" if hash_value == -1:\n" +" hash_value = -2\n" +" return hash_value" +msgstr "" +"import sys, math\n" +"\n" +"def hash_fraction(m, n):\n" +" \"\"\"Calcula o hash de um número racional m / n.\n" +"\n" +" Presume que m e n são inteiros, com n positivo.\n" +" Equivalente a hash(fractions.Fraction(m, n)).\n" +"\n" +" \"\"\"\n" +" P = sys.hash_info.modulus\n" +" # Remove fatores comuns de P. (Desnecessário se m e n são primos entre " +"si.)\n" +" while m % P == n % P == 0:\n" +" m, n = m // P, n // P\n" +"\n" +" if n % P == 0:\n" +" hash_value = sys.hash_info.inf\n" +" else:\n" +" # Pequeno teorema de Fermat: pow(n, P-1, P) é 1, então\n" +" # pow(n, P-2, P) dá o inverso de n módulo P.\n" +" hash_value = (abs(m) % P) * pow(n, P - 2, P) % P\n" +" if m < 0:\n" +" hash_value = -hash_value\n" +" if hash_value == -1:\n" +" hash_value = -2\n" +" return hash_value\n" +"\n" +"def hash_float(x):\n" +" \"\"\"Calcula o hash de um ponto flutuante x.\"\"\"\n" +"\n" +" if math.isnan(x):\n" +" return object.__hash__(x)\n" +" elif math.isinf(x):\n" +" return sys.hash_info.inf if x > 0 else -sys.hash_info.inf\n" +" else:\n" +" return hash_fraction(*x.as_integer_ratio())\n" +"\n" +"def hash_complex(z):\n" +" \"\"\"Calcula o hash de um número complexo z.\"\"\"\n" +"\n" +" hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z." +"imag)\n" +" # faz um módulo para redução de sinal 2**sys.hash_info.width\n" +" M = 2**(sys.hash_info.width - 1)\n" +" hash_value = (hash_value & (M - 1)) - (hash_value & M)\n" +" if hash_value == -1:\n" +" hash_value = -2\n" +" return hash_value" + #: ../../library/stdtypes.rst:812 msgid "Boolean Type - :class:`bool`" msgstr "Tipo booleano - :class:`bool`" @@ -1350,10 +1576,10 @@ msgstr "" #: ../../library/stdtypes.rst:834 msgid "" "The use of the bitwise inversion operator ``~`` is deprecated and will raise " -"an error in Python 3.14." +"an error in Python 3.16." msgstr "" "O uso do operador de inversão bit a bit ``~`` foi descontinuado e levantará " -"um erro no Python 3.14." +"um erro no Python 3.16." #: ../../library/stdtypes.rst:837 msgid "" @@ -1473,20 +1699,20 @@ msgstr "Tipos geradores" #: ../../library/stdtypes.rst:909 msgid "" "Python's :term:`generator`\\s provide a convenient way to implement the " -"iterator protocol. If a container object's :meth:`~iterator.__iter__` " -"method is implemented as a generator, it will automatically return an " -"iterator object (technically, a generator object) supplying the :meth:`!" +"iterator protocol. If a container object's :meth:`~object.__iter__` method " +"is implemented as a generator, it will automatically return an iterator " +"object (technically, a generator object) supplying the :meth:`~iterator." "__iter__` and :meth:`~generator.__next__` methods. More information about " "generators can be found in :ref:`the documentation for the yield expression " "`." msgstr "" "Os :term:`geradores ` do Python proveem uma maneira conveniente " -"para implementar o protocolo iterador. Se o método :meth:`~iterator." -"__iter__` de um objeto contêiner é implementado como um gerador, ele irá " +"para implementar o protocolo iterador. Se o método :meth:`~object.__iter__` " +"de um objeto contêiner é implementado como um gerador, ele irá " "automaticamente retornar um objeto iterador (tecnicamente, um objeto " -"gerador) fornecendo os métodos :meth:`!__iter__` e :meth:`~generator." -"__next__` . Mais informações sobre geradores podem ser encontradas na :ref:" -"`documentação para a expressão yield `." +"gerador) fornecendo os métodos :meth:`~iterator.__iter__` e :meth:" +"`~generator.__next__`. Mais informações sobre geradores podem ser " +"encontradas na :ref:`documentação para a expressão yield `." #: ../../library/stdtypes.rst:921 msgid "Sequence Types --- :class:`list`, :class:`tuple`, :class:`range`" @@ -1652,7 +1878,7 @@ msgstr "" "índice da primeira ocorrência de *x* em *s* (no ou após o índice *i*, e " "antes do índice *j*)" -#: ../../library/stdtypes.rst:992 ../../library/stdtypes.rst:3659 +#: ../../library/stdtypes.rst:992 ../../library/stdtypes.rst:3833 msgid "\\(8)" msgstr "\\(8)" @@ -1705,6 +1931,14 @@ msgstr "" "como :class:`str`, :class:`bytes` e :class:`bytearray`) também usam-nas para " "testes de subsequências::" +#: ../../library/stdtypes.rst:1024 +msgid "" +">>> \"gg\" in \"eggs\"\n" +"True" +msgstr "" +">>> \"gg\" in \"eggs\"\n" +"True" + #: ../../library/stdtypes.rst:1028 msgid "" "Values of *n* less than ``0`` are treated as ``0`` (which yields an empty " @@ -1717,6 +1951,22 @@ msgstr "" "*s* não são copiados; eles são referenciados várias vezes. Isso " "frequentemente assombra novos programadores Python; considere então que::" +#: ../../library/stdtypes.rst:1033 +msgid "" +">>> lists = [[]] * 3\n" +">>> lists\n" +"[[], [], []]\n" +">>> lists[0].append(3)\n" +">>> lists\n" +"[[3], [3], [3]]" +msgstr "" +">>> lists = [[]] * 3\n" +">>> lists\n" +"[[], [], []]\n" +">>> lists[0].append(3)\n" +">>> lists\n" +"[[3], [3], [3]]" + #: ../../library/stdtypes.rst:1040 msgid "" "What has happened is that ``[[]]`` is a one-element list containing an empty " @@ -1729,12 +1979,28 @@ msgstr "" "única lista vazia. Modificar qualquer um dos elementos de ``lists`` modifica " "a lista vazia. Podemos criar uma lista de listas diferentes dessa maneira::" +#: ../../library/stdtypes.rst:1045 +msgid "" +">>> lists = [[] for i in range(3)]\n" +">>> lists[0].append(3)\n" +">>> lists[1].append(5)\n" +">>> lists[2].append(7)\n" +">>> lists\n" +"[[3], [5], [7]]" +msgstr "" +">>> lists = [[] for i in range(3)]\n" +">>> lists[0].append(3)\n" +">>> lists[1].append(5)\n" +">>> lists[2].append(7)\n" +">>> lists\n" +"[[3], [5], [7]]" + #: ../../library/stdtypes.rst:1052 msgid "" "Further explanation is available in the FAQ entry :ref:`faq-multidimensional-" "list`." msgstr "" -"Outra explicação está disponível no FAQ :ref:`faq-multidimensional-list`." +"Mais explicação está disponível no FAQ :ref:`faq-multidimensional-list`." #: ../../library/stdtypes.rst:1056 msgid "" @@ -2423,6 +2689,38 @@ msgstr "" msgid "Range examples::" msgstr "Exemplos de intervalos::" +#: ../../library/stdtypes.rst:1417 +msgid "" +">>> list(range(10))\n" +"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n" +">>> list(range(1, 11))\n" +"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n" +">>> list(range(0, 30, 5))\n" +"[0, 5, 10, 15, 20, 25]\n" +">>> list(range(0, 10, 3))\n" +"[0, 3, 6, 9]\n" +">>> list(range(0, -10, -1))\n" +"[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]\n" +">>> list(range(0))\n" +"[]\n" +">>> list(range(1, 0))\n" +"[]" +msgstr "" +">>> list(range(10))\n" +"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n" +">>> list(range(1, 11))\n" +"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n" +">>> list(range(0, 30, 5))\n" +"[0, 5, 10, 15, 20, 25]\n" +">>> list(range(0, 10, 3))\n" +"[0, 3, 6, 9]\n" +">>> list(range(0, -10, -1))\n" +"[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]\n" +">>> list(range(0))\n" +"[]\n" +">>> list(range(1, 0))\n" +"[]" + #: ../../library/stdtypes.rst:1432 msgid "" "Ranges implement all of the :ref:`common ` sequence " @@ -2666,13 +2964,13 @@ msgid "" "buffer objects." msgstr "" "Se pelo menos um de *encoding* ou *errors* for fornecido, *object* deve ser " -"um :term:`objeto byte ou similar ` (por exemplo, :class:" -"`bytes` ou :class:`bytearray`). Nesse caso, se *object* for um objeto :class:" -"`bytes` (ou :class:`bytearray`), então ``str(bytes, encoding, errors)`` será " -"equivalente a :meth:`bytes.decode(encoding, errors) `. Caso " -"contrário, o objeto byte subjacente ao objeto buffer é obtido antes de " -"chamar :meth:`bytes.decode`. Veja :ref:`binaryseq` e :ref:`bufferobjects` " -"para obter informações sobre objetos buffer." +"um :term:`objeto bytes ou similar` (por exemplo, :class:`bytes` ou :class:" +"`bytearray`). Nesse caso, se *object* for um objeto :class:`bytes` (ou :" +"class:`bytearray`), então ``str(bytes, encoding, errors)`` equivale a :meth:" +"`bytes.decode(encoding, errors) `. Caso contrário, o objeto " +"bytes subjacente ao objeto buffer é obtido antes de chamar :meth:`bytes." +"decode`. Veja :ref:`binaryseq` e :ref:`bufferobjects` para obter informações " +"sobre objetos buffer." #: ../../library/stdtypes.rst:1584 msgid "" @@ -2686,6 +2984,14 @@ msgstr "" "representação informal de strings (consulte também a opção de linha de " "comando :option:`-b` para Python). Por exemplo::" +#: ../../library/stdtypes.rst:1589 +msgid "" +">>> str(b'Zoot!')\n" +"\"b'Zoot!'\"" +msgstr "" +">>> str(b'Zoot!')\n" +"\"b'Zoot!'\"" + #: ../../library/stdtypes.rst:1592 msgid "" "For more information on the ``str`` class and its methods, see :ref:" @@ -2700,7 +3006,7 @@ msgstr "" #: ../../library/stdtypes.rst:1604 msgid "String Methods" -msgstr "Métodos de string" +msgstr "String Methods" #: ../../library/stdtypes.rst:1609 msgid "" @@ -2792,14 +3098,30 @@ msgstr "" msgid "" "Return centered in a string of length *width*. Padding is done using the " "specified *fillchar* (default is an ASCII space). The original string is " -"returned if *width* is less than or equal to ``len(s)``." +"returned if *width* is less than or equal to ``len(s)``. For example::" msgstr "" "Retorna um texto centralizado em uma string de comprimento *width*. " "Preenchimento é feito usando o parâmetro *fillchar* especificado (padrão é o " "caractere de espaço ASCII). A string original é retornada se *width* é menor " -"ou igual que ``len(s)``." +"ou igual que ``len(s)``. Por exemplo::" + +#: ../../library/stdtypes.rst:1657 +msgid "" +">>> 'Python'.center(10)\n" +"' Python '\n" +">>> 'Python'.center(10, '-')\n" +"'--Python--'\n" +">>> 'Python'.center(4)\n" +"'Python'" +msgstr "" +">>> 'Python'.center(10)\n" +"' Python '\n" +">>> 'Python'.center(10, '-')\n" +"'--Python--'\n" +">>> 'Python'.center(4)\n" +"'Python'" -#: ../../library/stdtypes.rst:1661 +#: ../../library/stdtypes.rst:1667 msgid "" "Return the number of non-overlapping occurrences of substring *sub* in the " "range [*start*, *end*]. Optional arguments *start* and *end* are " @@ -2809,19 +3131,43 @@ msgstr "" "intervalo [*start*, *end*]. Argumentos opcionais *start* e *end* são " "interpretados como na notação de fatias." -#: ../../library/stdtypes.rst:1665 +#: ../../library/stdtypes.rst:1671 msgid "" "If *sub* is empty, returns the number of empty strings between characters " -"which is the length of the string plus one." +"which is the length of the string plus one. For example::" msgstr "" "Se *sub* estiver vazio, retorna o número de strings vazias entre os " -"caracteres, que é o comprimento da string mais um." - -#: ../../library/stdtypes.rst:1671 +"caracteres, que é o comprimento da string mais um. Por exemplo::" + +#: ../../library/stdtypes.rst:1674 +msgid "" +">>> 'spam, spam, spam'.count('spam')\n" +"3\n" +">>> 'spam, spam, spam'.count('spam', 5)\n" +"2\n" +">>> 'spam, spam, spam'.count('spam', 5, 10)\n" +"1\n" +">>> 'spam, spam, spam'.count('eggs')\n" +"0\n" +">>> 'spam, spam, spam'.count('')\n" +"17" +msgstr "" +">>> 'spam, spam, spam'.count('spam')\n" +"3\n" +">>> 'spam, spam, spam'.count('spam', 5)\n" +"2\n" +">>> 'spam, spam, spam'.count('spam', 5, 10)\n" +"1\n" +">>> 'spam, spam, spam'.count('eggs')\n" +"0\n" +">>> 'spam, spam, spam'.count('')\n" +"17" + +#: ../../library/stdtypes.rst:1687 msgid "Return the string encoded to :class:`bytes`." msgstr "Retorna a string codificada para :class:`bytes`." -#: ../../library/stdtypes.rst:1673 ../../library/stdtypes.rst:2824 +#: ../../library/stdtypes.rst:1689 ../../library/stdtypes.rst:2998 msgid "" "*encoding* defaults to ``'utf-8'``; see :ref:`standard-encodings` for " "possible values." @@ -2829,7 +3175,7 @@ msgstr "" "*encoding* tem como padrão ``'utf-8'``; veja :ref:`standard-encodings` para " "valores possíveis." -#: ../../library/stdtypes.rst:1676 +#: ../../library/stdtypes.rst:1692 msgid "" "*errors* controls how encoding errors are handled. If ``'strict'`` (the " "default), a :exc:`UnicodeError` exception is raised. Other possible values " @@ -2843,7 +3189,7 @@ msgstr "" "``'backslashreplace'`` e qualquer outro nome registrado via :func:`codecs." "register_error`. Veja :ref:`error-handlers` para detalhes." -#: ../../library/stdtypes.rst:1683 +#: ../../library/stdtypes.rst:1699 msgid "" "For performance reasons, the value of *errors* is not checked for validity " "unless an encoding error actually occurs, :ref:`devmode` is enabled or a :" @@ -2854,11 +3200,11 @@ msgstr "" "`devmode` esteja ativado ou uma :ref:`construção de depuração ` " "seja usada." -#: ../../library/stdtypes.rst:1688 ../../library/stdtypes.rst:2843 +#: ../../library/stdtypes.rst:1704 ../../library/stdtypes.rst:3017 msgid "Added support for keyword arguments." msgstr "Adicionado suporte para argumentos nomeados." -#: ../../library/stdtypes.rst:1691 ../../library/stdtypes.rst:2846 +#: ../../library/stdtypes.rst:1707 ../../library/stdtypes.rst:3020 msgid "" "The value of the *errors* argument is now checked in :ref:`devmode` and in :" "ref:`debug mode `." @@ -2866,7 +3212,7 @@ msgstr "" "O valor do argumento *errors* agora é verificado em :ref:`devmode` e no :ref:" "`modo de depuração `." -#: ../../library/stdtypes.rst:1698 +#: ../../library/stdtypes.rst:1714 msgid "" "Return ``True`` if the string ends with the specified *suffix*, otherwise " "return ``False``. *suffix* can also be a tuple of suffixes to look for. " @@ -2879,7 +3225,7 @@ msgstr "" "daquela posição. Com o parâmetro opcional *end*, devemos parar de comparar " "na posição especificada." -#: ../../library/stdtypes.rst:1706 +#: ../../library/stdtypes.rst:1722 msgid "" "Return a copy of the string where all tab characters are replaced by one or " "more spaces, depending on the current column and the given tab size. Tab " @@ -2908,7 +3254,7 @@ msgstr "" "ser modificado e a coluna atual é incrementada em uma unidade " "independentemente de como o caractere é representado quando é impresso." -#: ../../library/stdtypes.rst:1727 +#: ../../library/stdtypes.rst:1743 msgid "" "Return the lowest index in the string where substring *sub* is found within " "the slice ``s[start:end]``. Optional arguments *start* and *end* are " @@ -2919,7 +3265,7 @@ msgstr "" "são interpretados como na notação de fatiamento. Retorna ``-1`` se *sub* não " "for localizado." -#: ../../library/stdtypes.rst:1733 +#: ../../library/stdtypes.rst:1749 msgid "" "The :meth:`~str.find` method should be used only if you need to know the " "position of *sub*. To check if *sub* is a substring or not, use the :" @@ -2929,7 +3275,15 @@ msgstr "" "posição de *sub*. Para verificar se *sub* é ou não uma substring, use o " "operador :keyword:`in`::" -#: ../../library/stdtypes.rst:1743 +#: ../../library/stdtypes.rst:1753 +msgid "" +">>> 'Py' in 'Python'\n" +"True" +msgstr "" +">>> 'Py' in 'Python'\n" +"True" + +#: ../../library/stdtypes.rst:1759 msgid "" "Perform a string formatting operation. The string on which this method is " "called can contain literal text or replacement fields delimited by braces " @@ -2945,7 +3299,7 @@ msgstr "" "da string onde cada campo para substituição é substituído com o valor da " "string do argumento correspondente." -#: ../../library/stdtypes.rst:1753 +#: ../../library/stdtypes.rst:1769 msgid "" "See :ref:`formatstrings` for a description of the various formatting options " "that can be specified in format strings." @@ -2953,7 +3307,7 @@ msgstr "" "Veja :ref:`formatstrings` para uma descrição das várias opções de formatação " "que podem ser especificadas em uma strings de formato." -#: ../../library/stdtypes.rst:1757 +#: ../../library/stdtypes.rst:1773 msgid "" "When formatting a number (:class:`int`, :class:`float`, :class:`complex`, :" "class:`decimal.Decimal` and subclasses) with the ``n`` type (ex: ``'{:n}'." @@ -2972,7 +3326,7 @@ msgstr "" "diferente da localidade ``LC_CTYPE``. Esta mudança temporária afeta outras " "threads." -#: ../../library/stdtypes.rst:1766 +#: ../../library/stdtypes.rst:1782 msgid "" "When formatting a number with the ``n`` type, the function sets temporarily " "the ``LC_CTYPE`` locale to the ``LC_NUMERIC`` locale in some cases." @@ -2980,7 +3334,7 @@ msgstr "" "Ao formatar um número com o tipo ``n``, a função define temporariamente a " "localidade ``LC_CTYPE`` para a localidade ``LC_NUMERIC`` em alguns casos." -#: ../../library/stdtypes.rst:1774 +#: ../../library/stdtypes.rst:1790 msgid "" "Similar to ``str.format(**mapping)``, except that ``mapping`` is used " "directly and not copied to a :class:`dict`. This is useful if for example " @@ -2990,7 +3344,7 @@ msgstr "" "é usado diretamente e não copiado para uma classe :class:`dict`. Isso é útil " "se, por exemplo, ``mapping`` é uma subclasse de dict:" -#: ../../library/stdtypes.rst:1790 +#: ../../library/stdtypes.rst:1806 msgid "" "Like :meth:`~str.find`, but raise :exc:`ValueError` when the substring is " "not found." @@ -2998,7 +3352,7 @@ msgstr "" "Senelhante a :meth:`~str.find`, mas levanta :exc:`ValueError` quando a " "substring não é encontrada." -#: ../../library/stdtypes.rst:1796 +#: ../../library/stdtypes.rst:1812 msgid "" "Return ``True`` if all characters in the string are alphanumeric and there " "is at least one character, ``False`` otherwise. A character ``c`` is " @@ -3010,7 +3364,7 @@ msgstr "" "alfanumérico se um dos seguintes retorna ``True``: ``c.isalpha()``, ``c." "isdecimal()``, ``c.isdigit()``, ou ``c.isnumeric()``." -#: ../../library/stdtypes.rst:1804 +#: ../../library/stdtypes.rst:1820 msgid "" "Return ``True`` if all characters in the string are alphabetic and there is " "at least one character, ``False`` otherwise. Alphabetic characters are " @@ -3030,7 +3384,7 @@ msgstr "" "Ideographic\" do Padrão Unicode `_." -#: ../../library/stdtypes.rst:1815 +#: ../../library/stdtypes.rst:1831 msgid "" "Return ``True`` if the string is empty or all characters in the string are " "ASCII, ``False`` otherwise. ASCII characters have code points in the range " @@ -3040,7 +3394,7 @@ msgstr "" "ASCII, ``False`` caso contrário. Caracteres ASCII têm pontos de código no " "intervalo U+0000-U+007F." -#: ../../library/stdtypes.rst:1824 +#: ../../library/stdtypes.rst:1840 msgid "" "Return ``True`` if all characters in the string are decimal characters and " "there is at least one character, ``False`` otherwise. Decimal characters are " @@ -3054,7 +3408,7 @@ msgstr "" "exemplo U+0660, ou dígito zero para arábico-índico. Formalmente, um " "caractere decimal é um caractere em Unicode cuja categoria geral é \"Nd\"." -#: ../../library/stdtypes.rst:1834 +#: ../../library/stdtypes.rst:1850 msgid "" "Return ``True`` if all characters in the string are digits and there is at " "least one character, ``False`` otherwise. Digits include decimal characters " @@ -3071,7 +3425,7 @@ msgstr "" "de Kharosthi. Formalmente, um dígito é um caractere que tem a propriedade " "com valor Numeric_Type=Digit ou Numeric_Type=Decimal." -#: ../../library/stdtypes.rst:1844 +#: ../../library/stdtypes.rst:1860 msgid "" "Return ``True`` if the string is a valid identifier according to the " "language definition, section :ref:`identifiers`." @@ -3079,7 +3433,7 @@ msgstr "" "Retorna ``True`` se a string é um identificador válido conforme a definição " "da linguagem, seção :ref:`identifiers`." -#: ../../library/stdtypes.rst:1847 +#: ../../library/stdtypes.rst:1863 msgid "" ":func:`keyword.iskeyword` can be used to test whether string ``s`` is a " "reserved identifier, such as :keyword:`def` and :keyword:`class`." @@ -3087,11 +3441,27 @@ msgstr "" ":func:`keyword.iskeyword` pode ser usada para testar se a string ``s`` é uma " "palavra reservada, tal como :keyword:`def` e :keyword:`class`." -#: ../../library/stdtypes.rst:1850 +#: ../../library/stdtypes.rst:1866 msgid "Example: ::" msgstr "Exemplo: ::" -#: ../../library/stdtypes.rst:1863 +#: ../../library/stdtypes.rst:1869 +msgid "" +">>> from keyword import iskeyword\n" +"\n" +">>> 'hello'.isidentifier(), iskeyword('hello')\n" +"(True, False)\n" +">>> 'def'.isidentifier(), iskeyword('def')\n" +"(True, True)" +msgstr "" +">>> from keyword import iskeyword\n" +"\n" +">>> 'olá.isidentifier(), iskeyword('olá')\n" +"(True, False)\n" +">>> 'def'.isidentifier(), iskeyword('def')\n" +"(True, True)" + +#: ../../library/stdtypes.rst:1879 msgid "" "Return ``True`` if all cased characters [4]_ in the string are lowercase and " "there is at least one cased character, ``False`` otherwise." @@ -3100,7 +3470,7 @@ msgstr "" "minúsculo) [4]_ na string são minúsculos e existe pelo menos um caractere em " "caixa, ``False`` caso contrário." -#: ../../library/stdtypes.rst:1869 +#: ../../library/stdtypes.rst:1885 msgid "" "Return ``True`` if all characters in the string are numeric characters, and " "there is at least one character, ``False`` otherwise. Numeric characters " @@ -3116,27 +3486,41 @@ msgstr "" "Formalmente, caracteres numéricos são aqueles que possuem propriedades com " "valor Numeric_Type=Digit, Numeric_Type=Decimal ou Numeric_Type=Numeric." -#: ../../library/stdtypes.rst:1879 +#: ../../library/stdtypes.rst:1895 +msgid "" +"Return ``True`` if all characters in the string are printable, ``False`` if " +"it contains at least one non-printable character." +msgstr "" +"Retorna ``True`` se todos os caracteres na string forem imprimíveis, " +"``False`` se contiver pelo menos um caractere não imprimível." + +#: ../../library/stdtypes.rst:1898 msgid "" -"Return ``True`` if all characters in the string are printable or the string " -"is empty, ``False`` otherwise. Nonprintable characters are those characters " -"defined in the Unicode character database as \"Other\" or \"Separator\", " -"excepting the ASCII space (0x20) which is considered printable. (Note that " -"printable characters in this context are those which should not be escaped " -"when :func:`repr` is invoked on a string. It has no bearing on the handling " -"of strings written to :data:`sys.stdout` or :data:`sys.stderr`.)" -msgstr "" -"Retorna ``True`` se todos os caracteres na string podem ser impressos ou se " -"a string é vazia, ``False`` caso contrário. Caracteres que não podem ser " -"impressos são aqueles que estão definidos no banco de dados de caracteres " -"Unicode como \"Outros\" ou \"Separadores\", exceto o caractere ASCII que " -"representa o espaço (0x20), o qual é impresso. (Perceba que caracteres que " -"podem ser impressos, neste contexto, são aqueles que não devem ser escapados " -"quando :func:`repr` é invocada sobre uma string. Ela não tem sentido no " -"tratamento de strings escritas usando :data:`sys.stdout` ou :data:`sys." -"stderr`.)" - -#: ../../library/stdtypes.rst:1890 +"Here \"printable\" means the character is suitable for :func:`repr` to use " +"in its output; \"non-printable\" means that :func:`repr` on built-in types " +"will hex-escape the character. It has no bearing on the handling of strings " +"written to :data:`sys.stdout` or :data:`sys.stderr`." +msgstr "" +"Aqui, \"imprimíveis\" significa que o caractere é adequado para :func:`repr` " +"usar em sua saída; \"não imprimível\" significa que :func:`repr` em tipos " +"embutidos fará o escape hexadecimal do caractere. Não tem relação com o " +"tratamento de strings escritas em :data:`sys.stdout` ou :data:`sys.stderr`." + +#: ../../library/stdtypes.rst:1903 +msgid "" +"The printable characters are those which in the Unicode character database " +"(see :mod:`unicodedata`) have a general category in group Letter, Mark, " +"Number, Punctuation, or Symbol (L, M, N, P, or S); plus the ASCII space " +"0x20. Nonprintable characters are those in group Separator or Other (Z or " +"C), except the ASCII space." +msgstr "" +"Os caracteres imprimíveis são aqueles que no banco de dados de caracteres " +"Unicode (veja :mod:`unicodedata`) têm uma categoria geral no grupo Letra, " +"Marca, Número, Pontuação ou Símbolo (L, M, N, P ou S); mais o espaço ASCII " +"0x20. Caracteres não imprimíveis são aqueles no grupo Separador ou Outro (Z " +"ou C), exceto o espaço ASCII." + +#: ../../library/stdtypes.rst:1912 msgid "" "Return ``True`` if there are only whitespace characters in the string and " "there is at least one character, ``False`` otherwise." @@ -3144,7 +3528,7 @@ msgstr "" "Retorna ``True`` se existem apenas caracteres de espaço em branco na string " "e existe pelo menos um caractere, ``False`` caso contrário." -#: ../../library/stdtypes.rst:1893 +#: ../../library/stdtypes.rst:1915 msgid "" "A character is *whitespace* if in the Unicode character database (see :mod:" "`unicodedata`), either its general category is ``Zs`` (\"Separator, " @@ -3154,7 +3538,7 @@ msgstr "" "(veja :mod:`unicodedata`), ou pertence a categoria geral ``Zs`` " "(\"Separador, espaço\"), ou sua classe bidirecional é ``WS``, ``B`` ou ``S``." -#: ../../library/stdtypes.rst:1901 +#: ../../library/stdtypes.rst:1923 msgid "" "Return ``True`` if the string is a titlecased string and there is at least " "one character, for example uppercase characters may only follow uncased " @@ -3166,7 +3550,7 @@ msgstr "" "diferenciam maiúsculas/minúsculas, e caracteres minúsculos somente podem " "proceder caracteres que permitem ambos. Retorna ``False`` caso contrário." -#: ../../library/stdtypes.rst:1908 +#: ../../library/stdtypes.rst:1930 msgid "" "Return ``True`` if all cased characters [4]_ in the string are uppercase and " "there is at least one cased character, ``False`` otherwise." @@ -3175,7 +3559,7 @@ msgstr "" "minúsculas [4]_ na string estão com letras maiúsculas, e existe pelo menos " "um caractere maiúsculo, ``False`` caso contrário." -#: ../../library/stdtypes.rst:1926 +#: ../../library/stdtypes.rst:1948 msgid "" "Return a string which is the concatenation of the strings in *iterable*. A :" "exc:`TypeError` will be raised if there are any non-string values in " @@ -3187,7 +3571,7 @@ msgstr "" "strings no *iterável*, incluindo objetos :class:`bytes`. O separador entre " "elementos é a string que está fornecendo este método." -#: ../../library/stdtypes.rst:1934 +#: ../../library/stdtypes.rst:1956 msgid "" "Return the string left justified in a string of length *width*. Padding is " "done using the specified *fillchar* (default is an ASCII space). The " @@ -3198,7 +3582,7 @@ msgstr "" "caractere ASCII de espaço). A string original é retornada se *width* é menor " "ou igual que ``len(s)``." -#: ../../library/stdtypes.rst:1941 +#: ../../library/stdtypes.rst:1963 msgid "" "Return a copy of the string with all the cased characters [4]_ converted to " "lowercase." @@ -3206,7 +3590,7 @@ msgstr "" "Retorna uma cópia da string com todos os caracteres que permitem maiúsculo E " "minúsculo [4]_ convertidos para letras minúsculas." -#: ../../library/stdtypes.rst:1944 +#: ../../library/stdtypes.rst:1966 msgid "" "The lowercasing algorithm used is `described in section 3.13 'Default Case " "Folding' of the Unicode Standard `__." -#: ../../library/stdtypes.rst:1951 +#: ../../library/stdtypes.rst:1973 msgid "" "Return a copy of the string with leading characters removed. The *chars* " "argument is a string specifying the set of characters to be removed. If " @@ -3229,9 +3613,21 @@ msgstr "" "removidos. Se for omitido ou se for ``None``, o argumento *chars* será " "considerado como espaço em branco por padrão para a remoção. O argumento " "*chars* não é um prefixo; ao invés disso, todas as combinações dos seus " -"valores são retirados::" +"valores são removidas::" + +#: ../../library/stdtypes.rst:1978 +msgid "" +">>> ' spacious '.lstrip()\n" +"'spacious '\n" +">>> 'www.example.com'.lstrip('cmowz.')\n" +"'example.com'" +msgstr "" +">>> ' spacious '.lstrip()\n" +"'spacious '\n" +">>> 'www.example.com'.lstrip('cmowz.')\n" +"'example.com'" -#: ../../library/stdtypes.rst:1961 +#: ../../library/stdtypes.rst:1983 msgid "" "See :meth:`str.removeprefix` for a method that will remove a single prefix " "string rather than all of a set of characters. For example::" @@ -3239,7 +3635,19 @@ msgstr "" "Consulte :meth:`str.removeprefix` para um método que removerá uma única " "string de prefixo em vez de todo um conjunto de caracteres. Por exemplo::" -#: ../../library/stdtypes.rst:1972 +#: ../../library/stdtypes.rst:1986 +msgid "" +">>> 'Arthur: three!'.lstrip('Arthur: ')\n" +"'ee!'\n" +">>> 'Arthur: three!'.removeprefix('Arthur: ')\n" +"'three!'" +msgstr "" +">>> 'Arthur: three!'.lstrip('Arthur: ')\n" +"'ee!'\n" +">>> 'Arthur: three!'.removeprefix('Arthur: ')\n" +"'three!'" + +#: ../../library/stdtypes.rst:1994 msgid "" "This static method returns a translation table usable for :meth:`str." "translate`." @@ -3247,7 +3655,7 @@ msgstr "" "Este método estático retorna uma tabela de tradução usável para :meth:`str." "translate`." -#: ../../library/stdtypes.rst:1974 +#: ../../library/stdtypes.rst:1996 msgid "" "If there is only one argument, it must be a dictionary mapping Unicode " "ordinals (integers) or characters (strings of length 1) to Unicode ordinals, " @@ -3259,7 +3667,7 @@ msgstr "" "Unicode, strings (de comprimento arbitrário) ou ``None``. Caracteres chave " "serão então convertidos para números ordinais." -#: ../../library/stdtypes.rst:1979 +#: ../../library/stdtypes.rst:2001 msgid "" "If there are two arguments, they must be strings of equal length, and in the " "resulting dictionary, each character in x will be mapped to the character at " @@ -3271,7 +3679,7 @@ msgstr "" "na mesma posição em y. Se existir um terceiro argumento, ele deve ser uma " "string, cujos caracteres serão mapeados para ``None`` no resultado." -#: ../../library/stdtypes.rst:1987 +#: ../../library/stdtypes.rst:2009 msgid "" "Split the string at the first occurrence of *sep*, and return a 3-tuple " "containing the part before the separator, the separator itself, and the part " @@ -3283,7 +3691,7 @@ msgstr "" "parte após o separador. Se o separador não for encontrado, retorna uma tupla " "com 3 elementos contendo a string, seguido de duas strings vazias." -#: ../../library/stdtypes.rst:1995 +#: ../../library/stdtypes.rst:2017 msgid "" "If the string starts with the *prefix* string, return " "``string[len(prefix):]``. Otherwise, return a copy of the original string::" @@ -3291,7 +3699,19 @@ msgstr "" "Se a string começar com a string *prefix*, retorna ``string[len(prefix):]``. " "Caso contrário, retorna uma cópia da string original::" -#: ../../library/stdtypes.rst:2009 +#: ../../library/stdtypes.rst:2021 +msgid "" +">>> 'TestHook'.removeprefix('Test')\n" +"'Hook'\n" +">>> 'BaseTestCase'.removeprefix('Test')\n" +"'BaseTestCase'" +msgstr "" +">>> 'TestHook'.removeprefix('Test')\n" +"'Hook'\n" +">>> 'BaseTestCase'.removeprefix('Test')\n" +"'BaseTestCase'" + +#: ../../library/stdtypes.rst:2031 msgid "" "If the string ends with the *suffix* string and that *suffix* is not empty, " "return ``string[:-len(suffix)]``. Otherwise, return a copy of the original " @@ -3301,7 +3721,19 @@ msgstr "" "retorna ``string[:-len(suffix)]``. Caso contrário, retorna uma cópia da " "string original::" -#: ../../library/stdtypes.rst:2023 +#: ../../library/stdtypes.rst:2035 +msgid "" +">>> 'MiscTests'.removesuffix('Tests')\n" +"'Misc'\n" +">>> 'TmpDirMixin'.removesuffix('Tests')\n" +"'TmpDirMixin'" +msgstr "" +">>> 'MiscTests'.removesuffix('Tests')\n" +"'Misc'\n" +">>> 'TmpDirMixin'.removesuffix('Tests')\n" +"'TmpDirMixin'" + +#: ../../library/stdtypes.rst:2045 msgid "" "Return a copy of the string with all occurrences of substring *old* replaced " "by *new*. If *count* is given, only the first *count* occurrences are " @@ -3314,11 +3746,11 @@ msgstr "" "especificado ou é igual a ``-1``, então todas as ocorrências serão " "substituídas." -#: ../../library/stdtypes.rst:2027 +#: ../../library/stdtypes.rst:2049 msgid "*count* is now supported as a keyword argument." msgstr "*count* agora é suportado como um argumento nomeado." -#: ../../library/stdtypes.rst:2033 +#: ../../library/stdtypes.rst:2055 msgid "" "Return the highest index in the string where substring *sub* is found, such " "that *sub* is contained within ``s[start:end]``. Optional arguments *start* " @@ -3329,7 +3761,7 @@ msgstr "" "Argumentos opcionais *start* e *end* são interpretados usando a notação " "slice. Retorna ``-1`` em caso de falha." -#: ../../library/stdtypes.rst:2040 +#: ../../library/stdtypes.rst:2062 msgid "" "Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is " "not found." @@ -3337,7 +3769,7 @@ msgstr "" "Similar a :meth:`rfind` mas levanta um :exc:`ValueError` quando a substring " "*sub* não é encontrada." -#: ../../library/stdtypes.rst:2046 +#: ../../library/stdtypes.rst:2068 msgid "" "Return the string right justified in a string of length *width*. Padding is " "done using the specified *fillchar* (default is an ASCII space). The " @@ -3348,7 +3780,7 @@ msgstr "" "um caractere de espaço ASCII). A string original é retornada se *width* é " "menor que ou igual a ``len(s)``." -#: ../../library/stdtypes.rst:2053 +#: ../../library/stdtypes.rst:2075 msgid "" "Split the string at the last occurrence of *sep*, and return a 3-tuple " "containing the part before the separator, the separator itself, and the part " @@ -3361,7 +3793,7 @@ msgstr "" "com 3 elementos contendo duas strings vazias, seguido da própria string " "original." -#: ../../library/stdtypes.rst:2061 +#: ../../library/stdtypes.rst:2083 msgid "" "Return a list of the words in the string, using *sep* as the delimiter " "string. If *maxsplit* is given, at most *maxsplit* splits are done, the " @@ -3376,7 +3808,7 @@ msgstr "" "Exceto pelo fato de separar pela direita, :meth:`rsplit` se comporta como :" "meth:`split`, o qual é descrito em detalhes abaixo." -#: ../../library/stdtypes.rst:2070 +#: ../../library/stdtypes.rst:2092 msgid "" "Return a copy of the string with trailing characters removed. The *chars* " "argument is a string specifying the set of characters to be removed. If " @@ -3389,9 +3821,21 @@ msgstr "" "removidos. Se omitidos ou tiver o valor ``None``, o argumento *chars* " "considera como padrão a remoção dos espaços em branco. O argumento *chars* " "não é um sufixo; ao invés disso, todas as combinações dos seus valores são " -"removidos::" +"removidas::" + +#: ../../library/stdtypes.rst:2097 +msgid "" +">>> ' spacious '.rstrip()\n" +"' spacious'\n" +">>> 'mississippi'.rstrip('ipz')\n" +"'mississ'" +msgstr "" +">>> ' spacious '.rstrip()\n" +"' spacious'\n" +">>> 'mississippi'.rstrip('ipz')\n" +"'mississ'" -#: ../../library/stdtypes.rst:2080 +#: ../../library/stdtypes.rst:2102 msgid "" "See :meth:`str.removesuffix` for a method that will remove a single suffix " "string rather than all of a set of characters. For example::" @@ -3399,7 +3843,19 @@ msgstr "" "Consulte :meth:`str.removesuffix` para um método que removerá uma única " "string de sufixo em vez de todo um conjunto de caracteres. Por exemplo::" -#: ../../library/stdtypes.rst:2090 +#: ../../library/stdtypes.rst:2105 +msgid "" +">>> 'Monty Python'.rstrip(' Python')\n" +"'M'\n" +">>> 'Monty Python'.removesuffix(' Python')\n" +"'Monty'" +msgstr "" +">>> 'Monty Python'.rstrip(' Python')\n" +"'M'\n" +">>> 'Monty Python'.removesuffix(' Python')\n" +"'Monty'" + +#: ../../library/stdtypes.rst:2112 msgid "" "Return a list of the words in the string, using *sep* as the delimiter " "string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, " @@ -3413,7 +3869,7 @@ msgstr "" "*maxsplit* não foi especificado ou ``-1`` foi informado, então não existe " "limite no número de cortes (todos os cortes possíveis são realizados)." -#: ../../library/stdtypes.rst:2096 +#: ../../library/stdtypes.rst:2118 msgid "" "If *sep* is given, consecutive delimiters are not grouped together and are " "deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns " @@ -3429,20 +3885,40 @@ msgstr "" "delimitadores, use :func:`re.split`). Separar uma string vazia com um " "separador especificado retorna ``['']``." -#: ../../library/stdtypes.rst:2103 ../../library/stdtypes.rst:2121 -#: ../../library/stdtypes.rst:2173 ../../library/stdtypes.rst:2241 -#: ../../library/stdtypes.rst:2309 ../../library/stdtypes.rst:3161 -#: ../../library/stdtypes.rst:3179 ../../library/stdtypes.rst:3270 -#: ../../library/stdtypes.rst:3286 ../../library/stdtypes.rst:3311 -#: ../../library/stdtypes.rst:3325 ../../library/stdtypes.rst:3353 -#: ../../library/stdtypes.rst:3367 ../../library/stdtypes.rst:3385 -#: ../../library/stdtypes.rst:3412 ../../library/stdtypes.rst:3435 -#: ../../library/stdtypes.rst:3462 ../../library/stdtypes.rst:3504 -#: ../../library/stdtypes.rst:3528 +#: ../../library/stdtypes.rst:2125 ../../library/stdtypes.rst:2143 +#: ../../library/stdtypes.rst:2155 ../../library/stdtypes.rst:2207 +#: ../../library/stdtypes.rst:2275 ../../library/stdtypes.rst:2343 +#: ../../library/stdtypes.rst:3335 ../../library/stdtypes.rst:3353 +#: ../../library/stdtypes.rst:3444 ../../library/stdtypes.rst:3460 +#: ../../library/stdtypes.rst:3485 ../../library/stdtypes.rst:3499 +#: ../../library/stdtypes.rst:3527 ../../library/stdtypes.rst:3541 +#: ../../library/stdtypes.rst:3559 ../../library/stdtypes.rst:3586 +#: ../../library/stdtypes.rst:3609 ../../library/stdtypes.rst:3636 +#: ../../library/stdtypes.rst:3678 ../../library/stdtypes.rst:3702 msgid "For example::" msgstr "Por exemplo::" -#: ../../library/stdtypes.rst:2114 +#: ../../library/stdtypes.rst:2127 +msgid "" +">>> '1,2,3'.split(',')\n" +"['1', '2', '3']\n" +">>> '1,2,3'.split(',', maxsplit=1)\n" +"['1', '2,3']\n" +">>> '1,2,,3,'.split(',')\n" +"['1', '2', '', '3', '']\n" +">>> '1<>2<>3<4'.split('<>')\n" +"['1', '2', '3<4']" +msgstr "" +">>> '1,2,3'.split(',')\n" +"['1', '2', '3']\n" +">>> '1,2,3'.split(',', maxsplit=1)\n" +"['1', '2,3']\n" +">>> '1,2,,3,'.split(',')\n" +"['1', '2', '', '3', '']\n" +">>> '1<>2<>3<4'.split('<>')\n" +"['1', '2', '3<4']" + +#: ../../library/stdtypes.rst:2136 msgid "" "If *sep* is not specified or is ``None``, a different splitting algorithm is " "applied: runs of consecutive whitespace are regarded as a single separator, " @@ -3459,7 +3935,48 @@ msgstr "" "consiste apenas de espaços em branco com o separador ``None``, retorna " "``[]``." -#: ../../library/stdtypes.rst:2136 +#: ../../library/stdtypes.rst:2145 +msgid "" +">>> '1 2 3'.split()\n" +"['1', '2', '3']\n" +">>> '1 2 3'.split(maxsplit=1)\n" +"['1', '2 3']\n" +">>> ' 1 2 3 '.split()\n" +"['1', '2', '3']" +msgstr "" +">>> '1 2 3'.split()\n" +"['1', '2', '3']\n" +">>> '1 2 3'.split(maxsplit=1)\n" +"['1', '2 3']\n" +">>> ' 1 2 3 '.split()\n" +"['1', '2', '3']" + +#: ../../library/stdtypes.rst:2152 +msgid "" +"If *sep* is not specified or is ``None`` and *maxsplit* is ``0``, only " +"leading runs of consecutive whitespace are considered." +msgstr "" +"Se *sep* não for especificado ou for ``None`` e *maxsplit* for ``0``, " +"somente as sequências iniciais de espaços em branco consecutivos serão " +"consideradas." + +#: ../../library/stdtypes.rst:2157 +msgid "" +">>> \"\".split(None, 0)\n" +"[]\n" +">>> \" \".split(None, 0)\n" +"[]\n" +">>> \" foo \".split(maxsplit=0)\n" +"['foo ']" +msgstr "" +">>> \"\".split(None, 0)\n" +"[]\n" +">>> \" \".split(None, 0)\n" +"[]\n" +">>> \" foo \".split(maxsplit=0)\n" +"['foo ']" + +#: ../../library/stdtypes.rst:2170 msgid "" "Return a list of the lines in the string, breaking at line boundaries. Line " "breaks are not included in the resulting list unless *keepends* is given and " @@ -3469,7 +3986,7 @@ msgstr "" "cada linha. Quebras de linhas não são incluídas na lista resultante a não " "ser que *keepends* seja fornecido e seja verdadeiro." -#: ../../library/stdtypes.rst:2140 +#: ../../library/stdtypes.rst:2174 msgid "" "This method splits on the following line boundaries. In particular, the " "boundaries are a superset of :term:`universal newlines`." @@ -3478,107 +3995,119 @@ msgstr "" "limites são um superconjunto de :term:`novas linhas universais `." -#: ../../library/stdtypes.rst:2144 +#: ../../library/stdtypes.rst:2178 msgid "Representation" msgstr "Representação" -#: ../../library/stdtypes.rst:2144 +#: ../../library/stdtypes.rst:2178 msgid "Description" msgstr "Descrição" -#: ../../library/stdtypes.rst:2146 +#: ../../library/stdtypes.rst:2180 msgid "``\\n``" msgstr "``\\n``" -#: ../../library/stdtypes.rst:2146 +#: ../../library/stdtypes.rst:2180 msgid "Line Feed" msgstr "Feed de linha" -#: ../../library/stdtypes.rst:2148 +#: ../../library/stdtypes.rst:2182 msgid "``\\r``" msgstr "``\\r``" -#: ../../library/stdtypes.rst:2148 +#: ../../library/stdtypes.rst:2182 msgid "Carriage Return" msgstr "Retorno de Carro" -#: ../../library/stdtypes.rst:2150 +#: ../../library/stdtypes.rst:2184 msgid "``\\r\\n``" msgstr "``\\r\\n``" -#: ../../library/stdtypes.rst:2150 +#: ../../library/stdtypes.rst:2184 msgid "Carriage Return + Line Feed" msgstr "Retorno do Carro + Feed da Linha" -#: ../../library/stdtypes.rst:2152 +#: ../../library/stdtypes.rst:2186 msgid "``\\v`` or ``\\x0b``" msgstr "``\\v`` ou ``\\x0b``" -#: ../../library/stdtypes.rst:2152 +#: ../../library/stdtypes.rst:2186 msgid "Line Tabulation" msgstr "Tabulação de Linha" -#: ../../library/stdtypes.rst:2154 +#: ../../library/stdtypes.rst:2188 msgid "``\\f`` or ``\\x0c``" msgstr "``\\f`` ou ``\\x0c``" -#: ../../library/stdtypes.rst:2154 +#: ../../library/stdtypes.rst:2188 msgid "Form Feed" msgstr "Formulário de Feed" -#: ../../library/stdtypes.rst:2156 +#: ../../library/stdtypes.rst:2190 msgid "``\\x1c``" msgstr "``\\x1c``" -#: ../../library/stdtypes.rst:2156 +#: ../../library/stdtypes.rst:2190 msgid "File Separator" msgstr "Separador de Arquivos" -#: ../../library/stdtypes.rst:2158 +#: ../../library/stdtypes.rst:2192 msgid "``\\x1d``" msgstr "``\\x1d``" -#: ../../library/stdtypes.rst:2158 +#: ../../library/stdtypes.rst:2192 msgid "Group Separator" msgstr "Separador de Grupo" -#: ../../library/stdtypes.rst:2160 +#: ../../library/stdtypes.rst:2194 msgid "``\\x1e``" msgstr "``\\x1e``" -#: ../../library/stdtypes.rst:2160 +#: ../../library/stdtypes.rst:2194 msgid "Record Separator" msgstr "Separador de Registro" -#: ../../library/stdtypes.rst:2162 +#: ../../library/stdtypes.rst:2196 msgid "``\\x85``" msgstr "``\\x85``" -#: ../../library/stdtypes.rst:2162 +#: ../../library/stdtypes.rst:2196 msgid "Next Line (C1 Control Code)" msgstr "Próxima Linha (C1 Control Code)" -#: ../../library/stdtypes.rst:2164 +#: ../../library/stdtypes.rst:2198 msgid "``\\u2028``" msgstr "``\\u2028``" -#: ../../library/stdtypes.rst:2164 +#: ../../library/stdtypes.rst:2198 msgid "Line Separator" msgstr "Separador de Linha" -#: ../../library/stdtypes.rst:2166 +#: ../../library/stdtypes.rst:2200 msgid "``\\u2029``" msgstr "``\\u2029``" -#: ../../library/stdtypes.rst:2166 +#: ../../library/stdtypes.rst:2200 msgid "Paragraph Separator" msgstr "Separador de Parágrafo" -#: ../../library/stdtypes.rst:2171 +#: ../../library/stdtypes.rst:2205 msgid "``\\v`` and ``\\f`` added to list of line boundaries." msgstr "``\\v`` e ``\\f`` adicionado à lista de limites de linha." -#: ../../library/stdtypes.rst:2180 +#: ../../library/stdtypes.rst:2209 +msgid "" +">>> 'ab c\\n\\nde fg\\rkl\\r\\n'.splitlines()\n" +"['ab c', '', 'de fg', 'kl']\n" +">>> 'ab c\\n\\nde fg\\rkl\\r\\n'.splitlines(keepends=True)\n" +"['ab c\\n', '\\n', 'de fg\\r', 'kl\\r\\n']" +msgstr "" +">>> 'ab c\\n\\nde fg\\rkl\\r\\n'.splitlines()\n" +"['ab c', '', 'de fg', 'kl']\n" +">>> 'ab c\\n\\nde fg\\rkl\\r\\n'.splitlines(keepends=True)\n" +"['ab c\\n', '\\n', 'de fg\\r', 'kl\\r\\n']" + +#: ../../library/stdtypes.rst:2214 msgid "" "Unlike :meth:`~str.split` when a delimiter string *sep* is given, this " "method returns an empty list for the empty string, and a terminal line break " @@ -3588,11 +4117,35 @@ msgstr "" "*sep* é fornecido, este método retorna uma lista vazia para a uma String " "vazia e uma quebra de linha de terminal não resulta numa linha extra::" -#: ../../library/stdtypes.rst:2189 +#: ../../library/stdtypes.rst:2218 +msgid "" +">>> \"\".splitlines()\n" +"[]\n" +">>> \"One line\\n\".splitlines()\n" +"['One line']" +msgstr "" +">>> \"\".splitlines()\n" +"[]\n" +">>> \"Uma linha\\n\".splitlines()\n" +"['Uma linha']" + +#: ../../library/stdtypes.rst:2223 msgid "For comparison, ``split('\\n')`` gives::" msgstr "Para comparação, temos ``split('\\n')``::" -#: ../../library/stdtypes.rst:2199 +#: ../../library/stdtypes.rst:2225 +msgid "" +">>> ''.split('\\n')\n" +"['']\n" +">>> 'Two lines\\n'.split('\\n')\n" +"['Two lines', '']" +msgstr "" +">>> ''.split('\\n')\n" +"['']\n" +">>> 'Duas linhas\\n'.split('\\n')\n" +"['Duas linhas', '']" + +#: ../../library/stdtypes.rst:2233 msgid "" "Return ``True`` if string starts with the *prefix*, otherwise return " "``False``. *prefix* can also be a tuple of prefixes to look for. With " @@ -3604,7 +4157,7 @@ msgstr "" "procurados. Com *start* opcional, a String de teste começa nessa posição. " "Com *fim* opcional, interrompe a comparação de String nessa posição." -#: ../../library/stdtypes.rst:2207 +#: ../../library/stdtypes.rst:2241 msgid "" "Return a copy of the string with the leading and trailing characters " "removed. The *chars* argument is a string specifying the set of characters " @@ -3619,7 +4172,19 @@ msgstr "" "prefixo, nem um sufixo; ao contrário disso, todas as combinações dos seus " "seus valores são removidas::" -#: ../../library/stdtypes.rst:2218 +#: ../../library/stdtypes.rst:2247 +msgid "" +">>> ' spacious '.strip()\n" +"'spacious'\n" +">>> 'www.example.com'.strip('cmowz.')\n" +"'example'" +msgstr "" +">>> ' spacious '.strip()\n" +"'spacious'\n" +">>> 'www.example.com'.strip('cmowz.')\n" +"'example'" + +#: ../../library/stdtypes.rst:2252 msgid "" "The outermost leading and trailing *chars* argument values are stripped from " "the string. Characters are removed from the leading end until reaching a " @@ -3631,7 +4196,17 @@ msgstr "" "caractere da string que não está contido no conjunto de caracteres em " "*chars*. Uma ação similar acontece no extremo final da string. Por exemplo::" -#: ../../library/stdtypes.rst:2231 +#: ../../library/stdtypes.rst:2258 +msgid "" +">>> comment_string = '#....... Section 3.2.1 Issue #32 .......'\n" +">>> comment_string.strip('.#! ')\n" +"'Section 3.2.1 Issue #32'" +msgstr "" +">>> comment_string = '#....... Section 3.2.1 Issue #32 .......'\n" +">>> comment_string.strip('.#! ')\n" +"'Section 3.2.1 Issue #32'" + +#: ../../library/stdtypes.rst:2265 msgid "" "Return a copy of the string with uppercase characters converted to lowercase " "and vice versa. Note that it is not necessarily true that ``s.swapcase()." @@ -3641,7 +4216,7 @@ msgstr "" "minúsculos e vice-versa. Perceba que não é necessariamente verdade que ``s." "swapcase().swapcase() == s``." -#: ../../library/stdtypes.rst:2238 +#: ../../library/stdtypes.rst:2272 msgid "" "Return a titlecased version of the string where words start with an " "uppercase character and the remaining characters are lowercase." @@ -3650,7 +4225,15 @@ msgstr "" "caractere com letra maiúscula e os caracteres restantes são em letras " "minúsculas." -#: ../../library/stdtypes.rst:2246 ../../library/stdtypes.rst:3472 +#: ../../library/stdtypes.rst:2277 +msgid "" +">>> 'Hello world'.title()\n" +"'Hello World'" +msgstr "" +">>> 'Olá mundo'.title()\n" +"'Olá mundo'" + +#: ../../library/stdtypes.rst:2280 ../../library/stdtypes.rst:3646 msgid "" "The algorithm uses a simple language-independent definition of a word as " "groups of consecutive letters. The definition works in many contexts but it " @@ -3659,10 +4242,18 @@ msgid "" msgstr "" "O algoritmo usa uma definição simples independente de idioma para uma " "palavra, como grupos de letras consecutivas. A definição funciona em muitos " -"contextos, mas isso significa que apóstrofes em contradições e possessivos " +"contextos, mas isso significa que apóstrofes em contrações e possessivos " "formam limites de palavras, os quais podem não ser o resultado desejado::" -#: ../../library/stdtypes.rst:2254 +#: ../../library/stdtypes.rst:2285 +msgid "" +">>> \"they're bill's friends from the UK\".title()\n" +"\"They'Re Bill'S Friends From The Uk\"" +msgstr "" +">>> \"a caixa d'água do joe's bar está vazia\".title()\n" +"\"A Caixa D'Água Do Joe'S Bar Está Vazia\"" + +#: ../../library/stdtypes.rst:2288 msgid "" "The :func:`string.capwords` function does not have this problem, as it " "splits words on spaces only." @@ -3670,7 +4261,7 @@ msgstr "" "A função :func:`string.capwords` não tem esse problema, pois ela divide " "palavras apenas em espaços." -#: ../../library/stdtypes.rst:2257 +#: ../../library/stdtypes.rst:2291 msgid "" "Alternatively, a workaround for apostrophes can be constructed using regular " "expressions::" @@ -3678,7 +4269,27 @@ msgstr "" "Alternativamente, uma solução alternativa para os apóstrofes pode ser " "construída usando expressões regulares::" -#: ../../library/stdtypes.rst:2272 +#: ../../library/stdtypes.rst:2294 +msgid "" +">>> import re\n" +">>> def titlecase(s):\n" +"... return re.sub(r\"[A-Za-z]+('[A-Za-z]+)?\",\n" +"... lambda mo: mo.group(0).capitalize(),\n" +"... s)\n" +"...\n" +">>> titlecase(\"they're bill's friends.\")\n" +"\"They're Bill's Friends.\"" +msgstr "" +">>> import re\n" +">>> def titlecase(s):\n" +"... return re.sub(r\"[A-Za-z]+('[A-Za-z]+)?\",\n" +"... lambda mo: mo.group(0).capitalize(),\n" +"... s)\n" +"...\n" +">>> titlecase(\"o joe's bar está aberto\")\n" +"\"O Joe's Bar Está Aberto\"" + +#: ../../library/stdtypes.rst:2306 msgid "" "Return a copy of the string in which each character has been mapped through " "the given translation table. The table must be an object that implements " @@ -3699,7 +4310,7 @@ msgstr "" "caractere da string de retorno; ou levantar uma exceção :exc:`LookupError`, " "para mapear o caractere para si mesmo." -#: ../../library/stdtypes.rst:2281 +#: ../../library/stdtypes.rst:2315 msgid "" "You can use :meth:`str.maketrans` to create a translation map from character-" "to-character mappings in different formats." @@ -3707,7 +4318,7 @@ msgstr "" "Você pode usar :meth:`str.maketrans` para criar um mapa de tradução com " "mapeamentos caractere para caractere em diferentes formatos." -#: ../../library/stdtypes.rst:2284 +#: ../../library/stdtypes.rst:2318 msgid "" "See also the :mod:`codecs` module for a more flexible approach to custom " "character mappings." @@ -3715,7 +4326,7 @@ msgstr "" "Veja também o módulo :mod:`codecs` para uma abordagem mais flexível para " "mapeamento de caractere customizado." -#: ../../library/stdtypes.rst:2290 +#: ../../library/stdtypes.rst:2324 msgid "" "Return a copy of the string with all the cased characters [4]_ converted to " "uppercase. Note that ``s.upper().isupper()`` might be ``False`` if ``s`` " @@ -3730,7 +4341,7 @@ msgstr "" "resultante(s) não for \"Lu\" (Letra maiúscula), mas por ex \"Lt\" (Letra em " "titlecase)." -#: ../../library/stdtypes.rst:2296 +#: ../../library/stdtypes.rst:2330 msgid "" "The uppercasing algorithm used is `described in section 3.13 'Default Case " "Folding' of the Unicode Standard `__." -#: ../../library/stdtypes.rst:2303 +#: ../../library/stdtypes.rst:2337 msgid "" "Return a copy of the string left filled with ASCII ``'0'`` digits to make a " "string of length *width*. A leading sign prefix (``'+'``/``'-'``) is handled " @@ -3753,11 +4364,279 @@ msgstr "" "caractere de sinal em vez de antes. A String original será retornada se o " "*width* for menor ou igual a ``len(s)``." -#: ../../library/stdtypes.rst:2321 +#: ../../library/stdtypes.rst:2345 +msgid "" +">>> \"42\".zfill(5)\n" +"'00042'\n" +">>> \"-42\".zfill(5)\n" +"'-0042'" +msgstr "" +">>> \"42\".zfill(5)\n" +"'00042'\n" +">>> \"-42\".zfill(5)\n" +"'-0042'" + +#: ../../library/stdtypes.rst:2366 +msgid "Formatted String Literals (f-strings)" +msgstr "Strings literais formatadas (f-strings)" + +#: ../../library/stdtypes.rst:2369 +msgid "" +"The :keyword:`await` and :keyword:`async for` can be used in expressions " +"within f-strings." +msgstr "" +":keyword:`await` e :keyword:`async for` podem ser usados ​​em expressões " +"dentro de f-strings." + +#: ../../library/stdtypes.rst:2372 +msgid "Added the debugging operator (``=``)" +msgstr "Adicionado o operador de depuração (``=``)" + +#: ../../library/stdtypes.rst:2374 +msgid "" +"Many restrictions on expressions within f-strings have been removed. " +"Notably, nested strings, comments, and backslashes are now permitted." +msgstr "" +"Muitas restrições a expressões dentro de f-strings foram removidas. " +"Notavelmente, strings aninhadas, comentários e contrabarras agora são " +"permitidos." + +#: ../../library/stdtypes.rst:2378 +msgid "" +"An :dfn:`f-string` (formally a :dfn:`formatted string literal`) is a string " +"literal that is prefixed with ``f`` or ``F``. This type of string literal " +"allows embedding arbitrary Python expressions within *replacement fields*, " +"which are delimited by curly brackets (``{}``). These expressions are " +"evaluated at runtime, similarly to :meth:`str.format`, and are converted " +"into regular :class:`str` objects. For example:" +msgstr "" +"Uma :dfn:`f-string` (formalmente uma :dfn:`literal de string formatada`) é " +"uma literal de string prefixada com ``f`` ou ``F``. Esse tipo de literal de " +"string permite incorporar expressões Python arbitrárias dentro de *campos de " +"substituição*, delimitados por chaves (``{}``). Essas expressões são " +"avaliadas em tempo de execução, de forma semelhante a :meth:`str.format`, e " +"convertidas em objetos :class:`str` regulares. Por exemplo:" + +#: ../../library/stdtypes.rst:2386 +msgid "" +">>> who = 'nobody'\n" +">>> nationality = 'Spanish'\n" +">>> f'{who.title()} expects the {nationality} Inquisition!'\n" +"'Nobody expects the Spanish Inquisition!'" +msgstr "" +">>> who = 'Ninguém'\n" +">>> nationality = 'Espanhola'\n" +">>> f'{who.title()} está à espera da Inquisição {nationality}!'\n" +"'Ninguém está à espera da Inquisição Espanhola!'" + +#: ../../library/stdtypes.rst:2393 +msgid "It is also possible to use a multi line f-string:" +msgstr "Também é possível usar uma f-string de várias linhas:" + +#: ../../library/stdtypes.rst:2395 +msgid "" +">>> f'''This is a string\n" +"... on two lines'''\n" +"'This is a string\\non two lines'" +msgstr "" +">>> f'''Esta é uma string\n" +"... em duas linhas'''\n" +"'Esta é uma string\\nem duas linhas'" + +#: ../../library/stdtypes.rst:2401 +msgid "" +"A single opening curly bracket, ``'{'``, marks a *replacement field* that " +"can contain any Python expression:" +msgstr "" +"Uma única chave de abertura, ``'{'``, marca um *campo de substituição* que " +"pode conter qualquer expressão Python:" + +#: ../../library/stdtypes.rst:2404 +msgid "" +">>> nationality = 'Spanish'\n" +">>> f'The {nationality} Inquisition!'\n" +"'The Spanish Inquisition!'" +msgstr "" +">>> nationality = 'Espanhola'\n" +">>> f'A Inquisição {nationality}!'\n" +"'A Inquisição Espanhola!'" + +#: ../../library/stdtypes.rst:2410 +msgid "To include a literal ``{`` or ``}``, use a double bracket:" +msgstr "Para incluir um literal ``{`` ou ``}``, use chaves duplas:" + +#: ../../library/stdtypes.rst:2412 +msgid "" +">>> x = 42\n" +">>> f'{{x}} is {x}'\n" +"'{x} is 42'" +msgstr "" +">>> x = 42\n" +">>> f'{{x}} is {x}'\n" +"'{x} is 42'" + +#: ../../library/stdtypes.rst:2418 +msgid "" +"Functions can also be used, and :ref:`format specifiers `:" +msgstr "" +"Funções também podem ser usadas, como :ref:`especificadores de formato " +"`:" + +#: ../../library/stdtypes.rst:2420 +msgid "" +">>> from math import sqrt\n" +">>> f'√2 \\N{ALMOST EQUAL TO} {sqrt(2):.5f}'\n" +"'√2 ≈ 1.41421'" +msgstr "" +">>> from math import sqrt\n" +">>> f'√2 \\N{ALMOST EQUAL TO} {sqrt(2):.5f}'\n" +"'√2 ≈ 1.41421'" + +#: ../../library/stdtypes.rst:2426 +msgid "Any non-string expression is converted using :func:`str`, by default:" +msgstr "" +"Qualquer expressão que não seja string é convertida usando :func:`str`, por " +"padrão:" + +#: ../../library/stdtypes.rst:2428 +msgid "" +">>> from fractions import Fraction\n" +">>> f'{Fraction(1, 3)}'\n" +"'1/3'" +msgstr "" +">>> from fractions import Fraction\n" +">>> f'{Fraction(1, 3)}'\n" +"'1/3'" + +#: ../../library/stdtypes.rst:2434 +msgid "" +"To use an explicit conversion, use the ``!`` (exclamation mark) operator, " +"followed by any of the valid formats, which are:" +msgstr "" +"Para usar uma conversão explícita, use o operador ``!`` (ponto de " +"exclamação), seguido por qualquer um dos formatos válidos, que são:" + +#: ../../library/stdtypes.rst:2438 ../../library/stdtypes.rst:2606 +#: ../../library/stdtypes.rst:3825 +msgid "Conversion" +msgstr "Conversão" + +#: ../../library/stdtypes.rst:2440 +msgid "``!a``" +msgstr "``!a``" + +#: ../../library/stdtypes.rst:2440 +msgid ":func:`ascii`" +msgstr ":func:`ascii`" + +#: ../../library/stdtypes.rst:2441 +msgid "``!r``" +msgstr "``!r``" + +#: ../../library/stdtypes.rst:2441 +msgid ":func:`repr`" +msgstr ":func:`repr`" + +#: ../../library/stdtypes.rst:2442 +msgid "``!s``" +msgstr "``!s``" + +#: ../../library/stdtypes.rst:2442 +msgid ":func:`str`" +msgstr ":func:`str`" + +#: ../../library/stdtypes.rst:2445 +msgid "For example:" +msgstr "Por exemplo:" + +#: ../../library/stdtypes.rst:2447 +msgid "" +">>> from fractions import Fraction\n" +">>> f'{Fraction(1, 3)!s}'\n" +"'1/3'\n" +">>> f'{Fraction(1, 3)!r}'\n" +"'Fraction(1, 3)'\n" +">>> question = '¿Dónde está el Presidente?'\n" +">>> print(f'{question!a}')\n" +"'\\xbfD\\xf3nde est\\xe1 el Presidente?'" +msgstr "" +">>> from fractions import Fraction\n" +">>> f'{Fraction(1, 3)!s}'\n" +"'1/3'\n" +">>> f'{Fraction(1, 3)!r}'\n" +"'Fraction(1, 3)'\n" +">>> question = '¿Dónde está el Presidente?'\n" +">>> print(f'{question!a}')\n" +"'\\xbfD\\xf3nde est\\xe1 el Presidente?'" + +#: ../../library/stdtypes.rst:2458 +msgid "" +"While debugging it may be helpful to see both the expression and its value, " +"by using the equals sign (``=``) after the expression. This preserves spaces " +"within the brackets, and can be used with a converter. By default, the " +"debugging operator uses the :func:`repr` (``!r``) conversion. For example:" +msgstr "" +"Durante a depuração, pode ser útil visualizar tanto a expressão quanto seu " +"valor, usando o sinal de igual (``=``) após a expressão. Isso preserva os " +"espaços entre chaves e pode ser usado com um conversor. Por padrão, o " +"operador de depuração usa a conversão :func:`repr` (``!r``). Por exemplo:" + +#: ../../library/stdtypes.rst:2464 +msgid "" +">>> from fractions import Fraction\n" +">>> calculation = Fraction(1, 3)\n" +">>> f'{calculation=}'\n" +"'calculation=Fraction(1, 3)'\n" +">>> f'{calculation = }'\n" +"'calculation = Fraction(1, 3)'\n" +">>> f'{calculation = !s}'\n" +"'calculation = 1/3'" +msgstr "" +">>> from fractions import Fraction\n" +">>> calculation = Fraction(1, 3)\n" +">>> f'{calculation=}'\n" +"'calculation=Fraction(1, 3)'\n" +">>> f'{calculation = }'\n" +"'calculation = Fraction(1, 3)'\n" +">>> f'{calculation = !s}'\n" +"'calculation = 1/3'" + +#: ../../library/stdtypes.rst:2475 +msgid "" +"Once the output has been evaluated, it can be formatted using a :ref:`format " +"specifier ` following a colon (``':'``). After the expression " +"has been evaluated, and possibly converted to a string, the :meth:`!" +"__format__` method of the result is called with the format specifier, or the " +"empty string if no format specifier is given. The formatted result is then " +"used as the final value for the replacement field. For example:" +msgstr "" +"Após a avaliação da saída, ela pode ser formatada usando um :ref:" +"`especificador de formato ` seguido de dois pontos (``':'``). " +"Após a avaliação da expressão e sua possível conversão para uma string, o " +"método :meth:`!__format__` do resultado é chamado com o especificador de " +"formato, ou a string vazia, caso nenhum especificador de formato seja " +"fornecido. O resultado formatado é então usado como o valor final para o " +"campo de substituição. Por exemplo:" + +#: ../../library/stdtypes.rst:2483 +msgid "" +">>> from fractions import Fraction\n" +">>> f'{Fraction(1, 7):.6f}'\n" +"'0.142857'\n" +">>> f'{Fraction(1, 7):_^+10}'\n" +"'___+1/7___'" +msgstr "" +">>> from fractions import Fraction\n" +">>> f'{Fraction(1, 7):.6f}'\n" +"'0.142857'\n" +">>> f'{Fraction(1, 7):_^+10}'\n" +"'___+1/7___'" + +#: ../../library/stdtypes.rst:2495 msgid "``printf``-style String Formatting" -msgstr "Formatação de String no Formato no estilo ``printf``" +msgstr "Formatação de string no estilo ``printf``" -#: ../../library/stdtypes.rst:2334 +#: ../../library/stdtypes.rst:2508 msgid "" "The formatting operations described here exhibit a variety of quirks that " "lead to a number of common errors (such as failing to display tuples and " @@ -3775,7 +4654,7 @@ msgstr "" "erros. Cada uma dessas alternativas fornece seus próprios custos e " "benefícios de simplicidade, flexibilidade, e/ou extensibilidade." -#: ../../library/stdtypes.rst:2342 +#: ../../library/stdtypes.rst:2516 msgid "" "String objects have one unique built-in operation: the ``%`` operator " "(modulo). This is also known as the string *formatting* or *interpolation* " @@ -3791,7 +4670,15 @@ msgstr "" "mais elementos de *values*. O efeito é semelhante ao uso da função :c:func:" "`sprintf` na linguagem C. Por exemplo:" -#: ../../library/stdtypes.rst:2354 +#: ../../library/stdtypes.rst:2523 +msgid "" +">>> print('%s has %d quote types.' % ('Python', 2))\n" +"Python has 2 quote types." +msgstr "" +">>> print('%s tem %d tipos de aspas.' % ('Python', 2))\n" +"Python tem 2 tipos de aspas." + +#: ../../library/stdtypes.rst:2528 msgid "" "If *format* requires a single argument, *values* may be a single non-tuple " "object. [5]_ Otherwise, *values* must be a tuple with exactly the number of " @@ -3804,7 +4691,7 @@ msgstr "" "string de formatação, ou um único mapa de objetos (por exemplo, um " "dicionário)." -#: ../../library/stdtypes.rst:2364 ../../library/stdtypes.rst:3583 +#: ../../library/stdtypes.rst:2538 ../../library/stdtypes.rst:3757 msgid "" "A conversion specifier contains two or more characters and has the following " "components, which must occur in this order:" @@ -3812,19 +4699,19 @@ msgstr "" "Um especificador de conversão contém dois ou mais caracteres e tem os " "seguintes componentes, que devem aparecer nesta ordem:" -#: ../../library/stdtypes.rst:2367 ../../library/stdtypes.rst:3586 +#: ../../library/stdtypes.rst:2541 ../../library/stdtypes.rst:3760 msgid "The ``'%'`` character, which marks the start of the specifier." msgstr "O caractere ``'%'``, que determina o início do especificador." -#: ../../library/stdtypes.rst:2369 ../../library/stdtypes.rst:3588 +#: ../../library/stdtypes.rst:2543 ../../library/stdtypes.rst:3762 msgid "" "Mapping key (optional), consisting of a parenthesised sequence of characters " "(for example, ``(somename)``)." msgstr "" -"Mapeamento de Chaves (opcional), consistindo de uma sequência entre " +"Mapeamento de chaves (opcional), consistindo de uma sequência entre " "parênteses de caracteres (por exemplo, ``(algumnome)``)." -#: ../../library/stdtypes.rst:2372 ../../library/stdtypes.rst:3591 +#: ../../library/stdtypes.rst:2546 ../../library/stdtypes.rst:3765 msgid "" "Conversion flags (optional), which affect the result of some conversion " "types." @@ -3832,18 +4719,18 @@ msgstr "" "Flags de conversão (opcional), que afetam o resultado de alguns tipos de " "conversão." -#: ../../library/stdtypes.rst:2375 ../../library/stdtypes.rst:3594 +#: ../../library/stdtypes.rst:2549 ../../library/stdtypes.rst:3768 msgid "" "Minimum field width (optional). If specified as an ``'*'`` (asterisk), the " "actual width is read from the next element of the tuple in *values*, and the " "object to convert comes after the minimum field width and optional precision." msgstr "" -"Largura mínima do Campo(opcional). Se for especificado por ``'*'`` " +"Largura mínima do campo (opcional). Se for especificado como um ``'*'`` " "(asterisco), a largura real será lida a partir do próximo elemento da tupla " "em *values* e o objeto a converter virá após a largura mínima do campo e a " "precisão que é opcional." -#: ../../library/stdtypes.rst:2379 ../../library/stdtypes.rst:3598 +#: ../../library/stdtypes.rst:2553 ../../library/stdtypes.rst:3772 msgid "" "Precision (optional), given as a ``'.'`` (dot) followed by the precision. " "If specified as ``'*'`` (an asterisk), the actual precision is read from the " @@ -3855,15 +4742,15 @@ msgstr "" "será lida a partir do próximo elemento da tupla em *values*, e o valor a " "converter virá após a precisão." -#: ../../library/stdtypes.rst:2384 ../../library/stdtypes.rst:3603 +#: ../../library/stdtypes.rst:2558 ../../library/stdtypes.rst:3777 msgid "Length modifier (optional)." -msgstr "Modificador de Comprimento(opcional)." +msgstr "Modificador de comprimento (opcional)." -#: ../../library/stdtypes.rst:2386 ../../library/stdtypes.rst:3605 +#: ../../library/stdtypes.rst:2560 ../../library/stdtypes.rst:3779 msgid "Conversion type." -msgstr "Tipos de Conversão" +msgstr "Tipos de conversão." -#: ../../library/stdtypes.rst:2388 +#: ../../library/stdtypes.rst:2562 msgid "" "When the right argument is a dictionary (or other mapping type), then the " "formats in the string *must* include a parenthesised mapping key into that " @@ -3876,7 +4763,7 @@ msgstr "" "A key de mapeamento seleciona o valor a ser formatado a partir do " "mapeamento. Por exemplo:" -#: ../../library/stdtypes.rst:2397 ../../library/stdtypes.rst:3616 +#: ../../library/stdtypes.rst:2571 ../../library/stdtypes.rst:3790 msgid "" "In this case no ``*`` specifiers may occur in a format (since they require a " "sequential parameter list)." @@ -3884,38 +4771,38 @@ msgstr "" "Nesse caso, nenhum especificador ``*`` poderá ocorrer num formato (uma vez " "que eles exigem uma lista de parâmetros sequenciais)." -#: ../../library/stdtypes.rst:2400 ../../library/stdtypes.rst:3619 +#: ../../library/stdtypes.rst:2574 ../../library/stdtypes.rst:3793 msgid "The conversion flag characters are:" msgstr "Os caracteres flags de conversão são:" -#: ../../library/stdtypes.rst:2409 ../../library/stdtypes.rst:3628 +#: ../../library/stdtypes.rst:2583 ../../library/stdtypes.rst:3802 msgid "Flag" msgstr "Sinalizador" -#: ../../library/stdtypes.rst:2411 ../../library/stdtypes.rst:3630 +#: ../../library/stdtypes.rst:2585 ../../library/stdtypes.rst:3804 msgid "``'#'``" msgstr "``'#'``" -#: ../../library/stdtypes.rst:2411 ../../library/stdtypes.rst:3630 +#: ../../library/stdtypes.rst:2585 ../../library/stdtypes.rst:3804 msgid "" "The value conversion will use the \"alternate form\" (where defined below)." msgstr "" -"A conversão de valor usará o \"formulário alternativo\" (em que definimos " +"A conversão de valor usará o \"formulário alternativo\" (conforme definido " "abaixo)." -#: ../../library/stdtypes.rst:2414 ../../library/stdtypes.rst:3633 +#: ../../library/stdtypes.rst:2588 ../../library/stdtypes.rst:3807 msgid "``'0'``" msgstr "``'0'``" -#: ../../library/stdtypes.rst:2414 ../../library/stdtypes.rst:3633 +#: ../../library/stdtypes.rst:2588 ../../library/stdtypes.rst:3807 msgid "The conversion will be zero padded for numeric values." msgstr "A conversão será preenchida por zeros para valores numéricos." -#: ../../library/stdtypes.rst:2416 ../../library/stdtypes.rst:3635 +#: ../../library/stdtypes.rst:2590 ../../library/stdtypes.rst:3809 msgid "``'-'``" msgstr "``'-'``" -#: ../../library/stdtypes.rst:2416 ../../library/stdtypes.rst:3635 +#: ../../library/stdtypes.rst:2590 ../../library/stdtypes.rst:3809 msgid "" "The converted value is left adjusted (overrides the ``'0'`` conversion if " "both are given)." @@ -3923,190 +4810,187 @@ msgstr "" "O valor convertido será ajustado à esquerda (substitui a conversão ``'0'`` " "se ambos forem fornecidos)." -#: ../../library/stdtypes.rst:2419 ../../library/stdtypes.rst:3638 +#: ../../library/stdtypes.rst:2593 ../../library/stdtypes.rst:3812 msgid "``' '``" msgstr "``' '``" -#: ../../library/stdtypes.rst:2419 ../../library/stdtypes.rst:3638 +#: ../../library/stdtypes.rst:2593 ../../library/stdtypes.rst:3812 msgid "" "(a space) A blank should be left before a positive number (or empty string) " "produced by a signed conversion." msgstr "" "(um espaço) Um espaço em branco deverá ser deixado antes de um número " -"positivo (ou uma String vazia) produzido por uma conversão assinada." +"positivo (ou uma string vazia) produzido por uma conversão assinada." -#: ../../library/stdtypes.rst:2422 ../../library/stdtypes.rst:3641 +#: ../../library/stdtypes.rst:2596 ../../library/stdtypes.rst:3815 msgid "``'+'``" msgstr "``'+'``" -#: ../../library/stdtypes.rst:2422 ../../library/stdtypes.rst:3641 +#: ../../library/stdtypes.rst:2596 ../../library/stdtypes.rst:3815 msgid "" "A sign character (``'+'`` or ``'-'``) will precede the conversion (overrides " "a \"space\" flag)." msgstr "" -"Um sinal de caractere (``'+'`` ou ``'-'``) precedera a conversão " -"(substituindo o sinalizador \"space\")." +"Um sinal de caractere (``'+'`` ou ``'-'``) precederá a conversão " +"(substituindo o sinalizador de \"espaço\")." -#: ../../library/stdtypes.rst:2426 ../../library/stdtypes.rst:3645 +#: ../../library/stdtypes.rst:2600 ../../library/stdtypes.rst:3819 msgid "" "A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as " "it is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``." msgstr "" "Um modificador de comprimento (``h``, ``l``, ou ``L``) pode estar presente, " -"mas será ignorado, pois o mesmo não é necessário para o Python -- então por " -"exemplo ``%ld`` é idêntico a ``%d``." +"mas será ignorado, pois o mesmo não é necessário para o Python -- então, por " +"exemplo, ``%ld`` é idêntico a ``%d``." -#: ../../library/stdtypes.rst:2429 ../../library/stdtypes.rst:3648 +#: ../../library/stdtypes.rst:2603 ../../library/stdtypes.rst:3822 msgid "The conversion types are:" msgstr "Os tipos de conversão são:" -#: ../../library/stdtypes.rst:2432 ../../library/stdtypes.rst:3651 -msgid "Conversion" -msgstr "Conversão" - -#: ../../library/stdtypes.rst:2434 ../../library/stdtypes.rst:3653 +#: ../../library/stdtypes.rst:2608 ../../library/stdtypes.rst:3827 msgid "``'d'``" msgstr "``'d'``" -#: ../../library/stdtypes.rst:2434 ../../library/stdtypes.rst:2436 -#: ../../library/stdtypes.rst:3653 ../../library/stdtypes.rst:3655 +#: ../../library/stdtypes.rst:2608 ../../library/stdtypes.rst:2610 +#: ../../library/stdtypes.rst:3827 ../../library/stdtypes.rst:3829 msgid "Signed integer decimal." msgstr "Número decimal inteiro sinalizador." -#: ../../library/stdtypes.rst:2436 ../../library/stdtypes.rst:3655 +#: ../../library/stdtypes.rst:2610 ../../library/stdtypes.rst:3829 msgid "``'i'``" msgstr "``'i'``" -#: ../../library/stdtypes.rst:2438 ../../library/stdtypes.rst:3657 +#: ../../library/stdtypes.rst:2612 ../../library/stdtypes.rst:3831 msgid "``'o'``" msgstr "``'o'``" -#: ../../library/stdtypes.rst:2438 ../../library/stdtypes.rst:3657 +#: ../../library/stdtypes.rst:2612 ../../library/stdtypes.rst:3831 msgid "Signed octal value." msgstr "Valor octal sinalizador." -#: ../../library/stdtypes.rst:2440 ../../library/stdtypes.rst:3659 +#: ../../library/stdtypes.rst:2614 ../../library/stdtypes.rst:3833 msgid "``'u'``" msgstr "``'u'``" -#: ../../library/stdtypes.rst:2440 ../../library/stdtypes.rst:3659 +#: ../../library/stdtypes.rst:2614 ../../library/stdtypes.rst:3833 msgid "Obsolete type -- it is identical to ``'d'``." msgstr "Tipo obsoleto -- é idêntico a ``'d'``." -#: ../../library/stdtypes.rst:2442 ../../library/stdtypes.rst:3661 +#: ../../library/stdtypes.rst:2616 ../../library/stdtypes.rst:3835 msgid "``'x'``" msgstr "``'x'``" -#: ../../library/stdtypes.rst:2442 ../../library/stdtypes.rst:3661 +#: ../../library/stdtypes.rst:2616 ../../library/stdtypes.rst:3835 msgid "Signed hexadecimal (lowercase)." -msgstr "Sinalizador hexadecimal (minúsculas)." +msgstr "Hexadecimal com sinal (minúsculo)." -#: ../../library/stdtypes.rst:2444 ../../library/stdtypes.rst:3663 +#: ../../library/stdtypes.rst:2618 ../../library/stdtypes.rst:3837 msgid "``'X'``" msgstr "``'X'``" -#: ../../library/stdtypes.rst:2444 ../../library/stdtypes.rst:3663 +#: ../../library/stdtypes.rst:2618 ../../library/stdtypes.rst:3837 msgid "Signed hexadecimal (uppercase)." -msgstr "Sinalizador hexadecimal (maiúscula)." +msgstr "Hexadecimal com sinal (maiúsculo)." -#: ../../library/stdtypes.rst:2446 ../../library/stdtypes.rst:3665 +#: ../../library/stdtypes.rst:2620 ../../library/stdtypes.rst:3839 msgid "``'e'``" msgstr "``'e'``" -#: ../../library/stdtypes.rst:2446 ../../library/stdtypes.rst:3665 +#: ../../library/stdtypes.rst:2620 ../../library/stdtypes.rst:3839 msgid "Floating-point exponential format (lowercase)." -msgstr "Formato exponencial de ponto flutuante (minúsculas)." +msgstr "Formato exponencial de ponto flutuante (minúsculo)." -#: ../../library/stdtypes.rst:2448 ../../library/stdtypes.rst:3667 +#: ../../library/stdtypes.rst:2622 ../../library/stdtypes.rst:3841 msgid "``'E'``" msgstr "``'E'``" -#: ../../library/stdtypes.rst:2448 ../../library/stdtypes.rst:3667 +#: ../../library/stdtypes.rst:2622 ../../library/stdtypes.rst:3841 msgid "Floating-point exponential format (uppercase)." -msgstr "Formato exponencial de ponto flutuante (maiúscula)." +msgstr "Formato exponencial de ponto flutuante (maiúscul)." -#: ../../library/stdtypes.rst:2450 ../../library/stdtypes.rst:3669 +#: ../../library/stdtypes.rst:2624 ../../library/stdtypes.rst:3843 msgid "``'f'``" msgstr "``'f'``" -#: ../../library/stdtypes.rst:2450 ../../library/stdtypes.rst:2452 -#: ../../library/stdtypes.rst:3669 ../../library/stdtypes.rst:3671 +#: ../../library/stdtypes.rst:2624 ../../library/stdtypes.rst:2626 +#: ../../library/stdtypes.rst:3843 ../../library/stdtypes.rst:3845 msgid "Floating-point decimal format." msgstr "Formato decimal de ponto flutuante." -#: ../../library/stdtypes.rst:2452 ../../library/stdtypes.rst:3671 +#: ../../library/stdtypes.rst:2626 ../../library/stdtypes.rst:3845 msgid "``'F'``" msgstr "``'F'``" -#: ../../library/stdtypes.rst:2454 ../../library/stdtypes.rst:3673 +#: ../../library/stdtypes.rst:2628 ../../library/stdtypes.rst:3847 msgid "``'g'``" msgstr "``'g'``" -#: ../../library/stdtypes.rst:2454 ../../library/stdtypes.rst:3673 +#: ../../library/stdtypes.rst:2628 ../../library/stdtypes.rst:3847 msgid "" "Floating-point format. Uses lowercase exponential format if exponent is less " "than -4 or not less than precision, decimal format otherwise." msgstr "" -"O formato de ponto flutuante. Usa o formato exponencial em minúsculas se o " +"O formato de ponto flutuante. Usa o formato exponencial em minúsculo se o " "expoente for inferior a -4 ou não inferior a precisão, formato decimal, caso " "contrário." -#: ../../library/stdtypes.rst:2458 ../../library/stdtypes.rst:3677 +#: ../../library/stdtypes.rst:2632 ../../library/stdtypes.rst:3851 msgid "``'G'``" msgstr "``'G'``" -#: ../../library/stdtypes.rst:2458 ../../library/stdtypes.rst:3677 +#: ../../library/stdtypes.rst:2632 ../../library/stdtypes.rst:3851 msgid "" "Floating-point format. Uses uppercase exponential format if exponent is less " "than -4 or not less than precision, decimal format otherwise." msgstr "" -"Formato de ponto flutuante. Usa o formato exponencial em maiúsculas se o " +"Formato de ponto flutuante. Usa o formato exponencial em maiúsculo se o " "expoente for inferior a -4 ou não inferior que a precisão, formato decimal, " "caso contrário." -#: ../../library/stdtypes.rst:2462 ../../library/stdtypes.rst:3681 +#: ../../library/stdtypes.rst:2636 ../../library/stdtypes.rst:3855 msgid "``'c'``" msgstr "``'c'``" -#: ../../library/stdtypes.rst:2462 +#: ../../library/stdtypes.rst:2636 msgid "Single character (accepts integer or single character string)." -msgstr "Caráter único (aceita inteiro ou um único caractere String)." +msgstr "Caractere único (aceita inteiro ou um único caractere string)." -#: ../../library/stdtypes.rst:2465 ../../library/stdtypes.rst:3694 +#: ../../library/stdtypes.rst:2639 ../../library/stdtypes.rst:3868 msgid "``'r'``" msgstr "``'r'``" -#: ../../library/stdtypes.rst:2465 +#: ../../library/stdtypes.rst:2639 msgid "String (converts any Python object using :func:`repr`)." msgstr "String (converte qualquer objeto Python usando a função :func:`repr`)." -#: ../../library/stdtypes.rst:2468 ../../library/stdtypes.rst:3688 +#: ../../library/stdtypes.rst:2642 ../../library/stdtypes.rst:3862 msgid "``'s'``" msgstr "``'s'``" -#: ../../library/stdtypes.rst:2468 +#: ../../library/stdtypes.rst:2642 msgid "String (converts any Python object using :func:`str`)." msgstr "String (converte qualquer objeto Python usando a função :func:`str`)." -#: ../../library/stdtypes.rst:2471 ../../library/stdtypes.rst:3691 +#: ../../library/stdtypes.rst:2645 ../../library/stdtypes.rst:3865 msgid "``'a'``" msgstr "``'a'``" -#: ../../library/stdtypes.rst:2471 +#: ../../library/stdtypes.rst:2645 msgid "String (converts any Python object using :func:`ascii`)." msgstr "" "String (converte qualquer objeto Python usando a função :func:`ascii`)." -#: ../../library/stdtypes.rst:2474 ../../library/stdtypes.rst:3697 +#: ../../library/stdtypes.rst:2648 ../../library/stdtypes.rst:3871 msgid "``'%'``" msgstr "``'%'``" -#: ../../library/stdtypes.rst:2474 ../../library/stdtypes.rst:3697 +#: ../../library/stdtypes.rst:2648 ../../library/stdtypes.rst:3871 msgid "No argument is converted, results in a ``'%'`` character in the result." msgstr "" -"Nenhum argumento é convertido, resultando um caractere ``''%'`` no resultado." +"Nenhum argumento é convertido, resultando em um caractere ``'%'`` no " +"resultado." -#: ../../library/stdtypes.rst:2481 ../../library/stdtypes.rst:3704 +#: ../../library/stdtypes.rst:2655 ../../library/stdtypes.rst:3878 msgid "" "The alternate form causes a leading octal specifier (``'0o'``) to be " "inserted before the first digit." @@ -4114,7 +4998,7 @@ msgstr "" "A forma alternativa faz com que um especificador octal principal (``'0o'``) " "seja inserido antes do primeiro dígito." -#: ../../library/stdtypes.rst:2485 ../../library/stdtypes.rst:3708 +#: ../../library/stdtypes.rst:2659 ../../library/stdtypes.rst:3882 msgid "" "The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on " "whether the ``'x'`` or ``'X'`` format was used) to be inserted before the " @@ -4124,7 +5008,7 @@ msgstr "" "formato ``'x'`` or ``'X'`` foi usado) para ser inserido antes do primeiro " "dígito." -#: ../../library/stdtypes.rst:2489 ../../library/stdtypes.rst:3712 +#: ../../library/stdtypes.rst:2663 ../../library/stdtypes.rst:3886 msgid "" "The alternate form causes the result to always contain a decimal point, even " "if no digits follow it." @@ -4132,14 +5016,14 @@ msgstr "" "A forma alternativa faz com que o resultado sempre contenha um ponto " "decimal, mesmo que nenhum dígito o siga." -#: ../../library/stdtypes.rst:2492 ../../library/stdtypes.rst:3715 +#: ../../library/stdtypes.rst:2666 ../../library/stdtypes.rst:3889 msgid "" "The precision determines the number of digits after the decimal point and " "defaults to 6." msgstr "" "A precisão determina o número de dígitos após o ponto decimal e o padrão é 6." -#: ../../library/stdtypes.rst:2496 ../../library/stdtypes.rst:3719 +#: ../../library/stdtypes.rst:2670 ../../library/stdtypes.rst:3893 msgid "" "The alternate form causes the result to always contain a decimal point, and " "trailing zeroes are not removed as they would otherwise be." @@ -4147,31 +5031,31 @@ msgstr "" "A forma alternativa faz com que o resultado sempre contenha um ponto decimal " "e os zeros à direita não sejam removidos, como de outra forma seriam." -#: ../../library/stdtypes.rst:2499 ../../library/stdtypes.rst:3722 +#: ../../library/stdtypes.rst:2673 ../../library/stdtypes.rst:3896 msgid "" "The precision determines the number of significant digits before and after " "the decimal point and defaults to 6." msgstr "" "A precisão determina o número de dígitos significativos antes e depois do " -"ponto decimal e o padrão é 6." +"ponto decimal e o padrão seja 6." -#: ../../library/stdtypes.rst:2503 ../../library/stdtypes.rst:3726 +#: ../../library/stdtypes.rst:2677 ../../library/stdtypes.rst:3900 msgid "If precision is ``N``, the output is truncated to ``N`` characters." -msgstr "Se a precisão for ``N``, a saída será truncada em caracteres ``N``." +msgstr "Se a precisão for ``N``, a saída será truncada em ``N`` caracteres." -#: ../../library/stdtypes.rst:2506 ../../library/stdtypes.rst:3735 +#: ../../library/stdtypes.rst:2680 ../../library/stdtypes.rst:3909 msgid "See :pep:`237`." msgstr "Veja :pep:`237`." -#: ../../library/stdtypes.rst:2508 +#: ../../library/stdtypes.rst:2682 msgid "" "Since Python strings have an explicit length, ``%s`` conversions do not " "assume that ``'\\0'`` is the end of the string." msgstr "" -"Como as Strings do Python possuem comprimento explícito, ``%s`` as " -"conversões não presumem que ``'\\0'`` é o fim da string." +"Como as strings no Python possuem comprimento explícito, conversões de " +"``%s`` não presumem que ``'\\0'`` seja o fim da string." -#: ../../library/stdtypes.rst:2513 +#: ../../library/stdtypes.rst:2687 msgid "" "``%f`` conversions for numbers whose absolute value is over 1e50 are no " "longer replaced by ``%g`` conversions." @@ -4179,15 +5063,15 @@ msgstr "" "``%f`` as conversões para números cujo valor absoluto é superior a 1e50 não " "são mais substituídas pela conversão ``%g``." -#: ../../library/stdtypes.rst:2524 +#: ../../library/stdtypes.rst:2698 msgid "" "Binary Sequence Types --- :class:`bytes`, :class:`bytearray`, :class:" "`memoryview`" msgstr "" -"Tipos de Sequência Binária --- :class:`bytes`, :class:`bytearray`, :class:" +"Tipos de sequência binária --- :class:`bytes`, :class:`bytearray`, :class:" "`memoryview`" -#: ../../library/stdtypes.rst:2532 +#: ../../library/stdtypes.rst:2706 msgid "" "The core built-in types for manipulating binary data are :class:`bytes` and :" "class:`bytearray`. They are supported by :class:`memoryview` which uses the :" @@ -4196,23 +5080,23 @@ msgid "" msgstr "" "Os principais tipos embutidos para manipular dados binários são :class:" "`bytes` e :class:`bytearray`. Eles são suportados por :class:`memoryview` a " -"qual usa o :ref:`buffer protocol ` para acessar a memória de " +"qual usa o :ref:`protocolo buffer ` para acessar a memória de " "outros objetos binários sem precisar fazer uma cópia." -#: ../../library/stdtypes.rst:2537 +#: ../../library/stdtypes.rst:2711 msgid "" "The :mod:`array` module supports efficient storage of basic data types like " "32-bit integers and IEEE754 double-precision floating values." msgstr "" -"O módulo :mod:`array` suporta armazenamento eficiente de tipos de dados " -"básicos como inteiros de 32 bits e valores de ponto-flutuante com precisão " -"dupla IEEE754." +"O módulo :mod:`array` provê suporte a um armazenamento eficiente de tipos de " +"dados básicos como inteiros de 32 bits e valores de ponto flutuante com " +"precisão dupla IEEE754." -#: ../../library/stdtypes.rst:2543 +#: ../../library/stdtypes.rst:2717 msgid "Bytes Objects" -msgstr "Objetos Bytes" +msgstr "Objetos bytes" -#: ../../library/stdtypes.rst:2547 +#: ../../library/stdtypes.rst:2721 msgid "" "Bytes objects are immutable sequences of single bytes. Since many major " "binary protocols are based on the ASCII text encoding, bytes objects offer " @@ -4225,40 +5109,40 @@ msgstr "" "trabalhamos com dados compatíveis com ASCII, e são proximamente relacionados " "com objetos string em uma variedade de outros sentidos." -#: ../../library/stdtypes.rst:2554 +#: ../../library/stdtypes.rst:2728 msgid "" "Firstly, the syntax for bytes literals is largely the same as that for " "string literals, except that a ``b`` prefix is added:" msgstr "" "Em primeiro lugar, a sintaxe para literais de bytes é em grande parte a " -"mesma para literais de String, exceto que um prefixo ``b`` é adicionado:" +"mesma para literais de string, exceto que um prefixo ``b`` é adicionado:" -#: ../../library/stdtypes.rst:2557 +#: ../../library/stdtypes.rst:2731 msgid "Single quotes: ``b'still allows embedded \"double\" quotes'``" -msgstr "Aspas simples: ``b'still allows embedded \"double\" quotes'``" +msgstr "Aspas simples: ``b'ainda permite aspas \"duplas\" dentro'``" -#: ../../library/stdtypes.rst:2558 +#: ../../library/stdtypes.rst:2732 msgid "Double quotes: ``b\"still allows embedded 'single' quotes\"``" -msgstr "Aspas duplas: ``b\"still allows embedded 'single' quotes\"``" +msgstr "Aspas duplas: ``b\"ainda permite aspas 'simples' dentro\"``" -#: ../../library/stdtypes.rst:2559 +#: ../../library/stdtypes.rst:2733 msgid "" "Triple quoted: ``b'''3 single quotes'''``, ``b\"\"\"3 double quotes\"\"\"``" msgstr "" -"Aspas triplas: ``b'''3 single quotes'''``, ``b\"\"\"3 double quotes\"\"\"``" +"Aspas triplas: ``b'''3 aspas simples'''``, ``b\"\"\"3 aspas duplas\"\"\"``" -#: ../../library/stdtypes.rst:2561 +#: ../../library/stdtypes.rst:2735 msgid "" "Only ASCII characters are permitted in bytes literals (regardless of the " "declared source code encoding). Any binary values over 127 must be entered " "into bytes literals using the appropriate escape sequence." msgstr "" "Apenas caracteres ASCII são permitidos em literais de bytes " -"(independentemente da codificação declarada). Qualquer valor binário " -"superior a 127 deverá ser inserido em literais de bytes usando a sequência " -"de escape apropriada." +"(independentemente da codificação declarada no código-fonte). Qualquer valor " +"binário superior a 127 deverá ser inserido em literais de bytes usando a " +"sequência de escape apropriada." -#: ../../library/stdtypes.rst:2565 +#: ../../library/stdtypes.rst:2739 msgid "" "As with string literals, bytes literals may also use a ``r`` prefix to " "disable processing of escape sequences. See :ref:`strings` for more about " @@ -4269,7 +5153,7 @@ msgstr "" "`strings` para mais sobre as várias formas de bytes literais, incluindo " "suporte a sequências de escape." -#: ../../library/stdtypes.rst:2569 +#: ../../library/stdtypes.rst:2743 msgid "" "While bytes literals and representations are based on ASCII text, bytes " "objects actually behave like immutable sequences of integers, with each " @@ -4292,7 +5176,7 @@ msgstr "" "cegamente em formatos de dados binários que não são compatíveis com ASCII " "irá usualmente resultar em dados corrompidos)." -#: ../../library/stdtypes.rst:2579 +#: ../../library/stdtypes.rst:2753 msgid "" "In addition to the literal forms, bytes objects can be created in a number " "of other ways:" @@ -4300,27 +5184,27 @@ msgstr "" "Além das formas literais, os objetos bytes podem ser criados de várias " "outras maneiras:" -#: ../../library/stdtypes.rst:2582 +#: ../../library/stdtypes.rst:2756 msgid "A zero-filled bytes object of a specified length: ``bytes(10)``" msgstr "" "Um bytes preenchido com objetos zero com um comprimento especificado: " "``bytes(10)``" -#: ../../library/stdtypes.rst:2583 +#: ../../library/stdtypes.rst:2757 msgid "From an iterable of integers: ``bytes(range(20))``" msgstr "De um iterável de inteiros: ``bytes(range(20))``" -#: ../../library/stdtypes.rst:2584 +#: ../../library/stdtypes.rst:2758 msgid "Copying existing binary data via the buffer protocol: ``bytes(obj)``" msgstr "" "Copiando dados binários existentes através do protocolo de Buffer: " "``bytes(obj)``" -#: ../../library/stdtypes.rst:2586 +#: ../../library/stdtypes.rst:2760 msgid "Also see the :ref:`bytes ` built-in." msgstr "Veja também os embutidos :ref:`bytes `." -#: ../../library/stdtypes.rst:2588 +#: ../../library/stdtypes.rst:2762 msgid "" "Since 2 hexadecimal digits correspond precisely to a single byte, " "hexadecimal numbers are a commonly used format for describing binary data. " @@ -4332,7 +5216,7 @@ msgstr "" "binários. Portanto, o tipo bytes tem um método de classe adicional para ler " "dados nesse formato:" -#: ../../library/stdtypes.rst:2594 +#: ../../library/stdtypes.rst:2768 msgid "" "This :class:`bytes` class method returns a bytes object, decoding the given " "string object. The string must contain two hexadecimal digits per byte, " @@ -4342,7 +5226,7 @@ msgstr "" "decodificando o objeto string fornecido. A string deve conter dois dígitos " "hexadecimais por byte, com espaço em branco ASCII sendo ignorado." -#: ../../library/stdtypes.rst:2601 +#: ../../library/stdtypes.rst:2775 msgid "" ":meth:`bytes.fromhex` now skips all ASCII whitespace in the string, not just " "spaces." @@ -4350,7 +5234,7 @@ msgstr "" ":meth:`bytes.fromhex` agora ignora todos os espaços em branco em ASCII na " "string, não apenas espaços." -#: ../../library/stdtypes.rst:2605 +#: ../../library/stdtypes.rst:2779 msgid "" "A reverse conversion function exists to transform a bytes object into its " "hexadecimal representation." @@ -4358,7 +5242,7 @@ msgstr "" "Uma função de conversão reversa existe para transformar um objeto bytes na " "sua representação hexadecimal." -#: ../../library/stdtypes.rst:2610 ../../library/stdtypes.rst:2695 +#: ../../library/stdtypes.rst:2784 ../../library/stdtypes.rst:2869 msgid "" "Return a string object containing two hexadecimal digits for each byte in " "the instance." @@ -4366,7 +5250,7 @@ msgstr "" "Retorna um objeto string contendo dois dígitos hexadecimais para cada byte " "na instância." -#: ../../library/stdtypes.rst:2616 +#: ../../library/stdtypes.rst:2790 msgid "" "If you want to make the hex string easier to read, you can specify a single " "character separator *sep* parameter to include in the output. By default, " @@ -4381,7 +5265,7 @@ msgstr "" "Valores positivos calculam a posição do separador a partir da direita, " "valores negativos calculam a partir da esquerda." -#: ../../library/stdtypes.rst:2633 +#: ../../library/stdtypes.rst:2807 msgid "" ":meth:`bytes.hex` now supports optional *sep* and *bytes_per_sep* parameters " "to insert separators between bytes in the hex output." @@ -4389,7 +5273,7 @@ msgstr "" ":meth:`bytes.hex` agora suporta os parâmetros opcionais *sep* e " "*bytes_per_sep* para inserir separadores entre bytes na saída hexadecimal." -#: ../../library/stdtypes.rst:2637 +#: ../../library/stdtypes.rst:2811 msgid "" "Since bytes objects are sequences of integers (akin to a tuple), for a bytes " "object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be a bytes " @@ -4402,7 +5286,7 @@ msgstr "" "strings de texto, onde tanto o uso por índice quanto por fatiamento irão " "produzir uma string de comprimento 1)" -#: ../../library/stdtypes.rst:2642 +#: ../../library/stdtypes.rst:2816 msgid "" "The representation of bytes objects uses the literal format (``b'...'``) " "since it is often more useful than e.g. ``bytes([46, 46, 46])``. You can " @@ -4413,11 +5297,11 @@ msgstr "" "46])``. Você sempre pode converter um objeto bytes em uma lista de inteiros " "usando ``list(b)``." -#: ../../library/stdtypes.rst:2650 +#: ../../library/stdtypes.rst:2824 msgid "Bytearray Objects" msgstr "Objetos Bytearray" -#: ../../library/stdtypes.rst:2654 +#: ../../library/stdtypes.rst:2828 msgid "" ":class:`bytearray` objects are a mutable counterpart to :class:`bytes` " "objects." @@ -4425,7 +5309,7 @@ msgstr "" "Objetos :class:`bytearray` são mutáveis, em contrapartida a objetos :class:" "`bytes`." -#: ../../library/stdtypes.rst:2659 +#: ../../library/stdtypes.rst:2833 msgid "" "There is no dedicated literal syntax for bytearray objects, instead they are " "always created by calling the constructor:" @@ -4433,28 +5317,28 @@ msgstr "" "Não existe sintaxe literal dedicada para objetos de bytearray, ao invés " "disso eles sempre são criados através da chamada do construtor:" -#: ../../library/stdtypes.rst:2662 +#: ../../library/stdtypes.rst:2836 msgid "Creating an empty instance: ``bytearray()``" msgstr "Criando uma instância vazia: ``bytearray()``" -#: ../../library/stdtypes.rst:2663 +#: ../../library/stdtypes.rst:2837 msgid "Creating a zero-filled instance with a given length: ``bytearray(10)``" msgstr "" "Criando uma instância cheia de zero com um determinado comprimento: " "``bytearray(10)``" -#: ../../library/stdtypes.rst:2664 +#: ../../library/stdtypes.rst:2838 msgid "From an iterable of integers: ``bytearray(range(20))``" msgstr "A partir de inteiros iteráveis: ``bytearray(range(20))``" -#: ../../library/stdtypes.rst:2665 +#: ../../library/stdtypes.rst:2839 msgid "" "Copying existing binary data via the buffer protocol: ``bytearray(b'Hi!')``" msgstr "" "Copiando dados binários existentes através do protocolo de buffer: " "``bytearray(b'Hi!')``" -#: ../../library/stdtypes.rst:2667 +#: ../../library/stdtypes.rst:2841 msgid "" "As bytearray objects are mutable, they support the :ref:`mutable ` sequence operations in addition to the common bytes and bytearray " @@ -4464,11 +5348,11 @@ msgstr "" "sequência :ref:`mutable ` além das operações comuns de " "bytes e bytearray descritas em :ref:`bytes-methods`." -#: ../../library/stdtypes.rst:2671 +#: ../../library/stdtypes.rst:2845 msgid "Also see the :ref:`bytearray ` built-in." msgstr "Veja também o tipo embutido :ref:`bytearray `." -#: ../../library/stdtypes.rst:2673 +#: ../../library/stdtypes.rst:2847 msgid "" "Since 2 hexadecimal digits correspond precisely to a single byte, " "hexadecimal numbers are a commonly used format for describing binary data. " @@ -4480,7 +5364,7 @@ msgstr "" "dados binários. Consequentemente, o tipo de bytearray tem um método de " "classe adicional para ler dados nesse formato:" -#: ../../library/stdtypes.rst:2679 +#: ../../library/stdtypes.rst:2853 msgid "" "This :class:`bytearray` class method returns bytearray object, decoding the " "given string object. The string must contain two hexadecimal digits per " @@ -4491,7 +5375,7 @@ msgstr "" "dois dígitos hexadecimais por byte, com espaços em branco ASCII sendo " "ignorados." -#: ../../library/stdtypes.rst:2686 +#: ../../library/stdtypes.rst:2860 msgid "" ":meth:`bytearray.fromhex` now skips all ASCII whitespace in the string, not " "just spaces." @@ -4499,7 +5383,7 @@ msgstr "" ":meth:`bytearray.fromhex` agora ignora todos os espaços em branco em ASCII " "na string, não apenas espaços." -#: ../../library/stdtypes.rst:2690 +#: ../../library/stdtypes.rst:2864 msgid "" "A reverse conversion function exists to transform a bytearray object into " "its hexadecimal representation." @@ -4507,7 +5391,7 @@ msgstr "" "Existe uma função de conversão reversa para transformar um objeto bytearray " "em sua representação hexadecimal." -#: ../../library/stdtypes.rst:2703 +#: ../../library/stdtypes.rst:2877 msgid "" "Similar to :meth:`bytes.hex`, :meth:`bytearray.hex` now supports optional " "*sep* and *bytes_per_sep* parameters to insert separators between bytes in " @@ -4517,7 +5401,7 @@ msgstr "" "parâmetros opcionais *sep* e *bytes_per_sep* para inserir separadores entre " "bytes na saída hexadecimal." -#: ../../library/stdtypes.rst:2708 +#: ../../library/stdtypes.rst:2882 msgid "" "Since bytearray objects are sequences of integers (akin to a list), for a " "bytearray object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be " @@ -4530,7 +5414,7 @@ msgstr "" "Strings de texto, onde tanto a indexação como o fatiamento produzirão " "sequências de comprimento 1)" -#: ../../library/stdtypes.rst:2713 +#: ../../library/stdtypes.rst:2887 msgid "" "The representation of bytearray objects uses the bytes literal format " "(``bytearray(b'...')``) since it is often more useful than e.g. " @@ -4542,11 +5426,11 @@ msgstr "" "exemplo, ``bytearray([46, 46, 46])``. Você sempre pode converter um objeto " "bytearray em uma lista de inteiros usando ``list(b)``." -#: ../../library/stdtypes.rst:2722 +#: ../../library/stdtypes.rst:2896 msgid "Bytes and Bytearray Operations" msgstr "Operações com Bytes e Bytearray" -#: ../../library/stdtypes.rst:2727 +#: ../../library/stdtypes.rst:2901 msgid "" "Both bytes and bytearray objects support the :ref:`common ` " "sequence operations. They interoperate not just with operands of the same " @@ -4556,12 +5440,12 @@ msgid "" msgstr "" "Ambos os tipos, bytes e os objetos bytearray suportam as operações de " "sequências :ref:`comuns `. Os mesmo interagem não apenas " -"com operandos do mesmo tipo, mas com qualquer :term:`objeto byte ou similar " +"com operandos do mesmo tipo, mas com qualquer :term:`objeto bytes ou similar " "`. Devido a esta flexibilidade, os mesmos podem ser " "misturados livremente em operações sem causar erros. No entanto, o tipo de " "retorno do resultado pode depender da ordem dos operandos." -#: ../../library/stdtypes.rst:2735 +#: ../../library/stdtypes.rst:2909 msgid "" "The methods on bytes and bytearray objects don't accept strings as their " "arguments, just as the methods on strings don't accept bytes as their " @@ -4571,11 +5455,27 @@ msgstr "" "assim como os métodos de Strings não aceitam bytes como argumentos. Por " "exemplo, devemos escrever::" -#: ../../library/stdtypes.rst:2742 +#: ../../library/stdtypes.rst:2913 +msgid "" +"a = \"abc\"\n" +"b = a.replace(\"a\", \"f\")" +msgstr "" +"a = \"abc\"\n" +"b = a.replace(\"a\", \"f\")" + +#: ../../library/stdtypes.rst:2916 msgid "and::" msgstr "e::" -#: ../../library/stdtypes.rst:2747 +#: ../../library/stdtypes.rst:2918 +msgid "" +"a = b\"abc\"\n" +"b = a.replace(b\"a\", b\"f\")" +msgstr "" +"a = b\"abc\"\n" +"b = a.replace(b\"a\", b\"f\")" + +#: ../../library/stdtypes.rst:2921 msgid "" "Some bytes and bytearray operations assume the use of ASCII compatible " "binary formats, and hence should be avoided when working with arbitrary " @@ -4585,7 +5485,7 @@ msgstr "" "compatíveis com ASCII e, portanto, devem ser evitados ao trabalhar com dados " "binários arbitrários. Essas restrições são abordadas a seguir." -#: ../../library/stdtypes.rst:2752 +#: ../../library/stdtypes.rst:2926 msgid "" "Using these ASCII based operations to manipulate binary data that is not " "stored in an ASCII based format may lead to data corruption." @@ -4594,7 +5494,7 @@ msgstr "" "não são armazenados num formato baseado em ASCII poderá resultar na " "corrupção de dados." -#: ../../library/stdtypes.rst:2755 +#: ../../library/stdtypes.rst:2929 msgid "" "The following methods on bytes and bytearray objects can be used with " "arbitrary binary data." @@ -4602,7 +5502,7 @@ msgstr "" "Os métodos a seguir em Bytes e Bytearray podem ser usados com dados binários " "arbitrários." -#: ../../library/stdtypes.rst:2761 +#: ../../library/stdtypes.rst:2935 msgid "" "Return the number of non-overlapping occurrences of subsequence *sub* in the " "range [*start*, *end*]. Optional arguments *start* and *end* are " @@ -4612,17 +5512,17 @@ msgstr "" "intervalo [*start*, *end*]. Os argumentos opcionais *start* e *end* são " "interpretados como na notação de fatiamento." -#: ../../library/stdtypes.rst:2765 ../../library/stdtypes.rst:2870 -#: ../../library/stdtypes.rst:2892 ../../library/stdtypes.rst:2958 -#: ../../library/stdtypes.rst:2971 +#: ../../library/stdtypes.rst:2939 ../../library/stdtypes.rst:3044 +#: ../../library/stdtypes.rst:3066 ../../library/stdtypes.rst:3132 +#: ../../library/stdtypes.rst:3145 msgid "" "The subsequence to search for may be any :term:`bytes-like object` or an " "integer in the range 0 to 255." msgstr "" -"A subsequência a ser procurada poderá ser qualquer :term:`objeto byte ou " -"similar ` ou um inteiro no intervalo de 0 a 255." +"A subsequência a ser procurada poderá ser qualquer :term:`objeto bytes ou " +"similar` ou um inteiro no intervalo de 0 a 255." -#: ../../library/stdtypes.rst:2768 +#: ../../library/stdtypes.rst:2942 msgid "" "If *sub* is empty, returns the number of empty slices between characters " "which is the length of the bytes object plus one." @@ -4630,14 +5530,14 @@ msgstr "" "Se *sub* estiver vazio, retorna o número de fatias vazias entre os " "caracteres, que é o comprimento do objeto bytes mais um." -#: ../../library/stdtypes.rst:2771 ../../library/stdtypes.rst:2882 -#: ../../library/stdtypes.rst:2895 ../../library/stdtypes.rst:2961 -#: ../../library/stdtypes.rst:2974 +#: ../../library/stdtypes.rst:2945 ../../library/stdtypes.rst:3056 +#: ../../library/stdtypes.rst:3069 ../../library/stdtypes.rst:3135 +#: ../../library/stdtypes.rst:3148 msgid "Also accept an integer in the range 0 to 255 as the subsequence." msgstr "" "Também aceita um número inteiro no intervalo de 0 a 255 como subsequência." -#: ../../library/stdtypes.rst:2778 +#: ../../library/stdtypes.rst:2952 msgid "" "If the binary data starts with the *prefix* string, return " "``bytes[len(prefix):]``. Otherwise, return a copy of the original binary " @@ -4647,21 +5547,31 @@ msgstr "" "``bytes[len(prefix):]``. Caso contrário, retorna uma cópia dos dados " "binários originais::" -#: ../../library/stdtypes.rst:2787 -msgid "The *prefix* may be any :term:`bytes-like object`." +#: ../../library/stdtypes.rst:2956 +msgid "" +">>> b'TestHook'.removeprefix(b'Test')\n" +"b'Hook'\n" +">>> b'BaseTestCase'.removeprefix(b'Test')\n" +"b'BaseTestCase'" msgstr "" -"O *prefix* pode ser qualquer :term:`objeto byte ou similar `." +">>> b'TestHook'.removeprefix(b'Test')\n" +"b'Hook'\n" +">>> b'BaseTestCase'.removeprefix(b'Test')\n" +"b'BaseTestCase'" -#: ../../library/stdtypes.rst:2791 ../../library/stdtypes.rst:2813 -#: ../../library/stdtypes.rst:2946 ../../library/stdtypes.rst:3039 -#: ../../library/stdtypes.rst:3053 ../../library/stdtypes.rst:3084 -#: ../../library/stdtypes.rst:3098 ../../library/stdtypes.rst:3140 -#: ../../library/stdtypes.rst:3211 ../../library/stdtypes.rst:3229 -#: ../../library/stdtypes.rst:3257 ../../library/stdtypes.rst:3396 -#: ../../library/stdtypes.rst:3451 ../../library/stdtypes.rst:3494 -#: ../../library/stdtypes.rst:3515 ../../library/stdtypes.rst:3537 -#: ../../library/stdtypes.rst:3739 +#: ../../library/stdtypes.rst:2961 +msgid "The *prefix* may be any :term:`bytes-like object`." +msgstr "O *prefix* pode ser qualquer :term:`objeto bytes ou similar`." + +#: ../../library/stdtypes.rst:2965 ../../library/stdtypes.rst:2987 +#: ../../library/stdtypes.rst:3120 ../../library/stdtypes.rst:3213 +#: ../../library/stdtypes.rst:3227 ../../library/stdtypes.rst:3258 +#: ../../library/stdtypes.rst:3272 ../../library/stdtypes.rst:3314 +#: ../../library/stdtypes.rst:3385 ../../library/stdtypes.rst:3403 +#: ../../library/stdtypes.rst:3431 ../../library/stdtypes.rst:3570 +#: ../../library/stdtypes.rst:3625 ../../library/stdtypes.rst:3668 +#: ../../library/stdtypes.rst:3689 ../../library/stdtypes.rst:3711 +#: ../../library/stdtypes.rst:3913 msgid "" "The bytearray version of this method does *not* operate in place - it always " "produces a new object, even if no changes were made." @@ -4669,7 +5579,7 @@ msgstr "" "A versão Bytearray deste método *não* opera no local -- o mesmo sempre " "produz um novo objeto, mesmo que não tenha sido feitas alterações." -#: ../../library/stdtypes.rst:2800 +#: ../../library/stdtypes.rst:2974 msgid "" "If the binary data ends with the *suffix* string and that *suffix* is not " "empty, return ``bytes[:-len(suffix)]``. Otherwise, return a copy of the " @@ -4679,17 +5589,27 @@ msgstr "" "estiver vazia, retorna ``bytes[:-len(suffix)]``. Caso contrário, retorna uma " "cópia dos dados binários originais::" -#: ../../library/stdtypes.rst:2809 -msgid "The *suffix* may be any :term:`bytes-like object`." +#: ../../library/stdtypes.rst:2978 +msgid "" +">>> b'MiscTests'.removesuffix(b'Tests')\n" +"b'Misc'\n" +">>> b'TmpDirMixin'.removesuffix(b'Tests')\n" +"b'TmpDirMixin'" msgstr "" -"O *suffix* pode ser qualquer :term:`objeto byte ou similar `." +">>> b'MiscTests'.removesuffix(b'Tests')\n" +"b'Misc'\n" +">>> b'TmpDirMixin'.removesuffix(b'Tests')\n" +"b'TmpDirMixin'" + +#: ../../library/stdtypes.rst:2983 +msgid "The *suffix* may be any :term:`bytes-like object`." +msgstr "O *suffix* pode ser qualquer :term:`objeto bytes ou similar`." -#: ../../library/stdtypes.rst:2822 +#: ../../library/stdtypes.rst:2996 msgid "Return the bytes decoded to a :class:`str`." msgstr "Retorna os bytes decodificados para uma :class:`str`." -#: ../../library/stdtypes.rst:2827 +#: ../../library/stdtypes.rst:3001 msgid "" "*errors* controls how decoding errors are handled. If ``'strict'`` (the " "default), a :exc:`UnicodeError` exception is raised. Other possible values " @@ -4702,7 +5622,7 @@ msgstr "" "registrado via :func:`codecs.register_error`. Veja :ref:`error-handlers` " "para detalhes." -#: ../../library/stdtypes.rst:2833 +#: ../../library/stdtypes.rst:3007 msgid "" "For performance reasons, the value of *errors* is not checked for validity " "unless a decoding error actually occurs, :ref:`devmode` is enabled or a :ref:" @@ -4713,17 +5633,17 @@ msgstr "" "`devmode` esteja ativado ou uma :ref:`construção de depuração ` " "seja usada." -#: ../../library/stdtypes.rst:2839 +#: ../../library/stdtypes.rst:3013 msgid "" "Passing the *encoding* argument to :class:`str` allows decoding any :term:" "`bytes-like object` directly, without needing to make a temporary :class:`!" "bytes` or :class:`!bytearray` object." msgstr "" "Passar o argumento *encoding* para :class:`str` permite decodificar qualquer " -"objeto :term:`objeto byte ou similar` diretamente, sem a necessidade de " +"objeto :term:`objeto bytes ou similar` diretamente, sem a necessidade de " "criar um objeto :class:`!bytes` ou :class:`!bytearray` temporário." -#: ../../library/stdtypes.rst:2854 +#: ../../library/stdtypes.rst:3028 msgid "" "Return ``True`` if the binary data ends with the specified *suffix*, " "otherwise return ``False``. *suffix* can also be a tuple of suffixes to " @@ -4736,13 +5656,13 @@ msgstr "" "começa naquela posição. Com o parâmetro opcional *end*, o método encerra a " "comparação na posição fornecida." -#: ../../library/stdtypes.rst:2859 +#: ../../library/stdtypes.rst:3033 msgid "The suffix(es) to search for may be any :term:`bytes-like object`." msgstr "" -"O sufixo(es) para buscas pode ser qualquer termos :term:`objeto byte ou " -"similar `." +"O sufixo(es) para buscas pode ser qualquer termos :term:`objeto bytes ou " +"similar`." -#: ../../library/stdtypes.rst:2865 +#: ../../library/stdtypes.rst:3039 msgid "" "Return the lowest index in the data where the subsequence *sub* is found, " "such that *sub* is contained in the slice ``s[start:end]``. Optional " @@ -4754,7 +5674,7 @@ msgstr "" "opcionais *start* e *end* são interpretados como na notação de fatiamento. " "Retorna ``-1`` se *sub* não for localizada." -#: ../../library/stdtypes.rst:2875 +#: ../../library/stdtypes.rst:3049 msgid "" "The :meth:`~bytes.find` method should be used only if you need to know the " "position of *sub*. To check if *sub* is a substring or not, use the :" @@ -4764,7 +5684,15 @@ msgstr "" "posição de *sub*. Para verificar se *sub* é uma substring ou não, use o " "operador :keyword:`in`::" -#: ../../library/stdtypes.rst:2889 +#: ../../library/stdtypes.rst:3053 +msgid "" +">>> b'Py' in b'Python'\n" +"True" +msgstr "" +">>> b'Py' in b'Python'\n" +"True" + +#: ../../library/stdtypes.rst:3063 msgid "" "Like :meth:`~bytes.find`, but raise :exc:`ValueError` when the subsequence " "is not found." @@ -4772,7 +5700,7 @@ msgstr "" "Como :meth:`~bytes.find`, mas levanta a exceção :exc:`ValueError` quando a " "subsequência não for encontrada." -#: ../../library/stdtypes.rst:2902 +#: ../../library/stdtypes.rst:3076 msgid "" "Return a bytes or bytearray object which is the concatenation of the binary " "data sequences in *iterable*. A :exc:`TypeError` will be raised if there " @@ -4782,13 +5710,13 @@ msgid "" "method." msgstr "" "Retorna um objeto bytes ou bytearray que é a concatenação das sequências de " -"dados binários no *iterável*. Um :exc:`TypeError` será levantado se " -"existirem quaisquer valores que não sejam :term:`objeto byte ou similar " -"`, no *iterável*, incluindo objetos :class:`str`. O " -"separador entre elementos é o conteúdo do objeto bytes ou bytearray que está " +"dados binários no iterável *iterable*. Uma exceção :exc:`TypeError` será " +"levantada se existirem quaisquer valores que não sejam :term:`objeto bytes " +"ou similar`, no *iterable*, incluindo objetos :class:`str`. O separador " +"entre elementos é o conteúdo do objeto bytes ou bytearray que está " "fornecendo este método." -#: ../../library/stdtypes.rst:2913 +#: ../../library/stdtypes.rst:3087 msgid "" "This static method returns a translation table usable for :meth:`bytes." "translate` that will map each character in *from* into the character at the " @@ -4797,10 +5725,10 @@ msgid "" msgstr "" "Este método estático retorna uma tabela de tradução usável para :meth:`bytes." "translate`, que irá mapear cada caractere em *from* no caractere na mesma " -"posição em *to*; *from* e *to* devem ambos ser :term:`objeto byte ou similar " -"` e ter o mesmo comprimento." +"posição em *to*; *from* e *to* devem ambos ser :term:`objetos bytes ou " +"similar ` e ter o mesmo comprimento." -#: ../../library/stdtypes.rst:2924 +#: ../../library/stdtypes.rst:3098 msgid "" "Split the sequence at the first occurrence of *sep*, and return a 3-tuple " "containing the part before the separator, the separator itself or its " @@ -4814,13 +5742,12 @@ msgstr "" "com 3 elementos contendo uma cópia da sequência original, seguido de dois " "bytes ou objetos bytearray vazios." -#: ../../library/stdtypes.rst:2931 ../../library/stdtypes.rst:2988 +#: ../../library/stdtypes.rst:3105 ../../library/stdtypes.rst:3162 msgid "The separator to search for may be any :term:`bytes-like object`." msgstr "" -"O separador para buscar pode ser qualquer termos :term:`objeto byte ou " -"similar `." +"O separador para buscar pode ser qualquer :term:`objeto bytes ou similar`." -#: ../../library/stdtypes.rst:2937 +#: ../../library/stdtypes.rst:3111 msgid "" "Return a copy of the sequence with all occurrences of subsequence *old* " "replaced by *new*. If the optional argument *count* is given, only the " @@ -4830,15 +5757,15 @@ msgstr "" "*antigas* substituídas por *novo*. Se o argumento opcional *count* for " "fornecido, apenas as primeiras ocorrências de *count* serão substituídas." -#: ../../library/stdtypes.rst:2941 +#: ../../library/stdtypes.rst:3115 msgid "" "The subsequence to search for and its replacement may be any :term:`bytes-" "like object`." msgstr "" "A subsequência para buscar e substituição pode ser qualquer termos :term:" -"`objeto byte ou similar `." +"`objeto bytes ou similar`." -#: ../../library/stdtypes.rst:2953 +#: ../../library/stdtypes.rst:3127 msgid "" "Return the highest index in the sequence where the subsequence *sub* is " "found, such that *sub* is contained within ``s[start:end]``. Optional " @@ -4850,7 +5777,7 @@ msgstr "" "argumentos opcionais *start* e *end* são interpretados como na notação de " "fatiamento. Caso ocorra algum problema será retornado ``-1``." -#: ../../library/stdtypes.rst:2968 +#: ../../library/stdtypes.rst:3142 msgid "" "Like :meth:`~bytes.rfind` but raises :exc:`ValueError` when the subsequence " "*sub* is not found." @@ -4858,7 +5785,7 @@ msgstr "" "Semelhante a :meth:`~bytes.rfind` mas levanta :exc:`ValueError` quando a " "subsequência *sub* não é encontrada." -#: ../../library/stdtypes.rst:2981 +#: ../../library/stdtypes.rst:3155 msgid "" "Split the sequence at the last occurrence of *sep*, and return a 3-tuple " "containing the part before the separator, the separator itself or its " @@ -4872,7 +5799,7 @@ msgstr "" "com 3 elementos contendo dois bytes ou objetos bytearray vazios, seguido por " "uma cópia da sequência original." -#: ../../library/stdtypes.rst:2994 +#: ../../library/stdtypes.rst:3168 msgid "" "Return ``True`` if the binary data starts with the specified *prefix*, " "otherwise return ``False``. *prefix* can also be a tuple of prefixes to " @@ -4885,13 +5812,13 @@ msgstr "" "na posição indicada. Com o parâmetro opcional *end*, encerra a procura na " "posição indicada." -#: ../../library/stdtypes.rst:2999 +#: ../../library/stdtypes.rst:3173 msgid "The prefix(es) to search for may be any :term:`bytes-like object`." msgstr "" -"Os prefixos para pesquisar podem ser qualquer :term:`objeto byte ou similar " -"`." +"Os prefixos para pesquisar podem ser qualquer :term:`objeto bytes ou " +"similar`." -#: ../../library/stdtypes.rst:3005 +#: ../../library/stdtypes.rst:3179 msgid "" "Return a copy of the bytes or bytearray object where all bytes occurring in " "the optional argument *delete* are removed, and the remaining bytes have " @@ -4903,14 +5830,14 @@ msgstr "" "foram mapeados através da tabela de tradução fornecida, a qual deve ser um " "objeto bytes de comprimento 256." -#: ../../library/stdtypes.rst:3010 +#: ../../library/stdtypes.rst:3184 msgid "" "You can use the :func:`bytes.maketrans` method to create a translation table." msgstr "" "Você pode usar o método :func:`bytes.maketrans` para criar uma tabela de " "tradução." -#: ../../library/stdtypes.rst:3013 +#: ../../library/stdtypes.rst:3187 msgid "" "Set the *table* argument to ``None`` for translations that only delete " "characters::" @@ -4918,11 +5845,19 @@ msgstr "" "Define o argumento *table* como ``None`` para traduções que excluem apenas " "caracteres::" -#: ../../library/stdtypes.rst:3019 +#: ../../library/stdtypes.rst:3190 +msgid "" +">>> b'read this short text'.translate(None, b'aeiou')\n" +"b'rd ths shrt txt'" +msgstr "" +">>> b'leia este curto texto'.translate(None, b'aeiou')\n" +"b'l st crt txt'" + +#: ../../library/stdtypes.rst:3193 msgid "*delete* is now supported as a keyword argument." msgstr "*delete* agora é suportado como um argumento nomeado." -#: ../../library/stdtypes.rst:3023 +#: ../../library/stdtypes.rst:3197 msgid "" "The following methods on bytes and bytearray objects have default behaviours " "that assume the use of ASCII compatible binary formats, but can still be " @@ -4936,7 +5871,7 @@ msgstr "" "argumentos apropriados. Perceba que todos os métodos de bytearray nesta " "seção *não* alteram os argumentos, e ao invés disso produzem novos objetos." -#: ../../library/stdtypes.rst:3032 +#: ../../library/stdtypes.rst:3206 msgid "" "Return a copy of the object centered in a sequence of length *width*. " "Padding is done using the specified *fillbyte* (default is an ASCII space). " @@ -4948,7 +5883,7 @@ msgstr "" "um espaço ASCII). Para objetos :class:`bytes`, a sequência original é " "retornada se *width* é menor que ou igual a ``len(s)``." -#: ../../library/stdtypes.rst:3046 +#: ../../library/stdtypes.rst:3220 msgid "" "Return a copy of the object left justified in a sequence of length *width*. " "Padding is done using the specified *fillbyte* (default is an ASCII space). " @@ -4960,7 +5895,7 @@ msgstr "" "(o padrão é um espaço ASCII). Para objetos :class:`bytes`, a sequência " "original é retornada se *width* é menor que ou igual a ``len(s)``." -#: ../../library/stdtypes.rst:3060 +#: ../../library/stdtypes.rst:3234 msgid "" "Return a copy of the sequence with specified leading bytes removed. The " "*chars* argument is a binary sequence specifying the set of byte values to " @@ -4975,20 +5910,44 @@ msgstr "" "usualmente utilizado com caracteres ASCII. Se for omitido ou for ``None``, o " "argumento *chars* irá remover por padrão os espaços em branco ASCII. O " "argumento *chars* não é um prefixo; ao contrário disso, todas as combinações " -"dos seus seus valores são removidas::" +"dos seus valores são removidas::" -#: ../../library/stdtypes.rst:3072 +#: ../../library/stdtypes.rst:3241 +msgid "" +">>> b' spacious '.lstrip()\n" +"b'spacious '\n" +">>> b'www.example.com'.lstrip(b'cmowz.')\n" +"b'example.com'" +msgstr "" +">>> b' spacious '.lstrip()\n" +"b'spacious '\n" +">>> b'www.example.com'.lstrip(b'cmowz.')\n" +"b'example.com'" + +#: ../../library/stdtypes.rst:3246 msgid "" "The binary sequence of byte values to remove may be any :term:`bytes-like " "object`. See :meth:`~bytes.removeprefix` for a method that will remove a " "single prefix string rather than all of a set of characters. For example::" msgstr "" "A sequência binária de valores de bytes a serem removidos pode ser :term:" -"`objeto byte ou similar `. Consulte :meth:`~bytes." -"removeprefix` para um método que removerá uma única string de prefixo em vez " -"de todo um conjunto de caracteres. Por exemplo::" +"`objeto bytes ou similar`. Consulte :meth:`~bytes.removeprefix` para um " +"método que removerá uma única string de prefixo em vez de todo um conjunto " +"de caracteres. Por exemplo::" + +#: ../../library/stdtypes.rst:3251 +msgid "" +">>> b'Arthur: three!'.lstrip(b'Arthur: ')\n" +"b'ee!'\n" +">>> b'Arthur: three!'.removeprefix(b'Arthur: ')\n" +"b'three!'" +msgstr "" +">>> b'Arthur: three!'.lstrip(b'Arthur: ')\n" +"b'ee!'\n" +">>> b'Arthur: three!'.removeprefix(b'Arthur: ')\n" +"b'three!'" -#: ../../library/stdtypes.rst:3091 +#: ../../library/stdtypes.rst:3265 msgid "" "Return a copy of the object right justified in a sequence of length *width*. " "Padding is done using the specified *fillbyte* (default is an ASCII space). " @@ -5000,7 +5959,7 @@ msgstr "" "(o padrão é um espaço ASCII). Para objetos :class:`bytes`, a sequência " "original é retornada se *width* é menor que ou igual a ``len(s)``." -#: ../../library/stdtypes.rst:3105 +#: ../../library/stdtypes.rst:3279 msgid "" "Split the binary sequence into subsequences of the same type, using *sep* as " "the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are " @@ -5017,7 +5976,7 @@ msgstr "" "meth:`rsplit` comporta-se como :meth:`split`, o qual é descrito em detalhes " "abaixo." -#: ../../library/stdtypes.rst:3116 +#: ../../library/stdtypes.rst:3290 msgid "" "Return a copy of the sequence with specified trailing bytes removed. The " "*chars* argument is a binary sequence specifying the set of byte values to " @@ -5032,20 +5991,44 @@ msgstr "" "utilizado com caracteres ASCII. Se for omitido ou for ``None``, o argumento " "*chars* irá remover por padrão os espaços em branco ASCII. O argumento " "*chars* não é um sufixo; ao contrário disso, todas as combinações dos seus " -"seus valores são removidas::" +"valores são removidas::" + +#: ../../library/stdtypes.rst:3297 +msgid "" +">>> b' spacious '.rstrip()\n" +"b' spacious'\n" +">>> b'mississippi'.rstrip(b'ipz')\n" +"b'mississ'" +msgstr "" +">>> b' spacious '.rstrip()\n" +"b' spacious'\n" +">>> b'mississippi'.rstrip(b'ipz')\n" +"b'mississ'" -#: ../../library/stdtypes.rst:3128 +#: ../../library/stdtypes.rst:3302 msgid "" "The binary sequence of byte values to remove may be any :term:`bytes-like " "object`. See :meth:`~bytes.removesuffix` for a method that will remove a " "single suffix string rather than all of a set of characters. For example::" msgstr "" "A sequência binária de valores de bytes a serem removidos pode ser :term:" -"`objeto byte ou similar `. Consulte :meth:`~bytes." -"removesuffix` para um método que removerá uma única string de sufixo em vez " -"de todo um conjunto de caracteres. Por exemplo::" +"`objeto bytes ou similar`. Consulte :meth:`~bytes.removesuffix` para um " +"método que removerá uma única string de sufixo em vez de todo um conjunto de " +"caracteres. Por exemplo::" + +#: ../../library/stdtypes.rst:3307 +msgid "" +">>> b'Monty Python'.rstrip(b' Python')\n" +"b'M'\n" +">>> b'Monty Python'.removesuffix(b' Python')\n" +"b'Monty'" +msgstr "" +">>> b'Monty Python'.rstrip(b' Python')\n" +"b'M'\n" +">>> b'Monty Python'.removesuffix(b' Python')\n" +"b'Monty'" -#: ../../library/stdtypes.rst:3147 +#: ../../library/stdtypes.rst:3321 msgid "" "Split the binary sequence into subsequences of the same type, using *sep* as " "the delimiter string. If *maxsplit* is given and non-negative, at most " @@ -5059,7 +6042,7 @@ msgstr "" "elementos). Se *maxsplit* não é especificado ou é ``-1``, então não existe " "limite no número de divisões (todas as divisões possíveis são feitas)." -#: ../../library/stdtypes.rst:3153 +#: ../../library/stdtypes.rst:3327 msgid "" "If *sep* is given, consecutive delimiters are not grouped together and are " "deemed to delimit empty subsequences (for example, ``b'1,,2'.split(b',')`` " @@ -5075,10 +6058,30 @@ msgstr "" "consistir de uma sequência de múltiplos bytes como um único delimitador. " "Separar uma sequência vazia com um separador especificado retorna ``[b'']`` " "ou ``[bytearray(b'')]`` dependendo do tipo do objeto que está sendo " -"separado. O argumento *sep* pode ser qualquer :term:`objeto byte ou similar " -"`." - -#: ../../library/stdtypes.rst:3172 +"separado. O argumento *sep* pode ser qualquer :term:`objeto bytes ou " +"similar`." + +#: ../../library/stdtypes.rst:3337 +msgid "" +">>> b'1,2,3'.split(b',')\n" +"[b'1', b'2', b'3']\n" +">>> b'1,2,3'.split(b',', maxsplit=1)\n" +"[b'1', b'2,3']\n" +">>> b'1,2,,3,'.split(b',')\n" +"[b'1', b'2', b'', b'3', b'']\n" +">>> b'1<>2<>3<4'.split(b'<>')\n" +"[b'1', b'2', b'3<4']" +msgstr "" +">>> b'1,2,3'.split(b',')\n" +"[b'1', b'2', b'3']\n" +">>> b'1,2,3'.split(b',', maxsplit=1)\n" +"[b'1', b'2,3']\n" +">>> b'1,2,,3,'.split(b',')\n" +"[b'1', b'2', b'', b'3', b'']\n" +">>> b'1<>2<>3<4'.split(b'<>')\n" +"[b'1', b'2', b'3<4']" + +#: ../../library/stdtypes.rst:3346 msgid "" "If *sep* is not specified or is ``None``, a different splitting algorithm is " "applied: runs of consecutive ASCII whitespace are regarded as a single " @@ -5095,7 +6098,23 @@ msgstr "" "sequência que consiste apenas de espaços em branco ASCII sem um separador " "especificado, retorna ``[]``." -#: ../../library/stdtypes.rst:3193 +#: ../../library/stdtypes.rst:3356 +msgid "" +">>> b'1 2 3'.split()\n" +"[b'1', b'2', b'3']\n" +">>> b'1 2 3'.split(maxsplit=1)\n" +"[b'1', b'2 3']\n" +">>> b' 1 2 3 '.split()\n" +"[b'1', b'2', b'3']" +msgstr "" +">>> b'1 2 3'.split()\n" +"[b'1', b'2', b'3']\n" +">>> b'1 2 3'.split(maxsplit=1)\n" +"[b'1', b'2 3']\n" +">>> b' 1 2 3 '.split()\n" +"[b'1', b'2', b'3']" + +#: ../../library/stdtypes.rst:3367 msgid "" "Return a copy of the sequence with specified leading and trailing bytes " "removed. The *chars* argument is a binary sequence specifying the set of " @@ -5110,17 +6129,29 @@ msgstr "" "método é normalmente utilizado com caracteres ASCII. Se for omitido ou for " "``None``, o argumento *chars* irá remover por padrão os espaços em branco " "ASCII. O argumento *chars* não é um prefixo, nem um sufixo; ao contrário " -"disso, todas as combinações dos seus seus valores são removidas::" +"disso, todas as combinações dos seus valores são removidas::" -#: ../../library/stdtypes.rst:3206 +#: ../../library/stdtypes.rst:3375 +msgid "" +">>> b' spacious '.strip()\n" +"b'spacious'\n" +">>> b'www.example.com'.strip(b'cmowz.')\n" +"b'example'" +msgstr "" +">>> b' spacious '.strip()\n" +"b'spacious'\n" +">>> b'www.example.com'.strip(b'cmowz.')\n" +"b'example'" + +#: ../../library/stdtypes.rst:3380 msgid "" "The binary sequence of byte values to remove may be any :term:`bytes-like " "object`." msgstr "" "A sequência binária de valores de bytes a serem removidos pode ser qualquer :" -"term:`objeto byte ou similar `." +"term:`objeto bytes ou similar`." -#: ../../library/stdtypes.rst:3215 +#: ../../library/stdtypes.rst:3389 msgid "" "The following methods on bytes and bytearray objects assume the use of ASCII " "compatible binary formats and should not be applied to arbitrary binary " @@ -5132,7 +6163,7 @@ msgstr "" "arbitrários. Perceba que todos os métodos de bytearray nesta seção *não* " "alteram os argumentos, e ao invés disso produzem novos objetos." -#: ../../library/stdtypes.rst:3223 +#: ../../library/stdtypes.rst:3397 msgid "" "Return a copy of the sequence with each byte interpreted as an ASCII " "character, and the first byte capitalized and the rest lowercased. Non-ASCII " @@ -5142,7 +6173,7 @@ msgstr "" "ASCII, e o primeiro byte em letra maiúscula e o resto em letras minúsculas. " "Valores de bytes que não são ASCII são passados adiante sem mudanças." -#: ../../library/stdtypes.rst:3236 +#: ../../library/stdtypes.rst:3410 msgid "" "Return a copy of the sequence where all ASCII tab characters are replaced by " "one or more ASCII spaces, depending on the current column and the given tab " @@ -5172,7 +6203,19 @@ msgstr "" "incrementada em uma unidade independentemente de como o byte é representado " "quanto é impresso::" -#: ../../library/stdtypes.rst:3264 +#: ../../library/stdtypes.rst:3424 +msgid "" +">>> b'01\\t012\\t0123\\t01234'.expandtabs()\n" +"b'01 012 0123 01234'\n" +">>> b'01\\t012\\t0123\\t01234'.expandtabs(4)\n" +"b'01 012 0123 01234'" +msgstr "" +">>> b'01\\t012\\t0123\\t01234'.expandtabs()\n" +"b'01 012 0123 01234'\n" +">>> b'01\\t012\\t0123\\t01234'.expandtabs(4)\n" +"b'01 012 0123 01234'" + +#: ../../library/stdtypes.rst:3438 msgid "" "Return ``True`` if all bytes in the sequence are alphabetical ASCII " "characters or ASCII decimal digits and the sequence is not empty, ``False`` " @@ -5187,7 +6230,19 @@ msgstr "" "Dígitos decimais ASCII são aqueles valores de byte na sequência " "``b'0123456789'``." -#: ../../library/stdtypes.rst:3281 +#: ../../library/stdtypes.rst:3446 +msgid "" +">>> b'ABCabc1'.isalnum()\n" +"True\n" +">>> b'ABC abc1'.isalnum()\n" +"False" +msgstr "" +">>> b'ABCabc1'.isalnum()\n" +"True\n" +">>> b'ABC abc1'.isalnum()\n" +"False" + +#: ../../library/stdtypes.rst:3455 msgid "" "Return ``True`` if all bytes in the sequence are alphabetic ASCII characters " "and the sequence is not empty, ``False`` otherwise. Alphabetic ASCII " @@ -5199,7 +6254,19 @@ msgstr "" "alfabéticos ASCII são aqueles cujo valor dos bytes estão na sequência " "``b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'``." -#: ../../library/stdtypes.rst:3297 +#: ../../library/stdtypes.rst:3462 +msgid "" +">>> b'ABCabc'.isalpha()\n" +"True\n" +">>> b'ABCabc1'.isalpha()\n" +"False" +msgstr "" +">>> b'ABCabc'.isalpha()\n" +"True\n" +">>> b'ABCabc1'.isalpha()\n" +"False" + +#: ../../library/stdtypes.rst:3471 msgid "" "Return ``True`` if the sequence is empty or all bytes in the sequence are " "ASCII, ``False`` otherwise. ASCII bytes are in the range 0-0x7F." @@ -5207,7 +6274,7 @@ msgstr "" "Retorna ``True`` se a sequência é vazia ou todos os bytes na sequência são " "ASCII, ``False`` caso contrário. Bytes ASCII estão no intervalo 0-0x7F." -#: ../../library/stdtypes.rst:3307 +#: ../../library/stdtypes.rst:3481 msgid "" "Return ``True`` if all bytes in the sequence are ASCII decimal digits and " "the sequence is not empty, ``False`` otherwise. ASCII decimal digits are " @@ -5217,7 +6284,19 @@ msgstr "" "a sequência não é vazia, ``False`` caso contrário. Dígitos decimais ASCII " "são aqueles cujos valores dos bytes estão na sequência ``b'0123456789'``." -#: ../../library/stdtypes.rst:3322 +#: ../../library/stdtypes.rst:3487 +msgid "" +">>> b'1234'.isdigit()\n" +"True\n" +">>> b'1.23'.isdigit()\n" +"False" +msgstr "" +">>> b'1234'.isdigit()\n" +"True\n" +">>> b'1.23'.isdigit()\n" +"False" + +#: ../../library/stdtypes.rst:3496 msgid "" "Return ``True`` if there is at least one lowercase ASCII character in the " "sequence and no uppercase ASCII characters, ``False`` otherwise." @@ -5225,9 +6304,21 @@ msgstr "" "Retorna ``True`` se existe pelo menos um caractere minúsculo ASCII na " "sequência e nenhum caractere maiúsculo ASCII, ``False`` caso contrário." -#: ../../library/stdtypes.rst:3332 ../../library/stdtypes.rst:3374 -#: ../../library/stdtypes.rst:3390 ../../library/stdtypes.rst:3440 -#: ../../library/stdtypes.rst:3509 +#: ../../library/stdtypes.rst:3501 +msgid "" +">>> b'hello world'.islower()\n" +"True\n" +">>> b'Hello world'.islower()\n" +"False" +msgstr "" +">>> b'hello world'.islower()\n" +"True\n" +">>> b'Hello world'.islower()\n" +"False" + +#: ../../library/stdtypes.rst:3506 ../../library/stdtypes.rst:3548 +#: ../../library/stdtypes.rst:3564 ../../library/stdtypes.rst:3614 +#: ../../library/stdtypes.rst:3683 msgid "" "Lowercase ASCII characters are those byte values in the sequence " "``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters are those byte " @@ -5238,7 +6329,7 @@ msgstr "" "aqueles cujos valores de bytes estão na sequência " "``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``." -#: ../../library/stdtypes.rst:3340 +#: ../../library/stdtypes.rst:3514 msgid "" "Return ``True`` if all bytes in the sequence are ASCII whitespace and the " "sequence is not empty, ``False`` otherwise. ASCII whitespace characters are " @@ -5251,7 +6342,7 @@ msgstr "" "\\t\\n\\r\\x0b\\f'`` (espaço, tabulação, nova linha, retorno do cursor, " "tabulação vertical, formulário de entrada)." -#: ../../library/stdtypes.rst:3349 +#: ../../library/stdtypes.rst:3523 msgid "" "Return ``True`` if the sequence is ASCII titlecase and the sequence is not " "empty, ``False`` otherwise. See :meth:`bytes.title` for more details on the " @@ -5261,7 +6352,19 @@ msgstr "" "vazia, ``False`` caso contrário. Veja :meth:`bytes.title` para mais detalhes " "sobre a definição de \"titlecased\"." -#: ../../library/stdtypes.rst:3364 +#: ../../library/stdtypes.rst:3529 +msgid "" +">>> b'Hello World'.istitle()\n" +"True\n" +">>> b'Hello world'.istitle()\n" +"False" +msgstr "" +">>> b'Hello World'.istitle()\n" +"True\n" +">>> b'Hello world'.istitle()\n" +"False" + +#: ../../library/stdtypes.rst:3538 msgid "" "Return ``True`` if there is at least one uppercase alphabetic ASCII " "character in the sequence and no lowercase ASCII characters, ``False`` " @@ -5271,7 +6374,19 @@ msgstr "" "ASCII na sequência e nenhum caractere minúsculo ASCII, ``False`` caso " "contrário." -#: ../../library/stdtypes.rst:3382 +#: ../../library/stdtypes.rst:3543 +msgid "" +">>> b'HELLO WORLD'.isupper()\n" +"True\n" +">>> b'Hello world'.isupper()\n" +"False" +msgstr "" +">>> b'HELLO WORLD'.isupper()\n" +"True\n" +">>> b'Hello world'.isupper()\n" +"False" + +#: ../../library/stdtypes.rst:3556 msgid "" "Return a copy of the sequence with all the uppercase ASCII characters " "converted to their corresponding lowercase counterpart." @@ -5279,7 +6394,15 @@ msgstr "" "Retorna uma cópia da sequência com todos os caracteres maiúsculos ASCII " "convertidos para os seus correspondentes caracteres minúsculos." -#: ../../library/stdtypes.rst:3407 +#: ../../library/stdtypes.rst:3561 +msgid "" +">>> b'Hello World'.lower()\n" +"b'hello world'" +msgstr "" +">>> b'Hello World'.lower()\n" +"b'hello world'" + +#: ../../library/stdtypes.rst:3581 msgid "" "Return a list of the lines in the binary sequence, breaking at ASCII line " "boundaries. This method uses the :term:`universal newlines` approach to " @@ -5292,7 +6415,19 @@ msgstr "" "não são incluídas na lista resultante a não ser que *keepends* seja " "fornecido e verdadeiro." -#: ../../library/stdtypes.rst:3419 +#: ../../library/stdtypes.rst:3588 +msgid "" +">>> b'ab c\\n\\nde fg\\rkl\\r\\n'.splitlines()\n" +"[b'ab c', b'', b'de fg', b'kl']\n" +">>> b'ab c\\n\\nde fg\\rkl\\r\\n'.splitlines(keepends=True)\n" +"[b'ab c\\n', b'\\n', b'de fg\\r', b'kl\\r\\n']" +msgstr "" +">>> b'ab c\\n\\nde fg\\rkl\\r\\n'.splitlines()\n" +"[b'ab c', b'', b'de fg', b'kl']\n" +">>> b'ab c\\n\\nde fg\\rkl\\r\\n'.splitlines(keepends=True)\n" +"[b'ab c\\n', b'\\n', b'de fg\\r', b'kl\\r\\n']" + +#: ../../library/stdtypes.rst:3593 msgid "" "Unlike :meth:`~bytes.split` when a delimiter string *sep* is given, this " "method returns an empty list for the empty string, and a terminal line break " @@ -5302,7 +6437,19 @@ msgstr "" "fornecida, este método retorna uma lista vazia para a string vazia, e uma " "quebra de linha terminal não resulta em uma linha extra::" -#: ../../library/stdtypes.rst:3432 +#: ../../library/stdtypes.rst:3597 +msgid "" +">>> b\"\".split(b'\\n'), b\"Two lines\\n\".split(b'\\n')\n" +"([b''], [b'Two lines', b''])\n" +">>> b\"\".splitlines(), b\"One line\\n\".splitlines()\n" +"([], [b'One line'])" +msgstr "" +">>> b\"\".split(b'\\n'), b\"Two lines\\n\".split(b'\\n')\n" +"([b''], [b'Two lines', b''])\n" +">>> b\"\".splitlines(), b\"One line\\n\".splitlines()\n" +"([], [b'One line'])" + +#: ../../library/stdtypes.rst:3606 msgid "" "Return a copy of the sequence with all the lowercase ASCII characters " "converted to their corresponding uppercase counterpart and vice-versa." @@ -5310,19 +6457,27 @@ msgstr "" "Retorna uma cópia da sequência com todos os caracteres minúsculos ASCII " "convertidos para caracteres maiúsculos correspondentes, e vice-versa." -#: ../../library/stdtypes.rst:3444 +#: ../../library/stdtypes.rst:3611 msgid "" -"Unlike :func:`str.swapcase()`, it is always the case that ``bin.swapcase()." +">>> b'Hello World'.swapcase()\n" +"b'hELLO wORLD'" +msgstr "" +">>> b'Hello World'.swapcase()\n" +"b'hELLO wORLD'" + +#: ../../library/stdtypes.rst:3618 +msgid "" +"Unlike :func:`str.swapcase`, it is always the case that ``bin.swapcase()." "swapcase() == bin`` for the binary versions. Case conversions are " "symmetrical in ASCII, even though that is not generally true for arbitrary " "Unicode code points." msgstr "" -"Ao contrário de :func:`str.swapcase()`, é sempre fato que ``bin.swapcase()." +"Ao contrário de :func:`str.swapcase`, é sempre fato que ``bin.swapcase()." "swapcase() == bin`` para as versões binárias. Conversões maiúsculas/" "minúsculas são simétricas em ASCII, apesar que isso não é geralmente verdade " -"para pontos de codificação arbitrários Unicode." +"para pontos de código arbitrários Unicode." -#: ../../library/stdtypes.rst:3458 +#: ../../library/stdtypes.rst:3632 msgid "" "Return a titlecased version of the binary sequence where words start with an " "uppercase ASCII character and the remaining characters are lowercase. " @@ -5333,7 +6488,15 @@ msgstr "" "letras minúsculas. Bytes quem não possuem diferença entre maiúscula/" "minúscula não são alterados." -#: ../../library/stdtypes.rst:3467 +#: ../../library/stdtypes.rst:3638 +msgid "" +">>> b'Hello world'.title()\n" +"b'Hello World'" +msgstr "" +">>> b'Hello world'.title()\n" +"b'Hello World'" + +#: ../../library/stdtypes.rst:3641 msgid "" "Lowercase ASCII characters are those byte values in the sequence " "``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters are those byte " @@ -5346,14 +6509,44 @@ msgstr "" "``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. Todos os outros valores de bytes ignoram " "maiúsculas/minúsculas." -#: ../../library/stdtypes.rst:3480 +#: ../../library/stdtypes.rst:3651 +msgid "" +">>> b\"they're bill's friends from the UK\".title()\n" +"b\"They'Re Bill'S Friends From The Uk\"" +msgstr "" +">>> b\"they're bill's friends from the UK\".title()\n" +"b\"They'Re Bill'S Friends From The Uk\"" + +#: ../../library/stdtypes.rst:3654 msgid "" "A workaround for apostrophes can be constructed using regular expressions::" msgstr "" "Uma solução alternativa para os apóstrofes pode ser construída usando " "expressões regulares::" -#: ../../library/stdtypes.rst:3501 +#: ../../library/stdtypes.rst:3656 +msgid "" +">>> import re\n" +">>> def titlecase(s):\n" +"... return re.sub(rb\"[A-Za-z]+('[A-Za-z]+)?\",\n" +"... lambda mo: mo.group(0)[0:1].upper() +\n" +"... mo.group(0)[1:].lower(),\n" +"... s)\n" +"...\n" +">>> titlecase(b\"they're bill's friends.\")\n" +"b\"They're Bill's Friends.\"" +msgstr "" +">>> import re\n" +">>> def titlecase(s):\n" +"... return re.sub(rb\"[A-Za-z]+('[A-Za-z]+)?\",\n" +"... lambda mo: mo.group(0)[0:1].upper() +\n" +"... mo.group(0)[1:].lower(),\n" +"... s)\n" +"...\n" +">>> titlecase(b\"they're bill's friends.\")\n" +"b\"They're Bill's Friends.\"" + +#: ../../library/stdtypes.rst:3675 msgid "" "Return a copy of the sequence with all the lowercase ASCII characters " "converted to their corresponding uppercase counterpart." @@ -5361,7 +6554,15 @@ msgstr "" "Retorna uma cópia da sequência com todos os caracteres minúsculos ASCII " "convertidos para sua contraparte maiúscula correspondente." -#: ../../library/stdtypes.rst:3522 +#: ../../library/stdtypes.rst:3680 +msgid "" +">>> b'Hello World'.upper()\n" +"b'HELLO WORLD'" +msgstr "" +">>> b'Hello World'.upper()\n" +"b'HELLO WORLD'" + +#: ../../library/stdtypes.rst:3696 msgid "" "Return a copy of the sequence left filled with ASCII ``b'0'`` digits to make " "a sequence of length *width*. A leading sign prefix (``b'+'``/ ``b'-'``) is " @@ -5376,11 +6577,23 @@ msgstr "" "objetos :class:`bytes`, a sequência original é retornada se *width* é menor " "que ou igual a ``len(seq)``." -#: ../../library/stdtypes.rst:3544 +#: ../../library/stdtypes.rst:3704 +msgid "" +">>> b\"42\".zfill(5)\n" +"b'00042'\n" +">>> b\"-42\".zfill(5)\n" +"b'-0042'" +msgstr "" +">>> b\"42\".zfill(5)\n" +"b'00042'\n" +">>> b\"-42\".zfill(5)\n" +"b'-0042'" + +#: ../../library/stdtypes.rst:3718 msgid "``printf``-style Bytes Formatting" msgstr "Estilo de Formatação de bytes ``printf``-style" -#: ../../library/stdtypes.rst:3561 +#: ../../library/stdtypes.rst:3735 msgid "" "The formatting operations described here exhibit a variety of quirks that " "lead to a number of common errors (such as failing to display tuples and " @@ -5392,7 +6605,7 @@ msgstr "" "exibição de Tuplas e Dicionários corretamente). Se o valor que está sendo " "impresso puder ser uma tupla ou dicionário, envolva-o numa tupla." -#: ../../library/stdtypes.rst:3566 +#: ../../library/stdtypes.rst:3740 msgid "" "Bytes objects (``bytes``/``bytearray``) have one unique built-in operation: " "the ``%`` operator (modulo). This is also known as the bytes *formatting* or " @@ -5408,7 +6621,7 @@ msgstr "" "*format* são substituídas por zero ou mais elementos de *values*. O efeito é " "semelhante ao uso da função :c:func:`sprintf` na linguagem C." -#: ../../library/stdtypes.rst:3573 +#: ../../library/stdtypes.rst:3747 msgid "" "If *format* requires a single argument, *values* may be a single non-tuple " "object. [5]_ Otherwise, *values* must be a tuple with exactly the number of " @@ -5420,7 +6633,7 @@ msgstr "" "o número de itens especificados pelo objeto de formatação de Bytes, ou um " "único objeto de mapeamento (por exemplo, um dicionário)." -#: ../../library/stdtypes.rst:3607 +#: ../../library/stdtypes.rst:3781 msgid "" "When the right argument is a dictionary (or other mapping type), then the " "formats in the bytes object *must* include a parenthesised mapping key into " @@ -5433,15 +6646,15 @@ msgstr "" "O mapeamento de chaves seleciona o valor a ser formatado a partir do " "mapeamento. Por exemplo:" -#: ../../library/stdtypes.rst:3681 +#: ../../library/stdtypes.rst:3855 msgid "Single byte (accepts integer or single byte objects)." msgstr "Byte simples (aceita objetos inteiros ou de byte único)." -#: ../../library/stdtypes.rst:3684 +#: ../../library/stdtypes.rst:3858 msgid "``'b'``" msgstr "``'b'``" -#: ../../library/stdtypes.rst:3684 +#: ../../library/stdtypes.rst:3858 msgid "" "Bytes (any object that follows the :ref:`buffer protocol ` or " "has :meth:`~object.__bytes__`)." @@ -5449,7 +6662,7 @@ msgstr "" "Bytes (qualquer objeto que segue o :ref:`buffer protocol ` o " "que possui :meth:`~object.__bytes__`)." -#: ../../library/stdtypes.rst:3688 +#: ../../library/stdtypes.rst:3862 msgid "" "``'s'`` is an alias for ``'b'`` and should only be used for Python2/3 code " "bases." @@ -5457,7 +6670,7 @@ msgstr "" "``'s'`` é um alias para ``'b'`` e só deve ser usado para bases de código " "Python2/3." -#: ../../library/stdtypes.rst:3691 +#: ../../library/stdtypes.rst:3865 msgid "" "Bytes (converts any Python object using ``repr(obj).encode('ascii', " "'backslashreplace')``)." @@ -5465,7 +6678,7 @@ msgstr "" "Bytes (converte qualquer objeto Python usando ``repr(obj).encode('ascii', " "'backslashreplace')``)." -#: ../../library/stdtypes.rst:3694 +#: ../../library/stdtypes.rst:3868 msgid "" "``'r'`` is an alias for ``'a'`` and should only be used for Python2/3 code " "bases." @@ -5473,28 +6686,28 @@ msgstr "" "``'r'`` é um alias para ``'a'`` e só deve ser usado para bases de código " "Python2/3." -#: ../../library/stdtypes.rst:3694 +#: ../../library/stdtypes.rst:3868 msgid "\\(7)" msgstr "\\(7)" -#: ../../library/stdtypes.rst:3729 +#: ../../library/stdtypes.rst:3903 msgid "``b'%s'`` is deprecated, but will not be removed during the 3.x series." msgstr "" "``b'%s'`` está descontinuado, mas não será removido durante a versão 3.x." -#: ../../library/stdtypes.rst:3732 +#: ../../library/stdtypes.rst:3906 msgid "``b'%r'`` is deprecated, but will not be removed during the 3.x series." msgstr "``b'%r'`` entrou em desuso, mas não serão removidos na versão 3.x." -#: ../../library/stdtypes.rst:3744 +#: ../../library/stdtypes.rst:3918 msgid ":pep:`461` - Adding % formatting to bytes and bytearray" msgstr ":pep:`461` - Adicionar formatação % para to bytes e bytearray" -#: ../../library/stdtypes.rst:3751 +#: ../../library/stdtypes.rst:3925 msgid "Memory Views" msgstr "Memory Views" -#: ../../library/stdtypes.rst:3753 +#: ../../library/stdtypes.rst:3927 msgid "" ":class:`memoryview` objects allow Python code to access the internal data of " "an object that supports the :ref:`buffer protocol ` without " @@ -5504,7 +6717,7 @@ msgstr "" "internos de um objeto que suporte o :ref:`buffer protocol ` " "sem copiá-lo." -#: ../../library/stdtypes.rst:3759 +#: ../../library/stdtypes.rst:3933 msgid "" "Create a :class:`memoryview` that references *object*. *object* must " "support the buffer protocol. Built-in objects that support the buffer " @@ -5514,7 +6727,7 @@ msgstr "" "suporte ao protocolo de buffer. Objetos embutidos que suportam o protocolo " "de buffer incluem :class:`bytes` e :class:`bytearray`." -#: ../../library/stdtypes.rst:3763 +#: ../../library/stdtypes.rst:3937 msgid "" "A :class:`memoryview` has the notion of an *element*, which is the atomic " "memory unit handled by the originating *object*. For many simple types such " @@ -5527,7 +6740,7 @@ msgstr "" "único, mas outros tipos tais como :class:`array.array` podem ter elementos " "maiores." -#: ../../library/stdtypes.rst:3768 +#: ../../library/stdtypes.rst:3942 msgid "" "``len(view)`` is equal to the length of :class:`~memoryview.tolist`, which " "is the nested list representation of the view. If ``view.ndim = 1``, this is " @@ -5537,7 +6750,7 @@ msgstr "" "representação de lista aninhada da view. Se ``view.ndim = 1``, isso é igual " "ao número de elementos na visualização." -#: ../../library/stdtypes.rst:3772 +#: ../../library/stdtypes.rst:3946 msgid "" "If ``view.ndim == 0``, ``len(view)`` now raises :exc:`TypeError` instead of " "returning 1." @@ -5545,7 +6758,7 @@ msgstr "" "Se ``view.ndim == 0``, ``len(view)`` agora levanta :exc:`TypeError` em vez " "de retornar 1." -#: ../../library/stdtypes.rst:3775 +#: ../../library/stdtypes.rst:3949 msgid "" "The :class:`~memoryview.itemsize` attribute will give you the number of " "bytes in a single element." @@ -5553,7 +6766,7 @@ msgstr "" "O atributo :class:`~memoryview.itemsize` vai lhe dar um número de bytes em " "um único elemento." -#: ../../library/stdtypes.rst:3778 +#: ../../library/stdtypes.rst:3952 msgid "" "A :class:`memoryview` supports slicing and indexing to expose its data. One-" "dimensional slicing will result in a subview::" @@ -5561,7 +6774,29 @@ msgstr "" "Um :class:`memoryview` suporta fatiamento e indexação para expor seus dados. " "Fatiamento unidimensional irá resultar em uma subview::" -#: ../../library/stdtypes.rst:3791 +#: ../../library/stdtypes.rst:3955 +msgid "" +">>> v = memoryview(b'abcefg')\n" +">>> v[1]\n" +"98\n" +">>> v[-1]\n" +"103\n" +">>> v[1:4]\n" +"\n" +">>> bytes(v[1:4])\n" +"b'bce'" +msgstr "" +">>> v = memoryview(b'abcefg')\n" +">>> v[1]\n" +"98\n" +">>> v[-1]\n" +"103\n" +">>> v[1:4]\n" +"\n" +">>> bytes(v[1:4])\n" +"b'bce'" + +#: ../../library/stdtypes.rst:3965 msgid "" "If :class:`~memoryview.format` is one of the native format specifiers from " "the :mod:`struct` module, indexing with an integer or a tuple of integers is " @@ -5580,11 +6815,33 @@ msgstr "" "de dimensões. Memoryviews zero-dimensionais podem ser indexadas com uma " "tupla vazia." -#: ../../library/stdtypes.rst:3800 +#: ../../library/stdtypes.rst:3974 msgid "Here is an example with a non-byte format::" msgstr "Aqui temos um exemplo usando um formato não-byte::" -#: ../../library/stdtypes.rst:3812 +#: ../../library/stdtypes.rst:3976 +msgid "" +">>> import array\n" +">>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444])\n" +">>> m = memoryview(a)\n" +">>> m[0]\n" +"-11111111\n" +">>> m[-1]\n" +"44444444\n" +">>> m[::2].tolist()\n" +"[-11111111, -33333333]" +msgstr "" +">>> import array\n" +">>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444])\n" +">>> m = memoryview(a)\n" +">>> m[0]\n" +"-11111111\n" +">>> m[-1]\n" +"44444444\n" +">>> m[::2].tolist()\n" +"[-11111111, -33333333]" + +#: ../../library/stdtypes.rst:3986 msgid "" "If the underlying object is writable, the memoryview supports one-" "dimensional slice assignment. Resizing is not allowed::" @@ -5592,7 +6849,47 @@ msgstr "" "Se o objeto subjacente é gravável, a memoryview suporta atribuição de fatias " "unidimensionais. Redimensionamento não é permitido::" -#: ../../library/stdtypes.rst:3833 +#: ../../library/stdtypes.rst:3989 +msgid "" +">>> data = bytearray(b'abcefg')\n" +">>> v = memoryview(data)\n" +">>> v.readonly\n" +"False\n" +">>> v[0] = ord(b'z')\n" +">>> data\n" +"bytearray(b'zbcefg')\n" +">>> v[1:4] = b'123'\n" +">>> data\n" +"bytearray(b'z123fg')\n" +">>> v[2:3] = b'spam'\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: memoryview assignment: lvalue and rvalue have different " +"structures\n" +">>> v[2:6] = b'spam'\n" +">>> data\n" +"bytearray(b'z1spam')" +msgstr "" +">>> data = bytearray(b'abcefg')\n" +">>> v = memoryview(data)\n" +">>> v.readonly\n" +"False\n" +">>> v[0] = ord(b'z')\n" +">>> data\n" +"bytearray(b'zbcefg')\n" +">>> v[1:4] = b'123'\n" +">>> data\n" +"bytearray(b'z123fg')\n" +">>> v[2:3] = b'spam'\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: memoryview assignment: lvalue and rvalue have different " +"structures\n" +">>> v[2:6] = b'spam'\n" +">>> data\n" +"bytearray(b'z1spam')" + +#: ../../library/stdtypes.rst:4007 msgid "" "One-dimensional memoryviews of :term:`hashable` (read-only) types with " "formats 'B', 'b' or 'c' are also hashable. The hash is defined as ``hash(m) " @@ -5602,7 +6899,25 @@ msgstr "" "leitura) com formatos 'B', 'b' ou 'c' também são hasheáveis. O hash é " "definido como ``hash(m) == hash(m.tobytes())``::" -#: ../../library/stdtypes.rst:3845 +#: ../../library/stdtypes.rst:4011 +msgid "" +">>> v = memoryview(b'abcefg')\n" +">>> hash(v) == hash(b'abcefg')\n" +"True\n" +">>> hash(v[2:4]) == hash(b'ce')\n" +"True\n" +">>> hash(v[::-2]) == hash(b'abcefg'[::-2])\n" +"True" +msgstr "" +">>> v = memoryview(b'abcefg')\n" +">>> hash(v) == hash(b'abcefg')\n" +"True\n" +">>> hash(v[2:4]) == hash(b'ce')\n" +"True\n" +">>> hash(v[::-2]) == hash(b'abcefg'[::-2])\n" +"True" + +#: ../../library/stdtypes.rst:4019 msgid "" "One-dimensional memoryviews can now be sliced. One-dimensional memoryviews " "with formats 'B', 'b' or 'c' are now :term:`hashable`." @@ -5611,7 +6926,7 @@ msgstr "" "unidimensionais com formatos 'B', 'b' ou 'c' agora são :term:`hasheáveis " "`." -#: ../../library/stdtypes.rst:3849 +#: ../../library/stdtypes.rst:4023 msgid "" "memoryview is now registered automatically with :class:`collections.abc." "Sequence`" @@ -5619,17 +6934,17 @@ msgstr "" "O memoryview agora é registrado automaticamente como uma classe :class:" "`collections.abc.Sequence`" -#: ../../library/stdtypes.rst:3853 +#: ../../library/stdtypes.rst:4027 msgid "memoryviews can now be indexed with tuple of integers." msgstr "" "Atualmente, os memoryvies podem ser indexadas com uma tupla de números " "inteiros." -#: ../../library/stdtypes.rst:3856 +#: ../../library/stdtypes.rst:4030 msgid ":class:`memoryview` has several methods:" msgstr ":class:`memoryview` possui vários métodos:" -#: ../../library/stdtypes.rst:3860 +#: ../../library/stdtypes.rst:4034 msgid "" "A memoryview and a :pep:`3118` exporter are equal if their shapes are " "equivalent and if all corresponding values are equal when the operands' " @@ -5640,7 +6955,7 @@ msgstr "" "códigos de formatação dos respectivos operadores são interpretados usando a " "sintaxe :mod:`struct`." -#: ../../library/stdtypes.rst:3864 +#: ../../library/stdtypes.rst:4038 msgid "" "For the subset of :mod:`struct` format strings currently supported by :meth:" "`tolist`, ``v`` and ``w`` are equal if ``v.tolist() == w.tolist()``::" @@ -5649,7 +6964,41 @@ msgstr "" "suportadas por :meth:`tolist`, ``v`` e ``w`` são iguais se ``v.tolist() == w." "tolist()``::" -#: ../../library/stdtypes.rst:3883 +#: ../../library/stdtypes.rst:4041 +msgid "" +">>> import array\n" +">>> a = array.array('I', [1, 2, 3, 4, 5])\n" +">>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0])\n" +">>> c = array.array('b', [5, 3, 1])\n" +">>> x = memoryview(a)\n" +">>> y = memoryview(b)\n" +">>> x == a == y == b\n" +"True\n" +">>> x.tolist() == a.tolist() == y.tolist() == b.tolist()\n" +"True\n" +">>> z = y[::-2]\n" +">>> z == c\n" +"True\n" +">>> z.tolist() == c.tolist()\n" +"True" +msgstr "" +">>> import array\n" +">>> a = array.array('I', [1, 2, 3, 4, 5])\n" +">>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0])\n" +">>> c = array.array('b', [5, 3, 1])\n" +">>> x = memoryview(a)\n" +">>> y = memoryview(b)\n" +">>> x == a == y == b\n" +"True\n" +">>> x.tolist() == a.tolist() == y.tolist() == b.tolist()\n" +"True\n" +">>> z = y[::-2]\n" +">>> z == c\n" +"True\n" +">>> z.tolist() == c.tolist()\n" +"True" + +#: ../../library/stdtypes.rst:4057 msgid "" "If either format string is not supported by the :mod:`struct` module, then " "the objects will always compare as unequal (even if the format strings and " @@ -5659,7 +7008,33 @@ msgstr "" "`struct`, então os objetos irão sempre comparar como diferentes (mesmo se as " "strings de formatação e o conteúdo do buffer são idênticos)::" -#: ../../library/stdtypes.rst:3899 +#: ../../library/stdtypes.rst:4061 +msgid "" +">>> from ctypes import BigEndianStructure, c_long\n" +">>> class BEPoint(BigEndianStructure):\n" +"... _fields_ = [(\"x\", c_long), (\"y\", c_long)]\n" +"...\n" +">>> point = BEPoint(100, 200)\n" +">>> a = memoryview(point)\n" +">>> b = memoryview(point)\n" +">>> a == point\n" +"False\n" +">>> a == b\n" +"False" +msgstr "" +">>> from ctypes import BigEndianStructure, c_long\n" +">>> class BEPoint(BigEndianStructure):\n" +"... _fields_ = [(\"x\", c_long), (\"y\", c_long)]\n" +"...\n" +">>> point = BEPoint(100, 200)\n" +">>> a = memoryview(point)\n" +">>> b = memoryview(point)\n" +">>> a == point\n" +"False\n" +">>> a == b\n" +"False" + +#: ../../library/stdtypes.rst:4073 msgid "" "Note that, as with floating-point numbers, ``v is w`` does *not* imply ``v " "== w`` for memoryview objects." @@ -5667,7 +7042,7 @@ msgstr "" "Perceba que, assim como com números de ponto flutuante, ``v is w`` *não* " "implica em ``v == w`` para objetos memoryview." -#: ../../library/stdtypes.rst:3902 +#: ../../library/stdtypes.rst:4076 msgid "" "Previous versions compared the raw memory disregarding the item format and " "the logical array structure." @@ -5675,7 +7050,7 @@ msgstr "" "Versões anteriores comparavam a memória bruta desconsiderando o formato do " "item e estrutura lógica do array." -#: ../../library/stdtypes.rst:3908 +#: ../../library/stdtypes.rst:4082 msgid "" "Return the data in the buffer as a bytestring. This is equivalent to " "calling the :class:`bytes` constructor on the memoryview. ::" @@ -5683,7 +7058,21 @@ msgstr "" "Retorna os dados no buffer como um bytestring. Isso é equivalente a chamar o " "construtor de :class:`bytes` na memoryview. ::" -#: ../../library/stdtypes.rst:3917 +#: ../../library/stdtypes.rst:4085 +msgid "" +">>> m = memoryview(b\"abc\")\n" +">>> m.tobytes()\n" +"b'abc'\n" +">>> bytes(m)\n" +"b'abc'" +msgstr "" +">>> m = memoryview(b\"abc\")\n" +">>> m.tobytes()\n" +"b'abc'\n" +">>> bytes(m)\n" +"b'abc'" + +#: ../../library/stdtypes.rst:4091 msgid "" "For non-contiguous arrays the result is equal to the flattened list " "representation with all elements converted to bytes. :meth:`tobytes` " @@ -5695,7 +7084,7 @@ msgstr "" "suporta todos os formatos de strings, incluindo aqueles que não estão na " "sintaxe do módulo :mod:`struct`." -#: ../../library/stdtypes.rst:3922 +#: ../../library/stdtypes.rst:4096 msgid "" "*order* can be {'C', 'F', 'A'}. When *order* is 'C' or 'F', the data of the " "original array is converted to C or Fortran order. For contiguous views, 'A' " @@ -5709,7 +7098,7 @@ msgstr "" "ordem de Fortran em memória é preservada. Para views não contígua, os dados " "são convertidos primeiro para C. *order=None* é o mesmo que *order='C'*." -#: ../../library/stdtypes.rst:3931 +#: ../../library/stdtypes.rst:4105 msgid "" "Return a string object containing two hexadecimal digits for each byte in " "the buffer. ::" @@ -5717,7 +7106,17 @@ msgstr "" "Retorna um objeto string contendo dois dígitos hexadecimais para cada byte " "no buffer. ::" -#: ../../library/stdtypes.rst:3940 +#: ../../library/stdtypes.rst:4108 +msgid "" +">>> m = memoryview(b\"abc\")\n" +">>> m.hex()\n" +"'616263'" +msgstr "" +">>> m = memoryview(b\"abc\")\n" +">>> m.hex()\n" +"'616263'" + +#: ../../library/stdtypes.rst:4114 msgid "" "Similar to :meth:`bytes.hex`, :meth:`memoryview.hex` now supports optional " "*sep* and *bytes_per_sep* parameters to insert separators between bytes in " @@ -5727,11 +7126,29 @@ msgstr "" "parâmetros opcionais *sep* e *bytes_per_sep* para inserir separadores entre " "bytes na saída hexadecimal." -#: ../../library/stdtypes.rst:3947 +#: ../../library/stdtypes.rst:4121 msgid "Return the data in the buffer as a list of elements. ::" msgstr "Retorna os dados no buffer como uma lista de elementos. ::" -#: ../../library/stdtypes.rst:3957 +#: ../../library/stdtypes.rst:4123 +msgid "" +">>> memoryview(b'abc').tolist()\n" +"[97, 98, 99]\n" +">>> import array\n" +">>> a = array.array('d', [1.1, 2.2, 3.3])\n" +">>> m = memoryview(a)\n" +">>> m.tolist()\n" +"[1.1, 2.2, 3.3]" +msgstr "" +">>> memoryview(b'abc').tolist()\n" +"[97, 98, 99]\n" +">>> import array\n" +">>> a = array.array('d', [1.1, 2.2, 3.3])\n" +">>> m = memoryview(a)\n" +">>> m.tolist()\n" +"[1.1, 2.2, 3.3]" + +#: ../../library/stdtypes.rst:4131 msgid "" ":meth:`tolist` now supports all single character native formats in :mod:" "`struct` module syntax as well as multi-dimensional representations." @@ -5740,7 +7157,7 @@ msgstr "" "na sintaxe do módulo :mod:`struct`, assim como representações multi-" "dimensionais." -#: ../../library/stdtypes.rst:3964 +#: ../../library/stdtypes.rst:4138 msgid "" "Return a readonly version of the memoryview object. The original memoryview " "object is unchanged. ::" @@ -5748,7 +7165,33 @@ msgstr "" "Retorna uma versão somente leitura do objeto memoryview. O objeto memoryview " "original não é alterado. ::" -#: ../../library/stdtypes.rst:3983 +#: ../../library/stdtypes.rst:4141 +msgid "" +">>> m = memoryview(bytearray(b'abc'))\n" +">>> mm = m.toreadonly()\n" +">>> mm.tolist()\n" +"[97, 98, 99]\n" +">>> mm[0] = 42\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: cannot modify read-only memory\n" +">>> m[0] = 43\n" +">>> mm.tolist()\n" +"[43, 98, 99]" +msgstr "" +">>> m = memoryview(bytearray(b'abc'))\n" +">>> mm = m.toreadonly()\n" +">>> mm.tolist()\n" +"[97, 98, 99]\n" +">>> mm[0] = 42\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: cannot modify read-only memory\n" +">>> m[0] = 43\n" +">>> mm.tolist()\n" +"[43, 98, 99]" + +#: ../../library/stdtypes.rst:4157 msgid "" "Release the underlying buffer exposed by the memoryview object. Many " "objects take special actions when a view is held on them (for example, a :" @@ -5762,17 +7205,33 @@ msgstr "" "portanto, chamar release() é útil para remover essas restrições (e liberar " "quaisquer recursos pendurados) o mais breve possível." -#: ../../library/stdtypes.rst:3989 +#: ../../library/stdtypes.rst:4163 msgid "" "After this method has been called, any further operation on the view raises " -"a :class:`ValueError` (except :meth:`release()` itself which can be called " +"a :class:`ValueError` (except :meth:`release` itself which can be called " "multiple times)::" msgstr "" "Depois que este método foi chamado, qualquer operação posterior na visão " -"levanta um :class:`ValueError` (exceto :meth:`release()`, o qual pode ser " +"levanta um :class:`ValueError` (exceto :meth:`release`, o qual pode ser " "chamado múltiplas vezes)::" -#: ../../library/stdtypes.rst:4000 +#: ../../library/stdtypes.rst:4167 +msgid "" +">>> m = memoryview(b'abc')\n" +">>> m.release()\n" +">>> m[0]\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: operation forbidden on released memoryview object" +msgstr "" +">>> m = memoryview(b'abc')\n" +">>> m.release()\n" +">>> m[0]\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: operation forbidden on released memoryview object" + +#: ../../library/stdtypes.rst:4174 msgid "" "The context management protocol can be used for a similar effect, using the " "``with`` statement::" @@ -5780,7 +7239,27 @@ msgstr "" "O protocolo de gerenciamento de contexto pode ser usado para efeitos " "similares, usando a instrução ``with``::" -#: ../../library/stdtypes.rst:4016 +#: ../../library/stdtypes.rst:4177 +msgid "" +">>> with memoryview(b'abc') as m:\n" +"... m[0]\n" +"...\n" +"97\n" +">>> m[0]\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: operation forbidden on released memoryview object" +msgstr "" +">>> with memoryview(b'abc') as m:\n" +"... m[0]\n" +"...\n" +"97\n" +">>> m[0]\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: operation forbidden on released memoryview object" + +#: ../../library/stdtypes.rst:4190 msgid "" "Cast a memoryview to a new format or shape. *shape* defaults to " "``[byte_length//new_itemsize]``, which means that the result view will be " @@ -5794,7 +7273,7 @@ msgstr "" "si mesmo não é copiado. Conversões suportadas são 1D -> C-:term:`contíguo " "` r C-contíguo -> 1D." -#: ../../library/stdtypes.rst:4022 +#: ../../library/stdtypes.rst:4196 msgid "" "The destination format is restricted to a single element native format in :" "mod:`struct` syntax. One of the formats must be a byte format ('B', 'b' or " @@ -5807,36 +7286,188 @@ msgstr "" "original. Observe que todos os comprimentos de bytes podem depender do " "sistema operacional." -#: ../../library/stdtypes.rst:4028 +#: ../../library/stdtypes.rst:4202 msgid "Cast 1D/long to 1D/unsigned bytes::" msgstr "Converte de 1D/long para 1D/unsigned bytes::" -#: ../../library/stdtypes.rst:4051 +#: ../../library/stdtypes.rst:4204 +msgid "" +">>> import array\n" +">>> a = array.array('l', [1,2,3])\n" +">>> x = memoryview(a)\n" +">>> x.format\n" +"'l'\n" +">>> x.itemsize\n" +"8\n" +">>> len(x)\n" +"3\n" +">>> x.nbytes\n" +"24\n" +">>> y = x.cast('B')\n" +">>> y.format\n" +"'B'\n" +">>> y.itemsize\n" +"1\n" +">>> len(y)\n" +"24\n" +">>> y.nbytes\n" +"24" +msgstr "" +">>> import array\n" +">>> a = array.array('l', [1,2,3])\n" +">>> x = memoryview(a)\n" +">>> x.format\n" +"'l'\n" +">>> x.itemsize\n" +"8\n" +">>> len(x)\n" +"3\n" +">>> x.nbytes\n" +"24\n" +">>> y = x.cast('B')\n" +">>> y.format\n" +"'B'\n" +">>> y.itemsize\n" +"1\n" +">>> len(y)\n" +"24\n" +">>> y.nbytes\n" +"24" + +#: ../../library/stdtypes.rst:4225 msgid "Cast 1D/unsigned bytes to 1D/char::" msgstr "Converte de 1D/unsigned bytes para 1D/char::" -#: ../../library/stdtypes.rst:4064 +#: ../../library/stdtypes.rst:4227 +msgid "" +">>> b = bytearray(b'zyz')\n" +">>> x = memoryview(b)\n" +">>> x[0] = b'a'\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: memoryview: invalid type for format 'B'\n" +">>> y = x.cast('c')\n" +">>> y[0] = b'a'\n" +">>> b\n" +"bytearray(b'ayz')" +msgstr "" +">>> b = bytearray(b'zyz')\n" +">>> x = memoryview(b)\n" +">>> x[0] = b'a'\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: memoryview: invalid type for format 'B'\n" +">>> y = x.cast('c')\n" +">>> y[0] = b'a'\n" +">>> b\n" +"bytearray(b'ayz')" + +#: ../../library/stdtypes.rst:4238 msgid "Cast 1D/bytes to 3D/ints to 1D/signed char::" msgstr "Converte de 1D/bytes para 3D/ints para 1D/signed char::" -#: ../../library/stdtypes.rst:4090 +#: ../../library/stdtypes.rst:4240 +msgid "" +">>> import struct\n" +">>> buf = struct.pack(\"i\"*12, *list(range(12)))\n" +">>> x = memoryview(buf)\n" +">>> y = x.cast('i', shape=[2,2,3])\n" +">>> y.tolist()\n" +"[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]\n" +">>> y.format\n" +"'i'\n" +">>> y.itemsize\n" +"4\n" +">>> len(y)\n" +"2\n" +">>> y.nbytes\n" +"48\n" +">>> z = y.cast('b')\n" +">>> z.format\n" +"'b'\n" +">>> z.itemsize\n" +"1\n" +">>> len(z)\n" +"48\n" +">>> z.nbytes\n" +"48" +msgstr "" +">>> import struct\n" +">>> buf = struct.pack(\"i\"*12, *list(range(12)))\n" +">>> x = memoryview(buf)\n" +">>> y = x.cast('i', shape=[2,2,3])\n" +">>> y.tolist()\n" +"[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]\n" +">>> y.format\n" +"'i'\n" +">>> y.itemsize\n" +"4\n" +">>> len(y)\n" +"2\n" +">>> y.nbytes\n" +"48\n" +">>> z = y.cast('b')\n" +">>> z.format\n" +"'b'\n" +">>> z.itemsize\n" +"1\n" +">>> len(z)\n" +"48\n" +">>> z.nbytes\n" +"48" + +#: ../../library/stdtypes.rst:4264 msgid "Cast 1D/unsigned long to 2D/unsigned long::" msgstr "Converte 1D/unsigned long para 2D/unsigned long::" -#: ../../library/stdtypes.rst:4104 +#: ../../library/stdtypes.rst:4266 +msgid "" +">>> buf = struct.pack(\"L\"*6, *list(range(6)))\n" +">>> x = memoryview(buf)\n" +">>> y = x.cast('L', shape=[2,3])\n" +">>> len(y)\n" +"2\n" +">>> y.nbytes\n" +"48\n" +">>> y.tolist()\n" +"[[0, 1, 2], [3, 4, 5]]" +msgstr "" +">>> buf = struct.pack(\"L\"*6, *list(range(6)))\n" +">>> x = memoryview(buf)\n" +">>> y = x.cast('L', shape=[2,3])\n" +">>> len(y)\n" +"2\n" +">>> y.nbytes\n" +"48\n" +">>> y.tolist()\n" +"[[0, 1, 2], [3, 4, 5]]" + +#: ../../library/stdtypes.rst:4278 msgid "The source format is no longer restricted when casting to a byte view." msgstr "" "O formato fonte não é mais restrito ao converter para uma visão de byte." -#: ../../library/stdtypes.rst:4107 +#: ../../library/stdtypes.rst:4281 msgid "There are also several readonly attributes available:" msgstr "Existem também diversos atributos somente leitura disponíveis:" -#: ../../library/stdtypes.rst:4111 +#: ../../library/stdtypes.rst:4285 msgid "The underlying object of the memoryview::" msgstr "O objeto subjacente da memoryview::" -#: ../../library/stdtypes.rst:4122 +#: ../../library/stdtypes.rst:4287 +msgid "" +">>> b = bytearray(b'xyz')\n" +">>> m = memoryview(b)\n" +">>> m.obj is b\n" +"True" +msgstr "" +">>> b = bytearray(b'xyz')\n" +">>> m = memoryview(b)\n" +">>> m.obj is b\n" +"True" + +#: ../../library/stdtypes.rst:4296 msgid "" "``nbytes == product(shape) * itemsize == len(m.tobytes())``. This is the " "amount of space in bytes that the array would use in a contiguous " @@ -5846,15 +7477,71 @@ msgstr "" "quantidade de espaço em bytes que o array deve usar em uma representação " "contígua. Ela não é necessariamente igual a ``len(m)``::" -#: ../../library/stdtypes.rst:4141 +#: ../../library/stdtypes.rst:4300 +msgid "" +">>> import array\n" +">>> a = array.array('i', [1,2,3,4,5])\n" +">>> m = memoryview(a)\n" +">>> len(m)\n" +"5\n" +">>> m.nbytes\n" +"20\n" +">>> y = m[::2]\n" +">>> len(y)\n" +"3\n" +">>> y.nbytes\n" +"12\n" +">>> len(y.tobytes())\n" +"12" +msgstr "" +">>> import array\n" +">>> a = array.array('i', [1,2,3,4,5])\n" +">>> m = memoryview(a)\n" +">>> len(m)\n" +"5\n" +">>> m.nbytes\n" +"20\n" +">>> y = m[::2]\n" +">>> len(y)\n" +"3\n" +">>> y.nbytes\n" +"12\n" +">>> len(y.tobytes())\n" +"12" + +#: ../../library/stdtypes.rst:4315 msgid "Multi-dimensional arrays::" msgstr "Arrays Multi-dimensional::" -#: ../../library/stdtypes.rst:4158 +#: ../../library/stdtypes.rst:4317 +msgid "" +">>> import struct\n" +">>> buf = struct.pack(\"d\"*12, *[1.5*x for x in range(12)])\n" +">>> x = memoryview(buf)\n" +">>> y = x.cast('d', shape=[3,4])\n" +">>> y.tolist()\n" +"[[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]]\n" +">>> len(y)\n" +"3\n" +">>> y.nbytes\n" +"96" +msgstr "" +">>> import struct\n" +">>> buf = struct.pack(\"d\"*12, *[1.5*x for x in range(12)])\n" +">>> x = memoryview(buf)\n" +">>> y = x.cast('d', shape=[3,4])\n" +">>> y.tolist()\n" +"[[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]]\n" +">>> len(y)\n" +"3\n" +">>> y.nbytes\n" +"96" + +#: ../../library/stdtypes.rst:4332 msgid "A bool indicating whether the memory is read only." msgstr "Um bool que indica se a memória é somente leitura." -#: ../../library/stdtypes.rst:4162 +#: ../../library/stdtypes.rst:4336 msgid "" "A string containing the format (in :mod:`struct` module style) for each " "element in the view. A memoryview can be created from exporters with " @@ -5866,7 +7553,7 @@ msgstr "" "com strings de formato arbitrário, mas alguns métodos (ex: :meth:`tolist`) " "são restritos a formatos de elementos nativos." -#: ../../library/stdtypes.rst:4167 +#: ../../library/stdtypes.rst:4341 msgid "" "format ``'B'`` is now handled according to the struct module syntax. This " "means that ``memoryview(b'abc')[0] == b'abc'[0] == 97``." @@ -5874,11 +7561,31 @@ msgstr "" "formato ``'B'`` agora é tratado de acordo com a sintaxe do módulo struct. " "Isso significa que ``memoryview(b'abc')[0] == b'abc'[0] == 97``." -#: ../../library/stdtypes.rst:4173 +#: ../../library/stdtypes.rst:4347 msgid "The size in bytes of each element of the memoryview::" msgstr "O tamanho em Bytes de cada elemento do memoryview::" -#: ../../library/stdtypes.rst:4186 +#: ../../library/stdtypes.rst:4349 +msgid "" +">>> import array, struct\n" +">>> m = memoryview(array.array('H', [32000, 32001, 32002]))\n" +">>> m.itemsize\n" +"2\n" +">>> m[0]\n" +"32000\n" +">>> struct.calcsize('H') == m.itemsize\n" +"True" +msgstr "" +">>> import array, struct\n" +">>> m = memoryview(array.array('H', [32000, 32001, 32002]))\n" +">>> m.itemsize\n" +"2\n" +">>> m[0]\n" +"32000\n" +">>> struct.calcsize('H') == m.itemsize\n" +"True" + +#: ../../library/stdtypes.rst:4360 msgid "" "An integer indicating how many dimensions of a multi-dimensional array the " "memory represents." @@ -5886,7 +7593,7 @@ msgstr "" "Um número inteiro que indica quantas dimensões de uma matriz " "multidimensional a memória representa." -#: ../../library/stdtypes.rst:4191 +#: ../../library/stdtypes.rst:4365 msgid "" "A tuple of integers the length of :attr:`ndim` giving the shape of the " "memory as an N-dimensional array." @@ -5894,11 +7601,11 @@ msgstr "" "Uma tupla de inteiros de comprimento :attr:`ndim` dando a forma da memória " "como uma matriz N-dimensional." -#: ../../library/stdtypes.rst:4194 ../../library/stdtypes.rst:4202 +#: ../../library/stdtypes.rst:4368 ../../library/stdtypes.rst:4376 msgid "An empty tuple instead of ``None`` when ndim = 0." msgstr "Uma tupla vazia ao invés de ``None`` quando ndim = 0." -#: ../../library/stdtypes.rst:4199 +#: ../../library/stdtypes.rst:4373 msgid "" "A tuple of integers the length of :attr:`ndim` giving the size in bytes to " "access each element for each dimension of the array." @@ -5906,30 +7613,30 @@ msgstr "" "Uma tupla de inteiros de comprimento de :attr:`ndim` dando o tamanho em " "bytes para acessar cada elemento de cada dimensão da matriz." -#: ../../library/stdtypes.rst:4207 +#: ../../library/stdtypes.rst:4381 msgid "Used internally for PIL-style arrays. The value is informational only." msgstr "" "Usado internamente para estilos de Arrays PIL. O valor \\é apenas " "informativo." -#: ../../library/stdtypes.rst:4211 +#: ../../library/stdtypes.rst:4385 msgid "A bool indicating whether the memory is C-:term:`contiguous`." msgstr "Um bool que indica se a memória é :term:`contígua ` C." -#: ../../library/stdtypes.rst:4217 +#: ../../library/stdtypes.rst:4391 msgid "A bool indicating whether the memory is Fortran :term:`contiguous`." msgstr "" "Um bool que indica se a memória é :term:`contígua ` Fortran." -#: ../../library/stdtypes.rst:4223 +#: ../../library/stdtypes.rst:4397 msgid "A bool indicating whether the memory is :term:`contiguous`." msgstr "Um bool que indica se a memória é :term:`contígua `." -#: ../../library/stdtypes.rst:4231 +#: ../../library/stdtypes.rst:4405 msgid "Set Types --- :class:`set`, :class:`frozenset`" msgstr "Tipo conjuntos --- :class:`set`, :class:`frozenset`" -#: ../../library/stdtypes.rst:4235 +#: ../../library/stdtypes.rst:4409 msgid "" "A :dfn:`set` object is an unordered collection of distinct :term:`hashable` " "objects. Common uses include membership testing, removing duplicates from a " @@ -5945,7 +7652,7 @@ msgstr "" "de contêineres veja as classes embutidas :class:`dict`, :class:`list` e :" "class:`tuple`, e o módulo :mod:`collections`.)" -#: ../../library/stdtypes.rst:4242 +#: ../../library/stdtypes.rst:4416 msgid "" "Like other collections, sets support ``x in set``, ``len(set)``, and ``for x " "in set``. Being an unordered collection, sets do not record element " @@ -5957,7 +7664,7 @@ msgstr "" "posição de elementos ou ordem de inserção. Portanto, conjuntos não suportam " "indexação, fatiamento ou outros comportamentos de sequências ou similares." -#: ../../library/stdtypes.rst:4247 +#: ../../library/stdtypes.rst:4421 msgid "" "There are currently two built-in set types, :class:`set` and :class:" "`frozenset`. The :class:`set` type is mutable --- the contents can be " @@ -5977,7 +7684,7 @@ msgstr "" "alterado depois de ter sido criado; ele pode então ser usado como chave de " "dicionário ou como um elemento de outro conjunto." -#: ../../library/stdtypes.rst:4255 +#: ../../library/stdtypes.rst:4429 msgid "" "Non-empty sets (not frozensets) can be created by placing a comma-separated " "list of elements within braces, for example: ``{'jack', 'sjoerd'}``, in " @@ -5987,11 +7694,11 @@ msgstr "" "posicionando uma lista de elementos separados por vírgula dentro de chaves, " "por exemplo: ``{'jack', 'sjoerd'}``, além do construtor :class:`set`." -#: ../../library/stdtypes.rst:4259 +#: ../../library/stdtypes.rst:4433 msgid "The constructors for both classes work the same:" msgstr "Os construtores de ambas as classes funcionam da mesma forma:" -#: ../../library/stdtypes.rst:4264 +#: ../../library/stdtypes.rst:4438 msgid "" "Return a new set or frozenset object whose elements are taken from " "*iterable*. The elements of a set must be :term:`hashable`. To represent " @@ -6004,25 +7711,25 @@ msgstr "" "devem ser objetos :class:`frozenset`. Se *iterable* não for especificado, um " "novo conjunto vazio é retornado." -#: ../../library/stdtypes.rst:4270 +#: ../../library/stdtypes.rst:4444 msgid "Sets can be created by several means:" msgstr "Conjuntos podem ser criados de várias formas:" -#: ../../library/stdtypes.rst:4272 +#: ../../library/stdtypes.rst:4446 msgid "" "Use a comma-separated list of elements within braces: ``{'jack', 'sjoerd'}``" msgstr "" "Usar uma lista de elementos separados por vírgulas entre chaves: ``{'jack', " "'sjoerd'}``" -#: ../../library/stdtypes.rst:4273 +#: ../../library/stdtypes.rst:4447 msgid "" "Use a set comprehension: ``{c for c in 'abracadabra' if c not in 'abc'}``" msgstr "" "Usar uma compreensão de conjunto: ``{c for c in 'abracadabra' if c not in " "'abc'}``" -#: ../../library/stdtypes.rst:4274 +#: ../../library/stdtypes.rst:4448 msgid "" "Use the type constructor: ``set()``, ``set('foobar')``, ``set(['a', 'b', " "'foo'])``" @@ -6030,7 +7737,7 @@ msgstr "" "Usar o construtor de tipo: ``set()``, ``set('foobar')``, ``set(['a', 'b', " "'foo'])``" -#: ../../library/stdtypes.rst:4276 +#: ../../library/stdtypes.rst:4450 msgid "" "Instances of :class:`set` and :class:`frozenset` provide the following " "operations:" @@ -6038,19 +7745,19 @@ msgstr "" "Instâncias de :class:`set` e :class:`frozenset` fornecem as seguintes " "operações:" -#: ../../library/stdtypes.rst:4281 +#: ../../library/stdtypes.rst:4455 msgid "Return the number of elements in set *s* (cardinality of *s*)." msgstr "Retorna o número de elementos no set *s* (cardinalidade de *s*)." -#: ../../library/stdtypes.rst:4285 +#: ../../library/stdtypes.rst:4459 msgid "Test *x* for membership in *s*." msgstr "Testa se *x* pertence a *s*." -#: ../../library/stdtypes.rst:4289 +#: ../../library/stdtypes.rst:4463 msgid "Test *x* for non-membership in *s*." msgstr "Testa se *x* não pertence a *s*." -#: ../../library/stdtypes.rst:4293 +#: ../../library/stdtypes.rst:4467 msgid "" "Return ``True`` if the set has no elements in common with *other*. Sets are " "disjoint if and only if their intersection is the empty set." @@ -6058,11 +7765,11 @@ msgstr "" "Retorna ``True`` se o conjunto não tem elementos em comum com *other*. " "Conjuntos são disjuntos se e somente se a sua interseção é o conjunto vazio." -#: ../../library/stdtypes.rst:4299 +#: ../../library/stdtypes.rst:4473 msgid "Test whether every element in the set is in *other*." msgstr "Testa se cada elemento do conjunto está contido em *other*." -#: ../../library/stdtypes.rst:4303 +#: ../../library/stdtypes.rst:4477 msgid "" "Test whether the set is a proper subset of *other*, that is, ``set <= other " "and set != other``." @@ -6070,11 +7777,11 @@ msgstr "" "Testa se o conjunto é um subconjunto próprio de *other*, isto é, ``set <= " "other and set != other``." -#: ../../library/stdtypes.rst:4309 +#: ../../library/stdtypes.rst:4483 msgid "Test whether every element in *other* is in the set." msgstr "Testa se cada elemento em *other* está contido no conjunto." -#: ../../library/stdtypes.rst:4313 +#: ../../library/stdtypes.rst:4487 msgid "" "Test whether the set is a proper superset of *other*, that is, ``set >= " "other and set != other``." @@ -6082,34 +7789,34 @@ msgstr "" "Testa se o conjunto é um superconjunto próprio de *other*, isto é, ``set >= " "other and set != other``." -#: ../../library/stdtypes.rst:4319 +#: ../../library/stdtypes.rst:4493 msgid "Return a new set with elements from the set and all others." msgstr "" "Retorna um novo conjunto com elementos do conjunto e de todos os outros." -#: ../../library/stdtypes.rst:4324 +#: ../../library/stdtypes.rst:4498 msgid "Return a new set with elements common to the set and all others." msgstr "" "Retorna um novo conjunto com elementos comuns do conjunto e de todos os " "outros." -#: ../../library/stdtypes.rst:4329 +#: ../../library/stdtypes.rst:4503 msgid "Return a new set with elements in the set that are not in the others." msgstr "" "Retorna um novo conjunto com elementos no conjunto que não estão nos outros." -#: ../../library/stdtypes.rst:4334 +#: ../../library/stdtypes.rst:4508 msgid "" "Return a new set with elements in either the set or *other* but not both." msgstr "" "Retorna um novo conjunto com elementos estejam ou no conjunto ou em *other*, " "mas não em ambos." -#: ../../library/stdtypes.rst:4338 +#: ../../library/stdtypes.rst:4512 msgid "Return a shallow copy of the set." msgstr "Retorna uma cópia rasa do conjunto." -#: ../../library/stdtypes.rst:4341 +#: ../../library/stdtypes.rst:4515 msgid "" "Note, the non-operator versions of :meth:`union`, :meth:`intersection`, :" "meth:`difference`, :meth:`symmetric_difference`, :meth:`issubset`, and :meth:" @@ -6126,7 +7833,7 @@ msgstr "" "como ``set('abc') & 'cbs'`` e favorece a forma mais legível ``set('abc')." "intersection('cbs')``." -#: ../../library/stdtypes.rst:4348 +#: ../../library/stdtypes.rst:4522 msgid "" "Both :class:`set` and :class:`frozenset` support set to set comparisons. Two " "sets are equal if and only if every element of each set is contained in the " @@ -6144,7 +7851,7 @@ msgstr "" "um superconjunto próprio do segundo conjunto (é um superconjunto, mas não é " "igual)." -#: ../../library/stdtypes.rst:4355 +#: ../../library/stdtypes.rst:4529 msgid "" "Instances of :class:`set` are compared to instances of :class:`frozenset` " "based on their members. For example, ``set('abc') == frozenset('abc')`` " @@ -6154,7 +7861,7 @@ msgstr "" "baseados nos seus membros. Por exemplo, ``set('abc') == frozenset('abc')`` " "retorna ``True`` e assim como ``set('abc') in set([frozenset('abc')])``." -#: ../../library/stdtypes.rst:4359 +#: ../../library/stdtypes.rst:4533 msgid "" "The subset and equality comparisons do not generalize to a total ordering " "function. For example, any two nonempty disjoint sets are not equal and are " @@ -6166,7 +7873,7 @@ msgstr "" "vazios, não são iguais e não são subconjuntos um do outro, então *todos* os " "seguintes retornam ``False``: ``ab``." -#: ../../library/stdtypes.rst:4364 +#: ../../library/stdtypes.rst:4538 msgid "" "Since sets only define partial ordering (subset relationships), the output " "of the :meth:`list.sort` method is undefined for lists of sets." @@ -6175,13 +7882,13 @@ msgstr "" "relacionamentos), a saída do método :meth:`list.sort` é indefinida para " "listas e conjuntos." -#: ../../library/stdtypes.rst:4367 +#: ../../library/stdtypes.rst:4541 msgid "Set elements, like dictionary keys, must be :term:`hashable`." msgstr "" "Elementos de conjuntos, assim como chaves de dicionário, devem ser :term:" "`hasheáveis `." -#: ../../library/stdtypes.rst:4369 +#: ../../library/stdtypes.rst:4543 msgid "" "Binary operations that mix :class:`set` instances with :class:`frozenset` " "return the type of the first operand. For example: ``frozenset('ab') | " @@ -6191,7 +7898,7 @@ msgstr "" "`frozenset` retornam o tipo do primeiro operando. Por exemplo: " "``frozenset('ab') | set('bc')`` retorna uma instância de :class:`frozenset`." -#: ../../library/stdtypes.rst:4373 +#: ../../library/stdtypes.rst:4547 msgid "" "The following table lists operations available for :class:`set` that do not " "apply to immutable instances of :class:`frozenset`:" @@ -6199,31 +7906,31 @@ msgstr "" "A seguinte tabela lista operações disponíveis para :class:`set` que não se " "aplicam para instâncias imutáveis de :class:`frozenset`:" -#: ../../library/stdtypes.rst:4379 +#: ../../library/stdtypes.rst:4553 msgid "Update the set, adding elements from all others." msgstr "Atualiza o conjunto, adicionando elementos dos outros." -#: ../../library/stdtypes.rst:4384 +#: ../../library/stdtypes.rst:4558 msgid "Update the set, keeping only elements found in it and all others." msgstr "" "Atualiza o conjunto, mantendo somente elementos encontrados nele e em outros." -#: ../../library/stdtypes.rst:4389 +#: ../../library/stdtypes.rst:4563 msgid "Update the set, removing elements found in others." msgstr "Atualiza o conjunto, removendo elementos encontrados em outros." -#: ../../library/stdtypes.rst:4394 +#: ../../library/stdtypes.rst:4568 msgid "" "Update the set, keeping only elements found in either set, but not in both." msgstr "" "Atualiza o conjunto, mantendo somente elementos encontrados em qualquer " "conjunto, mas não em ambos." -#: ../../library/stdtypes.rst:4398 +#: ../../library/stdtypes.rst:4572 msgid "Add element *elem* to the set." msgstr "Adiciona o elemento *elem* ao conjunto." -#: ../../library/stdtypes.rst:4402 +#: ../../library/stdtypes.rst:4576 msgid "" "Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is not " "contained in the set." @@ -6231,11 +7938,11 @@ msgstr "" "Remove o elemento *elem* do conjunto. Levanta :exc:`KeyError` se *elem* não " "estiver contido no conjunto." -#: ../../library/stdtypes.rst:4407 +#: ../../library/stdtypes.rst:4581 msgid "Remove element *elem* from the set if it is present." msgstr "Remove o elemento *elem* do conjunto se ele estiver presente." -#: ../../library/stdtypes.rst:4411 +#: ../../library/stdtypes.rst:4585 msgid "" "Remove and return an arbitrary element from the set. Raises :exc:`KeyError` " "if the set is empty." @@ -6243,11 +7950,11 @@ msgstr "" "Remove e retorna um elemento arbitrário do conjunto. Levanta :exc:`KeyError` " "se o conjunto estiver vazio." -#: ../../library/stdtypes.rst:4416 +#: ../../library/stdtypes.rst:4590 msgid "Remove all elements from the set." msgstr "Remove todos os elementos do conjunto." -#: ../../library/stdtypes.rst:4419 +#: ../../library/stdtypes.rst:4593 msgid "" "Note, the non-operator versions of the :meth:`update`, :meth:" "`intersection_update`, :meth:`difference_update`, and :meth:" @@ -6259,7 +7966,7 @@ msgstr "" "`symmetric_difference_update` irão aceitar qualquer iterável como um " "argumento." -#: ../../library/stdtypes.rst:4424 +#: ../../library/stdtypes.rst:4598 msgid "" "Note, the *elem* argument to the :meth:`~object.__contains__`, :meth:" "`remove`, and :meth:`discard` methods may be a set. To support searching " @@ -6270,11 +7977,11 @@ msgstr "" "pesquisas por um frozenset equivalente, um frozenset temporário é criado a " "partir de *elem*." -#: ../../library/stdtypes.rst:4433 +#: ../../library/stdtypes.rst:4607 msgid "Mapping Types --- :class:`dict`" msgstr "Tipo mapeamento --- :class:`dict`" -#: ../../library/stdtypes.rst:4443 +#: ../../library/stdtypes.rst:4617 msgid "" "A :term:`mapping` object maps :term:`hashable` values to arbitrary objects. " "Mappings are mutable objects. There is currently only one standard mapping " @@ -6288,7 +7995,7 @@ msgstr "" "(Para outros contêineres, veja as classes embutidas :class:`list`, :class:" "`set` e :class:`tuple`, e o módulo :mod:`collections`.)" -#: ../../library/stdtypes.rst:4449 +#: ../../library/stdtypes.rst:4623 msgid "" "A dictionary's keys are *almost* arbitrary values. Values that are not :" "term:`hashable`, that is, values containing lists, dictionaries or other " @@ -6303,7 +8010,7 @@ msgstr "" "iguais (como ``1``, ``1.0`` e ``True``) podem ser usados alternadamente para " "indexar a mesma entrada do dicionário." -#: ../../library/stdtypes.rst:4460 +#: ../../library/stdtypes.rst:4634 msgid "" "Return a new dictionary initialized from an optional positional argument and " "a possibly empty set of keyword arguments." @@ -6311,11 +8018,11 @@ msgstr "" "Retorna um novo dicionário inicializado a partir de um argumento posicional " "opcional, e um conjunto de argumentos nomeados possivelmente vazio." -#: ../../library/stdtypes.rst:4463 +#: ../../library/stdtypes.rst:4637 msgid "Dictionaries can be created by several means:" msgstr "Os dicionários podem ser criados de várias formas:" -#: ../../library/stdtypes.rst:4465 +#: ../../library/stdtypes.rst:4639 msgid "" "Use a comma-separated list of ``key: value`` pairs within braces: ``{'jack': " "4098, 'sjoerd': 4127}`` or ``{4098: 'jack', 4127: 'sjoerd'}``" @@ -6323,13 +8030,13 @@ msgstr "" "Usar uma lista de pares ``key: value`` separados por vírgula com chaves: " "``{'jack': 4098, 'sjoerd': 4127}`` ou ``{4098: 'jack', 4127: 'sjoerd'}``" -#: ../../library/stdtypes.rst:4467 +#: ../../library/stdtypes.rst:4641 msgid "Use a dict comprehension: ``{}``, ``{x: x ** 2 for x in range(10)}``" msgstr "" "Usar uma compreensão de dicionário: ``{}``, ``{x: x ** 2 for x in range(10)}" "``" -#: ../../library/stdtypes.rst:4468 +#: ../../library/stdtypes.rst:4642 msgid "" "Use the type constructor: ``dict()``, ``dict([('foo', 100), ('bar', " "200)])``, ``dict(foo=100, bar=200)``" @@ -6337,28 +8044,29 @@ msgstr "" "Usar o construtor de tipo: ``dict()``, ``dict([('foo', 100), ('bar', " "200)])``, ``dict(foo=100, bar=200)``" -#: ../../library/stdtypes.rst:4471 +#: ../../library/stdtypes.rst:4645 msgid "" "If no positional argument is given, an empty dictionary is created. If a " -"positional argument is given and it is a mapping object, a dictionary is " -"created with the same key-value pairs as the mapping object. Otherwise, the " -"positional argument must be an :term:`iterable` object. Each item in the " -"iterable must itself be an iterable with exactly two objects. The first " -"object of each item becomes a key in the new dictionary, and the second " -"object the corresponding value. If a key occurs more than once, the last " -"value for that key becomes the corresponding value in the new dictionary." +"positional argument is given and it defines a ``keys()`` method, a " +"dictionary is created by calling :meth:`~object.__getitem__` on the argument " +"with each returned key from the method. Otherwise, the positional argument " +"must be an :term:`iterable` object. Each item in the iterable must itself " +"be an iterable with exactly two elements. The first element of each item " +"becomes a key in the new dictionary, and the second element the " +"corresponding value. If a key occurs more than once, the last value for " +"that key becomes the corresponding value in the new dictionary." msgstr "" "Se nenhum argumento posicional é fornecido, um dicionário vazio é criado. Se " -"um argumento posicional é fornecido e é um objeto de mapeamento, um " -"dicionário é criado com os mesmos pares de chave-valor que o objeto de " -"mapeamento. Caso contrário, o argumento posicional deve ser um objeto :term:" -"`iterável `. Cada item no iterável deve ser por si mesmo um " -"iterável com exatamente dois objetos. O primeiro objeto de cada item torna-" -"se a chave no novo dicionário, e o segundo objeto, o valor correspondente. " -"Se a chave ocorrer mais do que uma vez, o último valor para aquela chave " -"torna-se o valor correspondente no novo dicionário." +"um argumento posicional é fornecido e ele define um método ``keys()``, um " +"dicionário é criado chamando :meth:`~object.__getitem__` no argumento com " +"cada chave retornada pelo método. Caso contrário, o argumento posicional " +"deve ser um objeto :term:`iterável`. Cada item no iterável deve ser por si " +"mesmo um iterável com exatamente dois elementos. O primeiro elemento de cada " +"item torna-se a chave no novo dicionário, e o segundo elemento, o valor " +"correspondente. Se a chave ocorrer mais do que uma vez, o último valor para " +"aquela chave torna-se o valor correspondente no novo dicionário." -#: ../../library/stdtypes.rst:4481 +#: ../../library/stdtypes.rst:4655 msgid "" "If keyword arguments are given, the keyword arguments and their values are " "added to the dictionary created from the positional argument. If a key " @@ -6370,15 +8078,7 @@ msgstr "" "uma chave sendo adicionada já está presente, o valor do argumento nomeado " "substitui o valor do argumento posicional." -#: ../../library/stdtypes.rst:4486 -msgid "" -"To illustrate, the following examples all return a dictionary equal to " -"``{\"one\": 1, \"two\": 2, \"three\": 3}``::" -msgstr "" -"Para ilustrar, os seguintes exemplos todos retornam um dicionário igual a " -"``{\"one\": 1, \"two\": 2, \"three\": 3}``::" - -#: ../../library/stdtypes.rst:4498 +#: ../../library/stdtypes.rst:4660 ../../library/stdtypes.rst:4678 msgid "" "Providing keyword arguments as in the first example only works for keys that " "are valid Python identifiers. Otherwise, any valid keys can be used." @@ -6387,7 +8087,90 @@ msgstr "" "para chaves que são identificadores válidos no Python. Caso contrário, " "quaisquer chaves válidas podem ser usadas." -#: ../../library/stdtypes.rst:4502 +#: ../../library/stdtypes.rst:4663 +msgid "" +"Dictionaries compare equal if and only if they have the same ``(key, " +"value)`` pairs (regardless of ordering). Order comparisons ('<', '<=', '>=', " +"'>') raise :exc:`TypeError`. To illustrate dictionary creation and " +"equality, the following examples all return a dictionary equal to " +"``{\"one\": 1, \"two\": 2, \"three\": 3}``::" +msgstr "" +"Dicionários são iguais se e somente se eles os mesmos pares ``(key, value)`` " +"(independente de ordem). Comparações de ordem ('<', '<=', '>=', '>') " +"levantam :exc:`TypeError`. Para ilustrar a criação e igualdade de " +"dicionários, os exemplos a seguir retornam um dicionário igual a ``{\"one\": " +"1, \"two\": 2, \"three\": 3}``::" + +#: ../../library/stdtypes.rst:4669 +msgid "" +">>> a = dict(one=1, two=2, three=3)\n" +">>> b = {'one': 1, 'two': 2, 'three': 3}\n" +">>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))\n" +">>> d = dict([('two', 2), ('one', 1), ('three', 3)])\n" +">>> e = dict({'three': 3, 'one': 1, 'two': 2})\n" +">>> f = dict({'one': 1, 'three': 3}, two=2)\n" +">>> a == b == c == d == e == f\n" +"True" +msgstr "" +">>> a = dict(one=1, two=2, three=3)\n" +">>> b = {'one': 1, 'two': 2, 'three': 3}\n" +">>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))\n" +">>> d = dict([('two', 2), ('one', 1), ('three', 3)])\n" +">>> e = dict({'three': 3, 'one': 1, 'two': 2})\n" +">>> f = dict({'one': 1, 'three': 3}, two=2)\n" +">>> a == b == c == d == e == f\n" +"True" + +#: ../../library/stdtypes.rst:4681 +msgid "" +"Dictionaries preserve insertion order. Note that updating a key does not " +"affect the order. Keys added after deletion are inserted at the end. ::" +msgstr "" +"Dicionários preservam a ordem de inserção. Perceba que atualizar a chave não " +"afeta a ordem. Chaves adicionadas após a deleção são inseridas no final. ::" + +#: ../../library/stdtypes.rst:4684 +msgid "" +">>> d = {\"one\": 1, \"two\": 2, \"three\": 3, \"four\": 4}\n" +">>> d\n" +"{'one': 1, 'two': 2, 'three': 3, 'four': 4}\n" +">>> list(d)\n" +"['one', 'two', 'three', 'four']\n" +">>> list(d.values())\n" +"[1, 2, 3, 4]\n" +">>> d[\"one\"] = 42\n" +">>> d\n" +"{'one': 42, 'two': 2, 'three': 3, 'four': 4}\n" +">>> del d[\"two\"]\n" +">>> d[\"two\"] = None\n" +">>> d\n" +"{'one': 42, 'three': 3, 'four': 4, 'two': None}" +msgstr "" +">>> d = {\"um\": 1, \"dois\": 2, \"três\": 3, \"quatro\": 4}\n" +">>> d\n" +"{'um': 1, 'dois': 2, 'três': 3, 'quatro': 4}\n" +">>> list(d)\n" +"['um', 'dois', 'três', 'quatro']\n" +">>> list(d.values())\n" +"[1, 2, 3, 4]\n" +">>> d[\"um\"] = 42\n" +">>> d\n" +"{'um': 42, 'dois': 2, 'três': 3, 'quatro': 4}\n" +">>> del d[\"dois\"]\n" +">>> d[\"dois\"] = None\n" +">>> d\n" +"{'um': 42, 'três': 3, 'quatro': 4, 'dois': None}" + +#: ../../library/stdtypes.rst:4699 +msgid "" +"Dictionary order is guaranteed to be insertion order. This behavior was an " +"implementation detail of CPython from 3.6." +msgstr "" +"Ordem do dicionário é garantida conforme a ordem de inserção. Este " +"comportamento era um detalhe de implementação do CPython a partir da versão " +"3.6." + +#: ../../library/stdtypes.rst:4703 msgid "" "These are the operations that dictionaries support (and therefore, custom " "mapping types should support too):" @@ -6395,15 +8178,15 @@ msgstr "" "Estas são as operações que dicionários suportam (e portanto, tipos de " "mapeamento personalizados devem suportar também):" -#: ../../library/stdtypes.rst:4507 +#: ../../library/stdtypes.rst:4708 msgid "Return a list of all the keys used in the dictionary *d*." msgstr "Retorna uma lista de todas as chaves usadas no dicionário *d*." -#: ../../library/stdtypes.rst:4511 +#: ../../library/stdtypes.rst:4712 msgid "Return the number of items in the dictionary *d*." msgstr "Retorna o número de itens no dicionário *d*." -#: ../../library/stdtypes.rst:4515 +#: ../../library/stdtypes.rst:4716 msgid "" "Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is " "not in the map." @@ -6411,7 +8194,7 @@ msgstr "" "Retorna o item de *d* com a chave *key*. Levanta um :exc:`KeyError` se *key* " "não estiver no mapeamento." -#: ../../library/stdtypes.rst:4520 +#: ../../library/stdtypes.rst:4721 msgid "" "If a subclass of dict defines a method :meth:`__missing__` and *key* is not " "present, the ``d[key]`` operation calls that method with the key *key* as " @@ -6429,7 +8212,31 @@ msgstr "" "for definido, então :exc:`KeyError` é levantado. :meth:`__missing__` deve " "ser um método; ele não pode ser uma variável de instância::" -#: ../../library/stdtypes.rst:4539 +#: ../../library/stdtypes.rst:4729 +msgid "" +">>> class Counter(dict):\n" +"... def __missing__(self, key):\n" +"... return 0\n" +"...\n" +">>> c = Counter()\n" +">>> c['red']\n" +"0\n" +">>> c['red'] += 1\n" +">>> c['red']\n" +"1" +msgstr "" +">>> class Counter(dict):\n" +"... def __missing__(self, key):\n" +"... return 0\n" +"...\n" +">>> c = Counter()\n" +">>> c['red']\n" +"0\n" +">>> c['red'] += 1\n" +">>> c['red']\n" +"1" + +#: ../../library/stdtypes.rst:4740 msgid "" "The example above shows part of the implementation of :class:`collections." "Counter`. A different ``__missing__`` method is used by :class:`collections." @@ -6439,11 +8246,11 @@ msgstr "" "Counter`. Um método ``__missing__`` diferente é usado para :class:" "`collections.defaultdict`." -#: ../../library/stdtypes.rst:4545 +#: ../../library/stdtypes.rst:4746 msgid "Set ``d[key]`` to *value*." msgstr "Define ``d[key]`` para *value*." -#: ../../library/stdtypes.rst:4549 +#: ../../library/stdtypes.rst:4750 msgid "" "Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the " "map." @@ -6451,16 +8258,16 @@ msgstr "" "Remove ``d[key]`` do *d*. Levanta uma exceção :exc:`KeyError` se *key* não " "estiver no mapeamento." -#: ../../library/stdtypes.rst:4554 +#: ../../library/stdtypes.rst:4755 msgid "Return ``True`` if *d* has a key *key*, else ``False``." msgstr "" "Retorna ``True`` se *d* tiver uma chave *key*, caso contrário ``False``." -#: ../../library/stdtypes.rst:4558 +#: ../../library/stdtypes.rst:4759 msgid "Equivalent to ``not key in d``." msgstr "Equivalente a ``not key in d``." -#: ../../library/stdtypes.rst:4562 +#: ../../library/stdtypes.rst:4763 msgid "" "Return an iterator over the keys of the dictionary. This is a shortcut for " "``iter(d.keys())``." @@ -6468,22 +8275,22 @@ msgstr "" "Retorna um iterador para as chaves do dicionário. Isso é um atalho para " "``iter(d.keys())``." -#: ../../library/stdtypes.rst:4567 +#: ../../library/stdtypes.rst:4768 msgid "Remove all items from the dictionary." msgstr "Remove todos os itens do dicionário." -#: ../../library/stdtypes.rst:4571 +#: ../../library/stdtypes.rst:4772 msgid "Return a shallow copy of the dictionary." msgstr "Retorna uma cópia superficial do dicionário." -#: ../../library/stdtypes.rst:4575 +#: ../../library/stdtypes.rst:4776 msgid "" "Create a new dictionary with keys from *iterable* and values set to *value*." msgstr "" "Cria um novo dicionário com chaves provenientes de *iterable* e valores " "definidos como *value*." -#: ../../library/stdtypes.rst:4577 +#: ../../library/stdtypes.rst:4778 msgid "" ":meth:`fromkeys` is a class method that returns a new dictionary. *value* " "defaults to ``None``. All of the values refer to just a single instance, so " @@ -6497,7 +8304,7 @@ msgstr "" "objeto mutável tal como uma lista vazia. Para obter valores distintos, use " "uma :ref:`compreensão de dicionário ` ao invés." -#: ../../library/stdtypes.rst:4585 +#: ../../library/stdtypes.rst:4786 msgid "" "Return the value for *key* if *key* is in the dictionary, else *default*. If " "*default* is not given, it defaults to ``None``, so that this method never " @@ -6507,7 +8314,7 @@ msgstr "" "*default*. Se *default* não é fornecido, será usado o valor padrão ``None``, " "de tal forma que este método nunca levanta um :exc:`KeyError`." -#: ../../library/stdtypes.rst:4591 +#: ../../library/stdtypes.rst:4792 msgid "" "Return a new view of the dictionary's items (``(key, value)`` pairs). See " "the :ref:`documentation of view objects `." @@ -6515,7 +8322,7 @@ msgstr "" "Retorna uma nova visão dos itens do dicionário (pares de ``(key, value)``). " "Veja a :ref:`documentação de objetos de visão de dicionário `." -#: ../../library/stdtypes.rst:4596 +#: ../../library/stdtypes.rst:4797 msgid "" "Return a new view of the dictionary's keys. See the :ref:`documentation of " "view objects `." @@ -6523,7 +8330,7 @@ msgstr "" "Retorna uma nova visão das chaves do dicionário. Veja a :ref:`documentação " "de objetos de visão de dicionário `." -#: ../../library/stdtypes.rst:4601 +#: ../../library/stdtypes.rst:4802 msgid "" "If *key* is in the dictionary, remove it and return its value, else return " "*default*. If *default* is not given and *key* is not in the dictionary, a :" @@ -6533,7 +8340,7 @@ msgstr "" "contrário retorna *default*. Se *default* não foi fornecido e *key* não está " "no dicionário, um :exc:`KeyError` é levantado." -#: ../../library/stdtypes.rst:4607 +#: ../../library/stdtypes.rst:4808 msgid "" "Remove and return a ``(key, value)`` pair from the dictionary. Pairs are " "returned in :abbr:`LIFO (last-in, first-out)` order." @@ -6541,7 +8348,7 @@ msgstr "" "Remove e retorna um par ``(key, value)`` do dicionário. Pares são retornados " "como uma pilha, ou seja em ordem :abbr:`LIFO (last-in, first-out)`." -#: ../../library/stdtypes.rst:4610 +#: ../../library/stdtypes.rst:4811 msgid "" ":meth:`popitem` is useful to destructively iterate over a dictionary, as " "often used in set algorithms. If the dictionary is empty, calling :meth:" @@ -6551,7 +8358,7 @@ msgstr "" "comumente usado em algoritmos de conjunto. Se o dicionário estiver vazio, " "chamar :meth:`popitem` levanta um :exc:`KeyError`." -#: ../../library/stdtypes.rst:4614 +#: ../../library/stdtypes.rst:4815 msgid "" "LIFO order is now guaranteed. In prior versions, :meth:`popitem` would " "return an arbitrary key/value pair." @@ -6559,7 +8366,7 @@ msgstr "" "Ordem LIFO agora é garantida. Em versões anteriores, :meth:`popitem` iria " "retornar um par chave/valor arbitrário." -#: ../../library/stdtypes.rst:4620 +#: ../../library/stdtypes.rst:4821 msgid "" "Return a reverse iterator over the keys of the dictionary. This is a " "shortcut for ``reversed(d.keys())``." @@ -6567,7 +8374,7 @@ msgstr "" "Retorna um iterador revertido sobre as chaves do dicionário. Isso é um " "atalho para ``reversed(d.keys())``." -#: ../../library/stdtypes.rst:4627 +#: ../../library/stdtypes.rst:4828 msgid "" "If *key* is in the dictionary, return its value. If not, insert *key* with " "a value of *default* and return *default*. *default* defaults to ``None``." @@ -6576,7 +8383,7 @@ msgstr "" "valor *default* e retorna *default*. *default* por padrão usa o valor " "``None``." -#: ../../library/stdtypes.rst:4633 +#: ../../library/stdtypes.rst:4834 msgid "" "Update the dictionary with the key/value pairs from *other*, overwriting " "existing keys. Return ``None``." @@ -6584,19 +8391,22 @@ msgstr "" "Atualiza o dicionário com os pares chave/valor existente em *other*, " "sobrescrevendo chaves existentes. Retorna ``None``." -#: ../../library/stdtypes.rst:4636 +#: ../../library/stdtypes.rst:4837 msgid "" -":meth:`update` accepts either another dictionary object or an iterable of " -"key/value pairs (as tuples or other iterables of length two). If keyword " -"arguments are specified, the dictionary is then updated with those key/value " -"pairs: ``d.update(red=1, blue=2)``." +":meth:`update` accepts either another object with a ``keys()`` method (in " +"which case :meth:`~object.__getitem__` is called with every key returned " +"from the method) or an iterable of key/value pairs (as tuples or other " +"iterables of length two). If keyword arguments are specified, the dictionary " +"is then updated with those key/value pairs: ``d.update(red=1, blue=2)``." msgstr "" -":meth:`update` aceita ou outro objeto dicionário, ou um iterável de pares de " -"chave/valor (como tuplas ou outros iteráveis de comprimento dois). Se " -"argumentos nomeados são especificados, o dicionário é então atualizado com " -"esses pares de chave/valor: ``d.update(red=1, blue=2)``." +":meth:`update` aceita ou outro objeto com um método ``keys()`` (em cada " +"caso :meth:`~object.__getitem__` é chamado com cada chave retornada pelo " +"método) ou um iterável de pares de chave/valor (como tuplas ou outros " +"iteráveis de comprimento dois). Se argumentos nomeados são especificados, o " +"dicionário é então atualizado com esses pares de chave/valor: ``d." +"update(red=1, blue=2)``." -#: ../../library/stdtypes.rst:4643 +#: ../../library/stdtypes.rst:4845 msgid "" "Return a new view of the dictionary's values. See the :ref:`documentation " "of view objects `." @@ -6604,7 +8414,7 @@ msgstr "" "Retorna uma nova visão dos valores do dicionário. Veja a :ref:`documentação " "de objetos de visão de dicionário `." -#: ../../library/stdtypes.rst:4646 +#: ../../library/stdtypes.rst:4848 msgid "" "An equality comparison between one ``dict.values()`` view and another will " "always return ``False``. This also applies when comparing ``dict.values()`` " @@ -6614,7 +8424,17 @@ msgstr "" "sempre irá retornar ``False``. Isso também se aplica ao comparar ``dict." "values()`` entre si::" -#: ../../library/stdtypes.rst:4656 +#: ../../library/stdtypes.rst:4852 +msgid "" +">>> d = {'a': 1}\n" +">>> d.values() == d.values()\n" +"False" +msgstr "" +">>> d = {'a': 1}\n" +">>> d.values() == d.values()\n" +"False" + +#: ../../library/stdtypes.rst:4858 msgid "" "Create a new dictionary with the merged keys and values of *d* and *other*, " "which must both be dictionaries. The values of *other* take priority when " @@ -6624,7 +8444,7 @@ msgstr "" "*other*, que devem ser dicionários. Os valores de *other* têm prioridade " "quando *d* e *other* compartilham chaves." -#: ../../library/stdtypes.rst:4664 +#: ../../library/stdtypes.rst:4866 msgid "" "Update the dictionary *d* with keys and values from *other*, which may be " "either a :term:`mapping` or an :term:`iterable` of key/value pairs. The " @@ -6635,42 +8455,37 @@ msgstr "" "chave/valor. Os valores de *other* têm prioridade quando *d* e *other* " "compartilham chaves." -#: ../../library/stdtypes.rst:4670 -msgid "" -"Dictionaries compare equal if and only if they have the same ``(key, " -"value)`` pairs (regardless of ordering). Order comparisons ('<', '<=', '>=', " -"'>') raise :exc:`TypeError`." -msgstr "" -"Dicionários são iguais se e somente se eles os mesmos pares ``(key, value)`` " -"(independente de ordem). Comparações de ordem ('<', '<=', '>=', '>') " -"levantam :exc:`TypeError`." - -#: ../../library/stdtypes.rst:4674 -msgid "" -"Dictionaries preserve insertion order. Note that updating a key does not " -"affect the order. Keys added after deletion are inserted at the end. ::" -msgstr "" -"Dicionários preservam a ordem de inserção. Perceba que atualizar a chave não " -"afeta a ordem. Chaves adicionadas após a deleção são inseridas no final. ::" - -#: ../../library/stdtypes.rst:4692 -msgid "" -"Dictionary order is guaranteed to be insertion order. This behavior was an " -"implementation detail of CPython from 3.6." -msgstr "" -"Ordem do dicionário é garantida conforme a ordem de inserção. Este " -"comportamento era um detalhe de implementação do CPython a partir da versão " -"3.6." - -#: ../../library/stdtypes.rst:4696 +#: ../../library/stdtypes.rst:4872 msgid "Dictionaries and dictionary views are reversible. ::" msgstr "Dicionários e visões de dicionários são reversíveis. ::" -#: ../../library/stdtypes.rst:4708 +#: ../../library/stdtypes.rst:4874 +msgid "" +">>> d = {\"one\": 1, \"two\": 2, \"three\": 3, \"four\": 4}\n" +">>> d\n" +"{'one': 1, 'two': 2, 'three': 3, 'four': 4}\n" +">>> list(reversed(d))\n" +"['four', 'three', 'two', 'one']\n" +">>> list(reversed(d.values()))\n" +"[4, 3, 2, 1]\n" +">>> list(reversed(d.items()))\n" +"[('four', 4), ('three', 3), ('two', 2), ('one', 1)]" +msgstr "" +">>> d = {\"um\": 1, \"dois\": 2, \"três\": 3, \"quatro\": 4}\n" +">>> d\n" +"{'um': 1, 'dois': 2, 'três': 3, 'quatro': 4}\n" +">>> list(reversed(d))\n" +"['quatro', 'três', 'dois', 'um']\n" +">>> list(reversed(d.values()))\n" +"[4, 3, 2, 1]\n" +">>> list(reversed(d.items()))\n" +"[('quatro', 4), ('três', 3), ('dois', 2), ('um', 1)]" + +#: ../../library/stdtypes.rst:4884 msgid "Dictionaries are now reversible." msgstr "Dicionários agora são reversíveis." -#: ../../library/stdtypes.rst:4713 +#: ../../library/stdtypes.rst:4889 msgid "" ":class:`types.MappingProxyType` can be used to create a read-only view of a :" "class:`dict`." @@ -6678,11 +8493,11 @@ msgstr "" ":class:`types.MappingProxyType` podem ser usados para criar uma visão " "somente leitura de um :class:`dict`." -#: ../../library/stdtypes.rst:4720 +#: ../../library/stdtypes.rst:4896 msgid "Dictionary view objects" msgstr "Objetos de visão de dicionário" -#: ../../library/stdtypes.rst:4722 +#: ../../library/stdtypes.rst:4898 msgid "" "The objects returned by :meth:`dict.keys`, :meth:`dict.values` and :meth:" "`dict.items` are *view objects*. They provide a dynamic view on the " @@ -6694,7 +8509,7 @@ msgstr "" "entradas do dicionário, o que significa que quando o dicionário muda, a " "visão reflete essas mudanças." -#: ../../library/stdtypes.rst:4727 +#: ../../library/stdtypes.rst:4903 msgid "" "Dictionary views can be iterated over to yield their respective data, and " "support membership tests:" @@ -6702,11 +8517,11 @@ msgstr "" "Visões de dicionários podem ser iteradas para apresentar seus respectivos " "dados, e suportar testes de existência:" -#: ../../library/stdtypes.rst:4732 +#: ../../library/stdtypes.rst:4908 msgid "Return the number of entries in the dictionary." msgstr "Retorna o número de entradas no dicionário." -#: ../../library/stdtypes.rst:4736 +#: ../../library/stdtypes.rst:4912 msgid "" "Return an iterator over the keys, values or items (represented as tuples of " "``(key, value)``) in the dictionary." @@ -6714,7 +8529,7 @@ msgstr "" "Retorna um iterador sobre as chaves, valores ou itens (representados como " "tuplas de ``(key, value)``) no dicionário." -#: ../../library/stdtypes.rst:4739 +#: ../../library/stdtypes.rst:4915 msgid "" "Keys and values are iterated over in insertion order. This allows the " "creation of ``(value, key)`` pairs using :func:`zip`: ``pairs = zip(d." @@ -6726,7 +8541,7 @@ msgstr "" "keys())``. Outra maneira de criar a mesma lista é ``pairs = [(v, k) for (k, " "v) in d.items()]``." -#: ../../library/stdtypes.rst:4744 +#: ../../library/stdtypes.rst:4920 msgid "" "Iterating views while adding or deleting entries in the dictionary may raise " "a :exc:`RuntimeError` or fail to iterate over all entries." @@ -6734,11 +8549,11 @@ msgstr "" "Iterar sobre visões enquanto adiciona ou deleta entradas no dicionário pode " "levantar um :exc:`RuntimeError` ou falhar a iteração sobre todas as entradas." -#: ../../library/stdtypes.rst:4747 +#: ../../library/stdtypes.rst:4923 msgid "Dictionary order is guaranteed to be insertion order." msgstr "Ordem do dicionário é garantida como a ordem de inserção." -#: ../../library/stdtypes.rst:4752 +#: ../../library/stdtypes.rst:4928 msgid "" "Return ``True`` if *x* is in the underlying dictionary's keys, values or " "items (in the latter case, *x* should be a ``(key, value)`` tuple)." @@ -6746,7 +8561,7 @@ msgstr "" "Retorna ``True`` se *x* está nas chaves, valores ou itens do dicionário " "subjacente (no último caso, *x* deve ser uma tupla de ``(key, value)``)." -#: ../../library/stdtypes.rst:4757 +#: ../../library/stdtypes.rst:4933 msgid "" "Return a reverse iterator over the keys, values or items of the dictionary. " "The view will be iterated in reverse order of the insertion." @@ -6754,11 +8569,11 @@ msgstr "" "Retorna um iterador reverso sobre as chaves, valores ou itens do dicionário. " "A visão será iterada na ordem reversa de inserção." -#: ../../library/stdtypes.rst:4760 +#: ../../library/stdtypes.rst:4936 msgid "Dictionary views are now reversible." msgstr "Visões de dicionário agora são reversíveis." -#: ../../library/stdtypes.rst:4765 +#: ../../library/stdtypes.rst:4941 msgid "" "Return a :class:`types.MappingProxyType` that wraps the original dictionary " "to which the view refers." @@ -6766,7 +8581,7 @@ msgstr "" "Retorna um :class:`types.MappingProxyType` que envolve o dicionário original " "ao qual a visão se refere." -#: ../../library/stdtypes.rst:4770 +#: ../../library/stdtypes.rst:4946 msgid "" "Keys views are set-like since their entries are unique and :term:`hashable`. " "Items views also have set-like operations since the (key, value) pairs are " @@ -6792,15 +8607,95 @@ msgstr "" "iterável como outro operando, ao contrário de conjuntos que aceitam apenas " "conjuntos como entrada." -#: ../../library/stdtypes.rst:4782 +#: ../../library/stdtypes.rst:4958 msgid "An example of dictionary view usage::" msgstr "Um exemplo da utilização da visualização de dicionário::" -#: ../../library/stdtypes.rst:4826 +#: ../../library/stdtypes.rst:4960 +msgid "" +">>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}\n" +">>> keys = dishes.keys()\n" +">>> values = dishes.values()\n" +"\n" +">>> # iteration\n" +">>> n = 0\n" +">>> for val in values:\n" +"... n += val\n" +"...\n" +">>> print(n)\n" +"504\n" +"\n" +">>> # keys and values are iterated over in the same order (insertion order)\n" +">>> list(keys)\n" +"['eggs', 'sausage', 'bacon', 'spam']\n" +">>> list(values)\n" +"[2, 1, 1, 500]\n" +"\n" +">>> # view objects are dynamic and reflect dict changes\n" +">>> del dishes['eggs']\n" +">>> del dishes['sausage']\n" +">>> list(keys)\n" +"['bacon', 'spam']\n" +"\n" +">>> # set operations\n" +">>> keys & {'eggs', 'bacon', 'salad'}\n" +"{'bacon'}\n" +">>> keys ^ {'sausage', 'juice'} == {'juice', 'sausage', 'bacon', 'spam'}\n" +"True\n" +">>> keys | ['juice', 'juice', 'juice'] == {'bacon', 'spam', 'juice'}\n" +"True\n" +"\n" +">>> # get back a read-only proxy for the original dictionary\n" +">>> values.mapping\n" +"mappingproxy({'bacon': 1, 'spam': 500})\n" +">>> values.mapping['spam']\n" +"500" +msgstr "" +">>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}\n" +">>> keys = dishes.keys()\n" +">>> values = dishes.values()\n" +"\n" +">>> # iteration\n" +">>> n = 0\n" +">>> for val in values:\n" +"... n += val\n" +"...\n" +">>> print(n)\n" +"504\n" +"\n" +">>> # a iteração sobre chaves e valores é feita na mesma ordem (ordem de " +"inserção)\n" +">>> list(keys)\n" +"['eggs', 'sausage', 'bacon', 'spam']\n" +">>> list(values)\n" +"[2, 1, 1, 500]\n" +"\n" +">>> # objetos de visualização são dinâmicos e refletem mudanças no " +"dicionário\n" +">>> del dishes['eggs']\n" +">>> del dishes['sausage']\n" +">>> list(keys)\n" +"['bacon', 'spam']\n" +"\n" +">>> # operações de conjunto\n" +">>> keys & {'eggs', 'bacon', 'salad'}\n" +"{'bacon'}\n" +">>> keys ^ {'sausage', 'juice'} == {'juice', 'sausage', 'bacon', 'spam'}\n" +"True\n" +">>> keys | ['juice', 'juice', 'juice'] == {'bacon', 'spam', 'juice'}\n" +"True\n" +"\n" +">>> # recupera um proxy somente de leitura para o dicionário original\n" +">>> values.mapping\n" +"mappingproxy({'bacon': 1, 'spam': 500})\n" +">>> values.mapping['spam']\n" +"500" + +#: ../../library/stdtypes.rst:5002 msgid "Context Manager Types" msgstr "Tipos de Gerenciador de Contexto" -#: ../../library/stdtypes.rst:4833 +#: ../../library/stdtypes.rst:5009 msgid "" "Python's :keyword:`with` statement supports the concept of a runtime context " "defined by a context manager. This is implemented using a pair of methods " @@ -6814,7 +8709,7 @@ msgstr "" "inicializado antes da execução das instruções, e encerrado quando as " "instruções terminam:" -#: ../../library/stdtypes.rst:4841 +#: ../../library/stdtypes.rst:5017 msgid "" "Enter the runtime context and return either this object or another object " "related to the runtime context. The value returned by this method is bound " @@ -6826,7 +8721,7 @@ msgstr "" "método é ligado ao identificador na cláusula :keyword:`!as` das instruções :" "keyword:`with` usando este gerenciador de contexto." -#: ../../library/stdtypes.rst:4846 +#: ../../library/stdtypes.rst:5022 msgid "" "An example of a context manager that returns itself is a :term:`file " "object`. File objects return themselves from __enter__() to allow :func:" @@ -6837,7 +8732,7 @@ msgstr "" "método __enter__() para permitir que :func:`open` seja usado como a " "expressão de contexto em uma instrução :keyword:`with`." -#: ../../library/stdtypes.rst:4850 +#: ../../library/stdtypes.rst:5026 msgid "" "An example of a context manager that returns a related object is the one " "returned by :func:`decimal.localcontext`. These managers set the active " @@ -6853,7 +8748,7 @@ msgstr "" "no contexto decimal atual, no corpo contido na instrução :keyword:`with`, " "sem afetar o código fora da instrução :keyword:`!with`." -#: ../../library/stdtypes.rst:4860 +#: ../../library/stdtypes.rst:5036 msgid "" "Exit the runtime context and return a Boolean flag indicating if any " "exception that occurred should be suppressed. If an exception occurred while " @@ -6868,7 +8763,7 @@ msgstr "" "(situação da pilha de execução). Caso contrário, os três argumentos são " "``None``." -#: ../../library/stdtypes.rst:4865 +#: ../../library/stdtypes.rst:5041 msgid "" "Returning a true value from this method will cause the :keyword:`with` " "statement to suppress the exception and continue execution with the " @@ -6885,7 +8780,7 @@ msgstr "" "ocorrerem durante a execução deste método irão substituir qualquer exceção " "que tenha ocorrido dentro do corpo da instrução :keyword:`!with`." -#: ../../library/stdtypes.rst:4872 +#: ../../library/stdtypes.rst:5048 msgid "" "The exception passed in should never be reraised explicitly - instead, this " "method should return a false value to indicate that the method completed " @@ -6899,7 +8794,7 @@ msgstr "" "Isso permite ao código do gerenciador de contexto facilmente detectar se um " "método :meth:`~object.__exit__` realmente falhou ou não." -#: ../../library/stdtypes.rst:4878 +#: ../../library/stdtypes.rst:5054 msgid "" "Python defines several context managers to support easy thread " "synchronisation, prompt closure of files or other objects, and simpler " @@ -6914,7 +8809,7 @@ msgstr "" "implementação e do protocolo do gerenciador de contexto. Veja o módulo :mod:" "`contextlib` para alguns exemplos." -#: ../../library/stdtypes.rst:4884 +#: ../../library/stdtypes.rst:5060 msgid "" "Python's :term:`generator`\\s and the :class:`contextlib.contextmanager` " "decorator provide a convenient way to implement these protocols. If a " @@ -6931,7 +8826,7 @@ msgstr "" "meth:`~contextmanager.__exit__`, em vez de o iterador produzido por uma " "função geradora não decorada." -#: ../../library/stdtypes.rst:4891 +#: ../../library/stdtypes.rst:5067 msgid "" "Note that there is no specific slot for any of these methods in the type " "structure for Python objects in the Python/C API. Extension types wanting to " @@ -6946,7 +8841,7 @@ msgstr "" "contexto em tempo de execução, a sobrecarga na pesquisa de dicionário em uma " "única classe é negligenciável." -#: ../../library/stdtypes.rst:4899 +#: ../../library/stdtypes.rst:5075 msgid "" "Type Annotation Types --- :ref:`Generic Alias `, :ref:" "`Union `" @@ -6954,7 +8849,7 @@ msgstr "" "Tipos de anotação de tipo --- :ref:`Apelido genérico `, :" "ref:`União `" -#: ../../library/stdtypes.rst:4904 +#: ../../library/stdtypes.rst:5080 msgid "" "The core built-in types for :term:`type annotations ` are :ref:" "`Generic Alias ` and :ref:`Union `." @@ -6963,11 +8858,11 @@ msgstr "" "são :ref:`Apelido genérico ` e :ref:`União `." -#: ../../library/stdtypes.rst:4911 +#: ../../library/stdtypes.rst:5087 msgid "Generic Alias Type" msgstr "Tipo Generic Alias" -#: ../../library/stdtypes.rst:4917 +#: ../../library/stdtypes.rst:5093 msgid "" "``GenericAlias`` objects are generally created by :ref:`subscripting " "` a class. They are most often used with :ref:`container " @@ -6984,7 +8879,7 @@ msgstr "" "são destinados principalmente para uso com :term:`anotações de tipo " "`." -#: ../../library/stdtypes.rst:4927 +#: ../../library/stdtypes.rst:5103 msgid "" "It is generally only possible to subscript a class if the class implements " "the special method :meth:`~object.__class_getitem__`." @@ -6992,7 +8887,7 @@ msgstr "" "Geralmente só é possível subscrever uma classe se a classe implementar o " "método especial :meth:`~object.__class_getitem__`." -#: ../../library/stdtypes.rst:4930 +#: ../../library/stdtypes.rst:5106 msgid "" "A ``GenericAlias`` object acts as a proxy for a :term:`generic type`, " "implementing *parameterized generics*." @@ -7000,7 +8895,7 @@ msgstr "" "Um objeto ``GenericAlias`` atua como um proxy para um :term:`tipo genérico`, " "implementando *genéricos parametrizados*." -#: ../../library/stdtypes.rst:4933 +#: ../../library/stdtypes.rst:5109 msgid "" "For a container class, the argument(s) supplied to a :ref:`subscription " "` of the class may indicate the type(s) of the elements an " @@ -7014,7 +8909,7 @@ msgstr "" "em anotações de tipo para significar um :class:`set` em que todos os " "elementos são do tipo :class:`bytes`." -#: ../../library/stdtypes.rst:4939 +#: ../../library/stdtypes.rst:5115 msgid "" "For a class which defines :meth:`~object.__class_getitem__` but is not a " "container, the argument(s) supplied to a subscription of the class will " @@ -7028,7 +8923,7 @@ msgstr "" "em um objeto. Por exemplo, :mod:`expressões regulares ` podem ser usadas " "tanto no tipo de dados :class:`str` quanto no tipo de dados :class:`bytes`:" -#: ../../library/stdtypes.rst:4945 +#: ../../library/stdtypes.rst:5121 msgid "" "If ``x = re.search('foo', 'foo')``, ``x`` will be a :ref:`re.Match ` object where the return values of ``x.group(0)`` and ``x[0]`` will " @@ -7040,7 +8935,7 @@ msgstr "" "serão ambos do tipo :class:`str`. Podemos representar este tipo de objeto em " "anotações de tipo com o ``GenericAlias`` ``re.Match[str]``." -#: ../../library/stdtypes.rst:4951 +#: ../../library/stdtypes.rst:5127 msgid "" "If ``y = re.search(b'bar', b'bar')``, (note the ``b`` for :class:`bytes`), " "``y`` will also be an instance of ``re.Match``, but the return values of ``y." @@ -7054,7 +8949,7 @@ msgstr "" "anotações de tipo, representaríamos esta variedade de objetos :ref:`re.Match " "` com ``re.Match[bytes]``." -#: ../../library/stdtypes.rst:4957 +#: ../../library/stdtypes.rst:5133 msgid "" "``GenericAlias`` objects are instances of the class :class:`types." "GenericAlias`, which can also be used to create ``GenericAlias`` objects " @@ -7064,7 +8959,7 @@ msgstr "" "GenericAlias`, que também podem ser usadas para criar objetos " "``GenericAlias`` diretamente." -#: ../../library/stdtypes.rst:4963 +#: ../../library/stdtypes.rst:5139 msgid "" "Creates a ``GenericAlias`` representing a type ``T`` parameterized by types " "*X*, *Y*, and more depending on the ``T`` used. For example, a function " @@ -7074,7 +8969,15 @@ msgstr "" "*X*, *Y* e mais, dependendo do ``T`` usados. Por exemplo, uma função " "esperando uma :class:`list` contendo elementos :class:`float`::" -#: ../../library/stdtypes.rst:4971 +#: ../../library/stdtypes.rst:5144 +msgid "" +"def average(values: list[float]) -> float:\n" +" return sum(values) / len(values)" +msgstr "" +"def average(values: list[float]) -> float:\n" +" return sum(values) / len(values)" + +#: ../../library/stdtypes.rst:5147 msgid "" "Another example for :term:`mapping` objects, using a :class:`dict`, which is " "a generic type expecting two type parameters representing the key type and " @@ -7087,7 +8990,15 @@ msgstr "" "espera um ``dict`` com chaves do tipo :class:`str` e valores do tipo :class:" "`int`::" -#: ../../library/stdtypes.rst:4979 +#: ../../library/stdtypes.rst:5152 +msgid "" +"def send_post_request(url: str, body: dict[str, int]) -> None:\n" +" ..." +msgstr "" +"def send_post_request(url: str, body: dict[str, int]) -> None:\n" +" ..." + +#: ../../library/stdtypes.rst:5155 msgid "" "The builtin functions :func:`isinstance` and :func:`issubclass` do not " "accept ``GenericAlias`` types for their second argument::" @@ -7095,7 +9006,19 @@ msgstr "" "As funções embutidas :func:`isinstance` e :func:`issubclass` não aceitam " "tipos ``GenericAlias`` para o seu segundo argumento::" -#: ../../library/stdtypes.rst:4987 +#: ../../library/stdtypes.rst:5158 +msgid "" +">>> isinstance([1, 2], list[str])\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: isinstance() argument 2 cannot be a parameterized generic" +msgstr "" +">>> isinstance([1, 2], list[str])\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: isinstance() argument 2 cannot be a parameterized generic" + +#: ../../library/stdtypes.rst:5163 msgid "" "The Python runtime does not enforce :term:`type annotations `. " "This extends to generic types and their type parameters. When creating a " @@ -7109,7 +9032,17 @@ msgstr "" "verificados pelo seu tipo. Por exemplo, o seguinte código é desencorajado, " "mas irá executar sem erros::" -#: ../../library/stdtypes.rst:4997 +#: ../../library/stdtypes.rst:5169 +msgid "" +">>> t = list[str]\n" +">>> t([1, 2, 3])\n" +"[1, 2, 3]" +msgstr "" +">>> t = list[str]\n" +">>> t([1, 2, 3])\n" +"[1, 2, 3]" + +#: ../../library/stdtypes.rst:5173 msgid "" "Furthermore, parameterized generics erase type parameters during object " "creation::" @@ -7117,7 +9050,25 @@ msgstr "" "Além disso, genéricos parametrizados removem parâmetros tipados durante a " "criação do objeto::" -#: ../../library/stdtypes.rst:5008 +#: ../../library/stdtypes.rst:5176 +msgid "" +">>> t = list[str]\n" +">>> type(t)\n" +"\n" +"\n" +">>> l = t()\n" +">>> type(l)\n" +"" +msgstr "" +">>> t = list[str]\n" +">>> type(t)\n" +"\n" +"\n" +">>> l = t()\n" +">>> type(l)\n" +"" + +#: ../../library/stdtypes.rst:5184 msgid "" "Calling :func:`repr` or :func:`str` on a generic shows the parameterized " "type::" @@ -7125,7 +9076,21 @@ msgstr "" "Chamar :func:`repr` ou :func:`str` sobre um genérico mostra o tipo " "parametrizado::" -#: ../../library/stdtypes.rst:5016 +#: ../../library/stdtypes.rst:5186 +msgid "" +">>> repr(list[int])\n" +"'list[int]'\n" +"\n" +">>> str(list[int])\n" +"'list[int]'" +msgstr "" +">>> repr(list[int])\n" +"'list[int]'\n" +"\n" +">>> str(list[int])\n" +"'list[int]'" + +#: ../../library/stdtypes.rst:5192 msgid "" "The :meth:`~object.__getitem__` method of generic containers will raise an " "exception to disallow mistakes like ``dict[str][str]``::" @@ -7133,7 +9098,19 @@ msgstr "" "O método :meth:`~object.__getitem__` de contêineres genéricos irá levantar " "uma exceção para não permitir erros como ``dict[str][str]``::" -#: ../../library/stdtypes.rst:5024 +#: ../../library/stdtypes.rst:5195 +msgid "" +">>> dict[str][str]\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: dict[str] is not a generic class" +msgstr "" +">>> dict[str][str]\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: dict[str] is not a generic class" + +#: ../../library/stdtypes.rst:5200 msgid "" "However, such expressions are valid when :ref:`type variables ` " "are used. The index must have as many elements as there are type variable " @@ -7144,11 +9121,23 @@ msgstr "" "itens de variável de tipo no objeto ``GenericAlias`` :attr:`~genericalias." "__args__`. ::" -#: ../../library/stdtypes.rst:5035 +#: ../../library/stdtypes.rst:5204 +msgid "" +">>> from typing import TypeVar\n" +">>> Y = TypeVar('Y')\n" +">>> dict[str, Y][int]\n" +"dict[str, int]" +msgstr "" +">>> from typing import TypeVar\n" +">>> Y = TypeVar('Y')\n" +">>> dict[str, Y][int]\n" +"dict[str, int]" + +#: ../../library/stdtypes.rst:5211 msgid "Standard Generic Classes" msgstr "Classes genéricas padrão" -#: ../../library/stdtypes.rst:5037 +#: ../../library/stdtypes.rst:5213 msgid "" "The following standard library classes support parameterized generics. This " "list is non-exhaustive." @@ -7156,237 +9145,253 @@ msgstr "" "As seguintes classes de biblioteca padrão oferecem suporte a genéricos " "parametrizados. Esta lista não é exaustiva." -#: ../../library/stdtypes.rst:5040 +#: ../../library/stdtypes.rst:5216 msgid ":class:`tuple`" msgstr ":class:`tuple`" -#: ../../library/stdtypes.rst:5041 +#: ../../library/stdtypes.rst:5217 msgid ":class:`list`" msgstr ":class:`list`" -#: ../../library/stdtypes.rst:5042 +#: ../../library/stdtypes.rst:5218 msgid ":class:`dict`" msgstr ":class:`dict`" -#: ../../library/stdtypes.rst:5043 +#: ../../library/stdtypes.rst:5219 msgid ":class:`set`" msgstr ":class:`set`" -#: ../../library/stdtypes.rst:5044 +#: ../../library/stdtypes.rst:5220 msgid ":class:`frozenset`" msgstr ":class:`frozenset`" -#: ../../library/stdtypes.rst:5045 +#: ../../library/stdtypes.rst:5221 msgid ":class:`type`" msgstr ":class:`type`" -#: ../../library/stdtypes.rst:5046 +#: ../../library/stdtypes.rst:5222 +msgid ":class:`asyncio.Future`" +msgstr ":class:`asyncio.Future`" + +#: ../../library/stdtypes.rst:5223 +msgid ":class:`asyncio.Task`" +msgstr ":class:`asyncio.Task`" + +#: ../../library/stdtypes.rst:5224 msgid ":class:`collections.deque`" msgstr ":class:`collections.deque`" -#: ../../library/stdtypes.rst:5047 +#: ../../library/stdtypes.rst:5225 msgid ":class:`collections.defaultdict`" msgstr ":class:`collections.defaultdict`" -#: ../../library/stdtypes.rst:5048 +#: ../../library/stdtypes.rst:5226 msgid ":class:`collections.OrderedDict`" msgstr ":class:`collections.OrderedDict`" -#: ../../library/stdtypes.rst:5049 +#: ../../library/stdtypes.rst:5227 msgid ":class:`collections.Counter`" msgstr ":class:`collections.Counter`" -#: ../../library/stdtypes.rst:5050 +#: ../../library/stdtypes.rst:5228 msgid ":class:`collections.ChainMap`" msgstr ":class:`collections.ChainMap`" -#: ../../library/stdtypes.rst:5051 +#: ../../library/stdtypes.rst:5229 msgid ":class:`collections.abc.Awaitable`" msgstr ":class:`collections.abc.Awaitable`" -#: ../../library/stdtypes.rst:5052 +#: ../../library/stdtypes.rst:5230 msgid ":class:`collections.abc.Coroutine`" msgstr ":class:`collections.abc.Coroutine`" -#: ../../library/stdtypes.rst:5053 +#: ../../library/stdtypes.rst:5231 msgid ":class:`collections.abc.AsyncIterable`" msgstr ":class:`collections.abc.AsyncIterable`" -#: ../../library/stdtypes.rst:5054 +#: ../../library/stdtypes.rst:5232 msgid ":class:`collections.abc.AsyncIterator`" msgstr ":class:`collections.abc.AsyncIterator`" -#: ../../library/stdtypes.rst:5055 +#: ../../library/stdtypes.rst:5233 msgid ":class:`collections.abc.AsyncGenerator`" msgstr ":class:`collections.abc.AsyncGenerator`" -#: ../../library/stdtypes.rst:5056 +#: ../../library/stdtypes.rst:5234 msgid ":class:`collections.abc.Iterable`" msgstr ":class:`collections.abc.Iterable`" -#: ../../library/stdtypes.rst:5057 +#: ../../library/stdtypes.rst:5235 msgid ":class:`collections.abc.Iterator`" msgstr ":class:`collections.abc.Iterator`" -#: ../../library/stdtypes.rst:5058 +#: ../../library/stdtypes.rst:5236 msgid ":class:`collections.abc.Generator`" msgstr ":class:`collections.abc.Generator`" -#: ../../library/stdtypes.rst:5059 +#: ../../library/stdtypes.rst:5237 msgid ":class:`collections.abc.Reversible`" msgstr ":class:`collections.abc.Reversible`" -#: ../../library/stdtypes.rst:5060 +#: ../../library/stdtypes.rst:5238 msgid ":class:`collections.abc.Container`" msgstr ":class:`collections.abc.Container`" -#: ../../library/stdtypes.rst:5061 +#: ../../library/stdtypes.rst:5239 msgid ":class:`collections.abc.Collection`" msgstr ":class:`collections.abc.Collection`" -#: ../../library/stdtypes.rst:5062 +#: ../../library/stdtypes.rst:5240 msgid ":class:`collections.abc.Callable`" msgstr ":class:`collections.abc.Callable`" -#: ../../library/stdtypes.rst:5063 +#: ../../library/stdtypes.rst:5241 msgid ":class:`collections.abc.Set`" msgstr ":class:`collections.abc.Set`" -#: ../../library/stdtypes.rst:5064 +#: ../../library/stdtypes.rst:5242 msgid ":class:`collections.abc.MutableSet`" msgstr ":class:`collections.abc.MutableSet`" -#: ../../library/stdtypes.rst:5065 +#: ../../library/stdtypes.rst:5243 msgid ":class:`collections.abc.Mapping`" msgstr ":class:`collections.abc.Mapping`" -#: ../../library/stdtypes.rst:5066 +#: ../../library/stdtypes.rst:5244 msgid ":class:`collections.abc.MutableMapping`" msgstr ":class:`collections.abc.MutableMapping`" -#: ../../library/stdtypes.rst:5067 +#: ../../library/stdtypes.rst:5245 msgid ":class:`collections.abc.Sequence`" msgstr ":class:`collections.abc.Sequence`" -#: ../../library/stdtypes.rst:5068 +#: ../../library/stdtypes.rst:5246 msgid ":class:`collections.abc.MutableSequence`" msgstr ":class:`collections.abc.MutableSequence`" -#: ../../library/stdtypes.rst:5069 +#: ../../library/stdtypes.rst:5247 msgid ":class:`collections.abc.ByteString`" msgstr ":class:`collections.abc.ByteString`" -#: ../../library/stdtypes.rst:5070 +#: ../../library/stdtypes.rst:5248 msgid ":class:`collections.abc.MappingView`" msgstr ":class:`collections.abc.MappingView`" -#: ../../library/stdtypes.rst:5071 +#: ../../library/stdtypes.rst:5249 msgid ":class:`collections.abc.KeysView`" msgstr ":class:`collections.abc.KeysView`" -#: ../../library/stdtypes.rst:5072 +#: ../../library/stdtypes.rst:5250 msgid ":class:`collections.abc.ItemsView`" msgstr ":class:`collections.abc.ItemsView`" -#: ../../library/stdtypes.rst:5073 +#: ../../library/stdtypes.rst:5251 msgid ":class:`collections.abc.ValuesView`" msgstr ":class:`collections.abc.ValuesView`" -#: ../../library/stdtypes.rst:5074 +#: ../../library/stdtypes.rst:5252 msgid ":class:`contextlib.AbstractContextManager`" msgstr ":class:`contextlib.AbstractContextManager`" -#: ../../library/stdtypes.rst:5075 +#: ../../library/stdtypes.rst:5253 msgid ":class:`contextlib.AbstractAsyncContextManager`" msgstr ":class:`contextlib.AbstractAsyncContextManager`" -#: ../../library/stdtypes.rst:5076 +#: ../../library/stdtypes.rst:5254 msgid ":class:`dataclasses.Field`" msgstr ":class:`dataclasses.Field`" -#: ../../library/stdtypes.rst:5077 +#: ../../library/stdtypes.rst:5255 msgid ":class:`functools.cached_property`" msgstr ":class:`functools.cached_property`" -#: ../../library/stdtypes.rst:5078 +#: ../../library/stdtypes.rst:5256 msgid ":class:`functools.partialmethod`" msgstr ":class:`functools.partialmethod`" -#: ../../library/stdtypes.rst:5079 +#: ../../library/stdtypes.rst:5257 msgid ":class:`os.PathLike`" msgstr ":class:`os.PathLike`" -#: ../../library/stdtypes.rst:5080 +#: ../../library/stdtypes.rst:5258 msgid ":class:`queue.LifoQueue`" msgstr ":class:`queue.LifoQueue`" -#: ../../library/stdtypes.rst:5081 +#: ../../library/stdtypes.rst:5259 msgid ":class:`queue.Queue`" msgstr ":class:`queue.Queue`" -#: ../../library/stdtypes.rst:5082 +#: ../../library/stdtypes.rst:5260 msgid ":class:`queue.PriorityQueue`" msgstr ":class:`queue.PriorityQueue`" -#: ../../library/stdtypes.rst:5083 +#: ../../library/stdtypes.rst:5261 msgid ":class:`queue.SimpleQueue`" msgstr ":class:`queue.SimpleQueue`" -#: ../../library/stdtypes.rst:5084 +#: ../../library/stdtypes.rst:5262 msgid ":ref:`re.Pattern `" msgstr ":ref:`re.Pattern `" -#: ../../library/stdtypes.rst:5085 +#: ../../library/stdtypes.rst:5263 msgid ":ref:`re.Match `" msgstr ":ref:`re.Match `" -#: ../../library/stdtypes.rst:5086 +#: ../../library/stdtypes.rst:5264 msgid ":class:`shelve.BsdDbShelf`" msgstr ":class:`shelve.BsdDbShelf`" -#: ../../library/stdtypes.rst:5087 +#: ../../library/stdtypes.rst:5265 msgid ":class:`shelve.DbfilenameShelf`" msgstr ":class:`shelve.DbfilenameShelf`" -#: ../../library/stdtypes.rst:5088 +#: ../../library/stdtypes.rst:5266 msgid ":class:`shelve.Shelf`" msgstr ":class:`shelve.Shelf`" -#: ../../library/stdtypes.rst:5089 +#: ../../library/stdtypes.rst:5267 msgid ":class:`types.MappingProxyType`" msgstr ":class:`types.MappingProxyType`" -#: ../../library/stdtypes.rst:5090 +#: ../../library/stdtypes.rst:5268 msgid ":class:`weakref.WeakKeyDictionary`" msgstr ":class:`weakref.WeakKeyDictionary`" -#: ../../library/stdtypes.rst:5091 +#: ../../library/stdtypes.rst:5269 msgid ":class:`weakref.WeakMethod`" msgstr ":class:`weakref.WeakMethod`" -#: ../../library/stdtypes.rst:5092 +#: ../../library/stdtypes.rst:5270 msgid ":class:`weakref.WeakSet`" msgstr ":class:`weakref.WeakSet`" -#: ../../library/stdtypes.rst:5093 +#: ../../library/stdtypes.rst:5271 msgid ":class:`weakref.WeakValueDictionary`" msgstr ":class:`weakref.WeakValueDictionary`" -#: ../../library/stdtypes.rst:5098 +#: ../../library/stdtypes.rst:5276 msgid "Special Attributes of ``GenericAlias`` objects" msgstr "Atributos especiais de objetos ``GenericAlias``" -#: ../../library/stdtypes.rst:5100 +#: ../../library/stdtypes.rst:5278 msgid "All parameterized generics implement special read-only attributes." msgstr "" "Todos os genéricos parametrizados implementam atributos especiais somente " "leitura." -#: ../../library/stdtypes.rst:5104 +#: ../../library/stdtypes.rst:5282 msgid "This attribute points at the non-parameterized generic class::" msgstr "Este atributo aponta para a classe genérica não parametrizada::" -#: ../../library/stdtypes.rst:5112 +#: ../../library/stdtypes.rst:5284 +msgid "" +">>> list[int].__origin__\n" +"" +msgstr "" +">>> list[int].__origin__\n" +"" + +#: ../../library/stdtypes.rst:5290 msgid "" "This attribute is a :class:`tuple` (possibly of length 1) of generic types " "passed to the original :meth:`~object.__class_getitem__` of the generic " @@ -7396,7 +9401,15 @@ msgstr "" "genéricos passado para o método :meth:`~object.__class_getitem__` original " "da classe genérica::" -#: ../../library/stdtypes.rst:5122 +#: ../../library/stdtypes.rst:5294 +msgid "" +">>> dict[str, list[int]].__args__\n" +"(, list[int])" +msgstr "" +">>> dict[str, list[int]].__args__\n" +"(, list[int])" + +#: ../../library/stdtypes.rst:5300 msgid "" "This attribute is a lazily computed tuple (possibly empty) of unique type " "variables found in ``__args__``::" @@ -7404,7 +9417,21 @@ msgstr "" "O atributo é uma tupla computada preguiçosamente (possivelmente vazia) de " "variáveis de tipo único encontradas em ``__args__``::" -#: ../../library/stdtypes.rst:5133 +#: ../../library/stdtypes.rst:5303 +msgid "" +">>> from typing import TypeVar\n" +"\n" +">>> T = TypeVar('T')\n" +">>> list[T].__parameters__\n" +"(~T,)" +msgstr "" +">>> from typing import TypeVar\n" +"\n" +">>> T = TypeVar('T')\n" +">>> list[T].__parameters__\n" +"(~T,)" + +#: ../../library/stdtypes.rst:5311 msgid "" "A ``GenericAlias`` object with :class:`typing.ParamSpec` parameters may not " "have correct ``__parameters__`` after substitution because :class:`typing." @@ -7414,7 +9441,7 @@ msgstr "" "não ter ``__parameters__`` correto após a substituição porque :class:`typing." "ParamSpec` se destina principalmente à verificação de tipo estático." -#: ../../library/stdtypes.rst:5140 +#: ../../library/stdtypes.rst:5318 msgid "" "A boolean that is true if the alias has been unpacked using the ``*`` " "operator (see :data:`~typing.TypeVarTuple`)." @@ -7422,19 +9449,19 @@ msgstr "" "Um booleano que é true se o apelido foi desempacotado usando o operador " "``*`` (consulte :data:`~typing.TypeVarTuple`)." -#: ../../library/stdtypes.rst:5148 +#: ../../library/stdtypes.rst:5326 msgid ":pep:`484` - Type Hints" -msgstr ":pep:`484` - Dicas de tipos" +msgstr ":pep:`484` - Dicas de tipo" -#: ../../library/stdtypes.rst:5149 +#: ../../library/stdtypes.rst:5327 msgid "Introducing Python's framework for type annotations." msgstr "Apresentando a estrutura do Python para anotações de tipo." -#: ../../library/stdtypes.rst:5151 +#: ../../library/stdtypes.rst:5329 msgid ":pep:`585` - Type Hinting Generics In Standard Collections" msgstr ":pep:`585` - Sugestão de tipo para Genéricos em coleções padrão" -#: ../../library/stdtypes.rst:5152 +#: ../../library/stdtypes.rst:5330 msgid "" "Introducing the ability to natively parameterize standard-library classes, " "provided they implement the special class method :meth:`~object." @@ -7444,7 +9471,7 @@ msgstr "" "biblioteca padrão, desde que implementem o método de classe especial :meth:" "`~object.__class_getitem__`." -#: ../../library/stdtypes.rst:5156 +#: ../../library/stdtypes.rst:5334 msgid "" ":ref:`Generics`, :ref:`user-defined generics ` and :" "class:`typing.Generic`" @@ -7452,7 +9479,7 @@ msgstr "" ":ref:`Generics`, :ref:`genéricos definidos pelo usuário ` e :class:`typing.Generic`" -#: ../../library/stdtypes.rst:5157 +#: ../../library/stdtypes.rst:5335 msgid "" "Documentation on how to implement generic classes that can be parameterized " "at runtime and understood by static type-checkers." @@ -7461,11 +9488,11 @@ msgstr "" "parametrizadas em tempo de execução e compreendidas por verificadores de " "tipo estático." -#: ../../library/stdtypes.rst:5166 +#: ../../library/stdtypes.rst:5344 msgid "Union Type" msgstr "Tipo União" -#: ../../library/stdtypes.rst:5172 +#: ../../library/stdtypes.rst:5350 msgid "" "A union object holds the value of the ``|`` (bitwise or) operation on " "multiple :ref:`type objects `. These types are intended " @@ -7479,7 +9506,7 @@ msgstr "" "tipo de união habilita a sintaxe de sugestão de tipo mais limpo em " "comparação com :data:`typing.Union`." -#: ../../library/stdtypes.rst:5179 +#: ../../library/stdtypes.rst:5357 msgid "" "Defines a union object which holds types *X*, *Y*, and so forth. ``X | Y`` " "means either X or Y. It is equivalent to ``typing.Union[X, Y]``. For " @@ -7491,7 +9518,15 @@ msgstr "" "a seguinte função espera um argumento do tipo :class:`int` ou :class:" "`float`::" -#: ../../library/stdtypes.rst:5189 +#: ../../library/stdtypes.rst:5362 +msgid "" +"def square(number: int | float) -> int | float:\n" +" return number ** 2" +msgstr "" +"def square(number: int | float) -> int | float:\n" +" return number ** 2" + +#: ../../library/stdtypes.rst:5367 msgid "" "The ``|`` operand cannot be used at runtime to define unions where one or " "more members is a forward reference. For example, ``int | \"Foo\"``, where " @@ -7506,34 +9541,54 @@ msgstr "" "futuras, apresente a expressão inteira como uma string, por exemplo. ``\"int " "| Foo\"``." -#: ../../library/stdtypes.rst:5197 +#: ../../library/stdtypes.rst:5375 msgid "" "Union objects can be tested for equality with other union objects. Details:" msgstr "" "Os objetos união podem ser testados quanto à igualdade com outros objetos " "união. Detalhes:" -#: ../../library/stdtypes.rst:5199 +#: ../../library/stdtypes.rst:5377 msgid "Unions of unions are flattened::" msgstr "Uniões de uniões são achatadas::" -#: ../../library/stdtypes.rst:5203 +#: ../../library/stdtypes.rst:5379 +msgid "(int | str) | float == int | str | float" +msgstr "(int | str) | float == int | str | float" + +#: ../../library/stdtypes.rst:5381 msgid "Redundant types are removed::" msgstr "Tipos redundantes são removidos::" -#: ../../library/stdtypes.rst:5207 +#: ../../library/stdtypes.rst:5383 +msgid "int | str | int == int | str" +msgstr "int | str | int == int | str" + +#: ../../library/stdtypes.rst:5385 msgid "When comparing unions, the order is ignored::" msgstr "Ao comparar uniões, a ordem é ignorada::" -#: ../../library/stdtypes.rst:5211 +#: ../../library/stdtypes.rst:5387 +msgid "int | str == str | int" +msgstr "int | str == str | int" + +#: ../../library/stdtypes.rst:5389 msgid "It is compatible with :data:`typing.Union`::" msgstr "É compatível com :data:`typing.Union`::" -#: ../../library/stdtypes.rst:5215 +#: ../../library/stdtypes.rst:5391 +msgid "int | str == typing.Union[int, str]" +msgstr "int | str == typing.Union[int, str]" + +#: ../../library/stdtypes.rst:5393 msgid "Optional types can be spelled as a union with ``None``::" msgstr "Tipos opcionais podem ser escritos como uma união com ``None``::" -#: ../../library/stdtypes.rst:5222 +#: ../../library/stdtypes.rst:5395 +msgid "str | None == typing.Optional[str]" +msgstr "str | None == typing.Optional[str]" + +#: ../../library/stdtypes.rst:5400 msgid "" "Calls to :func:`isinstance` and :func:`issubclass` are also supported with a " "union object::" @@ -7541,7 +9596,15 @@ msgstr "" "Chamadas para :func:`isinstance` e :func:`issubclass` também são suportados " "com um objeto união::" -#: ../../library/stdtypes.rst:5228 +#: ../../library/stdtypes.rst:5403 +msgid "" +">>> isinstance(\"\", int | str)\n" +"True" +msgstr "" +">>> isinstance(\"\", int | str)\n" +"True" + +#: ../../library/stdtypes.rst:5406 msgid "" "However, :ref:`parameterized generics ` in union objects " "cannot be checked::" @@ -7549,7 +9612,23 @@ msgstr "" "No entanto, :ref:`genéricos parametrizados ` em objetos " "de união não podem ser verificados::" -#: ../../library/stdtypes.rst:5238 +#: ../../library/stdtypes.rst:5409 +msgid "" +">>> isinstance(1, int | list[int]) # short-circuit evaluation\n" +"True\n" +">>> isinstance([1], int | list[int])\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: isinstance() argument 2 cannot be a parameterized generic" +msgstr "" +">>> isinstance(1, int | list[int]) # cálculo em curto-circuito\n" +"True\n" +">>> isinstance([1], int | list[int])\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: isinstance() argument 2 cannot be a parameterized generic" + +#: ../../library/stdtypes.rst:5416 msgid "" "The user-exposed type for the union object can be accessed from :data:`types." "UnionType` and used for :func:`isinstance` checks. An object cannot be " @@ -7559,7 +9638,25 @@ msgstr "" "data:`types.UnionType` e usado por verificações de :func:`isinstance`. Um " "objeto não pode ser instanciado a partir do tipo::" -#: ../../library/stdtypes.rst:5251 +#: ../../library/stdtypes.rst:5420 +msgid "" +">>> import types\n" +">>> isinstance(int | str, types.UnionType)\n" +"True\n" +">>> types.UnionType()\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: cannot create 'types.UnionType' instances" +msgstr "" +">>> import types\n" +">>> isinstance(int | str, types.UnionType)\n" +"True\n" +">>> types.UnionType()\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: cannot create 'types.UnionType' instances" + +#: ../../library/stdtypes.rst:5429 msgid "" "The :meth:`!__or__` method for type objects was added to support the syntax " "``X | Y``. If a metaclass implements :meth:`!__or__`, the Union may " @@ -7569,15 +9666,41 @@ msgstr "" "sintaxe ``X | Y``. Se uma metaclasse implementa :meth:`!__or__`, a União " "pode substituí-la:" -#: ../../library/stdtypes.rst:5271 +#: ../../library/stdtypes.rst:5433 +msgid "" +">>> class M(type):\n" +"... def __or__(self, other):\n" +"... return \"Hello\"\n" +"...\n" +">>> class C(metaclass=M):\n" +"... pass\n" +"...\n" +">>> C | int\n" +"'Hello'\n" +">>> int | C\n" +"int | C" +msgstr "" +">>> class M(type):\n" +"... def __or__(self, other):\n" +"... return \"Hello\"\n" +"...\n" +">>> class C(metaclass=M):\n" +"... pass\n" +"...\n" +">>> C | int\n" +"'Hello'\n" +">>> int | C\n" +"int | C" + +#: ../../library/stdtypes.rst:5449 msgid ":pep:`604` -- PEP proposing the ``X | Y`` syntax and the Union type." msgstr ":pep:`604` -- PEP propondo a sintaxe ``X | Y`` e o tipo União." -#: ../../library/stdtypes.rst:5279 +#: ../../library/stdtypes.rst:5457 msgid "Other Built-in Types" msgstr "Outros tipos embutidos" -#: ../../library/stdtypes.rst:5281 +#: ../../library/stdtypes.rst:5459 msgid "" "The interpreter supports several other kinds of objects. Most of these " "support only one or two operations." @@ -7585,11 +9708,11 @@ msgstr "" "O interpretador suporta diversos outros tipos de objetos. Maior parte " "desses, suporta apenas uma ou duas operações." -#: ../../library/stdtypes.rst:5288 +#: ../../library/stdtypes.rst:5466 msgid "Modules" msgstr "Módulos" -#: ../../library/stdtypes.rst:5290 +#: ../../library/stdtypes.rst:5468 msgid "" "The only special operation on a module is attribute access: ``m.name``, " "where *m* is a module and *name* accesses a name defined in *m*'s symbol " @@ -7607,7 +9730,7 @@ msgstr "" "exista, ao invés disso requer uma *definição* (externa) de um módulo chamado " "*foo* em algum lugar.)" -#: ../../library/stdtypes.rst:5297 +#: ../../library/stdtypes.rst:5475 msgid "" "A special attribute of every module is :attr:`~object.__dict__`. This is the " "dictionary containing the module's symbol table. Modifying this dictionary " @@ -7625,7 +9748,7 @@ msgstr "" "``1``, mas você não consegue escrever ``m.__dict__ = {}``). Modificar :attr:" "`~object.__dict__` diretamente não é recomendado." -#: ../../library/stdtypes.rst:5305 +#: ../../library/stdtypes.rst:5483 msgid "" "Modules built into the interpreter are written like this: ````. If loaded from a file, they are written as ````. Se carregados a partir de um arquivo, eles são escritos " "como ````." -#: ../../library/stdtypes.rst:5313 +#: ../../library/stdtypes.rst:5491 msgid "Classes and Class Instances" msgstr "Classes e Instâncias de Classes" -#: ../../library/stdtypes.rst:5315 +#: ../../library/stdtypes.rst:5493 msgid "See :ref:`objects` and :ref:`class` for these." msgstr "Veja :ref:`objects` e :ref:`class` para estes." -#: ../../library/stdtypes.rst:5321 +#: ../../library/stdtypes.rst:5499 msgid "Functions" msgstr "Funções" -#: ../../library/stdtypes.rst:5323 +#: ../../library/stdtypes.rst:5501 msgid "" "Function objects are created by function definitions. The only operation on " "a function object is to call it: ``func(argument-list)``." @@ -7656,7 +9779,7 @@ msgstr "" "que pode ser feita em um objeto função é chamá-la: ``func(lista-de-" "argumentos)``." -#: ../../library/stdtypes.rst:5326 +#: ../../library/stdtypes.rst:5504 msgid "" "There are really two flavors of function objects: built-in functions and " "user-defined functions. Both support the same operation (to call the " @@ -7668,15 +9791,15 @@ msgstr "" "função), mas a implementação é diferente, portanto os diferentes tipos de " "objetos." -#: ../../library/stdtypes.rst:5330 +#: ../../library/stdtypes.rst:5508 msgid "See :ref:`function` for more information." msgstr "Veja a função :ref:`function` para mais informações." -#: ../../library/stdtypes.rst:5336 +#: ../../library/stdtypes.rst:5514 msgid "Methods" msgstr "Métodos" -#: ../../library/stdtypes.rst:5340 +#: ../../library/stdtypes.rst:5518 msgid "" "Methods are functions that are called using the attribute notation. There " "are two flavors: :ref:`built-in methods ` (such as :meth:" @@ -7688,7 +9811,7 @@ msgstr "" "`append` em listas) e :ref:`métodos de instância de classe `. Métodos embutidos são descritos com os tipos que suportam eles." -#: ../../library/stdtypes.rst:5345 +#: ../../library/stdtypes.rst:5523 msgid "" "If you access a method (a function defined in a class namespace) through an " "instance, you get a special object: a :dfn:`bound method` (also called :ref:" @@ -7710,7 +9833,7 @@ msgstr "" "implementa o método. Chamar ``m(arg-1, arg-2, ..., arg-n)`` é completamente " "equivalente a chamar ``m.__func__(m.__self__, arg-1, arg-2, ..., arg-n)``." -#: ../../library/stdtypes.rst:5356 +#: ../../library/stdtypes.rst:5534 msgid "" "Like :ref:`function objects `, bound method objects " "support getting arbitrary attributes. However, since method attributes are " @@ -7728,15 +9851,44 @@ msgstr "" "`AttributeError` sendo levantado. A fim de definir um atributo de método, " "você precisa definir explicitamente ele no objeto função subjacente::" -#: ../../library/stdtypes.rst:5379 +#: ../../library/stdtypes.rst:5542 +msgid "" +">>> class C:\n" +"... def method(self):\n" +"... pass\n" +"...\n" +">>> c = C()\n" +">>> c.method.whoami = 'my name is method' # can't set on the method\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"AttributeError: 'method' object has no attribute 'whoami'\n" +">>> c.method.__func__.whoami = 'my name is method'\n" +">>> c.method.whoami\n" +"'my name is method'" +msgstr "" +">>> class C:\n" +"... def method(self):\n" +"... pass\n" +"...\n" +">>> c = C()\n" +">>> c.method.whoami = 'my name is method' # proibido atribuir diretamente " +"no método\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"AttributeError: 'method' object has no attribute 'whoami'\n" +">>> c.method.__func__.whoami = 'my name is method'\n" +">>> c.method.whoami\n" +"'my name is method'" + +#: ../../library/stdtypes.rst:5557 msgid "See :ref:`instance-methods` for more information." msgstr "Veja :ref:`instance-methods` para mais informações." -#: ../../library/stdtypes.rst:5387 +#: ../../library/stdtypes.rst:5565 msgid "Code Objects" msgstr "Objetos código" -#: ../../library/stdtypes.rst:5393 +#: ../../library/stdtypes.rst:5571 msgid "" "Code objects are used by the implementation to represent \"pseudo-compiled\" " "executable Python code such as a function body. They differ from function " @@ -7752,7 +9904,7 @@ msgstr "" "embutida :func:`compile` e podem ser extraídos de objetos função através do " "seu atributo :attr:`~function.__code__`. Veja também o módulo :mod:`code`." -#: ../../library/stdtypes.rst:5400 +#: ../../library/stdtypes.rst:5578 msgid "" "Accessing :attr:`~function.__code__` raises an :ref:`auditing event " "` ``object.__getattr__`` with arguments ``obj`` and " @@ -7762,7 +9914,7 @@ msgstr "" "` ``object.__getattr__`` com os argumentos ``obj`` e " "``\"__code__\"``." -#: ../../library/stdtypes.rst:5407 +#: ../../library/stdtypes.rst:5585 msgid "" "A code object can be executed or evaluated by passing it (instead of a " "source string) to the :func:`exec` or :func:`eval` built-in functions." @@ -7770,15 +9922,15 @@ msgstr "" "Um objeto de código pode ser executado ou avaliado passando-o (ao invés da " "string fonte) para as funções embutidas :func:`exec` ou :func:`eval`." -#: ../../library/stdtypes.rst:5410 +#: ../../library/stdtypes.rst:5588 msgid "See :ref:`types` for more information." msgstr "Veja o tipo :ref:`types` para maiores informações." -#: ../../library/stdtypes.rst:5416 +#: ../../library/stdtypes.rst:5594 msgid "Type Objects" msgstr "Objetos tipo" -#: ../../library/stdtypes.rst:5422 +#: ../../library/stdtypes.rst:5600 msgid "" "Type objects represent the various object types. An object's type is " "accessed by the built-in function :func:`type`. There are no special " @@ -7790,15 +9942,15 @@ msgstr "" "especiais sobre tipos. O módulo padrão :mod:`types` define nomes para todos " "os tipos padrão embutidos." -#: ../../library/stdtypes.rst:5427 +#: ../../library/stdtypes.rst:5605 msgid "Types are written like this: ````." msgstr "Tipos são escritos como isto: ````." -#: ../../library/stdtypes.rst:5433 +#: ../../library/stdtypes.rst:5611 msgid "The Null Object" msgstr "O objeto nulo" -#: ../../library/stdtypes.rst:5435 +#: ../../library/stdtypes.rst:5613 msgid "" "This object is returned by functions that don't explicitly return a value. " "It supports no special operations. There is exactly one null object, named " @@ -7809,15 +9961,15 @@ msgstr "" "objeto nulo, chamado de ``None`` (um nome embutido). ``type(None)()`` produz " "o mesmo singleton." -#: ../../library/stdtypes.rst:5439 +#: ../../library/stdtypes.rst:5617 msgid "It is written as ``None``." msgstr "Ele é escrito como ``None``." -#: ../../library/stdtypes.rst:5446 +#: ../../library/stdtypes.rst:5624 msgid "The Ellipsis Object" msgstr "O Objeto Ellipsis" -#: ../../library/stdtypes.rst:5448 +#: ../../library/stdtypes.rst:5626 msgid "" "This object is commonly used by slicing (see :ref:`slicings`). It supports " "no special operations. There is exactly one ellipsis object, named :const:" @@ -7829,15 +9981,15 @@ msgstr "" "nomeado :const:`Ellipsis` (um nome embutido). ``type(Ellipsis)()`` produz o " "singleton :const:`Ellipsis`." -#: ../../library/stdtypes.rst:5453 +#: ../../library/stdtypes.rst:5631 msgid "It is written as ``Ellipsis`` or ``...``." msgstr "Está escrito com ``Ellipsis`` ou ``...``." -#: ../../library/stdtypes.rst:5459 +#: ../../library/stdtypes.rst:5637 msgid "The NotImplemented Object" msgstr "O Objeto NotImplemented" -#: ../../library/stdtypes.rst:5461 +#: ../../library/stdtypes.rst:5639 msgid "" "This object is returned from comparisons and binary operations when they are " "asked to operate on types they don't support. See :ref:`comparisons` for " @@ -7849,15 +10001,15 @@ msgstr "" "ref:`comparisons` para mais informações. Existe exatamente um objeto :data:" "`NotImplemented`. :code:`type(NotImplemented)()` produz o mesmo valor." -#: ../../library/stdtypes.rst:5466 +#: ../../library/stdtypes.rst:5644 msgid "It is written as :code:`NotImplemented`." msgstr "Está escrito como :code:`NotImplemented`." -#: ../../library/stdtypes.rst:5472 +#: ../../library/stdtypes.rst:5650 msgid "Internal Objects" msgstr "Objetos Internos" -#: ../../library/stdtypes.rst:5474 +#: ../../library/stdtypes.rst:5652 msgid "" "See :ref:`types` for this information. It describes :ref:`stack frame " "objects `, :ref:`traceback objects `, and " @@ -7867,11 +10019,11 @@ msgstr "" "pilha `, :ref:`objetos traceback (situação da pilha de " "execução) `, e objetos fatia." -#: ../../library/stdtypes.rst:5482 +#: ../../library/stdtypes.rst:5660 msgid "Special Attributes" msgstr "Atributos Especiais" -#: ../../library/stdtypes.rst:5484 +#: ../../library/stdtypes.rst:5662 msgid "" "The implementation adds a few special read-only attributes to several object " "types, where they are relevant. Some of these are not reported by the :func:" @@ -7881,28 +10033,12 @@ msgstr "" "diversos tipos de objetos, onde eles são relevantes. Alguns desses não são " "reportados pela função embutida :func:`dir`." -#: ../../library/stdtypes.rst:5491 -msgid "" -"A dictionary or other mapping object used to store an object's (writable) " -"attributes." -msgstr "" -"Um dicionário ou outro objeto de mapeamento usado para armazenar os " -"atributos (graváveis) de um objeto." - -#: ../../library/stdtypes.rst:5497 -msgid "The class to which a class instance belongs." -msgstr "A classe à qual pertence uma instância de classe." - -#: ../../library/stdtypes.rst:5502 -msgid "The tuple of base classes of a class object." -msgstr "A tupla de classes base de um objeto classe." - -#: ../../library/stdtypes.rst:5507 +#: ../../library/stdtypes.rst:5669 msgid "" "The name of the class, function, method, descriptor, or generator instance." msgstr "O nome da classe, função, método, descritor, ou instância geradora." -#: ../../library/stdtypes.rst:5513 +#: ../../library/stdtypes.rst:5675 msgid "" "The :term:`qualified name` of the class, function, method, descriptor, or " "generator instance." @@ -7910,55 +10046,32 @@ msgstr "" "O :term:`nome qualificado ` da classe, função, método, " "descritor, ou instância geradora." -#: ../../library/stdtypes.rst:5521 -msgid "" -"The :ref:`type parameters ` of generic classes, functions, and :" -"ref:`type aliases `." -msgstr "" -"Os :ref:`parâmetros de tipo ` de classes genéricas, funções e :" -"ref:`apelidos de tipo `." - -#: ../../library/stdtypes.rst:5529 -msgid "" -"This attribute is a tuple of classes that are considered when looking for " -"base classes during method resolution." -msgstr "" -"Este atributo é uma tupla de classes que são consideradas ao procurar por " -"classes bases durante resolução de métodos." - -#: ../../library/stdtypes.rst:5535 -msgid "" -"This method can be overridden by a metaclass to customize the method " -"resolution order for its instances. It is called at class instantiation, " -"and its result is stored in :attr:`~class.__mro__`." -msgstr "" -"Este método pode ser substituído por uma metaclasse para customizar a ordem " -"de resolução de métodos para suas instâncias. Ele é chamado na instanciação " -"da classe, e o seu resultado é armazenado em :attr:`~class.__mro__`." +#: ../../library/stdtypes.rst:5683 +msgid "The name of the module in which a class or function was defined." +msgstr "O nome do módulo no qual uma classe ou função foi definida." -#: ../../library/stdtypes.rst:5542 +#: ../../library/stdtypes.rst:5688 msgid "" -"Each class keeps a list of weak references to its immediate subclasses. " -"This method returns a list of all those references still alive. The list is " -"in definition order. Example::" +"The documentation string of a class or function, or ``None`` if undefined." msgstr "" -"Cada classe mantém uma lista de referências fracas para suas subclasses " -"imediatas. Este método retorna uma lista de todas essas referências ainda " -"vivas. A lista está na ordem que são definidas. Exemplo::" +"A string de documentação de uma classe ou função, ou ``None`` se não " +"definida." -#: ../../library/stdtypes.rst:5552 +#: ../../library/stdtypes.rst:5693 msgid "" -"A tuple containing names of attributes of this class which are accessed " -"through ``self.X`` from any function in its body." +"The :ref:`type parameters ` of generic classes, functions, and :" +"ref:`type aliases `. For classes and functions that are not " +"generic, this will be an empty tuple." msgstr "" -"Uma tupla contendo nomes de atributos dessa classe que são acessados por " -"meio de ``self.X`` de qualquer função em seu corpo." +"Os :ref:`parâmetros de tipo ` de classes genéricas, funções e :" +"ref:`apelidos de tipo `. Para classes e funções que não são " +"genéricas, isso será uma tupla vazia." -#: ../../library/stdtypes.rst:5560 +#: ../../library/stdtypes.rst:5703 msgid "Integer string conversion length limitation" msgstr "Limitação de comprimento de string na conversão para inteiro" -#: ../../library/stdtypes.rst:5562 +#: ../../library/stdtypes.rst:5705 msgid "" "CPython has a global limit for converting between :class:`int` and :class:" "`str` to mitigate denial of service attacks. This limit *only* applies to " @@ -7971,7 +10084,7 @@ msgstr "" "As conversões hexadecimais, octais e binárias são ilimitadas. O limite pode " "ser configurado." -#: ../../library/stdtypes.rst:5567 +#: ../../library/stdtypes.rst:5710 msgid "" "The :class:`int` type in CPython is an arbitrary length number stored in " "binary form (commonly known as a \"bignum\"). There exists no algorithm that " @@ -7988,14 +10101,14 @@ msgstr "" "têm complexidade subquadrática. Converter um valor grande como ``int('1' * " "500_000)`` pode levar mais de um segundo em uma CPU rápida." -#: ../../library/stdtypes.rst:5574 +#: ../../library/stdtypes.rst:5717 msgid "" "Limiting conversion size offers a practical way to avoid :cve:`2020-10735`." msgstr "" "Limitar o tamanho da conversão oferece uma maneira prática de evitar :cve:" "`2020-10735`." -#: ../../library/stdtypes.rst:5576 +#: ../../library/stdtypes.rst:5719 msgid "" "The limit is applied to the number of digit characters in the input or " "output string when a non-linear conversion algorithm would be involved. " @@ -8005,14 +10118,59 @@ msgstr "" "ou saída quando um algoritmo de conversão não linear estiver envolvido. " "Sublinhados e o sinal não são contados para o limite." -#: ../../library/stdtypes.rst:5580 +#: ../../library/stdtypes.rst:5723 msgid "" "When an operation would exceed the limit, a :exc:`ValueError` is raised:" msgstr "" "Quando uma operação excede o limite, uma exceção :exc:`ValueError` é " "levantada:" -#: ../../library/stdtypes.rst:5602 +#: ../../library/stdtypes.rst:5725 +msgid "" +">>> import sys\n" +">>> sys.set_int_max_str_digits(4300) # Illustrative, this is the default.\n" +">>> _ = int('2' * 5432)\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: Exceeds the limit (4300 digits) for integer string conversion: " +"value has 5432 digits; use sys.set_int_max_str_digits() to increase the " +"limit\n" +">>> i = int('2' * 4300)\n" +">>> len(str(i))\n" +"4300\n" +">>> i_squared = i*i\n" +">>> len(str(i_squared))\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: Exceeds the limit (4300 digits) for integer string conversion; " +"use sys.set_int_max_str_digits() to increase the limit\n" +">>> len(hex(i_squared))\n" +"7144\n" +">>> assert int(hex(i_squared), base=16) == i*i # Hexadecimal is unlimited." +msgstr "" +">>> import sys\n" +">>> sys.set_int_max_str_digits(4300) # Illustrativo, este é o padrão.\n" +">>> _ = int('2' * 5432)\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: Exceeds the limit (4300 digits) for integer string conversion: " +"value has 5432 digits; use sys.set_int_max_str_digits() to increase the " +"limit\n" +">>> i = int('2' * 4300)\n" +">>> len(str(i))\n" +"4300\n" +">>> i_squared = i*i\n" +">>> len(str(i_squared))\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: Exceeds the limit (4300 digits) for integer string conversion; " +"use sys.set_int_max_str_digits() to increase the limit\n" +">>> len(hex(i_squared))\n" +"7144\n" +">>> assert int(hex(i_squared), base=16) == i*i # Conversão envolvendo " +"hexadecimais é ilimitada." + +#: ../../library/stdtypes.rst:5745 msgid "" "The default limit is 4300 digits as provided in :data:`sys.int_info." "default_max_str_digits `. The lowest limit that can be " @@ -8024,15 +10182,33 @@ msgstr "" "configurado é de 640 dígitos conforme fornecido em :data:`sys.int_info." "str_digits_check_threshold `." -#: ../../library/stdtypes.rst:5607 +#: ../../library/stdtypes.rst:5750 msgid "Verification:" msgstr "Verificação:" -#: ../../library/stdtypes.rst:5622 +#: ../../library/stdtypes.rst:5752 +msgid "" +">>> import sys\n" +">>> assert sys.int_info.default_max_str_digits == 4300, sys.int_info\n" +">>> assert sys.int_info.str_digits_check_threshold == 640, sys.int_info\n" +">>> msg = int('578966293710682886880994035146873798396722250538762761564'\n" +"... '9252925514383915483333812743580549779436104706260696366600'\n" +"... '571186405732').to_bytes(53, 'big')\n" +"..." +msgstr "" +">>> import sys\n" +">>> assert sys.int_info.default_max_str_digits == 4300, sys.int_info\n" +">>> assert sys.int_info.str_digits_check_threshold == 640, sys.int_info\n" +">>> msg = int('578966293710682886880994035146873798396722250538762761564'\n" +"... '9252925514383915483333812743580549779436104706260696366600'\n" +"... '571186405732').to_bytes(53, 'big')\n" +"..." + +#: ../../library/stdtypes.rst:5765 msgid "Affected APIs" msgstr "APIs afetadas" -#: ../../library/stdtypes.rst:5624 +#: ../../library/stdtypes.rst:5767 msgid "" "The limitation only applies to potentially slow conversions between :class:" "`int` and :class:`str` or :class:`bytes`:" @@ -8040,24 +10216,24 @@ msgstr "" "A limitação só se aplica a conversões potencialmente lentas entre :class:" "`int` e :class:`str` ou :class:`bytes`:" -#: ../../library/stdtypes.rst:5627 +#: ../../library/stdtypes.rst:5770 msgid "``int(string)`` with default base 10." msgstr "``int(string)`` com padrão sendo base 10." -#: ../../library/stdtypes.rst:5628 +#: ../../library/stdtypes.rst:5771 msgid "``int(string, base)`` for all bases that are not a power of 2." msgstr "" "``int(string, base)`` para todas as bases que não são uma potência de 2." -#: ../../library/stdtypes.rst:5629 +#: ../../library/stdtypes.rst:5772 msgid "``str(integer)``." msgstr "``str(integer)``." -#: ../../library/stdtypes.rst:5630 +#: ../../library/stdtypes.rst:5773 msgid "``repr(integer)``." msgstr "``repr(integer)``." -#: ../../library/stdtypes.rst:5631 +#: ../../library/stdtypes.rst:5774 msgid "" "any other string conversion to base 10, for example ``f\"{integer}\"``, " "``\"{}\".format(integer)``, or ``b\"%d\" % integer``." @@ -8065,39 +10241,39 @@ msgstr "" "qualquer outra conversão de string para base 10 como, por exemplo, " "``f\"{integer}\"``, ``\"{}\".format(integer)`` ou ``b\"%d\" % integer``." -#: ../../library/stdtypes.rst:5634 +#: ../../library/stdtypes.rst:5777 msgid "The limitations do not apply to functions with a linear algorithm:" msgstr "As limitações não se aplicam a funções com um algoritmo linear:" -#: ../../library/stdtypes.rst:5636 +#: ../../library/stdtypes.rst:5779 msgid "``int(string, base)`` with base 2, 4, 8, 16, or 32." msgstr "``int(string, base)`` com base 2, 4, 8, 16 ou 32." -#: ../../library/stdtypes.rst:5637 +#: ../../library/stdtypes.rst:5780 msgid ":func:`int.from_bytes` and :func:`int.to_bytes`." msgstr ":func:`int.from_bytes` e :func:`int.to_bytes`." -#: ../../library/stdtypes.rst:5638 +#: ../../library/stdtypes.rst:5781 msgid ":func:`hex`, :func:`oct`, :func:`bin`." msgstr ":func:`hex`, :func:`oct`, :func:`bin`." -#: ../../library/stdtypes.rst:5639 +#: ../../library/stdtypes.rst:5782 msgid ":ref:`formatspec` for hex, octal, and binary numbers." msgstr ":ref:`formatspec` para números hexa, octal e binários" -#: ../../library/stdtypes.rst:5640 +#: ../../library/stdtypes.rst:5783 msgid ":class:`str` to :class:`float`." msgstr ":class:`str` para :class:`float`." -#: ../../library/stdtypes.rst:5641 +#: ../../library/stdtypes.rst:5784 msgid ":class:`str` to :class:`decimal.Decimal`." msgstr ":class:`str` para :class:`decimal.Decimal`." -#: ../../library/stdtypes.rst:5644 +#: ../../library/stdtypes.rst:5787 msgid "Configuring the limit" msgstr "Configurando o limiter" -#: ../../library/stdtypes.rst:5646 +#: ../../library/stdtypes.rst:5789 msgid "" "Before Python starts up you can use an environment variable or an " "interpreter command line flag to configure the limit:" @@ -8105,7 +10281,7 @@ msgstr "" "Antes de iniciar o Python, você pode usar uma variável de ambiente ou um " "sinalizador de linha de comando do interpretador para configurar o limite:" -#: ../../library/stdtypes.rst:5649 +#: ../../library/stdtypes.rst:5792 msgid "" ":envvar:`PYTHONINTMAXSTRDIGITS`, e.g. ``PYTHONINTMAXSTRDIGITS=640 python3`` " "to set the limit to 640 or ``PYTHONINTMAXSTRDIGITS=0 python3`` to disable " @@ -8115,7 +10291,7 @@ msgstr "" "python3`` para definir o limite para 640 ou ``PYTHONINTMAXSTRDIGITS=0 " "python3`` para desabilitar a limitação." -#: ../../library/stdtypes.rst:5652 +#: ../../library/stdtypes.rst:5795 msgid "" ":option:`-X int_max_str_digits <-X>`, e.g. ``python3 -X " "int_max_str_digits=640``" @@ -8123,7 +10299,7 @@ msgstr "" ":option:`-X int_max_str_digits <-X>`, por exemplo ``python3 -X " "int_max_str_digits=640``" -#: ../../library/stdtypes.rst:5654 +#: ../../library/stdtypes.rst:5797 msgid "" ":data:`sys.flags.int_max_str_digits` contains the value of :envvar:" "`PYTHONINTMAXSTRDIGITS` or :option:`-X int_max_str_digits <-X>`. If both the " @@ -8138,7 +10314,7 @@ msgstr "" "portanto, um valor de :data:`sys.int_info.default_max_str_digits` foi usado " "durante a inicialização." -#: ../../library/stdtypes.rst:5660 +#: ../../library/stdtypes.rst:5803 msgid "" "From code, you can inspect the current limit and set a new one using these :" "mod:`sys` APIs:" @@ -8146,7 +10322,7 @@ msgstr "" "A partir do código, você pode inspecionar o limite atual e definir um novo " "usando estas APIs :mod:`sys`:" -#: ../../library/stdtypes.rst:5663 +#: ../../library/stdtypes.rst:5806 msgid "" ":func:`sys.get_int_max_str_digits` and :func:`sys.set_int_max_str_digits` " "are a getter and setter for the interpreter-wide limit. Subinterpreters have " @@ -8156,7 +10332,7 @@ msgstr "" "um getter e um setter para o limite de todo o interpretador. Os " "subinterpretadores têm seu próprio limite." -#: ../../library/stdtypes.rst:5667 +#: ../../library/stdtypes.rst:5810 msgid "" "Information about the default and minimum can be found in :data:`sys." "int_info`:" @@ -8164,7 +10340,7 @@ msgstr "" "Informações sobre o padrão e o mínimo podem ser encontradas em :data:`sys." "int_info`:" -#: ../../library/stdtypes.rst:5669 +#: ../../library/stdtypes.rst:5812 msgid "" ":data:`sys.int_info.default_max_str_digits ` is the compiled-" "in default limit." @@ -8172,7 +10348,7 @@ msgstr "" ":data:`sys.int_info.default_max_str_digits ` é o limite padrão " "compilado." -#: ../../library/stdtypes.rst:5671 +#: ../../library/stdtypes.rst:5814 msgid "" ":data:`sys.int_info.str_digits_check_threshold ` is the lowest " "accepted value for the limit (other than 0 which disables it)." @@ -8180,7 +10356,7 @@ msgstr "" ":data:`sys.int_info.str_digits_check_threshold ` é o menor " "valor aceito para o limite (diferente de 0 que o desabilita)." -#: ../../library/stdtypes.rst:5678 +#: ../../library/stdtypes.rst:5821 msgid "" "Setting a low limit *can* lead to problems. While rare, code exists that " "contains integer constants in decimal in their source that exceed the " @@ -8201,7 +10377,7 @@ msgstr "" "para source que contém tais constantes grandes é convertê-las para a forma " "hexadecimal ``0x``, pois não há limite." -#: ../../library/stdtypes.rst:5687 +#: ../../library/stdtypes.rst:5830 msgid "" "Test your application thoroughly if you use a low limit. Ensure your tests " "run with the limit set early via the environment or flag so that it applies " @@ -8214,11 +10390,11 @@ msgstr "" "inicialização e até mesmo durante qualquer etapa de instalação que possa " "invocar o Python para pré-compilar fontes ``.py`` para arquivos ``.pyc``." -#: ../../library/stdtypes.rst:5693 +#: ../../library/stdtypes.rst:5836 msgid "Recommended configuration" msgstr "Configuração recomendada" -#: ../../library/stdtypes.rst:5695 +#: ../../library/stdtypes.rst:5838 msgid "" "The default :data:`sys.int_info.default_max_str_digits` is expected to be " "reasonable for most applications. If your application requires a different " @@ -8231,19 +10407,41 @@ msgstr "" "agnóstico de versão Python, pois essas APIs foram adicionadas em lançamentos " "de patch de segurança em versões anteriores a 3.12." -#: ../../library/stdtypes.rst:5700 +#: ../../library/stdtypes.rst:5843 msgid "Example::" msgstr "Exemplo::" -#: ../../library/stdtypes.rst:5712 +#: ../../library/stdtypes.rst:5845 +msgid "" +">>> import sys\n" +">>> if hasattr(sys, \"set_int_max_str_digits\"):\n" +"... upper_bound = 68000\n" +"... lower_bound = 4004\n" +"... current_limit = sys.get_int_max_str_digits()\n" +"... if current_limit == 0 or current_limit > upper_bound:\n" +"... sys.set_int_max_str_digits(upper_bound)\n" +"... elif current_limit < lower_bound:\n" +"... sys.set_int_max_str_digits(lower_bound)" +msgstr "" +">>> import sys\n" +">>> if hasattr(sys, \"set_int_max_str_digits\"):\n" +"... upper_bound = 68000\n" +"... lower_bound = 4004\n" +"... current_limit = sys.get_int_max_str_digits()\n" +"... if current_limit == 0 or current_limit > upper_bound:\n" +"... sys.set_int_max_str_digits(upper_bound)\n" +"... elif current_limit < lower_bound:\n" +"... sys.set_int_max_str_digits(lower_bound)" + +#: ../../library/stdtypes.rst:5855 msgid "If you need to disable it entirely, set it to ``0``." msgstr "Se você precisar desativá-lo totalmente, defina-o como ``0``." -#: ../../library/stdtypes.rst:5716 +#: ../../library/stdtypes.rst:5859 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../library/stdtypes.rst:5717 +#: ../../library/stdtypes.rst:5860 msgid "" "Additional information on these special methods may be found in the Python " "Reference Manual (:ref:`customization`)." @@ -8252,7 +10450,7 @@ msgstr "" "no Manual de Referência do Python (:ref:`Customização básica " "`)." -#: ../../library/stdtypes.rst:5720 +#: ../../library/stdtypes.rst:5863 msgid "" "As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, " "and similarly for tuples." @@ -8260,13 +10458,13 @@ msgstr "" "Como uma consequência, a lista ``[1, 2]`` é considerada igual a ``[1.0, " "2.0]``, e similarmente para tuplas." -#: ../../library/stdtypes.rst:5723 +#: ../../library/stdtypes.rst:5866 msgid "They must have since the parser can't tell the type of the operands." msgstr "" "Eles precisam ter, já que o analisador sintático não consegue dizer o tipo " "dos operandos." -#: ../../library/stdtypes.rst:5725 +#: ../../library/stdtypes.rst:5868 msgid "" "Cased characters are those with general category property being one of " "\"Lu\" (Letter, uppercase), \"Ll\" (Letter, lowercase), or \"Lt\" (Letter, " @@ -8276,7 +10474,7 @@ msgstr "" "de categoria geral igual a \"Lu\" (Letra, maiúscula), \"Ll\" (Letra, " "minúscula), ou \"Lt\" (Letra, em formato de título)." -#: ../../library/stdtypes.rst:5728 +#: ../../library/stdtypes.rst:5871 msgid "" "To format only a tuple you should therefore provide a singleton tuple whose " "only element is the tuple to be formatted." @@ -8291,13 +10489,13 @@ msgstr "embutido" #: ../../library/stdtypes.rst:13 ../../library/stdtypes.rst:316 #: ../../library/stdtypes.rst:393 ../../library/stdtypes.rst:950 #: ../../library/stdtypes.rst:1117 ../../library/stdtypes.rst:1139 -#: ../../library/stdtypes.rst:1154 ../../library/stdtypes.rst:4435 -#: ../../library/stdtypes.rst:5418 +#: ../../library/stdtypes.rst:1154 ../../library/stdtypes.rst:4609 +#: ../../library/stdtypes.rst:5596 msgid "types" msgstr "types" #: ../../library/stdtypes.rst:34 ../../library/stdtypes.rst:1154 -#: ../../library/stdtypes.rst:4435 +#: ../../library/stdtypes.rst:4609 msgid "statement" msgstr "instrução" @@ -8315,7 +10513,7 @@ msgstr "verdade" #: ../../library/stdtypes.rst:34 msgid "value" -msgstr "value" +msgstr "valor" #: ../../library/stdtypes.rst:34 ../../library/stdtypes.rst:81 #: ../../library/stdtypes.rst:208 ../../library/stdtypes.rst:817 @@ -8388,7 +10586,7 @@ msgstr "==" #: ../../library/stdtypes.rst:123 msgid "< (less)" -msgstr "< (menor)" +msgstr "< (menor que)" #: ../../library/stdtypes.rst:123 msgid "<=" @@ -8419,11 +10617,11 @@ msgstr "is not" #: ../../library/stdtypes.rst:1139 ../../library/stdtypes.rst:1260 #: ../../library/stdtypes.rst:1339 ../../library/stdtypes.rst:1383 #: ../../library/stdtypes.rst:1504 ../../library/stdtypes.rst:1540 -#: ../../library/stdtypes.rst:2526 ../../library/stdtypes.rst:2545 -#: ../../library/stdtypes.rst:2652 ../../library/stdtypes.rst:4233 -#: ../../library/stdtypes.rst:4435 ../../library/stdtypes.rst:4913 -#: ../../library/stdtypes.rst:5168 ../../library/stdtypes.rst:5338 -#: ../../library/stdtypes.rst:5382 +#: ../../library/stdtypes.rst:2700 ../../library/stdtypes.rst:2719 +#: ../../library/stdtypes.rst:2826 ../../library/stdtypes.rst:4407 +#: ../../library/stdtypes.rst:4609 ../../library/stdtypes.rst:5089 +#: ../../library/stdtypes.rst:5346 ../../library/stdtypes.rst:5516 +#: ../../library/stdtypes.rst:5560 msgid "object" msgstr "objeto" @@ -8515,9 +10713,9 @@ msgid "arithmetic" msgstr "aritmética" #: ../../library/stdtypes.rst:246 ../../library/stdtypes.rst:950 -#: ../../library/stdtypes.rst:1117 ../../library/stdtypes.rst:4435 -#: ../../library/stdtypes.rst:5389 ../../library/stdtypes.rst:5403 -#: ../../library/stdtypes.rst:5418 +#: ../../library/stdtypes.rst:1117 ../../library/stdtypes.rst:4609 +#: ../../library/stdtypes.rst:5567 ../../library/stdtypes.rst:5581 +#: ../../library/stdtypes.rst:5596 msgid "built-in function" msgstr "função embutida" @@ -8533,8 +10731,8 @@ msgstr "ponto flutuante" msgid "complex" msgstr "complexo" -#: ../../library/stdtypes.rst:246 ../../library/stdtypes.rst:2402 -#: ../../library/stdtypes.rst:3621 +#: ../../library/stdtypes.rst:246 ../../library/stdtypes.rst:2576 +#: ../../library/stdtypes.rst:3795 msgid "+ (plus)" msgstr "+ (mais)" @@ -8546,13 +10744,13 @@ msgstr "operador unário" msgid "binary operator" msgstr "operador binário" -#: ../../library/stdtypes.rst:246 ../../library/stdtypes.rst:2402 -#: ../../library/stdtypes.rst:3621 +#: ../../library/stdtypes.rst:246 ../../library/stdtypes.rst:2576 +#: ../../library/stdtypes.rst:3795 msgid "- (minus)" msgstr "- (menos)" -#: ../../library/stdtypes.rst:246 ../../library/stdtypes.rst:2359 -#: ../../library/stdtypes.rst:3578 +#: ../../library/stdtypes.rst:246 ../../library/stdtypes.rst:2533 +#: ../../library/stdtypes.rst:3752 msgid "* (asterisk)" msgstr "* (asterisco)" @@ -8564,8 +10762,8 @@ msgstr "/ (barra)" msgid "//" msgstr "//" -#: ../../library/stdtypes.rst:246 ../../library/stdtypes.rst:2323 -#: ../../library/stdtypes.rst:3546 +#: ../../library/stdtypes.rst:246 ../../library/stdtypes.rst:2497 +#: ../../library/stdtypes.rst:3720 msgid "% (percent)" msgstr "% (porcentagem)" @@ -8575,7 +10773,7 @@ msgstr "**" #: ../../library/stdtypes.rst:316 ../../library/stdtypes.rst:393 #: ../../library/stdtypes.rst:950 ../../library/stdtypes.rst:1154 -#: ../../library/stdtypes.rst:4435 +#: ../../library/stdtypes.rst:4609 msgid "operations on" msgstr "operações em" @@ -8584,7 +10782,7 @@ msgid "conjugate() (complex number method)" msgstr "conjugate() (método de número complexo)" #: ../../library/stdtypes.rst:335 ../../library/stdtypes.rst:1606 -#: ../../library/stdtypes.rst:2526 ../../library/stdtypes.rst:5418 +#: ../../library/stdtypes.rst:2700 ../../library/stdtypes.rst:5596 msgid "module" msgstr "módulo" @@ -8652,7 +10850,7 @@ msgstr "valores" msgid "iterator protocol" msgstr "protocolo iterador" -#: ../../library/stdtypes.rst:847 ../../library/stdtypes.rst:4828 +#: ../../library/stdtypes.rst:847 ../../library/stdtypes.rst:5004 msgid "protocol" msgstr "protocolo" @@ -8678,7 +10876,7 @@ msgstr "contêiner" msgid "iteration over" msgstr "iteração por" -#: ../../library/stdtypes.rst:950 ../../library/stdtypes.rst:4435 +#: ../../library/stdtypes.rst:950 ../../library/stdtypes.rst:4609 msgid "len" msgstr "len" @@ -8755,14 +10953,14 @@ msgstr "mutável" msgid "list" msgstr "lista" -#: ../../library/stdtypes.rst:1139 ../../library/stdtypes.rst:2526 -#: ../../library/stdtypes.rst:2652 ../../library/stdtypes.rst:2724 -#: ../../library/stdtypes.rst:3546 +#: ../../library/stdtypes.rst:1139 ../../library/stdtypes.rst:2700 +#: ../../library/stdtypes.rst:2826 ../../library/stdtypes.rst:2898 +#: ../../library/stdtypes.rst:3720 msgid "bytearray" msgstr "bytearray" -#: ../../library/stdtypes.rst:1154 ../../library/stdtypes.rst:4435 -#: ../../library/stdtypes.rst:5168 ../../library/stdtypes.rst:5418 +#: ../../library/stdtypes.rst:1154 ../../library/stdtypes.rst:4609 +#: ../../library/stdtypes.rst:5346 ../../library/stdtypes.rst:5596 msgid "type" msgstr "tipo" @@ -8770,7 +10968,7 @@ msgstr "tipo" msgid "assignment" msgstr "atribuição" -#: ../../library/stdtypes.rst:1154 ../../library/stdtypes.rst:4435 +#: ../../library/stdtypes.rst:1154 ../../library/stdtypes.rst:4609 msgid "del" msgstr "del" @@ -8811,7 +11009,8 @@ msgid "range" msgstr "range" #: ../../library/stdtypes.rst:1504 ../../library/stdtypes.rst:1553 -#: ../../library/stdtypes.rst:1598 ../../library/stdtypes.rst:2323 +#: ../../library/stdtypes.rst:1598 ../../library/stdtypes.rst:2351 +#: ../../library/stdtypes.rst:2497 msgid "string" msgstr "string" @@ -8832,17 +11031,17 @@ msgstr "(veja também string)" msgid "io.StringIO" msgstr "io.StringIO" -#: ../../library/stdtypes.rst:1571 ../../library/stdtypes.rst:2518 +#: ../../library/stdtypes.rst:1571 ../../library/stdtypes.rst:2692 msgid "buffer protocol" msgstr "protocolo de buffer" -#: ../../library/stdtypes.rst:1571 ../../library/stdtypes.rst:2526 -#: ../../library/stdtypes.rst:2545 ../../library/stdtypes.rst:2724 -#: ../../library/stdtypes.rst:3546 +#: ../../library/stdtypes.rst:1571 ../../library/stdtypes.rst:2700 +#: ../../library/stdtypes.rst:2719 ../../library/stdtypes.rst:2898 +#: ../../library/stdtypes.rst:3720 msgid "bytes" msgstr "bytes" -#: ../../library/stdtypes.rst:1598 ../../library/stdtypes.rst:2724 +#: ../../library/stdtypes.rst:1598 ../../library/stdtypes.rst:2898 msgid "methods" msgstr "métodos" @@ -8850,183 +11049,239 @@ msgstr "métodos" msgid "re" msgstr "re" -#: ../../library/stdtypes.rst:2131 ../../library/stdtypes.rst:3400 +#: ../../library/stdtypes.rst:2165 ../../library/stdtypes.rst:3574 msgid "universal newlines" msgstr "novas linhas universais" -#: ../../library/stdtypes.rst:2131 +#: ../../library/stdtypes.rst:2165 msgid "str.splitlines method" msgstr "método str.splitlines" -#: ../../library/stdtypes.rst:2323 +#: ../../library/stdtypes.rst:2351 +msgid "! formatted string literal" +msgstr "literal de string formatada com !" + +#: ../../library/stdtypes.rst:2351 +msgid "formatted string literals" +msgstr "literais de string formatadas" + +#: ../../library/stdtypes.rst:2351 +msgid "! f-string" +msgstr "! f-string" + +#: ../../library/stdtypes.rst:2351 +msgid "f-strings" +msgstr "Literais de strings formatadas" + +#: ../../library/stdtypes.rst:2351 +msgid "fstring" +msgstr "fstring" + +#: ../../library/stdtypes.rst:2351 +msgid "interpolated string literal" +msgstr "literal de string interpolada" + +#: ../../library/stdtypes.rst:2351 +msgid "formatted literal" +msgstr "literal formatado" + +#: ../../library/stdtypes.rst:2351 +msgid "interpolated literal" +msgstr "literal interpolado" + +#: ../../library/stdtypes.rst:2351 +msgid "{} (curly brackets)" +msgstr "{} (chaves)" + +#: ../../library/stdtypes.rst:2351 +msgid "in formatted string literal" +msgstr "em literal de string formatado" + +#: ../../library/stdtypes.rst:2351 +msgid "! (exclamation mark)" +msgstr "! (ponto de exclamação)" + +#: ../../library/stdtypes.rst:2351 +msgid ": (colon)" +msgstr ": (dois pontos)" + +#: ../../library/stdtypes.rst:2351 +msgid "= (equals)" +msgstr "= (igual)" + +#: ../../library/stdtypes.rst:2351 +msgid "for help in debugging using string literals" +msgstr "para ajudar na depuração usando literais de string" + +#: ../../library/stdtypes.rst:2497 msgid "formatting, string (%)" msgstr "formatação, string (%)" -#: ../../library/stdtypes.rst:2323 +#: ../../library/stdtypes.rst:2497 msgid "interpolation, string (%)" msgstr "interpolação, string (%)" -#: ../../library/stdtypes.rst:2323 +#: ../../library/stdtypes.rst:2497 msgid "formatting, printf" msgstr "formatação, printf" -#: ../../library/stdtypes.rst:2323 +#: ../../library/stdtypes.rst:2497 msgid "interpolation, printf" msgstr "interpolação, printf" -#: ../../library/stdtypes.rst:2323 ../../library/stdtypes.rst:3546 +#: ../../library/stdtypes.rst:2497 ../../library/stdtypes.rst:3720 msgid "printf-style formatting" msgstr "printf, estilo de formatação" -#: ../../library/stdtypes.rst:2323 ../../library/stdtypes.rst:3546 +#: ../../library/stdtypes.rst:2497 ../../library/stdtypes.rst:3720 msgid "sprintf-style formatting" msgstr "sprintf, estilo de formatação" -#: ../../library/stdtypes.rst:2359 ../../library/stdtypes.rst:3578 +#: ../../library/stdtypes.rst:2533 ../../library/stdtypes.rst:3752 msgid "() (parentheses)" msgstr "() (parênteses)" -#: ../../library/stdtypes.rst:2359 ../../library/stdtypes.rst:2402 -#: ../../library/stdtypes.rst:3578 ../../library/stdtypes.rst:3621 +#: ../../library/stdtypes.rst:2533 ../../library/stdtypes.rst:2576 +#: ../../library/stdtypes.rst:3752 ../../library/stdtypes.rst:3795 msgid "in printf-style formatting" msgstr "em formatação no estilo printf" -#: ../../library/stdtypes.rst:2359 ../../library/stdtypes.rst:3578 +#: ../../library/stdtypes.rst:2533 ../../library/stdtypes.rst:3752 msgid ". (dot)" msgstr ". (ponto)" -#: ../../library/stdtypes.rst:2402 ../../library/stdtypes.rst:3621 +#: ../../library/stdtypes.rst:2576 ../../library/stdtypes.rst:3795 msgid "# (hash)" msgstr "# (cerquilha)" -#: ../../library/stdtypes.rst:2402 ../../library/stdtypes.rst:3621 +#: ../../library/stdtypes.rst:2576 ../../library/stdtypes.rst:3795 msgid "space" msgstr "espaço" -#: ../../library/stdtypes.rst:2518 +#: ../../library/stdtypes.rst:2692 msgid "binary sequence types" msgstr "tipos de sequência binária" -#: ../../library/stdtypes.rst:2526 +#: ../../library/stdtypes.rst:2700 msgid "memoryview" msgstr "memoryview" -#: ../../library/stdtypes.rst:2526 +#: ../../library/stdtypes.rst:2700 msgid "array" msgstr "array" -#: ../../library/stdtypes.rst:3400 +#: ../../library/stdtypes.rst:3574 msgid "bytes.splitlines method" msgstr "método bytes.splitlines" -#: ../../library/stdtypes.rst:3400 +#: ../../library/stdtypes.rst:3574 msgid "bytearray.splitlines method" msgstr "método bytearray.splitlines" -#: ../../library/stdtypes.rst:3546 +#: ../../library/stdtypes.rst:3720 msgid "formatting" msgstr "formatação" -#: ../../library/stdtypes.rst:3546 +#: ../../library/stdtypes.rst:3720 msgid "bytes (%)" msgstr "bytes (%)" -#: ../../library/stdtypes.rst:3546 +#: ../../library/stdtypes.rst:3720 msgid "bytearray (%)" msgstr "bytearray (%)" -#: ../../library/stdtypes.rst:3546 +#: ../../library/stdtypes.rst:3720 msgid "interpolation" msgstr "interpolação" -#: ../../library/stdtypes.rst:4233 +#: ../../library/stdtypes.rst:4407 msgid "set" msgstr "set" -#: ../../library/stdtypes.rst:4435 +#: ../../library/stdtypes.rst:4609 msgid "mapping" msgstr "mapeamento" -#: ../../library/stdtypes.rst:4435 +#: ../../library/stdtypes.rst:4609 msgid "dictionary" msgstr "dicionário" -#: ../../library/stdtypes.rst:4518 +#: ../../library/stdtypes.rst:4719 msgid "__missing__()" msgstr "__missing__()" -#: ../../library/stdtypes.rst:4828 +#: ../../library/stdtypes.rst:5004 msgid "context manager" msgstr "gerenciador de contexto" -#: ../../library/stdtypes.rst:4828 +#: ../../library/stdtypes.rst:5004 msgid "context management protocol" msgstr "protocolo de gerenciamento de contexto" -#: ../../library/stdtypes.rst:4828 +#: ../../library/stdtypes.rst:5004 msgid "context management" msgstr "gerenciamento de contexto" -#: ../../library/stdtypes.rst:4901 +#: ../../library/stdtypes.rst:5077 msgid "annotation" msgstr "anotação" -#: ../../library/stdtypes.rst:4901 +#: ../../library/stdtypes.rst:5077 msgid "type annotation; type hint" msgstr "tipo, anotação de; tipo, dica de" -#: ../../library/stdtypes.rst:4913 +#: ../../library/stdtypes.rst:5089 msgid "GenericAlias" msgstr "GenericAlias" -#: ../../library/stdtypes.rst:4913 +#: ../../library/stdtypes.rst:5089 msgid "Generic" msgstr "Generic" -#: ../../library/stdtypes.rst:4913 +#: ../../library/stdtypes.rst:5089 msgid "Alias" msgstr "Alias" -#: ../../library/stdtypes.rst:5168 +#: ../../library/stdtypes.rst:5346 msgid "Union" msgstr "União" -#: ../../library/stdtypes.rst:5168 +#: ../../library/stdtypes.rst:5346 msgid "union" msgstr "união" -#: ../../library/stdtypes.rst:5338 +#: ../../library/stdtypes.rst:5516 msgid "method" msgstr "método" -#: ../../library/stdtypes.rst:5382 +#: ../../library/stdtypes.rst:5560 msgid "code" msgstr "código" -#: ../../library/stdtypes.rst:5382 +#: ../../library/stdtypes.rst:5560 msgid "code object" msgstr "objeto código" -#: ../../library/stdtypes.rst:5389 +#: ../../library/stdtypes.rst:5567 msgid "compile" msgstr "compile" -#: ../../library/stdtypes.rst:5389 +#: ../../library/stdtypes.rst:5567 msgid "__code__ (function object attribute)" msgstr "__code__ (atributo de objeto função)" -#: ../../library/stdtypes.rst:5403 +#: ../../library/stdtypes.rst:5581 msgid "exec" msgstr "exec" -#: ../../library/stdtypes.rst:5403 +#: ../../library/stdtypes.rst:5581 msgid "eval" msgstr "eval" -#: ../../library/stdtypes.rst:5442 +#: ../../library/stdtypes.rst:5620 msgid "..." msgstr "..." -#: ../../library/stdtypes.rst:5442 +#: ../../library/stdtypes.rst:5620 msgid "ellipsis literal" msgstr "reticências literais" diff --git a/library/string.po b/library/string.po index 1f70d7fbb..6cbfc7103 100644 --- a/library/string.po +++ b/library/string.po @@ -1,33 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Welington Carlos , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# (Douglas da Silva) , 2021 -# Adson Rodrigues , 2021 -# Marcos Wenneton Araújo , 2021 -# i17obot , 2021 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-20 00:52+0000\n" -"PO-Revision-Date: 2021-06-28 01:14+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-09 14:59+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -100,18 +92,28 @@ msgstr "" "String de caracteres ASCII que são considerados caracteres de pontuação na " "localidade ``C``: ``!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~``." -#: ../../library/string.rst:64 +#: ../../library/string.rst:65 msgid "" -"String of ASCII characters which are considered printable. This is a " -"combination of :const:`digits`, :const:`ascii_letters`, :const:" +"String of ASCII characters which are considered printable by Python. This is " +"a combination of :const:`digits`, :const:`ascii_letters`, :const:" "`punctuation`, and :const:`whitespace`." msgstr "" -"String de caracteres ASCII que são considerados imprimíveis. Esta é uma " -"combinação de :const:`digits`, :const:`ascii_letters`, :const:`punctuation` " -"e :const:`whitespace`." +"String de caracteres ASCII que são considerados imprimíveis pelo Python. " +"Esta é uma combinação de :const:`digits`, :const:`ascii_letters`, :const:" +"`punctuation` e :const:`whitespace`." #: ../../library/string.rst:71 msgid "" +"By design, :meth:`string.printable.isprintable() ` returns :" +"const:`False`. In particular, ``string.printable`` is not printable in the " +"POSIX sense (see :manpage:`LC_CTYPE `)." +msgstr "" +"Por design, :meth:`string.printable.isprintable() ` " +"retorna :const:`False`. Em particular, ``string.printable`` não é imprimível " +"no sentido POSIX (veja :manpage:`LC_CTYPE `)." + +#: ../../library/string.rst:78 +msgid "" "A string containing all ASCII characters that are considered whitespace. " "This includes the characters space, tab, linefeed, return, formfeed, and " "vertical tab." @@ -120,11 +122,11 @@ msgstr "" "em branco. Isso inclui espaço de caracteres, tabulação, avanço de linha, " "retorno, avanço de formulário e tabulação vertical." -#: ../../library/string.rst:79 +#: ../../library/string.rst:86 msgid "Custom String Formatting" msgstr "Formatação personalizada de strings" -#: ../../library/string.rst:81 +#: ../../library/string.rst:88 msgid "" "The built-in string class provides the ability to do complex variable " "substitutions and value formatting via the :meth:`~str.format` method " @@ -140,11 +142,11 @@ msgstr "" "formatação de strings usando a mesma implementação que o método embutido :" "meth:`~str.format`." -#: ../../library/string.rst:90 +#: ../../library/string.rst:97 msgid "The :class:`Formatter` class has the following public methods:" msgstr "A classe :class:`Formatter` tem os seguintes métodos públicos:" -#: ../../library/string.rst:94 +#: ../../library/string.rst:101 msgid "" "The primary API method. It takes a format string and an arbitrary set of " "positional and keyword arguments. It is just a wrapper that calls :meth:" @@ -154,7 +156,7 @@ msgstr "" "arbitrário de argumentos posicionais e nomeados. É apenas um invólucro que " "chama :meth:`vformat`." -#: ../../library/string.rst:98 +#: ../../library/string.rst:105 msgid "" "A format string argument is now :ref:`positional-only `." @@ -162,7 +164,7 @@ msgstr "" "Um argumento de string de formato é agora :ref:`somente-posicional " "`." -#: ../../library/string.rst:104 +#: ../../library/string.rst:111 msgid "" "This function does the actual work of formatting. It is exposed as a " "separate function for cases where you want to pass in a predefined " @@ -179,7 +181,7 @@ msgstr "" "caracteres e campos de substituição. Ela chama os vários métodos descritos " "abaixo." -#: ../../library/string.rst:112 +#: ../../library/string.rst:119 msgid "" "In addition, the :class:`Formatter` defines a number of methods that are " "intended to be replaced by subclasses:" @@ -187,7 +189,7 @@ msgstr "" "Além disso, o :class:`Formatter` define uma série de métodos que devem ser " "substituídos por subclasses:" -#: ../../library/string.rst:117 +#: ../../library/string.rst:124 msgid "" "Loop over the format_string and return an iterable of tuples " "(*literal_text*, *field_name*, *format_spec*, *conversion*). This is used " @@ -198,7 +200,7 @@ msgstr "" "*field_name*, *format_spec*, *conversion*). Isso é usado por :meth:`vformat` " "para quebrar a string em texto literal ou campos de substituição." -#: ../../library/string.rst:122 +#: ../../library/string.rst:129 msgid "" "The values in the tuple conceptually represent a span of literal text " "followed by a single replacement field. If there is no literal text (which " @@ -214,7 +216,7 @@ msgstr "" "Se não houver campo de substituição, então os valores de *field_name*, " "*format_spec* e *conversion* serão ``None``." -#: ../../library/string.rst:131 +#: ../../library/string.rst:138 msgid "" "Given *field_name* as returned by :meth:`parse` (see above), convert it to " "an object to be formatted. Returns a tuple (obj, used_key). The default " @@ -230,7 +232,7 @@ msgstr "" "meth:`vformat`. O valor de retorno *used_key* tem o mesmo significado que o " "parâmetro *key* para :meth:`get_value`." -#: ../../library/string.rst:140 +#: ../../library/string.rst:147 msgid "" "Retrieve a given field value. The *key* argument will be either an integer " "or a string. If it is an integer, it represents the index of the positional " @@ -242,7 +244,7 @@ msgstr "" "posicional em *args*; se for uma string, então representa um argumento " "nomeado em *kwargs*." -#: ../../library/string.rst:145 +#: ../../library/string.rst:152 msgid "" "The *args* parameter is set to the list of positional arguments to :meth:" "`vformat`, and the *kwargs* parameter is set to the dictionary of keyword " @@ -252,7 +254,7 @@ msgstr "" "meth:`vformat`, e o parâmetro *kwargs* é definido para o dicionário de " "argumentos nomeados." -#: ../../library/string.rst:149 +#: ../../library/string.rst:156 msgid "" "For compound field names, these functions are only called for the first " "component of the field name; subsequent components are handled through " @@ -262,7 +264,7 @@ msgstr "" "primeiro componente do nome do campo; os componentes subsequentes são " "tratados por meio de operações normais de atributo e indexação." -#: ../../library/string.rst:153 +#: ../../library/string.rst:160 msgid "" "So for example, the field expression '0.name' would cause :meth:`get_value` " "to be called with a *key* argument of 0. The ``name`` attribute will be " @@ -274,7 +276,7 @@ msgstr "" "será pesquisado após :meth:`get_value` retorna chamando a função embutida :" "func:`getattr`." -#: ../../library/string.rst:158 +#: ../../library/string.rst:165 msgid "" "If the index or keyword refers to an item that does not exist, then an :exc:" "`IndexError` or :exc:`KeyError` should be raised." @@ -282,7 +284,7 @@ msgstr "" "Se o índice ou palavra-chave se referir a um item que não existe, um :exc:" "`IndexError` ou :exc:`KeyError` deve ser levantada." -#: ../../library/string.rst:163 +#: ../../library/string.rst:170 msgid "" "Implement checking for unused arguments if desired. The arguments to this " "function is the set of all argument keys that were actually referred to in " @@ -299,7 +301,7 @@ msgstr "" "utilizados pode ser calculado a partir desses parâmetros. Presume-se que :" "meth:`check_unused_args` levata uma exceção se a verificação falhar." -#: ../../library/string.rst:173 +#: ../../library/string.rst:180 msgid "" ":meth:`format_field` simply calls the global :func:`format` built-in. The " "method is provided so that subclasses can override it." @@ -307,7 +309,7 @@ msgstr "" ":meth:`format_field` simplesmente chama o global embutido :func:`format`. O " "método é fornecido para que as subclasses possam substituí-lo." -#: ../../library/string.rst:178 +#: ../../library/string.rst:185 msgid "" "Converts the value (returned by :meth:`get_field`) given a conversion type " "(as in the tuple returned by the :meth:`parse` method). The default version " @@ -317,11 +319,11 @@ msgstr "" "(como na tupla retornada pelo método :meth:`parse`). A versão padrão entende " "os tipos de conversão \"s\" (str), \"r\" (repr) e \"a\" (ascii)." -#: ../../library/string.rst:187 +#: ../../library/string.rst:194 msgid "Format String Syntax" msgstr "Sintaxe das strings de formato" -#: ../../library/string.rst:189 +#: ../../library/string.rst:196 msgid "" "The :meth:`str.format` method and the :class:`Formatter` class share the " "same syntax for format strings (although in the case of :class:`Formatter`, " @@ -337,7 +339,7 @@ msgstr "" "mas é menos sofisticada e, em especial, não tem suporte a expressões " "arbitrárias." -#: ../../library/string.rst:202 +#: ../../library/string.rst:209 msgid "" "Format strings contain \"replacement fields\" surrounded by curly braces ``{}" "``. Anything that is not contained in braces is considered literal text, " @@ -350,11 +352,11 @@ msgstr "" "copiado inalterado para a saída. Se você precisar incluir um caractere de " "chave no texto literal, ele pode ser escapado duplicando: ``{{`` e ``}}``." -#: ../../library/string.rst:207 +#: ../../library/string.rst:214 msgid "The grammar for a replacement field is as follows:" msgstr "A gramática para um campo de substituição é a seguinte:" -#: ../../library/string.rst:219 +#: ../../library/string.rst:226 msgid "" "In less formal terms, the replacement field can start with a *field_name* " "that specifies the object whose value is to be formatted and inserted into " @@ -371,11 +373,11 @@ msgstr "" "pontos ``':'``. Eles especificam um formato não padrão para o valor de " "substituição." -#: ../../library/string.rst:226 +#: ../../library/string.rst:233 msgid "See also the :ref:`formatspec` section." msgstr "Veja também a seção :ref:`formatspec`." -#: ../../library/string.rst:228 +#: ../../library/string.rst:235 msgid "" "The *field_name* itself begins with an *arg_name* that is either a number or " "a keyword. If it's a number, it refers to a positional argument, and if " @@ -406,7 +408,7 @@ msgstr "" "`getattr`, enquanto uma expressão da forma ``'[index]'`` faz uma pesquisa de " "índice usando :meth:`~object.__getitem__`." -#: ../../library/string.rst:242 +#: ../../library/string.rst:249 msgid "" "The positional argument specifiers can be omitted for :meth:`str.format`, so " "``'{} {}'.format(a, b)`` is equivalent to ``'{0} {1}'.format(a, b)``." @@ -415,19 +417,43 @@ msgstr "" "`str.format`, de forma que ``'{} {}'.format(a, b)`` é equivalente a ``'{0} " "{1}'.format(a, b)``." -#: ../../library/string.rst:246 +#: ../../library/string.rst:253 msgid "" "The positional argument specifiers can be omitted for :class:`Formatter`." msgstr "" "Os especificadores de argumento posicional podem ser omitidos para :class:" "`Formatter`." -#: ../../library/string.rst:249 +#: ../../library/string.rst:256 msgid "Some simple format string examples::" msgstr "Alguns exemplos simples de string de formato::" #: ../../library/string.rst:258 msgid "" +"\"First, thou shalt count to {0}\" # References first positional argument\n" +"\"Bring me a {}\" # Implicitly references the first " +"positional argument\n" +"\"From {} to {}\" # Same as \"From {0} to {1}\"\n" +"\"My quest is {name}\" # References keyword argument 'name'\n" +"\"Weight in tons {0.weight}\" # 'weight' attribute of first positional " +"arg\n" +"\"Units destroyed: {players[0]}\" # First element of keyword argument " +"'players'." +msgstr "" +"\"Primeiro, tu deverás contar até {0}\" # Referencia o primeiro argumento " +"posicional\n" +"\"Traga-me um {}\" # Referencia implicitamente o " +"primeiro argumento posicional\n" +"\"De {} para {}\" # Mesmo que \"De {0} para {1}\"\n" +"\"Minha missão é {nome}\" # Referencia argumento nomeado " +"'nome'\n" +"\"Peso em toneladas {0.peso}\" # O atributo 'peso' do primeiro " +"argumento posicional\n" +"\"Unidades destruídas: {jogadores[0]}\" # Primeiro elemento do argumento " +"nomeado 'jogadores'." + +#: ../../library/string.rst:265 +msgid "" "The *conversion* field causes a type coercion before formatting. Normally, " "the job of formatting a value is done by the :meth:`~object.__format__` " "method of the value itself. However, in some cases it is desirable to force " @@ -443,7 +469,7 @@ msgstr "" "chamar :meth:`~object.__format__`, a lógica de formatação normal é " "contornada." -#: ../../library/string.rst:265 +#: ../../library/string.rst:272 msgid "" "Three conversion flags are currently supported: ``'!s'`` which calls :func:" "`str` on the value, ``'!r'`` which calls :func:`repr` and ``'!a'`` which " @@ -453,11 +479,21 @@ msgstr "" "chama :func:`str` no valor; ``'!r'``, que chama :func:`repr`; e ``'!a'``, " "que chama :func:`ascii`." -#: ../../library/string.rst:269 +#: ../../library/string.rst:276 msgid "Some examples::" msgstr "Alguns exemplos:" -#: ../../library/string.rst:275 +#: ../../library/string.rst:278 +msgid "" +"\"Harold's a clever {0!s}\" # Calls str() on the argument first\n" +"\"Bring out the holy {name!r}\" # Calls repr() on the argument first\n" +"\"More {!a}\" # Calls ascii() on the argument first" +msgstr "" +"\"Harold's a clever {0!s}\" # Chama str() no primeiro argumento\n" +"\"Bring out the holy {name!r}\" # Chama repr() no primeiro argumento\n" +"\"More {!a}\" # Chama ascii() no primeiro argumento" + +#: ../../library/string.rst:282 msgid "" "The *format_spec* field contains a specification of how the value should be " "presented, including such details as field width, alignment, padding, " @@ -470,7 +506,7 @@ msgstr "" "definir sua própria \"minilinguagem de formatação\" ou interpretação de " "*format_spec*." -#: ../../library/string.rst:280 +#: ../../library/string.rst:287 msgid "" "Most built-in types support a common formatting mini-language, which is " "described in the next section." @@ -478,7 +514,7 @@ msgstr "" "A maioria dos tipos embutidos oferece suporte a uma minilinguagem de " "formatação comum, que é descrita na próxima seção." -#: ../../library/string.rst:283 +#: ../../library/string.rst:290 msgid "" "A *format_spec* field can also include nested replacement fields within it. " "These nested replacement fields may contain a field name, conversion flag " @@ -495,15 +531,15 @@ msgstr "" "interpretada. Isso permite que a formatação de um valor seja especificada " "dinamicamente." -#: ../../library/string.rst:290 +#: ../../library/string.rst:297 msgid "See the :ref:`formatexamples` section for some examples." msgstr "Veja a seção :ref:`formatexamples` para alguns exemplos." -#: ../../library/string.rst:296 +#: ../../library/string.rst:303 msgid "Format Specification Mini-Language" msgstr "Minilinguagem de especificação de formato" -#: ../../library/string.rst:298 +#: ../../library/string.rst:305 msgid "" "\"Format specifications\" are used within replacement fields contained " "within a format string to define how individual values are presented (see :" @@ -518,7 +554,7 @@ msgstr "" "tipo formatável pode definir como a especificação do formato deve ser " "interpretada." -#: ../../library/string.rst:305 +#: ../../library/string.rst:312 msgid "" "Most built-in types implement the following options for format " "specifications, although some of the formatting options are only supported " @@ -528,7 +564,7 @@ msgstr "" "especificações de formato, embora algumas das opções de formatação sejam " "suportadas apenas pelos tipos numéricos." -#: ../../library/string.rst:308 +#: ../../library/string.rst:315 msgid "" "A general convention is that an empty format specification produces the same " "result as if you had called :func:`str` on the value. A non-empty format " @@ -538,11 +574,11 @@ msgstr "" "resultado como se você tivesse chamado :func:`str` no valor. Uma " "especificação de formato não vazio normalmente modifica o resultado." -#: ../../library/string.rst:312 +#: ../../library/string.rst:319 msgid "The general form of a *standard format specifier* is:" msgstr "A forma geral de um *especificador de formato padrão* é:" -#: ../../library/string.rst:324 +#: ../../library/string.rst:333 msgid "" "If a valid *align* value is specified, it can be preceded by a *fill* " "character that can be any character and defaults to a space if omitted. It " @@ -560,25 +596,26 @@ msgstr "" "inserir uma chave com um campo de substituição aninhado. Esta limitação não " "afeta a função :func:`format`." -#: ../../library/string.rst:333 +#: ../../library/string.rst:342 msgid "The meaning of the various alignment options is as follows:" msgstr "O significado das várias opções de alinhamento é o seguinte:" -#: ../../library/string.rst:342 ../../library/string.rst:373 +#: ../../library/string.rst:351 ../../library/string.rst:383 +#: ../../library/string.rst:442 msgid "Option" msgstr "Opção" -#: ../../library/string.rst:342 ../../library/string.rst:373 -#: ../../library/string.rst:456 ../../library/string.rst:467 -#: ../../library/string.rst:502 +#: ../../library/string.rst:351 ../../library/string.rst:383 +#: ../../library/string.rst:442 ../../library/string.rst:481 +#: ../../library/string.rst:492 ../../library/string.rst:527 msgid "Meaning" msgstr "Significado" -#: ../../library/string.rst:344 +#: ../../library/string.rst:353 msgid "``'<'``" msgstr "``'<'``" -#: ../../library/string.rst:344 +#: ../../library/string.rst:353 msgid "" "Forces the field to be left-aligned within the available space (this is the " "default for most objects)." @@ -586,11 +623,11 @@ msgstr "" "Força o alinhamento à esquerda do campo dentro do espaço disponível (este é " "o padrão para a maioria dos objetos)." -#: ../../library/string.rst:347 +#: ../../library/string.rst:356 msgid "``'>'``" msgstr "``'>'``" -#: ../../library/string.rst:347 +#: ../../library/string.rst:356 msgid "" "Forces the field to be right-aligned within the available space (this is the " "default for numbers)." @@ -598,31 +635,33 @@ msgstr "" "Força o alinhamento à direita do campo dentro do espaço disponível (este é o " "padrão para números)." -#: ../../library/string.rst:350 +#: ../../library/string.rst:359 msgid "``'='``" msgstr "``'='``" -#: ../../library/string.rst:350 +#: ../../library/string.rst:359 msgid "" "Forces the padding to be placed after the sign (if any) but before the " "digits. This is used for printing fields in the form '+000000120'. This " -"alignment option is only valid for numeric types. It becomes the default " -"for numbers when '0' immediately precedes the field width." +"alignment option is only valid for numeric types, excluding :class:" +"`complex`. It becomes the default for numbers when '0' immediately precedes " +"the field width." msgstr "" "Força o preenchimento a ser colocado após o sinal (se houver), mas antes dos " "dígitos. É usado para imprimir campos na forma \"+000000120\". Esta opção de " -"alinhamento só é válida para tipos numéricos. Torna-se o padrão para números " -"quando \"0\" precede imediatamente a largura do campo." +"alinhamento só é válida para tipos numéricos, excluindo :class:`complex`. " +"Torna-se o padrão para números quando \"0\" precede imediatamente a largura " +"do campo." -#: ../../library/string.rst:356 +#: ../../library/string.rst:366 msgid "``'^'``" msgstr "``'^'``" -#: ../../library/string.rst:356 +#: ../../library/string.rst:366 msgid "Forces the field to be centered within the available space." msgstr "Força a centralização do campo no espaço disponível." -#: ../../library/string.rst:360 +#: ../../library/string.rst:370 msgid "" "Note that unless a minimum field width is defined, the field width will " "always be the same size as the data to fill it, so that the alignment option " @@ -632,48 +671,48 @@ msgstr "" "largura do campo sempre será do mesmo tamanho que os dados para preenchê-lo, " "de modo que a opção de alinhamento não tem significado neste caso." -#: ../../library/string.rst:364 +#: ../../library/string.rst:374 msgid "" "The *sign* option is only valid for number types, and can be one of the " "following:" msgstr "" "A opção *sign* só é válida para tipos numéricos e pode ser um dos seguintes:" -#: ../../library/string.rst:375 +#: ../../library/string.rst:385 msgid "``'+'``" msgstr "``'+'``" -#: ../../library/string.rst:375 +#: ../../library/string.rst:385 msgid "" -"indicates that a sign should be used for both positive as well as negative " +"Indicates that a sign should be used for both positive as well as negative " "numbers." msgstr "indica que um sinal deve ser usado para números positivos e negativos." -#: ../../library/string.rst:378 +#: ../../library/string.rst:388 msgid "``'-'``" msgstr "``'-'``" -#: ../../library/string.rst:378 +#: ../../library/string.rst:388 msgid "" -"indicates that a sign should be used only for negative numbers (this is the " +"Indicates that a sign should be used only for negative numbers (this is the " "default behavior)." msgstr "" "indica que um sinal deve ser usado apenas para números negativos (este é o " "comportamento padrão)." -#: ../../library/string.rst:367 ../../library/string.rst:381 +#: ../../library/string.rst:377 ../../library/string.rst:391 msgid "space" msgstr "espaço" -#: ../../library/string.rst:381 +#: ../../library/string.rst:391 msgid "" -"indicates that a leading space should be used on positive numbers, and a " +"Indicates that a leading space should be used on positive numbers, and a " "minus sign on negative numbers." msgstr "" "indica que um espaço inicial deve ser usado em números positivos e um sinal " "de menos em números negativos." -#: ../../library/string.rst:388 +#: ../../library/string.rst:398 msgid "" "The ``'z'`` option coerces negative zero floating-point values to positive " "zero after rounding to the format precision. This option is only valid for " @@ -683,11 +722,11 @@ msgstr "" "positivo após o arredondamento para a precisão do formato. Esta opção só é " "válida para tipos de apresentação de ponto flutuante." -#: ../../library/string.rst:392 +#: ../../library/string.rst:402 msgid "Added the ``'z'`` option (see also :pep:`682`)." msgstr "Adicionada a opção ``'z'`` (veja também :pep:`682`)." -#: ../../library/string.rst:397 +#: ../../library/string.rst:407 msgid "" "The ``'#'`` option causes the \"alternate form\" to be used for the " "conversion. The alternate form is defined differently for different types. " @@ -712,61 +751,31 @@ msgstr "" "um dígito o seguir. Além disso, para conversões ``'g'`` e ``'G'``, os zeros " "finais não são removidos do resultado." -#: ../../library/string.rst:411 +#: ../../library/string.rst:419 msgid "" -"The ``','`` option signals the use of a comma for a thousands separator. For " -"a locale aware separator, use the ``'n'`` integer presentation type instead." -msgstr "" -"A opção ``','`` sinaliza o uso de uma vírgula para um separador de milhares. " -"Para um separador que reconhece a localidade, use o tipo de apresentação " -"inteiro ``'n'``." - -#: ../../library/string.rst:415 -msgid "Added the ``','`` option (see also :pep:`378`)." -msgstr "Adicionada a opção ``','`` (veja também :pep:`378`)." - -#: ../../library/string.rst:420 -msgid "" -"The ``'_'`` option signals the use of an underscore for a thousands " -"separator for floating-point presentation types and for integer presentation " -"type ``'d'``. For integer presentation types ``'b'``, ``'o'``, ``'x'``, and " -"``'X'``, underscores will be inserted every 4 digits. For other " -"presentation types, specifying this option is an error." -msgstr "" -"A opção ``'_'`` sinaliza o uso de um sublinhado para um separador de " -"milhares para tipos de apresentação de ponto flutuante e para o tipo de " -"apresentação de inteiro ``'d'``. Para os tipos de apresentação inteiros " -"``'b'``, ``'o'``, ``'x'`` e ``'X'``, sublinhados serão inseridos a cada 4 " -"dígitos. Para outros tipos de apresentação, especificar esta opção é um erro." - -#: ../../library/string.rst:427 -msgid "Added the ``'_'`` option (see also :pep:`515`)." -msgstr "Adicionada a opção ``'_'`` (veja também :pep:`515`)." - -#: ../../library/string.rst:430 -msgid "" -"*width* is a decimal integer defining the minimum total field width, " +"The *width* is a decimal integer defining the minimum total field width, " "including any prefixes, separators, and other formatting characters. If not " "specified, then the field width will be determined by the content." msgstr "" -"*width* é um número inteiro decimal que define a largura total mínima do " +"O *width* é um número inteiro decimal que define a largura total mínima do " "campo, incluindo quaisquer prefixos, separadores e outros caracteres de " "formatação. Se não for especificado, a largura do campo será determinada " "pelo conteúdo." -#: ../../library/string.rst:434 +#: ../../library/string.rst:423 msgid "" "When no explicit alignment is given, preceding the *width* field by a zero " -"(``'0'``) character enables sign-aware zero-padding for numeric types. This " -"is equivalent to a *fill* character of ``'0'`` with an *alignment* type of " -"``'='``." +"(``'0'``) character enables sign-aware zero-padding for numeric types, " +"excluding :class:`complex`. This is equivalent to a *fill* character of " +"``'0'`` with an *alignment* type of ``'='``." msgstr "" "Quando nenhum alinhamento explícito é fornecido, preceder o campo *width* " "com um caractere zero (``'0'``) habilita o preenchimento por zero com " -"reconhecimento de sinal para tipos numéricos. Isso é equivalente a um " -"caractere de *fill* de valor ``'0'`` com um tipo de *alignment* de ``'='``." +"reconhecimento de sinal para tipos numéricos excluindo :class:`complex`. " +"Isso é equivalente a um caractere de *fill* de valor ``'0'`` com um tipo de " +"*alignment* de ``'='``." -#: ../../library/string.rst:439 +#: ../../library/string.rst:428 msgid "" "Preceding the *width* field by ``'0'`` no longer affects the default " "alignment for strings." @@ -774,7 +783,60 @@ msgstr "" "Precedendo o campo *width* com ``'0'`` não afeta mais o alinhamento padrão " "para strings." -#: ../../library/string.rst:443 +#: ../../library/string.rst:433 +msgid "" +"The *grouping* option after the *width* field specifies a digit group " +"separator for the integral part of a number. It can be one of the following:" +msgstr "" + +#: ../../library/string.rst:444 +msgid "``','``" +msgstr "``','``" + +#: ../../library/string.rst:444 +msgid "" +"Inserts a comma every 3 digits for integer presentation type ``'d'`` and " +"floating-point presentation types, excluding ``'n'``. For other presentation " +"types, this option is not supported." +msgstr "" +"Insere uma vírgula a cada 3 dígitos para tipos de apresentação inteiros " +"``'d'`` e de ponto flutuante, excluindo ``'n'``. Para outros tipos de " +"apresentação, esta opção não é suportada." + +#: ../../library/string.rst:450 +msgid "``'_'``" +msgstr "``'_'``" + +#: ../../library/string.rst:450 +msgid "" +"Inserts an underscore every 3 digits for integer presentation type ``'d'`` " +"and floating-point presentation types, excluding ``'n'``. For integer " +"presentation types ``'b'``, ``'o'``, ``'x'``, and ``'X'``, underscores are " +"inserted every 4 digits. For other presentation types, this option is not " +"supported." +msgstr "" +"Insere um sublinhado a cada 3 dígitos para tipos de apresentação inteiros " +"``'d'`` e tipos de apresentação de ponto flutuante, excluindo ``'n'``. Para " +"tipos de apresentação inteiros ``'b'``, ``'o'``, ``'x'`` e ``'X'``, os " +"sublinhados são inseridos a cada 4 dígitos. Para outros tipos de " +"apresentação, esta opção não é suportada." + +#: ../../library/string.rst:460 +msgid "" +"For a locale aware separator, use the ``'n'`` presentation type instead." +msgstr "" +"Para um separador com reconhecimento de localidade, usa o tipo de " +"apresentação ``'n'``." + +#: ../../library/string.rst:462 +msgid "Added the ``','`` option (see also :pep:`378`)." +msgstr "Adicionada a opção ``','`` (veja também :pep:`378`)." + +#: ../../library/string.rst:465 +msgid "Added the ``'_'`` option (see also :pep:`515`)." +msgstr "Adicionada a opção ``'_'`` (veja também :pep:`515`)." + +#: ../../library/string.rst:468 msgid "" "The *precision* is a decimal integer indicating how many digits should be " "displayed after the decimal point for presentation types ``'f'`` and " @@ -792,54 +854,54 @@ msgstr "" "caracteres serão usados do conteúdo do campo. *precision* não é permitido " "para valores inteiros." -#: ../../library/string.rst:451 +#: ../../library/string.rst:476 msgid "Finally, the *type* determines how the data should be presented." msgstr "Finalmente, o *type* determina como os dados devem ser apresentados." -#: ../../library/string.rst:453 +#: ../../library/string.rst:478 msgid "The available string presentation types are:" msgstr "Os tipos de apresentação de string disponíveis são:" -#: ../../library/string.rst:456 ../../library/string.rst:467 -#: ../../library/string.rst:502 +#: ../../library/string.rst:481 ../../library/string.rst:492 +#: ../../library/string.rst:527 msgid "Type" msgstr "Tipo" -#: ../../library/string.rst:458 +#: ../../library/string.rst:483 msgid "``'s'``" msgstr "``'s'``" -#: ../../library/string.rst:458 +#: ../../library/string.rst:483 msgid "String format. This is the default type for strings and may be omitted." msgstr "" "Formato de string. Este é o tipo padrão para strings e pode ser omitido." -#: ../../library/string.rst:461 ../../library/string.rst:490 -#: ../../library/string.rst:577 +#: ../../library/string.rst:486 ../../library/string.rst:515 +#: ../../library/string.rst:601 msgid "None" msgstr "None" -#: ../../library/string.rst:461 +#: ../../library/string.rst:486 msgid "The same as ``'s'``." msgstr "O mesmo que ``'s'``." -#: ../../library/string.rst:464 +#: ../../library/string.rst:489 msgid "The available integer presentation types are:" msgstr "Os tipos de apresentação inteira disponíveis são:" -#: ../../library/string.rst:469 +#: ../../library/string.rst:494 msgid "``'b'``" msgstr "``'b'``" -#: ../../library/string.rst:469 +#: ../../library/string.rst:494 msgid "Binary format. Outputs the number in base 2." msgstr "Formato binário. Exibe o número na base 2." -#: ../../library/string.rst:471 +#: ../../library/string.rst:496 msgid "``'c'``" msgstr "``'c'``" -#: ../../library/string.rst:471 +#: ../../library/string.rst:496 msgid "" "Character. Converts the integer to the corresponding unicode character " "before printing." @@ -847,27 +909,27 @@ msgstr "" "Caractere. Converte o inteiro no caractere Unicode correspondente antes de " "imprimir." -#: ../../library/string.rst:474 +#: ../../library/string.rst:499 msgid "``'d'``" msgstr "``'d'``" -#: ../../library/string.rst:474 +#: ../../library/string.rst:499 msgid "Decimal Integer. Outputs the number in base 10." msgstr "Inteiro decimal. Exibe o número na base 10." -#: ../../library/string.rst:476 +#: ../../library/string.rst:501 msgid "``'o'``" msgstr "``'o'``" -#: ../../library/string.rst:476 +#: ../../library/string.rst:501 msgid "Octal format. Outputs the number in base 8." msgstr "Formato octal. Exibe o número na base 8." -#: ../../library/string.rst:478 +#: ../../library/string.rst:503 msgid "``'x'``" msgstr "``'x'``" -#: ../../library/string.rst:478 +#: ../../library/string.rst:503 msgid "" "Hex format. Outputs the number in base 16, using lower-case letters for the " "digits above 9." @@ -875,11 +937,11 @@ msgstr "" "Formato hexadecimal. Produz o número na base 16, usando letras minúsculas " "para os dígitos acima de 9." -#: ../../library/string.rst:481 +#: ../../library/string.rst:506 msgid "``'X'``" msgstr "``'X'``" -#: ../../library/string.rst:481 +#: ../../library/string.rst:506 msgid "" "Hex format. Outputs the number in base 16, using upper-case letters for the " "digits above 9. In case ``'#'`` is specified, the prefix ``'0x'`` will be " @@ -889,23 +951,23 @@ msgstr "" "para os dígitos acima de 9. No caso de ``'#'`` ser especificado, o prefixo " "``'0x'`` será maiúsculo para ``'0X'`` também." -#: ../../library/string.rst:486 ../../library/string.rst:570 +#: ../../library/string.rst:511 ../../library/string.rst:593 msgid "``'n'``" msgstr "``'n'``" -#: ../../library/string.rst:486 +#: ../../library/string.rst:511 msgid "" "Number. This is the same as ``'d'``, except that it uses the current locale " -"setting to insert the appropriate number separator characters." +"setting to insert the appropriate digit group separators." msgstr "" -"Número. É o mesmo que ``'d'``, exceto que usa a configuração local atual " -"para inserir os caracteres separadores de número apropriados." +"Número. É o mesmo que ``'d'``, exceto que usa a configuração de localidade " +"atual para inserir os separadores de grupo de dígitos apropriados." -#: ../../library/string.rst:490 +#: ../../library/string.rst:515 msgid "The same as ``'d'``." msgstr "O mesmo que ``'d'``." -#: ../../library/string.rst:493 +#: ../../library/string.rst:518 msgid "" "In addition to the above presentation types, integers can be formatted with " "the floating-point presentation types listed below (except ``'n'`` and " @@ -917,7 +979,7 @@ msgstr "" "e ``None``). Ao fazer isso, :func:`float` é usado para converter o inteiro " "em um número de ponto flutuante antes da formatação." -#: ../../library/string.rst:498 +#: ../../library/string.rst:523 msgid "" "The available presentation types for :class:`float` and :class:`~decimal." "Decimal` values are:" @@ -925,11 +987,11 @@ msgstr "" "Os tipos de apresentação disponíveis para :class:`float` e :class:`~decimal." "Decimal` valores são:" -#: ../../library/string.rst:504 +#: ../../library/string.rst:529 msgid "``'e'``" msgstr "``'e'``" -#: ../../library/string.rst:504 +#: ../../library/string.rst:529 msgid "" "Scientific notation. For a given precision ``p``, formats the number in " "scientific notation with the letter 'e' separating the coefficient from the " @@ -937,8 +999,8 @@ msgid "" "decimal point, for a total of ``p + 1`` significant digits. With no " "precision given, uses a precision of ``6`` digits after the decimal point " "for :class:`float`, and shows all coefficient digits for :class:`~decimal." -"Decimal`. If no digits follow the decimal point, the decimal point is also " -"removed unless the ``#`` option is used." +"Decimal`. If ``p=0``, the decimal point is omitted unless the ``#`` option " +"is used." msgstr "" "Notação científica. Para uma dada precisão ``p``, formata o número em " "notação científica com a letra \"e\" separando o coeficiente do expoente. O " @@ -946,14 +1008,13 @@ msgstr "" "para um total de ``p + 1`` dígitos significativos. Sem precisão fornecida, " "usa uma precisão de ``6`` dígitos após o ponto decimal para :class:`float`, " "e mostra todos os dígitos de coeficiente para :class:`~decimal.Decimal`. Se " -"nenhum dígito seguir o ponto decimal, o ponto decimal também é removido, a " -"menos que a opção ``#`` seja usada." +"``p=0``, o ponto decimal é omitido a menos que a opção ``#`` seja usada." -#: ../../library/string.rst:516 +#: ../../library/string.rst:540 msgid "``'E'``" msgstr "``'E'``" -#: ../../library/string.rst:516 +#: ../../library/string.rst:540 msgid "" "Scientific notation. Same as ``'e'`` except it uses an upper case 'E' as the " "separator character." @@ -961,33 +1022,31 @@ msgstr "" "Notação científica. O mesmo que ``'e'``, exceto que usa um 'E' maiúsculo " "como caractere separador." -#: ../../library/string.rst:519 +#: ../../library/string.rst:543 msgid "``'f'``" msgstr "``'f'``" -#: ../../library/string.rst:519 +#: ../../library/string.rst:543 msgid "" "Fixed-point notation. For a given precision ``p``, formats the number as a " "decimal number with exactly ``p`` digits following the decimal point. With " "no precision given, uses a precision of ``6`` digits after the decimal point " "for :class:`float`, and uses a precision large enough to show all " -"coefficient digits for :class:`~decimal.Decimal`. If no digits follow the " -"decimal point, the decimal point is also removed unless the ``#`` option is " -"used." +"coefficient digits for :class:`~decimal.Decimal`. If ``p=0``, the decimal " +"point is omitted unless the ``#`` option is used." msgstr "" "Notação de ponto fixo. Para uma dada precisão ``p``, formata o número como " "um número decimal com exatamente os ``p`` dígitos após o ponto decimal. Sem " "precisão fornecida, usa uma precisão de ``6`` dígitos após o ponto decimal " "para :class:`float`, e usa uma precisão grande o suficiente para mostrar " -"todos os dígitos de coeficiente para :class:`~decimal.Decimal`. Se nenhum " -"dígito seguir o ponto decimal, o ponto decimal também é removido, a menos " -"que a opção ``#`` seja usada." +"todos os dígitos de coeficiente para :class:`~decimal.Decimal`. Se ``p=0``, " +"o ponto decimal é omitido a menos que a opção ``#`` seja usada." -#: ../../library/string.rst:529 +#: ../../library/string.rst:552 msgid "``'F'``" msgstr "``'F'``" -#: ../../library/string.rst:529 +#: ../../library/string.rst:552 msgid "" "Fixed-point notation. Same as ``'f'``, but converts ``nan`` to ``NAN`` and " "``inf`` to ``INF``." @@ -995,11 +1054,11 @@ msgstr "" "Notação de ponto fixo. O mesmo que ``'f'``, mas converte ``nan`` para " "``NAN`` e ``inf`` para ``INF``." -#: ../../library/string.rst:532 +#: ../../library/string.rst:555 msgid "``'g'``" msgstr "``'g'``" -#: ../../library/string.rst:532 +#: ../../library/string.rst:555 msgid "" "General format. For a given precision ``p >= 1``, this rounds the number to " "``p`` significant digits and then formats the result in either fixed-point " @@ -1011,7 +1070,7 @@ msgstr "" "formato de ponto fixo ou em notação científica, dependendo de sua magnitude. " "Uma precisão de ``0`` é tratada como equivalente a uma precisão de ``1``." -#: ../../library/string.rst:539 +#: ../../library/string.rst:562 msgid "" "The precise rules are as follows: suppose that the result formatted with " "presentation type ``'e'`` and precision ``p-1`` would have exponent " @@ -1033,7 +1092,7 @@ msgstr "" "ponto decimal também é removido se não houver dígitos restantes após ele, a " "menos que a opção ``'#'`` seja usada." -#: ../../library/string.rst:552 +#: ../../library/string.rst:575 msgid "" "With no precision given, uses a precision of ``6`` significant digits for :" "class:`float`. For :class:`~decimal.Decimal`, the coefficient of the result " @@ -1049,7 +1108,7 @@ msgstr "" "valores onde o valor posicional do dígito menos significativo é maior que 1, " "e a notação de ponto fixo é usada de outra forma." -#: ../../library/string.rst:561 +#: ../../library/string.rst:584 msgid "" "Positive and negative infinity, positive and negative zero, and nans, are " "formatted as ``inf``, ``-inf``, ``0``, ``-0`` and ``nan`` respectively, " @@ -1059,11 +1118,11 @@ msgstr "" "formatados como ``inf``, ``-inf``, ``0``, ``-0`` e ``nan``, respectivamente, " "independentemente da precisão." -#: ../../library/string.rst:566 +#: ../../library/string.rst:589 msgid "``'G'``" msgstr "``'G'``" -#: ../../library/string.rst:566 +#: ../../library/string.rst:589 msgid "" "General format. Same as ``'g'`` except switches to ``'E'`` if the number " "gets too large. The representations of infinity and NaN are uppercased, too." @@ -1072,19 +1131,21 @@ msgstr "" "ficar muito grande. As representações de infinito e NaN também são " "maiúsculas." -#: ../../library/string.rst:570 +#: ../../library/string.rst:593 msgid "" "Number. This is the same as ``'g'``, except that it uses the current locale " -"setting to insert the appropriate number separator characters." +"setting to insert the appropriate digit group separators for the integral " +"part of a number." msgstr "" -"Número. É o mesmo que ``'g'``, exceto que usa a configuração da localidade " -"atual para inserir os caracteres separadores de número apropriados." +"Número. É o mesmo que ``'g'``, exceto que usa a configuração de localidade " +"atual para inserir os separadores de grupo de dígitos apropriados para a " +"parte inteira de um número." -#: ../../library/string.rst:574 +#: ../../library/string.rst:598 msgid "``'%'``" msgstr "``'%'``" -#: ../../library/string.rst:574 +#: ../../library/string.rst:598 msgid "" "Percentage. Multiplies the number by 100 and displays in fixed (``'f'``) " "format, followed by a percent sign." @@ -1092,19 +1153,21 @@ msgstr "" "Porcentagem. Multiplica o número por 100 e exibe no formato fixo (``'f'``), " "seguido por um sinal de porcentagem." -#: ../../library/string.rst:577 +#: ../../library/string.rst:601 msgid "" -"For :class:`float` this is the same as ``'g'``, except that when fixed-point " -"notation is used to format the result, it always includes at least one digit " -"past the decimal point. The precision used is as large as needed to " -"represent the given value faithfully." +"For :class:`float` this is like the ``'g'`` type, except that when fixed-" +"point notation is used to format the result, it always includes at least one " +"digit past the decimal point, and switches to the scientific notation when " +"``exp >= p - 1``. When the precision is not specified, the latter will be " +"as large as needed to represent the given value faithfully." msgstr "" -"Para :class:`float`, é o mesmo que ``'g'``, exceto que quando a notação de " +"Para :class:`float`, é o como o tipo ``'g'``, exceto que quando a notação de " "ponto fixo é usada para formatar o resultado, ela sempre inclui pelo menos " -"um dígito após a vírgula decimal. A precisão usada é tão grande quanto " -"necessário para representar o valor fornecido fielmente." +"um dígito após a ponto decimal, e troca para a notação científica quando " +"``exp >= p - 1``. Quando a precisão não é especificada, este último será tão " +"grande quanto necessário para representar o valor fornecido fielmente." -#: ../../library/string.rst:583 +#: ../../library/string.rst:609 msgid "" "For :class:`~decimal.Decimal`, this is the same as either ``'g'`` or ``'G'`` " "depending on the value of ``context.capitals`` for the current decimal " @@ -1113,7 +1176,7 @@ msgstr "" "Para :class:`~decimal.Decimal`, é o mesmo que ``'g'`` ou ``'G'`` dependendo " "do valor de ``context.capitals`` para o contexto decimal atual." -#: ../../library/string.rst:587 +#: ../../library/string.rst:613 msgid "" "The overall effect is to match the output of :func:`str` as altered by the " "other format modifiers." @@ -1121,11 +1184,45 @@ msgstr "" "O efeito geral é combinar a saída de :func:`str` conforme alterada pelos " "outros modificadores de formato." -#: ../../library/string.rst:595 +#: ../../library/string.rst:617 +msgid "" +"The result should be correctly rounded to a given precision ``p`` of digits " +"after the decimal point. The rounding mode for :class:`float` matches that " +"of the :func:`round` builtin. For :class:`~decimal.Decimal`, the rounding " +"mode of the current :ref:`context ` will be used." +msgstr "" +"O resultado deve ser arredondado corretamente para uma precisão dada ``p`` " +"de dígitos após o ponto decimal. O modo de arredondamento para :class:" +"`float` corresponde ao do builtin :func:`round`. Para :class:`~decimal." +"Decimal`, o modo de arredondamento do :ref:`contexto ` " +"atual será usado." + +#: ../../library/string.rst:622 +msgid "" +"The available presentation types for :class:`complex` are the same as those " +"for :class:`float` (``'%'`` is not allowed). Both the real and imaginary " +"components of a complex number are formatted as floating-point numbers, " +"according to the specified presentation type. They are separated by the " +"mandatory sign of the imaginary part, the latter being terminated by a ``j`` " +"suffix. If the presentation type is missing, the result will match the " +"output of :func:`str` (complex numbers with a non-zero real part are also " +"surrounded by parentheses), possibly altered by other format modifiers." +msgstr "" +"Os tipos de apresentação disponíveis para :class:`complex` são os mesmos que " +"para :class:`float` (``'%'`` não é permitido). Os componentes real e " +"imaginário de um número complexo são formatados como números de ponto " +"flutuante, de acordo com o tipo de apresentação especificado. Eles são " +"separados pelo sinal obrigatório da parte imaginária, sendo esta última " +"terminada por um sufixo ``j``. Se o tipo de apresentação estiver faltando, o " +"resultado corresponderá à saída de :func:`str` (números complexos com uma " +"parte real diferente de zero também são cercados por parênteses), " +"possivelmente alterados por outros modificadores de formato." + +#: ../../library/string.rst:635 msgid "Format examples" msgstr "Exemplos de formato" -#: ../../library/string.rst:597 +#: ../../library/string.rst:637 msgid "" "This section contains examples of the :meth:`str.format` syntax and " "comparison with the old ``%``-formatting." @@ -1133,7 +1230,7 @@ msgstr "" "Esta seção contém exemplos da sintaxe de :meth:`str.format` e comparação com " "a antiga formatação ``%``." -#: ../../library/string.rst:600 +#: ../../library/string.rst:640 msgid "" "In most of the cases the syntax is similar to the old ``%``-formatting, with " "the addition of the ``{}`` and with ``:`` used instead of ``%``. For " @@ -1143,7 +1240,7 @@ msgstr "" "com a adição de ``{}`` e com ``:`` usado em vez de ``%``. Por exemplo, " "``'%03.2f'`` pode ser traduzido para ``'{:03.2f}'``." -#: ../../library/string.rst:604 +#: ../../library/string.rst:644 msgid "" "The new format syntax also supports new and different options, shown in the " "following examples." @@ -1151,61 +1248,303 @@ msgstr "" "A nova sintaxe de formato também oferece suporte a opções novas e " "diferentes, mostradas nos exemplos a seguir." -#: ../../library/string.rst:607 +#: ../../library/string.rst:647 msgid "Accessing arguments by position::" msgstr "Acessando os argumentos por posição::" -#: ../../library/string.rst:620 +#: ../../library/string.rst:649 +msgid "" +">>> '{0}, {1}, {2}'.format('a', 'b', 'c')\n" +"'a, b, c'\n" +">>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only\n" +"'a, b, c'\n" +">>> '{2}, {1}, {0}'.format('a', 'b', 'c')\n" +"'c, b, a'\n" +">>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence\n" +"'c, b, a'\n" +">>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be " +"repeated\n" +"'abracadabra'" +msgstr "" +">>> '{0}, {1}, {2}'.format('a', 'b', 'c')\n" +"'a, b, c'\n" +">>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only\n" +"'a, b, c'\n" +">>> '{2}, {1}, {0}'.format('a', 'b', 'c')\n" +"'c, b, a'\n" +">>> '{2}, {1}, {0}'.format(*'abc') # desempacotando sequência de " +"argumentos\n" +"'c, b, a'\n" +">>> '{0}{1}{0}'.format('abra', 'cad') # índices dos argumentos podem ser " +"repetidos\n" +"'abracadabra'" + +#: ../../library/string.rst:660 msgid "Accessing arguments by name::" msgstr "Acessando os argumentos por nome::" -#: ../../library/string.rst:628 +#: ../../library/string.rst:662 +msgid "" +">>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', " +"longitude='-115.81W')\n" +"'Coordinates: 37.24N, -115.81W'\n" +">>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}\n" +">>> 'Coordinates: {latitude}, {longitude}'.format(**coord)\n" +"'Coordinates: 37.24N, -115.81W'" +msgstr "" +">>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', " +"longitude='-115.81W')\n" +"'Coordinates: 37.24N, -115.81W'\n" +">>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}\n" +">>> 'Coordinates: {latitude}, {longitude}'.format(**coord)\n" +"'Coordinates: 37.24N, -115.81W'" + +#: ../../library/string.rst:668 msgid "Accessing arguments' attributes::" msgstr "Acessando os atributos dos argumentos::" -#: ../../library/string.rst:643 +#: ../../library/string.rst:670 +msgid "" +">>> c = 3-5j\n" +">>> ('The complex number {0} is formed from the real part {0.real} '\n" +"... 'and the imaginary part {0.imag}.').format(c)\n" +"'The complex number (3-5j) is formed from the real part 3.0 and the " +"imaginary part -5.0.'\n" +">>> class Point:\n" +"... def __init__(self, x, y):\n" +"... self.x, self.y = x, y\n" +"... def __str__(self):\n" +"... return 'Point({self.x}, {self.y})'.format(self=self)\n" +"...\n" +">>> str(Point(4, 2))\n" +"'Point(4, 2)'" +msgstr "" +">>> c = 3-5j\n" +">>> ('The complex number {0} is formed from the real part {0.real} '\n" +"... 'and the imaginary part {0.imag}.').format(c)\n" +"'The complex number (3-5j) is formed from the real part 3.0 and the " +"imaginary part -5.0.'\n" +">>> class Point:\n" +"... def __init__(self, x, y):\n" +"... self.x, self.y = x, y\n" +"... def __str__(self):\n" +"... return 'Point({self.x}, {self.y})'.format(self=self)\n" +"...\n" +">>> str(Point(4, 2))\n" +"'Point(4, 2)'" + +#: ../../library/string.rst:683 msgid "Accessing arguments' items::" msgstr "Acessando os itens dos argumentos::" -#: ../../library/string.rst:649 +#: ../../library/string.rst:685 +msgid "" +">>> coord = (3, 5)\n" +">>> 'X: {0[0]}; Y: {0[1]}'.format(coord)\n" +"'X: 3; Y: 5'" +msgstr "" +">>> coord = (3, 5)\n" +">>> 'X: {0[0]}; Y: {0[1]}'.format(coord)\n" +"'X: 3; Y: 5'" + +#: ../../library/string.rst:689 msgid "Replacing ``%s`` and ``%r``::" msgstr "Substituindo ``%s`` e ``%r``::" -#: ../../library/string.rst:654 +#: ../../library/string.rst:691 +msgid "" +">>> \"repr() shows quotes: {!r}; str() doesn't: {!s}\".format('test1', " +"'test2')\n" +"\"repr() shows quotes: 'test1'; str() doesn't: test2\"" +msgstr "" +">>> \"repr() mostra aspas: {!r}; str() não mostra: {!s}\".format('teste1', " +"'teste2')\n" +"\"repr() mostra aspas: 'teste1'; str() não mostra: teste2\"" + +#: ../../library/string.rst:694 msgid "Aligning the text and specifying a width::" msgstr "Alinhando o texto e especificando uma largura::" -#: ../../library/string.rst:665 +#: ../../library/string.rst:696 +msgid "" +">>> '{:<30}'.format('left aligned')\n" +"'left aligned '\n" +">>> '{:>30}'.format('right aligned')\n" +"' right aligned'\n" +">>> '{:^30}'.format('centered')\n" +"' centered '\n" +">>> '{:*^30}'.format('centered') # use '*' as a fill char\n" +"'***********centered***********'" +msgstr "" +">>> '{:<30}'.format('alinhado à esquerda')\n" +"'alinhado à esquerda '\n" +">>> '{:>30}'.format('alinhado à direita')\n" +"' alinhado à direita'\n" +">>> '{:^30}'.format('centralizado')\n" +"' centralizado '\n" +">>> '{:*^30}'.format('centralizado') # usa '*' como preenchimento\n" +"'*********centralizado*********'" + +#: ../../library/string.rst:705 msgid "Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::" msgstr "Substituindo ``%+f``, ``%-f`` e ``% f`` e especificando um sinal::" -#: ../../library/string.rst:674 +#: ../../library/string.rst:707 +msgid "" +">>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always\n" +"'+3.140000; -3.140000'\n" +">>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers\n" +"' 3.140000; -3.140000'\n" +">>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:" +"f}; {:f}'\n" +"'3.140000; -3.140000'" +msgstr "" +">>> '{:+f}; {:+f}'.format(3.14, -3.14) # mostra sempre\n" +"'+3.140000; -3.140000'\n" +">>> '{: f}; {: f}'.format(3.14, -3.14) # mostra um espaço para números " +"positivos\n" +"' 3.140000; -3.140000'\n" +">>> '{:-f}; {:-f}'.format(3.14, -3.14) # mostra apenas o sinal de menos -- " +"mesmo que '{:f}; {:f}'\n" +"'3.140000; -3.140000'" + +#: ../../library/string.rst:714 msgid "" "Replacing ``%x`` and ``%o`` and converting the value to different bases::" msgstr "" "Substituindo ``%x`` e ``%o`` e convertendo o valor para bases diferentes::" -#: ../../library/string.rst:683 -msgid "Using the comma as a thousands separator::" -msgstr "Usando a vírgula como um separador de milhares::" +#: ../../library/string.rst:716 +msgid "" +">>> # format also supports binary numbers\n" +">>> \"int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}\".format(42)\n" +"'int: 42; hex: 2a; oct: 52; bin: 101010'\n" +">>> # with 0x, 0o, or 0b as prefix:\n" +">>> \"int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}\".format(42)\n" +"'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'" +msgstr "" +">>> # format também tem suporte a números binários\n" +">>> \"int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}\".format(42)\n" +"'int: 42; hex: 2a; oct: 52; bin: 101010'\n" +">>> # com 0x, 0o ou 0b como prefixo:\n" +">>> \"int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}\".format(42)\n" +"'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'" + +#: ../../library/string.rst:723 +msgid "Using the comma or the underscore as a digit group separator::" +msgstr "Usando a vírgula ou o sublinhado como separador de grupos de dígitos::" -#: ../../library/string.rst:688 +#: ../../library/string.rst:725 +msgid "" +">>> '{:,}'.format(1234567890)\n" +"'1,234,567,890'\n" +">>> '{:_}'.format(1234567890)\n" +"'1_234_567_890'\n" +">>> '{:_b}'.format(1234567890)\n" +"'100_1001_1001_0110_0000_0010_1101_0010'\n" +">>> '{:_x}'.format(1234567890)\n" +"'4996_02d2'" +msgstr "" + +#: ../../library/string.rst:734 msgid "Expressing a percentage::" msgstr "Expressando uma porcentagem::" -#: ../../library/string.rst:695 +#: ../../library/string.rst:736 +msgid "" +">>> points = 19\n" +">>> total = 22\n" +">>> 'Correct answers: {:.2%}'.format(points/total)\n" +"'Correct answers: 86.36%'" +msgstr "" +">>> points = 19\n" +">>> total = 22\n" +">>> 'Correct answers: {:.2%}'.format(points/total)\n" +"'Correct answers: 86.36%'" + +#: ../../library/string.rst:741 msgid "Using type-specific formatting::" msgstr "Usando formatação específica do tipo::" -#: ../../library/string.rst:702 +#: ../../library/string.rst:743 +msgid "" +">>> import datetime\n" +">>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)\n" +">>> '{:%Y-%m-%d %H:%M:%S}'.format(d)\n" +"'2010-07-04 12:15:58'" +msgstr "" +">>> import datetime\n" +">>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)\n" +">>> '{:%Y-%m-%d %H:%M:%S}'.format(d)\n" +"'2010-07-04 12:15:58'" + +#: ../../library/string.rst:748 msgid "Nesting arguments and more complex examples::" msgstr "Argumentos de aninhamento e exemplos mais complexos::" -#: ../../library/string.rst:736 +#: ../../library/string.rst:750 +msgid "" +">>> for align, text in zip('<^>', ['left', 'center', 'right']):\n" +"... '{0:{fill}{align}16}'.format(text, fill=align, align=align)\n" +"...\n" +"'left<<<<<<<<<<<<'\n" +"'^^^^^center^^^^^'\n" +"'>>>>>>>>>>>right'\n" +">>>\n" +">>> octets = [192, 168, 0, 1]\n" +">>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)\n" +"'C0A80001'\n" +">>> int(_, 16)\n" +"3232235521\n" +">>>\n" +">>> width = 5\n" +">>> for num in range(5,12):\n" +"... for base in 'dXob':\n" +"... print('{0:{width}{base}}'.format(num, base=base, width=width), " +"end=' ')\n" +"... print()\n" +"...\n" +" 5 5 5 101\n" +" 6 6 6 110\n" +" 7 7 7 111\n" +" 8 8 10 1000\n" +" 9 9 11 1001\n" +" 10 A 12 1010\n" +" 11 B 13 1011" +msgstr "" +">>> for align, text in zip('<^>', ['left', 'center', 'right']):\n" +"... '{0:{fill}{align}16}'.format(text, fill=align, align=align)\n" +"...\n" +"'left<<<<<<<<<<<<'\n" +"'^^^^^center^^^^^'\n" +"'>>>>>>>>>>>right'\n" +">>>\n" +">>> octets = [192, 168, 0, 1]\n" +">>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)\n" +"'C0A80001'\n" +">>> int(_, 16)\n" +"3232235521\n" +">>>\n" +">>> width = 5\n" +">>> for num in range(5,12):\n" +"... for base in 'dXob':\n" +"... print('{0:{width}{base}}'.format(num, base=base, width=width), " +"end=' ')\n" +"... print()\n" +"...\n" +" 5 5 5 101\n" +" 6 6 6 110\n" +" 7 7 7 111\n" +" 8 8 10 1000\n" +" 9 9 11 1001\n" +" 10 A 12 1010\n" +" 11 B 13 1011" + +#: ../../library/string.rst:782 msgid "Template strings" msgstr "Strings de modelo" -#: ../../library/string.rst:738 +#: ../../library/string.rst:784 msgid "" "Template strings provide simpler string substitutions as described in :pep:" "`292`. A primary use case for template strings is for internationalization " @@ -1222,7 +1561,7 @@ msgstr "" "biblioteca construída sobre strings de modelo para i18n, veja o pacote " "`flufl.i18n `_." -#: ../../library/string.rst:748 +#: ../../library/string.rst:794 msgid "" "Template strings support ``$``-based substitutions, using the following " "rules:" @@ -1230,11 +1569,11 @@ msgstr "" "Strings de modelo oferecem suporte a substituições baseadas em ``$``, usando " "as seguintes regras:" -#: ../../library/string.rst:750 +#: ../../library/string.rst:796 msgid "``$$`` is an escape; it is replaced with a single ``$``." msgstr "``$$`` é um escape; é substituído por um único ``$``." -#: ../../library/string.rst:752 +#: ../../library/string.rst:798 msgid "" "``$identifier`` names a substitution placeholder matching a mapping key of " "``\"identifier\"``. By default, ``\"identifier\"`` is restricted to any " @@ -1251,7 +1590,7 @@ msgstr "" "identificador após o caractere ``$`` termina esta especificação de espaço " "reservado." -#: ../../library/string.rst:759 +#: ../../library/string.rst:805 msgid "" "``${identifier}`` is equivalent to ``$identifier``. It is required when " "valid identifier characters follow the placeholder but are not part of the " @@ -1261,7 +1600,7 @@ msgstr "" "caracteres identificadores válidos seguem o marcador de posição, mas não " "fazem parte do marcador, como ``\"${noun}ification\"``." -#: ../../library/string.rst:763 +#: ../../library/string.rst:809 msgid "" "Any other appearance of ``$`` in the string will result in a :exc:" "`ValueError` being raised." @@ -1269,7 +1608,7 @@ msgstr "" "Qualquer outra ocorrência de ``$`` na string resultará em uma :exc:" "`ValueError` sendo levantada." -#: ../../library/string.rst:766 +#: ../../library/string.rst:812 msgid "" "The :mod:`string` module provides a :class:`Template` class that implements " "these rules. The methods of :class:`Template` are:" @@ -1277,11 +1616,11 @@ msgstr "" "O módulo :mod:`string` fornece uma classe :class:`Template` que implementa " "essas regras. Os métodos de :class:`Template` são:" -#: ../../library/string.rst:772 +#: ../../library/string.rst:818 msgid "The constructor takes a single argument which is the template string." msgstr "O construtor recebe um único argumento que é a string de modelo." -#: ../../library/string.rst:777 +#: ../../library/string.rst:823 msgid "" "Performs the template substitution, returning a new string. *mapping* is " "any dictionary-like object with keys that match the placeholders in the " @@ -1296,7 +1635,7 @@ msgstr "" "*kwds* são fornecidos e há duplicatas, os marcadores de *kwds* têm " "precedência." -#: ../../library/string.rst:786 +#: ../../library/string.rst:832 msgid "" "Like :meth:`substitute`, except that if placeholders are missing from " "*mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the " @@ -1311,7 +1650,7 @@ msgstr "" "ocorrência de ``$`` simplesmente retornará ``$`` em vez de levantar :exc:" "`ValueError`." -#: ../../library/string.rst:792 +#: ../../library/string.rst:838 msgid "" "While other exceptions may still occur, this method is called \"safe\" " "because it always tries to return a usable string instead of raising an " @@ -1328,15 +1667,15 @@ msgstr "" "correspondidas ou espacos reservados que não são identificadores Python " "válidos." -#: ../../library/string.rst:802 +#: ../../library/string.rst:848 msgid "" -"Returns false if the template has invalid placeholders that will cause :meth:" -"`substitute` to raise :exc:`ValueError`." +"Returns ``False`` if the template has invalid placeholders that will cause :" +"meth:`substitute` to raise :exc:`ValueError`." msgstr "" -"Retorna falso se o modelo tiver espaços reservados inválidos que farão com " -"que :meth:`substitute` levante :exc:`ValueError`." +"Retorna ``False`` se o modelo tiver espaços reservados inválidos que farão " +"com que :meth:`substitute` levante :exc:`ValueError`." -#: ../../library/string.rst:810 +#: ../../library/string.rst:856 msgid "" "Returns a list of the valid identifiers in the template, in the order they " "first appear, ignoring any invalid identifiers." @@ -1344,13 +1683,13 @@ msgstr "" "Retorna uma lista dos identificadores válidos no modelo, na ordem em que " "aparecem pela primeira vez, ignorando quaisquer identificadores inválidos." -#: ../../library/string.rst:815 +#: ../../library/string.rst:861 msgid ":class:`Template` instances also provide one public data attribute:" msgstr "" "Instâncias de :class:`Template` também fornecem um atributo de dados " "públicos:" -#: ../../library/string.rst:819 +#: ../../library/string.rst:865 msgid "" "This is the object passed to the constructor's *template* argument. In " "general, you shouldn't change it, but read-only access is not enforced." @@ -1358,11 +1697,45 @@ msgstr "" "Este é o objeto passado para o argumento *template* do construtor. Em geral, " "você não deve alterá-lo, mas o acesso somente leitura não é obrigatório." -#: ../../library/string.rst:822 +#: ../../library/string.rst:868 msgid "Here is an example of how to use a Template::" msgstr "Aqui está um exemplo de como usar uma instância de Template::" -#: ../../library/string.rst:840 +#: ../../library/string.rst:870 +msgid "" +">>> from string import Template\n" +">>> s = Template('$who likes $what')\n" +">>> s.substitute(who='tim', what='kung pao')\n" +"'tim likes kung pao'\n" +">>> d = dict(who='tim')\n" +">>> Template('Give $who $100').substitute(d)\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: Invalid placeholder in string: line 1, col 11\n" +">>> Template('$who likes $what').substitute(d)\n" +"Traceback (most recent call last):\n" +"...\n" +"KeyError: 'what'\n" +">>> Template('$who likes $what').safe_substitute(d)\n" +"'tim likes $what'" +msgstr "" +">>> from string import Template\n" +">>> s = Template('$who likes $what')\n" +">>> s.substitute(who='tim', what='kung pao')\n" +"'tim likes kung pao'\n" +">>> d = dict(who='tim')\n" +">>> Template('Give $who $100').substitute(d)\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: Invalid placeholder in string: line 1, col 11\n" +">>> Template('$who likes $what').substitute(d)\n" +"Traceback (most recent call last):\n" +"...\n" +"KeyError: 'what'\n" +">>> Template('$who likes $what').safe_substitute(d)\n" +"'tim likes $what'" + +#: ../../library/string.rst:886 msgid "" "Advanced usage: you can derive subclasses of :class:`Template` to customize " "the placeholder syntax, delimiter character, or the entire regular " @@ -1374,7 +1747,7 @@ msgstr "" "expressão regular usada para analisar strings de modelo. Para fazer isso, " "você pode substituir estes atributos de classe:" -#: ../../library/string.rst:845 +#: ../../library/string.rst:891 msgid "" "*delimiter* -- This is the literal string describing a placeholder " "introducing delimiter. The default value is ``$``. Note that this should " @@ -1390,7 +1763,7 @@ msgstr "" "alterar o delimitador após a criação da classe (ou seja, um delimitador " "diferente deve ser definido no espaço de nomes da classe da subclasse)." -#: ../../library/string.rst:852 +#: ../../library/string.rst:898 msgid "" "*idpattern* -- This is the regular expression describing the pattern for non-" "braced placeholders. The default value is the regular expression ``(?a:[_a-" @@ -1402,7 +1775,7 @@ msgstr "" "[_a-z][_a-z0-9]*)``. Se for fornecido e *braceidpattern* for ``None``, esse " "padrão também se aplicará o espaço reservado com chaves." -#: ../../library/string.rst:859 +#: ../../library/string.rst:905 msgid "" "Since default *flags* is ``re.IGNORECASE``, pattern ``[a-z]`` can match with " "some non-ASCII characters. That's why we use the local ``a`` flag here." @@ -1411,15 +1784,15 @@ msgstr "" "corresponder a alguns caracteres não ASCII. É por isso que usamos o " "sinalizador local ``a`` aqui." -#: ../../library/string.rst:863 +#: ../../library/string.rst:909 msgid "" "*braceidpattern* can be used to define separate patterns used inside and " "outside the braces." msgstr "" -"*braceidpattern* pode ser usado para definir padrões separados usados ​​dentro " +"*braceidpattern* pode ser usado para definir padrões separados usados dentro " "e fora das chaves." -#: ../../library/string.rst:867 +#: ../../library/string.rst:913 msgid "" "*braceidpattern* -- This is like *idpattern* but describes the pattern for " "braced placeholders. Defaults to ``None`` which means to fall back to " @@ -1433,7 +1806,7 @@ msgstr "" "fornecido, permite definir padrões diferentes para espaço reservado com e " "sem chaves." -#: ../../library/string.rst:875 +#: ../../library/string.rst:921 msgid "" "*flags* -- The regular expression flags that will be applied when compiling " "the regular expression used for recognizing substitutions. The default " @@ -1447,7 +1820,7 @@ msgstr "" "aos sinalizadores, então *idpattern*\\s personalizados devem seguir as " "convenções para expressões regulares verbosas." -#: ../../library/string.rst:883 +#: ../../library/string.rst:929 msgid "" "Alternatively, you can provide the entire regular expression pattern by " "overriding the class attribute *pattern*. If you do this, the value must be " @@ -1461,7 +1834,7 @@ msgstr "" "nomeados. Os grupos de captura correspondem às regras fornecidas acima, " "junto com a regra inválida do espaço reservado:" -#: ../../library/string.rst:889 +#: ../../library/string.rst:935 msgid "" "*escaped* -- This group matches the escape sequence, e.g. ``$$``, in the " "default pattern." @@ -1469,7 +1842,7 @@ msgstr "" "*escaped* -- Este grupo corresponde à sequência de escape, por exemplo ``$" "$``, no padrão." -#: ../../library/string.rst:892 +#: ../../library/string.rst:938 msgid "" "*named* -- This group matches the unbraced placeholder name; it should not " "include the delimiter in capturing group." @@ -1477,7 +1850,7 @@ msgstr "" "*named* -- Este grupo corresponde ao nome do espaço reservado sem chaves; " "não deve incluir o delimitador no grupo de captura." -#: ../../library/string.rst:895 +#: ../../library/string.rst:941 msgid "" "*braced* -- This group matches the brace enclosed placeholder name; it " "should not include either the delimiter or braces in the capturing group." @@ -1485,7 +1858,7 @@ msgstr "" "*braced* -- Este grupo corresponde ao nome do espaço reservado entre chaves; " "ele não deve incluir o delimitador ou chaves no grupo de captura." -#: ../../library/string.rst:898 +#: ../../library/string.rst:944 msgid "" "*invalid* -- This group matches any other delimiter pattern (usually a " "single delimiter), and it should appear last in the regular expression." @@ -1494,7 +1867,7 @@ msgstr "" "(geralmente um único delimitador) e deve aparecer por último na expressão " "regular." -#: ../../library/string.rst:901 +#: ../../library/string.rst:947 msgid "" "The methods on this class will raise :exc:`ValueError` if the pattern " "matches the template without one of these named groups matching." @@ -1502,11 +1875,11 @@ msgstr "" "Os métodos nesta classe irão levantar :exc:`ValueError` se o padrão " "corresponder ao modelo sem que um desses grupos nomeados corresponda." -#: ../../library/string.rst:906 +#: ../../library/string.rst:952 msgid "Helper functions" msgstr "Funções auxiliares" -#: ../../library/string.rst:910 +#: ../../library/string.rst:956 msgid "" "Split the argument into words using :meth:`str.split`, capitalize each word " "using :meth:`str.capitalize`, and join the capitalized words using :meth:" @@ -1523,77 +1896,76 @@ msgstr "" "direita são removidos, caso contrário *sep* é usado para dividir e unir as " "palavras." -#: ../../library/string.rst:195 +#: ../../library/string.rst:202 msgid "{} (curly brackets)" msgstr "{} (chaves)" -#: ../../library/string.rst:195 ../../library/string.rst:335 -#: ../../library/string.rst:367 ../../library/string.rst:386 -#: ../../library/string.rst:395 ../../library/string.rst:409 -#: ../../library/string.rst:418 +#: ../../library/string.rst:202 ../../library/string.rst:344 +#: ../../library/string.rst:377 ../../library/string.rst:396 +#: ../../library/string.rst:405 ../../library/string.rst:437 msgid "in string formatting" msgstr "na formatação de strings" -#: ../../library/string.rst:195 +#: ../../library/string.rst:202 msgid ". (dot)" msgstr ". (ponto)" -#: ../../library/string.rst:195 +#: ../../library/string.rst:202 msgid "[] (square brackets)" msgstr "[] (colchetes)" -#: ../../library/string.rst:195 +#: ../../library/string.rst:202 msgid "! (exclamation)" msgstr "! (exclamação)" -#: ../../library/string.rst:195 +#: ../../library/string.rst:202 msgid ": (colon)" msgstr ": (dois pontos)" -#: ../../library/string.rst:335 +#: ../../library/string.rst:344 msgid "< (less)" msgstr "< (menor que)" -#: ../../library/string.rst:335 +#: ../../library/string.rst:344 msgid "> (greater)" msgstr "> (maior)" -#: ../../library/string.rst:335 +#: ../../library/string.rst:344 msgid "= (equals)" msgstr "= (igual)" -#: ../../library/string.rst:335 +#: ../../library/string.rst:344 msgid "^ (caret)" msgstr "^ (circunflexo)" -#: ../../library/string.rst:367 +#: ../../library/string.rst:377 msgid "+ (plus)" msgstr "+ (mais)" -#: ../../library/string.rst:367 +#: ../../library/string.rst:377 msgid "- (minus)" msgstr "- (menos)" -#: ../../library/string.rst:386 +#: ../../library/string.rst:396 msgid "z" msgstr "z" -#: ../../library/string.rst:395 +#: ../../library/string.rst:405 msgid "# (hash)" msgstr "# (cerquilha)" -#: ../../library/string.rst:409 +#: ../../library/string.rst:437 msgid ", (comma)" msgstr ", (vírgula)" -#: ../../library/string.rst:418 +#: ../../library/string.rst:437 msgid "_ (underscore)" -msgstr "_ (underscore)" +msgstr "_ (sublinhado)" -#: ../../library/string.rst:746 +#: ../../library/string.rst:792 msgid "$ (dollar)" msgstr "$ (dólar)" -#: ../../library/string.rst:746 +#: ../../library/string.rst:792 msgid "in template strings" msgstr "no template de strings" diff --git a/library/stringprep.po b/library/stringprep.po index 33635ca76..76abb8fce 100644 --- a/library/stringprep.po +++ b/library/stringprep.po @@ -1,31 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:14+0000\n" -"Last-Translator: Rafael Fontenelle , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/stringprep.rst:2 msgid ":mod:`!stringprep` --- Internet String Preparation" -msgstr "" +msgstr ":mod:`!stringprep` --- Preparação de string para internet" #: ../../library/stringprep.rst:10 msgid "**Source code:** :source:`Lib/stringprep.py`" @@ -40,6 +40,12 @@ msgid "" "possible identifications, to allow only identifications consisting of " "\"printable\" characters." msgstr "" +"Ao identificar coisas (como nomes de host) na internet, muitas vezes é " +"necessário comparar tais identificações para \"igualdade\". Exatamente como " +"essa comparação é executada pode depender do domínio da aplicação, por " +"exemplo, se deve ser insensível a maiúsculas e minúsculas ou não. Também " +"pode ser necessário restringir as possíveis identificações, para permitir " +"apenas identificações consistindo de caracteres \"imprimíveis\"." #: ../../library/stringprep.rst:21 msgid "" @@ -52,6 +58,14 @@ msgid "" "``stringprep`` profile is ``nameprep``, which is used for internationalized " "domain names." msgstr "" +":rfc:`3454` define um procedimento para \"preparar\" strings Unicode em " +"protocolos de internet. Antes de passar strings para o fio, elas são " +"processadas com o procedimento de preparação, após o qual elas têm uma certa " +"forma normalizada. O RFC define um conjunto de tabelas, que podem ser " +"combinadas em perfis. Cada perfil deve definir quais tabelas ele usa, e " +"quais outras partes opcionais do procedimento ``stringprep`` são parte do " +"perfil. Um exemplo de um perfil ``stringprep`` é ``nameprep``, que é usado " +"para nomes de domínio internacionalizados." #: ../../library/stringprep.rst:29 msgid "" @@ -60,6 +74,11 @@ msgid "" "module uses the Unicode character database internally. The module source " "code itself was generated using the ``mkstringprep.py`` utility." msgstr "" +"O módulo :mod:`stringprep` expõe apenas as tabelas do :rfc:`3454`. Como " +"essas tabelas seriam muito grandes para representar como dicionários ou " +"listas, o módulo usa o banco de dados de caracteres Unicode internamente. O " +"código-fonte do módulo em si foi gerado usando o utilitário ``mkstringprep." +"py``." #: ../../library/stringprep.rst:34 msgid "" @@ -70,100 +89,130 @@ msgid "" "provides the mapping function: given the key, it returns the associated " "value. Below is a list of all functions available in the module." msgstr "" +"Como resultado, essas tabelas são expostas como funções, não como estruturas " +"de dados. Existem dois tipos de tabelas no RFC: conjuntos e mapeamentos. " +"Para um conjunto, :mod:`stringprep` fornece a \"função característica\", ou " +"seja, uma função que retorna ``True`` se o parâmetro fizer parte do " +"conjunto. Para mapeamentos, ele fornece a função de mapeamento: dada a " +"chave, ele retorna o valor associado. Abaixo está uma lista de todas as " +"funções disponíveis no módulo." #: ../../library/stringprep.rst:44 msgid "" "Determine whether *code* is in tableA.1 (Unassigned code points in Unicode " "3.2)." msgstr "" +"Determina se *code* está na tabela A.1 (pontos de código não atribuídos no " +"Unicode 3.2)." #: ../../library/stringprep.rst:49 msgid "Determine whether *code* is in tableB.1 (Commonly mapped to nothing)." -msgstr "" +msgstr "Determina se *code* está na tabela B.1 (comumente mapeado para nada)." #: ../../library/stringprep.rst:54 msgid "" "Return the mapped value for *code* according to tableB.2 (Mapping for case-" "folding used with NFKC)." msgstr "" +"Retorna o valor mapeado para *code* de acordo com a tabela B.2 (mapeamento " +"para dobramento de casos usado com NFKC)." #: ../../library/stringprep.rst:60 msgid "" "Return the mapped value for *code* according to tableB.3 (Mapping for case-" "folding used with no normalization)." msgstr "" +"Retorna o valor mapeado para *code* de acordo com a tabela B.3 (mapeamento " +"para dobramento de casos usado com nenhuma normalização)." #: ../../library/stringprep.rst:66 msgid "Determine whether *code* is in tableC.1.1 (ASCII space characters)." -msgstr "" +msgstr "Determina se *code* está na tabela C.1.1 (caracteres de espaço ASCII)." #: ../../library/stringprep.rst:71 msgid "" "Determine whether *code* is in tableC.1.2 (Non-ASCII space characters)." msgstr "" +"Determina se *code* está na tabela C.1.2 (caracteres de espaço não-ASCII)." #: ../../library/stringprep.rst:76 msgid "" "Determine whether *code* is in tableC.1 (Space characters, union of C.1.1 " "and C.1.2)." msgstr "" +"Determina se *code* está na tabela C.1 (caracteres de espaço, união de C.1.1 " +"e C.1.2)." #: ../../library/stringprep.rst:82 msgid "Determine whether *code* is in tableC.2.1 (ASCII control characters)." msgstr "" +"Determina se *code* está na tabela C.2.1 (caracteres de controle ASCII)." #: ../../library/stringprep.rst:87 msgid "" "Determine whether *code* is in tableC.2.2 (Non-ASCII control characters)." msgstr "" +"Determina se *code* está na tabela C.2.2 (caracteres de controle não-ASCII)." #: ../../library/stringprep.rst:92 msgid "" "Determine whether *code* is in tableC.2 (Control characters, union of C.2.1 " "and C.2.2)." msgstr "" +"Determina se *code* está na tabela C.2 (caracteres de controle, união de " +"C.2.1 e C.2.2)." #: ../../library/stringprep.rst:98 msgid "Determine whether *code* is in tableC.3 (Private use)." -msgstr "" +msgstr "Determina se *code* está na tabela C.3 (uso privado)." #: ../../library/stringprep.rst:103 msgid "Determine whether *code* is in tableC.4 (Non-character code points)." msgstr "" +"Determina se *code* está na tabela C.4 (pontos de código não-caracteres)." #: ../../library/stringprep.rst:108 msgid "Determine whether *code* is in tableC.5 (Surrogate codes)." -msgstr "" +msgstr "Determina se *code* está na tabela C.5 (códigos substitutos)." #: ../../library/stringprep.rst:113 msgid "" "Determine whether *code* is in tableC.6 (Inappropriate for plain text)." msgstr "" +"Determina se *code* está na tabela C.6 (inapropriado para texto simples)." #: ../../library/stringprep.rst:118 msgid "" "Determine whether *code* is in tableC.7 (Inappropriate for canonical " "representation)." msgstr "" +"Determina se *code* está na tabela C.7 (inapropriado para para representação " +"canônica)." #: ../../library/stringprep.rst:124 msgid "" "Determine whether *code* is in tableC.8 (Change display properties or are " "deprecated)." msgstr "" +"Determina se *code* está na tabela C.8 (alteram propriedades de exibição ou " +"estão descontinuadas)." #: ../../library/stringprep.rst:130 msgid "Determine whether *code* is in tableC.9 (Tagging characters)." -msgstr "" +msgstr "Determina se *code* está na tabela C.9 (caracteres de tag)." #: ../../library/stringprep.rst:135 msgid "" "Determine whether *code* is in tableD.1 (Characters with bidirectional " "property \"R\" or \"AL\")." msgstr "" +"Determina se *code* está na tabela D.1 (Caracteres com propriedade " +"bidirecional \"R\" ou \"AL\")." #: ../../library/stringprep.rst:141 msgid "" "Determine whether *code* is in tableD.2 (Characters with bidirectional " "property \"L\")." msgstr "" +"Determina se *code* está na tabela D.2 (Caracteres com propriedade " +"bidirecional \"L\")." diff --git a/library/struct.po b/library/struct.po index b662d72cf..bdcb61ea4 100644 --- a/library/struct.po +++ b/library/struct.po @@ -1,42 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Misael borges , 2021 -# Juliana Karoline , 2021 -# (Douglas da Silva) , 2022 -# i17obot , 2022 -# Vinicius Gubiani Ferreira , 2022 -# Julia Rizza , 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# Marco Rougeth , 2023 -# Adorilson Bezerra , 2023 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 01:14+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/struct.rst:2 msgid ":mod:`!struct` --- Interpret bytes as packed binary data" -msgstr "" +msgstr ":mod:`!struct` --- Interpreta bytes como dados binários empacotados" #: ../../library/struct.rst:11 msgid "**Source code:** :source:`Lib/struct.py`" @@ -52,6 +41,13 @@ msgid "" "connections), or data transfer between the Python application and the C " "layer." msgstr "" +"Este módulo converte entre valores Python e structs C representados como " +"objetos :class:`bytes` do Python. :ref:`Strings de formato ` compactas descrevem as conversões pretendidas de/para valores " +"Python. As funções e objetos do módulo podem ser usados para duas aplicações " +"amplamente distintas, troca de dados com fontes externas (arquivos ou " +"conexões de rede) ou transferência de dados entre a aplicação Python e a " +"camada C." #: ../../library/struct.rst:29 msgid "" @@ -64,6 +60,14 @@ msgid "" "for defining byte ordering and padding between elements. See :ref:`struct-" "alignment` for details." msgstr "" +"Quando nenhum caractere de prefixo é fornecido, o modo nativo é o padrão. " +"Ele empacota ou descompacta dados com base na plataforma e no compilador nos " +"quais o interpretador Python foi construído. O resultado do empacotamento de " +"uma dada estrutura C inclui bytes de preenchimento que mantêm o alinhamento " +"adequado para os tipos C envolvidos; similarmente, o alinhamento é levado em " +"conta ao desempacotar. Em contraste, ao comunicar dados entre fontes " +"externas, o programador é responsável por definir a ordenação de bytes e o " +"preenchimento entre os elementos. Veja :ref:`struct-alignment` para detalhes." #: ../../library/struct.rst:39 msgid "" @@ -75,20 +79,29 @@ msgid "" "implement the buffer protocol, so that they can be read/filled without " "additional copying from a :class:`bytes` object." msgstr "" +"Várias funções :mod:`struct` (e métodos de :class:`Struct`) recebem um " +"argumento *buffer*. Isso se refere a objetos que implementam :ref:" +"`bufferobjects` e fornecem um buffer legível ou de leitura-gravação. Os " +"tipos mais comuns usados para esse propósito são :class:`bytes` e :class:" +"`bytearray`, mas muitos outros tipos que podem ser vistos como uma matriz de " +"bytes implementam o protocolo de buffer, para que possam ser lidos/" +"preenchidos sem cópia adicional de um objeto :class:`bytes`." #: ../../library/struct.rst:48 msgid "Functions and Exceptions" -msgstr "Funções e Exceções" +msgstr "Funções e exceções" #: ../../library/struct.rst:50 msgid "The module defines the following exception and functions:" -msgstr "" +msgstr "O módulo define as seguintes exceções e funções:" #: ../../library/struct.rst:55 msgid "" "Exception raised on various occasions; argument is a string describing what " "is wrong." msgstr "" +"Exceção levantada em várias ocasiões; argumento é uma string que descreve o " +"que está errado." #: ../../library/struct.rst:61 msgid "" @@ -344,7 +357,7 @@ msgstr "Tipo em C" #: ../../library/struct.rst:224 msgid "Python type" -msgstr "Tipo Python" +msgstr "Tipo em Python" #: ../../library/struct.rst:224 msgid "Standard size" @@ -506,7 +519,7 @@ msgstr "``q``" #: ../../library/struct.rst:248 msgid ":c:expr:`long long`" -msgstr "" +msgstr ":c:expr:`long long`" #: ../../library/struct.rst:248 ../../library/struct.rst:250 #: ../../library/struct.rst:261 @@ -519,7 +532,7 @@ msgstr "``Q``" #: ../../library/struct.rst:250 msgid ":c:expr:`unsigned long long`" -msgstr "" +msgstr ":c:expr:`unsigned long long`" #: ../../library/struct.rst:253 msgid "``n``" @@ -552,7 +565,7 @@ msgstr "\\(6)" #: ../../library/struct.rst:257 ../../library/struct.rst:259 #: ../../library/struct.rst:261 msgid "float" -msgstr "float" +msgstr "ponto flutuante" #: ../../library/struct.rst:257 ../../library/struct.rst:259 #: ../../library/struct.rst:261 @@ -622,8 +635,7 @@ msgstr "" #: ../../library/struct.rst:282 msgid "" "The ``'?'`` conversion code corresponds to the :c:expr:`_Bool` type defined " -"by C99. If this type is not available, it is simulated using a :c:expr:" -"`char`. In standard mode, it is always represented by one byte." +"by C standards since C99. In standard mode, it is represented by one byte." msgstr "" #: ../../library/struct.rst:287 @@ -758,21 +770,59 @@ msgid "" "ordering::" msgstr "" +#: ../../library/struct.rst:390 +msgid "" +">>> from struct import *\n" +">>> pack(\">bhl\", 1, 2, 3)\n" +"b'\\x01\\x00\\x02\\x00\\x00\\x00\\x03'\n" +">>> unpack('>bhl', b'\\x01\\x00\\x02\\x00\\x00\\x00\\x03')\n" +"(1, 2, 3)\n" +">>> calcsize('>bhl')\n" +"7" +msgstr "" + #: ../../library/struct.rst:398 msgid "Attempt to pack an integer which is too large for the defined field::" msgstr "" +#: ../../library/struct.rst:400 +msgid "" +">>> pack(\">h\", 99999)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"struct.error: 'h' format requires -32768 <= number <= 32767" +msgstr "" + #: ../../library/struct.rst:405 msgid "" "Demonstrate the difference between ``'s'`` and ``'c'`` format characters::" msgstr "" +#: ../../library/struct.rst:408 +msgid "" +">>> pack(\"@ccc\", b'1', b'2', b'3')\n" +"b'123'\n" +">>> pack(\"@3s\", b'123')\n" +"b'123'" +msgstr "" + #: ../../library/struct.rst:413 msgid "" "Unpacked fields can be named by assigning them to variables or by wrapping " "the result in a named tuple::" msgstr "" +#: ../../library/struct.rst:416 +msgid "" +">>> record = b'raymond \\x32\\x12\\x08\\x01\\x08'\n" +">>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)\n" +"\n" +">>> from collections import namedtuple\n" +">>> Student = namedtuple('Student', 'name serialnum school gradelevel')\n" +">>> Student._make(unpack('<10sHHb', record))\n" +"Student(name=b'raymond ', serialnum=4658, school=264, gradelevel=8)" +msgstr "" + #: ../../library/struct.rst:424 msgid "" "The ordering of format characters may have an impact on size in native mode " @@ -783,12 +833,30 @@ msgid "" "a little endian machine::" msgstr "" +#: ../../library/struct.rst:432 +msgid "" +">>> pack('@ci', b'#', 0x12131415)\n" +"b'#\\x00\\x00\\x00\\x15\\x14\\x13\\x12'\n" +">>> pack('@ic', 0x12131415, b'#')\n" +"b'\\x15\\x14\\x13\\x12#'\n" +">>> calcsize('@ci')\n" +"8\n" +">>> calcsize('@ic')\n" +"5" +msgstr "" + #: ../../library/struct.rst:441 msgid "" "The following format ``'llh0l'`` results in two pad bytes being added at the " "end, assuming the platform's longs are aligned on 4-byte boundaries::" msgstr "" +#: ../../library/struct.rst:444 +msgid "" +">>> pack('@llh0l', 1, 2, 3)\n" +"b'\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x02\\x00\\x03\\x00\\x00'" +msgstr "" + #: ../../library/struct.rst:450 msgid "Module :mod:`array`" msgstr "" @@ -847,6 +915,14 @@ msgid "" "Consider these two simple examples (on a 64-bit, little-endian machine)::" msgstr "" +#: ../../library/struct.rst:489 +msgid "" +">>> calcsize('@lhl')\n" +"24\n" +">>> calcsize('@llh')\n" +"18" +msgstr "" + #: ../../library/struct.rst:494 msgid "" "Data is not padded to an 8-byte boundary at the end of the second format " @@ -854,6 +930,12 @@ msgid "" "that problem::" msgstr "" +#: ../../library/struct.rst:498 +msgid "" +">>> calcsize('@llh0l')\n" +"24" +msgstr "" + #: ../../library/struct.rst:501 msgid "" "The ``'x'`` format code can be used to specify the repeat, but for native " @@ -884,6 +966,24 @@ msgid "" "from the previous section, we have::" msgstr "" +#: ../../library/struct.rst:525 +msgid "" +">>> calcsize('>> pack('>> calcsize('@llh')\n" +"18\n" +">>> pack('@llh', 1, 2, 3) == pack('>> calcsize('>> calcsize('@llh0l')\n" +"24\n" +">>> pack('@llh0l', 1, 2, 3) == pack('>> calcsize('>> calcsize('@llh0l')\n" +"12\n" +">>> pack('@llh0l', 1, 2, 3) == pack(', YEAR. # # Translators: -# Leticia Portella , 2021 -# Vinicius Gubiani Ferreira , 2021 -# Raphael Mendonça, 2021 -# Marco Rougeth , 2021 -# Misael borges , 2021 -# i17obot , 2021 -# Augusta Carla Klug , 2021 -# Hildeberto Abreu Magalhães , 2022 -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:14+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-05-08 03:57+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/subprocess.rst:2 msgid ":mod:`!subprocess` --- Subprocess management" -msgstr "" +msgstr ":mod:`!subprocess` --- Gerenciamento de subprocessos" #: ../../library/subprocess.rst:10 msgid "**Source code:** :source:`Lib/subprocess.py`" @@ -50,6 +41,14 @@ msgstr "" "aos seus canais de entrada/saída/erro e obtenha seus códigos de retorno. " "Este módulo pretende substituir vários módulos e funções mais antigos::" +#: ../../library/subprocess.rst:18 +msgid "" +"os.system\n" +"os.spawn*" +msgstr "" +"os.system\n" +"os.spawn*" + #: ../../library/subprocess.rst:21 msgid "" "Information about how the :mod:`subprocess` module can be used to replace " @@ -62,21 +61,21 @@ msgstr "" msgid ":pep:`324` -- PEP proposing the subprocess module" msgstr ":pep:`324` -- PEP propondo o módulo subprocess" -#: ../../includes/wasm-ios-notavail.rst:3 -msgid ":ref:`Availability `: not WASI, not iOS." -msgstr ":ref:`Disponibilidade `: não WASI, não iOS." +#: ../../library/subprocess.rst:598 ../../library/subprocess.rst:605 +#: ../../library/subprocess.rst:615 ../../library/subprocess.rst:624 +#: ../../library/subprocess.rst:633 ../../library/subprocess.rst:639 +#: ../../library/subprocess.rst:1560 ../../library/subprocess.rst:1582 +#: ../../includes/wasm-mobile-notavail.rst:3 +msgid "Availability" +msgstr "Disponibilidade" -#: ../../includes/wasm-ios-notavail.rst:5 +#: ../../includes/wasm-mobile-notavail.rst:5 msgid "" -"This module does not work or is not available on WebAssembly platforms, or " -"on iOS. See :ref:`wasm-availability` for more information on WASM " -"availability; see :ref:`iOS-availability` for more information on iOS " -"availability." +"This module is not supported on :ref:`mobile platforms ` or :ref:`WebAssembly platforms `." msgstr "" -"Este módulo não funciona ou não está disponível nas plataformas WebAssembly " -"ou iOS. Veja :ref:`wasm-availability` para mais informações sobre a " -"disponibilidade no WASM; veja :ref:`iOS-availability` para mais informações " -"sobre a disponibilidade no iOS." +"Este módulo não tem suporte em :ref:`plataformas móveis ` ou :ref:`plataformas WebAssembly `." #: ../../library/subprocess.rst:31 msgid "Using the :mod:`subprocess` Module" @@ -127,6 +126,13 @@ msgid "" "`~subprocess.PIPE` and *stderr* to :data:`~subprocess.STDOUT`, instead of " "using *capture_output*." msgstr "" +"Se *capture_output* for verdadeiro, *stdout* e *stderr* serão capturados. " +"Quando usado, o objeto interno :class:`Popen` é automaticamente criado com " +"*stdout* and *stderr* definidos como :data:`~subprocess.PIPE`. Os argumentos " +"*stdout * e *stderr* não podem ser fornecidos ao mesmo tempo que " +"*capture_output*. Se você deseja capturar e combinar ambos os fluxos em um, " +"defina *stdout* para :data:`~subprocess.PIPE` e *stderr* para :data:" +"`~subprocess.STDOUT`, ao invés de usar *capture_output*." #: ../../library/subprocess.rst:62 msgid "" @@ -181,7 +187,7 @@ msgid "" "backwards compatibility. By default, file objects are opened in binary mode." msgstr "" "Se *encoding* ou *errors* forem especificados, ou *text* for verdadeiro, os " -"objetos de arquivo para stdin, stdout e stderr são abertos em modo de texto " +"objetos arquivo para stdin, stdout e stderr são abertos em modo de texto " "usando a *encoding* e *errors* especificados ou o :class:`io.TextIOWrapper` " "padrão. O argumento *universal_newlines* é equivalente a *text* e é " "fornecido para compatibilidade com versões anteriores. Por padrão, os " @@ -207,6 +213,34 @@ msgstr "" msgid "Examples::" msgstr "Exemplos::" +#: ../../library/subprocess.rst:97 +msgid "" +">>> subprocess.run([\"ls\", \"-l\"]) # doesn't capture output\n" +"CompletedProcess(args=['ls', '-l'], returncode=0)\n" +"\n" +">>> subprocess.run(\"exit 1\", shell=True, check=True)\n" +"Traceback (most recent call last):\n" +" ...\n" +"subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit " +"status 1\n" +"\n" +">>> subprocess.run([\"ls\", \"-l\", \"/dev/null\"], capture_output=True)\n" +"CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,\n" +"stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\\n', stderr=b'')" +msgstr "" +">>> subprocess.run([\"ls\", \"-l\"]) # não captura a saída\n" +"CompletedProcess(args=['ls', '-l'], returncode=0)\n" +"\n" +">>> subprocess.run(\"exit 1\", shell=True, check=True)\n" +"Traceback (most recent call last):\n" +" ...\n" +"subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit " +"status 1\n" +"\n" +">>> subprocess.run([\"ls\", \"-l\", \"/dev/null\"], capture_output=True)\n" +"CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,\n" +"stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\\n', stderr=b'')" + #: ../../library/subprocess.rst:113 msgid "Added *encoding* and *errors* parameters" msgstr "Adicionados os parâmetros *encoding* e *errors*." @@ -480,7 +514,7 @@ msgid "" "specified in the call or the defaults for :class:`io.TextIOWrapper`." msgstr "" "Se *encoding* ou *errors* forem especificados, ou *text* (também conhecido " -"como *universal_newlines*) for verdadeiro, os objetos de arquivo *stdin*, " +"como *universal_newlines*) for verdadeiro, os objetos arquivo *stdin*, " "*stdout* e *stderr* serão abertos em modo de texto usando a *encoding* e " "*errors* especificados na chamada ou os valores padrão para :class:`io." "TextIOWrapper`." @@ -512,7 +546,7 @@ msgstr "" #: ../../library/subprocess.rst:314 ../../library/subprocess.rst:1569 #: ../../library/subprocess.rst:1587 msgid "Added the *encoding* and *errors* parameters." -msgstr "" +msgstr "Adicionados os parâmetros *encoding* e *errors*." #: ../../library/subprocess.rst:317 msgid "Added the *text* parameter as an alias for *universal_newlines*." @@ -631,6 +665,11 @@ msgid "" "launch the current Python interpreter again, and use the ``-m`` command-line " "format to launch an installed module." msgstr "" +"Para confiabilidade máxima, use um caminho totalmente qualificado para o " +"executável. Para procurar um nome não qualificado no :envvar:`PATH`, use :" +"meth:`shutil.which`. Em todas as plataformas, passar :data:`sys.executable` " +"é a maneira recomendada de relançar o interpretador Python atual, e usar o " +"formato de linha de comando ``-m`` para iniciar um módulo instalado." #: ../../library/subprocess.rst:389 msgid "" @@ -645,6 +684,15 @@ msgid "" "the ``PATH`` environment variable. Using a full path avoids all of these " "variations." msgstr "" +"Resolver o caminho do executável (ou o primeiro item de *args*) depende da " +"plataforma. Para POSIX, veja :meth:`os.execvpe`, e note que ao resolver ou " +"procurar o caminho do executável, *cwd* substitui o diretório de trabalho " +"atual e *env* pode substituir a variável de ambiente ``PATH``. Para Windows, " +"veja a documentação dos parâmetros ``lpApplicationName`` e ``lpCommandLine`` " +"do WinAPI ``CreateProcess``, e note que ao resolver ou procurar o caminho do " +"executável com ``shell=False``, *cwd* não substitui o diretório de trabalho " +"atual e *env* não pode substituir a variável de ambiente ``PATH``. Usar um " +"caminho completo evita todas essas variações." #: ../../library/subprocess.rst:400 msgid "" @@ -654,6 +702,10 @@ msgstr "" "Um exemplo de passagem de alguns argumentos para um programa externo como " "uma sequência é::" +#: ../../library/subprocess.rst:403 +msgid "Popen([\"/usr/bin/git\", \"commit\", \"-m\", \"Fixes a bug.\"])" +msgstr "Popen([\"/usr/bin/git\", \"commit\", \"-m\", \"Fixes a bug.\"])" + #: ../../library/subprocess.rst:405 msgid "" "On POSIX, if *args* is a string, the string is interpreted as the name or " @@ -674,6 +726,28 @@ msgstr "" "argumentos, especialmente em casos complexos. :meth:`shlex.split` pode " "ilustrar como determinar a tokenização correta para *args*::" +#: ../../library/subprocess.rst:415 +msgid "" +">>> import shlex, subprocess\n" +">>> command_line = input()\n" +"/bin/vikings -input eggs.txt -output \"spam spam.txt\" -cmd \"echo " +"'$MONEY'\"\n" +">>> args = shlex.split(command_line)\n" +">>> print(args)\n" +"['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', " +"\"echo '$MONEY'\"]\n" +">>> p = subprocess.Popen(args) # Success!" +msgstr "" +">>> import shlex, subprocess\n" +">>> command_line = input()\n" +"/bin/vikings -input eggs.txt -output \"spam spam.txt\" -cmd \"echo " +"'$MONEY'\"\n" +">>> args = shlex.split(command_line)\n" +">>> print(args)\n" +"['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', " +"\"echo '$MONEY'\"]\n" +">>> p = subprocess.Popen(args) # Successo!" + #: ../../library/subprocess.rst:423 msgid "" "Note in particular that options (such as *-input*) and arguments (such as " @@ -712,6 +786,9 @@ msgid "" "*args* parameter accepts a :term:`path-like object` if *shell* is ``False`` " "and a sequence containing bytes and path-like objects on Windows." msgstr "" +"O parâmetro *args* aceita um :term:`objeto caminho ou similar` se *shell* " +"for ``False`` e uma sequência contendo bytes e objetos caminho ou similar no " +"Windows." #: ../../library/subprocess.rst:442 msgid "" @@ -719,6 +796,9 @@ msgid "" "the shell as the program to execute. If *shell* is ``True``, it is " "recommended to pass *args* as a string rather than as a sequence." msgstr "" +"O argumento *shell* (que por padrão é ``False``) especifica se deve usar o " +"*shell* como o programa a ser executado. Se *shell* for ``True``, é " +"recomendado passar *args* como uma string em vez de uma sequência." #: ../../library/subprocess.rst:446 msgid "" @@ -731,6 +811,18 @@ msgid "" "be treated as additional arguments to the shell itself. That is to say, :" "class:`Popen` does the equivalent of::" msgstr "" +"Em POSIX com ``shell=True``, o *shell* padrão é :file:`/bin/sh`. Se *args* " +"for uma string, a *string* especifica o comando a ser executado através do " +"*shell*. Isso significa que a *string* deve ser formatada exatamente como " +"seria ao ser digitada no prompt do *shell*. Isso inclui, por exemplo, citar " +"ou escapar com contrabarra nomes de arquivos que contenham espaços. Se " +"*args* for uma sequência, o primeiro item especifica a *string* do comando, " +"e quaisquer itens adicionais serão tratados como argumentos adicionais para " +"o próprio *shell*. Ou seja, :class:`Popen` faz o equivalente a:" + +#: ../../library/subprocess.rst:455 +msgid "Popen(['/bin/sh', '-c', args[0], args[1], ...])" +msgstr "Popen(['/bin/sh', '-c', args[0], args[1], ...])" #: ../../library/subprocess.rst:457 msgid "" @@ -740,34 +832,50 @@ msgid "" "into the shell (e.g. :command:`dir` or :command:`copy`). You do not need " "``shell=True`` to run a batch file or console-based executable." msgstr "" +"No Windows com ``shell=True``, a variável de ambiente :envvar:`COMSPEC` " +"especifica o shell padrão. A única vez que você precisa especificar " +"``shell=True`` no Windows é quando o comando que você deseja executar é " +"construído no shell (por exemplo, :command:`dir` ou :command:`copy`). Você " +"não precisa de ``shell=True`` para executar um arquivo em lote ou executável " +"baseado em console." #: ../../library/subprocess.rst:467 msgid "" "*bufsize* will be supplied as the corresponding argument to the :func:`open` " "function when creating the stdin/stdout/stderr pipe file objects:" msgstr "" +"*bufsize* será fornecido como o argumento correspondente à função :func:" +"`open` ao criar os objetos arquivo de encadeamento stdin/stdout/stderr:" #: ../../library/subprocess.rst:471 msgid "" "``0`` means unbuffered (read and write are one system call and can return " "short)" msgstr "" +"``0`` significa sem buffer (leitura e gravação são uma chamada de sistema e " +"podem retornar curto)" #: ../../library/subprocess.rst:473 msgid "" "``1`` means line buffered (only usable if ``text=True`` or " "``universal_newlines=True``)" msgstr "" +"``1`` significa buffer de linha (utilizável somente se ``text=True`` ou " +"``universal_newlines=True``)" #: ../../library/subprocess.rst:475 msgid "any other positive value means use a buffer of approximately that size" msgstr "" +"qualquer outro valor positivo significa usar um buffer de aproximadamente " +"esse tamanho" #: ../../library/subprocess.rst:477 msgid "" "negative bufsize (the default) means the system default of io." "DEFAULT_BUFFER_SIZE will be used." msgstr "" +"bufsize negativo (o padrão) significa que o padrão do sistema io." +"DEFAULT_BUFFER_SIZE será usado." #: ../../library/subprocess.rst:480 msgid "" @@ -777,6 +885,12 @@ msgid "" "short reads. This was unintentional and did not match the behavior of " "Python 2 as most code expected." msgstr "" +"*bufsize* agora assume o padrão -1 para habilitar o buffer por padrão para " +"corresponder ao comportamento que a maioria dos códigos espera. Em versões " +"anteriores ao Python 3.2.4 e 3.3.1, ele assumia incorretamente o padrão " +"``0``, que não tinha buffer e permitia leituras curtas. Isso não foi " +"intencional e não correspondeu ao comportamento do Python 2, como a maioria " +"dos códigos esperava." #: ../../library/subprocess.rst:487 msgid "" @@ -790,16 +904,29 @@ msgid "" "POSIX the *executable* argument specifies a replacement shell for the " "default :file:`/bin/sh`." msgstr "" +"O argumento *executable* especifica um programa de substituição para " +"executar. Ele é muito raramente necessário. Quando ``shell=False``, " +"*executable* substitui o programa a ser executado especificado por *args*. " +"No entanto, o *args* original ainda é passado para o programa. A maioria dos " +"programas trata o programa especificado por *args* como o nome do comando, " +"que pode então ser diferente do programa realmente executado. No POSIX, o " +"nome *args* se torna o nome de exibição para o executável em utilitários " +"como :program:`ps`. Se ``shell=True``, no POSIX o argumento *executable* " +"especifica um shell de substituição para o padrão :file:`/bin/sh`." #: ../../library/subprocess.rst:497 msgid "*executable* parameter accepts a :term:`path-like object` on POSIX." msgstr "" +"O parâmetro *executable* aceita um :term:`objeto caminho ou similar` no " +"POSIX." #: ../../library/subprocess.rst:500 msgid "" "*executable* parameter accepts a bytes and :term:`path-like object` on " "Windows." msgstr "" +"O parâmetro *executable* aceita um :term:`objeto caminho ou similar` bytes " +"no Windows." #: ../../library/subprocess.rst:512 msgid "" @@ -814,18 +941,33 @@ msgid "" "which indicates that the stderr data from the applications should be " "captured into the same file handle as for *stdout*." msgstr "" +"*stdin*, *stdout* e *stderr* especificam a entrada padrão, a saída padrão e " +"a saída de erro do programa executado, respectivamente. Os valores válidos " +"são ``None``, :data:`PIPE`, :data:`DEVNULL`, um descritor de arquivo " +"existente (um número inteiro positivo) e um :term:`objeto arquivo` existente " +"com um descritor de arquivo válido. Com as configurações padrão de ``None``, " +"nenhum redirecionamento ocorrerá. :data:`PIPE` indica que um novo canal para " +"o filho deve ser criado. :data:`DEVNULL` indica que o arquivo especial :data:" +"`os.devnull` será usado. Além disso, *stderr* pode ser :data:`STDOUT`, o que " +"indica que os dados de stderr da aplicação devem ser capturados no mesmo " +"identificador de arquivo que para *stdout*." #: ../../library/subprocess.rst:523 msgid "" "If *preexec_fn* is set to a callable object, this object will be called in " "the child process just before the child is executed. (POSIX only)" msgstr "" +"Se *preexec_fn* for definido como um objeto chamável, esse objeto será " +"chamado no processo filho pouco antes de o filho ser executado. (Somente " +"POSIX)" #: ../../library/subprocess.rst:529 msgid "" "The *preexec_fn* parameter is NOT SAFE to use in the presence of threads in " "your application. The child process could deadlock before exec is called." msgstr "" +"O parâmetro *preexec_fn* NÃO É SEGURO para uso na presença de threads em sua " +"aplicação. O processo filho pode travar antes de exec ser chamado." #: ../../library/subprocess.rst:535 msgid "" @@ -834,6 +976,10 @@ msgid "" "*process_group* parameters should take the place of code using *preexec_fn* " "to call :func:`os.setsid` or :func:`os.setpgid` in the child." msgstr "" +"Se você precisar modificar o ambiente para o filho, use o parâmetro *env* em " +"vez de fazer isso em um *preexec_fn*. Os parâmetros *start_new_session* e " +"*process_group* devem tomar o lugar do código usando *preexec_fn* para " +"chamar :func:`os.setsid` ou :func:`os.setpgid` no filho." #: ../../library/subprocess.rst:542 msgid "" @@ -842,6 +988,10 @@ msgid "" "restriction may affect applications that are deployed in mod_wsgi, uWSGI, " "and other embedded environments." msgstr "" +"O parâmetro *preexec_fn* não é mais suportado em subinterpretadores. O uso " +"do parâmetro em um subinterpretador levanta :exc:`RuntimeError`. A nova " +"restrição pode afetar aplicações que são implantadas em mod_wsgi, uWSGI e " +"outros ambientes incorporados." #: ../../library/subprocess.rst:547 msgid "" @@ -920,12 +1070,6 @@ msgid "" "the child process prior to the execution of the subprocess." msgstr "" -#: ../../library/subprocess.rst:598 ../../library/subprocess.rst:605 -#: ../../library/subprocess.rst:615 ../../library/subprocess.rst:624 -#: ../../library/subprocess.rst:633 ../../library/subprocess.rst:639 -msgid ":ref:`Availability `: POSIX" -msgstr ":ref:`Disponibilidade `: POSIX" - #: ../../library/subprocess.rst:599 msgid "*start_new_session* was added." msgstr "*start_new_session* foi adicionado." @@ -945,7 +1089,7 @@ msgstr "" msgid "" "If *group* is not ``None``, the setregid() system call will be made in the " "child process prior to the execution of the subprocess. If the provided " -"value is a string, it will be looked up via :func:`grp.getgrnam()` and the " +"value is a string, it will be looked up via :func:`grp.getgrnam` and the " "value in ``gr_gid`` will be used. If the value is an integer, it will be " "passed verbatim. (POSIX only)" msgstr "" @@ -954,7 +1098,7 @@ msgstr "" msgid "" "If *extra_groups* is not ``None``, the setgroups() system call will be made " "in the child process prior to the execution of the subprocess. Strings " -"provided in *extra_groups* will be looked up via :func:`grp.getgrnam()` and " +"provided in *extra_groups* will be looked up via :func:`grp.getgrnam` and " "the values in ``gr_gid`` will be used. Integer values will be passed " "verbatim. (POSIX only)" msgstr "" @@ -963,7 +1107,7 @@ msgstr "" msgid "" "If *user* is not ``None``, the setreuid() system call will be made in the " "child process prior to the execution of the subprocess. If the provided " -"value is a string, it will be looked up via :func:`pwd.getpwnam()` and the " +"value is a string, it will be looked up via :func:`pwd.getpwnam` and the " "value in ``pw_uid`` will be used. If the value is an integer, it will be " "passed verbatim. (POSIX only)" msgstr "" @@ -1086,6 +1230,12 @@ msgid "" "waited for. ::" msgstr "" +#: ../../library/subprocess.rst:698 +msgid "" +"with Popen([\"ifconfig\"], stdout=PIPE) as proc:\n" +" log.write(proc.stdout.read())" +msgstr "" + #: ../../library/subprocess.rst:701 ../../library/subprocess.rst:703 msgid "" "Popen and the other functions in this module that use it raise an :ref:" @@ -1287,6 +1437,16 @@ msgid "" "and finish communication::" msgstr "" +#: ../../library/subprocess.rst:840 +msgid "" +"proc = subprocess.Popen(...)\n" +"try:\n" +" outs, errs = proc.communicate(timeout=15)\n" +"except TimeoutExpired:\n" +" proc.kill()\n" +" outs, errs = proc.communicate()" +msgstr "" + #: ../../library/subprocess.rst:849 msgid "" "The data read is buffered in memory, so do not use this method if the data " @@ -1425,6 +1585,13 @@ msgid "" "are used when the process creates a window. ::" msgstr "" +#: ../../library/subprocess.rst:971 +msgid "" +"si = subprocess.STARTUPINFO()\n" +"si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess." +"STARTF_USESHOWWINDOW" +msgstr "" + #: ../../library/subprocess.rst:976 msgid "" "If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute is " @@ -1664,6 +1831,10 @@ msgid "" "Code needing to capture stdout or stderr should use :func:`run` instead::" msgstr "" +#: ../../library/subprocess.rst:1193 +msgid "run(...).returncode" +msgstr "" + #: ../../library/subprocess.rst:1195 ../../library/subprocess.rst:1235 msgid "To suppress stdout or stderr, supply a value of :data:`DEVNULL`." msgstr "" @@ -1692,6 +1863,10 @@ msgid "" "to start the process it will propagate the exception that was raised." msgstr "" +#: ../../library/subprocess.rst:1233 +msgid "run(..., check=True)" +msgstr "" + #: ../../library/subprocess.rst:1266 msgid "Run command with arguments and return its output." msgstr "Executa o comando com argumentos e retorna sua saída." @@ -1708,6 +1883,10 @@ msgstr "" msgid "This is equivalent to::" msgstr "Isso equivale a::" +#: ../../library/subprocess.rst:1275 +msgid "run(..., check=True, stdout=PIPE).stdout" +msgstr "" + #: ../../library/subprocess.rst:1277 msgid "" "The arguments shown above are merely some common ones. The full function " @@ -1738,6 +1917,15 @@ msgid "" "STDOUT``::" msgstr "" +#: ../../library/subprocess.rst:1295 +msgid "" +">>> subprocess.check_output(\n" +"... \"ls non_existent_file; exit 0\",\n" +"... stderr=subprocess.STDOUT,\n" +"... shell=True)\n" +"'ls: non_existent_file: No such file or directory\\n'" +msgstr "" + #: ../../library/subprocess.rst:1306 msgid "Support for the *input* keyword argument was added." msgstr "" @@ -1781,15 +1969,35 @@ msgstr "" msgid "Replacing :program:`/bin/sh` shell command substitution" msgstr "" +#: ../../library/subprocess.rst:1349 +msgid "output=$(mycmd myarg)" +msgstr "" + #: ../../library/subprocess.rst:1353 ../../library/subprocess.rst:1364 #: ../../library/subprocess.rst:1381 msgid "becomes::" msgstr "torna-se::" +#: ../../library/subprocess.rst:1355 +msgid "output = check_output([\"mycmd\", \"myarg\"])" +msgstr "" + #: ../../library/subprocess.rst:1358 msgid "Replacing shell pipeline" msgstr "" +#: ../../library/subprocess.rst:1360 ../../library/subprocess.rst:1377 +msgid "output=$(dmesg | grep hda)" +msgstr "" + +#: ../../library/subprocess.rst:1366 +msgid "" +"p1 = Popen([\"dmesg\"], stdout=PIPE)\n" +"p2 = Popen([\"grep\", \"hda\"], stdin=p1.stdout, stdout=PIPE)\n" +"p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.\n" +"output = p2.communicate()[0]" +msgstr "" + #: ../../library/subprocess.rst:1371 msgid "" "The ``p1.stdout.close()`` call after starting the p2 is important in order " @@ -1802,10 +2010,21 @@ msgid "" "be used directly:" msgstr "" +#: ../../library/subprocess.rst:1383 +msgid "output = check_output(\"dmesg | grep hda\", shell=True)" +msgstr "" + #: ../../library/subprocess.rst:1387 msgid "Replacing :func:`os.system`" msgstr "Substituindo :func:`os.system`" +#: ../../library/subprocess.rst:1391 +msgid "" +"sts = os.system(\"mycmd\" + \" myarg\")\n" +"# becomes\n" +"retcode = call(\"mycmd\" + \" myarg\", shell=True)" +msgstr "" + #: ../../library/subprocess.rst:1395 msgid "Notes:" msgstr "Notas:" @@ -1831,6 +2050,19 @@ msgstr "" msgid "A more realistic example would look like this::" msgstr "Um exemplo mais realista ficaria assim::" +#: ../../library/subprocess.rst:1407 +msgid "" +"try:\n" +" retcode = call(\"mycmd\" + \" myarg\", shell=True)\n" +" if retcode < 0:\n" +" print(\"Child was terminated by signal\", -retcode, file=sys." +"stderr)\n" +" else:\n" +" print(\"Child returned\", retcode, file=sys.stderr)\n" +"except OSError as e:\n" +" print(\"Execution failed:\", e, file=sys.stderr)" +msgstr "" + #: ../../library/subprocess.rst:1418 msgid "Replacing the :func:`os.spawn ` family" msgstr "" @@ -1839,26 +2071,100 @@ msgstr "" msgid "P_NOWAIT example::" msgstr "Exemplo P_NOWAIT::" +#: ../../library/subprocess.rst:1422 +msgid "" +"pid = os.spawnlp(os.P_NOWAIT, \"/bin/mycmd\", \"mycmd\", \"myarg\")\n" +"==>\n" +"pid = Popen([\"/bin/mycmd\", \"myarg\"]).pid" +msgstr "" + #: ../../library/subprocess.rst:1426 msgid "P_WAIT example::" msgstr "Exemplo P_WAIT::" +#: ../../library/subprocess.rst:1428 +msgid "" +"retcode = os.spawnlp(os.P_WAIT, \"/bin/mycmd\", \"mycmd\", \"myarg\")\n" +"==>\n" +"retcode = call([\"/bin/mycmd\", \"myarg\"])" +msgstr "" + #: ../../library/subprocess.rst:1432 msgid "Vector example::" msgstr "Exemplo de vetor::" +#: ../../library/subprocess.rst:1434 +msgid "" +"os.spawnvp(os.P_NOWAIT, path, args)\n" +"==>\n" +"Popen([path] + args[1:])" +msgstr "" + #: ../../library/subprocess.rst:1438 msgid "Environment example::" msgstr "Exemplo de ambiente::" +#: ../../library/subprocess.rst:1440 +msgid "" +"os.spawnlpe(os.P_NOWAIT, \"/bin/mycmd\", \"mycmd\", \"myarg\", env)\n" +"==>\n" +"Popen([\"/bin/mycmd\", \"myarg\"], env={\"PATH\": \"/usr/bin\"})" +msgstr "" + #: ../../library/subprocess.rst:1447 msgid "Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3`" msgstr "" +#: ../../library/subprocess.rst:1451 +msgid "" +"(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)\n" +"==>\n" +"p = Popen(cmd, shell=True, bufsize=bufsize,\n" +" stdin=PIPE, stdout=PIPE, close_fds=True)\n" +"(child_stdin, child_stdout) = (p.stdin, p.stdout)" +msgstr "" + +#: ../../library/subprocess.rst:1459 +msgid "" +"(child_stdin,\n" +" child_stdout,\n" +" child_stderr) = os.popen3(cmd, mode, bufsize)\n" +"==>\n" +"p = Popen(cmd, shell=True, bufsize=bufsize,\n" +" stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)\n" +"(child_stdin,\n" +" child_stdout,\n" +" child_stderr) = (p.stdin, p.stdout, p.stderr)" +msgstr "" + +#: ../../library/subprocess.rst:1471 +msgid "" +"(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)\n" +"==>\n" +"p = Popen(cmd, shell=True, bufsize=bufsize,\n" +" stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)\n" +"(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)" +msgstr "" + #: ../../library/subprocess.rst:1477 msgid "Return code handling translates as follows::" msgstr "" +#: ../../library/subprocess.rst:1479 +msgid "" +"pipe = os.popen(cmd, 'w')\n" +"...\n" +"rc = pipe.close()\n" +"if rc is not None and rc >> 8:\n" +" print(\"There were some errors\")\n" +"==>\n" +"process = Popen(cmd, stdin=PIPE)\n" +"...\n" +"process.stdin.close()\n" +"if process.wait() != 0:\n" +" print(\"There were some errors\")" +msgstr "" + #: ../../library/subprocess.rst:1493 msgid "Replacing functions from the :mod:`!popen2` module" msgstr "" @@ -1869,6 +2175,25 @@ msgid "" "through /bin/sh. If it is a list, the command is directly executed." msgstr "" +#: ../../library/subprocess.rst:1502 +msgid "" +"(child_stdout, child_stdin) = popen2.popen2(\"somestring\", bufsize, mode)\n" +"==>\n" +"p = Popen(\"somestring\", shell=True, bufsize=bufsize,\n" +" stdin=PIPE, stdout=PIPE, close_fds=True)\n" +"(child_stdout, child_stdin) = (p.stdout, p.stdin)" +msgstr "" + +#: ../../library/subprocess.rst:1510 +msgid "" +"(child_stdout, child_stdin) = popen2.popen2([\"mycmd\", \"myarg\"], bufsize, " +"mode)\n" +"==>\n" +"p = Popen([\"mycmd\", \"myarg\"], bufsize=bufsize,\n" +" stdin=PIPE, stdout=PIPE, close_fds=True)\n" +"(child_stdout, child_stdin) = (p.stdout, p.stdin)" +msgstr "" + #: ../../library/subprocess.rst:1516 msgid "" ":class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as :class:" @@ -1924,9 +2249,17 @@ msgid "" "command can be interpreted as the return code of subprocess. Example::" msgstr "" -#: ../../library/subprocess.rst:1560 ../../library/subprocess.rst:1582 -msgid ":ref:`Availability `: Unix, Windows." -msgstr ":ref:`Disponibilidade`: Unix, Windows." +#: ../../library/subprocess.rst:1551 +msgid "" +">>> subprocess.getstatusoutput('ls /bin/ls')\n" +"(0, '/bin/ls')\n" +">>> subprocess.getstatusoutput('cat /bin/junk')\n" +"(1, 'cat: /bin/junk: No such file or directory')\n" +">>> subprocess.getstatusoutput('/bin/junk')\n" +"(127, 'sh: /bin/junk: not found')\n" +">>> subprocess.getstatusoutput('/bin/kill $$')\n" +"(-15, '')" +msgstr "" #: ../../library/subprocess.rst:1562 msgid "Windows support was added." @@ -1949,6 +2282,12 @@ msgid "" "value is a string containing the command's output. Example::" msgstr "" +#: ../../library/subprocess.rst:1579 +msgid "" +">>> subprocess.getoutput('ls /bin/ls')\n" +"'/bin/ls'" +msgstr "" + #: ../../library/subprocess.rst:1584 msgid "Windows support added" msgstr "Suporte para Windows adicionado." @@ -1958,41 +2297,68 @@ msgid "Notes" msgstr "Notas" #: ../../library/subprocess.rst:1597 +msgid "Timeout Behavior" +msgstr "" + +#: ../../library/subprocess.rst:1599 +msgid "" +"When using the ``timeout`` parameter in functions like :func:`run`, :meth:" +"`Popen.wait`, or :meth:`Popen.communicate`, users should be aware of the " +"following behaviors:" +msgstr "" + +#: ../../library/subprocess.rst:1603 +msgid "" +"**Process Creation Delay**: The initial process creation itself cannot be " +"interrupted on many platform APIs. This means that even when specifying a " +"timeout, you are not guaranteed to see a timeout exception until at least " +"after however long process creation takes." +msgstr "" + +#: ../../library/subprocess.rst:1608 +msgid "" +"**Extremely Small Timeout Values**: Setting very small timeout values (such " +"as a few milliseconds) may result in almost immediate :exc:`TimeoutExpired` " +"exceptions because process creation and system scheduling inherently require " +"time." +msgstr "" + +#: ../../library/subprocess.rst:1615 msgid "Converting an argument sequence to a string on Windows" msgstr "Converter uma sequência de argumentos em uma string no Windows" -#: ../../library/subprocess.rst:1599 +#: ../../library/subprocess.rst:1617 msgid "" "On Windows, an *args* sequence is converted to a string that can be parsed " "using the following rules (which correspond to the rules used by the MS C " "runtime):" msgstr "" -#: ../../library/subprocess.rst:1603 +#: ../../library/subprocess.rst:1621 msgid "" "Arguments are delimited by white space, which is either a space or a tab." msgstr "" -#: ../../library/subprocess.rst:1606 +#: ../../library/subprocess.rst:1624 msgid "" "A string surrounded by double quotation marks is interpreted as a single " "argument, regardless of white space contained within. A quoted string can " "be embedded in an argument." msgstr "" -#: ../../library/subprocess.rst:1611 +#: ../../library/subprocess.rst:1629 msgid "" "A double quotation mark preceded by a backslash is interpreted as a literal " "double quotation mark." msgstr "" -#: ../../library/subprocess.rst:1614 +#: ../../library/subprocess.rst:1632 msgid "" "Backslashes are interpreted literally, unless they immediately precede a " "double quotation mark." msgstr "" -#: ../../library/subprocess.rst:1617 +#: ../../library/subprocess.rst:1635 msgid "" "If backslashes immediately precede a double quotation mark, every pair of " "backslashes is interpreted as a literal backslash. If the number of " @@ -2000,33 +2366,37 @@ msgid "" "mark as described in rule 3." msgstr "" -#: ../../library/subprocess.rst:1626 +#: ../../library/subprocess.rst:1644 msgid ":mod:`shlex`" msgstr ":mod:`shlex`" -#: ../../library/subprocess.rst:1627 +#: ../../library/subprocess.rst:1645 msgid "Module which provides function to parse and escape command lines." msgstr "" -#: ../../library/subprocess.rst:1634 +#: ../../library/subprocess.rst:1652 msgid "Disabling use of ``vfork()`` or ``posix_spawn()``" msgstr "" -#: ../../library/subprocess.rst:1636 +#: ../../library/subprocess.rst:1654 msgid "" "On Linux, :mod:`subprocess` defaults to using the ``vfork()`` system call " "internally when it is safe to do so rather than ``fork()``. This greatly " "improves performance." msgstr "" -#: ../../library/subprocess.rst:1640 +#: ../../library/subprocess.rst:1658 msgid "" "If you ever encounter a presumed highly unusual situation where you need to " "prevent ``vfork()`` from being used by Python, you can set the :const:" "`subprocess._USE_VFORK` attribute to a false value." msgstr "" -#: ../../library/subprocess.rst:1648 +#: ../../library/subprocess.rst:1664 +msgid "subprocess._USE_VFORK = False # See CPython issue gh-NNNNNN." +msgstr "" + +#: ../../library/subprocess.rst:1666 msgid "" "Setting this has no impact on use of ``posix_spawn()`` which could use " "``vfork()`` internally within its libc implementation. There is a similar :" @@ -2034,7 +2404,11 @@ msgid "" "that." msgstr "" -#: ../../library/subprocess.rst:1657 +#: ../../library/subprocess.rst:1673 +msgid "subprocess._USE_POSIX_SPAWN = False # See CPython issue gh-NNNNNN." +msgstr "" + +#: ../../library/subprocess.rst:1675 msgid "" "It is safe to set these to false on any Python version. They will have no " "effect on older versions when unsupported. Do not assume the attributes are " @@ -2042,18 +2416,18 @@ msgid "" "the corresponding function will be used, only that it may be." msgstr "" -#: ../../library/subprocess.rst:1662 +#: ../../library/subprocess.rst:1680 msgid "" "Please file issues any time you have to use these private knobs with a way " "to reproduce the issue you were seeing. Link to that issue from a comment in " "your code." msgstr "" -#: ../../library/subprocess.rst:1666 +#: ../../library/subprocess.rst:1684 msgid "``_USE_POSIX_SPAWN``" msgstr "" -#: ../../library/subprocess.rst:1667 +#: ../../library/subprocess.rst:1685 msgid "``_USE_VFORK``" msgstr "" diff --git a/library/sunau.po b/library/sunau.po new file mode 100644 index 000000000..6e7a97858 --- /dev/null +++ b/library/sunau.po @@ -0,0 +1,46 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../library/sunau.rst:2 +msgid ":mod:`!sunau` --- Read and write Sun AU files" +msgstr ":mod:`!sunau` --- Lê e escreve arquivos AU da Sun" + +#: ../../library/sunau.rst:10 +msgid "" +"This module is no longer part of the Python standard library. It was :ref:" +"`removed in Python 3.13 ` after being deprecated in " +"Python 3.11. The removal was decided in :pep:`594`." +msgstr "" +"Este módulo não faz mais parte da biblioteca padrão do Python. Ele foi :ref:" +"`removido no Python 3.13 ` após ser descontinuado no " +"Python 3.11. A remoção foi decidida na :pep:`594`." + +#: ../../library/sunau.rst:14 +msgid "" +"The last version of Python that provided the :mod:`!sunau` module was " +"`Python 3.12 `_." +msgstr "" +"A última versão do Python que forneceu o módulo :mod:`!sunau` foi o `Python " +"3.12 `_." diff --git a/library/superseded.po b/library/superseded.po index 8562dc533..ddb3777d7 100644 --- a/library/superseded.po +++ b/library/superseded.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-20 00:52+0000\n" -"PO-Revision-Date: 2021-06-28 01:14+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -30,11 +29,42 @@ msgstr "Módulos substituídos" #: ../../library/superseded.rst:7 msgid "" -"The modules described in this chapter are deprecated or :term:`soft " -"deprecated` and only kept for backwards compatibility. They have been " -"superseded by other modules." +"The modules described in this chapter have been superseded by other modules " +"for most use cases, and are retained primarily to preserve backwards " +"compatibility." +msgstr "" +"Os módulos descritos neste capítulo foram substituídos por outros módulos " +"para a maioria dos casos de uso e são mantidos principalmente para preservar " +"a retrocompatibilidade." + +#: ../../library/superseded.rst:10 +msgid "" +"Modules may appear in this chapter because they only cover a limited subset " +"of a problem space, and a more generally applicable solution is available " +"elsewhere in the standard library (for example, :mod:`getopt` covers the " +"very specific task of \"mimic the C :c:func:`!getopt` API in Python\", " +"rather than the broader command line option parsing and argument parsing " +"capabilities offered by :mod:`optparse` and :mod:`argparse`)." +msgstr "" +"Os módulos podem aparecer neste capítulo porque eles cobrem apenas um " +"subconjunto limitado de um espaço de problema, e uma solução mais geralmente " +"aplicável está disponível em outro lugar na biblioteca padrão (por exemplo, :" +"mod:`getopt` cobre a tarefa muito específica de \"imitar a API C :c:func:`!" +"getopt` no Python\", em vez dos recursos mais amplos de análise de opções de " +"linha de comando e análise de argumentos oferecidos por :mod:`optparse` e :" +"mod:`argparse`)." + +#: ../../library/superseded.rst:17 +msgid "" +"Alternatively, modules may appear in this chapter because they are " +"deprecated outright, and awaiting removal in a future release, or they are :" +"term:`soft deprecated` and their use is actively discouraged in new " +"projects. With the removal of various obsolete modules through :pep:`594`, " +"there are currently no modules in this latter category." msgstr "" -"Os módulos descritos neste capítulo são descontinuados ou :term:`suavemente " -"descontinuados ` e mantidos apenas para " -"compatibilidade com versões anteriores. Eles foram substituídos por outros " -"módulos." +"Alternativamente, módulos podem aparecer neste capítulo porque estão " +"totalmente descontinuados e aguardando remoção em uma versão futura, ou " +"estão :term:`suavemente descontinuados ` e seu uso " +"é ativamente desencorajado em novos projetos. Com a remoção de vários " +"módulos obsoletos por meio da :pep:`594`, atualmente não há módulos nesta " +"última categoria." diff --git a/library/symtable.po b/library/symtable.po index 92309e28b..acce9a54d 100644 --- a/library/symtable.po +++ b/library/symtable.po @@ -1,34 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# i17obot , 2024 -# Claudio Rogerio Carvalho Filho , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-20 06:40+0000\n" -"PO-Revision-Date: 2021-06-28 01:14+0000\n" -"Last-Translator: Claudio Rogerio Carvalho Filho , " -"2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/symtable.rst:2 msgid ":mod:`!symtable` --- Access to the compiler's symbol tables" -msgstr "" +msgstr ":mod:`!symtable` --- Acesso a tabela de símbolos do compilador" #: ../../library/symtable.rst:7 msgid "**Source code:** :source:`Lib/symtable.py`" @@ -199,139 +196,157 @@ msgid "Return a tuple containing names of globals in this function." msgstr "" #: ../../library/symtable.rst:170 -msgid "Return a tuple containing names of nonlocals in this function." +msgid "" +"Return a tuple containing names of explicitly declared nonlocals in this " +"function." msgstr "" #: ../../library/symtable.rst:174 -msgid "Return a tuple containing names of free variables in this function." +msgid "" +"Return a tuple containing names of :term:`free (closure) variables ` in this function." msgstr "" -#: ../../library/symtable.rst:179 +#: ../../library/symtable.rst:180 msgid "A namespace of a class. This class inherits from :class:`SymbolTable`." msgstr "" -#: ../../library/symtable.rst:183 +#: ../../library/symtable.rst:184 msgid "" "Return a tuple containing the names of method-like functions declared in the " "class." msgstr "" -#: ../../library/symtable.rst:186 +#: ../../library/symtable.rst:187 msgid "" "Here, the term 'method' designates *any* function defined in the class body " "via :keyword:`def` or :keyword:`async def`." msgstr "" -#: ../../library/symtable.rst:189 +#: ../../library/symtable.rst:190 msgid "" "Functions defined in a deeper scope (e.g., in an inner class) are not picked " "up by :meth:`get_methods`." msgstr "" -#: ../../library/symtable.rst:192 +#: ../../library/symtable.rst:193 msgid "For example:" msgstr "Por exemplo:" -#: ../../library/symtable.rst:214 +#: ../../library/symtable.rst:215 msgid "" "Although ``A().f()`` raises :exc:`TypeError` at runtime, ``A.f`` is still " "considered as a method-like function." msgstr "" -#: ../../library/symtable.rst:219 +#: ../../library/symtable.rst:220 msgid "" "An entry in a :class:`SymbolTable` corresponding to an identifier in the " "source. The constructor is not public." msgstr "" -#: ../../library/symtable.rst:224 +#: ../../library/symtable.rst:225 msgid "Return the symbol's name." msgstr "" -#: ../../library/symtable.rst:228 +#: ../../library/symtable.rst:229 msgid "Return ``True`` if the symbol is used in its block." msgstr "" -#: ../../library/symtable.rst:232 +#: ../../library/symtable.rst:233 msgid "Return ``True`` if the symbol is created from an import statement." msgstr "" -#: ../../library/symtable.rst:236 +#: ../../library/symtable.rst:237 msgid "Return ``True`` if the symbol is a parameter." msgstr "" -#: ../../library/symtable.rst:240 +#: ../../library/symtable.rst:241 msgid "Return ``True`` if the symbol is global." msgstr "" -#: ../../library/symtable.rst:244 +#: ../../library/symtable.rst:245 msgid "Return ``True`` if the symbol is nonlocal." msgstr "" -#: ../../library/symtable.rst:248 +#: ../../library/symtable.rst:249 msgid "" "Return ``True`` if the symbol is declared global with a global statement." msgstr "" -#: ../../library/symtable.rst:252 +#: ../../library/symtable.rst:253 msgid "Return ``True`` if the symbol is local to its block." msgstr "" -#: ../../library/symtable.rst:256 +#: ../../library/symtable.rst:257 msgid "Return ``True`` if the symbol is annotated." msgstr "" -#: ../../library/symtable.rst:262 +#: ../../library/symtable.rst:263 msgid "" "Return ``True`` if the symbol is referenced in its block, but not assigned " "to." msgstr "" -#: ../../library/symtable.rst:267 +#: ../../library/symtable.rst:268 msgid "Return ``True`` if the symbol is assigned to in its block." msgstr "" -#: ../../library/symtable.rst:271 +#: ../../library/symtable.rst:272 msgid "Return ``True`` if name binding introduces new namespace." msgstr "" -#: ../../library/symtable.rst:273 +#: ../../library/symtable.rst:274 msgid "" "If the name is used as the target of a function or class statement, this " "will be true." msgstr "" -#: ../../library/symtable.rst:276 +#: ../../library/symtable.rst:277 msgid "For example::" msgstr "Por exemplo::" -#: ../../library/symtable.rst:282 +#: ../../library/symtable.rst:279 +msgid "" +">>> table = symtable.symtable(\"def some_func(): pass\", \"string\", " +"\"exec\")\n" +">>> table.lookup(\"some_func\").is_namespace()\n" +"True" +msgstr "" + +#: ../../library/symtable.rst:283 msgid "" "Note that a single name can be bound to multiple objects. If the result is " "``True``, the name may also be bound to other objects, like an int or list, " "that does not introduce a new namespace." msgstr "" -#: ../../library/symtable.rst:288 +#: ../../library/symtable.rst:289 msgid "Return a list of namespaces bound to this name." msgstr "" -#: ../../library/symtable.rst:292 +#: ../../library/symtable.rst:293 msgid "" "Return the namespace bound to this name. If more than one or no namespace is " "bound to this name, a :exc:`ValueError` is raised." msgstr "" -#: ../../library/symtable.rst:299 +#: ../../library/symtable.rst:300 msgid "Command-Line Usage" -msgstr "Uso da linha de comando" +msgstr "Uso na linha de comando" -#: ../../library/symtable.rst:303 +#: ../../library/symtable.rst:304 msgid "" "The :mod:`symtable` module can be executed as a script from the command line." msgstr "" +"O módulo :mod:`symtable` pode ser invocado como um script na linha de " +"comando:" + +#: ../../library/symtable.rst:306 +msgid "python -m symtable [infile...]" +msgstr "" -#: ../../library/symtable.rst:309 +#: ../../library/symtable.rst:310 msgid "" "Symbol tables are generated for the specified Python source files and dumped " "to stdout. If no input file is specified, the content is read from stdin." diff --git a/library/sys.monitoring.po b/library/sys.monitoring.po index 78e55e3df..7fbf1a2b8 100644 --- a/library/sys.monitoring.po +++ b/library/sys.monitoring.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2023-09-08 14:16+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-04-25 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -149,6 +149,18 @@ msgstr "" "mas as seguintes IDs são predefinidas para facilitar a cooperação entre as " "ferramentas::" +#: ../../library/sys.monitoring.rst:73 +msgid "" +"sys.monitoring.DEBUGGER_ID = 0\n" +"sys.monitoring.COVERAGE_ID = 1\n" +"sys.monitoring.PROFILER_ID = 2\n" +"sys.monitoring.OPTIMIZER_ID = 5" +msgstr "" +"sys.monitoring.DEBUGGER_ID = 0\n" +"sys.monitoring.COVERAGE_ID = 1\n" +"sys.monitoring.PROFILER_ID = 2\n" +"sys.monitoring.OPTIMIZER_ID = 5" + #: ../../library/sys.monitoring.rst:80 msgid "Events" msgstr "Eventos" @@ -273,16 +285,16 @@ msgstr "Mais eventos poderão ser adicionados no futuro." msgid "" "These events are attributes of the :mod:`!sys.monitoring.events` namespace. " "Each event is represented as a power-of-2 integer constant. To define a set " -"of events, simply bitwise or the individual events together. For example, to " +"of events, simply bitwise OR the individual events together. For example, to " "specify both :monitoring-event:`PY_RETURN` and :monitoring-event:`PY_START` " "events, use the expression ``PY_RETURN | PY_START``." msgstr "" "Esses eventos são atributos do espaço de nomes :mod:`!sys.monitoring." "events`. Cada evento é representado como uma constante de potência de 2 " -"inteiros. Para definir um conjunto de eventos, basta usar o bit a bit ou os " -"eventos individuais juntos. Por exemplo, para especificar os eventos :" -"monitoring-event:`PY_RETURN` e :monitoring-event:`PY_START`, use a expressão " -"``PY_RETURN | PY_START``." +"inteiros. Para definir um conjunto de eventos, basta aplicar OU (OR) bit a " +"bit nos eventos individuais juntos. Por exemplo, para especificar os " +"eventos :monitoring-event:`PY_RETURN` e :monitoring-event:`PY_START`, use a " +"expressão ``PY_RETURN | PY_START``." #: ../../library/sys.monitoring.rst:163 msgid "An alias for ``0`` so users can do explicit comparisons like::" @@ -290,15 +302,23 @@ msgstr "" "Um apelido para ``0`` para que os usuários possam fazer comparações " "explícitas como::" +#: ../../library/sys.monitoring.rst:165 +msgid "" +"if get_events(DEBUGGER_ID) == NO_EVENTS:\n" +" ..." +msgstr "" +"if get_events(DEBUGGER_ID) == NO_EVENTS:\n" +" ..." + #: ../../library/sys.monitoring.rst:168 msgid "Events are divided into three groups:" msgstr "Os eventos são divididos em três grupos:" -#: ../../library/sys.monitoring.rst:171 +#: ../../library/sys.monitoring.rst:173 msgid "Local events" msgstr "Eventos locais" -#: ../../library/sys.monitoring.rst:173 +#: ../../library/sys.monitoring.rst:175 msgid "" "Local events are associated with normal execution of the program and happen " "at clearly defined locations. All local events can be disabled. The local " @@ -308,51 +328,51 @@ msgstr "" "em locais claramente definidos. Todos os eventos locais podem ser " "desativados. Os eventos locais são:" -#: ../../library/sys.monitoring.rst:177 +#: ../../library/sys.monitoring.rst:179 msgid ":monitoring-event:`PY_START`" msgstr ":monitoring-event:`PY_START`" -#: ../../library/sys.monitoring.rst:178 +#: ../../library/sys.monitoring.rst:180 msgid ":monitoring-event:`PY_RESUME`" msgstr ":monitoring-event:`PY_RESUME`" -#: ../../library/sys.monitoring.rst:179 +#: ../../library/sys.monitoring.rst:181 msgid ":monitoring-event:`PY_RETURN`" msgstr ":monitoring-event:`PY_RETURN`" -#: ../../library/sys.monitoring.rst:180 +#: ../../library/sys.monitoring.rst:182 msgid ":monitoring-event:`PY_YIELD`" msgstr ":monitoring-event:`PY_YIELD`" -#: ../../library/sys.monitoring.rst:181 +#: ../../library/sys.monitoring.rst:183 msgid ":monitoring-event:`CALL`" msgstr ":monitoring-event:`CALL`" -#: ../../library/sys.monitoring.rst:182 +#: ../../library/sys.monitoring.rst:184 msgid ":monitoring-event:`LINE`" msgstr ":monitoring-event:`LINE`" -#: ../../library/sys.monitoring.rst:183 +#: ../../library/sys.monitoring.rst:185 msgid ":monitoring-event:`INSTRUCTION`" msgstr ":monitoring-event:`INSTRUCTION`" -#: ../../library/sys.monitoring.rst:184 +#: ../../library/sys.monitoring.rst:186 msgid ":monitoring-event:`JUMP`" msgstr ":monitoring-event:`JUMP`" -#: ../../library/sys.monitoring.rst:185 +#: ../../library/sys.monitoring.rst:187 msgid ":monitoring-event:`BRANCH`" msgstr ":monitoring-event:`BRANCH`" -#: ../../library/sys.monitoring.rst:186 +#: ../../library/sys.monitoring.rst:188 msgid ":monitoring-event:`STOP_ITERATION`" msgstr ":monitoring-event:`STOP_ITERATION`" -#: ../../library/sys.monitoring.rst:189 +#: ../../library/sys.monitoring.rst:191 msgid "Ancillary events" msgstr "Eventos auxiliares" -#: ../../library/sys.monitoring.rst:191 +#: ../../library/sys.monitoring.rst:193 msgid "" "Ancillary events can be monitored like other events, but are controlled by " "another event:" @@ -360,15 +380,15 @@ msgstr "" "Os eventos auxiliares podem ser monitorados como outros eventos, mas são " "controlados por outro evento:" -#: ../../library/sys.monitoring.rst:194 +#: ../../library/sys.monitoring.rst:196 msgid ":monitoring-event:`C_RAISE`" msgstr ":monitoring-event:`C_RAISE`" -#: ../../library/sys.monitoring.rst:195 +#: ../../library/sys.monitoring.rst:197 msgid ":monitoring-event:`C_RETURN`" msgstr ":monitoring-event:`C_RETURN`" -#: ../../library/sys.monitoring.rst:197 +#: ../../library/sys.monitoring.rst:199 msgid "" "The :monitoring-event:`C_RETURN` and :monitoring-event:`C_RAISE` events are " "controlled by the :monitoring-event:`CALL` event. :monitoring-event:" @@ -380,11 +400,11 @@ msgstr "" "event:`C_RETURN` e :monitoring-event:`C_RAISE` só serão vistos se o evento :" "monitoring-event:`CALL` correspondente estiver sendo monitorado." -#: ../../library/sys.monitoring.rst:203 +#: ../../library/sys.monitoring.rst:205 msgid "Other events" msgstr "Outros eventos" -#: ../../library/sys.monitoring.rst:205 +#: ../../library/sys.monitoring.rst:207 msgid "" "Other events are not necessarily tied to a specific location in the program " "and cannot be individually disabled." @@ -392,31 +412,31 @@ msgstr "" "Outros eventos não estão necessariamente vinculados a um local específico no " "programa e não podem ser desativados individualmente." -#: ../../library/sys.monitoring.rst:208 +#: ../../library/sys.monitoring.rst:210 msgid "The other events that can be monitored are:" msgstr "Os outros eventos que podem ser monitorados são:" -#: ../../library/sys.monitoring.rst:210 +#: ../../library/sys.monitoring.rst:212 msgid ":monitoring-event:`PY_THROW`" msgstr ":monitoring-event:`PY_THROW`" -#: ../../library/sys.monitoring.rst:211 +#: ../../library/sys.monitoring.rst:213 msgid ":monitoring-event:`PY_UNWIND`" msgstr ":monitoring-event:`PY_UNWIND`" -#: ../../library/sys.monitoring.rst:212 +#: ../../library/sys.monitoring.rst:214 msgid ":monitoring-event:`RAISE`" msgstr ":monitoring-event:`RAISE`" -#: ../../library/sys.monitoring.rst:213 +#: ../../library/sys.monitoring.rst:215 msgid ":monitoring-event:`EXCEPTION_HANDLED`" msgstr ":monitoring-event:`EXCEPTION_HANDLED`" -#: ../../library/sys.monitoring.rst:217 +#: ../../library/sys.monitoring.rst:219 msgid "The STOP_ITERATION event" msgstr "O evento STOP_ITERATION" -#: ../../library/sys.monitoring.rst:219 +#: ../../library/sys.monitoring.rst:221 msgid "" ":pep:`PEP 380 <380#use-of-stopiteration-to-return-values>` specifies that a :" "exc:`StopIteration` exception is raised when returning a value from a " @@ -431,7 +451,7 @@ msgstr "" "o CPython 3.12+, não levantam uma exceção, a menos que ela seja visível para " "outro código." -#: ../../library/sys.monitoring.rst:225 +#: ../../library/sys.monitoring.rst:227 msgid "" "To allow tools to monitor for real exceptions without slowing down " "generators and coroutines, the :monitoring-event:`STOP_ITERATION` event is " @@ -443,11 +463,11 @@ msgstr "" "`STOP_ITERATION` é fornecido. O :monitoring-event:`STOP_ITERATION` pode ser " "desativado localmente, ao contrário do :monitoring-event:`RAISE`." -#: ../../library/sys.monitoring.rst:231 +#: ../../library/sys.monitoring.rst:233 msgid "Turning events on and off" msgstr "Ativação e desativação de eventos" -#: ../../library/sys.monitoring.rst:233 +#: ../../library/sys.monitoring.rst:235 msgid "" "In order to monitor an event, it must be turned on and a corresponding " "callback must be registered. Events can be turned on or off by setting the " @@ -457,11 +477,11 @@ msgstr "" "correspondente deve ser registrada. Os eventos podem ser ativados ou " "desativados definindo-os globalmente ou para um objeto código específico." -#: ../../library/sys.monitoring.rst:240 +#: ../../library/sys.monitoring.rst:242 msgid "Setting events globally" msgstr "Definir eventos globalmente" -#: ../../library/sys.monitoring.rst:242 +#: ../../library/sys.monitoring.rst:244 msgid "" "Events can be controlled globally by modifying the set of events being " "monitored." @@ -469,11 +489,11 @@ msgstr "" "Os eventos podem ser controlados globalmente, modificando o conjunto de " "eventos que estão sendo monitorados." -#: ../../library/sys.monitoring.rst:246 +#: ../../library/sys.monitoring.rst:248 msgid "Returns the ``int`` representing all the active events." msgstr "Retorna o endereço ``int`` que representa todos os eventos ativos." -#: ../../library/sys.monitoring.rst:250 +#: ../../library/sys.monitoring.rst:252 msgid "" "Activates all events which are set in *event_set*. Raises a :exc:" "`ValueError` if *tool_id* is not in use." @@ -481,31 +501,31 @@ msgstr "" "Ativa todos os eventos definidos em *event_set*. Levanta um :exc:" "`ValueError` se *tool_id* não estiver em uso." -#: ../../library/sys.monitoring.rst:253 +#: ../../library/sys.monitoring.rst:255 msgid "No events are active by default." msgstr "Nenhum evento está ativo por padrão." -#: ../../library/sys.monitoring.rst:256 +#: ../../library/sys.monitoring.rst:258 msgid "Per code object events" msgstr "Eventos por objeto código" -#: ../../library/sys.monitoring.rst:258 +#: ../../library/sys.monitoring.rst:260 msgid "" "Events can also be controlled on a per code object basis. The functions " "defined below which accept a :class:`types.CodeType` should be prepared to " "accept a look-alike object from functions which are not defined in Python " -"(see :ref:`monitoring`)." +"(see :ref:`c-api-monitoring`)." msgstr "" "Os eventos também podem ser controlados por objeto código. As funções " "definidas abaixo que aceitam um :class:`types.CodeType` devem estar " "preparadas para aceitar um objeto semelhante de funções que não são " -"definidas no Python (veja :ref:`monitoring`)." +"definidas no Python (veja :ref:`c-api-monitoring`)." -#: ../../library/sys.monitoring.rst:265 +#: ../../library/sys.monitoring.rst:267 msgid "Returns all the local events for *code*" msgstr "Retorna todos os eventos locais para *code*" -#: ../../library/sys.monitoring.rst:269 +#: ../../library/sys.monitoring.rst:271 msgid "" "Activates all the local events for *code* which are set in *event_set*. " "Raises a :exc:`ValueError` if *tool_id* is not in use." @@ -513,7 +533,7 @@ msgstr "" "Ativa todos os eventos locais para *code* que estão definidos em " "*event_set*. Levanta a :exc:`ValueError` se *tool_id* não estiver em uso." -#: ../../library/sys.monitoring.rst:272 +#: ../../library/sys.monitoring.rst:274 msgid "" "Local events add to global events, but do not mask them. In other words, all " "global events will trigger for a code object, regardless of the local events." @@ -522,11 +542,11 @@ msgstr "" "Em outras palavras, todos os eventos globais serão acionados para um objeto " "código, independentemente dos eventos locais." -#: ../../library/sys.monitoring.rst:278 +#: ../../library/sys.monitoring.rst:280 msgid "Disabling events" msgstr "Desativação de eventos" -#: ../../library/sys.monitoring.rst:282 +#: ../../library/sys.monitoring.rst:284 msgid "" "A special value that can be returned from a callback function to disable " "events for the current code location." @@ -534,7 +554,7 @@ msgstr "" "Um valor especial que pode ser retornado de um função de retorno função para " "desativar eventos para o local do código atual." -#: ../../library/sys.monitoring.rst:285 +#: ../../library/sys.monitoring.rst:287 msgid "" "Local events can be disabled for a specific code location by returning :data:" "`sys.monitoring.DISABLE` from a callback function. This does not change " @@ -545,7 +565,7 @@ msgstr "" "chamada. Isso não altera quais eventos são definidos ou quaisquer outros " "locais de código para o mesmo evento." -#: ../../library/sys.monitoring.rst:289 +#: ../../library/sys.monitoring.rst:291 msgid "" "Disabling events for specific locations is very important for high " "performance monitoring. For example, a program can be run under a debugger " @@ -557,7 +577,7 @@ msgstr "" "executado em um depurador sem sobrecarga se o depurador desativar todo o " "monitoramento, exceto alguns pontos de interrupção." -#: ../../library/sys.monitoring.rst:296 +#: ../../library/sys.monitoring.rst:298 msgid "" "Enable all the events that were disabled by :data:`sys.monitoring.DISABLE` " "for all tools." @@ -565,19 +585,19 @@ msgstr "" "Habilita todos os eventos que foram desabilitados por :data:`sys.monitoring." "DISABLE` para todas as ferramentas." -#: ../../library/sys.monitoring.rst:303 +#: ../../library/sys.monitoring.rst:305 msgid "Registering callback functions" msgstr "Registro de funções de retorno de chamada" -#: ../../library/sys.monitoring.rst:305 +#: ../../library/sys.monitoring.rst:307 msgid "To register a callable for events call" msgstr "Para registrar um chamável para eventos, chame" -#: ../../library/sys.monitoring.rst:309 +#: ../../library/sys.monitoring.rst:311 msgid "Registers the callable *func* for the *event* with the given *tool_id*" msgstr "Registra o chamável *func* para o *event* com o *tool_id* fornecido" -#: ../../library/sys.monitoring.rst:311 +#: ../../library/sys.monitoring.rst:313 msgid "" "If another callback was registered for the given *tool_id* and *event*, it " "is unregistered and returned. Otherwise :func:`register_callback` returns " @@ -587,7 +607,7 @@ msgstr "" "*event* fornecidos, ela será cancelada e retornada. Caso contrário, :func:" "`register_callback` retorna ``None``." -#: ../../library/sys.monitoring.rst:316 +#: ../../library/sys.monitoring.rst:318 msgid "" "Functions can be unregistered by calling ``sys.monitoring." "register_callback(tool_id, event, None)``." @@ -595,13 +615,13 @@ msgstr "" "As funções podem ser canceladas chamando ``sys.monitoring." "register_callback(tool_id, event, None)``." -#: ../../library/sys.monitoring.rst:319 +#: ../../library/sys.monitoring.rst:321 msgid "Callback functions can be registered and unregistered at any time." msgstr "" "As funções de retorno de chamada podem ser registradas e canceladas a " "qualquer momento." -#: ../../library/sys.monitoring.rst:321 +#: ../../library/sys.monitoring.rst:323 msgid "" "Registering or unregistering a callback function will generate a :func:`sys." "audit` event." @@ -609,11 +629,11 @@ msgstr "" "O registro ou o cancelamento do registro de uma função de retorno de chamada " "gerará um evento :func:`sys.audit`." -#: ../../library/sys.monitoring.rst:325 +#: ../../library/sys.monitoring.rst:327 msgid "Callback function arguments" msgstr "Argumentos da função de retorno de chamada" -#: ../../library/sys.monitoring.rst:329 +#: ../../library/sys.monitoring.rst:331 msgid "" "A special value that is passed to a callback function to indicate that there " "are no arguments to the call." @@ -621,7 +641,7 @@ msgstr "" "Um valor especial que é passado para uma função de retorno para indicar que " "não há argumento para a chamada." -#: ../../library/sys.monitoring.rst:332 +#: ../../library/sys.monitoring.rst:334 msgid "" "When an active event occurs, the registered callback function is called. " "Different events will provide the callback function with different " @@ -631,16 +651,28 @@ msgstr "" "chamada. Eventos diferentes fornecerão à função de retorno de chamada " "argumentos diferentes, como segue:" -#: ../../library/sys.monitoring.rst:335 +#: ../../library/sys.monitoring.rst:337 msgid ":monitoring-event:`PY_START` and :monitoring-event:`PY_RESUME`::" msgstr ":monitoring-event:`PY_START` e :monitoring-event:`PY_RESUME`::" -#: ../../library/sys.monitoring.rst:339 +#: ../../library/sys.monitoring.rst:339 ../../library/sys.monitoring.rst:370 +msgid "func(code: CodeType, instruction_offset: int) -> DISABLE | Any" +msgstr "func(code: CodeType, instruction_offset: int) -> DISABLE | Any" + +#: ../../library/sys.monitoring.rst:341 msgid ":monitoring-event:`PY_RETURN` and :monitoring-event:`PY_YIELD`::" msgstr ":monitoring-event:`PY_RETURN` e :monitoring-event:`PY_YIELD`::" #: ../../library/sys.monitoring.rst:343 msgid "" +"func(code: CodeType, instruction_offset: int, retval: object) -> DISABLE | " +"Any" +msgstr "" +"func(code: CodeType, instruction_offset: int, retval: object) -> DISABLE | " +"Any" + +#: ../../library/sys.monitoring.rst:345 +msgid "" ":monitoring-event:`CALL`, :monitoring-event:`C_RAISE` and :monitoring-event:" "`C_RETURN`::" msgstr "" @@ -649,12 +681,20 @@ msgstr "" #: ../../library/sys.monitoring.rst:347 msgid "" +"func(code: CodeType, instruction_offset: int, callable: object, arg0: object " +"| MISSING) -> DISABLE | Any" +msgstr "" +"func(code: CodeType, instruction_offset: int, callable: object, arg0: object " +"| MISSING) -> DISABLE | Any" + +#: ../../library/sys.monitoring.rst:349 +msgid "" "If there are no arguments, *arg0* is set to :data:`sys.monitoring.MISSING`." msgstr "" "Se não houver argumentos, *arg0* será definido como :data:`sys.monitoring." "MISSING`." -#: ../../library/sys.monitoring.rst:349 +#: ../../library/sys.monitoring.rst:351 msgid "" ":monitoring-event:`RAISE`, :monitoring-event:`RERAISE`, :monitoring-event:" "`EXCEPTION_HANDLED`, :monitoring-event:`PY_UNWIND`, :monitoring-event:" @@ -665,15 +705,35 @@ msgstr "" "`PY_THROW` e :monitoring-event:`STOP_ITERATION`::" #: ../../library/sys.monitoring.rst:354 +msgid "" +"func(code: CodeType, instruction_offset: int, exception: BaseException) -> " +"DISABLE | Any" +msgstr "" +"func(code: CodeType, instruction_offset: int, exception: BaseException) -> " +"DISABLE | Any" + +#: ../../library/sys.monitoring.rst:356 msgid ":monitoring-event:`LINE`::" msgstr ":monitoring-event:`LINE`::" #: ../../library/sys.monitoring.rst:358 +msgid "func(code: CodeType, line_number: int) -> DISABLE | Any" +msgstr "func(code: CodeType, line_number: int) -> DISABLE | Any" + +#: ../../library/sys.monitoring.rst:360 msgid ":monitoring-event:`BRANCH` and :monitoring-event:`JUMP`::" msgstr ":monitoring-event:`BRANCH` e :monitoring-event:`JUMP`::" #: ../../library/sys.monitoring.rst:362 msgid "" +"func(code: CodeType, instruction_offset: int, destination_offset: int) -> " +"DISABLE | Any" +msgstr "" +"func(code: CodeType, instruction_offset: int, destination_offset: int) -> " +"DISABLE | Any" + +#: ../../library/sys.monitoring.rst:364 +msgid "" "Note that the *destination_offset* is where the code will next execute. For " "an untaken branch this will be the offset of the instruction following the " "branch." @@ -682,6 +742,6 @@ msgstr "" "Para uma ramificação não executada, esse será o deslocamento da instrução " "que segue a ramificação." -#: ../../library/sys.monitoring.rst:366 +#: ../../library/sys.monitoring.rst:368 msgid ":monitoring-event:`INSTRUCTION`::" msgstr ":monitoring-event:`INSTRUCTION`::" diff --git a/library/sys.po b/library/sys.po index f883e1e05..23b3adcc0 100644 --- a/library/sys.po +++ b/library/sys.po @@ -1,37 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2021 -# Rogério Araújo , 2021 -# Welington Carlos , 2021 -# felipe caridade fernandes , 2021 -# a76d6fb6142d7607ab0526dcbddb02d7_7bf0da0 <3b5fb0f281c8dfb4c0170f2ee2a6cfcf_843623>, 2021 -# i17obot , 2021 -# yyyyyyyan , 2021 -# Raphael Mendonça, 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# Marco Rougeth , 2023 -# mvpetri , 2023 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:14+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-03-28 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -43,11 +31,13 @@ msgstr ":mod:`!sys` --- Parâmetros e funções específicas do sistema" msgid "" "This module provides access to some variables used or maintained by the " "interpreter and to functions that interact strongly with the interpreter. It " -"is always available." +"is always available. Unless explicitly noted otherwise, all variables are " +"read-only." msgstr "" "Este módulo fornece acesso a algumas variáveis usadas ou mantidas pelo " "interpretador e a funções que interagem fortemente com o interpretador. " -"Sempre disponível." +"Sempre disponível. A menos que explicitamente indicado o contrário, todas as " +"variáveis são somente leitura." #: ../../library/sys.rst:16 msgid "" @@ -66,10 +56,14 @@ msgstr "" "Os sinalizadores padrões se tornaram uma string vazia (o sinalizador ``m`` " "para pymalloc foi removido)." -#: ../../library/sys.rst:25 ../../library/sys.rst:778 -#: ../../library/sys.rst:1489 -msgid ":ref:`Availability `: Unix." -msgstr ":ref:`Disponibilidade `: Unix." +#: ../../library/sys.rst:25 ../../library/sys.rst:299 ../../library/sys.rst:369 +#: ../../library/sys.rst:760 ../../library/sys.rst:778 +#: ../../library/sys.rst:1020 ../../library/sys.rst:1522 +#: ../../library/sys.rst:1763 ../../library/sys.rst:1778 +#: ../../library/sys.rst:1786 ../../library/sys.rst:1802 +#: ../../library/sys.rst:2046 +msgid "Availability" +msgstr "Disponibilidade" #: ../../library/sys.rst:30 msgid "" @@ -548,11 +542,6 @@ msgstr "" msgid "Integer specifying the handle of the Python DLL." msgstr "Número inteiro que especifica o identificador da DLL do Python." -#: ../../library/sys.rst:299 ../../library/sys.rst:991 -#: ../../library/sys.rst:1769 ../../library/sys.rst:2013 -msgid ":ref:`Availability `: Windows." -msgstr ":ref:`Disponibilidade `: Windows." - #: ../../library/sys.rst:304 msgid "" "If *value* is not ``None``, this function prints ``repr(value)`` to ``sys." @@ -583,6 +572,44 @@ msgstr "" msgid "Pseudo-code::" msgstr "Pseudocódigo::" +#: ../../library/sys.rst:316 +msgid "" +"def displayhook(value):\n" +" if value is None:\n" +" return\n" +" # Set '_' to None to avoid recursion\n" +" builtins._ = None\n" +" text = repr(value)\n" +" try:\n" +" sys.stdout.write(text)\n" +" except UnicodeEncodeError:\n" +" bytes = text.encode(sys.stdout.encoding, 'backslashreplace')\n" +" if hasattr(sys.stdout, 'buffer'):\n" +" sys.stdout.buffer.write(bytes)\n" +" else:\n" +" text = bytes.decode(sys.stdout.encoding, 'strict')\n" +" sys.stdout.write(text)\n" +" sys.stdout.write(\"\\n\")\n" +" builtins._ = value" +msgstr "" +"def displayhook(value):\n" +" if value is None:\n" +" return\n" +" # Define '_' como None para evitar recursão\n" +" builtins._ = None\n" +" text = repr(value)\n" +" try:\n" +" sys.stdout.write(text)\n" +" except UnicodeEncodeError:\n" +" bytes = text.encode(sys.stdout.encoding, 'backslashreplace')\n" +" if hasattr(sys.stdout, 'buffer'):\n" +" sys.stdout.buffer.write(bytes)\n" +" else:\n" +" text = bytes.decode(sys.stdout.encoding, 'strict')\n" +" sys.stdout.write(text)\n" +" sys.stdout.write(\"\\n\")\n" +" builtins._ = value" + #: ../../library/sys.rst:334 msgid "Use ``'backslashreplace'`` error handler on :exc:`UnicodeEncodeError`." msgstr "" @@ -638,10 +665,6 @@ msgid "``True`` if Python is compiled with shared memory support." msgstr "" "``True`` se o Python for compilado com suporte a memória compartilhada." -#: ../../library/sys.rst:369 -msgid ":ref:`Availability `: Emscripten." -msgstr ":ref:`Disponibilidade `: Emscripten." - #: ../../library/sys.rst:376 msgid "" "If this is set (not ``None``), Python will write bytecode-cache ``.pyc`` " @@ -1244,6 +1267,24 @@ msgstr "" "flutuante e vice-versa recuperará uma string representando o mesmo decimal " "valor::" +#: ../../library/sys.rst:705 +msgid "" +">>> import sys\n" +">>> sys.float_info.dig\n" +"15\n" +">>> s = '3.14159265358979' # decimal string with 15 significant digits\n" +">>> format(float(s), '.15g') # convert to float and back -> same value\n" +"'3.14159265358979'" +msgstr "" +">>> import sys\n" +">>> sys.float_info.dig\n" +"15\n" +">>> s = '3.14159265358979' # string decimal com 15 dígitos " +"significativos\n" +">>> format(float(s), '.15g') # converter para float e desconverter retorna " +"mesmo valor\n" +"'3.14159265358979'" + #: ../../library/sys.rst:712 msgid "" "But for strings with more than :attr:`sys.float_info.dig` significant " @@ -1252,6 +1293,16 @@ msgstr "" "Mas para strings com mais de :attr:`sys.float_info.dig` dígitos " "significativos, isso nem sempre é verdade::" +#: ../../library/sys.rst:715 +msgid "" +">>> s = '9876543211234567' # 16 significant digits is too many!\n" +">>> format(float(s), '.16g') # conversion changes value\n" +"'9876543211234568'" +msgstr "" +">>> s = '9876543211234567' # 16 dígitos significativos é muito!\n" +">>> format(float(s), '.16g') # a conversão muda o valor\n" +"'9876543211234568'" + #: ../../library/sys.rst:721 msgid "" "A string indicating how the :func:`repr` function behaves for floats. If " @@ -1275,24 +1326,24 @@ msgid "" "regardless of their size. This function is mainly useful for tracking and " "debugging memory leaks. Because of the interpreter's internal caches, the " "result can vary from call to call; you may have to call :func:" -"`_clear_internal_caches()` and :func:`gc.collect()` to get more predictable " +"`_clear_internal_caches` and :func:`gc.collect` to get more predictable " "results." msgstr "" -"Retorna o número de blocos de memória atualmente alocados pelo " -"interpretador, independentemente de seu tamanho. Esta função é útil " -"principalmente para rastrear e depurar vazamentos de memória. Devido aos " -"caches internos do interpretador, o resultado pode variar de chamada para " -"chamada; você pode ter que chamar :func:`_clear_internal_caches()` e :func:" -"`gc.collect()` para obter resultados mais previsíveis." +"Retorna a quantidade de blocos de memória alocados atualmente pelo " +"interpretador, independentemente do tamanho. Esta função é útil " +"principalmente ao acompanhar e depurar vazamentos de memória. Devido aos " +"caches internos do interpretador, o resultado pode variar de chamada a " +"chamada; você pode ter que chamar :func:`_clear_internal_caches` e :func:`gc." +"collect` para obter resultados mais previsíveis." #: ../../library/sys.rst:741 msgid "" "If a Python build or implementation cannot reasonably compute this " -"information, :func:`getallocatedblocks()` is allowed to return 0 instead." +"information, :func:`getallocatedblocks` is allowed to return 0 instead." msgstr "" "Se uma construção ou implementação do Python não puder computar " -"razoavelmente essas informações, :func:`getallocatedblocks()` poderá " -"retornar 0 em seu lugar." +"razoavelmente essas informações, :func:`getallocatedblocks` poderá retornar " +"0 em seu lugar." #: ../../library/sys.rst:749 msgid "Return the number of unicode objects that have been interned." @@ -1309,17 +1360,13 @@ msgstr "" "pode ser executada. Para obter informações sobre a versão de tempo de " "execução, consulte :func:`platform.android_ver`." -#: ../../library/sys.rst:760 -msgid ":ref:`Availability `: Android." -msgstr ":ref:`Disponibilidade `: Android." - #: ../../library/sys.rst:767 msgid "" -"Return the name of the current default string encoding used by the Unicode " -"implementation." +"Return ``'utf-8'``. This is the name of the default string encoding, used in " +"methods like :meth:`str.encode`." msgstr "" -"Retorna o nome da codificação de string padrão atual usada pela " -"implementação Unicode." +"Retorna ``'utf-8'``. Este é o nome da codificação de string padrão, usada em " +"métodos como :meth:`str.encode`." #: ../../library/sys.rst:773 msgid "" @@ -1520,11 +1567,11 @@ msgstr "" #: ../../library/sys.rst:886 msgid "" -"Return the interpreter's \"thread switch interval\"; see :func:" +"Return the interpreter's \"thread switch interval\" in seconds; see :func:" "`setswitchinterval`." msgstr "" -"Retorna o \"intervalo de troca de thread\" do interpretador; veja :func:" -"`setswitchinterval`." +"Retorna o \"intervalo de troca de thread\" do interpretador em segundos; " +"veja :func:`setswitchinterval`." #: ../../library/sys.rst:894 msgid "" @@ -1578,16 +1625,64 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``sys._getframemodulename`` " "com o argumento ``depth``." +#: ../../library/sys.rst:925 +msgid "" +"This function only exists if CPython was built using the specialized " +"configure option :option:`--with-trace-refs`. It is intended only for " +"debugging garbage-collection issues." +msgstr "" +"Esta função só existe se o CPython foi construído usando a opção de " +"configuração especializada :option:`--with-trace-refs`. Ela é destinada " +"apenas para depurar problemas de coleta de lixo." + #: ../../library/sys.rst:929 +msgid "" +"Return a list of up to *limit* dynamically allocated Python objects. If " +"*type* is given, only objects of that exact type (not subtypes) are included." +msgstr "" +"Retorna uma lista de até *limit* objetos Python alocados dinamicamente. Se " +"*type* for fornecido, somente objetos daquele tipo exato (não subtipos) " +"serão incluídos." + +#: ../../library/sys.rst:933 +msgid "" +"Objects from the list are not safe to use. Specifically, the result will " +"include objects from all interpreters that share their object allocator " +"state (that is, ones created with :c:member:`PyInterpreterConfig." +"use_main_obmalloc` set to 1 or using :c:func:`Py_NewInterpreter`, and the :" +"ref:`main interpreter `). Mixing objects from " +"different interpreters may lead to crashes or other unexpected behavior." +msgstr "" +"Objetos da lista não são seguros para uso. Especificamente, o resultado " +"incluirá objetos de todos os interpretadores que compartilham seu estado de " +"alocador de objetos (ou seja, aqueles criados com :c:member:" +"`PyInterpreterConfig.use_main_obmalloc` definido como 1 ou usando :c:func:" +"`Py_NewInterpreter` e o :ref:`interpretador principal `). Misturar objetos de diferentes iinterpretadores pode levar a " +"travamentos ou outros comportamentos inesperados." + +#: ../../library/sys.rst:944 +msgid "" +"This function should be used for specialized purposes only. It is not " +"guaranteed to exist in all implementations of Python." +msgstr "" +"Esta função deve ser usada apenas para fins especializados. Não é garantido " +"que exista em todas as implementações do Python." + +#: ../../library/sys.rst:949 +msgid "The result may include objects from other interpreters." +msgstr "O resultado pode incluir objetos de outros interpretadores." + +#: ../../library/sys.rst:958 msgid "Get the profiler function as set by :func:`setprofile`." msgstr "" "Obtém a função do criador de perfil conforme definido por :func:`setprofile`." -#: ../../library/sys.rst:938 +#: ../../library/sys.rst:967 msgid "Get the trace function as set by :func:`settrace`." msgstr "Obtém a função trace conforme definido por :func:`settrace`." -#: ../../library/sys.rst:942 +#: ../../library/sys.rst:971 msgid "" "The :func:`gettrace` function is intended only for implementing debuggers, " "profilers, coverage tools and the like. Its behavior is part of the " @@ -1599,7 +1694,7 @@ msgstr "" "parte da plataforma de implementação, e não da definição da linguagem e, " "portanto, pode não estar disponível em todas as implementações do Python." -#: ../../library/sys.rst:950 +#: ../../library/sys.rst:979 msgid "" "Return a named tuple describing the Windows version currently running. The " "named elements are *major*, *minor*, *build*, *platform*, *service_pack*, " @@ -1620,47 +1715,47 @@ msgstr "" "Para compatibilidade com versões anteriores, apenas os primeiros 5 elementos " "são recuperáveis por indexação." -#: ../../library/sys.rst:961 +#: ../../library/sys.rst:990 msgid "*platform* will be ``2`` (VER_PLATFORM_WIN32_NT)." msgstr "*platform* será ``2`` (VER_PLATFORM_WIN32_NT)." -#: ../../library/sys.rst:963 +#: ../../library/sys.rst:992 msgid "*product_type* may be one of the following values:" msgstr "*product_type* pode ser um dos seguintes valores:" -#: ../../library/sys.rst:966 +#: ../../library/sys.rst:995 msgid "Constant" msgstr "Constante" -#: ../../library/sys.rst:966 +#: ../../library/sys.rst:995 msgid "Meaning" msgstr "Significado" -#: ../../library/sys.rst:968 +#: ../../library/sys.rst:997 msgid "``1`` (VER_NT_WORKSTATION)" msgstr "``1`` (VER_NT_WORKSTATION)" -#: ../../library/sys.rst:968 +#: ../../library/sys.rst:997 msgid "The system is a workstation." msgstr "O sistema é uma estação de trabalho" -#: ../../library/sys.rst:970 +#: ../../library/sys.rst:999 msgid "``2`` (VER_NT_DOMAIN_CONTROLLER)" msgstr "``2`` (VER_NT_DOMAIN_CONTROLLER)" -#: ../../library/sys.rst:970 +#: ../../library/sys.rst:999 msgid "The system is a domain controller." msgstr "O sistema é um controlador de domínio." -#: ../../library/sys.rst:973 +#: ../../library/sys.rst:1002 msgid "``3`` (VER_NT_SERVER)" msgstr "``3`` (VER_NT_SERVER)" -#: ../../library/sys.rst:973 +#: ../../library/sys.rst:1002 msgid "The system is a server, but not a domain controller." msgstr "O sistema é um servidor, mas não um controlador de domínio." -#: ../../library/sys.rst:977 +#: ../../library/sys.rst:1006 msgid "" "This function wraps the Win32 :c:func:`!GetVersionEx` function; see the " "Microsoft documentation on :c:func:`!OSVERSIONINFOEX` for more information " @@ -1670,7 +1765,7 @@ msgstr "" "GetVersionEx`; consulte a documentação da Microsoft em :c:func:`!" "OSVERSIONINFOEX` para obter mais informações sobre esses campos." -#: ../../library/sys.rst:981 +#: ../../library/sys.rst:1010 msgid "" "*platform_version* returns the major version, minor version and build number " "of the current operating system, rather than the version that is being " @@ -1682,7 +1777,7 @@ msgstr "" "sendo emulada para o processo. Destina-se a ser usado no registro, e não na " "detecção de recursos." -#: ../../library/sys.rst:987 +#: ../../library/sys.rst:1016 msgid "" "*platform_version* derives the version from kernel32.dll which can be of a " "different version than the OS version. Please use :mod:`platform` module for " @@ -1692,7 +1787,7 @@ msgstr "" "versão diferente da versão do sistema operacional. Use o módulo :mod:" "`platform` para obter a versão precisa do sistema operacional." -#: ../../library/sys.rst:993 +#: ../../library/sys.rst:1022 msgid "" "Changed to a named tuple and added *service_pack_minor*, " "*service_pack_major*, *suite_mask*, and *product_type*." @@ -1700,11 +1795,11 @@ msgstr "" "Alterado para uma tupla nomeada e adicionado *service_pack_minor*, " "*service_pack_major*, *suite_mask* e *product_type*." -#: ../../library/sys.rst:997 +#: ../../library/sys.rst:1026 msgid "Added *platform_version*" msgstr "Adicionado *platform_version*" -#: ../../library/sys.rst:1003 +#: ../../library/sys.rst:1032 msgid "" "Returns an *asyncgen_hooks* object, which is similar to a :class:" "`~collections.namedtuple` of the form ``(firstiter, finalizer)``, where " @@ -1719,18 +1814,18 @@ msgstr "" "`iterador gerador assíncrono` como argumento e são usadas para agendar a " "finalização de um gerador assíncrono por um laço de eventos." -#: ../../library/sys.rst:1010 +#: ../../library/sys.rst:1039 msgid "See :pep:`525` for more details." msgstr "Veja :pep:`525` para mais detalhes." -#: ../../library/sys.rst:1014 ../../library/sys.rst:1701 +#: ../../library/sys.rst:1043 ../../library/sys.rst:1734 msgid "" "This function has been added on a provisional basis (see :pep:`411` for " "details.)" msgstr "" "Esta função foi adicionada provisoriamente (veja :pep:`411` para detalhes.)" -#: ../../library/sys.rst:1020 +#: ../../library/sys.rst:1049 msgid "" "Get the current coroutine origin tracking depth, as set by :func:" "`set_coroutine_origin_tracking_depth`." @@ -1738,7 +1833,7 @@ msgstr "" "Obtém a profundidade de rastreamento da origem da corrotina atual, conforme " "definido por :func:`set_coroutine_origin_tracking_depth`." -#: ../../library/sys.rst:1026 ../../library/sys.rst:1722 +#: ../../library/sys.rst:1055 ../../library/sys.rst:1755 msgid "" "This function has been added on a provisional basis (see :pep:`411` for " "details.) Use it only for debugging purposes." @@ -1746,7 +1841,7 @@ msgstr "" "Esta função foi adicionada provisoriamente (veja :pep:`411` para detalhes.) " "Use-a apenas para propósitos de depuração." -#: ../../library/sys.rst:1032 +#: ../../library/sys.rst:1061 msgid "" "A :term:`named tuple` giving parameters of the numeric hash implementation. " "For more details about hashing of numeric types, see :ref:`numeric-hash`." @@ -1755,43 +1850,43 @@ msgstr "" "numérico. Para mais detalhes sobre hashing de tipos numéricos, veja :ref:" "`numeric-hash`." -#: ../../library/sys.rst:1038 +#: ../../library/sys.rst:1067 msgid "The width in bits used for hash values" msgstr "A largura em bits usada para fazer hash de valores" -#: ../../library/sys.rst:1042 +#: ../../library/sys.rst:1071 msgid "The prime modulus P used for numeric hash scheme" msgstr "O módulo primo P usado para esquema de hash numérico" -#: ../../library/sys.rst:1046 +#: ../../library/sys.rst:1075 msgid "The hash value returned for a positive infinity" msgstr "O valor de hash retornado para um infinito positivo" -#: ../../library/sys.rst:1050 +#: ../../library/sys.rst:1079 msgid "(This attribute is no longer used)" msgstr "(Este atributo não é mais usado)" -#: ../../library/sys.rst:1054 +#: ../../library/sys.rst:1083 msgid "The multiplier used for the imaginary part of a complex number" msgstr "O multiplicador usado para a parte imaginária de um número complexo" -#: ../../library/sys.rst:1058 +#: ../../library/sys.rst:1087 msgid "The name of the algorithm for hashing of str, bytes, and memoryview" msgstr "O nome do algoritmo para hash de str, bytes e memoryview" -#: ../../library/sys.rst:1062 +#: ../../library/sys.rst:1091 msgid "The internal output size of the hash algorithm" msgstr "O tamanho da saída interna do algoritmo de hash" -#: ../../library/sys.rst:1066 +#: ../../library/sys.rst:1095 msgid "The size of the seed key of the hash algorithm" msgstr "O tamanho da chave semente do algoritmo hash" -#: ../../library/sys.rst:1070 +#: ../../library/sys.rst:1099 msgid "Added *algorithm*, *hash_bits* and *seed_bits*" msgstr "Adicionado *algorithm*, *hash_bits* e *seed_bits*" -#: ../../library/sys.rst:1076 +#: ../../library/sys.rst:1105 msgid "" "The version number encoded as a single integer. This is guaranteed to " "increase with each version, including proper support for non-production " @@ -1803,7 +1898,23 @@ msgstr "" "produção. Por exemplo, para testar se o interpretador Python é pelo menos a " "versão 1.5.2, use::" -#: ../../library/sys.rst:1087 +#: ../../library/sys.rst:1109 +msgid "" +"if sys.hexversion >= 0x010502F0:\n" +" # use some advanced feature\n" +" ...\n" +"else:\n" +" # use an alternative implementation or warn the user\n" +" ..." +msgstr "" +"if sys.hexversion >= 0x010502F0:\n" +" # usa algum recurso avançado\n" +" ...\n" +"else:\n" +" # usa uma implementação alternativa ou adverte o usuário\n" +" ..." + +#: ../../library/sys.rst:1116 msgid "" "This is called ``hexversion`` since it only really looks meaningful when " "viewed as the result of passing it to the built-in :func:`hex` function. " @@ -1815,13 +1926,13 @@ msgstr "" "`hex`. A :term:`tupla nomeada` :data:`sys.version_info` pode ser usada para " "uma codificação mais amigável das mesmas informações." -#: ../../library/sys.rst:1092 +#: ../../library/sys.rst:1121 msgid "More details of ``hexversion`` can be found at :ref:`apiabiversion`." msgstr "" "Mais detalhes sobre ``hexversion`` podem ser encontrados em :ref:" "`apiabiversion`." -#: ../../library/sys.rst:1097 +#: ../../library/sys.rst:1126 msgid "" "An object containing information about the implementation of the currently " "running Python interpreter. The following attributes are required to exist " @@ -1831,7 +1942,7 @@ msgstr "" "Python em execução no momento. Os atributos a seguir devem existir em todas " "as implementações do Python." -#: ../../library/sys.rst:1101 +#: ../../library/sys.rst:1130 msgid "" "*name* is the implementation's identifier, e.g. ``'cpython'``. The actual " "string is defined by the Python implementation, but it is guaranteed to be " @@ -1841,7 +1952,7 @@ msgstr "" "string real é definida pela implementação do Python, mas é garantido que " "seja minúscula." -#: ../../library/sys.rst:1105 +#: ../../library/sys.rst:1134 msgid "" "*version* is a named tuple, in the same format as :data:`sys.version_info`. " "It represents the version of the Python *implementation*. This has a " @@ -1862,7 +1973,7 @@ msgstr "" "2, 'final', 0)``. Para CPython, eles são o mesmo valor, pois é a " "implementação de referência." -#: ../../library/sys.rst:1115 +#: ../../library/sys.rst:1144 msgid "" "*hexversion* is the implementation version in hexadecimal format, like :data:" "`sys.hexversion`." @@ -1870,7 +1981,7 @@ msgstr "" "*hexversion* é a versão de implementação em formato hexadecimal, como :data:" "`sys.hexversion`." -#: ../../library/sys.rst:1118 +#: ../../library/sys.rst:1147 msgid "" "*cache_tag* is the tag used by the import machinery in the filenames of " "cached modules. By convention, it would be a composite of the " @@ -1885,7 +1996,7 @@ msgstr "" "definido como ``None``, isso indica que o cache do módulo deve ser " "desabilitado." -#: ../../library/sys.rst:1125 +#: ../../library/sys.rst:1154 msgid "" ":data:`sys.implementation` may contain additional attributes specific to the " "Python implementation. These non-standard attributes must start with an " @@ -1901,7 +2012,7 @@ msgstr "" "nem entre versões de implementação. (No entanto, ele pode mudar entre " "versões da linguagem Python.) Veja a :pep:`421` para mais informações." -#: ../../library/sys.rst:1136 +#: ../../library/sys.rst:1165 msgid "" "The addition of new required attributes must go through the normal PEP " "process. See :pep:`421` for more information." @@ -1909,7 +2020,7 @@ msgstr "" "A adição de novos atributos obrigatórios deve passar pelo processo normal de " "PEPs. Veja a :pep:`421` para mais informações." -#: ../../library/sys.rst:1141 +#: ../../library/sys.rst:1170 msgid "" "A :term:`named tuple` that holds information about Python's internal " "representation of integers. The attributes are read only." @@ -1917,7 +2028,7 @@ msgstr "" "Uma :term:`tupla nomeada` que contém informações sobre a representação " "interna de inteiros do Python. Os atributos são somente leitura." -#: ../../library/sys.rst:1146 +#: ../../library/sys.rst:1175 msgid "" "The number of bits held in each digit. Python integers are stored internally " "in base ``2**int_info.bits_per_digit``." @@ -1925,11 +2036,11 @@ msgstr "" "O número de bits mantidos em cada dígito. Os inteiros do Python são " "armazenados internamente na base ``2**int_info.bits_per_digit``." -#: ../../library/sys.rst:1151 +#: ../../library/sys.rst:1180 msgid "The size in bytes of the C type used to represent a digit." msgstr "O tamanho em bytes do tipo C usado para representar um dígito." -#: ../../library/sys.rst:1155 +#: ../../library/sys.rst:1184 msgid "" "The default value for :func:`sys.get_int_max_str_digits` when it is not " "otherwise explicitly configured." @@ -1937,7 +2048,7 @@ msgstr "" "O valor padrão para :func:`sys.get_int_max_str_digits` quando não estiver " "explicitamente configurado." -#: ../../library/sys.rst:1160 +#: ../../library/sys.rst:1189 msgid "" "The minimum non-zero value for :func:`sys.set_int_max_str_digits`, :envvar:" "`PYTHONINTMAXSTRDIGITS`, or :option:`-X int_max_str_digits <-X>`." @@ -1945,7 +2056,7 @@ msgstr "" "O valor mínimo diferente de zero para :func:`sys.set_int_max_str_digits`, :" "envvar:`PYTHONINTMAXSTRDIGITS` ou :option:`-X int_max_str_digits <-X>`." -#: ../../library/sys.rst:1167 +#: ../../library/sys.rst:1196 msgid "" "Added :attr:`~int_info.default_max_str_digits` and :attr:`~int_info." "str_digits_check_threshold`." @@ -1953,7 +2064,7 @@ msgstr "" "Adicionados :attr:`~int_info.default_max_str_digits` e :attr:`~int_info." "str_digits_check_threshold`." -#: ../../library/sys.rst:1173 +#: ../../library/sys.rst:1202 msgid "" "When this attribute exists, its value is automatically called (with no " "arguments) when the interpreter is launched in :ref:`interactive mode `." -#: ../../library/sys.rst:1179 ../../library/sys.rst:1181 +#: ../../library/sys.rst:1208 ../../library/sys.rst:1210 msgid "" "Raises an :ref:`auditing event ` ``cpython.run_interactivehook`` " "with the hook object as the argument when the hook is called on startup." @@ -1976,7 +2087,7 @@ msgstr "" "run_interactivehook`` com o objeto gancho como o argumento quando o gancho é " "chamado na inicialização." -#: ../../library/sys.rst:1190 +#: ../../library/sys.rst:1219 msgid "" "Enter *string* in the table of \"interned\" strings and return the interned " "string -- which is *string* itself or a copy. Interning strings is useful to " @@ -1993,11 +2104,11 @@ msgstr "" "dicionário -- se as chaves em um dicionário foram internalizadas, e a chave " "de pesquisa para internalizada, já que comparações de chaves (após o hash) " "podem ser feitas por uma comparação de ponteiros em vez de uma comparação de " -"strings. Normalmente, os nomes usados ​​em programas Python são internalizados " -"automaticamente, e os dicionários usados ​​para armazenar atributos de módulo, " +"strings. Normalmente, os nomes usados em programas Python são internalizados " +"automaticamente, e os dicionários usados para armazenar atributos de módulo, " "classe ou instância têm chaves internalizadas." -#: ../../library/sys.rst:1198 +#: ../../library/sys.rst:1227 msgid "" "Interned strings are not :term:`immortal`; you must keep a reference to the " "return value of :func:`intern` around to benefit from it." @@ -2005,7 +2116,7 @@ msgstr "" "Strings internalizadas não são :term:`imortais `; você deve manter " "uma referência ao valor de retorno de :func:`intern` para se beneficiar dela." -#: ../../library/sys.rst:1204 +#: ../../library/sys.rst:1233 msgid "" "Return :const:`True` if the :term:`GIL` is enabled and :const:`False` if it " "is disabled." @@ -2013,7 +2124,11 @@ msgstr "" "Retorna :const:`True` se a :term:`GIL` estiver habiltada e :const:`False` " "caso contrário." -#: ../../library/sys.rst:1212 +#: ../../library/sys.rst:1240 ../../library/sys.rst:1272 +msgid "It is not guaranteed to exist in all implementations of Python." +msgstr "Não há garantia de que exista em todas as implementações do Python." + +#: ../../library/sys.rst:1244 msgid "" "Return :const:`True` if the main Python interpreter is :term:`shutting down " "`. Return :const:`False` otherwise." @@ -2021,11 +2136,11 @@ msgstr "" "Retorna :const:`True` se o interpretador Python principal estiver :term:" "`desligando `. Retorna :const:`False` caso contrário." -#: ../../library/sys.rst:1215 +#: ../../library/sys.rst:1247 msgid "See also the :exc:`PythonFinalizationError` exception." msgstr "Veja também a exceção :exc:`PythonFinalizationError`." -#: ../../library/sys.rst:1221 +#: ../../library/sys.rst:1253 msgid "" "This variable is not always defined; it is set to the exception instance " "when an exception is not handled and the interpreter prints an error message " @@ -2043,7 +2158,7 @@ msgstr "" "típico é ``import pdb; pdb.pm()`` para entrar no depurador post-mortem; veja " "o módulo :mod:`pdb` para mais informações.)" -#: ../../library/sys.rst:1233 +#: ../../library/sys.rst:1265 msgid "" "Return :const:`True` if the given string is \"interned\", :const:`False` " "otherwise." @@ -2051,21 +2166,17 @@ msgstr "" "Retorna :const:`True` se a string fornecida for \"internalizada\", :const:" "`False` caso contrário." -#: ../../library/sys.rst:1240 -msgid "It is not guaranteed to exist in all implementations of Python." -msgstr "Não há garantia de que exista em todas as implementações do Python." - -#: ../../library/sys.rst:1247 +#: ../../library/sys.rst:1279 msgid "" "These three variables are deprecated; use :data:`sys.last_exc` instead. They " "hold the legacy representation of ``sys.last_exc``, as returned from :func:" "`exc_info` above." msgstr "" -"Essas três variáveis ​​estão descontinuadas; use :data:`sys.last_exc` em vez " +"Essas três variáveis estão descontinuadas; use :data:`sys.last_exc` em vez " "disso. Elas mantêm a representação legada de ``sys.last_exc``, conforme " "retornada de :func:`exc_info` acima." -#: ../../library/sys.rst:1253 +#: ../../library/sys.rst:1285 msgid "" "An integer giving the maximum value a variable of type :c:type:`Py_ssize_t` " "can take. It's usually ``2**31 - 1`` on a 32-bit platform and ``2**63 - 1`` " @@ -2075,7 +2186,7 @@ msgstr "" "`Py_ssize_t` pode assumir. Geralmente é ``2**31 - 1`` em uma plataforma de " "32 bits e ``2**63 - 1`` em uma plataforma de 64 bits." -#: ../../library/sys.rst:1260 +#: ../../library/sys.rst:1292 msgid "" "An integer giving the value of the largest Unicode code point, i.e. " "``1114111`` (``0x10FFFF`` in hexadecimal)." @@ -2083,7 +2194,7 @@ msgstr "" "Um inteiro que fornece o valor do maior ponto de código Unicode, ou seja, " "``1114111`` (``0x10FFFF`` em hexadecimal)." -#: ../../library/sys.rst:1263 +#: ../../library/sys.rst:1295 msgid "" "Before :pep:`393`, ``sys.maxunicode`` used to be either ``0xFFFF`` or " "``0x10FFFF``, depending on the configuration option that specified whether " @@ -2093,7 +2204,7 @@ msgstr "" "``0x10FFFF``, dependendo da opção de configuração que especificava se os " "caracteres Unicode eram armazenados como UCS-2 ou UCS-4." -#: ../../library/sys.rst:1271 +#: ../../library/sys.rst:1303 msgid "" "A list of :term:`meta path finder` objects that have their :meth:`~importlib." "abc.MetaPathFinder.find_spec` methods called to see if one of the objects " @@ -2101,25 +2212,25 @@ msgid "" "implement Python's default import semantics. The :meth:`~importlib.abc." "MetaPathFinder.find_spec` method is called with at least the absolute name " "of the module being imported. If the module to be imported is contained in a " -"package, then the parent package's :attr:`__path__` attribute is passed in " -"as a second argument. The method returns a :term:`module spec`, or ``None`` " -"if the module cannot be found." -msgstr "" -"Uma lista de objetos :term:`localizador de metacaminho` que têm seus " -"métodos :meth:`~importlib.abc.MetaPathFinder.find_spec` chamados para ver se " -"um dos objetos consegue encontrar o módulo a ser importado. Por padrão, ele " -"contém entradas que implementam a semântica de importação padrão do Python. " -"O método :meth:`~importlib.abc.MetaPathFinder.find_spec` é chamado com pelo " -"menos o nome absoluto do módulo que está sendo importado. Se o módulo a ser " -"importado estiver contido em um pacote, o atributo :attr:`__path__` do " -"pacote pai é passado como um segundo argumento. O método retorna uma :term:" -"`especificação do módulo`, ou ``None`` se o módulo não puder ser encontrado." - -#: ../../library/sys.rst:1283 +"package, then the parent package's :attr:`~module.__path__` attribute is " +"passed in as a second argument. The method returns a :term:`module spec`, or " +"``None`` if the module cannot be found." +msgstr "" +"Uma lista de objetos :term:`localizadores de metacaminho ` que têm seus métodos :meth:`~importlib.abc.MetaPathFinder." +"find_spec` chamados para que algum deles localize o módulo a ser importado. " +"Por padrão, armazena entradas que implementam a semântica de importação " +"padrão de Python. O método :meth:`~importlib.abc.MetaPathFinder.find_spec` é " +"chamado com pelo menos o nome absoluto do módulo a ser importado. Se o " +"módulo a ser importado estiver contido num pacote, o atributo :attr:`~module." +"__path__` do pacote pai é passado como segundo argumento. O método retorna " +"um :term:`spec de módulo`, ou ``None`` se o módulo não for encontrado." + +#: ../../library/sys.rst:1316 msgid ":class:`importlib.abc.MetaPathFinder`" msgstr ":class:`importlib.abc.MetaPathFinder`" -#: ../../library/sys.rst:1284 +#: ../../library/sys.rst:1317 msgid "" "The abstract base class defining the interface of finder objects on :data:" "`meta_path`." @@ -2127,11 +2238,11 @@ msgstr "" "A classe base abstrata que define a interface dos objetos localizadores em :" "data:`meta_path`." -#: ../../library/sys.rst:1286 +#: ../../library/sys.rst:1319 msgid ":class:`importlib.machinery.ModuleSpec`" msgstr ":class:`importlib.machinery.ModuleSpec`" -#: ../../library/sys.rst:1287 +#: ../../library/sys.rst:1320 msgid "" "The concrete class which :meth:`~importlib.abc.MetaPathFinder.find_spec` " "should return instances of." @@ -2139,7 +2250,7 @@ msgstr "" "A classe concreta da qual :meth:`~importlib.abc.MetaPathFinder.find_spec` " "deve retornar instâncias." -#: ../../library/sys.rst:1293 +#: ../../library/sys.rst:1326 msgid "" ":term:`Module specs ` were introduced in Python 3.4, by :pep:" "`451`." @@ -2147,7 +2258,7 @@ msgstr "" ":term:`Especificações de módulo ` foram introduzidas no Python " "3.4, pela :pep:`451`." -#: ../../library/sys.rst:1298 +#: ../../library/sys.rst:1331 msgid "" "Removed the fallback that looked for a :meth:`!find_module` method if a :" "data:`meta_path` entry didn't have a :meth:`~importlib.abc.MetaPathFinder." @@ -2157,7 +2268,7 @@ msgstr "" "uma entrada :data:`meta_path` não tivesse um método :meth:`~importlib.abc." "MetaPathFinder.find_spec`." -#: ../../library/sys.rst:1304 +#: ../../library/sys.rst:1337 msgid "" "This is a dictionary that maps module names to modules which have already " "been loaded. This can be manipulated to force reloading of modules and " @@ -2177,15 +2288,15 @@ msgstr "" "evitar exceções, pois seu tamanho pode mudar durante a iteração como um " "efeito colateral do código ou atividade em outros threads." -#: ../../library/sys.rst:1316 +#: ../../library/sys.rst:1349 msgid "" "The list of the original command line arguments passed to the Python " "executable." msgstr "" -"A lista dos argumentos originais da linha de comando passados ​​para o " +"A lista dos argumentos originais da linha de comando passados para o " "executável Python." -#: ../../library/sys.rst:1319 +#: ../../library/sys.rst:1352 msgid "" "The elements of :data:`sys.orig_argv` are the arguments to the Python " "interpreter, while the elements of :data:`sys.argv` are the arguments to the " @@ -2197,7 +2308,7 @@ msgstr "" "programa do usuário. Os argumentos consumidos pelo próprio interpretador " "estarão presentes em :data:`sys.orig_argv` e ausentes em :data:`sys.argv`." -#: ../../library/sys.rst:1331 +#: ../../library/sys.rst:1364 msgid "" "A list of strings that specifies the search path for modules. Initialized " "from the environment variable :envvar:`PYTHONPATH`, plus an installation-" @@ -2207,7 +2318,7 @@ msgstr "" "Inicializado a partir da variável de ambiente :envvar:`PYTHONPATH`, mais um " "padrão dependente da instalação." -#: ../../library/sys.rst:1335 +#: ../../library/sys.rst:1368 msgid "" "By default, as initialized upon program startup, a potentially unsafe path " "is prepended to :data:`sys.path` (*before* the entries inserted as a result " @@ -2217,14 +2328,14 @@ msgstr "" "potencialmente inseguro é adicionado ao :data:`sys.path` (*antes* das " "entradas inseridas como resultado de :envvar:`PYTHONPATH`):" -#: ../../library/sys.rst:1339 +#: ../../library/sys.rst:1372 msgid "" "``python -m module`` command line: prepend the current working directory." msgstr "" "A linha de comando ``python -m módulo``: adiciona o diretório de trabalho " "atual" -#: ../../library/sys.rst:1341 +#: ../../library/sys.rst:1374 msgid "" "``python script.py`` command line: prepend the script's directory. If it's a " "symbolic link, resolve symbolic links." @@ -2232,7 +2343,7 @@ msgstr "" "A linha de comando ``python script.py``: prefixa o diretório do script. Se " "for um link simbólico, resolve links simbólicos." -#: ../../library/sys.rst:1343 +#: ../../library/sys.rst:1376 msgid "" "``python -c code`` and ``python`` (REPL) command lines: prepend an empty " "string, which means the current working directory." @@ -2240,7 +2351,7 @@ msgstr "" "As linhas de comando ``python -c código`` e ``python`` (REPL): adiciona uma " "string vazia, que indica o diretório de trabalho atual." -#: ../../library/sys.rst:1346 +#: ../../library/sys.rst:1379 msgid "" "To not prepend this potentially unsafe path, use the :option:`-P` command " "line option or the :envvar:`PYTHONSAFEPATH` environment variable." @@ -2249,7 +2360,7 @@ msgstr "" "linha de comando :option:`-P` ou a variável de ambiente :envvar:" "`PYTHONSAFEPATH`." -#: ../../library/sys.rst:1349 +#: ../../library/sys.rst:1382 msgid "" "A program is free to modify this list for its own purposes. Only strings " "should be added to :data:`sys.path`; all other data types are ignored during " @@ -2259,7 +2370,7 @@ msgstr "" "Somente strings devem ser adicionadas a :data:`sys.path`; todos os outros " "tipos de dados são ignorados durante a importação." -#: ../../library/sys.rst:1355 +#: ../../library/sys.rst:1388 msgid "" "Module :mod:`site` This describes how to use .pth files to extend :data:`sys." "path`." @@ -2267,7 +2378,7 @@ msgstr "" "Módulo :mod:`site` Descreve como usar arquivos .pth para estender :data:`sys." "path`." -#: ../../library/sys.rst:1360 +#: ../../library/sys.rst:1393 msgid "" "A list of callables that take a path argument to try to create a :term:" "`finder` for the path. If a finder can be created, it is to be returned by " @@ -2277,11 +2388,11 @@ msgstr "" "um :term:`localizador` para o caminho. Se um localizador puder ser criado, " "ele deve ser retornado pelo chamável, senão, ele levanta :exc:`ImportError`." -#: ../../library/sys.rst:1364 ../../library/sys.rst:1375 +#: ../../library/sys.rst:1397 ../../library/sys.rst:1408 msgid "Originally specified in :pep:`302`." msgstr "Originalmente especificado na :pep:`302`." -#: ../../library/sys.rst:1369 +#: ../../library/sys.rst:1402 msgid "" "A dictionary acting as a cache for :term:`finder` objects. The keys are " "paths that have been passed to :data:`sys.path_hooks` and the values are the " @@ -2289,97 +2400,97 @@ msgid "" "is found on :data:`sys.path_hooks` then ``None`` is stored." msgstr "" "Um dicionário atuando como um cache para objetos do :term:`localizador`. As " -"chaves são caminhos que foram passados ​​para :data:`sys.path_hooks` e os " +"chaves são caminhos que foram passados para :data:`sys.path_hooks` e os " "valores são os localizadores que são encontrados. Se um caminho for um " "caminho de sistema de arquivo válido, mas nenhum localizador for encontrado " "em :data:`sys.path_hooks`, então ``None`` é armazenado." -#: ../../library/sys.rst:1380 +#: ../../library/sys.rst:1413 msgid "A string containing a platform identifier. Known values are:" msgstr "" "Uma string contendo um identificador da plataforma. Valores conhecidos são:" -#: ../../library/sys.rst:1383 +#: ../../library/sys.rst:1416 msgid "System" msgstr "Sistema" -#: ../../library/sys.rst:1383 +#: ../../library/sys.rst:1416 msgid "``platform`` value" msgstr "Valor de ``platform``" -#: ../../library/sys.rst:1385 +#: ../../library/sys.rst:1418 msgid "AIX" msgstr "AIX" -#: ../../library/sys.rst:1385 +#: ../../library/sys.rst:1418 msgid "``'aix'``" msgstr "``'aix'``" -#: ../../library/sys.rst:1386 +#: ../../library/sys.rst:1419 msgid "Android" msgstr "Android" -#: ../../library/sys.rst:1386 +#: ../../library/sys.rst:1419 msgid "``'android'``" msgstr "``'android'``" -#: ../../library/sys.rst:1387 +#: ../../library/sys.rst:1420 msgid "Emscripten" msgstr "Emscripten" -#: ../../library/sys.rst:1387 +#: ../../library/sys.rst:1420 msgid "``'emscripten'``" msgstr "``'emscripten'``" -#: ../../library/sys.rst:1388 +#: ../../library/sys.rst:1421 msgid "iOS" msgstr "iOS" -#: ../../library/sys.rst:1388 +#: ../../library/sys.rst:1421 msgid "``'ios'``" msgstr "``'ios'``" -#: ../../library/sys.rst:1389 +#: ../../library/sys.rst:1422 msgid "Linux" msgstr "Linux" -#: ../../library/sys.rst:1389 +#: ../../library/sys.rst:1422 msgid "``'linux'``" msgstr "``'linux'``" -#: ../../library/sys.rst:1390 +#: ../../library/sys.rst:1423 msgid "macOS" msgstr "macOS" -#: ../../library/sys.rst:1390 +#: ../../library/sys.rst:1423 msgid "``'darwin'``" msgstr "``'darwin'``" -#: ../../library/sys.rst:1391 +#: ../../library/sys.rst:1424 msgid "Windows" msgstr "Windows" -#: ../../library/sys.rst:1391 +#: ../../library/sys.rst:1424 msgid "``'win32'``" msgstr "``'win32'``" -#: ../../library/sys.rst:1392 +#: ../../library/sys.rst:1425 msgid "Windows/Cygwin" msgstr "Windows/Cygwin" -#: ../../library/sys.rst:1392 +#: ../../library/sys.rst:1425 msgid "``'cygwin'``" msgstr "``'cygwin'``" -#: ../../library/sys.rst:1393 +#: ../../library/sys.rst:1426 msgid "WASI" msgstr "WASI" -#: ../../library/sys.rst:1393 +#: ../../library/sys.rst:1426 msgid "``'wasi'``" msgstr "``'wasi'``" -#: ../../library/sys.rst:1396 +#: ../../library/sys.rst:1429 msgid "" "On Unix systems not listed in the table, the value is the lowercased OS name " "as returned by ``uname -s``, with the first part of the version as returned " @@ -2394,7 +2505,15 @@ msgstr "" "construído*. A menos que você queira testar uma versão específica do " "sistema, é recomendável usar o seguinte idioma::" -#: ../../library/sys.rst:1405 +#: ../../library/sys.rst:1435 +msgid "" +"if sys.platform.startswith('freebsd'):\n" +" # FreeBSD-specific code here..." +msgstr "" +"if sys.platform.startswith('freebsd'):\n" +" # Código para FreeBSD aqui..." + +#: ../../library/sys.rst:1438 msgid "" "On Linux, :data:`sys.platform` doesn't contain the major version anymore. It " "is always ``'linux'``, instead of ``'linux2'`` or ``'linux3'``." @@ -2402,7 +2521,7 @@ msgstr "" "No Linux, :data:`sys.platform` não contém mais a versão principal. É sempre " "``'linux'``, em vez de ``'linux2'`` ou ``'linux3'``." -#: ../../library/sys.rst:1409 +#: ../../library/sys.rst:1442 msgid "" "On AIX, :data:`sys.platform` doesn't contain the major version anymore. It " "is always ``'aix'``, instead of ``'aix5'`` or ``'aix7'``." @@ -2410,7 +2529,7 @@ msgstr "" "No AIX, :data:`sys.platform` não contém mais a versão principal. É sempre " "``'aix'``, em vez de ``'aix5'`` ou ``'aix7'``." -#: ../../library/sys.rst:1413 +#: ../../library/sys.rst:1446 msgid "" "On Android, :data:`sys.platform` now returns ``'android'`` rather than " "``'linux'``." @@ -2418,7 +2537,7 @@ msgstr "" "No Android, :data:`sys.platform` agora retorna ``'android'`` em vez de " "``'linux'``." -#: ../../library/sys.rst:1419 +#: ../../library/sys.rst:1452 msgid "" ":data:`os.name` has a coarser granularity. :func:`os.uname` gives system-" "dependent version information." @@ -2426,7 +2545,7 @@ msgstr "" ":data:`os.name` tem uma granularidade mais substancial. :func:`os.uname` " "fornece informações de versão dependentes do sistema." -#: ../../library/sys.rst:1422 +#: ../../library/sys.rst:1455 msgid "" "The :mod:`platform` module provides detailed checks for the system's " "identity." @@ -2434,7 +2553,7 @@ msgstr "" "O módulo :mod:`platform` fornece verificações detalhadas sobre a " "identificação do sistema." -#: ../../library/sys.rst:1428 +#: ../../library/sys.rst:1461 msgid "" "Name of the platform-specific library directory. It is used to build the " "path of standard library and the paths of installed extension modules." @@ -2443,7 +2562,7 @@ msgstr "" "construir o caminho da biblioteca padrão e os caminhos dos módulos de " "extensão instalados." -#: ../../library/sys.rst:1431 +#: ../../library/sys.rst:1464 msgid "" "It is equal to ``\"lib\"`` on most platforms. On Fedora and SuSE, it is " "equal to ``\"lib64\"`` on 64-bit platforms which gives the following ``sys." @@ -2453,7 +2572,7 @@ msgstr "" "a ``\"lib64\"`` em plataformas de 64 bits, o que fornece os seguintes " "caminhos ``sys.path`` (onde ``X.Y`` é a versão ``major.minor`` do Python):" -#: ../../library/sys.rst:1435 +#: ../../library/sys.rst:1468 msgid "" "``/usr/lib64/pythonX.Y/``: Standard library (like ``os.py`` of the :mod:`os` " "module)" @@ -2461,7 +2580,7 @@ msgstr "" "``/usr/lib64/pythonX.Y/``: Biblioteca padrão (como ``os.py`` do módulo :mod:" "`os`)" -#: ../../library/sys.rst:1437 +#: ../../library/sys.rst:1470 msgid "" "``/usr/lib64/pythonX.Y/lib-dynload/``: C extension modules of the standard " "library (like the :mod:`errno` module, the exact filename is platform " @@ -2471,7 +2590,7 @@ msgstr "" "padrão (como o módulo :mod:`errno`, o nome exato do arquivo é específico da " "plataforma)" -#: ../../library/sys.rst:1440 +#: ../../library/sys.rst:1473 msgid "" "``/usr/lib/pythonX.Y/site-packages/`` (always use ``lib``, not :data:`sys." "platlibdir`): Third-party modules" @@ -2479,7 +2598,7 @@ msgstr "" "``/usr/lib/pythonX.Y/site-packages/`` (sempre usa ``lib``, não :data:`sys." "platlibdir`): Módulos de terceiros" -#: ../../library/sys.rst:1442 +#: ../../library/sys.rst:1475 msgid "" "``/usr/lib64/pythonX.Y/site-packages/``: C extension modules of third-party " "packages" @@ -2487,7 +2606,7 @@ msgstr "" "``/usr/lib64/pythonX.Y/site-packages/``: Módulos de extensão C de pacotes de " "terceiros" -#: ../../library/sys.rst:1450 +#: ../../library/sys.rst:1483 msgid "" "A string giving the site-specific directory prefix where the platform " "independent Python files are installed; on Unix, the default is :file:`/usr/" @@ -2501,7 +2620,7 @@ msgstr "" "com o argumento :option:`--prefix` para o script :program:`configure`. Veja :" "ref:`installation_paths` para caminhos derivados." -#: ../../library/sys.rst:1456 +#: ../../library/sys.rst:1489 msgid "" "If a :ref:`virtual environment ` is in effect, this value will be " "changed in ``site.py`` to point to the virtual environment. The value for " @@ -2511,7 +2630,7 @@ msgstr "" "alterado em ``site.py`` para apontar para o ambiente virtual. O valor para a " "instalação do Python ainda estará disponível, via :data:`base_prefix`." -#: ../../library/sys.rst:1471 +#: ../../library/sys.rst:1504 msgid "" "Strings specifying the primary and secondary prompt of the interpreter. " "These are only defined if the interpreter is in interactive mode. Their " @@ -2527,7 +2646,7 @@ msgstr "" "vez que o interpretador se prepara para ler um novo comando interativo; isso " "pode ser usado para implementar um prompt dinâmico." -#: ../../library/sys.rst:1481 +#: ../../library/sys.rst:1514 msgid "" "Set the flags used by the interpreter for :c:func:`dlopen` calls, such as " "when the interpreter loads extension modules. Among other things, this will " @@ -2537,7 +2656,7 @@ msgid "" "values can be found in the :mod:`os` module (:samp:`RTLD_{xxx}` constants, e." "g. :const:`os.RTLD_LAZY`)." msgstr "" -"Define os sinalizadores usados ​​pelo interpretador para chamadas :c:func:" +"Define os sinalizadores usados pelo interpretador para chamadas :c:func:" "`dlopen`, como quando o interpretador carrega módulos de extensão. Entre " "outras coisas, isso habilitará uma resolução preguiçosa de símbolos ao " "importar um módulo, se chamado como ``sys.setdlopenflags(0)``. Para " @@ -2546,7 +2665,7 @@ msgstr "" "sinalizadores podem ser encontrados no módulo :mod:`os` (constantes :samp:" "`RTLD_{xxx}`, por exemplo, :const:`os.RTLD_LAZY`)." -#: ../../library/sys.rst:1493 +#: ../../library/sys.rst:1526 msgid "" "Set the :ref:`integer string conversion length limitation " "` used by this interpreter. See also :func:" @@ -2556,7 +2675,7 @@ msgstr "" "` usada por este interpretador. Veja também :func:" "`get_int_max_str_digits`." -#: ../../library/sys.rst:1505 +#: ../../library/sys.rst:1538 msgid "" "Set the system's profile function, which allows you to implement a Python " "source code profiler in Python. See chapter :ref:`profile` for more " @@ -2583,7 +2702,7 @@ msgstr "" "pode simplesmente retornar ``None``. Um erro na função de perfil fará com " "que sua própria definição seja removida." -#: ../../library/sys.rst:1517 +#: ../../library/sys.rst:1550 msgid "" "The same tracing mechanism is used for :func:`!setprofile` as :func:" "`settrace`. To trace calls with :func:`!setprofile` inside a tracing " @@ -2594,7 +2713,7 @@ msgstr "" "uma função de rastreamento (por exemplo, em um ponto de interrupção do " "depurador), consulte :func:`call_tracing`." -#: ../../library/sys.rst:1521 +#: ../../library/sys.rst:1554 msgid "" "Profile functions should have three arguments: *frame*, *event*, and *arg*. " "*frame* is the current stack frame. *event* is a string: ``'call'``, " @@ -2606,15 +2725,15 @@ msgstr "" "``'return'``, ``'c_call'``, ``'c_return'`` ou ``'c_exception'``. *arg* " "depende do tipo de evento." -#: ../../library/sys.rst:1526 ../../library/sys.rst:1613 +#: ../../library/sys.rst:1559 ../../library/sys.rst:1646 msgid "The events have the following meaning:" msgstr "Os eventos têm o seguinte significado:" -#: ../../library/sys.rst:1528 ../../library/sys.rst:1615 +#: ../../library/sys.rst:1561 ../../library/sys.rst:1648 msgid "``'call'``" msgstr "``'call'``" -#: ../../library/sys.rst:1529 +#: ../../library/sys.rst:1562 msgid "" "A function is called (or some other code block entered). The profile " "function is called; *arg* is ``None``." @@ -2622,11 +2741,11 @@ msgstr "" "Uma função é chamada (ou algum outro bloco de código é inserido). A função " "de perfil é chamada; *arg* é ``None``." -#: ../../library/sys.rst:1532 ../../library/sys.rst:1630 +#: ../../library/sys.rst:1565 ../../library/sys.rst:1663 msgid "``'return'``" msgstr "``'return'``" -#: ../../library/sys.rst:1533 +#: ../../library/sys.rst:1566 msgid "" "A function (or other code block) is about to return. The profile function " "is called; *arg* is the value that will be returned, or ``None`` if the " @@ -2636,11 +2755,11 @@ msgstr "" "perfilação é chamada; *arg* é o valor que será retornado, ou ``None`` se o " "evento for causado por uma exceção sendo levantada." -#: ../../library/sys.rst:1537 +#: ../../library/sys.rst:1570 msgid "``'c_call'``" msgstr "``'c_call'``" -#: ../../library/sys.rst:1538 +#: ../../library/sys.rst:1571 msgid "" "A C function is about to be called. This may be an extension function or a " "built-in. *arg* is the C function object." @@ -2648,23 +2767,23 @@ msgstr "" "Uma função C está prestes a ser chamada. Pode ser uma função de extensão ou " "uma embutida. *arg* é o objeto da função C." -#: ../../library/sys.rst:1541 +#: ../../library/sys.rst:1574 msgid "``'c_return'``" msgstr "``'c_return'``" -#: ../../library/sys.rst:1542 +#: ../../library/sys.rst:1575 msgid "A C function has returned. *arg* is the C function object." msgstr "Uma função C foi retornada. *arg* é o objeto da função C." -#: ../../library/sys.rst:1544 +#: ../../library/sys.rst:1577 msgid "``'c_exception'``" msgstr "``'c_exception'``" -#: ../../library/sys.rst:1545 +#: ../../library/sys.rst:1578 msgid "A C function has raised an exception. *arg* is the C function object." msgstr "Uma função C levantou uma exceção. *arg* é o objeto da função C." -#: ../../library/sys.rst:1547 +#: ../../library/sys.rst:1580 msgid "" "Raises an :ref:`auditing event ` ``sys.setprofile`` with no " "arguments." @@ -2672,7 +2791,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``sys.setprofile`` sem " "argumentos." -#: ../../library/sys.rst:1552 +#: ../../library/sys.rst:1585 msgid "" "Set the maximum depth of the Python interpreter stack to *limit*. This " "limit prevents infinite recursion from causing an overflow of the C stack " @@ -2682,7 +2801,7 @@ msgstr "" "Esse limite impede que a recursão infinita cause um estouro da pilha C e " "trave o Python." -#: ../../library/sys.rst:1556 +#: ../../library/sys.rst:1589 msgid "" "The highest possible limit is platform-dependent. A user may need to set " "the limit higher when they have a program that requires deep recursion and a " @@ -2694,7 +2813,7 @@ msgstr "" "profunda e uma plataforma que dê suporte a um limite mais alto. Isso deve " "ser feito com cuidado, porque um limite muito alto pode levar a uma falha." -#: ../../library/sys.rst:1561 +#: ../../library/sys.rst:1594 msgid "" "If the new limit is too low at the current recursion depth, a :exc:" "`RecursionError` exception is raised." @@ -2702,7 +2821,7 @@ msgstr "" "Se o novo limite for muito baixo na profundidade de recursão atual, uma " "exceção :exc:`RecursionError` será levantada." -#: ../../library/sys.rst:1564 +#: ../../library/sys.rst:1597 msgid "" "A :exc:`RecursionError` exception is now raised if the new limit is too low " "at the current recursion depth." @@ -2710,7 +2829,7 @@ msgstr "" "Uma exceção :exc:`RecursionError` agora é levantada se o novo limite for " "muito baixo na profundidade de recursão atual." -#: ../../library/sys.rst:1571 +#: ../../library/sys.rst:1604 msgid "" "Set the interpreter's thread switch interval (in seconds). This floating-" "point value determines the ideal duration of the \"timeslices\" allocated to " @@ -2728,7 +2847,7 @@ msgstr "" "final do intervalo é uma decisão do sistema operacional. O interpretador não " "tem seu próprio escalonador." -#: ../../library/sys.rst:1588 +#: ../../library/sys.rst:1621 msgid "" "Set the system's trace function, which allows you to implement a Python " "source code debugger in Python. The function is thread-specific; for a " @@ -2742,7 +2861,7 @@ msgstr "" "trace usando :func:`settrace` para cada thread que está sendo depurada ou " "usar :func:`threading.settrace`." -#: ../../library/sys.rst:1593 +#: ../../library/sys.rst:1626 msgid "" "Trace functions should have three arguments: *frame*, *event*, and *arg*. " "*frame* is the current stack frame. *event* is a string: ``'call'``, " @@ -2754,7 +2873,7 @@ msgstr "" "``'line'``, ``'return'``, ``'exception'`` ou ``'opcode'``. *arg* depende do " "tipo de evento." -#: ../../library/sys.rst:1598 +#: ../../library/sys.rst:1631 msgid "" "The trace function is invoked (with *event* set to ``'call'``) whenever a " "new local scope is entered; it should return a reference to a local trace " @@ -2766,7 +2885,7 @@ msgstr "" "a uma função de rastreamento local a ser usada para o novo escopo, ou " "``None`` se o escopo não deve ser rastreado." -#: ../../library/sys.rst:1603 +#: ../../library/sys.rst:1636 msgid "" "The local trace function should return a reference to itself, or to another " "function which would then be used as the local trace function for the scope." @@ -2775,7 +2894,7 @@ msgstr "" "outra função que seria então usada como a função de rastreamento local para " "o escopo." -#: ../../library/sys.rst:1606 +#: ../../library/sys.rst:1639 msgid "" "If there is any error occurred in the trace function, it will be unset, just " "like ``settrace(None)`` is called." @@ -2783,7 +2902,7 @@ msgstr "" "Se ocorrer algum erro na função de rastreamento, ela será desativada, assim " "como ``settrace(None)`` é chamado." -#: ../../library/sys.rst:1610 +#: ../../library/sys.rst:1643 msgid "" "Tracing is disabled while calling the trace function (e.g. a function set " "by :func:`!settrace`). For recursive tracing see :func:`call_tracing`." @@ -2792,7 +2911,7 @@ msgstr "" "exemplo, uma função definida por :func:`!settrace`). Para rastreamento " "recursivo, veja :func:`call_tracing`." -#: ../../library/sys.rst:1616 +#: ../../library/sys.rst:1649 msgid "" "A function is called (or some other code block entered). The global trace " "function is called; *arg* is ``None``; the return value specifies the local " @@ -2802,11 +2921,11 @@ msgstr "" "de rastreamento global é chamada; *arg* é ``None``; o valor de retorno " "especifica a função de rastreamento local." -#: ../../library/sys.rst:1620 +#: ../../library/sys.rst:1653 msgid "``'line'``" msgstr "``'line'``" -#: ../../library/sys.rst:1621 +#: ../../library/sys.rst:1654 msgid "" "The interpreter is about to execute a new line of code or re-execute the " "condition of a loop. The local trace function is called; *arg* is ``None``; " @@ -2823,7 +2942,7 @@ msgstr "" "desabilitados para um quadro definindo :attr:`~frame.f_trace_lines` como :" "const:`False` naquele :ref:`quadro `." -#: ../../library/sys.rst:1631 +#: ../../library/sys.rst:1664 msgid "" "A function (or other code block) is about to return. The local trace " "function is called; *arg* is the value that will be returned, or ``None`` if " @@ -2835,11 +2954,11 @@ msgstr "" "``None`` se o evento for causado por uma exceção sendo levantada. O valor de " "retorno da função de rastreamento é ignorado." -#: ../../library/sys.rst:1636 +#: ../../library/sys.rst:1669 msgid "``'exception'``" msgstr "``'exception'``" -#: ../../library/sys.rst:1637 +#: ../../library/sys.rst:1670 msgid "" "An exception has occurred. The local trace function is called; *arg* is a " "tuple ``(exception, value, traceback)``; the return value specifies the new " @@ -2849,11 +2968,11 @@ msgstr "" "tupla ``(exception, value, traceback)``; o valor de retorno especifica a " "nova função de rastreamento local." -#: ../../library/sys.rst:1641 +#: ../../library/sys.rst:1674 msgid "``'opcode'``" msgstr "``'opcode'``" -#: ../../library/sys.rst:1642 +#: ../../library/sys.rst:1675 msgid "" "The interpreter is about to execute a new opcode (see :mod:`dis` for opcode " "details). The local trace function is called; *arg* is ``None``; the return " @@ -2869,7 +2988,7 @@ msgstr "" "explicitamente solicitados definindo :attr:`~frame.f_trace_opcodes` como :" "const:`True` no :ref:`quadro `." -#: ../../library/sys.rst:1649 +#: ../../library/sys.rst:1682 msgid "" "Note that as an exception is propagated down the chain of callers, an " "``'exception'`` event is generated at each level." @@ -2877,7 +2996,7 @@ msgstr "" "Observe que, à medida que uma exceção é propagada pela cadeia de chamadores, " "um evento ``'exception'`` é gerado em cada nível." -#: ../../library/sys.rst:1652 +#: ../../library/sys.rst:1685 msgid "" "For more fine-grained usage, it's possible to set a trace function by " "assigning ``frame.f_trace = tracefunc`` explicitly, rather than relying on " @@ -2902,13 +3021,13 @@ msgstr "" "simplesmente retorna ``None`` para se desabilitar imediatamente em cada " "quadro)." -#: ../../library/sys.rst:1663 +#: ../../library/sys.rst:1696 msgid "For more information on code and frame objects, refer to :ref:`types`." msgstr "" "Para mais informações sobre objetos de código e quadro, consulte :ref:" "`types`." -#: ../../library/sys.rst:1665 +#: ../../library/sys.rst:1698 msgid "" "Raises an :ref:`auditing event ` ``sys.settrace`` with no " "arguments." @@ -2916,7 +3035,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``sys.settrace`` sem " "argumentos." -#: ../../library/sys.rst:1669 +#: ../../library/sys.rst:1702 msgid "" "The :func:`settrace` function is intended only for implementing debuggers, " "profilers, coverage tools and the like. Its behavior is part of the " @@ -2928,7 +3047,7 @@ msgstr "" "parte da plataforma de implementação, e não da definição da linguagem e, " "portanto, pode não estar disponível em todas as implementações do Python." -#: ../../library/sys.rst:1676 +#: ../../library/sys.rst:1709 msgid "" "``'opcode'`` event type added; :attr:`~frame.f_trace_lines` and :attr:" "`~frame.f_trace_opcodes` attributes added to frames" @@ -2936,7 +3055,7 @@ msgstr "" "Tipo de evento ``'opcode'`` adicionado; atributos :attr:`~frame." "f_trace_lines` e :attr:`~frame.f_trace_opcodes` adicionados a quadros" -#: ../../library/sys.rst:1681 +#: ../../library/sys.rst:1714 msgid "" "Accepts two optional keyword arguments which are callables that accept an :" "term:`asynchronous generator iterator` as an argument. The *firstiter* " @@ -2950,7 +3069,7 @@ msgstr "" "*finalizer* será chamado quando um gerador assíncrono estiver prestes a ser " "coletado como lixo." -#: ../../library/sys.rst:1687 +#: ../../library/sys.rst:1720 msgid "" "Raises an :ref:`auditing event ` ``sys." "set_asyncgen_hooks_firstiter`` with no arguments." @@ -2958,7 +3077,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``sys." "set_asyncgen_hooks_firstiter`` sem argumentos." -#: ../../library/sys.rst:1689 +#: ../../library/sys.rst:1722 msgid "" "Raises an :ref:`auditing event ` ``sys." "set_asyncgen_hooks_finalizer`` with no arguments." @@ -2966,7 +3085,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``sys." "set_asyncgen_hooks_finalizer`` sem argumentos." -#: ../../library/sys.rst:1691 +#: ../../library/sys.rst:1724 msgid "" "Two auditing events are raised because the underlying API consists of two " "calls, each of which must raise its own event." @@ -2974,7 +3093,7 @@ msgstr "" "Dois eventos de auditoria são gerados porque a API subjacente consiste em " "duas chamadas, cada uma das quais deve levantar seu próprio evento." -#: ../../library/sys.rst:1694 +#: ../../library/sys.rst:1727 msgid "" "See :pep:`525` for more details, and for a reference example of a " "*finalizer* method see the implementation of ``asyncio.Loop." @@ -2984,7 +3103,7 @@ msgstr "" "método *finalizer* veja a implementação de ``asyncio.Loop." "shutdown_asyncgens`` em :source:`Lib/asyncio/base_events.py`" -#: ../../library/sys.rst:1706 +#: ../../library/sys.rst:1739 msgid "" "Allows enabling or disabling coroutine origin tracking. When enabled, the " "``cr_origin`` attribute on coroutine objects will contain a tuple of " @@ -2998,7 +3117,7 @@ msgstr "" "descrevendo o traceback onde o objeto corrotina foi criado, com a chamada " "mais recente primeiro. Quando desabilitado, ``cr_origin`` será ``None``." -#: ../../library/sys.rst:1713 +#: ../../library/sys.rst:1746 msgid "" "To enable, pass a *depth* value greater than zero; this sets the number of " "frames whose information will be captured. To disable, pass set *depth* to " @@ -3008,109 +3127,131 @@ msgstr "" "de quadros cujas informações serão capturadas. Para desabilitar, defina " "*depth* para zero." -#: ../../library/sys.rst:1717 +#: ../../library/sys.rst:1750 msgid "This setting is thread-specific." msgstr "Esta configuração é específica do thread." -#: ../../library/sys.rst:1727 +#: ../../library/sys.rst:1760 msgid "" "Activate the stack profiler trampoline *backend*. The only supported backend " "is ``\"perf\"``." msgstr "" +"Ativa o trampolim do perfilador de pilha *backend*. O único backend " +"suportado é ``\"perf\"``." -#: ../../library/sys.rst:1730 ../../library/sys.rst:1745 -#: ../../library/sys.rst:1753 -msgid ":ref:`Availability `: Linux." -msgstr ":ref:`Disponibilidade `: Linux." - -#: ../../library/sys.rst:1736 +#: ../../library/sys.rst:1769 msgid ":ref:`perf_profiling`" msgstr ":ref:`perf_profiling`" -#: ../../library/sys.rst:1737 +#: ../../library/sys.rst:1770 msgid "https://perf.wiki.kernel.org" msgstr "https://perf.wiki.kernel.org" -#: ../../library/sys.rst:1741 +#: ../../library/sys.rst:1774 msgid "Deactivate the current stack profiler trampoline backend." -msgstr "" +msgstr "Desativa o backend trampolim do perfilador de pilha atual." -#: ../../library/sys.rst:1743 +#: ../../library/sys.rst:1776 msgid "If no stack profiler is activated, this function has no effect." msgstr "" +"Se nenhum perfilador de pilha estiver ativado, esta função não terá efeito." -#: ../../library/sys.rst:1751 +#: ../../library/sys.rst:1784 msgid "Return ``True`` if a stack profiler trampoline is active." -msgstr "" +msgstr "Retorna ``True`` se um trampolim de perfilador de pilha estiver ativo." -#: ../../library/sys.rst:1759 +#: ../../library/sys.rst:1792 msgid "" "Changes the :term:`filesystem encoding and error handler` to 'mbcs' and " "'replace' respectively, for consistency with versions of Python prior to 3.6." msgstr "" +"Altera :term:`tratador de erros e codificação do sistema de arquivos` para " +"'replace' e 'mbcs' respectivamente, para consistência com versões do Python " +"anteriores à 3.6." -#: ../../library/sys.rst:1763 +#: ../../library/sys.rst:1796 msgid "" "This is equivalent to defining the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` " "environment variable before launching Python." msgstr "" +"Isso é equivalente a definir a variável de ambiente :envvar:" +"`PYTHONLEGACYWINDOWSFSENCODING` antes de iniciar o Python." -#: ../../library/sys.rst:1766 +#: ../../library/sys.rst:1799 msgid "" "See also :func:`sys.getfilesystemencoding` and :func:`sys." "getfilesystemencodeerrors`." msgstr "" +"Veja também :func:`sys.getfilesystemencoding` e :func:`sys." +"getfilesystemencodeerrors`." -#: ../../library/sys.rst:1772 +#: ../../library/sys.rst:1805 msgid "" "Changing the filesystem encoding after Python startup is risky because the " "old fsencoding or paths encoded by the old fsencoding may be cached " "somewhere. Use :envvar:`PYTHONLEGACYWINDOWSFSENCODING` instead." msgstr "" +"Alterar a codificação do sistema de arquivos após a inicialização do Python " +"é arriscado porque o fsencoding antigo ou os caminhos codificados pelo " +"fsencoding antigo podem estar armazenados em cache em algum lugar. Use :" +"envvar:`PYTHONLEGACYWINDOWSFSENCODING` em vez disso." -#: ../../library/sys.rst:1776 +#: ../../library/sys.rst:1809 msgid "See :pep:`529` for more details." msgstr "Veja :pep:`529` para mais detalhes." -#: ../../library/sys.rst:1779 +#: ../../library/sys.rst:1812 msgid "Use :envvar:`PYTHONLEGACYWINDOWSFSENCODING` instead." -msgstr "" +msgstr "Use :envvar:`PYTHONLEGACYWINDOWSFSENCODING`." -#: ../../library/sys.rst:1786 +#: ../../library/sys.rst:1819 msgid "" ":term:`File objects ` used by the interpreter for standard " "input, output and errors:" msgstr "" +":term:`Objetos arquivo ` usados pelo interpretador para entrada " +"padrão, saída e erros:" -#: ../../library/sys.rst:1789 +#: ../../library/sys.rst:1822 msgid "" "``stdin`` is used for all interactive input (including calls to :func:" "`input`);" msgstr "" +"``stdin`` é usado para todas as entradas interativas (incluindo chamadas " +"para :func:`input`);" -#: ../../library/sys.rst:1791 +#: ../../library/sys.rst:1824 msgid "" "``stdout`` is used for the output of :func:`print` and :term:`expression` " "statements and for the prompts of :func:`input`;" msgstr "" +"``stdout`` é usado para a saída das instruções :func:`print` e :term:" +"`expressões ` e para os prompts de :func:`input`;" -#: ../../library/sys.rst:1793 +#: ../../library/sys.rst:1826 msgid "The interpreter's own prompts and its error messages go to ``stderr``." msgstr "" +"Os prompts do próprio interpretador e suas mensagens de erro vão para " +"``stderr``." -#: ../../library/sys.rst:1795 +#: ../../library/sys.rst:1828 msgid "" "These streams are regular :term:`text files ` like those returned " "by the :func:`open` function. Their parameters are chosen as follows:" msgstr "" +"Esses fluxos são :term:`arquivos texto ` regulares como aqueles " +"retornados pela função :func:`open`. Seus parâmetros são escolhidos da " +"seguinte forma:" -#: ../../library/sys.rst:1799 +#: ../../library/sys.rst:1832 msgid "" "The encoding and error handling are is initialized from :c:member:`PyConfig." "stdio_encoding` and :c:member:`PyConfig.stdio_errors`." msgstr "" +"A codificação e o tratamento de erros são inicializados a partir de :c:" +"member:`PyConfig.stdio_encoding` e :c:member:`PyConfig.stdio_errors`." -#: ../../library/sys.rst:1802 +#: ../../library/sys.rst:1835 msgid "" "On Windows, UTF-8 is used for the console device. Non-character devices " "such as disk files and pipes use the system locale encoding (i.e. the ANSI " @@ -3120,15 +3261,27 @@ msgid "" "defaults to the system :term:`locale encoding` if the process is not " "initially attached to a console." msgstr "" +"No Windows, o UTF-8 é usado para o dispositivo de console. Dispositivos não-" +"caracteres, como arquivos de disco e pipes, usam a codificação da localidade " +"do sistema (ou seja, a página de código ANSI). Dispositivos de caracteres " +"não-console, como NUL (ou seja, onde ``isatty()`` retorna ``True``) usam o " +"valor das páginas de código de entrada e saída do console na inicialização, " +"respectivamente para stdin e stdout/stderr. Isso assume como padrão a :term:" +"`codificação da localidade` do sistema se o processo não for inicialmente " +"anexado a um console." -#: ../../library/sys.rst:1811 +#: ../../library/sys.rst:1844 msgid "" "The special behaviour of the console can be overridden by setting the " "environment variable PYTHONLEGACYWINDOWSSTDIO before starting Python. In " "that case, the console codepages are used as for any other character device." msgstr "" +"O comportamento especial do console pode ser substituído definindo a " +"variável de ambiente PYTHONLEGACYWINDOWSSTDIO antes de iniciar o Python. " +"Nesse caso, as páginas de código do console são usadas como para qualquer " +"outro dispositivo de caractere." -#: ../../library/sys.rst:1816 +#: ../../library/sys.rst:1849 msgid "" "Under all platforms, you can override the character encoding by setting the :" "envvar:`PYTHONIOENCODING` environment variable before starting Python or by " @@ -3136,8 +3289,14 @@ msgid "" "`PYTHONUTF8` environment variable. However, for the Windows console, this " "only applies when :envvar:`PYTHONLEGACYWINDOWSSTDIO` is also set." msgstr "" +"Em todas as plataformas, você pode substituir a codificação de caracteres " +"definindo a variável de ambiente :envvar:`PYTHONIOENCODING` antes de iniciar " +"o Python ou usando a nova opção de linha de comando :option:`-X` ``utf8`` e " +"a variável de ambiente :envvar:`PYTHONUTF8`. No entanto, para o console do " +"Windows, isso só se aplica quando :envvar:`PYTHONLEGACYWINDOWSSTDIO` também " +"está definido." -#: ../../library/sys.rst:1823 +#: ../../library/sys.rst:1856 msgid "" "When interactive, the ``stdout`` stream is line-buffered. Otherwise, it is " "block-buffered like regular text files. The ``stderr`` stream is line-" @@ -3145,126 +3304,168 @@ msgid "" "the :option:`-u` command-line option or setting the :envvar:" "`PYTHONUNBUFFERED` environment variable." msgstr "" +"Quando interativo, o fluxo ``stdout`` é armazenado em buffer de linha. Caso " +"contrário, ele é armazenado em buffer de bloco como arquivos texto comuns. O " +"fluxo ``stderr`` é armazenado em buffer de linha em ambos os casos. Você " +"pode tornar ambos os fluxos sem buffer passando a opção de linha de comando :" +"option:`-u` ou definindo a variável de ambiente :envvar:`PYTHONUNBUFFERED`." -#: ../../library/sys.rst:1829 +#: ../../library/sys.rst:1862 msgid "" "Non-interactive ``stderr`` is now line-buffered instead of fully buffered." msgstr "" +"``stderr`` não interativo agora é armazenado em buffer de linha em vez de " +"totalmente armazenado em buffer." -#: ../../library/sys.rst:1835 +#: ../../library/sys.rst:1868 msgid "" "To write or read binary data from/to the standard streams, use the " "underlying binary :data:`~io.TextIOBase.buffer` object. For example, to " "write bytes to :data:`stdout`, use ``sys.stdout.buffer.write(b'abc')``." msgstr "" +"Para escrever ou ler dados binários de/para os fluxos padrão, use o objeto " +"binário subjacente :data:`~io.TextIOBase.buffer`. Por exemplo, para escrever " +"bytes em :data:`stdout`, use ``sys.stdout.buffer.write(b'abc')``." -#: ../../library/sys.rst:1839 +#: ../../library/sys.rst:1872 msgid "" "However, if you are writing a library (and do not control in which context " "its code will be executed), be aware that the standard streams may be " "replaced with file-like objects like :class:`io.StringIO` which do not " "support the :attr:`!buffer` attribute." msgstr "" +"Entretanto, se você estiver escrevendo uma biblioteca (e não controlar em " +"qual contexto seu código será executado), esteja ciente de que os fluxos " +"padrão podem ser substituídos por objetos arquivo ou similar, como :class:" +"`io.StringIO`, que não oferecem suporte ao atributo :attr:`!buffer`." -#: ../../library/sys.rst:1849 +#: ../../library/sys.rst:1882 msgid "" "These objects contain the original values of ``stdin``, ``stderr`` and " "``stdout`` at the start of the program. They are used during finalization, " "and could be useful to print to the actual standard stream no matter if the " "``sys.std*`` object has been redirected." msgstr "" +"Esses objetos contêm os valores originais de ``stdin``, ``stderr`` e " +"``stdout`` no início do programa. Eles são usados durante a finalização e " +"podem ser úteis para imprimir no fluxo padrão real, não importa se o objeto " +"``sys.std*`` foi redirecionado." -#: ../../library/sys.rst:1854 +#: ../../library/sys.rst:1887 msgid "" "It can also be used to restore the actual files to known working file " "objects in case they have been overwritten with a broken object. However, " "the preferred way to do this is to explicitly save the previous stream " "before replacing it, and restore the saved object." msgstr "" +"Ele também pode ser usado para restaurar os arquivos reais para objetos " +"arquivo de trabalho conhecidos, caso tenham sido substituídos por um objeto " +"quebrado. No entanto, a maneira preferida de fazer isso é salvar " +"explicitamente o fluxo anterior antes de substituí-lo e restaurar o objeto " +"salvo." -#: ../../library/sys.rst:1860 +#: ../../library/sys.rst:1893 msgid "" "Under some conditions ``stdin``, ``stdout`` and ``stderr`` as well as the " "original values ``__stdin__``, ``__stdout__`` and ``__stderr__`` can be " "``None``. It is usually the case for Windows GUI apps that aren't connected " "to a console and Python apps started with :program:`pythonw`." msgstr "" +"Sob algumas condições, ``stdin``, ``stdout`` e ``stderr``, bem como os " +"valores originais de ``__stdin__``, ``__stdout__`` e ``__stderr__`` podem " +"ser ``None``. Geralmente é o caso de aplicativos GUI do Windows que não " +"estão conectados a um console e aplicativos Python iniciados com :program:" +"`pythonw`." -#: ../../library/sys.rst:1868 +#: ../../library/sys.rst:1901 msgid "" "A frozenset of strings containing the names of standard library modules." msgstr "" +"Um frozenset de strings contendo os nomes dos módulos da biblioteca padrão." -#: ../../library/sys.rst:1870 +#: ../../library/sys.rst:1903 msgid "" "It is the same on all platforms. Modules which are not available on some " "platforms and modules disabled at Python build are also listed. All module " "kinds are listed: pure Python, built-in, frozen and extension modules. Test " "modules are excluded." msgstr "" +"É o mesmo em todas as plataformas. Módulos que não estão disponíveis em " +"algumas plataformas e módulos desabilitados na construção do Python também " +"são listados. Todos os tipos de módulos são listados: Python puro, módulos " +"embutidos, congelados e de extensão. Módulos de teste são excluídos." -#: ../../library/sys.rst:1875 +#: ../../library/sys.rst:1908 msgid "" "For packages, only the main package is listed: sub-packages and sub-modules " "are not listed. For example, the ``email`` package is listed, but the " "``email.mime`` sub-package and the ``email.message`` sub-module are not " "listed." msgstr "" +"Para pacotes, somente o pacote principal é listado: subpacotes e submódulos " +"não são listados. Por exemplo, o pacote ``email`` é listado, mas o subpacote " +"``email.mime`` e o submódulo ``email.message`` não são listados." -#: ../../library/sys.rst:1880 +#: ../../library/sys.rst:1913 msgid "See also the :data:`sys.builtin_module_names` list." -msgstr "" +msgstr "Veja também a lista de :data:`sys.builtin_module_names`." -#: ../../library/sys.rst:1887 +#: ../../library/sys.rst:1920 msgid "" "A :term:`named tuple` holding information about the thread implementation." msgstr "" +"Uma :term:`tupla nomeada` contendo informações sobre a implementação de " +"threads." -#: ../../library/sys.rst:1892 +#: ../../library/sys.rst:1925 msgid "The name of the thread implementation:" -msgstr "" +msgstr "O nome da implementação da thread:" -#: ../../library/sys.rst:1894 +#: ../../library/sys.rst:1927 msgid "``\"nt\"``: Windows threads" -msgstr "" +msgstr "``\"nt\"``: Threads do Windows" -#: ../../library/sys.rst:1895 +#: ../../library/sys.rst:1928 msgid "``\"pthread\"``: POSIX threads" -msgstr "" +msgstr "``\"pthread\"``: Threads do POSIX" -#: ../../library/sys.rst:1896 +#: ../../library/sys.rst:1929 msgid "" "``\"pthread-stubs\"``: stub POSIX threads (on WebAssembly platforms without " "threading support)" msgstr "" +"``\"pthread-stubs\"``: stubs de threads POSIX (em plataformas WebAssembly " +"que não implementam threads)." -#: ../../library/sys.rst:1898 +#: ../../library/sys.rst:1931 msgid "``\"solaris\"``: Solaris threads" -msgstr "" +msgstr "``\"solaris\"``: Threads do Solaris" -#: ../../library/sys.rst:1902 +#: ../../library/sys.rst:1935 msgid "The name of the lock implementation:" -msgstr "" +msgstr "O nome da implementação de trava." -#: ../../library/sys.rst:1904 +#: ../../library/sys.rst:1937 msgid "``\"semaphore\"``: a lock uses a semaphore" -msgstr "" +msgstr "``\"semaphore\"``: uma trava usa um semáforo" -#: ../../library/sys.rst:1905 +#: ../../library/sys.rst:1938 msgid "``\"mutex+cond\"``: a lock uses a mutex and a condition variable" -msgstr "" +msgstr "``\"mutex+cond\"``: uma trava usa um mutex e uma variável de condição" -#: ../../library/sys.rst:1906 +#: ../../library/sys.rst:1939 msgid "``None`` if this information is unknown" -msgstr "" +msgstr "``None`` se essa informação for desconhecida" -#: ../../library/sys.rst:1910 +#: ../../library/sys.rst:1943 msgid "" "The name and version of the thread library. It is a string, or ``None`` if " "this information is unknown." msgstr "" +"O nome e a versão da biblioteca de threads. É uma string, ou ``None`` se " +"essa informação for desconhecida." -#: ../../library/sys.rst:1918 +#: ../../library/sys.rst:1951 msgid "" "When this variable is set to an integer value, it determines the maximum " "number of levels of traceback information printed when an unhandled " @@ -3272,82 +3473,106 @@ msgid "" "traceback information is suppressed and only the exception type and value " "are printed." msgstr "" +"Quando essa variável é definida como um valor inteiro, ela determina o " +"número máximo de níveis de informações de traceback impressas quando ocorre " +"uma exceção não tratada. O padrão é ``1000``. Quando definida como ``0`` ou " +"menos, todas as informações de traceback são suprimidas e apenas o tipo e o " +"valor da exceção são impressos." -#: ../../library/sys.rst:1926 +#: ../../library/sys.rst:1959 msgid "Handle an unraisable exception." -msgstr "" +msgstr "Manipula uma exceção não levantada" -#: ../../library/sys.rst:1928 +#: ../../library/sys.rst:1961 msgid "" "Called when an exception has occurred but there is no way for Python to " "handle it. For example, when a destructor raises an exception or during " "garbage collection (:func:`gc.collect`)." msgstr "" +"Chamada quando uma exceção ocorreu, mas não há como o Python manipulá-la. " +"Por exemplo, quando um destrutor levanta uma exceção ou durante a coleta de " +"lixo (:func:`gc.collect`)." -#: ../../library/sys.rst:1932 +#: ../../library/sys.rst:1965 msgid "The *unraisable* argument has the following attributes:" -msgstr "" +msgstr "O argumento *unraisable* tem os seguintes atributos:" -#: ../../library/sys.rst:1934 +#: ../../library/sys.rst:1967 msgid ":attr:`!exc_type`: Exception type." -msgstr "" +msgstr ":attr:`!exc_type`: Tipo de exceção." -#: ../../library/sys.rst:1935 +#: ../../library/sys.rst:1968 msgid ":attr:`!exc_value`: Exception value, can be ``None``." -msgstr "" +msgstr ":attr:`!exc_value`: Valor da exceção, pode ser ``None``." -#: ../../library/sys.rst:1936 +#: ../../library/sys.rst:1969 msgid ":attr:`!exc_traceback`: Exception traceback, can be ``None``." -msgstr "" +msgstr ":attr:`!exc_traceback`: Traceback da exceção, pode ser ``None``." -#: ../../library/sys.rst:1937 +#: ../../library/sys.rst:1970 msgid ":attr:`!err_msg`: Error message, can be ``None``." -msgstr "" +msgstr ":attr:`!err_msg`: Mensagem de erro, pode ser ``None``." -#: ../../library/sys.rst:1938 +#: ../../library/sys.rst:1971 msgid ":attr:`!object`: Object causing the exception, can be ``None``." -msgstr "" +msgstr ":attr:`!object`: O objeto que causa a exceção pode ser ``None``." -#: ../../library/sys.rst:1940 +#: ../../library/sys.rst:1973 msgid "" "The default hook formats :attr:`!err_msg` and :attr:`!object` as: " "``f'{err_msg}: {object!r}'``; use \"Exception ignored in\" error message if :" "attr:`!err_msg` is ``None``." msgstr "" +"Os formatos de gancho padrão :attr:`!err_msg` e :attr:`!object` como: " +"``f'{err_msg}: {object!r}'``; usa a mensagem de erro \"Exception ignored " +"in\" se :attr:`!err_msg` for ``None``." -#: ../../library/sys.rst:1944 +#: ../../library/sys.rst:1977 msgid "" ":func:`sys.unraisablehook` can be overridden to control how unraisable " "exceptions are handled." msgstr "" +":func:`sys.unraisablehook` pode ser substituída para controlar como exceções " +"não levantáveis são manipuladas." -#: ../../library/sys.rst:1949 +#: ../../library/sys.rst:1982 msgid ":func:`excepthook` which handles uncaught exceptions." -msgstr "" +msgstr ":func:`excepthook`, que manipula exceções não capturadas." -#: ../../library/sys.rst:1953 +#: ../../library/sys.rst:1986 msgid "" "Storing :attr:`!exc_value` using a custom hook can create a reference cycle. " "It should be cleared explicitly to break the reference cycle when the " "exception is no longer needed." msgstr "" +"Armazena :attr:`!exc_value` usando um gancho personalizado pode criar um " +"ciclo de referência. Ele deve ser limpo explicitamente para quebrar o ciclo " +"de referência quando a exceção não for mais necessária." -#: ../../library/sys.rst:1957 +#: ../../library/sys.rst:1990 msgid "" "Storing :attr:`!object` using a custom hook can resurrect it if it is set to " "an object which is being finalized. Avoid storing :attr:`!object` after the " "custom hook completes to avoid resurrecting objects." msgstr "" +"Armazenar :attr:`!object` usando um gancho personalizado pode ressuscitá-lo " +"se ele for definido como um objeto que está sendo finalizado. Evite " +"armazenar :attr:`!object` após o gancho personalizado ser concluído para " +"evitar ressuscitar objetos." -#: ../../library/sys.rst:1961 ../../library/sys.rst:1963 +#: ../../library/sys.rst:1994 ../../library/sys.rst:1996 msgid "" "Raise an auditing event ``sys.unraisablehook`` with arguments *hook*, " "*unraisable* when an exception that cannot be handled occurs. The " "*unraisable* object is the same as what will be passed to the hook. If no " "hook has been set, *hook* may be ``None``." msgstr "" +"Levanta um evento de auditoria ``sys.unraisablehook`` com argumentos *hook* " +"e *unraisable* quando ocorrer uma exceção que não puder ser manipulada. O " +"objeto *unraisable* é o mesmo que será passado para o gancho. Se nenhum " +"gancho tiver sido definido, *hook* pode ser ``None``." -#: ../../library/sys.rst:1972 +#: ../../library/sys.rst:2005 msgid "" "A string containing the version number of the Python interpreter plus " "additional information on the build number and compiler used. This string " @@ -3355,14 +3580,21 @@ msgid "" "version information out of it, rather, use :data:`version_info` and the " "functions provided by the :mod:`platform` module." msgstr "" +"Uma string contendo o número da versão do interpretador Python mais " +"informações adicionais sobre o número da construção e o compilador usado. " +"Esta string é exibida quando o interpretador interativo é iniciado. Não " +"extraia informações de versão dela, em vez disso, use :data:`version_info` e " +"as funções fornecidas pelo módulo :mod:`platform`." -#: ../../library/sys.rst:1981 +#: ../../library/sys.rst:2014 msgid "" "The C API version for this interpreter. Programmers may find this useful " "when debugging version conflicts between Python and extension modules." msgstr "" +"A versão da API C para este interpretador. Programadores podem achar isso " +"útil ao depurar conflitos de versão entre Python e módulos de extensão." -#: ../../library/sys.rst:1987 +#: ../../library/sys.rst:2020 msgid "" "A tuple containing the five components of the version number: *major*, " "*minor*, *micro*, *releaselevel*, and *serial*. All values except " @@ -3372,19 +3604,29 @@ msgid "" "also be accessed by name, so ``sys.version_info[0]`` is equivalent to ``sys." "version_info.major`` and so on." msgstr "" +"Uma tupla contendo os cinco componentes do número da versão: *major*, " +"*minor*, *micro*, *releaselevel* e *serial*. Todos os valores, exceto " +"*releaselevel*, são inteiros; o nível de versão é ``'alpha'``, ``'beta'``, " +"``'candidate'`` ou ``'final'``. O valor ``version_info`` correspondente à " +"versão 2.0 do Python é ``(2, 0, 0, 'final', 0)``. Os componentes também " +"podem ser acessados por nome, então ``sys.version_info[0]`` é equivalente a " +"``sys.version_info.major`` e assim por diante." -#: ../../library/sys.rst:1995 +#: ../../library/sys.rst:2028 msgid "Added named component attributes." -msgstr "" +msgstr "Adiciona componentes nomeados como atributos." -#: ../../library/sys.rst:2000 +#: ../../library/sys.rst:2033 msgid "" "This is an implementation detail of the warnings framework; do not modify " "this value. Refer to the :mod:`warnings` module for more information on the " "warnings framework." msgstr "" +"Este é um detalhe de implementação do framework de avisos; não modifique " +"este valor. Consulte o módulo :mod:`warnings` para obter mais informações " +"sobre o framework de avisos." -#: ../../library/sys.rst:2007 +#: ../../library/sys.rst:2040 msgid "" "The version number used to form registry keys on Windows platforms. This is " "stored as string resource 1000 in the Python DLL. The value is normally the " @@ -3392,41 +3634,80 @@ msgid "" "in the :mod:`sys` module for informational purposes; modifying this value " "has no effect on the registry keys used by Python." msgstr "" +"O número da versão usado para formar chaves de registro em plataformas " +"Windows. Isso é armazenado como recurso de string 1000 na DLL do Python. O " +"valor normalmente é a versão principal e secundária do interpretador Python " +"em execução. Ele é fornecido no módulo :mod:`sys` para fins informativos; " +"modificar esse valor não tem efeito nas chaves de registro usadas pelo " +"Python." -#: ../../library/sys.rst:2019 +#: ../../library/sys.rst:2052 msgid "" "Namespace containing functions and constants for register callbacks and " "controlling monitoring events. See :mod:`sys.monitoring` for details." msgstr "" +"Espaço de nomes contendo funções e constantes para função de retorno de " +"registro e controle de eventos de monitoramento. Veja :mod:`sys.monitoring` " +"para detalhes." -#: ../../library/sys.rst:2025 +#: ../../library/sys.rst:2058 msgid "" "A dictionary of the various implementation-specific flags passed through " "the :option:`-X` command-line option. Option names are either mapped to " "their values, if given explicitly, or to :const:`True`. Example:" msgstr "" - -#: ../../library/sys.rst:2041 +"Um dicionário dos vários sinalizadores específicos de implementação passados " +"pela opção de linha de comando :option:`-X`. Os nomes de opção são mapeados " +"para seus valores, se fornecidos explicitamente, ou para :const:`True`. " +"Exemplo:" + +#: ../../library/sys.rst:2062 +msgid "" +"$ ./python -Xa=b -Xc\n" +"Python 3.2a3+ (py3k, Oct 16 2010, 20:14:50)\n" +"[GCC 4.4.3] on linux2\n" +"Type \"help\", \"copyright\", \"credits\" or \"license\" for more " +"information.\n" +">>> import sys\n" +">>> sys._xoptions\n" +"{'a': 'b', 'c': True}" +msgstr "" +"$ ./python -Xa=b -Xc\n" +"Python 3.2a3+ (py3k, Oct 16 2010, 20:14:50)\n" +"[GCC 4.4.3] on linux2\n" +"Type \"help\", \"copyright\", \"credits\" or \"license\" for more " +"information.\n" +">>> import sys\n" +">>> sys._xoptions\n" +"{'a': 'b', 'c': True}" + +#: ../../library/sys.rst:2074 msgid "" "This is a CPython-specific way of accessing options passed through :option:`-" "X`. Other implementations may export them through other means, or not at " "all." msgstr "" +"Esta é uma maneira específica do CPython de acessar opções passadas por :" +"option:`-X`. Outras implementações podem exportá-las por outros meios, ou " +"não exportá-las." -#: ../../library/sys.rst:2049 +#: ../../library/sys.rst:2082 msgid "Citations" -msgstr "" +msgstr "Citações" -#: ../../library/sys.rst:2050 +#: ../../library/sys.rst:2083 msgid "" "ISO/IEC 9899:1999. \"Programming languages -- C.\" A public draft of this " "standard is available at https://www.open-std.org/jtc1/sc22/wg14/www/docs/" "n1256.pdf\\ ." msgstr "" +"ISO/IEC 9899:1999. \"Programming languages -- C.\" Um rascunho público " +"desta norma está disponível em https://www.open-std.org/jtc1/sc22/wg14/www/" +"docs/n1256.pdf\\ ." #: ../../library/sys.rst:99 msgid "auditing" -msgstr "" +msgstr "auditoria" #: ../../library/sys.rst:462 msgid "object" @@ -3436,50 +3717,50 @@ msgstr "objeto" msgid "traceback" msgstr "traceback" -#: ../../library/sys.rst:925 ../../library/sys.rst:1501 +#: ../../library/sys.rst:954 ../../library/sys.rst:1534 msgid "profile function" -msgstr "" +msgstr "função de perfilação" -#: ../../library/sys.rst:925 ../../library/sys.rst:1501 +#: ../../library/sys.rst:954 ../../library/sys.rst:1534 msgid "profiler" -msgstr "" +msgstr "perfilador" -#: ../../library/sys.rst:934 ../../library/sys.rst:1584 +#: ../../library/sys.rst:963 ../../library/sys.rst:1617 msgid "trace function" -msgstr "" +msgstr "função de rastreamento" -#: ../../library/sys.rst:934 ../../library/sys.rst:1584 +#: ../../library/sys.rst:963 ../../library/sys.rst:1617 msgid "debugger" msgstr "depurador" -#: ../../library/sys.rst:1329 +#: ../../library/sys.rst:1362 msgid "module" msgstr "módulo" -#: ../../library/sys.rst:1329 +#: ../../library/sys.rst:1362 msgid "search" msgstr "pesquisa" -#: ../../library/sys.rst:1329 +#: ../../library/sys.rst:1362 msgid "path" msgstr "caminho" -#: ../../library/sys.rst:1465 +#: ../../library/sys.rst:1498 msgid "interpreter prompts" -msgstr "" +msgstr "prompts do interpretador" -#: ../../library/sys.rst:1465 +#: ../../library/sys.rst:1498 msgid "prompts, interpreter" -msgstr "" +msgstr "interpretador, prompts" -#: ../../library/sys.rst:1465 +#: ../../library/sys.rst:1498 msgid ">>>" msgstr ">>>" -#: ../../library/sys.rst:1465 +#: ../../library/sys.rst:1498 msgid "interpreter prompt" -msgstr "" +msgstr "prompt do interpretador" -#: ../../library/sys.rst:1465 +#: ../../library/sys.rst:1498 msgid "..." msgstr "..." diff --git a/library/sys_path_init.po b/library/sys_path_init.po index 14b1ffa9b..3f05686c0 100644 --- a/library/sys_path_init.po +++ b/library/sys_path_init.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Julia Rizza , 2022 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2022-11-05 19:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/sysconfig.po b/library/sysconfig.po index 99dfc8c30..ab2a34a78 100644 --- a/library/sysconfig.po +++ b/library/sysconfig.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 -# Risaffi , 2023 -# Hildeberto Abreu Magalhães , 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# Marco Rougeth , 2023 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 01:14+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-02 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -112,6 +106,24 @@ msgstr "Se *name* não for encontrado, retorna ``None``." msgid "Example of usage::" msgstr "Exemplo de uso::" +#: ../../library/sysconfig.rst:56 +msgid "" +">>> import sysconfig\n" +">>> sysconfig.get_config_var('Py_ENABLE_SHARED')\n" +"0\n" +">>> sysconfig.get_config_var('LIBDIR')\n" +"'/usr/local/lib'\n" +">>> sysconfig.get_config_vars('AR', 'CXX')\n" +"['ar', 'g++']" +msgstr "" +">>> import sysconfig\n" +">>> sysconfig.get_config_var('Py_ENABLE_SHARED')\n" +"0\n" +">>> sysconfig.get_config_var('LIBDIR')\n" +"'/usr/local/lib'\n" +">>> sysconfig.get_config_vars('AR', 'CXX')\n" +"['ar', 'g++']" + #: ../../library/sysconfig.rst:68 msgid "Installation paths" msgstr "Caminhos de instalação" @@ -633,10 +645,10 @@ msgstr "" #: ../../library/sysconfig.rst:307 msgid "" "End users should not use this function, but :func:`get_default_scheme` and :" -"func:`get_preferred_scheme()` instead." +"func:`get_preferred_scheme` instead." msgstr "" "Os usuários finais não devem usar esta função, mas :func:" -"`get_default_scheme` e :func:`get_preferred_scheme()`." +"`get_default_scheme` e :func:`get_preferred_scheme`." #: ../../library/sysconfig.rst:315 msgid "" @@ -799,40 +811,44 @@ msgid "Windows will return one of:" msgstr "Windows vai retornar um entre:" #: ../../library/sysconfig.rst:391 -msgid "win-amd64 (64bit Windows on AMD64, aka x86_64, Intel64, and EM64T)" +msgid "win-amd64 (64-bit Windows on AMD64, aka x86_64, Intel64, and EM64T)" msgstr "win-amd64 (Windows 64 bits no AMD64, isto é, x86_64, Intel64 e EM64T)" #: ../../library/sysconfig.rst:392 +msgid "win-arm64 (64-bit Windows on ARM64, aka AArch64)" +msgstr "win-arm64 (Windows 64 bits no ARM64, isto é, AArch64)" + +#: ../../library/sysconfig.rst:393 msgid "win32 (all others - specifically, sys.platform is returned)" msgstr "win32 (todos os demais - especificamente, sys.platform é retornado)" -#: ../../library/sysconfig.rst:394 +#: ../../library/sysconfig.rst:395 msgid "macOS can return:" msgstr "macOS pode retornar:" -#: ../../library/sysconfig.rst:396 +#: ../../library/sysconfig.rst:397 msgid "macosx-10.6-ppc" msgstr "macosx-10.6-ppc" -#: ../../library/sysconfig.rst:397 +#: ../../library/sysconfig.rst:398 msgid "macosx-10.4-ppc64" msgstr "macosx-10.4-ppc64" -#: ../../library/sysconfig.rst:398 +#: ../../library/sysconfig.rst:399 msgid "macosx-10.3-i386" msgstr "macosx-10.3-i386" -#: ../../library/sysconfig.rst:399 +#: ../../library/sysconfig.rst:400 msgid "macosx-10.4-fat" msgstr "macosx-10.4-fat" -#: ../../library/sysconfig.rst:401 +#: ../../library/sysconfig.rst:402 msgid "" "For other non-POSIX platforms, currently just returns :data:`sys.platform`." msgstr "" "Para outras plataformas não POSIX, é retornado apenas :data:`sys.platform`." -#: ../../library/sysconfig.rst:406 +#: ../../library/sysconfig.rst:407 msgid "" "Return ``True`` if the running Python interpreter was built from source and " "is being run from its built location, and not from a location resulting from " @@ -843,18 +859,18 @@ msgstr "" "construção, e não de um local resultante de, por exemplo, executando ``make " "install`` ou instalando através de um instalador binário." -#: ../../library/sysconfig.rst:413 +#: ../../library/sysconfig.rst:414 msgid "Parse a :file:`config.h`\\-style file." msgstr "Analisa um arquivo no estilo :file:`config.h`." -#: ../../library/sysconfig.rst:415 +#: ../../library/sysconfig.rst:416 msgid "" "*fp* is a file-like object pointing to the :file:`config.h`\\-like file." msgstr "" "*fp* é um objeto arquivo ou similar apontando para o arquivo :file:`config." "h` ou similar." -#: ../../library/sysconfig.rst:417 +#: ../../library/sysconfig.rst:418 msgid "" "A dictionary containing name/value pairs is returned. If an optional " "dictionary is passed in as the second argument, it is used instead of a new " @@ -864,24 +880,70 @@ msgstr "" "opcional for passado como segundo argumento, ele será usado no lugar de um " "novo dicionário e atualizado com os valores lidos no arquivo." -#: ../../library/sysconfig.rst:424 +#: ../../library/sysconfig.rst:425 msgid "Return the path of :file:`pyconfig.h`." msgstr "Retorna o caminho do :file:`pyconfig.h`." -#: ../../library/sysconfig.rst:428 +#: ../../library/sysconfig.rst:429 msgid "Return the path of :file:`Makefile`." msgstr "Retorna o caminho do :file:`Makefile`." -#: ../../library/sysconfig.rst:433 -msgid "Using :mod:`sysconfig` as a script" -msgstr "Usando o módulo :mod:`sysconfig` como um Script" - #: ../../library/sysconfig.rst:435 +msgid "Command-line usage" +msgstr "Uso na linha de comando" + +#: ../../library/sysconfig.rst:437 msgid "You can use :mod:`sysconfig` as a script with Python's *-m* option:" msgstr "" "Você pode usar :mod:`sysconfig` como um script com a opção *-m* do Python:" -#: ../../library/sysconfig.rst:461 +#: ../../library/sysconfig.rst:439 +msgid "" +"$ python -m sysconfig\n" +"Platform: \"macosx-10.4-i386\"\n" +"Python version: \"3.2\"\n" +"Current installation scheme: \"posix_prefix\"\n" +"\n" +"Paths:\n" +" data = \"/usr/local\"\n" +" include = \"/Users/tarek/Dev/svn.python.org/py3k/Include\"\n" +" platinclude = \".\"\n" +" platlib = \"/usr/local/lib/python3.2/site-packages\"\n" +" platstdlib = \"/usr/local/lib/python3.2\"\n" +" purelib = \"/usr/local/lib/python3.2/site-packages\"\n" +" scripts = \"/usr/local/bin\"\n" +" stdlib = \"/usr/local/lib/python3.2\"\n" +"\n" +"Variables:\n" +" AC_APPLE_UNIVERSAL_BUILD = \"0\"\n" +" AIX_GENUINE_CPLUSPLUS = \"0\"\n" +" AR = \"ar\"\n" +" ARFLAGS = \"rc\"\n" +" ..." +msgstr "" +"$ python -m sysconfig\n" +"Platform: \"macosx-10.4-i386\"\n" +"Python version: \"3.2\"\n" +"Current installation scheme: \"posix_prefix\"\n" +"\n" +"Paths:\n" +" data = \"/usr/local\"\n" +" include = \"/Users/tarek/Dev/svn.python.org/py3k/Include\"\n" +" platinclude = \".\"\n" +" platlib = \"/usr/local/lib/python3.2/site-packages\"\n" +" platstdlib = \"/usr/local/lib/python3.2\"\n" +" purelib = \"/usr/local/lib/python3.2/site-packages\"\n" +" scripts = \"/usr/local/bin\"\n" +" stdlib = \"/usr/local/lib/python3.2\"\n" +"\n" +"Variables:\n" +" AC_APPLE_UNIVERSAL_BUILD = \"0\"\n" +" AIX_GENUINE_CPLUSPLUS = \"0\"\n" +" AR = \"ar\"\n" +" ARFLAGS = \"rc\"\n" +" ..." + +#: ../../library/sysconfig.rst:463 msgid "" "This call will print in the standard output the information returned by :" "func:`get_platform`, :func:`get_python_version`, :func:`get_path` and :func:" diff --git a/library/syslog.po b/library/syslog.po index 502c63590..978943da9 100644 --- a/library/syslog.po +++ b/library/syslog.po @@ -1,29 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:14+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -42,8 +38,8 @@ msgstr "" "do recurso ``syslog``." #: ../../library/syslog.rst:14 -msgid ":ref:`Availability `: Unix, not WASI, not iOS." -msgstr ":ref:`Disponibilidade `: Unix, não WASI, não iOS." +msgid "Availability" +msgstr "Disponibilidade" #: ../../library/syslog.rst:16 msgid "" @@ -268,6 +264,20 @@ msgstr "Exemplo simples" msgid "A simple set of examples::" msgstr "Um conjunto simples de exemplos::" +#: ../../library/syslog.rst:176 +msgid "" +"import syslog\n" +"\n" +"syslog.syslog('Processing started')\n" +"if error:\n" +" syslog.syslog(syslog.LOG_ERR, 'Processing started')" +msgstr "" +"import syslog\n" +"\n" +"syslog.syslog('Processing started')\n" +"if error:\n" +" syslog.syslog(syslog.LOG_ERR, 'Processing started')" + #: ../../library/syslog.rst:182 msgid "" "An example of setting some log options, these would include the process ID " @@ -277,3 +287,11 @@ msgstr "" "Um exemplo de configuração de algumas opções de log, isso incluiria o ID do " "processo nas mensagens registradas e escreveria as mensagens no recurso de " "destino usado para o log de correio::" + +#: ../../library/syslog.rst:186 +msgid "" +"syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL)\n" +"syslog.syslog('E-mail processing initiated...')" +msgstr "" +"syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL)\n" +"syslog.syslog('E-mail processing initiated...')" diff --git a/library/tabnanny.po b/library/tabnanny.po index aebfeb6c5..db0604fc4 100644 --- a/library/tabnanny.po +++ b/library/tabnanny.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Sheila Gomes , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:14+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/tarfile.po b/library/tarfile.po index 6966c5532..c0811a982 100644 --- a/library/tarfile.po +++ b/library/tarfile.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Giovana Morais , 2021 -# i17obot , 2021 -# Leandro Cavalcante Damascena , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 01:14+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -105,7 +99,7 @@ msgstr "" #: ../../library/tarfile.rst:57 msgid "mode" -msgstr "modo" +msgstr "mode" #: ../../library/tarfile.rst:57 msgid "action" @@ -910,8 +904,7 @@ msgid "" "default, although, since it affects all uses of *tarfile*, it is best " "practice to only do so in top-level applications or :mod:`site configuration " "`. To set a global default this way, a filter function needs to be " -"wrapped in :func:`staticmethod()` to prevent injection of a ``self`` " -"argument." +"wrapped in :func:`staticmethod` to prevent injection of a ``self`` argument." msgstr "" #: ../../library/tarfile.rst:624 @@ -1154,6 +1147,10 @@ msgid "" "set to ``'staff'``, use::" msgstr "" +#: ../../library/tarfile.rst:899 +msgid "new_tarinfo = old_tarinfo.replace(gname='staff')" +msgstr "" + #: ../../library/tarfile.rst:901 msgid "" "By default, a deep copy is made. If *deep* is false, the copy is shallow, i." @@ -1283,6 +1280,10 @@ msgid "" "members)::" msgstr "" +#: ../../library/tarfile.rst:1007 +msgid "filter(member: TarInfo, path: str, /) -> TarInfo | None" +msgstr "" + #: ../../library/tarfile.rst:1009 msgid "" "The callable is called just before each member is extracted, so it can take " @@ -1520,24 +1521,57 @@ msgstr "" msgid "Fully trusted archive::" msgstr "" +#: ../../library/tarfile.rst:1145 +msgid "" +"my_tarfile.extraction_filter = (lambda member, path: member)\n" +"my_tarfile.extractall()" +msgstr "" + #: ../../library/tarfile.rst:1148 msgid "" "Use the ``'data'`` filter if available, but revert to Python 3.11 behavior " "(``'fully_trusted'``) if this feature is not available::" msgstr "" +#: ../../library/tarfile.rst:1151 +msgid "" +"my_tarfile.extraction_filter = getattr(tarfile, 'data_filter',\n" +" (lambda member, path: member))\n" +"my_tarfile.extractall()" +msgstr "" + #: ../../library/tarfile.rst:1155 msgid "Use the ``'data'`` filter; *fail* if it is not available::" msgstr "Use o filtro ``'data'``; *fail* se ele não estiver disponível::" +#: ../../library/tarfile.rst:1157 +msgid "my_tarfile.extractall(filter=tarfile.data_filter)" +msgstr "" + #: ../../library/tarfile.rst:1159 msgid "or::" msgstr "ou::" +#: ../../library/tarfile.rst:1161 +msgid "" +"my_tarfile.extraction_filter = tarfile.data_filter\n" +"my_tarfile.extractall()" +msgstr "" + #: ../../library/tarfile.rst:1164 msgid "Use the ``'data'`` filter; *warn* if it is not available::" msgstr "Use o filtro ``'data'``; *warn* se ele não estiver disponível::" +#: ../../library/tarfile.rst:1166 +msgid "" +"if hasattr(tarfile, 'data_filter'):\n" +" my_tarfile.extractall(filter='data')\n" +"else:\n" +" # remove this when no longer needed\n" +" warn_the_user('Extracting may be unsafe; consider updating Python')\n" +" my_tarfile.extractall()" +msgstr "" + #: ../../library/tarfile.rst:1175 msgid "Stateful extraction filter example" msgstr "" @@ -1549,10 +1583,33 @@ msgid "" "to write these as context managers, to be used like this::" msgstr "" +#: ../../library/tarfile.rst:1181 +msgid "" +"with StatefulFilter() as filter_func:\n" +" tar.extractall(path, filter=filter_func)" +msgstr "" + #: ../../library/tarfile.rst:1184 msgid "Such a filter can be written as, for example::" msgstr "" +#: ../../library/tarfile.rst:1186 +msgid "" +"class StatefulFilter:\n" +" def __init__(self):\n" +" self.file_count = 0\n" +"\n" +" def __enter__(self):\n" +" return self\n" +"\n" +" def __call__(self, member, path):\n" +" self.file_count += 1\n" +" return member\n" +"\n" +" def __exit__(self, *exc_info):\n" +" print(f'{self.file_count} files extracted')" +msgstr "" + #: ../../library/tarfile.rst:1206 msgid "Command-Line Interface" msgstr "Interface de Linha de Comando" @@ -1569,9 +1626,17 @@ msgid "" "`-c` option and then list the filename(s) that should be included:" msgstr "" +#: ../../library/tarfile.rst:1216 +msgid "$ python -m tarfile -c monty.tar spam.txt eggs.txt" +msgstr "" + #: ../../library/tarfile.rst:1220 msgid "Passing a directory is also acceptable:" -msgstr "Passar um diretório também é aceito:" +msgstr "Passar um diretório também é aceitável:" + +#: ../../library/tarfile.rst:1222 +msgid "$ python -m tarfile -c monty.tar life-of-brian_1979/" +msgstr "" #: ../../library/tarfile.rst:1226 msgid "" @@ -1579,16 +1644,28 @@ msgid "" "option:`-e` option:" msgstr "" +#: ../../library/tarfile.rst:1229 +msgid "$ python -m tarfile -e monty.tar" +msgstr "" + #: ../../library/tarfile.rst:1233 msgid "" "You can also extract a tar archive into a different directory by passing the " "directory's name:" msgstr "" +#: ../../library/tarfile.rst:1236 +msgid "$ python -m tarfile -e monty.tar other-dir/" +msgstr "" + #: ../../library/tarfile.rst:1240 msgid "For a list of the files in a tar archive, use the :option:`-l` option:" msgstr "" +#: ../../library/tarfile.rst:1242 +msgid "$ python -m tarfile -l monty.tar" +msgstr "" + #: ../../library/tarfile.rst:1248 msgid "Command-line options" msgstr "Opções de linha de comando" @@ -1629,32 +1706,100 @@ msgstr "Exemplos" msgid "How to extract an entire tar archive to the current working directory::" msgstr "" +#: ../../library/tarfile.rst:1288 +msgid "" +"import tarfile\n" +"tar = tarfile.open(\"sample.tar.gz\")\n" +"tar.extractall(filter='data')\n" +"tar.close()" +msgstr "" + #: ../../library/tarfile.rst:1293 msgid "" "How to extract a subset of a tar archive with :meth:`TarFile.extractall` " "using a generator function instead of a list::" msgstr "" +#: ../../library/tarfile.rst:1296 +msgid "" +"import os\n" +"import tarfile\n" +"\n" +"def py_files(members):\n" +" for tarinfo in members:\n" +" if os.path.splitext(tarinfo.name)[1] == \".py\":\n" +" yield tarinfo\n" +"\n" +"tar = tarfile.open(\"sample.tar.gz\")\n" +"tar.extractall(members=py_files(tar))\n" +"tar.close()" +msgstr "" + #: ../../library/tarfile.rst:1308 msgid "How to create an uncompressed tar archive from a list of filenames::" msgstr "" +#: ../../library/tarfile.rst:1310 +msgid "" +"import tarfile\n" +"tar = tarfile.open(\"sample.tar\", \"w\")\n" +"for name in [\"foo\", \"bar\", \"quux\"]:\n" +" tar.add(name)\n" +"tar.close()" +msgstr "" + #: ../../library/tarfile.rst:1316 msgid "The same example using the :keyword:`with` statement::" msgstr "" +#: ../../library/tarfile.rst:1318 +msgid "" +"import tarfile\n" +"with tarfile.open(\"sample.tar\", \"w\") as tar:\n" +" for name in [\"foo\", \"bar\", \"quux\"]:\n" +" tar.add(name)" +msgstr "" + #: ../../library/tarfile.rst:1323 msgid "" "How to read a gzip compressed tar archive and display some member " "information::" msgstr "" +#: ../../library/tarfile.rst:1325 +msgid "" +"import tarfile\n" +"tar = tarfile.open(\"sample.tar.gz\", \"r:gz\")\n" +"for tarinfo in tar:\n" +" print(tarinfo.name, \"is\", tarinfo.size, \"bytes in size and is \", " +"end=\"\")\n" +" if tarinfo.isreg():\n" +" print(\"a regular file.\")\n" +" elif tarinfo.isdir():\n" +" print(\"a directory.\")\n" +" else:\n" +" print(\"something else.\")\n" +"tar.close()" +msgstr "" + #: ../../library/tarfile.rst:1337 msgid "" "How to create an archive and reset the user information using the *filter* " "parameter in :meth:`TarFile.add`::" msgstr "" +#: ../../library/tarfile.rst:1340 +msgid "" +"import tarfile\n" +"def reset(tarinfo):\n" +" tarinfo.uid = tarinfo.gid = 0\n" +" tarinfo.uname = tarinfo.gname = \"root\"\n" +" return tarinfo\n" +"tar = tarfile.open(\"sample.tar.gz\", \"w:gz\")\n" +"tar.add(\"foo\", filter=reset)\n" +"tar.close()" +msgstr "" + #: ../../library/tarfile.rst:1353 msgid "Supported tar formats" msgstr "Formatos tar suportados" diff --git a/library/telnetlib.po b/library/telnetlib.po new file mode 100644 index 000000000..42171a9d0 --- /dev/null +++ b/library/telnetlib.po @@ -0,0 +1,56 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../library/telnetlib.rst:2 +msgid ":mod:`!telnetlib` --- Telnet client" +msgstr ":mod:`!telnetlib` --- cliente Telnet" + +#: ../../library/telnetlib.rst:10 +msgid "" +"This module is no longer part of the Python standard library. It was :ref:" +"`removed in Python 3.13 ` after being deprecated in " +"Python 3.11. The removal was decided in :pep:`594`." +msgstr "" +"Este módulo não faz mais parte da biblioteca padrão do Python. Ele foi :ref:" +"`removido no Python 3.13 ` após ser descontinuado no " +"Python 3.11. A remoção foi decidida na :pep:`594`." + +#: ../../library/telnetlib.rst:14 +msgid "" +"Possible replacements are third-party libraries from PyPI: :pypi:" +"`telnetlib3` or :pypi:`Exscript`. These are not supported or maintained by " +"the Python core team." +msgstr "" +"Possíveis substituições são bibliotecas de terceiros do PyPI: :pypi:" +"`telnetlib3` ou :pypi:`Exscript`. Elas não são suportadas ou mantidas pela " +"equipe principal do Python." + +#: ../../library/telnetlib.rst:18 +msgid "" +"The last version of Python that provided the :mod:`!telnetlib` module was " +"`Python 3.12 `_." +msgstr "" +"A última versão do Python que forneceu o módulo :mod:`!telnetlib` foi o " +"`Python 3.12 `_." diff --git a/library/tempfile.po b/library/tempfile.po index 6bb1665e3..42a4ae870 100644 --- a/library/tempfile.po +++ b/library/tempfile.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2024 -# i17obot , 2024 -# Raphael Mendonça, 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:14+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -541,6 +538,49 @@ msgstr "Exemplos" msgid "Here are some examples of typical usage of the :mod:`tempfile` module::" msgstr "" +#: ../../library/tempfile.rst:390 +msgid "" +">>> import tempfile\n" +"\n" +"# create a temporary file and write some data to it\n" +">>> fp = tempfile.TemporaryFile()\n" +">>> fp.write(b'Hello world!')\n" +"# read data from file\n" +">>> fp.seek(0)\n" +">>> fp.read()\n" +"b'Hello world!'\n" +"# close the file, it will be removed\n" +">>> fp.close()\n" +"\n" +"# create a temporary file using a context manager\n" +">>> with tempfile.TemporaryFile() as fp:\n" +"... fp.write(b'Hello world!')\n" +"... fp.seek(0)\n" +"... fp.read()\n" +"b'Hello world!'\n" +">>>\n" +"# file is now closed and removed\n" +"\n" +"# create a temporary file using a context manager\n" +"# close the file, use the name to open the file again\n" +">>> with tempfile.NamedTemporaryFile(delete_on_close=False) as fp:\n" +"... fp.write(b'Hello world!')\n" +"... fp.close()\n" +"... # the file is closed, but not removed\n" +"... # open the file again by using its name\n" +"... with open(fp.name, mode='rb') as f:\n" +"... f.read()\n" +"b'Hello world!'\n" +">>>\n" +"# file is now removed\n" +"\n" +"# create a temporary directory using the context manager\n" +">>> with tempfile.TemporaryDirectory() as tmpdirname:\n" +"... print('created temporary directory', tmpdirname)\n" +">>>\n" +"# directory and contents have been removed" +msgstr "" + #: ../../library/tempfile.rst:433 msgid "Deprecated functions and variables" msgstr "" @@ -577,6 +617,19 @@ msgid "" "parameter::" msgstr "" +#: ../../library/tempfile.rst:462 +msgid "" +">>> f = NamedTemporaryFile(delete=False)\n" +">>> f.name\n" +"'/tmp/tmptjujjt'\n" +">>> f.write(b\"Hello World!\\n\")\n" +"13\n" +">>> f.close()\n" +">>> os.unlink(f.name)\n" +">>> os.path.exists(f.name)\n" +"False" +msgstr "" + #: ../../library/tempfile.rst:11 msgid "temporary" msgstr "" diff --git a/library/termios.po b/library/termios.po index 75624ae4f..e517e58aa 100644 --- a/library/termios.po +++ b/library/termios.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# And Past , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:14+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -44,8 +41,8 @@ msgstr "" "*termios* configurado durante a instalação." #: ../../library/termios.rst:19 -msgid ":ref:`Availability `: Unix." -msgstr ":ref:`Disponibilidade `: Unix." +msgid "Availability" +msgstr "Disponibilidade" #: ../../library/termios.rst:21 msgid "" @@ -205,6 +202,34 @@ msgstr "" "keyword:`try` ... :keyword:`finally` para garantir que os atributos tty " "antigos sejam restaurados exatamente, aconteça o que acontecer::" +#: ../../library/termios.rst:125 +msgid "" +"def getpass(prompt=\"Password: \"):\n" +" import termios, sys\n" +" fd = sys.stdin.fileno()\n" +" old = termios.tcgetattr(fd)\n" +" new = termios.tcgetattr(fd)\n" +" new[3] = new[3] & ~termios.ECHO # lflags\n" +" try:\n" +" termios.tcsetattr(fd, termios.TCSADRAIN, new)\n" +" passwd = input(prompt)\n" +" finally:\n" +" termios.tcsetattr(fd, termios.TCSADRAIN, old)\n" +" return passwd" +msgstr "" +"def getpass(prompt=\"Senha: \"):\n" +" import termios, sys\n" +" fd = sys.stdin.fileno()\n" +" old = termios.tcgetattr(fd)\n" +" new = termios.tcgetattr(fd)\n" +" new[3] = new[3] & ~termios.ECHO # lflags\n" +" try:\n" +" termios.tcsetattr(fd, termios.TCSADRAIN, new)\n" +" passwd = input(prompt)\n" +" finally:\n" +" termios.tcsetattr(fd, termios.TCSADRAIN, old)\n" +" return passwd" + #: ../../library/termios.rst:8 msgid "POSIX" msgstr "POSIX" diff --git a/library/test.po b/library/test.po index fd22a1c94..ba684f9c5 100644 --- a/library/test.po +++ b/library/test.po @@ -1,37 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# João Porfirio, 2022 -# Altair Ribeiro, 2022 -# Italo Penaforte , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:14+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/test.rst:2 msgid ":mod:`!test` --- Regression tests package for Python" -msgstr "" +msgstr ":mod:`!test` --- Pacote de Testes de Regressão do Python" #: ../../library/test.rst:10 msgid "" @@ -123,6 +117,70 @@ msgstr "" msgid "A basic boilerplate is often used::" msgstr "Um boilerplate básico é muitas vezes usado::" +#: ../../library/test.rst:57 +msgid "" +"import unittest\n" +"from test import support\n" +"\n" +"class MyTestCase1(unittest.TestCase):\n" +"\n" +" # Only use setUp() and tearDown() if necessary\n" +"\n" +" def setUp(self):\n" +" ... code to execute in preparation for tests ...\n" +"\n" +" def tearDown(self):\n" +" ... code to execute to clean up after tests ...\n" +"\n" +" def test_feature_one(self):\n" +" # Test feature one.\n" +" ... testing code ...\n" +"\n" +" def test_feature_two(self):\n" +" # Test feature two.\n" +" ... testing code ...\n" +"\n" +" ... more test methods ...\n" +"\n" +"class MyTestCase2(unittest.TestCase):\n" +" ... same structure as MyTestCase1 ...\n" +"\n" +"... more test classes ...\n" +"\n" +"if __name__ == '__main__':\n" +" unittest.main()" +msgstr "" +"import unittest\n" +"from test import support\n" +"\n" +"class MyTestCase1(unittest.TestCase):\n" +"\n" +" # Só use setUp() e tearDown() se necessário\n" +"\n" +" def setUp(self):\n" +" ... código para executar na preparação de testes ...\n" +"\n" +" def tearDown(self):\n" +" ... código para executar a limpeza após os testes ...\n" +"\n" +" def test_feature_one(self):\n" +" # Testa o recurso um.\n" +" ... código de teste ...\n" +"\n" +" def test_feature_two(self):\n" +" # Testa o recurso dois.\n" +" ... código de teste ...\n" +"\n" +" ... mais métodos de teste ...\n" +"\n" +"class MyTestCase2(unittest.TestCase):\n" +" ... mesma estrutura que MyTestCase1 ...\n" +"\n" +"... mais classes de teste ...\n" +"\n" +"if __name__ == '__main__':\n" +" unittest.main()" + #: ../../library/test.rst:88 msgid "" "This code pattern allows the testing suite to be run by :mod:`test." @@ -230,6 +288,40 @@ msgstr "" "de código criando uma subclasse básica de testes com uma classe que " "especifica o input::" +#: ../../library/test.rst:129 +msgid "" +"class TestFuncAcceptsSequencesMixin:\n" +"\n" +" func = mySuperWhammyFunction\n" +"\n" +" def test_func(self):\n" +" self.func(self.arg)\n" +"\n" +"class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):\n" +" arg = [1, 2, 3]\n" +"\n" +"class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):\n" +" arg = 'abc'\n" +"\n" +"class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):\n" +" arg = (1, 2, 3)" +msgstr "" +"class TestFuncAcceptsSequencesMixin:\n" +"\n" +" func = mySuperWhammyFunction\n" +"\n" +" def test_func(self):\n" +" self.func(self.arg)\n" +"\n" +"class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):\n" +" arg = [1, 2, 3]\n" +"\n" +"class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):\n" +" arg = 'abc'\n" +"\n" +"class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):\n" +" arg = (1, 2, 3)" + #: ../../library/test.rst:145 msgid "" "When using this pattern, remember that all classes that inherit from :class:" @@ -238,6 +330,11 @@ msgid "" "data and so can't be run by itself, thus it does not inherit from :class:" "`unittest.TestCase`." msgstr "" +"Ao usar este padrão, lembre-se que todas as classes que herdam de :class:" +"`unittest.TestCase` são executadas como testes. A classe :class:`!" +"TestFuncAcceptsSequencesMixin` no exemplo acima não tem nenhum dado e, " +"portanto, não pode ser executada sozinha, portanto, ela não herda de :class:" +"`unittest.TestCase`." #: ../../library/test.rst:153 msgid "Test Driven Development" @@ -528,6 +625,8 @@ msgid "" "``True`` if Python was built with the :c:macro:`Py_DEBUG` macro defined, " "that is, if Python was :ref:`built in debug mode `." msgstr "" +"``True`` se o Python foi criado com a macro :c:macro:`Py_DEBUG` definida, ou " +"seja, se o Python foi :ref:`criado no modo de depuração `." #: ../../library/test.rst:336 msgid "" @@ -547,7 +646,7 @@ msgstr "Define o diretório de mais alto nível para o pacote de teste." #: ../../library/test.rst:352 msgid "Set to the ``data`` directory within the test package." -msgstr "" +msgstr "Define o diretório ``data`` de dentro do pacote de teste." #: ../../library/test.rst:357 msgid "Set to :data:`sys.maxsize` for big memory tests." @@ -631,10 +730,26 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" +#: ../../library/test.rst:428 +msgid "" +"for _ in support.busy_retry(support.SHORT_TIMEOUT):\n" +" if check():\n" +" break" +msgstr "" + #: ../../library/test.rst:432 ../../library/test.rst:456 msgid "Example of error=False usage::" msgstr "" +#: ../../library/test.rst:434 +msgid "" +"for _ in support.busy_retry(support.SHORT_TIMEOUT, error=False):\n" +" if check():\n" +" break\n" +"else:\n" +" raise RuntimeError('my custom error')" +msgstr "" + #: ../../library/test.rst:442 msgid "Wait strategy that applies exponential backoff." msgstr "" @@ -654,6 +769,22 @@ msgstr "" msgid "Example raising an exception after SHORT_TIMEOUT seconds::" msgstr "" +#: ../../library/test.rst:452 +msgid "" +"for _ in support.sleeping_retry(support.SHORT_TIMEOUT):\n" +" if check():\n" +" break" +msgstr "" + +#: ../../library/test.rst:458 +msgid "" +"for _ in support.sleeping_retry(support.SHORT_TIMEOUT, error=False):\n" +" if check():\n" +" break\n" +"else:\n" +" raise RuntimeError('my custom error')" +msgstr "" + #: ../../library/test.rst:466 msgid "" "Return ``True`` if *resource* is enabled and available. The list of " @@ -711,6 +842,13 @@ msgid "" "returns ``True`` or ``False`` depending on the host platform. Example usage::" msgstr "" +#: ../../library/test.rst:524 +msgid "" +"check_impl_detail() # Only on CPython (default).\n" +"check_impl_detail(jython=True) # Only on Jython.\n" +"check_impl_detail(cpython=False) # Everywhere except CPython." +msgstr "" + #: ../../library/test.rst:531 msgid "" "Set the values for :data:`max_memuse` and :data:`real_max_memuse` for big " @@ -763,10 +901,29 @@ msgstr "" msgid "Example use with output streams::" msgstr "Exemplo do uso com fluxos de saída::" +#: ../../library/test.rst:568 +msgid "" +"with captured_stdout() as stdout, captured_stderr() as stderr:\n" +" print(\"hello\")\n" +" print(\"error\", file=sys.stderr)\n" +"assert stdout.getvalue() == \"hello\\n\"\n" +"assert stderr.getvalue() == \"error\\n\"" +msgstr "" + #: ../../library/test.rst:574 msgid "Example use with input stream::" msgstr "Exemplo de uso com fluxo de entrada::" +#: ../../library/test.rst:576 +msgid "" +"with captured_stdin() as stdin:\n" +" stdin.write('hello\\n')\n" +" stdin.seek(0)\n" +" # call test code that consumes from sys.stdin\n" +" captured = input()\n" +"self.assertEqual(captured, \"hello\")" +msgstr "" + #: ../../library/test.rst:586 msgid "A context manager that temporary disables :mod:`faulthandler`." msgstr "" @@ -799,6 +956,12 @@ msgstr "" msgid "Usage::" msgstr "Uso::" +#: ../../library/test.rst:609 +msgid "" +"with swap_attr(obj, \"attr\", 5):\n" +" ..." +msgstr "" + #: ../../library/test.rst:612 msgid "" "This will set ``obj.attr`` to 5 for the duration of the ``with`` block, " @@ -816,6 +979,12 @@ msgstr "" msgid "Context manager to swap out an item with a new object." msgstr "" +#: ../../library/test.rst:627 +msgid "" +"with swap_item(obj, \"item\", 5):\n" +" ..." +msgstr "" + #: ../../library/test.rst:630 msgid "" "This will set ``obj[\"item\"]`` to 5 for the duration of the ``with`` block, " @@ -1056,6 +1225,19 @@ msgid "" "the stored object." msgstr "" +#: ../../library/test.rst:868 +msgid "" +"with support.catch_unraisable_exception() as cm:\n" +" # code creating an \"unraisable exception\"\n" +" ...\n" +"\n" +" # check the unraisable exception: use cm.unraisable\n" +" ...\n" +"\n" +"# cm.unraisable attribute no longer exists at this point\n" +"# (to break a reference cycle)" +msgstr "" + #: ../../library/test.rst:883 msgid "" "Generic implementation of the :mod:`unittest` ``load_tests`` protocol for " @@ -1065,6 +1247,15 @@ msgid "" "the following::" msgstr "" +#: ../../library/test.rst:889 +msgid "" +"import os\n" +"from test.support import load_package_tests\n" +"\n" +"def load_tests(*args):\n" +" return load_package_tests(os.path.dirname(__file__), *args)" +msgstr "" + #: ../../library/test.rst:898 msgid "" "Returns the set of attributes, functions or methods of *ref_api* not found " @@ -1124,9 +1315,9 @@ msgstr "" #: ../../library/test.rst:948 msgid "" "The *extra* argument can be a set of names that wouldn't otherwise be " -"automatically detected as \"public\", like objects without a proper " -"``__module__`` attribute. If provided, it will be added to the automatically " -"detected ones." +"automatically detected as \"public\", like objects without a proper :attr:" +"`~definition.__module__` attribute. If provided, it will be added to the " +"automatically detected ones." msgstr "" #: ../../library/test.rst:952 @@ -1139,6 +1330,26 @@ msgstr "" msgid "Example use::" msgstr "Exemplo de uso::" +#: ../../library/test.rst:957 +msgid "" +"import bar\n" +"import foo\n" +"import unittest\n" +"from test import support\n" +"\n" +"class MiscTestCase(unittest.TestCase):\n" +" def test__all__(self):\n" +" support.check__all__(self, foo)\n" +"\n" +"class OtherTestCase(unittest.TestCase):\n" +" def test__all__(self):\n" +" extra = {'BAR_CONST', 'FOO_CONST'}\n" +" not_exported = {'baz'} # Undocumented name.\n" +" # bar imports part of its API from _bar.\n" +" support.check__all__(self, bar, ('bar', '_bar'),\n" +" extra=extra, not_exported=not_exported)" +msgstr "" + #: ../../library/test.rst:978 msgid "" "Skip tests if the :mod:`multiprocessing.synchronize` module is missing, if " @@ -1540,6 +1751,21 @@ msgstr "" msgid "These attributes are deleted at the context manager exit." msgstr "" +#: ../../library/test.rst:1334 +msgid "" +"with threading_helper.catch_threading_exception() as cm:\n" +" # code spawning a thread which raises an exception\n" +" ...\n" +"\n" +" # check the thread exception, use cm attributes:\n" +" # exc_type, exc_value, exc_traceback, thread\n" +" ...\n" +"\n" +"# exc_type, exc_value, exc_traceback, thread attributes of cm no longer\n" +"# exists at this point\n" +"# (to avoid reference cycles)" +msgstr "" + #: ../../library/test.rst:1350 msgid ":mod:`test.support.os_helper` --- Utilities for os tests" msgstr "" @@ -1802,6 +2028,16 @@ msgid "" "imported." msgstr "" +#: ../../library/test.rst:1584 +msgid "" +"# Get copies of the warnings module for testing without affecting the\n" +"# version being used by the rest of the test suite. One copy uses the\n" +"# C implementation, the other is forced to use the pure Python fallback\n" +"# implementation\n" +"py_warnings = import_fresh_module('warnings', blocked=['_warnings'])\n" +"c_warnings = import_fresh_module('warnings', fresh=['_warnings'])" +msgstr "" + #: ../../library/test.rst:1596 msgid "" "This function imports and returns the named module. Unlike a normal import, " @@ -1846,6 +2082,12 @@ msgid "" "`DeprecationWarning` on import. Example usage::" msgstr "" +#: ../../library/test.rst:1638 +msgid "" +"with CleanImport('foo'):\n" +" importlib.import_module('foo') # New reference." +msgstr "" + #: ../../library/test.rst:1644 msgid "A context manager to temporarily add directories to :data:`sys.path`." msgstr "" @@ -1882,6 +2124,13 @@ msgid "" "category=category) `. For example::" msgstr "" +#: ../../library/test.rst:1674 +msgid "" +"@warning_helper.ignore_warnings(category=DeprecationWarning)\n" +"def test_suppress_warning():\n" +" # do something" +msgstr "" + #: ../../library/test.rst:1683 msgid "" "Context manager to check that no :exc:`ResourceWarning` was raised. You " @@ -1903,7 +2152,7 @@ msgstr "" #: ../../library/test.rst:1704 msgid "" -"A convenience wrapper for :func:`warnings.catch_warnings()` that makes it " +"A convenience wrapper for :func:`warnings.catch_warnings` that makes it " "easier to test that a warning was correctly raised. It is approximately " "equivalent to calling ``warnings.catch_warnings(record=True)`` with :meth:" "`warnings.simplefilter` set to ``always`` and with the option to " @@ -1926,6 +2175,10 @@ msgstr "" msgid "If no arguments are specified, it defaults to::" msgstr "Se nenhum argumento é especificado, o padrão é::" +#: ../../library/test.rst:1721 +msgid "check_warnings((\"\", Warning), quiet=True)" +msgstr "" + #: ../../library/test.rst:1723 msgid "In this case all warnings are caught and no errors are raised." msgstr "Nesse caso, todos os avisos são capturados e nenhum erro é gerado." @@ -1952,6 +2205,14 @@ msgstr "" msgid "The context manager is designed to be used like this::" msgstr "O gerenciador de contexto é desenhado para ser utilizado dessa forma::" +#: ../../library/test.rst:1739 +msgid "" +"with check_warnings((\"assertion is always true\", SyntaxWarning),\n" +" (\"\", UserWarning)):\n" +" exec('assert(False, \"Hey!\")')\n" +" warnings.warn(UserWarning(\"Hide me!\"))" +msgstr "" + #: ../../library/test.rst:1744 msgid "" "In this case if either warning was not raised, or some other warning was " @@ -1966,6 +2227,19 @@ msgid "" "checking whether or not they occurred, code like this can be used::" msgstr "" +#: ../../library/test.rst:1750 +msgid "" +"with check_warnings(quiet=True) as w:\n" +" warnings.warn(\"foo\")\n" +" assert str(w.args[0]) == \"foo\"\n" +" warnings.warn(\"bar\")\n" +" assert str(w.args[0]) == \"bar\"\n" +" assert str(w.warnings[0].args[0]) == \"foo\"\n" +" assert str(w.warnings[1].args[0]) == \"bar\"\n" +" w.reset()\n" +" assert len(w.warnings) == 0" +msgstr "" + #: ../../library/test.rst:1761 msgid "" "Here all warnings will be caught, and the test code tests the captured " diff --git a/library/text.po b/library/text.po index 95496906c..bff9dd578 100644 --- a/library/text.po +++ b/library/text.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Raphael Mendonça, 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:15+0000\n" -"Last-Translator: Raphael Mendonça, 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/textwrap.po b/library/textwrap.po index a3f8cfef4..11022435a 100644 --- a/library/textwrap.po +++ b/library/textwrap.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Adorilson Bezerra , 2024 -# Claudio Rogerio Carvalho Filho , 2024 -# i17obot , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-05 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 01:15+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -82,6 +79,10 @@ msgstr "" "Quebra o parágrafo único em *text* e retorna uma única string contendo o " "parágrafo quebrado. :func:`fill` é uma abreviação de ::" +#: ../../library/textwrap.rst:48 +msgid "\"\\n\".join(wrap(text, ...))" +msgstr "\"\\n\".join(wrap(text, ...))" + #: ../../library/textwrap.rst:50 msgid "" "In particular, :func:`fill` accepts exactly the same keyword arguments as :" @@ -109,6 +110,22 @@ msgstr "" "eliminadas do final para que as palavras restantes mais o *placeholder* " "caibam em *largura*::" +#: ../../library/textwrap.rst:65 +msgid "" +">>> textwrap.shorten(\"Hello world!\", width=12)\n" +"'Hello world!'\n" +">>> textwrap.shorten(\"Hello world!\", width=11)\n" +"'Hello [...]'\n" +">>> textwrap.shorten(\"Hello world\", width=10, placeholder=\"...\")\n" +"'Hello...'" +msgstr "" +">>> textwrap.shorten(\"Olá mundo!\", width=12)\n" +"'Olá mundo!'\n" +">>> textwrap.shorten(\"Olá mundo!\", width=11)\n" +"'Olá [...]'\n" +">>> textwrap.shorten(\"Olá mundo\", width=10, placeholder=\"...\")\n" +"'Olá...'" + #: ../../library/textwrap.rst:72 msgid "" "Optional keyword arguments correspond to the instance attributes of :class:" @@ -160,6 +177,26 @@ msgstr "" msgid "For example::" msgstr "Por exemplo::" +#: ../../library/textwrap.rst:96 +msgid "" +"def test():\n" +" # end first line with \\ to avoid the empty line!\n" +" s = '''\\\n" +" hello\n" +" world\n" +" '''\n" +" print(repr(s)) # prints ' hello\\n world\\n '\n" +" print(repr(dedent(s))) # prints 'hello\\n world\\n'" +msgstr "" +"def test():\n" +" # fim da primeira linha com \\ para evitar uma linha vazia!\n" +" s = '''\\\n" +" olá\n" +" mundo\n" +" '''\n" +" print(repr(s)) # exibe ' olá\\n mundo\\n '\n" +" print(repr(dedent(s))) # exibe 'olá\\n mundo\\n'" + #: ../../library/textwrap.rst:108 msgid "Add *prefix* to the beginning of selected lines in *text*." msgstr "Adiciona *prefix* ao início das linhas selecionadas em *text*." @@ -176,6 +213,16 @@ msgstr "" "Por padrão, *prefix* é adicionado a todas as linhas que não consistem apenas " "em espaços em branco (incluindo quaisquer finais de linha)." +#: ../../library/textwrap.rst:117 +msgid "" +">>> s = 'hello\\n\\n \\nworld'\n" +">>> indent(s, ' ')\n" +"' hello\\n\\n \\n world'" +msgstr "" +">>> s = 'olá\\n\\n \\nmundo'\n" +">>> indent(s, ' ')\n" +"' olá\\n\\n \\n mundo'" + #: ../../library/textwrap.rst:121 msgid "" "The optional *predicate* argument can be used to control which lines are " @@ -186,6 +233,20 @@ msgstr "" "têm indentação. Por exemplo, é fácil adicionar *prefix* até mesmo em linhas " "vazias e apenas com espaços em branco::" +#: ../../library/textwrap.rst:125 +msgid "" +">>> print(indent(s, '+ ', lambda line: True))\n" +"+ hello\n" +"+\n" +"+\n" +"+ world" +msgstr "" +">>> print(indent(s, '+ ', lambda line: True))\n" +"+ olá\n" +"+\n" +"+\n" +"+ mundo" + #: ../../library/textwrap.rst:134 msgid "" ":func:`wrap`, :func:`fill` and :func:`shorten` work by creating a :class:" @@ -221,10 +282,22 @@ msgstr "" "opcionais. Cada argumento nomeado corresponde a um atributo de instância, " "por exemplo::" +#: ../../library/textwrap.rst:150 +msgid "wrapper = TextWrapper(initial_indent=\"* \")" +msgstr "wrapper = TextWrapper(initial_indent=\"* \")" + #: ../../library/textwrap.rst:152 msgid "is the same as ::" msgstr "é o mesmo que ::" +#: ../../library/textwrap.rst:154 +msgid "" +"wrapper = TextWrapper()\n" +"wrapper.initial_indent = \"* \"" +msgstr "" +"wrapper = TextWrapper()\n" +"wrapper.initial_indent = \"* \"" + #: ../../library/textwrap.rst:157 msgid "" "You can reuse the same :class:`TextWrapper` object many times, and you can " @@ -363,10 +436,18 @@ msgstr "" "ou ``\"'\"``, seguido por um espaço. Um problema com este algoritmo é que " "ele é incapaz de detectar a diferença entre \"Dr.\" em ::" +#: ../../library/textwrap.rst:244 +msgid "[...] Dr. Frankenstein's monster [...]" +msgstr "[...] Dr. Frankenstein's monster [...]" + #: ../../library/textwrap.rst:246 msgid "and \"Spot.\" in ::" msgstr "e \"Spot.\" em ::" +#: ../../library/textwrap.rst:248 +msgid "[...] See Spot. See Spot run [...]" +msgstr "[...] See Spot. See Spot run [...]" + #: ../../library/textwrap.rst:250 msgid ":attr:`fix_sentence_endings` is false by default." msgstr ":attr:`fix_sentence_endings` é falso por padrão" diff --git a/library/threading.po b/library/threading.po index 7b3402996..9236fe4a7 100644 --- a/library/threading.po +++ b/library/threading.po @@ -1,33 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2021 -# Sheila Gomes , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Octavio von Sydow , 2021 -# Vinicius Gubiani Ferreira , 2021 -# Fabio Aragao , 2021 -# i17obot , 2021 -# Italo Penaforte , 2022 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:15+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-16 14:58+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -45,11 +37,79 @@ msgid "" "level :mod:`_thread` module." msgstr "" -#: ../../library/threading.rst:14 +#: ../../library/threading.rst:194 ../../library/threading.rst:293 +#: ../../library/threading.rst:641 ../../includes/wasm-notavail.rst:3 +msgid "Availability" +msgstr "Disponibilidade" + +#: ../../includes/wasm-notavail.rst:5 +msgid "" +"This module does not work or is not available on WebAssembly. See :ref:`wasm-" +"availability` for more information." +msgstr "" +"Este módulo não funciona ou não está disponível em WebAssembly. Veja :ref:" +"`wasm-availability` para mais informações." + +#: ../../library/threading.rst:17 +msgid "Introduction" +msgstr "Introdução" + +#: ../../library/threading.rst:19 +msgid "" +"The :mod:`!threading` module provides a way to run multiple `threads " +"`_ (smaller units of a " +"process) concurrently within a single process. It allows for the creation " +"and management of threads, making it possible to execute tasks in parallel, " +"sharing memory space. Threads are particularly useful when tasks are I/O " +"bound, such as file operations or making network requests, where much of the " +"time is spent waiting for external resources." +msgstr "" + +#: ../../library/threading.rst:27 +msgid "" +"A typical use case for :mod:`!threading` includes managing a pool of worker " +"threads that can process multiple tasks concurrently. Here's a basic " +"example of creating and starting threads using :class:`~threading.Thread`::" +msgstr "" + +#: ../../library/threading.rst:31 +msgid "" +"import threading\n" +"import time\n" +"\n" +"def crawl(link, delay=3):\n" +" print(f\"crawl started for {link}\")\n" +" time.sleep(delay) # Blocking I/O (simulating a network request)\n" +" print(f\"crawl ended for {link}\")\n" +"\n" +"links = [\n" +" \"https://python.org\",\n" +" \"https://docs.python.org\",\n" +" \"https://peps.python.org\",\n" +"]\n" +"\n" +"# Start threads for each link\n" +"threads = []\n" +"for link in links:\n" +" # Using `args` to pass positional arguments and `kwargs` for keyword " +"arguments\n" +" t = threading.Thread(target=crawl, args=(link,), kwargs={\"delay\": 2})\n" +" threads.append(t)\n" +"\n" +"# Start each thread\n" +"for t in threads:\n" +" t.start()\n" +"\n" +"# Wait for all threads to finish\n" +"for t in threads:\n" +" t.join()" +msgstr "" + +#: ../../library/threading.rst:60 msgid "This module used to be optional, it is now always available." msgstr "Este módulo costumava ser opcional, agora está sempre disponível." -#: ../../library/threading.rst:19 +#: ../../library/threading.rst:65 msgid "" ":class:`concurrent.futures.ThreadPoolExecutor` offers a higher level " "interface to push tasks to a background thread without blocking execution of " @@ -57,26 +117,26 @@ msgid "" "needed." msgstr "" -#: ../../library/threading.rst:23 +#: ../../library/threading.rst:69 msgid "" ":mod:`queue` provides a thread-safe interface for exchanging data between " "running threads." msgstr "" -#: ../../library/threading.rst:26 +#: ../../library/threading.rst:72 msgid "" ":mod:`asyncio` offers an alternative approach to achieving task level " "concurrency without requiring the use of multiple operating system threads." msgstr "" -#: ../../library/threading.rst:31 +#: ../../library/threading.rst:77 msgid "" "In the Python 2.x series, this module contained ``camelCase`` names for some " "methods and functions. These are deprecated as of Python 3.10, but they are " "still supported for compatibility with Python 2.5 and lower." msgstr "" -#: ../../library/threading.rst:38 +#: ../../library/threading.rst:84 msgid "" "In CPython, due to the :term:`Global Interpreter Lock `, only one thread can execute Python code at once (even though certain " @@ -87,23 +147,37 @@ msgid "" "appropriate model if you want to run multiple I/O-bound tasks simultaneously." msgstr "" -#: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +#: ../../library/threading.rst:95 +msgid "GIL and performance considerations" +msgstr "" -#: ../../includes/wasm-notavail.rst:5 +#: ../../library/threading.rst:97 msgid "" -"This module does not work or is not available on WebAssembly. See :ref:`wasm-" -"availability` for more information." +"Unlike the :mod:`multiprocessing` module, which uses separate processes to " +"bypass the :term:`global interpreter lock` (GIL), the threading module " +"operates within a single process, meaning that all threads share the same " +"memory space. However, the GIL limits the performance gains of threading " +"when it comes to CPU-bound tasks, as only one thread can execute Python " +"bytecode at a time. Despite this, threads remain a useful tool for achieving " +"concurrency in many scenarios." msgstr "" -"Este módulo não funciona ou não está disponível em WebAssembly. Veja :ref:" -"`wasm-availability` para mais informações." -#: ../../library/threading.rst:50 +#: ../../library/threading.rst:105 +msgid "" +"As of Python 3.13, experimental :term:`free-threaded ` " +"builds can disable the GIL, enabling true parallel execution of threads, but " +"this feature is not available by default (see :pep:`703`)." +msgstr "" + +#: ../../library/threading.rst:112 +msgid "Reference" +msgstr "Referência" + +#: ../../library/threading.rst:114 msgid "This module defines the following functions:" msgstr "Este módulo define as seguintes funções:" -#: ../../library/threading.rst:55 +#: ../../library/threading.rst:119 msgid "" "Return the number of :class:`Thread` objects currently alive. The returned " "count is equal to the length of the list returned by :func:`.enumerate`." @@ -111,51 +185,47 @@ msgstr "" "Retorna o número de objetos :class:`Thread` atualmente ativos. A quantidade " "retornada é igual ao tamanho da lista retornada por :func:`.enumerate`." -#: ../../library/threading.rst:58 +#: ../../library/threading.rst:122 msgid "The function ``activeCount`` is a deprecated alias for this function." msgstr "" -#: ../../library/threading.rst:63 +#: ../../library/threading.rst:127 msgid "" "Return the current :class:`Thread` object, corresponding to the caller's " "thread of control. If the caller's thread of control was not created " -"through the :mod:`threading` module, a dummy thread object with limited " +"through the :mod:`!threading` module, a dummy thread object with limited " "functionality is returned." msgstr "" -"Retorna o objeto :class:`Thread` atual, correspondendo ao controle do " -"chamador da thread. Se o controle do chamador da thread não foi criado " -"através do módulo :mod:`threading`, um objeto thread vazio, com " -"funcionalidade limitada, é retornado." -#: ../../library/threading.rst:68 +#: ../../library/threading.rst:132 msgid "The function ``currentThread`` is a deprecated alias for this function." msgstr "" -#: ../../library/threading.rst:73 +#: ../../library/threading.rst:137 msgid "Handle uncaught exception raised by :func:`Thread.run`." msgstr " Lidar com exceção não capturada, levantada por :func:`Thread.run`." -#: ../../library/threading.rst:75 +#: ../../library/threading.rst:139 msgid "The *args* argument has the following attributes:" msgstr "O argumento *args* tem os seguintes atributos:" -#: ../../library/threading.rst:77 +#: ../../library/threading.rst:141 msgid "*exc_type*: Exception type." msgstr "*exc_type*: Tipo de exceção.." -#: ../../library/threading.rst:78 +#: ../../library/threading.rst:142 msgid "*exc_value*: Exception value, can be ``None``." msgstr "*exc_value*: Valor da exceção, pode ser ``None``." -#: ../../library/threading.rst:79 +#: ../../library/threading.rst:143 msgid "*exc_traceback*: Exception traceback, can be ``None``." msgstr "*exc_traceback*: Pilha de execução da exceção, pode ser ``None``." -#: ../../library/threading.rst:80 +#: ../../library/threading.rst:144 msgid "*thread*: Thread which raised the exception, can be ``None``." msgstr "*thread*: Thread que levantou a exceção, pode ser ``None``." -#: ../../library/threading.rst:82 +#: ../../library/threading.rst:146 msgid "" "If *exc_type* is :exc:`SystemExit`, the exception is silently ignored. " "Otherwise, the exception is printed out on :data:`sys.stderr`." @@ -163,7 +233,7 @@ msgstr "" "Se *exc_type* é :exc:`SystemExit`, a exceção é silenciosamente ignorada. " "Caso contrário, a exceção é exibida em :data:`sys.stderr`." -#: ../../library/threading.rst:85 +#: ../../library/threading.rst:149 msgid "" "If this function raises an exception, :func:`sys.excepthook` is called to " "handle it." @@ -171,7 +241,7 @@ msgstr "" "Se esta função levantar uma exceção, :func:`sys.excepthook` é chamada para " "tratá-la." -#: ../../library/threading.rst:88 +#: ../../library/threading.rst:152 msgid "" ":func:`threading.excepthook` can be overridden to control how uncaught " "exceptions raised by :func:`Thread.run` are handled." @@ -179,32 +249,32 @@ msgstr "" ":func:`threading.excepthook` pode ser substituída para controlar como " "exceções não capturadas levantadas por :func:`Thread.run` são tratadas." -#: ../../library/threading.rst:91 +#: ../../library/threading.rst:155 msgid "" "Storing *exc_value* using a custom hook can create a reference cycle. It " "should be cleared explicitly to break the reference cycle when the exception " "is no longer needed." msgstr "" -#: ../../library/threading.rst:95 +#: ../../library/threading.rst:159 msgid "" "Storing *thread* using a custom hook can resurrect it if it is set to an " "object which is being finalized. Avoid storing *thread* after the custom " "hook completes to avoid resurrecting objects." msgstr "" -#: ../../library/threading.rst:100 +#: ../../library/threading.rst:164 msgid ":func:`sys.excepthook` handles uncaught exceptions." msgstr ":func:`sys.excepthook` trata exceções não capturadas." -#: ../../library/threading.rst:106 +#: ../../library/threading.rst:170 msgid "" "Holds the original value of :func:`threading.excepthook`. It is saved so " "that the original value can be restored in case they happen to get replaced " "with broken or alternative objects." msgstr "" -#: ../../library/threading.rst:114 +#: ../../library/threading.rst:178 msgid "" "Return the 'thread identifier' of the current thread. This is a nonzero " "integer. Its value has no direct meaning; it is intended as a magic cookie " @@ -218,7 +288,7 @@ msgstr "" "dicionário de dados específicos do thread. identificadores de thread podem " "ser reciclados quando um thread sai e outro é criado." -#: ../../library/threading.rst:125 +#: ../../library/threading.rst:189 msgid "" "Return the native integral Thread ID of the current thread assigned by the " "kernel. This is a non-negative integer. Its value may be used to uniquely " @@ -231,19 +301,11 @@ msgstr "" "a thread termine, após o que o valor poderá ser reciclado pelo sistema " "operacional)." -#: ../../library/threading.rst:130 -msgid "" -":ref:`Availability `: Windows, FreeBSD, Linux, macOS, OpenBSD, " -"NetBSD, AIX, DragonFlyBSD, GNU/kFreeBSD." -msgstr "" -":ref:`Disponibilidade `: Windows, FreeBSD, Linux, macOS, " -"OpenBSD, NetBSD, AIX, DragonFlyBSD, GNU/kFreeBSD." - -#: ../../library/threading.rst:134 +#: ../../library/threading.rst:198 msgid "Added support for GNU/kFreeBSD." msgstr "Adicionado suporte a GNU/kFreeBSD." -#: ../../library/threading.rst:140 +#: ../../library/threading.rst:204 msgid "" "Return a list of all :class:`Thread` objects currently active. The list " "includes daemonic threads and dummy thread objects created by :func:" @@ -252,60 +314,60 @@ msgid "" "even when terminated." msgstr "" -#: ../../library/threading.rst:149 +#: ../../library/threading.rst:213 msgid "" "Return the main :class:`Thread` object. In normal conditions, the main " "thread is the thread from which the Python interpreter was started." msgstr "" -#: ../../library/threading.rst:160 +#: ../../library/threading.rst:224 msgid "" -"Set a trace function for all threads started from the :mod:`threading` " +"Set a trace function for all threads started from the :mod:`!threading` " "module. The *func* will be passed to :func:`sys.settrace` for each thread, " "before its :meth:`~Thread.run` method is called." msgstr "" -#: ../../library/threading.rst:166 +#: ../../library/threading.rst:230 msgid "" -"Set a trace function for all threads started from the :mod:`threading` " +"Set a trace function for all threads started from the :mod:`!threading` " "module and all Python threads that are currently executing." msgstr "" -#: ../../library/threading.rst:169 +#: ../../library/threading.rst:233 msgid "" "The *func* will be passed to :func:`sys.settrace` for each thread, before " "its :meth:`~Thread.run` method is called." msgstr "" -#: ../../library/threading.rst:180 +#: ../../library/threading.rst:244 msgid "Get the trace function as set by :func:`settrace`." msgstr "Obtém a função trace conforme definido por :func:`settrace`." -#: ../../library/threading.rst:189 +#: ../../library/threading.rst:253 msgid "" -"Set a profile function for all threads started from the :mod:`threading` " +"Set a profile function for all threads started from the :mod:`!threading` " "module. The *func* will be passed to :func:`sys.setprofile` for each " "thread, before its :meth:`~Thread.run` method is called." msgstr "" -#: ../../library/threading.rst:195 +#: ../../library/threading.rst:259 msgid "" -"Set a profile function for all threads started from the :mod:`threading` " +"Set a profile function for all threads started from the :mod:`!threading` " "module and all Python threads that are currently executing." msgstr "" -#: ../../library/threading.rst:198 +#: ../../library/threading.rst:262 msgid "" "The *func* will be passed to :func:`sys.setprofile` for each thread, before " "its :meth:`~Thread.run` method is called." msgstr "" -#: ../../library/threading.rst:207 +#: ../../library/threading.rst:271 msgid "Get the profiler function as set by :func:`setprofile`." msgstr "" "Obtém a função do criador de perfil conforme definido por :func:`setprofile`." -#: ../../library/threading.rst:214 +#: ../../library/threading.rst:278 msgid "" "Return the thread stack size used when creating new threads. The optional " "*size* argument specifies the stack size to be used for subsequently created " @@ -340,19 +402,15 @@ msgstr "" "múltiplos de 4096 para o tamanho da pilha é a abordagem sugerida na ausência " "de informações mais específicas)." -#: ../../library/threading.rst:229 -msgid ":ref:`Availability `: Windows, pthreads." -msgstr ":ref:`Disponibilidade `: Windows, pthreads." - -#: ../../library/threading.rst:231 +#: ../../library/threading.rst:295 msgid "Unix platforms with POSIX threads support." msgstr "Plataformas Unix com suporte a threads POSIX." -#: ../../library/threading.rst:234 +#: ../../library/threading.rst:298 msgid "This module also defines the following constant:" msgstr "" -#: ../../library/threading.rst:238 +#: ../../library/threading.rst:302 msgid "" "The maximum value allowed for the *timeout* parameter of blocking functions " "(:meth:`Lock.acquire`, :meth:`RLock.acquire`, :meth:`Condition.wait`, etc.). " @@ -360,13 +418,13 @@ msgid "" "`OverflowError`." msgstr "" -#: ../../library/threading.rst:246 +#: ../../library/threading.rst:310 msgid "" "This module defines a number of classes, which are detailed in the sections " "below." msgstr "" -#: ../../library/threading.rst:249 +#: ../../library/threading.rst:313 msgid "" "The design of this module is loosely based on Java's threading model. " "However, where Java makes locks and condition variables basic behavior of " @@ -377,40 +435,222 @@ msgid "" "Thread class, when implemented, are mapped to module-level functions." msgstr "" -#: ../../library/threading.rst:257 +#: ../../library/threading.rst:321 msgid "All of the methods described below are executed atomically." msgstr "" -#: ../../library/threading.rst:261 -msgid "Thread-Local Data" +#: ../../library/threading.rst:325 +msgid "Thread-local data" msgstr "" -#: ../../library/threading.rst:263 +#: ../../library/threading.rst:327 msgid "" -"Thread-local data is data whose values are thread specific. To manage " -"thread-local data, just create an instance of :class:`local` (or a subclass) " -"and store attributes on it::" +"Thread-local data is data whose values are thread specific. If you have data " +"that you want to be local to a thread, create a :class:`local` object and " +"use its attributes::" msgstr "" -#: ../../library/threading.rst:270 -msgid "The instance's values will be different for separate threads." +#: ../../library/threading.rst:331 +msgid "" +">>> mydata = local()\n" +">>> mydata.number = 42\n" +">>> mydata.number\n" +"42" msgstr "" -#: ../../library/threading.rst:275 -msgid "A class that represents thread-local data." +#: ../../library/threading.rst:336 +msgid "You can also access the :class:`local`-object's dictionary::" msgstr "" -#: ../../library/threading.rst:277 +#: ../../library/threading.rst:338 msgid "" -"For more details and extensive examples, see the documentation string of " -"the :mod:`!_threading_local` module: :source:`Lib/_threading_local.py`." +">>> mydata.__dict__\n" +"{'number': 42}\n" +">>> mydata.__dict__.setdefault('widgets', [])\n" +"[]\n" +">>> mydata.widgets\n" +"[]" msgstr "" -#: ../../library/threading.rst:284 -msgid "Thread Objects" +#: ../../library/threading.rst:345 +msgid "If we access the data in a different thread::" msgstr "" -#: ../../library/threading.rst:286 +#: ../../library/threading.rst:347 +msgid "" +">>> log = []\n" +">>> def f():\n" +"... items = sorted(mydata.__dict__.items())\n" +"... log.append(items)\n" +"... mydata.number = 11\n" +"... log.append(mydata.number)\n" +"\n" +">>> import threading\n" +">>> thread = threading.Thread(target=f)\n" +">>> thread.start()\n" +">>> thread.join()\n" +">>> log\n" +"[[], 11]" +msgstr "" + +#: ../../library/threading.rst:361 +msgid "" +"we get different data. Furthermore, changes made in the other thread don't " +"affect data seen in this thread::" +msgstr "" + +#: ../../library/threading.rst:364 +msgid "" +">>> mydata.number\n" +"42" +msgstr "" + +#: ../../library/threading.rst:367 +msgid "" +"Of course, values you get from a :class:`local` object, including their :" +"attr:`~object.__dict__` attribute, are for whatever thread was current at " +"the time the attribute was read. For that reason, you generally don't want " +"to save these values across threads, as they apply only to the thread they " +"came from." +msgstr "" + +#: ../../library/threading.rst:373 +msgid "" +"You can create custom :class:`local` objects by subclassing the :class:" +"`local` class::" +msgstr "" + +#: ../../library/threading.rst:376 +msgid "" +">>> class MyLocal(local):\n" +"... number = 2\n" +"... def __init__(self, /, **kw):\n" +"... self.__dict__.update(kw)\n" +"... def squared(self):\n" +"... return self.number ** 2" +msgstr "" + +#: ../../library/threading.rst:383 +msgid "" +"This can be useful to support default values, methods and initialization. " +"Note that if you define an :py:meth:`~object.__init__` method, it will be " +"called each time the :class:`local` object is used in a separate thread. " +"This is necessary to initialize each thread's dictionary." +msgstr "" + +#: ../../library/threading.rst:389 +msgid "Now if we create a :class:`local` object::" +msgstr "" + +#: ../../library/threading.rst:391 +msgid ">>> mydata = MyLocal(color='red')" +msgstr "" + +#: ../../library/threading.rst:393 +msgid "we have a default number::" +msgstr "" + +#: ../../library/threading.rst:395 +msgid "" +">>> mydata.number\n" +"2" +msgstr "" + +#: ../../library/threading.rst:398 +msgid "an initial color::" +msgstr "" + +#: ../../library/threading.rst:400 +msgid "" +">>> mydata.color\n" +"'red'\n" +">>> del mydata.color" +msgstr "" + +#: ../../library/threading.rst:404 +msgid "And a method that operates on the data::" +msgstr "" + +#: ../../library/threading.rst:406 +msgid "" +">>> mydata.squared()\n" +"4" +msgstr "" + +#: ../../library/threading.rst:409 +msgid "As before, we can access the data in a separate thread::" +msgstr "" + +#: ../../library/threading.rst:411 +msgid "" +">>> log = []\n" +">>> thread = threading.Thread(target=f)\n" +">>> thread.start()\n" +">>> thread.join()\n" +">>> log\n" +"[[('color', 'red')], 11]" +msgstr "" + +#: ../../library/threading.rst:418 +msgid "without affecting this thread's data::" +msgstr "" + +#: ../../library/threading.rst:420 +msgid "" +">>> mydata.number\n" +"2\n" +">>> mydata.color\n" +"Traceback (most recent call last):\n" +"...\n" +"AttributeError: 'MyLocal' object has no attribute 'color'" +msgstr "" + +#: ../../library/threading.rst:427 +msgid "" +"Note that subclasses can define :term:`__slots__`, but they are not thread " +"local. They are shared across threads::" +msgstr "" + +#: ../../library/threading.rst:430 +msgid "" +">>> class MyLocal(local):\n" +"... __slots__ = 'number'\n" +"\n" +">>> mydata = MyLocal()\n" +">>> mydata.number = 42\n" +">>> mydata.color = 'red'" +msgstr "" + +#: ../../library/threading.rst:437 +msgid "So, the separate thread::" +msgstr "" + +#: ../../library/threading.rst:439 +msgid "" +">>> thread = threading.Thread(target=f)\n" +">>> thread.start()\n" +">>> thread.join()" +msgstr "" + +#: ../../library/threading.rst:443 +msgid "affects what we see::" +msgstr "" + +#: ../../library/threading.rst:445 +msgid "" +">>> mydata.number\n" +"11" +msgstr "" + +#: ../../library/threading.rst:451 +msgid "A class that represents thread-local data." +msgstr "" + +#: ../../library/threading.rst:457 +msgid "Thread objects" +msgstr "" + +#: ../../library/threading.rst:459 msgid "" "The :class:`Thread` class represents an activity that is run in a separate " "thread of control. There are two ways to specify the activity: by passing a " @@ -420,14 +660,14 @@ msgid "" "``__init__()`` and :meth:`~Thread.run` methods of this class." msgstr "" -#: ../../library/threading.rst:293 +#: ../../library/threading.rst:466 msgid "" "Once a thread object is created, its activity must be started by calling the " "thread's :meth:`~Thread.start` method. This invokes the :meth:`~Thread.run` " "method in a separate thread of control." msgstr "" -#: ../../library/threading.rst:297 +#: ../../library/threading.rst:470 msgid "" "Once the thread's activity is started, the thread is considered 'alive'. It " "stops being alive when its :meth:`~Thread.run` method terminates -- either " @@ -435,27 +675,27 @@ msgid "" "is_alive` method tests whether the thread is alive." msgstr "" -#: ../../library/threading.rst:302 +#: ../../library/threading.rst:475 msgid "" "Other threads can call a thread's :meth:`~Thread.join` method. This blocks " "the calling thread until the thread whose :meth:`~Thread.join` method is " "called is terminated." msgstr "" -#: ../../library/threading.rst:306 +#: ../../library/threading.rst:479 msgid "" "A thread has a name. The name can be passed to the constructor, and read or " "changed through the :attr:`~Thread.name` attribute." msgstr "" -#: ../../library/threading.rst:309 +#: ../../library/threading.rst:482 msgid "" "If the :meth:`~Thread.run` method raises an exception, :func:`threading." "excepthook` is called to handle it. By default, :func:`threading.excepthook` " "ignores silently :exc:`SystemExit`." msgstr "" -#: ../../library/threading.rst:313 +#: ../../library/threading.rst:486 msgid "" "A thread can be flagged as a \"daemon thread\". The significance of this " "flag is that the entire Python program exits when only daemon threads are " @@ -464,7 +704,7 @@ msgid "" "constructor argument." msgstr "" -#: ../../library/threading.rst:320 +#: ../../library/threading.rst:493 msgid "" "Daemon threads are abruptly stopped at shutdown. Their resources (such as " "open files, database transactions, etc.) may not be released properly. If " @@ -472,13 +712,13 @@ msgid "" "suitable signalling mechanism such as an :class:`Event`." msgstr "" -#: ../../library/threading.rst:325 +#: ../../library/threading.rst:498 msgid "" "There is a \"main thread\" object; this corresponds to the initial thread of " "control in the Python program. It is not a daemon thread." msgstr "" -#: ../../library/threading.rst:328 +#: ../../library/threading.rst:501 msgid "" "There is the possibility that \"dummy thread objects\" are created. These " "are thread objects corresponding to \"alien threads\", which are threads of " @@ -489,25 +729,25 @@ msgid "" "threads." msgstr "" -#: ../../library/threading.rst:339 +#: ../../library/threading.rst:512 msgid "" "This constructor should always be called with keyword arguments. Arguments " "are:" msgstr "" -#: ../../library/threading.rst:342 +#: ../../library/threading.rst:515 msgid "" "*group* should be ``None``; reserved for future extension when a :class:`!" "ThreadGroup` class is implemented." msgstr "" -#: ../../library/threading.rst:345 +#: ../../library/threading.rst:518 msgid "" "*target* is the callable object to be invoked by the :meth:`run` method. " "Defaults to ``None``, meaning nothing is called." msgstr "" -#: ../../library/threading.rst:348 +#: ../../library/threading.rst:521 msgid "" "*name* is the thread name. By default, a unique name is constructed of the " "form \"Thread-*N*\" where *N* is a small decimal number, or \"Thread-*N* " @@ -515,62 +755,62 @@ msgid "" "is specified." msgstr "" -#: ../../library/threading.rst:353 +#: ../../library/threading.rst:526 msgid "" "*args* is a list or tuple of arguments for the target invocation. Defaults " "to ``()``." msgstr "" -#: ../../library/threading.rst:355 +#: ../../library/threading.rst:528 msgid "" "*kwargs* is a dictionary of keyword arguments for the target invocation. " "Defaults to ``{}``." msgstr "" -#: ../../library/threading.rst:358 +#: ../../library/threading.rst:531 msgid "" "If not ``None``, *daemon* explicitly sets whether the thread is daemonic. If " "``None`` (the default), the daemonic property is inherited from the current " "thread." msgstr "" -#: ../../library/threading.rst:362 +#: ../../library/threading.rst:535 msgid "" "If the subclass overrides the constructor, it must make sure to invoke the " "base class constructor (``Thread.__init__()``) before doing anything else to " "the thread." msgstr "" -#: ../../library/threading.rst:366 +#: ../../library/threading.rst:539 msgid "Added the *daemon* parameter." -msgstr "" +msgstr "Adicionado o parâmetro *daemon*." -#: ../../library/threading.rst:369 +#: ../../library/threading.rst:542 msgid "Use the *target* name if *name* argument is omitted." msgstr "" -#: ../../library/threading.rst:374 +#: ../../library/threading.rst:547 msgid "Start the thread's activity." msgstr "" -#: ../../library/threading.rst:376 +#: ../../library/threading.rst:549 msgid "" "It must be called at most once per thread object. It arranges for the " "object's :meth:`~Thread.run` method to be invoked in a separate thread of " "control." msgstr "" -#: ../../library/threading.rst:380 +#: ../../library/threading.rst:553 msgid "" "This method will raise a :exc:`RuntimeError` if called more than once on the " "same thread object." msgstr "" -#: ../../library/threading.rst:385 +#: ../../library/threading.rst:558 msgid "Method representing the thread's activity." msgstr "" -#: ../../library/threading.rst:387 +#: ../../library/threading.rst:560 msgid "" "You may override this method in a subclass. The standard :meth:`run` method " "invokes the callable object passed to the object's constructor as the " @@ -578,17 +818,28 @@ msgid "" "the *args* and *kwargs* arguments, respectively." msgstr "" -#: ../../library/threading.rst:392 +#: ../../library/threading.rst:565 msgid "" "Using list or tuple as the *args* argument which passed to the :class:" "`Thread` could achieve the same effect." msgstr "" -#: ../../library/threading.rst:395 +#: ../../library/threading.rst:568 msgid "Example::" msgstr "Exemplo::" -#: ../../library/threading.rst:409 +#: ../../library/threading.rst:570 +msgid "" +">>> from threading import Thread\n" +">>> t = Thread(target=print, args=[1])\n" +">>> t.run()\n" +"1\n" +">>> t = Thread(target=print, args=(1,))\n" +">>> t.run()\n" +"1" +msgstr "" + +#: ../../library/threading.rst:582 msgid "" "Wait until the thread terminates. This blocks the calling thread until the " "thread whose :meth:`~Thread.join` method is called terminates -- either " @@ -596,7 +847,7 @@ msgid "" "occurs." msgstr "" -#: ../../library/threading.rst:414 +#: ../../library/threading.rst:587 msgid "" "When the *timeout* argument is present and not ``None``, it should be a " "floating-point number specifying a timeout for the operation in seconds (or " @@ -606,17 +857,17 @@ msgid "" "`~Thread.join` call timed out." msgstr "" -#: ../../library/threading.rst:421 +#: ../../library/threading.rst:594 msgid "" "When the *timeout* argument is not present or ``None``, the operation will " "block until the thread terminates." msgstr "" -#: ../../library/threading.rst:424 +#: ../../library/threading.rst:597 msgid "A thread can be joined many times." msgstr "" -#: ../../library/threading.rst:426 +#: ../../library/threading.rst:599 msgid "" ":meth:`~Thread.join` raises a :exc:`RuntimeError` if an attempt is made to " "join the current thread as that would cause a deadlock. It is also an error " @@ -624,20 +875,20 @@ msgid "" "do so raise the same exception." msgstr "" -#: ../../library/threading.rst:433 +#: ../../library/threading.rst:606 msgid "" "A string used for identification purposes only. It has no semantics. " "Multiple threads may be given the same name. The initial name is set by the " "constructor." msgstr "" -#: ../../library/threading.rst:440 +#: ../../library/threading.rst:613 msgid "" "Deprecated getter/setter API for :attr:`~Thread.name`; use it directly as a " "property instead." msgstr "" -#: ../../library/threading.rst:447 +#: ../../library/threading.rst:620 msgid "" "The 'thread identifier' of this thread or ``None`` if the thread has not " "been started. This is a nonzero integer. See the :func:`get_ident` " @@ -646,7 +897,7 @@ msgid "" "thread has exited." msgstr "" -#: ../../library/threading.rst:455 +#: ../../library/threading.rst:628 msgid "" "The Thread ID (``TID``) of this thread, as assigned by the OS (kernel). This " "is a non-negative integer, or ``None`` if the thread has not been started. " @@ -655,33 +906,25 @@ msgid "" "after which the value may be recycled by the OS)." msgstr "" -#: ../../library/threading.rst:464 +#: ../../library/threading.rst:637 msgid "" "Similar to Process IDs, Thread IDs are only valid (guaranteed unique system-" "wide) from the time the thread is created until the thread has been " "terminated." msgstr "" -#: ../../library/threading.rst:468 -msgid "" -":ref:`Availability `: Windows, FreeBSD, Linux, macOS, OpenBSD, " -"NetBSD, AIX, DragonFlyBSD." -msgstr "" -":ref:`Disponibilidade `: Windows, FreeBSD, Linux, macOS, " -"OpenBSD, NetBSD, AIX, DragonFlyBSD." - -#: ../../library/threading.rst:474 +#: ../../library/threading.rst:647 msgid "Return whether the thread is alive." msgstr "" -#: ../../library/threading.rst:476 +#: ../../library/threading.rst:649 msgid "" "This method returns ``True`` just before the :meth:`~Thread.run` method " "starts until just after the :meth:`~Thread.run` method terminates. The " "module function :func:`.enumerate` returns a list of all alive threads." msgstr "" -#: ../../library/threading.rst:482 +#: ../../library/threading.rst:655 msgid "" "A boolean value indicating whether this thread is a daemon thread (``True``) " "or not (``False``). This must be set before :meth:`~Thread.start` is " @@ -691,22 +934,22 @@ msgid "" "`~Thread.daemon` = ``False``." msgstr "" -#: ../../library/threading.rst:489 +#: ../../library/threading.rst:662 msgid "" "The entire Python program exits when no alive non-daemon threads are left." msgstr "" -#: ../../library/threading.rst:494 +#: ../../library/threading.rst:667 msgid "" "Deprecated getter/setter API for :attr:`~Thread.daemon`; use it directly as " "a property instead." msgstr "" -#: ../../library/threading.rst:503 -msgid "Lock Objects" +#: ../../library/threading.rst:676 +msgid "Lock objects" msgstr "" -#: ../../library/threading.rst:505 +#: ../../library/threading.rst:678 msgid "" "A primitive lock is a synchronization primitive that is not owned by a " "particular thread when locked. In Python, it is currently the lowest level " @@ -714,7 +957,7 @@ msgid "" "`_thread` extension module." msgstr "" -#: ../../library/threading.rst:510 +#: ../../library/threading.rst:683 msgid "" "A primitive lock is in one of two states, \"locked\" or \"unlocked\". It is " "created in the unlocked state. It has two basic methods, :meth:`~Lock." @@ -728,11 +971,11 @@ msgid "" "an unlocked lock, a :exc:`RuntimeError` will be raised." msgstr "" -#: ../../library/threading.rst:521 +#: ../../library/threading.rst:694 msgid "Locks also support the :ref:`context management protocol `." msgstr "" -#: ../../library/threading.rst:523 +#: ../../library/threading.rst:696 msgid "" "When more than one thread is blocked in :meth:`~Lock.acquire` waiting for " "the state to turn to unlocked, only one thread proceeds when a :meth:`~Lock." @@ -740,41 +983,41 @@ msgid "" "proceeds is not defined, and may vary across implementations." msgstr "" -#: ../../library/threading.rst:528 +#: ../../library/threading.rst:701 msgid "All methods are executed atomically." msgstr "" -#: ../../library/threading.rst:533 +#: ../../library/threading.rst:706 msgid "" "The class implementing primitive lock objects. Once a thread has acquired a " "lock, subsequent attempts to acquire it block, until it is released; any " "thread may release it." msgstr "" -#: ../../library/threading.rst:537 +#: ../../library/threading.rst:710 msgid "" "``Lock`` is now a class. In earlier Pythons, ``Lock`` was a factory function " "which returned an instance of the underlying private lock type." msgstr "" -#: ../../library/threading.rst:545 ../../library/threading.rst:636 +#: ../../library/threading.rst:718 ../../library/threading.rst:809 msgid "Acquire a lock, blocking or non-blocking." -msgstr "" +msgstr "Adquire uma trava, bloqueante ou não." -#: ../../library/threading.rst:547 +#: ../../library/threading.rst:720 msgid "" "When invoked with the *blocking* argument set to ``True`` (the default), " "block until the lock is unlocked, then set it to locked and return ``True``." msgstr "" -#: ../../library/threading.rst:550 +#: ../../library/threading.rst:723 msgid "" "When invoked with the *blocking* argument set to ``False``, do not block. If " "a call with *blocking* set to ``True`` would block, return ``False`` " "immediately; otherwise, set the lock to locked and return ``True``." msgstr "" -#: ../../library/threading.rst:554 +#: ../../library/threading.rst:727 msgid "" "When invoked with the floating-point *timeout* argument set to a positive " "value, block for at most the number of seconds specified by *timeout* and as " @@ -783,53 +1026,53 @@ msgid "" "*blocking* is ``False``." msgstr "" -#: ../../library/threading.rst:560 +#: ../../library/threading.rst:733 msgid "" "The return value is ``True`` if the lock is acquired successfully, ``False`` " "if not (for example if the *timeout* expired)." msgstr "" -#: ../../library/threading.rst:563 ../../library/threading.rst:674 -#: ../../library/threading.rst:921 +#: ../../library/threading.rst:736 ../../library/threading.rst:847 +#: ../../library/threading.rst:1094 msgid "The *timeout* parameter is new." msgstr "O parâmetro *timeout* é novo." -#: ../../library/threading.rst:566 +#: ../../library/threading.rst:739 msgid "" "Lock acquisition can now be interrupted by signals on POSIX if the " "underlying threading implementation supports it." msgstr "" -#: ../../library/threading.rst:573 +#: ../../library/threading.rst:746 msgid "" "Release a lock. This can be called from any thread, not only the thread " "which has acquired the lock." msgstr "" -#: ../../library/threading.rst:576 +#: ../../library/threading.rst:749 msgid "" "When the lock is locked, reset it to unlocked, and return. If any other " "threads are blocked waiting for the lock to become unlocked, allow exactly " "one of them to proceed." msgstr "" -#: ../../library/threading.rst:580 +#: ../../library/threading.rst:753 msgid "When invoked on an unlocked lock, a :exc:`RuntimeError` is raised." msgstr "" -#: ../../library/threading.rst:582 ../../library/threading.rst:690 +#: ../../library/threading.rst:755 ../../library/threading.rst:863 msgid "There is no return value." msgstr "" -#: ../../library/threading.rst:586 +#: ../../library/threading.rst:759 msgid "Return ``True`` if the lock is acquired." msgstr "" -#: ../../library/threading.rst:593 -msgid "RLock Objects" -msgstr "Objetos RLock" +#: ../../library/threading.rst:766 +msgid "RLock objects" +msgstr "" -#: ../../library/threading.rst:595 +#: ../../library/threading.rst:768 msgid "" "A reentrant lock is a synchronization primitive that may be acquired " "multiple times by the same thread. Internally, it uses the concepts of " @@ -838,13 +1081,13 @@ msgid "" "lock; in the unlocked state, no thread owns it." msgstr "" -#: ../../library/threading.rst:601 +#: ../../library/threading.rst:774 msgid "" "Threads call a lock's :meth:`~RLock.acquire` method to lock it, and its :" "meth:`~Lock.release` method to unlock it." msgstr "" -#: ../../library/threading.rst:606 +#: ../../library/threading.rst:779 msgid "" "Reentrant locks support the :ref:`context management protocol `, " "so it is recommended to use :keyword:`with` instead of manually calling :" @@ -852,7 +1095,7 @@ msgid "" "releasing the lock for a block of code." msgstr "" -#: ../../library/threading.rst:611 +#: ../../library/threading.rst:784 msgid "" "RLock's :meth:`~RLock.acquire`/:meth:`~RLock.release` call pairs may be " "nested, unlike Lock's :meth:`~Lock.acquire`/:meth:`~Lock.release`. Only the " @@ -861,7 +1104,7 @@ msgid "" "in :meth:`~RLock.acquire` to proceed." msgstr "" -#: ../../library/threading.rst:617 +#: ../../library/threading.rst:790 msgid "" ":meth:`~RLock.acquire`/:meth:`~RLock.release` must be used in pairs: each " "acquire must have a release in the thread that has acquired the lock. " @@ -869,7 +1112,7 @@ msgid "" "deadlock." msgstr "" -#: ../../library/threading.rst:624 +#: ../../library/threading.rst:797 msgid "" "This class implements reentrant lock objects. A reentrant lock must be " "released by the thread that acquired it. Once a thread has acquired a " @@ -877,39 +1120,39 @@ msgid "" "thread must release it once for each time it has acquired it." msgstr "" -#: ../../library/threading.rst:629 +#: ../../library/threading.rst:802 msgid "" "Note that ``RLock`` is actually a factory function which returns an instance " "of the most efficient version of the concrete RLock class that is supported " "by the platform." msgstr "" -#: ../../library/threading.rst:640 +#: ../../library/threading.rst:813 msgid ":ref:`Using RLock as a context manager `" msgstr "" -#: ../../library/threading.rst:641 +#: ../../library/threading.rst:814 msgid "" "Recommended over manual :meth:`!acquire` and :meth:`release` calls whenever " "practical." msgstr "" -#: ../../library/threading.rst:645 +#: ../../library/threading.rst:818 msgid "" "When invoked with the *blocking* argument set to ``True`` (the default):" msgstr "" -#: ../../library/threading.rst:647 ../../library/threading.rst:659 +#: ../../library/threading.rst:820 ../../library/threading.rst:832 msgid "If no thread owns the lock, acquire the lock and return immediately." msgstr "" -#: ../../library/threading.rst:649 +#: ../../library/threading.rst:822 msgid "" "If another thread owns the lock, block until we are able to acquire lock, or " "*timeout*, if set to a positive float value." msgstr "" -#: ../../library/threading.rst:652 +#: ../../library/threading.rst:825 msgid "" "If the same thread owns the lock, acquire the lock again, and return " "immediately. This is the difference between :class:`Lock` and :class:`!" @@ -917,35 +1160,35 @@ msgid "" "until the lock can be acquired." msgstr "" -#: ../../library/threading.rst:657 +#: ../../library/threading.rst:830 msgid "When invoked with the *blocking* argument set to ``False``:" msgstr "" -#: ../../library/threading.rst:661 +#: ../../library/threading.rst:834 msgid "If another thread owns the lock, return immediately." msgstr "" -#: ../../library/threading.rst:663 +#: ../../library/threading.rst:836 msgid "" "If the same thread owns the lock, acquire the lock again and return " "immediately." msgstr "" -#: ../../library/threading.rst:666 +#: ../../library/threading.rst:839 msgid "" "In all cases, if the thread was able to acquire the lock, return ``True``. " "If the thread was unable to acquire the lock (i.e. if not blocking or the " "timeout was reached) return ``False``." msgstr "" -#: ../../library/threading.rst:670 +#: ../../library/threading.rst:843 msgid "" "If called multiple times, failing to call :meth:`~RLock.release` as many " "times may lead to deadlock. Consider using :class:`!RLock` as a context " "manager rather than calling acquire/release directly." msgstr "" -#: ../../library/threading.rst:680 +#: ../../library/threading.rst:853 msgid "" "Release a lock, decrementing the recursion level. If after the decrement it " "is zero, reset the lock to unlocked (not owned by any thread), and if any " @@ -954,18 +1197,18 @@ msgid "" "is still nonzero, the lock remains locked and owned by the calling thread." msgstr "" -#: ../../library/threading.rst:686 +#: ../../library/threading.rst:859 msgid "" "Only call this method when the calling thread owns the lock. A :exc:" "`RuntimeError` is raised if this method is called when the lock is not " "acquired." msgstr "" -#: ../../library/threading.rst:696 -msgid "Condition Objects" +#: ../../library/threading.rst:869 +msgid "Condition objects" msgstr "" -#: ../../library/threading.rst:698 +#: ../../library/threading.rst:871 msgid "" "A condition variable is always associated with some kind of lock; this can " "be passed in or one will be created by default. Passing one in is useful " @@ -973,7 +1216,7 @@ msgid "" "of the condition object: you don't have to track it separately." msgstr "" -#: ../../library/threading.rst:703 +#: ../../library/threading.rst:876 msgid "" "A condition variable obeys the :ref:`context management protocol `: using the ``with`` statement acquires the associated lock for the " @@ -982,7 +1225,7 @@ msgid "" "associated lock." msgstr "" -#: ../../library/threading.rst:709 +#: ../../library/threading.rst:882 msgid "" "Other methods must be called with the associated lock held. The :meth:" "`~Condition.wait` method releases the lock, and then blocks until another " @@ -991,14 +1234,14 @@ msgid "" "and returns. It is also possible to specify a timeout." msgstr "" -#: ../../library/threading.rst:715 +#: ../../library/threading.rst:888 msgid "" "The :meth:`~Condition.notify` method wakes up one of the threads waiting for " "the condition variable, if any are waiting. The :meth:`~Condition." "notify_all` method wakes up all threads waiting for the condition variable." msgstr "" -#: ../../library/threading.rst:719 +#: ../../library/threading.rst:892 msgid "" "Note: the :meth:`~Condition.notify` and :meth:`~Condition.notify_all` " "methods don't release the lock; this means that the thread or threads " @@ -1007,7 +1250,7 @@ msgid "" "or :meth:`~Condition.notify_all` finally relinquishes ownership of the lock." msgstr "" -#: ../../library/threading.rst:725 +#: ../../library/threading.rst:898 msgid "" "The typical programming style using condition variables uses the lock to " "synchronize access to some shared state; threads that are interested in a " @@ -1019,7 +1262,21 @@ msgid "" "situation with unlimited buffer capacity::" msgstr "" -#: ../../library/threading.rst:745 +#: ../../library/threading.rst:907 +msgid "" +"# Consume one item\n" +"with cv:\n" +" while not an_item_is_available():\n" +" cv.wait()\n" +" get_an_available_item()\n" +"\n" +"# Produce one item\n" +"with cv:\n" +" make_an_item_available()\n" +" cv.notify()" +msgstr "" + +#: ../../library/threading.rst:918 msgid "" "The ``while`` loop checking for the application's condition is necessary " "because :meth:`~Condition.wait` can return after an arbitrary long time, and " @@ -1029,7 +1286,15 @@ msgid "" "checking, and eases the computation of timeouts::" msgstr "" -#: ../../library/threading.rst:757 +#: ../../library/threading.rst:925 +msgid "" +"# Consume an item\n" +"with cv:\n" +" cv.wait_for(an_item_is_available)\n" +" get_an_available_item()" +msgstr "" + +#: ../../library/threading.rst:930 msgid "" "To choose between :meth:`~Condition.notify` and :meth:`~Condition." "notify_all`, consider whether one state change can be interesting for only " @@ -1038,45 +1303,45 @@ msgid "" "thread." msgstr "" -#: ../../library/threading.rst:765 +#: ../../library/threading.rst:938 msgid "" "This class implements condition variable objects. A condition variable " "allows one or more threads to wait until they are notified by another thread." msgstr "" -#: ../../library/threading.rst:768 +#: ../../library/threading.rst:941 msgid "" "If the *lock* argument is given and not ``None``, it must be a :class:`Lock` " "or :class:`RLock` object, and it is used as the underlying lock. Otherwise, " "a new :class:`RLock` object is created and used as the underlying lock." msgstr "" -#: ../../library/threading.rst:772 ../../library/threading.rst:896 -#: ../../library/threading.rst:942 ../../library/threading.rst:994 -#: ../../library/threading.rst:1062 +#: ../../library/threading.rst:945 ../../library/threading.rst:1069 +#: ../../library/threading.rst:1115 ../../library/threading.rst:1167 +#: ../../library/threading.rst:1235 msgid "changed from a factory function to a class." msgstr "" -#: ../../library/threading.rst:777 +#: ../../library/threading.rst:950 msgid "" "Acquire the underlying lock. This method calls the corresponding method on " "the underlying lock; the return value is whatever that method returns." msgstr "" -#: ../../library/threading.rst:782 +#: ../../library/threading.rst:955 msgid "" "Release the underlying lock. This method calls the corresponding method on " "the underlying lock; there is no return value." msgstr "" -#: ../../library/threading.rst:787 +#: ../../library/threading.rst:960 msgid "" "Wait until notified or until a timeout occurs. If the calling thread has not " "acquired the lock when this method is called, a :exc:`RuntimeError` is " "raised." msgstr "" -#: ../../library/threading.rst:791 +#: ../../library/threading.rst:964 msgid "" "This method releases the underlying lock, and then blocks until it is " "awakened by a :meth:`notify` or :meth:`notify_all` call for the same " @@ -1084,14 +1349,14 @@ msgid "" "Once awakened or timed out, it re-acquires the lock and returns." msgstr "" -#: ../../library/threading.rst:796 +#: ../../library/threading.rst:969 msgid "" "When the *timeout* argument is present and not ``None``, it should be a " "floating-point number specifying a timeout for the operation in seconds (or " "fractions thereof)." msgstr "" -#: ../../library/threading.rst:800 +#: ../../library/threading.rst:973 msgid "" "When the underlying lock is an :class:`RLock`, it is not released using its :" "meth:`release` method, since this may not actually unlock the lock when it " @@ -1101,24 +1366,24 @@ msgid "" "used to restore the recursion level when the lock is reacquired." msgstr "" -#: ../../library/threading.rst:808 +#: ../../library/threading.rst:981 msgid "" "The return value is ``True`` unless a given *timeout* expired, in which case " "it is ``False``." msgstr "" -#: ../../library/threading.rst:811 ../../library/threading.rst:1027 +#: ../../library/threading.rst:984 ../../library/threading.rst:1200 msgid "Previously, the method always returned ``None``." msgstr "" -#: ../../library/threading.rst:816 +#: ../../library/threading.rst:989 msgid "" "Wait until a condition evaluates to true. *predicate* should be a callable " "which result will be interpreted as a boolean value. A *timeout* may be " "provided giving the maximum time to wait." msgstr "" -#: ../../library/threading.rst:820 +#: ../../library/threading.rst:993 msgid "" "This utility method may call :meth:`wait` repeatedly until the predicate is " "satisfied, or until a timeout occurs. The return value is the last return " @@ -1126,33 +1391,39 @@ msgid "" "out." msgstr "" -#: ../../library/threading.rst:825 +#: ../../library/threading.rst:998 msgid "" "Ignoring the timeout feature, calling this method is roughly equivalent to " "writing::" msgstr "" -#: ../../library/threading.rst:831 +#: ../../library/threading.rst:1001 +msgid "" +"while not predicate():\n" +" cv.wait()" +msgstr "" + +#: ../../library/threading.rst:1004 msgid "" "Therefore, the same rules apply as with :meth:`wait`: The lock must be held " "when called and is re-acquired on return. The predicate is evaluated with " "the lock held." msgstr "" -#: ../../library/threading.rst:839 +#: ../../library/threading.rst:1012 msgid "" "By default, wake up one thread waiting on this condition, if any. If the " "calling thread has not acquired the lock when this method is called, a :exc:" "`RuntimeError` is raised." msgstr "" -#: ../../library/threading.rst:843 +#: ../../library/threading.rst:1016 msgid "" "This method wakes up at most *n* of the threads waiting for the condition " "variable; it is a no-op if no threads are waiting." msgstr "" -#: ../../library/threading.rst:846 +#: ../../library/threading.rst:1019 msgid "" "The current implementation wakes up exactly *n* threads, if at least *n* " "threads are waiting. However, it's not safe to rely on this behavior. A " @@ -1160,14 +1431,14 @@ msgid "" "threads." msgstr "" -#: ../../library/threading.rst:851 +#: ../../library/threading.rst:1024 msgid "" "Note: an awakened thread does not actually return from its :meth:`wait` call " "until it can reacquire the lock. Since :meth:`notify` does not release the " "lock, its caller should." msgstr "" -#: ../../library/threading.rst:857 +#: ../../library/threading.rst:1030 msgid "" "Wake up all threads waiting on this condition. This method acts like :meth:" "`notify`, but wakes up all waiting threads instead of one. If the calling " @@ -1175,15 +1446,15 @@ msgid "" "`RuntimeError` is raised." msgstr "" -#: ../../library/threading.rst:862 +#: ../../library/threading.rst:1035 msgid "The method ``notifyAll`` is a deprecated alias for this method." msgstr "" -#: ../../library/threading.rst:868 -msgid "Semaphore Objects" +#: ../../library/threading.rst:1041 +msgid "Semaphore objects" msgstr "" -#: ../../library/threading.rst:870 +#: ../../library/threading.rst:1043 msgid "" "This is one of the oldest synchronization primitives in the history of " "computer science, invented by the early Dutch computer scientist Edsger W. " @@ -1191,7 +1462,7 @@ msgid "" "acquire` and :meth:`~Semaphore.release`)." msgstr "" -#: ../../library/threading.rst:875 +#: ../../library/threading.rst:1048 msgid "" "A semaphore manages an internal counter which is decremented by each :meth:" "`~Semaphore.acquire` call and incremented by each :meth:`~Semaphore.release` " @@ -1200,12 +1471,12 @@ msgid "" "meth:`~Semaphore.release`." msgstr "" -#: ../../library/threading.rst:881 +#: ../../library/threading.rst:1054 msgid "" "Semaphores also support the :ref:`context management protocol `." msgstr "" -#: ../../library/threading.rst:886 +#: ../../library/threading.rst:1059 msgid "" "This class implements semaphore objects. A semaphore manages an atomic " "counter representing the number of :meth:`release` calls minus the number " @@ -1214,28 +1485,28 @@ msgid "" "If not given, *value* defaults to 1." msgstr "" -#: ../../library/threading.rst:892 +#: ../../library/threading.rst:1065 msgid "" "The optional argument gives the initial *value* for the internal counter; it " "defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is " "raised." msgstr "" -#: ../../library/threading.rst:901 +#: ../../library/threading.rst:1074 msgid "Acquire a semaphore." msgstr "" -#: ../../library/threading.rst:903 +#: ../../library/threading.rst:1076 msgid "When invoked without arguments:" msgstr "" -#: ../../library/threading.rst:905 +#: ../../library/threading.rst:1078 msgid "" "If the internal counter is larger than zero on entry, decrement it by one " "and return ``True`` immediately." msgstr "" -#: ../../library/threading.rst:907 +#: ../../library/threading.rst:1080 msgid "" "If the internal counter is zero on entry, block until awoken by a call to :" "meth:`~Semaphore.release`. Once awoken (and the counter is greater than 0), " @@ -1244,32 +1515,32 @@ msgid "" "threads are awoken should not be relied on." msgstr "" -#: ../../library/threading.rst:913 +#: ../../library/threading.rst:1086 msgid "" "When invoked with *blocking* set to ``False``, do not block. If a call " "without an argument would block, return ``False`` immediately; otherwise, do " "the same thing as when called without arguments, and return ``True``." msgstr "" -#: ../../library/threading.rst:917 +#: ../../library/threading.rst:1090 msgid "" "When invoked with a *timeout* other than ``None``, it will block for at most " "*timeout* seconds. If acquire does not complete successfully in that " "interval, return ``False``. Return ``True`` otherwise." msgstr "" -#: ../../library/threading.rst:926 +#: ../../library/threading.rst:1099 msgid "" "Release a semaphore, incrementing the internal counter by *n*. When it was " "zero on entry and other threads are waiting for it to become larger than " "zero again, wake up *n* of those threads." msgstr "" -#: ../../library/threading.rst:930 +#: ../../library/threading.rst:1103 msgid "Added the *n* parameter to release multiple waiting threads at once." msgstr "" -#: ../../library/threading.rst:936 +#: ../../library/threading.rst:1109 msgid "" "Class implementing bounded semaphore objects. A bounded semaphore checks to " "make sure its current value doesn't exceed its initial value. If it does, :" @@ -1278,11 +1549,11 @@ msgid "" "times it's a sign of a bug. If not given, *value* defaults to 1." msgstr "" -#: ../../library/threading.rst:949 -msgid ":class:`Semaphore` Example" -msgstr "Exemplo :class:`Semaphore`" +#: ../../library/threading.rst:1122 +msgid ":class:`Semaphore` example" +msgstr "" -#: ../../library/threading.rst:951 +#: ../../library/threading.rst:1124 msgid "" "Semaphores are often used to guard resources with limited capacity, for " "example, a database server. In any situation where the size of the resource " @@ -1290,37 +1561,54 @@ msgid "" "threads, your main thread would initialize the semaphore::" msgstr "" -#: ../../library/threading.rst:960 +#: ../../library/threading.rst:1129 +msgid "" +"maxconnections = 5\n" +"# ...\n" +"pool_sema = BoundedSemaphore(value=maxconnections)" +msgstr "" + +#: ../../library/threading.rst:1133 msgid "" "Once spawned, worker threads call the semaphore's acquire and release " "methods when they need to connect to the server::" msgstr "" -#: ../../library/threading.rst:970 +#: ../../library/threading.rst:1136 +msgid "" +"with pool_sema:\n" +" conn = connectdb()\n" +" try:\n" +" # ... use connection ...\n" +" finally:\n" +" conn.close()" +msgstr "" + +#: ../../library/threading.rst:1143 msgid "" "The use of a bounded semaphore reduces the chance that a programming error " "which causes the semaphore to be released more than it's acquired will go " "undetected." msgstr "" -#: ../../library/threading.rst:977 -msgid "Event Objects" +#: ../../library/threading.rst:1150 +msgid "Event objects" msgstr "" -#: ../../library/threading.rst:979 +#: ../../library/threading.rst:1152 msgid "" "This is one of the simplest mechanisms for communication between threads: " "one thread signals an event and other threads wait for it." msgstr "" -#: ../../library/threading.rst:982 +#: ../../library/threading.rst:1155 msgid "" "An event object manages an internal flag that can be set to true with the :" "meth:`~Event.set` method and reset to false with the :meth:`~Event.clear` " "method. The :meth:`~Event.wait` method blocks until the flag is true." msgstr "" -#: ../../library/threading.rst:989 +#: ../../library/threading.rst:1162 msgid "" "Class implementing event objects. An event manages a flag that can be set " "to true with the :meth:`~Event.set` method and reset to false with the :meth:" @@ -1328,49 +1616,49 @@ msgid "" "flag is initially false." msgstr "" -#: ../../library/threading.rst:999 +#: ../../library/threading.rst:1172 msgid "Return ``True`` if and only if the internal flag is true." msgstr "" -#: ../../library/threading.rst:1001 +#: ../../library/threading.rst:1174 msgid "The method ``isSet`` is a deprecated alias for this method." msgstr "" -#: ../../library/threading.rst:1005 +#: ../../library/threading.rst:1178 msgid "" "Set the internal flag to true. All threads waiting for it to become true are " "awakened. Threads that call :meth:`wait` once the flag is true will not " "block at all." msgstr "" -#: ../../library/threading.rst:1011 +#: ../../library/threading.rst:1184 msgid "" "Reset the internal flag to false. Subsequently, threads calling :meth:`wait` " "will block until :meth:`.set` is called to set the internal flag to true " "again." msgstr "" -#: ../../library/threading.rst:1017 +#: ../../library/threading.rst:1190 msgid "" "Block as long as the internal flag is false and the timeout, if given, has " "not expired. The return value represents the reason that this blocking " "method returned; ``True`` if returning because the internal flag is set to " -"true, or ``False`` if a timeout is given and the the internal flag did not " +"true, or ``False`` if a timeout is given and the internal flag did not " "become true within the given wait time." msgstr "" -#: ../../library/threading.rst:1023 +#: ../../library/threading.rst:1196 msgid "" "When the timeout argument is present and not ``None``, it should be a " "floating-point number specifying a timeout for the operation in seconds, or " "fractions thereof." msgstr "" -#: ../../library/threading.rst:1034 -msgid "Timer Objects" -msgstr "Objetos Timer" +#: ../../library/threading.rst:1207 +msgid "Timer objects" +msgstr "" -#: ../../library/threading.rst:1036 +#: ../../library/threading.rst:1209 msgid "" "This class represents an action that should be run only after a certain " "amount of time has passed --- a timer. :class:`Timer` is a subclass of :" @@ -1378,7 +1666,7 @@ msgid "" "threads." msgstr "" -#: ../../library/threading.rst:1040 +#: ../../library/threading.rst:1213 msgid "" "Timers are started, as with threads, by calling their :meth:`Timer.start " "` method. The timer can be stopped (before its action has " @@ -1387,11 +1675,20 @@ msgid "" "interval specified by the user." msgstr "" -#: ../../library/threading.rst:1046 +#: ../../library/threading.rst:1219 msgid "For example::" msgstr "Por exemplo::" -#: ../../library/threading.rst:1057 +#: ../../library/threading.rst:1221 +msgid "" +"def hello():\n" +" print(\"hello, world\")\n" +"\n" +"t = Timer(30.0, hello)\n" +"t.start() # after 30 seconds, \"hello, world\" will be printed" +msgstr "" + +#: ../../library/threading.rst:1230 msgid "" "Create a timer that will run *function* with arguments *args* and keyword " "arguments *kwargs*, after *interval* seconds have passed. If *args* is " @@ -1399,17 +1696,17 @@ msgid "" "``None`` (the default) then an empty dict will be used." msgstr "" -#: ../../library/threading.rst:1067 +#: ../../library/threading.rst:1240 msgid "" "Stop the timer, and cancel the execution of the timer's action. This will " "only work if the timer is still in its waiting stage." msgstr "" -#: ../../library/threading.rst:1072 -msgid "Barrier Objects" +#: ../../library/threading.rst:1245 +msgid "Barrier objects" msgstr "" -#: ../../library/threading.rst:1076 +#: ../../library/threading.rst:1249 msgid "" "This class provides a simple synchronization primitive for use by a fixed " "number of threads that need to wait for each other. Each of the threads " @@ -1418,18 +1715,36 @@ msgid "" "calls. At this point, the threads are released simultaneously." msgstr "" -#: ../../library/threading.rst:1082 +#: ../../library/threading.rst:1255 msgid "" "The barrier can be reused any number of times for the same number of threads." msgstr "" -#: ../../library/threading.rst:1084 +#: ../../library/threading.rst:1257 msgid "" "As an example, here is a simple way to synchronize a client and server " "thread::" msgstr "" -#: ../../library/threading.rst:1104 +#: ../../library/threading.rst:1259 +msgid "" +"b = Barrier(2, timeout=5)\n" +"\n" +"def server():\n" +" start_server()\n" +" b.wait()\n" +" while True:\n" +" connection = accept_connection()\n" +" process_server_connection(connection)\n" +"\n" +"def client():\n" +" b.wait()\n" +" while True:\n" +" connection = make_connection()\n" +" process_client_connection(connection)" +msgstr "" + +#: ../../library/threading.rst:1277 msgid "" "Create a barrier object for *parties* number of threads. An *action*, when " "provided, is a callable to be called by one of the threads when they are " @@ -1437,7 +1752,7 @@ msgid "" "the :meth:`wait` method." msgstr "" -#: ../../library/threading.rst:1111 +#: ../../library/threading.rst:1284 msgid "" "Pass the barrier. When all the threads party to the barrier have called " "this function, they are all released simultaneously. If a *timeout* is " @@ -1445,44 +1760,52 @@ msgid "" "constructor." msgstr "" -#: ../../library/threading.rst:1116 +#: ../../library/threading.rst:1289 msgid "" "The return value is an integer in the range 0 to *parties* -- 1, different " "for each thread. This can be used to select a thread to do some special " "housekeeping, e.g.::" msgstr "" -#: ../../library/threading.rst:1125 +#: ../../library/threading.rst:1293 +msgid "" +"i = barrier.wait()\n" +"if i == 0:\n" +" # Only one thread needs to print this\n" +" print(\"passed the barrier\")" +msgstr "" + +#: ../../library/threading.rst:1298 msgid "" "If an *action* was provided to the constructor, one of the threads will have " "called it prior to being released. Should this call raise an error, the " "barrier is put into the broken state." msgstr "" -#: ../../library/threading.rst:1129 +#: ../../library/threading.rst:1302 msgid "If the call times out, the barrier is put into the broken state." msgstr "" -#: ../../library/threading.rst:1131 +#: ../../library/threading.rst:1304 msgid "" "This method may raise a :class:`BrokenBarrierError` exception if the barrier " "is broken or reset while a thread is waiting." msgstr "" -#: ../../library/threading.rst:1136 +#: ../../library/threading.rst:1309 msgid "" "Return the barrier to the default, empty state. Any threads waiting on it " "will receive the :class:`BrokenBarrierError` exception." msgstr "" -#: ../../library/threading.rst:1139 +#: ../../library/threading.rst:1312 msgid "" "Note that using this function may require some external synchronization if " "there are other threads whose state is unknown. If a barrier is broken it " "may be better to just leave it and create a new one." msgstr "" -#: ../../library/threading.rst:1145 +#: ../../library/threading.rst:1318 msgid "" "Put the barrier into a broken state. This causes any active or future calls " "to :meth:`wait` to fail with the :class:`BrokenBarrierError`. Use this for " @@ -1490,36 +1813,36 @@ msgid "" "application." msgstr "" -#: ../../library/threading.rst:1150 +#: ../../library/threading.rst:1323 msgid "" "It may be preferable to simply create the barrier with a sensible *timeout* " "value to automatically guard against one of the threads going awry." msgstr "" -#: ../../library/threading.rst:1156 +#: ../../library/threading.rst:1329 msgid "The number of threads required to pass the barrier." msgstr "" -#: ../../library/threading.rst:1160 +#: ../../library/threading.rst:1333 msgid "The number of threads currently waiting in the barrier." msgstr "" -#: ../../library/threading.rst:1164 +#: ../../library/threading.rst:1337 msgid "A boolean that is ``True`` if the barrier is in the broken state." msgstr "" -#: ../../library/threading.rst:1169 +#: ../../library/threading.rst:1342 msgid "" "This exception, a subclass of :exc:`RuntimeError`, is raised when the :class:" "`Barrier` object is reset or broken." msgstr "" -#: ../../library/threading.rst:1176 +#: ../../library/threading.rst:1349 msgid "" "Using locks, conditions, and semaphores in the :keyword:`!with` statement" msgstr "" -#: ../../library/threading.rst:1178 +#: ../../library/threading.rst:1351 msgid "" "All of the objects provided by this module that have ``acquire`` and " "``release`` methods can be used as context managers for a :keyword:`with` " @@ -1528,25 +1851,40 @@ msgid "" "following snippet::" msgstr "" -#: ../../library/threading.rst:1187 +#: ../../library/threading.rst:1357 +msgid "" +"with some_lock:\n" +" # do something..." +msgstr "" + +#: ../../library/threading.rst:1360 msgid "is equivalent to::" msgstr "é equivalente a::" -#: ../../library/threading.rst:1195 +#: ../../library/threading.rst:1362 +msgid "" +"some_lock.acquire()\n" +"try:\n" +" # do something...\n" +"finally:\n" +" some_lock.release()" +msgstr "" + +#: ../../library/threading.rst:1368 msgid "" "Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`, :class:" "`Semaphore`, and :class:`BoundedSemaphore` objects may be used as :keyword:" "`with` statement context managers." msgstr "" -#: ../../library/threading.rst:158 ../../library/threading.rst:176 +#: ../../library/threading.rst:222 ../../library/threading.rst:240 msgid "trace function" -msgstr "" +msgstr "função de rastreamento" -#: ../../library/threading.rst:176 +#: ../../library/threading.rst:240 msgid "debugger" msgstr "depurador" -#: ../../library/threading.rst:187 ../../library/threading.rst:205 +#: ../../library/threading.rst:251 ../../library/threading.rst:269 msgid "profile function" -msgstr "" +msgstr "função de perfilação" diff --git a/library/time.po b/library/time.po index 47693d834..b73ca0c58 100644 --- a/library/time.po +++ b/library/time.po @@ -1,37 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Welington Carlos , 2021 -# Misael borges , 2021 -# Danielle Farias , 2021 -# Vinicius Gubiani Ferreira , 2021 -# i17obot , 2021 -# mvpetri , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Rodrigo Queiroz , 2021 -# Vitor Buxbaum Orlandi, 2021 -# (Douglas da Silva) , 2024 -# Marco Rougeth , 2024 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:15+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-03-14 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -70,8 +58,9 @@ msgid "" "The :dfn:`epoch` is the point where the time starts, the return value of " "``time.gmtime(0)``. It is January 1, 1970, 00:00:00 (UTC) on all platforms." msgstr "" -"O :dfn:`epoch` é o ponto onde o tempo começa, o valor de retorno de ``time." -"gmtime(0)``. É 1º de janeiro de 1970, 00:00:00 (UTC) em todas as plataformas." +"O :dfn:`era` (*epoch*) é o ponto onde o tempo começa, o valor de retorno de " +"``time.gmtime(0)``. É 1º de janeiro de 1970, 00:00:00 (UTC) em todas as " +"plataformas." #: ../../library/time.rst:31 msgid "" @@ -91,8 +80,8 @@ msgid "" "by the C library; for 32-bit systems, it is typically in 2038." msgstr "" "As funções desse módulo podem não conseguir tratar de datas e horários antes " -"da era_ ou muito distantes no futuro. O limite no futuro é determinado pela " -"biblioteca C; para sistemas de 32 bit, geralmente é 2038." +"do epoch_ ou muito distantes no futuro. O limite no futuro é determinado " +"pela biblioteca C; para sistemas de 32 bit, geralmente é 2038." #: ../../library/time.rst:45 msgid "" @@ -108,15 +97,19 @@ msgstr "" #: ../../library/time.rst:55 msgid "" -"UTC is Coordinated Universal Time (formerly known as Greenwich Mean Time, or " -"GMT). The acronym UTC is not a mistake but a compromise between English and " -"French." +"UTC is `Coordinated Universal Time`_ and superseded `Greenwich Mean Time`_ " +"or GMT as the basis of international timekeeping. The acronym UTC is not a " +"mistake but conforms to an earlier, language-agnostic naming scheme for time " +"standards such as UT0, UT1, and UT2." msgstr "" -"UTC é Coordinated Universal Time (antigamente conhecido como Greenwich Mean " -"Time ou GMT). O acrônimo UTC não é um erro, mas um acordo entre inglês e " -"francês." +"UTC é `Coordinated Universal Time`_ (em português, Horário Universal " +"Coordenado) e substituiu o GMT ou `Greenwich Mean Time`_ (em português, " +"Horário Médio de Greenwich) como base da cronometragem internacional. A " +"sigla UTC não é um erro, mas está em conformidade com um esquema de " +"nomenclatura anterior, independente de idioma, para padrões de tempo como " +"UT0, UT1 e UT2." -#: ../../library/time.rst:61 +#: ../../library/time.rst:65 msgid "" "DST is Daylight Saving Time, an adjustment of the timezone by (usually) one " "hour during part of the year. DST rules are magic (determined by local law) " @@ -131,7 +124,7 @@ msgstr "" "de um arquivo de sistema por flexibilidade) e nesse contexto é a única fonte " "de Conhecimento Verdadeiro." -#: ../../library/time.rst:67 +#: ../../library/time.rst:71 msgid "" "The precision of the various real-time functions may be less than suggested " "by the units in which their value or argument is expressed. E.g. on most " @@ -142,7 +135,7 @@ msgstr "" "expressos. Por exemplo, na maioria dos sistemas Unix, o relógio \"conta\" " "apenas 50 ou 100 vezes por segundo." -#: ../../library/time.rst:71 +#: ../../library/time.rst:75 msgid "" "On the other hand, the precision of :func:`.time` and :func:`sleep` is " "better than their Unix equivalents: times are expressed as floating-point " @@ -158,7 +151,7 @@ msgstr "" "`sleep` irá aceitar qualquer tempo como uma fração não zero (:c:func:`!" "select` do Unix é utilizada para implementar isto, quando disponível)." -#: ../../library/time.rst:78 +#: ../../library/time.rst:82 msgid "" "The time value as returned by :func:`gmtime`, :func:`localtime`, and :func:" "`strptime`, and accepted by :func:`asctime`, :func:`mktime` and :func:" @@ -172,11 +165,11 @@ msgstr "" "`gmtime`, :func:`localtime`, e :func:`strptime` também oferecem nomes de " "atributo para campos individuais." -#: ../../library/time.rst:84 +#: ../../library/time.rst:88 msgid "See :class:`struct_time` for a description of these objects." msgstr "Veja :class:`struct_time` para a descrição desses objetos." -#: ../../library/time.rst:86 +#: ../../library/time.rst:90 msgid "" "The :class:`struct_time` type was extended to provide the :attr:" "`~struct_time.tm_gmtoff` and :attr:`~struct_time.tm_zone` attributes when " @@ -186,7 +179,7 @@ msgstr "" "`~struct_time.tm_gmtoff` e :attr:`~struct_time.tm_zone` quando a plataforma " "suporta os membros ``struct tm`` correspondentes" -#: ../../library/time.rst:92 +#: ../../library/time.rst:96 msgid "" "The :class:`struct_time` attributes :attr:`~struct_time.tm_gmtoff` and :attr:" "`~struct_time.tm_zone` are now available on all platforms." @@ -195,58 +188,58 @@ msgstr "" "da classe :class:`struct_time` estão disponíveis em todas as plataformas " "agora." -#: ../../library/time.rst:97 +#: ../../library/time.rst:101 msgid "Use the following functions to convert between time representations:" msgstr "" "Utilize as seguintes funções para converter entre representações de tempo:" -#: ../../library/time.rst:100 +#: ../../library/time.rst:104 msgid "From" msgstr "De" -#: ../../library/time.rst:100 +#: ../../library/time.rst:104 msgid "To" msgstr "Para" -#: ../../library/time.rst:100 +#: ../../library/time.rst:104 msgid "Use" msgstr "Utilize" -#: ../../library/time.rst:29 ../../library/time.rst:102 -#: ../../library/time.rst:105 ../../library/time.rst:108 -#: ../../library/time.rst:111 +#: ../../library/time.rst:29 ../../library/time.rst:106 +#: ../../library/time.rst:109 ../../library/time.rst:112 +#: ../../library/time.rst:115 msgid "seconds since the epoch" msgstr "segundos desde a era" -#: ../../library/time.rst:102 ../../library/time.rst:108 +#: ../../library/time.rst:106 ../../library/time.rst:112 msgid ":class:`struct_time` in UTC" msgstr ":class:`struct_time` em UTC" -#: ../../library/time.rst:102 +#: ../../library/time.rst:106 msgid ":func:`gmtime`" msgstr ":func:`gmtime`" -#: ../../library/time.rst:105 ../../library/time.rst:111 +#: ../../library/time.rst:109 ../../library/time.rst:115 msgid ":class:`struct_time` in local time" msgstr ":class:`struct_time` em tempo local" -#: ../../library/time.rst:105 +#: ../../library/time.rst:109 msgid ":func:`localtime`" msgstr ":func:`localtime`" -#: ../../library/time.rst:108 +#: ../../library/time.rst:112 msgid ":func:`calendar.timegm`" msgstr ":func:`calendar.timegm`" -#: ../../library/time.rst:111 +#: ../../library/time.rst:115 msgid ":func:`mktime`" msgstr ":func:`mktime`" -#: ../../library/time.rst:119 +#: ../../library/time.rst:123 msgid "Functions" msgstr "Funções" -#: ../../library/time.rst:123 +#: ../../library/time.rst:127 msgid "" "Convert a tuple or :class:`struct_time` representing a time as returned by :" "func:`gmtime` or :func:`localtime` to a string of the following form: ``'Sun " @@ -259,7 +252,7 @@ msgstr "" "caracteres e possui espaçamento se o dia é de apenas um dígito. Por exemplo, " "``'Wed Jun 9 04:26:40 1993'``." -#: ../../library/time.rst:129 +#: ../../library/time.rst:133 msgid "" "If *t* is not provided, the current time as returned by :func:`localtime` is " "used. Locale information is not used by :func:`asctime`." @@ -267,7 +260,7 @@ msgstr "" "Se *t* não é fornecido, o tempo atual como retornado por :func:`localtime` é " "utilizado. Informação de localidade não é utilizada por :func:`asctime`." -#: ../../library/time.rst:134 +#: ../../library/time.rst:138 msgid "" "Unlike the C function of the same name, :func:`asctime` does not add a " "trailing newline." @@ -275,7 +268,7 @@ msgstr "" "Diferentemente da função em C de mesmo nome, :func:`asctime` não adiciona " "uma nova linha em seguida." -#: ../../library/time.rst:139 +#: ../../library/time.rst:143 msgid "" "Return the *clk_id* of the thread-specific CPU-time clock for the specified " "*thread_id*." @@ -283,7 +276,7 @@ msgstr "" "Retorna o *clk_id* do relógio de tempo de CPU específico da thread para a " "*thread_id* especificada." -#: ../../library/time.rst:141 +#: ../../library/time.rst:145 msgid "" "Use :func:`threading.get_ident` or the :attr:`~threading.Thread.ident` " "attribute of :class:`threading.Thread` objects to get a suitable value for " @@ -293,7 +286,7 @@ msgstr "" "ident` dos objetos :class:`threading.Thread` para obter um valor adequado " "para *thread_id*." -#: ../../library/time.rst:146 +#: ../../library/time.rst:150 msgid "" "Passing an invalid or expired *thread_id* may result in undefined behavior, " "such as segmentation fault." @@ -301,11 +294,21 @@ msgstr "" "Passando um *thread_id* inválido ou expirado pode resultar em um " "comportamento indefinido, como, por exemplo, falha de segmentação." -#: ../../library/time.rst:149 -msgid ":ref:`Availability `: Unix" -msgstr ":ref:`Disponibilidade `: Unix" - -#: ../../library/time.rst:151 +#: ../../library/time.rst:153 ../../library/time.rst:165 +#: ../../library/time.rst:178 ../../library/time.rst:187 +#: ../../library/time.rst:200 ../../library/time.rst:209 +#: ../../library/time.rst:747 ../../library/time.rst:771 +#: ../../library/time.rst:867 ../../library/time.rst:878 +#: ../../library/time.rst:888 ../../library/time.rst:898 +#: ../../library/time.rst:907 ../../library/time.rst:916 +#: ../../library/time.rst:925 ../../library/time.rst:936 +#: ../../library/time.rst:944 ../../library/time.rst:955 +#: ../../library/time.rst:966 ../../library/time.rst:975 +#: ../../library/time.rst:988 +msgid "Availability" +msgstr "Disponibilidade" + +#: ../../library/time.rst:155 msgid "" "See the man page for :manpage:`pthread_getcpuclockid(3)` for further " "information." @@ -313,7 +316,7 @@ msgstr "" "Veja a página man para :manpage:`pthread_getcpuclockid(3)` para mais " "informações." -#: ../../library/time.rst:158 +#: ../../library/time.rst:162 msgid "" "Return the resolution (precision) of the specified clock *clk_id*. Refer " "to :ref:`time-clock-id-constants` for a list of accepted values for *clk_id*." @@ -321,15 +324,7 @@ msgstr "" "Retorna a resolução (precisão) do relógio *clk_id* especificado. Confira :" "ref:`time-clock-id-constants` para uma lista de valores aceitos para *clk_id*" -#: ../../library/time.rst:161 ../../library/time.rst:174 -#: ../../library/time.rst:183 ../../library/time.rst:196 -#: ../../library/time.rst:205 ../../library/time.rst:745 -#: ../../library/time.rst:862 ../../library/time.rst:890 -#: ../../library/time.rst:918 ../../library/time.rst:962 -msgid ":ref:`Availability `: Unix." -msgstr ":ref:`Disponibilidade `: Unix." - -#: ../../library/time.rst:168 +#: ../../library/time.rst:172 msgid "" "Return the time of the specified clock *clk_id*. Refer to :ref:`time-clock-" "id-constants` for a list of accepted values for *clk_id*." @@ -337,7 +332,7 @@ msgstr "" "Retorna o tempo to relógio *clk_id* especificado. Confira :ref:`time-clock-" "id-constants` para uma lista de valores aceitos para *clk_id*." -#: ../../library/time.rst:171 +#: ../../library/time.rst:175 msgid "" "Use :func:`clock_gettime_ns` to avoid the precision loss caused by the :" "class:`float` type." @@ -345,12 +340,12 @@ msgstr "" "Use :func:`clock_gettime_ns` para evitar perda de precisão causada pelo " "tipo :class:`float`." -#: ../../library/time.rst:181 +#: ../../library/time.rst:185 msgid "Similar to :func:`clock_gettime` but return time as nanoseconds." msgstr "" "Semelhante à :func:`clock_gettime`, mas retorna o tempo em nanossegundos." -#: ../../library/time.rst:190 +#: ../../library/time.rst:194 msgid "" "Set the time of the specified clock *clk_id*. Currently, :data:" "`CLOCK_REALTIME` is the only accepted value for *clk_id*." @@ -358,7 +353,7 @@ msgstr "" "Define o tempo do relógio *clk_id* especificado. Atualmente, :data:" "`CLOCK_REALTIME` é o único valor aceito para *clk_id*." -#: ../../library/time.rst:193 +#: ../../library/time.rst:197 msgid "" "Use :func:`clock_settime_ns` to avoid the precision loss caused by the :" "class:`float` type." @@ -366,24 +361,24 @@ msgstr "" "Use :func:`clock_settime_ns` para evitar perda de precisão causada pelo " "tipo :class:`float`." -#: ../../library/time.rst:203 +#: ../../library/time.rst:207 msgid "Similar to :func:`clock_settime` but set time with nanoseconds." msgstr "" "Semelhante à :func:`clock_settime`, mas define o tempo em nanossegundos." -#: ../../library/time.rst:212 +#: ../../library/time.rst:216 msgid "" "Convert a time expressed in seconds since the epoch_ to a string of a form: " "``'Sun Jun 20 23:21:05 1993'`` representing local time. The day field is two " "characters long and is space padded if the day is a single digit, e.g.: " "``'Wed Jun 9 04:26:40 1993'``." msgstr "" -"Converte um tempo expresso em segundos desde a era_ para uma string de " +"Converte um tempo expresso em segundos desde o epoch_ para uma string de " "forma: ``'Sun Jun 20 23:21:05 1993'`` representando tempo local. O campo dia " "tem comprimento de dois caracteres e é deslocado por um espaço se o dia tem " "um único dígito. Por exemplo, ``'Wed Jun 9 04:26:40 1993'``." -#: ../../library/time.rst:217 +#: ../../library/time.rst:221 msgid "" "If *secs* is not provided or :const:`None`, the current time as returned by :" "func:`.time` is used. ``ctime(secs)`` is equivalent to " @@ -395,7 +390,7 @@ msgstr "" "``asctime(localtime(secs))``. Informação de localidade não é utilizada por :" "func:`ctime`." -#: ../../library/time.rst:225 +#: ../../library/time.rst:229 msgid "" "Get information on the specified clock as a namespace object. Supported " "clock names and the corresponding functions to read their value are:" @@ -404,31 +399,31 @@ msgstr "" "de relógios suportados e as funções correspondentes para ler seus valores " "são:" -#: ../../library/time.rst:229 +#: ../../library/time.rst:233 msgid "``'monotonic'``: :func:`time.monotonic`" msgstr "``'monotonic'``: :func:`time.monotonic`" -#: ../../library/time.rst:230 +#: ../../library/time.rst:234 msgid "``'perf_counter'``: :func:`time.perf_counter`" msgstr "``'perf_counter'``: :func:`time.perf_counter`" -#: ../../library/time.rst:231 +#: ../../library/time.rst:235 msgid "``'process_time'``: :func:`time.process_time`" msgstr "``'process_time'``: :func:`time.process_time`" -#: ../../library/time.rst:232 +#: ../../library/time.rst:236 msgid "``'thread_time'``: :func:`time.thread_time`" msgstr "``'thread_time'``: :func:`time.thread_time`" -#: ../../library/time.rst:233 +#: ../../library/time.rst:237 msgid "``'time'``: :func:`time.time`" msgstr "``'time'``: :func:`time.time`" -#: ../../library/time.rst:235 +#: ../../library/time.rst:239 msgid "The result has the following attributes:" -msgstr "O resultado possui os seguintes atributos:" +msgstr "O resultado tem os seguintes atributos:" -#: ../../library/time.rst:237 +#: ../../library/time.rst:241 msgid "" "*adjustable*: ``True`` if the clock can be changed automatically (e.g. by a " "NTP daemon) or manually by the system administrator, ``False`` otherwise" @@ -437,7 +432,7 @@ msgstr "" "exemplo, por um daemon NTP) ou manualmente por um administrador do sistema, " "``False`` se contrário" -#: ../../library/time.rst:239 +#: ../../library/time.rst:243 msgid "" "*implementation*: The name of the underlying C function used to get the " "clock value. Refer to :ref:`time-clock-id-constants` for possible values." @@ -445,18 +440,18 @@ msgstr "" "*implementation*: O nome da função C subjacente utilizada para obter o valor " "do relógio. Confira :ref:`time-clock-id-constants` para valores possíveis." -#: ../../library/time.rst:241 +#: ../../library/time.rst:245 msgid "" "*monotonic*: ``True`` if the clock cannot go backward, ``False`` otherwise" msgstr "" "*monotonic*: ``True`` se o relógio não pode retornar a valores anteriores, " "backward, ``False`` contrário" -#: ../../library/time.rst:243 +#: ../../library/time.rst:247 msgid "*resolution*: The resolution of the clock in seconds (:class:`float`)" msgstr "*resolution*: A resolução do relógio em segundos (:class:`float`)" -#: ../../library/time.rst:250 +#: ../../library/time.rst:254 msgid "" "Convert a time expressed in seconds since the epoch_ to a :class:" "`struct_time` in UTC in which the dst flag is always zero. If *secs* is not " @@ -465,14 +460,14 @@ msgid "" "the :class:`struct_time` object. See :func:`calendar.timegm` for the inverse " "of this function." msgstr "" -"Converte um tempo expresso em segundos desde a era_ para uma :class:" +"Converte um tempo expresso em segundos desde o epoch_ para uma :class:" "`struct_time` em UTC onde o sinalizador de horário de verão é sempre zero. " "Se *secs* não é fornecido ou :const:`None`, o tempo atual como retornado " "por :func:`.time` é utilizado. Frações de segundo são ignoradas. Veja acima " "para uma descrição do objeto :class:`struct_time`. Veja :func:`calendar." "timegm` para o inverso desta função." -#: ../../library/time.rst:260 +#: ../../library/time.rst:264 msgid "" "Like :func:`gmtime` but converts to local time. If *secs* is not provided " "or :const:`None`, the current time as returned by :func:`.time` is used. " @@ -483,7 +478,7 @@ msgstr "" "é utilizado. O sinalizador de horário de verão é definido como ``1`` quando " "o Horário de verão for aplicável para o tempo fornecido." -#: ../../library/time.rst:264 +#: ../../library/time.rst:268 msgid "" ":func:`localtime` may raise :exc:`OverflowError`, if the timestamp is " "outside the range of values supported by the platform C :c:func:`localtime` " @@ -497,7 +492,7 @@ msgstr "" "`localtime` ou :c:func:`gmtime` falharem. É comum É comum que isso seja " "restrito a anos de 1970 a 2038." -#: ../../library/time.rst:273 +#: ../../library/time.rst:277 msgid "" "This is the inverse function of :func:`localtime`. Its argument is the :" "class:`struct_time` or full 9-tuple (since the dst flag is needed; use " @@ -520,7 +515,7 @@ msgstr "" "C subjacentes). A data mais recente para qual um tempo pode ser gerado é " "dependente da plataforma." -#: ../../library/time.rst:285 +#: ../../library/time.rst:289 msgid "" "Return the value (in fractional seconds) of a monotonic clock, i.e. a clock " "that cannot go backwards. The clock is not affected by system clock " @@ -533,11 +528,11 @@ msgstr "" "retornado é indefinido, portanto apenas a diferença entre os resultados de " "duas chamadas é válida." -#: ../../library/time.rst:290 ../../library/time.rst:687 +#: ../../library/time.rst:294 ../../library/time.rst:713 msgid "Clock:" msgstr "Relógio:" -#: ../../library/time.rst:292 +#: ../../library/time.rst:296 msgid "" "On Windows, call ``QueryPerformanceCounter()`` and " "``QueryPerformanceFrequency()``." @@ -545,23 +540,23 @@ msgstr "" "No Windows, chama ``QueryPerformanceCounter()`` e " "``QueryPerformanceFrequency()``." -#: ../../library/time.rst:294 +#: ../../library/time.rst:298 msgid "On macOS, call ``mach_absolute_time()`` and ``mach_timebase_info()``." msgstr "No macOS, chama ``mach_absolute_time()`` e ``mach_timebase_info()``." -#: ../../library/time.rst:295 +#: ../../library/time.rst:299 msgid "On HP-UX, call ``gethrtime()``." msgstr "No HP-UX, chama ``gethrtime()``." -#: ../../library/time.rst:296 +#: ../../library/time.rst:300 msgid "Call ``clock_gettime(CLOCK_HIGHRES)`` if available." msgstr "Chama ``clock_gettime(CLOCK_HIGHRES)`` se disponível." -#: ../../library/time.rst:297 +#: ../../library/time.rst:301 msgid "Otherwise, call ``clock_gettime(CLOCK_MONOTONIC)``." msgstr "Do contrário, chama ``clock_gettime(CLOCK_MONOTONIC)``." -#: ../../library/time.rst:299 +#: ../../library/time.rst:303 msgid "" "Use :func:`monotonic_ns` to avoid the precision loss caused by the :class:" "`float` type." @@ -569,19 +564,19 @@ msgstr "" "Use :func:`monotonic_ns` para evitar perda de precisão causada pelo tipo :" "class:`float`." -#: ../../library/time.rst:304 +#: ../../library/time.rst:308 msgid "The function is now always available and always system-wide." msgstr "A função agora é sempre disponível e sempre de todo o sistema." -#: ../../library/time.rst:307 +#: ../../library/time.rst:311 msgid "On macOS, the function is now system-wide." msgstr "No macOS, a função agora é no âmbito do sistema." -#: ../../library/time.rst:313 +#: ../../library/time.rst:317 msgid "Similar to :func:`monotonic`, but return time as nanoseconds." msgstr "Semelhante à :func:`monotonic`, mas retorna tempo em nanossegundos." -#: ../../library/time.rst:322 +#: ../../library/time.rst:326 msgid "" "Return the value (in fractional seconds) of a performance counter, i.e. a " "clock with the highest available resolution to measure a short duration. It " @@ -595,15 +590,15 @@ msgstr "" "referência é do valor retornado é indefinido, portanto apenas a diferença " "entre resultados de duas chamadas é válida." -#: ../../library/time.rst:330 +#: ../../library/time.rst:334 msgid "" -"On CPython, use the same clock than :func:`time.monotonic()` and is a " -"monotonic clock, i.e. a clock that cannot go backwards." +"On CPython, use the same clock as :func:`time.monotonic` and is a monotonic " +"clock, i.e. a clock that cannot go backwards." msgstr "" -"No CPython, use o mesmo relógio que :func:`time.monotonic()` e é um relógio " +"No CPython, use o mesmo relógio que :func:`time.monotonic` e é um relógio " "monotônico, ou seja, um relógio que não pode retroceder." -#: ../../library/time.rst:333 +#: ../../library/time.rst:337 msgid "" "Use :func:`perf_counter_ns` to avoid the precision loss caused by the :class:" "`float` type." @@ -611,20 +606,20 @@ msgstr "" "Use :func:`perf_counter_ns` para evitar perda de precisão causada pelo tipo :" "class:`float`." -#: ../../library/time.rst:338 +#: ../../library/time.rst:342 msgid "On Windows, the function is now system-wide." msgstr "No Windows, a função agora é no âmbito do sistema." -#: ../../library/time.rst:341 -msgid "Use the same clock than :func:`time.monotonic()`." -msgstr "Usa o mesmo relógio que :func:`time.monotonic()`." +#: ../../library/time.rst:345 +msgid "Use the same clock as :func:`time.monotonic`." +msgstr "Usa o mesmo relógio que :func:`time.monotonic`." -#: ../../library/time.rst:347 +#: ../../library/time.rst:351 msgid "Similar to :func:`perf_counter`, but return time as nanoseconds." msgstr "" "Semelhante à :func:`perf_counter`, mas retorna o tempo em nanossegundos." -#: ../../library/time.rst:359 +#: ../../library/time.rst:363 msgid "" "Return the value (in fractional seconds) of the sum of the system and user " "CPU time of the current process. It does not include time elapsed during " @@ -638,7 +633,7 @@ msgstr "" "é indefinido, então apenas a diferença dos resultados de duas chamadas é " "válida." -#: ../../library/time.rst:365 +#: ../../library/time.rst:369 msgid "" "Use :func:`process_time_ns` to avoid the precision loss caused by the :class:" "`float` type." @@ -646,12 +641,12 @@ msgstr "" "Use :func:`process_time_ns` para evitar perda de precisão causada pelo tipo :" "class:`float`." -#: ../../library/time.rst:372 +#: ../../library/time.rst:376 msgid "Similar to :func:`process_time` but return time as nanoseconds." msgstr "" "Semelhante à :func:`process_time`, mas retorna o tempo em nanossegundos." -#: ../../library/time.rst:378 +#: ../../library/time.rst:382 msgid "" "Suspend execution of the calling thread for the given number of seconds. The " "argument may be a floating-point number to indicate a more precise sleep " @@ -661,7 +656,7 @@ msgstr "" "segundos. O argumento pode ser um número de ponto flutuante para indicar um " "tempo de pausa mais preciso." -#: ../../library/time.rst:382 +#: ../../library/time.rst:386 msgid "" "If the sleep is interrupted by a signal and no exception is raised by the " "signal handler, the sleep is restarted with a recomputed timeout." @@ -670,7 +665,7 @@ msgstr "" "pelo manipulador de sinal, a pausa será reiniciada com um tempo limite " "recalculado." -#: ../../library/time.rst:385 +#: ../../library/time.rst:389 msgid "" "The suspension time may be longer than requested by an arbitrary amount, " "because of the scheduling of other activity in the system." @@ -678,42 +673,61 @@ msgstr "" "O tempo de suspensão pode ser maior do que o solicitado por um valor " "arbitrário, devido ao agendamento de outras atividades no sistema." -#: ../../library/time.rst:388 +#: ../../library/time.rst:393 +msgid "Windows implementation" +msgstr "Implementação no Windows" + +#: ../../library/time.rst:394 msgid "" "On Windows, if *secs* is zero, the thread relinquishes the remainder of its " "time slice to any other thread that is ready to run. If there are no other " "threads ready to run, the function returns immediately, and the thread " "continues execution. On Windows 8.1 and newer the implementation uses a " -"`high-resolution timer `_ which provides resolution of 100 " +"`high-resolution timer `_ which provides resolution of 100 " "nanoseconds. If *secs* is zero, ``Sleep(0)`` is used." msgstr "" "No Windows, se *secs* é zero, a thread renuncia ao restante de sua fatia de " "tempo para qualquer outra thread que esteja pronto para executar. Se nenhuma " "outra thread estiver pronta pra ser executada, a função retorna " "imediatamente, e a thread continua a execução. No Windows 8.1 e mais novos a " -"implementação usa um `temporizador de alta resolução `_ que " +"implementação usa um `temporizador de alta resolução `_ que " "provê uma resolução de 100 nanossegundos. Se *secs* é zero, é usado " "``Sleep(0)``." -#: ../../library/time.rst:396 -msgid "Unix implementation:" -msgstr "Implementação no Unix:" +#: ../../library/time.rst:403 +msgid "Unix implementation" +msgstr "Implementação no Unix" -#: ../../library/time.rst:398 +#: ../../library/time.rst:404 msgid "Use ``clock_nanosleep()`` if available (resolution: 1 nanosecond);" msgstr "Usa ``clock_nanosleep()`` se disponível (resolução: 1 nanossegundo);" -#: ../../library/time.rst:399 +#: ../../library/time.rst:405 msgid "Or use ``nanosleep()`` if available (resolution: 1 nanosecond);" msgstr "Ou usa ``nanosleep()`` se disponível (resolução: 1 nanossegunda);" -#: ../../library/time.rst:400 +#: ../../library/time.rst:406 msgid "Or use ``select()`` (resolution: 1 microsecond)." msgstr "Ou usa ``select()`` (resolução: 1 microssegundo)." -#: ../../library/time.rst:402 +#: ../../library/time.rst:410 +msgid "" +"To emulate a \"no-op\", use :keyword:`pass` instead of ``time.sleep(0)``." +msgstr "" +"Para emular um \"no-op\", use :keyword:`pass` em vez de ``time.sleep(0)``." + +#: ../../library/time.rst:412 +msgid "" +"To voluntarily relinquish the CPU, specify a real-time :ref:`scheduling " +"policy ` and use :func:`os.sched_yield` instead." +msgstr "" +"Para abrir mão voluntariamente da CPU, especifique uma :ref:`política de " +"agendamento ` em tempo real e use :func:`os." +"sched_yield` em seu lugar." + +#: ../../library/time.rst:415 msgid "" "Raises an :ref:`auditing event ` ``time.sleep`` with argument " "``secs``." @@ -721,7 +735,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``time.sleep`` com o " "argumento ``secs``." -#: ../../library/time.rst:404 +#: ../../library/time.rst:417 msgid "" "The function now sleeps at least *secs* even if the sleep is interrupted by " "a signal, except if the signal handler raises an exception (see :pep:`475` " @@ -731,20 +745,20 @@ msgstr "" "por um sinal, exceto se o tratador de sinal levanta uma exceção (veja :pep:" "`475` para a explicação)." -#: ../../library/time.rst:409 +#: ../../library/time.rst:422 msgid "" "On Unix, the ``clock_nanosleep()`` and ``nanosleep()`` functions are now " "used if available. On Windows, a waitable timer is now used." msgstr "" -"No Unix, as funções ``clock_nanosleep()`` e ``nanosleep()``são agora usadas " +"No Unix, as funções ``clock_nanosleep()`` e ``nanosleep()`` são agora usadas " "se estiverem disponíveis. No Windows, um temporizador aguardável é agora " "usado." -#: ../../library/time.rst:413 +#: ../../library/time.rst:426 msgid "Raises an auditing event." msgstr "Levanta um evento de auditoria." -#: ../../library/time.rst:421 +#: ../../library/time.rst:434 msgid "" "Convert a tuple or :class:`struct_time` representing a time as returned by :" "func:`gmtime` or :func:`localtime` to a string as specified by the *format* " @@ -759,7 +773,7 @@ msgstr "" "string. A exceção :exc:`ValueError` é levantada se qualquer campo em *t* " "está fora do intervalo permitido." -#: ../../library/time.rst:427 +#: ../../library/time.rst:440 msgid "" "0 is a legal argument for any position in the time tuple; if it is normally " "illegal the value is forced to a correct one." @@ -767,7 +781,7 @@ msgstr "" "0 é um argumento legal para qualquer posição na tupla de tempo; se é " "normalmente ilegal, o valor é formado a um valor correto." -#: ../../library/time.rst:430 +#: ../../library/time.rst:443 msgid "" "The following directives can be embedded in the *format* string. They are " "shown without the optional field width and precision specification, and are " @@ -778,151 +792,151 @@ msgstr "" "opcionais, e estão substituídos pelos caracteres indicados no resultado da :" "func:`strftime`:" -#: ../../library/time.rst:435 +#: ../../library/time.rst:448 msgid "Directive" msgstr "Diretiva" -#: ../../library/time.rst:435 +#: ../../library/time.rst:448 msgid "Meaning" msgstr "Significado" -#: ../../library/time.rst:435 +#: ../../library/time.rst:448 msgid "Notes" msgstr "Notas" -#: ../../library/time.rst:437 +#: ../../library/time.rst:450 msgid "``%a``" msgstr "``%a``" -#: ../../library/time.rst:437 +#: ../../library/time.rst:450 msgid "Locale's abbreviated weekday name." msgstr "Nome abreviado do dia da semana da localidade." -#: ../../library/time.rst:440 +#: ../../library/time.rst:453 msgid "``%A``" msgstr "``%A``" -#: ../../library/time.rst:440 +#: ../../library/time.rst:453 msgid "Locale's full weekday name." msgstr "Nome completo do dia da semana da localidade." -#: ../../library/time.rst:442 +#: ../../library/time.rst:455 msgid "``%b``" msgstr "``%b``" -#: ../../library/time.rst:442 +#: ../../library/time.rst:455 msgid "Locale's abbreviated month name." msgstr "Nome abreviado do mês da localidade." -#: ../../library/time.rst:445 +#: ../../library/time.rst:458 msgid "``%B``" msgstr "``%B``" -#: ../../library/time.rst:445 +#: ../../library/time.rst:458 msgid "Locale's full month name." msgstr "Nome completo do mês da localidade." -#: ../../library/time.rst:447 +#: ../../library/time.rst:460 msgid "``%c``" msgstr "``%c``" -#: ../../library/time.rst:447 +#: ../../library/time.rst:460 msgid "Locale's appropriate date and time representation." msgstr "Representação de data e hora apropriada da localidade." -#: ../../library/time.rst:450 +#: ../../library/time.rst:463 msgid "``%d``" msgstr "``%d``" -#: ../../library/time.rst:450 +#: ../../library/time.rst:463 msgid "Day of the month as a decimal number [01,31]." msgstr "Dia do mês como um número decimal [01,31]." -#: ../../library/time.rst:453 +#: ../../library/time.rst:466 msgid "``%f``" msgstr "``%f``" -#: ../../library/time.rst:453 +#: ../../library/time.rst:466 msgid "Microseconds as a decimal number" msgstr "Microssegundos como um número decimal" -#: ../../library/time.rst:454 +#: ../../library/time.rst:467 msgid "[000000,999999]." msgstr "[000000,999999]." -#: ../../library/time.rst:453 +#: ../../library/time.rst:466 msgid "\\(1)" msgstr "\\(1)" -#: ../../library/time.rst:457 +#: ../../library/time.rst:470 msgid "``%H``" msgstr "``%H``" -#: ../../library/time.rst:457 +#: ../../library/time.rst:470 msgid "Hour (24-hour clock) as a decimal number [00,23]." msgstr "Hora (relógio 24 horas) como um número decimal [00,23]." -#: ../../library/time.rst:460 +#: ../../library/time.rst:473 msgid "``%I``" msgstr "``%I``" -#: ../../library/time.rst:460 +#: ../../library/time.rst:473 msgid "Hour (12-hour clock) as a decimal number [01,12]." msgstr "Hora (relógio 12 horas) como um número decimal [01,12]." -#: ../../library/time.rst:463 +#: ../../library/time.rst:476 msgid "``%j``" msgstr "``%j``" -#: ../../library/time.rst:463 +#: ../../library/time.rst:476 msgid "Day of the year as a decimal number [001,366]." msgstr "Dia do ano como um número decimal [001,366]." -#: ../../library/time.rst:466 +#: ../../library/time.rst:479 msgid "``%m``" msgstr "``%m``" -#: ../../library/time.rst:466 +#: ../../library/time.rst:479 msgid "Month as a decimal number [01,12]." msgstr "Mês como um número decimal [01,12]." -#: ../../library/time.rst:469 +#: ../../library/time.rst:482 msgid "``%M``" msgstr "``%M``" -#: ../../library/time.rst:469 +#: ../../library/time.rst:482 msgid "Minute as a decimal number [00,59]." msgstr "Minuto como um número decimal [00,59]." -#: ../../library/time.rst:472 +#: ../../library/time.rst:485 msgid "``%p``" msgstr "``%p``" -#: ../../library/time.rst:472 +#: ../../library/time.rst:485 msgid "Locale's equivalent of either AM or PM." msgstr "Equivalente da localidade a AM ou PM." -#: ../../library/time.rst:472 +#: ../../library/time.rst:485 msgid "\\(2)" msgstr "\\(2)" -#: ../../library/time.rst:475 +#: ../../library/time.rst:488 msgid "``%S``" msgstr "``%S``" -#: ../../library/time.rst:475 +#: ../../library/time.rst:488 msgid "Second as a decimal number [00,61]." msgstr "Segundo como um número decimal [00,61]." -#: ../../library/time.rst:475 +#: ../../library/time.rst:488 msgid "\\(3)" msgstr "\\(3)" -#: ../../library/time.rst:478 +#: ../../library/time.rst:491 msgid "``%U``" msgstr "``%U``" -#: ../../library/time.rst:478 +#: ../../library/time.rst:491 msgid "" "Week number of the year (Sunday as the first day of the week) as a decimal " "number [00,53]. All days in a new year preceding the first Sunday are " @@ -932,23 +946,32 @@ msgstr "" "decimal [00,53]. Todos os dias em um ano novo que precedem o primeiro " "domingo são considerados como estando na semana 0." -#: ../../library/time.rst:478 ../../library/time.rst:489 +#: ../../library/time.rst:491 ../../library/time.rst:505 msgid "\\(4)" msgstr "\\(4)" -#: ../../library/time.rst:486 +#: ../../library/time.rst:499 +msgid "``%u``" +msgstr "``%u``" + +#: ../../library/time.rst:499 +msgid "Day of the week (Monday is 1; Sunday is 7) as a decimal number [1, 7]." +msgstr "" +"Dia da semana (segunda-feira é 1; domingo é 7) como um número decimal [1, 7]." + +#: ../../library/time.rst:502 msgid "``%w``" msgstr "``%w``" -#: ../../library/time.rst:486 +#: ../../library/time.rst:502 msgid "Weekday as a decimal number [0(Sunday),6]." msgstr "Dia da semana como um número decimal [0(Domingo),6]" -#: ../../library/time.rst:489 +#: ../../library/time.rst:505 msgid "``%W``" msgstr "``%W``" -#: ../../library/time.rst:489 +#: ../../library/time.rst:505 msgid "" "Week number of the year (Monday as the first day of the week) as a decimal " "number [00,53]. All days in a new year preceding the first Monday are " @@ -958,43 +981,43 @@ msgstr "" "um número decimal [00,53]. Todos os dias do ano que precedem o primeiro " "domingo serão considerados como estando na semana 0." -#: ../../library/time.rst:497 +#: ../../library/time.rst:513 msgid "``%x``" msgstr "``%x``" -#: ../../library/time.rst:497 +#: ../../library/time.rst:513 msgid "Locale's appropriate date representation." msgstr "Representação de data apropriada de localidade." -#: ../../library/time.rst:500 +#: ../../library/time.rst:516 msgid "``%X``" msgstr "``%X``" -#: ../../library/time.rst:500 +#: ../../library/time.rst:516 msgid "Locale's appropriate time representation." msgstr "Representação de hora apropriada da localidade." -#: ../../library/time.rst:503 +#: ../../library/time.rst:519 msgid "``%y``" msgstr "``%y``" -#: ../../library/time.rst:503 +#: ../../library/time.rst:519 msgid "Year without century as a decimal number [00,99]." msgstr "Ano sem século como um número decimal [00,99]." -#: ../../library/time.rst:506 +#: ../../library/time.rst:522 msgid "``%Y``" msgstr "``%Y``" -#: ../../library/time.rst:506 +#: ../../library/time.rst:522 msgid "Year with century as a decimal number." msgstr "Ano com século como um número decimal." -#: ../../library/time.rst:509 +#: ../../library/time.rst:525 msgid "``%z``" msgstr "``%z``" -#: ../../library/time.rst:509 +#: ../../library/time.rst:525 msgid "" "Time zone offset indicating a positive or negative time difference from UTC/" "GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M " @@ -1005,29 +1028,57 @@ msgstr "" "dígitos decimais de hora e M representa os dígitos decimais de minuto " "[-23:59, +23:59]. [1]_" -#: ../../library/time.rst:515 +#: ../../library/time.rst:531 msgid "``%Z``" msgstr "``%Z``" -#: ../../library/time.rst:515 +#: ../../library/time.rst:531 msgid "Time zone name (no characters if no time zone exists). Deprecated. [1]_" msgstr "" "Nome do fuso horário (nenhum caractere se nenhum fuso horário existe). " "Descontinuado. [1]_" -#: ../../library/time.rst:518 +#: ../../library/time.rst:534 +msgid "``%G``" +msgstr "``%G``" + +#: ../../library/time.rst:534 +msgid "" +"ISO 8601 year (similar to ``%Y`` but follows the rules for the ISO 8601 " +"calendar year). The year starts with the week that contains the first " +"Thursday of the calendar year." +msgstr "" +"Ano ISO 8601 (semelhante a ``%Y``, mas segue as regras para o ano calendário " +"ISO 8601). O ano começa com a semana que contém a primeira quinta-feira do " +"ano calendário." + +#: ../../library/time.rst:539 +msgid "``%V``" +msgstr "``%V``" + +#: ../../library/time.rst:539 +msgid "" +"ISO 8601 week number (as a decimal number [01,53]). The first week of the " +"year is the one that contains the first Thursday of the year. Weeks start on " +"Monday." +msgstr "" +"Número da semana ISO 8601 (como um número decimal [01,53]). A primeira " +"semana do ano é aquela que contém a primeira quinta-feira do ano. As semanas " +"começam na segunda-feira." + +#: ../../library/time.rst:544 msgid "``%%``" msgstr "``%%``" -#: ../../library/time.rst:518 +#: ../../library/time.rst:544 msgid "A literal ``'%'`` character." msgstr "Um caractere literal ``'%'``." -#: ../../library/time.rst:521 +#: ../../library/time.rst:547 msgid "Notes:" msgstr "Notas:" -#: ../../library/time.rst:524 +#: ../../library/time.rst:550 msgid "" "The ``%f`` format directive only applies to :func:`strptime`, not to :func:" "`strftime`. However, see also :meth:`datetime.datetime.strptime` and :meth:" @@ -1039,7 +1090,7 @@ msgstr "" "strptime` e :meth:`datetime.datetime.strftime` onde a diretiva de formatação " "``%f`` :ref:`é aplicada para microssegundos `." -#: ../../library/time.rst:530 +#: ../../library/time.rst:556 msgid "" "When used with the :func:`strptime` function, the ``%p`` directive only " "affects the output hour field if the ``%I`` directive is used to parse the " @@ -1048,7 +1099,7 @@ msgstr "" "Quando utilizado com a função :func:`strptime`, a diretiva ``%p`` apenas " "afeta a saída do campo se a diretiva ``%I`` é utilizada para analisar a hora." -#: ../../library/time.rst:536 +#: ../../library/time.rst:562 msgid "" "The range really is ``0`` to ``61``; value ``60`` is valid in timestamps " "representing `leap seconds`_ and value ``61`` is supported for historical " @@ -1058,7 +1109,7 @@ msgstr "" "registros de data e hora representando `segundos bissextos`_ e o valor " "``61`` é suportado por razões históricas." -#: ../../library/time.rst:541 +#: ../../library/time.rst:567 msgid "" "When used with the :func:`strptime` function, ``%U`` and ``%W`` are only " "used in calculations when the day of the week and the year are specified." @@ -1066,7 +1117,7 @@ msgstr "" "Quando utilizado co a função :func:`strptime`, ``%U`` e ``%W`` são " "utilizados em cálculos apenas quando o dia da semana e ano são especificados." -#: ../../library/time.rst:544 +#: ../../library/time.rst:570 msgid "" "Here is an example, a format for dates compatible with that specified in " "the :rfc:`2822` Internet email standard. [1]_ ::" @@ -1074,7 +1125,17 @@ msgstr "" "Veja este exemplo, um formato para datas compatível com as especificações " "dos padrões de e-mail :rfc:`2822`. [1]_ ::" -#: ../../library/time.rst:551 +#: ../../library/time.rst:573 +msgid "" +">>> from time import gmtime, strftime\n" +">>> strftime(\"%a, %d %b %Y %H:%M:%S +0000\", gmtime())\n" +"'Thu, 28 Jun 2001 14:17:15 +0000'" +msgstr "" +">>> from time import gmtime, strftime\n" +">>> strftime(\"%a, %d %b %Y %H:%M:%S +0000\", gmtime())\n" +"'Thu, 28 Jun 2001 14:17:15 +0000'" + +#: ../../library/time.rst:577 msgid "" "Additional directives may be supported on certain platforms, but only the " "ones listed here have a meaning standardized by ANSI C. To see the full set " @@ -1086,7 +1147,7 @@ msgstr "" "a lista completa de códigos de formato suportados na sua plataforma, " "consulte a documentação :manpage:`strftime(3)`." -#: ../../library/time.rst:556 +#: ../../library/time.rst:582 msgid "" "On some platforms, an optional field width and precision specification can " "immediately follow the initial ``'%'`` of a directive in the following " @@ -1098,7 +1159,7 @@ msgstr "" "seguinte ordem; isto também não é portátil. O campo comprimento normalmente " "é 2 exceto para ``%j`` quando é 3." -#: ../../library/time.rst:567 +#: ../../library/time.rst:593 msgid "" "Parse a string representing a time according to a format. The return value " "is a :class:`struct_time` as returned by :func:`gmtime` or :func:`localtime`." @@ -1107,7 +1168,7 @@ msgstr "" "retornado é um :class:`struct_time` como retornado por :func:`gmtime` ou :" "func:`localtime`." -#: ../../library/time.rst:571 +#: ../../library/time.rst:597 msgid "" "The *format* parameter uses the same directives as those used by :func:" "`strftime`; it defaults to ``\"%a %b %d %H:%M:%S %Y\"`` which matches the " @@ -1126,11 +1187,11 @@ msgstr "" "puderem ser inferidos são ``(1900, 1, 1, 0, 0, 0, 0, 1, -1)``. Ambos " "*string* e *format* devem ser strings." -#: ../../library/time.rst:579 +#: ../../library/time.rst:605 msgid "For example:" msgstr "Por exemplo:" -#: ../../library/time.rst:586 +#: ../../library/time.rst:612 msgid "" "Support for the ``%Z`` directive is based on the values contained in " "``tzname`` and whether ``daylight`` is true. Because of this, it is " @@ -1142,7 +1203,7 @@ msgstr "" "exceto por reconhecer UTC e GMT, que são sempre conhecidos (e considerados " "fuso horários sem horários de verão)." -#: ../../library/time.rst:591 +#: ../../library/time.rst:617 msgid "" "Only the directives specified in the documentation are supported. Because " "``strftime()`` is implemented per platform it can sometimes offer more " @@ -1156,7 +1217,7 @@ msgstr "" "independente de quaisquer plataformas e portanto não necessariamente suporta " "todas as diretivas disponíveis que não estão documentadas como suportadas." -#: ../../library/time.rst:600 +#: ../../library/time.rst:626 msgid "" "The type of the time value sequence returned by :func:`gmtime`, :func:" "`localtime`, and :func:`strptime`. It is an object with a :term:`named " @@ -1168,104 +1229,104 @@ msgstr "" "tuple`: os valores podem ser acessados por um índice e por um nome de " "atributo. Os seguintes valores estão presentes:" -#: ../../library/time.rst:607 +#: ../../library/time.rst:633 msgid "Index" msgstr "Índice" -#: ../../library/time.rst:608 +#: ../../library/time.rst:634 msgid "Attribute" msgstr "Atributo" -#: ../../library/time.rst:609 +#: ../../library/time.rst:635 msgid "Values" msgstr "Valores" -#: ../../library/time.rst:611 +#: ../../library/time.rst:637 msgid "0" msgstr "0" -#: ../../library/time.rst:613 +#: ../../library/time.rst:639 msgid "(for example, 1993)" msgstr "(por exemplo, 1993)" -#: ../../library/time.rst:615 +#: ../../library/time.rst:641 msgid "1" msgstr "1" -#: ../../library/time.rst:617 +#: ../../library/time.rst:643 msgid "range [1, 12]" msgstr "intervalo [1,12]" -#: ../../library/time.rst:619 +#: ../../library/time.rst:645 msgid "2" msgstr "2" -#: ../../library/time.rst:621 +#: ../../library/time.rst:647 msgid "range [1, 31]" msgstr "intervalo [1,31]" -#: ../../library/time.rst:623 +#: ../../library/time.rst:649 msgid "3" msgstr "3" -#: ../../library/time.rst:625 +#: ../../library/time.rst:651 msgid "range [0, 23]" msgstr "intervalo [0,23]" -#: ../../library/time.rst:627 +#: ../../library/time.rst:653 msgid "4" msgstr "4" -#: ../../library/time.rst:629 +#: ../../library/time.rst:655 msgid "range [0, 59]" msgstr "intervalo [0,59]" -#: ../../library/time.rst:631 +#: ../../library/time.rst:657 msgid "5" msgstr "5" -#: ../../library/time.rst:633 +#: ../../library/time.rst:659 msgid "range [0, 61]; see :ref:`Note (2) ` in :func:`strftime`" msgstr "" "intervalo [0, 61]; veja :ref:`Nota (2) ` em :func:`strftime`" -#: ../../library/time.rst:635 +#: ../../library/time.rst:661 msgid "6" msgstr "6" -#: ../../library/time.rst:637 +#: ../../library/time.rst:663 msgid "range [0, 6]; Monday is 0" msgstr "intervalo [0, 6]; segunda-feira é 0" -#: ../../library/time.rst:639 +#: ../../library/time.rst:665 msgid "7" msgstr "7" -#: ../../library/time.rst:641 +#: ../../library/time.rst:667 msgid "range [1, 366]" msgstr "intervalo [1, 366]" -#: ../../library/time.rst:643 +#: ../../library/time.rst:669 msgid "8" msgstr "8" -#: ../../library/time.rst:645 +#: ../../library/time.rst:671 msgid "0, 1 or -1; see below" msgstr "0, 1 ou -1; veja abaixo" -#: ../../library/time.rst:647 ../../library/time.rst:651 +#: ../../library/time.rst:673 ../../library/time.rst:677 msgid "N/A" msgstr "N/D" -#: ../../library/time.rst:649 +#: ../../library/time.rst:675 msgid "abbreviation of timezone name" msgstr "abreviação do nome do fuso horário" -#: ../../library/time.rst:653 +#: ../../library/time.rst:679 msgid "offset east of UTC in seconds" msgstr "deslocamento a leste de UTC em segundos" -#: ../../library/time.rst:655 +#: ../../library/time.rst:681 msgid "" "Note that unlike the C structure, the month value is a range of [1, 12], not " "[0, 11]." @@ -1273,7 +1334,7 @@ msgstr "" "Note que diferentemente da estrutura C, o valor do mês é um intervalo [1,12] " "e não [0,11]." -#: ../../library/time.rst:658 +#: ../../library/time.rst:684 msgid "" "In calls to :func:`mktime`, :attr:`tm_isdst` may be set to 1 when daylight " "savings time is in effect, and 0 when it is not. A value of -1 indicates " @@ -1285,7 +1346,7 @@ msgstr "" "indica que esta informação não é conhecida, e geralmente resultará no " "preenchimento do estado correto." -#: ../../library/time.rst:662 +#: ../../library/time.rst:688 msgid "" "When a tuple with an incorrect length is passed to a function expecting a :" "class:`struct_time`, or having elements of the wrong type, a :exc:" @@ -1295,7 +1356,7 @@ msgstr "" "espera por um :class:`struct_time`, ou por possuir elementos do tipo errado, " "um :exc:`TypeError` é levantado." -#: ../../library/time.rst:668 +#: ../../library/time.rst:694 msgid "" "Return the time in seconds since the epoch_ as a floating-point number. The " "handling of `leap seconds`_ is platform dependent. On Windows and most Unix " @@ -1303,13 +1364,13 @@ msgid "" "the epoch_. This is commonly referred to as `Unix time `_." msgstr "" -"Retorna o tempo em segundos desde a era_ como um número em ponto flutuante. " -"A manipulação de `segundos bissextos`_ é dependente da plataforma. No " -"Windows e na maioria dos sistemas Unix, o segundo bissexto não é contado " -"para o tempo desde a era_. Isso é comumente referido como `era Unix `_. " +"Retorna o tempo em segundos desde o epoch_ como um número em ponto " +"flutuante. A manipulação de `segundos bissextos`_ é dependente da " +"plataforma. No Windows e na maioria dos sistemas Unix, o segundo bissexto " +"não é contado para o tempo desde o epoch_. Isso é comumente referido como " +"`epoch ou era Unix `_." -#: ../../library/time.rst:674 +#: ../../library/time.rst:700 msgid "" "Note that even though the time is always returned as a floating-point " "number, not all systems provide time with a better precision than 1 second. " @@ -1323,7 +1384,7 @@ msgstr "" "pode retornar valores menores do que os de uma chamada anterior se o relógio " "do sistema foi redefinido entre duas chamadas." -#: ../../library/time.rst:680 +#: ../../library/time.rst:706 msgid "" "The number returned by :func:`.time` may be converted into a more common " "time format (i.e. year, month, day, hour, etc...) in UTC by passing it to :" @@ -1339,19 +1400,19 @@ msgstr "" "por onde os componentes de data do calendário podem ser acessados ou " "atribuídos." -#: ../../library/time.rst:689 +#: ../../library/time.rst:715 msgid "On Windows, call ``GetSystemTimeAsFileTime()``." msgstr "No Windows, chama ``GetSystemTimeAsFileTime()``." -#: ../../library/time.rst:690 +#: ../../library/time.rst:716 msgid "Call ``clock_gettime(CLOCK_REALTIME)`` if available." msgstr "Chama ``clock_gettime(CLOCK_REALTIME)`` se disponível." -#: ../../library/time.rst:691 +#: ../../library/time.rst:717 msgid "Otherwise, call ``gettimeofday()``." msgstr "Caso contrário, chama ``gettimeofday()``." -#: ../../library/time.rst:693 +#: ../../library/time.rst:719 msgid "" "Use :func:`time_ns` to avoid the precision loss caused by the :class:`float` " "type." @@ -1359,15 +1420,15 @@ msgstr "" "Use :func:`time_ns` para evitar perda de precisão causada pelo tipo :class:" "`float`." -#: ../../library/time.rst:699 +#: ../../library/time.rst:725 msgid "" "Similar to :func:`~time.time` but returns time as an integer number of " "nanoseconds since the epoch_." msgstr "" "Semelhante à :func:`~time.time`, mas retorna o tempo como um número inteiro " -"de nanossegundos desde a era_." +"de nanossegundos desde o epoch_." -#: ../../library/time.rst:712 +#: ../../library/time.rst:738 msgid "" "Return the value (in fractional seconds) of the sum of the system and user " "CPU time of the current thread. It does not include time elapsed during " @@ -1381,7 +1442,7 @@ msgstr "" "retornado é indefinido, então apenas a diferença dos resultados de duas " "chamadas é válida." -#: ../../library/time.rst:718 +#: ../../library/time.rst:744 msgid "" "Use :func:`thread_time_ns` to avoid the precision loss caused by the :class:" "`float` type." @@ -1389,20 +1450,16 @@ msgstr "" "Use :func:`thread_time_ns` para evitar perda de precisão causada pelo tipo :" "class:`float`." -#: ../../library/time.rst:721 -msgid ":ref:`Availability `: Linux, Unix, Windows." -msgstr ":ref:`Disponibilidade `: Linux, Unix, Windows." - -#: ../../library/time.rst:723 +#: ../../library/time.rst:749 msgid "Unix systems supporting ``CLOCK_THREAD_CPUTIME_ID``." msgstr "Sistemas Unix possuem suporte para ``CLOCK_THREAD_CPUTIME_ID``." -#: ../../library/time.rst:730 +#: ../../library/time.rst:756 msgid "Similar to :func:`thread_time` but return time as nanoseconds." msgstr "" "Semelhante à :func:`thread_time`, mas retorna o tempo em nanossegundos." -#: ../../library/time.rst:737 +#: ../../library/time.rst:763 msgid "" "Reset the time conversion rules used by the library routines. The " "environment variable :envvar:`TZ` specifies how this is done. It will also " @@ -1421,7 +1478,7 @@ msgstr "" "de zero se há um tempo, no presente, passado ou futuro quando o horário de " "verão se aplica)." -#: ../../library/time.rst:749 +#: ../../library/time.rst:775 msgid "" "Although in many cases, changing the :envvar:`TZ` environment variable may " "affect the output of functions like :func:`localtime` without calling :func:" @@ -1431,11 +1488,11 @@ msgstr "" "afetar a saída de funções como :func:`localtime` sem chamar :func:`tzset`, " "este comportamento não deve ser confiado." -#: ../../library/time.rst:753 +#: ../../library/time.rst:779 msgid "The :envvar:`TZ` environment variable should contain no whitespace." msgstr "A variável de sistema :envvar:`TZ` não deve conter espaços em branco." -#: ../../library/time.rst:755 +#: ../../library/time.rst:781 msgid "" "The standard format of the :envvar:`TZ` environment variable is (whitespace " "added for clarity)::" @@ -1443,15 +1500,19 @@ msgstr "" "O formato padrão da variável de sistema :envvar:`TZ` é (espaços foram " "adicionados por motivos de clareza):" -#: ../../library/time.rst:760 +#: ../../library/time.rst:784 +msgid "std offset [dst [offset [,start[/time], end[/time]]]]" +msgstr "std offset [dst [offset [,start[/time], end[/time]]]]" + +#: ../../library/time.rst:786 msgid "Where the components are:" msgstr "Onde os componentes são:" -#: ../../library/time.rst:762 +#: ../../library/time.rst:788 msgid "``std`` and ``dst``" msgstr "``std`` e ``dst``" -#: ../../library/time.rst:763 +#: ../../library/time.rst:789 msgid "" "Three or more alphanumerics giving the timezone abbreviations. These will be " "propagated into time.tzname" @@ -1459,11 +1520,11 @@ msgstr "" "Três ou mais alfanuméricos fornecendo a abreviação do fuso horário. Estes " "serão propagados para time.tzname" -#: ../../library/time.rst:766 +#: ../../library/time.rst:792 msgid "``offset``" msgstr "``offset``" -#: ../../library/time.rst:767 +#: ../../library/time.rst:793 msgid "" "The offset has the form: ``± hh[:mm[:ss]]``. This indicates the value added " "the local time to arrive at UTC. If preceded by a '-', the timezone is east " @@ -1476,11 +1537,11 @@ msgstr "" "oeste. Se nenhum deslocamento segue o horário de verão, o tempo no verão é " "presumido como estando uma hora a frente do horário padrão." -#: ../../library/time.rst:772 +#: ../../library/time.rst:798 msgid "``start[/time], end[/time]``" msgstr "``start[/time], end[/time]``" -#: ../../library/time.rst:773 +#: ../../library/time.rst:799 msgid "" "Indicates when to change to and back from DST. The format of the start and " "end dates are one of the following:" @@ -1488,11 +1549,11 @@ msgstr "" "Indica quando mudar e voltar do Horário de Verão. O formato das datas de " "início e fim é um dos seguintes:" -#: ../../library/time.rst:776 +#: ../../library/time.rst:802 msgid ":samp:`J{n}`" msgstr ":samp:`J{n}`" -#: ../../library/time.rst:777 +#: ../../library/time.rst:803 msgid "" "The Julian day *n* (1 <= *n* <= 365). Leap days are not counted, so in all " "years February 28 is day 59 and March 1 is day 60." @@ -1500,11 +1561,11 @@ msgstr "" "I dia juliano *n* (1 <= *n* <= 365). Os dias bissextos não são contados, " "então, em todos os anos, 28 de fevereiro é o dia 59 e 1 de março é o dia 60." -#: ../../library/time.rst:780 +#: ../../library/time.rst:806 msgid ":samp:`{n}`" msgstr ":samp:`{n}`" -#: ../../library/time.rst:781 +#: ../../library/time.rst:807 msgid "" "The zero-based Julian day (0 <= *n* <= 365). Leap days are counted, and it " "is possible to refer to February 29." @@ -1512,11 +1573,11 @@ msgstr "" "O dia juliano baseado em zero (0 <= *n* <= 365). Dias bissextos são " "contados, e é possível fazer referência a 29 de fevereiro." -#: ../../library/time.rst:784 +#: ../../library/time.rst:810 msgid ":samp:`M{m}.{n}.{d}`" msgstr ":samp:`M{m}.{n}.{d}`" -#: ../../library/time.rst:785 +#: ../../library/time.rst:811 msgid "" "The *d*'th day (0 <= *d* <= 6) of week *n* of month *m* of the year (1 <= " "*n* <= 5, 1 <= *m* <= 12, where week 5 means \"the last *d* day in month " @@ -1528,7 +1589,7 @@ msgstr "" "que pode ocorrer tanto na quarta como quinta semana). Semana 1 é a primeira " "semana na qual o *d*-ésimo dia ocorre. Dia zero é o domingo." -#: ../../library/time.rst:791 +#: ../../library/time.rst:817 msgid "" "``time`` has the same format as ``offset`` except that no leading sign ('-' " "or '+') is allowed. The default, if time is not given, is 02:00:00." @@ -1536,7 +1597,27 @@ msgstr "" "``time`` tem o mesmo formato que ``offset``, exceto que nenhum sinal no " "início é permitido ('-' ou '+'). O padrão, se o tempo não é dado, é 02:00:00." -#: ../../library/time.rst:805 +#: ../../library/time.rst:822 +msgid "" +">>> os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'\n" +">>> time.tzset()\n" +">>> time.strftime('%X %x %Z')\n" +"'02:07:36 05/08/03 EDT'\n" +">>> os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'\n" +">>> time.tzset()\n" +">>> time.strftime('%X %x %Z')\n" +"'16:08:12 05/08/03 AEST'" +msgstr "" +">>> os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'\n" +">>> time.tzset()\n" +">>> time.strftime('%X %x %Z')\n" +"'02:07:36 05/08/03 EDT'\n" +">>> os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'\n" +">>> time.tzset()\n" +">>> time.strftime('%X %x %Z')\n" +"'16:08:12 05/08/03 AEST'" + +#: ../../library/time.rst:831 msgid "" "On many Unix systems (including \\*BSD, Linux, Solaris, and Darwin), it is " "more convenient to use the system's zoneinfo (:manpage:`tzfile(5)`) " @@ -1555,11 +1636,31 @@ msgstr "" "zoneinfo`. Por exemplo, ``'US/Eastern'``, ``'Australia/Melbourne'``, " "``'Egypt'`` ou ``'Europe/Amsterdam'``. ::" -#: ../../library/time.rst:826 +#: ../../library/time.rst:839 +msgid "" +">>> os.environ['TZ'] = 'US/Eastern'\n" +">>> time.tzset()\n" +">>> time.tzname\n" +"('EST', 'EDT')\n" +">>> os.environ['TZ'] = 'Egypt'\n" +">>> time.tzset()\n" +">>> time.tzname\n" +"('EET', 'EEST')" +msgstr "" +">>> os.environ['TZ'] = 'US/Eastern'\n" +">>> time.tzset()\n" +">>> time.tzname\n" +"('EST', 'EDT')\n" +">>> os.environ['TZ'] = 'Egypt'\n" +">>> time.tzset()\n" +">>> time.tzname\n" +"('EET', 'EEST')" + +#: ../../library/time.rst:852 msgid "Clock ID Constants" msgstr "Constantes de ID de Relógio" -#: ../../library/time.rst:828 +#: ../../library/time.rst:854 msgid "" "These constants are used as parameters for :func:`clock_getres` and :func:" "`clock_gettime`." @@ -1567,7 +1668,7 @@ msgstr "" "Essas constantes são utilizadas como parâmetros para :func:`clock_getres` e :" "func:`clock_gettime`." -#: ../../library/time.rst:833 +#: ../../library/time.rst:859 msgid "" "Identical to :data:`CLOCK_MONOTONIC`, except it also includes any time that " "the system is suspended." @@ -1575,7 +1676,7 @@ msgstr "" "Idêntica a :data:`CLOCK_MONOTONIC`, exceto por também incluir qualquer tempo " "que o sistema está suspenso." -#: ../../library/time.rst:836 +#: ../../library/time.rst:862 msgid "" "This allows applications to get a suspend-aware monotonic clock without " "having to deal with the complications of :data:`CLOCK_REALTIME`, which may " @@ -1587,11 +1688,7 @@ msgstr "" "que pode conter descontinuidades se o tempo é alterado utilizando " "``settimeofday()`` ou algo semelhante." -#: ../../library/time.rst:841 -msgid ":ref:`Availability `: Linux >= 2.6.39." -msgstr ":ref:`Disponibilidade `: Linux >= 2.6.39." - -#: ../../library/time.rst:848 +#: ../../library/time.rst:874 msgid "" "The Solaris OS has a ``CLOCK_HIGHRES`` timer that attempts to use an optimal " "hardware source, and may give close to nanosecond resolution. " @@ -1601,11 +1698,7 @@ msgstr "" "otimizados do hardware, e pode fornecer resolução perto de nanossegundos. " "``CLOCK_HIGHRES`` é o relógio nanoajustável de alta resolução." -#: ../../library/time.rst:852 -msgid ":ref:`Availability `: Solaris." -msgstr ":ref:`Disponibilidade `: Solaris." - -#: ../../library/time.rst:859 +#: ../../library/time.rst:885 msgid "" "Clock that cannot be set and represents monotonic time since some " "unspecified starting point." @@ -1613,7 +1706,7 @@ msgstr "" "Relógio que não pode ser definido e representa um tempo monotônico desde um " "ponto de início não especificado." -#: ../../library/time.rst:869 +#: ../../library/time.rst:895 msgid "" "Similar to :data:`CLOCK_MONOTONIC`, but provides access to a raw hardware-" "based time that is not subject to NTP adjustments." @@ -1621,12 +1714,7 @@ msgstr "" "Semelhante à :data:`CLOCK_MONOTONIC`, mas fornece acesso a um tempo bruto " "baseado em hardware que não está sujeito a ajustes NTP." -#: ../../library/time.rst:872 -msgid ":ref:`Availability `: Linux >= 2.6.28, macOS >= 10.12." -msgstr "" -":ref:`Disponibilidade `: Linux >= 2.6.28, macOS >= 10.12." - -#: ../../library/time.rst:878 +#: ../../library/time.rst:904 msgid "" "Similar to :data:`CLOCK_MONOTONIC_RAW`, but reads a value cached by the " "system at context switch and hence has less accuracy." @@ -1634,20 +1722,11 @@ msgstr "" "Semelhante a :data:`CLOCK_MONOTONIC_RAW`, mas lê um armazenado pelo sistema " "no gerenciador de contexto e, portanto, tem menor precisão." -#: ../../library/time.rst:881 ../../library/time.rst:940 -#: ../../library/time.rst:949 -msgid ":ref:`Availability `: macOS >= 10.12." -msgstr ":ref:`Disponibilidade `: macOS >= 10.12." - -#: ../../library/time.rst:888 ../../library/time.rst:897 +#: ../../library/time.rst:914 ../../library/time.rst:923 msgid "High-resolution per-process timer from the CPU." msgstr "Timer de alta resolução por processo no CPU." -#: ../../library/time.rst:899 -msgid ":ref:`Availability `: FreeBSD, NetBSD >= 7, OpenBSD." -msgstr ":ref:`Disponibilidade `: FreeBSD, NetBSD >= 7, OpenBSD." - -#: ../../library/time.rst:905 +#: ../../library/time.rst:931 msgid "" "`International Atomic Time `_" @@ -1655,7 +1734,7 @@ msgstr "" "`Tempo Atômico Internacional `_" -#: ../../library/time.rst:907 +#: ../../library/time.rst:933 msgid "" "The system must have a current leap second table in order for this to give " "the correct answer. PTP or NTP software can maintain a leap second table." @@ -1664,15 +1743,11 @@ msgstr "" "a resposta correta. Softwares PTP ou NTP podem manter uma tabela de segundos " "bissextos." -#: ../../library/time.rst:910 -msgid ":ref:`Availability `: Linux." -msgstr ":ref:`Disponibilidade `: Linux." - -#: ../../library/time.rst:916 +#: ../../library/time.rst:942 msgid "Thread-specific CPU-time clock." msgstr "Relógio de tempo de CPU específico a thread." -#: ../../library/time.rst:925 +#: ../../library/time.rst:951 msgid "" "Time whose absolute value is the time the system has been running and not " "suspended, providing accurate uptime measurement, both absolute and interval." @@ -1681,11 +1756,7 @@ msgstr "" "suspenso, fornecendo medidas de tempo de atividade precisas, tanto em valor " "absoluto quanto intervalo." -#: ../../library/time.rst:929 -msgid ":ref:`Availability `: FreeBSD, OpenBSD >= 5.5." -msgstr ":ref:`Disponibilidade `: FreeBSD, OpenBSD >= 5.5." - -#: ../../library/time.rst:936 +#: ../../library/time.rst:962 msgid "" "Clock that increments monotonically, tracking the time since an arbitrary " "point, unaffected by frequency or time adjustments and not incremented while " @@ -1695,7 +1766,7 @@ msgstr "" "arbitrário, não afetado pela frequência ou ajustes de tempo e não " "incrementado enquanto o sistema está dormindo." -#: ../../library/time.rst:946 +#: ../../library/time.rst:972 msgid "" "Like :data:`CLOCK_UPTIME_RAW`, but the value is cached by the system at " "context switches and therefore has less accuracy." @@ -1703,7 +1774,7 @@ msgstr "" "Semelhante a :data:`CLOCK_UPTIME_RAW`, mas o valor é armazenado pelo sistema " "no gerenciador de contexto e, portanto, tem menor precisão." -#: ../../library/time.rst:953 +#: ../../library/time.rst:979 msgid "" "The following constant is the only parameter that can be sent to :func:" "`clock_settime`." @@ -1711,7 +1782,7 @@ msgstr "" "A constante a seguir é o único parâmetro que pode ser enviado para :func:" "`clock_settime`." -#: ../../library/time.rst:959 +#: ../../library/time.rst:985 msgid "" "System-wide real-time clock. Setting this clock requires appropriate " "privileges." @@ -1719,11 +1790,11 @@ msgstr "" "Relógio em tempo real de todo o sistema. Definições deste relógio requerem " "privilégios apropriados." -#: ../../library/time.rst:970 +#: ../../library/time.rst:996 msgid "Timezone Constants" msgstr "Constantes de Fuso Horário" -#: ../../library/time.rst:974 +#: ../../library/time.rst:1000 msgid "" "The offset of the local DST timezone, in seconds west of UTC, if one is " "defined. This is negative if the local DST timezone is east of UTC (as in " @@ -1735,11 +1806,11 @@ msgstr "" "UTC (como na Europa Ocidental, incluindo o Reino Unido). Somente utilize se " "``daylight`` for diferente de zero. Veja a nota abaixo." -#: ../../library/time.rst:980 +#: ../../library/time.rst:1006 msgid "Nonzero if a DST timezone is defined. See note below." msgstr "Diferente de zero se um fuso horário DST é definido. Veja nota abaixo." -#: ../../library/time.rst:984 +#: ../../library/time.rst:1010 msgid "" "The offset of the local (non-DST) timezone, in seconds west of UTC (negative " "in most of Western Europe, positive in the US, zero in the UK). See note " @@ -1749,7 +1820,7 @@ msgstr "" "UTC (negativo na maior parte da Europa Ocidental, positivo nos Estados " "Unidos e Brasil, zero no Reino Unido). Ver nota abaixo." -#: ../../library/time.rst:989 +#: ../../library/time.rst:1015 msgid "" "A tuple of two strings: the first is the name of the local non-DST timezone, " "the second is the name of the local DST timezone. If no DST timezone is " @@ -1759,7 +1830,7 @@ msgstr "" "a segunda é o nome do fuso horário local DST. Se nenhum fuso horário DST for " "definido, a segunda string é usada. Veja nota abaixo." -#: ../../library/time.rst:995 +#: ../../library/time.rst:1021 msgid "" "For the above Timezone constants (:data:`altzone`, :data:`daylight`, :data:" "`timezone`, and :data:`tzname`), the value is determined by the timezone " @@ -1776,19 +1847,19 @@ msgstr "" "e :attr:`~struct_time.tm_zone` da :func:`localtime` para obter informação de " "fuso horário." -#: ../../library/time.rst:1004 +#: ../../library/time.rst:1030 msgid "Module :mod:`datetime`" msgstr "Módulo :mod:`datetime`" -#: ../../library/time.rst:1005 +#: ../../library/time.rst:1031 msgid "More object-oriented interface to dates and times." msgstr "Mais interfaces orientada a objetos para datas e tempos." -#: ../../library/time.rst:1007 +#: ../../library/time.rst:1033 msgid "Module :mod:`locale`" msgstr "Módulo :mod:`locale`" -#: ../../library/time.rst:1008 +#: ../../library/time.rst:1034 msgid "" "Internationalization services. The locale setting affects the " "interpretation of many format specifiers in :func:`strftime` and :func:" @@ -1798,11 +1869,11 @@ msgstr "" "interpretação de muitos especificadores de formato em :func:`strftime` e :" "func:`strptime`." -#: ../../library/time.rst:1011 +#: ../../library/time.rst:1037 msgid "Module :mod:`calendar`" msgstr "Módulo :mod:`calendar`" -#: ../../library/time.rst:1012 +#: ../../library/time.rst:1038 msgid "" "General calendar-related functions. :func:`~calendar.timegm` is the " "inverse of :func:`gmtime` from this module." @@ -1810,11 +1881,11 @@ msgstr "" "Funções gerais relacionadas a calendários. :func:`~calendar.timegm` é a " "função inversa de :func:`gmtime` deste módulo." -#: ../../library/time.rst:1016 +#: ../../library/time.rst:1042 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../library/time.rst:1017 +#: ../../library/time.rst:1043 msgid "" "The use of ``%Z`` is now deprecated, but the ``%z`` escape that expands to " "the preferred hour/minute offset is not supported by all ANSI C libraries. " @@ -1857,27 +1928,27 @@ msgstr "Tempo Universal Coordenado" msgid "Greenwich Mean Time" msgstr "Tempo Médio de Greenwich" -#: ../../library/time.rst:59 +#: ../../library/time.rst:63 msgid "Daylight Saving Time" msgstr "Horário de verão" -#: ../../library/time.rst:319 ../../library/time.rst:354 -#: ../../library/time.rst:707 +#: ../../library/time.rst:323 ../../library/time.rst:358 +#: ../../library/time.rst:733 msgid "benchmarking" msgstr "benchmarking" -#: ../../library/time.rst:354 ../../library/time.rst:707 +#: ../../library/time.rst:358 ../../library/time.rst:733 msgid "CPU time" msgstr "tempo da CPU" -#: ../../library/time.rst:354 ../../library/time.rst:707 +#: ../../library/time.rst:358 ../../library/time.rst:733 msgid "processor time" msgstr "tempo do processador" -#: ../../library/time.rst:416 ../../library/time.rst:562 +#: ../../library/time.rst:429 ../../library/time.rst:588 msgid "% (percent)" msgstr "% (porcentagem)" -#: ../../library/time.rst:416 ../../library/time.rst:562 +#: ../../library/time.rst:429 ../../library/time.rst:588 msgid "datetime format" msgstr "datetime, formato" diff --git a/library/timeit.po b/library/timeit.po index e880eb47f..530474721 100644 --- a/library/timeit.po +++ b/library/timeit.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Adorilson Bezerra , 2023 -# Leandro Cavalcante Damascena , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:15+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -64,14 +59,41 @@ msgstr "" "O exemplo a seguir mostra como a :ref:`timeit-command-line-interface` pode " "ser usado para comparar três expressões diferentes:" +#: ../../library/timeit.rst:28 +msgid "" +"$ python -m timeit \"'-'.join(str(n) for n in range(100))\"\n" +"10000 loops, best of 5: 30.2 usec per loop\n" +"$ python -m timeit \"'-'.join([str(n) for n in range(100)])\"\n" +"10000 loops, best of 5: 27.5 usec per loop\n" +"$ python -m timeit \"'-'.join(map(str, range(100)))\"\n" +"10000 loops, best of 5: 23.2 usec per loop" +msgstr "" + #: ../../library/timeit.rst:37 msgid "This can be achieved from the :ref:`python-interface` with::" msgstr "Isso pode ser obtido da interface :ref:`python-interface` ::" +#: ../../library/timeit.rst:39 +msgid "" +">>> import timeit\n" +">>> timeit.timeit('\"-\".join(str(n) for n in range(100))', number=10000)\n" +"0.3018611848820001\n" +">>> timeit.timeit('\"-\".join([str(n) for n in range(100)])', number=10000)\n" +"0.2727368790656328\n" +">>> timeit.timeit('\"-\".join(map(str, range(100)))', number=10000)\n" +"0.23702679807320237" +msgstr "" + #: ../../library/timeit.rst:47 msgid "A callable can also be passed from the :ref:`python-interface`::" msgstr "Um chamável também pode ser passado para a :ref:`python-interface`::" +#: ../../library/timeit.rst:49 +msgid "" +">>> timeit.timeit(lambda: \"-\".join(map(str, range(100))), number=10000)\n" +"0.19665591977536678" +msgstr "" + #: ../../library/timeit.rst:52 msgid "" "Note however that :func:`.timeit` will automatically determine the number of " @@ -115,6 +137,11 @@ msgid "" "count and *number* executions. The optional *globals* argument specifies a " "namespace in which to execute the code." msgstr "" +"Cria uma instância :class:`Timer` com a instrução fornecida, o código de " +"*setup* e a função *timer* e para executar o método :meth:`.repeat` com o " +"total de execuções informando em *repeat* e o *número* de execuções " +"fornecidos. O argumento opcional *globals* especifica um espaço de nomes no " +"qual executar o código." #: ../../library/timeit.rst:86 ../../library/timeit.rst:183 msgid "Default value of *repeat* changed from 3 to 5." @@ -149,6 +176,14 @@ msgid "" "will by default be executed within timeit's namespace; this behavior can be " "controlled by passing a namespace to *globals*." msgstr "" +"O construtor recebe uma instrução a ser cronometrada, uma instrução " +"adicional usada para configuração e uma função de timer. Ambas as instruções " +"têm como padrão ``'pass'``; a função de timer é dependente da plataforma " +"(veja a string do documento do módulo). *stmt* e *setup* também podem conter " +"múltiplas instruções separadas por ``;`` ou novas linhas, desde que não " +"contenham literais de string multilinhas. A instrução será, por padrão, " +"executada dentro do espaço de nomes do *timeit*; esse comportamento pode ser " +"controlado passando um espaço de nomes para *globals*." #: ../../library/timeit.rst:111 msgid "" @@ -175,6 +210,11 @@ msgid "" "will then be executed by :meth:`.timeit`. Note that the timing overhead is " "a little larger in this case because of the extra function calls." msgstr "" +"Os parâmetros *stmt* e *setup* também podem receber objetos que podem ser " +"chamados sem argumentos. Isso incorporará chamadas a eles em uma função de " +"timer que será executada por :meth:`.timeit`. Observe que a sobrecarga de " +"temporização é um pouco maior neste caso por causa das chamadas de função " +"extras." #: ../../library/timeit.rst:127 msgid "" @@ -185,6 +225,12 @@ msgid "" "million. The main statement, the setup statement and the timer function to " "be used are passed to the constructor." msgstr "" +"Mede o tempo para a quantidade *number* de execuções da instrução principal. " +"Isso executa a instrução setup uma vez e, em seguida, retorna o tempo " +"necessário para executar a instrução principal várias vezes. O temporizador " +"padrão retorna segundos como um float. O argumento é o número de vezes que o " +"laço passa, com padrão de um milhão. A instrução principal, a instrução de " +"configuração e a função de timer a ser usada são passadas para o construtor." #: ../../library/timeit.rst:136 msgid "" @@ -195,6 +241,16 @@ msgid "" "so, GC can be re-enabled as the first statement in the *setup* string. For " "example::" msgstr "" +"Por padrão, :meth:`.timeit` desativa temporariamente :term:`coleta de lixo` " +"durante a temporização. A vantagem dessa abordagem é que ela torna " +"temporizações independentes mais comparáveis. A desvantagem é que o GC pode " +"ser um componente importante do desempenho da função que está sendo medida. " +"Se for assim, o GC pode ser reativado como a primeira instrução na string " +"*setup*. Por exemplo::" + +#: ../../library/timeit.rst:143 +msgid "timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()" +msgstr "" #: ../../library/timeit.rst:148 msgid "Automatically determine how many times to call :meth:`.timeit`." @@ -208,6 +264,11 @@ msgid "" "numbers from the sequence 1, 2, 5, 10, 20, 50, ... until the time taken is " "at least 0.2 seconds." msgstr "" +"Esta é uma função de conveniência que chama :meth:`.timeit` repetidamente " +"para que o tempo total seja >= 0,2 segundos, retornando o eventual (número " +"de voltas, tempo gasto para esse número de voltas). Ela chama :meth:`." +"timeit` com números crescentes da sequência 1, 2, 5, 10, 20, 50, ... até que " +"o tempo gasto seja de pelo menos 0,2 segundos." #: ../../library/timeit.rst:156 msgid "" @@ -253,6 +314,20 @@ msgstr "Função auxiliar para imprimir um traceback do código cronometrado." msgid "Typical use::" msgstr "Uso típico::" +#: ../../library/timeit.rst:193 +msgid "" +"t = Timer(...) # outside the try/except\n" +"try:\n" +" t.timeit(...) # or t.repeat(...)\n" +"except Exception:\n" +" t.print_exc()" +msgstr "" +"t = Timer(...) # fora do try/except\n" +"try:\n" +" t.timeit(...) # ou t.repeat(...)\n" +"except Exception:\n" +" t.print_exc()" + #: ../../library/timeit.rst:199 msgid "" "The advantage over the standard traceback is that source lines in the " @@ -274,6 +349,11 @@ msgstr "" "Quando chamado como um programa a partir da linha de comando, as seguintes " "opções estão disponíveis::" +#: ../../library/timeit.rst:211 +msgid "" +"python -m timeit [-n N] [-r N] [-u U] [-s S] [-p] [-v] [-h] [statement ...]" +msgstr "" + #: ../../library/timeit.rst:213 msgid "Where the following options are understood:" msgstr "As seguintes opções são permitidas" @@ -370,6 +450,16 @@ msgstr "" "É possível fornecer uma instrução de configuração que é executada apenas uma " "vez no início:" +#: ../../library/timeit.rst:280 +msgid "" +"$ python -m timeit -s \"text = 'sample string'; char = 'g'\" \"char in " +"text\"\n" +"5000000 loops, best of 5: 0.0877 usec per loop\n" +"$ python -m timeit -s \"text = 'sample string'; char = 'g'\" \"text." +"find(char)\"\n" +"1000000 loops, best of 5: 0.342 usec per loop" +msgstr "" + #: ../../library/timeit.rst:287 msgid "" "In the output, there are three fields. The loop count, which tells you how " @@ -387,10 +477,33 @@ msgstr "" "Ou seja, o tempo necessário para a repetição mais rápida dividido pela " "contagem de interações." +#: ../../library/timeit.rst:296 +msgid "" +">>> import timeit\n" +">>> timeit.timeit('char in text', setup='text = \"sample string\"; char = " +"\"g\"')\n" +"0.41440500499993504\n" +">>> timeit.timeit('text.find(char)', setup='text = \"sample string\"; char = " +"\"g\"')\n" +"1.7246671520006203" +msgstr "" + #: ../../library/timeit.rst:302 msgid "The same can be done using the :class:`Timer` class and its methods::" msgstr "O mesmo pode ser feito usando a classe :class:`Timer` e seus métodos::" +#: ../../library/timeit.rst:304 +msgid "" +">>> import timeit\n" +">>> t = timeit.Timer('char in text', setup='text = \"sample string\"; char = " +"\"g\"')\n" +">>> t.timeit()\n" +"0.3955516149999312\n" +">>> t.repeat()\n" +"[0.40183617287970225, 0.37027556854118704, 0.38344867356679524, " +"0.3712595970846668, 0.37866875250654886]" +msgstr "" + #: ../../library/timeit.rst:312 msgid "" "The following examples show how to time expressions that contain multiple " @@ -401,6 +514,51 @@ msgstr "" "linhas. Aqui comparamos o custo de usar :func:`hasattr` vs. :keyword:`try`/:" "keyword:`except` para testar atributos de objetos presentes e ausentes:" +#: ../../library/timeit.rst:316 +msgid "" +"$ python -m timeit \"try:\" \" str.__bool__\" \"except AttributeError:\" " +"\" pass\"\n" +"20000 loops, best of 5: 15.7 usec per loop\n" +"$ python -m timeit \"if hasattr(str, '__bool__'): pass\"\n" +"50000 loops, best of 5: 4.26 usec per loop\n" +"\n" +"$ python -m timeit \"try:\" \" int.__bool__\" \"except AttributeError:\" " +"\" pass\"\n" +"200000 loops, best of 5: 1.43 usec per loop\n" +"$ python -m timeit \"if hasattr(int, '__bool__'): pass\"\n" +"100000 loops, best of 5: 2.23 usec per loop" +msgstr "" + +#: ../../library/timeit.rst:330 +msgid "" +">>> import timeit\n" +">>> # attribute is missing\n" +">>> s = \"\"\"\\\n" +"... try:\n" +"... str.__bool__\n" +"... except AttributeError:\n" +"... pass\n" +"... \"\"\"\n" +">>> timeit.timeit(stmt=s, number=100000)\n" +"0.9138244460009446\n" +">>> s = \"if hasattr(str, '__bool__'): pass\"\n" +">>> timeit.timeit(stmt=s, number=100000)\n" +"0.5829014980008651\n" +">>>\n" +">>> # attribute is present\n" +">>> s = \"\"\"\\\n" +"... try:\n" +"... int.__bool__\n" +"... except AttributeError:\n" +"... pass\n" +"... \"\"\"\n" +">>> timeit.timeit(stmt=s, number=100000)\n" +"0.04215312199994514\n" +">>> s = \"if hasattr(int, '__bool__'): pass\"\n" +">>> timeit.timeit(stmt=s, number=100000)\n" +"0.08588060699912603" +msgstr "" + #: ../../library/timeit.rst:358 msgid "" "To give the :mod:`timeit` module access to functions you define, you can " @@ -409,6 +567,17 @@ msgstr "" "Para dar ao módulo :mod:`timeit` acesso as funções que você definiu, você " "pode passar o parâmetro *setup*, que contém um instrução de importar::" +#: ../../library/timeit.rst:361 +msgid "" +"def test():\n" +" \"\"\"Stupid test function\"\"\"\n" +" L = [i for i in range(100)]\n" +"\n" +"if __name__ == '__main__':\n" +" import timeit\n" +" print(timeit.timeit(\"test()\", setup=\"from __main__ import test\"))" +msgstr "" + #: ../../library/timeit.rst:369 msgid "" "Another option is to pass :func:`globals` to the *globals* parameter, which " @@ -419,6 +588,19 @@ msgstr "" "com que o código seja executado em seu espaço de nomes global. Isso pode ser " "mais conveniente do que especificar individualmente imports::" +#: ../../library/timeit.rst:373 +msgid "" +"def f(x):\n" +" return x**2\n" +"def g(x):\n" +" return x**4\n" +"def h(x):\n" +" return x**8\n" +"\n" +"import timeit\n" +"print(timeit.timeit('[func(42) for func in (f,g,h)]', globals=globals()))" +msgstr "" + #: ../../library/timeit.rst:9 msgid "Benchmarking" msgstr "" diff --git a/library/tk.po b/library/tk.po index 8f19e9fb1..5da8d7e0d 100644 --- a/library/tk.po +++ b/library/tk.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:15+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/tkinter.colorchooser.po b/library/tkinter.colorchooser.po index d33861cb6..6c0c692b9 100644 --- a/library/tkinter.colorchooser.po +++ b/library/tkinter.colorchooser.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:15+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/tkinter.dnd.po b/library/tkinter.dnd.po index 1a22fa3a3..392a1b48f 100644 --- a/library/tkinter.dnd.po +++ b/library/tkinter.dnd.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:15+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/tkinter.font.po b/library/tkinter.font.po index d1308e4dc..c6a97fd3b 100644 --- a/library/tkinter.font.po +++ b/library/tkinter.font.po @@ -1,45 +1,47 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:15+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/tkinter.font.rst:2 msgid ":mod:`!tkinter.font` --- Tkinter font wrapper" -msgstr "" +msgstr ":mod:`!tkinter.font` --- Invólucro de fontes Tkinter" #: ../../library/tkinter.font.rst:8 msgid "**Source code:** :source:`Lib/tkinter/font.py`" -msgstr "" +msgstr "**Código-fonte:** :source:`Lib/tkinter/font.py`" #: ../../library/tkinter.font.rst:12 msgid "" "The :mod:`tkinter.font` module provides the :class:`Font` class for creating " "and using named fonts." msgstr "" +"O módulo :mod:`tkinter.font` apresenta a classe :class:`Font` para criação e " +"utilização de fontes nomeadas." #: ../../library/tkinter.font.rst:15 msgid "The different font weights and slants are:" -msgstr "" +msgstr "Os diferentes pesos e inclinações de fontes são:" #: ../../library/tkinter.font.rst:24 msgid "" @@ -49,6 +51,11 @@ msgid "" "as a single object, rather than specifying a font by its attributes with " "each occurrence." msgstr "" +"A classe :class:`Font` representa uma fonte nomeada. Instâncias *font* " +"recebem nomes únicos e podem ser especificadas por família, tamanho e " +"configuração de estilo. Fontes nomeadas são os métodos Tk para criação e " +"identificação de fontes de um objeto singular, ao invés de especificar a " +"fonte por seus atributos em cada ocorrência." #: ../../library/tkinter.font.rst:30 msgid "arguments:" @@ -56,27 +63,28 @@ msgstr "argumentos:" #: ../../library/tkinter.font.rst:0 msgid "*font* - font specifier tuple (family, size, options)" -msgstr "" +msgstr "*font* - tupla de especificação da fonte (família, tamanho, opções)" #: ../../library/tkinter.font.rst:0 msgid "*name* - unique font name" -msgstr "" +msgstr "*name* - nome único da fonte" #: ../../library/tkinter.font.rst:0 msgid "*exists* - self points to existing named font if true" -msgstr "" +msgstr "*exists* - aponta para uma fonte nomeada existente se for verdadeiro" #: ../../library/tkinter.font.rst:36 msgid "additional keyword options (ignored if *font* is specified):" msgstr "" +"palavras reservadas opcionais (ignoradas caso *font* seja especificado):" #: ../../library/tkinter.font.rst:0 msgid "*family* - font family i.e. Courier, Times" -msgstr "" +msgstr "*family* - a família da fonte e.x. Courier, Times" #: ../../library/tkinter.font.rst:0 msgid "*size* - font size" -msgstr "" +msgstr "*size* - tamanho da fonte" #: ../../library/tkinter.font.rst:0 msgid "If *size* is positive it is interpreted as size in points." @@ -84,43 +92,44 @@ msgstr "Se *size* for positivo, ele é interpretado como tamanho em pontos." #: ../../library/tkinter.font.rst:0 msgid "If *size* is a negative number its absolute value is treated" -msgstr "" +msgstr "Caso *size* seja um número negativo, seu valor absoluto é tratado" #: ../../library/tkinter.font.rst:0 msgid "as size in pixels." -msgstr "" +msgstr "como tamanho em pixels." #: ../../library/tkinter.font.rst:0 msgid "*weight* - font emphasis (NORMAL, BOLD)" -msgstr "" +msgstr "*weight* - ênfase da fonte (normal,negrito)" #: ../../library/tkinter.font.rst:0 msgid "*slant* - ROMAN, ITALIC" -msgstr "" +msgstr "*slant* - ROMAN, ITALIC" #: ../../library/tkinter.font.rst:0 msgid "*underline* - font underlining (0 - none, 1 - underline)" msgstr "" +"*underline* - sublinhamento da fonte (0 - sem sublinhamento, 1 - sublinhado)" #: ../../library/tkinter.font.rst:0 msgid "*overstrike* - font strikeout (0 - none, 1 - strikeout)" -msgstr "" +msgstr "*overstrike* - fonte riscada (0 - sem risco, 1 - letras riscadas)" #: ../../library/tkinter.font.rst:50 msgid "Return the attributes of the font." -msgstr "" +msgstr "Retorna os atributos da fonte." #: ../../library/tkinter.font.rst:54 msgid "Retrieve an attribute of the font." -msgstr "" +msgstr "Recupera um atributo da fonte." #: ../../library/tkinter.font.rst:58 msgid "Modify attributes of the font." -msgstr "" +msgstr "Modifica atributos da fonte." #: ../../library/tkinter.font.rst:62 msgid "Return new instance of the current font." -msgstr "" +msgstr "Retorna uma nova instância da fonte atual." #: ../../library/tkinter.font.rst:66 msgid "" @@ -128,47 +137,52 @@ msgid "" "formatted in the current font. If no display is specified then the main " "application window is assumed." msgstr "" +"Retorna a quantidade de espaço que o texto ocuparia na exibição especificada " +"ao ser formatado na fonte atual. Caso nenhuma exibição seja especificada, a " +"exibição presumida será a da janela principal da aplicação." #: ../../library/tkinter.font.rst:72 msgid "Return font-specific data. Options include:" -msgstr "" +msgstr "Retorna dados específicos da fonte. Opções inclusas:" #: ../../library/tkinter.font.rst:75 msgid "*ascent* - distance between baseline and highest point that a" -msgstr "" +msgstr "*ascent* - distância entre a linha de base e o ponto mais alto que um" #: ../../library/tkinter.font.rst:76 ../../library/tkinter.font.rst:79 msgid "character of the font can occupy" -msgstr "" +msgstr "caractere da fonte pode ocupar" #: ../../library/tkinter.font.rst:78 msgid "*descent* - distance between baseline and lowest point that a" msgstr "" +"*descent* - distância entre a linha de base e o ponto mais baixo que um" #: ../../library/tkinter.font.rst:81 msgid "*linespace* - minimum vertical separation necessary between any two" -msgstr "" +msgstr "*linespace* - separação vertical mínima necessária entre dois" #: ../../library/tkinter.font.rst:82 msgid "characters of the font that ensures no vertical overlap between lines." msgstr "" +"caracteres da fonte que garante que não ocorra sobreposição entre as linhas." #: ../../library/tkinter.font.rst:84 msgid "*fixed* - 1 if font is fixed-width else 0" -msgstr "" +msgstr "*fixed* - 1 caso a fonte seja de largura fixa, 0 caso contrário" #: ../../library/tkinter.font.rst:88 msgid "Return the different font families." -msgstr "" +msgstr "Retorna as diferentes famílias de fontes." #: ../../library/tkinter.font.rst:92 msgid "Return the names of defined fonts." -msgstr "" +msgstr "Retorna os nomes das fontes definidas." #: ../../library/tkinter.font.rst:96 msgid "Return a :class:`Font` representation of a tk named font." -msgstr "" +msgstr "Retorna a representação :class:`Font` de uma fonte nomeada do tk." #: ../../library/tkinter.font.rst:98 msgid "The *root* parameter was added." -msgstr "" +msgstr "O parâmetro *root* foi adicionado." diff --git a/library/tkinter.messagebox.po b/library/tkinter.messagebox.po index 96f4ec804..8ff82a09a 100644 --- a/library/tkinter.messagebox.po +++ b/library/tkinter.messagebox.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Julio Biason, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:15+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/tkinter.po b/library/tkinter.po index 1b3679b73..d0580cab0 100644 --- a/library/tkinter.po +++ b/library/tkinter.po @@ -1,38 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Italo Penaforte , 2021 -# And Past , 2021 -# Marco Rougeth , 2021 -# Welington Carlos , 2021 -# mvpetri , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# felipe caridade fernandes , 2021 -# i17obot , 2021 -# Augusta Carla Klug , 2021 -# Bruno Divino, 2022 -# Carine Neris, 2022 -# Italo Carvalho Vianelli Ribeiro, 2022 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 01:15+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -175,11 +162,11 @@ msgstr "Por Mark Roseman. (ISBN 978-1999149567)" #: ../../library/tkinter.rst:61 msgid "" -"`Python GUI programming with Tkinter `_" +"`Python GUI programming with Tkinter `_" msgstr "" -"`Python GUI programming with Tkinter `_" +"`Python GUI programming with Tkinter `_" #: ../../library/tkinter.rst:62 msgid "By Alan D. Moore. (ISBN 978-1788835886)" @@ -331,6 +318,14 @@ msgstr "" "módulo :mod:`tkinter.ttk`, que fornece o conjunto de widgets temáticos " "modernos e a API::" +#: ../../library/tkinter.rst:123 +msgid "" +"from tkinter import *\n" +"from tkinter import ttk" +msgstr "" +"from tkinter import *\n" +"from tkinter import ttk" + #: ../../library/tkinter.rst:129 msgid "" "Construct a toplevel Tk widget, which is usually the main window of an " @@ -700,6 +695,26 @@ msgstr "" "World\". Esta não é a menor aplicação que poderíamos escrever, mas tem o " "suficiente para ilustrar alguns conceitos-chave que você precisa saber." +#: ../../library/tkinter.rst:286 +msgid "" +"from tkinter import *\n" +"from tkinter import ttk\n" +"root = Tk()\n" +"frm = ttk.Frame(root, padding=10)\n" +"frm.grid()\n" +"ttk.Label(frm, text=\"Hello World!\").grid(column=0, row=0)\n" +"ttk.Button(frm, text=\"Quit\", command=root.destroy).grid(column=1, row=0)\n" +"root.mainloop()" +msgstr "" +"from tkinter import *\n" +"from tkinter import ttk\n" +"root = Tk()\n" +"frm = ttk.Frame(root, padding=10)\n" +"frm.grid()\n" +"ttk.Label(frm, text=\"Hello World!\").grid(column=0, row=0)\n" +"ttk.Button(frm, text=\"Quit\", command=root.destroy).grid(column=1, row=0)\n" +"root.mainloop()" + #: ../../library/tkinter.rst:296 msgid "" "After the imports, the next line creates an instance of the :class:`Tk` " @@ -867,6 +882,20 @@ msgstr "" "Para ilustrar, aqui está o equivalente Tcl/Tk da parte principal do script " "Tkinter acima." +#: ../../library/tkinter.rst:367 +msgid "" +"ttk::frame .frm -padding 10\n" +"grid .frm\n" +"grid [ttk::label .frm.lbl -text \"Hello World!\"] -column 0 -row 0\n" +"grid [ttk::button .frm.btn -text \"Quit\" -command \"destroy .\"] -column 1 -" +"row 0" +msgstr "" +"ttk::frame .frm -padding 10\n" +"grid .frm\n" +"grid [ttk::label .frm.lbl -text \"Hello World!\"] -column 0 -row 0\n" +"grid [ttk::button .frm.btn -text \"Quit\" -command \"destroy .\"] -column 1 -" +"row 0" + #: ../../library/tkinter.rst:373 msgid "" "Tcl's syntax is similar to many shell languages, where the first word is the " @@ -979,6 +1008,14 @@ msgstr "" "uma variedade de informações sobre cada objeto, incluindo seus valores " "padrão e atuais. Use :meth:`keys` para obter apenas os nomes de cada opção." +#: ../../library/tkinter.rst:423 +msgid "" +"btn = ttk.Button(frm, ...)\n" +"print(btn.configure().keys())" +msgstr "" +"btn = ttk.Button(frm, ...)\n" +"print(btn.configure().keys())" + #: ../../library/tkinter.rst:426 msgid "" "As most widgets have many configuration options in common, it can be useful " @@ -991,6 +1028,10 @@ msgstr "" "widget. Comparar a lista de opções com a de um widget mais simples, como um " "frame, é uma maneira de fazer isso." +#: ../../library/tkinter.rst:433 +msgid "print(set(btn.configure().keys()) - set(frm.configure().keys()))" +msgstr "print(set(btn.configure().keys()) - set(frm.configure().keys()))" + #: ../../library/tkinter.rst:435 msgid "" "Similarly, you can find the available methods for a widget object using the " @@ -1003,6 +1044,14 @@ msgstr "" "mais de 200 métodos comuns de widget, então identificar aqueles específicos " "para uma classe de widget é útil." +#: ../../library/tkinter.rst:442 +msgid "" +"print(dir(btn))\n" +"print(set(dir(btn)) - set(dir(frm)))" +msgstr "" +"print(dir(btn))\n" +"print(set(dir(btn)) - set(dir(frm)))" + #: ../../library/tkinter.rst:447 msgid "Navigating the Tcl/Tk Reference Manual" msgstr "Navegando no Manual de Referência Tcl/Tk" @@ -1033,6 +1082,14 @@ msgstr "" "como comandos que recebem um caminho de widget como seu primeiro parâmetro, " "seguido de parâmetros opcionais, por exemplo." +#: ../../library/tkinter.rst:461 +msgid "" +"destroy .\n" +"grid .frm.btn -column 0 -row 0" +msgstr "" +"destroy .\n" +"grid .frm.btn -column 0 -row 0" + #: ../../library/tkinter.rst:464 msgid "" "Others, however, look more like methods called on a widget object (in fact, " @@ -1045,6 +1102,14 @@ msgstr "" "com o nome do caminho do widget, sendo o primeiro parâmetro desse comando o " "nome de um método a ser chamado)." +#: ../../library/tkinter.rst:471 +msgid "" +".frm.btn invoke\n" +".frm.lbl configure -text \"Goodbye\"" +msgstr "" +".frm.btn invoke\n" +".frm.lbl configure -text \"Goodbye\"" + #: ../../library/tkinter.rst:475 msgid "" "In the official Tcl/Tk reference documentation, you'll find most operations " @@ -1251,12 +1316,24 @@ msgstr "" msgid "At object creation time, using keyword arguments" msgstr "No momento da criação do objeto, usando argumentos nomeados" +#: ../../library/tkinter.rst:570 +msgid "fred = Button(self, fg=\"red\", bg=\"blue\")" +msgstr "fred = Button(self, fg=\"red\", bg=\"blue\")" + #: ../../library/tkinter.rst:572 msgid "After object creation, treating the option name like a dictionary index" msgstr "" "Após a criação do objeto, tratando o nome da opção como um índice de " "dicionário" +#: ../../library/tkinter.rst:575 +msgid "" +"fred[\"fg\"] = \"red\"\n" +"fred[\"bg\"] = \"blue\"" +msgstr "" +"fred[\"fg\"] = \"red\"\n" +"fred[\"bg\"] = \"blue\"" + #: ../../library/tkinter.rst:578 msgid "" "Use the config() method to update multiple attrs subsequent to object " @@ -1265,6 +1342,10 @@ msgstr "" "Use o método config() para atualizar vários attrs posteriores à criação do " "objeto" +#: ../../library/tkinter.rst:581 +msgid "fred.config(fg=\"red\", bg=\"blue\")" +msgstr "fred.config(fg=\"red\", bg=\"blue\")" + #: ../../library/tkinter.rst:583 msgid "" "For a complete explanation of a given option and its behavior, see the Tk " @@ -1401,6 +1482,14 @@ msgstr "``'groove'``" msgid "Example::" msgstr "Exemplo::" +#: ../../library/tkinter.rst:626 +msgid "" +">>> print(fred.config())\n" +"{'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')}" +msgstr "" +">>> print(fred.config())\n" +"{'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')}" + #: ../../library/tkinter.rst:629 msgid "" "Of course, the dictionary printed will include all the options available and " @@ -1474,6 +1563,16 @@ msgstr "" "deverá se comportar quando a janela da aplicação principal for " "redimensionada. Aqui estão alguns exemplos::" +#: ../../library/tkinter.rst:662 +msgid "" +"fred.pack() # defaults to side = \"top\"\n" +"fred.pack(side=\"left\")\n" +"fred.pack(expand=1)" +msgstr "" +"fred.pack() # tem como padrão side = \"top\"\n" +"fred.pack(side=\"left\")\n" +"fred.pack(expand=1)" + #: ../../library/tkinter.rst:668 msgid "Packer Options" msgstr "Opções do Empacotador" @@ -1597,6 +1696,69 @@ msgstr "" msgid "For example::" msgstr "Por exemplo::" +#: ../../library/tkinter.rst:716 +msgid "" +"import tkinter as tk\n" +"\n" +"class App(tk.Frame):\n" +" def __init__(self, master):\n" +" super().__init__(master)\n" +" self.pack()\n" +"\n" +" self.entrythingy = tk.Entry()\n" +" self.entrythingy.pack()\n" +"\n" +" # Create the application variable.\n" +" self.contents = tk.StringVar()\n" +" # Set it to some value.\n" +" self.contents.set(\"this is a variable\")\n" +" # Tell the entry widget to watch this variable.\n" +" self.entrythingy[\"textvariable\"] = self.contents\n" +"\n" +" # Define a callback for when the user hits return.\n" +" # It prints the current value of the variable.\n" +" self.entrythingy.bind('',\n" +" self.print_contents)\n" +"\n" +" def print_contents(self, event):\n" +" print(\"Hi. The current entry content is:\",\n" +" self.contents.get())\n" +"\n" +"root = tk.Tk()\n" +"myapp = App(root)\n" +"myapp.mainloop()" +msgstr "" +"import tkinter as tk\n" +"\n" +"class App(tk.Frame):\n" +" def __init__(self, master):\n" +" super().__init__(master)\n" +" self.pack()\n" +"\n" +" self.entrythingy = tk.Entry()\n" +" self.entrythingy.pack()\n" +"\n" +" # Cria a variável da aplicação.\n" +" self.contents = tk.StringVar()\n" +" # Define-a com algum valor.\n" +" self.contents.set(\"this is a variable\")\n" +" # Fala para o widget de entrada para monitorar essa variável.\n" +" self.entrythingy[\"textvariable\"] = self.contents\n" +"\n" +" # Define um retorno de chamada para quando o usuário pressionar " +"Enter.\n" +" # Isso imprime o valor atual da variável.\n" +" self.entrythingy.bind('',\n" +" self.print_contents)\n" +"\n" +" def print_contents(self, event):\n" +" print(\"Hi. The current entry content is:\",\n" +" self.contents.get())\n" +"\n" +"root = tk.Tk()\n" +"myapp = App(root)\n" +"myapp.mainloop()" + #: ../../library/tkinter.rst:747 msgid "The Window Manager" msgstr "O Gerenciador de Janela" @@ -1639,6 +1801,46 @@ msgstr "" msgid "Here are some examples of typical usage::" msgstr "Aqui estão alguns exemplos de uso típico::" +#: ../../library/tkinter.rst:767 +msgid "" +"import tkinter as tk\n" +"\n" +"class App(tk.Frame):\n" +" def __init__(self, master=None):\n" +" super().__init__(master)\n" +" self.pack()\n" +"\n" +"# create the application\n" +"myapp = App()\n" +"\n" +"#\n" +"# here are method calls to the window manager class\n" +"#\n" +"myapp.master.title(\"My Do-Nothing Application\")\n" +"myapp.master.maxsize(1000, 400)\n" +"\n" +"# start the program\n" +"myapp.mainloop()" +msgstr "" +"import tkinter as tk\n" +"\n" +"class App(tk.Frame):\n" +" def __init__(self, master=None):\n" +" super().__init__(master)\n" +" self.pack()\n" +"\n" +"# Cria a aplicação\n" +"myapp = App()\n" +"\n" +"#\n" +"# aqui estão as chamadas de método para a classe do gerenciador de janelas\n" +"#\n" +"myapp.master.title(\"Meu Aplicativo Que Faz Nada\")\n" +"myapp.master.maxsize(1000, 400)\n" +"\n" +"# inicia o programa\n" +"myapp.mainloop()" + #: ../../library/tkinter.rst:788 ../../library/tkinter.rst:790 msgid "Tk Option Data Types" msgstr "Opções de Tipos de Dados do Tk" @@ -1687,6 +1889,16 @@ msgstr "função de retorno" msgid "This is any Python function that takes no arguments. For example::" msgstr "Esta é uma função Python que não aceita argumentos. Por exemplo::" +#: ../../library/tkinter.rst:808 +msgid "" +"def print_it():\n" +" print(\"hi there\")\n" +"fred[\"command\"] = print_it" +msgstr "" +"def print_it():\n" +" print(\"hi there\")\n" +"fred[\"command\"] = print_it" + #: ../../library/tkinter.rst:812 msgid "color" msgstr "cor" @@ -1843,13 +2055,17 @@ msgstr "" "eventos e tenha um acionamento de função de retorno de chamada quando esse " "tipo de evento ocorrer. A forma do método de ligação é::" +#: ../../library/tkinter.rst:874 +msgid "def bind(self, sequence, func, add=''):" +msgstr "def bind(self, sequence, func, add=''):" + #: ../../library/tkinter.rst:876 msgid "where:" msgstr "sendo que:" #: ../../library/tkinter.rst:878 msgid "sequence" -msgstr "sequence" +msgstr "sequência" #: ../../library/tkinter.rst:879 msgid "" @@ -1891,6 +2107,18 @@ msgstr "" "associado. Passar um ``'+'`` significa que esta função deve ser adicionada à " "lista de funções ligadas a este tipo de evento." +#: ../../library/tkinter.rst:896 +msgid "" +"def turn_red(self, event):\n" +" event.widget[\"activeforeground\"] = \"red\"\n" +"\n" +"self.button.bind(\"\", self.turn_red)" +msgstr "" +"def turn_red(self, event):\n" +" event.widget[\"activeforeground\"] = \"red\"\n" +"\n" +"self.button.bind(\"\", self.turn_red)" + #: ../../library/tkinter.rst:901 msgid "" "Notice how the widget field of the event is being accessed in the " @@ -2181,15 +2409,15 @@ msgid "" "Added the :class:`!PhotoImage` method :meth:`!copy_replace` to copy a region " "from one image to other image, possibly with pixel zooming and/or " "subsampling. Add *from_coords* parameter to :class:`!PhotoImage` methods :" -"meth:`!copy()`, :meth:`!zoom()` and :meth:`!subsample()`. Add *zoom* and " -"*subsample* parameters to :class:`!PhotoImage` method :meth:`!copy()`." +"meth:`!copy`, :meth:`!zoom` and :meth:`!subsample`. Add *zoom* and " +"*subsample* parameters to :class:`!PhotoImage` method :meth:`!copy`." msgstr "" -"Adicionado o método :meth:`!copy_replace` à classe :class:`!PhotoImage` " -"para copiar uma região de uma imagem para outra imagem, possivelmente com " +"Adicionado o método :meth:`!copy_replace` à classe :class:`!PhotoImage` para " +"copiar uma região de uma imagem para outra imagem, possivelmente com " "ampliação e subamostragem de pixels. Adiciona parâmetro *from_coords* para " -"os métodos :meth:`!copy()`, :meth:`!zoom()` e :meth:`!subsample()` da " -"classe :class:`!PhotoImage`. Adiciona parâmetros *zoom* e *subsample* para o " -"método :meth:`!copy()` da classe :class:`!PhotoImage`." +"os métodos :meth:`!copy`, :meth:`!zoom` e :meth:`!subsample` da classe :" +"class:`!PhotoImage`. Adiciona parâmetros *zoom* e *subsample* para o método :" +"meth:`!copy` da classe :class:`!PhotoImage`." #: ../../library/tkinter.rst:991 msgid "" @@ -2228,6 +2456,22 @@ msgstr "" "em um descritor de arquivo. Apenas um tratador pode ser registrado por " "descritor de arquivo. Código de exemplo::" +#: ../../library/tkinter.rst:1011 +msgid "" +"import tkinter\n" +"widget = tkinter.Tk()\n" +"mask = tkinter.READABLE | tkinter.WRITABLE\n" +"widget.tk.createfilehandler(file, mask, callback)\n" +"...\n" +"widget.tk.deletefilehandler(file)" +msgstr "" +"import tkinter\n" +"widget = tkinter.Tk()\n" +"mask = tkinter.READABLE | tkinter.WRITABLE\n" +"widget.tk.createfilehandler(file, mask, callback)\n" +"...\n" +"widget.tk.deletefilehandler(file)" + #: ../../library/tkinter.rst:1018 msgid "This feature is not available on Windows." msgstr "Este recurso não está disponível no Windows." @@ -2264,6 +2508,10 @@ msgstr "" "argumento *mask* é uma combinação OR de qualquer uma das três constantes " "abaixo. O retorno de chamada é chamado da seguinte maneira::" +#: ../../library/tkinter.rst:1037 +msgid "callback(file, mask)" +msgstr "callback(file, mask)" + #: ../../library/tkinter.rst:1042 msgid "Unregisters a file handler." msgstr "Cancela o registro de um tratador de arquivo." diff --git a/library/tkinter.scrolledtext.po b/library/tkinter.scrolledtext.po index 64b6fe581..58aa37d52 100644 --- a/library/tkinter.scrolledtext.po +++ b/library/tkinter.scrolledtext.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:15+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/tkinter.ttk.po b/library/tkinter.ttk.po index d805bb7d2..d68af1bd4 100644 --- a/library/tkinter.ttk.po +++ b/library/tkinter.ttk.po @@ -1,41 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Misael borges , 2021 -# i17obot , 2021 -# Raphael Mendonça, 2021 -# mvpetri , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Philippe Gonzaga , 2021 -# Danilo Lima , 2021 -# Luca Farah, 2021 -# Adorilson Bezerra , 2023 -# Rafael Fontenelle , 2023 -# Italo Penaforte , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 02:33+0000\n" -"PO-Revision-Date: 2021-06-28 01:15+0000\n" -"Last-Translator: Italo Penaforte , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/tkinter.ttk.rst:2 msgid ":mod:`!tkinter.ttk` --- Tk themed widgets" -msgstr "" +msgstr ":mod:`!tkinter.ttk` --- Widgets temáticos do Tk" #: ../../library/tkinter.ttk.rst:9 msgid "**Source code:** :source:`Lib/tkinter/ttk.py`" @@ -48,6 +38,11 @@ msgid "" "font rendering under X11 and window transparency (requiring a composition " "window manager on X11)." msgstr "" +"O módulo :mod:`tkinter.ttk` introduzido no Tk 8.5, fornece acesso ao " +"conjunto de widgets temáticos do Tk, Alguns dos beneficios incluídos são a " +"renderização de fontes com suavização de serrilhamento no x11 e " +"transparência de janelas (requer um gerenciador de composição de janelas no " +"x11)." #: ../../library/tkinter.ttk.rst:20 msgid "" @@ -76,6 +71,10 @@ msgstr "Usando Ttk" msgid "To start using Ttk, import its module::" msgstr "Para começar a usar Ttk, importe seu módulo::" +#: ../../library/tkinter.ttk.rst:36 +msgid "from tkinter import ttk" +msgstr "" + #: ../../library/tkinter.ttk.rst:38 msgid "" "To override the basic Tk widgets, the import should follow the Tk import::" @@ -83,6 +82,12 @@ msgstr "" "Para substituir os widgets básicos do Tk, a importação deve seguir a " "importação do Tk::" +#: ../../library/tkinter.ttk.rst:40 +msgid "" +"from tkinter import *\n" +"from tkinter.ttk import *" +msgstr "" + #: ../../library/tkinter.ttk.rst:43 msgid "" "That code causes several :mod:`tkinter.ttk` widgets (:class:`Button`, :class:" @@ -91,6 +96,11 @@ msgid "" "`Radiobutton`, :class:`Scale` and :class:`Scrollbar`) to automatically " "replace the Tk widgets." msgstr "" +"Esse código faz com que vários widgets :mod:`tkinter.ttk` (:class:`Button`, :" +"class:`Checkbutton`, :class:`Entry`, :class:`Frame`, :class:`Label`, :class:" +"`LabelFrame`, :class:`Menubutton`, :class:`PanedWindow`, :class:" +"`Radiobutton`, :class:`Scale` e :class:`Scrollbar`) substituam " +"automaticamente os widgets Tk." #: ../../library/tkinter.ttk.rst:49 msgid "" @@ -101,22 +111,32 @@ msgid "" "Ttk widgets. Instead, use the :class:`ttk.Style` class for improved " "styling effects." msgstr "" +"Isso traz o benefício direto de utilizar os widgets novos que possuem melhor " +"aparência e sensação de uso entre as plataformas, contudo, os widgets " +"substitutos não são completamente compatíveis. A maior diferença é que as " +"opções como \"fg\", \"bg\" e outras relacionadas à estilização do widget não " +"estão mais presentes nos widgets Ttk. Em vez disso, use a classe :class:" +"`ttk.Style` para melhores efeitos de estilização." #: ../../library/tkinter.ttk.rst:59 msgid "" "`Converting existing applications to use Tile widgets `_" msgstr "" +"`Convertendo aplicações existentes para utilização dos widgets Tile `_" #: ../../library/tkinter.ttk.rst:60 msgid "" "A monograph (using Tcl terminology) about differences typically encountered " "when moving applications to use the new widgets." msgstr "" +"Uma monografia (utilizando a terminologia Tcl) sobre diferenças tipicamente " +"encontradas ao mover aplicações para utilização de novos widgets." #: ../../library/tkinter.ttk.rst:65 msgid "Ttk Widgets" -msgstr "" +msgstr "Widgets Ttk" #: ../../library/tkinter.ttk.rst:67 msgid "" @@ -128,44 +148,73 @@ msgid "" "class:`Progressbar`, :class:`Separator`, :class:`Sizegrip` and :class:" "`Treeview`. And all them are subclasses of :class:`Widget`." msgstr "" +"Ttk traz 18 widgets, das quais doze já existiam no tkinter: :class:" +"`Button`, :class:`Checkbutton`, :class:`Entry`, :class:`Frame`, :class:" +"`Label`, :class:`LabelFrame`, :class:`Menubutton`, :class:`PanedWindow`, :" +"class:`Radiobutton`, :class:`Scale`, :class:`Scrollbar`, e :class:`Spinbox`. " +"As outras seis são novas: :class:`Combobox`, :class:`Notebook`, :class:" +"`Progressbar`, :class:`Separator`, :class:`Sizegrip` e :class:`Treeview`. E " +"todas elas são subclasses de :class:`Widget`." #: ../../library/tkinter.ttk.rst:75 msgid "" "Using the Ttk widgets gives the application an improved look and feel. As " "discussed above, there are differences in how the styling is coded." msgstr "" +"Utilizar os widgets Ttk melhora a experiência de uso e o visual da " +"aplicação. Conforme discutido anteriormente, existem diferenças em como a " +"estilização é codificada." #: ../../library/tkinter.ttk.rst:78 msgid "Tk code::" msgstr "Código Tk::" +#: ../../library/tkinter.ttk.rst:80 +msgid "" +"l1 = tkinter.Label(text=\"Test\", fg=\"black\", bg=\"white\")\n" +"l2 = tkinter.Label(text=\"Test\", fg=\"black\", bg=\"white\")" +msgstr "" + #: ../../library/tkinter.ttk.rst:84 msgid "Ttk code::" msgstr "Código Ttk::" +#: ../../library/tkinter.ttk.rst:86 +msgid "" +"style = ttk.Style()\n" +"style.configure(\"BW.TLabel\", foreground=\"black\", background=\"white\")\n" +"\n" +"l1 = ttk.Label(text=\"Test\", style=\"BW.TLabel\")\n" +"l2 = ttk.Label(text=\"Test\", style=\"BW.TLabel\")" +msgstr "" + #: ../../library/tkinter.ttk.rst:92 msgid "" "For more information about TtkStyling_, see the :class:`Style` class " "documentation." msgstr "" +"Para mais informações sobre TtkStyling_, veja a documentação da classe :" +"class:`Style`." #: ../../library/tkinter.ttk.rst:96 msgid "Widget" -msgstr "Ferramenta" +msgstr "Widget" #: ../../library/tkinter.ttk.rst:98 msgid "" ":class:`ttk.Widget` defines standard options and methods supported by Tk " "themed widgets and is not supposed to be directly instantiated." msgstr "" +":class:`ttk.Widget` define opções padrão e métodos suportados pelos widgets " +"temáticos Tk e não deve ser instanciada diretamente." #: ../../library/tkinter.ttk.rst:103 msgid "Standard Options" -msgstr "Opções padrões" +msgstr "Opções padrão" #: ../../library/tkinter.ttk.rst:105 msgid "All the :mod:`ttk` Widgets accept the following options:" -msgstr "" +msgstr "Todos os Widgets :mod:`ttk` aceitam as seguintes opções:" #: ../../library/tkinter.ttk.rst:110 ../../library/tkinter.ttk.rst:145 #: ../../library/tkinter.ttk.rst:171 ../../library/tkinter.ttk.rst:214 @@ -190,7 +239,7 @@ msgstr "Descrição" #: ../../library/tkinter.ttk.rst:112 msgid "class" -msgstr "class" +msgstr "classe" #: ../../library/tkinter.ttk.rst:112 msgid "" @@ -209,10 +258,12 @@ msgid "" "Specifies the mouse cursor to be used for the widget. If set to the empty " "string (the default), the cursor is inherited for the parent widget." msgstr "" +"Especifica o cursor do mouse a ser utilizado pelo widget. Caso seja definido " +"como uma string vazia (padrão), o cursor é herdado do widget pai." #: ../../library/tkinter.ttk.rst:123 msgid "takefocus" -msgstr "" +msgstr "takefocus" #: ../../library/tkinter.ttk.rst:123 msgid "" @@ -223,6 +274,12 @@ msgid "" "And an empty string means that the traversal scripts make the decision about " "whether or not to focus on the window." msgstr "" +"Determina se a janela aceitará foco durante a navegação com o teclado. " +"Retorna 0, 1 ou uma string vazia. Caso retorne 0, significa que a janela " +"deve ser completamente ignorada durante a navegação com o teclado. Caso " +"retorne 1, significa que a janela receberá as entradas do teclado enquanto " +"estiver visível. E a string vazia significa que os scripts de navegação " +"determinam quando a janela recebe foco ou não." #: ../../library/tkinter.ttk.rst:132 msgid "style" @@ -230,7 +287,7 @@ msgstr "estilo" #: ../../library/tkinter.ttk.rst:132 msgid "May be used to specify a custom widget style." -msgstr "" +msgstr "Pode ser utilizado para especificar um estilo customizado do widget." #: ../../library/tkinter.ttk.rst:137 msgid "Scrollable Widget Options" @@ -241,20 +298,24 @@ msgid "" "The following options are supported by widgets that are controlled by a " "scrollbar." msgstr "" +"As opções a seguir são suportadas pelos widgets que são controlados por uma " +"barra de rolagem." #: ../../library/tkinter.ttk.rst:147 msgid "xscrollcommand" -msgstr "" +msgstr "xscrollcommand" #: ../../library/tkinter.ttk.rst:147 msgid "Used to communicate with horizontal scrollbars." -msgstr "" +msgstr "Utilizado para comunicação com barras de rolagem horizontais." #: ../../library/tkinter.ttk.rst:149 msgid "" "When the view in the widget's window change, the widget will generate a Tcl " "command based on the scrollcommand." msgstr "" +"Quando a visualização na janela do widget mudar, o widget irá gerar um " +"comando Tcl baseado no comando da barra de rolagem." #: ../../library/tkinter.ttk.rst:152 msgid "" @@ -262,16 +323,21 @@ msgid "" "scrollbar. This will cause the scrollbar to be updated whenever the view in " "the window changes." msgstr "" +"Geralmente essa opção consiste no método :meth:`Scrollbar.set` de alguma " +"barra de rolagem. Isso fará com que a barra de rolagem seja atualizada " +"sempre que a visualização da janela mude." #: ../../library/tkinter.ttk.rst:157 msgid "yscrollcommand" -msgstr "" +msgstr "yscrollcommand" #: ../../library/tkinter.ttk.rst:157 msgid "" "Used to communicate with vertical scrollbars. For some more information, see " "above." msgstr "" +"Utilizado para comunicação com barras de rolagem verticais. Para mais " +"informações, veja acima." #: ../../library/tkinter.ttk.rst:163 msgid "Label Options" @@ -282,19 +348,21 @@ msgid "" "The following options are supported by labels, buttons and other button-like " "widgets." msgstr "" +"As opções a seguir são suportadas por rótulos, botões e outros widgets " +"semelhantes." #: ../../library/tkinter.ttk.rst:173 ../../library/tkinter.ttk.rst:521 #: ../../library/tkinter.ttk.rst:861 msgid "text" -msgstr "texto" +msgstr "text" #: ../../library/tkinter.ttk.rst:173 msgid "Specifies a text string to be displayed inside the widget." -msgstr "" +msgstr "Especifica uma string para exibição dentro do widget." #: ../../library/tkinter.ttk.rst:175 ../../library/tkinter.ttk.rst:339 msgid "textvariable" -msgstr "" +msgstr "textvariable" #: ../../library/tkinter.ttk.rst:175 msgid "" @@ -304,18 +372,21 @@ msgstr "" #: ../../library/tkinter.ttk.rst:178 ../../library/tkinter.ttk.rst:530 msgid "underline" -msgstr "" +msgstr "underline" #: ../../library/tkinter.ttk.rst:178 msgid "" "If set, specifies the index (0-based) of a character to underline in the " "text string. The underline character is used for mnemonic activation." msgstr "" +"Caso definido, especifica o índice (base-0) de um caractere para " +"sublinhamento na string de texto. O caractere sublinhado é utilizado para " +"ativação mnemônica." #: ../../library/tkinter.ttk.rst:182 ../../library/tkinter.ttk.rst:523 #: ../../library/tkinter.ttk.rst:863 ../../library/tkinter.ttk.rst:895 msgid "image" -msgstr "" +msgstr "image" #: ../../library/tkinter.ttk.rst:182 msgid "" @@ -325,16 +396,24 @@ msgid "" "different images to use when the widget is in a particular state or a " "combination of states. All images in the list should have the same size." msgstr "" +"Define uma imagem para exibição. Isso é uma lista de 1 ou mais elementos. O " +"primeiro elemento é o nome da imagem padrão. O resto da lista é uma " +"sequência de pares estado/valor conforme definido por :meth:`Style.map`, " +"definindo imagens diferentes para utilização quando o widget estiver em um " +"determinado estado ou em uma combinação de estados. Todas as imagens da " +"lista devem ter o mesmo tamanho." #: ../../library/tkinter.ttk.rst:190 ../../library/tkinter.ttk.rst:526 msgid "compound" -msgstr "" +msgstr "compound" #: ../../library/tkinter.ttk.rst:190 msgid "" "Specifies how to display the image relative to the text, in the case both " "text and images options are present. Valid values are:" msgstr "" +"Define como exibir a imagem em relação ao texto, no caso em que ambas as " +"opções de texto e imagem estejam presentes. Valores válidos são:" #: ../../library/tkinter.ttk.rst:194 msgid "text: display text only" @@ -349,10 +428,14 @@ msgid "" "top, bottom, left, right: display image above, below, left of, or right of " "the text, respectively." msgstr "" +"top, bottom, left, right: exibem a imagem acima, abaixo, à esquerda, ou à " +"direita do texto, respectivamente." #: ../../library/tkinter.ttk.rst:198 msgid "none: the default. display the image if present, otherwise the text." msgstr "" +"none: o padrão, exibe a imagem caso ela esteja presente, caso contrário , " +"exibe o texto." #: ../../library/tkinter.ttk.rst:201 ../../library/tkinter.ttk.rst:347 #: ../../library/tkinter.ttk.rst:491 @@ -365,6 +448,10 @@ msgid "" "allocate for the text label, if less than zero, specifies a minimum width. " "If zero or unspecified, the natural width of the text label is used." msgstr "" +"Caso maior que zero, especifica quanto espaço, em largura de caracteres, " +"alocar para o rótulo do texto, se menor que zero, especifica a largura " +"mínima. Se zero ou inespecífico, é utilizada a largura normal do rótulo de " +"texto." #: ../../library/tkinter.ttk.rst:209 msgid "Compatibility Options" @@ -384,11 +471,12 @@ msgstr "" #: ../../library/tkinter.ttk.rst:223 msgid "Widget States" -msgstr "" +msgstr "Estados de Widget" #: ../../library/tkinter.ttk.rst:225 msgid "The widget state is a bitmap of independent state flags." msgstr "" +"O estado do widget é um bitmap de sinalizadores de estado independentes." #: ../../library/tkinter.ttk.rst:230 msgid "Flag" @@ -396,21 +484,23 @@ msgstr "Sinalizador" #: ../../library/tkinter.ttk.rst:232 msgid "active" -msgstr "" +msgstr "active" #: ../../library/tkinter.ttk.rst:232 msgid "" "The mouse cursor is over the widget and pressing a mouse button will cause " "some action to occur" msgstr "" +"O cursor do mouse está sobre o widget e pressionar um botão do mouse causará " +"alguma ação" #: ../../library/tkinter.ttk.rst:235 msgid "disabled" -msgstr "inválido" +msgstr "disabled" #: ../../library/tkinter.ttk.rst:235 msgid "Widget is disabled under program control" -msgstr "" +msgstr "Widget está desabilitado sob controle do programa." #: ../../library/tkinter.ttk.rst:237 msgid "focus" @@ -418,19 +508,19 @@ msgstr "focus" #: ../../library/tkinter.ttk.rst:237 msgid "Widget has keyboard focus" -msgstr "" +msgstr "Widget tem foco do teclado" #: ../../library/tkinter.ttk.rst:239 msgid "pressed" -msgstr "" +msgstr "pressed" #: ../../library/tkinter.ttk.rst:239 msgid "Widget is being pressed" -msgstr "" +msgstr "Widget está sendo pressionado" #: ../../library/tkinter.ttk.rst:241 msgid "selected" -msgstr "selecionado" +msgstr "selected" #: ../../library/tkinter.ttk.rst:241 msgid "" @@ -448,6 +538,9 @@ msgid "" "*background* state is set for widgets in a background window, and cleared " "for those in the foreground window" msgstr "" +"Windows e Mac possuem uma noção de janela \"ativa\" ou em primeiro plano. O " +"estado de \"plano de fundo\" é definido para widgets em uma janela no plano " +"de fundo, e limpo para aqueles na janela de primeiro plano" #: ../../library/tkinter.ttk.rst:249 msgid "readonly" @@ -455,7 +548,7 @@ msgstr "readonly" #: ../../library/tkinter.ttk.rst:249 msgid "Widget should not allow user modification" -msgstr "" +msgstr "Widget não deve permitir modificação do usuário" #: ../../library/tkinter.ttk.rst:251 msgid "alternate" @@ -463,41 +556,49 @@ msgstr "alternate" #: ../../library/tkinter.ttk.rst:251 msgid "A widget-specific alternate display format" -msgstr "" +msgstr "Um formato de exibição específico do widget" #: ../../library/tkinter.ttk.rst:253 msgid "invalid" -msgstr "" +msgstr "invalid" #: ../../library/tkinter.ttk.rst:253 msgid "The widget's value is invalid" -msgstr "" +msgstr "O valor do widget é inválido" #: ../../library/tkinter.ttk.rst:256 msgid "" "A state specification is a sequence of state names, optionally prefixed with " "an exclamation point indicating that the bit is off." msgstr "" +"Uma especificação de estado é uma sequência de nomes de estado, " +"opcionalmente prefixada por um ponto de exclamação indicando que o bit está " +"desligado." #: ../../library/tkinter.ttk.rst:261 msgid "ttk.Widget" -msgstr "" +msgstr "ttk.Widget" #: ../../library/tkinter.ttk.rst:263 msgid "" "Besides the methods described below, the :class:`ttk.Widget` supports the " "methods :meth:`tkinter.Widget.cget` and :meth:`tkinter.Widget.configure`." msgstr "" +"Além dos métodos descritos abaixo, a classe :class:`ttk.Widget` oferece " +"suporte aos métodos :meth:`tkinter.Widget.cget` e :meth:`tkinter.Widget." +"configure`." #: ../../library/tkinter.ttk.rst:270 msgid "" "Returns the name of the element at position *x* *y*, or the empty string if " "the point does not lie within any element." msgstr "" +"Retorna o nome do elemento na posição *x* *y*, ou a string vazia caso o " +"ponto não esteja dentro de algum elemento." #: ../../library/tkinter.ttk.rst:273 msgid "*x* and *y* are pixel coordinates relative to the widget." -msgstr "" +msgstr "*x* e *y* são coordenadas de pixel relativas ao widget." #: ../../library/tkinter.ttk.rst:278 msgid "" @@ -527,6 +628,8 @@ msgid "" "The :class:`ttk.Combobox` widget combines a text field with a pop-down list " "of values. This widget is a subclass of :class:`Entry`." msgstr "" +"O widget :class:`ttk.Combobox` combina um campo de texto com uma lista " +"suspensa de valores. Esse widget é uma subclasse de :class:`Entry`." #: ../../library/tkinter.ttk.rst:300 msgid "" @@ -548,11 +651,11 @@ msgstr "Opções" #: ../../library/tkinter.ttk.rst:474 ../../library/tkinter.ttk.rst:664 #: ../../library/tkinter.ttk.rst:803 msgid "This widget accepts the following specific options:" -msgstr "" +msgstr "Este widget aceita as seguintes opções específicas:" #: ../../library/tkinter.ttk.rst:319 msgid "exportselection" -msgstr "" +msgstr "exportselection" #: ../../library/tkinter.ttk.rst:319 msgid "" @@ -560,6 +663,9 @@ msgid "" "selection (which can be returned by invoking Misc.selection_get, for " "example)." msgstr "" +"Valor booleano. Caso definido, a seleção do widget é vinculada à seleção do " +"Gerenciador de Janelas (que pode ser retornada ao chamar Misc.selection_get, " +"por exemplo)." #: ../../library/tkinter.ttk.rst:323 msgid "justify" @@ -570,6 +676,8 @@ msgid "" "Specifies how the text is aligned within the widget. One of \"left\", " "\"center\", or \"right\"." msgstr "" +"Especifica como o texto é alinhado dentro do widget. Pode ser \"left\", " +"\"center\" ou \"right\"." #: ../../library/tkinter.ttk.rst:326 ../../library/tkinter.ttk.rst:481 #: ../../library/tkinter.ttk.rst:818 @@ -578,17 +686,20 @@ msgstr "height" #: ../../library/tkinter.ttk.rst:326 msgid "Specifies the height of the pop-down listbox, in rows." -msgstr "" +msgstr "Especifica a altura, em linhas, da lista suspensa." #: ../../library/tkinter.ttk.rst:328 msgid "postcommand" -msgstr "" +msgstr "postcommand" #: ../../library/tkinter.ttk.rst:328 msgid "" "A script (possibly registered with Misc.register) that is called immediately " "before displaying the values. It may specify which values to display." msgstr "" +"Um script (possivelmente registrado com Misc.register) que é chamado " +"imediatamente antes da exibição dos valores. Ele pode especificar quais " +"valores exibir." #: ../../library/tkinter.ttk.rst:332 msgid "" @@ -597,6 +708,11 @@ msgid "" "values from the dropdown list. In the \"normal\" state, the text field is " "directly editable. In the \"disabled\" state, no interaction is possible." msgstr "" +"Um dos estados: \"normal\", \"readonly\" ou \"disabled\". No estado " +"\"readonly\", o valor não pode ser editado diretamente, e o usuário só pode " +"selecionar valores contidos na lista suspensa. No estado \"normal\", o campo " +"de texto é diretamente editável. No estado \"disabled\", nenhuma interação é " +"possível." #: ../../library/tkinter.ttk.rst:339 msgid "" @@ -604,6 +720,9 @@ msgid "" "value associated with that name changes, the widget value is updated, and " "vice versa. See :class:`tkinter.StringVar`." msgstr "" +"Especifica um nome que terá seu valor vinculado ao valor do widget. Sempre " +"que o valor associado a esse nome mudar, o valor do widget será atualizado, " +"e vice versa. Veja :class:`tkinter.StringVar`." #: ../../library/tkinter.ttk.rst:344 ../../library/tkinter.ttk.rst:417 #: ../../library/tkinter.ttk.rst:865 @@ -612,7 +731,7 @@ msgstr "valores" #: ../../library/tkinter.ttk.rst:344 msgid "Specifies the list of values to display in the drop-down listbox." -msgstr "" +msgstr "Especifica a lista de valores para exibição na lista suspensa." #: ../../library/tkinter.ttk.rst:347 msgid "" @@ -622,17 +741,19 @@ msgstr "" #: ../../library/tkinter.ttk.rst:354 ../../library/tkinter.ttk.rst:442 msgid "Virtual events" -msgstr "" +msgstr "Eventos virtuais" #: ../../library/tkinter.ttk.rst:356 msgid "" "The combobox widgets generates a **<>** virtual event when " "the user selects an element from the list of values." msgstr "" +"Os widgets combobox geram um evento virtual **<>** quando " +"o usuário seleciona um elemento da lista de valores." #: ../../library/tkinter.ttk.rst:361 msgid "ttk.Combobox" -msgstr "" +msgstr "ttk.Combobox" #: ../../library/tkinter.ttk.rst:367 msgid "" @@ -643,7 +764,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:374 msgid "Returns the current value of the combobox." -msgstr "" +msgstr "Retorna o valor atual do combobox." #: ../../library/tkinter.ttk.rst:379 msgid "Sets the value of the combobox to *value*." @@ -651,7 +772,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:383 msgid "Spinbox" -msgstr "" +msgstr "Spinbox" #: ../../library/tkinter.ttk.rst:384 msgid "" @@ -672,7 +793,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:405 msgid "from" -msgstr "de" +msgstr "from" #: ../../library/tkinter.ttk.rst:405 msgid "" @@ -683,7 +804,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:410 msgid "to" -msgstr "para" +msgstr "to" #: ../../library/tkinter.ttk.rst:410 msgid "" @@ -721,7 +842,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:428 msgid "format" -msgstr "formato" +msgstr "format" #: ../../library/tkinter.ttk.rst:428 msgid "" @@ -732,7 +853,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:434 msgid "command" -msgstr "" +msgstr "command" #: ../../library/tkinter.ttk.rst:434 msgid "" @@ -749,7 +870,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:449 msgid "ttk.Spinbox" -msgstr "" +msgstr "ttk.Spinbox" #: ../../library/tkinter.ttk.rst:455 msgid "Returns the current value of the spinbox." @@ -1050,7 +1171,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:677 msgid "mode" -msgstr "modo" +msgstr "mode" #: ../../library/tkinter.ttk.rst:677 msgid "One of \"determinate\" or \"indeterminate\"." @@ -1058,7 +1179,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:679 msgid "maximum" -msgstr "" +msgstr "maximum" #: ../../library/tkinter.ttk.rst:679 msgid "A number specifying the maximum value. Defaults to 100." @@ -1066,7 +1187,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:681 msgid "value" -msgstr "value" +msgstr "valor" #: ../../library/tkinter.ttk.rst:681 msgid "" @@ -1089,7 +1210,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:691 msgid "phase" -msgstr "" +msgstr "phase" #: ../../library/tkinter.ttk.rst:691 msgid "" @@ -1101,7 +1222,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:699 msgid "ttk.Progressbar" -msgstr "" +msgstr "ttk.Progressbar" #: ../../library/tkinter.ttk.rst:705 msgid "" @@ -1126,7 +1247,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:724 msgid "Separator" -msgstr "" +msgstr "Separator" #: ../../library/tkinter.ttk.rst:726 msgid "" @@ -1151,7 +1272,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:748 msgid "Sizegrip" -msgstr "" +msgstr "Sizegrip" #: ../../library/tkinter.ttk.rst:750 msgid "" @@ -1193,7 +1314,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:775 msgid "Treeview" -msgstr "" +msgstr "Treeview" #: ../../library/tkinter.ttk.rst:777 msgid "" @@ -1234,7 +1355,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:810 msgid "columns" -msgstr "" +msgstr "columns" #: ../../library/tkinter.ttk.rst:810 msgid "" @@ -1267,7 +1388,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:825 msgid "selectmode" -msgstr "" +msgstr "selectmode" #: ../../library/tkinter.ttk.rst:825 msgid "" @@ -1285,7 +1406,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:836 msgid "show" -msgstr "" +msgstr "show" #: ../../library/tkinter.ttk.rst:836 msgid "" @@ -1353,7 +1474,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:875 msgid "tags" -msgstr "" +msgstr "tags" #: ../../library/tkinter.ttk.rst:875 msgid "A list of tags associated with this item." @@ -1369,7 +1490,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:889 msgid "foreground" -msgstr "" +msgstr "foreground" #: ../../library/tkinter.ttk.rst:889 msgid "Specifies the text foreground color." @@ -1448,7 +1569,7 @@ msgstr "Evento" #: ../../library/tkinter.ttk.rst:934 msgid "<>" -msgstr "" +msgstr "<>" #: ../../library/tkinter.ttk.rst:934 msgid "Generated whenever the selection changes." @@ -1456,7 +1577,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:936 msgid "<>" -msgstr "" +msgstr "<>" #: ../../library/tkinter.ttk.rst:936 msgid "Generated just before settings the focus item to open=True." @@ -1464,7 +1585,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:939 msgid "<>" -msgstr "" +msgstr "<>" #: ../../library/tkinter.ttk.rst:939 msgid "Generated just after setting the focus item to open=False." @@ -1478,7 +1599,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:948 msgid "ttk.Treeview" -msgstr "" +msgstr "ttk.Treeview" #: ../../library/tkinter.ttk.rst:954 msgid "" @@ -1531,7 +1652,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:989 msgid "*id*" -msgstr "" +msgstr "*id*" #: ../../library/tkinter.ttk.rst:990 msgid "Returns the column name. This is a read-only option." @@ -1560,7 +1681,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:998 msgid "*stretch*: ``True``/``False``" -msgstr "" +msgstr "*stretch*: ``True``/``False``" #: ../../library/tkinter.ttk.rst:999 msgid "" @@ -1894,7 +2015,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:1264 msgid "Ttk Styling" -msgstr "" +msgstr "Ttk Styling" #: ../../library/tkinter.ttk.rst:1266 msgid "" @@ -1936,6 +2057,22 @@ msgid "" "padding and a different background color::" msgstr "" +#: ../../library/tkinter.ttk.rst:1294 +msgid "" +"from tkinter import ttk\n" +"import tkinter\n" +"\n" +"root = tkinter.Tk()\n" +"\n" +"ttk.Style().configure(\"TButton\", padding=6, relief=\"flat\",\n" +" background=\"#ccc\")\n" +"\n" +"btn = ttk.Button(text=\"Sample\")\n" +"btn.pack()\n" +"\n" +"root.mainloop()" +msgstr "" + #: ../../library/tkinter.ttk.rst:1310 msgid "Query or sets dynamic values of the specified option(s) in *style*." msgstr "" @@ -1951,6 +2088,24 @@ msgstr "" msgid "An example may make it more understandable::" msgstr "" +#: ../../library/tkinter.ttk.rst:1319 +msgid "" +"import tkinter\n" +"from tkinter import ttk\n" +"\n" +"root = tkinter.Tk()\n" +"\n" +"style = ttk.Style()\n" +"style.map(\"C.TButton\",\n" +" foreground=[('pressed', 'red'), ('active', 'blue')],\n" +" background=[('pressed', '!disabled', 'black'), ('active', 'white')]\n" +" )\n" +"\n" +"colored_btn = ttk.Button(text=\"Test\", style=\"C.TButton\").pack()\n" +"\n" +"root.mainloop()" +msgstr "" + #: ../../library/tkinter.ttk.rst:1335 msgid "" "Note that the order of the (states, value) sequences for an option does " @@ -1974,6 +2129,13 @@ msgstr "" msgid "To check what font a Button uses by default::" msgstr "" +#: ../../library/tkinter.ttk.rst:1351 +msgid "" +"from tkinter import ttk\n" +"\n" +"print(ttk.Style().lookup(\"TButton\", \"font\"))" +msgstr "" + #: ../../library/tkinter.ttk.rst:1358 msgid "" "Define the widget layout for given *style*. If *layoutspec* is omitted, " @@ -1994,6 +2156,31 @@ msgid "" "do anything useful)::" msgstr "" +#: ../../library/tkinter.ttk.rst:1369 +msgid "" +"from tkinter import ttk\n" +"import tkinter\n" +"\n" +"root = tkinter.Tk()\n" +"\n" +"style = ttk.Style()\n" +"style.layout(\"TMenubutton\", [\n" +" (\"Menubutton.background\", None),\n" +" (\"Menubutton.button\", {\"children\":\n" +" [(\"Menubutton.focus\", {\"children\":\n" +" [(\"Menubutton.padding\", {\"children\":\n" +" [(\"Menubutton.label\", {\"side\": \"left\", \"expand\": " +"1})]\n" +" })]\n" +" })]\n" +" }),\n" +"])\n" +"\n" +"mbtn = ttk.Menubutton(text='Text')\n" +"mbtn.pack()\n" +"root.mainloop()" +msgstr "" + #: ../../library/tkinter.ttk.rst:1393 msgid "" "Create a new element in the current theme, of the given *etype* which is " @@ -2063,6 +2250,17 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" +#: ../../library/tkinter.ttk.rst:1423 +msgid "" +"img1 = tkinter.PhotoImage(master=root, file='button.png')\n" +"img1 = tkinter.PhotoImage(master=root, file='button-pressed.png')\n" +"img1 = tkinter.PhotoImage(master=root, file='button-active.png')\n" +"style = ttk.Style(root)\n" +"style.element_create('Button.button', 'image',\n" +" img1, ('pressed', img2), ('active', img3),\n" +" border=(2, 4), sticky='we')" +msgstr "" + #: ../../library/tkinter.ttk.rst:1431 msgid "" "If \"from\" is used as the value of *etype*, :meth:`element_create` will " @@ -2072,6 +2270,12 @@ msgid "" "used. *kw* is discarded." msgstr "" +#: ../../library/tkinter.ttk.rst:1440 +msgid "" +"style = ttk.Style(root)\n" +"style.element_create('plain.background', 'from', 'default')" +msgstr "" + #: ../../library/tkinter.ttk.rst:1443 msgid "" "If \"vsapi\" is used as the value of *etype*, :meth:`element_create` will " @@ -2118,6 +2322,22 @@ msgstr "" msgid "Specifies the height of the element. See the comments for *width*." msgstr "" +#: ../../library/tkinter.ttk.rst:1485 +msgid "" +"style = ttk.Style(root)\n" +"style.element_create('pin', 'vsapi', 'EXPLORERBAR', 3, [\n" +" ('pressed', '!selected', 3),\n" +" ('active', '!selected', 2),\n" +" ('pressed', 'selected', 6),\n" +" ('active', 'selected', 5),\n" +" ('selected', 4),\n" +" ('', 1)])\n" +"style.layout('Explorer.Pin',\n" +" [('Explorer.Pin.pin', {'sticky': 'news'})])\n" +"pin = ttk.Checkbutton(style='Explorer.Pin')\n" +"pin.pack(expand=True, fill='both')" +msgstr "" + #: ../../library/tkinter.ttk.rst:1498 msgid "Added support of the \"vsapi\" element factory." msgstr "" @@ -2161,6 +2381,32 @@ msgstr "" msgid "As an example, let's change the Combobox for the default theme a bit::" msgstr "" +#: ../../library/tkinter.ttk.rst:1534 +msgid "" +"from tkinter import ttk\n" +"import tkinter\n" +"\n" +"root = tkinter.Tk()\n" +"\n" +"style = ttk.Style()\n" +"style.theme_settings(\"default\", {\n" +" \"TCombobox\": {\n" +" \"configure\": {\"padding\": 5},\n" +" \"map\": {\n" +" \"background\": [(\"active\", \"green2\"),\n" +" (\"!disabled\", \"green4\")],\n" +" \"fieldbackground\": [(\"!disabled\", \"green3\")],\n" +" \"foreground\": [(\"focus\", \"OliveDrab1\"),\n" +" (\"!disabled\", \"OliveDrab2\")]\n" +" }\n" +" }\n" +"})\n" +"\n" +"combo = ttk.Combobox().pack()\n" +"\n" +"root.mainloop()" +msgstr "" + #: ../../library/tkinter.ttk.rst:1560 msgid "Returns a list of all known themes." msgstr "" @@ -2174,7 +2420,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:1571 msgid "Layouts" -msgstr "" +msgstr "Layouts" #: ../../library/tkinter.ttk.rst:1573 msgid "" @@ -2204,7 +2450,7 @@ msgstr "" #: ../../library/tkinter.ttk.rst:1588 msgid "*unit*: 0 or 1" -msgstr "" +msgstr "*unit*: 0 ou 1" #: ../../library/tkinter.ttk.rst:1589 msgid "" @@ -2226,4 +2472,4 @@ msgstr "" #: ../../library/tkinter.ttk.rst:11 msgid "ttk" -msgstr "" +msgstr "ttk" diff --git a/library/token.po b/library/token.po index 6b100cb2d..92f56b659 100644 --- a/library/token.po +++ b/library/token.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:15+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-03-28 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -54,7 +54,18 @@ msgstr "" "algumas funções. As funções espelham definições nos arquivos de cabeçalho do " "Python C." -#: ../../library/token.rst:25 +#: ../../library/token.rst:22 +msgid "" +"Note that a token's value may depend on tokenizer options. For example, a " +"``\"+\"`` token may be reported as either :data:`PLUS` or :data:`OP`, or a " +"``\"match\"`` token may be either :data:`NAME` or :data:`SOFT_KEYWORD`." +msgstr "" +"Observe que o valor de um token pode depender das opções do tokenizador. Por " +"exemplo, um token ``\"+\"`` pode ser relatado como :data:`PLUS` ou :data:" +"`OP`, ou um token ``\"match\"`` pode ser :data:`NAME` ou :data:" +"`SOFT_KEYWORD`." + +#: ../../library/token.rst:29 msgid "" "Dictionary mapping the numeric values of the constants defined in this " "module back to name strings, allowing more human-readable representation of " @@ -64,267 +75,466 @@ msgstr "" "módulo de volta para cadeias de nomes, permitindo que seja gerada uma " "representação mais legível de árvores de análise." -#: ../../library/token.rst:32 +#: ../../library/token.rst:36 msgid "Return ``True`` for terminal token values." msgstr "Retorna ``True`` para valores de tokens terminais." -#: ../../library/token.rst:37 +#: ../../library/token.rst:41 msgid "Return ``True`` for non-terminal token values." msgstr "Retorna ``True`` para valores de tokens não terminais." -#: ../../library/token.rst:42 +#: ../../library/token.rst:46 msgid "Return ``True`` if *x* is the marker indicating the end of input." msgstr "Retorna ``True`` se *x* for o marcador que indica o final da entrada." -#: ../../library/token.rst:45 +#: ../../library/token.rst:49 msgid "The token constants are:" msgstr "Os constantes de tokens são:" -#: ../../library/token-list.inc:18 -msgid "Token value for ``\"(\"``." -msgstr "Valor de token para ``\"(\"``." +#: ../../library/token.rst:53 +msgid "" +"Token value that indicates an :ref:`identifier `. Note that " +"keywords are also initially tokenized an ``NAME`` tokens." +msgstr "" +"Valor de token que indica um :ref:`identificador `. Observe que " +"as palavras reservadas também são inicialmente tokenizadas como tokens " +"``NAME``." -#: ../../library/token-list.inc:22 -msgid "Token value for ``\")\"``." -msgstr "Valor de token para ``\")\"``." +#: ../../library/token.rst:58 +msgid "Token value that indicates a :ref:`numeric literal `" +msgstr "Valor de token que indica um :ref:`literal numérico `" -#: ../../library/token-list.inc:26 -msgid "Token value for ``\"[\"``." -msgstr "Valor de token para ``\"[\"``." +#: ../../library/token.rst:62 +msgid "" +"Token value that indicates a :ref:`string or byte literal `, " +"excluding :ref:`formatted string literals `. The token string is " +"not interpreted: it includes the surrounding quotation marks and the prefix " +"(if given); backslashes are included literally, without processing escape " +"sequences." +msgstr "" +"Valor de token que indica um :ref:`literal de string ou byte `, " +"excluindo :ref:`literais de strings formatadas `. A string de " +"token não é interpretada: ela inclui as aspas ao redor e o prefixo (se " +"fornecido); contrabarras são incluídas literalmente, sem processar " +"sequências de escape." -#: ../../library/token-list.inc:30 -msgid "Token value for ``\"]\"``." -msgstr "Valor de token para ``\"]\"``." +#: ../../library/token.rst:70 +msgid "" +"A generic token value that indicates an :ref:`operator ` or :ref:" +"`delimiter `." +msgstr "" +"Um valor de token genérico que indica um :ref:`operador ` ou :ref:" +"`delimitador `." -#: ../../library/token-list.inc:34 -msgid "Token value for ``\":\"``." -msgstr "Valor de token para ``\":\"``." +#: ../../library/token.rst:75 +msgid "" +"This value is only reported by the :mod:`tokenize` module. Internally, the " +"tokenizer uses :ref:`exact token types ` instead." +msgstr "" +"Este valor é relatado apenas pelo módulo :mod:`tokenize`. Internamente, o " +"tokenizador usa :ref:`tipos exatos de tokens ` " +"em vez disso." -#: ../../library/token-list.inc:38 -msgid "Token value for ``\",\"``." -msgstr "Valor de token para ``\",\"``." +#: ../../library/token.rst:81 +msgid "" +"Token value used to indicate a comment. The parser ignores :data:`!COMMENT` " +"tokens." +msgstr "" +"Valor de token usado para indicar um comentário. O analisador sintático " +"ignora tokens :data:`!COMMENT`." -#: ../../library/token-list.inc:42 -msgid "Token value for ``\";\"``." -msgstr "Valor de token para ``\";\"``." +#: ../../library/token.rst:86 +msgid "" +"Token value that indicates the end of a :ref:`logical line `." +msgstr "" +"Valor de token que indica o fim de uma :ref:`linha lógica `." -#: ../../library/token-list.inc:46 -msgid "Token value for ``\"+\"``." -msgstr "Valor de token para ``\"+\"``." +#: ../../library/token.rst:90 +msgid "" +"Token value used to indicate a non-terminating newline. :data:`!NL` tokens " +"are generated when a logical line of code is continued over multiple " +"physical lines. The parser ignores :data:`!NL` tokens." +msgstr "" +"Valor de token usado para indicar uma nova linha não terminante. Os tokens :" +"data:`!NL` são gerados quando uma linha lógica de código é continuada em " +"várias linhas físicas. O analisador sintático ignora os tokens :data:`!NL`." -#: ../../library/token-list.inc:50 -msgid "Token value for ``\"-\"``." -msgstr "Valor de token para ``\"-\"``." +#: ../../library/token.rst:96 +msgid "" +"Token value used at the beginning of a :ref:`logical line ` " +"to indicate the start of an :ref:`indented block `." +msgstr "" +"Valor de token usado no início de uma :ref:`linha lógica ` " +"para indicar o início de um :ref:`bloco indentado `." -#: ../../library/token-list.inc:54 -msgid "Token value for ``\"*\"``." -msgstr "Valor de token para ``\"*\"``." +#: ../../library/token.rst:101 +msgid "" +"Token value used at the beginning of a :ref:`logical line ` " +"to indicate the end of an :ref:`indented block `." +msgstr "" +"Valor de token usado no início de uma :ref:`linha lógica ` " +"para indicar o fim de um :ref:`bloco indentado `." -#: ../../library/token-list.inc:58 -msgid "Token value for ``\"/\"``." -msgstr "Valor de token para ``\"/\"``." +#: ../../library/token.rst:106 +msgid "" +"Token value used to indicate the beginning of an :ref:`f-string literal `." +msgstr "" +"Valor de token usado para indicar o início de um :ref:`literal de f-string " +"`." -#: ../../library/token-list.inc:62 -msgid "Token value for ``\"|\"``." -msgstr "Valor de token para ``\"|\"``." +#: ../../library/token.rst:111 +msgid "" +"The token string includes the prefix and the opening quote(s), but none of " +"the contents of the literal." +msgstr "" +"A string de token inclui o prefixo e as aspas iniciais, mas nenhum conteúdo " +"do literal." -#: ../../library/token-list.inc:66 -msgid "Token value for ``\"&\"``." -msgstr "Valor de token para ``\"&\"``." +#: ../../library/token.rst:116 +msgid "" +"Token value used for literal text inside an :ref:`f-string literal `, including format specifications." +msgstr "" +"Valor de token usado para texto literal dentro de um :ref:`literal de f-" +"string `, incluindo especificações de formato." -#: ../../library/token-list.inc:70 -msgid "Token value for ``\"<\"``." -msgstr "Valor de token para ``\"<\"``." +#: ../../library/token.rst:121 +msgid "" +"Replacement fields (that is, the non-literal parts of f-strings) use the " +"same tokens as other expressions, and are delimited by :data:`LBRACE`, :data:" +"`RBRACE`, :data:`EXCLAMATION` and :data:`COLON` tokens." +msgstr "" +"Campos de substituição (ou seja, as partes não literais de f-strings) usam " +"os mesmos tokens que outras expressões e são delimitados pelos tokens :data:" +"`LBRACE`, :data:`RBRACE`, :data:`EXCLAMATION` e :data:`COLON`." -#: ../../library/token-list.inc:74 -msgid "Token value for ``\">\"``." -msgstr "Valor de token para ``\">\"``." +#: ../../library/token.rst:128 +msgid "Token value used to indicate the end of a :ref:`f-string `." +msgstr "" +"Valor de token usado para indicar o fim de um :ref:`literal de f-string `." -#: ../../library/token-list.inc:78 -msgid "Token value for ``\"=\"``." -msgstr "Valor de token para ``\"=\"``." +#: ../../library/token.rst:132 +msgid "The token string contains the closing quote(s)." +msgstr "A string do token contém as aspas de fechamento." -#: ../../library/token-list.inc:82 -msgid "Token value for ``\".\"``." -msgstr "Valor de token para ``\".\"``." +#: ../../library/token.rst:136 +msgid "Token value that indicates the end of input." +msgstr "Valor de token que indica o fim da entrada." -#: ../../library/token-list.inc:86 -msgid "Token value for ``\"%\"``." -msgstr "Valor de token para ``\"%\"``." +#: ../../library/token.rst:140 +msgid "" +"Token value that indicates the encoding used to decode the source bytes into " +"text. The first token returned by :func:`tokenize.tokenize` will always be " +"an ``ENCODING`` token." +msgstr "" +"Valor de token que indica a codificação usada para decodificar os bytes de " +"origem em texto. O primeiro token retornado por :func:`tokenize.tokenize` " +"sempre será um token ``ENCODING``." -#: ../../library/token-list.inc:90 -msgid "Token value for ``\"{\"``." -msgstr "Valor de token para ``\"{\"``." +#: ../../library/token.rst:146 +msgid "" +"This token type isn't used by the C tokenizer but is needed for the :mod:" +"`tokenize` module." +msgstr "" +"Este tipo de token não é usado pelo tokenizador do C, mas é necessário para " +"o módulo :mod:`tokenize`." -#: ../../library/token-list.inc:94 -msgid "Token value for ``\"}\"``." -msgstr "Valor de token para ``\"}\"``." +#: ../../library/token.rst:150 +msgid "" +"The following token types are not produced by the :mod:`tokenize` module, " +"and are defined for special uses in the tokenizer or parser:" +msgstr "" +"Os seguintes tipos de token não são produzidos pelo módulo :mod:`tokenize` e " +"são definidos para usos especiais no tokenizador ou analisador:" -#: ../../library/token-list.inc:98 -msgid "Token value for ``\"==\"``." -msgstr "Valor de token para ``\"==\"``." +#: ../../library/token.rst:155 +msgid "" +"Token value indicating that a ``type: ignore`` comment was recognized. Such " +"tokens are produced instead of regular :data:`COMMENT` tokens only with the :" +"data:`~ast.PyCF_TYPE_COMMENTS` flag." +msgstr "" +"Valor de token indicando que um comentário ``type: ignore`` foi reconhecido. " +"Tais tokens são produzidos em vez de tokens :data:`COMMENT` regulares " +"somente com o sinalizador :data:`~ast.PyCF_TYPE_COMMENTS`." -#: ../../library/token-list.inc:102 -msgid "Token value for ``\"!=\"``." -msgstr "Valor de token para ``\"!=\"``." +#: ../../library/token.rst:161 +msgid "" +"Token value indicating that a type comment was recognized. Such tokens are " +"produced instead of regular :data:`COMMENT` tokens only with the :data:`~ast." +"PyCF_TYPE_COMMENTS` flag." +msgstr "" +"Valor de token indicando que um comentário de tipo foi reconhecido. Tais " +"tokens são produzidos em vez de tokens :data:`COMMENT` regulares somente com " +"o sinalizador :data:`~ast.PyCF_TYPE_COMMENTS`." -#: ../../library/token-list.inc:106 -msgid "Token value for ``\"<=\"``." -msgstr "Valor de token para ``\"<=\"``." +#: ../../library/token.rst:167 +msgid "Token value indicating a :ref:`soft keyword `." +msgstr "" +"Valor de token indicando uma :ref:`palavra reservada contextual `." -#: ../../library/token-list.inc:110 -msgid "Token value for ``\">=\"``." -msgstr "Valor de token para ``\">=\"``." +#: ../../library/token.rst:169 +msgid "" +"The tokenizer never produces this value. To check for a soft keyword, pass " +"a :data:`NAME` token's string to :func:`keyword.issoftkeyword`." +msgstr "" +"O tokenizador nunca produz esse valor. Para verificar uma palavra reservada " +"contextual, passe uma string do token :data:`NAME` para :func:`keyword." +"issoftkeyword`." -#: ../../library/token-list.inc:114 -msgid "Token value for ``\"~\"``." -msgstr "Valor de token para ``\"~\"``." +#: ../../library/token.rst:175 +msgid "Token value used to indicate wrong input." +msgstr "Valor de token usado para indicar uma entrada errada." -#: ../../library/token-list.inc:118 -msgid "Token value for ``\"^\"``." -msgstr "Valor de token para ``\"^\"``." +#: ../../library/token.rst:177 +msgid "" +"The :mod:`tokenize` module generally indicates errors by raising exceptions " +"instead of emitting this token. It can also emit tokens such as :data:`OP` " +"or :data:`NAME` with strings that are later rejected by the parser." +msgstr "" +"O módulo :mod:`tokenize` geralmente indica erros levantando exceções em vez " +"de emitir este token. Ele também pode emitir tokens como :data:`OP` ou :data:" +"`NAME` com strings que são rejeitadas posteriormente pelo parser." -#: ../../library/token-list.inc:122 -msgid "Token value for ``\"<<\"``." -msgstr "Valor de token para ``\"<<\"``." +#: ../../library/token.rst:185 +msgid "" +"The remaining tokens represent specific :ref:`operators ` and :" +"ref:`delimiters `. (The :mod:`tokenize` module reports these as :" +"data:`OP`; see ``exact_type`` in the :mod:`tokenize` documentation for " +"details.)" +msgstr "" +"Os tokens restantes representam :ref:`operadores ` e :ref:" +"`delimitadores ` específicos. (O módulo :mod:`tokenize` os " +"relata como :data:`OP`; consulte ``exact_type`` na documentação :mod:" +"`tokenize` para obter detalhes.)" -#: ../../library/token-list.inc:126 -msgid "Token value for ``\">>\"``." -msgstr "Valor de token para ``\">>\"``." +#: ../../library/token-list.inc:7 +msgid "Token" +msgstr "Token" -#: ../../library/token-list.inc:130 -msgid "Token value for ``\"**\"``." -msgstr "Valor de token para ``\"**\"``." +#: ../../library/token-list.inc:8 +msgid "Value" +msgstr "Valor" -#: ../../library/token-list.inc:134 -msgid "Token value for ``\"+=\"``." -msgstr "Valor de token para ``\"+=\"``." +#: ../../library/token-list.inc:10 +msgid "``\"(\"``" +msgstr "``\"(\"``" -#: ../../library/token-list.inc:138 -msgid "Token value for ``\"-=\"``." -msgstr "Valor de token para ``\"-=\"``." +#: ../../library/token-list.inc:12 +msgid "``\")\"``" +msgstr "``\")\"``" -#: ../../library/token-list.inc:142 -msgid "Token value for ``\"*=\"``." -msgstr "Valor de token para ``\"*=\"``." +#: ../../library/token-list.inc:14 +msgid "``\"[\"``" +msgstr "``\"[\"``" -#: ../../library/token-list.inc:146 -msgid "Token value for ``\"/=\"``." -msgstr "Valor de token para ``\"/=\"``." +#: ../../library/token-list.inc:16 +msgid "``\"]\"``" +msgstr "``\"]\"``" -#: ../../library/token-list.inc:150 -msgid "Token value for ``\"%=\"``." -msgstr "Valor de token para ``\"%=\"``." +#: ../../library/token-list.inc:18 +msgid "``\":\"``" +msgstr "``\":\"``" -#: ../../library/token-list.inc:154 -msgid "Token value for ``\"&=\"``." -msgstr "Valor de token para ``\"&=\"``." +#: ../../library/token-list.inc:20 +msgid "``\",\"``" +msgstr "``\",\"``" -#: ../../library/token-list.inc:158 -msgid "Token value for ``\"|=\"``." -msgstr "Valor de token para ``\"|=\"``." +#: ../../library/token-list.inc:22 +msgid "``\";\"``" +msgstr "``\";\"``" -#: ../../library/token-list.inc:162 -msgid "Token value for ``\"^=\"``." -msgstr "Valor de token para ``\"^=\"``." +#: ../../library/token-list.inc:24 +msgid "``\"+\"``" +msgstr "``\"+\"``" -#: ../../library/token-list.inc:166 -msgid "Token value for ``\"<<=\"``." -msgstr "Valor de token para ``\"<<=\"``." +#: ../../library/token-list.inc:26 +msgid "``\"-\"``" +msgstr "``\"-\"``" -#: ../../library/token-list.inc:170 -msgid "Token value for ``\">>=\"``." -msgstr "Valor de token para ``\">>=\"``." +#: ../../library/token-list.inc:28 +msgid "``\"*\"``" +msgstr "``\"*\"``" -#: ../../library/token-list.inc:174 -msgid "Token value for ``\"**=\"``." -msgstr "Valor de token para ``\"**=\"``." +#: ../../library/token-list.inc:30 +msgid "``\"/\"``" +msgstr "``\"/\"``" -#: ../../library/token-list.inc:178 -msgid "Token value for ``\"//\"``." -msgstr "Valor de token para ``\"//\"``." +#: ../../library/token-list.inc:32 +msgid "``\"|\"``" +msgstr "``\"|\"``" -#: ../../library/token-list.inc:182 -msgid "Token value for ``\"//=\"``." -msgstr "Valor de token para ``\"//=\"``." +#: ../../library/token-list.inc:34 +msgid "``\"&\"``" +msgstr "``\"&\"``" -#: ../../library/token-list.inc:186 -msgid "Token value for ``\"@\"``." -msgstr "Valor de token para ``\"@\"``." +#: ../../library/token-list.inc:36 +msgid "``\"<\"``" +msgstr "``\"<\"``" -#: ../../library/token-list.inc:190 -msgid "Token value for ``\"@=\"``." -msgstr "Valor de token para ``\"@=\"``." +#: ../../library/token-list.inc:38 +msgid "``\">\"``" +msgstr "``\">\"``" -#: ../../library/token-list.inc:194 -msgid "Token value for ``\"->\"``." -msgstr "Valor de token para ``\"->\"``." +#: ../../library/token-list.inc:40 +msgid "``\"=\"``" +msgstr "``\"=\"``" -#: ../../library/token-list.inc:198 -msgid "Token value for ``\"...\"``." -msgstr "Valor de token para ``\"...\"``." +#: ../../library/token-list.inc:42 +msgid "``\".\"``" +msgstr "``\".\"``" -#: ../../library/token-list.inc:202 -msgid "Token value for ``\":=\"``." -msgstr "Valor de token para ``\":=\"``." +#: ../../library/token-list.inc:44 +msgid "``\"%\"``" +msgstr "``\"%\"``" -#: ../../library/token-list.inc:206 -msgid "Token value for ``\"!\"``." -msgstr "Valor de token para ``\"!\"``." +#: ../../library/token-list.inc:46 +msgid "``\"{\"``" +msgstr "``\"{\"``" -#: ../../library/token.rst:49 -msgid "" -"The following token type values aren't used by the C tokenizer but are " -"needed for the :mod:`tokenize` module." -msgstr "" -"Os seguintes valores de tipo de token não são usados pelo tokenizador do C, " -"mas são necessários para o módulo :mod:`tokenize`." +#: ../../library/token-list.inc:48 +msgid "``\"}\"``" +msgstr "``\"}\"``" -#: ../../library/token.rst:55 -msgid "Token value used to indicate a comment." -msgstr "Valor de token usado para indicar um comentário." +#: ../../library/token-list.inc:50 +msgid "``\"==\"``" +msgstr "``\"==\"``" -#: ../../library/token.rst:61 -msgid "" -"Token value used to indicate a non-terminating newline. The :data:`NEWLINE` " -"token indicates the end of a logical line of Python code; ``NL`` tokens are " -"generated when a logical line of code is continued over multiple physical " -"lines." -msgstr "" -"Valor de token usado para indicar uma nova linha que não termina. O token :" -"data:`NEWLINE` indica o fim de uma linha lógica do código Python. Os tokens " -"``NL`` são gerados quando uma linha lógica de código é continuada em várias " -"linhas físicas." +#: ../../library/token-list.inc:52 +msgid "``\"!=\"``" +msgstr "``\"!=\"``" -#: ../../library/token.rst:69 -msgid "" -"Token value that indicates the encoding used to decode the source bytes into " -"text. The first token returned by :func:`tokenize.tokenize` will always be " -"an ``ENCODING`` token." -msgstr "" -"Valor de token que indica a codificação usada para decodificar os bytes de " -"origem em texto. O primeiro token retornado por :func:`tokenize.tokenize` " -"sempre será um token ``ENCODING``." +#: ../../library/token-list.inc:54 +msgid "``\"<=\"``" +msgstr "``\"<=\"``" + +#: ../../library/token-list.inc:56 +msgid "``\">=\"``" +msgstr "``\">=\"``" + +#: ../../library/token-list.inc:58 +msgid "``\"~\"``" +msgstr "``\"~\"``" + +#: ../../library/token-list.inc:60 +msgid "``\"^\"``" +msgstr "``\"^\"``" + +#: ../../library/token-list.inc:62 +msgid "``\"<<\"``" +msgstr "``\"<<\"``" + +#: ../../library/token-list.inc:64 +msgid "``\">>\"``" +msgstr "``\">>\"``" + +#: ../../library/token-list.inc:66 +msgid "``\"**\"``" +msgstr "``\"**\"``" + +#: ../../library/token-list.inc:68 +msgid "``\"+=\"``" +msgstr "``\"+=\"``" + +#: ../../library/token-list.inc:70 +msgid "``\"-=\"``" +msgstr "``\"-=\"``" + +#: ../../library/token-list.inc:72 +msgid "``\"*=\"``" +msgstr "``\"*=\"``" + +#: ../../library/token-list.inc:74 +msgid "``\"/=\"``" +msgstr "``\"/=\"``" + +#: ../../library/token-list.inc:76 +msgid "``\"%=\"``" +msgstr "``\"%=\"``" + +#: ../../library/token-list.inc:78 +msgid "``\"&=\"``" +msgstr "``\"&=\"``" + +#: ../../library/token-list.inc:80 +msgid "``\"|=\"``" +msgstr "``\"|=\"``" -#: ../../library/token.rst:77 +#: ../../library/token-list.inc:82 +msgid "``\"^=\"``" +msgstr "``\"^=\"``" + +#: ../../library/token-list.inc:84 +msgid "``\"<<=\"``" +msgstr "``\"<<=\"``" + +#: ../../library/token-list.inc:86 +msgid "``\">>=\"``" +msgstr "``\">>=\"``" + +#: ../../library/token-list.inc:88 +msgid "``\"**=\"``" +msgstr "``\"**=\"``" + +#: ../../library/token-list.inc:90 +msgid "``\"//\"``" +msgstr "``\"//\"``" + +#: ../../library/token-list.inc:92 +msgid "``\"//=\"``" +msgstr "``\"//=\"``" + +#: ../../library/token-list.inc:94 +msgid "``\"@\"``" +msgstr "``\"@\"``" + +#: ../../library/token-list.inc:96 +msgid "``\"@=\"``" +msgstr "``\"@=\"``" + +#: ../../library/token-list.inc:98 +msgid "``\"->\"``" +msgstr "``\"->\"``" + +#: ../../library/token-list.inc:100 +msgid "``\"...\"``" +msgstr "``\"...\"``" + +#: ../../library/token-list.inc:102 +msgid "``\":=\"``" +msgstr "``\":=\"``" + +#: ../../library/token-list.inc:104 +msgid "``\"!\"``" +msgstr "``\"!\"``" + +#: ../../library/token.rst:193 +msgid "The following non-token constants are provided:" +msgstr "As seguintes constantes não-tokens são fornecidas:" + +#: ../../library/token.rst:197 +msgid "The number of token types defined in this module." +msgstr "O número de tipos de token definidos neste módulo." + +#: ../../library/token.rst:204 msgid "" -"Token value indicating that a type comment was recognized. Such tokens are " -"only produced when :func:`ast.parse()` is invoked with " -"``type_comments=True``." +"A dictionary mapping the string representation of a token to its numeric " +"code." msgstr "" -"Valor do token indicando que um comentário de tipo foi reconhecido. Esses " -"tokens são produzidos apenas quando :func:`ast.parse()` é chamado com " -"``type_comments=True``." +"Um dicionário que mapeia a representação de string de um token para seu " +"código numérico." -#: ../../library/token.rst:82 +#: ../../library/token.rst:209 msgid "Added :data:`!AWAIT` and :data:`!ASYNC` tokens." msgstr "Adicionados os tokens :data:`!AWAIT` e :data:`!ASYNC`." -#: ../../library/token.rst:85 +#: ../../library/token.rst:212 msgid "Added :data:`COMMENT`, :data:`NL` and :data:`ENCODING` tokens." msgstr "Adicionados os tokens :data:`COMMENT`, :data:`NL` e :data:`ENCODING`." -#: ../../library/token.rst:88 +#: ../../library/token.rst:215 msgid "" "Removed :data:`!AWAIT` and :data:`!ASYNC` tokens. \"async\" and \"await\" " "are now tokenized as :data:`NAME` tokens." @@ -332,7 +542,7 @@ msgstr "" "Removido os tokens :data:`!AWAIT` e :data:`!ASYNC`. \"async\" e \"await\" " "são agora tokenizados como tokens :data:`NAME`." -#: ../../library/token.rst:92 +#: ../../library/token.rst:219 msgid "" "Added :data:`TYPE_COMMENT`, :data:`TYPE_IGNORE`, :data:`COLONEQUAL`. Added :" "data:`!AWAIT` and :data:`!ASYNC` tokens back (they're needed to support " @@ -344,6 +554,10 @@ msgstr "" "para dar suporte à análise de versões mais antigas do Python para :func:`ast." "parse` com ``feature_version`` definido como 6 ou inferior)." -#: ../../library/token.rst:98 +#: ../../library/token.rst:225 +msgid "Added :data:`EXCLAMATION`." +msgstr "Adicionado :data:`EXCLAMATION`." + +#: ../../library/token.rst:228 msgid "Removed :data:`!AWAIT` and :data:`!ASYNC` tokens again." msgstr "Removidos novamente os tokens :data:`!AWAIT` e :data:`!ASYNC`." diff --git a/library/tokenize.po b/library/tokenize.po index 36aa41ab6..fd6422ee1 100644 --- a/library/tokenize.po +++ b/library/tokenize.po @@ -1,34 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 01:16+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-24 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/tokenize.rst:2 msgid ":mod:`!tokenize` --- Tokenizer for Python source" -msgstr "" +msgstr ":mod:`!tokenize` --- Tokenizador para código-fonte Python" #: ../../library/tokenize.rst:10 msgid "**Source code:** :source:`Lib/tokenize.py`" @@ -41,6 +38,10 @@ msgid "" "tokens as well, making it useful for implementing \"pretty-printers\", " "including colorizers for on-screen displays." msgstr "" +"O módulo :mod:`tokenize` fornece um scanner léxico para código-fonte Python, " +"implementado em Python. O scanner neste módulo retorna comentários como " +"tokens também, tornando-o útil para implementar \"pretty-printers\", " +"incluindo colorizadores para exibições na tela." #: ../../library/tokenize.rst:19 msgid "" @@ -50,6 +51,11 @@ msgid "" "checking the ``exact_type`` property on the :term:`named tuple` returned " "from :func:`tokenize.tokenize`." msgstr "" +"Para simplificar o tratamento do fluxo de tokens, todos os tokens :ref:" +"`operadores ` e :ref:`delimitadores ` e :data:" +"`Ellipsis` são retornados usando o tipo de token genérico :data:`~token.OP`. " +"O tipo exato pode ser determinado verificando a propriedade ``exact_type`` " +"na :term:`tupla nomeada` retornada de :func:`tokenize.tokenize`." #: ../../library/tokenize.rst:28 msgid "" @@ -59,6 +65,11 @@ msgid "" "**undefined** when providing invalid Python code and it can change at any " "point." msgstr "" +"Observe que as funções neste módulo são projetadas apenas para analisar " +"código Python sintaticamente válido (código que não levanta exceção quando " +"analisado usando :func:`ast.parse`). O comportamento das funções neste " +"módulo é **indefinido** ao fornecer código Python inválido e pode mudar a " +"qualquer momento." #: ../../library/tokenize.rst:35 msgid "Tokenizing Input" @@ -66,7 +77,7 @@ msgstr "Tokenizando entradas" #: ../../library/tokenize.rst:37 msgid "The primary entry point is a :term:`generator`:" -msgstr "" +msgstr "O ponto de entrada principal é um :term:`gerador`:" #: ../../library/tokenize.rst:41 msgid "" @@ -75,6 +86,10 @@ msgid "" "IOBase.readline` method of file objects. Each call to the function should " "return one line of input as bytes." msgstr "" +"O gerador :func:`.tokenize` requer um argumento, *readline*, que deve ser um " +"objeto chamável que fornece a mesma interface que o método :meth:`io.IOBase." +"readline` de objetos arquivo. Cada chamada para a função deve retornar uma " +"linha de entrada como bytes." #: ../../library/tokenize.rst:46 msgid "" @@ -86,6 +101,14 @@ msgid "" "is the *physical* line. The 5 tuple is returned as a :term:`named tuple` " "with the field names: ``type string start end line``." msgstr "" +"O gerador produz tuplas de 5 elementos com estes membros: o tipo de token; a " +"string de token; uma tupla de 2 elementos ``(srow, scol)`` de ints " +"especificando a linha e a coluna onde o token começa na fonte; uma tupla de " +"2 elementos ``(erow, ecol)`` de ints especificando a linha e a coluna onde o " +"token termina na fonte; e a linha na qual o token foi encontrado. A linha " +"passada (o último item da tupla) é a linha *física*. A tupla 5 elementos é " +"retornada como uma :term:`tupla nomeada` com os nomes dos campos: ``tipo " +"string início fim linha``." #: ../../library/tokenize.rst:55 msgid "" @@ -94,6 +117,10 @@ msgid "" "tokens. For all other token types ``exact_type`` equals the named tuple " "``type`` field." msgstr "" +"A :term:`tupla nomeada` retornada tem uma propriedade adicional chamada " +"``exact_type`` que contém o tipo exato do operador para tokens :data:`~token." +"OP`. Para todos os outros tipos de token, ``exact_type`` é igual ao campo " +"``type`` da tupla nomeada." #: ../../library/tokenize.rst:60 msgid "Added support for named tuples." @@ -101,17 +128,19 @@ msgstr "Adiciona suporte para tuplas nomeadas." #: ../../library/tokenize.rst:63 msgid "Added support for ``exact_type``." -msgstr "" +msgstr "Adicionado suporte para ``exact_type``." #: ../../library/tokenize.rst:66 msgid "" ":func:`.tokenize` determines the source encoding of the file by looking for " "a UTF-8 BOM or encoding cookie, according to :pep:`263`." msgstr "" +":func:`.tokenize` determina a codificação de origem do arquivo procurando " +"por um BOM UTF-8 ou cookie de codificação, de acordo com :pep:`263`." #: ../../library/tokenize.rst:71 msgid "Tokenize a source reading unicode strings instead of bytes." -msgstr "" +msgstr "Tokeniza uma fonte lendo strings unicode em vez de bytes." #: ../../library/tokenize.rst:73 msgid "" @@ -119,18 +148,25 @@ msgid "" "single line of input. However, :func:`generate_tokens` expects *readline* to " "return a str object rather than bytes." msgstr "" +"Assim como :func:`.tokenize`, o argumento *readline* é um chamável que " +"retorna uma única linha de entrada. No entanto, :func:`generate_tokens` " +"espera que *readline* retorne um objeto str em vez de bytes." #: ../../library/tokenize.rst:77 msgid "" "The result is an iterator yielding named tuples, exactly like :func:`." "tokenize`. It does not yield an :data:`~token.ENCODING` token." msgstr "" +"O resultado é um iterador produzindo tuplas nomeadas, exatamente como :func:" +"`.tokenize`. Ele não produz um token :data:`~token.ENCODING`." #: ../../library/tokenize.rst:80 msgid "" "All constants from the :mod:`token` module are also exported from :mod:" "`tokenize`." msgstr "" +"Todas as constantes do módulo :mod:`token` também são exportadas de :mod:" +"`tokenize`." #: ../../library/tokenize.rst:83 msgid "" @@ -138,6 +174,9 @@ msgid "" "useful for creating tools that tokenize a script, modify the token stream, " "and write back the modified script." msgstr "" +"Outra função é fornecida para reverter o processo de tokenização. Isso é " +"útil para criar ferramentas que tokenizam um script, modificam o fluxo de " +"tokens e escrevem de volta o script modificado." #: ../../library/tokenize.rst:90 msgid "" @@ -145,139 +184,422 @@ msgid "" "sequences with at least two elements, the token type and the token string. " "Any additional sequence elements are ignored." msgstr "" +"Converte tokens de volta para o código-fonte Python. O *iterable* deve " +"retornar sequências com pelo menos dois elementos, o tipo de token e a " +"string do token. Quaisquer elementos de sequência adicionais são ignorados." #: ../../library/tokenize.rst:94 msgid "" -"The reconstructed script is returned as a single string. The result is " -"guaranteed to tokenize back to match the input so that the conversion is " -"lossless and round-trips are assured. The guarantee applies only to the " -"token type and token string as the spacing between tokens (column positions) " -"may change." +"The result is guaranteed to tokenize back to match the input so that the " +"conversion is lossless and round-trips are assured. The guarantee applies " +"only to the token type and token string as the spacing between tokens " +"(column positions) may change." msgstr "" +"O resultado é garantido para tokenizar de volta para corresponder à entrada, " +"de modo que a conversão seja sem perdas e as viagens de ida e volta sejam " +"garantidas. A garantia se aplica somente ao tipo de token e à sequência de " +"tokens, pois o espaçamento entre os tokens (posições de coluna) pode mudar." -#: ../../library/tokenize.rst:100 +#: ../../library/tokenize.rst:99 msgid "" "It returns bytes, encoded using the :data:`~token.ENCODING` token, which is " "the first token sequence output by :func:`.tokenize`. If there is no " "encoding token in the input, it returns a str instead." msgstr "" +"Retorna bytes, codificados usando o token :data:`~token.ENCODING`, que é a " +"primeira sequência de tokens gerada por :func:`.tokenize`. Se não houver " +"nenhum token de codificação na entrada, ele retorna um str em vez disso." -#: ../../library/tokenize.rst:105 +#: ../../library/tokenize.rst:104 msgid "" ":func:`.tokenize` needs to detect the encoding of source files it tokenizes. " "The function it uses to do this is available:" msgstr "" +":func:`.tokenize` precisa detectar a codificação dos arquivos fonte que ele " +"tokeniza. A função que ele usa para fazer isso está disponível:" -#: ../../library/tokenize.rst:110 +#: ../../library/tokenize.rst:109 msgid "" "The :func:`detect_encoding` function is used to detect the encoding that " "should be used to decode a Python source file. It requires one argument, " "readline, in the same way as the :func:`.tokenize` generator." msgstr "" +"A função :func:`detect_encoding` é usada para detectar a codificação que " +"deve ser usada para decodificar um arquivo de origem Python. Ela requer um " +"argumento, readline, da mesma forma que o gerador :func:`.tokenize`." -#: ../../library/tokenize.rst:114 +#: ../../library/tokenize.rst:113 msgid "" "It will call readline a maximum of twice, and return the encoding used (as a " "string) and a list of any lines (not decoded from bytes) it has read in." msgstr "" +"Ele chamará readline no máximo duas vezes e retornará a codificação usada " +"(como uma string) e uma lista de todas as linhas (não decodificadas de " +"bytes) que ele leu." -#: ../../library/tokenize.rst:118 +#: ../../library/tokenize.rst:117 msgid "" "It detects the encoding from the presence of a UTF-8 BOM or an encoding " "cookie as specified in :pep:`263`. If both a BOM and a cookie are present, " "but disagree, a :exc:`SyntaxError` will be raised. Note that if the BOM is " "found, ``'utf-8-sig'`` will be returned as an encoding." msgstr "" +"Ele detecta a codificação a partir da presença de um BOM UTF-8 ou um cookie " +"de codificação conforme especificado em :pep:`263`. Se um BOM e um cookie " +"estiverem presentes, mas discordarem, uma exceção :exc:`SyntaxError` será " +"levantada. Observe que se o BOM for encontrado, ``'utf-8-sig'`` será " +"retornado como uma codificação." -#: ../../library/tokenize.rst:123 +#: ../../library/tokenize.rst:122 msgid "" "If no encoding is specified, then the default of ``'utf-8'`` will be " "returned." msgstr "" +"Se nenhuma codificação for especificada, o padrão ``'utf-8'`` será retornado." -#: ../../library/tokenize.rst:126 +#: ../../library/tokenize.rst:125 msgid "" "Use :func:`.open` to open Python source files: it uses :func:" "`detect_encoding` to detect the file encoding." msgstr "" +"Use :func:`.open` para abrir arquivos de código-fonte Python: ele usa :func:" +"`detect_encoding` para detectar a codificação do arquivo." -#: ../../library/tokenize.rst:132 +#: ../../library/tokenize.rst:131 msgid "" "Open a file in read only mode using the encoding detected by :func:" "`detect_encoding`." msgstr "" +"Abre um arquivo no modo somente leitura usando a codificação detectada por :" +"func:`detect_encoding`." -#: ../../library/tokenize.rst:139 +#: ../../library/tokenize.rst:138 msgid "" "Raised when either a docstring or expression that may be split over several " "lines is not completed anywhere in the file, for example::" msgstr "" +"Levantada quando uma docstring ou expressão que pode ser dividida em várias " +"linhas não é concluída em nenhum lugar do arquivo, por exemplo:" -#: ../../library/tokenize.rst:145 +#: ../../library/tokenize.rst:141 +msgid "" +"\"\"\"Beginning of\n" +"docstring" +msgstr "" +"\"\"\"Início da\n" +"docstring" + +#: ../../library/tokenize.rst:144 msgid "or::" msgstr "ou::" -#: ../../library/tokenize.rst:154 +#: ../../library/tokenize.rst:146 +msgid "" +"[1,\n" +" 2,\n" +" 3" +msgstr "" +"[1,\n" +" 2,\n" +" 3" + +#: ../../library/tokenize.rst:153 msgid "Command-Line Usage" -msgstr "Uso da linha de comando" +msgstr "Uso na linha de comando" -#: ../../library/tokenize.rst:158 +#: ../../library/tokenize.rst:157 msgid "" "The :mod:`tokenize` module can be executed as a script from the command " "line. It is as simple as:" msgstr "" +"O módulo :mod:`tokenize` pode ser executado como um script a partir da linha " +"de comando. É tão simples quanto:" -#: ../../library/tokenize.rst:165 +#: ../../library/tokenize.rst:160 +msgid "python -m tokenize [-e] [filename.py]" +msgstr "python -m tokenize [-e] [nome-do-arquivo.py]" + +#: ../../library/tokenize.rst:164 msgid "The following options are accepted:" msgstr "As seguintes opções são aceitas:" -#: ../../library/tokenize.rst:171 +#: ../../library/tokenize.rst:170 msgid "show this help message and exit" -msgstr "" +msgstr "mostra esta mensagem de ajuda e sai" -#: ../../library/tokenize.rst:175 +#: ../../library/tokenize.rst:174 msgid "display token names using the exact type" -msgstr "" +msgstr "exibe nomes de tokens usando o tipo exato" -#: ../../library/tokenize.rst:177 +#: ../../library/tokenize.rst:176 msgid "" "If :file:`filename.py` is specified its contents are tokenized to stdout. " "Otherwise, tokenization is performed on stdin." msgstr "" +"Se :file:`nome-de-arquivo.py` for especificado, seu conteúdo será tokenizado " +"para stdout. Caso contrário, a tokenização será realizada em stdin." -#: ../../library/tokenize.rst:181 +#: ../../library/tokenize.rst:180 msgid "Examples" msgstr "Exemplos" -#: ../../library/tokenize.rst:183 +#: ../../library/tokenize.rst:182 msgid "" "Example of a script rewriter that transforms float literals into Decimal " "objects::" msgstr "" +"Exemplo de um reescritor de script que transforma literais float em objetos " +"Decimal::" -#: ../../library/tokenize.rst:225 +#: ../../library/tokenize.rst:185 +msgid "" +"from tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP\n" +"from io import BytesIO\n" +"\n" +"def decistmt(s):\n" +" \"\"\"Substitute Decimals for floats in a string of statements.\n" +"\n" +" >>> from decimal import Decimal\n" +" >>> s = 'print(+21.3e-5*-.1234/81.7)'\n" +" >>> decistmt(s)\n" +" \"print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))\"\n" +"\n" +" The format of the exponent is inherited from the platform C library.\n" +" Known cases are \"e-007\" (Windows) and \"e-07\" (not Windows). Since\n" +" we're only showing 12 digits, and the 13th isn't close to 5, the\n" +" rest of the output should be platform-independent.\n" +"\n" +" >>> exec(s) #doctest: +ELLIPSIS\n" +" -3.21716034272e-0...7\n" +"\n" +" Output from calculations with Decimal should be identical across all\n" +" platforms.\n" +"\n" +" >>> exec(decistmt(s))\n" +" -3.217160342717258261933904529E-7\n" +" \"\"\"\n" +" result = []\n" +" g = tokenize(BytesIO(s.encode('utf-8')).readline) # tokenize the " +"string\n" +" for toknum, tokval, _, _, _ in g:\n" +" if toknum == NUMBER and '.' in tokval: # replace NUMBER tokens\n" +" result.extend([\n" +" (NAME, 'Decimal'),\n" +" (OP, '('),\n" +" (STRING, repr(tokval)),\n" +" (OP, ')')\n" +" ])\n" +" else:\n" +" result.append((toknum, tokval))\n" +" return untokenize(result).decode('utf-8')" +msgstr "" +"from tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP\n" +"from io import BytesIO\n" +"\n" +"def decistmt(s):\n" +" \"\"\"Substitui Decimals por floats em uma string de instruções.\n" +"\n" +" >>> from decimal import Decimal\n" +" >>> s = 'print(+21.3e-5*-.1234/81.7)'\n" +" >>> decistmt(s)\n" +" \"print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))\"\n" +"\n" +" O formato do expoente é herdado da biblioteca da plataforma C. Casos\n" +" conhecidos são \"e-007\" (Windows) e \"e-07\" (não Windows). Como " +"estamos\n" +" mostrando apenas 12 dígitos, e o 13º não está próximo de 5, o restante\n" +" da saída deve ser independente da plataforma.\n" +"\n" +" >>> exec(s) #doctest: +ELLIPSIS\n" +" -3.21716034272e-0...7\n" +"\n" +" A saída dos cálculos com Decimal deve ser idêntica em todas as\n" +" plataformas.\n" +"\n" +" >>> exec(decistmt(s))\n" +" -3.217160342717258261933904529E-7\n" +" \"\"\"\n" +" result = []\n" +" g = tokenize(BytesIO(s.encode('utf-8')).readline) # tokenize the " +"string\n" +" for toknum, tokval, _, _, _ in g:\n" +" if toknum == NUMBER and '.' in tokval: # replace NUMBER tokens\n" +" result.extend([\n" +" (NAME, 'Decimal'),\n" +" (OP, '('),\n" +" (STRING, repr(tokval)),\n" +" (OP, ')')\n" +" ])\n" +" else:\n" +" result.append((toknum, tokval))\n" +" return untokenize(result).decode('utf-8')" + +#: ../../library/tokenize.rst:224 msgid "Example of tokenizing from the command line. The script::" +msgstr "Exemplo de tokenização a partir da linha de comando. O script::" + +#: ../../library/tokenize.rst:226 +msgid "" +"def say_hello():\n" +" print(\"Hello, World!\")\n" +"\n" +"say_hello()" msgstr "" +"def say_hello():\n" +" print(\"Hello, World!\")\n" +"\n" +"say_hello()" -#: ../../library/tokenize.rst:232 +#: ../../library/tokenize.rst:231 msgid "" "will be tokenized to the following output where the first column is the " "range of the line/column coordinates where the token is found, the second " "column is the name of the token, and the final column is the value of the " "token (if any)" msgstr "" +"será tokenizado para a seguinte saída, onde a primeira coluna é o intervalo " +"das coordenadas da linha/coluna onde o token é encontrado, a segunda coluna " +"é o nome do token e a coluna final é o valor do token (se houver)" -#: ../../library/tokenize.rst:260 +#: ../../library/tokenize.rst:235 +msgid "" +"$ python -m tokenize hello.py\n" +"0,0-0,0: ENCODING 'utf-8'\n" +"1,0-1,3: NAME 'def'\n" +"1,4-1,13: NAME 'say_hello'\n" +"1,13-1,14: OP '('\n" +"1,14-1,15: OP ')'\n" +"1,15-1,16: OP ':'\n" +"1,16-1,17: NEWLINE '\\n'\n" +"2,0-2,4: INDENT ' '\n" +"2,4-2,9: NAME 'print'\n" +"2,9-2,10: OP '('\n" +"2,10-2,25: STRING '\"Hello, World!\"'\n" +"2,25-2,26: OP ')'\n" +"2,26-2,27: NEWLINE '\\n'\n" +"3,0-3,1: NL '\\n'\n" +"4,0-4,0: DEDENT ''\n" +"4,0-4,9: NAME 'say_hello'\n" +"4,9-4,10: OP '('\n" +"4,10-4,11: OP ')'\n" +"4,11-4,12: NEWLINE '\\n'\n" +"5,0-5,0: ENDMARKER ''" +msgstr "" +"$ python -m tokenize hello.py\n" +"0,0-0,0: ENCODING 'utf-8'\n" +"1,0-1,3: NAME 'def'\n" +"1,4-1,13: NAME 'say_hello'\n" +"1,13-1,14: OP '('\n" +"1,14-1,15: OP ')'\n" +"1,15-1,16: OP ':'\n" +"1,16-1,17: NEWLINE '\\n'\n" +"2,0-2,4: INDENT ' '\n" +"2,4-2,9: NAME 'print'\n" +"2,9-2,10: OP '('\n" +"2,10-2,25: STRING '\"Hello, World!\"'\n" +"2,25-2,26: OP ')'\n" +"2,26-2,27: NEWLINE '\\n'\n" +"3,0-3,1: NL '\\n'\n" +"4,0-4,0: DEDENT ''\n" +"4,0-4,9: NAME 'say_hello'\n" +"4,9-4,10: OP '('\n" +"4,10-4,11: OP ')'\n" +"4,11-4,12: NEWLINE '\\n'\n" +"5,0-5,0: ENDMARKER ''" + +#: ../../library/tokenize.rst:259 msgid "" "The exact token type names can be displayed using the :option:`-e` option:" msgstr "" +"Os nomes exatos dos tipos de token podem ser exibidos usando a opção :option:" +"`-e`:" -#: ../../library/tokenize.rst:286 +#: ../../library/tokenize.rst:261 +msgid "" +"$ python -m tokenize -e hello.py\n" +"0,0-0,0: ENCODING 'utf-8'\n" +"1,0-1,3: NAME 'def'\n" +"1,4-1,13: NAME 'say_hello'\n" +"1,13-1,14: LPAR '('\n" +"1,14-1,15: RPAR ')'\n" +"1,15-1,16: COLON ':'\n" +"1,16-1,17: NEWLINE '\\n'\n" +"2,0-2,4: INDENT ' '\n" +"2,4-2,9: NAME 'print'\n" +"2,9-2,10: LPAR '('\n" +"2,10-2,25: STRING '\"Hello, World!\"'\n" +"2,25-2,26: RPAR ')'\n" +"2,26-2,27: NEWLINE '\\n'\n" +"3,0-3,1: NL '\\n'\n" +"4,0-4,0: DEDENT ''\n" +"4,0-4,9: NAME 'say_hello'\n" +"4,9-4,10: LPAR '('\n" +"4,10-4,11: RPAR ')'\n" +"4,11-4,12: NEWLINE '\\n'\n" +"5,0-5,0: ENDMARKER ''" +msgstr "" +"$ python -m tokenize -e hello.py\n" +"0,0-0,0: ENCODING 'utf-8'\n" +"1,0-1,3: NAME 'def'\n" +"1,4-1,13: NAME 'say_hello'\n" +"1,13-1,14: LPAR '('\n" +"1,14-1,15: RPAR ')'\n" +"1,15-1,16: COLON ':'\n" +"1,16-1,17: NEWLINE '\\n'\n" +"2,0-2,4: INDENT ' '\n" +"2,4-2,9: NAME 'print'\n" +"2,9-2,10: LPAR '('\n" +"2,10-2,25: STRING '\"Hello, World!\"'\n" +"2,25-2,26: RPAR ')'\n" +"2,26-2,27: NEWLINE '\\n'\n" +"3,0-3,1: NL '\\n'\n" +"4,0-4,0: DEDENT ''\n" +"4,0-4,9: NAME 'say_hello'\n" +"4,9-4,10: LPAR '('\n" +"4,10-4,11: RPAR ')'\n" +"4,11-4,12: NEWLINE '\\n'\n" +"5,0-5,0: ENDMARKER ''" + +#: ../../library/tokenize.rst:285 msgid "" "Example of tokenizing a file programmatically, reading unicode strings " "instead of bytes with :func:`generate_tokens`::" msgstr "" +"Exemplo de tokenização de um arquivo programaticamente, lendo strings " +"unicode em vez de bytes com :func:`generate_tokens`::" -#: ../../library/tokenize.rst:296 +#: ../../library/tokenize.rst:288 +msgid "" +"import tokenize\n" +"\n" +"with tokenize.open('hello.py') as f:\n" +" tokens = tokenize.generate_tokens(f.readline)\n" +" for token in tokens:\n" +" print(token)" +msgstr "" +"import tokenize\n" +"\n" +"with tokenize.open('hello.py') as f:\n" +" tokens = tokenize.generate_tokens(f.readline)\n" +" for token in tokens:\n" +" print(token)" + +#: ../../library/tokenize.rst:295 msgid "Or reading bytes directly with :func:`.tokenize`::" -msgstr "" +msgstr "Ou lendo bytes diretamente com :func:`.tokenize`::" + +#: ../../library/tokenize.rst:297 +msgid "" +"import tokenize\n" +"\n" +"with open('hello.py', 'rb') as f:\n" +" tokens = tokenize.tokenize(f.readline)\n" +" for token in tokens:\n" +" print(token)" +msgstr "" +"import tokenize\n" +"\n" +"with open('hello.py', 'rb') as f:\n" +" tokens = tokenize.tokenize(f.readline)\n" +" for token in tokens:\n" +" print(token)" diff --git a/library/tomllib.po b/library/tomllib.po index 211ae326b..dd0975d4d 100644 --- a/library/tomllib.po +++ b/library/tomllib.po @@ -1,33 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2022 -# Hildeberto Abreu Magalhães , 2022 -# Ricardo Cappellano , 2022 -# Augusta Carla Klug , 2022 -# felipe caridade fernandes , 2022 -# Marco Rougeth , 2022 -# Claudio Rogerio Carvalho Filho , 2022 -# i17obot , 2022 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2022-11-05 19:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -41,13 +33,13 @@ msgstr "**Código-fonte:** :source:`Lib/tomllib`" #: ../../library/tomllib.rst:16 msgid "" -"This module provides an interface for parsing TOML (Tom's Obvious Minimal " -"Language, `https://toml.io `_). This module does not " -"support writing TOML." +"This module provides an interface for parsing TOML 1.0.0 (Tom's Obvious " +"Minimal Language, `https://toml.io `_). This module " +"does not support writing TOML." msgstr "" -"Este módulo fornece uma interface para analisar TOML (Tom's Obvious Minimal " -"Language, `https://toml.io `_). Este módulo não oferece " -"suporte para escrever TOML." +"Este módulo fornece uma interface para analisar TOML 1.0.0 (Tom's Obvious " +"Minimal Language, `https://toml.io `_). Este módulo não " +"oferece suporte para escrever TOML." #: ../../library/tomllib.rst:22 msgid "" @@ -131,10 +123,42 @@ msgstr "Exemplos" msgid "Parsing a TOML file::" msgstr "Analisando um arquivo TOML::" +#: ../../library/tomllib.rst:73 +msgid "" +"import tomllib\n" +"\n" +"with open(\"pyproject.toml\", \"rb\") as f:\n" +" data = tomllib.load(f)" +msgstr "" +"import tomllib\n" +"\n" +"with open(\"pyproject.toml\", \"rb\") as f:\n" +" data = tomllib.load(f)" + #: ../../library/tomllib.rst:78 msgid "Parsing a TOML string::" msgstr "Analisando uma string TOML::" +#: ../../library/tomllib.rst:80 +msgid "" +"import tomllib\n" +"\n" +"toml_str = \"\"\"\n" +"python-version = \"3.11.0\"\n" +"python-implementation = \"CPython\"\n" +"\"\"\"\n" +"\n" +"data = tomllib.loads(toml_str)" +msgstr "" +"import tomllib\n" +"\n" +"toml_str = \"\"\"\n" +"python-version = \"3.11.0\"\n" +"python-implementation = \"CPython\"\n" +"\"\"\"\n" +"\n" +"data = tomllib.loads(toml_str)" + #: ../../library/tomllib.rst:91 msgid "Conversion Table" msgstr "Tabela de conversão" diff --git a/library/trace.po b/library/trace.po index 50008d94e..2dd969664 100644 --- a/library/trace.po +++ b/library/trace.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:16+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -60,7 +58,7 @@ msgstr "" #: ../../library/trace.rst:25 msgid "Command-Line Usage" -msgstr "Uso da linha de comando" +msgstr "Uso na linha de comando" #: ../../library/trace.rst:27 msgid "" @@ -70,6 +68,10 @@ msgstr "" "O módulo :mod:`trace` pode ser chamado a partir da linha de comando. Pode " "ser tão simples quanto::" +#: ../../library/trace.rst:30 +msgid "python -m trace --count -C . somefile.py ..." +msgstr "python -m trace --count -C . algumarquivo.py ..." + #: ../../library/trace.rst:32 msgid "" "The above will execute :file:`somefile.py` and generate annotated listings " @@ -334,3 +336,39 @@ msgstr "Adicionado o parâmetro *ignore_missing_files*." #: ../../library/trace.rst:206 msgid "A simple example demonstrating the use of the programmatic interface::" msgstr "Um exemplo simples que demonstra o uso da interface programática::" + +#: ../../library/trace.rst:208 +msgid "" +"import sys\n" +"import trace\n" +"\n" +"# create a Trace object, telling it what to ignore, and whether to\n" +"# do tracing or line-counting or both.\n" +"tracer = trace.Trace(\n" +" ignoredirs=[sys.prefix, sys.exec_prefix],\n" +" trace=0,\n" +" count=1)\n" +"\n" +"# run the new command using the given tracer\n" +"tracer.run('main()')\n" +"\n" +"# make a report, placing output in the current directory\n" +"r = tracer.results()\n" +"r.write_results(show_missing=True, coverdir=\".\")" +msgstr "" +"import sys\n" +"import trace\n" +"\n" +"# cria um objeto Trace, dizendo a ele o que ignorar e se deve\n" +"# fazer rastreamento ou contagem de linhas ou ambos.\n" +"tracer = trace.Trace(\n" +" ignoredirs=[sys.prefix, sys.exec_prefix],\n" +" trace=0,\n" +" count=1)\n" +"\n" +"# executa o novo comando usando o rastreador fornecido\n" +"tracer.run('main()')\n" +"\n" +"# faz um relatório, colocando a saída no diretório atual\n" +"r = tracer.results()\n" +"r.write_results(show_missing=True, coverdir=\".\")" diff --git a/library/traceback.po b/library/traceback.po index c4a278454..a28bda67b 100644 --- a/library/traceback.po +++ b/library/traceback.po @@ -1,33 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 -# Claudio Rogerio Carvalho Filho , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:16+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-03-07 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/traceback.rst:2 msgid ":mod:`!traceback` --- Print or retrieve a stack traceback" -msgstr "" +msgstr ":mod:`!traceback` --- Imprime ou recupera um traceback da pilha" #: ../../library/traceback.rst:7 msgid "**Source code:** :source:`Lib/traceback.py`" @@ -36,13 +34,16 @@ msgstr "**Código-fonte:** :source:`Lib/traceback.py`" #: ../../library/traceback.rst:11 msgid "" "This module provides a standard interface to extract, format and print stack " -"traces of Python programs. It exactly mimics the behavior of the Python " -"interpreter when it prints a stack trace. This is useful when you want to " -"print stack traces under program control, such as in a \"wrapper\" around " -"the interpreter." +"traces of Python programs. It is more flexible than the interpreter's " +"default traceback display, and therefore makes it possible to configure " +"certain aspects of the output. Finally, it contains a utility for capturing " +"enough information about an exception to print it later, without the need to " +"save a reference to the actual exception. Since exceptions can be the roots " +"of large objects graph, this utility can significantly improve memory " +"management." msgstr "" -#: ../../library/traceback.rst:19 +#: ../../library/traceback.rst:23 msgid "" "The module uses :ref:`traceback objects ` --- these are " "objects of type :class:`types.TracebackType`, which are assigned to the :" @@ -50,11 +51,11 @@ msgid "" "instances." msgstr "" -#: ../../library/traceback.rst:26 +#: ../../library/traceback.rst:30 msgid "Module :mod:`faulthandler`" msgstr "Módulo :mod:`faulthandler`" -#: ../../library/traceback.rst:27 +#: ../../library/traceback.rst:31 msgid "" "Used to dump Python tracebacks explicitly, on a fault, after a timeout, or " "on a user signal." @@ -62,19 +63,38 @@ msgstr "" "Usado para despejar tracebacks (situação da pilha de execução) do Python " "explicitamente, em uma falha, após um tempo limite ou em um sinal do usuário." -#: ../../library/traceback.rst:29 +#: ../../library/traceback.rst:33 msgid "Module :mod:`pdb`" msgstr "" -#: ../../library/traceback.rst:30 +#: ../../library/traceback.rst:34 msgid "Interactive source code debugger for Python programs." msgstr "" -#: ../../library/traceback.rst:32 -msgid "The module defines the following functions:" -msgstr "O módulo define as seguintes funções:" - #: ../../library/traceback.rst:36 +msgid "The module's API can be divided into two parts:" +msgstr "" + +#: ../../library/traceback.rst:38 +msgid "" +"Module-level functions offering basic functionality, which are useful for " +"interactive inspection of exceptions and tracebacks." +msgstr "" + +#: ../../library/traceback.rst:41 +msgid "" +":class:`TracebackException` class and its helper classes :class:" +"`StackSummary` and :class:`FrameSummary`. These offer both more flexibility " +"in the output generated and the ability to store the information necessary " +"for later formatting without holding references to actual exception and " +"traceback objects." +msgstr "" + +#: ../../library/traceback.rst:49 +msgid "Module-Level Functions" +msgstr "Funções de nível de módulo" + +#: ../../library/traceback.rst:53 msgid "" "Print up to *limit* stack trace entries from :ref:`traceback object " "` *tb* (starting from the caller's frame) if *limit* is " @@ -85,42 +105,50 @@ msgid "" "output." msgstr "" -#: ../../library/traceback.rst:45 ../../library/traceback.rst:110 +#: ../../library/traceback.rst:64 +msgid "" +"The meaning of the *limit* parameter is different than the meaning of :const:" +"`sys.tracebacklimit`. A negative *limit* value corresponds to a positive " +"value of :const:`!sys.tracebacklimit`, whereas the behaviour of a positive " +"*limit* value cannot be achieved with :const:`!sys.tracebacklimit`." +msgstr "" + +#: ../../library/traceback.rst:70 ../../library/traceback.rst:135 msgid "Added negative *limit* support." msgstr "" -#: ../../library/traceback.rst:52 +#: ../../library/traceback.rst:77 msgid "" "Print exception information and stack trace entries from :ref:`traceback " "object ` *tb* to *file*. This differs from :func:" "`print_tb` in the following ways:" msgstr "" -#: ../../library/traceback.rst:57 +#: ../../library/traceback.rst:82 msgid "" "if *tb* is not ``None``, it prints a header ``Traceback (most recent call " "last):``" msgstr "" -#: ../../library/traceback.rst:60 +#: ../../library/traceback.rst:85 msgid "it prints the exception type and *value* after the stack trace" msgstr "" -#: ../../library/traceback.rst:64 +#: ../../library/traceback.rst:89 msgid "" "if *type(value)* is :exc:`SyntaxError` and *value* has the appropriate " "format, it prints the line where the syntax error occurred with a caret " "indicating the approximate position of the error." msgstr "" -#: ../../library/traceback.rst:68 +#: ../../library/traceback.rst:93 msgid "" "Since Python 3.10, instead of passing *value* and *tb*, an exception object " "can be passed as the first argument. If *value* and *tb* are provided, the " "first argument is ignored in order to provide backwards compatibility." msgstr "" -#: ../../library/traceback.rst:72 +#: ../../library/traceback.rst:97 msgid "" "The optional *limit* argument has the same meaning as for :func:`print_tb`. " "If *chain* is true (the default), then chained exceptions (the :attr:" @@ -129,29 +157,29 @@ msgid "" "when printing an unhandled exception." msgstr "" -#: ../../library/traceback.rst:79 ../../library/traceback.rst:183 +#: ../../library/traceback.rst:104 ../../library/traceback.rst:215 msgid "The *etype* argument is ignored and inferred from the type of *value*." msgstr "" -#: ../../library/traceback.rst:82 ../../library/traceback.rst:163 +#: ../../library/traceback.rst:107 ../../library/traceback.rst:195 msgid "" "The *etype* parameter has been renamed to *exc* and is now positional-only." msgstr "" -#: ../../library/traceback.rst:89 +#: ../../library/traceback.rst:114 msgid "" -"This is a shorthand for ``print_exception(sys.exception(), limit, file, " -"chain)``." +"This is a shorthand for ``print_exception(sys.exception(), limit=limit, " +"file=file, chain=chain)``." msgstr "" -#: ../../library/traceback.rst:95 +#: ../../library/traceback.rst:120 msgid "" -"This is a shorthand for ``print_exception(sys.last_exc, limit, file, " -"chain)``. In general it will work only after an exception has reached an " -"interactive prompt (see :data:`sys.last_exc`)." +"This is a shorthand for ``print_exception(sys.last_exc, limit=limit, " +"file=file, chain=chain)``. In general it will work only after an exception " +"has reached an interactive prompt (see :data:`sys.last_exc`)." msgstr "" -#: ../../library/traceback.rst:102 +#: ../../library/traceback.rst:127 msgid "" "Print up to *limit* stack trace entries (starting from the invocation point) " "if *limit* is positive. Otherwise, print the last ``abs(limit)`` entries. " @@ -161,7 +189,7 @@ msgid "" "for :func:`print_tb`." msgstr "" -#: ../../library/traceback.rst:116 +#: ../../library/traceback.rst:141 msgid "" "Return a :class:`StackSummary` object representing a list of \"pre-" "processed\" stack trace entries extracted from the :ref:`traceback object " @@ -174,7 +202,7 @@ msgid "" "for a stack trace." msgstr "" -#: ../../library/traceback.rst:129 +#: ../../library/traceback.rst:154 msgid "" "Extract the raw traceback from the current :ref:`stack frame `. The return value has the same format as for :func:`extract_tb`. " @@ -182,7 +210,14 @@ msgid "" "`print_stack`." msgstr "" -#: ../../library/traceback.rst:137 +#: ../../library/traceback.rst:162 +msgid "" +"Print the list of tuples as returned by :func:`extract_tb` or :func:" +"`extract_stack` as a formatted stack trace to the given file. If *file* is " +"``None``, the output is written to :data:`sys.stderr`." +msgstr "" + +#: ../../library/traceback.rst:169 msgid "" "Given a list of tuples or :class:`FrameSummary` objects as returned by :func:" "`extract_tb` or :func:`extract_stack`, return a list of strings ready for " @@ -192,7 +227,7 @@ msgid "" "text line is not ``None``." msgstr "" -#: ../../library/traceback.rst:147 +#: ../../library/traceback.rst:179 msgid "" "Format the exception part of a traceback using an exception value such as " "given by :data:`sys.last_value`. The return value is a list of strings, " @@ -203,31 +238,31 @@ msgid "" "contains the exception's :attr:`notes `." msgstr "" -#: ../../library/traceback.rst:155 +#: ../../library/traceback.rst:187 msgid "" "Since Python 3.10, instead of passing *value*, an exception object can be " "passed as the first argument. If *value* is provided, the first argument is " "ignored in order to provide backwards compatibility." msgstr "" -#: ../../library/traceback.rst:159 ../../library/traceback.rst:386 +#: ../../library/traceback.rst:191 ../../library/traceback.rst:422 msgid "" "When *show_group* is ``True``, and the exception is an instance of :exc:" "`BaseExceptionGroup`, the nested exceptions are included as well, " "recursively, with indentation relative to their nesting depth." msgstr "" -#: ../../library/traceback.rst:167 +#: ../../library/traceback.rst:199 msgid "" "The returned list now includes any :attr:`notes ` " "attached to the exception." msgstr "" -#: ../../library/traceback.rst:171 +#: ../../library/traceback.rst:203 msgid "*show_group* parameter was added." msgstr "" -#: ../../library/traceback.rst:177 +#: ../../library/traceback.rst:209 msgid "" "Format a stack trace and the exception information. The arguments have the " "same meaning as the corresponding arguments to :func:`print_exception`. The " @@ -236,68 +271,69 @@ msgid "" "printed, exactly the same text is printed as does :func:`print_exception`." msgstr "" -#: ../../library/traceback.rst:186 +#: ../../library/traceback.rst:218 msgid "" "This function's behavior and signature were modified to match :func:" "`print_exception`." msgstr "" -#: ../../library/traceback.rst:193 +#: ../../library/traceback.rst:225 msgid "" "This is like ``print_exc(limit)`` but returns a string instead of printing " "to a file." msgstr "" -#: ../../library/traceback.rst:199 +#: ../../library/traceback.rst:231 msgid "A shorthand for ``format_list(extract_tb(tb, limit))``." msgstr "" -#: ../../library/traceback.rst:204 +#: ../../library/traceback.rst:236 msgid "A shorthand for ``format_list(extract_stack(f, limit))``." msgstr "" -#: ../../library/traceback.rst:208 +#: ../../library/traceback.rst:240 msgid "" "Clears the local variables of all the stack frames in a :ref:`traceback " "` *tb* by calling the :meth:`~frame.clear` method of " "each :ref:`frame object `." msgstr "" -#: ../../library/traceback.rst:217 +#: ../../library/traceback.rst:249 msgid "" "Walk a stack following :attr:`f.f_back ` from the given frame, " "yielding the frame and line number for each frame. If *f* is ``None``, the " "current stack is used. This helper is used with :meth:`StackSummary.extract`." msgstr "" -#: ../../library/traceback.rst:226 +#: ../../library/traceback.rst:258 msgid "" "Walk a traceback following :attr:`~traceback.tb_next` yielding the frame and " "line number for each frame. This helper is used with :meth:`StackSummary." "extract`." msgstr "" -#: ../../library/traceback.rst:232 -msgid "The module also defines the following classes:" -msgstr "" - -#: ../../library/traceback.rst:235 +#: ../../library/traceback.rst:266 msgid ":class:`!TracebackException` Objects" msgstr "" -#: ../../library/traceback.rst:239 +#: ../../library/traceback.rst:270 msgid "" ":class:`!TracebackException` objects are created from actual exceptions to " -"capture data for later printing in a lightweight fashion." +"capture data for later printing. They offer a more lightweight method of " +"storing this information by avoiding holding references to :ref:" +"`traceback` and :ref:`frame` objects. In " +"addition, they expose more options to configure the output compared to the " +"module-level functions described above." msgstr "" -#: ../../library/traceback.rst:244 ../../library/traceback.rst:351 +#: ../../library/traceback.rst:279 msgid "" -"Capture an exception for later rendering. *limit*, *lookup_lines* and " -"*capture_locals* are as for the :class:`StackSummary` class." +"Capture an exception for later rendering. The meaning of *limit*, " +"*lookup_lines* and *capture_locals* are as for the :class:`StackSummary` " +"class." msgstr "" -#: ../../library/traceback.rst:247 +#: ../../library/traceback.rst:283 msgid "" "If *compact* is true, only data that is required by :class:`!" "TracebackException`'s :meth:`format` method is saved in the class " @@ -305,12 +341,12 @@ msgid "" "if :attr:`__cause__` is ``None`` and :attr:`__suppress_context__` is false." msgstr "" -#: ../../library/traceback.rst:253 ../../library/traceback.rst:354 +#: ../../library/traceback.rst:289 ../../library/traceback.rst:390 msgid "" "Note that when locals are captured, they are also shown in the traceback." msgstr "" -#: ../../library/traceback.rst:255 +#: ../../library/traceback.rst:291 msgid "" "*max_group_width* and *max_group_depth* control the formatting of exception " "groups (see :exc:`BaseExceptionGroup`). The depth refers to the nesting " @@ -319,122 +355,128 @@ msgid "" "limit is exceeded." msgstr "" -#: ../../library/traceback.rst:261 +#: ../../library/traceback.rst:297 msgid "Added the *compact* parameter." msgstr "Adicionado o parâmetro *compact*." -#: ../../library/traceback.rst:264 +#: ../../library/traceback.rst:300 msgid "Added the *max_group_width* and *max_group_depth* parameters." msgstr "" -#: ../../library/traceback.rst:269 +#: ../../library/traceback.rst:305 msgid "" "A :class:`!TracebackException` of the original :attr:`~BaseException." "__cause__`." msgstr "" -#: ../../library/traceback.rst:274 +#: ../../library/traceback.rst:310 msgid "" "A :class:`!TracebackException` of the original :attr:`~BaseException." "__context__`." msgstr "" -#: ../../library/traceback.rst:279 +#: ../../library/traceback.rst:315 msgid "" "If ``self`` represents an :exc:`ExceptionGroup`, this field holds a list of :" "class:`!TracebackException` instances representing the nested exceptions. " "Otherwise it is ``None``." msgstr "" -#: ../../library/traceback.rst:287 +#: ../../library/traceback.rst:323 msgid "" "The :attr:`~BaseException.__suppress_context__` value from the original " "exception." msgstr "" -#: ../../library/traceback.rst:292 +#: ../../library/traceback.rst:328 msgid "" "The :attr:`~BaseException.__notes__` value from the original exception, or " "``None`` if the exception does not have any notes. If it is not ``None`` is " "it formatted in the traceback after the exception string." msgstr "" -#: ../../library/traceback.rst:301 +#: ../../library/traceback.rst:337 msgid "A :class:`StackSummary` representing the traceback." msgstr "" -#: ../../library/traceback.rst:305 +#: ../../library/traceback.rst:341 msgid "The class of the original traceback." msgstr "" -#: ../../library/traceback.rst:311 +#: ../../library/traceback.rst:347 msgid "String display of the class of the original exception." msgstr "" -#: ../../library/traceback.rst:317 +#: ../../library/traceback.rst:353 msgid "For syntax errors - the file name where the error occurred." msgstr "" -#: ../../library/traceback.rst:321 +#: ../../library/traceback.rst:357 msgid "For syntax errors - the line number where the error occurred." msgstr "" -#: ../../library/traceback.rst:325 +#: ../../library/traceback.rst:361 msgid "" "For syntax errors - the end line number where the error occurred. Can be " "``None`` if not present." msgstr "" -#: ../../library/traceback.rst:332 +#: ../../library/traceback.rst:368 msgid "For syntax errors - the text where the error occurred." msgstr "" -#: ../../library/traceback.rst:336 +#: ../../library/traceback.rst:372 msgid "For syntax errors - the offset into the text where the error occurred." msgstr "" -#: ../../library/traceback.rst:340 +#: ../../library/traceback.rst:376 msgid "" "For syntax errors - the end offset into the text where the error occurred. " "Can be ``None`` if not present." msgstr "" -#: ../../library/traceback.rst:347 +#: ../../library/traceback.rst:383 msgid "For syntax errors - the compiler error message." msgstr "" -#: ../../library/traceback.rst:358 +#: ../../library/traceback.rst:387 +msgid "" +"Capture an exception for later rendering. *limit*, *lookup_lines* and " +"*capture_locals* are as for the :class:`StackSummary` class." +msgstr "" + +#: ../../library/traceback.rst:394 msgid "" "Print to *file* (default ``sys.stderr``) the exception information returned " "by :meth:`format`." msgstr "" -#: ../../library/traceback.rst:365 +#: ../../library/traceback.rst:401 msgid "Format the exception." msgstr "" -#: ../../library/traceback.rst:367 +#: ../../library/traceback.rst:403 msgid "" "If *chain* is not ``True``, :attr:`__cause__` and :attr:`__context__` will " "not be formatted." msgstr "" -#: ../../library/traceback.rst:370 +#: ../../library/traceback.rst:406 msgid "" "The return value is a generator of strings, each ending in a newline and " "some containing internal newlines. :func:`~traceback.print_exception` is a " "wrapper around this method which just prints the lines to a file." msgstr "" -#: ../../library/traceback.rst:376 +#: ../../library/traceback.rst:412 msgid "Format the exception part of the traceback." msgstr "" -#: ../../library/traceback.rst:378 +#: ../../library/traceback.rst:414 msgid "The return value is a generator of strings, each ending in a newline." msgstr "" -#: ../../library/traceback.rst:380 +#: ../../library/traceback.rst:416 msgid "" "When *show_group* is ``False``, the generator emits the exception's message " "followed by its notes (if it has any). The exception message is normally a " @@ -443,32 +485,32 @@ msgid "" "the syntax error occurred." msgstr "" -#: ../../library/traceback.rst:390 +#: ../../library/traceback.rst:426 msgid "" "The exception's :attr:`notes ` are now included in " "the output." msgstr "" -#: ../../library/traceback.rst:394 +#: ../../library/traceback.rst:430 msgid "Added the *show_group* parameter." msgstr "" -#: ../../library/traceback.rst:399 +#: ../../library/traceback.rst:435 msgid ":class:`!StackSummary` Objects" msgstr "" -#: ../../library/traceback.rst:403 +#: ../../library/traceback.rst:439 msgid "" ":class:`!StackSummary` objects represent a call stack ready for formatting." msgstr "" -#: ../../library/traceback.rst:409 +#: ../../library/traceback.rst:445 msgid "" "Construct a :class:`!StackSummary` object from a frame generator (such as is " "returned by :func:`~traceback.walk_stack` or :func:`~traceback.walk_tb`)." msgstr "" -#: ../../library/traceback.rst:413 +#: ../../library/traceback.rst:449 msgid "" "If *limit* is supplied, only this many frames are taken from *frame_gen*. If " "*lookup_lines* is ``False``, the returned :class:`FrameSummary` objects will " @@ -478,20 +520,20 @@ msgid "" "class:`!FrameSummary` are captured as object representations." msgstr "" -#: ../../library/traceback.rst:421 +#: ../../library/traceback.rst:457 msgid "" "Exceptions raised from :func:`repr` on a local variable (when " "*capture_locals* is ``True``) are no longer propagated to the caller." msgstr "" -#: ../../library/traceback.rst:427 +#: ../../library/traceback.rst:463 msgid "" "Construct a :class:`!StackSummary` object from a supplied list of :class:" "`FrameSummary` objects or old-style list of tuples. Each tuple should be a " "4-tuple with *filename*, *lineno*, *name*, *line* as the elements." msgstr "" -#: ../../library/traceback.rst:434 +#: ../../library/traceback.rst:470 msgid "" "Returns a list of strings ready for printing. Each string in the resulting " "list corresponds to a single :ref:`frame ` from the stack. " @@ -499,18 +541,18 @@ msgid "" "well, for those items with source text lines." msgstr "" -#: ../../library/traceback.rst:440 +#: ../../library/traceback.rst:476 msgid "" "For long sequences of the same frame and line, the first few repetitions are " "shown, followed by a summary line stating the exact number of further " "repetitions." msgstr "" -#: ../../library/traceback.rst:444 +#: ../../library/traceback.rst:480 msgid "Long sequences of repeated frames are now abbreviated." msgstr "" -#: ../../library/traceback.rst:449 +#: ../../library/traceback.rst:485 msgid "" "Returns a string for printing one of the :ref:`frames ` " "involved in the stack. This method is called for each :class:`FrameSummary` " @@ -518,17 +560,17 @@ msgid "" "the frame is omitted from the output." msgstr "" -#: ../../library/traceback.rst:459 +#: ../../library/traceback.rst:495 msgid ":class:`!FrameSummary` Objects" msgstr "" -#: ../../library/traceback.rst:463 +#: ../../library/traceback.rst:499 msgid "" "A :class:`!FrameSummary` object represents a single :ref:`frame ` in a :ref:`traceback `." msgstr "" -#: ../../library/traceback.rst:468 +#: ../../library/traceback.rst:506 msgid "" "Represents a single :ref:`frame ` in the :ref:`traceback " "` or stack that is being formatted or printed. It may " @@ -542,38 +584,60 @@ msgid "" "display." msgstr "" -#: ../../library/traceback.rst:479 +#: ../../library/traceback.rst:517 msgid ":class:`!FrameSummary` instances have the following attributes:" msgstr "" -#: ../../library/traceback.rst:483 +#: ../../library/traceback.rst:521 msgid "" "The filename of the source code for this frame. Equivalent to accessing :" "attr:`f.f_code.co_filename ` on a :ref:`frame object " "` *f*." msgstr "" -#: ../../library/traceback.rst:489 +#: ../../library/traceback.rst:527 msgid "The line number of the source code for this frame." msgstr "" -#: ../../library/traceback.rst:493 +#: ../../library/traceback.rst:531 msgid "" "Equivalent to accessing :attr:`f.f_code.co_name ` on a :" "ref:`frame object ` *f*." msgstr "" -#: ../../library/traceback.rst:498 +#: ../../library/traceback.rst:536 msgid "" "A string representing the source code for this frame, with leading and " "trailing whitespace stripped. If the source is not available, it is ``None``." msgstr "" -#: ../../library/traceback.rst:505 -msgid "Traceback Examples" -msgstr "Exemplos de Traceback" +#: ../../library/traceback.rst:542 +msgid "" +"The last line number of the source code for this frame. By default, it is " +"set to ``lineno`` and indexation starts from 1." +msgstr "" -#: ../../library/traceback.rst:507 +#: ../../library/traceback.rst:545 +msgid "The default value changed from ``None`` to ``lineno``." +msgstr "" + +#: ../../library/traceback.rst:550 +msgid "" +"The column number of the source code for this frame. By default, it is " +"``None`` and indexation starts from 0." +msgstr "" + +#: ../../library/traceback.rst:555 +msgid "" +"The last column number of the source code for this frame. By default, it is " +"``None`` and indexation starts from 0." +msgstr "" + +#: ../../library/traceback.rst:562 +msgid "Examples of Using the Module-Level Functions" +msgstr "" + +#: ../../library/traceback.rst:564 msgid "" "This simple example implements a basic read-eval-print loop, similar to (but " "less useful than) the standard Python interactive interpreter loop. For a " @@ -581,38 +645,267 @@ msgid "" "`code` module. ::" msgstr "" -#: ../../library/traceback.rst:529 +#: ../../library/traceback.rst:569 +msgid "" +"import sys, traceback\n" +"\n" +"def run_user_code(envdir):\n" +" source = input(\">>> \")\n" +" try:\n" +" exec(source, envdir)\n" +" except Exception:\n" +" print(\"Exception in user code:\")\n" +" print(\"-\"*60)\n" +" traceback.print_exc(file=sys.stdout)\n" +" print(\"-\"*60)\n" +"\n" +"envdir = {}\n" +"while True:\n" +" run_user_code(envdir)" +msgstr "" + +#: ../../library/traceback.rst:586 msgid "" "The following example demonstrates the different ways to print and format " "the exception and traceback:" msgstr "" -#: ../../library/traceback.rst:564 +#: ../../library/traceback.rst:589 +msgid "" +"import sys, traceback\n" +"\n" +"def lumberjack():\n" +" bright_side_of_life()\n" +"\n" +"def bright_side_of_life():\n" +" return tuple()[0]\n" +"\n" +"try:\n" +" lumberjack()\n" +"except IndexError as exc:\n" +" print(\"*** print_tb:\")\n" +" traceback.print_tb(exc.__traceback__, limit=1, file=sys.stdout)\n" +" print(\"*** print_exception:\")\n" +" traceback.print_exception(exc, limit=2, file=sys.stdout)\n" +" print(\"*** print_exc:\")\n" +" traceback.print_exc(limit=2, file=sys.stdout)\n" +" print(\"*** format_exc, first and last line:\")\n" +" formatted_lines = traceback.format_exc().splitlines()\n" +" print(formatted_lines[0])\n" +" print(formatted_lines[-1])\n" +" print(\"*** format_exception:\")\n" +" print(repr(traceback.format_exception(exc)))\n" +" print(\"*** extract_tb:\")\n" +" print(repr(traceback.extract_tb(exc.__traceback__)))\n" +" print(\"*** format_tb:\")\n" +" print(repr(traceback.format_tb(exc.__traceback__)))\n" +" print(\"*** tb_lineno:\", exc.__traceback__.tb_lineno)" +msgstr "" + +#: ../../library/traceback.rst:620 msgid "The output for the example would look similar to this:" msgstr "" -#: ../../library/traceback.rst:611 +#: ../../library/traceback.rst:622 +msgid "" +"*** print_tb:\n" +" File \"\", line 10, in \n" +" lumberjack()\n" +" ~~~~~~~~~~^^\n" +"*** print_exception:\n" +"Traceback (most recent call last):\n" +" File \"\", line 10, in \n" +" lumberjack()\n" +" ~~~~~~~~~~^^\n" +" File \"\", line 4, in lumberjack\n" +" bright_side_of_life()\n" +" ~~~~~~~~~~~~~~~~~~~^^\n" +"IndexError: tuple index out of range\n" +"*** print_exc:\n" +"Traceback (most recent call last):\n" +" File \"\", line 10, in \n" +" lumberjack()\n" +" ~~~~~~~~~~^^\n" +" File \"\", line 4, in lumberjack\n" +" bright_side_of_life()\n" +" ~~~~~~~~~~~~~~~~~~~^^\n" +"IndexError: tuple index out of range\n" +"*** format_exc, first and last line:\n" +"Traceback (most recent call last):\n" +"IndexError: tuple index out of range\n" +"*** format_exception:\n" +"['Traceback (most recent call last):\\n',\n" +" ' File \"\", line 10, in \\n " +"lumberjack()\\n ~~~~~~~~~~^^\\n',\n" +" ' File \"\", line 4, in lumberjack\\n " +"bright_side_of_life()\\n ~~~~~~~~~~~~~~~~~~~^^\\n',\n" +" ' File \"\", line 7, in bright_side_of_life\\n " +"return tuple()[0]\\n ~~~~~~~^^^\\n',\n" +" 'IndexError: tuple index out of range\\n']\n" +"*** extract_tb:\n" +"[, line 10 in >,\n" +" , line 4 in lumberjack>,\n" +" , line 7 in bright_side_of_life>]\n" +"*** format_tb:\n" +"[' File \"\", line 10, in \\n " +"lumberjack()\\n ~~~~~~~~~~^^\\n',\n" +" ' File \"\", line 4, in lumberjack\\n " +"bright_side_of_life()\\n ~~~~~~~~~~~~~~~~~~~^^\\n',\n" +" ' File \"\", line 7, in bright_side_of_life\\n " +"return tuple()[0]\\n ~~~~~~~^^^\\n']\n" +"*** tb_lineno: 10" +msgstr "" + +#: ../../library/traceback.rst:667 msgid "" "The following example shows the different ways to print and format the " "stack::" msgstr "" -#: ../../library/traceback.rst:637 +#: ../../library/traceback.rst:669 +msgid "" +">>> import traceback\n" +">>> def another_function():\n" +"... lumberstack()\n" +"...\n" +">>> def lumberstack():\n" +"... traceback.print_stack()\n" +"... print(repr(traceback.extract_stack()))\n" +"... print(repr(traceback.format_stack()))\n" +"...\n" +">>> another_function()\n" +" File \"\", line 10, in \n" +" another_function()\n" +" File \"\", line 3, in another_function\n" +" lumberstack()\n" +" File \"\", line 6, in lumberstack\n" +" traceback.print_stack()\n" +"[('', 10, '', 'another_function()'),\n" +" ('', 3, 'another_function', 'lumberstack()'),\n" +" ('', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')]\n" +"[' File \"\", line 10, in \\n another_function()\\n',\n" +" ' File \"\", line 3, in another_function\\n " +"lumberstack()\\n',\n" +" ' File \"\", line 8, in lumberstack\\n print(repr(traceback." +"format_stack()))\\n']" +msgstr "" + +#: ../../library/traceback.rst:693 msgid "This last example demonstrates the final few formatting functions:" msgstr "" -#: ../../library/traceback.rst:17 +#: ../../library/traceback.rst:695 +msgid "" +">>> import traceback\n" +">>> traceback.format_list([('spam.py', 3, '', 'spam.eggs()'),\n" +"... ('eggs.py', 42, 'eggs', 'return \"bacon\"')])\n" +"[' File \"spam.py\", line 3, in \\n spam.eggs()\\n',\n" +" ' File \"eggs.py\", line 42, in eggs\\n return \"bacon\"\\n']\n" +">>> an_error = IndexError('tuple index out of range')\n" +">>> traceback.format_exception_only(an_error)\n" +"['IndexError: tuple index out of range\\n']" +msgstr "" + +#: ../../library/traceback.rst:709 +msgid "Examples of Using :class:`TracebackException`" +msgstr "" + +#: ../../library/traceback.rst:711 +msgid "With the helper class, we have more options::" +msgstr "" + +#: ../../library/traceback.rst:713 +msgid "" +">>> import sys\n" +">>> from traceback import TracebackException\n" +">>>\n" +">>> def lumberjack():\n" +"... bright_side_of_life()\n" +"...\n" +">>> def bright_side_of_life():\n" +"... t = \"bright\", \"side\", \"of\", \"life\"\n" +"... return t[5]\n" +"...\n" +">>> try:\n" +"... lumberjack()\n" +"... except IndexError as e:\n" +"... exc = e\n" +"...\n" +">>> try:\n" +"... try:\n" +"... lumberjack()\n" +"... except:\n" +"... 1/0\n" +"... except Exception as e:\n" +"... chained_exc = e\n" +"...\n" +">>> # limit works as with the module-level functions\n" +">>> TracebackException.from_exception(exc, limit=-2).print()\n" +"Traceback (most recent call last):\n" +" File \"\", line 6, in lumberjack\n" +" bright_side_of_life()\n" +" ~~~~~~~~~~~~~~~~~~~^^\n" +" File \"\", line 10, in bright_side_of_life\n" +" return t[5]\n" +" ~^^^\n" +"IndexError: tuple index out of range\n" +"\n" +">>> # capture_locals adds local variables in frames\n" +">>> TracebackException.from_exception(exc, limit=-2, capture_locals=True)." +"print()\n" +"Traceback (most recent call last):\n" +" File \"\", line 6, in lumberjack\n" +" bright_side_of_life()\n" +" ~~~~~~~~~~~~~~~~~~~^^\n" +" File \"\", line 10, in bright_side_of_life\n" +" return t[5]\n" +" ~^^^\n" +" t = (\"bright\", \"side\", \"of\", \"life\")\n" +"IndexError: tuple index out of range\n" +"\n" +">>> # The *chain* kwarg to print() controls whether chained\n" +">>> # exceptions are displayed\n" +">>> TracebackException.from_exception(chained_exc).print()\n" +"Traceback (most recent call last):\n" +" File \"\", line 4, in \n" +" lumberjack()\n" +" ~~~~~~~~~~^^\n" +" File \"\", line 7, in lumberjack\n" +" bright_side_of_life()\n" +" ~~~~~~~~~~~~~~~~~~~^^\n" +" File \"\", line 11, in bright_side_of_life\n" +" return t[5]\n" +" ~^^^\n" +"IndexError: tuple index out of range\n" +"\n" +"During handling of the above exception, another exception occurred:\n" +"\n" +"Traceback (most recent call last):\n" +" File \"\", line 6, in \n" +" 1/0\n" +" ~^~\n" +"ZeroDivisionError: division by zero\n" +"\n" +">>> TracebackException.from_exception(chained_exc).print(chain=False)\n" +"Traceback (most recent call last):\n" +" File \"\", line 6, in \n" +" 1/0\n" +" ~^~\n" +"ZeroDivisionError: division by zero" +msgstr "" + +#: ../../library/traceback.rst:21 msgid "object" msgstr "objeto" -#: ../../library/traceback.rst:17 +#: ../../library/traceback.rst:21 msgid "traceback" msgstr "traceback" -#: ../../library/traceback.rst:62 +#: ../../library/traceback.rst:87 msgid "^ (caret)" msgstr "^ (circunflexo)" -#: ../../library/traceback.rst:62 +#: ../../library/traceback.rst:87 msgid "marker" msgstr "" diff --git a/library/tracemalloc.po b/library/tracemalloc.po index 668697730..cd5c1d658 100644 --- a/library/tracemalloc.po +++ b/library/tracemalloc.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Italo Penaforte , 2021 -# And Past , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 01:16+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -52,15 +46,12 @@ msgid "" "Statistics on allocated memory blocks per filename and per line number: " "total size, number and average size of allocated memory blocks" msgstr "" -"Estatísticas sobre blocos de memória alocados por nome de arquivo e por " -"número de linha: tamanho total, número e tamanho médio dos blocos de memória " -"alocados" +"Statistics on allocated memory blocks per filename and per line number: " +"total size, number and average size of allocated memory blocks" #: ../../library/tracemalloc.rst:19 msgid "Compute the differences between two snapshots to detect memory leaks" -msgstr "" -"Calcula as diferenças entre dois instantâneos para detectar vazamentos de " -"memória" +msgstr "Compute the differences between two snapshots to detect memory leaks" #: ../../library/tracemalloc.rst:21 msgid "" @@ -91,10 +82,45 @@ msgstr "Exibe o top 10" msgid "Display the 10 files allocating the most memory::" msgstr "" +#: ../../library/tracemalloc.rst:41 +msgid "" +"import tracemalloc\n" +"\n" +"tracemalloc.start()\n" +"\n" +"# ... run your application ...\n" +"\n" +"snapshot = tracemalloc.take_snapshot()\n" +"top_stats = snapshot.statistics('lineno')\n" +"\n" +"print(\"[ Top 10 ]\")\n" +"for stat in top_stats[:10]:\n" +" print(stat)" +msgstr "" + #: ../../library/tracemalloc.rst:55 ../../library/tracemalloc.rst:225 msgid "Example of output of the Python test suite::" msgstr "" +#: ../../library/tracemalloc.rst:57 +msgid "" +"[ Top 10 ]\n" +":716: size=4855 KiB, count=39328, average=126 " +"B\n" +":284: size=521 KiB, count=3199, average=167 B\n" +"/usr/lib/python3.4/collections/__init__.py:368: size=244 KiB, count=2315, " +"average=108 B\n" +"/usr/lib/python3.4/unittest/case.py:381: size=185 KiB, count=779, " +"average=243 B\n" +"/usr/lib/python3.4/unittest/case.py:402: size=154 KiB, count=378, " +"average=416 B\n" +"/usr/lib/python3.4/abc.py:133: size=88.7 KiB, count=347, average=262 B\n" +":1446: size=70.4 KiB, count=911, average=79 B\n" +":1454: size=52.0 KiB, count=25, average=2131 B\n" +":5: size=49.7 KiB, count=148, average=344 B\n" +"/usr/lib/python3.4/sysconfig.py:411: size=48.0 KiB, count=1, average=48.0 KiB" +msgstr "" + #: ../../library/tracemalloc.rst:69 msgid "" "We can see that Python loaded ``4855 KiB`` data (bytecode and constants) " @@ -114,11 +140,53 @@ msgstr "" msgid "Take two snapshots and display the differences::" msgstr "" +#: ../../library/tracemalloc.rst:81 +msgid "" +"import tracemalloc\n" +"tracemalloc.start()\n" +"# ... start your application ...\n" +"\n" +"snapshot1 = tracemalloc.take_snapshot()\n" +"# ... call the function leaking memory ...\n" +"snapshot2 = tracemalloc.take_snapshot()\n" +"\n" +"top_stats = snapshot2.compare_to(snapshot1, 'lineno')\n" +"\n" +"print(\"[ Top 10 differences ]\")\n" +"for stat in top_stats[:10]:\n" +" print(stat)" +msgstr "" + #: ../../library/tracemalloc.rst:95 msgid "" "Example of output before/after running some tests of the Python test suite::" msgstr "" +#: ../../library/tracemalloc.rst:97 +msgid "" +"[ Top 10 differences ]\n" +":716: size=8173 KiB (+4428 KiB), count=71332 " +"(+39369), average=117 B\n" +"/usr/lib/python3.4/linecache.py:127: size=940 KiB (+940 KiB), count=8106 " +"(+8106), average=119 B\n" +"/usr/lib/python3.4/unittest/case.py:571: size=298 KiB (+298 KiB), count=589 " +"(+589), average=519 B\n" +":284: size=1005 KiB (+166 KiB), count=7423 " +"(+1526), average=139 B\n" +"/usr/lib/python3.4/mimetypes.py:217: size=112 KiB (+112 KiB), count=1334 " +"(+1334), average=86 B\n" +"/usr/lib/python3.4/http/server.py:848: size=96.0 KiB (+96.0 KiB), count=1 " +"(+1), average=96.0 KiB\n" +"/usr/lib/python3.4/inspect.py:1465: size=83.5 KiB (+83.5 KiB), count=109 " +"(+109), average=784 B\n" +"/usr/lib/python3.4/unittest/mock.py:491: size=77.7 KiB (+77.7 KiB), " +"count=143 (+143), average=557 B\n" +"/usr/lib/python3.4/urllib/parse.py:476: size=71.8 KiB (+71.8 KiB), count=969 " +"(+969), average=76 B\n" +"/usr/lib/python3.4/contextlib.py:38: size=67.2 KiB (+67.2 KiB), count=126 " +"(+126), average=546 B" +msgstr "" + #: ../../library/tracemalloc.rst:109 msgid "" "We can see that Python has loaded ``8173 KiB`` of module data (bytecode and " @@ -143,11 +211,68 @@ msgstr "" msgid "Code to display the traceback of the biggest memory block::" msgstr "" +#: ../../library/tracemalloc.rst:125 +msgid "" +"import tracemalloc\n" +"\n" +"# Store 25 frames\n" +"tracemalloc.start(25)\n" +"\n" +"# ... run your application ...\n" +"\n" +"snapshot = tracemalloc.take_snapshot()\n" +"top_stats = snapshot.statistics('traceback')\n" +"\n" +"# pick the biggest memory block\n" +"stat = top_stats[0]\n" +"print(\"%s memory blocks: %.1f KiB\" % (stat.count, stat.size / 1024))\n" +"for line in stat.traceback.format():\n" +" print(line)" +msgstr "" + #: ../../library/tracemalloc.rst:141 msgid "" "Example of output of the Python test suite (traceback limited to 25 frames)::" msgstr "" +#: ../../library/tracemalloc.rst:143 +msgid "" +"903 memory blocks: 870.1 KiB\n" +" File \"\", line 716\n" +" File \"\", line 1036\n" +" File \"\", line 934\n" +" File \"\", line 1068\n" +" File \"\", line 619\n" +" File \"\", line 1581\n" +" File \"\", line 1614\n" +" File \"/usr/lib/python3.4/doctest.py\", line 101\n" +" import pdb\n" +" File \"\", line 284\n" +" File \"\", line 938\n" +" File \"\", line 1068\n" +" File \"\", line 619\n" +" File \"\", line 1581\n" +" File \"\", line 1614\n" +" File \"/usr/lib/python3.4/test/support/__init__.py\", line 1728\n" +" import doctest\n" +" File \"/usr/lib/python3.4/test/test_pickletools.py\", line 21\n" +" support.run_doctest(pickletools)\n" +" File \"/usr/lib/python3.4/test/regrtest.py\", line 1276\n" +" test_runner()\n" +" File \"/usr/lib/python3.4/test/regrtest.py\", line 976\n" +" display_failure=not verbose)\n" +" File \"/usr/lib/python3.4/test/regrtest.py\", line 761\n" +" match_tests=ns.match_tests)\n" +" File \"/usr/lib/python3.4/test/regrtest.py\", line 1563\n" +" main()\n" +" File \"/usr/lib/python3.4/test/__main__.py\", line 3\n" +" regrtest.main_in_temp_cwd()\n" +" File \"/usr/lib/python3.4/runpy.py\", line 73\n" +" exec(code, run_globals)\n" +" File \"/usr/lib/python3.4/runpy.py\", line 160\n" +" \"__main__\", fname, loader, pkg_name)" +msgstr "" + #: ../../library/tracemalloc.rst:178 msgid "" "We can see that the most memory was allocated in the :mod:`importlib` module " @@ -167,6 +292,69 @@ msgid "" "output, ignoring ```` and ```` files::" msgstr "" +#: ../../library/tracemalloc.rst:191 +msgid "" +"import linecache\n" +"import os\n" +"import tracemalloc\n" +"\n" +"def display_top(snapshot, key_type='lineno', limit=10):\n" +" snapshot = snapshot.filter_traces((\n" +" tracemalloc.Filter(False, \"\"),\n" +" tracemalloc.Filter(False, \"\"),\n" +" ))\n" +" top_stats = snapshot.statistics(key_type)\n" +"\n" +" print(\"Top %s lines\" % limit)\n" +" for index, stat in enumerate(top_stats[:limit], 1):\n" +" frame = stat.traceback[0]\n" +" print(\"#%s: %s:%s: %.1f KiB\"\n" +" % (index, frame.filename, frame.lineno, stat.size / 1024))\n" +" line = linecache.getline(frame.filename, frame.lineno).strip()\n" +" if line:\n" +" print(' %s' % line)\n" +"\n" +" other = top_stats[limit:]\n" +" if other:\n" +" size = sum(stat.size for stat in other)\n" +" print(\"%s other: %.1f KiB\" % (len(other), size / 1024))\n" +" total = sum(stat.size for stat in top_stats)\n" +" print(\"Total allocated size: %.1f KiB\" % (total / 1024))\n" +"\n" +"tracemalloc.start()\n" +"\n" +"# ... run your application ...\n" +"\n" +"snapshot = tracemalloc.take_snapshot()\n" +"display_top(snapshot)" +msgstr "" + +#: ../../library/tracemalloc.rst:227 +msgid "" +"Top 10 lines\n" +"#1: Lib/base64.py:414: 419.8 KiB\n" +" _b85chars2 = [(a + b) for a in _b85chars for b in _b85chars]\n" +"#2: Lib/base64.py:306: 419.8 KiB\n" +" _a85chars2 = [(a + b) for a in _a85chars for b in _a85chars]\n" +"#3: collections/__init__.py:368: 293.6 KiB\n" +" exec(class_definition, namespace)\n" +"#4: Lib/abc.py:133: 115.2 KiB\n" +" cls = super().__new__(mcls, name, bases, namespace)\n" +"#5: unittest/case.py:574: 103.1 KiB\n" +" testMethod()\n" +"#6: Lib/linecache.py:127: 95.4 KiB\n" +" lines = fp.readlines()\n" +"#7: urllib/parse.py:476: 71.8 KiB\n" +" for a in _hexdig for b in _hexdig}\n" +"#8: :5: 62.0 KiB\n" +"#9: Lib/_weakrefset.py:37: 60.0 KiB\n" +" self.data = set()\n" +"#10: Lib/base64.py:142: 59.8 KiB\n" +" _b32tab2 = [a + b for a in _b32tab for b in _b32tab]\n" +"6220 other: 3602.8 KiB\n" +"Total allocated size: 5303.1 KiB" +msgstr "" + #: ../../library/tracemalloc.rst:253 msgid "Record the current and peak size of all traced memory blocks" msgstr "" @@ -180,10 +368,38 @@ msgid "" "memory usage during the computations::" msgstr "" +#: ../../library/tracemalloc.rst:261 +msgid "" +"import tracemalloc\n" +"\n" +"tracemalloc.start()\n" +"\n" +"# Example code: compute a sum with a large temporary list\n" +"large_sum = sum(list(range(100000)))\n" +"\n" +"first_size, first_peak = tracemalloc.get_traced_memory()\n" +"\n" +"tracemalloc.reset_peak()\n" +"\n" +"# Example code: compute a sum with a small temporary list\n" +"small_sum = sum(list(range(1000)))\n" +"\n" +"second_size, second_peak = tracemalloc.get_traced_memory()\n" +"\n" +"print(f\"{first_size=}, {first_peak=}\")\n" +"print(f\"{second_size=}, {second_peak=}\")" +msgstr "" + #: ../../library/tracemalloc.rst:280 ../../library/tracemalloc.rst:759 msgid "Output::" msgstr "Saída::" +#: ../../library/tracemalloc.rst:282 +msgid "" +"first_size=664, first_peak=3592984\n" +"second_size=804, second_peak=29704" +msgstr "" + #: ../../library/tracemalloc.rst:285 msgid "" "Using :func:`reset_peak` ensured we could accurately record the peak during " @@ -804,3 +1020,19 @@ msgstr "" #: ../../library/tracemalloc.rst:753 msgid "Example::" msgstr "Exemplo::" + +#: ../../library/tracemalloc.rst:755 +msgid "" +"print(\"Traceback (most recent call first):\")\n" +"for line in traceback:\n" +" print(line)" +msgstr "" + +#: ../../library/tracemalloc.rst:761 +msgid "" +"Traceback (most recent call first):\n" +" File \"test.py\", line 9\n" +" obj = Object()\n" +" File \"test.py\", line 12\n" +" tb = tracemalloc.get_object_traceback(f())" +msgstr "" diff --git a/library/tty.po b/library/tty.po index 94260c70d..0332a5a6c 100644 --- a/library/tty.po +++ b/library/tty.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:16+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -40,8 +40,8 @@ msgstr "" "não tratados (raw)." #: ../../library/tty.rst:18 -msgid ":ref:`Availability `: Unix." -msgstr ":ref:`Disponibilidade `: Unix." +msgid "Availability" +msgstr "Disponibilidade" #: ../../library/tty.rst:20 msgid "" diff --git a/library/turtle.po b/library/turtle.po index 894aee5c5..5c3b92112 100644 --- a/library/turtle.po +++ b/library/turtle.po @@ -1,42 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Ruan Aragão , 2021 -# Marco Rougeth , 2021 -# Danilo Lima , 2021 -# i17obot , 2021 -# Kattson Bastos, 2022 -# ramalho , 2022 -# Claudio Rogerio Carvalho Filho , 2023 -# And Past , 2023 -# FolkDigital - Soluções em Internet, 2023 -# Adorilson Bezerra , 2024 -# Leandro Cavalcante Damascena , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:16+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-02 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/turtle.rst:3 -msgid ":mod:`turtle` --- Turtle graphics" -msgstr ":mod:`turtle` --- Gráficos Tartaruga" +msgid ":mod:`!turtle` --- Turtle graphics" +msgstr ":mod:`!turtle` --- Gráficos Tartaruga" #: ../../library/turtle.rst:10 msgid "**Source code:** :source:`Lib/turtle.py`" @@ -137,6 +126,10 @@ msgstr "" "Em um console do Python, faça a importação de todos os objetos do módulo " "denominado ``turtle`` ::" +#: ../../library/turtle.rst:72 +msgid "from turtle import *" +msgstr "from turtle import *" + #: ../../library/turtle.rst:74 msgid "" "If you run into a ``No module named '_tkinter'`` error, you'll have to " @@ -154,6 +147,10 @@ msgstr "Desenho básico" msgid "Send the turtle forward 100 steps::" msgstr "Envie a tartaruga para frente 100 passos::" +#: ../../library/turtle.rst:83 +msgid "forward(100)" +msgstr "forward(100)" + #: ../../library/turtle.rst:85 msgid "" "You should see (most likely, in a new window on your display) a line drawn " @@ -165,10 +162,24 @@ msgstr "" "tartaruga, de modo que ela gire 120 graus para a esquerda (sentido anti-" "horário)::" +#: ../../library/turtle.rst:89 +msgid "left(120)" +msgstr "left(120)" + #: ../../library/turtle.rst:91 msgid "Let's continue by drawing a triangle::" msgstr "Vamos continuar desenhando um triângulo::" +#: ../../library/turtle.rst:93 +msgid "" +"forward(100)\n" +"left(120)\n" +"forward(100)" +msgstr "" +"forward(100)\n" +"left(120)\n" +"forward(100)" + #: ../../library/turtle.rst:97 msgid "" "Notice how the turtle, represented by an arrow, points in different " @@ -217,6 +228,10 @@ msgstr "" "Envie sua tartaruga de volta ao ponto de partida (útil se ela tiver " "desaparecido da tela)::" +#: ../../library/turtle.rst:120 +msgid "home()" +msgstr "home()" + #: ../../library/turtle.rst:122 msgid "" "The home position is at the center of the turtle's screen. If you ever need " @@ -225,6 +240,10 @@ msgstr "" "A posição inicial da tartaruga está no centro da tela. Se você precisar " "conhecê-la, obtenha as coordenadas x-y da tartaruga com::" +#: ../../library/turtle.rst:125 +msgid "pos()" +msgstr "pos()" + #: ../../library/turtle.rst:127 msgid "Home is at ``(0, 0)``." msgstr "A a posição inicial fica em ``(0, 0)``." @@ -237,6 +256,10 @@ msgstr "" "E, depois de um tempo, provavelmente vai querer ajudar a limpar a janela " "aberta para que possamos começar de novo::" +#: ../../library/turtle.rst:132 +msgid "clearscreen()" +msgstr "clearscreen()" + #: ../../library/turtle.rst:136 msgid "Making algorithmic patterns" msgstr "Criação de padrões algorítmicos" @@ -246,6 +269,20 @@ msgid "Using loops, it's possible to build up geometric patterns::" msgstr "" "Usando laços de repetição, é possível construir criar padrões geométricos::" +#: ../../library/turtle.rst:140 +msgid "" +"for steps in range(100):\n" +" for c in ('blue', 'red', 'green'):\n" +" color(c)\n" +" forward(steps)\n" +" right(30)" +msgstr "" +"for steps in range(100):\n" +" for c in ('blue', 'red', 'green'):\n" +" color(c)\n" +" forward(steps)\n" +" right(30)" + #: ../../library/turtle.rst:147 msgid "\\ - which of course, are limited only by the imagination!" msgstr "\\ - que, é claro, são limitados apenas pela imaginação!" @@ -258,6 +295,14 @@ msgstr "" "Vamos desenhar o formato de estrela na parte superior da página. Queremos " "linhas de contorno vermelhas, com preenchimento em amarelo::" +#: ../../library/turtle.rst:152 +msgid "" +"color('red')\n" +"fillcolor('yellow')" +msgstr "" +"color('red')\n" +"fillcolor('yellow')" + #: ../../library/turtle.rst:155 msgid "" "Just as ``up()`` and ``down()`` determine whether lines will be drawn, " @@ -266,10 +311,28 @@ msgstr "" "Assim como ``up()`` e ``down()`` determinam se as linhas serão desenhadas, o " "preenchimento pode ser ativado e desativado::" +#: ../../library/turtle.rst:158 +msgid "begin_fill()" +msgstr "begin_fill()" + #: ../../library/turtle.rst:160 msgid "Next we'll create a loop::" msgstr "Em seguida, vamos criar um laço de repetição::" +#: ../../library/turtle.rst:162 +msgid "" +"while True:\n" +" forward(200)\n" +" left(170)\n" +" if abs(pos()) < 1:\n" +" break" +msgstr "" +"while True:\n" +" forward(200)\n" +" left(170)\n" +" if abs(pos()) < 1:\n" +" break" + #: ../../library/turtle.rst:168 msgid "" "``abs(pos()) < 1`` is a good way to know when the turtle is back at its home " @@ -282,6 +345,10 @@ msgstr "" msgid "Finally, complete the filling::" msgstr "Por fim, complete o preenchimento::" +#: ../../library/turtle.rst:173 +msgid "end_fill()" +msgstr "end_fill()" + #: ../../library/turtle.rst:175 msgid "" "(Note that filling only actually takes place when you give the " @@ -398,6 +465,26 @@ msgstr "" "Recomenda-se usar o módulo ``turtle`` com uma apelido para identificador/" "domínio, conforme descrito acima, por exemplo::" +#: ../../library/turtle.rst:232 +msgid "" +"import turtle as t\n" +"from random import random\n" +"\n" +"for i in range(100):\n" +" steps = int(random() * 100)\n" +" angle = int(random() * 360)\n" +" t.right(angle)\n" +" t.fd(steps)" +msgstr "" +"import turtle as t\n" +"from random import random\n" +"\n" +"for i in range(100):\n" +" steps = int(random() * 100)\n" +" angle = int(random() * 360)\n" +" t.right(angle)\n" +" t.fd(steps)" + #: ../../library/turtle.rst:241 msgid "" "Another step is also required though - as soon as the script ends, Python " @@ -407,6 +494,10 @@ msgstr "" "janela da tartaruga assim que o código acima terminar de ser executado. " "Adicione::" +#: ../../library/turtle.rst:244 +msgid "t.mainloop()" +msgstr "t.mainloop()" + #: ../../library/turtle.rst:246 msgid "" "to the end of the script. The script will now wait to be dismissed and will " @@ -445,15 +536,41 @@ msgid "" "of ``Turtle`` objects). You *can* use the object-oriented approach in the " "shell, but it would be more typical in a Python script." msgstr "" -"Nessa abordagem, os vários comandos do módulo \"turtle\" são métodos de " -"objetos (principalmente objetos de ``Turtle``). Você *pode* usar a " -"abordagem orientada a objetos em console, mas ela " -"seria mais típica em um script Python." +"Nessa abordagem, os vários comandos do módulo turtle são métodos de objetos " +"(principalmente objetos de ``Turtle``). Você *pode* usar a abordagem " +"orientada a objetos em console, mas ela seria mais típica em um script " +"Python." #: ../../library/turtle.rst:265 msgid "The example above then becomes::" msgstr "O exemplo acima se torna então::" +#: ../../library/turtle.rst:267 +msgid "" +"from turtle import Turtle\n" +"from random import random\n" +"\n" +"t = Turtle()\n" +"for i in range(100):\n" +" steps = int(random() * 100)\n" +" angle = int(random() * 360)\n" +" t.right(angle)\n" +" t.fd(steps)\n" +"\n" +"t.screen.mainloop()" +msgstr "" +"from turtle import Turtle\n" +"from random import random\n" +"\n" +"t = Turtle()\n" +"for i in range(100):\n" +" steps = int(random() * 100)\n" +" angle = int(random() * 360)\n" +" t.right(angle)\n" +" t.fd(steps)\n" +"\n" +"t.screen.mainloop()" + #: ../../library/turtle.rst:279 msgid "" "Note the last line. ``t.screen`` is an instance of the :class:`Screen` that " @@ -468,6 +585,14 @@ msgstr "" msgid "The turtle's screen can be customised, for example::" msgstr "A tela da tartaruga pode ser personalizada, por exemplo::" +#: ../../library/turtle.rst:285 +msgid "" +"t.screen.title('Object-oriented turtle demo')\n" +"t.screen.bgcolor(\"orange\")" +msgstr "" +"t.screen.title('Object-oriented turtle demo')\n" +"t.screen.bgcolor(\"orange\")" + #: ../../library/turtle.rst:290 msgid "Turtle graphics reference" msgstr "Referência Gráficos de Tartaruga" @@ -956,6 +1081,26 @@ msgstr "" "Move a tartaruga para frente pela *distance* especificada, na direção em que " "a tartaruga está indo." +#: ../../library/turtle.rst:451 +msgid "" +">>> turtle.position()\n" +"(0.00,0.00)\n" +">>> turtle.forward(25)\n" +">>> turtle.position()\n" +"(25.00,0.00)\n" +">>> turtle.forward(-75)\n" +">>> turtle.position()\n" +"(-50.00,0.00)" +msgstr "" +">>> turtle.position()\n" +"(0.00,0.00)\n" +">>> turtle.forward(25)\n" +">>> turtle.position()\n" +"(25.00,0.00)\n" +">>> turtle.forward(-75)\n" +">>> turtle.position()\n" +"(-50.00,0.00)" + #: ../../library/turtle.rst:468 ../../library/turtle.rst:710 #: ../../library/turtle.rst:977 ../../library/turtle.rst:1485 msgid "a number" @@ -969,6 +1114,20 @@ msgstr "" "Move a tartaruga para trás por *distance*, na direção oposta à direção em " "que a tartaruga está indo. Não muda o rumo da tartaruga." +#: ../../library/turtle.rst:478 +msgid "" +">>> turtle.position()\n" +"(0.00,0.00)\n" +">>> turtle.backward(30)\n" +">>> turtle.position()\n" +"(-30.00,0.00)" +msgstr "" +">>> turtle.position()\n" +"(0.00,0.00)\n" +">>> turtle.backward(30)\n" +">>> turtle.position()\n" +"(-30.00,0.00)" + #: ../../library/turtle.rst:493 msgid "" "Turn turtle right by *angle* units. (Units are by default degrees, but can " @@ -980,6 +1139,20 @@ msgstr "" "func:`radians`.) A orientação do ângulo depende do modo tartaruga, veja :" "func:`mode`." +#: ../../library/turtle.rst:503 +msgid "" +">>> turtle.heading()\n" +"22.0\n" +">>> turtle.right(45)\n" +">>> turtle.heading()\n" +"337.0" +msgstr "" +">>> turtle.heading()\n" +"22.0\n" +">>> turtle.right(45)\n" +">>> turtle.heading()\n" +"337.0" + #: ../../library/turtle.rst:518 msgid "" "Turn turtle left by *angle* units. (Units are by default degrees, but can " @@ -991,6 +1164,20 @@ msgstr "" "func:`radians`.) A orientação do ângulo depende do modo tartaruga, veja :" "func:`mode`." +#: ../../library/turtle.rst:528 +msgid "" +">>> turtle.heading()\n" +"22.0\n" +">>> turtle.left(45)\n" +">>> turtle.heading()\n" +"67.0" +msgstr "" +">>> turtle.heading()\n" +"22.0\n" +">>> turtle.left(45)\n" +">>> turtle.heading()\n" +"67.0" + #: ../../library/turtle.rst:542 msgid "a number or a pair/vector of numbers" msgstr "um número ou um par/vetor de números" @@ -1016,6 +1203,34 @@ msgstr "" "Move a tartaruga para uma posição absoluta. Caso a caneta esteja virada para " "baixo, traça a linha. Não altera a orientação da tartaruga." +#: ../../library/turtle.rst:557 +msgid "" +">>> tp = turtle.pos()\n" +">>> tp\n" +"(0.00,0.00)\n" +">>> turtle.setpos(60,30)\n" +">>> turtle.pos()\n" +"(60.00,30.00)\n" +">>> turtle.setpos((20,80))\n" +">>> turtle.pos()\n" +"(20.00,80.00)\n" +">>> turtle.setpos(tp)\n" +">>> turtle.pos()\n" +"(0.00,0.00)" +msgstr "" +">>> tp = turtle.pos()\n" +">>> tp\n" +"(0.00,0.00)\n" +">>> turtle.setpos(60,30)\n" +">>> turtle.pos()\n" +"(60.00,30.00)\n" +">>> turtle.setpos((20,80))\n" +">>> turtle.pos()\n" +"(20.00,80.00)\n" +">>> turtle.setpos(tp)\n" +">>> turtle.pos()\n" +"(0.00,0.00)" + #: ../../library/turtle.rst:578 msgid "a boolean" msgstr "um valor booleano" @@ -1037,6 +1252,34 @@ msgstr "" "que a linha imaginária percorrida durante o teletransporte atue como uma " "barreira de preenchimento como em goto(x, y)." +#: ../../library/turtle.rst:593 +msgid "" +">>> tp = turtle.pos()\n" +">>> tp\n" +"(0.00,0.00)\n" +">>> turtle.teleport(60)\n" +">>> turtle.pos()\n" +"(60.00,0.00)\n" +">>> turtle.teleport(y=10)\n" +">>> turtle.pos()\n" +"(60.00,10.00)\n" +">>> turtle.teleport(20, 30)\n" +">>> turtle.pos()\n" +"(20.00,30.00)" +msgstr "" +">>> tp = turtle.pos()\n" +">>> tp\n" +"(0.00,0.00)\n" +">>> turtle.teleport(60)\n" +">>> turtle.pos()\n" +"(60.00,0.00)\n" +">>> turtle.teleport(y=10)\n" +">>> turtle.pos()\n" +"(60.00,10.00)\n" +">>> turtle.teleport(20, 30)\n" +">>> turtle.pos()\n" +"(20.00,30.00)" + #: ../../library/turtle.rst:616 msgid "" "Set the turtle's first coordinate to *x*, leave second coordinate unchanged." @@ -1044,6 +1287,20 @@ msgstr "" "Define a primeira coordenada da tartaruga para *x*, deixa a segunda " "coordenada inalterada." +#: ../../library/turtle.rst:625 +msgid "" +">>> turtle.position()\n" +"(0.00,240.00)\n" +">>> turtle.setx(10)\n" +">>> turtle.position()\n" +"(10.00,240.00)" +msgstr "" +">>> turtle.position()\n" +"(0.00,240.00)\n" +">>> turtle.setx(10)\n" +">>> turtle.position()\n" +"(10.00,240.00)" + #: ../../library/turtle.rst:639 msgid "" "Set the turtle's second coordinate to *y*, leave first coordinate unchanged." @@ -1051,6 +1308,20 @@ msgstr "" "Defina a segunda coordenada da tartaruga para *y*, deixa a primeira " "coordenada inalterada." +#: ../../library/turtle.rst:647 +msgid "" +">>> turtle.position()\n" +"(0.00,40.00)\n" +">>> turtle.sety(-10)\n" +">>> turtle.position()\n" +"(0.00,-10.00)" +msgstr "" +">>> turtle.position()\n" +"(0.00,40.00)\n" +">>> turtle.sety(-10)\n" +">>> turtle.position()\n" +"(0.00,-10.00)" + #: ../../library/turtle.rst:662 msgid "" "Set the orientation of the turtle to *to_angle*. Here are some common " @@ -1099,6 +1370,16 @@ msgstr "270 - sul" msgid "270 - west" msgstr "270 - oeste" +#: ../../library/turtle.rst:674 +msgid "" +">>> turtle.setheading(90)\n" +">>> turtle.heading()\n" +"90.0" +msgstr "" +">>> turtle.setheading(90)\n" +">>> turtle.heading()\n" +"90.0" + #: ../../library/turtle.rst:684 msgid "" "Move turtle to the origin -- coordinates (0,0) -- and set its heading to its " @@ -1107,6 +1388,28 @@ msgstr "" "Move a tartaruga para a origem -- coordenadas (0,0) -- e define seu rumo " "para sua orientação inicial (que depende do modo, veja :func:`mode`)." +#: ../../library/turtle.rst:694 +msgid "" +">>> turtle.heading()\n" +"90.0\n" +">>> turtle.position()\n" +"(0.00,-10.00)\n" +">>> turtle.home()\n" +">>> turtle.position()\n" +"(0.00,0.00)\n" +">>> turtle.heading()\n" +"0.0" +msgstr "" +">>> turtle.heading()\n" +"90.0\n" +">>> turtle.position()\n" +"(0.00,-10.00)\n" +">>> turtle.home()\n" +">>> turtle.position()\n" +"(0.00,0.00)\n" +">>> turtle.heading()\n" +"0.0" + #: ../../library/turtle.rst:711 msgid "a number (or ``None``)" msgstr "um número (ou ``None``)" @@ -1143,6 +1446,40 @@ msgstr "" "determina o número de passos a serem usados. Caso não seja informado, será " "calculado automaticamente. Pode ser usado para desenhar polígonos regulares." +#: ../../library/turtle.rst:726 +msgid "" +">>> turtle.home()\n" +">>> turtle.position()\n" +"(0.00,0.00)\n" +">>> turtle.heading()\n" +"0.0\n" +">>> turtle.circle(50)\n" +">>> turtle.position()\n" +"(-0.00,0.00)\n" +">>> turtle.heading()\n" +"0.0\n" +">>> turtle.circle(120, 180) # draw a semicircle\n" +">>> turtle.position()\n" +"(0.00,240.00)\n" +">>> turtle.heading()\n" +"180.0" +msgstr "" +">>> turtle.home()\n" +">>> turtle.position()\n" +"(0.00,0.00)\n" +">>> turtle.heading()\n" +"0.0\n" +">>> turtle.circle(50)\n" +">>> turtle.position()\n" +"(-0.00,0.00)\n" +">>> turtle.heading()\n" +"0.0\n" +">>> turtle.circle(120, 180) # draw a semicircle\n" +">>> turtle.position()\n" +"(0.00,240.00)\n" +">>> turtle.heading()\n" +"180.0" + #: ../../library/turtle.rst:748 msgid "an integer >= 1 (if given)" msgstr "um inteiro >= 1 (caso seja fornecido)" @@ -1159,6 +1496,24 @@ msgstr "" "Desenha um ponto circular com diâmetro *size*, usando *color*. Se *size* não " "for fornecido, o máximo de pensize+4 e 2*pensize será usado." +#: ../../library/turtle.rst:755 +msgid "" +">>> turtle.home()\n" +">>> turtle.dot()\n" +">>> turtle.fd(50); turtle.dot(20, \"blue\"); turtle.fd(50)\n" +">>> turtle.position()\n" +"(100.00,-0.00)\n" +">>> turtle.heading()\n" +"0.0" +msgstr "" +">>> turtle.home()\n" +">>> turtle.dot()\n" +">>> turtle.fd(50); turtle.dot(20, \"blue\"); turtle.fd(50)\n" +">>> turtle.position()\n" +"(100.00,-0.00)\n" +">>> turtle.heading()\n" +"0.0" + #: ../../library/turtle.rst:769 msgid "" "Stamp a copy of the turtle shape onto the canvas at the current turtle " @@ -1169,6 +1524,16 @@ msgstr "" "tartaruga. Retorna um stamp_id para esse carimbo, que pode ser usado para " "excluí-lo chamando ``clearstamp(stamp_id)``." +#: ../../library/turtle.rst:773 +msgid "" +">>> turtle.color(\"blue\")\n" +">>> stamp_id = turtle.stamp()\n" +">>> turtle.fd(50)" +msgstr "" +">>> turtle.color(\"blue\")\n" +">>> stamp_id = turtle.stamp()\n" +">>> turtle.fd(50)" + #: ../../library/turtle.rst:783 msgid "an integer, must be return value of previous :func:`stamp` call" msgstr "" @@ -1178,6 +1543,30 @@ msgstr "" msgid "Delete stamp with given *stampid*." msgstr "Exclui o carimbo com o *stamp* fornecido." +#: ../../library/turtle.rst:788 +msgid "" +">>> turtle.position()\n" +"(150.00,-0.00)\n" +">>> turtle.color(\"blue\")\n" +">>> astamp = turtle.stamp()\n" +">>> turtle.fd(50)\n" +">>> turtle.position()\n" +"(200.00,-0.00)\n" +">>> turtle.clearstamp(astamp)\n" +">>> turtle.position()\n" +"(200.00,-0.00)" +msgstr "" +">>> turtle.position()\n" +"(150.00,-0.00)\n" +">>> turtle.color(\"blue\")\n" +">>> astamp = turtle.stamp()\n" +">>> turtle.fd(50)\n" +">>> turtle.position()\n" +"(200.00,-0.00)\n" +">>> turtle.clearstamp(astamp)\n" +">>> turtle.position()\n" +"(200.00,-0.00)" + #: ../../library/turtle.rst:807 msgid "" "Delete all or first/last *n* of turtle's stamps. If *n* is ``None``, delete " @@ -1188,6 +1577,22 @@ msgstr "" "``None``, exclui todos os carimbos, se *n* > 0 exclui os primeiros *n* " "carimbos, senão se *n* < 0 exclui os últimos *n* carimbos." +#: ../../library/turtle.rst:811 +msgid "" +">>> for i in range(8):\n" +"... unused_stamp_id = turtle.stamp()\n" +"... turtle.fd(30)\n" +">>> turtle.clearstamps(2)\n" +">>> turtle.clearstamps(-2)\n" +">>> turtle.clearstamps()" +msgstr "" +">>> for i in range(8):\n" +"... unused_stamp_id = turtle.stamp()\n" +"... turtle.fd(30)\n" +">>> turtle.clearstamps(2)\n" +">>> turtle.clearstamps(-2)\n" +">>> turtle.clearstamps()" + #: ../../library/turtle.rst:823 msgid "" "Undo (repeatedly) the last turtle action(s). Number of available undo " @@ -1197,6 +1602,20 @@ msgstr "" "ações de desfazer disponíveis é determinado pelo tamanho do buffer de " "desfazer." +#: ../../library/turtle.rst:826 +msgid "" +">>> for i in range(4):\n" +"... turtle.fd(50); turtle.lt(80)\n" +"...\n" +">>> for i in range(8):\n" +"... turtle.undo()" +msgstr "" +">>> for i in range(4):\n" +"... turtle.fd(50); turtle.lt(80)\n" +"...\n" +">>> for i in range(8):\n" +"... turtle.undo()" + #: ../../library/turtle.rst:838 msgid "an integer in the range 0..10 or a speedstring (see below)" msgstr "" @@ -1252,9 +1671,29 @@ msgid "" "Attention: *speed* = 0 means that *no* animation takes place. forward/back " "makes turtle jump and likewise left/right make the turtle turn instantly." msgstr "" -"Atenção: *speed* = 0 significa que *nenhuma* animação ocorre. Para frente/" -"trás faz a tartaruga pular e da mesma forma para esquerda/direita faz a " -"tartaruga girar instantaneamente." +"Atenção: *speed* = 0 significa que *nenhuma* animação ocorre. forward/back " +"faz a tartaruga pular e da mesma forma para left/right faz a tartaruga girar " +"instantaneamente." + +#: ../../library/turtle.rst:859 +msgid "" +">>> turtle.speed()\n" +"3\n" +">>> turtle.speed('normal')\n" +">>> turtle.speed()\n" +"6\n" +">>> turtle.speed(9)\n" +">>> turtle.speed()\n" +"9" +msgstr "" +">>> turtle.speed()\n" +"3\n" +">>> turtle.speed('normal')\n" +">>> turtle.speed()\n" +"6\n" +">>> turtle.speed(9)\n" +">>> turtle.speed()\n" +"9" #: ../../library/turtle.rst:878 msgid "" @@ -1263,6 +1702,14 @@ msgstr "" "Retorna a localização atual da tartaruga (x,y) (como um vetor :class:" "`Vec2D`)." +#: ../../library/turtle.rst:880 +msgid "" +">>> turtle.pos()\n" +"(440.00,-0.00)" +msgstr "" +">>> turtle.pos()\n" +"(440.00,-0.00)" + #: ../../library/turtle.rst:889 ../../library/turtle.rst:952 msgid "a number or a pair/vector of numbers or a turtle instance" msgstr "um número ou um par/vetor de números ou uma instância de tartaruga" @@ -1283,14 +1730,60 @@ msgstr "" "orientação inicial da tartaruga, que depende do modo - \"standard\"/" "\"world\" ou \"logo\"." +#: ../../library/turtle.rst:896 +msgid "" +">>> turtle.goto(10, 10)\n" +">>> turtle.towards(0,0)\n" +"225.0" +msgstr "" +">>> turtle.goto(10, 10)\n" +">>> turtle.towards(0,0)\n" +"225.0" + #: ../../library/turtle.rst:906 msgid "Return the turtle's x coordinate." msgstr "Retorna a coordenada X da tartaruga." +#: ../../library/turtle.rst:908 +msgid "" +">>> turtle.home()\n" +">>> turtle.left(50)\n" +">>> turtle.forward(100)\n" +">>> turtle.pos()\n" +"(64.28,76.60)\n" +">>> print(round(turtle.xcor(), 5))\n" +"64.27876" +msgstr "" +">>> turtle.home()\n" +">>> turtle.left(50)\n" +">>> turtle.forward(100)\n" +">>> turtle.pos()\n" +"(64.28,76.60)\n" +">>> print(round(turtle.xcor(), 5))\n" +"64.27876" + #: ../../library/turtle.rst:922 msgid "Return the turtle's y coordinate." msgstr "Retorna a coordenada Y da tartaruga." +#: ../../library/turtle.rst:924 +msgid "" +">>> turtle.home()\n" +">>> turtle.left(60)\n" +">>> turtle.forward(100)\n" +">>> print(turtle.pos())\n" +"(50.00,86.60)\n" +">>> print(round(turtle.ycor(), 5))\n" +"86.60254" +msgstr "" +">>> turtle.home()\n" +">>> turtle.left(60)\n" +">>> turtle.forward(100)\n" +">>> print(turtle.pos())\n" +"(50.00,86.60)\n" +">>> print(round(turtle.ycor(), 5))\n" +"86.60254" + #: ../../library/turtle.rst:938 msgid "" "Return the turtle's current heading (value depends on the turtle mode, see :" @@ -1299,6 +1792,18 @@ msgstr "" "Retorna o título atual da tartaruga (o valor depende do modo da tartaruga, " "veja :func:`mode`)." +#: ../../library/turtle.rst:941 +msgid "" +">>> turtle.home()\n" +">>> turtle.left(67)\n" +">>> turtle.heading()\n" +"67.0" +msgstr "" +">>> turtle.home()\n" +">>> turtle.left(67)\n" +">>> turtle.heading()\n" +"67.0" + #: ../../library/turtle.rst:955 msgid "" "Return the distance from the turtle to (x,y), the given vector, or the given " @@ -1307,6 +1812,28 @@ msgstr "" "Retorna a distância da tartaruga para (x,y), o vetor dado, ou a outra " "tartaruga dada, em unidades de passo de tartaruga." +#: ../../library/turtle.rst:958 +msgid "" +">>> turtle.home()\n" +">>> turtle.distance(30,40)\n" +"50.0\n" +">>> turtle.distance((30,40))\n" +"50.0\n" +">>> joe = Turtle()\n" +">>> joe.forward(77)\n" +">>> turtle.distance(joe)\n" +"77.0" +msgstr "" +">>> turtle.home()\n" +">>> turtle.distance(30,40)\n" +"50.0\n" +">>> turtle.distance((30,40))\n" +"50.0\n" +">>> joe = Turtle()\n" +">>> joe.forward(77)\n" +">>> turtle.distance(joe)\n" +"77.0" + #: ../../library/turtle.rst:973 msgid "Settings for measurement" msgstr "Configurações de medida" @@ -1319,6 +1846,37 @@ msgstr "" "Define as unidades de medição do ângulo, ou seja, defina o número de " "\"graus\" para um círculo completo. O valor padrão é 360 graus." +#: ../../library/turtle.rst:982 +msgid "" +">>> turtle.home()\n" +">>> turtle.left(90)\n" +">>> turtle.heading()\n" +"90.0\n" +"\n" +">>> # Change angle measurement unit to grad (also known as gon,\n" +">>> # grade, or gradian and equals 1/100-th of the right angle.)\n" +">>> turtle.degrees(400.0)\n" +">>> turtle.heading()\n" +"100.0\n" +">>> turtle.degrees(360)\n" +">>> turtle.heading()\n" +"90.0" +msgstr "" +">>> turtle.home()\n" +">>> turtle.left(90)\n" +">>> turtle.heading()\n" +"90.0\n" +"\n" +">>> # Alterar unidade de medida de ângulo para grad (também\n" +">>> # conhecido como gon, grau ou grado e é igual a 1/100\n" +">>> # do ângulo reto).\n" +">>> turtle.degrees(400.0)\n" +">>> turtle.heading()\n" +"100.0\n" +">>> turtle.degrees(360)\n" +">>> turtle.heading()\n" +"90.0" + #: ../../library/turtle.rst:1002 msgid "" "Set the angle measurement units to radians. Equivalent to ``degrees(2*math." @@ -1327,6 +1885,24 @@ msgstr "" "Define as unidades de medida de ângulo para radianos. Equivalente a " "``degrees(2*math.pi)``." +#: ../../library/turtle.rst:1005 +msgid "" +">>> turtle.home()\n" +">>> turtle.left(90)\n" +">>> turtle.heading()\n" +"90.0\n" +">>> turtle.radians()\n" +">>> turtle.heading()\n" +"1.5707963267948966" +msgstr "" +">>> turtle.home()\n" +">>> turtle.left(90)\n" +">>> turtle.heading()\n" +"90.0\n" +">>> turtle.radians()\n" +">>> turtle.heading()\n" +"1.5707963267948966" + #: ../../library/turtle.rst:1033 msgid "Pull the pen down -- drawing when moving." msgstr "Desce a caneta - desenha ao se mover." @@ -1345,10 +1921,20 @@ msgid "" "\"auto\" and turtleshape is a polygon, that polygon is drawn with the same " "line thickness. If no argument is given, the current pensize is returned." msgstr "" -"Define a espessura da linha para *width* ou retorne-a. Se resizemode estiver " +"Define a espessura da linha para *width* ou retorna-a. Se resizemode estiver " "definido como \"auto\" e a forma de tartaruga for um polígono, esse polígono " "será desenhado com a mesma espessura de linha. Se nenhum argumento for " -"fornecido, o tamanho da pena atual será retornado." +"fornecido, a espessura atual da caneta será retornada." + +#: ../../library/turtle.rst:1052 +msgid "" +">>> turtle.pensize()\n" +"1\n" +">>> turtle.pensize(10) # from here on lines of width 10 are drawn" +msgstr "" +">>> turtle.pensize()\n" +"1\n" +">>> turtle.pensize(10) # from here on lines of width 10 are drawn" #: ../../library/turtle.rst:1062 msgid "a dictionary with some or all of the below listed keys" @@ -1420,12 +2006,60 @@ msgstr "" "ou mais desses atributos podem ser fornecidos como argumentos nomeados. Isso " "pode ser usado para definir vários atributos de caneta em uma instrução." +#: ../../library/turtle.rst:1084 +msgid "" +">>> turtle.pen(fillcolor=\"black\", pencolor=\"red\", pensize=10)\n" +">>> sorted(turtle.pen().items())\n" +"[('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'),\n" +" ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'),\n" +" ('shearfactor', 0.0), ('shown', True), ('speed', 9),\n" +" ('stretchfactor', (1.0, 1.0)), ('tilt', 0.0)]\n" +">>> penstate=turtle.pen()\n" +">>> turtle.color(\"yellow\", \"\")\n" +">>> turtle.penup()\n" +">>> sorted(turtle.pen().items())[:3]\n" +"[('fillcolor', ''), ('outline', 1), ('pencolor', 'yellow')]\n" +">>> turtle.pen(penstate, fillcolor=\"green\")\n" +">>> sorted(turtle.pen().items())[:3]\n" +"[('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red')]" +msgstr "" +">>> turtle.pen(fillcolor=\"black\", pencolor=\"red\", pensize=10)\n" +">>> sorted(turtle.pen().items())\n" +"[('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'),\n" +" ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'),\n" +" ('shearfactor', 0.0), ('shown', True), ('speed', 9),\n" +" ('stretchfactor', (1.0, 1.0)), ('tilt', 0.0)]\n" +">>> penstate=turtle.pen()\n" +">>> turtle.color(\"yellow\", \"\")\n" +">>> turtle.penup()\n" +">>> sorted(turtle.pen().items())[:3]\n" +"[('fillcolor', ''), ('outline', 1), ('pencolor', 'yellow')]\n" +">>> turtle.pen(penstate, fillcolor=\"green\")\n" +">>> sorted(turtle.pen().items())[:3]\n" +"[('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red')]" + #: ../../library/turtle.rst:1105 msgid "Return ``True`` if pen is down, ``False`` if it's up." msgstr "" "Retorna ``True`` se a caneta estiver abaixada, ``False`` se estiver " "levantada." +#: ../../library/turtle.rst:1107 +msgid "" +">>> turtle.penup()\n" +">>> turtle.isdown()\n" +"False\n" +">>> turtle.pendown()\n" +">>> turtle.isdown()\n" +"True" +msgstr "" +">>> turtle.penup()\n" +">>> turtle.isdown()\n" +"False\n" +">>> turtle.pendown()\n" +">>> turtle.isdown()\n" +"True" + #: ../../library/turtle.rst:1123 msgid "Return or set the pencolor." msgstr "Retorna ou define a cor da caneta ou pencolor." @@ -1493,6 +2127,44 @@ msgstr "" "Se a forma da tartaruga for um polígono, o contorno desse polígono será " "desenhado com a nova cor de caneta definida." +#: ../../library/turtle.rst:1148 +msgid "" +">>> colormode()\n" +"1.0\n" +">>> turtle.pencolor()\n" +"'red'\n" +">>> turtle.pencolor(\"brown\")\n" +">>> turtle.pencolor()\n" +"'brown'\n" +">>> tup = (0.2, 0.8, 0.55)\n" +">>> turtle.pencolor(tup)\n" +">>> turtle.pencolor()\n" +"(0.2, 0.8, 0.5490196078431373)\n" +">>> colormode(255)\n" +">>> turtle.pencolor()\n" +"(51.0, 204.0, 140.0)\n" +">>> turtle.pencolor('#32c18f')\n" +">>> turtle.pencolor()\n" +"(50.0, 193.0, 143.0)" +msgstr "" +">>> colormode()\n" +"1.0\n" +">>> turtle.pencolor()\n" +"'red'\n" +">>> turtle.pencolor(\"brown\")\n" +">>> turtle.pencolor()\n" +"'brown'\n" +">>> tup = (0.2, 0.8, 0.55)\n" +">>> turtle.pencolor(tup)\n" +">>> turtle.pencolor()\n" +"(0.2, 0.8, 0.5490196078431373)\n" +">>> colormode(255)\n" +">>> turtle.pencolor()\n" +"(51.0, 204.0, 140.0)\n" +">>> turtle.pencolor('#32c18f')\n" +">>> turtle.pencolor()\n" +"(50.0, 193.0, 143.0)" + #: ../../library/turtle.rst:1172 msgid "Return or set the fillcolor." msgstr "Retorna ou define o fillcolor." @@ -1558,6 +2230,32 @@ msgstr "" "Se turtleshape for um polígono, o interior desse polígono será desenhado com " "a nova cor de preenchimento definida." +#: ../../library/turtle.rst:1197 +msgid "" +">>> turtle.fillcolor(\"violet\")\n" +">>> turtle.fillcolor()\n" +"'violet'\n" +">>> turtle.pencolor()\n" +"(50.0, 193.0, 143.0)\n" +">>> turtle.fillcolor((50, 193, 143)) # Integers, not floats\n" +">>> turtle.fillcolor()\n" +"(50.0, 193.0, 143.0)\n" +">>> turtle.fillcolor('#ffffff')\n" +">>> turtle.fillcolor()\n" +"(255.0, 255.0, 255.0)" +msgstr "" +">>> turtle.fillcolor(\"violet\")\n" +">>> turtle.fillcolor()\n" +"'violet'\n" +">>> turtle.pencolor()\n" +"(50.0, 193.0, 143.0)\n" +">>> turtle.fillcolor((50, 193, 143)) # Inteiros, não pontos flutuantes\n" +">>> turtle.fillcolor()\n" +"(50.0, 193.0, 143.0)\n" +">>> turtle.fillcolor('#ffffff')\n" +">>> turtle.fillcolor()\n" +"(255.0, 255.0, 255.0)" + #: ../../library/turtle.rst:1215 msgid "Return or set pencolor and fillcolor." msgstr "Retorna ou define os valores de pencolor e fillcolor." @@ -1617,6 +2315,22 @@ msgstr "" "Se o turtleshape for um polígono, o contorno e o interior desse polígono " "serão desenhados com as cores recém-definidas." +#: ../../library/turtle.rst:1236 +msgid "" +">>> turtle.color(\"red\", \"green\")\n" +">>> turtle.color()\n" +"('red', 'green')\n" +">>> color(\"#285078\", \"#a0c8f0\")\n" +">>> color()\n" +"((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))" +msgstr "" +">>> turtle.color(\"red\", \"green\")\n" +">>> turtle.color()\n" +"('red', 'green')\n" +">>> color(\"#285078\", \"#a0c8f0\")\n" +">>> color()\n" +"((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))" + #: ../../library/turtle.rst:1247 msgid "See also: Screen method :func:`colormode`." msgstr "Veja também: Método da tela :func:`colormode`." @@ -1626,6 +2340,20 @@ msgid "Return fillstate (``True`` if filling, ``False`` else)." msgstr "" "Retorna fillstate (``True`` se estiver preenchido, ``False`` caso contrário)." +#: ../../library/turtle.rst:1263 +msgid "" +">>> turtle.begin_fill()\n" +">>> if turtle.filling():\n" +"... turtle.pensize(5)\n" +"... else:\n" +"... turtle.pensize(3)" +msgstr "" +">>> turtle.begin_fill()\n" +">>> if turtle.filling():\n" +"... turtle.pensize(5)\n" +"... else:\n" +"... turtle.pensize(3)" + #: ../../library/turtle.rst:1276 msgid "To be called just before drawing a shape to be filled." msgstr "Deve ser chamado antes de desenhar uma forma a ser preenchida." @@ -1647,6 +2375,18 @@ msgstr "" "sobreposição e do número de sobreposições. Por exemplo, a estrela da " "Tartaruga acima pode ser toda amarela ou ter algumas regiões brancas." +#: ../../library/turtle.rst:1288 +msgid "" +">>> turtle.color(\"black\", \"red\")\n" +">>> turtle.begin_fill()\n" +">>> turtle.circle(80)\n" +">>> turtle.end_fill()" +msgstr "" +">>> turtle.color(\"black\", \"red\")\n" +">>> turtle.begin_fill()\n" +">>> turtle.circle(80)\n" +">>> turtle.end_fill()" + #: ../../library/turtle.rst:1302 msgid "" "Delete the turtle's drawings from the screen, re-center the turtle and set " @@ -1655,6 +2395,32 @@ msgstr "" "Remove os desenhos da tartaruga da tela, centraliza novamente a tartaruga e " "define as variáveis para os valores padrões." +#: ../../library/turtle.rst:1305 +msgid "" +">>> turtle.goto(0,-22)\n" +">>> turtle.left(100)\n" +">>> turtle.position()\n" +"(0.00,-22.00)\n" +">>> turtle.heading()\n" +"100.0\n" +">>> turtle.reset()\n" +">>> turtle.position()\n" +"(0.00,0.00)\n" +">>> turtle.heading()\n" +"0.0" +msgstr "" +">>> turtle.goto(0,-22)\n" +">>> turtle.left(100)\n" +">>> turtle.position()\n" +"(0.00,-22.00)\n" +">>> turtle.heading()\n" +"100.0\n" +">>> turtle.reset()\n" +">>> turtle.position()\n" +"(0.00,0.00)\n" +">>> turtle.heading()\n" +"0.0" + #: ../../library/turtle.rst:1323 msgid "" "Delete the turtle's drawings from the screen. Do not move turtle. State " @@ -1703,10 +2469,18 @@ msgstr "" "fazendo algum desenho complexo, pois ocultar a tartaruga acelera o desenho " "de forma visível." +#: ../../library/turtle.rst:1356 +msgid ">>> turtle.hideturtle()" +msgstr ">>> turtle.hideturtle()" + #: ../../library/turtle.rst:1365 msgid "Make the turtle visible." msgstr "Tornar a tartaruga visível." +#: ../../library/turtle.rst:1367 +msgid ">>> turtle.showturtle()" +msgstr ">>> turtle.showturtle()" + #: ../../library/turtle.rst:1375 msgid "Return ``True`` if the Turtle is shown, ``False`` if it's hidden." msgstr "" @@ -1733,6 +2507,20 @@ msgstr "" "\"classic\" (clássico). Para saber mais sobre como lidar com formas, " "consulte o método Screen :func:`register_shape` ." +#: ../../library/turtle.rst:1398 +msgid "" +">>> turtle.shape()\n" +"'classic'\n" +">>> turtle.shape(\"turtle\")\n" +">>> turtle.shape()\n" +"'turtle'" +msgstr "" +">>> turtle.shape()\n" +"'classic'\n" +">>> turtle.shape(\"turtle\")\n" +">>> turtle.shape()\n" +"'turtle'" + #: ../../library/turtle.rst:1410 msgid "one of the strings \"auto\", \"user\", \"noresize\"" msgstr "uma das Strings \"auto\", \"user\", \"noresize\"" @@ -1776,6 +2564,20 @@ msgstr "" "``resizemode(\"user\")`` é chamado por :func:`shapesize` quando usado com " "argumentos." +#: ../../library/turtle.rst:1424 +msgid "" +">>> turtle.resizemode()\n" +"'noresize'\n" +">>> turtle.resizemode(\"auto\")\n" +">>> turtle.resizemode()\n" +"'auto'" +msgstr "" +">>> turtle.resizemode()\n" +"'noresize'\n" +">>> turtle.resizemode(\"auto\")\n" +">>> turtle.resizemode()\n" +"'auto'" + #: ../../library/turtle.rst:1437 ../../library/turtle.rst:1438 #: ../../library/turtle.rst:1439 msgid "positive number" @@ -1797,6 +2599,28 @@ msgstr "" "perpendicular à sua orientação, *stretch_len* é stretchfactor na direção de " "sua orientação, *outline* determina a largura do contorno da forma." +#: ../../library/turtle.rst:1448 +msgid "" +">>> turtle.shapesize()\n" +"(1.0, 1.0, 1)\n" +">>> turtle.resizemode(\"user\")\n" +">>> turtle.shapesize(5, 5, 12)\n" +">>> turtle.shapesize()\n" +"(5, 5, 12)\n" +">>> turtle.shapesize(outline=8)\n" +">>> turtle.shapesize()\n" +"(5, 5, 8)" +msgstr "" +">>> turtle.shapesize()\n" +"(1.0, 1.0, 1)\n" +">>> turtle.resizemode(\"user\")\n" +">>> turtle.shapesize(5, 5, 12)\n" +">>> turtle.shapesize()\n" +"(5, 5, 12)\n" +">>> turtle.shapesize(outline=8)\n" +">>> turtle.shapesize()\n" +"(5, 5, 8)" + #: ../../library/turtle.rst:1464 ../../library/turtle.rst:2101 #: ../../library/turtle.rst:2102 ../../library/turtle.rst:2103 msgid "number (optional)" @@ -1817,6 +2641,20 @@ msgstr "" "Isso é. a tangente do ângulo de shearfactor, pelo qual as linhas paralelas à " "direção da tartaruga são cortadas." +#: ../../library/turtle.rst:1473 +msgid "" +">>> turtle.shape(\"circle\")\n" +">>> turtle.shapesize(5,2)\n" +">>> turtle.shearfactor(0.5)\n" +">>> turtle.shearfactor()\n" +"0.5" +msgstr "" +">>> turtle.shape(\"circle\")\n" +">>> turtle.shapesize(5,2)\n" +">>> turtle.shearfactor(0.5)\n" +">>> turtle.shearfactor()\n" +"0.5" + #: ../../library/turtle.rst:1487 msgid "" "Rotate the turtleshape by *angle* from its current tilt-angle, but do *not* " @@ -1826,6 +2664,24 @@ msgstr "" "inclinação atual, mas *não* altera o rumo da tartaruga (direção do " "movimento)." +#: ../../library/turtle.rst:1490 +msgid "" +">>> turtle.reset()\n" +">>> turtle.shape(\"circle\")\n" +">>> turtle.shapesize(5,2)\n" +">>> turtle.tilt(30)\n" +">>> turtle.fd(50)\n" +">>> turtle.tilt(30)\n" +">>> turtle.fd(50)" +msgstr "" +">>> turtle.reset()\n" +">>> turtle.shape(\"circle\")\n" +">>> turtle.shapesize(5,2)\n" +">>> turtle.tilt(30)\n" +">>> turtle.fd(50)\n" +">>> turtle.tilt(30)\n" +">>> turtle.fd(50)" + #: ../../library/turtle.rst:1504 ../../library/turtle.rst:1527 #: ../../library/turtle.rst:1528 ../../library/turtle.rst:1529 #: ../../library/turtle.rst:1530 @@ -1848,6 +2704,22 @@ msgstr "" "ângulo de inclinação atual, que é o ângulo entre a orientação da forma da " "tartaruga e a direção da tartaruga (sua direção de movimento)." +#: ../../library/turtle.rst:1514 +msgid "" +">>> turtle.reset()\n" +">>> turtle.shape(\"circle\")\n" +">>> turtle.shapesize(5,2)\n" +">>> turtle.tilt(45)\n" +">>> turtle.tiltangle()\n" +"45.0" +msgstr "" +">>> turtle.reset()\n" +">>> turtle.shape(\"circle\")\n" +">>> turtle.shapesize(5,2)\n" +">>> turtle.tilt(45)\n" +">>> turtle.tiltangle()\n" +"45.0" + #: ../../library/turtle.rst:1532 msgid "Set or return the current transformation matrix of the turtle shape." msgstr "" @@ -1870,6 +2742,22 @@ msgstr "" "gerado um erro. Modifica stretchfactor, shearfactor e tiltangle de acordo " "com a matriz fornecida." +#: ../../library/turtle.rst:1543 +msgid "" +">>> turtle = Turtle()\n" +">>> turtle.shape(\"square\")\n" +">>> turtle.shapesize(4,2)\n" +">>> turtle.shearfactor(-0.5)\n" +">>> turtle.shapetransform()\n" +"(4.0, -1.0, -0.0, 2.0)" +msgstr "" +">>> turtle = Turtle()\n" +">>> turtle.shape(\"square\")\n" +">>> turtle.shapesize(4,2)\n" +">>> turtle.shearfactor(-0.5)\n" +">>> turtle.shapetransform()\n" +"(4.0, -1.0, -0.0, 2.0)" + #: ../../library/turtle.rst:1556 msgid "" "Return the current shape polygon as tuple of coordinate pairs. This can be " @@ -1879,6 +2767,18 @@ msgstr "" "Isto pode ser usado para definir uma nova forma ou componentes de uma forma " "composta." +#: ../../library/turtle.rst:1559 +msgid "" +">>> turtle.shape(\"square\")\n" +">>> turtle.shapetransform(4, -1, 0, 2)\n" +">>> turtle.get_shapepoly()\n" +"((50, -20), (30, 20), (-50, 20), (-30, -20))" +msgstr "" +">>> turtle.shape(\"square\")\n" +">>> turtle.shapetransform(4, -1, 0, 2)\n" +">>> turtle.get_shapepoly()\n" +"((50, -20), (30, 20), (-50, 20), (-30, -20))" + #: ../../library/turtle.rst:1574 ../../library/turtle.rst:1596 #: ../../library/turtle.rst:1621 ../../library/turtle.rst:2025 msgid "" @@ -1912,6 +2812,20 @@ msgstr "" "``None``, as associações existentes serão removidas. Exemplo para a " "tartaruga anônima, ou seja, a forma processual:" +#: ../../library/turtle.rst:1584 +msgid "" +">>> def turn(x, y):\n" +"... left(180)\n" +"...\n" +">>> onclick(turn) # Now clicking into the turtle will turn it.\n" +">>> onclick(None) # event-binding will be removed" +msgstr "" +">>> def turn(x, y):\n" +"... left(180)\n" +"...\n" +">>> onclick(turn) # Agora, clicar na tartaruga irá girá-la.\n" +">>> onclick(None) # a associação de eventos será removida" + #: ../../library/turtle.rst:1602 msgid "" "Bind *fun* to mouse-button-release events on this turtle. If *fun* is " @@ -1920,6 +2834,30 @@ msgstr "" "Vincule *fun* aos eventos de liberação do botão do mouse nesta tartaruga. " "Se *fun* for ``None``, as associações existentes serão removidas." +#: ../../library/turtle.rst:1605 +msgid "" +">>> class MyTurtle(Turtle):\n" +"... def glow(self,x,y):\n" +"... self.fillcolor(\"red\")\n" +"... def unglow(self,x,y):\n" +"... self.fillcolor(\"\")\n" +"...\n" +">>> turtle = MyTurtle()\n" +">>> turtle.onclick(turtle.glow) # clicking on turtle turns fillcolor " +"red,\n" +">>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent." +msgstr "" +">>> class MyTurtle(Turtle):\n" +"... def glow(self,x,y):\n" +"... self.fillcolor(\"red\")\n" +"... def unglow(self,x,y):\n" +"... self.fillcolor(\"\")\n" +"...\n" +">>> turtle = MyTurtle()\n" +">>> turtle.onclick(turtle.glow) # clicar na tartaruga torna o " +"preenchimento vermelho,\n" +">>> turtle.onrelease(turtle.unglow) # .liberar a transforma em transparente" + #: ../../library/turtle.rst:1627 msgid "" "Bind *fun* to mouse-move events on this turtle. If *fun* is ``None``, " @@ -1936,6 +2874,10 @@ msgstr "" "Observação: Cada sequência de eventos de movimento do mouse em uma tartaruga " "é precedida por um evento de clique do mouse naquela tartaruga." +#: ../../library/turtle.rst:1633 +msgid ">>> turtle.ondrag(turtle.goto)" +msgstr ">>> turtle.ondrag(turtle.goto)" + #: ../../library/turtle.rst:1638 msgid "" "Subsequently, clicking and dragging the Turtle will move it across the " @@ -1964,6 +2906,30 @@ msgstr "" msgid "Return the last recorded polygon." msgstr "Retorna o último polígono registrado." +#: ../../library/turtle.rst:1661 +msgid "" +">>> turtle.home()\n" +">>> turtle.begin_poly()\n" +">>> turtle.fd(100)\n" +">>> turtle.left(20)\n" +">>> turtle.fd(30)\n" +">>> turtle.left(60)\n" +">>> turtle.fd(50)\n" +">>> turtle.end_poly()\n" +">>> p = turtle.get_poly()\n" +">>> register_shape(\"myFavouriteShape\", p)" +msgstr "" +">>> turtle.home()\n" +">>> turtle.begin_poly()\n" +">>> turtle.fd(100)\n" +">>> turtle.left(20)\n" +">>> turtle.fd(30)\n" +">>> turtle.left(60)\n" +">>> turtle.fd(50)\n" +">>> turtle.end_poly()\n" +">>> p = turtle.get_poly()\n" +">>> register_shape(\"myFavouriteShape\", p)" + #: ../../library/turtle.rst:1678 msgid "" "Create and return a clone of the turtle with same position, heading and " @@ -1972,6 +2938,14 @@ msgstr "" "Cria e retorna um clone da tartaruga com a mesma posição, direção e " "propriedades da tartaruga original." +#: ../../library/turtle.rst:1681 +msgid "" +">>> mick = Turtle()\n" +">>> joe = mick.clone()" +msgstr "" +">>> mick = Turtle()\n" +">>> joe = mick.clone()" + #: ../../library/turtle.rst:1691 msgid "" "Return the Turtle object itself. Only reasonable use: as a function to " @@ -1980,6 +2954,18 @@ msgstr "" "Retorna o próprio objeto Turtle. Uso recomendado: como função para retornar " "a \"tartaruga anônima\":" +#: ../../library/turtle.rst:1694 +msgid "" +">>> pet = getturtle()\n" +">>> pet.fd(50)\n" +">>> pet\n" +"" +msgstr "" +">>> pet = getturtle()\n" +">>> pet.fd(50)\n" +">>> pet\n" +"" + #: ../../library/turtle.rst:1705 msgid "" "Return the :class:`TurtleScreen` object the turtle is drawing on. " @@ -1989,6 +2975,18 @@ msgstr "" "desenhada. Os métodos de TurtleScreen podem então ser chamados para este " "objeto." +#: ../../library/turtle.rst:1708 +msgid "" +">>> ts = turtle.getscreen()\n" +">>> ts\n" +"\n" +">>> ts.bgcolor(\"pink\")" +msgstr "" +">>> ts = turtle.getscreen()\n" +">>> ts\n" +"\n" +">>> ts.bgcolor(\"pink\")" + #: ../../library/turtle.rst:1719 msgid "an integer or ``None``" msgstr "um inteiro ou ``None``" @@ -2005,10 +3003,22 @@ msgstr "" "de ações da tartaruga que podem ser desfeitas pelo método/função :func:" "`undo` . Se *size* for ``None``, o undobuffer será desativado." +#: ../../library/turtle.rst:1726 +msgid ">>> turtle.setundobuffer(42)" +msgstr ">>> turtle.setundobuffer(42)" + #: ../../library/turtle.rst:1734 msgid "Return number of entries in the undobuffer." msgstr "Retorna o número de entradas no undobuffer." +#: ../../library/turtle.rst:1736 +msgid "" +">>> while undobufferentries():\n" +"... undo()" +msgstr "" +">>> while undobufferentries():\n" +"... undo()" + #: ../../library/turtle.rst:1747 msgid "Compound shapes" msgstr "Formas compostas" @@ -2039,10 +3049,32 @@ msgstr "" msgid "For example:" msgstr "Por exemplo:" +#: ../../library/turtle.rst:1759 +msgid "" +">>> s = Shape(\"compound\")\n" +">>> poly1 = ((0,0),(10,-5),(0,10),(-10,-5))\n" +">>> s.addcomponent(poly1, \"red\", \"blue\")\n" +">>> poly2 = ((0,0),(10,-5),(-10,-5))\n" +">>> s.addcomponent(poly2, \"blue\", \"red\")" +msgstr "" +">>> s = Shape(\"compound\")\n" +">>> poly1 = ((0,0),(10,-5),(0,10),(-10,-5))\n" +">>> s.addcomponent(poly1, \"red\", \"blue\")\n" +">>> poly2 = ((0,0),(10,-5),(-10,-5))\n" +">>> s.addcomponent(poly2, \"blue\", \"red\")" + #: ../../library/turtle.rst:1768 msgid "Now add the Shape to the Screen's shapelist and use it:" msgstr "Agora, adicione o Shape à lista de formas da tela e use-o:" +#: ../../library/turtle.rst:1770 +msgid "" +">>> register_shape(\"myshape\", s)\n" +">>> shape(\"myshape\")" +msgstr "" +">>> register_shape(\"myshape\", s)\n" +">>> shape(\"myshape\")" + #: ../../library/turtle.rst:1779 msgid "" "The :class:`Shape` class is used internally by the :func:`register_shape` " @@ -2078,6 +3110,22 @@ msgstr "" msgid "Set or return background color of the TurtleScreen." msgstr "Define ou retorna a cor de fundo do TurtleScreen." +#: ../../library/turtle.rst:1807 +msgid "" +">>> screen.bgcolor(\"orange\")\n" +">>> screen.bgcolor()\n" +"'orange'\n" +">>> screen.bgcolor(\"#800080\")\n" +">>> screen.bgcolor()\n" +"(128.0, 0.0, 128.0)" +msgstr "" +">>> screen.bgcolor(\"orange\")\n" +">>> screen.bgcolor()\n" +"'orange'\n" +">>> screen.bgcolor(\"#800080\")\n" +">>> screen.bgcolor()\n" +"(128.0, 0.0, 128.0)" + #: ../../library/turtle.rst:1820 msgid "a string, name of a gif-file or ``\"nopic\"``, or ``None``" msgstr "um string, um nome de um arquivo gif ou ``\"nopic\"``, ou ``None``" @@ -2095,6 +3143,20 @@ msgstr "" "caso haja. Se *picname* for ``None``, retorna o nome do arquivo da imagem de " "fundo atual:" +#: ../../library/turtle.rst:1827 +msgid "" +">>> screen.bgpic()\n" +"'nopic'\n" +">>> screen.bgpic(\"landscape.gif\")\n" +">>> screen.bgpic()\n" +"\"landscape.gif\"" +msgstr "" +">>> screen.bgpic()\n" +"'nopic'\n" +">>> screen.bgpic(\"landscape.gif\")\n" +">>> screen.bgpic()\n" +"\"landscape.gif\"" + #: ../../library/turtle.rst:1838 msgid "" "This TurtleScreen method is available as a global function only under the " @@ -2198,6 +3260,24 @@ msgstr "" "**ATENÇÃO**: em sistemas de coordenadas definidos pelo usuário, os ângulos " "podem aparecer distorcidos." +#: ../../library/turtle.rst:1899 +msgid "" +">>> screen.reset()\n" +">>> screen.setworldcoordinates(-50,-7.5,50,7.5)\n" +">>> for _ in range(72):\n" +"... left(10)\n" +"...\n" +">>> for _ in range(8):\n" +"... left(45); fd(2) # a regular octagon" +msgstr "" +">>> screen.reset()\n" +">>> screen.setworldcoordinates(-50,-7.5,50,7.5)\n" +">>> for _ in range(72):\n" +"... left(10)\n" +"...\n" +">>> for _ in range(8):\n" +"... left(45); fd(2) # a regular octagon" + #: ../../library/turtle.rst:1924 msgid "positive integer" msgstr "um número inteiro positivo" @@ -2216,6 +3296,20 @@ msgstr "" msgid "Optional argument:" msgstr "Argumentos opcionais:" +#: ../../library/turtle.rst:1932 +msgid "" +">>> screen.delay()\n" +"10\n" +">>> screen.delay(5)\n" +">>> screen.delay()\n" +"5" +msgstr "" +">>> screen.delay()\n" +"10\n" +">>> screen.delay(5)\n" +">>> screen.delay()\n" +"5" + #: ../../library/turtle.rst:1944 ../../library/turtle.rst:1945 msgid "nonnegative integer" msgstr "inteiro não-negativo" @@ -2235,6 +3329,22 @@ msgstr "" "atualmente armazenado de n. O segundo argumento define o valor do atraso " "(consulte :func:`delay`)." +#: ../../library/turtle.rst:1954 +msgid "" +">>> screen.tracer(8, 25)\n" +">>> dist = 2\n" +">>> for i in range(200):\n" +"... fd(dist)\n" +"... rt(90)\n" +"... dist += 2" +msgstr "" +">>> screen.tracer(8, 25)\n" +">>> dist = 2\n" +">>> for i in range(200):\n" +"... fd(dist)\n" +"... rt(90)\n" +"... dist += 2" + #: ../../library/turtle.rst:1967 msgid "Perform a TurtleScreen update. To be used when tracer is turned off." msgstr "" @@ -2276,6 +3386,22 @@ msgstr "" "eventos-chave, o TurtleScreen deve ter o foco. (Veja o método :func:" "`listen`.)" +#: ../../library/turtle.rst:1991 +msgid "" +">>> def f():\n" +"... fd(50)\n" +"... lt(60)\n" +"...\n" +">>> screen.onkey(f, \"Up\")\n" +">>> screen.listen()" +msgstr "" +">>> def f():\n" +"... fd(50)\n" +"... lt(60)\n" +"...\n" +">>> screen.onkey(f, \"Up\")\n" +">>> screen.listen()" + #: ../../library/turtle.rst:2007 msgid "" "Bind *fun* to key-press event of key if key is given, or to any key-press-" @@ -2287,6 +3413,20 @@ msgstr "" "fornecida. Observação: para poder registrar eventos-chave, o TurtleScreen " "deve ter foco. (Veja o método :func:`listen`.)" +#: ../../library/turtle.rst:2012 +msgid "" +">>> def f():\n" +"... fd(50)\n" +"...\n" +">>> screen.onkey(f, \"Up\")\n" +">>> screen.listen()" +msgstr "" +">>> def f():\n" +"... fd(50)\n" +"...\n" +">>> screen.onkey(f, \"Up\")\n" +">>> screen.listen()" + #: ../../library/turtle.rst:2031 msgid "" "Bind *fun* to mouse-click events on this screen. If *fun* is ``None``, " @@ -2303,6 +3443,19 @@ msgstr "" "Exemplo de uma instância de TurtleScreen chamada ``screen`` e uma instância " "de Turtle chamada ``turtle``:" +#: ../../library/turtle.rst:2037 +msgid "" +">>> screen.onclick(turtle.goto) # Subsequently clicking into the " +"TurtleScreen will\n" +">>> # make the turtle move to the clicked " +"point.\n" +">>> screen.onclick(None) # remove event binding again" +msgstr "" +">>> screen.onclick(turtle.goto) # Em seguida, clicar no TurtleScreen\n" +">>> # fará a tartaruga se mover até o ponto " +"clicado.\n" +">>> screen.onclick(None) # remove associação de evento novamente" + #: ../../library/turtle.rst:2045 msgid "" "This TurtleScreen method is available as a global function only under the " @@ -2325,6 +3478,26 @@ msgstr "um número >= 0" msgid "Install a timer that calls *fun* after *t* milliseconds." msgstr "Instala um cronômetro que chama *fun* após *t* milissegundos." +#: ../../library/turtle.rst:2057 +msgid "" +">>> running = True\n" +">>> def f():\n" +"... if running:\n" +"... fd(50)\n" +"... lt(60)\n" +"... screen.ontimer(f, 250)\n" +">>> f() ### makes the turtle march around\n" +">>> running = False" +msgstr "" +">>> running = True\n" +">>> def f():\n" +"... if running:\n" +"... fd(50)\n" +"... lt(60)\n" +"... screen.ontimer(f, 250)\n" +">>> f() ### faz a tartaruga marchar\n" +">>> running = False" + #: ../../library/turtle.rst:2073 msgid "" "Starts event loop - calling Tkinter's mainloop function. Must be the last " @@ -2337,6 +3510,10 @@ msgstr "" "ser usado se um script for executado no IDLE no modo -n (sem subprocesso) - " "para uso interativo de gráficos de tartaruga. ::" +#: ../../library/turtle.rst:2078 +msgid ">>> screen.mainloop()" +msgstr ">>> screen.mainloop()" + #: ../../library/turtle.rst:2086 ../../library/turtle.rst:2087 #: ../../library/turtle.rst:2099 ../../library/turtle.rst:2100 msgid "string" @@ -2355,6 +3532,10 @@ msgstr "" "a string que foi informada. Se a caixa de diálogo for cancelada, retorna " "``None``. ::" +#: ../../library/turtle.rst:2094 +msgid ">>> screen.textinput(\"NIM\", \"Name of first player:\")" +msgstr ">>> screen.textinput(\"NIM\", \"Name of first player:\")" + #: ../../library/turtle.rst:2105 msgid "" "Pop up a dialog window for input of a number. title is the title of the " @@ -2375,6 +3556,14 @@ msgstr "" "retorna o número informado. Se a caixa de diálogo for cancelada, retorna " "``None``. ::" +#: ../../library/turtle.rst:2114 +msgid "" +">>> screen.numinput(\"Poker\", \"Your stakes:\", 1000, minval=10, " +"maxval=10000)" +msgstr "" +">>> screen.numinput(\"Poker\", \"Your stakes:\", 1000, minval=10, " +"maxval=10000)" + #: ../../library/turtle.rst:2122 msgid "one of the strings \"standard\", \"logo\" or \"world\"" msgstr "uma das strings \"standard\", \"logo\" ou \"world\"" @@ -2436,6 +3625,16 @@ msgstr "upward (north)" msgid "clockwise" msgstr "sentido horário" +#: ../../library/turtle.rst:2139 +msgid "" +">>> mode(\"logo\") # resets turtle heading to north\n" +">>> mode()\n" +"'logo'" +msgstr "" +">>> mode(\"logo\") # resets turtle heading to north\n" +">>> mode()\n" +"'logo'" + #: ../../library/turtle.rst:2149 msgid "one of the values 1.0 or 255" msgstr "um dos valroes 1.0 ou 255" @@ -2448,6 +3647,32 @@ msgstr "" "Retorna o modo de cor ou defini-lo como 1,0 ou 255. Posteriormente, os " "valores *r*, *g*, *b* das triplas de cores devem estar no limite 0..*cmode*." +#: ../../library/turtle.rst:2154 +msgid "" +">>> screen.colormode(1)\n" +">>> turtle.pencolor(240, 160, 80)\n" +"Traceback (most recent call last):\n" +" ...\n" +"TurtleGraphicsError: bad color sequence: (240, 160, 80)\n" +">>> screen.colormode()\n" +"1.0\n" +">>> screen.colormode(255)\n" +">>> screen.colormode()\n" +"255\n" +">>> turtle.pencolor(240,160,80)" +msgstr "" +">>> screen.colormode(1)\n" +">>> turtle.pencolor(240, 160, 80)\n" +"Traceback (most recent call last):\n" +" ...\n" +"TurtleGraphicsError: bad color sequence: (240, 160, 80)\n" +">>> screen.colormode()\n" +"1.0\n" +">>> screen.colormode(255)\n" +">>> screen.colormode()\n" +"255\n" +">>> turtle.pencolor(240,160,80)" + #: ../../library/turtle.rst:2172 msgid "" "Return the Canvas of this TurtleScreen. Useful for insiders who know what " @@ -2456,12 +3681,30 @@ msgstr "" "Retorna a tela desse TurtleScreen. Útil para pessoas que sabem o que fazer " "com uma tela do Tkinter." +#: ../../library/turtle.rst:2175 +msgid "" +">>> cv = screen.getcanvas()\n" +">>> cv\n" +"" +msgstr "" +">>> cv = screen.getcanvas()\n" +">>> cv\n" +"" + #: ../../library/turtle.rst:2185 msgid "Return a list of names of all currently available turtle shapes." msgstr "" "Retorna uma lista dos nomes de todas as formas de tartarugas disponíveis no " "momento." +#: ../../library/turtle.rst:2187 +msgid "" +">>> screen.getshapes()\n" +"['arrow', 'blank', 'circle', ..., 'turtle']" +msgstr "" +">>> screen.getshapes()\n" +"['arrow', 'blank', 'circle', ..., 'turtle']" + #: ../../library/turtle.rst:2197 msgid "There are three different ways to call this function:" msgstr "Há três maneiras diferentes de chamar essa função:" @@ -2474,6 +3717,10 @@ msgstr "" "*name* é o nome de um arquivo gif e *shape* é ``None``: Instala a forma de " "imagem correspondente:" +#: ../../library/turtle.rst:2202 +msgid ">>> screen.register_shape(\"turtle.gif\")" +msgstr ">>> screen.register_shape(\"turtle.gif\")" + #: ../../library/turtle.rst:2205 msgid "" "Image shapes *do not* rotate when turning the turtle, so they do not display " @@ -2490,6 +3737,10 @@ msgstr "" "*name* é uma string arbitrária e *shape* é um tupla de pares de coordenadas: " "Instala a forma de polígono correspondente." +#: ../../library/turtle.rst:2211 +msgid ">>> screen.register_shape(\"triangle\", ((5,-3), (0,5), (-5,-3)))" +msgstr ">>> screen.register_shape(\"triangle\", ((5,-3), (0,5), (-5,-3)))" + #: ../../library/turtle.rst:2216 msgid "" "*name* is an arbitrary string and *shape* is a (compound) :class:`Shape` " @@ -2511,14 +3762,38 @@ msgstr "" msgid "Return the list of turtles on the screen." msgstr "Retorne uma lista de tartarugas na tela." +#: ../../library/turtle.rst:2227 +msgid "" +">>> for turtle in screen.turtles():\n" +"... turtle.color(\"red\")" +msgstr "" +">>> for turtle in screen.turtles():\n" +"... turtle.color(\"red\")" + #: ../../library/turtle.rst:2236 msgid "Return the height of the turtle window. ::" msgstr "Retorna a altura da janela da tartaruga. ::" +#: ../../library/turtle.rst:2238 +msgid "" +">>> screen.window_height()\n" +"480" +msgstr "" +">>> screen.window_height()\n" +"480" + #: ../../library/turtle.rst:2244 msgid "Return the width of the turtle window. ::" msgstr "Retorna a largura da janela da tartaruga. ::" +#: ../../library/turtle.rst:2246 +msgid "" +">>> screen.window_width()\n" +"640" +msgstr "" +">>> screen.window_width()\n" +"640" + #: ../../library/turtle.rst:2253 msgid "Methods specific to Screen, not inherited from TurtleScreen" msgstr "" @@ -2590,6 +3865,20 @@ msgstr "" "borda superior da tela; se negativo, define a partir da borda inferior; se " "for ``None``, centraliza a janela verticalmente" +#: ../../library/turtle.rst:2289 +msgid "" +">>> screen.setup (width=200, height=200, startx=0, starty=0)\n" +">>> # sets window to 200x200 pixels, in upper left of screen\n" +">>> screen.setup(width=.75, height=0.5, startx=None, starty=None)\n" +">>> # sets window to 75% of screen by 50% of screen and centers" +msgstr "" +">>> screen.setup (width=200, height=200, startx=0, starty=0)\n" +">>> # define a janela para 200x200 pixels, no canto superior " +"esquerdo da tela\n" +">>> screen.setup(width=.75, height=0.5, startx=None, starty=None)\n" +">>> # define a janela para 75% da tela por 50% da tela e " +"centraliza" + #: ../../library/turtle.rst:2300 msgid "a string that is shown in the titlebar of the turtle graphics window" msgstr "" @@ -2600,6 +3889,10 @@ msgstr "" msgid "Set title of turtle window to *titlestring*." msgstr "Define o título da janela da tartaruga como *titlestring*." +#: ../../library/turtle.rst:2305 +msgid ">>> screen.title(\"Welcome to the turtle zoo!\")" +msgstr ">>> screen.title(\"Welcome to the turtle zoo!\")" + #: ../../library/turtle.rst:2312 msgid "Public classes" msgstr "Classes Públicas" @@ -2728,6 +4021,18 @@ msgstr "uma cor para o contorno do polígono (se fornecido)" msgid "Example:" msgstr "Exemplo:" +#: ../../library/turtle.rst:2376 +msgid "" +">>> poly = ((0,0),(10,-5),(0,10),(-10,-5))\n" +">>> s = Shape(\"compound\")\n" +">>> s.addcomponent(poly, \"red\", \"blue\")\n" +">>> # ... add more components and then use register_shape()" +msgstr "" +">>> poly = ((0,0),(10,-5),(0,10),(-10,-5))\n" +">>> s = Shape(\"compound\")\n" +">>> s.addcomponent(poly, \"red\", \"blue\")\n" +">>> # ... adicione mais componentes e então use register_shape()" + #: ../../library/turtle.rst:2384 msgid "See :ref:`compoundshapes`." msgstr "Veja :ref:`compoundshapes`." @@ -2772,7 +4077,7 @@ msgstr "rotação ``a.rotate(angle)``" #: ../../library/turtle.rst:2406 msgid "Explanation" -msgstr "Explanação" +msgstr "Explicação" #: ../../library/turtle.rst:2408 msgid "" @@ -2871,6 +4176,66 @@ msgstr "" msgid "Calling :func:`help` on methods or functions displays the docstrings::" msgstr "Chamar :func:`help` em métodos ou funções exibe o seguinte docstring::" +#: ../../library/turtle.rst:2453 +msgid "" +">>> help(Screen.bgcolor)\n" +"Help on method bgcolor in module turtle:\n" +"\n" +"bgcolor(self, *args) unbound turtle.Screen method\n" +" Set or return backgroundcolor of the TurtleScreen.\n" +"\n" +" Arguments (if given): a color string or three numbers\n" +" in the range 0..colormode or a 3-tuple of such numbers.\n" +"\n" +"\n" +" >>> screen.bgcolor(\"orange\")\n" +" >>> screen.bgcolor()\n" +" \"orange\"\n" +" >>> screen.bgcolor(0.5,0,0.5)\n" +" >>> screen.bgcolor()\n" +" \"#800080\"\n" +"\n" +">>> help(Turtle.penup)\n" +"Help on method penup in module turtle:\n" +"\n" +"penup(self) unbound turtle.Turtle method\n" +" Pull the pen up -- no drawing when moving.\n" +"\n" +" Aliases: penup | pu | up\n" +"\n" +" No argument\n" +"\n" +" >>> turtle.penup()" +msgstr "" +">>> help(Screen.bgcolor)\n" +"Help on method bgcolor in module turtle:\n" +"\n" +"bgcolor(self, *args) unbound turtle.Screen method\n" +" Set or return backgroundcolor of the TurtleScreen.\n" +"\n" +" Arguments (if given): a color string or three numbers\n" +" in the range 0..colormode or a 3-tuple of such numbers.\n" +"\n" +"\n" +" >>> screen.bgcolor(\"orange\")\n" +" >>> screen.bgcolor()\n" +" \"orange\"\n" +" >>> screen.bgcolor(0.5,0,0.5)\n" +" >>> screen.bgcolor()\n" +" \"#800080\"\n" +"\n" +">>> help(Turtle.penup)\n" +"Help on method penup in module turtle:\n" +"\n" +"penup(self) unbound turtle.Turtle method\n" +" Pull the pen up -- no drawing when moving.\n" +"\n" +" Aliases: penup | pu | up\n" +"\n" +" No argument\n" +"\n" +" >>> turtle.penup()" + #: ../../library/turtle.rst:2482 msgid "" "The docstrings of the functions which are derived from methods have a " @@ -2879,6 +4244,70 @@ msgstr "" "Os docstrings de funções que são derivados do métodos têm um formato " "diferente::" +#: ../../library/turtle.rst:2485 +msgid "" +">>> help(bgcolor)\n" +"Help on function bgcolor in module turtle:\n" +"\n" +"bgcolor(*args)\n" +" Set or return backgroundcolor of the TurtleScreen.\n" +"\n" +" Arguments (if given): a color string or three numbers\n" +" in the range 0..colormode or a 3-tuple of such numbers.\n" +"\n" +" Example::\n" +"\n" +" >>> bgcolor(\"orange\")\n" +" >>> bgcolor()\n" +" \"orange\"\n" +" >>> bgcolor(0.5,0,0.5)\n" +" >>> bgcolor()\n" +" \"#800080\"\n" +"\n" +">>> help(penup)\n" +"Help on function penup in module turtle:\n" +"\n" +"penup()\n" +" Pull the pen up -- no drawing when moving.\n" +"\n" +" Aliases: penup | pu | up\n" +"\n" +" No argument\n" +"\n" +" Example:\n" +" >>> penup()" +msgstr "" +">>> help(bgcolor)\n" +"Help on function bgcolor in module turtle:\n" +"\n" +"bgcolor(*args)\n" +" Set or return backgroundcolor of the TurtleScreen.\n" +"\n" +" Arguments (if given): a color string or three numbers\n" +" in the range 0..colormode or a 3-tuple of such numbers.\n" +"\n" +" Example::\n" +"\n" +" >>> bgcolor(\"orange\")\n" +" >>> bgcolor()\n" +" \"orange\"\n" +" >>> bgcolor(0.5,0,0.5)\n" +" >>> bgcolor()\n" +" \"#800080\"\n" +"\n" +">>> help(penup)\n" +"Help on function penup in module turtle:\n" +"\n" +"penup()\n" +" Pull the pen up -- no drawing when moving.\n" +"\n" +" Aliases: penup | pu | up\n" +"\n" +" No argument\n" +"\n" +" Example:\n" +" >>> penup()" + #: ../../library/turtle.rst:2516 msgid "" "These modified docstrings are created automatically together with the " @@ -2978,6 +4407,50 @@ msgid "" "The built in configuration would correspond to the following ``turtle.cfg``:" msgstr "A configuração que definida no arquivo ``turtle.cfg``:" +#: ../../library/turtle.rst:2562 +msgid "" +"width = 0.5\n" +"height = 0.75\n" +"leftright = None\n" +"topbottom = None\n" +"canvwidth = 400\n" +"canvheight = 300\n" +"mode = standard\n" +"colormode = 1.0\n" +"delay = 10\n" +"undobuffersize = 1000\n" +"shape = classic\n" +"pencolor = black\n" +"fillcolor = black\n" +"resizemode = noresize\n" +"visible = True\n" +"language = english\n" +"exampleturtle = turtle\n" +"examplescreen = screen\n" +"title = Python Turtle Graphics\n" +"using_IDLE = False" +msgstr "" +"width = 0.5\n" +"height = 0.75\n" +"leftright = None\n" +"topbottom = None\n" +"canvwidth = 400\n" +"canvheight = 300\n" +"mode = standard\n" +"colormode = 1.0\n" +"delay = 10\n" +"undobuffersize = 1000\n" +"shape = classic\n" +"pencolor = black\n" +"fillcolor = black\n" +"resizemode = noresize\n" +"visible = True\n" +"language = english\n" +"exampleturtle = turtle\n" +"examplescreen = screen\n" +"title = Python Turtle Graphics\n" +"using_IDLE = False" + #: ../../library/turtle.rst:2585 msgid "Short explanation of selected entries:" msgstr "Breve explicação das entradas selecionadas:" @@ -3090,6 +4563,10 @@ msgstr "" "Esses scripts podem ser executados e visualizados usando o visualizador de " "demonstração fornecido da seguinte forma::" +#: ../../library/turtle.rst:2627 +msgid "python -m turtledemo" +msgstr "python -m turtledemo" + #: ../../library/turtle.rst:2629 msgid "" "Alternatively, you can run the demo scripts individually. For example, ::" @@ -3097,6 +4574,10 @@ msgstr "" "Como alternativa, você pode executar os scripts de demonstração " "individualmente. Por exemplo, ::" +#: ../../library/turtle.rst:2631 +msgid "python -m turtledemo.bytedesign" +msgstr "python -m turtledemo.bytedesign" + #: ../../library/turtle.rst:2633 msgid "The :mod:`turtledemo` package directory contains:" msgstr "O diretório do pacote :mod:`turtledemo` contém:" diff --git a/library/types.po b/library/types.po index 3bf26efc4..dba26c031 100644 --- a/library/types.po +++ b/library/types.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2023 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:16+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -187,16 +185,67 @@ msgstr "" msgid "" "For classes that have an ``__orig_bases__`` attribute, this function returns " "the value of ``cls.__orig_bases__``. For classes without the " -"``__orig_bases__`` attribute, ``cls.__bases__`` is returned." +"``__orig_bases__`` attribute, :attr:`cls.__bases__ ` is " +"returned." msgstr "" "Para classes que possuem um atributo ``__orig_bases__``, esta função retorna " "o valor de ``cls.__orig_bases__``. Para classes sem o atributo " -"``__orig_bases__``, ``cls.__bases__`` é retornado." +"``__orig_bases__``, :attr:`cls.__bases__ ` é retornado." #: ../../library/types.rst:97 msgid "Examples::" msgstr "Exemplos::" +#: ../../library/types.rst:99 +msgid "" +"from typing import TypeVar, Generic, NamedTuple, TypedDict\n" +"\n" +"T = TypeVar(\"T\")\n" +"class Foo(Generic[T]): ...\n" +"class Bar(Foo[int], float): ...\n" +"class Baz(list[str]): ...\n" +"Eggs = NamedTuple(\"Eggs\", [(\"a\", int), (\"b\", str)])\n" +"Spam = TypedDict(\"Spam\", {\"a\": int, \"b\": str})\n" +"\n" +"assert Bar.__bases__ == (Foo, float)\n" +"assert get_original_bases(Bar) == (Foo[int], float)\n" +"\n" +"assert Baz.__bases__ == (list,)\n" +"assert get_original_bases(Baz) == (list[str],)\n" +"\n" +"assert Eggs.__bases__ == (tuple,)\n" +"assert get_original_bases(Eggs) == (NamedTuple,)\n" +"\n" +"assert Spam.__bases__ == (dict,)\n" +"assert get_original_bases(Spam) == (TypedDict,)\n" +"\n" +"assert int.__bases__ == (object,)\n" +"assert get_original_bases(int) == (object,)" +msgstr "" +"from typing import TypeVar, Generic, NamedTuple, TypedDict\n" +"\n" +"T = TypeVar(\"T\")\n" +"class Foo(Generic[T]): ...\n" +"class Bar(Foo[int], float): ...\n" +"class Baz(list[str]): ...\n" +"Eggs = NamedTuple(\"Eggs\", [(\"a\", int), (\"b\", str)])\n" +"Spam = TypedDict(\"Spam\", {\"a\": int, \"b\": str})\n" +"\n" +"assert Bar.__bases__ == (Foo, float)\n" +"assert get_original_bases(Bar) == (Foo[int], float)\n" +"\n" +"assert Baz.__bases__ == (list,)\n" +"assert get_original_bases(Baz) == (list[str],)\n" +"\n" +"assert Eggs.__bases__ == (tuple,)\n" +"assert get_original_bases(Eggs) == (NamedTuple,)\n" +"\n" +"assert Spam.__bases__ == (dict,)\n" +"assert get_original_bases(Spam) == (TypedDict,)\n" +"\n" +"assert int.__bases__ == (object,)\n" +"assert get_original_bases(int) == (object,)" + #: ../../library/types.rst:127 msgid ":pep:`560` - Core support for typing module and generic types" msgstr ":pep:`560` - Suporte básico para módulo typing e tipos genéricos" @@ -322,10 +371,10 @@ msgstr "" #: ../../library/types.rst:201 msgid "" "The type for cell objects: such objects are used as containers for a " -"function's free variables." +"function's :term:`closure variables `." msgstr "" "O tipo para objetos de célula: tais objetos são usados como contêineres para " -"as variáveis livres de uma função." +"as :term:`variáveis de clausura ` de uma função." #: ../../library/types.rst:209 msgid "The type of methods of user-defined class instances." @@ -383,100 +432,41 @@ msgstr "" "O tipo de :term:`módulos `. O construtor aceita o nome do módulo a " "ser criado e, opcionalmente, seu :term:`docstring`." -#: ../../library/types.rst:264 -msgid "" -"Use :func:`importlib.util.module_from_spec` to create a new module if you " -"wish to set the various import-controlled attributes." -msgstr "" -"Use :func:`importlib.util.module_from_spec` para criar um novo módulo se " -"você deseja definir os vários atributos controlados por importação." - -#: ../../library/types.rst:269 -msgid "The :term:`docstring` of the module. Defaults to ``None``." -msgstr "A :term:`docstring` do módulo. O padrão é ``None``." - -#: ../../library/types.rst:273 -msgid "The :term:`loader` which loaded the module. Defaults to ``None``." -msgstr "O :term:`carregador` que carregou o módulo. O padrão é ``None``." - -#: ../../library/types.rst:275 -msgid "" -"This attribute is to match :attr:`importlib.machinery.ModuleSpec.loader` as " -"stored in the :attr:`__spec__` object." -msgstr "" -"Este atributo deve corresponder ao :attr:`importlib.machinery.ModuleSpec." -"loader` conforme armazenado no objeto :attr:`__spec__`." - -#: ../../library/types.rst:279 -msgid "" -"A future version of Python may stop setting this attribute by default. To " -"guard against this potential change, preferably read from the :attr:" -"`__spec__` attribute instead or use ``getattr(module, \"__loader__\", " -"None)`` if you explicitly need to use this attribute." -msgstr "" -"Uma versão futura do Python pode parar de definir esse atributo por padrão. " -"Para se proteger contra esta mudança potencial, de preferência leia o " -"atributo :attr:`__spec__` ou use ``getattr(module, \"__loader__\", None)`` " -"se você explicitamente precisar usar este atributo." - -#: ../../library/types.rst:285 ../../library/types.rst:310 -msgid "Defaults to ``None``. Previously the attribute was optional." -msgstr "O padrão é ``None``. Anteriormente, o atributo era opcional." - -#: ../../library/types.rst:290 -msgid "" -"The name of the module. Expected to match :attr:`importlib.machinery." -"ModuleSpec.name`." -msgstr "" -"O nome do módulo. Espera-se corresponder a :attr:`importlib.machinery." -"ModuleSpec.name`." - -#: ../../library/types.rst:295 -msgid "" -"Which :term:`package` a module belongs to. If the module is top-level (i.e. " -"not a part of any specific package) then the attribute should be set to " -"``''``, else it should be set to the name of the package (which can be :attr:" -"`__name__` if the module is a package itself). Defaults to ``None``." -msgstr "" -"A qual :term:`pacote` um módulo pertence. Se o módulo é de nível superior " -"(ou seja, não faz parte de nenhum pacote específico), o atributo deve ser " -"definido como ``''``, senão deve ser definido como o nome do pacote (que " -"pode ser :attr:`__name__` se o módulo for o próprio pacote). O padrão é " -"``None``." +#: ../../library/types.rst:265 +msgid ":ref:`Documentation on module objects `" +msgstr ":ref:`Documentação em objetos de módulo `" -#: ../../library/types.rst:300 +#: ../../library/types.rst:266 msgid "" -"This attribute is to match :attr:`importlib.machinery.ModuleSpec.parent` as " -"stored in the :attr:`__spec__` object." +"Provides details on the special attributes that can be found on instances " +"of :class:`!ModuleType`." msgstr "" -"Este atributo deve corresponder ao :attr:`importlib.machinery.ModuleSpec." -"parent` conforme armazenado no objeto :attr:`__spec__`." +"Fornece detalhes sobre os atributos especiais que podem ser encontrados em " +"instâncias de :class:`!ModuleType`." -#: ../../library/types.rst:304 -msgid "" -"A future version of Python may stop setting this attribute by default. To " -"guard against this potential change, preferably read from the :attr:" -"`__spec__` attribute instead or use ``getattr(module, \"__package__\", " -"None)`` if you explicitly need to use this attribute." -msgstr "" -"Uma versão futura do Python pode parar de definir este atributo por padrão. " -"Para se proteger contra esta mudança potencial, de preferência leia o " -"atributo :attr:`__spec__` ou use ``getattr(module, \"__package__\", None)`` " -"se você explicitamente precisar usar este atributo." +#: ../../library/types.rst:269 +msgid ":func:`importlib.util.module_from_spec`" +msgstr ":func:`importlib.util.module_from_spec`" -#: ../../library/types.rst:315 +#: ../../library/types.rst:270 msgid "" -"A record of the module's import-system-related state. Expected to be an " -"instance of :class:`importlib.machinery.ModuleSpec`." +"Modules created using the :class:`!ModuleType` constructor are created with " +"many of their special attributes unset or set to default values. :func:`!" +"module_from_spec` provides a more robust way of creating :class:`!" +"ModuleType` instances which ensures the various attributes are set " +"appropriately." msgstr "" -"Um registro do estado relacionado ao sistema de importação do módulo. Espera-" -"se que seja uma instância de :class:`importlib.machinery.ModuleSpec`." +"Módulos criados usando o construtor :class:`!ModuleType` são criados com " +"muitos de seus atributos especiais não definidos ou definidos com valores " +"padrão. :func:`!module_from_spec` fornece uma maneira mais robusta de criar " +"instâncias :class:`!ModuleType`, o que garante que os vários atributos sejam " +"definidos adequadamente." -#: ../../library/types.rst:323 +#: ../../library/types.rst:278 msgid "The type of :data:`Ellipsis`." msgstr "O tipo de :data:`Ellipsis`." -#: ../../library/types.rst:329 +#: ../../library/types.rst:284 msgid "" "The type of :ref:`parameterized generics ` such as " "``list[int]``." @@ -484,7 +474,7 @@ msgstr "" "O tipo dos :ref:`genéricos parametrizados ` como " "``list[int]``." -#: ../../library/types.rst:332 +#: ../../library/types.rst:287 msgid "" "``t_origin`` should be a non-parameterized generic class, such as ``list``, " "``tuple`` or ``dict``. ``t_args`` should be a :class:`tuple` (possibly of " @@ -494,32 +484,48 @@ msgstr "" "``tuple`` ou ``dict``. ``t_args`` deve ser uma :class:`tuple` " "(possivelmente com comprimento 1) de tipos que parametrizam ``t_origin``::" -#: ../../library/types.rst:345 +#: ../../library/types.rst:291 +msgid "" +">>> from types import GenericAlias\n" +"\n" +">>> list[int] == GenericAlias(list, (int,))\n" +"True\n" +">>> dict[str, int] == GenericAlias(dict, (str, int))\n" +"True" +msgstr "" +">>> from types import GenericAlias\n" +"\n" +">>> list[int] == GenericAlias(list, (int,))\n" +"True\n" +">>> dict[str, int] == GenericAlias(dict, (str, int))\n" +"True" + +#: ../../library/types.rst:300 msgid "This type can now be subclassed." msgstr "Este tipo pode agora ter uma subclasse." -#: ../../library/types.rst:350 +#: ../../library/types.rst:305 msgid ":ref:`Generic Alias Types`" msgstr ":ref:`Tipos Generic Alias `" -#: ../../library/types.rst:351 +#: ../../library/types.rst:306 msgid "In-depth documentation on instances of :class:`!types.GenericAlias`" msgstr "" "Documentação detalhada sobre instâncias de :class:`!types.GenericAlias`" -#: ../../library/types.rst:353 +#: ../../library/types.rst:308 msgid ":pep:`585` - Type Hinting Generics In Standard Collections" msgstr ":pep:`585` - Sugestão de tipo para Genéricos em coleções padrão" -#: ../../library/types.rst:354 +#: ../../library/types.rst:309 msgid "Introducing the :class:`!types.GenericAlias` class" msgstr "Apresentação da classe :class:`!types.GenericAlias`" -#: ../../library/types.rst:358 +#: ../../library/types.rst:313 msgid "The type of :ref:`union type expressions`." msgstr " O tipo de :ref:`expressões de tipo união `." -#: ../../library/types.rst:364 +#: ../../library/types.rst:319 msgid "" "The type of traceback objects such as found in ``sys.exception()." "__traceback__``." @@ -527,7 +533,7 @@ msgstr "" "O tipo de objetos traceback, como encontrados em ``sys.exception()." "__traceback__``." -#: ../../library/types.rst:366 +#: ../../library/types.rst:321 msgid "" "See :ref:`the language reference ` for details of the " "available attributes and operations, and guidance on creating tracebacks " @@ -537,7 +543,7 @@ msgstr "" "atributos e operações disponíveis, e orientação sobre como criar tracebacks " "dinamicamente." -#: ../../library/types.rst:373 +#: ../../library/types.rst:328 msgid "" "The type of :ref:`frame objects ` such as found in :attr:`tb." "tb_frame ` if ``tb`` is a traceback object." @@ -545,7 +551,7 @@ msgstr "" "O tipo de :ref:`objetos de quadro ` como encontrado em :attr:" "`tb.tb_frame ` se ``tb`` é um objeto traceback." -#: ../../library/types.rst:379 +#: ../../library/types.rst:334 msgid "" "The type of objects defined in extension modules with ``PyGetSetDef``, such " "as :attr:`FrameType.f_locals ` or ``array.array.typecode``. " @@ -559,7 +565,7 @@ msgstr "" "mesmo propósito que o tipo :class:`property`, mas para classes definidas em " "módulos de extensão." -#: ../../library/types.rst:388 +#: ../../library/types.rst:343 msgid "" "The type of objects defined in extension modules with ``PyMemberDef``, such " "as ``datetime.timedelta.days``. This type is used as descriptor for simple " @@ -573,19 +579,19 @@ msgstr "" "propósito que o tipo :class:`property`, mas para classes definidas em " "módulos de extensão." -#: ../../library/types.rst:393 +#: ../../library/types.rst:348 msgid "" "In addition, when a class is defined with a :attr:`~object.__slots__` " "attribute, then for each slot, an instance of :class:`!MemberDescriptorType` " "will be added as an attribute on the class. This allows the slot to appear " -"in the class's :attr:`~object.__dict__`." +"in the class's :attr:`~type.__dict__`." msgstr "" "Além disso, quando uma classe é definida com um atributo :attr:`~object." "__slots__`, então para cada atributo, uma instância de :class:`!" "MemberDescriptorType` será adicionada como um atributo na classe. Isso " -"permite que o atributo apareça no :attr:`~object.__dict__` da classe." +"permite que o atributo apareça no :attr:`~type.__dict__` da classe." -#: ../../library/types.rst:399 +#: ../../library/types.rst:354 msgid "" "In other implementations of Python, this type may be identical to " "``GetSetDescriptorType``." @@ -593,7 +599,7 @@ msgstr "" "Em outras implementações de Python, este tipo pode ser idêntico a " "``GetSetDescriptorType``." -#: ../../library/types.rst:404 +#: ../../library/types.rst:359 msgid "" "Read-only proxy of a mapping. It provides a dynamic view on the mapping's " "entries, which means that when the mapping changes, the view reflects these " @@ -603,7 +609,7 @@ msgstr "" "entradas do mapeamento, o que significa que quando o mapeamento muda, a " "visão reflete essas mudanças." -#: ../../library/types.rst:412 +#: ../../library/types.rst:367 msgid "" "Updated to support the new union (``|``) operator from :pep:`584`, which " "simply delegates to the underlying mapping." @@ -611,14 +617,14 @@ msgstr "" "Atualizado para ter suporte ao novo operador de união (``|``) da :pep:`584`, " "que simplesmente delega para o mapeamento subjacente." -#: ../../library/types.rst:417 +#: ../../library/types.rst:372 msgid "" "Return ``True`` if the underlying mapping has a key *key*, else ``False``." msgstr "" "Retorna ``True`` se o mapeamento subjacente tiver uma chave *key*, senão " "``False``." -#: ../../library/types.rst:422 +#: ../../library/types.rst:377 msgid "" "Return the item of the underlying mapping with key *key*. Raises a :exc:" "`KeyError` if *key* is not in the underlying mapping." @@ -626,7 +632,7 @@ msgstr "" "Retorna e o item do mapeamento subjacente com a chave *key*. Levanta um :exc:" "`KeyError` se *key* não estiver no mapeamento subjacente." -#: ../../library/types.rst:427 +#: ../../library/types.rst:382 msgid "" "Return an iterator over the keys of the underlying mapping. This is a " "shortcut for ``iter(proxy.keys())``." @@ -634,15 +640,15 @@ msgstr "" "Retorna um iterador sobre as chaves do mapeamento subjacente. Este é um " "atalho para ``iter(proxy.keys())``." -#: ../../library/types.rst:432 +#: ../../library/types.rst:387 msgid "Return the number of items in the underlying mapping." msgstr "Retorna o número de itens no mapeamento subjacente." -#: ../../library/types.rst:436 +#: ../../library/types.rst:391 msgid "Return a shallow copy of the underlying mapping." msgstr "Retorna uma cópia rasa do mapeamento subjacente." -#: ../../library/types.rst:440 +#: ../../library/types.rst:395 msgid "" "Return the value for *key* if *key* is in the underlying mapping, else " "*default*. If *default* is not given, it defaults to ``None``, so that this " @@ -652,38 +658,38 @@ msgstr "" "contrário, *default*. Se *default* não for fornecido, o padrão é ``None``, " "de forma que este método nunca levante uma :exc:`KeyError`." -#: ../../library/types.rst:446 +#: ../../library/types.rst:401 msgid "" "Return a new view of the underlying mapping's items (``(key, value)`` pairs)." msgstr "" "Retorna uma nova visão dos itens do mapeamento subjacente (pares ``(chave, " "valor)``)." -#: ../../library/types.rst:451 +#: ../../library/types.rst:406 msgid "Return a new view of the underlying mapping's keys." msgstr "Retorna uma nova visão das chaves do mapeamento subjacente." -#: ../../library/types.rst:455 +#: ../../library/types.rst:410 msgid "Return a new view of the underlying mapping's values." msgstr "Retorna uma nova visão dos valores do mapeamento subjacente." -#: ../../library/types.rst:459 +#: ../../library/types.rst:414 msgid "Return a reverse iterator over the keys of the underlying mapping." msgstr "Retorna um iterador reverso sobre as chaves do mapeamento subjacente." -#: ../../library/types.rst:465 +#: ../../library/types.rst:420 msgid "Return a hash of the underlying mapping." msgstr "Retorna um hash do mapeamento subjacente." -#: ../../library/types.rst:471 +#: ../../library/types.rst:426 msgid "The type of :ref:`capsule objects `." msgstr "O tipo de :ref:`objetos cápsula `." -#: ../../library/types.rst:477 +#: ../../library/types.rst:432 msgid "Additional Utility Classes and Functions" msgstr "Classes e funções de utilidades adicionais" -#: ../../library/types.rst:481 +#: ../../library/types.rst:436 msgid "" "A simple :class:`object` subclass that provides attribute access to its " "namespace, as well as a meaningful repr." @@ -691,7 +697,7 @@ msgstr "" "Uma subclasse :class:`object` simples que fornece acesso de atributo ao seu " "espaço de nomes, bem como um repr significativo." -#: ../../library/types.rst:484 +#: ../../library/types.rst:439 msgid "" "Unlike :class:`object`, with :class:`!SimpleNamespace` you can add and " "remove attributes." @@ -699,7 +705,7 @@ msgstr "" "Ao contrário de :class:`object`, com :class:`!SimpleNamespace` você pode " "adicionar e remover atributos." -#: ../../library/types.rst:487 +#: ../../library/types.rst:442 msgid "" ":py:class:`SimpleNamespace` objects may be initialized in the same way as :" "class:`dict`: either with keyword arguments, with a single positional " @@ -718,11 +724,43 @@ msgstr "" "objeto mapeamento ou um objeto :term:`iterável` produzindo pares de valores-" "chave). Todas essas chaves devem ser strings." -#: ../../library/types.rst:498 +#: ../../library/types.rst:453 msgid "The type is roughly equivalent to the following code::" msgstr "O tipo é aproximadamente equivalente ao seguinte código::" -#: ../../library/types.rst:514 +#: ../../library/types.rst:455 +msgid "" +"class SimpleNamespace:\n" +" def __init__(self, mapping_or_iterable=(), /, **kwargs):\n" +" self.__dict__.update(mapping_or_iterable)\n" +" self.__dict__.update(kwargs)\n" +"\n" +" def __repr__(self):\n" +" items = (f\"{k}={v!r}\" for k, v in self.__dict__.items())\n" +" return \"{}({})\".format(type(self).__name__, \", \".join(items))\n" +"\n" +" def __eq__(self, other):\n" +" if isinstance(self, SimpleNamespace) and isinstance(other, " +"SimpleNamespace):\n" +" return self.__dict__ == other.__dict__\n" +" return NotImplemented" +msgstr "" +"class SimpleNamespace:\n" +" def __init__(self, mapping_or_iterable=(), /, **kwargs):\n" +" self.__dict__.update(mapping_or_iterable)\n" +" self.__dict__.update(kwargs)\n" +"\n" +" def __repr__(self):\n" +" items = (f\"{k}={v!r}\" for k, v in self.__dict__.items())\n" +" return \"{}({})\".format(type(self).__name__, \", \".join(items))\n" +"\n" +" def __eq__(self, other):\n" +" if isinstance(self, SimpleNamespace) and isinstance(other, " +"SimpleNamespace):\n" +" return self.__dict__ == other.__dict__\n" +" return NotImplemented" + +#: ../../library/types.rst:469 msgid "" "``SimpleNamespace`` may be useful as a replacement for ``class NS: pass``. " "However, for a structured record type use :func:`~collections.namedtuple` " @@ -732,13 +770,13 @@ msgstr "" "pass``. No entanto, para um tipo de registro estruturado, use :func:" "`~collections.namedtuple`." -#: ../../library/types.rst:518 +#: ../../library/types.rst:473 msgid "" ":class:`!SimpleNamespace` objects are supported by :func:`copy.replace`." msgstr "" "Objetos :class:`!SimpleNamespace` são suportados por :func:`copy.replace`." -#: ../../library/types.rst:522 +#: ../../library/types.rst:477 msgid "" "Attribute order in the repr changed from alphabetical to insertion (like " "``dict``)." @@ -746,15 +784,15 @@ msgstr "" "A ordem dos atributos no repr mudou de alfabética para inserção (como no " "``dict``)." -#: ../../library/types.rst:526 +#: ../../library/types.rst:481 msgid "Added support for an optional positional argument." msgstr "Adicionado suporte para um argumento posicional opcional." -#: ../../library/types.rst:531 +#: ../../library/types.rst:486 msgid "Route attribute access on a class to __getattr__." msgstr "Roteia o acesso ao atributo em uma classe para __getattr__." -#: ../../library/types.rst:533 +#: ../../library/types.rst:488 msgid "" "This is a descriptor, used to define attributes that act differently when " "accessed through an instance and through a class. Instance access remains " @@ -767,7 +805,7 @@ msgstr "" "por meio de uma classe será roteado para o método __getattr__ da classe; " "isso é feito levantando AttributeError." -#: ../../library/types.rst:538 +#: ../../library/types.rst:493 msgid "" "This allows one to have properties active on an instance, and have virtual " "attributes on the class with the same name (see :class:`enum.Enum` for an " @@ -777,11 +815,11 @@ msgstr "" "virtuais na classe com o mesmo nome (veja :class:`enum.Enum` para um " "exemplo)." -#: ../../library/types.rst:545 +#: ../../library/types.rst:500 msgid "Coroutine Utility Functions" msgstr "Funções de utilidade de corrotina" -#: ../../library/types.rst:549 +#: ../../library/types.rst:504 msgid "" "This function transforms a :term:`generator` function into a :term:" "`coroutine function` which returns a generator-based coroutine. The " @@ -797,11 +835,11 @@ msgstr "" "entanto, pode não necessariamente implementar o método :meth:`~object." "__await__`." -#: ../../library/types.rst:556 +#: ../../library/types.rst:511 msgid "If *gen_func* is a generator function, it will be modified in-place." msgstr "Se *gen_func* for uma função geradora, ela será modificada no local." -#: ../../library/types.rst:558 +#: ../../library/types.rst:513 msgid "" "If *gen_func* is not a generator function, it will be wrapped. If it returns " "an instance of :class:`collections.abc.Generator`, the instance will be " diff --git a/library/typing.po b/library/typing.po index 3c1b55868..d68d558e9 100644 --- a/library/typing.po +++ b/library/typing.po @@ -1,44 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Augusta Carla Klug , 2021 -# Vinicius Gubiani Ferreira , 2021 -# Vitor Buxbaum Orlandi, 2021 -# Italo Penaforte , 2022 -# Hildeberto Abreu Magalhães , 2022 -# Rodrigo Cândido, 2022 -# Marco Rougeth , 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# Danilo Lima , 2023 -# i17obot , 2023 -# Cezar Peixeiro , 2023 -# Julio Biason, 2023 -# Rafael Fontenelle , 2024 -# Juliano Naves , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-20 00:52+0000\n" -"PO-Revision-Date: 2021-06-28 01:16+0000\n" -"Last-Translator: Juliano Naves , 2024\n" +"POT-Creation-Date: 2025-05-08 03:57+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/typing.rst:3 -msgid ":mod:`typing` --- Support for type hints" -msgstr ":mod:`typing` --- Suporte para dicas de tipo" +msgid ":mod:`!typing` --- Support for type hints" +msgstr ":mod:`!typing` --- Suporte para dicas de tipo" #: ../../library/typing.rst:16 msgid "**Source code:** :source:`Lib/typing.py`" @@ -50,7 +37,7 @@ msgid "" "They can be used by third party tools such as :term:`type checkers `, IDEs, linters, etc." msgstr "" -"O tempo de execução do Python não força anotações de tipos de variáveis e " +"O ambiente de execução do Python não força anotações de tipos de variáveis e " "funções. Elas podem ser usadas por ferramentas de terceiros como :term:" "`verificadores de tipo `, IDEs, linters, etc." @@ -62,6 +49,14 @@ msgstr "Este módulo fornece suporte em tempo de execução para dicas de tipo." msgid "Consider the function below::" msgstr "Considere a função abaixo::" +#: ../../library/typing.rst:30 +msgid "" +"def surface_area_of_cube(edge_length: float) -> str:\n" +" return f\"The surface area of the cube is {6 * edge_length ** 2}.\"" +msgstr "" +"def surface_area_of_cube(edge_length: float) -> str:\n" +" return f\"A área superficial de um cubo é {6 * edge_length ** 2}.\"" + #: ../../library/typing.rst:33 msgid "" "The function ``surface_area_of_cube`` takes an argument expected to be an " @@ -127,10 +122,9 @@ msgstr "" "inglês)." #: ../../library/typing.rst:56 -msgid "" -"`\"Static Typing with Python\" `_" +msgid "`\"Static Typing with Python\" `_" msgstr "" -"`\"Tipagem Estática com Python\" `_" +"`\"Tipagem Estática com Python\" `_" #: ../../library/typing.rst:57 msgid "" @@ -149,11 +143,11 @@ msgstr "Especificação para o sistema de tipos do Python" msgid "" "The canonical, up-to-date specification of the Python type system can be " "found at `\"Specification for the Python type system\" `_." +"python.org/en/latest/spec/index.html>`_." msgstr "" "A especificação canônica e atualizada do sistema de tipos Python pode ser " "encontrada em `\"Specification for the Python type system\" `_." +"python.org/en/latest/spec/index.html>`_." #: ../../library/typing.rst:72 msgid "Type aliases" @@ -170,6 +164,25 @@ msgstr "" "exemplo, ``Vector`` e ``list[float]`` serão tratados de maneira equivalente " "pelos verificadores de tipo estático::" +#: ../../library/typing.rst:79 +msgid "" +"type Vector = list[float]\n" +"\n" +"def scale(scalar: float, vector: Vector) -> Vector:\n" +" return [scalar * num for num in vector]\n" +"\n" +"# passes type checking; a list of floats qualifies as a Vector.\n" +"new_vector = scale(2.0, [1.0, -4.2, 5.4])" +msgstr "" +"type Vector = list[float]\n" +"\n" +"def scale(scalar: float, vector: Vector) -> Vector:\n" +" return [scalar * num for num in vector]\n" +"\n" +"# passa na verificação de tipos; uma lista de floats é qualificada como " +"Vector.\n" +"new_vector = scale(2.0, [1.0, -4.2, 5.4])" + #: ../../library/typing.rst:87 msgid "" "Type aliases are useful for simplifying complex type signatures. For " @@ -178,15 +191,55 @@ msgstr "" "Apelidos de tipo são úteis para simplificar assinaturas de tipo complexas. " "Por exemplo::" +#: ../../library/typing.rst:89 +msgid "" +"from collections.abc import Sequence\n" +"\n" +"type ConnectionOptions = dict[str, str]\n" +"type Address = tuple[str, int]\n" +"type Server = tuple[Address, ConnectionOptions]\n" +"\n" +"def broadcast_message(message: str, servers: Sequence[Server]) -> None:\n" +" ...\n" +"\n" +"# The static type checker will treat the previous type signature as\n" +"# being exactly equivalent to this one.\n" +"def broadcast_message(\n" +" message: str,\n" +" servers: Sequence[tuple[tuple[str, int], dict[str, str]]]\n" +") -> None:\n" +" ..." +msgstr "" +"from collections.abc import Sequence\n" +"\n" +"type ConnectionOptions = dict[str, str]\n" +"type Address = tuple[str, int]\n" +"type Server = tuple[Address, ConnectionOptions]\n" +"\n" +"def broadcast_message(message: str, servers: Sequence[Server]) -> None:\n" +" ...\n" +"\n" +"# O verificador de tipo tratará a assinatura de tipo anterior\n" +"# como exatamente equivalente à assinatura abaixo.\n" +"def broadcast_message(\n" +" message: str,\n" +" servers: Sequence[tuple[tuple[str, int], dict[str, str]]]\n" +") -> None:\n" +" ..." + #: ../../library/typing.rst:106 msgid "" "The :keyword:`type` statement is new in Python 3.12. For backwards " "compatibility, type aliases can also be created through simple assignment::" msgstr "" -"A instrução :keyword:`type` é nova no Python 3.12. Para compatibilidade " -"retroativa, apelidos de tipo também podem ser criados através da simples " +"A instrução :keyword:`type` é nova no Python 3.12. Para manter " +"retrocompatibilidade, apelidos de tipo também podem ser criados usando " "atribuição::" +#: ../../library/typing.rst:109 +msgid "Vector = list[float]" +msgstr "Vector = list[float]" + #: ../../library/typing.rst:111 msgid "" "Or marked with :data:`TypeAlias` to make it explicit that this is a type " @@ -195,6 +248,16 @@ msgstr "" "Ou marcado com :data:`TypeAlias` para tornar explícito que se trata de um " "apelido de tipo e não uma atribuição de variável comum::" +#: ../../library/typing.rst:114 +msgid "" +"from typing import TypeAlias\n" +"\n" +"Vector: TypeAlias = list[float]" +msgstr "" +"from typing import TypeAlias\n" +"\n" +"Vector: TypeAlias = list[float]" + #: ../../library/typing.rst:121 msgid "NewType" msgstr "NewType" @@ -203,6 +266,18 @@ msgstr "NewType" msgid "Use the :class:`NewType` helper to create distinct types::" msgstr "Utilize o auxiliar :class:`NewType` para criar tipos únicos::" +#: ../../library/typing.rst:125 +msgid "" +"from typing import NewType\n" +"\n" +"UserId = NewType('UserId', int)\n" +"some_id = UserId(524313)" +msgstr "" +"from typing import NewType\n" +"\n" +"UserId = NewType('UserId', int)\n" +"some_id = UserId(524313)" + #: ../../library/typing.rst:130 msgid "" "The static type checker will treat the new type as if it were a subclass of " @@ -212,6 +287,26 @@ msgstr "" "subclasse do tipo original. Isso é útil para ajudar a encontrar erros de " "lógica::" +#: ../../library/typing.rst:133 +msgid "" +"def get_user_name(user_id: UserId) -> str:\n" +" ...\n" +"\n" +"# passes type checking\n" +"user_a = get_user_name(UserId(42351))\n" +"\n" +"# fails type checking; an int is not a UserId\n" +"user_b = get_user_name(-1)" +msgstr "" +"def get_user_name(user_id: UserId) -> str:\n" +" ...\n" +"\n" +"# passa na verificação de tipo\n" +"user_a = get_user_name(UserId(42351))\n" +"\n" +"# falha na verificação de tipo: um int não é um UserId\n" +"user_b = get_user_name(-1)" + #: ../../library/typing.rst:142 msgid "" "You may still perform all ``int`` operations on a variable of type " @@ -225,6 +320,14 @@ msgstr "" "mas previne que você acidentalmente crie um ``UserId`` de uma forma " "inválida::" +#: ../../library/typing.rst:147 +msgid "" +"# 'output' is of type 'int', not 'UserId'\n" +"output = UserId(23413) + UserId(54341)" +msgstr "" +"# 'output' é do tipo 'int', em vez de 'UserId'\n" +"output = UserId(23413) + UserId(54341)" + #: ../../library/typing.rst:150 msgid "" "Note that these checks are enforced only by the static type checker. At " @@ -252,6 +355,22 @@ msgstr "" msgid "It is invalid to create a subtype of ``Derived``::" msgstr "É inválido criar um subtipo de ``Derived``::" +#: ../../library/typing.rst:161 +msgid "" +"from typing import NewType\n" +"\n" +"UserId = NewType('UserId', int)\n" +"\n" +"# Fails at runtime and does not pass type checking\n" +"class AdminUserId(UserId): pass" +msgstr "" +"from typing import NewType\n" +"\n" +"UserId = NewType('UserId', int)\n" +"\n" +"# Falha em tempo de execução e não passa na verificação de tipos\n" +"class AdminUserId(UserId): pass" + #: ../../library/typing.rst:168 msgid "" "However, it is possible to create a :class:`NewType` based on a 'derived' " @@ -260,9 +379,23 @@ msgstr "" "No entanto, é possível criar um :class:`NewType` baseado em um 'derivado' " "``NewType``::" +#: ../../library/typing.rst:170 +msgid "" +"from typing import NewType\n" +"\n" +"UserId = NewType('UserId', int)\n" +"\n" +"ProUserId = NewType('ProUserId', UserId)" +msgstr "" +"from typing import NewType\n" +"\n" +"UserId = NewType('UserId', int)\n" +"\n" +"ProUserId = NewType('ProUserId', UserId)" + #: ../../library/typing.rst:176 msgid "and typechecking for ``ProUserId`` will work as expected." -msgstr "e a verificação de tipo para ``ProUserId`` funcionará como esperado." +msgstr "e a verificação de tipos para ``ProUserId`` funcionará como esperado." #: ../../library/typing.rst:178 msgid "See :pep:`484` for more details." @@ -303,16 +436,16 @@ msgid "" "some additional runtime cost when calling ``NewType`` over a regular " "function." msgstr "" -"``NewType`` é agora uma classe ao invés de uma função. Como consequência, " -"existem alguns custos em tempo de execução ao chamar ``NewType`` ao invés " -"de uma função comum." +"``NewType`` agora é uma classe em vez de uma função. Consequentemente, " +"existem alguns custos em tempo de execução ao chamar ``NewType`` em vez de " +"uma função comum." #: ../../library/typing.rst:201 msgid "" "The performance of calling ``NewType`` has been restored to its level in " "Python 3.9." msgstr "" -"O desempenho de chamar ``NewType`` retornou ao mesmo nível da versão Python " +"O desempenho de chamar ``NewType`` voltou ao mesmo nível da versão Python " "3.9." #: ../../library/typing.rst:208 @@ -322,20 +455,50 @@ msgstr "Anotações de objetos chamáveis" #: ../../library/typing.rst:210 msgid "" "Functions -- or other :term:`callable` objects -- can be annotated using :" -"class:`collections.abc.Callable` or :data:`typing.Callable`. " +"class:`collections.abc.Callable` or deprecated :data:`typing.Callable`. " "``Callable[[int], str]`` signifies a function that takes a single parameter " "of type :class:`int` and returns a :class:`str`." msgstr "" -"Funções -- ou outros objetos :term:`chamáveis ` -- podem ser " -"anotados utilizando-se :class:`collections.abc.Callable` ou :data:`typing." -"Callable`. ``Callable[[int], str]``. Significa uma função que recebe um " -"único parâmetro do tipo :class:`int`. e retorna um :class:`str`." +"Funções -- ou outros objetos :term:`chamáveis ` -- podem ser " +"anotados com :class:`collections.abc.Callable` ou com o tipo descontinuado :" +"data:`typing.Callable`. ``Callable[[int], str]`` expressa uma função que " +"recebe um único parâmetro de tipo :class:`int` e retorna uma :class:`str`." -#: ../../library/typing.rst:215 ../../library/typing.rst:3028 -#: ../../library/typing.rst:3206 +#: ../../library/typing.rst:215 ../../library/typing.rst:3161 +#: ../../library/typing.rst:3341 msgid "For example:" msgstr "Por exemplo:" +#: ../../library/typing.rst:217 +msgid "" +"from collections.abc import Callable, Awaitable\n" +"\n" +"def feeder(get_next_item: Callable[[], str]) -> None:\n" +" ... # Body\n" +"\n" +"def async_query(on_success: Callable[[int], None],\n" +" on_error: Callable[[int, Exception], None]) -> None:\n" +" ... # Body\n" +"\n" +"async def on_update(value: str) -> None:\n" +" ... # Body\n" +"\n" +"callback: Callable[[str], Awaitable[None]] = on_update" +msgstr "" +"from collections.abc import Callable, Awaitable\n" +"\n" +"def feeder(get_next_item: Callable[[], str]) -> None:\n" +" ... # Corpo\n" +"\n" +"def async_query(on_success: Callable[[int], None],\n" +" on_error: Callable[[int, Exception], None]) -> None:\n" +" ... # Corpo\n" +"\n" +"async def on_update(value: str) -> None:\n" +" ... # Corpo\n" +"\n" +"callback: Callable[[str], Awaitable[None]] = on_update" + #: ../../library/typing.rst:233 msgid "" "The subscription syntax must always be used with exactly two values: the " @@ -345,7 +508,7 @@ msgid "" msgstr "" "A sintaxe da subscrição deve sempre ser usada com exatamente dois valores: " "uma lista de argumentos e o tipo de retorno. A lista de argumentos deve ser " -"uma lista de tipos, um :class:`ParamSpec`, :data:`Concatenate`, ou " +"uma lista de tipos, um :class:`ParamSpec`, :data:`Concatenate`, ou " "reticências. O tipo de retorno deve ser um único tipo." #: ../../library/typing.rst:238 @@ -354,9 +517,25 @@ msgid "" "that a callable with any arbitrary parameter list would be acceptable:" msgstr "" "Se uma reticências literal ``...`` é passada no lugar de uma lista de " -"argumentos, indica que um chamável com umas lista de qualquer parâmetro " +"argumentos, ela indica que um chamável com uma lista de qualquer parâmetro " "arbitrário seria aceita." +#: ../../library/typing.rst:241 +msgid "" +"def concat(x: str, y: str) -> str:\n" +" return x + y\n" +"\n" +"x: Callable[..., str]\n" +"x = str # OK\n" +"x = concat # Also OK" +msgstr "" +"def concat(x: str, y: str) -> str:\n" +" return x + y\n" +"\n" +"x: Callable[..., str]\n" +"x = str # OK\n" +"x = concat # OK também" + #: ../../library/typing.rst:250 msgid "" "``Callable`` cannot express complex signatures such as functions that take a " @@ -371,6 +550,49 @@ msgstr "" "entanto, essas assinaturas podem ser expressas ao se definir uma :class:" "`Protocol` com um método :meth:`~object.__call__`:" +#: ../../library/typing.rst:256 +msgid "" +"from collections.abc import Iterable\n" +"from typing import Protocol\n" +"\n" +"class Combiner(Protocol):\n" +" def __call__(self, *vals: bytes, maxlen: int | None = None) -> " +"list[bytes]: ...\n" +"\n" +"def batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes:\n" +" for item in data:\n" +" ...\n" +"\n" +"def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]:\n" +" ...\n" +"def bad_cb(*vals: bytes, maxitems: int | None) -> list[bytes]:\n" +" ...\n" +"\n" +"batch_proc([], good_cb) # OK\n" +"batch_proc([], bad_cb) # Error! Argument 2 has incompatible type because " +"of\n" +" # different name and kind in the callback" +msgstr "" +"from collections.abc import Iterable\n" +"from typing import Protocol\n" +"\n" +"class Combiner(Protocol):\n" +" def __call__(self, *vals: bytes, maxlen: int | None = None) -> " +"list[bytes]: ...\n" +"\n" +"def batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes:\n" +" for item in data:\n" +" ...\n" +"\n" +"def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]:\n" +" ...\n" +"def bad_cb(*vals: bytes, maxitems: int | None) -> list[bytes]:\n" +" ...\n" +"\n" +"batch_proc([], good_cb) # OK\n" +"batch_proc([], bad_cb) # Erro! Argumento 2 tem tipo incompatível por ter\n" +" # nome e tipo diferente do callback" + #: ../../library/typing.rst:277 msgid "" "Callables which take other callables as arguments may indicate that their " @@ -382,14 +604,14 @@ msgid "" "ReturnType]`` respectively." msgstr "" "Chamáveis que recebem outros chamáveis como argumentos podem indicar que " -"seus tipos de parâmetro são dependentes uns dos outros usando :class:" -"`ParamSpec`. Além disso, se esse chamável adiciona ou retira argumentos de " -"outros chamáveis, o operador :data:`Concatenate` pode ser usado. Eles " -"assumem a forma de ``Callable[ParamSpecVariable, ReturnType]`` e " +"seus tipos de parâmetro dependem uns dos outros usando :class:`ParamSpec`. " +"Além disso, se esse chamável adiciona ou remove argumentos de outros " +"chamáveis, o operador :data:`Concatenate` pode ser usado. Eles assumem a " +"forma de ``Callable[ParamSpecVariable, ReturnType]`` e " "``Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], " "ReturnType]``, respectivamente." -#: ../../library/typing.rst:285 ../../library/typing.rst:3749 +#: ../../library/typing.rst:285 ../../library/typing.rst:3831 msgid "" "``Callable`` now supports :class:`ParamSpec` and :data:`Concatenate`. See :" "pep:`612` for more details." @@ -416,22 +638,78 @@ msgid "" "support subscription to denote the expected types of container elements." msgstr "" "Como a informação de tipo sobre objetos mantidos em contêineres não pode ser " -"inferida estaticamente de uma maneira genérica, muitas classes de contêiner " -"na biblioteca padrão suportam subscrição para denotar tipos esperados de " -"elementos de contêiner." +"inferida estaticamente de uma maneira genérica, muitas classes de " +"contêineres na biblioteca padrão permitem usar subscrição para denotar o " +"tipo esperado dos elementos dos contêineres." + +#: ../../library/typing.rst:302 +msgid "" +"from collections.abc import Mapping, Sequence\n" +"\n" +"class Employee: ...\n" +"\n" +"# Sequence[Employee] indicates that all elements in the sequence\n" +"# must be instances of \"Employee\".\n" +"# Mapping[str, str] indicates that all keys and all values in the mapping\n" +"# must be strings.\n" +"def notify_by_email(employees: Sequence[Employee],\n" +" overrides: Mapping[str, str]) -> None: ..." +msgstr "" +"from collections.abc import Mapping, Sequence\n" +"\n" +"class Employee: ...\n" +"\n" +"# Sequence[Employee] indica que todos os elementos na sequência\n" +"# devem ser instâncias de \"Employee\".\n" +"# Mapping[str, str] indica que todas as chaves e valores no mapeamento\n" +"# devem ser strings.\n" +"def notify_by_email(employees: Sequence[Employee],\n" +" overrides: Mapping[str, str]) -> None: ..." #: ../../library/typing.rst:315 msgid "" "Generic functions and classes can be parameterized by using :ref:`type " "parameter syntax `::" msgstr "" -"Funções e classes genéricas podem ser parametrizadas utilizando-se :ref:" -"`sintaxe do parâmetro de tipo `::" +"Funções e classes genéricas podem ser parametrizadas utilizando a :ref:" +"`sintaxe de parâmetro de tipos `::" + +#: ../../library/typing.rst:318 +msgid "" +"from collections.abc import Sequence\n" +"\n" +"def first[T](l: Sequence[T]) -> T: # Function is generic over the TypeVar " +"\"T\"\n" +" return l[0]" +msgstr "" +"from collections.abc import Sequence\n" +"\n" +"def first[T](l: Sequence[T]) -> T: # Função é genérica sobre TypeVar \"T\"\n" +" return l[0]" #: ../../library/typing.rst:323 msgid "Or by using the :class:`TypeVar` factory directly::" msgstr "Ou utilizando a fábrica :class:`TypeVar` diretamente::" +#: ../../library/typing.rst:325 +msgid "" +"from collections.abc import Sequence\n" +"from typing import TypeVar\n" +"\n" +"U = TypeVar('U') # Declare type variable \"U\"\n" +"\n" +"def second(l: Sequence[U]) -> U: # Function is generic over the TypeVar " +"\"U\"\n" +" return l[1]" +msgstr "" +"from collections.abc import Sequence\n" +"from typing import TypeVar\n" +"\n" +"U = TypeVar('U') # Declara tipo variável \"U\"\n" +"\n" +"def second(l: Sequence[U]) -> U: # Função é genérica sobre a TypeVar \"U\"\n" +" return l[1]" + #: ../../library/typing.rst:333 msgid "Syntactic support for generics is new in Python 3.12." msgstr "O suporte sintático para genéricos é novo no Python 3.12." @@ -448,6 +726,34 @@ msgstr "" "Para a maior parte dos tipos containers em Python, o sistema de tipagem " "presume que todos os elementos do contêiner são do mesmo tipo. Por exemplo::" +#: ../../library/typing.rst:344 +msgid "" +"from collections.abc import Mapping\n" +"\n" +"# Type checker will infer that all elements in ``x`` are meant to be ints\n" +"x: list[int] = []\n" +"\n" +"# Type checker error: ``list`` only accepts a single type argument:\n" +"y: list[int, str] = [1, 'foo']\n" +"\n" +"# Type checker will infer that all keys in ``z`` are meant to be strings,\n" +"# and that all values in ``z`` are meant to be either strings or ints\n" +"z: Mapping[str, str | int] = {}" +msgstr "" +"from collections.abc import Mapping\n" +"\n" +"# Verificador de tipos irá inferir que todos os elementos em ``x`` devem ser " +"ints\n" +"x: list[int] = []\n" +"\n" +"# Erro no verificador: ``list`` aceita um único tipo de argumento\n" +"y: list[int, str] = [1, 'foo']\n" +"\n" +"# Verificador de tipos irá inferir que todas as chaves em ``z`` devem ser " +"strings,\n" +"# e todos os valores em ``z`` devem ser strings ou ints\n" +"z: Mapping[str, str | int] = {}" + #: ../../library/typing.rst:356 msgid "" ":class:`list` only accepts one type argument, so a type checker would emit " @@ -456,7 +762,7 @@ msgid "" "the keys, and the second indicates the type of the values." msgstr "" ":class:`list` aceita apenas um tipo de argumento, e assim o verificador de " -"tipos irá emitir um erro na atribuição ``y`` acima. Da mesma forma, :class:" +"tipos emitirá um erro na atribuição ``y`` acima. Da mesma forma, :class:" "`~collections.abc.Mapping` aceita apenas dois tipos de argumento: O primeiro " "indica o tipo das chaves, e o segundo indica o tipo dos valores." @@ -470,8 +776,34 @@ msgstr "" "Ao contrário da maioria dos outros contêineres Python, é comum no código " "Python idiomático que as tuplas tenham elementos que não sejam todos do " "mesmo tipo. Por esse motivo, as tuplas têm um caso especial no sistema de " -"tipagem do Python. :class:`tuple` aceita *qualquer número* do tipo " -"argumento::" +"tipagem do Python. :class:`tuple` aceita *qualquer quantidade* de argumentos " +"de tipo::" + +#: ../../library/typing.rst:367 +msgid "" +"# OK: ``x`` is assigned to a tuple of length 1 where the sole element is an " +"int\n" +"x: tuple[int] = (5,)\n" +"\n" +"# OK: ``y`` is assigned to a tuple of length 2;\n" +"# element 1 is an int, element 2 is a str\n" +"y: tuple[int, str] = (5, \"foo\")\n" +"\n" +"# Error: the type annotation indicates a tuple of length 1,\n" +"# but ``z`` has been assigned to a tuple of length 3\n" +"z: tuple[int] = (1, 2, 3)" +msgstr "" +"# OK: ``x`` foi atribuída a uma tupla de comprimento 1, onde o único " +"elemento é um int\n" +"x: tuple[int] = (5,)\n" +"\n" +"# OK: ``y`` foi atribuída a uma tupla de comprimento 2;\n" +"# o elemento 1 é um int, o elemento 2 é uma str\n" +"y: tuple[int, str] = (5, \"foo\")\n" +"\n" +"# Erro: a anotação de tipo indica uma tupla de comprimento 1,\n" +"# mas ``z`` foi atribuída a uma tupla de comprimento 3\n" +"z: tuple[int] = (1, 2, 3)" #: ../../library/typing.rst:378 msgid "" @@ -485,6 +817,42 @@ msgstr "" "denotar um tupla vazia, use ``tuple[()]``. Usando apenas ``tuple`` como " "anotação, é equivalente a usar ``tuple[Any, ...]``::" +#: ../../library/typing.rst:383 +msgid "" +"x: tuple[int, ...] = (1, 2)\n" +"# These reassignments are OK: ``tuple[int, ...]`` indicates x can be of any " +"length\n" +"x = (1, 2, 3)\n" +"x = ()\n" +"# This reassignment is an error: all elements in ``x`` must be ints\n" +"x = (\"foo\", \"bar\")\n" +"\n" +"# ``y`` can only ever be assigned to an empty tuple\n" +"y: tuple[()] = ()\n" +"\n" +"z: tuple = (\"foo\", \"bar\")\n" +"# These reassignments are OK: plain ``tuple`` is equivalent to " +"``tuple[Any, ...]``\n" +"z = (1, 2, 3)\n" +"z = ()" +msgstr "" +"x: tuple[int, ...] = (1, 2)\n" +"# Essas reatribuições são OK: ``tuple[int, ...]`` indica que x pode ter " +"qualquer comprimento\n" +"x = (1, 2, 3)\n" +"x = ()\n" +"# Essa reatribuição é um erro: todos os elementos de ``x`` devem ser ints\n" +"x = (\"foo\", \"bar\")\n" +"\n" +"# ``y`` só pode ser atribuída a uma tupla vazia\n" +"y: tuple[()] = ()\n" +"\n" +"z: tuple = (\"foo\", \"bar\")\n" +"# Essas reatribuições são OK: o tipo ``tuple`` equivale a " +"``tuple[Any, ...]``\n" +"z = (1, 2, 3)\n" +"z = ()" + #: ../../library/typing.rst:401 msgid "The type of class objects" msgstr "O tipo de objetos de classe" @@ -492,19 +860,65 @@ msgstr "O tipo de objetos de classe" #: ../../library/typing.rst:403 msgid "" "A variable annotated with ``C`` may accept a value of type ``C``. In " -"contrast, a variable annotated with ``type[C]`` (or :class:`typing.Type[C] " -"`) may accept values that are classes themselves -- specifically, it " -"will accept the *class object* of ``C``. For example::" +"contrast, a variable annotated with ``type[C]`` (or deprecated :class:" +"`typing.Type[C] `) may accept values that are classes themselves -- " +"specifically, it will accept the *class object* of ``C``. For example::" +msgstr "" +"Uma variável anotada com ``C`` pode aceitar um valor de tipo ``C``. Por " +"outro lado, uma variável anotada com ``type[C]`` (ou o tipo descontinuado :" +"class:`typing.Type[C] `) pode aceitar valores que são as próprias " +"classes -- mais especificamente, ela aceitará o *objeto classe* de ``C``. " +"Por exemplo::" + +#: ../../library/typing.rst:409 +msgid "" +"a = 3 # Has type ``int``\n" +"b = int # Has type ``type[int]``\n" +"c = type(a) # Also has type ``type[int]``" msgstr "" -"Uma variável anotada com ``C`` pode aceitar um valor do tipo ``C``. Por " -"outro lado, uma variável anotada com ``type[C]`` (ou :class:`typing.Type[C] " -"`) pode aceitar valores que são classes -- especificamente, ela " -"aceitará o *objeto classe* de ``C``. Por exemplo::" +"a = 3 # Tem tipo ``int``\n" +"b = int # Tem tipo ``type[int]``\n" +"c = type(a) # Também tem tipo ``type[int]``" #: ../../library/typing.rst:413 msgid "Note that ``type[C]`` is covariant::" msgstr "Observe que ``type[C]`` é covariante::" +#: ../../library/typing.rst:415 +msgid "" +"class User: ...\n" +"class ProUser(User): ...\n" +"class TeamUser(User): ...\n" +"\n" +"def make_new_user(user_class: type[User]) -> User:\n" +" # ...\n" +" return user_class()\n" +"\n" +"make_new_user(User) # OK\n" +"make_new_user(ProUser) # Also OK: ``type[ProUser]`` is a subtype of " +"``type[User]``\n" +"make_new_user(TeamUser) # Still fine\n" +"make_new_user(User()) # Error: expected ``type[User]`` but got ``User``\n" +"make_new_user(int) # Error: ``type[int]`` is not a subtype of " +"``type[User]``" +msgstr "" +"class User: ...\n" +"class ProUser(User): ...\n" +"class TeamUser(User): ...\n" +"\n" +"def make_new_user(user_class: type[User]) -> User:\n" +" # ...\n" +" return user_class()\n" +"\n" +"make_new_user(User) # OK\n" +"make_new_user(ProUser) # Também OK: ``type[ProUser]`` é subtipo de " +"``type[User]``\n" +"make_new_user(TeamUser) # Tudo bem\n" +"make_new_user(User()) # Erro: esperava-se ``type[User]`` mas retornou " +"``User``\n" +"make_new_user(int) # Erro: ``type[int]`` não é subtipo de " +"``type[User]``" + #: ../../library/typing.rst:429 msgid "" "The only legal parameters for :class:`type` are classes, :data:`Any`, :ref:" @@ -514,6 +928,24 @@ msgstr "" "ref:`type variables ` e uniões de qualquer um desses tipos. Por " "exemplo::" +#: ../../library/typing.rst:433 +msgid "" +"def new_non_team_user(user_class: type[BasicUser | ProUser]): ...\n" +"\n" +"new_non_team_user(BasicUser) # OK\n" +"new_non_team_user(ProUser) # OK\n" +"new_non_team_user(TeamUser) # Error: ``type[TeamUser]`` is not a subtype\n" +" # of ``type[BasicUser | ProUser]``\n" +"new_non_team_user(User) # Also an error" +msgstr "" +"def new_non_team_user(user_class: type[BasicUser | ProUser]): ...\n" +"\n" +"new_non_team_user(BasicUser) # OK\n" +"new_non_team_user(ProUser) # OK\n" +"new_non_team_user(TeamUser) # Erro: ``type[TeamUser]`` não é subtipo\n" +" # de ``type[BasicUser | ProUser]``\n" +"new_non_team_user(User) # Também é um erro" + #: ../../library/typing.rst:441 msgid "" "``type[Any]`` is equivalent to :class:`type`, which is the root of Python's :" @@ -522,16 +954,230 @@ msgstr "" "``type[Any]`` é equivalente a :class:`type`, que é a raiz da :ref:" "`hierarquia de metaclasses ` do Python." -#: ../../library/typing.rst:447 +#: ../../library/typing.rst:448 +msgid "Annotating generators and coroutines" +msgstr "Anotando geradores e corrotinas" + +#: ../../library/typing.rst:450 +msgid "" +"A generator can be annotated using the generic type :class:" +"`Generator[YieldType, SendType, ReturnType] `. " +"For example::" +msgstr "" +"Um gerador pode ser anotado usando um tipo genérico :class:" +"`Generator[YieldType, SendType, ReturnType] `. " +"Por exemplo::" + +#: ../../library/typing.rst:454 +msgid "" +"def echo_round() -> Generator[int, float, str]:\n" +" sent = yield 0\n" +" while sent >= 0:\n" +" sent = yield round(sent)\n" +" return 'Done'" +msgstr "" +"def echo_round() -> Generator[int, float, str]:\n" +" sent = yield 0\n" +" while sent >= 0:\n" +" sent = yield round(sent)\n" +" return 'Done'" + +#: ../../library/typing.rst:460 +msgid "" +"Note that unlike many other generic classes in the standard library, the " +"``SendType`` of :class:`~collections.abc.Generator` behaves contravariantly, " +"not covariantly or invariantly." +msgstr "" +"Note que, diferentemente de outras classes genéricas na biblioteca padrão, o " +"``SendType`` da classe :class:`~collections.abc.Generator` se comporta " +"contravariantemente, em vez de covariantemente ou invariantemente." + +#: ../../library/typing.rst:464 +msgid "" +"The ``SendType`` and ``ReturnType`` parameters default to :const:`!None`::" +msgstr "" +"Os parâmetros ``SendType`` e ``ReturnType`` são :const:`!None` por padrão::" + +#: ../../library/typing.rst:466 +msgid "" +"def infinite_stream(start: int) -> Generator[int]:\n" +" while True:\n" +" yield start\n" +" start += 1" +msgstr "" +"def infinite_stream(start: int) -> Generator[int]:\n" +" while True:\n" +" yield start\n" +" start += 1" + +#: ../../library/typing.rst:471 +msgid "It is also possible to set these types explicitly::" +msgstr "Também é possível definir esses tipos explicitamente::" + +#: ../../library/typing.rst:473 +msgid "" +"def infinite_stream(start: int) -> Generator[int, None, None]:\n" +" while True:\n" +" yield start\n" +" start += 1" +msgstr "" +"def infinite_stream(start: int) -> Generator[int, None, None]:\n" +" while True:\n" +" yield start\n" +" start += 1" + +#: ../../library/typing.rst:478 +msgid "" +"Simple generators that only ever yield values can also be annotated as " +"having a return type of either :class:`Iterable[YieldType] ` or :class:`Iterator[YieldType] `::" +msgstr "" +"Geradores simples que só produzem valores também podem ser anotados com tipo " +"de retorno :class:`Iterable[YieldType] ` ou :class:" +"`Iterator[YieldType] `::" + +#: ../../library/typing.rst:483 +msgid "" +"def infinite_stream(start: int) -> Iterator[int]:\n" +" while True:\n" +" yield start\n" +" start += 1" +msgstr "" +"def infinite_stream(start: int) -> Iterator[int]:\n" +" while True:\n" +" yield start\n" +" start += 1" + +#: ../../library/typing.rst:488 +msgid "" +"Async generators are handled in a similar fashion, but don't expect a " +"``ReturnType`` type argument (:class:`AsyncGenerator[YieldType, SendType] " +"`). The ``SendType`` argument defaults to :" +"const:`!None`, so the following definitions are equivalent::" +msgstr "" +"Geradores assíncronos são manipulados similarmente, mas não espere um " +"argumento de tipo ``ReturnType`` (:class:`AsyncGenerator[YieldType, " +"SendType] `). O argumento ``SendType`` é :" +"const:`!None` por padrão, então as seguintes definições são equivalentes::" + +#: ../../library/typing.rst:494 +msgid "" +"async def infinite_stream(start: int) -> AsyncGenerator[int]:\n" +" while True:\n" +" yield start\n" +" start = await increment(start)\n" +"\n" +"async def infinite_stream(start: int) -> AsyncGenerator[int, None]:\n" +" while True:\n" +" yield start\n" +" start = await increment(start)" +msgstr "" +"async def infinite_stream(start: int) -> AsyncGenerator[int]:\n" +" while True:\n" +" yield start\n" +" start = await increment(start)\n" +"\n" +"async def infinite_stream(start: int) -> AsyncGenerator[int, None]:\n" +" while True:\n" +" yield start\n" +" start = await increment(start)" + +#: ../../library/typing.rst:504 +msgid "" +"As in the synchronous case, :class:`AsyncIterable[YieldType] ` and :class:`AsyncIterator[YieldType] ` are available as well::" +msgstr "" +"Como no caso síncrono, :class:`AsyncIterable[YieldType] ` e :class:`AsyncIterator[YieldType] ` também estão disponíveis::" + +#: ../../library/typing.rst:509 +msgid "" +"async def infinite_stream(start: int) -> AsyncIterator[int]:\n" +" while True:\n" +" yield start\n" +" start = await increment(start)" +msgstr "" +"async def infinite_stream(start: int) -> AsyncIterator[int]:\n" +" while True:\n" +" yield start\n" +" start = await increment(start)" + +#: ../../library/typing.rst:514 +msgid "" +"Coroutines can be annotated using :class:`Coroutine[YieldType, SendType, " +"ReturnType] `. Generic arguments correspond to " +"those of :class:`~collections.abc.Generator`, for example::" +msgstr "" +"Corrotinas podem ser anotadas usando :class:`Coroutine[YieldType, SendType, " +"ReturnType] `. Argumentos genéricos correspondem " +"àqueles da classe :class:`~collections.abc.Generator`, por exemplo::" + +#: ../../library/typing.rst:519 +msgid "" +"from collections.abc import Coroutine\n" +"c: Coroutine[list[str], str, int] # Some coroutine defined elsewhere\n" +"x = c.send('hi') # Inferred type of 'x' is list[str]\n" +"async def bar() -> None:\n" +" y = await c # Inferred type of 'y' is int" +msgstr "" +"from collections.abc import Coroutine\n" +"c: Coroutine[list[str], str, int] # Uma corrotina defina em outro lugar\n" +"x = c.send('hi') # Tipo inferido de 'x' é list[str]\n" +"async def bar() -> None:\n" +" y = await c # Tipo inferido de 'y' é int" + +#: ../../library/typing.rst:528 msgid "User-defined generic types" msgstr "Tipos genéricos definidos pelo usuário" -#: ../../library/typing.rst:449 +#: ../../library/typing.rst:530 msgid "A user-defined class can be defined as a generic class." msgstr "" "Uma classe definida pelo usuário pode ser definica como uma classe genérica." -#: ../../library/typing.rst:472 +#: ../../library/typing.rst:534 +msgid "" +"from logging import Logger\n" +"\n" +"class LoggedVar[T]:\n" +" def __init__(self, value: T, name: str, logger: Logger) -> None:\n" +" self.name = name\n" +" self.logger = logger\n" +" self.value = value\n" +"\n" +" def set(self, new: T) -> None:\n" +" self.log('Set ' + repr(self.value))\n" +" self.value = new\n" +"\n" +" def get(self) -> T:\n" +" self.log('Get ' + repr(self.value))\n" +" return self.value\n" +"\n" +" def log(self, message: str) -> None:\n" +" self.logger.info('%s: %s', self.name, message)" +msgstr "" +"from logging import Logger\n" +"\n" +"class LoggedVar[T]:\n" +" def __init__(self, value: T, name: str, logger: Logger) -> None:\n" +" self.name = name\n" +" self.logger = logger\n" +" self.value = value\n" +"\n" +" def set(self, new: T) -> None:\n" +" self.log('Set ' + repr(self.value))\n" +" self.value = new\n" +"\n" +" def get(self) -> T:\n" +" self.log('Get ' + repr(self.value))\n" +" return self.value\n" +"\n" +" def log(self, message: str) -> None:\n" +" self.logger.info('%s: %s', self.name, message)" + +#: ../../library/typing.rst:553 msgid "" "This syntax indicates that the class ``LoggedVar`` is parameterised around a " "single :ref:`type variable ` ``T`` . This also makes ``T`` valid as " @@ -541,7 +1187,7 @@ msgstr "" "uma única :ref:`type variable ` ``T``. Isso também torna ``T`` " "válido como um tipo dentro do corpo da classe." -#: ../../library/typing.rst:476 +#: ../../library/typing.rst:557 msgid "" "Generic classes implicitly inherit from :class:`Generic`. For compatibility " "with Python 3.11 and lower, it is also possible to inherit explicitly from :" @@ -551,7 +1197,23 @@ msgstr "" "compatibilidade com Python 3.11 e versões inferiores, também é possível " "herdar explicitamente de :class:`Generic` para indicar uma classe genérica::" -#: ../../library/typing.rst:487 +#: ../../library/typing.rst:561 +msgid "" +"from typing import TypeVar, Generic\n" +"\n" +"T = TypeVar('T')\n" +"\n" +"class LoggedVar(Generic[T]):\n" +" ..." +msgstr "" +"from typing import TypeVar, Generic\n" +"\n" +"T = TypeVar('T')\n" +"\n" +"class LoggedVar(Generic[T]):\n" +" ..." + +#: ../../library/typing.rst:568 msgid "" "Generic classes have :meth:`~object.__class_getitem__` methods, meaning they " "can be parameterised at runtime (e.g. ``LoggedVar[int]`` below)::" @@ -560,7 +1222,21 @@ msgstr "" "significa que podem ser parametrizadas em tempo de execução (por exemplo, " "``LoggedVar[int]`` abaixo)::" -#: ../../library/typing.rst:496 +#: ../../library/typing.rst:571 +msgid "" +"from collections.abc import Iterable\n" +"\n" +"def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:\n" +" for var in vars:\n" +" var.set(0)" +msgstr "" +"from collections.abc import Iterable\n" +"\n" +"def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:\n" +" for var in vars:\n" +" var.set(0)" + +#: ../../library/typing.rst:577 msgid "" "A generic type can have any number of type variables. All varieties of :" "class:`TypeVar` are permissible as parameters for a generic type::" @@ -569,7 +1245,33 @@ msgstr "" "variedades de :class:`TypeVar` são permitidas como parâmetros para um tipo " "genérico::" -#: ../../library/typing.rst:511 +#: ../../library/typing.rst:580 +msgid "" +"from typing import TypeVar, Generic, Sequence\n" +"\n" +"class WeirdTrio[T, B: Sequence[bytes], S: (int, str)]:\n" +" ...\n" +"\n" +"OldT = TypeVar('OldT', contravariant=True)\n" +"OldB = TypeVar('OldB', bound=Sequence[bytes], covariant=True)\n" +"OldS = TypeVar('OldS', int, str)\n" +"\n" +"class OldWeirdTrio(Generic[OldT, OldB, OldS]):\n" +" ..." +msgstr "" +"from typing import TypeVar, Generic, Sequence\n" +"\n" +"class WeirdTrio[T, B: Sequence[bytes], S: (int, str)]:\n" +" ...\n" +"\n" +"OldT = TypeVar('OldT', contravariant=True)\n" +"OldB = TypeVar('OldB', bound=Sequence[bytes], covariant=True)\n" +"OldS = TypeVar('OldS', int, str)\n" +"\n" +"class OldWeirdTrio(Generic[OldT, OldB, OldS]):\n" +" ..." + +#: ../../library/typing.rst:592 msgid "" "Each type variable argument to :class:`Generic` must be distinct. This is " "thus invalid::" @@ -577,20 +1279,68 @@ msgstr "" "Cada tipo dos argumentos para :class:`Generic` devem ser distintos. Assim, " "os seguintes exemplos são inválidos::" -#: ../../library/typing.rst:525 +#: ../../library/typing.rst:595 +msgid "" +"from typing import TypeVar, Generic\n" +"...\n" +"\n" +"class Pair[M, M]: # SyntaxError\n" +" ...\n" +"\n" +"T = TypeVar('T')\n" +"\n" +"class Pair(Generic[T, T]): # INVALID\n" +" ..." +msgstr "" +"from typing import TypeVar, Generic\n" +"...\n" +"\n" +"class Pair[M, M]: # SyntaxError\n" +" ...\n" +"\n" +"T = TypeVar('T')\n" +"\n" +"class Pair(Generic[T, T]): # INVÁLIDO\n" +" ..." + +#: ../../library/typing.rst:606 msgid "Generic classes can also inherit from other classes::" msgstr "Classes genéricas podem também herdar de outras classes::" -#: ../../library/typing.rst:532 +#: ../../library/typing.rst:608 +msgid "" +"from collections.abc import Sized\n" +"\n" +"class LinkedList[T](Sized):\n" +" ..." +msgstr "" +"from collections.abc import Sized\n" +"\n" +"class LinkedList[T](Sized):\n" +" ..." + +#: ../../library/typing.rst:613 msgid "" "When inheriting from generic classes, some type parameters could be fixed::" msgstr "Ao herdar das classes genérico, algun tipos podem ser fixos::" -#: ../../library/typing.rst:539 +#: ../../library/typing.rst:615 +msgid "" +"from collections.abc import Mapping\n" +"\n" +"class MyDict[T](Mapping[str, T]):\n" +" ..." +msgstr "" +"from collections.abc import Mapping\n" +"\n" +"class MyDict[T](Mapping[str, T]):\n" +" ..." + +#: ../../library/typing.rst:620 msgid "In this case ``MyDict`` has a single parameter, ``T``." msgstr "Neste caso ``MyDict`` possui um único parâmetro, ``T``." -#: ../../library/typing.rst:541 +#: ../../library/typing.rst:622 msgid "" "Using a generic class without specifying type parameters assumes :data:`Any` " "for each position. In the following example, ``MyIterable`` is not generic " @@ -600,24 +1350,80 @@ msgstr "" "para cada posição. No exemplo a seguir, ``MyIterable`` não é genérico, mas " "herda implicitamente de ``Iterable[Any]``:" -#: ../../library/typing.rst:552 +#: ../../library/typing.rst:626 +msgid "" +"from collections.abc import Iterable\n" +"\n" +"class MyIterable(Iterable): # Same as Iterable[Any]\n" +" ..." +msgstr "" +"from collections.abc import Iterable\n" +"\n" +"class MyIterable(Iterable): # Igual a Iterable[Any]\n" +" ..." + +#: ../../library/typing.rst:633 msgid "User-defined generic type aliases are also supported. Examples::" msgstr "" "Também há suporte para tipos genéricos definidos pelo usuário. Exemplos::" -#: ../../library/typing.rst:567 +#: ../../library/typing.rst:635 +msgid "" +"from collections.abc import Iterable\n" +"\n" +"type Response[S] = Iterable[S] | int\n" +"\n" +"# Return type here is same as Iterable[str] | int\n" +"def response(query: str) -> Response[str]:\n" +" ...\n" +"\n" +"type Vec[T] = Iterable[tuple[T, T]]\n" +"\n" +"def inproduct[T: (int, float, complex)](v: Vec[T]) -> T: # Same as " +"Iterable[tuple[T, T]]\n" +" return sum(x*y for x, y in v)" +msgstr "" +"from collections.abc import Iterable\n" +"\n" +"type Response[S] = Iterable[S] | int\n" +"\n" +"# Tipo de retorno aqui é igual a Iterable[str] | int\n" +"def response(query: str) -> Response[str]:\n" +" ...\n" +"\n" +"type Vec[T] = Iterable[tuple[T, T]]\n" +"\n" +"def inproduct[T: (int, float, complex)](v: Vec[T]) -> T: # Igual a " +"Iterable[tuple[T, T]]\n" +" return sum(x*y for x, y in v)" + +#: ../../library/typing.rst:648 msgid "" "For backward compatibility, generic type aliases can also be created through " "a simple assignment::" msgstr "" -"Para compatibilidade retroativa, os apelidos para tipos genéricos também " -"podem ser criados por meio de um simples atribuição::" +"Para manter retrocompatibilidade, os apelidos de tipos genéricos também " +"podem ser criados usando atribuição::" + +#: ../../library/typing.rst:651 +msgid "" +"from collections.abc import Iterable\n" +"from typing import TypeVar\n" +"\n" +"S = TypeVar(\"S\")\n" +"Response = Iterable[S] | int" +msgstr "" +"from collections.abc import Iterable\n" +"from typing import TypeVar\n" +"\n" +"S = TypeVar(\"S\")\n" +"Response = Iterable[S] | int" -#: ../../library/typing.rst:576 +#: ../../library/typing.rst:657 msgid ":class:`Generic` no longer has a custom metaclass." msgstr ":class:`Generic` não possui mais uma metaclasse personalizada." -#: ../../library/typing.rst:579 +#: ../../library/typing.rst:660 msgid "" "Syntactic support for generics and type aliases is new in version 3.12. " "Previously, generic classes had to explicitly inherit from :class:`Generic` " @@ -627,24 +1433,36 @@ msgstr "" "Anteriormente, as classes genéricas precisavam explicitamente herdar de :" "class:`Generic` ou conter um tipo de variável em uma de suas bases." -#: ../../library/typing.rst:584 +#: ../../library/typing.rst:665 msgid "" "User-defined generics for parameter expressions are also supported via " "parameter specification variables in the form ``[**P]``. The behavior is " "consistent with type variables' described above as parameter specification " -"variables are treated by the typing module as a specialized type variable. " -"The one exception to this is that a list of types can be used to substitute " -"a :class:`ParamSpec`::" +"variables are treated by the :mod:`!typing` module as a specialized type " +"variable. The one exception to this is that a list of types can be used to " +"substitute a :class:`ParamSpec`::" msgstr "" "Genéricos definidos pelo usuário para expressões de parâmetros também " "oferecem suporte por meio de variáveis de especificação de parâmetros no " "formato ``[**P]``. O comportamento é consistente com as variáveis de tipo " "descritas acima, pois as variáveis de especificação de parâmetro são " -"tratadas pelo módulo typing como uma variável de tipo especializada. A única " -"exceção a isso é que uma lista de tipos pode ser usada para substituir um :" -"class:`ParamSpec`::" +"tratadas pelo módulo :mod:`!typing` como uma variável de tipo especializada. " +"A única exceção a isso é que uma lista de tipos pode ser usada para " +"substituir um :class:`ParamSpec`::" -#: ../../library/typing.rst:595 +#: ../../library/typing.rst:671 +msgid "" +">>> class Z[T, **P]: ... # T is a TypeVar; P is a ParamSpec\n" +"...\n" +">>> Z[int, [dict, float]]\n" +"__main__.Z[int, [dict, float]]" +msgstr "" +">>> class Z[T, **P]: ... # T é um TypeVar; P é um ParamSpec\n" +"...\n" +">>> Z[int, [dict, float]]\n" +"__main__.Z[int, [dict, float]]" + +#: ../../library/typing.rst:676 msgid "" "Classes generic over a :class:`ParamSpec` can also be created using explicit " "inheritance from :class:`Generic`. In this case, ``**`` is not used::" @@ -653,7 +1471,23 @@ msgstr "" "usando herança explícita de :class:`Generic`. Neste caso, ``**`` não é " "usado::" -#: ../../library/typing.rst:605 +#: ../../library/typing.rst:679 +msgid "" +"from typing import ParamSpec, Generic\n" +"\n" +"P = ParamSpec('P')\n" +"\n" +"class Z(Generic[P]):\n" +" ..." +msgstr "" +"from typing import ParamSpec, Generic\n" +"\n" +"P = ParamSpec('P')\n" +"\n" +"class Z(Generic[P]):\n" +" ..." + +#: ../../library/typing.rst:686 msgid "" "Another difference between :class:`TypeVar` and :class:`ParamSpec` is that a " "generic with only one parameter specification variable will accept parameter " @@ -667,7 +1501,23 @@ msgstr "" "``X[Type1, Type2, ...]`` por razões estéticas. Internamente, o último é " "convertido no primeiro, portanto são equivalentes::" -#: ../../library/typing.rst:618 +#: ../../library/typing.rst:692 +msgid "" +">>> class X[**P]: ...\n" +"...\n" +">>> X[int, str]\n" +"__main__.X[[int, str]]\n" +">>> X[[int, str]]\n" +"__main__.X[[int, str]]" +msgstr "" +">>> class X[**P]: ...\n" +"...\n" +">>> X[int, str]\n" +"__main__.X[[int, str]]\n" +">>> X[[int, str]]\n" +"__main__.X[[int, str]]" + +#: ../../library/typing.rst:699 msgid "" "Note that generics with :class:`ParamSpec` may not have correct " "``__parameters__`` after substitution in some cases because they are " @@ -677,7 +1527,7 @@ msgstr "" "``__parameters__`` corretos após a substituição em alguns casos porque eles " "são destinados principalmente à verificação de tipo estático." -#: ../../library/typing.rst:622 +#: ../../library/typing.rst:703 msgid "" ":class:`Generic` can now be parameterized over parameter expressions. See :" "class:`ParamSpec` and :pep:`612` for more details." @@ -685,24 +1535,24 @@ msgstr "" ":class:`Generic` agora pode ser parametrizado através de expressões de " "parâmetros. Veja :class:`ParamSpec` e :pep:`612` para mais detalhes." -#: ../../library/typing.rst:626 +#: ../../library/typing.rst:707 msgid "" "A user-defined generic class can have ABCs as base classes without a " "metaclass conflict. Generic metaclasses are not supported. The outcome of " -"parameterizing generics is cached, and most types in the typing module are :" -"term:`hashable` and comparable for equality." +"parameterizing generics is cached, and most types in the :mod:`!typing` " +"module are :term:`hashable` and comparable for equality." msgstr "" "Uma classe genérica definida pelo usuário pode ter ABCs como classes base " "sem conflito de metaclasse. Não há suporte a metaclasses genéricas. O " "resultado da parametrização de genéricos é armazenado em cache, e a maioria " -"dos tipos no módulo typing são :term:`hasheáveis ` e comparáveis " -"em termos de igualdade." +"dos tipos no módulo :mod:`!typing` são :term:`hasheáveis ` e " +"comparáveis em termos de igualdade." -#: ../../library/typing.rst:633 +#: ../../library/typing.rst:714 msgid "The :data:`Any` type" msgstr "O tipo :data:`Any`" -#: ../../library/typing.rst:635 +#: ../../library/typing.rst:716 msgid "" "A special kind of type is :data:`Any`. A static type checker will treat " "every type as being compatible with :data:`Any` and :data:`Any` as being " @@ -712,7 +1562,7 @@ msgstr "" "tratará cada tipo como sendo compatível com :data:`Any` e :data:`Any` como " "sendo compatível com todos os tipos." -#: ../../library/typing.rst:639 +#: ../../library/typing.rst:720 msgid "" "This means that it is possible to perform any operation or method call on a " "value of type :data:`Any` and assign it to any variable::" @@ -720,7 +1570,39 @@ msgstr "" "Isso significa que é possível realizar qualquer operação ou chamada de " "método sobre um valor do tipo :data:`Any` e atribuí-lo a qualquer variável::" -#: ../../library/typing.rst:657 +#: ../../library/typing.rst:723 +msgid "" +"from typing import Any\n" +"\n" +"a: Any = None\n" +"a = [] # OK\n" +"a = 2 # OK\n" +"\n" +"s: str = ''\n" +"s = a # OK\n" +"\n" +"def foo(item: Any) -> int:\n" +" # Passes type checking; 'item' could be any type,\n" +" # and that type might have a 'bar' method\n" +" item.bar()\n" +" ..." +msgstr "" +"from typing import Any\n" +"\n" +"a: Any = None\n" +"a = [] # OK\n" +"a = 2 # OK\n" +"\n" +"s: str = ''\n" +"s = a # OK\n" +"\n" +"def foo(item: Any) -> int:\n" +" # Passa na verificação de tipos; 'item' pode ser qualquer tipo,\n" +" # e esse tipo pode ter um método 'bar'\n" +" item.bar()\n" +" ..." + +#: ../../library/typing.rst:738 msgid "" "Notice that no type checking is performed when assigning a value of type :" "data:`Any` to a more precise type. For example, the static type checker did " @@ -734,7 +1616,7 @@ msgstr "" "sido declarado como sendo do tipo :class:`str` e receba um valor :class:" "`int` em tempo de execução!" -#: ../../library/typing.rst:663 +#: ../../library/typing.rst:744 msgid "" "Furthermore, all functions without a return type or parameter types will " "implicitly default to using :data:`Any`::" @@ -742,7 +1624,29 @@ msgstr "" "Além disso, todas as funções sem um tipo de retorno ou tipos de parâmetro " "terão como padrão implicitamente o uso de :data:`Any`::" -#: ../../library/typing.rst:676 +#: ../../library/typing.rst:747 +msgid "" +"def legacy_parser(text):\n" +" ...\n" +" return data\n" +"\n" +"# A static type checker will treat the above\n" +"# as having the same signature as:\n" +"def legacy_parser(text: Any) -> Any:\n" +" ...\n" +" return data" +msgstr "" +"def legacy_parser(text):\n" +" ...\n" +" return data\n" +"\n" +"# Um verificador de tipo estático tratará a função acima\n" +"# como tendo a mesma assinatura da função abaixo:\n" +"def legacy_parser(text: Any) -> Any:\n" +" ...\n" +" return data" + +#: ../../library/typing.rst:757 msgid "" "This behavior allows :data:`Any` to be used as an *escape hatch* when you " "need to mix dynamically and statically typed code." @@ -751,7 +1655,7 @@ msgstr "" "emergência* quando você precisar misturar código tipado dinamicamente e " "estaticamente." -#: ../../library/typing.rst:679 +#: ../../library/typing.rst:760 msgid "" "Contrast the behavior of :data:`Any` with the behavior of :class:`object`. " "Similar to :data:`Any`, every type is a subtype of :class:`object`. However, " @@ -763,7 +1667,7 @@ msgstr "" "`object`. No entanto, ao contrário de :data:`Any`, o inverso não é " "verdadeiro: :class:`object` *não* é um subtipo de qualquer outro tipo." -#: ../../library/typing.rst:684 +#: ../../library/typing.rst:765 msgid "" "That means when the type of a value is :class:`object`, a type checker will " "reject almost all operations on it, and assigning it to a variable (or using " @@ -775,7 +1679,46 @@ msgstr "" "uma variável (ou usá-la como valor de retorno) de um tipo mais especializado " "é um tipo erro. Por exemplo::" -#: ../../library/typing.rst:706 +#: ../../library/typing.rst:769 +msgid "" +"def hash_a(item: object) -> int:\n" +" # Fails type checking; an object does not have a 'magic' method.\n" +" item.magic()\n" +" ...\n" +"\n" +"def hash_b(item: Any) -> int:\n" +" # Passes type checking\n" +" item.magic()\n" +" ...\n" +"\n" +"# Passes type checking, since ints and strs are subclasses of object\n" +"hash_a(42)\n" +"hash_a(\"foo\")\n" +"\n" +"# Passes type checking, since Any is compatible with all types\n" +"hash_b(42)\n" +"hash_b(\"foo\")" +msgstr "" +"def hash_a(item: object) -> int:\n" +" # Falha na verificação de tipo; um 'object' não tem um método 'magic'.\n" +" item.magic()\n" +" ...\n" +"\n" +"def hash_b(item: Any) -> int:\n" +" # Passa na verificação de tipo\n" +" item.magic()\n" +" ...\n" +"\n" +"# Passa na verificação de tipo, já que ints e strs são subclasses de " +"'object'\n" +"hash_a(42)\n" +"hash_a(\"foo\")\n" +"\n" +"# Passa na verificação de tipo, já que Any é compatível com todos os tipos\n" +"hash_b(42)\n" +"hash_b(\"foo\")" + +#: ../../library/typing.rst:787 msgid "" "Use :class:`object` to indicate that a value could be any type in a typesafe " "manner. Use :data:`Any` to indicate that a value is dynamically typed." @@ -784,11 +1727,11 @@ msgstr "" "maneira segura. Use :data:`Any` para indicar que um valor é tipado " "dinamicamente." -#: ../../library/typing.rst:711 +#: ../../library/typing.rst:792 msgid "Nominal vs structural subtyping" msgstr "Subtipagem nominal vs estrutural" -#: ../../library/typing.rst:713 +#: ../../library/typing.rst:794 msgid "" "Initially :pep:`484` defined the Python static type system as using *nominal " "subtyping*. This means that a class ``A`` is allowed where a class ``B`` is " @@ -799,7 +1742,7 @@ msgstr "" "permitida onde uma classe ``B`` é esperada se e somente se ``A`` for uma " "subclasse de ``B``." -#: ../../library/typing.rst:717 +#: ../../library/typing.rst:798 msgid "" "This requirement previously also applied to abstract base classes, such as :" "class:`~collections.abc.Iterable`. The problem with this approach is that a " @@ -814,7 +1757,23 @@ msgstr "" "tipo dinamicamente idiomático. Por exemplo, isso está em conformidade com :" "pep:`484`::" -#: ../../library/typing.rst:730 +#: ../../library/typing.rst:804 +msgid "" +"from collections.abc import Sized, Iterable, Iterator\n" +"\n" +"class Bucket(Sized, Iterable[int]):\n" +" ...\n" +" def __len__(self) -> int: ...\n" +" def __iter__(self) -> Iterator[int]: ..." +msgstr "" +"from collections.abc import Sized, Iterable, Iterator\n" +"\n" +"class Bucket(Sized, Iterable[int]):\n" +" ...\n" +" def __len__(self) -> int: ...\n" +" def __iter__(self) -> Iterator[int]: ..." + +#: ../../library/typing.rst:811 msgid "" ":pep:`544` allows to solve this problem by allowing users to write the above " "code without explicit base classes in the class definition, allowing " @@ -828,7 +1787,29 @@ msgstr "" "``Sized`` e ``Iterable[int]`` por verificador de tipo estático. Isso é " "conhecido como *subtipagem estrutural* (ou tipagem pato estática)::" -#: ../../library/typing.rst:746 +#: ../../library/typing.rst:817 +msgid "" +"from collections.abc import Iterator, Iterable\n" +"\n" +"class Bucket: # Note: no base classes\n" +" ...\n" +" def __len__(self) -> int: ...\n" +" def __iter__(self) -> Iterator[int]: ...\n" +"\n" +"def collect(items: Iterable[int]) -> int: ...\n" +"result = collect(Bucket()) # Passes type check" +msgstr "" +"from collections.abc import Iterator, Iterable\n" +"\n" +"class Bucket: # Nota: sem classes base\n" +" ...\n" +" def __len__(self) -> int: ...\n" +" def __iter__(self) -> Iterator[int]: ...\n" +"\n" +"def collect(items: Iterable[int]) -> int: ...\n" +"result = collect(Bucket()) # Passa na verificação de tipo" + +#: ../../library/typing.rst:827 msgid "" "Moreover, by subclassing a special class :class:`Protocol`, a user can " "define new custom protocols to fully enjoy structural subtyping (see " @@ -838,26 +1819,26 @@ msgstr "" "um usuário pode definir novos protocolos personalizados para aproveitar ao " "máximo a subtipagem estrutural (veja exemplos abaixo)." -#: ../../library/typing.rst:751 +#: ../../library/typing.rst:832 msgid "Module contents" msgstr "Conteúdo do módulo" -#: ../../library/typing.rst:753 +#: ../../library/typing.rst:834 msgid "" "The ``typing`` module defines the following classes, functions and " "decorators." msgstr "" "O módulo ``typing`` define as seguintes classes, funções e decoracores." -#: ../../library/typing.rst:756 +#: ../../library/typing.rst:837 msgid "Special typing primitives" msgstr "Tipos primitivos especiais" -#: ../../library/typing.rst:759 +#: ../../library/typing.rst:840 msgid "Special types" msgstr "Tipos especiais" -#: ../../library/typing.rst:761 +#: ../../library/typing.rst:842 msgid "" "These can be used as types in annotations. They do not support subscription " "using ``[]``." @@ -865,19 +1846,19 @@ msgstr "" "Eles podem ser usados como tipos em anotações. Eles não oferecem suporte a " "subscrição usando ``[]``." -#: ../../library/typing.rst:766 +#: ../../library/typing.rst:847 msgid "Special type indicating an unconstrained type." msgstr "Tipo especial que indica um tipo irrestrito." -#: ../../library/typing.rst:768 +#: ../../library/typing.rst:849 msgid "Every type is compatible with :data:`Any`." msgstr "Todos os tipos são compatíveis com :data:`Any`." -#: ../../library/typing.rst:769 +#: ../../library/typing.rst:850 msgid ":data:`Any` is compatible with every type." msgstr ":data:`Any` é compatível com todos os tipos." -#: ../../library/typing.rst:771 +#: ../../library/typing.rst:852 msgid "" ":data:`Any` can now be used as a base class. This can be useful for avoiding " "type checker errors with classes that can duck type anywhere or are highly " @@ -887,15 +1868,19 @@ msgstr "" "evitar erros do verificador de tipo com classes que podem digitar em " "qualquer lugar ou são altamente dinâmicas." -#: ../../library/typing.rst:778 +#: ../../library/typing.rst:859 msgid "A :ref:`constrained type variable `." -msgstr "Uma :ref:`variável de tipo restrito `." +msgstr "Uma :ref:`tipo variável restrito `." -#: ../../library/typing.rst:780 +#: ../../library/typing.rst:861 msgid "Definition::" msgstr "Definição::" -#: ../../library/typing.rst:784 +#: ../../library/typing.rst:863 +msgid "AnyStr = TypeVar('AnyStr', str, bytes)" +msgstr "AnyStr = TypeVar('AnyStr', str, bytes)" + +#: ../../library/typing.rst:865 msgid "" "``AnyStr`` is meant to be used for functions that may accept :class:`str` " "or :class:`bytes` arguments but cannot allow the two to mix." @@ -903,15 +1888,31 @@ msgstr "" "``AnyStr`` deve ser usado para funções que podem aceitar argumentos :class:" "`str` ou :class:`bytes` mas não podem permitir que os dois se misturem." -#: ../../library/typing.rst:787 ../../library/typing.rst:905 -#: ../../library/typing.rst:962 ../../library/typing.rst:1128 -#: ../../library/typing.rst:1189 ../../library/typing.rst:1231 -#: ../../library/typing.rst:1429 ../../library/typing.rst:1490 -#: ../../library/typing.rst:2965 ../../library/typing.rst:3191 +#: ../../library/typing.rst:868 ../../library/typing.rst:986 +#: ../../library/typing.rst:1043 ../../library/typing.rst:1215 +#: ../../library/typing.rst:1302 ../../library/typing.rst:1344 +#: ../../library/typing.rst:1553 ../../library/typing.rst:1614 +#: ../../library/typing.rst:3098 ../../library/typing.rst:3326 msgid "For example::" msgstr "Por exemplo::" -#: ../../library/typing.rst:796 +#: ../../library/typing.rst:870 +msgid "" +"def concat(a: AnyStr, b: AnyStr) -> AnyStr:\n" +" return a + b\n" +"\n" +"concat(\"foo\", \"bar\") # OK, output has type 'str'\n" +"concat(b\"foo\", b\"bar\") # OK, output has type 'bytes'\n" +"concat(\"foo\", b\"bar\") # Error, cannot mix str and bytes" +msgstr "" +"def concat(a: AnyStr, b: AnyStr) -> AnyStr:\n" +" return a + b\n" +"\n" +"concat(\"foo\", \"bar\") # OK: saída tem tipo 'str'\n" +"concat(b\"foo\", b\"bar\") # OK: saída tem tipo 'bytes'\n" +"concat(\"foo\", b\"bar\") # Erro: não se mistura str com bytes" + +#: ../../library/typing.rst:877 msgid "" "Note that, despite its name, ``AnyStr`` has nothing to do with the :class:" "`Any` type, nor does it mean \"any string\". In particular, ``AnyStr`` and " @@ -921,7 +1922,29 @@ msgstr "" "`Any`, nem significa \"qualquer string\". Em particular, ``AnyStr`` e ``str " "| bytes`` são diferentes entre si e têm casos de uso diferentes::" -#: ../../library/typing.rst:811 +#: ../../library/typing.rst:882 +msgid "" +"# Invalid use of AnyStr:\n" +"# The type variable is used only once in the function signature,\n" +"# so cannot be \"solved\" by the type checker\n" +"def greet_bad(cond: bool) -> AnyStr:\n" +" return \"hi there!\" if cond else b\"greetings!\"\n" +"\n" +"# The better way of annotating this function:\n" +"def greet_proper(cond: bool) -> str | bytes:\n" +" return \"hi there!\" if cond else b\"greetings!\"" +msgstr "" +"# Uso inválido de AnyStr:\n" +"# A variável de tipo é usada somente uma vez na assinatura da função,\n" +"# então não pode ser \"resolvida\" pelo verificador de tipo\n" +"def greet_bad(cond: bool) -> AnyStr:\n" +" return \"hi there!\" if cond else b\"greetings!\"\n" +"\n" +"# O jeito melhor de anotar esta função\n" +"def greet_proper(cond: bool) -> str | bytes:\n" +" return \"hi there!\" if cond else b\"greetings!\"" + +#: ../../library/typing.rst:892 msgid "" "Deprecated in favor of the new :ref:`type parameter syntax `. " "Use ``class A[T: (str, bytes)]: ...`` instead of importing ``AnyStr``. See :" @@ -931,7 +1954,7 @@ msgstr "" "params>`. Use ``class A[T: (str, bytes)]: ...`` em vez de importar " "``AnyStr``. Veja a :pep:`695` para mais detalhes." -#: ../../library/typing.rst:816 +#: ../../library/typing.rst:897 msgid "" "In Python 3.16, ``AnyStr`` will be removed from ``typing.__all__``, and " "deprecation warnings will be emitted at runtime when it is accessed or " @@ -943,11 +1966,11 @@ msgstr "" "ou importado de ``typing``. ``AnyStr`` será removido do ``typing`` no Python " "3.18." -#: ../../library/typing.rst:823 +#: ../../library/typing.rst:904 msgid "Special type that includes only literal strings." msgstr "Tipo especial que inclui apenas strings literais." -#: ../../library/typing.rst:825 +#: ../../library/typing.rst:906 msgid "" "Any string literal is compatible with ``LiteralString``, as is another " "``LiteralString``. However, an object typed as just ``str`` is not. A string " @@ -959,11 +1982,37 @@ msgstr "" "é. Uma string criada pela composição de objetos do tipo ``LiteralString`` " "também é aceitável como uma ``LiteralString``." -#: ../../library/typing.rst:831 ../../library/typing.rst:2061 +#: ../../library/typing.rst:912 ../../library/typing.rst:2185 msgid "Example:" msgstr "Exemplo:" -#: ../../library/typing.rst:847 +#: ../../library/typing.rst:914 +msgid "" +"def run_query(sql: LiteralString) -> None:\n" +" ...\n" +"\n" +"def caller(arbitrary_string: str, literal_string: LiteralString) -> None:\n" +" run_query(\"SELECT * FROM students\") # OK\n" +" run_query(literal_string) # OK\n" +" run_query(\"SELECT * FROM \" + literal_string) # OK\n" +" run_query(arbitrary_string) # type checker error\n" +" run_query( # type checker error\n" +" f\"SELECT * FROM students WHERE name = {arbitrary_string}\"\n" +" )" +msgstr "" +"def run_query(sql: LiteralString) -> None:\n" +" ...\n" +"\n" +"def caller(arbitrary_string: str, literal_string: LiteralString) -> None:\n" +" run_query(\"SELECT * FROM students\") # OK\n" +" run_query(literal_string) # OK\n" +" run_query(\"SELECT * FROM \" + literal_string) # OK\n" +" run_query(arbitrary_string) # erro no verificador\n" +" run_query( # erro no verificador\n" +" f\"SELECT * FROM students WHERE name = {arbitrary_string}\"\n" +" )" + +#: ../../library/typing.rst:928 msgid "" "``LiteralString`` is useful for sensitive APIs where arbitrary user-" "generated strings could generate problems. For example, the two cases above " @@ -975,11 +2024,11 @@ msgstr "" "que geram erros no verificador de tipo podem ser vulneráveis a um ataque de " "injeção de SQL." -#: ../../library/typing.rst:852 +#: ../../library/typing.rst:933 msgid "See :pep:`675` for more details." msgstr "Veja :pep:`675` para mais detalhes." -#: ../../library/typing.rst:859 +#: ../../library/typing.rst:940 msgid "" ":data:`!Never` and :data:`!NoReturn` represent the `bottom type `_, a type that has no members." @@ -987,15 +2036,27 @@ msgstr "" ":data:`!Never` e :data:`!NoReturn` representam o `tipo inferior `_, um tipo que não possui membros." -#: ../../library/typing.rst:863 +#: ../../library/typing.rst:944 msgid "" "They can be used to indicate that a function never returns, such as :func:" "`sys.exit`::" msgstr "" -"Eles podem ser usados ​​para indicar que uma função nunca retorna, como :func:" +"Eles podem ser usados para indicar que uma função nunca retorna, como :func:" "`sys.exit`::" -#: ../../library/typing.rst:871 +#: ../../library/typing.rst:947 +msgid "" +"from typing import Never # or NoReturn\n" +"\n" +"def stop() -> Never:\n" +" raise RuntimeError('no way')" +msgstr "" +"from typing import Never # ou NoReturn\n" +"\n" +"def stop() -> Never:\n" +" raise RuntimeError('no way')" + +#: ../../library/typing.rst:952 msgid "" "Or to define a function that should never be called, as there are no valid " "arguments, such as :func:`assert_never`::" @@ -1003,7 +2064,39 @@ msgstr "" "Ou para definir uma função que nunca deve ser chamada, pois não existem " "argumentos válidos, como :func:`assert_never`::" -#: ../../library/typing.rst:890 +#: ../../library/typing.rst:956 +msgid "" +"from typing import Never # or NoReturn\n" +"\n" +"def never_call_me(arg: Never) -> None:\n" +" pass\n" +"\n" +"def int_or_str(arg: int | str) -> None:\n" +" never_call_me(arg) # type checker error\n" +" match arg:\n" +" case int():\n" +" print(\"It's an int\")\n" +" case str():\n" +" print(\"It's a str\")\n" +" case _:\n" +" never_call_me(arg) # OK, arg is of type Never (or NoReturn)" +msgstr "" +"from typing import Never # or NoReturn\n" +"\n" +"def never_call_me(arg: Never) -> None:\n" +" pass\n" +"\n" +"def int_or_str(arg: int | str) -> None:\n" +" never_call_me(arg) # erro no verificador\n" +" match arg:\n" +" case int():\n" +" print(\"It's an int\")\n" +" case str():\n" +" print(\"It's a str\")\n" +" case _:\n" +" never_call_me(arg) # OK, arg é do tipo Never (ou NoReturn)" + +#: ../../library/typing.rst:971 msgid "" ":data:`!Never` and :data:`!NoReturn` have the same meaning in the type " "system and static type checkers treat both equivalently." @@ -1011,19 +2104,47 @@ msgstr "" ":data:`!Never` e :data:`!NoReturn` têm o mesmo significado no sistema de " "tipos e os verificadores de tipo estático tratam ambos de forma equivalente." -#: ../../library/typing.rst:895 +#: ../../library/typing.rst:976 msgid "Added :data:`NoReturn`." msgstr "Adicionado :data:`NoReturn`." -#: ../../library/typing.rst:899 +#: ../../library/typing.rst:980 msgid "Added :data:`Never`." msgstr "Adicionado :data:`Never`." -#: ../../library/typing.rst:903 +#: ../../library/typing.rst:984 msgid "Special type to represent the current enclosed class." msgstr "Tipo especial para representar a classe atual inclusa." -#: ../../library/typing.rst:919 +#: ../../library/typing.rst:988 +msgid "" +"from typing import Self, reveal_type\n" +"\n" +"class Foo:\n" +" def return_self(self) -> Self:\n" +" ...\n" +" return self\n" +"\n" +"class SubclassOfFoo(Foo): pass\n" +"\n" +"reveal_type(Foo().return_self()) # Revealed type is \"Foo\"\n" +"reveal_type(SubclassOfFoo().return_self()) # Revealed type is " +"\"SubclassOfFoo\"" +msgstr "" +"from typing import Self, reveal_type\n" +"\n" +"class Foo:\n" +" def return_self(self) -> Self:\n" +" ...\n" +" return self\n" +"\n" +"class SubclassOfFoo(Foo): pass\n" +"\n" +"reveal_type(Foo().return_self()) # Tipo revelado é \"Foo\"\n" +"reveal_type(SubclassOfFoo().return_self()) # Tipo revelado é " +"\"SubclassOfFoo\"" + +#: ../../library/typing.rst:1000 msgid "" "This annotation is semantically equivalent to the following, albeit in a " "more succinct fashion::" @@ -1031,7 +2152,27 @@ msgstr "" "Esta anotação é semanticamente equivalente à seguinte, embora de forma mais " "sucinta::" -#: ../../library/typing.rst:931 +#: ../../library/typing.rst:1003 +msgid "" +"from typing import TypeVar\n" +"\n" +"Self = TypeVar(\"Self\", bound=\"Foo\")\n" +"\n" +"class Foo:\n" +" def return_self(self: Self) -> Self:\n" +" ...\n" +" return self" +msgstr "" +"from typing import TypeVar\n" +"\n" +"Self = TypeVar(\"Self\", bound=\"Foo\")\n" +"\n" +"class Foo:\n" +" def return_self(self: Self) -> Self:\n" +" ...\n" +" return self" + +#: ../../library/typing.rst:1012 msgid "" "In general, if something returns ``self``, as in the above examples, you " "should use ``Self`` as the return annotation. If ``Foo.return_self`` was " @@ -1045,11 +2186,11 @@ msgstr "" "retornado de ``SubclassOfFoo.return_self`` como sendo do tipo ``Foo`` em vez " "de ``SubclassOfFoo``." -#: ../../library/typing.rst:937 +#: ../../library/typing.rst:1018 msgid "Other common use cases include:" msgstr "Outros casos de uso comuns incluem:" -#: ../../library/typing.rst:939 +#: ../../library/typing.rst:1020 msgid "" ":class:`classmethod`\\s that are used as alternative constructors and return " "instances of the ``cls`` parameter." @@ -1057,11 +2198,11 @@ msgstr "" ":class:`classmethod`\\s que são usados como construtores alternativos e " "retornam instâncias do parâmetro ``cls``." -#: ../../library/typing.rst:941 +#: ../../library/typing.rst:1022 msgid "Annotating an :meth:`~object.__enter__` method which returns self." msgstr "Anotando um método :meth:`~object.__enter__` que retorna self." -#: ../../library/typing.rst:943 +#: ../../library/typing.rst:1024 msgid "" "You should not use ``Self`` as the return annotation if the method is not " "guaranteed to return an instance of a subclass when the class is subclassed::" @@ -1070,11 +2211,27 @@ msgstr "" "garantido que o método retorne uma instância de uma subclasse quando a " "classe for subclassificada::" -#: ../../library/typing.rst:954 +#: ../../library/typing.rst:1028 +msgid "" +"class Eggs:\n" +" # Self would be an incorrect return annotation here,\n" +" # as the object returned is always an instance of Eggs,\n" +" # even in subclasses\n" +" def returns_eggs(self) -> \"Eggs\":\n" +" return Eggs()" +msgstr "" +"class Eggs:\n" +" # Self seria uma anotação de retorno incorreta aqui,\n" +" # já que o objeto retornado sempre é instância de Eggs,\n" +" # inclusive em subclasses\n" +" def returns_eggs(self) -> \"Eggs\":\n" +" return Eggs()" + +#: ../../library/typing.rst:1035 msgid "See :pep:`673` for more details." msgstr "Veja :pep:`673` para mais detalhes." -#: ../../library/typing.rst:960 +#: ../../library/typing.rst:1041 msgid "" "Special annotation for explicitly declaring a :ref:`type alias `." @@ -1082,7 +2239,17 @@ msgstr "" "Anotações especiais para declarar explicitamente um :ref:`apelido de tipo " "`." -#: ../../library/typing.rst:968 +#: ../../library/typing.rst:1045 +msgid "" +"from typing import TypeAlias\n" +"\n" +"Factors: TypeAlias = list[int]" +msgstr "" +"from typing import TypeAlias\n" +"\n" +"Factors: TypeAlias = list[int]" + +#: ../../library/typing.rst:1049 msgid "" "``TypeAlias`` is particularly useful on older Python versions for annotating " "aliases that make use of forward references, as it can be hard for type " @@ -1093,11 +2260,43 @@ msgstr "" "para os verificadores de tipo distingui-los das atribuições normais de " "variáveis:" -#: ../../library/typing.rst:988 +#: ../../library/typing.rst:1053 +msgid "" +"from typing import Generic, TypeAlias, TypeVar\n" +"\n" +"T = TypeVar(\"T\")\n" +"\n" +"# \"Box\" does not exist yet,\n" +"# so we have to use quotes for the forward reference on Python <3.12.\n" +"# Using ``TypeAlias`` tells the type checker that this is a type alias " +"declaration,\n" +"# not a variable assignment to a string.\n" +"BoxOfStrings: TypeAlias = \"Box[str]\"\n" +"\n" +"class Box(Generic[T]):\n" +" @classmethod\n" +" def make_box_of_strings(cls) -> BoxOfStrings: ..." +msgstr "" +"from typing import Generic, TypeAlias, TypeVar\n" +"\n" +"T = TypeVar(\"T\")\n" +"\n" +"# \"Box\" não existe ainda,\n" +"# então temos que usar aspas para a referência futura em Python <3.12.\n" +"# Usar ``TypeAlias`` diz ao verificador de tipo que isso é uma declaração de " +"apelido de tipo,\n" +"# e não uma atribuição de variável a string.\n" +"BoxOfStrings: TypeAlias = \"Box[str]\"\n" +"\n" +"class Box(Generic[T]):\n" +" @classmethod\n" +" def make_box_of_strings(cls) -> BoxOfStrings: ..." + +#: ../../library/typing.rst:1069 msgid "See :pep:`613` for more details." msgstr "Veja :pep:`613` para mais detalhes." -#: ../../library/typing.rst:992 +#: ../../library/typing.rst:1073 msgid "" ":data:`TypeAlias` is deprecated in favor of the :keyword:`type` statement, " "which creates instances of :class:`TypeAliasType` and which natively " @@ -1108,33 +2307,33 @@ msgid "" "to :keyword:`type` statements." msgstr "" ":data:`TypeAlias` foi descontinuado em favor da instrução :keyword:`type`, " -"que cria instâncias de :class:`TypeAliasType` e que oferece suporte a " -"nativamente referências futuras. Observe que embora :data:`TypeAlias` e :" -"class:`TypeAliasType` sirvam propósitos semelhantes e tenham nomes " -"semelhantes, eles são distintos e o último não é o tipo do primeiro. A " -"remoção de :data:`TypeAlias` não está planejada atualmente, mas os usuários " -"são encorajados a migrar para instruções :keyword:`type`." - -#: ../../library/typing.rst:1003 +"que cria instâncias de :class:`TypeAliasType` e oferece suporte nativo a " +"referências futuras. Observe que embora :data:`TypeAlias` e :class:" +"`TypeAliasType` sirvam propósitos semelhantes e tenham nomes semelhantes, " +"eles são distintos e o último não é o tipo do primeiro. A remoção de :data:" +"`TypeAlias` não está planejada atualmente, mas os usuários são encorajados a " +"migrar para instruções :keyword:`type`." + +#: ../../library/typing.rst:1084 msgid "Special forms" msgstr "Formas especiais" -#: ../../library/typing.rst:1005 +#: ../../library/typing.rst:1086 msgid "" "These can be used as types in annotations. They all support subscription " "using ``[]``, but each has a unique syntax." msgstr "" -"Eles podem ser usados ​​como tipos em anotações. Todos eles oferecem suporte a " +"Eles podem ser usados como tipos em anotações. Todos eles oferecem suporte a " "subscrição usando ``[]``, mas cada um tem uma sintaxe única." -#: ../../library/typing.rst:1010 +#: ../../library/typing.rst:1091 msgid "" "Union type; ``Union[X, Y]`` is equivalent to ``X | Y`` and means either X or " "Y." msgstr "" "Tipo de união; ``Union[X, Y]`` é equivalente a ``X | Y`` e significa X ou Y." -#: ../../library/typing.rst:1012 +#: ../../library/typing.rst:1093 msgid "" "To define a union, use e.g. ``Union[int, str]`` or the shorthand ``int | " "str``. Using that shorthand is recommended. Details:" @@ -1142,74 +2341,127 @@ msgstr "" "Para definir uma união, use, por exemplo. ``Union[int, str]`` ou a " "abreviatura ``int | str``. Usar essa abreviação é recomendado. Detalhes:" -#: ../../library/typing.rst:1014 +#: ../../library/typing.rst:1095 msgid "The arguments must be types and there must be at least one." msgstr "Os argumentos devem ser tipos e deve haver pelo menos um." -#: ../../library/typing.rst:1016 +#: ../../library/typing.rst:1097 msgid "Unions of unions are flattened, e.g.::" msgstr "As uniões de uniões são achatadas, por exemplo::" -#: ../../library/typing.rst:1020 +#: ../../library/typing.rst:1099 +msgid "Union[Union[int, str], float] == Union[int, str, float]" +msgstr "Union[Union[int, str], float] == Union[int, str, float]" + +#: ../../library/typing.rst:1101 +msgid "" +"However, this does not apply to unions referenced through a type alias, to " +"avoid forcing evaluation of the underlying :class:`TypeAliasType`::" +msgstr "" + +#: ../../library/typing.rst:1104 +msgid "" +"type A = Union[int, str]\n" +"Union[A, float] != Union[int, str, float]" +msgstr "" + +#: ../../library/typing.rst:1107 msgid "Unions of a single argument vanish, e.g.::" msgstr "As uniões de um único argumento desaparecem, por exemplo::" -#: ../../library/typing.rst:1024 +#: ../../library/typing.rst:1109 +msgid "Union[int] == int # The constructor actually returns int" +msgstr "Union[int] == int # O construtor retorna um int" + +#: ../../library/typing.rst:1111 ../../library/typing.rst:1245 msgid "Redundant arguments are skipped, e.g.::" msgstr "Argumento redundantes são pulados, e.g.::" -#: ../../library/typing.rst:1028 +#: ../../library/typing.rst:1113 +msgid "Union[int, str, int] == Union[int, str] == int | str" +msgstr "Union[int, str, int] == Union[int, str] == int | str" + +#: ../../library/typing.rst:1115 msgid "When comparing unions, the argument order is ignored, e.g.::" -msgstr "" +msgstr "Ao comparar uniões, a ordem de argumentos é ignorada. Por exemplo::" -#: ../../library/typing.rst:1032 +#: ../../library/typing.rst:1117 +msgid "Union[int, str] == Union[str, int]" +msgstr "Union[int, str] == Union[str, int]" + +#: ../../library/typing.rst:1119 msgid "You cannot subclass or instantiate a ``Union``." msgstr "Você não pode estender ou instanciar uma ``Union``" -#: ../../library/typing.rst:1034 +#: ../../library/typing.rst:1121 msgid "You cannot write ``Union[X][Y]``." msgstr "Você não pode escrever ``Union[X][Y]``." -#: ../../library/typing.rst:1036 +#: ../../library/typing.rst:1123 msgid "Don't remove explicit subclasses from unions at runtime." -msgstr "" +msgstr "Não remova subclasses explícitas de uniões em tempo de execução." -#: ../../library/typing.rst:1039 +#: ../../library/typing.rst:1126 msgid "" "Unions can now be written as ``X | Y``. See :ref:`union type " "expressions`." msgstr "" +"Uniões agora podem ser escritas com ``X | Y``. Veja :ref:`expressões de " +"união de tipos `." -#: ../../library/typing.rst:1045 +#: ../../library/typing.rst:1132 msgid "``Optional[X]`` is equivalent to ``X | None`` (or ``Union[X, None]``)." -msgstr "" +msgstr "``Optional[X]`` equivale a ``X | None`` (ou ``Union[X, None]``)." -#: ../../library/typing.rst:1047 +#: ../../library/typing.rst:1134 msgid "" "Note that this is not the same concept as an optional argument, which is one " "that has a default. An optional argument with a default does not require " "the ``Optional`` qualifier on its type annotation just because it is " "optional. For example::" msgstr "" +"Note que isso não é o mesmo conceito de um argumento opcional, que possui um " +"valor por padrão. Um argumento opcional com padrão não requer o qualificador " +"``Optional`` em sua anotação de tipo só por ser opcional. Por exemplo::" + +#: ../../library/typing.rst:1139 +msgid "" +"def foo(arg: int = 0) -> None:\n" +" ..." +msgstr "" +"def foo(arg: int = 0) -> None:\n" +" ..." -#: ../../library/typing.rst:1055 +#: ../../library/typing.rst:1142 msgid "" "On the other hand, if an explicit value of ``None`` is allowed, the use of " "``Optional`` is appropriate, whether the argument is optional or not. For " "example::" msgstr "" +"Por outro lado, se um valor explícito de ``None`` for permitido, o uso de " +"``Optional`` é apropriado, seja o argumento opcional ou não. Por exemplo::" + +#: ../../library/typing.rst:1146 +msgid "" +"def foo(arg: Optional[int] = None) -> None:\n" +" ..." +msgstr "" +"def foo(arg: Optional[int] = None) -> None:\n" +" ..." -#: ../../library/typing.rst:1062 +#: ../../library/typing.rst:1149 msgid "" "Optional can now be written as ``X | None``. See :ref:`union type " "expressions`." msgstr "" +"Optional agora pode ser escrito como ``X | None``. Veja :ref:`expressões de " +"união de tipos`." -#: ../../library/typing.rst:1068 +#: ../../library/typing.rst:1155 msgid "Special form for annotating higher-order functions." msgstr "Forma especial para anotar funções de ordem superior." -#: ../../library/typing.rst:1070 +#: ../../library/typing.rst:1157 msgid "" "``Concatenate`` can be used in conjunction with :ref:`Callable ` and :class:`ParamSpec` to annotate a higher-order callable which " @@ -1219,8 +2471,15 @@ msgid "" "a :ref:`Callable `. The last parameter to " "``Concatenate`` must be a :class:`ParamSpec` or ellipsis (``...``)." msgstr "" +"``Concatenate`` pode ser usado em conjunção com :ref:`Callable ` e :class:`ParamSpec` para anotar um chamável de maior ordem que " +"adiciona, remove ou transforma parâmetros de outro chamável. Seu uso é feito " +"na forma ``Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]``, " +"``Concatenate`` atualmente só é válido quando usado como primeiro argumento " +"de um :ref:`Callable `. O último parâmetro de " +"``Concatenate`` deve ser um :class:`ParamSpec` ou reticências (``...``)." -#: ../../library/typing.rst:1079 +#: ../../library/typing.rst:1166 msgid "" "For example, to annotate a decorator ``with_lock`` which provides a :class:" "`threading.Lock` to the decorated function, ``Concatenate`` can be used to " @@ -1230,140 +2489,373 @@ msgid "" "parameter types are dependent on the parameter types of the callable being " "passed in::" msgstr "" - -#: ../../library/typing.rst:1115 ../../library/typing.rst:2029 +"Por exemplo, para anotar um decorador ``with_lock`` que oferece uma " +"instância de :class:`threading.Lock` para a função decorada, ``Concatenate`` " +"pode ser usado para indicar que ``with_lock`` espera um chamável cujo " +"primeiro argumento tem tipo ``Lock``, e retorna um chamável com uma " +"assinatura de tipos diferente. Neste caso, o :class:`ParamSpec` indica que " +"os tipos dos parâmetros do chamável retornado dependem dos tipos dos " +"parâmetros do chamável de entrada::" + +#: ../../library/typing.rst:1174 +msgid "" +"from collections.abc import Callable\n" +"from threading import Lock\n" +"from typing import Concatenate\n" +"\n" +"# Use this lock to ensure that only one thread is executing a function\n" +"# at any time.\n" +"my_lock = Lock()\n" +"\n" +"def with_lock[**P, R](f: Callable[Concatenate[Lock, P], R]) -> Callable[P, " +"R]:\n" +" '''A type-safe decorator which provides a lock.'''\n" +" def inner(*args: P.args, **kwargs: P.kwargs) -> R:\n" +" # Provide the lock as the first argument.\n" +" return f(my_lock, *args, **kwargs)\n" +" return inner\n" +"\n" +"@with_lock\n" +"def sum_threadsafe(lock: Lock, numbers: list[float]) -> float:\n" +" '''Add a list of numbers together in a thread-safe manner.'''\n" +" with lock:\n" +" return sum(numbers)\n" +"\n" +"# We don't need to pass in the lock ourselves thanks to the decorator.\n" +"sum_threadsafe([1.1, 2.2, 3.3])" +msgstr "" +"from collections.abc import Callable\n" +"from threading import Lock\n" +"from typing import Concatenate\n" +"\n" +"# Use esta trava para se certificar de que\n" +"# uma única thread a executa a qualquer momento.\n" +"my_lock = Lock()\n" +"\n" +"def with_lock[**P, R](f: Callable[Concatenate[Lock, P], R]) -> Callable[P, " +"R]:\n" +" '''Um decorador com segurança de tipos que oferece uma trava.'''\n" +" def inner(*args: P.args, **kwargs: P.kwargs) -> R:\n" +" # Oferece a trava como primeiro argumento.\n" +" return f(my_lock, *args, **kwargs)\n" +" return inner\n" +"\n" +"@with_lock\n" +"def sum_threadsafe(lock: Lock, numbers: list[float]) -> float:\n" +" '''Somatório de uma lista de números de modo seguro para threads.'''\n" +" with lock:\n" +" return sum(numbers)\n" +"\n" +"# We don't need to pass in the lock ourselves thanks to the decorator.\n" +"sum_threadsafe([1.1, 2.2, 3.3])" + +#: ../../library/typing.rst:1202 ../../library/typing.rst:2153 msgid "" ":pep:`612` -- Parameter Specification Variables (the PEP which introduced " "``ParamSpec`` and ``Concatenate``)" msgstr "" +":pep:`612` -- Variáveis de especificação de parâmetro (a PEP que introduz " +"``ParamSpec`` e ``Concatenate``)" -#: ../../library/typing.rst:1117 +#: ../../library/typing.rst:1204 msgid ":class:`ParamSpec`" -msgstr "" +msgstr ":class:`ParamSpec`" -#: ../../library/typing.rst:1118 ../../library/typing.rst:2032 +#: ../../library/typing.rst:1205 ../../library/typing.rst:2156 msgid ":ref:`annotating-callables`" -msgstr "" +msgstr ":ref:`annotating-callables`" -#: ../../library/typing.rst:1122 +#: ../../library/typing.rst:1209 msgid "Special typing form to define \"literal types\"." -msgstr "" +msgstr "Forma especial de tipagem para definir \"tipos literais\"." -#: ../../library/typing.rst:1124 +#: ../../library/typing.rst:1211 msgid "" "``Literal`` can be used to indicate to type checkers that the annotated " "object has a value equivalent to one of the provided literals." msgstr "" - -#: ../../library/typing.rst:1140 +"``Literal`` pode ser usado para indicar aos verificadores de tipo que o " +"objeto anotado tem valor equivalente a algum dos literais oferecidos." + +#: ../../library/typing.rst:1217 +msgid "" +"def validate_simple(data: Any) -> Literal[True]: # always returns True\n" +" ...\n" +"\n" +"type Mode = Literal['r', 'rb', 'w', 'wb']\n" +"def open_helper(file: str, mode: Mode) -> str:\n" +" ...\n" +"\n" +"open_helper('/some/path', 'r') # Passes type check\n" +"open_helper('/other/path', 'typo') # Error in type checker" +msgstr "" +"def validate_simple(data: Any) -> Literal[True]: # sempre retorna True\n" +" ...\n" +"\n" +"type Mode = Literal['r', 'rb', 'w', 'wb']\n" +"def open_helper(file: str, mode: Mode) -> str:\n" +" ...\n" +"\n" +"open_helper('/some/path', 'r') # Passa verificação de tipos\n" +"open_helper('/other/path', 'typo') # Erro em verificação de tipos" + +#: ../../library/typing.rst:1227 msgid "" "``Literal[...]`` cannot be subclassed. At runtime, an arbitrary value is " "allowed as type argument to ``Literal[...]``, but type checkers may impose " "restrictions. See :pep:`586` for more details about literal types." msgstr "" +"``Literal[...]`` não é subclasse. Em tempo de execução, permite-se um valor " +"arbitrário como argumento de tipo para ``Literal[...]``, mas verificadores " +"de tipo podem impor restrições. Veja :pep:`586` para mais detalhes sobre " +"tipos literais." -#: ../../library/typing.rst:1146 +#: ../../library/typing.rst:1231 +msgid "Additional details:" +msgstr "" + +#: ../../library/typing.rst:1233 +msgid "The arguments must be literal values and there must be at least one." +msgstr "" + +#: ../../library/typing.rst:1235 +msgid "Nested ``Literal`` types are flattened, e.g.::" +msgstr "" + +#: ../../library/typing.rst:1237 +msgid "assert Literal[Literal[1, 2], 3] == Literal[1, 2, 3]" +msgstr "" + +#: ../../library/typing.rst:1239 +msgid "" +"However, this does not apply to ``Literal`` types referenced through a type " +"alias, to avoid forcing evaluation of the underlying :class:`TypeAliasType`::" +msgstr "" + +#: ../../library/typing.rst:1242 +msgid "" +"type A = Literal[1, 2]\n" +"assert Literal[A, 3] != Literal[1, 2, 3]" +msgstr "" + +#: ../../library/typing.rst:1247 +msgid "assert Literal[1, 2, 1] == Literal[1, 2]" +msgstr "" + +#: ../../library/typing.rst:1249 +msgid "When comparing literals, the argument order is ignored, e.g.::" +msgstr "" + +#: ../../library/typing.rst:1251 +msgid "assert Literal[1, 2] == Literal[2, 1]" +msgstr "" + +#: ../../library/typing.rst:1253 +msgid "You cannot subclass or instantiate a ``Literal``." +msgstr "" + +#: ../../library/typing.rst:1255 +msgid "You cannot write ``Literal[X][Y]``." +msgstr "" + +#: ../../library/typing.rst:1259 msgid "" "``Literal`` now de-duplicates parameters. Equality comparisons of " "``Literal`` objects are no longer order dependent. ``Literal`` objects will " "now raise a :exc:`TypeError` exception during equality comparisons if one of " "their parameters are not :term:`hashable`." msgstr "" +"``Literal`` agora remove parâmetros duplicados. Comparações de igualdade " +"entre objetos ``Literal`` não dependem da ordem. Objetos ``Literal`` agora " +"levantam uma exceção :exc:`TypeError` durante comparações de igualdade se um " +"de seus parâmetros não for :term:`hasheável`." -#: ../../library/typing.rst:1154 +#: ../../library/typing.rst:1267 msgid "Special type construct to mark class variables." -msgstr "" +msgstr "Uma construção especial de tipagem para marcar variáveis de classe." -#: ../../library/typing.rst:1156 +#: ../../library/typing.rst:1269 msgid "" "As introduced in :pep:`526`, a variable annotation wrapped in ClassVar " "indicates that a given attribute is intended to be used as a class variable " "and should not be set on instances of that class. Usage::" msgstr "" +"Como introduzido na :pep:`526`, uma variável cuja anotação de tipo tem um " +"invólucro ClassVar indica que um dado atributo deve ser usado como uma " +"variável de classe, e que ele não deve ser definido em instâncias dessa " +"classe. Modo de usar::" + +#: ../../library/typing.rst:1273 +msgid "" +"class Starship:\n" +" stats: ClassVar[dict[str, int]] = {} # class variable\n" +" damage: int = 10 # instance variable" +msgstr "" +"class Starship:\n" +" stats: ClassVar[dict[str, int]] = {} # variável de classe\n" +" damage: int = 10 # variável de instância" -#: ../../library/typing.rst:1164 +#: ../../library/typing.rst:1277 msgid ":data:`ClassVar` accepts only types and cannot be further subscribed." msgstr "" +":data:`ClassVar` aceita apenas tipos e não pode ser subscrita posteriormente." -#: ../../library/typing.rst:1166 +#: ../../library/typing.rst:1279 msgid "" ":data:`ClassVar` is not a class itself, and should not be used with :func:" "`isinstance` or :func:`issubclass`. :data:`ClassVar` does not change Python " "runtime behavior, but it can be used by third-party type checkers. For " "example, a type checker might flag the following code as an error::" msgstr "" +":data:`ClassVar` não é uma classe, e não deve ser usada com :func:" +"`isinstance` ou :func:`issubclass`. :data:`ClassVar` não muda com o " +"comportamento do Python em tempo de execução, mas pode ser usada por " +"verificadores de tipos de terceiros. Por exemplo, um verificador de tipos " +"pode sinalizar que o seguinte código é errado::" + +#: ../../library/typing.rst:1285 +msgid "" +"enterprise_d = Starship(3000)\n" +"enterprise_d.stats = {} # Error, setting class variable on instance\n" +"Starship.stats = {} # This is OK" +msgstr "" +"enterprise_d = Starship(3000)\n" +"enterprise_d.stats = {} # Erro: atribuindo valor a variável de classe de uma " +"instância\n" +"Starship.stats = {} # Isso é OK" -#: ../../library/typing.rst:1180 +#: ../../library/typing.rst:1293 msgid ":data:`ClassVar` can now be nested in :data:`Final` and vice versa." msgstr "" +":data:`ClassVar` agora pode ser aninhada em :data:`Final` e vice-versa." -#: ../../library/typing.rst:1184 +#: ../../library/typing.rst:1297 msgid "Special typing construct to indicate final names to type checkers." msgstr "" +"Uma construção especial de tipagem para indicar nomes finais a verificadores " +"de tipos" -#: ../../library/typing.rst:1186 +#: ../../library/typing.rst:1299 msgid "" "Final names cannot be reassigned in any scope. Final names declared in class " "scopes cannot be overridden in subclasses." msgstr "" +"Nomes finais não podem ser reatribuídos em qualquer escopo. Nomes finais " +"declarados em escopos de classe não podem ser substituídos em subclasses." + +#: ../../library/typing.rst:1304 +msgid "" +"MAX_SIZE: Final = 9000\n" +"MAX_SIZE += 1 # Error reported by type checker\n" +"\n" +"class Connection:\n" +" TIMEOUT: Final[int] = 10\n" +"\n" +"class FastConnector(Connection):\n" +" TIMEOUT = 1 # Error reported by type checker" +msgstr "" +"MAX_SIZE: Final = 9000\n" +"MAX_SIZE += 1 # Erro reportado pelo verificador de tipos\n" +"\n" +"class Connection:\n" +" TIMEOUT: Final[int] = 10\n" +"\n" +"class FastConnector(Connection):\n" +" TIMEOUT = 1 # Error reportado pelo verificador de tipos" -#: ../../library/typing.rst:1200 ../../library/typing.rst:2981 +#: ../../library/typing.rst:1313 ../../library/typing.rst:3114 msgid "" "There is no runtime checking of these properties. See :pep:`591` for more " "details." msgstr "" +"Não há verificação em tempo de execução dessas propriedades. Veja :pep:`591` " +"para mais detalhes." -#: ../../library/typing.rst:1207 +#: ../../library/typing.rst:1320 msgid ":data:`Final` can now be nested in :data:`ClassVar` and vice versa." msgstr "" +":data:`Final` agora pode ser aninhada em :data:`ClassVar` e vice-versa." -#: ../../library/typing.rst:1211 +#: ../../library/typing.rst:1324 msgid "Special typing construct to mark a :class:`TypedDict` key as required." msgstr "" +"Uma construção especial de tipagem para marcar uma chave de :class:" +"`TypedDict` como necessária." -#: ../../library/typing.rst:1213 +#: ../../library/typing.rst:1326 msgid "" "This is mainly useful for ``total=False`` TypedDicts. See :class:`TypedDict` " "and :pep:`655` for more details." msgstr "" +"Isso é útil principalmente para TypedDicts com ``total=False``. Veja :class:" +"`TypedDict` e :pep:`655` para obter mais detalhes." -#: ../../library/typing.rst:1220 +#: ../../library/typing.rst:1333 msgid "" "Special typing construct to mark a :class:`TypedDict` key as potentially " "missing." msgstr "" +"Uma construção especial de tipagem para marcar uma chave de :class:" +"`TypedDict` como potencialmente ausente." -#: ../../library/typing.rst:1223 +#: ../../library/typing.rst:1336 msgid "See :class:`TypedDict` and :pep:`655` for more details." -msgstr "" +msgstr "Veja :class:`TypedDict` e :pep:`655` para obter mais detalhes." -#: ../../library/typing.rst:1229 +#: ../../library/typing.rst:1342 msgid "" "A special typing construct to mark an item of a :class:`TypedDict` as read-" "only." msgstr "" +"Uma construção especial de tipagem para marcar um item de um :class:" +"`TypedDict` como somente leitura." -#: ../../library/typing.rst:1241 -msgid "There is no runtime checking for this property." +#: ../../library/typing.rst:1346 +msgid "" +"class Movie(TypedDict):\n" +" title: ReadOnly[str]\n" +" year: int\n" +"\n" +"def mutate_movie(m: Movie) -> None:\n" +" m[\"year\"] = 1999 # allowed\n" +" m[\"title\"] = \"The Matrix\" # typechecker error" msgstr "" +"class Movie(TypedDict):\n" +" title: ReadOnly[str]\n" +" year: int\n" +"\n" +"def mutate_movie(m: Movie) -> None:\n" +" m[\"year\"] = 1999 # permitido\n" +" m[\"title\"] = \"The Matrix\" # erro no verificador de tipos" + +#: ../../library/typing.rst:1354 +msgid "There is no runtime checking for this property." +msgstr "Não há verificação em tempo de execução para esta propriedade." -#: ../../library/typing.rst:1243 +#: ../../library/typing.rst:1356 msgid "See :class:`TypedDict` and :pep:`705` for more details." -msgstr "" +msgstr "Consulte :class:`TypedDict` e :pep:`705` para obter mais detalhes." -#: ../../library/typing.rst:1249 +#: ../../library/typing.rst:1362 msgid "Special typing form to add context-specific metadata to an annotation." msgstr "" +"Forma especial de tipagem para adicionar metadados específicos de contexto " +"para uma anotação." -#: ../../library/typing.rst:1251 +#: ../../library/typing.rst:1364 msgid "" "Add metadata ``x`` to a given type ``T`` by using the annotation " "``Annotated[T, x]``. Metadata added using ``Annotated`` can be used by " "static analysis tools or at runtime. At runtime, the metadata is stored in " "a :attr:`!__metadata__` attribute." msgstr "" +"Adiciona metadados ``x`` a um determinado tipo ``T`` usando a anotação " +"``Annotated[T, x]``. Os metadados adicionados usando ``Annotated`` podem ser " +"usados por ferramentas de análise estática ou em tempo de execução. Em tempo " +"de execução, os metadados são armazenados em um atributo :attr:`!" +"__metadata__`." -#: ../../library/typing.rst:1256 +#: ../../library/typing.rst:1369 msgid "" "If a library or tool encounters an annotation ``Annotated[T, x]`` and has no " "special logic for the metadata, it should ignore the metadata and simply " @@ -1371,8 +2863,13 @@ msgid "" "that wants to use annotations for purposes outside Python's static typing " "system." msgstr "" +"Se uma biblioteca ou ferramenta encontrar uma anotação ``Annotated[T, x]`` e " +"ela não tiver lógica especial para os metadados, ela deverá ignorar os " +"metadados e simplesmente tratar a anotação como ``T``. Dessa forma, " +"``Annotated`` pode ser útil em códigos que desejarem usar a anotação para " +"propósitos fora do sistema de tipagem estática do Python." -#: ../../library/typing.rst:1262 +#: ../../library/typing.rst:1375 msgid "" "Using ``Annotated[T, x]`` as an annotation still allows for static " "typechecking of ``T``, as type checkers will simply ignore the metadata " @@ -1381,116 +2878,302 @@ msgid "" "outside the scope of the typing system, but completely disables typechecking " "for a function or class." msgstr "" +"Usar ``Annotated[T, x]`` como um anotação ainda permite a verificação " +"estática do tipo de ``T``, pois os verificadores de tipo simplesmente " +"ignoram os metadados em ``x``. Dessa forma, o ``Annotated`` difere do " +"decorador :func:`@no_type_check `, que também pode ser usado " +"para adicionar anotações fora do escopo do sistema de tipagem, mas desativa " +"completamente a verificação de tipos para uma função ou classe." -#: ../../library/typing.rst:1269 +#: ../../library/typing.rst:1382 msgid "" "The responsibility of how to interpret the metadata lies with the tool or " "library encountering an ``Annotated`` annotation. A tool or library " "encountering an ``Annotated`` type can scan through the metadata elements to " "determine if they are of interest (e.g., using :func:`isinstance`)." msgstr "" +"A responsabilidade de como interpretar os metadados é da ferramenta ou da " +"biblioteca que encontrar uma anotação ``Annotated``. Uma ferramenta ou " +"biblioteca que encontrar um tipo ``Annotated`` poderá examinar os elementos " +"de metadados para determinar se eles são de interesse (por exemplo, usando :" +"func:`isinstance`)." -#: ../../library/typing.rst:1277 +#: ../../library/typing.rst:1390 msgid "" "Here is an example of how you might use ``Annotated`` to add metadata to " "type annotations if you were doing range analysis:" msgstr "" - -#: ../../library/typing.rst:1290 -msgid "Details of the syntax:" -msgstr "Detalhes da sintaxe:" - -#: ../../library/typing.rst:1292 -msgid "The first argument to ``Annotated`` must be a valid type" -msgstr "" - -#: ../../library/typing.rst:1294 -msgid "" -"Multiple metadata elements can be supplied (``Annotated`` supports variadic " -"arguments)::" -msgstr "" - -#: ../../library/typing.rst:1303 +"Aqui está um exemplo de como você pode usar ``Annotated`` para adicionar " +"metadados a anotações de tipos se estiver fazendo uma análise de intervalos:" + +#: ../../library/typing.rst:1393 +msgid "" +"@dataclass\n" +"class ValueRange:\n" +" lo: int\n" +" hi: int\n" +"\n" +"T1 = Annotated[int, ValueRange(-10, 5)]\n" +"T2 = Annotated[T1, ValueRange(-20, 3)]" +msgstr "" +"@dataclass\n" +"class ValueRange:\n" +" lo: int\n" +" hi: int\n" +"\n" +"T1 = Annotated[int, ValueRange(-10, 5)]\n" +"T2 = Annotated[T1, ValueRange(-20, 3)]" + +#: ../../library/typing.rst:1403 +msgid "" +"The first argument to ``Annotated`` must be a valid type. Multiple metadata " +"elements can be supplied as ``Annotated`` supports variadic arguments. The " +"order of the metadata elements is preserved and matters for equality checks::" +msgstr "" +"O primeiro argumento para ``Annotated`` deve ser um tipo válido. Vários " +"elementos de metadados podem ser fornecidos, pois ``Annotated`` suporta " +"argumentos variádicos. A ordem dos elementos de metadados é preservada e " +"importa para verificações de igualdade::" + +#: ../../library/typing.rst:1407 +msgid "" +"@dataclass\n" +"class ctype:\n" +" kind: str\n" +"\n" +"a1 = Annotated[int, ValueRange(3, 10), ctype(\"char\")]\n" +"a2 = Annotated[int, ctype(\"char\"), ValueRange(3, 10)]\n" +"\n" +"assert a1 != a2 # Order matters" +msgstr "" +"@dataclass\n" +"class ctype:\n" +" kind: str\n" +"\n" +"a1 = Annotated[int, ValueRange(3, 10), ctype(\"char\")]\n" +"a2 = Annotated[int, ctype(\"char\"), ValueRange(3, 10)]\n" +"\n" +"assert a1 != a2 # a ordem importa" + +#: ../../library/typing.rst:1416 msgid "" "It is up to the tool consuming the annotations to decide whether the client " "is allowed to add multiple metadata elements to one annotation and how to " "merge those annotations." msgstr "" +"Cabe à ferramenta que consome as anotações decidir se o cliente tem " +"permissão de adicionar vários elementos de metadados a uma anotação e como " +"mesclar essas anotações." -#: ../../library/typing.rst:1307 +#: ../../library/typing.rst:1420 msgid "" -"``Annotated`` must be subscripted with at least two arguments " -"( ``Annotated[int]`` is not valid)" +"Nested ``Annotated`` types are flattened. The order of the metadata elements " +"starts with the innermost annotation::" msgstr "" +"Os tipos ``Annotated`` aninhados são achatados. A ordem dos elementos de " +"metadados começa com a anotação mais interna::" -#: ../../library/typing.rst:1310 +#: ../../library/typing.rst:1423 msgid "" -"The order of the metadata elements is preserved and matters for equality " -"checks::" +"assert Annotated[Annotated[int, ValueRange(3, 10)], ctype(\"char\")] == " +"Annotated[\n" +" int, ValueRange(3, 10), ctype(\"char\")\n" +"]" msgstr "" +"assert Annotated[Annotated[int, ValueRange(3, 10)], ctype(\"char\")] == " +"Annotated[\n" +" int, ValueRange(3, 10), ctype(\"char\")\n" +"]" -#: ../../library/typing.rst:1317 +#: ../../library/typing.rst:1427 msgid "" -"Nested ``Annotated`` types are flattened. The order of the metadata elements " -"starts with the innermost annotation::" +"However, this does not apply to ``Annotated`` types referenced through a " +"type alias, to avoid forcing evaluation of the underlying :class:" +"`TypeAliasType`::" msgstr "" -#: ../../library/typing.rst:1324 +#: ../../library/typing.rst:1430 +msgid "" +"type From3To10[T] = Annotated[T, ValueRange(3, 10)]\n" +"assert Annotated[From3To10[int], ctype(\"char\")] != Annotated[\n" +" int, ValueRange(3, 10), ctype(\"char\")\n" +"]" +msgstr "" + +#: ../../library/typing.rst:1435 msgid "Duplicated metadata elements are not removed::" msgstr "Elementos duplicados de metadata não são removidos::" -#: ../../library/typing.rst:1330 -msgid "``Annotated`` can be used with nested and generic aliases:" +#: ../../library/typing.rst:1437 +msgid "" +"assert Annotated[int, ValueRange(3, 10)] != Annotated[\n" +" int, ValueRange(3, 10), ValueRange(3, 10)\n" +"]" msgstr "" +"assert Annotated[int, ValueRange(3, 10)] != Annotated[\n" +" int, ValueRange(3, 10), ValueRange(3, 10)\n" +"]" -#: ../../library/typing.rst:1344 -msgid "``Annotated`` cannot be used with an unpacked :class:`TypeVarTuple`::" +#: ../../library/typing.rst:1441 +msgid "``Annotated`` can be used with nested and generic aliases:" +msgstr "" +"``Annotated`` pode ser usado com apelidos aninhados e apelidos genéricos:" + +#: ../../library/typing.rst:1443 +msgid "" +"@dataclass\n" +"class MaxLen:\n" +" value: int\n" +"\n" +"type Vec[T] = Annotated[list[tuple[T, T]], MaxLen(10)]\n" +"\n" +"# When used in a type annotation, a type checker will treat \"V\" the same " +"as\n" +"# ``Annotated[list[tuple[int, int]], MaxLen(10)]``:\n" +"type V = Vec[int]" +msgstr "" +"@dataclass\n" +"class MaxLen:\n" +" value: int\n" +"\n" +"type Vec[T] = Annotated[list[tuple[T, T]], MaxLen(10)]\n" +"\n" +"# Quando usado em uma anotação de tipo, um verificador de tipos tratará " +"\"V\" da mesma forma que\n" +"# ``Annotated[list[tuple[int, int]], MaxLen(10)]``:\n" +"type V = Vec[int]" + +#: ../../library/typing.rst:1455 +msgid "``Annotated`` cannot be used with an unpacked :class:`TypeVarTuple`::" msgstr "" +"``Annotated`` não pode ser usado com um :class:`TypeVarTuple` desempacotado::" -#: ../../library/typing.rst:1348 -msgid "This would be equivalent to::" -msgstr "Isso deve ser equivalente a ::" +#: ../../library/typing.rst:1457 +msgid "" +"type Variadic[*Ts] = Annotated[*Ts, Ann1] = Annotated[T1, T2, T3, ..., " +"Ann1] # NOT valid" +msgstr "" +"type Variadic[*Ts] = Annotated[*Ts, Ann1] = Annotated[T1, T2, T3, ..., " +"Ann1] # NÃO válido" -#: ../../library/typing.rst:1352 +#: ../../library/typing.rst:1459 msgid "" -"where ``T1``, ``T2``, etc. are :class:`TypeVars `. This would be " -"invalid: only one type should be passed to Annotated." +"where ``T1``, ``T2``, ... are :class:`TypeVars `. This is invalid " +"as only one type should be passed to Annotated." msgstr "" +"onde ``T1``, ``T2``, ... são :class:`TypeVars `. Isso é inválido, " +"pois somente um tipo deve ser passado para Annotated." -#: ../../library/typing.rst:1355 +#: ../../library/typing.rst:1462 msgid "" "By default, :func:`get_type_hints` strips the metadata from annotations. " "Pass ``include_extras=True`` to have the metadata preserved:" msgstr "" +"Por padrão, :func:`get_type_hints` retira os metadados de anotações. Passe " +"``include_extras=True`` para preservar os metadados:" + +#: ../../library/typing.rst:1465 +msgid "" +">>> from typing import Annotated, get_type_hints\n" +">>> def func(x: Annotated[int, \"metadata\"]) -> None: pass\n" +"...\n" +">>> get_type_hints(func)\n" +"{'x': , 'return': }\n" +">>> get_type_hints(func, include_extras=True)\n" +"{'x': typing.Annotated[int, 'metadata'], 'return': }" +msgstr "" +">>> from typing import Annotated, get_type_hints\n" +">>> def func(x: Annotated[int, \"metadata\"]) -> None: pass\n" +"...\n" +">>> get_type_hints(func)\n" +"{'x': , 'return': }\n" +">>> get_type_hints(func, include_extras=True)\n" +"{'x': typing.Annotated[int, 'metadata'], 'return': }" -#: ../../library/typing.rst:1368 +#: ../../library/typing.rst:1475 msgid "" "At runtime, the metadata associated with an ``Annotated`` type can be " "retrieved via the :attr:`!__metadata__` attribute:" msgstr "" +"Em tempo de execução, os metadados associados a um tipo ``Annotated`` podem " +"ser recuperados por meio do atributo :attr:`!__metadata__`:" -#: ../../library/typing.rst:1382 -msgid ":pep:`593` - Flexible function and variable annotations" +#: ../../library/typing.rst:1478 +msgid "" +">>> from typing import Annotated\n" +">>> X = Annotated[int, \"very\", \"important\", \"metadata\"]\n" +">>> X\n" +"typing.Annotated[int, 'very', 'important', 'metadata']\n" +">>> X.__metadata__\n" +"('very', 'important', 'metadata')" msgstr "" +">>> from typing import Annotated\n" +">>> X = Annotated[int, \"very\", \"important\", \"metadata\"]\n" +">>> X\n" +"typing.Annotated[int, 'very', 'important', 'metadata']\n" +">>> X.__metadata__\n" +"('very', 'important', 'metadata')" -#: ../../library/typing.rst:1383 -msgid "The PEP introducing ``Annotated`` to the standard library." +#: ../../library/typing.rst:1487 +msgid "" +"If you want to retrieve the original type wrapped by ``Annotated``, use the :" +"attr:`!__origin__` attribute:" +msgstr "" +"Se você quiser recuperar o tipo original envolvido por ``Annotated``, use o " +"atributo :attr:`!__origin__`:" + +#: ../../library/typing.rst:1490 +msgid "" +">>> from typing import Annotated, get_origin\n" +">>> Password = Annotated[str, \"secret\"]\n" +">>> Password.__origin__\n" +"" +msgstr "" +">>> from typing import Annotated, get_origin\n" +">>> Password = Annotated[str, \"secret\"]\n" +">>> Password.__origin__\n" +"" + +#: ../../library/typing.rst:1497 +msgid "Note that using :func:`get_origin` will return ``Annotated`` itself:" +msgstr "Note que usar :func:`get_origin` retornará o próprio ``Annotated``:" + +#: ../../library/typing.rst:1499 +msgid "" +">>> get_origin(Password)\n" +"typing.Annotated" msgstr "" +">>> get_origin(Password)\n" +"typing.Annotated" + +#: ../../library/typing.rst:1506 +msgid ":pep:`593` - Flexible function and variable annotations" +msgstr ":pep:`593` - Anotações flexíveis para funções e variáveis" -#: ../../library/typing.rst:1390 ../../library/typing.rst:1474 +#: ../../library/typing.rst:1507 +msgid "The PEP introducing ``Annotated`` to the standard library." +msgstr "A PEP que introduz ``Annotated`` à biblioteca padrão." + +#: ../../library/typing.rst:1514 ../../library/typing.rst:1598 msgid "" "Special typing construct for marking user-defined type predicate functions." msgstr "" +"Uma construção especial de tipagem para marcar funções de predicado de tipo " +"definidas pelo usuário." -#: ../../library/typing.rst:1392 +#: ../../library/typing.rst:1516 msgid "" "``TypeIs`` can be used to annotate the return type of a user-defined type " "predicate function. ``TypeIs`` only accepts a single type argument. At " "runtime, functions marked this way should return a boolean and take at least " "one positional argument." msgstr "" +"``TypeIs`` pode ser usado para anotar o tipo de retorno de uma função de " +"predicado de tipo definida pelo usuário. ``TypeIs`` aceita apenas um único " +"argumento de tipo. Em tempo de execução, funções marcadas dessa forma devem " +"retornar um booleano e receber, no mínimo, um argumento posicional." -#: ../../library/typing.rst:1397 +#: ../../library/typing.rst:1521 msgid "" "``TypeIs`` aims to benefit *type narrowing* -- a technique used by static " "type checkers to determine a more precise type of an expression within a " @@ -1499,8 +3182,34 @@ msgid "" "conditional expression here is sometimes referred to as a \"type " "predicate\"::" msgstr "" - -#: ../../library/typing.rst:1412 +"``TypeIs`` visa beneficiar *estreitamento de tipo* -- uma técnica usada por " +"verificador de tipo estático para determinar um tipo mais preciso de " +"expressão dentro do fluxo de código de um programa. Normalmente, o " +"estreitamento de tipo é feito por meio da análise do fluxo de código " +"condicional e da aplicação do estreitamento a um bloquear código. A " +"condicional expressão aqui é às vezes chamada de \"predicado de tipo\"::" + +#: ../../library/typing.rst:1527 +msgid "" +"def is_str(val: str | float):\n" +" # \"isinstance\" type predicate\n" +" if isinstance(val, str):\n" +" # Type of ``val`` is narrowed to ``str``\n" +" ...\n" +" else:\n" +" # Else, type of ``val`` is narrowed to ``float``.\n" +" ..." +msgstr "" +"def is_str(val: str | float):\n" +" # predicado de tipos \"isinstance\"\n" +" if isinstance(val, str):\n" +" # Tipo de ``val`` é restrito a ``str``\n" +" ...\n" +" else:\n" +" # Senão, tipo de ``val`` é restrito a ``float``.\n" +" ..." + +#: ../../library/typing.rst:1536 msgid "" "Sometimes it would be convenient to use a user-defined boolean function as a " "type predicate. Such a function should use ``TypeIs[...]`` or :data:" @@ -1510,30 +3219,88 @@ msgid "" "incompatible (e.g., ``list[object]`` to ``list[int]``) or when the function " "does not return ``True`` for all instances of the narrowed type." msgstr "" +"Às vezes, seria conveniente usar uma função booleana definida pelo usuário " +"como um predicado de tipo. Essa função deveria usar ``TypeIs[...]`` ou :data:" +"`TypeGuard` como seu tipo de retorno para alertar o verificador de tipo " +"estático sobre essa intenção. ``TypeIs`` geralmente tem um comportamento " +"mais intuitivo do que ``TypeGuard``, mas não pode ser usado quando os tipos " +"de entrada e saída são incompatíveis (por exemplo, de ``list[object]`` para " +"``list[int]``) ou quando a função não retorna ``True`` para todas as " +"instâncias do tipo restrito." -#: ../../library/typing.rst:1420 +#: ../../library/typing.rst:1544 msgid "" "Using ``-> TypeIs[NarrowedType]`` tells the static type checker that for a " "given function:" msgstr "" +"Usar ``-> TypeIs[NarrowedType]`` informa ao verificador de tipo estático " +"que, para uma determinada função:" -#: ../../library/typing.rst:1423 ../../library/typing.rst:1484 +#: ../../library/typing.rst:1547 ../../library/typing.rst:1608 msgid "The return value is a boolean." msgstr "O valor de retorno é um booleano." -#: ../../library/typing.rst:1424 +#: ../../library/typing.rst:1548 msgid "" "If the return value is ``True``, the type of its argument is the " "intersection of the argument's original type and ``NarrowedType``." msgstr "" +"Se o valor de retorno for ``True``, o tipo de seu argumento será a " +"interseção entre o tipo original do argumento e o ``NarrowedType``." -#: ../../library/typing.rst:1426 +#: ../../library/typing.rst:1550 msgid "" "If the return value is ``False``, the type of its argument is narrowed to " "exclude ``NarrowedType``." msgstr "" - -#: ../../library/typing.rst:1452 +"Se o valor de retorno for ``False``, o tipo de seu argumento será restrito " +"para excluir ``NarrowedType``." + +#: ../../library/typing.rst:1555 +msgid "" +"from typing import assert_type, final, TypeIs\n" +"\n" +"class Parent: pass\n" +"class Child(Parent): pass\n" +"@final\n" +"class Unrelated: pass\n" +"\n" +"def is_parent(val: object) -> TypeIs[Parent]:\n" +" return isinstance(val, Parent)\n" +"\n" +"def run(arg: Child | Unrelated):\n" +" if is_parent(arg):\n" +" # Type of ``arg`` is narrowed to the intersection\n" +" # of ``Parent`` and ``Child``, which is equivalent to\n" +" # ``Child``.\n" +" assert_type(arg, Child)\n" +" else:\n" +" # Type of ``arg`` is narrowed to exclude ``Parent``,\n" +" # so only ``Unrelated`` is left.\n" +" assert_type(arg, Unrelated)" +msgstr "" +"from typing import assert_type, final, TypeIs\n" +"\n" +"class Parent: pass\n" +"class Child(Parent): pass\n" +"@final\n" +"class Unrelated: pass\n" +"\n" +"def is_parent(val: object) -> TypeIs[Parent]:\n" +" return isinstance(val, Parent)\n" +"\n" +"def run(arg: Child | Unrelated):\n" +" if is_parent(arg):\n" +" # Tipo de ``arg`` é restrito à interseção\n" +" # de ``Parent`` e ``Child``, o que equivale a\n" +" # ``Child``.\n" +" assert_type(arg, Child)\n" +" else:\n" +" # Tipo de ``arg`` é restrito para excluir ``Parent``,\n" +" # então sobrou o tipo ``Unrelated``.\n" +" assert_type(arg, Unrelated)" + +#: ../../library/typing.rst:1576 msgid "" "The type inside ``TypeIs`` must be consistent with the type of the " "function's argument; if it is not, static type checkers will raise an " @@ -1541,66 +3308,119 @@ msgid "" "behavior in the type system; it is the user's responsibility to write such " "functions in a type-safe manner." msgstr "" +"O tipo dentro de ``TypeIs`` deve ser consistente com o tipo do argumento da " +"função; caso contrário, o verificador de tipo estático levantará um erro. " +"Uma função ``TypeIs`` escrita incorretamente pode ocasionar um comportamento " +"insensato pelo sistema de tipos; é de responsabilidade do usuário escrever " +"tais funções de forma segura para tipos." -#: ../../library/typing.rst:1458 +#: ../../library/typing.rst:1582 msgid "" "If a ``TypeIs`` function is a class or instance method, then the type in " "``TypeIs`` maps to the type of the second parameter (after ``cls`` or " "``self``)." msgstr "" +"Se uma função ``TypeIs`` for um método de classe ou instância, então o tipo " +"em ``TypeIs`` mapeia para o tipo do segundo parâmetro (depois de ``cls`` ou " +"``self``)." -#: ../../library/typing.rst:1462 +#: ../../library/typing.rst:1586 msgid "" "In short, the form ``def foo(arg: TypeA) -> TypeIs[TypeB]: ...``, means that " "if ``foo(arg)`` returns ``True``, then ``arg`` is an instance of ``TypeB``, " "and if it returns ``False``, it is not an instance of ``TypeB``." msgstr "" +"Em resumo, a forma ``def foo(arg: TypeA) -> TypeIs[TypeB]: ...``, significa " +"que se ``foo(arg)`` retorna ``True``, então ``arg`` é um instância de " +"``TypeB``, e se retorna ``False``, não é um instância de ``TypeB``." -#: ../../library/typing.rst:1466 +#: ../../library/typing.rst:1590 msgid "" "``TypeIs`` also works with type variables. For more information, see :pep:" "`742` (Narrowing types with ``TypeIs``)." msgstr "" +"``TypeIs`` também funciona com variáveis de tipo. Para mais informações, " +"consulte a :pep:`742` (Restringindo tipos com ``TypeIs``)." -#: ../../library/typing.rst:1476 +#: ../../library/typing.rst:1600 msgid "" "Type predicate functions are user-defined functions that return whether " "their argument is an instance of a particular type. ``TypeGuard`` works " "similarly to :data:`TypeIs`, but has subtly different effects on type " "checking behavior (see below)." msgstr "" +"Funções de predicados de tipo são funções definidas pelo usuário que " +"retornam se seu argumento é uma instância de um tipo específico. O " +"``TypeGuard`` funciona como :data:`TypeIs`, mas tem efeitos sutilmente " +"diferentes sobre o comportamento da verificação de tipos (veja abaixo)." -#: ../../library/typing.rst:1481 +#: ../../library/typing.rst:1605 msgid "" "Using ``-> TypeGuard`` tells the static type checker that for a given " "function:" msgstr "" +"Usar ``-> TypeGuard`` informa ao verificador de tipo estático que, para uma " +"determinada função:" -#: ../../library/typing.rst:1485 +#: ../../library/typing.rst:1609 msgid "" "If the return value is ``True``, the type of its argument is the type inside " "``TypeGuard``." msgstr "" +"Se o valor de retorno for ``True``, o tipo de seu argumento é o tipo dentro " +"de ``TypeGuard``." -#: ../../library/typing.rst:1488 +#: ../../library/typing.rst:1612 msgid "" "``TypeGuard`` also works with type variables. See :pep:`647` for more " "details." msgstr "" - -#: ../../library/typing.rst:1504 +"``TypeGuard`` também funciona com tipos variáveis. Consulte a :pep:`647` " +"para obter mais detalhes." + +#: ../../library/typing.rst:1616 +msgid "" +"def is_str_list(val: list[object]) -> TypeGuard[list[str]]:\n" +" '''Determines whether all objects in the list are strings'''\n" +" return all(isinstance(x, str) for x in val)\n" +"\n" +"def func1(val: list[object]):\n" +" if is_str_list(val):\n" +" # Type of ``val`` is narrowed to ``list[str]``.\n" +" print(\" \".join(val))\n" +" else:\n" +" # Type of ``val`` remains as ``list[object]``.\n" +" print(\"Not a list of strings!\")" +msgstr "" +"def is_str_list(val: list[object]) -> TypeGuard[list[str]]:\n" +" '''Determina se todos os objetos na lista são strings'''\n" +" return all(isinstance(x, str) for x in val)\n" +"\n" +"def func1(val: list[object]):\n" +" if is_str_list(val):\n" +" # Tipo de ``val`` é restrito a ``list[str]``.\n" +" print(\" \".join(val))\n" +" else:\n" +" # Tipo de ``val`` continua sendo ``list[object]``.\n" +" print(\"Not a list of strings!\")" + +#: ../../library/typing.rst:1628 msgid "``TypeIs`` and ``TypeGuard`` differ in the following ways:" -msgstr "" +msgstr "``TypeIs`` e ``TypeGuard`` diferem das seguintes maneiras:" -#: ../../library/typing.rst:1506 +#: ../../library/typing.rst:1630 msgid "" "``TypeIs`` requires the narrowed type to be a subtype of the input type, " "while ``TypeGuard`` does not. The main reason is to allow for things like " "narrowing ``list[object]`` to ``list[str]`` even though the latter is not a " "subtype of the former, since ``list`` is invariant." msgstr "" +"``TypeIs`` exige que o tipo restrito seja um subtipo do tipo de entrada, " +"enquanto o ``TypeGuard``, não. O motivo principal é permitir coisas como " +"restringir ``list[object]`` a ``list[str]``, embora este não seja um subtipo " +"daquele, já que ``list`` é invariante." -#: ../../library/typing.rst:1510 +#: ../../library/typing.rst:1634 msgid "" "When a ``TypeGuard`` function returns ``True``, type checkers narrow the " "type of the variable to exactly the ``TypeGuard`` type. When a ``TypeIs`` " @@ -1608,85 +3428,200 @@ msgid "" "combining the previously known type of the variable with the ``TypeIs`` " "type. (Technically, this is known as an intersection type.)" msgstr "" +"Quando uma função ``TypeGuard`` retorna ``True``, os verificadores de tipo " +"restringem o tipo da variável exatamente ao tipo ``TypeGuard``. Quando uma " +"função ``TypeIs`` retorna ``True``, os verificadores de tipo podem inferir " +"um tipo mais preciso combinando o tipo previamente conhecido da variável com " +"o tipo ``TypeIs``. (Tecnicamente, isso é conhecido como um tipo de " +"interseção)." -#: ../../library/typing.rst:1514 +#: ../../library/typing.rst:1638 msgid "" "When a ``TypeGuard`` function returns ``False``, type checkers cannot narrow " "the type of the variable at all. When a ``TypeIs`` function returns " "``False``, type checkers can narrow the type of the variable to exclude the " "``TypeIs`` type." msgstr "" +"Quando uma função ``TypeGuard`` retorna ``False``, os verificadores de tipo " +"não podem restringir o tipo da variável. Quando uma função ``TypeIs`` " +"retorna ``False``, os verificadores de tipo podem restringir o tipo da " +"variável para excluir o tipo ``TypeIs``." -#: ../../library/typing.rst:1523 +#: ../../library/typing.rst:1647 msgid "Typing operator to conceptually mark an object as having been unpacked." msgstr "" +"Operador de tipagem para marcar conceitualmente um objeto como tendo sido " +"desempacotado." -#: ../../library/typing.rst:1525 +#: ../../library/typing.rst:1649 msgid "" "For example, using the unpack operator ``*`` on a :ref:`type variable tuple " "` is equivalent to using ``Unpack`` to mark the type variable " "tuple as having been unpacked::" msgstr "" +"Por exemplo, usar o operador de desempacotamento ``*`` em uma :ref:`tupla de " +"tipos variáveis ` equivale a usar o ``Unpack`` para marcar a " +"tupla de tipos variáveis como tendo sido desempacotada::" -#: ../../library/typing.rst:1534 +#: ../../library/typing.rst:1653 +msgid "" +"Ts = TypeVarTuple('Ts')\n" +"tup: tuple[*Ts]\n" +"# Effectively does:\n" +"tup: tuple[Unpack[Ts]]" +msgstr "" +"Ts = TypeVarTuple('Ts')\n" +"tup: tuple[*Ts]\n" +"# Efetivamente faz:\n" +"tup: tuple[Unpack[Ts]]" + +#: ../../library/typing.rst:1658 msgid "" "In fact, ``Unpack`` can be used interchangeably with ``*`` in the context " "of :class:`typing.TypeVarTuple ` and :class:`builtins.tuple " "` types. You might see ``Unpack`` being used explicitly in older " "versions of Python, where ``*`` couldn't be used in certain places::" msgstr "" - -#: ../../library/typing.rst:1548 +"Na verdade, ``Unpack`` pode ser usado de forma intercambiável com ``*`` no " +"contexto dos tipos :class:`typing.TypeVarTuple ` e :class:" +"`builtins.tuple `. Você pode ver ``Unpack`` sendo usado " +"explicitamente em versões mais antigas do Python, onde ``*`` não podia ser " +"usado em certos lugares::" + +#: ../../library/typing.rst:1664 +msgid "" +"# In older versions of Python, TypeVarTuple and Unpack\n" +"# are located in the `typing_extensions` backports package.\n" +"from typing_extensions import TypeVarTuple, Unpack\n" +"\n" +"Ts = TypeVarTuple('Ts')\n" +"tup: tuple[*Ts] # Syntax error on Python <= 3.10!\n" +"tup: tuple[Unpack[Ts]] # Semantically equivalent, and backwards-compatible" +msgstr "" +"# Em versões mais antigas do Python, TypeVarTuple e Unpack\n" +"# estão localizados no pacote de backports `typing_extensions`.\n" +"from typing_extensions import TypeVarTuple, Unpack\n" +"\n" +"Ts = TypeVarTuple('Ts')\n" +"tup: tuple[*Ts] # Erro de sintaxe no Python <= 3.10!\n" +"tup: tuple[Unpack[Ts]] # Semanticamente equivalente e compatível com " +"versões anteriores" + +#: ../../library/typing.rst:1672 msgid "" "``Unpack`` can also be used along with :class:`typing.TypedDict` for typing " "``**kwargs`` in a function signature::" msgstr "" - -#: ../../library/typing.rst:1561 +"``Unpack`` também pode ser usado com :class:`typing.TypedDict` para a " +"tipagem de ``**kwargs`` em uma assinatura de função::" + +#: ../../library/typing.rst:1675 +msgid "" +"from typing import TypedDict, Unpack\n" +"\n" +"class Movie(TypedDict):\n" +" name: str\n" +" year: int\n" +"\n" +"# This function expects two keyword arguments - `name` of type `str`\n" +"# and `year` of type `int`.\n" +"def foo(**kwargs: Unpack[Movie]): ..." +msgstr "" +"from typing import TypedDict, Unpack\n" +"\n" +"class Movie(TypedDict):\n" +" name: str\n" +" year: int\n" +"\n" +"# Esta função espera dois argumentos nomeados: `name` de tipo `str`\n" +"# e `year` de tipo `int`.\n" +"def foo(**kwargs: Unpack[Movie]): ..." + +#: ../../library/typing.rst:1685 msgid "" "See :pep:`692` for more details on using ``Unpack`` for ``**kwargs`` typing." msgstr "" +"Consulte :pep:`692` para obter mais detalhes sobre como usar ``Unpack`` para " +"tipagem de ``**kwargs``." -#: ../../library/typing.rst:1566 +#: ../../library/typing.rst:1690 msgid "Building generic types and type aliases" msgstr "Criando tipos genéricos e apelidos de tipo" -#: ../../library/typing.rst:1568 +#: ../../library/typing.rst:1692 msgid "" "The following classes should not be used directly as annotations. Their " "intended purpose is to be building blocks for creating generic types and " "type aliases." msgstr "" +"As classes a seguir não devem ser usadas diretamente como anotações. " +"propósito O objetivo delas é construir bloquear para criar genérico e " +"digitar apelido." -#: ../../library/typing.rst:1572 +#: ../../library/typing.rst:1696 msgid "" "These objects can be created through special syntax (:ref:`type parameter " "lists ` and the :keyword:`type` statement). For compatibility " "with Python 3.11 and earlier, they can also be created without the dedicated " "syntax, as documented below." msgstr "" +"Esses objetos podem ser criados por meio de sintaxe especial (:ref:`listas " +"de parâmetros de tipo ` e a instrução :keyword:`type`). Para " +"compatibilidade com Python 3.11 e versões anteriores, eles também podem ser " +"criados sem a sintaxe dedicada, como documentado abaixo." -#: ../../library/typing.rst:1579 +#: ../../library/typing.rst:1703 msgid "Abstract base class for generic types." msgstr "Classe base abstrata para tipos genéricos" -#: ../../library/typing.rst:1581 +#: ../../library/typing.rst:1705 msgid "" "A generic type is typically declared by adding a list of type parameters " "after the class name::" msgstr "" +"Normalmente, um tipo genérico é declarado adicionando-se uma lista de " +"parâmetros de tipo após o nome da classe::" + +#: ../../library/typing.rst:1708 +msgid "" +"class Mapping[KT, VT]:\n" +" def __getitem__(self, key: KT) -> VT:\n" +" ...\n" +" # Etc." +msgstr "" +"class Mapping[KT, VT]:\n" +" def __getitem__(self, key: KT) -> VT:\n" +" ...\n" +" # Etc." -#: ../../library/typing.rst:1589 +#: ../../library/typing.rst:1713 msgid "" "Such a class implicitly inherits from ``Generic``. The runtime semantics of " "this syntax are discussed in the :ref:`Language Reference `." msgstr "" +"Essa classe herda implicitamente de ``Generic``. A semântica em tempo de " +"execução dessa sintaxe é discutida na :ref:`Referência da Linguagem `." -#: ../../library/typing.rst:1593 +#: ../../library/typing.rst:1717 msgid "This class can then be used as follows::" msgstr "Esta classe pode ser utilizada como segue::" -#: ../../library/typing.rst:1601 +#: ../../library/typing.rst:1719 +msgid "" +"def lookup_name[X, Y](mapping: Mapping[X, Y], key: X, default: Y) -> Y:\n" +" try:\n" +" return mapping[key]\n" +" except KeyError:\n" +" return default" +msgstr "" +"def lookup_name[X, Y](mapping: Mapping[X, Y], key: X, default: Y) -> Y:\n" +" try:\n" +" return mapping[key]\n" +" except KeyError:\n" +" return default" + +#: ../../library/typing.rst:1725 msgid "" "Here the brackets after the function name indicate a :ref:`generic function " "`." @@ -1694,50 +3629,157 @@ msgstr "" "Aqui os colchetes depois no nome da função indica uma :ref:`função genérica " "`." -#: ../../library/typing.rst:1604 +#: ../../library/typing.rst:1728 msgid "" "For backwards compatibility, generic classes can also be declared by " "explicitly inheriting from ``Generic``. In this case, the type parameters " "must be declared separately::" msgstr "" +"Para manter retrocompatibilidade, as classes genéricas também podem ser " +"declaradas herdando explicitamente de ``Generic``. Nesse caso, os parâmetros " +"de tipo devem ser declarados separadamente::" -#: ../../library/typing.rst:1621 +#: ../../library/typing.rst:1733 +msgid "" +"KT = TypeVar('KT')\n" +"VT = TypeVar('VT')\n" +"\n" +"class Mapping(Generic[KT, VT]):\n" +" def __getitem__(self, key: KT) -> VT:\n" +" ...\n" +" # Etc." +msgstr "" +"KT = TypeVar('KT')\n" +"VT = TypeVar('VT')\n" +"\n" +"class Mapping(Generic[KT, VT]):\n" +" def __getitem__(self, key: KT) -> VT:\n" +" ...\n" +" # Etc." + +#: ../../library/typing.rst:1745 msgid "Type variable." msgstr "Tipo variável." -#: ../../library/typing.rst:1623 +#: ../../library/typing.rst:1747 msgid "" "The preferred way to construct a type variable is via the dedicated syntax " "for :ref:`generic functions `, :ref:`generic classes " "`, and :ref:`generic type aliases `::" msgstr "" +"A maneira preferida de construir um tipo variável é por meio da sintaxe " +"dedicada para :ref:`funções genéricas `, :ref:`classes " +"genéricas ` e :ref:`apelidos de tipo genérico `::" -#: ../../library/typing.rst:1631 +#: ../../library/typing.rst:1752 msgid "" -"This syntax can also be used to create bound and constrained type variables::" +"class Sequence[T]: # T is a TypeVar\n" +" ..." msgstr "" +"class Sequence[T]: # T é um TypeVar\n" +" ..." -#: ../../library/typing.rst:1641 +#: ../../library/typing.rst:1755 +msgid "" +"This syntax can also be used to create bounded and constrained type " +"variables::" +msgstr "" +"Essa sintaxe também pode ser usada para criar tipos variáveis delimitados e " +"tipos variáveis restritos::" + +#: ../../library/typing.rst:1758 +msgid "" +"class StrSequence[S: str]: # S is a TypeVar with a `str` upper bound;\n" +" ... # we can say that S is \"bounded by `str`\"\n" +"\n" +"\n" +"class StrOrBytesSequence[A: (str, bytes)]: # A is a TypeVar constrained to " +"str or bytes\n" +" ..." +msgstr "" +"class StrSequence[S: str]: # S é a TypeVar com como limite superior em " +"`str`;\n" +" ... # podemos dizer que S é \"delimitada por " +"`str`\"\n" +"\n" +"\n" +"class StrOrBytesSequence[A: (str, bytes)]: # A é uma TypeVar restrita a str " +"ou bytes\n" +" ..." + +#: ../../library/typing.rst:1765 msgid "" "However, if desired, reusable type variables can also be constructed " "manually, like so::" msgstr "" +"No entanto, se desejado, tipos variáveis reutilizáveis também podem ser " +"construídas manualmente, como:" -#: ../../library/typing.rst:1647 +#: ../../library/typing.rst:1767 +msgid "" +"T = TypeVar('T') # Can be anything\n" +"S = TypeVar('S', bound=str) # Can be any subtype of str\n" +"A = TypeVar('A', str, bytes) # Must be exactly str or bytes" +msgstr "" +"T = TypeVar('T') # Pode ser qualquer coisa\n" +"S = TypeVar('S', bound=str) # Pode ser qualquer subtipo de str\n" +"A = TypeVar('A', str, bytes) # Deve ser exatamente str ou bytes" + +#: ../../library/typing.rst:1771 msgid "" "Type variables exist primarily for the benefit of static type checkers. " "They serve as the parameters for generic types as well as for generic " "function and type alias definitions. See :class:`Generic` for more " "information on generic types. Generic functions work as follows::" msgstr "" - -#: ../../library/typing.rst:1668 -msgid "" -"Note that type variables can be *bound*, *constrained*, or neither, but " -"cannot be both bound *and* constrained." -msgstr "" - -#: ../../library/typing.rst:1671 +"Tipos variáveis existem principalmente para o benefício de verificadores de " +"tipo estático. Eles servem como parâmetros para tipos genéricos, bem como " +"para definições de função genérica e apelidos de tipo. Consulte :class:" +"`Generic` para obter mais informações sobre genérico. Funções genéricas " +"funcionam da seguinte forma::" + +#: ../../library/typing.rst:1777 +msgid "" +"def repeat[T](x: T, n: int) -> Sequence[T]:\n" +" \"\"\"Return a list containing n references to x.\"\"\"\n" +" return [x]*n\n" +"\n" +"\n" +"def print_capitalized[S: str](x: S) -> S:\n" +" \"\"\"Print x capitalized, and return x.\"\"\"\n" +" print(x.capitalize())\n" +" return x\n" +"\n" +"\n" +"def concatenate[A: (str, bytes)](x: A, y: A) -> A:\n" +" \"\"\"Add two strings or bytes objects together.\"\"\"\n" +" return x + y" +msgstr "" +"def repeat[T](x: T, n: int) -> Sequence[T]:\n" +" \"\"\"Retorna uma lista contendo n referências para x.\"\"\"\n" +" return [x]*n\n" +"\n" +"\n" +"def print_capitalized[S: str](x: S) -> S:\n" +" \"\"\"Exibe x capitalizado, e retorna x.\"\"\"\n" +" print(x.capitalize())\n" +" return x\n" +"\n" +"\n" +"def concatenate[A: (str, bytes)](x: A, y: A) -> A:\n" +" \"\"\"Concatena dois objetos string ou bytes.\"\"\"\n" +" return x + y" + +#: ../../library/typing.rst:1792 +msgid "" +"Note that type variables can be *bounded*, *constrained*, or neither, but " +"cannot be both bounded *and* constrained." +msgstr "" +"Observe que tipos variáveis podem ser *delimitados*, *restritos*, nenhum dos " +"dois, mas não podem ser *ambos*." + +#: ../../library/typing.rst:1795 msgid "" "The variance of type variables is inferred by type checkers when they are " "created through the :ref:`type parameter syntax ` or when " @@ -1746,120 +3788,286 @@ msgid "" "or ``contravariant=True``. By default, manually created type variables are " "invariant. See :pep:`484` and :pep:`695` for more details." msgstr "" - -#: ../../library/typing.rst:1679 -msgid "" -"Bound type variables and constrained type variables have different semantics " -"in several important ways. Using a *bound* type variable means that the " -"``TypeVar`` will be solved using the most specific type possible::" -msgstr "" - -#: ../../library/typing.rst:1694 -msgid "" -"Type variables can be bound to concrete types, abstract types (ABCs or " -"protocols), and even unions of types::" -msgstr "" - -#: ../../library/typing.rst:1706 +"A variância de tipos variáveis é inferida pelos verificadores de tipo quando " +"eles são criados por meio do :ref:`sintaxe de parâmetro de tipo ` ou quando ``infer_variance=True`` é passado. Os tipos variáveis " +"criados manualmente podem ser explicitamente marcados como covariante ou " +"contravariantes ao passar ``covariant=True`` ou ``contravariant=True``. Por " +"padrão, os tipos variáveis criados manualmente são invariante. Consulte :pep:" +"`484` e :pep:`695` para obter mais detalhes." + +#: ../../library/typing.rst:1803 +msgid "" +"Bounded type variables and constrained type variables have different " +"semantics in several important ways. Using a *bounded* type variable means " +"that the ``TypeVar`` will be solved using the most specific type possible::" +msgstr "" +"Tipos variáveis delimitados e tipos variáveis restritos têm semânticas " +"diferentes de várias formas importantes. Usar um tipo variável *delimitado* " +"significa que a ``TypeVar`` será resolvido usando o tipo mais específico " +"possível::" + +#: ../../library/typing.rst:1807 +msgid "" +"x = print_capitalized('a string')\n" +"reveal_type(x) # revealed type is str\n" +"\n" +"class StringSubclass(str):\n" +" pass\n" +"\n" +"y = print_capitalized(StringSubclass('another string'))\n" +"reveal_type(y) # revealed type is StringSubclass\n" +"\n" +"z = print_capitalized(45) # error: int is not a subtype of str" +msgstr "" +"x = print_capitalized('a string')\n" +"reveal_type(x) # tipo revelado é str\n" +"\n" +"class StringSubclass(str):\n" +" pass\n" +"\n" +"y = print_capitalized(StringSubclass('another string'))\n" +"reveal_type(y) # tipo revelado é StringSubclass\n" +"\n" +"z = print_capitalized(45) # erro: int não é subtipo de str" + +#: ../../library/typing.rst:1818 +msgid "" +"The upper bound of a type variable can be a concrete type, abstract type " +"(ABC or Protocol), or even a union of types::" +msgstr "" +"O limite superior de um tipo variável pode ser um tipo concreto, um tipo " +"abstrato (classe base abstrata ou protocolo) ou até mesmo uma união de " +"tipos::" + +#: ../../library/typing.rst:1821 +msgid "" +"# Can be anything with an __abs__ method\n" +"def print_abs[T: SupportsAbs](arg: T) -> None:\n" +" print(\"Absolute value:\", abs(arg))\n" +"\n" +"U = TypeVar('U', bound=str|bytes) # Can be any subtype of the union str|" +"bytes\n" +"V = TypeVar('V', bound=SupportsAbs) # Can be anything with an __abs__ method" +msgstr "" +"# Pode ser qualquer coisa com um método __abs__\n" +"def print_abs[T: SupportsAbs](arg: T) -> None:\n" +" print(\"Absolute value:\", abs(arg))\n" +"\n" +"U = TypeVar('U', bound=str|bytes) # Pode ser qualquer subtipo com a união " +"str | bytes\n" +"V = TypeVar('V', bound=SupportsAbs) # Pode ser qualquer coisa com um método " +"__abs__" + +#: ../../library/typing.rst:1830 msgid "" "Using a *constrained* type variable, however, means that the ``TypeVar`` can " "only ever be solved as being exactly one of the constraints given::" msgstr "" +"Porém, usar um tipo variável *restrito* significa que a ``TypeVar`` só " +"poderá ser resolvida como sendo exatamente uma das restrições dadas::" + +#: ../../library/typing.rst:1833 +msgid "" +"a = concatenate('one', 'two')\n" +"reveal_type(a) # revealed type is str\n" +"\n" +"b = concatenate(StringSubclass('one'), StringSubclass('two'))\n" +"reveal_type(b) # revealed type is str, despite StringSubclass being passed " +"in\n" +"\n" +"c = concatenate('one', b'two') # error: type variable 'A' can be either str " +"or bytes in a function call, but not both" +msgstr "" +"a = concatenate('one', 'two')\n" +"reveal_type(a) # o tipo revelado é str\n" +"\n" +"b = concatenate(StringSubclass('one'), StringSubclass('two'))\n" +"reveal_type(b) # o tipo revelado é str, apesar de StringSubclass ter sido " +"passado\n" +"\n" +"c = concatenate('one', b'two') # erro: tipo variável 'A' pode ser str ou " +"bytes em uma chamada de função, mas não ambos" -#: ../../library/typing.rst:1717 +#: ../../library/typing.rst:1841 msgid "At runtime, ``isinstance(x, T)`` will raise :exc:`TypeError`." -msgstr "" +msgstr "Em tempo de execução, ``isinstance(x, T)`` levantará :exc:`TypeError`." -#: ../../library/typing.rst:1721 +#: ../../library/typing.rst:1845 msgid "The name of the type variable." -msgstr "" +msgstr "O nome do tipo variável." -#: ../../library/typing.rst:1725 +#: ../../library/typing.rst:1849 msgid "Whether the type var has been explicitly marked as covariant." -msgstr "" +msgstr "Se o tipo variável foi explicitamente marcado como covariante." -#: ../../library/typing.rst:1729 +#: ../../library/typing.rst:1853 msgid "Whether the type var has been explicitly marked as contravariant." -msgstr "" +msgstr "Se o tipo variável foi explicitamente marcado como contravariante." -#: ../../library/typing.rst:1733 +#: ../../library/typing.rst:1857 msgid "" "Whether the type variable's variance should be inferred by type checkers." msgstr "" +"Se a variância de tipo variável deve ser inferida por verificadores de tipo." -#: ../../library/typing.rst:1739 -msgid "The bound of the type variable, if any." -msgstr "" +#: ../../library/typing.rst:1863 +msgid "The upper bound of the type variable, if any." +msgstr "A limite superior do tipo variável, se houver." -#: ../../library/typing.rst:1743 +#: ../../library/typing.rst:1867 msgid "" "For type variables created through :ref:`type parameter syntax `, the bound is evaluated only when the attribute is accessed, not " "when the type variable is created (see :ref:`lazy-evaluation`)." msgstr "" +"Para tipos variáveis criado por meio da :ref:`sintaxe de parâmetro de tipo " +"` , a limite é avaliado somente quando o atributo é acessado, " +"não quando o tipo variável é criado (consulte :ref:`lazy-evaluation`)." -#: ../../library/typing.rst:1749 +#: ../../library/typing.rst:1873 msgid "A tuple containing the constraints of the type variable, if any." -msgstr "" +msgstr "Um tupla contendo as restrições do tipo variável, se houver." -#: ../../library/typing.rst:1753 +#: ../../library/typing.rst:1877 msgid "" "For type variables created through :ref:`type parameter syntax `, the constraints are evaluated only when the attribute is accessed, " "not when the type variable is created (see :ref:`lazy-evaluation`)." msgstr "" +"Para tipos variáveis criado por meio da :ref:`sintaxe de parâmetro de tipo " +"` , a restrição é avaliada somente quando o atributo é " +"acessado, não quando o tipo variável é criado (consulte :ref:`lazy-" +"evaluation`)." -#: ../../library/typing.rst:1759 +#: ../../library/typing.rst:1883 msgid "" "The default value of the type variable, or :data:`typing.NoDefault` if it " "has no default." msgstr "" +"O padrão valor do tipo variável, ou :data:`typing.NoDefault` se ele não " +"tiver padrão." -#: ../../library/typing.rst:1766 +#: ../../library/typing.rst:1890 msgid "" "Return whether or not the type variable has a default value. This is " "equivalent to checking whether :attr:`__default__` is not the :data:`typing." "NoDefault` singleton, except that it does not force evaluation of the :ref:" "`lazily evaluated ` default value." msgstr "" +"Retorna se o tipo variável tem ou não um valor padrão. Isso equivale a " +"verificar se :attr:`__default__` não é o singleton :data:`typing.NoDefault`, " +"exceto por não forçar a avaliação instantânea do valor padrão que é :ref:" +"`avaliado preguiçosamente `." -#: ../../library/typing.rst:1775 +#: ../../library/typing.rst:1899 msgid "" "Type variables can now be declared using the :ref:`type parameter ` syntax introduced by :pep:`695`. The ``infer_variance`` parameter " "was added." msgstr "" +"Tipos variáveis agora podem ser declarados usando a :ref:`sintaxe de " +"parâmetro de tipo ` introduzida por :pep:`695`. O parâmetro " +"``infer_variance`` foi adicionado." -#: ../../library/typing.rst:1781 ../../library/typing.rst:1920 -#: ../../library/typing.rst:2022 +#: ../../library/typing.rst:1905 ../../library/typing.rst:2044 +#: ../../library/typing.rst:2146 msgid "Support for default values was added." -msgstr "" +msgstr "Adiciona suporte a valores padrão." -#: ../../library/typing.rst:1787 +#: ../../library/typing.rst:1911 msgid "" "Type variable tuple. A specialized form of :ref:`type variable ` " "that enables *variadic* generics." msgstr "" +"Tupla de tipo variável. Uma forma especializada de :ref:`tipo variável " +"` que permite genéricos *variádicos*." -#: ../../library/typing.rst:1790 +#: ../../library/typing.rst:1914 msgid "" "Type variable tuples can be declared in :ref:`type parameter lists ` using a single asterisk (``*``) before the name::" msgstr "" +"Tuplas de tipo variável podem ser declarada em :ref:`listas de parâmetros de " +"tipo ` usando um único asterisco (``*``) antes do nome::" -#: ../../library/typing.rst:1796 +#: ../../library/typing.rst:1917 +msgid "" +"def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, " +"T]:\n" +" return (*tup[1:], tup[0])" +msgstr "" +"def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, " +"T]:\n" +" return (*tup[1:], tup[0])" + +#: ../../library/typing.rst:1920 msgid "Or by explicitly invoking the ``TypeVarTuple`` constructor::" +msgstr "Ou invocando o construtor ``TypeVarTuple`` explicitamente::" + +#: ../../library/typing.rst:1922 +msgid "" +"T = TypeVar(\"T\")\n" +"Ts = TypeVarTuple(\"Ts\")\n" +"\n" +"def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:\n" +" return (*tup[1:], tup[0])" msgstr "" +"T = TypeVar(\"T\")\n" +"Ts = TypeVarTuple(\"Ts\")\n" +"\n" +"def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:\n" +" return (*tup[1:], tup[0])" -#: ../../library/typing.rst:1804 +#: ../../library/typing.rst:1928 msgid "" "A normal type variable enables parameterization with a single type. A type " "variable tuple, in contrast, allows parameterization with an *arbitrary* " "number of types by acting like an *arbitrary* number of type variables " "wrapped in a tuple. For example::" msgstr "" - -#: ../../library/typing.rst:1826 +"Um tipo variável normal permite a parametrização com um único tipo. Uma " +"tupla de tipos variáveis, por outro lado, permite a parametrização com um " +"número *arbitrário* de tipos, agindo como um número *arbitrário* de tipos " +"variáveis envolvidos em um tupla. Por exemplo::" + +#: ../../library/typing.rst:1933 +msgid "" +"# T is bound to int, Ts is bound to ()\n" +"# Return value is (1,), which has type tuple[int]\n" +"move_first_element_to_last(tup=(1,))\n" +"\n" +"# T is bound to int, Ts is bound to (str,)\n" +"# Return value is ('spam', 1), which has type tuple[str, int]\n" +"move_first_element_to_last(tup=(1, 'spam'))\n" +"\n" +"# T is bound to int, Ts is bound to (str, float)\n" +"# Return value is ('spam', 3.0, 1), which has type tuple[str, float, int]\n" +"move_first_element_to_last(tup=(1, 'spam', 3.0))\n" +"\n" +"# This fails to type check (and fails at runtime)\n" +"# because tuple[()] is not compatible with tuple[T, *Ts]\n" +"# (at least one element is required)\n" +"move_first_element_to_last(tup=())" +msgstr "" +"# T é limitado a int, Ts é limitado a ()\n" +"# Valor retornado é (1,), que tem tipo tuple[int]\n" +"move_first_element_to_last(tup=(1,))\n" +"\n" +"# T é limitado a int, Ts é limitado a (str,)\n" +"# Valor retornado é ('spam', 1), que tem tipo tuple[str, int]\n" +"move_first_element_to_last(tup=(1, 'spam'))\n" +"\n" +"# T é limitado a int, Ts é limitado a (str, float)\n" +"# Valor retornado é ('spam', 3.0, 1), que tem tipo tuple[str, float, int]\n" +"move_first_element_to_last(tup=(1, 'spam', 3.0))\n" +"\n" +"# Isso é um erro para o verificador de tipos (e falha em tempo de execução)\n" +"# pois tuple[()] não é compatível com tuple[T, *Ts]\n" +"# (pelo menos um elemento é necessário)\n" +"move_first_element_to_last(tup=())" + +#: ../../library/typing.rst:1950 msgid "" "Note the use of the unpacking operator ``*`` in ``tuple[T, *Ts]``. " "Conceptually, you can think of ``Ts`` as a tuple of type variables ``(T1, " @@ -1868,37 +4076,128 @@ msgid "" "older versions of Python, you might see this written using :data:`Unpack " "` instead, as ``Unpack[Ts]``.)" msgstr "" +"Observe o uso do operador de desempacotamento ``*`` em ``tuple[T, *Ts]``. " +"Conceitualmente, você pode interpretar ``Ts`` como uma tupla de tipos " +"variáveis ``(T1, T2, ...)`` . Então o tipo ``tuple[T, *Ts]`` se tornaria " +"``tuple[T, *(T1, T2, ...)]``, que equivale a ``tuple[T, T1, T2, ...]``. " +"(Note que, em versões mais antigas de Python, você pode encontrar isso " +"escrito com :data:`Unpack ` em vez de ``Unpack[Ts]``.)" -#: ../../library/typing.rst:1834 +#: ../../library/typing.rst:1958 msgid "" "Type variable tuples must *always* be unpacked. This helps distinguish type " "variable tuples from normal type variables::" msgstr "" +"Tuplas de tipos variáveis devem *sempre* ser desempacotadas. Isso ajuda a " +"distinguir entre tuplas de tipos variáveis e tipos variáveis normais::" -#: ../../library/typing.rst:1841 +#: ../../library/typing.rst:1961 +msgid "" +"x: Ts # Not valid\n" +"x: tuple[Ts] # Not valid\n" +"x: tuple[*Ts] # The correct way to do it" +msgstr "" +"x: Ts # Inválido\n" +"x: tuple[Ts] # Inválido\n" +"x: tuple[*Ts] # O jeito correto" + +#: ../../library/typing.rst:1965 msgid "" "Type variable tuples can be used in the same contexts as normal type " "variables. For example, in class definitions, arguments, and return types::" msgstr "" +"As tuplas de tipos variáveis podem ser usadas no mesmo contexto que tipos " +"variáveis normais. Por exemplo, em argumentos, tipos de retorno e definições " +"de classes::" -#: ../../library/typing.rst:1849 +#: ../../library/typing.rst:1968 +msgid "" +"class Array[*Shape]:\n" +" def __getitem__(self, key: tuple[*Shape]) -> float: ...\n" +" def __abs__(self) -> \"Array[*Shape]\": ...\n" +" def get_shape(self) -> tuple[*Shape]: ..." +msgstr "" +"class Array[*Shape]:\n" +" def __getitem__(self, key: tuple[*Shape]) -> float: ...\n" +" def __abs__(self) -> \"Array[*Shape]\": ...\n" +" def get_shape(self) -> tuple[*Shape]: ..." + +#: ../../library/typing.rst:1973 msgid "" "Type variable tuples can be happily combined with normal type variables:" msgstr "" +"As tuplas de tipos variáveis podem ser combinadas com tipos variáveis " +"normais:" + +#: ../../library/typing.rst:1975 +msgid "" +"class Array[DType, *Shape]: # This is fine\n" +" pass\n" +"\n" +"class Array2[*Shape, DType]: # This would also be fine\n" +" pass\n" +"\n" +"class Height: ...\n" +"class Width: ...\n" +"\n" +"float_array_1d: Array[float, Height] = Array() # Totally fine\n" +"int_array_2d: Array[int, Height, Width] = Array() # Yup, fine too" +msgstr "" +"class Array[DType, *Shape]: # Tudo certo aqui\n" +" pass\n" +"\n" +"class Array2[*Shape, DType]: # Tudo certo aqui também\n" +" pass\n" +"\n" +"class Height: ...\n" +"class Width: ...\n" +"\n" +"float_array_1d: Array[float, Height] = Array() # Totalmente certo\n" +"int_array_2d: Array[int, Height, Width] = Array() # Sim, certo também" -#: ../../library/typing.rst:1865 +#: ../../library/typing.rst:1989 msgid "" "However, note that at most one type variable tuple may appear in a single " "list of type arguments or type parameters::" msgstr "" +"No entanto, observe que no máximo uma tupla de tipos variáveis pode aparecer " +"em uma única lista de argumentos de tipo ou parâmetros de tipo::" + +#: ../../library/typing.rst:1992 +msgid "" +"x: tuple[*Ts, *Ts] # Not valid\n" +"class Array[*Shape, *Shape]: # Not valid\n" +" pass" +msgstr "" +"x: tuple[*Ts, *Ts] # Inválido\n" +"class Array[*Shape, *Shape]: # Inválido\n" +" pass" -#: ../../library/typing.rst:1872 +#: ../../library/typing.rst:1996 msgid "" "Finally, an unpacked type variable tuple can be used as the type annotation " "of ``*args``::" msgstr "" +"Por fim, uma tupla de tipos variáveis desempacotada pode ser usada como " +"anotação de tipo de ``*args``::" + +#: ../../library/typing.rst:1999 +msgid "" +"def call_soon[*Ts](\n" +" callback: Callable[[*Ts], None],\n" +" *args: *Ts\n" +") -> None:\n" +" ...\n" +" callback(*args)" +msgstr "" +"def call_soon[*Ts](\n" +" callback: Callable[[*Ts], None],\n" +" *args: *Ts\n" +") -> None:\n" +" ...\n" +" callback(*args)" -#: ../../library/typing.rst:1882 +#: ../../library/typing.rst:2006 msgid "" "In contrast to non-unpacked annotations of ``*args`` - e.g. ``*args: int``, " "which would specify that *all* arguments are ``int`` - ``*args: *Ts`` " @@ -1906,54 +4205,83 @@ msgid "" "Here, this allows us to ensure the types of the ``*args`` passed to " "``call_soon`` match the types of the (positional) arguments of ``callback``." msgstr "" +"Ao contrário do que acontece com anotações não desempacotadas de ``*args`` - " +"por exemplo, ``*args: int``, que especificaria que *todos* os argumentos são " +"``int`` -, ``*args: *Ts`` permite referenciar os tipos de cada argumento em " +"``*args`` *individualmente*. Isso nos permite garantir que os tipos em " +"``*args`` passados para ``call_soon`` correspondem aos tipos dos argumentos " +"(posicionais) de ``callback``." -#: ../../library/typing.rst:1889 +#: ../../library/typing.rst:2013 msgid "See :pep:`646` for more details on type variable tuples." msgstr "" +"Consulte a :pep:`646` para mais detalhes sobre tuplas de tipos variáveis." -#: ../../library/typing.rst:1893 +#: ../../library/typing.rst:2017 msgid "The name of the type variable tuple." -msgstr "" +msgstr "O nome da tupla de tipos variáveis." -#: ../../library/typing.rst:1897 +#: ../../library/typing.rst:2021 msgid "" "The default value of the type variable tuple, or :data:`typing.NoDefault` if " "it has no default." msgstr "" +"O valor padrão da tupla de tipos variáveis, ou :data:`typing.NoDefault` se " +"não existir padrão." -#: ../../library/typing.rst:1904 +#: ../../library/typing.rst:2028 msgid "" "Return whether or not the type variable tuple has a default value. This is " "equivalent to checking whether :attr:`__default__` is not the :data:`typing." "NoDefault` singleton, except that it does not force evaluation of the :ref:" "`lazily evaluated ` default value." msgstr "" +"Retorna se a tupla de tipos variáveis tem ou não um valor padrão. Isso " +"equivale a verificar se :attr:`__default__` não é o singleton :data:`typing." +"NoDefault`, exceto por não forçar a avaliação instantânea do valor padrão " +"que é :ref:`avaliado preguiçosamente `." -#: ../../library/typing.rst:1915 +#: ../../library/typing.rst:2039 msgid "" "Type variable tuples can now be declared using the :ref:`type parameter " "` syntax introduced by :pep:`695`." msgstr "" +"Tuplas de tipos variáveis agora podem ser declaradas usando a sintaxe de :" +"ref:`parâmetros de tipo ` introduzido pela :pep:`695`." -#: ../../library/typing.rst:1924 +#: ../../library/typing.rst:2048 msgid "" "Parameter specification variable. A specialized version of :ref:`type " "variables `." msgstr "" +"Variável de especificação de parâmetro. Uma versão especializada de :ref:" +"`tipos variáveis `." -#: ../../library/typing.rst:1927 +#: ../../library/typing.rst:2051 msgid "" "In :ref:`type parameter lists `, parameter specifications can " "be declared with two asterisks (``**``)::" msgstr "" +"Em :ref:`listas de parâmetros de tipo ` as especificações de " +"parâmetros podem ser declaradas com dois asteriscos (``**``)::" + +#: ../../library/typing.rst:2054 +msgid "type IntFunc[**P] = Callable[P, int]" +msgstr "type IntFunc[**P] = Callable[P, int]" -#: ../../library/typing.rst:1932 +#: ../../library/typing.rst:2056 msgid "" "For compatibility with Python 3.11 and earlier, ``ParamSpec`` objects can " "also be created as follows::" msgstr "" +"Para compatibilidade com Python 3.11 e versões anteriores, os objetos " +"``ParamSpec`` também podem ser criados da seguinte forma::" -#: ../../library/typing.rst:1937 +#: ../../library/typing.rst:2059 +msgid "P = ParamSpec('P')" +msgstr "P = ParamSpec('P')" + +#: ../../library/typing.rst:2061 msgid "" "Parameter specification variables exist primarily for the benefit of static " "type checkers. They are used to forward the parameter types of one callable " @@ -1962,36 +4290,89 @@ msgid "" "first argument to ``Callable``, or as parameters for user-defined Generics. " "See :class:`Generic` for more information on generic types." msgstr "" +"Variáveis de especificação de parâmetro existem principalmente para o " +"benefício de verificadores de tipo estático. São usadas para encaminhar os " +"tipos de parâmetros de um chamável para outro chamável -- um padrão " +"comumente encontrado em funções e decoradores de ordem superior. Só são " +"válidas quando usados em ``Concatenate``, ou como o primeiro argumento para " +"``Callable``, ou como parâmetro para genéricos definidos pelo usuário. " +"Consulte :class:`Generic` para obter mais informações sobre tipos genéricos." -#: ../../library/typing.rst:1944 +#: ../../library/typing.rst:2068 msgid "" "For example, to add basic logging to a function, one can create a decorator " "``add_logging`` to log function calls. The parameter specification variable " "tells the type checker that the callable passed into the decorator and the " "new callable returned by it have inter-dependent type parameters::" msgstr "" +"Por exemplo, para adicionar um registro básico de eventos a uma função, é " +"possível criar um decorador ``add_logging`` para registrar chamadas de " +"função. A variável de especificação de parâmetro informa ao verificador de " +"tipos que o chamável passado para o decorador e o novo chamável retornado " +"por ele têm parâmetros de tipo interdependentes::" -#: ../../library/typing.rst:1964 +#: ../../library/typing.rst:2073 +msgid "" +"from collections.abc import Callable\n" +"import logging\n" +"\n" +"def add_logging[T, **P](f: Callable[P, T]) -> Callable[P, T]:\n" +" '''A type-safe decorator to add logging to a function.'''\n" +" def inner(*args: P.args, **kwargs: P.kwargs) -> T:\n" +" logging.info(f'{f.__name__} was called')\n" +" return f(*args, **kwargs)\n" +" return inner\n" +"\n" +"@add_logging\n" +"def add_two(x: float, y: float) -> float:\n" +" '''Add two numbers together.'''\n" +" return x + y" +msgstr "" +"from collections.abc import Callable\n" +"import logging\n" +"\n" +"def add_logging[T, **P](f: Callable[P, T]) -> Callable[P, T]:\n" +" '''Um decorador com segurança de tipos que acrescenta registros de " +"eventos (logs) a uma função.'''\n" +" def inner(*args: P.args, **kwargs: P.kwargs) -> T:\n" +" logging.info(f'{f.__name__} was called')\n" +" return f(*args, **kwargs)\n" +" return inner\n" +"\n" +"@add_logging\n" +"def add_two(x: float, y: float) -> float:\n" +" '''Soma dois números.'''\n" +" return x + y" + +#: ../../library/typing.rst:2088 msgid "" "Without ``ParamSpec``, the simplest way to annotate this previously was to " -"use a :class:`TypeVar` with bound ``Callable[..., Any]``. However this " -"causes two problems:" +"use a :class:`TypeVar` with upper bound ``Callable[..., Any]``. However " +"this causes two problems:" msgstr "" +"Sem o ``ParamSpec``, a maneira mais simples de anotar isso anteriormente era " +"usar um :class:`TypeVar` com o limite superior ``Callable[..., Any]``. No " +"entanto, isso causa dois problemas:" -#: ../../library/typing.rst:1968 +#: ../../library/typing.rst:2092 msgid "" "The type checker can't type check the ``inner`` function because ``*args`` " "and ``**kwargs`` have to be typed :data:`Any`." msgstr "" +"O verificador de tipos não consegue verificar a função ``inner``, porque " +"``*args`` e ``**kwargs`` precisam ter tipo :data:`Any`." -#: ../../library/typing.rst:1970 +#: ../../library/typing.rst:2094 msgid "" ":func:`~cast` may be required in the body of the ``add_logging`` decorator " "when returning the ``inner`` function, or the static type checker must be " "told to ignore the ``return inner``." msgstr "" +":func:`~cast` pode ser exigida no corpo do decorador ``add_logging`` ao " +"retornar a função ``inner``, ou o verificador de tipo estático deverá ser " +"instruído a ignorar o ``return inner``." -#: ../../library/typing.rst:1977 +#: ../../library/typing.rst:2101 msgid "" "Since ``ParamSpec`` captures both positional and keyword parameters, ``P." "args`` and ``P.kwargs`` can be used to split a ``ParamSpec`` into its " @@ -2003,26 +4384,42 @@ msgid "" "``P.kwargs`` are instances respectively of :class:`ParamSpecArgs` and :class:" "`ParamSpecKwargs`." msgstr "" +"Como ``ParamSpec`` captura tanto parâmetros posicionais quanto parâmetros " +"nomeados, ``P.args`` e ``P.kwargs`` podem ser usados para dividir um " +"``ParamSpec`` em seus componentes. ``P.args`` representa a tupla de " +"parâmetros posicionais em uma determinada chamada e só deve ser usada para " +"anotar ``*args``. ``P.kwargs`` representa o mapeamento de parâmetros " +"nomeados para seus valores em uma determinada chamada, e só deve ser usado " +"para anotar ``**kwargs``. Ambos os atributos exigem que o parâmetro anotado " +"esteja em escopo. Em tempo de execução, ``P.args`` e ``P.kwargs`` são " +"instâncias, respectivamente, de :class:`ParamSpecArgs` e :class:" +"`ParamSpecKwargs`." -#: ../../library/typing.rst:1989 +#: ../../library/typing.rst:2113 msgid "The name of the parameter specification." -msgstr "" +msgstr "O nome da especificação de parâmetros." -#: ../../library/typing.rst:1993 +#: ../../library/typing.rst:2117 msgid "" "The default value of the parameter specification, or :data:`typing." "NoDefault` if it has no default." msgstr "" +"O valor padrão da especificação de parâmetro, ou :data:`typing.NoDefault` se " +"não tiver padrão." -#: ../../library/typing.rst:2000 +#: ../../library/typing.rst:2124 msgid "" "Return whether or not the parameter specification has a default value. This " "is equivalent to checking whether :attr:`__default__` is not the :data:" "`typing.NoDefault` singleton, except that it does not force evaluation of " "the :ref:`lazily evaluated ` default value." msgstr "" +"Retorna se a especificação de parâmetros tem ou não um valor padrão. Isso " +"equivale a verificar se :attr:`__default__` não é o singleton :data:`typing." +"NoDefault`, exceto por não forçar a avaliação instantânea do valor padrão " +"que é :ref:`avaliado preguiçosamente `." -#: ../../library/typing.rst:2007 +#: ../../library/typing.rst:2131 msgid "" "Parameter specification variables created with ``covariant=True`` or " "``contravariant=True`` can be used to declare covariant or contravariant " @@ -2030,97 +4427,240 @@ msgid "" "`TypeVar`. However the actual semantics of these keywords are yet to be " "decided." msgstr "" +"Variáveis de especificação de parâmetros criadas com ``covariant=True`` ou " +"``contravariant=True`` podem ser usadas para declarar tipos genéricos " +"covariantes ou contravariantes. O argumento ``bound`` também é aceito, " +"semelhante ao :class:`TypeVar`. Porém, a semântica real dessas palavras " +"reservadas ainda não foi decidida." -#: ../../library/typing.rst:2017 +#: ../../library/typing.rst:2141 msgid "" "Parameter specifications can now be declared using the :ref:`type parameter " "` syntax introduced by :pep:`695`." msgstr "" +"Especificações de parâmetros agora podem ser declaradas usando a sintaxe de :" +"ref:`parâmetros de tipo ` introduzido pela :pep:`695`." -#: ../../library/typing.rst:2025 +#: ../../library/typing.rst:2149 msgid "" "Only parameter specification variables defined in global scope can be " "pickled." msgstr "" +"Somente variáveis de especificação de parâmetro definidas em escopo global " +"podem ser serializadas com pickle." -#: ../../library/typing.rst:2031 +#: ../../library/typing.rst:2155 msgid ":data:`Concatenate`" -msgstr "" +msgstr ":data:`Concatenate`" -#: ../../library/typing.rst:2037 +#: ../../library/typing.rst:2161 msgid "" "Arguments and keyword arguments attributes of a :class:`ParamSpec`. The ``P." "args`` attribute of a ``ParamSpec`` is an instance of ``ParamSpecArgs``, and " "``P.kwargs`` is an instance of ``ParamSpecKwargs``. They are intended for " "runtime introspection and have no special meaning to static type checkers." msgstr "" +"Tipos dos argumentos e dos argumentos nomeados de um :class:`ParamSpec`. O " +"atributo ``P.args`` de um ``ParamSpec`` é uma instância de " +"``ParamSpecArgs``, e o atributo ``P.kwargs`` é uma instância de " +"``ParamSpecKwargs``. São destinados à introspecção em tempo de execução, e " +"não têm nenhum significado especial para o verificador de tipo estático." -#: ../../library/typing.rst:2042 +#: ../../library/typing.rst:2166 msgid "" "Calling :func:`get_origin` on either of these objects will return the " "original ``ParamSpec``:" msgstr "" +"Chamar :func:`get_origin` em qualquer um desses objetos retornará o " +"``ParamSpec`` original:" -#: ../../library/typing.rst:2059 +#: ../../library/typing.rst:2169 +msgid "" +">>> from typing import ParamSpec, get_origin\n" +">>> P = ParamSpec(\"P\")\n" +">>> get_origin(P.args) is P\n" +"True\n" +">>> get_origin(P.kwargs) is P\n" +"True" +msgstr "" +">>> from typing import ParamSpec, get_origin\n" +">>> P = ParamSpec(\"P\")\n" +">>> get_origin(P.args) is P\n" +"True\n" +">>> get_origin(P.kwargs) is P\n" +"True" + +#: ../../library/typing.rst:2183 msgid "The type of type aliases created through the :keyword:`type` statement." +msgstr "O tipo de apelidos de tipo criados pela instrução :keyword:`type`." + +#: ../../library/typing.rst:2187 +msgid "" +">>> type Alias = int\n" +">>> type(Alias)\n" +"" msgstr "" +">>> type Alias = int\n" +">>> type(Alias)\n" +"" -#: ../../library/typing.rst:2073 +#: ../../library/typing.rst:2197 msgid "The name of the type alias:" +msgstr "O nome do apelido de tipo:" + +#: ../../library/typing.rst:2199 +msgid "" +">>> type Alias = int\n" +">>> Alias.__name__\n" +"'Alias'" msgstr "" +">>> type Alias = int\n" +">>> Alias.__name__\n" +"'Alias'" -#: ../../library/typing.rst:2083 +#: ../../library/typing.rst:2207 msgid "The module in which the type alias was defined::" -msgstr "O módulo na qual o apelido de tipo foi definido::" +msgstr "O módulo no qual o apelido de tipo foi definido::" + +#: ../../library/typing.rst:2209 +msgid "" +">>> type Alias = int\n" +">>> Alias.__module__\n" +"'__main__'" +msgstr "" +">>> type Alias = int\n" +">>> Alias.__module__\n" +"'__main__'" -#: ../../library/typing.rst:2091 +#: ../../library/typing.rst:2215 msgid "" "The type parameters of the type alias, or an empty tuple if the alias is not " "generic:" msgstr "" +"Os parâmetros de tipo do apelido de tipo, ou uma tupla vazia se o apelido " +"não for genérico:" -#: ../../library/typing.rst:2105 +#: ../../library/typing.rst:2218 +msgid "" +">>> type ListOrSet[T] = list[T] | set[T]\n" +">>> ListOrSet.__type_params__\n" +"(T,)\n" +">>> type NotGeneric = int\n" +">>> NotGeneric.__type_params__\n" +"()" +msgstr "" +">>> type ListOrSet[T] = list[T] | set[T]\n" +">>> ListOrSet.__type_params__\n" +"(T,)\n" +">>> type NotGeneric = int\n" +">>> NotGeneric.__type_params__\n" +"()" + +#: ../../library/typing.rst:2229 msgid "" "The type alias's value. This is :ref:`lazily evaluated `, " "so names used in the definition of the alias are not resolved until the " "``__value__`` attribute is accessed:" msgstr "" +"O valor do apelido de tipo. Isso é uma :ref:`avaliação preguiçosa `, portanto, os nomes usados na definição do apelido não são " +"resolvidos até que o atributo ``__value__`` seja acessado:" + +#: ../../library/typing.rst:2233 +msgid "" +">>> type Mutually = Recursive\n" +">>> type Recursive = Mutually\n" +">>> Mutually\n" +"Mutually\n" +">>> Recursive\n" +"Recursive\n" +">>> Mutually.__value__\n" +"Recursive\n" +">>> Recursive.__value__\n" +"Mutually" +msgstr "" +">>> type Mutually = Recursive\n" +">>> type Recursive = Mutually\n" +">>> Mutually\n" +"Mutually\n" +">>> Recursive\n" +"Recursive\n" +">>> Mutually.__value__\n" +"Recursive\n" +">>> Recursive.__value__\n" +"Mutually" -#: ../../library/typing.rst:2123 +#: ../../library/typing.rst:2247 msgid "Other special directives" msgstr "Outras diretivas especiais" -#: ../../library/typing.rst:2125 +#: ../../library/typing.rst:2249 msgid "" "These functions and classes should not be used directly as annotations. " "Their intended purpose is to be building blocks for creating and declaring " "types." msgstr "" +"Essas funções e classes não devem ser usadas diretamente como anotações. O " +"objetivo é que sejam blocos de construção para criar e declarar tipos." -#: ../../library/typing.rst:2131 +#: ../../library/typing.rst:2255 msgid "Typed version of :func:`collections.namedtuple`." -msgstr "" +msgstr "Versão tipada de :func:`collections.namedtuple`." -#: ../../library/typing.rst:2133 ../../library/typing.rst:2223 -#: ../../library/typing.rst:3262 +#: ../../library/typing.rst:2257 ../../library/typing.rst:2349 +#: ../../library/typing.rst:3397 msgid "Usage::" msgstr "Uso::" -#: ../../library/typing.rst:2139 +#: ../../library/typing.rst:2259 +msgid "" +"class Employee(NamedTuple):\n" +" name: str\n" +" id: int" +msgstr "" +"class Employee(NamedTuple):\n" +" name: str\n" +" id: int" + +#: ../../library/typing.rst:2263 msgid "This is equivalent to::" msgstr "Isso equivale a::" -#: ../../library/typing.rst:2143 +#: ../../library/typing.rst:2265 +msgid "Employee = collections.namedtuple('Employee', ['name', 'id'])" +msgstr "Employee = collections.namedtuple('Employee', ['name', 'id'])" + +#: ../../library/typing.rst:2267 msgid "" "To give a field a default value, you can assign to it in the class body::" msgstr "" +"Para dar um valor padrão a um campo, você pode atribuir um valor a ele no " +"corpo da classe::" -#: ../../library/typing.rst:2152 +#: ../../library/typing.rst:2269 +msgid "" +"class Employee(NamedTuple):\n" +" name: str\n" +" id: int = 3\n" +"\n" +"employee = Employee('Guido')\n" +"assert employee.id == 3" +msgstr "" +"class Employee(NamedTuple):\n" +" name: str\n" +" id: int = 3\n" +"\n" +"employee = Employee('Guido')\n" +"assert employee.id == 3" + +#: ../../library/typing.rst:2276 msgid "" "Fields with a default value must come after any fields without a default." msgstr "" +"Campos com valor padrão devem vir depois de quaisquer campos sem valor " +"padrão." -#: ../../library/typing.rst:2154 +#: ../../library/typing.rst:2278 msgid "" "The resulting class has an extra attribute ``__annotations__`` giving a dict " "that maps the field names to the field types. (The field names are in the " @@ -2128,51 +4668,116 @@ msgid "" "attribute, both of which are part of the :func:`~collections.namedtuple` " "API.)" msgstr "" +"A classe resultante tem um atributo extra ``__annotations__`` que fornece um " +"dicionário que mapeia os nomes de campos para os tipos de campos. (Os nomes " +"de campos estão no atributo ``_fields`` e os valores padrões estão no " +"atributo ``_field_defaults``, e ambos fazem parte da API de :func:" +"`~collections.namedtuple`.)" -#: ../../library/typing.rst:2160 +#: ../../library/typing.rst:2284 msgid "``NamedTuple`` subclasses can also have docstrings and methods::" msgstr "" +"Subclasses de ``NamedTuple`` também podem ter strings de documentação e " +"métodos::" -#: ../../library/typing.rst:2170 -msgid "``NamedTuple`` subclasses can be generic::" +#: ../../library/typing.rst:2286 +msgid "" +"class Employee(NamedTuple):\n" +" \"\"\"Represents an employee.\"\"\"\n" +" name: str\n" +" id: int = 3\n" +"\n" +" def __repr__(self) -> str:\n" +" return f''" msgstr "" +"class Employee(NamedTuple):\n" +" \"\"\"Representa um funcionário.\"\"\"\n" +" name: str\n" +" id: int = 3\n" +"\n" +" def __repr__(self) -> str:\n" +" return f''" -#: ../../library/typing.rst:2176 -msgid "Backward-compatible usage::" +#: ../../library/typing.rst:2294 +msgid "``NamedTuple`` subclasses can be generic::" +msgstr "Subclasses de ``NamedTuple`` podem ser genéricas::" + +#: ../../library/typing.rst:2296 +msgid "" +"class Group[T](NamedTuple):\n" +" key: T\n" +" group: list[T]" msgstr "" +"class Group[T](NamedTuple):\n" +" key: T\n" +" group: list[T]" -#: ../../library/typing.rst:2186 +#: ../../library/typing.rst:2300 +msgid "Backward-compatible usage::" +msgstr "Uso retrocompatível::" + +#: ../../library/typing.rst:2302 +msgid "" +"# For creating a generic NamedTuple on Python 3.11\n" +"T = TypeVar(\"T\")\n" +"\n" +"class Group(NamedTuple, Generic[T]):\n" +" key: T\n" +" group: list[T]\n" +"\n" +"# A functional syntax is also supported\n" +"Employee = NamedTuple('Employee', [('name', str), ('id', int)])" +msgstr "" +"# Para criar uma NamedTuple genérica em Python 3.11\n" +"T = TypeVar(\"T\")\n" +"\n" +"class Group(NamedTuple, Generic[T]):\n" +" key: T\n" +" group: list[T]\n" +"\n" +"# Também há suporte para a sintaxe funcional\n" +"Employee = NamedTuple('Employee', [('name', str), ('id', int)])" + +#: ../../library/typing.rst:2312 msgid "Added support for :pep:`526` variable annotation syntax." -msgstr "" +msgstr "Adiciona suporte à sintaxe de anotação de variáveis da :pep:`526`." -#: ../../library/typing.rst:2189 +#: ../../library/typing.rst:2315 msgid "Added support for default values, methods, and docstrings." -msgstr "" +msgstr "Adiciona suporte a valores padrões, métodos, e docstrings." -#: ../../library/typing.rst:2192 +#: ../../library/typing.rst:2318 msgid "" "The ``_field_types`` and ``__annotations__`` attributes are now regular " "dictionaries instead of instances of ``OrderedDict``." msgstr "" +"Os atributos ``_field_types`` e ``__annotations__`` agora são dicionários " +"regulares em vez de instâncias de ``OrderedDict``." -#: ../../library/typing.rst:2196 +#: ../../library/typing.rst:2322 msgid "" "Removed the ``_field_types`` attribute in favor of the more standard " "``__annotations__`` attribute which has the same information." msgstr "" +"Remove o atributo ``_field_types`` em favor do atributo mais padronizado " +"``__annotations__`` que tem as mesmas informações." -#: ../../library/typing.rst:2200 +#: ../../library/typing.rst:2326 msgid "Added support for generic namedtuples." -msgstr "" +msgstr "Adiciona suporte a tuplas nomeadas genéricas." -#: ../../library/typing.rst:2203 +#: ../../library/typing.rst:2329 msgid "" "The undocumented keyword argument syntax for creating NamedTuple classes " "(``NT = NamedTuple(\"NT\", x=int)``) is deprecated, and will be disallowed " "in 3.15. Use the class-based syntax or the functional syntax instead." msgstr "" +"A sintaxe de argumentos nomeados não documentados para criar classes " +"NamedTuple (``NT = NamedTuple(\"NT\", x=int)``) está descontinuado e será " +"proibido na versão 3.15. Em vez disso, use a sintaxe baseada em classes ou a " +"sintaxe funcional." -#: ../../library/typing.rst:2208 +#: ../../library/typing.rst:2334 msgid "" "When using the functional syntax to create a NamedTuple class, failing to " "pass a value to the 'fields' parameter (``NT = NamedTuple(\"NT\")``) is " @@ -2181,79 +4786,202 @@ msgid "" "Python 3.15. To create a NamedTuple class with 0 fields, use ``class " "NT(NamedTuple): pass`` or ``NT = NamedTuple(\"NT\", [])``." msgstr "" +"Ao usar a sintaxe funcional para criar uma classe NamedTuple, não passar um " +"valor para o parâmetro 'fields' (``NT = NamedTuple(\"NT\")``) está " +"descontinuado. Passar ``None`` para o parâmetro 'fields' (``NT = " +"NamedTuple(\"NT\", None)``) também está descontinuado. Ambos não serão " +"permitidos em Python 3.15. Para criar uma classe NamedTuple com 0 campos, " +"use ``class NT(NamedTuple): pass`` ou ``NT = NamedTuple(\"NT\", [])``." -#: ../../library/typing.rst:2218 +#: ../../library/typing.rst:2344 msgid "Helper class to create low-overhead :ref:`distinct types `." msgstr "" +"Classe auxiliar para criar :ref:`tipos únicos ` com baixo custo." -#: ../../library/typing.rst:2220 +#: ../../library/typing.rst:2346 msgid "" "A ``NewType`` is considered a distinct type by a typechecker. At runtime, " "however, calling a ``NewType`` returns its argument unchanged." msgstr "" +"Um tipo ``NewType`` é considerado um tipo distinto por um verificador de " +"tipos. Porém, em tempo de execução, chamar ``NewType`` retorna seu argumento " +"inalterado." -#: ../../library/typing.rst:2230 -msgid "The module in which the new type is defined." +#: ../../library/typing.rst:2351 +msgid "" +"UserId = NewType('UserId', int) # Declare the NewType \"UserId\"\n" +"first_user = UserId(1) # \"UserId\" returns the argument unchanged at " +"runtime" msgstr "" +"UserId = NewType('UserId', int) # Declare o NewType \"UserId\"\n" +"first_user = UserId(1) # \"UserId\" retorna o argumento inalterado em tempo " +"de execução" + +#: ../../library/typing.rst:2356 +msgid "The module in which the new type is defined." +msgstr "O módulo no qual o novo tipo está definido." -#: ../../library/typing.rst:2234 +#: ../../library/typing.rst:2360 msgid "The name of the new type." msgstr "O nome do novo tipo." -#: ../../library/typing.rst:2238 +#: ../../library/typing.rst:2364 msgid "The type that the new type is based on." msgstr "O tipo na qual o novo tipo é baseado." -#: ../../library/typing.rst:2242 +#: ../../library/typing.rst:2368 msgid "``NewType`` is now a class rather than a function." -msgstr "" +msgstr "``NewType`` agora é uma classe em vez de uma função." -#: ../../library/typing.rst:2247 +#: ../../library/typing.rst:2373 msgid "Base class for protocol classes." -msgstr "" +msgstr "Classe base para classes de protocolo." -#: ../../library/typing.rst:2249 +#: ../../library/typing.rst:2375 msgid "Protocol classes are defined like this::" +msgstr "Classes de protocolo são definidas assim::" + +#: ../../library/typing.rst:2377 +msgid "" +"class Proto(Protocol):\n" +" def meth(self) -> int:\n" +" ..." msgstr "" +"class Proto(Protocol):\n" +" def meth(self) -> int:\n" +" ..." -#: ../../library/typing.rst:2255 +#: ../../library/typing.rst:2381 msgid "" "Such classes are primarily used with static type checkers that recognize " "structural subtyping (static duck-typing), for example::" msgstr "" +"Essas classes são usadas principalmente com verificadores de tipo estático " +"que reconhecem a subtipagem estrutural (tipagem pato estática). Por exemplo::" -#: ../../library/typing.rst:2267 +#: ../../library/typing.rst:2384 +msgid "" +"class C:\n" +" def meth(self) -> int:\n" +" return 0\n" +"\n" +"def func(x: Proto) -> int:\n" +" return x.meth()\n" +"\n" +"func(C()) # Passes static type check" +msgstr "" +"class C:\n" +" def meth(self) -> int:\n" +" return 0\n" +"\n" +"def func(x: Proto) -> int:\n" +" return x.meth()\n" +"\n" +"func(C()) # Passa na verificação de tipos" + +#: ../../library/typing.rst:2393 msgid "" "See :pep:`544` for more details. Protocol classes decorated with :func:" "`runtime_checkable` (described later) act as simple-minded runtime protocols " "that check only the presence of given attributes, ignoring their type " -"signatures." +"signatures. Protocol classes without this decorator cannot be used as the " +"second argument to :func:`isinstance` or :func:`issubclass`." msgstr "" +"Consulte a :pep:`544` para obter mais detalhes. Classes de protocolo " +"decoradas com :func:`runtime_checkable` (descritas posteriormente) funcionam " +"como protocolos em tempo de execução simples, somente verificando a presença " +"de determinados atributos, e ignorando suas assinaturas de tipo. Classes de " +"protocolo sem este decorador não podem ser usadas como o segundo argumento " +"para :func:`isinstance` ou :func:`issubclass`." -#: ../../library/typing.rst:2272 +#: ../../library/typing.rst:2399 msgid "Protocol classes can be generic, for example::" +msgstr "Classes de protocolo podem ser genéricas. Por exemplo::" + +#: ../../library/typing.rst:2401 +msgid "" +"class GenProto[T](Protocol):\n" +" def meth(self) -> T:\n" +" ..." msgstr "" +"class GenProto[T](Protocol):\n" +" def meth(self) -> T:\n" +" ..." -#: ../../library/typing.rst:2278 +#: ../../library/typing.rst:2405 msgid "" "In code that needs to be compatible with Python 3.11 or older, generic " "Protocols can be written as follows::" msgstr "" +"Em códigos que precisam ser compatíveis com Python 3.11 ou versões " +"anteriores, protocolos genéricos podem ser escritos da seguinte forma::" -#: ../../library/typing.rst:2291 -msgid "Mark a protocol class as a runtime protocol." +#: ../../library/typing.rst:2408 +msgid "" +"T = TypeVar(\"T\")\n" +"\n" +"class GenProto(Protocol[T]):\n" +" def meth(self) -> T:\n" +" ..." msgstr "" +"T = TypeVar(\"T\")\n" +"\n" +"class GenProto(Protocol[T]):\n" +" def meth(self) -> T:\n" +" ..." -#: ../../library/typing.rst:2293 +#: ../../library/typing.rst:2418 +msgid "Mark a protocol class as a runtime protocol." +msgstr "Marca uma classe de protocolo como um protocolo de tempo de execução." + +#: ../../library/typing.rst:2420 msgid "" "Such a protocol can be used with :func:`isinstance` and :func:`issubclass`. " -"This raises :exc:`TypeError` when applied to a non-protocol class. This " -"allows a simple-minded structural check, very similar to \"one trick " +"This allows a simple-minded structural check, very similar to \"one trick " "ponies\" in :mod:`collections.abc` such as :class:`~collections.abc." "Iterable`. For example::" msgstr "" - -#: ../../library/typing.rst:2313 +"Esse protocolo pode ser usado com :func:`isinstance` e :func:`issubclass`. " +"Isso permite uma verificação estrutural simples, muito semelhante a \"pôneis " +"de um truque só\" em :mod:`collections.abc`, como :class:`~collections.abc." +"Iterable`. Por exemplo::" + +#: ../../library/typing.rst:2424 +msgid "" +"@runtime_checkable\n" +"class Closable(Protocol):\n" +" def close(self): ...\n" +"\n" +"assert isinstance(open('/some/file'), Closable)\n" +"\n" +"@runtime_checkable\n" +"class Named(Protocol):\n" +" name: str\n" +"\n" +"import threading\n" +"assert isinstance(threading.Thread(name='Bob'), Named)" +msgstr "" +"@runtime_checkable\n" +"class Closable(Protocol):\n" +" def close(self): ...\n" +"\n" +"assert isinstance(open('/some/file'), Closable)\n" +"\n" +"@runtime_checkable\n" +"class Named(Protocol):\n" +" name: str\n" +"\n" +"import threading\n" +"assert isinstance(threading.Thread(name='Bob'), Named)" + +#: ../../library/typing.rst:2437 +msgid "" +"This decorator raises :exc:`TypeError` when applied to a non-protocol class." +msgstr "" +"Este decorador levanta :exc:`TypeError` quando aplicado a uma classe não-" +"protocolo." + +#: ../../library/typing.rst:2441 msgid "" ":func:`!runtime_checkable` will check only the presence of the required " "methods or attributes, not their type signatures or types. For example, :" @@ -2263,16 +4991,28 @@ msgid "" "more informative message, therefore making it impossible to call " "(instantiate) :class:`ssl.SSLObject`." msgstr "" +":func:`!runtime_checkable` verificará apenas a presença dos métodos ou " +"atributos obrigatórios, em vez de tipos ou assinaturas de tipos. Por " +"exemplo, o :class:`ssl.SSLObject` é uma classe e, portanto, passa por uma " +"verificação :func:`issubclass` em relação a :ref:`Callable `. No entanto, o método ``ssl.SSLObject.__init__`` existe apenas " +"para levantar um :exc:`TypeError` com uma mensagem mais informativa, o que " +"impossibilita chamar (instanciar) o :class:`ssl.SSLObject`." -#: ../../library/typing.rst:2324 +#: ../../library/typing.rst:2452 msgid "" "An :func:`isinstance` check against a runtime-checkable protocol can be " "surprisingly slow compared to an ``isinstance()`` check against a non-" "protocol class. Consider using alternative idioms such as :func:`hasattr` " "calls for structural checks in performance-sensitive code." msgstr "" +"uma verificação com :func:`isinstance` sobre um protocolo verificável em " +"tempo de execução pode ser surpreendentemente lenta se comparada a uma " +"verificação ``isinstance()`` sobre outros tipos de classe. Considere usar " +"expressões alternativas, como chamar a função :func:`hasattr` para realizar " +"verificações estruturais em código sensível a desempenho." -#: ../../library/typing.rst:2332 +#: ../../library/typing.rst:2460 msgid "" "The internal implementation of :func:`isinstance` checks against runtime-" "checkable protocols now uses :func:`inspect.getattr_static` to look up " @@ -2281,8 +5021,15 @@ msgid "" "longer be considered instances of that protocol on Python 3.12+, and vice " "versa. Most users are unlikely to be affected by this change." msgstr "" +"A implementação interna do :func:`isinstance` agora verifica os protocolos " +"verificáveis em tempo de execução usando :func:`inspect.getattr_static` para " +"procurar o atributo (anteriormente, era usado :func:`hasattr`). Como " +"resultado, alguns objetos que costumavam ser considerados instâncias de um " +"protoloco verifiável em tempo de execução podem não ser mais considerados " +"instâncias desse protocolo em Python 3.12+, e vice-versa. É improvável que a " +"maioria dos usuários seja afetada por essa alteração." -#: ../../library/typing.rst:2341 +#: ../../library/typing.rst:2469 msgid "" "The members of a runtime-checkable protocol are now considered \"frozen\" at " "runtime as soon as the class has been created. Monkey-patching attributes " @@ -2290,107 +5037,361 @@ msgid "" "on :func:`isinstance` checks comparing objects to the protocol. See :ref:" "`\"What's new in Python 3.12\" ` for more details." msgstr "" +"Os membros de um protocolo verificável em tempo de execução agora serão " +"considerados \"congelados\" em tempo de execução assim que a classe for " +"criada. A alteração dinâmica de atributos de um protocolo em tempo de " +"execução ainda funcionará, mas não terá impacto nas verificações de :func:" +"`isinstance` ao comparar objetos com o protocolo. Consulte :ref:`whatsnew-" +"typing-py312` para mais detalhes." -#: ../../library/typing.rst:2352 +#: ../../library/typing.rst:2480 msgid "" "Special construct to add type hints to a dictionary. At runtime it is a " "plain :class:`dict`." msgstr "" +"Uma construção especial para adicionar dicas de tipo a um dicionário. Em " +"tempo de execução, é um simples :class:`dict`." -#: ../../library/typing.rst:2355 +#: ../../library/typing.rst:2483 msgid "" "``TypedDict`` declares a dictionary type that expects all of its instances " "to have a certain set of keys, where each key is associated with a value of " "a consistent type. This expectation is not checked at runtime but is only " "enforced by type checkers. Usage::" msgstr "" - -#: ../../library/typing.rst:2371 +"``TypedDict`` declara um tipo dicionário que espera que todas as suas " +"instâncias tenham um determinado conjunto de chaves, onde cada chave está " +"associada a um valor de um tipo consistente. Essa expectativa não é " +"verificada em tempo de execução, mas é imposta apenas por verificadores de " +"tipos. Modo de usar::" + +#: ../../library/typing.rst:2489 +msgid "" +"class Point2D(TypedDict):\n" +" x: int\n" +" y: int\n" +" label: str\n" +"\n" +"a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK\n" +"b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check\n" +"\n" +"assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')" +msgstr "" +"class Point2D(TypedDict):\n" +" x: int\n" +" y: int\n" +" label: str\n" +"\n" +"a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK\n" +"b: Point2D = {'z': 3, 'label': 'bad'} # Falha na verificação de " +"tipos\n" +"\n" +"assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')" + +#: ../../library/typing.rst:2499 msgid "" "An alternative way to create a ``TypedDict`` is by using function-call " "syntax. The second argument must be a literal :class:`dict`::" msgstr "" +"Um modo alternativo de criar um ``TypedDict`` é usando a sintaxe de chamada " +"de função. O segundo argumento deve ser um :class:`dict`::" + +#: ../../library/typing.rst:2502 +msgid "Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})" +msgstr "Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})" -#: ../../library/typing.rst:2376 +#: ../../library/typing.rst:2504 msgid "" "This functional syntax allows defining keys which are not valid :ref:" "`identifiers `, for example because they are keywords or " -"contain hyphens::" -msgstr "" - -#: ../../library/typing.rst:2388 +"contain hyphens, or when key names must not be :ref:`mangled ` like regular private names::" +msgstr "" +"Esta sintaxe funcional permite definirmos chaves usando :ref:" +"`identificadores ` inválidos, por exemplo, por serem palavras-" +"chave ou conterem hífens, ou quando os nomes das chaves não devem ser :ref:" +"`desconfigurados ` como nomes privados comuns::" + +#: ../../library/typing.rst:2509 +msgid "" +"# raises SyntaxError\n" +"class Point2D(TypedDict):\n" +" in: int # 'in' is a keyword\n" +" x-y: int # name with hyphens\n" +"\n" +"class Definition(TypedDict):\n" +" __schema: str # mangled to `_Definition__schema`\n" +"\n" +"# OK, functional syntax\n" +"Point2D = TypedDict('Point2D', {'in': int, 'x-y': int})\n" +"Definition = TypedDict('Definition', {'__schema': str}) # not mangled" +msgstr "" +"# levanta SyntaxError\n" +"class Point2D(TypedDict):\n" +" in: int # 'in' é uma palavra reservada\n" +" x-y: int # nome com hífen\n" +"\n" +"class Definition(TypedDict):\n" +" __schema: str # desconfigurado para `_Definition__schema`\n" +"\n" +"# OK, sintaxe funcional\n" +"Point2D = TypedDict('Point2D', {'in': int, 'x-y': int})\n" +"Definition = TypedDict('Definition', {'__schema': str}) # não desconfigurado" + +#: ../../library/typing.rst:2521 msgid "" "By default, all keys must be present in a ``TypedDict``. It is possible to " "mark individual keys as non-required using :data:`NotRequired`::" msgstr "" +"Por padrão, todas as chaves devem estar presentes em um ``TypedDict``. É " +"possível marcar chaves individuais como não-obrigatórias usando :data:" +"`NotRequired`::" -#: ../../library/typing.rst:2399 +#: ../../library/typing.rst:2524 +msgid "" +"class Point2D(TypedDict):\n" +" x: int\n" +" y: int\n" +" label: NotRequired[str]\n" +"\n" +"# Alternative syntax\n" +"Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': " +"NotRequired[str]})" +msgstr "" +"class Point2D(TypedDict):\n" +" x: int\n" +" y: int\n" +" label: NotRequired[str]\n" +"\n" +"# Sintaxe alternativa\n" +"Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': " +"NotRequired[str]})" + +#: ../../library/typing.rst:2532 msgid "" "This means that a ``Point2D`` ``TypedDict`` can have the ``label`` key " "omitted." msgstr "" +"Isso significa que um ``TypedDict`` ``Point2D`` pode ter a chave ``label`` " +"omitida." -#: ../../library/typing.rst:2402 +#: ../../library/typing.rst:2535 msgid "" "It is also possible to mark all keys as non-required by default by " "specifying a totality of ``False``::" msgstr "" +"Também é possível marcar todas as chaves como não necessárias por padrão, " +"especificando a totalidade como ``False``::" -#: ../../library/typing.rst:2412 +#: ../../library/typing.rst:2538 +msgid "" +"class Point2D(TypedDict, total=False):\n" +" x: int\n" +" y: int\n" +"\n" +"# Alternative syntax\n" +"Point2D = TypedDict('Point2D', {'x': int, 'y': int}, total=False)" +msgstr "" +"class Point2D(TypedDict, total=False):\n" +" x: int\n" +" y: int\n" +"\n" +"# Sintaxe alternativa\n" +"Point2D = TypedDict('Point2D', {'x': int, 'y': int}, total=False)" + +#: ../../library/typing.rst:2545 msgid "" "This means that a ``Point2D`` ``TypedDict`` can have any of the keys " "omitted. A type checker is only expected to support a literal ``False`` or " "``True`` as the value of the ``total`` argument. ``True`` is the default, " "and makes all items defined in the class body required." msgstr "" +"Isso significa que um ``TypedDict`` ``Point2D`` pode ter qualquer uma de " +"suas chaves omitidas. Espera-se que um verificador de tipos apenas permita " +"os literais ``False`` ou ``True`` como valores do argumento ``total``. " +"``True`` é o padrão, e todos os itens definidos no corpo da classe tornam-se " +"obrigatórios." -#: ../../library/typing.rst:2417 +#: ../../library/typing.rst:2550 msgid "" "Individual keys of a ``total=False`` ``TypedDict`` can be marked as required " "using :data:`Required`::" msgstr "" - -#: ../../library/typing.rst:2432 +"As chaves individuais de um ``TypedDict`` com ``total=False`` podem ser " +"marcadas como obrigatórias usando :data:`Required`::" + +#: ../../library/typing.rst:2553 +msgid "" +"class Point2D(TypedDict, total=False):\n" +" x: Required[int]\n" +" y: Required[int]\n" +" label: str\n" +"\n" +"# Alternative syntax\n" +"Point2D = TypedDict('Point2D', {\n" +" 'x': Required[int],\n" +" 'y': Required[int],\n" +" 'label': str\n" +"}, total=False)" +msgstr "" +"class Point2D(TypedDict, total=False):\n" +" x: Required[int]\n" +" y: Required[int]\n" +" label: str\n" +"\n" +"# Sintaxe alternativa\n" +"Point2D = TypedDict('Point2D', {\n" +" 'x': Required[int],\n" +" 'y': Required[int],\n" +" 'label': str\n" +"}, total=False)" + +#: ../../library/typing.rst:2565 msgid "" "It is possible for a ``TypedDict`` type to inherit from one or more other " "``TypedDict`` types using the class-based syntax. Usage::" msgstr "" +"É possível que um tipo ``TypedDict`` herde de um ou mais tipos ``TypedDict`` " +"usando a sintaxe baseada em classes. Modo de usar::" + +#: ../../library/typing.rst:2569 +msgid "" +"class Point3D(Point2D):\n" +" z: int" +msgstr "" +"class Point3D(Point2D):\n" +" z: int" -#: ../../library/typing.rst:2439 +#: ../../library/typing.rst:2572 msgid "" "``Point3D`` has three items: ``x``, ``y`` and ``z``. It is equivalent to " "this definition::" msgstr "" +"``Point3D`` tem três itens: ``x``, ``y`` e ``z``. Equivale a esta definição::" -#: ../../library/typing.rst:2447 +#: ../../library/typing.rst:2575 +msgid "" +"class Point3D(TypedDict):\n" +" x: int\n" +" y: int\n" +" z: int" +msgstr "" +"class Point3D(TypedDict):\n" +" x: int\n" +" y: int\n" +" z: int" + +#: ../../library/typing.rst:2580 msgid "" "A ``TypedDict`` cannot inherit from a non-\\ ``TypedDict`` class, except " "for :class:`Generic`. For example::" msgstr "" +"Um ``TypedDict`` não pode herdar de uma classe não ``TypedDict``, exceto :" +"class:`Generic`. Por exemplo::" + +#: ../../library/typing.rst:2583 +msgid "" +"class X(TypedDict):\n" +" x: int\n" +"\n" +"class Y(TypedDict):\n" +" y: int\n" +"\n" +"class Z(object): pass # A non-TypedDict class\n" +"\n" +"class XY(X, Y): pass # OK\n" +"\n" +"class XZ(X, Z): pass # raises TypeError" +msgstr "" +"class X(TypedDict):\n" +" x: int\n" +"\n" +"class Y(TypedDict):\n" +" y: int\n" +"\n" +"class Z(object): pass # Uma classe não TypedDict\n" +"\n" +"class XY(X, Y): pass # OK\n" +"\n" +"class XZ(X, Z): pass # levanta TypeError" -#: ../../library/typing.rst:2462 +#: ../../library/typing.rst:2595 msgid "A ``TypedDict`` can be generic::" msgstr "Um ``TypedDict`` pode ser genérico::" -#: ../../library/typing.rst:2468 +#: ../../library/typing.rst:2597 +msgid "" +"class Group[T](TypedDict):\n" +" key: T\n" +" group: list[T]" +msgstr "" +"class Group[T](TypedDict):\n" +" key: T\n" +" group: list[T]" + +#: ../../library/typing.rst:2601 msgid "" "To create a generic ``TypedDict`` that is compatible with Python 3.11 or " "lower, inherit from :class:`Generic` explicitly:" msgstr "" +"Para criar um ``TypedDict`` genérico que seja compatível com Python 3.11 ou " +"inferior, herde de :class:`Generic` explicitamente:" -#: ../../library/typing.rst:2479 +#: ../../library/typing.rst:2604 +msgid "" +"T = TypeVar(\"T\")\n" +"\n" +"class Group(TypedDict, Generic[T]):\n" +" key: T\n" +" group: list[T]" +msgstr "" +"T = TypeVar(\"T\")\n" +"\n" +"class Group(TypedDict, Generic[T]):\n" +" key: T\n" +" group: list[T]" + +#: ../../library/typing.rst:2612 msgid "" "A ``TypedDict`` can be introspected via annotations dicts (see :ref:" "`annotations-howto` for more information on annotations best practices), :" "attr:`__total__`, :attr:`__required_keys__`, and :attr:`__optional_keys__`." msgstr "" +"Um ``TypedDict`` pode ser inspecionado por meio de dicionários de anotações " +"(consulte :ref:`annotations-howto` para obter mais informações sobre as " +"melhores práticas de anotações), :attr:`__total__`, :attr:" +"`__required_keys__` e :attr:`__optional_keys__`." -#: ../../library/typing.rst:2485 +#: ../../library/typing.rst:2618 msgid "" "``Point2D.__total__`` gives the value of the ``total`` argument. Example:" -msgstr "" - -#: ../../library/typing.rst:2501 +msgstr "``Point2D.__total__`` fornece o valor do argumento ``total``. Exemplo:" + +#: ../../library/typing.rst:2621 +msgid "" +">>> from typing import TypedDict\n" +">>> class Point2D(TypedDict): pass\n" +">>> Point2D.__total__\n" +"True\n" +">>> class Point2D(TypedDict, total=False): pass\n" +">>> Point2D.__total__\n" +"False\n" +">>> class Point3D(Point2D): pass\n" +">>> Point3D.__total__\n" +"True" +msgstr "" +">>> from typing import TypedDict\n" +">>> class Point2D(TypedDict): pass\n" +">>> Point2D.__total__\n" +"True\n" +">>> class Point2D(TypedDict, total=False): pass\n" +">>> Point2D.__total__\n" +"False\n" +">>> class Point3D(Point2D): pass\n" +">>> Point3D.__total__\n" +"True" + +#: ../../library/typing.rst:2634 msgid "" "This attribute reflects *only* the value of the ``total`` argument to the " "current ``TypedDict`` class, not whether the class is semantically total. " @@ -2400,22 +5401,34 @@ msgid "" "use :attr:`__required_keys__` and :attr:`__optional_keys__` for " "introspection." msgstr "" +"Esse atributo reflete *apenas* o valor do argumento ``total`` para a classe " +"``TypedDict`` atual, e não que a classe é semanticamente total. Por exemplo, " +"um ``TypedDict`` com ``__total__`` definido como ``True`` pode ter chaves " +"marcadas com :data:`NotRequired`, ou pode herdar de outro ``TypedDict`` com " +"``total=False``. Portanto, geralmente é melhor usar :attr:" +"`__required_keys__` e :attr:`__optional_keys__` para introspecção." -#: ../../library/typing.rst:2514 +#: ../../library/typing.rst:2647 msgid "" "``Point2D.__required_keys__`` and ``Point2D.__optional_keys__`` return :" "class:`frozenset` objects containing required and non-required keys, " "respectively." msgstr "" +"``Point2D.__required_keys__`` e ``Point2D.__optional_keys__`` retornam " +"objetos :class:`frozenset` contendo chaves obrigatórias e opcionais, " +"respectivamente." -#: ../../library/typing.rst:2517 +#: ../../library/typing.rst:2650 msgid "" "Keys marked with :data:`Required` will always appear in " "``__required_keys__`` and keys marked with :data:`NotRequired` will always " "appear in ``__optional_keys__``." msgstr "" +"As chaves marcadas com :data:`Required` sempre aparecerão em " +"``__required_keys__`` e as chaves marcadas com :data:`NotRequired` sempre " +"aparecerão em ``__optional_keys__``." -#: ../../library/typing.rst:2520 +#: ../../library/typing.rst:2653 msgid "" "For backwards compatibility with Python 3.10 and below, it is also possible " "to use inheritance to declare both required and non-required keys in the " @@ -2423,8 +5436,39 @@ msgid "" "value for the ``total`` argument and then inheriting from it in another " "``TypedDict`` with a different value for ``total``:" msgstr "" - -#: ../../library/typing.rst:2545 +"Para manter a retrocompatibilidade com Python 3.10 e versões anteriores, " +"também é possível usar herança para declarar chaves obrigatórias e opcionais " +"no mesmo ``TypedDict``. Isso é feito declarando um ``TypedDict`` com um " +"valor para o argumento ``total`` e então herdando-a em outro ``TypedDict`` " +"usando um valor ``total`` diferente:" + +#: ../../library/typing.rst:2660 +msgid "" +">>> class Point2D(TypedDict, total=False):\n" +"... x: int\n" +"... y: int\n" +"...\n" +">>> class Point3D(Point2D):\n" +"... z: int\n" +"...\n" +">>> Point3D.__required_keys__ == frozenset({'z'})\n" +"True\n" +">>> Point3D.__optional_keys__ == frozenset({'x', 'y'})\n" +"True" +msgstr "" +">>> class Point2D(TypedDict, total=False):\n" +"... x: int\n" +"... y: int\n" +"...\n" +">>> class Point3D(Point2D):\n" +"... z: int\n" +"...\n" +">>> Point3D.__required_keys__ == frozenset({'z'})\n" +"True\n" +">>> Point3D.__optional_keys__ == frozenset({'x', 'y'})\n" +"True" + +#: ../../library/typing.rst:2678 msgid "" "If ``from __future__ import annotations`` is used or if annotations are " "given as strings, annotations are not evaluated when the ``TypedDict`` is " @@ -2432,49 +5476,66 @@ msgid "" "``__optional_keys__`` rely on may not work properly, and the values of the " "attributes may be incorrect." msgstr "" +"Se ``from __future__ import annotations`` for usado ou se anotações forem " +"fornecidas como strings, as anotações não serão avaliadas quando o " +"``TypedDict`` for definido. Portanto, a introspecção em tempo de execução da " +"qual ``__required_keys__`` e ``__optional_keys__`` dependem pode não " +"funcionar corretamente, e os valores dos atributos podem estar incorretos." -#: ../../library/typing.rst:2551 +#: ../../library/typing.rst:2684 msgid "Support for :data:`ReadOnly` is reflected in the following attributes:" msgstr "" +"O suporte para :data:`ReadOnly` está refletido nos seguintes atributos:" -#: ../../library/typing.rst:2555 +#: ../../library/typing.rst:2688 msgid "" "A :class:`frozenset` containing the names of all read-only keys. Keys are " "read-only if they carry the :data:`ReadOnly` qualifier." msgstr "" +"Um :class:`frozenset` contendo os nomes de todas as chaves somente para " +"leitura. As chaves são somente para leitura se tiverem o qualificador :data:" +"`ReadOnly`." -#: ../../library/typing.rst:2562 +#: ../../library/typing.rst:2695 msgid "" "A :class:`frozenset` containing the names of all mutable keys. Keys are " "mutable if they do not carry the :data:`ReadOnly` qualifier." msgstr "" +"Um :class:`frozenset` contendo os nomes de todas as chaves mutáveis. As " +"chaves são mutáveis se não tiverem o qualificador :data:`ReadOnly`." -#: ../../library/typing.rst:2567 +#: ../../library/typing.rst:2700 msgid "" "See :pep:`589` for more examples and detailed rules of using ``TypedDict``." msgstr "" +"Consulte :pep:`589` para obter mais exemplos e regras detalhadas sobre o uso " +"de ``TypedDict``." -#: ../../library/typing.rst:2571 +#: ../../library/typing.rst:2704 msgid "" "Added support for marking individual keys as :data:`Required` or :data:" "`NotRequired`. See :pep:`655`." msgstr "" +"Adicionado suporte para marcar chaves individuais como :data:`Required` ou :" +"data:`NotRequired`. Consulte :pep:`655`." -#: ../../library/typing.rst:2575 +#: ../../library/typing.rst:2708 msgid "Added support for generic ``TypedDict``\\ s." msgstr "Adicionado suporte para ``TypedDict``\\ s genéricos." -#: ../../library/typing.rst:2578 +#: ../../library/typing.rst:2711 msgid "" "Removed support for the keyword-argument method of creating ``TypedDict``\\ " "s." msgstr "" +"Removeu suporte para o método de argumento nomeado para criar " +"``TypedDict``\\ s." -#: ../../library/typing.rst:2581 +#: ../../library/typing.rst:2714 msgid "Support for the :data:`ReadOnly` qualifier was added." -msgstr "" +msgstr "Adiciona suporte ao qualificador :data:`ReadOnly`." -#: ../../library/typing.rst:2584 +#: ../../library/typing.rst:2717 msgid "" "When using the functional syntax to create a TypedDict class, failing to " "pass a value to the 'fields' parameter (``TD = TypedDict(\"TD\")``) is " @@ -2483,116 +5544,196 @@ msgid "" "Python 3.15. To create a TypedDict class with 0 fields, use ``class " "TD(TypedDict): pass`` or ``TD = TypedDict(\"TD\", {})``." msgstr "" +"Ao usar a sintaxe funcional para criar uma classe TypedDict, não passar um " +"valor para o parâmetro 'fields' (``TD = TypedDict(\"TD\")``) está " +"descontinuado. Passar ``None`` para o parâmetro 'fields' (``TD = " +"TypedDict(\"TD\", None)``) também está descontinuado. Ambos não serão " +"permitidos em Python 3.15. Para criar uma classe TypedDict com 0 campos, use " +"``class TD(TypedDict): pass`` ou ``TD = TypedDict(\"TD\", {})``." -#: ../../library/typing.rst:2593 +#: ../../library/typing.rst:2726 msgid "Protocols" msgstr "Protocolos" -#: ../../library/typing.rst:2595 +#: ../../library/typing.rst:2728 msgid "" -"The following protocols are provided by the typing module. All are decorated " -"with :func:`@runtime_checkable `." +"The following protocols are provided by the :mod:`!typing` module. All are " +"decorated with :func:`@runtime_checkable `." msgstr "" +"Os protocolos a seguir são fornecidos pelo módulo :mod:`!typing`. Todos são " +"decorados com :func:`@runtime_checkable `." -#: ../../library/typing.rst:2600 +#: ../../library/typing.rst:2733 msgid "" "An ABC with one abstract method ``__abs__`` that is covariant in its return " "type." msgstr "" +"Um ABC com um método abstrato ``__abs__`` que é covariante em seu tipo de " +"retorno." -#: ../../library/typing.rst:2605 +#: ../../library/typing.rst:2738 msgid "An ABC with one abstract method ``__bytes__``." -msgstr "" +msgstr "Um ABC com um método abstrato ``__bytes__``." -#: ../../library/typing.rst:2609 +#: ../../library/typing.rst:2742 msgid "An ABC with one abstract method ``__complex__``." -msgstr "" +msgstr "Um ABC com um método abstrato ``__complex__``." -#: ../../library/typing.rst:2613 +#: ../../library/typing.rst:2746 msgid "An ABC with one abstract method ``__float__``." -msgstr "" +msgstr "Um ABC com um método abstrato ``__float__``." -#: ../../library/typing.rst:2617 +#: ../../library/typing.rst:2750 msgid "An ABC with one abstract method ``__index__``." -msgstr "" +msgstr "Um ABC com um método abstrato ``__index__``." -#: ../../library/typing.rst:2623 +#: ../../library/typing.rst:2756 msgid "An ABC with one abstract method ``__int__``." -msgstr "" +msgstr "Um ABC com um método abstrato ``__int__``." -#: ../../library/typing.rst:2627 +#: ../../library/typing.rst:2760 msgid "" "An ABC with one abstract method ``__round__`` that is covariant in its " "return type." msgstr "" +"Uma ABC com um método abstrato ``__round__`` que é covariante em seu tipo de " +"retorno." -#: ../../library/typing.rst:2631 +#: ../../library/typing.rst:2764 msgid "ABCs for working with IO" -msgstr "ABCs para trabalhar com IO" +msgstr "ABCs para trabalhar com E/S" -#: ../../library/typing.rst:2637 +#: ../../library/typing.rst:2770 msgid "" "Generic type ``IO[AnyStr]`` and its subclasses ``TextIO(IO[str])`` and " "``BinaryIO(IO[bytes])`` represent the types of I/O streams such as returned " "by :func:`open`." msgstr "" +"O tipo genérico ``IO[AnyStr]`` e suas subclasses ``TextIO(IO[str])`` e " +"``BinaryIO(IO[bytes])`` representam os tipos de fluxos de E/S, como os " +"retornados por :func:`open`." -#: ../../library/typing.rst:2643 +#: ../../library/typing.rst:2776 msgid "Functions and decorators" msgstr "Funções e decoradores" -#: ../../library/typing.rst:2647 +#: ../../library/typing.rst:2780 msgid "Cast a value to a type." -msgstr "Define um valor para um tipo." +msgstr "Converta um valor em um tipo." -#: ../../library/typing.rst:2649 +#: ../../library/typing.rst:2782 msgid "" "This returns the value unchanged. To the type checker this signals that the " "return value has the designated type, but at runtime we intentionally don't " "check anything (we want this to be as fast as possible)." msgstr "" +"Isso retorna o valor inalterado. Para o verificador de tipos, isso indica " +"que o valor de retorno tem o tipo designado, mas em tempo de execução não " +"verificamos nada intencionalmente (queremos que isso seja o mais rápido " +"possível)." -#: ../../library/typing.rst:2656 +#: ../../library/typing.rst:2789 msgid "" "Ask a static type checker to confirm that *val* has an inferred type of " "*typ*." msgstr "" +"Pede para um verificador de tipo estático confirmar se *val* tem tipo " +"inferido *typ*." -#: ../../library/typing.rst:2658 +#: ../../library/typing.rst:2791 msgid "" "At runtime this does nothing: it returns the first argument unchanged with " "no checks or side effects, no matter the actual type of the argument." msgstr "" +"Essa função faz nada em tempo de execução: ela retorna o primeiro argumento " +"inalterado, sem verificações ou efeitos colaterais, independentemente do " +"tipo real do argumento." -#: ../../library/typing.rst:2661 +#: ../../library/typing.rst:2794 msgid "" "When a static type checker encounters a call to ``assert_type()``, it emits " "an error if the value is not of the specified type::" msgstr "" +"Quando um verificador de tipo estático encontra uma chamada para " +"``assert_type()``, ele emite um erro se o valor não for do tipo " +"especificado::" -#: ../../library/typing.rst:2668 +#: ../../library/typing.rst:2797 +msgid "" +"def greet(name: str) -> None:\n" +" assert_type(name, str) # OK, inferred type of `name` is `str`\n" +" assert_type(name, int) # type checker error" +msgstr "" +"def greet(name: str) -> None:\n" +" assert_type(name, str) # OK, o tipo inferido de `name` é `str`\n" +" assert_type(name, int) # erro no verificador de tipos" + +#: ../../library/typing.rst:2801 msgid "" "This function is useful for ensuring the type checker's understanding of a " "script is in line with the developer's intentions::" msgstr "" +"Esse função é útil para garantir que o verificador de tipos entende um " +"script conforme as intenções do desenvolvedor::" + +#: ../../library/typing.rst:2804 +msgid "" +"def complex_function(arg: object):\n" +" # Do some complex type-narrowing logic,\n" +" # after which we hope the inferred type will be `int`\n" +" ...\n" +" # Test whether the type checker correctly understands our function\n" +" assert_type(arg, int)" +msgstr "" +"def complex_function(arg: object):\n" +" # Realiza alguma lógica complexa de restrição de tipos\n" +" # após a qual esperamos que o tipo seja `int`\n" +" ...\n" +" # Testa se o verificador de tipos entendeu nossa função corretamente\n" +" assert_type(arg, int)" -#: ../../library/typing.rst:2682 +#: ../../library/typing.rst:2815 msgid "" "Ask a static type checker to confirm that a line of code is unreachable." msgstr "" +"Pede ao verificador de tipo estático para confirmar se uma linha de código é " +"inalcançável." -#: ../../library/typing.rst:2684 +#: ../../library/typing.rst:2817 msgid "Example::" msgstr "Exemplo::" -#: ../../library/typing.rst:2695 +#: ../../library/typing.rst:2819 +msgid "" +"def int_or_str(arg: int | str) -> None:\n" +" match arg:\n" +" case int():\n" +" print(\"It's an int\")\n" +" case str():\n" +" print(\"It's a str\")\n" +" case _ as unreachable:\n" +" assert_never(unreachable)" +msgstr "" +"def int_or_str(arg: int | str) -> None:\n" +" match arg:\n" +" case int():\n" +" print(\"É um int\")\n" +" case str():\n" +" print(\"É um str\")\n" +" case _ as unreachable:\n" +" assert_never(unreachable)" + +#: ../../library/typing.rst:2828 msgid "" "Here, the annotations allow the type checker to infer that the last case can " "never execute, because ``arg`` is either an :class:`int` or a :class:`str`, " "and both options are covered by earlier cases." msgstr "" +"Aqui, as anotações permitem que o verificador de tipos deduza que o último " +"caso nunca será executado, pois ``arg`` é um :class:`int` ou uma :class:" +"`str`, e ambas as opções são cobertas por casos anteriores." -#: ../../library/typing.rst:2700 +#: ../../library/typing.rst:2833 msgid "" "If a type checker finds that a call to ``assert_never()`` is reachable, it " "will emit an error. For example, if the type annotation for ``arg`` was " @@ -2601,62 +5742,105 @@ msgid "" "``assert_never`` to pass type checking, the inferred type of the argument " "passed in must be the bottom type, :data:`Never`, and nothing else." msgstr "" +"Se um verificador de tipos descobrir que uma chamada para ``assert_never()`` " +"é alcançável, ele emitirá um erro. Por exemplo, se a anotação de tipo para " +"``arg`` fosse ``int | str | float``, o verificador de tipos emitiria um erro " +"indicando que ``unreachable`` é do tipo :class:`float`. Para que uma chamada " +"para ``assert_never`` passe verificação de tipos, o tipo inferido do " +"argumento passado deve ser o tipo inferior, :data:`Never`, e nada mais." -#: ../../library/typing.rst:2708 +#: ../../library/typing.rst:2841 msgid "At runtime, this throws an exception when called." -msgstr "" +msgstr "Em tempo de execução, essa função levanta uma exceção quando chamada." -#: ../../library/typing.rst:2711 +#: ../../library/typing.rst:2844 msgid "" -"`Unreachable Code and Exhaustiveness Checking `__ has more information about " -"exhaustiveness checking with static typing." +"`Unreachable Code and Exhaustiveness Checking `__ has more information about exhaustiveness " +"checking with static typing." msgstr "" +"`Unreachable Code and Exhaustiveness Checking `__ tem mais informações sobre a verificação " +"de exaustividade com tipagem estática." -#: ../../library/typing.rst:2719 +#: ../../library/typing.rst:2852 msgid "Ask a static type checker to reveal the inferred type of an expression." msgstr "" +"Pede para um verificador de tipo estático revelar o tipo inferido de uma " +"expressão." -#: ../../library/typing.rst:2721 +#: ../../library/typing.rst:2854 msgid "" "When a static type checker encounters a call to this function, it emits a " "diagnostic with the inferred type of the argument. For example::" msgstr "" +"Quando um verificador de tipo estático encontra uma chamada para essa " +"função, ele emite um diagnóstico com o tipo inferido do argumento. Por " +"exemplo::" + +#: ../../library/typing.rst:2857 +msgid "" +"x: int = 1\n" +"reveal_type(x) # Revealed type is \"builtins.int\"" +msgstr "" +"x: int = 1\n" +"reveal_type(x) # O tipo revelado é \"builtins.int\"" -#: ../../library/typing.rst:2727 +#: ../../library/typing.rst:2860 msgid "" "This can be useful when you want to debug how your type checker handles a " "particular piece of code." msgstr "" +"Isso pode ser útil quando você deseja depurar como o verificador de tipos " +"lida com um determinado trecho de código." -#: ../../library/typing.rst:2730 +#: ../../library/typing.rst:2863 msgid "" "At runtime, this function prints the runtime type of its argument to :data:" "`sys.stderr` and returns the argument unchanged (allowing the call to be " "used within an expression)::" msgstr "" +"Em tempo de execução, esta função envia o tipo de seu argumento para :data:" +"`sys.stderr` e retorna o argumento inalterado (permitindo que a chamada seja " +"usada em uma expressão)::" + +#: ../../library/typing.rst:2867 +msgid "" +"x = reveal_type(1) # prints \"Runtime type is int\"\n" +"print(x) # prints \"1\"" +msgstr "" +"x = reveal_type(1) # exibe \"Runtime type is int\"\n" +"print(x) # exibe \"1\"" -#: ../../library/typing.rst:2737 +#: ../../library/typing.rst:2870 msgid "" "Note that the runtime type may be different from (more or less specific " "than) the type statically inferred by a type checker." msgstr "" +"Observe que o tipo em tempo de execução pode ser diferente (mais ou menos " +"específico) do tipo inferido estaticamente por um verificador de tipos." -#: ../../library/typing.rst:2740 +#: ../../library/typing.rst:2873 msgid "" "Most type checkers support ``reveal_type()`` anywhere, even if the name is " "not imported from ``typing``. Importing the name from ``typing``, however, " "allows your code to run without runtime errors and communicates intent more " "clearly." msgstr "" +"A maioria dos verificadores de tipos dá suporte a ``reveal_type()`` em " +"qualquer lugar, mesmo que o nome não seja importado de ``typing``. Porém, " +"importar o nome de ``typing`` permite que o código seja executado sem erros " +"em tempo de execução e comunica a intenção com mais clareza." -#: ../../library/typing.rst:2751 +#: ../../library/typing.rst:2884 msgid "" "Decorator to mark an object as providing :func:`dataclass `-like behavior." msgstr "" +"Um decorador que marca um objeto como tendo comportamento similar a uma :" +"func:`dataclass `." -#: ../../library/typing.rst:2754 +#: ../../library/typing.rst:2887 msgid "" "``dataclass_transform`` may be used to decorate a class, metaclass, or a " "function that is itself a decorator. The presence of " @@ -2664,28 +5848,96 @@ msgid "" "object performs runtime \"magic\" that transforms a class in a similar way " "to :func:`@dataclasses.dataclass `." msgstr "" +"``dataclass_transform`` pode ser usado para decorar uma classe, metaclasse, " +"ou função decoradora. A presença de ``@dataclass_transform()`` informa a um " +"verificador de tipo estático que o objeto decorado executa \"mágica\" em " +"tempo de execução que transforma uma classe de maneira semelhante a :func:" +"`@dataclasses.dataclass `." -#: ../../library/typing.rst:2761 +#: ../../library/typing.rst:2894 msgid "Example usage with a decorator function:" -msgstr "" - -#: ../../library/typing.rst:2775 +msgstr "Exemplo de uso com a função decoradora:" + +#: ../../library/typing.rst:2896 +msgid "" +"@dataclass_transform()\n" +"def create_model[T](cls: type[T]) -> type[T]:\n" +" ...\n" +" return cls\n" +"\n" +"@create_model\n" +"class CustomerModel:\n" +" id: int\n" +" name: str" +msgstr "" +"@dataclass_transform()\n" +"def create_model[T](cls: type[T]) -> type[T]:\n" +" ...\n" +" return cls\n" +"\n" +"@create_model\n" +"class CustomerModel:\n" +" id: int\n" +" name: str" + +#: ../../library/typing.rst:2908 msgid "On a base class::" -msgstr "" +msgstr "Em uma classe base::" -#: ../../library/typing.rst:2784 -msgid "On a metaclass::" +#: ../../library/typing.rst:2910 +msgid "" +"@dataclass_transform()\n" +"class ModelBase: ...\n" +"\n" +"class CustomerModel(ModelBase):\n" +" id: int\n" +" name: str" msgstr "" +"@dataclass_transform()\n" +"class ModelBase: ...\n" +"\n" +"class CustomerModel(ModelBase):\n" +" id: int\n" +" name: str" -#: ../../library/typing.rst:2795 +#: ../../library/typing.rst:2917 +msgid "On a metaclass::" +msgstr "Em uma metaclasse::" + +#: ../../library/typing.rst:2919 +msgid "" +"@dataclass_transform()\n" +"class ModelMeta(type): ...\n" +"\n" +"class ModelBase(metaclass=ModelMeta): ...\n" +"\n" +"class CustomerModel(ModelBase):\n" +" id: int\n" +" name: str" +msgstr "" +"@dataclass_transform()\n" +"class ModelMeta(type): ...\n" +"\n" +"class ModelBase(metaclass=ModelMeta): ...\n" +"\n" +"class CustomerModel(ModelBase):\n" +" id: int\n" +" name: str" + +#: ../../library/typing.rst:2928 msgid "" "The ``CustomerModel`` classes defined above will be treated by type checkers " "similarly to classes created with :func:`@dataclasses.dataclass `. For example, type checkers will assume these classes have " "``__init__`` methods that accept ``id`` and ``name``." msgstr "" +"As classes ``CustomerModel`` definidas acima serão tratadas pelos " +"verificadores de tipos semelhantemente às classes criadas com :func:" +"`@dataclasses.dataclass `. Por exemplo, os " +"verificadores de tipo presumirão que essas classes têm métodos ``__init__`` " +"que aceitam ``id`` e ``name``." -#: ../../library/typing.rst:2801 +#: ../../library/typing.rst:2934 msgid "" "The decorated class, metaclass, or function may accept the following bool " "arguments which type checkers will assume have the same effect as they would " @@ -2694,122 +5946,155 @@ msgid "" "``kw_only``, and ``slots``. It must be possible for the value of these " "arguments (``True`` or ``False``) to be statically evaluated." msgstr "" +"A classe, metaclasse, ou função decorada pode aceitar os seguintes " +"argumentos booleanos tal que verificadores de tipo presumirão ter o mesmo " +"efeito que teriam no decorador :func:`@dataclasses.dataclass`: ``init``, ``eq``, ``order``, ``unsafe_hash``, ``frozen``, " +"``match_args``, ``kw_only``, e ``slots``. É necessário que o valor desses " +"argumentos (``True`` ou ``False``) seja avaliado estaticamente." -#: ../../library/typing.rst:2809 +#: ../../library/typing.rst:2942 msgid "" "The arguments to the ``dataclass_transform`` decorator can be used to " "customize the default behaviors of the decorated class, metaclass, or " "function:" msgstr "" +"Os argumentos do decorador ``dataclass_transform`` podem ser usados para " +"personalizar o comportamento padrão da classe, metaclasse, ou função " +"decorada:" #: ../../library/typing.rst:0 msgid "Parameters" msgstr "Parâmetros" -#: ../../library/typing.rst:2813 +#: ../../library/typing.rst:2946 msgid "" "Indicates whether the ``eq`` parameter is assumed to be ``True`` or " "``False`` if it is omitted by the caller. Defaults to ``True``." msgstr "" +"Indica se o parâmetro ``eq`` é presumido como ``True`` ou ``False`` se for " +"omitido pelo chamador. O padrão é ``True``." -#: ../../library/typing.rst:2818 +#: ../../library/typing.rst:2951 msgid "" "Indicates whether the ``order`` parameter is assumed to be ``True`` or " "``False`` if it is omitted by the caller. Defaults to ``False``." msgstr "" +"Indica se o parâmetro ``order`` é presumido como ``True`` ou ``False`` se " +"for omitido pelo chamador. O padrão é ``False``." -#: ../../library/typing.rst:2823 +#: ../../library/typing.rst:2956 msgid "" "Indicates whether the ``kw_only`` parameter is assumed to be ``True`` or " "``False`` if it is omitted by the caller. Defaults to ``False``." msgstr "" +"Indica se o parâmetro ``kw_only`` é presumido como ``True`` ou ``False`` se " +"for omitido pelo chamador. O padrão é ``False``." -#: ../../library/typing.rst:2828 +#: ../../library/typing.rst:2961 msgid "" "Indicates whether the ``frozen`` parameter is assumed to be ``True`` or " "``False`` if it is omitted by the caller. Defaults to ``False``. .. " "versionadded:: 3.12" msgstr "" +"Indica se o parâmetro ``frozen`` é presumido como ``True`` ou ``False`` se " +"for omitido pelo chamador. O padrão é ``False``. .. versionadded:: 3.12" -#: ../../library/typing.rst:2829 +#: ../../library/typing.rst:2962 msgid "" "Indicates whether the ``frozen`` parameter is assumed to be ``True`` or " "``False`` if it is omitted by the caller. Defaults to ``False``." msgstr "" +"Indica se o parâmetro ``frozen`` é presumido como ``True`` ou ``False`` se " +"for omitido pelo chamador. O padrão é ``False``." -#: ../../library/typing.rst:2835 +#: ../../library/typing.rst:2968 msgid "" "Specifies a static list of supported classes or functions that describe " "fields, similar to :func:`dataclasses.field`. Defaults to ``()``." msgstr "" +"Especifica uma lista estática de classes ou funções compatíveis que " +"descrevem campos, semelhante a :func:`dataclasses.field`. O valor padrão é " +"``()``." -#: ../../library/typing.rst:2841 +#: ../../library/typing.rst:2974 msgid "" "Arbitrary other keyword arguments are accepted in order to allow for " "possible future extensions." msgstr "" +"Outros argumentos nomeados arbitrários são aceitos para permitir possíveis " +"futuras extensões." -#: ../../library/typing.rst:2845 +#: ../../library/typing.rst:2978 msgid "" "Type checkers recognize the following optional parameters on field " "specifiers:" msgstr "" +"Verificadores de tipo reconhecem os seguintes parâmetros opcionais em " +"especificadores de campos:" -#: ../../library/typing.rst:2848 +#: ../../library/typing.rst:2981 msgid "**Recognised parameters for field specifiers**" -msgstr "" +msgstr "**Parâmetros reconhecidos para especificadores de campos**" -#: ../../library/typing.rst:2852 +#: ../../library/typing.rst:2985 msgid "Parameter name" msgstr "Nome do parâmetro" -#: ../../library/typing.rst:2853 +#: ../../library/typing.rst:2986 msgid "Description" msgstr "Descrição" -#: ../../library/typing.rst:2854 +#: ../../library/typing.rst:2987 msgid "``init``" msgstr "``init``" -#: ../../library/typing.rst:2855 +#: ../../library/typing.rst:2988 msgid "" "Indicates whether the field should be included in the synthesized " "``__init__`` method. If unspecified, ``init`` defaults to ``True``." msgstr "" +"Indica se o campo deve ser incluído no método ``__init__`` sintetizado. Se " +"não for especificado, o valor padrão de ``init`` é ``True``." -#: ../../library/typing.rst:2858 +#: ../../library/typing.rst:2991 msgid "``default``" msgstr "``default``" -#: ../../library/typing.rst:2859 +#: ../../library/typing.rst:2992 msgid "Provides the default value for the field." -msgstr "" +msgstr "Fornece o valor padrão do campo." -#: ../../library/typing.rst:2860 +#: ../../library/typing.rst:2993 msgid "``default_factory``" -msgstr "" +msgstr "``default_factory``" -#: ../../library/typing.rst:2861 +#: ../../library/typing.rst:2994 msgid "" "Provides a runtime callback that returns the default value for the field. If " "neither ``default`` nor ``default_factory`` are specified, the field is " "assumed to have no default value and must be provided a value when the class " "is instantiated." msgstr "" +"Fornece uma função de retorno de tempo de execução que retorna o valor " +"padrão do campo. Se nem ``default`` nem ``default_factory`` forem " +"especificados, o campo é presumido como sem valor padrão e deverá receber um " +"valor quando a classe for instanciada." -#: ../../library/typing.rst:2866 +#: ../../library/typing.rst:2999 msgid "``factory``" -msgstr "" +msgstr "``factory``" -#: ../../library/typing.rst:2867 +#: ../../library/typing.rst:3000 msgid "An alias for the ``default_factory`` parameter on field specifiers." msgstr "" +"Um apelido para o parâmetro ``default_factory`` em especificadores de campos." -#: ../../library/typing.rst:2868 +#: ../../library/typing.rst:3001 msgid "``kw_only``" msgstr "``kw_only``" -#: ../../library/typing.rst:2869 +#: ../../library/typing.rst:3002 msgid "" "Indicates whether the field should be marked as keyword-only. If ``True``, " "the field will be keyword-only. If ``False``, it will not be keyword-only. " @@ -2818,41 +6103,55 @@ msgid "" "unspecified, the value of ``kw_only_default`` on ``dataclass_transform`` " "will be used." msgstr "" +"Indica se o campo deve ser marcado como somente-nomeado. Se verdadeiro, o " +"campo será somente-nomeado. Se falso, não será somente-nomeado. Se não for " +"especificado, será usado o valor do parâmetro ``kw_only`` do objeto decorado " +"com ``dataclass_transform`` ou, se este não for especificado, será usado o " +"valor de ``kw_only_default`` no ``dataclass_transform``." -#: ../../library/typing.rst:2875 +#: ../../library/typing.rst:3008 msgid "``alias``" -msgstr "" +msgstr "``alias``" -#: ../../library/typing.rst:2876 +#: ../../library/typing.rst:3009 msgid "" "Provides an alternative name for the field. This alternative name is used in " "the synthesized ``__init__`` method." msgstr "" +"Fornece um nome alternativo para o campo. Esse nome alternativo é usado no " +"método ``__init__`` sintetizado." -#: ../../library/typing.rst:2879 +#: ../../library/typing.rst:3012 msgid "" "At runtime, this decorator records its arguments in the " "``__dataclass_transform__`` attribute on the decorated object. It has no " "other runtime effect." msgstr "" +"Em tempo de execução, esse decorador registra seu argumento no atributo " +"``__dataclass_transform__`` no objeto decorado. Ele não tem nenhum outro " +"efeito em tempo de execução." -#: ../../library/typing.rst:2883 +#: ../../library/typing.rst:3016 msgid "See :pep:`681` for more details." msgstr "Veja :pep:`681` para mais detalhes." -#: ../../library/typing.rst:2891 +#: ../../library/typing.rst:3024 msgid "Decorator for creating overloaded functions and methods." -msgstr "" +msgstr "Decorador para criar funções e métodos sobrecarregados." -#: ../../library/typing.rst:2893 +#: ../../library/typing.rst:3026 msgid "" "The ``@overload`` decorator allows describing functions and methods that " "support multiple different combinations of argument types. A series of " "``@overload``-decorated definitions must be followed by exactly one non-" "``@overload``-decorated definition (for the same function/method)." msgstr "" +"O decorador ``@overload`` permite descrever funções e métodos com suporte a " +"várias combinações de tipos de argumento. Uma sequência de definições " +"decoradas com ``@overload`` deve preceder uma única definição não decorada " +"por ``@overload`` (para a mesma função/método)." -#: ../../library/typing.rst:2898 +#: ../../library/typing.rst:3031 msgid "" "``@overload``-decorated definitions are for the benefit of the type checker " "only, since they will be overwritten by the non-``@overload``-decorated " @@ -2861,31 +6160,71 @@ msgid "" "calling an ``@overload``-decorated function directly will raise :exc:" "`NotImplementedError`." msgstr "" +"Definições decoradas com ``@overload`` são usadas somente para benefício do " +"verificador de tipos, já que serão sobrescritas por definições sem decoração " +"de ``@overload``. Enquanto isso, definições sem decoração de ``@overload`` " +"serão usadas em tempo de execução, mas devem ser ignoradas pelo verificador " +"de tipos. Em tempo de execução, chamar uma função decorada por ``@overload`` " +"diretamente levantará :exc:`NotImplementedError`." -#: ../../library/typing.rst:2906 +#: ../../library/typing.rst:3039 msgid "" "An example of overload that gives a more precise type than can be expressed " "using a union or a type variable:" msgstr "" - -#: ../../library/typing.rst:2923 +"Um exemplo de sobrecarga que fornece um tipo mais preciso do que o expressar " +"o tipo expresso por uma união ou um tipo variável:" + +#: ../../library/typing.rst:3042 +msgid "" +"@overload\n" +"def process(response: None) -> None:\n" +" ...\n" +"@overload\n" +"def process(response: int) -> tuple[int, str]:\n" +" ...\n" +"@overload\n" +"def process(response: bytes) -> str:\n" +" ...\n" +"def process(response):\n" +" ... # actual implementation goes here" +msgstr "" +"@overload\n" +"def process(response: None) -> None:\n" +" ...\n" +"@overload\n" +"def process(response: int) -> tuple[int, str]:\n" +" ...\n" +"@overload\n" +"def process(response: bytes) -> str:\n" +" ...\n" +"def process(response):\n" +" ... # a implementação real vem aqui" + +#: ../../library/typing.rst:3056 msgid "" "See :pep:`484` for more details and comparison with other typing semantics." msgstr "" +"Consulte :pep:`484` para mais detalhes e uma comparação com outras " +"semânticas de tipagem." -#: ../../library/typing.rst:2925 +#: ../../library/typing.rst:3058 msgid "" "Overloaded functions can now be introspected at runtime using :func:" "`get_overloads`." msgstr "" +"Funções sobrecarregadas agora podem ser inspecionadas em tempo de execução " +"usando :func:`get_overloads`." -#: ../../library/typing.rst:2932 +#: ../../library/typing.rst:3065 msgid "" "Return a sequence of :func:`@overload `-decorated definitions for " "*func*." msgstr "" +"Retorna uma sequência de definições de *func* decoradas com :func:`@overload " +"`." -#: ../../library/typing.rst:2935 +#: ../../library/typing.rst:3068 msgid "" "*func* is the function object for the implementation of the overloaded " "function. For example, given the definition of ``process`` in the " @@ -2894,33 +6233,73 @@ msgid "" "overloads. If called on a function with no overloads, ``get_overloads()`` " "returns an empty sequence." msgstr "" +"*func* é o objeto função para a implementação da função sobrecarregada. Por " +"exemplo, dada a definição de ``process`` na documentação de :func:`@overload " +"`, ``get_overloads(process)`` retornará uma sequência de três " +"objetos função para as três sobrecargas definidas. Se for chamada em uma " +"função sem sobrecargas, ``get_overloads()`` retornará uma sequência vazia." -#: ../../library/typing.rst:2942 +#: ../../library/typing.rst:3075 msgid "" "``get_overloads()`` can be used for introspecting an overloaded function at " "runtime." msgstr "" +"A função ``get_overloads()`` pode ser usada em tempo de execução para " +"introspecção de uma função sobrecarregada." -#: ../../library/typing.rst:2950 +#: ../../library/typing.rst:3083 msgid "Clear all registered overloads in the internal registry." -msgstr "" +msgstr "Apaga todas as sobrecargas registradas no registro interno." -#: ../../library/typing.rst:2952 +#: ../../library/typing.rst:3085 msgid "This can be used to reclaim the memory used by the registry." -msgstr "" +msgstr "Isso pode ser usado para recuperar a memória usada pelo registro." -#: ../../library/typing.rst:2959 +#: ../../library/typing.rst:3092 msgid "Decorator to indicate final methods and final classes." -msgstr "" +msgstr "Um decorador para indicar métodos e classes finais." -#: ../../library/typing.rst:2961 +#: ../../library/typing.rst:3094 msgid "" "Decorating a method with ``@final`` indicates to a type checker that the " "method cannot be overridden in a subclass. Decorating a class with " "``@final`` indicates that it cannot be subclassed." msgstr "" - -#: ../../library/typing.rst:2986 +"Decorar um método com ``@final`` indica a um verificador de tipos que o " +"método não pode ser substituído em uma subclasse. Decorar uma classe com " +"``@final`` indica que ela não pode ser herdada." + +#: ../../library/typing.rst:3100 +msgid "" +"class Base:\n" +" @final\n" +" def done(self) -> None:\n" +" ...\n" +"class Sub(Base):\n" +" def done(self) -> None: # Error reported by type checker\n" +" ...\n" +"\n" +"@final\n" +"class Leaf:\n" +" ...\n" +"class Other(Leaf): # Error reported by type checker\n" +" ..." +msgstr "" +"class Base:\n" +" @final\n" +" def done(self) -> None:\n" +" ...\n" +"class Sub(Base):\n" +" def done(self) -> None: # Erro reportado pelo verificador de tipos\n" +" ...\n" +"\n" +"@final\n" +"class Leaf:\n" +" ...\n" +"class Other(Leaf): # Erro reportado pelo verificador de tipos\n" +" ..." + +#: ../../library/typing.rst:3119 msgid "" "The decorator will now attempt to set a ``__final__`` attribute to ``True`` " "on the decorated object. Thus, a check like ``if getattr(obj, \"__final__\", " @@ -2929,57 +6308,106 @@ msgid "" "attributes, the decorator returns the object unchanged without raising an " "exception." msgstr "" +"O decorador tentará definir um atributo ``__final__`` como ``True`` no " +"objeto decorado. Assim, uma verificação como ``if getattr(obj, " +"\"__final__\", False)`` pode ser usada em tempo de execução para determinar " +"se um objeto ``obj`` foi marcado como final. Se o objeto decorado não tem " +"suporte a definição de atributos, o decorador retorna o objeto inalterado " +"sem levantar uma exceção." -#: ../../library/typing.rst:2997 +#: ../../library/typing.rst:3130 msgid "Decorator to indicate that annotations are not type hints." -msgstr "" +msgstr "Decorador para indicar que anotações não são dicas de tipo." -#: ../../library/typing.rst:2999 +#: ../../library/typing.rst:3132 msgid "" "This works as a class or function :term:`decorator`. With a class, it " "applies recursively to all methods and classes defined in that class (but " "not to methods defined in its superclasses or subclasses). Type checkers " "will ignore all annotations in a function or class with this decorator." msgstr "" +"Isso funciona como :term:`decorator` de uma classe ou função. Com uma " +"classe, ele se aplica recursivamente a todos os métodos e classes definidos " +"nessa classe (mas não a métodos definidos em suas superclasses ou " +"subclasses). Os verificadores de tipos ignorarão todas as anotações em uma " +"função ou classe com este decorador." -#: ../../library/typing.rst:3005 +#: ../../library/typing.rst:3138 msgid "``@no_type_check`` mutates the decorated object in place." -msgstr "" +msgstr "``@no_type_check`` modifica o objeto decorado internamente." -#: ../../library/typing.rst:3009 +#: ../../library/typing.rst:3142 msgid "Decorator to give another decorator the :func:`no_type_check` effect." -msgstr "" +msgstr "Decorador para dar a outro decorador o efeito :func:`no_type_check`." -#: ../../library/typing.rst:3011 +#: ../../library/typing.rst:3144 msgid "" "This wraps the decorator with something that wraps the decorated function " "in :func:`no_type_check`." msgstr "" +"Isso envolve o decorador com algo que envolve a função decorada em :func:" +"`no_type_check`." -#: ../../library/typing.rst:3014 +#: ../../library/typing.rst:3147 msgid "" "No type checker ever added support for ``@no_type_check_decorator``. It is " "therefore deprecated, and will be removed in Python 3.15." msgstr "" +"Nenhum verificador de tipos jamais adicionou suporte para " +"``@no_type_check_decorator``. Portanto, ele está descontinuado e será " +"removido no Python 3.15." -#: ../../library/typing.rst:3020 +#: ../../library/typing.rst:3153 msgid "" "Decorator to indicate that a method in a subclass is intended to override a " "method or attribute in a superclass." msgstr "" +"Decorador para indicar que um método em uma subclasse deve substituir um " +"método ou atributo em uma superclasse." -#: ../../library/typing.rst:3023 +#: ../../library/typing.rst:3156 msgid "" "Type checkers should emit an error if a method decorated with ``@override`` " "does not, in fact, override anything. This helps prevent bugs that may occur " "when a base class is changed without an equivalent change to a child class." msgstr "" - -#: ../../library/typing.rst:3045 +"Os verificadores de tipo devem emitir um erro se um método decorado com " +"``@override`` substitui nada. Isso ajuda a evitar erros que podem ocorrer " +"quando uma classe base muda sem uma mudança equivalente em uma classe filha." + +#: ../../library/typing.rst:3163 +msgid "" +"class Base:\n" +" def log_status(self) -> None:\n" +" ...\n" +"\n" +"class Sub(Base):\n" +" @override\n" +" def log_status(self) -> None: # Okay: overrides Base.log_status\n" +" ...\n" +"\n" +" @override\n" +" def done(self) -> None: # Error reported by type checker\n" +" ..." +msgstr "" +"class Base:\n" +" def log_status(self) -> None:\n" +" ...\n" +"\n" +"class Sub(Base):\n" +" @override\n" +" def log_status(self) -> None: # OK: substitui Base.log_status\n" +" ...\n" +"\n" +" @override\n" +" def done(self) -> None: # Erro reportado pelo verificador de tipos\n" +" ..." + +#: ../../library/typing.rst:3178 msgid "There is no runtime checking of this property." -msgstr "" +msgstr "Não há verificação desta propriedade em tempo de execução." -#: ../../library/typing.rst:3047 +#: ../../library/typing.rst:3180 msgid "" "The decorator will attempt to set an ``__override__`` attribute to ``True`` " "on the decorated object. Thus, a check like ``if getattr(obj, " @@ -2988,45 +6416,78 @@ msgid "" "not support setting attributes, the decorator returns the object unchanged " "without raising an exception." msgstr "" +"O decorador tentará definir um atributo ``__override__`` como ``True`` no " +"objeto decorado. Assim, uma verificação como ``if getattr(obj, " +"\"__override__\", False)`` poderá ser usada em tempo de execução para " +"determinar se um objeto ``obj`` foi marcado como uma substituição. Se o " +"objeto decorado não der suporte à atribuição de atributos, o decorador " +"retorna o objeto inalterado sem levantar uma exceção." -#: ../../library/typing.rst:3054 +#: ../../library/typing.rst:3187 msgid "See :pep:`698` for more details." msgstr "Consulte :pep:`698` para obter mais detalhes." -#: ../../library/typing.rst:3061 +#: ../../library/typing.rst:3194 msgid "Decorator to mark a class or function as unavailable at runtime." msgstr "" +"Decorador para marcar uma classe ou função como indisponível em tempo de " +"execução." -#: ../../library/typing.rst:3063 +#: ../../library/typing.rst:3196 msgid "" "This decorator is itself not available at runtime. It is mainly intended to " "mark classes that are defined in type stub files if an implementation " "returns an instance of a private class::" msgstr "" +"Este decorador em si não está disponível em tempo de execução. Seu objetivo " +"principal é marcar classes definidas em arquivos de tipo stub se uma " +"implementação retornar uma instância de uma classe privada:" + +#: ../../library/typing.rst:3200 +msgid "" +"@type_check_only\n" +"class Response: # private or not available at runtime\n" +" code: int\n" +" def get_header(self, name: str) -> str: ...\n" +"\n" +"def fetch_response() -> Response: ..." +msgstr "" +"@type_check_only\n" +"class Response: # privado ou indisponível em tempo de execução\n" +" code: int\n" +" def get_header(self, name: str) -> str: ...\n" +"\n" +"def fetch_response() -> Response: ..." -#: ../../library/typing.rst:3074 +#: ../../library/typing.rst:3207 msgid "" "Note that returning instances of private classes is not recommended. It is " "usually preferable to make such classes public." msgstr "" +"Observe que retornar instâncias de classes privadas não é recomendado. " +"Normalmente, é preferível tornar essas classes públicas." -#: ../../library/typing.rst:3078 +#: ../../library/typing.rst:3211 msgid "Introspection helpers" -msgstr "" +msgstr "Auxiliares de introspecção" -#: ../../library/typing.rst:3082 +#: ../../library/typing.rst:3215 msgid "" "Return a dictionary containing type hints for a function, method, module or " "class object." msgstr "" +"Retorna um dicionário contendo dicas de tipo para uma função, método, módulo " +"ou objeto classe." -#: ../../library/typing.rst:3085 +#: ../../library/typing.rst:3218 msgid "" "This is often the same as ``obj.__annotations__``, but this function makes " "the following changes to the annotations dictionary:" msgstr "" +"Geralmente é o mesmo que ``obj.__annotations__``, mas esta função faz as " +"seguintes alterações no dicionário de anotações:" -#: ../../library/typing.rst:3088 +#: ../../library/typing.rst:3221 msgid "" "Forward references encoded as string literals or :class:`ForwardRef` objects " "are handled by evaluating them in *globalns*, *localns*, and (where " @@ -3034,41 +6495,60 @@ msgid "" "*globalns* or *localns* is not given, appropriate namespace dictionaries are " "inferred from *obj*." msgstr "" +"Referências futuras codificadas como literais de string ou objetos :class:" +"`ForwardRef` são tratados avaliando-as em *globalns*, *localns* e (quando " +"aplicável) no espaço de nomes de :ref:`parâmetro de tipo ` de " +"*obj*. Se *globalns* ou *localns* não forem fornecidos, os dicionários de " +"espaço de nomes apropriados serão inferidos de *obj*." -#: ../../library/typing.rst:3093 +#: ../../library/typing.rst:3226 msgid "``None`` is replaced with :class:`types.NoneType`." -msgstr "" +msgstr "``None`` é substituído por :class:`types.NoneType`." -#: ../../library/typing.rst:3094 +#: ../../library/typing.rst:3227 msgid "" "If :func:`@no_type_check ` has been applied to *obj*, an " "empty dictionary is returned." msgstr "" +"Se :func:`@no_type_check ` tiver sido aplicada a *obj*, será " +"retornado um dicionário vazio." -#: ../../library/typing.rst:3096 +#: ../../library/typing.rst:3229 msgid "" "If *obj* is a class ``C``, the function returns a dictionary that merges " "annotations from ``C``'s base classes with those on ``C`` directly. This is " -"done by traversing ``C.__mro__`` and iteratively combining " -"``__annotations__`` dictionaries. Annotations on classes appearing earlier " -"in the :term:`method resolution order` always take precedence over " +"done by traversing :attr:`C.__mro__ ` and iteratively " +"combining ``__annotations__`` dictionaries. Annotations on classes appearing " +"earlier in the :term:`method resolution order` always take precedence over " "annotations on classes appearing later in the method resolution order." msgstr "" +"Se *obj* for uma classe ``C``, a função retorna um dicionário que mescla " +"anotações das classes base de ``C`` com as de ``C`` diretamente. Isso é " +"feito percorrendo :attr:`C.__mro__ ` e combinando " +"iterativamente os dicionários ``__annotations__``. Anotações em classes que " +"aparecem antes na :term:`ordem de resolução de métodos` sempre tem " +"precedência sobre anotações em classes que aparecem depois no ordem de " +"resolução de métodos." -#: ../../library/typing.rst:3102 +#: ../../library/typing.rst:3236 msgid "" "The function recursively replaces all occurrences of ``Annotated[T, ...]`` " "with ``T``, unless *include_extras* is set to ``True`` (see :class:" "`Annotated` for more information)." msgstr "" +"A função substitui recursivamente todas as ocorrências de " +"``Annotated[T, ...]`` por ``T``, a menos que *include_extras* seja definido " +"como ``True`` (consulte :class:`Annotated` para obter mais informações)." -#: ../../library/typing.rst:3106 +#: ../../library/typing.rst:3240 msgid "" "See also :func:`inspect.get_annotations`, a lower-level function that " "returns annotations more directly." msgstr "" +"Veja também :func:`inspect.get_annotations`, uma função de nível mais baixo " +"que retorna anotações mais diretamente." -#: ../../library/typing.rst:3111 +#: ../../library/typing.rst:3245 msgid "" "If any forward references in the annotations of *obj* are not resolvable or " "are not valid Python code, this function will raise an exception such as :" @@ -3076,860 +6556,1124 @@ msgid "" "aliases ` that include forward references, or with names " "imported under :data:`if TYPE_CHECKING `." msgstr "" +"Se alguma referência futura nas anotações de *obj* não for resolvível ou não " +"for código Python válido, esta função levantará uma exceção como :exc:" +"`NameError`. Por exemplo, isso pode acontecer com :ref:`apelidos de tipo " +"` importados que incluem referências futuras, ou com nomes " +"importados em :data:`if TYPE_CHECKING `." -#: ../../library/typing.rst:3117 +#: ../../library/typing.rst:3251 msgid "" "Added ``include_extras`` parameter as part of :pep:`593`. See the " "documentation on :data:`Annotated` for more information." msgstr "" +"Adiciona o parâmetro ``include_extras`` como parte da :pep:`593`. Consulte a " +"documentação em :data:`Annotated` para mais informações." -#: ../../library/typing.rst:3121 +#: ../../library/typing.rst:3255 msgid "" "Previously, ``Optional[t]`` was added for function and method annotations if " "a default value equal to ``None`` was set. Now the annotation is returned " "unchanged." msgstr "" +"Anteriormente, ``Optional[t]`` era adicionado a anotações de funções e " +"métodos se um valor padrão igual a ``None`` fosse definido. Agora, a " +"anotação é retornada inalterada." -#: ../../library/typing.rst:3128 +#: ../../library/typing.rst:3262 msgid "" "Get the unsubscripted version of a type: for a typing object of the form " "``X[Y, Z, ...]`` return ``X``." msgstr "" +"Obtenha o versão sem subscrição de um tipo: para um objeto cujo tipo tem a " +"forma ``X[Y, Z, ...]``, retorna ``X`` ." -#: ../../library/typing.rst:3131 +#: ../../library/typing.rst:3265 msgid "" "If ``X`` is a typing-module alias for a builtin or :mod:`collections` class, " "it will be normalized to the original class. If ``X`` is an instance of :" "class:`ParamSpecArgs` or :class:`ParamSpecKwargs`, return the underlying :" "class:`ParamSpec`. Return ``None`` for unsupported objects." msgstr "" +"Se ``X`` for um apelido do módulo typing para uma classe embutida ou classe " +"de :mod:`collections`, ele será normalizado para a classe original. Se ``X`` " +"for uma instância de :class:`ParamSpecArgs` ou :class:`ParamSpecKwargs`, " +"retorna o :class:`ParamSpec` subjacente. Retorna ``None`` para objetos " +"incompatíveis." -#: ../../library/typing.rst:3137 ../../library/typing.rst:3160 +#: ../../library/typing.rst:3271 ../../library/typing.rst:3295 msgid "Examples:" msgstr "Exemplos:" -#: ../../library/typing.rst:3152 +#: ../../library/typing.rst:3273 +msgid "" +"assert get_origin(str) is None\n" +"assert get_origin(Dict[str, int]) is dict\n" +"assert get_origin(Union[int, str]) is Union\n" +"assert get_origin(Annotated[str, \"metadata\"]) is Annotated\n" +"P = ParamSpec('P')\n" +"assert get_origin(P.args) is P\n" +"assert get_origin(P.kwargs) is P" +msgstr "" +"assert get_origin(str) is None\n" +"assert get_origin(Dict[str, int]) is dict\n" +"assert get_origin(Union[int, str]) is Union\n" +"assert get_origin(Annotated[str, \"metadata\"]) is Annotated\n" +"P = ParamSpec('P')\n" +"assert get_origin(P.args) is P\n" +"assert get_origin(P.kwargs) is P" + +#: ../../library/typing.rst:3287 msgid "" "Get type arguments with all substitutions performed: for a typing object of " "the form ``X[Y, Z, ...]`` return ``(Y, Z, ...)``." msgstr "" +"Obtenha os argumentos de tipos com todas as substituições realizadas: para " +"um objeto cujo tipo tem a forma ``X[Y, Z, ...]``, retorna ``(Y, Z, ...)`` ." -#: ../../library/typing.rst:3155 +#: ../../library/typing.rst:3290 msgid "" "If ``X`` is a union or :class:`Literal` contained in another generic type, " "the order of ``(Y, Z, ...)`` may be different from the order of the original " "arguments ``[Y, Z, ...]`` due to type caching. Return ``()`` for unsupported " "objects." msgstr "" +"Se ``X`` for uma união ou um :class:`Literal`, e estiver contido em outro " +"tipo genérico, a ordem de ``(Y, Z, ...)`` poderá ser diferente da ordem dos " +"argumentos originais ``[Y, Z, ...]`` devido ao armazenamento dos tipos em " +"cache. Retorna ``()`` para objetos sem suporte." -#: ../../library/typing.rst:3172 +#: ../../library/typing.rst:3297 +msgid "" +"assert get_args(int) == ()\n" +"assert get_args(Dict[int, str]) == (int, str)\n" +"assert get_args(Union[int, str]) == (int, str)" +msgstr "" +"assert get_args(int) == ()\n" +"assert get_args(Dict[int, str]) == (int, str)\n" +"assert get_args(Union[int, str]) == (int, str)" + +#: ../../library/typing.rst:3307 msgid "Return the set of members defined in a :class:`Protocol`." +msgstr "Retorna o conjunto de membros definidos em um :class:`Protocol`." + +#: ../../library/typing.rst:3309 +msgid "" +">>> from typing import Protocol, get_protocol_members\n" +">>> class P(Protocol):\n" +"... def a(self) -> str: ...\n" +"... b: int\n" +">>> get_protocol_members(P) == frozenset({'a', 'b'})\n" +"True" msgstr "" +">>> from typing import Protocol, get_protocol_members\n" +">>> class P(Protocol):\n" +"... def a(self) -> str: ...\n" +"... b: int\n" +">>> get_protocol_members(P) == frozenset({'a', 'b'})\n" +"True" -#: ../../library/typing.rst:3183 +#: ../../library/typing.rst:3318 msgid "Raise :exc:`TypeError` for arguments that are not Protocols." -msgstr "" +msgstr "Levanta :exc:`TypeError` para argumentos que não são protocolos." -#: ../../library/typing.rst:3189 +#: ../../library/typing.rst:3324 msgid "Determine if a type is a :class:`Protocol`." -msgstr "" +msgstr "Determina se um tipo é um :class:`Protocol`." -#: ../../library/typing.rst:3204 -msgid "Check if a type is a :class:`TypedDict`." +#: ../../library/typing.rst:3328 +msgid "" +"class P(Protocol):\n" +" def a(self) -> str: ...\n" +" b: int\n" +"\n" +"is_protocol(P) # => True\n" +"is_protocol(int) # => False" msgstr "" +"class P(Protocol):\n" +" def a(self) -> str: ...\n" +" b: int\n" +"\n" +"is_protocol(P) # => True\n" +"is_protocol(int) # => False" -#: ../../library/typing.rst:3225 +#: ../../library/typing.rst:3339 +msgid "Check if a type is a :class:`TypedDict`." +msgstr "Verifica se um tipo é um :class:`TypedDict`." + +#: ../../library/typing.rst:3343 +msgid "" +"class Film(TypedDict):\n" +" title: str\n" +" year: int\n" +"\n" +"assert is_typeddict(Film)\n" +"assert not is_typeddict(list | str)\n" +"\n" +"# TypedDict is a factory for creating typed dicts,\n" +"# not a typed dict itself\n" +"assert not is_typeddict(TypedDict)" +msgstr "" +"class Film(TypedDict):\n" +" title: str\n" +" year: int\n" +"\n" +"assert is_typeddict(Film)\n" +"assert not is_typeddict(list | str)\n" +"\n" +"# TypedDict é uma fábrica para criar dicionários tipados\n" +"# e não um dicionário tipado em si.\n" +"assert not is_typeddict(TypedDict)" + +#: ../../library/typing.rst:3360 msgid "" "Class used for internal typing representation of string forward references." msgstr "" +"Classe usada para representação de tipagem interna de referências futuras " +"como strings." -#: ../../library/typing.rst:3227 +#: ../../library/typing.rst:3362 msgid "" "For example, ``List[\"SomeClass\"]`` is implicitly transformed into " "``List[ForwardRef(\"SomeClass\")]``. ``ForwardRef`` should not be " "instantiated by a user, but may be used by introspection tools." msgstr "" +"Por exemplo, o tipo ``List[\"SomeClass\"]`` é implicitamente transformado em " +"``List[ForwardRef(\"SomeClass\")]``. ``ForwardRef`` não deve ser instanciado " +"por um usuário, mas pode ser usado por ferramentas de introspecção." -#: ../../library/typing.rst:3232 +#: ../../library/typing.rst:3367 msgid "" ":pep:`585` generic types such as ``list[\"SomeClass\"]`` will not be " "implicitly transformed into ``list[ForwardRef(\"SomeClass\")]`` and thus " "will not automatically resolve to ``list[SomeClass]``." msgstr "" +"Tipos genéricos da :pep:`585` como ``list[\"SomeClass\"]`` não serão " +"transformados implicitamente em ``list[ForwardRef(\"SomeClass\")]`` e, " +"portanto, não serão resolvidos automaticamente para ``list[SomeClass]``." -#: ../../library/typing.rst:3240 +#: ../../library/typing.rst:3375 msgid "" "A sentinel object used to indicate that a type parameter has no default " "value. For example:" msgstr "" +"Um objeto sinalizador usado para indicar que um parâmetro de tipo não possui " +"valor-padrão. Por exemplo::" -#: ../../library/typing.rst:3255 +#: ../../library/typing.rst:3378 +msgid "" +">>> T = TypeVar(\"T\")\n" +">>> T.__default__ is typing.NoDefault\n" +"True\n" +">>> S = TypeVar(\"S\", default=None)\n" +">>> S.__default__ is None\n" +"True" +msgstr "" +">>> T = TypeVar(\"T\")\n" +">>> T.__default__ is typing.NoDefault\n" +"True\n" +">>> S = TypeVar(\"S\", default=None)\n" +">>> S.__default__ is None\n" +"True" + +#: ../../library/typing.rst:3390 msgid "Constant" msgstr "Constante" -#: ../../library/typing.rst:3259 +#: ../../library/typing.rst:3394 msgid "" "A special constant that is assumed to be ``True`` by 3rd party static type " "checkers. It is ``False`` at runtime." msgstr "" +"Uma constante especial presumida ser ``True`` por verificadores de tipo " +"estático de terceiros. É ``False`` em tempo de execução." -#: ../../library/typing.rst:3270 +#: ../../library/typing.rst:3399 +msgid "" +"if TYPE_CHECKING:\n" +" import expensive_mod\n" +"\n" +"def fun(arg: 'expensive_mod.SomeType') -> None:\n" +" local_var: expensive_mod.AnotherType = other_fun()" +msgstr "" +"if TYPE_CHECKING:\n" +" import expensive_mod\n" +"\n" +"def fun(arg: 'expensive_mod.SomeType') -> None:\n" +" local_var: expensive_mod.AnotherType = other_fun()" + +#: ../../library/typing.rst:3405 msgid "" "The first type annotation must be enclosed in quotes, making it a \"forward " "reference\", to hide the ``expensive_mod`` reference from the interpreter " "runtime. Type annotations for local variables are not evaluated, so the " "second annotation does not need to be enclosed in quotes." msgstr "" +"A primeira anotação de tipo deve ser colocada entre aspas, tornando-a uma " +"\"referência futura\", para esconder do interpretador a referência ao módulo " +"``expensive_mod``. As anotações de tipos em variáveis locais não são " +"avaliadas, então a segunda anotação não precisa ser colocada entre aspas." -#: ../../library/typing.rst:3277 +#: ../../library/typing.rst:3412 msgid "" "If ``from __future__ import annotations`` is used, annotations are not " "evaluated at function definition time. Instead, they are stored as strings " "in ``__annotations__``. This makes it unnecessary to use quotes around the " "annotation (see :pep:`563`)." msgstr "" +"Se ``from __future__ import annotations`` for usado, anotações não serão " +"avaliadas no momento de definição de funções. Em vez disso, elas são " +"armazenadas como string em ``__annotations__``. Isso torna desnecessário o " +"uso de aspas em anotações (consulte :pep:`563`)." -#: ../../library/typing.rst:3289 +#: ../../library/typing.rst:3424 msgid "Deprecated aliases" -msgstr "" +msgstr "Apelidos descontinuados" -#: ../../library/typing.rst:3291 +#: ../../library/typing.rst:3426 msgid "" "This module defines several deprecated aliases to pre-existing standard " -"library classes. These were originally included in the typing module in " -"order to support parameterizing these generic classes using ``[]``. However, " -"the aliases became redundant in Python 3.9 when the corresponding pre-" -"existing classes were enhanced to support ``[]`` (see :pep:`585`)." +"library classes. These were originally included in the :mod:`!typing` module " +"in order to support parameterizing these generic classes using ``[]``. " +"However, the aliases became redundant in Python 3.9 when the corresponding " +"pre-existing classes were enhanced to support ``[]`` (see :pep:`585`)." msgstr "" +"Este módulo define vários apelidos descontinuados de classes pré-existentes " +"da biblioteca padrão. Originalmente, elas eram incluídas no módulo :mod:`!" +"typing` para permitir a parametrização dessas classes genéricas usando " +"``[]``. Porém, os apelidos se tornaram redundantes no Python 3.9, quando as " +"classes pré-existentes correspondentes passaram a dar suporte a ``[]`` " +"(consulte a :pep:`585`)." -#: ../../library/typing.rst:3298 +#: ../../library/typing.rst:3433 msgid "" "The redundant types are deprecated as of Python 3.9. However, while the " "aliases may be removed at some point, removal of these aliases is not " "currently planned. As such, no deprecation warnings are currently issued by " "the interpreter for these aliases." msgstr "" +"Os tipos redundantes estão descontinuados desde Python 3.9. No entanto, " +"enquanto os apelidos podem ser removidos em algum momento, essa remoção " +"desses apelidos não está planejada. Assim, nenhum aviso de descontinuação " +"será enviado pelo interpretador para esses apelidos." -#: ../../library/typing.rst:3303 +#: ../../library/typing.rst:3438 msgid "" "If at some point it is decided to remove these deprecated aliases, a " "deprecation warning will be issued by the interpreter for at least two " -"releases prior to removal. The aliases are guaranteed to remain in the " -"typing module without deprecation warnings until at least Python 3.14." +"releases prior to removal. The aliases are guaranteed to remain in the :mod:" +"`!typing` module without deprecation warnings until at least Python 3.14." msgstr "" +"Se em algum momento decidirem remover esses apelidos descontinuados, o " +"interpretador emitirá um aviso de descontinuação por, no mínimo, duas " +"versões de lançamento antes da remoção. Os apelidos são garantidos a " +"permanecerem no módulo :mod:`!typing` sem avisos de descontinuação até, no " +"mínimo, Python 3.14." -#: ../../library/typing.rst:3308 +#: ../../library/typing.rst:3443 msgid "" "Type checkers are encouraged to flag uses of the deprecated types if the " "program they are checking targets a minimum Python version of 3.9 or newer." msgstr "" +"Verificadores de tipos são encorajados a sinalizar o uso de tipos " +"descontinuados se o programa que estão verificando respeita uma versão " +"mínima de Python 3.9 ou mais nova." -#: ../../library/typing.rst:3314 +#: ../../library/typing.rst:3449 msgid "Aliases to built-in types" -msgstr "" +msgstr "Apelidos de tipos embutidos" -#: ../../library/typing.rst:3318 +#: ../../library/typing.rst:3453 msgid "Deprecated alias to :class:`dict`." -msgstr "" +msgstr "Apelido descontinuado de :class:`dict`." -#: ../../library/typing.rst:3320 +#: ../../library/typing.rst:3455 msgid "" "Note that to annotate arguments, it is preferred to use an abstract " -"collection type such as :class:`Mapping` rather than to use :class:`dict` " -"or :class:`!typing.Dict`." +"collection type such as :class:`~collections.abc.Mapping` rather than to " +"use :class:`dict` or :class:`!typing.Dict`." msgstr "" +"Note que, para anotar argumentos, prefere-se usar um tipo de coleção " +"abstrata como :class:`~collections.abc.Mapping` em vez de :class:`dict` ou :" +"class:`!typing.Dict`." -#: ../../library/typing.rst:3324 ../../library/typing.rst:3555 -msgid "This type can be used as follows::" -msgstr "" - -#: ../../library/typing.rst:3329 +#: ../../library/typing.rst:3459 msgid "" ":class:`builtins.dict ` now supports subscripting (``[]``). See :pep:" "`585` and :ref:`types-genericalias`." msgstr "" +":class:`builtins.dict ` agora oferece suporte a subscrição (``[]``). " +"Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3335 +#: ../../library/typing.rst:3465 msgid "Deprecated alias to :class:`list`." -msgstr "" +msgstr "Apelido descontinuado de :class:`list`." -#: ../../library/typing.rst:3337 +#: ../../library/typing.rst:3467 msgid "" "Note that to annotate arguments, it is preferred to use an abstract " -"collection type such as :class:`Sequence` or :class:`Iterable` rather than " -"to use :class:`list` or :class:`!typing.List`." -msgstr "" - -#: ../../library/typing.rst:3341 -msgid "This type may be used as follows::" +"collection type such as :class:`~collections.abc.Sequence` or :class:" +"`~collections.abc.Iterable` rather than to use :class:`list` or :class:`!" +"typing.List`." msgstr "" +"Note que, para anotar argumentos, é preferível usar um tipo de coleção " +"abstrata, como :class:`~collections.abc.Sequence` ou :class:`~collections." +"abc.Iterable`, em vez de :class:`list` ou :class:`!typing.List`." -#: ../../library/typing.rst:3349 +#: ../../library/typing.rst:3472 msgid "" ":class:`builtins.list ` now supports subscripting (``[]``). See :pep:" "`585` and :ref:`types-genericalias`." msgstr "" +":class:`builtins.list ` agora oferece suporte a subscrição (``[]``). " +"Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3355 +#: ../../library/typing.rst:3478 msgid "Deprecated alias to :class:`builtins.set `." -msgstr "" +msgstr "Apelido descontinuado de :class:`builtins.set `." -#: ../../library/typing.rst:3357 +#: ../../library/typing.rst:3480 msgid "" "Note that to annotate arguments, it is preferred to use an abstract " -"collection type such as :class:`AbstractSet` rather than to use :class:`set` " -"or :class:`!typing.Set`." +"collection type such as :class:`collections.abc.Set` rather than to use :" +"class:`set` or :class:`typing.Set`." msgstr "" +"Note que, para anotar argumentos, prefere-se usar um tipo de coleção " +"abstrata como :class:`collections.abc.Set` em vez de :class:`set` ou :class:" +"`typing.Set`." -#: ../../library/typing.rst:3361 +#: ../../library/typing.rst:3484 msgid "" ":class:`builtins.set ` now supports subscripting (``[]``). See :pep:" "`585` and :ref:`types-genericalias`." msgstr "" +":class:`builtins.set ` agora oferece suporte a subscrição (``[]``). " +"Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3367 +#: ../../library/typing.rst:3490 msgid "Deprecated alias to :class:`builtins.frozenset `." -msgstr "" +msgstr "Apelido descontinuado de :class:`builtins.frozenset `." -#: ../../library/typing.rst:3369 +#: ../../library/typing.rst:3492 msgid "" ":class:`builtins.frozenset ` now supports subscripting (``[]``). " "See :pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`builtins.frozenset ` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3376 +#: ../../library/typing.rst:3499 msgid "Deprecated alias for :class:`tuple`." -msgstr "" +msgstr "Apelido descontinuado para :class:`tuple`." -#: ../../library/typing.rst:3378 +#: ../../library/typing.rst:3501 msgid "" ":class:`tuple` and ``Tuple`` are special-cased in the type system; see :ref:" "`annotating-tuples` for more details." msgstr "" +":class:`tuple` e ``Tuple`` são casos especiais no sistema de tipos; " +"consulte :ref:`annotating-tuples` para obter mais detalhes." -#: ../../library/typing.rst:3381 +#: ../../library/typing.rst:3504 msgid "" ":class:`builtins.tuple ` now supports subscripting (``[]``). See :pep:" "`585` and :ref:`types-genericalias`." msgstr "" +":class:`builtins.tuple ` agora oferece suporte a subscrição (``[]``). " +"Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3387 +#: ../../library/typing.rst:3510 msgid "Deprecated alias to :class:`type`." -msgstr "" +msgstr "Apelido descontinuado de :class:`type`." -#: ../../library/typing.rst:3389 +#: ../../library/typing.rst:3512 msgid "" "See :ref:`type-of-class-objects` for details on using :class:`type` or " "``typing.Type`` in type annotations." msgstr "" +"Consulte :ref:`type-of-class-objects` para obter detalhes sobre como usar :" +"class:`type` ou ``typing.Type`` em anotações de tipos." -#: ../../library/typing.rst:3394 +#: ../../library/typing.rst:3517 msgid "" ":class:`builtins.type ` now supports subscripting (``[]``). See :pep:" "`585` and :ref:`types-genericalias`." msgstr "" +":class:`builtins.type ` agora oferece suporte a subscrição (``[]``). " +"Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3401 +#: ../../library/typing.rst:3524 msgid "Aliases to types in :mod:`collections`" -msgstr "" +msgstr "Apelidos para tipos em :mod:`collections`" -#: ../../library/typing.rst:3405 +#: ../../library/typing.rst:3528 msgid "Deprecated alias to :class:`collections.defaultdict`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.defaultdict`." -#: ../../library/typing.rst:3409 +#: ../../library/typing.rst:3532 msgid "" ":class:`collections.defaultdict` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.defaultdict` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3415 +#: ../../library/typing.rst:3538 msgid "Deprecated alias to :class:`collections.OrderedDict`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.OrderedDict`." -#: ../../library/typing.rst:3419 +#: ../../library/typing.rst:3542 msgid "" ":class:`collections.OrderedDict` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.OrderedDict` agora oferece suporte a subscrição " +"(``[]``). consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3425 +#: ../../library/typing.rst:3548 msgid "Deprecated alias to :class:`collections.ChainMap`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.ChainMap`." -#: ../../library/typing.rst:3429 +#: ../../library/typing.rst:3552 msgid "" ":class:`collections.ChainMap` now supports subscripting (``[]``). See :pep:" "`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.ChainMap` agora oferece suporte a subscrição (``[]``). " +"consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3435 +#: ../../library/typing.rst:3558 msgid "Deprecated alias to :class:`collections.Counter`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.Counter`." -#: ../../library/typing.rst:3439 +#: ../../library/typing.rst:3562 msgid "" ":class:`collections.Counter` now supports subscripting (``[]``). See :pep:" "`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.Counter` agora oferece suporte a subscrição (``[]``). " +"consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3445 +#: ../../library/typing.rst:3568 msgid "Deprecated alias to :class:`collections.deque`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.deque`." -#: ../../library/typing.rst:3449 +#: ../../library/typing.rst:3572 msgid "" ":class:`collections.deque` now supports subscripting (``[]``). See :pep:" "`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.deque` agora oferece suporte a subscrição (``[]``). " +"Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3456 +#: ../../library/typing.rst:3579 msgid "Aliases to other concrete types" -msgstr "" +msgstr "Apelidos de outros tipos concretos" -#: ../../library/typing.rst:3461 +#: ../../library/typing.rst:3584 msgid "" "Deprecated aliases corresponding to the return types from :func:`re.compile` " "and :func:`re.match`." msgstr "" +"Apelidos descontinuados correspondem aos tipos de retorno de :func:`re." +"compile` e :func:`re.match`." -#: ../../library/typing.rst:3464 +#: ../../library/typing.rst:3587 msgid "" "These types (and the corresponding functions) are generic over :data:" "`AnyStr`. ``Pattern`` can be specialised as ``Pattern[str]`` or " "``Pattern[bytes]``; ``Match`` can be specialised as ``Match[str]`` or " "``Match[bytes]``." msgstr "" +"Esses tipos (e as funções correspondentes) são genéricas sobre :data:" +"`AnyStr`. ``Pattern`` pode ser especializado como ``Pattern[str]`` ou " +"``Pattern[bytes]``; ``Match`` pode ser especializado como ``Match[str]`` ou " +"``Match[bytes]``." -#: ../../library/typing.rst:3469 +#: ../../library/typing.rst:3592 msgid "" "Classes ``Pattern`` and ``Match`` from :mod:`re` now support ``[]``. See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +"Classes ``Pattern`` e ``Match`` de :mod:`re` agora suporte ``[]``. Consulte :" +"pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3475 +#: ../../library/typing.rst:3598 msgid "Deprecated alias for :class:`str`." -msgstr "" +msgstr "Apelido descontinuado de :class:`str`." -#: ../../library/typing.rst:3477 +#: ../../library/typing.rst:3600 msgid "" "``Text`` is provided to supply a forward compatible path for Python 2 code: " "in Python 2, ``Text`` is an alias for ``unicode``." msgstr "" +"``Text`` é fornecida para servir como um caminho compatível com versões " +"futuras para código em Python 2: no Python 2, ``Text`` é um apelido para " +"``unicode``." -#: ../../library/typing.rst:3481 +#: ../../library/typing.rst:3604 msgid "" "Use ``Text`` to indicate that a value must contain a unicode string in a " "manner that is compatible with both Python 2 and Python 3::" msgstr "" +"Use ``Text`` para indicar que um valor deve conter uma string unicode de " +"forma compatível com Python 2 e Python 3::" + +#: ../../library/typing.rst:3607 +msgid "" +"def add_unicode_checkmark(text: Text) -> Text:\n" +" return text + u' \\u2713'" +msgstr "" +"def add_unicode_checkmark(text: Text) -> Text:\n" +" return text + u' \\u2713'" -#: ../../library/typing.rst:3489 +#: ../../library/typing.rst:3612 msgid "" "Python 2 is no longer supported, and most type checkers also no longer " "support type checking Python 2 code. Removal of the alias is not currently " "planned, but users are encouraged to use :class:`str` instead of ``Text``." msgstr "" +"Python 2 deixou de receber suporte, e a maioria dos verificadores de tipos " +"também não oferece suporte à verificação de tipos de código de Python 2. A " +"remoção do apelido não está planejada no momento, mas os usuários são " +"incentivados a usar :class:`str` em vez de ``Text``." -#: ../../library/typing.rst:3499 +#: ../../library/typing.rst:3622 msgid "Aliases to container ABCs in :mod:`collections.abc`" -msgstr "" +msgstr "Apelidos de contêineres ABC em :mod:`collections.abc`." -#: ../../library/typing.rst:3503 +#: ../../library/typing.rst:3626 msgid "Deprecated alias to :class:`collections.abc.Set`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.Set`." -#: ../../library/typing.rst:3505 +#: ../../library/typing.rst:3628 msgid "" ":class:`collections.abc.Set` now supports subscripting (``[]``). See :pep:" "`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.Set` agora oferece suporte a subscrição (``[]``). " +"Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3511 +#: ../../library/typing.rst:3634 msgid "" "This type represents the types :class:`bytes`, :class:`bytearray`, and :" "class:`memoryview` of byte sequences." msgstr "" +"Este tipo representa os tipos :class:`bytes`, :class:`bytearray` e :class:" +"`memoryview` de sequências de bytes." -#: ../../library/typing.rst:3514 +#: ../../library/typing.rst:3637 msgid "" "Prefer :class:`collections.abc.Buffer`, or a union like ``bytes | bytearray " "| memoryview``." msgstr "" +"Prefira :class:`collections.abc.Buffer`, ou uma união como ``bytes | " +"bytearray | memoryview``." -#: ../../library/typing.rst:3519 +#: ../../library/typing.rst:3642 msgid "Deprecated alias to :class:`collections.abc.Collection`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.Collection`." -#: ../../library/typing.rst:3523 +#: ../../library/typing.rst:3646 msgid "" ":class:`collections.abc.Collection` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.Collection` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3529 +#: ../../library/typing.rst:3652 msgid "Deprecated alias to :class:`collections.abc.Container`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.Container`." -#: ../../library/typing.rst:3531 +#: ../../library/typing.rst:3654 msgid "" ":class:`collections.abc.Container` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.Container` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3537 +#: ../../library/typing.rst:3660 msgid "Deprecated alias to :class:`collections.abc.ItemsView`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.ItemsView`." -#: ../../library/typing.rst:3539 +#: ../../library/typing.rst:3662 msgid "" ":class:`collections.abc.ItemsView` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.ItemsView` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3545 +#: ../../library/typing.rst:3668 msgid "Deprecated alias to :class:`collections.abc.KeysView`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.KeysView`." -#: ../../library/typing.rst:3547 +#: ../../library/typing.rst:3670 msgid "" ":class:`collections.abc.KeysView` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.KeysView` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3553 +#: ../../library/typing.rst:3676 msgid "Deprecated alias to :class:`collections.abc.Mapping`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.Mapping`." -#: ../../library/typing.rst:3560 +#: ../../library/typing.rst:3678 msgid "" ":class:`collections.abc.Mapping` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.Mapping` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3566 +#: ../../library/typing.rst:3684 msgid "Deprecated alias to :class:`collections.abc.MappingView`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.MappingView`." -#: ../../library/typing.rst:3568 +#: ../../library/typing.rst:3686 msgid "" ":class:`collections.abc.MappingView` now supports subscripting (``[]``). " "See :pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.MappingView` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3574 +#: ../../library/typing.rst:3692 msgid "Deprecated alias to :class:`collections.abc.MutableMapping`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.MutableMapping`." -#: ../../library/typing.rst:3576 +#: ../../library/typing.rst:3694 msgid "" ":class:`collections.abc.MutableMapping` now supports subscripting (``[]``). " "See :pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.MutableMapping` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3583 +#: ../../library/typing.rst:3701 msgid "Deprecated alias to :class:`collections.abc.MutableSequence`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.MutableSequence`." -#: ../../library/typing.rst:3585 +#: ../../library/typing.rst:3703 msgid "" ":class:`collections.abc.MutableSequence` now supports subscripting (``[]``). " "See :pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.MutableSequence` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3592 +#: ../../library/typing.rst:3710 msgid "Deprecated alias to :class:`collections.abc.MutableSet`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.MutableSet`." -#: ../../library/typing.rst:3594 +#: ../../library/typing.rst:3712 msgid "" ":class:`collections.abc.MutableSet` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.MutableSet` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3600 +#: ../../library/typing.rst:3718 msgid "Deprecated alias to :class:`collections.abc.Sequence`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.Sequence`." -#: ../../library/typing.rst:3602 +#: ../../library/typing.rst:3720 msgid "" ":class:`collections.abc.Sequence` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.Sequence` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3608 +#: ../../library/typing.rst:3726 msgid "Deprecated alias to :class:`collections.abc.ValuesView`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.ValuesView`." -#: ../../library/typing.rst:3610 +#: ../../library/typing.rst:3728 msgid "" ":class:`collections.abc.ValuesView` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.ValuesView` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3617 +#: ../../library/typing.rst:3735 msgid "Aliases to asynchronous ABCs in :mod:`collections.abc`" -msgstr "" +msgstr "Apelidos para ABCs assíncronas em :mod:`collections.abc`" -#: ../../library/typing.rst:3621 +#: ../../library/typing.rst:3739 msgid "Deprecated alias to :class:`collections.abc.Coroutine`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.Coroutine`." -#: ../../library/typing.rst:3623 +#: ../../library/typing.rst:3741 msgid "" -"The variance and order of type variables correspond to those of :class:" -"`Generator`, for example::" +"See :ref:`annotating-generators-and-coroutines` for details on using :class:" +"`collections.abc.Coroutine` and ``typing.Coroutine`` in type annotations." msgstr "" +"Consulte :ref:`annotating-generators-and-coroutines` para obter detalhes " +"sobre como usar :class:`collections.abc.Coroutine` e ``typing.Coroutine`` em " +"anotações de tipos." -#: ../../library/typing.rst:3634 +#: ../../library/typing.rst:3747 msgid "" ":class:`collections.abc.Coroutine` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.Coroutine` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3640 +#: ../../library/typing.rst:3753 msgid "Deprecated alias to :class:`collections.abc.AsyncGenerator`." -msgstr "" - -#: ../../library/typing.rst:3642 -msgid "" -"An async generator can be annotated by the generic type " -"``AsyncGenerator[YieldType, SendType]``. For example::" -msgstr "" - -#: ../../library/typing.rst:3651 -msgid "" -"Unlike normal generators, async generators cannot return a value, so there " -"is no ``ReturnType`` type parameter. As with :class:`Generator`, the " -"``SendType`` behaves contravariantly." -msgstr "" - -#: ../../library/typing.rst:3655 -msgid "The ``SendType`` defaults to :const:`!None`::" -msgstr "" - -#: ../../library/typing.rst:3662 -msgid "It is also possible to set this type explicitly::" -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.AsyncGenerator`." -#: ../../library/typing.rst:3669 +#: ../../library/typing.rst:3755 msgid "" -"Alternatively, annotate your generator as having a return type of either " -"``AsyncIterable[YieldType]`` or ``AsyncIterator[YieldType]``::" +"See :ref:`annotating-generators-and-coroutines` for details on using :class:" +"`collections.abc.AsyncGenerator` and ``typing.AsyncGenerator`` in type " +"annotations." msgstr "" +"Consulte :ref:`annotating-generators-and-coroutines` para obter detalhes " +"sobre como usar :class:`collections.abc.AsyncGenerator` e ``typing." +"AsyncGenerator`` em anotações de tipos." -#: ../../library/typing.rst:3679 +#: ../../library/typing.rst:3761 msgid "" ":class:`collections.abc.AsyncGenerator` now supports subscripting (``[]``). " "See :pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.AsyncGenerator` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3684 +#: ../../library/typing.rst:3766 msgid "The ``SendType`` parameter now has a default." -msgstr "" +msgstr "O parâmetro ``SendType`` agora tem um valor-padrão." -#: ../../library/typing.rst:3689 +#: ../../library/typing.rst:3771 msgid "Deprecated alias to :class:`collections.abc.AsyncIterable`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.AsyncIterable`." -#: ../../library/typing.rst:3693 +#: ../../library/typing.rst:3775 msgid "" ":class:`collections.abc.AsyncIterable` now supports subscripting (``[]``). " "See :pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.AsyncIterable` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3699 +#: ../../library/typing.rst:3781 msgid "Deprecated alias to :class:`collections.abc.AsyncIterator`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.AsyncIterator`." -#: ../../library/typing.rst:3703 +#: ../../library/typing.rst:3785 msgid "" ":class:`collections.abc.AsyncIterator` now supports subscripting (``[]``). " "See :pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.AsyncIterator` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3709 +#: ../../library/typing.rst:3791 msgid "Deprecated alias to :class:`collections.abc.Awaitable`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.Awaitable`." -#: ../../library/typing.rst:3713 +#: ../../library/typing.rst:3795 msgid "" ":class:`collections.abc.Awaitable` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.Awaitable` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3720 +#: ../../library/typing.rst:3802 msgid "Aliases to other ABCs in :mod:`collections.abc`" -msgstr "" +msgstr "Apelidos para outros ABCs em :mod:`collections.abc`." -#: ../../library/typing.rst:3724 +#: ../../library/typing.rst:3806 msgid "Deprecated alias to :class:`collections.abc.Iterable`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.Iterable`." -#: ../../library/typing.rst:3726 +#: ../../library/typing.rst:3808 msgid "" ":class:`collections.abc.Iterable` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.Iterable` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3732 +#: ../../library/typing.rst:3814 msgid "Deprecated alias to :class:`collections.abc.Iterator`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.Iterator`." -#: ../../library/typing.rst:3734 +#: ../../library/typing.rst:3816 msgid "" ":class:`collections.abc.Iterator` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.Iterator` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3740 +#: ../../library/typing.rst:3822 msgid "Deprecated alias to :class:`collections.abc.Callable`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.Callable`." -#: ../../library/typing.rst:3742 +#: ../../library/typing.rst:3824 msgid "" "See :ref:`annotating-callables` for details on how to use :class:" "`collections.abc.Callable` and ``typing.Callable`` in type annotations." msgstr "" +"Veja :ref:`annotating-callables` para detalhes sobre como usar :class:" +"`collections.abc.Callable` e ``typing.Callable`` em anotações de tipo." -#: ../../library/typing.rst:3745 +#: ../../library/typing.rst:3827 msgid "" ":class:`collections.abc.Callable` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.Callable` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3755 +#: ../../library/typing.rst:3837 msgid "Deprecated alias to :class:`collections.abc.Generator`." -msgstr "" - -#: ../../library/typing.rst:3757 -msgid "" -"A generator can be annotated by the generic type ``Generator[YieldType, " -"SendType, ReturnType]``. For example::" -msgstr "" - -#: ../../library/typing.rst:3766 -msgid "" -"Note that unlike many other generics in the typing module, the ``SendType`` " -"of :class:`Generator` behaves contravariantly, not covariantly or " -"invariantly." -msgstr "" - -#: ../../library/typing.rst:3770 -msgid "" -"The ``SendType`` and ``ReturnType`` parameters default to :const:`!None`::" -msgstr "" - -#: ../../library/typing.rst:3777 -msgid "It is also possible to set these types explicitly::" -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.Generator`." -#: ../../library/typing.rst:3784 +#: ../../library/typing.rst:3839 msgid "" -"Alternatively, annotate your generator as having a return type of either " -"``Iterable[YieldType]`` or ``Iterator[YieldType]``::" +"See :ref:`annotating-generators-and-coroutines` for details on using :class:" +"`collections.abc.Generator` and ``typing.Generator`` in type annotations." msgstr "" +"Consulte :ref:`annotating-generators-and-coroutines` para obter detalhes " +"sobre como usar :class:`collections.abc.Generator` e ``typing.Generator`` em " +"anotações de tipos." -#: ../../library/typing.rst:3792 +#: ../../library/typing.rst:3843 msgid "" ":class:`collections.abc.Generator` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.Generator` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3796 +#: ../../library/typing.rst:3847 msgid "Default values for the send and return types were added." -msgstr "" +msgstr "Adiciona valores-padrão para os tipos de envio e retorno." -#: ../../library/typing.rst:3801 +#: ../../library/typing.rst:3852 msgid "Deprecated alias to :class:`collections.abc.Hashable`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.Hashable`." -#: ../../library/typing.rst:3803 +#: ../../library/typing.rst:3854 msgid "Use :class:`collections.abc.Hashable` directly instead." -msgstr "" +msgstr "Use :class:`collections.abc.Hashable` diretamente." -#: ../../library/typing.rst:3808 +#: ../../library/typing.rst:3859 msgid "Deprecated alias to :class:`collections.abc.Reversible`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.Reversible`." -#: ../../library/typing.rst:3810 +#: ../../library/typing.rst:3861 msgid "" ":class:`collections.abc.Reversible` now supports subscripting (``[]``). See :" "pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`collections.abc.Reversible` agora oferece suporte a subscrição " +"(``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3816 +#: ../../library/typing.rst:3867 msgid "Deprecated alias to :class:`collections.abc.Sized`." -msgstr "" +msgstr "Apelido descontinuado de :class:`collections.abc.Sized`." -#: ../../library/typing.rst:3818 +#: ../../library/typing.rst:3869 msgid "Use :class:`collections.abc.Sized` directly instead." -msgstr "" +msgstr "Use :class:`collections.abc.Sized` diretamente." -#: ../../library/typing.rst:3824 +#: ../../library/typing.rst:3875 msgid "Aliases to :mod:`contextlib` ABCs" -msgstr "" +msgstr "Apelidos de ABCs da :mod:`contextlib`" -#: ../../library/typing.rst:3828 +#: ../../library/typing.rst:3879 msgid "Deprecated alias to :class:`contextlib.AbstractContextManager`." -msgstr "" +msgstr "Apelido descontinuado de :class:`contextlib.AbstractContextManager`." -#: ../../library/typing.rst:3830 +#: ../../library/typing.rst:3881 msgid "" "The first type parameter, ``T_co``, represents the type returned by the :" "meth:`~object.__enter__` method. The optional second type parameter, " "``ExitT_co``, which defaults to ``bool | None``, represents the type " "returned by the :meth:`~object.__exit__` method." msgstr "" +"O primeiro parâmetro de tipo, ``T_co``, representa o tipo retornado pelo " +"método :meth:`~object.__enter__`. O segundo parâmetro opcional de tipo, " +"``ExitT_co``, cujo valor-padrão é ``bool | None``, representa o tipo " +"retornado pelo método :meth:`~object.__exit__`." -#: ../../library/typing.rst:3837 +#: ../../library/typing.rst:3888 msgid "" ":class:`contextlib.AbstractContextManager` now supports subscripting " "(``[]``). See :pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`contextlib.AbstractContextManager` agora oferece suporte a " +"subscrição (``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3842 +#: ../../library/typing.rst:3893 msgid "Added the optional second type parameter, ``ExitT_co``." -msgstr "" +msgstr "Adiciona o segundo parâmetro opcional de tipo, ``ExitT_co``." -#: ../../library/typing.rst:3847 +#: ../../library/typing.rst:3898 msgid "Deprecated alias to :class:`contextlib.AbstractAsyncContextManager`." msgstr "" +"Apelido descontinuado de :class:`contextlib.AbstractAsyncContextManager`." -#: ../../library/typing.rst:3849 +#: ../../library/typing.rst:3900 msgid "" "The first type parameter, ``T_co``, represents the type returned by the :" "meth:`~object.__aenter__` method. The optional second type parameter, " "``AExitT_co``, which defaults to ``bool | None``, represents the type " "returned by the :meth:`~object.__aexit__` method." msgstr "" +"O primeiro parâmetro de tipo, ``T_co``, representa o tipo retornado pelo " +"método :meth:`~object.__aenter__`. O segundo parâmetro opcional de tipo, " +"``AExitT_co``, cujo valor-padrão é ``bool | None``, representa o tipo " +"retornado pelo método :meth:`~object.__aexit__`." -#: ../../library/typing.rst:3856 +#: ../../library/typing.rst:3907 msgid "" ":class:`contextlib.AbstractAsyncContextManager` now supports subscripting " "(``[]``). See :pep:`585` and :ref:`types-genericalias`." msgstr "" +":class:`contextlib.AbstractAsyncContextManager` agora oferece suporte a " +"subscrição (``[]``). Consulte :pep:`585` e :ref:`types-genericalias`." -#: ../../library/typing.rst:3861 +#: ../../library/typing.rst:3912 msgid "Added the optional second type parameter, ``AExitT_co``." -msgstr "" +msgstr "Adiciona o segundo parâmetro opcional de tipo, ``AExitT_co``." -#: ../../library/typing.rst:3865 +#: ../../library/typing.rst:3916 msgid "Deprecation Timeline of Major Features" -msgstr "Cronograma de Descontinuação dos Principais Recursos" +msgstr "Cronograma de descontinuação dos principais recursos" -#: ../../library/typing.rst:3867 +#: ../../library/typing.rst:3918 msgid "" "Certain features in ``typing`` are deprecated and may be removed in a future " "version of Python. The following table summarizes major deprecations for " "your convenience. This is subject to change, and not all deprecations are " "listed." msgstr "" +"Alguns recursos em ``typing`` estão descontinuados e podem ser removidos em " +"uma versão futura de Python. A tabela a seguir resume as principais " +"descontinuações para sua conveniência. Ela está sujeita a alterações, e nem " +"todas as descontinuações estão listadas." -#: ../../library/typing.rst:3874 +#: ../../library/typing.rst:3925 msgid "Feature" -msgstr "" +msgstr "Recurso" -#: ../../library/typing.rst:3875 +#: ../../library/typing.rst:3926 msgid "Deprecated in" msgstr "Descontinuado em" -#: ../../library/typing.rst:3876 +#: ../../library/typing.rst:3927 msgid "Projected removal" -msgstr "" +msgstr "Remoção planejada" -#: ../../library/typing.rst:3877 +#: ../../library/typing.rst:3928 msgid "PEP/issue" -msgstr "" +msgstr "PEP/issue" -#: ../../library/typing.rst:3878 +#: ../../library/typing.rst:3929 msgid "``typing`` versions of standard collections" -msgstr "" +msgstr "versões ``typing`` de coleções-padrão" -#: ../../library/typing.rst:3879 ../../library/typing.rst:3883 +#: ../../library/typing.rst:3930 ../../library/typing.rst:3934 msgid "3.9" msgstr "3.9" -#: ../../library/typing.rst:3880 +#: ../../library/typing.rst:3931 msgid "Undecided (see :ref:`deprecated-aliases` for more information)" msgstr "" +"Não definido (consulte :ref:`apelidos descontinuados ` " +"para mais informações)" -#: ../../library/typing.rst:3881 +#: ../../library/typing.rst:3932 msgid ":pep:`585`" msgstr ":pep:`585`" -#: ../../library/typing.rst:3882 +#: ../../library/typing.rst:3933 msgid ":class:`typing.ByteString`" -msgstr "" +msgstr ":class:`typing.ByteString`" -#: ../../library/typing.rst:3884 +#: ../../library/typing.rst:3935 msgid "3.14" -msgstr "" +msgstr "3.14" -#: ../../library/typing.rst:3885 +#: ../../library/typing.rst:3936 msgid ":gh:`91896`" -msgstr "" +msgstr ":gh:`91896`" -#: ../../library/typing.rst:3886 +#: ../../library/typing.rst:3937 msgid ":data:`typing.Text`" -msgstr "" +msgstr ":data:`typing.Text`" -#: ../../library/typing.rst:3887 +#: ../../library/typing.rst:3938 msgid "3.11" msgstr "3.11" -#: ../../library/typing.rst:3888 ../../library/typing.rst:3892 -#: ../../library/typing.rst:3896 +#: ../../library/typing.rst:3939 ../../library/typing.rst:3943 +#: ../../library/typing.rst:3947 msgid "Undecided" -msgstr "" +msgstr "Não definido" -#: ../../library/typing.rst:3889 +#: ../../library/typing.rst:3940 msgid ":gh:`92332`" msgstr ":gh:`92332`" -#: ../../library/typing.rst:3890 +#: ../../library/typing.rst:3941 msgid ":class:`typing.Hashable` and :class:`typing.Sized`" -msgstr "" +msgstr ":class:`typing.Hashable` e :class:`typing.Sized`" -#: ../../library/typing.rst:3891 ../../library/typing.rst:3895 +#: ../../library/typing.rst:3942 ../../library/typing.rst:3946 msgid "3.12" -msgstr "" +msgstr "3.12" -#: ../../library/typing.rst:3893 +#: ../../library/typing.rst:3944 msgid ":gh:`94309`" -msgstr "" +msgstr ":gh:`94309`" -#: ../../library/typing.rst:3894 +#: ../../library/typing.rst:3945 msgid ":data:`typing.TypeAlias`" -msgstr "" +msgstr ":data:`typing.TypeAlias`" -#: ../../library/typing.rst:3897 +#: ../../library/typing.rst:3948 msgid ":pep:`695`" -msgstr "" +msgstr ":pep:`695`" -#: ../../library/typing.rst:3898 +#: ../../library/typing.rst:3949 msgid ":func:`@typing.no_type_check_decorator `" -msgstr "" +msgstr ":func:`@typing.no_type_check_decorator `" -#: ../../library/typing.rst:3899 ../../library/typing.rst:3903 +#: ../../library/typing.rst:3950 ../../library/typing.rst:3954 msgid "3.13" msgstr "3.13" -#: ../../library/typing.rst:3900 +#: ../../library/typing.rst:3951 msgid "3.15" -msgstr "" +msgstr "3.15" -#: ../../library/typing.rst:3901 +#: ../../library/typing.rst:3952 msgid ":gh:`106309`" -msgstr "" +msgstr ":gh:`106309`" -#: ../../library/typing.rst:3902 +#: ../../library/typing.rst:3953 msgid ":data:`typing.AnyStr`" -msgstr "" +msgstr ":data:`typing.AnyStr`" -#: ../../library/typing.rst:3904 +#: ../../library/typing.rst:3955 msgid "3.18" -msgstr "" +msgstr "3.18" -#: ../../library/typing.rst:3905 +#: ../../library/typing.rst:3956 msgid ":gh:`105578`" -msgstr "" +msgstr ":gh:`105578`" diff --git a/library/unicodedata.po b/library/unicodedata.po index 7d4baef3d..7cfe93b4a 100644 --- a/library/unicodedata.po +++ b/library/unicodedata.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Victor Matheus Castro , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 01:16+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/unittest.mock-examples.po b/library/unittest.mock-examples.po index f18a37a93..27725bba4 100644 --- a/library/unittest.mock-examples.po +++ b/library/unittest.mock-examples.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:16+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -161,6 +159,19 @@ msgid "" "return_value`. ::" msgstr "" +#: ../../library/unittest.mock-examples.rst:118 +msgid "" +">>> def some_function():\n" +"... instance = module.Foo()\n" +"... return instance.method()\n" +"...\n" +">>> with patch('module.Foo') as mock:\n" +"... instance = mock.return_value\n" +"... instance.method.return_value = 'the result'\n" +"... result = some_function()\n" +"... assert result == 'the result'" +msgstr "" + #: ../../library/unittest.mock-examples.rst:130 msgid "Naming your mocks" msgstr "Nomeando os mocks" @@ -333,6 +344,16 @@ msgid "" "named arguments::" msgstr "" +#: ../../library/unittest.mock-examples.rst:348 +msgid "" +">>> def f(a, b, c): pass\n" +"...\n" +">>> mock = Mock(spec=f)\n" +">>> mock(1, 2, 3)\n" +"\n" +">>> mock.assert_called_with(a=1, b=2, c=3)" +msgstr "" + #: ../../library/unittest.mock-examples.rst:355 msgid "" "If you want this smarter matching to also work with method calls on the " @@ -357,6 +378,26 @@ msgid "" "used to return different contents per file stored in a dictionary::" msgstr "" +#: ../../library/unittest.mock-examples.rst:370 +msgid "" +"DEFAULT = \"default\"\n" +"data_dict = {\"file1\": \"data1\",\n" +" \"file2\": \"data2\"}\n" +"\n" +"def open_side_effect(name):\n" +" return mock_open(read_data=data_dict.get(name, DEFAULT))()\n" +"\n" +"with patch(\"builtins.open\", side_effect=open_side_effect):\n" +" with open(\"file1\") as file1:\n" +" assert file1.read() == \"data1\"\n" +"\n" +" with open(\"file2\") as file2:\n" +" assert file2.read() == \"data2\"\n" +"\n" +" with open(\"file3\") as file2:\n" +" assert file2.read() == \"default\"" +msgstr "" + #: ../../library/unittest.mock-examples.rst:389 msgid "Patch Decorators" msgstr "" @@ -395,6 +436,24 @@ msgstr "" msgid "``patch.object``::" msgstr "" +#: ../../library/unittest.mock-examples.rst:414 +msgid "" +">>> original = SomeClass.attribute\n" +">>> @patch.object(SomeClass, 'attribute', sentinel.attribute)\n" +"... def test():\n" +"... assert SomeClass.attribute == sentinel.attribute\n" +"...\n" +">>> test()\n" +">>> assert SomeClass.attribute == original\n" +"\n" +">>> @patch('package.module.attribute', sentinel.attribute)\n" +"... def test():\n" +"... from package.module import attribute\n" +"... assert attribute is sentinel.attribute\n" +"...\n" +">>> test()" +msgstr "" + #: ../../library/unittest.mock-examples.rst:429 msgid "" "If you are patching a module (including :mod:`builtins`) then use :func:" @@ -406,6 +465,16 @@ msgid "" "The module name can be 'dotted', in the form ``package.module`` if needed::" msgstr "" +#: ../../library/unittest.mock-examples.rst:441 +msgid "" +">>> @patch('package.module.ClassName.attribute', sentinel.attribute)\n" +"... def test():\n" +"... from package.module import ClassName\n" +"... assert ClassName.attribute == sentinel.attribute\n" +"...\n" +">>> test()" +msgstr "" + #: ../../library/unittest.mock-examples.rst:448 msgid "A nice pattern is to actually decorate test methods themselves:" msgstr "" @@ -421,6 +490,18 @@ msgstr "" msgid "You can stack up multiple patch decorators using this pattern::" msgstr "" +#: ../../library/unittest.mock-examples.rst:473 +msgid "" +">>> class MyTest(unittest.TestCase):\n" +"... @patch('package.module.ClassName1')\n" +"... @patch('package.module.ClassName2')\n" +"... def test_something(self, MockClass2, MockClass1):\n" +"... self.assertIs(package.module.ClassName1, MockClass1)\n" +"... self.assertIs(package.module.ClassName2, MockClass2)\n" +"...\n" +">>> MyTest('test_something').test_something()" +msgstr "" + #: ../../library/unittest.mock-examples.rst:482 msgid "" "When you nest patch decorators the mocks are passed in to the decorated " @@ -519,18 +600,40 @@ msgid "" "final ``start_call`` we could do this::" msgstr "" +#: ../../library/unittest.mock-examples.rst:573 +msgid "" +"mock_backend.get_endpoint.return_value.create_call.return_value.start_call." +"return_value = mock_response" +msgstr "" + #: ../../library/unittest.mock-examples.rst:575 msgid "" "We can do that in a slightly nicer way using the :meth:`~Mock." "configure_mock` method to directly set the return value for us::" msgstr "" +#: ../../library/unittest.mock-examples.rst:578 +msgid "" +">>> something = Something()\n" +">>> mock_response = Mock(spec=open)\n" +">>> mock_backend = Mock()\n" +">>> config = {'get_endpoint.return_value.create_call.return_value.start_call." +"return_value': mock_response}\n" +">>> mock_backend.configure_mock(**config)" +msgstr "" + #: ../../library/unittest.mock-examples.rst:584 msgid "" "With these we monkey patch the \"mock backend\" in place and can make the " "real call::" msgstr "" +#: ../../library/unittest.mock-examples.rst:587 +msgid "" +">>> something.backend = mock_backend\n" +">>> something.method()" +msgstr "" + #: ../../library/unittest.mock-examples.rst:590 msgid "" "Using :attr:`~Mock.mock_calls` we can check the chained call with a single " @@ -539,6 +642,14 @@ msgid "" "create this list of calls for us::" msgstr "" +#: ../../library/unittest.mock-examples.rst:595 +msgid "" +">>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs')." +"start_call()\n" +">>> call_list = chained.call_list()\n" +">>> assert mock_backend.mock_calls == call_list" +msgstr "" + #: ../../library/unittest.mock-examples.rst:601 msgid "Partial mocking" msgstr "" @@ -568,6 +679,17 @@ msgid "" "returned by ``side_effect``. ::" msgstr "" +#: ../../library/unittest.mock-examples.rst:618 +msgid "" +">>> from datetime import date\n" +">>> with patch('mymodule.date') as mock_date:\n" +"... mock_date.today.return_value = date(2010, 10, 8)\n" +"... mock_date.side_effect = lambda *args, **kw: date(*args, **kw)\n" +"...\n" +"... assert mymodule.date.today() == date(2010, 10, 8)\n" +"... assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)" +msgstr "" + #: ../../library/unittest.mock-examples.rst:626 msgid "" "Note that we don't patch :class:`datetime.date` globally, we patch ``date`` " @@ -655,6 +777,26 @@ msgid "" "start with ``test``::" msgstr "" +#: ../../library/unittest.mock-examples.rst:692 +msgid "" +">>> @patch('mymodule.SomeClass')\n" +"... class MyTest(unittest.TestCase):\n" +"...\n" +"... def test_one(self, MockSomeClass):\n" +"... self.assertIs(mymodule.SomeClass, MockSomeClass)\n" +"...\n" +"... def test_two(self, MockSomeClass):\n" +"... self.assertIs(mymodule.SomeClass, MockSomeClass)\n" +"...\n" +"... def not_a_test(self):\n" +"... return 'something'\n" +"...\n" +">>> MyTest('test_one').test_one()\n" +">>> MyTest('test_two').test_two()\n" +">>> MyTest('test_two').not_a_test()\n" +"'something'" +msgstr "" + #: ../../library/unittest.mock-examples.rst:709 msgid "" "An alternative way of managing patches is to use the :ref:`start-and-stop`. " @@ -662,6 +804,22 @@ msgid "" "methods. ::" msgstr "" +#: ../../library/unittest.mock-examples.rst:713 +msgid "" +">>> class MyTest(unittest.TestCase):\n" +"... def setUp(self):\n" +"... self.patcher = patch('mymodule.foo')\n" +"... self.mock_foo = self.patcher.start()\n" +"...\n" +"... def test_foo(self):\n" +"... self.assertIs(mymodule.foo, self.mock_foo)\n" +"...\n" +"... def tearDown(self):\n" +"... self.patcher.stop()\n" +"...\n" +">>> MyTest('test_foo').run()" +msgstr "" + #: ../../library/unittest.mock-examples.rst:726 msgid "" "If you use this technique you must ensure that the patching is \"undone\" by " @@ -670,6 +828,20 @@ msgid "" "`unittest.TestCase.addCleanup` makes this easier::" msgstr "" +#: ../../library/unittest.mock-examples.rst:731 +msgid "" +">>> class MyTest(unittest.TestCase):\n" +"... def setUp(self):\n" +"... patcher = patch('mymodule.foo')\n" +"... self.addCleanup(patcher.stop)\n" +"... self.mock_foo = patcher.start()\n" +"...\n" +"... def test_foo(self):\n" +"... self.assertIs(mymodule.foo, self.mock_foo)\n" +"...\n" +">>> MyTest('test_foo').run()" +msgstr "" + #: ../../library/unittest.mock-examples.rst:744 msgid "Mocking Unbound Methods" msgstr "" @@ -758,12 +930,38 @@ msgid "" "functions defined in 'mymodule'::" msgstr "" +#: ../../library/unittest.mock-examples.rst:836 +msgid "" +"def frob(val):\n" +" pass\n" +"\n" +"def grob(val):\n" +" \"First frob and then clear val\"\n" +" frob(val)\n" +" val.clear()" +msgstr "" + #: ../../library/unittest.mock-examples.rst:844 msgid "" "When we try to test that ``grob`` calls ``frob`` with the correct argument " "look what happens::" msgstr "" +#: ../../library/unittest.mock-examples.rst:847 +msgid "" +">>> with patch('mymodule.frob') as mock_frob:\n" +"... val = {6}\n" +"... mymodule.grob(val)\n" +"...\n" +">>> val\n" +"set()\n" +">>> mock_frob.assert_called_with({6})\n" +"Traceback (most recent call last):\n" +" ...\n" +"AssertionError: Expected: (({6},), {})\n" +"Called with: ((set(),), {})" +msgstr "" + #: ../../library/unittest.mock-examples.rst:859 msgid "" "One possibility would be for mock to copy the arguments you pass in. This " @@ -782,6 +980,30 @@ msgid "" "me. ::" msgstr "" +#: ../../library/unittest.mock-examples.rst:871 +msgid "" +">>> from copy import deepcopy\n" +">>> from unittest.mock import Mock, patch, DEFAULT\n" +">>> def copy_call_args(mock):\n" +"... new_mock = Mock()\n" +"... def side_effect(*args, **kwargs):\n" +"... args = deepcopy(args)\n" +"... kwargs = deepcopy(kwargs)\n" +"... new_mock(*args, **kwargs)\n" +"... return DEFAULT\n" +"... mock.side_effect = side_effect\n" +"... return new_mock\n" +"...\n" +">>> with patch('mymodule.frob') as mock_frob:\n" +"... new_mock = copy_call_args(mock_frob)\n" +"... val = {6}\n" +"... mymodule.grob(val)\n" +"...\n" +">>> new_mock.assert_called_with({6})\n" +">>> new_mock.call_args\n" +"call({6})" +msgstr "" + #: ../../library/unittest.mock-examples.rst:892 msgid "" "``copy_call_args`` is called with the mock that will be called. It returns a " @@ -822,6 +1044,23 @@ msgid "" "right::" msgstr "" +#: ../../library/unittest.mock-examples.rst:949 +msgid "" +">>> class MyTest(unittest.TestCase):\n" +"...\n" +"... def test_foo(self):\n" +"... with patch('mymodule.Foo') as mock_foo:\n" +"... with patch('mymodule.Bar') as mock_bar:\n" +"... with patch('mymodule.Spam') as mock_spam:\n" +"... assert mymodule.Foo is mock_foo\n" +"... assert mymodule.Bar is mock_bar\n" +"... assert mymodule.Spam is mock_spam\n" +"...\n" +">>> original = mymodule.Foo\n" +">>> MyTest('test_foo').test_foo()\n" +">>> assert mymodule.Foo is original" +msgstr "" + #: ../../library/unittest.mock-examples.rst:963 msgid "" "With unittest ``cleanup`` functions and the :ref:`start-and-stop` we can " @@ -830,6 +1069,30 @@ msgid "" "mock for us::" msgstr "" +#: ../../library/unittest.mock-examples.rst:968 +msgid "" +">>> class MyTest(unittest.TestCase):\n" +"...\n" +"... def create_patch(self, name):\n" +"... patcher = patch(name)\n" +"... thing = patcher.start()\n" +"... self.addCleanup(patcher.stop)\n" +"... return thing\n" +"...\n" +"... def test_foo(self):\n" +"... mock_foo = self.create_patch('mymodule.Foo')\n" +"... mock_bar = self.create_patch('mymodule.Bar')\n" +"... mock_spam = self.create_patch('mymodule.Spam')\n" +"...\n" +"... assert mymodule.Foo is mock_foo\n" +"... assert mymodule.Bar is mock_bar\n" +"... assert mymodule.Spam is mock_spam\n" +"...\n" +">>> original = mymodule.Foo\n" +">>> MyTest('test_foo').run()\n" +">>> assert mymodule.Foo is original" +msgstr "" + #: ../../library/unittest.mock-examples.rst:991 msgid "Mocking a dictionary with MagicMock" msgstr "" @@ -1022,6 +1285,24 @@ msgid "" "After attaching calls will be recorded in ``mock_calls`` of the manager. ::" msgstr "" +#: ../../library/unittest.mock-examples.rst:1229 +msgid "" +">>> manager = MagicMock()\n" +">>> with patch('mymodule.Class1') as MockClass1:\n" +"... with patch('mymodule.Class2') as MockClass2:\n" +"... manager.attach_mock(MockClass1, 'MockClass1')\n" +"... manager.attach_mock(MockClass2, 'MockClass2')\n" +"... MockClass1().foo()\n" +"... MockClass2().bar()\n" +"\n" +"\n" +">>> manager.mock_calls\n" +"[call.MockClass1(),\n" +"call.MockClass1().foo(),\n" +"call.MockClass2(),\n" +"call.MockClass2().bar()]" +msgstr "" + #: ../../library/unittest.mock-examples.rst:1244 msgid "" "If many calls have been made, but you're only interested in a particular " diff --git a/library/unittest.mock.po b/library/unittest.mock.po index 9e7795930..658a30df1 100644 --- a/library/unittest.mock.po +++ b/library/unittest.mock.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Vinícius Muniz de Melo , 2021 -# Marco Rougeth , 2021 -# i17obot , 2021 -# Claudio Rogerio Carvalho Filho , 2022 -# Rafael Fontenelle , 2023 -# Vitor Buxbaum Orlandi, 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-19 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 01:16+0000\n" -"Last-Translator: Vitor Buxbaum Orlandi, 2023\n" +"POT-Creation-Date: 2025-05-16 14:58+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -110,11 +105,9 @@ msgstr "" #: ../../library/unittest.mock.rst:71 msgid "" -":attr:`side_effect` allows you to perform side effects, including raising an " -"exception when a mock is called:" +":attr:`~Mock.side_effect` allows you to perform side effects, including " +"raising an exception when a mock is called:" msgstr "" -":attr:`side_effect` permite que você execute efeitos colaterais, incluindo " -"levantar uma exceção quando um mock é chamado:" #: ../../library/unittest.mock.rst:92 msgid "" @@ -126,7 +119,7 @@ msgstr "" "O Mock tem muitas outras maneiras de configurá-lo e controlar seu " "comportamento. Por exemplo, o argumento *spec* configura o mock para obter " "sua especificação de outro objeto. Tentar acessar atributos ou métodos no " -"mock que não existem na especificação falhará com um :exc:`AttributeError`." +"mock que não existem no spec falhará com um :exc:`AttributeError`." #: ../../library/unittest.mock.rst:97 msgid "" @@ -140,6 +133,22 @@ msgstr "" "substituído por um mock (ou outro objeto) durante o teste e restaurado " "quando o teste terminar::" +#: ../../library/unittest.mock.rst:101 +msgid "" +">>> from unittest.mock import patch\n" +">>> @patch('module.ClassName2')\n" +"... @patch('module.ClassName1')\n" +"... def test(MockClass1, MockClass2):\n" +"... module.ClassName1()\n" +"... module.ClassName2()\n" +"... assert MockClass1 is module.ClassName1\n" +"... assert MockClass2 is module.ClassName2\n" +"... assert MockClass1.called\n" +"... assert MockClass2.called\n" +"...\n" +">>> test()" +msgstr "" + #: ../../library/unittest.mock.rst:116 msgid "" "When you nest patch decorators the mocks are passed in to the decorated " @@ -304,7 +313,7 @@ msgstr "" #: ../../library/unittest.mock.rst:241 msgid "" -"If *spec* is an object (rather than a list of strings) then :attr:`~instance." +"If *spec* is an object (rather than a list of strings) then :attr:`~object." "__class__` returns the class of the spec object. This allows mocks to pass :" "func:`isinstance` tests." msgstr "" @@ -443,117 +452,162 @@ msgstr "Afirma que o mock nunca foi chamado." msgid "The reset_mock method resets all the call attributes on a mock object:" msgstr "" -#: ../../library/unittest.mock.rst:412 -msgid "Added two keyword-only arguments to the reset_mock function." -msgstr "Foram adicionados dois argumentos somente-nomeado à função reset_mock." +#: ../../library/unittest.mock.rst:404 +msgid "" +">>> mock = Mock(return_value=None)\n" +">>> mock('hello')\n" +">>> mock.called\n" +"True\n" +">>> mock.reset_mock()\n" +">>> mock.called\n" +"False" +msgstr "" -#: ../../library/unittest.mock.rst:415 +#: ../../library/unittest.mock.rst:414 msgid "" "This can be useful where you want to make a series of assertions that reuse " -"the same object. Note that :meth:`reset_mock` *doesn't* clear the :attr:" -"`return_value`, :attr:`side_effect` or any child attributes you have set " -"using normal assignment by default. In case you want to reset :attr:" -"`return_value` or :attr:`side_effect`, then pass the corresponding parameter " -"as ``True``. Child mocks and the return value mock (if any) are reset as " -"well." +"the same object." +msgstr "" + +#: ../../library/unittest.mock.rst:417 +msgid "" +"*return_value* parameter when set to ``True`` resets :attr:`return_value`:" +msgstr "" + +#: ../../library/unittest.mock.rst:419 +msgid "" +">>> mock = Mock(return_value=5)\n" +">>> mock('hello')\n" +"5\n" +">>> mock.reset_mock(return_value=True)\n" +">>> mock('hello')\n" +"" +msgstr "" + +#: ../../library/unittest.mock.rst:428 +msgid "" +"*side_effect* parameter when set to ``True`` resets :attr:`side_effect`:" msgstr "" -#: ../../library/unittest.mock.rst:423 -msgid "*return_value*, and *side_effect* are keyword-only arguments." +#: ../../library/unittest.mock.rst:430 +msgid "" +">>> mock = Mock(side_effect=ValueError)\n" +">>> mock('hello')\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError\n" +">>> mock.reset_mock(side_effect=True)\n" +">>> mock('hello')\n" +"" msgstr "" -#: ../../library/unittest.mock.rst:429 +#: ../../library/unittest.mock.rst:441 +msgid "" +"Note that :meth:`reset_mock` *doesn't* clear the :attr:`return_value`, :attr:" +"`side_effect` or any child attributes you have set using normal assignment " +"by default." +msgstr "" + +#: ../../library/unittest.mock.rst:445 +msgid "Child mocks are reset as well." +msgstr "" + +#: ../../library/unittest.mock.rst:447 +msgid "Added two keyword-only arguments to the reset_mock function." +msgstr "Foram adicionados dois argumentos somente-nomeado à função reset_mock." + +#: ../../library/unittest.mock.rst:452 msgid "" "Add a spec to a mock. *spec* can either be an object or a list of strings. " "Only attributes on the *spec* can be fetched as attributes from the mock." msgstr "" -#: ../../library/unittest.mock.rst:433 +#: ../../library/unittest.mock.rst:456 msgid "If *spec_set* is true then only attributes on the spec can be set." msgstr "" -#: ../../library/unittest.mock.rst:438 +#: ../../library/unittest.mock.rst:461 msgid "" "Attach a mock as an attribute of this one, replacing its name and parent. " "Calls to the attached mock will be recorded in the :attr:`method_calls` and :" "attr:`mock_calls` attributes of this one." msgstr "" -#: ../../library/unittest.mock.rst:445 +#: ../../library/unittest.mock.rst:468 msgid "Set attributes on the mock through keyword arguments." msgstr "Define atributos no mock por meio de argumentos nomeados." -#: ../../library/unittest.mock.rst:447 +#: ../../library/unittest.mock.rst:470 msgid "" "Attributes plus return values and side effects can be set on child mocks " "using standard dot notation and unpacking a dictionary in the method call:" msgstr "" -#: ../../library/unittest.mock.rst:461 +#: ../../library/unittest.mock.rst:484 msgid "The same thing can be achieved in the constructor call to mocks:" msgstr "" -#: ../../library/unittest.mock.rst:474 +#: ../../library/unittest.mock.rst:497 msgid "" ":meth:`configure_mock` exists to make it easier to do configuration after " "the mock has been created." msgstr "" -#: ../../library/unittest.mock.rst:480 +#: ../../library/unittest.mock.rst:503 msgid "" ":class:`Mock` objects limit the results of ``dir(some_mock)`` to useful " "results. For mocks with a *spec* this includes all the permitted attributes " "for the mock." msgstr "" -#: ../../library/unittest.mock.rst:484 +#: ../../library/unittest.mock.rst:507 msgid "" "See :data:`FILTER_DIR` for what this filtering does, and how to switch it " "off." msgstr "" -#: ../../library/unittest.mock.rst:490 +#: ../../library/unittest.mock.rst:513 msgid "" "Create the child mocks for attributes and return value. By default child " "mocks will be the same type as the parent. Subclasses of Mock may want to " "override this to customize the way child mocks are made." msgstr "" -#: ../../library/unittest.mock.rst:495 +#: ../../library/unittest.mock.rst:518 msgid "" "For non-callable mocks the callable variant will be used (rather than any " "custom subclass)." msgstr "" -#: ../../library/unittest.mock.rst:501 +#: ../../library/unittest.mock.rst:524 msgid "A boolean representing whether or not the mock object has been called:" msgstr "" -#: ../../library/unittest.mock.rst:512 +#: ../../library/unittest.mock.rst:535 msgid "An integer telling you how many times the mock object has been called:" msgstr "" -#: ../../library/unittest.mock.rst:524 +#: ../../library/unittest.mock.rst:547 msgid "Set this to configure the value returned by calling the mock:" msgstr "" -#: ../../library/unittest.mock.rst:531 +#: ../../library/unittest.mock.rst:554 msgid "" "The default return value is a mock object and you can configure it in the " "normal way:" msgstr "" -#: ../../library/unittest.mock.rst:540 +#: ../../library/unittest.mock.rst:563 msgid ":attr:`return_value` can also be set in the constructor:" msgstr ":attr:`return_value` também pode ser definido no construtor:" -#: ../../library/unittest.mock.rst:551 +#: ../../library/unittest.mock.rst:574 msgid "" "This can either be a function to be called when the mock is called, an " "iterable or an exception (class or instance) to be raised." msgstr "" -#: ../../library/unittest.mock.rst:554 +#: ../../library/unittest.mock.rst:577 msgid "" "If you pass in a function it will be called with same arguments as the mock " "and unless the function returns the :data:`DEFAULT` singleton the call to " @@ -562,7 +616,7 @@ msgid "" "the :attr:`return_value`)." msgstr "" -#: ../../library/unittest.mock.rst:560 +#: ../../library/unittest.mock.rst:583 msgid "" "If you pass in an iterable, it is used to retrieve an iterator which must " "yield a value on every call. This value can either be an exception instance " @@ -570,31 +624,31 @@ msgid "" "`DEFAULT` handling is identical to the function case)." msgstr "" -#: ../../library/unittest.mock.rst:565 +#: ../../library/unittest.mock.rst:588 msgid "" "An example of a mock that raises an exception (to test exception handling of " "an API):" msgstr "" -#: ../../library/unittest.mock.rst:575 +#: ../../library/unittest.mock.rst:598 msgid "Using :attr:`side_effect` to return a sequence of values:" msgstr "Usando :attr:`side_effect` para retornar um sequência de valores:" -#: ../../library/unittest.mock.rst:582 +#: ../../library/unittest.mock.rst:605 msgid "Using a callable:" msgstr "Usando um chamável:" -#: ../../library/unittest.mock.rst:592 +#: ../../library/unittest.mock.rst:615 msgid "" ":attr:`side_effect` can be set in the constructor. Here's an example that " "adds one to the value the mock is called with and returns it:" msgstr "" -#: ../../library/unittest.mock.rst:602 +#: ../../library/unittest.mock.rst:625 msgid "Setting :attr:`side_effect` to ``None`` clears it:" msgstr "Configuração :attr:`side_effect` para ``None`` limpa isso:" -#: ../../library/unittest.mock.rst:616 +#: ../../library/unittest.mock.rst:639 msgid "" "This is either ``None`` (if the mock hasn't been called), or the arguments " "that the mock was last called with. This will be in the form of a tuple: the " @@ -604,7 +658,7 @@ msgid "" "is any keyword arguments (or an empty dictionary)." msgstr "" -#: ../../library/unittest.mock.rst:649 +#: ../../library/unittest.mock.rst:672 msgid "" ":attr:`call_args`, along with members of the lists :attr:`call_args_list`, :" "attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects. These " @@ -612,11 +666,11 @@ msgid "" "make more complex assertions. See :ref:`calls as tuples `." msgstr "" -#: ../../library/unittest.mock.rst:655 +#: ../../library/unittest.mock.rst:678 msgid "Added ``args`` and ``kwargs`` properties." msgstr "Adicionadas propriedades ``args`` e ``kwargs``." -#: ../../library/unittest.mock.rst:661 +#: ../../library/unittest.mock.rst:684 msgid "" "This is a list of all the calls made to the mock object in sequence (so the " "length of the list is the number of times it has been called). Before any " @@ -625,80 +679,80 @@ msgid "" "`call_args_list`." msgstr "" -#: ../../library/unittest.mock.rst:677 +#: ../../library/unittest.mock.rst:700 msgid "" "Members of :attr:`call_args_list` are :data:`call` objects. These can be " "unpacked as tuples to get at the individual arguments. See :ref:`calls as " "tuples `." msgstr "" -#: ../../library/unittest.mock.rst:684 +#: ../../library/unittest.mock.rst:707 msgid "" "As well as tracking calls to themselves, mocks also track calls to methods " "and attributes, and *their* methods and attributes:" msgstr "" -#: ../../library/unittest.mock.rst:695 +#: ../../library/unittest.mock.rst:718 msgid "" "Members of :attr:`method_calls` are :data:`call` objects. These can be " "unpacked as tuples to get at the individual arguments. See :ref:`calls as " "tuples `." msgstr "" -#: ../../library/unittest.mock.rst:702 +#: ../../library/unittest.mock.rst:725 msgid "" ":attr:`mock_calls` records *all* calls to the mock object, its methods, " "magic methods *and* return value mocks." msgstr "" -#: ../../library/unittest.mock.rst:720 +#: ../../library/unittest.mock.rst:743 msgid "" "Members of :attr:`mock_calls` are :data:`call` objects. These can be " "unpacked as tuples to get at the individual arguments. See :ref:`calls as " "tuples `." msgstr "" -#: ../../library/unittest.mock.rst:726 +#: ../../library/unittest.mock.rst:749 msgid "" "The way :attr:`mock_calls` are recorded means that where nested calls are " "made, the parameters of ancestor calls are not recorded and so will always " "compare equal:" msgstr "" -#: ../../library/unittest.mock.rst:740 +#: ../../library/unittest.mock.rst:763 msgid "" -"Normally the :attr:`__class__` attribute of an object will return its type. " -"For a mock object with a :attr:`spec`, ``__class__`` returns the spec class " -"instead. This allows mock objects to pass :func:`isinstance` tests for the " -"object they are replacing / masquerading as:" +"Normally the :attr:`!__class__` attribute of an object will return its type. " +"For a mock object with a :attr:`!spec`, :attr:`!__class__` returns the spec " +"class instead. This allows mock objects to pass :func:`isinstance` tests for " +"the object they are replacing / masquerading as:" msgstr "" -#: ../../library/unittest.mock.rst:749 +#: ../../library/unittest.mock.rst:772 msgid "" -":attr:`__class__` is assignable to, this allows a mock to pass an :func:" +":attr:`!__class__` is assignable to, this allows a mock to pass an :func:" "`isinstance` check without forcing you to use a spec:" msgstr "" -#: ../../library/unittest.mock.rst:759 +#: ../../library/unittest.mock.rst:782 msgid "" "A non-callable version of :class:`Mock`. The constructor parameters have the " "same meaning of :class:`Mock`, with the exception of *return_value* and " "*side_effect* which have no meaning on a non-callable mock." msgstr "" -#: ../../library/unittest.mock.rst:763 +#: ../../library/unittest.mock.rst:786 msgid "" -"Mock objects that use a class or an instance as a :attr:`spec` or :attr:" -"`spec_set` are able to pass :func:`isinstance` tests:" +"Mock objects that use a class or an instance as a :attr:`!spec` or :attr:`!" +"spec_set` are able to pass :func:`isinstance` tests:" msgstr "" -#: ../../library/unittest.mock.rst:773 +#: ../../library/unittest.mock.rst:796 msgid "" "The :class:`Mock` classes have support for mocking magic methods. See :ref:" "`magic methods ` for the full details." msgstr "" -#: ../../library/unittest.mock.rst:776 +#: ../../library/unittest.mock.rst:799 msgid "" "The mock classes and the :func:`patch` decorators all take arbitrary keyword " "arguments for configuration. For the :func:`patch` decorators the keywords " @@ -706,14 +760,14 @@ msgid "" "arguments are for configuring attributes of the mock:" msgstr "" -#: ../../library/unittest.mock.rst:787 +#: ../../library/unittest.mock.rst:810 msgid "" "The return value and side effect of child mocks can be set in the same way, " "using dotted notation. As you can't use dotted names directly in a call you " "have to create a dictionary and unpack it using ``**``:" msgstr "" -#: ../../library/unittest.mock.rst:802 +#: ../../library/unittest.mock.rst:825 msgid "" "A callable mock which was created with a *spec* (or a *spec_set*) will " "introspect the specification object's signature when matching calls to the " @@ -721,7 +775,18 @@ msgid "" "whether they were passed positionally or by name::" msgstr "" -#: ../../library/unittest.mock.rst:815 +#: ../../library/unittest.mock.rst:830 +msgid "" +">>> def f(a, b, c): pass\n" +"...\n" +">>> mock = Mock(spec=f)\n" +">>> mock(1, 2, c=3)\n" +"\n" +">>> mock.assert_called_with(1, 2, 3)\n" +">>> mock.assert_called_with(a=1, b=2, c=3)" +msgstr "" + +#: ../../library/unittest.mock.rst:838 msgid "" "This applies to :meth:`~Mock.assert_called_with`, :meth:`~Mock." "assert_called_once_with`, :meth:`~Mock.assert_has_calls` and :meth:`~Mock." @@ -729,13 +794,13 @@ msgid "" "calls on the mock object." msgstr "" -#: ../../library/unittest.mock.rst:820 +#: ../../library/unittest.mock.rst:843 msgid "Added signature introspection on specced and autospecced mock objects." msgstr "" "Adicionada introspecção de assinatura em objetos mock especificados e auto-" "especificados." -#: ../../library/unittest.mock.rst:826 +#: ../../library/unittest.mock.rst:849 msgid "" "A mock intended to be used as a :class:`property`, or other :term:" "`descriptor`, on a class. :class:`PropertyMock` provides :meth:`~object." @@ -743,76 +808,116 @@ msgid "" "value when it is fetched." msgstr "" -#: ../../library/unittest.mock.rst:831 +#: ../../library/unittest.mock.rst:854 msgid "" "Fetching a :class:`PropertyMock` instance from an object calls the mock, " "with no args. Setting it calls the mock with the value being set. ::" msgstr "" -#: ../../library/unittest.mock.rst:852 +#: ../../library/unittest.mock.rst:857 +msgid "" +">>> class Foo:\n" +"... @property\n" +"... def foo(self):\n" +"... return 'something'\n" +"... @foo.setter\n" +"... def foo(self, value):\n" +"... pass\n" +"...\n" +">>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:\n" +"... mock_foo.return_value = 'mockity-mock'\n" +"... this_foo = Foo()\n" +"... print(this_foo.foo)\n" +"... this_foo.foo = 6\n" +"...\n" +"mockity-mock\n" +">>> mock_foo.mock_calls\n" +"[call(), call(6)]" +msgstr "" + +#: ../../library/unittest.mock.rst:875 msgid "" "Because of the way mock attributes are stored you can't directly attach a :" "class:`PropertyMock` to a mock object. Instead you can attach it to the mock " "type object::" msgstr "" -#: ../../library/unittest.mock.rst:865 +#: ../../library/unittest.mock.rst:879 +msgid "" +">>> m = MagicMock()\n" +">>> p = PropertyMock(return_value=3)\n" +">>> type(m).foo = p\n" +">>> m.foo\n" +"3\n" +">>> p.assert_called_once_with()" +msgstr "" + +#: ../../library/unittest.mock.rst:888 msgid "" "If an :exc:`AttributeError` is raised by :class:`PropertyMock`, it will be " "interpreted as a missing descriptor and :meth:`~object.__getattr__` will be " "called on the parent mock::" msgstr "" -#: ../../library/unittest.mock.rst:875 +#: ../../library/unittest.mock.rst:892 +msgid "" +">>> m = MagicMock()\n" +">>> no_attribute = PropertyMock(side_effect=AttributeError)\n" +">>> type(m).my_property = no_attribute\n" +">>> m.my_property\n" +"" +msgstr "" + +#: ../../library/unittest.mock.rst:898 msgid "See :meth:`~object.__getattr__` for details." msgstr "" -#: ../../library/unittest.mock.rst:880 +#: ../../library/unittest.mock.rst:903 msgid "" "An asynchronous version of :class:`MagicMock`. The :class:`AsyncMock` object " "will behave so the object is recognized as an async function, and the result " "of a call is an awaitable." msgstr "" -#: ../../library/unittest.mock.rst:890 +#: ../../library/unittest.mock.rst:913 msgid "" "The result of ``mock()`` is an async function which will have the outcome of " "``side_effect`` or ``return_value`` after it has been awaited:" msgstr "" -#: ../../library/unittest.mock.rst:893 +#: ../../library/unittest.mock.rst:916 msgid "" "if ``side_effect`` is a function, the async function will return the result " "of that function," msgstr "" -#: ../../library/unittest.mock.rst:895 +#: ../../library/unittest.mock.rst:918 msgid "" "if ``side_effect`` is an exception, the async function will raise the " "exception," msgstr "" -#: ../../library/unittest.mock.rst:897 +#: ../../library/unittest.mock.rst:920 msgid "" "if ``side_effect`` is an iterable, the async function will return the next " "value of the iterable, however, if the sequence of result is exhausted, " "``StopAsyncIteration`` is raised immediately," msgstr "" -#: ../../library/unittest.mock.rst:900 +#: ../../library/unittest.mock.rst:923 msgid "" "if ``side_effect`` is not defined, the async function will return the value " "defined by ``return_value``, hence, by default, the async function returns a " "new :class:`AsyncMock` object." msgstr "" -#: ../../library/unittest.mock.rst:905 +#: ../../library/unittest.mock.rst:928 msgid "" "Setting the *spec* of a :class:`Mock` or :class:`MagicMock` to an async " "function will result in a coroutine object being returned after calling." msgstr "" -#: ../../library/unittest.mock.rst:917 +#: ../../library/unittest.mock.rst:940 msgid "" "Setting the *spec* of a :class:`Mock`, :class:`MagicMock`, or :class:" "`AsyncMock` to a class with asynchronous and synchronous functions will " @@ -822,129 +927,129 @@ msgid "" "functions will be :class:`AsyncMock`." msgstr "" -#: ../../library/unittest.mock.rst:945 +#: ../../library/unittest.mock.rst:968 msgid "" "Assert that the mock was awaited at least once. Note that this is separate " "from the object having been called, the ``await`` keyword must be used:" msgstr "" -#: ../../library/unittest.mock.rst:964 +#: ../../library/unittest.mock.rst:987 msgid "Assert that the mock was awaited exactly once." msgstr "Afirme que o mock foi aguardado exatamente uma vez." -#: ../../library/unittest.mock.rst:980 +#: ../../library/unittest.mock.rst:1003 msgid "Assert that the last await was with the specified arguments." msgstr "" -#: ../../library/unittest.mock.rst:997 +#: ../../library/unittest.mock.rst:1020 msgid "" "Assert that the mock was awaited exactly once and with the specified " "arguments." msgstr "" -#: ../../library/unittest.mock.rst:1014 +#: ../../library/unittest.mock.rst:1037 msgid "Assert the mock has ever been awaited with the specified arguments." msgstr "" -#: ../../library/unittest.mock.rst:1030 +#: ../../library/unittest.mock.rst:1053 msgid "" "Assert the mock has been awaited with the specified calls. The :attr:" "`await_args_list` list is checked for the awaits." msgstr "" -#: ../../library/unittest.mock.rst:1033 +#: ../../library/unittest.mock.rst:1056 msgid "" "If *any_order* is false then the awaits must be sequential. There can be " "extra calls before or after the specified awaits." msgstr "" -#: ../../library/unittest.mock.rst:1037 +#: ../../library/unittest.mock.rst:1060 msgid "" "If *any_order* is true then the awaits can be in any order, but they must " "all appear in :attr:`await_args_list`." msgstr "" -#: ../../library/unittest.mock.rst:1057 +#: ../../library/unittest.mock.rst:1080 msgid "Assert that the mock was never awaited." msgstr "Afirma que o mock nunca foi aguardado." -#: ../../library/unittest.mock.rst:1064 +#: ../../library/unittest.mock.rst:1087 msgid "" "See :func:`Mock.reset_mock`. Also sets :attr:`await_count` to 0, :attr:" "`await_args` to None, and clears the :attr:`await_args_list`." msgstr "" -#: ../../library/unittest.mock.rst:1069 +#: ../../library/unittest.mock.rst:1092 msgid "" "An integer keeping track of how many times the mock object has been awaited." msgstr "" -#: ../../library/unittest.mock.rst:1084 +#: ../../library/unittest.mock.rst:1107 msgid "" "This is either ``None`` (if the mock hasn’t been awaited), or the arguments " "that the mock was last awaited with. Functions the same as :attr:`Mock." "call_args`." msgstr "" -#: ../../library/unittest.mock.rst:1102 +#: ../../library/unittest.mock.rst:1125 msgid "" "This is a list of all the awaits made to the mock object in sequence (so the " "length of the list is the number of times it has been awaited). Before any " "awaits have been made it is an empty list." msgstr "" -#: ../../library/unittest.mock.rst:1122 +#: ../../library/unittest.mock.rst:1145 msgid "" "A version of :class:`MagicMock` for multithreading tests. The :class:" "`ThreadingMock` object provides extra methods to wait for a call to be " "invoked, rather than assert on it immediately." msgstr "" -#: ../../library/unittest.mock.rst:1126 +#: ../../library/unittest.mock.rst:1149 msgid "" "The default timeout is specified by the ``timeout`` argument, or if unset by " "the :attr:`ThreadingMock.DEFAULT_TIMEOUT` attribute, which defaults to " "blocking (``None``)." msgstr "" -#: ../../library/unittest.mock.rst:1129 +#: ../../library/unittest.mock.rst:1152 msgid "" "You can configure the global default timeout by setting :attr:`ThreadingMock." "DEFAULT_TIMEOUT`." msgstr "" -#: ../../library/unittest.mock.rst:1133 +#: ../../library/unittest.mock.rst:1156 msgid "Waits until the mock is called." msgstr "" -#: ../../library/unittest.mock.rst:1135 +#: ../../library/unittest.mock.rst:1158 msgid "" "If a timeout was passed at the creation of the mock or if a timeout argument " "is passed to this function, the function raises an :exc:`AssertionError` if " "the call is not performed in time." msgstr "" -#: ../../library/unittest.mock.rst:1147 +#: ../../library/unittest.mock.rst:1170 msgid "Waits until the mock is called with the specified arguments." msgstr "" -#: ../../library/unittest.mock.rst:1149 +#: ../../library/unittest.mock.rst:1172 msgid "" "If a timeout was passed at the creation of the mock the function raises an :" "exc:`AssertionError` if the call is not performed in time." msgstr "" -#: ../../library/unittest.mock.rst:1160 +#: ../../library/unittest.mock.rst:1183 msgid "" "Global default timeout in seconds to create instances of :class:" "`ThreadingMock`." msgstr "" -#: ../../library/unittest.mock.rst:1166 +#: ../../library/unittest.mock.rst:1189 msgid "Calling" msgstr "Fazendo chamadas" -#: ../../library/unittest.mock.rst:1168 +#: ../../library/unittest.mock.rst:1191 msgid "" "Mock objects are callable. The call will return the value set as the :attr:" "`~Mock.return_value` attribute. The default return value is a new Mock " @@ -953,89 +1058,103 @@ msgid "" "returned each time." msgstr "" -#: ../../library/unittest.mock.rst:1174 +#: ../../library/unittest.mock.rst:1197 msgid "" "Calls made to the object will be recorded in the attributes like :attr:" "`~Mock.call_args` and :attr:`~Mock.call_args_list`." msgstr "" -#: ../../library/unittest.mock.rst:1177 +#: ../../library/unittest.mock.rst:1200 msgid "" "If :attr:`~Mock.side_effect` is set then it will be called after the call " -"has been recorded, so if :attr:`side_effect` raises an exception the call is " -"still recorded." +"has been recorded, so if :attr:`!side_effect` raises an exception the call " +"is still recorded." msgstr "" -#: ../../library/unittest.mock.rst:1181 +#: ../../library/unittest.mock.rst:1204 msgid "" "The simplest way to make a mock raise an exception when called is to make :" "attr:`~Mock.side_effect` an exception class or instance:" msgstr "" -#: ../../library/unittest.mock.rst:1199 +#: ../../library/unittest.mock.rst:1222 msgid "" -"If :attr:`side_effect` is a function then whatever that function returns is " -"what calls to the mock return. The :attr:`side_effect` function is called " -"with the same arguments as the mock. This allows you to vary the return " -"value of the call dynamically, based on the input:" +"If :attr:`~Mock.side_effect` is a function then whatever that function " +"returns is what calls to the mock return. The :attr:`!side_effect` function " +"is called with the same arguments as the mock. This allows you to vary the " +"return value of the call dynamically, based on the input:" msgstr "" -#: ../../library/unittest.mock.rst:1215 +#: ../../library/unittest.mock.rst:1238 msgid "" "If you want the mock to still return the default return value (a new mock), " "or any set return value, then there are two ways of doing this. Either " -"return :attr:`mock.return_value` from inside :attr:`side_effect`, or return :" -"data:`DEFAULT`:" +"return :attr:`~Mock.return_value` from inside :attr:`~Mock.side_effect`, or " +"return :data:`DEFAULT`:" msgstr "" -#: ../../library/unittest.mock.rst:1234 +#: ../../library/unittest.mock.rst:1257 msgid "" -"To remove a :attr:`side_effect`, and return to the default behaviour, set " -"the :attr:`side_effect` to ``None``:" +"To remove a :attr:`~Mock.side_effect`, and return to the default behaviour, " +"set the :attr:`!side_effect` to ``None``:" msgstr "" -#: ../../library/unittest.mock.rst:1248 +#: ../../library/unittest.mock.rst:1271 msgid "" -"The :attr:`side_effect` can also be any iterable object. Repeated calls to " -"the mock will return values from the iterable (until the iterable is " -"exhausted and a :exc:`StopIteration` is raised):" +"The :attr:`~Mock.side_effect` can also be any iterable object. Repeated " +"calls to the mock will return values from the iterable (until the iterable " +"is exhausted and a :exc:`StopIteration` is raised):" msgstr "" -#: ../../library/unittest.mock.rst:1264 +#: ../../library/unittest.mock.rst:1287 msgid "" "If any members of the iterable are exceptions they will be raised instead of " "returned::" msgstr "" -#: ../../library/unittest.mock.rst:1282 +#: ../../library/unittest.mock.rst:1290 +msgid "" +">>> iterable = (33, ValueError, 66)\n" +">>> m = MagicMock(side_effect=iterable)\n" +">>> m()\n" +"33\n" +">>> m()\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError\n" +">>> m()\n" +"66" +msgstr "" + +#: ../../library/unittest.mock.rst:1305 msgid "Deleting Attributes" msgstr "Deletando Atributos" -#: ../../library/unittest.mock.rst:1284 +#: ../../library/unittest.mock.rst:1307 msgid "" "Mock objects create attributes on demand. This allows them to pretend to be " "objects of any type." msgstr "" -#: ../../library/unittest.mock.rst:1287 +#: ../../library/unittest.mock.rst:1310 msgid "" "You may want a mock object to return ``False`` to a :func:`hasattr` call, or " "raise an :exc:`AttributeError` when an attribute is fetched. You can do this " -"by providing an object as a :attr:`spec` for a mock, but that isn't always " +"by providing an object as a :attr:`!spec` for a mock, but that isn't always " "convenient." msgstr "" -#: ../../library/unittest.mock.rst:1291 +#: ../../library/unittest.mock.rst:1314 msgid "" "You \"block\" attributes by deleting them. Once deleted, accessing an " "attribute will raise an :exc:`AttributeError`." msgstr "" -#: ../../library/unittest.mock.rst:1308 +#: ../../library/unittest.mock.rst:1331 msgid "Mock names and the name attribute" msgstr "Nomes de Mock e o atributo *name*" -#: ../../library/unittest.mock.rst:1310 +#: ../../library/unittest.mock.rst:1333 msgid "" "Since \"name\" is an argument to the :class:`Mock` constructor, if you want " "your mock object to have a \"name\" attribute you can't just pass it in at " @@ -1043,17 +1162,31 @@ msgid "" "configure_mock`::" msgstr "" -#: ../../library/unittest.mock.rst:1320 +#: ../../library/unittest.mock.rst:1338 +msgid "" +">>> mock = MagicMock()\n" +">>> mock.configure_mock(name='my_name')\n" +">>> mock.name\n" +"'my_name'" +msgstr "" + +#: ../../library/unittest.mock.rst:1343 msgid "" "A simpler option is to simply set the \"name\" attribute after mock " "creation::" msgstr "" -#: ../../library/unittest.mock.rst:1327 +#: ../../library/unittest.mock.rst:1345 +msgid "" +">>> mock = MagicMock()\n" +">>> mock.name = \"foo\"" +msgstr "" + +#: ../../library/unittest.mock.rst:1350 msgid "Attaching Mocks as Attributes" msgstr "Anexando Mocks como Atributos" -#: ../../library/unittest.mock.rst:1329 +#: ../../library/unittest.mock.rst:1352 msgid "" "When you attach a mock as an attribute of another mock (or as the return " "value) it becomes a \"child\" of that mock. Calls to the child are recorded " @@ -1064,20 +1197,36 @@ msgid "" "calls between mocks:" msgstr "" -#: ../../library/unittest.mock.rst:1347 +#: ../../library/unittest.mock.rst:1370 msgid "" "The exception to this is if the mock has a name. This allows you to prevent " "the \"parenting\" if for some reason you don't want it to happen." msgstr "" -#: ../../library/unittest.mock.rst:1358 +#: ../../library/unittest.mock.rst:1381 msgid "" "Mocks created for you by :func:`patch` are automatically given names. To " "attach mocks that have names to a parent you use the :meth:`~Mock." "attach_mock` method::" msgstr "" -#: ../../library/unittest.mock.rst:1376 +#: ../../library/unittest.mock.rst:1385 +msgid "" +">>> thing1 = object()\n" +">>> thing2 = object()\n" +">>> parent = MagicMock()\n" +">>> with patch('__main__.thing1', return_value=None) as child1:\n" +"... with patch('__main__.thing2', return_value=None) as child2:\n" +"... parent.attach_mock(child1, 'child1')\n" +"... parent.attach_mock(child2, 'child2')\n" +"... child1('one')\n" +"... child2('two')\n" +"...\n" +">>> parent.mock_calls\n" +"[call.child1('one'), call.child2('two')]" +msgstr "" + +#: ../../library/unittest.mock.rst:1399 msgid "" "The only exceptions are magic methods and attributes (those that have " "leading and trailing double underscores). Mock doesn't create these but " @@ -1087,11 +1236,11 @@ msgid "" "support see :ref:`magic methods `." msgstr "" -#: ../../library/unittest.mock.rst:1385 +#: ../../library/unittest.mock.rst:1408 msgid "The patchers" msgstr "Os criadores de patches" -#: ../../library/unittest.mock.rst:1387 +#: ../../library/unittest.mock.rst:1410 msgid "" "The patch decorators are used for patching objects only within the scope of " "the function they decorate. They automatically handle the unpatching for " @@ -1099,17 +1248,17 @@ msgid "" "in with statements or as class decorators." msgstr "" -#: ../../library/unittest.mock.rst:1394 +#: ../../library/unittest.mock.rst:1417 msgid "patch" msgstr "patch" -#: ../../library/unittest.mock.rst:1398 +#: ../../library/unittest.mock.rst:1421 msgid "" "The key is to do the patching in the right namespace. See the section `where " "to patch`_." msgstr "" -#: ../../library/unittest.mock.rst:1402 +#: ../../library/unittest.mock.rst:1425 msgid "" ":func:`patch` acts as a function decorator, class decorator or a context " "manager. Inside the body of the function or with statement, the *target* is " @@ -1117,7 +1266,7 @@ msgid "" "patch is undone." msgstr "" -#: ../../library/unittest.mock.rst:1407 +#: ../../library/unittest.mock.rst:1430 msgid "" "If *new* is omitted, then the target is replaced with an :class:`AsyncMock` " "if the patched object is an async function or a :class:`MagicMock` " @@ -1127,7 +1276,7 @@ msgid "" "by the context manager." msgstr "" -#: ../../library/unittest.mock.rst:1415 +#: ../../library/unittest.mock.rst:1438 msgid "" "*target* should be a string in the form ``'package.module.ClassName'``. The " "*target* is imported and the specified object replaced with the *new* " @@ -1136,26 +1285,26 @@ msgid "" "function is executed, not at decoration time." msgstr "" -#: ../../library/unittest.mock.rst:1421 +#: ../../library/unittest.mock.rst:1444 msgid "" "The *spec* and *spec_set* keyword arguments are passed to the :class:" "`MagicMock` if patch is creating one for you." msgstr "" -#: ../../library/unittest.mock.rst:1424 +#: ../../library/unittest.mock.rst:1447 msgid "" "In addition you can pass ``spec=True`` or ``spec_set=True``, which causes " "patch to pass in the object being mocked as the spec/spec_set object." msgstr "" -#: ../../library/unittest.mock.rst:1427 +#: ../../library/unittest.mock.rst:1450 msgid "" "*new_callable* allows you to specify a different class, or callable object, " "that will be called to create the *new* object. By default :class:" "`AsyncMock` is used for async functions and :class:`MagicMock` for the rest." msgstr "" -#: ../../library/unittest.mock.rst:1431 +#: ../../library/unittest.mock.rst:1454 msgid "" "A more powerful form of *spec* is *autospec*. If you set ``autospec=True`` " "then the mock will be created with a spec from the object being replaced. " @@ -1167,13 +1316,13 @@ msgid "" "func:`create_autospec` function and :ref:`auto-speccing`." msgstr "" -#: ../../library/unittest.mock.rst:1441 +#: ../../library/unittest.mock.rst:1464 msgid "" "Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an " "arbitrary object as the spec instead of the one being replaced." msgstr "" -#: ../../library/unittest.mock.rst:1444 +#: ../../library/unittest.mock.rst:1467 msgid "" "By default :func:`patch` will fail to replace attributes that don't exist. " "If you pass in ``create=True``, and the attribute doesn't exist, patch will " @@ -1184,24 +1333,24 @@ msgid "" "write passing tests against APIs that don't actually exist!" msgstr "" -#: ../../library/unittest.mock.rst:1454 +#: ../../library/unittest.mock.rst:1477 msgid "" "If you are patching builtins in a module then you don't need to pass " "``create=True``, it will be added by default." msgstr "" -#: ../../library/unittest.mock.rst:1458 +#: ../../library/unittest.mock.rst:1481 msgid "" -"Patch can be used as a :class:`TestCase` class decorator. It works by " -"decorating each test method in the class. This reduces the boilerplate code " -"when your test methods share a common patchings set. :func:`patch` finds " -"tests by looking for method names that start with ``patch.TEST_PREFIX``. By " -"default this is ``'test'``, which matches the way :mod:`unittest` finds " -"tests. You can specify an alternative prefix by setting ``patch." -"TEST_PREFIX``." +"Patch can be used as a :class:`~unittest.TestCase` class decorator. It works " +"by decorating each test method in the class. This reduces the boilerplate " +"code when your test methods share a common patchings set. :func:`patch` " +"finds tests by looking for method names that start with ``patch." +"TEST_PREFIX``. By default this is ``'test'``, which matches the way :mod:" +"`unittest` finds tests. You can specify an alternative prefix by setting " +"``patch.TEST_PREFIX``." msgstr "" -#: ../../library/unittest.mock.rst:1465 +#: ../../library/unittest.mock.rst:1488 msgid "" "Patch can be used as a context manager, with the with statement. Here the " "patching applies to the indented block after the with statement. If you use " @@ -1209,14 +1358,14 @@ msgid "" "very useful if :func:`patch` is creating a mock object for you." msgstr "" -#: ../../library/unittest.mock.rst:1470 +#: ../../library/unittest.mock.rst:1493 msgid "" ":func:`patch` takes arbitrary keyword arguments. These will be passed to :" "class:`AsyncMock` if the patched object is asynchronous, to :class:" "`MagicMock` otherwise or to *new_callable* if specified." msgstr "" -#: ../../library/unittest.mock.rst:1474 +#: ../../library/unittest.mock.rst:1497 msgid "" "``patch.dict(...)``, ``patch.multiple(...)`` and ``patch.object(...)`` are " "available for alternate use-cases." @@ -1224,52 +1373,113 @@ msgstr "" "``patch.dict(...)``, ``patch.multiple(...)`` e ``patch.object(...)`` estão " "disponíveis para casos de uso alternativos." -#: ../../library/unittest.mock.rst:1477 +#: ../../library/unittest.mock.rst:1500 msgid "" ":func:`patch` as function decorator, creating the mock for you and passing " "it into the decorated function::" msgstr "" -#: ../../library/unittest.mock.rst:1487 +#: ../../library/unittest.mock.rst:1503 +msgid "" +">>> @patch('__main__.SomeClass')\n" +"... def function(normal_argument, mock_class):\n" +"... print(mock_class is SomeClass)\n" +"...\n" +">>> function(None)\n" +"True" +msgstr "" + +#: ../../library/unittest.mock.rst:1510 msgid "" "Patching a class replaces the class with a :class:`MagicMock` *instance*. If " "the class is instantiated in the code under test then it will be the :attr:" "`~Mock.return_value` of the mock that will be used." msgstr "" -#: ../../library/unittest.mock.rst:1491 +#: ../../library/unittest.mock.rst:1514 msgid "" "If the class is instantiated multiple times you could use :attr:`~Mock." "side_effect` to return a new mock each time. Alternatively you can set the " "*return_value* to be anything you want." msgstr "" -#: ../../library/unittest.mock.rst:1495 +#: ../../library/unittest.mock.rst:1518 msgid "" "To configure return values on methods of *instances* on the patched class " -"you must do this on the :attr:`return_value`. For example::" +"you must do this on the :attr:`~Mock.return_value`. For example::" msgstr "" -#: ../../library/unittest.mock.rst:1509 +#: ../../library/unittest.mock.rst:1521 +msgid "" +">>> class Class:\n" +"... def method(self):\n" +"... pass\n" +"...\n" +">>> with patch('__main__.Class') as MockClass:\n" +"... instance = MockClass.return_value\n" +"... instance.method.return_value = 'foo'\n" +"... assert Class() is instance\n" +"... assert Class().method() == 'foo'\n" +"..." +msgstr "" + +#: ../../library/unittest.mock.rst:1532 msgid "" "If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, " "then the return value of the created mock will have the same spec. ::" msgstr "" -#: ../../library/unittest.mock.rst:1519 +#: ../../library/unittest.mock.rst:1535 +msgid "" +">>> Original = Class\n" +">>> patcher = patch('__main__.Class', spec=True)\n" +">>> MockClass = patcher.start()\n" +">>> instance = MockClass()\n" +">>> assert isinstance(instance, Original)\n" +">>> patcher.stop()" +msgstr "" + +#: ../../library/unittest.mock.rst:1542 msgid "" "The *new_callable* argument is useful where you want to use an alternative " "class to the default :class:`MagicMock` for the created mock. For example, " "if you wanted a :class:`NonCallableMock` to be used::" msgstr "" -#: ../../library/unittest.mock.rst:1532 +#: ../../library/unittest.mock.rst:1546 +msgid "" +">>> thing = object()\n" +">>> with patch('__main__.thing', new_callable=NonCallableMock) as " +"mock_thing:\n" +"... assert thing is mock_thing\n" +"... thing()\n" +"...\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: 'NonCallableMock' object is not callable" +msgstr "" + +#: ../../library/unittest.mock.rst:1555 msgid "" "Another use case might be to replace an object with an :class:`io.StringIO` " "instance::" msgstr "" -#: ../../library/unittest.mock.rst:1545 +#: ../../library/unittest.mock.rst:1557 +msgid "" +">>> from io import StringIO\n" +">>> def foo():\n" +"... print('Something')\n" +"...\n" +">>> @patch('sys.stdout', new_callable=StringIO)\n" +"... def test(mock_stdout):\n" +"... foo()\n" +"... assert mock_stdout.getvalue() == 'Something\\n'\n" +"...\n" +">>> test()" +msgstr "" + +#: ../../library/unittest.mock.rst:1568 msgid "" "When :func:`patch` is creating a mock for you, it is common that the first " "thing you need to do is to configure the mock. Some of that configuration " @@ -1277,7 +1487,17 @@ msgid "" "call will be used to set attributes on the created mock::" msgstr "" -#: ../../library/unittest.mock.rst:1557 +#: ../../library/unittest.mock.rst:1573 +msgid "" +">>> patcher = patch('__main__.thing', first='one', second='two')\n" +">>> mock_thing = patcher.start()\n" +">>> mock_thing.first\n" +"'one'\n" +">>> mock_thing.second\n" +"'two'" +msgstr "" + +#: ../../library/unittest.mock.rst:1580 msgid "" "As well as attributes on the created mock attributes, like the :attr:`~Mock." "return_value` and :attr:`~Mock.side_effect`, of child mocks can also be " @@ -1286,36 +1506,71 @@ msgid "" "func:`patch` call using ``**``::" msgstr "" -#: ../../library/unittest.mock.rst:1573 +#: ../../library/unittest.mock.rst:1586 +msgid "" +">>> config = {'method.return_value': 3, 'other.side_effect': KeyError}\n" +">>> patcher = patch('__main__.thing', **config)\n" +">>> mock_thing = patcher.start()\n" +">>> mock_thing.method()\n" +"3\n" +">>> mock_thing.other()\n" +"Traceback (most recent call last):\n" +" ...\n" +"KeyError" +msgstr "" + +#: ../../library/unittest.mock.rst:1596 msgid "" "By default, attempting to patch a function in a module (or a method or an " "attribute in a class) that does not exist will fail with :exc:" "`AttributeError`::" msgstr "" -#: ../../library/unittest.mock.rst:1585 +#: ../../library/unittest.mock.rst:1599 +msgid "" +">>> @patch('sys.non_existing_attribute', 42)\n" +"... def test():\n" +"... assert sys.non_existing_attribute == 42\n" +"...\n" +">>> test()\n" +"Traceback (most recent call last):\n" +" ...\n" +"AttributeError: does not have the attribute " +"'non_existing_attribute'" +msgstr "" + +#: ../../library/unittest.mock.rst:1608 msgid "" "but adding ``create=True`` in the call to :func:`patch` will make the " "previous example work as expected::" msgstr "" -#: ../../library/unittest.mock.rst:1596 +#: ../../library/unittest.mock.rst:1611 +msgid "" +">>> @patch('sys.non_existing_attribute', 42, create=True)\n" +"... def test(mock_stdout):\n" +"... assert sys.non_existing_attribute == 42\n" +"...\n" +">>> test()" +msgstr "" + +#: ../../library/unittest.mock.rst:1619 msgid "" ":func:`patch` now returns an :class:`AsyncMock` if the target is an async " "function." msgstr "" -#: ../../library/unittest.mock.rst:1600 +#: ../../library/unittest.mock.rst:1623 msgid "patch.object" msgstr "patch.object" -#: ../../library/unittest.mock.rst:1604 +#: ../../library/unittest.mock.rst:1627 msgid "" "patch the named member (*attribute*) on an object (*target*) with a mock " "object." msgstr "" -#: ../../library/unittest.mock.rst:1607 +#: ../../library/unittest.mock.rst:1630 msgid "" ":func:`patch.object` can be used as a decorator, class decorator or a " "context manager. Arguments *new*, *spec*, *create*, *spec_set*, *autospec* " @@ -1324,112 +1579,112 @@ msgid "" "configuring the mock object it creates." msgstr "" -#: ../../library/unittest.mock.rst:1613 +#: ../../library/unittest.mock.rst:1636 msgid "" "When used as a class decorator :func:`patch.object` honours ``patch." "TEST_PREFIX`` for choosing which methods to wrap." msgstr "" -#: ../../library/unittest.mock.rst:1616 +#: ../../library/unittest.mock.rst:1639 msgid "" "You can either call :func:`patch.object` with three arguments or two " "arguments. The three argument form takes the object to be patched, the " "attribute name and the object to replace the attribute with." msgstr "" -#: ../../library/unittest.mock.rst:1620 +#: ../../library/unittest.mock.rst:1643 msgid "" "When calling with the two argument form you omit the replacement object, and " "a mock is created for you and passed in as an extra argument to the " "decorated function:" msgstr "" -#: ../../library/unittest.mock.rst:1631 +#: ../../library/unittest.mock.rst:1654 msgid "" "*spec*, *create* and the other arguments to :func:`patch.object` have the " "same meaning as they do for :func:`patch`." msgstr "" -#: ../../library/unittest.mock.rst:1636 +#: ../../library/unittest.mock.rst:1659 msgid "patch.dict" msgstr "patch.dict" -#: ../../library/unittest.mock.rst:1640 +#: ../../library/unittest.mock.rst:1663 msgid "" "Patch a dictionary, or dictionary like object, and restore the dictionary to " "its original state after the test." msgstr "" -#: ../../library/unittest.mock.rst:1643 +#: ../../library/unittest.mock.rst:1666 msgid "" "*in_dict* can be a dictionary or a mapping like container. If it is a " "mapping then it must at least support getting, setting and deleting items " "plus iterating over keys." msgstr "" -#: ../../library/unittest.mock.rst:1647 +#: ../../library/unittest.mock.rst:1670 msgid "" "*in_dict* can also be a string specifying the name of the dictionary, which " "will then be fetched by importing it." msgstr "" -#: ../../library/unittest.mock.rst:1650 +#: ../../library/unittest.mock.rst:1673 msgid "" "*values* can be a dictionary of values to set in the dictionary. *values* " "can also be an iterable of ``(key, value)`` pairs." msgstr "" -#: ../../library/unittest.mock.rst:1653 +#: ../../library/unittest.mock.rst:1676 msgid "" "If *clear* is true then the dictionary will be cleared before the new values " "are set." msgstr "" -#: ../../library/unittest.mock.rst:1656 +#: ../../library/unittest.mock.rst:1679 msgid "" ":func:`patch.dict` can also be called with arbitrary keyword arguments to " "set values in the dictionary." msgstr "" -#: ../../library/unittest.mock.rst:1661 +#: ../../library/unittest.mock.rst:1684 msgid "" ":func:`patch.dict` now returns the patched dictionary when used as a context " "manager." msgstr "" -#: ../../library/unittest.mock.rst:1664 +#: ../../library/unittest.mock.rst:1687 msgid "" ":func:`patch.dict` can be used as a context manager, decorator or class " "decorator:" msgstr "" -#: ../../library/unittest.mock.rst:1675 +#: ../../library/unittest.mock.rst:1698 msgid "" "When used as a class decorator :func:`patch.dict` honours ``patch." "TEST_PREFIX`` (default to ``'test'``) for choosing which methods to wrap:" msgstr "" -#: ../../library/unittest.mock.rst:1686 +#: ../../library/unittest.mock.rst:1709 msgid "" "If you want to use a different prefix for your test, you can inform the " "patchers of the different prefix by setting ``patch.TEST_PREFIX``. For more " "details about how to change the value of see :ref:`test-prefix`." msgstr "" -#: ../../library/unittest.mock.rst:1690 +#: ../../library/unittest.mock.rst:1713 msgid "" ":func:`patch.dict` can be used to add members to a dictionary, or simply let " "a test change a dictionary, and ensure the dictionary is restored when the " "test ends." msgstr "" -#: ../../library/unittest.mock.rst:1711 +#: ../../library/unittest.mock.rst:1734 msgid "" "Keywords can be used in the :func:`patch.dict` call to set values in the " "dictionary:" msgstr "" -#: ../../library/unittest.mock.rst:1721 +#: ../../library/unittest.mock.rst:1744 msgid "" ":func:`patch.dict` can be used with dictionary like objects that aren't " "actually dictionaries. At the very minimum they must support item getting, " @@ -1439,18 +1694,24 @@ msgid "" "__iter__` or :meth:`~object.__contains__`." msgstr "" -#: ../../library/unittest.mock.rst:1751 +#: ../../library/unittest.mock.rst:1774 msgid "patch.multiple" msgstr "patch.multiple" -#: ../../library/unittest.mock.rst:1755 +#: ../../library/unittest.mock.rst:1778 msgid "" "Perform multiple patches in a single call. It takes the object to be patched " "(either as an object or a string to fetch the object by importing) and " "keyword arguments for the patches::" msgstr "" -#: ../../library/unittest.mock.rst:1762 +#: ../../library/unittest.mock.rst:1782 +msgid "" +"with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):\n" +" ..." +msgstr "" + +#: ../../library/unittest.mock.rst:1785 msgid "" "Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to " "create mocks for you. In this case the created mocks are passed into a " @@ -1458,7 +1719,7 @@ msgid "" "`patch.multiple` is used as a context manager." msgstr "" -#: ../../library/unittest.mock.rst:1767 +#: ../../library/unittest.mock.rst:1790 msgid "" ":func:`patch.multiple` can be used as a decorator, class decorator or a " "context manager. The arguments *spec*, *spec_set*, *create*, *autospec* and " @@ -1466,13 +1727,13 @@ msgid "" "will be applied to *all* patches done by :func:`patch.multiple`." msgstr "" -#: ../../library/unittest.mock.rst:1772 +#: ../../library/unittest.mock.rst:1795 msgid "" "When used as a class decorator :func:`patch.multiple` honours ``patch." "TEST_PREFIX`` for choosing which methods to wrap." msgstr "" -#: ../../library/unittest.mock.rst:1775 +#: ../../library/unittest.mock.rst:1798 msgid "" "If you want :func:`patch.multiple` to create mocks for you, then you can " "use :data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a " @@ -1480,52 +1741,121 @@ msgid "" "keyword. ::" msgstr "" -#: ../../library/unittest.mock.rst:1789 +#: ../../library/unittest.mock.rst:1802 +msgid "" +">>> thing = object()\n" +">>> other = object()\n" +"\n" +">>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)\n" +"... def test_function(thing, other):\n" +"... assert isinstance(thing, MagicMock)\n" +"... assert isinstance(other, MagicMock)\n" +"...\n" +">>> test_function()" +msgstr "" + +#: ../../library/unittest.mock.rst:1812 msgid "" ":func:`patch.multiple` can be nested with other ``patch`` decorators, but " "put arguments passed by keyword *after* any of the standard arguments " "created by :func:`patch`::" msgstr "" -#: ../../library/unittest.mock.rst:1801 +#: ../../library/unittest.mock.rst:1815 +msgid "" +">>> @patch('sys.exit')\n" +"... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)\n" +"... def test_function(mock_exit, other, thing):\n" +"... assert 'other' in repr(other)\n" +"... assert 'thing' in repr(thing)\n" +"... assert 'exit' in repr(mock_exit)\n" +"...\n" +">>> test_function()" +msgstr "" + +#: ../../library/unittest.mock.rst:1824 msgid "" "If :func:`patch.multiple` is used as a context manager, the value returned " "by the context manager is a dictionary where created mocks are keyed by " "name::" msgstr "" -#: ../../library/unittest.mock.rst:1815 +#: ../../library/unittest.mock.rst:1827 +msgid "" +">>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as " +"values:\n" +"... assert 'other' in repr(values['other'])\n" +"... assert 'thing' in repr(values['thing'])\n" +"... assert values['thing'] is thing\n" +"... assert values['other'] is other\n" +"..." +msgstr "" + +#: ../../library/unittest.mock.rst:1838 msgid "patch methods: start and stop" msgstr "métodos do patch: *start* e *stop*" -#: ../../library/unittest.mock.rst:1817 +#: ../../library/unittest.mock.rst:1840 msgid "" -"All the patchers have :meth:`start` and :meth:`stop` methods. These make it " -"simpler to do patching in ``setUp`` methods or where you want to do multiple " -"patches without nesting decorators or with statements." +"All the patchers have :meth:`!start` and :meth:`!stop` methods. These make " +"it simpler to do patching in ``setUp`` methods or where you want to do " +"multiple patches without nesting decorators or with statements." msgstr "" -#: ../../library/unittest.mock.rst:1821 +#: ../../library/unittest.mock.rst:1844 msgid "" "To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` " "as normal and keep a reference to the returned ``patcher`` object. You can " -"then call :meth:`start` to put the patch in place and :meth:`stop` to undo " +"then call :meth:`!start` to put the patch in place and :meth:`!stop` to undo " "it." msgstr "" -#: ../../library/unittest.mock.rst:1825 +#: ../../library/unittest.mock.rst:1848 msgid "" "If you are using :func:`patch` to create a mock for you then it will be " "returned by the call to ``patcher.start``. ::" msgstr "" -#: ../../library/unittest.mock.rst:1839 +#: ../../library/unittest.mock.rst:1851 +msgid "" +">>> patcher = patch('package.module.ClassName')\n" +">>> from package import module\n" +">>> original = module.ClassName\n" +">>> new_mock = patcher.start()\n" +">>> assert module.ClassName is not original\n" +">>> assert module.ClassName is new_mock\n" +">>> patcher.stop()\n" +">>> assert module.ClassName is original\n" +">>> assert module.ClassName is not new_mock" +msgstr "" + +#: ../../library/unittest.mock.rst:1862 msgid "" "A typical use case for this might be for doing multiple patches in the " -"``setUp`` method of a :class:`TestCase`::" +"``setUp`` method of a :class:`~unittest.TestCase`::" +msgstr "" + +#: ../../library/unittest.mock.rst:1865 +msgid "" +">>> class MyTest(unittest.TestCase):\n" +"... def setUp(self):\n" +"... self.patcher1 = patch('package.module.Class1')\n" +"... self.patcher2 = patch('package.module.Class2')\n" +"... self.MockClass1 = self.patcher1.start()\n" +"... self.MockClass2 = self.patcher2.start()\n" +"...\n" +"... def tearDown(self):\n" +"... self.patcher1.stop()\n" +"... self.patcher2.stop()\n" +"...\n" +"... def test_something(self):\n" +"... assert package.module.Class1 is self.MockClass1\n" +"... assert package.module.Class2 is self.MockClass2\n" +"...\n" +">>> MyTest('test_something').run()" msgstr "" -#: ../../library/unittest.mock.rst:1861 +#: ../../library/unittest.mock.rst:1884 msgid "" "If you use this technique you must ensure that the patching is \"undone\" by " "calling ``stop``. This can be fiddlier than you might think, because if an " @@ -1533,37 +1863,61 @@ msgid "" "`unittest.TestCase.addCleanup` makes this easier::" msgstr "" -#: ../../library/unittest.mock.rst:1876 +#: ../../library/unittest.mock.rst:1889 +msgid "" +">>> class MyTest(unittest.TestCase):\n" +"... def setUp(self):\n" +"... patcher = patch('package.module.Class')\n" +"... self.MockClass = patcher.start()\n" +"... self.addCleanup(patcher.stop)\n" +"...\n" +"... def test_something(self):\n" +"... assert package.module.Class is self.MockClass\n" +"..." +msgstr "" + +#: ../../library/unittest.mock.rst:1899 msgid "" "As an added bonus you no longer need to keep a reference to the ``patcher`` " "object." msgstr "" -#: ../../library/unittest.mock.rst:1879 +#: ../../library/unittest.mock.rst:1902 msgid "" "It is also possible to stop all patches which have been started by using :" "func:`patch.stopall`." msgstr "" -#: ../../library/unittest.mock.rst:1884 +#: ../../library/unittest.mock.rst:1907 msgid "Stop all active patches. Only stops patches started with ``start``." msgstr "" -#: ../../library/unittest.mock.rst:1890 +#: ../../library/unittest.mock.rst:1913 msgid "patch builtins" msgstr "patch de embutidos" -#: ../../library/unittest.mock.rst:1891 +#: ../../library/unittest.mock.rst:1914 msgid "" "You can patch any builtins within a module. The following example patches " "builtin :func:`ord`::" msgstr "" -#: ../../library/unittest.mock.rst:1906 +#: ../../library/unittest.mock.rst:1917 +msgid "" +">>> @patch('__main__.ord')\n" +"... def test(mock_ord):\n" +"... mock_ord.return_value = 101\n" +"... print(ord('c'))\n" +"...\n" +">>> test()\n" +"101" +msgstr "" + +#: ../../library/unittest.mock.rst:1929 msgid "TEST_PREFIX" msgstr "TEST_PREFIX" -#: ../../library/unittest.mock.rst:1908 +#: ../../library/unittest.mock.rst:1931 msgid "" "All of the patchers can be used as class decorators. When used in this way " "they wrap every test method on the class. The patchers recognise methods " @@ -1571,39 +1925,60 @@ msgid "" "the :class:`unittest.TestLoader` finds test methods by default." msgstr "" -#: ../../library/unittest.mock.rst:1913 +#: ../../library/unittest.mock.rst:1936 msgid "" "It is possible that you want to use a different prefix for your tests. You " "can inform the patchers of the different prefix by setting ``patch." "TEST_PREFIX``::" msgstr "" -#: ../../library/unittest.mock.rst:1936 +#: ../../library/unittest.mock.rst:1939 +msgid "" +">>> patch.TEST_PREFIX = 'foo'\n" +">>> value = 3\n" +">>>\n" +">>> @patch('__main__.value', 'not three')\n" +"... class Thing:\n" +"... def foo_one(self):\n" +"... print(value)\n" +"... def foo_two(self):\n" +"... print(value)\n" +"...\n" +">>>\n" +">>> Thing().foo_one()\n" +"not three\n" +">>> Thing().foo_two()\n" +"not three\n" +">>> value\n" +"3" +msgstr "" + +#: ../../library/unittest.mock.rst:1959 msgid "Nesting Patch Decorators" msgstr "Aninhando Decoradores Patch" -#: ../../library/unittest.mock.rst:1938 +#: ../../library/unittest.mock.rst:1961 msgid "" "If you want to perform multiple patches then you can simply stack up the " "decorators." msgstr "" -#: ../../library/unittest.mock.rst:1941 +#: ../../library/unittest.mock.rst:1964 msgid "You can stack up multiple patch decorators using this pattern:" msgstr "" -#: ../../library/unittest.mock.rst:1957 +#: ../../library/unittest.mock.rst:1980 msgid "" "Note that the decorators are applied from the bottom upwards. This is the " "standard way that Python applies decorators. The order of the created mocks " "passed into your test function matches this order." msgstr "" -#: ../../library/unittest.mock.rst:1965 +#: ../../library/unittest.mock.rst:1988 msgid "Where to patch" msgstr "Onde fazer patch" -#: ../../library/unittest.mock.rst:1967 +#: ../../library/unittest.mock.rst:1990 msgid "" ":func:`patch` works by (temporarily) changing the object that a *name* " "points to with another one. There can be many names pointing to any " @@ -1611,29 +1986,39 @@ msgid "" "the name used by the system under test." msgstr "" -#: ../../library/unittest.mock.rst:1972 +#: ../../library/unittest.mock.rst:1995 msgid "" "The basic principle is that you patch where an object is *looked up*, which " "is not necessarily the same place as where it is defined. A couple of " "examples will help to clarify this." msgstr "" -#: ../../library/unittest.mock.rst:1976 +#: ../../library/unittest.mock.rst:1999 msgid "" "Imagine we have a project that we want to test with the following structure::" msgstr "" -#: ../../library/unittest.mock.rst:1985 +#: ../../library/unittest.mock.rst:2001 +msgid "" +"a.py\n" +" -> Defines SomeClass\n" +"\n" +"b.py\n" +" -> from a import SomeClass\n" +" -> some_function instantiates SomeClass" +msgstr "" + +#: ../../library/unittest.mock.rst:2008 msgid "" "Now we want to test ``some_function`` but we want to mock out ``SomeClass`` " "using :func:`patch`. The problem is that when we import module b, which we " -"will have to do then it imports ``SomeClass`` from module a. If we use :func:" +"will have to do when it imports ``SomeClass`` from module a. If we use :func:" "`patch` to mock out ``a.SomeClass`` then it will have no effect on our test; " "module b already has a reference to the *real* ``SomeClass`` and it looks " "like our patching had no effect." msgstr "" -#: ../../library/unittest.mock.rst:1992 +#: ../../library/unittest.mock.rst:2015 msgid "" "The key is to patch out ``SomeClass`` where it is used (or where it is " "looked up). In this case ``some_function`` will actually look up " @@ -1641,7 +2026,11 @@ msgid "" "look like::" msgstr "" -#: ../../library/unittest.mock.rst:1998 +#: ../../library/unittest.mock.rst:2019 +msgid "@patch('b.SomeClass')" +msgstr "" + +#: ../../library/unittest.mock.rst:2021 msgid "" "However, consider the alternative scenario where instead of ``from a import " "SomeClass`` module b does ``import a`` and ``some_function`` uses ``a." @@ -1650,11 +2039,15 @@ msgid "" "``a.SomeClass`` instead::" msgstr "" -#: ../../library/unittest.mock.rst:2007 +#: ../../library/unittest.mock.rst:2026 +msgid "@patch('a.SomeClass')" +msgstr "" + +#: ../../library/unittest.mock.rst:2030 msgid "Patching Descriptors and Proxy Objects" msgstr "" -#: ../../library/unittest.mock.rst:2009 +#: ../../library/unittest.mock.rst:2032 msgid "" "Both patch_ and patch.object_ correctly patch and restore descriptors: class " "methods, static methods and properties. You should patch these on the " @@ -1664,22 +2057,22 @@ msgid "" "arch_d7_2010_12_04.shtml#e1198>`_." msgstr "" -#: ../../library/unittest.mock.rst:2017 +#: ../../library/unittest.mock.rst:2040 msgid "MagicMock and magic method support" msgstr "" -#: ../../library/unittest.mock.rst:2022 +#: ../../library/unittest.mock.rst:2045 msgid "Mocking Magic Methods" msgstr "Simulando Métodos Mágicos" -#: ../../library/unittest.mock.rst:2024 +#: ../../library/unittest.mock.rst:2047 msgid "" ":class:`Mock` supports mocking the Python protocol methods, also known as :" "term:`\"magic methods\" `. This allows mock objects to replace " "containers or other objects that implement Python protocols." msgstr "" -#: ../../library/unittest.mock.rst:2028 +#: ../../library/unittest.mock.rst:2051 msgid "" "Because magic methods are looked up differently from normal methods [#]_, " "this support has been specially implemented. This means that only specific " @@ -1687,49 +2080,49 @@ msgid "" "them. If there are any missing that you need please let us know." msgstr "" -#: ../../library/unittest.mock.rst:2033 +#: ../../library/unittest.mock.rst:2056 msgid "" "You mock magic methods by setting the method you are interested in to a " "function or a mock instance. If you are using a function then it *must* take " "``self`` as the first argument [#]_." msgstr "" -#: ../../library/unittest.mock.rst:2056 +#: ../../library/unittest.mock.rst:2079 msgid "" "One use case for this is for mocking objects used as context managers in a :" "keyword:`with` statement:" msgstr "" -#: ../../library/unittest.mock.rst:2068 +#: ../../library/unittest.mock.rst:2091 msgid "" "Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they " "are recorded in :attr:`~Mock.mock_calls`." msgstr "" -#: ../../library/unittest.mock.rst:2073 +#: ../../library/unittest.mock.rst:2096 msgid "" "If you use the *spec* keyword argument to create a mock then attempting to " "set a magic method that isn't in the spec will raise an :exc:" "`AttributeError`." msgstr "" -#: ../../library/unittest.mock.rst:2076 +#: ../../library/unittest.mock.rst:2099 msgid "The full list of supported magic methods is:" msgstr "A lista completa de métodos mágicos compatíveis é:" -#: ../../library/unittest.mock.rst:2078 +#: ../../library/unittest.mock.rst:2101 msgid "``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__``" msgstr "``__hash__``, ``__sizeof__``, ``__repr__`` e ``__str__``" -#: ../../library/unittest.mock.rst:2079 +#: ../../library/unittest.mock.rst:2102 msgid "``__dir__``, ``__format__`` and ``__subclasses__``" msgstr "``__dir__``, ``__format__`` e ``__subclasses__``" -#: ../../library/unittest.mock.rst:2080 +#: ../../library/unittest.mock.rst:2103 msgid "``__round__``, ``__floor__``, ``__trunc__`` and ``__ceil__``" msgstr "``__round__``, ``__floor__``, ``__trunc__`` e ``__ceil__``" -#: ../../library/unittest.mock.rst:2081 +#: ../../library/unittest.mock.rst:2104 msgid "" "Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``, ``__eq__`` and " "``__ne__``" @@ -1737,14 +2130,14 @@ msgstr "" "Comparações: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``, ``__eq__`` e " "``__ne__``" -#: ../../library/unittest.mock.rst:2083 +#: ../../library/unittest.mock.rst:2106 msgid "" "Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``, " "``__contains__``, ``__len__``, ``__iter__``, ``__reversed__`` and " "``__missing__``" msgstr "" -#: ../../library/unittest.mock.rst:2086 +#: ../../library/unittest.mock.rst:2109 msgid "" "Context manager: ``__enter__``, ``__exit__``, ``__aenter__`` and " "``__aexit__``" @@ -1752,11 +2145,11 @@ msgstr "" "Gerenciador de contexto: ``__enter__``, ``__exit__``, ``__aenter__`` e " "``__aexit__``" -#: ../../library/unittest.mock.rst:2087 +#: ../../library/unittest.mock.rst:2110 msgid "Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__``" msgstr "Métodos numéricos unários: ``__neg__``, ``__pos__`` e ``__invert__``" -#: ../../library/unittest.mock.rst:2088 +#: ../../library/unittest.mock.rst:2111 msgid "" "The numeric methods (including right hand and in-place variants): " "``__add__``, ``__sub__``, ``__mul__``, ``__matmul__``, ``__truediv__``, " @@ -1764,7 +2157,7 @@ msgid "" "``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__``" msgstr "" -#: ../../library/unittest.mock.rst:2092 +#: ../../library/unittest.mock.rst:2115 msgid "" "Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__`` and " "``__index__``" @@ -1772,11 +2165,11 @@ msgstr "" "Métodos de conversão numérica: ``__complex__``, ``__int__``, ``__float__`` e " "``__index__``" -#: ../../library/unittest.mock.rst:2094 +#: ../../library/unittest.mock.rst:2117 msgid "Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``" msgstr "Métodos descritores: ``__get__``, ``__set__`` e ``__delete__``" -#: ../../library/unittest.mock.rst:2095 +#: ../../library/unittest.mock.rst:2118 msgid "" "Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, " "``__getnewargs__``, ``__getstate__`` and ``__setstate__``" @@ -1784,19 +2177,19 @@ msgstr "" "Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, " "``__getnewargs__``, ``__getstate__`` e ``__setstate__``" -#: ../../library/unittest.mock.rst:2097 +#: ../../library/unittest.mock.rst:2120 msgid "File system path representation: ``__fspath__``" msgstr "" -#: ../../library/unittest.mock.rst:2098 +#: ../../library/unittest.mock.rst:2121 msgid "Asynchronous iteration methods: ``__aiter__`` and ``__anext__``" msgstr "Métodos de iteração assíncrona: ``__aiter__`` e ``__anext__``" -#: ../../library/unittest.mock.rst:2100 +#: ../../library/unittest.mock.rst:2123 msgid "Added support for :func:`os.PathLike.__fspath__`." msgstr "Adicionado suporte para :func:`os.PathLike.__fspath__`." -#: ../../library/unittest.mock.rst:2103 +#: ../../library/unittest.mock.rst:2126 msgid "" "Added support for ``__aenter__``, ``__aexit__``, ``__aiter__`` and " "``__anext__``." @@ -1804,27 +2197,27 @@ msgstr "" "Adicionado suporte para ``__aenter__``, ``__aexit__``, ``__aiter__`` e " "``__anext__``." -#: ../../library/unittest.mock.rst:2107 +#: ../../library/unittest.mock.rst:2130 msgid "" "The following methods exist but are *not* supported as they are either in " "use by mock, can't be set dynamically, or can cause problems:" msgstr "" -#: ../../library/unittest.mock.rst:2110 +#: ../../library/unittest.mock.rst:2133 msgid "``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__``" msgstr "``__getattr__``, ``__setattr__``, ``__init__`` e ``__new__``" -#: ../../library/unittest.mock.rst:2111 +#: ../../library/unittest.mock.rst:2134 msgid "" "``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``" msgstr "" "``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``" -#: ../../library/unittest.mock.rst:2116 +#: ../../library/unittest.mock.rst:2139 msgid "Magic Mock" msgstr "Magic Mock" -#: ../../library/unittest.mock.rst:2118 +#: ../../library/unittest.mock.rst:2141 msgid "" "There are two ``MagicMock`` variants: :class:`MagicMock` and :class:" "`NonCallableMagicMock`." @@ -1832,41 +2225,41 @@ msgstr "" "Existem duas variantes de ``MagicMock``: :class:`MagicMock` e :class:" "`NonCallableMagicMock`." -#: ../../library/unittest.mock.rst:2123 +#: ../../library/unittest.mock.rst:2146 msgid "" "``MagicMock`` is a subclass of :class:`Mock` with default implementations of " "most of the :term:`magic methods `. You can use ``MagicMock`` " "without having to configure the magic methods yourself." msgstr "" -#: ../../library/unittest.mock.rst:2127 +#: ../../library/unittest.mock.rst:2150 msgid "The constructor parameters have the same meaning as for :class:`Mock`." msgstr "" -#: ../../library/unittest.mock.rst:2129 +#: ../../library/unittest.mock.rst:2152 msgid "" "If you use the *spec* or *spec_set* arguments then *only* magic methods that " "exist in the spec will be created." msgstr "" -#: ../../library/unittest.mock.rst:2135 +#: ../../library/unittest.mock.rst:2158 msgid "A non-callable version of :class:`MagicMock`." msgstr "Uma versão não-chamável de :class:`MagicMock`." -#: ../../library/unittest.mock.rst:2137 +#: ../../library/unittest.mock.rst:2160 msgid "" "The constructor parameters have the same meaning as for :class:`MagicMock`, " "with the exception of *return_value* and *side_effect* which have no meaning " "on a non-callable mock." msgstr "" -#: ../../library/unittest.mock.rst:2141 +#: ../../library/unittest.mock.rst:2164 msgid "" "The magic methods are setup with :class:`MagicMock` objects, so you can " "configure them and use them in the usual way:" msgstr "" -#: ../../library/unittest.mock.rst:2151 +#: ../../library/unittest.mock.rst:2174 msgid "" "By default many of the protocol methods are required to return objects of a " "specific type. These methods are preconfigured with a default return value, " @@ -1875,83 +2268,83 @@ msgid "" "manually if you want to change the default." msgstr "" -#: ../../library/unittest.mock.rst:2157 +#: ../../library/unittest.mock.rst:2180 msgid "Methods and their defaults:" msgstr "Métodos e seus padrões:" -#: ../../library/unittest.mock.rst:2159 +#: ../../library/unittest.mock.rst:2182 msgid "``__lt__``: :data:`NotImplemented`" msgstr "" -#: ../../library/unittest.mock.rst:2160 +#: ../../library/unittest.mock.rst:2183 msgid "``__gt__``: :data:`!NotImplemented`" msgstr "" -#: ../../library/unittest.mock.rst:2161 +#: ../../library/unittest.mock.rst:2184 msgid "``__le__``: :data:`!NotImplemented`" msgstr "" -#: ../../library/unittest.mock.rst:2162 +#: ../../library/unittest.mock.rst:2185 msgid "``__ge__``: :data:`!NotImplemented`" msgstr "" -#: ../../library/unittest.mock.rst:2163 +#: ../../library/unittest.mock.rst:2186 msgid "``__int__``: ``1``" msgstr "``__int__``: ``1``" -#: ../../library/unittest.mock.rst:2164 +#: ../../library/unittest.mock.rst:2187 msgid "``__contains__``: ``False``" msgstr "``__contains__``: ``False``" -#: ../../library/unittest.mock.rst:2165 +#: ../../library/unittest.mock.rst:2188 msgid "``__len__``: ``0``" msgstr "``__len__``: ``0``" -#: ../../library/unittest.mock.rst:2166 +#: ../../library/unittest.mock.rst:2189 msgid "``__iter__``: ``iter([])``" msgstr "``__iter__``: ``iter([])``" -#: ../../library/unittest.mock.rst:2167 +#: ../../library/unittest.mock.rst:2190 msgid "``__exit__``: ``False``" msgstr "``__exit__``: ``False``" -#: ../../library/unittest.mock.rst:2168 +#: ../../library/unittest.mock.rst:2191 msgid "``__aexit__``: ``False``" msgstr "``__aexit__``: ``False``" -#: ../../library/unittest.mock.rst:2169 +#: ../../library/unittest.mock.rst:2192 msgid "``__complex__``: ``1j``" msgstr "``__complex__``: ``1j``" -#: ../../library/unittest.mock.rst:2170 +#: ../../library/unittest.mock.rst:2193 msgid "``__float__``: ``1.0``" msgstr "``__float__``: ``1.0``" -#: ../../library/unittest.mock.rst:2171 +#: ../../library/unittest.mock.rst:2194 msgid "``__bool__``: ``True``" msgstr "``__bool__``: ``True``" -#: ../../library/unittest.mock.rst:2172 +#: ../../library/unittest.mock.rst:2195 msgid "``__index__``: ``1``" msgstr "``__index__``: ``1``" -#: ../../library/unittest.mock.rst:2173 +#: ../../library/unittest.mock.rst:2196 msgid "``__hash__``: default hash for the mock" msgstr "``__hash__``: hash padrão para o mock" -#: ../../library/unittest.mock.rst:2174 +#: ../../library/unittest.mock.rst:2197 msgid "``__str__``: default str for the mock" msgstr "``__str__``: *str* padrão para o mock" -#: ../../library/unittest.mock.rst:2175 +#: ../../library/unittest.mock.rst:2198 msgid "``__sizeof__``: default sizeof for the mock" msgstr "``__sizeof__``: *sizeof* padrão para o mock" -#: ../../library/unittest.mock.rst:2177 +#: ../../library/unittest.mock.rst:2200 msgid "For example:" msgstr "Por exemplo:" -#: ../../library/unittest.mock.rst:2189 +#: ../../library/unittest.mock.rst:2212 msgid "" "The two equality methods, :meth:`!__eq__` and :meth:`!__ne__`, are special. " "They do the default equality comparison on identity, using the :attr:`~Mock." @@ -1959,52 +2352,64 @@ msgid "" "something else::" msgstr "" -#: ../../library/unittest.mock.rst:2203 +#: ../../library/unittest.mock.rst:2217 +msgid "" +">>> MagicMock() == 3\n" +"False\n" +">>> MagicMock() != 3\n" +"True\n" +">>> mock = MagicMock()\n" +">>> mock.__eq__.return_value = True\n" +">>> mock == 3\n" +"True" +msgstr "" + +#: ../../library/unittest.mock.rst:2226 msgid "" "The return value of :meth:`MagicMock.__iter__` can be any iterable object " "and isn't required to be an iterator:" msgstr "" -#: ../../library/unittest.mock.rst:2213 +#: ../../library/unittest.mock.rst:2236 msgid "" "If the return value *is* an iterator, then iterating over it once will " "consume it and subsequent iterations will result in an empty list:" msgstr "" -#: ../../library/unittest.mock.rst:2222 +#: ../../library/unittest.mock.rst:2245 msgid "" "``MagicMock`` has all of the supported magic methods configured except for " "some of the obscure and obsolete ones. You can still set these up if you " "want." msgstr "" -#: ../../library/unittest.mock.rst:2225 +#: ../../library/unittest.mock.rst:2248 msgid "" "Magic methods that are supported but not setup by default in ``MagicMock`` " "are:" msgstr "" -#: ../../library/unittest.mock.rst:2227 +#: ../../library/unittest.mock.rst:2250 msgid "``__subclasses__``" msgstr "``__subclasses__``" -#: ../../library/unittest.mock.rst:2228 +#: ../../library/unittest.mock.rst:2251 msgid "``__dir__``" msgstr "``__dir__``" -#: ../../library/unittest.mock.rst:2229 +#: ../../library/unittest.mock.rst:2252 msgid "``__format__``" msgstr "``__format__``" -#: ../../library/unittest.mock.rst:2230 +#: ../../library/unittest.mock.rst:2253 msgid "``__get__``, ``__set__`` and ``__delete__``" msgstr "``__get__``, ``__set__`` e ``__delete__``" -#: ../../library/unittest.mock.rst:2231 +#: ../../library/unittest.mock.rst:2254 msgid "``__reversed__`` and ``__missing__``" msgstr "``__reversed__`` e ``__missing__``" -#: ../../library/unittest.mock.rst:2232 +#: ../../library/unittest.mock.rst:2255 msgid "" "``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``, " "``__getstate__`` and ``__setstate__``" @@ -2012,51 +2417,51 @@ msgstr "" "``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``, " "``__getstate__`` e ``__setstate__``" -#: ../../library/unittest.mock.rst:2234 +#: ../../library/unittest.mock.rst:2257 msgid "``__getformat__``" msgstr "``__getformat__``" -#: ../../library/unittest.mock.rst:2238 +#: ../../library/unittest.mock.rst:2261 msgid "" "Magic methods *should* be looked up on the class rather than the instance. " "Different versions of Python are inconsistent about applying this rule. The " "supported protocol methods should work with all supported versions of Python." msgstr "" -#: ../../library/unittest.mock.rst:2242 +#: ../../library/unittest.mock.rst:2265 msgid "" "The function is basically hooked up to the class, but each ``Mock`` instance " "is kept isolated from the others." msgstr "" -#: ../../library/unittest.mock.rst:2247 +#: ../../library/unittest.mock.rst:2270 msgid "Helpers" msgstr "Ajudantes" -#: ../../library/unittest.mock.rst:2250 +#: ../../library/unittest.mock.rst:2273 msgid "sentinel" msgstr "sentinel" -#: ../../library/unittest.mock.rst:2254 +#: ../../library/unittest.mock.rst:2277 msgid "" "The ``sentinel`` object provides a convenient way of providing unique " "objects for your tests." msgstr "" -#: ../../library/unittest.mock.rst:2257 +#: ../../library/unittest.mock.rst:2280 msgid "" "Attributes are created on demand when you access them by name. Accessing the " "same attribute will always return the same object. The objects returned have " "a sensible repr so that test failure messages are readable." msgstr "" -#: ../../library/unittest.mock.rst:2261 +#: ../../library/unittest.mock.rst:2284 msgid "" "The ``sentinel`` attributes now preserve their identity when they are :mod:" "`copied ` or :mod:`pickled `." msgstr "" -#: ../../library/unittest.mock.rst:2265 +#: ../../library/unittest.mock.rst:2288 msgid "" "Sometimes when testing you need to test that a specific object is passed as " "an argument to another method, or returned. It can be common to create named " @@ -2064,28 +2469,28 @@ msgid "" "creating and testing the identity of objects like this." msgstr "" -#: ../../library/unittest.mock.rst:2270 +#: ../../library/unittest.mock.rst:2293 msgid "" "In this example we monkey patch ``method`` to return ``sentinel." "some_object``:" msgstr "" -#: ../../library/unittest.mock.rst:2282 +#: ../../library/unittest.mock.rst:2305 msgid "DEFAULT" msgstr "DEFAULT" -#: ../../library/unittest.mock.rst:2287 +#: ../../library/unittest.mock.rst:2310 msgid "" "The :data:`DEFAULT` object is a pre-created sentinel (actually ``sentinel." "DEFAULT``). It can be used by :attr:`~Mock.side_effect` functions to " "indicate that the normal return value should be used." msgstr "" -#: ../../library/unittest.mock.rst:2293 +#: ../../library/unittest.mock.rst:2316 msgid "call" msgstr "chamada" -#: ../../library/unittest.mock.rst:2297 +#: ../../library/unittest.mock.rst:2320 msgid "" ":func:`call` is a helper object for making simpler assertions, for comparing " "with :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`, :attr:`~Mock." @@ -2093,13 +2498,13 @@ msgid "" "with :meth:`~Mock.assert_has_calls`." msgstr "" -#: ../../library/unittest.mock.rst:2310 +#: ../../library/unittest.mock.rst:2333 msgid "" "For a call object that represents multiple calls, :meth:`call_list` returns " "a list of all the intermediate calls as well as the final call." msgstr "" -#: ../../library/unittest.mock.rst:2314 +#: ../../library/unittest.mock.rst:2337 msgid "" "``call_list`` is particularly useful for making assertions on \"chained " "calls\". A chained call is multiple calls on a single line of code. This " @@ -2107,13 +2512,13 @@ msgid "" "constructing the sequence of calls can be tedious." msgstr "" -#: ../../library/unittest.mock.rst:2319 +#: ../../library/unittest.mock.rst:2342 msgid "" ":meth:`~call.call_list` can construct the sequence of calls from the same " "chained call:" msgstr "" -#: ../../library/unittest.mock.rst:2336 +#: ../../library/unittest.mock.rst:2359 msgid "" "A ``call`` object is either a tuple of (positional args, keyword args) or " "(name, positional args, keyword args) depending on how it was constructed. " @@ -2123,7 +2528,7 @@ msgid "" "to get at the individual arguments they contain." msgstr "" -#: ../../library/unittest.mock.rst:2343 +#: ../../library/unittest.mock.rst:2366 msgid "" "The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock." "call_args_list` are two-tuples of (positional args, keyword args) whereas " @@ -2132,7 +2537,7 @@ msgid "" "args)." msgstr "" -#: ../../library/unittest.mock.rst:2348 +#: ../../library/unittest.mock.rst:2371 msgid "" "You can use their \"tupleness\" to pull out the individual arguments for " "more complex introspection and assertions. The positional arguments are a " @@ -2140,29 +2545,29 @@ msgid "" "arguments are a dictionary:" msgstr "" -#: ../../library/unittest.mock.rst:2381 +#: ../../library/unittest.mock.rst:2404 msgid "create_autospec" msgstr "create_autospec" -#: ../../library/unittest.mock.rst:2385 +#: ../../library/unittest.mock.rst:2408 msgid "" "Create a mock object using another object as a spec. Attributes on the mock " "will use the corresponding attribute on the *spec* object as their spec." msgstr "" -#: ../../library/unittest.mock.rst:2389 +#: ../../library/unittest.mock.rst:2412 msgid "" "Functions or methods being mocked will have their arguments checked to " "ensure that they are called with the correct signature." msgstr "" -#: ../../library/unittest.mock.rst:2392 +#: ../../library/unittest.mock.rst:2415 msgid "" "If *spec_set* is ``True`` then attempting to set attributes that don't exist " "on the spec object will raise an :exc:`AttributeError`." msgstr "" -#: ../../library/unittest.mock.rst:2395 +#: ../../library/unittest.mock.rst:2418 msgid "" "If a class is used as a spec then the return value of the mock (the instance " "of the class) will have the same spec. You can use a class as the spec for " @@ -2170,29 +2575,29 @@ msgid "" "be callable if instances of the mock are callable." msgstr "" -#: ../../library/unittest.mock.rst:2400 +#: ../../library/unittest.mock.rst:2423 msgid "" ":func:`create_autospec` also takes arbitrary keyword arguments that are " "passed to the constructor of the created mock." msgstr "" -#: ../../library/unittest.mock.rst:2403 +#: ../../library/unittest.mock.rst:2426 msgid "" "See :ref:`auto-speccing` for examples of how to use auto-speccing with :func:" "`create_autospec` and the *autospec* argument to :func:`patch`." msgstr "" -#: ../../library/unittest.mock.rst:2409 +#: ../../library/unittest.mock.rst:2432 msgid "" ":func:`create_autospec` now returns an :class:`AsyncMock` if the target is " "an async function." msgstr "" -#: ../../library/unittest.mock.rst:2414 +#: ../../library/unittest.mock.rst:2437 msgid "ANY" msgstr "ANY" -#: ../../library/unittest.mock.rst:2418 +#: ../../library/unittest.mock.rst:2441 msgid "" "Sometimes you may need to make assertions about *some* of the arguments in a " "call to mock, but either not care about some of the arguments or want to " @@ -2200,30 +2605,39 @@ msgid "" "assertions on them." msgstr "" -#: ../../library/unittest.mock.rst:2423 +#: ../../library/unittest.mock.rst:2446 msgid "" "To ignore certain arguments you can pass in objects that compare equal to " "*everything*. Calls to :meth:`~Mock.assert_called_with` and :meth:`~Mock." "assert_called_once_with` will then succeed no matter what was passed in." msgstr "" -#: ../../library/unittest.mock.rst:2432 +#: ../../library/unittest.mock.rst:2455 msgid "" ":data:`ANY` can also be used in comparisons with call lists like :attr:" "`~Mock.mock_calls`:" msgstr "" -#: ../../library/unittest.mock.rst:2442 +#: ../../library/unittest.mock.rst:2465 msgid "" ":data:`ANY` is not limited to comparisons with call objects and so can also " "be used in test assertions::" msgstr "" -#: ../../library/unittest.mock.rst:2453 +#: ../../library/unittest.mock.rst:2468 +msgid "" +"class TestStringMethods(unittest.TestCase):\n" +"\n" +" def test_split(self):\n" +" s = 'hello world'\n" +" self.assertEqual(s.split(), ['hello', ANY])" +msgstr "" + +#: ../../library/unittest.mock.rst:2476 msgid "FILTER_DIR" msgstr "FILTER_DIR" -#: ../../library/unittest.mock.rst:2457 +#: ../../library/unittest.mock.rst:2480 msgid "" ":data:`FILTER_DIR` is a module level variable that controls the way mock " "objects respond to :func:`dir`. The default is ``True``, which uses the " @@ -2232,7 +2646,7 @@ msgid "" "FILTER_DIR = False``." msgstr "" -#: ../../library/unittest.mock.rst:2463 +#: ../../library/unittest.mock.rst:2486 msgid "" "With filtering on, ``dir(some_mock)`` shows only useful attributes and will " "include any dynamically created attributes that wouldn't normally be shown. " @@ -2241,7 +2655,28 @@ msgid "" "yet:" msgstr "" -#: ../../library/unittest.mock.rst:2490 +#: ../../library/unittest.mock.rst:2492 +msgid "" +">>> dir(Mock())\n" +"['assert_any_call',\n" +" 'assert_called',\n" +" 'assert_called_once',\n" +" 'assert_called_once_with',\n" +" 'assert_called_with',\n" +" 'assert_has_calls',\n" +" 'assert_not_called',\n" +" 'attach_mock',\n" +" ...\n" +">>> from urllib import request\n" +">>> dir(Mock(spec=request))\n" +"['AbstractBasicAuthHandler',\n" +" 'AbstractDigestAuthHandler',\n" +" 'AbstractHTTPHandler',\n" +" 'BaseHandler',\n" +" ..." +msgstr "" + +#: ../../library/unittest.mock.rst:2513 msgid "" "Many of the not-very-useful (private to :class:`Mock` rather than the thing " "being mocked) underscore and double underscore prefixed attributes have been " @@ -2250,90 +2685,138 @@ msgid "" "switch :data:`FILTER_DIR`:" msgstr "" -#: ../../library/unittest.mock.rst:2511 +#: ../../library/unittest.mock.rst:2519 +msgid "" +">>> from unittest import mock\n" +">>> mock.FILTER_DIR = False\n" +">>> dir(mock.Mock())\n" +"['_NonCallableMock__get_return_value',\n" +" '_NonCallableMock__get_side_effect',\n" +" '_NonCallableMock__return_value_doc',\n" +" '_NonCallableMock__set_return_value',\n" +" '_NonCallableMock__set_side_effect',\n" +" '__call__',\n" +" '__class__',\n" +" ..." +msgstr "" + +#: ../../library/unittest.mock.rst:2534 msgid "" "Alternatively you can just use ``vars(my_mock)`` (instance members) and " "``dir(type(my_mock))`` (type members) to bypass the filtering irrespective " -"of :const:`mock.FILTER_DIR`." +"of :const:`FILTER_DIR`." msgstr "" -#: ../../library/unittest.mock.rst:2517 +#: ../../library/unittest.mock.rst:2540 msgid "mock_open" msgstr "mock_open" -#: ../../library/unittest.mock.rst:2521 +#: ../../library/unittest.mock.rst:2544 msgid "" "A helper function to create a mock to replace the use of :func:`open`. It " "works for :func:`open` called directly or used as a context manager." msgstr "" -#: ../../library/unittest.mock.rst:2524 +#: ../../library/unittest.mock.rst:2547 msgid "" "The *mock* argument is the mock object to configure. If ``None`` (the " "default) then a :class:`MagicMock` will be created for you, with the API " "limited to methods or attributes available on standard file handles." msgstr "" -#: ../../library/unittest.mock.rst:2528 +#: ../../library/unittest.mock.rst:2551 msgid "" -"*read_data* is a string for the :meth:`~io.IOBase.read`, :meth:`~io.IOBase." -"readline`, and :meth:`~io.IOBase.readlines` methods of the file handle to " -"return. Calls to those methods will take data from *read_data* until it is " -"depleted. The mock of these methods is pretty simplistic: every time the " -"*mock* is called, the *read_data* is rewound to the start. If you need more " -"control over the data that you are feeding to the tested code you will need " -"to customize this mock for yourself. When that is insufficient, one of the " -"in-memory filesystem packages on `PyPI `_ can offer a " -"realistic filesystem for testing." +"*read_data* is a string for the :meth:`~io.RawIOBase.read`, :meth:`~io." +"IOBase.readline`, and :meth:`~io.IOBase.readlines` methods of the file " +"handle to return. Calls to those methods will take data from *read_data* " +"until it is depleted. The mock of these methods is pretty simplistic: every " +"time the *mock* is called, the *read_data* is rewound to the start. If you " +"need more control over the data that you are feeding to the tested code you " +"will need to customize this mock for yourself. When that is insufficient, " +"one of the in-memory filesystem packages on `PyPI `_ can " +"offer a realistic filesystem for testing." msgstr "" -#: ../../library/unittest.mock.rst:2538 +#: ../../library/unittest.mock.rst:2561 msgid "" "Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support. " -"The mock of :meth:`~io.IOBase.read` changed to consume *read_data* rather " +"The mock of :meth:`~io.RawIOBase.read` changed to consume *read_data* rather " "than returning it on each call." msgstr "" -#: ../../library/unittest.mock.rst:2543 +#: ../../library/unittest.mock.rst:2566 msgid "*read_data* is now reset on each call to the *mock*." msgstr "" -#: ../../library/unittest.mock.rst:2546 +#: ../../library/unittest.mock.rst:2569 msgid "" "Added :meth:`~container.__iter__` to implementation so that iteration (such " "as in for loops) correctly consumes *read_data*." msgstr "" -#: ../../library/unittest.mock.rst:2550 +#: ../../library/unittest.mock.rst:2573 msgid "" "Using :func:`open` as a context manager is a great way to ensure your file " "handles are closed properly and is becoming common::" msgstr "" -#: ../../library/unittest.mock.rst:2556 +#: ../../library/unittest.mock.rst:2576 +msgid "" +"with open('/some/path', 'w') as f:\n" +" f.write('something')" +msgstr "" + +#: ../../library/unittest.mock.rst:2579 msgid "" "The issue is that even if you mock out the call to :func:`open` it is the " "*returned object* that is used as a context manager (and has :meth:`~object." "__enter__` and :meth:`~object.__exit__` called)." msgstr "" -#: ../../library/unittest.mock.rst:2560 +#: ../../library/unittest.mock.rst:2583 msgid "" "Mocking context managers with a :class:`MagicMock` is common enough and " "fiddly enough that a helper function is useful. ::" msgstr "" -#: ../../library/unittest.mock.rst:2577 +#: ../../library/unittest.mock.rst:2586 +msgid "" +">>> m = mock_open()\n" +">>> with patch('__main__.open', m):\n" +"... with open('foo', 'w') as h:\n" +"... h.write('some stuff')\n" +"...\n" +">>> m.mock_calls\n" +"[call('foo', 'w'),\n" +" call().__enter__(),\n" +" call().write('some stuff'),\n" +" call().__exit__(None, None, None)]\n" +">>> m.assert_called_once_with('foo', 'w')\n" +">>> handle = m()\n" +">>> handle.write.assert_called_once_with('some stuff')" +msgstr "" + +#: ../../library/unittest.mock.rst:2600 msgid "And for reading files::" msgstr "E para ler arquivos::" -#: ../../library/unittest.mock.rst:2590 +#: ../../library/unittest.mock.rst:2602 +msgid "" +">>> with patch('__main__.open', mock_open(read_data='bibble')) as m:\n" +"... with open('foo') as h:\n" +"... result = h.read()\n" +"...\n" +">>> m.assert_called_once_with('foo')\n" +">>> assert result == 'bibble'" +msgstr "" + +#: ../../library/unittest.mock.rst:2613 msgid "Autospeccing" msgstr "Especificação automática" -#: ../../library/unittest.mock.rst:2592 +#: ../../library/unittest.mock.rst:2615 msgid "" -"Autospeccing is based on the existing :attr:`spec` feature of mock. It " +"Autospeccing is based on the existing :attr:`!spec` feature of mock. It " "limits the api of mocks to the api of an original object (the spec), but it " "is recursive (implemented lazily) so that attributes of mocks only have the " "same api as the attributes of the spec. In addition mocked functions / " @@ -2341,11 +2824,11 @@ msgid "" "`TypeError` if they are called incorrectly." msgstr "" -#: ../../library/unittest.mock.rst:2599 +#: ../../library/unittest.mock.rst:2622 msgid "Before I explain how auto-speccing works, here's why it is needed." msgstr "" -#: ../../library/unittest.mock.rst:2601 +#: ../../library/unittest.mock.rst:2624 msgid "" ":class:`Mock` is a very powerful and flexible object, but it suffers from a " "flaw which is general to mocking. If you refactor some of your code, rename " @@ -2354,14 +2837,14 @@ msgid "" "tests can all pass even though your code is broken." msgstr "" -#: ../../library/unittest.mock.rst:2609 +#: ../../library/unittest.mock.rst:2632 msgid "" "Before 3.5, tests with a typo in the word assert would silently pass when " "they should raise an error. You can still achieve this behavior by passing " "``unsafe=True`` to Mock." msgstr "" -#: ../../library/unittest.mock.rst:2612 +#: ../../library/unittest.mock.rst:2635 msgid "" "Note that this is another reason why you need integration tests as well as " "unit tests. Testing everything in isolation is all fine and dandy, but if " @@ -2369,20 +2852,27 @@ msgid "" "room for bugs that tests might have caught." msgstr "" -#: ../../library/unittest.mock.rst:2617 +#: ../../library/unittest.mock.rst:2640 msgid "" -":mod:`mock` already provides a feature to help with this, called speccing. " -"If you use a class or instance as the :attr:`spec` for a mock then you can " -"only access attributes on the mock that exist on the real class:" +":mod:`unittest.mock` already provides a feature to help with this, called " +"speccing. If you use a class or instance as the :attr:`!spec` for a mock " +"then you can only access attributes on the mock that exist on the real class:" msgstr "" -#: ../../library/unittest.mock.rst:2628 +#: ../../library/unittest.mock.rst:2651 msgid "" "The spec only applies to the mock itself, so we still have the same issue " "with any methods on the mock:" msgstr "" -#: ../../library/unittest.mock.rst:2637 +#: ../../library/unittest.mock.rst:2654 +msgid "" +">>> mock.header_items()\n" +"\n" +">>> mock.header_items.assret_called_with() # Intentional typo!" +msgstr "" + +#: ../../library/unittest.mock.rst:2660 msgid "" "Auto-speccing solves this problem. You can either pass ``autospec=True`` to :" "func:`patch` / :func:`patch.object` or use the :func:`create_autospec` " @@ -2394,45 +2884,82 @@ msgid "" "import modules) without a big performance hit." msgstr "" -#: ../../library/unittest.mock.rst:2646 +#: ../../library/unittest.mock.rst:2669 msgid "Here's an example of it in use::" msgstr "Aqui está um exemplo disso em uso::" -#: ../../library/unittest.mock.rst:2656 +#: ../../library/unittest.mock.rst:2671 msgid "" -"You can see that :class:`request.Request` has a spec. :class:`request." +">>> from urllib import request\n" +">>> patcher = patch('__main__.request', autospec=True)\n" +">>> mock_request = patcher.start()\n" +">>> request is mock_request\n" +"True\n" +">>> mock_request.Request\n" +"" +msgstr "" + +#: ../../library/unittest.mock.rst:2679 +msgid "" +"You can see that :class:`!request.Request` has a spec. :class:`!request." "Request` takes two arguments in the constructor (one of which is *self*). " "Here's what happens if we try to call it incorrectly::" msgstr "" -#: ../../library/unittest.mock.rst:2665 +#: ../../library/unittest.mock.rst:2683 +msgid "" +">>> req = request.Request()\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: () takes at least 2 arguments (1 given)" +msgstr "" + +#: ../../library/unittest.mock.rst:2688 msgid "" "The spec also applies to instantiated classes (i.e. the return value of " "specced mocks)::" msgstr "" -#: ../../library/unittest.mock.rst:2672 +#: ../../library/unittest.mock.rst:2691 msgid "" -":class:`Request` objects are not callable, so the return value of " -"instantiating our mocked out :class:`request.Request` is a non-callable " +">>> req = request.Request('foo')\n" +">>> req\n" +"" +msgstr "" + +#: ../../library/unittest.mock.rst:2695 +msgid "" +":class:`!Request` objects are not callable, so the return value of " +"instantiating our mocked out :class:`!request.Request` is a non-callable " "mock. With the spec in place any typos in our asserts will raise the correct " "error::" msgstr "" -#: ../../library/unittest.mock.rst:2684 +#: ../../library/unittest.mock.rst:2699 +msgid "" +">>> req.add_header('spam', 'eggs')\n" +"\n" +">>> req.add_header.assret_called_with # Intentional typo!\n" +"Traceback (most recent call last):\n" +" ...\n" +"AttributeError: Mock object has no attribute 'assret_called_with'\n" +">>> req.add_header.assert_called_with('spam', 'eggs')" +msgstr "" + +#: ../../library/unittest.mock.rst:2707 msgid "" "In many cases you will just be able to add ``autospec=True`` to your " "existing :func:`patch` calls and then be protected against bugs due to typos " "and api changes." msgstr "" -#: ../../library/unittest.mock.rst:2688 +#: ../../library/unittest.mock.rst:2711 msgid "" "As well as using *autospec* through :func:`patch` there is a :func:" "`create_autospec` for creating autospecced mocks directly:" msgstr "" -#: ../../library/unittest.mock.rst:2696 +#: ../../library/unittest.mock.rst:2719 msgid "" "This isn't without caveats and limitations however, which is why it is not " "the default behaviour. In order to know what attributes are available on the " @@ -2444,7 +2971,7 @@ msgid "" "objects so that introspection is safe [#]_." msgstr "" -#: ../../library/unittest.mock.rst:2705 +#: ../../library/unittest.mock.rst:2728 msgid "" "A more serious problem is that it is common for instance attributes to be " "created in the :meth:`~object.__init__` method and not to exist on the class " @@ -2452,7 +2979,22 @@ msgid "" "restricts the api to visible attributes. ::" msgstr "" -#: ../../library/unittest.mock.rst:2722 +#: ../../library/unittest.mock.rst:2733 +msgid "" +">>> class Something:\n" +"... def __init__(self):\n" +"... self.a = 33\n" +"...\n" +">>> with patch('__main__.Something', autospec=True):\n" +"... thing = Something()\n" +"... thing.a\n" +"...\n" +"Traceback (most recent call last):\n" +" ...\n" +"AttributeError: Mock object has no attribute 'a'" +msgstr "" + +#: ../../library/unittest.mock.rst:2745 msgid "" "There are a few different ways of resolving this problem. The easiest, but " "not necessarily the least annoying, way is to simply set the required " @@ -2461,7 +3003,15 @@ msgid "" "setting them::" msgstr "" -#: ../../library/unittest.mock.rst:2733 +#: ../../library/unittest.mock.rst:2751 +msgid "" +">>> with patch('__main__.Something', autospec=True):\n" +"... thing = Something()\n" +"... thing.a = 33\n" +"..." +msgstr "" + +#: ../../library/unittest.mock.rst:2756 msgid "" "There is a more aggressive version of both *spec* and *autospec* that *does* " "prevent you setting non-existent attributes. This is useful if you want to " @@ -2469,7 +3019,7 @@ msgid "" "this particular scenario:" msgstr "" -#: ../../library/unittest.mock.rst:2746 +#: ../../library/unittest.mock.rst:2769 msgid "" "Probably the best way of solving the problem is to add class attributes as " "default values for instance members initialised in :meth:`~object.__init__`. " @@ -2478,7 +3028,13 @@ msgid "" "course) is faster too. e.g." msgstr "" -#: ../../library/unittest.mock.rst:2757 +#: ../../library/unittest.mock.rst:2775 +msgid "" +"class Something:\n" +" a = 33" +msgstr "" + +#: ../../library/unittest.mock.rst:2780 msgid "" "This brings up another issue. It is relatively common to provide a default " "value of ``None`` for members that will later be an object of a different " @@ -2489,7 +3045,7 @@ msgid "" "These will just be ordinary mocks (well - MagicMocks):" msgstr "" -#: ../../library/unittest.mock.rst:2772 +#: ../../library/unittest.mock.rst:2795 msgid "" "If modifying your production classes to add defaults isn't to your liking " "then there are more options. One of these is simply to use an instance as " @@ -2500,53 +3056,80 @@ msgid "" "alternative object as the *autospec* argument::" msgstr "" -#: ../../library/unittest.mock.rst:2793 +#: ../../library/unittest.mock.rst:2803 +msgid "" +">>> class Something:\n" +"... def __init__(self):\n" +"... self.a = 33\n" +"...\n" +">>> class SomethingForTest(Something):\n" +"... a = 33\n" +"...\n" +">>> p = patch('__main__.Something', autospec=SomethingForTest)\n" +">>> mock = p.start()\n" +">>> mock.a\n" +"" +msgstr "" + +#: ../../library/unittest.mock.rst:2816 msgid "" "This only applies to classes or already instantiated objects. Calling a " "mocked class to create a mock instance *does not* create a real instance. It " "is only attribute lookups - along with calls to :func:`dir` - that are done." msgstr "" -#: ../../library/unittest.mock.rst:2798 +#: ../../library/unittest.mock.rst:2821 msgid "Sealing mocks" msgstr "Vedando mocks" -#: ../../library/unittest.mock.rst:2807 +#: ../../library/unittest.mock.rst:2830 msgid "" "Seal will disable the automatic creation of mocks when accessing an " "attribute of the mock being sealed or any of its attributes that are already " "mocks recursively." msgstr "" -#: ../../library/unittest.mock.rst:2810 +#: ../../library/unittest.mock.rst:2833 msgid "" "If a mock instance with a name or a spec is assigned to an attribute it " "won't be considered in the sealing chain. This allows one to prevent seal " "from fixing part of the mock object. ::" msgstr "" -#: ../../library/unittest.mock.rst:2826 +#: ../../library/unittest.mock.rst:2837 msgid "" -"Order of precedence of :attr:`side_effect`, :attr:`return_value` and *wraps*" +">>> mock = Mock()\n" +">>> mock.submock.attribute1 = 2\n" +">>> mock.not_submock = mock.Mock(name=\"sample_name\")\n" +">>> seal(mock)\n" +">>> mock.new_attribute # This will raise AttributeError.\n" +">>> mock.submock.attribute2 # This will raise AttributeError.\n" +">>> mock.not_submock.attribute2 # This won't raise." msgstr "" -#: ../../library/unittest.mock.rst:2828 +#: ../../library/unittest.mock.rst:2849 +msgid "" +"Order of precedence of :attr:`!side_effect`, :attr:`!return_value` and " +"*wraps*" +msgstr "" + +#: ../../library/unittest.mock.rst:2851 msgid "The order of their precedence is:" msgstr "" -#: ../../library/unittest.mock.rst:2830 +#: ../../library/unittest.mock.rst:2853 msgid ":attr:`~Mock.side_effect`" msgstr "" -#: ../../library/unittest.mock.rst:2831 +#: ../../library/unittest.mock.rst:2854 msgid ":attr:`~Mock.return_value`" msgstr "" -#: ../../library/unittest.mock.rst:2832 +#: ../../library/unittest.mock.rst:2855 msgid "*wraps*" msgstr "" -#: ../../library/unittest.mock.rst:2834 +#: ../../library/unittest.mock.rst:2857 msgid "" "If all three are set, mock will return the value from :attr:`~Mock." "side_effect`, ignoring :attr:`~Mock.return_value` and the wrapped object " @@ -2555,7 +3138,7 @@ msgid "" "of precedence remains unchanged." msgstr "" -#: ../../library/unittest.mock.rst:2852 +#: ../../library/unittest.mock.rst:2875 msgid "" "As ``None`` is the default value of :attr:`~Mock.side_effect`, if you " "reassign its value back to ``None``, the order of precedence will be checked " @@ -2563,46 +3146,46 @@ msgid "" "`~Mock.side_effect`." msgstr "" -#: ../../library/unittest.mock.rst:2861 +#: ../../library/unittest.mock.rst:2884 msgid "" "If the value being returned by :attr:`~Mock.side_effect` is :data:`DEFAULT`, " "it is ignored and the order of precedence moves to the successor to obtain " "the value to return." msgstr "" -#: ../../library/unittest.mock.rst:2870 +#: ../../library/unittest.mock.rst:2893 msgid "" "When :class:`Mock` wraps an object, the default value of :attr:`~Mock." "return_value` will be :data:`DEFAULT`." msgstr "" -#: ../../library/unittest.mock.rst:2879 +#: ../../library/unittest.mock.rst:2902 msgid "" "The order of precedence will ignore this value and it will move to the last " "successor which is the wrapped object." msgstr "" -#: ../../library/unittest.mock.rst:2882 +#: ../../library/unittest.mock.rst:2905 msgid "" "As the real call is being made to the wrapped object, creating an instance " "of this mock will return the real instance of the class. The positional " "arguments, if any, required by the wrapped object must be passed." msgstr "" -#: ../../library/unittest.mock.rst:2900 +#: ../../library/unittest.mock.rst:2923 msgid "" "But if you assign ``None`` to it, this will not be ignored as it is an " "explicit assignment. So, the order of precedence will not move to the " "wrapped object." msgstr "" -#: ../../library/unittest.mock.rst:2908 +#: ../../library/unittest.mock.rst:2931 msgid "" "Even if you set all three at once when initializing the mock, the order of " "precedence remains the same:" msgstr "" -#: ../../library/unittest.mock.rst:2925 +#: ../../library/unittest.mock.rst:2948 msgid "" "If :attr:`~Mock.side_effect` is exhausted, the order of precedence will not " "cause a value to be obtained from the successors. Instead, ``StopIteration`` " diff --git a/library/unittest.po b/library/unittest.po index 80a01824c..8bfde81bc 100644 --- a/library/unittest.po +++ b/library/unittest.po @@ -1,35 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Italo Penaforte , 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Giovana Morais , 2021 -# Hugo Santos Piauilino , 2021 -# Renan Lopes , 2021 -# i17obot , 2021 -# Victor Moura , 2021 -# Vinicius Gubiani Ferreira , 2021 -# Renan Renan, 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-19 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 01:16+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -229,17 +219,37 @@ msgstr "" msgid "Here is a short script to test three string methods::" msgstr "Aqui temos um simples Script para testar três métodos de String::" +#: ../../library/unittest.rst:91 +msgid "" +"import unittest\n" +"\n" +"class TestStringMethods(unittest.TestCase):\n" +"\n" +" def test_upper(self):\n" +" self.assertEqual('foo'.upper(), 'FOO')\n" +"\n" +" def test_isupper(self):\n" +" self.assertTrue('FOO'.isupper())\n" +" self.assertFalse('Foo'.isupper())\n" +"\n" +" def test_split(self):\n" +" s = 'hello world'\n" +" self.assertEqual(s.split(), ['hello', 'world'])\n" +" # check that s.split fails when the separator is not a string\n" +" with self.assertRaises(TypeError):\n" +" s.split(2)\n" +"\n" +"if __name__ == '__main__':\n" +" unittest.main()" +msgstr "" + #: ../../library/unittest.rst:113 msgid "" -"A testcase is created by subclassing :class:`unittest.TestCase`. The three " +"A test case is created by subclassing :class:`unittest.TestCase`. The three " "individual tests are defined with methods whose names start with the letters " "``test``. This naming convention informs the test runner about which " "methods represent tests." msgstr "" -"Para criar um testcase basta criar uma classe que estende de :class:" -"`unittest.TestCase`. Os três testes individuais são definidos com métodos " -"cujos nomes começam com as letras ``test``. Esta convenção na nomenclatura " -"informa o runner a respeitos de quais métodos são, na verdade, testes." #: ../../library/unittest.rst:118 msgid "" @@ -280,6 +290,15 @@ msgstr "" "de teste. Quando executado a partir da linha de comando, o Script acima " "produz uma saída que se parece com isso::" +#: ../../library/unittest.rst:133 +msgid "" +"...\n" +"----------------------------------------------------------------------\n" +"Ran 3 tests in 0.000s\n" +"\n" +"OK" +msgstr "" + #: ../../library/unittest.rst:139 msgid "" "Passing the ``-v`` option to your test script will instruct :func:`unittest." @@ -290,6 +309,18 @@ msgstr "" "func:`unittest.main` a habilitar um nível mais alto de verbosidade e " "produzirá a seguinte saída::" +#: ../../library/unittest.rst:142 +msgid "" +"test_isupper (__main__.TestStringMethods.test_isupper) ... ok\n" +"test_split (__main__.TestStringMethods.test_split) ... ok\n" +"test_upper (__main__.TestStringMethods.test_upper) ... ok\n" +"\n" +"----------------------------------------------------------------------\n" +"Ran 3 tests in 0.001s\n" +"\n" +"OK" +msgstr "" + #: ../../library/unittest.rst:151 msgid "" "The above examples show the most commonly used :mod:`unittest` features " @@ -319,6 +350,13 @@ msgstr "" "O módulo unittest pode ser usado diretamente da linha de comando para " "executar testes de módulos, classes ou mesmo testes de métodos individuais::" +#: ../../library/unittest.rst:168 +msgid "" +"python -m unittest test_module1 test_module2\n" +"python -m unittest test_module.TestClass\n" +"python -m unittest test_module.TestClass.test_method" +msgstr "" + #: ../../library/unittest.rst:172 msgid "" "You can pass in a list with any combination of module names, and fully " @@ -332,6 +370,10 @@ msgid "Test modules can be specified by file path as well::" msgstr "" "Os módulos de teste podem ser especificados por caminhos de arquivo também::" +#: ../../library/unittest.rst:177 +msgid "python -m unittest tests/test_something.py" +msgstr "" + #: ../../library/unittest.rst:179 msgid "" "This allows you to use the shell filename completion to specify the test " @@ -355,16 +397,28 @@ msgstr "" "Você pode executar os testes com mais detalhes (maior verbosidade) ao usar o " "sinalizador -v::" +#: ../../library/unittest.rst:187 +msgid "python -m unittest -v test_module" +msgstr "" + #: ../../library/unittest.rst:189 msgid "" "When executed without arguments :ref:`unittest-test-discovery` is started::" msgstr "" "Quando executado sem argumentos :ref:`unittest-test-discovery` é iniciado::" +#: ../../library/unittest.rst:191 +msgid "python -m unittest" +msgstr "" + #: ../../library/unittest.rst:193 msgid "For a list of all the command-line options::" msgstr "Para uma lista de todas as opções de linha de comando::" +#: ../../library/unittest.rst:195 +msgid "python -m unittest -h" +msgstr "" + #: ../../library/unittest.rst:197 msgid "" "In earlier versions it was only possible to run individual test methods and " @@ -504,6 +558,12 @@ msgstr "" "também pode ser utilizado a partir da linha de comando. O comando básico " "para uso é::" +#: ../../library/unittest.rst:282 +msgid "" +"cd project_directory\n" +"python -m unittest discover" +msgstr "" + #: ../../library/unittest.rst:287 msgid "" "As a shortcut, ``python -m unittest`` is the equivalent of ``python -m " @@ -546,6 +606,12 @@ msgstr "" "argumentos posicionais nessa ordem. As duas linhas de comando seguintes são " "equivalentes::" +#: ../../library/unittest.rst:315 +msgid "" +"python -m unittest discover -s project_directory -p \"*_test.py\"\n" +"python -m unittest discover project_directory \"*_test.py\"" +msgstr "" + #: ../../library/unittest.rst:318 msgid "" "As well as being a path it is possible to pass a package name, for example " @@ -627,6 +693,17 @@ msgid "" "target directory explicitly. For example::" msgstr "" +#: ../../library/unittest.rst:358 +msgid "" +"# proj/ <-- current directory\n" +"# namespace/\n" +"# mypkg/\n" +"# __init__.py\n" +"# test_mypkg.py\n" +"\n" +"python -m unittest discover -s namespace.mypkg -t ." +msgstr "" + #: ../../library/unittest.rst:370 msgid "Organizing test code" msgstr "Organizando código teste" @@ -666,6 +743,16 @@ msgstr "" "A mais simples subclasse de :class:`TestCase` irá implementar um método de " "teste (i.e. um método cujo nome começa com ``test``) para executar um teste::" +#: ../../library/unittest.rst:386 +msgid "" +"import unittest\n" +"\n" +"class DefaultWidgetSizeTestCase(unittest.TestCase):\n" +" def test_default_widget_size(self):\n" +" widget = Widget('The widget')\n" +" self.assertEqual(widget.size(), (50, 50))" +msgstr "" + #: ../../library/unittest.rst:393 msgid "" "Note that in order to test something, we use one of the :ref:`assert\\* " @@ -687,6 +774,24 @@ msgstr "" "chamado :meth:`~TestCase.setUp`, o qual será automaticamente chamado pelo " "framework de teste para cada teste único que executarmos::" +#: ../../library/unittest.rst:404 +msgid "" +"import unittest\n" +"\n" +"class WidgetTestCase(unittest.TestCase):\n" +" def setUp(self):\n" +" self.widget = Widget('The widget')\n" +"\n" +" def test_default_widget_size(self):\n" +" self.assertEqual(self.widget.size(), (50,50),\n" +" 'incorrect default size')\n" +"\n" +" def test_widget_resize(self):\n" +" self.widget.resize(100,150)\n" +" self.assertEqual(self.widget.size(), (100,150),\n" +" 'wrong size after resize')" +msgstr "" + #: ../../library/unittest.rst:420 msgid "" "The order in which the various tests will be run is determined by sorting " @@ -714,6 +819,18 @@ msgstr "" "De maneira similar, pode-se definir um método :meth:`~TestCase.tearDown` que " "limpa o ambiente após a execução do método de teste::" +#: ../../library/unittest.rst:431 +msgid "" +"import unittest\n" +"\n" +"class WidgetTestCase(unittest.TestCase):\n" +" def setUp(self):\n" +" self.widget = Widget('The widget')\n" +"\n" +" def tearDown(self):\n" +" self.widget.dispose()" +msgstr "" + #: ../../library/unittest.rst:440 msgid "" "If :meth:`~TestCase.setUp` succeeded, :meth:`~TestCase.tearDown` will be run " @@ -761,6 +878,19 @@ msgstr "" "Entretanto, caso você queira customizar a construção da sua suíte de testes, " "é possível fazê-la desta forma::" +#: ../../library/unittest.rst:459 +msgid "" +"def suite():\n" +" suite = unittest.TestSuite()\n" +" suite.addTest(WidgetTestCase('test_default_widget_size'))\n" +" suite.addTest(WidgetTestCase('test_widget_resize'))\n" +" return suite\n" +"\n" +"if __name__ == '__main__':\n" +" runner = unittest.TextTestRunner()\n" +" runner.run(suite())" +msgstr "" + #: ../../library/unittest.rst:469 msgid "" "You can place the definitions of test cases and test suites in the same " @@ -847,6 +977,14 @@ msgstr "" msgid "Given the following test function::" msgstr "Dadas as seguintes funções de teste::" +#: ../../library/unittest.rst:506 +msgid "" +"def testSomething():\n" +" something = makeSomething()\n" +" assert something.name is not None\n" +" # ..." +msgstr "" + #: ../../library/unittest.rst:511 msgid "" "one can create an equivalent test case instance as follows, with optional " @@ -855,6 +993,13 @@ msgstr "" "é possível criar uma instância de caso de teste, com métodos opcionais de " "configuração inicial e final (set-up e tear-down), como mostrado a seguir::" +#: ../../library/unittest.rst:514 +msgid "" +"testcase = unittest.FunctionTestCase(testSomething,\n" +" setUp=makeSomethingDB,\n" +" tearDown=deleteSomethingDB)" +msgstr "" + #: ../../library/unittest.rst:520 msgid "" "Even though :class:`FunctionTestCase` can be used to quickly convert an " @@ -912,14 +1057,66 @@ msgstr "" msgid "Basic skipping looks like this::" msgstr "Ignorar se parece basicamente com::" +#: ../../library/unittest.rst:549 +msgid "" +"class MyTestCase(unittest.TestCase):\n" +"\n" +" @unittest.skip(\"demonstrating skipping\")\n" +" def test_nothing(self):\n" +" self.fail(\"shouldn't happen\")\n" +"\n" +" @unittest.skipIf(mylib.__version__ < (1, 3),\n" +" \"not supported in this library version\")\n" +" def test_format(self):\n" +" # Tests that work for only a certain version of the library.\n" +" pass\n" +"\n" +" @unittest.skipUnless(sys.platform.startswith(\"win\"), \"requires " +"Windows\")\n" +" def test_windows_support(self):\n" +" # windows specific testing code\n" +" pass\n" +"\n" +" def test_maybe_skipped(self):\n" +" if not external_resource_available():\n" +" self.skipTest(\"external resource not available\")\n" +" # test code that depends on the external resource\n" +" pass" +msgstr "" + #: ../../library/unittest.rst:572 msgid "This is the output of running the example above in verbose mode::" msgstr "Esta é a saída da execução do exemplo acima em modo verboso::" +#: ../../library/unittest.rst:574 +msgid "" +"test_format (__main__.MyTestCase.test_format) ... skipped 'not supported in " +"this library version'\n" +"test_nothing (__main__.MyTestCase.test_nothing) ... skipped 'demonstrating " +"skipping'\n" +"test_maybe_skipped (__main__.MyTestCase.test_maybe_skipped) ... skipped " +"'external resource not available'\n" +"test_windows_support (__main__.MyTestCase.test_windows_support) ... skipped " +"'requires Windows'\n" +"\n" +"----------------------------------------------------------------------\n" +"Ran 4 tests in 0.005s\n" +"\n" +"OK (skipped=4)" +msgstr "" + #: ../../library/unittest.rst:584 msgid "Classes can be skipped just like methods::" msgstr "Classes podem ser puladas assim como métodos::" +#: ../../library/unittest.rst:586 +msgid "" +"@unittest.skip(\"showing class skipping\")\n" +"class MySkippedTestCase(unittest.TestCase):\n" +" def test_not_run(self):\n" +" pass" +msgstr "" + #: ../../library/unittest.rst:591 msgid "" ":meth:`TestCase.setUp` can also skip the test. This is useful when a " @@ -932,6 +1129,14 @@ msgstr "" msgid "Expected failures use the :func:`expectedFailure` decorator. ::" msgstr "Falhas esperadas usam o decorador :func:`expectedFailure`::" +#: ../../library/unittest.rst:596 +msgid "" +"class ExpectedFailureTestCase(unittest.TestCase):\n" +" @unittest.expectedFailure\n" +" def test_fail(self):\n" +" self.assertEqual(1, 0, \"broken\")" +msgstr "" + #: ../../library/unittest.rst:601 msgid "" "It's easy to roll your own skipping decorators by making a decorator that " @@ -943,6 +1148,14 @@ msgstr "" "ignora o teste a não ser que o objeto fornecido tenha um determinado " "atributo::" +#: ../../library/unittest.rst:605 +msgid "" +"def skipUnlessHasattr(obj, attr):\n" +" if hasattr(obj, attr):\n" +" return lambda func: func\n" +" return unittest.skip(\"{!r} doesn't have {!r}\".format(obj, attr))" +msgstr "" + #: ../../library/unittest.rst:610 msgid "" "The following decorators and exception implement test skipping and expected " @@ -1021,10 +1234,56 @@ msgstr "" msgid "For example, the following test::" msgstr "Por exemplo, o teste seguinte::" +#: ../../library/unittest.rst:657 +msgid "" +"class NumbersTest(unittest.TestCase):\n" +"\n" +" def test_even(self):\n" +" \"\"\"\n" +" Test that numbers between 0 and 5 are all even.\n" +" \"\"\"\n" +" for i in range(0, 6):\n" +" with self.subTest(i=i):\n" +" self.assertEqual(i % 2, 0)" +msgstr "" + #: ../../library/unittest.rst:667 msgid "will produce the following output::" msgstr "irá produzir a seguinte saída::" +#: ../../library/unittest.rst:669 +msgid "" +"======================================================================\n" +"FAIL: test_even (__main__.NumbersTest.test_even) (i=1)\n" +"Test that numbers between 0 and 5 are all even.\n" +"----------------------------------------------------------------------\n" +"Traceback (most recent call last):\n" +" File \"subtests.py\", line 11, in test_even\n" +" self.assertEqual(i % 2, 0)\n" +" ^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +"AssertionError: 1 != 0\n" +"\n" +"======================================================================\n" +"FAIL: test_even (__main__.NumbersTest.test_even) (i=3)\n" +"Test that numbers between 0 and 5 are all even.\n" +"----------------------------------------------------------------------\n" +"Traceback (most recent call last):\n" +" File \"subtests.py\", line 11, in test_even\n" +" self.assertEqual(i % 2, 0)\n" +" ^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +"AssertionError: 1 != 0\n" +"\n" +"======================================================================\n" +"FAIL: test_even (__main__.NumbersTest.test_even) (i=5)\n" +"Test that numbers between 0 and 5 are all even.\n" +"----------------------------------------------------------------------\n" +"Traceback (most recent call last):\n" +" File \"subtests.py\", line 11, in test_even\n" +" self.assertEqual(i % 2, 0)\n" +" ^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +"AssertionError: 1 != 0" +msgstr "" + #: ../../library/unittest.rst:699 msgid "" "Without using a subtest, execution would stop after the first failure, and " @@ -1034,6 +1293,17 @@ msgstr "" "Sem usar um subteste, a execução para depois da primeira falha e o erro será " "menos fácil de ser diagnosticado porque o valor de ``i`` não será mostrado::" +#: ../../library/unittest.rst:703 +msgid "" +"======================================================================\n" +"FAIL: test_even (__main__.NumbersTest.test_even)\n" +"----------------------------------------------------------------------\n" +"Traceback (most recent call last):\n" +" File \"subtests.py\", line 32, in test_even\n" +" self.assertEqual(i % 2, 0)\n" +"AssertionError: 1 != 0" +msgstr "" + #: ../../library/unittest.rst:715 msgid "Classes and functions" msgstr "Classes e funções" @@ -1146,6 +1416,13 @@ msgstr "" "específica. O método ``setUpClass`` é chamado com a classe sendo o único " "argumento e deve ser decorada como um :func:`classmethod`::" +#: ../../library/unittest.rst:778 +msgid "" +"@classmethod\n" +"def setUpClass(cls):\n" +" ..." +msgstr "" + #: ../../library/unittest.rst:782 ../../library/unittest.rst:797 msgid "See `Class and Module Fixtures`_ for more details." msgstr "Veja `Classes e Módulos de Definição de Contexto`_ para mais detalhes." @@ -1160,6 +1437,13 @@ msgstr "" "específica. O método ``tearDownClass`` é chamado com a classe sendo o único " "argumento e deve ser decorada como um :func:`classmethod`::" +#: ../../library/unittest.rst:793 +msgid "" +"@classmethod\n" +"def tearDownClass(cls):\n" +" ..." +msgstr "" + #: ../../library/unittest.rst:804 msgid "" "Run the test, collecting the result into the :class:`TestResult` object " @@ -1572,6 +1856,12 @@ msgstr "" "retorna um gerenciador de contexto para que o código sob teste possa ser " "escrito de forma embutida ao invés de ser definido como uma função::" +#: ../../library/unittest.rst:1009 +msgid "" +"with self.assertRaises(SomeException):\n" +" do_something()" +msgstr "" + #: ../../library/unittest.rst:1012 msgid "" "When used as a context manager, :meth:`assertRaises` accepts the additional " @@ -1590,6 +1880,15 @@ msgstr "" "atributo :attr:`exception`. Isso pode ser útil se a intenção for realizar " "testes adicionais na exceção levantada::" +#: ../../library/unittest.rst:1019 +msgid "" +"with self.assertRaises(SomeException) as cm:\n" +" do_something()\n" +"\n" +"the_exception = cm.exception\n" +"self.assertEqual(the_exception.error_code, 3)" +msgstr "" + #: ../../library/unittest.rst:1025 msgid "Added the ability to use :meth:`assertRaises` as a context manager." msgstr "" @@ -1619,9 +1918,21 @@ msgstr "" "expressão regular ou uma string contendo uma expressão regular compatível " "com o uso pela função :func:`re.search`. Exemplos::" +#: ../../library/unittest.rst:1043 +msgid "" +"self.assertRaisesRegex(ValueError, \"invalid literal for.*XYZ'$\",\n" +" int, 'XYZ')" +msgstr "" + #: ../../library/unittest.rst:1046 ../../library/unittest.rst:1114 msgid "or::" -msgstr "or::" +msgstr "ou::" + +#: ../../library/unittest.rst:1048 +msgid "" +"with self.assertRaisesRegex(ValueError, 'literal'):\n" +" int('XYZ')" +msgstr "" #: ../../library/unittest.rst:1051 msgid "Added under the name ``assertRaisesRegexp``." @@ -1656,6 +1967,12 @@ msgstr "" "retorna um gerenciador de contexto para que o código sob teste possa ser " "escrito de forma embutida ao invés de ser definido como uma função::" +#: ../../library/unittest.rst:1075 +msgid "" +"with self.assertWarns(SomeWarning):\n" +" do_something()" +msgstr "" + #: ../../library/unittest.rst:1078 msgid "" "When used as a context manager, :meth:`assertWarns` accepts the additional " @@ -1676,6 +1993,15 @@ msgstr "" "atributos :attr:`filename` e :attr:`lineno`. Isso pode ser útil se a " "intenção for executar verificações adicionais no aviso capturado::" +#: ../../library/unittest.rst:1087 +msgid "" +"with self.assertWarns(SomeWarning) as cm:\n" +" do_something()\n" +"\n" +"self.assertIn('myfile.py', cm.filename)\n" +"self.assertEqual(320, cm.lineno)" +msgstr "" + #: ../../library/unittest.rst:1093 msgid "" "This method works regardless of the warning filters in place when it is " @@ -1696,6 +2022,19 @@ msgstr "" "uma string contendo uma expressão regular compatível para uso pela função :" "func:`re.search`. Exemplo::" +#: ../../library/unittest.rst:1110 +msgid "" +"self.assertWarnsRegex(DeprecationWarning,\n" +" r'legacy_function\\(\\) is deprecated',\n" +" legacy_function, 'XYZ')" +msgstr "" + +#: ../../library/unittest.rst:1116 +msgid "" +"with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):\n" +" frobnicate('/etc/passwd')" +msgstr "" + #: ../../library/unittest.rst:1126 msgid "" "A context manager to test that at least one message is logged on the " @@ -1760,6 +2099,15 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" +#: ../../library/unittest.rst:1158 +msgid "" +"with self.assertLogs('foo', level='INFO') as cm:\n" +" logging.getLogger('foo').info('first message')\n" +" logging.getLogger('foo.bar').error('second message')\n" +"self.assertEqual(cm.output, ['INFO:foo:first message',\n" +" 'ERROR:foo.bar:second message'])" +msgstr "" + #: ../../library/unittest.rst:1168 msgid "" "A context manager to test that no messages are logged on the *logger* or one " @@ -1915,6 +2263,12 @@ msgstr "" "Testa que *first* é respectivamente >, >=, < ou <= que *second*, dependendo " "do nome do método. Se não for, o teste irá falhar::" +#: ../../library/unittest.rst:1248 +msgid "" +">>> self.assertGreaterEqual(3, 4)\n" +"AssertionError: \"3\" unexpectedly not greater than or equal to \"4\"" +msgstr "" + #: ../../library/unittest.rst:1257 msgid "" "Test that a *regex* search matches (or does not match) *text*. In case of " @@ -2297,7 +2651,7 @@ msgid "" "with :class:`asyncio.EventLoop` to avoid using the asyncio policy system." msgstr "" -#: ../../library/unittest.rst:1584 +#: ../../library/unittest.rst:1585 msgid "" "Method called to prepare the test fixture. This is called after :meth:" "`setUp`. This is called immediately before calling the test method; other " @@ -2306,7 +2660,7 @@ msgid "" "implementation does nothing." msgstr "" -#: ../../library/unittest.rst:1592 +#: ../../library/unittest.rst:1594 msgid "" "Method called immediately after the test method has been called and the " "result recorded. This is called before :meth:`tearDown`. This is called " @@ -2319,11 +2673,11 @@ msgid "" "the outcome of the test method. The default implementation does nothing." msgstr "" -#: ../../library/unittest.rst:1604 +#: ../../library/unittest.rst:1606 msgid "This method accepts a coroutine that can be used as a cleanup function." msgstr "" -#: ../../library/unittest.rst:1608 +#: ../../library/unittest.rst:1611 msgid "" "Enter the supplied :term:`asynchronous context manager`. If successful, " "also add its :meth:`~object.__aexit__` method as a cleanup function by :meth:" @@ -2331,7 +2685,7 @@ msgid "" "method." msgstr "" -#: ../../library/unittest.rst:1618 +#: ../../library/unittest.rst:1621 msgid "" "Sets up a new event loop to run the test, collecting the result into the :" "class:`TestResult` object passed as *result*. If *result* is omitted or " @@ -2341,18 +2695,56 @@ msgid "" "cancelled." msgstr "" -#: ../../library/unittest.rst:1626 +#: ../../library/unittest.rst:1629 msgid "An example illustrating the order::" msgstr "" -#: ../../library/unittest.rst:1662 +#: ../../library/unittest.rst:1631 +msgid "" +"from unittest import IsolatedAsyncioTestCase\n" +"\n" +"events = []\n" +"\n" +"\n" +"class Test(IsolatedAsyncioTestCase):\n" +"\n" +"\n" +" def setUp(self):\n" +" events.append(\"setUp\")\n" +"\n" +" async def asyncSetUp(self):\n" +" self._async_connection = await AsyncConnection()\n" +" events.append(\"asyncSetUp\")\n" +"\n" +" async def test_response(self):\n" +" events.append(\"test_response\")\n" +" response = await self._async_connection.get(\"https://example." +"com\")\n" +" self.assertEqual(response.status_code, 200)\n" +" self.addAsyncCleanup(self.on_cleanup)\n" +"\n" +" def tearDown(self):\n" +" events.append(\"tearDown\")\n" +"\n" +" async def asyncTearDown(self):\n" +" await self._async_connection.close()\n" +" events.append(\"asyncTearDown\")\n" +"\n" +" async def on_cleanup(self):\n" +" events.append(\"cleanup\")\n" +"\n" +"if __name__ == \"__main__\":\n" +" unittest.main()" +msgstr "" + +#: ../../library/unittest.rst:1665 msgid "" "After running the test, ``events`` would contain ``[\"setUp\", " "\"asyncSetUp\", \"test_response\", \"asyncTearDown\", \"tearDown\", " "\"cleanup\"]``." msgstr "" -#: ../../library/unittest.rst:1667 +#: ../../library/unittest.rst:1670 msgid "" "This class implements the portion of the :class:`TestCase` interface which " "allows the test runner to drive the test, but does not provide the methods " @@ -2361,11 +2753,11 @@ msgid "" "`unittest`-based test framework." msgstr "" -#: ../../library/unittest.rst:1677 +#: ../../library/unittest.rst:1680 msgid "Grouping tests" msgstr "" -#: ../../library/unittest.rst:1681 +#: ../../library/unittest.rst:1684 msgid "" "This class represents an aggregation of individual test cases and test " "suites. The class presents the interface needed by the test runner to allow " @@ -2373,14 +2765,14 @@ msgid "" "is the same as iterating over the suite, running each test individually." msgstr "" -#: ../../library/unittest.rst:1686 +#: ../../library/unittest.rst:1689 msgid "" "If *tests* is given, it must be an iterable of individual test cases or " "other test suites that will be used to build the suite initially. Additional " "methods are provided to add test cases and suites to the collection later on." msgstr "" -#: ../../library/unittest.rst:1690 +#: ../../library/unittest.rst:1693 msgid "" ":class:`TestSuite` objects behave much like :class:`TestCase` objects, " "except they do not actually implement a test. Instead, they are used to " @@ -2389,47 +2781,47 @@ msgid "" "instances:" msgstr "" -#: ../../library/unittest.rst:1698 +#: ../../library/unittest.rst:1701 msgid "Add a :class:`TestCase` or :class:`TestSuite` to the suite." msgstr "" -#: ../../library/unittest.rst:1703 +#: ../../library/unittest.rst:1706 msgid "" "Add all the tests from an iterable of :class:`TestCase` and :class:" "`TestSuite` instances to this test suite." msgstr "" -#: ../../library/unittest.rst:1706 +#: ../../library/unittest.rst:1709 msgid "" "This is equivalent to iterating over *tests*, calling :meth:`addTest` for " "each element." msgstr "" -#: ../../library/unittest.rst:1709 +#: ../../library/unittest.rst:1712 msgid ":class:`TestSuite` shares the following methods with :class:`TestCase`:" msgstr "" -#: ../../library/unittest.rst:1714 +#: ../../library/unittest.rst:1717 msgid "" "Run the tests associated with this suite, collecting the result into the " "test result object passed as *result*. Note that unlike :meth:`TestCase." "run`, :meth:`TestSuite.run` requires the result object to be passed in." msgstr "" -#: ../../library/unittest.rst:1722 +#: ../../library/unittest.rst:1725 msgid "" "Run the tests associated with this suite without collecting the result. This " "allows exceptions raised by the test to be propagated to the caller and can " "be used to support running tests under a debugger." msgstr "" -#: ../../library/unittest.rst:1729 +#: ../../library/unittest.rst:1732 msgid "" "Return the number of tests represented by this test object, including all " "individual tests and sub-suites." msgstr "" -#: ../../library/unittest.rst:1735 +#: ../../library/unittest.rst:1738 msgid "" "Tests grouped by a :class:`TestSuite` are always accessed by iteration. " "Subclasses can lazily provide tests by overriding :meth:`!__iter__`. Note " @@ -2441,31 +2833,31 @@ msgid "" "overrides :meth:`TestSuite._removeTestAtIndex` to preserve test references." msgstr "" -#: ../../library/unittest.rst:1745 +#: ../../library/unittest.rst:1748 msgid "" "In earlier versions the :class:`TestSuite` accessed tests directly rather " "than through iteration, so overriding :meth:`!__iter__` wasn't sufficient " "for providing tests." msgstr "" -#: ../../library/unittest.rst:1750 +#: ../../library/unittest.rst:1753 msgid "" "In earlier versions the :class:`TestSuite` held references to each :class:" "`TestCase` after :meth:`TestSuite.run`. Subclasses can restore that behavior " "by overriding :meth:`TestSuite._removeTestAtIndex`." msgstr "" -#: ../../library/unittest.rst:1755 +#: ../../library/unittest.rst:1758 msgid "" "In the typical usage of a :class:`TestSuite` object, the :meth:`run` method " "is invoked by a :class:`TestRunner` rather than by the end-user test harness." msgstr "" -#: ../../library/unittest.rst:1760 +#: ../../library/unittest.rst:1763 msgid "Loading and running tests" msgstr "Carregando e executando testes" -#: ../../library/unittest.rst:1764 +#: ../../library/unittest.rst:1767 msgid "" "The :class:`TestLoader` class is used to create test suites from classes and " "modules. Normally, there is no need to create an instance of this class; " @@ -2474,11 +2866,11 @@ msgid "" "customization of some configurable properties." msgstr "" -#: ../../library/unittest.rst:1770 +#: ../../library/unittest.rst:1773 msgid ":class:`TestLoader` objects have the following attributes:" msgstr "Objetos da classe :class:`TestLoader` possuem os seguintes atributos:" -#: ../../library/unittest.rst:1775 +#: ../../library/unittest.rst:1778 msgid "" "A list of the non-fatal errors encountered while loading tests. Not reset by " "the loader at any point. Fatal errors are signalled by the relevant method " @@ -2486,17 +2878,17 @@ msgid "" "synthetic test that will raise the original error when run." msgstr "" -#: ../../library/unittest.rst:1784 +#: ../../library/unittest.rst:1787 msgid ":class:`TestLoader` objects have the following methods:" msgstr "Objetos da classe :class:`TestLoader` possuem os seguintes métodos:" -#: ../../library/unittest.rst:1789 +#: ../../library/unittest.rst:1792 msgid "" "Return a suite of all test cases contained in the :class:`TestCase`\\ -" "derived :class:`testCaseClass`." msgstr "" -#: ../../library/unittest.rst:1792 +#: ../../library/unittest.rst:1795 msgid "" "A test case instance is created for each method named by :meth:" "`getTestCaseNames`. By default these are the method names beginning with " @@ -2505,14 +2897,14 @@ msgid "" "method instead." msgstr "" -#: ../../library/unittest.rst:1801 +#: ../../library/unittest.rst:1804 msgid "" "Return a suite of all test cases contained in the given module. This method " "searches *module* for classes derived from :class:`TestCase` and creates an " "instance of the class for each test method defined for the class." msgstr "" -#: ../../library/unittest.rst:1808 +#: ../../library/unittest.rst:1811 msgid "" "While using a hierarchy of :class:`TestCase`\\ -derived classes can be " "convenient in sharing fixtures and helper functions, defining test methods " @@ -2521,7 +2913,7 @@ msgid "" "fixtures are different and defined in subclasses." msgstr "" -#: ../../library/unittest.rst:1814 +#: ../../library/unittest.rst:1817 msgid "" "If a module provides a ``load_tests`` function it will be called to load the " "tests. This allows modules to customize test loading. This is the " @@ -2529,24 +2921,24 @@ msgid "" "argument to ``load_tests``." msgstr "" -#: ../../library/unittest.rst:1819 +#: ../../library/unittest.rst:1822 msgid "Support for ``load_tests`` added." msgstr "Suporte para ``load_tests`` adicionado." -#: ../../library/unittest.rst:1822 +#: ../../library/unittest.rst:1825 msgid "Support for a keyword-only argument *pattern* has been added." msgstr "" -#: ../../library/unittest.rst:1825 +#: ../../library/unittest.rst:1828 msgid "" "The undocumented and unofficial *use_load_tests* parameter has been removed." msgstr "" -#: ../../library/unittest.rst:1832 +#: ../../library/unittest.rst:1835 msgid "Return a suite of all test cases given a string specifier." msgstr "" -#: ../../library/unittest.rst:1834 +#: ../../library/unittest.rst:1837 msgid "" "The specifier *name* is a \"dotted name\" that may resolve either to a " "module, a test case class, a test method within a test case class, a :class:" @@ -2557,7 +2949,7 @@ msgid "" "object\"." msgstr "" -#: ../../library/unittest.rst:1842 +#: ../../library/unittest.rst:1845 msgid "" "For example, if you have a module :mod:`SampleTests` containing a :class:" "`TestCase`\\ -derived class :class:`SampleTestCase` with three test methods " @@ -2570,31 +2962,31 @@ msgid "" "a side-effect." msgstr "" -#: ../../library/unittest.rst:1852 +#: ../../library/unittest.rst:1855 msgid "The method optionally resolves *name* relative to the given *module*." msgstr "O método opcionalmente resolve o *nome* relativo ao *módulo* dado." -#: ../../library/unittest.rst:1854 +#: ../../library/unittest.rst:1857 msgid "" "If an :exc:`ImportError` or :exc:`AttributeError` occurs while traversing " "*name* then a synthetic test that raises that error when run will be " "returned. These errors are included in the errors accumulated by self.errors." msgstr "" -#: ../../library/unittest.rst:1863 +#: ../../library/unittest.rst:1866 msgid "" "Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather " "than a single name. The return value is a test suite which supports all the " "tests defined for each name." msgstr "" -#: ../../library/unittest.rst:1870 +#: ../../library/unittest.rst:1873 msgid "" "Return a sorted sequence of method names found within *testCaseClass*; this " "should be a subclass of :class:`TestCase`." msgstr "" -#: ../../library/unittest.rst:1876 +#: ../../library/unittest.rst:1879 msgid "" "Find all the test modules by recursing into subdirectories from the " "specified start directory, and return a TestSuite object containing them. " @@ -2603,14 +2995,14 @@ msgid "" "Python identifiers) will be loaded." msgstr "" -#: ../../library/unittest.rst:1882 +#: ../../library/unittest.rst:1885 msgid "" "All test modules must be importable from the top level of the project. If " "the start directory is not the top level directory then *top_level_dir* must " "be specified separately." msgstr "" -#: ../../library/unittest.rst:1886 +#: ../../library/unittest.rst:1889 msgid "" "If importing a module fails, for example due to a syntax error, then this " "will be recorded as a single error and discovery will continue. If the " @@ -2618,7 +3010,7 @@ msgid "" "as a skip instead of an error." msgstr "" -#: ../../library/unittest.rst:1891 +#: ../../library/unittest.rst:1894 msgid "" "If a package (a directory containing a file named :file:`__init__.py`) is " "found, the package will be checked for a ``load_tests`` function. If this " @@ -2628,103 +3020,103 @@ msgid "" "itself calls ``loader.discover``." msgstr "" -#: ../../library/unittest.rst:1899 +#: ../../library/unittest.rst:1902 msgid "" "If ``load_tests`` exists then discovery does *not* recurse into the package, " "``load_tests`` is responsible for loading all tests in the package." msgstr "" -#: ../../library/unittest.rst:1903 +#: ../../library/unittest.rst:1906 msgid "" "The pattern is deliberately not stored as a loader attribute so that " "packages can continue discovery themselves." msgstr "" -#: ../../library/unittest.rst:1906 +#: ../../library/unittest.rst:1909 msgid "" "*top_level_dir* is stored internally, and used as a default to any nested " "calls to ``discover()``. That is, if a package's ``load_tests`` calls " "``loader.discover()``, it does not need to pass this argument." msgstr "" -#: ../../library/unittest.rst:1910 +#: ../../library/unittest.rst:1913 msgid "*start_dir* can be a dotted module name as well as a directory." msgstr "" -#: ../../library/unittest.rst:1914 +#: ../../library/unittest.rst:1917 msgid "" "Modules that raise :exc:`SkipTest` on import are recorded as skips, not " "errors." msgstr "" -#: ../../library/unittest.rst:1918 +#: ../../library/unittest.rst:1921 msgid "*start_dir* can be a :term:`namespace packages `." msgstr "" -#: ../../library/unittest.rst:1921 +#: ../../library/unittest.rst:1924 msgid "" "Paths are sorted before being imported so that execution order is the same " "even if the underlying file system's ordering is not dependent on file name." msgstr "" -#: ../../library/unittest.rst:1926 +#: ../../library/unittest.rst:1929 msgid "" "Found packages are now checked for ``load_tests`` regardless of whether " "their path matches *pattern*, because it is impossible for a package name to " "match the default pattern." msgstr "" -#: ../../library/unittest.rst:1931 +#: ../../library/unittest.rst:1934 msgid "" "*start_dir* can not be a :term:`namespace packages `. It " "has been broken since Python 3.7 and Python 3.11 officially remove it." msgstr "" -#: ../../library/unittest.rst:1935 +#: ../../library/unittest.rst:1938 msgid "*top_level_dir* is only stored for the duration of *discover* call." msgstr "" -#: ../../library/unittest.rst:1939 +#: ../../library/unittest.rst:1942 msgid "" "The following attributes of a :class:`TestLoader` can be configured either " "by subclassing or assignment on an instance:" msgstr "" -#: ../../library/unittest.rst:1945 +#: ../../library/unittest.rst:1948 msgid "" "String giving the prefix of method names which will be interpreted as test " "methods. The default value is ``'test'``." msgstr "" -#: ../../library/unittest.rst:1948 +#: ../../library/unittest.rst:1951 msgid "" "This affects :meth:`getTestCaseNames` and all the ``loadTestsFrom*`` methods." msgstr "" -#: ../../library/unittest.rst:1954 +#: ../../library/unittest.rst:1957 msgid "" "Function to be used to compare method names when sorting them in :meth:" "`getTestCaseNames` and all the ``loadTestsFrom*`` methods." msgstr "" -#: ../../library/unittest.rst:1960 +#: ../../library/unittest.rst:1963 msgid "" "Callable object that constructs a test suite from a list of tests. No " "methods on the resulting object are needed. The default value is the :class:" "`TestSuite` class." msgstr "" -#: ../../library/unittest.rst:1964 ../../library/unittest.rst:1977 +#: ../../library/unittest.rst:1967 ../../library/unittest.rst:1980 msgid "This affects all the ``loadTestsFrom*`` methods." msgstr "" -#: ../../library/unittest.rst:1968 +#: ../../library/unittest.rst:1971 msgid "" "List of Unix shell-style wildcard test name patterns that test methods have " "to match to be included in test suites (see ``-k`` option)." msgstr "" -#: ../../library/unittest.rst:1971 +#: ../../library/unittest.rst:1974 msgid "" "If this attribute is not ``None`` (the default), all test methods to be " "included in test suites must match one of the patterns in this list. Note " @@ -2733,13 +3125,13 @@ msgid "" "have to be converted using ``*`` wildcards." msgstr "" -#: ../../library/unittest.rst:1984 +#: ../../library/unittest.rst:1987 msgid "" "This class is used to compile information about which tests have succeeded " "and which have failed." msgstr "" -#: ../../library/unittest.rst:1987 +#: ../../library/unittest.rst:1990 msgid "" "A :class:`TestResult` object stores the results of a set of tests. The :" "class:`TestCase` and :class:`TestSuite` classes ensure that results are " @@ -2747,7 +3139,7 @@ msgid "" "outcome of tests." msgstr "" -#: ../../library/unittest.rst:1992 +#: ../../library/unittest.rst:1995 msgid "" "Testing frameworks built on top of :mod:`unittest` may want access to the :" "class:`TestResult` object generated by running a set of tests for reporting " @@ -2755,61 +3147,61 @@ msgid "" "`TestRunner.run` method for this purpose." msgstr "" -#: ../../library/unittest.rst:1997 +#: ../../library/unittest.rst:2000 msgid "" ":class:`TestResult` instances have the following attributes that will be of " "interest when inspecting the results of running a set of tests:" msgstr "" -#: ../../library/unittest.rst:2003 +#: ../../library/unittest.rst:2006 msgid "" "A list containing 2-tuples of :class:`TestCase` instances and strings " "holding formatted tracebacks. Each tuple represents a test which raised an " "unexpected exception." msgstr "" -#: ../../library/unittest.rst:2009 +#: ../../library/unittest.rst:2012 msgid "" "A list containing 2-tuples of :class:`TestCase` instances and strings " "holding formatted tracebacks. Each tuple represents a test where a failure " "was explicitly signalled using the :ref:`assert\\* methods `." msgstr "" -#: ../../library/unittest.rst:2015 +#: ../../library/unittest.rst:2018 msgid "" "A list containing 2-tuples of :class:`TestCase` instances and strings " "holding the reason for skipping the test." msgstr "" -#: ../../library/unittest.rst:2022 +#: ../../library/unittest.rst:2025 msgid "" "A list containing 2-tuples of :class:`TestCase` instances and strings " "holding formatted tracebacks. Each tuple represents an expected failure or " "error of the test case." msgstr "" -#: ../../library/unittest.rst:2028 +#: ../../library/unittest.rst:2031 msgid "" "A list containing :class:`TestCase` instances that were marked as expected " "failures, but succeeded." msgstr "" -#: ../../library/unittest.rst:2033 +#: ../../library/unittest.rst:2036 msgid "" "A list containing 2-tuples of test case names and floats representing the " "elapsed time of each test which was run." msgstr "" -#: ../../library/unittest.rst:2040 +#: ../../library/unittest.rst:2043 msgid "" "Set to ``True`` when the execution of tests should stop by :meth:`stop`." msgstr "" -#: ../../library/unittest.rst:2044 +#: ../../library/unittest.rst:2047 msgid "The total number of tests run so far." msgstr "" -#: ../../library/unittest.rst:2048 +#: ../../library/unittest.rst:2051 msgid "" "If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in " "between :meth:`startTest` and :meth:`stopTest` being called. Collected " @@ -2818,7 +3210,7 @@ msgid "" "error message." msgstr "" -#: ../../library/unittest.rst:2057 +#: ../../library/unittest.rst:2060 msgid "" "If set to true :meth:`stop` will be called on the first failure or error, " "halting the test run." @@ -2826,23 +3218,23 @@ msgstr "" "Se definido como true (verdadeiro) :meth:`stop` será chamado na primeira " "falha ou erro, interrompendo a execução do teste." -#: ../../library/unittest.rst:2064 +#: ../../library/unittest.rst:2067 msgid "If set to true then local variables will be shown in tracebacks." msgstr "" -#: ../../library/unittest.rst:2070 +#: ../../library/unittest.rst:2073 msgid "" "Return ``True`` if all tests run so far have passed, otherwise returns " "``False``." msgstr "" -#: ../../library/unittest.rst:2073 +#: ../../library/unittest.rst:2076 msgid "" "Returns ``False`` if there were any :attr:`unexpectedSuccesses` from tests " "marked with the :func:`expectedFailure` decorator." msgstr "" -#: ../../library/unittest.rst:2079 +#: ../../library/unittest.rst:2082 msgid "" "This method can be called to signal that the set of tests being run should " "be aborted by setting the :attr:`shouldStop` attribute to ``True``. :class:" @@ -2850,7 +3242,7 @@ msgid "" "additional tests." msgstr "" -#: ../../library/unittest.rst:2084 +#: ../../library/unittest.rst:2087 msgid "" "For example, this feature is used by the :class:`TextTestRunner` class to " "stop the test framework when the user signals an interrupt from the " @@ -2858,7 +3250,7 @@ msgid "" "implementations can use this in a similar manner." msgstr "" -#: ../../library/unittest.rst:2089 +#: ../../library/unittest.rst:2092 msgid "" "The following methods of the :class:`TestResult` class are used to maintain " "the internal data structures, and may be extended in subclasses to support " @@ -2866,141 +3258,141 @@ msgid "" "tools which support interactive reporting while tests are being run." msgstr "" -#: ../../library/unittest.rst:2097 +#: ../../library/unittest.rst:2100 msgid "Called when the test case *test* is about to be run." msgstr "" -#: ../../library/unittest.rst:2101 +#: ../../library/unittest.rst:2104 msgid "" "Called after the test case *test* has been executed, regardless of the " "outcome." msgstr "" -#: ../../library/unittest.rst:2106 +#: ../../library/unittest.rst:2109 msgid "Called once before any tests are executed." msgstr "" -#: ../../library/unittest.rst:2113 +#: ../../library/unittest.rst:2116 msgid "Called once after all tests are executed." msgstr "" -#: ../../library/unittest.rst:2120 +#: ../../library/unittest.rst:2123 msgid "" "Called when the test case *test* raises an unexpected exception. *err* is a " "tuple of the form returned by :func:`sys.exc_info`: ``(type, value, " "traceback)``." msgstr "" -#: ../../library/unittest.rst:2124 +#: ../../library/unittest.rst:2127 msgid "" "The default implementation appends a tuple ``(test, formatted_err)`` to the " "instance's :attr:`errors` attribute, where *formatted_err* is a formatted " "traceback derived from *err*." msgstr "" -#: ../../library/unittest.rst:2131 +#: ../../library/unittest.rst:2134 msgid "" "Called when the test case *test* signals a failure. *err* is a tuple of the " "form returned by :func:`sys.exc_info`: ``(type, value, traceback)``." msgstr "" -#: ../../library/unittest.rst:2134 +#: ../../library/unittest.rst:2137 msgid "" "The default implementation appends a tuple ``(test, formatted_err)`` to the " "instance's :attr:`failures` attribute, where *formatted_err* is a formatted " "traceback derived from *err*." msgstr "" -#: ../../library/unittest.rst:2141 +#: ../../library/unittest.rst:2144 msgid "Called when the test case *test* succeeds." msgstr "" -#: ../../library/unittest.rst:2143 +#: ../../library/unittest.rst:2146 msgid "The default implementation does nothing." msgstr "" -#: ../../library/unittest.rst:2148 +#: ../../library/unittest.rst:2151 msgid "" "Called when the test case *test* is skipped. *reason* is the reason the " "test gave for skipping." msgstr "" -#: ../../library/unittest.rst:2151 +#: ../../library/unittest.rst:2154 msgid "" "The default implementation appends a tuple ``(test, reason)`` to the " "instance's :attr:`skipped` attribute." msgstr "" -#: ../../library/unittest.rst:2157 +#: ../../library/unittest.rst:2160 msgid "" "Called when the test case *test* fails or errors, but was marked with the :" "func:`expectedFailure` decorator." msgstr "" -#: ../../library/unittest.rst:2160 +#: ../../library/unittest.rst:2163 msgid "" "The default implementation appends a tuple ``(test, formatted_err)`` to the " "instance's :attr:`expectedFailures` attribute, where *formatted_err* is a " "formatted traceback derived from *err*." msgstr "" -#: ../../library/unittest.rst:2167 +#: ../../library/unittest.rst:2170 msgid "" "Called when the test case *test* was marked with the :func:`expectedFailure` " "decorator, but succeeded." msgstr "" -#: ../../library/unittest.rst:2170 +#: ../../library/unittest.rst:2173 msgid "" "The default implementation appends the test to the instance's :attr:" "`unexpectedSuccesses` attribute." msgstr "" -#: ../../library/unittest.rst:2176 +#: ../../library/unittest.rst:2179 msgid "" "Called when a subtest finishes. *test* is the test case corresponding to " "the test method. *subtest* is a custom :class:`TestCase` instance " "describing the subtest." msgstr "" -#: ../../library/unittest.rst:2180 +#: ../../library/unittest.rst:2183 msgid "" "If *outcome* is :const:`None`, the subtest succeeded. Otherwise, it failed " "with an exception where *outcome* is a tuple of the form returned by :func:" "`sys.exc_info`: ``(type, value, traceback)``." msgstr "" -#: ../../library/unittest.rst:2184 +#: ../../library/unittest.rst:2187 msgid "" "The default implementation does nothing when the outcome is a success, and " "records subtest failures as normal failures." msgstr "" -#: ../../library/unittest.rst:2191 +#: ../../library/unittest.rst:2194 msgid "" "Called when the test case finishes. *elapsed* is the time represented in " "seconds, and it includes the execution of cleanup functions." msgstr "" -#: ../../library/unittest.rst:2198 +#: ../../library/unittest.rst:2201 msgid "" "A concrete implementation of :class:`TestResult` used by the :class:" "`TextTestRunner`. Subclasses should accept ``**kwargs`` to ensure " "compatibility as the interface changes." msgstr "" -#: ../../library/unittest.rst:2204 +#: ../../library/unittest.rst:2207 msgid "Added the *durations* keyword parameter." msgstr "" -#: ../../library/unittest.rst:2209 +#: ../../library/unittest.rst:2212 msgid "" "Instance of the :class:`TestLoader` class intended to be shared. If no " "customization of the :class:`TestLoader` is needed, this instance can be " "used instead of repeatedly creating new instances." msgstr "" -#: ../../library/unittest.rst:2218 +#: ../../library/unittest.rst:2221 msgid "" "A basic test runner implementation that outputs results to a stream. If " "*stream* is ``None``, the default, :data:`sys.stderr` is used as the output " @@ -3011,7 +3403,7 @@ msgid "" "unittest." msgstr "" -#: ../../library/unittest.rst:2225 +#: ../../library/unittest.rst:2228 msgid "" "By default this runner shows :exc:`DeprecationWarning`, :exc:" "`PendingDeprecationWarning`, :exc:`ResourceWarning` and :exc:`ImportWarning` " @@ -3021,32 +3413,32 @@ msgid "" "``None``." msgstr "" -#: ../../library/unittest.rst:2233 +#: ../../library/unittest.rst:2236 msgid "Added the *warnings* parameter." msgstr "" -#: ../../library/unittest.rst:2236 +#: ../../library/unittest.rst:2239 msgid "" "The default stream is set to :data:`sys.stderr` at instantiation time rather " "than import time." msgstr "" -#: ../../library/unittest.rst:2240 +#: ../../library/unittest.rst:2243 msgid "Added the *tb_locals* parameter." msgstr "" -#: ../../library/unittest.rst:2243 +#: ../../library/unittest.rst:2246 msgid "Added the *durations* parameter." msgstr "" -#: ../../library/unittest.rst:2248 +#: ../../library/unittest.rst:2251 msgid "" "This method returns the instance of ``TestResult`` used by :meth:`run`. It " "is not intended to be called directly, but can be overridden in subclasses " "to provide a custom ``TestResult``." msgstr "" -#: ../../library/unittest.rst:2252 +#: ../../library/unittest.rst:2255 msgid "" "``_makeResult()`` instantiates the class or callable passed in the " "``TextTestRunner`` constructor as the ``resultclass`` argument. It defaults " @@ -3054,7 +3446,11 @@ msgid "" "class is instantiated with the following arguments::" msgstr "" -#: ../../library/unittest.rst:2261 +#: ../../library/unittest.rst:2260 +msgid "stream, descriptions, verbosity" +msgstr "" + +#: ../../library/unittest.rst:2264 msgid "" "This method is the main public interface to the ``TextTestRunner``. This " "method takes a :class:`TestSuite` or :class:`TestCase` instance. A :class:" @@ -3062,7 +3458,7 @@ msgid "" "run and the results printed to stdout." msgstr "" -#: ../../library/unittest.rst:2272 +#: ../../library/unittest.rst:2275 msgid "" "A command-line program that loads a set of tests from *module* and runs " "them; this is primarily for making test modules conveniently executable. The " @@ -3072,19 +3468,31 @@ msgstr "" #: ../../library/unittest.rst:2280 msgid "" +"if __name__ == '__main__':\n" +" unittest.main()" +msgstr "" + +#: ../../library/unittest.rst:2283 +msgid "" "You can run tests with more detailed information by passing in the verbosity " "argument::" msgstr "" #: ../../library/unittest.rst:2286 msgid "" +"if __name__ == '__main__':\n" +" unittest.main(verbosity=2)" +msgstr "" + +#: ../../library/unittest.rst:2289 +msgid "" "The *defaultTest* argument is either the name of a single test or an " "iterable of test names to run if no test names are specified via *argv*. If " "not specified or ``None`` and no test names are provided via *argv*, all " "tests found in *module* are run." msgstr "" -#: ../../library/unittest.rst:2291 +#: ../../library/unittest.rst:2294 msgid "" "The *argv* argument can be a list of options passed to the program, with the " "first element being the program name. If not specified or ``None``, the " @@ -3094,7 +3502,7 @@ msgstr "" "o primeiro elemento sendo o nome do programa. Se não for especificado ou for " "``None``, os valores de :data:`sys.argv` são usados." -#: ../../library/unittest.rst:2295 +#: ../../library/unittest.rst:2298 msgid "" "The *testRunner* argument can either be a test runner class or an already " "created instance of it. By default ``main`` calls :func:`sys.exit` with an " @@ -3102,13 +3510,13 @@ msgid "" "code of 5 indicates that no tests were run or skipped." msgstr "" -#: ../../library/unittest.rst:2300 +#: ../../library/unittest.rst:2303 msgid "" "The *testLoader* argument has to be a :class:`TestLoader` instance, and " "defaults to :data:`defaultTestLoader`." msgstr "" -#: ../../library/unittest.rst:2303 +#: ../../library/unittest.rst:2306 msgid "" "``main`` supports being used from the interactive interpreter by passing in " "the argument ``exit=False``. This displays the result on standard output " @@ -3117,11 +3525,17 @@ msgstr "" #: ../../library/unittest.rst:2310 msgid "" +">>> from unittest import main\n" +">>> main(module='test_module', exit=False)" +msgstr "" + +#: ../../library/unittest.rst:2313 +msgid "" "The *failfast*, *catchbreak* and *buffer* parameters have the same effect as " "the same-name `command-line options`_." msgstr "" -#: ../../library/unittest.rst:2313 +#: ../../library/unittest.rst:2316 msgid "" "The *warnings* argument specifies the :ref:`warning filter ` " "that should be used while running the tests. If it's not specified, it will " @@ -3130,56 +3544,60 @@ msgid "" "to ``'default'``." msgstr "" -#: ../../library/unittest.rst:2319 +#: ../../library/unittest.rst:2322 msgid "" "Calling ``main`` returns an object with the ``result`` attribute that " "contains the result of the tests run as a :class:`unittest.TestResult`." msgstr "" -#: ../../library/unittest.rst:2322 +#: ../../library/unittest.rst:2325 msgid "The *exit* parameter was added." msgstr "" -#: ../../library/unittest.rst:2325 +#: ../../library/unittest.rst:2328 msgid "" "The *verbosity*, *failfast*, *catchbreak*, *buffer* and *warnings* " "parameters were added." msgstr "" -#: ../../library/unittest.rst:2329 +#: ../../library/unittest.rst:2332 msgid "" "The *defaultTest* parameter was changed to also accept an iterable of test " "names." msgstr "" -#: ../../library/unittest.rst:2337 +#: ../../library/unittest.rst:2340 msgid "load_tests Protocol" msgstr "" -#: ../../library/unittest.rst:2341 +#: ../../library/unittest.rst:2344 msgid "" "Modules or packages can customize how tests are loaded from them during " "normal test runs or test discovery by implementing a function called " "``load_tests``." msgstr "" -#: ../../library/unittest.rst:2344 +#: ../../library/unittest.rst:2347 msgid "" "If a test module defines ``load_tests`` it will be called by :meth:" "`TestLoader.loadTestsFromModule` with the following arguments::" msgstr "" -#: ../../library/unittest.rst:2349 +#: ../../library/unittest.rst:2350 ../../library/unittest.rst:2382 +msgid "load_tests(loader, standard_tests, pattern)" +msgstr "" + +#: ../../library/unittest.rst:2352 msgid "" "where *pattern* is passed straight through from ``loadTestsFromModule``. It " "defaults to ``None``." msgstr "" -#: ../../library/unittest.rst:2352 +#: ../../library/unittest.rst:2355 msgid "It should return a :class:`TestSuite`." msgstr "" -#: ../../library/unittest.rst:2354 +#: ../../library/unittest.rst:2357 msgid "" "*loader* is the instance of :class:`TestLoader` doing the loading. " "*standard_tests* are the tests that would be loaded by default from the " @@ -3188,13 +3606,25 @@ msgid "" "packages as part of test discovery." msgstr "" -#: ../../library/unittest.rst:2360 +#: ../../library/unittest.rst:2363 msgid "" "A typical ``load_tests`` function that loads tests from a specific set of :" "class:`TestCase` classes may look like::" msgstr "" -#: ../../library/unittest.rst:2372 +#: ../../library/unittest.rst:2366 +msgid "" +"test_cases = (TestCase1, TestCase2, TestCase3)\n" +"\n" +"def load_tests(loader, tests, pattern):\n" +" suite = TestSuite()\n" +" for test_class in test_cases:\n" +" tests = loader.loadTestsFromTestCase(test_class)\n" +" suite.addTests(tests)\n" +" return suite" +msgstr "" + +#: ../../library/unittest.rst:2375 msgid "" "If discovery is started in a directory containing a package, either from the " "command line or by calling :meth:`TestLoader.discover`, then the package :" @@ -3204,31 +3634,41 @@ msgid "" "left up to ``load_tests`` which is called with the following arguments::" msgstr "" -#: ../../library/unittest.rst:2381 +#: ../../library/unittest.rst:2384 msgid "" "This should return a :class:`TestSuite` representing all the tests from the " "package. (``standard_tests`` will only contain tests collected from :file:" "`__init__.py`.)" msgstr "" -#: ../../library/unittest.rst:2385 +#: ../../library/unittest.rst:2388 msgid "" "Because the pattern is passed into ``load_tests`` the package is free to " "continue (and potentially modify) test discovery. A 'do nothing' " "``load_tests`` function for a test package would look like::" msgstr "" -#: ../../library/unittest.rst:2396 +#: ../../library/unittest.rst:2392 +msgid "" +"def load_tests(loader, standard_tests, pattern):\n" +" # top level directory cached on loader instance\n" +" this_dir = os.path.dirname(__file__)\n" +" package_tests = loader.discover(start_dir=this_dir, pattern=pattern)\n" +" standard_tests.addTests(package_tests)\n" +" return standard_tests" +msgstr "" + +#: ../../library/unittest.rst:2399 msgid "" "Discovery no longer checks package names for matching *pattern* due to the " "impossibility of package names matching the default pattern." msgstr "" -#: ../../library/unittest.rst:2403 +#: ../../library/unittest.rst:2406 msgid "Class and Module Fixtures" msgstr "Classes e Módulos de Definição de Contexto" -#: ../../library/unittest.rst:2405 +#: ../../library/unittest.rst:2408 msgid "" "Class and module level fixtures are implemented in :class:`TestSuite`. When " "the test suite encounters a test from a new class then :meth:`tearDownClass` " @@ -3241,14 +3681,14 @@ msgstr "" "houver alguma) é chamado logo antes da chamada do método :meth:`setUpClass` " "da nova classe." -#: ../../library/unittest.rst:2410 +#: ../../library/unittest.rst:2413 msgid "" "Similarly if a test is from a different module from the previous test then " "``tearDownModule`` from the previous module is run, followed by " "``setUpModule`` from the new module." msgstr "" -#: ../../library/unittest.rst:2414 +#: ../../library/unittest.rst:2417 msgid "" "After all the tests have run the final ``tearDownClass`` and " "``tearDownModule`` are run." @@ -3256,14 +3696,14 @@ msgstr "" "Após executar todos os testes, haverá a execução final do ``tearDownClass`` " "e do ``tearDownModule``." -#: ../../library/unittest.rst:2417 +#: ../../library/unittest.rst:2420 msgid "" "Note that shared fixtures do not play well with [potential] features like " "test parallelization and they break test isolation. They should be used with " "care." msgstr "" -#: ../../library/unittest.rst:2420 +#: ../../library/unittest.rst:2423 msgid "" "The default ordering of tests created by the unittest test loaders is to " "group all tests from the same modules and classes together. This will lead " @@ -3273,14 +3713,14 @@ msgid "" "functions may be called multiple times in a single test run." msgstr "" -#: ../../library/unittest.rst:2427 +#: ../../library/unittest.rst:2430 msgid "" "Shared fixtures are not intended to work with suites with non-standard " "ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to " "support shared fixtures." msgstr "" -#: ../../library/unittest.rst:2431 +#: ../../library/unittest.rst:2434 msgid "" "If there are any exceptions raised during one of the shared fixture " "functions the test is reported as an error. Because there is no " @@ -3290,22 +3730,36 @@ msgid "" "matter, but if you are a framework author it may be relevant." msgstr "" -#: ../../library/unittest.rst:2440 +#: ../../library/unittest.rst:2443 msgid "setUpClass and tearDownClass" msgstr "" -#: ../../library/unittest.rst:2442 +#: ../../library/unittest.rst:2445 msgid "These must be implemented as class methods::" msgstr "" -#: ../../library/unittest.rst:2455 +#: ../../library/unittest.rst:2447 +msgid "" +"import unittest\n" +"\n" +"class Test(unittest.TestCase):\n" +" @classmethod\n" +" def setUpClass(cls):\n" +" cls._connection = createExpensiveConnectionObject()\n" +"\n" +" @classmethod\n" +" def tearDownClass(cls):\n" +" cls._connection.destroy()" +msgstr "" + +#: ../../library/unittest.rst:2458 msgid "" "If you want the ``setUpClass`` and ``tearDownClass`` on base classes called " "then you must call up to them yourself. The implementations in :class:" "`TestCase` are empty." msgstr "" -#: ../../library/unittest.rst:2459 +#: ../../library/unittest.rst:2462 msgid "" "If an exception is raised during a ``setUpClass`` then the tests in the " "class are not run and the ``tearDownClass`` is not run. Skipped classes will " @@ -3314,15 +3768,24 @@ msgid "" "instead of as an error." msgstr "" -#: ../../library/unittest.rst:2467 +#: ../../library/unittest.rst:2470 msgid "setUpModule and tearDownModule" msgstr "" -#: ../../library/unittest.rst:2469 +#: ../../library/unittest.rst:2472 msgid "These should be implemented as functions::" msgstr "" -#: ../../library/unittest.rst:2477 +#: ../../library/unittest.rst:2474 +msgid "" +"def setUpModule():\n" +" createConnection()\n" +"\n" +"def tearDownModule():\n" +" closeConnection()" +msgstr "" + +#: ../../library/unittest.rst:2480 msgid "" "If an exception is raised in a ``setUpModule`` then none of the tests in the " "module will be run and the ``tearDownModule`` will not be run. If the " @@ -3330,13 +3793,13 @@ msgid "" "having been skipped instead of as an error." msgstr "" -#: ../../library/unittest.rst:2482 +#: ../../library/unittest.rst:2485 msgid "" "To add cleanup code that must be run even in the case of an exception, use " "``addModuleCleanup``:" msgstr "" -#: ../../library/unittest.rst:2488 +#: ../../library/unittest.rst:2491 msgid "" "Add a function to be called after :func:`tearDownModule` to cleanup " "resources used during the test class. Functions will be called in reverse " @@ -3345,13 +3808,13 @@ msgid "" "`addModuleCleanup` when they are added." msgstr "" -#: ../../library/unittest.rst:2494 +#: ../../library/unittest.rst:2497 msgid "" "If :meth:`setUpModule` fails, meaning that :func:`tearDownModule` is not " "called, then any cleanup functions added will still be called." msgstr "" -#: ../../library/unittest.rst:2502 +#: ../../library/unittest.rst:2505 msgid "" "Enter the supplied :term:`context manager`. If successful, also add its :" "meth:`~object.__exit__` method as a cleanup function by :func:" @@ -3359,40 +3822,40 @@ msgid "" "method." msgstr "" -#: ../../library/unittest.rst:2512 +#: ../../library/unittest.rst:2515 msgid "" "This function is called unconditionally after :func:`tearDownModule`, or " "after :func:`setUpModule` if :func:`setUpModule` raises an exception." msgstr "" -#: ../../library/unittest.rst:2515 +#: ../../library/unittest.rst:2518 msgid "" "It is responsible for calling all the cleanup functions added by :func:" "`addModuleCleanup`. If you need cleanup functions to be called *prior* to :" "func:`tearDownModule` then you can call :func:`doModuleCleanups` yourself." msgstr "" -#: ../../library/unittest.rst:2520 +#: ../../library/unittest.rst:2523 msgid "" ":func:`doModuleCleanups` pops methods off the stack of cleanup functions one " "at a time, so it can be called at any time." msgstr "" -#: ../../library/unittest.rst:2527 +#: ../../library/unittest.rst:2530 msgid "Signal Handling" msgstr "Tratamento de sinal" -#: ../../library/unittest.rst:2531 +#: ../../library/unittest.rst:2534 msgid "" "The :option:`-c/--catch ` command-line option to unittest, " -"along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide " +"along with the ``catchbreak`` parameter to :func:`unittest.main`, provide " "more friendly handling of control-C during a test run. With catch break " "behavior enabled control-C will allow the currently running test to " "complete, and the test run will then end and report all the results so far. " "A second control-c will raise a :exc:`KeyboardInterrupt` in the usual way." msgstr "" -#: ../../library/unittest.rst:2538 +#: ../../library/unittest.rst:2541 msgid "" "The control-c handling signal handler attempts to remain compatible with " "code or tests that install their own :const:`signal.SIGINT` handler. If the " @@ -3404,34 +3867,34 @@ msgid "" "disabled the :func:`removeHandler` decorator can be used." msgstr "" -#: ../../library/unittest.rst:2547 +#: ../../library/unittest.rst:2550 msgid "" "There are a few utility functions for framework authors to enable control-c " "handling functionality within test frameworks." msgstr "" -#: ../../library/unittest.rst:2552 +#: ../../library/unittest.rst:2555 msgid "" "Install the control-c handler. When a :const:`signal.SIGINT` is received " "(usually in response to the user pressing control-c) all registered results " "have :meth:`~TestResult.stop` called." msgstr "" -#: ../../library/unittest.rst:2559 +#: ../../library/unittest.rst:2562 msgid "" "Register a :class:`TestResult` object for control-c handling. Registering a " "result stores a weak reference to it, so it doesn't prevent the result from " "being garbage collected." msgstr "" -#: ../../library/unittest.rst:2563 +#: ../../library/unittest.rst:2566 msgid "" "Registering a :class:`TestResult` object has no side-effects if control-c " "handling is not enabled, so test frameworks can unconditionally register all " "results they create independently of whether or not handling is enabled." msgstr "" -#: ../../library/unittest.rst:2570 +#: ../../library/unittest.rst:2573 msgid "" "Remove a registered result. Once a result has been removed then :meth:" "`~TestResult.stop` will no longer be called on that result object in " @@ -3441,9 +3904,16 @@ msgstr "" "meth:`~TestResult.stop` não será mais chamado no objeto resultado em " "resposta a um Ctrl+C" -#: ../../library/unittest.rst:2577 +#: ../../library/unittest.rst:2580 msgid "" "When called without arguments this function removes the control-c handler if " "it has been installed. This function can also be used as a test decorator to " "temporarily remove the handler while the test is being executed::" msgstr "" + +#: ../../library/unittest.rst:2584 +msgid "" +"@unittest.removeHandler\n" +"def test_signal_handling(self):\n" +" ..." +msgstr "" diff --git a/library/unix.po b/library/unix.po index 271b704d7..8d16e022a 100644 --- a/library/unix.po +++ b/library/unix.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:16+0000\n" -"Last-Translator: Claudio Rogerio Carvalho Filho , " -"2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/urllib.error.po b/library/urllib.error.po index 379c53a84..a8c27eb97 100644 --- a/library/urllib.error.po +++ b/library/urllib.error.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:16+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/urllib.parse.po b/library/urllib.parse.po index 523417dbc..f917d0064 100644 --- a/library/urllib.parse.po +++ b/library/urllib.parse.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# i17obot , 2021 -# Claudio Rogerio Carvalho Filho , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-26 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:17+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -56,6 +53,13 @@ msgid "" "``rtsps``, ``rtspu``, ``sftp``, ``shttp``, ``sip``, ``sips``, ``snews``, " "``svn``, ``svn+ssh``, ``telnet``, ``wais``, ``ws``, ``wss``." msgstr "" +"O módulo foi projetado para corresponder ao RFC da internet sobre " +"Localizadores de Recursos Uniformes Relativos, ou URL relativa. Ele tem " +"suporte aos seguintes esquemas de URL: ``file``, ``ftp``, ``gopher``, " +"``hdl``, ``http``, ``https``, ``imap``, ``itms-services``, ``mailto``, " +"``mms``, ``news``, ``nntp``, ``prospero``, ``rsync``, ``rtsp``, ``rtsps``," +"``rtspu``, ``sftp``, ``shttp``, ``sip``, ``sips``, ``snews``, ``svn``, " +"``svn+ssh``, ``telnet``, ``wais``, ``ws``, ``wss``." #: ../../library/urllib.parse.rst:32 msgid "" @@ -65,6 +69,11 @@ msgid "" "macOS, it *may* be removed if CPython has been built with the :option:`--" "with-app-store-compliance` option." msgstr "" +"A inclusão do esquema de URL ``itms-services`` pode impedir que uma " +"aplicação passe pelo processo de revisão da App Store da Apple para as App " +"Stores do macOS e iOS. O tratamento do esquema ``itms-services`` é sempre " +"removido no iOS; no macOS, ele *pode* ser removido se o CPython tiver sido " +"criado com a opção :option:`--with-app-store-compliance`." #: ../../library/urllib.parse.rst:38 msgid "" @@ -121,6 +130,52 @@ msgstr "" "resultado, exceto por uma barra inicial no componente *path*, que é retido " "se estiver presente. Por exemplo:" +#: ../../library/urllib.parse.rst:64 +msgid "" +">>> from urllib.parse import urlparse\n" +">>> urlparse(\"scheme://netloc/path;parameters?query#fragment\")\n" +"ParseResult(scheme='scheme', netloc='netloc', path='/path;parameters', " +"params='',\n" +" query='query', fragment='fragment')\n" +">>> o = urlparse(\"http://docs.python.org:80/3/library/urllib.parse.html?\"\n" +"... \"highlight=params#url-parsing\")\n" +">>> o\n" +"ParseResult(scheme='http', netloc='docs.python.org:80',\n" +" path='/3/library/urllib.parse.html', params='',\n" +" query='highlight=params', fragment='url-parsing')\n" +">>> o.scheme\n" +"'http'\n" +">>> o.netloc\n" +"'docs.python.org:80'\n" +">>> o.hostname\n" +"'docs.python.org'\n" +">>> o.port\n" +"80\n" +">>> o._replace(fragment=\"\").geturl()\n" +"'http://docs.python.org:80/3/library/urllib.parse.html?highlight=params'" +msgstr "" +">>> from urllib.parse import urlparse\n" +">>> urlparse(\"scheme://netloc/path;parameters?query#fragment\")\n" +"ParseResult(scheme='scheme', netloc='netloc', path='/path;parameters', " +"params='',\n" +" query='query', fragment='fragment')\n" +">>> o = urlparse(\"http://docs.python.org:80/3/library/urllib.parse.html?\"\n" +"... \"highlight=params#url-parsing\")\n" +">>> o\n" +"ParseResult(scheme='http', netloc='docs.python.org:80',\n" +" path='/3/library/urllib.parse.html', params='',\n" +" query='highlight=params', fragment='url-parsing')\n" +">>> o.scheme\n" +"'http'\n" +">>> o.netloc\n" +"'docs.python.org:80'\n" +">>> o.hostname\n" +"'docs.python.org'\n" +">>> o.port\n" +"80\n" +">>> o._replace(fragment=\"\").geturl()\n" +"'http://docs.python.org:80/3/library/urllib.parse.html?highlight=params'" + #: ../../library/urllib.parse.rst:88 msgid "" "Following the syntax specifications in :rfc:`1808`, urlparse recognizes a " @@ -132,6 +187,32 @@ msgstr "" "contrário, presume-se que a entrada seja uma URL relativa e, portanto, " "comece com um componente de caminho." +#: ../../library/urllib.parse.rst:93 +msgid "" +">>> from urllib.parse import urlparse\n" +">>> urlparse('//www.cwi.nl:80/%7Eguido/Python.html')\n" +"ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python." +"html',\n" +" params='', query='', fragment='')\n" +">>> urlparse('www.cwi.nl/%7Eguido/Python.html')\n" +"ParseResult(scheme='', netloc='', path='www.cwi.nl/%7Eguido/Python.html',\n" +" params='', query='', fragment='')\n" +">>> urlparse('help/Python.html')\n" +"ParseResult(scheme='', netloc='', path='help/Python.html', params='',\n" +" query='', fragment='')" +msgstr "" +">>> from urllib.parse import urlparse\n" +">>> urlparse('//www.cwi.nl:80/%7Eguido/Python.html')\n" +"ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python." +"html',\n" +" params='', query='', fragment='')\n" +">>> urlparse('www.cwi.nl/%7Eguido/Python.html')\n" +"ParseResult(scheme='', netloc='', path='www.cwi.nl/%7Eguido/Python.html',\n" +" params='', query='', fragment='')\n" +">>> urlparse('help/Python.html')\n" +"ParseResult(scheme='', netloc='', path='help/Python.html', params='',\n" +" query='', fragment='')" + #: ../../library/urllib.parse.rst:107 msgid "" "The *scheme* argument gives the default addressing scheme, to be used only " @@ -165,22 +246,22 @@ msgstr "" "itens podem ser acessados por índice ou como atributos nomeados, que são:" #: ../../library/urllib.parse.rst:121 ../../library/urllib.parse.rst:310 -#: ../../library/urllib.parse.rst:423 +#: ../../library/urllib.parse.rst:432 msgid "Attribute" msgstr "Atributo" #: ../../library/urllib.parse.rst:121 ../../library/urllib.parse.rst:310 -#: ../../library/urllib.parse.rst:423 +#: ../../library/urllib.parse.rst:432 msgid "Index" msgstr "Índice" #: ../../library/urllib.parse.rst:121 ../../library/urllib.parse.rst:310 -#: ../../library/urllib.parse.rst:423 +#: ../../library/urllib.parse.rst:432 msgid "Value" msgstr "Valor" #: ../../library/urllib.parse.rst:121 ../../library/urllib.parse.rst:310 -#: ../../library/urllib.parse.rst:423 +#: ../../library/urllib.parse.rst:432 msgid "Value if not present" msgstr "Valor, se não presente" @@ -189,7 +270,7 @@ msgid ":attr:`scheme`" msgstr ":attr:`scheme`" #: ../../library/urllib.parse.rst:123 ../../library/urllib.parse.rst:312 -#: ../../library/urllib.parse.rst:425 +#: ../../library/urllib.parse.rst:434 msgid "0" msgstr "0" @@ -206,7 +287,7 @@ msgid ":attr:`netloc`" msgstr ":attr:`netloc`" #: ../../library/urllib.parse.rst:125 ../../library/urllib.parse.rst:314 -#: ../../library/urllib.parse.rst:427 +#: ../../library/urllib.parse.rst:436 msgid "1" msgstr "1" @@ -218,8 +299,8 @@ msgstr "Parte da localização na rede" #: ../../library/urllib.parse.rst:129 ../../library/urllib.parse.rst:132 #: ../../library/urllib.parse.rst:134 ../../library/urllib.parse.rst:314 #: ../../library/urllib.parse.rst:316 ../../library/urllib.parse.rst:318 -#: ../../library/urllib.parse.rst:320 ../../library/urllib.parse.rst:425 -#: ../../library/urllib.parse.rst:427 +#: ../../library/urllib.parse.rst:320 ../../library/urllib.parse.rst:434 +#: ../../library/urllib.parse.rst:436 msgid "empty string" msgstr "string vazia" @@ -260,7 +341,7 @@ msgid "Query component" msgstr "Componente da consulta" #: ../../library/urllib.parse.rst:134 ../../library/urllib.parse.rst:320 -#: ../../library/urllib.parse.rst:427 +#: ../../library/urllib.parse.rst:436 msgid ":attr:`fragment`" msgstr ":attr:`fragment`" @@ -269,7 +350,7 @@ msgid "5" msgstr "5" #: ../../library/urllib.parse.rst:134 ../../library/urllib.parse.rst:320 -#: ../../library/urllib.parse.rst:427 +#: ../../library/urllib.parse.rst:436 msgid "Fragment identifier" msgstr "Identificador do fragmento" @@ -354,6 +435,30 @@ msgstr "" "meth:`_replace`. O método :meth:`_replace` retornará um novo objeto " "ParseResult substituindo os campos especificados por novos valores." +#: ../../library/urllib.parse.rst:163 +msgid "" +">>> from urllib.parse import urlparse\n" +">>> u = urlparse('//www.cwi.nl:80/%7Eguido/Python.html')\n" +">>> u\n" +"ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python." +"html',\n" +" params='', query='', fragment='')\n" +">>> u._replace(scheme='http')\n" +"ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python." +"html',\n" +" params='', query='', fragment='')" +msgstr "" +">>> from urllib.parse import urlparse\n" +">>> u = urlparse('//www.cwi.nl:80/%7Eguido/Python.html')\n" +">>> u\n" +"ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python." +"html',\n" +" params='', query='', fragment='')\n" +">>> u._replace(scheme='http')\n" +"ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python." +"html',\n" +" params='', query='', fragment='')" + #: ../../library/urllib.parse.rst:177 msgid "" ":func:`urlparse` does not perform validation. See :ref:`URL parsing " @@ -483,6 +588,10 @@ msgid "" "parameter separator. This has been changed to allow only a single separator " "key, with ``&`` as the default separator." msgstr "" +"Adicionado parâmetro *separator* com o valor padrão de ``&``. Versões do " +"Python anteriores ao Python 3.10 permitiam o uso de ``;`` e ``&`` como " +"separador de parâmetro de consulta. Isso foi alterado para permitir apenas " +"uma única chave separadora, com ``&`` como o separador padrão." #: ../../library/urllib.parse.rst:245 msgid "" @@ -490,12 +599,17 @@ msgid "" "`application/x-www-form-urlencoded`). Data are returned as a list of name, " "value pairs." msgstr "" +"Analisa uma string de consulta fornecida como um argumento de string (dados " +"do tipo :mimetype:`application/x-www-form-urlencoded`). Os dados são " +"retornados como uma lista de pares de nome e valor." #: ../../library/urllib.parse.rst:270 msgid "" "Use the :func:`urllib.parse.urlencode` function to convert such lists of " "pairs into query strings." msgstr "" +"Use a função :func:`urllib.parse.urlencode` para converter essas listas " +"pares de strings de consulta." #: ../../library/urllib.parse.rst:288 msgid "" @@ -505,6 +619,12 @@ msgid "" "unnecessary delimiters (for example, a ``?`` with an empty query; the RFC " "states that these are equivalent)." msgstr "" +"Constrói uma URL a partir de uma tupla conforme retornada por " +"``urlparse()``. O argumento *parts* pode ser qualquer iterável de seis " +"itens. Isso pode resultar em uma URL ligeiramente diferente, mas " +"equivalente, se a URL que foi analisada originalmente tiver delimitadores " +"desnecessários (por exemplo, um ``?`` com uma consulta vazia; o RFC afirma " +"que eles são equivalentes)." #: ../../library/urllib.parse.rst:297 msgid "" @@ -515,12 +635,27 @@ msgid "" "is needed to separate the path segments and parameters. This function " "returns a 5-item :term:`named tuple`::" msgstr "" +"Isto é similar a :func:`urlparse`, mas não divide os parâmetros da URL. Isto " +"deve ser usado geralmente em vez de :func:`urlparse` se a sintaxe de URL " +"mais recente permitindo que parâmetros sejam aplicados a cada segmento da " +"porção *path* da URL (veja :rfc:`2396`) for desejada. Uma função separada é " +"necessária para separar os segmentos de caminho e parâmetros. Esta função " +"retorna uma :term:`tupla nomeada` de 5 itens::" + +#: ../../library/urllib.parse.rst:304 +msgid "" +"(addressing scheme, network location, path, query, fragment identifier)." +msgstr "" +"(esquema de endereçamento, local de rede, caminho, consulta, identificador " +"de fragmento)." -#: ../../library/urllib.parse.rst:306 ../../library/urllib.parse.rst:419 +#: ../../library/urllib.parse.rst:306 ../../library/urllib.parse.rst:428 msgid "" "The return value is a :term:`named tuple`, its items can be accessed by " "index or as named attributes:" msgstr "" +"O valor de retorno é uma :term:`tupla nomeada`, seus itens podem ser " +"acessados por índice ou como atributos nomeados:" #: ../../library/urllib.parse.rst:344 msgid "" @@ -528,21 +663,29 @@ msgid "" "control and space characters are stripped from the URL. ``\\n``, ``\\r`` and " "tab ``\\t`` characters are removed from the URL at any position." msgstr "" +"Seguindo algumas das `especificações WHATWG`_ que atualizam o RFC 3986, os " +"caracteres de controle C0 e espaço iniciais são removidos da URL. Os " +"caracteres ``\\n``, ``\\r`` e tab ``\\t`` são removidos da URL em qualquer " +"posição." #: ../../library/urllib.parse.rst:350 msgid "" ":func:`urlsplit` does not perform validation. See :ref:`URL parsing " "security ` for details." msgstr "" +":func:`urlsplit` não executa validação. Veja :ref:`Segurança ao analisar " +"URLs ` para detalhes." #: ../../library/urllib.parse.rst:361 msgid "ASCII newline and tab characters are stripped from the URL." -msgstr "" +msgstr "Caracteres de nova linha e tabulação ASCII são removidos do URL." #: ../../library/urllib.parse.rst:364 msgid "" "Leading WHATWG C0 control and space characters are stripped from the URL." msgstr "" +"Os caracteres iniciais de espaço e de controle WHATWG C0 são removidos do " +"URL." #: ../../library/urllib.parse.rst:371 msgid "" @@ -552,6 +695,12 @@ msgid "" "the URL that was parsed originally had unnecessary delimiters (for example, " "a ? with an empty query; the RFC states that these are equivalent)." msgstr "" +"Combina os elementos de uma tupla conforme retornado por :func:`urlsplit` em " +"uma URL completa como uma string. O argumento *parts* pode ser qualquer " +"iterável de cinco itens. Isso pode resultar em uma URL ligeiramente " +"diferente, mas equivalente, se a URL que foi analisada originalmente tiver " +"delimitadores desnecessários (por exemplo, um ? com uma consulta vazia; o " +"RFC afirma que eles são equivalentes)." #: ../../library/urllib.parse.rst:380 msgid "" @@ -560,12 +709,19 @@ msgid "" "in particular the addressing scheme, the network location and (part of) the " "path, to provide missing components in the relative URL. For example:" msgstr "" +"Constrói uma URL completa (\"absoluta\") combinando uma \"URL " +"base\" (*base*) com outra URL (*url*). Informalmente, isso usa componentes " +"da URL base, em particular o esquema de endereçamento, o local da rede e " +"(parte do) caminho, para fornecer componentes ausentes na URL relativa. Por " +"exemplo:" #: ../../library/urllib.parse.rst:389 msgid "" "The *allow_fragments* argument has the same meaning and default as for :func:" "`urlparse`." msgstr "" +"O argumento *allow_fragments* tem o mesmo significado e padrão que :func:" +"`urlparse`." #: ../../library/urllib.parse.rst:394 msgid "" @@ -573,56 +729,100 @@ msgid "" "``), the *url*'s hostname and/or scheme will be present in the result. For " "example:" msgstr "" +"Se *url* for uma URL absoluta (ou seja, começa com ``//`` ou ``scheme://``), " +"o nome do host e/ou esquema da *url* estarão presentes no resultado. Por " +"exemplo:" + +#: ../../library/urllib.parse.rst:397 +msgid "" +">>> urljoin('http://www.cwi.nl/%7Eguido/Python.html',\n" +"... '//www.python.org/%7Eguido')\n" +"'http://www.python.org/%7Eguido'" +msgstr "" +">>> urljoin('http://www.cwi.nl/%7Eguido/Python.html',\n" +"... '//www.python.org/%7Eguido')\n" +"'http://www.python.org/%7Eguido'" #: ../../library/urllib.parse.rst:403 msgid "" "If you do not want that behavior, preprocess the *url* with :func:`urlsplit` " "and :func:`urlunsplit`, removing possible *scheme* and *netloc* parts." msgstr "" +"Se você não quiser esse comportamento, pré-processe a *url* com :func:" +"`urlsplit` e :func:`urlunsplit`, removendo possíveis partes *scheme* e " +"*netloc*." + +#: ../../library/urllib.parse.rst:408 +msgid "" +"Because an absolute URL may be passed as the ``url`` parameter, it is " +"generally **not secure** to use ``urljoin`` with an attacker-controlled " +"``url``. For example in, ``urljoin(\"https://website.com/users/\", " +"username)``, if ``username`` can contain an absolute URL, the result of " +"``urljoin`` will be the absolute URL." +msgstr "" +"Como uma URL absoluta pode ser passada como o parâmetro ``url``, geralmente " +"**não é seguro** usar ``urljoin`` com uma ``url`` controlada pelo invasor. " +"Por exemplo, em ``urljoin(\"https://website.com/users/\", username)``, se " +"``username`` puder conter uma URL absoluta, o resultado de ``urljoin`` será " +"a URL absoluta." -#: ../../library/urllib.parse.rst:409 +#: ../../library/urllib.parse.rst:418 msgid "Behavior updated to match the semantics defined in :rfc:`3986`." msgstr "" +"Comportamento atualizado para corresponder à semântica definida no :rfc:" +"`3986`." -#: ../../library/urllib.parse.rst:414 +#: ../../library/urllib.parse.rst:423 msgid "" "If *url* contains a fragment identifier, return a modified version of *url* " "with no fragment identifier, and the fragment identifier as a separate " "string. If there is no fragment identifier in *url*, return *url* " "unmodified and an empty string." msgstr "" +"Se *url* contiver um identificador de fragmento, retorna uma versão " +"modificada de *url* sem identificador de fragmento, e o identificador de " +"fragmento como uma string separada. Se não houver identificador de fragmento " +"em *url*, retorna *url* não modificado e uma string vazia." -#: ../../library/urllib.parse.rst:425 +#: ../../library/urllib.parse.rst:434 msgid ":attr:`url`" msgstr ":attr:`url`" -#: ../../library/urllib.parse.rst:425 +#: ../../library/urllib.parse.rst:434 msgid "URL with no fragment" -msgstr "" +msgstr "URL com nenhum fragmento" -#: ../../library/urllib.parse.rst:430 +#: ../../library/urllib.parse.rst:439 msgid "" "See section :ref:`urlparse-result-object` for more information on the result " "object." msgstr "" +"Veja a seção :ref:`urlparse-result-object` para obter mais informações sobre " +"o objeto de resultado." -#: ../../library/urllib.parse.rst:433 +#: ../../library/urllib.parse.rst:442 msgid "Result is a structured object rather than a simple 2-tuple." msgstr "" +"O resultado é um objeto estruturado em vez de uma simples tupla de 2 " +"elementos." -#: ../../library/urllib.parse.rst:438 +#: ../../library/urllib.parse.rst:447 msgid "" "Extract the url from a wrapped URL (that is, a string formatted as ````, ````, ``URL:scheme://host/path`` " "or ``scheme://host/path``). If *url* is not a wrapped URL, it is returned " "without changes." msgstr "" +"Extrai a URL de uma URL encapsulada (ou seja, uma string formatada como " +"````, ````, ``URL:" +"esquema://host/caminho`` ou ``esquema://host/caminho``). Se *url* não for " +"uma URL encapsulada, ela será retornada sem alterações." -#: ../../library/urllib.parse.rst:446 +#: ../../library/urllib.parse.rst:455 msgid "URL parsing security" msgstr "Segurança ao analisar URLs" -#: ../../library/urllib.parse.rst:448 +#: ../../library/urllib.parse.rst:457 msgid "" "The :func:`urlsplit` and :func:`urlparse` APIs do not perform **validation** " "of inputs. They may not raise errors on inputs that other applications " @@ -630,15 +830,23 @@ msgid "" "considered URLs elsewhere. Their purpose is for practical functionality " "rather than purity." msgstr "" +"As APIs :func:`urlsplit` e :func:`urlparse` não realizam **validação** de " +"entradas. Elas podem não levantar erros em entradas que outras aplicações " +"consideram inválidas. Elas também podem ter sucesso em algumas entradas que " +"podem não ser consideradas URLs em outros lugares. Seu propósito é para " +"funcionalidade prática em vez de pureza." -#: ../../library/urllib.parse.rst:454 +#: ../../library/urllib.parse.rst:463 msgid "" "Instead of raising an exception on unusual input, they may instead return " "some component parts as empty strings. Or components may contain more than " "perhaps they should." msgstr "" +"Em vez de levantar uma exceção em uma entrada incomum, eles podem retornar " +"algumas partes do componente como strings vazias. Ou os componentes podem " +"conter mais do que talvez devessem." -#: ../../library/urllib.parse.rst:458 +#: ../../library/urllib.parse.rst:467 msgid "" "We recommend that users of these APIs where the values may be used anywhere " "with security implications code defensively. Do some verification within " @@ -646,8 +854,13 @@ msgid "" "make sense? Is that a sensible ``path``? Is there anything strange about " "that ``hostname``? etc." msgstr "" +"Recomendamos que os usuários dessas APIs, onde os valores podem ser usados " +"em qualquer lugar com implicações de segurança, codifiquem defensivamente. " +"Faça alguma verificação dentro do seu código antes de confiar em uma parte " +"do componente retornada. Esse ``esquema`` faz sentido? Esse ``caminho`` " +"sensato? Há algo estranho sobre esse ``hostname``? etc." -#: ../../library/urllib.parse.rst:464 +#: ../../library/urllib.parse.rst:473 msgid "" "What constitutes a URL is not universally well defined. Different " "applications have different needs and desired constraints. For instance the " @@ -658,12 +871,21 @@ msgid "" "behaviors predate both standards leading us to be very cautious about making " "API behavior changes." msgstr "" - -#: ../../library/urllib.parse.rst:475 +"O que constitui uma URL não é universalmente bem definido. Diferentes " +"aplicações têm diferentes necessidades e restrições desejadas. Por exemplo, " +"a `especificação WHATWG`_ descreve o que os clientes web voltados para o " +"usuário, como um navegador web, exigem. Por outro lado, :rfc:`3986` é mais " +"geral. Essas funções incorporam alguns aspectos de ambos, mas não podem ser " +"reivindicadas como compatíveis com nenhum deles. As APIs e o código de " +"usuário existente com expectativas sobre comportamentos específicos são " +"anteriores a ambos os padrões, o que nos leva a ser muito cautelosos ao " +"fazer alterações no comportamento da API." + +#: ../../library/urllib.parse.rst:484 msgid "Parsing ASCII Encoded Bytes" msgstr "Analisando bytes codificados em ASCII" -#: ../../library/urllib.parse.rst:477 +#: ../../library/urllib.parse.rst:486 msgid "" "The URL parsing functions were originally designed to operate on character " "strings only. In practice, it is useful to be able to manipulate properly " @@ -671,23 +893,35 @@ msgid "" "parsing functions in this module all operate on :class:`bytes` and :class:" "`bytearray` objects in addition to :class:`str` objects." msgstr "" +"As funções de análise de URL foram originalmente projetadas para operar " +"somente em strings de caracteres. Na prática, é útil ser capaz de manipular " +"URLs corretamente citadas e codificadas como sequências de bytes ASCII. " +"Consequentemente, todas as funções de análise de URL neste módulo operam em " +"objetos :class:`bytes` e :class:`bytearray` além de objetos :class:`str`." -#: ../../library/urllib.parse.rst:483 +#: ../../library/urllib.parse.rst:492 msgid "" "If :class:`str` data is passed in, the result will also contain only :class:" "`str` data. If :class:`bytes` or :class:`bytearray` data is passed in, the " "result will contain only :class:`bytes` data." msgstr "" +"Se dados :class:`str` forem passados, o resultado também conterá apenas " +"dados :class:`str`. Se dados :class:`bytes` ou :class:`bytearray` forem " +"passados, o resultado conterá apenas dados :class:`bytes`." -#: ../../library/urllib.parse.rst:487 +#: ../../library/urllib.parse.rst:496 msgid "" "Attempting to mix :class:`str` data with :class:`bytes` or :class:" "`bytearray` in a single function call will result in a :exc:`TypeError` " "being raised, while attempting to pass in non-ASCII byte values will " "trigger :exc:`UnicodeDecodeError`." msgstr "" +"Tentar misturar dados :class:`str` com :class:`bytes` ou :class:`bytearray` " +"em uma única chamada de função resultará em uma :exc:`TypeError` sendo " +"levantada, enquanto tentar passar valores de bytes não-ASCII acionará :exc:" +"`UnicodeDecodeError`." -#: ../../library/urllib.parse.rst:492 +#: ../../library/urllib.parse.rst:501 msgid "" "To support easier conversion of result objects between :class:`str` and :" "class:`bytes`, all return values from URL parsing functions provide either " @@ -699,31 +933,50 @@ msgid "" "contains either :class:`bytes` data (for :meth:`encode` methods) or :class:" "`str` data (for :meth:`decode` methods)." msgstr "" +"Para prover uma conversão mais fácil de objetos de resultado entre :class:" +"`str` e :class:`bytes`, todos os valores de retorno das funções de análise " +"de URL fornecem um método :meth:`encode` (quando o resultado contém dados :" +"class:`str`) ou um método :meth:`decode` (quando o resultado contém dados :" +"class:`bytes`). As assinaturas desses métodos correspondem às dos métodos :" +"class:`str` e :class:`bytes` correspondentes (exceto que a codificação " +"padrão é ``'ascii'`` em vez de ``'utf-8'``). Cada um produz um valor de um " +"tipo correspondente que contém dados :class:`bytes` (para métodos :meth:" +"`encode`) ou dados :class:`str` (para métodos :meth:`decode`)." -#: ../../library/urllib.parse.rst:503 +#: ../../library/urllib.parse.rst:512 msgid "" "Applications that need to operate on potentially improperly quoted URLs that " "may contain non-ASCII data will need to do their own decoding from bytes to " "characters before invoking the URL parsing methods." msgstr "" +"Os aplicações que precisam operar em URLs possivelmente envolta em aspas de " +"forma incorreta, e que podem conter dados não ASCII, precisarão fazer sua " +"própria decodificação de bytes para caracteres antes de invocar os métodos " +"de análise de URL." -#: ../../library/urllib.parse.rst:507 +#: ../../library/urllib.parse.rst:516 msgid "" "The behaviour described in this section applies only to the URL parsing " "functions. The URL quoting functions use their own rules when producing or " "consuming byte sequences as detailed in the documentation of the individual " "URL quoting functions." msgstr "" +"O comportamento descrito nesta seção se aplica somente às funções de análise " +"de URL. As funções de aplicação de aspas em URL usam suas próprias regras ao " +"produzir ou consumir sequências de bytes, conforme detalhado na documentação " +"das funções de citação de URL individuais." -#: ../../library/urllib.parse.rst:512 +#: ../../library/urllib.parse.rst:521 msgid "URL parsing functions now accept ASCII encoded byte sequences" msgstr "" +"As funções de análise de URL agora aceitam sequências de bytes codificadas " +"em ASCII" -#: ../../library/urllib.parse.rst:519 +#: ../../library/urllib.parse.rst:528 msgid "Structured Parse Results" msgstr "" -#: ../../library/urllib.parse.rst:521 +#: ../../library/urllib.parse.rst:530 msgid "" "The result objects from the :func:`urlparse`, :func:`urlsplit` and :func:" "`urldefrag` functions are subclasses of the :class:`tuple` type. These " @@ -732,7 +985,7 @@ msgid "" "section, as well as an additional method:" msgstr "" -#: ../../library/urllib.parse.rst:529 +#: ../../library/urllib.parse.rst:538 msgid "" "Return the re-combined version of the original URL as a string. This may " "differ from the original URL in that the scheme may be normalized to lower " @@ -740,72 +993,72 @@ msgid "" "queries, and fragment identifiers will be removed." msgstr "" -#: ../../library/urllib.parse.rst:534 +#: ../../library/urllib.parse.rst:543 msgid "" "For :func:`urldefrag` results, only empty fragment identifiers will be " "removed. For :func:`urlsplit` and :func:`urlparse` results, all noted " "changes will be made to the URL returned by this method." msgstr "" -#: ../../library/urllib.parse.rst:538 +#: ../../library/urllib.parse.rst:547 msgid "" "The result of this method remains unchanged if passed back through the " "original parsing function:" msgstr "" -#: ../../library/urllib.parse.rst:551 +#: ../../library/urllib.parse.rst:560 msgid "" "The following classes provide the implementations of the structured parse " "results when operating on :class:`str` objects:" msgstr "" -#: ../../library/urllib.parse.rst:556 +#: ../../library/urllib.parse.rst:565 msgid "" "Concrete class for :func:`urldefrag` results containing :class:`str` data. " "The :meth:`encode` method returns a :class:`DefragResultBytes` instance." msgstr "" -#: ../../library/urllib.parse.rst:564 +#: ../../library/urllib.parse.rst:573 msgid "" "Concrete class for :func:`urlparse` results containing :class:`str` data. " "The :meth:`encode` method returns a :class:`ParseResultBytes` instance." msgstr "" -#: ../../library/urllib.parse.rst:570 +#: ../../library/urllib.parse.rst:579 msgid "" "Concrete class for :func:`urlsplit` results containing :class:`str` data. " "The :meth:`encode` method returns a :class:`SplitResultBytes` instance." msgstr "" -#: ../../library/urllib.parse.rst:575 +#: ../../library/urllib.parse.rst:584 msgid "" "The following classes provide the implementations of the parse results when " "operating on :class:`bytes` or :class:`bytearray` objects:" msgstr "" -#: ../../library/urllib.parse.rst:580 +#: ../../library/urllib.parse.rst:589 msgid "" "Concrete class for :func:`urldefrag` results containing :class:`bytes` data. " "The :meth:`decode` method returns a :class:`DefragResult` instance." msgstr "" -#: ../../library/urllib.parse.rst:588 +#: ../../library/urllib.parse.rst:597 msgid "" "Concrete class for :func:`urlparse` results containing :class:`bytes` data. " "The :meth:`decode` method returns a :class:`ParseResult` instance." msgstr "" -#: ../../library/urllib.parse.rst:596 +#: ../../library/urllib.parse.rst:605 msgid "" "Concrete class for :func:`urlsplit` results containing :class:`bytes` data. " "The :meth:`decode` method returns a :class:`SplitResult` instance." msgstr "" -#: ../../library/urllib.parse.rst:604 +#: ../../library/urllib.parse.rst:613 msgid "URL Quoting" msgstr "" -#: ../../library/urllib.parse.rst:606 +#: ../../library/urllib.parse.rst:615 msgid "" "The URL quoting functions focus on taking program data and making it safe " "for use as URL components by quoting special characters and appropriately " @@ -814,7 +1067,7 @@ msgid "" "isn't already covered by the URL parsing functions above." msgstr "" -#: ../../library/urllib.parse.rst:614 +#: ../../library/urllib.parse.rst:623 msgid "" "Replace special characters in *string* using the :samp:`%{xx}` escape. " "Letters, digits, and the characters ``'_.-~'`` are never quoted. By default, " @@ -823,18 +1076,18 @@ msgid "" "not be quoted --- its default value is ``'/'``." msgstr "" -#: ../../library/urllib.parse.rst:620 ../../library/urllib.parse.rst:666 -#: ../../library/urllib.parse.rst:695 +#: ../../library/urllib.parse.rst:629 ../../library/urllib.parse.rst:675 +#: ../../library/urllib.parse.rst:704 msgid "*string* may be either a :class:`str` or a :class:`bytes` object." msgstr "" -#: ../../library/urllib.parse.rst:622 +#: ../../library/urllib.parse.rst:631 msgid "" "Moved from :rfc:`2396` to :rfc:`3986` for quoting URL strings. \"~\" is now " "included in the set of unreserved characters." msgstr "" -#: ../../library/urllib.parse.rst:626 +#: ../../library/urllib.parse.rst:635 msgid "" "The optional *encoding* and *errors* parameters specify how to deal with non-" "ASCII characters, as accepted by the :meth:`str.encode` method. *encoding* " @@ -844,17 +1097,17 @@ msgid "" "`TypeError` is raised." msgstr "" -#: ../../library/urllib.parse.rst:634 +#: ../../library/urllib.parse.rst:643 msgid "" "Note that ``quote(string, safe, encoding, errors)`` is equivalent to " "``quote_from_bytes(string.encode(encoding, errors), safe)``." msgstr "" -#: ../../library/urllib.parse.rst:637 +#: ../../library/urllib.parse.rst:646 msgid "Example: ``quote('/El Niño/')`` yields ``'/El%20Ni%C3%B1o/'``." msgstr "" -#: ../../library/urllib.parse.rst:642 +#: ../../library/urllib.parse.rst:651 msgid "" "Like :func:`quote`, but also replace spaces with plus signs, as required for " "quoting HTML form values when building up a query string to go into a URL. " @@ -862,21 +1115,21 @@ msgid "" "*safe*. It also does not have *safe* default to ``'/'``." msgstr "" -#: ../../library/urllib.parse.rst:647 +#: ../../library/urllib.parse.rst:656 msgid "Example: ``quote_plus('/El Niño/')`` yields ``'%2FEl+Ni%C3%B1o%2F'``." msgstr "" -#: ../../library/urllib.parse.rst:652 +#: ../../library/urllib.parse.rst:661 msgid "" "Like :func:`quote`, but accepts a :class:`bytes` object rather than a :class:" "`str`, and does not perform string-to-bytes encoding." msgstr "" -#: ../../library/urllib.parse.rst:655 +#: ../../library/urllib.parse.rst:664 msgid "Example: ``quote_from_bytes(b'a&\\xef')`` yields ``'a%26%EF'``." msgstr "" -#: ../../library/urllib.parse.rst:661 +#: ../../library/urllib.parse.rst:670 msgid "" "Replace :samp:`%{xx}` escapes with their single-character equivalent. The " "optional *encoding* and *errors* parameters specify how to decode percent-" @@ -884,52 +1137,52 @@ msgid "" "decode` method." msgstr "" -#: ../../library/urllib.parse.rst:668 +#: ../../library/urllib.parse.rst:677 msgid "" "*encoding* defaults to ``'utf-8'``. *errors* defaults to ``'replace'``, " "meaning invalid sequences are replaced by a placeholder character." msgstr "" -#: ../../library/urllib.parse.rst:672 +#: ../../library/urllib.parse.rst:681 msgid "Example: ``unquote('/El%20Ni%C3%B1o/')`` yields ``'/El Niño/'``." msgstr "" -#: ../../library/urllib.parse.rst:674 +#: ../../library/urllib.parse.rst:683 msgid "" "*string* parameter supports bytes and str objects (previously only str)." msgstr "" -#: ../../library/urllib.parse.rst:682 +#: ../../library/urllib.parse.rst:691 msgid "" "Like :func:`unquote`, but also replace plus signs with spaces, as required " "for unquoting HTML form values." msgstr "" -#: ../../library/urllib.parse.rst:685 +#: ../../library/urllib.parse.rst:694 msgid "*string* must be a :class:`str`." msgstr "" -#: ../../library/urllib.parse.rst:687 +#: ../../library/urllib.parse.rst:696 msgid "Example: ``unquote_plus('/El+Ni%C3%B1o/')`` yields ``'/El Niño/'``." msgstr "" -#: ../../library/urllib.parse.rst:692 +#: ../../library/urllib.parse.rst:701 msgid "" "Replace :samp:`%{xx}` escapes with their single-octet equivalent, and return " "a :class:`bytes` object." msgstr "" -#: ../../library/urllib.parse.rst:697 +#: ../../library/urllib.parse.rst:706 msgid "" "If it is a :class:`str`, unescaped non-ASCII characters in *string* are " "encoded into UTF-8 bytes." msgstr "" -#: ../../library/urllib.parse.rst:700 +#: ../../library/urllib.parse.rst:709 msgid "Example: ``unquote_to_bytes('a%26%EF')`` yields ``b'a&\\xef'``." msgstr "" -#: ../../library/urllib.parse.rst:706 +#: ../../library/urllib.parse.rst:715 msgid "" "Convert a mapping object or a sequence of two-element tuples, which may " "contain :class:`str` or :class:`bytes` objects, to a percent-encoded ASCII " @@ -938,7 +1191,7 @@ msgid "" "be encoded to bytes, otherwise it would result in a :exc:`TypeError`." msgstr "" -#: ../../library/urllib.parse.rst:713 +#: ../../library/urllib.parse.rst:722 msgid "" "The resulting string is a series of ``key=value`` pairs separated by ``'&'`` " "characters, where both *key* and *value* are quoted using the *quote_via* " @@ -951,7 +1204,7 @@ msgid "" "``quote`` and specify a value for *safe*." msgstr "" -#: ../../library/urllib.parse.rst:723 +#: ../../library/urllib.parse.rst:732 msgid "" "When a sequence of two-element tuples is used as the *query* argument, the " "first element of each tuple is a key and the second is a value. The value " @@ -962,49 +1215,49 @@ msgid "" "order of parameter tuples in the sequence." msgstr "" -#: ../../library/urllib.parse.rst:731 +#: ../../library/urllib.parse.rst:740 msgid "" "The *safe*, *encoding*, and *errors* parameters are passed down to " "*quote_via* (the *encoding* and *errors* parameters are only passed when a " "query element is a :class:`str`)." msgstr "" -#: ../../library/urllib.parse.rst:735 +#: ../../library/urllib.parse.rst:744 msgid "" "To reverse this encoding process, :func:`parse_qs` and :func:`parse_qsl` are " "provided in this module to parse query strings into Python data structures." msgstr "" -#: ../../library/urllib.parse.rst:738 +#: ../../library/urllib.parse.rst:747 msgid "" "Refer to :ref:`urllib examples ` to find out how the :func:" "`urllib.parse.urlencode` method can be used for generating the query string " "of a URL or data for a POST request." msgstr "" -#: ../../library/urllib.parse.rst:742 +#: ../../library/urllib.parse.rst:751 msgid "*query* supports bytes and string objects." msgstr "" -#: ../../library/urllib.parse.rst:745 +#: ../../library/urllib.parse.rst:754 msgid "Added the *quote_via* parameter." msgstr "" -#: ../../library/urllib.parse.rst:751 +#: ../../library/urllib.parse.rst:760 msgid "`WHATWG`_ - URL Living standard" msgstr "" -#: ../../library/urllib.parse.rst:752 +#: ../../library/urllib.parse.rst:761 msgid "" "Working Group for the URL Standard that defines URLs, domains, IP addresses, " "the application/x-www-form-urlencoded format, and their API." msgstr "" -#: ../../library/urllib.parse.rst:755 +#: ../../library/urllib.parse.rst:764 msgid ":rfc:`3986` - Uniform Resource Identifiers" msgstr "" -#: ../../library/urllib.parse.rst:756 +#: ../../library/urllib.parse.rst:765 msgid "" "This is the current standard (STD66). Any changes to urllib.parse module " "should conform to this. Certain deviations could be observed, which are " @@ -1012,48 +1265,48 @@ msgid "" "requirements as commonly observed in major browsers." msgstr "" -#: ../../library/urllib.parse.rst:761 +#: ../../library/urllib.parse.rst:770 msgid ":rfc:`2732` - Format for Literal IPv6 Addresses in URL's." msgstr "" -#: ../../library/urllib.parse.rst:762 +#: ../../library/urllib.parse.rst:771 msgid "This specifies the parsing requirements of IPv6 URLs." msgstr "" -#: ../../library/urllib.parse.rst:764 +#: ../../library/urllib.parse.rst:773 msgid ":rfc:`2396` - Uniform Resource Identifiers (URI): Generic Syntax" msgstr "" -#: ../../library/urllib.parse.rst:765 +#: ../../library/urllib.parse.rst:774 msgid "" "Document describing the generic syntactic requirements for both Uniform " "Resource Names (URNs) and Uniform Resource Locators (URLs)." msgstr "" -#: ../../library/urllib.parse.rst:768 +#: ../../library/urllib.parse.rst:777 msgid ":rfc:`2368` - The mailto URL scheme." msgstr "" -#: ../../library/urllib.parse.rst:769 +#: ../../library/urllib.parse.rst:778 msgid "Parsing requirements for mailto URL schemes." msgstr "" -#: ../../library/urllib.parse.rst:771 +#: ../../library/urllib.parse.rst:780 msgid ":rfc:`1808` - Relative Uniform Resource Locators" msgstr "" -#: ../../library/urllib.parse.rst:772 +#: ../../library/urllib.parse.rst:781 msgid "" "This Request For Comments includes the rules for joining an absolute and a " "relative URL, including a fair number of \"Abnormal Examples\" which govern " "the treatment of border cases." msgstr "" -#: ../../library/urllib.parse.rst:776 +#: ../../library/urllib.parse.rst:785 msgid ":rfc:`1738` - Uniform Resource Locators (URL)" msgstr "" -#: ../../library/urllib.parse.rst:777 +#: ../../library/urllib.parse.rst:786 msgid "This specifies the formal syntax and semantics of absolute URLs." msgstr "" diff --git a/library/urllib.po b/library/urllib.po index f6f784846..f4c268c60 100644 --- a/library/urllib.po +++ b/library/urllib.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:17+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/urllib.request.po b/library/urllib.request.po index 856687c6a..260db65d1 100644 --- a/library/urllib.request.po +++ b/library/urllib.request.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Sheila Gomes , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:17+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-16 14:58+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -63,8 +58,8 @@ msgid "" msgstr "" #: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +msgid "Availability" +msgstr "Disponibilidade" #: ../../includes/wasm-notavail.rst:5 msgid "" @@ -280,21 +275,38 @@ msgstr "" #: ../../library/urllib.request.rst:152 msgid "" -"Convert the pathname *path* from the local syntax for a path to the form " -"used in the path component of a URL. This does not produce a complete URL. " -"The return value will already be quoted using the :func:`~urllib.parse." -"quote` function." +"Convert the given local path to a ``file:`` URL. This function uses :func:" +"`~urllib.parse.quote` function to encode the path. For historical reasons, " +"the return value omits the ``file:`` scheme prefix. This example shows the " +"function being used on Windows::" msgstr "" -#: ../../library/urllib.request.rst:159 +#: ../../library/urllib.request.rst:157 msgid "" -"Convert the path component *path* from a percent-encoded URL to the local " -"syntax for a path. This does not accept a complete URL. This function " -"uses :func:`~urllib.parse.unquote` to decode *path*." +">>> from urllib.request import pathname2url\n" +">>> path = 'C:\\\\Program Files'\n" +">>> 'file:' + pathname2url(path)\n" +"'file:///C:/Program%20Files'" msgstr "" #: ../../library/urllib.request.rst:165 msgid "" +"Convert the given ``file:`` URL to a local path. This function uses :func:" +"`~urllib.parse.unquote` to decode the URL. For historical reasons, the given " +"value *must* omit the ``file:`` scheme prefix. This example shows the " +"function being used on Windows::" +msgstr "" + +#: ../../library/urllib.request.rst:170 +msgid "" +">>> from urllib.request import url2pathname\n" +">>> url = 'file:///C:/Program%20Files'\n" +">>> url2pathname(url.removeprefix('file:'))\n" +"'C:\\\\Program Files'" +msgstr "" + +#: ../../library/urllib.request.rst:177 +msgid "" "This helper function returns a dictionary of scheme to proxy server URL " "mappings. It scans the environment for variables named ``_proxy``, " "in a case insensitive approach, for all operating systems first, and when it " @@ -303,7 +315,7 @@ msgid "" "uppercase environment variables exist (and disagree), lowercase is preferred." msgstr "" -#: ../../library/urllib.request.rst:175 +#: ../../library/urllib.request.rst:187 msgid "" "If the environment variable ``REQUEST_METHOD`` is set, which usually " "indicates your script is running in a CGI environment, the environment " @@ -314,19 +326,19 @@ msgid "" "(or at least the ``_proxy`` suffix)." msgstr "" -#: ../../library/urllib.request.rst:184 +#: ../../library/urllib.request.rst:196 msgid "The following classes are provided:" -msgstr "" +msgstr "As sequintes classes são disponibilizadas:" -#: ../../library/urllib.request.rst:188 +#: ../../library/urllib.request.rst:200 msgid "This class is an abstraction of a URL request." msgstr "" -#: ../../library/urllib.request.rst:190 +#: ../../library/urllib.request.rst:202 msgid "*url* should be a string containing a valid, properly encoded URL." msgstr "" -#: ../../library/urllib.request.rst:192 +#: ../../library/urllib.request.rst:204 msgid "" "*data* must be an object specifying additional data to send to the server, " "or ``None`` if no such data is needed. Currently HTTP requests are the only " @@ -339,7 +351,7 @@ msgid "" "iterables." msgstr "" -#: ../../library/urllib.request.rst:202 +#: ../../library/urllib.request.rst:214 msgid "" "For an HTTP POST request method, *data* should be a buffer in the standard :" "mimetype:`application/x-www-form-urlencoded` format. The :func:`urllib." @@ -348,7 +360,7 @@ msgid "" "being used as the *data* parameter." msgstr "" -#: ../../library/urllib.request.rst:208 +#: ../../library/urllib.request.rst:220 msgid "" "*headers* should be a dictionary, and will be treated as if :meth:" "`add_header` was called with each key and value as arguments. This is often " @@ -361,7 +373,7 @@ msgid "" "case." msgstr "" -#: ../../library/urllib.request.rst:219 +#: ../../library/urllib.request.rst:231 msgid "" "An appropriate ``Content-Type`` header should be included if the *data* " "argument is present. If this header has not been provided and *data* is not " @@ -369,13 +381,13 @@ msgid "" "as a default." msgstr "" -#: ../../library/urllib.request.rst:224 +#: ../../library/urllib.request.rst:236 msgid "" "The next two arguments are only of interest for correct handling of third-" "party HTTP cookies:" msgstr "" -#: ../../library/urllib.request.rst:227 +#: ../../library/urllib.request.rst:239 msgid "" "*origin_req_host* should be the request-host of the origin transaction, as " "defined by :rfc:`2965`. It defaults to ``http.cookiejar." @@ -385,7 +397,7 @@ msgid "" "for the page containing the image." msgstr "" -#: ../../library/urllib.request.rst:235 +#: ../../library/urllib.request.rst:247 msgid "" "*unverifiable* should indicate whether the request is unverifiable, as " "defined by :rfc:`2965`. It defaults to ``False``. An unverifiable request " @@ -394,17 +406,17 @@ msgid "" "option to approve the automatic fetching of the image, this should be true." msgstr "" -#: ../../library/urllib.request.rst:242 +#: ../../library/urllib.request.rst:254 msgid "" "*method* should be a string that indicates the HTTP request method that will " "be used (e.g. ``'HEAD'``). If provided, its value is stored in the :attr:" -"`~Request.method` attribute and is used by :meth:`get_method()`. The default " +"`~Request.method` attribute and is used by :meth:`get_method`. The default " "is ``'GET'`` if *data* is ``None`` or ``'POST'`` otherwise. Subclasses may " "indicate a different default method by setting the :attr:`~Request.method` " "attribute in the class itself." msgstr "" -#: ../../library/urllib.request.rst:250 +#: ../../library/urllib.request.rst:262 msgid "" "The request will not work as expected if the data object is unable to " "deliver its content more than once (e.g. a file or an iterable that can " @@ -414,49 +426,49 @@ msgid "" "library." msgstr "" -#: ../../library/urllib.request.rst:257 +#: ../../library/urllib.request.rst:269 msgid ":attr:`Request.method` argument is added to the Request class." msgstr "" -#: ../../library/urllib.request.rst:260 +#: ../../library/urllib.request.rst:272 msgid "Default :attr:`Request.method` may be indicated at the class level." msgstr "" -#: ../../library/urllib.request.rst:263 +#: ../../library/urllib.request.rst:275 msgid "" "Do not raise an error if the ``Content-Length`` has not been provided and " "*data* is neither ``None`` nor a bytes object. Fall back to use chunked " "transfer encoding instead." msgstr "" -#: ../../library/urllib.request.rst:270 +#: ../../library/urllib.request.rst:282 msgid "" "The :class:`OpenerDirector` class opens URLs via :class:`BaseHandler`\\ s " "chained together. It manages the chaining of handlers, and recovery from " "errors." msgstr "" -#: ../../library/urllib.request.rst:276 +#: ../../library/urllib.request.rst:288 msgid "" "This is the base class for all registered handlers --- and handles only the " "simple mechanics of registration." msgstr "" -#: ../../library/urllib.request.rst:282 +#: ../../library/urllib.request.rst:294 msgid "" "A class which defines a default handler for HTTP error responses; all " "responses are turned into :exc:`~urllib.error.HTTPError` exceptions." msgstr "" -#: ../../library/urllib.request.rst:288 +#: ../../library/urllib.request.rst:300 msgid "A class to handle redirections." -msgstr "" +msgstr "Uma classe para lidar com redirecionamentos." -#: ../../library/urllib.request.rst:293 +#: ../../library/urllib.request.rst:305 msgid "A class to handle HTTP Cookies." -msgstr "" +msgstr "Classe para lidar com Cookies HTTP." -#: ../../library/urllib.request.rst:298 +#: ../../library/urllib.request.rst:310 msgid "" "Cause requests to go through a proxy. If *proxies* is given, it must be a " "dictionary mapping protocol names to URLs of proxies. The default is to read " @@ -467,11 +479,11 @@ msgid "" "Configuration Framework." msgstr "" -#: ../../library/urllib.request.rst:306 +#: ../../library/urllib.request.rst:318 msgid "To disable autodetected proxy pass an empty dictionary." msgstr "" -#: ../../library/urllib.request.rst:308 +#: ../../library/urllib.request.rst:320 msgid "" "The :envvar:`no_proxy` environment variable can be used to specify hosts " "which shouldn't be reached via proxy; if set, it should be a comma-separated " @@ -479,24 +491,24 @@ msgid "" "``cern.ch,ncsa.uiuc.edu,some.host:8080``." msgstr "" -#: ../../library/urllib.request.rst:315 +#: ../../library/urllib.request.rst:327 msgid "" "``HTTP_PROXY`` will be ignored if a variable ``REQUEST_METHOD`` is set; see " "the documentation on :func:`~urllib.request.getproxies`." msgstr "" -#: ../../library/urllib.request.rst:321 +#: ../../library/urllib.request.rst:333 msgid "Keep a database of ``(realm, uri) -> (user, password)`` mappings." msgstr "" -#: ../../library/urllib.request.rst:326 +#: ../../library/urllib.request.rst:338 msgid "" "Keep a database of ``(realm, uri) -> (user, password)`` mappings. A realm " "of ``None`` is considered a catch-all realm, which is searched if no other " "realm fits." msgstr "" -#: ../../library/urllib.request.rst:333 +#: ../../library/urllib.request.rst:345 msgid "" "A variant of :class:`HTTPPasswordMgrWithDefaultRealm` that also has a " "database of ``uri -> is_authenticated`` mappings. Can be used by a " @@ -504,7 +516,7 @@ msgid "" "immediately instead of waiting for a ``401`` response first." msgstr "" -#: ../../library/urllib.request.rst:343 +#: ../../library/urllib.request.rst:355 msgid "" "This is a mixin class that helps with HTTP authentication, both to the " "remote host and to a proxy. *password_mgr*, if given, should be something " @@ -523,11 +535,11 @@ msgid "" "will automatically include the authentication credentials." msgstr "" -#: ../../library/urllib.request.rst:360 +#: ../../library/urllib.request.rst:372 msgid "Added ``is_authenticated`` support." msgstr "" -#: ../../library/urllib.request.rst:366 +#: ../../library/urllib.request.rst:378 msgid "" "Handle authentication with the remote host. *password_mgr*, if given, should " "be something that is compatible with :class:`HTTPPasswordMgr`; refer to " @@ -536,7 +548,7 @@ msgid "" "presented with a wrong Authentication scheme." msgstr "" -#: ../../library/urllib.request.rst:375 ../../library/urllib.request.rst:409 +#: ../../library/urllib.request.rst:387 ../../library/urllib.request.rst:421 msgid "" "Handle authentication with the proxy. *password_mgr*, if given, should be " "something that is compatible with :class:`HTTPPasswordMgr`; refer to " @@ -544,7 +556,7 @@ msgid "" "be supported." msgstr "" -#: ../../library/urllib.request.rst:383 +#: ../../library/urllib.request.rst:395 msgid "" "This is a mixin class that helps with HTTP authentication, both to the " "remote host and to a proxy. *password_mgr*, if given, should be something " @@ -552,7 +564,7 @@ msgid "" "`http-password-mgr` for information on the interface that must be supported." msgstr "" -#: ../../library/urllib.request.rst:392 +#: ../../library/urllib.request.rst:404 msgid "" "Handle authentication with the remote host. *password_mgr*, if given, should " "be something that is compatible with :class:`HTTPPasswordMgr`; refer to " @@ -565,108 +577,108 @@ msgid "" "Digest or Basic." msgstr "" -#: ../../library/urllib.request.rst:402 +#: ../../library/urllib.request.rst:414 msgid "Raise :exc:`ValueError` on unsupported Authentication Scheme." msgstr "" -#: ../../library/urllib.request.rst:417 +#: ../../library/urllib.request.rst:429 msgid "A class to handle opening of HTTP URLs." msgstr "" -#: ../../library/urllib.request.rst:422 +#: ../../library/urllib.request.rst:434 msgid "" "A class to handle opening of HTTPS URLs. *context* and *check_hostname* " "have the same meaning as in :class:`http.client.HTTPSConnection`." msgstr "" -#: ../../library/urllib.request.rst:425 +#: ../../library/urllib.request.rst:437 msgid "*context* and *check_hostname* were added." msgstr "" -#: ../../library/urllib.request.rst:431 +#: ../../library/urllib.request.rst:443 msgid "Open local files." msgstr "Abre arquivos locais." -#: ../../library/urllib.request.rst:435 +#: ../../library/urllib.request.rst:447 msgid "Open data URLs." msgstr "Abre dados das URLs." -#: ../../library/urllib.request.rst:441 +#: ../../library/urllib.request.rst:453 msgid "Open FTP URLs." msgstr "Abre URLs de FTP." -#: ../../library/urllib.request.rst:446 +#: ../../library/urllib.request.rst:458 msgid "" "Open FTP URLs, keeping a cache of open FTP connections to minimize delays." msgstr "" -#: ../../library/urllib.request.rst:451 +#: ../../library/urllib.request.rst:463 msgid "A catch-all class to handle unknown URLs." msgstr "" -#: ../../library/urllib.request.rst:456 ../../library/urllib.request.rst:1162 +#: ../../library/urllib.request.rst:468 ../../library/urllib.request.rst:1174 msgid "Process HTTP error responses." msgstr "" -#: ../../library/urllib.request.rst:462 +#: ../../library/urllib.request.rst:474 msgid "Request Objects" msgstr "Objeto Request" -#: ../../library/urllib.request.rst:464 +#: ../../library/urllib.request.rst:476 msgid "" "The following methods describe :class:`Request`'s public interface, and so " "all may be overridden in subclasses. It also defines several public " "attributes that can be used by clients to inspect the parsed request." msgstr "" -#: ../../library/urllib.request.rst:471 +#: ../../library/urllib.request.rst:483 msgid "The original URL passed to the constructor." msgstr "" -#: ../../library/urllib.request.rst:475 +#: ../../library/urllib.request.rst:487 msgid "" "Request.full_url is a property with setter, getter and a deleter. Getting :" "attr:`~Request.full_url` returns the original request URL with the fragment, " "if it was present." msgstr "" -#: ../../library/urllib.request.rst:481 +#: ../../library/urllib.request.rst:493 msgid "The URI scheme." msgstr "" -#: ../../library/urllib.request.rst:485 +#: ../../library/urllib.request.rst:497 msgid "" "The URI authority, typically a host, but may also contain a port separated " "by a colon." msgstr "" -#: ../../library/urllib.request.rst:490 +#: ../../library/urllib.request.rst:502 msgid "The original host for the request, without port." msgstr "" -#: ../../library/urllib.request.rst:494 +#: ../../library/urllib.request.rst:506 msgid "" "The URI path. If the :class:`Request` uses a proxy, then selector will be " "the full URL that is passed to the proxy." msgstr "" -#: ../../library/urllib.request.rst:499 +#: ../../library/urllib.request.rst:511 msgid "The entity body for the request, or ``None`` if not specified." msgstr "" -#: ../../library/urllib.request.rst:501 +#: ../../library/urllib.request.rst:513 msgid "" "Changing value of :attr:`Request.data` now deletes \"Content-Length\" header " "if it was previously set or calculated." msgstr "" -#: ../../library/urllib.request.rst:507 +#: ../../library/urllib.request.rst:519 msgid "" "boolean, indicates whether the request is unverifiable as defined by :rfc:" "`2965`." msgstr "" -#: ../../library/urllib.request.rst:512 +#: ../../library/urllib.request.rst:524 msgid "" "The HTTP request method to use. By default its value is :const:`None`, " "which means that :meth:`~Request.get_method` will do its normal computation " @@ -677,13 +689,13 @@ msgid "" "argument." msgstr "" -#: ../../library/urllib.request.rst:522 +#: ../../library/urllib.request.rst:534 msgid "" "A default value can now be set in subclasses; previously it could only be " "set via the constructor argument." msgstr "" -#: ../../library/urllib.request.rst:529 +#: ../../library/urllib.request.rst:541 msgid "" "Return a string indicating the HTTP request method. If :attr:`Request." "method` is not ``None``, return its value, otherwise return ``'GET'`` if :" @@ -691,11 +703,11 @@ msgid "" "meaningful for HTTP requests." msgstr "" -#: ../../library/urllib.request.rst:534 +#: ../../library/urllib.request.rst:546 msgid "get_method now looks at the value of :attr:`Request.method`." msgstr "" -#: ../../library/urllib.request.rst:540 +#: ../../library/urllib.request.rst:552 msgid "" "Add another header to the request. Headers are currently ignored by all " "handlers except HTTP handlers, where they are added to the list of headers " @@ -707,17 +719,17 @@ msgid "" "headers added using this method are also added to redirected requests." msgstr "" -#: ../../library/urllib.request.rst:552 +#: ../../library/urllib.request.rst:564 msgid "Add a header that will not be added to a redirected request." msgstr "" -#: ../../library/urllib.request.rst:557 +#: ../../library/urllib.request.rst:569 msgid "" "Return whether the instance has the named header (checks both regular and " "unredirected)." msgstr "" -#: ../../library/urllib.request.rst:563 +#: ../../library/urllib.request.rst:575 msgid "" "Remove named header from the request instance (both from regular and " "unredirected headers)." @@ -725,48 +737,48 @@ msgstr "" "Remove o cabeçalho nomeado da instância de solicitação (tanto de cabeçalhos " "regulares como de cabeçalhos não-redirecionados)." -#: ../../library/urllib.request.rst:571 +#: ../../library/urllib.request.rst:583 msgid "Return the URL given in the constructor." msgstr "" -#: ../../library/urllib.request.rst:575 +#: ../../library/urllib.request.rst:587 msgid "Returns :attr:`Request.full_url`" msgstr "" -#: ../../library/urllib.request.rst:580 +#: ../../library/urllib.request.rst:592 msgid "" "Prepare the request by connecting to a proxy server. The *host* and *type* " "will replace those of the instance, and the instance's selector will be the " "original URL given in the constructor." msgstr "" -#: ../../library/urllib.request.rst:587 +#: ../../library/urllib.request.rst:599 msgid "" "Return the value of the given header. If the header is not present, return " "the default value." msgstr "" -#: ../../library/urllib.request.rst:593 +#: ../../library/urllib.request.rst:605 msgid "" "Return a list of tuples (header_name, header_value) of the Request headers." msgstr "" -#: ../../library/urllib.request.rst:595 +#: ../../library/urllib.request.rst:607 msgid "" "The request methods add_data, has_data, get_data, get_type, get_host, " "get_selector, get_origin_req_host and is_unverifiable that were deprecated " "since 3.3 have been removed." msgstr "" -#: ../../library/urllib.request.rst:604 +#: ../../library/urllib.request.rst:616 msgid "OpenerDirector Objects" msgstr "" -#: ../../library/urllib.request.rst:606 +#: ../../library/urllib.request.rst:618 msgid ":class:`OpenerDirector` instances have the following methods:" msgstr "" -#: ../../library/urllib.request.rst:611 +#: ../../library/urllib.request.rst:623 msgid "" "*handler* should be an instance of :class:`BaseHandler`. The following " "methods are searched, and added to the possible chains (note that HTTP " @@ -777,53 +789,53 @@ msgid "" "`http_error_404` would handle HTTP 404 errors." msgstr "" -#: ../../library/urllib.request.rst:619 +#: ../../library/urllib.request.rst:631 msgid "" ":meth:`!_open` --- signal that the handler knows how to open " "*protocol* URLs." msgstr "" -#: ../../library/urllib.request.rst:622 +#: ../../library/urllib.request.rst:634 msgid "See |protocol_open|_ for more information." msgstr "Veja |protocol_open|_ para maiores informações." -#: ../../library/urllib.request.rst:624 +#: ../../library/urllib.request.rst:636 msgid "" ":meth:`!http_error_\\` --- signal that the handler knows how to " "handle HTTP errors with HTTP error code *type*." msgstr "" -#: ../../library/urllib.request.rst:627 +#: ../../library/urllib.request.rst:639 msgid "See |http_error_nnn|_ for more information." msgstr "Veja |http_error_nnn|_ para maiores informações." -#: ../../library/urllib.request.rst:629 +#: ../../library/urllib.request.rst:641 msgid "" ":meth:`!_error` --- signal that the handler knows how to handle " "errors from (non-\\ ``http``) *protocol*." msgstr "" -#: ../../library/urllib.request.rst:632 +#: ../../library/urllib.request.rst:644 msgid "" ":meth:`!_request` --- signal that the handler knows how to pre-" "process *protocol* requests." msgstr "" -#: ../../library/urllib.request.rst:635 +#: ../../library/urllib.request.rst:647 msgid "See |protocol_request|_ for more information." msgstr "Veja |protocol_request|_ para maiores informações." -#: ../../library/urllib.request.rst:637 +#: ../../library/urllib.request.rst:649 msgid "" ":meth:`!_response` --- signal that the handler knows how to post-" "process *protocol* responses." msgstr "" -#: ../../library/urllib.request.rst:640 +#: ../../library/urllib.request.rst:652 msgid "See |protocol_response|_ for more information." msgstr "Veja |protocol_response|_ para maiores informações." -#: ../../library/urllib.request.rst:649 +#: ../../library/urllib.request.rst:661 msgid "" "Open the given *url* (which can be a request object or a string), optionally " "passing the given *data*. Arguments, return values and exceptions raised are " @@ -835,7 +847,7 @@ msgid "" "HTTP, HTTPS and FTP connections." msgstr "" -#: ../../library/urllib.request.rst:661 +#: ../../library/urllib.request.rst:673 msgid "" "Handle an error of the given protocol. This will call the registered error " "handlers for the given protocol with the given arguments (which are protocol " @@ -844,28 +856,28 @@ msgid "" "http_error_\\` methods of the handler classes." msgstr "" -#: ../../library/urllib.request.rst:667 +#: ../../library/urllib.request.rst:679 msgid "" "Return values and exceptions raised are the same as those of :func:`urlopen`." msgstr "" -#: ../../library/urllib.request.rst:669 +#: ../../library/urllib.request.rst:681 msgid "OpenerDirector objects open URLs in three stages:" msgstr "" -#: ../../library/urllib.request.rst:671 +#: ../../library/urllib.request.rst:683 msgid "" "The order in which these methods are called within each stage is determined " "by sorting the handler instances." msgstr "" -#: ../../library/urllib.request.rst:674 +#: ../../library/urllib.request.rst:686 msgid "" "Every handler with a method named like :meth:`!_request` has that " "method called to pre-process the request." msgstr "" -#: ../../library/urllib.request.rst:677 +#: ../../library/urllib.request.rst:689 msgid "" "Handlers with a method named like :meth:`!_open` are called to " "handle the request. This stage ends when a handler either returns a non-\\ :" @@ -873,7 +885,7 @@ msgid "" "`~urllib.error.URLError`). Exceptions are allowed to propagate." msgstr "" -#: ../../library/urllib.request.rst:682 +#: ../../library/urllib.request.rst:694 msgid "" "In fact, the above algorithm is first tried for methods named :meth:" "`~BaseHandler.default_open`. If all such methods return :const:`None`, the " @@ -882,64 +894,64 @@ msgid "" "named :meth:`~BaseHandler.unknown_open`." msgstr "" -#: ../../library/urllib.request.rst:688 +#: ../../library/urllib.request.rst:700 msgid "" "Note that the implementation of these methods may involve calls of the " "parent :class:`OpenerDirector` instance's :meth:`~OpenerDirector.open` and :" "meth:`~OpenerDirector.error` methods." msgstr "" -#: ../../library/urllib.request.rst:692 +#: ../../library/urllib.request.rst:704 msgid "" "Every handler with a method named like :meth:`!_response` has that " "method called to post-process the response." msgstr "" -#: ../../library/urllib.request.rst:699 +#: ../../library/urllib.request.rst:711 msgid "BaseHandler Objects" msgstr "" -#: ../../library/urllib.request.rst:701 +#: ../../library/urllib.request.rst:713 msgid "" ":class:`BaseHandler` objects provide a couple of methods that are directly " "useful, and others that are meant to be used by derived classes. These are " "intended for direct use:" msgstr "" -#: ../../library/urllib.request.rst:708 +#: ../../library/urllib.request.rst:720 msgid "Add a director as parent." msgstr "" -#: ../../library/urllib.request.rst:713 +#: ../../library/urllib.request.rst:725 msgid "Remove any parents." msgstr "" -#: ../../library/urllib.request.rst:715 +#: ../../library/urllib.request.rst:727 msgid "" "The following attribute and methods should only be used by classes derived " "from :class:`BaseHandler`." msgstr "" -#: ../../library/urllib.request.rst:720 +#: ../../library/urllib.request.rst:732 msgid "" "The convention has been adopted that subclasses defining :meth:`!" "_request` or :meth:`!_response` methods are named :class:" "`!\\*Processor`; all others are named :class:`!\\*Handler`." msgstr "" -#: ../../library/urllib.request.rst:727 +#: ../../library/urllib.request.rst:739 msgid "" "A valid :class:`OpenerDirector`, which can be used to open using a different " "protocol, or handle errors." msgstr "" -#: ../../library/urllib.request.rst:733 +#: ../../library/urllib.request.rst:745 msgid "" "This method is *not* defined in :class:`BaseHandler`, but subclasses should " "define it if they want to catch all URLs." msgstr "" -#: ../../library/urllib.request.rst:736 +#: ../../library/urllib.request.rst:748 msgid "" "This method, if implemented, will be called by the parent :class:" "`OpenerDirector`. It should return a file-like object as described in the " @@ -949,38 +961,38 @@ msgid "" "`MemoryError` should not be mapped to :exc:`~urllib.error.URLError`)." msgstr "" -#: ../../library/urllib.request.rst:743 +#: ../../library/urllib.request.rst:755 msgid "This method will be called before any protocol-specific open method." msgstr "" -#: ../../library/urllib.request.rst:750 +#: ../../library/urllib.request.rst:762 msgid "" "This method is *not* defined in :class:`BaseHandler`, but subclasses should " "define it if they want to handle URLs with the given protocol." msgstr "" -#: ../../library/urllib.request.rst:753 +#: ../../library/urllib.request.rst:765 msgid "" "This method, if defined, will be called by the parent :class:" "`OpenerDirector`. Return values should be the same as for :meth:" "`~BaseHandler.default_open`." msgstr "" -#: ../../library/urllib.request.rst:759 +#: ../../library/urllib.request.rst:771 msgid "" "This method is *not* defined in :class:`BaseHandler`, but subclasses should " "define it if they want to catch all URLs with no specific registered handler " "to open it." msgstr "" -#: ../../library/urllib.request.rst:763 +#: ../../library/urllib.request.rst:775 msgid "" "This method, if implemented, will be called by the :attr:`parent` :class:" "`OpenerDirector`. Return values should be the same as for :meth:" "`default_open`." msgstr "" -#: ../../library/urllib.request.rst:770 +#: ../../library/urllib.request.rst:782 msgid "" "This method is *not* defined in :class:`BaseHandler`, but subclasses should " "override it if they intend to provide a catch-all for otherwise unhandled " @@ -989,7 +1001,7 @@ msgid "" "other circumstances." msgstr "" -#: ../../library/urllib.request.rst:775 +#: ../../library/urllib.request.rst:787 msgid "" "*req* will be a :class:`Request` object, *fp* will be a file-like object " "with the HTTP error body, *code* will be the three-digit code of the error, " @@ -997,49 +1009,49 @@ msgid "" "mapping object with the headers of the error." msgstr "" -#: ../../library/urllib.request.rst:780 +#: ../../library/urllib.request.rst:792 msgid "" "Return values and exceptions raised should be the same as those of :func:" "`urlopen`." msgstr "" -#: ../../library/urllib.request.rst:787 +#: ../../library/urllib.request.rst:799 msgid "" "*nnn* should be a three-digit HTTP error code. This method is also not " "defined in :class:`BaseHandler`, but will be called, if it exists, on an " "instance of a subclass, when an HTTP error with code *nnn* occurs." msgstr "" -#: ../../library/urllib.request.rst:791 +#: ../../library/urllib.request.rst:803 msgid "Subclasses should override this method to handle specific HTTP errors." msgstr "" -#: ../../library/urllib.request.rst:793 +#: ../../library/urllib.request.rst:805 msgid "" "Arguments, return values and exceptions raised should be the same as for :" "meth:`~BaseHandler.http_error_default`." msgstr "" -#: ../../library/urllib.request.rst:801 +#: ../../library/urllib.request.rst:813 msgid "" "This method is *not* defined in :class:`BaseHandler`, but subclasses should " "define it if they want to pre-process requests of the given protocol." msgstr "" -#: ../../library/urllib.request.rst:804 +#: ../../library/urllib.request.rst:816 msgid "" "This method, if defined, will be called by the parent :class:" "`OpenerDirector`. *req* will be a :class:`Request` object. The return value " "should be a :class:`Request` object." msgstr "" -#: ../../library/urllib.request.rst:813 +#: ../../library/urllib.request.rst:825 msgid "" "This method is *not* defined in :class:`BaseHandler`, but subclasses should " "define it if they want to post-process responses of the given protocol." msgstr "" -#: ../../library/urllib.request.rst:816 +#: ../../library/urllib.request.rst:828 msgid "" "This method, if defined, will be called by the parent :class:" "`OpenerDirector`. *req* will be a :class:`Request` object. *response* will " @@ -1048,25 +1060,25 @@ msgid "" "return value of :func:`urlopen`." msgstr "" -#: ../../library/urllib.request.rst:826 +#: ../../library/urllib.request.rst:838 msgid "HTTPRedirectHandler Objects" msgstr "" -#: ../../library/urllib.request.rst:830 +#: ../../library/urllib.request.rst:842 msgid "" "Some HTTP redirections require action from this module's client code. If " "this is the case, :exc:`~urllib.error.HTTPError` is raised. See :rfc:`2616` " "for details of the precise meanings of the various redirection codes." msgstr "" -#: ../../library/urllib.request.rst:834 +#: ../../library/urllib.request.rst:846 msgid "" "An :exc:`~urllib.error.HTTPError` exception raised as a security " "consideration if the HTTPRedirectHandler is presented with a redirected URL " "which is not an HTTP, HTTPS or FTP URL." msgstr "" -#: ../../library/urllib.request.rst:841 +#: ../../library/urllib.request.rst:853 msgid "" "Return a :class:`Request` or ``None`` in response to a redirect. This is " "called by the default implementations of the :meth:`!http_error_30\\*` " @@ -1077,7 +1089,7 @@ msgid "" "URL, or return ``None`` if you can't but another handler might." msgstr "" -#: ../../library/urllib.request.rst:851 +#: ../../library/urllib.request.rst:863 msgid "" "The default implementation of this method does not strictly follow :rfc:" "`2616`, which says that 301 and 302 responses to ``POST`` requests must not " @@ -1086,54 +1098,54 @@ msgid "" "POST to a ``GET``, and the default implementation reproduces this behavior." msgstr "" -#: ../../library/urllib.request.rst:860 +#: ../../library/urllib.request.rst:872 msgid "" "Redirect to the ``Location:`` or ``URI:`` URL. This method is called by the " "parent :class:`OpenerDirector` when getting an HTTP 'moved permanently' " "response." msgstr "" -#: ../../library/urllib.request.rst:866 +#: ../../library/urllib.request.rst:878 msgid "" "The same as :meth:`http_error_301`, but called for the 'found' response." msgstr "" -#: ../../library/urllib.request.rst:871 +#: ../../library/urllib.request.rst:883 msgid "" "The same as :meth:`http_error_301`, but called for the 'see other' response." msgstr "" -#: ../../library/urllib.request.rst:876 +#: ../../library/urllib.request.rst:888 msgid "" "The same as :meth:`http_error_301`, but called for the 'temporary redirect' " "response. It does not allow changing the request method from ``POST`` to " "``GET``." msgstr "" -#: ../../library/urllib.request.rst:883 +#: ../../library/urllib.request.rst:895 msgid "" "The same as :meth:`http_error_301`, but called for the 'permanent redirect' " "response. It does not allow changing the request method from ``POST`` to " "``GET``." msgstr "" -#: ../../library/urllib.request.rst:893 +#: ../../library/urllib.request.rst:905 msgid "HTTPCookieProcessor Objects" msgstr "" -#: ../../library/urllib.request.rst:895 +#: ../../library/urllib.request.rst:907 msgid ":class:`HTTPCookieProcessor` instances have one attribute:" msgstr "" -#: ../../library/urllib.request.rst:899 +#: ../../library/urllib.request.rst:911 msgid "The :class:`http.cookiejar.CookieJar` in which cookies are stored." msgstr "" -#: ../../library/urllib.request.rst:905 +#: ../../library/urllib.request.rst:917 msgid "ProxyHandler Objects" msgstr "" -#: ../../library/urllib.request.rst:911 +#: ../../library/urllib.request.rst:923 msgid "" "The :class:`ProxyHandler` will have a method :meth:`!_open` for " "every *protocol* which has a proxy in the *proxies* dictionary given in the " @@ -1142,17 +1154,17 @@ msgid "" "actually execute the protocol." msgstr "" -#: ../../library/urllib.request.rst:921 +#: ../../library/urllib.request.rst:933 msgid "HTTPPasswordMgr Objects" msgstr "" -#: ../../library/urllib.request.rst:923 +#: ../../library/urllib.request.rst:935 msgid "" "These methods are available on :class:`HTTPPasswordMgr` and :class:" "`HTTPPasswordMgrWithDefaultRealm` objects." msgstr "" -#: ../../library/urllib.request.rst:929 +#: ../../library/urllib.request.rst:941 msgid "" "*uri* can be either a single URI, or a sequence of URIs. *realm*, *user* and " "*passwd* must be strings. This causes ``(user, passwd)`` to be used as " @@ -1160,30 +1172,30 @@ msgid "" "of the given URIs is given." msgstr "" -#: ../../library/urllib.request.rst:937 +#: ../../library/urllib.request.rst:949 msgid "" "Get user/password for given realm and URI, if any. This method will return " "``(None, None)`` if there is no matching user/password." msgstr "" -#: ../../library/urllib.request.rst:940 +#: ../../library/urllib.request.rst:952 msgid "" "For :class:`HTTPPasswordMgrWithDefaultRealm` objects, the realm ``None`` " "will be searched if the given *realm* has no matching user/password." msgstr "" -#: ../../library/urllib.request.rst:947 +#: ../../library/urllib.request.rst:959 msgid "HTTPPasswordMgrWithPriorAuth Objects" msgstr "" -#: ../../library/urllib.request.rst:949 +#: ../../library/urllib.request.rst:961 msgid "" "This password manager extends :class:`HTTPPasswordMgrWithDefaultRealm` to " "support tracking URIs for which authentication credentials should always be " "sent." msgstr "" -#: ../../library/urllib.request.rst:956 +#: ../../library/urllib.request.rst:968 msgid "" "*realm*, *uri*, *user*, *passwd* are as for :meth:`HTTPPasswordMgr." "add_password`. *is_authenticated* sets the initial value of the " @@ -1191,25 +1203,25 @@ msgid "" "*is_authenticated* is specified as ``True``, *realm* is ignored." msgstr "" -#: ../../library/urllib.request.rst:964 +#: ../../library/urllib.request.rst:976 msgid "Same as for :class:`HTTPPasswordMgrWithDefaultRealm` objects" msgstr "" -#: ../../library/urllib.request.rst:970 +#: ../../library/urllib.request.rst:982 msgid "" "Update the ``is_authenticated`` flag for the given *uri* or list of URIs." msgstr "" -#: ../../library/urllib.request.rst:976 +#: ../../library/urllib.request.rst:988 msgid "" "Returns the current state of the ``is_authenticated`` flag for the given URI." msgstr "" -#: ../../library/urllib.request.rst:983 +#: ../../library/urllib.request.rst:995 msgid "AbstractBasicAuthHandler Objects" msgstr "" -#: ../../library/urllib.request.rst:988 +#: ../../library/urllib.request.rst:1000 msgid "" "Handle an authentication request by getting a user/password pair, and re-" "trying the request. *authreq* should be the name of the header where the " @@ -1218,7 +1230,7 @@ msgid "" "`Request` object, and *headers* should be the error headers." msgstr "" -#: ../../library/urllib.request.rst:994 +#: ../../library/urllib.request.rst:1006 msgid "" "*host* is either an authority (e.g. ``\"python.org\"``) or a URL containing " "an authority component (e.g. ``\"http://python.org/\"``). In either case, " @@ -1226,24 +1238,24 @@ msgid "" "and ``\"python.org:80\"`` are fine, ``\"joe:password@python.org\"`` is not)." msgstr "" -#: ../../library/urllib.request.rst:1003 +#: ../../library/urllib.request.rst:1015 msgid "HTTPBasicAuthHandler Objects" msgstr "" -#: ../../library/urllib.request.rst:1008 ../../library/urllib.request.rst:1019 -#: ../../library/urllib.request.rst:1044 ../../library/urllib.request.rst:1055 +#: ../../library/urllib.request.rst:1020 ../../library/urllib.request.rst:1031 +#: ../../library/urllib.request.rst:1056 ../../library/urllib.request.rst:1067 msgid "Retry the request with authentication information, if available." msgstr "" -#: ../../library/urllib.request.rst:1014 +#: ../../library/urllib.request.rst:1026 msgid "ProxyBasicAuthHandler Objects" msgstr "" -#: ../../library/urllib.request.rst:1025 +#: ../../library/urllib.request.rst:1037 msgid "AbstractDigestAuthHandler Objects" msgstr "" -#: ../../library/urllib.request.rst:1030 +#: ../../library/urllib.request.rst:1042 msgid "" "*authreq* should be the name of the header where the information about the " "realm is included in the request, *host* should be the host to authenticate " @@ -1251,55 +1263,55 @@ msgid "" "should be the error headers." msgstr "" -#: ../../library/urllib.request.rst:1039 +#: ../../library/urllib.request.rst:1051 msgid "HTTPDigestAuthHandler Objects" msgstr "" -#: ../../library/urllib.request.rst:1050 +#: ../../library/urllib.request.rst:1062 msgid "ProxyDigestAuthHandler Objects" msgstr "" -#: ../../library/urllib.request.rst:1061 +#: ../../library/urllib.request.rst:1073 msgid "HTTPHandler Objects" msgstr "" -#: ../../library/urllib.request.rst:1066 +#: ../../library/urllib.request.rst:1078 msgid "" "Send an HTTP request, which can be either GET or POST, depending on ``req." -"has_data()``." +"data``." msgstr "" -#: ../../library/urllib.request.rst:1073 +#: ../../library/urllib.request.rst:1085 msgid "HTTPSHandler Objects" msgstr "Objetos HTTPSHandler" -#: ../../library/urllib.request.rst:1078 +#: ../../library/urllib.request.rst:1090 msgid "" "Send an HTTPS request, which can be either GET or POST, depending on ``req." -"has_data()``." +"data``." msgstr "" -#: ../../library/urllib.request.rst:1085 +#: ../../library/urllib.request.rst:1097 msgid "FileHandler Objects" msgstr "" -#: ../../library/urllib.request.rst:1090 +#: ../../library/urllib.request.rst:1102 msgid "" "Open the file locally, if there is no host name, or the host name is " "``'localhost'``." msgstr "" -#: ../../library/urllib.request.rst:1093 +#: ../../library/urllib.request.rst:1105 msgid "" "This method is applicable only for local hostnames. When a remote hostname " "is given, a :exc:`~urllib.error.URLError` is raised." msgstr "" -#: ../../library/urllib.request.rst:1101 +#: ../../library/urllib.request.rst:1113 msgid "DataHandler Objects" msgstr "" -#: ../../library/urllib.request.rst:1105 +#: ../../library/urllib.request.rst:1117 msgid "" "Read a data URL. This kind of URL contains the content encoded in the URL " "itself. The data URL syntax is specified in :rfc:`2397`. This implementation " @@ -1309,51 +1321,51 @@ msgid "" "implementation will raise a :exc:`ValueError` in that case." msgstr "" -#: ../../library/urllib.request.rst:1116 +#: ../../library/urllib.request.rst:1128 msgid "FTPHandler Objects" msgstr "" -#: ../../library/urllib.request.rst:1121 +#: ../../library/urllib.request.rst:1133 msgid "" "Open the FTP file indicated by *req*. The login is always done with empty " "username and password." msgstr "" -#: ../../library/urllib.request.rst:1128 +#: ../../library/urllib.request.rst:1140 msgid "CacheFTPHandler Objects" msgstr "" -#: ../../library/urllib.request.rst:1130 +#: ../../library/urllib.request.rst:1142 msgid "" ":class:`CacheFTPHandler` objects are :class:`FTPHandler` objects with the " "following additional methods:" msgstr "" -#: ../../library/urllib.request.rst:1136 +#: ../../library/urllib.request.rst:1148 msgid "Set timeout of connections to *t* seconds." msgstr "" -#: ../../library/urllib.request.rst:1141 +#: ../../library/urllib.request.rst:1153 msgid "Set maximum number of cached connections to *m*." msgstr "" -#: ../../library/urllib.request.rst:1147 +#: ../../library/urllib.request.rst:1159 msgid "UnknownHandler Objects" msgstr "Objetos UnknownHandler" -#: ../../library/urllib.request.rst:1152 +#: ../../library/urllib.request.rst:1164 msgid "Raise a :exc:`~urllib.error.URLError` exception." msgstr "" -#: ../../library/urllib.request.rst:1158 +#: ../../library/urllib.request.rst:1170 msgid "HTTPErrorProcessor Objects" msgstr "" -#: ../../library/urllib.request.rst:1164 +#: ../../library/urllib.request.rst:1176 msgid "For 200 error codes, the response object is returned immediately." msgstr "" -#: ../../library/urllib.request.rst:1166 +#: ../../library/urllib.request.rst:1178 msgid "" "For non-200 error codes, this simply passes the job on to the :meth:`!" "http_error_\\` handler methods, via :meth:`OpenerDirector.error`. " @@ -1361,31 +1373,43 @@ msgid "" "error.HTTPError` if no other handler handles the error." msgstr "" -#: ../../library/urllib.request.rst:1174 +#: ../../library/urllib.request.rst:1186 msgid "Process HTTPS error responses." msgstr "" -#: ../../library/urllib.request.rst:1176 +#: ../../library/urllib.request.rst:1188 msgid "The behavior is same as :meth:`http_response`." msgstr "" -#: ../../library/urllib.request.rst:1182 +#: ../../library/urllib.request.rst:1194 msgid "Examples" msgstr "Exemplos" -#: ../../library/urllib.request.rst:1184 +#: ../../library/urllib.request.rst:1196 msgid "" "In addition to the examples below, more examples are given in :ref:`urllib-" "howto`." msgstr "" -#: ../../library/urllib.request.rst:1187 +#: ../../library/urllib.request.rst:1199 msgid "" "This example gets the python.org main page and displays the first 300 bytes " -"of it. ::" +"of it::" +msgstr "" + +#: ../../library/urllib.request.rst:1202 +msgid "" +">>> import urllib.request\n" +">>> with urllib.request.urlopen('http://www.python.org/') as f:\n" +"... print(f.read(300))\n" +"...\n" +"b'\\n\\n\\n\n" +">> import urllib.request\n" +">>> f = urllib.request.urlopen('http://www.python.org/')\n" +">>> try:\n" +"... print(f.read(100).decode('utf-8'))\n" +"... finally:\n" +"... f.close()\n" +"...\n" +"\n" +"\n" +"', char.text)" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:349 msgid "" "A better way to search the namespaced XML example is to create a dictionary " @@ -392,10 +593,33 @@ msgstr "" "A melhor maneira de pesquisar o exemplo XML com espaço de nomes é criar um " "dicionário com seus próprios prefixos e usá-los nas funções de pesquisa::" +#: ../../library/xml.etree.elementtree.rst:352 +msgid "" +"ns = {'real_person': 'http://people.example.com',\n" +" 'role': 'http://characters.example.com'}\n" +"\n" +"for actor in root.findall('real_person:actor', ns):\n" +" name = actor.find('real_person:name', ns)\n" +" print(name.text)\n" +" for char in actor.findall('role:character', ns):\n" +" print(' |-->', char.text)" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:361 msgid "These two approaches both output::" msgstr "Essas duas abordagens resultam no seguinte::" +#: ../../library/xml.etree.elementtree.rst:363 +msgid "" +"John Cleese\n" +" |--> Lancelot\n" +" |--> Archie Leach\n" +"Eric Idle\n" +" |--> Sir Robin\n" +" |--> Gunther\n" +" |--> Commander Clement" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:375 msgid "XPath support" msgstr "Suporte a XPath" @@ -427,6 +651,29 @@ msgstr "" "Estaremos usando o documento XML ``countrydata`` da seção :ref:`Analisando " "XML `::" +#: ../../library/xml.etree.elementtree.rst:389 +msgid "" +"import xml.etree.ElementTree as ET\n" +"\n" +"root = ET.fromstring(countrydata)\n" +"\n" +"# Top-level elements\n" +"root.findall(\".\")\n" +"\n" +"# All 'neighbor' grand-children of 'country' children of the top-level\n" +"# elements\n" +"root.findall(\"./country/neighbor\")\n" +"\n" +"# Nodes with name='Singapore' that have a 'year' child\n" +"root.findall(\".//year/..[@name='Singapore']\")\n" +"\n" +"# 'year' nodes that are children of nodes with name='Singapore'\n" +"root.findall(\".//*[@name='Singapore']/year\")\n" +"\n" +"# All 'neighbor' nodes that are the second child of their parent\n" +"root.findall(\".//neighbor[2]\")" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:409 msgid "" "For XML with namespaces, use the usual qualified ``{namespace}tag`` " @@ -435,6 +682,12 @@ msgstr "" "Para XML com espaços de nomes, use a notação qualificada usual ``{espaço-de-" "nomes}tag``::" +#: ../../library/xml.etree.elementtree.rst:411 +msgid "" +"# All dublin-core \"title\" tags in the document\n" +"root.findall(\".//{http://purl.org/dc/elements/1.1/}title\")" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:416 msgid "Supported XPath syntax" msgstr "" @@ -638,6 +891,18 @@ msgstr "" msgid "Typical uses::" msgstr "" +#: ../../library/xml.etree.elementtree.rst:525 +msgid "" +"xml_data = \"...\"\n" +"print(canonicalize(xml_data))\n" +"\n" +"with open(\"c14n_output.xml\", mode='w', encoding='utf-8') as out_file:\n" +" canonicalize(xml_data, out=out_file)\n" +"\n" +"with open(\"c14n_output.xml\", mode='w', encoding='utf-8') as out_file:\n" +" canonicalize(from_file=\"inputfile.xml\", out=out_file)" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:534 msgid "The configuration *options* are as follows:" msgstr "" @@ -948,6 +1213,14 @@ msgid "" "and use the **href** attribute to specify the document to include." msgstr "" +#: ../../library/xml.etree.elementtree.rst:786 +msgid "" +"\n" +"\n" +" \n" +"" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:793 msgid "" "By default, the **href** attribute is treated as a file name. You can use " @@ -961,6 +1234,16 @@ msgid "" "mod:`xml.etree.ElementTree` module:" msgstr "" +#: ../../library/xml.etree.elementtree.rst:797 +msgid "" +"from xml.etree import ElementTree, ElementInclude\n" +"\n" +"tree = ElementTree.parse(\"document.xml\")\n" +"root = tree.getroot()\n" +"\n" +"ElementInclude.include(root)" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:806 msgid "" "The ElementInclude module replaces the ``{http://www.w3.org/2001/XInclude}" @@ -968,6 +1251,13 @@ msgid "" "The result might look something like this:" msgstr "" +#: ../../library/xml.etree.elementtree.rst:808 +msgid "" +"\n" +" This is a paragraph.\n" +"" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:814 msgid "" "If the **parse** attribute is omitted, it defaults to \"xml\". The href " @@ -980,10 +1270,25 @@ msgid "" "include`` element, and set the **parse** attribute to \"text\":" msgstr "" +#: ../../library/xml.etree.elementtree.rst:818 +msgid "" +"\n" +"\n" +" Copyright (c) .\n" +"" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:825 msgid "The result might look something like:" msgstr "" +#: ../../library/xml.etree.elementtree.rst:827 +msgid "" +"\n" +" Copyright (c) 2003.\n" +"" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:845 msgid "" "Default loader. This default loader reads an included resource from disk. " @@ -1047,6 +1352,10 @@ msgid "" "the XML data" msgstr "" +#: ../../library/xml.etree.elementtree.rst:907 +msgid "1234" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:911 msgid "" "the *a* element has ``None`` for both *text* and *tail* attributes, the *b* " @@ -1122,8 +1431,8 @@ msgstr "" #: ../../library/xml.etree.elementtree.rst:974 msgid "" -"Appends *subelements* from a sequence object with zero or more elements. " -"Raises :exc:`TypeError` if a subelement is not an :class:`Element`." +"Appends *subelements* from an iterable of elements. Raises :exc:`TypeError` " +"if a subelement is not an :class:`Element`." msgstr "" #: ../../library/xml.etree.elementtree.rst:982 @@ -1212,6 +1521,17 @@ msgid "" "None`` tests.::" msgstr "" +#: ../../library/xml.etree.elementtree.rst:1067 +msgid "" +"element = root.find('foo')\n" +"\n" +"if not element: # careful!\n" +" print(\"element not found, or element has no subelements\")\n" +"\n" +"if element is None:\n" +" print(\"element not found\")" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:1075 msgid "Testing the truth value of an Element emits :exc:`DeprecationWarning`." msgstr "" @@ -1246,6 +1566,18 @@ msgid "" "independently from the Element creation::" msgstr "" +#: ../../library/xml.etree.elementtree.rst:1099 +msgid "" +"def reorder_attributes(root):\n" +" for el in root.iter():\n" +" attrib = el.attrib\n" +" if len(attrib) > 1:\n" +" # adjust attribute order, e.g. by sorting\n" +" attribs = sorted(attrib.items())\n" +" attrib.clear()\n" +" attrib.update(attribs)" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:1112 msgid "ElementTree Objects" msgstr "" @@ -1340,12 +1672,43 @@ msgstr "" msgid "This is the XML file that is going to be manipulated::" msgstr "" +#: ../../library/xml.etree.elementtree.rst:1209 +msgid "" +"\n" +" \n" +" Example page\n" +" \n" +" \n" +"

Moved to example.org\n" +" or example.com.

\n" +" \n" +"" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:1219 msgid "" "Example of changing the attribute \"target\" of every link in first " "paragraph::" msgstr "" +#: ../../library/xml.etree.elementtree.rst:1221 +msgid "" +">>> from xml.etree.ElementTree import ElementTree\n" +">>> tree = ElementTree()\n" +">>> tree.parse(\"index.xhtml\")\n" +"\n" +">>> p = tree.find(\"body/p\") # Finds first occurrence of tag p in body\n" +">>> p\n" +"\n" +">>> links = list(p.iter(\"a\")) # Returns list of all links\n" +">>> links\n" +"[, ]\n" +">>> for i in links: # Iterates through all found links\n" +"... i.attrib[\"target\"] = \"blank\"\n" +"...\n" +">>> tree.write(\"output.xhtml\")" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:1239 msgid "QName Objects" msgstr "" @@ -1479,7 +1842,7 @@ msgstr "" #: ../../library/xml.etree.elementtree.rst:1376 msgid "" "Parameters are now :ref:`keyword-only `. The *html* " -"argument no longer supported." +"argument is no longer supported." msgstr "" #: ../../library/xml.etree.elementtree.rst:1383 @@ -1523,6 +1886,41 @@ msgid "" "of an XML file::" msgstr "" +#: ../../library/xml.etree.elementtree.rst:1418 +msgid "" +">>> from xml.etree.ElementTree import XMLParser\n" +">>> class MaxDepth: # The target object of the parser\n" +"... maxDepth = 0\n" +"... depth = 0\n" +"... def start(self, tag, attrib): # Called for each opening tag.\n" +"... self.depth += 1\n" +"... if self.depth > self.maxDepth:\n" +"... self.maxDepth = self.depth\n" +"... def end(self, tag): # Called for each closing tag.\n" +"... self.depth -= 1\n" +"... def data(self, data):\n" +"... pass # We do not need to do anything with data.\n" +"... def close(self): # Called when all data has been parsed.\n" +"... return self.maxDepth\n" +"...\n" +">>> target = MaxDepth()\n" +">>> parser = XMLParser(target=target)\n" +">>> exampleXml = \"\"\"\n" +"... \n" +"... \n" +"... \n" +"... \n" +"... \n" +"... \n" +"... \n" +"... \n" +"... \n" +"... \"\"\"\n" +">>> parser.feed(exampleXml)\n" +">>> parser.close()\n" +"4" +msgstr "" + #: ../../library/xml.etree.elementtree.rst:1454 msgid "XMLPullParser Objects" msgstr "" diff --git a/library/xml.po b/library/xml.po index 863e6406b..fba687406 100644 --- a/library/xml.po +++ b/library/xml.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:18+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/xml.sax.handler.po b/library/xml.sax.handler.po index 5126367de..4e50a512f 100644 --- a/library/xml.sax.handler.po +++ b/library/xml.sax.handler.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Hemílio Lauro , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:18+0000\n" -"Last-Translator: Hemílio Lauro , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/xml.sax.po b/library/xml.sax.po index 5ddc478a8..397486d6b 100644 --- a/library/xml.sax.po +++ b/library/xml.sax.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:18+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/xml.sax.reader.po b/library/xml.sax.reader.po index 712c8fc65..152d1facb 100644 --- a/library/xml.sax.reader.po +++ b/library/xml.sax.reader.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:18+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/library/xml.sax.utils.po b/library/xml.sax.utils.po index d393f7355..68197962b 100644 --- a/library/xml.sax.utils.po +++ b/library/xml.sax.utils.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:18+0000\n" -"Last-Translator: Rafael Fontenelle , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -82,6 +82,12 @@ msgid "" "directly as an attribute value::" msgstr "" +#: ../../library/xml.sax.utils.rst:55 +msgid "" +">>> print(\"\" % quoteattr(\"ab ' cd \\\" ef\"))\n" +"" +msgstr "" + #: ../../library/xml.sax.utils.rst:58 msgid "" "This function is useful when generating attribute values for HTML or any " diff --git a/library/xmlrpc.client.po b/library/xmlrpc.client.po index cb8e645b1..1fc27b8ea 100644 --- a/library/xmlrpc.client.po +++ b/library/xmlrpc.client.po @@ -1,35 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Julio Biason, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:18+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-03-07 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/xmlrpc.client.rst:2 msgid ":mod:`!xmlrpc.client` --- XML-RPC client access" -msgstr "" +msgstr ":mod:`!xmlrpc.client` --- Cliente XML-RPC" #: ../../library/xmlrpc.client.rst:10 msgid "**Source code:** :source:`Lib/xmlrpc/client.py`" @@ -69,8 +65,8 @@ msgstr "" "certificado e nome do servidor necessárias por padrão." #: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +msgid "Availability" +msgstr "Disponibilidade" #: ../../includes/wasm-notavail.rst:5 msgid "" @@ -115,55 +111,30 @@ msgid "" "class:`bytes` and :class:`bytearray` objects may be passed to calls. The " "*headers* parameter is an optional sequence of HTTP headers to send with " "each request, expressed as a sequence of 2-tuples representing the header " -"name and value. (e.g. ``[('Header-Name', 'value')]``). The obsolete " -"*use_datetime* flag is similar to *use_builtin_types* but it applies only to " -"date/time values." -msgstr "" -"Os seguite parâmetros coordenam o uso da intância de proxy retornada. Se " -"*alow_none* for verdadeiro, a constante ``None`` do Python será traduzida " -"para XML; o comportamento padrão é que ``None`` levante uma :exc:" -"`TypeError`, Isso é uma extensão comum da especificação do XML-RPC, mas não " -"é suportado por todos os clientes e servidores, veja `http://ontosys.com/" -"xml-rpc/extensions.php `_ para uma descrição. A flag " -"*use_builtin_types* pode ser usada para que valores de data e hora sejam " -"representados como objetos :class:`datetime.datetime` e dados binários " -"representados com objetos :class:`bytes`; essa flag é False por padrão. " -"Objetos :class:`datetime.datetime`, :class:`bytes` e :class:`bytearray` " -"podem ser usados nas chamadas. O parâmetro *headers* é uma sequência " -"opcional de headers a serem enviados em cada requisição, representados por " -"uma sequência de tuplas de dois valores representando o nome do header e seu " -"valor (como ``[('Header-Name', 'value')]``). A flag *use_datetime* é " -"obsoleta e é similar a *use_builtin_types* mas se aplica somente a valores " -"de data e hora." - -#: ../../library/xmlrpc.client.rst:67 ../../library/xmlrpc.client.rst:549 +"name and value. (e.g. ``[('Header-Name', 'value')]``). If an HTTPS URL is " +"provided, *context* may be :class:`ssl.SSLContext` and configures the SSL " +"settings of the underlying HTTPS connection. The obsolete *use_datetime* " +"flag is similar to *use_builtin_types* but it applies only to date/time " +"values." +msgstr "" + +#: ../../library/xmlrpc.client.rst:69 ../../library/xmlrpc.client.rst:549 msgid "The *use_builtin_types* flag was added." msgstr "O sinalizador *use_builtin_types* foi adicionado." -#: ../../library/xmlrpc.client.rst:70 +#: ../../library/xmlrpc.client.rst:72 msgid "The *headers* parameter was added." msgstr "O parâmetro *headers* foi adicionado." -#: ../../library/xmlrpc.client.rst:73 +#: ../../library/xmlrpc.client.rst:75 msgid "" "Both the HTTP and HTTPS transports support the URL syntax extension for HTTP " "Basic Authentication: ``http://user:pass@host:port/path``. The ``user:" "pass`` portion will be base64-encoded as an HTTP 'Authorization' header, and " "sent to the remote server as part of the connection process when invoking an " "XML-RPC method. You only need to use this if the remote server requires a " -"Basic Authentication user and password. If an HTTPS URL is provided, " -"*context* may be :class:`ssl.SSLContext` and configures the SSL settings of " -"the underlying HTTPS connection." -msgstr "" -"Tanto o transporte por HTTP quanto o transporte por HTTP suportam a extensão " -"da sintaxe de URL para Autenticação Básica do HTTP: ``http://user:pass@host:" -"port/path``. A parte ``user:pass`` será codificada em Base64 como um header " -"HTTP 'Authorization', e enviada para o servidor remoto como parte do " -"processo de conexão quando for invocado um método XML-RPC. Você só precisar " -"usar isso se o servidor remoto requer Autenticação Básica com usuário e " -"senha. Se for usada uma URL HTTPS, *context* pode ser do tipo :class:`ssl." -"SSLContext` e configurar o SSL da conexão HTTPS por baixo." +"Basic Authentication user and password." +msgstr "" #: ../../library/xmlrpc.client.rst:82 msgid "" @@ -195,7 +166,7 @@ msgstr "Tipo XML-RPC" #: ../../library/xmlrpc.client.rst:95 msgid "Python type" -msgstr "Python type" +msgstr "Tipo em Python" #: ../../library/xmlrpc.client.rst:97 msgid "``boolean``" @@ -381,11 +352,8 @@ msgstr "" #: ../../library/xmlrpc.client.rst:168 msgid "" -"`XML-RPC Introspection `_" +"`XML-RPC Introspection `_" msgstr "" -"`XML-RPC Introspection `_" #: ../../library/xmlrpc.client.rst:169 msgid "Describes the XML-RPC protocol extension for introspection." @@ -473,11 +441,33 @@ msgstr "" msgid "A working example follows. The server code::" msgstr "" +#: ../../library/xmlrpc.client.rst:231 +msgid "" +"from xmlrpc.server import SimpleXMLRPCServer\n" +"\n" +"def is_even(n):\n" +" return n % 2 == 0\n" +"\n" +"server = SimpleXMLRPCServer((\"localhost\", 8000))\n" +"print(\"Listening on port 8000...\")\n" +"server.register_function(is_even, \"is_even\")\n" +"server.serve_forever()" +msgstr "" + #: ../../library/xmlrpc.client.rst:241 ../../library/xmlrpc.client.rst:291 #: ../../library/xmlrpc.client.rst:401 ../../library/xmlrpc.client.rst:507 msgid "The client code for the preceding server::" msgstr "" +#: ../../library/xmlrpc.client.rst:243 +msgid "" +"import xmlrpc.client\n" +"\n" +"with xmlrpc.client.ServerProxy(\"http://localhost:8000/\") as proxy:\n" +" print(\"3 is even: %s\" % str(proxy.is_even(3)))\n" +" print(\"100 is even: %s\" % str(proxy.is_even(100)))" +msgstr "" + #: ../../library/xmlrpc.client.rst:252 msgid "DateTime Objects" msgstr "Objetos DateTime" @@ -506,6 +496,35 @@ msgid "" "comparison ` and :meth:`~object.__repr__` methods." msgstr "" +#: ../../library/xmlrpc.client.rst:278 +msgid "" +"import datetime\n" +"from xmlrpc.server import SimpleXMLRPCServer\n" +"import xmlrpc.client\n" +"\n" +"def today():\n" +" today = datetime.datetime.today()\n" +" return xmlrpc.client.DateTime(today)\n" +"\n" +"server = SimpleXMLRPCServer((\"localhost\", 8000))\n" +"print(\"Listening on port 8000...\")\n" +"server.register_function(today, \"today\")\n" +"server.serve_forever()" +msgstr "" + +#: ../../library/xmlrpc.client.rst:293 +msgid "" +"import xmlrpc.client\n" +"import datetime\n" +"\n" +"proxy = xmlrpc.client.ServerProxy(\"http://localhost:8000/\")\n" +"\n" +"today = proxy.today()\n" +"# convert the ISO8601 string to a datetime object\n" +"converted = datetime.datetime.strptime(today.value, \"%Y%m%dT%H:%M:%S\")\n" +"print(\"Today: %s\" % converted.strftime(\"%d.%m.%Y, %H:%M\"))" +msgstr "" + #: ../../library/xmlrpc.client.rst:306 msgid "Binary Objects" msgstr "Objetos Binários" @@ -560,10 +579,35 @@ msgid "" "XMLRPC::" msgstr "" +#: ../../library/xmlrpc.client.rst:344 +msgid "" +"from xmlrpc.server import SimpleXMLRPCServer\n" +"import xmlrpc.client\n" +"\n" +"def python_logo():\n" +" with open(\"python_logo.jpg\", \"rb\") as handle:\n" +" return xmlrpc.client.Binary(handle.read())\n" +"\n" +"server = SimpleXMLRPCServer((\"localhost\", 8000))\n" +"print(\"Listening on port 8000...\")\n" +"server.register_function(python_logo, 'python_logo')\n" +"\n" +"server.serve_forever()" +msgstr "" + #: ../../library/xmlrpc.client.rst:357 msgid "The client gets the image and saves it to a file::" msgstr "" +#: ../../library/xmlrpc.client.rst:359 +msgid "" +"import xmlrpc.client\n" +"\n" +"proxy = xmlrpc.client.ServerProxy(\"http://localhost:8000/\")\n" +"with open(\"fetched_python_logo.jpg\", \"wb\") as handle:\n" +" handle.write(proxy.python_logo().data)" +msgstr "" + #: ../../library/xmlrpc.client.rst:368 msgid "Fault Objects" msgstr "Objetos Fault" @@ -588,9 +632,38 @@ msgid "" "by returning a complex type object. The server code::" msgstr "" +#: ../../library/xmlrpc.client.rst:388 +msgid "" +"from xmlrpc.server import SimpleXMLRPCServer\n" +"\n" +"# A marshalling error is going to occur because we're returning a\n" +"# complex number\n" +"def add(x, y):\n" +" return x+y+0j\n" +"\n" +"server = SimpleXMLRPCServer((\"localhost\", 8000))\n" +"print(\"Listening on port 8000...\")\n" +"server.register_function(add, 'add')\n" +"\n" +"server.serve_forever()" +msgstr "" + +#: ../../library/xmlrpc.client.rst:403 +msgid "" +"import xmlrpc.client\n" +"\n" +"proxy = xmlrpc.client.ServerProxy(\"http://localhost:8000/\")\n" +"try:\n" +" proxy.add(2, 5)\n" +"except xmlrpc.client.Fault as err:\n" +" print(\"A fault occurred\")\n" +" print(\"Fault code: %d\" % err.faultCode)\n" +" print(\"Fault string: %s\" % err.faultString)" +msgstr "" + #: ../../library/xmlrpc.client.rst:418 msgid "ProtocolError Objects" -msgstr "Objeto ProtocolError" +msgstr "Objetos ProtocolError" #: ../../library/xmlrpc.client.rst:422 msgid "" @@ -623,6 +696,23 @@ msgid "" "`ProtocolError` by providing an invalid URI::" msgstr "" +#: ../../library/xmlrpc.client.rst:450 +msgid "" +"import xmlrpc.client\n" +"\n" +"# create a ServerProxy with a URI that doesn't respond to XMLRPC requests\n" +"proxy = xmlrpc.client.ServerProxy(\"http://google.com/\")\n" +"\n" +"try:\n" +" proxy.some_method()\n" +"except xmlrpc.client.ProtocolError as err:\n" +" print(\"A protocol error occurred\")\n" +" print(\"URL: %s\" % err.url)\n" +" print(\"HTTP/HTTPS headers: %s\" % err.headers)\n" +" print(\"Error code: %d\" % err.errcode)\n" +" print(\"Error message: %s\" % err.errmsg)" +msgstr "" + #: ../../library/xmlrpc.client.rst:465 msgid "MultiCall Objects" msgstr "Objetos MultiCall" @@ -648,6 +738,48 @@ msgstr "" msgid "A usage example of this class follows. The server code::" msgstr "" +#: ../../library/xmlrpc.client.rst:483 +msgid "" +"from xmlrpc.server import SimpleXMLRPCServer\n" +"\n" +"def add(x, y):\n" +" return x + y\n" +"\n" +"def subtract(x, y):\n" +" return x - y\n" +"\n" +"def multiply(x, y):\n" +" return x * y\n" +"\n" +"def divide(x, y):\n" +" return x // y\n" +"\n" +"# A simple server with simple arithmetic functions\n" +"server = SimpleXMLRPCServer((\"localhost\", 8000))\n" +"print(\"Listening on port 8000...\")\n" +"server.register_multicall_functions()\n" +"server.register_function(add, 'add')\n" +"server.register_function(subtract, 'subtract')\n" +"server.register_function(multiply, 'multiply')\n" +"server.register_function(divide, 'divide')\n" +"server.serve_forever()" +msgstr "" + +#: ../../library/xmlrpc.client.rst:509 +msgid "" +"import xmlrpc.client\n" +"\n" +"proxy = xmlrpc.client.ServerProxy(\"http://localhost:8000/\")\n" +"multicall = xmlrpc.client.MultiCall(proxy)\n" +"multicall.add(7, 3)\n" +"multicall.subtract(7, 3)\n" +"multicall.multiply(7, 3)\n" +"multicall.divide(7, 3)\n" +"result = multicall()\n" +"\n" +"print(\"7+3=%d, 7-3=%d, 7*3=%d, 7//3=%d\" % tuple(result))" +msgstr "" + #: ../../library/xmlrpc.client.rst:523 msgid "Convenience Functions" msgstr "" @@ -685,19 +817,59 @@ msgstr "" msgid "Example of Client Usage" msgstr "Exemplo de uso do cliente" +#: ../../library/xmlrpc.client.rst:560 +msgid "" +"# simple test program (from the XML-RPC specification)\n" +"from xmlrpc.client import ServerProxy, Error\n" +"\n" +"# server = ServerProxy(\"http://localhost:8000\") # local server\n" +"with ServerProxy(\"http://betty.userland.com\") as proxy:\n" +"\n" +" print(proxy)\n" +"\n" +" try:\n" +" print(proxy.examples.getStateName(41))\n" +" except Error as v:\n" +" print(\"ERROR\", v)" +msgstr "" + #: ../../library/xmlrpc.client.rst:573 msgid "" "To access an XML-RPC server through a HTTP proxy, you need to define a " "custom transport. The following example shows how::" msgstr "" +#: ../../library/xmlrpc.client.rst:576 +msgid "" +"import http.client\n" +"import xmlrpc.client\n" +"\n" +"class ProxiedTransport(xmlrpc.client.Transport):\n" +"\n" +" def set_proxy(self, host, port=None, headers=None):\n" +" self.proxy = host, port\n" +" self.proxy_headers = headers\n" +"\n" +" def make_connection(self, host):\n" +" connection = http.client.HTTPConnection(*self.proxy)\n" +" connection.set_tunnel(host, headers=self.proxy_headers)\n" +" self._connection = host, connection\n" +" return connection\n" +"\n" +"transport = ProxiedTransport()\n" +"transport.set_proxy('proxy-server', 8080)\n" +"server = xmlrpc.client.ServerProxy('http://betty.userland.com', " +"transport=transport)\n" +"print(server.examples.getStateName(41))" +msgstr "" + #: ../../library/xmlrpc.client.rst:598 msgid "Example of Client and Server Usage" msgstr "" #: ../../library/xmlrpc.client.rst:600 msgid "See :ref:`simplexmlrpcserver-example`." -msgstr "" +msgstr "Veja :ref:`simplexmlrpcserver-example`." #: ../../library/xmlrpc.client.rst:604 msgid "Footnotes" diff --git a/library/xmlrpc.po b/library/xmlrpc.po index d2a9585f2..f1a00f808 100644 --- a/library/xmlrpc.po +++ b/library/xmlrpc.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:18+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -27,7 +27,7 @@ msgstr "" msgid ":mod:`!xmlrpc` --- XMLRPC server and client modules" msgstr ":mod:`!xmlrpc` --- Módulos de servidor e cliente XMLRPC" -#: ../../library/xmlrpc.rst:4 +#: ../../library/xmlrpc.rst:7 msgid "" "XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a " "transport. With it, a client can call methods with parameters on a remote " @@ -38,7 +38,7 @@ msgstr "" "parâmetros em um servidor remoto (o servidor é nomeado por um URI) e receber " "dados estruturados." -#: ../../library/xmlrpc.rst:8 +#: ../../library/xmlrpc.rst:11 msgid "" "``xmlrpc`` is a package that collects server and client modules implementing " "XML-RPC. The modules are:" @@ -46,10 +46,10 @@ msgstr "" "``xmlrpc`` é um pacote que coleta módulos de servidor e de cliente que " "implementam o XML-RPC. Os módulos são:" -#: ../../library/xmlrpc.rst:11 +#: ../../library/xmlrpc.rst:14 msgid ":mod:`xmlrpc.client`" msgstr ":mod:`xmlrpc.client`" -#: ../../library/xmlrpc.rst:12 +#: ../../library/xmlrpc.rst:15 msgid ":mod:`xmlrpc.server`" msgstr ":mod:`xmlrpc.server`" diff --git a/library/xmlrpc.server.po b/library/xmlrpc.server.po index 4ab1d5c3e..41375cc17 100644 --- a/library/xmlrpc.server.po +++ b/library/xmlrpc.server.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Italo Penaforte , 2021 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:18+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -56,8 +54,8 @@ msgstr "" "autenticados, consulte :ref:`xml-vulnerabilities`." #: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +msgid "Availability" +msgstr "Disponibilidade" #: ../../includes/wasm-notavail.rst:5 msgid "" @@ -90,7 +88,7 @@ msgstr "" "registro de funções que podem ser chamadas pelo protocolo XML-RPC. O " "parâmetro *requestHandler* deve ser uma fábrica para instâncias do tratador " "de solicitações; o padrão é :class:`SimpleXMLRPCRequestHandler`. Os " -"parâmetros *addr* e *requestHandler* são passados ​​para o construtor :class:" +"parâmetros *addr* e *requestHandler* são passados para o construtor :class:" "`socketserver.TCPServer`. Se *logRequests* for true (o padrão), as " "solicitações serão registradas; definir esse parâmetro como false desativará " "os registros. Os parâmetros *allow_none* e *encoding* são transmitidos para :" @@ -100,7 +98,7 @@ msgstr "" "é true. A configuração como false permite que o código manipule a variável " "de classe *allow_reuse_address* antes que o endereço seja vinculado. O " "parâmetro *use_builtin_types* é passado para a função :func:`~xmlrpc.client." -"loads` e controla quais tipos são processados ​​quando valores de data/hora ou " +"loads` e controla quais tipos são processados quando valores de data/hora ou " "dados binários são recebidos; o padrão é false." #: ../../library/xmlrpc.server.rst:48 ../../library/xmlrpc.server.rst:62 @@ -262,6 +260,73 @@ msgstr "Exemplo de SimpleXMLRPCServer" msgid "Server code::" msgstr "Código do servidor::" +#: ../../library/xmlrpc.server.rst:150 +msgid "" +"from xmlrpc.server import SimpleXMLRPCServer\n" +"from xmlrpc.server import SimpleXMLRPCRequestHandler\n" +"\n" +"# Restrict to a particular path.\n" +"class RequestHandler(SimpleXMLRPCRequestHandler):\n" +" rpc_paths = ('/RPC2',)\n" +"\n" +"# Create server\n" +"with SimpleXMLRPCServer(('localhost', 8000),\n" +" requestHandler=RequestHandler) as server:\n" +" server.register_introspection_functions()\n" +"\n" +" # Register pow() function; this will use the value of\n" +" # pow.__name__ as the name, which is just 'pow'.\n" +" server.register_function(pow)\n" +"\n" +" # Register a function under a different name\n" +" def adder_function(x, y):\n" +" return x + y\n" +" server.register_function(adder_function, 'add')\n" +"\n" +" # Register an instance; all the methods of the instance are\n" +" # published as XML-RPC methods (in this case, just 'mul').\n" +" class MyFuncs:\n" +" def mul(self, x, y):\n" +" return x * y\n" +"\n" +" server.register_instance(MyFuncs())\n" +"\n" +" # Run the server's main loop\n" +" server.serve_forever()" +msgstr "" +"from xmlrpc.server import SimpleXMLRPCServer\n" +"from xmlrpc.server import SimpleXMLRPCRequestHandler\n" +"\n" +"# Restringe a um caminho em particular.\n" +"class RequestHandler(SimpleXMLRPCRequestHandler):\n" +" rpc_paths = ('/RPC2',)\n" +"\n" +"# Cria o servidor\n" +"with SimpleXMLRPCServer(('localhost', 8000),\n" +" requestHandler=RequestHandler) as server:\n" +" server.register_introspection_functions()\n" +"\n" +" # Registra uma função pow(); isso vai usar o valor de\n" +" # pow.__name__ como o nome, que é apenas 'pow'.\n" +" server.register_function(pow)\n" +"\n" +" # Registra uma função sob um nome diferente\n" +" def adder_function(x, y):\n" +" return x + y\n" +" server.register_function(adder_function, 'add')\n" +"\n" +" # Registra uma instância; todos os métodos da instância\n" +" # são publicados como métodos XML-RPC (neste caso,\n" +" # apenas 'mul').\n" +" class MyFuncs:\n" +" def mul(self, x, y):\n" +" return x * y\n" +"\n" +" server.register_instance(MyFuncs())\n" +"\n" +" # Executa o laço principal do servidor\n" +" server.serve_forever()" + #: ../../library/xmlrpc.server.rst:182 msgid "" "The following client code will call the methods made available by the " @@ -270,6 +335,28 @@ msgstr "" "O código do cliente a seguir chamará os métodos disponibilizados pelo " "servidor anterior::" +#: ../../library/xmlrpc.server.rst:185 +msgid "" +"import xmlrpc.client\n" +"\n" +"s = xmlrpc.client.ServerProxy('http://localhost:8000')\n" +"print(s.pow(2,3)) # Returns 2**3 = 8\n" +"print(s.add(2,3)) # Returns 5\n" +"print(s.mul(5,2)) # Returns 5*2 = 10\n" +"\n" +"# Print list of available methods\n" +"print(s.system.listMethods())" +msgstr "" +"import xmlrpc.client\n" +"\n" +"s = xmlrpc.client.ServerProxy('http://localhost:8000')\n" +"print(s.pow(2,3)) # Returns 2**3 = 8\n" +"print(s.add(2,3)) # Returns 5\n" +"print(s.mul(5,2)) # Returns 5*2 = 10\n" +"\n" +"# Exibe uma lista dos métodos disponíveis\n" +"print(s.system.listMethods())" + #: ../../library/xmlrpc.server.rst:195 msgid "" ":meth:`register_function` can also be used as a decorator. The previous " @@ -278,6 +365,64 @@ msgstr "" ":meth:`register_function` também pode ser usado como um decorador. O exemplo " "anterior do servidor pode registrar funções com um decorador::" +#: ../../library/xmlrpc.server.rst:198 +msgid "" +"from xmlrpc.server import SimpleXMLRPCServer\n" +"from xmlrpc.server import SimpleXMLRPCRequestHandler\n" +"\n" +"class RequestHandler(SimpleXMLRPCRequestHandler):\n" +" rpc_paths = ('/RPC2',)\n" +"\n" +"with SimpleXMLRPCServer(('localhost', 8000),\n" +" requestHandler=RequestHandler) as server:\n" +" server.register_introspection_functions()\n" +"\n" +" # Register pow() function; this will use the value of\n" +" # pow.__name__ as the name, which is just 'pow'.\n" +" server.register_function(pow)\n" +"\n" +" # Register a function under a different name, using\n" +" # register_function as a decorator. *name* can only be given\n" +" # as a keyword argument.\n" +" @server.register_function(name='add')\n" +" def adder_function(x, y):\n" +" return x + y\n" +"\n" +" # Register a function under function.__name__.\n" +" @server.register_function\n" +" def mul(x, y):\n" +" return x * y\n" +"\n" +" server.serve_forever()" +msgstr "" +"from xmlrpc.server import SimpleXMLRPCServer\n" +"from xmlrpc.server import SimpleXMLRPCRequestHandler\n" +"\n" +"class RequestHandler(SimpleXMLRPCRequestHandler):\n" +" rpc_paths = ('/RPC2',)\n" +"\n" +"with SimpleXMLRPCServer(('localhost', 8000),\n" +" requestHandler=RequestHandler) as server:\n" +" server.register_introspection_functions()\n" +"\n" +" # Registra a função pow(); isso vai usar o valor de\n" +" # pow.__name__ como o nome, que é apenas 'pow'.\n" +" server.register_function(pow)\n" +"\n" +" # Registra uma função sob um nome diferente, usando\n" +" # register_function como um decorador. *name* só pode\n" +" # ser dado como um argumento nomeado.\n" +" @server.register_function(name='add')\n" +" def adder_function(x, y):\n" +" return x + y\n" +"\n" +" # Registra uma função sob function.__name__.\n" +" @server.register_function\n" +" def mul(x, y):\n" +" return x * y\n" +"\n" +" server.serve_forever()" + #: ../../library/xmlrpc.server.rst:226 msgid "" "The following example included in the :file:`Lib/xmlrpc/server.py` module " @@ -298,11 +443,63 @@ msgstr "" "códigos arbitrários em sua máquina. Use este exemplo apenas em uma rede " "fechada e segura." +#: ../../library/xmlrpc.server.rst:237 +msgid "" +"import datetime\n" +"\n" +"class ExampleService:\n" +" def getData(self):\n" +" return '42'\n" +"\n" +" class currentTime:\n" +" @staticmethod\n" +" def getCurrentTime():\n" +" return datetime.datetime.now()\n" +"\n" +"with SimpleXMLRPCServer((\"localhost\", 8000)) as server:\n" +" server.register_function(pow)\n" +" server.register_function(lambda x,y: x+y, 'add')\n" +" server.register_instance(ExampleService(), allow_dotted_names=True)\n" +" server.register_multicall_functions()\n" +" print('Serving XML-RPC on localhost port 8000')\n" +" try:\n" +" server.serve_forever()\n" +" except KeyboardInterrupt:\n" +" print(\"\\nKeyboard interrupt received, exiting.\")\n" +" sys.exit(0)" +msgstr "" +"import datetime\n" +"\n" +"class ExampleService:\n" +" def getData(self):\n" +" return '42'\n" +"\n" +" class currentTime:\n" +" @staticmethod\n" +" def getCurrentTime():\n" +" return datetime.datetime.now()\n" +"\n" +"with SimpleXMLRPCServer((\"localhost\", 8000)) as server:\n" +" server.register_function(pow)\n" +" server.register_function(lambda x,y: x+y, 'add')\n" +" server.register_instance(ExampleService(), allow_dotted_names=True)\n" +" server.register_multicall_functions()\n" +" print('Serving XML-RPC on localhost port 8000')\n" +" try:\n" +" server.serve_forever()\n" +" except KeyboardInterrupt:\n" +" print(\"\\nKeyboard interrupt received, exiting.\")\n" +" sys.exit(0)" + #: ../../library/xmlrpc.server.rst:260 msgid "This ExampleService demo can be invoked from the command line::" msgstr "" "Esta demonstração ExampleService pode ser chamada na linha de comando::" +#: ../../library/xmlrpc.server.rst:262 +msgid "python -m xmlrpc.server" +msgstr "python -m xmlrpc.server" + #: ../../library/xmlrpc.server.rst:265 msgid "" "The client that interacts with the above server is included in ``Lib/xmlrpc/" @@ -311,6 +508,42 @@ msgstr "" "O cliente que interage com o servidor acima está incluído em ``Lib/xmlrpc/" "client.py``::" +#: ../../library/xmlrpc.server.rst:268 +msgid "" +"server = ServerProxy(\"http://localhost:8000\")\n" +"\n" +"try:\n" +" print(server.currentTime.getCurrentTime())\n" +"except Error as v:\n" +" print(\"ERROR\", v)\n" +"\n" +"multi = MultiCall(server)\n" +"multi.getData()\n" +"multi.pow(2,9)\n" +"multi.add(1,2)\n" +"try:\n" +" for response in multi():\n" +" print(response)\n" +"except Error as v:\n" +" print(\"ERROR\", v)" +msgstr "" +"server = ServerProxy(\"http://localhost:8000\")\n" +"\n" +"try:\n" +" print(server.currentTime.getCurrentTime())\n" +"except Error as v:\n" +" print(\"ERROR\", v)\n" +"\n" +"multi = MultiCall(server)\n" +"multi.getData()\n" +"multi.pow(2,9)\n" +"multi.add(1,2)\n" +"try:\n" +" for response in multi():\n" +" print(response)\n" +"except Error as v:\n" +" print(\"ERROR\", v)" + #: ../../library/xmlrpc.server.rst:285 msgid "" "This client which interacts with the demo XMLRPC server can be invoked as::" @@ -318,6 +551,10 @@ msgstr "" "Este cliente que interage com o servidor XMLRPC de demonstração pode ser " "chamado como::" +#: ../../library/xmlrpc.server.rst:287 +msgid "python -m xmlrpc.client" +msgstr "python -m xmlrpc.client" + #: ../../library/xmlrpc.server.rst:291 msgid "CGIXMLRPCRequestHandler" msgstr "CGIXMLRPCRequestHandler" @@ -381,6 +618,32 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" +#: ../../library/xmlrpc.server.rst:344 +msgid "" +"class MyFuncs:\n" +" def mul(self, x, y):\n" +" return x * y\n" +"\n" +"\n" +"handler = CGIXMLRPCRequestHandler()\n" +"handler.register_function(pow)\n" +"handler.register_function(lambda x,y: x+y, 'add')\n" +"handler.register_introspection_functions()\n" +"handler.register_instance(MyFuncs())\n" +"handler.handle_request()" +msgstr "" +"class MyFuncs:\n" +" def mul(self, x, y):\n" +" return x * y\n" +"\n" +"\n" +"handler = CGIXMLRPCRequestHandler()\n" +"handler.register_function(pow)\n" +"handler.register_function(lambda x,y: x+y, 'add')\n" +"handler.register_introspection_functions()\n" +"handler.register_instance(MyFuncs())\n" +"handler.handle_request()" + #: ../../library/xmlrpc.server.rst:358 msgid "Documenting XMLRPC server" msgstr "Documentando servidor XMLRPC" diff --git a/library/zipapp.po b/library/zipapp.po index dfb361bc6..c54df05da 100644 --- a/library/zipapp.po +++ b/library/zipapp.po @@ -1,34 +1,31 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:18+0000\n" -"Last-Translator: i17obot , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/zipapp.rst:2 msgid ":mod:`!zipapp` --- Manage executable Python zip archives" -msgstr "" +msgstr ":mod:`!zipapp` --- Gerencia arquivos zip executáveis do Python" #: ../../library/zipapp.rst:9 msgid "**Source code:** :source:`Lib/zipapp.py`" @@ -41,10 +38,14 @@ msgid "" "`. The module provides both a :ref:`zipapp-" "command-line-interface` and a :ref:`zipapp-python-api`." msgstr "" +"Este módulo fornece ferramentas para gerenciar a criação de arquivos zip " +"contendo código Python, que pode ser :ref:`executado diretamente pelo " +"interpretador Python `. O módulo fornece uma :" +"ref:`zipapp-command-line-interface` e uma :ref:`zipapp-python-api`." #: ../../library/zipapp.rst:23 msgid "Basic Example" -msgstr "" +msgstr "Exemplo básico" #: ../../library/zipapp.rst:25 msgid "" @@ -53,6 +54,20 @@ msgid "" "code. When run, the archive will execute the ``main`` function from the " "module ``myapp`` in the archive." msgstr "" +"O exemplo a seguir mostra como a :ref:`zipapp-command-line-interface` pode " +"ser usada para criar um arquivo executável a partir de um diretório contendo " +"código Python. Quando executado, o arquivo executará a função ``main`` do " +"módulo ``myapp`` no arquivo." + +#: ../../library/zipapp.rst:30 +msgid "" +"$ python -m zipapp myapp -m \"myapp:main\"\n" +"$ python myapp.pyz\n" +"" +msgstr "" +"$ python -m zipapp myapp -m \"myapp:main\"\n" +"$ python myapp.pyz\n" +"" #: ../../library/zipapp.rst:40 msgid "Command-Line Interface" @@ -62,6 +77,12 @@ msgstr "Interface de Linha de Comando" msgid "" "When called as a program from the command line, the following form is used:" msgstr "" +"Quando chamado como um programa a partir da linha de comando, as seguintes " +"opções estão disponíveis:" + +#: ../../library/zipapp.rst:44 +msgid "$ python -m zipapp source [options]" +msgstr "$ python -m zipapp source [options]" #: ../../library/zipapp.rst:48 msgid "" @@ -70,10 +91,14 @@ msgid "" "copied to the target archive (or the contents of its shebang line will be " "displayed if the --info option is specified)." msgstr "" +"Se *source* for um diretório, isso criará um arquivo a partir do conteúdo de " +"*source*. Se *source* for um arquivo, ele deve ser um arquivo, e será " +"copiado para o arquivo de destino (ou o conteúdo de sua linha shebang será " +"exibido se a opção --info for especificada)." #: ../../library/zipapp.rst:53 msgid "The following options are understood:" -msgstr "" +msgstr "As seguintes opções são compreendidas:" #: ../../library/zipapp.rst:59 msgid "" @@ -82,12 +107,19 @@ msgid "" "extension ``.pyz`` added. If an explicit filename is given, it is used as " "is (so a ``.pyz`` extension should be included if required)." msgstr "" +"Escreve a saída em um arquivo chamado *output*. Se essa opção não for " +"especificada, o nome do arquivo de saída será o mesmo que o *source* de " +"entrada, com a extensão ``.pyz`` adicionada. Se um nome de arquivo explícito " +"for fornecido, ele será usado como está (então uma extensão ``.pyz`` deve " +"ser incluída se necessário)." #: ../../library/zipapp.rst:64 msgid "" "An output filename must be specified if the *source* is an archive (and in " "that case, *output* must not be the same as *source*)." msgstr "" +"Um nome de arquivo de saída deve ser especificado se *source* for um arquivo " +"(e nesse caso, *output* não deve ser o mesmo que *source*)." #: ../../library/zipapp.rst:69 msgid "" @@ -95,6 +127,9 @@ msgid "" "run. Also, on POSIX, make the archive executable. The default is to write " "no ``#!`` line, and not make the file executable." msgstr "" +"Adiciona uma linha ``#!`` ao arquivo especificando *interpreter* como o " +"comando a ser executado. Além disso, no POSIX, torne o arquivo executável. O " +"padrão é não escrever nenhuma linha ``#!`` e não tornar o arquivo executável." #: ../../library/zipapp.rst:75 msgid "" @@ -103,20 +138,26 @@ msgid "" "a package/module in the archive, and \"fn\" is a callable in the given " "module. The ``__main__.py`` file will execute that callable." msgstr "" +"Escreve um arquivo ``__main__.py`` no arquivo que executa *mainfn*. O " +"argumento *mainfn* deve ter o formato \"pkg.mod:fn\", onde \"pkg.mod\" é um " +"pacote/módulo no arquivo, e \"fn\" é um chamável no módulo fornecido. O " +"arquivo ``__main__.py`` executará esse chamável." #: ../../library/zipapp.rst:80 msgid ":option:`--main` cannot be specified when copying an archive." -msgstr "" +msgstr ":option:`--main` não pode ser especificado ao copiar um arquivo." #: ../../library/zipapp.rst:84 msgid "" "Compress files with the deflate method, reducing the size of the output " "file. By default, files are stored uncompressed in the archive." msgstr "" +"Compacta arquivos com o método deflate, reduzindo o tamanho do arquivo de " +"saída. Por padrão, os arquivos são armazenados descompactados no arquivo." #: ../../library/zipapp.rst:87 msgid ":option:`--compress` has no effect when copying an archive." -msgstr "" +msgstr ":option:`--compress` não tem efeito ao copiar um arquivo." #: ../../library/zipapp.rst:93 msgid "" @@ -124,24 +165,29 @@ msgid "" "In this case, any other options are ignored and SOURCE must be an archive, " "not a directory." msgstr "" +"Exibe o interpretador incorporado no arquivo, para fins de diagnóstico. " +"Neste caso, quaisquer outras opções são ignoradas e SOURCE deve ser um " +"arquivo, não um diretório." #: ../../library/zipapp.rst:99 msgid "Print a short usage message and exit." -msgstr "" +msgstr "Exibe uma mensagem curta de uso e sai" #: ../../library/zipapp.rst:105 msgid "Python API" -msgstr "API Python" +msgstr "API do Python" #: ../../library/zipapp.rst:107 msgid "The module defines two convenience functions:" -msgstr "" +msgstr "O módulo define duas funções de conveniência:" #: ../../library/zipapp.rst:112 msgid "" "Create an application archive from *source*. The source can be any of the " "following:" msgstr "" +"Cria um arquivo de aplicação a partir de *source*. A fonte pode ser qualquer " +"um dos seguintes:" #: ../../library/zipapp.rst:115 msgid "" @@ -149,6 +195,9 @@ msgid "" "directory, in which case a new application archive will be created from the " "content of that directory." msgstr "" +"O nome de um diretório, ou um :term:`objeto caminho ou similar` referente a " +"um diretório, caso em que um novo arquivo de aplicação será criado a partir " +"do conteúdo desse diretório." #: ../../library/zipapp.rst:118 msgid "" @@ -157,6 +206,11 @@ msgid "" "target (modifying it to reflect the value given for the *interpreter* " "argument). The file name should include the ``.pyz`` extension, if required." msgstr "" +"O nome de um arquivo de aplicação existente, ou um :term:`objeto caminho ou " +"similar` referindo-se a tal arquivo, em cujo caso o arquivo é copiado para o " +"alvo (modificando-o para refletir o valor dado para o argumento " +"*interpreter*). O nome do arquivo deve incluir a extensão ``.pyz``, se " +"necessário." #: ../../library/zipapp.rst:122 msgid "" @@ -164,23 +218,30 @@ msgid "" "should be an application archive, and the file object is assumed to be " "positioned at the start of the archive." msgstr "" +"Um objeto arquivo aberto para leitura no modo bytes. O conteúdo do arquivo " +"deve ser um arquivo de aplicação, e o objeto arquivo é presumido como " +"estando posicionado no início do arquivo." #: ../../library/zipapp.rst:126 msgid "" "The *target* argument determines where the resulting archive will be written:" -msgstr "" +msgstr "O argumento *target* determina onde o arquivo resultante será escrito:" #: ../../library/zipapp.rst:129 msgid "" "If it is the name of a file, or a :term:`path-like object`, the archive will " "be written to that file." msgstr "" +"Se for o nome de um arquivo ou um :term:`objeto caminho ou similar`, o " +"arquivo será escrito nesse arquivo." #: ../../library/zipapp.rst:131 msgid "" "If it is an open file object, the archive will be written to that file " "object, which must be open for writing in bytes mode." msgstr "" +"Se for um objeto arquivo aberto, o arquivo será escrito naquele objeto " +"arquivo, que deve estar aberto para escrita no modo bytes." #: ../../library/zipapp.rst:133 msgid "" @@ -188,6 +249,9 @@ msgid "" "the target will be a file with the same name as the source, with a ``.pyz`` " "extension added." msgstr "" +"Se o destino for omitido (ou ``Nenhum``), a fonte deverá ser um diretório e " +"o destino será um arquivo com o mesmo nome da fonte, com uma extensão ``." +"pyz`` adicionada." #: ../../library/zipapp.rst:137 msgid "" @@ -199,6 +263,13 @@ msgid "" "is specified, and the target is a filename, the executable bit of the target " "file will be set." msgstr "" +"O argumento *interpreter* especifica o nome do interpretador Python com o " +"qual o arquivo será executado. Ele é escrito como uma linha \"shebang\" no " +"início do arquivo. No POSIX, isso será interpretado pelo sistema " +"operacional, e no Windows será manipulado pelo inicializador Python. Omitir " +"o *interpreter* resulta em nenhuma linha shebang sendo escrita. Se um " +"interpretador for especificado, e o alvo for um nome de arquivo, o bit " +"executável do arquivo alvo será definido." #: ../../library/zipapp.rst:145 msgid "" @@ -211,6 +282,14 @@ msgid "" "a directory and does not contain a ``__main__.py`` file, as otherwise the " "resulting archive would not be executable." msgstr "" +"O argumento *main* especifica o nome de um chamável que será usado como o " +"programa principal para o arquivo. Ele só pode ser especificado se a fonte " +"for um diretório, e a fonte ainda não contiver um arquivo ``__main__.py``. O " +"argumento *main* deve ter o formato \"pkg.módulo:chamável\" e o arquivo será " +"executado importando \"pkg.módulo\" e executando o chamável fornecido sem " +"argumentos. É um erro omitir *main* se a fonte for um diretório e não " +"contiver um arquivo ``__main__.py``, pois, caso contrário, o arquivo " +"resultante não seria executável." #: ../../library/zipapp.rst:155 msgid "" @@ -218,6 +297,10 @@ msgid "" "a Path object representing the path to the file being added (relative to the " "source directory). It should return ``True`` if the file is to be added." msgstr "" +"O argumento opcional *filter* especifica uma função de retorno de chamada " +"que recebe um objeto Path representando o caminho para o arquivo que está " +"sendo adicionado (relativo ao diretório da fonte). Ele deve retornar " +"``True`` se o arquivo for adicionado." #: ../../library/zipapp.rst:160 msgid "" @@ -226,12 +309,18 @@ msgid "" "method; otherwise, files are stored uncompressed. This argument has no " "effect when copying an existing archive." msgstr "" +"O argumento opcional *compressed* determina se os arquivos são compactados. " +"Se definido como ``True``, os arquivos no arquivo são compactados com o " +"método deflate; caso contrário, os arquivos são armazenados descompactados. " +"Este argumento não tem efeito ao copiar um arquivo existente." #: ../../library/zipapp.rst:165 msgid "" "If a file object is specified for *source* or *target*, it is the caller's " "responsibility to close it after calling create_archive." msgstr "" +"Se um objeto arquivo for especificado para *source* ou *target*, é " +"responsabilidade do chamador fechá-lo após chamar create_archive." #: ../../library/zipapp.rst:168 msgid "" @@ -240,10 +329,15 @@ msgid "" "directory, if the target is a file object it will be passed to the ``zipfile." "ZipFile`` class, and must supply the methods needed by that class." msgstr "" +"Ao copiar um arquivo existente, os objetos arquivo fornecidos precisam " +"apenas dos métodos ``read`` e ``readline`` ou ``write``. Ao criar um arquivo " +"de um diretório, se o alvo for um objeto arquivo, ele será passado para a " +"classe ``zipfile.ZipFile`` e deve fornecer os métodos necessários para essa " +"classe." #: ../../library/zipapp.rst:174 msgid "Added the *filter* and *compressed* parameters." -msgstr "" +msgstr "Adicionados os parâmetros *filter* e *compressed*." #: ../../library/zipapp.rst:179 msgid "" @@ -252,6 +346,10 @@ msgid "" "argument can be a filename or a file-like object open for reading in bytes " "mode. It is assumed to be at the start of the archive." msgstr "" +"Retorna o interpretador especificado na linha ``#!`` no início do arquivo. " +"Se não houver nenhuma linha ``#!``, retorna :const:`None`. O argumento " +"*archive* pode ser um nome de arquivo ou um objeto arquivo ou similar aberto " +"para leitura no modo bytes. É presumido esteja no início do arquivo." #: ../../library/zipapp.rst:188 msgid "Examples" @@ -259,23 +357,65 @@ msgstr "Exemplos" #: ../../library/zipapp.rst:190 msgid "Pack up a directory into an archive, and run it." +msgstr "Compacte um diretório em um arquivo e execute-o." + +#: ../../library/zipapp.rst:192 +msgid "" +"$ python -m zipapp myapp\n" +"$ python myapp.pyz\n" +"" msgstr "" +"$ python -m zipapp myapp\n" +"$ python myapp.pyz\n" +"" #: ../../library/zipapp.rst:198 msgid "The same can be done using the :func:`create_archive` function::" +msgstr "O mesmo pode ser feito usando a função :func:`create_archive`::" + +#: ../../library/zipapp.rst:200 +msgid "" +">>> import zipapp\n" +">>> zipapp.create_archive('myapp', 'myapp.pyz')" msgstr "" +">>> import zipapp\n" +">>> zipapp.create_archive('myapp', 'myapp.pyz')" #: ../../library/zipapp.rst:203 msgid "" "To make the application directly executable on POSIX, specify an interpreter " "to use." msgstr "" +"Para tornar o aplicativo diretamente executável no POSIX, especifique um " +"interpretador a ser usado." + +#: ../../library/zipapp.rst:206 +msgid "" +"$ python -m zipapp myapp -p \"/usr/bin/env python\"\n" +"$ ./myapp.pyz\n" +"" +msgstr "" +"$ python -m zipapp myapp -p \"/usr/bin/env python\"\n" +"$ ./myapp.pyz\n" +"" #: ../../library/zipapp.rst:212 msgid "" "To replace the shebang line on an existing archive, create a modified " "archive using the :func:`create_archive` function::" msgstr "" +"Para substituir a linha shebang em um arquivo existente, crie um arquivo " +"modificado usando a função :func:`create_archive`::" + +#: ../../library/zipapp.rst:215 +msgid "" +">>> import zipapp\n" +">>> zipapp.create_archive('old_archive.pyz', 'new_archive.pyz', '/usr/bin/" +"python3')" +msgstr "" +">>> import zipapp\n" +">>> zipapp.create_archive('old_archive.pyz', 'new_archive.pyz', '/usr/bin/" +"python3')" #: ../../library/zipapp.rst:218 msgid "" @@ -286,6 +426,28 @@ msgid "" "errors, but production code should do so. Also, this method will only work " "if the archive fits in memory::" msgstr "" +"Para atualizar o arquivo no local, faça a substituição na memória usando um " +"objeto :class:`~io.BytesIO` e, em seguida, sobrescreva a fonte depois. " +"Observe que há um risco ao sobrescrever um arquivo no local de que um erro " +"resultará na perda do arquivo original. Este código não protege contra tais " +"erros, mas o código de produção deve fazê-lo. Além disso, este método só " +"funcionará se o arquivo couber na memória::" + +#: ../../library/zipapp.rst:225 +msgid "" +">>> import zipapp\n" +">>> import io\n" +">>> temp = io.BytesIO()\n" +">>> zipapp.create_archive('myapp.pyz', temp, '/usr/bin/python2')\n" +">>> with open('myapp.pyz', 'wb') as f:\n" +">>> f.write(temp.getvalue())" +msgstr "" +">>> import zipapp\n" +">>> import io\n" +">>> temp = io.BytesIO()\n" +">>> zipapp.create_archive('myapp.pyz', temp, '/usr/bin/python2')\n" +">>> with open('myapp.pyz', 'wb') as f:\n" +">>> f.write(temp.getvalue())" #: ../../library/zipapp.rst:236 msgid "Specifying the Interpreter" @@ -298,6 +460,10 @@ msgid "" "Python launcher for Windows supports most common forms of POSIX ``#!`` line, " "but there are other issues to consider:" msgstr "" +"Observe que se você especificar um interpretador e então distribuir seu " +"arquivo de aplicação, você precisa garantir que o interpretador usado seja " +"portátil. O inicializador Python para Windows oferece suporte às formas mais " +"comuns da linha POSIX ``#!``, mas há outras questões a serem consideradas:" #: ../../library/zipapp.rst:243 msgid "" @@ -306,6 +472,10 @@ msgid "" "may have either Python 2 or Python 3 as their default, and write your code " "to work under both versions." msgstr "" +"Se você usar \"/usr/bin/env python\" (ou outras formas do comando " +"\"python\", como \"/usr/bin/python\"), você precisa considerar que seus " +"usuários podem ter Python 2 ou Python 3 como padrão, e escrever seu código " +"para funcionar em ambas as versões." #: ../../library/zipapp.rst:247 msgid "" @@ -313,6 +483,10 @@ msgid "" "application will not work for users who do not have that version. (This may " "be what you want if you have not made your code Python 2 compatible)." msgstr "" +"Se você usar uma versão explícita, por exemplo \"/usr/bin/env python3\", sua " +"aplicação não funcionará para usuários que não tenham essa versão. (Isso " +"pode ser o que você quer se não tiver tornado seu código compatível com " +"Python 2)." #: ../../library/zipapp.rst:250 msgid "" @@ -320,16 +494,21 @@ msgid "" "exact version like \"/usr/bin/env python3.4\" as you will need to change " "your shebang line for users of Python 3.5, for example." msgstr "" +"Não há como dizer \"python X.Y ou posterior\", então tome cuidado ao usar " +"uma versão exata como \"/usr/bin/env python3.4\", pois você precisará " +"alterar sua linha shebang para usuários do Python 3.5, por exemplo." #: ../../library/zipapp.rst:254 msgid "" "Typically, you should use an \"/usr/bin/env python2\" or \"/usr/bin/env " "python3\", depending on whether your code is written for Python 2 or 3." msgstr "" +"Normalmente, você deve usar \"/usr/bin/env python2\" ou \"/usr/bin/env " +"python3\", dependendo se seu código foi escrito para Python 2 ou 3." #: ../../library/zipapp.rst:259 msgid "Creating Standalone Applications with zipapp" -msgstr "" +msgstr "Criando aplicações autônomas com zipapp" #: ../../library/zipapp.rst:261 msgid "" @@ -339,10 +518,15 @@ msgid "" "this is to bundle all of the application's dependencies into the archive, " "along with the application code." msgstr "" +"Usando o módulo :mod:`zipapp`, é possível criar programas Python " +"autocontidos, que podem ser distribuídos para usuários finais que precisam " +"apenas ter uma versão adequada do Python instalada em seu sistema. A chave " +"para fazer isso é agrupar todas as dependências da aplicação no arquivo, " +"junto com o código da aplicação." #: ../../library/zipapp.rst:267 msgid "The steps to create a standalone archive are as follows:" -msgstr "" +msgstr "As etapas para criar um arquivo autônomo são as seguintes:" #: ../../library/zipapp.rst:269 msgid "" @@ -350,12 +534,21 @@ msgid "" "directory containing a ``__main__.py`` file, and any supporting application " "code." msgstr "" +"Crie sua aplicação em um diretório normalmente, para que você tenha um " +"diretório ``myapp`` contendo um arquivo ``__main__.py`` e qualquer código de " +"aplicação de suporte." #: ../../library/zipapp.rst:273 msgid "" "Install all of your application's dependencies into the ``myapp`` directory, " "using pip:" msgstr "" +"Instale todas as dependências da sua aplicação no diretório ``myapp``, " +"usando pip:" + +#: ../../library/zipapp.rst:276 +msgid "$ python -m pip install -r requirements.txt --target myapp" +msgstr "$ python -m pip install -r requirements.txt --target myapp" #: ../../library/zipapp.rst:280 msgid "" @@ -363,17 +556,28 @@ msgid "" "file - if not, you can just list the dependencies manually on the pip " "command line)." msgstr "" +"(isso presume que você tenha os requisitos do seu projeto em um arquivo " +"``requirements.txt`` - caso contrário, você pode simplesmente listar as " +"dependências manualmente na linha de comando do pip)." #: ../../library/zipapp.rst:284 msgid "Package the application using:" msgstr "Empacote a aplicação usando:" +#: ../../library/zipapp.rst:286 +msgid "$ python -m zipapp -p \"interpreter\" myapp" +msgstr "$ python -m zipapp -p \"interpreter\" myapp" + #: ../../library/zipapp.rst:290 msgid "" "This will produce a standalone executable, which can be run on any machine " "with the appropriate interpreter available. See :ref:`zipapp-specifying-the-" "interpreter` for details. It can be shipped to users as a single file." msgstr "" +"Isso produzirá um executável autônomo, que pode ser executado em qualquer " +"máquina com o interpretador apropriado disponível. Veja :ref:`zipapp-" +"specifying-the-interpreter` para detalhes. Ele pode ser enviado aos usuários " +"como um único arquivo." #: ../../library/zipapp.rst:294 msgid "" @@ -383,10 +587,15 @@ msgid "" "fact that the Python interpreter registers the ``.pyz`` and ``.pyzw`` file " "extensions when installed." msgstr "" +"No Unix, o arquivo ``myapp.pyz`` é executável como está. Você pode renomear " +"o arquivo para remover a extensão ``.pyz`` se preferir um nome de comando " +"\"simples\". No Windows, o arquivo ``myapp.pyz[w]`` é executável em virtude " +"do fato de que o interpretador Python registra as extensões de arquivo ``." +"pyz`` e ``.pyzw`` quando instalado." #: ../../library/zipapp.rst:302 msgid "Caveats" -msgstr "" +msgstr "Advertência" #: ../../library/zipapp.rst:304 msgid "" @@ -401,10 +610,21 @@ msgid "" "(and potentially pick the correct version to add to ``sys.path`` at runtime, " "based on the user's machine)." msgstr "" +"Se sua aplicação depende de um pacote que inclui uma extensão C, esse pacote " +"não pode ser executado a partir de um arquivo zip (essa é uma limitação do " +"sistema operacional, pois o código executável deve estar presente no sistema " +"de arquivos para que o carregador do sistema operacional o carregue). Nesse " +"caso, você pode excluir essa dependência do arquivo zip e exigir que seus " +"usuários o tenham instalado ou enviá-lo junto com seu arquivo zip e " +"adicionar código ao seu ``__main__.py`` para incluir o diretório que contém " +"o módulo descompactado em ``sys.path``. Nesse caso, você precisará " +"certificar-se de enviar binários apropriados para sua(s) arquitetura(s) de " +"destino (e potencialmente escolher a versão correta para adicionar ao ``sys." +"path`` no tempo de execução, com base na máquina do usuário)." #: ../../library/zipapp.rst:316 msgid "The Python Zip Application Archive Format" -msgstr "" +msgstr "O formato de arquivo da aplicação zip Python" #: ../../library/zipapp.rst:318 msgid "" @@ -416,6 +636,13 @@ msgid "" "be placed on :data:`sys.path` and thus further modules can be imported from " "the zip file." msgstr "" +"O Python tem sido capaz de executar arquivos zip que contêm um arquivo " +"``__main__.py`` desde a versão 2.6. Para ser executado pelo Python, um " +"arquivo de aplicação simplesmente tem que ser um arquivo zip padrão contendo " +"um arquivo ``__main__.py`` que será executado como o ponto de entrada para o " +"aplicativo. Como de costume para qualquer script Python, o pai do script " +"(neste caso, o arquivo zip) será colocado em :data:`sys.path` e, portanto, " +"outros módulos podem ser importados do arquivo zip." #: ../../library/zipapp.rst:325 msgid "" @@ -423,10 +650,14 @@ msgid "" "The zip application format uses this ability to prepend a standard POSIX " "\"shebang\" line to the file (``#!/path/to/interpreter``)." msgstr "" +"O formato de arquivo zip permite que dados arbitrários sejam prefixados a um " +"arquivo zip. O formato de aplicação zip usa essa habilidade para prefixar " +"uma linha \"shebang\" padrão POSIX ao arquivo (``#!/caminho/para/" +"interpretador``)." #: ../../library/zipapp.rst:329 msgid "Formally, the Python zip application format is therefore:" -msgstr "" +msgstr "Formalmente, o formato de aplicação zip Python é:" #: ../../library/zipapp.rst:331 msgid "" @@ -434,9 +665,15 @@ msgid "" "interpreter name, and then a newline (``b'\\n'``) character. The " "interpreter name can be anything acceptable to the OS \"shebang\" " "processing, or the Python launcher on Windows. The interpreter should be " -"encoded in UTF-8 on Windows, and in :func:`sys.getfilesystemencoding()` on " +"encoded in UTF-8 on Windows, and in :func:`sys.getfilesystemencoding` on " "POSIX." msgstr "" +"Uma linha shebang opcional, contendo os caracteres ``b'#!'`` seguidos por um " +"nome de interpretador e, em seguida, um caractere de nova linha " +"(``b'\\n'``). O nome do interpretador pode ser qualquer coisa aceitável para " +"o processamento \"shebang\" do sistema operacional ou o inicializador Python " +"no Windows. O interpretador deve ser codificado em UTF-8 no Windows e em :" +"func:`sys.getfilesystemencoding` no POSIX." #: ../../library/zipapp.rst:336 msgid "" @@ -445,12 +682,19 @@ msgid "" "in the \"root\" of the zipfile - i.e., it cannot be in a subdirectory). The " "zipfile data can be compressed or uncompressed." msgstr "" +"Dados padrão do zipfile, conforme gerados pelo módulo :mod:`zipfile`. O " +"conteúdo do zipfile *deve* incluir um arquivo chamado ``__main__.py`` (que " +"deve estar na \"raiz\" do zipfile - ou seja, não pode estar em um " +"subdiretório). Os dados do zipfile podem ser compactados ou descompactados." #: ../../library/zipapp.rst:341 msgid "" "If an application archive has a shebang line, it may have the executable bit " "set on POSIX systems, to allow it to be executed directly." msgstr "" +"Se um arquivo de aplicação tiver uma linha shebang, ele poderá ter o bit " +"executável definido em sistemas POSIX, para permitir que seja executado " +"diretamente." #: ../../library/zipapp.rst:344 msgid "" @@ -458,7 +702,10 @@ msgid "" "application archives - the module is a convenience, but archives in the " "above format created by any means are acceptable to Python." msgstr "" +"Não há exigência de que as ferramentas neste módulo sejam usadas para criar " +"arquivos de aplicações - o módulo é uma conveniência, mas arquivos no " +"formato acima criados por qualquer meio são aceitáveis para Python." #: ../../library/zipapp.rst:11 msgid "Executable Zip Files" -msgstr "" +msgstr "Arquivos zip executáveis" diff --git a/library/zipfile.po b/library/zipfile.po index 0151f1a30..e0485aad0 100644 --- a/library/zipfile.po +++ b/library/zipfile.po @@ -1,33 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Welington Carlos , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Giovana Morais , 2021 -# Christian Janiake , 2021 -# i17obot , 2021 -# Henrique Junqueira, 2022 -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-07 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:18+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-03-14 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -306,7 +298,7 @@ msgstr "" "Quando usado :const:`ZIP_BZIP2` inteiros de ``1`` a ``9`` são aceitos (veja :" "class:`bz2 ` para mais informações)." -#: ../../library/zipfile.rst:187 ../../library/zipfile.rst:760 +#: ../../library/zipfile.rst:187 ../../library/zipfile.rst:768 msgid "" "The *strict_timestamps* argument, when set to ``False``, allows to zip files " "older than 1980-01-01 at the cost of setting the timestamp to 1980-01-01. " @@ -349,6 +341,14 @@ msgstr "" "keyword:`with`. Neste exemplo, *myzip* é fechado ao final da execução da " "instrução :keyword:`!with` -- mesmo que ocorra uma exceção::" +#: ../../library/zipfile.rst:205 +msgid "" +"with ZipFile('spam.zip', 'w') as myzip:\n" +" myzip.write('eggs.txt')" +msgstr "" +"with ZipFile('spam.zip', 'w') as myzip:\n" +" myzip.write('eggs.txt')" + #: ../../library/zipfile.rst:210 msgid "" "*metadata_encoding* is an instance-wide setting for the ZipFile. It is not " @@ -382,7 +382,7 @@ msgstr "Adicionado o uso de :class:`ZipFile` como um gerenciador de contexto." msgid "Added support for :mod:`bzip2 ` and :mod:`lzma` compression." msgstr "Adicionado suporte para compactação :mod:`bzip2 ` e :mod:`lzma`." -#: ../../library/zipfile.rst:227 ../../library/zipfile.rst:673 +#: ../../library/zipfile.rst:227 ../../library/zipfile.rst:681 msgid "ZIP64 extensions are enabled by default." msgstr "Extensões ZIP64 são habilitadas por padrão." @@ -476,6 +476,16 @@ msgstr "" ":meth:`~ZipFile.open` também é um gerenciador de contexto e, portanto, " "suporta a instrução :keyword:`with`::" +#: ../../library/zipfile.rst:288 +msgid "" +"with ZipFile('spam.zip') as myzip:\n" +" with myzip.open('eggs.txt') as myfile:\n" +" print(myfile.read())" +msgstr "" +"with ZipFile('spam.zip') as myzip:\n" +" with myzip.open('eggs.txt') as myfile:\n" +" print(myfile.read())" + #: ../../library/zipfile.rst:292 msgid "" "With *mode* ``'r'`` the file-like object (``ZipExtFile``) is read-only and " @@ -912,22 +922,41 @@ msgstr "" "exemplo, \"dir/arquivo.txt\", \"dir/\" ou \"\". O padrão é a string vazia, " "indicando a raiz." -#: ../../library/zipfile.rst:546 +#: ../../library/zipfile.rst:547 +msgid "" +"The :class:`Path` class does not sanitize filenames within the ZIP archive. " +"Unlike the :meth:`ZipFile.extract` and :meth:`ZipFile.extractall` methods, " +"it is the caller's responsibility to validate or sanitize filenames to " +"prevent path traversal vulnerabilities (e.g., filenames containing \"..\" or " +"absolute paths). When handling untrusted archives, consider resolving " +"filenames using :func:`os.path.abspath` and checking against the target " +"directory with :func:`os.path.commonpath`." +msgstr "" +"A classe :class:`Path` não sanitiza nomes de arquivos dentro do arquivo ZIP. " +"Ao contrário dos métodos :meth:`ZipFile.extract` e :meth:`ZipFile." +"extractall`, é responsabilidade do chamador validar ou sanitizar nomes de " +"arquivos para evitar vulnerabilidades de travessia de caminho (por exemplo, " +"nomes de arquivos contendo \"..\" ou caminhos absolutos). Ao lidar com " +"arquivos não confiáveis, considere resolver nomes de arquivos usando :func:" +"`os.path.abspath` e verificar o diretório de destino com :func:`os.path." +"commonpath`." + +#: ../../library/zipfile.rst:554 msgid "" "Path objects expose the following features of :mod:`pathlib.Path` objects:" msgstr "" "Objetos Path expõem os seguintes recursos de objetos :mod:`pathlib.Path`:" -#: ../../library/zipfile.rst:549 +#: ../../library/zipfile.rst:557 msgid "Path objects are traversable using the ``/`` operator or ``joinpath``." msgstr "" "Objetos Path podem ser percorridos usando o operador ``/`` ou ``joinpath``." -#: ../../library/zipfile.rst:553 +#: ../../library/zipfile.rst:561 msgid "The final path component." msgstr "O componente final do caminho." -#: ../../library/zipfile.rst:557 +#: ../../library/zipfile.rst:565 msgid "" "Invoke :meth:`ZipFile.open` on the current path. Allows opening for read or " "write, text or binary through supported modes: 'r', 'w', 'rb', 'wb'. " @@ -942,14 +971,14 @@ msgstr "" "ignorados caso contrário. ``pwd`` é o parâmetro ``pwd`` para :meth:`ZipFile." "open`." -#: ../../library/zipfile.rst:566 +#: ../../library/zipfile.rst:574 msgid "" "Added support for text and binary modes for open. Default mode is now text." msgstr "" "Adicionado suporte para modos de texto e binários para aberto. O modo padrão " "agora é texto." -#: ../../library/zipfile.rst:570 ../../library/zipfile.rst:631 +#: ../../library/zipfile.rst:578 ../../library/zipfile.rst:639 msgid "" "The ``encoding`` parameter can be supplied as a positional argument without " "causing a :exc:`TypeError`. As it could in 3.9. Code needing to be " @@ -962,28 +991,28 @@ msgstr "" "argumentos de :class:`io.TextIOWrapper`, incluindo ``encoding``, como " "palavras reservadas." -#: ../../library/zipfile.rst:578 +#: ../../library/zipfile.rst:586 msgid "Enumerate the children of the current directory." msgstr "Enumera os filhos do diretório atual." -#: ../../library/zipfile.rst:582 +#: ../../library/zipfile.rst:590 msgid "Return ``True`` if the current context references a directory." msgstr "Retorna ``True`` se o contexto atual fizer referência a um diretório." -#: ../../library/zipfile.rst:586 +#: ../../library/zipfile.rst:594 msgid "Return ``True`` if the current context references a file." msgstr "Retorna ``True`` se o contexto atual fizer referência a um arquivo." -#: ../../library/zipfile.rst:590 +#: ../../library/zipfile.rst:598 msgid "Return ``True`` if the current context references a symbolic link." msgstr "" "Retorna ``True`` se o contexto atual fizer referência a um link simbólico." -#: ../../library/zipfile.rst:594 +#: ../../library/zipfile.rst:602 msgid "Previously, ``is_symlink`` would unconditionally return ``False``." msgstr "Anteriormente, ``is_symlink`` retornava ``False`` incondicionalmente." -#: ../../library/zipfile.rst:599 +#: ../../library/zipfile.rst:607 msgid "" "Return ``True`` if the current context references a file or directory in the " "zip file." @@ -991,7 +1020,7 @@ msgstr "" "Retorna ``True`` se o contexto atual fizer referência a um arquivo ou " "diretório no arquivo zip." -#: ../../library/zipfile.rst:604 +#: ../../library/zipfile.rst:612 msgid "" "The last dot-separated portion of the final component, if any. This is " "commonly called the file extension." @@ -999,28 +1028,28 @@ msgstr "" "A última parte separada por pontos do componente final, se houver. Isso é " "comumente chamado de extensão de arquivo." -#: ../../library/zipfile.rst:607 +#: ../../library/zipfile.rst:615 msgid "Added :data:`Path.suffix` property." msgstr "Adicionada a propriedade :data:`Path.suffix`." -#: ../../library/zipfile.rst:612 +#: ../../library/zipfile.rst:620 msgid "The final path component, without its suffix." msgstr "O componente final do caminho, sem seu sufixo." -#: ../../library/zipfile.rst:614 +#: ../../library/zipfile.rst:622 msgid "Added :data:`Path.stem` property." msgstr "Adicionada a propriedade :data:`Path.stem`." -#: ../../library/zipfile.rst:619 +#: ../../library/zipfile.rst:627 msgid "A list of the path’s suffixes, commonly called file extensions." msgstr "" "Uma lista dos sufixos do caminho, comumente chamados de extensões de arquivo." -#: ../../library/zipfile.rst:621 +#: ../../library/zipfile.rst:629 msgid "Added :data:`Path.suffixes` property." msgstr "Adicionada a propriedade :data:`Path.suffixes`." -#: ../../library/zipfile.rst:626 +#: ../../library/zipfile.rst:634 msgid "" "Read the current file as unicode text. Positional and keyword arguments are " "passed through to :class:`io.TextIOWrapper` (except ``buffer``, which is " @@ -1030,11 +1059,11 @@ msgstr "" "nomeados são passados para :class:`io.TextIOWrapper` (exceto ``buffer``, que " "está implícito no contexto)." -#: ../../library/zipfile.rst:639 +#: ../../library/zipfile.rst:647 msgid "Read the current file as bytes." msgstr "Lê o arquivo atual como bytes." -#: ../../library/zipfile.rst:643 +#: ../../library/zipfile.rst:651 msgid "" "Return a new Path object with each of the *other* arguments joined. The " "following are equivalent::" @@ -1042,7 +1071,17 @@ msgstr "" "Retorna um novo objeto Path com cada um dos *outros* argumentos unidos. Os " "seguintes são equivalentes::" -#: ../../library/zipfile.rst:650 +#: ../../library/zipfile.rst:654 +msgid "" +">>> Path(...).joinpath('child').joinpath('grandchild')\n" +">>> Path(...).joinpath('child', 'grandchild')\n" +">>> Path(...) / 'child' / 'grandchild'" +msgstr "" +">>> Path(...).joinpath('child').joinpath('grandchild')\n" +">>> Path(...).joinpath('child', 'grandchild')\n" +">>> Path(...) / 'child' / 'grandchild'" + +#: ../../library/zipfile.rst:658 msgid "" "Prior to 3.10, ``joinpath`` was undocumented and accepted exactly one " "parameter." @@ -1050,7 +1089,7 @@ msgstr "" "Antes de 3.10, ``joinpath`` não estava documentado e aceitava exatamente um " "parâmetro." -#: ../../library/zipfile.rst:654 +#: ../../library/zipfile.rst:662 msgid "" "The :pypi:`zipp` project provides backports of the latest path object " "functionality to older Pythons. Use ``zipp.Path`` in place of ``zipfile." @@ -1060,11 +1099,11 @@ msgstr "" "objeto caminho para versões mais antigas do Pythons. Use ``zipp.Path`` " "internamente de ``zipfile.Path`` para acesso antecipado às alterações." -#: ../../library/zipfile.rst:662 +#: ../../library/zipfile.rst:670 msgid "PyZipFile Objects" msgstr "Objetos PyZipFile" -#: ../../library/zipfile.rst:664 +#: ../../library/zipfile.rst:672 msgid "" "The :class:`PyZipFile` constructor takes the same parameters as the :class:" "`ZipFile` constructor, and one additional parameter, *optimize*." @@ -1072,17 +1111,17 @@ msgstr "" "O construtor :class:`PyZipFile` usa os mesmos parâmetros que o construtor :" "class:`ZipFile`, e um parâmetro adicional, *otimize*." -#: ../../library/zipfile.rst:670 +#: ../../library/zipfile.rst:678 msgid "Added the *optimize* parameter." msgstr "Adicionado o parâmetro *optimize*." -#: ../../library/zipfile.rst:676 +#: ../../library/zipfile.rst:684 msgid "" "Instances have one method in addition to those of :class:`ZipFile` objects:" msgstr "" "As instâncias têm um método além daqueles dos objetos :class:`ZipFile`:" -#: ../../library/zipfile.rst:680 +#: ../../library/zipfile.rst:688 msgid "" "Search for files :file:`\\*.py` and add the corresponding file to the " "archive." @@ -1090,7 +1129,7 @@ msgstr "" "Pesquisa por arquivos :file:`\\*.py` e adiciona o arquivo correspondente ao " "arquivo." -#: ../../library/zipfile.rst:683 +#: ../../library/zipfile.rst:691 msgid "" "If the *optimize* parameter to :class:`PyZipFile` was not given or ``-1``, " "the corresponding file is a :file:`\\*.pyc` file, compiling if necessary." @@ -1099,7 +1138,7 @@ msgstr "" "``-1``, o arquivo correspondente é um arquivo :file:`\\*.pyc`, compilando se " "necessário." -#: ../../library/zipfile.rst:686 +#: ../../library/zipfile.rst:694 msgid "" "If the *optimize* parameter to :class:`PyZipFile` was ``0``, ``1`` or ``2``, " "only files with that optimization level (see :func:`compile`) are added to " @@ -1109,7 +1148,7 @@ msgstr "" "apenas arquivos com esse nível de otimização (ver :func:`compile`) são " "adicionados ao o arquivo, compilando se necessário." -#: ../../library/zipfile.rst:690 +#: ../../library/zipfile.rst:698 msgid "" "If *pathname* is a file, the filename must end with :file:`.py`, and just " "the (corresponding :file:`\\*.pyc`) file is added at the top level (no path " @@ -1132,11 +1171,11 @@ msgstr "" "diretório de pacotes, todos serão adicionados recursivamente na ordem de " "classificação." -#: ../../library/zipfile.rst:700 +#: ../../library/zipfile.rst:708 msgid "*basename* is intended for internal use only." msgstr "*basename* destina-se apenas a uso interno." -#: ../../library/zipfile.rst:702 +#: ../../library/zipfile.rst:710 msgid "" "*filterfunc*, if given, must be a function taking a single string argument. " "It will be passed each path (including each individual full file path) " @@ -1154,29 +1193,59 @@ msgstr "" "arquivos de teste estão todos nos diretórios ``test`` ou começam com a " "string ``test_``, podemos usar um *filterfunc* para excluí-los::" -#: ../../library/zipfile.rst:717 +#: ../../library/zipfile.rst:718 +msgid "" +">>> zf = PyZipFile('myprog.zip')\n" +">>> def notests(s):\n" +"... fn = os.path.basename(s)\n" +"... return (not (fn == 'test' or fn.startswith('test_')))\n" +"...\n" +">>> zf.writepy('myprog', filterfunc=notests)" +msgstr "" +">>> zf = PyZipFile('myprog.zip')\n" +">>> def notests(s):\n" +"... fn = os.path.basename(s)\n" +"... return (not (fn == 'test' or fn.startswith('test_')))\n" +"...\n" +">>> zf.writepy('myprog', filterfunc=notests)" + +#: ../../library/zipfile.rst:725 msgid "The :meth:`writepy` method makes archives with file names like this::" msgstr "O método :meth:`writepy` faz arquivos com nomes de arquivo como este::" -#: ../../library/zipfile.rst:726 +#: ../../library/zipfile.rst:728 +msgid "" +"string.pyc # Top level name\n" +"test/__init__.pyc # Package directory\n" +"test/testall.pyc # Module test.testall\n" +"test/bogus/__init__.pyc # Subpackage directory\n" +"test/bogus/myfile.pyc # Submodule test.bogus.myfile" +msgstr "" +"string.pyc # Nome de nível superior\n" +"test/__init__.pyc # Diretório do pacote\n" +"test/testall.pyc # Módulo test.testall\n" +"test/bogus/__init__.pyc # Diretório do subpacote\n" +"test/bogus/myfile.pyc # Submódulo test.bogus.myfile" + +#: ../../library/zipfile.rst:734 msgid "Added the *filterfunc* parameter." msgstr "Adicionado o parâmetro *filterfunc*." -#: ../../library/zipfile.rst:729 +#: ../../library/zipfile.rst:737 msgid "The *pathname* parameter accepts a :term:`path-like object`." msgstr "" "O parâmetro *pathname* aceita um :term:`objeto caminho ou similar `." -#: ../../library/zipfile.rst:732 +#: ../../library/zipfile.rst:740 msgid "Recursion sorts directory entries." msgstr "A recursão classifica as entradas de diretório." -#: ../../library/zipfile.rst:739 +#: ../../library/zipfile.rst:747 msgid "ZipInfo Objects" msgstr "Objetos ZipInfo" -#: ../../library/zipfile.rst:741 +#: ../../library/zipfile.rst:749 msgid "" "Instances of the :class:`ZipInfo` class are returned by the :meth:`.getinfo` " "and :meth:`.infolist` methods of :class:`ZipFile` objects. Each object " @@ -1186,7 +1255,7 @@ msgstr "" "getinfo` e :meth:`.infolist` dos objetos :class:`ZipFile`. Cada objeto " "armazena informações sobre um único membro do arquivo ZIP." -#: ../../library/zipfile.rst:745 +#: ../../library/zipfile.rst:753 msgid "" "There is one classmethod to make a :class:`ZipInfo` instance for a " "filesystem file:" @@ -1194,7 +1263,7 @@ msgstr "" "Existe um método de classe para fazer uma instância :class:`ZipInfo` para um " "arquivo de sistema de arquivos:" -#: ../../library/zipfile.rst:751 +#: ../../library/zipfile.rst:759 msgid "" "Construct a :class:`ZipInfo` instance for a file on the filesystem, in " "preparation for adding it to a zip file." @@ -1202,13 +1271,13 @@ msgstr "" "Constrói uma instância :class:`ZipInfo` para um arquivo no sistema de " "arquivos, em preparação para adicioná-lo a um arquivo zip." -#: ../../library/zipfile.rst:754 +#: ../../library/zipfile.rst:762 msgid "*filename* should be the path to a file or directory on the filesystem." msgstr "" "*filename* deve ser o caminho para um arquivo ou diretório no sistema de " "arquivos." -#: ../../library/zipfile.rst:756 +#: ../../library/zipfile.rst:764 msgid "" "If *arcname* is specified, it is used as the name within the archive. If " "*arcname* is not specified, the name will be the same as *filename*, but " @@ -1218,34 +1287,34 @@ msgstr "" "Se *arcname* não for especificado, o nome será igual a *filename*, mas com " "qualquer letra de unidade e separadores de caminho removidos." -#: ../../library/zipfile.rst:768 +#: ../../library/zipfile.rst:776 msgid "The *filename* parameter accepts a :term:`path-like object`." msgstr "" "O parâmetro *filename* aceita um :term:`objeto caminho ou similar `." -#: ../../library/zipfile.rst:771 +#: ../../library/zipfile.rst:779 msgid "Added the *strict_timestamps* keyword-only parameter." msgstr "Adicionado o parâmetro somente-nomeado *strict_timestamps*." -#: ../../library/zipfile.rst:775 +#: ../../library/zipfile.rst:783 msgid "Instances have the following methods and attributes:" msgstr "As instâncias têm os seguintes métodos e atributos:" -#: ../../library/zipfile.rst:779 +#: ../../library/zipfile.rst:787 msgid "Return ``True`` if this archive member is a directory." msgstr "Retorna ``True`` se este membro do arquivo for um diretório." -#: ../../library/zipfile.rst:781 +#: ../../library/zipfile.rst:789 msgid "This uses the entry's name: directories should always end with ``/``." msgstr "" "Isso usa o nome da entrada: os diretórios devem sempre terminar com ``/``." -#: ../../library/zipfile.rst:788 +#: ../../library/zipfile.rst:796 msgid "Name of the file in the archive." msgstr "Nome do arquivo no pacote." -#: ../../library/zipfile.rst:793 +#: ../../library/zipfile.rst:801 msgid "" "The time and date of the last modification to the archive member. This is a " "tuple of six values:" @@ -1253,78 +1322,78 @@ msgstr "" "A hora e a data da última modificação do membro do arquivo. Esta é uma tupla " "de seis valores:" -#: ../../library/zipfile.rst:797 +#: ../../library/zipfile.rst:805 msgid "Index" msgstr "Índice" -#: ../../library/zipfile.rst:797 +#: ../../library/zipfile.rst:805 msgid "Value" msgstr "Valor" -#: ../../library/zipfile.rst:799 +#: ../../library/zipfile.rst:807 msgid "``0``" msgstr "``0``" -#: ../../library/zipfile.rst:799 +#: ../../library/zipfile.rst:807 msgid "Year (>= 1980)" msgstr "Ano (>= 1980)" -#: ../../library/zipfile.rst:801 +#: ../../library/zipfile.rst:809 msgid "``1``" msgstr "``1``" -#: ../../library/zipfile.rst:801 +#: ../../library/zipfile.rst:809 msgid "Month (one-based)" msgstr "Mês (iniciado em 1)" -#: ../../library/zipfile.rst:803 +#: ../../library/zipfile.rst:811 msgid "``2``" msgstr "``2``" -#: ../../library/zipfile.rst:803 +#: ../../library/zipfile.rst:811 msgid "Day of month (one-based)" msgstr "Dia do mês (iniciado em 1)" -#: ../../library/zipfile.rst:805 +#: ../../library/zipfile.rst:813 msgid "``3``" msgstr "``3``" -#: ../../library/zipfile.rst:805 +#: ../../library/zipfile.rst:813 msgid "Hours (zero-based)" msgstr "Horas (iniciado em 0)" -#: ../../library/zipfile.rst:807 +#: ../../library/zipfile.rst:815 msgid "``4``" msgstr "``4``" -#: ../../library/zipfile.rst:807 +#: ../../library/zipfile.rst:815 msgid "Minutes (zero-based)" msgstr "Minutos (base zero)" -#: ../../library/zipfile.rst:809 +#: ../../library/zipfile.rst:817 msgid "``5``" msgstr "``5``" -#: ../../library/zipfile.rst:809 +#: ../../library/zipfile.rst:817 msgid "Seconds (zero-based)" msgstr "Segundos (iniciado em 0)" -#: ../../library/zipfile.rst:814 +#: ../../library/zipfile.rst:822 msgid "The ZIP file format does not support timestamps before 1980." msgstr "" "O formato de arquivo ZIP não oferece suporte a carimbos de data/hora " "anteriores a 1980." -#: ../../library/zipfile.rst:819 +#: ../../library/zipfile.rst:827 msgid "Type of compression for the archive member." msgstr "Tipo de compressão do membro do pacote." -#: ../../library/zipfile.rst:824 +#: ../../library/zipfile.rst:832 msgid "Comment for the individual archive member as a :class:`bytes` object." msgstr "" "Comentário para o membro individual do pacote como um objeto :class:`bytes`." -#: ../../library/zipfile.rst:829 +#: ../../library/zipfile.rst:837 msgid "" "Expansion field data. The `PKZIP Application Note`_ contains some comments " "on the internal structure of the data contained in this :class:`bytes` " @@ -1334,59 +1403,59 @@ msgstr "" "comentários sobre a estrutura interna dos dados contidos neste objeto :class:" "`bytes`." -#: ../../library/zipfile.rst:836 +#: ../../library/zipfile.rst:844 msgid "System which created ZIP archive." msgstr "O sistema que criou o pacote ZIP." -#: ../../library/zipfile.rst:841 +#: ../../library/zipfile.rst:849 msgid "PKZIP version which created ZIP archive." msgstr "A versão do PKZIP que criou o pacote ZIP." -#: ../../library/zipfile.rst:846 +#: ../../library/zipfile.rst:854 msgid "PKZIP version needed to extract archive." msgstr "A versão do PKZIP necessária para extrair o pacote." -#: ../../library/zipfile.rst:851 +#: ../../library/zipfile.rst:859 msgid "Must be zero." msgstr "Deve ser zero" -#: ../../library/zipfile.rst:856 +#: ../../library/zipfile.rst:864 msgid "ZIP flag bits." msgstr "Bits de sinalizador do ZIP." -#: ../../library/zipfile.rst:861 +#: ../../library/zipfile.rst:869 msgid "Volume number of file header." msgstr "Número de volume do cabeçalho do arquivo." -#: ../../library/zipfile.rst:866 +#: ../../library/zipfile.rst:874 msgid "Internal attributes." msgstr "Atributos internos." -#: ../../library/zipfile.rst:871 +#: ../../library/zipfile.rst:879 msgid "External file attributes." msgstr "Atributos de arquivo externo." -#: ../../library/zipfile.rst:876 +#: ../../library/zipfile.rst:884 msgid "Byte offset to the file header." msgstr "Deslocamento de byte para o cabeçalho do arquivo." -#: ../../library/zipfile.rst:881 +#: ../../library/zipfile.rst:889 msgid "CRC-32 of the uncompressed file." msgstr "CRC-32 do arquivo não comprimido." -#: ../../library/zipfile.rst:886 +#: ../../library/zipfile.rst:894 msgid "Size of the compressed data." msgstr "Tamanho dos dados comprimidos." -#: ../../library/zipfile.rst:891 +#: ../../library/zipfile.rst:899 msgid "Size of the uncompressed file." msgstr "Tamanho do arquivo não comprimido." -#: ../../library/zipfile.rst:898 +#: ../../library/zipfile.rst:906 msgid "Command-Line Interface" msgstr "Interface de Linha de Comando" -#: ../../library/zipfile.rst:900 +#: ../../library/zipfile.rst:908 msgid "" "The :mod:`zipfile` module provides a simple command-line interface to " "interact with ZIP archives." @@ -1394,7 +1463,7 @@ msgstr "" "O módulo :mod:`zipfile` fornece uma interface de linha de comando simples " "para interagir com arquivos ZIP." -#: ../../library/zipfile.rst:903 +#: ../../library/zipfile.rst:911 msgid "" "If you want to create a new ZIP archive, specify its name after the :option:" "`-c` option and then list the filename(s) that should be included:" @@ -1403,11 +1472,19 @@ msgstr "" "option:`-c` e, em seguida, liste os nomes dos arquivos que devem ser " "incluídos:" -#: ../../library/zipfile.rst:910 +#: ../../library/zipfile.rst:914 +msgid "$ python -m zipfile -c monty.zip spam.txt eggs.txt" +msgstr "$ python -m zipfile -c monty.zip spam.txt eggs.txt" + +#: ../../library/zipfile.rst:918 msgid "Passing a directory is also acceptable:" msgstr "Passar um diretório também é aceitável:" -#: ../../library/zipfile.rst:916 +#: ../../library/zipfile.rst:920 +msgid "$ python -m zipfile -c monty.zip life-of-brian_1979/" +msgstr "$ python -m zipfile -c monty.zip life-of-brian_1979/" + +#: ../../library/zipfile.rst:924 msgid "" "If you want to extract a ZIP archive into the specified directory, use the :" "option:`-e` option:" @@ -1415,33 +1492,41 @@ msgstr "" "Se você deseja extrair um arquivo ZIP para o diretório especificado, use a " "opção :option:`-e`:" -#: ../../library/zipfile.rst:923 +#: ../../library/zipfile.rst:927 +msgid "$ python -m zipfile -e monty.zip target-dir/" +msgstr "$ python -m zipfile -e monty.zip target-dir/" + +#: ../../library/zipfile.rst:931 msgid "For a list of the files in a ZIP archive, use the :option:`-l` option:" msgstr "" "Para obter uma lista dos arquivos em um arquivo ZIP, use a opção :option:`-" "l`:" -#: ../../library/zipfile.rst:931 +#: ../../library/zipfile.rst:933 +msgid "$ python -m zipfile -l monty.zip" +msgstr "$ python -m zipfile -l monty.zip" + +#: ../../library/zipfile.rst:939 msgid "Command-line options" msgstr "Opções de linha de comando" -#: ../../library/zipfile.rst:936 +#: ../../library/zipfile.rst:944 msgid "List files in a zipfile." msgstr "Lista arquivos em um arquivo zip." -#: ../../library/zipfile.rst:941 +#: ../../library/zipfile.rst:949 msgid "Create zipfile from source files." msgstr "Cria um arquivo zip a partir dos arquivos fonte." -#: ../../library/zipfile.rst:946 +#: ../../library/zipfile.rst:954 msgid "Extract zipfile into target directory." msgstr "Extrai um arquivo zip para um diretório de destino." -#: ../../library/zipfile.rst:951 +#: ../../library/zipfile.rst:959 msgid "Test whether the zipfile is valid or not." msgstr "Testa se o arquivo zip é válido ou não." -#: ../../library/zipfile.rst:955 +#: ../../library/zipfile.rst:963 msgid "" "Specify encoding of member names for :option:`-l`, :option:`-e` and :option:" "`-t`." @@ -1449,11 +1534,11 @@ msgstr "" "Especifica a codificação dos nomes dos membros para :option:`-l`, :option:`-" "e` e :option:`-t`." -#: ../../library/zipfile.rst:962 +#: ../../library/zipfile.rst:970 msgid "Decompression pitfalls" msgstr "Armadilhas de descompressão" -#: ../../library/zipfile.rst:964 +#: ../../library/zipfile.rst:972 msgid "" "The extraction in zipfile module might fail due to some pitfalls listed " "below." @@ -1461,11 +1546,11 @@ msgstr "" "A extração no módulo zipfile pode falhar devido a algumas armadilhas " "listadas abaixo." -#: ../../library/zipfile.rst:967 +#: ../../library/zipfile.rst:975 msgid "From file itself" msgstr "Do próprio arquivo" -#: ../../library/zipfile.rst:969 +#: ../../library/zipfile.rst:977 msgid "" "Decompression may fail due to incorrect password / CRC checksum / ZIP format " "or unsupported compression method / decryption." @@ -1474,11 +1559,11 @@ msgstr "" "formato ZIP incorretos ou método de compactação / descriptografia não " "compatível." -#: ../../library/zipfile.rst:973 +#: ../../library/zipfile.rst:981 msgid "File System limitations" msgstr "Limitações do sistema de arquivos" -#: ../../library/zipfile.rst:975 +#: ../../library/zipfile.rst:983 msgid "" "Exceeding limitations on different file systems can cause decompression " "failed. Such as allowable characters in the directory entries, length of the " @@ -1490,11 +1575,11 @@ msgstr "" "comprimento do nome do arquivo, comprimento do caminho, tamanho de um único " "arquivo e número de arquivos, etc." -#: ../../library/zipfile.rst:982 +#: ../../library/zipfile.rst:990 msgid "Resources limitations" msgstr "Limitações de recursos" -#: ../../library/zipfile.rst:984 +#: ../../library/zipfile.rst:992 msgid "" "The lack of memory or disk volume would lead to decompression failed. For " "example, decompression bombs (aka `ZIP bomb`_) apply to zipfile library that " @@ -1505,11 +1590,11 @@ msgstr "" "aplicam-se à biblioteca de arquivos zip que podem causar o esgotamento do " "volume do disco." -#: ../../library/zipfile.rst:989 +#: ../../library/zipfile.rst:997 msgid "Interruption" msgstr "Interrupção" -#: ../../library/zipfile.rst:991 +#: ../../library/zipfile.rst:999 msgid "" "Interruption during the decompression, such as pressing control-C or killing " "the decompression process may result in incomplete decompression of the " @@ -1519,11 +1604,11 @@ msgstr "" "interromper o processo de descompressão pode resultar na descompressão " "incompleta do arquivo." -#: ../../library/zipfile.rst:995 +#: ../../library/zipfile.rst:1003 msgid "Default behaviors of extraction" msgstr "Comportamentos padrão da extração" -#: ../../library/zipfile.rst:997 +#: ../../library/zipfile.rst:1005 msgid "" "Not knowing the default extraction behaviors can cause unexpected " "decompression results. For example, when extracting the same archive twice, " diff --git a/library/zipimport.po b/library/zipimport.po index ba5515230..78f70da32 100644 --- a/library/zipimport.po +++ b/library/zipimport.po @@ -1,39 +1,35 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Christian Janiake , 2021 -# i17obot , 2021 -# Vinicius Gubiani Ferreira , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:18+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../library/zipimport.rst:2 msgid ":mod:`!zipimport` --- Import modules from Zip archives" -msgstr "" +msgstr ":mod:`!zipimport` - Importa módulos de arquivos Zip" #: ../../library/zipimport.rst:9 msgid "**Source code:** :source:`Lib/zipimport.py`" -msgstr "" +msgstr "**Código-fonte:** :source:`Lib/zipimport.py`" #: ../../library/zipimport.rst:13 msgid "" @@ -43,6 +39,11 @@ msgid "" "the built-in :keyword:`import` mechanism for :data:`sys.path` items that are " "paths to ZIP archives." msgstr "" +"Este módulo adiciona a capacidade de importar módulos Python (:file:`\\*." +"py`, :file:`\\*.pyc`) e pacotes de arquivos em formato ZIP. Normalmente, não " +"é necessário usar o módulo :mod:`zipimport` explicitamente; ele é usado " +"automaticamente pelo mecanismo embutido no :keyword:`import` para itens :" +"data:`sys.path` que são caminhos para arquivos ZIP." #: ../../library/zipimport.rst:19 msgid "" @@ -54,6 +55,13 @@ msgid "" "lib/` would only import from the :file:`lib/` subdirectory within the " "archive." msgstr "" +"Normalmente, :data:`sys.path` é uma lista de nomes de diretórios como " +"strings. Este módulo também permite que um item de :data:`sys.path` seja uma " +"string que nomeia um arquivo ZIP. O arquivo ZIP pode conter uma estrutura de " +"subdiretório para suportar importações de pacotes, e um caminho dentro do " +"arquivo pode ser especificado para importar apenas de um subdiretório. Por " +"exemplo, o caminho :file:`example.zip/lib/` importaria apenas do " +"subdiretório :file:`lib/` dentro do arquivo." #: ../../library/zipimport.rst:26 msgid "" @@ -64,20 +72,31 @@ msgid "" "adding the corresponding :file:`.pyc` file, meaning that if a ZIP archive " "doesn't contain :file:`.pyc` files, importing may be rather slow." msgstr "" +"Quaisquer arquivos podem estar presentes no arquivo ZIP, mas os importadores " +"são invocados apenas para os arquivos :file:`.py` e :file:`.pyc`. A " +"importação ZIP de módulos dinâmicos (:file:`.pyd`, :file:`.so`) não é " +"permitida. Observe que, se um arquivo contiver apenas arquivos :file:`.py`, " +"o Python não tentará modificá-lo adicionando o arquivo :file:`.pyc` " +"correspondente, o que significa que, se um arquivo ZIP não contiver " +"arquivos :file:`.pyc`, a importação poderá ser bastante lenta." #: ../../library/zipimport.rst:33 msgid "ZIP64 is supported" -msgstr "" +msgstr "Suporte para ZIP64." #: ../../library/zipimport.rst:36 msgid "Previously, ZIP archives with an archive comment were not supported." msgstr "" +"Anteriormente, não havia suporte para arquivos ZIP com um comentário de " +"arquivo." #: ../../library/zipimport.rst:41 msgid "" "`PKZIP Application Note `_" msgstr "" +"`Nota da aplicação PKZIP `_" #: ../../library/zipimport.rst:42 msgid "" @@ -89,7 +108,7 @@ msgstr "" #: ../../library/zipimport.rst:45 msgid ":pep:`273` - Import Modules from Zip Archives" -msgstr ":pep:`273` - Importar módulos de arquivos Zip" +msgstr ":pep:`273` - Import Modules from Zip Archives" #: ../../library/zipimport.rst:46 msgid "" @@ -98,33 +117,41 @@ msgid "" "written by Just van Rossum that uses the import hooks described in :pep:" "`302`." msgstr "" +"Escrito por James C. Ahlstrom, que também forneceu uma implementação. O " +"Python 2.3 segue a especificação em :pep:`273`, mas usa uma implementação " +"escrita por Just van Rossum que utiliza os ganchos de importação descritos " +"em :pep:`302`." #: ../../library/zipimport.rst:50 msgid ":mod:`importlib` - The implementation of the import machinery" -msgstr "" +msgstr ":mod:`importlib` - A importação do maquinário de importação" #: ../../library/zipimport.rst:51 msgid "" "Package providing the relevant protocols for all importers to implement." msgstr "" +"Pacote que fornece os protocolos relevantes para todos os importadores " +"implementarem." #: ../../library/zipimport.rst:55 msgid "This module defines an exception:" -msgstr "" +msgstr "Este módulo define uma exceção:" #: ../../library/zipimport.rst:59 msgid "" "Exception raised by zipimporter objects. It's a subclass of :exc:" "`ImportError`, so it can be caught as :exc:`ImportError`, too." msgstr "" +"Exceção levantada por objetos zipimporter. É uma subclasse de :exc:" +"`ImportError`, portanto, também pode ser capturada como :exc:`ImportError`." #: ../../library/zipimport.rst:66 msgid "zipimporter Objects" -msgstr "" +msgstr "Objetos zipimporter" #: ../../library/zipimport.rst:68 msgid ":class:`zipimporter` is the class for importing ZIP files." -msgstr "" +msgstr ":class:`zipimporter` é a classe para importar arquivos ZIP." #: ../../library/zipimport.rst:72 msgid "" @@ -134,49 +161,64 @@ msgid "" "`lib` directory inside the ZIP file :file:`foo/bar.zip` (provided that it " "exists)." msgstr "" +"Cria uma nova instância de zipimporter. *archivepath* deve ser um caminho " +"para um arquivo ZIP ou para um caminho específico dentro de um arquivo ZIP. " +"Por exemplo, um *archivepath* de :file:`foo/bar.zip/lib` procurará módulos " +"no diretório :file:`lib` dentro do arquivo ZIP :file:`foo/bar.zip` (desde " +"que exista)." #: ../../library/zipimport.rst:77 msgid "" ":exc:`ZipImportError` is raised if *archivepath* doesn't point to a valid " "ZIP archive." msgstr "" +":exc:`ZipImportError` é levantada se *archivepath* não apontar para um " +"arquivo ZIP válido." #: ../../library/zipimport.rst:82 msgid "" "Methods ``find_loader()`` and ``find_module()``, deprecated in 3.10 are now " "removed. Use :meth:`find_spec` instead." msgstr "" +"Os métodos ``find_loader()`` e ``find_module()``, descontinuados na versão " +"3.10, foram removidos. Em vez disso, use :meth:`find_spec`." #: ../../library/zipimport.rst:87 msgid "" "Implementation of :meth:`importlib.abc.Loader.create_module` that returns :" "const:`None` to explicitly request the default semantics." msgstr "" +"Implementação de :meth:`importlib.abc.Loader.create_module` que retorna :" +"const:`None` para solicitar explicitamente a semântica padrão." #: ../../library/zipimport.rst:95 msgid "Implementation of :meth:`importlib.abc.Loader.exec_module`." -msgstr "" +msgstr "Implementação de :meth:`importlib.abc.Loader.exec_module`." #: ../../library/zipimport.rst:102 msgid "An implementation of :meth:`importlib.abc.PathEntryFinder.find_spec`." -msgstr "" +msgstr "Uma implementação de :meth:`importlib.abc.PathEntryFinder.find_spec`." #: ../../library/zipimport.rst:109 msgid "" "Return the code object for the specified module. Raise :exc:`ZipImportError` " "if the module couldn't be imported." msgstr "" +"Retorna o objeto código para o módulo especificado. Levanta :exc:" +"`ZipImportError` se o módulo não puder ser importado." #: ../../library/zipimport.rst:115 msgid "" "Return the data associated with *pathname*. Raise :exc:`OSError` if the file " "wasn't found." msgstr "" +"Retorna os dados associados a *pathname*. Levanta :exc:`OSError` se o " +"arquivo não for encontrado." #: ../../library/zipimport.rst:118 msgid ":exc:`IOError` used to be raised, it is now an alias of :exc:`OSError`." msgstr "" -":exc:`IOError` costumava ser levantado, agora ele é um codinome para :exc:" +":exc:`IOError` costumava ser levantada, agora ela é um apelido para :exc:" "`OSError`." #: ../../library/zipimport.rst:124 @@ -184,6 +226,9 @@ msgid "" "Return the value ``__file__`` would be set to if the specified module was " "imported. Raise :exc:`ZipImportError` if the module couldn't be imported." msgstr "" +"Retorna o valor que ``__file__`` seria definido se o módulo especificado " +"fosse importado. Levanta :exc:`ZipImportError` se o módulo não puder ser " +"importado." #: ../../library/zipimport.rst:133 msgid "" @@ -191,13 +236,16 @@ msgid "" "if the module couldn't be found, return :const:`None` if the archive does " "contain the module, but has no source for it." msgstr "" +"Retorna o código-fonte do módulo especificado. Levanta :exc:`ZipImportError` " +"se o módulo não puder ser encontrado, e retorna :const:`None` se o arquivo " +"contiver o módulo, mas não tiver o código-fonte para ele." #: ../../library/zipimport.rst:141 msgid "" "Return ``True`` if the module specified by *fullname* is a package. Raise :" "exc:`ZipImportError` if the module couldn't be found." msgstr "" -"Devolve ``True`` se o módulo especificado por *fullname* é um pacote. " +"Retorna ``True`` se o módulo especificado por *fullname* é um pacote. " "Levanta :exc:`ZipImportError` se o módulo não pode ser localizado." #: ../../library/zipimport.rst:147 @@ -206,6 +254,9 @@ msgid "" "qualified (dotted) module name. Returns the imported module on success, " "raises :exc:`ZipImportError` on failure." msgstr "" +"Carrega o módulo especificado por *fullname*. *fullname* deve ser o nome " +"completo (com pontos) do módulo. Retorna o módulo importado em caso de " +"sucesso e levanta :exc:`ZipImportError` em caso de falha." #: ../../library/zipimport.rst:153 msgid "Use :meth:`exec_module` instead." @@ -216,18 +267,23 @@ msgid "" "Clear out the internal cache of information about files found within the ZIP " "archive." msgstr "" +"Limpa o cache interno de informações sobre arquivos encontrados no arquivo " +"ZIP." #: ../../library/zipimport.rst:166 msgid "" "The file name of the importer's associated ZIP file, without a possible " "subpath." msgstr "" +"O nome do arquivo ZIP associado ao importador, sem um possível subcaminho." #: ../../library/zipimport.rst:172 msgid "" "The subpath within the ZIP file where modules are searched. This is the " "empty string for zipimporter objects which point to the root of the ZIP file." msgstr "" +"O subcaminho dentro do arquivo ZIP onde os módulos são pesquisados. Esta é a " +"string vazia para objetos zipimporter que apontam para a raiz do arquivo ZIP." #: ../../library/zipimport.rst:176 msgid "" @@ -235,6 +291,9 @@ msgid "" "slash, equal the original *archivepath* argument given to the :class:" "`zipimporter` constructor." msgstr "" +"Os atributos :attr:`archive` e :attr:`prefix`, quando combinados com uma " +"barra, são iguais ao argumento original *archivepath* fornecido ao " +"construtor da :class:`zipimporter`." #: ../../library/zipimport.rst:184 msgid "Examples" @@ -245,3 +304,38 @@ msgid "" "Here is an example that imports a module from a ZIP archive - note that the :" "mod:`zipimport` module is not explicitly used." msgstr "" +"Aqui está um exemplo que importa um módulo de um arquivo ZIP - observe que o " +"módulo :mod:`zipimport` não é usado explicitamente." + +#: ../../library/zipimport.rst:189 +msgid "" +"$ unzip -l example.zip\n" +"Archive: example.zip\n" +" Length Date Time Name\n" +" -------- ---- ---- ----\n" +" 8467 11-26-02 22:30 jwzthreading.py\n" +" -------- -------\n" +" 8467 1 file\n" +"$ ./python\n" +"Python 2.3 (#1, Aug 1 2003, 19:54:32)\n" +">>> import sys\n" +">>> sys.path.insert(0, 'example.zip') # Add .zip file to front of path\n" +">>> import jwzthreading\n" +">>> jwzthreading.__file__\n" +"'example.zip/jwzthreading.py'" +msgstr "" +"$ unzip -l example.zip\n" +"Archive: example.zip\n" +" Length Date Time Name\n" +" -------- ---- ---- ----\n" +" 8467 11-26-02 22:30 jwzthreading.py\n" +" -------- -------\n" +" 8467 1 file\n" +"$ ./python\n" +"Python 2.3 (#1, Aug 1 2003, 19:54:32)\n" +">>> import sys\n" +">>> sys.path.insert(0, 'example.zip') # Adiciona arquivo .zip para a frente " +"do caminho\n" +">>> import jwzthreading\n" +">>> jwzthreading.__file__\n" +"'example.zip/jwzthreading.py'" diff --git a/library/zlib.po b/library/zlib.po index 600d9dba2..07b216698 100644 --- a/library/zlib.po +++ b/library/zlib.po @@ -1,29 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# i17obot , 2021 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 -# Leandro Cavalcante Damascena , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:18+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-04-25 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -653,6 +649,14 @@ msgstr "" "O manual da zlib explica a semântica e uso de diversas funções desta " "biblioteca." +#: ../../library/zlib.rst:345 +msgid "" +"In case gzip (de)compression is a bottleneck, the `python-isal`_ package " +"speeds up (de)compression with a mostly compatible API." +msgstr "" +"Caso a (des)compressão do gzip seja um gargalo, o pacote `python-isal`_ " +"acelera a (des)compressão com uma API quase sempre compatível." + #: ../../library/zlib.rst:123 msgid "Cyclic Redundancy Check" msgstr "Do inglês: Cyclic Redundancy Check" diff --git a/library/zoneinfo.po b/library/zoneinfo.po index df421f93b..d86c86daa 100644 --- a/library/zoneinfo.po +++ b/library/zoneinfo.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:19+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -63,8 +61,8 @@ msgid "" msgstr "" #: ../../includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not WASI." -msgstr ":ref:`Disponibilidade `: não WASI." +msgid "Availability" +msgstr "Disponibilidade" #: ../../includes/wasm-notavail.rst:5 msgid "" @@ -87,12 +85,37 @@ msgid "" "astimezone>`::" msgstr "" +#: ../../library/zoneinfo.rst:42 +msgid "" +">>> from zoneinfo import ZoneInfo\n" +">>> from datetime import datetime, timedelta\n" +"\n" +">>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo(\"America/" +"Los_Angeles\"))\n" +">>> print(dt)\n" +"2020-10-31 12:00:00-07:00\n" +"\n" +">>> dt.tzname()\n" +"'PDT'" +msgstr "" + #: ../../library/zoneinfo.rst:52 msgid "" "Datetimes constructed in this way are compatible with datetime arithmetic " "and handle daylight saving time transitions with no further intervention::" msgstr "" +#: ../../library/zoneinfo.rst:55 +msgid "" +">>> dt_add = dt + timedelta(days=1)\n" +"\n" +">>> print(dt_add)\n" +"2020-11-01 12:00:00-08:00\n" +"\n" +">>> dt_add.tzname()\n" +"'PST'" +msgstr "" + #: ../../library/zoneinfo.rst:63 msgid "" "These time zones also support the :attr:`~datetime.datetime.fold` attribute " @@ -102,12 +125,37 @@ msgid "" "*after* the transition is used when ``fold=1``, for example::" msgstr "" +#: ../../library/zoneinfo.rst:69 +msgid "" +">>> dt = datetime(2020, 11, 1, 1, tzinfo=ZoneInfo(\"America/Los_Angeles\"))\n" +">>> print(dt)\n" +"2020-11-01 01:00:00-07:00\n" +"\n" +">>> print(dt.replace(fold=1))\n" +"2020-11-01 01:00:00-08:00" +msgstr "" + #: ../../library/zoneinfo.rst:76 msgid "" "When converting from another time zone, the fold will be set to the correct " "value::" msgstr "" +#: ../../library/zoneinfo.rst:79 +msgid "" +">>> from datetime import timezone\n" +">>> LOS_ANGELES = ZoneInfo(\"America/Los_Angeles\")\n" +">>> dt_utc = datetime(2020, 11, 1, 8, tzinfo=timezone.utc)\n" +"\n" +">>> # Before the PDT -> PST transition\n" +">>> print(dt_utc.astimezone(LOS_ANGELES))\n" +"2020-11-01 01:00:00-07:00\n" +"\n" +">>> # After the PDT -> PST transition\n" +">>> print((dt_utc + timedelta(hours=1)).astimezone(LOS_ANGELES))\n" +"2020-11-01 01:00:00-08:00" +msgstr "" + #: ../../library/zoneinfo.rst:92 msgid "Data sources" msgstr "" @@ -231,6 +279,13 @@ msgid "" "``key``, the following assertion will always be true:" msgstr "" +#: ../../library/zoneinfo.rst:182 +msgid "" +"a = ZoneInfo(key)\n" +"b = ZoneInfo(key)\n" +"assert a is b" +msgstr "" + #: ../../library/zoneinfo.rst:188 msgid "" "``key`` must be in the form of a relative, normalized POSIX path, with no up-" @@ -350,6 +405,17 @@ msgid "" "the note on usage in the attribute documentation)::" msgstr "" +#: ../../library/zoneinfo.rst:275 +msgid "" +">>> zone = ZoneInfo(\"Pacific/Kwajalein\")\n" +">>> str(zone)\n" +"'Pacific/Kwajalein'\n" +"\n" +">>> dt = datetime(2020, 4, 1, 3, 15, tzinfo=zone)\n" +">>> f\"{dt.isoformat()} [{dt.tzinfo}]\"\n" +"'2020-04-01T03:15:00+12:00 [Pacific/Kwajalein]'" +msgstr "" + #: ../../library/zoneinfo.rst:283 msgid "" "For objects constructed from a file without specifying a ``key`` parameter, " @@ -384,6 +450,14 @@ msgid "" "following behavior:" msgstr "" +#: ../../library/zoneinfo.rst:307 +msgid "" +">>> a = ZoneInfo(\"Europe/Berlin\")\n" +">>> b = pickle.loads(europe_berlin_pkl)\n" +">>> a is b\n" +"True" +msgstr "" + #: ../../library/zoneinfo.rst:314 msgid "" "``ZoneInfo.no_cache(key)``: When constructed from the cache-bypassing " @@ -394,6 +468,14 @@ msgid "" "the following behavior:" msgstr "" +#: ../../library/zoneinfo.rst:321 +msgid "" +">>> a = ZoneInfo(\"Europe/Berlin\")\n" +">>> b = pickle.loads(europe_berlin_pkl_nc)\n" +">>> a is b\n" +"False" +msgstr "" + #: ../../library/zoneinfo.rst:328 msgid "" "``ZoneInfo.from_file(fobj, /, key=None)``: When constructed from a file, the " diff --git a/license.po b/license.po index 95bf7a45d..db6bbf8f1 100644 --- a/license.po +++ b/license.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# felipe caridade fernandes , 2021 -# Claudio Rogerio Carvalho Filho , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-03 17:40+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -36,53 +34,51 @@ msgstr "História do software" #: ../../license.rst:13 msgid "" "Python was created in the early 1990s by Guido van Rossum at Stichting " -"Mathematisch Centrum (CWI, see https://www.cwi.nl/) in the Netherlands as a " +"Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands as a " "successor of a language called ABC. Guido remains Python's principal " "author, although it includes many contributions from others." msgstr "" -"O Python foi criado no início dos anos 1990 por Guido van Rossum na " -"Stichting Mathematisch Centrum (CWI, veja https://www.cwi.nl/) na Holanda " -"como um sucessor de uma linguagem chamada ABC. Guido continua a ser o " -"principal autor de Python, embora inclua muitas contribuições de outros." +"Python foi criado no início dos anos 1990 por Guido van Rossum no Stichting " +"Mathematisch Centrum (CWI, veja https://www.cwi.nl) na Holanda como sucessor " +"de uma linguagem chamada ABC. Guido continua sendo o principal autor do " +"Python, embora inclua muitas contribuições de outros." #: ../../license.rst:18 msgid "" "In 1995, Guido continued his work on Python at the Corporation for National " -"Research Initiatives (CNRI, see https://www.cnri.reston.va.us/) in Reston, " +"Research Initiatives (CNRI, see https://www.cnri.reston.va.us) in Reston, " "Virginia where he released several versions of the software." msgstr "" -"Em 1995, Guido continuou seu trabalho em Python na Corporação para " -"Iniciativas Nacionais de Pesquisa (CNRI, veja https://www.cnri.reston.va." -"us/) em Reston, Virgínia, onde lançou várias versões do software." +"Em 1995, Guido continuou seu trabalho em Python na Corporation for National " +"Research Initiatives (CNRI, veja https://www.cnri.reston.va.us) em Reston, " +"Virgínia, onde lançou várias versões do software." #: ../../license.rst:22 msgid "" "In May 2000, Guido and the Python core development team moved to BeOpen.com " "to form the BeOpen PythonLabs team. In October of the same year, the " -"PythonLabs team moved to Digital Creations (now Zope Corporation; see " -"https://www.zope.org/). In 2001, the Python Software Foundation (PSF, see " -"https://www.python.org/psf/) was formed, a non-profit organization created " -"specifically to own Python-related Intellectual Property. Zope Corporation " -"is a sponsoring member of the PSF." -msgstr "" -"Em maio de 2000, Guido e a equipe principal de desenvolvimento do Python " -"mudaram-se para o BeOpen.com para formar a equipe BeOpen PythonLabs. Em " -"outubro do mesmo ano, a equipe da PythonLabs mudou para a Digital Creations " -"(agora Zope Corporation; veja https://www.zope.org/). Em 2001, formou-se a " -"Python Software Foundation (PSF, veja https://www.python.org/psf/), uma " -"organização sem fins lucrativos criada especificamente para possuir " -"propriedade intelectual relacionada a Python. A Zope Corporation é um membro " -"patrocinador do PSF." +"PythonLabs team moved to Digital Creations, which became Zope Corporation. " +"In 2001, the Python Software Foundation (PSF, see https://www.python.org/" +"psf/) was formed, a non-profit organization created specifically to own " +"Python-related Intellectual Property. Zope Corporation was a sponsoring " +"member of the PSF." +msgstr "" +"Em maio de 2000, Guido e a equipe de desenvolvimento do núcleo Python " +"mudaram-se para BeOpen.com para formar a equipe BeOpen PythonLabs. Em " +"outubro do mesmo ano, a equipe PythonLabs mudou-se para a Digital Creations, " +"que se tornou Zope Corporation. Em 2001, a Python Software Foundation (PSF, " +"veja https://www.python.org/psf/) foi formada, uma organização sem fins " +"lucrativos criada especificamente para possuir Propriedade Intelectual " +"relacionada ao Python. A Zope Corporation era um membro patrocinador da PSF." #: ../../license.rst:30 msgid "" -"All Python releases are Open Source (see https://opensource.org/ for the " -"Open Source Definition). Historically, most, but not all, Python releases " -"have also been GPL-compatible; the table below summarizes the various " -"releases." +"All Python releases are Open Source (see https://opensource.org for the Open " +"Source Definition). Historically, most, but not all, Python releases have " +"also been GPL-compatible; the table below summarizes the various releases." msgstr "" "Todas as versões do Python são de código aberto (consulte https://opensource." -"org/ para a definição de código aberto). Historicamente, a maioria, mas não " +"org para a definição de código aberto). Historicamente, a maioria, mas não " "todas, versões do Python também são compatíveis com GPL; a tabela abaixo " "resume os vários lançamentos." @@ -103,8 +99,8 @@ msgid "Owner" msgstr "Proprietário" #: ../../license.rst:35 -msgid "GPL compatible?" -msgstr "Compatível com a GPL?" +msgid "GPL-compatible? (1)" +msgstr "Compatível com a GPL? (1)" #: ../../license.rst:37 msgid "0.9.0 thru 1.2" @@ -156,8 +152,7 @@ msgstr "1.5.2" msgid "2000" msgstr "2000" -#: ../../license.rst:41 ../../license.rst:43 ../../license.rst:45 -#: ../../license.rst:47 +#: ../../license.rst:41 ../../license.rst:43 ../../license.rst:47 msgid "no" msgstr "não" @@ -178,6 +173,10 @@ msgstr "1.6.1" msgid "2001" msgstr "2001" +#: ../../license.rst:45 +msgid "yes (2)" +msgstr "sim (2)" + #: ../../license.rst:47 msgid "2.1" msgstr "2.1" @@ -225,7 +224,7 @@ msgstr "2001-agora" #: ../../license.rst:62 msgid "" -"GPL-compatible doesn't mean that we're distributing Python under the GPL. " +"GPL-compatible doesn't mean that we're distributing Python under the GPL. " "All Python licenses, unlike the GPL, let you distribute a modified version " "without making your changes open source. The GPL-compatible licenses make it " "possible to combine Python with other software that is released under the " @@ -239,35 +238,47 @@ msgstr "" #: ../../license.rst:68 msgid "" +"According to Richard Stallman, 1.6.1 is not GPL-compatible, because its " +"license has a choice of law clause. According to CNRI, however, Stallman's " +"lawyer has told CNRI's lawyer that 1.6.1 is \"not incompatible\" with the " +"GPL." +msgstr "" +"De acordo com Richard Stallman, 1.6.1 não é compatível com GPL, porque sua " +"licença tem uma cláusula de escolha de lei. De acordo com a CNRI, no " +"entanto, o advogado de Stallman disse ao advogado da CNRI que 1.6.1 \"não é " +"incompatível\" com a GPL." + +#: ../../license.rst:72 +msgid "" "Thanks to the many outside volunteers who have worked under Guido's " "direction to make these releases possible." msgstr "" "Graças aos muitos voluntários externos que trabalharam sob a direção de " "Guido para tornar esses lançamentos possíveis." -#: ../../license.rst:73 +#: ../../license.rst:77 msgid "Terms and conditions for accessing or otherwise using Python" msgstr "Termos e condições para acessar ou usar Python" -#: ../../license.rst:75 +#: ../../license.rst:79 msgid "" -"Python software and documentation are licensed under the :ref:`PSF License " -"Agreement `." +"Python software and documentation are licensed under the Python Software " +"Foundation License Version 2." msgstr "" -"O software e a documentação do Python são licenciados sob o :ref:`Acordo de " -"Licenciamento PSF `." +"O software e a documentação do Python são licenciados sob a Python Software " +"Foundation License Versão 2." -#: ../../license.rst:78 +#: ../../license.rst:82 msgid "" "Starting with Python 3.8.6, examples, recipes, and other code in the " -"documentation are dual licensed under the PSF License Agreement and the :ref:" +"documentation are dual licensed under the PSF License Version 2 and the :ref:" "`Zero-Clause BSD license `." msgstr "" "A partir do Python 3.8.6, exemplos, receitas e outros códigos na " -"documentação são licenciados duplamente sob o Acordo de Licenciamento PSF e " -"a :ref:`Licença BSD de Zero Cláusula `." +"documentação são licenciados duplamente sob o Licença PSF versão 2 e a :ref:" +"`Licença BSD de Zero Cláusula `." -#: ../../license.rst:82 +#: ../../license.rst:86 msgid "" "Some software incorporated into Python is under different licenses. The " "licenses are listed with code falling under that license. See :ref:" @@ -277,36 +288,569 @@ msgstr "" "licenças são listadas com o código abrangido por essa licença. Veja :ref:" "`OtherLicenses` para uma lista incompleta dessas licenças." -#: ../../license.rst:90 -msgid "PSF LICENSE AGREEMENT FOR PYTHON |release|" -msgstr "ACORDO DE LICENCIAMENTO DA PSF PARA PYTHON |release|" +#: ../../license.rst:94 +msgid "PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2" +msgstr "PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2" -#: ../../license.rst:138 +#: ../../license.rst:98 +msgid "" +"1. This LICENSE AGREEMENT is between the Python Software Foundation " +"(\"PSF\"), and\n" +" the Individual or Organization (\"Licensee\") accessing and otherwise " +"using this\n" +" software (\"Python\") in source or binary form and its associated " +"documentation.\n" +"\n" +"2. Subject to the terms and conditions of this License Agreement, PSF " +"hereby\n" +" grants Licensee a nonexclusive, royalty-free, world-wide license to " +"reproduce,\n" +" analyze, test, perform and/or display publicly, prepare derivative " +"works,\n" +" distribute, and otherwise use Python alone or in any derivative\n" +" version, provided, however, that PSF's License Agreement and PSF's notice " +"of\n" +" copyright, i.e., \"Copyright © 2001-2024 Python Software Foundation; All " +"Rights\n" +" Reserved\" are retained in Python alone or in any derivative version\n" +" prepared by Licensee.\n" +"\n" +"3. In the event Licensee prepares a derivative work that is based on or\n" +" incorporates Python or any part thereof, and wants to make the\n" +" derivative work available to others as provided herein, then Licensee " +"hereby\n" +" agrees to include in any such work a brief summary of the changes made to " +"Python.\n" +"\n" +"4. PSF is making Python available to Licensee on an \"AS IS\" basis.\n" +" PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY " +"OF\n" +" EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY " +"REPRESENTATION OR\n" +" WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT " +"THE\n" +" USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.\n" +"\n" +"5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n" +" FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT " +"OF\n" +" MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE\n" +" THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n" +"\n" +"6. This License Agreement will automatically terminate upon a material " +"breach of\n" +" its terms and conditions.\n" +"\n" +"7. Nothing in this License Agreement shall be deemed to create any " +"relationship\n" +" of agency, partnership, or joint venture between PSF and Licensee. This " +"License\n" +" Agreement does not grant permission to use PSF trademarks or trade name " +"in a\n" +" trademark sense to endorse or promote products or services of Licensee, " +"or any\n" +" third party.\n" +"\n" +"8. By copying, installing or otherwise using Python, Licensee agrees\n" +" to be bound by the terms and conditions of this License Agreement." +msgstr "" +"1. This LICENSE AGREEMENT is between the Python Software Foundation " +"(\"PSF\"), and\n" +" the Individual or Organization (\"Licensee\") accessing and otherwise " +"using this\n" +" software (\"Python\") in source or binary form and its associated " +"documentation.\n" +"\n" +"2. Subject to the terms and conditions of this License Agreement, PSF " +"hereby\n" +" grants Licensee a nonexclusive, royalty-free, world-wide license to " +"reproduce,\n" +" analyze, test, perform and/or display publicly, prepare derivative " +"works,\n" +" distribute, and otherwise use Python alone or in any derivative\n" +" version, provided, however, that PSF's License Agreement and PSF's notice " +"of\n" +" copyright, i.e., \"Copyright © 2001-2024 Python Software Foundation; All " +"Rights\n" +" Reserved\" are retained in Python alone or in any derivative version\n" +" prepared by Licensee.\n" +"\n" +"3. In the event Licensee prepares a derivative work that is based on or\n" +" incorporates Python or any part thereof, and wants to make the\n" +" derivative work available to others as provided herein, then Licensee " +"hereby\n" +" agrees to include in any such work a brief summary of the changes made to " +"Python.\n" +"\n" +"4. PSF is making Python available to Licensee on an \"AS IS\" basis.\n" +" PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY " +"OF\n" +" EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY " +"REPRESENTATION OR\n" +" WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT " +"THE\n" +" USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.\n" +"\n" +"5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n" +" FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT " +"OF\n" +" MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE\n" +" THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n" +"\n" +"6. This License Agreement will automatically terminate upon a material " +"breach of\n" +" its terms and conditions.\n" +"\n" +"7. Nothing in this License Agreement shall be deemed to create any " +"relationship\n" +" of agency, partnership, or joint venture between PSF and Licensee. This " +"License\n" +" Agreement does not grant permission to use PSF trademarks or trade name " +"in a\n" +" trademark sense to endorse or promote products or services of Licensee, " +"or any\n" +" third party.\n" +"\n" +"8. By copying, installing or otherwise using Python, Licensee agrees\n" +" to be bound by the terms and conditions of this License Agreement." + +#: ../../license.rst:141 msgid "BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0" msgstr "ACORDO DE LICENCIAMENTO DA BEOPEN.COM PARA PYTHON 2.0" -#: ../../license.rst:140 +#: ../../license.rst:143 msgid "BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1" msgstr "ACORDO DE LICENCIAMENTO DA BEOPEN DE FONTE ABERTA DO PYTHON VERSÃO 1" -#: ../../license.rst:185 +#: ../../license.rst:147 +msgid "" +"1. This LICENSE AGREEMENT is between BeOpen.com (\"BeOpen\"), having an " +"office at\n" +" 160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or " +"Organization\n" +" (\"Licensee\") accessing and otherwise using this software in source or " +"binary\n" +" form and its associated documentation (\"the Software\").\n" +"\n" +"2. Subject to the terms and conditions of this BeOpen Python License " +"Agreement,\n" +" BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide " +"license\n" +" to reproduce, analyze, test, perform and/or display publicly, prepare " +"derivative\n" +" works, distribute, and otherwise use the Software alone or in any " +"derivative\n" +" version, provided, however, that the BeOpen Python License is retained in " +"the\n" +" Software, alone or in any derivative version prepared by Licensee.\n" +"\n" +"3. BeOpen is making the Software available to Licensee on an \"AS IS\" " +"basis.\n" +" BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY " +"WAY OF\n" +" EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY " +"REPRESENTATION OR\n" +" WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT " +"THE\n" +" USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.\n" +"\n" +"4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE " +"FOR\n" +" ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF " +"USING,\n" +" MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN " +"IF\n" +" ADVISED OF THE POSSIBILITY THEREOF.\n" +"\n" +"5. This License Agreement will automatically terminate upon a material " +"breach of\n" +" its terms and conditions.\n" +"\n" +"6. This License Agreement shall be governed by and interpreted in all " +"respects\n" +" by the law of the State of California, excluding conflict of law " +"provisions.\n" +" Nothing in this License Agreement shall be deemed to create any " +"relationship of\n" +" agency, partnership, or joint venture between BeOpen and Licensee. This " +"License\n" +" Agreement does not grant permission to use BeOpen trademarks or trade " +"names in a\n" +" trademark sense to endorse or promote products or services of Licensee, " +"or any\n" +" third party. As an exception, the \"BeOpen Python\" logos available at\n" +" http://www.pythonlabs.com/logos.html may be used according to the " +"permissions\n" +" granted on that web page.\n" +"\n" +"7. By copying, installing or otherwise using the software, Licensee agrees " +"to be\n" +" bound by the terms and conditions of this License Agreement." +msgstr "" +"1. This LICENSE AGREEMENT is between BeOpen.com (\"BeOpen\"), having an " +"office at\n" +" 160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or " +"Organization\n" +" (\"Licensee\") accessing and otherwise using this software in source or " +"binary\n" +" form and its associated documentation (\"the Software\").\n" +"\n" +"2. Subject to the terms and conditions of this BeOpen Python License " +"Agreement,\n" +" BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide " +"license\n" +" to reproduce, analyze, test, perform and/or display publicly, prepare " +"derivative\n" +" works, distribute, and otherwise use the Software alone or in any " +"derivative\n" +" version, provided, however, that the BeOpen Python License is retained in " +"the\n" +" Software, alone or in any derivative version prepared by Licensee.\n" +"\n" +"3. BeOpen is making the Software available to Licensee on an \"AS IS\" " +"basis.\n" +" BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY " +"WAY OF\n" +" EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY " +"REPRESENTATION OR\n" +" WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT " +"THE\n" +" USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.\n" +"\n" +"4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE " +"FOR\n" +" ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF " +"USING,\n" +" MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN " +"IF\n" +" ADVISED OF THE POSSIBILITY THEREOF.\n" +"\n" +"5. This License Agreement will automatically terminate upon a material " +"breach of\n" +" its terms and conditions.\n" +"\n" +"6. This License Agreement shall be governed by and interpreted in all " +"respects\n" +" by the law of the State of California, excluding conflict of law " +"provisions.\n" +" Nothing in this License Agreement shall be deemed to create any " +"relationship of\n" +" agency, partnership, or joint venture between BeOpen and Licensee. This " +"License\n" +" Agreement does not grant permission to use BeOpen trademarks or trade " +"names in a\n" +" trademark sense to endorse or promote products or services of Licensee, " +"or any\n" +" third party. As an exception, the \"BeOpen Python\" logos available at\n" +" http://www.pythonlabs.com/logos.html may be used according to the " +"permissions\n" +" granted on that web page.\n" +"\n" +"7. By copying, installing or otherwise using the software, Licensee agrees " +"to be\n" +" bound by the terms and conditions of this License Agreement." + +#: ../../license.rst:188 msgid "CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1" msgstr "CONTRATO DE LICENÇA DA CNRI PARA O PYTHON 1.6.1" -#: ../../license.rst:250 +#: ../../license.rst:192 +msgid "" +"1. This LICENSE AGREEMENT is between the Corporation for National Research\n" +" Initiatives, having an office at 1895 Preston White Drive, Reston, VA " +"20191\n" +" (\"CNRI\"), and the Individual or Organization (\"Licensee\") accessing " +"and\n" +" otherwise using Python 1.6.1 software in source or binary form and its\n" +" associated documentation.\n" +"\n" +"2. Subject to the terms and conditions of this License Agreement, CNRI " +"hereby\n" +" grants Licensee a nonexclusive, royalty-free, world-wide license to " +"reproduce,\n" +" analyze, test, perform and/or display publicly, prepare derivative " +"works,\n" +" distribute, and otherwise use Python 1.6.1 alone or in any derivative " +"version,\n" +" provided, however, that CNRI's License Agreement and CNRI's notice of " +"copyright,\n" +" i.e., \"Copyright © 1995-2001 Corporation for National Research " +"Initiatives; All\n" +" Rights Reserved\" are retained in Python 1.6.1 alone or in any derivative " +"version\n" +" prepared by Licensee. Alternately, in lieu of CNRI's License Agreement,\n" +" Licensee may substitute the following text (omitting the quotes): " +"\"Python 1.6.1\n" +" is made available subject to the terms and conditions in CNRI's License\n" +" Agreement. This Agreement together with Python 1.6.1 may be located on " +"the\n" +" internet using the following unique, persistent identifier (known as a " +"handle):\n" +" 1895.22/1013. This Agreement may also be obtained from a proxy server on " +"the\n" +" internet using the following URL: http://hdl.handle.net/1895.22/1013\".\n" +"\n" +"3. In the event Licensee prepares a derivative work that is based on or\n" +" incorporates Python 1.6.1 or any part thereof, and wants to make the " +"derivative\n" +" work available to others as provided herein, then Licensee hereby agrees " +"to\n" +" include in any such work a brief summary of the changes made to Python " +"1.6.1.\n" +"\n" +"4. CNRI is making Python 1.6.1 available to Licensee on an \"AS IS\" basis. " +"CNRI\n" +" MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF " +"EXAMPLE,\n" +" BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR " +"WARRANTY\n" +" OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE " +"OF\n" +" PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.\n" +"\n" +"5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 " +"FOR\n" +" ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF\n" +" MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY " +"DERIVATIVE\n" +" THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n" +"\n" +"6. This License Agreement will automatically terminate upon a material " +"breach of\n" +" its terms and conditions.\n" +"\n" +"7. This License Agreement shall be governed by the federal intellectual " +"property\n" +" law of the United States, including without limitation the federal " +"copyright\n" +" law, and, to the extent such U.S. federal law does not apply, by the law " +"of the\n" +" Commonwealth of Virginia, excluding Virginia's conflict of law " +"provisions.\n" +" Notwithstanding the foregoing, with regard to derivative works based on " +"Python\n" +" 1.6.1 that incorporate non-separable material that was previously " +"distributed\n" +" under the GNU General Public License (GPL), the law of the Commonwealth " +"of\n" +" Virginia shall govern this License Agreement only as to issues arising " +"under or\n" +" with respect to Paragraphs 4, 5, and 7 of this License Agreement. " +"Nothing in\n" +" this License Agreement shall be deemed to create any relationship of " +"agency,\n" +" partnership, or joint venture between CNRI and Licensee. This License " +"Agreement\n" +" does not grant permission to use CNRI trademarks or trade name in a " +"trademark\n" +" sense to endorse or promote products or services of Licensee, or any " +"third\n" +" party.\n" +"\n" +"8. By clicking on the \"ACCEPT\" button where indicated, or by copying, " +"installing\n" +" or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms " +"and\n" +" conditions of this License Agreement." +msgstr "" +"1. This LICENSE AGREEMENT is between the Corporation for National Research\n" +" Initiatives, having an office at 1895 Preston White Drive, Reston, VA " +"20191\n" +" (\"CNRI\"), and the Individual or Organization (\"Licensee\") accessing " +"and\n" +" otherwise using Python 1.6.1 software in source or binary form and its\n" +" associated documentation.\n" +"\n" +"2. Subject to the terms and conditions of this License Agreement, CNRI " +"hereby\n" +" grants Licensee a nonexclusive, royalty-free, world-wide license to " +"reproduce,\n" +" analyze, test, perform and/or display publicly, prepare derivative " +"works,\n" +" distribute, and otherwise use Python 1.6.1 alone or in any derivative " +"version,\n" +" provided, however, that CNRI's License Agreement and CNRI's notice of " +"copyright,\n" +" i.e., \"Copyright © 1995-2001 Corporation for National Research " +"Initiatives; All\n" +" Rights Reserved\" are retained in Python 1.6.1 alone or in any derivative " +"version\n" +" prepared by Licensee. Alternately, in lieu of CNRI's License Agreement,\n" +" Licensee may substitute the following text (omitting the quotes): " +"\"Python 1.6.1\n" +" is made available subject to the terms and conditions in CNRI's License\n" +" Agreement. This Agreement together with Python 1.6.1 may be located on " +"the\n" +" internet using the following unique, persistent identifier (known as a " +"handle):\n" +" 1895.22/1013. This Agreement may also be obtained from a proxy server on " +"the\n" +" internet using the following URL: http://hdl.handle.net/1895.22/1013\".\n" +"\n" +"3. In the event Licensee prepares a derivative work that is based on or\n" +" incorporates Python 1.6.1 or any part thereof, and wants to make the " +"derivative\n" +" work available to others as provided herein, then Licensee hereby agrees " +"to\n" +" include in any such work a brief summary of the changes made to Python " +"1.6.1.\n" +"\n" +"4. CNRI is making Python 1.6.1 available to Licensee on an \"AS IS\" basis. " +"CNRI\n" +" MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF " +"EXAMPLE,\n" +" BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR " +"WARRANTY\n" +" OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE " +"OF\n" +" PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.\n" +"\n" +"5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 " +"FOR\n" +" ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF\n" +" MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY " +"DERIVATIVE\n" +" THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n" +"\n" +"6. This License Agreement will automatically terminate upon a material " +"breach of\n" +" its terms and conditions.\n" +"\n" +"7. This License Agreement shall be governed by the federal intellectual " +"property\n" +" law of the United States, including without limitation the federal " +"copyright\n" +" law, and, to the extent such U.S. federal law does not apply, by the law " +"of the\n" +" Commonwealth of Virginia, excluding Virginia's conflict of law " +"provisions.\n" +" Notwithstanding the foregoing, with regard to derivative works based on " +"Python\n" +" 1.6.1 that incorporate non-separable material that was previously " +"distributed\n" +" under the GNU General Public License (GPL), the law of the Commonwealth " +"of\n" +" Virginia shall govern this License Agreement only as to issues arising " +"under or\n" +" with respect to Paragraphs 4, 5, and 7 of this License Agreement. " +"Nothing in\n" +" this License Agreement shall be deemed to create any relationship of " +"agency,\n" +" partnership, or joint venture between CNRI and Licensee. This License " +"Agreement\n" +" does not grant permission to use CNRI trademarks or trade name in a " +"trademark\n" +" sense to endorse or promote products or services of Licensee, or any " +"third\n" +" party.\n" +"\n" +"8. By clicking on the \"ACCEPT\" button where indicated, or by copying, " +"installing\n" +" or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms " +"and\n" +" conditions of this License Agreement." + +#: ../../license.rst:253 msgid "CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2" msgstr "ACORDO DE LICENÇA DA CWI PARA PYTHON 0.9.0 A 1.2" -#: ../../license.rst:277 -msgid "ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON |release| DOCUMENTATION" +#: ../../license.rst:257 +msgid "" +"Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The\n" +"Netherlands. All rights reserved.\n" +"\n" +"Permission to use, copy, modify, and distribute this software and its\n" +"documentation for any purpose and without fee is hereby granted, provided " +"that\n" +"the above copyright notice appear in all copies and that both that " +"copyright\n" +"notice and this permission notice appear in supporting documentation, and " +"that\n" +"the name of Stichting Mathematisch Centrum or CWI not be used in advertising " +"or\n" +"publicity pertaining to distribution of the software without specific, " +"written\n" +"prior permission.\n" +"\n" +"STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS\n" +"SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, " +"IN NO\n" +"EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, " +"INDIRECT\n" +"OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF " +"USE,\n" +"DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER " +"TORTIOUS\n" +"ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS\n" +"SOFTWARE." msgstr "" -"LICENÇA BSD DE ZERO CLÁUSULA PARA CÓDIGO NA DOCUMENTAÇÃO DO PYTHON |release|" - -#: ../../license.rst:296 +"Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The\n" +"Netherlands. All rights reserved.\n" +"\n" +"Permission to use, copy, modify, and distribute this software and its\n" +"documentation for any purpose and without fee is hereby granted, provided " +"that\n" +"the above copyright notice appear in all copies and that both that " +"copyright\n" +"notice and this permission notice appear in supporting documentation, and " +"that\n" +"the name of Stichting Mathematisch Centrum or CWI not be used in advertising " +"or\n" +"publicity pertaining to distribution of the software without specific, " +"written\n" +"prior permission.\n" +"\n" +"STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS\n" +"SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, " +"IN NO\n" +"EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, " +"INDIRECT\n" +"OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF " +"USE,\n" +"DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER " +"TORTIOUS\n" +"ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS\n" +"SOFTWARE." + +#: ../../license.rst:280 +msgid "ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION" +msgstr "ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION" + +#: ../../license.rst:284 +msgid "" +"Permission to use, copy, modify, and/or distribute this software for any\n" +"purpose with or without fee is hereby granted.\n" +"\n" +"THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES " +"WITH\n" +"REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n" +"AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, " +"DIRECT,\n" +"INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n" +"LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE " +"OR\n" +"OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n" +"PERFORMANCE OF THIS SOFTWARE." +msgstr "" +"Permission to use, copy, modify, and/or distribute this software for any\n" +"purpose with or without fee is hereby granted.\n" +"\n" +"THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES " +"WITH\n" +"REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n" +"AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, " +"DIRECT,\n" +"INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n" +"LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE " +"OR\n" +"OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n" +"PERFORMANCE OF THIS SOFTWARE." + +#: ../../license.rst:299 msgid "Licenses and Acknowledgements for Incorporated Software" msgstr "Licenças e Reconhecimentos para Software Incorporado" -#: ../../license.rst:298 +#: ../../license.rst:301 msgid "" "This section is an incomplete, but growing list of licenses and " "acknowledgements for third-party software incorporated in the Python " @@ -316,11 +860,11 @@ msgstr "" "reconhecimentos para softwares de terceiros incorporados na distribuição do " "Python." -#: ../../license.rst:303 +#: ../../license.rst:306 msgid "Mersenne Twister" msgstr "Mersenne Twister" -#: ../../license.rst:305 +#: ../../license.rst:308 msgid "" "The :mod:`!_random` C extension underlying the :mod:`random` module includes " "code based on a download from http://www.math.sci.hiroshima-u.ac.jp/~m-mat/" @@ -332,11 +876,97 @@ msgstr "" "mat/MT/MT2002/emt19937ar.html. A seguir estão os comentários literais do " "código original::" -#: ../../license.rst:353 +#: ../../license.rst:313 +msgid "" +"A C-program for MT19937, with initialization improved 2002/1/26.\n" +"Coded by Takuji Nishimura and Makoto Matsumoto.\n" +"\n" +"Before using, initialize the state by using init_genrand(seed)\n" +"or init_by_array(init_key, key_length).\n" +"\n" +"Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,\n" +"All rights reserved.\n" +"\n" +"Redistribution and use in source and binary forms, with or without\n" +"modification, are permitted provided that the following conditions\n" +"are met:\n" +"\n" +" 1. Redistributions of source code must retain the above copyright\n" +" notice, this list of conditions and the following disclaimer.\n" +"\n" +" 2. Redistributions in binary form must reproduce the above copyright\n" +" notice, this list of conditions and the following disclaimer in the\n" +" documentation and/or other materials provided with the distribution.\n" +"\n" +" 3. The names of its contributors may not be used to endorse or promote\n" +" products derived from this software without specific prior written\n" +" permission.\n" +"\n" +"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" +"\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" +"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" +"A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER " +"OR\n" +"CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" +"EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" +"PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" +"PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" +"LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" +"NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" +"SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" +"\n" +"\n" +"Any feedback is very welcome.\n" +"http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html\n" +"email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)" +msgstr "" +"A C-program for MT19937, with initialization improved 2002/1/26.\n" +"Coded by Takuji Nishimura and Makoto Matsumoto.\n" +"\n" +"Before using, initialize the state by using init_genrand(seed)\n" +"or init_by_array(init_key, key_length).\n" +"\n" +"Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,\n" +"All rights reserved.\n" +"\n" +"Redistribution and use in source and binary forms, with or without\n" +"modification, are permitted provided that the following conditions\n" +"are met:\n" +"\n" +" 1. Redistributions of source code must retain the above copyright\n" +" notice, this list of conditions and the following disclaimer.\n" +"\n" +" 2. Redistributions in binary form must reproduce the above copyright\n" +" notice, this list of conditions and the following disclaimer in the\n" +" documentation and/or other materials provided with the distribution.\n" +"\n" +" 3. The names of its contributors may not be used to endorse or promote\n" +" products derived from this software without specific prior written\n" +" permission.\n" +"\n" +"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" +"\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" +"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" +"A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER " +"OR\n" +"CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" +"EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" +"PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" +"PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" +"LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" +"NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" +"SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" +"\n" +"\n" +"Any feedback is very welcome.\n" +"http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html\n" +"email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)" + +#: ../../license.rst:356 msgid "Sockets" msgstr "Soquetes" -#: ../../license.rst:355 +#: ../../license.rst:358 msgid "" "The :mod:`socket` module uses the functions, :c:func:`!getaddrinfo`, and :c:" "func:`!getnameinfo`, which are coded in separate source files from the WIDE " @@ -346,11 +976,67 @@ msgstr "" "getnameinfo`, que são codificadas em arquivos de origem separados do Projeto " "WIDE, https://www.wide.ad.jp/. ::" -#: ../../license.rst:388 +#: ../../license.rst:362 +msgid "" +"Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.\n" +"All rights reserved.\n" +"\n" +"Redistribution and use in source and binary forms, with or without\n" +"modification, are permitted provided that the following conditions\n" +"are met:\n" +"1. Redistributions of source code must retain the above copyright\n" +" notice, this list of conditions and the following disclaimer.\n" +"2. Redistributions in binary form must reproduce the above copyright\n" +" notice, this list of conditions and the following disclaimer in the\n" +" documentation and/or other materials provided with the distribution.\n" +"3. Neither the name of the project nor the names of its contributors\n" +" may be used to endorse or promote products derived from this software\n" +" without specific prior written permission.\n" +"\n" +"THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS \"AS IS\" AND\n" +"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" +"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" +"ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE\n" +"FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n" +"DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n" +"OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n" +"HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n" +"LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n" +"OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n" +"SUCH DAMAGE." +msgstr "" +"Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.\n" +"All rights reserved.\n" +"\n" +"Redistribution and use in source and binary forms, with or without\n" +"modification, are permitted provided that the following conditions\n" +"are met:\n" +"1. Redistributions of source code must retain the above copyright\n" +" notice, this list of conditions and the following disclaimer.\n" +"2. Redistributions in binary form must reproduce the above copyright\n" +" notice, this list of conditions and the following disclaimer in the\n" +" documentation and/or other materials provided with the distribution.\n" +"3. Neither the name of the project nor the names of its contributors\n" +" may be used to endorse or promote products derived from this software\n" +" without specific prior written permission.\n" +"\n" +"THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS \"AS IS\" AND\n" +"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" +"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" +"ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE\n" +"FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n" +"DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n" +"OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n" +"HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n" +"LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n" +"OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n" +"SUCH DAMAGE." + +#: ../../license.rst:391 msgid "Asynchronous socket services" msgstr "Serviços de soquete assíncrono" -#: ../../license.rst:390 +#: ../../license.rst:393 msgid "" "The :mod:`!test.support.asynchat` and :mod:`!test.support.asyncore` modules " "contain the following notice::" @@ -358,62 +1044,408 @@ msgstr "" "Os módulos :mod:`!test.support.asynchat` e :mod:`!test.support.asyncore` " "contêm o seguinte aviso::" -#: ../../license.rst:416 +#: ../../license.rst:396 +msgid "" +"Copyright 1996 by Sam Rushing\n" +"\n" +" All Rights Reserved\n" +"\n" +"Permission to use, copy, modify, and distribute this software and\n" +"its documentation for any purpose and without fee is hereby\n" +"granted, provided that the above copyright notice appear in all\n" +"copies and that both that copyright notice and this permission\n" +"notice appear in supporting documentation, and that the name of Sam\n" +"Rushing not be used in advertising or publicity pertaining to\n" +"distribution of the software without specific, written prior\n" +"permission.\n" +"\n" +"SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,\n" +"INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN\n" +"NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR\n" +"CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n" +"OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,\n" +"NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n" +"CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE." +msgstr "" +"Copyright 1996 by Sam Rushing\n" +"\n" +" All Rights Reserved\n" +"\n" +"Permission to use, copy, modify, and distribute this software and\n" +"its documentation for any purpose and without fee is hereby\n" +"granted, provided that the above copyright notice appear in all\n" +"copies and that both that copyright notice and this permission\n" +"notice appear in supporting documentation, and that the name of Sam\n" +"Rushing not be used in advertising or publicity pertaining to\n" +"distribution of the software without specific, written prior\n" +"permission.\n" +"\n" +"SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,\n" +"INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN\n" +"NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR\n" +"CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n" +"OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,\n" +"NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n" +"CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE." + +#: ../../license.rst:419 msgid "Cookie management" msgstr "Gerenciamento de cookies" -#: ../../license.rst:418 +#: ../../license.rst:421 msgid "The :mod:`http.cookies` module contains the following notice::" msgstr "O módulo :mod:`http.cookies` contém o seguinte aviso::" -#: ../../license.rst:444 +#: ../../license.rst:423 +msgid "" +"Copyright 2000 by Timothy O'Malley \n" +"\n" +" All Rights Reserved\n" +"\n" +"Permission to use, copy, modify, and distribute this software\n" +"and its documentation for any purpose and without fee is hereby\n" +"granted, provided that the above copyright notice appear in all\n" +"copies and that both that copyright notice and this permission\n" +"notice appear in supporting documentation, and that the name of\n" +"Timothy O'Malley not be used in advertising or publicity\n" +"pertaining to distribution of the software without specific, written\n" +"prior permission.\n" +"\n" +"Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS\n" +"SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n" +"AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR\n" +"ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n" +"WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,\n" +"WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\n" +"ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n" +"PERFORMANCE OF THIS SOFTWARE." +msgstr "" +"Copyright 2000 by Timothy O'Malley \n" +"\n" +" All Rights Reserved\n" +"\n" +"Permission to use, copy, modify, and distribute this software\n" +"and its documentation for any purpose and without fee is hereby\n" +"granted, provided that the above copyright notice appear in all\n" +"copies and that both that copyright notice and this permission\n" +"notice appear in supporting documentation, and that the name of\n" +"Timothy O'Malley not be used in advertising or publicity\n" +"pertaining to distribution of the software without specific, written\n" +"prior permission.\n" +"\n" +"Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS\n" +"SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n" +"AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR\n" +"ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n" +"WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,\n" +"WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\n" +"ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n" +"PERFORMANCE OF THIS SOFTWARE." + +#: ../../license.rst:447 msgid "Execution tracing" msgstr "Rastreamento de execução" -#: ../../license.rst:446 +#: ../../license.rst:449 msgid "The :mod:`trace` module contains the following notice::" msgstr "O módulo :mod:`trace` contém o seguinte aviso::" -#: ../../license.rst:477 +#: ../../license.rst:451 +msgid "" +"portions copyright 2001, Autonomous Zones Industries, Inc., all rights...\n" +"err... reserved and offered to the public under the terms of the\n" +"Python 2.2 license.\n" +"Author: Zooko O'Whielacronx\n" +"http://zooko.com/\n" +"mailto:zooko@zooko.com\n" +"\n" +"Copyright 2000, Mojam Media, Inc., all rights reserved.\n" +"Author: Skip Montanaro\n" +"\n" +"Copyright 1999, Bioreason, Inc., all rights reserved.\n" +"Author: Andrew Dalke\n" +"\n" +"Copyright 1995-1997, Automatrix, Inc., all rights reserved.\n" +"Author: Skip Montanaro\n" +"\n" +"Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved.\n" +"\n" +"\n" +"Permission to use, copy, modify, and distribute this Python software and\n" +"its associated documentation for any purpose without fee is hereby\n" +"granted, provided that the above copyright notice appears in all copies,\n" +"and that both that copyright notice and this permission notice appear in\n" +"supporting documentation, and that the name of neither Automatrix,\n" +"Bioreason or Mojam Media be used in advertising or publicity pertaining to\n" +"distribution of the software without specific, written prior permission." +msgstr "" +"portions copyright 2001, Autonomous Zones Industries, Inc., all rights...\n" +"err... reserved and offered to the public under the terms of the\n" +"Python 2.2 license.\n" +"Author: Zooko O'Whielacronx\n" +"http://zooko.com/\n" +"mailto:zooko@zooko.com\n" +"\n" +"Copyright 2000, Mojam Media, Inc., all rights reserved.\n" +"Author: Skip Montanaro\n" +"\n" +"Copyright 1999, Bioreason, Inc., all rights reserved.\n" +"Author: Andrew Dalke\n" +"\n" +"Copyright 1995-1997, Automatrix, Inc., all rights reserved.\n" +"Author: Skip Montanaro\n" +"\n" +"Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved.\n" +"\n" +"\n" +"Permission to use, copy, modify, and distribute this Python software and\n" +"its associated documentation for any purpose without fee is hereby\n" +"granted, provided that the above copyright notice appears in all copies,\n" +"and that both that copyright notice and this permission notice appear in\n" +"supporting documentation, and that the name of neither Automatrix,\n" +"Bioreason or Mojam Media be used in advertising or publicity pertaining to\n" +"distribution of the software without specific, written prior permission." + +#: ../../license.rst:480 msgid "UUencode and UUdecode functions" msgstr "Funções UUencode e UUdecode" -#: ../../license.rst:479 +#: ../../license.rst:482 msgid "The ``uu`` codec contains the following notice::" msgstr "O codec ``uu`` contém o seguinte aviso::" -#: ../../license.rst:507 +#: ../../license.rst:484 +msgid "" +"Copyright 1994 by Lance Ellinghouse\n" +"Cathedral City, California Republic, United States of America.\n" +" All Rights Reserved\n" +"Permission to use, copy, modify, and distribute this software and its\n" +"documentation for any purpose and without fee is hereby granted,\n" +"provided that the above copyright notice appear in all copies and that\n" +"both that copyright notice and this permission notice appear in\n" +"supporting documentation, and that the name of Lance Ellinghouse\n" +"not be used in advertising or publicity pertaining to distribution\n" +"of the software without specific, written prior permission.\n" +"LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO\n" +"THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n" +"FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE\n" +"FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n" +"WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n" +"ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\n" +"OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n" +"\n" +"Modified by Jack Jansen, CWI, July 1995:\n" +"- Use binascii module to do the actual line-by-line conversion\n" +" between ascii and binary. This results in a 1000-fold speedup. The C\n" +" version is still 5 times faster, though.\n" +"- Arguments more compliant with Python standard" +msgstr "" +"Copyright 1994 by Lance Ellinghouse\n" +"Cathedral City, California Republic, United States of America.\n" +" All Rights Reserved\n" +"Permission to use, copy, modify, and distribute this software and its\n" +"documentation for any purpose and without fee is hereby granted,\n" +"provided that the above copyright notice appear in all copies and that\n" +"both that copyright notice and this permission notice appear in\n" +"supporting documentation, and that the name of Lance Ellinghouse\n" +"not be used in advertising or publicity pertaining to distribution\n" +"of the software without specific, written prior permission.\n" +"LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO\n" +"THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n" +"FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE\n" +"FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n" +"WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n" +"ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\n" +"OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n" +"\n" +"Modified by Jack Jansen, CWI, July 1995:\n" +"- Use binascii module to do the actual line-by-line conversion\n" +" between ascii and binary. This results in a 1000-fold speedup. The C\n" +" version is still 5 times faster, though.\n" +"- Arguments more compliant with Python standard" + +#: ../../license.rst:510 msgid "XML Remote Procedure Calls" msgstr "Chamadas de procedimento remoto XML" -#: ../../license.rst:509 +#: ../../license.rst:512 msgid "The :mod:`xmlrpc.client` module contains the following notice::" msgstr "O módulo :mod:`xmlrpc.client` contém o seguinte aviso::" -#: ../../license.rst:540 +#: ../../license.rst:514 +msgid "" +" The XML-RPC client interface is\n" +"\n" +"Copyright (c) 1999-2002 by Secret Labs AB\n" +"Copyright (c) 1999-2002 by Fredrik Lundh\n" +"\n" +"By obtaining, using, and/or copying this software and/or its\n" +"associated documentation, you agree that you have read, understood,\n" +"and will comply with the following terms and conditions:\n" +"\n" +"Permission to use, copy, modify, and distribute this software and\n" +"its associated documentation for any purpose and without fee is\n" +"hereby granted, provided that the above copyright notice appears in\n" +"all copies, and that both that copyright notice and this permission\n" +"notice appear in supporting documentation, and that the name of\n" +"Secret Labs AB or the author not be used in advertising or publicity\n" +"pertaining to distribution of the software without specific, written\n" +"prior permission.\n" +"\n" +"SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD\n" +"TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-\n" +"ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR\n" +"BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY\n" +"DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,\n" +"WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\n" +"ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE\n" +"OF THIS SOFTWARE." +msgstr "" +" The XML-RPC client interface is\n" +"\n" +"Copyright (c) 1999-2002 by Secret Labs AB\n" +"Copyright (c) 1999-2002 by Fredrik Lundh\n" +"\n" +"By obtaining, using, and/or copying this software and/or its\n" +"associated documentation, you agree that you have read, understood,\n" +"and will comply with the following terms and conditions:\n" +"\n" +"Permission to use, copy, modify, and distribute this software and\n" +"its associated documentation for any purpose and without fee is\n" +"hereby granted, provided that the above copyright notice appears in\n" +"all copies, and that both that copyright notice and this permission\n" +"notice appear in supporting documentation, and that the name of\n" +"Secret Labs AB or the author not be used in advertising or publicity\n" +"pertaining to distribution of the software without specific, written\n" +"prior permission.\n" +"\n" +"SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD\n" +"TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-\n" +"ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR\n" +"BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY\n" +"DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,\n" +"WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\n" +"ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE\n" +"OF THIS SOFTWARE." + +#: ../../license.rst:543 msgid "test_epoll" msgstr "test_epoll" -#: ../../license.rst:542 +#: ../../license.rst:545 msgid "The :mod:`!test.test_epoll` module contains the following notice::" msgstr "O módulo :mod:`!test.test_epoll` contém o seguinte aviso::" -#: ../../license.rst:566 +#: ../../license.rst:547 +msgid "" +"Copyright (c) 2001-2006 Twisted Matrix Laboratories.\n" +"\n" +"Permission is hereby granted, free of charge, to any person obtaining\n" +"a copy of this software and associated documentation files (the\n" +"\"Software\"), to deal in the Software without restriction, including\n" +"without limitation the rights to use, copy, modify, merge, publish,\n" +"distribute, sublicense, and/or sell copies of the Software, and to\n" +"permit persons to whom the Software is furnished to do so, subject to\n" +"the following conditions:\n" +"\n" +"The above copyright notice and this permission notice shall be\n" +"included in all copies or substantial portions of the Software.\n" +"\n" +"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" +"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n" +"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n" +"NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n" +"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n" +"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n" +"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." +msgstr "" +"Copyright (c) 2001-2006 Twisted Matrix Laboratories.\n" +"\n" +"Permission is hereby granted, free of charge, to any person obtaining\n" +"a copy of this software and associated documentation files (the\n" +"\"Software\"), to deal in the Software without restriction, including\n" +"without limitation the rights to use, copy, modify, merge, publish,\n" +"distribute, sublicense, and/or sell copies of the Software, and to\n" +"permit persons to whom the Software is furnished to do so, subject to\n" +"the following conditions:\n" +"\n" +"The above copyright notice and this permission notice shall be\n" +"included in all copies or substantial portions of the Software.\n" +"\n" +"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" +"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n" +"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n" +"NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n" +"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n" +"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n" +"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." + +#: ../../license.rst:569 msgid "Select kqueue" msgstr "kqueue de seleção" -#: ../../license.rst:568 +#: ../../license.rst:571 msgid "" "The :mod:`select` module contains the following notice for the kqueue " "interface::" msgstr "" "O módulo :mod:`select` contém o seguinte aviso para a interface do kqueue::" -#: ../../license.rst:597 +#: ../../license.rst:574 +msgid "" +"Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes\n" +"All rights reserved.\n" +"\n" +"Redistribution and use in source and binary forms, with or without\n" +"modification, are permitted provided that the following conditions\n" +"are met:\n" +"1. Redistributions of source code must retain the above copyright\n" +" notice, this list of conditions and the following disclaimer.\n" +"2. Redistributions in binary form must reproduce the above copyright\n" +" notice, this list of conditions and the following disclaimer in the\n" +" documentation and/or other materials provided with the distribution.\n" +"\n" +"THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND\n" +"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" +"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" +"ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n" +"FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n" +"DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n" +"OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n" +"HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n" +"LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n" +"OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n" +"SUCH DAMAGE." +msgstr "" +"Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes\n" +"All rights reserved.\n" +"\n" +"Redistribution and use in source and binary forms, with or without\n" +"modification, are permitted provided that the following conditions\n" +"are met:\n" +"1. Redistributions of source code must retain the above copyright\n" +" notice, this list of conditions and the following disclaimer.\n" +"2. Redistributions in binary form must reproduce the above copyright\n" +" notice, this list of conditions and the following disclaimer in the\n" +" documentation and/or other materials provided with the distribution.\n" +"\n" +"THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND\n" +"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" +"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" +"ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n" +"FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n" +"DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n" +"OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n" +"HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n" +"LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n" +"OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n" +"SUCH DAMAGE." + +#: ../../license.rst:600 msgid "SipHash24" msgstr "SipHash24" -#: ../../license.rst:599 +#: ../../license.rst:602 msgid "" "The file :file:`Python/pyhash.c` contains Marek Majkowski' implementation of " "Dan Bernstein's SipHash24 algorithm. It contains the following note::" @@ -421,11 +1453,63 @@ msgstr "" "O arquivo :file:`Python/pyhash.c` contém a implementação de Marek Majkowski " "do algoritmo SipHash24 de Dan Bernstein. Contém a seguinte nota::" -#: ../../license.rst:626 +#: ../../license.rst:605 +msgid "" +"\n" +"Copyright (c) 2013 Marek Majkowski \n" +"\n" +"Permission is hereby granted, free of charge, to any person obtaining a " +"copy\n" +"of this software and associated documentation files (the \"Software\"), to " +"deal\n" +"in the Software without restriction, including without limitation the " +"rights\n" +"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n" +"copies of the Software, and to permit persons to whom the Software is\n" +"furnished to do so, subject to the following conditions:\n" +"\n" +"The above copyright notice and this permission notice shall be included in\n" +"all copies or substantial portions of the Software.\n" +"\n" +"\n" +"Original location:\n" +" https://github.com/majek/csiphash/\n" +"\n" +"Solution inspired by code from:\n" +" Samuel Neves (supercop/crypto_auth/siphash24/little)\n" +" djb (supercop/crypto_auth/siphash24/little2)\n" +" Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c)" +msgstr "" +"\n" +"Copyright (c) 2013 Marek Majkowski \n" +"\n" +"Permission is hereby granted, free of charge, to any person obtaining a " +"copy\n" +"of this software and associated documentation files (the \"Software\"), to " +"deal\n" +"in the Software without restriction, including without limitation the " +"rights\n" +"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n" +"copies of the Software, and to permit persons to whom the Software is\n" +"furnished to do so, subject to the following conditions:\n" +"\n" +"The above copyright notice and this permission notice shall be included in\n" +"all copies or substantial portions of the Software.\n" +"\n" +"\n" +"Original location:\n" +" https://github.com/majek/csiphash/\n" +"\n" +"Solution inspired by code from:\n" +" Samuel Neves (supercop/crypto_auth/siphash24/little)\n" +" djb (supercop/crypto_auth/siphash24/little2)\n" +" Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c)" + +#: ../../license.rst:629 msgid "strtod and dtoa" msgstr "strtod e dtoa" -#: ../../license.rst:628 +#: ../../license.rst:631 msgid "" "The file :file:`Python/dtoa.c`, which supplies C functions dtoa and strtod " "for conversion of C doubles to and from strings, is derived from the file of " @@ -441,11 +1525,53 @@ msgstr "" "conforme recuperado em 16 de março de 2009, contém os seguintes avisos de " "direitos autorais e de licenciamento::" -#: ../../license.rst:656 +#: ../../license.rst:638 +msgid "" +"/****************************************************************\n" +" *\n" +" * The author of this software is David M. Gay.\n" +" *\n" +" * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.\n" +" *\n" +" * Permission to use, copy, modify, and distribute this software for any\n" +" * purpose without fee is hereby granted, provided that this entire notice\n" +" * is included in all copies of any software which is or includes a copy\n" +" * or modification of this software and in all copies of the supporting\n" +" * documentation for such software.\n" +" *\n" +" * THIS SOFTWARE IS BEING PROVIDED \"AS IS\", WITHOUT ANY EXPRESS OR " +"IMPLIED\n" +" * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY\n" +" * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY\n" +" * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.\n" +" *\n" +" ***************************************************************/" +msgstr "" +"/****************************************************************\n" +" *\n" +" * The author of this software is David M. Gay.\n" +" *\n" +" * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.\n" +" *\n" +" * Permission to use, copy, modify, and distribute this software for any\n" +" * purpose without fee is hereby granted, provided that this entire notice\n" +" * is included in all copies of any software which is or includes a copy\n" +" * or modification of this software and in all copies of the supporting\n" +" * documentation for such software.\n" +" *\n" +" * THIS SOFTWARE IS BEING PROVIDED \"AS IS\", WITHOUT ANY EXPRESS OR " +"IMPLIED\n" +" * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY\n" +" * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY\n" +" * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.\n" +" *\n" +" ***************************************************************/" + +#: ../../license.rst:659 msgid "OpenSSL" msgstr "OpenSSL" -#: ../../license.rst:658 +#: ../../license.rst:661 msgid "" "The modules :mod:`hashlib`, :mod:`posix` and :mod:`ssl` use the OpenSSL " "library for added performance if made available by the operating system. " @@ -462,11 +1588,367 @@ msgstr "" "3.0, e lançamentos posteriores derivados deste, se aplica a Apache License " "v2::" -#: ../../license.rst:845 +#: ../../license.rst:669 +msgid "" +" Apache License\n" +" Version 2.0, January 2004\n" +" https://www.apache.org/licenses/\n" +"\n" +"TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n" +"\n" +"1. Definitions.\n" +"\n" +" \"License\" shall mean the terms and conditions for use, reproduction,\n" +" and distribution as defined by Sections 1 through 9 of this document.\n" +"\n" +" \"Licensor\" shall mean the copyright owner or entity authorized by\n" +" the copyright owner that is granting the License.\n" +"\n" +" \"Legal Entity\" shall mean the union of the acting entity and all\n" +" other entities that control, are controlled by, or are under common\n" +" control with that entity. For the purposes of this definition,\n" +" \"control\" means (i) the power, direct or indirect, to cause the\n" +" direction or management of such entity, whether by contract or\n" +" otherwise, or (ii) ownership of fifty percent (50%) or more of the\n" +" outstanding shares, or (iii) beneficial ownership of such entity.\n" +"\n" +" \"You\" (or \"Your\") shall mean an individual or Legal Entity\n" +" exercising permissions granted by this License.\n" +"\n" +" \"Source\" form shall mean the preferred form for making modifications,\n" +" including but not limited to software source code, documentation\n" +" source, and configuration files.\n" +"\n" +" \"Object\" form shall mean any form resulting from mechanical\n" +" transformation or translation of a Source form, including but\n" +" not limited to compiled object code, generated documentation,\n" +" and conversions to other media types.\n" +"\n" +" \"Work\" shall mean the work of authorship, whether in Source or\n" +" Object form, made available under the License, as indicated by a\n" +" copyright notice that is included in or attached to the work\n" +" (an example is provided in the Appendix below).\n" +"\n" +" \"Derivative Works\" shall mean any work, whether in Source or Object\n" +" form, that is based on (or derived from) the Work and for which the\n" +" editorial revisions, annotations, elaborations, or other modifications\n" +" represent, as a whole, an original work of authorship. For the purposes\n" +" of this License, Derivative Works shall not include works that remain\n" +" separable from, or merely link (or bind by name) to the interfaces of,\n" +" the Work and Derivative Works thereof.\n" +"\n" +" \"Contribution\" shall mean any work of authorship, including\n" +" the original version of the Work and any modifications or additions\n" +" to that Work or Derivative Works thereof, that is intentionally\n" +" submitted to Licensor for inclusion in the Work by the copyright owner\n" +" or by an individual or Legal Entity authorized to submit on behalf of\n" +" the copyright owner. For the purposes of this definition, \"submitted\"\n" +" means any form of electronic, verbal, or written communication sent\n" +" to the Licensor or its representatives, including but not limited to\n" +" communication on electronic mailing lists, source code control systems,\n" +" and issue tracking systems that are managed by, or on behalf of, the\n" +" Licensor for the purpose of discussing and improving the Work, but\n" +" excluding communication that is conspicuously marked or otherwise\n" +" designated in writing by the copyright owner as \"Not a Contribution.\"\n" +"\n" +" \"Contributor\" shall mean Licensor and any individual or Legal Entity\n" +" on behalf of whom a Contribution has been received by Licensor and\n" +" subsequently incorporated within the Work.\n" +"\n" +"2. Grant of Copyright License. Subject to the terms and conditions of\n" +" this License, each Contributor hereby grants to You a perpetual,\n" +" worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n" +" copyright license to reproduce, prepare Derivative Works of,\n" +" publicly display, publicly perform, sublicense, and distribute the\n" +" Work and such Derivative Works in Source or Object form.\n" +"\n" +"3. Grant of Patent License. Subject to the terms and conditions of\n" +" this License, each Contributor hereby grants to You a perpetual,\n" +" worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n" +" (except as stated in this section) patent license to make, have made,\n" +" use, offer to sell, sell, import, and otherwise transfer the Work,\n" +" where such license applies only to those patent claims licensable\n" +" by such Contributor that are necessarily infringed by their\n" +" Contribution(s) alone or by combination of their Contribution(s)\n" +" with the Work to which such Contribution(s) was submitted. If You\n" +" institute patent litigation against any entity (including a\n" +" cross-claim or counterclaim in a lawsuit) alleging that the Work\n" +" or a Contribution incorporated within the Work constitutes direct\n" +" or contributory patent infringement, then any patent licenses\n" +" granted to You under this License for that Work shall terminate\n" +" as of the date such litigation is filed.\n" +"\n" +"4. Redistribution. You may reproduce and distribute copies of the\n" +" Work or Derivative Works thereof in any medium, with or without\n" +" modifications, and in Source or Object form, provided that You\n" +" meet the following conditions:\n" +"\n" +" (a) You must give any other recipients of the Work or\n" +" Derivative Works a copy of this License; and\n" +"\n" +" (b) You must cause any modified files to carry prominent notices\n" +" stating that You changed the files; and\n" +"\n" +" (c) You must retain, in the Source form of any Derivative Works\n" +" that You distribute, all copyright, patent, trademark, and\n" +" attribution notices from the Source form of the Work,\n" +" excluding those notices that do not pertain to any part of\n" +" the Derivative Works; and\n" +"\n" +" (d) If the Work includes a \"NOTICE\" text file as part of its\n" +" distribution, then any Derivative Works that You distribute must\n" +" include a readable copy of the attribution notices contained\n" +" within such NOTICE file, excluding those notices that do not\n" +" pertain to any part of the Derivative Works, in at least one\n" +" of the following places: within a NOTICE text file distributed\n" +" as part of the Derivative Works; within the Source form or\n" +" documentation, if provided along with the Derivative Works; or,\n" +" within a display generated by the Derivative Works, if and\n" +" wherever such third-party notices normally appear. The contents\n" +" of the NOTICE file are for informational purposes only and\n" +" do not modify the License. You may add Your own attribution\n" +" notices within Derivative Works that You distribute, alongside\n" +" or as an addendum to the NOTICE text from the Work, provided\n" +" that such additional attribution notices cannot be construed\n" +" as modifying the License.\n" +"\n" +" You may add Your own copyright statement to Your modifications and\n" +" may provide additional or different license terms and conditions\n" +" for use, reproduction, or distribution of Your modifications, or\n" +" for any such Derivative Works as a whole, provided Your use,\n" +" reproduction, and distribution of the Work otherwise complies with\n" +" the conditions stated in this License.\n" +"\n" +"5. Submission of Contributions. Unless You explicitly state otherwise,\n" +" any Contribution intentionally submitted for inclusion in the Work\n" +" by You to the Licensor shall be under the terms and conditions of\n" +" this License, without any additional terms or conditions.\n" +" Notwithstanding the above, nothing herein shall supersede or modify\n" +" the terms of any separate license agreement you may have executed\n" +" with Licensor regarding such Contributions.\n" +"\n" +"6. Trademarks. This License does not grant permission to use the trade\n" +" names, trademarks, service marks, or product names of the Licensor,\n" +" except as required for reasonable and customary use in describing the\n" +" origin of the Work and reproducing the content of the NOTICE file.\n" +"\n" +"7. Disclaimer of Warranty. Unless required by applicable law or\n" +" agreed to in writing, Licensor provides the Work (and each\n" +" Contributor provides its Contributions) on an \"AS IS\" BASIS,\n" +" WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n" +" implied, including, without limitation, any warranties or conditions\n" +" of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n" +" PARTICULAR PURPOSE. You are solely responsible for determining the\n" +" appropriateness of using or redistributing the Work and assume any\n" +" risks associated with Your exercise of permissions under this License.\n" +"\n" +"8. Limitation of Liability. In no event and under no legal theory,\n" +" whether in tort (including negligence), contract, or otherwise,\n" +" unless required by applicable law (such as deliberate and grossly\n" +" negligent acts) or agreed to in writing, shall any Contributor be\n" +" liable to You for damages, including any direct, indirect, special,\n" +" incidental, or consequential damages of any character arising as a\n" +" result of this License or out of the use or inability to use the\n" +" Work (including but not limited to damages for loss of goodwill,\n" +" work stoppage, computer failure or malfunction, or any and all\n" +" other commercial damages or losses), even if such Contributor\n" +" has been advised of the possibility of such damages.\n" +"\n" +"9. Accepting Warranty or Additional Liability. While redistributing\n" +" the Work or Derivative Works thereof, You may choose to offer,\n" +" and charge a fee for, acceptance of support, warranty, indemnity,\n" +" or other liability obligations and/or rights consistent with this\n" +" License. However, in accepting such obligations, You may act only\n" +" on Your own behalf and on Your sole responsibility, not on behalf\n" +" of any other Contributor, and only if You agree to indemnify,\n" +" defend, and hold each Contributor harmless for any liability\n" +" incurred by, or claims asserted against, such Contributor by reason\n" +" of your accepting any such warranty or additional liability.\n" +"\n" +"END OF TERMS AND CONDITIONS" +msgstr "" +" Apache License\n" +" Version 2.0, January 2004\n" +" https://www.apache.org/licenses/\n" +"\n" +"TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n" +"\n" +"1. Definitions.\n" +"\n" +" \"License\" shall mean the terms and conditions for use, reproduction,\n" +" and distribution as defined by Sections 1 through 9 of this document.\n" +"\n" +" \"Licensor\" shall mean the copyright owner or entity authorized by\n" +" the copyright owner that is granting the License.\n" +"\n" +" \"Legal Entity\" shall mean the union of the acting entity and all\n" +" other entities that control, are controlled by, or are under common\n" +" control with that entity. For the purposes of this definition,\n" +" \"control\" means (i) the power, direct or indirect, to cause the\n" +" direction or management of such entity, whether by contract or\n" +" otherwise, or (ii) ownership of fifty percent (50%) or more of the\n" +" outstanding shares, or (iii) beneficial ownership of such entity.\n" +"\n" +" \"You\" (or \"Your\") shall mean an individual or Legal Entity\n" +" exercising permissions granted by this License.\n" +"\n" +" \"Source\" form shall mean the preferred form for making modifications,\n" +" including but not limited to software source code, documentation\n" +" source, and configuration files.\n" +"\n" +" \"Object\" form shall mean any form resulting from mechanical\n" +" transformation or translation of a Source form, including but\n" +" not limited to compiled object code, generated documentation,\n" +" and conversions to other media types.\n" +"\n" +" \"Work\" shall mean the work of authorship, whether in Source or\n" +" Object form, made available under the License, as indicated by a\n" +" copyright notice that is included in or attached to the work\n" +" (an example is provided in the Appendix below).\n" +"\n" +" \"Derivative Works\" shall mean any work, whether in Source or Object\n" +" form, that is based on (or derived from) the Work and for which the\n" +" editorial revisions, annotations, elaborations, or other modifications\n" +" represent, as a whole, an original work of authorship. For the purposes\n" +" of this License, Derivative Works shall not include works that remain\n" +" separable from, or merely link (or bind by name) to the interfaces of,\n" +" the Work and Derivative Works thereof.\n" +"\n" +" \"Contribution\" shall mean any work of authorship, including\n" +" the original version of the Work and any modifications or additions\n" +" to that Work or Derivative Works thereof, that is intentionally\n" +" submitted to Licensor for inclusion in the Work by the copyright owner\n" +" or by an individual or Legal Entity authorized to submit on behalf of\n" +" the copyright owner. For the purposes of this definition, \"submitted\"\n" +" means any form of electronic, verbal, or written communication sent\n" +" to the Licensor or its representatives, including but not limited to\n" +" communication on electronic mailing lists, source code control systems,\n" +" and issue tracking systems that are managed by, or on behalf of, the\n" +" Licensor for the purpose of discussing and improving the Work, but\n" +" excluding communication that is conspicuously marked or otherwise\n" +" designated in writing by the copyright owner as \"Not a Contribution.\"\n" +"\n" +" \"Contributor\" shall mean Licensor and any individual or Legal Entity\n" +" on behalf of whom a Contribution has been received by Licensor and\n" +" subsequently incorporated within the Work.\n" +"\n" +"2. Grant of Copyright License. Subject to the terms and conditions of\n" +" this License, each Contributor hereby grants to You a perpetual,\n" +" worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n" +" copyright license to reproduce, prepare Derivative Works of,\n" +" publicly display, publicly perform, sublicense, and distribute the\n" +" Work and such Derivative Works in Source or Object form.\n" +"\n" +"3. Grant of Patent License. Subject to the terms and conditions of\n" +" this License, each Contributor hereby grants to You a perpetual,\n" +" worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n" +" (except as stated in this section) patent license to make, have made,\n" +" use, offer to sell, sell, import, and otherwise transfer the Work,\n" +" where such license applies only to those patent claims licensable\n" +" by such Contributor that are necessarily infringed by their\n" +" Contribution(s) alone or by combination of their Contribution(s)\n" +" with the Work to which such Contribution(s) was submitted. If You\n" +" institute patent litigation against any entity (including a\n" +" cross-claim or counterclaim in a lawsuit) alleging that the Work\n" +" or a Contribution incorporated within the Work constitutes direct\n" +" or contributory patent infringement, then any patent licenses\n" +" granted to You under this License for that Work shall terminate\n" +" as of the date such litigation is filed.\n" +"\n" +"4. Redistribution. You may reproduce and distribute copies of the\n" +" Work or Derivative Works thereof in any medium, with or without\n" +" modifications, and in Source or Object form, provided that You\n" +" meet the following conditions:\n" +"\n" +" (a) You must give any other recipients of the Work or\n" +" Derivative Works a copy of this License; and\n" +"\n" +" (b) You must cause any modified files to carry prominent notices\n" +" stating that You changed the files; and\n" +"\n" +" (c) You must retain, in the Source form of any Derivative Works\n" +" that You distribute, all copyright, patent, trademark, and\n" +" attribution notices from the Source form of the Work,\n" +" excluding those notices that do not pertain to any part of\n" +" the Derivative Works; and\n" +"\n" +" (d) If the Work includes a \"NOTICE\" text file as part of its\n" +" distribution, then any Derivative Works that You distribute must\n" +" include a readable copy of the attribution notices contained\n" +" within such NOTICE file, excluding those notices that do not\n" +" pertain to any part of the Derivative Works, in at least one\n" +" of the following places: within a NOTICE text file distributed\n" +" as part of the Derivative Works; within the Source form or\n" +" documentation, if provided along with the Derivative Works; or,\n" +" within a display generated by the Derivative Works, if and\n" +" wherever such third-party notices normally appear. The contents\n" +" of the NOTICE file are for informational purposes only and\n" +" do not modify the License. You may add Your own attribution\n" +" notices within Derivative Works that You distribute, alongside\n" +" or as an addendum to the NOTICE text from the Work, provided\n" +" that such additional attribution notices cannot be construed\n" +" as modifying the License.\n" +"\n" +" You may add Your own copyright statement to Your modifications and\n" +" may provide additional or different license terms and conditions\n" +" for use, reproduction, or distribution of Your modifications, or\n" +" for any such Derivative Works as a whole, provided Your use,\n" +" reproduction, and distribution of the Work otherwise complies with\n" +" the conditions stated in this License.\n" +"\n" +"5. Submission of Contributions. Unless You explicitly state otherwise,\n" +" any Contribution intentionally submitted for inclusion in the Work\n" +" by You to the Licensor shall be under the terms and conditions of\n" +" this License, without any additional terms or conditions.\n" +" Notwithstanding the above, nothing herein shall supersede or modify\n" +" the terms of any separate license agreement you may have executed\n" +" with Licensor regarding such Contributions.\n" +"\n" +"6. Trademarks. This License does not grant permission to use the trade\n" +" names, trademarks, service marks, or product names of the Licensor,\n" +" except as required for reasonable and customary use in describing the\n" +" origin of the Work and reproducing the content of the NOTICE file.\n" +"\n" +"7. Disclaimer of Warranty. Unless required by applicable law or\n" +" agreed to in writing, Licensor provides the Work (and each\n" +" Contributor provides its Contributions) on an \"AS IS\" BASIS,\n" +" WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n" +" implied, including, without limitation, any warranties or conditions\n" +" of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n" +" PARTICULAR PURPOSE. You are solely responsible for determining the\n" +" appropriateness of using or redistributing the Work and assume any\n" +" risks associated with Your exercise of permissions under this License.\n" +"\n" +"8. Limitation of Liability. In no event and under no legal theory,\n" +" whether in tort (including negligence), contract, or otherwise,\n" +" unless required by applicable law (such as deliberate and grossly\n" +" negligent acts) or agreed to in writing, shall any Contributor be\n" +" liable to You for damages, including any direct, indirect, special,\n" +" incidental, or consequential damages of any character arising as a\n" +" result of this License or out of the use or inability to use the\n" +" Work (including but not limited to damages for loss of goodwill,\n" +" work stoppage, computer failure or malfunction, or any and all\n" +" other commercial damages or losses), even if such Contributor\n" +" has been advised of the possibility of such damages.\n" +"\n" +"9. Accepting Warranty or Additional Liability. While redistributing\n" +" the Work or Derivative Works thereof, You may choose to offer,\n" +" and charge a fee for, acceptance of support, warranty, indemnity,\n" +" or other liability obligations and/or rights consistent with this\n" +" License. However, in accepting such obligations, You may act only\n" +" on Your own behalf and on Your sole responsibility, not on behalf\n" +" of any other Contributor, and only if You agree to indemnify,\n" +" defend, and hold each Contributor harmless for any liability\n" +" incurred by, or claims asserted against, such Contributor by reason\n" +" of your accepting any such warranty or additional liability.\n" +"\n" +"END OF TERMS AND CONDITIONS" + +#: ../../license.rst:848 msgid "expat" msgstr "expat" -#: ../../license.rst:847 +#: ../../license.rst:850 msgid "" "The :mod:`pyexpat ` extension is built using an included " "copy of the expat sources unless the build is configured ``--with-system-" @@ -476,11 +1958,57 @@ msgstr "" "incluída das fontes de expatriadas, a menos que a compilação esteja " "configurada ``--with-system-expat``::" -#: ../../license.rst:874 +#: ../../license.rst:853 +msgid "" +"Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd\n" +" and Clark Cooper\n" +"\n" +"Permission is hereby granted, free of charge, to any person obtaining\n" +"a copy of this software and associated documentation files (the\n" +"\"Software\"), to deal in the Software without restriction, including\n" +"without limitation the rights to use, copy, modify, merge, publish,\n" +"distribute, sublicense, and/or sell copies of the Software, and to\n" +"permit persons to whom the Software is furnished to do so, subject to\n" +"the following conditions:\n" +"\n" +"The above copyright notice and this permission notice shall be included\n" +"in all copies or substantial portions of the Software.\n" +"\n" +"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" +"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n" +"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n" +"IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n" +"CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n" +"TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n" +"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." +msgstr "" +"Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd\n" +" and Clark Cooper\n" +"\n" +"Permission is hereby granted, free of charge, to any person obtaining\n" +"a copy of this software and associated documentation files (the\n" +"\"Software\"), to deal in the Software without restriction, including\n" +"without limitation the rights to use, copy, modify, merge, publish,\n" +"distribute, sublicense, and/or sell copies of the Software, and to\n" +"permit persons to whom the Software is furnished to do so, subject to\n" +"the following conditions:\n" +"\n" +"The above copyright notice and this permission notice shall be included\n" +"in all copies or substantial portions of the Software.\n" +"\n" +"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" +"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n" +"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n" +"IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n" +"CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n" +"TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n" +"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." + +#: ../../license.rst:877 msgid "libffi" msgstr "libffi" -#: ../../license.rst:876 +#: ../../license.rst:879 msgid "" "The :mod:`!_ctypes` C extension underlying the :mod:`ctypes` module is built " "using an included copy of the libffi sources unless the build is configured " @@ -490,11 +2018,57 @@ msgstr "" "usando uma cópia incluída das fontes do libffi, a menos que a construção " "esteja configurada com ``--with-system-libffi``::" -#: ../../license.rst:904 +#: ../../license.rst:883 +msgid "" +"Copyright (c) 1996-2008 Red Hat, Inc and others.\n" +"\n" +"Permission is hereby granted, free of charge, to any person obtaining\n" +"a copy of this software and associated documentation files (the\n" +"\"Software\"), to deal in the Software without restriction, including\n" +"without limitation the rights to use, copy, modify, merge, publish,\n" +"distribute, sublicense, and/or sell copies of the Software, and to\n" +"permit persons to whom the Software is furnished to do so, subject to\n" +"the following conditions:\n" +"\n" +"The above copyright notice and this permission notice shall be included\n" +"in all copies or substantial portions of the Software.\n" +"\n" +"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" +"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n" +"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n" +"NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n" +"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n" +"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n" +"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n" +"DEALINGS IN THE SOFTWARE." +msgstr "" +"Copyright (c) 1996-2008 Red Hat, Inc and others.\n" +"\n" +"Permission is hereby granted, free of charge, to any person obtaining\n" +"a copy of this software and associated documentation files (the\n" +"\"Software\"), to deal in the Software without restriction, including\n" +"without limitation the rights to use, copy, modify, merge, publish,\n" +"distribute, sublicense, and/or sell copies of the Software, and to\n" +"permit persons to whom the Software is furnished to do so, subject to\n" +"the following conditions:\n" +"\n" +"The above copyright notice and this permission notice shall be included\n" +"in all copies or substantial portions of the Software.\n" +"\n" +"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" +"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n" +"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n" +"NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n" +"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n" +"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n" +"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n" +"DEALINGS IN THE SOFTWARE." + +#: ../../license.rst:907 msgid "zlib" msgstr "zlib" -#: ../../license.rst:906 +#: ../../license.rst:909 msgid "" "The :mod:`zlib` extension is built using an included copy of the zlib " "sources if the zlib version found on the system is too old to be used for " @@ -504,11 +2078,59 @@ msgstr "" "zlib se a versão do zlib encontrada no sistema for muito antiga para ser " "usada na construção::" -#: ../../license.rst:935 +#: ../../license.rst:913 +msgid "" +"Copyright (C) 1995-2011 Jean-loup Gailly and Mark Adler\n" +"\n" +"This software is provided 'as-is', without any express or implied\n" +"warranty. In no event will the authors be held liable for any damages\n" +"arising from the use of this software.\n" +"\n" +"Permission is granted to anyone to use this software for any purpose,\n" +"including commercial applications, and to alter it and redistribute it\n" +"freely, subject to the following restrictions:\n" +"\n" +"1. The origin of this software must not be misrepresented; you must not\n" +" claim that you wrote the original software. If you use this software\n" +" in a product, an acknowledgment in the product documentation would be\n" +" appreciated but is not required.\n" +"\n" +"2. Altered source versions must be plainly marked as such, and must not be\n" +" misrepresented as being the original software.\n" +"\n" +"3. This notice may not be removed or altered from any source distribution.\n" +"\n" +"Jean-loup Gailly Mark Adler\n" +"jloup@gzip.org madler@alumni.caltech.edu" +msgstr "" +"Copyright (C) 1995-2011 Jean-loup Gailly and Mark Adler\n" +"\n" +"This software is provided 'as-is', without any express or implied\n" +"warranty. In no event will the authors be held liable for any damages\n" +"arising from the use of this software.\n" +"\n" +"Permission is granted to anyone to use this software for any purpose,\n" +"including commercial applications, and to alter it and redistribute it\n" +"freely, subject to the following restrictions:\n" +"\n" +"1. The origin of this software must not be misrepresented; you must not\n" +" claim that you wrote the original software. If you use this software\n" +" in a product, an acknowledgment in the product documentation would be\n" +" appreciated but is not required.\n" +"\n" +"2. Altered source versions must be plainly marked as such, and must not be\n" +" misrepresented as being the original software.\n" +"\n" +"3. This notice may not be removed or altered from any source distribution.\n" +"\n" +"Jean-loup Gailly Mark Adler\n" +"jloup@gzip.org madler@alumni.caltech.edu" + +#: ../../license.rst:938 msgid "cfuhash" msgstr "cfuhash" -#: ../../license.rst:937 +#: ../../license.rst:940 msgid "" "The implementation of the hash table used by the :mod:`tracemalloc` is based " "on the cfuhash project::" @@ -516,11 +2138,81 @@ msgstr "" "A implementação da tabela de hash usada pelo :mod:`tracemalloc` é baseada no " "projeto cfuhash::" -#: ../../license.rst:976 +#: ../../license.rst:943 +msgid "" +"Copyright (c) 2005 Don Owens\n" +"All rights reserved.\n" +"\n" +"This code is released under the BSD license:\n" +"\n" +"Redistribution and use in source and binary forms, with or without\n" +"modification, are permitted provided that the following conditions\n" +"are met:\n" +"\n" +" * Redistributions of source code must retain the above copyright\n" +" notice, this list of conditions and the following disclaimer.\n" +"\n" +" * Redistributions in binary form must reproduce the above\n" +" copyright notice, this list of conditions and the following\n" +" disclaimer in the documentation and/or other materials provided\n" +" with the distribution.\n" +"\n" +" * Neither the name of the author nor the names of its\n" +" contributors may be used to endorse or promote products derived\n" +" from this software without specific prior written permission.\n" +"\n" +"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" +"\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" +"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n" +"FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n" +"COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n" +"INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n" +"(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n" +"SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n" +"HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n" +"STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n" +"ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n" +"OF THE POSSIBILITY OF SUCH DAMAGE." +msgstr "" +"Copyright (c) 2005 Don Owens\n" +"All rights reserved.\n" +"\n" +"This code is released under the BSD license:\n" +"\n" +"Redistribution and use in source and binary forms, with or without\n" +"modification, are permitted provided that the following conditions\n" +"are met:\n" +"\n" +" * Redistributions of source code must retain the above copyright\n" +" notice, this list of conditions and the following disclaimer.\n" +"\n" +" * Redistributions in binary form must reproduce the above\n" +" copyright notice, this list of conditions and the following\n" +" disclaimer in the documentation and/or other materials provided\n" +" with the distribution.\n" +"\n" +" * Neither the name of the author nor the names of its\n" +" contributors may be used to endorse or promote products derived\n" +" from this software without specific prior written permission.\n" +"\n" +"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" +"\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" +"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n" +"FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n" +"COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n" +"INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n" +"(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n" +"SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n" +"HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n" +"STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n" +"ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n" +"OF THE POSSIBILITY OF SUCH DAMAGE." + +#: ../../license.rst:979 msgid "libmpdec" msgstr "libmpdec" -#: ../../license.rst:978 +#: ../../license.rst:981 msgid "" "The :mod:`!_decimal` C extension underlying the :mod:`decimal` module is " "built using an included copy of the libmpdec library unless the build is " @@ -530,11 +2222,63 @@ msgstr "" "construída usando uma cópia incluída da biblioteca libmpdec, a menos que a " "construção esteja configurada com ``--with-system-libmpdec``::" -#: ../../license.rst:1009 +#: ../../license.rst:985 +msgid "" +"Copyright (c) 2008-2020 Stefan Krah. All rights reserved.\n" +"\n" +"Redistribution and use in source and binary forms, with or without\n" +"modification, are permitted provided that the following conditions\n" +"are met:\n" +"\n" +"1. Redistributions of source code must retain the above copyright\n" +" notice, this list of conditions and the following disclaimer.\n" +"\n" +"2. Redistributions in binary form must reproduce the above copyright\n" +" notice, this list of conditions and the following disclaimer in the\n" +" documentation and/or other materials provided with the distribution.\n" +"\n" +"THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND\n" +"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" +"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" +"ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n" +"FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n" +"DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n" +"OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n" +"HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n" +"LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n" +"OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n" +"SUCH DAMAGE." +msgstr "" +"Copyright (c) 2008-2020 Stefan Krah. All rights reserved.\n" +"\n" +"Redistribution and use in source and binary forms, with or without\n" +"modification, are permitted provided that the following conditions\n" +"are met:\n" +"\n" +"1. Redistributions of source code must retain the above copyright\n" +" notice, this list of conditions and the following disclaimer.\n" +"\n" +"2. Redistributions in binary form must reproduce the above copyright\n" +" notice, this list of conditions and the following disclaimer in the\n" +" documentation and/or other materials provided with the distribution.\n" +"\n" +"THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND\n" +"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" +"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" +"ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n" +"FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n" +"DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n" +"OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n" +"HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n" +"LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n" +"OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n" +"SUCH DAMAGE." + +#: ../../license.rst:1012 msgid "W3C C14N test suite" msgstr "Conjunto de testes C14N do W3C" -#: ../../license.rst:1011 +#: ../../license.rst:1014 msgid "" "The C14N 2.0 test suite in the :mod:`test` package (``Lib/test/xmltestdata/" "c14n-20/``) was retrieved from the W3C website at https://www.w3.org/TR/xml-" @@ -544,19 +2288,133 @@ msgstr "" "c14n-20/``) foi recuperado do site do W3C em https://www.w3.org/TR/xml-c14n2-" "testcases/ e é distribuído sob a licença BSD de 3 cláusulas::" -#: ../../license.rst:1048 +#: ../../license.rst:1019 +msgid "" +"Copyright (c) 2013 W3C(R) (MIT, ERCIM, Keio, Beihang),\n" +"All Rights Reserved.\n" +"\n" +"Redistribution and use in source and binary forms, with or without\n" +"modification, are permitted provided that the following conditions\n" +"are met:\n" +"\n" +"* Redistributions of works must retain the original copyright notice,\n" +" this list of conditions and the following disclaimer.\n" +"* Redistributions in binary form must reproduce the original copyright\n" +" notice, this list of conditions and the following disclaimer in the\n" +" documentation and/or other materials provided with the distribution.\n" +"* Neither the name of the W3C nor the names of its contributors may be\n" +" used to endorse or promote products derived from this work without\n" +" specific prior written permission.\n" +"\n" +"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" +"\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" +"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" +"A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n" +"OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" +"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n" +"LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" +"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" +"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" +"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" +"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +msgstr "" +"Copyright (c) 2013 W3C(R) (MIT, ERCIM, Keio, Beihang),\n" +"All Rights Reserved.\n" +"\n" +"Redistribution and use in source and binary forms, with or without\n" +"modification, are permitted provided that the following conditions\n" +"are met:\n" +"\n" +"* Redistributions of works must retain the original copyright notice,\n" +" this list of conditions and the following disclaimer.\n" +"* Redistributions in binary form must reproduce the original copyright\n" +" notice, this list of conditions and the following disclaimer in the\n" +" documentation and/or other materials provided with the distribution.\n" +"* Neither the name of the W3C nor the names of its contributors may be\n" +" used to endorse or promote products derived from this work without\n" +" specific prior written permission.\n" +"\n" +"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" +"\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" +"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" +"A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n" +"OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" +"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n" +"LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" +"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" +"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" +"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" +"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + +#: ../../license.rst:1051 msgid "mimalloc" msgstr "mimalloc" -#: ../../license.rst:1050 +#: ../../license.rst:1053 msgid "MIT License::" msgstr "Licença MIT::" -#: ../../license.rst:1074 +#: ../../license.rst:1055 +msgid "" +"Copyright (c) 2018-2021 Microsoft Corporation, Daan Leijen\n" +"\n" +"Permission is hereby granted, free of charge, to any person obtaining a " +"copy\n" +"of this software and associated documentation files (the \"Software\"), to " +"deal\n" +"in the Software without restriction, including without limitation the " +"rights\n" +"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n" +"copies of the Software, and to permit persons to whom the Software is\n" +"furnished to do so, subject to the following conditions:\n" +"\n" +"The above copyright notice and this permission notice shall be included in " +"all\n" +"copies or substantial portions of the Software.\n" +"\n" +"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS " +"OR\n" +"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n" +"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n" +"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n" +"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING " +"FROM,\n" +"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN " +"THE\n" +"SOFTWARE." +msgstr "" +"Copyright (c) 2018-2021 Microsoft Corporation, Daan Leijen\n" +"\n" +"Permission is hereby granted, free of charge, to any person obtaining a " +"copy\n" +"of this software and associated documentation files (the \"Software\"), to " +"deal\n" +"in the Software without restriction, including without limitation the " +"rights\n" +"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n" +"copies of the Software, and to permit persons to whom the Software is\n" +"furnished to do so, subject to the following conditions:\n" +"\n" +"The above copyright notice and this permission notice shall be included in " +"all\n" +"copies or substantial portions of the Software.\n" +"\n" +"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS " +"OR\n" +"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n" +"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n" +"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n" +"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING " +"FROM,\n" +"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN " +"THE\n" +"SOFTWARE." + +#: ../../license.rst:1077 msgid "asyncio" msgstr "asyncio" -#: ../../license.rst:1076 +#: ../../license.rst:1079 msgid "" "Parts of the :mod:`asyncio` module are incorporated from `uvloop 0.16 " "`_, which is distributed " @@ -566,11 +2424,55 @@ msgstr "" "github.com/MagicStack/uvloop/tree/v0.16.0>`_, que é distribuído sob a " "licença MIT::" -#: ../../license.rst:1103 +#: ../../license.rst:1083 +msgid "" +"Copyright (c) 2015-2021 MagicStack Inc. http://magic.io\n" +"\n" +"Permission is hereby granted, free of charge, to any person obtaining\n" +"a copy of this software and associated documentation files (the\n" +"\"Software\"), to deal in the Software without restriction, including\n" +"without limitation the rights to use, copy, modify, merge, publish,\n" +"distribute, sublicense, and/or sell copies of the Software, and to\n" +"permit persons to whom the Software is furnished to do so, subject to\n" +"the following conditions:\n" +"\n" +"The above copyright notice and this permission notice shall be\n" +"included in all copies or substantial portions of the Software.\n" +"\n" +"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" +"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n" +"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n" +"NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n" +"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n" +"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n" +"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." +msgstr "" +"Copyright (c) 2015-2021 MagicStack Inc. http://magic.io\n" +"\n" +"Permission is hereby granted, free of charge, to any person obtaining\n" +"a copy of this software and associated documentation files (the\n" +"\"Software\"), to deal in the Software without restriction, including\n" +"without limitation the rights to use, copy, modify, merge, publish,\n" +"distribute, sublicense, and/or sell copies of the Software, and to\n" +"permit persons to whom the Software is furnished to do so, subject to\n" +"the following conditions:\n" +"\n" +"The above copyright notice and this permission notice shall be\n" +"included in all copies or substantial portions of the Software.\n" +"\n" +"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" +"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n" +"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n" +"NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n" +"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n" +"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n" +"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." + +#: ../../license.rst:1106 msgid "Global Unbounded Sequences (GUS)" msgstr "Global Unbounded Sequences (GUS)" -#: ../../license.rst:1105 +#: ../../license.rst:1108 msgid "" "The file :file:`Python/qsbr.c` is adapted from FreeBSD's \"Global Unbounded " "Sequences\" safe memory reclamation scheme in `subr_smr.c `_. O " "arquivo é distribuído sob a licença BSD de 2 cláusulas::" + +#: ../../license.rst:1113 +msgid "" +"Copyright (c) 2019,2020 Jeffrey Roberson \n" +"\n" +"Redistribution and use in source and binary forms, with or without\n" +"modification, are permitted provided that the following conditions\n" +"are met:\n" +"1. Redistributions of source code must retain the above copyright\n" +" notice unmodified, this list of conditions, and the following\n" +" disclaimer.\n" +"2. Redistributions in binary form must reproduce the above copyright\n" +" notice, this list of conditions and the following disclaimer in the\n" +" documentation and/or other materials provided with the distribution.\n" +"\n" +"THIS SOFTWARE IS PROVIDED BY THE AUTHOR \"AS IS\" AND ANY EXPRESS OR\n" +"IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n" +"OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n" +"IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n" +"INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n" +"NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" +"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" +"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" +"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n" +"THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +msgstr "" +"Copyright (c) 2019,2020 Jeffrey Roberson \n" +"\n" +"Redistribution and use in source and binary forms, with or without\n" +"modification, are permitted provided that the following conditions\n" +"are met:\n" +"1. Redistributions of source code must retain the above copyright\n" +" notice unmodified, this list of conditions, and the following\n" +" disclaimer.\n" +"2. Redistributions in binary form must reproduce the above copyright\n" +" notice, this list of conditions and the following disclaimer in the\n" +" documentation and/or other materials provided with the distribution.\n" +"\n" +"THIS SOFTWARE IS PROVIDED BY THE AUTHOR \"AS IS\" AND ANY EXPRESS OR\n" +"IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n" +"OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n" +"IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n" +"INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n" +"NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" +"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" +"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" +"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n" +"THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." diff --git a/potodo.md b/potodo.md new file mode 100644 index 000000000..f8820e561 --- /dev/null +++ b/potodo.md @@ -0,0 +1,219 @@ + + +# 3.13 (98.55% done) + +- sphinx.po 101 / 111 ( 90.0% translated). + + +# c-api (54.59% done) + +- exceptions.po 194 / 370 ( 52.0% translated). +- float.po 15 / 35 ( 42.0% translated). +- frame.po 20 / 42 ( 47.0% translated). +- function.po 33 / 39 ( 84.0% translated). +- gcsupport.po 9 / 52 ( 17.0% translated). +- import.po 33 / 62 ( 53.0% translated). +- init.po 165 / 481 ( 34.0% translated). +- init_config.po 135 / 417 ( 32.0% translated). +- intro.po 96 / 140 ( 68.0% translated). +- long.po 37 / 104 ( 35.0% translated). +- memory.po 53 / 200 ( 26.0% translated). +- module.po 63 / 132 ( 47.0% translated). +- number.po 14 / 48 ( 29.0% translated). +- object.po 43 / 119 ( 36.0% translated). +- refcounting.po 4 / 48 ( 8.0% translated). +- structures.po 71 / 180 ( 39.0% translated). +- sys.po 28 / 75 ( 37.0% translated). +- type.po 19 / 102 ( 18.0% translated). +- typeobj.po 228 / 682 ( 33.0% translated). +- unicode.po 70 / 342 ( 20.0% translated). + + +# deprecations (100.00% done) + + + +# distributing (100.00% done) + + + +# extending (15.92% done) + +- embedding.po 4 / 59 ( 6.0% translated). +- extending.po 15 / 206 ( 7.0% translated). +- newtypes.po 8 / 117 ( 6.0% translated). +- newtypes_tutorial.po 25 / 177 ( 14.0% translated). + + +# faq (100.00% done) + + + +# howto (62.58% done) + +- curses.po 58 / 121 ( 47.0% translated). +- descriptor.po 187 / 230 ( 81.0% translated). +- enum.po 62 / 327 ( 18.0% translated). +- functional.po 138 / 252 ( 54.0% translated). +- isolating-extensions.po 132 / 134 ( 98.0% translated). +- logging-cookbook.po 40 / 421 ( 9.0% translated). +- logging.po 121 / 250 ( 48.0% translated). +- regex.po 317 / 332 ( 95.0% translated). +- sockets.po 35 / 63 ( 55.0% translated). +- sorting.po 46 / 75 ( 61.0% translated). +- unicode.po 30 / 145 ( 20.0% translated). +- urllib2.po 75 / 100 ( 75.0% translated). + + +# installing (100.00% done) + + + +# library (64.48% done) + +- array.po 84 / 86 ( 97.0% translated). +- asyncio-dev.po 16 / 54 ( 29.0% translated). +- asyncio-eventloop.po 308 / 409 ( 75.0% translated). +- asyncio-future.po 9 / 64 ( 14.0% translated). +- asyncio-platforms.po 6 / 26 ( 23.0% translated). +- asyncio-policy.po 10 / 68 ( 14.0% translated). +- asyncio-protocol.po 25 / 194 ( 12.0% translated). +- asyncio-runner.po 5 / 37 ( 13.0% translated). +- asyncio-stream.po 71 / 101 ( 70.0% translated). +- asyncio-sync.po 12 / 100 ( 12.0% translated). +- asyncio-task.po 141 / 268 ( 52.0% translated). +- base64.po 15 / 71 ( 21.0% translated). +- bdb.po 9 / 112 ( 8.0% translated). +- binascii.po 23 / 38 ( 60.0% translated). +- code.po 32 / 33 ( 96.0% translated). +- codecs.po 250 / 532 ( 46.0% translated). +- concurrent.futures.po 14 / 100 ( 14.0% translated). +- contextlib.po 55 / 172 ( 31.0% translated). +- ctypes.po 103 / 526 ( 19.0% translated). +- curses.po 66 / 486 ( 13.0% translated). +- dataclasses.po 45 / 155 ( 29.0% translated). +- decimal.po 370 / 378 ( 97.0% translated). +- difflib.po 14 / 140 ( 10.0% translated). +- dis.po 208 / 396 ( 52.0% translated). +- doctest.po 88 / 376 ( 23.0% translated). +- email.compat32-message.po 6 / 115 ( 5.0% translated). +- email.contentmanager.po 9 / 42 ( 21.0% translated). +- email.errors.po 6 / 26 ( 23.0% translated). +- email.examples.po 19 / 20 ( 95.0% translated). +- email.header.po 4 / 40 ( 10.0% translated). +- email.headerregistry.po 12 / 111 ( 10.0% translated). +- email.message.po 7 / 110 ( 6.0% translated). +- email.parser.po 3 / 48 ( 6.0% translated). +- email.policy.po 11 / 107 ( 10.0% translated). +- enum.po 73 / 244 ( 29.0% translated). +- errno.po 115 / 160 ( 71.0% translated). +- faulthandler.po 4 / 43 ( 9.0% translated). +- ftplib.po 11 / 99 ( 11.0% translated). +- functools.po 20 / 115 ( 17.0% translated). +- hashlib.po 75 / 170 ( 44.0% translated). +- html.parser.po 3 / 60 ( 5.0% translated). +- http.client.po 45 / 117 ( 38.0% translated). +- http.cookiejar.po 9 / 159 ( 5.0% translated). +- http.cookies.po 7 / 49 ( 14.0% translated). +- http.po 163 / 247 ( 65.0% translated). +- http.server.po 15 / 115 ( 13.0% translated). +- idle.po 17 / 293 ( 5.0% translated). +- imaplib.po 13 / 117 ( 11.0% translated). +- importlib.po 245 / 312 ( 78.0% translated). +- inspect.po 81 / 390 ( 20.0% translated). +- io.po 21 / 272 ( 7.0% translated). +- itertools.po 156 / 200 ( 78.0% translated). +- json.po 170 / 176 ( 96.0% translated). +- logging.config.po 18 / 171 ( 10.0% translated). +- logging.handlers.po 51 / 271 ( 18.0% translated). +- logging.po 99 / 369 ( 26.0% translated). +- mailbox.po 10 / 307 ( 3.0% translated). +- mimetypes.po 20 / 54 ( 37.0% translated). +- mmap.po 12 / 65 ( 18.0% translated). +- msvcrt.po 22 / 46 ( 47.0% translated). +- multiprocessing.po 328 / 596 ( 55.0% translated). +- pathlib.po 252 / 418 ( 60.0% translated). +- pickle.po 237 / 245 ( 96.0% translated). +- pkgutil.po 6 / 50 ( 12.0% translated). +- platform.po 74 / 87 ( 85.0% translated). +- poplib.po 10 / 53 ( 18.0% translated). +- profile.po 34 / 181 ( 18.0% translated). +- pyexpat.po 21 / 144 ( 14.0% translated). +- queue.po 9 / 53 ( 16.0% translated). +- sched.po 4 / 25 ( 16.0% translated). +- select.po 78 / 206 ( 37.0% translated). +- selectors.po 13 / 58 ( 22.0% translated). +- shelve.po 11 / 40 ( 27.0% translated). +- shlex.po 3 / 77 ( 3.0% translated). +- smtplib.po 30 / 116 ( 25.0% translated). +- socket.po 53 / 367 ( 14.0% translated). +- sqlite3.po 116 / 477 ( 24.0% translated). +- ssl.po 61 / 544 ( 11.0% translated). +- string.po 218 / 220 ( 99.0% translated). +- struct.po 96 / 195 ( 49.0% translated). +- subprocess.po 149 / 327 ( 45.0% translated). +- symtable.po 6 / 65 ( 9.0% translated). +- tarfile.po 103 / 337 ( 30.0% translated). +- tempfile.po 8 / 87 ( 9.0% translated). +- test.po 119 / 321 ( 37.0% translated). +- threading.po 34 / 274 ( 12.0% translated). +- timeit.po 52 / 68 ( 76.0% translated). +- tkinter.ttk.po 141 / 429 ( 32.0% translated). +- traceback.po 9 / 116 ( 7.0% translated). +- tracemalloc.po 21 / 156 ( 13.0% translated). +- typing.po 785 / 800 ( 98.0% translated). +- unicodedata.po 5 / 32 ( 15.0% translated). +- unittest.mock-examples.po 22 / 182 ( 12.0% translated). +- unittest.mock.po 103 / 448 ( 22.0% translated). +- unittest.po 281 / 537 ( 52.0% translated). +- urllib.parse.po 110 / 168 ( 65.0% translated). +- urllib.request.po 40 / 298 ( 13.0% translated). +- warnings.po 72 / 138 ( 52.0% translated). +- wave.po 17 / 54 ( 31.0% translated). +- winreg.po 30 / 176 ( 17.0% translated). +- wsgiref.po 78 / 134 ( 58.0% translated). +- xml.dom.minidom.po 6 / 56 ( 10.0% translated). +- xml.dom.po 67 / 235 ( 28.0% translated). +- xml.dom.pulldom.po 13 / 30 ( 43.0% translated). +- xml.etree.elementtree.po 67 / 266 ( 25.0% translated). +- xml.sax.handler.po 4 / 103 ( 3.0% translated). +- xml.sax.po 2 / 32 ( 6.0% translated). +- xml.sax.reader.po 2 / 75 ( 2.0% translated). +- xml.sax.utils.po 1 / 15 ( 6.0% translated). +- xmlrpc.client.po 54 / 113 ( 47.0% translated). +- zoneinfo.po 7 / 83 ( 8.0% translated). + + +# reference (99.97% done) + +- grammar.po 3 / 4 ( 75.0% translated). + + +# tutorial (100.00% done) + + + +# using (99.92% done) + +- cmdline.po 248 / 249 ( 99.0% translated). + + +# whatsnew (46.25% done) + +- 2.3.po 327 / 387 ( 84.0% translated). +- 2.4.po 266 / 319 ( 83.0% translated). +- 2.5.po 388 / 452 ( 85.0% translated). +- 2.6.po 542 / 626 ( 86.0% translated). +- 3.0.po 192 / 212 ( 90.0% translated). +- 3.1.po 114 / 132 ( 86.0% translated). +- 3.13.po 877 / 882 ( 99.0% translated). +- 3.2.po 65 / 576 ( 11.0% translated). +- 3.3.po 137 / 682 ( 20.0% translated). +- 3.5.po 125 / 578 ( 21.0% translated). +- 3.6.po 237 / 544 ( 43.0% translated). +- 3.7.po 252 / 568 ( 44.0% translated). +- changelog.po 2446 / 12353 ( 19.0% translated). + + +# TOTAL (61.46% done) + diff --git a/reference/compound_stmts.po b/reference/compound_stmts.po index cc9b8d4fc..1e26a5f86 100644 --- a/reference/compound_stmts.po +++ b/reference/compound_stmts.po @@ -1,35 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Alexandre B A Villares, 2021 -# Vinicius Gubiani Ferreira , 2023 -# felipe caridade fernandes , 2023 -# Octavio von Sydow , 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# Marco Rougeth , 2023 -# And Past , 2023 -# Augusta Carla Klug , 2023 -# Adorilson Bezerra , 2023 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:19+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-24 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -94,6 +84,10 @@ msgstr "" "não ficaria claro a qual cláusula :keyword:`if` a seguinte cláusula :keyword:" "`else` pertenceria::" +#: ../../reference/compound_stmts.rst:37 +msgid "if test1: if test2: print(x)" +msgstr "if test1: if test2: print(x)" + #: ../../reference/compound_stmts.rst:39 msgid "" "Also note that the semicolon binds tighter than the colon in this context, " @@ -104,6 +98,10 @@ msgstr "" "neste contexto, de modo que no exemplo a seguir, todas ou nenhuma das " "chamadas :func:`print` são executadas::" +#: ../../reference/compound_stmts.rst:43 +msgid "if x < y < z: print(x); print(y); print(z)" +msgstr "if x < y < z: print(x); print(y); print(z)" + #: ../../reference/compound_stmts.rst:45 msgid "Summarizing:" msgstr "Resumindo:" @@ -186,7 +184,7 @@ msgid "" "`continue` statement executed in the first suite skips the rest of the suite " "and goes back to testing the expression." msgstr "" -"Uma instrução :keyword:`break` executada no primeiro conjunto termina o loop " +"Uma instrução :keyword:`break` executada no primeiro conjunto termina o laço " "sem executar o conjunto da cláusula :keyword:`!else`. Uma instrução :keyword:" "`continue` executada no primeiro conjunto ignora o resto do conjunto e volta " "a testar a expressão." @@ -245,6 +243,19 @@ msgstr "" "todas as atribuições anteriores a essas variáveis, incluindo aquelas feitas " "no conjunto do laço for::" +#: ../../reference/compound_stmts.rst:183 +msgid "" +"for i in range(10):\n" +" print(i)\n" +" i = 5 # this will not affect the for-loop\n" +" # because i will be overwritten with the next\n" +" # index in the range" +msgstr "" +"for i in range(10):\n" +" print(i)\n" +" i = 5 # não afeta o laço for, porque i será\n" +" # substituída pelo índice seguinte no range" + #: ../../reference/compound_stmts.rst:193 msgid "" "Names in the target list are not deleted when the loop is finished, but if " @@ -377,10 +388,32 @@ msgstr "" "Quando uma exceção foi atribuída usando ``as target``, ela é limpa no final " "da cláusula :keyword:`!except`. É como se ::" +#: ../../reference/compound_stmts.rst:281 +msgid "" +"except E as N:\n" +" foo" +msgstr "" +"except E as N:\n" +" foo" + #: ../../reference/compound_stmts.rst:284 msgid "was translated to ::" msgstr "fosse traduzido para ::" +#: ../../reference/compound_stmts.rst:286 +msgid "" +"except E as N:\n" +" try:\n" +" foo\n" +" finally:\n" +" del N" +msgstr "" +"except E as N:\n" +" try:\n" +" foo\n" +" finally:\n" +" del N" + #: ../../reference/compound_stmts.rst:292 msgid "" "This means the exception must be assigned to a different name to be able to " @@ -409,6 +442,44 @@ msgstr "" "sair de um manipulador de exceções, a exceção armazenada no módulo :mod:" "`sys` é redefinida para seu valor anterior::" +#: ../../reference/compound_stmts.rst:308 +msgid "" +">>> print(sys.exception())\n" +"None\n" +">>> try:\n" +"... raise TypeError\n" +"... except:\n" +"... print(repr(sys.exception()))\n" +"... try:\n" +"... raise ValueError\n" +"... except:\n" +"... print(repr(sys.exception()))\n" +"... print(repr(sys.exception()))\n" +"...\n" +"TypeError()\n" +"ValueError()\n" +"TypeError()\n" +">>> print(sys.exception())\n" +"None" +msgstr "" +">>> print(sys.exception())\n" +"None\n" +">>> try:\n" +"... raise TypeError\n" +"... except:\n" +"... print(repr(sys.exception()))\n" +"... try:\n" +"... raise ValueError\n" +"... except:\n" +"... print(repr(sys.exception()))\n" +"... print(repr(sys.exception()))\n" +"...\n" +"TypeError()\n" +"ValueError()\n" +"TypeError()\n" +">>> print(sys.exception())\n" +"None" + #: ../../reference/compound_stmts.rst:333 msgid ":keyword:`!except*` clause" msgstr "Cláusula :keyword:`!except*`" @@ -435,6 +506,42 @@ msgstr "" "todas as exceções correspondentes. Cada exceção no grupo é manipulada por no " "máximo uma cláusula :keyword:`!except*`, a primeira que corresponde a ela. ::" +#: ../../reference/compound_stmts.rst:345 +msgid "" +">>> try:\n" +"... raise ExceptionGroup(\"eg\",\n" +"... [ValueError(1), TypeError(2), OSError(3), OSError(4)])\n" +"... except* TypeError as e:\n" +"... print(f'caught {type(e)} with nested {e.exceptions}')\n" +"... except* OSError as e:\n" +"... print(f'caught {type(e)} with nested {e.exceptions}')\n" +"...\n" +"caught with nested (TypeError(2),)\n" +"caught with nested (OSError(3), OSError(4))\n" +" + Exception Group Traceback (most recent call last):\n" +" | File \"\", line 2, in \n" +" | ExceptionGroup: eg\n" +" +-+---------------- 1 ----------------\n" +" | ValueError: 1\n" +" +------------------------------------" +msgstr "" +">>> try:\n" +"... raise ExceptionGroup(\"eg\",\n" +"... [ValueError(1), TypeError(2), OSError(3), OSError(4)])\n" +"... except* TypeError as e:\n" +"... print(f'caught {type(e)} with nested {e.exceptions}')\n" +"... except* OSError as e:\n" +"... print(f'caught {type(e)} with nested {e.exceptions}')\n" +"...\n" +"caught with nested (TypeError(2),)\n" +"caught with nested (OSError(3), OSError(4))\n" +" + Exception Group Traceback (most recent call last):\n" +" | File \"\", line 2, in \n" +" | ExceptionGroup: eg\n" +" +-+---------------- 1 ----------------\n" +" | ValueError: 1\n" +" +------------------------------------" + #: ../../reference/compound_stmts.rst:363 msgid "" "Any remaining exceptions that were not handled by any :keyword:`!except*` " @@ -458,6 +565,22 @@ msgstr "" "a uma das cláusulas :keyword:`!except*`, ela será capturada e encapsulada " "por um grupo de exceções com uma string de mensagem vazia. ::" +#: ../../reference/compound_stmts.rst:373 +msgid "" +">>> try:\n" +"... raise BlockingIOError\n" +"... except* BlockingIOError as e:\n" +"... print(repr(e))\n" +"...\n" +"ExceptionGroup('', (BlockingIOError()))" +msgstr "" +">>> try:\n" +"... raise BlockingIOError\n" +"... except* BlockingIOError as e:\n" +"... print(repr(e))\n" +"...\n" +"ExceptionGroup('', (BlockingIOError()))" + #: ../../reference/compound_stmts.rst:380 msgid "" "An :keyword:`!except*` clause must have a matching expression; it cannot be " @@ -524,6 +647,26 @@ msgstr "" "keyword:`!finally` executar uma instrução :keyword:`return`, :keyword:" "`break` ou :keyword:`continue`, a exceção salva será descartada::" +#: ../../reference/compound_stmts.rst:425 +msgid "" +">>> def f():\n" +"... try:\n" +"... 1/0\n" +"... finally:\n" +"... return 42\n" +"...\n" +">>> f()\n" +"42" +msgstr "" +">>> def f():\n" +"... try:\n" +"... 1/0\n" +"... finally:\n" +"... return 42\n" +"...\n" +">>> f()\n" +"42" + #: ../../reference/compound_stmts.rst:434 msgid "" "The exception information is not available to the program during execution " @@ -556,6 +699,26 @@ msgstr "" "executada, uma instrução :keyword:`!return` executada na cláusula :keyword:`!" "finally` sempre será a última executada::" +#: ../../reference/compound_stmts.rst:451 +msgid "" +">>> def foo():\n" +"... try:\n" +"... return 'try'\n" +"... finally:\n" +"... return 'finally'\n" +"...\n" +">>> foo()\n" +"'finally'" +msgstr "" +">>> def foo():\n" +"... try:\n" +"... return 'try'\n" +"... finally:\n" +"... return 'finally'\n" +"...\n" +">>> foo()\n" +"'finally'" + #: ../../reference/compound_stmts.rst:460 msgid "" "Prior to Python 3.8, a :keyword:`continue` statement was illegal in the :" @@ -650,7 +813,7 @@ msgid "" msgstr "" "O método :meth:`~object.__exit__` do gerenciador de contexto é invocado. Se " "uma exceção fez com que o conjunto fosse encerrado, seu tipo, valor e " -"traceback são passados ​​como argumentos para :meth:`~object.__exit__`. Caso " +"traceback são passados como argumentos para :meth:`~object.__exit__`. Caso " "contrário, três argumentos :const:`None` são fornecidos." #: ../../reference/compound_stmts.rst:517 @@ -676,25 +839,87 @@ msgstr "" "prossegue no local normal para o tipo de saída que foi realizada." #: ../../reference/compound_stmts.rst:526 -#: ../../reference/compound_stmts.rst:1541 -#: ../../reference/compound_stmts.rst:1582 +#: ../../reference/compound_stmts.rst:1549 +#: ../../reference/compound_stmts.rst:1590 msgid "The following code::" msgstr "O seguinte código::" +#: ../../reference/compound_stmts.rst:528 +msgid "" +"with EXPRESSION as TARGET:\n" +" SUITE" +msgstr "" +"with EXPRESSION as TARGET:\n" +" SUITE" + #: ../../reference/compound_stmts.rst:531 #: ../../reference/compound_stmts.rst:556 -#: ../../reference/compound_stmts.rst:1587 +#: ../../reference/compound_stmts.rst:1595 msgid "is semantically equivalent to::" msgstr "é semanticamente equivalente a::" +#: ../../reference/compound_stmts.rst:533 +msgid "" +"manager = (EXPRESSION)\n" +"enter = type(manager).__enter__\n" +"exit = type(manager).__exit__\n" +"value = enter(manager)\n" +"hit_except = False\n" +"\n" +"try:\n" +" TARGET = value\n" +" SUITE\n" +"except:\n" +" hit_except = True\n" +" if not exit(manager, *sys.exc_info()):\n" +" raise\n" +"finally:\n" +" if not hit_except:\n" +" exit(manager, None, None, None)" +msgstr "" +"manager = (EXPRESSION)\n" +"enter = type(manager).__enter__\n" +"exit = type(manager).__exit__\n" +"value = enter(manager)\n" +"hit_except = False\n" +"\n" +"try:\n" +" TARGET = value\n" +" SUITE\n" +"except:\n" +" hit_except = True\n" +" if not exit(manager, *sys.exc_info()):\n" +" raise\n" +"finally:\n" +" if not hit_except:\n" +" exit(manager, None, None, None)" + #: ../../reference/compound_stmts.rst:550 msgid "" "With more than one item, the context managers are processed as if multiple :" "keyword:`with` statements were nested::" msgstr "" -"Com mais de um item, os gerenciadores de contexto são processados ​​como se " +"Com mais de um item, os gerenciadores de contexto são processados como se " "várias instruções :keyword:`with` estivessem aninhadas::" +#: ../../reference/compound_stmts.rst:553 +msgid "" +"with A() as a, B() as b:\n" +" SUITE" +msgstr "" +"with A() as a, B() as b:\n" +" SUITE" + +#: ../../reference/compound_stmts.rst:558 +msgid "" +"with A() as a:\n" +" with B() as b:\n" +" SUITE" +msgstr "" +"with A() as a:\n" +" with B() as b:\n" +" SUITE" + #: ../../reference/compound_stmts.rst:562 msgid "" "You can also write multi-item context managers in multiple lines if the " @@ -703,6 +928,20 @@ msgstr "" "Você também pode escrever gerenciadores de contexto multi-item em várias " "linhas se os itens estiverem entre parênteses. Por exemplo::" +#: ../../reference/compound_stmts.rst:565 +msgid "" +"with (\n" +" A() as a,\n" +" B() as b,\n" +"):\n" +" SUITE" +msgstr "" +"with (\n" +" A() as a,\n" +" B() as b,\n" +"):\n" +" SUITE" + #: ../../reference/compound_stmts.rst:571 msgid "Support for multiple context expressions." msgstr "Suporte para múltiplas expressões de contexto." @@ -829,7 +1068,7 @@ msgid "" msgstr "" "Durante correspondências de padrões com falha, alguns subpadrões podem ter " "sucesso. Não confie em vinculações sendo feitas para uma correspondência com " -"falha. Por outro lado, não confie em variáveis ​​permanecendo inalteradas após " +"falha. Por outro lado, não confie em variáveis permanecendo inalteradas após " "uma correspondência com falha. O comportamento exato depende da " "implementação e pode variar. Esta é uma decisão intencional feita para " "permitir que diferentes implementações adicionem otimizações." @@ -875,6 +1114,35 @@ msgstr "" msgid "A sample match statement::" msgstr "Um exemplo de instrução match::" +#: ../../reference/compound_stmts.rst:673 +msgid "" +">>> flag = False\n" +">>> match (100, 200):\n" +"... case (100, 300): # Mismatch: 200 != 300\n" +"... print('Case 1')\n" +"... case (100, 200) if flag: # Successful match, but guard fails\n" +"... print('Case 2')\n" +"... case (100, y): # Matches and binds y to 200\n" +"... print(f'Case 3, y: {y}')\n" +"... case _: # Pattern not attempted\n" +"... print('Case 4, I match anything!')\n" +"...\n" +"Case 3, y: 200" +msgstr "" +">>> flag = False\n" +">>> match (100, 200):\n" +"... case (100, 300): # Não corresponde: 200 != 300\n" +"... print('Case 1')\n" +"... case (100, 200) if flag: # Corresponde com sucesso, mas o guard " +"falha...\n" +" print('Case 2')\n" +"... case (100, y): # Corresponde e vincula y a 200\n" +"... print(f'Case 3, y: {y}')\n" +"... case _: # Padrão não testado\n" +"... print('Case 4, I match anything!')\n" +"...\n" +"Case 3, y: 200" + #: ../../reference/compound_stmts.rst:687 msgid "" "In this case, ``if flag`` is a guard. Read more about that in the next " @@ -1013,7 +1281,7 @@ msgstr "" #: ../../reference/compound_stmts.rst:767 msgid "The top-level syntax for ``patterns`` is:" -msgstr "" +msgstr "Esta é a sintaxe de nível superior para ``patterns`` (padrões):" #: ../../reference/compound_stmts.rst:781 msgid "" @@ -1024,22 +1292,33 @@ msgid "" "the underlying implementation. Furthermore, they do not cover all valid " "forms." msgstr "" +"As descrições abaixo incluirão uma descrição \"em termos simples\" de o que " +"o padrão faz para fins ilustrativos (créditos a Raymond Hettinger pelo " +"documento que inspirou a maioria das descrições). Note que essas descrições " +"são puramente para fins ilustrativos, e **não necessariamente** refletem a " +"implementação subjacente. Além disso, elas não cobrem todas as formas " +"válidas." #: ../../reference/compound_stmts.rst:791 msgid "OR Patterns" -msgstr "" +msgstr "Padrões OR" #: ../../reference/compound_stmts.rst:793 msgid "" "An OR pattern is two or more patterns separated by vertical bars ``|``. " "Syntax:" msgstr "" +"Um padrão OR é composto por dois ou mais padrões separados por barras " +"verticais ``|``. Sintaxe:" #: ../../reference/compound_stmts.rst:799 msgid "" "Only the final subpattern may be :ref:`irrefutable `, and " "each subpattern must bind the same set of names to avoid ambiguity." msgstr "" +"Somente o último subpadrão pode ser :ref:`irrefutável `, e " +"cada subpadrão deve vincular o mesmo conjunto de nomes para evitar " +"ambiguidades." #: ../../reference/compound_stmts.rst:802 msgid "" @@ -1047,6 +1326,10 @@ msgid "" "until one succeeds. The OR pattern is then considered successful. " "Otherwise, if none of the subpatterns succeed, the OR pattern fails." msgstr "" +"Um padrão OR testa a correspondência de cada um dos seus subpadrões, em " +"sequência, ao valor do sujeito, até que uma delas seja bem sucedida. O " +"padrão OR é então considerado bem sucedido. Caso contrário, se todas elas " +"falharam, o padrão OR falhou." #: ../../reference/compound_stmts.rst:806 msgid "" @@ -1054,16 +1337,21 @@ msgid "" "will try to match ``P2``, succeeding immediately if any succeeds, failing " "otherwise." msgstr "" +"Em termos simples, ``P1 | P2 | ...`` vai tentar fazer corresponder ``P1``, " +"se falhar vai tentar ``P2``, declarando sucesso se houver sucesso em " +"qualquer uma das tentativas, e falhando caso contrário." #: ../../reference/compound_stmts.rst:812 msgid "AS Patterns" -msgstr "" +msgstr "Padrões AS" #: ../../reference/compound_stmts.rst:814 msgid "" "An AS pattern matches an OR pattern on the left of the :keyword:`as` keyword " "against a subject. Syntax:" msgstr "" +"Um padrão AS corresponde a um padrão OR à esquerda da palavra reservada :" +"keyword:`as` de um assunto. Sintaxe:" #: ../../reference/compound_stmts.rst:820 msgid "" @@ -1071,22 +1359,29 @@ msgid "" "binds the subject to the name on the right of the as keyword and succeeds. " "``capture_pattern`` cannot be a ``_``." msgstr "" +"Se o padrão OR falhar, o padrão AS falhará. Caso contrário, o padrão AS " +"vincula o assunto ao nome à direita da palavra-chave as e obtém sucesso. " +"``capture_pattern`` não pode ser um ``_``." #: ../../reference/compound_stmts.rst:824 msgid "" "In simple terms ``P as NAME`` will match with ``P``, and on success it will " "set ``NAME = ``." msgstr "" +"Em termos simples, ``P as NAME`` corresponderá a ``P`` e, em caso de " +"sucesso, definirá ``NAME = ``." #: ../../reference/compound_stmts.rst:831 msgid "Literal Patterns" -msgstr "" +msgstr "Padrões literais" #: ../../reference/compound_stmts.rst:833 msgid "" "A literal pattern corresponds to most :ref:`literals ` in Python. " "Syntax:" msgstr "" +"Um padrão literal corresponde à maioria dos :ref:`literais ` em " +"Python. Sintaxe:" #: ../../reference/compound_stmts.rst:846 msgid "" @@ -1095,6 +1390,10 @@ msgid "" "supported. Raw strings and byte strings are supported. :ref:`f-strings` " "are not supported." msgstr "" +"A regra ``strings`` e o token ``NUMBER`` são definidos na :doc:`gramática " +"Python padrão <./grammar>`. Strings entre aspas triplas são suportadas. " +"Strings brutas e strings de bytes são suportadas. :ref:`f-strings` não são " +"suportadas." #: ../../reference/compound_stmts.rst:851 msgid "" @@ -1102,6 +1401,9 @@ msgid "" "for expressing :ref:`complex numbers `; they require a real " "number on the left and an imaginary number on the right. E.g. ``3 + 4j``." msgstr "" +"As formas ``signed_number '+' NUMBER`` e ``signed_number '-' NUMBER`` são " +"para expressar :ref:`números complexos `; elas requerem um número " +"real à esquerda e um número imaginário à direita. Por exemplo, ``3 + 4j``." #: ../../reference/compound_stmts.rst:855 msgid "" @@ -1109,14 +1411,17 @@ msgid "" "For the singletons ``None``, ``True`` and ``False``, the :keyword:`is` " "operator is used." msgstr "" +"Em termos simples, ``LITERAL`` terá sucesso somente se `` == " +"LITERAL``. Para os singletons ``None``, ``True`` e ``False``, o operador :" +"keyword:`is` é usado." #: ../../reference/compound_stmts.rst:861 msgid "Capture Patterns" -msgstr "" +msgstr "Padrões de captura" #: ../../reference/compound_stmts.rst:863 msgid "A capture pattern binds the subject value to a name. Syntax:" -msgstr "" +msgstr "Um padrão de captura vincula o valor do assunto a um nome. Sintaxe:" #: ../../reference/compound_stmts.rst:869 msgid "" @@ -1124,12 +1429,18 @@ msgid "" "expresses). It is instead treated as a :token:`~python-grammar:" "wildcard_pattern`." msgstr "" +"Um único sublinhado ``_`` não é um padrão de captura (é o que ``!'_'`` " +"expressa). Em vez disso, ele é tratado como um :token:`~python-grammar:" +"wildcard_pattern`." #: ../../reference/compound_stmts.rst:873 msgid "" "In a given pattern, a given name can only be bound once. E.g. ``case x, " "x: ...`` is invalid while ``case [x] | x: ...`` is allowed." msgstr "" +"Em um determinado padrão, um determinado nome só pode ser vinculado uma vez. " +"Por exemplo, ``case x, x: ...`` é inválido enquanto ``case [x] | x: ...`` é " +"permitido." #: ../../reference/compound_stmts.rst:876 msgid "" @@ -1138,22 +1449,31 @@ msgid "" "becomes a local variable in the closest containing function scope unless " "there's an applicable :keyword:`global` or :keyword:`nonlocal` statement." msgstr "" +"Os padrões de captura sempre são bem-sucedidos. A vinculação segue regras de " +"escopo estabelecidas pelo operador de expressão de atribuição na :pep:`572`; " +"o nome se torna uma variável local no escopo de função de contenção mais " +"próximo, a menos que haja uma instrução :keyword:`global` ou :keyword:" +"`nonlocal` aplicável." #: ../../reference/compound_stmts.rst:881 msgid "" "In simple terms ``NAME`` will always succeed and it will set ``NAME = " "``." msgstr "" +"Em termos simples, ``NAME`` sempre terá sucesso e definirá ``NAME = " +"``." #: ../../reference/compound_stmts.rst:886 msgid "Wildcard Patterns" -msgstr "" +msgstr "Padrões curingas" #: ../../reference/compound_stmts.rst:888 msgid "" "A wildcard pattern always succeeds (matches anything) and binds no name. " "Syntax:" msgstr "" +"Um padrão curinga sempre tem sucesso (corresponde a qualquer coisa) e não " +"vincula nenhum nome. Sintaxe:" #: ../../reference/compound_stmts.rst:894 msgid "" @@ -1161,18 +1481,22 @@ msgid "" "within patterns. It is an identifier, as usual, even within ``match`` " "subject expressions, ``guard``\\ s, and ``case`` blocks." msgstr "" +"``_`` é uma :ref:`palavra reservada contextual ` dentro de " +"qualquer padrão, mas somente dentro de padrões. É um identificador, como de " +"costume, mesmo dentro de expressões de assunto ``match``\\ s, ``guard``\\ s " +"e blocos ``case``." #: ../../reference/compound_stmts.rst:898 msgid "In simple terms, ``_`` will always succeed." -msgstr "" +msgstr "Em termos simples, ``_`` sempre terá sucesso." #: ../../reference/compound_stmts.rst:903 msgid "Value Patterns" -msgstr "" +msgstr "Padrões de valor" #: ../../reference/compound_stmts.rst:905 msgid "A value pattern represents a named value in Python. Syntax:" -msgstr "" +msgstr "Um padrão de valor representa um valor nomeado em Python. Sintaxe:" #: ../../reference/compound_stmts.rst:913 msgid "" @@ -1180,12 +1504,18 @@ msgid "" "resolution rules `. The pattern succeeds if the value found " "compares equal to the subject value (using the ``==`` equality operator)." msgstr "" +"O nome pontilhado no padrão é pesquisado usando as :ref:`regras de resolução " +"de nomes ` padrão do Python. O padrão é bem-sucedido se o " +"valor encontrado for comparado igual ao valor do assunto (usando o operador " +"de igualdade ``==``)." #: ../../reference/compound_stmts.rst:918 msgid "" "In simple terms ``NAME1.NAME2`` will succeed only if `` == NAME1." "NAME2``" msgstr "" +"Em termos simples, ``NAME1.NAME2`` terá sucesso somente se `` == " +"NAME1.NAME2``" #: ../../reference/compound_stmts.rst:922 msgid "" @@ -1194,36 +1524,48 @@ msgid "" "the same lookup. This cache is strictly tied to a given execution of a " "given match statement." msgstr "" +"Se o mesmo valor ocorrer várias vezes na mesma instrução match, o " +"interpretador pode armazenar em cache o primeiro valor encontrado e " +"reutilizá-lo em vez de repetir a mesma pesquisa. Esse cache é estritamente " +"vinculado a uma determinada execução de uma determinada instrução match." #: ../../reference/compound_stmts.rst:930 msgid "Group Patterns" -msgstr "" +msgstr "Padrões de grupo" #: ../../reference/compound_stmts.rst:932 msgid "" "A group pattern allows users to add parentheses around patterns to emphasize " "the intended grouping. Otherwise, it has no additional syntax. Syntax:" msgstr "" +"Um padrão de grupo permite que os usuários adicionem parênteses em torno de " +"padrões para enfatizar o agrupamento pretendido. Caso contrário, não há " +"sintaxe adicional. Sintaxe:" #: ../../reference/compound_stmts.rst:939 msgid "In simple terms ``(P)`` has the same effect as ``P``." -msgstr "" +msgstr "Em termos simples, ``(P)`` tem o mesmo efeito que ``P``." #: ../../reference/compound_stmts.rst:944 msgid "Sequence Patterns" -msgstr "" +msgstr "Padrões de sequência" #: ../../reference/compound_stmts.rst:946 msgid "" "A sequence pattern contains several subpatterns to be matched against " "sequence elements. The syntax is similar to the unpacking of a list or tuple." msgstr "" +"Um padrão de sequência contém vários subpadrões a serem correspondidos com " +"elementos de sequência. A sintaxe é similar ao desempacotamento de uma lista " +"ou tupla." #: ../../reference/compound_stmts.rst:957 msgid "" "There is no difference if parentheses or square brackets are used for " "sequence patterns (i.e. ``(...)`` vs ``[...]`` )." msgstr "" +"Não há diferença se parênteses ou colchetes são usados para padrões de " +"sequência (por exemplo, ``(...)`` vs ``[...]``)." #: ../../reference/compound_stmts.rst:961 msgid "" @@ -1231,6 +1573,9 @@ msgid "" "| 4)``) is a :ref:`group pattern `. While a single pattern " "enclosed in square brackets (e.g. ``[3 | 4]``) is still a sequence pattern." msgstr "" +"Um único padrão entre parênteses sem uma vírgula final (por exemplo, ``(3 | " +"4)``) é um :ref:`padrão de grupo `. Enquanto um único padrão " +"entre colchetes (por exemplo, ``[3 | 4]``) ainda é um padrão de sequência." #: ../../reference/compound_stmts.rst:966 msgid "" @@ -1239,39 +1584,54 @@ msgid "" "sequence pattern is a fixed-length sequence pattern; otherwise it is a " "variable-length sequence pattern." msgstr "" +"No máximo um subpadrão de estrela pode estar em um padrão de sequência. O " +"subpadrão de estrela pode ocorrer em qualquer posição. Se nenhum subpadrão " +"de estrela estiver presente, o padrão de sequência é um padrão de sequência " +"de comprimento fixo; caso contrário, é um padrão de sequência de comprimento " +"variável." #: ../../reference/compound_stmts.rst:971 msgid "" "The following is the logical flow for matching a sequence pattern against a " "subject value:" msgstr "" +"A seguir está o fluxo lógico para corresponder um padrão de sequência com um " +"valor de assunto:" #: ../../reference/compound_stmts.rst:974 msgid "" "If the subject value is not a sequence [#]_, the sequence pattern fails." msgstr "" +"Se o valor do assunto não for uma sequência [#]_, o padrão de sequência " +"falhará." #: ../../reference/compound_stmts.rst:977 msgid "" "If the subject value is an instance of ``str``, ``bytes`` or ``bytearray`` " "the sequence pattern fails." msgstr "" +"Se o valor do assunto for uma instância de ``str``, ``bytes`` ou " +"``bytearray``, o padrão de sequência falhará." #: ../../reference/compound_stmts.rst:980 msgid "" "The subsequent steps depend on whether the sequence pattern is fixed or " "variable-length." msgstr "" +"As etapas subsequentes dependem se o padrão de sequência é fixo ou de " +"comprimento variável." #: ../../reference/compound_stmts.rst:983 msgid "If the sequence pattern is fixed-length:" -msgstr "" +msgstr "Se o padrão de sequência for de comprimento fixo:" #: ../../reference/compound_stmts.rst:985 msgid "" "If the length of the subject sequence is not equal to the number of " "subpatterns, the sequence pattern fails" msgstr "" +"Se o comprimento da sequência do assunto não for igual ao número de " +"subpadrões, o padrão da sequência falha" #: ../../reference/compound_stmts.rst:988 msgid "" @@ -1280,22 +1640,31 @@ msgid "" "subpattern fails. If all subpatterns succeed in matching their " "corresponding item, the sequence pattern succeeds." msgstr "" +"Subpadrões no padrão de sequência são correspondidos aos seus itens " +"correspondentes na sequência de assunto da esquerda para a direita. A " +"correspondência para assim que um subpadrão falha. Se todos os subpadrões " +"tiverem sucesso em corresponder ao seu item correspondente, o padrão de " +"sequência é bem-sucedido." #: ../../reference/compound_stmts.rst:993 msgid "Otherwise, if the sequence pattern is variable-length:" -msgstr "" +msgstr "Caso contrário, se o padrão de sequência for de comprimento variável:" #: ../../reference/compound_stmts.rst:995 msgid "" "If the length of the subject sequence is less than the number of non-star " "subpatterns, the sequence pattern fails." msgstr "" +"Se o comprimento da sequência do assunto for menor que o número de " +"subpadrões não-estrela, o padrão da sequência falha." #: ../../reference/compound_stmts.rst:998 msgid "" "The leading non-star subpatterns are matched to their corresponding items as " "for fixed-length sequences." msgstr "" +"Os principais subpadrões não estelares são correspondidos aos seus itens " +"correspondentes, como nas sequências de comprimento fixo." #: ../../reference/compound_stmts.rst:1001 msgid "" @@ -1303,12 +1672,17 @@ msgid "" "the remaining subject items, excluding the remaining items corresponding to " "non-star subpatterns following the star subpattern." msgstr "" +"Se a etapa anterior for bem-sucedida, o subpadrão estrela corresponde a uma " +"lista formada pelos itens de assunto restantes, excluindo os itens restantes " +"correspondentes aos subpadrões não-estrela que seguem o subpadrão estrela." #: ../../reference/compound_stmts.rst:1005 msgid "" "Remaining non-star subpatterns are matched to their corresponding subject " "items, as for a fixed-length sequence." msgstr "" +"Os subpadrões não-estrela restantes são correspondidos aos seus itens de " +"assunto correspondentes, como em uma sequência de comprimento fixo." #: ../../reference/compound_stmts.rst:1008 msgid "" @@ -1316,50 +1690,65 @@ msgid "" "the :meth:`__len__` protocol). This length may be cached by the interpreter " "in a similar manner as :ref:`value patterns `." msgstr "" +"O comprimento da sequência de assunto é obtido via :func:`len` (ou seja, via " +"protocolo :meth:`__len__`). Esse comprimento pode ser armazenado em cache " +"pelo interpretador de forma similar a :ref:`padrões de valor `." #: ../../reference/compound_stmts.rst:1014 msgid "" "In simple terms ``[P1, P2, P3,`` ... ``, P]`` matches only if all the " "following happens:" msgstr "" +"Em termos simples, ``[P1, P2, P3,`` ... ``, P]`` corresponde somente se " +"tudo o seguinte acontecer:" #: ../../reference/compound_stmts.rst:1017 msgid "check ```` is a sequence" -msgstr "" +msgstr "verifica se ```` é uma sequência" #: ../../reference/compound_stmts.rst:1018 msgid "``len(subject) == ``" -msgstr "" +msgstr "``len(subject) == ``" #: ../../reference/compound_stmts.rst:1019 msgid "" "``P1`` matches ``[0]`` (note that this match can also bind names)" msgstr "" +"``P1`` corresponde a ``[0]`` (observe que esta correspondência " +"também pode vincular nomes)" #: ../../reference/compound_stmts.rst:1020 msgid "" "``P2`` matches ``[1]`` (note that this match can also bind names)" msgstr "" +"``P2`` corresponde a ``[1]`` (observe que esta correspondência " +"também pode vincular nomes)" #: ../../reference/compound_stmts.rst:1021 msgid "... and so on for the corresponding pattern/element." -msgstr "" +msgstr "... e assim por diante para o padrão/elemento correspondente." #: ../../reference/compound_stmts.rst:1026 msgid "Mapping Patterns" -msgstr "" +msgstr "Padrões de mapeamento" #: ../../reference/compound_stmts.rst:1028 msgid "" "A mapping pattern contains one or more key-value patterns. The syntax is " "similar to the construction of a dictionary. Syntax:" msgstr "" +"Um padrão de mapeamento contém um ou mais padrões de chave-valor. A sintaxe " +"é similar à construção de um dicionário. Sintaxe:" #: ../../reference/compound_stmts.rst:1039 msgid "" "At most one double star pattern may be in a mapping pattern. The double " "star pattern must be the last subpattern in the mapping pattern." msgstr "" +"No máximo um padrão de estrela dupla pode estar em um padrão de mapeamento. " +"O padrão de estrela dupla deve ser o último subpadrão no padrão de " +"mapeamento." #: ../../reference/compound_stmts.rst:1042 msgid "" @@ -1367,16 +1756,24 @@ msgid "" "will raise a :exc:`SyntaxError`. Two keys that otherwise have the same value " "will raise a :exc:`ValueError` at runtime." msgstr "" +"Chaves duplicadas em padrões de mapeamento não são permitidas. Chaves " +"literais duplicadas levantarão um :exc:`SyntaxError`. Duas chaves que de " +"outra forma têm o mesmo valor levantarão :exc:`ValueError` em tempo de " +"execução." #: ../../reference/compound_stmts.rst:1046 msgid "" "The following is the logical flow for matching a mapping pattern against a " "subject value:" msgstr "" +"A seguir está o fluxo lógico para comparar um padrão de mapeamento com um " +"valor de assunto:" #: ../../reference/compound_stmts.rst:1049 msgid "If the subject value is not a mapping [#]_,the mapping pattern fails." msgstr "" +"Se o valor do assunto não for um mapeamento [#]_, o padrão de mapeamento " +"falhará." #: ../../reference/compound_stmts.rst:1051 msgid "" @@ -1384,6 +1781,10 @@ msgid "" "and the pattern for each key matches the corresponding item of the subject " "mapping, the mapping pattern succeeds." msgstr "" +"Se cada chave fornecida no padrão de mapeamento estiver presente no " +"mapeamento de assunto, e o padrão para cada chave corresponder ao item " +"correspondente do mapeamento de assunto, o padrão de mapeamento será bem-" +"sucedido." #: ../../reference/compound_stmts.rst:1055 msgid "" @@ -1391,6 +1792,10 @@ msgid "" "considered invalid. A :exc:`SyntaxError` is raised for duplicate literal " "values; or a :exc:`ValueError` for named keys of the same value." msgstr "" +"Se chaves duplicadas forem detectadas no padrão de mapeamento, o padrão será " +"considerado inválido. Uma exceção :exc:`SyntaxError` é levantada para " +"valores literais duplicados; ou :exc:`ValueError` para chaves nomeadas do " +"mesmo valor." #: ../../reference/compound_stmts.rst:1059 msgid "" @@ -1399,60 +1804,75 @@ msgid "" "in the mapping, and not created on-the-fly via :meth:`__missing__` or :meth:" "`~object.__getitem__`." msgstr "" +"Os pares de chave-valor são correspondidos usando o formato de dois " +"argumentos do método ``get()`` do assunto do mapeamento. Os pares de chave-" +"valor correspondidos já devem estar presentes no mapeamento e não devem ser " +"criados em tempo de uso via :meth:`__missing__` ou :meth:`~object." +"__getitem__`." #: ../../reference/compound_stmts.rst:1064 msgid "" "In simple terms ``{KEY1: P1, KEY2: P2, ... }`` matches only if all the " "following happens:" msgstr "" +"Em termos simples, ``{KEY1: P1, KEY2: P2, ... }`` corresponde somente se " +"tudo o seguinte acontecer:" #: ../../reference/compound_stmts.rst:1067 msgid "check ```` is a mapping" -msgstr "" +msgstr "verifica se ```` é um mapeamento" #: ../../reference/compound_stmts.rst:1068 msgid "``KEY1 in ``" -msgstr "" +msgstr "``KEY1 in ``" #: ../../reference/compound_stmts.rst:1069 msgid "``P1`` matches ``[KEY1]``" -msgstr "" +msgstr "``P1`` corresponde a ``[KEY1]``" #: ../../reference/compound_stmts.rst:1070 msgid "... and so on for the corresponding KEY/pattern pair." -msgstr "" +msgstr "... e assim por diante para o par KEY/elemento correspondente." #: ../../reference/compound_stmts.rst:1076 msgid "Class Patterns" -msgstr "" +msgstr "Padrões de classe" #: ../../reference/compound_stmts.rst:1078 msgid "" "A class pattern represents a class and its positional and keyword arguments " "(if any). Syntax:" msgstr "" +"Um padrão de classe representa uma classe e seus argumentos nomeados e " +"posicionais (se houver). Sintaxe:" #: ../../reference/compound_stmts.rst:1089 msgid "The same keyword should not be repeated in class patterns." -msgstr "" +msgstr "O mesmo argumento nomeado não deve ser repetido em padrões de classe." #: ../../reference/compound_stmts.rst:1091 msgid "" "The following is the logical flow for matching a class pattern against a " "subject value:" msgstr "" +"A seguir está o fluxo lógico para corresponder a um padrão de classe com um " +"valor de assunto:" #: ../../reference/compound_stmts.rst:1094 msgid "" "If ``name_or_attr`` is not an instance of the builtin :class:`type` , raise :" "exc:`TypeError`." msgstr "" +"Se ``name_or_attr`` não for uma instância do tipo embutido :class:`type` , " +"levanta :exc:`TypeError`." #: ../../reference/compound_stmts.rst:1097 msgid "" "If the subject value is not an instance of ``name_or_attr`` (tested via :" "func:`isinstance`), the class pattern fails." msgstr "" +"Se o valor do assunto não for uma instância de ``name_or_attr`` (testado " +"via :func:`isinstance`), o padrão de classe falhará." #: ../../reference/compound_stmts.rst:1100 msgid "" @@ -1460,6 +1880,9 @@ msgid "" "subsequent steps depend on whether keyword or positional argument patterns " "are present." msgstr "" +"Se nenhum argumento de padrão estiver presente, o padrão é bem-sucedido. " +"Caso contrário, as etapas subsequentes dependem se os padrões de argumento " +"posicional ou nomeado estão presentes." #: ../../reference/compound_stmts.rst:1104 msgid "" @@ -1467,26 +1890,34 @@ msgid "" "subpattern is accepted which will match the entire subject; for these types " "keyword patterns also work as for other types." msgstr "" +"Para vários tipos embutidos (especificados abaixo), um único subpadrão " +"posicional é aceito, o qual corresponderá a todo o assunto; para esses " +"tipos, os padrões de argumentos nomeados também funcionam como para outros " +"tipos." #: ../../reference/compound_stmts.rst:1108 msgid "" "If only keyword patterns are present, they are processed as follows, one by " "one:" msgstr "" +"Se apenas padrões de argumentos nomeados estiverem presentes, eles serão " +"processados da seguinte forma, um por um:" #: ../../reference/compound_stmts.rst:1111 msgid "I. The keyword is looked up as an attribute on the subject." -msgstr "" +msgstr "I. A palavra-chave é procurada como um atributo no assunto." #: ../../reference/compound_stmts.rst:1113 msgid "" "If this raises an exception other than :exc:`AttributeError`, the exception " "bubbles up." msgstr "" +"Se isso levantar uma exceção diferente de :exc:`AttributeError`, a exceção " +"será exibida." #: ../../reference/compound_stmts.rst:1116 msgid "If this raises :exc:`AttributeError`, the class pattern has failed." -msgstr "" +msgstr "Se isso levantar :exc:`AttributeError`, o padrão de classe falhou." #: ../../reference/compound_stmts.rst:1118 msgid "" @@ -1494,10 +1925,16 @@ msgid "" "the subject's attribute value. If this fails, the class pattern fails; if " "this succeeds, the match proceeds to the next keyword." msgstr "" +"Caso contrário, o subpadrão associado ao padrão de argumento nomeado é " +"correspondido ao valor de atributo do sujeito. Se isso falhar, o padrão de " +"classe falha; se isso for bem-sucedido, a correspondência prossegue para o " +"próximo argumento nomeado." #: ../../reference/compound_stmts.rst:1123 msgid "II. If all keyword patterns succeed, the class pattern succeeds." msgstr "" +"II. Se todos os padrões de argumento nomeado forem bem-sucedidos, o padrão " +"de classe será bem-sucedido." #: ../../reference/compound_stmts.rst:1125 msgid "" @@ -1505,27 +1942,35 @@ msgid "" "patterns using the :data:`~object.__match_args__` attribute on the class " "``name_or_attr`` before matching:" msgstr "" +"Se houver algum padrão posicional presente, ele será convertido em padrões " +"de argumento nomeado usando o atributo :data:`~object.__match_args__` na " +"classe ``name_or_attr`` antes da correspondência:" #: ../../reference/compound_stmts.rst:1129 msgid "" "I. The equivalent of ``getattr(cls, \"__match_args__\", ())`` is called." msgstr "" +"I. O equivalente de ``getattr(cls, \"__match_args__\", ())`` é chamado." #: ../../reference/compound_stmts.rst:1131 msgid "If this raises an exception, the exception bubbles up." -msgstr "" +msgstr "Se isso levantar uma exceção, a exceção surgirá." #: ../../reference/compound_stmts.rst:1133 msgid "" "If the returned value is not a tuple, the conversion fails and :exc:" "`TypeError` is raised." msgstr "" +"Se o valor retornado não for uma tupla, a conversão falhará e :exc:" +"`TypeError` será levantada." #: ../../reference/compound_stmts.rst:1136 msgid "" "If there are more positional patterns than ``len(cls.__match_args__)``, :exc:" "`TypeError` is raised." msgstr "" +"Se houver mais padrões posicionais do que ``len(cls.__match_args__)``, :exc:" +"`TypeError` será levantada." #: ../../reference/compound_stmts.rst:1139 msgid "" @@ -1533,29 +1978,39 @@ msgid "" "``__match_args__[i]`` as the keyword. ``__match_args__[i]`` must be a " "string; if not :exc:`TypeError` is raised." msgstr "" +"Caso contrário, o padrão posicional ``i`` é convertido em um padrão de " +"argumento nomeado usando ``__match_args__[i]`` como argumento nomeado. " +"``__match_args__[i]`` deve ser uma string; caso contrário, :exc:`TypeError` " +"é levantada." #: ../../reference/compound_stmts.rst:1143 msgid "If there are duplicate keywords, :exc:`TypeError` is raised." msgstr "" +"Se houver argumentos nomeados duplicados, :exc:`TypeError` será levantada." #: ../../reference/compound_stmts.rst:1145 msgid ":ref:`class-pattern-matching`" -msgstr "" +msgstr ":ref:`class-pattern-matching`" #: ../../reference/compound_stmts.rst:1147 msgid "" "II. Once all positional patterns have been converted to keyword patterns," msgstr "" +"II. Uma vez que todos os padrões posicionais foram convertidos em padrões de " +"argumentos nomeados," #: ../../reference/compound_stmts.rst:1148 msgid "the match proceeds as if there were only keyword patterns." msgstr "" +"a partida prossegue como se houvesse apenas padrões de argumentos nomeados." #: ../../reference/compound_stmts.rst:1150 msgid "" "For the following built-in types the handling of positional subpatterns is " "different:" msgstr "" +"Para os seguintes tipos embutidos, o tratamento de subpadrões posicionais é " +"diferente:" #: ../../reference/compound_stmts.rst:1153 msgid ":class:`bool`" @@ -1563,7 +2018,7 @@ msgstr ":class:`bool`" #: ../../reference/compound_stmts.rst:1154 msgid ":class:`bytearray`" -msgstr "" +msgstr ":class:`bytearray`" #: ../../reference/compound_stmts.rst:1155 msgid ":class:`bytes`" @@ -1586,7 +2041,7 @@ msgid ":class:`int`" msgstr ":class:`int`" #: ../../reference/compound_stmts.rst:1160 -#: ../../reference/compound_stmts.rst:1872 +#: ../../reference/compound_stmts.rst:1880 msgid ":class:`list`" msgstr ":class:`list`" @@ -1599,7 +2054,7 @@ msgid ":class:`str`" msgstr ":class:`str`" #: ../../reference/compound_stmts.rst:1163 -#: ../../reference/compound_stmts.rst:1875 +#: ../../reference/compound_stmts.rst:1883 msgid ":class:`tuple`" msgstr ":class:`tuple`" @@ -1609,35 +2064,43 @@ msgid "" "matched against the whole object rather than an attribute. For example " "``int(0|1)`` matches the value ``0``, but not the value ``0.0``." msgstr "" +"Essas classes aceitam um único argumento posicional, e o padrão ali é " +"correspondido ao objeto inteiro em vez de um atributo. Por exemplo, ``int(0|" +"1)`` corresponde ao valor ``0``, mas não ao valor ``0.0``." #: ../../reference/compound_stmts.rst:1169 msgid "" "In simple terms ``CLS(P1, attr=P2)`` matches only if the following happens:" msgstr "" +"Em termos simples, ``CLS(P1, attr=P2)`` corresponde somente se o seguinte " +"acontecer:" #: ../../reference/compound_stmts.rst:1171 msgid "``isinstance(, CLS)``" -msgstr "" +msgstr "``isinstance(, CLS)``" #: ../../reference/compound_stmts.rst:1172 msgid "convert ``P1`` to a keyword pattern using ``CLS.__match_args__``" msgstr "" +"converte ``P1`` em um padrão de argumento nomeado usando ``CLS." +"__match_args__``" #: ../../reference/compound_stmts.rst:1173 msgid "For each keyword argument ``attr=P2``:" -msgstr "" +msgstr "Para cada argumento de palavra-chave ``attr=P2``:" #: ../../reference/compound_stmts.rst:1175 msgid "``hasattr(, \"attr\")``" -msgstr "" +msgstr "``hasattr(, \"attr\")``" #: ../../reference/compound_stmts.rst:1176 msgid "``P2`` matches ``.attr``" -msgstr "" +msgstr "``P2`` corresponde a ``.attr``" #: ../../reference/compound_stmts.rst:1178 msgid "... and so on for the corresponding keyword argument/pattern pair." msgstr "" +"... e assim por diante para o par argumento nomeado/elemento correspondente." #: ../../reference/compound_stmts.rst:1193 msgid "Function definitions" @@ -1648,8 +2111,10 @@ msgid "" "A function definition defines a user-defined function object (see section :" "ref:`types`):" msgstr "" +"Uma definição de função define um objeto de função definido pelo usuário " +"(veja a seção :ref:`types`):" -#: ../../reference/compound_stmts.rst:1227 +#: ../../reference/compound_stmts.rst:1230 msgid "" "A function definition is an executable statement. Its execution binds the " "function name in the current local namespace to a function object (a wrapper " @@ -1657,14 +2122,21 @@ msgid "" "a reference to the current global namespace as the global namespace to be " "used when the function is called." msgstr "" +"Uma definição de função é uma instrução executável. Sua execução vincula o " +"nome da função no espaço de nomes local atual a um objeto função (um " +"invólucro em torno do código executável para a função). Este objeto função " +"contém uma referência ao espaço de nomes global atual como o espaço de nomes " +"global a ser usado quando a função é chamada." -#: ../../reference/compound_stmts.rst:1233 +#: ../../reference/compound_stmts.rst:1236 msgid "" "The function definition does not execute the function body; this gets " "executed only when the function is called. [#]_" msgstr "" +"A definição da função não executa o corpo da função; ela é executada somente " +"quando a função é chamada. [#]_" -#: ../../reference/compound_stmts.rst:1239 +#: ../../reference/compound_stmts.rst:1242 msgid "" "A function definition may be wrapped by one or more :term:`decorator` " "expressions. Decorator expressions are evaluated when the function is " @@ -1674,26 +2146,56 @@ msgid "" "function object. Multiple decorators are applied in nested fashion. For " "example, the following code ::" msgstr "" +"Uma definição de função pode ser encapsulada por uma ou mais expressões :" +"term:`decoradoras `. Expressões decoradoras são avaliadas quando " +"a função é definida, no escopo que contém a definição da função. O resultado " +"deve ser um chamável, que é invocado com o objeto de função como o único " +"argumento. O valor retornado é vinculado ao nome da função em vez do objeto " +"de função. Vários decoradores são aplicados de forma aninhada. Por exemplo, " +"o código a seguir ::" -#: ../../reference/compound_stmts.rst:1250 -#: ../../reference/compound_stmts.rst:1440 -msgid "is roughly equivalent to ::" +#: ../../reference/compound_stmts.rst:1249 +msgid "" +"@f1(arg)\n" +"@f2\n" +"def func(): pass" msgstr "" +"@f1(arg)\n" +"@f2\n" +"def func(): pass" + +#: ../../reference/compound_stmts.rst:1253 +#: ../../reference/compound_stmts.rst:1448 +msgid "is roughly equivalent to ::" +msgstr "é aproximadamente equivalente a ::" #: ../../reference/compound_stmts.rst:1255 msgid "" +"def func(): pass\n" +"func = f1(arg)(f2(func))" +msgstr "" +"def func(): pass\n" +"func = f1(arg)(f2(func))" + +#: ../../reference/compound_stmts.rst:1258 +msgid "" "except that the original function is not temporarily bound to the name " "``func``." msgstr "" +"exceto que a função original não está temporariamente vinculada ao nome " +"``func``." -#: ../../reference/compound_stmts.rst:1257 +#: ../../reference/compound_stmts.rst:1260 msgid "" "Functions may be decorated with any valid :token:`~python-grammar:" "assignment_expression`. Previously, the grammar was much more restrictive; " "see :pep:`614` for details." msgstr "" +"Funções podem ser decoradas com qualquer :token:`~python-grammar:" +"assignment_expression` válida. Anteriormente, a gramática era muito mais " +"restritiva; veja :pep:`614` para detalhes." -#: ../../reference/compound_stmts.rst:1262 +#: ../../reference/compound_stmts.rst:1265 msgid "" "A list of :ref:`type parameters ` may be given in square " "brackets between the function's name and the opening parenthesis for its " @@ -1702,13 +2204,19 @@ msgid "" "function's :attr:`~function.__type_params__` attribute. See :ref:`generic-" "functions` for more." msgstr "" +"Uma lista de :ref:`parâmetros de tipo ` pode ser dada entre " +"colchetes entre o nome da função e o parêntese de abertura para sua lista de " +"parâmetros. Isso indica aos verificadores de tipo estático que a função é " +"genérica. Em tempo de execução, os parâmetros de tipo podem ser recuperados " +"do atributo :attr:`~function.__type_params__` da função. Veja :ref:`generic-" +"functions` para mais." -#: ../../reference/compound_stmts.rst:1269 -#: ../../reference/compound_stmts.rst:1459 +#: ../../reference/compound_stmts.rst:1272 +#: ../../reference/compound_stmts.rst:1467 msgid "Type parameter lists are new in Python 3.12." -msgstr "" +msgstr "Listas de parâmetros de tipo são novas no Python 3.12." -#: ../../reference/compound_stmts.rst:1277 +#: ../../reference/compound_stmts.rst:1280 msgid "" "When one or more :term:`parameters ` have the form *parameter* " "``=`` *expression*, the function is said to have \"default parameter values." @@ -1718,8 +2226,15 @@ msgid "" "up until the \"``*``\" must also have a default value --- this is a " "syntactic restriction that is not expressed by the grammar." msgstr "" +"Quando um ou mais :term:`parâmetros ` têm a forma *parameter* " +"``=`` *expression*, diz-se que a função tem \"valores de parâmetro padrão\". " +"Para um parâmetro com um valor padrão, o :term:`argumento` correspondente " +"pode ser omitido de uma chamada, em cujo caso o valor padrão do parâmetro é " +"substituído. Se um parâmetro tiver um valor padrão, todos os parâmetros " +"seguintes até \"``*``\" também devem ter um valor padrão --- esta é uma " +"restrição sintática que não é expressa pela gramática." -#: ../../reference/compound_stmts.rst:1285 +#: ../../reference/compound_stmts.rst:1288 msgid "" "**Default parameter values are evaluated from left to right when the " "function definition is executed.** This means that the expression is " @@ -1731,8 +2246,32 @@ msgid "" "is generally not what was intended. A way around this is to use ``None`` as " "the default, and explicitly test for it in the body of the function, e.g.::" msgstr "" - -#: ../../reference/compound_stmts.rst:1306 +"**Os valores de parâmetro padrão são avaliados da esquerda para a direita " +"quando a definição da função é executada.** Isso significa que a expressão é " +"avaliada uma vez, quando a função é definida, e que o mesmo valor \"pré-" +"calculado\" é usado para cada chamada. Isso é especialmente importante para " +"entender quando um valor de parâmetro padrão é um objeto mutável, como uma " +"lista ou um dicionário: se a função modifica o objeto (por exemplo, anexando " +"um item a uma lista), o valor de parâmetro padrão é efetivamente modificado. " +"Isso geralmente não é o que se pretendia. Uma maneira de contornar isso é " +"usar ``None`` como o padrão e testá-lo explicitamente no corpo da função, " +"por exemplo::" + +#: ../../reference/compound_stmts.rst:1298 +msgid "" +"def whats_on_the_telly(penguin=None):\n" +" if penguin is None:\n" +" penguin = []\n" +" penguin.append(\"property of the zoo\")\n" +" return penguin" +msgstr "" +"def whats_on_the_telly(penguin=None):\n" +" if penguin is None:\n" +" penguin = []\n" +" penguin.append(\"property of the zoo\")\n" +" return penguin" + +#: ../../reference/compound_stmts.rst:1309 msgid "" "Function call semantics are described in more detail in section :ref:" "`calls`. A function call always assigns values to all parameters mentioned " @@ -1747,31 +2286,71 @@ msgid "" "\"``/``\" are positional-only parameters and may only be passed by " "positional arguments." msgstr "" - -#: ../../reference/compound_stmts.rst:1318 +"A semântica de chamada de função é descrita em mais detalhes na seção :ref:" +"`calls`. Uma chamada de função sempre atribui valores a todos os parâmetros " +"mencionados na lista de parâmetros, seja de argumentos posicionais, de " +"argumentos nomeados ou de valores padrão. Se o formato \"``*identifier``\" " +"estiver presente, ele será inicializado para uma tupla que recebe quaisquer " +"parâmetros posicionais excedentes, padronizando para a tupla vazia. Se o " +"formato \"``**identifier``\" estiver presente, ele será inicializado para um " +"novo mapeamento ordenado que recebe quaisquer argumentos nomeados " +"excedentes, padronizando para um novo mapeamento vazio do mesmo tipo. " +"Parâmetros após \"``*``\" ou \"``*identifier``\" são parâmetros somente-" +"nomeados e podem ser passados somente por argumentos nomeados. Parâmetros " +"antes de \"``/``\" são parâmetros somente-posicionais e podem ser passados " +"somente por argumentos posicionais." + +#: ../../reference/compound_stmts.rst:1321 msgid "" "The ``/`` function parameter syntax may be used to indicate positional-only " "parameters. See :pep:`570` for details." msgstr "" +"A sintaxe do parâmetro de função ``/`` pode ser usada para indicar " +"parâmetros somente-posicionais. Veja a :pep:`570` para detalhes." -#: ../../reference/compound_stmts.rst:1327 +#: ../../reference/compound_stmts.rst:1330 msgid "" "Parameters may have an :term:`annotation ` of the form " "\"``: expression``\" following the parameter name. Any parameter may have " -"an annotation, even those of the form ``*identifier`` or ``**identifier``. " -"Functions may have \"return\" annotation of the form \"``-> expression``\" " -"after the parameter list. These annotations can be any valid Python " -"expression. The presence of annotations does not change the semantics of a " -"function. The annotation values are available as values of a dictionary " -"keyed by the parameters' names in the :attr:`__annotations__` attribute of " -"the function object. If the ``annotations`` import from :mod:`__future__` " -"is used, annotations are preserved as strings at runtime which enables " -"postponed evaluation. Otherwise, they are evaluated when the function " -"definition is executed. In this case annotations may be evaluated in a " -"different order than they appear in the source code." -msgstr "" +"an annotation, even those of the form ``*identifier`` or ``**identifier``. " +"(As a special case, parameters of the form ``*identifier`` may have an " +"annotation \"``: *expression``\".) Functions may have \"return\" annotation " +"of the form \"``-> expression``\" after the parameter list. These " +"annotations can be any valid Python expression. The presence of annotations " +"does not change the semantics of a function. The annotation values are " +"available as values of a dictionary keyed by the parameters' names in the :" +"attr:`__annotations__` attribute of the function object. If the " +"``annotations`` import from :mod:`__future__` is used, annotations are " +"preserved as strings at runtime which enables postponed evaluation. " +"Otherwise, they are evaluated when the function definition is executed. In " +"this case annotations may be evaluated in a different order than they appear " +"in the source code." +msgstr "" +"Os parâmetros podem ter uma :term:`anotação ` do " +"formato \"``: expressão``\" após o nome do parâmetro. Qualquer parâmetro " +"pode ter uma anotação, mesmo aqueles do formato ``*identificador`` ou " +"``**identificador``. (Como um caso especial, parâmetros do formato " +"``*identificador`` podem ter uma anotação \"``: *expressão``\".) As funções " +"podem ter uma anotação \"return\" do formato \"``-> expressão``\" após a " +"lista de parâmetros. Essas anotações podem ser qualquer expressão Python " +"válida. A presença de anotações não altera a semântica de uma função. Os " +"valores de anotação estão disponíveis como valores de um dicionário " +"indexados pelos nomes dos parâmetros no atributo :attr:`__annotations__` do " +"objeto função. Se a importação de ``annotations`` de :mod:`__future__` for " +"usada, as anotações serão preservadas como strings em tempo de execução, o " +"que permite avaliação adiada. Caso contrário, elas são avaliadas quando a " +"definição da função é executada. Nesse caso, as anotações podem ser " +"avaliadas em uma ordem diferente daquela em que aparecem no código-fonte." + +#: ../../reference/compound_stmts.rst:1344 +msgid "" +"Parameters of the form \"``*identifier``\" may have an annotation \"``: " +"*expression``\". See :pep:`646`." +msgstr "" +"Parâmetros do formato \"``*identificador``\" podem ter uma anotação \"``: " +"*expressão``\". Veja :pep:`646`." -#: ../../reference/compound_stmts.rst:1342 +#: ../../reference/compound_stmts.rst:1350 msgid "" "It is also possible to create anonymous functions (functions not bound to a " "name), for immediate use in expressions. This uses lambda expressions, " @@ -1782,8 +2361,16 @@ msgid "" "keyword:`!def`\" form is actually more powerful since it allows the " "execution of multiple statements and annotations." msgstr "" +"Também é possível criar funções anônimas (funções não vinculadas a um nome), " +"para uso imediato em expressões. Isso usa expressões lambda, descritas na " +"seção :ref:`lambda`. Observe que a expressão lambda é meramente uma " +"abreviação para uma definição de função simplificada; uma função definida em " +"uma instrução \":keyword:`def`\" pode ser passada adiante ou atribuída a " +"outro nome, assim como uma função definida por uma expressão lambda. O " +"formato \":keyword:`!def`\" é, na verdade, mais poderoso, pois permite a " +"execução de várias instruções e anotações." -#: ../../reference/compound_stmts.rst:1350 +#: ../../reference/compound_stmts.rst:1358 msgid "" "**Programmer's note:** Functions are first-class objects. A \"``def``\" " "statement executed inside a function definition defines a local function " @@ -1791,62 +2378,74 @@ msgid "" "function can access the local variables of the function containing the def. " "See section :ref:`naming` for details." msgstr "" +"**Nota do programador:** Funções são objetos de primeira classe. Uma " +"instrução \"``def``\" executada dentro de uma definição de função define uma " +"função local que pode ser retornada ou passada adiante. Variáveis livres " +"usadas na função aninhada podem acessar as variáveis locais da função que " +"contém o \"def\". Veja a seção :ref:`naming` para detalhes." -#: ../../reference/compound_stmts.rst:1358 +#: ../../reference/compound_stmts.rst:1366 msgid ":pep:`3107` - Function Annotations" -msgstr "" +msgstr ":pep:`3107` - Anotações de função" -#: ../../reference/compound_stmts.rst:1359 +#: ../../reference/compound_stmts.rst:1367 msgid "The original specification for function annotations." -msgstr "" +msgstr "A especificação original para anotações de funções." -#: ../../reference/compound_stmts.rst:1361 +#: ../../reference/compound_stmts.rst:1369 msgid ":pep:`484` - Type Hints" -msgstr ":pep:`484` - Dicas de tipos" +msgstr ":pep:`484` - Dicas de tipo" -#: ../../reference/compound_stmts.rst:1362 +#: ../../reference/compound_stmts.rst:1370 msgid "Definition of a standard meaning for annotations: type hints." -msgstr "" +msgstr "Definição de um significado padrão para anotações: dicas de tipo." -#: ../../reference/compound_stmts.rst:1364 +#: ../../reference/compound_stmts.rst:1372 msgid ":pep:`526` - Syntax for Variable Annotations" msgstr ":pep:`526` - Sintaxe para Anotações de Variáveis" -#: ../../reference/compound_stmts.rst:1365 +#: ../../reference/compound_stmts.rst:1373 msgid "" "Ability to type hint variable declarations, including class variables and " "instance variables." msgstr "" +"Capacidade de fornecer dica de tipo para declarações de variáveis, incluindo " +"variáveis de classe e variáveis de instância." -#: ../../reference/compound_stmts.rst:1368 +#: ../../reference/compound_stmts.rst:1376 msgid ":pep:`563` - Postponed Evaluation of Annotations" -msgstr "" +msgstr ":pep:`563` - Avaliação postergada de anotações" -#: ../../reference/compound_stmts.rst:1369 +#: ../../reference/compound_stmts.rst:1377 msgid "" "Support for forward references within annotations by preserving annotations " "in a string form at runtime instead of eager evaluation." msgstr "" +"Suporte para referências futuras dentro de anotações, preservando anotações " +"em um formato de string em tempo de execução em vez de avaliação antecipada." -#: ../../reference/compound_stmts.rst:1372 +#: ../../reference/compound_stmts.rst:1380 msgid ":pep:`318` - Decorators for Functions and Methods" -msgstr "" +msgstr ":pep:`318` - Decoradores para funções e métodos" -#: ../../reference/compound_stmts.rst:1373 +#: ../../reference/compound_stmts.rst:1381 msgid "" "Function and method decorators were introduced. Class decorators were " "introduced in :pep:`3129`." msgstr "" +"Decoradores de função e método foram introduzidos. Decoradores de classe " +"foram introduzidos na :pep:`3129`." -#: ../../reference/compound_stmts.rst:1379 +#: ../../reference/compound_stmts.rst:1387 msgid "Class definitions" msgstr "Definições de classe" -#: ../../reference/compound_stmts.rst:1394 +#: ../../reference/compound_stmts.rst:1402 msgid "A class definition defines a class object (see section :ref:`types`):" msgstr "" +"Uma definição de classe define um objeto classe (veja a seção :ref:`types`):" -#: ../../reference/compound_stmts.rst:1401 +#: ../../reference/compound_stmts.rst:1409 msgid "" "A class definition is an executable statement. The inheritance list usually " "gives a list of base classes (see :ref:`metaclasses` for more advanced " @@ -1854,12 +2453,33 @@ msgid "" "allows subclassing. Classes without an inheritance list inherit, by " "default, from the base class :class:`object`; hence, ::" msgstr "" +"Uma definição de classe é uma instrução executável. A lista de herança " +"geralmente fornece uma lista de classes base (veja :ref:`metaclasses` para " +"usos mais avançados), então cada item na lista deve ser executada como um " +"objeto classe que permite extensão via subclasse. Classes sem uma lista de " +"herança herdam, por padrão, da classe base :class:`object`; portanto, ::" + +#: ../../reference/compound_stmts.rst:1415 +msgid "" +"class Foo:\n" +" pass" +msgstr "" +"class Foo:\n" +" pass" -#: ../../reference/compound_stmts.rst:1410 +#: ../../reference/compound_stmts.rst:1418 msgid "is equivalent to ::" -msgstr "é equivalente a ::" +msgstr "equivale a ::" -#: ../../reference/compound_stmts.rst:1415 +#: ../../reference/compound_stmts.rst:1420 +msgid "" +"class Foo(object):\n" +" pass" +msgstr "" +"class Foo(object):\n" +" pass" + +#: ../../reference/compound_stmts.rst:1423 msgid "" "The class's suite is then executed in a new execution frame (see :ref:" "`naming`), using a newly created local namespace and the original global " @@ -1870,48 +2490,91 @@ msgid "" "attribute dictionary. The class name is bound to this class object in the " "original local namespace." msgstr "" +"O conjunto da classe é então executado em um novo quadro de execução (veja :" +"ref:`naming`), usando um espaço de nomes local recém-criado e o espaço de " +"nomes global original. (Normalmente, o conjunto contém principalmente " +"definições de função.) Quando o conjunto da classe termina a execução, seu " +"quadro de execução é descartado, mas seu espaço de nomes local é salvo. [#]_ " +"Um objeto classe é então criado usando a lista de herança para as classes " +"base e o espaço de nomes local salvo para o dicionário de atributos. O nome " +"da classe é vinculado a este objeto classe no espaço de nomes local original." -#: ../../reference/compound_stmts.rst:1424 +#: ../../reference/compound_stmts.rst:1432 msgid "" "The order in which attributes are defined in the class body is preserved in " -"the new class's ``__dict__``. Note that this is reliable only right after " -"the class is created and only for classes that were defined using the " -"definition syntax." +"the new class's :attr:`~type.__dict__`. Note that this is reliable only " +"right after the class is created and only for classes that were defined " +"using the definition syntax." msgstr "" +"A ordem em que os atributos são definidos no corpo da classe é preservada " +"no :attr:`~type.__dict__` da nova classe. Observe que isso é confiável " +"somente logo após a classe ser criada e somente para classes que foram " +"definidas usando a sintaxe de definição." -#: ../../reference/compound_stmts.rst:1429 +#: ../../reference/compound_stmts.rst:1437 msgid "" "Class creation can be customized heavily using :ref:`metaclasses " "`." msgstr "" +"A criação de classes pode ser bastante personalizada usando :ref:" +"`metaclasses `." -#: ../../reference/compound_stmts.rst:1434 +#: ../../reference/compound_stmts.rst:1442 msgid "Classes can also be decorated: just like when decorating functions, ::" msgstr "" +"As classes também podem ser decoradas: assim como na decoração de funções, ::" + +#: ../../reference/compound_stmts.rst:1444 +msgid "" +"@f1(arg)\n" +"@f2\n" +"class Foo: pass" +msgstr "" +"@f1(arg)\n" +"@f2\n" +"class Foo: pass" + +#: ../../reference/compound_stmts.rst:1450 +msgid "" +"class Foo: pass\n" +"Foo = f1(arg)(f2(Foo))" +msgstr "" +"class Foo: pass\n" +"Foo = f1(arg)(f2(Foo))" -#: ../../reference/compound_stmts.rst:1445 +#: ../../reference/compound_stmts.rst:1453 msgid "" "The evaluation rules for the decorator expressions are the same as for " "function decorators. The result is then bound to the class name." msgstr "" +"As regras de execução para as expressões de decorador são as mesmas que para " +"decoradores de função. O resultado é então vinculado ao nome da classe." -#: ../../reference/compound_stmts.rst:1448 +#: ../../reference/compound_stmts.rst:1456 msgid "" "Classes may be decorated with any valid :token:`~python-grammar:" "assignment_expression`. Previously, the grammar was much more restrictive; " "see :pep:`614` for details." msgstr "" +"Classes podem ser decoradas com qualquer :token:`~python-grammar:" +"assignment_expression` válida. Anteriormente, a gramática era muito mais " +"restritiva; veja :pep:`614` para detalhes." -#: ../../reference/compound_stmts.rst:1453 +#: ../../reference/compound_stmts.rst:1461 msgid "" "A list of :ref:`type parameters ` may be given in square " "brackets immediately after the class's name. This indicates to static type " "checkers that the class is generic. At runtime, the type parameters can be " -"retrieved from the class's ``__type_params__`` attribute. See :ref:`generic-" -"classes` for more." +"retrieved from the class's :attr:`~type.__type_params__` attribute. See :ref:" +"`generic-classes` for more." msgstr "" +"Uma lista de :ref:`parâmetros de tipo ` pode ser dada entre " +"colchetes imediatamente após o nome da classe. Isso indica aos verificadores " +"de tipo estático que a classe é genérica. Em tempo de execução, os " +"parâmetros de tipo podem ser recuperados do atributo :attr:`~type." +"__type_params__` da classe. Veja :ref:`generic-classes` para mais." -#: ../../reference/compound_stmts.rst:1462 +#: ../../reference/compound_stmts.rst:1470 msgid "" "**Programmer's note:** Variables defined in the class definition are class " "attributes; they are shared by instances. Instance attributes can be set in " @@ -1923,153 +2586,331 @@ msgid "" "` can be used to create instance variables with different " "implementation details." msgstr "" - -#: ../../reference/compound_stmts.rst:1474 +"**Nota do programador:** Variáveis definidas na definição de classe são " +"atributos de classe; elas são compartilhadas por instâncias. Atributos de " +"instância podem ser definidos em um método com ``self.nome = valor``. " +"Atributos de classe e instância são acessíveis por meio da notação \"``self." +"nome``\", e um atributo de instância oculta um atributo de classe com o " +"mesmo nome quando acessado dessa forma. Atributos de classe podem ser usados " +"como padrões para atributos de instância, mas usar valores mutáveis pode " +"levar a resultados inesperados. :ref:`Descritores ` podem ser " +"usados para criar variáveis de instância com diferentes detalhes de " +"implementação." + +#: ../../reference/compound_stmts.rst:1482 msgid ":pep:`3115` - Metaclasses in Python 3000" msgstr ":pep:`3115` - Metaclasses no Python 3000" -#: ../../reference/compound_stmts.rst:1475 +#: ../../reference/compound_stmts.rst:1483 msgid "" "The proposal that changed the declaration of metaclasses to the current " "syntax, and the semantics for how classes with metaclasses are constructed." msgstr "" +"A proposta que alterou a declaração de metaclasses para a sintaxe atual e a " +"semântica de como as classes com metaclasses são construídas." -#: ../../reference/compound_stmts.rst:1479 +#: ../../reference/compound_stmts.rst:1487 msgid ":pep:`3129` - Class Decorators" msgstr ":pep:`3129` - Class Decorators" -#: ../../reference/compound_stmts.rst:1480 +#: ../../reference/compound_stmts.rst:1488 msgid "" "The proposal that added class decorators. Function and method decorators " "were introduced in :pep:`318`." msgstr "" +"A proposta que adicionou decoradores de classe. Decoradores de função e " +"método foram introduzidos na :pep:`318`." -#: ../../reference/compound_stmts.rst:1487 +#: ../../reference/compound_stmts.rst:1495 msgid "Coroutines" msgstr "Corrotinas" -#: ../../reference/compound_stmts.rst:1495 +#: ../../reference/compound_stmts.rst:1503 msgid "Coroutine function definition" msgstr "Definição de função de corrotina" -#: ../../reference/compound_stmts.rst:1505 +#: ../../reference/compound_stmts.rst:1513 msgid "" "Execution of Python coroutines can be suspended and resumed at many points " "(see :term:`coroutine`). :keyword:`await` expressions, :keyword:`async for` " "and :keyword:`async with` can only be used in the body of a coroutine " "function." msgstr "" +"A execução de corrotinas do Python pode ser suspensa e retomada em muitos " +"pontos (consulte :term:`coroutine`). As expressões :keyword:`await`, :" +"keyword:`async for` e :keyword:`async with` só podem ser usadas no corpo de " +"uma função de corrotina." -#: ../../reference/compound_stmts.rst:1509 +#: ../../reference/compound_stmts.rst:1517 msgid "" "Functions defined with ``async def`` syntax are always coroutine functions, " "even if they do not contain ``await`` or ``async`` keywords." msgstr "" +"Funções definidas com a sintaxe ``async def`` são sempre funções de " +"corrotina, mesmo que não contenham palavras reservadas ``await`` ou " +"``async``." -#: ../../reference/compound_stmts.rst:1512 +#: ../../reference/compound_stmts.rst:1520 msgid "" "It is a :exc:`SyntaxError` to use a ``yield from`` expression inside the " "body of a coroutine function." msgstr "" +"Ocorre uma :exc:`SyntaxError` se usada uma expressão ``yield from`` dentro " +"do corpo de uma função de corrotina." -#: ../../reference/compound_stmts.rst:1515 +#: ../../reference/compound_stmts.rst:1523 msgid "An example of a coroutine function::" +msgstr "Um exemplo de uma função de corrotina::" + +#: ../../reference/compound_stmts.rst:1525 +msgid "" +"async def func(param1, param2):\n" +" do_stuff()\n" +" await some_coroutine()" msgstr "" +"async def func(param1, param2):\n" +" faz_algo()\n" +" await alguma_corrotina()" -#: ../../reference/compound_stmts.rst:1521 +#: ../../reference/compound_stmts.rst:1529 msgid "" "``await`` and ``async`` are now keywords; previously they were only treated " "as such inside the body of a coroutine function." msgstr "" +"``await`` e ``async`` agora são palavras reservadas; anteriormente, elas só " +"eram tratadas como tal dentro do corpo de uma função de corrotina." -#: ../../reference/compound_stmts.rst:1529 +#: ../../reference/compound_stmts.rst:1537 msgid "The :keyword:`!async for` statement" -msgstr "" +msgstr "A instrução :keyword:`!async for`" -#: ../../reference/compound_stmts.rst:1534 +#: ../../reference/compound_stmts.rst:1542 msgid "" "An :term:`asynchronous iterable` provides an ``__aiter__`` method that " "directly returns an :term:`asynchronous iterator`, which can call " "asynchronous code in its ``__anext__`` method." msgstr "" +"Um :term:`iterável assíncrono` fornece um método ``__aiter__`` que retorna " +"diretamente um :term:`iterador assíncrono`, que pode chamar código " +"assíncrono em seu método ``__anext__``." -#: ../../reference/compound_stmts.rst:1538 +#: ../../reference/compound_stmts.rst:1546 msgid "" "The ``async for`` statement allows convenient iteration over asynchronous " "iterables." msgstr "" +"A instrução ``async for`` permite iteração conveniente sobre iteráveis " +"assíncronos." -#: ../../reference/compound_stmts.rst:1548 -msgid "Is semantically equivalent to::" +#: ../../reference/compound_stmts.rst:1551 +msgid "" +"async for TARGET in ITER:\n" +" SUITE\n" +"else:\n" +" SUITE2" msgstr "" +"async for TARGET in ITER:\n" +" SUITE\n" +"else:\n" +" SUITE2" -#: ../../reference/compound_stmts.rst:1564 +#: ../../reference/compound_stmts.rst:1556 +msgid "Is semantically equivalent to::" +msgstr "É semanticamente equivalente a::" + +#: ../../reference/compound_stmts.rst:1558 +msgid "" +"iter = (ITER)\n" +"iter = type(iter).__aiter__(iter)\n" +"running = True\n" +"\n" +"while running:\n" +" try:\n" +" TARGET = await type(iter).__anext__(iter)\n" +" except StopAsyncIteration:\n" +" running = False\n" +" else:\n" +" SUITE\n" +"else:\n" +" SUITE2" +msgstr "" +"iter = (ITER)\n" +"iter = type(iter).__aiter__(iter)\n" +"running = True\n" +"\n" +"while running:\n" +" try:\n" +" TARGET = await type(iter).__anext__(iter)\n" +" except StopAsyncIteration:\n" +" running = False\n" +" else:\n" +" SUITE\n" +"else:\n" +" SUITE2" + +#: ../../reference/compound_stmts.rst:1572 msgid "" "See also :meth:`~object.__aiter__` and :meth:`~object.__anext__` for details." msgstr "" +"Veja também :meth:`~object.__aiter__` e :meth:`~object.__anext__` para " +"detalhes." -#: ../../reference/compound_stmts.rst:1566 +#: ../../reference/compound_stmts.rst:1574 msgid "" "It is a :exc:`SyntaxError` to use an ``async for`` statement outside the " "body of a coroutine function." msgstr "" +"Ocorre uma :exc:`SyntaxError` se usada uma instrução ``async for`` fora do " +"corpo de uma função de corrotina." -#: ../../reference/compound_stmts.rst:1574 +#: ../../reference/compound_stmts.rst:1582 msgid "The :keyword:`!async with` statement" -msgstr "" +msgstr "A instrução :keyword:`!async with`" -#: ../../reference/compound_stmts.rst:1579 +#: ../../reference/compound_stmts.rst:1587 msgid "" "An :term:`asynchronous context manager` is a :term:`context manager` that is " "able to suspend execution in its *enter* and *exit* methods." msgstr "" +"Um :term:`gerenciador de contexto assíncrono` é um :term:`gerenciador de " +"contexto` que é capaz de suspender a execução em seus métodos *enter* e " +"*exit*." + +#: ../../reference/compound_stmts.rst:1592 +msgid "" +"async with EXPRESSION as TARGET:\n" +" SUITE" +msgstr "" +"async with EXPRESSÃO as ALVO:\n" +" COMANDOS" + +#: ../../reference/compound_stmts.rst:1597 +msgid "" +"manager = (EXPRESSION)\n" +"aenter = type(manager).__aenter__\n" +"aexit = type(manager).__aexit__\n" +"value = await aenter(manager)\n" +"hit_except = False\n" +"\n" +"try:\n" +" TARGET = value\n" +" SUITE\n" +"except:\n" +" hit_except = True\n" +" if not await aexit(manager, *sys.exc_info()):\n" +" raise\n" +"finally:\n" +" if not hit_except:\n" +" await aexit(manager, None, None, None)" +msgstr "" +"manager = (EXPRESSÃO)\n" +"aenter = type(manager).__aenter__\n" +"aexit = type(manager).__aexit__\n" +"value = await aenter(manager)\n" +"hit_except = False\n" +"\n" +"try:\n" +" ALVO = value\n" +" COMANDOS\n" +"except:\n" +" hit_except = True\n" +" if not await aexit(manager, *sys.exc_info()):\n" +" raise\n" +"finally:\n" +" if not hit_except:\n" +" await aexit(manager, None, None, None)" -#: ../../reference/compound_stmts.rst:1606 +#: ../../reference/compound_stmts.rst:1614 msgid "" "See also :meth:`~object.__aenter__` and :meth:`~object.__aexit__` for " "details." msgstr "" +"Veja também :meth:`~object.__aenter__` e :meth:`~object.__aexit__` para " +"detalhes." -#: ../../reference/compound_stmts.rst:1608 +#: ../../reference/compound_stmts.rst:1616 msgid "" "It is a :exc:`SyntaxError` to use an ``async with`` statement outside the " "body of a coroutine function." msgstr "" +"Ocorre uma :exc:`SyntaxError` se usada uma instrução ``async with`` fora do " +"corpo de uma função de corrotina." -#: ../../reference/compound_stmts.rst:1613 +#: ../../reference/compound_stmts.rst:1621 msgid ":pep:`492` - Coroutines with async and await syntax" -msgstr "" +msgstr ":pep:`492` - Corrotina com sintaxe de async e wait" -#: ../../reference/compound_stmts.rst:1614 +#: ../../reference/compound_stmts.rst:1622 msgid "" "The proposal that made coroutines a proper standalone concept in Python, and " "added supporting syntax." msgstr "" +"A proposta que tornou as corrotinas um conceito autônomo em Python e " +"adicionou sintaxe de suporte." -#: ../../reference/compound_stmts.rst:1620 +#: ../../reference/compound_stmts.rst:1628 msgid "Type parameter lists" -msgstr "" +msgstr "Listas de parâmetros de tipo" -#: ../../reference/compound_stmts.rst:1624 +#: ../../reference/compound_stmts.rst:1632 msgid "Support for default values was added (see :pep:`696`)." -msgstr "" +msgstr "Foi adicionado suporte para valores padrão (veja :pep:`696`)." -#: ../../reference/compound_stmts.rst:1637 +#: ../../reference/compound_stmts.rst:1645 msgid "" ":ref:`Functions ` (including :ref:`coroutines `), :ref:" "`classes ` and :ref:`type aliases ` may contain a type " "parameter list::" msgstr "" - -#: ../../reference/compound_stmts.rst:1656 +":ref:`Funções ` (incluindo :ref:`corrotinas `), :ref:" +"`classes ` e :ref:`apelidos de tipo ` podem conter uma lista de " +"parâmetros de tipo::" + +#: ../../reference/compound_stmts.rst:1649 +msgid "" +"def max[T](args: list[T]) -> T:\n" +" ...\n" +"\n" +"async def amax[T](args: list[T]) -> T:\n" +" ...\n" +"\n" +"class Bag[T]:\n" +" def __iter__(self) -> Iterator[T]:\n" +" ...\n" +"\n" +" def add(self, arg: T) -> None:\n" +" ...\n" +"\n" +"type ListOrSet[T] = list[T] | set[T]" +msgstr "" +"def max[T](args: list[T]) -> T:\n" +" ...\n" +"\n" +"async def amax[T](args: list[T]) -> T:\n" +" ...\n" +"\n" +"class Bag[T]:\n" +" def __iter__(self) -> Iterator[T]:\n" +" ...\n" +"\n" +" def add(self, arg: T) -> None:\n" +" ...\n" +"\n" +"type ListOrSet[T] = list[T] | set[T]" + +#: ../../reference/compound_stmts.rst:1664 msgid "" "Semantically, this indicates that the function, class, or type alias is " "generic over a type variable. This information is primarily used by static " "type checkers, and at runtime, generic objects behave much like their non-" "generic counterparts." msgstr "" +"Semanticamente, isso indica que a função, classe ou apelido de tipo é " +"genérico sobre uma variável de tipo. Essas informações são usadas " +"principalmente por verificadores de tipo estático e, em tempo de execução, " +"objetos genéricos se comportam muito como suas contrapartes não genéricas." -#: ../../reference/compound_stmts.rst:1661 +#: ../../reference/compound_stmts.rst:1669 msgid "" "Type parameters are declared in square brackets (``[]``) immediately after " "the name of the function, class, or type alias. The type parameters are " @@ -2080,37 +2921,56 @@ msgid "" "function (technically, an :ref:`annotation scope `) that " "wraps the creation of the generic object." msgstr "" +"Parâmetros de tipo são declarados entre colchetes (``[]``) imediatamente " +"após o nome da função, classe ou apelido de tipo. Os parâmetros de tipo são " +"acessíveis dentro do escopo do objeto genérico, mas não em outro lugar. " +"Assim, após uma declaração ``def func[T](): pass``, o nome ``T`` não está " +"disponível no escopo do módulo. Abaixo, a semântica de objetos genéricos é " +"descrita com mais precisão. O escopo de parâmetros de tipo é modelado com " +"uma função especial (tecnicamente, um :ref:`escopo de anotação `) que encapsula a criação do objeto genérico." -#: ../../reference/compound_stmts.rst:1670 +#: ../../reference/compound_stmts.rst:1678 msgid "" -"Generic functions, classes, and type aliases have a :attr:`!__type_params__` " -"attribute listing their type parameters." +"Generic functions, classes, and type aliases have a :attr:`~definition." +"__type_params__` attribute listing their type parameters." msgstr "" +"Funções genéricas, classes e apelidos de tipo têm um atributo :attr:" +"`~definition.__type_params__` listando seus parâmetros de tipo." -#: ../../reference/compound_stmts.rst:1673 +#: ../../reference/compound_stmts.rst:1681 msgid "Type parameters come in three kinds:" -msgstr "" +msgstr "Existem três espécies de parâmetros de tipo:" -#: ../../reference/compound_stmts.rst:1675 +#: ../../reference/compound_stmts.rst:1683 msgid "" ":data:`typing.TypeVar`, introduced by a plain name (e.g., ``T``). " "Semantically, this represents a single type to a type checker." msgstr "" +":data:`typing.TypeVar`, introduzido por um nome simples (por exemplo, " +"``T``). Semanticamente, isso representa um único tipo para um verificador de " +"tipos." -#: ../../reference/compound_stmts.rst:1677 +#: ../../reference/compound_stmts.rst:1685 msgid "" ":data:`typing.TypeVarTuple`, introduced by a name prefixed with a single " "asterisk (e.g., ``*Ts``). Semantically, this stands for a tuple of any " "number of types." msgstr "" +":data:`typing.TypeVarTuple`, introduzido por um nome prefixado com um único " +"asterisco (por exemplo, ``*Ts``). Semanticamente, isso representa uma tupla " +"de qualquer número de tipos." -#: ../../reference/compound_stmts.rst:1680 +#: ../../reference/compound_stmts.rst:1688 msgid "" ":data:`typing.ParamSpec`, introduced by a name prefixed with two asterisks " "(e.g., ``**P``). Semantically, this stands for the parameters of a callable." msgstr "" +":data:`typing.ParamSpec`, introduzido por um nome prefixado com dois " +"asteriscos (por exemplo, ``**P``). Semanticamente, isso representa os " +"parâmetros de um chamável." -#: ../../reference/compound_stmts.rst:1683 +#: ../../reference/compound_stmts.rst:1691 msgid "" ":data:`typing.TypeVar` declarations can define *bounds* and *constraints* " "with a colon (``:``) followed by an expression. A single expression after " @@ -2121,8 +2981,18 @@ msgid "" "should be a type (again, this is not enforced at runtime). Constrained type " "variables can only take on one of the types in the list of constraints." msgstr "" +"As declarações de :data:`typing.TypeVar` podem definir delimitações " +"(*bounds*) e restrições (*constraints*) com dois pontos (``:``) seguidos por " +"uma expressão. Uma única expressão após os dois pontos indica uma " +"delimitação (por exemplo, ``T: int``). Semanticamente, isso significa que o :" +"data:`!typing.TypeVar` pode representar apenas tipos que são um subtipo " +"desse limite. Uma tupla de expressões entre parênteses após os dois pontos " +"indica um conjunto de restrições (por exemplo, ``T: (str, bytes)``). Cada " +"membro da tupla deve ser um tipo (novamente, isso não é imposto em tempo de " +"execução). Variáveis de tipo restrito podem assumir apenas um dos tipos na " +"lista de restrições." -#: ../../reference/compound_stmts.rst:1692 +#: ../../reference/compound_stmts.rst:1700 msgid "" "For :data:`!typing.TypeVar`\\ s declared using the type parameter list " "syntax, the bound and constraints are not evaluated when the generic object " @@ -2131,14 +3001,22 @@ msgid "" "bounds or constraints are evaluated in a separate :ref:`annotation scope " "`." msgstr "" +"Para :data:`!typing.TypeVar`\\ s declarados usando a sintaxe de lista de " +"parâmetros de tipo, a delimitação e as restrições não são avaliados quando o " +"objeto genérico é criado, mas somente quando o valor é acessado " +"explicitamente por meio dos atributos ``__bound__`` e ``__constraints__``. " +"Para fazer isso, as delimitações ou restrições são avaliados em um :ref:" +"`escopo de anotação ` separado." -#: ../../reference/compound_stmts.rst:1698 +#: ../../reference/compound_stmts.rst:1706 msgid "" ":data:`typing.TypeVarTuple`\\ s and :data:`typing.ParamSpec`\\ s cannot have " "bounds or constraints." msgstr "" +":data:`typing.TypeVarTuple`\\ s e :data:`typing.ParamSpec`\\ s não pode ter " +"delimitações e restrições." -#: ../../reference/compound_stmts.rst:1701 +#: ../../reference/compound_stmts.rst:1709 msgid "" "All three flavors of type parameters can also have a *default value*, which " "is used when the type parameter is not explicitly provided. This is added by " @@ -2150,27 +3028,91 @@ msgid "" "default value is specified for a type parameter, the ``__default__`` " "attribute is set to the special sentinel object :data:`typing.NoDefault`." msgstr "" +"Todas as três espécies de parâmetros de tipo também podem ter um *valor " +"padrão*, que é usado quando o parâmetro de tipo não é fornecido " +"explicitamente. Isso é adicionado anexando um único sinal de igual (``=``) " +"seguido por uma expressão. Como os limites e restrições de tipos variáveis, " +"o valor padrão não é avaliado quando o objeto é criado, mas apenas quando o " +"atributo ``__default__`` do parâmetro de tipo é acessado. Para esse fim, o " +"valor padrão é avaliado em um :ref:`escopo de anotação ` " +"separado. Se nenhum valor padrão for especificado para um parâmetro de tipo, " +"o atributo ``__default__`` é definido como o objeto sinalizador especial :" +"data:`typing.NoDefault`." -#: ../../reference/compound_stmts.rst:1711 +#: ../../reference/compound_stmts.rst:1719 msgid "" "The following example indicates the full set of allowed type parameter " "declarations::" msgstr "" - -#: ../../reference/compound_stmts.rst:1731 +"O exemplo a seguir indica o conjunto completo de declarações de parâmetros " +"de tipo permitidas:" + +#: ../../reference/compound_stmts.rst:1721 +msgid "" +"def overly_generic[\n" +" SimpleTypeVar,\n" +" TypeVarWithDefault = int,\n" +" TypeVarWithBound: int,\n" +" TypeVarWithConstraints: (str, bytes),\n" +" *SimpleTypeVarTuple = (int, float),\n" +" **SimpleParamSpec = (str, bytearray),\n" +"](\n" +" a: SimpleTypeVar,\n" +" b: TypeVarWithDefault,\n" +" c: TypeVarWithBound,\n" +" d: Callable[SimpleParamSpec, TypeVarWithConstraints],\n" +" *e: SimpleTypeVarTuple,\n" +"): ..." +msgstr "" +"def overly_generic[\n" +" SimpleTypeVar,\n" +" TypeVarWithDefault = int,\n" +" TypeVarWithBound: int,\n" +" TypeVarWithConstraints: (str, bytes),\n" +" *SimpleTypeVarTuple = (int, float),\n" +" **SimpleParamSpec = (str, bytearray),\n" +"](\n" +" a: SimpleTypeVar,\n" +" b: TypeVarWithDefault,\n" +" c: TypeVarWithBound,\n" +" d: Callable[SimpleParamSpec, TypeVarWithConstraints],\n" +" *e: SimpleTypeVarTuple,\n" +"): ..." + +#: ../../reference/compound_stmts.rst:1739 msgid "Generic functions" -msgstr "" +msgstr "Funções genéricas" -#: ../../reference/compound_stmts.rst:1733 +#: ../../reference/compound_stmts.rst:1741 msgid "Generic functions are declared as follows::" -msgstr "" +msgstr "Funções genéricas são declaradas assim:" -#: ../../reference/compound_stmts.rst:1737 -#: ../../reference/compound_stmts.rst:1797 +#: ../../reference/compound_stmts.rst:1743 +msgid "def func[T](arg: T): ..." +msgstr "def func[T](arg: T): ..." + +#: ../../reference/compound_stmts.rst:1745 +#: ../../reference/compound_stmts.rst:1805 msgid "This syntax is equivalent to::" +msgstr "Essa sintaxe é equivalente a:" + +#: ../../reference/compound_stmts.rst:1747 +msgid "" +"annotation-def TYPE_PARAMS_OF_func():\n" +" T = typing.TypeVar(\"T\")\n" +" def func(arg: T): ...\n" +" func.__type_params__ = (T,)\n" +" return func\n" +"func = TYPE_PARAMS_OF_func()" msgstr "" +"annotation-def TYPE_PARAMS_OF_func():\n" +" T = typing.TypeVar(\"T\")\n" +" def func(arg: T): ...\n" +" func.__type_params__ = (T,)\n" +" return func\n" +"func = TYPE_PARAMS_OF_func()" -#: ../../reference/compound_stmts.rst:1746 +#: ../../reference/compound_stmts.rst:1754 msgid "" "Here ``annotation-def`` indicates an :ref:`annotation scope `, which is not actually bound to any name at runtime. (One other " @@ -2178,183 +3120,359 @@ msgid "" "attribute access on the :mod:`typing` module, but creates an instance of :" "data:`typing.TypeVar` directly.)" msgstr "" +"Aqui, ``annotation-def`` indica um :ref:`escopo de anotação `, que não é vinculado de verdade a nenhum nome em tempo de execução. " +"(Uma outra liberdade foi tomada na tradução: essa sintaxe não faz ocorrer um " +"acesso de atributo no módulo :mod:`typing`; ao invés disso é criada uma " +"instância de :data:`typing.TypeVar` diretamente.)" -#: ../../reference/compound_stmts.rst:1752 +#: ../../reference/compound_stmts.rst:1760 msgid "" "The annotations of generic functions are evaluated within the annotation " "scope used for declaring the type parameters, but the function's defaults " "and decorators are not." msgstr "" +"As anotações das funções genéricas são lidas dentro do escopo de anotação " +"usado para declarar os parâmetros de tipo, mas os valores padrão dos " +"argumentos e decoradores da função não são." -#: ../../reference/compound_stmts.rst:1756 +#: ../../reference/compound_stmts.rst:1764 msgid "" "The following example illustrates the scoping rules for these cases, as well " "as for additional flavors of type parameters::" msgstr "" +"Este exemplo ilustra as regras de escopo para estes casos, bem como para " +"outras espécies de parâmetros de tipo::" + +#: ../../reference/compound_stmts.rst:1767 +msgid "" +"@decorator\n" +"def func[T: int, *Ts, **P](*args: *Ts, arg: Callable[P, T] = some_default):\n" +" ..." +msgstr "" +"@decorator\n" +"def func[T: int, *Ts, **P](*args: *Ts, arg: Callable[P, T] = some_default):\n" +" ..." -#: ../../reference/compound_stmts.rst:1763 +#: ../../reference/compound_stmts.rst:1771 msgid "" "Except for the :ref:`lazy evaluation ` of the :class:" "`~typing.TypeVar` bound, this is equivalent to::" msgstr "" +"Tirando a :ref:`avaliação preguiçosa ` da delimitação da :" +"class:`~typing.TypeVar`, isso é equivalente a::" + +#: ../../reference/compound_stmts.rst:1774 +msgid "" +"DEFAULT_OF_arg = some_default\n" +"\n" +"annotation-def TYPE_PARAMS_OF_func():\n" +"\n" +" annotation-def BOUND_OF_T():\n" +" return int\n" +" # In reality, BOUND_OF_T() is evaluated only on demand.\n" +" T = typing.TypeVar(\"T\", bound=BOUND_OF_T())\n" +"\n" +" Ts = typing.TypeVarTuple(\"Ts\")\n" +" P = typing.ParamSpec(\"P\")\n" +"\n" +" def func(*args: *Ts, arg: Callable[P, T] = DEFAULT_OF_arg):\n" +" ...\n" +"\n" +" func.__type_params__ = (T, Ts, P)\n" +" return func\n" +"func = decorator(TYPE_PARAMS_OF_func())" +msgstr "" +"DEFAULT_OF_arg = some_default\n" +"\n" +"annotation-def TYPE_PARAMS_OF_func():\n" +"\n" +" annotation-def BOUND_OF_T():\n" +" return int\n" +" # In reality, BOUND_OF_T() is evaluated only on demand.\n" +" T = typing.TypeVar(\"T\", bound=BOUND_OF_T())\n" +"\n" +" Ts = typing.TypeVarTuple(\"Ts\")\n" +" P = typing.ParamSpec(\"P\")\n" +"\n" +" def func(*args: *Ts, arg: Callable[P, T] = DEFAULT_OF_arg):\n" +" ...\n" +"\n" +" func.__type_params__ = (T, Ts, P)\n" +" return func\n" +"func = decorator(TYPE_PARAMS_OF_func())" -#: ../../reference/compound_stmts.rst:1785 +#: ../../reference/compound_stmts.rst:1793 msgid "" "The capitalized names like ``DEFAULT_OF_arg`` are not actually bound at " "runtime." msgstr "" +"Os nomes com maiúsculas como ``DEFAULT_OF_arg`` não são realmente vinculados " +"em tempo de execução." -#: ../../reference/compound_stmts.rst:1791 +#: ../../reference/compound_stmts.rst:1799 msgid "Generic classes" -msgstr "" +msgstr "Classes genéricas" -#: ../../reference/compound_stmts.rst:1793 +#: ../../reference/compound_stmts.rst:1801 msgid "Generic classes are declared as follows::" -msgstr "" +msgstr "Classes genéricas são declaradas assim:" + +#: ../../reference/compound_stmts.rst:1803 +msgid "class Bag[T]: ..." +msgstr "class Bag[T]: ..." #: ../../reference/compound_stmts.rst:1807 msgid "" +"annotation-def TYPE_PARAMS_OF_Bag():\n" +" T = typing.TypeVar(\"T\")\n" +" class Bag(typing.Generic[T]):\n" +" __type_params__ = (T,)\n" +" ...\n" +" return Bag\n" +"Bag = TYPE_PARAMS_OF_Bag()" +msgstr "" +"annotation-def TYPE_PARAMS_OF_Bag():\n" +" T = typing.TypeVar(\"T\")\n" +" class Bag(typing.Generic[T]):\n" +" __type_params__ = (T,)\n" +" ...\n" +" return Bag\n" +"Bag = TYPE_PARAMS_OF_Bag()" + +#: ../../reference/compound_stmts.rst:1815 +msgid "" "Here again ``annotation-def`` (not a real keyword) indicates an :ref:" "`annotation scope `, and the name ``TYPE_PARAMS_OF_Bag`` " "is not actually bound at runtime." msgstr "" +"Aqui novamente ``annotation-def`` (não é uma palavra reservada real) indica " +"um :ref:`escopo de anotação `, e o nome " +"``TYPE_PARAMS_OF_Bag`` não é realmente vinculado em tempo de execução." -#: ../../reference/compound_stmts.rst:1811 +#: ../../reference/compound_stmts.rst:1819 msgid "" "Generic classes implicitly inherit from :data:`typing.Generic`. The base " "classes and keyword arguments of generic classes are evaluated within the " "type scope for the type parameters, and decorators are evaluated outside " "that scope. This is illustrated by this example::" msgstr "" +"Classes genéricas herdam implicitamente de :data:`typing.Generic`. As " +"classes base e os argumentos nomeados de classes genéricas são avaliados " +"dentro do escopo de tipo para os parâmetros de tipo, e os decoradores são " +"avaliados fora desse escopo. Isso é ilustrado por este exemplo::" -#: ../../reference/compound_stmts.rst:1820 +#: ../../reference/compound_stmts.rst:1825 +msgid "" +"@decorator\n" +"class Bag(Base[T], arg=T): ..." +msgstr "" +"@decorator\n" +"class Bag(Base[T], arg=T): ..." + +#: ../../reference/compound_stmts.rst:1828 msgid "This is equivalent to::" msgstr "Isso equivale a::" -#: ../../reference/compound_stmts.rst:1833 +#: ../../reference/compound_stmts.rst:1830 +msgid "" +"annotation-def TYPE_PARAMS_OF_Bag():\n" +" T = typing.TypeVar(\"T\")\n" +" class Bag(Base[T], typing.Generic[T], arg=T):\n" +" __type_params__ = (T,)\n" +" ...\n" +" return Bag\n" +"Bag = decorator(TYPE_PARAMS_OF_Bag())" +msgstr "" +"annotation-def TYPE_PARAMS_OF_Bag():\n" +" T = typing.TypeVar(\"T\")\n" +" class Bag(Base[T], typing.Generic[T], arg=T):\n" +" __type_params__ = (T,)\n" +" ...\n" +" return Bag\n" +"Bag = decorator(TYPE_PARAMS_OF_Bag())" + +#: ../../reference/compound_stmts.rst:1841 msgid "Generic type aliases" -msgstr "" +msgstr "Apelidos de tipo genérico" -#: ../../reference/compound_stmts.rst:1835 +#: ../../reference/compound_stmts.rst:1843 msgid "" "The :keyword:`type` statement can also be used to create a generic type " "alias::" msgstr "" +"A instrução :keyword:`type` também pode ser usada para criar um apelido de " +"tipo genérico::" -#: ../../reference/compound_stmts.rst:1839 +#: ../../reference/compound_stmts.rst:1845 +msgid "type ListOrSet[T] = list[T] | set[T]" +msgstr "type ListOrSet[T] = list[T] | set[T]" + +#: ../../reference/compound_stmts.rst:1847 msgid "" "Except for the :ref:`lazy evaluation ` of the value, this " "is equivalent to::" msgstr "" - -#: ../../reference/compound_stmts.rst:1851 +"Exceto pela :ref:`avaliação preguiçosa ` do valor, isso é " +"equivalente a::" + +#: ../../reference/compound_stmts.rst:1850 +msgid "" +"annotation-def TYPE_PARAMS_OF_ListOrSet():\n" +" T = typing.TypeVar(\"T\")\n" +"\n" +" annotation-def VALUE_OF_ListOrSet():\n" +" return list[T] | set[T]\n" +" # In reality, the value is lazily evaluated\n" +" return typing.TypeAliasType(\"ListOrSet\", VALUE_OF_ListOrSet(), " +"type_params=(T,))\n" +"ListOrSet = TYPE_PARAMS_OF_ListOrSet()" +msgstr "" +"annotation-def TYPE_PARAMS_OF_ListOrSet():\n" +" T = typing.TypeVar(\"T\")\n" +"\n" +" annotation-def VALUE_OF_ListOrSet():\n" +" return list[T] | set[T]\n" +" # Na realidade, o valor é avaliado preguiçosamente\n" +" return typing.TypeAliasType(\"ListOrSet\", VALUE_OF_ListOrSet(), " +"type_params=(T,))\n" +"ListOrSet = TYPE_PARAMS_OF_ListOrSet()" + +#: ../../reference/compound_stmts.rst:1859 msgid "" "Here, ``annotation-def`` (not a real keyword) indicates an :ref:`annotation " "scope `. The capitalized names like " "``TYPE_PARAMS_OF_ListOrSet`` are not actually bound at runtime." msgstr "" +"Aqui, ``annotation-def`` (não é uma palavra reservada real) indica um :ref:" +"`escopo de anotação `. Os nomes em maiúsculas como " +"``TYPE_PARAMS_OF_ListOrSet`` não são realmente vinculados em tempo de " +"execução." -#: ../../reference/compound_stmts.rst:1856 +#: ../../reference/compound_stmts.rst:1864 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../reference/compound_stmts.rst:1857 +#: ../../reference/compound_stmts.rst:1865 msgid "" "The exception is propagated to the invocation stack unless there is a :" "keyword:`finally` clause which happens to raise another exception. That new " "exception causes the old one to be lost." msgstr "" +"A exceção é propagada para a pilha de invocação, a menos que haja uma " +"cláusula :keyword:`finally` que por acaso levante outra exceção. Essa nova " +"exceção faz com que a antiga seja perdida." -#: ../../reference/compound_stmts.rst:1861 +#: ../../reference/compound_stmts.rst:1869 msgid "In pattern matching, a sequence is defined as one of the following:" msgstr "" +"Na correspondência de padrões, uma sequência é definida como uma das " +"seguintes:" -#: ../../reference/compound_stmts.rst:1863 +#: ../../reference/compound_stmts.rst:1871 msgid "a class that inherits from :class:`collections.abc.Sequence`" -msgstr "" +msgstr "uma classe que herda de :class:`collections.abc.Sequence`" -#: ../../reference/compound_stmts.rst:1864 +#: ../../reference/compound_stmts.rst:1872 msgid "" "a Python class that has been registered as :class:`collections.abc.Sequence`" msgstr "" +"uma classe Python que foi registrada como :class:`collections.abc.Sequence`" -#: ../../reference/compound_stmts.rst:1865 +#: ../../reference/compound_stmts.rst:1873 msgid "" "a builtin class that has its (CPython) :c:macro:`Py_TPFLAGS_SEQUENCE` bit set" msgstr "" +"uma classe embutida que tem seu bit :c:macro:`Py_TPFLAGS_SEQUENCE` (CPython) " +"definido" -#: ../../reference/compound_stmts.rst:1866 -#: ../../reference/compound_stmts.rst:1885 +#: ../../reference/compound_stmts.rst:1874 +#: ../../reference/compound_stmts.rst:1893 msgid "a class that inherits from any of the above" -msgstr "" +msgstr "uma classe que herda de qualquer uma das anteriores" -#: ../../reference/compound_stmts.rst:1868 +#: ../../reference/compound_stmts.rst:1876 msgid "The following standard library classes are sequences:" -msgstr "" +msgstr "As seguintes classes de biblioteca padrão são sequências:" -#: ../../reference/compound_stmts.rst:1870 +#: ../../reference/compound_stmts.rst:1878 msgid ":class:`array.array`" msgstr ":class:`array.array`" -#: ../../reference/compound_stmts.rst:1871 +#: ../../reference/compound_stmts.rst:1879 msgid ":class:`collections.deque`" msgstr ":class:`collections.deque`" -#: ../../reference/compound_stmts.rst:1873 +#: ../../reference/compound_stmts.rst:1881 msgid ":class:`memoryview`" msgstr ":class:`memoryview`" -#: ../../reference/compound_stmts.rst:1874 +#: ../../reference/compound_stmts.rst:1882 msgid ":class:`range`" msgstr ":class:`range`" -#: ../../reference/compound_stmts.rst:1877 +#: ../../reference/compound_stmts.rst:1885 msgid "" "Subject values of type ``str``, ``bytes``, and ``bytearray`` do not match " "sequence patterns." msgstr "" +"Valores de assunto do tipo ``str``, ``bytes`` e ``bytearray`` não " +"correspondem aos padrões de sequência." -#: ../../reference/compound_stmts.rst:1880 +#: ../../reference/compound_stmts.rst:1888 msgid "In pattern matching, a mapping is defined as one of the following:" msgstr "" +"Na correspondência de padrões, um mapeamento é definido como uma das " +"seguintes:" -#: ../../reference/compound_stmts.rst:1882 +#: ../../reference/compound_stmts.rst:1890 msgid "a class that inherits from :class:`collections.abc.Mapping`" -msgstr "" +msgstr "uma classe que herda de :class:`collections.abc.Mapping`" -#: ../../reference/compound_stmts.rst:1883 +#: ../../reference/compound_stmts.rst:1891 msgid "" "a Python class that has been registered as :class:`collections.abc.Mapping`" msgstr "" +"uma classe Python que foi registrada como :class:`collections.abc.Mapping`" -#: ../../reference/compound_stmts.rst:1884 +#: ../../reference/compound_stmts.rst:1892 msgid "" "a builtin class that has its (CPython) :c:macro:`Py_TPFLAGS_MAPPING` bit set" msgstr "" +"uma classe embutida que tem seu bit :c:macro:`Py_TPFLAGS_MAPPING` (CPython) " +"definido" -#: ../../reference/compound_stmts.rst:1887 +#: ../../reference/compound_stmts.rst:1895 msgid "" "The standard library classes :class:`dict` and :class:`types." "MappingProxyType` are mappings." msgstr "" +"As classes de biblioteca padrão :class:`dict` e :class:`types." +"MappingProxyType` são mapeamentos." -#: ../../reference/compound_stmts.rst:1890 +#: ../../reference/compound_stmts.rst:1898 msgid "" "A string literal appearing as the first statement in the function body is " "transformed into the function's :attr:`~function.__doc__` attribute and " "therefore the function's :term:`docstring`." msgstr "" +"Um literal de string que aparece como a primeira instrução no corpo da " +"função é transformado no atributo :attr:`~function.__doc__` da função e, " +"portanto, no :term:`docstring` da função." -#: ../../reference/compound_stmts.rst:1894 +#: ../../reference/compound_stmts.rst:1902 msgid "" "A string literal appearing as the first statement in the class body is " -"transformed into the namespace's ``__doc__`` item and therefore the class's :" -"term:`docstring`." +"transformed into the namespace's :attr:`~type.__doc__` item and therefore " +"the class's :term:`docstring`." msgstr "" +"Um literal de string que aparece como a primeira instrução no corpo da " +"classe é transformado no item :attr:`~type.__doc__` do espaço de nomes e, " +"portanto, no :term:`docstring` da classe." #: ../../reference/compound_stmts.rst:7 msgid "compound" -msgstr "" +msgstr "compound" #: ../../reference/compound_stmts.rst:7 ../../reference/compound_stmts.rst:86 #: ../../reference/compound_stmts.rst:111 @@ -2367,20 +3485,20 @@ msgstr "" #: ../../reference/compound_stmts.rst:471 #: ../../reference/compound_stmts.rst:588 #: ../../reference/compound_stmts.rst:1195 -#: ../../reference/compound_stmts.rst:1381 -#: ../../reference/compound_stmts.rst:1491 -#: ../../reference/compound_stmts.rst:1525 -#: ../../reference/compound_stmts.rst:1570 +#: ../../reference/compound_stmts.rst:1389 +#: ../../reference/compound_stmts.rst:1499 +#: ../../reference/compound_stmts.rst:1533 +#: ../../reference/compound_stmts.rst:1578 msgid "statement" msgstr "instrução" #: ../../reference/compound_stmts.rst:21 msgid "clause" -msgstr "" +msgstr "cláusula" #: ../../reference/compound_stmts.rst:21 msgid "suite" -msgstr "" +msgstr "conjunto (suite)" #: ../../reference/compound_stmts.rst:21 msgid "; (semicolon)" @@ -2396,7 +3514,7 @@ msgstr "token DEDENT" #: ../../reference/compound_stmts.rst:64 msgid "dangling" -msgstr "" +msgstr "pendurado" #: ../../reference/compound_stmts.rst:64 ../../reference/compound_stmts.rst:86 #: ../../reference/compound_stmts.rst:111 @@ -2418,13 +3536,13 @@ msgstr "if" #: ../../reference/compound_stmts.rst:408 #: ../../reference/compound_stmts.rst:471 #: ../../reference/compound_stmts.rst:588 -#: ../../reference/compound_stmts.rst:1501 +#: ../../reference/compound_stmts.rst:1509 msgid "keyword" msgstr "palavra reservada" #: ../../reference/compound_stmts.rst:86 msgid "elif" -msgstr "" +msgstr "elif" #: ../../reference/compound_stmts.rst:86 ../../reference/compound_stmts.rst:111 #: ../../reference/compound_stmts.rst:144 @@ -2432,8 +3550,8 @@ msgstr "" #: ../../reference/compound_stmts.rst:471 #: ../../reference/compound_stmts.rst:588 #: ../../reference/compound_stmts.rst:1195 -#: ../../reference/compound_stmts.rst:1322 -#: ../../reference/compound_stmts.rst:1381 +#: ../../reference/compound_stmts.rst:1325 +#: ../../reference/compound_stmts.rst:1389 msgid ": (colon)" msgstr ": (dois pontos)" @@ -2443,9 +3561,9 @@ msgstr ": (dois pontos)" #: ../../reference/compound_stmts.rst:471 #: ../../reference/compound_stmts.rst:588 #: ../../reference/compound_stmts.rst:1195 -#: ../../reference/compound_stmts.rst:1381 +#: ../../reference/compound_stmts.rst:1389 msgid "compound statement" -msgstr "" +msgstr "instrução composta" #: ../../reference/compound_stmts.rst:111 msgid "while" @@ -2489,7 +3607,7 @@ msgstr "lista" #: ../../reference/compound_stmts.rst:144 #: ../../reference/compound_stmts.rst:298 #: ../../reference/compound_stmts.rst:1195 -#: ../../reference/compound_stmts.rst:1381 +#: ../../reference/compound_stmts.rst:1389 msgid "object" msgstr "objeto" @@ -2527,7 +3645,7 @@ msgstr "as" #: ../../reference/compound_stmts.rst:265 msgid "except clause" -msgstr "" +msgstr "cláusula except" #: ../../reference/compound_stmts.rst:298 msgid "module" @@ -2543,7 +3661,7 @@ msgstr "traceback" #: ../../reference/compound_stmts.rst:327 msgid "except_star" -msgstr "" +msgstr "except_star" #: ../../reference/compound_stmts.rst:390 #: ../../reference/compound_stmts.rst:437 @@ -2552,206 +3670,206 @@ msgstr "return" #: ../../reference/compound_stmts.rst:471 msgid "with" -msgstr "" +msgstr "with" #: ../../reference/compound_stmts.rst:471 msgid "with statement" -msgstr "" +msgstr "instrução with" #: ../../reference/compound_stmts.rst:471 #: ../../reference/compound_stmts.rst:1195 -#: ../../reference/compound_stmts.rst:1381 +#: ../../reference/compound_stmts.rst:1389 msgid ", (comma)" msgstr ", (vírgula)" #: ../../reference/compound_stmts.rst:588 msgid "match" -msgstr "" +msgstr "match" #: ../../reference/compound_stmts.rst:588 msgid "case" -msgstr "" +msgstr "case" #: ../../reference/compound_stmts.rst:588 msgid "pattern matching" -msgstr "" +msgstr "correspondência de padrões" #: ../../reference/compound_stmts.rst:588 msgid "match statement" -msgstr "" +msgstr "instrução match" #: ../../reference/compound_stmts.rst:692 msgid "guard" -msgstr "" +msgstr "guard" #: ../../reference/compound_stmts.rst:731 msgid "irrefutable case block" -msgstr "" +msgstr "bloco irrefutável de case" #: ../../reference/compound_stmts.rst:731 msgid "case block" -msgstr "" +msgstr "bloco de case" #: ../../reference/compound_stmts.rst:755 msgid "! patterns" -msgstr "" +msgstr "padrões !" #: ../../reference/compound_stmts.rst:755 msgid "AS pattern, OR pattern, capture pattern, wildcard pattern" -msgstr "" +msgstr "padrão AS, padrão OR, padrão de captura, padrão curinga" #: ../../reference/compound_stmts.rst:1186 -#: ../../reference/compound_stmts.rst:1272 +#: ../../reference/compound_stmts.rst:1275 msgid "parameter" msgstr "parâmetro" #: ../../reference/compound_stmts.rst:1186 #: ../../reference/compound_stmts.rst:1195 -#: ../../reference/compound_stmts.rst:1236 -#: ../../reference/compound_stmts.rst:1272 -#: ../../reference/compound_stmts.rst:1301 +#: ../../reference/compound_stmts.rst:1239 +#: ../../reference/compound_stmts.rst:1275 +#: ../../reference/compound_stmts.rst:1304 msgid "function definition" -msgstr "" +msgstr "definição de função" #: ../../reference/compound_stmts.rst:1195 msgid "def" -msgstr "" +msgstr "def" #: ../../reference/compound_stmts.rst:1195 -#: ../../reference/compound_stmts.rst:1322 +#: ../../reference/compound_stmts.rst:1325 msgid "function" msgstr "função" #: ../../reference/compound_stmts.rst:1195 -#: ../../reference/compound_stmts.rst:1381 +#: ../../reference/compound_stmts.rst:1389 msgid "definition" msgstr "definição" #: ../../reference/compound_stmts.rst:1195 -#: ../../reference/compound_stmts.rst:1381 +#: ../../reference/compound_stmts.rst:1389 msgid "name" msgstr "nome" #: ../../reference/compound_stmts.rst:1195 -#: ../../reference/compound_stmts.rst:1381 +#: ../../reference/compound_stmts.rst:1389 msgid "binding" -msgstr "vinculação" +msgstr "vinculação; ligação" #: ../../reference/compound_stmts.rst:1195 msgid "user-defined function" msgstr "função definida por usuário" #: ../../reference/compound_stmts.rst:1195 -#: ../../reference/compound_stmts.rst:1381 +#: ../../reference/compound_stmts.rst:1389 msgid "() (parentheses)" msgstr "() (parênteses)" #: ../../reference/compound_stmts.rst:1195 msgid "parameter list" -msgstr "" +msgstr "lista de parâmetros" -#: ../../reference/compound_stmts.rst:1236 -#: ../../reference/compound_stmts.rst:1431 +#: ../../reference/compound_stmts.rst:1239 +#: ../../reference/compound_stmts.rst:1439 msgid "@ (at)" msgstr "@ (arroba)" -#: ../../reference/compound_stmts.rst:1272 +#: ../../reference/compound_stmts.rst:1275 msgid "default" msgstr "default" -#: ../../reference/compound_stmts.rst:1272 +#: ../../reference/compound_stmts.rst:1275 msgid "value" -msgstr "value" +msgstr "valor" -#: ../../reference/compound_stmts.rst:1272 +#: ../../reference/compound_stmts.rst:1275 msgid "argument" msgstr "argumento" -#: ../../reference/compound_stmts.rst:1272 +#: ../../reference/compound_stmts.rst:1275 msgid "= (equals)" msgstr "= (igual)" -#: ../../reference/compound_stmts.rst:1301 +#: ../../reference/compound_stmts.rst:1304 msgid "/ (slash)" msgstr "/ (barra)" -#: ../../reference/compound_stmts.rst:1301 +#: ../../reference/compound_stmts.rst:1304 msgid "* (asterisk)" msgstr "* (asterisco)" -#: ../../reference/compound_stmts.rst:1301 +#: ../../reference/compound_stmts.rst:1304 msgid "**" msgstr "**" -#: ../../reference/compound_stmts.rst:1322 +#: ../../reference/compound_stmts.rst:1325 msgid "annotations" msgstr "annotations" -#: ../../reference/compound_stmts.rst:1322 +#: ../../reference/compound_stmts.rst:1325 msgid "->" msgstr "->" -#: ../../reference/compound_stmts.rst:1322 +#: ../../reference/compound_stmts.rst:1325 msgid "function annotations" msgstr "anotações de função" -#: ../../reference/compound_stmts.rst:1340 +#: ../../reference/compound_stmts.rst:1348 msgid "lambda" msgstr "lambda" -#: ../../reference/compound_stmts.rst:1340 +#: ../../reference/compound_stmts.rst:1348 msgid "expression" msgstr "expressão" -#: ../../reference/compound_stmts.rst:1381 +#: ../../reference/compound_stmts.rst:1389 msgid "class" msgstr "classe" -#: ../../reference/compound_stmts.rst:1381 +#: ../../reference/compound_stmts.rst:1389 msgid "execution" msgstr "execução" -#: ../../reference/compound_stmts.rst:1381 +#: ../../reference/compound_stmts.rst:1389 msgid "frame" msgstr "quadro" -#: ../../reference/compound_stmts.rst:1381 +#: ../../reference/compound_stmts.rst:1389 msgid "inheritance" -msgstr "" +msgstr "herança" -#: ../../reference/compound_stmts.rst:1381 +#: ../../reference/compound_stmts.rst:1389 msgid "docstring" msgstr "docstring" -#: ../../reference/compound_stmts.rst:1381 -#: ../../reference/compound_stmts.rst:1431 +#: ../../reference/compound_stmts.rst:1389 +#: ../../reference/compound_stmts.rst:1439 msgid "class definition" -msgstr "" +msgstr "definição de classe" -#: ../../reference/compound_stmts.rst:1381 +#: ../../reference/compound_stmts.rst:1389 msgid "expression list" msgstr "expressão, lista de" -#: ../../reference/compound_stmts.rst:1491 +#: ../../reference/compound_stmts.rst:1499 msgid "async def" -msgstr "" +msgstr "async def" -#: ../../reference/compound_stmts.rst:1501 +#: ../../reference/compound_stmts.rst:1509 msgid "async" -msgstr "" +msgstr "async" -#: ../../reference/compound_stmts.rst:1501 +#: ../../reference/compound_stmts.rst:1509 msgid "await" msgstr "await" -#: ../../reference/compound_stmts.rst:1525 +#: ../../reference/compound_stmts.rst:1533 msgid "async for" msgstr "async for" -#: ../../reference/compound_stmts.rst:1570 +#: ../../reference/compound_stmts.rst:1578 msgid "async with" -msgstr "" +msgstr "async with" -#: ../../reference/compound_stmts.rst:1627 +#: ../../reference/compound_stmts.rst:1635 msgid "type parameters" -msgstr "" +msgstr "parâmetros de tipo" diff --git a/reference/datamodel.po b/reference/datamodel.po index aa4ea0059..9e2db3cf1 100644 --- a/reference/datamodel.po +++ b/reference/datamodel.po @@ -1,40 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Tiago Henrique , 2021 -# Raphael Mendonça, 2021 -# Welington Carlos , 2021 -# Willian Lopes, 2021 -# Paulo Candido, 2023 -# Alexandre B A Villares, 2023 -# Vinicius Gubiani Ferreira , 2023 -# Marco Rougeth , 2023 -# Ricardo Cappellano , 2023 -# felipe caridade fernandes , 2023 -# Victor Matheus Castro , 2023 -# Julia Rizza , 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# Vitor Buxbaum Orlandi, 2023 -# Adorilson Bezerra , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:19+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-02 14:19+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -631,13 +616,13 @@ msgstr "Bytes" msgid "" "A bytes object is an immutable array. The items are 8-bit bytes, " "represented by integers in the range 0 <= x < 256. Bytes literals (like " -"``b'abc'``) and the built-in :func:`bytes()` constructor can be used to " -"create bytes objects. Also, bytes objects can be decoded to strings via " -"the :meth:`~bytes.decode` method." +"``b'abc'``) and the built-in :func:`bytes` constructor can be used to create " +"bytes objects. Also, bytes objects can be decoded to strings via the :meth:" +"`~bytes.decode` method." msgstr "" "Um objeto bytes é um vetor imutável. Os itens são bytes de 8 bits, " "representados por inteiros no intervalo 0 <= x < 256. Literais de bytes " -"(como ``b'abc'``) e o construtor embutido :func:`bytes()` podem ser usados " +"(como ``b'abc'``) e o construtor embutido :func:`bytes` podem ser usados " "para criar objetos bytes. Além disso, os objetos bytes podem ser " "decodificados em strings através do método :meth:`~bytes.decode`." @@ -826,10 +811,10 @@ msgstr "" #: ../../reference/datamodel.rst:499 msgid "" -"Dictionaries are mutable; they can be created by the ``{...}`` notation (see " +"Dictionaries are mutable; they can be created by the ``{}`` notation (see " "section :ref:`dict`)." msgstr "" -"Os dicionários são mutáveis; eles podem ser criados pela notação ``{...}`` " +"Os dicionários são mutáveis; eles podem ser criados pela notação ``{}`` " "(veja a seção :ref:`dict`)." #: ../../reference/datamodel.rst:506 @@ -878,16 +863,18 @@ msgstr "" "argumentos contendo o mesmo número de itens que a lista de parâmetros " "formais da função." -#: ../../reference/datamodel.rst:545 ../../reference/datamodel.rst:1133 -#: ../../reference/datamodel.rst:1330 +#: ../../reference/datamodel.rst:545 ../../reference/datamodel.rst:1395 +#: ../../reference/datamodel.rst:1594 msgid "Special read-only attributes" msgstr "Atributos especiais de somente leitura" -#: ../../reference/datamodel.rst:555 ../../reference/datamodel.rst:589 +#: ../../reference/datamodel.rst:555 ../../reference/datamodel.rst:590 +#: ../../reference/datamodel.rst:1170 msgid "Attribute" msgstr "Atributo" -#: ../../reference/datamodel.rst:556 ../../reference/datamodel.rst:590 +#: ../../reference/datamodel.rst:556 ../../reference/datamodel.rst:591 +#: ../../reference/datamodel.rst:1171 msgid "Meaning" msgstr "Significado" @@ -903,13 +890,15 @@ msgstr "" #: ../../reference/datamodel.rst:564 msgid "" -"``None`` or a :class:`tuple` of cells that contain bindings for the " -"function's free variables." +"``None`` or a :class:`tuple` of cells that contain bindings for the names " +"specified in the :attr:`~codeobject.co_freevars` attribute of the " +"function's :attr:`code object `." msgstr "" -"``None`` ou uma :class:`tuple` de células que contêm vinculações para as " -"variáveis livres da função." +"``None`` ou uma :class:`tuple` de células que contêm ligação para os nomes " +"especificados no atributo :attr:`~codeobject.co_freevars` do :attr:`objeto " +"código ` da função." -#: ../../reference/datamodel.rst:567 +#: ../../reference/datamodel.rst:568 msgid "" "A cell object has the attribute ``cell_contents``. This can be used to get " "the value of the cell, as well as set the value." @@ -917,21 +906,17 @@ msgstr "" "Um objeto de célula tem o atributo ``cell_contents``. Isso pode ser usado " "para obter o valor da célula, bem como definir o valor." -#: ../../reference/datamodel.rst:571 ../../reference/datamodel.rst:1372 +#: ../../reference/datamodel.rst:572 ../../reference/datamodel.rst:1636 msgid "Special writable attributes" msgstr "Atributos especiais graváveis" -#: ../../reference/datamodel.rst:584 +#: ../../reference/datamodel.rst:585 msgid "Most of these attributes check the type of the assigned value:" msgstr "A maioria desses atributos verifica o tipo do valor atribuído:" -#: ../../reference/datamodel.rst:593 -msgid "" -"The function's documentation string, or ``None`` if unavailable. Not " -"inherited by subclasses." -msgstr "" -"A string de documentação da função, ou ``None`` se não estiver disponível. " -"Não herdado por subclasses." +#: ../../reference/datamodel.rst:594 +msgid "The function's documentation string, or ``None`` if unavailable." +msgstr "A string de documentação da função, ou ``None`` se indisponível." #: ../../reference/datamodel.rst:597 msgid "" @@ -1053,7 +1038,7 @@ msgstr "" "Um objeto método de instância combina uma classe, uma instância de classe e " "qualquer objeto chamável (normalmente uma função definida pelo usuário)." -#: ../../reference/datamodel.rst:676 ../../reference/datamodel.rst:1468 +#: ../../reference/datamodel.rst:676 ../../reference/datamodel.rst:1732 msgid "Special read-only attributes:" msgstr "Atributos especiais de somente leitura:" @@ -1321,11 +1306,11 @@ msgstr "" "atributo tem a mesma semântica de :attr:`outros métodos de instância `.)" -#: ../../reference/datamodel.rst:837 +#: ../../reference/datamodel.rst:838 msgid "Classes" msgstr "Classes" -#: ../../reference/datamodel.rst:839 +#: ../../reference/datamodel.rst:840 msgid "" "Classes are callable. These objects normally act as factories for new " "instances of themselves, but variations are possible for class types that " @@ -1339,11 +1324,11 @@ msgstr "" "passados para :meth:`!__new__` e, no caso típico, para :meth:`~object." "__init__` para inicializar a nova instância." -#: ../../reference/datamodel.rst:847 +#: ../../reference/datamodel.rst:848 msgid "Class Instances" msgstr "Instâncias de classe" -#: ../../reference/datamodel.rst:849 +#: ../../reference/datamodel.rst:850 msgid "" "Instances of arbitrary classes can be made callable by defining a :meth:" "`~object.__call__` method in their class." @@ -1351,11 +1336,11 @@ msgstr "" "Instâncias de classes arbitrárias podem ser tornados chamáveis definindo um " "método :meth:`~object.__call__` em sua classe." -#: ../../reference/datamodel.rst:854 +#: ../../reference/datamodel.rst:857 msgid "Modules" msgstr "Módulos" -#: ../../reference/datamodel.rst:860 +#: ../../reference/datamodel.rst:863 msgid "" "Modules are a basic organizational unit of Python code, and are created by " "the :ref:`import system ` as invoked either by the :keyword:" @@ -1381,7 +1366,7 @@ msgstr "" "inicializar o módulo (uma vez que não é necessário depois que a " "inicialização é concluída)." -#: ../../reference/datamodel.rst:873 +#: ../../reference/datamodel.rst:876 msgid "" "Attribute assignment updates the module's namespace dictionary, e.g., ``m.x " "= 1`` is equivalent to ``m.__dict__[\"x\"] = 1``." @@ -1389,50 +1374,378 @@ msgstr "" "A atribuição de atributo atualiza o dicionário de espaço de nomes do módulo, " "por exemplo, ``m.x = 1`` é equivalente a ``m.__dict__[\"x\"] = 1``." -#: ../../reference/datamodel.rst:883 -msgid "Predefined (writable) attributes:" -msgstr "Atributos predefinidos (graváveis):" +#: ../../reference/datamodel.rst:894 +msgid "Import-related attributes on module objects" +msgstr "Atributos relacionados à importação em objetos de módulo" + +#: ../../reference/datamodel.rst:896 +msgid "" +"Module objects have the following attributes that relate to the :ref:`import " +"system `. When a module is created using the machinery " +"associated with the import system, these attributes are filled in based on " +"the module's :term:`spec `, before the :term:`loader` executes " +"and loads the module." +msgstr "" +"Objetos de módulo têm os seguintes atributos que se relacionam ao :ref:" +"`sistema de importação `. Quando um módulo é criado usando o " +"maquinário associado ao sistema de importação, esses atributos são " +"preenchidos com base no :term:`spec ` do módulo, antes que o :" +"term:`carregador` execute e carregue o módulo." + +#: ../../reference/datamodel.rst:902 +msgid "" +"To create a module dynamically rather than using the import system, it's " +"recommended to use :func:`importlib.util.module_from_spec`, which will set " +"the various import-controlled attributes to appropriate values. It's also " +"possible to use the :class:`types.ModuleType` constructor to create modules " +"directly, but this technique is more error-prone, as most attributes must be " +"manually set on the module object after it has been created when using this " +"approach." +msgstr "" +"Para criar um módulo dinamicamente em vez de usar o sistema de importação, é " +"recomendado usar :func:`importlib.util.module_from_spec`, que definirá os " +"vários atributos controlados pela importação para valores apropriados. " +"Também é possível usar o construtor :class:`types.ModuleType` para criar " +"módulos diretamente, mas essa técnica é mais propensa a erros, pois a " +"maioria dos atributos deve ser definida manualmente no objeto do módulo após " +"ele ter sido criado ao usar essa abordagem." + +#: ../../reference/datamodel.rst:912 +msgid "" +"With the exception of :attr:`~module.__name__`, it is **strongly** " +"recommended that you rely on :attr:`~module.__spec__` and its attributes " +"instead of any of the other individual attributes listed in this subsection. " +"Note that updating an attribute on :attr:`!__spec__` will not update the " +"corresponding attribute on the module itself:" +msgstr "" +"Com exceção de :attr:`~module.__name__`, é **fortemente** recomendado que " +"você confie no :attr:`~module.__spec__` e seus atributos em vez de qualquer " +"um dos outros atributos individuais listados nesta subseção. Observe que " +"atualizar um atributo em :attr:`!__spec__` não atualizará o atributo " +"correspondente no próprio módulo:" + +#: ../../reference/datamodel.rst:918 +msgid "" +">>> import typing\n" +">>> typing.__name__, typing.__spec__.name\n" +"('typing', 'typing')\n" +">>> typing.__spec__.name = 'spelling'\n" +">>> typing.__name__, typing.__spec__.name\n" +"('typing', 'spelling')\n" +">>> typing.__name__ = 'keyboard_smashing'\n" +">>> typing.__name__, typing.__spec__.name\n" +"('keyboard_smashing', 'spelling')" +msgstr "" +">>> import typing\n" +">>> typing.__name__, typing.__spec__.name\n" +"('typing', 'typing')\n" +">>> typing.__spec__.name = 'spelling'\n" +">>> typing.__name__, typing.__spec__.name\n" +"('typing', 'spelling')\n" +">>> typing.__name__ = 'keyboard_smashing'\n" +">>> typing.__name__, typing.__spec__.name\n" +"('keyboard_smashing', 'spelling')" + +#: ../../reference/datamodel.rst:932 +msgid "" +"The name used to uniquely identify the module in the import system. For a " +"directly executed module, this will be set to ``\"__main__\"``." +msgstr "" +"O nome usado para identificar exclusivamente o módulo no sistema de " +"importação. Para um módulo executado diretamente, isso será definido como " +"``\"__main__\"``." + +#: ../../reference/datamodel.rst:935 +msgid "" +"This attribute must be set to the fully qualified name of the module. It is " +"expected to match the value of :attr:`module.__spec__.name `." +msgstr "" +"Este atributo deve ser definido como o nome totalmente qualificado do " +"módulo. Espera-se que ele corresponda ao valor de :attr:`module.__spec__." +"name `." + +#: ../../reference/datamodel.rst:941 +msgid "A record of the module's import-system-related state." +msgstr "Um registro do estado relacionado ao sistema de importação do módulo." + +#: ../../reference/datamodel.rst:943 +msgid "" +"Set to the :class:`module spec ` that was " +"used when importing the module. See :ref:`module-specs` for more details." +msgstr "" +"Define com :class:`spec de módulo ` que foi " +"usado ao importar o módulo. Veja :ref:`module-specs` para mais detalhes." + +#: ../../reference/datamodel.rst:950 +msgid "The :term:`package` a module belongs to." +msgstr "O :term:`pacote` ao qual um módulo pertence." + +#: ../../reference/datamodel.rst:952 +msgid "" +"If the module is top-level (that is, not a part of any specific package) " +"then the attribute should be set to ``''`` (the empty string). Otherwise, it " +"should be set to the name of the module's package (which can be equal to :" +"attr:`module.__name__` if the module itself is a package). See :pep:`366` " +"for further details." +msgstr "" +"Se o módulo for de nível superior (ou seja, não fizer parte de nenhum pacote " +"específico), o atributo deve ser definido como ``''`` (a string vazia). Caso " +"contrário, deve ser definido como o nome do pacote do módulo (que pode ser " +"igual a :attr:`module.__name__` se o módulo em si for um pacote). Veja :pep:" +"`366` para mais detalhes." + +#: ../../reference/datamodel.rst:958 +msgid "" +"This attribute is used instead of :attr:`~module.__name__` to calculate " +"explicit relative imports for main modules. It defaults to ``None`` for " +"modules created dynamically using the :class:`types.ModuleType` constructor; " +"use :func:`importlib.util.module_from_spec` instead to ensure the attribute " +"is set to a :class:`str`." +msgstr "" +"Este atributo é usado em vez de :attr:`~module.__name__` para calcular " +"importações relativas explícitas para módulos principais. O padrão é " +"``None`` para módulos criados dinamicamente usando o construtor :class:" +"`types.ModuleType`; use :func:`importlib.util.module_from_spec` em vez disso " +"para garantir que o atributo seja definido como :class:`str`." + +#: ../../reference/datamodel.rst:964 +msgid "" +"It is **strongly** recommended that you use :attr:`module.__spec__.parent " +"` instead of :attr:`!module." +"__package__`. :attr:`__package__` is now only used as a fallback if :attr:`!" +"__spec__.parent` is not set, and this fallback path is deprecated." +msgstr "" +"É **fortemente** recomendado que você use :attr:`module.__spec__.parent " +"` em vez de :attr:`!module." +"__package__`. :attr:`__package__` agora só é usado como fallback se :attr:`!" +"__spec__.parent` não estiver definido, e esse caminho de fallback está " +"descontinuado." -#: ../../reference/datamodel.rst:885 -msgid ":attr:`__name__`" -msgstr ":attr:`__name__`" +#: ../../reference/datamodel.rst:970 ../../reference/datamodel.rst:1011 +msgid "" +"This attribute now defaults to ``None`` for modules created dynamically " +"using the :class:`types.ModuleType` constructor. Previously the attribute " +"was optional." +msgstr "" +"Este atributo agora presume o padrão ``None`` para módulos criados " +"dinamicamente usando o construtor :class:`types.ModuleType`. Anteriormente, " +"o atributo era opcional." -#: ../../reference/datamodel.rst:886 -msgid "The module's name." -msgstr "O nome do módulo." +#: ../../reference/datamodel.rst:975 +msgid "" +"The value of :attr:`!__package__` is expected to be the same as :attr:" +"`__spec__.parent `. :attr:" +"`__package__` is now only used as a fallback during import resolution if :" +"attr:`!__spec__.parent` is not defined." +msgstr "" +"Espera-se que o valor de :attr:`!__package__` seja o mesmo que :attr:" +"`__spec__.parent `. :attr:" +"`__package__` agora é usado apenas como fallback durante a resolução de " +"importação se :attr:`!__spec__.parent` não estiver definido." -#: ../../reference/datamodel.rst:888 ../../reference/datamodel.rst:988 -msgid ":attr:`__doc__`" -msgstr ":attr:`__doc__`" +#: ../../reference/datamodel.rst:981 +msgid "" +":exc:`ImportWarning` is raised if an import resolution falls back to :attr:`!" +"__package__` instead of :attr:`__spec__.parent `." +msgstr "" +":exc:`ImportWarning` é levantada se uma resolução de importação retorna " +"para :attr:`!__package__` em vez de :attr:`__spec__.parent `." -#: ../../reference/datamodel.rst:889 -msgid "The module's documentation string, or ``None`` if unavailable." -msgstr "A string de documentação do módulo, ou ``None`` se indisponível." +#: ../../reference/datamodel.rst:986 +msgid "" +"Raise :exc:`DeprecationWarning` instead of :exc:`ImportWarning` when falling " +"back to :attr:`!__package__` during import resolution." +msgstr "" +"Levanta :exc:`DeprecationWarning` em vez de :exc:`ImportWarning` ao retornar " +"para :attr:`!__package__` durante a resolução de importação." -#: ../../reference/datamodel.rst:892 -msgid ":attr:`__file__`" -msgstr ":attr:`__file__`" +#: ../../reference/datamodel.rst:990 +msgid "" +":attr:`!__package__` will cease to be set or taken into consideration by the " +"import system or standard library." +msgstr "" +":attr:`!__package__` deixará de ser definido ou levado em consideração pelo " +"sistema de importação ou biblioteca padrão." -#: ../../reference/datamodel.rst:893 +#: ../../reference/datamodel.rst:996 msgid "" -"The pathname of the file from which the module was loaded, if it was loaded " -"from a file. The :attr:`__file__` attribute may be missing for certain types " -"of modules, such as C modules that are statically linked into the " -"interpreter. For extension modules loaded dynamically from a shared " -"library, it's the pathname of the shared library file." +"The :term:`loader` object that the import machinery used to load the module." msgstr "" -"O endereço do caminho do arquivo que o módulo foi carregado, se ele foi " -"carregado a partir de um arquivo. O atributo :attr:`__file__` pode estar " -"ausente para certos tipos de módulos, como os módulos C que são " -"estaticamente vinculados ao interpretador. Para extensões de módulos " -"carregadas dinamicamente de uma biblioteca compartilhada, é o endereço do " -"caminho do arquivo da biblioteca compartilhada." +"O objeto :term:`carregador` que o maquinário de importação usou para " +"carregar o módulo." -#: ../../reference/datamodel.rst:901 ../../reference/datamodel.rst:991 -msgid ":attr:`__annotations__`" -msgstr ":attr:`__annotations__`" +#: ../../reference/datamodel.rst:998 +msgid "" +"This attribute is mostly useful for introspection, but can be used for " +"additional loader-specific functionality, for example getting data " +"associated with a loader." +msgstr "" +"Este atributo é útil principalmente para introspecção, mas pode ser usado " +"para funcionalidades adicionais específicas do carregador, por exemplo, para " +"obter dados associados a um carregador." -#: ../../reference/datamodel.rst:902 +#: ../../reference/datamodel.rst:1002 +msgid "" +":attr:`!__loader__` defaults to ``None`` for modules created dynamically " +"using the :class:`types.ModuleType` constructor; use :func:`importlib.util." +"module_from_spec` instead to ensure the attribute is set to a :term:`loader` " +"object." +msgstr "" +":attr:`!__loader__` assume como padrão ``None`` para módulos criados " +"dinamicamente usando o construtor :class:`types.ModuleType`; use :func:" +"`importlib.util.module_from_spec` para garantir que o atributo seja definido " +"como um objeto :term:`carregador`." + +#: ../../reference/datamodel.rst:1007 +msgid "" +"It is **strongly** recommended that you use :attr:`module.__spec__.loader " +"` instead of :attr:`!module." +"__loader__`." +msgstr "" +"É **fortemetne** recomendado que você use :attr:`module.__spec__.loader " +"` em vez de :attr:`!module." +"__loader__`." + +#: ../../reference/datamodel.rst:1016 +msgid "" +"Setting :attr:`!__loader__` on a module while failing to set :attr:`!" +"__spec__.loader` is deprecated. In Python 3.16, :attr:`!__loader__` will " +"cease to be set or taken into consideration by the import system or the " +"standard library." +msgstr "" +"A definição :attr:`!__loader__` em um módulo enquanto falha na definição de :" +"attr:`!__spec__.loader` está descontinuado. No Python 3.16, :attr:`!" +"__loader__` deixará de ser definido ou levado em consideração pelo sistema " +"de importação ou pela biblioteca padrão." + +#: ../../reference/datamodel.rst:1024 +msgid "" +"A (possibly empty) :term:`sequence` of strings enumerating the locations " +"where the package's submodules will be found. Non-package modules should not " +"have a :attr:`!__path__` attribute. See :ref:`package-path-rules` for more " +"details." +msgstr "" +"Uma :term:`sequência` (possivelmente vazia) de strings enumerando os locais " +"onde os submódulos do pacote serão encontrados. Módulos que não sejam de " +"pacote não devem ter um atributo :attr:`!__path__`. Veja :ref:`package-path-" +"rules` para mais detalhes." + +#: ../../reference/datamodel.rst:1029 +msgid "" +"It is **strongly** recommended that you use :attr:`module.__spec__." +"submodule_search_locations ` instead of :attr:`!module.__path__`." +msgstr "" +"É **fortemente** recomendado que você use :attr:`module.__spec__." +"submodule_search_locations ` em vez de :attr:`!module.__path__`." + +#: ../../reference/datamodel.rst:1036 +msgid "" +":attr:`!__file__` and :attr:`!__cached__` are both optional attributes that " +"may or may not be set. Both attributes should be a :class:`str` when they " +"are available." +msgstr "" +":attr:`!__file__` e :attr:`!__cached__` são atributos opcionais que podem ou " +"não ser definidos. Ambos os atributos devem ser um :class:`str` quando " +"estiverem disponíveis." + +#: ../../reference/datamodel.rst:1040 +msgid "" +":attr:`!__file__` indicates the pathname of the file from which the module " +"was loaded (if loaded from a file), or the pathname of the shared library " +"file for extension modules loaded dynamically from a shared library. It " +"might be missing for certain types of modules, such as C modules that are " +"statically linked into the interpreter, and the :ref:`import system " +"` may opt to leave it unset if it has no semantic meaning (for " +"example, a module loaded from a database)." +msgstr "" +":attr:`!__file__` indica o nome do caminho do arquivo do qual o módulo foi " +"carregado (se carregado de um arquivo) ou o nome do caminho do arquivo da " +"biblioteca compartilhada para módulos de extensão carregados dinamicamente " +"de uma biblioteca compartilhada. Pode estar faltando para certos tipos de " +"módulos, como módulos C que estão estaticamente vinculados ao interpretador, " +"e o :ref:`sistema de importação ` pode optar por deixá-lo sem " +"definição se não tiver significado semântico (por exemplo, um módulo " +"carregado de um banco de dados)." + +#: ../../reference/datamodel.rst:1048 +msgid "" +"If :attr:`!__file__` is set then the :attr:`!__cached__` attribute might " +"also be set, which is the path to any compiled version of the code (for " +"example, a byte-compiled file). The file does not need to exist to set this " +"attribute; the path can simply point to where the compiled file *would* " +"exist (see :pep:`3147`)." +msgstr "" +"Se :attr:`!__file__` estiver definido então o atributo :attr:`!__cached__` " +"também pode ser definido, que é o caminho para qualquer versão compilada do " +"código (por exemplo, um arquivo compilado por byte). O arquivo não precisa " +"existir para configurar esse atributo; o caminho pode simplesmente apontar " +"para onde o arquivo compilado existiria (veja :pep:`3147`)." + +#: ../../reference/datamodel.rst:1054 +msgid "" +"Note that :attr:`!__cached__` may be set even if :attr:`!__file__` is not " +"set. However, that scenario is quite atypical. Ultimately, the :term:" +"`loader` is what makes use of the module spec provided by the :term:`finder` " +"(from which :attr:`!__file__` and :attr:`!__cached__` are derived). So if a " +"loader can load from a cached module but otherwise does not load from a " +"file, that atypical scenario may be appropriate." +msgstr "" +"Observe que :attr:`!__cached__` pode ser definido mesmo se :attr:`!__file__` " +"não estiver definido. No entanto, esse cenário é bastante atípico. Em última " +"análise, o :term:`carregador` é o que faz uso do spec de módulo fornecido " +"pelo :term:`localizador` (do qual :attr:`!__file__` e :attr:`!__cached__` " +"são derivados). Portanto, se um carregador puder carregar a partir de um " +"módulo em cache, mas não carregar a partir de um arquivo, esse cenário " +"atípico poderá ser apropriado." + +#: ../../reference/datamodel.rst:1061 +msgid "" +"It is **strongly** recommended that you use :attr:`module.__spec__.cached " +"` instead of :attr:`!module." +"__cached__`." +msgstr "" +"É **fortemente** recomendado que você use :attr:`module.__spec__.cached " +"` em vez de :attr:`!module." +"__cached__`." + +#: ../../reference/datamodel.rst:1065 +msgid "" +"Setting :attr:`!__cached__` on a module while failing to set :attr:`!" +"__spec__.cached` is deprecated. In Python 3.15, :attr:`!__cached__` will " +"cease to be set or taken into consideration by the import system or standard " +"library." +msgstr "" +"A definição :attr:`!__cached__` em um módulo enquanto falha na definição de :" +"attr:`!__spec__.cached` está descontinuado. No Python 3.15, :attr:`!" +"__cached__` deixará de ser definido ou levado em consideração pelo sistema " +"de importação ou pela biblioteca padrão." + +#: ../../reference/datamodel.rst:1072 +msgid "Other writable attributes on module objects" +msgstr "Outros atributos graváveis em objetos de módulo" + +#: ../../reference/datamodel.rst:1074 +msgid "" +"As well as the import-related attributes listed above, module objects also " +"have the following writable attributes:" +msgstr "" +"Além dos atributos relacionados à importação listados acima, os objetos de " +"módulo também têm os seguintes atributos graváveis:" + +#: ../../reference/datamodel.rst:1079 +msgid "" +"The module's documentation string, or ``None`` if unavailable. See also: :" +"attr:`__doc__ attributes `." +msgstr "" +"A string de documentação do módulo, ou ``None`` se indisponível. Veja " +"também: :attr:`atributos __doc__ `." + +#: ../../reference/datamodel.rst:1084 msgid "" "A dictionary containing :term:`variable annotations ` " "collected during module body execution. For best practices on working with :" @@ -1443,15 +1756,27 @@ msgstr "" "sobre como trabalhar com :attr:`__annotations__`, por favor veja :ref:" "`annotations-howto`." -#: ../../reference/datamodel.rst:909 +#: ../../reference/datamodel.rst:1090 +msgid "Module dictionaries" +msgstr "Dicionários do módulo" + +#: ../../reference/datamodel.rst:1092 +msgid "Module objects also have the following special read-only attribute:" +msgstr "" +"Os objetos de módulo também têm o seguinte atributo especial somente leitura:" + +#: ../../reference/datamodel.rst:1097 msgid "" -"Special read-only attribute: :attr:`~object.__dict__` is the module's " -"namespace as a dictionary object." +"The module's namespace as a dictionary object. Uniquely among the attributes " +"listed here, :attr:`!__dict__` cannot be accessed as a global variable from " +"within a module; it can only be accessed as an attribute on module objects." msgstr "" -"Atributo especial somente leitura: :attr:`~object.__dict__` é o espaço de " -"nomes do módulo como um objeto dicionário." +"O espaço de nomes do módulo como um objeto dicionário. Exclusivamente entre " +"os atributos listados aqui, :attr:`!__dict__` não pode ser acessado como uma " +"variável global de dentro de um módulo; ele só pode ser acessado como um " +"atributo em objetos de módulo." -#: ../../reference/datamodel.rst:914 +#: ../../reference/datamodel.rst:1103 msgid "" "Because of the way CPython clears module dictionaries, the module dictionary " "will be cleared when the module falls out of scope even if the dictionary " @@ -1463,11 +1788,11 @@ msgstr "" "ainda tiver referências ativas. Para evitar isso, copie o dicionário ou " "mantenha o módulo por perto enquanto usa seu dicionário diretamente." -#: ../../reference/datamodel.rst:921 +#: ../../reference/datamodel.rst:1112 msgid "Custom classes" msgstr "Classes personalizadas" -#: ../../reference/datamodel.rst:923 +#: ../../reference/datamodel.rst:1114 msgid "" "Custom class types are typically created by class definitions (see section :" "ref:`class`). A class has a namespace implemented by a dictionary object. " @@ -1494,7 +1819,7 @@ msgstr "" "Detalhes adicionais sobre a ordem de resolução de métodos (MRO) C3 usado " "pelo Python podem ser encontrados em :ref:`python_2.3_mro`." -#: ../../reference/datamodel.rst:944 +#: ../../reference/datamodel.rst:1135 msgid "" "When a class attribute reference (for class :class:`!C`, say) would yield a " "class method object, it is transformed into an instance method object whose :" @@ -1513,7 +1838,7 @@ msgstr "" "classe podem diferir daqueles realmente contidos em seu :attr:`~object." "__dict__`." -#: ../../reference/datamodel.rst:955 +#: ../../reference/datamodel.rst:1146 msgid "" "Class attribute assignments update the class's dictionary, never the " "dictionary of a base class." @@ -1521,7 +1846,7 @@ msgstr "" "As atribuições de atributos de classe atualizam o dicionário da classe, " "nunca o dicionário de uma classe base." -#: ../../reference/datamodel.rst:960 +#: ../../reference/datamodel.rst:1151 msgid "" "A class object can be called (see above) to yield a class instance (see " "below)." @@ -1529,101 +1854,165 @@ msgstr "" "Um objeto classe pode ser chamado (veja acima) para produzir uma instância " "de classe (veja abaixo)." -#: ../../reference/datamodel.rst:973 -msgid "Special attributes:" -msgstr "Atributos especiais:" - -#: ../../reference/datamodel.rst:975 -msgid ":attr:`~definition.__name__`" -msgstr ":attr:`~definition.__name__`" +#: ../../reference/datamodel.rst:1154 ../../reference/datamodel.rst:1301 +msgid "Special attributes" +msgstr "Atributos especiais" -#: ../../reference/datamodel.rst:976 -msgid "The class name." -msgstr "O nome da classe." +#: ../../reference/datamodel.rst:1174 +msgid "" +"The class's name. See also: :attr:`__name__ attributes `." +msgstr "" +"O nome da classe. Veja também: :attr:`atributos __name__ `." -#: ../../reference/datamodel.rst:978 -msgid ":attr:`__module__`" -msgstr ":attr:`__module__`" +#: ../../reference/datamodel.rst:1178 +msgid "" +"The class's :term:`qualified name`. See also: :attr:`__qualname__ attributes " +"`." +msgstr "" +"O :term:`nome qualificado` da classe. Veja também: :attr:`atributos " +"__qualname__ `." -#: ../../reference/datamodel.rst:979 +#: ../../reference/datamodel.rst:1182 msgid "The name of the module in which the class was defined." msgstr "O nome do módulo no qual a classe foi definida." -#: ../../reference/datamodel.rst:981 -msgid ":attr:`~object.__dict__`" -msgstr ":attr:`~object.__dict__`" - -#: ../../reference/datamodel.rst:982 -msgid "The dictionary containing the class's namespace." -msgstr "O dicionário contendo o espaço de nomes da classe." - -#: ../../reference/datamodel.rst:984 -msgid ":attr:`~class.__bases__`" -msgstr ":attr:`~class.__bases__`" +#: ../../reference/datamodel.rst:1185 +msgid "" +"A :class:`mapping proxy ` providing a read-only view " +"of the class's namespace. See also: :attr:`__dict__ attributes `." +msgstr "" +"Um :class:`proxy de mapeamento ` fornecendo uma " +"visão somente leitura do espaço de nomes da classe. Veja também: :attr:" +"`atributos __dict__ `." -#: ../../reference/datamodel.rst:985 +#: ../../reference/datamodel.rst:1190 msgid "" -"A tuple containing the base classes, in the order of their occurrence in the " -"base class list." +"A :class:`tuple` containing the class's bases. In most cases, for a class " +"defined as ``class X(A, B, C)``, ``X.__bases__`` will be exactly equal to " +"``(A, B, C)``." msgstr "" -"Uma tupla contendo a classe base, na ordem de suas ocorrências na lista da " -"classe base." +"Uma :class:`tuple` contendo as bases da classe. Na maioria dos casos, para " +"uma classe definida como ``class X(A, B, C)``, ``X.__bases__`` será " +"exatamente igual a ``(A, B, C)``." -#: ../../reference/datamodel.rst:989 -msgid "The class's documentation string, or ``None`` if undefined." -msgstr "A string de documentação da classe, ou ``None`` se não definida." +#: ../../reference/datamodel.rst:1195 +msgid "" +"The class's documentation string, or ``None`` if undefined. Not inherited by " +"subclasses." +msgstr "" +"A string de documentação da classe, ou ``None`` se não estiver definida. Não " +"herdado por subclasses." -#: ../../reference/datamodel.rst:992 +#: ../../reference/datamodel.rst:1199 msgid "" "A dictionary containing :term:`variable annotations ` " -"collected during class body execution. For best practices on working with :" -"attr:`__annotations__`, please see :ref:`annotations-howto`." +"collected during class body execution. For best practices on working with :" +"attr:`!__annotations__`, please see :ref:`annotations-howto`." msgstr "" "Um dicionário contendo :term:`anotações de variável ` " "coletadas durante a execução do corpo da classe. Para melhores práticas " -"sobre como trabalhar com :attr:`__annotations__`, por favor veja :ref:" +"sobre como trabalhar com :attr:`!__annotations__`, por favor veja :ref:" "`annotations-howto`." -#: ../../reference/datamodel.rst:998 -msgid ":attr:`__type_params__`" -msgstr ":attr:`__type_params__`" +#: ../../reference/datamodel.rst:1206 +msgid "" +"Accessing the :attr:`!__annotations__` attribute of a class object directly " +"may yield incorrect results in the presence of metaclasses. In addition, the " +"attribute may not exist for some classes. Use :func:`inspect." +"get_annotations` to retrieve class annotations safely." +msgstr "" +"Acessar o atributo :attr:`!__annotations__` de um objeto classe diretamente " +"pode produzir resultados incorretos na presença de metaclasses. Além disso, " +"o atributo pode não existir para algumas classes. Use :func:`inspect." +"get_annotations` para recuperar anotações de classe com segurança." -#: ../../reference/datamodel.rst:999 +#: ../../reference/datamodel.rst:1213 msgid "" -"A tuple containing the :ref:`type parameters ` of a :ref:" -"`generic class `." +"A :class:`tuple` containing the :ref:`type parameters ` of a :" +"ref:`generic class `." msgstr "" -"Uma tupla contendo os :ref:`parâmetos de tipos ` de uma :ref:" -"`classe genérica `." +"Uma :class:`tuple` contendo os :ref:`parâmetros de tipo ` de " +"uma :ref:`classe genérica `." -#: ../../reference/datamodel.rst:1002 -msgid ":attr:`~class.__static_attributes__`" -msgstr ":attr:`~class.__static_attributes__`" +#: ../../reference/datamodel.rst:1219 +msgid "" +"A :class:`tuple` containing names of attributes of this class which are " +"assigned through ``self.X`` from any function in its body." +msgstr "" +"Uma :class:`tuple` contendo nomes de atributos dessa classe que são " +"atribuídos por meio de ``self.X`` de qualquer função em seu corpo." -#: ../../reference/datamodel.rst:1003 +#: ../../reference/datamodel.rst:1225 msgid "" -"A tuple containing names of attributes of this class which are assigned " -"through ``self.X`` from any function in its body." +"The line number of the first line of the class definition, including " +"decorators. Setting the :attr:`__module__` attribute removes the :attr:`!" +"__firstlineno__` item from the type's dictionary." msgstr "" -"Uma tupla contendo nomes de atributos dessa classe que são atribuídos por " -"meio de ``self.X`` de qualquer função em seu corpo." +"O número da linha da primeira linha da definição de classe, incluindo " +"decoradores. Definir o atributo :attr:`__module__` remove o item :attr:`!" +"__firstlineno__` do dicionário do tipo." -#: ../../reference/datamodel.rst:1006 -msgid ":attr:`__firstlineno__`" -msgstr ":attr:`__firstlineno__`" +#: ../../reference/datamodel.rst:1233 +msgid "" +"The :class:`tuple` of classes that are considered when looking for base " +"classes during method resolution." +msgstr "" +"A :class:`tuple` de classes que são consideradas ao procurar por classes " +"bases durante resolução de métodos." -#: ../../reference/datamodel.rst:1007 +#: ../../reference/datamodel.rst:1238 +msgid "Special methods" +msgstr "Métodos especiais" + +#: ../../reference/datamodel.rst:1240 msgid "" -"The line number of the first line of the class definition, including " -"decorators." +"In addition to the special attributes described above, all Python classes " +"also have the following two methods available:" +msgstr "" +"Além dos atributos especiais descritos acima, todas as classes Python também " +"têm os dois métodos a seguir disponíveis:" + +#: ../../reference/datamodel.rst:1245 +msgid "" +"This method can be overridden by a metaclass to customize the method " +"resolution order for its instances. It is called at class instantiation, " +"and its result is stored in :attr:`~type.__mro__`." msgstr "" -"O número da primeira linha da definição de classe, incluindo decoradores." +"Este método pode ser substituído por uma metaclasse para personalizar a " +"ordem de resolução de métodos para suas instâncias. Ele é chamado na " +"instanciação da classe, e o seu resultado é armazenado em :attr:`~type." +"__mro__`." -#: ../../reference/datamodel.rst:1011 +#: ../../reference/datamodel.rst:1251 +msgid "" +"Each class keeps a list of weak references to its immediate subclasses. This " +"method returns a list of all those references still alive. The list is in " +"definition order. Example:" +msgstr "" +"Cada classe mantém uma lista de referências fracas para suas subclasses " +"imediatas. Este método retorna uma lista de todas essas referências ainda " +"vivas. A lista está na ordem que são definidas. Exemplo::" + +#: ../../reference/datamodel.rst:1255 +msgid "" +">>> class A: pass\n" +">>> class B(A): pass\n" +">>> A.__subclasses__()\n" +"[]" +msgstr "" +">>> class A: pass\n" +">>> class B(A): pass\n" +">>> A.__subclasses__()\n" +"[]" + +#: ../../reference/datamodel.rst:1263 msgid "Class instances" msgstr "Instâncias de classe" -#: ../../reference/datamodel.rst:1019 +#: ../../reference/datamodel.rst:1271 msgid "" "A class instance is created by calling a class object (see above). A class " "instance has a namespace implemented as a dictionary which is the first " @@ -1654,7 +2043,7 @@ msgstr "" "classe for encontrado, e a classe do objeto tiver um método :meth:`~object." "__getattr__`, este é chamado para satisfazer a pesquisa." -#: ../../reference/datamodel.rst:1035 +#: ../../reference/datamodel.rst:1287 msgid "" "Attribute assignments and deletions update the instance's dictionary, never " "a class's dictionary. If the class has a :meth:`~object.__setattr__` or :" @@ -1666,7 +2055,7 @@ msgstr "" "__setattr__` ou :meth:`~object.__delattr__`, ele é chamado ao invés de " "atualizar o dicionário da instância diretamente." -#: ../../reference/datamodel.rst:1045 +#: ../../reference/datamodel.rst:1297 msgid "" "Class instances can pretend to be numbers, sequences, or mappings if they " "have methods with certain special names. See section :ref:`specialnames`." @@ -1675,19 +2064,25 @@ msgstr "" "se tiverem métodos com certos nomes especiais. Veja a seção :ref:" "`specialnames`." -#: ../../reference/datamodel.rst:1052 +#: ../../reference/datamodel.rst:1309 +msgid "The class to which a class instance belongs." +msgstr "A classe à qual pertence uma instância de classe." + +#: ../../reference/datamodel.rst:1313 msgid "" -"Special attributes: :attr:`~object.__dict__` is the attribute dictionary; :" -"attr:`~instance.__class__` is the instance's class." +"A dictionary or other mapping object used to store an object's (writable) " +"attributes. Not all instances have a :attr:`!__dict__` attribute; see the " +"section on :ref:`slots` for more details." msgstr "" -"Atributos especiais: :attr:`~object.__dict__` é o dicionário de atributos; :" -"attr:`~instance.__class__` é a classe da instância." +"Um dicionário ou outro objeto de mapeamento usado para armazenar atributos " +"(graváveis) de um objeto. Nem todas as instâncias têm um atributo :attr:`!" +"__dict__`; veja a seção sobre :ref:`slots` para mais detalhes." -#: ../../reference/datamodel.rst:1057 +#: ../../reference/datamodel.rst:1319 msgid "I/O objects (also known as file objects)" msgstr "Objetos de E/S (também conhecidos como objetos arquivo)" -#: ../../reference/datamodel.rst:1072 +#: ../../reference/datamodel.rst:1334 msgid "" "A :term:`file object` represents an open file. Various shortcuts are " "available to create file objects: the :func:`open` built-in function, and " @@ -1701,7 +2096,7 @@ msgstr "" "`~socket.socket.makefile` de objetos soquete (e talvez por outras funções ou " "métodos fornecidos por módulos de extensão)." -#: ../../reference/datamodel.rst:1078 +#: ../../reference/datamodel.rst:1340 msgid "" "The objects ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are initialized " "to file objects corresponding to the interpreter's standard input, output " @@ -1713,11 +2108,11 @@ msgstr "" "padrão do interpretador; eles são todos abertos em modo texto e, portanto, " "seguem a interface definida pela classe abstrata :class:`io.TextIOBase`." -#: ../../reference/datamodel.rst:1086 +#: ../../reference/datamodel.rst:1348 msgid "Internal types" msgstr "Tipos internos" -#: ../../reference/datamodel.rst:1092 +#: ../../reference/datamodel.rst:1354 msgid "" "A few types used internally by the interpreter are exposed to the user. " "Their definitions may change with future versions of the interpreter, but " @@ -1727,11 +2122,11 @@ msgstr "" "Suas definições podem mudar com versões futuras do interpretador, mas são " "mencionadas aqui para fins de integridade." -#: ../../reference/datamodel.rst:1100 +#: ../../reference/datamodel.rst:1362 msgid "Code objects" msgstr "Objetos código" -#: ../../reference/datamodel.rst:1104 +#: ../../reference/datamodel.rst:1366 msgid "" "Code objects represent *byte-compiled* executable Python code, or :term:" "`bytecode`. The difference between a code object and a function object is " @@ -1752,15 +2147,15 @@ msgstr "" "são imutáveis e não contêm referências (direta ou indiretamente) a objetos " "mutáveis." -#: ../../reference/datamodel.rst:1138 +#: ../../reference/datamodel.rst:1400 msgid "The function name" msgstr "O nome da função" -#: ../../reference/datamodel.rst:1141 +#: ../../reference/datamodel.rst:1403 msgid "The fully qualified function name" msgstr "O nome completo da função" -#: ../../reference/datamodel.rst:1146 +#: ../../reference/datamodel.rst:1408 msgid "" "The total number of positional :term:`parameters ` (including " "positional-only parameters and parameters with default values) that the " @@ -1770,7 +2165,7 @@ msgstr "" "parâmetros somente-posicionais e parâmetros com valores padrão) que a função " "possui" -#: ../../reference/datamodel.rst:1151 +#: ../../reference/datamodel.rst:1413 msgid "" "The number of positional-only :term:`parameters ` (including " "arguments with default values) that the function has" @@ -1778,7 +2173,7 @@ msgstr "" "O número de :term:`parâmetros ` somente-posicionais (incluindo " "argumentos com valores padrão) que a função possui" -#: ../../reference/datamodel.rst:1155 +#: ../../reference/datamodel.rst:1417 msgid "" "The number of keyword-only :term:`parameters ` (including " "arguments with default values) that the function has" @@ -1786,7 +2181,7 @@ msgstr "" "O número de :term:`parâmetros ` somente-nomeados (incluindo " "argumentos com valores padrão) que a função possui" -#: ../../reference/datamodel.rst:1159 +#: ../../reference/datamodel.rst:1421 msgid "" "The number of :ref:`local variables ` used by the function " "(including parameters)" @@ -1794,56 +2189,69 @@ msgstr "" "O número de :ref:`variáveis locais ` usadas pela função (incluindo " "parâmetros)" -#: ../../reference/datamodel.rst:1163 +#: ../../reference/datamodel.rst:1425 msgid "" "A :class:`tuple` containing the names of the local variables in the function " "(starting with the parameter names)" msgstr "" -"Uma :class:`tuple` contendo os nomes das variáveis ​​locais na função " +"Uma :class:`tuple` contendo os nomes das variáveis locais na função " "(começando com os nomes dos parâmetros)" -#: ../../reference/datamodel.rst:1167 +#: ../../reference/datamodel.rst:1429 msgid "" "A :class:`tuple` containing the names of :ref:`local variables ` " -"that are referenced by nested functions inside the function" +"that are referenced from at least one :term:`nested scope` inside the " +"function" msgstr "" -"Uma :class:`tuple` contendo os nomes de :ref:`variáveis ​​locais ` que " -"são referenciadas por funções aninhadas dentro da função" +"Uma :class:`tuple` contendo os nomes de :ref:`variáveis locais ` que " +"são referenciadas a partir de pelo menos um :term:`escopo aninhado` de " +"dentro da função" -#: ../../reference/datamodel.rst:1171 -msgid "A :class:`tuple` containing the names of free variables in the function" -msgstr "Uma :class:`tuple` contendo os nomes das variáveis ​​livres na função" +#: ../../reference/datamodel.rst:1433 +msgid "" +"A :class:`tuple` containing the names of :term:`free (closure) variables " +"` that a :term:`nested scope` references in an outer " +"scope. See also :attr:`function.__closure__`." +msgstr "" +"Uma :class:`tuple` contendo os nomes de :term:`variáveis livres (de " +"clausura) ` que um :term:`escopo aninhado` referencia em " +"um escopo externo. Veja também :attr:`function.__closure__`." -#: ../../reference/datamodel.rst:1174 +#: ../../reference/datamodel.rst:1437 +msgid "Note: references to global and builtin names are *not* included." +msgstr "" +"Observação: referências a nomes globais e embutidos *não* estão incluídas." + +#: ../../reference/datamodel.rst:1440 msgid "" "A string representing the sequence of :term:`bytecode` instructions in the " "function" msgstr "" "Uma string representando a sequência de instruções :term:`bytecode` na função" -#: ../../reference/datamodel.rst:1178 +#: ../../reference/datamodel.rst:1444 msgid "" "A :class:`tuple` containing the literals used by the :term:`bytecode` in the " "function" msgstr "" -"Um :class:`tuple` contendo os literais usados ​​pelo :term:`bytecode` na função" +"Um :class:`tuple` contendo os literais usados pelo :term:`bytecode` na função" -#: ../../reference/datamodel.rst:1182 +#: ../../reference/datamodel.rst:1448 msgid "" "A :class:`tuple` containing the names used by the :term:`bytecode` in the " "function" msgstr "" -"Um :class:`tuple` contendo os nomes usados ​​pelo :term:`bytecode` na função" +"Um :class:`tuple` contendo os nomes usados pelo :term:`bytecode` na função" -#: ../../reference/datamodel.rst:1186 +#: ../../reference/datamodel.rst:1452 msgid "The name of the file from which the code was compiled" msgstr "O nome do arquivo do qual o código foi compilado" -#: ../../reference/datamodel.rst:1189 +#: ../../reference/datamodel.rst:1455 msgid "The line number of the first line of the function" msgstr "O número da linha da primeira linha da função" -#: ../../reference/datamodel.rst:1192 +#: ../../reference/datamodel.rst:1458 msgid "" "A string encoding the mapping from :term:`bytecode` offsets to line numbers. " "For details, see the source code of the interpreter." @@ -1852,26 +2260,26 @@ msgstr "" "números de linha. Para obter detalhes, consulte o código-fonte do " "interpretador." -#: ../../reference/datamodel.rst:1195 +#: ../../reference/datamodel.rst:1461 msgid "" "This attribute of code objects is deprecated, and may be removed in Python " -"3.14." +"3.15." msgstr "" "Este atributo de objetos código está descontinuado e pode ser removido no " -"Python 3.14." +"Python 3.15." -#: ../../reference/datamodel.rst:1200 +#: ../../reference/datamodel.rst:1466 msgid "The required stack size of the code object" msgstr "O tamanho de pilha necessário do objeto código" -#: ../../reference/datamodel.rst:1203 +#: ../../reference/datamodel.rst:1469 msgid "" "An :class:`integer ` encoding a number of flags for the interpreter." msgstr "" "Um número :class:`inteiro ` codificando uma série de sinalizadores para " "o interpretador." -#: ../../reference/datamodel.rst:1208 +#: ../../reference/datamodel.rst:1474 msgid "" "The following flag bits are defined for :attr:`~codeobject.co_flags`: bit " "``0x04`` is set if the function uses the ``*arguments`` syntax to accept an " @@ -1889,27 +2297,25 @@ msgstr "" "função for um gerador. Veja :ref:`inspect-module-co-flags` para detalhes na " "semântica de cada sinalizadores que podem estar presentes." -#: ../../reference/datamodel.rst:1216 +#: ../../reference/datamodel.rst:1482 msgid "" -"Future feature declarations (``from __future__ import division``) also use " -"bits in :attr:`~codeobject.co_flags` to indicate whether a code object was " -"compiled with a particular feature enabled: bit ``0x2000`` is set if the " -"function was compiled with future division enabled; bits ``0x10`` and " -"``0x1000`` were used in earlier versions of Python." +"Future feature declarations (for example, ``from __future__ import " +"division``) also use bits in :attr:`~codeobject.co_flags` to indicate " +"whether a code object was compiled with a particular feature enabled. See :" +"attr:`~__future__._Feature.compiler_flag`." msgstr "" -"Declarações de recursos futuros (``from __future__ import division``) também " -"usam bits em :attr:`~codeobject.co_flags` para indicar se um objeto código " -"foi compilado com um recurso específico habilitado: o bit ``0x2000`` é " -"definido se a função foi compilada com divisão futura habilitada; os bits " -"``0x10`` e ``0x1000`` foram usados em versões anteriores do Python." +"Declarações de recursos futuros (por exemplo, ``from __future__ import " +"division``) também usam bits em :attr:`~codeobject.co_flags` para indicar se " +"um objeto código foi compilado com um recurso específico habilitado. Veja :" +"attr:`~__future__._Feature.compiler_flag`." -#: ../../reference/datamodel.rst:1222 +#: ../../reference/datamodel.rst:1486 msgid "" "Other bits in :attr:`~codeobject.co_flags` are reserved for internal use." msgstr "" "Outros bits em :attr:`~codeobject.co_flags` são reservados para uso interno." -#: ../../reference/datamodel.rst:1226 +#: ../../reference/datamodel.rst:1490 msgid "" "If a code object represents a function, the first item in :attr:`~codeobject." "co_consts` is the documentation string of the function, or ``None`` if " @@ -1919,11 +2325,11 @@ msgstr "" "`~codeobject.co_consts` é a string de documentação da função, ou ``None`` se " "indefinido." -#: ../../reference/datamodel.rst:1231 +#: ../../reference/datamodel.rst:1495 msgid "Methods on code objects" msgstr "Métodos de objetos código" -#: ../../reference/datamodel.rst:1235 +#: ../../reference/datamodel.rst:1499 msgid "" "Returns an iterable over the source code positions of each :term:`bytecode` " "instruction in the code object." @@ -1931,7 +2337,7 @@ msgstr "" "Retorna um iterável das posições no código-fonte de cada instrução :term:" "`bytecode` no objeto código." -#: ../../reference/datamodel.rst:1238 +#: ../../reference/datamodel.rst:1502 msgid "" "The iterator returns :class:`tuple`\\s containing the ``(start_line, " "end_line, start_column, end_column)``. The *i-th* tuple corresponds to the " @@ -1944,7 +2350,7 @@ msgstr "" "informações da coluna são deslocamentos de bytes utf-8 indexados em 0 na " "linha de código fornecida." -#: ../../reference/datamodel.rst:1244 +#: ../../reference/datamodel.rst:1508 msgid "" "This positional information can be missing. A non-exhaustive lists of cases " "where this may happen:" @@ -1952,21 +2358,21 @@ msgstr "" "A informação posicional pode estar ausente. Veja uma lista não-exaustiva de " "casos onde isso pode acontecer:" -#: ../../reference/datamodel.rst:1247 +#: ../../reference/datamodel.rst:1511 msgid "Running the interpreter with :option:`-X` ``no_debug_ranges``." msgstr "Executando o interpretador com ``no_debug_ranges`` :option:`-X`." -#: ../../reference/datamodel.rst:1248 +#: ../../reference/datamodel.rst:1512 msgid "" "Loading a pyc file compiled while using :option:`-X` ``no_debug_ranges``." msgstr "" "Carregando um arquivo pyc compilado com ``no_debug_ranges`` :option:`-X`." -#: ../../reference/datamodel.rst:1249 +#: ../../reference/datamodel.rst:1513 msgid "Position tuples corresponding to artificial instructions." msgstr "Tuplas posicionais correspondendo a instruções artificiais." -#: ../../reference/datamodel.rst:1250 +#: ../../reference/datamodel.rst:1514 msgid "" "Line and column numbers that can't be represented due to implementation " "specific limitations." @@ -1974,14 +2380,14 @@ msgstr "" "Números de linha e coluna que não podem ser representados devido a " "limitações específicas de implementação." -#: ../../reference/datamodel.rst:1253 +#: ../../reference/datamodel.rst:1517 msgid "" "When this occurs, some or all of the tuple elements can be :const:`None`." msgstr "" "Quando isso ocorre, alguns ou todos elementos da tupla podem ser :const:" "`None`." -#: ../../reference/datamodel.rst:1259 +#: ../../reference/datamodel.rst:1523 msgid "" "This feature requires storing column positions in code objects which may " "result in a small increase of disk usage of compiled Python files or " @@ -1997,7 +2403,7 @@ msgstr "" "rastreamento, use a opção de linha de comando ``no_debug_ranges`` :option:`-" "X` ou a variável de ambiente :envvar:`PYTHONNODEBUGRANGES`." -#: ../../reference/datamodel.rst:1268 +#: ../../reference/datamodel.rst:1532 msgid "" "Returns an iterator that yields information about successive ranges of :term:" "`bytecode`\\s. Each item yielded is a ``(start, end, lineno)`` :class:" @@ -2007,7 +2413,7 @@ msgstr "" "term:`bytecode`\\s. Cada item gerado é uma :class:`tuple` de ``(start, end, " "lineno)``:" -#: ../../reference/datamodel.rst:1272 +#: ../../reference/datamodel.rst:1536 msgid "" "``start`` (an :class:`int`) represents the offset (inclusive) of the start " "of the :term:`bytecode` range" @@ -2015,7 +2421,7 @@ msgstr "" "``start`` (um :class:`int`) representa o deslocamento (inclusivo) do início " "do intervalo :term:`bytecode`" -#: ../../reference/datamodel.rst:1274 +#: ../../reference/datamodel.rst:1538 msgid "" "``end`` (an :class:`int`) represents the offset (exclusive) of the end of " "the :term:`bytecode` range" @@ -2023,7 +2429,7 @@ msgstr "" "``end`` (um :class:`int`) representa o deslocamento (exclusivo) do fim do " "intervalo :term:`bytecode`" -#: ../../reference/datamodel.rst:1276 +#: ../../reference/datamodel.rst:1540 msgid "" "``lineno`` is an :class:`int` representing the line number of the :term:" "`bytecode` range, or ``None`` if the bytecodes in the given range have no " @@ -2033,15 +2439,15 @@ msgstr "" "do :term:`bytecode`, ou ``None`` se os bytecodes no intervalo fornecido não " "tiverem número de linha" -#: ../../reference/datamodel.rst:1280 +#: ../../reference/datamodel.rst:1544 msgid "The items yielded will have the following properties:" msgstr "Os itens gerados terão as seguintes propriedades:" -#: ../../reference/datamodel.rst:1282 +#: ../../reference/datamodel.rst:1546 msgid "The first range yielded will have a ``start`` of 0." msgstr "O primeiro intervalo gerado terá um ``start`` de 0." -#: ../../reference/datamodel.rst:1283 +#: ../../reference/datamodel.rst:1547 msgid "" "The ``(start, end)`` ranges will be non-decreasing and consecutive. That is, " "for any pair of :class:`tuple`\\s, the ``start`` of the second will be equal " @@ -2051,11 +2457,11 @@ msgstr "" "seja, para qualquer par de :class:`tuple`\\s, o ``start`` do segundo será " "igual ao ``end`` do primeiro." -#: ../../reference/datamodel.rst:1286 +#: ../../reference/datamodel.rst:1550 msgid "No range will be backwards: ``end >= start`` for all triples." msgstr "Nenhum intervalo será inverso: ``end >= start`` para todos os trios." -#: ../../reference/datamodel.rst:1287 +#: ../../reference/datamodel.rst:1551 msgid "" "The last :class:`tuple` yielded will have ``end`` equal to the size of the :" "term:`bytecode`." @@ -2063,44 +2469,44 @@ msgstr "" "A última :class:`tuple` gerada terá ``end`` igual ao tamanho do :term:" "`bytecode`." -#: ../../reference/datamodel.rst:1290 +#: ../../reference/datamodel.rst:1554 msgid "" "Zero-width ranges, where ``start == end``, are allowed. Zero-width ranges " "are used for lines that are present in the source code, but have been " "eliminated by the :term:`bytecode` compiler." msgstr "" "Intervalos de largura zero, onde ``start == end``, são permitidos. " -"Intervalos de largura zero são usados ​​para linhas que estão presentes no " +"Intervalos de largura zero são usados para linhas que estão presentes no " "código-fonte, mas foram eliminadas pelo compilador de :term:`bytecode`." -#: ../../reference/datamodel.rst:1298 +#: ../../reference/datamodel.rst:1562 msgid ":pep:`626` - Precise line numbers for debugging and other tools." msgstr "" ":pep:`626` - Números de linha precisos para depuração e outras ferramentas." -#: ../../reference/datamodel.rst:1299 +#: ../../reference/datamodel.rst:1563 msgid "The PEP that introduced the :meth:`!co_lines` method." msgstr "A PEP que introduziu o método :meth:`!co_lines`." -#: ../../reference/datamodel.rst:1303 +#: ../../reference/datamodel.rst:1567 msgid "" "Return a copy of the code object with new values for the specified fields." msgstr "" "Retorna uma cópia do objeto de código com novos valores para os campos " "especificados." -#: ../../reference/datamodel.rst:1305 +#: ../../reference/datamodel.rst:1569 msgid "" "Code objects are also supported by the generic function :func:`copy.replace`." msgstr "" "Objetos de código também são suportados pela função genérica :func:`copy." "replace`." -#: ../../reference/datamodel.rst:1313 +#: ../../reference/datamodel.rst:1577 msgid "Frame objects" msgstr "Objetos quadro" -#: ../../reference/datamodel.rst:1317 +#: ../../reference/datamodel.rst:1581 msgid "" "Frame objects represent execution frames. They may occur in :ref:`traceback " "objects `, and are also passed to registered trace " @@ -2110,7 +2516,7 @@ msgstr "" "`objetos traceback ` e também são passados para funções " "de rastreamento registradas." -#: ../../reference/datamodel.rst:1335 +#: ../../reference/datamodel.rst:1599 msgid "" "Points to the previous stack frame (towards the caller), or ``None`` if this " "is the bottom stack frame" @@ -2118,7 +2524,7 @@ msgstr "" "Aponta para o quadro de pilha anterior (em direção ao chamador), ou ``None`` " "se este for o quadro de pilha mais abaixo." -#: ../../reference/datamodel.rst:1339 +#: ../../reference/datamodel.rst:1603 msgid "" "The :ref:`code object ` being executed in this frame. " "Accessing this attribute raises an :ref:`auditing event ` ``object." @@ -2128,28 +2534,28 @@ msgstr "" "este atributo levanta um :ref:`evento de auditoria ` ``object." "__getattr__`` com os argumentos ``obj`` e ``\"f_code\"``." -#: ../../reference/datamodel.rst:1344 +#: ../../reference/datamodel.rst:1608 msgid "" "The mapping used by the frame to look up :ref:`local variables `. If " "the frame refers to an :term:`optimized scope`, this may return a write-" "through proxy object." msgstr "" -"O mapeamento usado pelo quadro para procurar :ref:`variáveis ​​locais " +"O mapeamento usado pelo quadro para procurar :ref:`variáveis locais " "`. Se o quadro se referir a um :term:`escopo otimizado`, isso pode " "retornar um objeto proxy write-through." -#: ../../reference/datamodel.rst:1349 +#: ../../reference/datamodel.rst:1613 msgid "Return a proxy for optimized scopes." msgstr "Retorna um proxy para escopos otimizados." -#: ../../reference/datamodel.rst:1353 +#: ../../reference/datamodel.rst:1617 msgid "" "The dictionary used by the frame to look up :ref:`global variables `" msgstr "" -"O dicionário usado pelo quadro para procurar :ref:`variáveis ​​globais " +"O dicionário usado pelo quadro para procurar :ref:`variáveis globais " "`" -#: ../../reference/datamodel.rst:1357 +#: ../../reference/datamodel.rst:1621 msgid "" "The dictionary used by the frame to look up :ref:`built-in (intrinsic) names " "`" @@ -2157,7 +2563,7 @@ msgstr "" "O dicionário usado pelo quadro para procurar :ref:`nomes embutidos " "(intrínsecos) `" -#: ../../reference/datamodel.rst:1361 +#: ../../reference/datamodel.rst:1625 msgid "" "The \"precise instruction\" of the frame object (this is an index into the :" "term:`bytecode` string of the :ref:`code object `)" @@ -2165,7 +2571,7 @@ msgstr "" "A \"instrução precisa\" do objeto quadro (este é um índice na string :term:" "`bytecode` do :ref:`objeto código `)" -#: ../../reference/datamodel.rst:1377 +#: ../../reference/datamodel.rst:1641 msgid "" "If not ``None``, this is a function called for various events during code " "execution (this is used by debuggers). Normally an event is triggered for " @@ -2175,7 +2581,7 @@ msgstr "" "execução do código (isso é usado por depuradores). Normalmente, um evento é " "disparado para cada nova linha de origem (veja :attr:`~frame.f_trace_lines`)." -#: ../../reference/datamodel.rst:1382 +#: ../../reference/datamodel.rst:1646 msgid "" "Set this attribute to :const:`False` to disable triggering a tracing event " "for each source line." @@ -2183,7 +2589,7 @@ msgstr "" "Defina este atributo como :const:`False` para desabilitar o acionamento de " "um evento de rastreamento para cada linha de origem." -#: ../../reference/datamodel.rst:1386 +#: ../../reference/datamodel.rst:1650 msgid "" "Set this attribute to :const:`True` to allow per-opcode events to be " "requested. Note that this may lead to undefined interpreter behaviour if " @@ -2194,7 +2600,7 @@ msgstr "" "do interpretador se as exceções levantadas pela função de rastreamento " "escaparem para a função que está sendo rastreada." -#: ../../reference/datamodel.rst:1392 +#: ../../reference/datamodel.rst:1656 msgid "" "The current line number of the frame -- writing to this from within a trace " "function jumps to the given line (only for the bottom-most frame). A " @@ -2206,15 +2612,15 @@ msgstr "" "mais abaixo). Um depurador pode implementar um comando Jump (também " "conhecido como Set Next Statement) escrevendo para esse atributo." -#: ../../reference/datamodel.rst:1398 +#: ../../reference/datamodel.rst:1662 msgid "Frame object methods" msgstr "Métodos de objetos quadro" -#: ../../reference/datamodel.rst:1400 +#: ../../reference/datamodel.rst:1664 msgid "Frame objects support one method:" msgstr "Objetos quadro têm suporte a um método:" -#: ../../reference/datamodel.rst:1404 +#: ../../reference/datamodel.rst:1668 msgid "" "This method clears all references to :ref:`local variables ` held by " "the frame. Also, if the frame belonged to a :term:`generator`, the " @@ -2229,14 +2635,14 @@ msgstr "" "`exceção ` e armazenar seu :ref:`traceback ` para uso posterior)." -#: ../../reference/datamodel.rst:1410 +#: ../../reference/datamodel.rst:1674 msgid "" ":exc:`RuntimeError` is raised if the frame is currently executing or " "suspended." msgstr "" ":exc:`RuntimeError` é levantada se o quadro estiver em execução ou suspenso." -#: ../../reference/datamodel.rst:1415 +#: ../../reference/datamodel.rst:1679 msgid "" "Attempting to clear a suspended frame raises :exc:`RuntimeError` (as has " "always been the case for executing frames)." @@ -2244,11 +2650,11 @@ msgstr "" "Tentar limpar um quadro suspenso levanta :exc:`RuntimeError` (como sempre " "foi o caso para quadros em execução)." -#: ../../reference/datamodel.rst:1423 +#: ../../reference/datamodel.rst:1687 msgid "Traceback objects" msgstr "Objetos traceback" -#: ../../reference/datamodel.rst:1436 +#: ../../reference/datamodel.rst:1700 msgid "" "Traceback objects represent the stack trace of an :ref:`exception `. A traceback object is implicitly created when an exception occurs, " @@ -2259,13 +2665,13 @@ msgstr "" "implicitamente quando ocorre uma exceção e também pode ser criado " "explicitamente chamando :class:`types.TracebackType`." -#: ../../reference/datamodel.rst:1441 +#: ../../reference/datamodel.rst:1705 msgid "Traceback objects can now be explicitly instantiated from Python code." msgstr "" "Objetos traceback agora podem ser instanciados explicitamente a partir de " "código Python." -#: ../../reference/datamodel.rst:1444 +#: ../../reference/datamodel.rst:1708 msgid "" "For implicitly created tracebacks, when the search for an exception handler " "unwinds the execution stack, at each unwound level a traceback object is " @@ -2283,7 +2689,7 @@ msgstr "" "func:`sys.exc_info`, e como o atributo :attr:`~BaseException.__traceback__` " "da exceção capturada." -#: ../../reference/datamodel.rst:1453 +#: ../../reference/datamodel.rst:1717 msgid "" "When the program contains no suitable handler, the stack trace is written " "(nicely formatted) to the standard error stream; if the interpreter is " @@ -2295,7 +2701,7 @@ msgstr "" "interpretador for interativo, ele também é disponibilizado ao usuário como :" "data:`sys.last_traceback`." -#: ../../reference/datamodel.rst:1458 +#: ../../reference/datamodel.rst:1722 msgid "" "For explicitly created tracebacks, it is up to the creator of the traceback " "to determine how the :attr:`~traceback.tb_next` attributes should be linked " @@ -2305,13 +2711,13 @@ msgstr "" "determinar como os atributos :attr:`~traceback.tb_next` devem ser vinculados " "para formar um stack trace completo." -#: ../../reference/datamodel.rst:1473 +#: ../../reference/datamodel.rst:1737 msgid "" "Points to the execution :ref:`frame ` of the current level." msgstr "" "Aponta para o :ref:`quadro ` de execução do nível atual." -#: ../../reference/datamodel.rst:1476 +#: ../../reference/datamodel.rst:1740 msgid "" "Accessing this attribute raises an :ref:`auditing event ` ``object." "__getattr__`` with arguments ``obj`` and ``\"tb_frame\"``." @@ -2319,15 +2725,15 @@ msgstr "" "Acessar este atributo levanta um :ref:`evento de auditoria ` " "``object.__getattr__`` com os argumentos ``obj`` e ``\"tb_frame\"``." -#: ../../reference/datamodel.rst:1481 +#: ../../reference/datamodel.rst:1745 msgid "Gives the line number where the exception occurred" msgstr "Fornece o número da linha onde ocorreu a exceção" -#: ../../reference/datamodel.rst:1484 +#: ../../reference/datamodel.rst:1748 msgid "Indicates the \"precise instruction\"." msgstr "Indica a \"instrução precisa\"." -#: ../../reference/datamodel.rst:1486 +#: ../../reference/datamodel.rst:1750 msgid "" "The line number and last instruction in the traceback may differ from the " "line number of its :ref:`frame object ` if the exception " @@ -2339,7 +2745,7 @@ msgstr "" "uma instrução :keyword:`try` sem cláusula except correspondente ou com uma " "cláusula :keyword:`finally`." -#: ../../reference/datamodel.rst:1497 +#: ../../reference/datamodel.rst:1761 msgid "" "The special writable attribute :attr:`!tb_next` is the next level in the " "stack trace (towards the frame where the exception occurred), or ``None`` if " @@ -2349,15 +2755,15 @@ msgstr "" "trace (em direção ao quadro onde a exceção ocorreu), ou ``None`` se não " "houver próximo nível." -#: ../../reference/datamodel.rst:1501 +#: ../../reference/datamodel.rst:1765 msgid "This attribute is now writable" msgstr "Este atributo agora é gravável" -#: ../../reference/datamodel.rst:1506 +#: ../../reference/datamodel.rst:1770 msgid "Slice objects" msgstr "Objetos slice" -#: ../../reference/datamodel.rst:1510 +#: ../../reference/datamodel.rst:1774 msgid "" "Slice objects are used to represent slices for :meth:`~object.__getitem__` " "methods. They are also created by the built-in :func:`slice` function." @@ -2365,7 +2771,7 @@ msgstr "" "Objetos slice são usados para representar fatias para métodos :meth:`~object." "__getitem__`. Eles também são criados pela função embutida :func:`slice`." -#: ../../reference/datamodel.rst:1519 +#: ../../reference/datamodel.rst:1783 msgid "" "Special read-only attributes: :attr:`~slice.start` is the lower bound; :attr:" "`~slice.stop` is the upper bound; :attr:`~slice.step` is the step value; " @@ -2376,11 +2782,11 @@ msgstr "" "valor da diferença entre elementos subjacentes; cada um desses atributos é " "``None`` se omitido. Esses atributos podem ter qualquer tipo." -#: ../../reference/datamodel.rst:1523 +#: ../../reference/datamodel.rst:1787 msgid "Slice objects support one method:" msgstr "Objetos slice têm suporte a um método:" -#: ../../reference/datamodel.rst:1527 +#: ../../reference/datamodel.rst:1791 msgid "" "This method takes a single integer argument *length* and computes " "information about the slice that the slice object would describe if applied " @@ -2396,11 +2802,11 @@ msgstr "" "da fatia. Índices ausentes ou fora dos limites são tratados de maneira " "consistente com fatias regulares." -#: ../../reference/datamodel.rst:1536 +#: ../../reference/datamodel.rst:1800 msgid "Static method objects" msgstr "Objetos método estático" -#: ../../reference/datamodel.rst:1538 +#: ../../reference/datamodel.rst:1802 msgid "" "Static method objects provide a way of defeating the transformation of " "function objects to method objects described above. A static method object " @@ -2419,11 +2825,11 @@ msgstr "" "também são chamáveis. Objetos método estático são criados pelo construtor " "embutido :func:`staticmethod`." -#: ../../reference/datamodel.rst:1548 +#: ../../reference/datamodel.rst:1812 msgid "Class method objects" msgstr "Objetos método de classe" -#: ../../reference/datamodel.rst:1550 +#: ../../reference/datamodel.rst:1814 msgid "" "A class method object, like a static method object, is a wrapper around " "another object that alters the way in which that object is retrieved from " @@ -2439,11 +2845,11 @@ msgstr "" "instância\" `. Objetos método de classe são criados pelo " "construtor embutido :func:`classmethod`." -#: ../../reference/datamodel.rst:1560 +#: ../../reference/datamodel.rst:1824 msgid "Special method names" msgstr "Nomes de métodos especiais" -#: ../../reference/datamodel.rst:1566 +#: ../../reference/datamodel.rst:1830 msgid "" "A class can implement certain operations that are invoked by special syntax " "(such as arithmetic operations or subscripting and slicing) by defining " @@ -2467,7 +2873,7 @@ msgstr "" "executar uma operação levantam uma exceção quando nenhum método apropriado é " "definido (tipicamente :exc:`AttributeError` ou :exc:`TypeError`)." -#: ../../reference/datamodel.rst:1577 +#: ../../reference/datamodel.rst:1841 msgid "" "Setting a special method to ``None`` indicates that the corresponding " "operation is not available. For example, if a class sets :meth:`~object." @@ -2481,7 +2887,7 @@ msgstr "" "func:`iter` em suas instâncias irá levantar um :exc:`TypeError` (sem " "retroceder para :meth:`~object.__getitem__`). [#]_" -#: ../../reference/datamodel.rst:1583 +#: ../../reference/datamodel.rst:1847 msgid "" "When implementing a class that emulates any built-in type, it is important " "that the emulation only be implemented to the degree that it makes sense for " @@ -2497,11 +2903,11 @@ msgstr "" "fatia pode não fazer sentido. (Um exemplo disso é a interface :class:`~xml." "dom.NodeList` no Document Object Model do W3C.)" -#: ../../reference/datamodel.rst:1594 +#: ../../reference/datamodel.rst:1858 msgid "Basic customization" msgstr "Personalização básica" -#: ../../reference/datamodel.rst:1600 +#: ../../reference/datamodel.rst:1864 msgid "" "Called to create a new instance of class *cls*. :meth:`__new__` is a static " "method (special-cased so you need not declare it as such) that takes the " @@ -2518,7 +2924,7 @@ msgstr "" "retorno de :meth:`__new__` deve ser a nova instância do objeto (geralmente " "uma instância de *cls*)." -#: ../../reference/datamodel.rst:1607 +#: ../../reference/datamodel.rst:1871 msgid "" "Typical implementations create a new instance of the class by invoking the " "superclass's :meth:`__new__` method using ``super().__new__(cls[, ...])`` " @@ -2530,7 +2936,7 @@ msgstr "" "com os argumentos apropriados e, em seguida, modificando a instância recém-" "criada conforme necessário antes de retorná-la." -#: ../../reference/datamodel.rst:1612 +#: ../../reference/datamodel.rst:1876 msgid "" "If :meth:`__new__` is invoked during object construction and it returns an " "instance of *cls*, then the new instance’s :meth:`__init__` method will be " @@ -2544,7 +2950,7 @@ msgstr "" "argumentos restantes são os mesmos que foram passados para o construtor do " "objeto." -#: ../../reference/datamodel.rst:1617 +#: ../../reference/datamodel.rst:1881 msgid "" "If :meth:`__new__` does not return an instance of *cls*, then the new " "instance's :meth:`__init__` method will not be invoked." @@ -2552,7 +2958,7 @@ msgstr "" "Se :meth:`__new__` não retornar uma instância de *cls*, então o método :meth:" "`__init__` da nova instância não será invocado." -#: ../../reference/datamodel.rst:1620 +#: ../../reference/datamodel.rst:1884 msgid "" ":meth:`__new__` is intended mainly to allow subclasses of immutable types " "(like int, str, or tuple) to customize instance creation. It is also " @@ -2564,7 +2970,7 @@ msgstr "" "Também é comumente substituído em metaclasses personalizadas para " "personalizar a criação de classes." -#: ../../reference/datamodel.rst:1629 +#: ../../reference/datamodel.rst:1893 msgid "" "Called after the instance has been created (by :meth:`__new__`), but before " "it is returned to the caller. The arguments are those passed to the class " @@ -2580,7 +2986,7 @@ msgstr "" "chamá-lo explicitamente para garantir a inicialização apropriada da parte da " "classe base da instância; por exemplo: ``super().__init__([args...])``." -#: ../../reference/datamodel.rst:1636 +#: ../../reference/datamodel.rst:1900 msgid "" "Because :meth:`__new__` and :meth:`__init__` work together in constructing " "objects (:meth:`__new__` to create it, and :meth:`__init__` to customize " @@ -2593,7 +2999,7 @@ msgstr "" "`__init__`; fazer isso fará com que uma :exc:`TypeError` seja levantada em " "tempo de execução." -#: ../../reference/datamodel.rst:1649 +#: ../../reference/datamodel.rst:1913 msgid "" "Called when the instance is about to be destroyed. This is also called a " "finalizer or (improperly) a destructor. If a base class has a :meth:" @@ -2607,7 +3013,7 @@ msgstr "" "houver, deve chamá-lo explicitamente para garantir a exclusão adequada da " "parte da classe base da instância." -#: ../../reference/datamodel.rst:1655 +#: ../../reference/datamodel.rst:1919 msgid "" "It is possible (though not recommended!) for the :meth:`__del__` method to " "postpone destruction of the instance by creating a new reference to it. " @@ -2622,7 +3028,7 @@ msgstr "" "chamado uma segunda vez quando um objeto ressuscitado está prestes a ser " "destruído; a implementação atual do :term:`CPython` chama-o apenas uma vez." -#: ../../reference/datamodel.rst:1662 +#: ../../reference/datamodel.rst:1926 msgid "" "It is not guaranteed that :meth:`__del__` methods are called for objects " "that still exist when the interpreter exits. :class:`weakref.finalize` " @@ -2634,7 +3040,7 @@ msgstr "" "finalize` fornece uma maneira direta de registrar uma função de limpeza a " "ser chamada quando um objeto é coletado como lixo." -#: ../../reference/datamodel.rst:1669 +#: ../../reference/datamodel.rst:1933 msgid "" "``del x`` doesn't directly call ``x.__del__()`` --- the former decrements " "the reference count for ``x`` by one, and the latter is only called when " @@ -2644,7 +3050,7 @@ msgstr "" "contagem de referências para ``x`` em um, e o segundo só é chamado quando a " "contagem de referências de ``x`` atinge zero." -#: ../../reference/datamodel.rst:1674 +#: ../../reference/datamodel.rst:1938 msgid "" "It is possible for a reference cycle to prevent the reference count of an " "object from going to zero. In this case, the cycle will be later detected " @@ -2662,11 +3068,11 @@ msgstr "" "referencia seu próprio traceback, que referencia o locals de todos os " "quadros capturados no traceback." -#: ../../reference/datamodel.rst:1684 +#: ../../reference/datamodel.rst:1948 msgid "Documentation for the :mod:`gc` module." msgstr "Documentação do módulo :mod:`gc`." -#: ../../reference/datamodel.rst:1688 +#: ../../reference/datamodel.rst:1952 msgid "" "Due to the precarious circumstances under which :meth:`__del__` methods are " "invoked, exceptions that occur during their execution are ignored, and a " @@ -2676,7 +3082,7 @@ msgstr "" "são invocados, as exceções que ocorrem durante sua execução são ignoradas e " "um aviso é impresso em ``sys.stderr`` em seu lugar. Em particular:" -#: ../../reference/datamodel.rst:1692 +#: ../../reference/datamodel.rst:1956 msgid "" ":meth:`__del__` can be invoked when arbitrary code is being executed, " "including from any arbitrary thread. If :meth:`__del__` needs to take a " @@ -2690,7 +3096,7 @@ msgstr "" "um impasse, pois o recurso já pode ter sido levado pelo código que é " "interrompido para executar :meth:`__del__`." -#: ../../reference/datamodel.rst:1698 +#: ../../reference/datamodel.rst:1962 msgid "" ":meth:`__del__` can be executed during interpreter shutdown. As a " "consequence, the global variables it needs to access (including other " @@ -2709,7 +3115,7 @@ msgstr "" "módulos importados ainda estejam disponíveis no momento em que o método :" "meth:`__del__` for chamado." -#: ../../reference/datamodel.rst:1713 +#: ../../reference/datamodel.rst:1977 msgid "" "Called by the :func:`repr` built-in function to compute the \"official\" " "string representation of an object. If at all possible, this should look " @@ -2730,27 +3136,29 @@ msgstr "" "quando uma representação de string \"informal\" de instâncias daquela classe " "é necessária." -#: ../../reference/datamodel.rst:1722 +#: ../../reference/datamodel.rst:1986 msgid "" "This is typically used for debugging, so it is important that the " -"representation is information-rich and unambiguous." +"representation is information-rich and unambiguous. A default implementation " +"is provided by the :class:`object` class itself." msgstr "" "Isso é normalmente usado para depuração, portanto, é importante que a " -"representação seja rica em informações e inequívoca." +"representação seja rica em informações e inequívoca. Uma implementação " +"padrão é fornecida pela própria classe :class:`object`." -#: ../../reference/datamodel.rst:1733 +#: ../../reference/datamodel.rst:1998 msgid "" -"Called by :func:`str(object) ` and the built-in functions :func:" -"`format` and :func:`print` to compute the \"informal\" or nicely printable " -"string representation of an object. The return value must be a :ref:`string " -"` object." +"Called by :func:`str(object) `, the default :meth:`__format__` " +"implementation, and the built-in function :func:`print`, to compute the " +"\"informal\" or nicely printable string representation of an object. The " +"return value must be a :ref:`str ` object." msgstr "" -"Chamado por :func:`str(object) ` e as funções embutidas :func:`format` " -"e :func:`print` para calcular a representação da string \"informal\" ou " -"agradável para exibição de um objeto. O valor de retorno deve ser um objeto :" -"ref:`string `." +"Chamado por :func:`str(object) `, a implementação padrão de :meth:" +"`__format__`, e as funções embutidas :func:`print`, para calcular a " +"representação da string \"informal\" ou agradável para exibição de um " +"objeto. O valor de retorno deve ser um objeto :ref:`str `." -#: ../../reference/datamodel.rst:1738 +#: ../../reference/datamodel.rst:2003 msgid "" "This method differs from :meth:`object.__repr__` in that there is no " "expectation that :meth:`__str__` return a valid Python expression: a more " @@ -2760,7 +3168,7 @@ msgstr "" "que :meth:`__str__` retorne uma expressão Python válida: uma representação " "mais conveniente ou concisa pode ser usada." -#: ../../reference/datamodel.rst:1742 +#: ../../reference/datamodel.rst:2007 msgid "" "The default implementation defined by the built-in type :class:`object` " "calls :meth:`object.__repr__`." @@ -2768,15 +3176,17 @@ msgstr "" "A implementação padrão definida pelo tipo embutido :class:`object` chama :" "meth:`object.__repr__`." -#: ../../reference/datamodel.rst:1752 +#: ../../reference/datamodel.rst:2017 msgid "" "Called by :ref:`bytes ` to compute a byte-string representation " -"of an object. This should return a :class:`bytes` object." +"of an object. This should return a :class:`bytes` object. The :class:" +"`object` class itself does not provide this method." msgstr "" "Chamado por :ref:`bytes ` para calcular uma representação de " -"string de bytes de um objeto. Isso deve retornar um objeto :class:`bytes`." +"string de bytes de um objeto. Isso deve retornar um objeto :class:`bytes`. A " +"classe :class:`object` em si não fornece este método." -#: ../../reference/datamodel.rst:1763 +#: ../../reference/datamodel.rst:2029 msgid "" "Called by the :func:`format` built-in function, and by extension, evaluation " "of :ref:`formatted string literals ` and the :meth:`str.format` " @@ -2796,18 +3206,26 @@ msgstr "" "classes delegará a formatação a um dos tipos embutidos ou usará uma sintaxe " "de opção de formatação semelhante." -#: ../../reference/datamodel.rst:1773 +#: ../../reference/datamodel.rst:2039 msgid "" "See :ref:`formatspec` for a description of the standard formatting syntax." msgstr "" "Consulte :ref:`formatspec` para uma descrição da sintaxe de formatação " "padrão." -#: ../../reference/datamodel.rst:1775 +#: ../../reference/datamodel.rst:2041 msgid "The return value must be a string object." msgstr "O valor de retorno deve ser um objeto string." -#: ../../reference/datamodel.rst:1777 +#: ../../reference/datamodel.rst:2043 +msgid "" +"The default implementation by the :class:`object` class should be given an " +"empty *format_spec* string. It delegates to :meth:`__str__`." +msgstr "" +"A implementação padrão pela classe :class:`object` deve receber uma string " +"*format_spec* vazia. Ela delega para :meth:`__str__`." + +#: ../../reference/datamodel.rst:2046 msgid "" "The __format__ method of ``object`` itself raises a :exc:`TypeError` if " "passed any non-empty string." @@ -2815,7 +3233,7 @@ msgstr "" "O método __format__ do próprio ``object`` levanta uma :exc:`TypeError` se " "passada qualquer string não vazia." -#: ../../reference/datamodel.rst:1781 +#: ../../reference/datamodel.rst:2050 msgid "" "``object.__format__(x, '')`` is now equivalent to ``str(x)`` rather than " "``format(str(x), '')``." @@ -2823,7 +3241,7 @@ msgstr "" "``object.__format__(x, '')`` é agora equivalente a ``str(x)`` em vez de " "``format(str(x), '')``." -#: ../../reference/datamodel.rst:1797 +#: ../../reference/datamodel.rst:2066 msgid "" "These are the so-called \"rich comparison\" methods. The correspondence " "between operator symbols and method names is as follows: ``xy`` chama ``x.__gt__(y)`` e " "``x>=y`` chama ``x.__ge__(y)``." -#: ../../reference/datamodel.rst:1803 +#: ../../reference/datamodel.rst:2072 msgid "" "A rich comparison method may return the singleton :data:`NotImplemented` if " "it does not implement the operation for a given pair of arguments. By " @@ -2856,7 +3274,7 @@ msgstr "" "chamar :func:`bool` no valor para determinar se o resultado for verdadeiro " "ou falso." -#: ../../reference/datamodel.rst:1810 +#: ../../reference/datamodel.rst:2079 msgid "" "By default, ``object`` implements :meth:`__eq__` by using ``is``, returning :" "data:`NotImplemented` in the case of a false comparison: ``True if x is y " @@ -2876,7 +3294,21 @@ msgstr "" "não implica ``x<=y``. Para gerar operações de ordenação automaticamente a " "partir de uma única operação raiz, consulte :func:`functools.total_ordering`." -#: ../../reference/datamodel.rst:1819 +#: ../../reference/datamodel.rst:2088 +msgid "" +"By default, the :class:`object` class provides implementations consistent " +"with :ref:`expressions-value-comparisons`: equality compares according to " +"object identity, and order comparisons raise :exc:`TypeError`. Each default " +"method may generate these results directly, but may also return :data:" +"`NotImplemented`." +msgstr "" +"Por padrão, a classe :class:`object` fornece implementações consistentes " +"com :ref:`expressions-value-comparisons`: igualdade compara de acordo com a " +"identidade do objeto, e comparações de ordem levantam :exc:`TypeError`. Cada " +"método padrão pode gerar esses resultados diretamente, mas também pode " +"retornar :data:`NotImplemented`." + +#: ../../reference/datamodel.rst:2094 msgid "" "See the paragraph on :meth:`__hash__` for some important notes on creating :" "term:`hashable` objects which support custom comparison operations and are " @@ -2886,7 +3318,7 @@ msgstr "" "a criação de objetos :term:`hasheáveis ` que implementam operações " "de comparação personalizadas e são utilizáveis como chaves de dicionário." -#: ../../reference/datamodel.rst:1823 +#: ../../reference/datamodel.rst:2098 msgid "" "There are no swapped-argument versions of these methods (to be used when the " "left argument does not support the operation but the right argument does); " @@ -2908,7 +3340,7 @@ msgstr "" "direito tem prioridade, caso contrário, o método do operando esquerdo tem " "prioridade. Subclasse virtual não é considerada." -#: ../../reference/datamodel.rst:1834 +#: ../../reference/datamodel.rst:2109 msgid "" "When no appropriate method returns any value other than :data:" "`NotImplemented`, the ``==`` and ``!=`` operators will fall back to ``is`` " @@ -2918,7 +3350,7 @@ msgstr "" "`NotImplemented`, os operadores ``==`` e ``!=`` retornarão para ``is`` e " "``is not``, respectivamente." -#: ../../reference/datamodel.rst:1843 +#: ../../reference/datamodel.rst:2118 msgid "" "Called by built-in function :func:`hash` and for operations on members of " "hashed collections including :class:`set`, :class:`frozenset`, and :class:" @@ -2936,7 +3368,15 @@ msgstr "" "do objeto que também desempenham um papel na comparação dos objetos, " "empacotando-os em uma tupla e fazendo o hash da tupla. Exemplo::" -#: ../../reference/datamodel.rst:1856 +#: ../../reference/datamodel.rst:2126 +msgid "" +"def __hash__(self):\n" +" return hash((self.name, self.nick, self.color))" +msgstr "" +"def __hash__(self):\n" +" return hash((self.name, self.nick, self.color))" + +#: ../../reference/datamodel.rst:2131 msgid "" ":func:`hash` truncates the value returned from an object's custom :meth:" "`__hash__` method to the size of a :c:type:`Py_ssize_t`. This is typically " @@ -2953,7 +3393,7 @@ msgstr "" "as compilações com suporte. Uma maneira fácil de fazer isso é com ``python -" "c \"import sys; print(sys.hash_info.width)\"``." -#: ../../reference/datamodel.rst:1864 +#: ../../reference/datamodel.rst:2139 msgid "" "If a class does not define an :meth:`__eq__` method it should not define a :" "meth:`__hash__` operation either; if it defines :meth:`__eq__` but not :meth:" @@ -2973,19 +3413,21 @@ msgstr "" "valor hash de uma chave seja imutável (se o valor hash do objeto mudar, " "estará no balde de hash errado)." -#: ../../reference/datamodel.rst:1873 +#: ../../reference/datamodel.rst:2148 msgid "" "User-defined classes have :meth:`__eq__` and :meth:`__hash__` methods by " -"default; with them, all objects compare unequal (except with themselves) and " -"``x.__hash__()`` returns an appropriate value such that ``x == y`` implies " -"both that ``x is y`` and ``hash(x) == hash(y)``." +"default (inherited from the :class:`object` class); with them, all objects " +"compare unequal (except with themselves) and ``x.__hash__()`` returns an " +"appropriate value such that ``x == y`` implies both that ``x is y`` and " +"``hash(x) == hash(y)``." msgstr "" "As classes definidas pelo usuário têm os métodos :meth:`__eq__` e :meth:" -"`__hash__` por padrão; com eles, todos os objetos se comparam desiguais " -"(exceto com eles mesmos) e ``x.__hash__()`` retorna um valor apropriado tal " -"que ``x == y`` implica que ``x is y`` e ``hash(x) == hash(y)``." +"`__hash__` por padrão (herdados da classe :class:`object`); com eles, todos " +"os objetos se comparam desiguais (exceto com eles mesmos) e ``x.__hash__()`` " +"retorna um valor apropriado tal que ``x == y`` implica que ``x is y`` e " +"``hash(x) == hash(y)``." -#: ../../reference/datamodel.rst:1878 +#: ../../reference/datamodel.rst:2153 msgid "" "A class that overrides :meth:`__eq__` and does not define :meth:`__hash__` " "will have its :meth:`__hash__` implicitly set to ``None``. When the :meth:" @@ -3001,17 +3443,17 @@ msgstr "" "hash, e também será identificado corretamente como não-hasheável ao " "verificar ``isinstance(obj, collections.abc.Hashable)``." -#: ../../reference/datamodel.rst:1885 +#: ../../reference/datamodel.rst:2160 msgid "" "If a class that overrides :meth:`__eq__` needs to retain the implementation " "of :meth:`__hash__` from a parent class, the interpreter must be told this " "explicitly by setting ``__hash__ = .__hash__``." msgstr "" -"Se uma classe que sobrescreve :meth:`__eq__` precisa manter a implementação " -"de :meth:`__hash__` de uma classe pai, o interpretador deve ser informado " -"disso explicitamente pela configuração ``__hash__ = .__hash__``." +"Se uma classe que substitui :meth:`__eq__` precisa manter a implementação " +"de :meth:`__hash__` de uma classe base, o interpretador deve ser informado " +"disso explicitamente pela configuração ``__hash__ = .__hash__``." -#: ../../reference/datamodel.rst:1889 +#: ../../reference/datamodel.rst:2164 msgid "" "If a class that does not override :meth:`__eq__` wishes to suppress hash " "support, it should include ``__hash__ = None`` in the class definition. A " @@ -3025,7 +3467,7 @@ msgstr "" "`TypeError` seria incorretamente identificada como hasheável por uma chamada " "``isinstance(obj, collections.abc.Hashable)``." -#: ../../reference/datamodel.rst:1898 +#: ../../reference/datamodel.rst:2173 msgid "" "By default, the :meth:`__hash__` values of str and bytes objects are " "\"salted\" with an unpredictable random value. Although they remain " @@ -3037,7 +3479,7 @@ msgstr "" "constantes em um processo individual do Python, eles não são previsíveis " "entre invocações repetidas do Python." -#: ../../reference/datamodel.rst:1903 +#: ../../reference/datamodel.rst:2178 msgid "" "This is intended to provide protection against a denial-of-service caused by " "carefully chosen inputs that exploit the worst case performance of a dict " @@ -3050,7 +3492,7 @@ msgstr "" "`2`). Consulte http://ocert.org/advisories/ocert-2011-003.html para obter " "detalhes." -#: ../../reference/datamodel.rst:1908 +#: ../../reference/datamodel.rst:2183 msgid "" "Changing hash values affects the iteration order of sets. Python has never " "made guarantees about this ordering (and it typically varies between 32-bit " @@ -3060,34 +3502,36 @@ msgstr "" "nunca deu garantias sobre essa ordem (e normalmente varia entre compilações " "de 32 e 64 bits)." -#: ../../reference/datamodel.rst:1912 +#: ../../reference/datamodel.rst:2187 msgid "See also :envvar:`PYTHONHASHSEED`." msgstr "Consulte também :envvar:`PYTHONHASHSEED`." -#: ../../reference/datamodel.rst:1914 +#: ../../reference/datamodel.rst:2189 msgid "Hash randomization is enabled by default." msgstr "Aleatorização de hash está habilitada por padrão." -#: ../../reference/datamodel.rst:1922 +#: ../../reference/datamodel.rst:2197 msgid "" "Called to implement truth value testing and the built-in operation " "``bool()``; should return ``False`` or ``True``. When this method is not " "defined, :meth:`~object.__len__` is called, if it is defined, and the object " "is considered true if its result is nonzero. If a class defines neither :" -"meth:`!__len__` nor :meth:`!__bool__`, all its instances are considered true." +"meth:`!__len__` nor :meth:`!__bool__` (which is true of the :class:`object` " +"class itself), all its instances are considered true." msgstr "" "Chamado para implementar o teste de valor verdade e a operação embutida " "``bool()``; deve retornar ``False`` ou ``True``. Quando este método não é " "definido, :meth:`~object.__len__` é chamado, se estiver definido, e o objeto " "é considerado verdadeiro se seu resultado for diferente de zero. Se uma " -"classe não define :meth:`!__len__` nem :meth:`!__bool__`, todas as suas " -"instâncias são consideradas verdadeiras." +"classe não define :meth:`!__len__` nem :meth:`!__bool__` (o que é verdadeiro " +"da classe :class:`object` em si), todas as suas instâncias são consideradas " +"verdadeiras." -#: ../../reference/datamodel.rst:1933 +#: ../../reference/datamodel.rst:2208 msgid "Customizing attribute access" msgstr "Personalizando o acesso aos atributos" -#: ../../reference/datamodel.rst:1935 +#: ../../reference/datamodel.rst:2210 msgid "" "The following methods can be defined to customize the meaning of attribute " "access (use of, assignment to, or deletion of ``x.name``) for class " @@ -3097,23 +3541,25 @@ msgstr "" "acesso aos atributos (uso, atribuição ou exclusão de ``x.name``) para " "instâncias de classe." -#: ../../reference/datamodel.rst:1943 +#: ../../reference/datamodel.rst:2218 msgid "" "Called when the default attribute access fails with an :exc:`AttributeError` " "(either :meth:`__getattribute__` raises an :exc:`AttributeError` because " "*name* is not an instance attribute or an attribute in the class tree for " "``self``; or :meth:`__get__` of a *name* property raises :exc:" "`AttributeError`). This method should either return the (computed) " -"attribute value or raise an :exc:`AttributeError` exception." +"attribute value or raise an :exc:`AttributeError` exception. The :class:" +"`object` class itself does not provide this method." msgstr "" "Chamado quando o acesso padrão ao atributo falha com um :exc:" "`AttributeError` (ou :meth:`__getattribute__` levanta uma :exc:" "`AttributeError` porque *name* não é um atributo de instância ou um atributo " "na árvore de classes para ``self``; ou :meth:`__get__` de uma propriedade " "*name* levanta :exc:`AttributeError`). Este método deve retornar o valor do " -"atributo (calculado) ou levantar uma exceção :exc:`AttributeError`." +"atributo (calculado) ou levantar uma exceção :exc:`AttributeError`. A " +"classe :class:`object` em si não fornece este método." -#: ../../reference/datamodel.rst:1950 +#: ../../reference/datamodel.rst:2226 msgid "" "Note that if the attribute is found through the normal mechanism, :meth:" "`__getattr__` is not called. (This is an intentional asymmetry between :" @@ -3125,8 +3571,17 @@ msgid "" "object). See the :meth:`__getattribute__` method below for a way to " "actually get total control over attribute access." msgstr "" +"Observe que se o atributo for encontrado através do mecanismo normal, :meth:" +"`__getattr__` não é chamado. (Esta é uma assimetria intencional entre :meth:" +"`__getattr__` e :meth:`__setattr__`.) Isso é feito tanto por razões de " +"eficiência quanto porque :meth:`__getattr__` não teria como acessar outros " +"atributos da instância. Observe que pelo menos para variáveis de instâncias, " +"você pode obter controle total não inserindo nenhum valor no dicionário de " +"atributos de instância (mas, em vez disso, inserindo-os em outro objeto). " +"Veja o método :meth:`__getattribute__` abaixo para uma maneira de realmente " +"obter controle total sobre o acesso ao atributo." -#: ../../reference/datamodel.rst:1963 +#: ../../reference/datamodel.rst:2239 msgid "" "Called unconditionally to implement attribute accesses for instances of the " "class. If the class also defines :meth:`__getattr__`, the latter will not be " @@ -3147,7 +3602,7 @@ msgstr "" "para acessar quaisquer atributos de que necessita, por exemplo, ``object." "__getattribute__(self, name)``." -#: ../../reference/datamodel.rst:1974 +#: ../../reference/datamodel.rst:2250 msgid "" "This method may still be bypassed when looking up special methods as the " "result of implicit invocation via language syntax or :ref:`built-in " @@ -3157,7 +3612,7 @@ msgstr "" "resultado de invocação implícita por meio da sintaxe da linguagem ou :ref:" "`built-in functions `. Consulte :ref:`special-lookup`." -#: ../../reference/datamodel.rst:1979 ../../reference/datamodel.rst:1981 +#: ../../reference/datamodel.rst:2255 ../../reference/datamodel.rst:2257 msgid "" "For certain sensitive attribute accesses, raises an :ref:`auditing event " "` ``object.__getattr__`` with arguments ``obj`` and ``name``." @@ -3166,7 +3621,7 @@ msgstr "" "auditoria ` ``object.__getattr__`` com os argumentos ``obj`` e " "``name``." -#: ../../reference/datamodel.rst:1988 +#: ../../reference/datamodel.rst:2264 msgid "" "Called when an attribute assignment is attempted. This is called instead of " "the normal mechanism (i.e. store the value in the instance dictionary). " @@ -3177,7 +3632,7 @@ msgstr "" "da instância). *name* é o nome do atributo, *value* é o valor a ser " "atribuído a ele." -#: ../../reference/datamodel.rst:1992 +#: ../../reference/datamodel.rst:2268 msgid "" "If :meth:`__setattr__` wants to assign to an instance attribute, it should " "call the base class method with the same name, for example, ``object." @@ -3187,7 +3642,7 @@ msgstr "" "chamar o método da classe base com o mesmo nome, por exemplo, ``object." "__setattr__(self, name, value)``." -#: ../../reference/datamodel.rst:1996 ../../reference/datamodel.rst:1998 +#: ../../reference/datamodel.rst:2272 ../../reference/datamodel.rst:2274 msgid "" "For certain sensitive attribute assignments, raises an :ref:`auditing event " "` ``object.__setattr__`` with arguments ``obj``, ``name``, " @@ -3197,7 +3652,7 @@ msgstr "" "auditoria ` ``object.__setattr__`` com os argumentos ``obj``, " "``name`` e ``value``." -#: ../../reference/datamodel.rst:2005 +#: ../../reference/datamodel.rst:2281 msgid "" "Like :meth:`__setattr__` but for attribute deletion instead of assignment. " "This should only be implemented if ``del obj.name`` is meaningful for the " @@ -3207,7 +3662,7 @@ msgstr "" "atribuição. Este método só deve ser implementado se ``del obj.name`` for " "significativo para o objeto." -#: ../../reference/datamodel.rst:2008 ../../reference/datamodel.rst:2010 +#: ../../reference/datamodel.rst:2284 ../../reference/datamodel.rst:2286 msgid "" "For certain sensitive attribute deletions, raises an :ref:`auditing event " "` ``object.__delattr__`` with arguments ``obj`` and ``name``." @@ -3216,17 +3671,20 @@ msgstr "" "auditoria ` ``object.__delattr__`` com os argumentos ``obj`` e " "``name``." -#: ../../reference/datamodel.rst:2017 +#: ../../reference/datamodel.rst:2293 msgid "" "Called when :func:`dir` is called on the object. An iterable must be " "returned. :func:`dir` converts the returned iterable to a list and sorts it." msgstr "" +"Chamado quando :func:`dir` é chamado com o objeto como argumento. Um " +"iterável deve ser retornada. :func:`dir` converte o iterável retornado em " +"uma lista e o ordena." -#: ../../reference/datamodel.rst:2022 +#: ../../reference/datamodel.rst:2298 msgid "Customizing module attribute access" msgstr "Personalizando acesso a atributos de módulos" -#: ../../reference/datamodel.rst:2029 +#: ../../reference/datamodel.rst:2305 msgid "" "Special names ``__getattr__`` and ``__dir__`` can be also used to customize " "access to module attributes. The ``__getattr__`` function at the module " @@ -3247,14 +3705,17 @@ msgstr "" "exc:`AttributeError`. Se encontrado, ele é chamado com o nome do atributo e " "o resultado é retornado." -#: ../../reference/datamodel.rst:2038 +#: ../../reference/datamodel.rst:2314 msgid "" "The ``__dir__`` function should accept no arguments, and return an iterable " "of strings that represents the names accessible on module. If present, this " "function overrides the standard :func:`dir` search on a module." msgstr "" +"A função ``__dir__`` não deve aceitar nenhum argumento e retorna um iterável " +"de strings que representa os nomes acessíveis no módulo. Se presente, esta " +"função substitui a pesquisa padrão :func:`dir` em um módulo." -#: ../../reference/datamodel.rst:2042 +#: ../../reference/datamodel.rst:2318 msgid "" "For a more fine grained customization of the module behavior (setting " "attributes, properties, etc.), one can set the ``__class__`` attribute of a " @@ -3265,7 +3726,35 @@ msgstr "" "de um objeto de módulo para uma subclasse de :class:`types.ModuleType`. Por " "exemplo::" -#: ../../reference/datamodel.rst:2060 +#: ../../reference/datamodel.rst:2322 +msgid "" +"import sys\n" +"from types import ModuleType\n" +"\n" +"class VerboseModule(ModuleType):\n" +" def __repr__(self):\n" +" return f'Verbose {self.__name__}'\n" +"\n" +" def __setattr__(self, attr, value):\n" +" print(f'Setting {attr}...')\n" +" super().__setattr__(attr, value)\n" +"\n" +"sys.modules[__name__].__class__ = VerboseModule" +msgstr "" +"import sys\n" +"from types import ModuleType\n" +"\n" +"class VerboseModule(ModuleType):\n" +" def __repr__(self):\n" +" return f'Verbose {self.__name__}'\n" +"\n" +" def __setattr__(self, attr, value):\n" +" print(f'Setting {attr}...')\n" +" super().__setattr__(attr, value)\n" +"\n" +"sys.modules[__name__].__class__ = VerboseModule" + +#: ../../reference/datamodel.rst:2336 msgid "" "Defining module ``__getattr__`` and setting module ``__class__`` only affect " "lookups made using the attribute access syntax -- directly accessing the " @@ -3277,43 +3766,45 @@ msgstr "" "diretamente os globais do módulo (seja por código dentro do módulo, ou por " "meio de uma referência ao dicionário global do módulo) não tem efeito." -#: ../../reference/datamodel.rst:2065 +#: ../../reference/datamodel.rst:2341 msgid "``__class__`` module attribute is now writable." msgstr "O atributo de módulo ``__class__`` pode agora ser escrito." -#: ../../reference/datamodel.rst:2068 +#: ../../reference/datamodel.rst:2344 msgid "``__getattr__`` and ``__dir__`` module attributes." msgstr "Atributos de módulo ``__getattr__`` e ``__dir__``." -#: ../../reference/datamodel.rst:2073 +#: ../../reference/datamodel.rst:2349 msgid ":pep:`562` - Module __getattr__ and __dir__" msgstr ":pep:`562` - __getattr__ e __dir__ de módulo" -#: ../../reference/datamodel.rst:2074 +#: ../../reference/datamodel.rst:2350 msgid "Describes the ``__getattr__`` and ``__dir__`` functions on modules." msgstr "Descreve as funções ``__getattr__`` e ``__dir__`` nos módulos." -#: ../../reference/datamodel.rst:2080 +#: ../../reference/datamodel.rst:2356 msgid "Implementing Descriptors" msgstr "Implementando descritores" -#: ../../reference/datamodel.rst:2082 +#: ../../reference/datamodel.rst:2358 msgid "" "The following methods only apply when an instance of the class containing " "the method (a so-called *descriptor* class) appears in an *owner* class (the " "descriptor must be in either the owner's class dictionary or in the class " "dictionary for one of its parents). In the examples below, \"the " "attribute\" refers to the attribute whose name is the key of the property in " -"the owner class' :attr:`~object.__dict__`." +"the owner class' :attr:`~object.__dict__`. The :class:`object` class itself " +"does not implement any of these protocols." msgstr "" "Os métodos a seguir se aplicam apenas quando uma instância da classe que " "contém o método (uma classe chamada *descritora*) aparece em uma classe " "proprietária *owner* (o descritor deve estar no dicionário de classe do " "proprietário ou no dicionário de classe para um dos seus pais). Nos exemplos " "abaixo, \"o atributo\" refere-se ao atributo cujo nome é a chave da " -"propriedade no :attr:`~object.__dict__` da classe proprietária." +"propriedade no :attr:`~object.__dict__` da classe proprietária. A classe :" +"class:`object` em si não implementa quaisquer desses protocolos." -#: ../../reference/datamodel.rst:2092 +#: ../../reference/datamodel.rst:2368 msgid "" "Called to get the attribute of the owner class (class attribute access) or " "of an instance of that class (instance attribute access). The optional " @@ -3327,7 +3818,7 @@ msgstr "" "a instância pela qual o atributo foi acessado, ou ``None`` quando o atributo " "é acessado por meio de *owner*." -#: ../../reference/datamodel.rst:2098 +#: ../../reference/datamodel.rst:2374 msgid "" "This method should return the computed attribute value or raise an :exc:" "`AttributeError` exception." @@ -3335,7 +3826,7 @@ msgstr "" "Este método deve retornar o valor do atributo calculado ou levantar uma " "exceção :exc:`AttributeError`." -#: ../../reference/datamodel.rst:2101 +#: ../../reference/datamodel.rst:2377 msgid "" ":PEP:`252` specifies that :meth:`__get__` is callable with one or two " "arguments. Python's own built-in descriptors support this specification; " @@ -3351,7 +3842,7 @@ msgstr "" "meth:`__getattribute__` do próprio Python sempre passa em ambos os " "argumentos sejam eles requeridos ou não." -#: ../../reference/datamodel.rst:2110 +#: ../../reference/datamodel.rst:2386 msgid "" "Called to set the attribute on an instance *instance* of the owner class to " "a new value, *value*." @@ -3359,7 +3850,7 @@ msgstr "" "Chamado para definir o atributo em uma instância *instance* da classe " "proprietária para um novo valor, *value*." -#: ../../reference/datamodel.rst:2113 +#: ../../reference/datamodel.rst:2389 msgid "" "Note, adding :meth:`__set__` or :meth:`__delete__` changes the kind of " "descriptor to a \"data descriptor\". See :ref:`descriptor-invocation` for " @@ -3369,14 +3860,14 @@ msgstr "" "descritor para um \"descritor de dados\". Consulte :ref:`descriptor-" "invocation` para mais detalhes." -#: ../../reference/datamodel.rst:2119 +#: ../../reference/datamodel.rst:2395 msgid "" "Called to delete the attribute on an instance *instance* of the owner class." msgstr "" "Chamado para excluir o atributo em uma instância *instance* da classe " "proprietária." -#: ../../reference/datamodel.rst:2121 +#: ../../reference/datamodel.rst:2397 msgid "" "Instances of descriptors may also have the :attr:`!__objclass__` attribute " "present:" @@ -3384,7 +3875,7 @@ msgstr "" "Instâncias de descritores também podem ter o atributo :attr:`!__objclass__` " "presente:" -#: ../../reference/datamodel.rst:2126 +#: ../../reference/datamodel.rst:2402 msgid "" "The attribute :attr:`!__objclass__` is interpreted by the :mod:`inspect` " "module as specifying the class where this object was defined (setting this " @@ -3402,11 +3893,11 @@ msgstr "" "o primeiro argumento posicional (por exemplo, CPython define este atributo " "para métodos não acoplados que são implementados em C)." -#: ../../reference/datamodel.rst:2137 +#: ../../reference/datamodel.rst:2413 msgid "Invoking Descriptors" msgstr "Invocando descritores" -#: ../../reference/datamodel.rst:2139 +#: ../../reference/datamodel.rst:2415 msgid "" "In general, a descriptor is an object attribute with \"binding behavior\", " "one whose attribute access has been overridden by methods in the descriptor " @@ -3420,7 +3911,7 @@ msgstr "" "`~object.__delete__`. Se qualquer um desses métodos for definido para um " "objeto, é considerado um descritor." -#: ../../reference/datamodel.rst:2145 +#: ../../reference/datamodel.rst:2421 msgid "" "The default behavior for attribute access is to get, set, or delete the " "attribute from an object's dictionary. For instance, ``a.x`` has a lookup " @@ -3433,7 +3924,7 @@ msgstr "" "__dict__['x']``, e continunando pelas classes bases de ``type(a)`` excluindo " "metaclasses." -#: ../../reference/datamodel.rst:2150 +#: ../../reference/datamodel.rst:2426 msgid "" "However, if the looked-up value is an object defining one of the descriptor " "methods, then Python may override the default behavior and invoke the " @@ -3445,7 +3936,7 @@ msgstr "" "do descritor. Onde isso ocorre na cadeia de precedência depende de quais " "métodos descritores foram definidos e como eles foram chamados." -#: ../../reference/datamodel.rst:2155 +#: ../../reference/datamodel.rst:2431 msgid "" "The starting point for descriptor invocation is a binding, ``a.x``. How the " "arguments are assembled depends on ``a``:" @@ -3453,11 +3944,11 @@ msgstr "" "O ponto de partida para a invocação do descritor é uma ligação, ``a.x``. " "Como os argumentos são montados depende de ``a``:" -#: ../../reference/datamodel.rst:2158 +#: ../../reference/datamodel.rst:2434 msgid "Direct Call" msgstr "Chamada direta" -#: ../../reference/datamodel.rst:2159 +#: ../../reference/datamodel.rst:2435 msgid "" "The simplest and least common call is when user code directly invokes a " "descriptor method: ``x.__get__(a)``." @@ -3465,11 +3956,11 @@ msgstr "" "A chamada mais simples e menos comum é quando o código do usuário invoca " "diretamente um método descritor: ``x.__get__(a)``." -#: ../../reference/datamodel.rst:2162 +#: ../../reference/datamodel.rst:2438 msgid "Instance Binding" msgstr "Ligação de instâncias" -#: ../../reference/datamodel.rst:2163 +#: ../../reference/datamodel.rst:2439 msgid "" "If binding to an object instance, ``a.x`` is transformed into the call: " "``type(a).__dict__['x'].__get__(a, type(a))``." @@ -3477,11 +3968,11 @@ msgstr "" "Se estiver ligando a uma instância de objeto, ``a.x`` é transformado na " "chamada: ``type(a).__dict__['x'].__get__(a, type(a))``." -#: ../../reference/datamodel.rst:2166 +#: ../../reference/datamodel.rst:2442 msgid "Class Binding" msgstr "Ligação de classes" -#: ../../reference/datamodel.rst:2167 +#: ../../reference/datamodel.rst:2443 msgid "" "If binding to a class, ``A.x`` is transformed into the call: ``A." "__dict__['x'].__get__(None, A)``." @@ -3489,11 +3980,11 @@ msgstr "" "Se estiver ligando a uma classe, ``A.x`` é transformado na chamada: ``A." "__dict__['x'].__get__(None, A)``." -#: ../../reference/datamodel.rst:2170 +#: ../../reference/datamodel.rst:2446 msgid "Super Binding" msgstr "Ligação de super" -#: ../../reference/datamodel.rst:2171 +#: ../../reference/datamodel.rst:2447 msgid "" "A dotted lookup such as ``super(A, a).x`` searches ``a.__class__.__mro__`` " "for a base class ``B`` following ``A`` and then returns ``B.__dict__['x']." @@ -3504,7 +3995,7 @@ msgstr "" "retorna ``B.__dict__['x'].__get__(a, A)``. Se não for um descritor, ``x`` é " "retornado inalterado." -#: ../../reference/datamodel.rst:2208 +#: ../../reference/datamodel.rst:2484 msgid "" "For instance bindings, the precedence of descriptor invocation depends on " "which descriptor methods are defined. A descriptor can define any " @@ -3535,7 +4026,7 @@ msgstr "" "substituem uma redefinição em um dicionário de instância. Em contraste, " "descritores sem dados podem ser substituídos por instâncias." -#: ../../reference/datamodel.rst:2223 +#: ../../reference/datamodel.rst:2499 msgid "" "Python methods (including those decorated with :func:`@staticmethod " "` and :func:`@classmethod `) are implemented as " @@ -3549,7 +4040,7 @@ msgstr "" "substituir métodos. Isso permite que instâncias individuais adquiram " "comportamentos que diferem de outras instâncias da mesma classe." -#: ../../reference/datamodel.rst:2229 +#: ../../reference/datamodel.rst:2505 msgid "" "The :func:`property` function is implemented as a data descriptor. " "Accordingly, instances cannot override the behavior of a property." @@ -3558,11 +4049,11 @@ msgstr "" "mesma forma, as instâncias não podem substituir o comportamento de uma " "propriedade." -#: ../../reference/datamodel.rst:2236 +#: ../../reference/datamodel.rst:2512 msgid "__slots__" msgstr "__slots__" -#: ../../reference/datamodel.rst:2238 +#: ../../reference/datamodel.rst:2514 msgid "" "*__slots__* allow us to explicitly declare data members (like properties) " "and deny the creation of :attr:`~object.__dict__` and *__weakref__* (unless " @@ -3573,7 +4064,7 @@ msgstr "" "(a menos que explicitamente declarado em *__slots__* ou disponível em uma " "classe base.)" -#: ../../reference/datamodel.rst:2242 +#: ../../reference/datamodel.rst:2518 msgid "" "The space saved over using :attr:`~object.__dict__` can be significant. " "Attribute lookup speed can be significantly improved as well." @@ -3582,7 +4073,7 @@ msgstr "" "significativo. A velocidade de pesquisa de atributos também pode ser " "significativamente melhorada." -#: ../../reference/datamodel.rst:2247 +#: ../../reference/datamodel.rst:2523 msgid "" "This class variable can be assigned a string, iterable, or sequence of " "strings with variable names used by instances. *__slots__* reserves space " @@ -3594,11 +4085,11 @@ msgstr "" "*__slots__* reserva espaço para as variáveis declaradas e evita a criação " "automática de :attr:`~object.__dict__` e *__weakref__* para cada instância." -#: ../../reference/datamodel.rst:2256 +#: ../../reference/datamodel.rst:2532 msgid "Notes on using *__slots__*:" msgstr "Observações ao uso de *__slots__*:" -#: ../../reference/datamodel.rst:2258 +#: ../../reference/datamodel.rst:2534 msgid "" "When inheriting from a class without *__slots__*, the :attr:`~object." "__dict__` and *__weakref__* attribute of the instances will always be " @@ -3607,7 +4098,7 @@ msgstr "" "Ao herdar de uma classe sem *__slots__*, os atributos :attr:`~object." "__dict__` e *__weakref__* das instâncias sempre estarão acessíveis." -#: ../../reference/datamodel.rst:2262 +#: ../../reference/datamodel.rst:2538 msgid "" "Without a :attr:`~object.__dict__` variable, instances cannot be assigned " "new variables not listed in the *__slots__* definition. Attempts to assign " @@ -3622,7 +4113,7 @@ msgstr "" "então adicione ``'__dict__'`` à sequência de strings na declaração de " "*__slots__*." -#: ../../reference/datamodel.rst:2269 +#: ../../reference/datamodel.rst:2545 msgid "" "Without a *__weakref__* variable for each instance, classes defining " "*__slots__* do not support :mod:`weak references ` to its " @@ -3634,7 +4125,7 @@ msgstr "" "instâncias. Se for necessário um suporte de referência fraca, adicione " "``'__weakref__'`` à sequência de strings na declaração *__slots__*." -#: ../../reference/datamodel.rst:2275 +#: ../../reference/datamodel.rst:2551 msgid "" "*__slots__* are implemented at the class level by creating :ref:`descriptors " "` for each variable name. As a result, class attributes cannot " @@ -3647,21 +4138,21 @@ msgstr "" "instância definidas por *__slots__*; caso contrário, o atributo de classe " "substituiria a atribuição do descritor." -#: ../../reference/datamodel.rst:2281 +#: ../../reference/datamodel.rst:2557 msgid "" "The action of a *__slots__* declaration is not limited to the class where it " "is defined. *__slots__* declared in parents are available in child classes. " -"However, child subclasses will get a :attr:`~object.__dict__` and " -"*__weakref__* unless they also define *__slots__* (which should only contain " -"names of any *additional* slots)." +"However, instances of a child subclass will get a :attr:`~object.__dict__` " +"and *__weakref__* unless the subclass also defines *__slots__* (which should " +"only contain names of any *additional* slots)." msgstr "" "A ação de uma declaração *__slots__* se limita à classe em que é definida. " "*__slots__* declarados em uma classe base estão disponíveis nas subclasses. " -"No entanto, as subclasses receberão um :attr:`~object.__dict__` e " -"*__weakref__* a menos que também definam *__slots__* (que deve conter apenas " -"nomes de quaisquer slots *adicionais*)." +"No entanto, instâncias de uma subclasse filha vai receber um :attr:`~object." +"__dict__` e *__weakref__* a menos que a subclasse também defina *__slots__* " +"(que deve conter apenas nomes de quaisquer slots *adicionais*)." -#: ../../reference/datamodel.rst:2287 +#: ../../reference/datamodel.rst:2563 msgid "" "If a class defines a slot also defined in a base class, the instance " "variable defined by the base class slot is inaccessible (except by " @@ -3675,7 +4166,7 @@ msgstr "" "significado do programa indefinido. No futuro, uma verificação pode ser " "adicionada para evitar isso." -#: ../../reference/datamodel.rst:2292 +#: ../../reference/datamodel.rst:2568 msgid "" ":exc:`TypeError` will be raised if nonempty *__slots__* are defined for a " "class derived from a :c:member:`\"variable-length\" built-in type " @@ -3687,11 +4178,11 @@ msgstr "" "` como :class:`int`, :class:`bytes` e :class:" "`tuple`." -#: ../../reference/datamodel.rst:2297 +#: ../../reference/datamodel.rst:2573 msgid "Any non-string :term:`iterable` may be assigned to *__slots__*." msgstr "Qualquer :term:`iterável` não string pode ser atribuído a *__slots__*." -#: ../../reference/datamodel.rst:2299 +#: ../../reference/datamodel.rst:2575 msgid "" "If a :class:`dictionary ` is used to assign *__slots__*, the " "dictionary keys will be used as the slot names. The values of the dictionary " @@ -3704,15 +4195,15 @@ msgstr "" "(docstrings) por atributo que serão reconhecidos por :func:`inspect.getdoc` " "e exibidos na saída de :func:`help`." -#: ../../reference/datamodel.rst:2304 +#: ../../reference/datamodel.rst:2580 msgid "" -":attr:`~instance.__class__` assignment works only if both classes have the " +":attr:`~object.__class__` assignment works only if both classes have the " "same *__slots__*." msgstr "" -"Atribuição de :attr:`~instance.__class__` funciona apenas se ambas as " -"classes têm o mesmo *__slots__*." +"Atribuição de :attr:`~object.__class__` funciona apenas se ambas as classes " +"têm o mesmo *__slots__*." -#: ../../reference/datamodel.rst:2307 +#: ../../reference/datamodel.rst:2583 msgid "" ":ref:`Multiple inheritance ` with multiple slotted parent " "classes can be used, but only one parent is allowed to have attributes " @@ -3724,7 +4215,7 @@ msgstr "" "criados por slots (as outras classes bases devem ter layouts de slots " "vazios) -- violações levantam :exc:`TypeError`." -#: ../../reference/datamodel.rst:2313 +#: ../../reference/datamodel.rst:2589 msgid "" "If an :term:`iterator` is used for *__slots__* then a :term:`descriptor` is " "created for each of the iterator's values. However, the *__slots__* " @@ -3734,11 +4225,11 @@ msgstr "" "criado para cada um dos valores do iterador. No entanto, o atributo " "*__slots__* será um iterador vazio." -#: ../../reference/datamodel.rst:2321 +#: ../../reference/datamodel.rst:2597 msgid "Customizing class creation" msgstr "Personalizando a criação de classe" -#: ../../reference/datamodel.rst:2323 +#: ../../reference/datamodel.rst:2599 msgid "" "Whenever a class inherits from another class, :meth:`~object." "__init_subclass__` is called on the parent class. This way, it is possible " @@ -3755,7 +4246,7 @@ msgstr "" "``__init_subclass__`` aplica-se apenas a futuras subclasses da classe que " "define o método." -#: ../../reference/datamodel.rst:2332 +#: ../../reference/datamodel.rst:2608 msgid "" "This method is called whenever the containing class is subclassed. *cls* is " "then the new subclass. If defined as a normal instance method, this method " @@ -3765,15 +4256,37 @@ msgstr "" "é então a nova subclasse. Se definido como um método de instância normal, " "esse método é convertido implicitamente em um método de classe." -#: ../../reference/datamodel.rst:2336 +#: ../../reference/datamodel.rst:2612 msgid "" "Keyword arguments which are given to a new class are passed to the parent " "class's ``__init_subclass__``. For compatibility with other classes using " "``__init_subclass__``, one should take out the needed keyword arguments and " "pass the others over to the base class, as in::" msgstr "" +"Argumentos nomeados dados a uma nova classe são passados para " +"``__init_subclass__`` da classe base. Para compatibilidade com outras " +"classes usando ``__init_subclass__``, deve-se retirar os argumentos nomeados " +"necessários e passar os outros para a classe base, como em::" -#: ../../reference/datamodel.rst:2350 +#: ../../reference/datamodel.rst:2618 +msgid "" +"class Philosopher:\n" +" def __init_subclass__(cls, /, default_name, **kwargs):\n" +" super().__init_subclass__(**kwargs)\n" +" cls.default_name = default_name\n" +"\n" +"class AustralianPhilosopher(Philosopher, default_name=\"Bruce\"):\n" +" pass" +msgstr "" +"class Philosopher:\n" +" def __init_subclass__(cls, /, default_name, **kwargs):\n" +" super().__init_subclass__(**kwargs)\n" +" cls.default_name = default_name\n" +"\n" +"class AustralianPhilosopher(Philosopher, default_name=\"Bruce\"):\n" +" pass" + +#: ../../reference/datamodel.rst:2626 msgid "" "The default implementation ``object.__init_subclass__`` does nothing, but " "raises an error if it is called with any arguments." @@ -3781,7 +4294,7 @@ msgstr "" "A implementação padrão de ``object.__init_subclass__`` não faz nada, mas " "levanta um erro se for chamada com quaisquer argumentos." -#: ../../reference/datamodel.rst:2355 +#: ../../reference/datamodel.rst:2631 msgid "" "The metaclass hint ``metaclass`` is consumed by the rest of the type " "machinery, and is never passed to ``__init_subclass__`` implementations. The " @@ -3793,7 +4306,7 @@ msgstr "" "metaclasse real (em vez da dica explícita) pode ser acessada como " "``type(cls)``." -#: ../../reference/datamodel.rst:2363 +#: ../../reference/datamodel.rst:2639 msgid "" "When a class is created, :meth:`type.__new__` scans the class variables and " "makes callbacks to those with a :meth:`~object.__set_name__` hook." @@ -3802,7 +4315,7 @@ msgstr "" "classe e faz chamadas a funções de retorno (callback) para aqueles com um " "gancho :meth:`~object.__set_name__`." -#: ../../reference/datamodel.rst:2368 +#: ../../reference/datamodel.rst:2644 msgid "" "Automatically called at the time the owning class *owner* is created. The " "object has been assigned to *name* in that class::" @@ -3810,7 +4323,15 @@ msgstr "" "Chamado automaticamente no momento em que a classe proprietária *owner* é " "criada. O objeto foi atribuído a *name* nessa classe::" -#: ../../reference/datamodel.rst:2374 +#: ../../reference/datamodel.rst:2647 +msgid "" +"class A:\n" +" x = C() # Automatically calls: x.__set_name__(A, 'x')" +msgstr "" +"class A:\n" +" x = C() # Automaticamente chama: x.__set_name__(A, 'x')" + +#: ../../reference/datamodel.rst:2650 msgid "" "If the class variable is assigned after the class is created, :meth:" "`__set_name__` will not be called automatically. If needed, :meth:" @@ -3820,15 +4341,31 @@ msgstr "" "`__set_name__` não será chamado automaticamente. Se necessário, :meth:" "`__set_name__` pode ser chamado diretamente::" -#: ../../reference/datamodel.rst:2385 +#: ../../reference/datamodel.rst:2654 +msgid "" +"class A:\n" +" pass\n" +"\n" +"c = C()\n" +"A.x = c # The hook is not called\n" +"c.__set_name__(A, 'x') # Manually invoke the hook" +msgstr "" +"class A:\n" +" pass\n" +"\n" +"c = C()\n" +"A.x = c # O gancho não é chamado\n" +"c.__set_name__(A, 'x') # Invoca manualmente o gancho" + +#: ../../reference/datamodel.rst:2661 msgid "See :ref:`class-object-creation` for more details." msgstr "Consulte :ref:`class-object-creation` para mais detalhes." -#: ../../reference/datamodel.rst:2393 +#: ../../reference/datamodel.rst:2669 msgid "Metaclasses" msgstr "Metaclasses" -#: ../../reference/datamodel.rst:2400 +#: ../../reference/datamodel.rst:2676 msgid "" "By default, classes are constructed using :func:`type`. The class body is " "executed in a new namespace and the class name is bound locally to the " @@ -3838,7 +4375,7 @@ msgstr "" "classe é executado em um novo espaço de nomes e o nome da classe é vinculado " "localmente ao resultado de ``type(name, bases, namespace)``." -#: ../../reference/datamodel.rst:2404 +#: ../../reference/datamodel.rst:2680 msgid "" "The class creation process can be customized by passing the ``metaclass`` " "keyword argument in the class definition line, or by inheriting from an " @@ -3850,7 +4387,27 @@ msgstr "" "classe existente que incluiu tal argumento. No exemplo a seguir, ``MyClass`` " "e ``MySubclass`` são instâncias de ``Meta``::" -#: ../../reference/datamodel.rst:2418 +#: ../../reference/datamodel.rst:2685 +msgid "" +"class Meta(type):\n" +" pass\n" +"\n" +"class MyClass(metaclass=Meta):\n" +" pass\n" +"\n" +"class MySubclass(MyClass):\n" +" pass" +msgstr "" +"class Meta(type):\n" +" pass\n" +"\n" +"class MyClass(metaclass=Meta):\n" +" pass\n" +"\n" +"class MySubclass(MyClass):\n" +" pass" + +#: ../../reference/datamodel.rst:2694 msgid "" "Any other keyword arguments that are specified in the class definition are " "passed through to all metaclass operations described below." @@ -3858,36 +4415,36 @@ msgstr "" "Quaisquer outros argumentos nomeados especificados na definição de classe " "são transmitidos para todas as operações de metaclasse descritas abaixo." -#: ../../reference/datamodel.rst:2421 +#: ../../reference/datamodel.rst:2697 msgid "When a class definition is executed, the following steps occur:" msgstr "" "Quando uma definição de classe é executada, as seguintes etapas ocorrem:" -#: ../../reference/datamodel.rst:2423 +#: ../../reference/datamodel.rst:2699 msgid "MRO entries are resolved;" msgstr "entradas de MRO são resolvidas;" -#: ../../reference/datamodel.rst:2424 +#: ../../reference/datamodel.rst:2700 msgid "the appropriate metaclass is determined;" msgstr "a metaclasse apropriada é determinada;" -#: ../../reference/datamodel.rst:2425 +#: ../../reference/datamodel.rst:2701 msgid "the class namespace is prepared;" msgstr "o espaço de nomes da classe é preparada;" -#: ../../reference/datamodel.rst:2426 +#: ../../reference/datamodel.rst:2702 msgid "the class body is executed;" msgstr "o corpo da classe é executado;" -#: ../../reference/datamodel.rst:2427 +#: ../../reference/datamodel.rst:2703 msgid "the class object is created." msgstr "o objeto da classe é criado." -#: ../../reference/datamodel.rst:2431 +#: ../../reference/datamodel.rst:2707 msgid "Resolving MRO entries" msgstr "Resolvendo entradas de MRO" -#: ../../reference/datamodel.rst:2435 +#: ../../reference/datamodel.rst:2711 msgid "" "If a base that appears in a class definition is not an instance of :class:" "`type`, then an :meth:`!__mro_entries__` method is searched on the base. If " @@ -3907,19 +4464,19 @@ msgstr "" "classes que serão usadas no lugar da base. A tupla retornada pode estar " "vazia: nesses casos, a base original é ignorada." -#: ../../reference/datamodel.rst:2446 +#: ../../reference/datamodel.rst:2722 msgid ":func:`types.resolve_bases`" msgstr ":func:`types.resolve_bases`" -#: ../../reference/datamodel.rst:2447 +#: ../../reference/datamodel.rst:2723 msgid "Dynamically resolve bases that are not instances of :class:`type`." msgstr "Dinamicamente resolve bases que não são instâncias de :class:`type`." -#: ../../reference/datamodel.rst:2449 +#: ../../reference/datamodel.rst:2725 msgid ":func:`types.get_original_bases`" msgstr ":func:`types.get_original_bases`" -#: ../../reference/datamodel.rst:2450 +#: ../../reference/datamodel.rst:2726 msgid "" "Retrieve a class's \"original bases\" prior to modifications by :meth:" "`~object.__mro_entries__`." @@ -3927,33 +4484,33 @@ msgstr "" "Recupera as \"bases originais\" de uma classe antes das modificações feitas " "por :meth:`~object.__mro_entries__`." -#: ../../reference/datamodel.rst:2453 +#: ../../reference/datamodel.rst:2729 msgid ":pep:`560`" msgstr ":pep:`560`" -#: ../../reference/datamodel.rst:2454 +#: ../../reference/datamodel.rst:2730 msgid "Core support for typing module and generic types." msgstr "Suporte básico para módulo typing e tipos genéricos." -#: ../../reference/datamodel.rst:2458 +#: ../../reference/datamodel.rst:2734 msgid "Determining the appropriate metaclass" msgstr "Determinando a metaclasse apropriada" -#: ../../reference/datamodel.rst:2462 +#: ../../reference/datamodel.rst:2738 msgid "" "The appropriate metaclass for a class definition is determined as follows:" msgstr "" "A metaclasse apropriada para uma definição de classe é determinada da " "seguinte forma:" -#: ../../reference/datamodel.rst:2464 +#: ../../reference/datamodel.rst:2740 msgid "" "if no bases and no explicit metaclass are given, then :func:`type` is used;" msgstr "" "se nenhuma classe base e nenhuma metaclasse explícita forem fornecidas, " "então :func:`type` é usada;" -#: ../../reference/datamodel.rst:2465 +#: ../../reference/datamodel.rst:2741 msgid "" "if an explicit metaclass is given and it is *not* an instance of :func:" "`type`, then it is used directly as the metaclass;" @@ -3961,7 +4518,7 @@ msgstr "" "se uma metaclasse explícita é fornecida e *não* é uma instância de :func:" "`type`, então ela é usada diretamente como a metaclasse;" -#: ../../reference/datamodel.rst:2467 +#: ../../reference/datamodel.rst:2743 msgid "" "if an instance of :func:`type` is given as the explicit metaclass, or bases " "are defined, then the most derived metaclass is used." @@ -3969,7 +4526,7 @@ msgstr "" "se uma instância de :func:`type` é fornecida como a metaclasse explícita, ou " "classes bases são definidas, então a metaclasse mais derivada é usada." -#: ../../reference/datamodel.rst:2470 +#: ../../reference/datamodel.rst:2746 msgid "" "The most derived metaclass is selected from the explicitly specified " "metaclass (if any) and the metaclasses (i.e. ``type(cls)``) of all specified " @@ -3984,11 +4541,11 @@ msgstr "" "Se nenhuma das metaclasses candidatas atender a esse critério, a definição " "de classe falhará com ``TypeError``." -#: ../../reference/datamodel.rst:2480 +#: ../../reference/datamodel.rst:2756 msgid "Preparing the class namespace" msgstr "Preparando o espaço de nomes da classe" -#: ../../reference/datamodel.rst:2485 +#: ../../reference/datamodel.rst:2761 msgid "" "Once the appropriate metaclass has been identified, then the class namespace " "is prepared. If the metaclass has a ``__prepare__`` attribute, it is called " @@ -4008,7 +4565,7 @@ msgstr "" "é passado para ``__new__``, mas quando o objeto classe final é criado, o " "espaço de nomes é copiado para um novo ``dict``." -#: ../../reference/datamodel.rst:2494 +#: ../../reference/datamodel.rst:2770 msgid "" "If the metaclass has no ``__prepare__`` attribute, then the class namespace " "is initialised as an empty ordered mapping." @@ -4016,19 +4573,19 @@ msgstr "" "Se a metaclasse não tiver o atributo ``__prepare__``, então o espaço de " "nomes da classe é inicializado como um mapeamento ordenado vazio." -#: ../../reference/datamodel.rst:2499 +#: ../../reference/datamodel.rst:2775 msgid ":pep:`3115` - Metaclasses in Python 3000" msgstr ":pep:`3115` - Metaclasses no Python 3000" -#: ../../reference/datamodel.rst:2500 +#: ../../reference/datamodel.rst:2776 msgid "Introduced the ``__prepare__`` namespace hook" msgstr "Introduzido o gancho de espaço de nomes ``__prepare__``" -#: ../../reference/datamodel.rst:2504 +#: ../../reference/datamodel.rst:2780 msgid "Executing the class body" msgstr "Executando o corpo da classe" -#: ../../reference/datamodel.rst:2509 +#: ../../reference/datamodel.rst:2785 msgid "" "The class body is executed (approximately) as ``exec(body, globals(), " "namespace)``. The key difference from a normal call to :func:`exec` is that " @@ -4042,7 +4599,7 @@ msgstr "" "métodos) faça referência a nomes dos escopos atual e externo quando a " "definição de classe ocorre dentro de uma função." -#: ../../reference/datamodel.rst:2515 +#: ../../reference/datamodel.rst:2791 msgid "" "However, even when the class definition occurs inside the function, methods " "defined inside the class still cannot see names defined at the class scope. " @@ -4057,11 +4614,11 @@ msgstr "" "referência implícita com escopo léxico ``__class__`` descrita na próxima " "seção." -#: ../../reference/datamodel.rst:2524 +#: ../../reference/datamodel.rst:2800 msgid "Creating the class object" msgstr "Criando o objeto classe" -#: ../../reference/datamodel.rst:2531 +#: ../../reference/datamodel.rst:2807 msgid "" "Once the class namespace has been populated by executing the class body, the " "class object is created by calling ``metaclass(name, bases, namespace, " @@ -4073,7 +4630,7 @@ msgstr "" "namespace, **kwds)`` (os argumentos adicionais passados aqui são os mesmos " "passados para ``__prepare__``)." -#: ../../reference/datamodel.rst:2536 +#: ../../reference/datamodel.rst:2812 msgid "" "This class object is the one that will be referenced by the zero-argument " "form of :func:`super`. ``__class__`` is an implicit closure reference " @@ -4092,7 +4649,7 @@ msgstr "" "chamada atual é identificada com base no primeiro argumento passado para o " "método." -#: ../../reference/datamodel.rst:2546 +#: ../../reference/datamodel.rst:2822 msgid "" "In CPython 3.6 and later, the ``__class__`` cell is passed to the metaclass " "as a ``__classcell__`` entry in the class namespace. If present, this must " @@ -4106,7 +4663,7 @@ msgstr "" "__new__`` para que a classe seja inicializada corretamente. Não fazer isso " "resultará em um :exc:`RuntimeError` no Python 3.8." -#: ../../reference/datamodel.rst:2552 +#: ../../reference/datamodel.rst:2828 msgid "" "When using the default metaclass :class:`type`, or any metaclass that " "ultimately calls ``type.__new__``, the following additional customization " @@ -4116,7 +4673,7 @@ msgstr "" "chame ``type.__new__``, as seguintes etapas de personalização adicionais são " "executadas depois da criação do objeto classe:" -#: ../../reference/datamodel.rst:2556 +#: ../../reference/datamodel.rst:2832 msgid "" "The ``type.__new__`` method collects all of the attributes in the class " "namespace that define a :meth:`~object.__set_name__` method;" @@ -4124,7 +4681,7 @@ msgstr "" "O método ``type.__new__`` coleta todos os atributos no espaço de nomes da " "classe que definem um método :meth:`~object.__set_name__`;" -#: ../../reference/datamodel.rst:2558 +#: ../../reference/datamodel.rst:2834 msgid "" "Those ``__set_name__`` methods are called with the class being defined and " "the assigned name of that particular attribute;" @@ -4132,7 +4689,7 @@ msgstr "" "Esses métodos ``__set_name__`` são chamados com a classe sendo definida e o " "nome atribuído para este atributo específico;" -#: ../../reference/datamodel.rst:2560 +#: ../../reference/datamodel.rst:2836 msgid "" "The :meth:`~object.__init_subclass__` hook is called on the immediate parent " "of the new class in its method resolution order." @@ -4140,7 +4697,7 @@ msgstr "" "O gancho :meth:`~object.__init_subclass__` é chamado na classe base imediata " "da nova classe em sua ordem de resolução de método." -#: ../../reference/datamodel.rst:2563 +#: ../../reference/datamodel.rst:2839 msgid "" "After the class object is created, it is passed to the class decorators " "included in the class definition (if any) and the resulting object is bound " @@ -4150,32 +4707,32 @@ msgstr "" "classe incluídos na definição de classe (se houver) e o objeto resultante é " "vinculado ao espaço de nomes local como a classe definida." -#: ../../reference/datamodel.rst:2567 +#: ../../reference/datamodel.rst:2843 msgid "" "When a new class is created by ``type.__new__``, the object provided as the " "namespace parameter is copied to a new ordered mapping and the original " "object is discarded. The new copy is wrapped in a read-only proxy, which " -"becomes the :attr:`~object.__dict__` attribute of the class object." +"becomes the :attr:`~type.__dict__` attribute of the class object." msgstr "" "Quando uma nova classe é criada por ``type.__new__``, o objeto fornecido " "como o parâmetro do espaço de nomes é copiado para um novo mapeamento " "ordenado e o objeto original é descartado. A nova cópia é envolta em um " -"proxy de somente leitura, que se torna o atributo :attr:`~object.__dict__` " -"do objeto classe." +"proxy de somente leitura, que se torna o atributo :attr:`~type.__dict__` do " +"objeto classe." -#: ../../reference/datamodel.rst:2574 +#: ../../reference/datamodel.rst:2850 msgid ":pep:`3135` - New super" msgstr ":pep:`3135` - Novo super" -#: ../../reference/datamodel.rst:2575 +#: ../../reference/datamodel.rst:2851 msgid "Describes the implicit ``__class__`` closure reference" msgstr "Descreve a referência de clausura implícita de ``__class__``" -#: ../../reference/datamodel.rst:2579 +#: ../../reference/datamodel.rst:2855 msgid "Uses for metaclasses" msgstr "Usos para metaclasses" -#: ../../reference/datamodel.rst:2581 +#: ../../reference/datamodel.rst:2857 msgid "" "The potential uses for metaclasses are boundless. Some ideas that have been " "explored include enum, logging, interface checking, automatic delegation, " @@ -4187,11 +4744,11 @@ msgstr "" "delegação automática, criação automática de propriedade, proxies, estruturas " "e travamento/sincronização automático/a de recursos." -#: ../../reference/datamodel.rst:2588 +#: ../../reference/datamodel.rst:2864 msgid "Customizing instance and subclass checks" msgstr "Personalizando verificações de instância e subclasse" -#: ../../reference/datamodel.rst:2590 +#: ../../reference/datamodel.rst:2866 msgid "" "The following methods are used to override the default behavior of the :func:" "`isinstance` and :func:`issubclass` built-in functions." @@ -4199,7 +4756,7 @@ msgstr "" "Os seguintes métodos são usados para substituir o comportamento padrão das " "funções embutidas :func:`isinstance` e :func:`issubclass`." -#: ../../reference/datamodel.rst:2593 +#: ../../reference/datamodel.rst:2869 msgid "" "In particular, the metaclass :class:`abc.ABCMeta` implements these methods " "in order to allow the addition of Abstract Base Classes (ABCs) as \"virtual " @@ -4211,7 +4768,7 @@ msgstr "" "base virtuais\" para qualquer classe ou tipo (incluindo tipos embutidos), " "incluindo outras ABCs." -#: ../../reference/datamodel.rst:2600 +#: ../../reference/datamodel.rst:2876 msgid "" "Return true if *instance* should be considered a (direct or indirect) " "instance of *class*. If defined, called to implement ``isinstance(instance, " @@ -4221,7 +4778,7 @@ msgstr "" "ou indireta) da classe *class*. Se definido, chamado para implementar " "``isinstance(instance, class)``." -#: ../../reference/datamodel.rst:2607 +#: ../../reference/datamodel.rst:2883 msgid "" "Return true if *subclass* should be considered a (direct or indirect) " "subclass of *class*. If defined, called to implement ``issubclass(subclass, " @@ -4231,7 +4788,7 @@ msgstr "" "ou indireta) da classe *class*. Se definido, chamado para implementar " "``issubclass(subclass, class)``." -#: ../../reference/datamodel.rst:2612 +#: ../../reference/datamodel.rst:2888 msgid "" "Note that these methods are looked up on the type (metaclass) of a class. " "They cannot be defined as class methods in the actual class. This is " @@ -4243,29 +4800,29 @@ msgstr "" "Isso é consistente com a pesquisa de métodos especiais que são chamados em " "instâncias, apenas neste caso a própria instância é uma classe." -#: ../../reference/datamodel.rst:2619 +#: ../../reference/datamodel.rst:2895 msgid ":pep:`3119` - Introducing Abstract Base Classes" msgstr ":pep:`3119` - Introduzindo classes base abstratas" -#: ../../reference/datamodel.rst:2620 +#: ../../reference/datamodel.rst:2896 msgid "" "Includes the specification for customizing :func:`isinstance` and :func:" -"`issubclass` behavior through :meth:`~class.__instancecheck__` and :meth:" -"`~class.__subclasscheck__`, with motivation for this functionality in the " +"`issubclass` behavior through :meth:`~type.__instancecheck__` and :meth:" +"`~type.__subclasscheck__`, with motivation for this functionality in the " "context of adding Abstract Base Classes (see the :mod:`abc` module) to the " "language." msgstr "" "Inclui a especificação para personalizar o comportamento de :func:" -"`isinstance` e :func:`issubclass` através de :meth:`~class." -"__instancecheck__` e :meth:`~class.__subclasscheck__`, com motivação para " -"esta funcionalidade no contexto da adição de classes base abstratas (veja o " -"módulo :mod:`abc`) para a linguagem." +"`isinstance` e :func:`issubclass` através de :meth:`~type.__instancecheck__` " +"e :meth:`~type.__subclasscheck__`, com motivação para esta funcionalidade no " +"contexto da adição de classes base abstratas (veja o módulo :mod:`abc`) para " +"a linguagem." -#: ../../reference/datamodel.rst:2628 +#: ../../reference/datamodel.rst:2904 msgid "Emulating generic types" msgstr "Emulando tipos genéricos" -#: ../../reference/datamodel.rst:2630 +#: ../../reference/datamodel.rst:2906 msgid "" "When using :term:`type annotations`, it is often useful to " "*parameterize* a :term:`generic type` using Python's square-brackets " @@ -4278,24 +4835,24 @@ msgstr "" "para indicar uma :class:`list` em que todos os seus elementos são do tipo :" "class:`int`." -#: ../../reference/datamodel.rst:2637 +#: ../../reference/datamodel.rst:2913 msgid ":pep:`484` - Type Hints" msgstr ":pep:`484` - Dicas de tipo" -#: ../../reference/datamodel.rst:2638 +#: ../../reference/datamodel.rst:2914 msgid "Introducing Python's framework for type annotations" msgstr "Apresenta a estrutura do Python para anotações de tipo" -#: ../../reference/datamodel.rst:2640 +#: ../../reference/datamodel.rst:2916 msgid ":ref:`Generic Alias Types`" msgstr ":ref:`Tipos Generic Alias `" -#: ../../reference/datamodel.rst:2641 +#: ../../reference/datamodel.rst:2917 msgid "Documentation for objects representing parameterized generic classes" msgstr "" "Documentação de objetos que representam classes genéricas parametrizadas" -#: ../../reference/datamodel.rst:2643 +#: ../../reference/datamodel.rst:2919 msgid "" ":ref:`Generics`, :ref:`user-defined generics` and :" "class:`typing.Generic`" @@ -4303,7 +4860,7 @@ msgstr "" ":ref:`Generics`, :ref:`genéricos definidos pelo usuário` e :class:`typing.Generic`" -#: ../../reference/datamodel.rst:2644 +#: ../../reference/datamodel.rst:2920 msgid "" "Documentation on how to implement generic classes that can be parameterized " "at runtime and understood by static type-checkers." @@ -4312,7 +4869,7 @@ msgstr "" "parametrizadas em tempo de execução e compreendidas por verificadores de " "tipo estático." -#: ../../reference/datamodel.rst:2647 +#: ../../reference/datamodel.rst:2923 msgid "" "A class can *generally* only be parameterized if it defines the special " "class method ``__class_getitem__()``." @@ -4320,7 +4877,7 @@ msgstr "" "Uma classe pode *geralmente* ser parametrizada somente se ela define o " "método de classe especial ``__class_getitem__()``." -#: ../../reference/datamodel.rst:2652 +#: ../../reference/datamodel.rst:2928 msgid "" "Return an object representing the specialization of a generic class by type " "arguments found in *key*." @@ -4328,7 +4885,7 @@ msgstr "" "Retorna um objeto que representa a especialização de uma classe genérica por " "argumentos de tipo encontrados em *key*." -#: ../../reference/datamodel.rst:2655 +#: ../../reference/datamodel.rst:2931 msgid "" "When defined on a class, ``__class_getitem__()`` is automatically a class " "method. As such, there is no need for it to be decorated with :func:" @@ -4338,11 +4895,11 @@ msgstr "" "método de classe. Assim, não é necessário que seja decorado com :func:" "`@classmethod` quando de sua definição." -#: ../../reference/datamodel.rst:2661 +#: ../../reference/datamodel.rst:2937 msgid "The purpose of *__class_getitem__*" msgstr "O propósito de *__class_getitem__*" -#: ../../reference/datamodel.rst:2663 +#: ../../reference/datamodel.rst:2939 msgid "" "The purpose of :meth:`~object.__class_getitem__` is to allow runtime " "parameterization of standard-library generic classes in order to more easily " @@ -4352,7 +4909,7 @@ msgstr "" "em tempo de execução de classes genéricas da biblioteca padrão, a fim de " "aplicar mais facilmente :term:`dicas de tipo` a essas classes." -#: ../../reference/datamodel.rst:2667 +#: ../../reference/datamodel.rst:2943 msgid "" "To implement custom generic classes that can be parameterized at runtime and " "understood by static type-checkers, users should either inherit from a " @@ -4367,7 +4924,7 @@ msgstr "" "`typing.Generic`, que possui sua própria implementação de " "``__class_getitem__()``." -#: ../../reference/datamodel.rst:2673 +#: ../../reference/datamodel.rst:2949 msgid "" "Custom implementations of :meth:`~object.__class_getitem__` on classes " "defined outside of the standard library may not be understood by third-party " @@ -4380,11 +4937,11 @@ msgstr "" "``__class_getitem__()`` em qualquer classe para fins diferentes de dicas de " "tipo é desencorajado." -#: ../../reference/datamodel.rst:2683 +#: ../../reference/datamodel.rst:2959 msgid "*__class_getitem__* versus *__getitem__*" msgstr "*__class_getitem__* versus *__getitem__*" -#: ../../reference/datamodel.rst:2685 +#: ../../reference/datamodel.rst:2961 msgid "" "Usually, the :ref:`subscription` of an object using square " "brackets will call the :meth:`~object.__getitem__` instance method defined " @@ -4400,7 +4957,7 @@ msgstr "" "chamado em seu lugar. ``__class_getitem__()`` deve retornar um objeto :ref:" "`GenericAlias` se estiver devidamente definido." -#: ../../reference/datamodel.rst:2692 +#: ../../reference/datamodel.rst:2968 msgid "" "Presented with the :term:`expression` ``obj[x]``, the Python interpreter " "follows something like the following process to decide whether :meth:" @@ -4410,7 +4967,55 @@ msgstr "" "segue algo parecido com o seguinte processo para decidir se :meth:`~object." "__getitem__` ou :meth:`~object.__class_getitem__` deve ser chamado:" -#: ../../reference/datamodel.rst:2720 +#: ../../reference/datamodel.rst:2973 +msgid "" +"from inspect import isclass\n" +"\n" +"def subscribe(obj, x):\n" +" \"\"\"Return the result of the expression 'obj[x]'\"\"\"\n" +"\n" +" class_of_obj = type(obj)\n" +"\n" +" # If the class of obj defines __getitem__,\n" +" # call class_of_obj.__getitem__(obj, x)\n" +" if hasattr(class_of_obj, '__getitem__'):\n" +" return class_of_obj.__getitem__(obj, x)\n" +"\n" +" # Else, if obj is a class and defines __class_getitem__,\n" +" # call obj.__class_getitem__(x)\n" +" elif isclass(obj) and hasattr(obj, '__class_getitem__'):\n" +" return obj.__class_getitem__(x)\n" +"\n" +" # Else, raise an exception\n" +" else:\n" +" raise TypeError(\n" +" f\"'{class_of_obj.__name__}' object is not subscriptable\"\n" +" )" +msgstr "" +"from inspect import isclass\n" +"\n" +"def subscribe(obj, x):\n" +" \"\"\"Return the result of the expression 'obj[x]'\"\"\"\n" +"\n" +" class_of_obj = type(obj)\n" +"\n" +" # Se a classe de obj define __getitem__,\n" +" # chama class_of_obj.__getitem__(obj, x)\n" +" if hasattr(class_of_obj, '__getitem__'):\n" +" return class_of_obj.__getitem__(obj, x)\n" +"\n" +" # Do contrário, se obj for uma classe e define __class_getitem__,\n" +" # chama obj.__class_getitem__(x)\n" +" elif isclass(obj) and hasattr(obj, '__class_getitem__'):\n" +" return obj.__class_getitem__(x)\n" +"\n" +" # Do contrário, levanta uma exceção\n" +" else:\n" +" raise TypeError(\n" +" f\"'{class_of_obj.__name__}' object is not subscriptable\"\n" +" )" + +#: ../../reference/datamodel.rst:2996 msgid "" "In Python, all classes are themselves instances of other classes. The class " "of a class is known as that class's :term:`metaclass`, and most classes have " @@ -4426,7 +5031,34 @@ msgstr "" "expressões como ``list[int]``, ``dict[str, float]`` e ``tuple[str, bytes]`` " "resultam em chamadas para :meth:`~object.__class_getitem__`::" -#: ../../reference/datamodel.rst:2739 +#: ../../reference/datamodel.rst:3003 +msgid "" +">>> # list has class \"type\" as its metaclass, like most classes:\n" +">>> type(list)\n" +"\n" +">>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes)\n" +"True\n" +">>> # \"list[int]\" calls \"list.__class_getitem__(int)\"\n" +">>> list[int]\n" +"list[int]\n" +">>> # list.__class_getitem__ returns a GenericAlias object:\n" +">>> type(list[int])\n" +"" +msgstr "" +">>> # lista tem a classe \"type\" como sua metaclasse, como a maioria das " +"classes:\n" +">>> type(list)\n" +"\n" +">>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes)\n" +"True\n" +">>> # \"list[int]\" chama \"list.__class_getitem__(int)\"\n" +">>> list[int]\n" +"list[int]\n" +">>> # list.__class_getitem__ retorna um objeto GenericAlias:\n" +">>> type(list[int])\n" +"" + +#: ../../reference/datamodel.rst:3015 msgid "" "However, if a class has a custom metaclass that defines :meth:`~object." "__getitem__`, subscribing the class may result in different behaviour. An " @@ -4437,11 +5069,47 @@ msgstr "" "comportamento diferente. Um exemplo disso pode ser encontrado no módulo :mod:" "`enum`::" -#: ../../reference/datamodel.rst:2762 +#: ../../reference/datamodel.rst:3019 +msgid "" +">>> from enum import Enum\n" +">>> class Menu(Enum):\n" +"... \"\"\"A breakfast menu\"\"\"\n" +"... SPAM = 'spam'\n" +"... BACON = 'bacon'\n" +"...\n" +">>> # Enum classes have a custom metaclass:\n" +">>> type(Menu)\n" +"\n" +">>> # EnumMeta defines __getitem__,\n" +">>> # so __class_getitem__ is not called,\n" +">>> # and the result is not a GenericAlias object:\n" +">>> Menu['SPAM']\n" +"\n" +">>> type(Menu['SPAM'])\n" +"" +msgstr "" +">>> from enum import Enum\n" +">>> class Menu(Enum):\n" +"... \"\"\"A breakfast menu\"\"\"\n" +"... SPAM = 'spam'\n" +"... BACON = 'bacon'\n" +"...\n" +">>> # Classes Enum têm uma metaclasses personalizada:\n" +">>> type(Menu)\n" +"\n" +">>> # EnumMeta define __getitem__,\n" +">>> # de forma que __class_getitem__ não é chamado,\n" +">>> # e o resultado não é um objeto GenericAlias:\n" +">>> Menu['SPAM']\n" +"\n" +">>> type(Menu['SPAM'])\n" +"" + +#: ../../reference/datamodel.rst:3038 msgid ":pep:`560` - Core Support for typing module and generic types" msgstr ":pep:`560` - Suporte básico para módulo typing e tipos genéricos" -#: ../../reference/datamodel.rst:2763 +#: ../../reference/datamodel.rst:3039 msgid "" "Introducing :meth:`~object.__class_getitem__`, and outlining when a :ref:" "`subscription` results in ``__class_getitem__()`` being " @@ -4451,35 +5119,37 @@ msgstr "" "`subscrição` resulta na chamada de ``__class_getitem__()`` em " "vez de :meth:`~object.__getitem__`" -#: ../../reference/datamodel.rst:2771 +#: ../../reference/datamodel.rst:3047 msgid "Emulating callable objects" msgstr "Emulando objetos chamáveis" -#: ../../reference/datamodel.rst:2778 +#: ../../reference/datamodel.rst:3054 msgid "" "Called when the instance is \"called\" as a function; if this method is " "defined, ``x(arg1, arg2, ...)`` roughly translates to ``type(x).__call__(x, " -"arg1, ...)``." +"arg1, ...)``. The :class:`object` class itself does not provide this method." msgstr "" "Chamado quando a instância é \"chamada\" como uma função; se este método for " "definido, ``x(arg1, arg2, ...)`` basicamente traduz para ``type(x)." -"__call__(x, arg1, ...)``." +"__call__(x, arg1, ...)``. A classe :class:`object` em si não fornece este " +"método." -#: ../../reference/datamodel.rst:2785 +#: ../../reference/datamodel.rst:3062 msgid "Emulating container types" -msgstr "Emulando de tipos contêineres" - -#: ../../reference/datamodel.rst:2787 -msgid "" -"The following methods can be defined to implement container objects. " -"Containers usually are :term:`sequences ` (such as :class:`lists " -"` or :class:`tuples `) or :term:`mappings ` (like :" -"class:`dictionaries `), but can represent other containers as well. " -"The first set of methods is used either to emulate a sequence or to emulate " -"a mapping; the difference is that for a sequence, the allowable keys should " -"be the integers *k* for which ``0 <= k < N`` where *N* is the length of the " -"sequence, or :class:`slice` objects, which define a range of items. It is " -"also recommended that mappings provide the methods :meth:`!keys`, :meth:`!" +msgstr "Emulando tipos contêineres" + +#: ../../reference/datamodel.rst:3064 +msgid "" +"The following methods can be defined to implement container objects. None of " +"them are provided by the :class:`object` class itself. Containers usually " +"are :term:`sequences ` (such as :class:`lists ` or :class:" +"`tuples `) or :term:`mappings ` (like :term:`dictionaries " +"`), but can represent other containers as well. The first set " +"of methods is used either to emulate a sequence or to emulate a mapping; the " +"difference is that for a sequence, the allowable keys should be the integers " +"*k* for which ``0 <= k < N`` where *N* is the length of the sequence, or :" +"class:`slice` objects, which define a range of items. It is also " +"recommended that mappings provide the methods :meth:`!keys`, :meth:`!" "values`, :meth:`!items`, :meth:`!get`, :meth:`!clear`, :meth:`!setdefault`, :" "meth:`!pop`, :meth:`!popitem`, :meth:`!copy`, and :meth:`!update` behaving " "similar to those for Python's standard :class:`dictionary ` objects. " @@ -4504,16 +5174,54 @@ msgid "" "meth:`!__iter__` should iterate through the object's keys; for sequences, it " "should iterate through the values." msgstr "" - -#: ../../reference/datamodel.rst:2828 +"Os métodos a seguir podem ser definidos para implementar objetos " +"contêineres. Nenhum deles são fornecidos pela classe :class:`object` em si. " +"Os contêineres geralmente são :term:`sequências ` (tal como :class:" +"`listas ` ou :class:`tuplas `) ou :term:`mapeamentos ` " +"(com :term:`dicionários `), mas também podem representar outros " +"contêineres. O primeiro conjunto de métodos é usado para emular uma " +"sequência ou para emular um mapeamento; a diferença é que, para uma " +"sequência, as chaves permitidas devem ser os inteiros *k* para os quais ``0 " +"<= k < N`` onde *N* é o comprimento da sequência, ou objetos :class:`slice`, " +"que definem um intervalo de itens. Também é recomendado que os mapeamentos " +"forneçam os métodos :meth:`!keys`, :meth:`!values`, :meth:`!items`, :meth:`!" +"get`, :meth:`!clear`, :meth:`!setdefault`, :meth:`!pop`, :meth:`!popitem`, :" +"meth:`!copy` e :meth:`!update` se comportando de forma semelhante aos " +"objetos :class:`dicionário ` padrão do Python. O módulo :mod:" +"`collections.abc` fornece uma :term:`classe base abstrata` :class:" +"`~collections.abc.MutableMapping` para ajudar a criar esses métodos a partir " +"de um conjunto base de :meth:`~object.__getitem__`, :meth:`~object." +"__setitem__`, :meth:`~object.__delitem__` e :meth:`!keys`. Sequências " +"mutáveis devem fornecer métodos :meth:`!append`, :meth:`!count`, :meth:`!" +"index`, :meth:`!extend`, :meth:`!insert`, :meth:`!pop`, :meth:`!remove`, :" +"meth:`!reverse` e :meth:`!sort`, como objetos :class:`list` padrão do " +"Python. Finalmente, os tipos sequência devem implementar adição " +"(significando concatenação) e multiplicação (significando repetição) " +"definindo os métodos :meth:`~object.__add__`, :meth:`~object.__radd__`, :" +"meth:`~object.__iadd__`, :meth:`~object.__mul__`, :meth:`~object.__rmul__` " +"e :meth:`~object.__imul__` descritos abaixo; eles não devem definir outros " +"operadores numéricos. É recomendado que ambos os mapeamentos e sequências " +"implementem o método :meth:`~object.__contains__` para permitir o uso " +"eficiente do operador ``in``; para mapeamentos, ``in`` deve pesquisar as " +"chaves do mapeamento; para sequências, ele deve pesquisar os valores. É " +"ainda recomendado que ambos os mapeamentos e sequências implementem o " +"método :meth:`~object.__iter__` para permitir a iteração eficiente através " +"do contêiner; para mapeamentos, :meth:`!__iter__` deve iterar através das " +"chaves do objeto; para sequências, ele deve iterar por meio dos valores." + +#: ../../reference/datamodel.rst:3106 msgid "" "Called to implement the built-in function :func:`len`. Should return the " "length of the object, an integer ``>=`` 0. Also, an object that doesn't " "define a :meth:`~object.__bool__` method and whose :meth:`!__len__` method " "returns zero is considered to be false in a Boolean context." msgstr "" +"Chamado para implementar a função embutida :func:`len`. Deve retornar o " +"comprimento do objeto, um inteiro ``>=`` 0. Além disso, um objeto que não " +"define um método :meth:`~object.__bool__` e cujo método :meth:`!__len__` " +"retorna zero é considerado como falso em um contexto booleano." -#: ../../reference/datamodel.rst:2835 +#: ../../reference/datamodel.rst:3113 msgid "" "In CPython, the length is required to be at most :data:`sys.maxsize`. If the " "length is larger than :data:`!sys.maxsize` some features (such as :func:" @@ -4521,8 +5229,13 @@ msgid "" "OverflowError` by truth value testing, an object must define a :meth:" "`~object.__bool__` method." msgstr "" +"No CPython, o comprimento deve ser no máximo :data:`sys.maxsize`. Se o " +"comprimento for maior que :data:`!sys.maxsize`, alguns recursos (como :func:" +"`len`) podem levantar :exc:`OverflowError`. Para evitar levantar :exc:`!" +"OverflowError` pelo teste de valor de verdade, um objeto deve definir um " +"método :meth:`~object.__bool__`." -#: ../../reference/datamodel.rst:2844 +#: ../../reference/datamodel.rst:3122 msgid "" "Called to implement :func:`operator.length_hint`. Should return an estimated " "length for the object (which may be greater or less than the actual length). " @@ -4531,25 +5244,39 @@ msgid "" "method didn't exist at all. This method is purely an optimization and is " "never required for correctness." msgstr "" +"Chamado para implementar :func:`operator.length_hint`. Deve retornar um " +"comprimento estimado para o objeto (que pode ser maior ou menor que o " +"comprimento real). O comprimento deve ser um inteiro ``>=`` 0. O valor de " +"retorno também pode ser :data:`NotImplemented`, que é tratado da mesma forma " +"como se o método ``__length_hint__`` não existisse. Este método é puramente " +"uma otimização e nunca é necessário para a correção." -#: ../../reference/datamodel.rst:2858 +#: ../../reference/datamodel.rst:3136 msgid "" "Slicing is done exclusively with the following three methods. A call like ::" msgstr "" "O fatiamento é feito exclusivamente com os três métodos a seguir. Uma " "chamada como ::" -#: ../../reference/datamodel.rst:2862 +#: ../../reference/datamodel.rst:3138 +msgid "a[1:2] = b" +msgstr "a[1:2] = b" + +#: ../../reference/datamodel.rst:3140 msgid "is translated to ::" msgstr "é traduzida com ::" -#: ../../reference/datamodel.rst:2866 +#: ../../reference/datamodel.rst:3142 +msgid "a[slice(1, 2, None)] = b" +msgstr "a[slice(1, 2, None)] = b" + +#: ../../reference/datamodel.rst:3144 msgid "and so forth. Missing slice items are always filled in with ``None``." msgstr "" "e assim por diante. Os itens de fatia ausentes são sempre preenchidos com " "``None``." -#: ../../reference/datamodel.rst:2871 +#: ../../reference/datamodel.rst:3149 msgid "" "Called to implement evaluation of ``self[key]``. For :term:`sequence` types, " "the accepted keys should be integers. Optionally, they may support :class:" @@ -4560,8 +5287,17 @@ msgid "" "term:`mapping` types, if *key* is missing (not in the container), :exc:" "`KeyError` should be raised." msgstr "" +"Chamado para implementar a avaliação de ``self[key]``. Para tipos de :term:" +"`sequência`, as chaves aceitas devem ser inteiros. Opcionalmente, eles " +"também podem oferecer suporte a objetos :class:`slice`. Suporte a índice " +"negativo também é opcional. Se *key* for de um tipo impróprio, :exc:" +"`TypeError` pode ser levantada; se *key* for de um valor fora do conjunto de " +"índices para a sequência (após qualquer interpretação especial de valores " +"negativos), :exc:`IndexError` deve ser levantada. Para tipos :term:" +"`mapeamento`, se *key* estiver faltando (não no contêiner), :exc:`KeyError` " +"deve ser levantada." -#: ../../reference/datamodel.rst:2883 +#: ../../reference/datamodel.rst:3161 msgid "" ":keyword:`for` loops expect that an :exc:`IndexError` will be raised for " "illegal indexes to allow proper detection of the end of the sequence." @@ -4569,14 +5305,18 @@ msgstr "" "Os loops :keyword:`for` esperam que uma :exc:`IndexError` seja levantada " "para índices ilegais para permitir a detecção apropriada do fim da sequência." -#: ../../reference/datamodel.rst:2888 +#: ../../reference/datamodel.rst:3166 msgid "" "When :ref:`subscripting` a *class*, the special class method :" "meth:`~object.__class_getitem__` may be called instead of ``__getitem__()``. " "See :ref:`classgetitem-versus-getitem` for more details." msgstr "" +"Ao fazer :ref:`subscrição ` de uma *classe*, o método de " +"classe especial :meth:`~object.__class_getitem__` pode ser chamado em vez de " +"``__getitem__()``. Veja :ref:`classgetitem-versus-getitem` para mais " +"detalhes." -#: ../../reference/datamodel.rst:2896 +#: ../../reference/datamodel.rst:3174 msgid "" "Called to implement assignment to ``self[key]``. Same note as for :meth:" "`__getitem__`. This should only be implemented for mappings if the objects " @@ -4591,7 +5331,7 @@ msgstr "" "substituídos. As mesmas exceções devem ser levantadas para valores *key* " "impróprios do método :meth:`__getitem__`." -#: ../../reference/datamodel.rst:2905 +#: ../../reference/datamodel.rst:3183 msgid "" "Called to implement deletion of ``self[key]``. Same note as for :meth:" "`__getitem__`. This should only be implemented for mappings if the objects " @@ -4605,7 +5345,7 @@ msgstr "" "puderem ser removidos da sequência. As mesmas exceções devem ser levantadas " "para valores *key* impróprios do método :meth:`__getitem__`." -#: ../../reference/datamodel.rst:2914 +#: ../../reference/datamodel.rst:3192 msgid "" "Called by :class:`dict`\\ .\\ :meth:`__getitem__` to implement ``self[key]`` " "for dict subclasses when key is not in the dictionary." @@ -4614,15 +5354,19 @@ msgstr "" "``self[key]`` para subclasses de dicionário quando a chave não estiver no " "dicionário." -#: ../../reference/datamodel.rst:2920 +#: ../../reference/datamodel.rst:3198 msgid "" "This method is called when an :term:`iterator` is required for a container. " "This method should return a new iterator object that can iterate over all " "the objects in the container. For mappings, it should iterate over the keys " "of the container." msgstr "" +"Este método é chamado quando um :term:`iterador` é necessário para um " +"contêiner. Este método deve retornar um novo objeto iterador que pode iterar " +"sobre todos os objetos no contêiner. Para mapeamentos, ele deve iterar sobre " +"as chaves do contêiner." -#: ../../reference/datamodel.rst:2928 +#: ../../reference/datamodel.rst:3206 msgid "" "Called (if present) by the :func:`reversed` built-in to implement reverse " "iteration. It should return a new iterator object that iterates over all " @@ -4632,7 +5376,7 @@ msgstr "" "iteração reversa. Ele deve retornar um novo objeto iterador que itera sobre " "todos os objetos no contêiner na ordem reversa." -#: ../../reference/datamodel.rst:2932 +#: ../../reference/datamodel.rst:3210 msgid "" "If the :meth:`__reversed__` method is not provided, the :func:`reversed` " "built-in will fall back to using the sequence protocol (:meth:`__len__` and :" @@ -4646,7 +5390,7 @@ msgstr "" "fornecer :meth:`__reversed__` se eles puderem fornecer uma implementação que " "seja mais eficiente do que aquela fornecida por :func:`reversed`." -#: ../../reference/datamodel.rst:2939 +#: ../../reference/datamodel.rst:3217 msgid "" "The membership test operators (:keyword:`in` and :keyword:`not in`) are " "normally implemented as an iteration through a container. However, container " @@ -4659,7 +5403,7 @@ msgstr "" "uma implementação mais eficiente, que também não requer que o objeto seja " "iterável." -#: ../../reference/datamodel.rst:2946 +#: ../../reference/datamodel.rst:3224 msgid "" "Called to implement membership test operators. Should return true if *item* " "is in *self*, false otherwise. For mapping objects, this should consider " @@ -4670,7 +5414,7 @@ msgstr "" "de mapeamento, isso deve considerar as chaves do mapeamento em vez dos " "valores ou pares de itens-chave." -#: ../../reference/datamodel.rst:2950 +#: ../../reference/datamodel.rst:3228 msgid "" "For objects that don't define :meth:`__contains__`, the membership test " "first tries iteration via :meth:`__iter__`, then the old sequence iteration " @@ -4682,11 +5426,11 @@ msgstr "" "iteração de sequência antigo via :meth:`__getitem__`, consulte :ref:`esta " "seção em a referência da linguagem `." -#: ../../reference/datamodel.rst:2959 +#: ../../reference/datamodel.rst:3237 msgid "Emulating numeric types" msgstr "Emulando tipos numéricos" -#: ../../reference/datamodel.rst:2961 +#: ../../reference/datamodel.rst:3239 msgid "" "The following methods can be defined to emulate numeric objects. Methods " "corresponding to operations that are not supported by the particular kind of " @@ -4698,7 +5442,7 @@ msgstr "" "particular de número implementado (por exemplo, operações bit a bit para " "números não inteiros) devem ser deixados indefinidos." -#: ../../reference/datamodel.rst:2987 +#: ../../reference/datamodel.rst:3265 msgid "" "These methods are called to implement the binary arithmetic operations " "(``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, :func:" @@ -4711,14 +5455,25 @@ msgid "" "optional third argument if the ternary version of the built-in :func:`pow` " "function is to be supported." msgstr "" +"Esses métodos são chamados para implementar as operações aritméticas " +"binárias (``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, :" +"func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). Por exemplo, para " +"avaliar a expressão ``x + y``, onde *x* é uma instância de uma classe que " +"tem um método :meth:`__add__`, ``type(x).__add__(x, y)`` é chamado. O " +"método :meth:`__divmod__` deve ser equivalente a usar :meth:`__floordiv__` " +"e :meth:`__mod__`; não deve estar relacionado a :meth:`__truediv__`. Note " +"que :meth:`__pow__` deve ser definido para aceitar um terceiro argumento " +"opcional se a versão ternária da função embutida :func:`pow` for suportada." -#: ../../reference/datamodel.rst:2998 +#: ../../reference/datamodel.rst:3276 msgid "" "If one of those methods does not support the operation with the supplied " "arguments, it should return :data:`NotImplemented`." msgstr "" +"Se um desses métodos não suporta a operação com os argumentos fornecidos, " +"ele deve retornar :data:`NotImplemented`." -#: ../../reference/datamodel.rst:3021 +#: ../../reference/datamodel.rst:3299 msgid "" "These methods are called to implement the binary arithmetic operations " "(``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, :func:" @@ -4730,8 +5485,17 @@ msgid "" "__rsub__(y, x)`` is called if ``type(x).__sub__(x, y)`` returns :data:" "`NotImplemented`." msgstr "" +"Esses métodos são chamados para implementar as operações aritméticas " +"binárias (``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, :" +"func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) com operandos " +"refletidos (trocados). Essas funções são chamadas apenas se o operando " +"esquerdo não suportar a operação correspondente [#]_ e os operandos forem de " +"tipos diferentes. [#]_ Por exemplo, para avaliar a expressão ``x - y``, onde " +"*y* é uma instância de uma classe que tem um método :meth:`__rsub__`, " +"``type(y).__rsub__(y, x)`` é chamado se ``type(x).__sub__(x, y)`` retorna :" +"data:`NotImplemented`." -#: ../../reference/datamodel.rst:3033 +#: ../../reference/datamodel.rst:3311 msgid "" "Note that ternary :func:`pow` will not try calling :meth:`__rpow__` (the " "coercion rules would become too complicated)." @@ -4739,7 +5503,7 @@ msgstr "" "Note que ternário :func:`pow` não tentará chamar :meth:`__rpow__` (as regras " "de coerção se tornariam muito complicadas)." -#: ../../reference/datamodel.rst:3038 +#: ../../reference/datamodel.rst:3316 msgid "" "If the right operand's type is a subclass of the left operand's type and " "that subclass provides a different implementation of the reflected method " @@ -4753,7 +5517,7 @@ msgstr "" "operando esquerdo. Esse comportamento permite que as subclasses substituam " "as operações de seus ancestrais." -#: ../../reference/datamodel.rst:3059 +#: ../../reference/datamodel.rst:3337 msgid "" "These methods are called to implement the augmented arithmetic assignments " "(``+=``, ``-=``, ``*=``, ``@=``, ``/=``, ``//=``, ``%=``, ``**=``, ``<<=``, " @@ -4770,8 +5534,22 @@ msgid "" "augmented-assignment-tuple-error`), but this behavior is in fact part of the " "data model." msgstr "" +"Esses métodos são chamados para implementar as atribuições aritméticas " +"aumentadas (``+=``, ``-=``, ``*=``, ``@=``, ``/=``, ``//=``, ``%=``, " +"``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``). Esses métodos devem " +"tentar fazer a operação no local (modificando *self*) e retornar o resultado " +"(que poderia ser, mas não precisa ser, *self*). Se um método específico não " +"for definido, ou se esse método retorna :data:`NotImplemented`, a atribuição " +"aumentada volta aos métodos normais. Por exemplo, se *x* é uma instância de " +"uma classe com um método :meth:`__iadd__`, ``x += y`` equivale a ``x = x." +"__iadd__(y)``. Se :meth:`__iadd__` não existe, ou se ``x.__iadd__(y)`` " +"retorna :data:`!NotImplemented`, ``x.__add__(y)`` e ``y.__radd__(x)`` são " +"considerados, como com a avaliação de ``x + y``. Em certas situações, a " +"atribuição aumentada pode resultar em erros inesperados (veja :ref:`faq-" +"augmented-assignment-tuple-error`), mas este comportamento é na verdade " +"parte do modelo de dados." -#: ../../reference/datamodel.rst:3082 +#: ../../reference/datamodel.rst:3360 msgid "" "Called to implement the unary arithmetic operations (``-``, ``+``, :func:" "`abs` and ``~``)." @@ -4779,7 +5557,7 @@ msgstr "" "Chamado para implementar as operações aritméticas unárias (``-``, ``+``, :" "func:`abs` e ``~``)." -#: ../../reference/datamodel.rst:3095 +#: ../../reference/datamodel.rst:3373 msgid "" "Called to implement the built-in functions :func:`complex`, :func:`int` and :" "func:`float`. Should return a value of the appropriate type." @@ -4787,7 +5565,7 @@ msgstr "" "Chamado para implementar as funções embutidas :func:`complex`, :func:`int` " "e :func:`float`. Deve retornar um valor do tipo apropriado." -#: ../../reference/datamodel.rst:3102 +#: ../../reference/datamodel.rst:3380 msgid "" "Called to implement :func:`operator.index`, and whenever Python needs to " "losslessly convert the numeric object to an integer object (such as in " @@ -4801,7 +5579,7 @@ msgstr "" "`oct`). A presença deste método indica que o objeto numérico é do tipo " "inteiro. Deve retornar um número inteiro." -#: ../../reference/datamodel.rst:3108 +#: ../../reference/datamodel.rst:3386 msgid "" "If :meth:`__int__`, :meth:`__float__` and :meth:`__complex__` are not " "defined then corresponding built-in functions :func:`int`, :func:`float` " @@ -4811,7 +5589,7 @@ msgstr "" "definidos, funções embutidas correspondentes :func:`int`, :func:`float` e :" "func:`complex` recorre a :meth:`__index__`." -#: ../../reference/datamodel.rst:3120 +#: ../../reference/datamodel.rst:3398 msgid "" "Called to implement the built-in function :func:`round` and :mod:`math` " "functions :func:`~math.trunc`, :func:`~math.floor` and :func:`~math.ceil`. " @@ -4825,21 +5603,23 @@ msgstr "" "retornar o valor do objeto truncado para um :class:`~numbers.Integral` " "(tipicamente um :class:`int`)." -#: ../../reference/datamodel.rst:3126 +#: ../../reference/datamodel.rst:3404 msgid "" "The built-in function :func:`int` falls back to :meth:`__trunc__` if " "neither :meth:`__int__` nor :meth:`__index__` is defined." msgstr "" +"A função embutida :func:`int` retorna para :meth:`__trunc__` se nem :meth:" +"`__int__` nem :meth:`__index__` estiverem definidos." -#: ../../reference/datamodel.rst:3129 +#: ../../reference/datamodel.rst:3407 msgid "The delegation of :func:`int` to :meth:`__trunc__` is deprecated." -msgstr "" +msgstr "A delegação de :func:`int` para :meth:`__trunc__` foi descontinuada." -#: ../../reference/datamodel.rst:3136 +#: ../../reference/datamodel.rst:3414 msgid "With Statement Context Managers" msgstr "Gerenciadores de contexto da instrução with" -#: ../../reference/datamodel.rst:3138 +#: ../../reference/datamodel.rst:3416 msgid "" "A :dfn:`context manager` is an object that defines the runtime context to be " "established when executing a :keyword:`with` statement. The context manager " @@ -4856,7 +5636,7 @@ msgstr "" "(descrita na seção :ref:`with`), mas também podem ser usados invocando " "diretamente seus métodos." -#: ../../reference/datamodel.rst:3149 +#: ../../reference/datamodel.rst:3427 msgid "" "Typical uses of context managers include saving and restoring various kinds " "of global state, locking and unlocking resources, closing opened files, etc." @@ -4865,14 +5645,17 @@ msgstr "" "vários tipos de estado global, travar e destravar recursos, fechar arquivos " "abertos, etc." -#: ../../reference/datamodel.rst:3152 +#: ../../reference/datamodel.rst:3430 msgid "" -"For more information on context managers, see :ref:`typecontextmanager`." +"For more information on context managers, see :ref:`typecontextmanager`. " +"The :class:`object` class itself does not provide the context manager " +"methods." msgstr "" -"Para obter mais informações sobre gerenciadores de contexto, consulte :ref:" -"`typecontextmanager`." +"Para mais informações sobre gerenciadores de contexto, veja :ref:" +"`typecontextmanager`. A classe :class:`object` em si não fornece os métodos " +"do gerenciador de contexto." -#: ../../reference/datamodel.rst:3157 +#: ../../reference/datamodel.rst:3436 msgid "" "Enter the runtime context related to this object. The :keyword:`with` " "statement will bind this method's return value to the target(s) specified in " @@ -4882,7 +5665,7 @@ msgstr "" "instrução :keyword:`with` vinculará o valor de retorno deste método ao(s) " "alvo(s) especificado(s) na cláusula :keyword:`!as` da instrução, se houver." -#: ../../reference/datamodel.rst:3164 +#: ../../reference/datamodel.rst:3443 msgid "" "Exit the runtime context related to this object. The parameters describe the " "exception that caused the context to be exited. If the context was exited " @@ -4893,7 +5676,7 @@ msgstr "" "Se o contexto foi encerrado sem exceção, todos os três argumentos serão :" "const:`None`." -#: ../../reference/datamodel.rst:3168 +#: ../../reference/datamodel.rst:3447 msgid "" "If an exception is supplied, and the method wishes to suppress the exception " "(i.e., prevent it from being propagated), it should return a true value. " @@ -4904,17 +5687,19 @@ msgstr "" "evitar que ela seja propagada), ele deve retornar um valor verdadeiro. Caso " "contrário, a exceção será processada normalmente ao sair deste método." -#: ../../reference/datamodel.rst:3172 +#: ../../reference/datamodel.rst:3451 msgid "" "Note that :meth:`~object.__exit__` methods should not reraise the passed-in " "exception; this is the caller's responsibility." msgstr "" +"Observe que os métodos :meth:`~object.__exit__` não devem relançar a exceção " +"passada; esta é a responsabilidade do chamador." -#: ../../reference/datamodel.rst:3178 +#: ../../reference/datamodel.rst:3457 msgid ":pep:`343` - The \"with\" statement" msgstr ":pep:`343` - A instrução \"with\"" -#: ../../reference/datamodel.rst:3179 +#: ../../reference/datamodel.rst:3458 msgid "" "The specification, background, and examples for the Python :keyword:`with` " "statement." @@ -4922,20 +5707,24 @@ msgstr "" "A especificação, o histórico e os exemplos para a instrução Python :keyword:" "`with`." -#: ../../reference/datamodel.rst:3186 +#: ../../reference/datamodel.rst:3465 msgid "Customizing positional arguments in class pattern matching" msgstr "" "Customizando argumentos posicionais na classe correspondência de padrão" -#: ../../reference/datamodel.rst:3188 +#: ../../reference/datamodel.rst:3467 msgid "" "When using a class name in a pattern, positional arguments in the pattern " "are not allowed by default, i.e. ``case MyClass(x, y)`` is typically invalid " "without special support in ``MyClass``. To be able to use that kind of " "pattern, the class needs to define a *__match_args__* attribute." msgstr "" +"Ao usar um nome de classe em um padrão, argumentos posicionais não são " +"permitidos por padrão, ou seja, ``case MyClass(x, y)`` é tipicamente " +"inválida sem suporte especial em ``MyClass``. Para permitir a utilização " +"desse tipo de padrão, a classe precisa definir um atributo *__match_args__*" -#: ../../reference/datamodel.rst:3195 +#: ../../reference/datamodel.rst:3474 msgid "" "This class variable can be assigned a tuple of strings. When this class is " "used in a class pattern with positional arguments, each positional argument " @@ -4949,7 +5738,7 @@ msgstr "" "correspondência de valor em *__match_args__* como palavra reservada. A " "ausência desse atributo é equivalente a defini-lo como ``()``" -#: ../../reference/datamodel.rst:3201 +#: ../../reference/datamodel.rst:3480 msgid "" "For example, if ``MyClass.__match_args__`` is ``(\"left\", \"center\", " "\"right\")`` that means that ``case MyClass(x, y)`` is equivalent to ``case " @@ -4965,33 +5754,40 @@ msgstr "" "maior, a tentativa de correspondência de padrão irá levantar uma :exc:" "`TypeError`." -#: ../../reference/datamodel.rst:3211 +#: ../../reference/datamodel.rst:3490 msgid ":pep:`634` - Structural Pattern Matching" msgstr ":pep:`634` - Correspondência de Padrão Estrutural" -#: ../../reference/datamodel.rst:3212 +#: ../../reference/datamodel.rst:3491 msgid "The specification for the Python ``match`` statement." msgstr "A especificação para a instrução Python ``match``" -#: ../../reference/datamodel.rst:3218 +#: ../../reference/datamodel.rst:3497 msgid "Emulating buffer types" -msgstr "" +msgstr "Emulando tipos buffer" -#: ../../reference/datamodel.rst:3220 +#: ../../reference/datamodel.rst:3499 msgid "" "The :ref:`buffer protocol ` provides a way for Python objects " "to expose efficient access to a low-level memory array. This protocol is " "implemented by builtin types such as :class:`bytes` and :class:`memoryview`, " "and third-party libraries may define additional buffer types." msgstr "" +"O :ref:`protocolo buffer ` fornece uma maneira para objetos " +"Python exporem acesso eficiente a um vetor de memória de baixo nível. Este " +"protocolo é implementado por tipos embutido como :class:`bytes` e :class:" +"`memoryview`, e bibliotecas de terceiros podem definir tipos de buffer " +"adicionais." -#: ../../reference/datamodel.rst:3225 +#: ../../reference/datamodel.rst:3504 msgid "" "While buffer types are usually implemented in C, it is also possible to " "implement the protocol in Python." msgstr "" +"Embora os tipos buffer sejam geralmente implementados em C, também é " +"possível implementar o protocolo em Python." -#: ../../reference/datamodel.rst:3230 +#: ../../reference/datamodel.rst:3509 msgid "" "Called when a buffer is requested from *self* (for example, by the :class:" "`memoryview` constructor). The *flags* argument is an integer representing " @@ -5000,8 +5796,14 @@ msgid "" "convenient way to interpret the flags. The method must return a :class:" "`memoryview` object." msgstr "" +"Chamado quando um buffer é solicitado de *self* (por exemplo, pelo " +"construtor de :class:`memoryview`). O argumento *flags* é um inteiro que " +"representa o tipo de buffer solicitado, afetando, por exemplo, se o buffer " +"retornado é somente leitura ou gravável. :class:`inspect.BufferFlags` " +"fornece uma maneira conveniente de interpretar os sinalizadores. O método " +"deve retornar um objeto :class:`memoryview`." -#: ../../reference/datamodel.rst:3239 +#: ../../reference/datamodel.rst:3518 msgid "" "Called when a buffer is no longer needed. The *buffer* argument is a :class:" "`memoryview` object that was previously returned by :meth:`~object." @@ -5009,29 +5811,34 @@ msgid "" "buffer. This method should return ``None``. Buffer objects that do not need " "to perform any cleanup are not required to implement this method." msgstr "" +"Chamado quando um buffer não é mais necessário. O argumento *buffer* é um " +"objeto :class:`memoryview` que foi retornado anteriormente por :meth:" +"`~object.__buffer__`. O método deve liberar quaisquer recursos associados ao " +"buffer. Este método deve retornar ``None``. Objetos buffer que não precisam " +"executar nenhuma limpeza não são necessários para implementar este método." -#: ../../reference/datamodel.rst:3250 +#: ../../reference/datamodel.rst:3529 msgid ":pep:`688` - Making the buffer protocol accessible in Python" -msgstr "" +msgstr ":pep:`688` - Tornando o protocolo de buffer acessível no Python" -#: ../../reference/datamodel.rst:3251 +#: ../../reference/datamodel.rst:3530 msgid "" "Introduces the Python ``__buffer__`` and ``__release_buffer__`` methods." -msgstr "" +msgstr "Introduz os métodos ``__buffer__`` e ``__release_buffer__`` no Python" -#: ../../reference/datamodel.rst:3253 +#: ../../reference/datamodel.rst:3532 msgid ":class:`collections.abc.Buffer`" -msgstr "" +msgstr ":class:`collections.abc.Buffer`" -#: ../../reference/datamodel.rst:3254 +#: ../../reference/datamodel.rst:3533 msgid "ABC for buffer types." -msgstr "" +msgstr "ABC para tipos buffer." -#: ../../reference/datamodel.rst:3259 +#: ../../reference/datamodel.rst:3538 msgid "Special method lookup" msgstr "Pesquisa de método especial" -#: ../../reference/datamodel.rst:3261 +#: ../../reference/datamodel.rst:3540 msgid "" "For custom classes, implicit invocations of special methods are only " "guaranteed to work correctly if defined on an object's type, not in the " @@ -5043,7 +5850,29 @@ msgstr "" "não no dicionário de instância do objeto. Esse comportamento é o motivo pelo " "qual o código a seguir levanta uma exceção::" -#: ../../reference/datamodel.rst:3276 +#: ../../reference/datamodel.rst:3545 +msgid "" +">>> class C:\n" +"... pass\n" +"...\n" +">>> c = C()\n" +">>> c.__len__ = lambda: 5\n" +">>> len(c)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: object of type 'C' has no len()" +msgstr "" +">>> class C:\n" +"... pass\n" +"...\n" +">>> c = C()\n" +">>> c.__len__ = lambda: 5\n" +">>> len(c)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: object of type 'C' has no len()" + +#: ../../reference/datamodel.rst:3555 msgid "" "The rationale behind this behaviour lies with a number of special methods " "such as :meth:`~object.__hash__` and :meth:`~object.__repr__` that are " @@ -5051,8 +5880,29 @@ msgid "" "of these methods used the conventional lookup process, they would fail when " "invoked on the type object itself::" msgstr "" +"A justificativa por trás desse comportamento está em uma série de métodos " +"especiais como :meth:`~object.__hash__` e :meth:`~object.__repr__` que são " +"implementados por todos os objetos, incluindo objetos de tipo. Se a pesquisa " +"implícita desses métodos usasse o processo de pesquisa convencional, eles " +"falhariam quando invocados no próprio objeto do tipo::" + +#: ../../reference/datamodel.rst:3562 +msgid "" +">>> 1 .__hash__() == hash(1)\n" +"True\n" +">>> int.__hash__() == hash(int)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: descriptor '__hash__' of 'int' object needs an argument" +msgstr "" +">>> 1 .__hash__() == hash(1)\n" +"True\n" +">>> int.__hash__() == hash(int)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: descriptor '__hash__' of 'int' object needs an argument" -#: ../../reference/datamodel.rst:3290 +#: ../../reference/datamodel.rst:3569 msgid "" "Incorrectly attempting to invoke an unbound method of a class in this way is " "sometimes referred to as 'metaclass confusion', and is avoided by bypassing " @@ -5062,14 +5912,75 @@ msgstr "" "maneira é às vezes referida como \"confusão de metaclasse\" e é evitada " "ignorando a instância ao pesquisar métodos especiais::" -#: ../../reference/datamodel.rst:3299 +#: ../../reference/datamodel.rst:3573 +msgid "" +">>> type(1).__hash__(1) == hash(1)\n" +"True\n" +">>> type(int).__hash__(int) == hash(int)\n" +"True" +msgstr "" +">>> type(1).__hash__(1) == hash(1)\n" +"True\n" +">>> type(int).__hash__(int) == hash(int)\n" +"True" + +#: ../../reference/datamodel.rst:3578 msgid "" "In addition to bypassing any instance attributes in the interest of " "correctness, implicit special method lookup generally also bypasses the :" "meth:`~object.__getattribute__` method even of the object's metaclass::" msgstr "" - -#: ../../reference/datamodel.rst:3325 +"Além de contornar quaisquer atributos de instância no interesse da correção, " +"a pesquisa de método especial implícita geralmente também contorna o método :" +"meth:`~object.__getattribute__` mesmo da metaclasse do objeto::" + +#: ../../reference/datamodel.rst:3582 +msgid "" +">>> class Meta(type):\n" +"... def __getattribute__(*args):\n" +"... print(\"Metaclass getattribute invoked\")\n" +"... return type.__getattribute__(*args)\n" +"...\n" +">>> class C(object, metaclass=Meta):\n" +"... def __len__(self):\n" +"... return 10\n" +"... def __getattribute__(*args):\n" +"... print(\"Class getattribute invoked\")\n" +"... return object.__getattribute__(*args)\n" +"...\n" +">>> c = C()\n" +">>> c.__len__() # Explicit lookup via instance\n" +"Class getattribute invoked\n" +"10\n" +">>> type(c).__len__(c) # Explicit lookup via type\n" +"Metaclass getattribute invoked\n" +"10\n" +">>> len(c) # Implicit lookup\n" +"10" +msgstr "" +">>> class Meta(type):\n" +"... def __getattribute__(*args):\n" +"... print(\"Metaclass getattribute invoked\")\n" +"... return type.__getattribute__(*args)\n" +"...\n" +">>> class C(object, metaclass=Meta):\n" +"... def __len__(self):\n" +"... return 10\n" +"... def __getattribute__(*args):\n" +"... print(\"Class getattribute invoked\")\n" +"... return object.__getattribute__(*args)\n" +"...\n" +">>> c = C()\n" +">>> c.__len__() # Explicit lookup via instance\n" +"Class getattribute invoked\n" +"10\n" +">>> type(c).__len__(c) # Explicit lookup via type\n" +"Metaclass getattribute invoked\n" +"10\n" +">>> len(c) # Implicit lookup\n" +"10" + +#: ../../reference/datamodel.rst:3604 msgid "" "Bypassing the :meth:`~object.__getattribute__` machinery in this fashion " "provides significant scope for speed optimisations within the interpreter, " @@ -5077,56 +5988,73 @@ msgid "" "special method *must* be set on the class object itself in order to be " "consistently invoked by the interpreter)." msgstr "" +"Ignorar a maquinaria de :meth:`~object.__getattribute__` desta forma fornece " +"um escopo significativo para otimizações de velocidade dentro do " +"interpretador, ao custo de alguma flexibilidade no tratamento de métodos " +"especiais (o método especial *deve* ser definido no próprio objeto classe em " +"ordem ser invocado de forma consistente pelo interpretador)." -#: ../../reference/datamodel.rst:3336 +#: ../../reference/datamodel.rst:3615 msgid "Coroutines" msgstr "Corrotinas" -#: ../../reference/datamodel.rst:3340 +#: ../../reference/datamodel.rst:3619 msgid "Awaitable Objects" msgstr "Objetos aguardáveis" -#: ../../reference/datamodel.rst:3342 +#: ../../reference/datamodel.rst:3621 msgid "" "An :term:`awaitable` object generally implements an :meth:`~object." "__await__` method. :term:`Coroutine objects ` returned from :" "keyword:`async def` functions are awaitable." msgstr "" +"Um objeto :term:`aguardável` geralmente implementa um método :meth:`~object." +"__await__`. Os :term:`objetos corrotina ` retornados das funções :" +"keyword:`async def` são aguardáveis." -#: ../../reference/datamodel.rst:3348 +#: ../../reference/datamodel.rst:3627 msgid "" "The :term:`generator iterator` objects returned from generators decorated " "with :func:`types.coroutine` are also awaitable, but they do not implement :" "meth:`~object.__await__`." msgstr "" +"Os objetos :term:`iteradores geradores ` retornados de " +"geradores decorados com :func:`types.coroutine` também são aguardáveis, mas " +"eles não implementam :meth:`~object.__await__`." -#: ../../reference/datamodel.rst:3354 +#: ../../reference/datamodel.rst:3633 msgid "" "Must return an :term:`iterator`. Should be used to implement :term:" "`awaitable` objects. For instance, :class:`asyncio.Future` implements this " -"method to be compatible with the :keyword:`await` expression." +"method to be compatible with the :keyword:`await` expression. The :class:" +"`object` class itself is not awaitable and does not provide this method." msgstr "" "Deve retornar um :term:`iterador`. Deve ser usado para implementar objetos :" "term:`aguardáveis `. Por exemplo, :class:`asyncio.Future` " -"implementa este método para ser compatível com a expressão :keyword:`await`." +"implementa este método para ser compatível com a expressão :keyword:`await`. " +"A classe :class:`object` em si não é aguardável e não fornece este método." -#: ../../reference/datamodel.rst:3360 +#: ../../reference/datamodel.rst:3641 msgid "" "The language doesn't place any restriction on the type or value of the " "objects yielded by the iterator returned by ``__await__``, as this is " "specific to the implementation of the asynchronous execution framework (e." "g. :mod:`asyncio`) that will be managing the :term:`awaitable` object." msgstr "" +"A linguagem não impõe nenhuma restrição ao tipo ou valor dos objetos " +"produzidos pelo iterador retornado por ``__await__``, pois isso é específico " +"para a implementação da estrutura de execução assíncrona (por exemplo, :mod:" +"`asyncio`) que gerenciará o objeto :term:`awaitable`." -#: ../../reference/datamodel.rst:3368 +#: ../../reference/datamodel.rst:3649 msgid ":pep:`492` for additional information about awaitable objects." msgstr ":pep:`492` para informações adicionais sobre objetos aguardáveis." -#: ../../reference/datamodel.rst:3374 +#: ../../reference/datamodel.rst:3655 msgid "Coroutine Objects" msgstr "Objetos corrotina" -#: ../../reference/datamodel.rst:3376 +#: ../../reference/datamodel.rst:3657 msgid "" ":term:`Coroutine objects ` are :term:`awaitable` objects. A " "coroutine's execution can be controlled by calling :meth:`~object.__await__` " @@ -5136,8 +6064,16 @@ msgid "" "coroutine raises an exception, it is propagated by the iterator. Coroutines " "should not directly raise unhandled :exc:`StopIteration` exceptions." msgstr "" +":term:`Objetos corrotina ` são objetos :term:`aguardáveis " +"`. A execução de uma corrotina pode ser controlada chamando :" +"meth:`~object.__await__` e iterando sobre o resultado. Quando a corrotina " +"termina a execução e retorna, o iterador levanta :exc:`StopIteration`, e o " +"atributo :attr:`~StopIteration.value` da exceção contém o valor de retorno. " +"Se a corrotina levantar uma exceção, ela será propagada pelo iterador. As " +"corrotinas não devem levantar exceções :exc:`StopIteration` diretamente não " +"tratadas." -#: ../../reference/datamodel.rst:3384 +#: ../../reference/datamodel.rst:3665 msgid "" "Coroutines also have the methods listed below, which are analogous to those " "of generators (see :ref:`generator-methods`). However, unlike generators, " @@ -5147,11 +6083,11 @@ msgstr "" "dos geradores (ver :ref:`generator-methods`). No entanto, ao contrário dos " "geradores, as corrotinas não suportam diretamente a iteração." -#: ../../reference/datamodel.rst:3388 +#: ../../reference/datamodel.rst:3669 msgid "It is a :exc:`RuntimeError` to await on a coroutine more than once." msgstr "É uma :exc:`RuntimeError` para aguardar uma corrotina mais de uma vez." -#: ../../reference/datamodel.rst:3394 +#: ../../reference/datamodel.rst:3675 msgid "" "Starts or resumes execution of the coroutine. If *value* is ``None``, this " "is equivalent to advancing the iterator returned by :meth:`~object." @@ -5161,8 +6097,14 @@ msgid "" "exception) is the same as when iterating over the :meth:`!__await__` return " "value, described above." msgstr "" +"Inicia ou retoma a execução da corrotina. Se *value* for ``None``, isso " +"equivale a avançar o iterador retornado por :meth:`~object.__await__`. Se " +"*value* não for ``None``, este método delega para o método :meth:`~generator." +"send` do iterador que causou a suspensão da corrotina. O resultado (valor de " +"retorno, :exc:`StopIteration` ou outra exceção) é o mesmo de iterar sobre o " +"valor de retorno :meth:`!__await__`, descrito acima." -#: ../../reference/datamodel.rst:3405 +#: ../../reference/datamodel.rst:3686 msgid "" "Raises the specified exception in the coroutine. This method delegates to " "the :meth:`~generator.throw` method of the iterator that caused the " @@ -5172,16 +6114,23 @@ msgid "" "meth:`~object.__await__` return value, described above. If the exception is " "not caught in the coroutine, it propagates back to the caller." msgstr "" +"Levanta a exceção especificada na corrotina. Este método delega ao método :" +"meth:`~generator.throw` do iterador que causou a suspensão da corrotina, se " +"ela tiver tal método. Caso contrário, a exceção é levantada no ponto de " +"suspensão. O resultado (valor de retorno, :exc:`StopIteration` ou outra " +"exceção) é o mesmo de iterar sobre o valor de retorno :meth:`~object." +"__await__`, descrito acima. Se a exceção não for capturada na corrotina, ela " +"se propagará de volta para o chamador." -#: ../../reference/datamodel.rst:3416 +#: ../../reference/datamodel.rst:3697 msgid "" "The second signature \\(type\\[, value\\[, traceback\\]\\]\\) is deprecated " "and may be removed in a future version of Python." msgstr "" -"A segunda assinatura \\(tipo\\[, valor\\[, traceback\\]\\]\\]\\) foi " +"A segunda assinatura \\(tipo\\[, valor\\[, traceback\\]\\]\\) foi " "descontinuada e pode ser removida em uma versão futura do Python." -#: ../../reference/datamodel.rst:3421 +#: ../../reference/datamodel.rst:3702 msgid "" "Causes the coroutine to clean itself up and exit. If the coroutine is " "suspended, this method first delegates to the :meth:`~generator.close` " @@ -5197,7 +6146,7 @@ msgstr "" "limpe imediatamente. Por fim, a corrotina é marcada como tendo sua execução " "concluída, mesmo que nunca tenha sido iniciada." -#: ../../reference/datamodel.rst:3429 +#: ../../reference/datamodel.rst:3710 msgid "" "Coroutine objects are automatically closed using the above process when they " "are about to be destroyed." @@ -5205,11 +6154,11 @@ msgstr "" "Objetos corrotina são fechados automaticamente usando o processo acima " "quando estão prestes a ser destruídos." -#: ../../reference/datamodel.rst:3435 +#: ../../reference/datamodel.rst:3716 msgid "Asynchronous Iterators" msgstr "Iteradores assíncronos" -#: ../../reference/datamodel.rst:3437 +#: ../../reference/datamodel.rst:3718 msgid "" "An *asynchronous iterator* can call asynchronous code in its ``__anext__`` " "method." @@ -5217,18 +6166,22 @@ msgstr "" "Um *iterador assíncrono* pode chamar código assíncrono em seu método " "``__anext__``." -#: ../../reference/datamodel.rst:3440 +#: ../../reference/datamodel.rst:3721 msgid "" "Asynchronous iterators can be used in an :keyword:`async for` statement." msgstr "" -"Os iteradores assíncronos podem ser usados ​​em uma instrução :keyword:`async " +"Os iteradores assíncronos podem ser usados em uma instrução :keyword:`async " "for`." -#: ../../reference/datamodel.rst:3444 +#: ../../reference/datamodel.rst:3723 ../../reference/datamodel.rst:3772 +msgid "The :class:`object` class itself does not provide these methods." +msgstr "A classe :class:`object` em si não fornece estes métodos." + +#: ../../reference/datamodel.rst:3728 msgid "Must return an *asynchronous iterator* object." msgstr "Deve retornar um objeto *iterador assíncrono*." -#: ../../reference/datamodel.rst:3448 +#: ../../reference/datamodel.rst:3732 msgid "" "Must return an *awaitable* resulting in a next value of the iterator. " "Should raise a :exc:`StopAsyncIteration` error when the iteration is over." @@ -5236,29 +6189,63 @@ msgstr "" "Deve retornar um *aguardável* resultando em um próximo valor do iterador. " "Deve levantar um erro :exc:`StopAsyncIteration` quando a iteração terminar." -#: ../../reference/datamodel.rst:3451 +#: ../../reference/datamodel.rst:3735 msgid "An example of an asynchronous iterable object::" msgstr "Um exemplo de objeto iterável assíncrono::" -#: ../../reference/datamodel.rst:3468 +#: ../../reference/datamodel.rst:3737 +msgid "" +"class Reader:\n" +" async def readline(self):\n" +" ...\n" +"\n" +" def __aiter__(self):\n" +" return self\n" +"\n" +" async def __anext__(self):\n" +" val = await self.readline()\n" +" if val == b'':\n" +" raise StopAsyncIteration\n" +" return val" +msgstr "" +"class Reader:\n" +" async def readline(self):\n" +" ...\n" +"\n" +" def __aiter__(self):\n" +" return self\n" +"\n" +" async def __anext__(self):\n" +" val = await self.readline()\n" +" if val == b'':\n" +" raise StopAsyncIteration\n" +" return val" + +#: ../../reference/datamodel.rst:3752 msgid "" "Prior to Python 3.7, :meth:`~object.__aiter__` could return an *awaitable* " "that would resolve to an :term:`asynchronous iterator `." msgstr "" +"Antes do Python 3.7, :meth:`~object.__aiter__` poderia retornar um " +"*aguardável* que resolveria para um :term:`iterador assíncrono `." -#: ../../reference/datamodel.rst:3473 +#: ../../reference/datamodel.rst:3757 msgid "" "Starting with Python 3.7, :meth:`~object.__aiter__` must return an " "asynchronous iterator object. Returning anything else will result in a :exc:" "`TypeError` error." msgstr "" +"A partir do Python 3.7, :meth:`~object.__aiter__` deve retornar um objeto " +"iterador assíncrono. Retornar qualquer outra coisa resultará em um erro :exc:" +"`TypeError`." -#: ../../reference/datamodel.rst:3481 +#: ../../reference/datamodel.rst:3765 msgid "Asynchronous Context Managers" msgstr "Gerenciadores de contexto assíncronos" -#: ../../reference/datamodel.rst:3483 +#: ../../reference/datamodel.rst:3767 msgid "" "An *asynchronous context manager* is a *context manager* that is able to " "suspend execution in its ``__aenter__`` and ``__aexit__`` methods." @@ -5266,35 +6253,55 @@ msgstr "" "Um *gerenciador de contexto assíncrono* é um *gerenciador de contexto* que é " "capaz de suspender a execução em seus métodos ``__aenter__`` e ``__aexit__``." -#: ../../reference/datamodel.rst:3486 +#: ../../reference/datamodel.rst:3770 msgid "" "Asynchronous context managers can be used in an :keyword:`async with` " "statement." msgstr "" -"Os gerenciadores de contexto assíncronos podem ser usados ​​em uma instrução :" +"Os gerenciadores de contexto assíncronos podem ser usados em uma instrução :" "keyword:`async with`." -#: ../../reference/datamodel.rst:3490 +#: ../../reference/datamodel.rst:3776 msgid "" "Semantically similar to :meth:`~object.__enter__`, the only difference being " "that it must return an *awaitable*." msgstr "" +"Semanticamente semelhante a :meth:`~object.__enter__`, a única diferença é " +"que ele deve retornar um *aguardável*." -#: ../../reference/datamodel.rst:3495 +#: ../../reference/datamodel.rst:3781 msgid "" "Semantically similar to :meth:`~object.__exit__`, the only difference being " "that it must return an *awaitable*." msgstr "" +"Semanticamente semelhante a :meth:`~object.__exit__`, a única diferença é " +"que ele deve retornar um *aguardável*." -#: ../../reference/datamodel.rst:3498 +#: ../../reference/datamodel.rst:3784 msgid "An example of an asynchronous context manager class::" msgstr "Um exemplo de uma classe gerenciadora de contexto assíncrona::" -#: ../../reference/datamodel.rst:3511 +#: ../../reference/datamodel.rst:3786 +msgid "" +"class AsyncContextManager:\n" +" async def __aenter__(self):\n" +" await log('entering context')\n" +"\n" +" async def __aexit__(self, exc_type, exc, tb):\n" +" await log('exiting context')" +msgstr "" +"class AsyncContextManager:\n" +" async def __aenter__(self):\n" +" await log('entrando no contexto')\n" +"\n" +" async def __aexit__(self, exc_type, exc, tb):\n" +" await log('saindo do contexto')" + +#: ../../reference/datamodel.rst:3797 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../reference/datamodel.rst:3512 +#: ../../reference/datamodel.rst:3798 msgid "" "It *is* possible in some cases to change an object's type, under certain " "controlled conditions. It generally isn't a good idea though, since it can " @@ -5304,7 +6311,7 @@ msgstr "" "condições controladas. No entanto, geralmente não é uma boa ideia, pois pode " "levar a um comportamento muito estranho se for tratado incorretamente." -#: ../../reference/datamodel.rst:3516 +#: ../../reference/datamodel.rst:3802 msgid "" "The :meth:`~object.__hash__`, :meth:`~object.__iter__`, :meth:`~object." "__reversed__`, :meth:`~object.__contains__`, :meth:`~object." @@ -5312,21 +6319,33 @@ msgid "" "handling for this. Others will still raise a :exc:`TypeError`, but may do so " "by relying on the behavior that ``None`` is not callable." msgstr "" +"Os métodos :meth:`~object.__hash__`, :meth:`~object.__iter__`, :meth:" +"`~object.__reversed__` e :meth:`~object.__contains__`, :meth:`~object." +"__class_getitem__` e :meth:`~os.PathLike.__fspath__` têm um tratamento " +"especial para isso. Outros ainda irão levantar um :exc:`TypeError`, mas " +"podem fazer isso contando com o comportamento de que ``None`` não é chamável." -#: ../../reference/datamodel.rst:3523 +#: ../../reference/datamodel.rst:3809 msgid "" "\"Does not support\" here means that the class has no such method, or the " "method returns :data:`NotImplemented`. Do not set the method to ``None`` if " "you want to force fallback to the right operand's reflected method—that will " "instead have the opposite effect of explicitly *blocking* such fallback." msgstr "" +"\"Não suportar\" aqui significa que a classe não possui tal método, ou o " +"método retorna :data:`NotImplemented`. Não defina o método como ``None`` se " +"quiser forçar o fallback para o método refletido do operando correto -- isso " +"terá o efeito oposto de *bloquear* explicitamente esse fallback." -#: ../../reference/datamodel.rst:3529 +#: ../../reference/datamodel.rst:3815 msgid "" "For operands of the same type, it is assumed that if the non-reflected " "method -- such as :meth:`~object.__add__` -- fails then the overall " "operation is not supported, which is why the reflected method is not called." msgstr "" +"Para operandos do mesmo tipo, presume-se que se o método não refletido -- " +"como :meth:`~object.__add__` -- falhar, a operação geral não será suportada, " +"razão pela qual o método refletido não é chamado." #: ../../reference/datamodel.rst:14 ../../reference/datamodel.rst:152 #: ../../reference/datamodel.rst:163 ../../reference/datamodel.rst:184 @@ -5340,11 +6359,11 @@ msgstr "" #: ../../reference/datamodel.rst:483 ../../reference/datamodel.rst:519 #: ../../reference/datamodel.rst:534 ../../reference/datamodel.rst:661 #: ../../reference/datamodel.rst:799 ../../reference/datamodel.rst:823 -#: ../../reference/datamodel.rst:856 ../../reference/datamodel.rst:935 -#: ../../reference/datamodel.rst:1013 ../../reference/datamodel.rst:1040 -#: ../../reference/datamodel.rst:1102 ../../reference/datamodel.rst:1206 -#: ../../reference/datamodel.rst:1315 ../../reference/datamodel.rst:1425 -#: ../../reference/datamodel.rst:1839 ../../reference/datamodel.rst:2854 +#: ../../reference/datamodel.rst:859 ../../reference/datamodel.rst:1126 +#: ../../reference/datamodel.rst:1265 ../../reference/datamodel.rst:1292 +#: ../../reference/datamodel.rst:1364 ../../reference/datamodel.rst:1472 +#: ../../reference/datamodel.rst:1579 ../../reference/datamodel.rst:1689 +#: ../../reference/datamodel.rst:2114 ../../reference/datamodel.rst:3132 msgid "object" msgstr "objeto" @@ -5355,13 +6374,13 @@ msgstr "dados" #: ../../reference/datamodel.rst:23 ../../reference/datamodel.rst:296 #: ../../reference/datamodel.rst:343 ../../reference/datamodel.rst:427 #: ../../reference/datamodel.rst:466 ../../reference/datamodel.rst:799 -#: ../../reference/datamodel.rst:1059 ../../reference/datamodel.rst:1508 -#: ../../reference/datamodel.rst:1750 ../../reference/datamodel.rst:1755 -#: ../../reference/datamodel.rst:1839 ../../reference/datamodel.rst:2395 -#: ../../reference/datamodel.rst:2824 ../../reference/datamodel.rst:2982 -#: ../../reference/datamodel.rst:3017 ../../reference/datamodel.rst:3031 -#: ../../reference/datamodel.rst:3080 ../../reference/datamodel.rst:3090 -#: ../../reference/datamodel.rst:3118 +#: ../../reference/datamodel.rst:1321 ../../reference/datamodel.rst:1772 +#: ../../reference/datamodel.rst:2015 ../../reference/datamodel.rst:2021 +#: ../../reference/datamodel.rst:2114 ../../reference/datamodel.rst:2671 +#: ../../reference/datamodel.rst:3102 ../../reference/datamodel.rst:3260 +#: ../../reference/datamodel.rst:3295 ../../reference/datamodel.rst:3309 +#: ../../reference/datamodel.rst:3358 ../../reference/datamodel.rst:3368 +#: ../../reference/datamodel.rst:3396 msgid "built-in function" msgstr "função embutida" @@ -5370,29 +6389,29 @@ msgid "id" msgstr "id" #: ../../reference/datamodel.rst:23 ../../reference/datamodel.rst:126 -#: ../../reference/datamodel.rst:2395 +#: ../../reference/datamodel.rst:2671 msgid "type" msgstr "tipo" #: ../../reference/datamodel.rst:23 msgid "identity of an object" -msgstr "" +msgstr "identidade de um objeto" #: ../../reference/datamodel.rst:23 msgid "value of an object" -msgstr "" +msgstr "valor de um objeto" #: ../../reference/datamodel.rst:23 msgid "type of an object" -msgstr "" +msgstr "tipo de um objeto" #: ../../reference/datamodel.rst:23 msgid "mutable object" -msgstr "" +msgstr "objeto mutável" #: ../../reference/datamodel.rst:23 msgid "immutable object" -msgstr "" +msgstr "objeto imutável" #: ../../reference/datamodel.rst:60 msgid "garbage collection" @@ -5400,28 +6419,28 @@ msgstr "coleta de lixo" #: ../../reference/datamodel.rst:60 msgid "reference counting" -msgstr "" +msgstr "contagem de referências" #: ../../reference/datamodel.rst:60 msgid "unreachable object" -msgstr "" +msgstr "objeto inalcançável" -#: ../../reference/datamodel.rst:95 ../../reference/datamodel.rst:935 +#: ../../reference/datamodel.rst:95 ../../reference/datamodel.rst:1126 msgid "container" msgstr "contêiner" #: ../../reference/datamodel.rst:126 msgid "hierarchy" -msgstr "" +msgstr "hierarquia" #: ../../reference/datamodel.rst:126 msgid "extension" -msgstr "" +msgstr "extensão" #: ../../reference/datamodel.rst:126 ../../reference/datamodel.rst:400 #: ../../reference/datamodel.rst:401 ../../reference/datamodel.rst:502 -#: ../../reference/datamodel.rst:856 ../../reference/datamodel.rst:876 -#: ../../reference/datamodel.rst:1059 +#: ../../reference/datamodel.rst:859 ../../reference/datamodel.rst:879 +#: ../../reference/datamodel.rst:1321 msgid "module" msgstr "módulo" @@ -5435,9 +6454,9 @@ msgstr "C" msgid "language" msgstr "linguagem" -#: ../../reference/datamodel.rst:139 ../../reference/datamodel.rst:935 -#: ../../reference/datamodel.rst:953 ../../reference/datamodel.rst:1013 -#: ../../reference/datamodel.rst:1033 +#: ../../reference/datamodel.rst:139 ../../reference/datamodel.rst:1126 +#: ../../reference/datamodel.rst:1144 ../../reference/datamodel.rst:1265 +#: ../../reference/datamodel.rst:1285 msgid "attribute" msgstr "atributo" @@ -5447,7 +6466,7 @@ msgstr "especial" #: ../../reference/datamodel.rst:139 msgid "generic" -msgstr "" +msgstr "genérico" #: ../../reference/datamodel.rst:184 msgid "..." @@ -5457,7 +6476,7 @@ msgstr "..." msgid "ellipsis literal" msgstr "reticências literais" -#: ../../reference/datamodel.rst:196 ../../reference/datamodel.rst:1040 +#: ../../reference/datamodel.rst:196 ../../reference/datamodel.rst:1292 msgid "numeric" msgstr "numérico" @@ -5468,7 +6487,7 @@ msgstr "inteiro" #: ../../reference/datamodel.rst:235 msgid "representation" -msgstr "" +msgstr "representação" #: ../../reference/datamodel.rst:250 msgid "Boolean" @@ -5488,32 +6507,32 @@ msgstr "ponto flutuante" #: ../../reference/datamodel.rst:265 ../../reference/datamodel.rst:283 msgid "number" -msgstr "number" +msgstr "número" #: ../../reference/datamodel.rst:265 msgid "Java" -msgstr "" +msgstr "Java" -#: ../../reference/datamodel.rst:283 ../../reference/datamodel.rst:3090 +#: ../../reference/datamodel.rst:283 ../../reference/datamodel.rst:3368 msgid "complex" msgstr "complexo" #: ../../reference/datamodel.rst:296 ../../reference/datamodel.rst:427 -#: ../../reference/datamodel.rst:466 ../../reference/datamodel.rst:2824 +#: ../../reference/datamodel.rst:466 ../../reference/datamodel.rst:3102 msgid "len" msgstr "len" -#: ../../reference/datamodel.rst:296 ../../reference/datamodel.rst:1040 +#: ../../reference/datamodel.rst:296 ../../reference/datamodel.rst:1292 msgid "sequence" msgstr "sequência" #: ../../reference/datamodel.rst:296 msgid "index operation" -msgstr "" +msgstr "operação com índice" #: ../../reference/datamodel.rst:296 msgid "item selection" -msgstr "" +msgstr "seleção item" #: ../../reference/datamodel.rst:296 ../../reference/datamodel.rst:388 #: ../../reference/datamodel.rst:466 @@ -5526,28 +6545,28 @@ msgstr "fatiamento" #: ../../reference/datamodel.rst:328 msgid "immutable sequence" -msgstr "" +msgstr "sequência imutável" #: ../../reference/datamodel.rst:328 msgid "immutable" msgstr "imutável" -#: ../../reference/datamodel.rst:339 ../../reference/datamodel.rst:1725 -#: ../../reference/datamodel.rst:1755 +#: ../../reference/datamodel.rst:339 ../../reference/datamodel.rst:1990 +#: ../../reference/datamodel.rst:2021 msgid "string" msgstr "string" #: ../../reference/datamodel.rst:339 msgid "immutable sequences" -msgstr "" +msgstr "sequências imutáveis" #: ../../reference/datamodel.rst:343 msgid "chr" -msgstr "" +msgstr "chr" #: ../../reference/datamodel.rst:343 msgid "ord" -msgstr "" +msgstr "ord" #: ../../reference/datamodel.rst:343 msgid "character" @@ -5563,19 +6582,19 @@ msgstr "tupla" #: ../../reference/datamodel.rst:363 msgid "singleton" -msgstr "" +msgstr "Singleton" #: ../../reference/datamodel.rst:363 msgid "empty" -msgstr "vazio" +msgstr "vazia" -#: ../../reference/datamodel.rst:376 ../../reference/datamodel.rst:1750 +#: ../../reference/datamodel.rst:376 ../../reference/datamodel.rst:2015 msgid "bytes" msgstr "bytes" #: ../../reference/datamodel.rst:376 msgid "byte" -msgstr "" +msgstr "byte" #: ../../reference/datamodel.rst:388 msgid "mutable sequence" @@ -5585,14 +6604,14 @@ msgstr "sequência mutável" msgid "mutable" msgstr "mutável" -#: ../../reference/datamodel.rst:388 ../../reference/datamodel.rst:953 -#: ../../reference/datamodel.rst:1033 +#: ../../reference/datamodel.rst:388 ../../reference/datamodel.rst:1144 +#: ../../reference/datamodel.rst:1285 msgid "assignment" msgstr "atribuição" -#: ../../reference/datamodel.rst:388 ../../reference/datamodel.rst:856 -#: ../../reference/datamodel.rst:1462 ../../reference/datamodel.rst:1644 -#: ../../reference/datamodel.rst:3145 +#: ../../reference/datamodel.rst:388 ../../reference/datamodel.rst:859 +#: ../../reference/datamodel.rst:1726 ../../reference/datamodel.rst:1908 +#: ../../reference/datamodel.rst:3423 msgid "statement" msgstr "instrução" @@ -5614,7 +6633,7 @@ msgstr "bytearray" #: ../../reference/datamodel.rst:427 msgid "set type" -msgstr "" +msgstr "tipo conjunto" #: ../../reference/datamodel.rst:447 msgid "set" @@ -5624,22 +6643,22 @@ msgstr "set" msgid "frozenset" msgstr "frozenset" -#: ../../reference/datamodel.rst:466 ../../reference/datamodel.rst:1040 +#: ../../reference/datamodel.rst:466 ../../reference/datamodel.rst:1292 msgid "mapping" msgstr "mapeamento" -#: ../../reference/datamodel.rst:483 ../../reference/datamodel.rst:935 -#: ../../reference/datamodel.rst:1839 +#: ../../reference/datamodel.rst:483 ../../reference/datamodel.rst:1126 +#: ../../reference/datamodel.rst:2114 msgid "dictionary" msgstr "dicionário" #: ../../reference/datamodel.rst:502 msgid "dbm.ndbm" -msgstr "" +msgstr "dbm.ndbm" #: ../../reference/datamodel.rst:502 msgid "dbm.gnu" -msgstr "" +msgstr "dbm.gnu" #: ../../reference/datamodel.rst:519 msgid "callable" @@ -5651,14 +6670,14 @@ msgstr "chamável" msgid "function" msgstr "função" -#: ../../reference/datamodel.rst:519 ../../reference/datamodel.rst:935 -#: ../../reference/datamodel.rst:958 ../../reference/datamodel.rst:2776 +#: ../../reference/datamodel.rst:519 ../../reference/datamodel.rst:1126 +#: ../../reference/datamodel.rst:1149 ../../reference/datamodel.rst:3052 msgid "call" msgstr "chamada" #: ../../reference/datamodel.rst:519 msgid "invocation" -msgstr "" +msgstr "invocação" #: ../../reference/datamodel.rst:519 msgid "argument" @@ -5678,51 +6697,51 @@ msgstr "__closure__ (atributo de função)" #: ../../reference/datamodel.rst:547 msgid "__globals__ (function attribute)" -msgstr "" +msgstr "__globals__ (atributo de função)" #: ../../reference/datamodel.rst:547 msgid "global" msgstr "global" -#: ../../reference/datamodel.rst:547 ../../reference/datamodel.rst:876 +#: ../../reference/datamodel.rst:547 ../../reference/datamodel.rst:879 msgid "namespace" msgstr "espaço de nomes" -#: ../../reference/datamodel.rst:573 +#: ../../reference/datamodel.rst:574 msgid "__doc__ (function attribute)" -msgstr "" +msgstr "__doc__ (atributo de função)" -#: ../../reference/datamodel.rst:573 +#: ../../reference/datamodel.rst:574 msgid "__name__ (function attribute)" -msgstr "" +msgstr "__name__ (atributo de função)" -#: ../../reference/datamodel.rst:573 +#: ../../reference/datamodel.rst:574 msgid "__module__ (function attribute)" -msgstr "" +msgstr "__module__ (atributo de função)" -#: ../../reference/datamodel.rst:573 +#: ../../reference/datamodel.rst:574 msgid "__dict__ (function attribute)" -msgstr "" +msgstr "__dict__ (atributo de função)" -#: ../../reference/datamodel.rst:573 +#: ../../reference/datamodel.rst:574 msgid "__defaults__ (function attribute)" -msgstr "" +msgstr "__defaults__ (atributo de função)" -#: ../../reference/datamodel.rst:573 +#: ../../reference/datamodel.rst:574 msgid "__code__ (function attribute)" -msgstr "" +msgstr "__code__ (atributo de função)" -#: ../../reference/datamodel.rst:573 +#: ../../reference/datamodel.rst:574 msgid "__annotations__ (function attribute)" -msgstr "" +msgstr "__annotations__ (atributo de função)" -#: ../../reference/datamodel.rst:573 +#: ../../reference/datamodel.rst:574 msgid "__kwdefaults__ (function attribute)" -msgstr "" +msgstr "__kwdefaults__ (atributo de função)" -#: ../../reference/datamodel.rst:573 +#: ../../reference/datamodel.rst:574 msgid "__type_params__ (function attribute)" -msgstr "" +msgstr "__type_params__ (atributo de função)" #: ../../reference/datamodel.rst:661 ../../reference/datamodel.rst:823 msgid "method" @@ -5730,29 +6749,29 @@ msgstr "método" #: ../../reference/datamodel.rst:661 msgid "user-defined method" -msgstr "" +msgstr "método definido por usuário" #: ../../reference/datamodel.rst:669 msgid "__func__ (method attribute)" -msgstr "" +msgstr "__func__ (atributo de método)" #: ../../reference/datamodel.rst:669 msgid "__self__ (method attribute)" -msgstr "" +msgstr "__self__ (atributo de método)" #: ../../reference/datamodel.rst:669 msgid "__doc__ (method attribute)" -msgstr "" +msgstr "__doc__ (atributo de método)" #: ../../reference/datamodel.rst:669 msgid "__name__ (method attribute)" -msgstr "" +msgstr "__name__ (atributo de método)" #: ../../reference/datamodel.rst:669 msgid "__module__ (method attribute)" -msgstr "" +msgstr "__module__ (atributo de método)" -#: ../../reference/datamodel.rst:743 ../../reference/datamodel.rst:1206 +#: ../../reference/datamodel.rst:743 ../../reference/datamodel.rst:1472 msgid "generator" msgstr "gerador" @@ -5760,7 +6779,7 @@ msgstr "gerador" msgid "iterator" msgstr "iterador" -#: ../../reference/datamodel.rst:761 ../../reference/datamodel.rst:3332 +#: ../../reference/datamodel.rst:761 ../../reference/datamodel.rst:3611 msgid "coroutine" msgstr "corrotina" @@ -5780,511 +6799,531 @@ msgstr "método embutido" msgid "built-in" msgstr "embutido" -#: ../../reference/datamodel.rst:856 +#: ../../reference/datamodel.rst:859 msgid "import" -msgstr "importação" +msgstr "import" -#: ../../reference/datamodel.rst:876 +#: ../../reference/datamodel.rst:879 msgid "__name__ (module attribute)" -msgstr "" +msgstr "__name__ (atributo de módulo)" -#: ../../reference/datamodel.rst:876 -msgid "__doc__ (module attribute)" -msgstr "" +#: ../../reference/datamodel.rst:879 +msgid "__spec__ (module attribute)" +msgstr "__spec__ (atributo de módulo)" -#: ../../reference/datamodel.rst:876 +#: ../../reference/datamodel.rst:879 +msgid "__package__ (module attribute)" +msgstr "__package__ (atributo de módulo)" + +#: ../../reference/datamodel.rst:879 +msgid "__loader__ (module attribute)" +msgstr "__loader__ (atributo de módulo)" + +#: ../../reference/datamodel.rst:879 +msgid "__path__ (module attribute)" +msgstr "__path__ (atributo de módulo)" + +#: ../../reference/datamodel.rst:879 msgid "__file__ (module attribute)" -msgstr "" +msgstr "__file__ (atributo de módulo)" -#: ../../reference/datamodel.rst:876 +#: ../../reference/datamodel.rst:879 +msgid "__cached__ (module attribute)" +msgstr "__cached__ (atributo de módulo)" + +#: ../../reference/datamodel.rst:879 +msgid "__doc__ (module attribute)" +msgstr "__doc__ (atributo de módulo)" + +#: ../../reference/datamodel.rst:879 msgid "__annotations__ (module attribute)" -msgstr "" +msgstr "__annotations__ (atributo de módulo)" -#: ../../reference/datamodel.rst:907 +#: ../../reference/datamodel.rst:1094 msgid "__dict__ (module attribute)" -msgstr "" +msgstr "__dict__ (atributo de módulo)" -#: ../../reference/datamodel.rst:935 ../../reference/datamodel.rst:953 -#: ../../reference/datamodel.rst:1013 ../../reference/datamodel.rst:1627 -#: ../../reference/datamodel.rst:2506 +#: ../../reference/datamodel.rst:1126 ../../reference/datamodel.rst:1144 +#: ../../reference/datamodel.rst:1265 ../../reference/datamodel.rst:1891 +#: ../../reference/datamodel.rst:2782 msgid "class" msgstr "classe" -#: ../../reference/datamodel.rst:935 ../../reference/datamodel.rst:1013 -#: ../../reference/datamodel.rst:1033 +#: ../../reference/datamodel.rst:1126 ../../reference/datamodel.rst:1265 +#: ../../reference/datamodel.rst:1285 msgid "class instance" msgstr "instância de classe" -#: ../../reference/datamodel.rst:935 ../../reference/datamodel.rst:1013 -#: ../../reference/datamodel.rst:2776 +#: ../../reference/datamodel.rst:1126 ../../reference/datamodel.rst:1265 +#: ../../reference/datamodel.rst:3052 msgid "instance" msgstr "instância" -#: ../../reference/datamodel.rst:935 ../../reference/datamodel.rst:958 +#: ../../reference/datamodel.rst:1126 ../../reference/datamodel.rst:1149 msgid "class object" msgstr "objeto classe" -#: ../../reference/datamodel.rst:962 +#: ../../reference/datamodel.rst:1156 msgid "__name__ (class attribute)" -msgstr "" +msgstr "__name__ (atributo de classe)" -#: ../../reference/datamodel.rst:962 +#: ../../reference/datamodel.rst:1156 msgid "__module__ (class attribute)" -msgstr "" +msgstr "__module__ (atributo de classe)" -#: ../../reference/datamodel.rst:962 +#: ../../reference/datamodel.rst:1156 msgid "__dict__ (class attribute)" -msgstr "" +msgstr "__dict__ (atributo de classe)" -#: ../../reference/datamodel.rst:962 +#: ../../reference/datamodel.rst:1156 msgid "__bases__ (class attribute)" -msgstr "" +msgstr "__bases__ (atributo de classe)" -#: ../../reference/datamodel.rst:962 +#: ../../reference/datamodel.rst:1156 msgid "__doc__ (class attribute)" -msgstr "" +msgstr "__doc__ (atributo de classe)" -#: ../../reference/datamodel.rst:962 +#: ../../reference/datamodel.rst:1156 msgid "__annotations__ (class attribute)" -msgstr "" +msgstr "__annotations__ (atributo de classe)" -#: ../../reference/datamodel.rst:962 +#: ../../reference/datamodel.rst:1156 msgid "__type_params__ (class attribute)" -msgstr "" +msgstr "__type_params__ (atributo de classe)" -#: ../../reference/datamodel.rst:962 +#: ../../reference/datamodel.rst:1156 msgid "__static_attributes__ (class attribute)" -msgstr "" +msgstr "__static_attributes__ (atributo de classe)" -#: ../../reference/datamodel.rst:962 +#: ../../reference/datamodel.rst:1156 msgid "__firstlineno__ (class attribute)" -msgstr "" +msgstr "__firstlineno__ (atributo de classe)" -#: ../../reference/datamodel.rst:1048 +#: ../../reference/datamodel.rst:1303 msgid "__dict__ (instance attribute)" -msgstr "" +msgstr "__dict__ (atributo de instância)" -#: ../../reference/datamodel.rst:1048 +#: ../../reference/datamodel.rst:1303 msgid "__class__ (instance attribute)" -msgstr "" +msgstr "__class__ (atributo de instância)" -#: ../../reference/datamodel.rst:1059 +#: ../../reference/datamodel.rst:1321 msgid "open" msgstr "open" -#: ../../reference/datamodel.rst:1059 +#: ../../reference/datamodel.rst:1321 msgid "io" msgstr "io" -#: ../../reference/datamodel.rst:1059 +#: ../../reference/datamodel.rst:1321 msgid "popen() (in module os)" -msgstr "" +msgstr "popen() (no módulo os)" -#: ../../reference/datamodel.rst:1059 +#: ../../reference/datamodel.rst:1321 msgid "makefile() (socket method)" -msgstr "" +msgstr "makefile() (método de socket)" -#: ../../reference/datamodel.rst:1059 +#: ../../reference/datamodel.rst:1321 msgid "sys.stdin" -msgstr "" +msgstr "sys.stdin" -#: ../../reference/datamodel.rst:1059 +#: ../../reference/datamodel.rst:1321 msgid "sys.stdout" -msgstr "" +msgstr "sys.stdout" -#: ../../reference/datamodel.rst:1059 +#: ../../reference/datamodel.rst:1321 msgid "sys.stderr" -msgstr "" +msgstr "sys.stderr" -#: ../../reference/datamodel.rst:1059 +#: ../../reference/datamodel.rst:1321 msgid "stdio" -msgstr "" +msgstr "stdio" -#: ../../reference/datamodel.rst:1059 +#: ../../reference/datamodel.rst:1321 msgid "stdin (in module sys)" -msgstr "" +msgstr "stdin (no módulo sys)" -#: ../../reference/datamodel.rst:1059 +#: ../../reference/datamodel.rst:1321 msgid "stdout (in module sys)" -msgstr "" +msgstr "stdout (no módulo sys)" -#: ../../reference/datamodel.rst:1059 +#: ../../reference/datamodel.rst:1321 msgid "stderr (in module sys)" -msgstr "" +msgstr "stderr (no módulo sys)" -#: ../../reference/datamodel.rst:1088 +#: ../../reference/datamodel.rst:1350 msgid "internal type" -msgstr "" +msgstr "tipo interno" -#: ../../reference/datamodel.rst:1088 +#: ../../reference/datamodel.rst:1350 msgid "types, internal" -msgstr "" +msgstr "tipos, internos" -#: ../../reference/datamodel.rst:1102 +#: ../../reference/datamodel.rst:1364 msgid "bytecode" msgstr "bytecode" -#: ../../reference/datamodel.rst:1102 +#: ../../reference/datamodel.rst:1364 msgid "code" msgstr "código" -#: ../../reference/datamodel.rst:1102 +#: ../../reference/datamodel.rst:1364 msgid "code object" msgstr "objeto código" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_argcount (code object attribute)" msgstr "co_argcount (atributo de objeto código)" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_posonlyargcount (code object attribute)" msgstr "co_posonlyargcount (atributo de objeto código)" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_kwonlyargcount (code object attribute)" msgstr "co_kwonlyargcount (atributo de objeto código)" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_code (code object attribute)" msgstr "co_code (atributo de objeto código)" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_consts (code object attribute)" msgstr "co_consts (atributo de objeto código)" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_filename (code object attribute)" msgstr "co_filename (atributo de objeto código)" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_firstlineno (code object attribute)" msgstr "co_firstlineno (atributo de objeto código)" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_flags (code object attribute)" msgstr "co_flags (atributo de objeto código)" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_lnotab (code object attribute)" msgstr "co_lnotab (atributo de objeto código)" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_name (code object attribute)" msgstr "co_name (atributo de objeto código)" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_names (code object attribute)" msgstr "co_names (atributo de objeto código)" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_nlocals (code object attribute)" msgstr "co_nlocals (atributo de objeto código)" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_stacksize (code object attribute)" msgstr "co_stacksize (atributo de objeto código)" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_varnames (code object attribute)" msgstr "co_varnames (atributo de objeto código)" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_cellvars (code object attribute)" msgstr "co_cellvars (atributo de objeto código)" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_freevars (code object attribute)" msgstr "co_freevars (atributo de objeto código)" -#: ../../reference/datamodel.rst:1113 +#: ../../reference/datamodel.rst:1375 msgid "co_qualname (code object attribute)" msgstr "co_qualname (atributo de objeto código)" -#: ../../reference/datamodel.rst:1224 +#: ../../reference/datamodel.rst:1488 msgid "documentation string" msgstr "string de documentação" -#: ../../reference/datamodel.rst:1315 +#: ../../reference/datamodel.rst:1579 msgid "frame" msgstr "quadro" -#: ../../reference/datamodel.rst:1321 +#: ../../reference/datamodel.rst:1585 msgid "f_back (frame attribute)" -msgstr "" +msgstr "f_back (atributo de frame)" -#: ../../reference/datamodel.rst:1321 +#: ../../reference/datamodel.rst:1585 msgid "f_code (frame attribute)" -msgstr "" +msgstr "f_code (atributo de frame)" -#: ../../reference/datamodel.rst:1321 +#: ../../reference/datamodel.rst:1585 msgid "f_globals (frame attribute)" -msgstr "" +msgstr "f_globals (atributo de frame)" -#: ../../reference/datamodel.rst:1321 +#: ../../reference/datamodel.rst:1585 msgid "f_locals (frame attribute)" -msgstr "" +msgstr "f_locals (atributo de frame)" -#: ../../reference/datamodel.rst:1321 +#: ../../reference/datamodel.rst:1585 msgid "f_lasti (frame attribute)" -msgstr "" +msgstr "f_lasti (atributo de frame)" -#: ../../reference/datamodel.rst:1321 +#: ../../reference/datamodel.rst:1585 msgid "f_builtins (frame attribute)" -msgstr "" +msgstr "f_builtins (atributo de frame)" -#: ../../reference/datamodel.rst:1365 +#: ../../reference/datamodel.rst:1629 msgid "f_trace (frame attribute)" -msgstr "" +msgstr "f_trace (atributo de frame)" -#: ../../reference/datamodel.rst:1365 +#: ../../reference/datamodel.rst:1629 msgid "f_trace_lines (frame attribute)" -msgstr "" +msgstr "f_trace_lines (atributo de frame)" -#: ../../reference/datamodel.rst:1365 +#: ../../reference/datamodel.rst:1629 msgid "f_trace_opcodes (frame attribute)" -msgstr "" +msgstr "f_trace_opcodes (atributo de frame)" -#: ../../reference/datamodel.rst:1365 +#: ../../reference/datamodel.rst:1629 msgid "f_lineno (frame attribute)" -msgstr "" +msgstr "f_lineno (atributo de frame)" -#: ../../reference/datamodel.rst:1425 +#: ../../reference/datamodel.rst:1689 msgid "traceback" msgstr "traceback" -#: ../../reference/datamodel.rst:1425 +#: ../../reference/datamodel.rst:1689 msgid "stack" -msgstr "" +msgstr "pilha (stack)" -#: ../../reference/datamodel.rst:1425 +#: ../../reference/datamodel.rst:1689 msgid "trace" -msgstr "" +msgstr "rastro (trace)" -#: ../../reference/datamodel.rst:1425 +#: ../../reference/datamodel.rst:1689 msgid "exception" msgstr "exceção" -#: ../../reference/datamodel.rst:1425 +#: ../../reference/datamodel.rst:1689 msgid "handler" -msgstr "" +msgstr "manipulador (handler)" -#: ../../reference/datamodel.rst:1425 +#: ../../reference/datamodel.rst:1689 msgid "execution" msgstr "execução" -#: ../../reference/datamodel.rst:1425 +#: ../../reference/datamodel.rst:1689 msgid "exc_info (in module sys)" -msgstr "" +msgstr "exc_info (no módulo sys)" -#: ../../reference/datamodel.rst:1425 +#: ../../reference/datamodel.rst:1689 msgid "last_traceback (in module sys)" -msgstr "" +msgstr "last_traceback (no módulo sys)" -#: ../../reference/datamodel.rst:1425 +#: ../../reference/datamodel.rst:1689 msgid "sys.exc_info" msgstr "sys.exc_info" -#: ../../reference/datamodel.rst:1425 +#: ../../reference/datamodel.rst:1689 msgid "sys.exception" msgstr "sys.exception" -#: ../../reference/datamodel.rst:1425 +#: ../../reference/datamodel.rst:1689 msgid "sys.last_traceback" msgstr "sys.last_traceback" -#: ../../reference/datamodel.rst:1462 +#: ../../reference/datamodel.rst:1726 msgid "tb_frame (traceback attribute)" -msgstr "" +msgstr "tb_frame (atributo de traceback)" -#: ../../reference/datamodel.rst:1462 +#: ../../reference/datamodel.rst:1726 msgid "tb_lineno (traceback attribute)" -msgstr "" +msgstr "tb_lineno (atributo de traceback)" -#: ../../reference/datamodel.rst:1462 +#: ../../reference/datamodel.rst:1726 msgid "tb_lasti (traceback attribute)" -msgstr "" +msgstr "tb_lasti (atributo de traceback)" -#: ../../reference/datamodel.rst:1462 +#: ../../reference/datamodel.rst:1726 msgid "try" msgstr "try" -#: ../../reference/datamodel.rst:1492 +#: ../../reference/datamodel.rst:1756 msgid "tb_next (traceback attribute)" -msgstr "" +msgstr "tb_next (atributo de traceback)" -#: ../../reference/datamodel.rst:1508 ../../reference/datamodel.rst:2854 +#: ../../reference/datamodel.rst:1772 ../../reference/datamodel.rst:3132 msgid "slice" msgstr "fatia" -#: ../../reference/datamodel.rst:1514 +#: ../../reference/datamodel.rst:1778 msgid "start (slice object attribute)" -msgstr "início (atributo de objeto fatia)" +msgstr "start (atributo de objeto fatia)" -#: ../../reference/datamodel.rst:1514 +#: ../../reference/datamodel.rst:1778 msgid "stop (slice object attribute)" msgstr "stop (atributo de objeto fatia)" -#: ../../reference/datamodel.rst:1514 +#: ../../reference/datamodel.rst:1778 msgid "step (slice object attribute)" msgstr "step (atributo de objeto fatia)" -#: ../../reference/datamodel.rst:1562 +#: ../../reference/datamodel.rst:1826 msgid "operator" msgstr "operador" -#: ../../reference/datamodel.rst:1562 +#: ../../reference/datamodel.rst:1826 msgid "overloading" -msgstr "" +msgstr "sobrecarga" -#: ../../reference/datamodel.rst:1562 +#: ../../reference/datamodel.rst:1826 msgid "__getitem__() (mapping object method)" -msgstr "" +msgstr "__getitem__() (método de objeto mapeamento)" -#: ../../reference/datamodel.rst:1598 +#: ../../reference/datamodel.rst:1862 msgid "subclassing" -msgstr "" +msgstr "subclasse" -#: ../../reference/datamodel.rst:1598 +#: ../../reference/datamodel.rst:1862 msgid "immutable types" -msgstr "" +msgstr "tipos imutáveis" -#: ../../reference/datamodel.rst:1627 +#: ../../reference/datamodel.rst:1891 msgid "constructor" -msgstr "" +msgstr "construtor" -#: ../../reference/datamodel.rst:1644 +#: ../../reference/datamodel.rst:1908 msgid "destructor" msgstr "destrutor" -#: ../../reference/datamodel.rst:1644 +#: ../../reference/datamodel.rst:1908 msgid "finalizer" -msgstr "" +msgstr "finalizador" -#: ../../reference/datamodel.rst:1644 +#: ../../reference/datamodel.rst:1908 msgid "del" msgstr "del" -#: ../../reference/datamodel.rst:1708 +#: ../../reference/datamodel.rst:1972 msgid "repr() (built-in function)" -msgstr "" +msgstr "repr() (função embutida)" -#: ../../reference/datamodel.rst:1708 +#: ../../reference/datamodel.rst:1972 msgid "__repr__() (object method)" -msgstr "" +msgstr "__repr__() (método de objeto)" -#: ../../reference/datamodel.rst:1725 +#: ../../reference/datamodel.rst:1990 msgid "__str__() (object method)" -msgstr "" +msgstr "__str__() (método de objeto)" -#: ../../reference/datamodel.rst:1725 +#: ../../reference/datamodel.rst:1990 msgid "format() (built-in function)" msgstr "format() (função embutida)" -#: ../../reference/datamodel.rst:1725 +#: ../../reference/datamodel.rst:1990 msgid "print() (built-in function)" -msgstr "" +msgstr "print() (função embutida)" -#: ../../reference/datamodel.rst:1755 +#: ../../reference/datamodel.rst:2021 msgid "__format__() (object method)" -msgstr "" +msgstr "__format__() (método de objeto)" -#: ../../reference/datamodel.rst:1755 +#: ../../reference/datamodel.rst:2021 msgid "conversion" msgstr "conversão" -#: ../../reference/datamodel.rst:1755 +#: ../../reference/datamodel.rst:2021 msgid "print" -msgstr "" +msgstr "print" -#: ../../reference/datamodel.rst:1794 +#: ../../reference/datamodel.rst:2063 msgid "comparisons" msgstr "comparações" -#: ../../reference/datamodel.rst:1839 +#: ../../reference/datamodel.rst:2114 msgid "hash" msgstr "hash" -#: ../../reference/datamodel.rst:1920 +#: ../../reference/datamodel.rst:2195 msgid "__len__() (mapping object method)" -msgstr "" +msgstr "__len__() (método de objeto mapeamento)" -#: ../../reference/datamodel.rst:2024 +#: ../../reference/datamodel.rst:2300 msgid "__getattr__ (module attribute)" -msgstr "" +msgstr "__getattr__ (atributo de módulo)" -#: ../../reference/datamodel.rst:2024 +#: ../../reference/datamodel.rst:2300 msgid "__dir__ (module attribute)" -msgstr "" +msgstr "__dir__ (atributo de módulo)" -#: ../../reference/datamodel.rst:2024 +#: ../../reference/datamodel.rst:2300 msgid "__class__ (module attribute)" -msgstr "" +msgstr "__class__ (atributo de módulo)" -#: ../../reference/datamodel.rst:2395 +#: ../../reference/datamodel.rst:2671 msgid "metaclass" msgstr "metaclasse" -#: ../../reference/datamodel.rst:2395 +#: ../../reference/datamodel.rst:2671 msgid "= (equals)" msgstr "= (igual)" -#: ../../reference/datamodel.rst:2395 +#: ../../reference/datamodel.rst:2671 msgid "class definition" -msgstr "" +msgstr "definição de classe" -#: ../../reference/datamodel.rst:2459 +#: ../../reference/datamodel.rst:2735 msgid "metaclass hint" -msgstr "" +msgstr "dica de metaclasse" -#: ../../reference/datamodel.rst:2482 +#: ../../reference/datamodel.rst:2758 msgid "__prepare__ (metaclass method)" -msgstr "" +msgstr "__prepare__ (método de metaclasse)" -#: ../../reference/datamodel.rst:2506 +#: ../../reference/datamodel.rst:2782 msgid "body" -msgstr "" +msgstr "corpo" -#: ../../reference/datamodel.rst:2526 +#: ../../reference/datamodel.rst:2802 msgid "__class__ (method cell)" -msgstr "" +msgstr "__class__ (célula de método)" -#: ../../reference/datamodel.rst:2526 +#: ../../reference/datamodel.rst:2802 msgid "__classcell__ (class namespace entry)" -msgstr "" +msgstr "__classcell__ (entrada de espaço de nomes de classe)" -#: ../../reference/datamodel.rst:2824 +#: ../../reference/datamodel.rst:3102 msgid "__bool__() (object method)" -msgstr "" +msgstr "__bool__() (método de objeto)" -#: ../../reference/datamodel.rst:2982 ../../reference/datamodel.rst:3017 +#: ../../reference/datamodel.rst:3260 ../../reference/datamodel.rst:3295 msgid "divmod" -msgstr "" +msgstr "divmod" -#: ../../reference/datamodel.rst:2982 ../../reference/datamodel.rst:3017 -#: ../../reference/datamodel.rst:3031 +#: ../../reference/datamodel.rst:3260 ../../reference/datamodel.rst:3295 +#: ../../reference/datamodel.rst:3309 msgid "pow" -msgstr "" +msgstr "pow" -#: ../../reference/datamodel.rst:3080 +#: ../../reference/datamodel.rst:3358 msgid "abs" -msgstr "" +msgstr "abs" -#: ../../reference/datamodel.rst:3090 +#: ../../reference/datamodel.rst:3368 msgid "int" msgstr "int" -#: ../../reference/datamodel.rst:3090 +#: ../../reference/datamodel.rst:3368 msgid "float" msgstr "ponto flutuante" -#: ../../reference/datamodel.rst:3118 +#: ../../reference/datamodel.rst:3396 msgid "round" -msgstr "" +msgstr "round" -#: ../../reference/datamodel.rst:3145 +#: ../../reference/datamodel.rst:3423 msgid "with" -msgstr "" +msgstr "with" -#: ../../reference/datamodel.rst:3145 +#: ../../reference/datamodel.rst:3423 msgid "context manager" msgstr "gerenciador de contexto" diff --git a/reference/executionmodel.po b/reference/executionmodel.po index 8832432a7..aaed87f39 100644 --- a/reference/executionmodel.po +++ b/reference/executionmodel.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Leticia Portella , 2021 -# Adorilson Bezerra , 2023 -# Marco Rougeth , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 01:19+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -179,13 +176,13 @@ msgid "" "declared as :keyword:`nonlocal` or :keyword:`global`. If a name is bound at " "the module level, it is a global variable. (The variables of the module " "code block are local and global.) If a variable is used in a code block but " -"not defined there, it is a :dfn:`free variable`." +"not defined there, it is a :term:`free variable`." msgstr "" "Se um nome está ligado a um bloco, é uma variável local desse bloco, a menos " "que declarado como :keyword:`nonlocal` ou :keyword:`global`. Se um nome está " -"ligado a nível do módulo, é uma variável global. (As variáveis ​​do bloco de " +"ligado a nível do módulo, é uma variável global. (As variáveis do bloco de " "código do módulo são locais e globais.) Se uma variável for usada em um " -"bloco de código, mas não definida lá, é uma :dfn:`variável livre`." +"bloco de código, mas não definida lá, é uma :term:`variável livre`." #: ../../reference/executionmodel.rst:95 msgid "" @@ -255,8 +252,8 @@ msgstr "" "permite que as operações de ligação de nomes ocorram em qualquer lugar " "dentro de um bloco de código. As variáveis locais de um bloco de código " "podem ser determinadas pela varredura de todo o texto do bloco para " -"operações de ligação de nome. Veja :ref:`the FAQ entry on UnboundLocalError " -"` para exemplos." +"operações de ligação de nome. Veja :ref:`o FAQ sobre UnboundLocalError ` para exemplos." #: ../../reference/executionmodel.rst:136 msgid "" @@ -343,10 +340,34 @@ msgstr "" "inclui :ref:`escopos de anotação `, que têm acesso a seus " "escopos de classe delimitadores. Isso significa que o seguinte falhará::" +#: ../../reference/executionmodel.rst:176 +msgid "" +"class A:\n" +" a = 42\n" +" b = list(a + i for i in range(10))" +msgstr "" +"class A:\n" +" a = 42\n" +" b = list(a + i for i in range(10))" + #: ../../reference/executionmodel.rst:180 msgid "However, the following will succeed::" msgstr "Porém, o seguinte vai funcionar::" +#: ../../reference/executionmodel.rst:182 +msgid "" +"class A:\n" +" type Alias = Nested\n" +" class Nested: pass\n" +"\n" +"print(A.Alias.__value__) # " +msgstr "" +"class A:\n" +" type Alias = Nested\n" +" class Nested: pass\n" +"\n" +"print(A.Alias.__value__) # " + #: ../../reference/executionmodel.rst:191 msgid "Annotation scopes" msgstr "Escopos de anotação" @@ -460,13 +481,13 @@ msgstr "" #: ../../reference/executionmodel.rst:227 msgid "" "While annotation scopes have an internal name, that name is not reflected in " -"the :term:`__qualname__ ` of objects defined within the " -"scope. Instead, the :attr:`!__qualname__` of such objects is as if the " -"object were defined in the enclosing scope." +"the :term:`qualified name` of objects defined within the scope. Instead, " +"the :attr:`~definition.__qualname__` of such objects is as if the object " +"were defined in the enclosing scope." msgstr "" "Embora os escopos de anotação tenham um nome interno, esse nome não é " -"refletido no :term:`__qualname__ ` dos objetos definidos " -"dentro do escopo. Em vez disso, o :attr:`!__qualname__` de tais objetos é " +"refletido no :term:`nome qualificado` dos objetos definidos dentro do " +"escopo. Em vez disso, o :attr:`~definition.__qualname__` de tais objetos é " "como se o objeto fosse definido no escopo delimitador." #: ../../reference/executionmodel.rst:232 @@ -508,6 +529,32 @@ msgstr "" msgid "Example:" msgstr "Exemplo:" +#: ../../reference/executionmodel.rst:253 +msgid "" +">>> type Alias = 1/0\n" +">>> Alias.__value__\n" +"Traceback (most recent call last):\n" +" ...\n" +"ZeroDivisionError: division by zero\n" +">>> def func[T: 1/0](): pass\n" +">>> T = func.__type_params__[0]\n" +">>> T.__bound__\n" +"Traceback (most recent call last):\n" +" ...\n" +"ZeroDivisionError: division by zero" +msgstr "" +">>> type Alias = 1/0\n" +">>> Alias.__value__\n" +"Traceback (most recent call last):\n" +" ...\n" +"ZeroDivisionError: division by zero\n" +">>> def func[T: 1/0](): pass\n" +">>> T = func.__type_params__[0]\n" +">>> T.__bound__\n" +"Traceback (most recent call last):\n" +" ...\n" +"ZeroDivisionError: division by zero" + #: ../../reference/executionmodel.rst:267 msgid "" "Here the exception is raised only when the ``__value__`` attribute of the " @@ -527,6 +574,20 @@ msgstr "" "exemplo, a avaliação preguiçosa permite a criação de apelidos de tipo " "mutuamente recursivos::" +#: ../../reference/executionmodel.rst:275 +msgid "" +"from typing import Literal\n" +"\n" +"type SimpleExpr = int | Parenthesized\n" +"type Parenthesized = tuple[Literal[\"(\"], Expr, Literal[\")\"]]\n" +"type Expr = SimpleExpr | tuple[SimpleExpr, Literal[\"+\", \"-\"], Expr]" +msgstr "" +"from typing import Literal\n" +"\n" +"type SimpleExpr = int | Parenthesized\n" +"type Parenthesized = tuple[Literal[\"(\"], Expr, Literal[\")\"]]\n" +"type Expr = SimpleExpr | tuple[SimpleExpr, Literal[\"+\", \"-\"], Expr]" + #: ../../reference/executionmodel.rst:281 msgid "" "Lazily evaluated values are evaluated in :ref:`annotation scope ` dela. A instância pode ser recebida pelo manipulador " "e pode conter informações adicionais sobre a condição excepcional." -#: ../../reference/executionmodel.rst:383 +#: ../../reference/executionmodel.rst:386 msgid "" "Exception messages are not part of the Python API. Their contents may " "change from one version of Python to the next without warning and should not " @@ -688,7 +763,7 @@ msgstr "" "mudar de uma versão do Python para outra sem aviso e não deve ser invocado " "pelo código que será executado em várias versões do interpretador." -#: ../../reference/executionmodel.rst:387 +#: ../../reference/executionmodel.rst:390 msgid "" "See also the description of the :keyword:`try` statement in section :ref:" "`try` and :keyword:`raise` statement in section :ref:`raise`." @@ -696,11 +771,11 @@ msgstr "" "Veja também a descrição da declaração :keyword:`try` na seção :ref:`try` e a " "instrução :keyword:`raise` na seção :ref:`raise`." -#: ../../reference/executionmodel.rst:392 +#: ../../reference/executionmodel.rst:395 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../reference/executionmodel.rst:393 +#: ../../reference/executionmodel.rst:396 msgid "" "This limitation occurs because the code that is executed by these operations " "is not available at the time the module is compiled." @@ -742,7 +817,7 @@ msgstr "nome" #: ../../reference/executionmodel.rst:51 msgid "binding" -msgstr "vinculação" +msgstr "vinculação; ligação" #: ../../reference/executionmodel.rst:57 msgid "from" @@ -784,34 +859,34 @@ msgstr "__main__" msgid "restricted" msgstr "restrita" -#: ../../reference/executionmodel.rst:339 +#: ../../reference/executionmodel.rst:342 msgid "exception" msgstr "exceção" -#: ../../reference/executionmodel.rst:341 +#: ../../reference/executionmodel.rst:344 msgid "raise an exception" msgstr "levantar uma exceção" -#: ../../reference/executionmodel.rst:341 +#: ../../reference/executionmodel.rst:344 msgid "handle an exception" msgstr "manipular uma exceção" -#: ../../reference/executionmodel.rst:341 +#: ../../reference/executionmodel.rst:344 msgid "exception handler" msgstr "tratador de exceção" -#: ../../reference/executionmodel.rst:341 +#: ../../reference/executionmodel.rst:344 msgid "errors" msgstr "erros" -#: ../../reference/executionmodel.rst:341 +#: ../../reference/executionmodel.rst:344 msgid "error handling" msgstr "tratamento de erros" -#: ../../reference/executionmodel.rst:362 +#: ../../reference/executionmodel.rst:365 msgid "termination model" msgstr "modelo de terminação" -#: ../../reference/executionmodel.rst:369 +#: ../../reference/executionmodel.rst:372 msgid "SystemExit (built-in exception)" msgstr "SystemExit (exceção embutida)" diff --git a/reference/expressions.po b/reference/expressions.po index fb2b44e99..78dbedaea 100644 --- a/reference/expressions.po +++ b/reference/expressions.po @@ -1,37 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Danilo Lima , 2021 -# Misael borges , 2021 -# Italo Penaforte , 2023 -# Julia Rizza , 2023 -# felipe caridade fernandes , 2023 -# Vinicius Gubiani Ferreira , 2023 -# Alexandre B A Villares, 2023 -# Marco Rougeth , 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# Adorilson Bezerra , 2023 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 01:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-28 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -194,11 +182,11 @@ msgstr "" #: ../../reference/expressions.rst:107 msgid "" -"The ``__name__`` attribute of nested functions, classes, and type aliases is " -"however not mangled." +"The :attr:`~definition.__name__` attribute of nested functions, classes, and " +"type aliases is however not mangled." msgstr "" -"O atributo ``__name__`` de funções aninhadas, classes e apelidos de tipo, " -"entretanto, não é desfigurado." +"O atributo :attr:`~definition.__name__` de funções aninhadas, classes e " +"apelidos de tipo, entretanto, não é desfigurado." #: ../../reference/expressions.rst:110 msgid "" @@ -724,6 +712,20 @@ msgstr "" "geradora, e usá-la no corpo de uma função :keyword:`async def` faz com que " "essa função de corrotina seja uma função geradora assíncrona. Por exemplo::" +#: ../../reference/expressions.rst:466 +msgid "" +"def gen(): # defines a generator function\n" +" yield 123\n" +"\n" +"async def agen(): # defines an asynchronous generator function\n" +" yield 123" +msgstr "" +"def gen(): # define uma função geradora\n" +" yield 123\n" +"\n" +"async def agen(): # define uma função geradora assíncrona\n" +" yield 123" + #: ../../reference/expressions.rst:472 msgid "" "Due to their side effects on the containing scope, ``yield`` expressions are " @@ -759,9 +761,9 @@ msgid "" "function. The execution starts when one of the generator's methods is " "called. At that time, the execution proceeds to the first yield expression, " "where it is suspended again, returning the value of :token:`~python-grammar:" -"expression_list` to the generator's caller, or ``None`` if :token:`~python-" -"grammar:expression_list` is omitted. By suspended, we mean that all local " -"state is retained, including the current bindings of local variables, the " +"yield_list` to the generator's caller, or ``None`` if :token:`~python-" +"grammar:yield_list` is omitted. By suspended, we mean that all local state " +"is retained, including the current bindings of local variables, the " "instruction pointer, the internal evaluation stack, and the state of any " "exception handling. When the execution is resumed by calling one of the " "generator's methods, the function can proceed exactly as if the yield " @@ -776,18 +778,18 @@ msgstr "" "gerador. Esse gerador então controla a execução da função geradora. A " "execução começa quando um dos métodos do gerador é chamado. Nesse momento, a " "execução segue para a primeira expressão yield, onde é suspensa novamente, " -"retornando o valor de :token:`~python-grammar:expression_list` ao chamador " -"do gerador, ou ``None`` se :token:`~python-grammar:expression_list` é " -"omitido. Por suspenso, queremos dizer que todo o estado local é retido, " -"incluindo as chamadas atuais de variáveis locais, o ponteiro de instrução, a " -"pilha de avaliação interna e o estado de qualquer tratamento de exceção. " -"Quando a execução é retomada chamando um dos métodos do gerador, a função " -"pode prosseguir exatamente como se a expressão yield fosse apenas outra " -"chamada externa. O valor da expressão yield após a retomada depende do " -"método que retomou a execução. Se :meth:`~generator.__next__` for usado " -"(tipicamente através de uma :keyword:`for` ou do :func:`next` embutido) " -"então o resultado será :const:`None`. Caso contrário, se :meth:`~generator." -"send` for usado, o resultado será o valor passado para esse método." +"retornando o valor de :token:`~python-grammar:yield_list` ao chamador do " +"gerador, ou ``None`` se :token:`~python-grammar:yield_list` é omitido. Por " +"suspenso, queremos dizer que todo o estado local é retido, incluindo as " +"chamadas atuais de variáveis locais, o ponteiro de instrução, a pilha de " +"avaliação interna e o estado de qualquer tratamento de exceção. Quando a " +"execução é retomada chamando um dos métodos do gerador, a função pode " +"prosseguir exatamente como se a expressão yield fosse apenas outra chamada " +"externa. O valor da expressão yield após a retomada depende do método que " +"retomou a execução. Se :meth:`~generator.__next__` for usado (tipicamente " +"através de uma :keyword:`for` ou do :func:`next` embutido) então o resultado " +"será :const:`None`. Caso contrário, se :meth:`~generator.send` for usado, o " +"resultado será o valor passado para esse método." #: ../../reference/expressions.rst:504 msgid "" @@ -867,7 +869,7 @@ msgstr "" #: ../../reference/expressions.rst:542 msgid ":pep:`255` - Simple Generators" -msgstr ":pep:`255` - Geradores simples" +msgstr ":pep:`255` - Simple Generators" #: ../../reference/expressions.rst:543 msgid "" @@ -939,7 +941,7 @@ msgid "" "meth:`~generator.__next__` method, the current yield expression always " "evaluates to :const:`None`. The execution then continues to the next yield " "expression, where the generator is suspended again, and the value of the :" -"token:`~python-grammar:expression_list` is returned to :meth:`__next__`'s " +"token:`~python-grammar:yield_list` is returned to :meth:`__next__`'s " "caller. If the generator exits without yielding another value, a :exc:" "`StopIteration` exception is raised." msgstr "" @@ -948,8 +950,8 @@ msgstr "" "`~generator.__next__`, a expressão yield atual sempre é avaliada como :const:" "`None`. A execução então continua para a próxima expressão yield, onde o " "gerador é suspenso novamente, e o valor de :token:`~python-grammar:" -"expression_list` é retornado para o chamador de :meth:`__next__`. Se o " -"gerador sair sem produzir outro valor, uma exceção :exc:`StopIteration` será " +"yield_list` é retornado para o chamador de :meth:`__next__`. Se o gerador " +"sair sem produzir outro valor, uma exceção :exc:`StopIteration` será " "levantada." #: ../../reference/expressions.rst:583 @@ -1018,7 +1020,7 @@ msgstr "" "`~BaseException.__traceback__` existente armazenado em *value* poderá ser " "limpo." -#: ../../reference/expressions.rst:621 ../../reference/expressions.rst:802 +#: ../../reference/expressions.rst:621 ../../reference/expressions.rst:805 msgid "" "The second signature \\(type\\[, value\\[, traceback\\]\\]\\) is deprecated " "and may be removed in a future version of Python." @@ -1068,6 +1070,59 @@ msgstr "" "Aqui está um exemplo simples que demonstra o comportamento de geradores e " "funções geradoras::" +#: ../../reference/expressions.rst:652 +msgid "" +">>> def echo(value=None):\n" +"... print(\"Execution starts when 'next()' is called for the first time." +"\")\n" +"... try:\n" +"... while True:\n" +"... try:\n" +"... value = (yield value)\n" +"... except Exception as e:\n" +"... value = e\n" +"... finally:\n" +"... print(\"Don't forget to clean up when 'close()' is called.\")\n" +"...\n" +">>> generator = echo(1)\n" +">>> print(next(generator))\n" +"Execution starts when 'next()' is called for the first time.\n" +"1\n" +">>> print(next(generator))\n" +"None\n" +">>> print(generator.send(2))\n" +"2\n" +">>> generator.throw(TypeError, \"spam\")\n" +"TypeError('spam',)\n" +">>> generator.close()\n" +"Don't forget to clean up when 'close()' is called." +msgstr "" +">>> def echo(value=None):\n" +"... print(\"A execução inicia quando 'next()' é chamada pela primeira " +"vez.\")\n" +"... try:\n" +"... while True:\n" +"... try:\n" +"... value = (yield value)\n" +"... except Exception as e:\n" +"... value = e\n" +"... finally:\n" +"... print(\"Não se esqueça de fazer uma limpeza quando 'close()' for " +"chamada.\")\n" +"...\n" +">>> generator = echo(1)\n" +">>> print(next(generator))\n" +"A execução inicia quando 'next()' é chamada pela primeira vez.\n" +"1\n" +">>> print(next(generator))\n" +"None\n" +">>> print(generator.send(2))\n" +"2\n" +">>> generator.throw(TypeError, \"spam\")\n" +"TypeError('spam',)\n" +">>> generator.close()\n" +"Não se esqueça de fazer uma limpeza quando 'close()' for chamada." + #: ../../reference/expressions.rst:676 msgid "" "For examples using ``yield from``, see :ref:`pep-380` in \"What's New in " @@ -1112,29 +1167,28 @@ msgid "" "`awaitable` object, and the execution starts when this object is awaited on. " "At that time, the execution proceeds to the first yield expression, where it " "is suspended again, returning the value of :token:`~python-grammar:" -"expression_list` to the awaiting coroutine. As with a generator, suspension " -"means that all local state is retained, including the current bindings of " -"local variables, the instruction pointer, the internal evaluation stack, and " -"the state of any exception handling. When the execution is resumed by " -"awaiting on the next object returned by the asynchronous generator's " -"methods, the function can proceed exactly as if the yield expression were " -"just another external call. The value of the yield expression after resuming " -"depends on the method which resumed the execution. If :meth:`~agen." -"__anext__` is used then the result is :const:`None`. Otherwise, if :meth:" -"`~agen.asend` is used, then the result will be the value passed in to that " -"method." +"yield_list` to the awaiting coroutine. As with a generator, suspension means " +"that all local state is retained, including the current bindings of local " +"variables, the instruction pointer, the internal evaluation stack, and the " +"state of any exception handling. When the execution is resumed by awaiting " +"on the next object returned by the asynchronous generator's methods, the " +"function can proceed exactly as if the yield expression were just another " +"external call. The value of the yield expression after resuming depends on " +"the method which resumed the execution. If :meth:`~agen.__anext__` is used " +"then the result is :const:`None`. Otherwise, if :meth:`~agen.asend` is used, " +"then the result will be the value passed in to that method." msgstr "" "A chamada de um dos métodos do gerador assíncrono retorna um objeto :term:" "`aguardável`, e a execução começa quando esse objeto é aguardado. Nesse " "momento, a execução prossegue até a primeira expressão yield, onde é " "suspensa novamente, retornando o valor de :token:`~python-grammar:" -"expression_list` para a corrotina em aguardo. Assim como ocorre com um " -"gerador, a suspensão significa que todo o estado local é mantido, inclusive " -"as ligações atuais das variáveis locais, o ponteiro de instruções, a pilha " -"de avaliação interna e o estado de qualquer tratamento de exceção. Quando a " -"execução é retomada, aguardando o próximo objeto retornado pelos métodos do " -"gerador assíncrono, a função pode prosseguir exatamente como se a expressão " -"de rendimento fosse apenas outra chamada externa. O valor da expressão yield " +"yield_list` para a corrotina em aguardo. Assim como ocorre com um gerador, a " +"suspensão significa que todo o estado local é mantido, inclusive as ligações " +"atuais das variáveis locais, o ponteiro de instruções, a pilha de avaliação " +"interna e o estado de qualquer tratamento de exceção. Quando a execução é " +"retomada, aguardando o próximo objeto retornado pelos métodos do gerador " +"assíncrono, a função pode prosseguir exatamente como se a expressão de " +"rendimento fosse apenas outra chamada externa. O valor da expressão yield " "após a retomada depende do método que retomou a execução. Se :meth:`~agen." "__anext__` for usado, o resultado será :const:`None`. Caso contrário, se :" "meth:`~agen.asend` for usado, o resultado será o valor passado para esse " @@ -1227,14 +1281,14 @@ msgstr "" "Esta subseção descreve os métodos de um iterador gerador assíncrono, que são " "usados para controlar a execução de uma função geradora." -#: ../../reference/expressions.rst:757 +#: ../../reference/expressions.rst:758 msgid "" "Returns an awaitable which when run starts to execute the asynchronous " "generator or resumes it at the last executed yield expression. When an " "asynchronous generator function is resumed with an :meth:`~agen.__anext__` " "method, the current yield expression always evaluates to :const:`None` in " "the returned awaitable, which when run will continue to the next yield " -"expression. The value of the :token:`~python-grammar:expression_list` of the " +"expression. The value of the :token:`~python-grammar:yield_list` of the " "yield expression is the value of the :exc:`StopIteration` exception raised " "by the completing coroutine. If the asynchronous generator exits without " "yielding another value, the awaitable instead raises a :exc:" @@ -1246,23 +1300,23 @@ msgstr "" "uma função geradora assíncrona é retomada com o método :meth:`~agen." "__anext__`, a expressão yield atual sempre avalia para :const:`None` no " "objeto aguardável retornado, que, quando executado, continuará para a " -"próxima expressão yield. O valor de :token:`~python-grammar:expression_list` " -"da expressão yield é o valor da exceção :exc:`StopIteration` levantada pela " +"próxima expressão yield. O valor de :token:`~python-grammar:yield_list` da " +"expressão yield é o valor da exceção :exc:`StopIteration` levantada pela " "corrotina em conclusão. Se o gerador assíncrono sair sem produzir outro " "valor, o objeto aguardável em vez disso levanta uma exceção :exc:" "`StopAsyncIteration`, sinalizando que a iteração assíncrona foi concluída." -#: ../../reference/expressions.rst:769 +#: ../../reference/expressions.rst:770 msgid "" "This method is normally called implicitly by a :keyword:`async for` loop." msgstr "" "Este método é normalmente chamado implicitamente por um laço :keyword:`async " "for`." -#: ../../reference/expressions.rst:774 +#: ../../reference/expressions.rst:776 msgid "" "Returns an awaitable which when run resumes the execution of the " -"asynchronous generator. As with the :meth:`~generator.send()` method for a " +"asynchronous generator. As with the :meth:`~generator.send` method for a " "generator, this \"sends\" a value into the asynchronous generator function, " "and the *value* argument becomes the result of the current yield expression. " "The awaitable returned by the :meth:`asend` method will return the next " @@ -1274,7 +1328,7 @@ msgid "" "receive the value." msgstr "" "Retorna um objeto aguardável que, quando executado, retoma a execução do " -"gerador assíncrono. Assim como o método :meth:`~generator.send()` para um " +"gerador assíncrono. Assim como o método :meth:`~generator.send` para um " "gerador, isso \"envia\" um valor para a função geradora assíncrona, e o " "argumento *value* se torna o resultado da expressão de yield atual. O objeto " "aguardável retornado pelo método :meth:`asend` retornará o próximo valor " @@ -1284,7 +1338,7 @@ msgstr "" "gerador assíncrono, ele deve ser chamado com :const:`None` como argumento, " "pois não há expressão yield que possa receber o valor." -#: ../../reference/expressions.rst:790 +#: ../../reference/expressions.rst:793 msgid "" "Returns an awaitable that raises an exception of type ``type`` at the point " "where the asynchronous generator was paused, and returns the next value " @@ -1304,7 +1358,7 @@ msgstr "" "então quando o objeto aguardável for executado, essa exceção se propagará " "para o chamador do objeto aguardável." -#: ../../reference/expressions.rst:810 +#: ../../reference/expressions.rst:814 msgid "" "Returns an awaitable that when run will throw a :exc:`GeneratorExit` into " "the asynchronous generator function at the point where it was paused. If the " @@ -1333,11 +1387,11 @@ msgstr "" "uma exceção ou saída normal, então chamadas posteriores ao método :meth:" "`aclose` retornarão um objeto aguardável que não faz nada." -#: ../../reference/expressions.rst:826 +#: ../../reference/expressions.rst:830 msgid "Primaries" msgstr "Primárias" -#: ../../reference/expressions.rst:830 +#: ../../reference/expressions.rst:834 msgid "" "Primaries represent the most tightly bound operations of the language. Their " "syntax is:" @@ -1345,16 +1399,16 @@ msgstr "" "Primárias representam as operações mais fortemente vinculadas da linguagem. " "Sua sintaxe é:" -#: ../../reference/expressions.rst:840 +#: ../../reference/expressions.rst:844 msgid "Attribute references" msgstr "Referências de atributo" -#: ../../reference/expressions.rst:846 +#: ../../reference/expressions.rst:850 msgid "An attribute reference is a primary followed by a period and a name:" msgstr "" "Uma referência de atributo é um primário seguido de um ponto e um nome." -#: ../../reference/expressions.rst:856 +#: ../../reference/expressions.rst:860 msgid "" "The primary must evaluate to an object of a type that supports attribute " "references, which most objects do. This object is then asked to produce the " @@ -1368,7 +1422,7 @@ msgstr "" "o valor produzido são determinados pelo objeto. Várias avaliações da mesma " "referência de atributo podem produzir diferentes objetos." -#: ../../reference/expressions.rst:862 +#: ../../reference/expressions.rst:866 msgid "" "This production can be customized by overriding the :meth:`~object." "__getattribute__` method or the :meth:`~object.__getattr__` method. The :" @@ -1380,7 +1434,7 @@ msgstr "" "__getattribute__` é chamado primeiro e retorna um valor ou levanta uma :exc:" "`AttributeError` se o atributo não estiver disponível." -#: ../../reference/expressions.rst:868 +#: ../../reference/expressions.rst:872 msgid "" "If an :exc:`AttributeError` is raised and the object has a :meth:`!" "__getattr__` method, that method is called as a fallback." @@ -1388,11 +1442,11 @@ msgstr "" "Se for levantada uma :exc:`AttributeError` e o objeto tiver um método :meth:" "`!__getattr__`, esse método será chamado como alternativa." -#: ../../reference/expressions.rst:874 +#: ../../reference/expressions.rst:878 msgid "Subscriptions" msgstr "Subscrições" -#: ../../reference/expressions.rst:889 +#: ../../reference/expressions.rst:893 msgid "" "The subscription of an instance of a :ref:`container class ` " "will generally select an element from the container. The subscription of a :" @@ -1404,7 +1458,7 @@ msgstr "" "subscrição de uma :term:`classe genérica ` geralmente " "retornará um objeto :ref:`GenericAlias `." -#: ../../reference/expressions.rst:897 +#: ../../reference/expressions.rst:901 msgid "" "When an object is subscripted, the interpreter will evaluate the primary and " "the expression list." @@ -1412,7 +1466,7 @@ msgstr "" "Quando um objeto é subscrito, o interpretador avaliará o primário e a lista " "de expressões." -#: ../../reference/expressions.rst:900 +#: ../../reference/expressions.rst:904 msgid "" "The primary must evaluate to an object that supports subscription. An object " "may support subscription through defining one or both of :meth:`~object." @@ -1429,18 +1483,25 @@ msgstr "" "``__class_getitem__`` é chamado em vez de ``__getitem__``, veja :ref:" "`classgetitem-versus-getitem`." -#: ../../reference/expressions.rst:907 +#: ../../reference/expressions.rst:911 msgid "" -"If the expression list contains at least one comma, it will evaluate to a :" -"class:`tuple` containing the items of the expression list. Otherwise, the " +"If the expression list contains at least one comma, or if any of the " +"expressions are starred, the expression list will evaluate to a :class:" +"`tuple` containing the items of the expression list. Otherwise, the " "expression list will evaluate to the value of the list's sole member." msgstr "" -"Se a lista de expressões contiver pelo menos uma vírgula, ela será avaliada " -"como uma :class:`tuple` contendo os itens da lista de expressões. Caso " -"contrário, a lista de expressões será avaliada como o valor do único membro " -"da lista." +"Se a lista de expressões contiver pelo menos uma vírgula ou se alguma das " +"expressões for estrelada, ela será avaliada como uma :class:`tuple` contendo " +"os itens da lista de expressões. Caso contrário, a lista de expressões será " +"avaliada como o valor do único membro da lista." -#: ../../reference/expressions.rst:911 +#: ../../reference/expressions.rst:916 +msgid "Expressions in an expression list may be starred. See :pep:`646`." +msgstr "" +"Expressões em uma lista de expressões podem ser estreladas. Veja a :pep:" +"`646`." + +#: ../../reference/expressions.rst:919 msgid "" "For built-in objects, there are two types of objects that support " "subscription via :meth:`~object.__getitem__`:" @@ -1448,7 +1509,7 @@ msgstr "" "Para objetos embutido, existem dois tipos de objetos que oferecem suporte a " "subscrição via :meth:`~object.__getitem__`:" -#: ../../reference/expressions.rst:914 +#: ../../reference/expressions.rst:922 msgid "" "Mappings. If the primary is a :term:`mapping`, the expression list must " "evaluate to an object whose value is one of the keys of the mapping, and the " @@ -1460,7 +1521,7 @@ msgstr "" "e a subscrição seleciona o valor no mapeamento que corresponde a essa chave. " "Um exemplo de classe de mapeamento integrada é a classe :class:`dict`." -#: ../../reference/expressions.rst:918 +#: ../../reference/expressions.rst:926 msgid "" "Sequences. If the primary is a :term:`sequence`, the expression list must " "evaluate to an :class:`int` or a :class:`slice` (as discussed in the " @@ -1472,7 +1533,7 @@ msgstr "" "seção seguinte). Exemplos de classes de sequência embutidas incluem as " "classes :class:`str`, :class:`list` e :class:`tuple`." -#: ../../reference/expressions.rst:923 +#: ../../reference/expressions.rst:931 msgid "" "The formal syntax makes no special provision for negative indices in :term:" "`sequences `. However, built-in sequences all provide a :meth:" @@ -1496,7 +1557,7 @@ msgstr "" "método :meth:`~object.__getitem__` do objeto, as subclasses que substituem " "esse método precisarão adicionar explicitamente esse suporte." -#: ../../reference/expressions.rst:937 +#: ../../reference/expressions.rst:945 msgid "" "A :class:`string ` is a special kind of sequence whose items are " "*characters*. A character is not a separate data type but a string of " @@ -1506,11 +1567,11 @@ msgstr "" "*caracteres*. Um caractere não é um tipo de dados separado, mas uma string " "de exatamente um caractere." -#: ../../reference/expressions.rst:945 +#: ../../reference/expressions.rst:953 msgid "Slicings" msgstr "Fatiamentos" -#: ../../reference/expressions.rst:959 +#: ../../reference/expressions.rst:967 msgid "" "A slicing selects a range of items in a sequence object (e.g., a string, " "tuple or list). Slicings may be used as expressions or as targets in " @@ -1521,7 +1582,7 @@ msgstr "" "expressões ou como alvos em instruções de atribuição ou :keyword:`del`. A " "sintaxe para um fatiamento:" -#: ../../reference/expressions.rst:972 +#: ../../reference/expressions.rst:980 msgid "" "There is ambiguity in the formal syntax here: anything that looks like an " "expression list also looks like a slice list, so any subscription can be " @@ -1538,7 +1599,7 @@ msgstr "" "interpretação como um fatiamento (este é o caso se a lista de fatias não " "contiver uma fatia adequada)." -#: ../../reference/expressions.rst:984 +#: ../../reference/expressions.rst:992 msgid "" "The semantics for a slicing are as follows. The primary is indexed (using " "the same :meth:`~object.__getitem__` method as normal subscription) with a " @@ -1564,11 +1625,11 @@ msgstr "" "inferior, limite superior e passo, respectivamente, substituindo ``None`` " "pelas expressões ausentes." -#: ../../reference/expressions.rst:1008 +#: ../../reference/expressions.rst:1016 msgid "Calls" msgstr "Chamadas" -#: ../../reference/expressions.rst:1010 +#: ../../reference/expressions.rst:1018 msgid "" "A call calls a callable object (e.g., a :term:`function`) with a possibly " "empty series of :term:`arguments `:" @@ -1577,7 +1638,7 @@ msgstr "" "`função`) com uma série possivelmente vazia de :term:`argumentos " "`:" -#: ../../reference/expressions.rst:1027 +#: ../../reference/expressions.rst:1035 msgid "" "An optional trailing comma may be present after the positional and keyword " "arguments but does not affect the semantics." @@ -1585,7 +1646,7 @@ msgstr "" "Uma vírgula final opcional pode estar presente após os argumentos " "posicionais e nomeados, mas não afeta a semântica." -#: ../../reference/expressions.rst:1033 +#: ../../reference/expressions.rst:1041 msgid "" "The primary must evaluate to a callable object (user-defined functions, " "built-in functions, methods of built-in objects, class objects, methods of " @@ -1602,7 +1663,7 @@ msgstr "" "Consulte a seção :ref:`function` para a sintaxe das listas formais de :term:" "`parâmetros `." -#: ../../reference/expressions.rst:1041 +#: ../../reference/expressions.rst:1049 msgid "" "If keyword arguments are present, they are first converted to positional " "arguments, as follows. First, a list of unfilled slots is created for the " @@ -1642,7 +1703,7 @@ msgstr "" "levantada. Caso contrário, a lista de slots preenchidos será usada como " "lista de argumentos para a chamada." -#: ../../reference/expressions.rst:1061 +#: ../../reference/expressions.rst:1069 msgid "" "An implementation may provide built-in functions whose positional parameters " "do not have names, even if they are 'named' for the purpose of " @@ -1656,7 +1717,7 @@ msgstr "" "CPython, este é o caso de funções implementadas em C que usam :c:func:" "`PyArg_ParseTuple` para analisar seus argumentos." -#: ../../reference/expressions.rst:1067 +#: ../../reference/expressions.rst:1075 msgid "" "If there are more positional arguments than there are formal parameter " "slots, a :exc:`TypeError` exception is raised, unless a formal parameter " @@ -1670,7 +1731,7 @@ msgstr "" "parâmetro formal recebe uma tupla contendo os argumentos posicionais em " "excesso (ou uma tupla vazia se não houver argumentos posicionais em excesso)." -#: ../../reference/expressions.rst:1073 +#: ../../reference/expressions.rst:1081 msgid "" "If any keyword argument does not correspond to a formal parameter name, a :" "exc:`TypeError` exception is raised, unless a formal parameter using the " @@ -1687,7 +1748,7 @@ msgstr "" "valores correspondentes), ou um (novo) dicionário vazio se não houver " "argumentos nomeados em excesso." -#: ../../reference/expressions.rst:1084 +#: ../../reference/expressions.rst:1092 msgid "" "If the syntax ``*expression`` appears in the function call, ``expression`` " "must evaluate to an :term:`iterable`. Elements from these iterables are " @@ -1703,7 +1764,7 @@ msgstr "" "*yM*, isso é equivalente a uma chamada com M+4 argumentos posicionais *x1*, " "*x2*, *y1*, ..., *yM*, *x3*, *x4*." -#: ../../reference/expressions.rst:1091 +#: ../../reference/expressions.rst:1099 msgid "" "A consequence of this is that although the ``*expression`` syntax may appear " "*after* explicit keyword arguments, it is processed *before* the keyword " @@ -1714,7 +1775,33 @@ msgstr "" "argumentos nomeados (e de quaisquer argumentos de ``**expressão`` -- veja " "abaixo). Então::" -#: ../../reference/expressions.rst:1107 +#: ../../reference/expressions.rst:1103 +msgid "" +">>> def f(a, b):\n" +"... print(a, b)\n" +"...\n" +">>> f(b=1, *(2,))\n" +"2 1\n" +">>> f(a=1, *(2,))\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: f() got multiple values for keyword argument 'a'\n" +">>> f(1, *(2,))\n" +"1 2" +msgstr "" +">>> def f(a, b):\n" +"... print(a, b)\n" +"...\n" +">>> f(b=1, *(2,))\n" +"2 1\n" +">>> f(a=1, *(2,))\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: f() got multiple values for keyword argument 'a'\n" +">>> f(1, *(2,))\n" +"1 2" + +#: ../../reference/expressions.rst:1115 msgid "" "It is unusual for both keyword arguments and the ``*expression`` syntax to " "be used in the same call, so in practice this confusion does not often arise." @@ -1723,7 +1810,7 @@ msgstr "" "usados na mesma chamada, portanto, na prática, essa confusão não surge com " "frequência." -#: ../../reference/expressions.rst:1113 +#: ../../reference/expressions.rst:1121 msgid "" "If the syntax ``**expression`` appears in the function call, ``expression`` " "must evaluate to a :term:`mapping`, the contents of which are treated as " @@ -1737,7 +1824,7 @@ msgstr "" "já recebeu um valor (por um argumento nomeado explícito ou de outro " "desempacotamento), uma exceção :exc:`TypeError` é levantada." -#: ../../reference/expressions.rst:1119 +#: ../../reference/expressions.rst:1127 msgid "" "When ``**expression`` is used, each key in this mapping must be a string. " "Each value from the mapping is assigned to the first formal parameter " @@ -1757,7 +1844,7 @@ msgstr "" "chave-valor é coletado pelo parâmetro ``**``, se houver, ou se não houver, " "uma exceção :exc:`TypeError` é levantada." -#: ../../reference/expressions.rst:1129 +#: ../../reference/expressions.rst:1137 msgid "" "Formal parameters using the syntax ``*identifier`` or ``**identifier`` " "cannot be used as positional argument slots or as keyword argument names." @@ -1766,7 +1853,7 @@ msgstr "" "``**identificador`` não podem ser usados como slots de argumentos " "posicionais ou como nomes de argumentos nomeados." -#: ../../reference/expressions.rst:1132 +#: ../../reference/expressions.rst:1140 msgid "" "Function calls accept any number of ``*`` and ``**`` unpackings, positional " "arguments may follow iterable unpackings (``*``), and keyword arguments may " @@ -1777,7 +1864,7 @@ msgstr "" "(``*``) e argumentos nomeados podem seguir desempacotamentos de dicionário " "(``**``). Originalmente proposto pela :pep:`448`." -#: ../../reference/expressions.rst:1138 +#: ../../reference/expressions.rst:1146 msgid "" "A call always returns some value, possibly ``None``, unless it raises an " "exception. How this value is computed depends on the type of the callable " @@ -1787,33 +1874,37 @@ msgstr "" "levanta uma exceção. A forma como esse valor é calculado depende do tipo do " "objeto chamável." -#: ../../reference/expressions.rst:1142 +#: ../../reference/expressions.rst:1150 msgid "If it is---" msgstr "Se for..." -#: ../../reference/expressions.rst:1144 +#: ../../reference/expressions.rst:1152 msgid "a user-defined function:" msgstr "uma função definida por usuário:" -#: ../../reference/expressions.rst:1151 +#: ../../reference/expressions.rst:1159 msgid "" "The code block for the function is executed, passing it the argument list. " "The first thing the code block will do is bind the formal parameters to the " "arguments; this is described in section :ref:`function`. When the code " "block executes a :keyword:`return` statement, this specifies the return " -"value of the function call." +"value of the function call. If execution reaches the end of the code block " +"without executing a :keyword:`return` statement, the return value is " +"``None``." msgstr "" "O bloco de código da função é executado, passando-lhe a lista de argumentos. " "A primeira coisa que o bloco de código fará é vincular os parâmetros formais " "aos argumentos; isso é descrito na seção :ref:`function`. Quando o bloco de " "código executa uma instrução :keyword:`return`, isso especifica o valor de " -"retorno da chamada de função." +"retorno da chamada de função. Se a execução atingir o final do bloco de " +"código sem executar uma instrução :keyword:`return`, o valor de retorno será " +"``None``." -#: ../../reference/expressions.rst:1157 +#: ../../reference/expressions.rst:1166 msgid "a built-in function or method:" msgstr "um método embutido ou uma função embutida:" -#: ../../reference/expressions.rst:1168 +#: ../../reference/expressions.rst:1177 msgid "" "The result is up to the interpreter; see :ref:`built-in-funcs` for the " "descriptions of built-in functions and methods." @@ -1821,19 +1912,19 @@ msgstr "" "O resultado fica por conta do interpretador; veja :ref:`built-in-funcs` para " "descrições de funções embutidas e métodos embutidos." -#: ../../reference/expressions.rst:1171 +#: ../../reference/expressions.rst:1180 msgid "a class object:" msgstr "um objeto classe:" -#: ../../reference/expressions.rst:1176 +#: ../../reference/expressions.rst:1185 msgid "A new instance of that class is returned." msgstr "Uma nova instância dessa classe é retornada." -#: ../../reference/expressions.rst:1178 +#: ../../reference/expressions.rst:1187 msgid "a class instance method:" msgstr "um método de instância de classe:" -#: ../../reference/expressions.rst:1184 +#: ../../reference/expressions.rst:1193 msgid "" "The corresponding user-defined function is called, with an argument list " "that is one longer than the argument list of the call: the instance becomes " @@ -1843,11 +1934,11 @@ msgstr "" "argumentos que é maior que a lista de argumentos da chamada: a instância se " "torna o primeiro argumento." -#: ../../reference/expressions.rst:1188 +#: ../../reference/expressions.rst:1197 msgid "a class instance:" msgstr "uma instância de classe:" -#: ../../reference/expressions.rst:1193 +#: ../../reference/expressions.rst:1202 msgid "" "The class must define a :meth:`~object.__call__` method; the effect is then " "the same as if that method was called." @@ -1855,11 +1946,11 @@ msgstr "" "A classe deve definir um método :meth:`~object.__call__`; o efeito é então o " "mesmo como se esse método fosse chamado." -#: ../../reference/expressions.rst:1201 ../../reference/expressions.rst:1994 +#: ../../reference/expressions.rst:1210 ../../reference/expressions.rst:2011 msgid "Await expression" msgstr "Expressão await" -#: ../../reference/expressions.rst:1203 +#: ../../reference/expressions.rst:1212 msgid "" "Suspend the execution of :term:`coroutine` on an :term:`awaitable` object. " "Can only be used inside a :term:`coroutine function`." @@ -1867,11 +1958,11 @@ msgstr "" "Suspende a execução de :term:`corrotina` em um objeto :term:`aguardável`. Só " "pode ser usado dentro de uma :term:`função de corrotina`." -#: ../../reference/expressions.rst:1215 +#: ../../reference/expressions.rst:1224 msgid "The power operator" msgstr "O operador de potência" -#: ../../reference/expressions.rst:1221 +#: ../../reference/expressions.rst:1230 msgid "" "The power operator binds more tightly than unary operators on its left; it " "binds less tightly than unary operators on its right. The syntax is:" @@ -1880,7 +1971,7 @@ msgstr "" "unários à sua esquerda; ele se vincula com menos força do que os operadores " "unários à sua direita. A sintaxe é:" -#: ../../reference/expressions.rst:1227 +#: ../../reference/expressions.rst:1236 msgid "" "Thus, in an unparenthesized sequence of power and unary operators, the " "operators are evaluated from right to left (this does not constrain the " @@ -1890,7 +1981,7 @@ msgstr "" "os operadores são avaliados da direita para a esquerda (isso não restringe a " "ordem de avaliação dos operandos): ``-1**2`` resulta em ``-1`` ." -#: ../../reference/expressions.rst:1231 +#: ../../reference/expressions.rst:1240 msgid "" "The power operator has the same semantics as the built-in :func:`pow` " "function, when called with two arguments: it yields its left argument raised " @@ -1902,7 +1993,7 @@ msgstr "" "elevado à potência de seu argumento direito. Os argumentos numéricos são " "primeiro convertidos em um tipo comum e o resultado é desse tipo." -#: ../../reference/expressions.rst:1236 +#: ../../reference/expressions.rst:1245 msgid "" "For int operands, the result has the same type as the operands unless the " "second argument is negative; in that case, all arguments are converted to " @@ -1914,7 +2005,7 @@ msgstr "" "convertidos em ponto flutuante e um resultado ponto flutuante é entregue. " "Por exemplo, ``10**2`` retorna ``100``, mas ``10**-2`` retorna ``0.01``." -#: ../../reference/expressions.rst:1241 +#: ../../reference/expressions.rst:1250 msgid "" "Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`. " "Raising a negative number to a fractional power results in a :class:" @@ -1925,7 +2016,7 @@ msgstr "" "resulta em um número :class:`complex`. (Em versões anteriores, levantava :" "exc:`ValueError`.)" -#: ../../reference/expressions.rst:1245 +#: ../../reference/expressions.rst:1254 msgid "" "This operation can be customized using the special :meth:`~object.__pow__` " "and :meth:`~object.__rpow__` methods." @@ -1933,16 +2024,16 @@ msgstr "" "Esta operação pode ser personalizada usando os métodos especial :meth:" "`~object.__pow__` e :meth:`~object.__rpow__`." -#: ../../reference/expressions.rst:1251 +#: ../../reference/expressions.rst:1260 msgid "Unary arithmetic and bitwise operations" msgstr "Operações aritméticas unárias e bit a bit" -#: ../../reference/expressions.rst:1257 +#: ../../reference/expressions.rst:1266 msgid "All unary arithmetic and bitwise operations have the same priority:" msgstr "" "Todas as operações aritméticas unárias e bit a bit têm a mesma prioridade:" -#: ../../reference/expressions.rst:1268 +#: ../../reference/expressions.rst:1277 msgid "" "The unary ``-`` (minus) operator yields the negation of its numeric " "argument; the operation can be overridden with the :meth:`~object.__neg__` " @@ -1951,7 +2042,7 @@ msgstr "" "O operador unário ``-`` (menos) produz a negação de seu argumento numérico; " "a operação pode ser substituída pelo método especial :meth:`~object.__neg__`." -#: ../../reference/expressions.rst:1276 +#: ../../reference/expressions.rst:1285 msgid "" "The unary ``+`` (plus) operator yields its numeric argument unchanged; the " "operation can be overridden with the :meth:`~object.__pos__` special method." @@ -1959,7 +2050,7 @@ msgstr "" "O operador unário ``+`` (mais) produz seu argumento numérico inalterado; a " "operação pode ser substituída pelo método especial :meth:`~object.__pos__`." -#: ../../reference/expressions.rst:1283 +#: ../../reference/expressions.rst:1292 msgid "" "The unary ``~`` (invert) operator yields the bitwise inversion of its " "integer argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. " @@ -1971,7 +2062,7 @@ msgstr "" "Aplica-se apenas a números inteiros ou a objetos personalizados que " "substituem o método especial :meth:`~object.__invert__`." -#: ../../reference/expressions.rst:1292 +#: ../../reference/expressions.rst:1301 msgid "" "In all three cases, if the argument does not have the proper type, a :exc:" "`TypeError` exception is raised." @@ -1979,11 +2070,11 @@ msgstr "" "Em todos os três casos, se o argumento não tiver o tipo adequado, uma " "exceção :exc:`TypeError` é levantada." -#: ../../reference/expressions.rst:1299 +#: ../../reference/expressions.rst:1308 msgid "Binary arithmetic operations" msgstr "Operações binárias aritméticas" -#: ../../reference/expressions.rst:1303 +#: ../../reference/expressions.rst:1312 msgid "" "The binary arithmetic operations have the conventional priority levels. " "Note that some of these operations also apply to certain non-numeric types. " @@ -1996,7 +2087,7 @@ msgstr "" "dois níveis, um para operadores multiplicativos e outro para operadores " "aditivos:" -#: ../../reference/expressions.rst:1318 +#: ../../reference/expressions.rst:1327 msgid "" "The ``*`` (multiplication) operator yields the product of its arguments. " "The arguments must either both be numbers, or one argument must be an " @@ -2012,7 +2103,7 @@ msgstr "" "repetição da sequência; um fator de repetição negativo produz uma sequência " "vazia." -#: ../../reference/expressions.rst:1324 +#: ../../reference/expressions.rst:1333 msgid "" "This operation can be customized using the special :meth:`~object.__mul__` " "and :meth:`~object.__rmul__` methods." @@ -2020,7 +2111,7 @@ msgstr "" "Esta operação pode ser personalizada usando os métodos especial :meth:" "`~object.__mul__` e :meth:`~object.__rmul__`." -#: ../../reference/expressions.rst:1331 +#: ../../reference/expressions.rst:1340 msgid "" "The ``@`` (at) operator is intended to be used for matrix multiplication. " "No builtin Python types implement this operator." @@ -2028,7 +2119,7 @@ msgstr "" "O operador ``@`` (arroba) deve ser usado para multiplicação de matrizes. " "Nenhum tipo embutido do Python implementa este operador." -#: ../../reference/expressions.rst:1334 +#: ../../reference/expressions.rst:1343 msgid "" "This operation can be customized using the special :meth:`~object." "__matmul__` and :meth:`~object.__rmatmul__` methods." @@ -2036,7 +2127,7 @@ msgstr "" "Esta operação pode ser personalizada usando os métodos especial :meth:" "`~object.__matmul__` e :meth:`~object.__rmatmul__`." -#: ../../reference/expressions.rst:1345 +#: ../../reference/expressions.rst:1354 msgid "" "The ``/`` (division) and ``//`` (floor division) operators yield the " "quotient of their arguments. The numeric arguments are first converted to a " @@ -2052,7 +2143,7 @@ msgstr "" "resultado é o da divisão matemática com a função 'floor' aplicada ao " "resultado. A divisão por zero levanta a exceção :exc:`ZeroDivisionError`." -#: ../../reference/expressions.rst:1352 +#: ../../reference/expressions.rst:1361 msgid "" "The division operation can be customized using the special :meth:`~object." "__truediv__` and :meth:`~object.__rtruediv__` methods. The floor division " @@ -2064,7 +2155,7 @@ msgstr "" "divisão pelo piso pode ser personalizada usando os métodos especiais :meth:" "`~object.__floordiv__` e :meth:`~object.__rfloordiv__`." -#: ../../reference/expressions.rst:1361 +#: ../../reference/expressions.rst:1370 msgid "" "The ``%`` (modulo) operator yields the remainder from the division of the " "first argument by the second. The numeric arguments are first converted to " @@ -2084,7 +2175,7 @@ msgstr "" "seu segundo operando (ou zero); o valor absoluto do resultado é estritamente " "menor que o valor absoluto do segundo operando [#]_." -#: ../../reference/expressions.rst:1370 +#: ../../reference/expressions.rst:1379 msgid "" "The floor division and modulo operators are connected by the following " "identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also " @@ -2096,7 +2187,7 @@ msgstr "" "estão conectados com a função embutida :func:`divmod`: ``divmod(x, y) == (x//" "y, x%y)``. [#]_." -#: ../../reference/expressions.rst:1375 +#: ../../reference/expressions.rst:1384 msgid "" "In addition to performing the modulo operation on numbers, the ``%`` " "operator is also overloaded by string objects to perform old-style string " @@ -2110,7 +2201,7 @@ msgstr "" "formatação de string é descrita na Referência da Biblioteca Python, seção :" "ref:`old-string-formatting`." -#: ../../reference/expressions.rst:1380 +#: ../../reference/expressions.rst:1389 msgid "" "The *modulo* operation can be customized using the special :meth:`~object." "__mod__` and :meth:`~object.__rmod__` methods." @@ -2118,7 +2209,7 @@ msgstr "" "A operação *módulo* pode ser personalizada usando os métodos especial :meth:" "`~object.__mod__` e :meth:`~object.__rmod__`." -#: ../../reference/expressions.rst:1383 +#: ../../reference/expressions.rst:1392 msgid "" "The floor division operator, the modulo operator, and the :func:`divmod` " "function are not defined for complex numbers. Instead, convert to a " @@ -2128,7 +2219,7 @@ msgstr "" "`divmod` não são definidos para números complexos. Em vez disso, converta " "para um número de ponto flutuante usando a função :func:`abs` se apropriado." -#: ../../reference/expressions.rst:1392 +#: ../../reference/expressions.rst:1401 msgid "" "The ``+`` (addition) operator yields the sum of its arguments. The " "arguments must either both be numbers or both be sequences of the same " @@ -2140,7 +2231,7 @@ msgstr "" "são convertidos para um tipo comum e depois somados. Neste último caso, as " "sequências são concatenadas." -#: ../../reference/expressions.rst:1397 +#: ../../reference/expressions.rst:1406 msgid "" "This operation can be customized using the special :meth:`~object.__add__` " "and :meth:`~object.__radd__` methods." @@ -2148,7 +2239,7 @@ msgstr "" "Esta operação pode ser personalizada usando os métodos especial :meth:" "`~object.__add__` e :meth:`~object.__radd__`." -#: ../../reference/expressions.rst:1405 +#: ../../reference/expressions.rst:1414 msgid "" "The ``-`` (subtraction) operator yields the difference of its arguments. " "The numeric arguments are first converted to a common type." @@ -2156,7 +2247,7 @@ msgstr "" "O operador ``-`` (subtração) produz a diferença de seus argumentos. Os " "argumentos numéricos são primeiro convertidos em um tipo comum." -#: ../../reference/expressions.rst:1408 +#: ../../reference/expressions.rst:1417 msgid "" "This operation can be customized using the special :meth:`~object.__sub__` " "and :meth:`~object.__rsub__` methods." @@ -2164,18 +2255,18 @@ msgstr "" "Esta operação pode ser personalizada usando os métodos especial :meth:" "`~object.__sub__` e :meth:`~object.__rsub__`." -#: ../../reference/expressions.rst:1415 +#: ../../reference/expressions.rst:1424 msgid "Shifting operations" msgstr "Operações de deslocamento" -#: ../../reference/expressions.rst:1422 +#: ../../reference/expressions.rst:1431 msgid "" "The shifting operations have lower priority than the arithmetic operations:" msgstr "" "As operações de deslocamento têm menor prioridade que as operações " "aritméticas:" -#: ../../reference/expressions.rst:1427 +#: ../../reference/expressions.rst:1436 msgid "" "These operators accept integers as arguments. They shift the first argument " "to the left or right by the number of bits given by the second argument." @@ -2184,7 +2275,7 @@ msgstr "" "primeiro argumento para a esquerda ou para a direita pelo número de bits " "fornecido pelo segundo argumento." -#: ../../reference/expressions.rst:1430 +#: ../../reference/expressions.rst:1439 msgid "" "The left shift operation can be customized using the special :meth:`~object." "__lshift__` and :meth:`~object.__rlshift__` methods. The right shift " @@ -2196,7 +2287,7 @@ msgstr "" "A operação de deslocamento à direita pode ser personalizada usando os " "métodos especiais :meth:`~object.__rshift__` e :meth:`~object.__rrshift__`." -#: ../../reference/expressions.rst:1437 +#: ../../reference/expressions.rst:1446 msgid "" "A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A " "left shift by *n* bits is defined as multiplication with ``pow(2,n)``." @@ -2205,16 +2296,16 @@ msgstr "" "piso por ``pow(2,n)``. Um deslocamento à esquerda por *n* bits é definido " "como multiplicação com ``pow(2,n)``." -#: ../../reference/expressions.rst:1444 +#: ../../reference/expressions.rst:1453 msgid "Binary bitwise operations" msgstr "Operações binárias bit a bit" -#: ../../reference/expressions.rst:1448 +#: ../../reference/expressions.rst:1457 msgid "Each of the three bitwise operations has a different priority level:" msgstr "" "Cada uma das três operações bit a bit tem um nível de prioridade diferente:" -#: ../../reference/expressions.rst:1459 +#: ../../reference/expressions.rst:1468 msgid "" "The ``&`` operator yields the bitwise AND of its arguments, which must be " "integers or one of them must be a custom object overriding :meth:`~object." @@ -2224,7 +2315,7 @@ msgstr "" "ser inteiros ou um deles deve ser um objeto personalizado substituindo os " "métodos especiais :meth:`~object.__and__` ou :meth:`~object.__rand__`." -#: ../../reference/expressions.rst:1468 +#: ../../reference/expressions.rst:1477 msgid "" "The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, " "which must be integers or one of them must be a custom object overriding :" @@ -2235,7 +2326,7 @@ msgstr "" "sobrescrevendo os métodos especiais :meth:`~object.__xor__` ou :meth:" "`~object.__rxor__`." -#: ../../reference/expressions.rst:1477 +#: ../../reference/expressions.rst:1486 msgid "" "The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which " "must be integers or one of them must be a custom object overriding :meth:" @@ -2245,11 +2336,11 @@ msgstr "" "ser inteiros ou um deles deve ser um objeto personalizado sobrescrevendo os " "métodos especiais :meth:`~object.__or__` ou :meth:`~object.__ror__`." -#: ../../reference/expressions.rst:1485 +#: ../../reference/expressions.rst:1494 msgid "Comparisons" msgstr "Comparações" -#: ../../reference/expressions.rst:1497 +#: ../../reference/expressions.rst:1506 msgid "" "Unlike C, all comparison operations in Python have the same priority, which " "is lower than that of any arithmetic, shifting or bitwise operation. Also " @@ -2261,7 +2352,7 @@ msgstr "" "ou bit a bit. Também diferentemente de C, expressões como ``a < b < c`` têm " "a interpretação que é convencional em matemática:" -#: ../../reference/expressions.rst:1507 +#: ../../reference/expressions.rst:1516 msgid "" "Comparisons yield boolean values: ``True`` or ``False``. Custom :dfn:`rich " "comparison methods` may return non-boolean values. In this case Python will " @@ -2271,7 +2362,7 @@ msgstr "" "de comparação rica` personalizados podem retornar valores não booleanos. " "Neste caso, o Python chamará :func:`bool` nesse valor em contextos booleanos." -#: ../../reference/expressions.rst:1513 +#: ../../reference/expressions.rst:1522 msgid "" "Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent " "to ``x < y and y <= z``, except that ``y`` is evaluated only once (but in " @@ -2283,7 +2374,7 @@ msgstr "" "uma vez (mas em ambos os casos ``z`` não é avaliado quando ``x < y`` é " "considerado falso)." -#: ../../reference/expressions.rst:1517 +#: ../../reference/expressions.rst:1526 msgid "" "Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, " "*op2*, ..., *opN* are comparison operators, then ``a op1 b op2 c ... y opN " @@ -2295,7 +2386,7 @@ msgstr "" "opN z`` é equivalente a ``a op1 b e b op2 c e ... y opN z``, exceto que cada " "expressão é avaliada no máximo uma vez." -#: ../../reference/expressions.rst:1522 +#: ../../reference/expressions.rst:1531 msgid "" "Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* " "and *c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not " @@ -2305,11 +2396,11 @@ msgstr "" "*a* e *c*, de modo que, por exemplo, ``x < y > z`` é perfeitamente válido " "(embora talvez não seja bonito)." -#: ../../reference/expressions.rst:1529 +#: ../../reference/expressions.rst:1538 msgid "Value comparisons" msgstr "Comparações de valor" -#: ../../reference/expressions.rst:1531 +#: ../../reference/expressions.rst:1540 msgid "" "The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the " "values of two objects. The objects do not need to have the same type." @@ -2317,7 +2408,7 @@ msgstr "" "Os operadores ``<``, ``>``, ``==``, ``>=``, ``<=`` e ``!=`` comparam os " "valores de dois objetos. Os objetos não precisam ser do mesmo tipo." -#: ../../reference/expressions.rst:1534 +#: ../../reference/expressions.rst:1543 msgid "" "Chapter :ref:`objects` states that objects have a value (in addition to type " "and identity). The value of an object is a rather abstract notion in " @@ -2338,7 +2429,7 @@ msgstr "" "definindo o valor de um objeto indiretamente, por meio de sua implementação " "de comparação." -#: ../../reference/expressions.rst:1543 +#: ../../reference/expressions.rst:1552 msgid "" "Because all types are (direct or indirect) subtypes of :class:`object`, they " "inherit the default comparison behavior from :class:`object`. Types can " @@ -2351,7 +2442,7 @@ msgstr "" "`métodos de comparação rica` como :meth:`~object.__lt__`, descrito em :ref:" "`customization`." -#: ../../reference/expressions.rst:1549 +#: ../../reference/expressions.rst:1558 msgid "" "The default behavior for equality comparison (``==`` and ``!=``) is based on " "the identity of the objects. Hence, equality comparison of instances with " @@ -2367,7 +2458,7 @@ msgstr "" "desigualdade. Uma motivação para este comportamento padrão é o desejo de que " "todos os objetos sejam reflexivos (ou seja, ``x is y`` implica ``x == y``)." -#: ../../reference/expressions.rst:1556 +#: ../../reference/expressions.rst:1565 msgid "" "A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not " "provided; an attempt raises :exc:`TypeError`. A motivation for this default " @@ -2377,7 +2468,7 @@ msgstr "" "fornecida; uma tentativa levanta :exc:`TypeError`. Uma motivação para este " "comportamento padrão é a falta de um invariante semelhante ao da igualdade." -#: ../../reference/expressions.rst:1560 +#: ../../reference/expressions.rst:1569 msgid "" "The behavior of the default equality comparison, that instances with " "different identities are always unequal, may be in contrast to what types " @@ -2391,7 +2482,7 @@ msgstr "" "baseada em valor. Esses tipos precisarão personalizar seu comportamento de " "comparação e, de fato, vários tipos embutidos fizeram isso." -#: ../../reference/expressions.rst:1566 +#: ../../reference/expressions.rst:1575 msgid "" "The following list describes the comparison behavior of the most important " "built-in types." @@ -2399,7 +2490,7 @@ msgstr "" "A lista a seguir descreve o comportamento de comparação dos tipos embutidos " "mais importantes." -#: ../../reference/expressions.rst:1569 +#: ../../reference/expressions.rst:1578 msgid "" "Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard " "library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can " @@ -2415,7 +2506,7 @@ msgstr "" "limites dos tipos envolvidos, eles comparam matematicamente " "(algoritmicamente) corretos sem perda de precisão." -#: ../../reference/expressions.rst:1576 +#: ../../reference/expressions.rst:1585 msgid "" "The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are " "special. Any ordered comparison of a number to a not-a-number value is " @@ -2431,7 +2522,7 @@ msgstr "" "float('NaN')``, ``3 < x``, ``x < 3`` e ``x == x`` são todos falsos, enquanto " "``x != x`` é verdadeiro. Esse comportamento é compatível com IEEE 754." -#: ../../reference/expressions.rst:1583 +#: ../../reference/expressions.rst:1592 msgid "" "``None`` and :data:`NotImplemented` are singletons. :PEP:`8` advises that " "comparisons for singletons should always be done with ``is`` or ``is not``, " @@ -2441,7 +2532,7 @@ msgstr "" "comparações para singletons devem sempre ser feitas com ``is`` ou ``is " "not``, nunca com os operadores de igualdade." -#: ../../reference/expressions.rst:1587 +#: ../../reference/expressions.rst:1596 msgid "" "Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be " "compared within and across their types. They compare lexicographically " @@ -2451,7 +2542,7 @@ msgstr "" "podem ser comparadas dentro e entre seus tipos. Eles comparam " "lexicograficamente usando os valores numéricos de seus elementos." -#: ../../reference/expressions.rst:1591 +#: ../../reference/expressions.rst:1600 msgid "" "Strings (instances of :class:`str`) compare lexicographically using the " "numerical Unicode code points (the result of the built-in function :func:" @@ -2461,11 +2552,11 @@ msgstr "" "usando os pontos de código Unicode numéricos (o resultado da função " "embutida :func:`ord`) de seus caracteres. [#]_" -#: ../../reference/expressions.rst:1595 +#: ../../reference/expressions.rst:1604 msgid "Strings and binary sequences cannot be directly compared." msgstr "Strings e sequências binárias não podem ser comparadas diretamente." -#: ../../reference/expressions.rst:1597 +#: ../../reference/expressions.rst:1606 msgid "" "Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) " "can be compared only within each of their types, with the restriction that " @@ -2479,7 +2570,7 @@ msgstr "" "de igualdade entre esses tipos resulta em desigualdade, e a comparação " "ordenada entre esses tipos levanta :exc:`TypeError`." -#: ../../reference/expressions.rst:1603 +#: ../../reference/expressions.rst:1612 msgid "" "Sequences compare lexicographically using comparison of corresponding " "elements. The built-in containers typically assume identical objects are " @@ -2492,14 +2583,14 @@ msgstr "" "igualdade para objetos idênticos para melhorar o desempenho e manter seus " "invariantes internos." -#: ../../reference/expressions.rst:1608 +#: ../../reference/expressions.rst:1617 msgid "" "Lexicographical comparison between built-in collections works as follows:" msgstr "" "A comparação lexicográfica entre coleções embutidas funciona da seguinte " "forma:" -#: ../../reference/expressions.rst:1610 +#: ../../reference/expressions.rst:1619 msgid "" "For two collections to compare equal, they must be of the same type, have " "the same length, and each pair of corresponding elements must compare equal " @@ -2510,7 +2601,7 @@ msgstr "" "ser comparado igual (por exemplo, ``[1,2] == (1,2)`` é false porque o tipo " "não é o mesmo)." -#: ../../reference/expressions.rst:1615 +#: ../../reference/expressions.rst:1624 msgid "" "Collections that support order comparison are ordered the same as their " "first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same " @@ -2524,7 +2615,7 @@ msgstr "" "existir, a coleção mais curta é ordenada primeiro (por exemplo, ``[1,2] < " "[1,2,3]`` é verdadeiro)." -#: ../../reference/expressions.rst:1621 +#: ../../reference/expressions.rst:1630 msgid "" "Mappings (instances of :class:`dict`) compare equal if and only if they have " "equal ``(key, value)`` pairs. Equality comparison of the keys and values " @@ -2534,14 +2625,14 @@ msgstr "" "eles tiverem pares ``(chave, valor)`` iguais. A comparação de igualdade das " "chaves e valores reforça a reflexividade." -#: ../../reference/expressions.rst:1625 +#: ../../reference/expressions.rst:1634 msgid "" "Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`." msgstr "" "Comparações de ordem (``<``, ``>``, ``<=`` e ``>=``) levantam :exc:" "`TypeError`." -#: ../../reference/expressions.rst:1627 +#: ../../reference/expressions.rst:1636 msgid "" "Sets (instances of :class:`set` or :class:`frozenset`) can be compared " "within and across their types." @@ -2549,7 +2640,7 @@ msgstr "" "Conjuntos (instâncias de :class:`set` ou :class:`frozenset`) podem ser " "comparados dentro e entre seus tipos." -#: ../../reference/expressions.rst:1630 +#: ../../reference/expressions.rst:1639 msgid "" "They define order comparison operators to mean subset and superset tests. " "Those relations do not define total orderings (for example, the two sets " @@ -2567,11 +2658,11 @@ msgstr "" "ordenação total (por exemplo, :func:`min`, :func:`max` e :func:`sorted` " "produzem resultados indefinidos dada uma lista de conjuntos como entradas) ." -#: ../../reference/expressions.rst:1638 +#: ../../reference/expressions.rst:1647 msgid "Comparison of sets enforces reflexivity of its elements." msgstr "A comparação de conjuntos reforça a reflexividade de seus elementos." -#: ../../reference/expressions.rst:1640 +#: ../../reference/expressions.rst:1649 msgid "" "Most other built-in types have no comparison methods implemented, so they " "inherit the default comparison behavior." @@ -2579,7 +2670,7 @@ msgstr "" "A maioria dos outros tipos embutidos não possui métodos de comparação " "implementados, portanto, eles herdam o comportamento de comparação padrão." -#: ../../reference/expressions.rst:1643 +#: ../../reference/expressions.rst:1652 msgid "" "User-defined classes that customize their comparison behavior should follow " "some consistency rules, if possible:" @@ -2587,7 +2678,7 @@ msgstr "" "As classes definidas pelo usuário que personalizam seu comportamento de " "comparação devem seguir algumas regras de consistência, se possível:" -#: ../../reference/expressions.rst:1646 +#: ../../reference/expressions.rst:1655 msgid "" "Equality comparison should be reflexive. In other words, identical objects " "should compare equal:" @@ -2595,11 +2686,11 @@ msgstr "" "A comparação da igualdade deve ser reflexiva. Em outras palavras, objetos " "idênticos devem ser comparados iguais:" -#: ../../reference/expressions.rst:1649 +#: ../../reference/expressions.rst:1658 msgid "``x is y`` implies ``x == y``" msgstr "``x is y`` implica em ``x == y``" -#: ../../reference/expressions.rst:1651 +#: ../../reference/expressions.rst:1660 msgid "" "Comparison should be symmetric. In other words, the following expressions " "should have the same result:" @@ -2607,23 +2698,23 @@ msgstr "" "A comparação deve ser simétrica. Em outras palavras, as seguintes expressões " "devem ter o mesmo resultado:" -#: ../../reference/expressions.rst:1654 +#: ../../reference/expressions.rst:1663 msgid "``x == y`` and ``y == x``" msgstr "``x == y`` e ``y == x``" -#: ../../reference/expressions.rst:1656 +#: ../../reference/expressions.rst:1665 msgid "``x != y`` and ``y != x``" msgstr "``x != y`` e ``y != x``" -#: ../../reference/expressions.rst:1658 +#: ../../reference/expressions.rst:1667 msgid "``x < y`` and ``y > x``" msgstr "``x < y`` e ``y > x``" -#: ../../reference/expressions.rst:1660 +#: ../../reference/expressions.rst:1669 msgid "``x <= y`` and ``y >= x``" msgstr "``x <= y`` e ``y >= x``" -#: ../../reference/expressions.rst:1662 +#: ../../reference/expressions.rst:1671 msgid "" "Comparison should be transitive. The following (non-exhaustive) examples " "illustrate that:" @@ -2631,15 +2722,15 @@ msgstr "" "A comparação deve ser transitiva. Os seguintes exemplos (não exaustivos) " "ilustram isso:" -#: ../../reference/expressions.rst:1665 +#: ../../reference/expressions.rst:1674 msgid "``x > y and y > z`` implies ``x > z``" msgstr "``x > y and y > z`` implica em ``x > z``" -#: ../../reference/expressions.rst:1667 +#: ../../reference/expressions.rst:1676 msgid "``x < y and y <= z`` implies ``x < z``" msgstr "``x < y and y <= z`` implica em ``x < z``" -#: ../../reference/expressions.rst:1669 +#: ../../reference/expressions.rst:1678 msgid "" "Inverse comparison should result in the boolean negation. In other words, " "the following expressions should have the same result:" @@ -2647,19 +2738,19 @@ msgstr "" "A comparação inversa deve resultar na negação booleana. Em outras palavras, " "as seguintes expressões devem ter o mesmo resultado:" -#: ../../reference/expressions.rst:1672 +#: ../../reference/expressions.rst:1681 msgid "``x == y`` and ``not x != y``" msgstr "``x == y`` e ``not x != y``" -#: ../../reference/expressions.rst:1674 +#: ../../reference/expressions.rst:1683 msgid "``x < y`` and ``not x >= y`` (for total ordering)" msgstr "``x < y`` e ``not x >= y`` (pra classificação total)" -#: ../../reference/expressions.rst:1676 +#: ../../reference/expressions.rst:1685 msgid "``x > y`` and ``not x <= y`` (for total ordering)" msgstr "``x > y`` e ``not x <= y`` (pra classificação total)" -#: ../../reference/expressions.rst:1678 +#: ../../reference/expressions.rst:1687 msgid "" "The last two expressions apply to totally ordered collections (e.g. to " "sequences, but not to sets or mappings). See also the :func:`~functools." @@ -2669,7 +2760,7 @@ msgstr "" "exemplo, a sequências, mas não a conjuntos ou mapeamentos). Veja também o " "decorador :func:`~functools.total_ordering`." -#: ../../reference/expressions.rst:1682 +#: ../../reference/expressions.rst:1691 msgid "" "The :func:`hash` result should be consistent with equality. Objects that are " "equal should either have the same hash value, or be marked as unhashable." @@ -2677,7 +2768,7 @@ msgstr "" "O resultado :func:`hash` deve ser consistente com a igualdade. Objetos " "iguais devem ter o mesmo valor de hash ou ser marcados como não-hasheáveis." -#: ../../reference/expressions.rst:1686 +#: ../../reference/expressions.rst:1695 msgid "" "Python does not enforce these consistency rules. In fact, the not-a-number " "values are an example for not following these rules." @@ -2685,11 +2776,11 @@ msgstr "" "Python não impõe essas regras de consistência. Na verdade, os valores não " "numéricos são um exemplo de não cumprimento dessas regras." -#: ../../reference/expressions.rst:1695 +#: ../../reference/expressions.rst:1704 msgid "Membership test operations" msgstr "Operações de teste de pertinência" -#: ../../reference/expressions.rst:1697 +#: ../../reference/expressions.rst:1706 msgid "" "The operators :keyword:`in` and :keyword:`not in` test for membership. ``x " "in s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` " @@ -2708,7 +2799,7 @@ msgstr "" "tuple, set, frozenset, dict ou Collections.deque, a expressão ``x in y`` é " "equivalente a ``any(x is e or x == e for e in y)``." -#: ../../reference/expressions.rst:1705 +#: ../../reference/expressions.rst:1714 msgid "" "For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is " "a substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty " @@ -2720,7 +2811,7 @@ msgstr "" "vazias são sempre consideradas uma substring de qualquer outra string, então " "``\"\" in \"abc\"`` retornará ``True``." -#: ../../reference/expressions.rst:1710 +#: ../../reference/expressions.rst:1719 msgid "" "For user-defined classes which define the :meth:`~object.__contains__` " "method, ``x in y`` returns ``True`` if ``y.__contains__(x)`` returns a true " @@ -2730,7 +2821,7 @@ msgstr "" "__contains__`, ``x in y`` retorna ``True`` se ``y.__contains__(x)`` retorna " "um valor verdadeiro, e ``False`` caso contrário." -#: ../../reference/expressions.rst:1714 +#: ../../reference/expressions.rst:1723 msgid "" "For user-defined classes which do not define :meth:`~object.__contains__` " "but do define :meth:`~object.__iter__`, ``x in y`` is ``True`` if some value " @@ -2745,7 +2836,7 @@ msgstr "" "levantada durante a iteração, é como se :keyword:`in` tivesse levantado essa " "exceção." -#: ../../reference/expressions.rst:1720 +#: ../../reference/expressions.rst:1729 msgid "" "Lastly, the old-style iteration protocol is tried: if a class defines :meth:" "`~object.__getitem__`, ``x in y`` is ``True`` if and only if there is a non-" @@ -2760,7 +2851,7 @@ msgstr "" "`IndexError`. (Se qualquer outra exceção for levantada, é como se :keyword:" "`in` levantasse essa exceção)." -#: ../../reference/expressions.rst:1732 +#: ../../reference/expressions.rst:1741 msgid "" "The operator :keyword:`not in` is defined to have the inverse truth value " "of :keyword:`in`." @@ -2768,11 +2859,11 @@ msgstr "" "O operador :keyword:`not in` é definido para ter o valor verdade inverso de :" "keyword:`in`." -#: ../../reference/expressions.rst:1745 +#: ../../reference/expressions.rst:1754 msgid "Identity comparisons" msgstr "Comparações de identidade" -#: ../../reference/expressions.rst:1747 +#: ../../reference/expressions.rst:1756 msgid "" "The operators :keyword:`is` and :keyword:`is not` test for an object's " "identity: ``x is y`` is true if and only if *x* and *y* are the same " @@ -2784,11 +2875,11 @@ msgstr "" "objeto. A identidade de um objeto é determinada usando a função :meth:`id`. " "``x is not y`` produz o valor verdade inverso. [#]_" -#: ../../reference/expressions.rst:1759 +#: ../../reference/expressions.rst:1768 msgid "Boolean operations" msgstr "Operações booleanas" -#: ../../reference/expressions.rst:1770 +#: ../../reference/expressions.rst:1779 msgid "" "In the context of Boolean operations, and also when expressions are used by " "control flow statements, the following values are interpreted as false: " @@ -2806,7 +2897,7 @@ msgstr "" "verdadeiros. Objetos definidos pelo usuário podem personalizar seu valor " "verdade fornecendo um método :meth:`~object.__bool__`." -#: ../../reference/expressions.rst:1779 +#: ../../reference/expressions.rst:1788 msgid "" "The operator :keyword:`not` yields ``True`` if its argument is false, " "``False`` otherwise." @@ -2814,7 +2905,7 @@ msgstr "" "O operador :keyword:`not` produz ``True`` se seu argumento for falso, " "``False`` caso contrário." -#: ../../reference/expressions.rst:1784 +#: ../../reference/expressions.rst:1793 msgid "" "The expression ``x and y`` first evaluates *x*; if *x* is false, its value " "is returned; otherwise, *y* is evaluated and the resulting value is returned." @@ -2823,7 +2914,7 @@ msgstr "" "será retornado; caso contrário, *y* será avaliado e o valor resultante será " "retornado." -#: ../../reference/expressions.rst:1789 +#: ../../reference/expressions.rst:1798 msgid "" "The expression ``x or y`` first evaluates *x*; if *x* is true, its value is " "returned; otherwise, *y* is evaluated and the resulting value is returned." @@ -2832,7 +2923,7 @@ msgstr "" "será retornado; caso contrário, *y* será avaliado e o valor resultante será " "retornado." -#: ../../reference/expressions.rst:1792 +#: ../../reference/expressions.rst:1801 msgid "" "Note that neither :keyword:`and` nor :keyword:`or` restrict the value and " "type they return to ``False`` and ``True``, but rather return the last " @@ -2850,11 +2941,11 @@ msgstr "" "valor, ele retorna um valor booleano independente do tipo de seu argumento " "(por exemplo, ``not 'foo'`` produz ``False`` em vez de ``''``.)" -#: ../../reference/expressions.rst:1808 +#: ../../reference/expressions.rst:1820 msgid "Assignment expressions" msgstr "Expressões de atribuição" -#: ../../reference/expressions.rst:1813 +#: ../../reference/expressions.rst:1825 msgid "" "An assignment expression (sometimes also called a \"named expression\" or " "\"walrus\") assigns an :token:`~python-grammar:expression` to an :token:" @@ -2866,16 +2957,32 @@ msgstr "" "token:`~python-grammar:identifier`, ao mesmo tempo que retorna o valor de :" "token:`~python-grammar:expression`." -#: ../../reference/expressions.rst:1818 +#: ../../reference/expressions.rst:1830 msgid "One common use case is when handling matched regular expressions:" msgstr "" "Um caso de uso comum é ao lidar com expressões regulares correspondentes:" -#: ../../reference/expressions.rst:1825 +#: ../../reference/expressions.rst:1832 +msgid "" +"if matching := pattern.search(data):\n" +" do_something(matching)" +msgstr "" +"if matching := pattern.search(data):\n" +" do_something(matching)" + +#: ../../reference/expressions.rst:1837 msgid "Or, when processing a file stream in chunks:" msgstr "Ou, ao processar um fluxo de arquivos em partes:" -#: ../../reference/expressions.rst:1832 +#: ../../reference/expressions.rst:1839 +msgid "" +"while chunk := file.read(9000):\n" +" process(chunk)" +msgstr "" +"while chunk := file.read(9000):\n" +" process(chunk)" + +#: ../../reference/expressions.rst:1844 msgid "" "Assignment expressions must be surrounded by parentheses when used as " "expression statements and when used as sub-expressions in slicing, " @@ -2891,15 +2998,15 @@ msgstr "" "todos os outros lugares onde eles podem ser usados, os parênteses não são " "necessários, inclusive nas instruções ``if`` e ``while``." -#: ../../reference/expressions.rst:1840 +#: ../../reference/expressions.rst:1852 msgid "See :pep:`572` for more details about assignment expressions." msgstr "Veja :pep:`572` para mais detalhes sobre expressões de atribuição." -#: ../../reference/expressions.rst:1847 +#: ../../reference/expressions.rst:1859 msgid "Conditional expressions" msgstr "Expressões condicionais" -#: ../../reference/expressions.rst:1859 +#: ../../reference/expressions.rst:1871 msgid "" "Conditional expressions (sometimes called a \"ternary operator\") have the " "lowest priority of all Python operations." @@ -2907,7 +3014,7 @@ msgstr "" "Expressões condicionais (às vezes chamadas de \"operador ternário\") têm a " "prioridade mais baixa de todas as operações Python." -#: ../../reference/expressions.rst:1862 +#: ../../reference/expressions.rst:1874 msgid "" "The expression ``x if C else y`` first evaluates the condition, *C* rather " "than *x*. If *C* is true, *x* is evaluated and its value is returned; " @@ -2917,15 +3024,15 @@ msgstr "" "Se *C* for verdadeiro, *x* é avaliado e seu valor é retornado; caso " "contrário, *y* será avaliado e seu valor será retornado." -#: ../../reference/expressions.rst:1866 +#: ../../reference/expressions.rst:1878 msgid "See :pep:`308` for more details about conditional expressions." msgstr "Veja :pep:`308` para mais detalhes sobre expressões condicionais." -#: ../../reference/expressions.rst:1873 +#: ../../reference/expressions.rst:1885 msgid "Lambdas" msgstr "Lambdas" -#: ../../reference/expressions.rst:1884 +#: ../../reference/expressions.rst:1896 msgid "" "Lambda expressions (sometimes called lambda forms) are used to create " "anonymous functions. The expression ``lambda parameters: expression`` yields " @@ -2937,7 +3044,15 @@ msgstr "" "um objeto função. O objeto sem nome se comporta como um objeto de função " "definido com:" -#: ../../reference/expressions.rst:1893 +#: ../../reference/expressions.rst:1900 +msgid "" +"def (parameters):\n" +" return expression" +msgstr "" +"def (parâmetros):\n" +" return expressão" + +#: ../../reference/expressions.rst:1905 msgid "" "See section :ref:`function` for the syntax of parameter lists. Note that " "functions created with lambda expressions cannot contain statements or " @@ -2947,11 +3062,11 @@ msgstr "" "Observe que as funções criadas com expressões lambda não podem conter " "instruções ou anotações." -#: ../../reference/expressions.rst:1901 +#: ../../reference/expressions.rst:1913 msgid "Expression lists" msgstr "Listas de expressões" -#: ../../reference/expressions.rst:1915 +#: ../../reference/expressions.rst:1929 msgid "" "Except when part of a list or set display, an expression list containing at " "least one comma yields a tuple. The length of the tuple is the number of " @@ -2962,7 +3077,7 @@ msgstr "" "comprimento da tupla é o número de expressões na lista. As expressões são " "avaliadas da esquerda para a direita." -#: ../../reference/expressions.rst:1924 +#: ../../reference/expressions.rst:1938 msgid "" "An asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be " "an :term:`iterable`. The iterable is expanded into a sequence of items, " @@ -2974,14 +3089,20 @@ msgstr "" "itens, que são incluídos na nova tupla, lista ou conjunto, no local do " "desempacotamento." -#: ../../reference/expressions.rst:1929 +#: ../../reference/expressions.rst:1943 msgid "" "Iterable unpacking in expression lists, originally proposed by :pep:`448`." msgstr "" "Desempacotamento de iterável em listas de expressões, originalmente proposta " "pela :pep:`448`." -#: ../../reference/expressions.rst:1934 +#: ../../reference/expressions.rst:1946 +msgid "Any item in an expression list may be starred. See :pep:`646`." +msgstr "" +"Qualquer item em uma lista de expressões pode ser estrelado. Veja a :pep:" +"`646`." + +#: ../../reference/expressions.rst:1951 msgid "" "A trailing comma is required only to create a one-item tuple, such as ``1," "``; it is optional in all other cases. A single expression without a " @@ -2994,11 +3115,11 @@ msgstr "" "final não cria uma tupla, mas produz o valor dessa expressão. (Para criar " "uma tupla vazia, use um par vazio de parênteses: ``()``.)" -#: ../../reference/expressions.rst:1945 +#: ../../reference/expressions.rst:1962 msgid "Evaluation order" msgstr "Ordem de avaliação" -#: ../../reference/expressions.rst:1949 +#: ../../reference/expressions.rst:1966 msgid "" "Python evaluates expressions from left to right. Notice that while " "evaluating an assignment, the right-hand side is evaluated before the left-" @@ -3007,7 +3128,7 @@ msgstr "" "Python avalia expressões da esquerda para a direita. Observe que ao avaliar " "uma tarefa, o lado direito é avaliado antes do lado esquerdo." -#: ../../reference/expressions.rst:1952 +#: ../../reference/expressions.rst:1969 msgid "" "In the following lines, expressions will be evaluated in the arithmetic " "order of their suffixes::" @@ -3015,11 +3136,27 @@ msgstr "" "Nas linhas a seguir, as expressões serão avaliadas na ordem aritmética de " "seus sufixos::" -#: ../../reference/expressions.rst:1966 +#: ../../reference/expressions.rst:1972 +msgid "" +"expr1, expr2, expr3, expr4\n" +"(expr1, expr2, expr3, expr4)\n" +"{expr1: expr2, expr3: expr4}\n" +"expr1 + expr2 * (expr3 - expr4)\n" +"expr1(expr2, expr3, *expr4, **expr5)\n" +"expr3, expr4 = expr1, expr2" +msgstr "" +"expr1, expr2, expr3, expr4\n" +"(expr1, expr2, expr3, expr4)\n" +"{expr1: expr2, expr3: expr4}\n" +"expr1 + expr2 * (expr3 - expr4)\n" +"expr1(expr2, expr3, *expr4, **expr5)\n" +"expr3, expr4 = expr1, expr2" + +#: ../../reference/expressions.rst:1983 msgid "Operator precedence" msgstr "Precedência de operadores" -#: ../../reference/expressions.rst:1971 +#: ../../reference/expressions.rst:1988 msgid "" "The following table summarizes the operator precedence in Python, from " "highest precedence (most binding) to lowest precedence (least binding). " @@ -3036,7 +3173,7 @@ msgstr "" "exponenciação e expressões condicionais, que agrupam da direita para a " "esquerda)." -#: ../../reference/expressions.rst:1977 +#: ../../reference/expressions.rst:1994 msgid "" "Note that comparisons, membership tests, and identity tests, all have the " "same precedence and have a left-to-right chaining feature as described in " @@ -3046,23 +3183,23 @@ msgstr "" "todos a mesma precedência e possuem um recurso de encadeamento da esquerda " "para a direita, conforme descrito na seção :ref:`comparisons`." -#: ../../reference/expressions.rst:1983 +#: ../../reference/expressions.rst:2000 msgid "Operator" msgstr "Operador" -#: ../../reference/expressions.rst:1983 +#: ../../reference/expressions.rst:2000 msgid "Description" msgstr "Descrição" -#: ../../reference/expressions.rst:1985 +#: ../../reference/expressions.rst:2002 msgid "``(expressions...)``," msgstr "``(expressions...)``," -#: ../../reference/expressions.rst:1987 +#: ../../reference/expressions.rst:2004 msgid "``[expressions...]``, ``{key: value...}``, ``{expressions...}``" msgstr "``[expressões...]``, ``{chave: valor...}``, ``{expressões...}``" -#: ../../reference/expressions.rst:1985 +#: ../../reference/expressions.rst:2002 msgid "" "Binding or parenthesized expression, list display, dictionary display, set " "display" @@ -3070,40 +3207,40 @@ msgstr "" "Expressão entre parênteses ou de ligação, sintaxe de criação de lista, " "sintaxe de criação de dicionário, sintaxe de criação de conjunto" -#: ../../reference/expressions.rst:1991 +#: ../../reference/expressions.rst:2008 msgid "``x[index]``, ``x[index:index]``, ``x(arguments...)``, ``x.attribute``" msgstr "" "``x[índice]``, ``x[índice:índice]``, ``x(argumentos...)``, ``x.atributo``" -#: ../../reference/expressions.rst:1991 +#: ../../reference/expressions.rst:2008 msgid "Subscription, slicing, call, attribute reference" msgstr "subscrição, fatiamento, chamada, referência a atributo" -#: ../../reference/expressions.rst:1994 +#: ../../reference/expressions.rst:2011 msgid ":keyword:`await x `" msgstr ":keyword:`await x `" -#: ../../reference/expressions.rst:1996 +#: ../../reference/expressions.rst:2013 msgid "``**``" msgstr "``**``" -#: ../../reference/expressions.rst:1996 +#: ../../reference/expressions.rst:2013 msgid "Exponentiation [#]_" msgstr "Exponenciação [#]_" -#: ../../reference/expressions.rst:1998 +#: ../../reference/expressions.rst:2015 msgid "``+x``, ``-x``, ``~x``" msgstr "``+x``, ``-x``, ``~x``" -#: ../../reference/expressions.rst:1998 +#: ../../reference/expressions.rst:2015 msgid "Positive, negative, bitwise NOT" msgstr "positivo, negativo, NEGAÇÃO (NOT) bit a bit" -#: ../../reference/expressions.rst:2000 +#: ../../reference/expressions.rst:2017 msgid "``*``, ``@``, ``/``, ``//``, ``%``" msgstr "``*``, ``@``, ``/``, ``//``, ``%``" -#: ../../reference/expressions.rst:2000 +#: ../../reference/expressions.rst:2017 msgid "" "Multiplication, matrix multiplication, division, floor division, remainder " "[#]_" @@ -3111,47 +3248,47 @@ msgstr "" "Multiplicação, multiplicação de matrizes, divisão, divisão pelo piso, resto " "[#]_" -#: ../../reference/expressions.rst:2004 +#: ../../reference/expressions.rst:2021 msgid "``+``, ``-``" msgstr "``+``, ``-``" -#: ../../reference/expressions.rst:2004 +#: ../../reference/expressions.rst:2021 msgid "Addition and subtraction" msgstr "Adição e subtração" -#: ../../reference/expressions.rst:2006 +#: ../../reference/expressions.rst:2023 msgid "``<<``, ``>>``" msgstr "``<<``, ``>>``" -#: ../../reference/expressions.rst:2006 +#: ../../reference/expressions.rst:2023 msgid "Shifts" msgstr "Deslocamentos" -#: ../../reference/expressions.rst:2008 +#: ../../reference/expressions.rst:2025 msgid "``&``" msgstr "``&``" -#: ../../reference/expressions.rst:2008 +#: ../../reference/expressions.rst:2025 msgid "Bitwise AND" msgstr "E (AND) bit a bit" -#: ../../reference/expressions.rst:2010 +#: ../../reference/expressions.rst:2027 msgid "``^``" msgstr "``^``" -#: ../../reference/expressions.rst:2010 +#: ../../reference/expressions.rst:2027 msgid "Bitwise XOR" msgstr "OU EXCLUSIVO (XOR) bit a bit" -#: ../../reference/expressions.rst:2012 +#: ../../reference/expressions.rst:2029 msgid "``|``" msgstr "``|``" -#: ../../reference/expressions.rst:2012 +#: ../../reference/expressions.rst:2029 msgid "Bitwise OR" msgstr "OU (OR) bit a bit" -#: ../../reference/expressions.rst:2014 +#: ../../reference/expressions.rst:2031 msgid "" ":keyword:`in`, :keyword:`not in`, :keyword:`is`, :keyword:`is not`, ``<``, " "``<=``, ``>``, ``>=``, ``!=``, ``==``" @@ -3159,63 +3296,63 @@ msgstr "" ":keyword:`in`, :keyword:`not in`, :keyword:`is`, :keyword:`is not`, ``<``, " "``<=``, ``>``, ``>=``, ``!=``, ``==``" -#: ../../reference/expressions.rst:2014 +#: ../../reference/expressions.rst:2031 msgid "Comparisons, including membership tests and identity tests" msgstr "Comparações, incluindo testes de pertinência e testes de identidade" -#: ../../reference/expressions.rst:2018 +#: ../../reference/expressions.rst:2035 msgid ":keyword:`not x `" msgstr ":keyword:`not x `" -#: ../../reference/expressions.rst:2018 +#: ../../reference/expressions.rst:2035 msgid "Boolean NOT" msgstr "NEGAÇÃO (NOT) booleana" -#: ../../reference/expressions.rst:2020 +#: ../../reference/expressions.rst:2037 msgid ":keyword:`and`" msgstr ":keyword:`and`" -#: ../../reference/expressions.rst:2020 +#: ../../reference/expressions.rst:2037 msgid "Boolean AND" msgstr "E (AND) booleano" -#: ../../reference/expressions.rst:2022 +#: ../../reference/expressions.rst:2039 msgid ":keyword:`or`" msgstr ":keyword:`or`" -#: ../../reference/expressions.rst:2022 +#: ../../reference/expressions.rst:2039 msgid "Boolean OR" msgstr "OU (OR) booleano" -#: ../../reference/expressions.rst:2024 +#: ../../reference/expressions.rst:2041 msgid ":keyword:`if ` -- :keyword:`!else`" msgstr ":keyword:`if ` -- :keyword:`!else`" -#: ../../reference/expressions.rst:2024 +#: ../../reference/expressions.rst:2041 msgid "Conditional expression" msgstr "Expressão condicional" -#: ../../reference/expressions.rst:2026 +#: ../../reference/expressions.rst:2043 msgid ":keyword:`lambda`" msgstr ":keyword:`lambda`" -#: ../../reference/expressions.rst:2026 +#: ../../reference/expressions.rst:2043 msgid "Lambda expression" msgstr "Expressão lambda" -#: ../../reference/expressions.rst:2028 +#: ../../reference/expressions.rst:2045 msgid "``:=``" msgstr "``:=``" -#: ../../reference/expressions.rst:2028 +#: ../../reference/expressions.rst:2045 msgid "Assignment expression" msgstr "Expressão de atribuição" -#: ../../reference/expressions.rst:2033 +#: ../../reference/expressions.rst:2050 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../reference/expressions.rst:2034 +#: ../../reference/expressions.rst:2051 msgid "" "While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be " "true numerically due to roundoff. For example, and assuming a platform on " @@ -3236,7 +3373,7 @@ msgstr "" "e, portanto, retorna ``-1e-100`` neste caso. Qual abordagem é mais " "apropriada depende da aplicação." -#: ../../reference/expressions.rst:2043 +#: ../../reference/expressions.rst:2060 msgid "" "If x is very close to an exact integer multiple of y, it's possible for ``x//" "y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such cases, " @@ -3248,7 +3385,7 @@ msgstr "" "casos, Python retorna o último resultado, para preservar que ``divmod(x,y)" "[0] * y + x % y`` esteja muito próximo de ``x``." -#: ../../reference/expressions.rst:2048 +#: ../../reference/expressions.rst:2065 msgid "" "The Unicode standard distinguishes between :dfn:`code points` (e.g. U+0041) " "and :dfn:`abstract characters` (e.g. \"LATIN CAPITAL LETTER A\"). While most " @@ -3273,7 +3410,7 @@ msgstr "" "LETTER C), seguido por um :dfn:`caractere de combinação` na posição de " "código U+0327 (COMBINING CEDILLA)." -#: ../../reference/expressions.rst:2059 +#: ../../reference/expressions.rst:2076 msgid "" "The comparison operators on strings compare at the level of Unicode code " "points. This may be counter-intuitive to humans. For example, ``\"\\u00C7\" " @@ -3286,7 +3423,7 @@ msgstr "" "strings representem o mesmo caractere abstrato \"LATIN CAPITAL LETTER C WITH " "CEDILLA\"." -#: ../../reference/expressions.rst:2064 +#: ../../reference/expressions.rst:2081 msgid "" "To compare strings at the level of abstract characters (that is, in a way " "intuitive to humans), use :func:`unicodedata.normalize`." @@ -3294,7 +3431,7 @@ msgstr "" "Para comparar strings no nível de caracteres abstratos (ou seja, de uma " "forma intuitiva para humanos), use :func:`unicodedata.normalize`." -#: ../../reference/expressions.rst:2067 +#: ../../reference/expressions.rst:2084 msgid "" "Due to automatic garbage-collection, free lists, and the dynamic nature of " "descriptors, you may notice seemingly unusual behaviour in certain uses of " @@ -3307,7 +3444,7 @@ msgstr "" "entre métodos de instância ou constantes. Confira a documentação para obter " "mais informações." -#: ../../reference/expressions.rst:2072 +#: ../../reference/expressions.rst:2089 msgid "" "The power operator ``**`` binds less tightly than an arithmetic or bitwise " "unary operator on its right, that is, ``2**-1`` is ``0.5``." @@ -3315,7 +3452,7 @@ msgstr "" "O operador de potência ``**`` liga-se com menos força do que um operador " "aritmético ou unário bit a bit à sua direita, ou seja, ``2**-1`` é ``0.5``." -#: ../../reference/expressions.rst:2075 +#: ../../reference/expressions.rst:2092 msgid "" "The ``%`` operator is also used for string formatting; the same precedence " "applies." @@ -3324,9 +3461,9 @@ msgstr "" "precedência se aplica." #: ../../reference/expressions.rst:8 ../../reference/expressions.rst:393 -#: ../../reference/expressions.rst:448 ../../reference/expressions.rst:1761 -#: ../../reference/expressions.rst:1849 ../../reference/expressions.rst:1875 -#: ../../reference/expressions.rst:1903 +#: ../../reference/expressions.rst:448 ../../reference/expressions.rst:1770 +#: ../../reference/expressions.rst:1810 ../../reference/expressions.rst:1861 +#: ../../reference/expressions.rst:1887 ../../reference/expressions.rst:1915 msgid "expression" msgstr "expressão" @@ -3334,8 +3471,8 @@ msgstr "expressão" msgid "BNF" msgstr "BNF" -#: ../../reference/expressions.rst:28 ../../reference/expressions.rst:1253 -#: ../../reference/expressions.rst:1301 +#: ../../reference/expressions.rst:28 ../../reference/expressions.rst:1262 +#: ../../reference/expressions.rst:1310 msgid "arithmetic" msgstr "aritmética" @@ -3357,9 +3494,9 @@ msgstr "identificador" #: ../../reference/expressions.rst:74 ../../reference/expressions.rst:569 #: ../../reference/expressions.rst:624 ../../reference/expressions.rst:753 -#: ../../reference/expressions.rst:805 ../../reference/expressions.rst:851 -#: ../../reference/expressions.rst:1290 ../../reference/expressions.rst:1339 -#: ../../reference/expressions.rst:1435 +#: ../../reference/expressions.rst:808 ../../reference/expressions.rst:855 +#: ../../reference/expressions.rst:1299 ../../reference/expressions.rst:1348 +#: ../../reference/expressions.rst:1444 msgid "exception" msgstr "exceção" @@ -3399,11 +3536,11 @@ msgstr "tipo" #: ../../reference/expressions.rst:301 ../../reference/expressions.rst:329 #: ../../reference/expressions.rst:372 ../../reference/expressions.rst:393 #: ../../reference/expressions.rst:557 ../../reference/expressions.rst:743 -#: ../../reference/expressions.rst:851 ../../reference/expressions.rst:880 -#: ../../reference/expressions.rst:953 ../../reference/expressions.rst:997 -#: ../../reference/expressions.rst:1145 ../../reference/expressions.rst:1158 -#: ../../reference/expressions.rst:1172 ../../reference/expressions.rst:1179 -#: ../../reference/expressions.rst:1726 ../../reference/expressions.rst:1913 +#: ../../reference/expressions.rst:855 ../../reference/expressions.rst:884 +#: ../../reference/expressions.rst:961 ../../reference/expressions.rst:1005 +#: ../../reference/expressions.rst:1153 ../../reference/expressions.rst:1167 +#: ../../reference/expressions.rst:1181 ../../reference/expressions.rst:1188 +#: ../../reference/expressions.rst:1735 ../../reference/expressions.rst:1927 msgid "object" msgstr "objeto" @@ -3412,7 +3549,7 @@ msgid "parenthesized form" msgstr "forma entre parênteses" #: ../../reference/expressions.rst:162 ../../reference/expressions.rst:393 -#: ../../reference/expressions.rst:997 +#: ../../reference/expressions.rst:1005 msgid "() (parentheses)" msgstr "() (parênteses)" @@ -3424,19 +3561,19 @@ msgstr "sintaxe de criação de tupla" msgid "empty" msgstr "vazia" -#: ../../reference/expressions.rst:175 ../../reference/expressions.rst:880 -#: ../../reference/expressions.rst:953 ../../reference/expressions.rst:1913 +#: ../../reference/expressions.rst:175 ../../reference/expressions.rst:884 +#: ../../reference/expressions.rst:961 ../../reference/expressions.rst:1927 msgid "tuple" msgstr "tupla" -#: ../../reference/expressions.rst:181 ../../reference/expressions.rst:1932 +#: ../../reference/expressions.rst:181 ../../reference/expressions.rst:1949 msgid "comma" msgstr "vírgula" #: ../../reference/expressions.rst:181 ../../reference/expressions.rst:275 #: ../../reference/expressions.rst:301 ../../reference/expressions.rst:329 -#: ../../reference/expressions.rst:947 ../../reference/expressions.rst:997 -#: ../../reference/expressions.rst:1903 +#: ../../reference/expressions.rst:955 ../../reference/expressions.rst:1005 +#: ../../reference/expressions.rst:1915 msgid ", (comma)" msgstr ", (vírgula)" @@ -3453,7 +3590,7 @@ msgstr "for" msgid "in comprehensions" msgstr "em compreensões" -#: ../../reference/expressions.rst:206 ../../reference/expressions.rst:1849 +#: ../../reference/expressions.rst:206 ../../reference/expressions.rst:1861 msgid "if" msgstr "if" @@ -3461,13 +3598,13 @@ msgstr "if" msgid "async for" msgstr "async for" -#: ../../reference/expressions.rst:241 ../../reference/expressions.rst:1197 +#: ../../reference/expressions.rst:241 ../../reference/expressions.rst:1206 msgid "await" msgstr "await" -#: ../../reference/expressions.rst:275 ../../reference/expressions.rst:851 -#: ../../reference/expressions.rst:880 ../../reference/expressions.rst:953 -#: ../../reference/expressions.rst:1903 +#: ../../reference/expressions.rst:275 ../../reference/expressions.rst:855 +#: ../../reference/expressions.rst:884 ../../reference/expressions.rst:961 +#: ../../reference/expressions.rst:1915 msgid "list" msgstr "lista" @@ -3476,7 +3613,7 @@ msgstr "lista" msgid "display" msgstr "sintaxe de criação" -#: ../../reference/expressions.rst:275 ../../reference/expressions.rst:876 +#: ../../reference/expressions.rst:275 ../../reference/expressions.rst:880 msgid "[] (square brackets)" msgstr "[] (colchetes)" @@ -3485,7 +3622,7 @@ msgid "list expression" msgstr "expressão de lista" #: ../../reference/expressions.rst:275 ../../reference/expressions.rst:301 -#: ../../reference/expressions.rst:1903 +#: ../../reference/expressions.rst:1915 msgid "expression list" msgstr "expressão, lista de" @@ -3502,7 +3639,7 @@ msgid "set expression" msgstr "expressão de conjunto" #: ../../reference/expressions.rst:329 ../../reference/expressions.rst:355 -#: ../../reference/expressions.rst:880 +#: ../../reference/expressions.rst:884 msgid "dictionary" msgstr "dicionário" @@ -3522,8 +3659,8 @@ msgstr "par chave/valor" msgid "dictionary expression" msgstr "expressão de dicionário" -#: ../../reference/expressions.rst:329 ../../reference/expressions.rst:947 -#: ../../reference/expressions.rst:1875 +#: ../../reference/expressions.rst:329 ../../reference/expressions.rst:955 +#: ../../reference/expressions.rst:1887 msgid ": (colon)" msgstr ": (dois pontos)" @@ -3535,13 +3672,13 @@ msgstr "em expressões de dicionário" msgid "in dictionary displays" msgstr "em sintaxes de criação de dicionário" -#: ../../reference/expressions.rst:355 ../../reference/expressions.rst:1080 -#: ../../reference/expressions.rst:1920 +#: ../../reference/expressions.rst:355 ../../reference/expressions.rst:1088 +#: ../../reference/expressions.rst:1934 msgid "unpacking" msgstr "desempacotamento" -#: ../../reference/expressions.rst:355 ../../reference/expressions.rst:1110 -#: ../../reference/expressions.rst:1217 +#: ../../reference/expressions.rst:355 ../../reference/expressions.rst:1118 +#: ../../reference/expressions.rst:1226 msgid "**" msgstr "**" @@ -3558,7 +3695,7 @@ msgstr "gerador" msgid "generator expression" msgstr "expressão geradora" -#: ../../reference/expressions.rst:448 ../../reference/expressions.rst:1197 +#: ../../reference/expressions.rst:448 ../../reference/expressions.rst:1206 msgid "keyword" msgstr "palavra reservada" @@ -3570,8 +3707,8 @@ msgstr "yield" msgid "from" msgstr "from" -#: ../../reference/expressions.rst:448 ../../reference/expressions.rst:1145 -#: ../../reference/expressions.rst:1158 ../../reference/expressions.rst:1875 +#: ../../reference/expressions.rst:448 ../../reference/expressions.rst:1153 +#: ../../reference/expressions.rst:1167 ../../reference/expressions.rst:1887 msgid "function" msgstr "função" @@ -3587,7 +3724,7 @@ msgstr "yield from expressão" msgid "StopIteration" msgstr "StopIteration" -#: ../../reference/expressions.rst:624 ../../reference/expressions.rst:805 +#: ../../reference/expressions.rst:624 ../../reference/expressions.rst:808 msgid "GeneratorExit" msgstr "GeneratorExit" @@ -3603,483 +3740,487 @@ msgstr "gerador assíncrono" msgid "StopAsyncIteration" msgstr "StopAsyncIteration" -#: ../../reference/expressions.rst:828 +#: ../../reference/expressions.rst:832 msgid "primary" msgstr "primário" -#: ../../reference/expressions.rst:842 +#: ../../reference/expressions.rst:846 msgid "attribute" msgstr "atributo" -#: ../../reference/expressions.rst:842 +#: ../../reference/expressions.rst:846 msgid "reference" msgstr "referência" -#: ../../reference/expressions.rst:842 +#: ../../reference/expressions.rst:846 msgid ". (dot)" msgstr ". (ponto)" -#: ../../reference/expressions.rst:842 +#: ../../reference/expressions.rst:846 msgid "attribute reference" msgstr "referência de atributo" -#: ../../reference/expressions.rst:851 +#: ../../reference/expressions.rst:855 msgid "AttributeError" msgstr "AttributeError" -#: ../../reference/expressions.rst:851 +#: ../../reference/expressions.rst:855 msgid "module" msgstr "módulo" -#: ../../reference/expressions.rst:876 +#: ../../reference/expressions.rst:880 msgid "subscription" msgstr "subscrição" -#: ../../reference/expressions.rst:880 ../../reference/expressions.rst:953 -#: ../../reference/expressions.rst:1726 +#: ../../reference/expressions.rst:884 ../../reference/expressions.rst:961 +#: ../../reference/expressions.rst:1735 msgid "sequence" msgstr "sequência" -#: ../../reference/expressions.rst:880 +#: ../../reference/expressions.rst:884 msgid "mapping" msgstr "mapeamento" -#: ../../reference/expressions.rst:880 ../../reference/expressions.rst:933 -#: ../../reference/expressions.rst:953 +#: ../../reference/expressions.rst:884 ../../reference/expressions.rst:941 +#: ../../reference/expressions.rst:961 msgid "string" msgstr "string" -#: ../../reference/expressions.rst:880 ../../reference/expressions.rst:933 +#: ../../reference/expressions.rst:884 ../../reference/expressions.rst:941 msgid "item" msgstr "item" -#: ../../reference/expressions.rst:933 +#: ../../reference/expressions.rst:941 msgid "character" msgstr "caractere" -#: ../../reference/expressions.rst:947 +#: ../../reference/expressions.rst:955 msgid "slicing" msgstr "fatiamento" -#: ../../reference/expressions.rst:947 +#: ../../reference/expressions.rst:955 msgid "slice" msgstr "fatia" -#: ../../reference/expressions.rst:979 +#: ../../reference/expressions.rst:987 msgid "start (slice object attribute)" msgstr "start (atributo de objeto fatia)" -#: ../../reference/expressions.rst:979 +#: ../../reference/expressions.rst:987 msgid "stop (slice object attribute)" msgstr "stop (atributo de objeto fatia)" -#: ../../reference/expressions.rst:979 +#: ../../reference/expressions.rst:987 msgid "step (slice object attribute)" msgstr "step (atributo de objeto fatia)" -#: ../../reference/expressions.rst:997 +#: ../../reference/expressions.rst:1005 msgid "callable" msgstr "chamável" -#: ../../reference/expressions.rst:997 ../../reference/expressions.rst:1145 -#: ../../reference/expressions.rst:1158 ../../reference/expressions.rst:1172 -#: ../../reference/expressions.rst:1179 ../../reference/expressions.rst:1189 +#: ../../reference/expressions.rst:1005 ../../reference/expressions.rst:1153 +#: ../../reference/expressions.rst:1167 ../../reference/expressions.rst:1181 +#: ../../reference/expressions.rst:1188 ../../reference/expressions.rst:1198 msgid "call" msgstr "chamada" -#: ../../reference/expressions.rst:997 +#: ../../reference/expressions.rst:1005 msgid "argument" msgstr "argumento" -#: ../../reference/expressions.rst:997 ../../reference/expressions.rst:1030 +#: ../../reference/expressions.rst:1005 ../../reference/expressions.rst:1038 msgid "call semantics" msgstr "semântica de chamadas" -#: ../../reference/expressions.rst:997 +#: ../../reference/expressions.rst:1005 msgid "argument list" msgstr "lista de argumentos" -#: ../../reference/expressions.rst:997 +#: ../../reference/expressions.rst:1005 msgid "= (equals)" msgstr "= (igual)" -#: ../../reference/expressions.rst:997 ../../reference/expressions.rst:1080 -#: ../../reference/expressions.rst:1110 +#: ../../reference/expressions.rst:1005 ../../reference/expressions.rst:1088 +#: ../../reference/expressions.rst:1118 msgid "in function calls" msgstr "em chamadas de função" -#: ../../reference/expressions.rst:1030 +#: ../../reference/expressions.rst:1038 msgid "parameter" msgstr "parâmetro" -#: ../../reference/expressions.rst:1080 ../../reference/expressions.rst:1314 -#: ../../reference/expressions.rst:1920 +#: ../../reference/expressions.rst:1088 ../../reference/expressions.rst:1323 +#: ../../reference/expressions.rst:1934 msgid "* (asterisk)" msgstr "* (asterisco)" -#: ../../reference/expressions.rst:1145 +#: ../../reference/expressions.rst:1153 msgid "user-defined" msgstr "definida por usuário" -#: ../../reference/expressions.rst:1145 +#: ../../reference/expressions.rst:1153 msgid "user-defined function" msgstr "função definida por usuário" -#: ../../reference/expressions.rst:1158 +#: ../../reference/expressions.rst:1167 msgid "built-in function" msgstr "função embutida" -#: ../../reference/expressions.rst:1158 +#: ../../reference/expressions.rst:1167 msgid "method" msgstr "método" -#: ../../reference/expressions.rst:1158 +#: ../../reference/expressions.rst:1167 msgid "built-in method" msgstr "método embutido" -#: ../../reference/expressions.rst:1172 +#: ../../reference/expressions.rst:1181 msgid "class" msgstr "classe" -#: ../../reference/expressions.rst:1172 +#: ../../reference/expressions.rst:1181 msgid "class object" msgstr "objeto classe" -#: ../../reference/expressions.rst:1179 +#: ../../reference/expressions.rst:1188 msgid "class instance" msgstr "instância de classe" -#: ../../reference/expressions.rst:1179 ../../reference/expressions.rst:1189 +#: ../../reference/expressions.rst:1188 ../../reference/expressions.rst:1198 msgid "instance" msgstr "instância" -#: ../../reference/expressions.rst:1189 +#: ../../reference/expressions.rst:1198 msgid "__call__() (object method)" msgstr "__call__() (método objeto)" -#: ../../reference/expressions.rst:1217 +#: ../../reference/expressions.rst:1226 msgid "power" msgstr "potência" -#: ../../reference/expressions.rst:1217 ../../reference/expressions.rst:1253 -#: ../../reference/expressions.rst:1301 ../../reference/expressions.rst:1417 -#: ../../reference/expressions.rst:1446 ../../reference/expressions.rst:1761 +#: ../../reference/expressions.rst:1226 ../../reference/expressions.rst:1262 +#: ../../reference/expressions.rst:1310 ../../reference/expressions.rst:1426 +#: ../../reference/expressions.rst:1455 ../../reference/expressions.rst:1770 msgid "operation" msgstr "operação" -#: ../../reference/expressions.rst:1217 ../../reference/expressions.rst:1262 -#: ../../reference/expressions.rst:1271 ../../reference/expressions.rst:1279 -#: ../../reference/expressions.rst:1314 ../../reference/expressions.rst:1327 -#: ../../reference/expressions.rst:1339 ../../reference/expressions.rst:1357 -#: ../../reference/expressions.rst:1387 ../../reference/expressions.rst:1400 -#: ../../reference/expressions.rst:1417 ../../reference/expressions.rst:1455 -#: ../../reference/expressions.rst:1463 ../../reference/expressions.rst:1472 -#: ../../reference/expressions.rst:1487 ../../reference/expressions.rst:1726 -#: ../../reference/expressions.rst:1735 ../../reference/expressions.rst:1777 -#: ../../reference/expressions.rst:1782 ../../reference/expressions.rst:1787 -#: ../../reference/expressions.rst:1849 ../../reference/expressions.rst:1968 +#: ../../reference/expressions.rst:1226 ../../reference/expressions.rst:1271 +#: ../../reference/expressions.rst:1280 ../../reference/expressions.rst:1288 +#: ../../reference/expressions.rst:1323 ../../reference/expressions.rst:1336 +#: ../../reference/expressions.rst:1348 ../../reference/expressions.rst:1366 +#: ../../reference/expressions.rst:1396 ../../reference/expressions.rst:1409 +#: ../../reference/expressions.rst:1426 ../../reference/expressions.rst:1464 +#: ../../reference/expressions.rst:1472 ../../reference/expressions.rst:1481 +#: ../../reference/expressions.rst:1496 ../../reference/expressions.rst:1735 +#: ../../reference/expressions.rst:1744 ../../reference/expressions.rst:1786 +#: ../../reference/expressions.rst:1791 ../../reference/expressions.rst:1796 +#: ../../reference/expressions.rst:1861 ../../reference/expressions.rst:1985 msgid "operator" msgstr "operador" -#: ../../reference/expressions.rst:1253 +#: ../../reference/expressions.rst:1262 msgid "unary" msgstr "unária" -#: ../../reference/expressions.rst:1253 ../../reference/expressions.rst:1446 -#: ../../reference/expressions.rst:1455 ../../reference/expressions.rst:1463 -#: ../../reference/expressions.rst:1472 +#: ../../reference/expressions.rst:1262 ../../reference/expressions.rst:1455 +#: ../../reference/expressions.rst:1464 ../../reference/expressions.rst:1472 +#: ../../reference/expressions.rst:1481 msgid "bitwise" msgstr "bit a bit" -#: ../../reference/expressions.rst:1262 +#: ../../reference/expressions.rst:1271 msgid "negation" msgstr "negação" -#: ../../reference/expressions.rst:1262 +#: ../../reference/expressions.rst:1271 msgid "minus" msgstr "menos" -#: ../../reference/expressions.rst:1262 ../../reference/expressions.rst:1400 +#: ../../reference/expressions.rst:1271 ../../reference/expressions.rst:1409 msgid "- (minus)" msgstr "- (menos)" -#: ../../reference/expressions.rst:1262 ../../reference/expressions.rst:1271 +#: ../../reference/expressions.rst:1271 ../../reference/expressions.rst:1280 msgid "unary operator" msgstr "operador unário" -#: ../../reference/expressions.rst:1271 +#: ../../reference/expressions.rst:1280 msgid "plus" msgstr "mais" -#: ../../reference/expressions.rst:1271 ../../reference/expressions.rst:1387 +#: ../../reference/expressions.rst:1280 ../../reference/expressions.rst:1396 msgid "+ (plus)" msgstr "+ (mais)" -#: ../../reference/expressions.rst:1279 +#: ../../reference/expressions.rst:1288 msgid "inversion" msgstr "inversão" -#: ../../reference/expressions.rst:1279 +#: ../../reference/expressions.rst:1288 msgid "~ (tilde)" msgstr "~ (til)" -#: ../../reference/expressions.rst:1290 +#: ../../reference/expressions.rst:1299 msgid "TypeError" msgstr "TypeError" -#: ../../reference/expressions.rst:1301 ../../reference/expressions.rst:1446 +#: ../../reference/expressions.rst:1310 ../../reference/expressions.rst:1455 msgid "binary" msgstr "binário" -#: ../../reference/expressions.rst:1314 +#: ../../reference/expressions.rst:1323 msgid "multiplication" msgstr "multiplicação" -#: ../../reference/expressions.rst:1327 +#: ../../reference/expressions.rst:1336 msgid "matrix multiplication" msgstr "multiplicação de matrizes" -#: ../../reference/expressions.rst:1327 +#: ../../reference/expressions.rst:1336 msgid "@ (at)" msgstr "@ (arroba)" -#: ../../reference/expressions.rst:1339 +#: ../../reference/expressions.rst:1348 msgid "ZeroDivisionError" msgstr "ZeroDivisionError" -#: ../../reference/expressions.rst:1339 +#: ../../reference/expressions.rst:1348 msgid "division" msgstr "divisão" -#: ../../reference/expressions.rst:1339 +#: ../../reference/expressions.rst:1348 msgid "/ (slash)" msgstr "/ (barra)" -#: ../../reference/expressions.rst:1339 +#: ../../reference/expressions.rst:1348 msgid "//" msgstr "//" -#: ../../reference/expressions.rst:1357 +#: ../../reference/expressions.rst:1366 msgid "modulo" msgstr "módulo" -#: ../../reference/expressions.rst:1357 +#: ../../reference/expressions.rst:1366 msgid "% (percent)" msgstr "% (porcentagem)" -#: ../../reference/expressions.rst:1387 +#: ../../reference/expressions.rst:1396 msgid "addition" msgstr "adição" -#: ../../reference/expressions.rst:1387 ../../reference/expressions.rst:1400 +#: ../../reference/expressions.rst:1396 ../../reference/expressions.rst:1409 msgid "binary operator" msgstr "operador binário" -#: ../../reference/expressions.rst:1400 +#: ../../reference/expressions.rst:1409 msgid "subtraction" msgstr "substração" -#: ../../reference/expressions.rst:1417 +#: ../../reference/expressions.rst:1426 msgid "shifting" msgstr "deslocamento" -#: ../../reference/expressions.rst:1417 +#: ../../reference/expressions.rst:1426 msgid "<<" msgstr "<<" -#: ../../reference/expressions.rst:1417 +#: ../../reference/expressions.rst:1426 msgid ">>" msgstr ">>" -#: ../../reference/expressions.rst:1435 +#: ../../reference/expressions.rst:1444 msgid "ValueError" msgstr "ValueError" -#: ../../reference/expressions.rst:1455 ../../reference/expressions.rst:1782 +#: ../../reference/expressions.rst:1464 ../../reference/expressions.rst:1791 msgid "and" msgstr "and" -#: ../../reference/expressions.rst:1455 +#: ../../reference/expressions.rst:1464 msgid "& (ampersand)" msgstr "& (e comercial)" -#: ../../reference/expressions.rst:1463 +#: ../../reference/expressions.rst:1472 msgid "xor" msgstr "xor" -#: ../../reference/expressions.rst:1463 +#: ../../reference/expressions.rst:1472 msgid "exclusive" msgstr "exclusivo" -#: ../../reference/expressions.rst:1463 ../../reference/expressions.rst:1472 -#: ../../reference/expressions.rst:1787 +#: ../../reference/expressions.rst:1472 ../../reference/expressions.rst:1481 +#: ../../reference/expressions.rst:1796 msgid "or" msgstr "or" -#: ../../reference/expressions.rst:1463 +#: ../../reference/expressions.rst:1472 msgid "^ (caret)" msgstr "^ (circunflexo)" -#: ../../reference/expressions.rst:1472 +#: ../../reference/expressions.rst:1481 msgid "inclusive" msgstr "inclusive" -#: ../../reference/expressions.rst:1472 +#: ../../reference/expressions.rst:1481 msgid "| (vertical bar)" msgstr "| (barra vertical)" -#: ../../reference/expressions.rst:1487 +#: ../../reference/expressions.rst:1496 msgid "comparison" msgstr "comparação" -#: ../../reference/expressions.rst:1487 +#: ../../reference/expressions.rst:1496 msgid "C" msgstr "C" -#: ../../reference/expressions.rst:1487 +#: ../../reference/expressions.rst:1496 msgid "language" msgstr "linguagem" -#: ../../reference/expressions.rst:1487 +#: ../../reference/expressions.rst:1496 msgid "< (less)" msgstr "< (menor que)" -#: ../../reference/expressions.rst:1487 +#: ../../reference/expressions.rst:1496 msgid "> (greater)" msgstr "> (maior)" -#: ../../reference/expressions.rst:1487 +#: ../../reference/expressions.rst:1496 msgid "<=" msgstr "<=" -#: ../../reference/expressions.rst:1487 +#: ../../reference/expressions.rst:1496 msgid ">=" msgstr ">=" -#: ../../reference/expressions.rst:1487 +#: ../../reference/expressions.rst:1496 msgid "==" msgstr "==" -#: ../../reference/expressions.rst:1487 +#: ../../reference/expressions.rst:1496 msgid "!=" msgstr "!=" -#: ../../reference/expressions.rst:1511 +#: ../../reference/expressions.rst:1520 msgid "chaining" msgstr "encadeamento" -#: ../../reference/expressions.rst:1511 +#: ../../reference/expressions.rst:1520 msgid "comparisons" msgstr "comparações" -#: ../../reference/expressions.rst:1726 +#: ../../reference/expressions.rst:1735 msgid "in" msgstr "in" -#: ../../reference/expressions.rst:1726 +#: ../../reference/expressions.rst:1735 msgid "not in" msgstr "not in" -#: ../../reference/expressions.rst:1726 +#: ../../reference/expressions.rst:1735 msgid "membership" msgstr "pertinência" -#: ../../reference/expressions.rst:1726 ../../reference/expressions.rst:1735 +#: ../../reference/expressions.rst:1735 ../../reference/expressions.rst:1744 msgid "test" msgstr "teste" -#: ../../reference/expressions.rst:1735 +#: ../../reference/expressions.rst:1744 msgid "is" msgstr "is" -#: ../../reference/expressions.rst:1735 +#: ../../reference/expressions.rst:1744 msgid "is not" msgstr "is not" -#: ../../reference/expressions.rst:1735 +#: ../../reference/expressions.rst:1744 msgid "identity" msgstr "identidade" -#: ../../reference/expressions.rst:1761 +#: ../../reference/expressions.rst:1770 msgid "Conditional" msgstr "Condicional" -#: ../../reference/expressions.rst:1761 +#: ../../reference/expressions.rst:1770 msgid "Boolean" msgstr "Booleano" -#: ../../reference/expressions.rst:1777 +#: ../../reference/expressions.rst:1786 msgid "not" msgstr "not" -#: ../../reference/expressions.rst:1801 +#: ../../reference/expressions.rst:1810 msgid ":= (colon equals)" msgstr ":= (dois points igual)" -#: ../../reference/expressions.rst:1801 +#: ../../reference/expressions.rst:1810 msgid "assignment expression" msgstr "expressão de atribuição" -#: ../../reference/expressions.rst:1801 +#: ../../reference/expressions.rst:1810 msgid "walrus operator" msgstr "operador morsa" -#: ../../reference/expressions.rst:1801 +#: ../../reference/expressions.rst:1810 msgid "named expression" msgstr "expressão nomeada" -#: ../../reference/expressions.rst:1849 +#: ../../reference/expressions.rst:1810 +msgid "assignment" +msgstr "atribuição" + +#: ../../reference/expressions.rst:1861 msgid "conditional" msgstr "condicional" -#: ../../reference/expressions.rst:1849 +#: ../../reference/expressions.rst:1861 msgid "ternary" msgstr "ternário" -#: ../../reference/expressions.rst:1849 +#: ../../reference/expressions.rst:1861 msgid "conditional expression" msgstr "expressão condicional" -#: ../../reference/expressions.rst:1849 +#: ../../reference/expressions.rst:1861 msgid "else" msgstr "else" -#: ../../reference/expressions.rst:1875 +#: ../../reference/expressions.rst:1887 msgid "lambda" msgstr "lambda" -#: ../../reference/expressions.rst:1875 +#: ../../reference/expressions.rst:1887 msgid "form" msgstr "função" -#: ../../reference/expressions.rst:1875 +#: ../../reference/expressions.rst:1887 msgid "anonymous" msgstr "anônima" -#: ../../reference/expressions.rst:1875 +#: ../../reference/expressions.rst:1887 msgid "lambda expression" msgstr "expressão lambda" -#: ../../reference/expressions.rst:1920 +#: ../../reference/expressions.rst:1934 msgid "iterable" -msgstr "Iterável" +msgstr "iterável" -#: ../../reference/expressions.rst:1920 +#: ../../reference/expressions.rst:1934 msgid "in expression lists" msgstr "em listas de expressões" -#: ../../reference/expressions.rst:1932 +#: ../../reference/expressions.rst:1949 msgid "trailing" msgstr "ao final" -#: ../../reference/expressions.rst:1947 +#: ../../reference/expressions.rst:1964 msgid "evaluation" msgstr "avaliação" -#: ../../reference/expressions.rst:1947 +#: ../../reference/expressions.rst:1964 msgid "order" msgstr "ordem" -#: ../../reference/expressions.rst:1968 +#: ../../reference/expressions.rst:1985 msgid "precedence" msgstr "precedência" diff --git a/reference/grammar.po b/reference/grammar.po index 75374004f..694b216a9 100644 --- a/reference/grammar.po +++ b/reference/grammar.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 01:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-05-16 14:58+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -60,3 +60,1770 @@ msgstr "" "``|`` para significar a \"escolha ordenada\" do GASE (escrito como ``/`` nas " "gramáticas GASE tradicionais). Veja :pep:`617` para mais detalhes sobre a " "sintaxe da gramática." + +#: ../../reference/grammar.rst:21 +msgid "" +"# PEG grammar for Python\n" +"\n" +"@trailer '''\n" +"void *\n" +"_PyPegen_parse(Parser *p)\n" +"{\n" +" // Initialize keywords\n" +" p->keywords = reserved_keywords;\n" +" p->n_keyword_lists = n_keyword_lists;\n" +" p->soft_keywords = soft_keywords;\n" +"\n" +" // Run parser\n" +" void *result = NULL;\n" +" if (p->start_rule == Py_file_input) {\n" +" result = file_rule(p);\n" +" } else if (p->start_rule == Py_single_input) {\n" +" result = interactive_rule(p);\n" +" } else if (p->start_rule == Py_eval_input) {\n" +" result = eval_rule(p);\n" +" } else if (p->start_rule == Py_func_type_input) {\n" +" result = func_type_rule(p);\n" +" }\n" +"\n" +" return result;\n" +"}\n" +"'''\n" +"\n" +"# ========================= START OF THE GRAMMAR =========================\n" +"\n" +"# General grammatical elements and rules:\n" +"#\n" +"# * Strings with double quotes (\") denote SOFT KEYWORDS\n" +"# * Strings with single quotes (') denote KEYWORDS\n" +"# * Upper case names (NAME) denote tokens in the Grammar/Tokens file\n" +"# * Rule names starting with \"invalid_\" are used for specialized syntax " +"errors\n" +"# - These rules are NOT used in the first pass of the parser.\n" +"# - Only if the first pass fails to parse, a second pass including the " +"invalid\n" +"# rules will be executed.\n" +"# - If the parser fails in the second phase with a generic syntax error, " +"the\n" +"# location of the generic failure of the first pass will be used (this " +"avoids\n" +"# reporting incorrect locations due to the invalid rules).\n" +"# - The order of the alternatives involving invalid rules matter\n" +"# (like any rule in PEG).\n" +"#\n" +"# Grammar Syntax (see PEP 617 for more information):\n" +"#\n" +"# rule_name: expression\n" +"# Optionally, a type can be included right after the rule name, which\n" +"# specifies the return type of the C or Python function corresponding to " +"the\n" +"# rule:\n" +"# rule_name[return_type]: expression\n" +"# If the return type is omitted, then a void * is returned in C and an Any " +"in\n" +"# Python.\n" +"# e1 e2\n" +"# Match e1, then match e2.\n" +"# e1 | e2\n" +"# Match e1 or e2.\n" +"# The first alternative can also appear on the line after the rule name " +"for\n" +"# formatting purposes. In that case, a | must be used before the first\n" +"# alternative, like so:\n" +"# rule_name[return_type]:\n" +"# | first_alt\n" +"# | second_alt\n" +"# ( e )\n" +"# Match e (allows also to use other operators in the group like '(e)*')\n" +"# [ e ] or e?\n" +"# Optionally match e.\n" +"# e*\n" +"# Match zero or more occurrences of e.\n" +"# e+\n" +"# Match one or more occurrences of e.\n" +"# s.e+\n" +"# Match one or more occurrences of e, separated by s. The generated parse " +"tree\n" +"# does not include the separator. This is otherwise identical to (e (s " +"e)*).\n" +"# &e\n" +"# Succeed if e can be parsed, without consuming any input.\n" +"# !e\n" +"# Fail if e can be parsed, without consuming any input.\n" +"# ~\n" +"# Commit to the current alternative, even if it fails to parse.\n" +"# &&e\n" +"# Eager parse e. The parser will not backtrack and will immediately\n" +"# fail with SyntaxError if e cannot be parsed.\n" +"#\n" +"\n" +"# STARTING RULES\n" +"# ==============\n" +"\n" +"file[mod_ty]: a=[statements] ENDMARKER { _PyPegen_make_module(p, a) }\n" +"interactive[mod_ty]: a=statement_newline { _PyAST_Interactive(a, p-" +">arena) }\n" +"eval[mod_ty]: a=expressions NEWLINE* ENDMARKER { _PyAST_Expression(a, p-" +">arena) }\n" +"func_type[mod_ty]: '(' a=[type_expressions] ')' '->' b=expression NEWLINE* " +"ENDMARKER { _PyAST_FunctionType(a, b, p->arena) }\n" +"\n" +"# GENERAL STATEMENTS\n" +"# ==================\n" +"\n" +"statements[asdl_stmt_seq*]: a=statement+ " +"{ (asdl_stmt_seq*)_PyPegen_seq_flatten(p, a) }\n" +"\n" +"statement[asdl_stmt_seq*]: a=compound_stmt " +"{ (asdl_stmt_seq*)_PyPegen_singleton_seq(p, a) } | " +"a[asdl_stmt_seq*]=simple_stmts { a }\n" +"\n" +"statement_newline[asdl_stmt_seq*]:\n" +" | a=compound_stmt NEWLINE { (asdl_stmt_seq*)_PyPegen_singleton_seq(p, " +"a) }\n" +" | simple_stmts\n" +" | NEWLINE { (asdl_stmt_seq*)_PyPegen_singleton_seq(p, CHECK(stmt_ty, " +"_PyAST_Pass(EXTRA))) }\n" +" | ENDMARKER { _PyPegen_interactive_exit(p) }\n" +"\n" +"simple_stmts[asdl_stmt_seq*]:\n" +" | a=simple_stmt !';' NEWLINE { (asdl_stmt_seq*)_PyPegen_singleton_seq(p, " +"a) } # Not needed, there for speedup\n" +" | a[asdl_stmt_seq*]=';'.simple_stmt+ [';'] NEWLINE { a }\n" +"\n" +"# NOTE: assignment MUST precede expression, else parsing a simple " +"assignment\n" +"# will throw a SyntaxError.\n" +"simple_stmt[stmt_ty] (memo):\n" +" | assignment\n" +" | &\"type\" type_alias\n" +" | e=star_expressions { _PyAST_Expr(e, EXTRA) }\n" +" | &'return' return_stmt\n" +" | &('import' | 'from') import_stmt\n" +" | &'raise' raise_stmt\n" +" | 'pass' { _PyAST_Pass(EXTRA) }\n" +" | &'del' del_stmt\n" +" | &'yield' yield_stmt\n" +" | &'assert' assert_stmt\n" +" | 'break' { _PyAST_Break(EXTRA) }\n" +" | 'continue' { _PyAST_Continue(EXTRA) }\n" +" | &'global' global_stmt\n" +" | &'nonlocal' nonlocal_stmt\n" +"\n" +"compound_stmt[stmt_ty]:\n" +" | &('def' | '@' | 'async') function_def\n" +" | &'if' if_stmt\n" +" | &('class' | '@') class_def\n" +" | &('with' | 'async') with_stmt\n" +" | &('for' | 'async') for_stmt\n" +" | &'try' try_stmt\n" +" | &'while' while_stmt\n" +" | match_stmt\n" +"\n" +"# SIMPLE STATEMENTS\n" +"# =================\n" +"\n" +"# NOTE: annotated_rhs may start with 'yield'; yield_expr must start with " +"'yield'\n" +"assignment[stmt_ty]:\n" +" | a=NAME ':' b=expression c=['=' d=annotated_rhs { d }] {\n" +" CHECK_VERSION(\n" +" stmt_ty,\n" +" 6,\n" +" \"Variable annotation syntax is\",\n" +" _PyAST_AnnAssign(CHECK(expr_ty, _PyPegen_set_expr_context(p, a, " +"Store)), b, c, 1, EXTRA)\n" +" ) }\n" +" | a=('(' b=single_target ')' { b }\n" +" | single_subscript_attribute_target) ':' b=expression c=['=' " +"d=annotated_rhs { d }] {\n" +" CHECK_VERSION(stmt_ty, 6, \"Variable annotations syntax is\", " +"_PyAST_AnnAssign(a, b, c, 0, EXTRA)) }\n" +" | a[asdl_expr_seq*]=(z=star_targets '=' { z })+ b=(yield_expr | " +"star_expressions) !'=' tc=[TYPE_COMMENT] {\n" +" _PyAST_Assign(a, b, NEW_TYPE_COMMENT(p, tc), EXTRA) }\n" +" | a=single_target b=augassign ~ c=(yield_expr | star_expressions) {\n" +" _PyAST_AugAssign(a, b->kind, c, EXTRA) }\n" +" | invalid_assignment\n" +"\n" +"annotated_rhs[expr_ty]: yield_expr | star_expressions\n" +"\n" +"augassign[AugOperator*]:\n" +" | '+=' { _PyPegen_augoperator(p, Add) }\n" +" | '-=' { _PyPegen_augoperator(p, Sub) }\n" +" | '*=' { _PyPegen_augoperator(p, Mult) }\n" +" | '@=' { CHECK_VERSION(AugOperator*, 5, \"The '@' operator is\", " +"_PyPegen_augoperator(p, MatMult)) }\n" +" | '/=' { _PyPegen_augoperator(p, Div) }\n" +" | '%=' { _PyPegen_augoperator(p, Mod) }\n" +" | '&=' { _PyPegen_augoperator(p, BitAnd) }\n" +" | '|=' { _PyPegen_augoperator(p, BitOr) }\n" +" | '^=' { _PyPegen_augoperator(p, BitXor) }\n" +" | '<<=' { _PyPegen_augoperator(p, LShift) }\n" +" | '>>=' { _PyPegen_augoperator(p, RShift) }\n" +" | '**=' { _PyPegen_augoperator(p, Pow) }\n" +" | '//=' { _PyPegen_augoperator(p, FloorDiv) }\n" +"\n" +"return_stmt[stmt_ty]:\n" +" | 'return' a=[star_expressions] { _PyAST_Return(a, EXTRA) }\n" +"\n" +"raise_stmt[stmt_ty]:\n" +" | 'raise' a=expression b=['from' z=expression { z }] { _PyAST_Raise(a, " +"b, EXTRA) }\n" +" | 'raise' { _PyAST_Raise(NULL, NULL, EXTRA) }\n" +"\n" +"global_stmt[stmt_ty]: 'global' a[asdl_expr_seq*]=','.NAME+ {\n" +" _PyAST_Global(CHECK(asdl_identifier_seq*, _PyPegen_map_names_to_ids(p, " +"a)), EXTRA) }\n" +"\n" +"nonlocal_stmt[stmt_ty]: 'nonlocal' a[asdl_expr_seq*]=','.NAME+ {\n" +" _PyAST_Nonlocal(CHECK(asdl_identifier_seq*, _PyPegen_map_names_to_ids(p, " +"a)), EXTRA) }\n" +"\n" +"del_stmt[stmt_ty]:\n" +" | 'del' a=del_targets &(';' | NEWLINE) { _PyAST_Delete(a, EXTRA) }\n" +" | invalid_del_stmt\n" +"\n" +"yield_stmt[stmt_ty]: y=yield_expr { _PyAST_Expr(y, EXTRA) }\n" +"\n" +"assert_stmt[stmt_ty]: 'assert' a=expression b=[',' z=expression { z }] " +"{ _PyAST_Assert(a, b, EXTRA) }\n" +"\n" +"import_stmt[stmt_ty]:\n" +" | invalid_import\n" +" | import_name\n" +" | import_from\n" +"\n" +"# Import statements\n" +"# -----------------\n" +"\n" +"import_name[stmt_ty]: 'import' a=dotted_as_names { _PyAST_Import(a, " +"EXTRA) }\n" +"# note below: the ('.' | '...') is necessary because '...' is tokenized as " +"ELLIPSIS\n" +"import_from[stmt_ty]:\n" +" | 'from' a=('.' | '...')* b=dotted_name 'import' c=import_from_targets " +"{\n" +" _PyPegen_checked_future_import(p, b->v.Name.id, c, " +"_PyPegen_seq_count_dots(a), EXTRA) }\n" +" | 'from' a=('.' | '...')+ 'import' b=import_from_targets {\n" +" _PyAST_ImportFrom(NULL, b, _PyPegen_seq_count_dots(a), EXTRA) }\n" +"import_from_targets[asdl_alias_seq*]:\n" +" | '(' a=import_from_as_names [','] ')' { a }\n" +" | import_from_as_names !','\n" +" | '*' { (asdl_alias_seq*)_PyPegen_singleton_seq(p, CHECK(alias_ty, " +"_PyPegen_alias_for_star(p, EXTRA))) }\n" +" | invalid_import_from_targets\n" +"import_from_as_names[asdl_alias_seq*]:\n" +" | a[asdl_alias_seq*]=','.import_from_as_name+ { a }\n" +"import_from_as_name[alias_ty]:\n" +" | a=NAME b=['as' z=NAME { z }] { _PyAST_alias(a->v.Name.id,\n" +" (b) ? ((expr_ty) b)->v.Name." +"id : NULL,\n" +" EXTRA) }\n" +"dotted_as_names[asdl_alias_seq*]:\n" +" | a[asdl_alias_seq*]=','.dotted_as_name+ { a }\n" +"dotted_as_name[alias_ty]:\n" +" | a=dotted_name b=['as' z=NAME { z }] { _PyAST_alias(a->v.Name.id,\n" +" (b) ? ((expr_ty) b)->v." +"Name.id : NULL,\n" +" EXTRA) }\n" +"dotted_name[expr_ty]:\n" +" | a=dotted_name '.' b=NAME { _PyPegen_join_names_with_dot(p, a, b) }\n" +" | NAME\n" +"\n" +"# COMPOUND STATEMENTS\n" +"# ===================\n" +"\n" +"# Common elements\n" +"# ---------------\n" +"\n" +"block[asdl_stmt_seq*] (memo):\n" +" | NEWLINE INDENT a=statements DEDENT { a }\n" +" | simple_stmts\n" +" | invalid_block\n" +"\n" +"decorators[asdl_expr_seq*]: a[asdl_expr_seq*]=('@' f=named_expression " +"NEWLINE { f })+ { a }\n" +"\n" +"# Class definitions\n" +"# -----------------\n" +"\n" +"class_def[stmt_ty]:\n" +" | a=decorators b=class_def_raw { _PyPegen_class_def_decorators(p, a, " +"b) }\n" +" | class_def_raw\n" +"\n" +"class_def_raw[stmt_ty]:\n" +" | invalid_class_def_raw\n" +" | 'class' a=NAME t=[type_params] b=['(' z=[arguments] ')' { z }] ':' " +"c=block {\n" +" _PyAST_ClassDef(a->v.Name.id,\n" +" (b) ? ((expr_ty) b)->v.Call.args : NULL,\n" +" (b) ? ((expr_ty) b)->v.Call.keywords : NULL,\n" +" c, NULL, t, EXTRA) }\n" +"\n" +"# Function definitions\n" +"# --------------------\n" +"\n" +"function_def[stmt_ty]:\n" +" | d=decorators f=function_def_raw { _PyPegen_function_def_decorators(p, " +"d, f) }\n" +" | function_def_raw\n" +"\n" +"function_def_raw[stmt_ty]:\n" +" | invalid_def_raw\n" +" | 'def' n=NAME t=[type_params] '(' params=[params] ')' a=['->' " +"z=expression { z }] ':' tc=[func_type_comment] b=block {\n" +" _PyAST_FunctionDef(n->v.Name.id,\n" +" (params) ? params : CHECK(arguments_ty, " +"_PyPegen_empty_arguments(p)),\n" +" b, NULL, a, NEW_TYPE_COMMENT(p, tc), t, EXTRA) }\n" +" | 'async' 'def' n=NAME t=[type_params] '(' params=[params] ')' a=['->' " +"z=expression { z }] ':' tc=[func_type_comment] b=block {\n" +" CHECK_VERSION(\n" +" stmt_ty,\n" +" 5,\n" +" \"Async functions are\",\n" +" _PyAST_AsyncFunctionDef(n->v.Name.id,\n" +" (params) ? params : CHECK(arguments_ty, " +"_PyPegen_empty_arguments(p)),\n" +" b, NULL, a, NEW_TYPE_COMMENT(p, tc), t, EXTRA)\n" +" ) }\n" +"\n" +"# Function parameters\n" +"# -------------------\n" +"\n" +"params[arguments_ty]:\n" +" | invalid_parameters\n" +" | parameters\n" +"\n" +"parameters[arguments_ty]:\n" +" | a=slash_no_default b[asdl_arg_seq*]=param_no_default* " +"c=param_with_default* d=[star_etc] {\n" +" CHECK_VERSION(arguments_ty, 8, \"Positional-only parameters are\", " +"_PyPegen_make_arguments(p, a, NULL, b, c, d)) }\n" +" | a=slash_with_default b=param_with_default* c=[star_etc] {\n" +" CHECK_VERSION(arguments_ty, 8, \"Positional-only parameters are\", " +"_PyPegen_make_arguments(p, NULL, a, NULL, b, c)) }\n" +" | a[asdl_arg_seq*]=param_no_default+ b=param_with_default* c=[star_etc] " +"{\n" +" _PyPegen_make_arguments(p, NULL, NULL, a, b, c) }\n" +" | a=param_with_default+ b=[star_etc] { _PyPegen_make_arguments(p, NULL, " +"NULL, NULL, a, b)}\n" +" | a=star_etc { _PyPegen_make_arguments(p, NULL, NULL, NULL, NULL, a) }\n" +"\n" +"# Some duplication here because we can't write (',' | &')'),\n" +"# which is because we don't support empty alternatives (yet).\n" +"\n" +"slash_no_default[asdl_arg_seq*]:\n" +" | a[asdl_arg_seq*]=param_no_default+ '/' ',' { a }\n" +" | a[asdl_arg_seq*]=param_no_default+ '/' &')' { a }\n" +"slash_with_default[SlashWithDefault*]:\n" +" | a=param_no_default* b=param_with_default+ '/' " +"',' { _PyPegen_slash_with_default(p, (asdl_arg_seq *)a, b) }\n" +" | a=param_no_default* b=param_with_default+ '/' " +"&')' { _PyPegen_slash_with_default(p, (asdl_arg_seq *)a, b) }\n" +"\n" +"star_etc[StarEtc*]:\n" +" | invalid_star_etc\n" +" | '*' a=param_no_default b=param_maybe_default* c=[kwds] {\n" +" _PyPegen_star_etc(p, a, b, c) }\n" +" | '*' a=param_no_default_star_annotation b=param_maybe_default* c=[kwds] " +"{\n" +" _PyPegen_star_etc(p, a, b, c) }\n" +" | '*' ',' b=param_maybe_default+ c=[kwds] {\n" +" _PyPegen_star_etc(p, NULL, b, c) }\n" +" | a=kwds { _PyPegen_star_etc(p, NULL, NULL, a) }\n" +"\n" +"kwds[arg_ty]:\n" +" | invalid_kwds\n" +" | '**' a=param_no_default { a }\n" +"\n" +"# One parameter. This *includes* a following comma and type comment.\n" +"#\n" +"# There are three styles:\n" +"# - No default\n" +"# - With default\n" +"# - Maybe with default\n" +"#\n" +"# There are two alternative forms of each, to deal with type comments:\n" +"# - Ends in a comma followed by an optional type comment\n" +"# - No comma, optional type comment, must be followed by close paren\n" +"# The latter form is for a final parameter without trailing comma.\n" +"#\n" +"\n" +"param_no_default[arg_ty]:\n" +" | a=param ',' tc=TYPE_COMMENT? { _PyPegen_add_type_comment_to_arg(p, a, " +"tc) }\n" +" | a=param tc=TYPE_COMMENT? &')' { _PyPegen_add_type_comment_to_arg(p, a, " +"tc) }\n" +"param_no_default_star_annotation[arg_ty]:\n" +" | a=param_star_annotation ',' tc=TYPE_COMMENT? " +"{ _PyPegen_add_type_comment_to_arg(p, a, tc) }\n" +" | a=param_star_annotation tc=TYPE_COMMENT? " +"&')' { _PyPegen_add_type_comment_to_arg(p, a, tc) }\n" +"param_with_default[NameDefaultPair*]:\n" +" | a=param c=default ',' tc=TYPE_COMMENT? { _PyPegen_name_default_pair(p, " +"a, c, tc) }\n" +" | a=param c=default tc=TYPE_COMMENT? " +"&')' { _PyPegen_name_default_pair(p, a, c, tc) }\n" +"param_maybe_default[NameDefaultPair*]:\n" +" | a=param c=default? ',' tc=TYPE_COMMENT? " +"{ _PyPegen_name_default_pair(p, a, c, tc) }\n" +" | a=param c=default? tc=TYPE_COMMENT? " +"&')' { _PyPegen_name_default_pair(p, a, c, tc) }\n" +"param[arg_ty]: a=NAME b=annotation? { _PyAST_arg(a->v.Name.id, b, NULL, " +"EXTRA) }\n" +"param_star_annotation[arg_ty]: a=NAME b=star_annotation { _PyAST_arg(a->v." +"Name.id, b, NULL, EXTRA) }\n" +"annotation[expr_ty]: ':' a=expression { a }\n" +"star_annotation[expr_ty]: ':' a=star_expression { a }\n" +"default[expr_ty]: '=' a=expression { a } | invalid_default\n" +"\n" +"# If statement\n" +"# ------------\n" +"\n" +"if_stmt[stmt_ty]:\n" +" | invalid_if_stmt\n" +" | 'if' a=named_expression ':' b=block c=elif_stmt {\n" +" _PyAST_If(a, b, CHECK(asdl_stmt_seq*, _PyPegen_singleton_seq(p, c)), " +"EXTRA) }\n" +" | 'if' a=named_expression ':' b=block c=[else_block] { _PyAST_If(a, b, " +"c, EXTRA) }\n" +"elif_stmt[stmt_ty]:\n" +" | invalid_elif_stmt\n" +" | 'elif' a=named_expression ':' b=block c=elif_stmt {\n" +" _PyAST_If(a, b, CHECK(asdl_stmt_seq*, _PyPegen_singleton_seq(p, c)), " +"EXTRA) }\n" +" | 'elif' a=named_expression ':' b=block c=[else_block] { _PyAST_If(a, b, " +"c, EXTRA) }\n" +"else_block[asdl_stmt_seq*]:\n" +" | invalid_else_stmt\n" +" | 'else' &&':' b=block { b }\n" +"\n" +"# While statement\n" +"# ---------------\n" +"\n" +"while_stmt[stmt_ty]:\n" +" | invalid_while_stmt\n" +" | 'while' a=named_expression ':' b=block c=[else_block] " +"{ _PyAST_While(a, b, c, EXTRA) }\n" +"\n" +"# For statement\n" +"# -------------\n" +"\n" +"for_stmt[stmt_ty]:\n" +" | invalid_for_stmt\n" +" | 'for' t=star_targets 'in' ~ ex=star_expressions ':' tc=[TYPE_COMMENT] " +"b=block el=[else_block] {\n" +" _PyAST_For(t, ex, b, el, NEW_TYPE_COMMENT(p, tc), EXTRA) }\n" +" | 'async' 'for' t=star_targets 'in' ~ ex=star_expressions ':' " +"tc=[TYPE_COMMENT] b=block el=[else_block] {\n" +" CHECK_VERSION(stmt_ty, 5, \"Async for loops are\", " +"_PyAST_AsyncFor(t, ex, b, el, NEW_TYPE_COMMENT(p, tc), EXTRA)) }\n" +" | invalid_for_target\n" +"\n" +"# With statement\n" +"# --------------\n" +"\n" +"with_stmt[stmt_ty]:\n" +" | invalid_with_stmt_indent\n" +" | 'with' '(' a[asdl_withitem_seq*]=','.with_item+ ','? ')' ':' " +"tc=[TYPE_COMMENT] b=block {\n" +" _PyAST_With(a, b, NEW_TYPE_COMMENT(p, tc), EXTRA) }\n" +" | 'with' a[asdl_withitem_seq*]=','.with_item+ ':' tc=[TYPE_COMMENT] " +"b=block {\n" +" _PyAST_With(a, b, NEW_TYPE_COMMENT(p, tc), EXTRA) }\n" +" | 'async' 'with' '(' a[asdl_withitem_seq*]=','.with_item+ ','? ')' ':' " +"b=block {\n" +" CHECK_VERSION(stmt_ty, 5, \"Async with statements are\", " +"_PyAST_AsyncWith(a, b, NULL, EXTRA)) }\n" +" | 'async' 'with' a[asdl_withitem_seq*]=','.with_item+ ':' " +"tc=[TYPE_COMMENT] b=block {\n" +" CHECK_VERSION(stmt_ty, 5, \"Async with statements are\", " +"_PyAST_AsyncWith(a, b, NEW_TYPE_COMMENT(p, tc), EXTRA)) }\n" +" | invalid_with_stmt\n" +"\n" +"with_item[withitem_ty]:\n" +" | e=expression 'as' t=star_target &(',' | ')' | ':') " +"{ _PyAST_withitem(e, t, p->arena) }\n" +" | invalid_with_item\n" +" | e=expression { _PyAST_withitem(e, NULL, p->arena) }\n" +"\n" +"# Try statement\n" +"# -------------\n" +"\n" +"try_stmt[stmt_ty]:\n" +" | invalid_try_stmt\n" +" | 'try' &&':' b=block f=finally_block { _PyAST_Try(b, NULL, NULL, f, " +"EXTRA) }\n" +" | 'try' &&':' b=block ex[asdl_excepthandler_seq*]=except_block+ " +"el=[else_block] f=[finally_block] { _PyAST_Try(b, ex, el, f, EXTRA) }\n" +" | 'try' &&':' b=block ex[asdl_excepthandler_seq*]=except_star_block+ " +"el=[else_block] f=[finally_block] {\n" +" CHECK_VERSION(stmt_ty, 11, \"Exception groups are\",\n" +" _PyAST_TryStar(b, ex, el, f, EXTRA)) }\n" +"\n" +"\n" +"# Except statement\n" +"# ----------------\n" +"\n" +"except_block[excepthandler_ty]:\n" +" | invalid_except_stmt_indent\n" +" | 'except' e=expression t=['as' z=NAME { z }] ':' b=block {\n" +" _PyAST_ExceptHandler(e, (t) ? ((expr_ty) t)->v.Name.id : NULL, b, " +"EXTRA) }\n" +" | 'except' ':' b=block { _PyAST_ExceptHandler(NULL, NULL, b, EXTRA) }\n" +" | invalid_except_stmt\n" +"except_star_block[excepthandler_ty]:\n" +" | invalid_except_star_stmt_indent\n" +" | 'except' '*' e=expression t=['as' z=NAME { z }] ':' b=block {\n" +" _PyAST_ExceptHandler(e, (t) ? ((expr_ty) t)->v.Name.id : NULL, b, " +"EXTRA) }\n" +" | invalid_except_stmt\n" +"finally_block[asdl_stmt_seq*]:\n" +" | invalid_finally_stmt\n" +" | 'finally' &&':' a=block { a }\n" +"\n" +"# Match statement\n" +"# ---------------\n" +"\n" +"match_stmt[stmt_ty]:\n" +" | \"match\" subject=subject_expr ':' NEWLINE INDENT " +"cases[asdl_match_case_seq*]=case_block+ DEDENT {\n" +" CHECK_VERSION(stmt_ty, 10, \"Pattern matching is\", " +"_PyAST_Match(subject, cases, EXTRA)) }\n" +" | invalid_match_stmt\n" +"\n" +"subject_expr[expr_ty]:\n" +" | value=star_named_expression ',' values=star_named_expressions? {\n" +" _PyAST_Tuple(CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, " +"value, values)), Load, EXTRA) }\n" +" | named_expression\n" +"\n" +"case_block[match_case_ty]:\n" +" | invalid_case_block\n" +" | \"case\" pattern=patterns guard=guard? ':' body=block {\n" +" _PyAST_match_case(pattern, guard, body, p->arena) }\n" +"\n" +"guard[expr_ty]: 'if' guard=named_expression { guard }\n" +"\n" +"patterns[pattern_ty]:\n" +" | patterns[asdl_pattern_seq*]=open_sequence_pattern {\n" +" _PyAST_MatchSequence(patterns, EXTRA) }\n" +" | pattern\n" +"\n" +"pattern[pattern_ty]:\n" +" | as_pattern\n" +" | or_pattern\n" +"\n" +"as_pattern[pattern_ty]:\n" +" | pattern=or_pattern 'as' target=pattern_capture_target {\n" +" _PyAST_MatchAs(pattern, target->v.Name.id, EXTRA) }\n" +" | invalid_as_pattern\n" +"\n" +"or_pattern[pattern_ty]:\n" +" | patterns[asdl_pattern_seq*]='|'.closed_pattern+ {\n" +" asdl_seq_LEN(patterns) == 1 ? asdl_seq_GET(patterns, 0) : " +"_PyAST_MatchOr(patterns, EXTRA) }\n" +"\n" +"closed_pattern[pattern_ty] (memo):\n" +" | literal_pattern\n" +" | capture_pattern\n" +" | wildcard_pattern\n" +" | value_pattern\n" +" | group_pattern\n" +" | sequence_pattern\n" +" | mapping_pattern\n" +" | class_pattern\n" +"\n" +"# Literal patterns are used for equality and identity constraints\n" +"literal_pattern[pattern_ty]:\n" +" | value=signed_number !('+' | '-') { _PyAST_MatchValue(value, EXTRA) }\n" +" | value=complex_number { _PyAST_MatchValue(value, EXTRA) }\n" +" | value=strings { _PyAST_MatchValue(value, EXTRA) }\n" +" | 'None' { _PyAST_MatchSingleton(Py_None, EXTRA) }\n" +" | 'True' { _PyAST_MatchSingleton(Py_True, EXTRA) }\n" +" | 'False' { _PyAST_MatchSingleton(Py_False, EXTRA) }\n" +"\n" +"# Literal expressions are used to restrict permitted mapping pattern keys\n" +"literal_expr[expr_ty]:\n" +" | signed_number !('+' | '-')\n" +" | complex_number\n" +" | strings\n" +" | 'None' { _PyAST_Constant(Py_None, NULL, EXTRA) }\n" +" | 'True' { _PyAST_Constant(Py_True, NULL, EXTRA) }\n" +" | 'False' { _PyAST_Constant(Py_False, NULL, EXTRA) }\n" +"\n" +"complex_number[expr_ty]:\n" +" | real=signed_real_number '+' imag=imaginary_number {\n" +" _PyAST_BinOp(real, Add, imag, EXTRA) }\n" +" | real=signed_real_number '-' imag=imaginary_number {\n" +" _PyAST_BinOp(real, Sub, imag, EXTRA) }\n" +"\n" +"signed_number[expr_ty]:\n" +" | NUMBER\n" +" | '-' number=NUMBER { _PyAST_UnaryOp(USub, number, EXTRA) }\n" +"\n" +"signed_real_number[expr_ty]:\n" +" | real_number\n" +" | '-' real=real_number { _PyAST_UnaryOp(USub, real, EXTRA) }\n" +"\n" +"real_number[expr_ty]:\n" +" | real=NUMBER { _PyPegen_ensure_real(p, real) }\n" +"\n" +"imaginary_number[expr_ty]:\n" +" | imag=NUMBER { _PyPegen_ensure_imaginary(p, imag) }\n" +"\n" +"capture_pattern[pattern_ty]:\n" +" | target=pattern_capture_target { _PyAST_MatchAs(NULL, target->v.Name." +"id, EXTRA) }\n" +"\n" +"pattern_capture_target[expr_ty]:\n" +" | !\"_\" name=NAME !('.' | '(' | '=') {\n" +" _PyPegen_set_expr_context(p, name, Store) }\n" +"\n" +"wildcard_pattern[pattern_ty]:\n" +" | \"_\" { _PyAST_MatchAs(NULL, NULL, EXTRA) }\n" +"\n" +"value_pattern[pattern_ty]:\n" +" | attr=attr !('.' | '(' | '=') { _PyAST_MatchValue(attr, EXTRA) }\n" +"\n" +"attr[expr_ty]:\n" +" | value=name_or_attr '.' attr=NAME {\n" +" _PyAST_Attribute(value, attr->v.Name.id, Load, EXTRA) }\n" +"\n" +"name_or_attr[expr_ty]:\n" +" | attr\n" +" | NAME\n" +"\n" +"group_pattern[pattern_ty]:\n" +" | '(' pattern=pattern ')' { pattern }\n" +"\n" +"sequence_pattern[pattern_ty]:\n" +" | '[' patterns=maybe_sequence_pattern? " +"']' { _PyAST_MatchSequence(patterns, EXTRA) }\n" +" | '(' patterns=open_sequence_pattern? " +"')' { _PyAST_MatchSequence(patterns, EXTRA) }\n" +"\n" +"open_sequence_pattern[asdl_seq*]:\n" +" | pattern=maybe_star_pattern ',' patterns=maybe_sequence_pattern? {\n" +" _PyPegen_seq_insert_in_front(p, pattern, patterns) }\n" +"\n" +"maybe_sequence_pattern[asdl_seq*]:\n" +" | patterns=','.maybe_star_pattern+ ','? { patterns }\n" +"\n" +"maybe_star_pattern[pattern_ty]:\n" +" | star_pattern\n" +" | pattern\n" +"\n" +"star_pattern[pattern_ty] (memo):\n" +" | '*' target=pattern_capture_target {\n" +" _PyAST_MatchStar(target->v.Name.id, EXTRA) }\n" +" | '*' wildcard_pattern {\n" +" _PyAST_MatchStar(NULL, EXTRA) }\n" +"\n" +"mapping_pattern[pattern_ty]:\n" +" | '{' '}' {\n" +" _PyAST_MatchMapping(NULL, NULL, NULL, EXTRA) }\n" +" | '{' rest=double_star_pattern ','? '}' {\n" +" _PyAST_MatchMapping(NULL, NULL, rest->v.Name.id, EXTRA) }\n" +" | '{' items=items_pattern ',' rest=double_star_pattern ','? '}' {\n" +" _PyAST_MatchMapping(\n" +" CHECK(asdl_expr_seq*, _PyPegen_get_pattern_keys(p, items)),\n" +" CHECK(asdl_pattern_seq*, _PyPegen_get_patterns(p, items)),\n" +" rest->v.Name.id,\n" +" EXTRA) }\n" +" | '{' items=items_pattern ','? '}' {\n" +" _PyAST_MatchMapping(\n" +" CHECK(asdl_expr_seq*, _PyPegen_get_pattern_keys(p, items)),\n" +" CHECK(asdl_pattern_seq*, _PyPegen_get_patterns(p, items)),\n" +" NULL,\n" +" EXTRA) }\n" +"\n" +"items_pattern[asdl_seq*]:\n" +" | ','.key_value_pattern+\n" +"\n" +"key_value_pattern[KeyPatternPair*]:\n" +" | key=(literal_expr | attr) ':' pattern=pattern {\n" +" _PyPegen_key_pattern_pair(p, key, pattern) }\n" +"\n" +"double_star_pattern[expr_ty]:\n" +" | '**' target=pattern_capture_target { target }\n" +"\n" +"class_pattern[pattern_ty]:\n" +" | cls=name_or_attr '(' ')' {\n" +" _PyAST_MatchClass(cls, NULL, NULL, NULL, EXTRA) }\n" +" | cls=name_or_attr '(' patterns=positional_patterns ','? ')' {\n" +" _PyAST_MatchClass(cls, patterns, NULL, NULL, EXTRA) }\n" +" | cls=name_or_attr '(' keywords=keyword_patterns ','? ')' {\n" +" _PyAST_MatchClass(\n" +" cls, NULL,\n" +" CHECK(asdl_identifier_seq*, _PyPegen_map_names_to_ids(p,\n" +" CHECK(asdl_expr_seq*, _PyPegen_get_pattern_keys(p, " +"keywords)))),\n" +" CHECK(asdl_pattern_seq*, _PyPegen_get_patterns(p, keywords)),\n" +" EXTRA) }\n" +" | cls=name_or_attr '(' patterns=positional_patterns ',' " +"keywords=keyword_patterns ','? ')' {\n" +" _PyAST_MatchClass(\n" +" cls,\n" +" patterns,\n" +" CHECK(asdl_identifier_seq*, _PyPegen_map_names_to_ids(p,\n" +" CHECK(asdl_expr_seq*, _PyPegen_get_pattern_keys(p, " +"keywords)))),\n" +" CHECK(asdl_pattern_seq*, _PyPegen_get_patterns(p, keywords)),\n" +" EXTRA) }\n" +" | invalid_class_pattern\n" +"\n" +"positional_patterns[asdl_pattern_seq*]:\n" +" | args[asdl_pattern_seq*]=','.pattern+ { args }\n" +"\n" +"keyword_patterns[asdl_seq*]:\n" +" | ','.keyword_pattern+\n" +"\n" +"keyword_pattern[KeyPatternPair*]:\n" +" | arg=NAME '=' value=pattern { _PyPegen_key_pattern_pair(p, arg, " +"value) }\n" +"\n" +"# Type statement\n" +"# ---------------\n" +"\n" +"type_alias[stmt_ty]:\n" +" | \"type\" n=NAME t=[type_params] '=' b=expression {\n" +" CHECK_VERSION(stmt_ty, 12, \"Type statement is\",\n" +" _PyAST_TypeAlias(CHECK(expr_ty, _PyPegen_set_expr_context(p, n, " +"Store)), t, b, EXTRA)) }\n" +"\n" +"# Type parameter declaration\n" +"# --------------------------\n" +"\n" +"type_params[asdl_type_param_seq*]:\n" +" | invalid_type_params\n" +" | '[' t=type_param_seq ']' {\n" +" CHECK_VERSION(asdl_type_param_seq *, 12, \"Type parameter lists " +"are\", t) }\n" +"\n" +"type_param_seq[asdl_type_param_seq*]: a[asdl_type_param_seq*]=','." +"type_param+ [','] { a }\n" +"\n" +"type_param[type_param_ty] (memo):\n" +" | a=NAME b=[type_param_bound] c=[type_param_default] { _PyAST_TypeVar(a-" +">v.Name.id, b, c, EXTRA) }\n" +" | '*' a=NAME colon=':' e=expression {\n" +" RAISE_SYNTAX_ERROR_STARTING_FROM(colon, e->kind == Tuple_kind\n" +" ? \"cannot use constraints with TypeVarTuple\"\n" +" : \"cannot use bound with TypeVarTuple\")\n" +" }\n" +" | '*' a=NAME b=[type_param_starred_default] { _PyAST_TypeVarTuple(a->v." +"Name.id, b, EXTRA) }\n" +" | '**' a=NAME colon=':' e=expression {\n" +" RAISE_SYNTAX_ERROR_STARTING_FROM(colon, e->kind == Tuple_kind\n" +" ? \"cannot use constraints with ParamSpec\"\n" +" : \"cannot use bound with ParamSpec\")\n" +" }\n" +" | '**' a=NAME b=[type_param_default] { _PyAST_ParamSpec(a->v.Name.id, b, " +"EXTRA) }\n" +"\n" +"type_param_bound[expr_ty]: ':' e=expression { e }\n" +"type_param_default[expr_ty]: '=' e=expression {\n" +" CHECK_VERSION(expr_ty, 13, \"Type parameter defaults are\", e) }\n" +"type_param_starred_default[expr_ty]: '=' e=star_expression {\n" +" CHECK_VERSION(expr_ty, 13, \"Type parameter defaults are\", e) }\n" +"\n" +"# EXPRESSIONS\n" +"# -----------\n" +"\n" +"expressions[expr_ty]:\n" +" | a=expression b=(',' c=expression { c })+ [','] {\n" +" _PyAST_Tuple(CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, " +"a, b)), Load, EXTRA) }\n" +" | a=expression ',' { _PyAST_Tuple(CHECK(asdl_expr_seq*, " +"_PyPegen_singleton_seq(p, a)), Load, EXTRA) }\n" +" | expression\n" +"\n" +"expression[expr_ty] (memo):\n" +" | invalid_expression\n" +" | invalid_legacy_expression\n" +" | a=disjunction 'if' b=disjunction 'else' c=expression { _PyAST_IfExp(b, " +"a, c, EXTRA) }\n" +" | disjunction\n" +" | lambdef\n" +"\n" +"yield_expr[expr_ty]:\n" +" | 'yield' 'from' a=expression { _PyAST_YieldFrom(a, EXTRA) }\n" +" | 'yield' a=[star_expressions] { _PyAST_Yield(a, EXTRA) }\n" +"\n" +"star_expressions[expr_ty]:\n" +" | a=star_expression b=(',' c=star_expression { c })+ [','] {\n" +" _PyAST_Tuple(CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, " +"a, b)), Load, EXTRA) }\n" +" | a=star_expression ',' { _PyAST_Tuple(CHECK(asdl_expr_seq*, " +"_PyPegen_singleton_seq(p, a)), Load, EXTRA) }\n" +" | star_expression\n" +"\n" +"star_expression[expr_ty] (memo):\n" +" | '*' a=bitwise_or { _PyAST_Starred(a, Load, EXTRA) }\n" +" | expression\n" +"\n" +"star_named_expressions[asdl_expr_seq*]: a[asdl_expr_seq*]=','." +"star_named_expression+ [','] { a }\n" +"\n" +"star_named_expression[expr_ty]:\n" +" | '*' a=bitwise_or { _PyAST_Starred(a, Load, EXTRA) }\n" +" | named_expression\n" +"\n" +"assignment_expression[expr_ty]:\n" +" | a=NAME ':=' ~ b=expression {\n" +" CHECK_VERSION(expr_ty, 8, \"Assignment expressions are\",\n" +" _PyAST_NamedExpr(CHECK(expr_ty, _PyPegen_set_expr_context(p, a, " +"Store)), b, EXTRA)) }\n" +"\n" +"named_expression[expr_ty]:\n" +" | assignment_expression\n" +" | invalid_named_expression\n" +" | expression !':='\n" +"\n" +"disjunction[expr_ty] (memo):\n" +" | a=conjunction b=('or' c=conjunction { c })+ { _PyAST_BoolOp(\n" +" Or,\n" +" CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, a, b)),\n" +" EXTRA) }\n" +" | conjunction\n" +"\n" +"conjunction[expr_ty] (memo):\n" +" | a=inversion b=('and' c=inversion { c })+ { _PyAST_BoolOp(\n" +" And,\n" +" CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, a, b)),\n" +" EXTRA) }\n" +" | inversion\n" +"\n" +"inversion[expr_ty] (memo):\n" +" | 'not' a=inversion { _PyAST_UnaryOp(Not, a, EXTRA) }\n" +" | comparison\n" +"\n" +"# Comparison operators\n" +"# --------------------\n" +"\n" +"comparison[expr_ty]:\n" +" | a=bitwise_or b=compare_op_bitwise_or_pair+ {\n" +" _PyAST_Compare(\n" +" a,\n" +" CHECK(asdl_int_seq*, _PyPegen_get_cmpops(p, b)),\n" +" CHECK(asdl_expr_seq*, _PyPegen_get_exprs(p, b)),\n" +" EXTRA) }\n" +" | bitwise_or\n" +"\n" +"compare_op_bitwise_or_pair[CmpopExprPair*]:\n" +" | eq_bitwise_or\n" +" | noteq_bitwise_or\n" +" | lte_bitwise_or\n" +" | lt_bitwise_or\n" +" | gte_bitwise_or\n" +" | gt_bitwise_or\n" +" | notin_bitwise_or\n" +" | in_bitwise_or\n" +" | isnot_bitwise_or\n" +" | is_bitwise_or\n" +"\n" +"eq_bitwise_or[CmpopExprPair*]: '==' a=bitwise_or " +"{ _PyPegen_cmpop_expr_pair(p, Eq, a) }\n" +"noteq_bitwise_or[CmpopExprPair*]:\n" +" | (tok='!=' { _PyPegen_check_barry_as_flufl(p, tok) ? NULL : tok}) " +"a=bitwise_or {_PyPegen_cmpop_expr_pair(p, NotEq, a) }\n" +"lte_bitwise_or[CmpopExprPair*]: '<=' a=bitwise_or " +"{ _PyPegen_cmpop_expr_pair(p, LtE, a) }\n" +"lt_bitwise_or[CmpopExprPair*]: '<' a=bitwise_or " +"{ _PyPegen_cmpop_expr_pair(p, Lt, a) }\n" +"gte_bitwise_or[CmpopExprPair*]: '>=' a=bitwise_or " +"{ _PyPegen_cmpop_expr_pair(p, GtE, a) }\n" +"gt_bitwise_or[CmpopExprPair*]: '>' a=bitwise_or " +"{ _PyPegen_cmpop_expr_pair(p, Gt, a) }\n" +"notin_bitwise_or[CmpopExprPair*]: 'not' 'in' a=bitwise_or " +"{ _PyPegen_cmpop_expr_pair(p, NotIn, a) }\n" +"in_bitwise_or[CmpopExprPair*]: 'in' a=bitwise_or " +"{ _PyPegen_cmpop_expr_pair(p, In, a) }\n" +"isnot_bitwise_or[CmpopExprPair*]: 'is' 'not' a=bitwise_or " +"{ _PyPegen_cmpop_expr_pair(p, IsNot, a) }\n" +"is_bitwise_or[CmpopExprPair*]: 'is' a=bitwise_or " +"{ _PyPegen_cmpop_expr_pair(p, Is, a) }\n" +"\n" +"# Bitwise operators\n" +"# -----------------\n" +"\n" +"bitwise_or[expr_ty]:\n" +" | a=bitwise_or '|' b=bitwise_xor { _PyAST_BinOp(a, BitOr, b, EXTRA) }\n" +" | bitwise_xor\n" +"\n" +"bitwise_xor[expr_ty]:\n" +" | a=bitwise_xor '^' b=bitwise_and { _PyAST_BinOp(a, BitXor, b, EXTRA) }\n" +" | bitwise_and\n" +"\n" +"bitwise_and[expr_ty]:\n" +" | a=bitwise_and '&' b=shift_expr { _PyAST_BinOp(a, BitAnd, b, EXTRA) }\n" +" | shift_expr\n" +"\n" +"shift_expr[expr_ty]:\n" +" | a=shift_expr '<<' b=sum { _PyAST_BinOp(a, LShift, b, EXTRA) }\n" +" | a=shift_expr '>>' b=sum { _PyAST_BinOp(a, RShift, b, EXTRA) }\n" +" | invalid_arithmetic\n" +" | sum\n" +"\n" +"# Arithmetic operators\n" +"# --------------------\n" +"\n" +"sum[expr_ty]:\n" +" | a=sum '+' b=term { _PyAST_BinOp(a, Add, b, EXTRA) }\n" +" | a=sum '-' b=term { _PyAST_BinOp(a, Sub, b, EXTRA) }\n" +" | term\n" +"\n" +"term[expr_ty]:\n" +" | a=term '*' b=factor { _PyAST_BinOp(a, Mult, b, EXTRA) }\n" +" | a=term '/' b=factor { _PyAST_BinOp(a, Div, b, EXTRA) }\n" +" | a=term '//' b=factor { _PyAST_BinOp(a, FloorDiv, b, EXTRA) }\n" +" | a=term '%' b=factor { _PyAST_BinOp(a, Mod, b, EXTRA) }\n" +" | a=term '@' b=factor { CHECK_VERSION(expr_ty, 5, \"The '@' operator " +"is\", _PyAST_BinOp(a, MatMult, b, EXTRA)) }\n" +" | invalid_factor\n" +" | factor\n" +"\n" +"factor[expr_ty] (memo):\n" +" | '+' a=factor { _PyAST_UnaryOp(UAdd, a, EXTRA) }\n" +" | '-' a=factor { _PyAST_UnaryOp(USub, a, EXTRA) }\n" +" | '~' a=factor { _PyAST_UnaryOp(Invert, a, EXTRA) }\n" +" | power\n" +"\n" +"power[expr_ty]:\n" +" | a=await_primary '**' b=factor { _PyAST_BinOp(a, Pow, b, EXTRA) }\n" +" | await_primary\n" +"\n" +"# Primary elements\n" +"# ----------------\n" +"\n" +"# Primary elements are things like \"obj.something.something\", " +"\"obj[something]\", \"obj(something)\", \"obj\" ...\n" +"\n" +"await_primary[expr_ty] (memo):\n" +" | 'await' a=primary { CHECK_VERSION(expr_ty, 5, \"Await expressions " +"are\", _PyAST_Await(a, EXTRA)) }\n" +" | primary\n" +"\n" +"primary[expr_ty]:\n" +" | a=primary '.' b=NAME { _PyAST_Attribute(a, b->v.Name.id, Load, " +"EXTRA) }\n" +" | a=primary b=genexp { _PyAST_Call(a, CHECK(asdl_expr_seq*, " +"(asdl_expr_seq*)_PyPegen_singleton_seq(p, b)), NULL, EXTRA) }\n" +" | a=primary '(' b=[arguments] ')' {\n" +" _PyAST_Call(a,\n" +" (b) ? ((expr_ty) b)->v.Call.args : NULL,\n" +" (b) ? ((expr_ty) b)->v.Call.keywords : NULL,\n" +" EXTRA) }\n" +" | a=primary '[' b=slices ']' { _PyAST_Subscript(a, b, Load, EXTRA) }\n" +" | atom\n" +"\n" +"slices[expr_ty]:\n" +" | a=slice !',' { a }\n" +" | a[asdl_expr_seq*]=','.(slice | starred_expression)+ [','] " +"{ _PyAST_Tuple(a, Load, EXTRA) }\n" +"\n" +"slice[expr_ty]:\n" +" | a=[expression] ':' b=[expression] c=[':' d=[expression] { d }] " +"{ _PyAST_Slice(a, b, c, EXTRA) }\n" +" | a=named_expression { a }\n" +"\n" +"atom[expr_ty]:\n" +" | NAME\n" +" | 'True' { _PyAST_Constant(Py_True, NULL, EXTRA) }\n" +" | 'False' { _PyAST_Constant(Py_False, NULL, EXTRA) }\n" +" | 'None' { _PyAST_Constant(Py_None, NULL, EXTRA) }\n" +" | &(STRING|FSTRING_START) strings\n" +" | NUMBER\n" +" | &'(' (tuple | group | genexp)\n" +" | &'[' (list | listcomp)\n" +" | &'{' (dict | set | dictcomp | setcomp)\n" +" | '...' { _PyAST_Constant(Py_Ellipsis, NULL, EXTRA) }\n" +"\n" +"group[expr_ty]:\n" +" | '(' a=(yield_expr | named_expression) ')' { a }\n" +" | invalid_group\n" +"\n" +"# Lambda functions\n" +"# ----------------\n" +"\n" +"lambdef[expr_ty]:\n" +" | 'lambda' a=[lambda_params] ':' b=expression {\n" +" _PyAST_Lambda((a) ? a : CHECK(arguments_ty, " +"_PyPegen_empty_arguments(p)), b, EXTRA) }\n" +"\n" +"lambda_params[arguments_ty]:\n" +" | invalid_lambda_parameters\n" +" | lambda_parameters\n" +"\n" +"# lambda_parameters etc. duplicates parameters but without annotations\n" +"# or type comments, and if there's no comma after a parameter, we expect\n" +"# a colon, not a close parenthesis. (For more, see parameters above.)\n" +"#\n" +"lambda_parameters[arguments_ty]:\n" +" | a=lambda_slash_no_default b[asdl_arg_seq*]=lambda_param_no_default* " +"c=lambda_param_with_default* d=[lambda_star_etc] {\n" +" CHECK_VERSION(arguments_ty, 8, \"Positional-only parameters are\", " +"_PyPegen_make_arguments(p, a, NULL, b, c, d)) }\n" +" | a=lambda_slash_with_default b=lambda_param_with_default* " +"c=[lambda_star_etc] {\n" +" CHECK_VERSION(arguments_ty, 8, \"Positional-only parameters are\", " +"_PyPegen_make_arguments(p, NULL, a, NULL, b, c)) }\n" +" | a[asdl_arg_seq*]=lambda_param_no_default+ b=lambda_param_with_default* " +"c=[lambda_star_etc] {\n" +" _PyPegen_make_arguments(p, NULL, NULL, a, b, c) }\n" +" | a=lambda_param_with_default+ b=[lambda_star_etc] " +"{ _PyPegen_make_arguments(p, NULL, NULL, NULL, a, b)}\n" +" | a=lambda_star_etc { _PyPegen_make_arguments(p, NULL, NULL, NULL, NULL, " +"a) }\n" +"\n" +"lambda_slash_no_default[asdl_arg_seq*]:\n" +" | a[asdl_arg_seq*]=lambda_param_no_default+ '/' ',' { a }\n" +" | a[asdl_arg_seq*]=lambda_param_no_default+ '/' &':' { a }\n" +"\n" +"lambda_slash_with_default[SlashWithDefault*]:\n" +" | a=lambda_param_no_default* b=lambda_param_with_default+ '/' " +"',' { _PyPegen_slash_with_default(p, (asdl_arg_seq *)a, b) }\n" +" | a=lambda_param_no_default* b=lambda_param_with_default+ '/' " +"&':' { _PyPegen_slash_with_default(p, (asdl_arg_seq *)a, b) }\n" +"\n" +"lambda_star_etc[StarEtc*]:\n" +" | invalid_lambda_star_etc\n" +" | '*' a=lambda_param_no_default b=lambda_param_maybe_default* " +"c=[lambda_kwds] {\n" +" _PyPegen_star_etc(p, a, b, c) }\n" +" | '*' ',' b=lambda_param_maybe_default+ c=[lambda_kwds] {\n" +" _PyPegen_star_etc(p, NULL, b, c) }\n" +" | a=lambda_kwds { _PyPegen_star_etc(p, NULL, NULL, a) }\n" +"\n" +"lambda_kwds[arg_ty]:\n" +" | invalid_lambda_kwds\n" +" | '**' a=lambda_param_no_default { a }\n" +"\n" +"lambda_param_no_default[arg_ty]:\n" +" | a=lambda_param ',' { a }\n" +" | a=lambda_param &':' { a }\n" +"lambda_param_with_default[NameDefaultPair*]:\n" +" | a=lambda_param c=default ',' { _PyPegen_name_default_pair(p, a, c, " +"NULL) }\n" +" | a=lambda_param c=default &':' { _PyPegen_name_default_pair(p, a, c, " +"NULL) }\n" +"lambda_param_maybe_default[NameDefaultPair*]:\n" +" | a=lambda_param c=default? ',' { _PyPegen_name_default_pair(p, a, c, " +"NULL) }\n" +" | a=lambda_param c=default? &':' { _PyPegen_name_default_pair(p, a, c, " +"NULL) }\n" +"lambda_param[arg_ty]: a=NAME { _PyAST_arg(a->v.Name.id, NULL, NULL, " +"EXTRA) }\n" +"\n" +"# LITERALS\n" +"# ========\n" +"\n" +"fstring_middle[expr_ty]:\n" +" | fstring_replacement_field\n" +" | t=FSTRING_MIDDLE { _PyPegen_constant_from_token(p, t) }\n" +"fstring_replacement_field[expr_ty]:\n" +" | '{' a=annotated_rhs debug_expr='='? conversion=[fstring_conversion] " +"format=[fstring_full_format_spec] rbrace='}' {\n" +" _PyPegen_formatted_value(p, a, debug_expr, conversion, format, " +"rbrace, EXTRA) }\n" +" | invalid_replacement_field\n" +"fstring_conversion[ResultTokenWithMetadata*]:\n" +" | conv_token=\"!\" conv=NAME { _PyPegen_check_fstring_conversion(p, " +"conv_token, conv) }\n" +"fstring_full_format_spec[ResultTokenWithMetadata*]:\n" +" | colon=':' spec=fstring_format_spec* " +"{ _PyPegen_setup_full_format_spec(p, colon, (asdl_expr_seq *) spec, " +"EXTRA) }\n" +"fstring_format_spec[expr_ty]:\n" +" | t=FSTRING_MIDDLE { _PyPegen_decoded_constant_from_token(p, t) }\n" +" | fstring_replacement_field\n" +"fstring[expr_ty]:\n" +" | a=FSTRING_START b=fstring_middle* c=FSTRING_END " +"{ _PyPegen_joined_str(p, a, (asdl_expr_seq*)b, c) }\n" +"\n" +"string[expr_ty]: s[Token*]=STRING { _PyPegen_constant_from_string(p, s) }\n" +"strings[expr_ty] (memo): a[asdl_expr_seq*]=(fstring|string)+ " +"{ _PyPegen_concatenate_strings(p, a, EXTRA) }\n" +"\n" +"list[expr_ty]:\n" +" | '[' a=[star_named_expressions] ']' { _PyAST_List(a, Load, EXTRA) }\n" +"\n" +"tuple[expr_ty]:\n" +" | '(' a=[y=star_named_expression ',' z=[star_named_expressions] " +"{ _PyPegen_seq_insert_in_front(p, y, z) } ] ')' {\n" +" _PyAST_Tuple(a, Load, EXTRA) }\n" +"\n" +"set[expr_ty]: '{' a=star_named_expressions '}' { _PyAST_Set(a, EXTRA) }\n" +"\n" +"# Dicts\n" +"# -----\n" +"\n" +"dict[expr_ty]:\n" +" | '{' a=[double_starred_kvpairs] '}' {\n" +" _PyAST_Dict(\n" +" CHECK(asdl_expr_seq*, _PyPegen_get_keys(p, a)),\n" +" CHECK(asdl_expr_seq*, _PyPegen_get_values(p, a)),\n" +" EXTRA) }\n" +" | '{' invalid_double_starred_kvpairs '}'\n" +"\n" +"double_starred_kvpairs[asdl_seq*]: a=','.double_starred_kvpair+ [','] { a }\n" +"\n" +"double_starred_kvpair[KeyValuePair*]:\n" +" | '**' a=bitwise_or { _PyPegen_key_value_pair(p, NULL, a) }\n" +" | kvpair\n" +"\n" +"kvpair[KeyValuePair*]: a=expression ':' b=expression " +"{ _PyPegen_key_value_pair(p, a, b) }\n" +"\n" +"# Comprehensions & Generators\n" +"# ---------------------------\n" +"\n" +"for_if_clauses[asdl_comprehension_seq*]:\n" +" | a[asdl_comprehension_seq*]=for_if_clause+ { a }\n" +"\n" +"for_if_clause[comprehension_ty]:\n" +" | 'async' 'for' a=star_targets 'in' ~ b=disjunction " +"c[asdl_expr_seq*]=('if' z=disjunction { z })* {\n" +" CHECK_VERSION(comprehension_ty, 6, \"Async comprehensions are\", " +"_PyAST_comprehension(a, b, c, 1, p->arena)) }\n" +" | 'for' a=star_targets 'in' ~ b=disjunction c[asdl_expr_seq*]=('if' " +"z=disjunction { z })* {\n" +" _PyAST_comprehension(a, b, c, 0, p->arena) }\n" +" | 'async'? 'for' (bitwise_or (',' bitwise_or)* [',']) !'in' {\n" +" RAISE_SYNTAX_ERROR(\"'in' expected after for-loop variables\") }\n" +" | invalid_for_target\n" +"\n" +"listcomp[expr_ty]:\n" +" | '[' a=named_expression b=for_if_clauses ']' { _PyAST_ListComp(a, b, " +"EXTRA) }\n" +" | invalid_comprehension\n" +"\n" +"setcomp[expr_ty]:\n" +" | '{' a=named_expression b=for_if_clauses '}' { _PyAST_SetComp(a, b, " +"EXTRA) }\n" +" | invalid_comprehension\n" +"\n" +"genexp[expr_ty]:\n" +" | '(' a=( assignment_expression | expression !':=') b=for_if_clauses " +"')' { _PyAST_GeneratorExp(a, b, EXTRA) }\n" +" | invalid_comprehension\n" +"\n" +"dictcomp[expr_ty]:\n" +" | '{' a=kvpair b=for_if_clauses '}' { _PyAST_DictComp(a->key, a->value, " +"b, EXTRA) }\n" +" | invalid_dict_comprehension\n" +"\n" +"# FUNCTION CALL ARGUMENTS\n" +"# =======================\n" +"\n" +"arguments[expr_ty] (memo):\n" +" | a=args [','] &')' { a }\n" +" | invalid_arguments\n" +"\n" +"args[expr_ty]:\n" +" | a[asdl_expr_seq*]=','.(starred_expression | ( assignment_expression | " +"expression !':=') !'=')+ b=[',' k=kwargs {k}] {\n" +" _PyPegen_collect_call_seqs(p, a, b, EXTRA) }\n" +" | a=kwargs { _PyAST_Call(_PyPegen_dummy_name(p),\n" +" CHECK_NULL_ALLOWED(asdl_expr_seq*, " +"_PyPegen_seq_extract_starred_exprs(p, a)),\n" +" CHECK_NULL_ALLOWED(asdl_keyword_seq*, " +"_PyPegen_seq_delete_starred_exprs(p, a)),\n" +" EXTRA) }\n" +"\n" +"kwargs[asdl_seq*]:\n" +" | a=','.kwarg_or_starred+ ',' b=','.kwarg_or_double_starred+ " +"{ _PyPegen_join_sequences(p, a, b) }\n" +" | ','.kwarg_or_starred+\n" +" | ','.kwarg_or_double_starred+\n" +"\n" +"starred_expression[expr_ty]:\n" +" | invalid_starred_expression\n" +" | '*' a=expression { _PyAST_Starred(a, Load, EXTRA) }\n" +" | '*' { RAISE_SYNTAX_ERROR(\"Invalid star expression\") }\n" +"\n" +"kwarg_or_starred[KeywordOrStarred*]:\n" +" | invalid_kwarg\n" +" | a=NAME '=' b=expression {\n" +" _PyPegen_keyword_or_starred(p, CHECK(keyword_ty, _PyAST_keyword(a->v." +"Name.id, b, EXTRA)), 1) }\n" +" | a=starred_expression { _PyPegen_keyword_or_starred(p, a, 0) }\n" +"\n" +"kwarg_or_double_starred[KeywordOrStarred*]:\n" +" | invalid_kwarg\n" +" | a=NAME '=' b=expression {\n" +" _PyPegen_keyword_or_starred(p, CHECK(keyword_ty, _PyAST_keyword(a->v." +"Name.id, b, EXTRA)), 1) }\n" +" | '**' a=expression { _PyPegen_keyword_or_starred(p, CHECK(keyword_ty, " +"_PyAST_keyword(NULL, a, EXTRA)), 1) }\n" +"\n" +"# ASSIGNMENT TARGETS\n" +"# ==================\n" +"\n" +"# Generic targets\n" +"# ---------------\n" +"\n" +"# NOTE: star_targets may contain *bitwise_or, targets may not.\n" +"star_targets[expr_ty]:\n" +" | a=star_target !',' { a }\n" +" | a=star_target b=(',' c=star_target { c })* [','] {\n" +" _PyAST_Tuple(CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, " +"a, b)), Store, EXTRA) }\n" +"\n" +"star_targets_list_seq[asdl_expr_seq*]: a[asdl_expr_seq*]=','.star_target+ " +"[','] { a }\n" +"\n" +"star_targets_tuple_seq[asdl_expr_seq*]:\n" +" | a=star_target b=(',' c=star_target { c })+ [','] { (asdl_expr_seq*) " +"_PyPegen_seq_insert_in_front(p, a, b) }\n" +" | a=star_target ',' { (asdl_expr_seq*) _PyPegen_singleton_seq(p, a) }\n" +"\n" +"star_target[expr_ty] (memo):\n" +" | '*' a=(!'*' star_target) {\n" +" _PyAST_Starred(CHECK(expr_ty, _PyPegen_set_expr_context(p, a, " +"Store)), Store, EXTRA) }\n" +" | target_with_star_atom\n" +"\n" +"target_with_star_atom[expr_ty] (memo):\n" +" | a=t_primary '.' b=NAME !t_lookahead { _PyAST_Attribute(a, b->v.Name." +"id, Store, EXTRA) }\n" +" | a=t_primary '[' b=slices ']' !t_lookahead { _PyAST_Subscript(a, b, " +"Store, EXTRA) }\n" +" | star_atom\n" +"\n" +"star_atom[expr_ty]:\n" +" | a=NAME { _PyPegen_set_expr_context(p, a, Store) }\n" +" | '(' a=target_with_star_atom ')' { _PyPegen_set_expr_context(p, a, " +"Store) }\n" +" | '(' a=[star_targets_tuple_seq] ')' { _PyAST_Tuple(a, Store, EXTRA) }\n" +" | '[' a=[star_targets_list_seq] ']' { _PyAST_List(a, Store, EXTRA) }\n" +"\n" +"single_target[expr_ty]:\n" +" | single_subscript_attribute_target\n" +" | a=NAME { _PyPegen_set_expr_context(p, a, Store) }\n" +" | '(' a=single_target ')' { a }\n" +"\n" +"single_subscript_attribute_target[expr_ty]:\n" +" | a=t_primary '.' b=NAME !t_lookahead { _PyAST_Attribute(a, b->v.Name." +"id, Store, EXTRA) }\n" +" | a=t_primary '[' b=slices ']' !t_lookahead { _PyAST_Subscript(a, b, " +"Store, EXTRA) }\n" +"\n" +"t_primary[expr_ty]:\n" +" | a=t_primary '.' b=NAME &t_lookahead { _PyAST_Attribute(a, b->v.Name." +"id, Load, EXTRA) }\n" +" | a=t_primary '[' b=slices ']' &t_lookahead { _PyAST_Subscript(a, b, " +"Load, EXTRA) }\n" +" | a=t_primary b=genexp &t_lookahead {\n" +" _PyAST_Call(a, CHECK(asdl_expr_seq*, " +"(asdl_expr_seq*)_PyPegen_singleton_seq(p, b)), NULL, EXTRA) }\n" +" | a=t_primary '(' b=[arguments] ')' &t_lookahead {\n" +" _PyAST_Call(a,\n" +" (b) ? ((expr_ty) b)->v.Call.args : NULL,\n" +" (b) ? ((expr_ty) b)->v.Call.keywords : NULL,\n" +" EXTRA) }\n" +" | a=atom &t_lookahead { a }\n" +"\n" +"t_lookahead: '(' | '[' | '.'\n" +"\n" +"# Targets for del statements\n" +"# --------------------------\n" +"\n" +"del_targets[asdl_expr_seq*]: a[asdl_expr_seq*]=','.del_target+ [','] { a }\n" +"\n" +"del_target[expr_ty] (memo):\n" +" | a=t_primary '.' b=NAME !t_lookahead { _PyAST_Attribute(a, b->v.Name." +"id, Del, EXTRA) }\n" +" | a=t_primary '[' b=slices ']' !t_lookahead { _PyAST_Subscript(a, b, " +"Del, EXTRA) }\n" +" | del_t_atom\n" +"\n" +"del_t_atom[expr_ty]:\n" +" | a=NAME { _PyPegen_set_expr_context(p, a, Del) }\n" +" | '(' a=del_target ')' { _PyPegen_set_expr_context(p, a, Del) }\n" +" | '(' a=[del_targets] ')' { _PyAST_Tuple(a, Del, EXTRA) }\n" +" | '[' a=[del_targets] ']' { _PyAST_List(a, Del, EXTRA) }\n" +"\n" +"# TYPING ELEMENTS\n" +"# ---------------\n" +"\n" +"# type_expressions allow */** but ignore them\n" +"type_expressions[asdl_expr_seq*]:\n" +" | a=','.expression+ ',' '*' b=expression ',' '**' c=expression {\n" +" (asdl_expr_seq*)_PyPegen_seq_append_to_end(\n" +" p,\n" +" CHECK(asdl_seq*, _PyPegen_seq_append_to_end(p, a, b)),\n" +" c) }\n" +" | a=','.expression+ ',' '*' b=expression " +"{ (asdl_expr_seq*)_PyPegen_seq_append_to_end(p, a, b) }\n" +" | a=','.expression+ ',' '**' b=expression " +"{ (asdl_expr_seq*)_PyPegen_seq_append_to_end(p, a, b) }\n" +" | '*' a=expression ',' '**' b=expression {\n" +" (asdl_expr_seq*)_PyPegen_seq_append_to_end(\n" +" p,\n" +" CHECK(asdl_seq*, _PyPegen_singleton_seq(p, a)),\n" +" b) }\n" +" | '*' a=expression { (asdl_expr_seq*)_PyPegen_singleton_seq(p, a) }\n" +" | '**' a=expression { (asdl_expr_seq*)_PyPegen_singleton_seq(p, a) }\n" +" | a[asdl_expr_seq*]=','.expression+ {a}\n" +"\n" +"func_type_comment[Token*]:\n" +" | NEWLINE t=TYPE_COMMENT &(NEWLINE INDENT) { t } # Must be followed by " +"indented block\n" +" | invalid_double_type_comments\n" +" | TYPE_COMMENT\n" +"\n" +"# ========================= END OF THE GRAMMAR ===========================\n" +"\n" +"\n" +"\n" +"# ========================= START OF INVALID RULES =======================\n" +"\n" +"# From here on, there are rules for invalid syntax with specialised error " +"messages\n" +"invalid_arguments:\n" +" | ((','.(starred_expression | ( assignment_expression | expression !':" +"=') !'=')+ ',' kwargs) | kwargs) a=',' ','.(starred_expression !'=')+ {\n" +" RAISE_SYNTAX_ERROR_STARTING_FROM(a, \"iterable argument unpacking " +"follows keyword argument unpacking\") }\n" +" | a=expression b=for_if_clauses ',' [args | expression for_if_clauses] " +"{\n" +" RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, " +"_PyPegen_get_last_comprehension_item(PyPegen_last_item(b, " +"comprehension_ty)), \"Generator expression must be parenthesized\") }\n" +" | a=NAME b='=' expression for_if_clauses {\n" +" RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, \"invalid syntax. Maybe you " +"meant '==' or ':=' instead of '='?\")}\n" +" | (args ',')? a=NAME b='=' &(',' | ')') {\n" +" RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, \"expected argument value " +"expression\")}\n" +" | a=args b=for_if_clauses { _PyPegen_nonparen_genexp_in_call(p, a, b) }\n" +" | args ',' a=expression b=for_if_clauses {\n" +" RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, " +"_PyPegen_get_last_comprehension_item(PyPegen_last_item(b, " +"comprehension_ty)), \"Generator expression must be parenthesized\") }\n" +" | a=args ',' args { _PyPegen_arguments_parsing_error(p, a) }\n" +"invalid_kwarg:\n" +" | a[Token*]=('True'|'False'|'None') b='=' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, \"cannot assign to %s\", " +"PyBytes_AS_STRING(a->bytes)) }\n" +" | a=NAME b='=' expression for_if_clauses {\n" +" RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, \"invalid syntax. Maybe you " +"meant '==' or ':=' instead of '='?\")}\n" +" | !(NAME '=') a=expression b='=' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_RANGE(\n" +" a, b, \"expression cannot contain assignment, perhaps you meant " +"\\\"==\\\"?\") }\n" +" | a='**' expression '=' b=expression {\n" +" RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, \"cannot assign to keyword " +"argument unpacking\") }\n" +"\n" +"# IMPORTANT: Note that the \"_without_invalid\" suffix causes the rule to " +"not call invalid rules under it\n" +"expression_without_invalid[expr_ty]:\n" +" | a=disjunction 'if' b=disjunction 'else' c=expression { _PyAST_IfExp(b, " +"a, c, EXTRA) }\n" +" | disjunction\n" +" | lambdef\n" +"invalid_legacy_expression:\n" +" | a=NAME !'(' b=star_expressions {\n" +" _PyPegen_check_legacy_stmt(p, a) ? RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, " +"b,\n" +" \"Missing parentheses in call to '%U'. Did you mean %U(...)?\", " +"a->v.Name.id, a->v.Name.id) : NULL}\n" +"\n" +"invalid_expression:\n" +" # !(NAME STRING) is not matched so we don't show this error with some " +"invalid string prefixes like: kf\"dsfsdf\"\n" +" # Soft keywords need to also be ignored because they can be parsed as " +"NAME NAME\n" +" | !(NAME STRING | SOFT_KEYWORD) a=disjunction " +"b=expression_without_invalid {\n" +" _PyPegen_check_legacy_stmt(p, a) ? NULL : p->tokens[p->mark-1]-" +">level == 0 ? NULL :\n" +" RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, \"invalid syntax. Perhaps you " +"forgot a comma?\") }\n" +" | a=disjunction 'if' b=disjunction !('else'|':') " +"{ RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, \"expected 'else' after 'if' " +"expression\") }\n" +" | a='lambda' [lambda_params] b=':' &FSTRING_MIDDLE {\n" +" RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, \"f-string: lambda expressions " +"are not allowed without parentheses\") }\n" +"\n" +"invalid_named_expression(memo):\n" +" | a=expression ':=' expression {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(\n" +" a, \"cannot use assignment expressions with %s\", " +"_PyPegen_get_expr_name(a)) }\n" +" | a=NAME '=' b=bitwise_or !('='|':=') {\n" +" RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, \"invalid syntax. Maybe you " +"meant '==' or ':=' instead of '='?\") }\n" +" | !(list|tuple|genexp|'True'|'None'|'False') a=bitwise_or b='=' " +"bitwise_or !('='|':=') {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"cannot assign to %s here. " +"Maybe you meant '==' instead of '='?\",\n" +" _PyPegen_get_expr_name(a)) }\n" +"\n" +"invalid_assignment:\n" +" | a=invalid_ann_assign_target ':' expression {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(\n" +" a,\n" +" \"only single target (not %s) can be annotated\",\n" +" _PyPegen_get_expr_name(a)\n" +" )}\n" +" | a=star_named_expression ',' star_named_expressions* ':' expression {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"only single target (not " +"tuple) can be annotated\") }\n" +" | a=expression ':' expression {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"illegal target for " +"annotation\") }\n" +" | (star_targets '=')* a=star_expressions '=' {\n" +" RAISE_SYNTAX_ERROR_INVALID_TARGET(STAR_TARGETS, a) }\n" +" | (star_targets '=')* a=yield_expr " +"'=' { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"assignment to yield expression " +"not possible\") }\n" +" | a=star_expressions augassign annotated_rhs {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(\n" +" a,\n" +" \"'%s' is an illegal expression for augmented assignment\",\n" +" _PyPegen_get_expr_name(a)\n" +" )}\n" +"invalid_ann_assign_target[expr_ty]:\n" +" | list\n" +" | tuple\n" +" | '(' a=invalid_ann_assign_target ')' { a }\n" +"invalid_del_stmt:\n" +" | 'del' a=star_expressions {\n" +" RAISE_SYNTAX_ERROR_INVALID_TARGET(DEL_TARGETS, a) }\n" +"invalid_block:\n" +" | NEWLINE !INDENT { RAISE_INDENTATION_ERROR(\"expected an indented " +"block\") }\n" +"invalid_comprehension:\n" +" | ('[' | '(' | '{') a=starred_expression for_if_clauses {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"iterable unpacking cannot be " +"used in comprehension\") }\n" +" | ('[' | '{') a=star_named_expression ',' b=star_named_expressions " +"for_if_clauses {\n" +" RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, PyPegen_last_item(b, expr_ty),\n" +" \"did you forget parentheses around the comprehension target?\") }\n" +" | ('[' | '{') a=star_named_expression b=',' for_if_clauses {\n" +" RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, \"did you forget parentheses " +"around the comprehension target?\") }\n" +"invalid_dict_comprehension:\n" +" | '{' a='**' bitwise_or for_if_clauses '}' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"dict unpacking cannot be used " +"in dict comprehension\") }\n" +"invalid_parameters:\n" +" | a=\"/\" ',' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"at least one argument must " +"precede /\") }\n" +" | (slash_no_default | slash_with_default) param_maybe_default* a='/' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"/ may appear only once\") }\n" +" | slash_no_default? param_no_default* invalid_parameters_helper " +"a=param_no_default {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"parameter without a default " +"follows parameter with a default\") }\n" +" | param_no_default* a='(' param_no_default+ ','? b=')' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, \"Function parameters cannot be " +"parenthesized\") }\n" +" | (slash_no_default | slash_with_default)? param_maybe_default* '*' (',' " +"| param_no_default) param_maybe_default* a='/' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"/ must be ahead of *\") }\n" +" | param_maybe_default+ '/' a='*' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"expected comma between / and " +"*\") }\n" +"invalid_default:\n" +" | a='=' &(')'|',') { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"expected " +"default value expression\") }\n" +"invalid_star_etc:\n" +" | a='*' (')' | ',' (')' | '**')) { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, " +"\"named arguments must follow bare *\") }\n" +" | '*' ',' TYPE_COMMENT { RAISE_SYNTAX_ERROR(\"bare * has associated type " +"comment\") }\n" +" | '*' param a='=' { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"var-" +"positional argument cannot have default value\") }\n" +" | '*' (param_no_default | ',') param_maybe_default* " +"a='*' (param_no_default | ',') {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"* argument may appear only " +"once\") }\n" +"invalid_kwds:\n" +" | '**' param a='=' { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"var-keyword " +"argument cannot have default value\") }\n" +" | '**' param ',' a=param { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, " +"\"arguments cannot follow var-keyword argument\") }\n" +" | '**' param ',' a[Token*]=('*'|'**'|'/') " +"{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"arguments cannot follow var-keyword " +"argument\") }\n" +"invalid_parameters_helper: # This is only there to avoid type errors\n" +" | a=slash_with_default { _PyPegen_singleton_seq(p, a) }\n" +" | param_with_default+\n" +"invalid_lambda_parameters:\n" +" | a=\"/\" ',' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"at least one argument must " +"precede /\") }\n" +" | (lambda_slash_no_default | lambda_slash_with_default) " +"lambda_param_maybe_default* a='/' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"/ may appear only once\") }\n" +" | lambda_slash_no_default? lambda_param_no_default* " +"invalid_lambda_parameters_helper a=lambda_param_no_default {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"parameter without a default " +"follows parameter with a default\") }\n" +" | lambda_param_no_default* a='(' ','.lambda_param+ ','? b=')' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, \"Lambda expression parameters " +"cannot be parenthesized\") }\n" +" | (lambda_slash_no_default | lambda_slash_with_default)? " +"lambda_param_maybe_default* '*' (',' | lambda_param_no_default) " +"lambda_param_maybe_default* a='/' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"/ must be ahead of *\") }\n" +" | lambda_param_maybe_default+ '/' a='*' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"expected comma between / and " +"*\") }\n" +"invalid_lambda_parameters_helper:\n" +" | a=lambda_slash_with_default { _PyPegen_singleton_seq(p, a) }\n" +" | lambda_param_with_default+\n" +"invalid_lambda_star_etc:\n" +" | '*' (':' | ',' (':' | '**')) { RAISE_SYNTAX_ERROR(\"named arguments " +"must follow bare *\") }\n" +" | '*' lambda_param a='=' { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"var-" +"positional argument cannot have default value\") }\n" +" | '*' (lambda_param_no_default | ',') lambda_param_maybe_default* " +"a='*' (lambda_param_no_default | ',') {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"* argument may appear only " +"once\") }\n" +"invalid_lambda_kwds:\n" +" | '**' lambda_param a='=' { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"var-" +"keyword argument cannot have default value\") }\n" +" | '**' lambda_param ',' a=lambda_param " +"{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"arguments cannot follow var-keyword " +"argument\") }\n" +" | '**' lambda_param ',' a[Token*]=('*'|'**'|'/') " +"{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"arguments cannot follow var-keyword " +"argument\") }\n" +"invalid_double_type_comments:\n" +" | TYPE_COMMENT NEWLINE TYPE_COMMENT NEWLINE INDENT {\n" +" RAISE_SYNTAX_ERROR(\"Cannot have two type comments on def\") }\n" +"invalid_with_item:\n" +" | expression 'as' a=expression &(',' | ')' | ':') {\n" +" RAISE_SYNTAX_ERROR_INVALID_TARGET(STAR_TARGETS, a) }\n" +"\n" +"invalid_for_target:\n" +" | 'async'? 'for' a=star_expressions {\n" +" RAISE_SYNTAX_ERROR_INVALID_TARGET(FOR_TARGETS, a) }\n" +"\n" +"invalid_group:\n" +" | '(' a=starred_expression ')' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"cannot use starred expression " +"here\") }\n" +" | '(' a='**' expression ')' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"cannot use double starred " +"expression here\") }\n" +"invalid_import:\n" +" | a='import' ','.dotted_name+ 'from' dotted_name {\n" +" RAISE_SYNTAX_ERROR_STARTING_FROM(a, \"Did you mean to use 'from ... " +"import ...' instead?\") }\n" +" | 'import' token=NEWLINE {\n" +" RAISE_SYNTAX_ERROR_STARTING_FROM(token, \"Expected one or more names " +"after 'import'\") }\n" +"\n" +"invalid_import_from_targets:\n" +" | import_from_as_names ',' NEWLINE {\n" +" RAISE_SYNTAX_ERROR(\"trailing comma not allowed without surrounding " +"parentheses\") }\n" +" | token=NEWLINE {\n" +" RAISE_SYNTAX_ERROR_STARTING_FROM(token, \"Expected one or more names " +"after 'import'\") }\n" +"\n" +"invalid_with_stmt:\n" +" | ['async'] 'with' ','.(expression ['as' star_target])+ NEWLINE " +"{ RAISE_SYNTAX_ERROR(\"expected ':'\") }\n" +" | ['async'] 'with' '(' ','.(expressions ['as' star_target])+ ','? ')' " +"NEWLINE { RAISE_SYNTAX_ERROR(\"expected ':'\") }\n" +"invalid_with_stmt_indent:\n" +" | ['async'] a='with' ','.(expression ['as' star_target])+ ':' NEWLINE !" +"INDENT {\n" +" RAISE_INDENTATION_ERROR(\"expected an indented block after 'with' " +"statement on line %d\", a->lineno) }\n" +" | ['async'] a='with' '(' ','.(expressions ['as' star_target])+ ','? ')' " +"':' NEWLINE !INDENT {\n" +" RAISE_INDENTATION_ERROR(\"expected an indented block after 'with' " +"statement on line %d\", a->lineno) }\n" +"\n" +"invalid_try_stmt:\n" +" | a='try' ':' NEWLINE !INDENT {\n" +" RAISE_INDENTATION_ERROR(\"expected an indented block after 'try' " +"statement on line %d\", a->lineno) }\n" +" | 'try' ':' block !('except' | 'finally') " +"{ RAISE_SYNTAX_ERROR(\"expected 'except' or 'finally' block\") }\n" +" | 'try' ':' block* except_block+ a='except' b='*' expression ['as' NAME] " +"':' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, \"cannot have both 'except' and " +"'except*' on the same 'try'\") }\n" +" | 'try' ':' block* except_star_block+ a='except' [expression ['as' " +"NAME]] ':' {\n" +" RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"cannot have both 'except' and " +"'except*' on the same 'try'\") }\n" +"invalid_except_stmt:\n" +" | 'except' '*'? a=expression ',' expressions ['as' NAME ] ':' {\n" +" RAISE_SYNTAX_ERROR_STARTING_FROM(a, \"multiple exception types must " +"be parenthesized\") }\n" +" | a='except' '*'? expression ['as' NAME ] NEWLINE " +"{ RAISE_SYNTAX_ERROR(\"expected ':'\") }\n" +" | a='except' NEWLINE { RAISE_SYNTAX_ERROR(\"expected ':'\") }\n" +" | a='except' '*' (NEWLINE | ':') { RAISE_SYNTAX_ERROR(\"expected one or " +"more exception types\") }\n" +"invalid_finally_stmt:\n" +" | a='finally' ':' NEWLINE !INDENT {\n" +" RAISE_INDENTATION_ERROR(\"expected an indented block after 'finally' " +"statement on line %d\", a->lineno) }\n" +"invalid_except_stmt_indent:\n" +" | a='except' expression ['as' NAME ] ':' NEWLINE !INDENT {\n" +" RAISE_INDENTATION_ERROR(\"expected an indented block after 'except' " +"statement on line %d\", a->lineno) }\n" +" | a='except' ':' NEWLINE !INDENT { RAISE_INDENTATION_ERROR(\"expected an " +"indented block after 'except' statement on line %d\", a->lineno) }\n" +"invalid_except_star_stmt_indent:\n" +" | a='except' '*' expression ['as' NAME ] ':' NEWLINE !INDENT {\n" +" RAISE_INDENTATION_ERROR(\"expected an indented block after 'except*' " +"statement on line %d\", a->lineno) }\n" +"invalid_match_stmt:\n" +" | \"match\" subject_expr NEWLINE { CHECK_VERSION(void*, 10, \"Pattern " +"matching is\", RAISE_SYNTAX_ERROR(\"expected ':'\") ) }\n" +" | a=\"match\" subject=subject_expr ':' NEWLINE !INDENT {\n" +" RAISE_INDENTATION_ERROR(\"expected an indented block after 'match' " +"statement on line %d\", a->lineno) }\n" +"invalid_case_block:\n" +" | \"case\" patterns guard? NEWLINE { RAISE_SYNTAX_ERROR(\"expected " +"':'\") }\n" +" | a=\"case\" patterns guard? ':' NEWLINE !INDENT {\n" +" RAISE_INDENTATION_ERROR(\"expected an indented block after 'case' " +"statement on line %d\", a->lineno) }\n" +"invalid_as_pattern:\n" +" | or_pattern 'as' a=\"_\" { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, " +"\"cannot use '_' as a target\") }\n" +" | or_pattern 'as' !NAME a=expression " +"{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"invalid pattern target\") }\n" +"invalid_class_pattern:\n" +" | name_or_attr '(' a=invalid_class_argument_pattern " +"{ RAISE_SYNTAX_ERROR_KNOWN_RANGE(\n" +" PyPegen_first_item(a, pattern_ty),\n" +" PyPegen_last_item(a, pattern_ty),\n" +" \"positional patterns follow keyword patterns\") }\n" +"invalid_class_argument_pattern[asdl_pattern_seq*]:\n" +" | [positional_patterns ','] keyword_patterns ',' a=positional_patterns " +"{ a }\n" +"invalid_if_stmt:\n" +" | 'if' named_expression NEWLINE { RAISE_SYNTAX_ERROR(\"expected " +"':'\") }\n" +" | a='if' a=named_expression ':' NEWLINE !INDENT {\n" +" RAISE_INDENTATION_ERROR(\"expected an indented block after 'if' " +"statement on line %d\", a->lineno) }\n" +"invalid_elif_stmt:\n" +" | 'elif' named_expression NEWLINE { RAISE_SYNTAX_ERROR(\"expected " +"':'\") }\n" +" | a='elif' named_expression ':' NEWLINE !INDENT {\n" +" RAISE_INDENTATION_ERROR(\"expected an indented block after 'elif' " +"statement on line %d\", a->lineno) }\n" +"invalid_else_stmt:\n" +" | a='else' ':' NEWLINE !INDENT {\n" +" RAISE_INDENTATION_ERROR(\"expected an indented block after 'else' " +"statement on line %d\", a->lineno) }\n" +"invalid_while_stmt:\n" +" | 'while' named_expression NEWLINE { RAISE_SYNTAX_ERROR(\"expected " +"':'\") }\n" +" | a='while' named_expression ':' NEWLINE !INDENT {\n" +" RAISE_INDENTATION_ERROR(\"expected an indented block after 'while' " +"statement on line %d\", a->lineno) }\n" +"invalid_for_stmt:\n" +" | ['async'] 'for' star_targets 'in' star_expressions NEWLINE " +"{ RAISE_SYNTAX_ERROR(\"expected ':'\") }\n" +" | ['async'] a='for' star_targets 'in' star_expressions ':' NEWLINE !" +"INDENT {\n" +" RAISE_INDENTATION_ERROR(\"expected an indented block after 'for' " +"statement on line %d\", a->lineno) }\n" +"invalid_def_raw:\n" +" | ['async'] a='def' NAME [type_params] '(' [params] ')' ['->' " +"expression] ':' NEWLINE !INDENT {\n" +" RAISE_INDENTATION_ERROR(\"expected an indented block after function " +"definition on line %d\", a->lineno) }\n" +" | ['async'] 'def' NAME [type_params] &&'(' [params] ')' ['->' " +"expression] &&':' [func_type_comment] block\n" +"invalid_class_def_raw:\n" +" | 'class' NAME [type_params] ['(' [arguments] ')'] NEWLINE " +"{ RAISE_SYNTAX_ERROR(\"expected ':'\") }\n" +" | a='class' NAME [type_params] ['(' [arguments] ')'] ':' NEWLINE !INDENT " +"{\n" +" RAISE_INDENTATION_ERROR(\"expected an indented block after class " +"definition on line %d\", a->lineno) }\n" +"\n" +"invalid_double_starred_kvpairs:\n" +" | ','.double_starred_kvpair+ ',' invalid_kvpair\n" +" | expression ':' a='*' bitwise_or { RAISE_SYNTAX_ERROR_STARTING_FROM(a, " +"\"cannot use a starred expression in a dictionary value\") }\n" +" | expression a=':' &('}'|',') { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, " +"\"expression expected after dictionary key and ':'\") }\n" +"invalid_kvpair:\n" +" | a=expression !(':') {\n" +" RAISE_ERROR_KNOWN_LOCATION(p, PyExc_SyntaxError, a->lineno, a-" +">end_col_offset - 1, a->end_lineno, -1, \"':' expected after dictionary " +"key\") }\n" +" | expression ':' a='*' bitwise_or { RAISE_SYNTAX_ERROR_STARTING_FROM(a, " +"\"cannot use a starred expression in a dictionary value\") }\n" +" | expression a=':' &('}'|',') {RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, " +"\"expression expected after dictionary key and ':'\") }\n" +"invalid_starred_expression:\n" +" | a='*' expression '=' b=expression { RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, " +"b, \"cannot assign to iterable argument unpacking\") }\n" +"\n" +"invalid_replacement_field:\n" +" | '{' a='=' { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"f-string: valid " +"expression required before '='\") }\n" +" | '{' a='!' { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"f-string: valid " +"expression required before '!'\") }\n" +" | '{' a=':' { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"f-string: valid " +"expression required before ':'\") }\n" +" | '{' a='}' { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, \"f-string: valid " +"expression required before '}'\") }\n" +" | '{' !annotated_rhs { RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(\"f-string: " +"expecting a valid expression after '{'\")}\n" +" | '{' annotated_rhs !('=' | '!' | ':' | '}') {\n" +" PyErr_Occurred() ? NULL : RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(\"f-" +"string: expecting '=', or '!', or ':', or '}'\") }\n" +" | '{' annotated_rhs '=' !('!' | ':' | '}') {\n" +" PyErr_Occurred() ? NULL : RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(\"f-" +"string: expecting '!', or ':', or '}'\") }\n" +" | '{' annotated_rhs '='? invalid_conversion_character\n" +" | '{' annotated_rhs '='? ['!' NAME] !(':' | '}') {\n" +" PyErr_Occurred() ? NULL : RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(\"f-" +"string: expecting ':' or '}'\") }\n" +" | '{' annotated_rhs '='? ['!' NAME] ':' fstring_format_spec* !'}' {\n" +" PyErr_Occurred() ? NULL : RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(\"f-" +"string: expecting '}', or format specs\") }\n" +" | '{' annotated_rhs '='? ['!' NAME] !'}' {\n" +" PyErr_Occurred() ? NULL : RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(\"f-" +"string: expecting '}'\") }\n" +"\n" +"invalid_conversion_character:\n" +" | '!' &(':' | '}') { RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(\"f-string: " +"missing conversion character\") }\n" +" | '!' !NAME { RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(\"f-string: invalid " +"conversion character\") }\n" +"\n" +"invalid_arithmetic:\n" +" | sum ('+'|'-'|'*'|'/'|'%'|'//'|'@') a='not' b=inversion " +"{ RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, \"'not' after an operator must be " +"parenthesized\") }\n" +"invalid_factor:\n" +" | ('+' | '-' | '~') a='not' b=factor { RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, " +"b, \"'not' after an operator must be parenthesized\") }\n" +"\n" +"invalid_type_params:\n" +" | '[' token=']' {\n" +" RAISE_SYNTAX_ERROR_STARTING_FROM(\n" +" token,\n" +" \"Type parameter list cannot be empty\")}\n" +msgstr "" diff --git a/reference/import.po b/reference/import.po index a414db908..734b39be7 100644 --- a/reference/import.po +++ b/reference/import.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Hildeberto Abreu Magalhães , 2023 -# Marco Rougeth , 2023 -# Vinicius Gubiani Ferreira , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-29 04:06+0000\n" -"PO-Revision-Date: 2021-06-28 01:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -236,6 +231,26 @@ msgstr "" "Por exemplo, o layout do sistema de arquivos a seguir define um pacote " "``parent`` de nível superior com três subpacotes::" +#: ../../reference/import.rst:111 +msgid "" +"parent/\n" +" __init__.py\n" +" one/\n" +" __init__.py\n" +" two/\n" +" __init__.py\n" +" three/\n" +" __init__.py" +msgstr "" +"parent/\n" +" __init__.py\n" +" one/\n" +" __init__.py\n" +" two/\n" +" __init__.py\n" +" three/\n" +" __init__.py" + #: ../../reference/import.rst:120 msgid "" "Importing ``parent.one`` will implicitly execute ``parent/__init__.py`` and " @@ -248,11 +263,11 @@ msgstr "" "two`` ou ``parent.three`` vão executar ``parent/two/__init__.py`` e ``parent/" "three/__init__.py``, respectivamente." -#: ../../reference/import.rst:127 +#: ../../reference/import.rst:129 msgid "Namespace packages" msgstr "Pacotes de espaço de nomes" -#: ../../reference/import.rst:133 +#: ../../reference/import.rst:135 msgid "" "A namespace package is a composite of various :term:`portions `, " "where each portion contributes a subpackage to the parent package. Portions " @@ -270,7 +285,7 @@ msgstr "" "nomes podem ou não corresponder diretamente aos objetos no sistema de " "arquivos; eles podem ser módulos virtuais que não têm representação concreta." -#: ../../reference/import.rst:141 +#: ../../reference/import.rst:143 msgid "" "Namespace packages do not use an ordinary list for their ``__path__`` " "attribute. They instead use a custom iterable type which will automatically " @@ -284,7 +299,7 @@ msgstr "" "tentativa de importação dentro desse pacote, se o caminho do pacote pai (ou :" "data:`sys.path` para um pacote de nível superior) for alterado." -#: ../../reference/import.rst:147 +#: ../../reference/import.rst:149 msgid "" "With namespace packages, there is no ``parent/__init__.py`` file. In fact, " "there may be multiple ``parent`` directories found during import search, " @@ -301,16 +316,16 @@ msgstr "" "``pai`` de nível superior sempre que ele ou um de seus subpacotes for " "importado." -#: ../../reference/import.rst:154 +#: ../../reference/import.rst:156 msgid "See also :pep:`420` for the namespace package specification." msgstr "" "Veja também :pep:`420` para a especificação de pacotes de espaço de nomes." -#: ../../reference/import.rst:158 +#: ../../reference/import.rst:160 msgid "Searching" msgstr "Caminho de busca" -#: ../../reference/import.rst:160 +#: ../../reference/import.rst:162 msgid "" "To begin the search, Python needs the :term:`fully qualified ` name of the module (or package, but for the purposes of this " @@ -325,7 +340,7 @@ msgstr "" "para a instrução :keyword:`import`, ou dos parâmetros das funções :func:" "`importlib.import_module` ou :func:`__import__`." -#: ../../reference/import.rst:166 +#: ../../reference/import.rst:168 msgid "" "This name will be used in various phases of the import search, and it may be " "the dotted path to a submodule, e.g. ``foo.bar.baz``. In this case, Python " @@ -339,11 +354,11 @@ msgstr "" "finalmente, ``foo.bar.baz``. Se alguma das importações intermediárias " "falharem, uma exceção :exc:`ModuleNotFoundError` é levantada." -#: ../../reference/import.rst:173 +#: ../../reference/import.rst:175 msgid "The module cache" msgstr "O cache de módulos" -#: ../../reference/import.rst:178 +#: ../../reference/import.rst:180 msgid "" "The first place checked during import search is :data:`sys.modules`. This " "mapping serves as a cache of all modules that have been previously imported, " @@ -359,7 +374,7 @@ msgstr "" "para ``foo``, ``foo.bar`` e ``foo.bar.baz``. Cada chave terá como valor um " "objeto módulo correspondente." -#: ../../reference/import.rst:185 +#: ../../reference/import.rst:187 msgid "" "During import, the module name is looked up in :data:`sys.modules` and if " "present, the associated value is the module satisfying the import, and the " @@ -373,7 +388,7 @@ msgstr "" "`ModuleNotFoundError` é levantada. Se o nome do módulo não foi encontrado, " "Python continuará a busca pelo módulo." -#: ../../reference/import.rst:191 +#: ../../reference/import.rst:193 msgid "" ":data:`sys.modules` is writable. Deleting a key may not destroy the " "associated module (as other modules may hold references to it), but it will " @@ -389,7 +404,7 @@ msgstr "" "``None`` para a chave, forçando que a próxima importação do módulo resulte " "numa exceção :exc:`ModuleNotFoundError`." -#: ../../reference/import.rst:198 +#: ../../reference/import.rst:200 msgid "" "Beware though, as if you keep a reference to the module object, invalidate " "its cache entry in :data:`sys.modules`, and then re-import the named module, " @@ -404,11 +419,11 @@ msgstr "" "objeto módulo e simplesmente reinicializará o conteúdo do módulo executando " "novamente o código do módulo." -#: ../../reference/import.rst:208 +#: ../../reference/import.rst:210 msgid "Finders and loaders" msgstr "Localizadores e carregadores" -#: ../../reference/import.rst:215 +#: ../../reference/import.rst:217 msgid "" "If the named module is not found in :data:`sys.modules`, then Python's " "import protocol is invoked to find and load the module. This protocol " @@ -429,7 +444,7 @@ msgstr "" "retornam a si mesmos, quando eles descobrem que eles podem carregar o módulo " "requisitado." -#: ../../reference/import.rst:223 +#: ../../reference/import.rst:225 msgid "" "Python includes a number of default finders and importers. The first one " "knows how to locate built-in modules, and the second knows how to locate " @@ -446,7 +461,7 @@ msgstr "" "arquivos zip. Ele também pode ser estendido para buscar por qualquer recurso " "localizável, tais como aqueles identificados por URLs." -#: ../../reference/import.rst:230 +#: ../../reference/import.rst:232 msgid "" "The import machinery is extensible, so new finders can be added to extend " "the range and scope of module searching." @@ -454,7 +469,7 @@ msgstr "" "O mecanismo de importação é extensível, então novos localizadores podem ser " "adicionados para estender o alcance e o escopo de buscar módulos." -#: ../../reference/import.rst:233 +#: ../../reference/import.rst:235 msgid "" "Finders do not actually load modules. If they can find the named module, " "they return a :dfn:`module spec`, an encapsulation of the module's import-" @@ -462,11 +477,11 @@ msgid "" "module." msgstr "" "Localizadores na verdade não carregam módulos. Se eles conseguirem encontrar " -"o módulo nomeado, eles retornam uma :dfn:`especificação do módulo`, um " -"encapsulamento da informação relacionada a importação do módulo, a qual o " -"mecanismo de importação então usa quando o módulo é carregado." +"o módulo nomeado, eles retornam um :dfn:`spec de módulo`, um encapsulamento " +"da informação relacionada a importação do módulo, a qual o mecanismo de " +"importação então usa quando o módulo é carregado." -#: ../../reference/import.rst:237 +#: ../../reference/import.rst:239 msgid "" "The following sections describe the protocol for finders and loaders in more " "detail, including how you can create and register new ones to extend the " @@ -476,7 +491,7 @@ msgstr "" "em mais detalhes, incluindo como você pode criar e registrar novos para " "estender o mecanismo de importação." -#: ../../reference/import.rst:241 +#: ../../reference/import.rst:243 msgid "" "In previous versions of Python, finders returned :term:`loaders ` " "directly, whereas now they return module specs which *contain* loaders. " @@ -487,11 +502,11 @@ msgstr "" "especificações de módulo, as qual *contêm* carregadores. Carregadores ainda " "são usados durante a importação, mas possuem menos responsabilidades." -#: ../../reference/import.rst:247 +#: ../../reference/import.rst:249 msgid "Import hooks" msgstr "Ganchos de importação" -#: ../../reference/import.rst:257 +#: ../../reference/import.rst:259 msgid "" "The import machinery is designed to be extensible; the primary mechanism for " "this are the *import hooks*. There are two types of import hooks: *meta " @@ -501,7 +516,7 @@ msgstr "" "primário para isso são os *ganchos de importação*. Existem dois tipos de " "ganchos de importação: *metaganchos* e *ganchos de importação de caminho*." -#: ../../reference/import.rst:261 +#: ../../reference/import.rst:263 msgid "" "Meta hooks are called at the start of import processing, before any other " "import processing has occurred, other than :data:`sys.modules` cache look " @@ -516,7 +531,7 @@ msgstr "" "embutidos. Metaganchos são registrados adicionando novos objetos " "localizadores a :data:`sys.meta_path`, conforme descrito abaixo." -#: ../../reference/import.rst:267 +#: ../../reference/import.rst:269 msgid "" "Import path hooks are called as part of :data:`sys.path` (or ``package." "__path__``) processing, at the point where their associated path item is " @@ -529,32 +544,32 @@ msgstr "" "adicionando novos chamáveis para :data:`sys.path_hooks`, conforme descrito " "abaixo." -#: ../../reference/import.rst:274 +#: ../../reference/import.rst:276 msgid "The meta path" msgstr "O metacaminho" -#: ../../reference/import.rst:280 +#: ../../reference/import.rst:282 msgid "" "When the named module is not found in :data:`sys.modules`, Python next " "searches :data:`sys.meta_path`, which contains a list of meta path finder " "objects. These finders are queried in order to see if they know how to " "handle the named module. Meta path finders must implement a method called :" -"meth:`~importlib.abc.MetaPathFinder.find_spec()` which takes three " -"arguments: a name, an import path, and (optionally) a target module. The " -"meta path finder can use any strategy it wants to determine whether it can " -"handle the named module or not." -msgstr "" -"Quando o módulo nomeado não é encontrado em :data:`sys.modules`, Python em " -"seguida busca :data:`sys.meta_path`, o qual contém uma lista de objetos " -"localizador de metacaminho. Esses buscadores são consultados a fim de " +"meth:`~importlib.abc.MetaPathFinder.find_spec` which takes three arguments: " +"a name, an import path, and (optionally) a target module. The meta path " +"finder can use any strategy it wants to determine whether it can handle the " +"named module or not." +msgstr "" +"Quando o módulo nomeado não é encontrado em :data:`sys.modules`, o Python em " +"seguida o busca em :data:`sys.meta_path`, o qual contém uma lista de objetos " +"localizadores de metacaminho. Esses localizadores são consultados a fim de " "verificar se eles sabem como manipular o módulo nomeado. Os localizadores de " "metacaminho devem implementar um método chamado :meth:`~importlib.abc." -"MetaPathFinder.find_spec()`, o qual recebe três argumentos: um nome, um " +"MetaPathFinder.find_spec`, o qual recebe três argumentos: um nome, um " "caminho de importação, e (opcionalmente) um módulo alvo. O localizador de " "metacaminho pode usar qualquer estratégia que ele quiser para determinar se " "ele pode manipular o módulo nomeado ou não." -#: ../../reference/import.rst:289 +#: ../../reference/import.rst:291 msgid "" "If the meta path finder knows how to handle the named module, it returns a " "spec object. If it cannot handle the named module, it returns ``None``. " @@ -563,15 +578,15 @@ msgid "" "exceptions raised are simply propagated up, aborting the import process." msgstr "" "Se o localizador de metacaminho souber como tratar o módulo nomeado, ele " -"retorna um objeto com especificações. Se ele não puder tratar o módulo " -"nomeado, ele retorna ``None``. Se o processamento de :data:`sys.meta_path` " -"alcançar o fim da sua lista sem retornar uma especificação, então :exc:" -"`ModuleNotFoundError` é levantada. Qualquer outras exceções levantadas são " -"simplesmente propagadas para cima, abortando o processo de importação." +"retorna um objeto spec. Se ele não puder tratar o módulo nomeado, ele " +"retorna ``None``. Se o processamento de :data:`sys.meta_path` alcançar o fim " +"da sua lista sem retornar um spec, então :exc:`ModuleNotFoundError` é " +"levantada. Quaisquer outras exceções levantadas são simplesmente propagadas " +"para cima, abortando o processo de importação." -#: ../../reference/import.rst:295 +#: ../../reference/import.rst:297 msgid "" -"The :meth:`~importlib.abc.MetaPathFinder.find_spec()` method of meta path " +"The :meth:`~importlib.abc.MetaPathFinder.find_spec` method of meta path " "finders is called with two or three arguments. The first is the fully " "qualified name of the module being imported, for example ``foo.bar.baz``. " "The second argument is the path entries to use for the module search. For " @@ -582,19 +597,19 @@ msgid "" "existing module object that will be the target of loading later. The import " "system passes in a target module only during reload." msgstr "" -"O método :meth:`~importlib.abc.MetaPathFinder.find_spec()` dos localizadores " +"O método :meth:`~importlib.abc.MetaPathFinder.find_spec` dos localizadores " "de metacaminhos é chamado com dois ou três argumentos. O primeiro é o nome " "totalmente qualificado do módulo sendo importado, por exemplo ``foo.bar." -"baz``. O segundo argumento é o caminho de entradas para usar para a busca do " -"módulo. Para módulos de alto nível, o segundo argumento é ``None``, mas para " -"submódulos ou subpacotes, o segundo argumento é o valor do atributo " +"baz``. O segundo argumento são as entradas do caminho a ser usado na busca " +"do módulo. Para módulos de nível superior, o segundo argumento é ``None``, " +"mas para submódulos ou subpacotes, o segundo argumento é o valor do atributo " "``__path__`` do pacote pai. Se o atributo ``__path__`` apropriado não puder " "ser acessado, uma exceção :exc:`ModuleNotFoundError` é levantada. O terceiro " "argumento é um objeto módulo existente que será o alvo do carregamento " "posteriormente. O sistema de importação passa um módulo alvo apenas durante " "o recarregamento." -#: ../../reference/import.rst:306 +#: ../../reference/import.rst:308 msgid "" "The meta path may be traversed multiple times for a single import request. " "For example, assuming none of the modules involved has already been cached, " @@ -615,7 +630,7 @@ msgstr "" "None)``. Uma vez que ``foo.bar`` tenha sido importado, a travessia final irá " "chamar ``mpf.find_spec(\"foo.bar.baz\", foo.bar.__path__, None)``." -#: ../../reference/import.rst:316 +#: ../../reference/import.rst:318 msgid "" "Some meta path finders only support top level imports. These importers will " "always return ``None`` when anything other than ``None`` is passed as the " @@ -625,7 +640,7 @@ msgstr "" "nível. Estes importadores vão sempre retornar ``None`` quando qualquer coisa " "diferente de ``None`` for passada como o segundo argumento." -#: ../../reference/import.rst:320 +#: ../../reference/import.rst:322 msgid "" "Python's default :data:`sys.meta_path` has three meta path finders, one that " "knows how to import built-in modules, one that knows how to import frozen " @@ -638,7 +653,7 @@ msgstr "" "term:`caminho de importação` (isto é, o :term:`localizador baseado no " "caminho`)." -#: ../../reference/import.rst:325 +#: ../../reference/import.rst:327 msgid "" "The :meth:`~importlib.abc.MetaPathFinder.find_spec` method of meta path " "finders replaced :meth:`!find_module`, which is now deprecated. While it " @@ -652,7 +667,7 @@ msgstr "" "tentará fazê-lo se o localizador não implementar :meth:`~importlib.abc." "MetaPathFinder.find_spec`." -#: ../../reference/import.rst:332 +#: ../../reference/import.rst:334 msgid "" "Use of :meth:`!find_module` by the import system now raises :exc:" "`ImportWarning`." @@ -660,7 +675,7 @@ msgstr "" "O uso de :meth:`!find_module` pelo sistema de importação agora levanta :exc:" "`ImportWarning`." -#: ../../reference/import.rst:336 +#: ../../reference/import.rst:338 msgid "" ":meth:`!find_module` has been removed. Use :meth:`~importlib.abc." "MetaPathFinder.find_spec` instead." @@ -668,26 +683,86 @@ msgstr "" ":meth:`!find_module` foi removido. Use :meth:`~importlib.abc.MetaPathFinder." "find_spec`." -#: ../../reference/import.rst:342 +#: ../../reference/import.rst:344 msgid "Loading" msgstr "Carregando" -#: ../../reference/import.rst:344 +#: ../../reference/import.rst:346 msgid "" "If and when a module spec is found, the import machinery will use it (and " "the loader it contains) when loading the module. Here is an approximation " "of what happens during the loading portion of import::" msgstr "" -"Se e quando uma especificação do módulo for encontrada, o mecanismo de " -"importação irá usá-lo (e o carregador que ele contém) durante o carregamento " -"do módulo. Aqui está uma aproximação do que acontece durante a etapa de " -"carregamento de uma importação::" +"Se e quando uma spec de módulo é encontrada, o mecanismo de importação vai " +"usá-la (e o carregador que ela contém) durante o carregamento do módulo. " +"Esta é uma aproximação do que acontece durante a etapa de carregamento de " +"uma importação::" + +#: ../../reference/import.rst:350 +msgid "" +"module = None\n" +"if spec.loader is not None and hasattr(spec.loader, 'create_module'):\n" +" # It is assumed 'exec_module' will also be defined on the loader.\n" +" module = spec.loader.create_module(spec)\n" +"if module is None:\n" +" module = ModuleType(spec.name)\n" +"# The import-related module attributes get set here:\n" +"_init_module_attrs(spec, module)\n" +"\n" +"if spec.loader is None:\n" +" # unsupported\n" +" raise ImportError\n" +"if spec.origin is None and spec.submodule_search_locations is not None:\n" +" # namespace package\n" +" sys.modules[spec.name] = module\n" +"elif not hasattr(spec.loader, 'exec_module'):\n" +" module = spec.loader.load_module(spec.name)\n" +"else:\n" +" sys.modules[spec.name] = module\n" +" try:\n" +" spec.loader.exec_module(module)\n" +" except BaseException:\n" +" try:\n" +" del sys.modules[spec.name]\n" +" except KeyError:\n" +" pass\n" +" raise\n" +"return sys.modules[spec.name]" +msgstr "" +"module = None\n" +"if spec.loader is not None and hasattr(spec.loader, 'create_module'):\n" +" # É assumido que o carregador também define 'exec_module'.\n" +" module = spec.loader.create_module(spec)\n" +"if module is None:\n" +" module = ModuleType(spec.name)\n" +"# Define os atributos do módulo relacionados à importação:\n" +"_init_module_attrs(spec, module)\n" +"\n" +"if spec.loader is None:\n" +" # não suportado\n" +" raise ImportError\n" +"if spec.origin is None and spec.submodule_search_locations is not None:\n" +" # pacote espaço de nomes\n" +" sys.modules[spec.name] = module\n" +"elif not hasattr(spec.loader, 'exec_module'):\n" +" module = spec.loader.load_module(spec.name)\n" +"else:\n" +" sys.modules[spec.name] = module\n" +" try:\n" +" spec.loader.exec_module(module)\n" +" except BaseException:\n" +" try:\n" +" del sys.modules[spec.name]\n" +" except KeyError:\n" +" pass\n" +" raise\n" +"return sys.modules[spec.name]" -#: ../../reference/import.rst:377 +#: ../../reference/import.rst:379 msgid "Note the following details:" msgstr "Perceba os seguintes detalhes:" -#: ../../reference/import.rst:379 +#: ../../reference/import.rst:381 msgid "" "If there is an existing module object with the given name in :data:`sys." "modules`, import will have already returned it." @@ -695,7 +770,7 @@ msgstr "" "Se houver um objeto módulo existente com o nome fornecido em :data:`sys." "modules`, a importação já tera retornado ele." -#: ../../reference/import.rst:382 +#: ../../reference/import.rst:384 msgid "" "The module will exist in :data:`sys.modules` before the loader executes the " "module code. This is crucial because the module code may (directly or " @@ -709,7 +784,7 @@ msgstr "" "antecipadamente previne recursão infinita no pior caso e múltiplos " "carregamentos no melhor caso." -#: ../../reference/import.rst:388 +#: ../../reference/import.rst:390 msgid "" "If loading fails, the failing module -- and only the failing module -- gets " "removed from :data:`sys.modules`. Any module already in the :data:`sys." @@ -724,7 +799,7 @@ msgstr "" "com recarregamento, onde mesmo o módulo com falha é mantido em :data:`sys." "modules`." -#: ../../reference/import.rst:394 +#: ../../reference/import.rst:396 msgid "" "After the module is created but before execution, the import machinery sets " "the import-related module attributes (\"_init_module_attrs\" in the pseudo-" @@ -736,7 +811,7 @@ msgstr "" "(\"_init_module_attrs\" no exemplo de pseudocódigo acima), assim como foi " "resumido em :ref:`uma seção posterior `." -#: ../../reference/import.rst:399 +#: ../../reference/import.rst:401 msgid "" "Module execution is the key moment of loading in which the module's " "namespace gets populated. Execution is entirely delegated to the loader, " @@ -746,7 +821,7 @@ msgstr "" "nomes do módulo é populado. Execução é inteiramente delegada para o " "carregador, o qual pode decidir o que será populado e como." -#: ../../reference/import.rst:403 +#: ../../reference/import.rst:405 msgid "" "The module created during loading and passed to exec_module() may not be the " "one returned at the end of import [#fnlo]_." @@ -754,7 +829,7 @@ msgstr "" "O módulo criado durante o carregamento e passado para exec_module() pode não " "ser aquele retornado ao final da importação [#fnlo]_." -#: ../../reference/import.rst:406 +#: ../../reference/import.rst:408 msgid "" "The import system has taken over the boilerplate responsibilities of " "loaders. These were previously performed by the :meth:`importlib.abc.Loader." @@ -764,11 +839,11 @@ msgstr "" "carregadores. Essas responsabilidades eram anteriormente executadas pelo " "método :meth:`importlib.abc.Loader.load_module`." -#: ../../reference/import.rst:412 +#: ../../reference/import.rst:414 msgid "Loaders" msgstr "Carregadores" -#: ../../reference/import.rst:414 +#: ../../reference/import.rst:416 msgid "" "Module loaders provide the critical function of loading: module execution. " "The import machinery calls the :meth:`importlib.abc.Loader.exec_module` " @@ -781,11 +856,11 @@ msgstr "" "módulo a ser executado. Qualquer valor retornado de :meth:`~importlib.abc." "Loader.exec_module` é ignorado." -#: ../../reference/import.rst:419 +#: ../../reference/import.rst:421 msgid "Loaders must satisfy the following requirements:" msgstr "Os carregadores devem atender aos seguintes requisitos:" -#: ../../reference/import.rst:421 +#: ../../reference/import.rst:423 msgid "" "If the module is a Python module (as opposed to a built-in module or a " "dynamically loaded extension), the loader should execute the module's code " @@ -795,7 +870,7 @@ msgstr "" "extensão carregada dinamicamente), o carregador deve executar o código do " "módulo no espaço de nomes global do módulo (``module.__dict__``)." -#: ../../reference/import.rst:425 +#: ../../reference/import.rst:427 msgid "" "If the loader cannot execute the module, it should raise an :exc:" "`ImportError`, although any other exception raised during :meth:`~importlib." @@ -805,7 +880,7 @@ msgstr "" "exc:`ImportError`, embora qualquer outra exceção levantada durante :meth:" "`~importlib.abc.Loader.exec_module` será propagada." -#: ../../reference/import.rst:429 +#: ../../reference/import.rst:431 msgid "" "In many cases, the finder and loader can be the same object; in such cases " "the :meth:`~importlib.abc.MetaPathFinder.find_spec` method would just return " @@ -813,9 +888,9 @@ msgid "" msgstr "" "Em muitos casos, o localizador e o carregador podem ser o mesmo objeto; " "nesses casos o método :meth:`~importlib.abc.MetaPathFinder.find_spec` apenas " -"retornaria uma especificação com o carregador definido como ``self``." +"retornaria um spec com o carregador definido como ``self``." -#: ../../reference/import.rst:433 +#: ../../reference/import.rst:435 msgid "" "Module loaders may opt in to creating the module object during loading by " "implementing a :meth:`~importlib.abc.Loader.create_module` method. It takes " @@ -826,16 +901,16 @@ msgid "" msgstr "" "Os carregadores de módulo podem optar por criar o objeto do módulo durante o " "carregamento, implementando um método :meth:`~importlib.abc.Loader." -"create_module`. Leva um argumento, a especificação do módulo e retorna o " -"novo objeto do módulo para usar durante o carregamento. ``create_module()`` " -"não precisa definir nenhum atributo no objeto do módulo. Se o método " -"retornar ``None``, o mecanismo de importação criará ele mesmo o novo módulo." +"create_module`. Leva um argumento, o spec de módulo e retorna o novo objeto " +"do módulo para usar durante o carregamento. ``create_module()`` não precisa " +"definir nenhum atributo no objeto do módulo. Se o método retornar ``None``, " +"o mecanismo de importação criará ele mesmo o novo módulo." -#: ../../reference/import.rst:440 +#: ../../reference/import.rst:442 msgid "The :meth:`~importlib.abc.Loader.create_module` method of loaders." msgstr "O método :meth:`~importlib.abc.Loader.create_module` de carregadores." -#: ../../reference/import.rst:443 +#: ../../reference/import.rst:445 msgid "" "The :meth:`~importlib.abc.Loader.load_module` method was replaced by :meth:" "`~importlib.abc.Loader.exec_module` and the import machinery assumed all the " @@ -845,7 +920,7 @@ msgstr "" "`~importlib.abc.Loader.exec_module` e o mecanismo de importação assumiu " "todas as responsabilidades inerentes de carregamento." -#: ../../reference/import.rst:448 +#: ../../reference/import.rst:450 msgid "" "For compatibility with existing loaders, the import machinery will use the " "``load_module()`` method of loaders if it exists and the loader does not " @@ -858,7 +933,7 @@ msgstr "" "``load_module()`` foi descontinuado e os carregadores devem implementar " "``exec_module()`` em seu lugar." -#: ../../reference/import.rst:453 +#: ../../reference/import.rst:455 msgid "" "The ``load_module()`` method must implement all the boilerplate loading " "functionality described above in addition to executing the module. All the " @@ -868,7 +943,7 @@ msgstr "" "de carregamento descrita acima, além de executar o módulo. Todas as mesmas " "restrições se aplicam, com alguns esclarecimentos adicionais:" -#: ../../reference/import.rst:457 +#: ../../reference/import.rst:459 msgid "" "If there is an existing module object with the given name in :data:`sys." "modules`, the loader must use that existing module. (Otherwise, :func:" @@ -882,7 +957,7 @@ msgstr "" "não existir em :data:`sys.modules`, o carregador deverá criar um novo objeto " "de módulo e adicioná-lo a :data:`sys.modules`." -#: ../../reference/import.rst:463 +#: ../../reference/import.rst:465 msgid "" "The module *must* exist in :data:`sys.modules` before the loader executes " "the module code, to prevent unbounded recursion or multiple loading." @@ -891,7 +966,7 @@ msgstr "" "execute o código do módulo, para evitar recursão ilimitada ou carregamento " "múltiplo." -#: ../../reference/import.rst:467 +#: ../../reference/import.rst:469 msgid "" "If loading fails, the loader must remove any modules it has inserted into :" "data:`sys.modules`, but it must remove **only** the failing module(s), and " @@ -902,7 +977,7 @@ msgstr "" "módulo(s) com falha, e somente se o próprio carregador tiver carregado o(s) " "módulo(s) explicitamente." -#: ../../reference/import.rst:472 +#: ../../reference/import.rst:474 msgid "" "A :exc:`DeprecationWarning` is raised when ``exec_module()`` is defined but " "``create_module()`` is not." @@ -910,7 +985,7 @@ msgstr "" "Uma exceção :exc:`DeprecationWarning` é levantada quando ``exec_module()`` " "está definido, mas ``create_module()`` não." -#: ../../reference/import.rst:476 +#: ../../reference/import.rst:478 msgid "" "An :exc:`ImportError` is raised when ``exec_module()`` is defined but " "``create_module()`` is not." @@ -918,15 +993,15 @@ msgstr "" "Uma exceção :exc:`ImportError` é levantada quando ``exec_module()`` está " "definido, mas ``create_module()`` não." -#: ../../reference/import.rst:480 +#: ../../reference/import.rst:482 msgid "Use of ``load_module()`` will raise :exc:`ImportWarning`." msgstr "O uso de ``load_module()`` vai levantar :exc:`ImportWarning`." -#: ../../reference/import.rst:484 +#: ../../reference/import.rst:486 msgid "Submodules" msgstr "Submódulos" -#: ../../reference/import.rst:486 +#: ../../reference/import.rst:488 msgid "" "When a submodule is loaded using any mechanism (e.g. ``importlib`` APIs, the " "``import`` or ``import-from`` statements, or built-in ``__import__()``) a " @@ -936,18 +1011,32 @@ msgid "" "submodule. Let's say you have the following directory structure::" msgstr "" "Quando um submódulo é carregado usando qualquer mecanismo (por exemplo, APIs " -"``importlib``, as instruções ``import`` ou ``import-from``, ou " -"``__import__()`` embutidas) uma ligação é colocada no espaço de nomes do " +"``importlib``, as instruções ``import`` ou ``import-from``, ou a função " +"``__import__()`` embutida) uma ligação é colocada no espaço de nomes do " "módulo pai para o objeto submódulo. Por exemplo, se o pacote ``spam`` tiver " "um submódulo ``foo``, após importar ``spam.foo``, ``spam`` terá um atributo " "``foo`` que está vinculado ao submódulo. Digamos que você tenha a seguinte " "estrutura de diretórios::" -#: ../../reference/import.rst:497 +#: ../../reference/import.rst:495 +msgid "" +"spam/\n" +" __init__.py\n" +" foo.py" +msgstr "" +"spam/\n" +" __init__.py\n" +" foo.py" + +#: ../../reference/import.rst:499 msgid "and ``spam/__init__.py`` has the following line in it::" msgstr "e ``spam/__init__.py`` tem a seguinte linha::" #: ../../reference/import.rst:501 +msgid "from .foo import Foo" +msgstr "from .foo import Foo" + +#: ../../reference/import.rst:503 msgid "" "then executing the following puts name bindings for ``foo`` and ``Foo`` in " "the ``spam`` module::" @@ -955,7 +1044,21 @@ msgstr "" "então executar o seguinte coloca ligações de nome para ``foo`` e ``Foo`` no " "módulo ``spam``::" -#: ../../reference/import.rst:510 +#: ../../reference/import.rst:506 +msgid "" +">>> import spam\n" +">>> spam.foo\n" +"\n" +">>> spam.Foo\n" +"" +msgstr "" +">>> import spam\n" +">>> spam.foo\n" +"\n" +">>> spam.Foo\n" +"" + +#: ../../reference/import.rst:512 msgid "" "Given Python's familiar name binding rules this might seem surprising, but " "it's actually a fundamental feature of the import system. The invariant " @@ -970,11 +1073,11 @@ msgstr "" "importação acima), o último deve aparecer como o atributo ``foo`` do " "primeiro." -#: ../../reference/import.rst:517 -msgid "Module spec" -msgstr "Especificação do módulo" +#: ../../reference/import.rst:521 +msgid "Module specs" +msgstr "Especificações de módulo" -#: ../../reference/import.rst:519 +#: ../../reference/import.rst:523 msgid "" "The import machinery uses a variety of information about each module during " "import, especially before loading. Most of the information is common to all " @@ -983,11 +1086,10 @@ msgid "" msgstr "" "O mecanismo de importação utiliza diversas informações sobre cada módulo " "durante a importação, principalmente antes do carregamento. A maior parte " -"das informações é comum a todos os módulos. O propósito de uma especificação " -"de módulo (spec) é encapsular essas informações relacionadas à importação " -"por módulo." +"das informações é comum a todos os módulos. O propósito da spec do módulo é " +"encapsular essas informações relacionadas à importação por módulo." -#: ../../reference/import.rst:524 +#: ../../reference/import.rst:528 msgid "" "Using a spec during import allows state to be transferred between import " "system components, e.g. between the finder that creates the module spec and " @@ -995,310 +1097,106 @@ msgid "" "machinery to perform the boilerplate operations of loading, whereas without " "a module spec the loader had that responsibility." msgstr "" -"Usar uma especificação durante a importação permite que o estado seja " -"transferido entre componentes do sistema de importação, por exemplo. entre o " -"localizador que cria a especificação do módulo e o carregador que o executa. " -"Mais importante ainda, permite que o mecanismo de importação execute as " -"operações inerentes de carregamento, enquanto que sem uma especificação de " -"módulo o carregador tinha essa responsabilidade." - -#: ../../reference/import.rst:530 -msgid "" -"The module's spec is exposed as the ``__spec__`` attribute on a module " -"object. See :class:`~importlib.machinery.ModuleSpec` for details on the " -"contents of the module spec." -msgstr "" -"A especificação do módulo é exposta como o atributo ``__spec__`` em um " -"objeto módulo. Veja :class:`~importlib.machinery.ModuleSpec` para detalhes " -"sobre o conteúdo da especificação do módulo." - -#: ../../reference/import.rst:539 -msgid "Import-related module attributes" -msgstr "Atributos de módulo relacionados à importação" - -#: ../../reference/import.rst:541 -msgid "" -"The import machinery fills in these attributes on each module object during " -"loading, based on the module's spec, before the loader executes the module." -msgstr "" -"O mecanismo de importação preenche esses atributos em cada objeto do módulo " -"durante o carregamento, com base na especificação do módulo, antes que o " -"carregador execute o módulo." - -#: ../../reference/import.rst:545 -msgid "" -"It is **strongly** recommended that you rely on :attr:`__spec__` and its " -"attributes instead of any of the other individual attributes listed below." -msgstr "" -"É **fortemente** recomendado que você confie em :attr:`__spec__` e seus " -"atributos em vez de qualquer um dos outros atributos individuais listados " -"abaixo." - -#: ../../reference/import.rst:551 -msgid "" -"The ``__name__`` attribute must be set to the fully qualified name of the " -"module. This name is used to uniquely identify the module in the import " -"system." -msgstr "" -"O atributo ``__name__`` deve ser definido como o nome totalmente qualificado " -"do módulo. Este nome é usado para identificar exclusivamente o módulo no " -"sistema de importação." - -#: ../../reference/import.rst:557 -msgid "" -"The ``__loader__`` attribute must be set to the loader object that the " -"import machinery used when loading the module. This is mostly for " -"introspection, but can be used for additional loader-specific functionality, " -"for example getting data associated with a loader." -msgstr "" -"O atributo ``__loader__`` deve ser definido para o objeto carregador que o " -"mecanismo de importação usou ao carregar o módulo. Isto é principalmente " -"para introspecção, mas pode ser usado para funcionalidades adicionais " -"específicas do carregador, por exemplo, obter dados associados a um " -"carregador." - -#: ../../reference/import.rst:562 ../../reference/import.rst:583 -msgid "" -"It is **strongly** recommended that you rely on :attr:`__spec__` instead of " -"this attribute." -msgstr "" -"É **fortemente** recomendado que você confie em :attr:`__spec__` em vez " -"deste atributo." - -#: ../../reference/import.rst:565 -msgid "" -"The value of ``__loader__`` is expected to be the same as ``__spec__." -"loader``. The use of ``__loader__`` is deprecated and slated for removal in " -"Python 3.14." -msgstr "" -"Espera-se que o valor de ``__loader__`` seja o mesmo que ``__spec__." -"loader``. O uso de ``__loader__`` foi descontinuado e programado para " -"remoção no Python 3.14." - -#: ../../reference/import.rst:572 -msgid "" -"The module's ``__package__`` attribute may be set. Its value must be a " -"string, but it can be the same value as its ``__name__``. When the module " -"is a package, its ``__package__`` value should be set to its ``__name__``. " -"When the module is not a package, ``__package__`` should be set to the empty " -"string for top-level modules, or for submodules, to the parent package's " -"name. See :pep:`366` for further details." -msgstr "" -"O atributo ``__package__`` do módulo pode ser definido. Seu valor deve ser " -"uma string, mas pode ser o mesmo valor que seu ``__name__``. Quando o módulo " -"é um pacote, seu valor ``__package__`` deve ser definido como seu " -"``__name__``. Quando o módulo não é um pacote, ``__package__`` deve ser " -"definido como uma string vazia para módulos de nível superior, ou para " -"submódulos, como o nome do pacote pai. Veja :pep:`366` para mais detalhes." +"Usar um spec durante a importação permite que o estado seja transferido " +"entre componentes do sistema de importação, por exemplo entre o localizador " +"que cria o spec de módulo e o carregador que o executa. Mais importante " +"ainda, permite que o mecanismo de importação execute as operações inerentes " +"de carregamento, enquanto que sem um spec de módulo o carregador tinha essa " +"responsabilidade." -#: ../../reference/import.rst:580 +#: ../../reference/import.rst:534 msgid "" -"This attribute is used instead of ``__name__`` to calculate explicit " -"relative imports for main modules, as defined in :pep:`366`." +"The module's spec is exposed as :attr:`module.__spec__`. Setting :attr:`!" +"__spec__` appropriately applies equally to :ref:`modules initialized during " +"interpreter startup `. The one exception is ``__main__``, where :" +"attr:`!__spec__` is :ref:`set to None in some cases `." msgstr "" -"Este atributo é usado em vez de ``__name__`` para calcular importações " -"relativas explícitas para módulos principais, conforme definido na :pep:" -"`366`." +"O spec do módulo é exposto no atributo :attr:`module.__spec__`. A " +"configuração oportuna do :attr:`!__spec__` se aplica igualmente aos :ref:" +"`módulos inicializados durante a inicialização do interpretador `. " +"A única exceção é o ``__main__``, cujo :attr:`!__spec__` é :ref:`definido " +"como None em alguns casos `." -#: ../../reference/import.rst:586 +#: ../../reference/import.rst:540 msgid "" -"The value of ``__package__`` is expected to be the same as ``__spec__." -"parent``." +"See :class:`~importlib.machinery.ModuleSpec` for details on the contents of " +"the module spec." msgstr "" -"Espera-se que o valor de ``__package__`` seja o mesmo que ``__spec__." -"parent``." +"Consulte :class:`~importlib.machinery.ModuleSpec` para detalhes sobre o " +"conteúdo do spec de módulo." -#: ../../reference/import.rst:590 -msgid "" -":exc:`ImportWarning` is raised if import falls back to ``__package__`` " -"instead of :attr:`~importlib.machinery.ModuleSpec.parent`." -msgstr "" -":exc:`ImportWarning` é levantada se a importação retornar para " -"``__package__`` em vez de :attr:`~importlib.machinery.ModuleSpec.parent`." - -#: ../../reference/import.rst:595 -msgid "" -"Raise :exc:`DeprecationWarning` instead of :exc:`ImportWarning` when falling " -"back to ``__package__``." -msgstr "" -"Levanta :exc:`DeprecationWarning` em vez de :exc:`ImportWarning` ao se " -"recorrer a ``__package__``." - -#: ../../reference/import.rst:602 -msgid "" -"The ``__spec__`` attribute must be set to the module spec that was used when " -"importing the module. Setting ``__spec__`` appropriately applies equally to :" -"ref:`modules initialized during interpreter startup `. The one " -"exception is ``__main__``, where ``__spec__`` is :ref:`set to None in some " -"cases `." -msgstr "" -"O atributo ``__spec__`` deve ser definido para a especificação do módulo que " -"foi usada ao importar o módulo. Definir ``__spec__`` apropriadamente se " -"aplica igualmente a :ref:`módulos inicializados durante a inicialização do " -"interpretador `. A única exceção é ``__main__``, onde ``__spec__`` " -"é :ref:`definido como None em alguns casos `." +#: ../../reference/import.rst:548 +msgid "__path__ attributes on modules" +msgstr "Atributo __path__ dos módulos" -#: ../../reference/import.rst:608 +#: ../../reference/import.rst:550 msgid "" -"When ``__spec__.parent`` is not set, ``__package__`` is used as a fallback." +"The :attr:`~module.__path__` attribute should be a (possibly empty) :term:" +"`sequence` of strings enumerating the locations where the package's " +"submodules will be found. By definition, if a module has a :attr:`!__path__` " +"attribute, it is a :term:`package`." msgstr "" -"Quando ``__spec__.parent`` não está definido, ``__package__`` é usado com " -"alternativa." +"O atributo :attr:`~module.__path__` deve ser uma :term:`sequência` " +"(possivelmente vazia) de strings enumerando os locais onde os submódulos do " +"pacote serão encontrados. Por definição, um módulo que tenha um atributo :" +"attr:`!__path__` é um :term:`pacote`." -#: ../../reference/import.rst:613 -msgid "" -"``__spec__.parent`` is used as a fallback when ``__package__`` is not " -"defined." -msgstr "" -"``__spec__.parent`` é usado como uma alternativa quando ``__package__`` não " -"está definido." - -#: ../../reference/import.rst:619 +#: ../../reference/import.rst:555 msgid "" -"If the module is a package (either regular or namespace), the module " -"object's ``__path__`` attribute must be set. The value must be iterable, " -"but may be empty if ``__path__`` has no further significance. If " -"``__path__`` is not empty, it must produce strings when iterated over. More " -"details on the semantics of ``__path__`` are given :ref:`below `." -msgstr "" -"Se o módulo for um pacote (normal ou espaço de nomes), o atributo " -"``__path__`` do objeto do módulo deve ser definido. O valor deve ser " -"iterável, mas pode estar vazio se ``__path__`` não tiver mais significado. " -"Se ``__path__`` não estiver vazio, ele deverá produzir strings quando " -"iterado. Mais detalhes sobre a semântica de ``__path__`` são fornecidos :ref:" -"`abaixo `." - -#: ../../reference/import.rst:626 -msgid "Non-package modules should not have a ``__path__`` attribute." -msgstr "Módulos que não são de pacote não devem ter um atributo ``__path__``." - -#: ../../reference/import.rst:631 -msgid "" -"``__file__`` is optional (if set, value must be a string). It indicates the " -"pathname of the file from which the module was loaded (if loaded from a " -"file), or the pathname of the shared library file for extension modules " -"loaded dynamically from a shared library. It might be missing for certain " -"types of modules, such as C modules that are statically linked into the " -"interpreter, and the import system may opt to leave it unset if it has no " -"semantic meaning (e.g. a module loaded from a database)." -msgstr "" -"``__file__`` é opcional (se definido, o valor deve ser uma string). Indica o " -"nome do caminho do arquivo do qual o módulo foi carregado (se carregado de " -"um arquivo) ou o nome do caminho do arquivo da biblioteca compartilhada para " -"módulos de extensão carregados dinamicamente de uma biblioteca " -"compartilhada. Pode estar faltando para certos tipos de módulos, como " -"módulos C que estão estaticamente vinculados ao interpretador, e o sistema " -"de importação pode optar por deixá-lo sem definição se não tiver significado " -"semântico (por exemplo, um módulo carregado de um banco de dados)." - -#: ../../reference/import.rst:640 -msgid "" -"If ``__file__`` is set then the ``__cached__`` attribute might also be set, " -"which is the path to any compiled version of the code (e.g. byte-compiled " -"file). The file does not need to exist to set this attribute; the path can " -"simply point to where the compiled file would exist (see :pep:`3147`)." -msgstr "" -"Se ``__file__`` estiver definido então o atributo ``__cached__`` também pode " -"ser definido, que é o caminho para qualquer versão compilada do código (por " -"exemplo, arquivo compilado por byte). O arquivo não precisa existir para " -"configurar esse atributo; o caminho pode simplesmente apontar para onde o " -"arquivo compilado existiria (veja :pep:`3147`)." - -#: ../../reference/import.rst:646 -msgid "" -"Note that ``__cached__`` may be set even if ``__file__`` is not set. " -"However, that scenario is quite atypical. Ultimately, the loader is what " -"makes use of the module spec provided by the finder (from which ``__file__`` " -"and ``__cached__`` are derived). So if a loader can load from a cached " -"module but otherwise does not load from a file, that atypical scenario may " -"be appropriate." -msgstr "" -"Observe que ``__cached__`` pode ser definido mesmo se ``__file__`` não " -"estiver definido. No entanto, esse cenário é bastante atípico. Em última " -"análise, o carregador é o que faz uso da especificação do módulo fornecida " -"pelo localizador (do qual ``__file__`` e ``__cached__`` são derivados). " -"Portanto, se um carregador puder carregar a partir de um módulo em cache, " -"mas não carregar a partir de um arquivo, esse cenário atípico poderá ser " -"apropriado." - -#: ../../reference/import.rst:653 -msgid "" -"It is **strongly** recommended that you rely on :attr:`__spec__` instead of " -"``__cached__``." -msgstr "" -"É **fortemente** recomendado que você confie em :attr:`__spec__` em vez de " -"``__cached__``." - -#: ../../reference/import.rst:659 -msgid "module.__path__" -msgstr "module.__path__" - -#: ../../reference/import.rst:661 -msgid "" -"By definition, if a module has a ``__path__`` attribute, it is a package." -msgstr "" -"Por definição, se um módulo possui um atributo ``__path__``, ele é um pacote." - -#: ../../reference/import.rst:663 -msgid "" -"A package's ``__path__`` attribute is used during imports of its " +"A package's :attr:`~module.__path__` attribute is used during imports of its " "subpackages. Within the import machinery, it functions much the same as :" "data:`sys.path`, i.e. providing a list of locations to search for modules " -"during import. However, ``__path__`` is typically much more constrained " -"than :data:`sys.path`." -msgstr "" -"O atributo ``__path__`` de um pacote é usado durante as importações de seus " -"subpacotes. Dentro do mecanismo de importação, funciona da mesma forma que :" -"data:`sys.path`, ou seja, fornecendo uma lista de locais para procurar " -"módulos durante a importação. Entretanto, ``__path__`` normalmente é muito " -"mais restrito que :data:`sys.path`." - -#: ../../reference/import.rst:669 -msgid "" -"``__path__`` must be an iterable of strings, but it may be empty. The same " -"rules used for :data:`sys.path` also apply to a package's ``__path__``, and :" -"data:`sys.path_hooks` (described below) are consulted when traversing a " -"package's ``__path__``." -msgstr "" -"``__path__`` deve ser um iterável de strings, mas pode estar vazio. As " -"mesmas regras usadas para :data:`sys.path` também se aplicam ao ``__path__`` " -"de um pacote, e :data:`sys.path_hooks` (descrito abaixo) são consultados ao " -"percorrer o ``__path__`` de um pacote." - -#: ../../reference/import.rst:674 -msgid "" -"A package's ``__init__.py`` file may set or alter the package's ``__path__`` " -"attribute, and this was typically the way namespace packages were " -"implemented prior to :pep:`420`. With the adoption of :pep:`420`, namespace " -"packages no longer need to supply ``__init__.py`` files containing only " -"``__path__`` manipulation code; the import machinery automatically sets " -"``__path__`` correctly for the namespace package." -msgstr "" -"O arquivo ``__init__.py`` de um pacote pode definir ou alterar o atributo " -"``__path__`` do pacote, e esta era tipicamente a forma como os pacotes de " -"espaço de nomes eram implementados antes de :pep:`420`. Com a adoção da :pep:" -"`420`, os pacotes de espaço de nomes não precisam mais fornecer arquivos " -"``__init__.py`` contendo apenas código de manipulação de ``__path__``; o " -"mecanismo de importação define automaticamente ``__path__`` corretamente " -"para o pacote de espaço de nomes." - -#: ../../reference/import.rst:682 +"during import. However, :attr:`!__path__` is typically much more constrained " +"than :data:`!sys.path`." +msgstr "" +"O atributo :attr:`~module.__path__` de um pacote é usado durante as " +"importações de seus subpacotes. Dentro do mecanismo de importação, funciona " +"da mesma forma que :data:`sys.path`, ou seja, fornecendo uma lista de locais " +"para procurar módulos durante a importação. Entretanto, o :attr:`!__path__` " +"normalmente é muito mais restrito que :data:`!sys.path`." + +#: ../../reference/import.rst:562 +msgid "" +"The same rules used for :data:`sys.path` also apply to a package's :attr:`!" +"__path__`. :data:`sys.path_hooks` (described below) are consulted when " +"traversing a package's :attr:`!__path__`." +msgstr "" +"As mesmas regras usadas para :data:`sys.path` também se aplicam ao :attr:`!" +"__path__` de um pacote. Os :data:`sys.path_hooks` (descritos abaixo) são " +"consultados ao percorrer o :attr:`!__path__` de um pacote." + +#: ../../reference/import.rst:566 +msgid "" +"A package's ``__init__.py`` file may set or alter the package's :attr:" +"`~module.__path__` attribute, and this was typically the way namespace " +"packages were implemented prior to :pep:`420`. With the adoption of :pep:" +"`420`, namespace packages no longer need to supply ``__init__.py`` files " +"containing only :attr:`!__path__` manipulation code; the import machinery " +"automatically sets :attr:`!__path__` correctly for the namespace package." +msgstr "" +"O arquivo ``__init__.py`` de um pacote pode definir ou alterar o atributo :" +"attr:`~module.__path__` do pacote, e esta era tipicamente a forma como os " +"pacotes de espaço de nomes eram implementados antes da :pep:`420`. Com a " +"adoção da :pep:`420`, os pacotes de espaço de nomes não precisam mais " +"fornecer arquivos ``__init__.py`` contendo apenas código de manipulação do :" +"attr:`!__path__`; o mecanismo de importação define automaticamente o :attr:`!" +"__path__` corretamente para o pacote de espaço de nomes." + +#: ../../reference/import.rst:575 msgid "Module reprs" msgstr "Representações do módulo" -#: ../../reference/import.rst:684 +#: ../../reference/import.rst:577 msgid "" "By default, all modules have a usable repr, however depending on the " "attributes set above, and in the module's spec, you can more explicitly " "control the repr of module objects." msgstr "" "Por padrão, todos os módulos têm uma representação (repr) utilizável, no " -"entanto, dependendo dos atributos definidos acima e da especificação do " -"módulo, você pode controlar mais explicitamente a representação dos objetos " -"módulo." +"entanto, dependendo dos atributos definidos acima e do spec do módulo, você " +"pode controlar mais explicitamente a representação dos objetos módulo." -#: ../../reference/import.rst:688 +#: ../../reference/import.rst:581 msgid "" "If the module has a spec (``__spec__``), the import machinery will try to " "generate a repr from it. If that fails or there is no spec, the import " @@ -1307,29 +1205,28 @@ msgid "" "__file__``, and ``module.__loader__`` as input into the repr, with defaults " "for whatever information is missing." msgstr "" -"Se o módulo tiver uma especificação (``__spec__``), o mecanismo de " -"importação tentará gerar uma representação a partir dele. Se isso falhar ou " -"não houver nenhuma especificação, o sistema de importação criará uma " -"representação padrão usando qualquer informação disponível no módulo. Ele " -"tentará usar ``module.__name__``, ``module.__file__`` e ``module." -"__loader__`` como entrada para a representação, com padrões para qualquer " -"informação que esteja faltando." +"Se o módulo tiver um spec (``__spec__``), o mecanismo de importação tentará " +"gerar uma representação a partir dele. Se isso falhar ou não houver nenhuma " +"especificação, o sistema de importação criará uma representação padrão " +"usando qualquer informação disponível no módulo. Ele tentará usar ``module." +"__name__``, ``module.__file__`` e ``module.__loader__`` como entrada para a " +"representação, com padrões para qualquer informação que esteja faltando." -#: ../../reference/import.rst:695 +#: ../../reference/import.rst:588 msgid "Here are the exact rules used:" msgstr "Arquivo estão as exatas regras usadas:" -#: ../../reference/import.rst:697 +#: ../../reference/import.rst:590 msgid "" "If the module has a ``__spec__`` attribute, the information in the spec is " "used to generate the repr. The \"name\", \"loader\", \"origin\", and " "\"has_location\" attributes are consulted." msgstr "" -"Se o módulo tiver um atributo ``__spec__``, a informação na especificação é " -"usada para gerar a representação. Os atributos \"name\", \"loader\", " -"\"origin\" e \"has_location\" são consultados." +"Se o módulo tiver um atributo ``__spec__``, a informação no spec é usada " +"para gerar a representação. Os atributos \"name\", \"loader\", \"origin\" e " +"\"has_location\" são consultados." -#: ../../reference/import.rst:701 +#: ../../reference/import.rst:594 msgid "" "If the module has a ``__file__`` attribute, this is used as part of the " "module's repr." @@ -1337,7 +1234,7 @@ msgstr "" "Se o módulo tiver um atributo ``__file__``, ele será usado como parte da " "representação do módulo." -#: ../../reference/import.rst:704 +#: ../../reference/import.rst:597 msgid "" "If the module has no ``__file__`` but does have a ``__loader__`` that is not " "``None``, then the loader's repr is used as part of the module's repr." @@ -1346,11 +1243,11 @@ msgstr "" "``None``, então a representação do carregador é usado como parte da " "representação do módulo." -#: ../../reference/import.rst:707 +#: ../../reference/import.rst:600 msgid "Otherwise, just use the module's ``__name__`` in the repr." msgstr "Caso contrário, basta usar o ``__name__`` do módulo na representação." -#: ../../reference/import.rst:709 +#: ../../reference/import.rst:602 msgid "" "Use of :meth:`!module_repr`, having been deprecated since Python 3.4, was " "removed in Python 3.12 and is no longer called during the resolution of a " @@ -1360,11 +1257,11 @@ msgstr "" "removido no Python 3.12 e não é mais chamado durante a resolução da " "representação de um módulo." -#: ../../reference/import.rst:717 +#: ../../reference/import.rst:610 msgid "Cached bytecode invalidation" msgstr "Invalidação de bytecode em cache" -#: ../../reference/import.rst:719 +#: ../../reference/import.rst:612 msgid "" "Before Python loads cached bytecode from a ``.pyc`` file, it checks whether " "the cache is up-to-date with the source ``.py`` file. By default, Python " @@ -1381,7 +1278,7 @@ msgstr "" "verificando os metadados armazenados no arquivo de cache em relação aos " "metadados do código-fonte." -#: ../../reference/import.rst:726 +#: ../../reference/import.rst:619 msgid "" "Python also supports \"hash-based\" cache files, which store a hash of the " "source file's contents rather than its metadata. There are two variants of " @@ -1407,7 +1304,7 @@ msgstr "" "arquivos ``.pyc`` baseados em hash pode ser substituído pelo sinalizador :" "option:`--check-hash-based-pycs`." -#: ../../reference/import.rst:737 +#: ../../reference/import.rst:630 msgid "" "Added hash-based ``.pyc`` files. Previously, Python only supported timestamp-" "based invalidation of bytecode caches." @@ -1416,11 +1313,11 @@ msgstr "" "oferecia suporte apenas à invalidação de caches de bytecode baseada em " "registro de data e hora." -#: ../../reference/import.rst:743 +#: ../../reference/import.rst:636 msgid "The Path Based Finder" msgstr "O localizador baseado no caminho" -#: ../../reference/import.rst:748 +#: ../../reference/import.rst:641 msgid "" "As mentioned previously, Python comes with several default meta path " "finders. One of these, called the :term:`path based finder` (:class:" @@ -1434,7 +1331,7 @@ msgstr "" "importação`, que contém uma lista de :term:`entradas de caminho `. Cada entrada de caminho nomeia um local para procurar módulos." -#: ../../reference/import.rst:754 +#: ../../reference/import.rst:647 msgid "" "The path based finder itself doesn't know how to import anything. Instead, " "it traverses the individual path entries, associating each of them with a " @@ -1445,7 +1342,7 @@ msgstr "" "delas a um localizador de entrada de caminho que sabe como lidar com esse " "tipo específico de caminho." -#: ../../reference/import.rst:758 +#: ../../reference/import.rst:651 msgid "" "The default set of path entry finders implement all the semantics for " "finding modules on the file system, handling special file types such as " @@ -1464,7 +1361,7 @@ msgstr "" "lidam com o carregamento de todos esses tipos de arquivos (exceto " "bibliotecas compartilhadas) de arquivos zip." -#: ../../reference/import.rst:765 +#: ../../reference/import.rst:658 msgid "" "Path entries need not be limited to file system locations. They can refer " "to URLs, database queries, or any other location that can be specified as a " @@ -1474,7 +1371,7 @@ msgstr "" "arquivos. Eles podem referir-se a URLs, consultas de banco de dados ou " "qualquer outro local que possa ser especificado como uma string." -#: ../../reference/import.rst:769 +#: ../../reference/import.rst:662 msgid "" "The path based finder provides additional hooks and protocols so that you " "can extend and customize the types of searchable path entries. For example, " @@ -1493,7 +1390,7 @@ msgstr "" "protocolo descrito abaixo, que foi então usado para obter um carregador para " "o módulo da web." -#: ../../reference/import.rst:777 +#: ../../reference/import.rst:670 msgid "" "A word of warning: this section and the previous both use the term *finder*, " "distinguishing between them by using the terms :term:`meta path finder` and :" @@ -1512,7 +1409,7 @@ msgstr "" "diferentes. Em particular, os localizadores de metacaminho operam no início " "do processo de importação, conforme a travessia de :data:`sys.meta_path`." -#: ../../reference/import.rst:785 +#: ../../reference/import.rst:678 msgid "" "By contrast, path entry finders are in a sense an implementation detail of " "the path based finder, and in fact, if the path based finder were to be " @@ -1525,11 +1422,11 @@ msgstr "" "meta_path`, nenhuma semântica do localizador de entrada de caminho seria ser " "invocado." -#: ../../reference/import.rst:792 +#: ../../reference/import.rst:685 msgid "Path entry finders" msgstr "Localizadores de entrada de caminho" -#: ../../reference/import.rst:800 +#: ../../reference/import.rst:693 msgid "" "The :term:`path based finder` is responsible for finding and loading Python " "modules and packages whose location is specified with a string :term:`path " @@ -1541,7 +1438,7 @@ msgstr "" "string :term:`entrada de caminho`. A maioria das entradas de caminho nomeiam " "locais no sistema de arquivos, mas não precisam ser limitadas a isso." -#: ../../reference/import.rst:805 +#: ../../reference/import.rst:698 msgid "" "As a meta path finder, the :term:`path based finder` implements the :meth:" "`~importlib.abc.MetaPathFinder.find_spec` protocol previously described, " @@ -1554,7 +1451,7 @@ msgstr "" "ser usados para personalizar como os módulos são encontrados e carregado do :" "term:`caminho de importação`." -#: ../../reference/import.rst:810 +#: ../../reference/import.rst:703 msgid "" "Three variables are used by the :term:`path based finder`, :data:`sys." "path`, :data:`sys.path_hooks` and :data:`sys.path_importer_cache`. The " @@ -1566,7 +1463,7 @@ msgstr "" "atributos ``__path__`` em objetos de pacote também são usados. Eles fornecem " "maneiras adicionais de personalizar o mecanismo de importação." -#: ../../reference/import.rst:815 +#: ../../reference/import.rst:708 msgid "" ":data:`sys.path` contains a list of strings providing search locations for " "modules and packages. It is initialized from the :envvar:`PYTHONPATH` " @@ -1586,7 +1483,7 @@ msgstr "" "consultas ao banco de dados. Apenas strings devem estar presentes em :data:" "`sys.path`; todos os outros tipos de dados são ignorados." -#: ../../reference/import.rst:824 +#: ../../reference/import.rst:717 msgid "" "The :term:`path based finder` is a :term:`meta path finder`, so the import " "machinery begins the :term:`import path` search by calling the path based " @@ -1607,7 +1504,7 @@ msgstr "" "uma importação dentro desse pacote. Se o argumento ``path`` for ``None``, " "isso indica uma importação de nível superior e :data:`sys.path` é usado." -#: ../../reference/import.rst:833 +#: ../../reference/import.rst:726 msgid "" "The path based finder iterates over every entry in the search path, and for " "each of these, looks for an appropriate :term:`path entry finder` (:class:" @@ -1637,7 +1534,7 @@ msgstr "" "`sys.path_importer_cache`, forçando o localizador baseado no caminho a " "realizar a pesquisa de entrada de caminho novamente." -#: ../../reference/import.rst:846 +#: ../../reference/import.rst:739 msgid "" "If the path entry is not present in the cache, the path based finder " "iterates over every callable in :data:`sys.path_hooks`. Each of the :term:" @@ -1667,7 +1564,7 @@ msgstr "" "outra coisa) e, se o gancho não puder decodificar o argumento, ele deve " "levantar :exc:`ImportError`." -#: ../../reference/import.rst:860 +#: ../../reference/import.rst:753 msgid "" "If :data:`sys.path_hooks` iteration ends with no :term:`path entry finder` " "being returned, then the path based finder's :meth:`~importlib.machinery." @@ -1684,7 +1581,7 @@ msgstr "" "``None``, indicando que este :term:`localizador de metacaminho` não " "conseguiu encontrar o módulo." -#: ../../reference/import.rst:867 +#: ../../reference/import.rst:760 msgid "" "If a :term:`path entry finder` *is* returned by one of the :term:`path entry " "hook` callables on :data:`sys.path_hooks`, then the following protocol is " @@ -1692,11 +1589,11 @@ msgid "" "the module." msgstr "" "Se um :term:`localizador de entrada de caminho` *for* retornado por um dos " -"chamáveis de :term:`gancho de entrada de caminho` ​​em :data:`sys.path_hooks`, " -"então o seguinte protocolo é usado para solicitar ao localizador uma " -"especificação de módulo, que é então usada ao carregar o módulo." +"chamáveis de :term:`gancho de entrada de caminho` em :data:`sys.path_hooks`, " +"então o seguinte protocolo é usado para solicitar ao localizador um spec de " +"módulo, que é então usada ao carregar o módulo." -#: ../../reference/import.rst:872 +#: ../../reference/import.rst:765 msgid "" "The current working directory -- denoted by an empty string -- is handled " "slightly differently from other entries on :data:`sys.path`. First, if the " @@ -1716,11 +1613,11 @@ msgstr "" "path_importer_cache` e retornado por :meth:`importlib.machinery.PathFinder." "find_spec` será o diretório de trabalho atual real e não a string vazia." -#: ../../reference/import.rst:882 +#: ../../reference/import.rst:775 msgid "Path entry finder protocol" msgstr "Protocolo do localizador de entrada de caminho" -#: ../../reference/import.rst:884 +#: ../../reference/import.rst:777 msgid "" "In order to support imports of modules and initialized packages and also to " "contribute portions to namespace packages, path entry finders must implement " @@ -1731,7 +1628,7 @@ msgstr "" "entrada de caminho devem implementar o método :meth:`~importlib.abc." "PathEntryFinder.find_spec`." -#: ../../reference/import.rst:888 +#: ../../reference/import.rst:781 msgid "" ":meth:`~importlib.abc.PathEntryFinder.find_spec` takes two arguments: the " "fully qualified name of the module being imported, and the (optional) target " @@ -1740,31 +1637,30 @@ msgid "" msgstr "" ":meth:`~importlib.abc.PathEntryFinder.find_spec` recebe dois argumentos: o " "nome totalmente qualificado do módulo que está sendo importado e o módulo de " -"destino (opcional). ``find_spec()`` retorna uma especificação totalmente " -"preenchida para o módulo. Esta especificação sempre terá \"loader\" definido " -"(com uma exceção)." +"destino (opcional). ``find_spec()`` retorna um spec totalmente preenchido " +"para o módulo. Este spec sempre terá \"loader\" definido (com uma exceção)." -#: ../../reference/import.rst:893 +#: ../../reference/import.rst:786 msgid "" "To indicate to the import machinery that the spec represents a namespace :" "term:`portion`, the path entry finder sets ``submodule_search_locations`` to " "a list containing the portion." msgstr "" -"Para indicar ao maquinário de importação que a especificação representa uma :" -"term:`porção` de espaço de nomes, o localizador de entrada de caminho define " +"Para indicar ao maquinário de importação que o spec representa uma :term:" +"`porção` de espaço de nomes, o localizador de entrada de caminho define " "``submodule_search_locations`` como uma lista contendo a porção." -#: ../../reference/import.rst:897 +#: ../../reference/import.rst:790 msgid "" ":meth:`~importlib.abc.PathEntryFinder.find_spec` replaced :meth:`!" "find_loader` and :meth:`!find_module`, both of which are now deprecated, but " "will be used if ``find_spec()`` is not defined." msgstr "" ":meth:`~importlib.abc.PathEntryFinder.find_spec` substituiu :meth:`!" -"find_loader` e :meth:`!find_module`, ambos descontinuados, mas serão usados ​​" +"find_loader` e :meth:`!find_module`, ambos descontinuados, mas serão usados " "se ``find_spec()`` não estiver definido." -#: ../../reference/import.rst:903 +#: ../../reference/import.rst:796 msgid "" "Older path entry finders may implement one of these two deprecated methods " "instead of ``find_spec()``. The methods are still respected for the sake of " @@ -1777,7 +1673,7 @@ msgstr "" "No entanto, se ``find_spec()`` for implementado no localizador de entrada de " "caminho, os métodos legados serão ignorados." -#: ../../reference/import.rst:908 +#: ../../reference/import.rst:801 msgid "" ":meth:`!find_loader` takes one argument, the fully qualified name of the " "module being imported. ``find_loader()`` returns a 2-tuple where the first " @@ -1788,7 +1684,7 @@ msgstr "" "o primeiro item é o carregador e o segundo item é uma :term:`porção` de " "espaço de nomes." -#: ../../reference/import.rst:913 +#: ../../reference/import.rst:806 msgid "" "For backwards compatibility with other implementations of the import " "protocol, many path entry finders also support the same, traditional " @@ -1805,7 +1701,7 @@ msgstr "" "``path`` (espera-se que eles registrem as informações de caminho apropriadas " "da chamada inicial para o gancho de caminho)." -#: ../../reference/import.rst:920 +#: ../../reference/import.rst:813 msgid "" "The ``find_module()`` method on path entry finders is deprecated, as it does " "not allow the path entry finder to contribute portions to namespace " @@ -1820,7 +1716,7 @@ msgstr "" "sistema de importação sempre chamará ``find_loader()`` em preferência a " "``find_module()``." -#: ../../reference/import.rst:926 +#: ../../reference/import.rst:819 msgid "" "Calls to :meth:`!find_module` and :meth:`!find_loader` by the import system " "will raise :exc:`ImportWarning`." @@ -1828,15 +1724,15 @@ msgstr "" "Chamadas para :meth:`!find_module` e :meth:`!find_loader` pelo sistema de " "importação vão levantar :exc:`ImportWarning`." -#: ../../reference/import.rst:931 +#: ../../reference/import.rst:824 msgid "``find_module()`` and ``find_loader()`` have been removed." msgstr "``find_module()`` e ``find_loader()`` foram removidos." -#: ../../reference/import.rst:936 +#: ../../reference/import.rst:829 msgid "Replacing the standard import system" msgstr "Substituindo o sistema de importação padrão" -#: ../../reference/import.rst:938 +#: ../../reference/import.rst:831 msgid "" "The most reliable mechanism for replacing the entire import system is to " "delete the default contents of :data:`sys.meta_path`, replacing them " @@ -1846,7 +1742,7 @@ msgstr "" "excluir o conteúdo padrão de :data:`sys.meta_path`, substituindo-o " "inteiramente por um gancho de metacaminho personalizado." -#: ../../reference/import.rst:942 +#: ../../reference/import.rst:835 msgid "" "If it is acceptable to only alter the behaviour of import statements without " "affecting other APIs that access the import system, then replacing the " @@ -1860,7 +1756,7 @@ msgstr "" "também pode ser empregada no nível do módulo para alterar apenas o " "comportamento de instruções de importação dentro desse módulo." -#: ../../reference/import.rst:948 +#: ../../reference/import.rst:841 msgid "" "To selectively prevent the import of some modules from a hook early on the " "meta path (rather than disabling the standard import system entirely), it is " @@ -1876,11 +1772,11 @@ msgstr "" "``None``. O último indica que a busca do metacaminho deve continuar, " "enquanto levantar uma exceção a encerra imediatamente." -#: ../../reference/import.rst:958 +#: ../../reference/import.rst:851 msgid "Package Relative Imports" msgstr "Importações relativas ao pacote" -#: ../../reference/import.rst:960 +#: ../../reference/import.rst:853 msgid "" "Relative imports use leading dots. A single leading dot indicates a relative " "import, starting with the current package. Two or more leading dots indicate " @@ -1893,7 +1789,31 @@ msgstr "" "pacote atual, um nível por ponto após o primeiro. Por exemplo, dado o " "seguinte layout de pacote::" -#: ../../reference/import.rst:976 +#: ../../reference/import.rst:858 +msgid "" +"package/\n" +" __init__.py\n" +" subpackage1/\n" +" __init__.py\n" +" moduleX.py\n" +" moduleY.py\n" +" subpackage2/\n" +" __init__.py\n" +" moduleZ.py\n" +" moduleA.py" +msgstr "" +"package/\n" +" __init__.py\n" +" subpackage1/\n" +" __init__.py\n" +" moduleX.py\n" +" moduleY.py\n" +" subpackage2/\n" +" __init__.py\n" +" moduleZ.py\n" +" moduleA.py" + +#: ../../reference/import.rst:869 msgid "" "In either ``subpackage1/moduleX.py`` or ``subpackage1/__init__.py``, the " "following are valid relative imports::" @@ -1901,7 +1821,23 @@ msgstr "" "Em ``subpackage1/moduleX.py`` ou ``subpackage1/__init__.py``, as seguintes " "são importações relativas válidas:" -#: ../../reference/import.rst:986 +#: ../../reference/import.rst:872 +msgid "" +"from .moduleY import spam\n" +"from .moduleY import spam as ham\n" +"from . import moduleY\n" +"from ..subpackage1 import moduleY\n" +"from ..subpackage2.moduleZ import eggs\n" +"from ..moduleA import foo" +msgstr "" +"from .moduleY import spam\n" +"from .moduleY import spam as ham\n" +"from . import moduleY\n" +"from ..subpackage1 import moduleY\n" +"from ..subpackage2.moduleZ import eggs\n" +"from ..moduleA import foo" + +#: ../../reference/import.rst:879 msgid "" "Absolute imports may use either the ``import <>`` or ``from <> import <>`` " "syntax, but relative imports may only use the second form; the reason for " @@ -1911,7 +1847,11 @@ msgstr "" "<>``, mas importações relativas podem usar apenas a segunda forma; o motivo " "para isso é que:" -#: ../../reference/import.rst:992 +#: ../../reference/import.rst:883 +msgid "import XXX.YYY.ZZZ" +msgstr "import XXX.YYY.ZZZ" + +#: ../../reference/import.rst:885 msgid "" "should expose ``XXX.YYY.ZZZ`` as a usable expression, but .moduleY is not a " "valid expression." @@ -1919,11 +1859,11 @@ msgstr "" "deve expor ``XXX.YYY.ZZZ`` como uma expressão utilizável, mas .moduleY não é " "uma expressão válida." -#: ../../reference/import.rst:999 +#: ../../reference/import.rst:892 msgid "Special considerations for __main__" msgstr "Considerações especiais para __main__" -#: ../../reference/import.rst:1001 +#: ../../reference/import.rst:894 msgid "" "The :mod:`__main__` module is a special case relative to Python's import " "system. As noted :ref:`elsewhere `, the ``__main__`` module is " @@ -1942,11 +1882,11 @@ msgstr "" "``__main__`` é inicializado depende dos sinalizadores e outras opções com as " "quais o interpretador é invocado." -#: ../../reference/import.rst:1012 +#: ../../reference/import.rst:905 msgid "__main__.__spec__" msgstr "__main__.__spec__" -#: ../../reference/import.rst:1014 +#: ../../reference/import.rst:907 msgid "" "Depending on how :mod:`__main__` is initialized, ``__main__.__spec__`` gets " "set appropriately or to ``None``." @@ -1954,7 +1894,7 @@ msgstr "" "Dependendo de como :mod:`__main__` é inicializado, ``__main__.__spec__`` é " "definido apropriadamente ou como ``None``." -#: ../../reference/import.rst:1017 +#: ../../reference/import.rst:910 msgid "" "When Python is started with the :option:`-m` option, ``__spec__`` is set to " "the module spec of the corresponding module or package. ``__spec__`` is also " @@ -1962,11 +1902,11 @@ msgid "" "directory, zipfile or other :data:`sys.path` entry." msgstr "" "Quando o Python é iniciado com a opção :option:`-m`, ``__spec__`` é definido " -"como a especificação do módulo ou pacote correspondente. ``__spec__`` também " -"é preenchido quando o módulo ``__main__`` é carregado como parte da execução " +"como o spec de módulo ou pacote correspondente. ``__spec__`` também é " +"preenchido quando o módulo ``__main__`` é carregado como parte da execução " "de um diretório, arquivo zip ou outra entrada :data:`sys.path`." -#: ../../reference/import.rst:1022 +#: ../../reference/import.rst:915 msgid "" "In :ref:`the remaining cases ` ``__main__." "__spec__`` is set to ``None``, as the code used to populate the :mod:" @@ -1976,23 +1916,23 @@ msgstr "" "é definido como ``None``, pois o código usado para preencher o :mod:" "`__main__` não corresponde diretamente a um módulo importável:" -#: ../../reference/import.rst:1026 +#: ../../reference/import.rst:919 msgid "interactive prompt" msgstr "prompt interativo" -#: ../../reference/import.rst:1027 +#: ../../reference/import.rst:920 msgid ":option:`-c` option" msgstr "opção :option:`-c`" -#: ../../reference/import.rst:1028 +#: ../../reference/import.rst:921 msgid "running from stdin" msgstr "executar a partir de stdin" -#: ../../reference/import.rst:1029 +#: ../../reference/import.rst:922 msgid "running directly from a source or bytecode file" msgstr "executar diretamente de um arquivo de código-fonte ou bytecode" -#: ../../reference/import.rst:1031 +#: ../../reference/import.rst:924 msgid "" "Note that ``__main__.__spec__`` is always ``None`` in the last case, *even " "if* the file could technically be imported directly as a module instead. Use " @@ -2004,7 +1944,7 @@ msgstr "" "option:`-m` se metadados de módulo válidos forem desejados em :mod:" "`__main__`." -#: ../../reference/import.rst:1036 +#: ../../reference/import.rst:929 msgid "" "Note also that even when ``__main__`` corresponds with an importable module " "and ``__main__.__spec__`` is set accordingly, they're still considered " @@ -2019,11 +1959,11 @@ msgstr "" "somente quando o módulo é usado para preencher o espaço de nomes " "``__main__``, e não durante a importação normal." -#: ../../reference/import.rst:1044 +#: ../../reference/import.rst:937 msgid "References" msgstr "Referências" -#: ../../reference/import.rst:1046 +#: ../../reference/import.rst:939 msgid "" "The import machinery has evolved considerably since Python's early days. " "The original `specification for packages `_ ainda está disponível para leitura, embora alguns " "detalhes tenham mudado desde a escrita desse documento." -#: ../../reference/import.rst:1051 +#: ../../reference/import.rst:944 msgid "" "The original specification for :data:`sys.meta_path` was :pep:`302`, with " "subsequent extension in :pep:`420`." @@ -2043,7 +1983,7 @@ msgstr "" "A especificação original para :data:`sys.meta_path` era :pep:`302`, com " "extensão subsequente em :pep:`420`." -#: ../../reference/import.rst:1054 +#: ../../reference/import.rst:947 msgid "" ":pep:`420` introduced :term:`namespace packages ` for " "Python 3.3. :pep:`420` also introduced the :meth:`!find_loader` protocol as " @@ -2053,7 +1993,7 @@ msgstr "" "para Python 3.3. :pep:`420` também introduziu o protocolo :meth:`!" "find_loader` como uma alternativa ao :meth:`!find_module`." -#: ../../reference/import.rst:1058 +#: ../../reference/import.rst:951 msgid "" ":pep:`366` describes the addition of the ``__package__`` attribute for " "explicit relative imports in main modules." @@ -2061,7 +2001,7 @@ msgstr "" ":pep:`366` descreve a adição do atributo ``__package__`` para importações " "relativas explícitas em módulos principais." -#: ../../reference/import.rst:1061 +#: ../../reference/import.rst:954 msgid "" ":pep:`328` introduced absolute and explicit relative imports and initially " "proposed ``__name__`` for semantics :pep:`366` would eventually specify for " @@ -2071,11 +2011,11 @@ msgstr "" "inicialmente propôs ``__name__`` para semântica. :pep:`366` eventualmente " "especificaria ``__package__``." -#: ../../reference/import.rst:1065 +#: ../../reference/import.rst:958 msgid ":pep:`338` defines executing modules as scripts." msgstr ":pep:`338` define módulos de execução como scripts." -#: ../../reference/import.rst:1067 +#: ../../reference/import.rst:960 msgid "" ":pep:`451` adds the encapsulation of per-module import state in spec " "objects. It also off-loads most of the boilerplate responsibilities of " @@ -2084,21 +2024,20 @@ msgid "" "finders and loaders." msgstr "" ":pep:`451` adiciona o encapsulamento do estado de importação por módulo em " -"objetos de especificação. Ele também descarrega a maioria das " -"responsabilidades inerentes dos carregadores de volta para o maquinário de " -"importação. Essas mudanças permitem a descontinuação de várias APIs no " -"sistema de importação e também a adição de novos métodos para localizadores " -"e carregadores." +"objetos spec. Ele também descarrega a maioria das responsabilidades " +"inerentes dos carregadores de volta para o maquinário de importação. Essas " +"mudanças permitem a descontinuação de várias APIs no sistema de importação e " +"também a adição de novos métodos para localizadores e carregadores." -#: ../../reference/import.rst:1074 +#: ../../reference/import.rst:967 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../reference/import.rst:1075 +#: ../../reference/import.rst:968 msgid "See :class:`types.ModuleType`." msgstr "Veja :class:`types.ModuleType`." -#: ../../reference/import.rst:1077 +#: ../../reference/import.rst:970 msgid "" "The importlib implementation avoids using the return value directly. " "Instead, it gets the module object by looking the module name up in :data:" @@ -2118,7 +2057,7 @@ msgid "import machinery" msgstr "maquinário de importação" #: ../../reference/import.rst:64 ../../reference/import.rst:95 -#: ../../reference/import.rst:129 +#: ../../reference/import.rst:131 msgid "package" msgstr "pacote" @@ -2126,82 +2065,82 @@ msgstr "pacote" msgid "regular" msgstr "regular" -#: ../../reference/import.rst:129 +#: ../../reference/import.rst:131 msgid "namespace" msgstr "espaço de nomes" -#: ../../reference/import.rst:129 +#: ../../reference/import.rst:131 msgid "portion" msgstr "porção" -#: ../../reference/import.rst:175 +#: ../../reference/import.rst:177 msgid "sys.modules" msgstr "sys.modules" -#: ../../reference/import.rst:210 ../../reference/import.rst:276 +#: ../../reference/import.rst:212 ../../reference/import.rst:278 msgid "finder" msgstr "localizador" -#: ../../reference/import.rst:210 +#: ../../reference/import.rst:212 msgid "loader" msgstr "carregador" -#: ../../reference/import.rst:210 +#: ../../reference/import.rst:212 msgid "module spec" -msgstr "módulo spec" +msgstr "spec de módulo" -#: ../../reference/import.rst:249 +#: ../../reference/import.rst:251 msgid "import hooks" msgstr "ganchos de importação" -#: ../../reference/import.rst:249 +#: ../../reference/import.rst:251 msgid "meta hooks" msgstr "metaganchos" -#: ../../reference/import.rst:249 +#: ../../reference/import.rst:251 msgid "path hooks" msgstr "ganchos de caminho" -#: ../../reference/import.rst:249 +#: ../../reference/import.rst:251 msgid "hooks" msgstr "ganchos" -#: ../../reference/import.rst:249 +#: ../../reference/import.rst:251 msgid "import" -msgstr "importação" +msgstr "import" -#: ../../reference/import.rst:249 +#: ../../reference/import.rst:251 msgid "meta" msgstr "meta" -#: ../../reference/import.rst:249 +#: ../../reference/import.rst:251 msgid "path" msgstr "caminho" -#: ../../reference/import.rst:276 +#: ../../reference/import.rst:278 msgid "sys.meta_path" msgstr "sys.meta_path" -#: ../../reference/import.rst:276 +#: ../../reference/import.rst:278 msgid "find_spec" msgstr "find_spec" -#: ../../reference/import.rst:745 +#: ../../reference/import.rst:638 msgid "path based finder" msgstr "localizador baseado no caminho" -#: ../../reference/import.rst:794 +#: ../../reference/import.rst:687 msgid "sys.path" msgstr "sys.path" -#: ../../reference/import.rst:794 +#: ../../reference/import.rst:687 msgid "sys.path_hooks" msgstr "sys.path_hooks" -#: ../../reference/import.rst:794 +#: ../../reference/import.rst:687 msgid "sys.path_importer_cache" msgstr "sys.path_importer_cache" -#: ../../reference/import.rst:794 +#: ../../reference/import.rst:687 msgid "PYTHONPATH" msgstr "PYTHONPATH" diff --git a/reference/index.po b/reference/index.po index 9b1c31a8e..a1a16d827 100644 --- a/reference/index.po +++ b/reference/index.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Raphael Mendonça, 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:49+0000\n" -"Last-Translator: Raphael Mendonça, 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/reference/introduction.po b/reference/introduction.po index 044668484..f657d7fa0 100644 --- a/reference/introduction.po +++ b/reference/introduction.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Ruan Aragão , 2021 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -192,8 +190,8 @@ msgid "" "support and a Just in Time compiler. One of the goals of the project is to " "encourage experimentation with the language itself by making it easier to " "modify the interpreter (since it is written in Python). Additional " -"information is available on `the PyPy project's home page `_." +"information is available on `the PyPy project's home page `_." msgstr "" "Uma implementação do Python escrita completamente em Python. A mesma suporta " "vários recursos avançados não encontrados em outras implementações, como " @@ -201,7 +199,7 @@ msgstr "" "é incentivar a construção de experimentos com a própria linguagem, " "facilitando a modificação do interpretador (uma vez que o mesmos está " "escrito em Python). Informações adicionais estão disponíveis no `site do " -"projeto PyPy `_." +"projeto PyPy `_." #: ../../reference/introduction.rst:79 msgid "" diff --git a/reference/lexical_analysis.po b/reference/lexical_analysis.po index 24677984f..bca15eae8 100644 --- a/reference/lexical_analysis.po +++ b/reference/lexical_analysis.po @@ -1,32 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Welington Carlos , 2021 -# Misael borges , 2021 -# (Douglas da Silva) , 2022 -# Claudio Rogerio Carvalho Filho , 2023 -# felipe caridade fernandes , 2023 -# Julia Rizza , 2023 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-08 03:57+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -36,15 +29,17 @@ msgstr "Análise léxica" #: ../../reference/lexical_analysis.rst:10 msgid "" -"A Python program is read by a *parser*. Input to the parser is a stream of " -"*tokens*, generated by the *lexical analyzer*. This chapter describes how " -"the lexical analyzer breaks a file into tokens." +"A Python program is read by a *parser*. Input to the parser is a stream of :" +"term:`tokens `, generated by the *lexical analyzer* (also known as " +"the *tokenizer*). This chapter describes how the lexical analyzer breaks a " +"file into tokens." msgstr "" "Um programa Python é lido por um *analisador*. A entrada para o analisador é " -"um fluxo de *tokens*, gerado pelo *analisador léxico*. Este capítulo " -"descreve como o analisador léxico divide um arquivo em tokens." +"um fluxo de :term:`tokens `, gerados pelo *analisador léxico* (também " +"conhecido como *tokenizador*). Este capítulo descreve como o analisador " +"léxico divide um arquivo em tokens." -#: ../../reference/lexical_analysis.rst:14 +#: ../../reference/lexical_analysis.rst:15 msgid "" "Python reads program text as Unicode code points; the encoding of a source " "file can be given by an encoding declaration and defaults to UTF-8, see :pep:" @@ -57,19 +52,19 @@ msgstr "" "arquivo de origem não puder ser decodificado, uma exceção :exc:`SyntaxError` " "será levantada." -#: ../../reference/lexical_analysis.rst:23 +#: ../../reference/lexical_analysis.rst:24 msgid "Line structure" msgstr "Estrutura das linhas" -#: ../../reference/lexical_analysis.rst:27 +#: ../../reference/lexical_analysis.rst:28 msgid "A Python program is divided into a number of *logical lines*." msgstr "Um programa Python é dividido em uma série de *linhas lógicas*." -#: ../../reference/lexical_analysis.rst:33 +#: ../../reference/lexical_analysis.rst:34 msgid "Logical lines" msgstr "Linhas lógicas" -#: ../../reference/lexical_analysis.rst:37 +#: ../../reference/lexical_analysis.rst:38 msgid "" "The end of a logical line is represented by the token NEWLINE. Statements " "cannot cross logical line boundaries except where NEWLINE is allowed by the " @@ -83,11 +78,11 @@ msgstr "" "compostas). Uma linha lógica é construída a partir de uma ou mais *linhas " "físicas* seguindo as regras explícitas ou implícitas que *juntam as linhas*." -#: ../../reference/lexical_analysis.rst:47 +#: ../../reference/lexical_analysis.rst:48 msgid "Physical lines" msgstr "Linhas físicas" -#: ../../reference/lexical_analysis.rst:49 +#: ../../reference/lexical_analysis.rst:50 msgid "" "A physical line is a sequence of characters terminated by an end-of-line " "sequence. In source files and strings, any of the standard platform line " @@ -103,10 +98,10 @@ msgstr "" "usada - o formato Unix usando ASCII LF (linefeed), o formato Windows usando " "a sequência ASCII CR LF (return seguido de linefeed) ou o antigo formato " "Macintosh usando o caractere ASCII CR (return). Todos esses formatos podem " -"ser usados ​​igualmente, independentemente da plataforma. O final da entrada " +"ser usados igualmente, independentemente da plataforma. O final da entrada " "também serve como um finalizador implícito para a linha física final." -#: ../../reference/lexical_analysis.rst:57 +#: ../../reference/lexical_analysis.rst:58 msgid "" "When embedding Python, source code strings should be passed to Python APIs " "using the standard C conventions for newline characters (the ``\\n`` " @@ -116,11 +111,11 @@ msgstr "" "do Python usando as convenções C padrão para caracteres de nova linha (o " "caractere ``\\n``, representando ASCII LF, será o terminador de linha)." -#: ../../reference/lexical_analysis.rst:65 +#: ../../reference/lexical_analysis.rst:66 msgid "Comments" msgstr "Comentários" -#: ../../reference/lexical_analysis.rst:70 +#: ../../reference/lexical_analysis.rst:71 msgid "" "A comment starts with a hash character (``#``) that is not part of a string " "literal, and ends at the end of the physical line. A comment signifies the " @@ -132,11 +127,11 @@ msgstr "" "significa o fim da linha lógica a menos que regras de junção de linha " "implicitas sejam invocadas. Comentários são ignorados pela sintaxe." -#: ../../reference/lexical_analysis.rst:79 +#: ../../reference/lexical_analysis.rst:80 msgid "Encoding declarations" msgstr "Declarações de codificação" -#: ../../reference/lexical_analysis.rst:84 +#: ../../reference/lexical_analysis.rst:85 msgid "" "If a comment in the first or second line of the Python script matches the " "regular expression ``coding[=:]\\s*([-\\w.]+)``, this comment is processed " @@ -153,26 +148,35 @@ msgstr "" "está na segunda linha, a primeira linha também deve ser uma linha somente " "com comentário. As formas recomendadas de uma declaração de codificação são:" -#: ../../reference/lexical_analysis.rst:93 +#: ../../reference/lexical_analysis.rst:92 +msgid "# -*- coding: -*-" +msgstr "# -*- coding: -*-" + +#: ../../reference/lexical_analysis.rst:94 msgid "which is recognized also by GNU Emacs, and ::" msgstr "que é reconhecido também por GNU Emacs, e ::" -#: ../../reference/lexical_analysis.rst:97 +#: ../../reference/lexical_analysis.rst:96 +msgid "# vim:fileencoding=" +msgstr "# vim:fileencoding=" + +#: ../../reference/lexical_analysis.rst:98 msgid "which is recognized by Bram Moolenaar's VIM." msgstr "que é reconhecido pelo VIM de Bram Moolenaar." -#: ../../reference/lexical_analysis.rst:99 +#: ../../reference/lexical_analysis.rst:100 msgid "" "If no encoding declaration is found, the default encoding is UTF-8. If the " "implicit or explicit encoding of a file is UTF-8, an initial UTF-8 byte-" -"order mark (b'\\xef\\xbb\\xbf') is ignored rather than being a syntax error." +"order mark (``b'\\xef\\xbb\\xbf'``) is ignored rather than being a syntax " +"error." msgstr "" "Se nenhuma codificação é declarada, a codificação padrão é UTF-8. Se a " "codificação implícita ou explícita de um arquivo é UTF-8, uma marca inicial " -"de ordem de byte UTF-8 (b'xefxbbxbf') será ignorada em vez de ser um erro de " -"sintaxe." +"de ordem de byte UTF-8 (``b'\\xef\\xbb\\xbf'``) será ignorada em vez de ser " +"um erro de sintaxe." -#: ../../reference/lexical_analysis.rst:103 +#: ../../reference/lexical_analysis.rst:104 msgid "" "If an encoding is declared, the encoding name must be recognized by Python " "(see :ref:`standard-encodings`). The encoding is used for all lexical " @@ -182,11 +186,11 @@ msgstr "" "pelo Python (veja :ref:`standard-encodings`). A codificação é usada por toda " "análise léxica, incluindo literais strings, comment and identificadores." -#: ../../reference/lexical_analysis.rst:112 +#: ../../reference/lexical_analysis.rst:113 msgid "Explicit line joining" msgstr "Junção de linha explícita" -#: ../../reference/lexical_analysis.rst:116 +#: ../../reference/lexical_analysis.rst:117 msgid "" "Two or more physical lines may be joined into logical lines using backslash " "characters (``\\``), as follows: when a physical line ends in a backslash " @@ -201,7 +205,20 @@ msgstr "" "lógica, removendo a contrabarra e o caractere de fim de linha seguinte. Por " "exemplo::" -#: ../../reference/lexical_analysis.rst:127 +#: ../../reference/lexical_analysis.rst:123 +msgid "" +"if 1900 < year < 2100 and 1 <= month <= 12 \\\n" +" and 1 <= day <= 31 and 0 <= hour < 24 \\\n" +" and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date\n" +" return 1" +msgstr "" +"if 1900 < year < 2100 and 1 <= month <= 12 \\\n" +" and 1 <= day <= 31 and 0 <= hour < 24 \\\n" +" and 0 <= minute < 60 and 0 <= second < 60: # Parece ser uma data " +"válida\n" +" return 1" + +#: ../../reference/lexical_analysis.rst:128 msgid "" "A line ending in a backslash cannot carry a comment. A backslash does not " "continue a comment. A backslash does not continue a token except for string " @@ -216,11 +233,11 @@ msgstr "" "Uma contrabarra é ilegal em qualquer outro lugar em uma linha fora de uma " "string literal." -#: ../../reference/lexical_analysis.rst:137 +#: ../../reference/lexical_analysis.rst:138 msgid "Implicit line joining" msgstr "Junção de linha implícita" -#: ../../reference/lexical_analysis.rst:139 +#: ../../reference/lexical_analysis.rst:140 msgid "" "Expressions in parentheses, square brackets or curly braces can be split " "over more than one physical line without using backslashes. For example::" @@ -228,7 +245,19 @@ msgstr "" "Expressões entre parênteses, colchetes ou chaves podem ser quebradas em mais " "de uma linha física sem a necessidade do uso de contrabarras. Por exemplo::" -#: ../../reference/lexical_analysis.rst:147 +#: ../../reference/lexical_analysis.rst:143 +msgid "" +"month_names = ['Januari', 'Februari', 'Maart', # These are the\n" +" 'April', 'Mei', 'Juni', # Dutch names\n" +" 'Juli', 'Augustus', 'September', # for the months\n" +" 'Oktober', 'November', 'December'] # of the year" +msgstr "" +"month_names = ['Januari', 'Februari', 'Maart', # Estes são os\n" +" 'April', 'Mei', 'Juni', # nomes holandeses\n" +" 'Juli', 'Augustus', 'September', # para os meses\n" +" 'Oktober', 'November', 'December'] # do ano" + +#: ../../reference/lexical_analysis.rst:148 msgid "" "Implicitly continued lines can carry comments. The indentation of the " "continuation lines is not important. Blank continuation lines are allowed. " @@ -242,11 +271,11 @@ msgstr "" "Linhas continuadas implicitamente também podem ocorrer dentro de strings com " "aspas triplas (veja abaixo); nesse caso, eles não podem conter comentários." -#: ../../reference/lexical_analysis.rst:157 +#: ../../reference/lexical_analysis.rst:158 msgid "Blank lines" msgstr "Linhas em branco" -#: ../../reference/lexical_analysis.rst:161 +#: ../../reference/lexical_analysis.rst:162 msgid "" "A logical line that contains only spaces, tabs, formfeeds and possibly a " "comment, is ignored (i.e., no NEWLINE token is generated). During " @@ -264,11 +293,11 @@ msgstr "" "(ou seja, uma que não contenha nem mesmo espaço em branco ou um comentário) " "encerra uma instrução de várias linhas." -#: ../../reference/lexical_analysis.rst:172 +#: ../../reference/lexical_analysis.rst:173 msgid "Indentation" msgstr "Indentação" -#: ../../reference/lexical_analysis.rst:176 +#: ../../reference/lexical_analysis.rst:177 msgid "" "Leading whitespace (spaces and tabs) at the beginning of a logical line is " "used to compute the indentation level of the line, which in turn is used to " @@ -278,7 +307,7 @@ msgstr "" "usado para calcular o nível de indentação da linha, que por sua vez é usado " "para determinar o agrupamento de instruções." -#: ../../reference/lexical_analysis.rst:180 +#: ../../reference/lexical_analysis.rst:181 msgid "" "Tabs are replaced (from left to right) by one to eight spaces such that the " "total number of characters up to and including the replacement is a multiple " @@ -296,7 +325,7 @@ msgstr "" "dividido em várias linhas físicas usando contrabarra; o espaço em branco até " "a primeira contrabarra determina a indentação." -#: ../../reference/lexical_analysis.rst:188 +#: ../../reference/lexical_analysis.rst:189 msgid "" "Indentation is rejected as inconsistent if a source file mixes tabs and " "spaces in a way that makes the meaning dependent on the worth of a tab in " @@ -307,7 +336,7 @@ msgstr "" "valor de uma tabulação em espaços; uma exceção :exc:`TabError` é levantada " "nesse caso." -#: ../../reference/lexical_analysis.rst:192 +#: ../../reference/lexical_analysis.rst:193 msgid "" "**Cross-platform compatibility note:** because of the nature of text editors " "on non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for " @@ -320,7 +349,7 @@ msgstr "" "Deve-se notar também que diferentes plataformas podem limitar explicitamente " "o nível máximo de indentação." -#: ../../reference/lexical_analysis.rst:197 +#: ../../reference/lexical_analysis.rst:198 msgid "" "A formfeed character may be present at the start of the line; it will be " "ignored for the indentation calculations above. Formfeed characters " @@ -333,7 +362,7 @@ msgstr "" "efeito indefinido (por exemplo, eles podem redefinir a contagem de espaços " "para zero)." -#: ../../reference/lexical_analysis.rst:204 +#: ../../reference/lexical_analysis.rst:205 msgid "" "The indentation levels of consecutive lines are used to generate INDENT and " "DEDENT tokens, using a stack, as follows." @@ -341,7 +370,7 @@ msgstr "" "Os níveis de indentação das linhas consecutivas são usados para gerar tokens " "INDENT e DEDENT, usando uma pilha, como segue." -#: ../../reference/lexical_analysis.rst:207 +#: ../../reference/lexical_analysis.rst:208 msgid "" "Before the first line of the file is read, a single zero is pushed on the " "stack; this will never be popped off again. The numbers pushed on the stack " @@ -364,7 +393,7 @@ msgstr "" "token DEDENT é gerado. Ao final do arquivo, um token DEDENT é gerado para " "cada número restante na pilha que seja maior que zero." -#: ../../reference/lexical_analysis.rst:218 +#: ../../reference/lexical_analysis.rst:219 msgid "" "Here is an example of a correctly (though confusingly) indented piece of " "Python code::" @@ -372,11 +401,55 @@ msgstr "" "Aqui está um exemplo de um trecho de código Python indentado corretamente " "(embora confuso):" -#: ../../reference/lexical_analysis.rst:233 +#: ../../reference/lexical_analysis.rst:222 +msgid "" +"def perm(l):\n" +" # Compute the list of all permutations of l\n" +" if len(l) <= 1:\n" +" return [l]\n" +" r = []\n" +" for i in range(len(l)):\n" +" s = l[:i] + l[i+1:]\n" +" p = perm(s)\n" +" for x in p:\n" +" r.append(l[i:i+1] + x)\n" +" return r" +msgstr "" +"def perm(l):\n" +" # Calcula a lista de todas as permutações de l\n" +" if len(l) <= 1:\n" +" return [l]\n" +" r = []\n" +" for i in range(len(l)):\n" +" s = l[:i] + l[i+1:]\n" +" p = perm(s)\n" +" for x in p:\n" +" r.append(l[i:i+1] + x)\n" +" return r" + +#: ../../reference/lexical_analysis.rst:234 msgid "The following example shows various indentation errors::" msgstr "O exemplo a seguir mostra vários erros de indentação:" -#: ../../reference/lexical_analysis.rst:243 +#: ../../reference/lexical_analysis.rst:236 +msgid "" +" def perm(l): # error: first line indented\n" +"for i in range(len(l)): # error: not indented\n" +" s = l[:i] + l[i+1:]\n" +" p = perm(l[:i] + l[i+1:]) # error: unexpected indent\n" +" for x in p:\n" +" r.append(l[i:i+1] + x)\n" +" return r # error: inconsistent dedent" +msgstr "" +" def perm(l): # erro: primeira linha indentada\n" +"for i in range(len(l)): # erro: não indentada\n" +" s = l[:i] + l[i+1:]\n" +" p = perm(l[:i] + l[i+1:]) # erro: indentação inesperada\n" +" for x in p:\n" +" r.append(l[i:i+1] + x)\n" +" return r # erro: desindentação inconsistente" + +#: ../../reference/lexical_analysis.rst:244 msgid "" "(Actually, the first three errors are detected by the parser; only the last " "error is found by the lexical analyzer --- the indentation of ``return r`` " @@ -386,11 +459,11 @@ msgstr "" "sintático; apenas o último erro é encontrado pelo analisador léxico --- o " "recuo de não corresponde a um nível retirado da pilha.)" -#: ../../reference/lexical_analysis.rst:251 +#: ../../reference/lexical_analysis.rst:252 msgid "Whitespace between tokens" msgstr "Espaços em branco entre tokens" -#: ../../reference/lexical_analysis.rst:253 +#: ../../reference/lexical_analysis.rst:254 msgid "" "Except at the beginning of a logical line or in string literals, the " "whitespace characters space, tab and formfeed can be used interchangeably to " @@ -404,11 +477,11 @@ msgstr "" "dois tokens somente se sua concatenação puder ser interpretada como um token " "diferente (por exemplo, ab é um token, mas a b são dois tokens)." -#: ../../reference/lexical_analysis.rst:263 +#: ../../reference/lexical_analysis.rst:264 msgid "Other tokens" msgstr "Outros tokens" -#: ../../reference/lexical_analysis.rst:265 +#: ../../reference/lexical_analysis.rst:266 msgid "" "Besides NEWLINE, INDENT and DEDENT, the following categories of tokens " "exist: *identifiers*, *keywords*, *literals*, *operators*, and *delimiters*. " @@ -424,11 +497,11 @@ msgstr "" "tokens. Onde existe ambiguidade, um token compreende a string mais longa " "possível que forma um token legal, quando lido da esquerda para a direita." -#: ../../reference/lexical_analysis.rst:275 +#: ../../reference/lexical_analysis.rst:276 msgid "Identifiers and keywords" msgstr "Identificadores e palavras-chave" -#: ../../reference/lexical_analysis.rst:279 +#: ../../reference/lexical_analysis.rst:280 msgid "" "Identifiers (also referred to as *names*) are described by the following " "lexical definitions." @@ -436,7 +509,7 @@ msgstr "" "Identificadores (também chamados de *nomes*) são descritos pelas seguintes " "definições lexicais." -#: ../../reference/lexical_analysis.rst:282 +#: ../../reference/lexical_analysis.rst:283 msgid "" "The syntax of identifiers in Python is based on the Unicode standard annex " "UAX-31, with elaboration and changes as defined below; see also :pep:`3131` " @@ -446,28 +519,23 @@ msgstr "" "UAX-31, com elaboração e alterações conforme definido abaixo; veja também :" "pep:`3131` para mais detalhes." -#: ../../reference/lexical_analysis.rst:286 +#: ../../reference/lexical_analysis.rst:287 msgid "" "Within the ASCII range (U+0001..U+007F), the valid characters for " -"identifiers are the same as in Python 2.x: the uppercase and lowercase " -"letters ``A`` through ``Z``, the underscore ``_`` and, except for the first " -"character, the digits ``0`` through ``9``." -msgstr "" -"Dentro do intervalo ASCII (U+0001..U+007F), os caracteres válidos para " -"identificadores são os mesmos de Python 2.x: as letras maiúsculas e " -"minúsculas de ``A`` até ``Z``, o sublinhado ``_`` e, exceto para o primeiro " -"caractere, os dígitos ``0`` até ``9``." - -#: ../../reference/lexical_analysis.rst:291 -msgid "" -"Python 3.0 introduces additional characters from outside the ASCII range " -"(see :pep:`3131`). For these characters, the classification uses the " -"version of the Unicode Character Database as included in the :mod:" +"identifiers include the uppercase and lowercase letters ``A`` through ``Z``, " +"the underscore ``_`` and, except for the first character, the digits ``0`` " +"through ``9``. Python 3.0 introduced additional characters from outside the " +"ASCII range (see :pep:`3131`). For these characters, the classification " +"uses the version of the Unicode Character Database as included in the :mod:" "`unicodedata` module." msgstr "" -"Python 3.0 introduz caracteres adicionais fora do intervalo ASCII (consulte :" -"pep:`3131`). Para esses caracteres, a classificação utiliza a versão do " -"Banco de Dados de Caracteres Unicode incluída no módulo :mod:`unicodedata`." +"Dentro do intervalo ASCII (U+0001..U+007F), os caracteres válidos para " +"identificadores incluem as letras maiúsculas e minúsculas ``A`` a ``Z``, o " +"sublinhado ``_`` e, exceto pelo primeiro caractere, os dígitos ``0`` a " +"``9``. O Python 3.0 introduziu caracteres adicionais de fora do intervalo " +"ASCII (veja :pep:`3131`). Para esses caracteres, a classificação usa a " +"versão do Unicode Character Database conforme incluído no módulo :mod:" +"`unicodedata`." #: ../../reference/lexical_analysis.rst:295 msgid "Identifiers are unlimited in length. Case is significant." @@ -565,6 +633,24 @@ msgstr "" "*palavras-chave* da linguagem, e não podem ser usados como identificadores " "comuns. Eles devem ser escritos exatamente como estão escritos aqui:" +#: ../../reference/lexical_analysis.rst:342 +msgid "" +"False await else import pass\n" +"None break except in raise\n" +"True class finally is return\n" +"and continue for lambda try\n" +"as def from nonlocal while\n" +"assert del global not with\n" +"async elif if or yield" +msgstr "" +"False await else import pass\n" +"None break except in raise\n" +"True class finally is return\n" +"and continue for lambda try\n" +"as def from nonlocal while\n" +"assert del global not with\n" +"async elif if or yield" + #: ../../reference/lexical_analysis.rst:356 msgid "Soft Keywords" msgstr "Palavras reservadas contextuais" @@ -1030,6 +1116,16 @@ msgstr "" "Uma contrabarra pode ser adicionada ao fim da linha para ignorar a nova " "linha::" +#: ../../reference/lexical_analysis.rst:608 +msgid "" +">>> 'This string will not include \\\n" +"... backslashes or newline characters.'\n" +"'This string will not include backslashes or newline characters.'" +msgstr "" +">>> 'Esta string não vai incluir \\\n" +"... contrabarras e caracteres de nova linha.'\n" +"'Esta string não vai incluir contrabarras e caracteres de nova linha.'" + #: ../../reference/lexical_analysis.rst:612 msgid "" "The same result can be achieved using :ref:`triple-quoted strings " @@ -1168,6 +1264,16 @@ msgstr "" "necessárias, para dividir strings longas convenientemente em linhas longas " "ou até mesmo para adicionar comentários a partes de strings, por exemplo:" +#: ../../reference/lexical_analysis.rst:686 +msgid "" +"re.compile(\"[A-Za-z_]\" # letter or underscore\n" +" \"[A-Za-z0-9_]*\" # letter, digit or underscore\n" +" )" +msgstr "" +"re.compile(\"[A-Za-z_]\" # letra ou sublinhado\n" +" \"[A-Za-z0-9_]*\" # letra, dígito ou sublinhado\n" +" )" + #: ../../reference/lexical_analysis.rst:690 msgid "" "Note that this feature is defined at the syntactical level, but implemented " @@ -1260,6 +1366,16 @@ msgstr "" "substituição é um comentário (até mesmo colchetes e aspas). Nesse caso, os " "campos de substituição deverão ser fechados em uma linha diferente." +#: ../../reference/lexical_analysis.rst:758 +msgid "" +">>> f\"abc{a # This is a comment }\"\n" +"... + 3}\"\n" +"'abc5'" +msgstr "" +">>> f\"abc{a # Este é um comentário }\"\n" +"... + 3}\"\n" +"'abc5'" + #: ../../reference/lexical_analysis.rst:764 msgid "" "Prior to Python 3.7, an :keyword:`await` expression and comprehensions " @@ -1351,6 +1467,68 @@ msgstr "" msgid "Some examples of formatted string literals::" msgstr "Alguns exemplos de literais de string formatados::" +#: ../../reference/lexical_analysis.rst:805 +msgid "" +">>> name = \"Fred\"\n" +">>> f\"He said his name is {name!r}.\"\n" +"\"He said his name is 'Fred'.\"\n" +">>> f\"He said his name is {repr(name)}.\" # repr() is equivalent to !r\n" +"\"He said his name is 'Fred'.\"\n" +">>> width = 10\n" +">>> precision = 4\n" +">>> value = decimal.Decimal(\"12.34567\")\n" +">>> f\"result: {value:{width}.{precision}}\" # nested fields\n" +"'result: 12.35'\n" +">>> today = datetime(year=2017, month=1, day=27)\n" +">>> f\"{today:%B %d, %Y}\" # using date format specifier\n" +"'January 27, 2017'\n" +">>> f\"{today=:%B %d, %Y}\" # using date format specifier and debugging\n" +"'today=January 27, 2017'\n" +">>> number = 1024\n" +">>> f\"{number:#0x}\" # using integer format specifier\n" +"'0x400'\n" +">>> foo = \"bar\"\n" +">>> f\"{ foo = }\" # preserves whitespace\n" +"\" foo = 'bar'\"\n" +">>> line = \"The mill's closed\"\n" +">>> f\"{line = }\"\n" +"'line = \"The mill\\'s closed\"'\n" +">>> f\"{line = :20}\"\n" +"\"line = The mill's closed \"\n" +">>> f\"{line = !r:20}\"\n" +"'line = \"The mill\\'s closed\" '" +msgstr "" +">>> nome = \"Fred\"\n" +">>> f\"Ele falou que o nome dele é {nome!r}.\"\n" +"\"Ele falou que o nome dele é 'Fred'.\"\n" +">>> f\"Ele falou que o nome dele é {repr(nome)}.\" # repr() é um " +"equivalente a !r\n" +"\"Ele falou que o nome dele é 'Fred'.\"\n" +">>> largura = 10\n" +">>> precisão = 4\n" +">>> valor = decimal.Decimal(\"12.34567\")\n" +">>> f\"resultado: {valor:{largura}.{precisão}}\" # campos aninhados\n" +"'resultado: 12.35'\n" +">>> hoje = datetime(year=2017, month=1, day=27)\n" +">>> f\"{hoje:%B %d, %Y}\" # usando especificador de formato de data\n" +"'January 27, 2017'\n" +">>> f\"{hoje=:%B %d, %Y}\" # usando especificador de formato de data e " +"depuração\n" +"'hoje=January 27, 2017'\n" +">>> número = 1024\n" +">>> f\"{número:#0x}\" # usando especificador de formato de número inteiro\n" +"'0x400'\n" +">>> foo = \"bar\"\n" +">>> f\"{ foo = }\" # preserva espaço em branco\n" +"\" foo = 'bar'\"\n" +">>> linha = \"Olha a caixa d'água\"\n" +">>> f\"{linha = }\"\n" +"'linha = \"Olha a caixa d\\'água\"'\n" +">>> f\"{linha = :20}\"\n" +"\"linha = Olha a caixa d'água \"\n" +">>> f\"{linha = !r:20}\"\n" +"'linha = \"Olha a caixa d\\'água\"'" + #: ../../reference/lexical_analysis.rst:835 msgid "" "Reusing the outer f-string quoting type inside a replacement field is " @@ -1359,6 +1537,16 @@ msgstr "" "É permitido reutilizar o tipo de aspas de f-string externa dentro de um " "campo de substituição:" +#: ../../reference/lexical_analysis.rst:838 +msgid "" +">>> a = dict(x=2)\n" +">>> f\"abc {a[\"x\"]} def\"\n" +"'abc 2 def'" +msgstr "" +">>> a = dict(x=2)\n" +">>> f\"abc {a[\"x\"]} def\"\n" +"'abc 2 def'" + #: ../../reference/lexical_analysis.rst:842 msgid "" "Prior to Python 3.12, reuse of the same quoting type of the outer f-string " @@ -1375,6 +1563,22 @@ msgstr "" "Contrabarras também são permitidas em campos de substituição e são avaliadas " "da mesma forma que em qualquer outro contexto:" +#: ../../reference/lexical_analysis.rst:849 +msgid "" +">>> a = [\"a\", \"b\", \"c\"]\n" +">>> print(f\"List a contains:\\n{\"\\n\".join(a)}\")\n" +"List a contains:\n" +"a\n" +"b\n" +"c" +msgstr "" +">>> a = [\"a\", \"b\", \"c\"]\n" +">>> print(f\"A lista a contém:\\n{\"\\n\".join(a)}\")\n" +"A lista a contém:\n" +"a\n" +"b\n" +"c" + #: ../../reference/lexical_analysis.rst:856 msgid "" "Prior to Python 3.12, backslashes were not permitted inside an f-string " @@ -1391,6 +1595,20 @@ msgstr "" "Literais de string formatados não podem ser usados como strings de " "documentação, mesmo que não incluam expressões." +#: ../../reference/lexical_analysis.rst:865 +msgid "" +">>> def foo():\n" +"... f\"Not a docstring\"\n" +"...\n" +">>> foo.__doc__ is None\n" +"True" +msgstr "" +">>> def foo():\n" +"... f\"Não é uma docstring\"\n" +"...\n" +">>> foo.__doc__ is None\n" +"True" + #: ../../reference/lexical_analysis.rst:871 msgid "" "See also :pep:`498` for the proposal that added formatted string literals, " @@ -1466,6 +1684,16 @@ msgstr "" msgid "Some examples of integer literals::" msgstr "Alguns exemplos de literais inteiros::" +#: ../../reference/lexical_analysis.rst:931 +msgid "" +"7 2147483647 0o177 0b100110111\n" +"3 79228162514264337593543950336 0o377 0xdeadbeef\n" +" 100_000_000_000 0b_1110_0101" +msgstr "" +"7 2147483647 0o177 0b100110111\n" +"3 79228162514264337593543950336 0o377 0xdeadbeef\n" +" 100_000_000_000 0b_1110_0101" + #: ../../reference/lexical_analysis.rst:935 #: ../../reference/lexical_analysis.rst:967 msgid "Underscores are now allowed for grouping purposes in literals." @@ -1500,6 +1728,10 @@ msgstr "" msgid "Some examples of floating-point literals::" msgstr "Alguns exemplos de literais de ponto flutuante::" +#: ../../reference/lexical_analysis.rst:965 +msgid "3.14 10. .001 1e100 3.14e-10 0e0 3.14_15_93" +msgstr "3.14 10. .001 1e100 3.14e-10 0e0 3.14_15_93" + #: ../../reference/lexical_analysis.rst:976 msgid "Imaginary literals" msgstr "Literais imaginários" @@ -1524,6 +1756,10 @@ msgstr "" "flutuante a ele, por exemplo, ``(3+4j)``. Alguns exemplos de literais " "imaginários::" +#: ../../reference/lexical_analysis.rst:989 +msgid "3.14j 10.j 10j .001j 1e100j 3.14e-10j 3.14_15_93j" +msgstr "3.14j 10.j 10j .001j 1e100j 3.14e-10j 3.14_15_93j" + #: ../../reference/lexical_analysis.rst:995 msgid "Operators" msgstr "Operadores" @@ -1532,6 +1768,16 @@ msgstr "Operadores" msgid "The following tokens are operators:" msgstr "Os seguintes tokens são operadores:" +#: ../../reference/lexical_analysis.rst:1001 +msgid "" +"+ - * ** / // % @\n" +"<< >> & | ^ ~ :=\n" +"< > <= >= == !=" +msgstr "" +"+ - * ** / // % @\n" +"<< >> & | ^ ~ :=\n" +"< > <= >= == !=" + #: ../../reference/lexical_analysis.rst:1012 msgid "Delimiters" msgstr "Delimitadores" @@ -1540,6 +1786,18 @@ msgstr "Delimitadores" msgid "The following tokens serve as delimiters in the grammar:" msgstr "Os seguintes tokens servem como delimitadores na gramática:" +#: ../../reference/lexical_analysis.rst:1018 +msgid "" +"( ) [ ] { }\n" +", : ! . ; @ =\n" +"-> += -= *= /= //= %=\n" +"@= &= |= ^= >>= <<= **=" +msgstr "" +"( ) [ ] { }\n" +", : ! . ; @ =\n" +"-> += -= *= /= //= %=\n" +"@= &= |= ^= >>= <<= **=" + #: ../../reference/lexical_analysis.rst:1025 msgid "" "The period can also occur in floating-point and imaginary literals. A " @@ -1561,6 +1819,10 @@ msgstr "" "Os seguintes caracteres ASCII imprimíveis têm um significado especial como " "parte de outros tokens ou são significativos para o analisador léxico:" +#: ../../reference/lexical_analysis.rst:1033 +msgid "' \" # \\" +msgstr "' \" # \\" + #: ../../reference/lexical_analysis.rst:1037 msgid "" "The following printing ASCII characters are not used in Python. Their " @@ -1569,6 +1831,10 @@ msgstr "" "Os seguintes caracteres ASCII imprimíveis não são usados em Python. Sua " "ocorrência fora de literais de string e comentários é um erro incondicional:" +#: ../../reference/lexical_analysis.rst:1040 +msgid "$ ? `" +msgstr "$ ? `" + #: ../../reference/lexical_analysis.rst:1046 msgid "Footnotes" msgstr "Notas de rodapé" @@ -1589,103 +1855,103 @@ msgstr "analisador sintático" msgid "token" msgstr "token" -#: ../../reference/lexical_analysis.rst:25 +#: ../../reference/lexical_analysis.rst:26 msgid "line structure" msgstr "estrutura da linha" -#: ../../reference/lexical_analysis.rst:35 +#: ../../reference/lexical_analysis.rst:36 msgid "logical line" msgstr "linha lógica" -#: ../../reference/lexical_analysis.rst:35 -#: ../../reference/lexical_analysis.rst:114 +#: ../../reference/lexical_analysis.rst:36 +#: ../../reference/lexical_analysis.rst:115 #: ../../reference/lexical_analysis.rst:532 msgid "physical line" msgstr "linha física" -#: ../../reference/lexical_analysis.rst:35 -#: ../../reference/lexical_analysis.rst:114 +#: ../../reference/lexical_analysis.rst:36 +#: ../../reference/lexical_analysis.rst:115 msgid "line joining" msgstr "junção de linha" -#: ../../reference/lexical_analysis.rst:35 +#: ../../reference/lexical_analysis.rst:36 msgid "NEWLINE token" msgstr "token NEWLINE" -#: ../../reference/lexical_analysis.rst:67 +#: ../../reference/lexical_analysis.rst:68 msgid "comment" msgstr "comentário" -#: ../../reference/lexical_analysis.rst:67 +#: ../../reference/lexical_analysis.rst:68 msgid "hash character" msgstr "caractere cerquilha" -#: ../../reference/lexical_analysis.rst:67 -#: ../../reference/lexical_analysis.rst:81 +#: ../../reference/lexical_analysis.rst:68 +#: ../../reference/lexical_analysis.rst:82 msgid "# (hash)" msgstr "# (cerquilha)" -#: ../../reference/lexical_analysis.rst:81 +#: ../../reference/lexical_analysis.rst:82 msgid "source character set" msgstr "conjunto de caracteres do código-fonte" -#: ../../reference/lexical_analysis.rst:81 +#: ../../reference/lexical_analysis.rst:82 msgid "encoding declarations (source file)" msgstr "declaração de codificação (arquivo fonte)" -#: ../../reference/lexical_analysis.rst:81 +#: ../../reference/lexical_analysis.rst:82 msgid "source encoding declaration" msgstr "declaração de codificação de código-fonte" -#: ../../reference/lexical_analysis.rst:114 +#: ../../reference/lexical_analysis.rst:115 msgid "line continuation" msgstr "continuação de linha" -#: ../../reference/lexical_analysis.rst:114 +#: ../../reference/lexical_analysis.rst:115 msgid "backslash character" msgstr "caractere contrabarra" -#: ../../reference/lexical_analysis.rst:159 +#: ../../reference/lexical_analysis.rst:160 msgid "blank line" msgstr "linha em branco" -#: ../../reference/lexical_analysis.rst:174 +#: ../../reference/lexical_analysis.rst:175 msgid "indentation" msgstr "indentação" -#: ../../reference/lexical_analysis.rst:174 +#: ../../reference/lexical_analysis.rst:175 msgid "leading whitespace" msgstr "espaço em branco inicial" -#: ../../reference/lexical_analysis.rst:174 +#: ../../reference/lexical_analysis.rst:175 msgid "space" msgstr "espaço" -#: ../../reference/lexical_analysis.rst:174 +#: ../../reference/lexical_analysis.rst:175 msgid "tab" msgstr "tabulação" -#: ../../reference/lexical_analysis.rst:174 +#: ../../reference/lexical_analysis.rst:175 msgid "grouping" msgstr "agrupamento" -#: ../../reference/lexical_analysis.rst:174 +#: ../../reference/lexical_analysis.rst:175 msgid "statement grouping" msgstr "agrupamento de instruções" -#: ../../reference/lexical_analysis.rst:202 +#: ../../reference/lexical_analysis.rst:203 msgid "INDENT token" msgstr "token INDENT" -#: ../../reference/lexical_analysis.rst:202 +#: ../../reference/lexical_analysis.rst:203 msgid "DEDENT token" msgstr "token DEDENT" -#: ../../reference/lexical_analysis.rst:277 +#: ../../reference/lexical_analysis.rst:278 msgid "identifier" msgstr "identificador" -#: ../../reference/lexical_analysis.rst:277 +#: ../../reference/lexical_analysis.rst:278 msgid "name" msgstr "nome" @@ -1750,7 +2016,7 @@ msgstr "u\"" #: ../../reference/lexical_analysis.rst:479 msgid "triple-quoted string" -msgstr "string entre aspas triplas" +msgstr "aspas triplas" #: ../../reference/lexical_analysis.rst:479 msgid "Unicode Consortium" diff --git a/reference/simple_stmts.po b/reference/simple_stmts.po index 8f626e132..8dda39d8d 100644 --- a/reference/simple_stmts.po +++ b/reference/simple_stmts.po @@ -1,32 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# felipe caridade fernandes , 2023 -# Ricardo Cappellano , 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# Vinicius Gubiani Ferreira , 2023 -# Marco Rougeth , 2023 -# Adorilson Bezerra , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -259,6 +252,18 @@ msgstr "" "atributo de classe, o lado esquerdo cria um novo atributo de instância como " "alvo da atribuição::" +#: ../../reference/simple_stmts.rst:179 +msgid "" +"class Cls:\n" +" x = 3 # class variable\n" +"inst = Cls()\n" +"inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3" +msgstr "" +"class Cls:\n" +" x = 3 # variável de classe\n" +"inst = Cls()\n" +"inst.x = inst.x + 1 # escreve inst.x como 4 deixando Cls.x como 3" + #: ../../reference/simple_stmts.rst:184 msgid "" "This description does not necessarily apply to descriptor attributes, such " @@ -372,6 +377,18 @@ msgstr "" "atribuídas ocorrem da esquerda para a direita, às vezes resultando em " "confusão. Por exemplo, o programa a seguir imprime ``[0, 2]``::" +#: ../../reference/simple_stmts.rst:246 +msgid "" +"x = [0, 1]\n" +"i = 0\n" +"i, x[i] = 1, 2 # i is updated, then x[i] is updated\n" +"print(x)" +msgstr "" +"x = [0, 1]\n" +"i = 0\n" +"i, x[i] = 1, 2 # i é atualizado e, em seguida, x[i] é atualizado\n" +"print(x)" + #: ../../reference/simple_stmts.rst:254 msgid ":pep:`3132` - Extended Iterable Unpacking" msgstr ":pep:`3132` - Desempacotamento estendido de iterável" @@ -593,32 +610,49 @@ msgstr "" msgid "The simple form, ``assert expression``, is equivalent to ::" msgstr "A forma simples, ``assert expression``, é equivalente a ::" +#: ../../reference/simple_stmts.rst:395 +msgid "" +"if __debug__:\n" +" if not expression: raise AssertionError" +msgstr "" +"if __debug__:\n" +" if not expression: raise AssertionError" + #: ../../reference/simple_stmts.rst:398 msgid "" "The extended form, ``assert expression1, expression2``, is equivalent to ::" msgstr "" "A forma estendida, ``assert expression1, expression2``, é equivalente a ::" +#: ../../reference/simple_stmts.rst:400 +msgid "" +"if __debug__:\n" +" if not expression1: raise AssertionError(expression2)" +msgstr "" +"if __debug__:\n" +" if not expression1: raise AssertionError(expression2)" + #: ../../reference/simple_stmts.rst:407 msgid "" "These equivalences assume that :const:`__debug__` and :exc:`AssertionError` " "refer to the built-in variables with those names. In the current " -"implementation, the built-in variable :const:`__debug__` is ``True`` under " -"normal circumstances, ``False`` when optimization is requested (command line " -"option :option:`-O`). The current code generator emits no code for an " -"assert statement when optimization is requested at compile time. Note that " -"it is unnecessary to include the source code for the expression that failed " -"in the error message; it will be displayed as part of the stack trace." +"implementation, the built-in variable ``__debug__`` is ``True`` under normal " +"circumstances, ``False`` when optimization is requested (command line " +"option :option:`-O`). The current code generator emits no code for an :" +"keyword:`assert` statement when optimization is requested at compile time. " +"Note that it is unnecessary to include the source code for the expression " +"that failed in the error message; it will be displayed as part of the stack " +"trace." msgstr "" "Essas equivalências presumem que :const:`__debug__` e :exc:`AssertionError` " "referem-se às variáveis embutidas com esses nomes. Na implementação atual, a " -"variável embutida :const:`__debug__` é ``True`` em circunstâncias normais, " +"variável embutida ``__debug__`` é ``True`` em circunstâncias normais, " "``False`` quando a otimização é solicitada (opção de linha de comando :" -"option:`-O`). O gerador de código atual não emite código para uma instrução " -"assert quando a otimização é solicitada em tempo de compilação. Observe que " -"não é necessário incluir o código-fonte da expressão que falhou na mensagem " -"de erro; ele será exibido como parte do stack trace (situação da pilha de " -"execução)." +"option:`-O`). O gerador de código atual não emite código para uma instrução :" +"keyword:`assert` quando a otimização é solicitada em tempo de compilação. " +"Observe que não é necessário incluir o código-fonte da expressão que falhou " +"na mensagem de erro; ele será exibido como parte do stack trace (situação da " +"pilha de execução)." #: ../../reference/simple_stmts.rst:416 msgid "" @@ -642,6 +676,16 @@ msgstr "" "útil como um espaço reservado quando uma instrução é necessária " "sintaticamente, mas nenhum código precisa ser executado, por exemplo::" +#: ../../reference/simple_stmts.rst:437 +msgid "" +"def f(arg): pass # a function that does nothing (yet)\n" +"\n" +"class C: pass # a class with no methods (yet)" +msgstr "" +"def f(arg): pass # uma função que faz nada (ainda)\n" +"\n" +"class C: pass # uma classe com nenhum método (ainda)" + #: ../../reference/simple_stmts.rst:445 msgid "The :keyword:`!del` statement" msgstr "A instrução :keyword:`!del`" @@ -764,30 +808,47 @@ msgstr "A instrução :keyword:`!yield`" #: ../../reference/simple_stmts.rst:533 msgid "" "A :keyword:`yield` statement is semantically equivalent to a :ref:`yield " -"expression `. The yield statement can be used to omit the " +"expression `. The ``yield`` statement can be used to omit the " "parentheses that would otherwise be required in the equivalent yield " "expression statement. For example, the yield statements ::" msgstr "" "Uma instrução :keyword:`yield` é semanticamente equivalente a uma :ref:" -"`expressão yield `. A instrução yield pode ser usada para omitir " -"os parênteses que, de outra forma, seriam necessários na instrução de " +"`expressão yield `. A instrução ``yield`` pode ser usada para " +"omitir os parênteses que, de outra forma, seriam necessários na instrução de " "expressão yield equivalente. Por exemplo, as instruções yield ::" +#: ../../reference/simple_stmts.rst:538 +msgid "" +"yield \n" +"yield from " +msgstr "" +"yield \n" +"yield from " + #: ../../reference/simple_stmts.rst:541 msgid "are equivalent to the yield expression statements ::" msgstr "são equivalentes às instruções de expressão yield ::" +#: ../../reference/simple_stmts.rst:543 +msgid "" +"(yield )\n" +"(yield from )" +msgstr "" +"(yield )\n" +"(yield from )" + #: ../../reference/simple_stmts.rst:546 msgid "" "Yield expressions and statements are only used when defining a :term:" "`generator` function, and are only used in the body of the generator " -"function. Using yield in a function definition is sufficient to cause that " -"definition to create a generator function instead of a normal function." +"function. Using :keyword:`yield` in a function definition is sufficient to " +"cause that definition to create a generator function instead of a normal " +"function." msgstr "" "Expressões e instruções yield são usadas apenas ao definir uma função :term:" -"`geradora ` e são usadas apenas no corpo da função geradora. Usar " -"yield em uma definição de função é suficiente para fazer com que essa " -"definição crie uma função geradora em vez de uma função normal." +"`geradora ` e são usadas apenas no corpo da função geradora. Usar :" +"keyword:`yield` em uma definição de função é suficiente para fazer com que " +"essa definição crie uma função geradora em vez de uma função normal." #: ../../reference/simple_stmts.rst:551 msgid "" @@ -849,6 +910,10 @@ msgstr "" "`~BaseException.with_traceback` (que retorna a mesma instância de exceção, " "com seu traceback definido para seu argumento), assim::" +#: ../../reference/simple_stmts.rst:589 +msgid "raise Exception(\"foo occurred\").with_traceback(tracebackobj)" +msgstr "raise Exception(\"ocorreu foo\").with_traceback(tracebackobj)" + #: ../../reference/simple_stmts.rst:595 msgid "" "The ``from`` clause is used for exception chaining: if given, the second " @@ -869,6 +934,44 @@ msgstr "" "levantada como o atributo :attr:`!__cause__`. Se a exceção levantada não for " "tratada, ambas as exceções serão impressas::" +#: ../../reference/simple_stmts.rst:604 +msgid "" +">>> try:\n" +"... print(1 / 0)\n" +"... except Exception as exc:\n" +"... raise RuntimeError(\"Something bad happened\") from exc\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +" print(1 / 0)\n" +" ~~^~~\n" +"ZeroDivisionError: division by zero\n" +"\n" +"The above exception was the direct cause of the following exception:\n" +"\n" +"Traceback (most recent call last):\n" +" File \"\", line 4, in \n" +" raise RuntimeError(\"Something bad happened\") from exc\n" +"RuntimeError: Something bad happened" +msgstr "" +">>> try:\n" +"... print(1 / 0)\n" +"... except Exception as exc:\n" +"... raise RuntimeError(\"Something bad happened\") from exc\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +" print(1 / 0)\n" +" ~~^~~\n" +"ZeroDivisionError: division by zero\n" +"\n" +"The above exception was the direct cause of the following exception:\n" +"\n" +"Traceback (most recent call last):\n" +" File \"\", line 4, in \n" +" raise RuntimeError(\"Something bad happened\") from exc\n" +"RuntimeError: Something bad happened" + #: ../../reference/simple_stmts.rst:624 msgid "" "A similar mechanism works implicitly if a new exception is raised when an " @@ -883,6 +986,44 @@ msgstr "" "instrução :keyword:`with`, é usada. A exceção anterior é então anexada como " "o atributo :attr:`~BaseException.__context__` da nova exceção:" +#: ../../reference/simple_stmts.rst:630 +msgid "" +">>> try:\n" +"... print(1 / 0)\n" +"... except:\n" +"... raise RuntimeError(\"Something bad happened\")\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +" print(1 / 0)\n" +" ~~^~~\n" +"ZeroDivisionError: division by zero\n" +"\n" +"During handling of the above exception, another exception occurred:\n" +"\n" +"Traceback (most recent call last):\n" +" File \"\", line 4, in \n" +" raise RuntimeError(\"Something bad happened\")\n" +"RuntimeError: Something bad happened" +msgstr "" +">>> try:\n" +"... print(1 / 0)\n" +"... except:\n" +"... raise RuntimeError(\"Something bad happened\")\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +" print(1 / 0)\n" +" ~~^~~\n" +"ZeroDivisionError: division by zero\n" +"\n" +"During handling of the above exception, another exception occurred:\n" +"\n" +"Traceback (most recent call last):\n" +" File \"\", line 4, in \n" +" raise RuntimeError(\"Something bad happened\")\n" +"RuntimeError: Something bad happened" + #: ../../reference/simple_stmts.rst:650 msgid "" "Exception chaining can be explicitly suppressed by specifying :const:`None` " @@ -891,6 +1032,26 @@ msgstr "" "O encadeamento de exceção pode ser explicitamente suprimido especificando :" "const:`None` na cláusula ``from``:" +#: ../../reference/simple_stmts.rst:653 +msgid "" +">>> try:\n" +"... print(1 / 0)\n" +"... except:\n" +"... raise RuntimeError(\"Something bad happened\") from None\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 4, in \n" +"RuntimeError: Something bad happened" +msgstr "" +">>> try:\n" +"... print(1 / 0)\n" +"... except:\n" +"... raise RuntimeError(\"Something bad happened\") from None\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 4, in \n" +"RuntimeError: Something bad happened" + #: ../../reference/simple_stmts.rst:664 msgid "" "Additional information on exceptions can be found in section :ref:" @@ -1057,8 +1218,8 @@ msgid "" "If the module name is followed by :keyword:`!as`, then the name following :" "keyword:`!as` is bound directly to the imported module." msgstr "" -"Se o nome do módulo é seguido pela palavra reservada :keyword:`!as`, o nome " -"a seguir é vinculado diretamente ao módulo importado." +"Se o nome do módulo é seguido pela palavra-chave :keyword:`!as`, o nome a " +"seguir é vinculado diretamente ao módulo importado." #: ../../reference/simple_stmts.rst:789 msgid "" @@ -1131,6 +1292,26 @@ msgstr "" msgid "Examples::" msgstr "Exemplos::" +#: ../../reference/simple_stmts.rst:818 +msgid "" +"import foo # foo imported and bound locally\n" +"import foo.bar.baz # foo, foo.bar, and foo.bar.baz imported, foo " +"bound locally\n" +"import foo.bar.baz as fbb # foo, foo.bar, and foo.bar.baz imported, foo.bar." +"baz bound as fbb\n" +"from foo.bar import baz # foo, foo.bar, and foo.bar.baz imported, foo.bar." +"baz bound as baz\n" +"from foo import attr # foo imported and foo.attr bound as attr" +msgstr "" +"import foo # foo importado e vinculado localmente\n" +"import foo.bar.baz # foo, foo.bar e foo.bar.baz importados, foo " +"vinculado localmente\n" +"import foo.bar.baz as fbb # foo, foo.bar e foo.bar.baz importados, foo.bar." +"baz vinculado como fbb\n" +"from foo.bar import baz # foo, foo.bar e foo.bar.baz importados, foo.bar." +"baz vinculado como baz\n" +"from foo import attr # foo importado e foo.attr vinculado como attr" + #: ../../reference/simple_stmts.rst:826 msgid "" "If the list of identifiers is replaced by a star (``'*'``), all public names " @@ -1347,6 +1528,10 @@ msgstr "" msgid "Note that there is nothing special about the statement::" msgstr "Observe que não há nada de especial sobre a instrução::" +#: ../../reference/simple_stmts.rst:931 +msgid "import __future__ [as name]" +msgstr "import __future__ [as name]" + #: ../../reference/simple_stmts.rst:933 msgid "" "That is not a future statement; it's an ordinary import statement with no " @@ -1397,51 +1582,27 @@ msgstr "A instrução :keyword:`!global`" #: ../../reference/simple_stmts.rst:967 msgid "" -"The :keyword:`global` statement is a declaration which holds for the entire " -"current code block. It means that the listed identifiers are to be " -"interpreted as globals. It would be impossible to assign to a global " +"The :keyword:`global` statement causes the listed identifiers to be " +"interpreted as globals. It would be impossible to assign to a global " "variable without :keyword:`!global`, although free variables may refer to " "globals without being declared global." msgstr "" -"A instrução :keyword:`global` é uma declaração que vale para todo o bloco de " -"código atual. Isso significa que os identificadores listados devem ser " -"interpretados como globais. Seria impossível atribuir a uma variável global " -"sem :keyword:`!global`, embora variáveis livres possam se referir a globais " -"sem serem declaradas globais." - -#: ../../reference/simple_stmts.rst:973 -msgid "" -"Names listed in a :keyword:`global` statement must not be used in the same " -"code block textually preceding that :keyword:`!global` statement." -msgstr "" -"Nomes listados em uma instrução :keyword:`global` não devem ser usados no " -"mesmo bloco de código que precede textualmente a instrução :keyword:`!" -"global`." - -#: ../../reference/simple_stmts.rst:976 -msgid "" -"Names listed in a :keyword:`global` statement must not be defined as formal " -"parameters, or as targets in :keyword:`with` statements or :keyword:`except` " -"clauses, or in a :keyword:`for` target list, :keyword:`class` definition, " -"function definition, :keyword:`import` statement, or variable annotation." -msgstr "" -"Os nomes listados em uma instrução :keyword:`global` não devem ser definidos " -"como parâmetros formais, ou como alvos em instruções :keyword:`with` ou " -"cláusulas :keyword:`except`, ou em uma lista alvo :keyword:`for`, definição " -"de :keyword:`class`, definição de função, instrução :keyword:`import` ou " -"anotação de variável." +"A instrução :keyword:`global` faz com que os identificadores listados a " +"serem interpretados como globais. Seria impossível atribuir a uma variável " +"global sem :keyword:`!global`, embora variáveis livres possam se referir a " +"globais sem serem declaradas globais." -#: ../../reference/simple_stmts.rst:983 +#: ../../reference/simple_stmts.rst:972 msgid "" -"The current implementation does not enforce some of these restrictions, but " -"programs should not abuse this freedom, as future implementations may " -"enforce them or silently change the meaning of the program." +"The :keyword:`global` statement applies to the entire scope of a function or " +"class body. A :exc:`SyntaxError` is raised if a variable is used or assigned " +"to prior to its global declaration in the scope." msgstr "" -"A implementação atual não impõe algumas dessas restrições, mas os programas " -"não devem abusar dessa liberdade, pois implementações future podem aplicá-" -"las ou alterar silenciosamente o significado do programa." +"A instrução :keyword:`global` se aplica a todo o escopo de uma função ou " +"corpo da classe. Uma exceção :exc:`SyntaxError` é levantada se uma variável " +"for usada ou atribuída antes de sua declaração global no escopo." -#: ../../reference/simple_stmts.rst:992 +#: ../../reference/simple_stmts.rst:981 msgid "" "**Programmer's note:** :keyword:`global` is a directive to the parser. It " "applies only to code parsed at the same time as the :keyword:`!global` " @@ -1461,11 +1622,11 @@ msgstr "" "global` no código que contém a chamada da função. O mesmo se aplica às " "funções :func:`eval` e :func:`compile`." -#: ../../reference/simple_stmts.rst:1004 +#: ../../reference/simple_stmts.rst:993 msgid "The :keyword:`!nonlocal` statement" msgstr "A instrução :keyword:`!nonlocal`" -#: ../../reference/simple_stmts.rst:1012 +#: ../../reference/simple_stmts.rst:1001 msgid "" "When the definition of a function or class is nested (enclosed) within the " "definitions of other functions, its nonlocal scopes are the local scopes of " @@ -1486,25 +1647,25 @@ msgstr "" "vinculado a nenhum escopo não local, ou se não houver escopo não local, uma " "exceção :exc:`SyntaxError` será levantada." -#: ../../reference/simple_stmts.rst:1021 +#: ../../reference/simple_stmts.rst:1010 msgid "" -"The nonlocal statement applies to the entire scope of a function or class " -"body. A :exc:`SyntaxError` is raised if a variable is used or assigned to " -"prior to its nonlocal declaration in the scope." +"The :keyword:`nonlocal` statement applies to the entire scope of a function " +"or class body. A :exc:`SyntaxError` is raised if a variable is used or " +"assigned to prior to its nonlocal declaration in the scope." msgstr "" -"A instrução não local se aplica a todo o escopo de uma função ou corpo da " -"classe. Uma exceção :exc:`SyntaxError` é levantada se uma variável for usada " -"ou atribuída antes de sua declaração não local no escopo." +"A instrução :keyword:`nonlocal` se aplica a todo o escopo de uma função ou " +"corpo da classe. Uma exceção :exc:`SyntaxError` é levantada se uma variável " +"for usada ou atribuída antes de sua declaração nonlocal no escopo." -#: ../../reference/simple_stmts.rst:1027 +#: ../../reference/simple_stmts.rst:1016 msgid ":pep:`3104` - Access to Names in Outer Scopes" msgstr ":pep:`3104` - Acesso a nomes em escopos externos" -#: ../../reference/simple_stmts.rst:1028 +#: ../../reference/simple_stmts.rst:1017 msgid "The specification for the :keyword:`nonlocal` statement." msgstr "A especificação para a instrução :keyword:`nonlocal`." -#: ../../reference/simple_stmts.rst:1030 +#: ../../reference/simple_stmts.rst:1019 msgid "" "**Programmer's note:** :keyword:`nonlocal` is a directive to the parser and " "applies only to code parsed along with it. See the note for the :keyword:" @@ -1514,11 +1675,11 @@ msgstr "" "analisador sintático e se aplica apenas ao código analisado junto com ele. " "Veja a nota para a instrução :keyword:`global`." -#: ../../reference/simple_stmts.rst:1038 +#: ../../reference/simple_stmts.rst:1027 msgid "The :keyword:`!type` statement" msgstr "A instrução :keyword:`!type`" -#: ../../reference/simple_stmts.rst:1045 +#: ../../reference/simple_stmts.rst:1034 msgid "" "The :keyword:`!type` statement declares a type alias, which is an instance " "of :class:`typing.TypeAliasType`." @@ -1526,15 +1687,29 @@ msgstr "" "A instrução :keyword:`!type` declara um apelido de tipo, que é uma instância " "de :class:`typing.TypeAliasType`." -#: ../../reference/simple_stmts.rst:1048 +#: ../../reference/simple_stmts.rst:1037 msgid "For example, the following statement creates a type alias::" msgstr "Por exemplo, a instrução a seguir cria um apelido de tipo::" -#: ../../reference/simple_stmts.rst:1052 +#: ../../reference/simple_stmts.rst:1039 +msgid "type Point = tuple[float, float]" +msgstr "type Point = tuple[float, float]" + +#: ../../reference/simple_stmts.rst:1041 msgid "This code is roughly equivalent to::" msgstr "Este código é aproximadamente equivalente a::" -#: ../../reference/simple_stmts.rst:1058 +#: ../../reference/simple_stmts.rst:1043 +msgid "" +"annotation-def VALUE_OF_Point():\n" +" return tuple[float, float]\n" +"Point = typing.TypeAliasType(\"Point\", VALUE_OF_Point())" +msgstr "" +"annotation-def VALUE_OF_Point():\n" +" return tuple[float, float]\n" +"Point = typing.TypeAliasType(\"Point\", VALUE_OF_Point())" + +#: ../../reference/simple_stmts.rst:1047 msgid "" "``annotation-def`` indicates an :ref:`annotation scope `, " "which behaves mostly like a function, but with several small differences." @@ -1543,7 +1718,7 @@ msgstr "" "que se comporta principalmente como uma função, mas com diversas pequenas " "diferenças." -#: ../../reference/simple_stmts.rst:1061 +#: ../../reference/simple_stmts.rst:1050 msgid "" "The value of the type alias is evaluated in the annotation scope. It is not " "evaluated when the type alias is created, but only when the value is " @@ -1557,7 +1732,7 @@ msgstr "" "ref:`lazy-evaluation`). Isso permite que o apelido de tipo se refira a nomes " "que ainda não estão definidos." -#: ../../reference/simple_stmts.rst:1067 +#: ../../reference/simple_stmts.rst:1056 msgid "" "Type aliases may be made generic by adding a :ref:`type parameter list ` after the name. See :ref:`generic-type-aliases` for more." @@ -1566,16 +1741,16 @@ msgstr "" "parâmetros de tipo ` após o nome. Veja :ref:`generic-type-" "aliases` para mais." -#: ../../reference/simple_stmts.rst:1070 +#: ../../reference/simple_stmts.rst:1059 msgid ":keyword:`!type` is a :ref:`soft keyword `." msgstr "" ":keyword:`!type` é uma :ref:`palavra reservada contextual `." -#: ../../reference/simple_stmts.rst:1076 +#: ../../reference/simple_stmts.rst:1065 msgid ":pep:`695` - Type Parameter Syntax" msgstr ":pep:`695` - Sintaxe de parâmetros de tipo" -#: ../../reference/simple_stmts.rst:1077 +#: ../../reference/simple_stmts.rst:1066 msgid "" "Introduced the :keyword:`!type` statement and syntax for generic classes and " "functions." @@ -1595,8 +1770,8 @@ msgstr "simples" #: ../../reference/simple_stmts.rst:523 ../../reference/simple_stmts.rst:559 #: ../../reference/simple_stmts.rst:684 ../../reference/simple_stmts.rst:718 #: ../../reference/simple_stmts.rst:743 ../../reference/simple_stmts.rst:873 -#: ../../reference/simple_stmts.rst:959 ../../reference/simple_stmts.rst:1006 -#: ../../reference/simple_stmts.rst:1040 +#: ../../reference/simple_stmts.rst:959 ../../reference/simple_stmts.rst:995 +#: ../../reference/simple_stmts.rst:1029 msgid "statement" msgstr "instrução" @@ -1610,7 +1785,7 @@ msgstr "expressão" msgid "list" msgstr "lista" -#: ../../reference/simple_stmts.rst:56 ../../reference/simple_stmts.rst:987 +#: ../../reference/simple_stmts.rst:56 ../../reference/simple_stmts.rst:976 msgid "built-in function" msgstr "função embutida" @@ -1706,7 +1881,7 @@ msgstr "alvo" #: ../../reference/simple_stmts.rst:116 ../../reference/simple_stmts.rst:382 #: ../../reference/simple_stmts.rst:743 ../../reference/simple_stmts.rst:959 -#: ../../reference/simple_stmts.rst:1006 +#: ../../reference/simple_stmts.rst:995 msgid ", (comma)" msgstr ", (vírgula)" @@ -2036,26 +2211,26 @@ msgstr "__future__" msgid "future statement" msgstr "instrução future" -#: ../../reference/simple_stmts.rst:959 ../../reference/simple_stmts.rst:1006 +#: ../../reference/simple_stmts.rst:959 ../../reference/simple_stmts.rst:995 msgid "identifier list" msgstr "identificadores, lista de" -#: ../../reference/simple_stmts.rst:987 +#: ../../reference/simple_stmts.rst:976 msgid "exec" msgstr "exec" -#: ../../reference/simple_stmts.rst:987 +#: ../../reference/simple_stmts.rst:976 msgid "eval" msgstr "eval" -#: ../../reference/simple_stmts.rst:987 +#: ../../reference/simple_stmts.rst:976 msgid "compile" msgstr "compile" -#: ../../reference/simple_stmts.rst:1006 +#: ../../reference/simple_stmts.rst:995 msgid "nonlocal" msgstr "nonlocal" -#: ../../reference/simple_stmts.rst:1040 +#: ../../reference/simple_stmts.rst:1029 msgid "type" msgstr "tipo" diff --git a/reference/toplevel_components.po b/reference/toplevel_components.po index 518cc2e32..2ce030930 100644 --- a/reference/toplevel_components.po +++ b/reference/toplevel_components.po @@ -1,29 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Julia Rizza , 2021 -# Claudio Rogerio Carvalho Filho , 2023 -# Marco Rougeth , 2023 -# felipe caridade fernandes , 2023 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 6582ba5fe..000000000 --- a/requirements.txt +++ /dev/null @@ -1,35 +0,0 @@ -alabaster==0.7.16 -Babel==2.15.0 -certifi==2024.7.4 -charset-normalizer==3.3.2 -click==8.1.7 -docutils==0.21.2 -idna==3.7 -imagesize==1.4.1 -Jinja2==3.1.4 -MarkupSafe==2.1.5 -packaging==24.1 -polib==1.2.0 -pomerge==0.1.4 -pospell==1.3 -powrap==1.0.1 -Pygments==2.18.0 -python-docs-theme>=2023.3.1,!=2023.7 -regex==2024.5.15 -requests==2.32.3 -snowballstemmer==2.2.0 -Sphinx==7.3.0 -sphinx-autobuild==2024.4.16 -sphinx-intl==2.2.0 -sphinx-lint==0.9.1 -sphinx-notfound-page==1.0.2 -sphinxcontrib-applehelp==1.0.8 -sphinxcontrib-devhelp==1.0.6 -sphinxcontrib-htmlhelp==2.0.5 -sphinxcontrib-jsmath==1.0.1 -sphinxcontrib-qthelp==1.0.7 -sphinxcontrib-serializinghtml==1.1.10 -sphinxext-opengraph==0.9.1 -tqdm==4.66.4 -translate-toolkit==3.13.2 -urllib3==1.26.19 diff --git a/requirements.txt.in b/requirements.txt.in deleted file mode 100644 index 0640e6881..000000000 --- a/requirements.txt.in +++ /dev/null @@ -1,5 +0,0 @@ -pomerge -powrap -pospell -sphinx-intl>=2.1.0 -sphinx-lint diff --git a/sphinx.po b/sphinx.po index c71e76db8..ba41f0d1b 100644 --- a/sphinx.po +++ b/sphinx.po @@ -1,60 +1,62 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Welington Carlos , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# And Past , 2021 -# Adorilson Bezerra , 2024 -# i17obot , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 00:47+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" +#: ../../tools/templates/_docs_by_version.html:10 +msgid "Stable" +msgstr "Estável" + +#: ../../tools/templates/_docs_by_version.html:11 +msgid "In development" +msgstr "Em desenvolvimento" + #: ../../tools/templates/customsourcelink.html:3 -msgid "This Page" -msgstr "Esta página" +msgid "This page" +msgstr "" #: ../../tools/templates/customsourcelink.html:5 -msgid "Report a Bug" -msgstr "Relatar um erro" +msgid "Report a bug" +msgstr "" #: ../../tools/templates/customsourcelink.html:8 -msgid "Show Source" -msgstr "Exibir código-fonte" +msgid "Show source" +msgstr "" #: ../../tools/templates/download.html:2 #: ../../tools/templates/indexsidebar.html:1 msgid "Download" msgstr "Download" -#: ../../tools/templates/download.html:14 -msgid "Download Python %(release)s Documentation" -msgstr "Download da documentação do Python %(release)s" +#: ../../tools/templates/download.html:30 +msgid "Download Python %(dl_version)s documentation" +msgstr "" -#: ../../tools/templates/download.html:16 +#: ../../tools/templates/download.html:32 msgid "Last updated on: %(last_updated)s." msgstr "Última atualização em: %(last_updated)s." -#: ../../tools/templates/download.html:18 +#: ../../tools/templates/download.html:34 msgid "" "To download an archive containing all the documents for this version of\n" "Python in one of various formats, follow one of links in this table." @@ -62,139 +64,119 @@ msgstr "" "Para baixar um arquivo contendo todos os documentos para esta versão do\n" "Python em um dos vários formatos, siga um dos links nesta tabela." -#: ../../tools/templates/download.html:23 +#: ../../tools/templates/download.html:39 msgid "Format" msgstr "Formatação" -#: ../../tools/templates/download.html:24 +#: ../../tools/templates/download.html:40 msgid "Packed as .zip" msgstr "Compactado como .zip" -#: ../../tools/templates/download.html:25 +#: ../../tools/templates/download.html:41 msgid "Packed as .tar.bz2" msgstr "Compactado como .tar.bz2" -#: ../../tools/templates/download.html:28 -msgid "PDF (US-Letter paper size)" -msgstr "PDF (tamanho de papel Carta)" +#: ../../tools/templates/download.html:44 +msgid "PDF" +msgstr "PDF" -#: ../../tools/templates/download.html:29 +#: ../../tools/templates/download.html:45 msgid "" -"Download " +"Download " "(ca. %(download_size)s MiB)" msgstr "" -"Baixar " +"Baixar " "(%(download_size)s MiB)" -#: ../../tools/templates/download.html:30 +#: ../../tools/templates/download.html:46 msgid "" -"DownloadDownload (ca. %(download_size)s MiB)" msgstr "" -"Baixar " -"(%(download_size)s MiB)" - -#: ../../tools/templates/download.html:33 -msgid "PDF (A4 paper size)" -msgstr "PDF (tamanho de papel A4)" - -#: ../../tools/templates/download.html:34 -msgid "" -"Download (ca. " -"%(download_size)s MiB)" -msgstr "" -"Baixar " +"Baixar " "(%(download_size)s MiB)" -#: ../../tools/templates/download.html:35 -msgid "" -"Download " -"(ca. %(download_size)s MiB)" -msgstr "" -"Baixar " -"(%(download_size)s MiB)" - -#: ../../tools/templates/download.html:38 +#: ../../tools/templates/download.html:49 msgid "HTML" msgstr "HTML" -#: ../../tools/templates/download.html:39 +#: ../../tools/templates/download.html:50 msgid "" -"Download (ca. " -"%(download_size)s MiB)" +"Download " +"(ca. %(download_size)s MiB)" msgstr "" -"Baixar " +"Baixar " "(%(download_size)s MiB)" -#: ../../tools/templates/download.html:40 +#: ../../tools/templates/download.html:51 msgid "" -"Download " +"Download " "(ca. %(download_size)s MiB)" msgstr "" -"Baixar " +"Baixar " "(%(download_size)s MiB)" -#: ../../tools/templates/download.html:43 +#: ../../tools/templates/download.html:54 msgid "Plain text" msgstr "Texto simples" -#: ../../tools/templates/download.html:44 +#: ../../tools/templates/download.html:55 msgid "" -"Download (ca. " -"%(download_size)s MiB)" +"Download " +"(ca. %(download_size)s MiB)" msgstr "" -"Baixar " -"( %(download_size)s MiB)" +"Baixar " +"(%(download_size)s MiB)" -#: ../../tools/templates/download.html:45 +#: ../../tools/templates/download.html:56 msgid "" -"Download " +"Download " "(ca. %(download_size)s MiB)" msgstr "" -"Baixar " +"Baixar " "(%(download_size)s MiB)" -#: ../../tools/templates/download.html:48 +#: ../../tools/templates/download.html:59 msgid "Texinfo" msgstr "Texinfo" -#: ../../tools/templates/download.html:49 +#: ../../tools/templates/download.html:60 msgid "" -"Download (ca. " -"%(download_size)s MiB)" +"Download " +"(ca. %(download_size)s MiB)" msgstr "" -"Baixar " +"Baixar " "(%(download_size)s MiB)" -#: ../../tools/templates/download.html:50 +#: ../../tools/templates/download.html:61 msgid "" -"Download " -"(ca. %(download_size)s MiB)" +"Download (ca. %(download_size)s MiB)" msgstr "" -"Baixar " -"(%(download_size)s MiB)" +"Baixar (%(download_size)s MiB)" -#: ../../tools/templates/download.html:53 +#: ../../tools/templates/download.html:64 msgid "EPUB" msgstr "EPUB" -#: ../../tools/templates/download.html:54 +#: ../../tools/templates/download.html:65 msgid "" -"Download (ca. " +"Download (ca. " "%(download_size)s MiB)" msgstr "" -"Baixar " +"Baixar " "(%(download_size)s MiB)" -#: ../../tools/templates/download.html:59 +#: ../../tools/templates/download.html:70 msgid "These archives contain all the content in the documentation." msgstr "Esses arquivos contêm todo o conteúdo da documentação." -#: ../../tools/templates/download.html:62 +#: ../../tools/templates/download.html:73 msgid "Unpacking" msgstr "Descompactando" -#: ../../tools/templates/download.html:64 +#: ../../tools/templates/download.html:75 msgid "" "Unix users should download the .tar.bz2 archives; these are bzipped tar\n" "archives and can be handled in the usual way using tar and the bzip2\n" @@ -211,7 +193,7 @@ msgstr "" "desejado. Os arquivos .tar.bz2 fornecem a melhor compressão e tempos de " "download mais rápidos." -#: ../../tools/templates/download.html:70 +#: ../../tools/templates/download.html:81 msgid "" "Windows users can use the ZIP archives since those are customary on that\n" "platform. These are created on Unix using the Info-ZIP zip program." @@ -219,11 +201,11 @@ msgstr "" "Usuários do Windows podem usar os arquivos ZIP, pois eles são comuns nessa " "plataforma. Eles são criados no Unix usando o programa zip do Info-ZIP." -#: ../../tools/templates/download.html:74 +#: ../../tools/templates/download.html:85 msgid "Problems" msgstr "Problemas" -#: ../../tools/templates/download.html:76 +#: ../../tools/templates/download.html:87 msgid "" "If you have comments or suggestions for the Python documentation, please " "send\n" @@ -233,105 +215,109 @@ msgstr "" "um e-mail para docs@python.org." #: ../../tools/templates/dummy.html:6 -msgid "CPython implementation detail:" -msgstr "Detalhes da implementação do CPython:" - -#: ../../tools/templates/dummy.html:7 -msgid "" -"Deprecated since version {deprecated}, will be removed in version {removed}" -msgstr "" -"Descontinuado desde a versão {deprecated}, será removido na versão {removed}" - -#: ../../tools/templates/dummy.html:8 -msgid "Deprecated since version {deprecated}, removed in version {removed}" -msgstr "" -"Descontinuado desde a versão {deprecated}, removido na versão {removed}" +msgid "Availability" +msgstr "Disponibilidade" -#: ../../tools/templates/dummy.html:12 +#: ../../tools/templates/dummy.html:10 msgid "Part of the" msgstr "Parte da" -#: ../../tools/templates/dummy.html:13 +#: ../../tools/templates/dummy.html:11 msgid "Limited API" msgstr "API Limitada" -#: ../../tools/templates/dummy.html:14 +#: ../../tools/templates/dummy.html:12 msgid "Stable ABI" msgstr "ABI Estável" -#: ../../tools/templates/dummy.html:15 +#: ../../tools/templates/dummy.html:13 msgid "(as an opaque struct)" msgstr "(como uma estrutura opaca)" -#: ../../tools/templates/dummy.html:16 +#: ../../tools/templates/dummy.html:14 msgid "(including all members)" msgstr "(incluindo todos os membros)" -#: ../../tools/templates/dummy.html:17 +#: ../../tools/templates/dummy.html:15 msgid "since version %s" msgstr "desde a versão %s" -#: ../../tools/templates/dummy.html:18 +#: ../../tools/templates/dummy.html:16 msgid "(Only some members are part of the stable ABI.)" msgstr "(Somente alguns membros são parte da ABI estável.)" -#: ../../tools/templates/dummy.html:19 +#: ../../tools/templates/dummy.html:17 msgid "This is" msgstr "Esta é uma" -#: ../../tools/templates/dummy.html:20 +#: ../../tools/templates/dummy.html:18 msgid "Unstable API" msgstr "API Instável" -#: ../../tools/templates/dummy.html:21 +#: ../../tools/templates/dummy.html:19 msgid ". It may change without warning in minor releases." msgstr ". Isso pode se alterado sem aviso em lançamentos menores." -#: ../../tools/templates/dummy.html:22 +#: ../../tools/templates/dummy.html:20 msgid "Return value: Always NULL." msgstr "Retorna valor: Sempre NULL." -#: ../../tools/templates/dummy.html:23 +#: ../../tools/templates/dummy.html:21 msgid "Return value: New reference." msgstr "Retorna valor: Nova referência." -#: ../../tools/templates/dummy.html:24 +#: ../../tools/templates/dummy.html:22 msgid "Return value: Borrowed reference." msgstr "Retorna valor: Referência emprestada." -#: ../../tools/templates/dummy.html:28 +#: ../../tools/templates/dummy.html:26 +msgid "CPython implementation detail:" +msgstr "Detalhes da implementação do CPython:" + +#: ../../tools/templates/dummy.html:30 +msgid "" +"Deprecated since version {deprecated}, will be removed in version {removed}" +msgstr "" +"Descontinuado desde a versão {deprecated}, será removido na versão {removed}" + +#: ../../tools/templates/dummy.html:31 +msgid "Deprecated since version {deprecated}, removed in version {removed}" +msgstr "" +"Descontinuado desde a versão {deprecated}, removido na versão {removed}" + +#: ../../tools/templates/dummy.html:35 msgid "in development" msgstr "em desenvolvimento" -#: ../../tools/templates/dummy.html:29 +#: ../../tools/templates/dummy.html:36 msgid "pre-release" msgstr "pré-lançamento" -#: ../../tools/templates/dummy.html:30 +#: ../../tools/templates/dummy.html:37 msgid "stable" msgstr "estável" -#: ../../tools/templates/dummy.html:31 +#: ../../tools/templates/dummy.html:38 msgid "security-fixes" msgstr "correções de segurança" -#: ../../tools/templates/dummy.html:32 +#: ../../tools/templates/dummy.html:39 msgid "EOL" msgstr "EOL (fim de vida)" -#: ../../tools/templates/indexcontent.html:8 +#: ../../tools/templates/indexcontent.html:21 msgid "Welcome! This is the official documentation for Python %(release)s." msgstr "Seja bem-vindo! Esta é a documentação oficial do Python %(release)s." -#: ../../tools/templates/indexcontent.html:10 +#: ../../tools/templates/indexcontent.html:23 msgid "Documentation sections:" msgstr "Seções da documentação:" -#: ../../tools/templates/indexcontent.html:13 +#: ../../tools/templates/indexcontent.html:26 msgid "What's new in Python %(version)s?" msgstr "O que há de novo no Python %(version)s?" -#: ../../tools/templates/indexcontent.html:14 +#: ../../tools/templates/indexcontent.html:27 msgid "" "Or all \"What's new\" documents since Python " "2.0" @@ -339,165 +325,165 @@ msgstr "" "Ou todos os documentos \"O que há de novo\" " "desde o Python 2.0" -#: ../../tools/templates/indexcontent.html:15 +#: ../../tools/templates/indexcontent.html:28 msgid "Tutorial" msgstr "Tutorial" -#: ../../tools/templates/indexcontent.html:16 +#: ../../tools/templates/indexcontent.html:29 msgid "Start here: a tour of Python's syntax and features" msgstr "Comece aqui: um passeio pela sintaxe e pelos recursos do Python" -#: ../../tools/templates/indexcontent.html:17 +#: ../../tools/templates/indexcontent.html:30 msgid "Library reference" msgstr "Referência da biblioteca" -#: ../../tools/templates/indexcontent.html:18 +#: ../../tools/templates/indexcontent.html:31 msgid "Standard library and builtins" msgstr "Biblioteca padrão e embutidos" -#: ../../tools/templates/indexcontent.html:19 +#: ../../tools/templates/indexcontent.html:32 msgid "Language reference" msgstr "Referência da linguagem" -#: ../../tools/templates/indexcontent.html:20 +#: ../../tools/templates/indexcontent.html:33 msgid "Syntax and language elements" msgstr "Sintaxe e elementos da linguagem" -#: ../../tools/templates/indexcontent.html:21 +#: ../../tools/templates/indexcontent.html:34 msgid "Python setup and usage" msgstr "Configurações e uso do Python" -#: ../../tools/templates/indexcontent.html:22 +#: ../../tools/templates/indexcontent.html:35 msgid "How to install, configure, and use Python" msgstr "Como instalar, configurar e usar o Python" -#: ../../tools/templates/indexcontent.html:23 +#: ../../tools/templates/indexcontent.html:36 msgid "Python HOWTOs" msgstr "Python HOWTOs" -#: ../../tools/templates/indexcontent.html:24 +#: ../../tools/templates/indexcontent.html:37 msgid "In-depth topic manuals" msgstr "Manuais de tópicos detalhados" -#: ../../tools/templates/indexcontent.html:26 +#: ../../tools/templates/indexcontent.html:39 msgid "Installing Python modules" msgstr "Instalando módulos Python" -#: ../../tools/templates/indexcontent.html:27 +#: ../../tools/templates/indexcontent.html:40 msgid "Third-party modules and PyPI.org" msgstr "Módulos de terceiros e PyPI.org" -#: ../../tools/templates/indexcontent.html:28 +#: ../../tools/templates/indexcontent.html:41 msgid "Distributing Python modules" msgstr "Distribuindo módulos Python" -#: ../../tools/templates/indexcontent.html:29 +#: ../../tools/templates/indexcontent.html:42 msgid "Publishing modules for use by other people" msgstr "Publicando módulos para uso por outras pessoas" -#: ../../tools/templates/indexcontent.html:30 +#: ../../tools/templates/indexcontent.html:43 msgid "Extending and embedding" msgstr "Estendendo e incorporando" -#: ../../tools/templates/indexcontent.html:31 +#: ../../tools/templates/indexcontent.html:44 msgid "For C/C++ programmers" msgstr "Para programadores de C/C++" -#: ../../tools/templates/indexcontent.html:32 +#: ../../tools/templates/indexcontent.html:45 msgid "Python's C API" msgstr "API C do Python" -#: ../../tools/templates/indexcontent.html:33 +#: ../../tools/templates/indexcontent.html:46 msgid "C API reference" msgstr "Referência da API C" -#: ../../tools/templates/indexcontent.html:34 +#: ../../tools/templates/indexcontent.html:47 msgid "FAQs" msgstr "FAQs" -#: ../../tools/templates/indexcontent.html:35 +#: ../../tools/templates/indexcontent.html:48 msgid "Frequently asked questions (with answers!)" msgstr "Perguntas frequentes (com respostas!)" -#: ../../tools/templates/indexcontent.html:36 +#: ../../tools/templates/indexcontent.html:49 msgid "Deprecations" msgstr "Descontinuações" -#: ../../tools/templates/indexcontent.html:37 +#: ../../tools/templates/indexcontent.html:50 msgid "Deprecated functionality" msgstr "Funcionalidade descontinuada" -#: ../../tools/templates/indexcontent.html:41 +#: ../../tools/templates/indexcontent.html:54 msgid "Indices, glossary, and search:" msgstr "Índices, glossário e pesquisa:" -#: ../../tools/templates/indexcontent.html:44 +#: ../../tools/templates/indexcontent.html:57 msgid "Global module index" msgstr "Índice global de módulos" -#: ../../tools/templates/indexcontent.html:45 +#: ../../tools/templates/indexcontent.html:58 msgid "All modules and libraries" msgstr "Todos os módulos e todas as bibliotecas" -#: ../../tools/templates/indexcontent.html:46 +#: ../../tools/templates/indexcontent.html:59 msgid "General index" msgstr "Índice geral" -#: ../../tools/templates/indexcontent.html:47 +#: ../../tools/templates/indexcontent.html:60 msgid "All functions, classes, and terms" msgstr "Todas funções, classes e termos" -#: ../../tools/templates/indexcontent.html:48 +#: ../../tools/templates/indexcontent.html:61 msgid "Glossary" msgstr "Glossário" -#: ../../tools/templates/indexcontent.html:49 +#: ../../tools/templates/indexcontent.html:62 msgid "Terms explained" msgstr "Termos explicados" -#: ../../tools/templates/indexcontent.html:51 +#: ../../tools/templates/indexcontent.html:64 msgid "Search page" msgstr "Página de busca" -#: ../../tools/templates/indexcontent.html:52 +#: ../../tools/templates/indexcontent.html:65 msgid "Search this documentation" msgstr "Busque nessa documentação" -#: ../../tools/templates/indexcontent.html:53 +#: ../../tools/templates/indexcontent.html:66 msgid "Complete table of contents" msgstr "Conteúdo completo" -#: ../../tools/templates/indexcontent.html:54 +#: ../../tools/templates/indexcontent.html:67 msgid "Lists all sections and subsections" msgstr "Lista todas seções e subseções" -#: ../../tools/templates/indexcontent.html:58 +#: ../../tools/templates/indexcontent.html:71 msgid "Project information:" msgstr "Informações do projeto:" -#: ../../tools/templates/indexcontent.html:61 +#: ../../tools/templates/indexcontent.html:74 msgid "Reporting issues" msgstr "Relatando problemas" -#: ../../tools/templates/indexcontent.html:62 -msgid "Contributing to Docs" -msgstr "Contribuindo para Docs" +#: ../../tools/templates/indexcontent.html:75 +msgid "Contributing to docs" +msgstr "" -#: ../../tools/templates/indexcontent.html:63 +#: ../../tools/templates/indexcontent.html:76 msgid "Download the documentation" msgstr "Baixar a documentação" -#: ../../tools/templates/indexcontent.html:65 +#: ../../tools/templates/indexcontent.html:78 msgid "History and license of Python" msgstr "História e licença do Python" -#: ../../tools/templates/indexcontent.html:66 +#: ../../tools/templates/indexcontent.html:79 msgid "Copyright" msgstr "Direitos autorais" -#: ../../tools/templates/indexcontent.html:67 +#: ../../tools/templates/indexcontent.html:80 msgid "About the documentation" -msgstr "Sobre a Documentação" +msgstr "Sobre a documentação" #: ../../tools/templates/indexsidebar.html:2 msgid "Download these documents" @@ -507,41 +493,33 @@ msgstr "Baixar esses documentos" msgid "Docs by version" msgstr "Documentação por versão" -#: ../../tools/templates/indexsidebar.html:5 -msgid "Stable" -msgstr "Estável" - -#: ../../tools/templates/indexsidebar.html:6 -msgid "In development" -msgstr "Em desenvolvimento" - #: ../../tools/templates/indexsidebar.html:7 msgid "All versions" msgstr "Todas versões" -#: ../../tools/templates/indexsidebar.html:10 +#: ../../tools/templates/indexsidebar.html:9 msgid "Other resources" msgstr "Outros recursos" +#: ../../tools/templates/indexsidebar.html:12 +msgid "PEP index" +msgstr "" + #: ../../tools/templates/indexsidebar.html:13 -msgid "PEP Index" -msgstr "Índice das PEPs" +msgid "Beginner's guide" +msgstr "" #: ../../tools/templates/indexsidebar.html:14 -msgid "Beginner's Guide" -msgstr "Guia do Iniciante" +msgid "Book list" +msgstr "" #: ../../tools/templates/indexsidebar.html:15 -msgid "Book List" -msgstr "Lista de Livros" +msgid "Audio/visual talks" +msgstr "" #: ../../tools/templates/indexsidebar.html:16 -msgid "Audio/Visual Talks" -msgstr "Material Audiovisual" - -#: ../../tools/templates/indexsidebar.html:17 -msgid "Python Developer’s Guide" -msgstr "Guia do Desenvolvedor do Python" +msgid "Python developer’s guide" +msgstr "" #: ../../tools/templates/layout.html:6 msgid "" diff --git a/stats.json b/stats.json new file mode 100644 index 000000000..b717ff908 --- /dev/null +++ b/stats.json @@ -0,0 +1 @@ +{"completion": "61.46%", "translated": 46705, "entries": 75992, "updated_at": "2025-05-25T23:30:17+00:00Z"} \ No newline at end of file diff --git a/tutorial/appendix.po b/tutorial/appendix.po index 133466629..3cc31e84b 100644 --- a/tutorial/appendix.po +++ b/tutorial/appendix.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# msilvavieira, 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -50,8 +48,8 @@ msgid "" "editing, history browsing, and paste mode. To disable color, see :ref:" "`using-on-controlling-color` for details. Function keys provide some " "additional functionality. :kbd:`F1` enters the interactive help browser :mod:" -"`pydoc`. :kbd:`F2` allows for browsing command-line history without output " -"nor the :term:`>>>` and :term:`...` prompts. :kbd:`F3` enters \"paste " +"`pydoc`. :kbd:`F2` allows for browsing command-line history with neither " +"output nor the :term:`>>>` and :term:`...` prompts. :kbd:`F3` enters \"paste " "mode\", which makes pasting larger blocks of code easier. Press :kbd:`F3` to " "return to the regular prompt." msgstr "" @@ -70,7 +68,7 @@ msgid "" "When using the new interactive shell, exit the shell by typing :kbd:`exit` " "or :kbd:`quit`. Adding call parentheses after those commands is not required." msgstr "" -"Ao usar o novo console interativo, saia do shell digitando :kbd:`exit` ou :" +"Ao usar o novo console interativo, saia do console digitando :kbd:`exit` ou :" "kbd:`quit`. Não é necessário adicionar parênteses de chamada após esses " "comandos." @@ -103,12 +101,12 @@ msgstr "" "volta para o prompt primário; se a entrada veio de um arquivo, a execução " "termina com um status de saída *nonzero* (diferente de zero) após a exibição " "do *stack trace*. (Exceções tratadas por uma cláusula :keyword:`except` numa " -"declaração :keyword:`try` não são consideradas erros, nesse contexto.) " -"Alguns erros são irremediavelmente graves e causam términos de execução com " -"status de saída *nonzero*; isso pode acontecer devido a inconsistências " -"internas e em alguns casos por falta de memória. Todas as mensagens de erro " -"são escritas no fluxo de erros padrão; a saída normal resultante da execução " -"de comandos é escrita no canal de saída padrão." +"instrução :keyword:`try` não são consideradas erros, nesse contexto.) Alguns " +"erros são irremediavelmente graves e causam términos de execução com status " +"de saída *nonzero*; isso pode acontecer devido a inconsistências internas e " +"em alguns casos por falta de memória. Todas as mensagens de erro são " +"escritas no fluxo de erros padrão; a saída normal resultante da execução de " +"comandos é escrita no canal de saída padrão." #: ../../tutorial/appendix.rst:50 msgid "" @@ -136,6 +134,10 @@ msgstr "" "Em sistemas Unix similares ao BSD, scripts Python podem ser executados " "diretamente, tal como scripts shell, se tiverem a linha de código ::" +#: ../../tutorial/appendix.rst:65 +msgid "#!/usr/bin/env python3" +msgstr "#!/usr/bin/env python3" + #: ../../tutorial/appendix.rst:67 msgid "" "(assuming that the interpreter is on the user's :envvar:`PATH`) at the " @@ -161,6 +163,10 @@ msgstr "" "O script pode receber a permissão para atuar em modo executável através do " "comando :program:`chmod`." +#: ../../tutorial/appendix.rst:77 +msgid "$ chmod +x myscript.py" +msgstr "$ chmod +x meuscript.py" + #: ../../tutorial/appendix.rst:81 msgid "" "On Windows systems, there is no notion of an \"executable mode\". The " @@ -227,6 +233,22 @@ msgstr "" "exec(open('.pythonrc.py').read())``. Se quiser usar o arquivo de " "inicialização num script, será necessário fazê-lo explicitamente no script::" +#: ../../tutorial/appendix.rst:113 +msgid "" +"import os\n" +"filename = os.environ.get('PYTHONSTARTUP')\n" +"if filename and os.path.isfile(filename):\n" +" with open(filename) as fobj:\n" +" startup_file = fobj.read()\n" +" exec(startup_file)" +msgstr "" +"import os\n" +"filename = os.environ.get('PYTHONSTARTUP')\n" +"if filename and os.path.isfile(filename):\n" +" with open(filename) as fobj:\n" +" startup_file = fobj.read()\n" +" exec(startup_file)" + #: ../../tutorial/appendix.rst:124 msgid "The Customization Modules" msgstr "Módulos de customização" @@ -243,6 +265,16 @@ msgstr "" "primeiro você deve localizar o diretório site-packages do usuário. Inicie o " "Python e execute este código::" +#: ../../tutorial/appendix.rst:130 +msgid "" +">>> import site\n" +">>> site.getusersitepackages()\n" +"'/home/user/.local/lib/python3.x/site-packages'" +msgstr "" +">>> import site\n" +">>> site.getusersitepackages()\n" +"'/home/user/.local/lib/python3.x/site-packages'" + #: ../../tutorial/appendix.rst:134 msgid "" "Now you can create a file named :file:`usercustomize.py` in that directory " diff --git a/tutorial/appetite.po b/tutorial/appetite.po index faf501027..9596b5158 100644 --- a/tutorial/appetite.po +++ b/tutorial/appetite.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Adorilson Bezerra , 2021 -# David Macedo, 2022 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:49+0000\n" -"Last-Translator: David Macedo, 2022\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -37,12 +35,12 @@ msgid "" "of photo files in a complicated way. Perhaps you'd like to write a small " "custom database, or a specialized GUI application, or a simple game." msgstr "" -"Se você trabalha muito com computadores, acabará encontrando alguma tarefa " -"que gostaria de automatizar. Por exemplo, você pode querer fazer busca-e-" -"troca em um grande número de arquivos de texto, ou renomear e reorganizar um " -"monte de arquivos de fotos de uma maneira complicada. Talvez você gostaria " -"de escrever um pequeno banco de dados personalizado, ou um aplicativo GUI " -"especializado, ou um jogo simples." +"Se você trabalha bastante com computadores, eventualmente perceberá que há " +"alguma tarefa que gostaria de automatizar. Por exemplo, pode querer realizar " +"uma busca e substituição em um grande número de arquivos de texto ou " +"renomear e reorganizar um conjunto de fotos de maneira complexa. Talvez " +"deseje criar um pequeno banco de dados personalizado, uma aplicação GUI " +"especializada ou um jogo simples." #: ../../tutorial/appetite.rst:13 msgid "" @@ -76,9 +74,9 @@ msgid "" msgstr "" "Você pode escrever um script shell do Unix ou arquivos batch do Windows para " "algumas dessas tarefas, mas os scripts shell são melhores para mover " -"arquivos e alterar dados de texto, não são adequados para aplicativos GUI ou " +"arquivos e alterar dados de texto, não são adequados para aplicações GUI ou " "jogos. Você pode escrever um programa C/C++/Java, mas pode levar muito tempo " -"de desenvolvimento para obter até mesmo um primeiro rascunho de programa. O " +"de desenvolvimento para obter até mesmo um primeiro rascunho de programa. O " "Python é mais simples de usar, está disponível nos sistemas operacionais " "Windows, macOS e Unix e ajudará você a terminar o trabalho mais rapidamente." @@ -130,7 +128,7 @@ msgid "" msgstr "" "Python é uma linguagem interpretada, por isso você pode economizar um tempo " "considerável durante o desenvolvimento, uma vez que não há necessidade de " -"compilação e vinculação (*linking*). O interpretador pode ser usado " +"compilação e ligação (*linking*). O interpretador pode ser usado " "interativamente, o que torna fácil experimentar diversas características da " "linguagem, escrever programas “descartáveis”, ou testar funções em um " "desenvolvimento debaixo para cima (*bottom-up*). É também uma útil " @@ -177,12 +175,12 @@ msgid "" "extension or command language for that application." msgstr "" "Python é *extensível*: se você sabe como programar em C, é fácil adicionar " -"funções ou módulos diretamente no interpretador, seja para desempenhar " -"operações críticas em máxima velocidade, ou para vincular programas Python a " -"bibliotecas que só estejam disponíveis em formato binário (como uma " -"biblioteca gráfica de terceiros). Uma vez que você tenha sido fisgado, você " -"pode vincular o interpretador Python a uma aplicação escrita em C e utilizá-" -"la como linguagem de comandos ou extensão para esta aplicação." +"módulos ou funções embutidas diretamente no interpretador, seja para " +"desempenhar operações críticas em máxima velocidade, ou para vincular " +"programas Python a bibliotecas que só estejam disponíveis em formato binário " +"(como uma biblioteca gráfica de terceiros). Uma vez que você tenha sido " +"fisgado, você pode vincular o interpretador Python a uma aplicação escrita " +"em C e utilizá-la como linguagem de comandos ou extensão para esta aplicação." #: ../../tutorial/appetite.rst:70 msgid "" @@ -201,9 +199,10 @@ msgid "" "more detail. Since the best way to learn a language is to use it, the " "tutorial invites you to play with the Python interpreter as you read." msgstr "" -"Agora que você está entusiasmado com Python, vai querer conhecê-la com mais " +"Agora que você se entusiasmou com o Python, vai querer conhecê-lo com mais " "detalhes. Partindo do princípio que a melhor maneira de aprender uma " -"linguagem é usando-a, você está agora convidado a fazê-lo com este tutorial." +"linguagem é usando-a, este tutorial lhe convida para fazê-lo com o " +"interpretador do Python enquanto você o lê." #: ../../tutorial/appetite.rst:78 msgid "" @@ -223,6 +222,6 @@ msgid "" "advanced concepts like exceptions and user-defined classes." msgstr "" "O resto do tutorial introduz diversos aspectos do sistema e linguagem Python " -"por intermédio de exemplos. Serão abordadas expressões simples, comandos, " +"por intermédio de exemplos. Serão abordadas expressões simples, instruções, " "tipos, funções e módulos. Finalmente, serão explicados alguns conceitos " "avançados como exceções e classes definidas pelo usuário." diff --git a/tutorial/classes.po b/tutorial/classes.po index 5001a6725..fd5b00ede 100644 --- a/tutorial/classes.po +++ b/tutorial/classes.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Hildeberto Abreu Magalhães , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# msilvavieira, 2021 -# guilhermegouw , 2021 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-20 00:52+0000\n" -"PO-Revision-Date: 2021-06-28 01:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -404,10 +398,70 @@ msgstr "" "espaços de nomes, e como :keyword:`global` e :keyword:`nonlocal` pode afetar " "ligação entre as variáveis::" +#: ../../tutorial/classes.rst:168 +msgid "" +"def scope_test():\n" +" def do_local():\n" +" spam = \"local spam\"\n" +"\n" +" def do_nonlocal():\n" +" nonlocal spam\n" +" spam = \"nonlocal spam\"\n" +"\n" +" def do_global():\n" +" global spam\n" +" spam = \"global spam\"\n" +"\n" +" spam = \"test spam\"\n" +" do_local()\n" +" print(\"After local assignment:\", spam)\n" +" do_nonlocal()\n" +" print(\"After nonlocal assignment:\", spam)\n" +" do_global()\n" +" print(\"After global assignment:\", spam)\n" +"\n" +"scope_test()\n" +"print(\"In global scope:\", spam)" +msgstr "" +"def teste_de_escopo():\n" +" def faz_local():\n" +" spam = \"spam local\"\n" +"\n" +" def faz_nonlocal():\n" +" nonlocal spam\n" +" spam = \"spam não-local\"\n" +"\n" +" def faz_global():\n" +" global spam\n" +" spam = \"spam global\"\n" +"\n" +" spam = \"spam teste\"\n" +" faz_local()\n" +" print(\"Após atribuição local:\", spam)\n" +" faz_nonlocal()\n" +" print(\"Após atribuição não-local:\", spam)\n" +" faz_global()\n" +" print(\"Após atribuição global:\", spam)\n" +"\n" +"teste_de_escopo()\n" +"print(\"No escopo global:\", spam)" + #: ../../tutorial/classes.rst:191 msgid "The output of the example code is:" msgstr "A saída do código de exemplo é:" +#: ../../tutorial/classes.rst:193 +msgid "" +"After local assignment: test spam\n" +"After nonlocal assignment: nonlocal spam\n" +"After global assignment: nonlocal spam\n" +"In global scope: global spam" +msgstr "" +"Após atribuição local: spam teste\n" +"Após atribuição não-local: spam não-local\n" +"Após atribuição global: spam não-local\n" +"No escopo global: spam global" + #: ../../tutorial/classes.rst:200 msgid "" "Note how the *local* assignment (which is default) didn't change " @@ -416,9 +470,9 @@ msgid "" "assignment changed the module-level binding." msgstr "" "Observe como uma atribuição *local* (que é o padrão) não altera o vínculo de " -"*scope_test* a *spam*. A instrução :keyword:`nonlocal` mudou o vínculo de " -"*scope_test* de *spam* e a atribuição :keyword:`global` alterou a ligação " -"para o nível do módulo." +"*teste_de_escopo* a *spam*. A instrução :keyword:`nonlocal` mudou o vínculo " +"de *teste_de_escopo* de *spam* e a atribuição :keyword:`global` alterou a " +"ligação para o nível do módulo." #: ../../tutorial/classes.rst:205 msgid "" @@ -448,6 +502,22 @@ msgstr "Sintaxe da definição de classe" msgid "The simplest form of class definition looks like this::" msgstr "A forma mais simples de definir uma classe é::" +#: ../../tutorial/classes.rst:225 +msgid "" +"class ClassName:\n" +" \n" +" .\n" +" .\n" +" .\n" +" " +msgstr "" +"class NomeClasse:\n" +" \n" +" .\n" +" .\n" +" .\n" +" " + #: ../../tutorial/classes.rst:232 msgid "" "Class definitions, like function definitions (:keyword:`def` statements) " @@ -502,11 +572,11 @@ msgstr "" "nomes criado pela definição da classe; aprenderemos mais sobre objetos " "classe na próxima seção. O escopo local (que estava vigente antes da " "definição da classe) é reativado, e o objeto classe é vinculado ao " -"identificador da classe nesse escopo (:class:`!ClassName` no exemplo)." +"identificador da classe nesse escopo (:class:`!NomeClasse` no exemplo)." #: ../../tutorial/classes.rst:259 msgid "Class Objects" -msgstr "Objetos de Class" +msgstr "Objetos classe" #: ../../tutorial/classes.rst:261 msgid "" @@ -529,19 +599,36 @@ msgstr "" "classe, quando o objeto classe foi criado. Portanto, se a definição de " "classe tem esta forma::" +#: ../../tutorial/classes.rst:269 +msgid "" +"class MyClass:\n" +" \"\"\"A simple example class\"\"\"\n" +" i = 12345\n" +"\n" +" def f(self):\n" +" return 'hello world'" +msgstr "" +"class MinhaClasse:\n" +" \"\"\"Um exemplo de classe simples\"\"\"\n" +" i = 12345\n" +"\n" +" def f(self):\n" +" return 'olá mundo'" + #: ../../tutorial/classes.rst:276 msgid "" "then ``MyClass.i`` and ``MyClass.f`` are valid attribute references, " "returning an integer and a function object, respectively. Class attributes " "can also be assigned to, so you can change the value of ``MyClass.i`` by " -"assignment. :attr:`!__doc__` is also a valid attribute, returning the " +"assignment. :attr:`~type.__doc__` is also a valid attribute, returning the " "docstring belonging to the class: ``\"A simple example class\"``." msgstr "" -"então ``MyClass.i`` e ``MyClass.f`` são referências a atributo válidas, " -"retornando, respectivamente, um inteiro e um objeto função. Atributos de " -"classe podem receber valores, pode-se modificar o valor de ``MyClass.i`` num " -"atribuição. :attr:`!__doc__` também é um atributo válido da classe, " -"retornando a docstring associada à classe: ``\"A simple example class\"``." +"então ``MinhaClasse.i`` e ``MinhaClasse.f`` são referências a atributo " +"válidas, retornando, respectivamente, um inteiro e um objeto função. " +"Atributos de classe podem receber valores, pode-se modificar o valor de " +"``MinhaClasse.i`` num atribuição. :attr:`~type.__doc__` também é um atributo " +"válido da classe, retornando a docstring associada à classe: ``\"Um exemplo " +"de classe simples\"``." #: ../../tutorial/classes.rst:282 msgid "" @@ -554,6 +641,10 @@ msgstr "" "devolve uma nova instância da classe. Por exemplo (presumindo a classe " "acima)::" +#: ../../tutorial/classes.rst:286 ../../tutorial/classes.rst:303 +msgid "x = MyClass()" +msgstr "x = MinhaClasse()" + #: ../../tutorial/classes.rst:288 msgid "" "creates a new *instance* of the class and assigns this object to the local " @@ -574,6 +665,14 @@ msgstr "" "predeterminado. Para tanto, a classe pode definir um método especial " "chamado :meth:`~object.__init__`, assim::" +#: ../../tutorial/classes.rst:296 +msgid "" +"def __init__(self):\n" +" self.data = []" +msgstr "" +"def __init__(self):\n" +" self.data = []" + #: ../../tutorial/classes.rst:299 msgid "" "When a class defines an :meth:`~object.__init__` method, class instantiation " @@ -596,6 +695,26 @@ msgstr "" "maior flexibilidade. Neste caso, os argumentos fornecidos na invocação da " "classe serão passados para o método :meth:`!__init__`. Por exemplo, ::" +#: ../../tutorial/classes.rst:309 +msgid "" +">>> class Complex:\n" +"... def __init__(self, realpart, imagpart):\n" +"... self.r = realpart\n" +"... self.i = imagpart\n" +"...\n" +">>> x = Complex(3.0, -4.5)\n" +">>> x.r, x.i\n" +"(3.0, -4.5)" +msgstr "" +">>> class Complex:\n" +"... def __init__(self, realpart, imagpart):\n" +"... self.r = realpart\n" +"... self.i = imagpart\n" +"...\n" +">>> x = Complex(3.0, -4.5)\n" +">>> x.r, x.i\n" +"(3.0, -4.5)" + #: ../../tutorial/classes.rst:322 msgid "Instance Objects" msgstr "Objetos instância" @@ -624,8 +743,22 @@ msgstr "" "a \"membros de dados\" em C++. Atributos de dados não precisam ser " "declarados. Assim como variáveis locais, eles passam a existir na primeira " "vez em que é feita uma atribuição. Por exemplo, se ``x`` é uma instância da :" -"class:`!MyClass` criada acima, o próximo trecho de código irá exibir o valor " -"``16``, sem deixar nenhum rastro::" +"class:`!MinhaClasse` criada acima, o próximo trecho de código irá exibir o " +"valor ``16``, sem deixar nenhum rastro::" + +#: ../../tutorial/classes.rst:334 +msgid "" +"x.counter = 1\n" +"while x.counter < 10:\n" +" x.counter = x.counter * 2\n" +"print(x.counter)\n" +"del x.counter" +msgstr "" +"x.contador = 1\n" +"while x.contador < 10:\n" +" x.contador = x.contador * 2\n" +"print(x.contador)\n" +"del x.contador" #: ../../tutorial/classes.rst:340 msgid "" @@ -647,10 +780,10 @@ msgstr "" "Nomes de métodos válidos de uma instância dependem de sua classe. Por " "definição, cada atributo de uma classe que é uma função corresponde a um " "método das instâncias. Em nosso exemplo, ``x.f`` é uma referência de método " -"válida já que ``MyClass.f`` é uma função, enquanto ``x.i`` não é, já que " -"``MyClass.i`` não é uma função. Entretanto, ``x.f`` não é o mesmo que " -"``MyClass.f``. A referência ``x.f`` acessa um objeto método e a ``MyClass." -"f`` acessa um objeto função." +"válida já que ``MinhaClasse.f`` é uma função, enquanto ``x.i`` não é, já que " +"``MinhaClasse.i`` não é uma função. Entretanto, ``x.f`` não é o mesmo que " +"``MinhaClasse.f``. A referência ``x.f`` acessa um objeto método e a " +"``MinhaClasse.f`` acessa um objeto função." #: ../../tutorial/classes.rst:356 msgid "Method Objects" @@ -660,6 +793,10 @@ msgstr "Objetos método" msgid "Usually, a method is called right after it is bound::" msgstr "Normalmente, um método é chamado imediatamente após ser referenciado::" +#: ../../tutorial/classes.rst:360 +msgid "x.f()" +msgstr "x.f()" + #: ../../tutorial/classes.rst:362 msgid "" "In the :class:`!MyClass` example, this will return the string ``'hello " @@ -667,14 +804,24 @@ msgid "" "is a method object, and can be stored away and called at a later time. For " "example::" msgstr "" -"No exemplo :class:`!MyClass`, o resultado da expressão acima será a string " -"``'hello world'``. No entanto, não é obrigatório invocar o método " +"No exemplo :class:`!MinhaClasse`, o resultado da expressão acima será a " +"string ``\"olá mundo\"``. No entanto, não é obrigatório invocar o método " "imediatamente: como ``x.f`` é também um objeto ele pode ser atribuído a uma " "variável e invocado depois. Por exemplo::" +#: ../../tutorial/classes.rst:366 +msgid "" +"xf = x.f\n" +"while True:\n" +" print(xf())" +msgstr "" +"xf = x.f\n" +"while True:\n" +" print(xf())" + #: ../../tutorial/classes.rst:370 msgid "will continue to print ``hello world`` until the end of time." -msgstr "exibirá o texto ``hello world`` até o mundo acabar." +msgstr "exibirá o texto ``olá mundo`` até o mundo acabar." #: ../../tutorial/classes.rst:372 msgid "" @@ -704,7 +851,7 @@ msgid "" msgstr "" "Na verdade, pode-se supor a resposta: a particularidade sobre os métodos é " "que o objeto da instância é passado como o primeiro argumento da função. Em " -"nosso exemplo, a chamada ``x.f()`` é exatamente equivalente a ``MyClass." +"nosso exemplo, a chamada ``x.f()`` é exatamente equivalente a ``MinhaClasse." "f(x)``. Em geral, chamar um método com uma lista de *n* argumentos é " "equivalente a chamar a função correspondente com uma lista de argumentos que " "é criada inserindo o objeto de instância do método antes do primeiro " @@ -744,6 +891,46 @@ msgstr "" "de atributos e de métodos que são comuns a todas as instâncias de uma " "classe::" +#: ../../tutorial/classes.rst:404 +msgid "" +"class Dog:\n" +"\n" +" kind = 'canine' # class variable shared by all instances\n" +"\n" +" def __init__(self, name):\n" +" self.name = name # instance variable unique to each instance\n" +"\n" +">>> d = Dog('Fido')\n" +">>> e = Dog('Buddy')\n" +">>> d.kind # shared by all dogs\n" +"'canine'\n" +">>> e.kind # shared by all dogs\n" +"'canine'\n" +">>> d.name # unique to d\n" +"'Fido'\n" +">>> e.name # unique to e\n" +"'Buddy'" +msgstr "" +"class Cachorro:\n" +"\n" +" tipo = 'canino' # variável de classe compartilhada por todas as " +"instâncias\n" +"\n" +" def __init__(self, nome):\n" +" self.nome = nome # variável de instância única para cada " +"instância\n" +"\n" +">>> d = Cachorro('Fido')\n" +">>> e = Cachorro('Buddy')\n" +">>> d.tipo # compartilhada por todos os cachorros\n" +"'canino'\n" +">>> e.tipo # compartilhada por todos os cachorros\n" +"'canino'\n" +">>> d.nome # exclusiva do d\n" +"'Fido'\n" +">>> e.nome # exclusiva do e\n" +"'Buddy'" + #: ../../tutorial/classes.rst:422 msgid "" "As discussed in :ref:`tut-object`, shared data can have possibly surprising " @@ -753,10 +940,47 @@ msgid "" "by all *Dog* instances::" msgstr "" "Como vimos em :ref:`tut-object`, dados compartilhados podem causar efeitos " -"inesperados quando envolvem objetos (:term:`mutáveis `), como " +"inesperados quando envolvem objetos (:term:`mutáveis `), como " "listas ou dicionários. Por exemplo, a lista *tricks* do código abaixo não " "deve ser usada como variável de classe, pois assim seria compartilhada por " -"todas as instâncias de *Dog*::" +"todas as instâncias de *Cachorro*::" + +#: ../../tutorial/classes.rst:428 +msgid "" +"class Dog:\n" +"\n" +" tricks = [] # mistaken use of a class variable\n" +"\n" +" def __init__(self, name):\n" +" self.name = name\n" +"\n" +" def add_trick(self, trick):\n" +" self.tricks.append(trick)\n" +"\n" +">>> d = Dog('Fido')\n" +">>> e = Dog('Buddy')\n" +">>> d.add_trick('roll over')\n" +">>> e.add_trick('play dead')\n" +">>> d.tricks # unexpectedly shared by all dogs\n" +"['roll over', 'play dead']" +msgstr "" +"class Cachorro:\n" +"\n" +" truques = [] # uso incorreto de uma variável de classe\n" +"\n" +" def __init__(self, nome):\n" +" self.nome = nome\n" +"\n" +" def adicionar_truque(self, truque):\n" +" self.truques.append(truque)\n" +"\n" +">>> d = Cachorro('Fido')\n" +">>> e = Cachorro('Buddy')\n" +">>> d.adicionar_truque('rolar')\n" +">>> e.adicionar_truque('fingir de morto')\n" +">>> d.truques # inesperadamente compartilhado por todos os " +"cães\n" +"['rolar', 'fingir de morto']" #: ../../tutorial/classes.rst:445 msgid "Correct design of the class should use an instance variable instead::" @@ -764,6 +988,44 @@ msgstr "" "Em vez disso, o modelo correto da classe deve usar uma variável de " "instância::" +#: ../../tutorial/classes.rst:447 +msgid "" +"class Dog:\n" +"\n" +" def __init__(self, name):\n" +" self.name = name\n" +" self.tricks = [] # creates a new empty list for each dog\n" +"\n" +" def add_trick(self, trick):\n" +" self.tricks.append(trick)\n" +"\n" +">>> d = Dog('Fido')\n" +">>> e = Dog('Buddy')\n" +">>> d.add_trick('roll over')\n" +">>> e.add_trick('play dead')\n" +">>> d.tricks\n" +"['roll over']\n" +">>> e.tricks\n" +"['play dead']" +msgstr "" +"class Cachorro:\n" +"\n" +" def __init__(self, nome):\n" +" self.nome = nome\n" +" self.truques = [] # cria uma nova lista vazia para cada cachorro\n" +"\n" +" def adicionar_truque(self, truque):\n" +" self.truques.append(truque)\n" +"\n" +">>> d = Cachorro('Fido')\n" +">>> e = Cachorro('Buddy')\n" +">>> d.adicionar_truque('rolar')\n" +">>> e.adicionar_truque('fingir de morto')\n" +">>> d.truques\n" +"['rolar']\n" +">>> e.truques\n" +"['fingir de morto']" + #: ../../tutorial/classes.rst:469 msgid "Random Remarks" msgstr "Observações aleatórias" @@ -776,6 +1038,32 @@ msgstr "" "Se um mesmo nome de atributo ocorre tanto na instância quanto na classe, a " "busca pelo atributo prioriza a instância::" +#: ../../tutorial/classes.rst:476 +msgid "" +">>> class Warehouse:\n" +"... purpose = 'storage'\n" +"... region = 'west'\n" +"...\n" +">>> w1 = Warehouse()\n" +">>> print(w1.purpose, w1.region)\n" +"storage west\n" +">>> w2 = Warehouse()\n" +">>> w2.region = 'east'\n" +">>> print(w2.purpose, w2.region)\n" +"storage east" +msgstr "" +">>> class Armazém:\n" +"... propósito = 'armazenar'\n" +"... região = 'oeste'\n" +"...\n" +">>> a1 = Armazém()\n" +">>> print(a1.propósito, a1.região)\n" +"armazenar oeste\n" +">>> a2 = Armazém()\n" +">>> a2.região = 'leste'\n" +">>> print(a2.propósito, a2.região)\n" +"armazenar leste" + #: ../../tutorial/classes.rst:488 msgid "" "Data attributes may be referenced by methods as well as by ordinary users " @@ -850,6 +1138,32 @@ msgstr "" "esteja textualmente embutida na definição da classe. Atribuir um objeto " "função a uma variável local da classe é válido. Por exemplo::" +#: ../../tutorial/classes.rst:518 +msgid "" +"# Function defined outside the class\n" +"def f1(self, x, y):\n" +" return min(x, x+y)\n" +"\n" +"class C:\n" +" f = f1\n" +"\n" +" def g(self):\n" +" return 'hello world'\n" +"\n" +" h = g" +msgstr "" +"# Função definida fora da classe\n" +"def f1(self, x, y):\n" +" return min(x, x+y)\n" +"\n" +"class C:\n" +" f = f1\n" +"\n" +" def g(self):\n" +" return 'olá mundo'\n" +"\n" +" h = g" + #: ../../tutorial/classes.rst:530 msgid "" "Now ``f``, ``g`` and ``h`` are all attributes of class :class:`!C` that " @@ -870,6 +1184,30 @@ msgstr "" "Métodos podem invocar outros métodos usando atributos de método do argumento " "``self``::" +#: ../../tutorial/classes.rst:538 +msgid "" +"class Bag:\n" +" def __init__(self):\n" +" self.data = []\n" +"\n" +" def add(self, x):\n" +" self.data.append(x)\n" +"\n" +" def addtwice(self, x):\n" +" self.add(x)\n" +" self.add(x)" +msgstr "" +"class Bolsa:\n" +" def __init__(self):\n" +" self.data = []\n" +"\n" +" def adicionar(self, x):\n" +" self.data.append(x)\n" +"\n" +" def adicionar_em_dobro(self, x):\n" +" self.adicionar(x)\n" +" self.adicionar(x)" + #: ../../tutorial/classes.rst:549 msgid "" "Methods may reference global names in the same way as ordinary functions. " @@ -915,6 +1253,22 @@ msgstr "" "\"classe\" se não suportasse herança. A sintaxe para uma classe derivada é " "assim::" +#: ../../tutorial/classes.rst:572 +msgid "" +"class DerivedClassName(BaseClassName):\n" +" \n" +" .\n" +" .\n" +" .\n" +" " +msgstr "" +"class NomeClasseDerivada(NomeClasseBase):\n" +" \n" +" .\n" +" .\n" +" .\n" +" " + #: ../../tutorial/classes.rst:579 msgid "" "The name :class:`!BaseClassName` must be defined in a namespace accessible " @@ -927,6 +1281,10 @@ msgstr "" "lugar do nome da classe base, também são aceitas outras expressões. Isso é " "muito útil, por exemplo, quando a classe base é definida em outro módulo::" +#: ../../tutorial/classes.rst:585 +msgid "class DerivedClassName(modname.BaseClassName):" +msgstr "class NomeClasseDerivada(nomemódulo.NomeClasseBase):" + #: ../../tutorial/classes.rst:587 msgid "" "Execution of a derived class definition proceeds the same as for a base " @@ -952,7 +1310,7 @@ msgid "" "method reference is valid if this yields a function object." msgstr "" "Não há nada de especial sobre instanciação de classes derivadas: " -"``DerivedClassName()`` cria uma nova instância da classe. Referências a " +"``NomeClasseDerivada()`` cria uma nova instância da classe. Referências a " "métodos são resolvidas da seguinte forma: o atributo correspondente é " "procurado através da cadeia de classes base, e referências a métodos são " "válidas se essa procura produzir um objeto função." @@ -1026,6 +1384,22 @@ msgstr "" "Python também suporta uma forma de herança múltipla. Uma definição de classe " "com várias classes bases tem esta forma::" +#: ../../tutorial/classes.rst:633 +msgid "" +"class DerivedClassName(Base1, Base2, Base3):\n" +" \n" +" .\n" +" .\n" +" .\n" +" " +msgstr "" +"class NomeClasseDerivada(Base1, Base2, Base3):\n" +" \n" +" .\n" +" .\n" +" .\n" +" " + #: ../../tutorial/classes.rst:640 msgid "" "For most purposes, in the simplest cases, you can think of the search for " @@ -1100,7 +1474,7 @@ msgid "" "a function, a method or a data member). It should be considered an " "implementation detail and subject to change without notice." msgstr "" -"Variáveis de instância \"privadas\", que não podem ser acessadas, ​​exceto em " +"Variáveis de instância \"privadas\", que não podem ser acessadas, exceto em " "métodos do próprio objeto, não existem em Python. No entanto, existe uma " "convenção que é seguida pela maioria dos programas em Python: um nome " "prefixado com um sublinhado (por exemplo: ``_spam`` ) deve ser tratado como " @@ -1147,6 +1521,47 @@ msgstr "" "métodos sem quebrar invocações de métodos dentro de outra classe. Por " "exemplo::" +#: ../../tutorial/classes.rst:699 +msgid "" +"class Mapping:\n" +" def __init__(self, iterable):\n" +" self.items_list = []\n" +" self.__update(iterable)\n" +"\n" +" def update(self, iterable):\n" +" for item in iterable:\n" +" self.items_list.append(item)\n" +"\n" +" __update = update # private copy of original update() method\n" +"\n" +"class MappingSubclass(Mapping):\n" +"\n" +" def update(self, keys, values):\n" +" # provides new signature for update()\n" +" # but does not break __init__()\n" +" for item in zip(keys, values):\n" +" self.items_list.append(item)" +msgstr "" +"class Mapeamento:\n" +" def __init__(self, iterável):\n" +" self.lista_itens = []\n" +" self.__atualizar(iterável)\n" +"\n" +" def atualizar(self, iterável):\n" +" for item in iterável:\n" +" self.lista_itens.append(item)\n" +"\n" +" __atualizar = atualizar # cópia privada do método atualizar() " +"original\n" +"\n" +"class SubclasseMapeamento(Mapeamento):\n" +"\n" +" def update(self, chaves, valores):\n" +" # fornece nova assinatura para atualizar(),\n" +" # mas não quebra __init__()\n" +" for item in zip(chaves, valores):\n" +" self.lista_itens.append(item)" + #: ../../tutorial/classes.rst:718 msgid "" "The above example would work even if ``MappingSubclass`` were to introduce a " @@ -1154,10 +1569,11 @@ msgid "" "the ``Mapping`` class and ``_MappingSubclass__update`` in the " "``MappingSubclass`` class respectively." msgstr "" -"O exemplo acima deve funcionar mesmo se ``MappingSubclass`` introduzisse um " -"identificador ``__update`` uma vez que é substituído por " -"``_Mapping__update`` na classe ``Mapping`` e ``_MappingSubclass__update`` na " -"classe ``MappingSubclass``, respectivamente." +"O exemplo acima deve funcionar mesmo se ``SubclasseMapeamento`` introduzisse " +"um identificador ``__atualizar`` uma vez que é substituído por " +"``_Mapeamento__atualizar`` na classe ``Mapeamento`` e " +"``_SubclasseMapeamento__atualizar`` na classe ``SubclasseMapeamento``, " +"respectivamente." #: ../../tutorial/classes.rst:723 msgid "" @@ -1201,6 +1617,38 @@ msgstr "" "\"struct\" de C, para agrupar alguns itens de dados. A maneira pythônica " "para este fim é usar :mod:`dataclasses`::" +#: ../../tutorial/classes.rst:744 +msgid "" +"from dataclasses import dataclass\n" +"\n" +"@dataclass\n" +"class Employee:\n" +" name: str\n" +" dept: str\n" +" salary: int" +msgstr "" +"from dataclasses import dataclass\n" +"\n" +"@dataclass\n" +"class Empregado:\n" +" nome: str\n" +" dept: str\n" +" salário: int" + +#: ../../tutorial/classes.rst:754 +msgid "" +">>> john = Employee('john', 'computer lab', 1000)\n" +">>> john.dept\n" +"'computer lab'\n" +">>> john.salary\n" +"1000" +msgstr "" +">>> joão = Empregado('joão', 'lab de computadores', 1000)\n" +">>> joão.dept\n" +"'lab de computadores'\n" +">>> joão.salário\n" +"1000" + #: ../../tutorial/classes.rst:760 msgid "" "A piece of Python code that expects a particular abstract data type can " @@ -1241,6 +1689,30 @@ msgstr "" "Você já deve ter notado que pode usar laços :keyword:`for` com a maioria das " "coleções em Python::" +#: ../../tutorial/classes.rst:787 +msgid "" +"for element in [1, 2, 3]:\n" +" print(element)\n" +"for element in (1, 2, 3):\n" +" print(element)\n" +"for key in {'one':1, 'two':2}:\n" +" print(key)\n" +"for char in \"123\":\n" +" print(char)\n" +"for line in open(\"myfile.txt\"):\n" +" print(line, end='')" +msgstr "" +"for elemento in [1, 2, 3]:\n" +" print(elemento)\n" +"for elemento in (1, 2, 3):\n" +" print(elemento)\n" +"for chave in {'um':1, 'dois':2}:\n" +" print(chave)\n" +"for char in \"123\":\n" +" print(char)\n" +"for linha in open(\"meuarquivo.txt\"):\n" +" print(linha, end='')" + #: ../../tutorial/classes.rst:798 msgid "" "This style of access is clear, concise, and convenient. The use of " @@ -1263,6 +1735,40 @@ msgstr "" "usando a função embutida :func:`next`; este exemplo mostra como tudo " "funciona::" +#: ../../tutorial/classes.rst:807 +msgid "" +">>> s = 'abc'\n" +">>> it = iter(s)\n" +">>> it\n" +"\n" +">>> next(it)\n" +"'a'\n" +">>> next(it)\n" +"'b'\n" +">>> next(it)\n" +"'c'\n" +">>> next(it)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" next(it)\n" +"StopIteration" +msgstr "" +">>> s = 'abc'\n" +">>> it = iter(s)\n" +">>> it\n" +"\n" +">>> next(it)\n" +"'a'\n" +">>> next(it)\n" +"'b'\n" +">>> next(it)\n" +"'c'\n" +">>> next(it)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" next(it)\n" +"StopIteration" + #: ../../tutorial/classes.rst:823 msgid "" "Having seen the mechanics behind the iterator protocol, it is easy to add " @@ -1277,6 +1783,63 @@ msgstr "" "`~iterator.__next__`. Se uma classe já define :meth:`!__next__`, então :meth:" "`!__iter__` pode simplesmente retornar ``self``::" +#: ../../tutorial/classes.rst:828 +msgid "" +"class Reverse:\n" +" \"\"\"Iterator for looping over a sequence backwards.\"\"\"\n" +" def __init__(self, data):\n" +" self.data = data\n" +" self.index = len(data)\n" +"\n" +" def __iter__(self):\n" +" return self\n" +"\n" +" def __next__(self):\n" +" if self.index == 0:\n" +" raise StopIteration\n" +" self.index = self.index - 1\n" +" return self.data[self.index]" +msgstr "" +"class Inverter:\n" +" \"\"\"Iterador para fazer um laço em uma sequência de trás para frente." +"\"\"\"\n" +" def __init__(self, dados):\n" +" self.dados = dados\n" +" self.índice = len(dados)\n" +"\n" +" def __iter__(self):\n" +" return self\n" +"\n" +" def __next__(self):\n" +" if self.índice == 0:\n" +" raise StopIteration\n" +" self.índice = self.índice - 1\n" +" return self.dados[self.índice]" + +#: ../../tutorial/classes.rst:845 +msgid "" +">>> rev = Reverse('spam')\n" +">>> iter(rev)\n" +"<__main__.Reverse object at 0x00A1DB50>\n" +">>> for char in rev:\n" +"... print(char)\n" +"...\n" +"m\n" +"a\n" +"p\n" +"s" +msgstr "" +">>> rev = Interverter('spam')\n" +">>> iter(rev)\n" +"<__main__.Interverter object at 0x00A1DB50>\n" +">>> for char in rev:\n" +"... print(char)\n" +"...\n" +"m\n" +"a\n" +"p\n" +"s" + #: ../../tutorial/classes.rst:860 msgid "Generators" msgstr "Geradores" @@ -1297,6 +1860,34 @@ msgstr "" "dados e qual instrução foi executada pela última vez). Um exemplo mostra " "como geradores podem ser trivialmente fáceis de criar::" +#: ../../tutorial/classes.rst:869 +msgid "" +"def reverse(data):\n" +" for index in range(len(data)-1, -1, -1):\n" +" yield data[index]" +msgstr "" +"def inverter(dados):\n" +" for índice in range(len(dados)-1, -1, -1):\n" +" yield dados[índice]" + +#: ../../tutorial/classes.rst:875 +msgid "" +">>> for char in reverse('golf'):\n" +"... print(char)\n" +"...\n" +"f\n" +"l\n" +"o\n" +"g" +msgstr "" +">>> for char in inverter('golf'):\n" +"... print(char)\n" +"...\n" +"f\n" +"l\n" +"o\n" +"g" + #: ../../tutorial/classes.rst:883 msgid "" "Anything that can be done with generators can also be done with class-based " @@ -1357,6 +1948,43 @@ msgstr "" msgid "Examples::" msgstr "Exemplos::" +#: ../../tutorial/classes.rst:913 +msgid "" +">>> sum(i*i for i in range(10)) # sum of squares\n" +"285\n" +"\n" +">>> xvec = [10, 20, 30]\n" +">>> yvec = [7, 5, 3]\n" +">>> sum(x*y for x,y in zip(xvec, yvec)) # dot product\n" +"260\n" +"\n" +">>> unique_words = set(word for line in page for word in line.split())\n" +"\n" +">>> valedictorian = max((student.gpa, student.name) for student in " +"graduates)\n" +"\n" +">>> data = 'golf'\n" +">>> list(data[i] for i in range(len(data)-1, -1, -1))\n" +"['f', 'l', 'o', 'g']" +msgstr "" +">>> sum(i*i for i in range(10)) # soma dos quadrados\n" +"285\n" +"\n" +">>> xvec = [10, 20, 30]\n" +">>> yvec = [7, 5, 3]\n" +">>> sum(x*y for x,y in zip(xvec, yvec)) # produto escalar\n" +"260\n" +"\n" +">>> palavras_únicas = set(palavra for linha página for palavra in linha." +"split())\n" +"\n" +">>> orador_da_turma = max((estudante.gpa, estudante.nome) for estudante in " +"graduados)\n" +"\n" +">>> dados = 'golf'\n" +">>> list(dados[i] for i in range(len(dados)-1, -1, -1))\n" +"['f', 'l', 'o', 'g']" + #: ../../tutorial/classes.rst:932 msgid "Footnotes" msgstr "Notas de rodapé" @@ -1365,17 +1993,17 @@ msgstr "Notas de rodapé" msgid "" "Except for one thing. Module objects have a secret read-only attribute " "called :attr:`~object.__dict__` which returns the dictionary used to " -"implement the module's namespace; the name :attr:`~object.__dict__` is an " -"attribute but not a global name. Obviously, using this violates the " -"abstraction of namespace implementation, and should be restricted to things " -"like post-mortem debuggers." +"implement the module's namespace; the name ``__dict__`` is an attribute but " +"not a global name. Obviously, using this violates the abstraction of " +"namespace implementation, and should be restricted to things like post-" +"mortem debuggers." msgstr "" "Exceto por uma coisa. Os objetos módulo têm um atributo secreto e somente " "para leitura chamado :attr:`~object.__dict__` que retorna o dicionário usado " -"para implementar o espaço de nomes do módulo; o nome :attr:`~object." -"__dict__` é um atributo, mas não um nome global. Obviamente, usar isso viola " -"a abstração da implementação do espaço de nomes, e deve ser restrito a " -"coisas como depuradores post-mortem." +"para implementar o espaço de nomes do módulo; o nome ``__dict__`` é um " +"atributo, mas não um nome global. Obviamente, usar isso viola a abstração da " +"implementação do espaço de nomes, e deve ser restrito a coisas como " +"depuradores post-mortem." #: ../../tutorial/classes.rst:343 msgid "object" diff --git a/tutorial/controlflow.po b/tutorial/controlflow.po index 24a84f2b4..8a9b62d63 100644 --- a/tutorial/controlflow.po +++ b/tutorial/controlflow.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2021 -# Alexandre B A Villares, 2021 -# Vinicius Gubiani Ferreira , 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# Octavio von Sydow , 2023 -# Adorilson Bezerra , 2023 -# Rafael Fontenelle , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2023\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -43,16 +37,46 @@ msgstr "" #: ../../tutorial/controlflow.rst:14 msgid ":keyword:`!if` Statements" -msgstr "Comandos :keyword:`!if`" +msgstr "Instruções :keyword:`!if`" #: ../../tutorial/controlflow.rst:16 msgid "" "Perhaps the most well-known statement type is the :keyword:`if` statement. " "For example::" msgstr "" -"Provavelmente o mais conhecido comando de controle de fluxo é o :keyword:" +"Provavelmente a mais conhecida instrução de controle de fluxo é o :keyword:" "`if`. Por exemplo::" +#: ../../tutorial/controlflow.rst:19 +msgid "" +">>> x = int(input(\"Please enter an integer: \"))\n" +"Please enter an integer: 42\n" +">>> if x < 0:\n" +"... x = 0\n" +"... print('Negative changed to zero')\n" +"... elif x == 0:\n" +"... print('Zero')\n" +"... elif x == 1:\n" +"... print('Single')\n" +"... else:\n" +"... print('More')\n" +"...\n" +"More" +msgstr "" +">>> x = int(input(\"Insira um número inteiro: \"))\n" +"Insira um número inteiro: 42\n" +">>> if x < 0:\n" +"... x = 0\n" +"... print('Negativo alterado para zero')\n" +"... elif x == 0:\n" +"... print('Zero')\n" +"... elif x == 1:\n" +"... print('Um')\n" +"... else:\n" +"... print('Mais')\n" +"...\n" +"Mais" + #: ../../tutorial/controlflow.rst:33 msgid "" "There can be zero or more :keyword:`elif` parts, and the :keyword:`else` " @@ -64,7 +88,7 @@ msgstr "" "Pode haver zero ou mais partes :keyword:`elif`, e a parte :keyword:`else` é " "opcional. A palavra-chave ':keyword:`!elif`' é uma abreviação para 'else " "if', e é útil para evitar indentação excessiva. Uma sequência :keyword:`!" -"if` ... :keyword:`!elif` ... :keyword:`!elif` ... substitui os comandos " +"if` ... :keyword:`!elif` ... :keyword:`!elif` ... substitui as instruções " "``switch`` ou ``case``, encontrados em outras linguagens." #: ../../tutorial/controlflow.rst:39 @@ -79,7 +103,7 @@ msgstr "" #: ../../tutorial/controlflow.rst:46 msgid ":keyword:`!for` Statements" -msgstr "Comandos :keyword:`!for`" +msgstr "Instruções :keyword:`!for`" #: ../../tutorial/controlflow.rst:51 msgid "" @@ -91,13 +115,33 @@ msgid "" "a string), in the order that they appear in the sequence. For example (no " "pun intended):" msgstr "" -"O comando :keyword:`for` em Python é um pouco diferente do que costuma ser " +"A instrução :keyword:`for` em Python é um pouco diferente do que costuma ser " "em C ou Pascal. Ao invés de sempre iterar sobre uma progressão aritmética de " "números (como no Pascal), ou permitir ao usuário definir o passo de iteração " -"e a condição de parada (como C), o comando :keyword:`!for` do Python itera " +"e a condição de parada (como C), a instrução :keyword:`!for` do Python itera " "sobre os itens de qualquer sequência (seja uma lista ou uma string), na " "ordem que aparecem na sequência. Por exemplo:" +#: ../../tutorial/controlflow.rst:63 +msgid "" +">>> # Measure some strings:\n" +">>> words = ['cat', 'window', 'defenestrate']\n" +">>> for w in words:\n" +"... print(w, len(w))\n" +"...\n" +"cat 3\n" +"window 6\n" +"defenestrate 12" +msgstr "" +">>> # Mede algumas strings:\n" +">>> palavras = ['gato', 'janela', 'defenestrar']\n" +">>> for p in palavras:\n" +"... print(p, len(p))\n" +"...\n" +"gato 4\n" +"janela 6\n" +"defenestrar 11" + #: ../../tutorial/controlflow.rst:72 msgid "" "Code that modifies a collection while iterating over that same collection " @@ -108,6 +152,36 @@ msgstr "" "inseguro. No lugar disso, usualmente você deve iterar sobre uma cópia da " "coleção ou criar uma nova coleção::" +#: ../../tutorial/controlflow.rst:76 +msgid "" +"# Create a sample collection\n" +"users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}\n" +"\n" +"# Strategy: Iterate over a copy\n" +"for user, status in users.copy().items():\n" +" if status == 'inactive':\n" +" del users[user]\n" +"\n" +"# Strategy: Create a new collection\n" +"active_users = {}\n" +"for user, status in users.items():\n" +" if status == 'active':\n" +" active_users[user] = status" +msgstr "" +"# Cria uma amostra de coleção\n" +"users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}\n" +"\n" +"# Estratégia: iterar por uma cópia\n" +"for user, status in users.copy().items():\n" +" if status == 'inactive':\n" +" del users[user]\n" +"\n" +"# Estratégia: criar uma nova coleção\n" +"active_users = {}\n" +"for user, status in users.items():\n" +" if status == 'active':\n" +" active_users[user] = status" + #: ../../tutorial/controlflow.rst:94 msgid "The :func:`range` Function" msgstr "A função :func:`range`" @@ -120,6 +194,26 @@ msgstr "" "Se você precisa iterar sobre sequências numéricas, a função embutida :func:" "`range` é a resposta. Ela gera progressões aritméticas::" +#: ../../tutorial/controlflow.rst:99 +msgid "" +">>> for i in range(5):\n" +"... print(i)\n" +"...\n" +"0\n" +"1\n" +"2\n" +"3\n" +"4" +msgstr "" +">>> for i in range(5):\n" +"... print(i)\n" +"...\n" +"0\n" +"1\n" +"2\n" +"3\n" +"4" + #: ../../tutorial/controlflow.rst:108 msgid "" "The given end point is never part of the generated sequence; ``range(10)`` " @@ -132,6 +226,26 @@ msgstr "" "de comprimento 10. É possível iniciar o intervalo com outro número, ou " "alterar a razão da progressão (inclusive com passo negativo)::" +#: ../../tutorial/controlflow.rst:113 +msgid "" +">>> list(range(5, 10))\n" +"[5, 6, 7, 8, 9]\n" +"\n" +">>> list(range(0, 10, 3))\n" +"[0, 3, 6, 9]\n" +"\n" +">>> list(range(-10, -100, -30))\n" +"[-10, -40, -70]" +msgstr "" +">>> list(range(5, 10))\n" +"[5, 6, 7, 8, 9]\n" +"\n" +">>> list(range(0, 10, 3))\n" +"[0, 3, 6, 9]\n" +"\n" +">>> list(range(-10, -100, -30))\n" +"[-10, -40, -70]" + #: ../../tutorial/controlflow.rst:122 msgid "" "To iterate over the indices of a sequence, you can combine :func:`range` " @@ -140,6 +254,27 @@ msgstr "" "Para iterar sobre os índices de uma sequência, combine :func:`range` e :func:" "`len` da seguinte forma::" +#: ../../tutorial/controlflow.rst:125 +msgid "" +">>> a = ['Mary', 'had', 'a', 'little', 'lamb']\n" +">>> for i in range(len(a)):\n" +"... print(i, a[i])\n" +"...\n" +"0 Mary\n" +"1 had\n" +"2 a\n" +"3 little\n" +"4 lamb" +msgstr "" +">>> a = ['Maria', 'tinha', 'um', 'carneirinho']\n" +">>> for i in range(len(a)):\n" +"... print(i, a[i])\n" +"...\n" +"0 Maria\n" +"1 tinha\n" +"2 um\n" +"3 carneirinho" + #: ../../tutorial/controlflow.rst:135 msgid "" "In most such cases, however, it is convenient to use the :func:`enumerate` " @@ -152,6 +287,14 @@ msgstr "" msgid "A strange thing happens if you just print a range::" msgstr "Uma coisa estranha acontece se você imprime um intervalo::" +#: ../../tutorial/controlflow.rst:140 +msgid "" +">>> range(10)\n" +"range(0, 10)" +msgstr "" +">>> range(10)\n" +"range(0, 10)" + #: ../../tutorial/controlflow.rst:143 msgid "" "In many ways the object returned by :func:`range` behaves as if it is a " @@ -172,12 +315,20 @@ msgid "" "keyword:`for` statement is such a construct, while an example of a function " "that takes an iterable is :func:`sum`::" msgstr "" -"Dizemos que um objeto é :term:`iterável`, isso é, candidato a ser " -"alvo de uma função ou construção que espera alguma coisa capaz de retornar " -"sucessivamente seus elementos um de cada vez. Nós vimos que o comando :" +"Dizemos que um objeto é :term:`iterável`, isso é, candidato a ser alvo de " +"uma função ou construção que espera alguma coisa capaz de retornar " +"sucessivamente seus elementos um de cada vez. Nós vimos que a instrução :" "keyword:`for` é um exemplo de construção, enquanto que um exemplo de função " "que recebe um iterável é :func:`sum`::" +#: ../../tutorial/controlflow.rst:154 +msgid "" +">>> sum(range(4)) # 0 + 1 + 2 + 3\n" +"6" +msgstr "" +">>> sum(range(4)) # 0 + 1 + 2 + 3\n" +"6" + #: ../../tutorial/controlflow.rst:157 msgid "" "Later we will see more functions that return iterables and take iterables as " @@ -189,38 +340,106 @@ msgstr "" "detalhes sobre :func:`list`." #: ../../tutorial/controlflow.rst:164 -msgid "" -":keyword:`!break` and :keyword:`!continue` Statements, and :keyword:`!else` " -"Clauses on Loops" -msgstr "" -"Comandos :keyword:`!break` e :keyword:`!continue`, e cláusula :keyword:`!" -"else`, nos laços de repetição" +msgid ":keyword:`!break` and :keyword:`!continue` Statements" +msgstr "Instruções :keyword:`!break` e :keyword:`!continue`" #: ../../tutorial/controlflow.rst:166 msgid "" "The :keyword:`break` statement breaks out of the innermost enclosing :" -"keyword:`for` or :keyword:`while` loop." +"keyword:`for` or :keyword:`while` loop::" msgstr "" "A instrução :keyword:`break` sai imediatamente do laço de repetição mais " -"interno, seja :keyword:`for` ou :keyword:`while`." +"interno, seja :keyword:`for` ou :keyword:`while`::" #: ../../tutorial/controlflow.rst:169 msgid "" -"A :keyword:`!for` or :keyword:`!while` loop can include an :keyword:`!else` " -"clause." -msgstr "" -"Um laço :keyword:`!for` ou :keyword:`!while` pode incluir uma cláusula :" -"keyword:`!else`." - -#: ../../tutorial/controlflow.rst:171 +">>> for n in range(2, 10):\n" +"... for x in range(2, n):\n" +"... if n % x == 0:\n" +"... print(f\"{n} equals {x} * {n//x}\")\n" +"... break\n" +"...\n" +"4 equals 2 * 2\n" +"6 equals 2 * 3\n" +"8 equals 2 * 4\n" +"9 equals 3 * 3" +msgstr "" +">>> for n in range(2, 10):\n" +"... for x in range(2, n):\n" +"... if n % x == 0:\n" +"... print(f\"{n} igual a {x} * {n//x}\")\n" +"... break\n" +"...\n" +"4 igual a 2 * 2\n" +"6 igual a 2 * 3\n" +"8 igual a 2 * 4\n" +"9 equals 3 * 3" + +#: ../../tutorial/controlflow.rst:180 +msgid "" +"The :keyword:`continue` statement continues with the next iteration of the " +"loop::" +msgstr "" +"A instrução :keyword:`continue` continua com a próxima iteração do laço::" + +#: ../../tutorial/controlflow.rst:183 +msgid "" +">>> for num in range(2, 10):\n" +"... if num % 2 == 0:\n" +"... print(f\"Found an even number {num}\")\n" +"... continue\n" +"... print(f\"Found an odd number {num}\")\n" +"...\n" +"Found an even number 2\n" +"Found an odd number 3\n" +"Found an even number 4\n" +"Found an odd number 5\n" +"Found an even number 6\n" +"Found an odd number 7\n" +"Found an even number 8\n" +"Found an odd number 9" +msgstr "" +">>> for num in range(2, 10):\n" +"... if num % 2 == 0:\n" +"... print(f\"Encontrado um número par {num}\")\n" +"... continue\n" +"... print(f\"Encontrado um número ímpar {num}\")\n" +"...\n" +"Encontrado um número par 2\n" +"Encontrado um número ímpar 3\n" +"Encontrado um número par 4\n" +"Encontrado um número ímpar 5\n" +"Encontrado um número par 6\n" +"Encontrado um número ímpar 7\n" +"Encontrado um número par 8\n" +"Encontrado um número ímpar 9" + +#: ../../tutorial/controlflow.rst:202 +msgid ":keyword:`!else` Clauses on Loops" +msgstr "Cláusulas :keyword:`!else` em laços" + +#: ../../tutorial/controlflow.rst:204 +msgid "" +"In a :keyword:`!for` or :keyword:`!while` loop the :keyword:`!break` " +"statement may be paired with an :keyword:`!else` clause. If the loop " +"finishes without executing the :keyword:`!break`, the :keyword:`!else` " +"clause executes." +msgstr "" +"Em um laço :keyword:`!for` ou :keyword:`!while` a instrução :keyword:`!" +"break` pode ser pareada com uma cláusula :keyword:`!else`. Se o laço " +"terminar sem executar o :keyword:`!break`, a cláusula :keyword:`!else` será " +"executada." + +#: ../../tutorial/controlflow.rst:208 msgid "" "In a :keyword:`for` loop, the :keyword:`!else` clause is executed after the " -"loop reaches its final iteration." +"loop finishes its final iteration, that is, if no break occurred." msgstr "" "Em um laço :keyword:`for`, a cláusula :keyword:`!else` é executada após o " -"laço atingir sua iteração final." +"laço finalizar sua iteração final, ou seja, se não ocorrer nenhuma " +"interrupção." -#: ../../tutorial/controlflow.rst:174 +#: ../../tutorial/controlflow.rst:211 msgid "" "In a :keyword:`while` loop, it's executed after the loop's condition becomes " "false." @@ -228,15 +447,19 @@ msgstr "" "Em um laço :keyword:`while`, ele é executado após a condição do laço se " "tornar falsa." -#: ../../tutorial/controlflow.rst:176 +#: ../../tutorial/controlflow.rst:213 msgid "" "In either kind of loop, the :keyword:`!else` clause is **not** executed if " -"the loop was terminated by a :keyword:`break`." +"the loop was terminated by a :keyword:`break`. Of course, other ways of " +"ending the loop early, such as a :keyword:`return` or a raised exception, " +"will also skip execution of the :keyword:`else` clause." msgstr "" "Em qualquer tipo de laço, a cláusula :keyword:`!else` **não** é executada se " -"o laço for encerrado por um :keyword:`break`." +"o laço foi encerrado por um :keyword:`break`. Claro, outras maneiras de " +"encerrar o laço mais cedo, como um :keyword:`return` ou uma exceção " +"levantada, também pularão a execução da cláusula :keyword:`else`." -#: ../../tutorial/controlflow.rst:179 +#: ../../tutorial/controlflow.rst:218 msgid "" "This is exemplified in the following :keyword:`!for` loop, which searches " "for prime numbers::" @@ -244,56 +467,120 @@ msgstr "" "Isso é exemplificado no seguinte laço :keyword:`!for`, que procura por " "números primos::" -#: ../../tutorial/controlflow.rst:200 +#: ../../tutorial/controlflow.rst:221 +msgid "" +">>> for n in range(2, 10):\n" +"... for x in range(2, n):\n" +"... if n % x == 0:\n" +"... print(n, 'equals', x, '*', n//x)\n" +"... break\n" +"... else:\n" +"... # loop fell through without finding a factor\n" +"... print(n, 'is a prime number')\n" +"...\n" +"2 is a prime number\n" +"3 is a prime number\n" +"4 equals 2 * 2\n" +"5 is a prime number\n" +"6 equals 2 * 3\n" +"7 is a prime number\n" +"8 equals 2 * 4\n" +"9 equals 3 * 3" +msgstr "" +">>> for n in range(2, 10):\n" +"... for x in range(2, n):\n" +"... if n % x == 0:\n" +"... print(n, 'igual a', x, '*', n//x)\n" +"... break\n" +"... else:\n" +"... # a iteração passou direto sem encontrar um fator\n" +"... print(n, 'é um número primo')\n" +"...\n" +"2 é um número primo\n" +"3 é um número primo\n" +"4 igual a 2 * 2\n" +"5 é um número primo\n" +"6 igual a 2 * 3\n" +"7 é um número primo\n" +"8 igual a 2 * 4\n" +"9 igual a 3 * 3" + +#: ../../tutorial/controlflow.rst:239 msgid "" "(Yes, this is the correct code. Look closely: the ``else`` clause belongs " -"to the :keyword:`for` loop, **not** the :keyword:`if` statement.)" +"to the ``for`` loop, **not** the ``if`` statement.)" msgstr "" -"(Sim, o código está correto. Olhe atentamente: a cláusula ``else`` pertence " -"ao laço :keyword:`for`, e **não** ao comando :keyword:`if`.)" +"(Sim, este é o código correto. Observe atentamente: a cláusula ``else`` " +"pertence ao laço ``for``, **não** à instrução ``if``.)" -#: ../../tutorial/controlflow.rst:203 +#: ../../tutorial/controlflow.rst:242 msgid "" -"When used with a loop, the ``else`` clause has more in common with the " -"``else`` clause of a :keyword:`try` statement than it does with that of :" -"keyword:`if` statements: a :keyword:`try` statement's ``else`` clause runs " -"when no exception occurs, and a loop's ``else`` clause runs when no " -"``break`` occurs. For more on the :keyword:`!try` statement and exceptions, " -"see :ref:`tut-handling`." +"One way to think of the else clause is to imagine it paired with the ``if`` " +"inside the loop. As the loop executes, it will run a sequence like if/if/if/" +"else. The ``if`` is inside the loop, encountered a number of times. If the " +"condition is ever true, a ``break`` will happen. If the condition is never " +"true, the ``else`` clause outside the loop will execute." msgstr "" -"Quando usado em um laço, a cláusula ``else`` tem mais em comum com a " -"cláusula ``else`` de um comando :keyword:`try` do que com a de um comando :" -"keyword:`if`: a cláusula ``else`` de um comando :keyword:`try` executa " -"quando não ocorre exceção, e o ``else`` de um laço executa quando não ocorre " -"um ``break``. Para mais informações sobre comando :keyword:`!try` e " -"exceções, veja :ref:`tut-handling`." +"Uma maneira de pensar na cláusula else é imaginá-la pareada com o ``if`` " +"dentro do laço. Conforme o laço é executado, ele executará uma sequência " +"como if/if/if/else. O ``if`` está dentro do laço, encontrado várias vezes. " +"Se a condição for verdadeira, um ``break`` acontecerá. Se a condição nunca " +"for verdadeira, a cláusula ``else`` fora do laçoserá executada." -#: ../../tutorial/controlflow.rst:210 +#: ../../tutorial/controlflow.rst:248 msgid "" -"The :keyword:`continue` statement, also borrowed from C, continues with the " -"next iteration of the loop::" +"When used with a loop, the ``else`` clause has more in common with the " +"``else`` clause of a :keyword:`try` statement than it does with that of " +"``if`` statements: a ``try`` statement's ``else`` clause runs when no " +"exception occurs, and a loop's ``else`` clause runs when no ``break`` " +"occurs. For more on the ``try`` statement and exceptions, see :ref:`tut-" +"handling`." msgstr "" -"A instrução :keyword:`continue`, também emprestada da linguagem C, continua " -"com a próxima iteração do laço::" +"Quando usado em um laço, a cláusula ``else`` tem mais em comum com a " +"cláusula ``else`` de uma instrução :keyword:`try` do que com a de instruções " +"``if``: a cláusula ``else`` de uma instrução ``try`` é executada quando não " +"ocorre exceção, e a cláusula ``else`` de um laço é executada quando não " +"ocorre um ``break``. Para mais informações sobre instrução ``try`` e " +"exceções, veja :ref:`tut-handling`." -#: ../../tutorial/controlflow.rst:231 +#: ../../tutorial/controlflow.rst:257 msgid ":keyword:`!pass` Statements" -msgstr "Comandos :keyword:`!pass`" +msgstr "Instruções :keyword:`!pass`" -#: ../../tutorial/controlflow.rst:233 +#: ../../tutorial/controlflow.rst:259 msgid "" "The :keyword:`pass` statement does nothing. It can be used when a statement " "is required syntactically but the program requires no action. For example::" msgstr "" -"O comando :keyword:`pass` não faz nada. Pode ser usada quando a sintaxe " -"exige um comando mas a semântica do programa não requer nenhuma ação. Por " -"exemplo::" +"A instrução :keyword:`pass` não faz nada. Pode ser usada quando a sintaxe " +"exige uma instrução, mas a semântica do programa não requer nenhuma ação. " +"Por exemplo::" -#: ../../tutorial/controlflow.rst:240 +#: ../../tutorial/controlflow.rst:262 +msgid "" +">>> while True:\n" +"... pass # Busy-wait for keyboard interrupt (Ctrl+C)\n" +"..." +msgstr "" +">>> while True:\n" +"... pass # Ocupado, aguardando interrupção por teclado (Ctrl+C)\n" +"..." + +#: ../../tutorial/controlflow.rst:266 msgid "This is commonly used for creating minimal classes::" msgstr "Isto é usado muitas vezes para se definir classes mínimas::" -#: ../../tutorial/controlflow.rst:246 +#: ../../tutorial/controlflow.rst:268 +msgid "" +">>> class MyEmptyClass:\n" +"... pass\n" +"..." +msgstr "" +">>> class MinhaClasseVazia:\n" +"... pass\n" +"..." + +#: ../../tutorial/controlflow.rst:272 msgid "" "Another place :keyword:`pass` can be used is as a place-holder for a " "function or conditional body when you are working on new code, allowing you " @@ -305,11 +592,21 @@ msgstr "" "com código novo, ainda indefinido, permitindo que mantenha-se o pensamento " "num nível mais abstrato. O :keyword:`!pass` é silenciosamente ignorado::" -#: ../../tutorial/controlflow.rst:258 +#: ../../tutorial/controlflow.rst:276 +msgid "" +">>> def initlog(*args):\n" +"... pass # Remember to implement this!\n" +"..." +msgstr "" +">>> def initlog(*args):\n" +"... pass # Lembre-se de implementar isso!\n" +"..." + +#: ../../tutorial/controlflow.rst:284 msgid ":keyword:`!match` Statements" msgstr "Instruções :keyword:`!match`" -#: ../../tutorial/controlflow.rst:260 +#: ../../tutorial/controlflow.rst:286 msgid "" "A :keyword:`match` statement takes an expression and compares its value to " "successive patterns given as one or more case blocks. This is superficially " @@ -329,13 +626,37 @@ msgstr "" "extrair componentes (elementos de sequência ou atributos de objetos) do " "valor para variáveis." -#: ../../tutorial/controlflow.rst:268 +#: ../../tutorial/controlflow.rst:294 msgid "" "The simplest form compares a subject value against one or more literals::" msgstr "" "A forma mais simples compara um valor de assunto com um ou mais literais::" -#: ../../tutorial/controlflow.rst:281 +#: ../../tutorial/controlflow.rst:296 +msgid "" +"def http_error(status):\n" +" match status:\n" +" case 400:\n" +" return \"Bad request\"\n" +" case 404:\n" +" return \"Not found\"\n" +" case 418:\n" +" return \"I'm a teapot\"\n" +" case _:\n" +" return \"Something's wrong with the internet\"" +msgstr "" +"def http_error(status):\n" +" match status:\n" +" case 400:\n" +" return \"Bad request\"\n" +" case 404:\n" +" return \"Not found\"\n" +" case 418:\n" +" return \"I'm a teapot\"\n" +" case _:\n" +" return \"Something's wrong with the internet\"" + +#: ../../tutorial/controlflow.rst:307 msgid "" "Note the last block: the \"variable name\" ``_`` acts as a *wildcard* and " "never fails to match. If no case matches, none of the branches is executed." @@ -344,13 +665,21 @@ msgstr "" "e nunca falha em corresponder. Se nenhum caso corresponder, nenhuma das " "ramificações será executada." -#: ../../tutorial/controlflow.rst:284 +#: ../../tutorial/controlflow.rst:310 msgid "" "You can combine several literals in a single pattern using ``|`` (\"or\")::" msgstr "" "Você pode combinar vários literais em um único padrão usando ``|`` (\"ou\")::" -#: ../../tutorial/controlflow.rst:289 +#: ../../tutorial/controlflow.rst:312 +msgid "" +"case 401 | 403 | 404:\n" +" return \"Not allowed\"" +msgstr "" +"case 401 | 403 | 404:\n" +" return \"Não permitido\"" + +#: ../../tutorial/controlflow.rst:315 msgid "" "Patterns can look like unpacking assignments, and can be used to bind " "variables::" @@ -358,7 +687,35 @@ msgstr "" "Os padrões podem se parecer com atribuições de desempacotamento e podem ser " "usados para vincular variáveis::" -#: ../../tutorial/controlflow.rst:305 +#: ../../tutorial/controlflow.rst:318 +msgid "" +"# point is an (x, y) tuple\n" +"match point:\n" +" case (0, 0):\n" +" print(\"Origin\")\n" +" case (0, y):\n" +" print(f\"Y={y}\")\n" +" case (x, 0):\n" +" print(f\"X={x}\")\n" +" case (x, y):\n" +" print(f\"X={x}, Y={y}\")\n" +" case _:\n" +" raise ValueError(\"Not a point\")" +msgstr "" +"# ponto é uma tupla (x, y)\n" +"match ponto:\n" +" case (0, 0):\n" +" print(\"Origem\")\n" +" case (0, y):\n" +" print(f\"Y={y}\")\n" +" case (x, 0):\n" +" print(f\"X={x}\")\n" +" case (x, y):\n" +" print(f\"X={x}, Y={y}\")\n" +" case _:\n" +" raise ValueError(\"Não é um ponto\")" + +#: ../../tutorial/controlflow.rst:331 msgid "" "Study that one carefully! The first pattern has two literals, and can be " "thought of as an extension of the literal pattern shown above. But the next " @@ -370,11 +727,11 @@ msgstr "" "Estude isso com cuidado! O primeiro padrão tem dois literais e pode ser " "considerado uma extensão do padrão literal mostrado acima. Mas os próximos " "dois padrões combinam um literal e uma variável, e a variável *vincula* um " -"valor do assunto (``point``). O quarto padrão captura dois valores, o que o " +"valor do assunto (``ponto``). O quarto padrão captura dois valores, o que o " "torna conceitualmente semelhante à atribuição de desempacotamento ``(x, y) = " -"point``." +"ponto``." -#: ../../tutorial/controlflow.rst:312 +#: ../../tutorial/controlflow.rst:338 msgid "" "If you are using classes to structure your data you can use the class name " "followed by an argument list resembling a constructor, but with the ability " @@ -384,7 +741,45 @@ msgstr "" "nome da classe seguido por uma lista de argumentos semelhante a um " "construtor, mas com a capacidade de capturar atributos em variáveis::" -#: ../../tutorial/controlflow.rst:334 +#: ../../tutorial/controlflow.rst:342 +msgid "" +"class Point:\n" +" def __init__(self, x, y):\n" +" self.x = x\n" +" self.y = y\n" +"\n" +"def where_is(point):\n" +" match point:\n" +" case Point(x=0, y=0):\n" +" print(\"Origin\")\n" +" case Point(x=0, y=y):\n" +" print(f\"Y={y}\")\n" +" case Point(x=x, y=0):\n" +" print(f\"X={x}\")\n" +" case Point():\n" +" print(\"Somewhere else\")\n" +" case _:\n" +" print(\"Not a point\")" +msgstr "" +"class Ponto:\n" +" def __init__(self, x, y):\n" +" self.x = x\n" +" self.y = y\n" +"\n" +"def onde_está(ponto):\n" +" match ponto:\n" +" case Ponto(x=0, y=0):\n" +" print(\"Origem\")\n" +" case Ponto(x=0, y=y):\n" +" print(f\"Y={y}\")\n" +" case Ponto(x=x, y=0):\n" +" print(f\"X={x}\")\n" +" case Ponto():\n" +" print(\"Em outro lugar\")\n" +" case _:\n" +" print(\"Não é um ponto\")" + +#: ../../tutorial/controlflow.rst:360 msgid "" "You can use positional parameters with some builtin classes that provide an " "ordering for their attributes (e.g. dataclasses). You can also define a " @@ -398,9 +793,21 @@ msgstr "" "também pode definir uma posição específica para atributos em padrões " "configurando o atributo especial ``__match_args__`` em suas classes. Se for " "definido como (\"x\", \"y\"), os seguintes padrões são todos equivalentes (e " -"todos vinculam o atributo ``y`` à variável ``var``)::" +"todos ligam o atributo ``y`` à variável ``var``)::" -#: ../../tutorial/controlflow.rst:345 +#: ../../tutorial/controlflow.rst:366 +msgid "" +"Point(1, var)\n" +"Point(1, y=var)\n" +"Point(x=1, y=var)\n" +"Point(y=var, x=1)" +msgstr "" +"Ponto(1, var)\n" +"Ponto(1, y=var)\n" +"Ponto(x=1, y=var)\n" +"Ponto(y=var, x=1)" + +#: ../../tutorial/controlflow.rst:371 msgid "" "A recommended way to read patterns is to look at them as an extended form of " "what you would put on the left of an assignment, to understand which " @@ -416,9 +823,9 @@ msgstr "" "acima) são atribuídos por uma instrução de correspondência. Nomes " "pontilhados (como ``foo.bar``), nomes de atributos (o ``x=`` e ``y=`` acima) " "ou nomes de classes (reconhecidos pelo \"(...)\" próximo a eles, como " -"``Point`` acima) nunca são atribuídos." +"``Ponto`` acima) nunca são atribuídos." -#: ../../tutorial/controlflow.rst:352 +#: ../../tutorial/controlflow.rst:378 msgid "" "Patterns can be arbitrarily nested. For example, if we have a short list of " "Points, with ``__match_args__`` added, we could match it like this::" @@ -427,22 +834,73 @@ msgstr "" "pequena lista de Pontos, com ``__match_args__`` adicionado, poderíamos " "correspondê-la assim::" -#: ../../tutorial/controlflow.rst:373 +#: ../../tutorial/controlflow.rst:381 +msgid "" +"class Point:\n" +" __match_args__ = ('x', 'y')\n" +" def __init__(self, x, y):\n" +" self.x = x\n" +" self.y = y\n" +"\n" +"match points:\n" +" case []:\n" +" print(\"No points\")\n" +" case [Point(0, 0)]:\n" +" print(\"The origin\")\n" +" case [Point(x, y)]:\n" +" print(f\"Single point {x}, {y}\")\n" +" case [Point(0, y1), Point(0, y2)]:\n" +" print(f\"Two on the Y axis at {y1}, {y2}\")\n" +" case _:\n" +" print(\"Something else\")" +msgstr "" +"class Ponto:\n" +" __match_args__ = ('x', 'y')\n" +" def __init__(self, x, y):\n" +" self.x = x\n" +" self.y = y\n" +"\n" +"match pontos:\n" +" case []:\n" +" print(\"Sem pontos\")\n" +" case [Ponto(0, 0)]:\n" +" print(\"A origem\")\n" +" case [Ponto(x, y)]:\n" +" print(f\"Ponto único {x}, {y}\")\n" +" case [Ponto(0, y1), Ponto(0, y2)]:\n" +" print(f\"Dois do eixo Y em {y1}, {y2}\")\n" +" case _:\n" +" print(\"Outra coisa\")" + +#: ../../tutorial/controlflow.rst:399 msgid "" "We can add an ``if`` clause to a pattern, known as a \"guard\". If the " "guard is false, ``match`` goes on to try the next case block. Note that " "value capture happens before the guard is evaluated::" msgstr "" "Podemos adicionar uma cláusula ``if`` a um padrão, conhecido como " -"\"guarda\". Se a guarda for falsa, ``match`` continua para tentar o próximo " -"bloco de caso. Observe que a captura de valor ocorre antes que a guarda seja " -"avaliada::" +"\"guarda\". Se a guarda for falsa, ``match`` tenta o próximo bloco de caso. " +"Observe que a captura de valor ocorre antes que a guarda seja avaliada::" + +#: ../../tutorial/controlflow.rst:403 +msgid "" +"match point:\n" +" case Point(x, y) if x == y:\n" +" print(f\"Y=X at {x}\")\n" +" case Point(x, y):\n" +" print(f\"Not on the diagonal\")" +msgstr "" +"match ponto:\n" +" case Ponto(x, y) if x == y:\n" +" print(f\"Y=X at {x}\")\n" +" case Ponto(x, y):\n" +" print(f\"Não está na diagonal\")" -#: ../../tutorial/controlflow.rst:383 +#: ../../tutorial/controlflow.rst:409 msgid "Several other key features of this statement:" msgstr "Vários outros recursos importantes desta instrução::" -#: ../../tutorial/controlflow.rst:385 +#: ../../tutorial/controlflow.rst:411 msgid "" "Like unpacking assignments, tuple and list patterns have exactly the same " "meaning and actually match arbitrary sequences. An important exception is " @@ -453,7 +911,7 @@ msgstr "" "arbitrárias. Uma exceção importante é que eles não correspondem a iteradores " "ou strings." -#: ../../tutorial/controlflow.rst:389 +#: ../../tutorial/controlflow.rst:415 msgid "" "Sequence patterns support extended unpacking: ``[x, y, *rest]`` and ``(x, y, " "*rest)`` work similar to unpacking assignments. The name after ``*`` may " @@ -466,7 +924,7 @@ msgstr "" "``_``, então ``(x, y, *_)`` corresponde a uma sequência de pelo menos dois " "itens sem ligar os itens restantes." -#: ../../tutorial/controlflow.rst:394 +#: ../../tutorial/controlflow.rst:420 msgid "" "Mapping patterns: ``{\"bandwidth\": b, \"latency\": l}`` captures the " "``\"bandwidth\"`` and ``\"latency\"`` values from a dictionary. Unlike " @@ -479,11 +937,15 @@ msgstr "" "``**rest`` também é permitido. (Mas ``**_`` seria redundante, então não é " "permitido.)" -#: ../../tutorial/controlflow.rst:399 +#: ../../tutorial/controlflow.rst:425 msgid "Subpatterns may be captured using the ``as`` keyword::" -msgstr "Subpadrões podem ser capturados usando a palavra reservada ``as``::" +msgstr "Subpadrões podem ser capturados usando a palavra reservada ``as`` ::" -#: ../../tutorial/controlflow.rst:403 +#: ../../tutorial/controlflow.rst:427 +msgid "case (Point(x1, y1), Point(x2, y2) as p2): ..." +msgstr "case (Ponto(x1, y1), Ponto(x2, y2) as p2): ..." + +#: ../../tutorial/controlflow.rst:429 msgid "" "will capture the second element of the input as ``p2`` (as long as the input " "is a sequence of two points)" @@ -491,7 +953,7 @@ msgstr "" "Vai capturar o segundo elemento da entrada como ``p2`` (se a entrada for uma " "sequência de dois pontos)" -#: ../../tutorial/controlflow.rst:406 +#: ../../tutorial/controlflow.rst:432 msgid "" "Most literals are compared by equality, however the singletons ``True``, " "``False`` and ``None`` are compared by identity." @@ -499,7 +961,7 @@ msgstr "" "A maioria dos literais são comparados por igualdade, no entando os " "singletons ``True``, ``False`` e ``None`` são comparados por identidade." -#: ../../tutorial/controlflow.rst:409 +#: ../../tutorial/controlflow.rst:435 msgid "" "Patterns may use named constants. These must be dotted names to prevent " "them from being interpreted as capture variable::" @@ -507,7 +969,41 @@ msgstr "" "Padrões podem usar constantes nomeadas. Estas devem ser nomes pontilhados " "para prevenir que sejam interpretadas como variáveis de captura::" -#: ../../tutorial/controlflow.rst:428 +#: ../../tutorial/controlflow.rst:438 +msgid "" +"from enum import Enum\n" +"class Color(Enum):\n" +" RED = 'red'\n" +" GREEN = 'green'\n" +" BLUE = 'blue'\n" +"\n" +"color = Color(input(\"Enter your choice of 'red', 'blue' or 'green': \"))\n" +"\n" +"match color:\n" +" case Color.RED:\n" +" print(\"I see red!\")\n" +" case Color.GREEN:\n" +" print(\"Grass is green\")\n" +" case Color.BLUE:\n" +" print(\"I'm feeling the blues :(\")" +msgstr "" +"from enum import Enum\n" +"class Cor(Enum):\n" +" VERMELHO = 'vermelho'\n" +" VERDE = 'verde'\n" +" AZUL = 'azul'\n" +"\n" +"cor = Cor(input(\"Insira sua escolha de 'vermelho, 'azul' ou 'verde': \"))\n" +"\n" +"match color:\n" +" case Cor.VERMELHO:\n" +" print(\"Eu vejo vermelho!\")\n" +" case Cor.VERDE:\n" +" print(\"Grama é verde\")\n" +" case Cor.AZUL:\n" +" print(\"O céu é azul :)\")" + +#: ../../tutorial/controlflow.rst:454 msgid "" "For a more detailed explanation and additional examples, you can look into :" "pep:`636` which is written in a tutorial format." @@ -515,11 +1011,11 @@ msgstr "" "Para uma explicação mais detalhada e exemplos adicionais, você pode olhar :" "pep:`636` que foi escrita em formato de tutorial." -#: ../../tutorial/controlflow.rst:434 +#: ../../tutorial/controlflow.rst:460 msgid "Defining Functions" msgstr "Definindo funções" -#: ../../tutorial/controlflow.rst:436 +#: ../../tutorial/controlflow.rst:462 msgid "" "We can create a function that writes the Fibonacci series to an arbitrary " "boundary::" @@ -527,7 +1023,33 @@ msgstr "" "Podemos criar uma função que escreve a série de Fibonacci até um limite " "arbitrário::" -#: ../../tutorial/controlflow.rst:456 +#: ../../tutorial/controlflow.rst:465 +msgid "" +">>> def fib(n): # write Fibonacci series less than n\n" +"... \"\"\"Print a Fibonacci series less than n.\"\"\"\n" +"... a, b = 0, 1\n" +"... while a < n:\n" +"... print(a, end=' ')\n" +"... a, b = b, a+b\n" +"... print()\n" +"...\n" +">>> # Now call the function we just defined:\n" +">>> fib(2000)\n" +"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597" +msgstr "" +">>> def fib(n): # escreve série de Fibonacci menor que n\n" +"... \"\"\"Imprime uma série de Fibonacci menor que n.\"\"\"\n" +"... a, b = 0, 1\n" +"... while a < n:\n" +"... print(a, end=' ')\n" +"... a, b = b, a+b\n" +"... print()\n" +"...\n" +">>> # Agora chamamos a função que acabamos de definir:\n" +">>> fib(2000)\n" +"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597" + +#: ../../tutorial/controlflow.rst:482 msgid "" "The keyword :keyword:`def` introduces a function *definition*. It must be " "followed by the function name and the parenthesized list of formal " @@ -536,10 +1058,10 @@ msgid "" msgstr "" "A palavra reservada :keyword:`def` inicia a *definição* de uma função. Ela " "deve ser seguida do nome da função e da lista de parâmetros formais entre " -"parênteses. Os comandos que formam o corpo da função começam na linha " +"parênteses. As instruções que formam o corpo da função começam na linha " "seguinte e devem ser indentados." -#: ../../tutorial/controlflow.rst:461 +#: ../../tutorial/controlflow.rst:487 msgid "" "The first statement of the function body can optionally be a string literal; " "this string literal is the function's documentation string, or :dfn:" @@ -557,7 +1079,7 @@ msgstr "" "o usuário navegue interativamente pelo código. É uma boa prática incluir " "sempre docstrings em suas funções, portanto, tente fazer disso um hábito." -#: ../../tutorial/controlflow.rst:468 +#: ../../tutorial/controlflow.rst:494 msgid "" "The *execution* of a function introduces a new symbol table used for the " "local variables of the function. More precisely, all variable assignments " @@ -578,10 +1100,10 @@ msgstr "" "circundantes, depois na tabela de símbolos global e, finalmente, na tabela " "de nomes da própria linguagem. Embora possam ser referenciadas, variáveis " "globais e de funções externas não podem ter atribuições (a menos que seja " -"utilizado o comando :keyword:`global`, para variáveis globais, ou :keyword:" +"utilizada a instrução :keyword:`global`, para variáveis globais, ou :keyword:" "`nonlocal`, para variáveis de funções externas)." -#: ../../tutorial/controlflow.rst:479 +#: ../../tutorial/controlflow.rst:505 msgid "" "The actual parameters (arguments) to a function call are introduced in the " "local symbol table of the called function when it is called; thus, arguments " @@ -597,7 +1119,7 @@ msgstr "" "chama outra função, ou chama a si mesma recursivamente, uma nova tabela de " "símbolos é criada para tal chamada." -#: ../../tutorial/controlflow.rst:486 +#: ../../tutorial/controlflow.rst:512 msgid "" "A function definition associates the function name with the function object " "in the current symbol table. The interpreter recognizes the object pointed " @@ -610,7 +1132,21 @@ msgstr "" "apontar para o mesmo objeto função e também pode ser usados pra acessar a " "função::" -#: ../../tutorial/controlflow.rst:497 +#: ../../tutorial/controlflow.rst:517 +msgid "" +">>> fib\n" +"\n" +">>> f = fib\n" +">>> f(100)\n" +"0 1 1 2 3 5 8 13 21 34 55 89" +msgstr "" +">>> fib\n" +"\n" +">>> f = fib\n" +">>> f(100)\n" +"0 1 1 2 3 5 8 13 21 34 55 89" + +#: ../../tutorial/controlflow.rst:523 msgid "" "Coming from other languages, you might object that ``fib`` is not a function " "but a procedure since it doesn't return a value. In fact, even functions " @@ -622,13 +1158,23 @@ msgid "" msgstr "" "Conhecendo outras linguagens, pode-se questionar que ``fib`` não é uma " "função, mas um procedimento, pois ela não devolve um valor. Na verdade, " -"mesmo funções que não usam o comando :keyword:`return` devolvem um valor, " +"mesmo funções que não usam a instrução :keyword:`return` devolvem um valor, " "ainda que pouco interessante. Esse valor é chamado ``None`` (é um nome " "embutido). O interpretador interativo evita escrever ``None`` quando ele é o " "único resultado de uma expressão. Mas se quiser vê-lo pode usar a função :" "func:`print`::" -#: ../../tutorial/controlflow.rst:508 +#: ../../tutorial/controlflow.rst:530 +msgid "" +">>> fib(0)\n" +">>> print(fib(0))\n" +"None" +msgstr "" +">>> fib(0)\n" +">>> print(fib(0))\n" +"None" + +#: ../../tutorial/controlflow.rst:534 msgid "" "It is simple to write a function that returns a list of the numbers of the " "Fibonacci series, instead of printing it::" @@ -636,11 +1182,39 @@ msgstr "" "É fácil escrever uma função que retorna uma lista de números da série de " "Fibonacci, ao invés de exibi-los::" -#: ../../tutorial/controlflow.rst:524 +#: ../../tutorial/controlflow.rst:537 +msgid "" +">>> def fib2(n): # return Fibonacci series up to n\n" +"... \"\"\"Return a list containing the Fibonacci series up to n.\"\"\"\n" +"... result = []\n" +"... a, b = 0, 1\n" +"... while a < n:\n" +"... result.append(a) # see below\n" +"... a, b = b, a+b\n" +"... return result\n" +"...\n" +">>> f100 = fib2(100) # call it\n" +">>> f100 # write the result\n" +"[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]" +msgstr "" +">>> def fib2(n): # retorna série de Fibonacci até n\n" +"... \"\"\"Retorna uma lista contendo a série de Fibonacci até n.\"\"\"\n" +"... resultado = []\n" +"... a, b = 0, 1\n" +"... while a < n:\n" +"... resultado.append(a) # veja abaixo\n" +"... a, b = b, a+b\n" +"... return resultado\n" +"...\n" +">>> f100 = fib2(100) # chama-o\n" +">>> f100 # escreve o resultado\n" +"[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]" + +#: ../../tutorial/controlflow.rst:550 msgid "This example, as usual, demonstrates some new Python features:" msgstr "Este exemplo demonstra novos recursos de Python:" -#: ../../tutorial/controlflow.rst:526 +#: ../../tutorial/controlflow.rst:552 msgid "" "The :keyword:`return` statement returns with a value from a function. :" "keyword:`!return` without an expression argument returns ``None``. Falling " @@ -650,7 +1224,7 @@ msgstr "" "função. :keyword:`!return` sem qualquer expressão como argumento retorna " "``None``. Atingir o final da função também retorna ``None``." -#: ../../tutorial/controlflow.rst:530 +#: ../../tutorial/controlflow.rst:556 msgid "" "The statement ``result.append(a)`` calls a *method* of the list object " "``result``. A method is a function that 'belongs' to an object and is named " @@ -675,11 +1249,11 @@ msgstr "" "objetos do tipo lista; adiciona um novo elemento ao final da lista. Neste " "exemplo, ele equivale a ``result = result + [a]``, só que mais eficiente." -#: ../../tutorial/controlflow.rst:545 +#: ../../tutorial/controlflow.rst:571 msgid "More on Defining Functions" msgstr "Mais sobre definição de funções" -#: ../../tutorial/controlflow.rst:547 +#: ../../tutorial/controlflow.rst:573 msgid "" "It is also possible to define functions with a variable number of arguments. " "There are three forms, which can be combined." @@ -687,11 +1261,11 @@ msgstr "" "É possível definir funções com um número variável de argumentos. Existem " "três formas, que podem ser combinadas." -#: ../../tutorial/controlflow.rst:554 +#: ../../tutorial/controlflow.rst:580 msgid "Default Argument Values" msgstr "Argumentos com valor padrão" -#: ../../tutorial/controlflow.rst:556 +#: ../../tutorial/controlflow.rst:582 msgid "" "The most useful form is to specify a default value for one or more " "arguments. This creates a function that can be called with fewer arguments " @@ -701,18 +1275,45 @@ msgstr "" "argumentos. Isso cria uma função que pode ser invocada com menos argumentos " "do que os que foram definidos. Por exemplo::" -#: ../../tutorial/controlflow.rst:572 +#: ../../tutorial/controlflow.rst:586 +msgid "" +"def ask_ok(prompt, retries=4, reminder='Please try again!'):\n" +" while True:\n" +" reply = input(prompt)\n" +" if reply in {'y', 'ye', 'yes'}:\n" +" return True\n" +" if reply in {'n', 'no', 'nop', 'nope'}:\n" +" return False\n" +" retries = retries - 1\n" +" if retries < 0:\n" +" raise ValueError('invalid user response')\n" +" print(reminder)" +msgstr "" +"def pergunta_ok(mensagem, tentativas=4, lembrete='Por favor, tente " +"novamente!'):\n" +" while True:\n" +" resposta = input(mensagem)\n" +" if resposta in {'s', 'sim', 'é}:\n" +" return True\n" +" if resposta in {'n', 'não', 'nah'}:\n" +" return False\n" +" tentativas = tentativas - 1\n" +" if tentativas < 0:\n" +" raise ValueError('resposta inválida de usuário')\n" +" print(lembrete)" + +#: ../../tutorial/controlflow.rst:598 msgid "This function can be called in several ways:" msgstr "Essa função pode ser chamada de várias formas:" -#: ../../tutorial/controlflow.rst:574 +#: ../../tutorial/controlflow.rst:600 msgid "" "giving only the mandatory argument: ``ask_ok('Do you really want to quit?')``" msgstr "" "fornecendo apenas o argumento obrigatório: ``ask_ok('Do you really want to " "quit?')``" -#: ../../tutorial/controlflow.rst:576 +#: ../../tutorial/controlflow.rst:602 msgid "" "giving one of the optional arguments: ``ask_ok('OK to overwrite the file?', " "2)``" @@ -720,7 +1321,7 @@ msgstr "" "fornecendo um dos argumentos opcionais: ``ask_ok('OK to overwrite the " "file?', 2)``" -#: ../../tutorial/controlflow.rst:578 +#: ../../tutorial/controlflow.rst:604 msgid "" "or even giving all arguments: ``ask_ok('OK to overwrite the file?', 2, 'Come " "on, only yes or no!')``" @@ -728,7 +1329,7 @@ msgstr "" "ou fornecendo todos os argumentos: ``ask_ok('OK to overwrite the file?', 2, " "'Come on, only yes or no!')``" -#: ../../tutorial/controlflow.rst:581 +#: ../../tutorial/controlflow.rst:607 msgid "" "This example also introduces the :keyword:`in` keyword. This tests whether " "or not a sequence contains a certain value." @@ -736,7 +1337,7 @@ msgstr "" "Este exemplo também introduz a palavra-chave :keyword:`in`, que verifica se " "uma sequência contém ou não um determinado valor." -#: ../../tutorial/controlflow.rst:584 +#: ../../tutorial/controlflow.rst:610 msgid "" "The default values are evaluated at the point of function definition in the " "*defining* scope, so that ::" @@ -744,11 +1345,29 @@ msgstr "" "Os valores padrões são avaliados no momento da definição da função, e no " "escopo em que a função foi *definida*, portanto::" -#: ../../tutorial/controlflow.rst:595 +#: ../../tutorial/controlflow.rst:613 +msgid "" +"i = 5\n" +"\n" +"def f(arg=i):\n" +" print(arg)\n" +"\n" +"i = 6\n" +"f()" +msgstr "" +"i = 5\n" +"\n" +"def f(arg=i):\n" +" print(arg)\n" +"\n" +"i = 6\n" +"f()" + +#: ../../tutorial/controlflow.rst:621 msgid "will print ``5``." msgstr "irá exibir ``5``." -#: ../../tutorial/controlflow.rst:597 +#: ../../tutorial/controlflow.rst:623 msgid "" "**Important warning:** The default value is evaluated only once. This makes " "a difference when the default is a mutable object such as a list, " @@ -760,11 +1379,39 @@ msgstr "" "instâncias de classes. Por exemplo, a função a seguir acumula os argumentos " "passados, nas chamadas subsequentes::" -#: ../../tutorial/controlflow.rst:610 +#: ../../tutorial/controlflow.rst:628 +msgid "" +"def f(a, L=[]):\n" +" L.append(a)\n" +" return L\n" +"\n" +"print(f(1))\n" +"print(f(2))\n" +"print(f(3))" +msgstr "" +"def f(a, L=[]):\n" +" L.append(a)\n" +" return L\n" +"\n" +"print(f(1))\n" +"print(f(2))\n" +"print(f(3))" + +#: ../../tutorial/controlflow.rst:636 msgid "This will print ::" msgstr "Isso exibirá::" -#: ../../tutorial/controlflow.rst:616 +#: ../../tutorial/controlflow.rst:638 +msgid "" +"[1]\n" +"[1, 2]\n" +"[1, 2, 3]" +msgstr "" +"[1]\n" +"[1, 2]\n" +"[1, 2, 3]" + +#: ../../tutorial/controlflow.rst:642 msgid "" "If you don't want the default to be shared between subsequent calls, you can " "write the function like this instead::" @@ -772,11 +1419,25 @@ msgstr "" "Se não quiser que o valor padrão seja compartilhado entre chamadas " "subsequentes, pode reescrever a função assim::" -#: ../../tutorial/controlflow.rst:629 +#: ../../tutorial/controlflow.rst:645 +msgid "" +"def f(a, L=None):\n" +" if L is None:\n" +" L = []\n" +" L.append(a)\n" +" return L" +msgstr "" +"def f(a, L=None):\n" +" if L is None:\n" +" L = []\n" +" L.append(a)\n" +" return L" + +#: ../../tutorial/controlflow.rst:655 msgid "Keyword Arguments" msgstr "Argumentos nomeados" -#: ../../tutorial/controlflow.rst:631 +#: ../../tutorial/controlflow.rst:657 msgid "" "Functions can also be called using :term:`keyword arguments ` of the form ``kwarg=value``. For instance, the following " @@ -785,21 +1446,74 @@ msgstr "" "Funções também podem ser chamadas usando :term:`argumentos nomeados ` da forma ``chave=valor``. Por exemplo, a função a seguir::" -#: ../../tutorial/controlflow.rst:640 +#: ../../tutorial/controlflow.rst:660 +msgid "" +"def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):\n" +" print(\"-- This parrot wouldn't\", action, end=' ')\n" +" print(\"if you put\", voltage, \"volts through it.\")\n" +" print(\"-- Lovely plumage, the\", type)\n" +" print(\"-- It's\", state, \"!\")" +msgstr "" +"def papagaio(voltagem, estado='é um cadáver', ação='voar', tipo='Azul " +"Norueguês'):\n" +" print(\"-- Este papagaio não conseguiria\", ação, end=' ')\n" +" print(\"nem se você desse um choque de\", voltagem, \"de volts nele.\")\n" +" print(\"-- Plumagem formosa, o\", tipo)\n" +" print(\"-- Ele\", estado, \"!\")" + +#: ../../tutorial/controlflow.rst:666 msgid "" "accepts one required argument (``voltage``) and three optional arguments " "(``state``, ``action``, and ``type``). This function can be called in any " "of the following ways::" msgstr "" -"aceita um argumento obrigatório (``voltage``) e três argumentos opcionais " -"(``state``, ``action``, e ``type``). Esta função pode ser chamada de " -"qualquer uma dessas formas::" - -#: ../../tutorial/controlflow.rst:651 +"aceita um argumento obrigatório (``voltagem``) e três argumentos opcionais " +"(``estado``, ``ação``, e ``tipo``). Esta função pode ser chamada de qualquer " +"uma dessas formas::" + +#: ../../tutorial/controlflow.rst:670 +msgid "" +"parrot(1000) # 1 positional " +"argument\n" +"parrot(voltage=1000) # 1 keyword argument\n" +"parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments\n" +"parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments\n" +"parrot('a million', 'bereft of life', 'jump') # 3 positional " +"arguments\n" +"parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 " +"keyword" +msgstr "" +"papagaio(1000) # 1 argumento " +"posicional\n" +"papagaio(voltagem=1000) # 1 argumento nomeado\n" +"papagaio(voltagem=1000000, ação='fazer VOOOOOM') # 2 argumentos " +"nomeados\n" +"papagaio(ação='fazer VOOOOOM', voltagem=1000000) # 2 argumentos " +"nomeados\n" +"papagaio('um milhão', 'sem vida', 'pular') # 3 argumentos " +"posicionais\n" +"papagaio('mil', estado='estaria no céu') # 1 posicional, 1 " +"argumento" + +#: ../../tutorial/controlflow.rst:677 msgid "but all the following calls would be invalid::" msgstr "mas todas as formas a seguir seriam inválidas::" -#: ../../tutorial/controlflow.rst:658 +#: ../../tutorial/controlflow.rst:679 +msgid "" +"parrot() # required argument missing\n" +"parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword " +"argument\n" +"parrot(110, voltage=220) # duplicate value for the same argument\n" +"parrot(actor='John Cleese') # unknown keyword argument" +msgstr "" +"papagaio() # faltando argumento obrigatório\n" +"papagaio(voltagem=5.0, 'morto') # argumento não nomeado após um argumento " +"nomeado\n" +"papagaio(110, voltagem=220) # valor duplicado para o mesmo argumento\n" +"papagaio(ator='John Cleese') # argumento nomeado desconhecido" + +#: ../../tutorial/controlflow.rst:684 msgid "" "In a function call, keyword arguments must follow positional arguments. All " "the keyword arguments passed must match one of the arguments accepted by the " @@ -811,13 +1525,31 @@ msgid "" msgstr "" "Em uma chamada de função, argumentos nomeados devem vir depois dos " "argumentos posicionais. Todos os argumentos nomeados passados devem " -"corresponder com argumentos aceitos pela função (ex. ``actor`` não é um " -"argumento nomeado válido para a função ``parrot``), mas sua ordem é " +"corresponder com argumentos aceitos pela função (ex. ``ator`` não é um " +"argumento nomeado válido para a função ``papagaio``), mas sua ordem é " "irrelevante. Isto também inclui argumentos obrigatórios (ex.: " -"``parrot(voltage=1000)`` funciona). Nenhum argumento pode receber mais de um " -"valor. Eis um exemplo que não funciona devido a esta restrição::" +"``papagaio(voltagem=1000)`` funciona). Nenhum argumento pode receber mais de " +"um valor. Eis um exemplo que não funciona devido a esta restrição::" + +#: ../../tutorial/controlflow.rst:692 +msgid "" +">>> def function(a):\n" +"... pass\n" +"...\n" +">>> function(0, a=0)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: function() got multiple values for argument 'a'" +msgstr "" +">>> def função(a):\n" +"... pass\n" +"...\n" +">>> função(0, a=0)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: função() got multiple values for argument 'a'" -#: ../../tutorial/controlflow.rst:674 +#: ../../tutorial/controlflow.rst:700 msgid "" "When a final formal parameter of the form ``**name`` is present, it receives " "a dictionary (see :ref:`typesmapping`) containing all keyword arguments " @@ -835,15 +1567,69 @@ msgstr "" "argumentos posicionais, além da lista de parâmetros formais. (``*nome`` deve " "ocorrer antes de ``**nome``.) Por exemplo, se definirmos uma função assim::" -#: ../../tutorial/controlflow.rst:691 +#: ../../tutorial/controlflow.rst:708 +msgid "" +"def cheeseshop(kind, *arguments, **keywords):\n" +" print(\"-- Do you have any\", kind, \"?\")\n" +" print(\"-- I'm sorry, we're all out of\", kind)\n" +" for arg in arguments:\n" +" print(arg)\n" +" print(\"-\" * 40)\n" +" for kw in keywords:\n" +" print(kw, \":\", keywords[kw])" +msgstr "" +"def loja_de_queijos(tipo, *argumentos, **argumentos_nomeados):\n" +" print(\"-- Você tem algum\", tipo, \"?\")\n" +" print(\"-- Lamento, acabou o\", tipo)\n" +" for arg in argumentos:\n" +" print(arg)\n" +" print(\"-\" * 40)\n" +" for kw in argumentos_nomeados:\n" +" print(kw, \":\", argumentos_nomeados[kw])" + +#: ../../tutorial/controlflow.rst:717 msgid "It could be called like this::" msgstr "Pode ser chamada assim::" -#: ../../tutorial/controlflow.rst:699 +#: ../../tutorial/controlflow.rst:719 +msgid "" +"cheeseshop(\"Limburger\", \"It's very runny, sir.\",\n" +" \"It's really very, VERY runny, sir.\",\n" +" shopkeeper=\"Michael Palin\",\n" +" client=\"John Cleese\",\n" +" sketch=\"Cheese Shop Sketch\")" +msgstr "" +"loja_de_queijos(\"Limburger\", \"Está muito mole, senhor\",\n" +" \"Está realmente muito, MUITO mole, senhor.\",\n" +" vendedor=\"Michael Palin\",\n" +" cliente=\"John Cleese\",\n" +" sketch=\"Sketch da Loja de Queijos\")" + +#: ../../tutorial/controlflow.rst:725 msgid "and of course it would print:" msgstr "e, claro, exibiria:" -#: ../../tutorial/controlflow.rst:712 +#: ../../tutorial/controlflow.rst:727 +msgid "" +"-- Do you have any Limburger ?\n" +"-- I'm sorry, we're all out of Limburger\n" +"It's very runny, sir.\n" +"It's really very, VERY runny, sir.\n" +"----------------------------------------\n" +"shopkeeper : Michael Palin\n" +"client : John Cleese\n" +"sketch : Cheese Shop Sketch" +msgstr "" +"-- Você tem algum Limburger ?\n" +"-- Lamento, acabou o Limburger\n" +"Está muito mole, senhor.\n" +"Está realmente muito, MUITO mole, senhor.\n" +"----------------------------------------\n" +"vendedor : Michael Palin\n" +"cliente : John Cleese\n" +"sketch : Cheese Shop Sketch" + +#: ../../tutorial/controlflow.rst:738 msgid "" "Note that the order in which the keyword arguments are printed is guaranteed " "to match the order in which they were provided in the function call." @@ -851,11 +1637,11 @@ msgstr "" "Observe que a ordem em que os argumentos nomeados são exibidos é garantida " "para corresponder à ordem em que foram fornecidos na chamada da função." -#: ../../tutorial/controlflow.rst:716 +#: ../../tutorial/controlflow.rst:742 msgid "Special parameters" msgstr "Parâmetros especiais" -#: ../../tutorial/controlflow.rst:718 +#: ../../tutorial/controlflow.rst:744 msgid "" "By default, arguments may be passed to a Python function either by position " "or explicitly by keyword. For readability and performance, it makes sense to " @@ -870,11 +1656,27 @@ msgstr "" "função para determinar se os itens são passados por posição, por posição e " "nome, ou por nome." -#: ../../tutorial/controlflow.rst:724 +#: ../../tutorial/controlflow.rst:750 msgid "A function definition may look like:" msgstr "A definição de uma função pode parecer com:" -#: ../../tutorial/controlflow.rst:735 +#: ../../tutorial/controlflow.rst:752 +msgid "" +"def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):\n" +" ----------- ---------- ----------\n" +" | | |\n" +" | Positional or keyword |\n" +" | - Keyword only\n" +" -- Positional only" +msgstr "" +"def f(pos1, pos2, /, pos_ou_kwd, *, kwd1, kwd2):\n" +" ----------- ---------- ----------\n" +" | | |\n" +" | Posicional ou nomeado |\n" +" | - Somente nomeado\n" +" -- Somente posicional" + +#: ../../tutorial/controlflow.rst:761 msgid "" "where ``/`` and ``*`` are optional. If used, these symbols indicate the kind " "of parameter by how the arguments may be passed to the function: positional-" @@ -886,11 +1688,11 @@ msgstr "" "somente-posicional, posicional-ou-nomeado, e somente-nomeado. Parâmetros " "nomeados são também conhecidos como parâmetros palavra-chave." -#: ../../tutorial/controlflow.rst:742 +#: ../../tutorial/controlflow.rst:768 msgid "Positional-or-Keyword Arguments" msgstr "Argumentos posicional-ou-nomeados" -#: ../../tutorial/controlflow.rst:744 +#: ../../tutorial/controlflow.rst:770 msgid "" "If ``/`` and ``*`` are not present in the function definition, arguments may " "be passed to a function by position or by keyword." @@ -898,11 +1700,11 @@ msgstr "" "Se ``/`` e ``*`` não estão presentes na definição da função, argumentos " "podem ser passados para uma função por posição ou por nome." -#: ../../tutorial/controlflow.rst:749 +#: ../../tutorial/controlflow.rst:775 msgid "Positional-Only Parameters" msgstr "Parâmetros somente-posicionais" -#: ../../tutorial/controlflow.rst:751 +#: ../../tutorial/controlflow.rst:777 msgid "" "Looking at this in a bit more detail, it is possible to mark certain " "parameters as *positional-only*. If *positional-only*, the parameters' order " @@ -920,7 +1722,7 @@ msgstr "" "Se não existe uma ``/`` na definição da função, não existe parâmetros " "somente-posicionais." -#: ../../tutorial/controlflow.rst:759 +#: ../../tutorial/controlflow.rst:785 msgid "" "Parameters following the ``/`` may be *positional-or-keyword* or *keyword-" "only*." @@ -928,11 +1730,11 @@ msgstr "" "Parâmetros após a ``/`` podem ser *posicional-ou-nomeado* ou *somente-" "nomeado*." -#: ../../tutorial/controlflow.rst:763 +#: ../../tutorial/controlflow.rst:789 msgid "Keyword-Only Arguments" msgstr "Argumentos somente-nomeados" -#: ../../tutorial/controlflow.rst:765 +#: ../../tutorial/controlflow.rst:791 msgid "" "To mark parameters as *keyword-only*, indicating the parameters must be " "passed by keyword argument, place an ``*`` in the arguments list just before " @@ -942,11 +1744,11 @@ msgstr "" "deve ser passado por argumento nomeado, colocamos um ``*`` na lista de " "argumentos imediatamente antes do primeiro parâmetro *somente-nomeado*." -#: ../../tutorial/controlflow.rst:771 +#: ../../tutorial/controlflow.rst:797 msgid "Function Examples" msgstr "Exemplos de funções" -#: ../../tutorial/controlflow.rst:773 +#: ../../tutorial/controlflow.rst:799 msgid "" "Consider the following example function definitions paying close attention " "to the markers ``/`` and ``*``::" @@ -954,68 +1756,220 @@ msgstr "" "Considere o seguinte exemplo de definição de função com atenção redobrada " "para os marcadores ``/`` e ``*``::" -#: ../../tutorial/controlflow.rst:789 +#: ../../tutorial/controlflow.rst:802 +msgid "" +">>> def standard_arg(arg):\n" +"... print(arg)\n" +"...\n" +">>> def pos_only_arg(arg, /):\n" +"... print(arg)\n" +"...\n" +">>> def kwd_only_arg(*, arg):\n" +"... print(arg)\n" +"...\n" +">>> def combined_example(pos_only, /, standard, *, kwd_only):\n" +"... print(pos_only, standard, kwd_only)" +msgstr "" +">>> def arg_padrão(arg):\n" +"... print(arg)\n" +"...\n" +">>> def arg_somente_pos(arg, /):\n" +"... print(arg)\n" +"...\n" +">>> def arg_somente_nom(*, arg):\n" +"... print(arg)\n" +"...\n" +">>> def exemplo_combinado(somente_pos, /, padrão, *, somente_nom):\n" +"... print(somente_pos, padrão, somente_nom)" + +#: ../../tutorial/controlflow.rst:815 msgid "" "The first function definition, ``standard_arg``, the most familiar form, " "places no restrictions on the calling convention and arguments may be passed " "by position or keyword::" msgstr "" -"A definição da primeira função, ``standard_arg``, a forma mais familiar, não " +"A definição da primeira função, ``arg_padrão``, a forma mais familiar, não " "coloca nenhuma restrição para a chamada da função e argumentos podem ser " "passados por posição ou nome::" -#: ../../tutorial/controlflow.rst:799 +#: ../../tutorial/controlflow.rst:819 +msgid "" +">>> standard_arg(2)\n" +"2\n" +"\n" +">>> standard_arg(arg=2)\n" +"2" +msgstr "" +">>> arg_padrão(2)\n" +"2\n" +"\n" +">>> arg_padrão(arg=2)\n" +"2" + +#: ../../tutorial/controlflow.rst:825 msgid "" "The second function ``pos_only_arg`` is restricted to only use positional " "parameters as there is a ``/`` in the function definition::" msgstr "" -"A segunda função ``pos_only_arg`` está restrita ao uso de parâmetros somente " -"posicionais, uma vez que existe uma ``/`` na definição da função::" +"A segunda função ``arg_somente_pos`` está restrita ao uso de parâmetros " +"somente posicionais, uma vez que existe uma ``/`` na definição da função::" -#: ../../tutorial/controlflow.rst:810 +#: ../../tutorial/controlflow.rst:828 msgid "" -"The third function ``kwd_only_args`` only allows keyword arguments as " +">>> pos_only_arg(1)\n" +"1\n" +"\n" +">>> pos_only_arg(arg=1)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: pos_only_arg() got some positional-only arguments passed as " +"keyword arguments: 'arg'" +msgstr "" +">>> arg_somente_pos(1)\n" +"1\n" +"\n" +">>> arg_somente_pos(arg=1)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: arg_somente_pos() got some positional-only arguments passed as " +"keyword arguments: 'arg'" + +#: ../../tutorial/controlflow.rst:836 +msgid "" +"The third function ``kwd_only_arg`` only allows keyword arguments as " "indicated by a ``*`` in the function definition::" msgstr "" -"A terceira função ``kwd_only_args`` permite somente argumentos nomeados como " -"indicado pelo ``*`` na definição da função::" +"A terceira função ``arg_somente_nom`` permite somente argumentos nomeados " +"como indicado pelo ``*`` na definição da função::" -#: ../../tutorial/controlflow.rst:821 +#: ../../tutorial/controlflow.rst:839 +msgid "" +">>> kwd_only_arg(3)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given\n" +"\n" +">>> kwd_only_arg(arg=3)\n" +"3" +msgstr "" +">>> arg_somente_nom(3)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: arg_somente_nom() takes 0 positional arguments but 1 was given\n" +"\n" +">>> arg_somente_nom(arg=3)\n" +"3" + +#: ../../tutorial/controlflow.rst:847 msgid "" "And the last uses all three calling conventions in the same function " "definition::" msgstr "" "E a última usa as três convenções de chamada na mesma definição de função::" -#: ../../tutorial/controlflow.rst:841 +#: ../../tutorial/controlflow.rst:850 +msgid "" +">>> combined_example(1, 2, 3)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: combined_example() takes 2 positional arguments but 3 were given\n" +"\n" +">>> combined_example(1, 2, kwd_only=3)\n" +"1 2 3\n" +"\n" +">>> combined_example(1, standard=2, kwd_only=3)\n" +"1 2 3\n" +"\n" +">>> combined_example(pos_only=1, standard=2, kwd_only=3)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: combined_example() got some positional-only arguments passed as " +"keyword arguments: 'pos_only'" +msgstr "" +">>> exemplo_combinado(1, 2, 3)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: exemplo_combinado() takes 2 positional arguments but 3 were " +"given\n" +"\n" +">>> exemplo_combinado(1, 2, somente_nom=3)\n" +"1 2 3\n" +"\n" +">>> exemplo_combinado(1, padrão=2, somente_nom=3)\n" +"1 2 3\n" +"\n" +">>> exemplo_combinado(somente_pos=1, padrão=2, somente_nom=3)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: exemplo_combinado() got some positional-only arguments passed as " +"keyword arguments: 'somente_pos'" + +#: ../../tutorial/controlflow.rst:867 msgid "" "Finally, consider this function definition which has a potential collision " "between the positional argument ``name`` and ``**kwds`` which has ``name`` " "as a key::" msgstr "" "Finalmente, considere essa definição de função que possui uma potencial " -"colisão entre o argumento posicional ``name`` e ``**kwds`` que possui " -"``name`` como uma chave::" +"colisão entre o argumento posicional ``nome`` e ``**kwds`` que possui " +"``nome`` como uma chave::" + +#: ../../tutorial/controlflow.rst:869 +msgid "" +"def foo(name, **kwds):\n" +" return 'name' in kwds" +msgstr "" +"def foo(nome, **kwds):\n" +" return 'nome' in kwds" -#: ../../tutorial/controlflow.rst:846 +#: ../../tutorial/controlflow.rst:872 msgid "" "There is no possible call that will make it return ``True`` as the keyword " "``'name'`` will always bind to the first parameter. For example::" msgstr "" -"Não é possível essa chamada devolver ``True``, uma vez que a chave " -"``'name'`` sempre será aplicada para o primeiro parâmetro. Por exemplo::" +"Não é possível essa chamada devolver ``True``, uma vez que o argumento " +"nomeado ``'nome'`` sempre será aplicado para o primeiro parâmetro. Por " +"exemplo::" + +#: ../../tutorial/controlflow.rst:875 +msgid "" +">>> foo(1, **{'name': 2})\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: foo() got multiple values for argument 'name'\n" +">>>" +msgstr "" +">>> foo(1, **{'nome': 2})\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: foo() got multiple values for argument 'nome'\n" +">>>" -#: ../../tutorial/controlflow.rst:855 +#: ../../tutorial/controlflow.rst:881 msgid "" "But using ``/`` (positional only arguments), it is possible since it allows " "``name`` as a positional argument and ``'name'`` as a key in the keyword " "arguments::" msgstr "" -"Mas usando ``/`` (somente argumentos posicionais), isso é possível já que " -"permite ``name`` como um argumento posicional e ``'name'`` como uma chave " +"Mas usando ``/`` (argumentos somente-posicionais), isso é possível já que " +"permite ``nome`` como um argumento posicional e ``'nome'`` como uma chave " "nos argumentos nomeados::" -#: ../../tutorial/controlflow.rst:863 +#: ../../tutorial/controlflow.rst:883 +msgid "" +">>> def foo(name, /, **kwds):\n" +"... return 'name' in kwds\n" +"...\n" +">>> foo(1, **{'name': 2})\n" +"True" +msgstr "" +">>> def foo(nome, /, **kwds):\n" +"... return 'nome' in kwds\n" +"...\n" +">>> foo(1, **{'nome': 2})\n" +"True" + +#: ../../tutorial/controlflow.rst:889 msgid "" "In other words, the names of positional-only parameters can be used in " "``**kwds`` without ambiguity." @@ -1023,22 +1977,26 @@ msgstr "" "Em outras palavras, o nome de parâmetros somente-posicional podem ser usados " "em ``**kwds`` sem ambiguidade." -#: ../../tutorial/controlflow.rst:868 +#: ../../tutorial/controlflow.rst:894 msgid "Recap" msgstr "Recapitulando" -#: ../../tutorial/controlflow.rst:870 +#: ../../tutorial/controlflow.rst:896 msgid "" "The use case will determine which parameters to use in the function " "definition::" msgstr "" "A situação irá determinar quais parâmetros usar na definição da função::" -#: ../../tutorial/controlflow.rst:874 +#: ../../tutorial/controlflow.rst:898 +msgid "def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):" +msgstr "def f(pos1, pos2, /, pos_ou_nom *, nom1, nom2):" + +#: ../../tutorial/controlflow.rst:900 msgid "As guidance:" msgstr "Como guia:" -#: ../../tutorial/controlflow.rst:876 +#: ../../tutorial/controlflow.rst:902 msgid "" "Use positional-only if you want the name of the parameters to not be " "available to the user. This is useful when parameter names have no real " @@ -1052,7 +2010,7 @@ msgstr "" "quando ela é chamada ou se você precisa ter alguns parâmetros posicionais e " "alguns nomeados." -#: ../../tutorial/controlflow.rst:881 +#: ../../tutorial/controlflow.rst:907 msgid "" "Use keyword-only when names have meaning and the function definition is more " "understandable by being explicit with names or you want to prevent users " @@ -1062,7 +2020,7 @@ msgstr "" "fica mais clara deixando esses nomes explícitos ou se você quer evitar que " "usuários confiem na posição dos argumentos que estão sendo passados." -#: ../../tutorial/controlflow.rst:884 +#: ../../tutorial/controlflow.rst:910 msgid "" "For an API, use positional-only to prevent breaking API changes if the " "parameter's name is modified in the future." @@ -1070,11 +2028,11 @@ msgstr "" "Para uma API, use somente-posicional para evitar quebras na mudança da API " "se os nomes dos parâmetros forem alterados no futuro." -#: ../../tutorial/controlflow.rst:890 +#: ../../tutorial/controlflow.rst:916 msgid "Arbitrary Argument Lists" msgstr "Listas de argumentos arbitrárias" -#: ../../tutorial/controlflow.rst:895 +#: ../../tutorial/controlflow.rst:921 msgid "" "Finally, the least frequently used option is to specify that a function can " "be called with an arbitrary number of arguments. These arguments will be " @@ -1086,7 +2044,15 @@ msgstr "" "em uma tupla (ver :ref:`tut-tuples`). Antes dos argumentos em número " "variável, zero ou mais argumentos normais podem estar presentes. ::" -#: ../../tutorial/controlflow.rst:904 +#: ../../tutorial/controlflow.rst:926 +msgid "" +"def write_multiple_items(file, separator, *args):\n" +" file.write(separator.join(args))" +msgstr "" +"def escreve_vários_itens(arquivo, separador, *args):\n" +" file.write(separador.join(args))" + +#: ../../tutorial/controlflow.rst:930 msgid "" "Normally, these *variadic* arguments will be last in the list of formal " "parameters, because they scoop up all remaining input arguments that are " @@ -1101,11 +2067,29 @@ msgstr "" "significa que eles só podem ser usados como chave-valor, em vez de " "argumentos posicionais::" -#: ../../tutorial/controlflow.rst:921 +#: ../../tutorial/controlflow.rst:936 +msgid "" +">>> def concat(*args, sep=\"/\"):\n" +"... return sep.join(args)\n" +"...\n" +">>> concat(\"earth\", \"mars\", \"venus\")\n" +"'earth/mars/venus'\n" +">>> concat(\"earth\", \"mars\", \"venus\", sep=\".\")\n" +"'earth.mars.venus'" +msgstr "" +">>> def concat(*args, sep=\"/\"):\n" +"... return sep.join(args)\n" +"...\n" +">>> concat(\"terra\", \"marte\", \"vênus\")\n" +"'terra/marte/vênus'\n" +">>> concat(\"terra\", \"marte\", \"vênus\", sep=\".\")\n" +"'terra.marte.vênus'" + +#: ../../tutorial/controlflow.rst:947 msgid "Unpacking Argument Lists" msgstr "Desempacotando listas de argumentos" -#: ../../tutorial/controlflow.rst:923 +#: ../../tutorial/controlflow.rst:949 msgid "" "The reverse situation occurs when the arguments are already in a list or " "tuple but need to be unpacked for a function call requiring separate " @@ -1121,7 +2105,23 @@ msgstr "" "uma lista ou tupla, escreva a chamada de função com o operador ``*`` para " "desempacotá-los da sequência::" -#: ../../tutorial/controlflow.rst:939 +#: ../../tutorial/controlflow.rst:956 +msgid "" +">>> list(range(3, 6)) # normal call with separate arguments\n" +"[3, 4, 5]\n" +">>> args = [3, 6]\n" +">>> list(range(*args)) # call with arguments unpacked from a " +"list\n" +"[3, 4, 5]" +msgstr "" +">>> list(range(3, 6)) # chamada normal com argumentos separados\n" +"[3, 4, 5]\n" +">>> args = [3, 6]\n" +">>> list(range(*args)) # chamada com argumentos desempacotados a " +"partir de uma lista\n" +"[3, 4, 5]" + +#: ../../tutorial/controlflow.rst:965 msgid "" "In the same fashion, dictionaries can deliver keyword arguments with the " "``**``\\ -operator::" @@ -1129,11 +2129,36 @@ msgstr "" "Da mesma forma, dicionários podem produzir argumentos nomeados com o " "operador ``**``::" -#: ../../tutorial/controlflow.rst:955 +#: ../../tutorial/controlflow.rst:968 +msgid "" +">>> def parrot(voltage, state='a stiff', action='voom'):\n" +"... print(\"-- This parrot wouldn't\", action, end=' ')\n" +"... print(\"if you put\", voltage, \"volts through it.\", end=' ')\n" +"... print(\"E's\", state, \"!\")\n" +"...\n" +">>> d = {\"voltage\": \"four million\", \"state\": \"bleedin' demised\", " +"\"action\": \"VOOM\"}\n" +">>> parrot(**d)\n" +"-- This parrot wouldn't VOOM if you put four million volts through it. E's " +"bleedin' demised !" +msgstr "" +">>> def papagaio(voltagem, estado='um cadáver', ação='voar'):\n" +"... print(\"-- Este papagaio não conseguiria\", ação, end=' ')\n" +"... print(\"nem se você desse um choque de\", voltagem, \"de volts nele." +"\", end=' ')\n" +"... print(\"Ele\", estado, \"!\")\n" +"...\n" +">>> d = {\"voltagem\": \"quatro milhões\", \"estado\": \"está realmente " +"morto\", \"ação\": \"voar\"}\n" +">>> papagaio(**d)\n" +"-- Este papagaio não conseguiria voar nem se você desse um choque de quatro " +"milhões de volts nele. Ele está realmente morto !" + +#: ../../tutorial/controlflow.rst:981 msgid "Lambda Expressions" msgstr "Expressões lambda" -#: ../../tutorial/controlflow.rst:957 +#: ../../tutorial/controlflow.rst:983 msgid "" "Small anonymous functions can be created with the :keyword:`lambda` keyword. " "This function returns the sum of its two arguments: ``lambda a, b: a+b``. " @@ -1151,19 +2176,54 @@ msgstr "" "função normal. Como definições de funções aninhadas, as funções lambda podem " "referenciar variáveis contidas no escopo::" -#: ../../tutorial/controlflow.rst:974 +#: ../../tutorial/controlflow.rst:991 +msgid "" +">>> def make_incrementor(n):\n" +"... return lambda x: x + n\n" +"...\n" +">>> f = make_incrementor(42)\n" +">>> f(0)\n" +"42\n" +">>> f(1)\n" +"43" +msgstr "" +">>> def cria_incrementador(n):\n" +"... return lambda x: x + n\n" +"...\n" +">>> f = cria_incrementador(42)\n" +">>> f(0)\n" +"42\n" +">>> f(1)\n" +"43" + +#: ../../tutorial/controlflow.rst:1000 msgid "" "The above example uses a lambda expression to return a function. Another " -"use is to pass a small function as an argument::" +"use is to pass a small function as an argument. For instance, :meth:`list." +"sort` takes a sorting key function *key* which can be a lambda function::" msgstr "" "O exemplo acima usa uma expressão lambda para retornar uma função. Outro uso " -"é passar uma pequena função como um argumento::" +"é passar uma pequena função como um argumento. Por exemplo, :meth:`list." +"sort` recebe uma função chave de ordenação *key* que pode ser uma função " +"lambda::" -#: ../../tutorial/controlflow.rst:986 +#: ../../tutorial/controlflow.rst:1004 +msgid "" +">>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]\n" +">>> pairs.sort(key=lambda pair: pair[1])\n" +">>> pairs\n" +"[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]" +msgstr "" +">>> pairs = [(1, 'um'), (2, 'dois'), (3, 'três), (4, 'quatro')]\n" +">>> pairs.sort(key=lambda pair: pair[1])\n" +">>> pairs\n" +"[(4, 'quatro'), (1, 'um'), (3, 'três'), (2, 'dois')]" + +#: ../../tutorial/controlflow.rst:1013 msgid "Documentation Strings" msgstr "Strings de documentação" -#: ../../tutorial/controlflow.rst:993 +#: ../../tutorial/controlflow.rst:1020 msgid "" "Here are some conventions about the content and formatting of documentation " "strings." @@ -1171,7 +2231,7 @@ msgstr "" "Aqui estão algumas convenções sobre o conteúdo e formatação de strings de " "documentação, também conhecidas como docstrings." -#: ../../tutorial/controlflow.rst:996 +#: ../../tutorial/controlflow.rst:1023 msgid "" "The first line should always be a short, concise summary of the object's " "purpose. For brevity, it should not explicitly state the object's name or " @@ -1185,7 +2245,7 @@ msgstr "" "(exceto se o nome da função for o próprio verbo que descreve a finalidade da " "função). Essa linha deve começar com letra maiúscula e terminar com ponto." -#: ../../tutorial/controlflow.rst:1002 +#: ../../tutorial/controlflow.rst:1029 msgid "" "If there are more lines in the documentation string, the second line should " "be blank, visually separating the summary from the rest of the description. " @@ -1197,7 +2257,7 @@ msgstr "" "seguintes devem conter um ou mais parágrafos descrevendo as convenções de " "chamada ao objeto, seus efeitos colaterais, etc." -#: ../../tutorial/controlflow.rst:1007 +#: ../../tutorial/controlflow.rst:1034 msgid "" "The Python parser does not strip indentation from multi-line string literals " "in Python, so tools that process documentation have to strip indentation if " @@ -1223,15 +2283,41 @@ msgstr "" "espaços à sua esquerda são removidos. A equivalência de espaços em branco " "deve ser testada após a expansão das tabulações (8 espaços, normalmente)." -#: ../../tutorial/controlflow.rst:1019 +#: ../../tutorial/controlflow.rst:1046 msgid "Here is an example of a multi-line docstring::" msgstr "Eis um exemplo de uma string de documentação multilinha::" -#: ../../tutorial/controlflow.rst:1037 +#: ../../tutorial/controlflow.rst:1048 +msgid "" +">>> def my_function():\n" +"... \"\"\"Do nothing, but document it.\n" +"...\n" +"... No, really, it doesn't do anything.\n" +"... \"\"\"\n" +"... pass\n" +"...\n" +">>> print(my_function.__doc__)\n" +"Do nothing, but document it.\n" +"\n" +"No, really, it doesn't do anything." +msgstr "" +">>> def minha_função():\n" +"... \"\"\"Não faça nada, mas documente o fato.\n" +"...\n" +"... Não, é sério, ela faz nada mesmo.\n" +"... \"\"\"\n" +"... pass\n" +"...\n" +">>> print(minha_função.__doc__)\n" +"Não faça nada, mas documente o fato.\n" +"\n" +"Não, é sério, ela faz nada mesmo." + +#: ../../tutorial/controlflow.rst:1064 msgid "Function Annotations" msgstr "Anotações de função" -#: ../../tutorial/controlflow.rst:1045 +#: ../../tutorial/controlflow.rst:1072 msgid "" ":ref:`Function annotations ` are completely optional metadata " "information about the types used by user-defined functions (see :pep:`3107` " @@ -1241,7 +2327,7 @@ msgstr "" "completamente opcionais sobre os tipos usados pelas funções definidas pelo " "usuário (veja :pep:`3107` e :pep:`484` para mais informações)." -#: ../../tutorial/controlflow.rst:1049 +#: ../../tutorial/controlflow.rst:1076 msgid "" ":term:`Annotations ` are stored in the :attr:`!" "__annotations__` attribute of the function as a dictionary and have no " @@ -1262,11 +2348,35 @@ msgstr "" "`def` . O exemplo a seguir possui um argumento obrigatório, um argumento " "opcional e o valor de retorno anotados::" -#: ../../tutorial/controlflow.rst:1071 +#: ../../tutorial/controlflow.rst:1085 +msgid "" +">>> def f(ham: str, eggs: str = 'eggs') -> str:\n" +"... print(\"Annotations:\", f.__annotations__)\n" +"... print(\"Arguments:\", ham, eggs)\n" +"... return ham + ' and ' + eggs\n" +"...\n" +">>> f('spam')\n" +"Annotations: {'ham': , 'return': , 'eggs': }\n" +"Arguments: spam eggs\n" +"'spam and eggs'" +msgstr "" +">>> def f(ham: str, ovos: str = 'ovos') -> str:\n" +"... print(\"Anotações:\", f.__annotations__)\n" +"... print(\"Argumentos:\", ham, ovos)\n" +"... return ham + ' e ' + ovos\n" +"...\n" +">>> f('spam')\n" +"Anotações: {'ham': , 'return': , 'ovos': }\n" +"Argumentos: spam ovos\n" +"'spam e ovos'" + +#: ../../tutorial/controlflow.rst:1098 msgid "Intermezzo: Coding Style" msgstr "Intermezzo: estilo de codificação" -#: ../../tutorial/controlflow.rst:1076 +#: ../../tutorial/controlflow.rst:1103 msgid "" "Now that you are about to write longer, more complex pieces of Python, it is " "a good time to talk about *coding style*. Most languages can be written (or " @@ -1281,7 +2391,7 @@ msgstr "" "ler, para os outros, é sempre uma boa ideia, e adotar um estilo de " "codificação agradável ajuda bastante." -#: ../../tutorial/controlflow.rst:1082 +#: ../../tutorial/controlflow.rst:1109 msgid "" "For Python, :pep:`8` has emerged as the style guide that most projects " "adhere to; it promotes a very readable and eye-pleasing coding style. Every " @@ -1293,11 +2403,11 @@ msgstr "" "agradável. Todo desenvolvedor Python deve lê-lo em algum momento; eis os " "pontos mais importantes, selecionados para você:" -#: ../../tutorial/controlflow.rst:1087 +#: ../../tutorial/controlflow.rst:1114 msgid "Use 4-space indentation, and no tabs." msgstr "Use indentação com 4 espaços, e não use tabulações." -#: ../../tutorial/controlflow.rst:1089 +#: ../../tutorial/controlflow.rst:1116 msgid "" "4 spaces are a good compromise between small indentation (allows greater " "nesting depth) and large indentation (easier to read). Tabs introduce " @@ -1307,11 +2417,11 @@ msgstr "" "profundidade de aninhamento) e indentação larga (mais fácil de ler). " "Tabulações trazem complicações, e o melhor é não usar." -#: ../../tutorial/controlflow.rst:1093 +#: ../../tutorial/controlflow.rst:1120 msgid "Wrap lines so that they don't exceed 79 characters." msgstr "Quebre as linhas de modo que não excedam 79 caracteres." -#: ../../tutorial/controlflow.rst:1095 +#: ../../tutorial/controlflow.rst:1122 msgid "" "This helps users with small displays and makes it possible to have several " "code files side-by-side on larger displays." @@ -1319,7 +2429,7 @@ msgstr "" "Isso ajuda os usuários com telas pequenas e torna possível abrir vários " "arquivos de código lado a lado em telas maiores." -#: ../../tutorial/controlflow.rst:1098 +#: ../../tutorial/controlflow.rst:1125 msgid "" "Use blank lines to separate functions and classes, and larger blocks of code " "inside functions." @@ -1327,15 +2437,15 @@ msgstr "" "Deixe linhas em branco para separar funções e classes, e blocos de código " "dentro de funções." -#: ../../tutorial/controlflow.rst:1101 +#: ../../tutorial/controlflow.rst:1128 msgid "When possible, put comments on a line of their own." msgstr "Quando possível, coloque comentários em uma linha própria." -#: ../../tutorial/controlflow.rst:1103 +#: ../../tutorial/controlflow.rst:1130 msgid "Use docstrings." msgstr "Escreva strings de documentação." -#: ../../tutorial/controlflow.rst:1105 +#: ../../tutorial/controlflow.rst:1132 msgid "" "Use spaces around operators and after commas, but not directly inside " "bracketing constructs: ``a = f(1, 2) + g(3, 4)``." @@ -1343,7 +2453,7 @@ msgstr "" "Use espaços ao redor de operadores e após vírgulas, mas não diretamente " "dentro de parênteses, colchetes e chaves: ``a = f(1, 2) + g(3, 4)``." -#: ../../tutorial/controlflow.rst:1108 +#: ../../tutorial/controlflow.rst:1135 msgid "" "Name your classes and functions consistently; the convention is to use " "``UpperCamelCase`` for classes and ``lowercase_with_underscores`` for " @@ -1356,7 +2466,7 @@ msgstr "" "dos métodos (veja :ref:`tut-firstclasses` para mais informações sobre " "classes e métodos)." -#: ../../tutorial/controlflow.rst:1113 +#: ../../tutorial/controlflow.rst:1140 msgid "" "Don't use fancy encodings if your code is meant to be used in international " "environments. Python's default, UTF-8, or even plain ASCII work best in any " @@ -1366,7 +2476,7 @@ msgstr "" "contexto internacional. O padrão do Python, UTF-8, ou mesmo ASCII puro " "funciona bem em qualquer caso." -#: ../../tutorial/controlflow.rst:1117 +#: ../../tutorial/controlflow.rst:1144 msgid "" "Likewise, don't use non-ASCII characters in identifiers if there is only the " "slightest chance people speaking a different language will read or maintain " @@ -1376,11 +2486,11 @@ msgstr "" "apenas a menor chance de pessoas falando um idioma diferente ler ou manter o " "código." -#: ../../tutorial/controlflow.rst:1123 +#: ../../tutorial/controlflow.rst:1150 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../tutorial/controlflow.rst:1124 +#: ../../tutorial/controlflow.rst:1151 msgid "" "Actually, *call by object reference* would be a better description, since if " "a mutable object is passed, the caller will see any changes the callee makes " @@ -1399,54 +2509,54 @@ msgstr "instrução" msgid "for" msgstr "for" -#: ../../tutorial/controlflow.rst:451 ../../tutorial/controlflow.rst:988 +#: ../../tutorial/controlflow.rst:477 ../../tutorial/controlflow.rst:1015 msgid "documentation strings" msgstr "strings, documentação" -#: ../../tutorial/controlflow.rst:451 ../../tutorial/controlflow.rst:988 +#: ../../tutorial/controlflow.rst:477 ../../tutorial/controlflow.rst:1015 msgid "docstrings" msgstr "docstrings" -#: ../../tutorial/controlflow.rst:451 ../../tutorial/controlflow.rst:988 +#: ../../tutorial/controlflow.rst:477 ../../tutorial/controlflow.rst:1015 msgid "strings, documentation" msgstr "strings, documentação" -#: ../../tutorial/controlflow.rst:892 +#: ../../tutorial/controlflow.rst:918 msgid "* (asterisk)" msgstr "* (asterisco)" -#: ../../tutorial/controlflow.rst:892 ../../tutorial/controlflow.rst:936 +#: ../../tutorial/controlflow.rst:918 ../../tutorial/controlflow.rst:962 msgid "in function calls" msgstr "em chamadas de função" -#: ../../tutorial/controlflow.rst:936 +#: ../../tutorial/controlflow.rst:962 msgid "**" msgstr "**" -#: ../../tutorial/controlflow.rst:1040 +#: ../../tutorial/controlflow.rst:1067 msgid "function" msgstr "função" -#: ../../tutorial/controlflow.rst:1040 +#: ../../tutorial/controlflow.rst:1067 msgid "annotations" msgstr "annotations" -#: ../../tutorial/controlflow.rst:1040 +#: ../../tutorial/controlflow.rst:1067 msgid "->" msgstr "->" -#: ../../tutorial/controlflow.rst:1040 +#: ../../tutorial/controlflow.rst:1067 msgid "function annotations" msgstr "anotações de função" -#: ../../tutorial/controlflow.rst:1040 +#: ../../tutorial/controlflow.rst:1067 msgid ": (colon)" msgstr ": (dois pontos)" -#: ../../tutorial/controlflow.rst:1074 +#: ../../tutorial/controlflow.rst:1101 msgid "coding" msgstr "codificação" -#: ../../tutorial/controlflow.rst:1074 +#: ../../tutorial/controlflow.rst:1101 msgid "style" msgstr "estilo" diff --git a/tutorial/datastructures.po b/tutorial/datastructures.po index 5a08f2443..9b0bcdcc8 100644 --- a/tutorial/datastructures.po +++ b/tutorial/datastructures.po @@ -1,33 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Leticia Portella , 2021 -# Cauê Baasch de Souza , 2021 -# Victor Matheus Castro , 2021 -# Adorilson Bezerra , 2022 -# Vitor Buxbaum Orlandi, 2024 -# Rafael Fontenelle , 2024 -# Leandro Cavalcante Damascena , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 01:50+0000\n" -"Last-Translator: Leandro Cavalcante Damascena , " -"2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -56,17 +48,16 @@ msgstr "" "os métodos de objetos do tipo lista:" #: ../../tutorial/datastructures.rst:22 -msgid "" -"Add an item to the end of the list. Equivalent to ``a[len(a):] = [x]``." -msgstr "Adiciona um item ao fim da lista. Equivalente a ``a[len(a):] = [x]``." +msgid "Add an item to the end of the list. Similar to ``a[len(a):] = [x]``." +msgstr "Adiciona um item ao fim da lista. Similar a ``a[len(a):] = [x]``." #: ../../tutorial/datastructures.rst:28 msgid "" -"Extend the list by appending all the items from the iterable. Equivalent to " +"Extend the list by appending all the items from the iterable. Similar to " "``a[len(a):] = iterable``." msgstr "" -"Prolonga a lista, adicionando no fim todos os elementos do argumento " -"`iterable` passado como parâmetro. Equivalente a ``a[len(a):] = iterable``." +"Estende a lista, adicionando no fim todos os elementos do argumento iterável " +"passado como parâmetro. Similar a ``a[len(a):] = iterable``." #: ../../tutorial/datastructures.rst:35 msgid "" @@ -100,8 +91,8 @@ msgstr "" "intervalo da lista." #: ../../tutorial/datastructures.rst:59 -msgid "Remove all items from the list. Equivalent to ``del a[:]``." -msgstr "Remove todos os itens de uma lista. Equivalente a ``del a[:]``." +msgid "Remove all items from the list. Similar to ``del a[:]``." +msgstr "Remove todos os itens de uma lista. Similar a ``del a[:]``." #: ../../tutorial/datastructures.rst:65 msgid "" @@ -140,13 +131,60 @@ msgid "Reverse the elements of the list in place." msgstr "Inverte a ordem dos elementos na lista." #: ../../tutorial/datastructures.rst:96 -msgid "Return a shallow copy of the list. Equivalent to ``a[:]``." -msgstr "Devolve uma cópia rasa da lista. Equivalente a ``a[:]``." +msgid "Return a shallow copy of the list. Similar to ``a[:]``." +msgstr "Devolve uma cópia rasa da lista. Similar a ``a[:]``." #: ../../tutorial/datastructures.rst:99 msgid "An example that uses most of the list methods::" msgstr "Um exemplo que usa a maior parte dos métodos das listas::" +#: ../../tutorial/datastructures.rst:101 +msgid "" +">>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', " +"'banana']\n" +">>> fruits.count('apple')\n" +"2\n" +">>> fruits.count('tangerine')\n" +"0\n" +">>> fruits.index('banana')\n" +"3\n" +">>> fruits.index('banana', 4) # Find next banana starting at position 4\n" +"6\n" +">>> fruits.reverse()\n" +">>> fruits\n" +"['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']\n" +">>> fruits.append('grape')\n" +">>> fruits\n" +"['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']\n" +">>> fruits.sort()\n" +">>> fruits\n" +"['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']\n" +">>> fruits.pop()\n" +"'pear'" +msgstr "" +">>> frutas = ['laranja', 'maçã', 'pera', 'banana', 'kiwi', 'maçã', " +"'banana']\n" +">>> frutas.count('maçã')\n" +"2\n" +">>> frutas.count('tangerina')\n" +"0\n" +">>> frutas.index('banana')\n" +"3\n" +">>> frutas.index('banana', 4) # Encontra a próxima banana iniciando da " +"posição 4\n" +"6\n" +">>> frutas.reverse()\n" +">>> frutas\n" +"['banana', 'maçã', 'kiwi', 'banana', 'pera', 'maçã', 'laranja']\n" +">>> frutas.append('uva')\n" +">>> frutas\n" +"['banana', 'maçã', 'kiwi', 'banana', 'pera', 'maçã', 'laranja', 'uva']\n" +">>> frutas.sort()\n" +">>> frutas\n" +"['maçã', 'maçã', 'banana', 'banana', 'uva', 'kiwi', 'laranja', 'pera']\n" +">>> frutas.pop()\n" +"'pera'" + #: ../../tutorial/datastructures.rst:122 msgid "" "You might have noticed that methods like ``insert``, ``remove`` or ``sort`` " @@ -182,15 +220,49 @@ msgstr "Usando listas como pilhas" msgid "" "The list methods make it very easy to use a list as a stack, where the last " "element added is the first element retrieved (\"last-in, first-out\"). To " -"add an item to the top of the stack, use :meth:`~list.append`. To retrieve " -"an item from the top of the stack, use :meth:`~list.pop` without an explicit " -"index. For example::" +"add an item to the top of the stack, use :meth:`!append`. To retrieve an " +"item from the top of the stack, use :meth:`!pop` without an explicit index. " +"For example::" msgstr "" "Os métodos de lista tornam muito fácil utilizar listas como pilhas, onde o " "item adicionado por último é o primeiro a ser recuperado (política “último a " "entrar, primeiro a sair”). Para adicionar um item ao topo da pilha, use :" -"meth:`~list.append`. Para recuperar um item do topo da pilha use :meth:" -"`~list.pop` sem nenhum índice explícito. Por exemplo::" +"meth:`!append`. Para recuperar um item do topo da pilha use :meth:`!pop` sem " +"nenhum índice. Por exemplo::" + +#: ../../tutorial/datastructures.rst:148 +msgid "" +">>> stack = [3, 4, 5]\n" +">>> stack.append(6)\n" +">>> stack.append(7)\n" +">>> stack\n" +"[3, 4, 5, 6, 7]\n" +">>> stack.pop()\n" +"7\n" +">>> stack\n" +"[3, 4, 5, 6]\n" +">>> stack.pop()\n" +"6\n" +">>> stack.pop()\n" +"5\n" +">>> stack\n" +"[3, 4]" +msgstr "" +">>> pilha = [3, 4, 5]\n" +">>> pilha.append(6)\n" +">>> pilha.append(7)\n" +">>> pilha\n" +"[3, 4, 5, 6, 7]\n" +">>> pilha.pop()\n" +"7\n" +">>> pilha\n" +"[3, 4, 5, 6]\n" +">>> pilha.pop()\n" +"6\n" +">>> pilha.pop()\n" +"5\n" +">>> pilha\n" +"[3, 4]" #: ../../tutorial/datastructures.rst:168 msgid "Using Lists as Queues" @@ -220,9 +292,33 @@ msgstr "" "projetada para permitir *appends* e *pops* eficientes nas duas extremidades. " "Por exemplo::" +#: ../../tutorial/datastructures.rst:181 +msgid "" +">>> from collections import deque\n" +">>> queue = deque([\"Eric\", \"John\", \"Michael\"])\n" +">>> queue.append(\"Terry\") # Terry arrives\n" +">>> queue.append(\"Graham\") # Graham arrives\n" +">>> queue.popleft() # The first to arrive now leaves\n" +"'Eric'\n" +">>> queue.popleft() # The second to arrive now leaves\n" +"'John'\n" +">>> queue # Remaining queue in order of arrival\n" +"deque(['Michael', 'Terry', 'Graham'])" +msgstr "" +">>> from collections import deque\n" +">>> fila = deque([\"Erik\", \"João\", \"Miguel\"])\n" +">>> fila.append(\"Tiago\") # Tiago chega\n" +">>> fila.append(\"George\") # George chega\n" +">>> fila.popleft() # O primeiro a chegar agora sai\n" +"'Erik'\n" +">>> fila.popleft() # O segundo a chegar agora sai\n" +"'João'\n" +">>> fila # A fila restante na ordem de chegada\n" +"deque(['Miguel', 'Tiago', 'George'])" + #: ../../tutorial/datastructures.rst:196 msgid "List Comprehensions" -msgstr "Compreensões de lista" +msgstr "List Comprehensions" #: ../../tutorial/datastructures.rst:198 msgid "" @@ -243,6 +339,22 @@ msgid "For example, assume we want to create a list of squares, like::" msgstr "" "Por exemplo, suponha que queremos criar uma lista de quadrados, assim::" +#: ../../tutorial/datastructures.rst:205 +msgid "" +">>> squares = []\n" +">>> for x in range(10):\n" +"... squares.append(x**2)\n" +"...\n" +">>> squares\n" +"[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]" +msgstr "" +">>> quadrados = []\n" +">>> for x in range(10):\n" +"... quadrados.append(x**2)\n" +"...\n" +">>> quadrados\n" +"[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]" + #: ../../tutorial/datastructures.rst:212 msgid "" "Note that this creates (or overwrites) a variable named ``x`` that still " @@ -253,10 +365,18 @@ msgstr "" "existe após o término do laço. Podemos calcular a lista dos quadrados sem " "qualquer efeito colateral usando::" +#: ../../tutorial/datastructures.rst:216 +msgid "squares = list(map(lambda x: x**2, range(10)))" +msgstr "quadrados = list(map(lambda x: x**2, range(10)))" + #: ../../tutorial/datastructures.rst:218 msgid "or, equivalently::" msgstr "ou, de maneira equivalente::" +#: ../../tutorial/datastructures.rst:220 +msgid "squares = [x**2 for x in range(10)]" +msgstr "quadrados = [x**2 for x in range(10)]" + #: ../../tutorial/datastructures.rst:222 msgid "which is more concise and readable." msgstr "que é mais conciso e legível." @@ -277,10 +397,38 @@ msgstr "" "for` e :keyword:`!if`. Por exemplo, essa compreensão combina os elementos de " "duas listas se eles forem diferentes::" +#: ../../tutorial/datastructures.rst:231 +msgid "" +">>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]\n" +"[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]" +msgstr "" +">>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]\n" +"[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]" + #: ../../tutorial/datastructures.rst:234 msgid "and it's equivalent to::" msgstr "e é equivalente a::" +#: ../../tutorial/datastructures.rst:236 +msgid "" +">>> combs = []\n" +">>> for x in [1,2,3]:\n" +"... for y in [3,1,4]:\n" +"... if x != y:\n" +"... combs.append((x, y))\n" +"...\n" +">>> combs\n" +"[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]" +msgstr "" +">>> combos = []\n" +">>> for x in [1,2,3]:\n" +"... for y in [3,1,4]:\n" +"... if x != y:\n" +"... combos.append((x, y))\n" +"...\n" +">>> combos\n" +"[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]" + #: ../../tutorial/datastructures.rst:245 msgid "" "Note how the order of the :keyword:`for` and :keyword:`if` statements is the " @@ -297,12 +445,81 @@ msgstr "" "Se a expressão é uma tupla (ex., ``(x, y)`` no exemplo anterior), ela deve " "ser inserida entre parênteses. ::" +#: ../../tutorial/datastructures.rst:251 +msgid "" +">>> vec = [-4, -2, 0, 2, 4]\n" +">>> # create a new list with the values doubled\n" +">>> [x*2 for x in vec]\n" +"[-8, -4, 0, 4, 8]\n" +">>> # filter the list to exclude negative numbers\n" +">>> [x for x in vec if x >= 0]\n" +"[0, 2, 4]\n" +">>> # apply a function to all the elements\n" +">>> [abs(x) for x in vec]\n" +"[4, 2, 0, 2, 4]\n" +">>> # call a method on each element\n" +">>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']\n" +">>> [weapon.strip() for weapon in freshfruit]\n" +"['banana', 'loganberry', 'passion fruit']\n" +">>> # create a list of 2-tuples like (number, square)\n" +">>> [(x, x**2) for x in range(6)]\n" +"[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]\n" +">>> # the tuple must be parenthesized, otherwise an error is raised\n" +">>> [x, x**2 for x in range(6)]\n" +" File \"\", line 1\n" +" [x, x**2 for x in range(6)]\n" +" ^^^^^^^\n" +"SyntaxError: did you forget parentheses around the comprehension target?\n" +">>> # flatten a list using a listcomp with two 'for'\n" +">>> vec = [[1,2,3], [4,5,6], [7,8,9]]\n" +">>> [num for elem in vec for num in elem]\n" +"[1, 2, 3, 4, 5, 6, 7, 8, 9]" +msgstr "" +">>> vec = [-4, -2, 0, 2, 4]\n" +">>> # cria uma nova lista com os valores dobrados\n" +">>> [x*2 for x in vec]\n" +"[-8, -4, 0, 4, 8]\n" +">>> # filtra a lista para excluir números negativos\n" +">>> [x for x in vec if x >= 0]\n" +"[0, 2, 4]\n" +">>> # aplica uma função para todos os elementos\n" +">>> [abs(x) for x in vec]\n" +"[4, 2, 0, 2, 4]\n" +">>> # chama um método em cada elemento\n" +">>> frutafresca = [' banana', ' baga-de-logan ', 'maracujá ']\n" +">>> [arma.strip() for arma in frutafresca]\n" +"['banana', 'baga-de-logan', 'maracujá']\n" +">>> # cria uma lista de tuplas de 2 elementos como (número, quadrado)\n" +">>> [(x, x**2) for x in range(6)]\n" +"[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]\n" +">>> # a tupla deve estar entre parênteses, do contrário um erro é levantado\n" +">>> [x, x**2 for x in range(6)]\n" +" File \"\", line 1\n" +" [x, x**2 for x in range(6)]\n" +" ^^^^^^^\n" +"SyntaxError: did you forget parentheses around the comprehension target?\n" +">>> # achatamento de uma lista usando uma compreensão de lista com dois " +"'for'\n" +">>> vec = [[1,2,3], [4,5,6], [7,8,9]]\n" +">>> [num for elem in vec for num in elem]\n" +"[1, 2, 3, 4, 5, 6, 7, 8, 9]" + #: ../../tutorial/datastructures.rst:279 msgid "" "List comprehensions can contain complex expressions and nested functions::" msgstr "" "Compreensões de lista podem conter expressões complexas e funções aninhadas::" +#: ../../tutorial/datastructures.rst:281 +msgid "" +">>> from math import pi\n" +">>> [str(round(pi, i)) for i in range(1, 6)]\n" +"['3.1', '3.14', '3.142', '3.1416', '3.14159']" +msgstr "" +">>> from math import pi\n" +">>> [str(round(pi, i)) for i in range(1, 6)]\n" +"['3.1', '3.14', '3.142', '3.1416', '3.14159']" + #: ../../tutorial/datastructures.rst:286 msgid "Nested List Comprehensions" msgstr "Compreensões de lista aninhadas" @@ -323,10 +540,32 @@ msgstr "" "Observe este exemplo de uma matriz 3x4 implementada como uma lista de 3 " "listas de comprimento 4::" +#: ../../tutorial/datastructures.rst:294 +msgid "" +">>> matrix = [\n" +"... [1, 2, 3, 4],\n" +"... [5, 6, 7, 8],\n" +"... [9, 10, 11, 12],\n" +"... ]" +msgstr "" +">>> matriz = [\n" +"... [1, 2, 3, 4],\n" +"... [5, 6, 7, 8],\n" +"... [9, 10, 11, 12],\n" +"... ]" + #: ../../tutorial/datastructures.rst:300 msgid "The following list comprehension will transpose rows and columns::" msgstr "A compreensão de lista abaixo transpõe as linhas e colunas::" +#: ../../tutorial/datastructures.rst:302 +msgid "" +">>> [[row[i] for row in matrix] for i in range(4)]\n" +"[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]" +msgstr "" +">>> [[linha[i] for linha in matriz] for i in range(4)]\n" +"[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]" + #: ../../tutorial/datastructures.rst:305 msgid "" "As we saw in the previous section, the inner list comprehension is evaluated " @@ -337,10 +576,51 @@ msgstr "" "contexto da cláusula :keyword:`for` seguinte, portanto o exemplo acima " "equivale a::" +#: ../../tutorial/datastructures.rst:309 +msgid "" +">>> transposed = []\n" +">>> for i in range(4):\n" +"... transposed.append([row[i] for row in matrix])\n" +"...\n" +">>> transposed\n" +"[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]" +msgstr "" +">>> transposta = []\n" +">>> for i in range(4):\n" +"... transposta.append([row[i] for linha in matriz])\n" +"...\n" +">>> transposta\n" +"[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]" + #: ../../tutorial/datastructures.rst:316 msgid "which, in turn, is the same as::" msgstr "e isso, por sua vez, faz o mesmo que isto::" +#: ../../tutorial/datastructures.rst:318 +msgid "" +">>> transposed = []\n" +">>> for i in range(4):\n" +"... # the following 3 lines implement the nested listcomp\n" +"... transposed_row = []\n" +"... for row in matrix:\n" +"... transposed_row.append(row[i])\n" +"... transposed.append(transposed_row)\n" +"...\n" +">>> transposed\n" +"[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]" +msgstr "" +">>> transposta = []\n" +">>> for i in range(4):\n" +"... # as 3 linhas a seguir implementam uma compreensão de lista " +"aninhada\n" +"... linha_transposta = []\n" +"... for linha in matriz:\n" +"... linha_transposta.append(linha[i])\n" +"... transposta.append(linha_transposta)\n" +"...\n" +">>> transposta\n" +"[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]" + #: ../../tutorial/datastructures.rst:329 msgid "" "In the real world, you should prefer built-in functions to complex flow " @@ -350,6 +630,14 @@ msgstr "" "instruções complexas. A função :func:`zip` resolve muito bem este caso de " "uso::" +#: ../../tutorial/datastructures.rst:332 +msgid "" +">>> list(zip(*matrix))\n" +"[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]" +msgstr "" +">>> list(zip(*matriz))\n" +"[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]" + #: ../../tutorial/datastructures.rst:335 msgid "" "See :ref:`tut-unpacking-arguments` for details on the asterisk in this line." @@ -364,23 +652,50 @@ msgstr "A instrução :keyword:`!del`" #: ../../tutorial/datastructures.rst:342 msgid "" "There is a way to remove an item from a list given its index instead of its " -"value: the :keyword:`del` statement. This differs from the :meth:`~list." -"pop` method which returns a value. The :keyword:`!del` statement can also " -"be used to remove slices from a list or clear the entire list (which we did " +"value: the :keyword:`del` statement. This differs from the :meth:`!pop` " +"method which returns a value. The :keyword:`!del` statement can also be " +"used to remove slices from a list or clear the entire list (which we did " "earlier by assignment of an empty list to the slice). For example::" msgstr "" "Existe uma maneira de remover um item de uma lista usando seu índice no " -"lugar do seu valor: a instrução :keyword:`del`. Ele difere do método :meth:" -"`~list.pop` que devolve um valor. A instrução :keyword:`!del` pode também " -"ser utilizada para remover fatias de uma lista ou limpar a lista inteira " -"(que fizemos antes por atribuição de uma lista vazia à fatia ``a[:]``). Por " -"exemplo::" +"lugar do seu valor: a instrução :keyword:`del`. Ele difere do método :meth:`!" +"pop` que devolve um valor. A instrução :keyword:`!del` pode também ser " +"utilizada para remover fatias de uma lista ou limpar a lista inteira (que " +"fizemos antes atribuindo uma lista vazia à fatia ``a[:]``). Por exemplo::" + +#: ../../tutorial/datastructures.rst:348 +msgid "" +">>> a = [-1, 1, 66.25, 333, 333, 1234.5]\n" +">>> del a[0]\n" +">>> a\n" +"[1, 66.25, 333, 333, 1234.5]\n" +">>> del a[2:4]\n" +">>> a\n" +"[1, 66.25, 1234.5]\n" +">>> del a[:]\n" +">>> a\n" +"[]" +msgstr "" +">>> a = [-1, 1, 66.25, 333, 333, 1234.5]\n" +">>> del a[0]\n" +">>> a\n" +"[1, 66.25, 333, 333, 1234.5]\n" +">>> del a[2:4]\n" +">>> a\n" +"[1, 66.25, 1234.5]\n" +">>> del a[:]\n" +">>> a\n" +"[]" #: ../../tutorial/datastructures.rst:359 msgid ":keyword:`del` can also be used to delete entire variables::" msgstr "" ":keyword:`del` também pode ser usado para remover totalmente uma variável::" +#: ../../tutorial/datastructures.rst:361 +msgid ">>> del a" +msgstr ">>> del a" + #: ../../tutorial/datastructures.rst:363 msgid "" "Referencing the name ``a`` hereafter is an error (at least until another " @@ -415,6 +730,46 @@ msgstr "" "Uma tupla consiste em uma sequência de valores separados por vírgulas, por " "exemplo::" +#: ../../tutorial/datastructures.rst:380 +msgid "" +">>> t = 12345, 54321, 'hello!'\n" +">>> t[0]\n" +"12345\n" +">>> t\n" +"(12345, 54321, 'hello!')\n" +">>> # Tuples may be nested:\n" +">>> u = t, (1, 2, 3, 4, 5)\n" +">>> u\n" +"((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))\n" +">>> # Tuples are immutable:\n" +">>> t[0] = 88888\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: 'tuple' object does not support item assignment\n" +">>> # but they can contain mutable objects:\n" +">>> v = ([1, 2, 3], [3, 2, 1])\n" +">>> v\n" +"([1, 2, 3], [3, 2, 1])" +msgstr "" +">>> t = 12345, 54321, 'olá!'\n" +">>> t[0]\n" +"12345\n" +">>> t\n" +"(12345, 54321, 'olá!')\n" +">>> # Tuplas pode ser aninhadas:\n" +">>> u = t, (1, 2, 3, 4, 5)\n" +">>> u\n" +"((12345, 54321, 'olá!'), (1, 2, 3, 4, 5))\n" +">>> # Tuplas são imutáveis:\n" +">>> t[0] = 88888\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: 'tuple' object does not support item assignment\n" +">>> # mas elas podem conter objetos mutáveis:\n" +">>> v = ([1, 2, 3], [3, 2, 1])\n" +">>> v\n" +"([1, 2, 3], [3, 2, 1])" + #: ../../tutorial/datastructures.rst:400 msgid "" "As you see, on output tuples are always enclosed in parentheses, so that " @@ -461,8 +816,28 @@ msgstr "" "Um problema especial é a criação de tuplas contendo 0 ou 1 itens: a sintaxe " "usa certos truques para acomodar estes casos. Tuplas vazias são construídas " "por um par de parênteses vazios; uma tupla unitária é construída por um " -"único valor e uma vírgula entre parênteses (não basta colocar um único valor " -"entre parênteses). Feio, mas funciona. Por exemplo::" +"único valor seguido de uma vírgula (não basta colocar um único valor entre " +"parênteses). Feio, mas funciona. Por exemplo::" + +#: ../../tutorial/datastructures.rst:421 +msgid "" +">>> empty = ()\n" +">>> singleton = 'hello', # <-- note trailing comma\n" +">>> len(empty)\n" +"0\n" +">>> len(singleton)\n" +"1\n" +">>> singleton\n" +"('hello',)" +msgstr "" +">>> vazio = ()\n" +">>> unitário = 'olá', # >> len(vazio)\n" +"0\n" +">>> len(unitário)\n" +"1\n" +">>> unitário\n" +"('olá',)" #: ../../tutorial/datastructures.rst:430 msgid "" @@ -474,6 +849,10 @@ msgstr "" "de tupla*: os valores ``12345``, ``54321`` e ``'bom dia!'`` são empacotados " "em uma tupla. A operação inversa também é possível::" +#: ../../tutorial/datastructures.rst:434 +msgid ">>> x, y, z = t" +msgstr ">>> x, y, z = t" + #: ../../tutorial/datastructures.rst:436 msgid "" "This is called, appropriately enough, *sequence unpacking* and works for any " @@ -524,6 +903,56 @@ msgstr "" msgid "Here is a brief demonstration::" msgstr "Uma pequena demonstração::" +#: ../../tutorial/datastructures.rst:459 +msgid "" +">>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}\n" +">>> print(basket) # show that duplicates have been " +"removed\n" +"{'orange', 'banana', 'pear', 'apple'}\n" +">>> 'orange' in basket # fast membership testing\n" +"True\n" +">>> 'crabgrass' in basket\n" +"False\n" +"\n" +">>> # Demonstrate set operations on unique letters from two words\n" +">>>\n" +">>> a = set('abracadabra')\n" +">>> b = set('alacazam')\n" +">>> a # unique letters in a\n" +"{'a', 'r', 'b', 'c', 'd'}\n" +">>> a - b # letters in a but not in b\n" +"{'r', 'd', 'b'}\n" +">>> a | b # letters in a or b or both\n" +"{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}\n" +">>> a & b # letters in both a and b\n" +"{'a', 'c'}\n" +">>> a ^ b # letters in a or b but not both\n" +"{'r', 'd', 'b', 'm', 'z', 'l'}" +msgstr "" +">>> cesta = {'maçã', 'laranja', 'maçã', 'pera', 'laranja', 'banana'}\n" +">>> print(cesta) # mostra que itens duplicados foram " +"removidos\n" +"{'laranja', 'banana', 'pera', 'maçã'}\n" +">>> 'laranja' in cesta # teste de pertinência rápido\n" +"True\n" +">>> 'crabgrass' in cesta\n" +"False\n" +"\n" +">>> # Demonstra operações de conjunto em letras únicas de duas palavras\n" +">>>\n" +">>> a = set('abracadabra')\n" +">>> b = set('alacazam')\n" +">>> a # letras únicas em a\n" +"{'a', 'r', 'b', 'c', 'd'}\n" +">>> a - b # letras em a, mas não em b\n" +"{'r', 'd', 'b'}\n" +">>> a | b # letras em a ou em b ou ambos\n" +"{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}\n" +">>> a & b # letras em ambos a e b\n" +"{'a', 'c'}\n" +">>> a ^ b # letras em a ou b, mas não em ambos\n" +"{'r', 'd', 'b', 'm', 'z', 'l'}" + #: ../../tutorial/datastructures.rst:482 msgid "" "Similarly to :ref:`list comprehensions `, set comprehensions " @@ -532,6 +961,16 @@ msgstr "" "Da mesma forma que :ref:`compreensão de listas `, " "compreensões de conjunto também são suportadas::" +#: ../../tutorial/datastructures.rst:485 +msgid "" +">>> a = {x for x in 'abracadabra' if x not in 'abc'}\n" +">>> a\n" +"{'r', 'd'}" +msgstr "" +">>> a = {x for x in 'abracadabra' if x not in 'abc'}\n" +">>> a\n" +"{'r', 'd'}" + #: ../../tutorial/datastructures.rst:493 msgid "Dictionaries" msgstr "Dicionários" @@ -546,10 +985,10 @@ msgid "" "can be used as keys if they contain only strings, numbers, or tuples; if a " "tuple contains any mutable object either directly or indirectly, it cannot " "be used as a key. You can't use lists as keys, since lists can be modified " -"in place using index assignments, slice assignments, or methods like :meth:" -"`~list.append` and :meth:`~list.extend`." +"in place using index assignments, slice assignments, or methods like :meth:`!" +"append` and :meth:`!extend`." msgstr "" -"Outra estrutura de dados muito útil embutida em Python é o *dicionário*, " +"Outra estrutura de dados embutida muito útil em Python é o *dicionário*, " "cujo tipo é ``dict`` (ver :ref:`typesmapping`). Dicionários são também " "chamados de “memória associativa” ou “vetor associativo” em outras " "linguagens. Diferente de sequências que são indexadas por inteiros, " @@ -559,7 +998,7 @@ msgstr "" "direta ou indiretamente, qualquer valor mutável, não poderá ser chave. " "Listas não podem ser usadas como chaves porque podem ser modificadas " "*internamente* pela atribuição em índices ou fatias, e por métodos como :" -"meth:`~list.append` e :meth:`~list.extend`." +"meth:`!append` e :meth:`!extend`." #: ../../tutorial/datastructures.rst:506 msgid "" @@ -606,6 +1045,46 @@ msgstr "" msgid "Here is a small example using a dictionary::" msgstr "A seguir, um exemplo de uso do dicionário::" +#: ../../tutorial/datastructures.rst:525 +msgid "" +">>> tel = {'jack': 4098, 'sape': 4139}\n" +">>> tel['guido'] = 4127\n" +">>> tel\n" +"{'jack': 4098, 'sape': 4139, 'guido': 4127}\n" +">>> tel['jack']\n" +"4098\n" +">>> del tel['sape']\n" +">>> tel['irv'] = 4127\n" +">>> tel\n" +"{'jack': 4098, 'guido': 4127, 'irv': 4127}\n" +">>> list(tel)\n" +"['jack', 'guido', 'irv']\n" +">>> sorted(tel)\n" +"['guido', 'irv', 'jack']\n" +">>> 'guido' in tel\n" +"True\n" +">>> 'jack' not in tel\n" +"False" +msgstr "" +">>> tel = {'jack': 4098, 'sape': 4139}\n" +">>> tel['guido'] = 4127\n" +">>> tel\n" +"{'jack': 4098, 'sape': 4139, 'guido': 4127}\n" +">>> tel['jack']\n" +"4098\n" +">>> del tel['sape']\n" +">>> tel['irv'] = 4127\n" +">>> tel\n" +"{'jack': 4098, 'guido': 4127, 'irv': 4127}\n" +">>> list(tel)\n" +"['jack', 'guido', 'irv']\n" +">>> sorted(tel)\n" +"['guido', 'irv', 'jack']\n" +">>> 'guido' in tel\n" +"True\n" +">>> 'jack' not in tel\n" +"False" + #: ../../tutorial/datastructures.rst:544 msgid "" "The :func:`dict` constructor builds dictionaries directly from sequences of " @@ -614,6 +1093,14 @@ msgstr "" "O construtor :func:`dict` produz dicionários diretamente de sequências de " "pares chave-valor::" +#: ../../tutorial/datastructures.rst:547 +msgid "" +">>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])\n" +"{'sape': 4139, 'guido': 4127, 'jack': 4098}" +msgstr "" +">>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])\n" +"{'sape': 4139, 'guido': 4127, 'jack': 4098}" + #: ../../tutorial/datastructures.rst:550 msgid "" "In addition, dict comprehensions can be used to create dictionaries from " @@ -622,6 +1109,14 @@ msgstr "" "Além disso, as compreensões de dicionários podem ser usadas para criar " "dicionários a partir de expressões arbitrárias de chave e valor::" +#: ../../tutorial/datastructures.rst:553 +msgid "" +">>> {x: x**2 for x in (2, 4, 6)}\n" +"{2: 4, 4: 16, 6: 36}" +msgstr "" +">>> {x: x**2 for x in (2, 4, 6)}\n" +"{2: 4, 4: 16, 6: 36}" + #: ../../tutorial/datastructures.rst:556 msgid "" "When the keys are simple strings, it is sometimes easier to specify pairs " @@ -630,6 +1125,14 @@ msgstr "" "Quando chaves são strings simples, é mais fácil especificar os pares usando " "argumentos nomeados no construtor::" +#: ../../tutorial/datastructures.rst:559 +msgid "" +">>> dict(sape=4139, guido=4127, jack=4098)\n" +"{'sape': 4139, 'guido': 4127, 'jack': 4098}" +msgstr "" +">>> dict(sape=4139, guido=4127, jack=4098)\n" +"{'sape': 4139, 'guido': 4127, 'jack': 4098}" + #: ../../tutorial/datastructures.rst:566 msgid "Looping Techniques" msgstr "Técnicas de iteração" @@ -642,6 +1145,22 @@ msgstr "" "Ao iterar sobre dicionários, a chave e o valor correspondente podem ser " "obtidos simultaneamente usando o método :meth:`~dict.items`. ::" +#: ../../tutorial/datastructures.rst:571 +msgid "" +">>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}\n" +">>> for k, v in knights.items():\n" +"... print(k, v)\n" +"...\n" +"gallahad the pure\n" +"robin the brave" +msgstr "" +">>> cavaleiros = {'gallahad': 'o puro', 'robin': 'o bravo'}\n" +">>> for k, v in cavaleiros.items():\n" +"... print(k, v)\n" +"...\n" +"gallahad o puro\n" +"robin o bravo" + #: ../../tutorial/datastructures.rst:578 msgid "" "When looping through a sequence, the position index and corresponding value " @@ -650,6 +1169,22 @@ msgstr "" "Ao iterar sobre sequências, a posição e o valor correspondente podem ser " "obtidos simultaneamente usando a função :func:`enumerate`. ::" +#: ../../tutorial/datastructures.rst:581 +msgid "" +">>> for i, v in enumerate(['tic', 'tac', 'toe']):\n" +"... print(i, v)\n" +"...\n" +"0 tic\n" +"1 tac\n" +"2 toe" +msgstr "" +">>> for i, v in enumerate(['jogo', 'da', 'velha']):\n" +"... print(i, v)\n" +"...\n" +"0 jogo\n" +"1 da\n" +"2 velha" + #: ../../tutorial/datastructures.rst:588 msgid "" "To loop over two or more sequences at the same time, the entries can be " @@ -658,6 +1193,26 @@ msgstr "" "Para percorrer duas ou mais sequências ao mesmo tempo, as entradas podem ser " "pareadas com a função :func:`zip`. ::" +#: ../../tutorial/datastructures.rst:591 +msgid "" +">>> questions = ['name', 'quest', 'favorite color']\n" +">>> answers = ['lancelot', 'the holy grail', 'blue']\n" +">>> for q, a in zip(questions, answers):\n" +"... print('What is your {0}? It is {1}.'.format(q, a))\n" +"...\n" +"What is your name? It is lancelot.\n" +"What is your quest? It is the holy grail.\n" +"What is your favorite color? It is blue." +msgstr "" +">>> perguntas = ['Nome', 'Missão', 'Cor favorita']\n" +">>> respostas = ['Lancelot', 'o santo graal', 'azul']\n" +">>> for q, a in zip(perguntas, respostas):\n" +"... print('{0}? É {1}.'.format(q, a))\n" +"...\n" +"Nome? É Lancelot.\n" +"Missão? É o santo graal.\n" +"Cor favorita? É azul." + #: ../../tutorial/datastructures.rst:600 msgid "" "To loop over a sequence in reverse, first specify the sequence in a forward " @@ -666,6 +1221,26 @@ msgstr "" "Para percorrer uma sequência em ordem inversa, chame a função :func:" "`reversed` com a sequência na ordem original. ::" +#: ../../tutorial/datastructures.rst:603 +msgid "" +">>> for i in reversed(range(1, 10, 2)):\n" +"... print(i)\n" +"...\n" +"9\n" +"7\n" +"5\n" +"3\n" +"1" +msgstr "" +">>> for i in reversed(range(1, 10, 2)):\n" +"... print(i)\n" +"...\n" +"9\n" +"7\n" +"5\n" +"3\n" +"1" + #: ../../tutorial/datastructures.rst:612 msgid "" "To loop over a sequence in sorted order, use the :func:`sorted` function " @@ -675,6 +1250,30 @@ msgstr "" "`sorted`, que retorna uma lista ordenada com os itens, mantendo a sequência " "original inalterada. ::" +#: ../../tutorial/datastructures.rst:615 +msgid "" +">>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']\n" +">>> for i in sorted(basket):\n" +"... print(i)\n" +"...\n" +"apple\n" +"apple\n" +"banana\n" +"orange\n" +"orange\n" +"pear" +msgstr "" +">>> cesta = ['maçã', 'laranja', 'maçã', 'pera', 'laranja', 'banana']\n" +">>> for i in sorted(cesta):\n" +"... print(i)\n" +"...\n" +"maçã\n" +"maçã\n" +"banana\n" +"laranja\n" +"laranja\n" +"pera" + #: ../../tutorial/datastructures.rst:626 msgid "" "Using :func:`set` on a sequence eliminates duplicate elements. The use of :" @@ -687,6 +1286,28 @@ msgstr "" "maneira idiomática de fazer um loop sobre elementos exclusivos da sequência " "na ordem de classificação. ::" +#: ../../tutorial/datastructures.rst:630 +msgid "" +">>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']\n" +">>> for f in sorted(set(basket)):\n" +"... print(f)\n" +"...\n" +"apple\n" +"banana\n" +"orange\n" +"pear" +msgstr "" +">>> cesta = ['maçã', 'laranja', 'maçã', 'pera', 'laranja', 'banana']\n" +">>> for i in sorted(cesta):\n" +"... print(i)\n" +"...\n" +"maçã\n" +"maçã\n" +"banana\n" +"laranja\n" +"laranja\n" +"pera" + #: ../../tutorial/datastructures.rst:639 msgid "" "It is sometimes tempting to change a list while you are looping over it; " @@ -695,6 +1316,29 @@ msgstr "" "Às vezes é tentador alterar uma lista enquanto você itera sobre ela; porém, " "costuma ser mais simples e seguro criar uma nova lista. ::" +#: ../../tutorial/datastructures.rst:642 +msgid "" +">>> import math\n" +">>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]\n" +">>> filtered_data = []\n" +">>> for value in raw_data:\n" +"... if not math.isnan(value):\n" +"... filtered_data.append(value)\n" +"...\n" +">>> filtered_data\n" +"[56.2, 51.7, 55.3, 52.5, 47.8]" +msgstr "" +">>> import math\n" +">>> dados_brutos = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), " +"47.8]\n" +">>> dados_filtrados = []\n" +">>> for valor in dados_brutos:\n" +"... if not math.isnan(value):\n" +"... dados_filtrados.append(valor)\n" +"...\n" +">>> dados_filtrados\n" +"[56.2, 51.7, 55.3, 52.5, 47.8]" + #: ../../tutorial/datastructures.rst:656 msgid "More on Conditions" msgstr "Mais sobre condições" @@ -771,6 +1415,18 @@ msgstr "" "É possível atribuir o resultado de uma comparação ou outra expressão " "booleana para uma variável. Por exemplo::" +#: ../../tutorial/datastructures.rst:688 +msgid "" +">>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'\n" +">>> non_null = string1 or string2 or string3\n" +">>> non_null\n" +"'Trondheim'" +msgstr "" +">>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'\n" +">>> non_null = string1 or string2 or string3\n" +">>> non_null\n" +"'Trondheim'" + #: ../../tutorial/datastructures.rst:693 msgid "" "Note that in Python, unlike C, assignment inside expressions must be done " @@ -816,6 +1472,24 @@ msgstr "" "utiliza codificação Unicode para definir a ordenação. Alguns exemplos de " "comparações entre sequências do mesmo tipo::" +#: ../../tutorial/datastructures.rst:716 +msgid "" +"(1, 2, 3) < (1, 2, 4)\n" +"[1, 2, 3] < [1, 2, 4]\n" +"'ABC' < 'C' < 'Pascal' < 'Python'\n" +"(1, 2, 3, 4) < (1, 2, 4)\n" +"(1, 2) < (1, 2, -1)\n" +"(1, 2, 3) == (1.0, 2.0, 3.0)\n" +"(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)" +msgstr "" +"(1, 2, 3) < (1, 2, 4)\n" +"[1, 2, 3] < [1, 2, 4]\n" +"'ABC' < 'C' < 'Pascal' < 'Python'\n" +"(1, 2, 3, 4) < (1, 2, 4)\n" +"(1, 2) < (1, 2, -1)\n" +"(1, 2, 3) == (1.0, 2.0, 3.0)\n" +"(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)" + #: ../../tutorial/datastructures.rst:724 msgid "" "Note that comparing objects of different types with ``<`` or ``>`` is legal " diff --git a/tutorial/errors.po b/tutorial/errors.po index 1b698705e..a81c823a9 100644 --- a/tutorial/errors.po +++ b/tutorial/errors.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Leticia Portella , 2021 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-03-21 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -52,27 +49,46 @@ msgstr "" "Erros de sintaxe, também conhecidos como erros de parse, são provavelmente " "os mais frequentes entre aqueles que ainda estão aprendendo Python::" +#: ../../tutorial/errors.rst:20 +msgid "" +">>> while True print('Hello world')\n" +" File \"\", line 1\n" +" while True print('Hello world')\n" +" ^^^^^\n" +"SyntaxError: invalid syntax" +msgstr "" +">>> while True print('Olá mundo')\n" +" File \"\", line 1\n" +" while True print('Olá mundo')\n" +" ^^^^^\n" +"SyntaxError: invalid syntax" + #: ../../tutorial/errors.rst:26 msgid "" -"The parser repeats the offending line and displays little 'arrow's pointing " -"at the token in the line where the error was detected. The error may be " -"caused by the absence of a token *before* the indicated token. In the " -"example, the error is detected at the function :func:`print`, since a colon " -"(``':'``) is missing before it. File name and line number are printed so " -"you know where to look in case the input came from a script." -msgstr "" -"O analisador sintático repete a linha inválida e apresenta uma pequena " -"'seta' apontando para o ponto da linha em que o erro foi detectado. O erro " -"deve ter sido causado pela ausência do símbolo que *precede* a seta. No " -"exemplo, o erro foi detectado na função :func:`print`, uma vez que um dois-" -"pontos (``':'``) está faltando antes dela. O nome de arquivo e número de " -"linha são exibidos para que você possa rastrear o erro no texto do script." - -#: ../../tutorial/errors.rst:37 +"The parser repeats the offending line and displays little arrows pointing at " +"the place where the error was detected. Note that this is not always the " +"place that needs to be fixed. In the example, the error is detected at the " +"function :func:`print`, since a colon (``':'``) is missing just before it." +msgstr "" +"O analisador sintático repete a linha ofensiva e exibe pequenas setas " +"apontando para o local onde o erro foi detectado. Note que esse nem sempre é " +"o local que precisa ser corrigido. No exemplo, o erro é detectado na função :" +"func:`print`, já que dois pontos (``':'``) estão faltando logo antes dele." + +#: ../../tutorial/errors.rst:31 +msgid "" +"The file name (```` in our example) and line number are printed so " +"you know where to look in case the input came from a file." +msgstr "" +"O nome do arquivo (```` no nosso exemplo) e o número da linha são " +"impressos para que você saiba onde procurar caso a entrada tenha vindo de um " +"arquivo." + +#: ../../tutorial/errors.rst:38 msgid "Exceptions" msgstr "Exceções" -#: ../../tutorial/errors.rst:39 +#: ../../tutorial/errors.rst:40 msgid "" "Even if a statement or expression is syntactically correct, it may cause an " "error when an attempt is made to execute it. Errors detected during " @@ -87,7 +103,47 @@ msgstr "" "tratá-las em programas Python. A maioria das exceções não são tratadas pelos " "programas e acabam resultando em mensagens de erro::" -#: ../../tutorial/errors.rst:58 +#: ../../tutorial/errors.rst:46 +msgid "" +">>> 10 * (1/0)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" 10 * (1/0)\n" +" ~^~\n" +"ZeroDivisionError: division by zero\n" +">>> 4 + spam*3\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" 4 + spam*3\n" +" ^^^^\n" +"NameError: name 'spam' is not defined\n" +">>> '2' + 2\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" '2' + 2\n" +" ~~~~^~~\n" +"TypeError: can only concatenate str (not \"int\") to str" +msgstr "" +">>> 10 * (1/0)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" 10 * (1/0)\n" +" ~^~\n" +"ZeroDivisionError: division by zero\n" +">>> 4 + spam*3\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" 4 + spam*3\n" +" ^^^^\n" +"NameError: name 'spam' is not defined\n" +">>> '2' + 2\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" '2' + 2\n" +" ~~~~^~~\n" +"TypeError: can only concatenate str (not \"int\") to str" + +#: ../../tutorial/errors.rst:65 msgid "" "The last line of the error message indicates what happened. Exceptions come " "in different types, and the type is printed as part of the message: the " @@ -107,7 +163,7 @@ msgstr "" "uma convenção útil). Os nomes das exceções padrões são identificadores " "embutidos (não palavras reservadas)." -#: ../../tutorial/errors.rst:66 +#: ../../tutorial/errors.rst:73 msgid "" "The rest of the line provides detail based on the type of exception and what " "caused it." @@ -115,7 +171,7 @@ msgstr "" "O resto da linha é um detalhamento que depende do tipo da exceção ocorrida e " "sua causa." -#: ../../tutorial/errors.rst:69 +#: ../../tutorial/errors.rst:76 msgid "" "The preceding part of the error message shows the context where the " "exception occurred, in the form of a stack traceback. In general it contains " @@ -127,17 +183,17 @@ msgstr "" "de execução). Em geral, contém uma lista de linhas do código-fonte, sem " "apresentar, no entanto, linhas lidas da entrada padrão." -#: ../../tutorial/errors.rst:74 +#: ../../tutorial/errors.rst:81 msgid "" ":ref:`bltin-exceptions` lists the built-in exceptions and their meanings." msgstr "" ":ref:`bltin-exceptions` lista as exceções pré-definidas e seus significados." -#: ../../tutorial/errors.rst:80 +#: ../../tutorial/errors.rst:87 msgid "Handling Exceptions" msgstr "Tratamento de exceções" -#: ../../tutorial/errors.rst:82 +#: ../../tutorial/errors.rst:89 msgid "" "It is possible to write programs that handle selected exceptions. Look at " "the following example, which asks the user for input until a valid integer " @@ -153,11 +209,29 @@ msgstr "" "note que uma interrupção gerada pelo usuário será sinalizada pela exceção :" "exc:`KeyboardInterrupt`. ::" -#: ../../tutorial/errors.rst:96 +#: ../../tutorial/errors.rst:95 +msgid "" +">>> while True:\n" +"... try:\n" +"... x = int(input(\"Please enter a number: \"))\n" +"... break\n" +"... except ValueError:\n" +"... print(\"Oops! That was no valid number. Try again...\")\n" +"..." +msgstr "" +">>> while True:\n" +"... try:\n" +"... x = int(input(\"Insira um número: \"))\n" +"... break\n" +"... except ValueError:\n" +"... print(\"Ops! Esse não é um número válido. Tente novamente...\")\n" +"..." + +#: ../../tutorial/errors.rst:103 msgid "The :keyword:`try` statement works as follows." msgstr "A instrução :keyword:`try` funciona da seguinte maneira:" -#: ../../tutorial/errors.rst:98 +#: ../../tutorial/errors.rst:105 msgid "" "First, the *try clause* (the statement(s) between the :keyword:`try` and :" "keyword:`except` keywords) is executed." @@ -165,7 +239,7 @@ msgstr "" "Primeiramente, a *cláusula try* (o conjunto de instruções entre as palavras " "reservadas :keyword:`try` e :keyword:`except` ) é executada." -#: ../../tutorial/errors.rst:101 +#: ../../tutorial/errors.rst:108 msgid "" "If no exception occurs, the *except clause* is skipped and execution of the :" "keyword:`try` statement is finished." @@ -173,7 +247,7 @@ msgstr "" "Se nenhuma exceção ocorrer, a *cláusula except* é ignorada e a execução da " "instrução :keyword:`try` é finalizada." -#: ../../tutorial/errors.rst:104 +#: ../../tutorial/errors.rst:111 msgid "" "If an exception occurs during execution of the :keyword:`try` clause, the " "rest of the clause is skipped. Then, if its type matches the exception " @@ -186,7 +260,7 @@ msgstr "" "except* é executada, e então depois a execução continua após o bloco try/" "except." -#: ../../tutorial/errors.rst:109 +#: ../../tutorial/errors.rst:116 msgid "" "If an exception occurs which does not match the exception named in the " "*except clause*, it is passed on to outer :keyword:`try` statements; if no " @@ -199,7 +273,7 @@ msgstr "" "trata-se de uma *exceção não tratada* e a execução do programa termina com " "uma mensagem de erro." -#: ../../tutorial/errors.rst:113 +#: ../../tutorial/errors.rst:120 msgid "" "A :keyword:`try` statement may have more than one *except clause*, to " "specify handlers for different exceptions. At most one handler will be " @@ -216,7 +290,15 @@ msgstr "" "Uma *cláusula de exceção* pode ser sensível a múltiplas exceções, desde que " "as especifique em uma tupla, por exemplo::" -#: ../../tutorial/errors.rst:122 +#: ../../tutorial/errors.rst:126 +msgid "" +"... except (RuntimeError, TypeError, NameError):\n" +"... pass" +msgstr "" +"... except (RuntimeError, TypeError, NameError):\n" +"... pass" + +#: ../../tutorial/errors.rst:129 msgid "" "A class in an :keyword:`except` clause matches exceptions which are " "instances of the class itself or one of its derived classes (but not the " @@ -230,7 +312,47 @@ msgstr "" "derivada não corresponde a instâncias de suas classes base). Por exemplo, o " "seguinte código irá mostrar B, C, D nessa ordem::" -#: ../../tutorial/errors.rst:146 +#: ../../tutorial/errors.rst:134 +msgid "" +"class B(Exception):\n" +" pass\n" +"\n" +"class C(B):\n" +" pass\n" +"\n" +"class D(C):\n" +" pass\n" +"\n" +"for cls in [B, C, D]:\n" +" try:\n" +" raise cls()\n" +" except D:\n" +" print(\"D\")\n" +" except C:\n" +" print(\"C\")\n" +" except B:\n" +" print(\"B\")" +msgstr "" +"class B(Exception):\n" +" pass\n" +"\n" +"class C(B):\n" +" pass\n" +"\n" +"class D(C):\n" +" pass\n" +"\n" +"for cls in [B, C, D]:\n" +" try:\n" +" raise cls()\n" +" except D:\n" +" print(\"D\")\n" +" except C:\n" +" print(\"C\")\n" +" except B:\n" +" print(\"B\")" + +#: ../../tutorial/errors.rst:153 msgid "" "Note that if the *except clauses* were reversed (with ``except B`` first), " "it would have printed B, B, B --- the first matching *except clause* is " @@ -240,7 +362,7 @@ msgstr "" "início), seria exibido B, B, B --- somente a primeira *cláusula de exceção* " "compatível é ativada." -#: ../../tutorial/errors.rst:149 +#: ../../tutorial/errors.rst:156 msgid "" "When an exception occurs, it may have associated values, also known as the " "exception's *arguments*. The presence and types of the arguments depend on " @@ -250,7 +372,7 @@ msgstr "" "*argumentos* da exceção. A presença e os tipos dos argumentos dependem do " "tipo da exceção." -#: ../../tutorial/errors.rst:153 +#: ../../tutorial/errors.rst:160 msgid "" "The *except clause* may specify a variable after the exception name. The " "variable is bound to the exception instance which typically has an ``args`` " @@ -264,7 +386,45 @@ msgstr "" "exceção embutidos definem :meth:`~object.__str__` para exibir todos os " "argumentos sem acessar explicitamente ``.args``. ::" -#: ../../tutorial/errors.rst:176 +#: ../../tutorial/errors.rst:166 +msgid "" +">>> try:\n" +"... raise Exception('spam', 'eggs')\n" +"... except Exception as inst:\n" +"... print(type(inst)) # the exception type\n" +"... print(inst.args) # arguments stored in .args\n" +"... print(inst) # __str__ allows args to be printed directly,\n" +"... # but may be overridden in exception " +"subclasses\n" +"... x, y = inst.args # unpack args\n" +"... print('x =', x)\n" +"... print('y =', y)\n" +"...\n" +"\n" +"('spam', 'eggs')\n" +"('spam', 'eggs')\n" +"x = spam\n" +"y = eggs" +msgstr "" +">>> try:\n" +"... raise Exception('spam', 'ovos')\n" +"... except Exception as inst:\n" +"... print(type(inst)) # o tipo da exceção\n" +"... print(inst.args) # argumentos armazenados em .args\n" +"... print(inst) # __str__ permite imprimir args diretamente,\n" +"... # mas pode ser substituído em subclasses de " +"exceção\n" +"... x, y = inst.args # desempacota args\n" +"... print('x =', x)\n" +"... print('y =', y)\n" +"...\n" +"\n" +"('spam', 'ovos')\n" +"('spam', 'ovos')\n" +"x = spam\n" +"y = ovos" + +#: ../../tutorial/errors.rst:183 msgid "" "The exception's :meth:`~object.__str__` output is printed as the last part " "('detail') of the message for unhandled exceptions." @@ -272,7 +432,7 @@ msgstr "" "A saída :meth:`~object.__str__` da exceção é exibida como a última parte " "(\"detalhe\") da mensagem para exceções não tratadas." -#: ../../tutorial/errors.rst:179 +#: ../../tutorial/errors.rst:186 msgid "" ":exc:`BaseException` is the common base class of all exceptions. One of its " "subclasses, :exc:`Exception`, is the base class of all the non-fatal " @@ -290,7 +450,7 @@ msgstr "" "`KeyboardInterrupt` que é levantada quando um usuário deseja interromper o " "programa." -#: ../../tutorial/errors.rst:187 +#: ../../tutorial/errors.rst:194 msgid "" ":exc:`Exception` can be used as a wildcard that catches (almost) everything. " "However, it is good practice to be as specific as possible with the types of " @@ -302,7 +462,7 @@ msgstr "" "exceções que pretendemos manipular e permitir que quaisquer exceções " "inesperadas se propaguem." -#: ../../tutorial/errors.rst:192 +#: ../../tutorial/errors.rst:199 msgid "" "The most common pattern for handling :exc:`Exception` is to print or log the " "exception and then re-raise it (allowing a caller to handle the exception as " @@ -312,7 +472,37 @@ msgstr "" "a exceção e então levantá-la novamente (permitindo que um chamador lide com " "a exceção também)::" -#: ../../tutorial/errors.rst:210 +#: ../../tutorial/errors.rst:203 +msgid "" +"import sys\n" +"\n" +"try:\n" +" f = open('myfile.txt')\n" +" s = f.readline()\n" +" i = int(s.strip())\n" +"except OSError as err:\n" +" print(\"OS error:\", err)\n" +"except ValueError:\n" +" print(\"Could not convert data to an integer.\")\n" +"except Exception as err:\n" +" print(f\"Unexpected {err=}, {type(err)=}\")\n" +" raise" +msgstr "" +"import sys\n" +"\n" +"try:\n" +" f = open('meuarquivo.txt')\n" +" s = f.readline()\n" +" i = int(s.strip())\n" +"except OSError as err:\n" +" print(\"Erro de E/S:\", err)\n" +"except ValueError:\n" +" print(\"Não foi possível converter dados para um inteiro.\")\n" +"except Exception as err:\n" +" print(f\"Não esperava {err=}, {type(err)=}\")\n" +" raise" + +#: ../../tutorial/errors.rst:217 msgid "" "The :keyword:`try` ... :keyword:`except` statement has an optional *else " "clause*, which, when present, must follow all *except clauses*. It is " @@ -324,7 +514,27 @@ msgstr "" "cláusulas. É útil para um código que precisa ser executado se nenhuma " "exceção foi levantada. Por exemplo::" -#: ../../tutorial/errors.rst:224 +#: ../../tutorial/errors.rst:222 +msgid "" +"for arg in sys.argv[1:]:\n" +" try:\n" +" f = open(arg, 'r')\n" +" except OSError:\n" +" print('cannot open', arg)\n" +" else:\n" +" print(arg, 'has', len(f.readlines()), 'lines')\n" +" f.close()" +msgstr "" +"for arg in sys.argv[1:]:\n" +" try:\n" +" f = open(arg, 'r')\n" +" except OSError:\n" +" print('não foi possível abrir', arg)\n" +" else:\n" +" print(arg, 'tem', len(f.readlines()), 'linhas')\n" +" f.close()" + +#: ../../tutorial/errors.rst:231 msgid "" "The use of the :keyword:`!else` clause is better than adding additional code " "to the :keyword:`try` clause because it avoids accidentally catching an " @@ -336,7 +546,7 @@ msgstr "" "uma exceção que não foi levantada pelo código protegido pela construção com " "as instruções :keyword:`!try` ... :keyword:`!except`." -#: ../../tutorial/errors.rst:229 +#: ../../tutorial/errors.rst:236 msgid "" "Exception handlers do not handle only exceptions that occur immediately in " "the *try clause*, but also those that occur inside functions that are called " @@ -347,11 +557,33 @@ msgstr "" "funções que são chamadas (mesmo indiretamente) na *cláusula try*. Por " "exemplo::" -#: ../../tutorial/errors.rst:247 +#: ../../tutorial/errors.rst:240 +msgid "" +">>> def this_fails():\n" +"... x = 1/0\n" +"...\n" +">>> try:\n" +"... this_fails()\n" +"... except ZeroDivisionError as err:\n" +"... print('Handling run-time error:', err)\n" +"...\n" +"Handling run-time error: division by zero" +msgstr "" +">>> def this_fails():\n" +"... x = 1/0\n" +"...\n" +">>> try:\n" +"... isso_aqui_falha()\n" +"... except ZeroDivisionError as err:\n" +"... print('Tratando o erro de tempo execução:', err)\n" +"...\n" +"Tratando o erro de tempo execução: division by zero" + +#: ../../tutorial/errors.rst:254 msgid "Raising Exceptions" msgstr "Levantando exceções" -#: ../../tutorial/errors.rst:249 +#: ../../tutorial/errors.rst:256 msgid "" "The :keyword:`raise` statement allows the programmer to force a specified " "exception to occur. For example::" @@ -359,7 +591,21 @@ msgstr "" "A instrução :keyword:`raise` permite ao programador forçar a ocorrência de " "um determinado tipo de exceção. Por exemplo::" -#: ../../tutorial/errors.rst:257 +#: ../../tutorial/errors.rst:259 +msgid "" +">>> raise NameError('HiThere')\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" raise NameError('HiThere')\n" +"NameError: HiThere" +msgstr "" +">>> raise NameError('Olá')\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" raise NameError('Olá')\n" +"NameError: Olá" + +#: ../../tutorial/errors.rst:265 msgid "" "The sole argument to :keyword:`raise` indicates the exception to be raised. " "This must be either an exception instance or an exception class (a class " @@ -373,7 +619,11 @@ msgstr "" "uma de suas subclasses). Se uma classe de exceção for passada, será " "implicitamente instanciada invocando o seu construtor sem argumentos::" -#: ../../tutorial/errors.rst:265 +#: ../../tutorial/errors.rst:271 +msgid "raise ValueError # shorthand for 'raise ValueError()'" +msgstr "raise ValueError # abreviação para 'raise ValueError()'" + +#: ../../tutorial/errors.rst:273 msgid "" "If you need to determine whether an exception was raised but don't intend to " "handle it, a simpler form of the :keyword:`raise` statement allows you to re-" @@ -383,11 +633,37 @@ msgstr "" "quer manipular o erro, uma forma simples de instrução :keyword:`raise` " "permite que você levante-a novamente::" -#: ../../tutorial/errors.rst:284 +#: ../../tutorial/errors.rst:277 +msgid "" +">>> try:\n" +"... raise NameError('HiThere')\n" +"... except NameError:\n" +"... print('An exception flew by!')\n" +"... raise\n" +"...\n" +"An exception flew by!\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +" raise NameError('HiThere')\n" +"NameError: HiThere" +msgstr "" +">>> try:\n" +"... raise NameError('Olá')\n" +"... except NameError:\n" +"... print('Uma exceção passou por aqui!')\n" +"... raise\n" +"...\n" +"Uma exceção passou por aqui!\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +" raise NameError('Olá')\n" +"NameError: Olá" + +#: ../../tutorial/errors.rst:293 msgid "Exception Chaining" msgstr "Encadeamento de exceções" -#: ../../tutorial/errors.rst:286 +#: ../../tutorial/errors.rst:295 msgid "" "If an unhandled exception occurs inside an :keyword:`except` section, it " "will have the exception being handled attached to it and included in the " @@ -397,7 +673,45 @@ msgstr "" "ela terá a exceção sendo tratada anexada a ela e incluída na mensagem de " "erro::" -#: ../../tutorial/errors.rst:305 +#: ../../tutorial/errors.rst:299 +msgid "" +">>> try:\n" +"... open(\"database.sqlite\")\n" +"... except OSError:\n" +"... raise RuntimeError(\"unable to handle error\")\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +" open(\"database.sqlite\")\n" +" ~~~~^^^^^^^^^^^^^^^^^^^\n" +"FileNotFoundError: [Errno 2] No such file or directory: 'database.sqlite'\n" +"\n" +"During handling of the above exception, another exception occurred:\n" +"\n" +"Traceback (most recent call last):\n" +" File \"\", line 4, in \n" +" raise RuntimeError(\"unable to handle error\")\n" +"RuntimeError: unable to handle error" +msgstr "" +">>> try:\n" +"... open(\"bancodedados.sqlite\")\n" +"... except OSError:\n" +"... raise RuntimeError(\"não foi possível tratar o erro\")\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +" open(\"bancodedados.sqlite\")\n" +" ~~~~^^^^^^^^^^^^^^^^^^^\n" +"FileNotFoundError: [Errno 2] No such file or directory: 'bancodedados." +"sqlite'\n" +"\n" +"During handling of the above exception, another exception occurred:\n" +"\n" +"Traceback (most recent call last):\n" +" File \"\", line 4, in \n" +"RuntimeError: não foi possível tratar o erro" + +#: ../../tutorial/errors.rst:317 msgid "" "To indicate that an exception is a direct consequence of another, the :" "keyword:`raise` statement allows an optional :keyword:`from` clause::" @@ -406,12 +720,65 @@ msgstr "" "instrução :keyword:`raise` permite uma cláusula opcional :keyword:`from " "`::" -#: ../../tutorial/errors.rst:311 +#: ../../tutorial/errors.rst:320 +msgid "" +"# exc must be exception instance or None.\n" +"raise RuntimeError from exc" +msgstr "" +"# exc deve ser uma instância de exceção ou None.\n" +"raise RuntimeError from exc" + +#: ../../tutorial/errors.rst:323 msgid "This can be useful when you are transforming exceptions. For example::" msgstr "" "Isso pode ser útil quando você está transformando exceções. Por exemplo::" -#: ../../tutorial/errors.rst:332 +#: ../../tutorial/errors.rst:325 +msgid "" +">>> def func():\n" +"... raise ConnectionError\n" +"...\n" +">>> try:\n" +"... func()\n" +"... except ConnectionError as exc:\n" +"... raise RuntimeError('Failed to open database') from exc\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +" func()\n" +" ~~~~^^\n" +" File \"\", line 2, in func\n" +"ConnectionError\n" +"\n" +"The above exception was the direct cause of the following exception:\n" +"\n" +"Traceback (most recent call last):\n" +" File \"\", line 4, in \n" +" raise RuntimeError('Failed to open database') from exc\n" +"RuntimeError: Failed to open database" +msgstr "" +">>> def func():\n" +"... raise ConnectionError\n" +"...\n" +">>> try:\n" +"... func()\n" +"... except ConnectionError as exc:\n" +"... raise RuntimeError('Falha ao abrir banco de dados') from exc\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +" func()\n" +" ~~~~^^\n" +" File \"\", line 2, in func\n" +"ConnectionError\n" +"\n" +"The above exception was the direct cause of the following exception:\n" +"\n" +"Traceback (most recent call last):\n" +" File \"\", line 4, in \n" +"RuntimeError: Falha ao abrir banco de dados" + +#: ../../tutorial/errors.rst:347 msgid "" "It also allows disabling automatic exception chaining using the ``from " "None`` idiom::" @@ -419,18 +786,40 @@ msgstr "" "Ele também permite desabilitar o encadeamento automático de exceções usando " "o idioma ``from None``::" -#: ../../tutorial/errors.rst:344 +#: ../../tutorial/errors.rst:350 +msgid "" +">>> try:\n" +"... open('database.sqlite')\n" +"... except OSError:\n" +"... raise RuntimeError from None\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 4, in \n" +" raise RuntimeError from None\n" +"RuntimeError" +msgstr "" +">>> try:\n" +"... open('bancodedados.sqlite')\n" +"... except OSError:\n" +"... raise RuntimeError from None\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 4, in \n" +" raise RuntimeError from None\n" +"RuntimeError" + +#: ../../tutorial/errors.rst:360 msgid "" "For more information about chaining mechanics, see :ref:`bltin-exceptions`." msgstr "" "Para mais informações sobre os mecanismos de encadeamento, veja :ref:`bltin-" "exceptions`." -#: ../../tutorial/errors.rst:350 +#: ../../tutorial/errors.rst:366 msgid "User-defined Exceptions" msgstr "Exceções definidas pelo usuário" -#: ../../tutorial/errors.rst:352 +#: ../../tutorial/errors.rst:368 msgid "" "Programs may name their own exceptions by creating a new exception class " "(see :ref:`tut-classes` for more about Python classes). Exceptions should " @@ -442,7 +831,7 @@ msgstr "" "Python). Exceções devem ser derivadas da classe :exc:`Exception`, direta ou " "indiretamente." -#: ../../tutorial/errors.rst:356 +#: ../../tutorial/errors.rst:372 msgid "" "Exception classes can be defined which do anything any other class can do, " "but are usually kept simple, often only offering a number of attributes that " @@ -454,7 +843,7 @@ msgstr "" "geralmente oferecendo apenas um número de atributos que permitem que " "informações sobre o erro sejam extraídas por manipuladores para a exceção." -#: ../../tutorial/errors.rst:360 +#: ../../tutorial/errors.rst:376 msgid "" "Most exceptions are defined with names that end in \"Error\", similar to the " "naming of the standard exceptions." @@ -462,7 +851,7 @@ msgstr "" "É comum que novas exceções sejam definidas com nomes terminando em " "\"Error\", semelhante a muitas exceções embutidas." -#: ../../tutorial/errors.rst:363 +#: ../../tutorial/errors.rst:379 msgid "" "Many standard modules define their own exceptions to report errors that may " "occur in functions they define." @@ -470,11 +859,11 @@ msgstr "" "Muitos módulos padrão definem suas próprias exceções para relatar erros que " "podem ocorrer nas funções que definem." -#: ../../tutorial/errors.rst:370 +#: ../../tutorial/errors.rst:386 msgid "Defining Clean-up Actions" msgstr "Definindo ações de limpeza" -#: ../../tutorial/errors.rst:372 +#: ../../tutorial/errors.rst:388 msgid "" "The :keyword:`try` statement has another optional clause which is intended " "to define clean-up actions that must be executed under all circumstances. " @@ -484,7 +873,31 @@ msgstr "" "permitir a implementação de ações de limpeza, que sempre devem ser " "executadas independentemente da ocorrência de exceções. Como no exemplo::" -#: ../../tutorial/errors.rst:386 +#: ../../tutorial/errors.rst:392 +msgid "" +">>> try:\n" +"... raise KeyboardInterrupt\n" +"... finally:\n" +"... print('Goodbye, world!')\n" +"...\n" +"Goodbye, world!\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +" raise KeyboardInterrupt\n" +"KeyboardInterrupt" +msgstr "" +">>> try:\n" +"... raise KeyboardInterrupt\n" +"... finally:\n" +"... print('Adeus, mundo!')\n" +"...\n" +"Adeus, mundo!\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +" raise KeyboardInterrupt\n" +"KeyboardInterrupt" + +#: ../../tutorial/errors.rst:403 msgid "" "If a :keyword:`finally` clause is present, the :keyword:`!finally` clause " "will execute as the last task before the :keyword:`try` statement completes. " @@ -498,7 +911,7 @@ msgstr "" "instrução :keyword:`!try` produz uma exceção. Os pontos a seguir discutem " "casos mais complexos quando ocorre uma exceção:" -#: ../../tutorial/errors.rst:392 +#: ../../tutorial/errors.rst:409 msgid "" "If an exception occurs during execution of the :keyword:`!try` clause, the " "exception may be handled by an :keyword:`except` clause. If the exception is " @@ -510,7 +923,7 @@ msgstr "" "não for tratada por uma cláusula :keyword:`!except`, a exceção será gerada " "novamente após a execução da cláusula :keyword:`!finally`." -#: ../../tutorial/errors.rst:398 +#: ../../tutorial/errors.rst:415 msgid "" "An exception could occur during execution of an :keyword:`!except` or :" "keyword:`!else` clause. Again, the exception is re-raised after the :keyword:" @@ -520,7 +933,7 @@ msgstr "" "except` ou :keyword:`!else`. Novamente, a exceção é re-levantada depois que :" "keyword:`!finally` é executada." -#: ../../tutorial/errors.rst:402 +#: ../../tutorial/errors.rst:419 msgid "" "If the :keyword:`!finally` clause executes a :keyword:`break`, :keyword:" "`continue` or :keyword:`return` statement, exceptions are not re-raised." @@ -529,7 +942,7 @@ msgstr "" "keyword:`continue` ou :keyword:`return`, as exceções não são levantadas " "novamente." -#: ../../tutorial/errors.rst:406 +#: ../../tutorial/errors.rst:423 msgid "" "If the :keyword:`!try` statement reaches a :keyword:`break`, :keyword:" "`continue` or :keyword:`return` statement, the :keyword:`!finally` clause " @@ -541,7 +954,7 @@ msgstr "" "executada imediatamente antes da execução da instrução :keyword:`!break`, :" "keyword:`!continue` ou :keyword:`!return`." -#: ../../tutorial/errors.rst:412 +#: ../../tutorial/errors.rst:429 msgid "" "If a :keyword:`!finally` clause includes a :keyword:`!return` statement, the " "returned value will be the one from the :keyword:`!finally` clause's :" @@ -553,15 +966,91 @@ msgstr "" "cláusula :keyword:`!finally`, não o valor da instrução :keyword:`!return` da " "cláusula :keyword:`!try`." -#: ../../tutorial/errors.rst:418 +#: ../../tutorial/errors.rst:435 msgid "For example::" msgstr "Por exemplo::" -#: ../../tutorial/errors.rst:429 +#: ../../tutorial/errors.rst:437 +msgid "" +">>> def bool_return():\n" +"... try:\n" +"... return True\n" +"... finally:\n" +"... return False\n" +"...\n" +">>> bool_return()\n" +"False" +msgstr "" +">>> def retorna_booleano():\n" +"... try:\n" +"... return True\n" +"... finally:\n" +"... return False\n" +"...\n" +">>> retorna_booleano()\n" +"False" + +#: ../../tutorial/errors.rst:446 msgid "A more complicated example::" msgstr "Um exemplo mais complicado::" -#: ../../tutorial/errors.rst:454 +#: ../../tutorial/errors.rst:448 +msgid "" +">>> def divide(x, y):\n" +"... try:\n" +"... result = x / y\n" +"... except ZeroDivisionError:\n" +"... print(\"division by zero!\")\n" +"... else:\n" +"... print(\"result is\", result)\n" +"... finally:\n" +"... print(\"executing finally clause\")\n" +"...\n" +">>> divide(2, 1)\n" +"result is 2.0\n" +"executing finally clause\n" +">>> divide(2, 0)\n" +"division by zero!\n" +"executing finally clause\n" +">>> divide(\"2\", \"1\")\n" +"executing finally clause\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" divide(\"2\", \"1\")\n" +" ~~~~~~^^^^^^^^^^\n" +" File \"\", line 3, in divide\n" +" result = x / y\n" +" ~~^~~\n" +"TypeError: unsupported operand type(s) for /: 'str' and 'str'" +msgstr "" +">>> def divide(x, y):\n" +"... try:\n" +"... result = x / y\n" +"... except ZeroDivisionError:\n" +"... print(\"division by zero!\")\n" +"... else:\n" +"... print(\"result is\", result)\n" +"... finally:\n" +"... print(\"executing finally clause\")\n" +"...\n" +">>> divide(2, 1)\n" +"result is 2.0\n" +"executing finally clause\n" +">>> divide(2, 0)\n" +"division by zero!\n" +"executing finally clause\n" +">>> divide(\"2\", \"1\")\n" +"executing finally clause\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" divide(\"2\", \"1\")\n" +" ~~~~~~^^^^^^^^^^\n" +" File \"\", line 3, in divide\n" +" result = x / y\n" +" ~~^~~\n" +"TypeError: unsupported operand type(s) for /: 'str' and 'str'" + +#: ../../tutorial/errors.rst:475 msgid "" "As you can see, the :keyword:`finally` clause is executed in any event. " "The :exc:`TypeError` raised by dividing two strings is not handled by the :" @@ -573,7 +1062,7 @@ msgstr "" "é tratada pela cláusula :keyword:`except` e portanto é re-levantada depois " "que a cláusula :keyword:`!finally` é executada." -#: ../../tutorial/errors.rst:459 +#: ../../tutorial/errors.rst:480 msgid "" "In real world applications, the :keyword:`finally` clause is useful for " "releasing external resources (such as files or network connections), " @@ -583,11 +1072,11 @@ msgstr "" "liberar recursos externos (como arquivos ou conexões de rede), " "independentemente do uso do recurso ter sido bem sucedido ou não." -#: ../../tutorial/errors.rst:467 +#: ../../tutorial/errors.rst:488 msgid "Predefined Clean-up Actions" msgstr "Ações de limpeza predefinidas" -#: ../../tutorial/errors.rst:469 +#: ../../tutorial/errors.rst:490 msgid "" "Some objects define standard clean-up actions to be undertaken when the " "object is no longer needed, regardless of whether or not the operation using " @@ -599,7 +1088,15 @@ msgstr "" "usando o objeto ter sido ou não bem sucedida. Veja o exemplo a seguir, que " "tenta abrir um arquivo e exibir seu conteúdo na tela. ::" -#: ../../tutorial/errors.rst:477 +#: ../../tutorial/errors.rst:495 +msgid "" +"for line in open(\"myfile.txt\"):\n" +" print(line, end=\"\")" +msgstr "" +"for linha in open(\"meuarquivo.txt\"):\n" +" print(linha, end=\"\")" + +#: ../../tutorial/errors.rst:498 msgid "" "The problem with this code is that it leaves the file open for an " "indeterminate amount of time after this part of the code has finished " @@ -615,7 +1112,17 @@ msgstr "" "utilizados com a certeza de que sempre serão prontamente e corretamente " "finalizados. ::" -#: ../../tutorial/errors.rst:487 +#: ../../tutorial/errors.rst:504 +msgid "" +"with open(\"myfile.txt\") as f:\n" +" for line in f:\n" +" print(line, end=\"\")" +msgstr "" +"with open(\"meuarquivo.txt\") as f:\n" +" for linha in f:\n" +" print(linha, end=\"\")" + +#: ../../tutorial/errors.rst:508 msgid "" "After the statement is executed, the file *f* is always closed, even if a " "problem was encountered while processing the lines. Objects which, like " @@ -627,11 +1134,11 @@ msgstr "" "como arquivos, fornecem ações de limpeza predefinidas as indicarão em suas " "documentações." -#: ../../tutorial/errors.rst:495 +#: ../../tutorial/errors.rst:516 msgid "Raising and Handling Multiple Unrelated Exceptions" msgstr "Criando e tratando várias exceções não relacionadas" -#: ../../tutorial/errors.rst:497 +#: ../../tutorial/errors.rst:518 msgid "" "There are situations where it is necessary to report several exceptions that " "have occurred. This is often the case in concurrency frameworks, when " @@ -645,7 +1152,7 @@ msgstr "" "que é desejável continuar a execução e coletar vários erros em vez de " "levantar a primeira exceção." -#: ../../tutorial/errors.rst:503 +#: ../../tutorial/errors.rst:524 msgid "" "The builtin :exc:`ExceptionGroup` wraps a list of exception instances so " "that they can be raised together. It is an exception itself, so it can be " @@ -655,7 +1162,58 @@ msgstr "" "para que elas possam ser levantadas juntas. É uma exceção em si, portanto, " "pode ser capturada como qualquer outra exceção. ::" -#: ../../tutorial/errors.rst:529 +#: ../../tutorial/errors.rst:528 +msgid "" +">>> def f():\n" +"... excs = [OSError('error 1'), SystemError('error 2')]\n" +"... raise ExceptionGroup('there were problems', excs)\n" +"...\n" +">>> f()\n" +" + Exception Group Traceback (most recent call last):\n" +" | File \"\", line 1, in \n" +" | f()\n" +" | ~^^\n" +" | File \"\", line 3, in f\n" +" | raise ExceptionGroup('there were problems', excs)\n" +" | ExceptionGroup: there were problems (2 sub-exceptions)\n" +" +-+---------------- 1 ----------------\n" +" | OSError: error 1\n" +" +---------------- 2 ----------------\n" +" | SystemError: error 2\n" +" +------------------------------------\n" +">>> try:\n" +"... f()\n" +"... except Exception as e:\n" +"... print(f'caught {type(e)}: e')\n" +"...\n" +"caught : e\n" +">>>" +msgstr "" +">>> def f():\n" +"... excs = [OSError('error 1'), SystemError('error 2')]\n" +"... raise ExceptionGroup('houve problemas', excs)\n" +"...\n" +">>> f()\n" +" + Exception Group Traceback (most recent call last):\n" +" | File \"\", line 1, in \n" +" | f()\n" +" | ~^^\n" +" | File \"\", line 3, in f\n" +" | ExceptionGroup: houve problemas (2 sub-exceptions)\n" +" +-+---------------- 1 ----------------\n" +" | OSError: error 1\n" +" +---------------- 2 ----------------\n" +" | SystemError: error 2\n" +" +------------------------------------\n" +">>> try:\n" +"... f()\n" +"... except Exception as e:\n" +"... print(f'capturada {type(e)}: e')\n" +"...\n" +"capturada : e\n" +">>>" + +#: ../../tutorial/errors.rst:553 msgid "" "By using ``except*`` instead of ``except``, we can selectively handle only " "the exceptions in the group that match a certain type. In the following " @@ -670,7 +1228,91 @@ msgstr "" "todas as outras exceções se propaguem para outras cláusulas e eventualmente " "sejam levantadas novamente. ::" -#: ../../tutorial/errors.rst:572 +#: ../../tutorial/errors.rst:560 +msgid "" +">>> def f():\n" +"... raise ExceptionGroup(\n" +"... \"group1\",\n" +"... [\n" +"... OSError(1),\n" +"... SystemError(2),\n" +"... ExceptionGroup(\n" +"... \"group2\",\n" +"... [\n" +"... OSError(3),\n" +"... RecursionError(4)\n" +"... ]\n" +"... )\n" +"... ]\n" +"... )\n" +"...\n" +">>> try:\n" +"... f()\n" +"... except* OSError as e:\n" +"... print(\"There were OSErrors\")\n" +"... except* SystemError as e:\n" +"... print(\"There were SystemErrors\")\n" +"...\n" +"There were OSErrors\n" +"There were SystemErrors\n" +" + Exception Group Traceback (most recent call last):\n" +" | File \"\", line 2, in \n" +" | f()\n" +" | ~^^\n" +" | File \"\", line 2, in f\n" +" | raise ExceptionGroup(\n" +" | ...<12 lines>...\n" +" | )\n" +" | ExceptionGroup: group1 (1 sub-exception)\n" +" +-+---------------- 1 ----------------\n" +" | ExceptionGroup: group2 (1 sub-exception)\n" +" +-+---------------- 1 ----------------\n" +" | RecursionError: 4\n" +" +------------------------------------\n" +">>>" +msgstr "" +">>> def f():\n" +"... raise ExceptionGroup(\n" +"... \"group1\",\n" +"... [\n" +"... OSError(1),\n" +"... SystemError(2),\n" +"... ExceptionGroup(\n" +"... \"group2\",\n" +"... [\n" +"... OSError(3),\n" +"... RecursionError(4)\n" +"... ]\n" +"... )\n" +"... ]\n" +"... )\n" +"...\n" +">>> try:\n" +"... f()\n" +"... except* OSError as e:\n" +"... print(\"Houve OSErrors\")\n" +"... except* SystemError as e:\n" +"... print(\"Houve SystemErrors\")\n" +"...\n" +"Houve OSErrors\n" +"Houve SystemErrors\n" +" + Exception Group Traceback (most recent call last):\n" +" | File \"\", line 2, in \n" +" | f()\n" +" | ~^^\n" +" | File \"\", line 2, in f\n" +" | raise ExceptionGroup(\n" +" | ...<12 lines>...\n" +" | )\n" +" | ExceptionGroup: group1\n" +" +-+---------------- 1 ----------------\n" +" | ExceptionGroup: group2\n" +" +-+---------------- 1 ----------------\n" +" | RecursionError: 4\n" +" +------------------------------------\n" +">>>" + +#: ../../tutorial/errors.rst:601 msgid "" "Note that the exceptions nested in an exception group must be instances, not " "types. This is because in practice the exceptions would typically be ones " @@ -682,11 +1324,35 @@ msgstr "" "normalmente seriam aquelas que já foram levantadas e capturadas pelo " "programa, seguindo o seguinte padrão::" -#: ../../tutorial/errors.rst:592 +#: ../../tutorial/errors.rst:606 +msgid "" +">>> excs = []\n" +"... for test in tests:\n" +"... try:\n" +"... test.run()\n" +"... except Exception as e:\n" +"... excs.append(e)\n" +"...\n" +">>> if excs:\n" +"... raise ExceptionGroup(\"Test Failures\", excs)\n" +"..." +msgstr "" +">>> excs = []\n" +"... for test in tests:\n" +"... try:\n" +"... test.run()\n" +"... except Exception as e:\n" +"... excs.append(e)\n" +"...\n" +">>> if excs:\n" +"... raise ExceptionGroup(\"Falhas no teste\", excs)\n" +"..." + +#: ../../tutorial/errors.rst:621 msgid "Enriching Exceptions with Notes" msgstr "Enriquecendo exceções com notas" -#: ../../tutorial/errors.rst:594 +#: ../../tutorial/errors.rst:623 msgid "" "When an exception is created in order to be raised, it is usually " "initialized with information that describes the error that has occurred. " @@ -703,7 +1369,39 @@ msgstr "" "adiciona à lista de notas da exceção. A renderização de traceback padrão " "inclui todas as notas, na ordem em que foram adicionadas, após a exceção. ::" -#: ../../tutorial/errors.rst:615 +#: ../../tutorial/errors.rst:630 +msgid "" +">>> try:\n" +"... raise TypeError('bad type')\n" +"... except Exception as e:\n" +"... e.add_note('Add some information')\n" +"... e.add_note('Add some more information')\n" +"... raise\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +" raise TypeError('bad type')\n" +"TypeError: bad type\n" +"Add some information\n" +"Add some more information\n" +">>>" +msgstr "" +">>> try:\n" +"... raise TypeError('tipo inválido')\n" +"... except Exception as e:\n" +"... e.add_note('Adiciona algumas informações')\n" +"... e.add_note('Adiciona mais algumas informações')\n" +"... raise\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +" raise TypeError('tipo inválido')\n" +"TypeError: tipo inválido\n" +"Adiciona algumas informações\n" +"Adiciona mais algumas informações\n" +">>>" + +#: ../../tutorial/errors.rst:645 msgid "" "For example, when collecting exceptions into an exception group, we may want " "to add context information for the individual errors. In the following each " @@ -712,3 +1410,97 @@ msgstr "" "Por exemplo, ao coletar exceções em um grupo de exceções, podemos querer " "adicionar informações de contexto para os erros individuais. A seguir, cada " "exceção no grupo tem uma nota indicando quando esse erro ocorreu. ::" + +#: ../../tutorial/errors.rst:649 +msgid "" +">>> def f():\n" +"... raise OSError('operation failed')\n" +"...\n" +">>> excs = []\n" +">>> for i in range(3):\n" +"... try:\n" +"... f()\n" +"... except Exception as e:\n" +"... e.add_note(f'Happened in Iteration {i+1}')\n" +"... excs.append(e)\n" +"...\n" +">>> raise ExceptionGroup('We have some problems', excs)\n" +" + Exception Group Traceback (most recent call last):\n" +" | File \"\", line 1, in \n" +" | raise ExceptionGroup('We have some problems', excs)\n" +" | ExceptionGroup: We have some problems (3 sub-exceptions)\n" +" +-+---------------- 1 ----------------\n" +" | Traceback (most recent call last):\n" +" | File \"\", line 3, in \n" +" | f()\n" +" | ~^^\n" +" | File \"\", line 2, in f\n" +" | raise OSError('operation failed')\n" +" | OSError: operation failed\n" +" | Happened in Iteration 1\n" +" +---------------- 2 ----------------\n" +" | Traceback (most recent call last):\n" +" | File \"\", line 3, in \n" +" | f()\n" +" | ~^^\n" +" | File \"\", line 2, in f\n" +" | raise OSError('operation failed')\n" +" | OSError: operation failed\n" +" | Happened in Iteration 2\n" +" +---------------- 3 ----------------\n" +" | Traceback (most recent call last):\n" +" | File \"\", line 3, in \n" +" | f()\n" +" | ~^^\n" +" | File \"\", line 2, in f\n" +" | raise OSError('operation failed')\n" +" | OSError: operation failed\n" +" | Happened in Iteration 3\n" +" +------------------------------------\n" +">>>" +msgstr "" +">>> def f():\n" +"... raise OSError('operação falhou')\n" +"...\n" +">>> excs = []\n" +">>> for i in range(3):\n" +"... try:\n" +"... f()\n" +"... except Exception as e:\n" +"... e.add_note(f'Aconteceu na iteração {i+1}')\n" +"... excs.append(e)\n" +"...\n" +">>> raise ExceptionGroup('Nós temos alguns problemas', excs)\n" +" + Exception Group Traceback (most recent call last):\n" +" | File \"\", line 1, in \n" +" | raise ExceptionGroup('Nós temos alguns problemas', excs)\n" +" | ExceptionGroup: Nós temos alguns problemas (3 sub-exceptions)\n" +" +-+---------------- 1 ----------------\n" +" | Traceback (most recent call last):\n" +" | File \"\", line 3, in \n" +" | f()\n" +" | ~^^\n" +" | File \"\", line 2, in f\n" +" | raise OSError('operação falhou')\n" +" | OSError: operação falhou\n" +" | Aconteceu na iteração 1\n" +" +---------------- 2 ----------------\n" +" | Traceback (most recent call last):\n" +" | File \"\", line 3, in \n" +" | f()\n" +" | ~^^\n" +" | File \"\", line 2, in f\n" +" | raise OSError('operação falhou')\n" +" | OSError: operação falhou\n" +" | Aconteceu na iteração 2\n" +" +---------------- 3 ----------------\n" +" | Traceback (most recent call last):\n" +" | File \"\", line 3, in \n" +" | f()\n" +" | ~^^\n" +" | File \"\", line 2, in f\n" +" | raise OSError('operação falhou')\n" +" | OSError: operação falhou\n" +" | Aconteceu na iteração 3\n" +" +------------------------------------\n" +">>>" diff --git a/tutorial/floatingpoint.po b/tutorial/floatingpoint.po index e71eda1d4..3129a3ac7 100644 --- a/tutorial/floatingpoint.po +++ b/tutorial/floatingpoint.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-20 00:52+0000\n" -"PO-Revision-Date: 2021-06-28 01:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -52,23 +51,34 @@ msgid "" "numbers actually stored in the machine." msgstr "" "Infelizmente, muitas frações decimais não podem ser representadas " -"precisamente\n" -"como frações binárias. O resultado é que, em geral, os números decimais de\n" -"ponto flutuante que você digita acabam sendo armazenados de forma apenas\n" -"aproximada, na forma de números binários de ponto flutuante." +"precisamente como frações binárias. O resultado é que, em geral, os números " +"decimais de ponto flutuante que você digita acabam sendo armazenados de " +"forma apenas aproximada, na forma de números binários de ponto flutuante." #: ../../tutorial/floatingpoint.rst:28 msgid "" "The problem is easier to understand at first in base 10. Consider the " "fraction 1/3. You can approximate that as a base 10 fraction::" msgstr "" -"O problema é mais fácil de entender primeiro em base 10. Considere a fração\n" +"O problema é mais fácil de entender primeiro em base 10. Considere a fração " "1/3. Podemos representá-la aproximadamente como uma fração base 10::" +#: ../../tutorial/floatingpoint.rst:31 +msgid "0.3" +msgstr "0.3" + #: ../../tutorial/floatingpoint.rst:33 ../../tutorial/floatingpoint.rst:37 msgid "or, better, ::" msgstr "ou melhor, ::" +#: ../../tutorial/floatingpoint.rst:35 +msgid "0.33" +msgstr "0.33" + +#: ../../tutorial/floatingpoint.rst:39 +msgid "0.333" +msgstr "0.333" + #: ../../tutorial/floatingpoint.rst:41 msgid "" "and so on. No matter how many digits you're willing to write down, the " @@ -76,9 +86,8 @@ msgid "" "approximation of 1/3." msgstr "" "e assim por diante. Não importa quantos dígitos você está disposto a " -"escrever,\n" -"o resultado nunca será exatamente 1/3, mas será uma aproximação de cada vez\n" -"melhor de 1/3." +"escrever, o resultado nunca será exatamente 1/3, mas será uma aproximação de " +"cada vez melhor de 1/3." #: ../../tutorial/floatingpoint.rst:45 msgid "" @@ -91,6 +100,10 @@ msgstr "" "fração de base 2. No sistema de base 2, 1/10 é uma fração binária que se " "repete infinitamente::" +#: ../../tutorial/floatingpoint.rst:49 +msgid "0.0001100110011001100110011001100110011001100110011..." +msgstr "0.0001100110011001100110011001100110011001100110011..." + #: ../../tutorial/floatingpoint.rst:51 msgid "" "Stop at any finite number of bits, and you get an approximation. On most " @@ -117,22 +130,38 @@ msgid "" "stored for 0.1, it would have to display::" msgstr "" "É fácil esquecer que o valor armazenado é uma aproximação da fração decimal " -"original, devido à forma como os floats são exibidos no interpretador " -"interativo. O Python exibe apenas uma aproximação decimal do verdadeiro " -"valor decimal da aproximação binária armazenada pela máquina. Se o Python " -"exibisse o verdadeiro valor decimal da aproximação binária que representa o " -"decimal 0.1, seria necessário mostrar::" +"original, devido à forma como os pontos flutuantes são exibidos no " +"interpretador interativo. O Python exibe apenas uma aproximação decimal do " +"verdadeiro valor decimal da aproximação binária armazenada pela máquina. Se " +"o Python exibisse o verdadeiro valor decimal da aproximação binária que " +"representa o decimal 0.1, seria necessário mostrar::" + +#: ../../tutorial/floatingpoint.rst:64 +msgid "" +">>> 0.1\n" +"0.1000000000000000055511151231257827021181583404541015625" +msgstr "" +">>> 0.1\n" +"0.1000000000000000055511151231257827021181583404541015625" #: ../../tutorial/floatingpoint.rst:67 msgid "" "That is more digits than most people find useful, so Python keeps the number " "of digits manageable by displaying a rounded value instead:" msgstr "" -"Contém muito mais dígitos do que é o esperado e utilizado pela grande " +"Isto contém muito mais dígitos do que é o esperado e utilizado pela grande " "maioria dos desenvolvedores, portanto, o Python limita o número de dígitos " "exibidos, apresentando um valor arredondado, ao invés de mostrar todas as " "casas decimais::" +#: ../../tutorial/floatingpoint.rst:70 +msgid "" +">>> 1 / 10\n" +"0.1" +msgstr "" +">>> 1 / 10\n" +"0.1" + #: ../../tutorial/floatingpoint.rst:75 msgid "" "Just remember, even though the printed result looks like the exact value of " @@ -193,9 +222,31 @@ msgid "" "limited number of significant digits:" msgstr "" "Para obter um valor mais agradável, poderás utilizar a formatação de " -"sequência de caracteres sendo capaz de gerar um número limitado de dígitos " +"sequência de caracteres para produzir um número limitado de dígitos " "significativos:" +#: ../../tutorial/floatingpoint.rst:100 +msgid "" +">>> format(math.pi, '.12g') # give 12 significant digits\n" +"'3.14159265359'\n" +"\n" +">>> format(math.pi, '.2f') # give 2 digits after the point\n" +"'3.14'\n" +"\n" +">>> repr(math.pi)\n" +"'3.141592653589793'" +msgstr "" +">>> format(math.pi, '.12g') # ponto flutuante fornece 12 dígitos " +"significativos\n" +"'3.14159265359'\n" +"\n" +">>> format(math.pi, '.2f') # ponto flutuante fornece 2 dígitos " +"significativos\n" +"'3.14'\n" +"\n" +">>> repr(math.pi)\n" +"'3.141592653589793'" + #: ../../tutorial/floatingpoint.rst:111 msgid "" "It's important to realize that this is, in a real sense, an illusion: you're " @@ -209,9 +260,17 @@ msgid "" "One illusion may beget another. For example, since 0.1 is not exactly 1/10, " "summing three values of 0.1 may not yield exactly 0.3, either:" msgstr "" -"Uma ilusão pode gerar outra. Por exemplo, uma vez que 0,1 não é exatamente " +"Uma ilusão pode gerar outra. Por exemplo, uma vez que 0.1 não é exatamente " "1/10, somar três vezes o valor 0.1, não garantirá que o resultado seja " -"exatamente 0,3, isso porque:" +"exatamente 0.3, isso porque:" + +#: ../../tutorial/floatingpoint.rst:117 +msgid "" +">>> 0.1 + 0.1 + 0.1 == 0.3\n" +"False" +msgstr "" +">>> 0.1 + 0.1 + 0.1 == 0.3\n" +"False" #: ../../tutorial/floatingpoint.rst:122 msgid "" @@ -219,10 +278,18 @@ msgid "" "cannot get any closer to the exact value of 3/10, then pre-rounding with :" "func:`round` function cannot help:" msgstr "" -"Inclusive, uma vez que o 0,1 não consegue aproximar-se do valor exato de " -"1/10 e 0,3 não pode se aproximar mais do valor exato de 3/10, temos então " +"Inclusive, uma vez que o 0.1 não consegue aproximar-se do valor exato de " +"1/10 e 0.3 não pode se aproximar mais do valor exato de 3/10, temos então " "que o pré-arredondamento com a função :func:`round` não servirá como ajuda:" +#: ../../tutorial/floatingpoint.rst:126 +msgid "" +">>> round(0.1, 1) + round(0.1, 1) + round(0.1, 1) == round(0.3, 1)\n" +"False" +msgstr "" +">>> round(0.1, 1) + round(0.1, 1) + round(0.1, 1) == round(0.3, 1)\n" +"False" + #: ../../tutorial/floatingpoint.rst:131 msgid "" "Though the numbers cannot be made closer to their intended exact values, " @@ -232,6 +299,14 @@ msgstr "" "desejamos, a função :func:`math.isclose` poderá ser útil para comparar " "valores inexatos:" +#: ../../tutorial/floatingpoint.rst:134 +msgid "" +">>> math.isclose(0.1 + 0.1 + 0.1, 0.3)\n" +"True" +msgstr "" +">>> math.isclose(0.1 + 0.1 + 0.1, 0.3)\n" +"True" + #: ../../tutorial/floatingpoint.rst:139 msgid "" "Alternatively, the :func:`round` function can be used to compare rough " @@ -240,6 +315,14 @@ msgstr "" "Alternativamente, a função :func:`round` pode ser usada para comparar " "aproximações aproximadas:" +#: ../../tutorial/floatingpoint.rst:142 +msgid "" +">>> round(math.pi, ndigits=2) == round(22 / 7, ndigits=2)\n" +"True" +msgstr "" +">>> round(math.pi, ndigits=2) == round(22 / 7, ndigits=2)\n" +"True" + #: ../../tutorial/floatingpoint.rst:147 msgid "" "Binary floating-point arithmetic holds many surprises like this. The " @@ -337,9 +420,19 @@ msgid "" "as_integer_ratio` method expresses the value of a float as a fraction:" msgstr "" "O Python fornece ferramentas que podem ajudar nessas raras ocasiões em que " -"realmente *faz* necessitas conhecer o valor exato de um float. O método :" -"meth:`float.as_integer_ratio` expressa o valor do tipo float em sua forma " -"fracionária:" +"realmente *faz* necessário conhecer o valor exato de um ponto flutuante. O " +"método :meth:`float.as_integer_ratio` expressa o valor de um número do tipo " +"float em sua forma fracionária:" + +#: ../../tutorial/floatingpoint.rst:186 +msgid "" +">>> x = 3.14159\n" +">>> x.as_integer_ratio()\n" +"(3537115888337719, 1125899906842624)" +msgstr "" +">>> x = 3.14159\n" +">>> x.as_integer_ratio()\n" +"(3537115888337719, 1125899906842624)" #: ../../tutorial/floatingpoint.rst:192 msgid "" @@ -347,15 +440,31 @@ msgid "" "value:" msgstr "" "Uma vez que a relação seja exata, será possível utiliza-la para obter, sem " -"que haja quaisquer perda o valor original:" +"que haja quaisquer perda do valor original:" + +#: ../../tutorial/floatingpoint.rst:195 +msgid "" +">>> x == 3537115888337719 / 1125899906842624\n" +"True" +msgstr "" +">>> x == 3537115888337719 / 1125899906842624\n" +"True" #: ../../tutorial/floatingpoint.rst:200 msgid "" "The :meth:`float.hex` method expresses a float in hexadecimal (base 16), " "again giving the exact value stored by your computer:" msgstr "" -"O método :meth:`float.hex` expressa um tipo float em hexadecimal (base 16), " -"o mesmo também conferirá o valor exato pelo computador:" +"O método :meth:`float.hex` expressa um ponto flutuante em hexadecimal (base " +"16), o mesmo também retornará o valor exato pelo computador:" + +#: ../../tutorial/floatingpoint.rst:203 +msgid "" +">>> x.hex()\n" +"'0x1.921f9f01b866ep+1'" +msgstr "" +">>> x.hex()\n" +"'0x1.921f9f01b866ep+1'" #: ../../tutorial/floatingpoint.rst:208 msgid "" @@ -363,7 +472,15 @@ msgid "" "value exactly:" msgstr "" "Sua precisa representação hexadecimal poderá ser utilizada para reconstruir " -"o valor exato do float:" +"o valor exato do ponto flutuante:" + +#: ../../tutorial/floatingpoint.rst:211 +msgid "" +">>> x == float.fromhex('0x1.921f9f01b866ep+1')\n" +"True" +msgstr "" +">>> x == float.fromhex('0x1.921f9f01b866ep+1')\n" +"True" #: ../../tutorial/floatingpoint.rst:216 msgid "" @@ -392,19 +509,70 @@ msgstr "" "forma que os erros não se acumulem chegando ao ponto de afetar o resultado " "final:" +#: ../../tutorial/floatingpoint.rst:226 +msgid "" +">>> 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1.0\n" +"False\n" +">>> sum([0.1] * 10) == 1.0\n" +"True" +msgstr "" +">>> 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1.0\n" +"False\n" +">>> sum([0.1] * 10) == 1.0\n" +"True" + #: ../../tutorial/floatingpoint.rst:233 msgid "" -"The :func:`math.fsum()` goes further and tracks all of the \"lost digits\" " -"as values are added onto a running total so that the result has only a " -"single rounding. This is slower than :func:`sum` but will be more accurate " -"in uncommon cases where large magnitude inputs mostly cancel each other out " +"The :func:`math.fsum` goes further and tracks all of the \"lost digits\" as " +"values are added onto a running total so that the result has only a single " +"rounding. This is slower than :func:`sum` but will be more accurate in " +"uncommon cases where large magnitude inputs mostly cancel each other out " "leaving a final sum near zero:" msgstr "" -"A função :func:`math.fsum()` vai além e rastreia todos os \"dígitos " -"perdidos\" à medida que os valores são adicionados a um total contínuo, de " -"modo que o resultado tenha apenas um único arredondamento. Isso é mais lento " -"que :func:`sum`, mas será mais preciso em casos incomuns em que entradas de " -"grande magnitude se cancelam, deixando uma soma final próxima de zero:" +"A função :func:`math.fsum` vai além e rastreia todos os \"dígitos perdidos\" " +"à medida que os valores são adicionados a um total contínuo, de modo que o " +"resultado tenha apenas um único arredondamento. Isso é mais lento que :func:" +"`sum`, mas será mais preciso em casos incomuns em que entradas de grande " +"magnitude se cancelam, deixando uma soma final próxima de zero:" + +#: ../../tutorial/floatingpoint.rst:239 +msgid "" +">>> arr = [-0.10430216751806065, -266310978.67179024, 143401161448607.16,\n" +"... -143401161400469.7, 266262841.31058735, -0.003244936839808227]\n" +">>> float(sum(map(Fraction, arr))) # Exact summation with single rounding\n" +"8.042173697819788e-13\n" +">>> math.fsum(arr) # Single rounding\n" +"8.042173697819788e-13\n" +">>> sum(arr) # Multiple roundings in extended " +"precision\n" +"8.042178034628478e-13\n" +">>> total = 0.0\n" +">>> for x in arr:\n" +"... total += x # Multiple roundings in standard " +"precision\n" +"...\n" +">>> total # Straight addition has no correct " +"digits!\n" +"-0.0051575902860057365" +msgstr "" +">>> arr = [-0.10430216751806065, -266310978.67179024, 143401161448607.16,\n" +"... -143401161400469.7, 266262841.31058735, -0.003244936839808227]\n" +">>> float(sum(map(Fraction, arr))) # Soma exata com arredondamento " +"simples\n" +"8.042173697819788e-13\n" +">>> math.fsum(arr) # Arredondamento simples\n" +"8.042173697819788e-13\n" +">>> sum(arr) # Arredondamentos múltiplos em precisão " +"estendida\n" +"8.042178034628478e-13\n" +">>> total = 0.0\n" +">>> for x in arr:\n" +"... total += x # Arredondamentos múltiplos em precisão " +"padrão\n" +"...\n" +">>> total # A adição direta não tem dígitos " +"corretos!\n" +"-0.0051575902860057365" #: ../../tutorial/floatingpoint.rst:260 msgid "Representation Error" @@ -444,7 +612,7 @@ msgid "" "fraction it can of the form *J*/2**\\ *N* where *J* is an integer containing " "exactly 53 bits. Rewriting ::" msgstr "" -"Por que isso acontece? 1/10 não é representado exatamente ​​sendo fração " +"Por que isso acontece? 1/10 não é representado exatamente sendo fração " "binária. Desde pelo menos 2000, quase todas as máquinas usam aritmética " "binária de ponto flutuante da IEEE 754 e quase todas as plataformas " "representam pontos flutuante do Python como valores binary64 de \"double " @@ -453,10 +621,18 @@ msgstr "" "converter \"0.1\" para a fração mais próxima que puder, na forma *J*/2**\\ " "*N* onde *J* é um número inteiro contendo exatamente 53 bits. Reescrevendo::" +#: ../../tutorial/floatingpoint.rst:280 +msgid "1 / 10 ~= J / (2**N)" +msgstr "1 / 10 ~= J / (2**N)" + #: ../../tutorial/floatingpoint.rst:282 msgid "as ::" msgstr "como ::" +#: ../../tutorial/floatingpoint.rst:284 +msgid "J ~= 2**N / 10" +msgstr "J ~= 2**N / 10" + #: ../../tutorial/floatingpoint.rst:286 msgid "" "and recalling that *J* has exactly 53 bits (is ``>= 2**52`` but ``< " @@ -465,6 +641,14 @@ msgstr "" "e recordando que *J* tenha exatamente 53 bits (é ``>= 2**52``, mas ``< " "2**53``), o melhor valor para *N* é 56::" +#: ../../tutorial/floatingpoint.rst:289 +msgid "" +">>> 2**52 <= 2**56 // 10 < 2**53\n" +"True" +msgstr "" +">>> 2**52 <= 2**56 // 10 < 2**53\n" +"True" + #: ../../tutorial/floatingpoint.rst:294 msgid "" "That is, 56 is the only value for *N* that leaves *J* with exactly 53 bits. " @@ -474,6 +658,16 @@ msgstr "" "Portanto, o melhor valor que conseguimos obter pra *J* será aquele que " "possui o quociente arredondado:" +#: ../../tutorial/floatingpoint.rst:297 +msgid "" +">>> q, r = divmod(2**56, 10)\n" +">>> r\n" +"6" +msgstr "" +">>> q, r = divmod(2**56, 10)\n" +">>> r\n" +"6" + #: ../../tutorial/floatingpoint.rst:303 msgid "" "Since the remainder is more than half of 10, the best approximation is " @@ -482,6 +676,14 @@ msgstr "" "Uma vez que o resto seja maior do que a metade de 10, a melhor aproximação " "que poderá ser obtida se arredondarmos para cima:" +#: ../../tutorial/floatingpoint.rst:306 +msgid "" +">>> q+1\n" +"7205759403792794" +msgstr "" +">>> q+1\n" +"7205759403792794" + #: ../../tutorial/floatingpoint.rst:313 msgid "" "Therefore the best possible approximation to 1/10 in IEEE 754 double " @@ -490,11 +692,19 @@ msgstr "" "Portanto, a melhor aproximação possível de 1/10 como um \"IEEE 754 double " "precision\" é::" +#: ../../tutorial/floatingpoint.rst:316 +msgid "7205759403792794 / 2 ** 56" +msgstr "7205759403792794 / 2 ** 56" + #: ../../tutorial/floatingpoint.rst:318 msgid "" "Dividing both the numerator and denominator by two reduces the fraction to::" msgstr "Dividir o numerador e o denominador por dois reduzirá a fração para::" +#: ../../tutorial/floatingpoint.rst:320 +msgid "3602879701896397 / 2 ** 55" +msgstr "3602879701896397 / 2 ** 55" + #: ../../tutorial/floatingpoint.rst:322 msgid "" "Note that since we rounded up, this is actually a little bit larger than " @@ -514,14 +724,30 @@ msgstr "" "Por isso, o computador nunca \"vê\" 1/10: o que ele vê é exatamente a fração " "que é obtida pra cima, a melhor aproximação \"IEEE 754 double\" possível é:" +#: ../../tutorial/floatingpoint.rst:329 +msgid "" +">>> 0.1 * 2 ** 55\n" +"3602879701896397.0" +msgstr "" +">>> 0.1 * 2 ** 55\n" +"3602879701896397.0" + #: ../../tutorial/floatingpoint.rst:334 msgid "" "If we multiply that fraction by 10\\*\\*55, we can see the value out to 55 " "decimal digits:" msgstr "" -"Se multiplicarmos essa fração por 10\\*\\*30, podemos ver o valor contendo " +"Se multiplicarmos essa fração por 10\\*\\*55, podemos ver o valor contendo " "os 55 dígitos mais significativos:" +#: ../../tutorial/floatingpoint.rst:337 +msgid "" +">>> 3602879701896397 * 10 ** 55 // 2 ** 55\n" +"1000000000000000055511151231257827021181583404541015625" +msgstr "" +">>> 3602879701896397 * 10 ** 55 // 2 ** 55\n" +"1000000000000000055511151231257827021181583404541015625" + #: ../../tutorial/floatingpoint.rst:342 msgid "" "meaning that the exact number stored in the computer is equal to the decimal " @@ -534,9 +760,49 @@ msgstr "" "exibir o valor decimal completo, muitas linguagens (incluindo versões mais " "antigas do Python), arredondam o resultado para 17 dígitos significativos:" +#: ../../tutorial/floatingpoint.rst:347 +msgid "" +">>> format(0.1, '.17f')\n" +"'0.10000000000000001'" +msgstr "" +">>> format(0.1, '.17f')\n" +"'0.10000000000000001'" + #: ../../tutorial/floatingpoint.rst:352 msgid "" "The :mod:`fractions` and :mod:`decimal` modules make these calculations easy:" msgstr "" "Módulos como o :mod:`fractions` e o :mod:`decimal` tornam esses cálculos " "muito mais fáceis:" + +#: ../../tutorial/floatingpoint.rst:355 +msgid "" +">>> from decimal import Decimal\n" +">>> from fractions import Fraction\n" +"\n" +">>> Fraction.from_float(0.1)\n" +"Fraction(3602879701896397, 36028797018963968)\n" +"\n" +">>> (0.1).as_integer_ratio()\n" +"(3602879701896397, 36028797018963968)\n" +"\n" +">>> Decimal.from_float(0.1)\n" +"Decimal('0.1000000000000000055511151231257827021181583404541015625')\n" +"\n" +">>> format(Decimal.from_float(0.1), '.17')\n" +"'0.10000000000000001'" +msgstr "" +">>> from decimal import Decimal\n" +">>> from fractions import Fraction\n" +"\n" +">>> Fraction.from_float(0.1)\n" +"Fraction(3602879701896397, 36028797018963968)\n" +"\n" +">>> (0.1).as_integer_ratio()\n" +"(3602879701896397, 36028797018963968)\n" +"\n" +">>> Decimal.from_float(0.1)\n" +"Decimal('0.1000000000000000055511151231257827021181583404541015625')\n" +"\n" +">>> format(Decimal.from_float(0.1), '.17')\n" +"'0.10000000000000001'" diff --git a/tutorial/index.po b/tutorial/index.po index 4fe3dfe03..aaff4b39f 100644 --- a/tutorial/index.po +++ b/tutorial/index.po @@ -1,37 +1,43 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Leticia Portella , 2021 -# Adorilson Bezerra , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:50+0000\n" -"Last-Translator: Adorilson Bezerra , 2021\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../tutorial/index.rst:5 msgid "The Python Tutorial" -msgstr "O tutorial de Python" +msgstr "O tutorial do Python" #: ../../tutorial/index.rst:7 msgid "" +"This tutorial is designed for *programmers* that are new to the Python " +"language, **not** *beginners* who are new to programming." +msgstr "" +"Este tutorial foi desenvolvido para pessoas *que já programam*, mas são " +"recém-chegadas na linguagem Python, **não** pessoas *iniciantes* em " +"programação." + +#: ../../tutorial/index.rst:11 +msgid "" "Python is an easy to learn, powerful programming language. It has efficient " "high-level data structures and a simple but effective approach to object-" "oriented programming. Python's elegant syntax and dynamic typing, together " @@ -40,12 +46,12 @@ msgid "" msgstr "" "Python é uma linguagem fácil de aprender e poderosa. Ela tem estruturas de " "dados de alto nível eficientes e uma abordagem simples mas efetiva de " -"programação orientada a objetos. A elegância de sintaxe e a tipagem dinâmica " -"de Python aliadas com sua natureza interpretativa, o fazem a linguagem ideal " -"para programas e desenvolvimento de aplicações rápidas em diversas áreas e " -"na maioria das plataformas." +"programação orientada a objetos. A sintaxe elegante e a tipagem dinâmica do " +"Python, aliadas com sua natureza interpretativa, o tornam uma linguagem " +"ideal para fazer scripts e desenvolvimento de aplicações rápidas em diversas " +"áreas e na maioria das plataformas." -#: ../../tutorial/index.rst:13 +#: ../../tutorial/index.rst:17 msgid "" "The Python interpreter and the extensive standard library are freely " "available in source or binary form for all major platforms from the Python " @@ -53,38 +59,40 @@ msgid "" "site also contains distributions of and pointers to many free third party " "Python modules, programs and tools, and additional documentation." msgstr "" -"O interpretador Python e a extensiva biblioteca padrão estão disponíveis " -"gratuitamente em código ou na forma binária para todas as maiores " -"plataformas no endereço eletrônico do Python, https://www.python.org/, e " -"pode ser livremente distribuído. O mesmo endereço contém distribuições de " -"diversos módulos, programas e ferramentas gratuitos produzidos por terceiros " -"e documentação adicional." +"O interpretador do Python e sua extensiva biblioteca padrão estão " +"disponíveis gratuitamente na forma de código ou binária para todas as " +"principais plataformas no endereço eletrônico do Python, https://www.python." +"org/, e pode ser livremente distribuído. O mesmo endereço contém " +"distribuições e indicações de diversos módulos, programas e ferramentas " +"gratuitos produzidos por terceiros e documentação adicional." -#: ../../tutorial/index.rst:19 +#: ../../tutorial/index.rst:23 msgid "" "The Python interpreter is easily extended with new functions and data types " "implemented in C or C++ (or other languages callable from C). Python is also " "suitable as an extension language for customizable applications." msgstr "" -"O interpretador Python pode ser facilmente estendido com novas funções e " -"tipos de dados implementados em C ou C++ (ou outras linguagens chamadas a " -"partir de C). Python também é adequada como uma linguagem de extensão para " +"O interpretador do Python pode ser facilmente estendido com novas funções e " +"tipos de dados implementados em C ou C++ (ou outras linguagens chamáveis a " +"partir de C). Python também é adequado como uma linguagem de extensão para " "aplicações personalizáveis." -#: ../../tutorial/index.rst:23 +#: ../../tutorial/index.rst:27 msgid "" "This tutorial introduces the reader informally to the basic concepts and " -"features of the Python language and system. It helps to have a Python " -"interpreter handy for hands-on experience, but all examples are self-" +"features of the Python language and system. Be aware that it expects you to " +"have a basic understanding of programming in general. It helps to have a " +"Python interpreter handy for hands-on experience, but all examples are self-" "contained, so the tutorial can be read off-line as well." msgstr "" "Este tutorial introduz informalmente o leitor aos conceitos básicos e aos " -"recursos da linguagem e do sistema Python. É mais fácil se você possuir um " -"interpretador Python para uma experiência prática, mas os exemplos são " -"autossuficientes e, portanto, o tutorial pode apenas ser lido off-line " -"também." +"recursos da linguagem e do sistema Python. Esteja ciente de que ele espera " +"que você tenha um conhecimento básico de programação em geral. É mais fácil " +"se você possuir um interpretador Python para uma experiência prática, mas os " +"exemplos são autossuficientes e, portanto, o tutorial pode apenas ser lido " +"off-line também." -#: ../../tutorial/index.rst:28 +#: ../../tutorial/index.rst:33 msgid "" "For a description of standard objects and modules, see :ref:`library-" "index`. :ref:`reference-index` gives a more formal definition of the " @@ -93,11 +101,11 @@ msgid "" msgstr "" "Para uma descrição detalhada dos módulos e objetos padrões, veja :ref:" "`library-index`. Em :ref:`reference-index` você encontra uma definição mais " -"formal da linguagem. Para escrever extensões em C ou C++ leia :ref:" +"formal da linguagem. Para escrever extensões em C ou C++, leia :ref:" "`extending-index` e :ref:`c-api-index`. Existe também uma série de livros " "que cobrem Python em profundidade." -#: ../../tutorial/index.rst:33 +#: ../../tutorial/index.rst:38 msgid "" "This tutorial does not attempt to be comprehensive and cover every single " "feature, or even every commonly used feature. Instead, it introduces many of " @@ -113,6 +121,6 @@ msgstr "" "Python e estará pronto para aprender mais sobre os diversos módulos " "descritos em :ref:`library-index`." -#: ../../tutorial/index.rst:40 +#: ../../tutorial/index.rst:45 msgid "The :ref:`glossary` is also worth going through." msgstr "O :ref:`glossary` também vale a pena ser estudado." diff --git a/tutorial/inputoutput.po b/tutorial/inputoutput.po index 55b073baf..1752ab3ae 100644 --- a/tutorial/inputoutput.po +++ b/tutorial/inputoutput.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Adson Rodrigues , 2021 -# Clara Matos, 2022 -# Marco Rougeth , 2023 -# Adorilson Bezerra , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-05 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 01:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -83,6 +77,18 @@ msgstr "" "dessa string, pode-se escrever uma expressão Python entre caracteres ``{`` e " "``}``, que podem se referir a variáveis, ou valores literais." +#: ../../tutorial/inputoutput.rst:32 +msgid "" +">>> year = 2016\n" +">>> event = 'Referendum'\n" +">>> f'Results of the {year} {event}'\n" +"'Results of the 2016 Referendum'" +msgstr "" +">>> ano = 2016\n" +">>> evento = 'Referendo'\n" +">>> f'Resultados do {evento} {ano}'\n" +"'Resultados do Referendo 2016'" + #: ../../tutorial/inputoutput.rst:37 msgid "" "The :meth:`str.format` method of strings requires more manual effort. " @@ -97,6 +103,20 @@ msgstr "" "precisará incluir a informação a ser formatada. No bloco de código a seguir " "há dois exemplos de como formatar variáveis:" +#: ../../tutorial/inputoutput.rst:46 +msgid "" +">>> yes_votes = 42_572_654\n" +">>> total_votes = 85_705_149\n" +">>> percentage = yes_votes / total_votes\n" +">>> '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage)\n" +"' 42572654 YES votes 49.67%'" +msgstr "" +">>> votos_sim = 42_572_654\n" +">>> votos_totais = 85_705_149\n" +">>> porcentagem = votos_sim / votos_totais\n" +">>> '{:-9} votos SIM {:2.2%}'.format(votos_sim, porcentagem)\n" +"' 42572654 votos SIM 49.67%'" + #: ../../tutorial/inputoutput.rst:52 msgid "" "Notice how the ``yes_votes`` are padded with spaces and a negative sign only " @@ -155,6 +175,50 @@ msgstr "" msgid "Some examples::" msgstr "Alguns exemplos:" +#: ../../tutorial/inputoutput.rst:77 +msgid "" +">>> s = 'Hello, world.'\n" +">>> str(s)\n" +"'Hello, world.'\n" +">>> repr(s)\n" +"\"'Hello, world.'\"\n" +">>> str(1/7)\n" +"'0.14285714285714285'\n" +">>> x = 10 * 3.25\n" +">>> y = 200 * 200\n" +">>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'\n" +">>> print(s)\n" +"The value of x is 32.5, and y is 40000...\n" +">>> # The repr() of a string adds string quotes and backslashes:\n" +">>> hello = 'hello, world\\n'\n" +">>> hellos = repr(hello)\n" +">>> print(hellos)\n" +"'hello, world\\n'\n" +">>> # The argument to repr() may be any Python object:\n" +">>> repr((x, y, ('spam', 'eggs')))\n" +"\"(32.5, 40000, ('spam', 'eggs'))\"" +msgstr "" +">>> s = 'Olá, mundo.'\n" +">>> str(s)\n" +"'Olá, mundo.'\n" +">>> repr(s)\n" +"\"'Olá, mundo.'\"\n" +">>> str(1/7)\n" +"'0.14285714285714285'\n" +">>> x = 10 * 3.25\n" +">>> y = 200 * 200\n" +">>> s = 'O valor de x é ' + repr(x) + ' e de y é ' + repr(y) + '...'\n" +">>> print(s)\n" +"O valor de x é 32.5 e de y é 40000...\n" +">>> # A repr() da string adiciona aspas e contrabarras:\n" +">>> olá = 'olá, mundo\\n'\n" +">>> olás = repr(olá)\n" +">>> print(olás)\n" +"'olá, mundo\\n'\n" +">>> # O argumento de repr() pode ser qualquer objeto Python:\n" +">>> repr((x, y, ('spam', 'ovos')))\n" +"\"(32.5, 40000, ('spam', 'ovos'))\"" + #: ../../tutorial/inputoutput.rst:98 msgid "" "The :mod:`string` module contains a :class:`~string.Template` class that " @@ -167,11 +231,11 @@ msgstr "" "reservados como ``$x`` e substituindo-os por valores de um dicionário, mas " "oferece muito menos controle da formatação." -#: ../../tutorial/inputoutput.rst:107 +#: ../../tutorial/inputoutput.rst:114 msgid "Formatted String Literals" msgstr "Strings literais formatadas" -#: ../../tutorial/inputoutput.rst:109 +#: ../../tutorial/inputoutput.rst:116 msgid "" ":ref:`Formatted string literals ` (also called f-strings for " "short) let you include the value of Python expressions inside a string by " @@ -183,7 +247,7 @@ msgstr "" "uma string, prefixando-a com ``f`` ou ``F`` e escrevendo expressões na forma " "``{expression}``." -#: ../../tutorial/inputoutput.rst:114 +#: ../../tutorial/inputoutput.rst:121 msgid "" "An optional format specifier can follow the expression. This allows greater " "control over how the value is formatted. The following example rounds pi to " @@ -193,7 +257,17 @@ msgstr "" "Isso permite maior controle sobre como o valor é formatado. O exemplo a " "seguir arredonda pi para três casas decimais::" -#: ../../tutorial/inputoutput.rst:122 +#: ../../tutorial/inputoutput.rst:125 +msgid "" +">>> import math\n" +">>> print(f'The value of pi is approximately {math.pi:.3f}.')\n" +"The value of pi is approximately 3.142." +msgstr "" +">>> import math\n" +">>> print(f'O valor de pi é aproximadamente {math.pi:.3f}.')\n" +"O valor de pi é aproximadamente 3.142." + +#: ../../tutorial/inputoutput.rst:129 msgid "" "Passing an integer after the ``':'`` will cause that field to be a minimum " "number of characters wide. This is useful for making columns line up. ::" @@ -201,7 +275,25 @@ msgstr "" "Passando um inteiro após o ``':'`` fará com que o campo tenha um número " "mínimo de caracteres de largura. Isso é útil para alinhar colunas. ::" -#: ../../tutorial/inputoutput.rst:133 +#: ../../tutorial/inputoutput.rst:132 +msgid "" +">>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}\n" +">>> for name, phone in table.items():\n" +"... print(f'{name:10} ==> {phone:10d}')\n" +"...\n" +"Sjoerd ==> 4127\n" +"Jack ==> 4098\n" +"Dcab ==> 7678" +msgstr "" +">>> tabela = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}\n" +">>> for nome, telefone in tabela.items():\n" +"... print(f'{n9me:10} ==> {telefone:10d}')\n" +"...\n" +"Sjoerd ==> 4127\n" +"Jack ==> 4098\n" +"Dcab ==> 7678" + +#: ../../tutorial/inputoutput.rst:140 msgid "" "Other modifiers can be used to convert the value before it is formatted. ``'!" "a'`` applies :func:`ascii`, ``'!s'`` applies :func:`str`, and ``'!r'`` " @@ -211,7 +303,21 @@ msgstr "" "formatado. ``'!a'`` aplica a função :func:`ascii`, ``'!s'`` aplica a função :" "func:`str` e ``'!r'`` aplica a função :func:`repr` ::" -#: ../../tutorial/inputoutput.rst:143 +#: ../../tutorial/inputoutput.rst:144 +msgid "" +">>> animals = 'eels'\n" +">>> print(f'My hovercraft is full of {animals}.')\n" +"My hovercraft is full of eels.\n" +">>> print(f'My hovercraft is full of {animals!r}.')\n" +"My hovercraft is full of 'eels'." +msgstr "" +">>> animais = 'enguias'\n" +">>> print(f'Meu hovercraft está cheio de {animais}.')\n" +"Meu hovercraft está cheio de enguias.\n" +">>> print(f'Meu hovercraft está cheio de {animais!r}.')\n" +"Meu hovercraft está cheio de 'enguias'." + +#: ../../tutorial/inputoutput.rst:150 msgid "" "The ``=`` specifier can be used to expand an expression to the text of the " "expression, an equal sign, then the representation of the evaluated " @@ -221,7 +327,7 @@ msgstr "" "texto da expressão, um sinal de igual e, então, a representação da expressão " "avaliada:" -#: ../../tutorial/inputoutput.rst:152 +#: ../../tutorial/inputoutput.rst:159 msgid "" "See :ref:`self-documenting expressions ` for more " "information on the ``=`` specifier. For a reference on these format " @@ -232,15 +338,23 @@ msgstr "" "essas especificações de formato, consulte o guia de referência para a :ref:" "`formatspec`." -#: ../../tutorial/inputoutput.rst:159 +#: ../../tutorial/inputoutput.rst:166 msgid "The String format() Method" msgstr "O método format()" -#: ../../tutorial/inputoutput.rst:161 +#: ../../tutorial/inputoutput.rst:168 msgid "Basic usage of the :meth:`str.format` method looks like this::" msgstr "Um uso básico do método :meth:`str.format` tem esta forma::" -#: ../../tutorial/inputoutput.rst:166 +#: ../../tutorial/inputoutput.rst:170 +msgid "" +">>> print('We are the {} who say \"{}!\"'.format('knights', 'Ni'))\n" +"We are the knights who say \"Ni!\"" +msgstr "" +">>> print('Nós somos os {} que dizem \"{}!\"'.format('cavaleiros', 'Ni'))\n" +"Nós somos os cavaleiros que dizem \"Ni!\"" + +#: ../../tutorial/inputoutput.rst:173 msgid "" "The brackets and characters within them (called format fields) are replaced " "with the objects passed into the :meth:`str.format` method. A number in the " @@ -252,7 +366,19 @@ msgstr "" "chaves pode ser usado para referenciar a posição do objeto passado no " "método :meth:`str.format`. ::" -#: ../../tutorial/inputoutput.rst:176 +#: ../../tutorial/inputoutput.rst:178 +msgid "" +">>> print('{0} and {1}'.format('spam', 'eggs'))\n" +"spam and eggs\n" +">>> print('{1} and {0}'.format('spam', 'eggs'))\n" +"eggs and spam" +msgstr "" +">>> print('{0} e {1}'.format('spam', 'ovos'))\n" +"spam e eggs\n" +">>> print('{1} e {0}'.format('spam', 'ovos'))\n" +"eggs e spam" + +#: ../../tutorial/inputoutput.rst:183 msgid "" "If keyword arguments are used in the :meth:`str.format` method, their values " "are referred to by using the name of the argument. ::" @@ -260,11 +386,31 @@ msgstr "" "Se argumentos nomeados são passados para o método :meth:`str.format`, seus " "valores serão referenciados usando o nome do argumento::" -#: ../../tutorial/inputoutput.rst:183 +#: ../../tutorial/inputoutput.rst:186 +msgid "" +">>> print('This {food} is {adjective}.'.format(\n" +"... food='spam', adjective='absolutely horrible'))\n" +"This spam is absolutely horrible." +msgstr "" +">>> print('Este {comida} está {adjetivo}.'.format(\n" +"... comida='spam', adjetivo='absolutamente horrível'))\n" +"Este spam está absolutamente horrível." + +#: ../../tutorial/inputoutput.rst:190 msgid "Positional and keyword arguments can be arbitrarily combined::" msgstr "Argumentos posicionais e nomeados podem ser combinados à vontade::" -#: ../../tutorial/inputoutput.rst:189 +#: ../../tutorial/inputoutput.rst:192 +msgid "" +">>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',\n" +"... other='Georg'))\n" +"The story of Bill, Manfred, and Georg." +msgstr "" +">>> print('A história de {0}, {1} e {outro}.'.format('Bill', 'Manfred',\n" +"... outro='Georg'))\n" +"A história de Bill, Manfred e Georg." + +#: ../../tutorial/inputoutput.rst:196 msgid "" "If you have a really long format string that you don't want to split up, it " "would be nice if you could reference the variables to be formatted by name " @@ -276,7 +422,19 @@ msgstr "" "posição. Isto pode ser feito passando um dicionário usando colchetes " "``'[]'`` para acessar as chaves. ::" -#: ../../tutorial/inputoutput.rst:199 +#: ../../tutorial/inputoutput.rst:201 +msgid "" +">>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}\n" +">>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '\n" +"... 'Dcab: {0[Dcab]:d}'.format(table))\n" +"Jack: 4098; Sjoerd: 4127; Dcab: 8637678" +msgstr "" +">>> tabela = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}\n" +">>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '\n" +"... 'Dcab: {0[Dcab]:d}'.format(tabela))\n" +"Jack: 4098; Sjoerd: 4127; Dcab: 8637678" + +#: ../../tutorial/inputoutput.rst:206 msgid "" "This could also be done by passing the ``table`` dictionary as keyword " "arguments with the ``**`` notation. ::" @@ -284,7 +442,19 @@ msgstr "" "Isto também pode ser feito passando o dicionário ``table`` como argumentos " "nomeados com a notação ``**``. ::" -#: ../../tutorial/inputoutput.rst:206 +#: ../../tutorial/inputoutput.rst:209 +msgid "" +">>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}\n" +">>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'." +"format(**table))\n" +"Jack: 4098; Sjoerd: 4127; Dcab: 8637678" +msgstr "" +">>> tabela = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}\n" +">>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'." +"format(**tabela))\n" +"Jack: 4098; Sjoerd: 4127; Dcab: 8637678" + +#: ../../tutorial/inputoutput.rst:213 msgid "" "This is particularly useful in combination with the built-in function :func:" "`vars`, which returns a dictionary containing all local variables::" @@ -292,7 +462,20 @@ msgstr "" "Isto é particularmente útil em conjunto com a função embutida :func:`vars`, " "que devolve um dicionário contendo todas as variáveis locais::" -#: ../../tutorial/inputoutput.rst:214 +#: ../../tutorial/inputoutput.rst:216 +msgid "" +">>> table = {k: str(v) for k, v in vars().items()}\n" +">>> message = \" \".join([f'{k}: ' + '{' + k +'};' for k in table.keys()])\n" +">>> print(message.format(**table))\n" +"__name__: __main__; __doc__: None; __package__: None; __loader__: ..." +msgstr "" +">>> tabela = {k: str(v) for k, v in vars().items()}\n" +">>> mensagem = \" \".join([f'{k}: ' + '{' + k +'};' for k in tabela." +"keys()])\n" +">>> print(mensagem.format(**tabela))\n" +"__name__: __main__; __doc__: None; __package__: None; __loader__: ..." + +#: ../../tutorial/inputoutput.rst:221 msgid "" "As an example, the following lines produce a tidily aligned set of columns " "giving integers and their squares and cubes::" @@ -300,7 +483,37 @@ msgstr "" "Como exemplo, as linhas seguintes produzem um conjunto de colunas alinhadas, " "com alguns inteiros e seus quadrados e cubos::" -#: ../../tutorial/inputoutput.rst:231 +#: ../../tutorial/inputoutput.rst:224 +msgid "" +">>> for x in range(1, 11):\n" +"... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))\n" +"...\n" +" 1 1 1\n" +" 2 4 8\n" +" 3 9 27\n" +" 4 16 64\n" +" 5 25 125\n" +" 6 36 216\n" +" 7 49 343\n" +" 8 64 512\n" +" 9 81 729\n" +"10 100 1000" +msgstr "" +">>> for x in range(1, 11):\n" +"... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))\n" +"...\n" +" 1 1 1\n" +" 2 4 8\n" +" 3 9 27\n" +" 4 16 64\n" +" 5 25 125\n" +" 6 36 216\n" +" 7 49 343\n" +" 8 64 512\n" +" 9 81 729\n" +"10 100 1000" + +#: ../../tutorial/inputoutput.rst:238 msgid "" "For a complete overview of string formatting with :meth:`str.format`, see :" "ref:`formatstrings`." @@ -308,16 +521,50 @@ msgstr "" "Para uma visão completa da formatação de strings com :meth:`str.format`, " "veja a seção :ref:`formatstrings`." -#: ../../tutorial/inputoutput.rst:236 +#: ../../tutorial/inputoutput.rst:243 msgid "Manual String Formatting" msgstr "Formatação manual de string" -#: ../../tutorial/inputoutput.rst:238 +#: ../../tutorial/inputoutput.rst:245 msgid "Here's the same table of squares and cubes, formatted manually::" msgstr "" "Aqui está a mesma tabela de quadrados e cubos, formatados manualmente::" -#: ../../tutorial/inputoutput.rst:256 +#: ../../tutorial/inputoutput.rst:247 +msgid "" +">>> for x in range(1, 11):\n" +"... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')\n" +"... # Note use of 'end' on previous line\n" +"... print(repr(x*x*x).rjust(4))\n" +"...\n" +" 1 1 1\n" +" 2 4 8\n" +" 3 9 27\n" +" 4 16 64\n" +" 5 25 125\n" +" 6 36 216\n" +" 7 49 343\n" +" 8 64 512\n" +" 9 81 729\n" +"10 100 1000" +msgstr "" +">>> for x in range(1, 11):\n" +"... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')\n" +"... # Observe o uso do 'end' na linha anterior\n" +"... print(repr(x*x*x).rjust(4))\n" +"...\n" +" 1 1 1\n" +" 2 4 8\n" +" 3 9 27\n" +" 4 16 64\n" +" 5 25 125\n" +" 6 36 216\n" +" 7 49 343\n" +" 8 64 512\n" +" 9 81 729\n" +"10 100 1000" + +#: ../../tutorial/inputoutput.rst:263 msgid "" "(Note that the one space between each column was added by the way :func:" "`print` works: it always adds spaces between its arguments.)" @@ -325,7 +572,7 @@ msgstr "" "(Note que o espaço entre cada coluna foi adicionado pela forma que a função :" "func:`print` funciona: sempre adiciona espaços entre seus argumentos.)" -#: ../../tutorial/inputoutput.rst:259 +#: ../../tutorial/inputoutput.rst:266 msgid "" "The :meth:`str.rjust` method of string objects right-justifies a string in a " "field of a given width by padding it with spaces on the left. There are " @@ -346,7 +593,7 @@ msgstr "" "distorcendo o valor. (Se realmente quiser truncar, sempre se pode adicionar " "uma operação de fatiamento, como em ``x.ljust(n)[:n]``.)" -#: ../../tutorial/inputoutput.rst:268 +#: ../../tutorial/inputoutput.rst:275 msgid "" "There is another method, :meth:`str.zfill`, which pads a numeric string on " "the left with zeros. It understands about plus and minus signs::" @@ -354,11 +601,27 @@ msgstr "" "Existe ainda o método :meth:`str.zfill` que preenche uma string numérica com " "zeros à esquerda, e sabe lidar com sinais positivos e negativos::" -#: ../../tutorial/inputoutput.rst:280 +#: ../../tutorial/inputoutput.rst:278 +msgid "" +">>> '12'.zfill(5)\n" +"'00012'\n" +">>> '-3.14'.zfill(7)\n" +"'-003.14'\n" +">>> '3.14159265359'.zfill(5)\n" +"'3.14159265359'" +msgstr "" +">>> '12'.zfill(5)\n" +"'00012'\n" +">>> '-3.14'.zfill(7)\n" +"'-003.14'\n" +">>> '3.14159265359'.zfill(5)\n" +"'3.14159265359'" + +#: ../../tutorial/inputoutput.rst:287 msgid "Old string formatting" msgstr "Formatação de strings à moda antiga" -#: ../../tutorial/inputoutput.rst:282 +#: ../../tutorial/inputoutput.rst:289 msgid "" "The % operator (modulo) can also be used for string formatting. Given " "``format % values`` (where *format* is a string), ``%`` conversion " @@ -371,17 +634,27 @@ msgstr "" "em ``formato`` serão substituídas por zero ou mais elementos de ``valores``. " "Essa operação é conhecida como interpolação de string. Por exemplo::" -#: ../../tutorial/inputoutput.rst:293 +#: ../../tutorial/inputoutput.rst:296 +msgid "" +">>> import math\n" +">>> print('The value of pi is approximately %5.3f.' % math.pi)\n" +"The value of pi is approximately 3.142." +msgstr "" +">>> import math\n" +">>> print('O valor de pi é aproximadamente %5.3f.' % math.pi)\n" +"O valor de pi é aproximadamente 3.142." + +#: ../../tutorial/inputoutput.rst:300 msgid "" "More information can be found in the :ref:`old-string-formatting` section." msgstr "" "Mais informação pode ser encontrada na seção :ref:`old-string-formatting`." -#: ../../tutorial/inputoutput.rst:299 +#: ../../tutorial/inputoutput.rst:306 msgid "Reading and Writing Files" msgstr "Leitura e escrita de arquivos" -#: ../../tutorial/inputoutput.rst:305 +#: ../../tutorial/inputoutput.rst:312 msgid "" ":func:`open` returns a :term:`file object`, and is most commonly used with " "two positional arguments and one keyword argument: ``open(filename, mode, " @@ -392,6 +665,10 @@ msgstr "" "encoding=None)``" #: ../../tutorial/inputoutput.rst:318 +msgid ">>> f = open('workfile', 'w', encoding=\"utf-8\")" +msgstr ">>> f = open('arquivo_de_trabalho', 'w', encoding=\"utf-8\")" + +#: ../../tutorial/inputoutput.rst:325 msgid "" "The first argument is a string containing the filename. The second argument " "is another string containing a few characters describing the way in which " @@ -411,7 +688,7 @@ msgstr "" "tanto para leitura como para escrita. O argumento *modo* é opcional, em caso " "de omissão será presumido ``'r'``." -#: ../../tutorial/inputoutput.rst:327 +#: ../../tutorial/inputoutput.rst:334 msgid "" "Normally, files are opened in :dfn:`text mode`, that means, you read and " "write strings from and to the file, which are encoded in a specific " @@ -432,7 +709,7 @@ msgstr "" "objetos :class:`bytes`. Você não pode especificar a *codificação* quando " "estiver abrindo os arquivos em modo binário." -#: ../../tutorial/inputoutput.rst:337 +#: ../../tutorial/inputoutput.rst:344 msgid "" "In text mode, the default when reading is to convert platform-specific line " "endings (``\\n`` on Unix, ``\\r\\n`` on Windows) to just ``\\n``. When " @@ -451,7 +728,7 @@ msgstr "" "`JPEG` ou :file:`EXE`. Tenha muito cuidado para só usar o modo binário, ao " "ler e gravar esses arquivos." -#: ../../tutorial/inputoutput.rst:345 +#: ../../tutorial/inputoutput.rst:352 msgid "" "It is good practice to use the :keyword:`with` keyword when dealing with " "file objects. The advantage is that the file is properly closed after its " @@ -467,6 +744,22 @@ msgstr "" #: ../../tutorial/inputoutput.rst:358 msgid "" +">>> with open('workfile', encoding=\"utf-8\") as f:\n" +"... read_data = f.read()\n" +"\n" +">>> # We can check that the file has been automatically closed.\n" +">>> f.closed\n" +"True" +msgstr "" +">>> with open('arquivo_de_trabalho', encoding=\"utf-8\") as f:\n" +"... read_data = f.read()\n" +"\n" +">>> # Podemos verificar se o arquivo foi fechado automaticamente.\n" +">>> f.closed\n" +"True" + +#: ../../tutorial/inputoutput.rst:365 +msgid "" "If you're not using the :keyword:`with` keyword, then you should call ``f." "close()`` to close the file and immediately free up any system resources " "used by it." @@ -475,7 +768,7 @@ msgstr "" "deveria chamar ``f.close()`` para fechar o arquivo e imediatamente liberar " "qualquer recurso do sistema usado por ele." -#: ../../tutorial/inputoutput.rst:363 +#: ../../tutorial/inputoutput.rst:370 msgid "" "Calling ``f.write()`` without using the :keyword:`!with` keyword or calling " "``f.close()`` **might** result in the arguments of ``f.write()`` not being " @@ -485,7 +778,7 @@ msgstr "" "``f.close()`` **pode** resultar nos argumentos de ``f.write()`` não serem " "completamente escritos no disco, mesmo se o programa for encerrado com êxito." -#: ../../tutorial/inputoutput.rst:371 +#: ../../tutorial/inputoutput.rst:378 msgid "" "After a file object is closed, either by a :keyword:`with` statement or by " "calling ``f.close()``, attempts to use the file object will automatically " @@ -495,11 +788,25 @@ msgstr "" "chamando ``f.close()``, as tentativas de usar o arquivo falharão " "automaticamente. ::" -#: ../../tutorial/inputoutput.rst:385 +#: ../../tutorial/inputoutput.rst:382 +msgid "" +">>> f.close()\n" +">>> f.read()\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: I/O operation on closed file." +msgstr "" +">>> f.close()\n" +">>> f.read()\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: I/O operation on closed file." + +#: ../../tutorial/inputoutput.rst:392 msgid "Methods of File Objects" msgstr "Métodos de objetos arquivo" -#: ../../tutorial/inputoutput.rst:387 +#: ../../tutorial/inputoutput.rst:394 msgid "" "The rest of the examples in this section will assume that a file object " "called ``f`` has already been created." @@ -507,7 +814,7 @@ msgstr "" "Para simplificar, o resto dos exemplos nesta seção presumem que um objeto " "arquivo chamado ``f`` já foi criado." -#: ../../tutorial/inputoutput.rst:390 +#: ../../tutorial/inputoutput.rst:397 msgid "" "To read a file's contents, call ``f.read(size)``, which reads some quantity " "of data and returns it as a string (in text mode) or bytes object (in binary " @@ -527,7 +834,19 @@ msgstr "" "(em modo binário) são lidos e devolvidos. Se o fim do arquivo for atingido, " "``f.read()`` devolve uma string vazia (``''``). ::" -#: ../../tutorial/inputoutput.rst:404 +#: ../../tutorial/inputoutput.rst:406 +msgid "" +">>> f.read()\n" +"'This is the entire file.\\n'\n" +">>> f.read()\n" +"''" +msgstr "" +">>> f.read()\n" +"'Este é o arquivo inteiro.\\n'\n" +">>> f.read()\n" +"''" + +#: ../../tutorial/inputoutput.rst:411 msgid "" "``f.readline()`` reads a single line from the file; a newline character " "(``\\n``) is left at the end of the string, and is only omitted on the last " @@ -546,13 +865,43 @@ msgstr "" #: ../../tutorial/inputoutput.rst:418 msgid "" +">>> f.readline()\n" +"'This is the first line of the file.\\n'\n" +">>> f.readline()\n" +"'Second line of the file\\n'\n" +">>> f.readline()\n" +"''" +msgstr "" +">>> f.readline()\n" +"'Está é a primeira linha do arquivo.\\n'\n" +">>> f.readline()\n" +"'Segunda linha do arquivo\\n'\n" +">>> f.readline()\n" +"''" + +#: ../../tutorial/inputoutput.rst:425 +msgid "" "For reading lines from a file, you can loop over the file object. This is " "memory efficient, fast, and leads to simple code::" msgstr "" "Uma maneira alternativa de ler linhas do arquivo é iterar diretamente pelo " "objeto arquivo. É eficiente, rápido e resulta em código mais simples::" -#: ../../tutorial/inputoutput.rst:427 +#: ../../tutorial/inputoutput.rst:428 +msgid "" +">>> for line in f:\n" +"... print(line, end='')\n" +"...\n" +"This is the first line of the file.\n" +"Second line of the file" +msgstr "" +">>> for line in f:\n" +"... print(line, end='')\n" +"...\n" +"Esta é a primeira linha do arquivo.\n" +"Segunda linha do arquivo" + +#: ../../tutorial/inputoutput.rst:434 msgid "" "If you want to read all the lines of a file in a list you can also use " "``list(f)`` or ``f.readlines()``." @@ -560,7 +909,7 @@ msgstr "" "Se desejar ler todas as linhas de um arquivo em uma lista, pode-se usar " "``list(f)`` ou ``f.readlines()``." -#: ../../tutorial/inputoutput.rst:430 +#: ../../tutorial/inputoutput.rst:437 msgid "" "``f.write(string)`` writes the contents of *string* to the file, returning " "the number of characters written. ::" @@ -568,7 +917,15 @@ msgstr "" "``f.write(string)`` escreve o conteúdo de *string* para o arquivo, " "retornando o número de caracteres escritos. ::" -#: ../../tutorial/inputoutput.rst:436 +#: ../../tutorial/inputoutput.rst:440 +msgid "" +">>> f.write('This is a test\\n')\n" +"15" +msgstr "" +">>> f.write('Este é um teste\\n')\n" +"15" + +#: ../../tutorial/inputoutput.rst:443 msgid "" "Other types of objects need to be converted -- either to a string (in text " "mode) or a bytes object (in binary mode) -- before writing them::" @@ -576,7 +933,19 @@ msgstr "" "Outros tipos de objetos precisam ser convertidos -- seja para uma string (em " "modo texto) ou para bytes (em modo binário) -- antes de escrevê-los::" -#: ../../tutorial/inputoutput.rst:444 +#: ../../tutorial/inputoutput.rst:446 +msgid "" +">>> value = ('the answer', 42)\n" +">>> s = str(value) # convert the tuple to string\n" +">>> f.write(s)\n" +"18" +msgstr "" +">>> value = ('a resposta', 42)\n" +">>> s = str(value) # converte a tupla para string\n" +">>> f.write(s)\n" +"18" + +#: ../../tutorial/inputoutput.rst:451 msgid "" "``f.tell()`` returns an integer giving the file object's current position in " "the file represented as number of bytes from the beginning of the file when " @@ -586,7 +955,7 @@ msgstr "" "arquivo representado, como número de bytes desde o início do arquivo, no " "modo binário, e um número ininteligível, quando no modo de texto." -#: ../../tutorial/inputoutput.rst:448 +#: ../../tutorial/inputoutput.rst:455 msgid "" "To change the file object's position, use ``f.seek(offset, whence)``. The " "position is computed from adding *offset* to a reference point; the " @@ -603,7 +972,33 @@ msgstr "" "ao fim do arquivo. Este argumento pode ser omitido e o valor padrão é 0, " "usando o início do arquivo como referência. ::" -#: ../../tutorial/inputoutput.rst:467 +#: ../../tutorial/inputoutput.rst:462 +msgid "" +">>> f = open('workfile', 'rb+')\n" +">>> f.write(b'0123456789abcdef')\n" +"16\n" +">>> f.seek(5) # Go to the 6th byte in the file\n" +"5\n" +">>> f.read(1)\n" +"b'5'\n" +">>> f.seek(-3, 2) # Go to the 3rd byte before the end\n" +"13\n" +">>> f.read(1)\n" +"b'd'" +msgstr "" +">>> f = open('arquivo_de_trabalho', 'rb+')\n" +">>> f.write(b'0123456789abcdef')\n" +"16\n" +">>> f.seek(5) # Vai até o 6º byte no arquivo\n" +"5\n" +">>> f.read(1)\n" +"b'5'\n" +">>> f.seek(-3, 2) # Vai até o 3º byte antes do fim\n" +"13\n" +">>> f.read(1)\n" +"b'd'" + +#: ../../tutorial/inputoutput.rst:474 msgid "" "In text files (those opened without a ``b`` in the mode string), only seeks " "relative to the beginning of the file are allowed (the exception being " @@ -617,7 +1012,7 @@ msgstr "" "são aqueles retornados por chamada à ``f.tell()``, ou zero. Qualquer outro " "valor para *offset* produz um comportamento indefinido." -#: ../../tutorial/inputoutput.rst:473 +#: ../../tutorial/inputoutput.rst:480 msgid "" "File objects have some additional methods, such as :meth:`~io.IOBase.isatty` " "and :meth:`~io.IOBase.truncate` which are less frequently used; consult the " @@ -627,11 +1022,11 @@ msgstr "" "isatty` e :meth:`~io.IOBase.truncate` que não são usados com frequência; " "consulte a Biblioteca de Referência para um guia completo de objetos arquivo." -#: ../../tutorial/inputoutput.rst:481 +#: ../../tutorial/inputoutput.rst:488 msgid "Saving structured data with :mod:`json`" msgstr "Gravando dados estruturados com :mod:`json`" -#: ../../tutorial/inputoutput.rst:485 +#: ../../tutorial/inputoutput.rst:492 msgid "" "Strings can easily be written to and read from a file. Numbers take a bit " "more effort, since the :meth:`~io.TextIOBase.read` method only returns " @@ -647,7 +1042,7 @@ msgstr "" "Quando você deseja salvar tipos de dados mais complexos, como listas e " "dicionários aninhados, a análise e serialização manual tornam-se complicadas." -#: ../../tutorial/inputoutput.rst:492 +#: ../../tutorial/inputoutput.rst:499 msgid "" "Rather than having users constantly writing and debugging code to save " "complicated data types to files, Python allows you to use the popular data " @@ -670,7 +1065,7 @@ msgstr "" "armazenada em um arquivo, ou estrutura de dados, ou enviada por uma conexão " "de rede para alguma outra máquina." -#: ../../tutorial/inputoutput.rst:503 +#: ../../tutorial/inputoutput.rst:510 msgid "" "The JSON format is commonly used by modern applications to allow for data " "exchange. Many programmers are already familiar with it, which makes it a " @@ -680,7 +1075,7 @@ msgstr "" "troca de dados. Pessoas que programam já estão familiarizadas com esse " "formato, o que o torna uma boa opção para interoperabilidade." -#: ../../tutorial/inputoutput.rst:507 +#: ../../tutorial/inputoutput.rst:514 msgid "" "If you have an object ``x``, you can view its JSON string representation " "with a simple line of code::" @@ -688,7 +1083,19 @@ msgstr "" "Um objeto ``x``, pode ser visualizado na sua representação JSON com uma " "simples linha de código::" -#: ../../tutorial/inputoutput.rst:515 +#: ../../tutorial/inputoutput.rst:517 +msgid "" +">>> import json\n" +">>> x = [1, 'simple', 'list']\n" +">>> json.dumps(x)\n" +"'[1, \"simple\", \"list\"]'" +msgstr "" +">>> import json\n" +">>> x = [1, 'lista', 'simples']\n" +">>> json.dumps(x)\n" +"'[1, \"lista\", \"simples\"]'" + +#: ../../tutorial/inputoutput.rst:522 msgid "" "Another variant of the :func:`~json.dumps` function, called :func:`~json." "dump`, simply serializes the object to a :term:`text file`. So if ``f`` is " @@ -698,7 +1105,11 @@ msgstr "" "serializa o objeto para um :term:`arquivo texto`. Se ``f`` é um :term:" "`arquivo texto` aberto para escrita, podemos fazer isto::" -#: ../../tutorial/inputoutput.rst:521 +#: ../../tutorial/inputoutput.rst:526 +msgid "json.dump(x, f)" +msgstr "json.dump(x, f)" + +#: ../../tutorial/inputoutput.rst:528 msgid "" "To decode the object again, if ``f`` is a :term:`binary file` or :term:`text " "file` object which has been opened for reading::" @@ -706,7 +1117,11 @@ msgstr "" "Para decodificar o objeto novamente, se ``f`` é um objeto :term:`arquivo " "binário` ou :term:`arquivo texto` que foi aberto para leitura::" -#: ../../tutorial/inputoutput.rst:527 +#: ../../tutorial/inputoutput.rst:531 +msgid "x = json.load(f)" +msgstr "x = json.load(f)" + +#: ../../tutorial/inputoutput.rst:534 msgid "" "JSON files must be encoded in UTF-8. Use ``encoding=\"utf-8\"`` when opening " "JSON file as a :term:`text file` for both of reading and writing." @@ -715,7 +1130,7 @@ msgstr "" "quando abrir um arquivo JSON como um :term:`arquivo texto` tanto para " "leitura quanto para escrita." -#: ../../tutorial/inputoutput.rst:530 +#: ../../tutorial/inputoutput.rst:537 msgid "" "This simple serialization technique can handle lists and dictionaries, but " "serializing arbitrary class instances in JSON requires a bit of extra " @@ -727,11 +1142,11 @@ msgstr "" "pouco mais de esforço. A referência para o módulo :mod:`json` contém uma " "explicação disso." -#: ../../tutorial/inputoutput.rst:536 +#: ../../tutorial/inputoutput.rst:543 msgid ":mod:`pickle` - the pickle module" msgstr "O módulo :mod:`pickle`" -#: ../../tutorial/inputoutput.rst:538 +#: ../../tutorial/inputoutput.rst:545 msgid "" "Contrary to :ref:`JSON `, *pickle* is a protocol which allows the " "serialization of arbitrarily complex Python objects. As such, it is " @@ -747,26 +1162,54 @@ msgstr "" "dados de pickle, provenientes de uma fonte não confiável, pode executar " "código arbitrário, se os dados foram criados por um invasor habilidoso." -#: ../../tutorial/inputoutput.rst:301 +#: ../../tutorial/inputoutput.rst:103 +msgid "formatted string literal" +msgstr "literal de string formatado" + +#: ../../tutorial/inputoutput.rst:103 +msgid "interpolated string literal" +msgstr "literal de string interpolada" + +#: ../../tutorial/inputoutput.rst:103 +msgid "string" +msgstr "string" + +#: ../../tutorial/inputoutput.rst:103 +msgid "formatted literal" +msgstr "literal formatado" + +#: ../../tutorial/inputoutput.rst:103 +msgid "interpolated literal" +msgstr "literal interpolado" + +#: ../../tutorial/inputoutput.rst:103 +msgid "f-string" +msgstr "f-string" + +#: ../../tutorial/inputoutput.rst:103 +msgid "fstring" +msgstr "fstring" + +#: ../../tutorial/inputoutput.rst:308 msgid "built-in function" msgstr "função embutida" -#: ../../tutorial/inputoutput.rst:301 +#: ../../tutorial/inputoutput.rst:308 msgid "open" msgstr "open" -#: ../../tutorial/inputoutput.rst:301 +#: ../../tutorial/inputoutput.rst:308 msgid "object" msgstr "objeto" -#: ../../tutorial/inputoutput.rst:301 +#: ../../tutorial/inputoutput.rst:308 msgid "file" msgstr "arquivo" -#: ../../tutorial/inputoutput.rst:483 +#: ../../tutorial/inputoutput.rst:490 msgid "module" msgstr "módulo" -#: ../../tutorial/inputoutput.rst:483 +#: ../../tutorial/inputoutput.rst:490 msgid "json" msgstr "json" diff --git a/tutorial/interactive.po b/tutorial/interactive.po index 769d51b71..7ae8349ad 100644 --- a/tutorial/interactive.po +++ b/tutorial/interactive.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Welington Carlos , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2023 -# Adorilson Bezerra , 2023 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-17 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:50+0000\n" -"Last-Translator: Adorilson Bezerra , 2023\n" +"POT-Creation-Date: 2025-03-21 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -84,16 +81,17 @@ msgid "" "This facility is an enormous step forward compared to earlier versions of " "the interpreter; however, some wishes are left: It would be nice if the " "proper indentation were suggested on continuation lines (the parser knows if " -"an indent token is required next). The completion mechanism might use the " -"interpreter's symbol table. A command to check (or even suggest) matching " -"parentheses, quotes, etc., would also be useful." +"an :data:`~token.INDENT` token is required next). The completion mechanism " +"might use the interpreter's symbol table. A command to check (or even " +"suggest) matching parentheses, quotes, etc., would also be useful." msgstr "" "Esta facilidade é um enorme passo em frente em comparação com as versões " "anteriores do interpretador; No entanto, alguns desejos são deixados: seria " -"bom se a indentação adequada fosse sugerida nas linhas de continuação (o " -"analisador sabe se é necessário um token de recuo). O mecanismo de conclusão " -"pode usar a tabela de símbolos do interpretador. Um comando para verificar " -"(ou mesmo sugerir) parênteses, aspas, etc., também seria útil." +"bom se um :data:`~token.INDENT` adequado fosse sugerido nas linhas de " +"continuação (o analisador sabe se é necessário um token de recuo). O " +"mecanismo de conclusão pode usar a tabela de símbolos do interpretador. Um " +"comando para verificar (ou mesmo sugerir) parênteses, aspas, etc., também " +"seria útil." #: ../../tutorial/interactive.rst:45 msgid "" diff --git a/tutorial/interpreter.po b/tutorial/interpreter.po index 40f446bb6..bea137140 100644 --- a/tutorial/interpreter.po +++ b/tutorial/interpreter.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Adorilson Bezerra , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 01:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -46,6 +43,10 @@ msgstr "" "adicionando :file:`/usr/local/bin` ao caminho de busca da shell de seu Unix " "torna-se possível iniciá-lo digitando o comando:" +#: ../../tutorial/interpreter.rst:17 +msgid "python3.13" +msgstr "python3.13" + #: ../../tutorial/interpreter.rst:21 msgid "" "to the shell. [#]_ Since the choice of the directory where the interpreter " @@ -79,7 +80,7 @@ msgid "" "exit status. If that doesn't work, you can exit the interpreter by typing " "the following command: ``quit()``." msgstr "" -"Digitando um caractere de fim-de-arquivo (:kbd:`Control-D` no Unix, :kbd:" +"Digitar um caractere de fim de arquivo (:kbd:`Control-D` no Unix, :kbd:" "`Control-Z` no Windows) diretamente no prompt força o interpretador a sair " "com status de saída zero. Se isso não funcionar, você pode sair do " "interpretador digitando o seguinte comando: ``quit()``." @@ -214,6 +215,22 @@ msgstr "" "boas vindas, informando seu número de versão e um aviso de copyright antes " "de exibir o primeiro prompt::" +#: ../../tutorial/interpreter.rst:98 +msgid "" +"$ python3.13\n" +"Python 3.13 (default, April 4 2023, 09:25:04)\n" +"[GCC 10.2.0] on linux\n" +"Type \"help\", \"copyright\", \"credits\" or \"license\" for more " +"information.\n" +">>>" +msgstr "" +"$ python3.13\n" +"Python 3.13 (default, April 4 2023, 09:25:04)\n" +"[GCC 10.2.0] on linux\n" +"Type \"help\", \"copyright\", \"credits\" or \"license\" for more " +"information.\n" +">>>" + #: ../../tutorial/interpreter.rst:108 msgid "" "Continuation lines are needed when entering a multi-line construct. As an " @@ -222,6 +239,20 @@ msgstr "" "Linhas de continuação são necessárias em construções multi-linha. Como " "exemplo, dê uma olhada nesse comando :keyword:`if`::" +#: ../../tutorial/interpreter.rst:111 +msgid "" +">>> the_world_is_flat = True\n" +">>> if the_world_is_flat:\n" +"... print(\"Be careful not to fall off!\")\n" +"...\n" +"Be careful not to fall off!" +msgstr "" +">>> o_mundo_é_plano = True\n" +">>> if o_mundo_é_plano:\n" +"... print(\"Cuidado para não cair da borda!\")\n" +"...\n" +"Cuidado para não cair da borda!" + #: ../../tutorial/interpreter.rst:118 msgid "For more on interactive mode, see :ref:`tut-interac`." msgstr "" @@ -262,6 +293,10 @@ msgstr "" "especial deve ser adicionada como *primeira* linha do arquivo. A sintaxe é " "essa::" +#: ../../tutorial/interpreter.rst:143 +msgid "# -*- coding: encoding -*-" +msgstr "# -*- coding: encoding -*-" + #: ../../tutorial/interpreter.rst:145 msgid "where *encoding* is one of the valid :mod:`codecs` supported by Python." msgstr "onde *encoding* é uma das :mod:`codecs` válidas com suporte do Python." @@ -274,6 +309,10 @@ msgstr "" "Por exemplo, para declarar que a codificação Windows-1252 deve ser usada, a " "primeira linha do seu arquivo fonte deve ser::" +#: ../../tutorial/interpreter.rst:150 +msgid "# -*- coding: cp1252 -*-" +msgstr "# -*- coding: cp1252 -*-" + #: ../../tutorial/interpreter.rst:152 msgid "" "One exception to the *first line* rule is when the source code starts with " @@ -285,6 +324,14 @@ msgstr "" "declaração de codificação deve ser adicionada como a segunda linha do " "arquivo. Por exemplo::" +#: ../../tutorial/interpreter.rst:156 +msgid "" +"#!/usr/bin/env python3\n" +"# -*- coding: cp1252 -*-" +msgstr "" +"#!/usr/bin/env python3\n" +"# -*- coding: cp1252 -*-" + #: ../../tutorial/interpreter.rst:160 msgid "Footnotes" msgstr "Notas de rodapé" diff --git a/tutorial/introduction.po b/tutorial/introduction.po index dfd81d916..604310e64 100644 --- a/tutorial/introduction.po +++ b/tutorial/introduction.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Leticia Portella , 2021 -# Adson Rodrigues , 2021 -# David Macedo, 2022 -# Adorilson Bezerra , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-20 00:52+0000\n" -"PO-Revision-Date: 2021-06-28 01:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-09 14:59+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -73,9 +68,9 @@ msgid "" msgstr "" "Muitos exemplos neste manual, mesmo aqueles inscritos na linha de comando " "interativa, incluem comentários. Comentários em Python começam com o " -"caractere cerquilha '#' e estende até o final da linha. Um comentário pode " +"caractere cerquilha ``#`` e estende até o final da linha. Um comentário pode " "aparecer no inicio da linha ou após espaço em branco ou código, mas não " -"dentro de uma string literal. O caracterer cerquilha dentro de uma string " +"dentro de uma string literal. O caractere cerquilha dentro de uma string " "literal é apenas uma cerquilha. Como os comentários são para esclarecer o " "código e não são interpretados pelo Python, eles podem ser omitidos ao " "digitar exemplos." @@ -84,6 +79,18 @@ msgstr "" msgid "Some examples::" msgstr "Alguns exemplos:" +#: ../../tutorial/introduction.rst:33 +msgid "" +"# this is the first comment\n" +"spam = 1 # and this is the second comment\n" +" # ... and now a third!\n" +"text = \"# This is not a comment because it's inside quotes.\"" +msgstr "" +"# este é o primeiro comentário\n" +"spam = 1 # e este é o segundo comentário\n" +" # ... e agora um terceiro!\n" +"texto = \"# Este não é um comentário por estar entre aspas.\"" + #: ../../tutorial/introduction.rst:42 msgid "Using Python as a Calculator" msgstr "Usando Python como uma calculadora" @@ -113,6 +120,26 @@ msgstr "" "operações aritméticas; parênteses (``()``) podem ser usados para agrupar " "expressões. Por exemplo::" +#: ../../tutorial/introduction.rst:59 +msgid "" +">>> 2 + 2\n" +"4\n" +">>> 50 - 5*6\n" +"20\n" +">>> (50 - 5*6) / 4\n" +"5.0\n" +">>> 8 / 5 # division always returns a floating-point number\n" +"1.6" +msgstr "" +">>> 2 + 2\n" +"4\n" +">>> 50 - 5*6\n" +"20\n" +">>> (50 - 5*6) / 4\n" +"5.0\n" +">>> 8 / 5 # divisão sempre retorna um número de ponto flutuante\n" +"1.6" + #: ../../tutorial/introduction.rst:68 msgid "" "The integer numbers (e.g. ``2``, ``4``, ``20``) have type :class:`int`, the " @@ -133,6 +160,28 @@ msgstr "" "`divisão pelo piso` e receber um inteiro como resultado você pode usar o " "operador ``//``; para calcular o resto você pode usar o ``%``::" +#: ../../tutorial/introduction.rst:76 +msgid "" +">>> 17 / 3 # classic division returns a float\n" +"5.666666666666667\n" +">>>\n" +">>> 17 // 3 # floor division discards the fractional part\n" +"5\n" +">>> 17 % 3 # the % operator returns the remainder of the division\n" +"2\n" +">>> 5 * 3 + 2 # floored quotient * divisor + remainder\n" +"17" +msgstr "" +">>> 17 / 3 # divisão clássica retorna um ponto flutuante\n" +"5.666666666666667\n" +">>>\n" +">>> 17 // 3 # divisão pelo piso descarta a parte fracionária\n" +"5\n" +">>> 17 % 3 # o operador % retorna o resto da divisão\n" +"2\n" +">>> 5 * 3 + 2 # quociente do piso * divisor + restante\n" +"17" + #: ../../tutorial/introduction.rst:86 msgid "" "With Python, it is possible to use the ``**`` operator to calculate powers " @@ -140,6 +189,18 @@ msgid "" msgstr "" "Com Python, é possível usar o operador ``**`` para calcular potências [#]_::" +#: ../../tutorial/introduction.rst:88 +msgid "" +">>> 5 ** 2 # 5 squared\n" +"25\n" +">>> 2 ** 7 # 2 to the power of 7\n" +"128" +msgstr "" +">>> 5 ** 2 # 5 ao quadrado\n" +"25\n" +">>> 2 ** 7 # 2 à potência de 7\n" +"128" + #: ../../tutorial/introduction.rst:93 msgid "" "The equal sign (``=``) is used to assign a value to a variable. Afterwards, " @@ -149,6 +210,18 @@ msgstr "" "Depois de uma atribuição, nenhum resultado é exibido antes do próximo " "prompt::" +#: ../../tutorial/introduction.rst:96 +msgid "" +">>> width = 20\n" +">>> height = 5 * 9\n" +">>> width * height\n" +"900" +msgstr "" +">>> largura = 20\n" +">>> altura = 5 * 9\n" +">>> largura * altura\n" +"900" + #: ../../tutorial/introduction.rst:101 msgid "" "If a variable is not \"defined\" (assigned a value), trying to use it will " @@ -157,6 +230,18 @@ msgstr "" "Se uma variável não é \"definida\" (não tem um valor atribuído), tentar " "utilizá-la gerará um erro::" +#: ../../tutorial/introduction.rst:104 +msgid "" +">>> n # try to access an undefined variable\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"NameError: name 'n' is not defined" +msgstr "" +">>> n # tenta acessar uma variável não definida\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"NameError: name 'n' is not defined" + #: ../../tutorial/introduction.rst:109 msgid "" "There is full support for floating point; operators with mixed type operands " @@ -165,6 +250,14 @@ msgstr "" "Há suporte completo para ponto flutuante (*float*); operadores com operandos " "de diferentes tipos convertem o inteiro para ponto flutuante::" +#: ../../tutorial/introduction.rst:112 +msgid "" +">>> 4 * 3.75 - 1\n" +"14.0" +msgstr "" +">>> 4 * 3.75 - 1\n" +"14.0" + #: ../../tutorial/introduction.rst:115 msgid "" "In interactive mode, the last printed expression is assigned to the variable " @@ -175,6 +268,26 @@ msgstr "" "variável ``_``. Assim, ao utilizar Python como uma calculadora, fica mais " "fácil prosseguir com os cálculos, por exemplo::" +#: ../../tutorial/introduction.rst:119 +msgid "" +">>> tax = 12.5 / 100\n" +">>> price = 100.50\n" +">>> price * tax\n" +"12.5625\n" +">>> price + _\n" +"113.0625\n" +">>> round(_, 2)\n" +"113.06" +msgstr "" +">>> taxa = 12.5 / 100\n" +">>> preço = 100.50\n" +">>> preço * taxa\n" +"12.5625\n" +">>> preço + _\n" +"113.0625\n" +">>> round(_, 2)\n" +"113.06" + #: ../../tutorial/introduction.rst:128 msgid "" "This variable should be treated as read-only by the user. Don't explicitly " @@ -218,7 +331,23 @@ msgstr "" "etc. \"``Oba! :)``\". Eles podem ser colocados entre aspas simples " "(``'...'``) ou aspas duplas (``\"...\"``) com o mesmo resultado [#]_." -#: ../../tutorial/introduction.rst:157 +#: ../../tutorial/introduction.rst:150 +msgid "" +">>> 'spam eggs' # single quotes\n" +"'spam eggs'\n" +">>> \"Paris rabbit got your back :)! Yay!\" # double quotes\n" +"'Paris rabbit got your back :)! Yay!'\n" +">>> '1975' # digits and numerals enclosed in quotes are also strings\n" +"'1975'" +msgstr "" +">>> 'spam eggs' # aspas simples\n" +"'spam eggs'\n" +">>> \"Coelho de Paris, eu te projeto :)! Viva!\" # aspas duplas\n" +"'Coelho de Paris, eu te projeto :)! Viva!'\n" +">>> '1975' # dígitos e numerais envoltos em aspas também são strings\n" +"'1975'" + +#: ../../tutorial/introduction.rst:159 msgid "" "To quote a quote, we need to \"escape\" it, by preceding it with ``\\``. " "Alternatively, we can use the other type of quotation marks::" @@ -226,7 +355,31 @@ msgstr "" "Para colocar aspas entre aspas, precisamos \"escapá-la\", precedendo-as com " "``\\``. Alternativamente, podemos usar o outro tipo de aspas::" -#: ../../tutorial/introduction.rst:171 +#: ../../tutorial/introduction.rst:162 +msgid "" +">>> 'doesn\\'t' # use \\' to escape the single quote...\n" +"\"doesn't\"\n" +">>> \"doesn't\" # ...or use double quotes instead\n" +"\"doesn't\"\n" +">>> '\"Yes,\" they said.'\n" +"'\"Yes,\" they said.'\n" +">>> \"\\\"Yes,\\\" they said.\"\n" +"'\"Yes,\" they said.'\n" +">>> '\"Isn\\'t,\" they said.'\n" +"'\"Isn\\'t,\" they said.'" +msgstr "" +">>> 'd\\'água' # use \\' para escapar a aspa simples...\n" +"\"d'água\"\n" +">>> \"d'água\" # ...ou use aspas duplas\n" +"\"d'água\"\n" +">>> '\"Sim\", eles disseram.'\n" +"'\"Sim\", eles disseram.'\n" +">>> \"\\\"Sim\\\", eles disseram.\"\n" +"'\"Sim\", eles disseram.'\n" +">>> '\"Copo d\\'água\", eles pediram.'\n" +"'\"Copo d'água\", eles pediram.'" + +#: ../../tutorial/introduction.rst:173 msgid "" "In the Python shell, the string definition and output string can look " "different. The :func:`print` function produces a more readable output, by " @@ -237,7 +390,25 @@ msgstr "" "diferentes. A função :func:`print` produz uma saída mais legível, omitindo " "as aspas delimitadoras e imprimindo caracteres de escape e especiais::" -#: ../../tutorial/introduction.rst:182 +#: ../../tutorial/introduction.rst:177 +msgid "" +">>> s = 'First line.\\nSecond line.' # \\n means newline\n" +">>> s # without print(), special characters are included in the string\n" +"'First line.\\nSecond line.'\n" +">>> print(s) # with print(), special characters are interpreted, so \\n " +"produces new line\n" +"First line.\n" +"Second line." +msgstr "" +">>> s = 'Primeira linha.\\nSegunda linha.' # \\n significa nova linha\n" +">>> s # sem print(), caracteres especiais são incluídos na string\n" +"'Primeira linha.\\nSegunda linha.'\n" +">>> print(s) # com print(), caracteres especiais são interpretados, então " +"\\n produz nova linha\n" +"Primeira linha.\n" +"Segunda linha." + +#: ../../tutorial/introduction.rst:184 msgid "" "If you don't want characters prefaced by ``\\`` to be interpreted as special " "characters, you can use *raw strings* by adding an ``r`` before the first " @@ -245,38 +416,71 @@ msgid "" msgstr "" "Se não quiseres que os caracteres sejam precedidos por ``\\`` para serem " "interpretados como caracteres especiais, poderás usar *strings raw* (N.d.T: " -"“crua” ou sem processamento de caracteres de escape) adicionando um ``r`` " +"“bruta” ou sem processamento de caracteres de escape) adicionando um ``r`` " "antes da primeira aspa::" -#: ../../tutorial/introduction.rst:192 +#: ../../tutorial/introduction.rst:188 +msgid "" +">>> print('C:\\some\\name') # here \\n means newline!\n" +"C:\\some\n" +"ame\n" +">>> print(r'C:\\some\\name') # note the r before the quote\n" +"C:\\some\\name" +msgstr "" +">>> print('C:\\algum\\nome') # aqui \\n significa nova linha!\n" +"C:\\algum\n" +"ome\n" +">>> print(r'C:\\algum\\nome') # observe o r antes das aspas\n" +"C:\\algum\\nome" + +#: ../../tutorial/introduction.rst:194 msgid "" "There is one subtle aspect to raw strings: a raw string may not end in an " "odd number of ``\\`` characters; see :ref:`the FAQ entry ` for more information and workarounds." msgstr "" -"Há um aspecto sutil nas strings raw: uma string raw não pode terminar em um " -"número ímpar de caracteres ``\\``; consulte :ref:`a entrada do FAQ ` para mais informações e soluções " +"Há um aspecto sutil nas strings brutas: uma string bruta não pode terminar " +"em um número ímpar de caracteres ``\\``; consulte :ref:`o FAQ relacionado " +"` para mais informações e soluções " "alternativas." -#: ../../tutorial/introduction.rst:197 +#: ../../tutorial/introduction.rst:199 msgid "" "String literals can span multiple lines. One way is using triple-quotes: " -"``\"\"\"...\"\"\"`` or ``'''...'''``. End of lines are automatically " -"included in the string, but it's possible to prevent this by adding a ``\\`` " -"at the end of the line. The following example::" +"``\"\"\"...\"\"\"`` or ``'''...'''``. End-of-line characters are " +"automatically included in the string, but it's possible to prevent this by " +"adding a ``\\`` at the end of the line. In the following example, the " +"initial newline is not included::" msgstr "" "As strings literais podem abranger várias linhas. Uma maneira é usar as " -"aspas triplas: ``\"\"\"...\"\"\"`` ou ``'''...'''``. O fim das linhas é " -"incluído automaticamente na string, mas é possível evitar isso adicionando " -"uma ``\\`` no final. O seguinte exemplo::" +"aspas triplas: ``\"\"\"...\"\"\"`` ou ``'''...'''``. Caracteres de fim de " +"linha são incluídos automaticamente na string, mas é possível evitar isso " +"adicionando uma ``\\`` no final. No exemplo a seguir, a nova linha no início " +"não é incluída::" -#: ../../tutorial/introduction.rst:208 +#: ../../tutorial/introduction.rst:205 msgid "" -"produces the following output (note that the initial newline is not " -"included):" +">>> print(\"\"\"\\\n" +"... Usage: thingy [OPTIONS]\n" +"... -h Display this usage message\n" +"... -H hostname Hostname to connect to\n" +"... \"\"\")\n" +"Usage: thingy [OPTIONS]\n" +" -h Display this usage message\n" +" -H hostname Hostname to connect to\n" +"\n" +">>>" msgstr "" -"produz a seguinte saída (observe que a linha inicial não está incluída):" +">>> print(\"\"\"\\\n" +"... Uso: coisinha [OPÇÕES]\n" +"... -h Exibe esta mensagem de uso\n" +"... -H hostname Hostname para se conectar\n" +"... \"\"\")\n" +"Usage: coisinha [OPÇÕES]\n" +" -h Exibe esta mensagem de ajuda\n" +" -H hostname Hostname para se conectar\n" +"\n" +">>>" #: ../../tutorial/introduction.rst:216 msgid "" @@ -286,6 +490,16 @@ msgstr "" "Strings podem ser concatenadas (coladas) com o operador ``+``, e repetidas " "com ``*``::" +#: ../../tutorial/introduction.rst:219 +msgid "" +">>> # 3 times 'un', followed by 'ium'\n" +">>> 3 * 'un' + 'ium'\n" +"'unununium'" +msgstr "" +">>> # 3 vezes 'un', seguido por 'ium'\n" +">>> 3 * 'un' + 'ium'\n" +"'unununium'" + #: ../../tutorial/introduction.rst:223 msgid "" "Two or more *string literals* (i.e. the ones enclosed between quotes) next " @@ -294,18 +508,66 @@ msgstr "" "Duas ou mais *strings literais* (ou seja, entre aspas) ao lado da outra são " "automaticamente concatenados. ::" +#: ../../tutorial/introduction.rst:226 +msgid "" +">>> 'Py' 'thon'\n" +"'Python'" +msgstr "" +">>> 'Py' 'thon'\n" +"'Python'" + #: ../../tutorial/introduction.rst:229 msgid "" "This feature is particularly useful when you want to break long strings::" msgstr "" "Esse recurso é particularmente útil quando você quer quebrar strings longas::" +#: ../../tutorial/introduction.rst:231 +msgid "" +">>> text = ('Put several strings within parentheses '\n" +"... 'to have them joined together.')\n" +">>> text\n" +"'Put several strings within parentheses to have them joined together.'" +msgstr "" +">>> texto = ('Coloque várias strings dentro de parênteses '\n" +"... 'para fazer com que elas sejam concatenadas.')\n" +">>> texto\n" +"'Coloque várias strings dentro de parênteses para fazer com que elas sejam " +"concatenadas.'" + #: ../../tutorial/introduction.rst:236 msgid "" "This only works with two literals though, not with variables or expressions::" msgstr "" "Isso só funciona com duas strings literais, não com variáveis ou expressões::" +#: ../../tutorial/introduction.rst:238 +msgid "" +">>> prefix = 'Py'\n" +">>> prefix 'thon' # can't concatenate a variable and a string literal\n" +" File \"\", line 1\n" +" prefix 'thon'\n" +" ^^^^^^\n" +"SyntaxError: invalid syntax\n" +">>> ('un' * 3) 'ium'\n" +" File \"\", line 1\n" +" ('un' * 3) 'ium'\n" +" ^^^^^\n" +"SyntaxError: invalid syntax" +msgstr "" +">>> prefixo = 'Py'\n" +">>> prefixo 'thon' # não é possível concatenar uma variável e um literal de " +"string\n" +" File \"\", line 1\n" +" prefixi 'thon'\n" +" ^^^^^^\n" +"SyntaxError: invalid syntax\n" +">>> ('un' * 3) 'ium'\n" +" File \"\", line 1\n" +" ('un' * 3) 'ium'\n" +" ^^^^^\n" +"SyntaxError: invalid syntax" + #: ../../tutorial/introduction.rst:250 msgid "" "If you want to concatenate variables or a variable and a literal, use ``+``::" @@ -313,6 +575,14 @@ msgstr "" "Se você quiser concatenar variáveis ou uma variável e uma literal, use " "``+``::" +#: ../../tutorial/introduction.rst:252 +msgid "" +">>> prefix + 'thon'\n" +"'Python'" +msgstr "" +">>> prefixo + 'thon'\n" +"'Python'" + #: ../../tutorial/introduction.rst:255 msgid "" "Strings can be *indexed* (subscripted), with the first character having " @@ -323,6 +593,20 @@ msgstr "" "índice 0. Não existe um tipo específico para caracteres; um caractere é " "simplesmente uma string cujo tamanho é 1::" +#: ../../tutorial/introduction.rst:259 +msgid "" +">>> word = 'Python'\n" +">>> word[0] # character in position 0\n" +"'P'\n" +">>> word[5] # character in position 5\n" +"'n'" +msgstr "" +">>> palavra = 'Python'\n" +">>> palavra[0] # caractere na posição 0\n" +"'P'\n" +">>> palavra[5] # caractere na posição 5\n" +"'n'" + #: ../../tutorial/introduction.rst:265 msgid "" "Indices may also be negative numbers, to start counting from the right::" @@ -330,6 +614,22 @@ msgstr "" "Índices também podem ser números negativos para iniciar a contagem pela " "direita::" +#: ../../tutorial/introduction.rst:267 +msgid "" +">>> word[-1] # last character\n" +"'n'\n" +">>> word[-2] # second-last character\n" +"'o'\n" +">>> word[-6]\n" +"'P'" +msgstr "" +">>> palavra[-1] # último caractere\n" +"'n'\n" +">>> palavra[-2] # penúltimo caractere\n" +"'o'\n" +">>> palavra[-6]\n" +"'P'" + #: ../../tutorial/introduction.rst:274 msgid "Note that since -0 is the same as 0, negative indices start from -1." msgstr "Note que dado que -0 é o mesmo que 0, índices negativos começam em -1." @@ -344,6 +644,18 @@ msgstr "" "seja usada para obter caracteres individuais, *fatiar* permite que você " "obtenha uma substring::" +#: ../../tutorial/introduction.rst:279 +msgid "" +">>> word[0:2] # characters from position 0 (included) to 2 (excluded)\n" +"'Py'\n" +">>> word[2:5] # characters from position 2 (included) to 5 (excluded)\n" +"'tho'" +msgstr "" +">>> palavra[0:2] # caracteres da posição 0 (incluída) até 2 (excluída)\n" +"'Py'\n" +">>> palavra[2:5] # caracteres da posição 2 (incluída) até 5 (excluída)\n" +"'tho'" + #: ../../tutorial/introduction.rst:284 msgid "" "Slice indices have useful defaults; an omitted first index defaults to zero, " @@ -353,6 +665,22 @@ msgstr "" "padrão é zero, um segundo índice omitido é por padrão o tamanho da string " "sendo fatiada::" +#: ../../tutorial/introduction.rst:287 +msgid "" +">>> word[:2] # character from the beginning to position 2 (excluded)\n" +"'Py'\n" +">>> word[4:] # characters from position 4 (included) to the end\n" +"'on'\n" +">>> word[-2:] # characters from the second-last (included) to the end\n" +"'on'" +msgstr "" +">>> palavra[:2] # caracteres do início até a posição 2 (excluída)\n" +"'Py'\n" +">>> palavra[4:] # caracteres da posição 4 (incluída) até o fim\n" +"'on'\n" +">>> palavra[-2:] # caracteres da penúltima (incluída) até o fim\n" +"'on'" + #: ../../tutorial/introduction.rst:294 msgid "" "Note how the start is always included, and the end always excluded. This " @@ -361,6 +689,18 @@ msgstr "" "Observe como o início sempre está incluído, e o fim sempre é excluído. Isso " "garante que ``s[:i] + s[i:]`` seja sempre igual a ``s``::" +#: ../../tutorial/introduction.rst:297 +msgid "" +">>> word[:2] + word[2:]\n" +"'Python'\n" +">>> word[:4] + word[4:]\n" +"'Python'" +msgstr "" +">>> palavra[:2] + palavra[2:]\n" +"'Python'\n" +">>> palavra[:4] + palavra[4:]\n" +"'Python'" + #: ../../tutorial/introduction.rst:302 msgid "" "One way to remember how slices work is to think of the indices as pointing " @@ -373,6 +713,20 @@ msgstr "" "0. Assim, a borda direita do último caractere de uma string de comprimento " "*n* tem índice *n*, por exemplo::" +#: ../../tutorial/introduction.rst:307 +msgid "" +" +---+---+---+---+---+---+\n" +" | P | y | t | h | o | n |\n" +" +---+---+---+---+---+---+\n" +" 0 1 2 3 4 5 6\n" +"-6 -5 -4 -3 -2 -1" +msgstr "" +" +---+---+---+---+---+---+\n" +" | P | y | t | h | o | n |\n" +" +---+---+---+---+---+---+\n" +" 0 1 2 3 4 5 6\n" +"-6 -5 -4 -3 -2 -1" + #: ../../tutorial/introduction.rst:313 msgid "" "The first row of numbers gives the position of the indices 0...6 in the " @@ -400,6 +754,18 @@ msgid "Attempting to use an index that is too large will result in an error::" msgstr "" "A tentativa de usar um índice que seja muito grande resultará em um erro::" +#: ../../tutorial/introduction.rst:324 +msgid "" +">>> word[42] # the word only has 6 characters\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"IndexError: string index out of range" +msgstr "" +">>> palavra[42] # a palavra só tem 6 caracteres\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"IndexError: string index out of range" + #: ../../tutorial/introduction.rst:329 msgid "" "However, out of range slice indexes are handled gracefully when used for " @@ -411,6 +777,18 @@ msgstr "" "comprimento é trocado pelo comprimento, um limite superior menor que o " "limite inferior produz uma string vazia::" +#: ../../tutorial/introduction.rst:332 +msgid "" +">>> word[4:42]\n" +"'on'\n" +">>> word[42:]\n" +"''" +msgstr "" +">>> palavra[4:42]\n" +"'on'\n" +">>> palavra[42:]\n" +"''" + #: ../../tutorial/introduction.rst:337 msgid "" "Python strings cannot be changed --- they are :term:`immutable`. Therefore, " @@ -420,14 +798,56 @@ msgstr "" "`imutável`. Portanto, atribuir a uma posição indexada na sequência resulta " "em um erro::" +#: ../../tutorial/introduction.rst:340 +msgid "" +">>> word[0] = 'J'\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: 'str' object does not support item assignment\n" +">>> word[2:] = 'py'\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: 'str' object does not support item assignment" +msgstr "" +">>> palavra[0] = 'J'\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: 'str' object does not support item assignment\n" +">>> palavra[2:] = 'py'\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: 'str' object does not support item assignment" + #: ../../tutorial/introduction.rst:349 msgid "If you need a different string, you should create a new one::" msgstr "Se você precisar de uma string diferente, deverá criar uma nova::" +#: ../../tutorial/introduction.rst:351 +msgid "" +">>> 'J' + word[1:]\n" +"'Jython'\n" +">>> word[:2] + 'py'\n" +"'Pypy'" +msgstr "" +">>> 'J' + palavra[1:]\n" +"'Jython'\n" +">>> palavra[:2] + 'py'\n" +"'Pypy'" + #: ../../tutorial/introduction.rst:356 msgid "The built-in function :func:`len` returns the length of a string::" msgstr "A função embutida :func:`len` devolve o comprimento de uma string::" +#: ../../tutorial/introduction.rst:358 +msgid "" +">>> s = 'supercalifragilisticexpialidocious'\n" +">>> len(s)\n" +"34" +msgstr "" +">>> s = 'supercalifragilisticexpialidoce'\n" +">>> len(s)\n" +"31" + #: ../../tutorial/introduction.rst:365 msgid ":ref:`textseq`" msgstr ":ref:`textseq`" @@ -497,6 +917,16 @@ msgstr "" "uma lista de valores (itens) separados por vírgula, entre colchetes. Os " "valores contidos na lista não precisam ser todos do mesmo tipo. ::" +#: ../../tutorial/introduction.rst:394 +msgid "" +">>> squares = [1, 4, 9, 16, 25]\n" +">>> squares\n" +"[1, 4, 9, 16, 25]" +msgstr "" +">>> quadrados = [1, 4, 9, 16, 25]\n" +">>> quadrados\n" +"[1, 4, 9, 16, 25]" + #: ../../tutorial/introduction.rst:398 msgid "" "Like strings (and all other built-in :term:`sequence` types), lists can be " @@ -505,10 +935,34 @@ msgstr "" "Como strings (e todos os tipos embutidos de :term:`sequência`), listas pode " "ser indexados e fatiados::" +#: ../../tutorial/introduction.rst:401 +msgid "" +">>> squares[0] # indexing returns the item\n" +"1\n" +">>> squares[-1]\n" +"25\n" +">>> squares[-3:] # slicing returns a new list\n" +"[9, 16, 25]" +msgstr "" +">>> quadrados[0] # indexação retorna o item\n" +"1\n" +">>> quadrados[-1]\n" +"25\n" +">>> quadrados[-3:] # fatiamento retorna uma nova lista\n" +"[9, 16, 25]" + #: ../../tutorial/introduction.rst:408 msgid "Lists also support operations like concatenation::" msgstr "As listas também suportam operações como concatenação::" +#: ../../tutorial/introduction.rst:410 +msgid "" +">>> squares + [36, 49, 64, 81, 100]\n" +"[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]" +msgstr "" +">>> quadrados + [36, 49, 64, 81, 100]\n" +"[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]" + #: ../../tutorial/introduction.rst:413 msgid "" "Unlike strings, which are :term:`immutable`, lists are a :term:`mutable` " @@ -518,6 +972,22 @@ msgstr "" "term:`mutáveis`, ou seja, é possível alterar elementos individuais " "de uma lista::" +#: ../../tutorial/introduction.rst:416 +msgid "" +">>> cubes = [1, 8, 27, 65, 125] # something's wrong here\n" +">>> 4 ** 3 # the cube of 4 is 64, not 65!\n" +"64\n" +">>> cubes[3] = 64 # replace the wrong value\n" +">>> cubes\n" +"[1, 8, 27, 64, 125]" +msgstr "" +">>> cubos = [1, 8, 27, 65, 125] # algo errado aqui\n" +">>> 4 ** 3 # o cubo de 4 é 64, não 65!\n" +"64\n" +">>> cubos[3] = 64 # substitui o valor errado\n" +">>> cubos\n" +"[1, 8, 27, 64, 125]" + #: ../../tutorial/introduction.rst:423 msgid "" "You can also add new items at the end of the list, by using the :meth:`!list." @@ -527,6 +997,18 @@ msgstr "" "meth:`!list.append` (estudaremos mais a respeito dos métodos " "posteriormente)::" +#: ../../tutorial/introduction.rst:426 +msgid "" +">>> cubes.append(216) # add the cube of 6\n" +">>> cubes.append(7 ** 3) # and the cube of 7\n" +">>> cubes\n" +"[1, 8, 27, 64, 125, 216, 343]" +msgstr "" +">>> cubos.append(216) # adiciona o cubo de 6\n" +">>> cubos.append(7 ** 3) # e o cubo de 7\n" +">>> cubos\n" +"[1, 8, 27, 64, 125, 216, 343]" + #: ../../tutorial/introduction.rst:431 msgid "" "Simple assignment in Python never copies data. When you assign a list to a " @@ -537,7 +1019,25 @@ msgstr "" "A atribuição simples em Python nunca copia dados. Quando você atribui uma " "lista a uma variável, a variável se refere à *lista existente*. Quaisquer " "alterações que você fizer na lista por meio de uma variável serão vistas por " -"todas as outras variáveis que se referem a ela.::" +"todas as outras variáveis que se referem a ela::" + +#: ../../tutorial/introduction.rst:436 +msgid "" +">>> rgb = [\"Red\", \"Green\", \"Blue\"]\n" +">>> rgba = rgb\n" +">>> id(rgb) == id(rgba) # they reference the same object\n" +"True\n" +">>> rgba.append(\"Alph\")\n" +">>> rgb\n" +"[\"Red\", \"Green\", \"Blue\", \"Alph\"]" +msgstr "" +">>> rgb = [\"Vermelho\", \"Verde\", \"Azul\"]\n" +">>> rgba = rgb\n" +">>> id(rgb) == id(rgba) # elas referenciam o mesmo objeto\n" +"True\n" +">>> rgba.append(\"Alf\")\n" +">>> rgb\n" +"[\"Vermelho\", \"Verde\", \"Azul\", \"Alf\"]" #: ../../tutorial/introduction.rst:444 msgid "" @@ -547,7 +1047,23 @@ msgid "" msgstr "" "Todas as operações de fatiamento devolvem uma nova lista contendo os " "elementos solicitados. Isso significa que o seguinte fatiamento devolve uma :" -"ref:`cópia rasa` da lista::" +"ref:`cópia rasa ` da lista::" + +#: ../../tutorial/introduction.rst:448 +msgid "" +">>> correct_rgba = rgba[:]\n" +">>> correct_rgba[-1] = \"Alpha\"\n" +">>> correct_rgba\n" +"[\"Red\", \"Green\", \"Blue\", \"Alpha\"]\n" +">>> rgba\n" +"[\"Red\", \"Green\", \"Blue\", \"Alph\"]" +msgstr "" +">>> rgba_correto = rgba[:]\n" +">>> rgba_correto[-1] = \"Alfa\"\n" +">>> rgba_correto\n" +"[\"Vermelho\", \"Verde\", \"Azul\", \"Alfa\"]\n" +">>> rgba\n" +"[\"Vermelho\", \"Verde\", \"Azul\", \"Alf\"]" #: ../../tutorial/introduction.rst:455 msgid "" @@ -557,10 +1073,54 @@ msgstr "" "Atribuição a fatias também é possível, e isso pode até alterar o tamanho da " "lista ou remover todos os itens dela::" +#: ../../tutorial/introduction.rst:458 +msgid "" +">>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']\n" +">>> letters\n" +"['a', 'b', 'c', 'd', 'e', 'f', 'g']\n" +">>> # replace some values\n" +">>> letters[2:5] = ['C', 'D', 'E']\n" +">>> letters\n" +"['a', 'b', 'C', 'D', 'E', 'f', 'g']\n" +">>> # now remove them\n" +">>> letters[2:5] = []\n" +">>> letters\n" +"['a', 'b', 'f', 'g']\n" +">>> # clear the list by replacing all the elements with an empty list\n" +">>> letters[:] = []\n" +">>> letters\n" +"[]" +msgstr "" +">>> letras = ['a', 'b', 'c', 'd', 'e', 'f', 'g']\n" +">>> letras\n" +"['a', 'b', 'c', 'd', 'e', 'f', 'g']\n" +">>> # substitui alguns valores\n" +">>> letras[2:5] = ['C', 'D', 'E']\n" +">>> letras\n" +"['a', 'b', 'C', 'D', 'E', 'f', 'g']\n" +">>> # agora remove-os\n" +">>> letras[2:5] = []\n" +">>> letras\n" +"['a', 'b', 'f', 'g']\n" +">>> # limpa a lista substituindo todos os elementos por uma lista vazia\n" +">>> letras[:] = []\n" +">>> letras\n" +"[]" + #: ../../tutorial/introduction.rst:474 msgid "The built-in function :func:`len` also applies to lists::" msgstr "A função embutida :func:`len` também se aplica a listas::" +#: ../../tutorial/introduction.rst:476 +msgid "" +">>> letters = ['a', 'b', 'c', 'd']\n" +">>> len(letters)\n" +"4" +msgstr "" +">>> letras = ['a', 'b', 'c', 'd']\n" +">>> len(letras)\n" +"4" + #: ../../tutorial/introduction.rst:480 msgid "" "It is possible to nest lists (create lists containing other lists), for " @@ -569,6 +1129,28 @@ msgstr "" "É possível aninhar listas (criar listas contendo outras listas), por " "exemplo::" +#: ../../tutorial/introduction.rst:483 +msgid "" +">>> a = ['a', 'b', 'c']\n" +">>> n = [1, 2, 3]\n" +">>> x = [a, n]\n" +">>> x\n" +"[['a', 'b', 'c'], [1, 2, 3]]\n" +">>> x[0]\n" +"['a', 'b', 'c']\n" +">>> x[0][1]\n" +"'b'" +msgstr "" +">>> a = ['a', 'b', 'c']\n" +">>> n = [1, 2, 3]\n" +">>> x = [a, n]\n" +">>> x\n" +"[['a', 'b', 'c'], [1, 2, 3]]\n" +">>> x[0]\n" +"['a', 'b', 'c']\n" +">>> x[0][1]\n" +"'b'" + #: ../../tutorial/introduction.rst:496 msgid "First Steps Towards Programming" msgstr "Primeiros passos para a programação" @@ -584,6 +1166,38 @@ msgstr "" "Por exemplo, podemos escrever o início da `sequência de Fibonacci `_ assim::" +#: ../../tutorial/introduction.rst:503 +msgid "" +">>> # Fibonacci series:\n" +">>> # the sum of two elements defines the next\n" +">>> a, b = 0, 1\n" +">>> while a < 10:\n" +"... print(a)\n" +"... a, b = b, a+b\n" +"...\n" +"0\n" +"1\n" +"1\n" +"2\n" +"3\n" +"5\n" +"8" +msgstr "" +">>> # Sequência de Fibonacci:\n" +">>> # a soma de dois elementos define a próxima\n" +">>> a, b = 0, 1\n" +">>> while a < 10:\n" +"... print(a)\n" +"... a, b = b, a+b\n" +"...\n" +"0\n" +"1\n" +"1\n" +"2\n" +"3\n" +"5\n" +"8" + #: ../../tutorial/introduction.rst:518 msgid "This example introduces several new features." msgstr "Este exemplo introduz diversas características ainda não mencionadas." @@ -660,13 +1274,39 @@ msgstr "" "são impressas sem aspas, e um espaço é inserido entre os itens, assim você " "pode formatar bem o resultado, dessa forma::" +#: ../../tutorial/introduction.rst:551 +msgid "" +">>> i = 256*256\n" +">>> print('The value of i is', i)\n" +"The value of i is 65536" +msgstr "" +">>> i = 256*256\n" +">>> print('O valor de i é', i)\n" +"O valor de i é 65536" + #: ../../tutorial/introduction.rst:555 msgid "" "The keyword argument *end* can be used to avoid the newline after the " "output, or end the output with a different string::" msgstr "" -"O argumento *end* pode ser usado para evitar uma nova linha após a saída ou " -"finalizar a saída com uma string diferente::" +"O argumento nomeado *end* pode ser usado para evitar uma nova linha após a " +"saída ou finalizar a saída com uma string diferente::" + +#: ../../tutorial/introduction.rst:558 +msgid "" +">>> a, b = 0, 1\n" +">>> while a < 1000:\n" +"... print(a, end=',')\n" +"... a, b = b, a+b\n" +"...\n" +"0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987," +msgstr "" +">>> a, b = 0, 1\n" +">>> while a < 1000:\n" +"... print(a, end=',')\n" +"... a, b = b, a+b\n" +"...\n" +"0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987," #: ../../tutorial/introduction.rst:567 msgid "Footnotes" diff --git a/tutorial/modules.po b/tutorial/modules.po index 945ced9f4..a2f126559 100644 --- a/tutorial/modules.po +++ b/tutorial/modules.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2021 -# Tiago Henrique , 2021 -# Adorilson Bezerra , 2022 -# Claudio Rogerio Carvalho Filho , 2023 -# Marco Rougeth , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-05 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 01:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -84,6 +79,42 @@ msgstr "" "para criar um arquivo chamado :file:`fibo.py` no diretório atual com o " "seguinte conteúdo::" +#: ../../tutorial/modules.rst:28 +msgid "" +"# Fibonacci numbers module\n" +"\n" +"def fib(n): # write Fibonacci series up to n\n" +" a, b = 0, 1\n" +" while a < n:\n" +" print(a, end=' ')\n" +" a, b = b, a+b\n" +" print()\n" +"\n" +"def fib2(n): # return Fibonacci series up to n\n" +" result = []\n" +" a, b = 0, 1\n" +" while a < n:\n" +" result.append(a)\n" +" a, b = b, a+b\n" +" return result" +msgstr "" +"# Módulo de números de Fibonacci\n" +"\n" +"def fib(n): # escreve a série de Fibonacci até n\n" +" a, b = 0, 1\n" +" while a < n:\n" +" print(a, end=' ')\n" +" a, b = b, a+b\n" +" print()\n" +"\n" +"def fib2(n): # retorna a série de Fibonacci até n\n" +" result = []\n" +" a, b = 0, 1\n" +" while a < n:\n" +" result.append(a)\n" +" a, b = b, a+b\n" +" return result" + #: ../../tutorial/modules.rst:45 msgid "" "Now enter the Python interpreter and import this module with the following " @@ -92,6 +123,10 @@ msgstr "" "Agora, entre no interpretador Python e importe esse módulo com o seguinte\n" "comando::" +#: ../../tutorial/modules.rst:48 +msgid ">>> import fibo" +msgstr ">>> import fibo" + #: ../../tutorial/modules.rst:50 msgid "" "This does not add the names of the functions defined in ``fibo`` directly " @@ -104,6 +139,22 @@ msgstr "" "isso adiciona somente o nome do módulo ``fibo``. Usando o nome do módulo " "você pode acessar as funções::" +#: ../../tutorial/modules.rst:55 +msgid "" +">>> fibo.fib(1000)\n" +"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987\n" +">>> fibo.fib2(100)\n" +"[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n" +">>> fibo.__name__\n" +"'fibo'" +msgstr "" +">>> fibo.fib(1000)\n" +"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987\n" +">>> fibo.fib2(100)\n" +"[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n" +">>> fibo.__name__\n" +"'fibo'" + #: ../../tutorial/modules.rst:62 msgid "" "If you intend to use a function often you can assign it to a local name::" @@ -111,6 +162,16 @@ msgstr "" "Se você pretende usar uma função muitas vezes, você pode atribui-lá a um " "nome local::" +#: ../../tutorial/modules.rst:64 +msgid "" +">>> fib = fibo.fib\n" +">>> fib(500)\n" +"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" +msgstr "" +">>> fib = fibo.fib\n" +">>> fib(500)\n" +"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" + #: ../../tutorial/modules.rst:72 msgid "More on Modules" msgstr "Mais sobre módulos" @@ -167,6 +228,16 @@ msgstr "" "um módulo diretamente para o espaço de nomes do módulo importador. Por " "exemplo::" +#: ../../tutorial/modules.rst:94 +msgid "" +">>> from fibo import fib, fib2\n" +">>> fib(500)\n" +"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" +msgstr "" +">>> from fibo import fib, fib2\n" +">>> fib(500)\n" +"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" + #: ../../tutorial/modules.rst:98 msgid "" "This does not introduce the module name from which the imports are taken in " @@ -180,6 +251,16 @@ msgid "There is even a variant to import all names that a module defines::" msgstr "" "Existe ainda uma variante que importa todos os nomes definidos em um módulo::" +#: ../../tutorial/modules.rst:103 +msgid "" +">>> from fibo import *\n" +">>> fib(500)\n" +"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" +msgstr "" +">>> from fibo import *\n" +">>> fib(500)\n" +"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" + #: ../../tutorial/modules.rst:107 msgid "" "This imports all names except those beginning with an underscore (``_``). In " @@ -210,6 +291,16 @@ msgstr "" "Se o nome do módulo é seguido pela palavra-chave :keyword:`!as`, o nome a " "seguir é vinculado diretamente ao módulo importado." +#: ../../tutorial/modules.rst:121 +msgid "" +">>> import fibo as fib\n" +">>> fib.fib(500)\n" +"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" +msgstr "" +">>> import fibo as fib\n" +">>> fib.fib(500)\n" +"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" + #: ../../tutorial/modules.rst:125 msgid "" "This is effectively importing the module in the same way that ``import " @@ -225,6 +316,16 @@ msgstr "" "Também pode ser utilizado com a palavra-chave :keyword:`from`, com efeitos " "similares::" +#: ../../tutorial/modules.rst:130 +msgid "" +">>> from fibo import fib as fibonacci\n" +">>> fibonacci(500)\n" +"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" +msgstr "" +">>> from fibo import fib as fibonacci\n" +">>> fibonacci(500)\n" +"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" + #: ../../tutorial/modules.rst:137 msgid "" "For efficiency reasons, each module is only imported once per interpreter " @@ -247,6 +348,10 @@ msgstr "Executando módulos como scripts" msgid "When you run a Python module with ::" msgstr "Quando você rodar um módulo Python com ::" +#: ../../tutorial/modules.rst:151 +msgid "python fibo.py " +msgstr "python fibo.py " + #: ../../tutorial/modules.rst:153 msgid "" "the code in the module will be executed, just as if you imported it, but " @@ -257,6 +362,16 @@ msgstr "" "mas com a variável ``__name__`` com valor ``\"__main__\"``. Isto significa " "que adicionando este código ao final do seu módulo::" +#: ../../tutorial/modules.rst:157 +msgid "" +"if __name__ == \"__main__\":\n" +" import sys\n" +" fib(int(sys.argv[1]))" +msgstr "" +"if __name__ == \"__main__\":\n" +" import sys\n" +" fib(int(sys.argv[1]))" + #: ../../tutorial/modules.rst:161 msgid "" "you can make the file usable as a script as well as an importable module, " @@ -267,10 +382,26 @@ msgstr "" "módulo importável, porque o código que analisa a linha de comando só roda se " "o módulo é executado como arquivo \"principal\":" +#: ../../tutorial/modules.rst:165 +msgid "" +"$ python fibo.py 50\n" +"0 1 1 2 3 5 8 13 21 34" +msgstr "" +"$ python fibo.py 50\n" +"0 1 1 2 3 5 8 13 21 34" + #: ../../tutorial/modules.rst:170 msgid "If the module is imported, the code is not run::" msgstr "Se o módulo é importado, o código não é executado::" +#: ../../tutorial/modules.rst:172 +msgid "" +">>> import fibo\n" +">>>" +msgstr "" +">>> import fibo\n" +">>>" + #: ../../tutorial/modules.rst:175 msgid "" "This is often used either to provide a convenient user interface to a " @@ -485,6 +616,28 @@ msgstr "" "interpretador Python. As variáveis ``sys.ps1`` e ``sys.ps2`` definem as " "strings utilizadas como prompt primário e secundário::" +#: ../../tutorial/modules.rst:281 +msgid "" +">>> import sys\n" +">>> sys.ps1\n" +"'>>> '\n" +">>> sys.ps2\n" +"'... '\n" +">>> sys.ps1 = 'C> '\n" +"C> print('Yuck!')\n" +"Yuck!\n" +"C>" +msgstr "" +">>> import sys\n" +">>> sys.ps1\n" +"'>>> '\n" +">>> sys.ps2\n" +"'... '\n" +">>> sys.ps1 = 'C> '\n" +"C> print('ECA!')\n" +"Yuck!\n" +"C>" + #: ../../tutorial/modules.rst:292 msgid "" "These two variables are only defined if the interpreter is in interactive " @@ -508,6 +661,14 @@ msgstr "" "`PYTHONPATH` não estiver definida. Você pode modificá-la com as operações " "típicas de lista, por exemplo::" +#: ../../tutorial/modules.rst:300 +msgid "" +">>> import sys\n" +">>> sys.path.append('/ufs/guido/lib/python')" +msgstr "" +">>> import sys\n" +">>> sys.path.append('/ufs/guido/lib/python')" + #: ../../tutorial/modules.rst:307 msgid "The :func:`dir` Function" msgstr "A função :func:`dir`" @@ -520,11 +681,93 @@ msgstr "" "A função embutida :func:`dir` é usada para descobrir quais nomes são " "definidos por um módulo. Ela devolve uma lista ordenada de strings::" +#: ../../tutorial/modules.rst:312 +msgid "" +">>> import fibo, sys\n" +">>> dir(fibo)\n" +"['__name__', 'fib', 'fib2']\n" +">>> dir(sys)\n" +"['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__',\n" +" '__interactivehook__', '__loader__', '__name__', '__package__', " +"'__spec__',\n" +" '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__',\n" +" '_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework',\n" +" '_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook',\n" +" 'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix',\n" +" 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing',\n" +" 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', " +"'exc_info',\n" +" 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info',\n" +" 'float_repr_style', 'get_asyncgen_hooks', " +"'get_coroutine_origin_tracking_depth',\n" +" 'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags',\n" +" 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile',\n" +" 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval',\n" +" 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',\n" +" 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value',\n" +" 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',\n" +" 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', " +"'pycache_prefix',\n" +" 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', " +"'setdlopenflags',\n" +" 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', " +"'stderr',\n" +" 'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', " +"'version_info',\n" +" 'warnoptions']" +msgstr "" +">>> import fibo, sys\n" +">>> dir(fibo)\n" +"['__name__', 'fib', 'fib2']\n" +">>> dir(sys)\n" +"['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__',\n" +" '__interactivehook__', '__loader__', '__name__', '__package__', " +"'__spec__',\n" +" '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__',\n" +" '_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework',\n" +" '_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook',\n" +" 'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix',\n" +" 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing',\n" +" 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', " +"'exc_info',\n" +" 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info',\n" +" 'float_repr_style', 'get_asyncgen_hooks', " +"'get_coroutine_origin_tracking_depth',\n" +" 'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags',\n" +" 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile',\n" +" 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval',\n" +" 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',\n" +" 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value',\n" +" 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',\n" +" 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', " +"'pycache_prefix',\n" +" 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', " +"'setdlopenflags',\n" +" 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', " +"'stderr',\n" +" 'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', " +"'version_info',\n" +" 'warnoptions']" + #: ../../tutorial/modules.rst:338 msgid "" "Without arguments, :func:`dir` lists the names you have defined currently::" msgstr "Sem argumentos, :func:`dir` lista os nomes atualmente definidos::" +#: ../../tutorial/modules.rst:340 +msgid "" +">>> a = [1, 2, 3, 4, 5]\n" +">>> import fibo\n" +">>> fib = fibo.fib\n" +">>> dir()\n" +"['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']" +msgstr "" +">>> a = [1, 2, 3, 4, 5]\n" +">>> import fibo\n" +">>> fib = fibo.fib\n" +">>> dir()\n" +"['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']" + #: ../../tutorial/modules.rst:346 msgid "" "Note that it lists all types of names: variables, modules, functions, etc." @@ -540,6 +783,74 @@ msgstr "" ":func:`dir` não lista os nomes de variáveis e funções embutidas. Esta lista " "está disponível no módulo padrão :mod:`builtins`::" +#: ../../tutorial/modules.rst:354 +msgid "" +">>> import builtins\n" +">>> dir(builtins)\n" +"['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',\n" +" 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',\n" +" 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',\n" +" 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',\n" +" 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',\n" +" 'FileExistsError', 'FileNotFoundError', 'FloatingPointError',\n" +" 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',\n" +" 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',\n" +" 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',\n" +" 'MemoryError', 'NameError', 'None', 'NotADirectoryError', " +"'NotImplemented',\n" +" 'NotImplementedError', 'OSError', 'OverflowError',\n" +" 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',\n" +" 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',\n" +" 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',\n" +" 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',\n" +" 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',\n" +" 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',\n" +" 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',\n" +" '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',\n" +" 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',\n" +" 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',\n" +" 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',\n" +" 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',\n" +" 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',\n" +" 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',\n" +" 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',\n" +" 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',\n" +" 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',\n" +" 'zip']" +msgstr "" +">>> import builtins\n" +">>> dir(builtins)\n" +"['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',\n" +" 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',\n" +" 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',\n" +" 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',\n" +" 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',\n" +" 'FileExistsError', 'FileNotFoundError', 'FloatingPointError',\n" +" 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',\n" +" 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',\n" +" 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',\n" +" 'MemoryError', 'NameError', 'None', 'NotADirectoryError', " +"'NotImplemented',\n" +" 'NotImplementedError', 'OSError', 'OverflowError',\n" +" 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',\n" +" 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',\n" +" 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',\n" +" 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',\n" +" 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',\n" +" 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',\n" +" 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',\n" +" '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',\n" +" 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',\n" +" 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',\n" +" 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',\n" +" 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',\n" +" 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',\n" +" 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',\n" +" 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',\n" +" 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',\n" +" 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',\n" +" 'zip']" + #: ../../tutorial/modules.rst:389 msgid "Packages" msgstr "Pacotes" @@ -589,6 +900,57 @@ msgstr "" "estrutura para o seu pacote (expressa em termos de um sistema de arquivos " "hierárquico)::" +#: ../../tutorial/modules.rst:410 +msgid "" +"sound/ Top-level package\n" +" __init__.py Initialize the sound package\n" +" formats/ Subpackage for file format conversions\n" +" __init__.py\n" +" wavread.py\n" +" wavwrite.py\n" +" aiffread.py\n" +" aiffwrite.py\n" +" auread.py\n" +" auwrite.py\n" +" ...\n" +" effects/ Subpackage for sound effects\n" +" __init__.py\n" +" echo.py\n" +" surround.py\n" +" reverse.py\n" +" ...\n" +" filters/ Subpackage for filters\n" +" __init__.py\n" +" equalizer.py\n" +" vocoder.py\n" +" karaoke.py\n" +" ..." +msgstr "" +"sound/ pacote de nível superior\n" +" __init__.py Inicializa o pacote de som\n" +" formats/ Subpacote para as conversões entre formatos " +"de arquivos\n" +" __init__.py\n" +" wavread.py\n" +" wavwrite.py\n" +" aiffread.py\n" +" aiffwrite.py\n" +" auread.py\n" +" auwrite.py\n" +" ...\n" +" effects/ Subpacote para efeitos de som\n" +" __init__.py\n" +" echo.py\n" +" surround.py\n" +" reverse.py\n" +" ...\n" +" filters/ Subpacote para filtros\n" +" __init__.py\n" +" equalizer.py\n" +" vocoder.py\n" +" karaoke.py\n" +" ..." + #: ../../tutorial/modules.rst:436 msgid "" "When importing the package, Python searches through the directories on ``sys." @@ -622,6 +984,10 @@ msgid "" "example::" msgstr "Usuários do pacote podem importar módulos individuais, por exemplo::" +#: ../../tutorial/modules.rst:450 +msgid "import sound.effects.echo" +msgstr "import sound.effects.echo" + #: ../../tutorial/modules.rst:452 msgid "" "This loads the submodule :mod:`!sound.effects.echo`. It must be referenced " @@ -630,10 +996,18 @@ msgstr "" "Isso carrega o submódulo :mod:`!sound.effects.echo`. Ele deve ser " "referenciado com seu nome completo, como em::" +#: ../../tutorial/modules.rst:455 +msgid "sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)" +msgstr "sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)" + #: ../../tutorial/modules.rst:457 msgid "An alternative way of importing the submodule is::" msgstr "Uma maneira alternativa para a importação desse módulo é::" +#: ../../tutorial/modules.rst:459 +msgid "from sound.effects import echo" +msgstr "from sound.effects import echo" + #: ../../tutorial/modules.rst:461 msgid "" "This also loads the submodule :mod:`!echo`, and makes it available without " @@ -642,12 +1016,20 @@ msgstr "" "Isso carrega o submódulo :mod:`!echo` sem necessidade de mencionar o prefixo " "do pacote no momento da utilização, assim::" +#: ../../tutorial/modules.rst:464 +msgid "echo.echofilter(input, output, delay=0.7, atten=4)" +msgstr "echo.echofilter(input, output, delay=0.7, atten=4)" + #: ../../tutorial/modules.rst:466 msgid "" "Yet another variation is to import the desired function or variable " "directly::" msgstr "Também é possível importar diretamente uma única variável ou função::" +#: ../../tutorial/modules.rst:468 +msgid "from sound.effects.echo import echofilter" +msgstr "from sound.effects.echo import echofilter" + #: ../../tutorial/modules.rst:470 msgid "" "Again, this loads the submodule :mod:`!echo`, but this makes its function :" @@ -656,6 +1038,10 @@ msgstr "" "Novamente, isso carrega o submódulo :mod:`!echo`, mas a função :func:`!" "echofilter` está acessível diretamente sem prefixo::" +#: ../../tutorial/modules.rst:473 +msgid "echofilter(input, output, delay=0.7, atten=4)" +msgstr "echofilter(input, output, delay=0.7, atten=4)" + #: ../../tutorial/modules.rst:475 msgid "" "Note that when using ``from package import item``, the item can be either a " @@ -724,6 +1110,10 @@ msgstr "" "*``. Por exemplo, o arquivo :file:`sounds/effects/__init__.py` poderia " "conter apenas::" +#: ../../tutorial/modules.rst:511 +msgid "__all__ = [\"echo\", \"surround\", \"reverse\"]" +msgstr "__all__ = [\"echo\", \"surround\", \"reverse\"]" + #: ../../tutorial/modules.rst:513 msgid "" "This would mean that ``from sound.effects import *`` would import the three " @@ -748,6 +1138,27 @@ msgstr "" "*não* o submódulo ``reverse``, porque ele fica sobreposto pela função " "``reverse`` definida localmente::" +#: ../../tutorial/modules.rst:523 +msgid "" +"__all__ = [\n" +" \"echo\", # refers to the 'echo.py' file\n" +" \"surround\", # refers to the 'surround.py' file\n" +" \"reverse\", # !!! refers to the 'reverse' function now !!!\n" +"]\n" +"\n" +"def reverse(msg: str): # <-- this name shadows the 'reverse.py' submodule\n" +" return msg[::-1] # in the case of a 'from sound.effects import *'" +msgstr "" +"__all__ = [\n" +" \"echo\", # refere-se ao arquivo 'echo.py'\n" +" \"surround\", # refere-se ao arquivo 'surround.py'\n" +" \"reverse\", # !!! refere-se à função 'reverse' agora !!!\n" +"]\n" +"\n" +"def reverse(msg: str): # <-- este nome ofusca o submódulo 'reverse.py'\n" +" return msg[::-1] # no caso de uma importação 'from sound.effects " +"import *'" + #: ../../tutorial/modules.rst:532 msgid "" "If ``__all__`` is not defined, the statement ``from sound.effects import *`` " @@ -770,6 +1181,16 @@ msgstr "" "tenham sido carregados explicitamente por instruções :keyword:`import` " "anteriores. Considere o código abaixo::" +#: ../../tutorial/modules.rst:541 +msgid "" +"import sound.effects.echo\n" +"import sound.effects.surround\n" +"from sound.effects import *" +msgstr "" +"import sound.effects.echo\n" +"import sound.effects.surround\n" +"from sound.effects import *" + #: ../../tutorial/modules.rst:545 msgid "" "In this example, the :mod:`!echo` and :mod:`!surround` modules are imported " @@ -835,6 +1256,16 @@ msgstr "" "atual, envolvidos no import relativo. Do módulo :mod:`!surround`, por " "exemplo, pode-se usar::" +#: ../../tutorial/modules.rst:576 +msgid "" +"from . import echo\n" +"from .. import formats\n" +"from ..filters import equalizer" +msgstr "" +"from . import echo\n" +"from .. import formats\n" +"from ..filters import equalizer" + #: ../../tutorial/modules.rst:580 msgid "" "Note that relative imports are based on the name of the current module. " @@ -853,19 +1284,19 @@ msgstr "Pacotes em múltiplos diretórios" #: ../../tutorial/modules.rst:588 msgid "" -"Packages support one more special attribute, :attr:`__path__`. This is " -"initialized to be a list containing the name of the directory holding the " -"package's :file:`__init__.py` before the code in that file is executed. " -"This variable can be modified; doing so affects future searches for modules " -"and subpackages contained in the package." +"Packages support one more special attribute, :attr:`~module.__path__`. This " +"is initialized to be a :term:`sequence` of strings containing the name of " +"the directory holding the package's :file:`__init__.py` before the code in " +"that file is executed. This variable can be modified; doing so affects " +"future searches for modules and subpackages contained in the package." msgstr "" -"Pacotes possuem mais um atributo especial, :attr:`__path__`. Inicializado " -"como uma lista contendo o nome do diretório onde está o arquivo :file:" -"`__init__.py` do pacote, antes do código naquele arquivo ser executado. Esta " -"variável pode ser modificada; isso afeta a busca futura de módulos e " -"subpacotes contidos no pacote." +"Pacotes possuem mais um atributo especial, :attr:`~module.__path__`. " +"Inicializado como uma :term:`sequência` de strings contendo o nome do " +"diretório onde está o arquivo :file:`__init__.py` do pacote, antes do código " +"naquele arquivo ser executado. Esta variável pode ser modificada; isso afeta " +"a busca futura de módulos e subpacotes contidos no pacote." -#: ../../tutorial/modules.rst:594 +#: ../../tutorial/modules.rst:595 msgid "" "While this feature is not often needed, it can be used to extend the set of " "modules found in a package." @@ -873,11 +1304,11 @@ msgstr "" "Apesar de não ser muito usado, esse mecanismo permite estender o conjunto de " "módulos encontrados em um pacote." -#: ../../tutorial/modules.rst:599 +#: ../../tutorial/modules.rst:600 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../tutorial/modules.rst:600 +#: ../../tutorial/modules.rst:601 msgid "" "In fact function definitions are also 'statements' that are 'executed'; the " "execution of a module-level function definition adds the function name to " diff --git a/tutorial/stdlib.po b/tutorial/stdlib.po index 83fe29164..7ee5008e9 100644 --- a/tutorial/stdlib.po +++ b/tutorial/stdlib.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Leticia Portella , 2021 -# Misael borges , 2021 -# Adorilson Bezerra , 2021 -# And Past , 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-20 00:52+0000\n" -"PO-Revision-Date: 2021-06-28 01:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -44,6 +39,22 @@ msgstr "" "O módulo :mod:`os` fornece dúzias de funções para interagir com o sistema " "operacional::" +#: ../../tutorial/stdlib.rst:16 +msgid "" +">>> import os\n" +">>> os.getcwd() # Return the current working directory\n" +"'C:\\\\Python313'\n" +">>> os.chdir('/server/accesslogs') # Change current working directory\n" +">>> os.system('mkdir today') # Run the command mkdir in the system shell\n" +"0" +msgstr "" +">>> import os\n" +">>> os.getcwd() # Retorna o diretório de trabalho atual\n" +"'C:\\\\Python313'\n" +">>> os.chdir('/server/accesslogs') # Altera o diretório de trabalho atual\n" +">>> os.system('mkdir hoje') # Executa o comando mkdir no shell do sistema\n" +"0" + #: ../../tutorial/stdlib.rst:23 msgid "" "Be sure to use the ``import os`` style instead of ``from os import *``. " @@ -62,6 +73,21 @@ msgstr "" "As funções embutidas :func:`dir` e :func:`help` são úteis como um sistema de " "ajuda interativa para lidar com módulos grandes como :mod:`os`::" +#: ../../tutorial/stdlib.rst:32 +msgid "" +">>> import os\n" +">>> dir(os)\n" +"\n" +">>> help(os)\n" +"" +msgstr "" +">>> import os\n" +">>> dir(os)\n" +"\n" +">>> help(os)\n" +"" + #: ../../tutorial/stdlib.rst:38 msgid "" "For daily file and directory management tasks, the :mod:`shutil` module " @@ -70,6 +96,20 @@ msgstr "" "Para tarefas de gerenciamento cotidiano de arquivos e diretórios, o módulo :" "mod:`shutil` fornece uma interface de alto nível que é mais simples de usar::" +#: ../../tutorial/stdlib.rst:41 +msgid "" +">>> import shutil\n" +">>> shutil.copyfile('data.db', 'archive.db')\n" +"'archive.db'\n" +">>> shutil.move('/build/executables', 'installdir')\n" +"'installdir'" +msgstr "" +">>> import shutil\n" +">>> shutil.copyfile('dados.db', 'arquivo.db')\n" +"'arquivo.db'\n" +">>> shutil.move('/build/executáveis', 'dir_instal')\n" +"'dir_instal'" + #: ../../tutorial/stdlib.rst:51 msgid "File Wildcards" msgstr "Caracteres curinga" @@ -82,6 +122,16 @@ msgstr "" "O módulo :mod:`glob` fornece uma função para criar listas de arquivos a " "partir de buscas em diretórios usando caracteres curinga::" +#: ../../tutorial/stdlib.rst:56 +msgid "" +">>> import glob\n" +">>> glob.glob('*.py')\n" +"['primes.py', 'random.py', 'quote.py']" +msgstr "" +">>> import glob\n" +">>> glob.glob('*.py')\n" +"['primos.py', 'aleatorizar.py', 'aspas.py']" + #: ../../tutorial/stdlib.rst:64 msgid "Command Line Arguments" msgstr "Argumentos de linha de comando" @@ -97,14 +147,28 @@ msgstr "" "do módulo :mod:`sys`. Por exemplo, consideremos o arquivo :file:`demo.py` a " "seguir::" +#: ../../tutorial/stdlib.rst:70 +msgid "" +"# File demo.py\n" +"import sys\n" +"print(sys.argv)" +msgstr "" +"# Arquivo demo.py\n" +"import sys\n" +"print(sys.argv)" + #: ../../tutorial/stdlib.rst:74 msgid "" "Here is the output from running ``python demo.py one two three`` at the " "command line::" msgstr "" -"Aqui está a saída da execução ``python demo.py one two three`` na linha de " +"Aqui está a saída da execução ``python demo.py um dois três`` na linha de " "comando::" +#: ../../tutorial/stdlib.rst:77 +msgid "['demo.py', 'one', 'two', 'three']" +msgstr "['demo.py', 'um', 'dois, 'três']" + #: ../../tutorial/stdlib.rst:79 msgid "" "The :mod:`argparse` module provides a more sophisticated mechanism to " @@ -115,15 +179,37 @@ msgstr "" "processar argumentos de linha de comando. O script seguinte extrai e exibe " "um ou mais nomes de arquivos e um número de linhas opcional::" +#: ../../tutorial/stdlib.rst:83 +msgid "" +"import argparse\n" +"\n" +"parser = argparse.ArgumentParser(\n" +" prog='top',\n" +" description='Show top lines from each file')\n" +"parser.add_argument('filenames', nargs='+')\n" +"parser.add_argument('-l', '--lines', type=int, default=10)\n" +"args = parser.parse_args()\n" +"print(args)" +msgstr "" +"import argparse\n" +"\n" +"parser = argparse.ArgumentParser(\n" +" prog='topo',\n" +" description='Mostra as primeiras linhas de cada arquivo')\n" +"parser.add_argument('arquivos, nargs='+')\n" +"parser.add_argument('-l', '--linhas', type=int, default=10)\n" +"args = parser.parse_args()\n" +"print(args)" + #: ../../tutorial/stdlib.rst:93 msgid "" "When run at the command line with ``python top.py --lines=5 alpha.txt beta." "txt``, the script sets ``args.lines`` to ``5`` and ``args.filenames`` to " "``['alpha.txt', 'beta.txt']``." msgstr "" -"Quando executada a linha de comando ``python top.py --lines=5 alpha.txt beta." -"txt``, o script define ``args.lines`` para ``5`` e ``args.filenames`` para " -"``['alpha.txt', 'beta.txt']``." +"Quando executada na linha de comando ``python topo.py --linhas=5 alfa.txt " +"beta.txt``, o script define ``args.linhas`` para ``5`` e ``args.arquivos`` " +"para ``['alfa.txt', 'beta.txt']``." #: ../../tutorial/stdlib.rst:101 msgid "Error Output Redirection and Program Termination" @@ -139,6 +225,15 @@ msgstr "" "*stderr*. O último é usado para emitir avisos e mensagens de erros visíveis " "mesmo quando *stdout* foi redirecionado::" +#: ../../tutorial/stdlib.rst:107 +msgid "" +">>> sys.stderr.write('Warning, log file not found starting a new one\\n')\n" +"Warning, log file not found starting a new one" +msgstr "" +">>> sys.stderr.write('Aviso, arquivo log não encontrado, iniciando um " +"novo\\n')\n" +"Aviso, arquivo log não encontrado, iniciando um novo" + #: ../../tutorial/stdlib.rst:110 msgid "The most direct way to terminate a script is to use ``sys.exit()``." msgstr "A forma mais direta de encerrar um script é usando ``sys.exit()``." @@ -157,6 +252,20 @@ msgstr "" "strings através de expressões regulares. Para reconhecimento de padrões " "complexos, expressões regulares oferecem uma solução sucinta e eficiente::" +#: ../../tutorial/stdlib.rst:122 +msgid "" +">>> import re\n" +">>> re.findall(r'\\bf[a-z]*', 'which foot or hand fell fastest')\n" +"['foot', 'fell', 'fastest']\n" +">>> re.sub(r'(\\b[a-z]+) \\1', r'\\1', 'cat in the the hat')\n" +"'cat in the hat'" +msgstr "" +">>> import re\n" +">>> re.findall(r'\\br[a-z]*', 'o rato roeu a roupa do rei de roma')\n" +"['rato', 'roeu', 'roupa', 'rei', 'roma']\n" +">>> re.sub(r'(\\b[a-z]+) \\1', r'\\1', 'o gato de de chapéu')\n" +"'o gato de chapéu'" + #: ../../tutorial/stdlib.rst:128 msgid "" "When only simple capabilities are needed, string methods are preferred " @@ -165,6 +274,14 @@ msgstr "" "Quando as exigências são simples, métodos de strings são preferíveis por " "serem mais fáceis de ler e depurar::" +#: ../../tutorial/stdlib.rst:131 +msgid "" +">>> 'tea for too'.replace('too', 'two')\n" +"'tea for two'" +msgstr "" +">>> 'xá para dois'.replace('xá', 'chá')\n" +"'chá para dois'" + #: ../../tutorial/stdlib.rst:138 msgid "Mathematics" msgstr "Matemática" @@ -177,11 +294,47 @@ msgstr "" "O módulo :mod:`math` oferece acesso às funções da biblioteca C para " "matemática de ponto flutuante::" +#: ../../tutorial/stdlib.rst:143 +msgid "" +">>> import math\n" +">>> math.cos(math.pi / 4)\n" +"0.70710678118654757\n" +">>> math.log(1024, 2)\n" +"10.0" +msgstr "" +">>> import math\n" +">>> math.cos(math.pi / 4)\n" +"0.70710678118654757\n" +">>> math.log(1024, 2)\n" +"10.0" + #: ../../tutorial/stdlib.rst:149 msgid "The :mod:`random` module provides tools for making random selections::" msgstr "" "O módulo :mod:`random` fornece ferramentas para gerar seleções aleatórias::" +#: ../../tutorial/stdlib.rst:151 +msgid "" +">>> import random\n" +">>> random.choice(['apple', 'pear', 'banana'])\n" +"'apple'\n" +">>> random.sample(range(100), 10) # sampling without replacement\n" +"[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]\n" +">>> random.random() # random float from the interval [0.0, 1.0)\n" +"0.17970987693706186\n" +">>> random.randrange(6) # random integer chosen from range(6)\n" +"4" +msgstr "" +">>> import random\n" +">>> random.choice(['maçã', 'pera', 'banana'])\n" +"'maçã'\n" +">>> random.sample(range(100), 10) # amostragem sem reposição\n" +"[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]\n" +">>> random.random() # ponto flutuante aleatório do intervalo [0.0, 1.0)\n" +"0.17970987693706186\n" +">>> random.randrange(6) # inteiro aleatório escolhido de range(6)\n" +"4" + #: ../../tutorial/stdlib.rst:161 msgid "" "The :mod:`statistics` module calculates basic statistical properties (the " @@ -190,6 +343,26 @@ msgstr "" "O módulo :mod:`statistics` calcula as propriedades estatísticas básicas (a " "média, a mediana, a variação, etc.) de dados numéricos::" +#: ../../tutorial/stdlib.rst:164 +msgid "" +">>> import statistics\n" +">>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]\n" +">>> statistics.mean(data)\n" +"1.6071428571428572\n" +">>> statistics.median(data)\n" +"1.25\n" +">>> statistics.variance(data)\n" +"1.3720238095238095" +msgstr "" +">>> import statistics\n" +">>> dados = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]\n" +">>> statistics.mean(dados)\n" +"1.6071428571428572\n" +">>> statistics.median(dados)\n" +"1.25\n" +">>> statistics.variance(dados)\n" +"1.3720238095238095" + #: ../../tutorial/stdlib.rst:173 msgid "" "The SciPy project has many other modules for numerical " @@ -213,6 +386,48 @@ msgstr "" "dados a partir de URLs e :mod:`smtplib` para enviar mensagens de correio " "eletrônico::" +#: ../../tutorial/stdlib.rst:185 +msgid "" +">>> from urllib.request import urlopen\n" +">>> with urlopen('http://worldtimeapi.org/api/timezone/etc/UTC.txt') as " +"response:\n" +"... for line in response:\n" +"... line = line.decode() # Convert bytes to a str\n" +"... if line.startswith('datetime'):\n" +"... print(line.rstrip()) # Remove trailing newline\n" +"...\n" +"datetime: 2022-01-01T01:36:47.689215+00:00\n" +"\n" +">>> import smtplib\n" +">>> server = smtplib.SMTP('localhost')\n" +">>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',\n" +"... \"\"\"To: jcaesar@example.org\n" +"... From: soothsayer@example.org\n" +"...\n" +"... Beware the Ides of March.\n" +"... \"\"\")\n" +">>> server.quit()" +msgstr "" +">>> from urllib.request import urlopen\n" +">>> with urlopen('http://worldtimeapi.org/api/timezone/etc/UTC.txt') as " +"response:\n" +"... for line in response:\n" +"... line = line.decode() # Converte bytes para str\n" +"... if line.startswith('datetime'):\n" +"... print(line.rstrip()) # Remove nova linha ao final\n" +"...\n" +"datetime: 2022-01-01T01:36:47.689215+00:00\n" +"\n" +">>> import smtplib\n" +">>> server = smtplib.SMTP('localhost')\n" +">>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',\n" +"... \"\"\"To: jcaesar@example.org\n" +"... From: soothsayer@example.org\n" +"...\n" +"... Beware the Ides of March.\n" +"... \"\"\")\n" +">>> server.quit()" + #: ../../tutorial/stdlib.rst:204 msgid "(Note that the second example needs a mailserver running on localhost.)" msgstr "" @@ -237,6 +452,36 @@ msgstr "" "formatação e manipulação. O módulo também oferece objetos que levam os fusos " "horários em consideração. ::" +#: ../../tutorial/stdlib.rst:218 +msgid "" +">>> # dates are easily constructed and formatted\n" +">>> from datetime import date\n" +">>> now = date.today()\n" +">>> now\n" +"datetime.date(2003, 12, 2)\n" +">>> now.strftime(\"%m-%d-%y. %d %b %Y is a %A on the %d day of %B.\")\n" +"'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'\n" +"\n" +">>> # dates support calendar arithmetic\n" +">>> birthday = date(1964, 7, 31)\n" +">>> age = now - birthday\n" +">>> age.days\n" +"14368" +msgstr "" +">>> # datas são facilmente construídas e formatadas\n" +">>> from datetime import date\n" +">>> now = date.today()\n" +">>> now\n" +"datetime.date(2003, 12, 2)\n" +">>> now.strftime(\"%m-%d-%y. %d %b %Y is a %A on the %d day of %B.\")\n" +"'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'\n" +"\n" +">>> # datas têm suporte a matemática de calendário\n" +">>> birthday = date(1964, 7, 31)\n" +">>> age = now - birthday\n" +">>> age.days\n" +"14368" + #: ../../tutorial/stdlib.rst:236 msgid "Data Compression" msgstr "Compressão de dados" @@ -251,6 +496,32 @@ msgstr "" "diretamente através de alguns módulos, entre eles: :mod:`zlib`, :mod:" "`gzip`, :mod:`bz2`, :mod:`lzma`, :mod:`zipfile` and :mod:`tarfile`. ::" +#: ../../tutorial/stdlib.rst:242 +msgid "" +">>> import zlib\n" +">>> s = b'witch which has which witches wrist watch'\n" +">>> len(s)\n" +"41\n" +">>> t = zlib.compress(s)\n" +">>> len(t)\n" +"37\n" +">>> zlib.decompress(t)\n" +"b'witch which has which witches wrist watch'\n" +">>> zlib.crc32(s)\n" +"226805979" +msgstr "" +">>> import zlib\n" +">>> s = b'A vaca malhada foi molhada por outra vaca molhada e malhada.'\n" +">>> len(s)\n" +"60\n" +">>> t = zlib.compress(s)\n" +">>> len(t)\n" +"47\n" +">>> zlib.decompress(t)\n" +"b'A vaca malhada foi molhada por outra vaca molhada e malhada.'\n" +">>> zlib.crc32(s)\n" +"2444551089" + #: ../../tutorial/stdlib.rst:258 msgid "Performance Measurement" msgstr "Medição de desempenho" @@ -275,6 +546,20 @@ msgstr "" "tuplas ao invés da abordagem tradicional de permutar os argumentos. O " "módulo :mod:`timeit` rapidamente mostra uma modesta vantagem de desempenho::" +#: ../../tutorial/stdlib.rst:268 +msgid "" +">>> from timeit import Timer\n" +">>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()\n" +"0.57535828626024577\n" +">>> Timer('a,b = b,a', 'a=1; b=2').timeit()\n" +"0.54962537085770791" +msgstr "" +">>> from timeit import Timer\n" +">>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()\n" +"0.57535828626024577\n" +">>> Timer('a,b = b,a', 'a=1; b=2').timeit()\n" +"0.54962537085770791" + #: ../../tutorial/stdlib.rst:274 msgid "" "In contrast to :mod:`timeit`'s fine level of granularity, the :mod:`profile` " @@ -316,6 +601,30 @@ msgstr "" "real, e permite que o módulo doctest verifique se o código continua fiel à " "documentação::" +#: ../../tutorial/stdlib.rst:295 +msgid "" +"def average(values):\n" +" \"\"\"Computes the arithmetic mean of a list of numbers.\n" +"\n" +" >>> print(average([20, 30, 70]))\n" +" 40.0\n" +" \"\"\"\n" +" return sum(values) / len(values)\n" +"\n" +"import doctest\n" +"doctest.testmod() # automatically validate the embedded tests" +msgstr "" +"def average(values):\n" +" \"\"\"Calcula a média aritmética da lista de números.\n" +"\n" +" >>> print(average([20, 30, 70]))\n" +" 40.0\n" +" \"\"\"\n" +" return sum(values) / len(values)\n" +"\n" +"import doctest\n" +"doctest.testmod() # valida automaticamente os testes incorporados" + #: ../../tutorial/stdlib.rst:306 msgid "" "The :mod:`unittest` module is not as effortless as the :mod:`doctest` " @@ -326,6 +635,36 @@ msgstr "" "`doctest`, mas permite que um conjunto muito maior de testes seja mantido em " "um arquivo separado::" +#: ../../tutorial/stdlib.rst:310 +msgid "" +"import unittest\n" +"\n" +"class TestStatisticalFunctions(unittest.TestCase):\n" +"\n" +" def test_average(self):\n" +" self.assertEqual(average([20, 30, 70]), 40.0)\n" +" self.assertEqual(round(average([1, 5, 7]), 1), 4.3)\n" +" with self.assertRaises(ZeroDivisionError):\n" +" average([])\n" +" with self.assertRaises(TypeError):\n" +" average(20, 30, 70)\n" +"\n" +"unittest.main() # Calling from the command line invokes all tests" +msgstr "" +"import unittest\n" +"\n" +"class TestStatisticalFunctions(unittest.TestCase):\n" +"\n" +" def test_average(self):\n" +" self.assertEqual(average([20, 30, 70]), 40.0)\n" +" self.assertEqual(round(average([1, 5, 7]), 1), 4.3)\n" +" with self.assertRaises(ZeroDivisionError):\n" +" average([])\n" +" with self.assertRaises(TypeError):\n" +" average(20, 30, 70)\n" +"\n" +"unittest.main() # Chamar a partir da linha de comando invoca todos os testes" + #: ../../tutorial/stdlib.rst:328 msgid "Batteries Included" msgstr "Baterias incluídas" diff --git a/tutorial/stdlib2.po b/tutorial/stdlib2.po index cde11705b..7c6ee4fbd 100644 --- a/tutorial/stdlib2.po +++ b/tutorial/stdlib2.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-20 00:52+0000\n" -"PO-Revision-Date: 2021-06-28 01:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -49,6 +48,16 @@ msgstr "" "O módulo :mod:`reprlib` fornece uma versão de :func:`repr` personalizado " "para exibições abreviadas de contêineres grandes ou profundamente aninhados::" +#: ../../tutorial/stdlib2.rst:19 +msgid "" +">>> import reprlib\n" +">>> reprlib.repr(set('supercalifragilisticexpialidocious'))\n" +"\"{'a', 'c', 'd', 'e', 'f', 'g', ...}\"" +msgstr "" +">>> import reprlib\n" +">>> reprlib.repr(set('supercalifragilisticexpialidoce'))\n" +"\"{'a', 'c', 'd', 'e', 'f', 'g', ...}\"" + #: ../../tutorial/stdlib2.rst:23 msgid "" "The :mod:`pprint` module offers more sophisticated control over printing " @@ -62,6 +71,31 @@ msgstr "" "linha, o \"pretty printer\" acrescenta quebras de linha e indentação para " "revelar as estruturas de maneira mais clara::" +#: ../../tutorial/stdlib2.rst:28 +msgid "" +">>> import pprint\n" +">>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',\n" +"... 'yellow'], 'blue']]]\n" +"...\n" +">>> pprint.pprint(t, width=30)\n" +"[[[['black', 'cyan'],\n" +" 'white',\n" +" ['green', 'red']],\n" +" [['magenta', 'yellow'],\n" +" 'blue']]]" +msgstr "" +">>> import pprint\n" +">>> t = [[[['preto', 'ciano'], 'branco', ['verde', 'vermelho']], " +"[['magenta',\n" +"... 'amarelo'], 'azul']]]\n" +">>>\n" +">>> pprint.pprint(t, width=30)\n" +"[[[['preto', 'ciano'],\n" +" 'branco',\n" +" ['verde', 'vermelho']],\n" +" [['magenta', 'amarelo'],\n" +" 'azul']]]" + #: ../../tutorial/stdlib2.rst:39 msgid "" "The :mod:`textwrap` module formats paragraphs of text to fit a given screen " @@ -70,6 +104,31 @@ msgstr "" "O módulo :mod:`textwrap` formata parágrafos de texto para que caibam em uma " "dada largura de tela::" +#: ../../tutorial/stdlib2.rst:42 +msgid "" +">>> import textwrap\n" +">>> doc = \"\"\"The wrap() method is just like fill() except that it " +"returns\n" +"... a list of strings instead of one big string with newlines to separate\n" +"... the wrapped lines.\"\"\"\n" +"...\n" +">>> print(textwrap.fill(doc, width=40))\n" +"The wrap() method is just like fill()\n" +"except that it returns a list of strings\n" +"instead of one big string with newlines\n" +"to separate the wrapped lines." +msgstr "" +">>> import textwrap\n" +">>> doc = \"\"\"O método wrap() é como fill(), exceto que ele retorna\n" +"... uma lista de strings em vez de uma string grande com quebras\n" +"... de linha para separar as linhas quebradas.\"\"\"\n" +"...\n" +">>> print(textwrap.fill(doc, width=40))\n" +"O método wrap() é como fill(), exceto\n" +"que ele retorna uma lista de strings em\n" +"vez de uma string grande com quebras de\n" +"linha para separar as linhas quebradas." + #: ../../tutorial/stdlib2.rst:53 msgid "" "The :mod:`locale` module accesses a database of culture specific data " @@ -80,6 +139,30 @@ msgstr "" "determinada cultura. O atributo de agrupamento da função \"format\" oferece " "uma forma direta de formatar números com separadores de grupo::" +#: ../../tutorial/stdlib2.rst:57 +msgid "" +">>> import locale\n" +">>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')\n" +"'English_United States.1252'\n" +">>> conv = locale.localeconv() # get a mapping of conventions\n" +">>> x = 1234567.8\n" +">>> locale.format_string(\"%d\", x, grouping=True)\n" +"'1,234,567'\n" +">>> locale.format_string(\"%s%.*f\", (conv['currency_symbol'],\n" +"... conv['frac_digits'], x), grouping=True)\n" +"'$1,234,567.80'" +msgstr "" +">>> import locale\n" +">>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')\n" +"'English_United States.1252'\n" +">>> conv = locale.localeconv() # obtém mapeamento de convenções\n" +">>> x = 1234567.8\n" +">>> locale.format_string(\"%d\", x, grouping=True)\n" +"'1,234,567'\n" +">>> locale.format_string(\"%s%.*f\", (conv['currency_symbol'],\n" +"... conv['frac_digits'], x), grouping=True)\n" +"'$1,234,567.80'" + #: ../../tutorial/stdlib2.rst:72 msgid "Templating" msgstr "Usando templates" @@ -111,6 +194,18 @@ msgstr "" "seguido por mais caracteres alfanuméricos sem a necessidade de espaços. " "Escrevendo-se ``$$`` cria-se um único ``$``::" +#: ../../tutorial/stdlib2.rst:83 +msgid "" +">>> from string import Template\n" +">>> t = Template('${village}folk send $$10 to $cause.')\n" +">>> t.substitute(village='Nottingham', cause='the ditch fund')\n" +"'Nottinghamfolk send $10 to the ditch fund.'" +msgstr "" +">>> from string import Template\n" +">>> t = Template('O povo de ${vila} envia $$10 para $causa.')\n" +">>> t.substitute(vila='Nottingham', causa='o fundo de recuperação')\n" +"'O povo de Nottingham envia $10 para o fundo de recuperação.'" + #: ../../tutorial/stdlib2.rst:88 msgid "" "The :meth:`~string.Template.substitute` method raises a :exc:`KeyError` when " @@ -126,6 +221,26 @@ msgstr "" "pode ser mais apropriado --- deixará os marcadores intactos se os dados " "estiverem faltando::" +#: ../../tutorial/stdlib2.rst:94 +msgid "" +">>> t = Template('Return the $item to $owner.')\n" +">>> d = dict(item='unladen swallow')\n" +">>> t.substitute(d)\n" +"Traceback (most recent call last):\n" +" ...\n" +"KeyError: 'owner'\n" +">>> t.safe_substitute(d)\n" +"'Return the unladen swallow to $owner.'" +msgstr "" +">>> t = Template('Devolva $item para $dono.')\n" +">>> d = dict(item='a andorinha descarregada')\n" +">>> t.substitute(d)\n" +"Traceback (most recent call last):\n" +" ...\n" +"KeyError: 'dono'\n" +">>> t.safe_substitute(d)\n" +"'Devolva a andorinha descarregada para $dono.'" + #: ../../tutorial/stdlib2.rst:103 msgid "" "Template subclasses can specify a custom delimiter. For example, a batch " @@ -138,6 +253,48 @@ msgstr "" "porcentagem para marcações como a data atual, número sequencial da imagem ou " "formato do aquivo::" +#: ../../tutorial/stdlib2.rst:107 +msgid "" +">>> import time, os.path\n" +">>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']\n" +">>> class BatchRename(Template):\n" +"... delimiter = '%'\n" +"...\n" +">>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ')\n" +"Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f\n" +"\n" +">>> t = BatchRename(fmt)\n" +">>> date = time.strftime('%d%b%y')\n" +">>> for i, filename in enumerate(photofiles):\n" +"... base, ext = os.path.splitext(filename)\n" +"... newname = t.substitute(d=date, n=i, f=ext)\n" +"... print('{0} --> {1}'.format(filename, newname))\n" +"\n" +"img_1074.jpg --> Ashley_0.jpg\n" +"img_1076.jpg --> Ashley_1.jpg\n" +"img_1077.jpg --> Ashley_2.jpg" +msgstr "" +">>> import time, os.path\n" +">>> arquivos_fotos = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']\n" +">>> class RenomeiaEmLote(Template):\n" +"... delimiter = '%'\n" +"...\n" +">>> formato = input('Informe o estilo de renomeação (%d-data %n-sequencia %f-" +"formato): ')\n" +"Informe o estilo de renomeação (%d-data %n-sequencia %f-formato): " +"Ashley_%n%f\n" +"\n" +">>> t = RenomeiaEmLote(formato)\n" +">>> data = time.strftime('%d%b%y')\n" +">>> for i, nome_arquivo in enumerate(arquivos_fotos):\n" +"... base, extensão = os.path.splitext(nome_arquivo)\n" +"... novo_nome = t.substitute(d=data, n=i, f=extensão)\n" +"... print('{0} --> {1}'.format(nome_arquivo, novo_nome))\n" +"\n" +"img_1074.jpg --> Ashley_0.jpg\n" +"img_1076.jpg --> Ashley_1.jpg\n" +"img_1077.jpg --> Ashley_2.jpg" + #: ../../tutorial/stdlib2.rst:126 msgid "" "Another application for templating is separating program logic from the " @@ -171,6 +328,50 @@ msgstr "" "respectivamente. O ``\"<\"`` indica que os números têm tamanho padrão e são " "little-endian (bytes menos significativos primeiro)::" +#: ../../tutorial/stdlib2.rst:144 +msgid "" +"import struct\n" +"\n" +"with open('myfile.zip', 'rb') as f:\n" +" data = f.read()\n" +"\n" +"start = 0\n" +"for i in range(3): # show the first 3 file headers\n" +" start += 14\n" +" fields = struct.unpack('` " -"[coleta de lixo] para eliminar ciclos). A memória ocupada por um objeto é " -"liberada logo depois da última referência a ele ser eliminada." +"a maioria dos objetos e :term:`coleta de lixo ` para " +"eliminar ciclos). A memória ocupada por um objeto é liberada logo depois da " +"última referência a ele ser eliminada." #: ../../tutorial/stdlib2.rst:255 msgid "" @@ -307,7 +582,55 @@ msgstr "" "para rastrear objetos sem criar uma referência. Quando o objeto não é mais " "necessário, ele é automaticamente removido de uma tabela de referências " "fracas e uma chamada (*callback*) é disparada. Aplicações típicas incluem " -"cacheamento de objetos que são muito custosos para criar::" +"armazenamento em cache de objetos que são muito custosos para criar::" + +#: ../../tutorial/stdlib2.rst:263 +msgid "" +">>> import weakref, gc\n" +">>> class A:\n" +"... def __init__(self, value):\n" +"... self.value = value\n" +"... def __repr__(self):\n" +"... return str(self.value)\n" +"...\n" +">>> a = A(10) # create a reference\n" +">>> d = weakref.WeakValueDictionary()\n" +">>> d['primary'] = a # does not create a reference\n" +">>> d['primary'] # fetch the object if it is still alive\n" +"10\n" +">>> del a # remove the one reference\n" +">>> gc.collect() # run garbage collection right away\n" +"0\n" +">>> d['primary'] # entry was automatically removed\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" d['primary'] # entry was automatically removed\n" +" File \"C:/python313/lib/weakref.py\", line 46, in __getitem__\n" +" o = self.data[key]()\n" +"KeyError: 'primary'" +msgstr "" +">>> import weakref, gc\n" +">>> class A:\n" +"... def __init__(self, valor):\n" +"... self.valor = valor\n" +"... def __repr__(self):\n" +"... return str(self.valor)\n" +"...\n" +">>> a = A(10) # cria uma referência\n" +">>> d = weakref.WeakValueDictionary()\n" +">>> d['primaria'] = a # não cria uma referência\n" +">>> d['primaria'] # busca o objeto se ele estiver ativo\n" +"10\n" +">>> del a # remove a referência criada\n" +">>> gc.collect() # roda imediatamente a coleta de lixo\n" +"0\n" +">>> d['primaria'] # o acesso foi automaticamente removido\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" d['primaria'] # o acesso foi automaticamente removido\n" +" File \"C:/python313/lib/weakref.py\", line 46, in __getitem__\n" +" o = self.data[key]()\n" +"KeyError: 'primaria'" #: ../../tutorial/stdlib2.rst:290 msgid "Tools for Working with Lists" @@ -338,6 +661,22 @@ msgstr "" "números binários de dois bytes sem sinal (código de tipo ``\"H\"``) ao invés " "dos 16 bytes usuais para cada item em uma lista de ``int``::" +#: ../../tutorial/stdlib2.rst:302 +msgid "" +">>> from array import array\n" +">>> a = array('H', [4000, 10, 700, 22222])\n" +">>> sum(a)\n" +"26932\n" +">>> a[1:3]\n" +"array('H', [10, 700])" +msgstr "" +">>> from array import array\n" +">>> a = array('H', [4000, 10, 700, 22222])\n" +">>> sum(a)\n" +"26932\n" +">>> a[1:3]\n" +"array('H', [10, 700])" + #: ../../tutorial/stdlib2.rst:309 msgid "" "The :mod:`collections` module provides a :class:`~collections.deque` object " @@ -348,8 +687,40 @@ msgstr "" "O módulo :mod:`collections` oferece um objeto :class:`~collections.deque` " "que comporta-se como uma lista mas com *appends* e *pops* pela esquerda mais " "rápidos, porém mais lento ao percorrer o meio da sequência. Esses objetos " -"são adequados para implementar filas e buscas de amplitude em árvores de " -"dados (*breadth first tree searches*)::" +"são adequados para implementar filas e buscas em amplitude em árvores de " +"dados::" + +#: ../../tutorial/stdlib2.rst:314 +msgid "" +">>> from collections import deque\n" +">>> d = deque([\"task1\", \"task2\", \"task3\"])\n" +">>> d.append(\"task4\")\n" +">>> print(\"Handling\", d.popleft())\n" +"Handling task1" +msgstr "" +">>> from collections import deque\n" +">>> d = deque([\"tarefa1\", \"tarefa2\", \"tarefa3\"])\n" +">>> d.append(\"tarefa4\")\n" +">>> print(\"Tratando\", d.popleft())\n" +"Tratando tarefa1" + +#: ../../tutorial/stdlib2.rst:322 +msgid "" +"unsearched = deque([starting_node])\n" +"def breadth_first_search(unsearched):\n" +" node = unsearched.popleft()\n" +" for m in gen_moves(node):\n" +" if is_goal(m):\n" +" return m\n" +" unsearched.append(m)" +msgstr "" +"nao_pesquisada = deque([no_inicial])\n" +"def busca_em_profundidade(nao_pesquisada):\n" +" no = nao_pesquisada.popleft()\n" +" for m in gen_moves(no):\n" +" if eh_o_alvo(m):\n" +" return m\n" +" nao_pesquisada.append(m)" #: ../../tutorial/stdlib2.rst:330 msgid "" @@ -361,6 +732,20 @@ msgstr "" "outras ferramentas como o módulo :mod:`bisect` com funções para manipulação " "de listas ordenadas::" +#: ../../tutorial/stdlib2.rst:334 +msgid "" +">>> import bisect\n" +">>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]\n" +">>> bisect.insort(scores, (300, 'ruby'))\n" +">>> scores\n" +"[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]" +msgstr "" +">>> import bisect\n" +">>> notas = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]\n" +">>> bisect.insort(notas, (300, 'ruby'))\n" +">>> notas\n" +"[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]" + #: ../../tutorial/stdlib2.rst:340 msgid "" "The :mod:`heapq` module provides functions for implementing heaps based on " @@ -373,6 +758,22 @@ msgstr "" "é útil para aplicações que acessam repetidamente o menor elemento, mas não " "querem reordenar a lista toda a cada acesso::" +#: ../../tutorial/stdlib2.rst:345 +msgid "" +">>> from heapq import heapify, heappop, heappush\n" +">>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]\n" +">>> heapify(data) # rearrange the list into heap order\n" +">>> heappush(data, -5) # add a new entry\n" +">>> [heappop(data) for i in range(3)] # fetch the three smallest entries\n" +"[-5, 0, 1]" +msgstr "" +">>> from heapq import heapify, heappop, heappush\n" +">>> dados = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]\n" +">>> heapify(dados) # reorganiza a lista como um heap\n" +">>> heappush(dados, -5) # adiciona o valor -5 ao heap\n" +">>> [heappop(dados) for i in range(3)] # encontra as 3 menores entradas\n" +"[-5, 0, 1]" + #: ../../tutorial/stdlib2.rst:356 msgid "Decimal Floating-Point Arithmetic" msgstr "Aritmética decimal com ponto flutuante" @@ -425,6 +826,20 @@ msgstr "" "decimal ou binária. A diferença torna-se significativa se os resultados são " "arredondados para o centavo mais próximo::" +#: ../../tutorial/stdlib2.rst:374 +msgid "" +">>> from decimal import *\n" +">>> round(Decimal('0.70') * Decimal('1.05'), 2)\n" +"Decimal('0.74')\n" +">>> round(.70 * 1.05, 2)\n" +"0.73" +msgstr "" +">>> from decimal import *\n" +">>> round(Decimal('0.70') * Decimal('1.05'), 2)\n" +"Decimal('0.74')\n" +">>> round(.70 * 1.05, 2)\n" +"0.73" + #: ../../tutorial/stdlib2.rst:380 msgid "" "The :class:`~decimal.Decimal` result keeps a trailing zero, automatically " @@ -449,6 +864,28 @@ msgstr "" "cálculos de módulo e testes de igualdade que não funcionam bem em ponto " "flutuante binário::" +#: ../../tutorial/stdlib2.rst:390 +msgid "" +">>> Decimal('1.00') % Decimal('.10')\n" +"Decimal('0.00')\n" +">>> 1.00 % 0.10\n" +"0.09999999999999995\n" +"\n" +">>> sum([Decimal('0.1')]*10) == Decimal('1.0')\n" +"True\n" +">>> 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1.0\n" +"False" +msgstr "" +">>> Decimal('1.00') % Decimal('.10')\n" +"Decimal('0.00')\n" +">>> 1.00 % 0.10\n" +"0.09999999999999995\n" +"\n" +">>> sum([Decimal('0.1')]*10) == Decimal('1.0')\n" +"True\n" +">>> 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1.0\n" +"False" + #: ../../tutorial/stdlib2.rst:400 msgid "" "The :mod:`decimal` module provides arithmetic with as much precision as " @@ -456,3 +893,13 @@ msgid "" msgstr "" "O módulo :mod:`decimal` implementa a aritmética com tanta precisão quanto " "necessária::" + +#: ../../tutorial/stdlib2.rst:402 +msgid "" +">>> getcontext().prec = 36\n" +">>> Decimal(1) / Decimal(7)\n" +"Decimal('0.142857142857142857142857142857142857')" +msgstr "" +">>> getcontext().prec = 36\n" +">>> Decimal(1) / Decimal(7)\n" +"Decimal('0.142857142857142857142857142857142857')" diff --git a/tutorial/venv.po b/tutorial/venv.po index 42520c613..cc51c5b3a 100644 --- a/tutorial/venv.po +++ b/tutorial/venv.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Ruan Aragão , 2021 -# Leticia Portella , 2021 -# Adorilson Bezerra , 2021 -# Hildeberto Abreu Magalhães , 2021 -# Fabio Santos , 2022 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-31 14:14+0000\n" -"PO-Revision-Date: 2021-06-28 01:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -115,6 +110,10 @@ msgstr "" "Para criar um ambiente virtual, escolha um diretório onde deseja colocá-lo e " "execute o módulo :mod:`venv` como um script com o caminho do diretório::" +#: ../../tutorial/venv.rst:47 +msgid "python -m venv tutorial-env" +msgstr "python -m venv tutorial-env" + #: ../../tutorial/venv.rst:49 msgid "" "This will create the ``tutorial-env`` directory if it doesn't exist, and " @@ -147,10 +146,18 @@ msgstr "Uma vez criado seu ambiente virtual, você deve ativá-lo." msgid "On Windows, run::" msgstr "No Windows, execute::" +#: ../../tutorial/venv.rst:63 +msgid "tutorial-env\\Scripts\\activate" +msgstr "tutorial-env\\Scripts\\activate" + #: ../../tutorial/venv.rst:65 msgid "On Unix or MacOS, run::" msgstr "No Unix ou no MacOS, executa::" +#: ../../tutorial/venv.rst:67 +msgid "source tutorial-env/bin/activate" +msgstr "source tutorial-env/bin/activate" + #: ../../tutorial/venv.rst:69 msgid "" "(This script is written for the bash shell. If you use the :program:`csh` " @@ -173,10 +180,36 @@ msgstr "" "que quando você executar ``python`` ativar a versão e instalação do Python " "particular àquele ambiente. Por exemplo:" +#: ../../tutorial/venv.rst:79 +msgid "" +"$ source ~/envs/tutorial-env/bin/activate\n" +"(tutorial-env) $ python\n" +"Python 3.5.1 (default, May 6 2016, 10:59:36)\n" +" ...\n" +">>> import sys\n" +">>> sys.path\n" +"['', '/usr/local/lib/python35.zip', ...,\n" +"'~/envs/tutorial-env/lib/python3.5/site-packages']\n" +">>>" +msgstr "" +"$ source ~/envs/tutorial-env/bin/activate\n" +"(tutorial-env) $ python\n" +"Python 3.5.1 (default, May 6 2016, 10:59:36)\n" +" ...\n" +">>> import sys\n" +">>> sys.path\n" +"['', '/usr/local/lib/python35.zip', ...,\n" +"'~/envs/tutorial-env/lib/python3.5/site-packages']\n" +">>>" + #: ../../tutorial/venv.rst:91 msgid "To deactivate a virtual environment, type::" msgstr "Para desativar um ambiente virtual, digite::" +#: ../../tutorial/venv.rst:93 +msgid "deactivate" +msgstr "deactivate" + #: ../../tutorial/venv.rst:95 msgid "into the terminal." msgstr "no terminal." @@ -215,6 +248,22 @@ msgstr "" "Você pode instalar a última versão de um pacote apenas especificando nome do " "pacote:" +#: ../../tutorial/venv.rst:111 +msgid "" +"(tutorial-env) $ python -m pip install novas\n" +"Collecting novas\n" +" Downloading novas-3.1.1.3.tar.gz (136kB)\n" +"Installing collected packages: novas\n" +" Running setup.py install for novas\n" +"Successfully installed novas-3.1.1.3" +msgstr "" +"(tutorial-env) $ python -m pip install novas\n" +"Collecting novas\n" +" Downloading novas-3.1.1.3.tar.gz (136kB)\n" +"Installing collected packages: novas\n" +" Running setup.py install for novas\n" +"Successfully installed novas-3.1.1.3" + #: ../../tutorial/venv.rst:120 msgid "" "You can also install a specific version of a package by giving the package " @@ -223,6 +272,20 @@ msgstr "" "Você também pode instalar uma versão específica de um pacote dando o nome do " "pacote seguido por ``==`` e o número da versão:" +#: ../../tutorial/venv.rst:123 +msgid "" +"(tutorial-env) $ python -m pip install requests==2.6.0\n" +"Collecting requests==2.6.0\n" +" Using cached requests-2.6.0-py2.py3-none-any.whl\n" +"Installing collected packages: requests\n" +"Successfully installed requests-2.6.0" +msgstr "" +"(tutorial-env) $ python -m pip install requests==2.6.0\n" +"Collecting requests==2.6.0\n" +" Using cached requests-2.6.0-py2.py3-none-any.whl\n" +"Installing collected packages: requests\n" +"Successfully installed requests-2.6.0" + #: ../../tutorial/venv.rst:131 msgid "" "If you re-run this command, ``pip`` will notice that the requested version " @@ -235,6 +298,24 @@ msgstr "" "versão diferente para obter essa versão ou pode executar ``python -m pip " "install --upgrade`` para atualizar o pacote para a versão mais recente:" +#: ../../tutorial/venv.rst:136 +msgid "" +"(tutorial-env) $ python -m pip install --upgrade requests\n" +"Collecting requests\n" +"Installing collected packages: requests\n" +" Found existing installation: requests 2.6.0\n" +" Uninstalling requests-2.6.0:\n" +" Successfully uninstalled requests-2.6.0\n" +"Successfully installed requests-2.7.0" +msgstr "" +"(tutorial-env) $ python -m pip install --upgrade requests\n" +"Collecting requests\n" +"Installing collected packages: requests\n" +" Found existing installation: requests 2.6.0\n" +" Uninstalling requests-2.6.0:\n" +" Successfully uninstalled requests-2.6.0\n" +"Successfully installed requests-2.7.0" + #: ../../tutorial/venv.rst:146 msgid "" "``python -m pip uninstall`` followed by one or more package names will " @@ -248,6 +329,34 @@ msgid "" "``python -m pip show`` will display information about a particular package:" msgstr "``python -m pip show`` exibirá informações sobre um pacote específico:" +#: ../../tutorial/venv.rst:151 +msgid "" +"(tutorial-env) $ python -m pip show requests\n" +"---\n" +"Metadata-Version: 2.0\n" +"Name: requests\n" +"Version: 2.7.0\n" +"Summary: Python HTTP for Humans.\n" +"Home-page: http://python-requests.org\n" +"Author: Kenneth Reitz\n" +"Author-email: me@kennethreitz.com\n" +"License: Apache 2.0\n" +"Location: /Users/akuchling/envs/tutorial-env/lib/python3.4/site-packages\n" +"Requires:" +msgstr "" +"(tutorial-env) $ python -m pip show requests\n" +"---\n" +"Metadata-Version: 2.0\n" +"Name: requests\n" +"Version: 2.7.0\n" +"Summary: Python HTTP for Humans.\n" +"Home-page: http://python-requests.org\n" +"Author: Kenneth Reitz\n" +"Author-email: me@kennethreitz.com\n" +"License: Apache 2.0\n" +"Location: /Users/akuchling/envs/tutorial-env/lib/python3.4/site-packages\n" +"Requires:" + #: ../../tutorial/venv.rst:166 msgid "" "``python -m pip list`` will display all of the packages installed in the " @@ -256,6 +365,22 @@ msgstr "" "``python -m pip list`` exibirá todos os pacotes instalados no ambiente " "virtual:" +#: ../../tutorial/venv.rst:169 +msgid "" +"(tutorial-env) $ python -m pip list\n" +"novas (3.1.1.3)\n" +"numpy (1.9.2)\n" +"pip (7.0.3)\n" +"requests (2.7.0)\n" +"setuptools (16.0)" +msgstr "" +"(tutorial-env) $ python -m pip list\n" +"novas (3.1.1.3)\n" +"numpy (1.9.2)\n" +"pip (7.0.3)\n" +"requests (2.7.0)\n" +"setuptools (16.0)" + #: ../../tutorial/venv.rst:178 msgid "" "``python -m pip freeze`` will produce a similar list of the installed " @@ -267,6 +392,20 @@ msgstr "" "instalados, mas a saída usa o formato que ``python -m pip install`` espera. " "Uma convenção comum é colocar esta lista em um arquivo ``requirements.txt``:" +#: ../../tutorial/venv.rst:182 +msgid "" +"(tutorial-env) $ python -m pip freeze > requirements.txt\n" +"(tutorial-env) $ cat requirements.txt\n" +"novas==3.1.1.3\n" +"numpy==1.9.2\n" +"requests==2.7.0" +msgstr "" +"(tutorial-env) $ python -m pip freeze > requirements.txt\n" +"(tutorial-env) $ cat requirements.txt\n" +"novas==3.1.1.3\n" +"numpy==1.9.2\n" +"requests==2.7.0" + #: ../../tutorial/venv.rst:190 msgid "" "The ``requirements.txt`` can then be committed to version control and " @@ -277,6 +416,30 @@ msgstr "" "adicionado como parte da aplicação. Usuários poderão então instalar todos os " "pacotes necessários com um ``install -r``:" +#: ../../tutorial/venv.rst:194 +msgid "" +"(tutorial-env) $ python -m pip install -r requirements.txt\n" +"Collecting novas==3.1.1.3 (from -r requirements.txt (line 1))\n" +" ...\n" +"Collecting numpy==1.9.2 (from -r requirements.txt (line 2))\n" +" ...\n" +"Collecting requests==2.7.0 (from -r requirements.txt (line 3))\n" +" ...\n" +"Installing collected packages: novas, numpy, requests\n" +" Running setup.py install for novas\n" +"Successfully installed novas-3.1.1.3 numpy-1.9.2 requests-2.7.0" +msgstr "" +"(tutorial-env) $ python -m pip install -r requirements.txt\n" +"Collecting novas==3.1.1.3 (from -r requirements.txt (line 1))\n" +" ...\n" +"Collecting numpy==1.9.2 (from -r requirements.txt (line 2))\n" +" ...\n" +"Collecting requests==2.7.0 (from -r requirements.txt (line 3))\n" +" ...\n" +"Installing collected packages: novas, numpy, requests\n" +" Running setup.py install for novas\n" +"Successfully installed novas-3.1.1.3 numpy-1.9.2 requests-2.7.0" + #: ../../tutorial/venv.rst:207 msgid "" "``pip`` has many more options. Consult the :ref:`installing-index` guide " diff --git a/tutorial/whatnow.po b/tutorial/whatnow.po index 7a94cf03c..5a5eb8c8b 100644 --- a/tutorial/whatnow.po +++ b/tutorial/whatnow.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Otávio Carneiro , 2021 -# Adorilson Bezerra , 2022 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 01:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -179,10 +176,10 @@ msgid "" "questions that come up again and again, and may already contain the solution " "for your problem." msgstr "" -"Antes de postar, certifique-se de checar a lista de Perguntas Frequentes (:" -"ref:`Frequently Asked Questions ` , também chamada de FAQ). A FAQ " -"responde muitas das perguntas que aparecem com frequência e pode já conter a " -"solução para o seu problema." +"Antes de postar, certifique-se de checar a lista de :ref:`perguntas " +"frequentes ` (também chamada de FAQ). O FAQ responde muitas das " +"perguntas que aparecem com frequência e pode já conter a solução para o seu " +"problema." #: ../../tutorial/whatnow.rst:70 msgid "Footnotes" diff --git a/using/android.po b/using/android.po new file mode 100644 index 000000000..72f999485 --- /dev/null +++ b/using/android.po @@ -0,0 +1,186 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2025, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +# Translators: +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-04-04 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_BR/)\n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../using/android.rst:5 +msgid "Using Python on Android" +msgstr "Utilizando Python no Android" + +#: ../../using/android.rst:7 +msgid "" +"Python on Android is unlike Python on desktop platforms. On a desktop " +"platform, Python is generally installed as a system resource that can be " +"used by any user of that computer. Users then interact with Python by " +"running a :program:`python` executable and entering commands at an " +"interactive prompt, or by running a Python script." +msgstr "" +"Python no Android é diferente do Python em plataformas de desktop. Em uma " +"plataforma desktop, o Python geralmente é instalado como um recurso do " +"sistema que pode ser usado por qualquer usuário daquele computador. Os " +"usuários então interagem com o Python executando um executável :program:" +"`python` e inserindo comandos em um prompt interativo ou executando um " +"script Python." + +#: ../../using/android.rst:13 +msgid "" +"On Android, there is no concept of installing as a system resource. The only " +"unit of software distribution is an \"app\". There is also no console where " +"you could run a :program:`python` executable, or interact with a Python REPL." +msgstr "" +"No Android, não existe o conceito de instalação como recurso do sistema. A " +"única unidade de distribuição de software é uma aplicação, ou \"app\". " +"Também não há console onde você possa executar um executável :program:" +"`python` ou interagir com um REPL do Python." + +#: ../../using/android.rst:17 +msgid "" +"As a result, the only way you can use Python on Android is in embedded mode " +"– that is, by writing a native Android application, embedding a Python " +"interpreter using ``libpython``, and invoking Python code using the :ref:" +"`Python embedding API `. The full Python interpreter, the " +"standard library, and all your Python code is then packaged into your app " +"for its own private use." +msgstr "" +"Como resultado, a única maneira de usar Python no Andoid é no modo " +"incorporado – ou seja, escrevendo uma aplicação Android nativo, incorporando " +"um interpretador Python usando ``libpython`` e invocando o código Python " +"usando :ref:`API de incorporação do Python `. O interpretador " +"Python completo, a biblioteca padrão e todo o seu código Python são então " +"empacotados para sua aplicação para seu próprio uso privado." + +#: ../../using/android.rst:23 +msgid "" +"The Python standard library has some notable omissions and restrictions on " +"Android. See the :ref:`API availability guide ` for " +"details." +msgstr "" +"A biblioteca padrão do Python tem algumas omissões e restrições notáveis no " +"Andoid. Consulte o :ref:`guia de disponibilidade de API para Android ` para obter detalhes." + +#: ../../using/android.rst:28 +msgid "Adding Python to an Android app" +msgstr "Adicionando Python a uma aplicação Android" + +#: ../../using/android.rst:30 +msgid "" +"Most app developers should use one of the following tools, which will " +"provide a much easier experience:" +msgstr "" +"A maioria dos desenvolvedores de aplicações deve usar uma das seguintes " +"ferramentas, o que proporcionará uma experiência muito mais fácil:" + +#: ../../using/android.rst:33 +msgid "" +"`Briefcase `__, from the BeeWare project" +msgstr "`Briefcase `__, do projeto BeeWare" + +#: ../../using/android.rst:34 +msgid "`Buildozer `__, from the Kivy project" +msgstr "`Buildozer `__, do projeto Kivy" + +#: ../../using/android.rst:35 +msgid "`Chaquopy `__" +msgstr "`Chaquopy `__" + +#: ../../using/android.rst:36 +msgid "" +"`pyqtdeploy `__" +msgstr "" +"`pyqtdeploy `__" + +#: ../../using/android.rst:37 +msgid "`Termux `__" +msgstr "`Termux `__" + +#: ../../using/android.rst:39 +msgid "" +"If you're sure you want to do all of this manually, read on. You can use " +"the :source:`testbed app ` as a guide; each step below " +"contains a link to the relevant file." +msgstr "" +"Se você tem certeza de que quer fazer tudo isso manualmente, continue lendo. " +"Você pode usar a :source:`aplicação testbed ` como um guia; " +"cada passo abaixo contém um link para o arquivo relevante." + +#: ../../using/android.rst:43 +msgid "" +"Build Python by following the instructions in :source:`Android/README.md`. " +"This will create the directory ``cross-build/HOST/prefix``." +msgstr "" +"Construa o Python seguindo as instruções em :source:`Android/README.md`. " +"Isso vai criar o diretório ``cross-build/HOST/prefix``." + +#: ../../using/android.rst:46 +msgid "" +"Add code to your :source:`build.gradle ` file to copy the following items into your project. All except your " +"own Python code can be copied from ``prefix/lib``:" +msgstr "" +"Adicione código ao seu arquivo :source:`build.gradle ` para copiar os seguintes itens para o seu projeto. Todos, " +"exceto seu próprio código Python, podem ser copiados de ``prefix/lib``:" + +#: ../../using/android.rst:50 +msgid "In your JNI libraries:" +msgstr "Em suas bibliotecas JNI:" + +#: ../../using/android.rst:52 +msgid "``libpython*.*.so``" +msgstr "``libpython*.*.so``" + +#: ../../using/android.rst:53 +msgid "``lib*_python.so`` (external libraries such as OpenSSL)" +msgstr "``lib*_python.so`` (bibliotecas externas, tal como OpenSSL)" + +#: ../../using/android.rst:55 +msgid "In your assets:" +msgstr "Em seus ativos (*assets*):" + +#: ../../using/android.rst:57 +msgid "``python*.*`` (the Python standard library)" +msgstr "``python*.*`` (a biblioteca padrão do Python)" + +#: ../../using/android.rst:58 +msgid "``python*.*/site-packages`` (your own Python code)" +msgstr "``python*.*/site-packages`` (seu próprio código Python)" + +#: ../../using/android.rst:60 +msgid "" +"Add code to your app to :source:`extract the assets to the filesystem " +"`." +msgstr "" +"Adicione código ao seu aplicativo para :source:`extrair os ativos para o " +"sistema de arquivos `." + +#: ../../using/android.rst:63 +msgid "" +"Add code to your app to :source:`start Python in embedded mode `. This will need to be C code called " +"via JNI." +msgstr "" +"Adicione código a sua aplicação para :source:`iniciar o Python em modo " +"incorporado `. Isso " +"precisará ser código C chamado via JNI." diff --git a/using/cmdline.po b/using/cmdline.po index b9f49209a..692bd1fb9 100644 --- a/using/cmdline.po +++ b/using/cmdline.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Mariana Costa , 2021 -# a76d6fb6142d7607ab0526dcbddb02d7_7bf0da0 <3b5fb0f281c8dfb4c0170f2ee2a6cfcf_843623>, 2021 -# Hemílio Lauro , 2021 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-08 03:57+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -57,12 +52,24 @@ msgid "When invoking Python, you may specify any of these options::" msgstr "" "Ao invocar o Python, você pode especificar qualquer uma destas opções::" +#: ../../using/cmdline.rst:27 +msgid "" +"python [-bBdEhiIOPqRsSuvVWx?] [-c command | -m module-name | script | - ] " +"[args]" +msgstr "" +"python [-bBdEhiIOPqRsSuvVWx?] [-c comando | -m nome-módulo | script | - ] " +"[args]" + #: ../../using/cmdline.rst:29 msgid "" "The most common use case is, of course, a simple invocation of a script::" msgstr "" "O caso de uso mais comum é, obviamente, uma simples invocação de um script::" +#: ../../using/cmdline.rst:31 +msgid "python myscript.py" +msgstr "python meuscript.py" + #: ../../using/cmdline.rst:37 msgid "Interface options" msgstr "Opções de interface" @@ -250,6 +257,15 @@ msgstr "" "Muitos módulos de biblioteca padrão contêm código que é chamado em sua " "execução como um script. Um exemplo é o módulo :mod:`timeit`::" +#: ../../using/cmdline.rst:113 +msgid "" +"python -m timeit -s \"setup here\" \"benchmarked code here\"\n" +"python -m timeit -h # for details" +msgstr "" +"python -m timeit -s \"configuração inicial aqui\" \"código a ser analisado " +"aqui\"\n" +"python -m timeit -h # para detalhes" + #: ../../using/cmdline.rst:116 msgid "" "Raises an :ref:`auditing event ` ``cpython.run_module`` with " @@ -295,7 +311,7 @@ msgstr "" "Se esta opção for fornecida, o primeiro elemento de :data:`sys.argv` será " "``\"-\"`` e o diretório atual será adicionado ao início de :data:`sys.path`." -#: ../../using/cmdline.rst:141 ../../using/cmdline.rst:790 +#: ../../using/cmdline.rst:141 ../../using/cmdline.rst:796 msgid "" "Raises an :ref:`auditing event ` ``cpython.run_stdin`` with no " "arguments." @@ -423,11 +439,23 @@ msgid "Print the Python version number and exit. Example output could be:" msgstr "" "Exibe o número da versão do Python e saia. O exemplo de saída poderia ser:" +#: ../../using/cmdline.rst:224 +msgid "Python 3.8.0b2+" +msgstr "Python 3.8.0b2+" + #: ../../using/cmdline.rst:228 msgid "When given twice, print more information about the build, like:" msgstr "" "Quando fornecido duas vezes, exibe mais informações sobre a construção, como:" +#: ../../using/cmdline.rst:230 +msgid "" +"Python 3.8.0b2+ (3.8:0c076caaa8, Apr 20 2019, 21:55:00)\n" +"[GCC 6.2.0 20161005]" +msgstr "" +"Python 3.8.0b2+ (3.8:0c076caaa8, Apr 20 2019, 21:55:00)\n" +"[GCC 6.2.0 20161005]" + #: ../../using/cmdline.rst:235 msgid "The ``-VV`` option." msgstr "A opção ``-VV``." @@ -516,18 +544,38 @@ msgid "See also the :option:`-P` and :option:`-I` (isolated) options." msgstr "Veja também as opções :option:`-P` e :option:`-I` (isolado)." #: ../../using/cmdline.rst:293 +msgid "Enter interactive mode after execution." +msgstr "Entra no modo interativo após a execução." + +#: ../../using/cmdline.rst:295 msgid "" -"When a script is passed as first argument or the :option:`-c` option is " -"used, enter interactive mode after executing the script or the command, even " -"when :data:`sys.stdin` does not appear to be a terminal. The :envvar:" -"`PYTHONSTARTUP` file is not read." +"Using the :option:`-i` option will enter interactive mode in any of the " +"following circumstances\\:" msgstr "" -"Quando um script é passado como primeiro argumento ou a opção :option:`-c` é " -"usada, entre no modo interativo depois de executar o script ou o comando, " -"mesmo quando :data:`sys.stdin` não parece ser um terminal. O arquivo :envvar:" -"`PYTHONSTARTUP` não foi lido." +"Usanr a opção :option:`-i` vai entrar no modo interativo em qualquer uma das " +"circunstâncias\\:" + +#: ../../using/cmdline.rst:297 +msgid "When a script is passed as first argument" +msgstr "quando um script é passado como primeiro argumento" #: ../../using/cmdline.rst:298 +msgid "When the :option:`-c` option is used" +msgstr "quando a opção :option:`-c` é usada" + +#: ../../using/cmdline.rst:299 +msgid "When the :option:`-m` option is used" +msgstr "quando a opção :option:`-m` é usada" + +#: ../../using/cmdline.rst:301 +msgid "" +"Interactive mode will start even when :data:`sys.stdin` does not appear to " +"be a terminal. The :envvar:`PYTHONSTARTUP` file is not read." +msgstr "" +"O modo interativo vai ser iniciado mesmo quando a :data:`sys.stdin` não " +"parecer ser um terminal. O arquivo :envvar:`PYTHONSTARTUP` não é lido." + +#: ../../using/cmdline.rst:304 msgid "" "This can be useful to inspect global variables or a stack trace when a " "script raises an exception. See also :envvar:`PYTHONINSPECT`." @@ -536,7 +584,7 @@ msgstr "" "(situação da pilha de execução) quando um script levanta uma exceção. Veja " "também :envvar:`PYTHONINSPECT`." -#: ../../using/cmdline.rst:304 +#: ../../using/cmdline.rst:310 msgid "" "Run Python in isolated mode. This also implies :option:`-E`, :option:`-P` " "and :option:`-s` options." @@ -544,7 +592,7 @@ msgstr "" "Executa o Python no modo isolado. Isso também implica nas opções :option:`-" "E`, :option:`-P` e :option:`-s`." -#: ../../using/cmdline.rst:307 +#: ../../using/cmdline.rst:313 msgid "" "In isolated mode :data:`sys.path` contains neither the script's directory " "nor the user's site-packages directory. All ``PYTHON*`` environment " @@ -556,7 +604,7 @@ msgstr "" "``PYTHON*`` são ignoradas também. Outras restrições podem ser impostas para " "evitar que o usuário injete código malicioso." -#: ../../using/cmdline.rst:317 +#: ../../using/cmdline.rst:323 msgid "" "Remove assert statements and any code conditional on the value of :const:" "`__debug__`. Augment the filename for compiled (:term:`bytecode`) files by " @@ -568,11 +616,11 @@ msgstr "" "`bytecode`) adicionando ``.opt-1`` antes da extensão ``.pyc`` (veja :pep:" "`488`). Veja também :envvar:`PYTHONOPTIMIZE`." -#: ../../using/cmdline.rst:322 ../../using/cmdline.rst:332 +#: ../../using/cmdline.rst:328 ../../using/cmdline.rst:338 msgid "Modify ``.pyc`` filenames according to :pep:`488`." msgstr "Modifica nomes de arquivos ``.pyc`` conforme a :pep:`488`." -#: ../../using/cmdline.rst:328 +#: ../../using/cmdline.rst:334 msgid "" "Do :option:`-O` and also discard docstrings. Augment the filename for " "compiled (:term:`bytecode`) files by adding ``.opt-2`` before the ``.pyc`` " @@ -582,17 +630,17 @@ msgstr "" "arquivo para arquivos compilados (:term:`bytecode`) adicionando ``.opt-2`` " "antes da extensão ``.pyc`` (veja :pep:`488`)." -#: ../../using/cmdline.rst:338 +#: ../../using/cmdline.rst:344 msgid "Don't prepend a potentially unsafe path to :data:`sys.path`:" msgstr "Não anexa um caminho potencialmente inseguro a :data:`sys.path`:" -#: ../../using/cmdline.rst:340 +#: ../../using/cmdline.rst:346 msgid "" "``python -m module`` command line: Don't prepend the current working " "directory." msgstr "A linha de comando ``python -m módulo``: Não anexa o diretório atual." -#: ../../using/cmdline.rst:342 +#: ../../using/cmdline.rst:348 msgid "" "``python script.py`` command line: Don't prepend the script's directory. If " "it's a symbolic link, resolve symbolic links." @@ -600,7 +648,7 @@ msgstr "" "A linha de comando ``python script.py``: não anexa o diretório do script. Se " "for um link simbólico, resolve os links simbólicos." -#: ../../using/cmdline.rst:344 +#: ../../using/cmdline.rst:350 msgid "" "``python -c code`` and ``python`` (REPL) command lines: Don't prepend an " "empty string, which means the current working directory." @@ -608,7 +656,7 @@ msgstr "" "Linhas de comando ``python -c código`` e ``python`` (REPL): Não anexa uma " "string vazia, o que significa o diretório de trabalho atual." -#: ../../using/cmdline.rst:347 +#: ../../using/cmdline.rst:353 msgid "" "See also the :envvar:`PYTHONSAFEPATH` environment variable, and :option:`-E` " "and :option:`-I` (isolated) options." @@ -616,14 +664,14 @@ msgstr "" "Veja também a variável de ambiente :envvar:`PYTHONSAFEPATH` e as opções :" "option:`-E` e :option:`-I` (isolado)." -#: ../../using/cmdline.rst:355 +#: ../../using/cmdline.rst:361 msgid "" "Don't display the copyright and version messages even in interactive mode." msgstr "" "Não exibe as mensagens de direitos autorais e de versão nem mesmo no modo " "interativo." -#: ../../using/cmdline.rst:362 +#: ../../using/cmdline.rst:368 msgid "" "Turn on hash randomization. This option only has an effect if the :envvar:" "`PYTHONHASHSEED` environment variable is set to ``0``, since hash " @@ -633,7 +681,7 @@ msgstr "" "ambiente :envvar:`PYTHONHASHSEED` estiver configurada para ``0``, uma vez " "que a aleatorização com hash é habilitada por padrão." -#: ../../using/cmdline.rst:366 +#: ../../using/cmdline.rst:372 msgid "" "On previous versions of Python, this option turns on hash randomization, so " "that the :meth:`~object.__hash__` values of str and bytes objects are " @@ -647,7 +695,7 @@ msgstr "" "constantes em um processo Python individual, eles não são previsíveis entre " "invocações repetidas de Python." -#: ../../using/cmdline.rst:372 +#: ../../using/cmdline.rst:378 msgid "" "Hash randomization is intended to provide protection against a denial-of-" "service caused by carefully chosen inputs that exploit the worst case " @@ -660,7 +708,7 @@ msgstr "" "(*n*\\ :sup:`2`). Consulte http://ocert.org/advisories/ocert-2011-003.html " "para obter detalhes." -#: ../../using/cmdline.rst:377 +#: ../../using/cmdline.rst:383 msgid "" ":envvar:`PYTHONHASHSEED` allows you to set a fixed value for the hash seed " "secret." @@ -668,11 +716,11 @@ msgstr "" ":envvar:`PYTHONHASHSEED` permite que você defina um valor fixo para o " "segredo da semente de hash." -#: ../../using/cmdline.rst:382 +#: ../../using/cmdline.rst:388 msgid "The option is no longer ignored." msgstr "A opção não é mais ignorada." -#: ../../using/cmdline.rst:388 +#: ../../using/cmdline.rst:394 msgid "" "Don't add the :data:`user site-packages directory ` to :data:" "`sys.path`." @@ -680,16 +728,16 @@ msgstr "" "Não adiciona o :data:`diretório site-packages de usuário ` a :data:`sys.path`." -#: ../../using/cmdline.rst:391 +#: ../../using/cmdline.rst:397 msgid "See also :envvar:`PYTHONNOUSERSITE`." msgstr "Veja também :envvar:`PYTHONNOUSERSITE`." -#: ../../using/cmdline.rst:395 ../../using/cmdline.rst:887 -#: ../../using/cmdline.rst:899 +#: ../../using/cmdline.rst:401 ../../using/cmdline.rst:893 +#: ../../using/cmdline.rst:905 msgid ":pep:`370` -- Per user site-packages directory" msgstr ":pep:`370` -- Diretório site-packages por usuário." -#: ../../using/cmdline.rst:400 +#: ../../using/cmdline.rst:406 msgid "" "Disable the import of the module :mod:`site` and the site-dependent " "manipulations of :data:`sys.path` that it entails. Also disable these " @@ -701,7 +749,7 @@ msgstr "" "manipulações se :mod:`site` for explicitamente importado mais tarde (chame :" "func:`site.main` se você quiser que eles sejam acionados)." -#: ../../using/cmdline.rst:408 +#: ../../using/cmdline.rst:414 msgid "" "Force the stdout and stderr streams to be unbuffered. This option has no " "effect on the stdin stream." @@ -709,15 +757,15 @@ msgstr "" "Força os fluxos stdout e stderr a serem sem buffer. Esta opção não tem " "efeito no fluxo stdin." -#: ../../using/cmdline.rst:411 +#: ../../using/cmdline.rst:417 msgid "See also :envvar:`PYTHONUNBUFFERED`." msgstr "Veja também :envvar:`PYTHONUNBUFFERED`." -#: ../../using/cmdline.rst:413 +#: ../../using/cmdline.rst:419 msgid "The text layer of the stdout and stderr streams now is unbuffered." msgstr "A camada de texto dos fluxos stdout e stderr agora é sem buffer." -#: ../../using/cmdline.rst:419 +#: ../../using/cmdline.rst:425 msgid "" "Print a message each time a module is initialized, showing the place " "(filename or built-in module) from which it is loaded. When given twice (:" @@ -730,7 +778,7 @@ msgstr "" "que é verificado durante a busca por um módulo. Também fornece informações " "sobre a limpeza do módulo na saída." -#: ../../using/cmdline.rst:424 +#: ../../using/cmdline.rst:430 msgid "" "The :mod:`site` module reports the site-specific paths and :file:`.pth` " "files being processed." @@ -738,11 +786,11 @@ msgstr "" "O módulo :mod:`site` relata os caminhos específicos do site e os arquivos :" "file:`.pth` sendo processados." -#: ../../using/cmdline.rst:428 +#: ../../using/cmdline.rst:434 msgid "See also :envvar:`PYTHONVERBOSE`." msgstr "Veja também :envvar:`PYTHONVERBOSE`." -#: ../../using/cmdline.rst:434 +#: ../../using/cmdline.rst:440 msgid "" "Warning control. Python's warning machinery by default prints warning " "messages to :data:`sys.stderr`." @@ -750,7 +798,7 @@ msgstr "" "Controle de advertência. O mecanismo de aviso do Python por padrão exibe " "mensagens de aviso para :data:`sys.stderr`." -#: ../../using/cmdline.rst:437 ../../using/cmdline.rst:915 +#: ../../using/cmdline.rst:443 ../../using/cmdline.rst:921 msgid "" "The simplest settings apply a particular action unconditionally to all " "warnings emitted by a process (even those that are otherwise ignored by " @@ -760,7 +808,25 @@ msgstr "" "incondicionalmente a todos os avisos emitidos por um processo (mesmo aqueles " "que são ignorados por padrão)::" -#: ../../using/cmdline.rst:449 +#: ../../using/cmdline.rst:447 +msgid "" +"-Wdefault # Warn once per call location\n" +"-Werror # Convert to exceptions\n" +"-Walways # Warn every time\n" +"-Wall # Same as -Walways\n" +"-Wmodule # Warn once per calling module\n" +"-Wonce # Warn once per Python process\n" +"-Wignore # Never warn" +msgstr "" +"-Wdefault # Avisa uma vez por local de chamada\n" +"-Werror # Converte para exceções\n" +"-Walways # Avisa toda vez\n" +"-Wall # Mesmo que -Walways\n" +"-Wmodule # Avisa uma vez por módulo chamador\n" +"-Wonce # Avisa uma vez por processo do Python\n" +"-Wignore # Nunca avisar" + +#: ../../using/cmdline.rst:455 msgid "" "The action names can be abbreviated as desired and the interpreter will " "resolve them to the appropriate action name. For example, ``-Wi`` is the " @@ -770,11 +836,15 @@ msgstr "" "irá resolvê-los para o nome da ação apropriado. Por exemplo, ``-Wi`` é o " "mesmo que ``-Wignore``." -#: ../../using/cmdline.rst:453 +#: ../../using/cmdline.rst:459 msgid "The full form of argument is::" msgstr "A forma completa de argumento é::" -#: ../../using/cmdline.rst:457 +#: ../../using/cmdline.rst:461 +msgid "action:message:category:module:lineno" +msgstr "ação:mensagem:categoria:módulo:número-da-linha" + +#: ../../using/cmdline.rst:463 msgid "" "Empty fields match all values; trailing empty fields may be omitted. For " "example ``-W ignore::DeprecationWarning`` ignores all DeprecationWarning " @@ -784,7 +854,7 @@ msgstr "" "podem ser omitidos. Por exemplo, ``-W ignore::DeprecationWarning`` ignora " "todos os avisos de DeprecationWarning." -#: ../../using/cmdline.rst:461 +#: ../../using/cmdline.rst:467 msgid "" "The *action* field is as explained above but only applies to warnings that " "match the remaining fields." @@ -792,7 +862,7 @@ msgstr "" "O campo *action* é explicado acima, mas se aplica apenas a avisos que " "correspondem aos campos restantes." -#: ../../using/cmdline.rst:464 +#: ../../using/cmdline.rst:470 msgid "" "The *message* field must match the whole warning message; this match is case-" "insensitive." @@ -800,7 +870,7 @@ msgstr "" "O campo *message* deve corresponder a toda a mensagem de aviso; essa " "correspondência não diferencia maiúsculas de minúsculas." -#: ../../using/cmdline.rst:467 +#: ../../using/cmdline.rst:473 msgid "" "The *category* field matches the warning category (ex: " "``DeprecationWarning``). This must be a class name; the match test whether " @@ -812,7 +882,7 @@ msgstr "" "correspondência se a categoria de aviso real da mensagem é uma subclasse da " "categoria de aviso especificada." -#: ../../using/cmdline.rst:472 +#: ../../using/cmdline.rst:478 msgid "" "The *module* field matches the (fully qualified) module name; this match is " "case-sensitive." @@ -820,7 +890,7 @@ msgstr "" "O campo *module* corresponde ao nome do módulo (totalmente qualificado); " "esta correspondência diferencia maiúsculas de minúsculas." -#: ../../using/cmdline.rst:475 +#: ../../using/cmdline.rst:481 msgid "" "The *lineno* field matches the line number, where zero matches all line " "numbers and is thus equivalent to an omitted line number." @@ -829,7 +899,7 @@ msgstr "" "todos os números da linha e, portanto, é equivalente a um número da linha " "omitido." -#: ../../using/cmdline.rst:478 +#: ../../using/cmdline.rst:484 msgid "" "Multiple :option:`-W` options can be given; when a warning matches more than " "one option, the action for the last matching option is performed. Invalid :" @@ -842,7 +912,7 @@ msgstr "" "mensagem de aviso seja exibida sobre opções inválidas quando o primeiro " "aviso for emitido)." -#: ../../using/cmdline.rst:483 +#: ../../using/cmdline.rst:489 msgid "" "Warnings can also be controlled using the :envvar:`PYTHONWARNINGS` " "environment variable and from within a Python program using the :mod:" @@ -854,7 +924,7 @@ msgstr "" "`warnings`. Por exemplo, a função :func:`warnings.filterwarnings` pode ser " "usada para usar uma expressão regular na mensagem de aviso." -#: ../../using/cmdline.rst:488 ../../using/cmdline.rst:927 +#: ../../using/cmdline.rst:494 ../../using/cmdline.rst:933 msgid "" "See :ref:`warning-filter` and :ref:`describing-warning-filters` for more " "details." @@ -862,7 +932,7 @@ msgstr "" "Veja :ref:`warning-filter` e :ref:`describing-warning-filters` para mais " "detalhes." -#: ../../using/cmdline.rst:494 +#: ../../using/cmdline.rst:500 msgid "" "Skip the first line of the source, allowing use of non-Unix forms of ``#!" "cmd``. This is intended for a DOS specific hack only." @@ -870,7 +940,7 @@ msgstr "" "Pula a primeira linha do código-fonte, permitindo o uso de formas não-Unix " "de ``#!cmd``. Isso se destina apenas a um hack específico do DOS." -#: ../../using/cmdline.rst:500 +#: ../../using/cmdline.rst:506 msgid "" "Reserved for various implementation-specific options. CPython currently " "defines the following possible values:" @@ -878,7 +948,7 @@ msgstr "" "Reservado para várias opções específicas de implementação. CPython " "atualmente define os seguintes valores possíveis:" -#: ../../using/cmdline.rst:503 +#: ../../using/cmdline.rst:509 msgid "" "``-X faulthandler`` to enable :mod:`faulthandler`. See also :envvar:" "`PYTHONFAULTHANDLER`." @@ -886,7 +956,7 @@ msgstr "" "``-X faulthandler`` para habilitar :mod:`faulthandler`. Veja também :envvar:" "`PYTHONFAULTHANDLER`." -#: ../../using/cmdline.rst:508 +#: ../../using/cmdline.rst:514 msgid "" "``-X showrefcount`` to output the total reference count and number of used " "memory blocks when the program finishes or after each statement in the " @@ -898,7 +968,7 @@ msgstr "" "no interpretador interativo. Isso só funciona em :ref:`construções de " "depuração `." -#: ../../using/cmdline.rst:515 +#: ../../using/cmdline.rst:521 msgid "" "``-X tracemalloc`` to start tracing Python memory allocations using the :mod:" "`tracemalloc` module. By default, only the most recent frame is stored in a " @@ -913,7 +983,7 @@ msgstr "" "traceback de quadros *NFRAME*. Veja o :func:`tracemalloc.start` e :envvar:" "`PYTHONTRACEMALLOC` para mais informações." -#: ../../using/cmdline.rst:524 +#: ../../using/cmdline.rst:530 msgid "" "``-X int_max_str_digits`` configures the :ref:`integer string conversion " "length limitation `. See also :envvar:" @@ -923,7 +993,7 @@ msgstr "" "string na conversão para inteiro `. Veja também :envvar:" "`PYTHONINTMAXSTRDIGITS`." -#: ../../using/cmdline.rst:530 +#: ../../using/cmdline.rst:536 msgid "" "``-X importtime`` to show how long each import takes. It shows module name, " "cumulative time (including nested imports) and self time (excluding nested " @@ -938,7 +1008,7 @@ msgstr "" "importtime -c 'import asyncio'``. Veja também :envvar:" "`PYTHONPROFILEIMPORTTIME`." -#: ../../using/cmdline.rst:538 +#: ../../using/cmdline.rst:544 msgid "" "``-X dev``: enable :ref:`Python Development Mode `, introducing " "additional runtime checks that are too expensive to be enabled by default. " @@ -949,7 +1019,7 @@ msgstr "" "custosas para serem habilitadas por padrão. Veja também :envvar:" "`PYTHONDEVMODE`." -#: ../../using/cmdline.rst:544 +#: ../../using/cmdline.rst:550 msgid "" "``-X utf8`` enables the :ref:`Python UTF-8 Mode `. ``-X utf8=0`` " "explicitly disables :ref:`Python UTF-8 Mode ` (even when it would " @@ -960,7 +1030,7 @@ msgstr "" "(mesmo quando de outra forma seria ativado automaticamente). Veja também :" "envvar:`PYTHONUTF8`." -#: ../../using/cmdline.rst:551 +#: ../../using/cmdline.rst:557 msgid "" "``-X pycache_prefix=PATH`` enables writing ``.pyc`` files to a parallel tree " "rooted at the given directory instead of to the code tree. See also :envvar:" @@ -970,7 +1040,7 @@ msgstr "" "árvore paralela enraizada em um determinado diretório em vez de na árvore de " "código. Veja também :envvar:`PYTHONPYCACHEPREFIX`." -#: ../../using/cmdline.rst:557 +#: ../../using/cmdline.rst:563 msgid "" "``-X warn_default_encoding`` issues a :class:`EncodingWarning` when the " "locale-specific default encoding is used for opening files. See also :envvar:" @@ -980,7 +1050,7 @@ msgstr "" "codificação padrão específica da localidade é usada para abrir arquivos. " "Veja também :envvar:`PYTHONWARNDEFAULTENCODING`." -#: ../../using/cmdline.rst:563 +#: ../../using/cmdline.rst:569 msgid "" "``-X no_debug_ranges`` disables the inclusion of the tables mapping extra " "location information (end line, start column offset and end column offset) " @@ -997,7 +1067,7 @@ msgstr "" "quando o interpretador exibe tracebacks. Veja também :envvar:" "`PYTHONNODEBUGRANGES`." -#: ../../using/cmdline.rst:572 +#: ../../using/cmdline.rst:578 msgid "" "``-X frozen_modules`` determines whether or not frozen modules are ignored " "by the import machinery. A value of ``on`` means they get imported and " @@ -1018,7 +1088,7 @@ msgstr "" "sinalizador esteja definido como ``off``. Veja também :envvar:" "`PYTHON_FROZEN_MODULES`." -#: ../../using/cmdline.rst:583 +#: ../../using/cmdline.rst:589 msgid "" "``-X perf`` enables support for the Linux ``perf`` profiler. When this " "option is provided, the ``perf`` profiler will be able to report Python " @@ -1032,7 +1102,7 @@ msgstr "" "nada se não for compatível com o sistema atual. A opção padrão valor é " "\"off\". Consulte também :envvar:`PYTHONPERFSUPPORT` e :ref:`perf_profiling`." -#: ../../using/cmdline.rst:591 +#: ../../using/cmdline.rst:597 msgid "" "``-X perf_jit`` enables support for the Linux ``perf`` profiler with DWARF " "support. When this option is provided, the ``perf`` profiler will be able to " @@ -1048,7 +1118,7 @@ msgstr "" "compatível com o sistema atual. A opção padrão valor é \"off\". Veja também :" "envvar:`PYTHON_PERF_JIT_SUPPORT` e :ref:`perf_profiling`." -#: ../../using/cmdline.rst:600 +#: ../../using/cmdline.rst:606 msgid "" ":samp:`-X cpu_count={n}` overrides :func:`os.cpu_count`, :func:`os." "process_cpu_count`, and :func:`multiprocessing.cpu_count`. *n* must be " @@ -1062,7 +1132,7 @@ msgstr "" "recursos da CPU de um sistema contêiner. Veja também :envvar:" "`PYTHON_CPU_COUNT`. Se *n* for ``default``, nada será substituído." -#: ../../using/cmdline.rst:609 +#: ../../using/cmdline.rst:615 msgid "" ":samp:`-X presite={package.module}` specifies a module that should be " "imported before the :mod:`site` module is executed and before the :mod:" @@ -1078,18 +1148,19 @@ msgstr "" "do Python. Python precisa ser :ref:`construído no modo de depuração ` para que esta opção exista. Veja também :envvar:`PYTHON_PRESITE`." -#: ../../using/cmdline.rst:618 +#: ../../using/cmdline.rst:624 msgid "" ":samp:`-X gil={0,1}` forces the GIL to be disabled or enabled, respectively. " -"Only available in builds configured with :option:`--disable-gil`. See also :" -"envvar:`PYTHON_GIL` and :ref:`whatsnew313-free-threaded-cpython`." +"Setting to ``0`` is only available in builds configured with :option:`--" +"disable-gil`. See also :envvar:`PYTHON_GIL` and :ref:`whatsnew313-free-" +"threaded-cpython`." msgstr "" ":samp:`-X gil={0,1}` força a GIL a ser desabilitada ou habilitada, " -"respectivamente. Disponível apenas em construções configuradas com :option:" -"`--disable-gil`. Veja também :envvar:`PYTHON_GIL` e :ref:`whatsnew313-free-" -"threaded-cpython`." +"respectivamente. A definição para ``0`` está disponível apenas em " +"construções configuradas com :option:`--disable-gil`. Veja também :envvar:" +"`PYTHON_GIL` e :ref:`whatsnew313-free-threaded-cpython`." -#: ../../using/cmdline.rst:625 +#: ../../using/cmdline.rst:631 msgid "" "It also allows passing arbitrary values and retrieving them through the :" "data:`sys._xoptions` dictionary." @@ -1097,19 +1168,19 @@ msgstr "" "Também permite passar valores arbitrários e recuperá-los através do " "dicionário :data:`sys._xoptions`." -#: ../../using/cmdline.rst:630 +#: ../../using/cmdline.rst:636 msgid "Removed the ``-X showalloccount`` option." msgstr "Removida a opção ``-X showalloccount``." -#: ../../using/cmdline.rst:633 +#: ../../using/cmdline.rst:639 msgid "Removed the ``-X oldparser`` option." msgstr "Removida a opção ``-X oldparser``." -#: ../../using/cmdline.rst:639 +#: ../../using/cmdline.rst:645 msgid "Controlling color" msgstr "Controlando cores" -#: ../../using/cmdline.rst:641 +#: ../../using/cmdline.rst:647 msgid "" "The Python interpreter is configured by default to use colors to highlight " "output in certain situations such as when displaying tracebacks. This " @@ -1119,13 +1190,13 @@ msgstr "" "destacar a saída em determinadas situações, como ao exibir tracebacks. Este " "comportamento pode ser controlado definindo diferentes variáveis de ambiente." -#: ../../using/cmdline.rst:645 +#: ../../using/cmdline.rst:651 msgid "" "Setting the environment variable ``TERM`` to ``dumb`` will disable color." msgstr "" "Definir a variável de ambiente ``TERM`` como ``dumb`` desativará cores." -#: ../../using/cmdline.rst:647 +#: ../../using/cmdline.rst:653 msgid "" "If the |FORCE_COLOR|_ environment variable is set, then color will be " "enabled regardless of the value of TERM. This is useful on CI systems which " @@ -1135,7 +1206,7 @@ msgstr "" "habilitada independentemente do valor de TERM. Isso é útil em sistemas CI " "que não são terminais, mas ainda podem exibir sequências de escape ANSI." -#: ../../using/cmdline.rst:651 +#: ../../using/cmdline.rst:657 msgid "" "If the |NO_COLOR|_ environment variable is set, Python will disable all " "color in the output. This takes precedence over ``FORCE_COLOR``." @@ -1143,7 +1214,7 @@ msgstr "" "Se a variável de ambiente |NO_COLOR|_ estiver definida, o Python desativará " "todas as cores na saída. Isto tem precedência sobre ``FORCE_COLOR``." -#: ../../using/cmdline.rst:654 +#: ../../using/cmdline.rst:660 msgid "" "All these environment variables are used also by other tools to control " "color output. To control the color output only in the Python interpreter, " @@ -1157,19 +1228,19 @@ msgstr "" "ser usada. Esta variável tem precedência sobre ``NO_COLOR``, que por sua vez " "tem precedência sobre ``FORCE_COLOR``." -#: ../../using/cmdline.rst:669 +#: ../../using/cmdline.rst:675 msgid "Options you shouldn't use" msgstr "Opções que você não deve usar" -#: ../../using/cmdline.rst:673 +#: ../../using/cmdline.rst:679 msgid "Reserved for use by Jython_." msgstr "Reservado para uso pelo Jython_." -#: ../../using/cmdline.rst:681 +#: ../../using/cmdline.rst:687 msgid "Environment variables" msgstr "Variáveis de ambiente" -#: ../../using/cmdline.rst:683 +#: ../../using/cmdline.rst:689 msgid "" "These environment variables influence Python's behavior, they are processed " "before the command-line switches other than -E or -I. It is customary that " @@ -1181,7 +1252,7 @@ msgstr "" "comum que as opções de linha de comando substituam as variáveis ambientais " "onde há um conflito." -#: ../../using/cmdline.rst:690 +#: ../../using/cmdline.rst:696 msgid "" "Change the location of the standard Python libraries. By default, the " "libraries are searched in :file:`{prefix}/lib/python{version}` and :file:" @@ -1195,7 +1266,7 @@ msgstr "" "`{exec_prefix}` são diretórios dependentes da instalação, ambos padronizando " "para :file:`/usr/local`." -#: ../../using/cmdline.rst:696 +#: ../../using/cmdline.rst:702 msgid "" "When :envvar:`PYTHONHOME` is set to a single directory, its value replaces " "both :file:`{prefix}` and :file:`{exec_prefix}`. To specify different " @@ -1206,7 +1277,7 @@ msgstr "" "diferentes para estes, defina :envvar:`PYTHONHOME` para :file:`{prefix}:" "{exec_prefix}`." -#: ../../using/cmdline.rst:703 +#: ../../using/cmdline.rst:709 msgid "" "Augment the default search path for module files. The format is the same as " "the shell's :envvar:`PATH`: one or more directory pathnames separated by :" @@ -1218,7 +1289,7 @@ msgstr "" "por :data:`os.pathsep` (por exemplo, dois pontos no Unix ou ponto e vírgula " "no Windows). Os diretórios inexistentes são ignorados silenciosamente." -#: ../../using/cmdline.rst:708 +#: ../../using/cmdline.rst:714 msgid "" "In addition to normal directories, individual :envvar:`PYTHONPATH` entries " "may refer to zipfiles containing pure Python modules (in either source or " @@ -1229,7 +1300,7 @@ msgstr "" "fonte quanto na forma compilada). Módulos de extensão não podem ser " "importados de arquivos zip." -#: ../../using/cmdline.rst:712 +#: ../../using/cmdline.rst:718 msgid "" "The default search path is installation dependent, but generally begins " "with :file:`{prefix}/lib/python{version}` (see :envvar:`PYTHONHOME` above). " @@ -1239,7 +1310,7 @@ msgstr "" "com :file:`{prefix}/lib/python{version}` (veja :envvar:`PYTHONHOME` acima). " "É *sempre* anexado a :envvar:`PYTHONPATH`." -#: ../../using/cmdline.rst:716 +#: ../../using/cmdline.rst:722 msgid "" "An additional directory will be inserted in the search path in front of :" "envvar:`PYTHONPATH` as described above under :ref:`using-on-interface-" @@ -1251,7 +1322,7 @@ msgstr "" "caminho de pesquisa pode ser manipulado de dentro de um programa Python como " "a variável :data:`sys.path`." -#: ../../using/cmdline.rst:724 +#: ../../using/cmdline.rst:730 msgid "" "If this is set to a non-empty string, don't prepend a potentially unsafe " "path to :data:`sys.path`: see the :option:`-P` option for details." @@ -1260,7 +1331,7 @@ msgstr "" "potencialmente inseguro para :data:`sys.path`: consulte a opção :option:`-P` " "para obter detalhes." -#: ../../using/cmdline.rst:732 +#: ../../using/cmdline.rst:738 msgid "" "If this is set to a non-empty string, it overrides the :data:`sys." "platlibdir` value." @@ -1268,7 +1339,7 @@ msgstr "" "Se for definido como uma string não vazia, ela substitui o valor :data:`sys." "platlibdir`." -#: ../../using/cmdline.rst:740 +#: ../../using/cmdline.rst:746 msgid "" "If this is the name of a readable file, the Python commands in that file are " "executed before the first prompt is displayed in interactive mode. The file " @@ -1286,7 +1357,7 @@ msgstr "" "alterar os prompts :data:`sys.ps1` e :data:`sys.ps2` e o gancho :data:`sys." "__interactivehook__` neste arquivo." -#: ../../using/cmdline.rst:747 ../../using/cmdline.rst:749 +#: ../../using/cmdline.rst:753 ../../using/cmdline.rst:755 msgid "" "Raises an :ref:`auditing event ` ``cpython.run_startup`` with the " "filename as the argument when called on startup." @@ -1294,7 +1365,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``cpython.run_startup`` com " "o nome de arquivo como argumento quando chamado na inicialização." -#: ../../using/cmdline.rst:755 +#: ../../using/cmdline.rst:761 msgid "" "If this is set to a non-empty string it is equivalent to specifying the :" "option:`-O` option. If set to an integer, it is equivalent to specifying :" @@ -1304,7 +1375,7 @@ msgstr "" "opção :option:`-O`. Se definido como um inteiro, é equivalente a " "especificar :option:`-O` várias vezes." -#: ../../using/cmdline.rst:762 +#: ../../using/cmdline.rst:768 msgid "" "If this is set, it names a callable using dotted-path notation. The module " "containing the callable will be imported and then the callable will be run " @@ -1322,7 +1393,7 @@ msgstr "" "isso para a string \"0\" faz com que a implementação padrão de :func:`sys." "breakpointhook` não faça nada além de retornar imediatamente." -#: ../../using/cmdline.rst:774 +#: ../../using/cmdline.rst:780 msgid "" "If this is set to a non-empty string it is equivalent to specifying the :" "option:`-d` option. If set to an integer, it is equivalent to specifying :" @@ -1332,7 +1403,7 @@ msgstr "" "opção :option:`-d`. Se definido como um inteiro, é equivalente a " "especificar :option:`-d` várias vezes." -#: ../../using/cmdline.rst:778 +#: ../../using/cmdline.rst:784 msgid "" "This environment variable requires a :ref:`debug build of Python `, otherwise it's ignored." @@ -1340,7 +1411,7 @@ msgstr "" "Essa variável de ambiente requer uma :ref:`construção de depuração do Python " "`, caso contrário, será ignorada." -#: ../../using/cmdline.rst:784 +#: ../../using/cmdline.rst:790 msgid "" "If this is set to a non-empty string it is equivalent to specifying the :" "option:`-i` option." @@ -1348,7 +1419,7 @@ msgstr "" "Se for definido como uma string não vazia, é equivalente a especificar a " "opção :option:`-i`." -#: ../../using/cmdline.rst:787 +#: ../../using/cmdline.rst:793 msgid "" "This variable can also be modified by Python code using :data:`os.environ` " "to force inspect mode on program termination." @@ -1356,11 +1427,11 @@ msgstr "" "Esta variável também pode ser modificada pelo código Python usando :data:`os." "environ` para forçar o modo de inspeção no encerramento do programa." -#: ../../using/cmdline.rst:792 +#: ../../using/cmdline.rst:798 msgid "(also 3.11.10, 3.10.15, 3.9.20, and 3.8.20) Emits audit events." msgstr "(também 3.11.10, 3.10.15, 3.9.20 e 3.8.20) Emite eventos de auditoria." -#: ../../using/cmdline.rst:795 +#: ../../using/cmdline.rst:801 msgid "" "Uses PyREPL if possible, in which case :envvar:`PYTHONSTARTUP` is also " "executed. Emits audit events." @@ -1368,7 +1439,7 @@ msgstr "" "Usa PyrePL, se possível, nesse caso :envvar:`PYTHONSTARTUP` também é " "executado. Emite eventos de auditoria." -#: ../../using/cmdline.rst:802 +#: ../../using/cmdline.rst:808 msgid "" "If this is set to a non-empty string it is equivalent to specifying the :" "option:`-u` option." @@ -1376,7 +1447,7 @@ msgstr "" "Se for definido como uma string não vazia, é equivalente a especificar a " "opção :option:`-u`." -#: ../../using/cmdline.rst:808 +#: ../../using/cmdline.rst:814 msgid "" "If this is set to a non-empty string it is equivalent to specifying the :" "option:`-v` option. If set to an integer, it is equivalent to specifying :" @@ -1386,7 +1457,7 @@ msgstr "" "opção :option:`-v`. Se definido como um inteiro, é equivalente a " "especificar :option:`-v` várias vezes." -#: ../../using/cmdline.rst:815 +#: ../../using/cmdline.rst:821 msgid "" "If this is set, Python ignores case in :keyword:`import` statements. This " "only works on Windows and macOS." @@ -1394,7 +1465,7 @@ msgstr "" "Se estiver definido, Python não diferencia letras maiúsculas e minúsculas " "nas instruções :keyword:`import`. Isso só funciona no Windows e OS X." -#: ../../using/cmdline.rst:821 +#: ../../using/cmdline.rst:827 msgid "" "If this is set to a non-empty string, Python won't try to write ``.pyc`` " "files on the import of source modules. This is equivalent to specifying " @@ -1404,7 +1475,7 @@ msgstr "" "arquivos ``.pyc`` na importação de módulos fonte. Isso é equivalente a " "especificar a opção :option:`-B`." -#: ../../using/cmdline.rst:828 +#: ../../using/cmdline.rst:834 msgid "" "If this is set, Python will write ``.pyc`` files in a mirror directory tree " "at this path, instead of in ``__pycache__`` directories within the source " @@ -1416,7 +1487,7 @@ msgstr "" "dentro da árvore de fontes. Isso é equivalente a especificar a opção :option:" "`-X` ``pycache_prefix=PATH``." -#: ../../using/cmdline.rst:838 +#: ../../using/cmdline.rst:844 msgid "" "If this variable is not set or set to ``random``, a random value is used to " "seed the hashes of str and bytes objects." @@ -1424,7 +1495,7 @@ msgstr "" "Se esta variável não for definida ou definida como ``random``, um valor " "aleatório é usado para semear os hashes de objetos str e bytes." -#: ../../using/cmdline.rst:841 +#: ../../using/cmdline.rst:847 msgid "" "If :envvar:`PYTHONHASHSEED` is set to an integer value, it is used as a " "fixed seed for generating the hash() of the types covered by the hash " @@ -1434,7 +1505,7 @@ msgstr "" "como uma semente fixa para gerar o hash() dos tipos cobertos pela " "aleatorização do hash." -#: ../../using/cmdline.rst:845 +#: ../../using/cmdline.rst:851 msgid "" "Its purpose is to allow repeatable hashing, such as for selftests for the " "interpreter itself, or to allow a cluster of python processes to share hash " @@ -1444,7 +1515,7 @@ msgstr "" "interpretador, ou permitir que um cluster de processos Python compartilhe " "valores de hash." -#: ../../using/cmdline.rst:849 +#: ../../using/cmdline.rst:855 msgid "" "The integer must be a decimal number in the range [0,4294967295]. " "Specifying the value 0 will disable hash randomization." @@ -1452,7 +1523,7 @@ msgstr "" "O número inteiro deve ser um número decimal no intervalo [0,4294967295]. " "Especificar o valor 0 desabilitará a aleatorização de hash." -#: ../../using/cmdline.rst:856 +#: ../../using/cmdline.rst:862 msgid "" "If this variable is set to an integer, it is used to configure the " "interpreter's global :ref:`integer string conversion length limitation " @@ -1462,7 +1533,7 @@ msgstr "" "a :ref:`limitação de comprimento de string na conversão para inteiro " "` global do interpretador." -#: ../../using/cmdline.rst:864 +#: ../../using/cmdline.rst:870 msgid "" "If this is set before running the interpreter, it overrides the encoding " "used for stdin/stdout/stderr, in the syntax ``encodingname:errorhandler``. " @@ -1474,7 +1545,7 @@ msgstr "" "errorhandler``. Ambas as partes ``encodingname`` e ``:errorhandler`` são " "opcionais e têm o mesmo significado que em :func:`str.encode`." -#: ../../using/cmdline.rst:869 +#: ../../using/cmdline.rst:875 msgid "" "For stderr, the ``:errorhandler`` part is ignored; the handler will always " "be ``'backslashreplace'``." @@ -1482,11 +1553,11 @@ msgstr "" "Para stderr, a parte ``:errorhandler`` é ignorada; o tratador sempre será " "``'backslashreplace'``." -#: ../../using/cmdline.rst:872 +#: ../../using/cmdline.rst:878 msgid "The ``encodingname`` part is now optional." msgstr "A parte ``encodingname`` é agora opcional." -#: ../../using/cmdline.rst:875 +#: ../../using/cmdline.rst:881 msgid "" "On Windows, the encoding specified by this variable is ignored for " "interactive console buffers unless :envvar:`PYTHONLEGACYWINDOWSSTDIO` is " @@ -1498,7 +1569,7 @@ msgstr "" "`PYTHONLEGACYWINDOWSSTDIO` também seja especificado. Arquivos e canais " "redirecionados por meio de fluxos padrão não são afetados." -#: ../../using/cmdline.rst:882 +#: ../../using/cmdline.rst:888 msgid "" "If this is set, Python won't add the :data:`user site-packages directory " "` to :data:`sys.path`." @@ -1506,7 +1577,7 @@ msgstr "" "Se estiver definido, o Python não adicionará o :data:`diretório site-" "packages do usuário ` a :data:`sys.path`." -#: ../../using/cmdline.rst:892 +#: ../../using/cmdline.rst:898 msgid "" "Defines the :data:`user base directory `, which is used to " "compute the path of the :data:`user site-packages directory ` e :ref:`caminhos de instalação ` para " "``python -m pip install --user``." -#: ../../using/cmdline.rst:904 +#: ../../using/cmdline.rst:910 msgid "" "If this environment variable is set, ``sys.argv[0]`` will be set to its " "value instead of the value got through the C runtime. Only works on macOS." @@ -1527,7 +1598,7 @@ msgstr "" "seu valor em vez do valor obtido através do tempo de execução C. Funciona " "apenas no macOS." -#: ../../using/cmdline.rst:910 +#: ../../using/cmdline.rst:916 msgid "" "This is equivalent to the :option:`-W` option. If set to a comma separated " "string, it is equivalent to specifying :option:`-W` multiple times, with " @@ -1538,7 +1609,25 @@ msgstr "" "vezes, com os filtros posteriores na lista tendo precedência sobre os " "anteriores na lista." -#: ../../using/cmdline.rst:933 +#: ../../using/cmdline.rst:925 +msgid "" +"PYTHONWARNINGS=default # Warn once per call location\n" +"PYTHONWARNINGS=error # Convert to exceptions\n" +"PYTHONWARNINGS=always # Warn every time\n" +"PYTHONWARNINGS=all # Same as PYTHONWARNINGS=always\n" +"PYTHONWARNINGS=module # Warn once per calling module\n" +"PYTHONWARNINGS=once # Warn once per Python process\n" +"PYTHONWARNINGS=ignore # Never warn" +msgstr "" +"PYTHONWARNINGS=default # Avisa uma vez por local de chamada\n" +"PYTHONWARNINGS=error # Converte para exceções\n" +"PYTHONWARNINGS=always # Avisa toda vez\n" +"PYTHONWARNINGS=all # Mesmo que PYTHONWARNINGS=always\n" +"PYTHONWARNINGS=module # Avisa uma vez por módulo chamador\n" +"PYTHONWARNINGS=once # Avisa uma vez por processo do Python\n" +"PYTHONWARNINGS=ignore # Nunca avisar" + +#: ../../using/cmdline.rst:939 msgid "" "If this environment variable is set to a non-empty string, :func:" "`faulthandler.enable` is called at startup: install a handler for :const:" @@ -1553,7 +1642,7 @@ msgstr "" "traceback (situação da pilha de execução) do Python. Isso é equivalente à " "opção :option:`-X` ``faulthandler``." -#: ../../using/cmdline.rst:945 +#: ../../using/cmdline.rst:951 msgid "" "If this environment variable is set to a non-empty string, start tracing " "Python memory allocations using the :mod:`tracemalloc` module. The value of " @@ -1570,7 +1659,7 @@ msgstr "" "start` para mais informações. Isso é o equivalente a definir a opção :option:" "`-X` ``tracemalloc``." -#: ../../using/cmdline.rst:958 +#: ../../using/cmdline.rst:964 msgid "" "If this environment variable is set to a non-empty string, Python will show " "how long each import takes. This is equivalent to setting the :option:`-X` " @@ -1580,7 +1669,7 @@ msgstr "" "Python mostrará quanto tempo leva cada importação. Isso é o equivalente a " "definir a opção :option:`-X` ``importtime``." -#: ../../using/cmdline.rst:967 +#: ../../using/cmdline.rst:973 msgid "" "If this environment variable is set to a non-empty string, enable the :ref:" "`debug mode ` of the :mod:`asyncio` module." @@ -1589,16 +1678,16 @@ msgstr "" "habilita o :ref:`modo de depuração ` do módulo :mod:" "`asyncio`." -#: ../../using/cmdline.rst:975 +#: ../../using/cmdline.rst:981 msgid "Set the Python memory allocators and/or install debug hooks." msgstr "" "Define os alocadores de memória Python e/ou instale ganchos de depuração." -#: ../../using/cmdline.rst:977 +#: ../../using/cmdline.rst:983 msgid "Set the family of memory allocators used by Python:" -msgstr "Define a família de alocadores de memória usados ​​pelo Python:" +msgstr "Define a família de alocadores de memória usados pelo Python:" -#: ../../using/cmdline.rst:979 +#: ../../using/cmdline.rst:985 msgid "" "``default``: use the :ref:`default memory allocators `." @@ -1606,7 +1695,7 @@ msgstr "" "``default``: usa os :ref:`alocadores padrão de memória `." -#: ../../using/cmdline.rst:981 +#: ../../using/cmdline.rst:987 msgid "" "``malloc``: use the :c:func:`malloc` function of the C library for all " "domains (:c:macro:`PYMEM_DOMAIN_RAW`, :c:macro:`PYMEM_DOMAIN_MEM`, :c:macro:" @@ -1616,7 +1705,7 @@ msgstr "" "domínios (:c:macro:`PYMEM_DOMAIN_RAW`, :c:macro:`PYMEM_DOMAIN_MEM`, :c:macro:" "`PYMEM_DOMAIN_OBJ`)." -#: ../../using/cmdline.rst:984 +#: ../../using/cmdline.rst:990 msgid "" "``pymalloc``: use the :ref:`pymalloc allocator ` for :c:macro:" "`PYMEM_DOMAIN_MEM` and :c:macro:`PYMEM_DOMAIN_OBJ` domains and use the :c:" @@ -1626,7 +1715,7 @@ msgstr "" "macro:`PYMEM_DOMAIN_MEM` e :c:macro:`PYMEM_DOMAIN_OBJ` e usa a função :c:" "func:`malloc` para o domínio :c:macro:`PYMEM_DOMAIN_RAW`." -#: ../../using/cmdline.rst:987 +#: ../../using/cmdline.rst:993 msgid "" "``mimalloc``: use the :ref:`mimalloc allocator ` for :c:macro:" "`PYMEM_DOMAIN_MEM` and :c:macro:`PYMEM_DOMAIN_OBJ` domains and use the :c:" @@ -1636,11 +1725,11 @@ msgstr "" "macro:`PYMEM_DOMAIN_MEM` e :c:macro:`PYMEM_DOMAIN_OBJ` e usa a função :c:" "func:`malloc` para o domínio :c:macro:`PYMEM_DOMAIN_RAW`." -#: ../../using/cmdline.rst:991 +#: ../../using/cmdline.rst:997 msgid "Install :ref:`debug hooks `:" msgstr "Instala :ref:`ganchos de depuração `:" -#: ../../using/cmdline.rst:993 +#: ../../using/cmdline.rst:999 msgid "" "``debug``: install debug hooks on top of the :ref:`default memory allocators " "`." @@ -1648,29 +1737,29 @@ msgstr "" "``debug``: instala os ganchos de depuração sobre os :ref:`alocadores padrão " "de memória `." -#: ../../using/cmdline.rst:995 +#: ../../using/cmdline.rst:1001 msgid "``malloc_debug``: same as ``malloc`` but also install debug hooks." msgstr "" "``malloc_debug``: o mesmo que ``malloc``, mas também instala ganchos de " "depuração." -#: ../../using/cmdline.rst:996 +#: ../../using/cmdline.rst:1002 msgid "``pymalloc_debug``: same as ``pymalloc`` but also install debug hooks." msgstr "" "``pymalloc_debug``: o mesmo que ``pymalloc``, mas também instala ganchos de " "depuração." -#: ../../using/cmdline.rst:997 +#: ../../using/cmdline.rst:1003 msgid "``mimalloc_debug``: same as ``mimalloc`` but also install debug hooks." msgstr "" "``mimalloc_debug``: o mesmo que ``mimalloc``, mas também instala ganchos de " "depuração." -#: ../../using/cmdline.rst:1001 +#: ../../using/cmdline.rst:1007 msgid "Added the ``\"default\"`` allocator." msgstr "Adicionado o alocador ``\"default\"``." -#: ../../using/cmdline.rst:1007 +#: ../../using/cmdline.rst:1013 msgid "" "If set to a non-empty string, Python will print statistics of the :ref:" "`pymalloc memory allocator ` every time a new pymalloc object " @@ -1680,7 +1769,7 @@ msgstr "" "`alocador de memória pymalloc ` toda vez que uma nova arena de " "objeto pymalloc for criada e ao no desligamento." -#: ../../using/cmdline.rst:1011 +#: ../../using/cmdline.rst:1017 msgid "" "This variable is ignored if the :envvar:`PYTHONMALLOC` environment variable " "is used to force the :c:func:`malloc` allocator of the C library, or if " @@ -1690,7 +1779,7 @@ msgstr "" "usada para forçar o alocador :c:func:`malloc` da biblioteca C, ou se Python " "está configurado sem suporte a ``pymalloc``." -#: ../../using/cmdline.rst:1015 +#: ../../using/cmdline.rst:1021 msgid "" "This variable can now also be used on Python compiled in release mode. It " "now has no effect if set to an empty string." @@ -1698,7 +1787,7 @@ msgstr "" "Esta variável agora também pode ser usada em Python compilado no modo de " "lançamento. Agora não tem efeito se definido como uma string vazia." -#: ../../using/cmdline.rst:1022 +#: ../../using/cmdline.rst:1028 msgid "" "If set to a non-empty string, the default :term:`filesystem encoding and " "error handler` mode will revert to their pre-3.6 values of 'mbcs' and " @@ -1710,23 +1799,24 @@ msgstr "" "pré-3.6 de \"mbcs\" e \"replace\", respectivamente. Caso contrário, os novos " "padrões \"utf-8\" e \"surrogatepass\" serão usados." -#: ../../using/cmdline.rst:1027 +#: ../../using/cmdline.rst:1033 msgid "" "This may also be enabled at runtime with :func:`sys." -"_enablelegacywindowsfsencoding()`." +"_enablelegacywindowsfsencoding`." msgstr "" "Isso também pode ser habilitado em tempo de execução com :func:`sys." -"_enablelegacywindowsfsencoding()`." +"_enablelegacywindowsfsencoding`." -#: ../../using/cmdline.rst:1030 ../../using/cmdline.rst:1044 -msgid ":ref:`Availability `: Windows." -msgstr ":ref:`Disponibilidade `: Windows." +#: ../../using/cmdline.rst:1036 ../../using/cmdline.rst:1050 +#: ../../using/cmdline.rst:1101 +msgid "Availability" +msgstr "Disponibilidade" -#: ../../using/cmdline.rst:1032 +#: ../../using/cmdline.rst:1038 msgid "See :pep:`529` for more details." msgstr "Veja :pep:`529` para mais detalhes." -#: ../../using/cmdline.rst:1037 +#: ../../using/cmdline.rst:1043 msgid "" "If set to a non-empty string, does not use the new console reader and " "writer. This means that Unicode characters will be encoded according to the " @@ -1736,7 +1826,7 @@ msgstr "" "console. Isso significa que os caracteres Unicode serão codificados de " "acordo com a página de código do console ativo, em vez de usar utf-8." -#: ../../using/cmdline.rst:1041 +#: ../../using/cmdline.rst:1047 msgid "" "This variable is ignored if the standard streams are redirected (to files or " "pipes) rather than referring to console buffers." @@ -1744,7 +1834,7 @@ msgstr "" "Esta variável é ignorada se os fluxos padrão forem redirecionados (para " "arquivos ou canais) em vez de se referir aos buffers do console." -#: ../../using/cmdline.rst:1051 +#: ../../using/cmdline.rst:1057 msgid "" "If set to the value ``0``, causes the main Python command line application " "to skip coercing the legacy ASCII-based C and POSIX locales to a more " @@ -1754,7 +1844,7 @@ msgstr "" "comando Python ignore a coerção dos códigos de idioma legados C e POSIX " "baseados em ASCII para uma alternativa baseada em UTF-8 mais capaz." -#: ../../using/cmdline.rst:1055 +#: ../../using/cmdline.rst:1061 msgid "" "If this variable is *not* set (or is set to a value other than ``0``), the " "``LC_ALL`` locale override environment variable is also not set, and the " @@ -1772,19 +1862,19 @@ msgstr "" "configurar as seguintes localidades para a categoria ``LC_CTYPE`` na ordem " "listada antes de carregar o tempo de execução do interpretador:" -#: ../../using/cmdline.rst:1063 +#: ../../using/cmdline.rst:1069 msgid "``C.UTF-8``" msgstr "``C.UTF-8``" -#: ../../using/cmdline.rst:1064 +#: ../../using/cmdline.rst:1070 msgid "``C.utf8``" msgstr "``C.utf8``" -#: ../../using/cmdline.rst:1065 +#: ../../using/cmdline.rst:1071 msgid "``UTF-8``" msgstr "``UTF-8``" -#: ../../using/cmdline.rst:1067 +#: ../../using/cmdline.rst:1073 msgid "" "If setting one of these locale categories succeeds, then the ``LC_CTYPE`` " "environment variable will also be set accordingly in the current process " @@ -1807,7 +1897,7 @@ msgstr "" "consultam o ambiente em vez da localidade C atual (como o :func:`locale." "getdefaultlocale` do próprio Python)." -#: ../../using/cmdline.rst:1077 +#: ../../using/cmdline.rst:1083 msgid "" "Configuring one of these locales (either explicitly or via the above " "implicit locale coercion) automatically enables the ``surrogateescape`` :ref:" @@ -1823,7 +1913,7 @@ msgstr "" "faz em qualquer outra localidade). Este comportamento de tratamento de fluxo " "pode ser substituído usando :envvar:`PYTHONIOENCODING` como de costume." -#: ../../using/cmdline.rst:1084 +#: ../../using/cmdline.rst:1090 msgid "" "For debugging purposes, setting ``PYTHONCOERCECLOCALE=warn`` will cause " "Python to emit warning messages on ``stderr`` if either the locale coercion " @@ -1835,7 +1925,7 @@ msgstr "" "ativada ou se uma localidade que *teria* acionado a coerção ainda estiver " "ativa quando o Python o tempo de execução é inicializado." -#: ../../using/cmdline.rst:1089 +#: ../../using/cmdline.rst:1095 msgid "" "Also note that even when locale coercion is disabled, or when it fails to " "find a suitable target locale, :envvar:`PYTHONUTF8` will still activate by " @@ -1850,15 +1940,11 @@ msgstr "" "interpretador a usar ``ASCII`` ao invés de ``UTF-8`` para interfaces de " "sistema." -#: ../../using/cmdline.rst:1095 -msgid ":ref:`Availability `: Unix." -msgstr ":ref:`Disponibilidade `: Unix." - -#: ../../using/cmdline.rst:1097 +#: ../../using/cmdline.rst:1103 msgid "See :pep:`538` for more details." msgstr "Veja :pep:`538` para mais detalhes." -#: ../../using/cmdline.rst:1103 +#: ../../using/cmdline.rst:1109 msgid "" "If this environment variable is set to a non-empty string, enable :ref:" "`Python Development Mode `, introducing additional runtime checks " @@ -1871,17 +1957,17 @@ msgstr "" "habilitadas por padrão. Isso é o equivalente a definir a opção :option:`-X` " "``dev``." -#: ../../using/cmdline.rst:1112 +#: ../../using/cmdline.rst:1118 msgid "If set to ``1``, enable the :ref:`Python UTF-8 Mode `." msgstr "" "Se definido para ``1``, habilita o :ref:`modo UTF-8 do Python `." -#: ../../using/cmdline.rst:1114 +#: ../../using/cmdline.rst:1120 msgid "If set to ``0``, disable the :ref:`Python UTF-8 Mode `." msgstr "" "Se definido para ``0``, desabilita o :ref:`modo UTF-8 do Python `." -#: ../../using/cmdline.rst:1116 +#: ../../using/cmdline.rst:1122 msgid "" "Setting any other non-empty string causes an error during interpreter " "initialisation." @@ -1889,7 +1975,7 @@ msgstr "" "Definir qualquer outra string não vazia causa um erro durante a " "inicialização do interpretador." -#: ../../using/cmdline.rst:1123 +#: ../../using/cmdline.rst:1129 msgid "" "If this environment variable is set to a non-empty string, issue a :class:" "`EncodingWarning` when the locale-specific default encoding is used." @@ -1898,11 +1984,11 @@ msgstr "" "uma :class:`EncodingWarning` quando a codificação padrão específica da " "localidade é usada." -#: ../../using/cmdline.rst:1126 +#: ../../using/cmdline.rst:1132 msgid "See :ref:`io-encoding-warning` for details." msgstr "Veja :ref:`io-encoding-warning` para detalhes." -#: ../../using/cmdline.rst:1132 +#: ../../using/cmdline.rst:1138 msgid "" "If this variable is set, it disables the inclusion of the tables mapping " "extra location information (end line, start column offset and end column " @@ -1917,7 +2003,7 @@ msgstr "" "desejados, bem como suprimir os indicadores de localização visual extra " "quando o interpretador exibe tracebacks." -#: ../../using/cmdline.rst:1142 +#: ../../using/cmdline.rst:1148 msgid "" "If this variable is set to a nonzero value, it enables support for the Linux " "``perf`` profiler so Python calls can be detected by it." @@ -1926,12 +2012,12 @@ msgstr "" "suporte para o perfilador do Linux ``perf`` para que as chamadas Python " "possam ser detectadas por ele." -#: ../../using/cmdline.rst:1145 ../../using/cmdline.rst:1158 +#: ../../using/cmdline.rst:1151 ../../using/cmdline.rst:1164 msgid "If set to ``0``, disable Linux ``perf`` profiler support." msgstr "" "Se definido como ``0``, desativa o suporte ao perfilador do Linux ``perf``." -#: ../../using/cmdline.rst:1147 +#: ../../using/cmdline.rst:1153 msgid "" "See also the :option:`-X perf <-X>` command-line option and :ref:" "`perf_profiling`." @@ -1939,7 +2025,7 @@ msgstr "" "Consulte também a opção de linha de comando :option:`-X perf <-X>` e :ref:" "`perf_profiling`." -#: ../../using/cmdline.rst:1154 +#: ../../using/cmdline.rst:1160 msgid "" "If this variable is set to a nonzero value, it enables support for the Linux " "``perf`` profiler so Python calls can be detected by it using DWARF " @@ -1949,7 +2035,7 @@ msgstr "" "suporte para o perfilador do Linux ``perf`` para que as chamadas Python " "possam ser detectadas por ele usando informações de DWARF." -#: ../../using/cmdline.rst:1160 +#: ../../using/cmdline.rst:1166 msgid "" "See also the :option:`-X perf_jit <-X>` command-line option and :ref:" "`perf_profiling`." @@ -1957,7 +2043,7 @@ msgstr "" "Veja também a opção de linha de comando :option:`-X perf_jit <-X>` e :ref:" "`perf_profiling`." -#: ../../using/cmdline.rst:1169 +#: ../../using/cmdline.rst:1175 msgid "" "If this variable is set to a positive integer, it overrides the return " "values of :func:`os.cpu_count` and :func:`os.process_cpu_count`." @@ -1965,11 +2051,11 @@ msgstr "" "Se esta variável for definida como um número inteiro positivo, ela substitui " "os valores de retorno de :func:`os.cpu_count` e :func:`os.process_cpu_count`." -#: ../../using/cmdline.rst:1172 +#: ../../using/cmdline.rst:1178 msgid "See also the :option:`-X cpu_count <-X>` command-line option." msgstr "Veja também a opção de linha de comando :option:`-X cpu_count <-X>`." -#: ../../using/cmdline.rst:1178 +#: ../../using/cmdline.rst:1184 msgid "" "If this variable is set to ``on`` or ``off``, it determines whether or not " "frozen modules are ignored by the import machinery. A value of ``on`` means " @@ -1988,12 +2074,12 @@ msgstr "" "importlib_bootstrap_external` são sempre usados, mesmo se este sinalizador " "estiver definido como ``off``." -#: ../../using/cmdline.rst:1186 +#: ../../using/cmdline.rst:1192 msgid "See also the :option:`-X frozen_modules <-X>` command-line option." msgstr "" "Veja também a opção de linha de comando :option:`-X frozen_modules <-X>`." -#: ../../using/cmdline.rst:1192 +#: ../../using/cmdline.rst:1198 msgid "" "If this variable is set to ``1``, the interpreter will colorize various " "kinds of output. Setting it to ``0`` deactivates this behavior. See also :" @@ -2003,18 +2089,18 @@ msgstr "" "tipos de saída. Definir como ``0`` desativa este comportamento. Veja também :" "ref:`using-on-controlling-color`." -#: ../../using/cmdline.rst:1200 +#: ../../using/cmdline.rst:1206 msgid "" -"If this variable is set to ``1``, the interpreter will not attempt to load " -"the Python-based :term:`REPL` that requires :mod:`curses` and :mod:" +"If this variable is set to any value, the interpreter will not attempt to " +"load the Python-based :term:`REPL` that requires :mod:`curses` and :mod:" "`readline`, and will instead use the traditional parser-based :term:`REPL`." msgstr "" -"Se esta variável for definida como ``1``, o interpretador não tentará " -"carregar o :term:`REPL` baseado em Python que requer :mod:`curses` e :mod:" -"`readline`, e em vez disso usará o baseado em analisador tradicional :term:" -"`REPL`." +"Se esta variável for definida como qualquer valor, o interpretador não " +"tentará carregar o :term:`REPL` baseado em Python que requer :mod:`curses` " +"e :mod:`readline`, e em vez disso usará o :term:`REPL` com o analisador " +"sintático tradicional." -#: ../../using/cmdline.rst:1209 +#: ../../using/cmdline.rst:1215 msgid "" "This environment variable can be used to set the location of a ``." "python_history`` file (by default, it is ``.python_history`` in the user's " @@ -2024,15 +2110,17 @@ msgstr "" "arquivo ``.python_history`` (por padrão, é ``.python_history`` no diretório " "inicial do usuário)." -#: ../../using/cmdline.rst:1217 +#: ../../using/cmdline.rst:1223 msgid "" "If this variable is set to ``1``, the global interpreter lock (GIL) will be " -"forced on. Setting it to ``0`` forces the GIL off." +"forced on. Setting it to ``0`` forces the GIL off (needs Python configured " +"with the :option:`--disable-gil` build option)." msgstr "" "Se esta variável for definida como ``1``, a trava global do interpretador " -"(GIL) será forçada. Definir como ``0`` força a GIL a desligar." +"(GIL) será forçada. Definir como ``0`` força a GIL a desligar (precisa do " +"Python configurado com a opção de construção :option:`--disable-gil`)." -#: ../../using/cmdline.rst:1220 +#: ../../using/cmdline.rst:1227 msgid "" "See also the :option:`-X gil <-X>` command-line option, which takes " "precedence over this variable, and :ref:`whatsnew313-free-threaded-cpython`." @@ -2040,17 +2128,18 @@ msgstr "" "Veja também a opção de linha de comando :option:`-X gil <-X>`, que tem " "precedência sobre esta variável, e :ref:`whatsnew313-free-threaded-cpython`." -#: ../../using/cmdline.rst:1223 -msgid "Needs Python configured with the :option:`--disable-gil` build option." +#: ../../using/cmdline.rst:1234 +msgid "" +"On builds where experimental just-in-time compilation is available, this " +"variable can force the JIT to be disabled (``0``) or enabled (``1``) at " +"interpreter startup." msgstr "" -"Precisa do Python configurado com a opção de construção :option:`--disable-" -"gil`." -#: ../../using/cmdline.rst:1228 +#: ../../using/cmdline.rst:1241 msgid "Debug-mode variables" msgstr "Variáveis de modo de depuração" -#: ../../using/cmdline.rst:1232 +#: ../../using/cmdline.rst:1245 msgid "" "If set, Python will dump objects and reference counts still alive after " "shutting down the interpreter." @@ -2058,14 +2147,14 @@ msgstr "" "Se definido, Python irá despejar objetos e contagens de referências ainda " "vivas após desligar o interpretador." -#: ../../using/cmdline.rst:1235 ../../using/cmdline.rst:1243 +#: ../../using/cmdline.rst:1248 ../../using/cmdline.rst:1256 msgid "" "Needs Python configured with the :option:`--with-trace-refs` build option." msgstr "" "Precisa do Python configurado com a opção de construção :option:`--with-" "trace-refs`." -#: ../../using/cmdline.rst:1239 +#: ../../using/cmdline.rst:1252 msgid "" "If set, Python will dump objects and reference counts still alive after " "shutting down the interpreter into a file under the path given as the value " @@ -2075,7 +2164,7 @@ msgstr "" "ativas após desligar o interpretador em um arquivo no caminho fornecido como " "valor para esta variável de ambiente." -#: ../../using/cmdline.rst:1249 +#: ../../using/cmdline.rst:1262 msgid "" "If this variable is set to a module, that module will be imported early in " "the interpreter lifecycle, before the :mod:`site` module is executed, and " @@ -2087,13 +2176,13 @@ msgstr "" "executado, e antes do módulo :mod:`__main__` ser criado. Portanto, o módulo " "importado não é tratado como :mod:`__main__`." -#: ../../using/cmdline.rst:1254 +#: ../../using/cmdline.rst:1267 msgid "This can be used to execute code early during Python initialization." msgstr "" "Isso pode ser usado para executar código antecipadamente durante a " "inicialização do Python." -#: ../../using/cmdline.rst:1256 +#: ../../using/cmdline.rst:1269 msgid "" "To import a submodule, use ``package.module`` as the value, like in an " "import statement." @@ -2101,7 +2190,7 @@ msgstr "" "Para importar um submódulo, use ``pacote.módulo`` como valor, como em uma " "instrução de importação." -#: ../../using/cmdline.rst:1259 +#: ../../using/cmdline.rst:1272 msgid "" "See also the :option:`-X presite <-X>` command-line option, which takes " "precedence over this variable." @@ -2109,7 +2198,7 @@ msgstr "" "Veja também a opção de linha de comando :option:`-X presite <-X>`, que tem " "precedência sobre esta variável." -#: ../../using/cmdline.rst:1262 +#: ../../using/cmdline.rst:1275 msgid "Needs Python configured with the :option:`--with-pydebug` build option." msgstr "" "Precisa do Python configurado com a opção de construção :option:`--with-" diff --git a/using/configure.po b/using/configure.po index 144d5cf18..d899662d4 100644 --- a/using/configure.po +++ b/using/configure.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:50+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-02-28 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -81,10 +81,10 @@ msgstr "Tcl/Tk 8.5.12 para o módulo :mod:`tkinter`." #: ../../using/configure.rst:32 msgid "" -"Autoconf 2.71 and aclocal 1.16.4 are required to regenerate the :file:" +"Autoconf 2.71 and aclocal 1.16.5 are required to regenerate the :file:" "`configure` script." msgstr "" -"Autoconf 2.71 e aclocal 1.16.4 são necessários para regenerar o script :file:" +"Autoconf 2.71 e aclocal 1.16.5 são necessários para regenerar o script :file:" "`configure`." #: ../../using/configure.rst:35 @@ -126,8 +126,8 @@ msgstr "" "agora é necessária para o módulo :mod:`tkinter`." #: ../../using/configure.rst:58 -msgid "Autoconf 2.71, aclocal 1.16.4 and SQLite 3.15.2 are now required." -msgstr "Autoconf 2.71, aclocal 1.16.4 e SQLite 3.15.2 agora são necessários." +msgid "Autoconf 2.71, aclocal 1.16.5 and SQLite 3.15.2 are now required." +msgstr "Autoconf 2.71, aclocal 1.16.5 e SQLite 3.15.2 agora são necessários." #: ../../using/configure.rst:61 msgid "" @@ -149,6 +149,18 @@ msgstr "" "Para reduzir as dependências de construção, o código-fonte do Python contém " "vários arquivos gerados. Comandos para regenerar todos os arquivos gerados::" +#: ../../using/configure.rst:71 +msgid "" +"make regen-all\n" +"make regen-stdlib-module-names\n" +"make regen-limited-abi\n" +"make regen-configure" +msgstr "" +"make regen-all\n" +"make regen-stdlib-module-names\n" +"make regen-limited-abi\n" +"make regen-configure" + #: ../../using/configure.rst:76 msgid "" "The ``Makefile.pre.in`` file documents generated files, their inputs, and " @@ -178,6 +190,10 @@ msgid "The container is optional, the following command can be run locally::" msgstr "" "O contêiner é opcional, o seguinte comando pode ser executado localmente::" +#: ../../using/configure.rst:89 +msgid "autoreconf -ivf -Werror" +msgstr "autoreconf -ivf -Werror" + #: ../../using/configure.rst:91 msgid "" "The generated files can change depending on the exact ``autoconf-archive``, " @@ -194,6 +210,10 @@ msgstr "Opções de configuração" msgid "List all :file:`configure` script options using::" msgstr "Liste todas as opções do :file:`configure` usando::" +#: ../../using/configure.rst:102 +msgid "./configure --help" +msgstr "./configure --help" + #: ../../using/configure.rst:104 msgid "" "See also the :file:`Misc/SpecialBuilds.txt` in the Python source " @@ -422,7 +442,7 @@ msgstr "" "Na saída do Python, despeja as estatísticas se a coleta de estatísticas " "estiver ativada e não apagada." -#: ../../using/configure.rst:236 ../../using/configure.rst:708 +#: ../../using/configure.rst:236 ../../using/configure.rst:725 msgid "Effects:" msgstr "Efeitos:" @@ -605,197 +625,242 @@ msgid "See :ref:`whatsnew313-free-threaded-cpython` for more detail." msgstr "Veja :ref:`whatsnew313-free-threaded-cpython` para mais detalhes." #: ../../using/configure.rst:308 +msgid "" +"Indicate how to integrate the :ref:`JIT compiler `." +msgstr "" +"Indica como integrar o :ref:`compilador JIT `." + +#: ../../using/configure.rst:310 +msgid "``no`` - build the interpreter without the JIT." +msgstr "``no`` - constrói o interpretador sem o JIT." + +#: ../../using/configure.rst:311 +msgid "``yes`` - build the interpreter with the JIT." +msgstr "``yes`` - constrói o interpretador com o JIT." + +#: ../../using/configure.rst:312 +msgid "" +"``yes-off`` - build the interpreter with the JIT but disable it by default." +msgstr "" +"``yes-off`` - constrói o interpretador com o JIT, mas desabilitado por " +"padrão." + +#: ../../using/configure.rst:313 +msgid "" +"``interpreter`` - build the interpreter without the JIT, but with the tier 2 " +"enabled interpreter." +msgstr "" +"``interpreter`` - constrói o interpretador sem o JIT, mas com o " +"interpretador habilitado para nível 2." + +#: ../../using/configure.rst:315 +msgid "" +"By convention, ``--enable-experimental-jit`` is a shorthand for ``--enable-" +"experimental-jit=yes``." +msgstr "" +"Por convenção, ``--enable-experimental-jit`` é uma abreviação de ``--enable-" +"experimental-jit=yes``." + +#: ../../using/configure.rst:319 +msgid "" +"When building CPython with JIT enabled, ensure that your system has Python " +"3.11 or later installed." +msgstr "" +"Ao construir o CPython com o JIT habilitado, certifique-se de que seu " +"sistema tenha o Python 3.11 ou posterior instalado." + +#: ../../using/configure.rst:325 msgid "Path to ``pkg-config`` utility." msgstr "Caminho para o utilitário ``pkg-config``." -#: ../../using/configure.rst:313 +#: ../../using/configure.rst:330 msgid "``pkg-config`` options." msgstr "Opções do ``pkg-config``." -#: ../../using/configure.rst:317 +#: ../../using/configure.rst:334 msgid "C compiler options" msgstr "Opções do compilador C" -#: ../../using/configure.rst:321 ../../using/configure.rst:1228 +#: ../../using/configure.rst:338 ../../using/configure.rst:1251 msgid "C compiler command." msgstr "Comando do compilador C." -#: ../../using/configure.rst:325 ../../using/configure.rst:1240 +#: ../../using/configure.rst:342 ../../using/configure.rst:1263 msgid "C compiler flags." msgstr "Sinalizadores do compilador C." -#: ../../using/configure.rst:329 +#: ../../using/configure.rst:346 msgid "C preprocessor command." msgstr "Comando do pré-processador C." -#: ../../using/configure.rst:333 +#: ../../using/configure.rst:350 msgid "C preprocessor flags, e.g. :samp:`-I{include_dir}`." msgstr "Sinalizadores do pré-processador C, p.ex., :samp:`-I{include_dir}`." -#: ../../using/configure.rst:337 ../../using/configure.rst:779 +#: ../../using/configure.rst:354 ../../using/configure.rst:796 msgid "Linker options" msgstr "Opções da ligação" -#: ../../using/configure.rst:341 +#: ../../using/configure.rst:358 msgid "Linker flags, e.g. :samp:`-L{library_directory}`." msgstr "Sinalizadores do vinculador. p.ex., :samp:`-L{library_directory}`." -#: ../../using/configure.rst:345 +#: ../../using/configure.rst:362 msgid "Libraries to pass to the linker, e.g. :samp:`-l{library}`." msgstr "Bibliotecas para passar para o vinculador, p.ex. :samp:`-l{library}`." -#: ../../using/configure.rst:349 +#: ../../using/configure.rst:366 msgid "Name for machine-dependent library files." msgstr "Nome para arquivos de biblioteca dependentes de máquina." -#: ../../using/configure.rst:353 +#: ../../using/configure.rst:370 msgid "Options for third-party dependencies" msgstr "Opções para dependências de terceiros" -#: ../../using/configure.rst:360 +#: ../../using/configure.rst:377 msgid "" "C compiler and linker flags to link Python to ``libbz2``, used by :mod:`bz2` " "module, overriding ``pkg-config``." msgstr "" "Sinalizadores de compilador C e vinculador para vincular Python a " -"``libbz2``, usados ​​pelo módulo :mod:`bz2`, substituindo ``pkg-config``." +"``libbz2``, usados pelo módulo :mod:`bz2`, substituindo ``pkg-config``." -#: ../../using/configure.rst:366 +#: ../../using/configure.rst:383 msgid "" "C compiler and linker flags for ``libncurses`` or ``libncursesw``, used by :" "mod:`curses` module, overriding ``pkg-config``." msgstr "" "Sinalizadores de compilador C e vinculador para ``libncurses`` ou " -"``libncursesw``, usados ​​pelo módulo :mod:`curses`, substituindo ``pkg-" +"``libncursesw``, usados pelo módulo :mod:`curses`, substituindo ``pkg-" "config``." -#: ../../using/configure.rst:372 +#: ../../using/configure.rst:389 msgid "C compiler and linker flags for ``gdbm``." msgstr "Sinalizadores de compilador C e vinculador para ``gdbm``." -#: ../../using/configure.rst:377 +#: ../../using/configure.rst:394 msgid "" "C compiler and linker flags for ``libb2`` (:ref:`BLAKE2 `), " "used by :mod:`hashlib` module, overriding ``pkg-config``." msgstr "" "Sinalizadores de compilador C e vinculador para ``libb2`` (:ref:`BLAKE2 " -"`), usados ​​pelo módulo :mod:`hashlib`, substituindo ``pkg-" +"`), usados pelo módulo :mod:`hashlib`, substituindo ``pkg-" "config``." -#: ../../using/configure.rst:383 +#: ../../using/configure.rst:400 msgid "" "C compiler and linker flags for ``libedit``, used by :mod:`readline` module, " "overriding ``pkg-config``." msgstr "" -"Sinalizadores de compilador C e vinculador para ``libedit``, usados ​​pelo " +"Sinalizadores de compilador C e vinculador para ``libedit``, usados pelo " "módulo :mod:`readline`, substituindo ``pkg-config``." -#: ../../using/configure.rst:389 +#: ../../using/configure.rst:406 msgid "" "C compiler and linker flags for ``libffi``, used by :mod:`ctypes` module, " "overriding ``pkg-config``." msgstr "" -"Sinalizadores de compilador C e vinculador para ``libffi``, usados ​​pelo " +"Sinalizadores de compilador C e vinculador para ``libffi``, usados pelo " "módulo :mod:`ctypes`, substituindo ``pkg-config``." -#: ../../using/configure.rst:395 +#: ../../using/configure.rst:412 msgid "" "C compiler and linker flags for ``libmpdec``, used by :mod:`decimal` module, " "overriding ``pkg-config``." msgstr "" -"Sinalizadores de compilador C e vinculador para ``libmpdec``, usados ​​pelo " +"Sinalizadores de compilador C e vinculador para ``libmpdec``, usados pelo " "módulo :mod:`decimal`, substituindo ``pkg-config``." -#: ../../using/configure.rst:400 +#: ../../using/configure.rst:417 msgid "" "These environment variables have no effect unless :option:`--with-system-" "libmpdec` is specified." msgstr "" -"Estas variáveis ​​de ambiente não têm efeito a menos que :option:`--with-" +"Estas variáveis de ambiente não têm efeito a menos que :option:`--with-" "system-libmpdec` seja especificado." -#: ../../using/configure.rst:406 +#: ../../using/configure.rst:423 msgid "" "C compiler and linker flags for ``liblzma``, used by :mod:`lzma` module, " "overriding ``pkg-config``." msgstr "" -"Sinalizadores de compilador C e vinculador para ``liblzma``, usados ​​pelo " +"Sinalizadores de compilador C e vinculador para ``liblzma``, usados pelo " "módulo :mod:`lzma`, substituindo ``pkg-config``." -#: ../../using/configure.rst:412 +#: ../../using/configure.rst:429 msgid "" "C compiler and linker flags for ``libreadline``, used by :mod:`readline` " "module, overriding ``pkg-config``." msgstr "" -"Sinalizadores de compilador C e vinculador para ``libreadline``, usados ​​pelo " +"Sinalizadores de compilador C e vinculador para ``libreadline``, usados pelo " "módulo :mod:`readline`, substituindo ``pkg-config``." -#: ../../using/configure.rst:418 +#: ../../using/configure.rst:435 msgid "" "C compiler and linker flags for ``libsqlite3``, used by :mod:`sqlite3` " "module, overriding ``pkg-config``." msgstr "" -"Sinalizadores de compilador C e vinculador para ``libsqlite3``, usados ​​pelo " +"Sinalizadores de compilador C e vinculador para ``libsqlite3``, usados pelo " "módulo :mod:`sqlite3`, substituindo ``pkg-config``." -#: ../../using/configure.rst:424 +#: ../../using/configure.rst:441 msgid "" "C compiler and linker flags for ``libuuid``, used by :mod:`uuid` module, " "overriding ``pkg-config``." msgstr "" -"Sinalizadores de compilador C e vinculador para ``libuuid``, usados ​​pelo " +"Sinalizadores de compilador C e vinculador para ``libuuid``, usados pelo " "módulo :mod:`uuid`, substituindo ``pkg-config``." -#: ../../using/configure.rst:430 +#: ../../using/configure.rst:447 msgid "C compiler and linker flags for PANEL, overriding ``pkg-config``." msgstr "" "Sinalizadores de compilador C e vinculador para PANEL, substituindo ``pkg-" "config``." -#: ../../using/configure.rst:432 +#: ../../using/configure.rst:449 msgid "" "C compiler and linker flags for ``libpanel`` or ``libpanelw``, used by :mod:" "`curses.panel` module, overriding ``pkg-config``." msgstr "" "Sinalizadores de compilador C e vinculador para ``libpanel`` ou " -"``libpanelw``, usados ​​pelo módulo :mod:`curses.panel`, substituindo ``pkg-" +"``libpanelw``, usados pelo módulo :mod:`curses.panel`, substituindo ``pkg-" "config``." -#: ../../using/configure.rst:438 +#: ../../using/configure.rst:455 msgid "C compiler and linker flags for TCLTK, overriding ``pkg-config``." msgstr "" "Sinalizadores de compilador C e vinculador para TCLTK, substituindo ``pkg-" "config``.;" -#: ../../using/configure.rst:443 +#: ../../using/configure.rst:460 msgid "" "C compiler and linker flags for ``libzlib``, used by :mod:`gzip` module, " "overriding ``pkg-config``." msgstr "" -"Sinalizadores de compilador C e vinculador para ``libzlib``, usados ​​pelo " +"Sinalizadores de compilador C e vinculador para ``libzlib``, usados pelo " "módulo :mod:`gzip`, substituindo ``pkg-config``." -#: ../../using/configure.rst:448 +#: ../../using/configure.rst:465 msgid "WebAssembly Options" msgstr "Opções de WebAssembly" -#: ../../using/configure.rst:452 +#: ../../using/configure.rst:469 msgid "Set build flavor for ``wasm32-emscripten``." msgstr "Define o \"sabor\" de construção para ``wasm32-emscripten``." -#: ../../using/configure.rst:454 +#: ../../using/configure.rst:471 msgid "``browser`` (default): preload minimal stdlib, default MEMFS." msgstr "``browser`` (padrão): pré-carrega stdlib mínima, MEMFS padrão." -#: ../../using/configure.rst:455 +#: ../../using/configure.rst:472 msgid "``node``: NODERAWFS and pthread support." msgstr "``node``: suporte a NODERAWFS e pthread." -#: ../../using/configure.rst:461 +#: ../../using/configure.rst:478 msgid "Turn on dynamic linking support for WASM." msgstr "Ativa o suporte de vinculação dinâmica para WASM." -#: ../../using/configure.rst:463 +#: ../../using/configure.rst:480 msgid "" "Dynamic linking enables ``dlopen``. File size of the executable increases " "due to limited dead code elimination and additional features." @@ -803,15 +868,15 @@ msgstr "" "A vinculação dinâmica permite ``dlopen``. O tamanho do arquivo executável " "aumenta devido à eliminação limitada de código morto e recursos adicionais." -#: ../../using/configure.rst:470 +#: ../../using/configure.rst:487 msgid "Turn on pthreads support for WASM." msgstr "Ativa o suporte a pthreads para WASM." -#: ../../using/configure.rst:476 +#: ../../using/configure.rst:493 msgid "Install Options" msgstr "Opções de instalação" -#: ../../using/configure.rst:480 +#: ../../using/configure.rst:497 msgid "" "Install architecture-independent files in PREFIX. On Unix, it defaults to :" "file:`/usr/local`." @@ -819,13 +884,13 @@ msgstr "" "Instala arquivos independentes de arquitetura em PREFIX. No Unix, o padrão " "é :file:`/usr/local`." -#: ../../using/configure.rst:483 +#: ../../using/configure.rst:500 msgid "This value can be retrieved at runtime using :data:`sys.prefix`." msgstr "" "Este valor pode ser recuperado em tempo de execução usando :data:`sys." "prefix`." -#: ../../using/configure.rst:485 +#: ../../using/configure.rst:502 msgid "" "As an example, one can use ``--prefix=\"$HOME/.local/\"`` to install a " "Python in its home directory." @@ -833,7 +898,7 @@ msgstr "" "Como exemplo, pode-se usar ``--prefix=\"$HOME/.local/\"`` para instalar um " "Python em seu diretório pessoal (home)." -#: ../../using/configure.rst:490 +#: ../../using/configure.rst:507 msgid "" "Install architecture-dependent files in EPREFIX, defaults to :option:`--" "prefix`." @@ -841,13 +906,13 @@ msgstr "" "Instala arquivos dependentes de arquitetura no EPREFIX, o padrão é :option:" "`--prefix`." -#: ../../using/configure.rst:492 +#: ../../using/configure.rst:509 msgid "This value can be retrieved at runtime using :data:`sys.exec_prefix`." msgstr "" "Este valor pode ser recuperado em tempo de execução usando :data:`sys." "exec_prefix`." -#: ../../using/configure.rst:496 +#: ../../using/configure.rst:513 msgid "" "Don't build nor install test modules, like the :mod:`test` package or the :" "mod:`!_testcapi` extension module (built and installed by default)." @@ -855,12 +920,12 @@ msgstr "" "Não constrói nem instala módulos de teste, como o pacote :mod:`test` ou o " "módulo de extensão :mod:`!_testcapi` (construído e instalado por padrão)." -#: ../../using/configure.rst:503 +#: ../../using/configure.rst:520 msgid "Select the :mod:`ensurepip` command run on Python installation:" msgstr "" "Seleciona o comando :mod:`ensurepip` executado na instalação do Python:" -#: ../../using/configure.rst:505 +#: ../../using/configure.rst:522 msgid "" "``upgrade`` (default): run ``python -m ensurepip --altinstall --upgrade`` " "command." @@ -868,19 +933,19 @@ msgstr "" "``upgrade`` (padrão): executa o comando ``python -m ensurepip --altinstall --" "upgrade``." -#: ../../using/configure.rst:507 +#: ../../using/configure.rst:524 msgid "``install``: run ``python -m ensurepip --altinstall`` command;" msgstr "``install``: executa o comando ``python -m ensurepip --altinstall``;" -#: ../../using/configure.rst:508 +#: ../../using/configure.rst:525 msgid "``no``: don't run ensurepip;" msgstr "``no``: não executa ensurepip;" -#: ../../using/configure.rst:514 +#: ../../using/configure.rst:531 msgid "Performance options" msgstr "Opções de desempenho" -#: ../../using/configure.rst:516 +#: ../../using/configure.rst:533 msgid "" "Configuring Python using ``--enable-optimizations --with-lto`` (PGO + LTO) " "is recommended for best performance. The experimental ``--enable-bolt`` flag " @@ -890,7 +955,7 @@ msgstr "" "é o recomendado para melhor desempenho. O sinalizador experimental ``--" "enable-bolt`` também pode ser usado para melhorar o desempenho." -#: ../../using/configure.rst:522 +#: ../../using/configure.rst:539 msgid "" "Enable Profile Guided Optimization (PGO) using :envvar:`PROFILE_TASK` " "(disabled by default)." @@ -898,7 +963,7 @@ msgstr "" "Habilita a otimização guiada por perfil (PGO, do inglês Profile Guided " "Optimization) usando :envvar:`PROFILE_TASK` (desabilitado por padrão)." -#: ../../using/configure.rst:525 +#: ../../using/configure.rst:542 msgid "" "The C compiler Clang requires ``llvm-profdata`` program for PGO. On macOS, " "GCC also requires it: GCC is just an alias to Clang on macOS." @@ -906,7 +971,7 @@ msgstr "" "O compilador C Clang requer o programa ``llvm-profdata`` para PGO. No macOS, " "o GCC também exige: o GCC é apenas um apelido para o Clang no macOS." -#: ../../using/configure.rst:528 +#: ../../using/configure.rst:545 msgid "" "Disable also semantic interposition in libpython if ``--enable-shared`` and " "GCC is used: add ``-fno-semantic-interposition`` to the compiler and linker " @@ -916,7 +981,7 @@ msgstr "" "shared`` e GCC forem usados: adiciona ``-fno-semantic-interposition`` aos " "sinalizadores do compilador e do vinculador." -#: ../../using/configure.rst:534 +#: ../../using/configure.rst:551 msgid "" "During the build, you may encounter compiler warnings about profile data not " "being available for some source files. These warnings are harmless, as only " @@ -931,11 +996,11 @@ msgstr "" "Clang, suprima-os manualmente adicionando ``-Wno-profile-instr-unprofiled`` " "a :envvar:`CFLAGS`." -#: ../../using/configure.rst:543 +#: ../../using/configure.rst:560 msgid "Use ``-fno-semantic-interposition`` on GCC." msgstr "Usa ``-fno-semantic-interposition`` no GCC." -#: ../../using/configure.rst:548 +#: ../../using/configure.rst:565 msgid "" "Environment variable used in the Makefile: Python command line arguments for " "the PGO generation task." @@ -943,21 +1008,21 @@ msgstr "" "Variável de ambiente usada no Makefile: argumentos de linha de comando do " "Python para a tarefa de geração de PGO." -#: ../../using/configure.rst:551 +#: ../../using/configure.rst:568 msgid "Default: ``-m test --pgo --timeout=$(TESTTIMEOUT)``." msgstr "Padrão: ``-m test --pgo --timeout=$(TESTTIMEOUT)``." -#: ../../using/configure.rst:555 +#: ../../using/configure.rst:572 msgid "Task failure is no longer ignored silently." msgstr "A falha da tarefa não é mais ignorada silenciosamente." -#: ../../using/configure.rst:560 +#: ../../using/configure.rst:577 msgid "Enable Link Time Optimization (LTO) in any build (disabled by default)." msgstr "" "Habilita o otimização em tempo de vinculação (LTO, do inglês Link Time " -"Optimization) em qualquer compilação (desabilitado por padrão)." +"Optimization) em qualquer construção (desabilitado por padrão)." -#: ../../using/configure.rst:562 +#: ../../using/configure.rst:579 msgid "" "The C compiler Clang requires ``llvm-ar`` for LTO (``ar`` on macOS), as well " "as an LTO-aware linker (``ld.gold`` or ``lld``)." @@ -965,11 +1030,11 @@ msgstr "" "O compilador C Clang requer ``llvm-ar`` para LTO (``ar`` no macOS), bem como " "um vinculador compatível com LTO (``ld.gold`` ou ``lld``)." -#: ../../using/configure.rst:567 +#: ../../using/configure.rst:584 msgid "To use ThinLTO feature, use ``--with-lto=thin`` on Clang." msgstr "Para usar o recurso ThinLTO, use ``--with-lto=thin`` no Clang." -#: ../../using/configure.rst:570 +#: ../../using/configure.rst:587 msgid "" "Use ThinLTO as the default optimization policy on Clang if the compiler " "accepts the flag." @@ -977,7 +1042,7 @@ msgstr "" "Usa ThinLTO como política de otimização padrão no Clang se o compilador " "aceitar o sinalizador." -#: ../../using/configure.rst:575 +#: ../../using/configure.rst:592 msgid "" "Enable usage of the `BOLT post-link binary optimizer `_ (disabled by default)." @@ -985,7 +1050,7 @@ msgstr "" "Habilita o uso do `otimizador binário pós-vinculação BOLT `_ (desabilitado por padrão)." -#: ../../using/configure.rst:579 +#: ../../using/configure.rst:596 msgid "" "BOLT is part of the LLVM project but is not always included in their binary " "distributions. This flag requires that ``llvm-bolt`` and ``merge-fdata`` are " @@ -995,7 +1060,7 @@ msgstr "" "distribuições binárias. Este sinalizador requer que ``llvm-bolt`` e ``merge-" "fdata`` estejam disponíveis." -#: ../../using/configure.rst:583 +#: ../../using/configure.rst:600 msgid "" "BOLT is still a fairly new project so this flag should be considered " "experimental for now. Because this tool operates on machine code its success " @@ -1013,7 +1078,7 @@ msgstr "" "LLVM 16 são conhecidas por travar o BOLT em alguns cenários. O uso do LLVM " "16 ou mais recente para otimização do BOLT é fortemente incentivado." -#: ../../using/configure.rst:591 +#: ../../using/configure.rst:608 msgid "" "The :envvar:`!BOLT_INSTRUMENT_FLAGS` and :envvar:`!BOLT_APPLY_FLAGS` :" "program:`configure` variables can be defined to override the default set of " @@ -1025,7 +1090,7 @@ msgstr "" "padrão de argumentos para :program:`llvm-bolt` para instrumentar e aplicar " "dados BOLT aos binários , respectivamente." -#: ../../using/configure.rst:600 +#: ../../using/configure.rst:617 msgid "" "Arguments to ``llvm-bolt`` when creating a `BOLT optimized binary `_." @@ -1033,11 +1098,11 @@ msgstr "" "Argumentos para ``llvm-bolt`` ao criar um `binário otimizado com BOLT " "`_." -#: ../../using/configure.rst:607 +#: ../../using/configure.rst:624 msgid "Arguments to ``llvm-bolt`` when instrumenting binaries." msgstr "Argumentos para ``llvm-bolt`` ao instrumentar binários." -#: ../../using/configure.rst:613 +#: ../../using/configure.rst:630 msgid "" "Enable computed gotos in evaluation loop (enabled by default on supported " "compilers)." @@ -1045,18 +1110,18 @@ msgstr "" "Habilita \"gotos\" computados no laço de avaliação (habilitado por padrão em " "compiladores suportados)." -#: ../../using/configure.rst:618 +#: ../../using/configure.rst:635 msgid "" "Disable the fast :ref:`mimalloc ` allocator (enabled by default)." msgstr "" "Desativa o alocador rápido :ref:`mimalloc ` (habilitado por " "padrão)." -#: ../../using/configure.rst:621 ../../using/configure.rst:628 +#: ../../using/configure.rst:638 ../../using/configure.rst:645 msgid "See also :envvar:`PYTHONMALLOC` environment variable." msgstr "Veja também a variável de ambiente :envvar:`PYTHONMALLOC`." -#: ../../using/configure.rst:625 +#: ../../using/configure.rst:642 msgid "" "Disable the specialized Python memory allocator :ref:`pymalloc ` " "(enabled by default)." @@ -1064,7 +1129,7 @@ msgstr "" "Desabilita o alocador de memória especializado do Python :ref:`pymalloc " "` (habilitado por padrão)." -#: ../../using/configure.rst:632 +#: ../../using/configure.rst:649 msgid "" "Disable static documentation strings to reduce the memory footprint (enabled " "by default). Documentation strings defined in Python are not affected." @@ -1073,21 +1138,21 @@ msgstr "" "memória (habilitado por padrão). As strings de documentação definidas em " "Python não são afetadas." -#: ../../using/configure.rst:635 +#: ../../using/configure.rst:652 msgid "Don't define the ``WITH_DOC_STRINGS`` macro." msgstr "Não define a macro ``WITH_DOC_STRINGS``." -#: ../../using/configure.rst:637 +#: ../../using/configure.rst:654 msgid "See the ``PyDoc_STRVAR()`` macro." msgstr "Veja a macro ``PyDoc_STRVAR()``." -#: ../../using/configure.rst:641 +#: ../../using/configure.rst:658 msgid "Enable C-level code profiling with ``gprof`` (disabled by default)." msgstr "" "Habilita o perfil de código a nível C com ``gprof`` (desabilitado por " "padrão)." -#: ../../using/configure.rst:645 +#: ../../using/configure.rst:662 msgid "" "Add ``-fstrict-overflow`` to the C compiler flags (by default we add ``-fno-" "strict-overflow`` instead)." @@ -1095,11 +1160,11 @@ msgstr "" "Adiciona ``-fstrict-overflow`` aos sinalizadores do compilador C (por padrão " "adicionamos ``-fno-strict-overflow``)." -#: ../../using/configure.rst:652 +#: ../../using/configure.rst:669 msgid "Python Debug Build" msgstr "Compilação de depuração do Python" -#: ../../using/configure.rst:654 +#: ../../using/configure.rst:671 msgid "" "A debug build is Python built with the :option:`--with-pydebug` configure " "option." @@ -1107,11 +1172,11 @@ msgstr "" "Uma compilação de depuração é Python compilada com a opção de configuração :" "option:`--with-pydebug`." -#: ../../using/configure.rst:657 +#: ../../using/configure.rst:674 msgid "Effects of a debug build:" msgstr "Efeitos de uma compilação de depuração:" -#: ../../using/configure.rst:659 +#: ../../using/configure.rst:676 msgid "" "Display all warnings by default: the list of default warning filters is " "empty in the :mod:`warnings` module." @@ -1119,19 +1184,19 @@ msgstr "" "Exibe todos os avisos por padrão: a lista de filtros de aviso padrão está " "vazia no módulo :mod:`warnings`." -#: ../../using/configure.rst:661 +#: ../../using/configure.rst:678 msgid "Add ``d`` to :data:`sys.abiflags`." msgstr "Adiciona ``d`` a :data:`sys.abiflags`." -#: ../../using/configure.rst:662 +#: ../../using/configure.rst:679 msgid "Add :func:`!sys.gettotalrefcount` function." msgstr "Adiciona a função :func:`!sys.gettotalrefcount`." -#: ../../using/configure.rst:663 +#: ../../using/configure.rst:680 msgid "Add :option:`-X showrefcount <-X>` command line option." msgstr "Adiciona a opção de linha de comando :option:`-X showrefcount <-X>`." -#: ../../using/configure.rst:664 +#: ../../using/configure.rst:681 msgid "" "Add :option:`-d` command line option and :envvar:`PYTHONDEBUG` environment " "variable to debug the parser." @@ -1139,7 +1204,7 @@ msgstr "" "Adiciona a opção de linha de comando :option:`-d` e a variável de ambiente :" "envvar:`PYTHONDEBUG` para depurar o analisador sintático." -#: ../../using/configure.rst:666 +#: ../../using/configure.rst:683 msgid "" "Add support for the ``__lltrace__`` variable: enable low-level tracing in " "the bytecode evaluation loop if the variable is defined." @@ -1147,7 +1212,7 @@ msgstr "" "Adiciona suporte para a variável ``__lltrace__``: habilita o rastreamento de " "baixo nível no laço de avaliação de bytecode se a variável estiver definida." -#: ../../using/configure.rst:668 +#: ../../using/configure.rst:685 msgid "" "Install :ref:`debug hooks on memory allocators ` " "to detect buffer overflow and other memory errors." @@ -1155,11 +1220,11 @@ msgstr "" "Instala :ref:`ganchos de depuração nos alocadores de memória ` para detectar estouro de buffer e outros erros de memória." -#: ../../using/configure.rst:670 +#: ../../using/configure.rst:687 msgid "Define ``Py_DEBUG`` and ``Py_REF_DEBUG`` macros." msgstr "Define as macros ``Py_DEBUG`` e ``Py_REF_DEBUG``." -#: ../../using/configure.rst:671 +#: ../../using/configure.rst:688 msgid "" "Add runtime checks: code surrounded by ``#ifdef Py_DEBUG`` and ``#endif``. " "Enable ``assert(...)`` and ``_PyObject_ASSERT(...)`` assertions: don't set " @@ -1172,11 +1237,11 @@ msgstr "" "configuração :option:`--with-assertions` opção). Principais verificações de " "tempo de execução:" -#: ../../using/configure.rst:676 +#: ../../using/configure.rst:693 msgid "Add sanity checks on the function arguments." msgstr "Adiciona verificações de sanidade nos argumentos da função." -#: ../../using/configure.rst:677 +#: ../../using/configure.rst:694 msgid "" "Unicode and int objects are created with their memory filled with a pattern " "to detect usage of uninitialized objects." @@ -1184,7 +1249,7 @@ msgstr "" "Objetos Unicode e int são criados com sua memória preenchida com um padrão " "para detectar o uso de objetos não inicializados." -#: ../../using/configure.rst:679 +#: ../../using/configure.rst:696 msgid "" "Ensure that functions which can clear or replace the current exception are " "not called with an exception raised." @@ -1192,11 +1257,11 @@ msgstr "" "Garante que as funções que podem limpar ou substituir a exceção atual não " "sejam chamadas com uma exceção levantada." -#: ../../using/configure.rst:681 +#: ../../using/configure.rst:698 msgid "Check that deallocator functions don't change the current exception." msgstr "Verifica se as funções desalocadoras não alteram a exceção atual." -#: ../../using/configure.rst:682 +#: ../../using/configure.rst:699 msgid "" "The garbage collector (:func:`gc.collect` function) runs some basic checks " "on objects consistency." @@ -1204,7 +1269,7 @@ msgstr "" "O coletor de lixo (função :func:`gc.collect`) executa algumas verificações " "básicas na consistência dos objetos." -#: ../../using/configure.rst:684 +#: ../../using/configure.rst:701 msgid "" "The :c:macro:`!Py_SAFE_DOWNCAST()` macro checks for integer underflow and " "overflow when downcasting from wide types to narrow types." @@ -1212,7 +1277,7 @@ msgstr "" "A macro :c:macro:`!Py_SAFE_DOWNCAST()` verifica o underflow e o overflow de " "inteiros ao fazer o downcast de tipos largos para tipos estreitos." -#: ../../using/configure.rst:687 +#: ../../using/configure.rst:704 msgid "" "See also the :ref:`Python Development Mode ` and the :option:`--" "with-trace-refs` configure option." @@ -1220,7 +1285,7 @@ msgstr "" "Veja também o :ref:`Modo de Desenvolvimento do Python ` e a opção " "de configuração :option:`--with-trace-refs`." -#: ../../using/configure.rst:690 +#: ../../using/configure.rst:707 msgid "" "Release builds and debug builds are now ABI compatible: defining the " "``Py_DEBUG`` macro no longer implies the ``Py_TRACE_REFS`` macro (see the :" @@ -1230,11 +1295,11 @@ msgstr "" "com ABI: definir a macro ``Py_DEBUG`` não implica mais na macro " "``Py_TRACE_REFS`` (consulte a opção :option:`--with-trace-refs`)." -#: ../../using/configure.rst:697 +#: ../../using/configure.rst:714 msgid "Debug options" msgstr "Opções de depuração" -#: ../../using/configure.rst:701 +#: ../../using/configure.rst:718 msgid "" ":ref:`Build Python in debug mode `: define the ``Py_DEBUG`` " "macro (disabled by default)." @@ -1242,25 +1307,25 @@ msgstr "" ":ref:`Construção de depuração do Python `: define a macro " "``Py_DEBUG`` (desabilitada por padrão)." -#: ../../using/configure.rst:706 +#: ../../using/configure.rst:723 msgid "Enable tracing references for debugging purpose (disabled by default)." msgstr "" "Habilita referências de rastreamento para fins de depuração (desabilitado " "por padrão)." -#: ../../using/configure.rst:710 +#: ../../using/configure.rst:727 msgid "Define the ``Py_TRACE_REFS`` macro." msgstr "Define a macro ``Py_TRACE_REFS``." -#: ../../using/configure.rst:711 -msgid "Add :func:`!sys.getobjects` function." -msgstr "Adiciona a função :func:`!sys.getobjects`." +#: ../../using/configure.rst:728 +msgid "Add :func:`sys.getobjects` function." +msgstr "Adiciona a função :func:`sys.getobjects`." -#: ../../using/configure.rst:712 +#: ../../using/configure.rst:729 msgid "Add :envvar:`PYTHONDUMPREFS` environment variable." msgstr "Adiciona a variável de ambiente :envvar:`PYTHONDUMPREFS`." -#: ../../using/configure.rst:714 +#: ../../using/configure.rst:731 msgid "" "The :envvar:`PYTHONDUMPREFS` environment variable can be used to dump " "objects and reference counts still alive at Python exit." @@ -1268,12 +1333,12 @@ msgstr "" "A variável de ambiente :envvar:`PYTHONDUMPREFS` pode ser usada para despejar " "objetos e contagens de referências ainda ativas na saída do Python." -#: ../../using/configure.rst:717 +#: ../../using/configure.rst:734 msgid ":ref:`Statically allocated objects ` are not traced." msgstr "" ":ref:`Objetos alocados estaticamente ` não são rastreados." -#: ../../using/configure.rst:721 +#: ../../using/configure.rst:738 msgid "" "This build is now ABI compatible with release build and :ref:`debug build " "`." @@ -1281,7 +1346,7 @@ msgstr "" "Esta construção agora é compatibilidade de ABI com a construção de " "lançamento e :ref:`construção de depuração `." -#: ../../using/configure.rst:727 +#: ../../using/configure.rst:744 msgid "" "Build with C assertions enabled (default is no): ``assert(...);`` and " "``_PyObject_ASSERT(...);``." @@ -1289,7 +1354,7 @@ msgstr "" "Constrói com asserções C habilitadas (o padrão é não): ``assert(...);`` e " "``_PyObject_ASSERT(...);``." -#: ../../using/configure.rst:730 +#: ../../using/configure.rst:747 msgid "" "If set, the ``NDEBUG`` macro is not defined in the :envvar:`OPT` compiler " "variable." @@ -1297,7 +1362,7 @@ msgstr "" "Se definido, a macro ``NDEBUG`` não é definida na variável do compilador :" "envvar:`OPT`." -#: ../../using/configure.rst:733 +#: ../../using/configure.rst:750 msgid "" "See also the :option:`--with-pydebug` option (:ref:`debug build `) which also enables assertions." @@ -1305,36 +1370,36 @@ msgstr "" "Veja também a opção :option:`--with-pydebug` (:ref:`construção de depuração " "`) que também habilita asserções." -#: ../../using/configure.rst:740 +#: ../../using/configure.rst:757 msgid "Enable Valgrind support (default is no)." msgstr "Habilita suporte ao Valgrind (o padrão é não)." -#: ../../using/configure.rst:744 +#: ../../using/configure.rst:761 msgid "Enable DTrace support (default is no)." msgstr "Habilita suporte ao DTrace (o padrão é não)." -#: ../../using/configure.rst:746 +#: ../../using/configure.rst:763 msgid "" "See :ref:`Instrumenting CPython with DTrace and SystemTap `." msgstr "" "Veja :ref:`Instrumentando o CPython com DTrace e SystemTap " "`." -#: ../../using/configure.rst:753 +#: ../../using/configure.rst:770 msgid "" "Enable AddressSanitizer memory error detector, ``asan`` (default is no)." msgstr "" "Habilita o detector de erros de memória AddressSanitizer, ``asan`` (o padrão " "é não)." -#: ../../using/configure.rst:759 +#: ../../using/configure.rst:776 msgid "" "Enable MemorySanitizer allocation error detector, ``msan`` (default is no)." msgstr "" "Habilita o detector de erros de alocação do MemorySanitizer, ``msan`` (o " "padrão é não)." -#: ../../using/configure.rst:765 +#: ../../using/configure.rst:782 msgid "" "Enable UndefinedBehaviorSanitizer undefined behaviour detector, ``ubsan`` " "(default is no)." @@ -1342,19 +1407,19 @@ msgstr "" "Habilita o detector de comportamento indefinido UndefinedBehaviorSanitizer, " "``ubsan`` (o padrão é não)." -#: ../../using/configure.rst:772 +#: ../../using/configure.rst:789 msgid "Enable ThreadSanitizer data race detector, ``tsan`` (default is no)." msgstr "" "Habilita o detector de corrida de dados ThreadSanitizer, ``tsan`` (o padrão " "é não)." -#: ../../using/configure.rst:783 +#: ../../using/configure.rst:800 msgid "Enable building a shared Python library: ``libpython`` (default is no)." msgstr "" "Habilita a construção de uma biblioteca Python compartilhada: ``libpython`` " "(o padrão é não)." -#: ../../using/configure.rst:787 +#: ../../using/configure.rst:804 msgid "" "Do not build ``libpythonMAJOR.MINOR.a`` and do not install ``python.o`` " "(built and enabled by default)." @@ -1362,15 +1427,15 @@ msgstr "" "Não constrói ``libpythonMAJOR.MINOR.a`` e não instala ``python.o`` " "(construído e habilitado por padrão)." -#: ../../using/configure.rst:794 +#: ../../using/configure.rst:811 msgid "Libraries options" msgstr "Opções da biblioteca" -#: ../../using/configure.rst:798 +#: ../../using/configure.rst:815 msgid "Link against additional libraries (default is no)." msgstr "Vincula bibliotecas adicionais (o padrão é não)." -#: ../../using/configure.rst:802 +#: ../../using/configure.rst:819 msgid "" "Build the :mod:`!pyexpat` module using an installed ``expat`` library " "(default is no)." @@ -1378,7 +1443,7 @@ msgstr "" "Constrói o módulo :mod:`!pyexpat` usando uma biblioteca ``expat`` instalada " "(o padrão é não)." -#: ../../using/configure.rst:807 +#: ../../using/configure.rst:824 msgid "" "Build the ``_decimal`` extension module using an installed ``mpdecimal`` " "library, see the :mod:`decimal` module (default is yes)." @@ -1386,11 +1451,11 @@ msgstr "" "Constrói o módulo de extensão ``_decimal`` usando uma biblioteca " "``mpdecimal`` instalada, veja o módulo :mod:`decimal` (o padrão é sim)." -#: ../../using/configure.rst:812 +#: ../../using/configure.rst:829 msgid "Default to using the installed ``mpdecimal`` library." msgstr "O padrão é usar a biblioteca ``mpdecimal`` instalada." -#: ../../using/configure.rst:815 +#: ../../using/configure.rst:832 msgid "" "A copy of the ``mpdecimal`` library sources will no longer be distributed " "with Python 3.15." @@ -1398,140 +1463,140 @@ msgstr "" "Uma cópia dos fontes da biblioteca ``mpdecimal`` não será mais distribuída " "com Python 3.15." -#: ../../using/configure.rst:819 +#: ../../using/configure.rst:836 msgid ":option:`LIBMPDEC_CFLAGS` and :option:`LIBMPDEC_LIBS`." msgstr ":option:`LIBMPDEC_CFLAGS` e :option:`LIBMPDEC_LIBS`." -#: ../../using/configure.rst:823 +#: ../../using/configure.rst:840 msgid "Designate a backend library for the :mod:`readline` module." msgstr "Designa uma biblioteca backend para o módulo :mod:`readline`." -#: ../../using/configure.rst:825 +#: ../../using/configure.rst:842 msgid "readline: Use readline as the backend." msgstr "readline: Usa readline como o backend." -#: ../../using/configure.rst:826 +#: ../../using/configure.rst:843 msgid "editline: Use editline as the backend." msgstr "editline: Usa editline como o backend." -#: ../../using/configure.rst:832 +#: ../../using/configure.rst:849 msgid "Don't build the :mod:`readline` module (built by default)." msgstr "Não constrói o módulo :mod:`readline` (construído por padrão)." -#: ../../using/configure.rst:834 +#: ../../using/configure.rst:851 msgid "Don't define the ``HAVE_LIBREADLINE`` macro." msgstr "Não define a macro ``HAVE_LIBREADLINE``." -#: ../../using/configure.rst:840 +#: ../../using/configure.rst:857 msgid "" "Override ``libm`` math library to *STRING* (default is system-dependent)." msgstr "" "Substitui a biblioteca matemática ``libm`` por *STRING* (o padrão depende do " "sistema)." -#: ../../using/configure.rst:844 +#: ../../using/configure.rst:861 msgid "Override ``libc`` C library to *STRING* (default is system-dependent)." msgstr "" "Substitui a biblioteca C ``libc`` por *STRING* (o padrão depende do sistema)." -#: ../../using/configure.rst:848 +#: ../../using/configure.rst:865 msgid "Root of the OpenSSL directory." msgstr "Raiz do diretório OpenSSL." -#: ../../using/configure.rst:854 +#: ../../using/configure.rst:871 msgid "Set runtime library directory (rpath) for OpenSSL libraries:" msgstr "" "Define o diretório da biblioteca de tempo de execução (rpath) para " "bibliotecas OpenSSL:" -#: ../../using/configure.rst:856 +#: ../../using/configure.rst:873 msgid "``no`` (default): don't set rpath;" msgstr "``no`` (padrão): não define o rpath;" -#: ../../using/configure.rst:857 +#: ../../using/configure.rst:874 msgid "" "``auto``: auto-detect rpath from :option:`--with-openssl` and ``pkg-config``;" msgstr "" "``auto``: detecta automaticamente o rpath de :option:`--with-openssl` e " "``pkg-config``;" -#: ../../using/configure.rst:859 +#: ../../using/configure.rst:876 msgid "*DIR*: set an explicit rpath." msgstr "*DIR*: define um rpath explícito." -#: ../../using/configure.rst:865 +#: ../../using/configure.rst:882 msgid "Security Options" msgstr "Opções de segurança" -#: ../../using/configure.rst:869 +#: ../../using/configure.rst:886 msgid "Select hash algorithm for use in ``Python/pyhash.c``:" msgstr "Seleciona o algoritmo de hash para usar em ``Python/pyhash.c``:" -#: ../../using/configure.rst:871 +#: ../../using/configure.rst:888 msgid "``siphash13`` (default);" msgstr "``siphash13`` (padrão);" -#: ../../using/configure.rst:872 +#: ../../using/configure.rst:889 msgid "``siphash24``;" msgstr "``siphash24``;" -#: ../../using/configure.rst:873 +#: ../../using/configure.rst:890 msgid "``fnv``." msgstr "``fnv``." -#: ../../using/configure.rst:877 +#: ../../using/configure.rst:894 msgid "``siphash13`` is added and it is the new default." msgstr "``siphash13`` é adicionado e é o novo padrão." -#: ../../using/configure.rst:882 +#: ../../using/configure.rst:899 msgid "Built-in hash modules:" msgstr "Módulos embutidos de hash" -#: ../../using/configure.rst:884 +#: ../../using/configure.rst:901 msgid "``md5``;" msgstr "``md5``;" -#: ../../using/configure.rst:885 +#: ../../using/configure.rst:902 msgid "``sha1``;" msgstr "``sha1``;" -#: ../../using/configure.rst:886 +#: ../../using/configure.rst:903 msgid "``sha256``;" msgstr "``sha256``;" -#: ../../using/configure.rst:887 +#: ../../using/configure.rst:904 msgid "``sha512``;" msgstr "``sha512``;" -#: ../../using/configure.rst:888 +#: ../../using/configure.rst:905 msgid "``sha3`` (with shake);" msgstr "``sha3`` (com shake);" -#: ../../using/configure.rst:889 +#: ../../using/configure.rst:906 msgid "``blake2``." msgstr "``blake2``." -#: ../../using/configure.rst:895 +#: ../../using/configure.rst:912 msgid "Override the OpenSSL default cipher suites string:" msgstr "Substitui a string dos conjuntos de criptografia padrão do OpenSSL:" -#: ../../using/configure.rst:897 +#: ../../using/configure.rst:914 msgid "``python`` (default): use Python's preferred selection;" msgstr "``python`` (padrão): use a seleciona preferida do Python;" -#: ../../using/configure.rst:898 +#: ../../using/configure.rst:915 msgid "``openssl``: leave OpenSSL's defaults untouched;" msgstr "``openssl``: mantém inalterados os padrões do OpenSSL;" -#: ../../using/configure.rst:899 +#: ../../using/configure.rst:916 msgid "*STRING*: use a custom string" msgstr "*STRING*: usa uma string personalizada" -#: ../../using/configure.rst:901 +#: ../../using/configure.rst:918 msgid "See the :mod:`ssl` module." msgstr "Veja o módulo :mod:`ssl`." -#: ../../using/configure.rst:907 +#: ../../using/configure.rst:924 msgid "" "The settings ``python`` and *STRING* also set TLS 1.2 as minimum protocol " "version." @@ -1539,15 +1604,15 @@ msgstr "" "As configurações ``python`` e *STRING* também definem TLS 1.2 como versão " "mínima do protocolo." -#: ../../using/configure.rst:911 +#: ../../using/configure.rst:928 msgid "macOS Options" msgstr "Opções do macOS" -#: ../../using/configure.rst:913 +#: ../../using/configure.rst:930 msgid "See :source:`Mac/README.rst`." msgstr "Veja :source:`Mac/README.rst`." -#: ../../using/configure.rst:918 +#: ../../using/configure.rst:935 msgid "" "Create a universal binary build. *SDKDIR* specifies which macOS SDK should " "be used to perform the build (default is no)." @@ -1555,7 +1620,7 @@ msgstr "" "Cria uma construção binária universal. *SDKDIR* especifica qual SDK do macOS " "deve ser usado para executar a construção (o padrão é não)." -#: ../../using/configure.rst:924 +#: ../../using/configure.rst:941 msgid "" "Create a Python.framework rather than a traditional Unix install. Optional " "*INSTALLDIR* specifies the installation path (default is no)." @@ -1563,7 +1628,7 @@ msgstr "" "Cria um Python.framework em vez de uma instalação tradicional do Unix. O " "*INSTALLDIR* opcional especifica o caminho de instalação (o padrão é não)." -#: ../../using/configure.rst:929 +#: ../../using/configure.rst:946 msgid "" "Specify the kind of universal binary that should be created. This option is " "only valid when :option:`--enable-universalsdk` is set." @@ -1571,43 +1636,58 @@ msgstr "" "Especifica o tipo de binário universal que deve ser criado. Esta opção só é " "válida quando :option:`--enable-universalsdk` está definido." -#: ../../using/configure.rst:932 +#: ../../using/configure.rst:949 msgid "Options:" msgstr "Opções:" -#: ../../using/configure.rst:934 -msgid "``universal2``;" -msgstr "``universal2``;" +#: ../../using/configure.rst:951 +msgid "``universal2`` (x86-64 and arm64);" +msgstr "``universal2`` (x86-64 e arm64);" -#: ../../using/configure.rst:935 -msgid "``32-bit``;" -msgstr "``32-bit``;" +#: ../../using/configure.rst:952 +msgid "``32-bit`` (PPC and i386);" +msgstr "``32-bit`` (PPC e i386);" -#: ../../using/configure.rst:936 -msgid "``64-bit``;" -msgstr "``64-bit``;" +#: ../../using/configure.rst:953 +msgid "``64-bit`` (PPC64 and x86-64);" +msgstr "``64-bit`` (PPC64 e x86-64);" -#: ../../using/configure.rst:937 -msgid "``3-way``;" -msgstr "``3-way``;" +#: ../../using/configure.rst:954 +msgid "``3-way`` (i386, PPC and x86-64);" +msgstr "``3-way`` (i386, PPC e x86-64);" -#: ../../using/configure.rst:938 -msgid "``intel``;" -msgstr "``intel``;" +#: ../../using/configure.rst:955 +msgid "``intel`` (i386 and x86-64);" +msgstr "``intel`` (i386 e x86-64);" -#: ../../using/configure.rst:939 -msgid "``intel-32``;" -msgstr "``intel-32``;" +#: ../../using/configure.rst:956 +msgid "``intel-32`` (i386);" +msgstr "``intel-32`` (i386);" -#: ../../using/configure.rst:940 -msgid "``intel-64``;" -msgstr "``intel-64``;" +#: ../../using/configure.rst:957 +msgid "``intel-64`` (x86-64);" +msgstr "``intel-64`` (x86-64);" -#: ../../using/configure.rst:941 -msgid "``all``." -msgstr "``all``." +#: ../../using/configure.rst:958 +msgid "``all`` (PPC, i386, PPC64 and x86-64)." +msgstr "``all`` (PPC, i386, PPC64 e x86-64)." -#: ../../using/configure.rst:945 +#: ../../using/configure.rst:960 +msgid "" +"Note that values for this configuration item are *not* the same as the " +"identifiers used for universal binary wheels on macOS. See the Python " +"Packaging User Guide for details on the `packaging platform compatibility " +"tags used on macOS `_" +msgstr "" +"Observe que os valores para este item de configuração *não* são os mesmos " +"que os identificadores usados para rodas binárias universais no macOS. Veja " +"o Guia de Empacotamento do Python para detalhes sobre as `tags de " +"compatibilidade de plataforma de empacotamento usadas no macOS `_" + +#: ../../using/configure.rst:968 msgid "" "Specify the name for the python framework on macOS only valid when :option:" "`--enable-framework` is set (default: ``Python``)." @@ -1615,7 +1695,7 @@ msgstr "" "Especifica o nome do framework python no macOS válido apenas quando :option:" "`--enable-framework` está definido (padrão: ``Python``)." -#: ../../using/configure.rst:951 +#: ../../using/configure.rst:974 msgid "" "The Python standard library contains strings that are known to trigger " "automated inspection tool errors when submitted for distribution by the " @@ -1630,15 +1710,15 @@ msgstr "" "arquivo de patch personalizado também pode ser especificado. Esta opção está " "desativada por padrão." -#: ../../using/configure.rst:960 +#: ../../using/configure.rst:983 msgid "iOS Options" msgstr "Opções do iOS" -#: ../../using/configure.rst:962 +#: ../../using/configure.rst:985 msgid "See :source:`iOS/README.rst`." msgstr "Veja :source:`iOS/README.rst`." -#: ../../using/configure.rst:966 +#: ../../using/configure.rst:989 msgid "" "Create a Python.framework. Unlike macOS, the *INSTALLDIR* argument " "specifying the installation path is mandatory." @@ -1646,15 +1726,15 @@ msgstr "" "Cria um Python.framework. Ao contrário do macOS, o argumento *INSTALLDIR* " "que especifica o caminho de instalação é obrigatório." -#: ../../using/configure.rst:971 +#: ../../using/configure.rst:994 msgid "Specify the name for the framework (default: ``Python``)." msgstr "Especifica o nome do framework (padrão: ``Python``)." -#: ../../using/configure.rst:975 +#: ../../using/configure.rst:998 msgid "Cross Compiling Options" msgstr "Opções de compilação cruzada" -#: ../../using/configure.rst:977 +#: ../../using/configure.rst:1000 msgid "" "Cross compiling, also known as cross building, can be used to build Python " "for another CPU architecture or platform. Cross compiling requires a Python " @@ -1667,66 +1747,90 @@ msgstr "" "construção. A versão do Python para construção deve corresponder à versão do " "Python da compilação cruzada do host." -#: ../../using/configure.rst:984 +#: ../../using/configure.rst:1007 msgid "" "configure for building on BUILD, usually guessed by :program:`config.guess`." msgstr "" "configura para construir em BUILD, geralmente adivinhado por :program:" "`config.guess`." -#: ../../using/configure.rst:988 +#: ../../using/configure.rst:1011 msgid "cross-compile to build programs to run on HOST (target platform)" msgstr "" "faz compilação cruzada para construir programas para executar no HOST " "(plataforma de destino)" -#: ../../using/configure.rst:992 +#: ../../using/configure.rst:1015 msgid "path to build ``python`` binary for cross compiling" msgstr "caminho para construir o binário ``python`` para compilação cruzada" -#: ../../using/configure.rst:998 +#: ../../using/configure.rst:1021 msgid "An environment variable that points to a file with configure overrides." msgstr "" "Uma variável de ambiente que aponta para um arquivo com substituições de " "configuração." -#: ../../using/configure.rst:1000 +#: ../../using/configure.rst:1023 msgid "Example *config.site* file:" msgstr "Exemplo de arquivo *config.site*:" -#: ../../using/configure.rst:1011 +#: ../../using/configure.rst:1025 +msgid "" +"# config.site-aarch64\n" +"ac_cv_buggy_getaddrinfo=no\n" +"ac_cv_file__dev_ptmx=yes\n" +"ac_cv_file__dev_ptc=no" +msgstr "" +"# config.site-aarch64\n" +"ac_cv_buggy_getaddrinfo=no\n" +"ac_cv_file__dev_ptmx=yes\n" +"ac_cv_file__dev_ptc=no" + +#: ../../using/configure.rst:1034 msgid "Program to run CPython for the host platform for cross-compilation." msgstr "" "Programa para executar CPython para a plataforma host para compilação " "cruzada." -#: ../../using/configure.rst:1016 +#: ../../using/configure.rst:1039 msgid "Cross compiling example::" msgstr "Exemplo de compilação cruzada::" -#: ../../using/configure.rst:1025 +#: ../../using/configure.rst:1041 +msgid "" +"CONFIG_SITE=config.site-aarch64 ../configure \\\n" +" --build=x86_64-pc-linux-gnu \\\n" +" --host=aarch64-unknown-linux-gnu \\\n" +" --with-build-python=../x86_64/python" +msgstr "" +"CONFIG_SITE=config.site-aarch64 ../configure \\\n" +" --build=x86_64-pc-linux-gnu \\\n" +" --host=aarch64-unknown-linux-gnu \\\n" +" --with-build-python=../x86_64/python" + +#: ../../using/configure.rst:1048 msgid "Python Build System" msgstr "Sistema de Construção Python" -#: ../../using/configure.rst:1028 +#: ../../using/configure.rst:1051 msgid "Main files of the build system" msgstr "Arquivos principais do sistema de construção" -#: ../../using/configure.rst:1030 +#: ../../using/configure.rst:1053 msgid ":file:`configure.ac` => :file:`configure`;" msgstr ":file:`configure.ac` => :file:`configure`;" -#: ../../using/configure.rst:1031 +#: ../../using/configure.rst:1054 msgid "" ":file:`Makefile.pre.in` => :file:`Makefile` (created by :file:`configure`);" msgstr "" ":file:`Makefile.pre.in` => :file:`Makefile` (criado por :file:`configure`);" -#: ../../using/configure.rst:1032 +#: ../../using/configure.rst:1055 msgid ":file:`pyconfig.h` (created by :file:`configure`);" msgstr ":file:`pyconfig.h` (criado por :file:`configure`);" -#: ../../using/configure.rst:1033 +#: ../../using/configure.rst:1056 msgid "" ":file:`Modules/Setup`: C extensions built by the Makefile using :file:" "`Module/makesetup` shell script;" @@ -1734,21 +1838,21 @@ msgstr "" ":file:`Modules/Setup`: Extensões C construídas pelo Makefile usando o shell " "script :file:`Module/makesetup`;" -#: ../../using/configure.rst:1037 +#: ../../using/configure.rst:1060 msgid "Main build steps" msgstr "Principais etapas de construção" -#: ../../using/configure.rst:1039 +#: ../../using/configure.rst:1062 msgid "C files (``.c``) are built as object files (``.o``)." msgstr "Arquivos C (``.c``) são construídos como arquivos objeto (``.o``)." -#: ../../using/configure.rst:1040 +#: ../../using/configure.rst:1063 msgid "A static ``libpython`` library (``.a``) is created from objects files." msgstr "" "Uma biblioteca estática ``libpython`` (``.a``) é criada a partir de arquivos " "de objetos." -#: ../../using/configure.rst:1041 +#: ../../using/configure.rst:1064 msgid "" "``python.o`` and the static ``libpython`` library are linked into the final " "``python`` program." @@ -1756,20 +1860,20 @@ msgstr "" "``python.o`` e a biblioteca estática ``libpython`` estão vinculadas ao " "programa final ``python``." -#: ../../using/configure.rst:1043 +#: ../../using/configure.rst:1066 msgid "C extensions are built by the Makefile (see :file:`Modules/Setup`)." msgstr "" "Extensões C são construídas pelo Makefile (veja :file:`Modules/Setup`)." -#: ../../using/configure.rst:1046 +#: ../../using/configure.rst:1069 msgid "Main Makefile targets" msgstr "Alvos principais do Makefile" -#: ../../using/configure.rst:1049 +#: ../../using/configure.rst:1072 msgid "make" msgstr "make" -#: ../../using/configure.rst:1051 +#: ../../using/configure.rst:1074 msgid "" "For the most part, when rebuilding after editing some code or refreshing " "your checkout from upstream, all you need to do is execute ``make``, which " @@ -1787,20 +1891,20 @@ msgstr "" "``@DEF_MAKE_ALL_RULE@`` para descrever precisamente quais alvos ``make all`` " "serão construídos. As três opções são:" -#: ../../using/configure.rst:1060 +#: ../../using/configure.rst:1083 msgid "``profile-opt`` (configured with ``--enable-optimizations``)" msgstr "``profile-opt`` (configurado com ``--enable-optimizations``)" -#: ../../using/configure.rst:1061 +#: ../../using/configure.rst:1084 msgid "``build_wasm`` (configured with ``--with-emscripten-target``)" msgstr "``build_wasm`` (configurado com ``--with-emscripten-target``)" -#: ../../using/configure.rst:1062 +#: ../../using/configure.rst:1085 msgid "" "``build_all`` (configured without explicitly using either of the others)" msgstr "``build_all`` (configurado sem usar explicitamente nenhum dos outros)" -#: ../../using/configure.rst:1064 +#: ../../using/configure.rst:1087 msgid "" "Depending on the most recent source file changes, Make will rebuild any " "targets (object files and executables) deemed out-of-date, including running " @@ -1823,11 +1927,11 @@ msgstr "" "explicar de outra forma, ``make clean && make`` deve resolver a maioria dos " "problemas de dependência, às custas de tempos de construção mais longos." -#: ../../using/configure.rst:1077 +#: ../../using/configure.rst:1100 msgid "make platform" msgstr "make platform" -#: ../../using/configure.rst:1079 +#: ../../using/configure.rst:1102 msgid "" "Build the ``python`` program, but don't build the standard library extension " "modules. This generates a file named ``platform`` which contains a single " @@ -1839,11 +1943,11 @@ msgstr "" "única linha descrevendo os detalhes da plataforma de construção, por " "exemplo, ``macosx-14.3-arm64-3.12`` ou ``linux-x86_64-3.13``." -#: ../../using/configure.rst:1086 +#: ../../using/configure.rst:1109 msgid "make profile-opt" msgstr "make profile-opt" -#: ../../using/configure.rst:1088 +#: ../../using/configure.rst:1111 msgid "" "Build Python using profile-guided optimization (PGO). You can use the " "configure :option:`--enable-optimizations` option to make this the default " @@ -1853,41 +1957,41 @@ msgstr "" "opção :option:`--enable-optimizations` do configure para tornar este o alvo " "padrão do comando ``make`` (``make all`` ou apenas ``make``)." -#: ../../using/configure.rst:1096 +#: ../../using/configure.rst:1119 msgid "make clean" msgstr "make clean" -#: ../../using/configure.rst:1098 +#: ../../using/configure.rst:1121 msgid "Remove built files." msgstr "Remove arquivos construídos." -#: ../../using/configure.rst:1102 +#: ../../using/configure.rst:1125 msgid "make distclean" msgstr "make distclean" -#: ../../using/configure.rst:1104 +#: ../../using/configure.rst:1127 msgid "" -"In addition to the the work done by ``make clean``, remove files created by " -"the configure script. ``configure`` will have to be run before building " -"again. [#]_" +"In addition to the work done by ``make clean``, remove files created by the " +"configure script. ``configure`` will have to be run before building again. " +"[#]_" msgstr "" "Além do trabalho feito por ``make clean``, remove os arquivos criados pelo " "script configure. ``configure`` terá que ser executado antes de construir " "novamente. [#]_" -#: ../../using/configure.rst:1110 +#: ../../using/configure.rst:1133 msgid "make install" msgstr "make install" -#: ../../using/configure.rst:1112 +#: ../../using/configure.rst:1135 msgid "Build the ``all`` target and install Python." msgstr "Constrói o alvo ``all`` e instala o Python." -#: ../../using/configure.rst:1116 +#: ../../using/configure.rst:1139 msgid "make test" msgstr "make test" -#: ../../using/configure.rst:1118 +#: ../../using/configure.rst:1141 msgid "" "Build the ``all`` target and run the Python test suite with the ``--fast-" "ci`` option. Variables:" @@ -1895,23 +1999,23 @@ msgstr "" "Constrói o alvo ``all`` e execute o conjunto de testes Python com a opção " "``--fast-ci``. Variáveis:" -#: ../../using/configure.rst:1121 +#: ../../using/configure.rst:1144 msgid "``TESTOPTS``: additional regrtest command-line options." msgstr "``TESTOPTS``: opções adicionais de linha de comando regrtest." -#: ../../using/configure.rst:1122 +#: ../../using/configure.rst:1145 msgid "``TESTPYTHONOPTS``: additional Python command-line options." msgstr "``TESTPYTHONOPTS``: opções adicionais de linha de comando do Python." -#: ../../using/configure.rst:1123 +#: ../../using/configure.rst:1146 msgid "``TESTTIMEOUT``: timeout in seconds (default: 10 minutes)." msgstr "``TESTTIMEOUT``: tempo limite em segundos (padrão: 10 minutos)." -#: ../../using/configure.rst:1127 +#: ../../using/configure.rst:1150 msgid "make buildbottest" msgstr "make buildbottest" -#: ../../using/configure.rst:1129 +#: ../../using/configure.rst:1152 msgid "" "This is similar to ``make test``, but uses the ``--slow-ci`` option and " "default timeout of 20 minutes, instead of ``--fast-ci`` option." @@ -1919,11 +2023,11 @@ msgstr "" "Isto é semelhante ao ``make test``, mas usa a opção ``--slow-ci`` e o tempo " "limite padrão de 20 minutos, em vez da opção ``--fast-ci``." -#: ../../using/configure.rst:1134 +#: ../../using/configure.rst:1157 msgid "make regen-all" msgstr "make regen-all" -#: ../../using/configure.rst:1136 +#: ../../using/configure.rst:1159 msgid "" "Regenerate (almost) all generated files. These include (but are not limited " "to) bytecode cases, and parser generator file. ``make regen-stdlib-module-" @@ -1935,11 +2039,11 @@ msgstr "" "``make regen-stdlib-module-names`` e ``autoconf`` devem ser executados " "separadamente para os restantes `arquivos gerados <#generated-files>`_." -#: ../../using/configure.rst:1143 +#: ../../using/configure.rst:1166 msgid "C extensions" msgstr "Extensões C" -#: ../../using/configure.rst:1145 +#: ../../using/configure.rst:1168 msgid "" "Some C extensions are built as built-in modules, like the ``sys`` module. " "They are built with the ``Py_BUILD_CORE_BUILTIN`` macro defined. Built-in " @@ -1949,7 +2053,25 @@ msgstr "" "``sys``. Eles são construídos com a macro ``Py_BUILD_CORE_BUILTIN`` " "definida. Módulos embutidos não possuem nenhum atributo ``__file__``:" -#: ../../using/configure.rst:1159 +#: ../../using/configure.rst:1172 +msgid "" +">>> import sys\n" +">>> sys\n" +"\n" +">>> sys.__file__\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"AttributeError: module 'sys' has no attribute '__file__'" +msgstr "" +">>> import sys\n" +">>> sys\n" +"\n" +">>> sys.__file__\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"AttributeError: module 'sys' has no attribute '__file__'" + +#: ../../using/configure.rst:1182 msgid "" "Other C extensions are built as dynamic libraries, like the ``_asyncio`` " "module. They are built with the ``Py_BUILD_CORE_MODULE`` macro defined. " @@ -1959,7 +2081,23 @@ msgstr "" "``_asyncio``. Eles são construídos com a macro ``Py_BUILD_CORE_MODULE`` " "definida. Exemplo no Linux x86-64:" -#: ../../using/configure.rst:1171 +#: ../../using/configure.rst:1186 +msgid "" +">>> import _asyncio\n" +">>> _asyncio\n" +"\n" +">>> _asyncio.__file__\n" +"'/usr/lib64/python3.9/lib-dynload/_asyncio.cpython-39-x86_64-linux-gnu.so'" +msgstr "" +">>> import _asyncio\n" +">>> _asyncio\n" +"\n" +">>> _asyncio.__file__\n" +"'/usr/lib64/python3.9/lib-dynload/_asyncio.cpython-39-x86_64-linux-gnu.so'" + +#: ../../using/configure.rst:1194 msgid "" ":file:`Modules/Setup` is used to generate Makefile targets to build C " "extensions. At the beginning of the files, C extensions are built as built-" @@ -1971,7 +2109,7 @@ msgstr "" "módulos embutidos. Extensões definidas após o marcador ``*shared*`` são " "construídas como bibliotecas dinâmicas." -#: ../../using/configure.rst:1175 +#: ../../using/configure.rst:1198 msgid "" "The :c:macro:`!PyAPI_FUNC()`, :c:macro:`!PyAPI_DATA()` and :c:macro:" "`PyMODINIT_FUNC` macros of :file:`Include/exports.h` are defined differently " @@ -1981,16 +2119,16 @@ msgstr "" "`PyMODINIT_FUNC` de :file:`Include/exports.h` são definidas de forma " "diferente dependendo se a macro ``Py_BUILD_CORE_MODULE`` está definida:" -#: ../../using/configure.rst:1179 +#: ../../using/configure.rst:1202 msgid "Use ``Py_EXPORTED_SYMBOL`` if the ``Py_BUILD_CORE_MODULE`` is defined" msgstr "" "Usa ``Py_EXPORTED_SYMBOL`` se ``Py_BUILD_CORE_MODULE`` estiver definido" -#: ../../using/configure.rst:1180 +#: ../../using/configure.rst:1203 msgid "Use ``Py_IMPORTED_SYMBOL`` otherwise." msgstr "Do contrário, usa ``Py_IMPORTED_SYMBOL``." -#: ../../using/configure.rst:1182 +#: ../../using/configure.rst:1205 msgid "" "If the ``Py_BUILD_CORE_BUILTIN`` macro is used by mistake on a C extension " "built as a shared library, its :samp:`PyInit_{xxx}()` function is not " @@ -2000,29 +2138,29 @@ msgstr "" "construída como uma biblioteca compartilhada, sua função :samp:`PyInit_{xxx}" "()` não será exportada, causando um :exc:`ImportError` na importação." -#: ../../using/configure.rst:1188 +#: ../../using/configure.rst:1211 msgid "Compiler and linker flags" msgstr "Sinalizadores do compilador e do vinculador" -#: ../../using/configure.rst:1190 +#: ../../using/configure.rst:1213 msgid "" "Options set by the ``./configure`` script and environment variables and used " "by ``Makefile``." msgstr "" -"Opções definidas pelo script ``./configure`` e variáveis ​​de ambiente e " +"Opções definidas pelo script ``./configure`` e variáveis de ambiente e " "usadas por ``Makefile``." -#: ../../using/configure.rst:1194 +#: ../../using/configure.rst:1217 msgid "Preprocessor flags" msgstr "Sinalizadores do pré-processador" -#: ../../using/configure.rst:1198 +#: ../../using/configure.rst:1221 msgid "" "Value of :envvar:`CPPFLAGS` variable passed to the ``./configure`` script." msgstr "" "Valor da variável :envvar:`CPPFLAGS` passado para o script ``./configure``." -#: ../../using/configure.rst:1204 +#: ../../using/configure.rst:1227 msgid "" "(Objective) C/C++ preprocessor flags, e.g. :samp:`-I{include_dir}` if you " "have headers in a nonstandard directory *include_dir*." @@ -2031,7 +2169,7 @@ msgstr "" "I{include_dir}` se você tiver cabeçalhos em um diretório não padrão " "*include_dir*." -#: ../../using/configure.rst:1207 ../../using/configure.rst:1397 +#: ../../using/configure.rst:1230 ../../using/configure.rst:1420 msgid "" "Both :envvar:`CPPFLAGS` and :envvar:`LDFLAGS` need to contain the shell's " "value to be able to build extension modules using the directories specified " @@ -2039,16 +2177,16 @@ msgid "" msgstr "" "Tanto :envvar:`CPPFLAGS` quanto :envvar:`LDFLAGS` precisam conter o valor do " "shell para poder construir módulos de extensão usando os diretórios " -"especificados nas variáveis ​​de ambiente." +"especificados nas variáveis de ambiente." -#: ../../using/configure.rst:1217 +#: ../../using/configure.rst:1240 msgid "" "Extra preprocessor flags added for building the interpreter object files." msgstr "" "Sinalizadores extras de pré-processador adicionados para construir os " "arquivos de objeto do interpretador." -#: ../../using/configure.rst:1219 +#: ../../using/configure.rst:1242 msgid "" "Default: ``$(BASECPPFLAGS) -I. -I$(srcdir)/Include $(CONFIGURE_CPPFLAGS) " "$(CPPFLAGS)``." @@ -2056,23 +2194,23 @@ msgstr "" "Padrão: ``$(BASECPPFLAGS) -I. -I$(srcdir)/Include $(CONFIGURE_CPPFLAGS) " "$(CPPFLAGS)``." -#: ../../using/configure.rst:1224 +#: ../../using/configure.rst:1247 msgid "Compiler flags" msgstr "Sinalizadores do compilador" -#: ../../using/configure.rst:1230 +#: ../../using/configure.rst:1253 msgid "Example: ``gcc -pthread``." msgstr "Exemplo: ``gcc -pthread``." -#: ../../using/configure.rst:1234 +#: ../../using/configure.rst:1257 msgid "C++ compiler command." msgstr "Comando do compilador C++." -#: ../../using/configure.rst:1236 +#: ../../using/configure.rst:1259 msgid "Example: ``g++ -pthread``." msgstr "Exemplo: ``g++ -pthread``." -#: ../../using/configure.rst:1244 +#: ../../using/configure.rst:1267 msgid "" ":envvar:`CFLAGS_NODIST` is used for building the interpreter and stdlib C " "extensions. Use it when a compiler flag should *not* be part of :envvar:" @@ -2082,11 +2220,11 @@ msgstr "" "da stdlib. Use-o quando um sinalizador do compilador *não* deve fazer parte " "de :envvar:`CFLAGS` depois que o Python estiver instalado (:gh:`65320`)." -#: ../../using/configure.rst:1248 +#: ../../using/configure.rst:1271 msgid "In particular, :envvar:`CFLAGS` should not contain:" msgstr "Em particular, :envvar:`CFLAGS` não deve conter:" -#: ../../using/configure.rst:1250 +#: ../../using/configure.rst:1273 msgid "" "the compiler flag ``-I`` (for setting the search path for include files). " "The ``-I`` flags are processed from left to right, and any flags in :envvar:" @@ -2098,7 +2236,7 @@ msgstr "" "precedência sobre os sinalizadores ``-I`` fornecidos pelo usuário e pelo " "pacote." -#: ../../using/configure.rst:1255 +#: ../../using/configure.rst:1278 msgid "" "hardening flags such as ``-Werror`` because distributions cannot control " "whether packages installed by users conform to such heightened standards." @@ -2107,7 +2245,7 @@ msgstr "" "podem controlar se os pacotes instalados pelos usuários estão em " "conformidade com esses padrões elevados." -#: ../../using/configure.rst:1263 +#: ../../using/configure.rst:1286 msgid "" "Options passed to the :mod:`compileall` command line when building PYC files " "in ``make install``. Default: ``-j0``." @@ -2115,17 +2253,17 @@ msgstr "" "Opções passadas para a linha de comando :mod:`compileall` ao construir " "arquivos PYC em ``make install``. Padrão: ``-j0``." -#: ../../using/configure.rst:1270 +#: ../../using/configure.rst:1293 msgid "Extra C compiler flags." msgstr "Sinalizadores extra do compilador C." -#: ../../using/configure.rst:1274 +#: ../../using/configure.rst:1297 msgid "" "Value of :envvar:`CFLAGS` variable passed to the ``./configure`` script." msgstr "" "Valor da variável :envvar:`CFLAGS` passado para o script ``./configure``." -#: ../../using/configure.rst:1281 +#: ../../using/configure.rst:1304 msgid "" "Value of :envvar:`CFLAGS_NODIST` variable passed to the ``./configure`` " "script." @@ -2133,37 +2271,37 @@ msgstr "" "Valor da variável :envvar:`CFLAGS_NODIST` passado para o script ``./" "configure``." -#: ../../using/configure.rst:1288 +#: ../../using/configure.rst:1311 msgid "Base compiler flags." msgstr "Sinalizadores base do compilador." -#: ../../using/configure.rst:1292 +#: ../../using/configure.rst:1315 msgid "Optimization flags." msgstr "Sinalizadores de otimização." -#: ../../using/configure.rst:1296 +#: ../../using/configure.rst:1319 msgid "Strict or non-strict aliasing flags used to compile ``Python/dtoa.c``." msgstr "" -"Sinalizadores de alias estritos ou não estritos usados ​​para compilar " +"Sinalizadores de alias estritos ou não estritos usados para compilar " "``Python/dtoa.c``." -#: ../../using/configure.rst:1302 +#: ../../using/configure.rst:1325 msgid "Compiler flags used to build a shared library." msgstr "" -"Sinalizadores de compilador usados ​​para construir uma biblioteca " +"Sinalizadores de compilador usados para construir uma biblioteca " "compartilhada." -#: ../../using/configure.rst:1304 +#: ../../using/configure.rst:1327 msgid "For example, ``-fPIC`` is used on Linux and on BSD." msgstr "Por exemplo, ``-fPIC`` é usado no Linux e no BSD." -#: ../../using/configure.rst:1308 +#: ../../using/configure.rst:1331 msgid "Extra C flags added for building the interpreter object files." msgstr "" "Sinalizadores extras de C adicionados para construir os arquivos de objeto " "do interpretador." -#: ../../using/configure.rst:1310 +#: ../../using/configure.rst:1333 msgid "" "Default: ``$(CCSHARED)`` when :option:`--enable-shared` is used, or an empty " "string otherwise." @@ -2171,7 +2309,7 @@ msgstr "" "Padrão: ``$(CCSHARED)`` quando :option:`--enable-shared` é usado, ou uma " "string vazia caso contrário." -#: ../../using/configure.rst:1315 +#: ../../using/configure.rst:1338 msgid "" "Default: ``$(BASECFLAGS) $(OPT) $(CONFIGURE_CFLAGS) $(CFLAGS) " "$(EXTRA_CFLAGS)``." @@ -2179,7 +2317,7 @@ msgstr "" "Padrão: ``$(BASECFLAGS) $(OPT) $(CONFIGURE_CFLAGS) $(CFLAGS) " "$(EXTRA_CFLAGS)``." -#: ../../using/configure.rst:1319 +#: ../../using/configure.rst:1342 msgid "" "Default: ``$(CONFIGURE_CFLAGS_NODIST) $(CFLAGS_NODIST) -I$(srcdir)/Include/" "internal``." @@ -2187,13 +2325,13 @@ msgstr "" "Padrão: ``$(CONFIGURE_CFLAGS_NODIST) $(CFLAGS_NODIST) -I$(srcdir)/Include/" "internal``." -#: ../../using/configure.rst:1325 +#: ../../using/configure.rst:1348 msgid "C flags used for building the interpreter object files." msgstr "" "Sinalizadores do C usados para construir os arquivos de objeto do " "interpretador." -#: ../../using/configure.rst:1327 +#: ../../using/configure.rst:1350 msgid "" "Default: ``$(PY_CFLAGS) $(PY_CFLAGS_NODIST) $(PY_CPPFLAGS) " "$(CFLAGSFORSHARED)``." @@ -2201,11 +2339,11 @@ msgstr "" "Padrão: ``$(PY_CFLAGS) $(PY_CFLAGS_NODIST) $(PY_CPPFLAGS) " "$(CFLAGSFORSHARED)``." -#: ../../using/configure.rst:1333 +#: ../../using/configure.rst:1356 msgid "Default: ``$(PY_STDMODULE_CFLAGS) -DPy_BUILD_CORE``." msgstr "Padrão: ``$(PY_STDMODULE_CFLAGS) -DPy_BUILD_CORE``." -#: ../../using/configure.rst:1339 +#: ../../using/configure.rst:1362 msgid "" "Compiler flags to build a standard library extension module as a built-in " "module, like the :mod:`posix` module." @@ -2213,40 +2351,40 @@ msgstr "" "Sinalizadores do compilador para construir um módulo de extensão de " "biblioteca padrão como um módulo embutido, como o módulo :mod:`posix`." -#: ../../using/configure.rst:1342 +#: ../../using/configure.rst:1365 msgid "Default: ``$(PY_STDMODULE_CFLAGS) -DPy_BUILD_CORE_BUILTIN``." msgstr "Padrão: ``$(PY_STDMODULE_CFLAGS) -DPy_BUILD_CORE_BUILTIN``." -#: ../../using/configure.rst:1348 +#: ../../using/configure.rst:1371 msgid "Purify command. Purify is a memory debugger program." msgstr "Comando de Purify. Purify é um programa depurador de memória." -#: ../../using/configure.rst:1350 +#: ../../using/configure.rst:1373 msgid "Default: empty string (not used)." msgstr "Padrão: string vazia (não usada)." -#: ../../using/configure.rst:1354 +#: ../../using/configure.rst:1377 msgid "Linker flags" msgstr "Sinalizadores do vinculador" -#: ../../using/configure.rst:1358 +#: ../../using/configure.rst:1381 msgid "" "Linker command used to build programs like ``python`` and ``_testembed``." msgstr "" "Comando do vinculador usado para construir programas como ``python`` e " "``_testembed``." -#: ../../using/configure.rst:1360 +#: ../../using/configure.rst:1383 msgid "Default: ``$(PURIFY) $(CC)``." msgstr "Padrão: ``$(PURIFY) $(CC)``." -#: ../../using/configure.rst:1364 +#: ../../using/configure.rst:1387 msgid "" "Value of :envvar:`LDFLAGS` variable passed to the ``./configure`` script." msgstr "" "Valor da variável :envvar:`LDFLAGS` passado para o script ``./configure``." -#: ../../using/configure.rst:1366 +#: ../../using/configure.rst:1389 msgid "" "Avoid assigning :envvar:`CFLAGS`, :envvar:`LDFLAGS`, etc. so users can use " "them on the command line to append to these values without stomping the pre-" @@ -2256,7 +2394,7 @@ msgstr "" "usuários possam usá-los na linha de comando para anexar a esses valores sem " "pisotear os valores predefinidos." -#: ../../using/configure.rst:1374 +#: ../../using/configure.rst:1397 msgid "" ":envvar:`LDFLAGS_NODIST` is used in the same manner as :envvar:" "`CFLAGS_NODIST`. Use it when a linker flag should *not* be part of :envvar:" @@ -2266,11 +2404,11 @@ msgstr "" "`CFLAGS_NODIST`. Use-o quando um sinalizador de vinculador *não* fizer parte " "de :envvar:`LDFLAGS` depois que o Python estiver instalado (:gh:`65320`)." -#: ../../using/configure.rst:1378 +#: ../../using/configure.rst:1401 msgid "In particular, :envvar:`LDFLAGS` should not contain:" msgstr "Em particular, :envvar:`LDFLAGS` não deve conter:" -#: ../../using/configure.rst:1380 +#: ../../using/configure.rst:1403 msgid "" "the compiler flag ``-L`` (for setting the search path for libraries). The ``-" "L`` flags are processed from left to right, and any flags in :envvar:" @@ -2282,7 +2420,7 @@ msgstr "" "precedência sobre os sinalizadores ``-L`` fornecidos pelo usuário e pelo " "pacote." -#: ../../using/configure.rst:1387 +#: ../../using/configure.rst:1410 msgid "" "Value of :envvar:`LDFLAGS_NODIST` variable passed to the ``./configure`` " "script." @@ -2290,7 +2428,7 @@ msgstr "" "Valor da variável :envvar:`LDFLAGS_NODIST` passado para o script ``./" "configure``." -#: ../../using/configure.rst:1394 +#: ../../using/configure.rst:1417 msgid "" "Linker flags, e.g. :samp:`-L{lib_dir}` if you have libraries in a " "nonstandard directory *lib_dir*." @@ -2298,7 +2436,7 @@ msgstr "" "Sinalizadores do vinculador, p.ex. :samp:`-L{lib_dir}`, se você tiver " "bibliotecas em um diretório não padrão *lib_dir*." -#: ../../using/configure.rst:1403 +#: ../../using/configure.rst:1426 msgid "" "Linker flags to pass libraries to the linker when linking the Python " "executable." @@ -2306,45 +2444,45 @@ msgstr "" "Sinalizadores do vinculador para passar bibliotecas para o vinculador ao " "vincular o executável Python." -#: ../../using/configure.rst:1406 +#: ../../using/configure.rst:1429 msgid "Example: ``-lrt``." msgstr "Exemplo: ``-lrt``." -#: ../../using/configure.rst:1410 +#: ../../using/configure.rst:1433 msgid "Command to build a shared library." msgstr "Comando para construir uma biblioteca compartilhada." -#: ../../using/configure.rst:1412 +#: ../../using/configure.rst:1435 msgid "Default: ``@LDSHARED@ $(PY_LDFLAGS)``." msgstr "Padrão: ``@LDSHARED@ $(PY_LDFLAGS)``." -#: ../../using/configure.rst:1416 +#: ../../using/configure.rst:1439 msgid "Command to build ``libpython`` shared library." msgstr "Comando para construir a biblioteca compartilhada ``libpython``." -#: ../../using/configure.rst:1418 +#: ../../using/configure.rst:1441 msgid "Default: ``@BLDSHARED@ $(PY_CORE_LDFLAGS)``." msgstr "Padrão: ``@BLDSHARED@ $(PY_CORE_LDFLAGS)``." -#: ../../using/configure.rst:1422 +#: ../../using/configure.rst:1445 msgid "Default: ``$(CONFIGURE_LDFLAGS) $(LDFLAGS)``." msgstr "Padrão: ``$(CONFIGURE_LDFLAGS) $(LDFLAGS)``." -#: ../../using/configure.rst:1426 +#: ../../using/configure.rst:1449 msgid "Default: ``$(CONFIGURE_LDFLAGS_NODIST) $(LDFLAGS_NODIST)``." msgstr "Padrão: ``$(CONFIGURE_LDFLAGS_NODIST) $(LDFLAGS_NODIST)``." -#: ../../using/configure.rst:1432 +#: ../../using/configure.rst:1455 msgid "Linker flags used for building the interpreter object files." msgstr "" "Sinalizadores de vinculador usados para construir os arquivos de objeto do " "interpretador." -#: ../../using/configure.rst:1438 +#: ../../using/configure.rst:1461 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../using/configure.rst:1439 +#: ../../using/configure.rst:1462 msgid "" "``git clean -fdx`` is an even more extreme way to \"clean\" your checkout. " "It removes all files not known to Git. When bug hunting using ``git " diff --git a/using/editors.po b/using/editors.po index bb13e5910..c38094dc8 100644 --- a/using/editors.po +++ b/using/editors.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2021 -# Claudio Rogerio Carvalho Filho , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:51+0000\n" -"Last-Translator: Claudio Rogerio Carvalho Filho , " -"2021\n" +"POT-Creation-Date: 2025-02-14 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -35,17 +33,45 @@ msgid "" "editors and IDEs provide syntax highlighting, debugging tools, and :pep:`8` " "checks." msgstr "" -"Há um grande número de IDEs que suportam a linguagem de programação Python. " +"Há um grande número de IDEs com suporte à linguagem de programação Python. " "Vários editores e IDEs provêem destaques coloridos de sintaxe, ferramentas " -"de depuração, e checagem do código frente à :pep:`8`." +"de depuração, e checagem do código conforme a :pep:`8`." -#: ../../using/editors.rst:12 +#: ../../using/editors.rst:14 +msgid "IDLE --- Python editor and shell" +msgstr "IDLE --- editor e console Python" + +#: ../../using/editors.rst:16 msgid "" -"Please go to `Python Editors `_ " -"and `Integrated Development Environments `_ for a comprehensive list." +"IDLE is Python’s Integrated Development and Learning Environment and is " +"generally bundled with Python installs. If you are on Linux and do not have " +"IDLE installed see :ref:`Installing IDLE on Linux " +"`. For more information see the :ref:`IDLE docs " +"`." msgstr "" -"Por favor, vá para `Python Editors `. Para obter mais informações consulte, consulte " +"os documentos do :ref:`IDLE `." + +#: ../../using/editors.rst:22 +msgid "Other Editors and IDEs" +msgstr "Outros editores e IDEs" + +#: ../../using/editors.rst:24 +msgid "" +"Python's community wiki has information submitted by the community on " +"Editors and IDEs. Please go to `Python Editors `_ and `Integrated Development Environments `_ para obter uma lista " -"completa." +"python.org/moin/IntegratedDevelopmentEnvironments>`_ for a comprehensive " +"list." +msgstr "" +"As wikis da comunidades Python têm informações enviadas pela comunidade " +"sobre Editores e IDEs. Acesse `Ferramentas de Desenvolvimento `_ para obter uma lista abrangente enviada pela " +"comunidade brasileira ou `Python Editors `_ e `Integrated Development Environments `_ para listas enviadas pela " +"comunidade internacional (em inglês)." diff --git a/using/index.po b/using/index.po index c99cbfdbd..e22fe89ce 100644 --- a/using/index.po +++ b/using/index.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:51+0000\n" -"Last-Translator: Rafael Fontenelle , 2021\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" diff --git a/using/ios.po b/using/ios.po index 9f2ae4edf..b6c061399 100644 --- a/using/ios.po +++ b/using/ios.po @@ -1,25 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-26 14:15+0000\n" -"PO-Revision-Date: 2024-05-11 01:08+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-03-14 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -136,20 +136,20 @@ msgstr "" msgid "" "Information about the specific runtime environment, including the iOS " "version, device model, and whether the device is a simulator, can be " -"obtained using :func:`platform.ios_ver()`. :func:`platform.system()` will " -"report ``iOS`` or ``iPadOS``, depending on the device." +"obtained using :func:`platform.ios_ver`. :func:`platform.system` will report " +"``iOS`` or ``iPadOS``, depending on the device." msgstr "" "Informações sobre o ambiente de execução específico, incluindo a versão do " "iOS, modelo do dispositivo e se o dispositivo é um simulador, podem ser " -"obtidas usando :func:`platform.ios_ver()`. :func:`platform.system()` " -"reportará ``iOS`` ou ``iPadOS``, dependendo do dispositivo." +"obtidas usando :func:`platform.ios_ver`. :func:`platform.system` reportará " +"``iOS`` ou ``iPadOS``, dependendo do dispositivo." #: ../../using/ios.rst:59 msgid "" -":func:`os.uname()` reports kernel-level details; it will report a name of " +":func:`os.uname` reports kernel-level details; it will report a name of " "``Darwin``." msgstr "" -":func:`os.uname()` reporta detalhes em nível de kernel; ele reportará o nome " +":func:`os.uname` reporta detalhes em nível de kernel; ele reportará o nome " "``Darwin``." #: ../../using/ios.rst:63 @@ -159,11 +159,11 @@ msgstr "Disponibilidade da biblioteca padrão" #: ../../using/ios.rst:65 msgid "" "The Python standard library has some notable omissions and restrictions on " -"iOS. See the :ref:`API availability guide for iOS ` for " +"iOS. See the :ref:`API availability guide for iOS ` for " "details." msgstr "" "A biblioteca padrão do Python tem algumas omissões e restrições notáveis no " -"iOS. Consulte o :ref:`guia de disponibilidade de API para iOS ` para obter detalhes." #: ../../using/ios.rst:70 @@ -325,7 +325,7 @@ msgstr "" "Para evitar esses problemas, o Python forneceu stubs para essas ferramentas. " "Esses stubs são wrappers de script de shell em torno das ferramentas " "subjacentes ``xcrun``, distribuídos em uma pasta ``bin`` distribuída junto " -"com a estrutura iOS compilada. Esses scripts são relocáveis ​​e sempre serão " +"com a estrutura iOS compilada. Esses scripts são relocáveis e sempre serão " "resolvidos para os caminhos apropriados do sistema local. Ao incluir esses " "scripts na pasta bin que acompanha um framework, o conteúdo do módulo " "``sysconfig`` se torna útil para usuários finais compilarem seus próprios " @@ -507,6 +507,34 @@ msgstr "" "Target Specific Python Standard Library\", desative a caixa de seleção " "\"Based on dependency analysis\" e defina o conteúdo do script como:" +#: ../../using/ios.rst:220 +msgid "" +"set -e\n" +"\n" +"mkdir -p \"$CODESIGNING_FOLDER_PATH/python/lib\"\n" +"if [ \"$EFFECTIVE_PLATFORM_NAME\" = \"-iphonesimulator\" ]; then\n" +" echo \"Installing Python modules for iOS Simulator\"\n" +" rsync -au --delete \"$PROJECT_DIR/Python.xcframework/ios-arm64_x86_64-" +"simulator/lib/\" \"$CODESIGNING_FOLDER_PATH/python/lib/\"\n" +"else\n" +" echo \"Installing Python modules for iOS Device\"\n" +" rsync -au --delete \"$PROJECT_DIR/Python.xcframework/ios-arm64/lib/\" " +"\"$CODESIGNING_FOLDER_PATH/python/lib/\"\n" +"fi" +msgstr "" +"set -e\n" +"\n" +"mkdir -p \"$CODESIGNING_FOLDER_PATH/python/lib\"\n" +"if [ \"$EFFECTIVE_PLATFORM_NAME\" = \"-iphonesimulator\" ]; then\n" +" echo \"Instalando módulos Python para iOS Simulator\"\n" +" rsync -au --delete \"$PROJECT_DIR/Python.xcframework/ios-arm64_x86_64-" +"simulator/lib/\" \"$CODESIGNING_FOLDER_PATH/python/lib/\"\n" +"else\n" +" echo \"Instalando módulos Python para iOS Device\"\n" +" rsync -au --delete \"$PROJECT_DIR/Python.xcframework/ios-arm64/lib/\" " +"\"$CODESIGNING_FOLDER_PATH/python/lib/\"\n" +"fi" + #: ../../using/ios.rst:233 msgid "" "Note that the name of the simulator \"slice\" in the XCframework may be " @@ -529,6 +557,133 @@ msgstr "" "etapa 8, chamada \"Prepare Python Binary Modules\". Também deve ter \"Based " "on dependency analysis\" desmarcado, com o seguinte conteúdo de script:" +#: ../../using/ios.rst:242 +msgid "" +"set -e\n" +"\n" +"install_dylib () {\n" +" INSTALL_BASE=$1\n" +" FULL_EXT=$2\n" +"\n" +" # The name of the extension file\n" +" EXT=$(basename \"$FULL_EXT\")\n" +" # The location of the extension file, relative to the bundle\n" +" RELATIVE_EXT=${FULL_EXT#$CODESIGNING_FOLDER_PATH/}\n" +" # The path to the extension file, relative to the install base\n" +" PYTHON_EXT=${RELATIVE_EXT/$INSTALL_BASE/}\n" +" # The full dotted name of the extension module, constructed from the " +"file path.\n" +" FULL_MODULE_NAME=$(echo $PYTHON_EXT | cut -d \".\" -f 1 | tr \"/\" \"." +"\");\n" +" # A bundle identifier; not actually used, but required by Xcode " +"framework packaging\n" +" FRAMEWORK_BUNDLE_ID=$(echo $PRODUCT_BUNDLE_IDENTIFIER.$FULL_MODULE_NAME " +"| tr \"_\" \"-\")\n" +" # The name of the framework folder.\n" +" FRAMEWORK_FOLDER=\"Frameworks/$FULL_MODULE_NAME.framework\"\n" +"\n" +" # If the framework folder doesn't exist, create it.\n" +" if [ ! -d \"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER\" ]; then\n" +" echo \"Creating framework for $RELATIVE_EXT\"\n" +" mkdir -p \"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER\"\n" +" cp \"$CODESIGNING_FOLDER_PATH/dylib-Info-template.plist\" " +"\"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER/Info.plist\"\n" +" plutil -replace CFBundleExecutable -string \"$FULL_MODULE_NAME\" " +"\"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER/Info.plist\"\n" +" plutil -replace CFBundleIdentifier -string \"$FRAMEWORK_BUNDLE_ID\" " +"\"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER/Info.plist\"\n" +" fi\n" +"\n" +" echo \"Installing binary for $FRAMEWORK_FOLDER/$FULL_MODULE_NAME\"\n" +" mv \"$FULL_EXT\" \"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER/" +"$FULL_MODULE_NAME\"\n" +" # Create a placeholder .fwork file where the .so was\n" +" echo \"$FRAMEWORK_FOLDER/$FULL_MODULE_NAME\" > ${FULL_EXT%.so}.fwork\n" +" # Create a back reference to the .so file location in the framework\n" +" echo \"${RELATIVE_EXT%.so}.fwork\" > \"$CODESIGNING_FOLDER_PATH/" +"$FRAMEWORK_FOLDER/$FULL_MODULE_NAME.origin\"\n" +" }\n" +"\n" +" PYTHON_VER=$(ls -1 \"$CODESIGNING_FOLDER_PATH/python/lib\")\n" +" echo \"Install Python $PYTHON_VER standard library extension modules...\"\n" +" find \"$CODESIGNING_FOLDER_PATH/python/lib/$PYTHON_VER/lib-dynload\" -name " +"\"*.so\" | while read FULL_EXT; do\n" +" install_dylib python/lib/$PYTHON_VER/lib-dynload/ \"$FULL_EXT\"\n" +" done\n" +"\n" +" # Clean up dylib template\n" +" rm -f \"$CODESIGNING_FOLDER_PATH/dylib-Info-template.plist\"\n" +"\n" +" echo \"Signing frameworks as $EXPANDED_CODE_SIGN_IDENTITY_NAME " +"($EXPANDED_CODE_SIGN_IDENTITY)...\"\n" +" find \"$CODESIGNING_FOLDER_PATH/Frameworks\" -name \"*.framework\" -exec /" +"usr/bin/codesign --force --sign \"$EXPANDED_CODE_SIGN_IDENTITY\" " +"${OTHER_CODE_SIGN_FLAGS:-} -o runtime --timestamp=none --preserve-" +"metadata=identifier,entitlements,flags --generate-entitlement-der \"{}\" \\;" +msgstr "" +"set -e\n" +"\n" +"install_dylib () {\n" +" INSTALL_BASE=$1\n" +" FULL_EXT=$2\n" +"\n" +" # O nome do arquivo da extensão\n" +" EXT=$(basename \"$FULL_EXT\")\n" +" # A localização do arquivo da extensão, relativo ao pacote\n" +" RELATIVE_EXT=${FULL_EXT#$CODESIGNING_FOLDER_PATH/}\n" +" # O caminho para o arquivo da extensão, relativo à base de instalação\n" +" PYTHON_EXT=${RELATIVE_EXT/$INSTALL_BASE/}\n" +" # O nome completo e pontilhado do módulo de extensão, construído a " +"partir do caminho do arquivo.\n" +" FULL_MODULE_NAME=$(echo $PYTHON_EXT | cut -d \".\" -f 1 | tr \"/\" \"." +"\");\n" +" # Um identificador de pacote; não é realmente usado, mas é necessário " +"para empacotamento de frameworks no Xcode\n" +" FRAMEWORK_BUNDLE_ID=$(echo $PRODUCT_BUNDLE_IDENTIFIER.$FULL_MODULE_NAME " +"| tr \"_\" \"-\")\n" +" # O nome da pasta do framework.\n" +" FRAMEWORK_FOLDER=\"Frameworks/$FULL_MODULE_NAME.framework\"\n" +"\n" +" # Se a pasta do framework não existir, cria-a.\n" +" if [ ! -d \"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER\" ]; then\n" +" echo \"Criando framework para $RELATIVE_EXT\"\n" +" mkdir -p \"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER\"\n" +" cp \"$CODESIGNING_FOLDER_PATH/dylib-Info-template.plist\" " +"\"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER/Info.plist\"\n" +" plutil -replace CFBundleExecutable -string \"$FULL_MODULE_NAME\" " +"\"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER/Info.plist\"\n" +" plutil -replace CFBundleIdentifier -string \"$FRAMEWORK_BUNDLE_ID\" " +"\"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER/Info.plist\"\n" +" fi\n" +"\n" +" echo \"Instalando binário para $FRAMEWORK_FOLDER/$FULL_MODULE_NAME\"\n" +" mv \"$FULL_EXT\" \"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER/" +"$FULL_MODULE_NAME\"\n" +" # Cria um arquivo substituto .fwork onde o .so estava\n" +" echo \"$FRAMEWORK_FOLDER/$FULL_MODULE_NAME\" > ${FULL_EXT%.so}.fwork\n" +" # Cria uma referência para o local do arquivo .so no framework\n" +" echo \"${RELATIVE_EXT%.so}.fwork\" > \"$CODESIGNING_FOLDER_PATH/" +"$FRAMEWORK_FOLDER/$FULL_MODULE_NAME.origin\"\n" +"}\n" +"\n" +"PYTHON_VER=$(ls -1 \"$CODESIGNING_FOLDER_PATH/python/lib\")\n" +"echo \"Instalando módulos de extensão da biblioteca padrão para Python " +"$PYTHON_VER...\"\n" +"find \"$CODESIGNING_FOLDER_PATH/python/lib/$PYTHON_VER/lib-dynload\" -name " +"\"*.so\" | while read FULL_EXT; do\n" +" install_dylib python/lib/$PYTHON_VER/lib-dynload/ \"$FULL_EXT\"\n" +"done\n" +"\n" +"# Remove o modelo dylib\n" +"rm -f \"$CODESIGNING_FOLDER_PATH/dylib-Info-template.plist\"\n" +"\n" +"echo \"Assinando frameworks como $EXPANDED_CODE_SIGN_IDENTITY_NAME " +"($EXPANDED_CODE_SIGN_IDENTITY)...\"\n" +"find \"$CODESIGNING_FOLDER_PATH/Frameworks\" -name \"*.framework\" -exec /" +"usr/bin/codesign --force --sign \"$EXPANDED_CODE_SIGN_IDENTITY\" " +"${OTHER_CODE_SIGN_FLAGS:-} -o runtime --timestamp=none --preserve-" +"metadata=identifier,entitlements,flags --generate-entitlement-der \"{}\" \\;" + #: ../../using/ios.rst:292 msgid "" "Add Objective C code to initialize and use a Python interpreter in embedded " @@ -538,25 +693,26 @@ msgstr "" "em modo embarcado. Você deve garantir que:" #: ../../using/ios.rst:295 -msgid ":c:member:`UTF-8 mode ` is *enabled*;" -msgstr ":c:member:`Modo UTF-8 ` esteja *enabled*;" +msgid "UTF-8 mode (:c:member:`PyPreConfig.utf8_mode`) is *enabled*;" +msgstr "Modo UTF-8 (:c:member:`PyPreConfig.utf8_mode`) esteja habilitado;" #: ../../using/ios.rst:296 -msgid ":c:member:`Buffered stdio ` is *disabled*;" +msgid "Buffered stdio (:c:member:`PyConfig.buffered_stdio`) is *disabled*;" msgstr "" -":c:member:`Buffered stdio ` esteja *disabled*;" +"Stdio buffered (:c:member:`PyConfig.buffered_stdio`) esteja desabilitado;" #: ../../using/ios.rst:297 -msgid ":c:member:`Writing bytecode ` is *disabled*;" +msgid "Writing bytecode (:c:member:`PyConfig.write_bytecode`) is *disabled*;" msgstr "" -":c:member:`Escrita de bytecode ` esteja *disabled*;" +"Escrita de bytecode (:c:member:`PyConfig.write_bytecode`) esteja " +"desabilitada;" #: ../../using/ios.rst:298 msgid "" -":c:member:`Signal handlers ` are *enabled*;" +"Signal handlers (:c:member:`PyConfig.install_signal_handlers`) are *enabled*;" msgstr "" -":c:member:`Manipuladores de sinais ` " -"estejam *enabled*;" +"Manipuladores de sinais (:c:member:`PyConfig.install_signal_handlers`) " +"estejam habilitados;" #: ../../using/ios.rst:299 msgid "" @@ -639,10 +795,103 @@ msgstr "" "``PYTHONPATH`` no passo 10." #: ../../using/ios.rst:328 +msgid "Testing a Python package" +msgstr "Testando um pacote Python" + +#: ../../using/ios.rst:330 +msgid "" +"The CPython source tree contains :source:`a testbed project ` " +"that is used to run the CPython test suite on the iOS simulator. This " +"testbed can also be used as a testbed project for running your Python " +"library's test suite on iOS." +msgstr "" +"A árvore de fontes do CPython contém :source:`um projeto de banco de testes " +"` que é usado para executar o conjunto de testes do CPython no " +"simulador do iOS. Este banco de testes também pode ser usado como um projeto " +"de banco de testes para executar o conjunto de testes da sua biblioteca " +"Python no iOS." + +#: ../../using/ios.rst:334 +msgid "" +"After building or obtaining an iOS XCFramework (See :source:`iOS/README.rst` " +"for details), create a clone of the Python iOS testbed project by running:" +msgstr "" +"Depois de criar ou obter um iOS XCFramework (consulte :source:`iOS/README." +"rst` para obter detalhes), crie um clone do projeto de banco de testes de " +"iOS do Python executando:" + +#: ../../using/ios.rst:337 +msgid "" +"$ python iOS/testbed clone --framework --app " +" --app app-testbed" +msgstr "" +"$ python iOS/testbed clone --framework --" +"app --app app-testbed" + +#: ../../using/ios.rst:341 +msgid "" +"You will need to modify the ``iOS/testbed`` reference to point to that " +"directory in the CPython source tree; any folders specified with the ``--" +"app`` flag will be copied into the cloned testbed project. The resulting " +"testbed will be created in the ``app-testbed`` folder. In this example, the " +"``module1`` and ``module2`` would be importable modules at runtime. If your " +"project has additional dependencies, they can be installed into the ``app-" +"testbed/iOSTestbed/app_packages`` folder (using ``pip install --target app-" +"testbed/iOSTestbed/app_packages`` or similar)." +msgstr "" +"Você precisará modificar a referência ``iOS/testbed`` para apontar para esse " +"diretório na árvore de fontes do CPython; todas as pastas especificadas com " +"o sinalizador ``--app`` serão copiadas para o projeto de banco de testes " +"clonado. O banco de testes resultante será criado na pasta ``app-testbed``. " +"Neste exemplo, ``módulo1`` e ``módulo2`` seriam módulos importáveis em tempo " +"de execução. Se seu projeto tiver dependências adicionais, elas podem ser " +"instaladas na pasta ``app-testbed/iOSTestbed/app_packages`` (usando ``pip " +"install --target app-testbed/iOSTestbed/app_packages`` ou similar)." + +#: ../../using/ios.rst:350 +msgid "" +"You can then use the ``app-testbed`` folder to run the test suite for your " +"app, For example, if ``module1.tests`` was the entry point to your test " +"suite, you could run:" +msgstr "" +"Você pode então usar a pasta ``app-testbed`` para executar o conjunto de " +"testes para seu aplicativo. Por exemplo, se ``módulo1.tests`` fosse o ponto " +"de entrada para seu conjunto de testes, você poderia executar:" + +#: ../../using/ios.rst:354 +msgid "$ python app-testbed run -- module1.tests" +msgstr "$ python app-testbed run -- módulo1.tests" + +#: ../../using/ios.rst:358 +msgid "" +"This is the equivalent of running ``python -m module1.tests`` on a desktop " +"Python build. Any arguments after the ``--`` will be passed to the testbed " +"as if they were arguments to ``python -m`` on a desktop machine." +msgstr "" +"Isso é o equivalente a executar ``python -m módulo1.tests`` em uma " +"compilação Python de desktop. Quaisquer argumentos após ``--`` serão " +"passados para o banco de testes como se fossem argumentos para ``python -m`` " +"em uma máquina de desktop." + +#: ../../using/ios.rst:362 +msgid "You can also open the testbed project in Xcode by running:" +msgstr "Você também pode abrir o projeto de teste no Xcode executando:" + +#: ../../using/ios.rst:364 +msgid "$ open app-testbed/iOSTestbed.xcodeproj" +msgstr "$ open app-testbed/iOSTestbed.xcodeproj" + +#: ../../using/ios.rst:368 +msgid "This will allow you to use the full Xcode suite of tools for debugging." +msgstr "" +"Isso permitirá que você use o conjunto completo de ferramentas do Xcode para " +"depuração." + +#: ../../using/ios.rst:371 msgid "App Store Compliance" msgstr "Conformidade com a App Store" -#: ../../using/ios.rst:330 +#: ../../using/ios.rst:373 msgid "" "The only mechanism for distributing apps to third-party iOS devices is to " "submit the app to the iOS App Store; apps submitted for distribution must " @@ -657,7 +906,7 @@ msgstr "" "automatizadas que inspecionam o pacote de aplicação enviado em busca de " "código problemático." -#: ../../using/ios.rst:335 +#: ../../using/ios.rst:378 msgid "" "The Python standard library contains some code that is known to violate " "these automated rules. While these violations appear to be false positives, " @@ -670,7 +919,7 @@ msgstr "" "modificar a biblioteca padrão do Python para que uma aplicação passe na " "revisão da App Store." -#: ../../using/ios.rst:340 +#: ../../using/ios.rst:383 msgid "" "The Python source tree contains :source:`a patch file ` that will remove all code that is known to cause " diff --git a/using/mac.po b/using/mac.po index ffa3ec0e5..3d3b4c97c 100644 --- a/using/mac.po +++ b/using/mac.po @@ -1,367 +1,899 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-26 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:51+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../using/mac.rst:6 -msgid "Using Python on a Mac" -msgstr "Utilizando Python em um Mac" - -#: ../../using/mac.rst:0 -msgid "Author" -msgstr "Autor" - -#: ../../using/mac.rst:8 -msgid "Bob Savage " -msgstr "Bob Savage " +msgid "Using Python on macOS" +msgstr "Usando Python em macOS" #: ../../using/mac.rst:11 msgid "" -"Python on a Mac running macOS is in principle very similar to Python on any " -"other Unix platform, but there are a number of additional features such as " -"the integrated development environment (IDE) and the Package Manager that " -"are worth pointing out." -msgstr "" -"O Python em um Mac executando o macOS é, em princípio, muito semelhante ao " -"Python em qualquer outra plataforma Unix, mas há vários recursos adicionais, " -"como o ambiente integrado de desenvolvimento (IDE) e o Gerenciador de " -"Pacotes, que merecem destaque." - -#: ../../using/mac.rst:21 -msgid "Getting and Installing Python" -msgstr "Obtendo e instalando o Python" - -#: ../../using/mac.rst:23 -msgid "" -"macOS used to come with Python 2.7 pre-installed between versions 10.8 and " -"`12.3 `_. You are invited to install the most " -"recent version of Python 3 from the `Python website `__. A current \"universal2 binary\" build of Python, which " -"runs natively on the Mac's new Apple Silicon and legacy Intel processors, is " -"available there." -msgstr "" -"O macOS costumava vir com o Python 2.7 pré-instalado entre as versões 10.8 e " -"`12.3 `_. Convidamos você a instalar a versão mais " -"recente do Python 3 no `site do Python `__.. Uma versão atual do \"binário universal2\" do Python, que " -"funciona nativamente nos novos processadores Apple Silicon e nos legados " -"Intel do Mac, está disponível lá." - -#: ../../using/mac.rst:30 -msgid "What you get after installing is a number of things:" -msgstr "O que você obtém após a instalação é uma série de coisas:" - -#: ../../using/mac.rst:32 -msgid "" -"A |python_version_literal| folder in your :file:`Applications` folder. In " -"here you find IDLE, the development environment that is a standard part of " -"official Python distributions; and :program:`Python Launcher`, which handles " -"double-clicking Python scripts from the Finder." -msgstr "" -"A pasta |python_version_literal| na sua pasta :file:`Applications`. Aqui " -"você encontra o IDLE, o ambiente de desenvolvimento que é parte padrão das " -"distribuições oficiais do Python; e :program:`Python Launcher`, que lida com " -"scripts de Python clicando duas vezes no Finder." +"This document aims to give an overview of macOS-specific behavior you should " +"know about to get started with Python on Mac computers. Python on a Mac " +"running macOS is very similar to Python on other Unix-derived platforms, but " +"there are some differences in installation and some features." +msgstr "" +"Este documento tem o objetivo de fornecer uma visão geral dos comportamentos " +"específicos do macOS que você deve conhecer para começar a usar o Python em " +"computadores Mac. O Python em um Mac com macOS é muito semelhante ao Python " +"em outras plataformas derivadas do Unix, mas há algumas diferenças na " +"instalação e alguns recursos." + +#: ../../using/mac.rst:16 +msgid "" +"There are various ways to obtain and install Python for macOS. Pre-built " +"versions of the most recent versions of Python are available from a number " +"of distributors. Much of this document describes use of the Pythons provided " +"by the CPython release team for download from the `python.org website " +"`_. See :ref:`alternative_bundles` for " +"some other options." +msgstr "" +"Há várias maneiras de obter e instalar o Python para macOS. Versões pré-" +"construídas das versões mais recentes do Python estão disponíveis em vários " +"distribuidores. Grande parte deste documento descreve o uso dos Pythons " +"fornecidos pela equipe de lançamento do CPython, disponíveis para download " +"no site `python.org `_. Consulte :ref:" +"`alternative_bundles` para conhecer outras opções." + +#: ../../using/mac.rst:34 +msgid "Using Python for macOS from ``python.org``" +msgstr "Usando Python para macOS do ``python.org``" #: ../../using/mac.rst:37 +msgid "Installation steps" +msgstr "Etapas de instalação" + +#: ../../using/mac.rst:39 +msgid "" +"For `current Python versions `_ (other " +"than those in ``security`` status), the release team produces a **Python for " +"macOS** installer package for each new release. A list of available " +"installers is available `here `_. " +"We recommend using the most recent supported Python version where possible. " +"Current installers provide a `universal2 binary `_ build of Python which runs natively on all Macs " +"(Apple Silicon and Intel) that are supported by a wide range of macOS " +"versions, currently typically from at least **macOS 10.13 High Sierra** on." +msgstr "" +"Para `as versões atuais de Python `_ " +"(exceto as com status ``security``), a equipe de lançamento produz um pacote " +"de instalação **Python para macOS** em cada novo lançamento. Uma lista dos " +"instaladores disponíveis está disponível `aqui `_. Recomendamos usar a versão suportada mais recente de " +"Python sempre que possível. Os instaladores atuais fornecem uma versão de " +"Python como `binário universal 2 `_ que é executado nativamente em todos os Macs " +"(Apple Silicon e Intel) compatíveis com uma ampla gama de versões do macOS, " +"atualmente do **macOS 10.13 High Sierra** em diante." + +#: ../../using/mac.rst:51 +msgid "" +"The downloaded file is a standard macOS installer package file (``.pkg``). " +"File integrity information (checksum, size, sigstore signature, etc) for " +"each file is included on the release download page. Installer packages and " +"their contents are signed and notarized with ``Python Software Foundation`` " +"Apple Developer ID certificates to meet `macOS Gatekeeper requirements " +"`_." +msgstr "" +"O arquivo baixado é um arquivo padrão do instalador de pacotes do macOS (``." +"pkg``). As informações de integridade do arquivo (soma de verificação, " +"tamanho, assinatura de Sigstore, etc.) de cada arquivo estão inclusas na " +"página de download dos lançamentos. Os pacotes de instalação e seus " +"conteúdos são assinados e autenticados com certificados Apple Developer ID " +"``Python Software Foundation`` para atender aos `requisitos do macOS " +"Gatekeeper `_." + +#: ../../using/mac.rst:57 +msgid "" +"For a default installation, double-click on the downloaded installer package " +"file. This should launch the standard macOS Installer app and display the " +"first of several installer windows steps." +msgstr "" +"Para uma instalação padrão, clique duas vezes no arquivo instalador de " +"pacotes baixado. Isso deverá abrir o aplicativo padrão de instalação do " +"macOS e exibir o primeiro de vários passos de instalação." + +#: ../../using/mac.rst:63 +msgid "" +"Clicking on the **Continue** button brings up the **Read Me** for this " +"installer. Besides other important information, the **Read Me** documents " +"which Python version is going to be installed and on what versions of macOS " +"it is supported. You may need to scroll through to read the whole file. By " +"default, this **Read Me** will also be installed in |" +"usemac_applications_folder_version| and available to read anytime." +msgstr "" +"Ao clicar no botão **Continuar**, é exibido o **Read Me** desse instalador. " +"Além de outras informações importantes, o **Read Me** documenta qual versão " +"de Python será instalada e em quais versões do macOS ele é compatível. " +"Talvez você precise rolar a tela para ler o arquivo inteiro. Por padrão, " +"esse **Read Me** também será instalado em |" +"usemac_applications_folder_version| e estará disponível para leitura a " +"qualquer momento." + +#: ../../using/mac.rst:71 +msgid "" +"Clicking on **Continue** proceeds to display the license for Python and for " +"other included software. You will then need to **Agree** to the license " +"terms before proceeding to the next step. This license file will also be " +"installed and available to be read later." +msgstr "" +"Ao clicar em **Continuar**, o instalador exibe a licença do Python e de " +"outros softwares incluídos. Você precisará **Concordar** com os termos da " +"licença antes de prosseguir para a próxima etapa. Esse arquivo de licença " +"também será instalado e estará disponível para leitura a qualquer momento." + +#: ../../using/mac.rst:78 +msgid "" +"After the license terms are accepted, the next step is the **Installation " +"Type** display. For most uses, the standard set of installation operations " +"is appropriate." +msgstr "" +"Após aceitar os termos da licença, a próxima etapa será a tela **Tipo de " +"instalação**. Para a maioria dos usos, o conjunto padrão de operações de " +"instalação é adequado." + +#: ../../using/mac.rst:83 +msgid "" +"By pressing the **Customize** button, you can choose to omit or select " +"certain package components of the installer. Click on each package name to " +"see a description of what it installs. To also install support for the " +"optional experimental free-threaded feature, see :ref:`install-freethreaded-" +"macos`." +msgstr "" +"Ao pressionar o botão **Personalizar**, você pode optar por omitir ou " +"selecionar determinados componentes de pacote do instalador. Clique em cada " +"nome de pacote para ver uma descrição do que ele instala. Para também " +"instalar o suporte para o recurso experimental opcional de threads livres, " +"consulte :ref:`install-freethreaded-macos`." + +#: ../../using/mac.rst:91 +msgid "" +"In either case, clicking **Install** will begin the install process by " +"asking permission to install new software. A macOS user name with " +"``Administrator`` privilege is needed as the installed Python will be " +"available to all users of the Mac." +msgstr "" +"Em ambos os casos, clicar em **Instalar** iniciará o processo de instalação " +"solicitando a permissão para instalar um novo software. É necessário um nome " +"de usuário do macOS com privilégio de ``Administrador``, pois o Python " +"instalado estará disponível para todos os usuários do Mac." + +#: ../../using/mac.rst:95 +msgid "When the installation is complete, the **Summary** window will appear." +msgstr "Quando a instalação for concluída, a janela **Resumo** será exibida." + +#: ../../using/mac.rst:99 +msgid "" +"Double-click on the :command:`Install Certificates.command` icon or file in " +"the |usemac_applications_folder_version| window to complete the installation." +msgstr "" +"Clique duas vezes no ícone ou arquivo :command:`Install Certificates." +"command` na janela |usemac_applications_folder_version| para concluir a " +"instalação." + +#: ../../using/mac.rst:105 +msgid "" +"This will open a temporary :program:`Terminal` shell window that will use " +"the new Python to download and install SSL root certificates for its use." +msgstr "" +"Isso abrirá uma janela temporária do console :program:`Terminal` que usará o " +"novo Python para baixar e instalar certificados raiz SSL para seu uso." + +#: ../../using/mac.rst:111 +msgid "" +"If ``Successfully installed certifi`` and ``update complete`` appears in the " +"terminal window, the installation is complete. Close this terminal window " +"and the installer window." +msgstr "" +"Se ``Successfully installed certifi`` e ``update complete`` aparecerem na " +"janela do terminal, a instalação estará concluída. Feche essa janela do " +"terminal e a janela do instalador." + +#: ../../using/mac.rst:115 +msgid "A default install will include:" +msgstr "Uma instalação do padrão incluirá:" + +#: ../../using/mac.rst:117 +msgid "" +"A |usemac_applications_folder_name| folder in your :file:`Applications` " +"folder. In here you find :program:`IDLE`, the development environment that " +"is a standard part of official Python distributions; and :program:`Python " +"Launcher`, which handles double-clicking Python scripts from the macOS " +"`Finder `_." +msgstr "" +"Uma pasta |usemac_applications_folder_name| em sua pasta :file:" +"`Applications`. Aqui você encontra o :program:`IDLE`, o ambiente de " +"desenvolvimento que é parte das distribuições oficiais do Python; e o :" +"program:`Python Launcher`, que executa scripts Python quando são clicados " +"duas vezes dentro do `Finder `_ ." + +#: ../../using/mac.rst:122 msgid "" "A framework :file:`/Library/Frameworks/Python.framework`, which includes the " "Python executable and libraries. The installer adds this location to your " -"shell path. To uninstall Python, you can remove these three things. A " -"symlink to the Python executable is placed in :file:`/usr/local/bin/`." -msgstr "" -"Um framework :file:`/Library/Frameworks/Python.framework`, que inclui o " -"executável e as bibliotecas do Python. O instalador adiciona esse local ao " -"seu caminho do console. Para desinstalar o Python, você pode remover essas " -"três coisas. Um link simbólico para o executável Python é colocado em :file:" -"`/usr/local/bin/`." - -#: ../../using/mac.rst:44 -msgid "" -"On macOS 10.8-12.3, the Apple-provided build of Python is installed in :file:" -"`/System/Library/Frameworks/Python.framework` and :file:`/usr/bin/python`, " -"respectively. You should never modify or delete these, as they are Apple-" -"controlled and are used by Apple- or third-party software. Remember that if " -"you choose to install a newer Python version from python.org, you will have " -"two different but functional Python installations on your computer, so it " -"will be important that your paths and usages are consistent with what you " -"want to do." -msgstr "" -"No macOS da versão 10.8 ao 12.3, a construção do Python fornecido pela Apple " -"é instalada em :file:`/System/Library/Frameworks/Python.framework` e :file:`/" -"usr/bin/python`, respectivamente. Você nunca deve modificá-las ou excluí-" -"las, pois elas são controladas pela Apple e são usadas por software da Apple " -"ou de terceiros. Lembre-se de que, se você optar por instalar uma versão " -"mais recente do Python a partir do python.org, terá duas instalações Python " -"diferentes, mas funcionais, no seu computador, por isso será importante que " -"seus caminhos e usos sejam consistentes com o que você deseja fazer." - -#: ../../using/mac.rst:52 -msgid "" -"IDLE includes a Help menu that allows you to access Python documentation. If " -"you are completely new to Python you should start reading the tutorial " -"introduction in that document." -msgstr "" -"O IDLE inclui um menu Help (de ajuda) que permite acessar a documentação do " -"Python. Se você é completamente novo no Python, comece a ler a introdução do " -"tutorial nesse documento." - -#: ../../using/mac.rst:56 -msgid "" -"If you are familiar with Python on other Unix platforms you should read the " -"section on running Python scripts from the Unix shell." -msgstr "" -"Se você está familiarizado com o Python em outras plataformas Unix, leia a " -"seção sobre a execução de scripts Python no shell do Unix." - -#: ../../using/mac.rst:61 +"shell path. To uninstall Python, you can remove these three things. Symlinks " +"to the Python executable are placed in :file:`/usr/local/bin/`." +msgstr "" +"Uma framework :file:`/Library/Frameworks/Python.framework`, que inclui o " +"executável Python e suas bibliotecas. O instalador adiciona esse local ao " +"seu *path* do console. Para desinstalar o Python, você pode remover esses " +"três itens. É um link simbólico para o executável Python armazenado na " +"pasta :file:`/usr/local/bin/`." + +#: ../../using/mac.rst:129 +msgid "" +"Recent versions of macOS include a :command:`python3` command in :file:`/usr/" +"bin/python3` that links to a usually older and incomplete version of Python " +"provided by and for use by the Apple development tools, :program:`Xcode` or " +"the :program:`Command Line Tools for Xcode`. You should never modify or " +"attempt to delete this installation, as it is Apple-controlled and is used " +"by Apple-provided or third-party software. If you choose to install a newer " +"Python version from ``python.org``, you will have two different but " +"functional Python installations on your computer that can co-exist. The " +"default installer options should ensure that its :command:`python3` will be " +"used instead of the system :command:`python3`." +msgstr "" +"As versões recentes do macOS incluem um comando :command:`python3` em :file:" +"`/usr/bin/python3` que aponta para uma versão geralmente mais antiga e " +"incompleta de Python fornecida por e para uso pelas ferramentas de " +"desenvolvimento da Apple, :program:`Xcode` ou o :program:`Command Line Tools " +"for Xcode`. Você nunca deve modificar ou tentar excluir essa instalação por " +"ser controlada pela Apple e é usada por softwares da Apple ou de terceiros. " +"Se você optar por instalar uma versão mais recente do Python a partir de " +"``python.org``, você terá duas instalações diferentes, mas funcionais, de " +"Python no computador que podem coexistir. As opções do instalador padrão " +"devem garantir que o comando :command:`python3` seja usado em vez do :" +"command:`python3` do sistema." + +#: ../../using/mac.rst:140 msgid "How to run a Python script" msgstr "Como executar um script Python" -#: ../../using/mac.rst:63 +#: ../../using/mac.rst:142 msgid "" -"Your best way to get started with Python on macOS is through the IDLE " -"integrated development environment; see section :ref:`ide` and use the Help " -"menu when the IDE is running." -msgstr "" -"A melhor maneira de você começar o uso do Python no macOS é através do " -"ambiente de desenvolvimento integrado IDLE. Consulte a seção :ref:`ide` e " -"use o menu Help quando o IDE estiver em execução." - -#: ../../using/mac.rst:67 -msgid "" -"If you want to run Python scripts from the Terminal window command line or " -"from the Finder you first need an editor to create your script. macOS comes " -"with a number of standard Unix command line editors, :program:`vim` :program:" -"`nano` among them. If you want a more Mac-like editor, :program:`BBEdit` " -"from Bare Bones Software (see https://www.barebones.com/products/bbedit/" -"index.html) are good choices, as is :program:`TextMate` (see https://" -"macromates.com). Other editors include :program:`MacVim` (https://macvim." -"org) and :program:`Aquamacs` (https://aquamacs.org)." -msgstr "" -"Se você deseja executar scripts Python na linha de comando da janela " -"Terminal ou no Finder, primeiro precisa de um editor para criar seu script. " -"O macOS vem com vários editores de linha de comando padrão do Unix, entre os " -"quais :program:`vim` e :program:`nano`. Se você deseja um editor mais ao " -"estilo do Mac, :program:`BBEdit` da Bare Bones Software (consulte https://" -"www.barebones.com/products/bbedit/index.html) são boas escolhas , como é :" -"program:`TextMate` (consulte https://macromates.com). Outros editores " -"incluem :program:`MacVim` (https://macvim.org) e :program:`Aquamacs` " -"(https://aquamacs.org)." - -#: ../../using/mac.rst:77 -msgid "" -"To run your script from the Terminal window you must make sure that :file:`/" -"usr/local/bin` is in your shell search path." -msgstr "" -"Para executar seu script a partir da janela do Terminal, você deve se " -"certificar de que :file:`/usr/local/bin` esteja no seu caminho de pesquisa " -"do shell." - -#: ../../using/mac.rst:80 -msgid "To run your script from the Finder you have two options:" -msgstr "Para executar seu script no Finder, você tem duas opções:" - -#: ../../using/mac.rst:82 +"There are two ways to invoke the Python interpreter. If you are familiar " +"with using a Unix shell in a terminal window, you can invoke |" +"usemac_python_x_dot_y_literal| or ``python3`` optionally followed by one or " +"more command line options (described in :ref:`using-on-general`). The Python " +"tutorial also has a useful section on :ref:`using Python interactively from " +"a shell `." +msgstr "" +"Há duas maneiras de invocar o interpretador Python. Se você estiver " +"familiarizado com o uso de um console Unix em terminal, você pode invocar |" +"usemac_python_x_dot_y_literal| ou ``python3``, opcionalmente seguido por uma " +"ou mais opções da linha de comando (descritas em :ref:`using-on-general`). O " +"tutorial de Python também tem uma seção útil sobre o :ref:`uso interativo do " +"Python a partir de um console `." + +#: ../../using/mac.rst:149 +msgid "" +"You can also invoke the interpreter through an integrated development " +"environment. :ref:`idle` is a basic editor and interpreter environment which " +"is included with the standard distribution of Python. :program:`IDLE` " +"includes a Help menu that allows you to access Python documentation. If you " +"are completely new to Python, you can read the tutorial introduction in that " +"document." +msgstr "" +"Você também pode invocar o interpretador por um ambiente de desenvolvimento " +"integrado (IDE). O :ref:`idle` é um editor e ambiente de desenvolvimento " +"básico incluído com a distribuição padrão de Python. :program:`IDLE` inclui " +"um menu Ajuda que te permite acessar a documentação de Python. Se você for " +"completamente iniciante em Python, você pode ler o tutorial de introdução na " +"documentação." + +#: ../../using/mac.rst:157 +msgid "" +"There are many other editors and IDEs available, see :ref:`editors` for more " +"information." +msgstr "" +"Há muitos outros editores e IDEs disponíveis. Consulte :ref:`editors` para " +"mais informações." + +#: ../../using/mac.rst:160 +msgid "" +"To run a Python script file from the terminal window, you can invoke the " +"interpreter with the name of the script file:" +msgstr "" +"Para executar um script Python na janela do terminal, você pode invocar o " +"interpretador com o nome do arquivo de script:" + +#: ../../using/mac.rst:163 +msgid "|usemac_python_x_dot_y_literal| ``myscript.py``" +msgstr "|usemac_python_x_dot_y_literal| ``myscript.py``" + +#: ../../using/mac.rst:165 +msgid "To run your script from the Finder, you can either:" +msgstr "Para executar seu script a partir do Finder, você pode:" + +#: ../../using/mac.rst:167 msgid "Drag it to :program:`Python Launcher`." msgstr "Arrastá-lo para o :program:`Python Launcher`." -#: ../../using/mac.rst:84 +#: ../../using/mac.rst:169 msgid "" "Select :program:`Python Launcher` as the default application to open your " -"script (or any ``.py`` script) through the finder Info window and double-" +"script (or any ``.py`` script) through the Finder Info window and double-" "click it. :program:`Python Launcher` has various preferences to control how " "your script is launched. Option-dragging allows you to change these for one " -"invocation, or use its Preferences menu to change things globally." +"invocation, or use its ``Preferences`` menu to change things globally." msgstr "" -"Selecionar :program:`Python Launcher` como aplicação padrão para abrir seu " -"script (ou qualquer script ``.py``) através da janela de Informações do " -"Finder e clique duas vezes nele. :program:`Python Launcher` tem várias " -"preferências para controlar como o script é iniciado. Arrastar com opções " -"permite alterar esses itens para uma chamada ou usar o menu Preferências " -"para alterar as coisas globalmente." +"Selecione :program:`Python Launcher` como a aplicação padrão para abrir seu " +"script (ou qualquer script ``.py``) na janela de informações Finder Info, e " +"clique duas vezes nele. O :program:`Python Launcher` tem várias preferências " +"para controlar como o script é iniciado. Você pode arrastar opções para " +"alterá-las por uma invocação, ou usar o menu ``Preferências`` para alterar " +"configurações globalmente." -#: ../../using/mac.rst:94 -msgid "Running scripts with a GUI" -msgstr "Executando scripts como uma GUI" - -#: ../../using/mac.rst:96 +#: ../../using/mac.rst:175 msgid "" -"With older versions of Python, there is one macOS quirk that you need to be " -"aware of: programs that talk to the Aqua window manager (in other words, " -"anything that has a GUI) need to be run in a special way. Use :program:" -"`pythonw` instead of :program:`python` to start such scripts." +"Be aware that running the script directly from the macOS Finder might " +"produce different results than when running from a terminal window as the " +"script will not be run in the usual shell environment including any setting " +"of environment variables in shell profiles. And, as with any other script or " +"program, be certain of what you are about to run." msgstr "" -"Nas versões mais antigas do Python, há uma peculiaridade do macOS que você " -"precisa conhecer: os programas que conversam com o gerenciador de janelas " -"Aqua (em outras palavras, qualquer coisa que tenha uma GUI) precisam ser " -"executados de uma maneira especial. Use :program:`pythonw` em vez de :" -"program:`python` para iniciar esses scripts." +"Saiba que executar o script diretamente do Finder pode produzir resultados " +"diferentes daqueles obtidos em uma janela de terminal, pois o script não " +"será executado no ambiente normal do console, incluindo qualquer " +"configuração de variáveis de ambiente nos perfis do console. E, como em " +"qualquer outro script ou programa, certifique-se do que está prestes a " +"executar." -#: ../../using/mac.rst:101 +#: ../../using/mac.rst:185 +msgid "Alternative Distributions" +msgstr "Distribuições alternativas" + +#: ../../using/mac.rst:187 msgid "" -"With Python 3.9, you can use either :program:`python` or :program:`pythonw`." +"Besides the standard ``python.org`` for macOS installer, there are third-" +"party distributions for macOS that may include additional functionality. " +"Some popular distributions and their key features:" msgstr "" -"Com o Python 3.9, você pode usar :program:`python` ou :program:`pythonw`." +"Além do instalador padrão do ``python.org`` para macOS, existem " +"distribuições de terceiros para macOS que podem incluir funcionalidades " +"adicionais. Algumas distribuições populares e seus recursos-chave são:" -#: ../../using/mac.rst:105 -msgid "Configuration" -msgstr "Configuração" +#: ../../using/mac.rst:191 +msgid "`ActivePython `_" +msgstr "`ActivePython `_" + +#: ../../using/mac.rst:192 +msgid "Installer with multi-platform compatibility, documentation" +msgstr "Instalador com compatibilidade multiplataforma, documentação" + +#: ../../using/mac.rst:194 +msgid "`Anaconda `_" +msgstr "`Anaconda `_" -#: ../../using/mac.rst:107 +#: ../../using/mac.rst:195 msgid "" -"Python on macOS honors all standard Unix environment variables such as :" -"envvar:`PYTHONPATH`, but setting these variables for programs started from " -"the Finder is non-standard as the Finder does not read your :file:`.profile` " -"or :file:`.cshrc` at startup. You need to create a file :file:`~/.MacOSX/" -"environment.plist`. See Apple's `Technical Q&A QA1067 `__ for details." +"Popular scientific modules (such as numpy, scipy, and pandas) and the " +"``conda`` package manager." msgstr "" -"O Python no macOS honra todas as variáveis de ambiente padrão do Unix, como :" -"envvar:`PYTHONPATH`, mas definir essas variáveis para programas iniciados no " -"Finder não é padrão, pois o Finder não lê o seu :file:`.profile` ou :file:`." -"cshrc` na inicialização. Você precisa criar um arquivo :file:`~/.MacOSX/" -"environment.plist`. Consulte o `Technical Q&A QA1067 `__ para obter detalhes." +"Módulos científicos populares (como numpy, scipy e pandas) e o gerenciador " +"de pacotes ``conda``." -#: ../../using/mac.rst:115 +#: ../../using/mac.rst:198 +msgid "`Homebrew `_" +msgstr "`Homebrew `_" + +#: ../../using/mac.rst:199 msgid "" -"For more information on installation Python packages, see section :ref:`mac-" -"package-manager`." +"Package manager for macOS including multiple versions of Python and many " +"third-party Python-based packages (including numpy, scipy, and pandas)." msgstr "" -"Para obter mais informações sobre a instalação de pacotes Python, consulte a " -"seção :ref:`mac-package-manager`." +"Gerenciador de pacotes para macOS que inclui várias versões do Python e " +"muitos pacotes Python de terceiros (incluindo numpy, scipy e pandas)." -#: ../../using/mac.rst:122 -msgid "The IDE" -msgstr "A IDE" +#: ../../using/mac.rst:202 +msgid "`MacPorts `_" +msgstr "`MacPorts `_" -#: ../../using/mac.rst:124 +#: ../../using/mac.rst:203 msgid "" -"Python ships with the standard IDLE development environment. A good " -"introduction to using IDLE can be found at https://www.hashcollision.org/hkn/" -"python/idle_intro/index.html." +"Another package manager for macOS including multiple versions of Python and " +"many third-party Python-based packages. May include pre-built versions of " +"Python and many packages for older versions of macOS." msgstr "" -"O Python é fornecido com o ambiente de desenvolvimento IDLE padrão. Uma boa " -"introdução ao uso do IDLE pode ser encontrada em https://www.hashcollision." -"org/hkn/python/idle_intro/index.html." +"Outro gerenciador de pacotes para macOS, incluindo várias versões de Python " +"e muitos pacotes Python de terceiros. Pode incluir versões pré-construídas " +"do Python e muitos pacotes para versões mais antigas do macOS." -#: ../../using/mac.rst:132 +#: ../../using/mac.rst:207 +msgid "" +"Note that distributions might not include the latest versions of Python or " +"other libraries, and are not maintained or supported by the core Python team." +msgstr "" +"Note que distribuições podem não incluir versões mais recentes de Python ou " +"de outras bibliotecas, e não são mantidas ou providas pela equipe do Python." + +#: ../../using/mac.rst:213 msgid "Installing Additional Python Packages" msgstr "Instalando pacotes adicionais ao python" -#: ../../using/mac.rst:134 -msgid "This section has moved to the `Python Packaging User Guide`_." +#: ../../using/mac.rst:215 +msgid "Refer to the `Python Packaging User Guide`_ for more information." msgstr "" -"Esta seção foi movida para o `Guia de Usuário para Empacotamento de Python`_." +"Consulte o `Guia de Usuário para Empacotamento de Python`_ para mais " +"informações." -#: ../../using/mac.rst:142 +#: ../../using/mac.rst:225 msgid "GUI Programming" msgstr "Programação de GUI" -#: ../../using/mac.rst:144 +#: ../../using/mac.rst:227 msgid "" "There are several options for building GUI applications on the Mac with " "Python." msgstr "Existem várias opções para criar aplicações GUI no Mac com Python." -#: ../../using/mac.rst:146 +#: ../../using/mac.rst:229 msgid "" -"*PyObjC* is a Python binding to Apple's Objective-C/Cocoa framework, which " -"is the foundation of most modern Mac development. Information on PyObjC is " -"available from :pypi:`pyobjc`." +"The standard Python GUI toolkit is :mod:`tkinter`, based on the cross-" +"platform Tk toolkit (https://www.tcl.tk). A macOS-native version of Tk is " +"included with the installer." msgstr "" -"*PyObjC* é uma ligação do Python para o framework Objective-C/Cocoa da " -"Apple, que é a base do desenvolvimento mais moderno do Mac. Informações " -"sobre PyObjC estão disponíveis em :pypi:`pyobjc`." +"O kit de ferramentas GUI padrão de Python é o módulo :mod:`tkinter`, baseado " +"no kit de ferramentas multiplataforma Tk (https://www.tcl.tk). Uma versão " +"nativa do Tk para macOS está incluída no instalador." -#: ../../using/mac.rst:150 +#: ../../using/mac.rst:233 msgid "" -"The standard Python GUI toolkit is :mod:`tkinter`, based on the cross-" -"platform Tk toolkit (https://www.tcl.tk). An Aqua-native version of Tk is " -"bundled with macOS by Apple, and the latest version can be downloaded and " -"installed from https://www.activestate.com; it can also be built from source." +"*PyObjC* is a Python binding to Apple's Objective-C/Cocoa framework. " +"Information on PyObjC is available from :pypi:`pyobjc`." msgstr "" -"O kit de ferramentas de GUI padrão do Python é :mod:`tkinter`, baseado no " -"kit de ferramentas plataforma cruzada Tk (https://www.tcl.tk). Uma versão " -"nativa do Aqua do Tk é fornecida com o macOS da Apple, e a versão mais " -"recente pode ser baixada e instalada em https://www.activestate.com; também " -"pode ser construído a partir do código-fonte." +"*O PyObjC* é uma ligação em Python para o Objective-C/Cocoa da Apple " +"framework. Informações sobre o PyObjC estão disponíveis em :pypi:`pyobjc`." -#: ../../using/mac.rst:155 -msgid "A number of alternative macOS GUI toolkits are available:" +#: ../../using/mac.rst:236 +msgid "A number of alternative macOS GUI toolkits are available including:" msgstr "" -"Vários kits de ferramentas alternativos da GUI do macOS estão disponíveis:" +"Há vários kits de ferramentas GUI alternativas disponíveis para o macOS, " +"incluindo:" -#: ../../using/mac.rst:157 +#: ../../using/mac.rst:238 msgid "" -"`PySide `__: Official Python bindings to " -"the `Qt GUI toolkit `__." +"`PySide `_: Official Python bindings to the " +"`Qt GUI toolkit `_." msgstr "" -"`PySide `__: Ligações oficiais do Python ao " -"`Qt GUI toolkit `__." +"`PySide `_: Ligações oficiais em Python ao " +"kit de ferramentas `Qt GUI `_ ." -#: ../../using/mac.rst:160 +#: ../../using/mac.rst:241 msgid "" -"`PyQt `__: Alternative " -"Python bindings to Qt." +"`PyQt `_: Alternative Python " +"bindings to Qt." msgstr "" -"`PyQt `__: Ligações " -"alternativas do Python ao Qt." +"`PyQt `_: Ligações " +"alternativas em Python ao Qt." -#: ../../using/mac.rst:163 +#: ../../using/mac.rst:244 msgid "" -"`Kivy `__: A cross-platform GUI toolkit that supports " +"`Kivy `_: A cross-platform GUI toolkit that supports " "desktop and mobile platforms." msgstr "" -"`Kivy `__: Um kit de ferramentas GUI multiplataforma que " -"oferece suporte a plataformas desktop e móveis." +"`Kivy `_: Um kit de ferramentas GUI multiplataforma que dá " +"suporte a plataformas de desktop e dispositivos móveis." -#: ../../using/mac.rst:166 +#: ../../using/mac.rst:247 msgid "" -"`Toga `__: Part of the `BeeWare Project " -"`__; supports desktop, mobile, web and console apps." -msgstr "" -"`Toga `__: Parte do `Projeto BeeWare `__; oferece suporte a aplicativos de desktop, dispositivos " -"móveis, web e console." +"`Toga `_: Part of the `BeeWare Project `_; supports desktop, mobile, web and console apps." +msgstr "" +"`Toga `_: Parte do `BeeWare Project `_; dá suporte a aplicativos para desktop, dispositivos móveis, " +"Web e console." -#: ../../using/mac.rst:169 +#: ../../using/mac.rst:250 msgid "" -"`wxPython `__: A cross-platform toolkit that " -"supports desktop operating systems." +"`wxPython `_: A cross-platform toolkit that supports " +"desktop operating systems." msgstr "" -"`wxPython `__: Um kit de ferramentas " -"multiplataforma que oferece suporte a sistemas operacionais de desktop." +"`wxPython `_: Um kit de ferramentas multiplataforma " +"que dá suporte a sistemas operacionais desktop." -#: ../../using/mac.rst:175 +#: ../../using/mac.rst:255 +msgid "Advanced Topics" +msgstr "Tópicos Avançados" + +#: ../../using/mac.rst:260 +msgid "Installing Free-threaded Binaries" +msgstr "Instalando binários com threads livres" + +#: ../../using/mac.rst:262 +msgid "(Experimental)" +msgstr "(Experimental)" + +#: ../../using/mac.rst:266 +msgid "" +"Everything described in this section is considered experimental, and should " +"be expected to change in future releases." +msgstr "" +"Tudo descrito nesta seção é considerado experimental e espera-se que mude em " +"versões futuras." + +#: ../../using/mac.rst:269 +msgid "" +"The ``python.org`` :ref:`Python for macOS ` installer package can optionally install an additional build of " +"Python |usemac_x_dot_y| that supports :pep:`703`, the experimental free-" +"threading feature (running with the :term:`global interpreter lock` " +"disabled). Check the release page on ``python.org`` for possible updated " +"information." +msgstr "" +"O pacote de instalação do :ref:`Python para macOS ` em ``python.org`` pode, opcionalmente, instalar uma compilação " +"adicional do Python |usemac_x_dot_y| que dá suporte à :pep:`703`, o recurso " +"experimental de threads livres (executado com o :term:`trava global do " +"interpretador` desativado). Verifique a página de lançamento em ``python." +"org`` para obter informações atualizadas." + +#: ../../using/mac.rst:275 +msgid "" +"Because this feature is still considered experimental, the support for it is " +"not installed by default. It is packaged as a separate install option, " +"available by clicking the **Customize** button on the **Installation Type** " +"step of the installer as described above." +msgstr "" +"Como esse recurso ainda é considerado experimental, seu suporte não é " +"instalado por padrão. Ele é empacotado como uma opção de instalação " +"separada, disponível clicando no botão **Personalizar** na etapa **Tipo de " +"instalação** do instalador, como descrito acima." + +#: ../../using/mac.rst:282 +msgid "" +"If the box next to the **Free-threaded Python** package name is checked, a " +"separate :file:`PythonT.framework` will also be installed alongside the " +"normal :file:`Python.framework` in :file:`/Library/Frameworks`. This " +"configuration allows a free-threaded Python |usemac_x_dot_y| build to co-" +"exist on your system with a traditional (GIL only) Python |usemac_x_dot_y| " +"build with minimal risk while installing or testing. This installation " +"layout is itself experimental and is subject to change in future releases." +msgstr "" +"Se a caixa ao lado do nome **Free-Threaded Python** for marcada, um arquivo :" +"file:`PythonT.framework` também será instalado junto ao arquivo :file:" +"`Python.framework` em :file:`/Library/Frameworks`. Essa configuração permite " +"que a compilação de Python |usemac_x_dot_y| com threads livres coexista no " +"seu sistema com a compilação de Python |usemac_x_dot_y| tradicional (com " +"GIL) com risco mínimo durante instalação ou testagem. Esse layout de " +"instalação é experimental, e sujeito a mudanças em lançamentos futuros." + +#: ../../using/mac.rst:290 +msgid "Known cautions and limitations:" +msgstr "Precauções e limitações conhecidas:" + +#: ../../using/mac.rst:292 +msgid "" +"The **UNIX command-line tools** package, which is selected by default, will " +"install links in :file:`/usr/local/bin` for |" +"usemac_python_x_dot_y_t_literal|, the free-threaded interpreter, and |" +"usemac_python_x_dot_y_t_literal_config|, a configuration utility which may " +"be useful for package builders. Since :file:`/usr/local/bin` is typically " +"included in your shell ``PATH``, in most cases no changes to your ``PATH`` " +"environment variables should be needed to use |" +"usemac_python_x_dot_y_t_literal|." +msgstr "" +"O pacote **Unix command-line tools**, que é selecionado por padrão, " +"instalará links em :file:`/usr/local/bin` para |" +"usemac_python_x_dot_y_t_literal|, o interpretador com threads livres e |" +"usemac_python_x_dot_y_t_literal_config|, um utilitário de configuração que " +"pode ser útil para criadores de pacote. Como :file:`/usr/local/bin` é " +"normalmente incluído em seu ``PATH`` do console, geralmente não é necessário " +"alterar as variáveis de ambiente do ``PATH`` para usar o |" +"usemac_python_x_dot_y_t_literal|." + +#: ../../using/mac.rst:300 +msgid "" +"For this release, the **Shell profile updater** package and the :file:" +"`Update Shell Profile.command` in |usemac_applications_folder_version| do " +"not support the free-threaded package." +msgstr "" +"Neste lançamento, o pacote **Shell profile updater** e o comando :file:" +"`Update Shell Profile.command` em |usemac_applications_folder_version| não " +"dão suporte ao pacote de threads livres." + +#: ../../using/mac.rst:304 +msgid "" +"The free-threaded build and the traditional build have separate search paths " +"and separate :file:`site-packages` directories so, by default, if you need a " +"package available in both builds, it may need to be installed in both. The " +"free-threaded package will install a separate instance of :program:`pip` for " +"use with |usemac_python_x_dot_y_t_literal|." +msgstr "" +"A compilação com threads livres e a compilação tradicional têm caminhos de " +"pesquisa separados e diretórios :file:`site-packages` separados, portanto, " +"por padrão, se você precisar de um pacote disponível em ambas compilações, " +"talvez seja necessário instalá-lo em ambos. O pacote com threads livres " +"instalará uma instância separada do :program:`pip` para uso com o |" +"usemac_python_x_dot_y_t_literal|." + +#: ../../using/mac.rst:310 +msgid "To install a package using :command:`pip` without a :command:`venv`:" +msgstr "Para instalar um pacote usando :command:`pip` sem um :command:`venv`:" + +#: ../../using/mac.rst:312 +msgid "|usemac_python_x_dot_y_t_literal| ``-m pip install ``" +msgstr "|usemac_python_x_dot_y_t_literal| ``-m pip install ``" + +#: ../../using/mac.rst:314 +msgid "" +"When working with multiple Python environments, it is usually safest and " +"easiest to :ref:`create and use virtual environments `. This can " +"avoid possible command name conflicts and confusion about which Python is in " +"use:" +msgstr "" +"Ao trabalhar com vários ambientes Python, geralmente é mais seguro e mais " +"fácil :ref:`criar e usar ambientes virtuais `. Isso pode tanto " +"evitar possíveis conflitos de comandos, quanto evitar a confusão sobre qual " +"Python está sendo usado:" + +#: ../../using/mac.rst:318 +msgid "|usemac_python_x_dot_y_t_literal| ``-m venv ``" +msgstr "|usemac_python_x_dot_y_t_literal| ``-m venv ``" + +#: ../../using/mac.rst:320 +msgid "then :command:`activate`." +msgstr "e, em seguida, :command:`activate`." + +#: ../../using/mac.rst:322 +msgid "To run a free-threaded version of IDLE:" +msgstr "Para executar uma versão do IDLE com threads livres:" + +#: ../../using/mac.rst:324 +msgid "|usemac_python_x_dot_y_t_literal| ``-m idlelib``" +msgstr "|usemac_python_x_dot_y_t_literal| ``-m idlelib``" + +#: ../../using/mac.rst:326 +msgid "" +"The interpreters in both builds respond to the same :ref:`PYTHON environment " +"variables ` which may have unexpected results, for " +"example, if you have ``PYTHONPATH`` set in a shell profile. If necessary, " +"there are :ref:`command line options ` like ``-" +"E`` to ignore these environment variables." +msgstr "" +"Os intérpretes em ambos as compilações respondem às mesmas variáveis de " +"ambiente :ref:`PYTHON `, o que pode gerar resultados " +"inesperados, por exemplo, se você tiver ``PYTHONPATH`` definido em um perfil " +"de console. Se necessário, há :ref:`opções de linha de comando ` como ``-E`` para ignorar essas variáveis de ambiente." + +#: ../../using/mac.rst:333 +msgid "" +"The free-threaded build links to the third-party shared libraries, such as " +"``OpenSSL`` and ``Tk``, installed in the traditional framework. This means " +"that both builds also share one set of trust certificates as installed by " +"the :command:`Install Certificates.command` script, thus it only needs to be " +"run once." +msgstr "" +"A compilação com threads livres é ligada às bibliotecas compartilhadas de " +"terceiros, como ``OpenSSL`` e ``Tk``, instaladas no framework tradicional. " +"Isso significa que ambas as compilações também compartilham um conjunto de " +"certificados, como instalados pelo script :command:`Install Certificates." +"command`, portanto, ele só precisa ser executado uma vez." + +#: ../../using/mac.rst:339 +msgid "" +"If you cannot depend on the link in ``/usr/local/bin`` pointing to the " +"``python.org`` free-threaded |usemac_python_x_dot_y_t_literal| (for example, " +"if you want to install your own version there or some other distribution " +"does), you can explicitly set your shell ``PATH`` environment variable to " +"include the ``PythonT`` framework ``bin`` directory:" +msgstr "" +"Se você não puder depender do link em ``/usr/local/bin`` apontando para |" +"usemac_python_x_dot_y_t_literal| com threads livres do ``python.org`` (por " +"exemplo, se quiser instalar sua própria versão lá ou se alguma outra " +"distribuição instalá-lo lá), você poderá definir explicitamente sua variável " +"de ambiente de console ``PATH`` para incluir o diretório da framework " +"``PythonT`` ``bin``:" + +#: ../../using/mac.rst:345 +msgid "" +"export PATH=\"/Library/Frameworks/PythonT.framework/Versions/3.13/bin\":" +"\"$PATH\"" +msgstr "" +"export PATH=\"/Library/Frameworks/PythonT.framework/Versions/3.13/bin\":" +"\"$PATH\"" + +#: ../../using/mac.rst:349 +msgid "" +"The traditional framework installation by default does something similar, " +"except for :file:`Python.framework`. Be aware that having both framework " +"``bin`` directories in ``PATH`` can lead to confusion if there are duplicate " +"names like ``python3.13`` in both; which one is actually used depends on the " +"order they appear in ``PATH``. The ``which python3.x`` or ``which python3." +"xt`` commands can show which path is being used. Using virtual environments " +"can help avoid such ambiguities. Another option might be to create a shell :" +"command:`alias` to the desired interpreter, like:" +msgstr "" +"A instalação tradicional do framework por padrão faz algo semelhante, exceto " +"pelo arquivo :file:`Python.framework`. Observe que ter dois diretórios " +"``bin`` do framework em ``PATH`` pode gerar confusão se houver nomes " +"duplicados, como ``python3.13``, em ambos; qual deles é realmente usado " +"depende da ordem em que aparecem em ``PATH``. Os comandos ``which python3." +"x`` ou ``which python3.xt`` pode mostrar qual caminho está sendo usado. Usar " +"ambientes virtuais pode ajudar a evitar essas ambiguidades. Outra opção pode " +"ser criar um :command:`alias` no console para o interpretador desejado, como:" + +#: ../../using/mac.rst:358 +msgid "" +"alias py3.13=\"/Library/Frameworks/Python.framework/Versions/3.13/bin/" +"python3.13\"\n" +"alias py3.13t=\"/Library/Frameworks/PythonT.framework/Versions/3.13/bin/" +"python3.13t\"" +msgstr "" +"alias py3.13=\"/Library/Frameworks/Python.framework/Versions/3.13/bin/" +"python3.13\"\n" +"alias py3.13t=\"/Library/Frameworks/PythonT.framework/Versions/3.13/bin/" +"python3.13t\"" + +#: ../../using/mac.rst:364 +msgid "Installing using the command line" +msgstr "Instalação usando a linha de comando" + +#: ../../using/mac.rst:366 +msgid "" +"If you want to use automation to install the ``python.org`` installer " +"package (rather than by using the familiar macOS :program:`Installer` GUI " +"app), the macOS command line :command:`installer` utility lets you select " +"non-default options, too. If you are not familiar with :command:`installer`, " +"it can be somewhat cryptic (see :command:`man installer` for more " +"information). As an example, the following shell snippet shows one way to do " +"it, using the ``3.13.0b2`` release and selecting the free-threaded " +"interpreter option:" +msgstr "" +"Se você quiser usar automação para instalar o pacote de instalação ``python." +"org`` (em vez de usar o aplicativo GUI :program:`Installer` do macOS), o " +"utilitário para linha de comando :command:`installer` permite que você " +"selecione opções que não sejam do padrão. Se você não estiver familiarizado " +"com o :command:`installer`, ele pode ser um tanto enigmático (consulte: " +"command:`man installer` para obter mais informações). Como exemplo, o " +"seguinte trecho de console mostra uma maneira de fazer isso, usando a versão " +"``3.13.0b2`` e selecionando a opção de interpretador com threads livres:" + +#: ../../using/mac.rst:375 +msgid "" +"RELEASE=\"python-3.13.0b2-macos11.pkg\"\n" +"\n" +"# download installer pkg\n" +"curl -O https://www.python.org/ftp/python/3.13.0/${RELEASE}\n" +"\n" +"# create installer choicechanges to customize the install:\n" +"# enable the PythonTFramework-3.13 package\n" +"# while accepting the other defaults (install all other packages)\n" +"cat > ./choicechanges.plist <\n" +"\n" +"\n" +"\n" +" \n" +" attributeSetting\n" +" 1\n" +" choiceAttribute\n" +" selected\n" +" choiceIdentifier\n" +" org.python.Python.PythonTFramework-3.13\n" +" \n" +"\n" +"\n" +"EOF\n" +"\n" +"sudo installer -pkg ./${RELEASE} -applyChoiceChangesXML ./choicechanges." +"plist -target /" +msgstr "" +"RELEASE=\"python-3.13.0b2-macos11.pkg\"\n" +"\n" +"# baixa o pkg do instalador\n" +"curl -O https://www.python.org/ftp/python/3.13.0/${RELEASE}\n" +"\n" +"# cria o choicechanges do instalador para personalizar a instalação:\n" +"# habilita o pacote PythonTFramework-3.13\n" +"# enquanto aceita outros padrões (instala todos os outros apcotes)\n" +"cat > ./choicechanges.plist <\n" +"\n" +"\n" +"\n" +" \n" +" attributeSetting\n" +" 1\n" +" choiceAttribute\n" +" selected\n" +" choiceIdentifier\n" +" org.python.Python.PythonTFramework-3.13\n" +" \n" +"\n" +"\n" +"EOF\n" +"\n" +"sudo installer -pkg ./${RELEASE} -applyChoiceChangesXML ./choicechanges." +"plist -target /" + +#: ../../using/mac.rst:405 +msgid "" +"You can then test that both installer builds are now available with " +"something like:" +msgstr "" +"Você pode então testar que ambas as compilações de instaladores estão " +"disponíveis com algo como:" + +#: ../../using/mac.rst:407 +msgid "" +"$ # test that the free-threaded interpreter was installed if the Unix " +"Command Tools package was enabled\n" +"$ /usr/local/bin/python3.13t -VV\n" +"Python 3.13.0b2 experimental free-threading build (v3.13.0b2:3a83b172af, " +"Jun 5 2024, 12:57:31) [Clang 15.0.0 (clang-1500.3.9.4)]\n" +"$ # and the traditional interpreter\n" +"$ /usr/local/bin/python3.13 -VV\n" +"Python 3.13.0b2 (v3.13.0b2:3a83b172af, Jun 5 2024, 12:50:24) [Clang 15.0.0 " +"(clang-1500.3.9.4)]\n" +"$ # test that they are also available without the prefix if /usr/local/bin " +"is on $PATH\n" +"$ python3.13t -VV\n" +"Python 3.13.0b2 experimental free-threading build (v3.13.0b2:3a83b172af, " +"Jun 5 2024, 12:57:31) [Clang 15.0.0 (clang-1500.3.9.4)]\n" +"$ python3.13 -VV\n" +"Python 3.13.0b2 (v3.13.0b2:3a83b172af, Jun 5 2024, 12:50:24) [Clang 15.0.0 " +"(clang-1500.3.9.4)]" +msgstr "" +"$ # teste que o interpretador com threads livres foi instalado se o pacote " +"Unix Command Tools foi habilitado\n" +"$ /usr/local/bin/python3.13t -VV\n" +"Python 3.13.0b2 experimental free-threading build (v3.13.0b2:3a83b172af, " +"Jun 5 2024, 12:57:31) [Clang 15.0.0 (clang-1500.3.9.4)]\n" +"$ # e o interpretador tradicional\n" +"$ /usr/local/bin/python3.13 -VV\n" +"Python 3.13.0b2 (v3.13.0b2:3a83b172af, Jun 5 2024, 12:50:24) [Clang 15.0.0 " +"(clang-1500.3.9.4)]\n" +"$ # teste que também eles estão disponíveis sem o prefixo se /usr/local/bin " +"estiver no $PATH\n" +"$ python3.13t -VV\n" +"Python 3.13.0b2 experimental free-threading build (v3.13.0b2:3a83b172af, " +"Jun 5 2024, 12:57:31) [Clang 15.0.0 (clang-1500.3.9.4)]\n" +"$ python3.13 -VV\n" +"Python 3.13.0b2 (v3.13.0b2:3a83b172af, Jun 5 2024, 12:50:24) [Clang 15.0.0 " +"(clang-1500.3.9.4)]" + +#: ../../using/mac.rst:423 +msgid "" +"Current ``python.org`` installers only install to fixed locations like :file:" +"`/Library/Frameworks/`, :file:`/Applications`, and :file:`/usr/local/bin`. " +"You cannot use the :command:`installer` ``-domain`` option to install to " +"other locations." +msgstr "" +"Os instaladores atuais do ``python.org`` só instalam em locais fixos, como :" +"file:`/Library/Frameworks/`, :file:`/Applications` e :file:`/usr/local/bin`. " +"Não é possível usar a opção ``-domain`` do :command:`installer` para " +"instalar em outros locais." + +#: ../../using/mac.rst:431 msgid "Distributing Python Applications" msgstr "Distribuindo aplicações Python" -#: ../../using/mac.rst:177 +#: ../../using/mac.rst:433 msgid "" "A range of tools exist for converting your Python code into a standalone " "distributable application:" @@ -369,7 +901,7 @@ msgstr "" "Existe uma variedade de ferramentas para converter seu código Python em uma " "aplicação distribuível independente:" -#: ../../using/mac.rst:180 +#: ../../using/mac.rst:436 msgid "" ":pypi:`py2app`: Supports creating macOS ``.app`` bundles from a Python " "project." @@ -377,32 +909,32 @@ msgstr "" ":pypi:`py2app`: Oferece suporte à criação de pacotes ``.app`` do macOS a " "partir de um projeto Python." -#: ../../using/mac.rst:183 +#: ../../using/mac.rst:439 msgid "" -"`Briefcase `__: Part of the `BeeWare " -"Project `__; a cross-platform packaging tool that " +"`Briefcase `_: Part of the `BeeWare " +"Project `_; a cross-platform packaging tool that " "supports creation of ``.app`` bundles on macOS, as well as managing signing " "and notarization." msgstr "" -"`Briefcase `__: Parte do `Projeto BeeWare " -"`__; uma ferramenta de empacotamento multiplataforma " -"que suporta a criação de pacotes ``.app`` no macOS, bem como o gerenciamento " -"de assinatura e reconhecimento de firma." +"`Briefcase `_: Parte do `BeeWare Project " +"`_; uma ferramenta de empacotamento multiplataforma que " +"permite criar *bundles* ``.app`` no macOS, além de gerenciar assinaturas " +"digitais e a notarização." -#: ../../using/mac.rst:188 +#: ../../using/mac.rst:444 msgid "" -"`PyInstaller `__: A cross-platform packaging tool " +"`PyInstaller `_: A cross-platform packaging tool " "that creates a single file or folder as a distributable artifact." msgstr "" -"`PyInstaller `__: Uma ferramenta de empacotamento " +"`PyInstaller `_: Uma ferramenta de empacotamento " "multiplataforma que cria um único arquivo ou pasta como um artefato " "distribuível." -#: ../../using/mac.rst:192 +#: ../../using/mac.rst:448 msgid "App Store Compliance" msgstr "Conformidade com a App Store" -#: ../../using/mac.rst:194 +#: ../../using/mac.rst:450 msgid "" "Apps submitted for distribution through the macOS App Store must pass " "Apple's app review process. This process includes a set of automated " @@ -414,7 +946,7 @@ msgstr "" "conjunto de regras de validação automatizadas que inspecionam o pacote de " "aplicativos enviado em busca de código problemático." -#: ../../using/mac.rst:198 +#: ../../using/mac.rst:454 msgid "" "The Python standard library contains some code that is known to violate " "these automated rules. While these violations appear to be false positives, " @@ -427,7 +959,7 @@ msgstr "" "modificar a biblioteca padrão do Python para que uma aplicação passe na " "revisão da App Store." -#: ../../using/mac.rst:203 +#: ../../using/mac.rst:459 msgid "" "The Python source tree contains :source:`a patch file ` that will remove all code that is known to cause " @@ -441,7 +973,7 @@ msgstr "" "patch é aplicado automaticamente quando o CPython é configurado com a opção :" "option:`--with-app-store-compliance`." -#: ../../using/mac.rst:209 +#: ../../using/mac.rst:465 msgid "" "This patch is not normally required to use CPython on a Mac; nor is it " "required if you are distributing an app *outside* the macOS App Store. It is " @@ -453,26 +985,19 @@ msgstr "" "macOS. É necessário *apenas* se você estiver usando a App Store do macOS " "como canal de distribuição." -#: ../../using/mac.rst:214 +#: ../../using/mac.rst:470 msgid "Other Resources" msgstr "Outros recursos" -#: ../../using/mac.rst:216 +#: ../../using/mac.rst:472 msgid "" -"The Pythonmac-SIG mailing list is an excellent support resource for Python " -"users and developers on the Mac:" +"The `python.org Help page `_ has links " +"to many useful resources. The `Pythonmac-SIG mailing list `_ is another support " +"resource specifically for Python users and developers on the Mac." msgstr "" -"A lista de discussão do Pythonmac-SIG é um excelente recurso de suporte para " -"usuários e desenvolvedores de Python no Mac:" - -#: ../../using/mac.rst:219 -msgid "https://www.python.org/community/sigs/current/pythonmac-sig/" -msgstr "https://www.python.org/community/sigs/current/pythonmac-sig/" - -#: ../../using/mac.rst:221 -msgid "Another useful resource is the MacPython wiki:" -msgstr "Outro recurso útil é o wiki do MacPython:" - -#: ../../using/mac.rst:223 -msgid "https://wiki.python.org/moin/MacPython" -msgstr "https://wiki.python.org/moin/MacPython" +"A `página de ajuda do python.org `_ " +"contém links para vários recursos úteis. A `lista de discussão Pythonmac-SIG " +"`_ é outro " +"recurso específico de suporte para usuários e desenvolvedores de Python no " +"Mac." diff --git a/using/unix.po b/using/unix.po index fd76652e7..3555bf20a 100644 --- a/using/unix.po +++ b/using/unix.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Marco Rougeth , 2021 -# Welington Carlos , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-11 18:37+0000\n" -"PO-Revision-Date: 2021-06-28 01:51+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-03-21 14:18+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -44,24 +39,24 @@ msgstr "No Linux" msgid "" "Python comes preinstalled on most Linux distributions, and is available as a " "package on all others. However there are certain features you might want to " -"use that are not available on your distro's package. You can easily compile " -"the latest version of Python from source." +"use that are not available on your distro's package. You can compile the " +"latest version of Python from source." msgstr "" "O Python vem pré-instalado na maioria das distribuições Linux e está " -"disponível como um pacote em todos as outras. No entanto, existem certos " -"recursos que podemos querer utilizar e que não estão disponíveis no pacote " -"da sua distro. Poderás compilar facilmente a versão mais recente do Python " -"desde a origem." +"disponível como um pacote em todas as outras. No entanto, há certos recursos " +"que você pode querer usar que não estão disponíveis no pacote da sua " +"distribuição. Você pode compilar a versão mais recente do Python a partir do " +"código-fonte." #: ../../using/unix.rst:23 msgid "" -"In the event that Python doesn't come preinstalled and isn't in the " -"repositories as well, you can easily make packages for your own distro. " -"Have a look at the following links:" +"In the event that the latest version of Python doesn't come preinstalled and " +"isn't in the repositories as well, you can make packages for your own " +"distro. Have a look at the following links:" msgstr "" -"Nas situações em que o Python não vier pré-instalado e também não estiver " -"nos repositórios, poderás facilmente gerar os pacotes para a sua distro. " -"Veja os seguintes links:" +"No caso de a versão mais recente do Python não vir pré-instalada e não estar " +"nos repositórios também, você pode criar pacotes para sua própria distro. Dê " +"uma olhada nos seguintes links:" #: ../../using/unix.rst:29 msgid "https://www.debian.org/doc/manuals/maint-guide/first.en.html" @@ -99,29 +94,98 @@ msgstr "https://slackbook.org/html/package-management-making-packages.html" msgid "for Slackware users" msgstr "para usuários do Slackware" -#: ../../using/unix.rst:40 +#: ../../using/unix.rst:41 +msgid "Installing IDLE" +msgstr "Instalação do IDLE" + +#: ../../using/unix.rst:43 +msgid "In some cases, IDLE might not be included in your Python installation." +msgstr "" +"Em alguns casos, o IDLE pode não estar incluído em sua instalação do Python." + +#: ../../using/unix.rst:45 +msgid "For Debian and Ubuntu users::" +msgstr "Para usuários do Debian e do Ubuntu::" + +#: ../../using/unix.rst:47 +msgid "" +"sudo apt update\n" +"sudo apt install idle" +msgstr "" +"sudo apt update\n" +"sudo apt install idle" + +#: ../../using/unix.rst:50 +msgid "For Fedora, RHEL, and CentOS users::" +msgstr "Para usuários do Fedora, RHEL e CentOS::" + +#: ../../using/unix.rst:52 +msgid "sudo dnf install python3-idle" +msgstr "sudo dnf install python3-idle" + +#: ../../using/unix.rst:54 +msgid "For SUSE and OpenSUSE users::" +msgstr "Para usuários do SUSE e do OpenSUSE::" + +#: ../../using/unix.rst:56 +msgid "sudo zypper install python3-idle" +msgstr "sudo zypper install python3-idle" + +#: ../../using/unix.rst:58 +msgid "For Alpine Linux users::" +msgstr "Para usuários do Alpine Linux::" + +#: ../../using/unix.rst:60 +msgid "sudo apk add python3-idle" +msgstr "sudo apk add python3-idle" + +#: ../../using/unix.rst:65 msgid "On FreeBSD and OpenBSD" msgstr "No FreeBSD e OpenBSD" -#: ../../using/unix.rst:42 +#: ../../using/unix.rst:67 msgid "FreeBSD users, to add the package use::" msgstr "usuários do FreeBSD, para adicionar a utilização do pacote utilize::" -#: ../../using/unix.rst:46 +#: ../../using/unix.rst:69 +msgid "pkg install python3" +msgstr "pkg install python3" + +#: ../../using/unix.rst:71 msgid "OpenBSD users, to add the package use::" msgstr "Usuários do OpenBSD, para adicionar pacotes use::" -#: ../../using/unix.rst:52 +#: ../../using/unix.rst:73 +msgid "" +"pkg_add -r python\n" +"\n" +"pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages//python-.tgz" +msgstr "" +"pkg_add -r python\n" +"\n" +"pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages//python-.tgz" + +#: ../../using/unix.rst:77 msgid "For example i386 users get the 2.5.1 version of Python using::" msgstr "" "Por exemplo, usuários i386 podem pegar a versão 2.5.1 do Python usando o " "comando::" -#: ../../using/unix.rst:60 +#: ../../using/unix.rst:79 +msgid "" +"pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2." +"tgz" +msgstr "" +"pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2." +"tgz" + +#: ../../using/unix.rst:85 msgid "Building Python" msgstr "Compilando o Python" -#: ../../using/unix.rst:62 +#: ../../using/unix.rst:87 msgid "" "If you want to compile CPython yourself, first thing you should do is get " "the `source `_. You can download " @@ -135,11 +199,21 @@ msgstr "" "devguide.python.org/setup/#get-the-source-code>`_. (Se você pretende " "contribuir modificações, você vai precisar um \"clone\".)" -#: ../../using/unix.rst:68 +#: ../../using/unix.rst:93 msgid "The build process consists of the usual commands::" msgstr "O processo de compilação consiste nos comandos usuais::" -#: ../../using/unix.rst:74 +#: ../../using/unix.rst:95 +msgid "" +"./configure\n" +"make\n" +"make install" +msgstr "" +"./configure\n" +"make\n" +"make install" + +#: ../../using/unix.rst:99 msgid "" ":ref:`Configuration options ` and caveats for specific " "Unix platforms are extensively documented in the :source:`README.rst` file " @@ -149,7 +223,7 @@ msgstr "" "plataformas específicas do Unix estão amplamente documentadas no arquivo :" "source:`README.rst` na raiz da árvore de fontes Python." -#: ../../using/unix.rst:80 +#: ../../using/unix.rst:105 msgid "" "``make install`` can overwrite or masquerade the :file:`python3` binary. " "``make altinstall`` is therefore recommended instead of ``make install`` " @@ -160,11 +234,11 @@ msgstr "" "install`` uma vez que o mesmo apenas instala o arquivo :file:`{exec_prefix}/" "bin/python{version}`." -#: ../../using/unix.rst:86 +#: ../../using/unix.rst:111 msgid "Python-related paths and files" msgstr "Paths e arquivos relacionados com o Python" -#: ../../using/unix.rst:88 +#: ../../using/unix.rst:113 msgid "" "These are subject to difference depending on local installation " "conventions; :option:`prefix <--prefix>` and :option:`exec_prefix <--exec-" @@ -176,30 +250,30 @@ msgstr "" "dependem da instalação e devem ser interpretados da mesma forma que para o " "software GNU; eles poderão ser os mesmos." -#: ../../using/unix.rst:93 +#: ../../using/unix.rst:118 msgid "" "For example, on most Linux systems, the default for both is :file:`/usr`." msgstr "" "Por exemplo, na maioria dos sistemas Linux, o padrão para ambos é :file:`/" "usr`." -#: ../../using/unix.rst:96 +#: ../../using/unix.rst:121 msgid "File/directory" msgstr "Arquivo/diretório" -#: ../../using/unix.rst:96 +#: ../../using/unix.rst:121 msgid "Meaning" msgstr "Significado" -#: ../../using/unix.rst:98 +#: ../../using/unix.rst:123 msgid ":file:`{exec_prefix}/bin/python3`" msgstr ":file:`{exec_prefix}/bin/python3`" -#: ../../using/unix.rst:98 +#: ../../using/unix.rst:123 msgid "Recommended location of the interpreter." msgstr "Localização recomendada do interpretador." -#: ../../using/unix.rst:100 +#: ../../using/unix.rst:125 msgid "" ":file:`{prefix}/lib/python{version}`, :file:`{exec_prefix}/lib/" "python{version}`" @@ -207,12 +281,12 @@ msgstr "" ":file:`{prefix}/lib/python{version}`, :file:`{exec_prefix}/lib/" "python{version}`" -#: ../../using/unix.rst:100 +#: ../../using/unix.rst:125 msgid "" "Recommended locations of the directories containing the standard modules." msgstr "A localização recomendada dos diretórios contendo os módulos padrão." -#: ../../using/unix.rst:103 +#: ../../using/unix.rst:128 msgid "" ":file:`{prefix}/include/python{version}`, :file:`{exec_prefix}/include/" "python{version}`" @@ -220,7 +294,7 @@ msgstr "" ":file:`{prefix}/include/python{version}`, :file:`{exec_prefix}/include/" "python{version}`" -#: ../../using/unix.rst:103 +#: ../../using/unix.rst:128 msgid "" "Recommended locations of the directories containing the include files needed " "for developing Python extensions and embedding the interpreter." @@ -229,11 +303,11 @@ msgstr "" "necessários para o desenvolvimento de extensões Python e incorporação do " "interpretador." -#: ../../using/unix.rst:111 +#: ../../using/unix.rst:136 msgid "Miscellaneous" msgstr "Diversos" -#: ../../using/unix.rst:113 +#: ../../using/unix.rst:138 msgid "" "To easily use Python scripts on Unix, you need to make them executable, e.g. " "with" @@ -241,7 +315,11 @@ msgstr "" "Para usar facilmente scripts Python no Unix, você precisa torná-los " "executáveis, por exemplo, com" -#: ../../using/unix.rst:120 +#: ../../using/unix.rst:141 +msgid "$ chmod +x script" +msgstr "$ chmod +x script" + +#: ../../using/unix.rst:145 msgid "" "and put an appropriate Shebang line at the top of the script. A good choice " "is usually ::" @@ -249,7 +327,11 @@ msgstr "" "e colocar uma linha Shebang apropriada no topo do script. Uma boa escolha " "normalmente é ::" -#: ../../using/unix.rst:125 +#: ../../using/unix.rst:148 +msgid "#!/usr/bin/env python3" +msgstr "#!/usr/bin/env python3" + +#: ../../using/unix.rst:150 msgid "" "which searches for the Python interpreter in the whole :envvar:`PATH`. " "However, some Unices may not have the :program:`env` command, so you may " @@ -260,7 +342,7 @@ msgstr "" "você pode precisar codificar ``/usr/bin/python3`` como o caminho do " "interpretador." -#: ../../using/unix.rst:129 +#: ../../using/unix.rst:154 msgid "" "To use shell commands in your Python scripts, look at the :mod:`subprocess` " "module." @@ -268,11 +350,11 @@ msgstr "" "Para usar comandos Shell em seus scripts Python, veja o módulo :mod:" "`subprocess`." -#: ../../using/unix.rst:134 +#: ../../using/unix.rst:159 msgid "Custom OpenSSL" msgstr "OpenSSL personalizado" -#: ../../using/unix.rst:136 +#: ../../using/unix.rst:161 msgid "" "To use your vendor's OpenSSL configuration and system trust store, locate " "the directory with ``openssl.cnf`` file or symlink in ``/etc``. On most " @@ -286,7 +368,15 @@ msgstr "" "ssl`` ou em ``/etc/pki/tls``. O diretório também deve conter um arquivo " "``cert.pem`` e/ou um diretório ``certs``." -#: ../../using/unix.rst:147 +#: ../../using/unix.rst:167 +msgid "" +"$ find /etc/ -name openssl.cnf -printf \"%h\\n\"\n" +"/etc/ssl" +msgstr "" +"$ find /etc/ -name openssl.cnf -printf \"%h\\n\"\n" +"/etc/ssl" + +#: ../../using/unix.rst:172 msgid "" "Download, build, and install OpenSSL. Make sure you use ``install_sw`` and " "not ``install``. The ``install_sw`` target does not override ``openssl.cnf``." @@ -294,15 +384,59 @@ msgstr "" "Baixe, construa e instale o OpenSSL. Certifique-se de usar ``install_sw`` e " "não ``install``. O destino ``install_sw`` não substitui o ``openssl.cnf``." -#: ../../using/unix.rst:165 +#: ../../using/unix.rst:176 +msgid "" +"$ curl -O https://www.openssl.org/source/openssl-VERSION.tar.gz\n" +"$ tar xzf openssl-VERSION\n" +"$ pushd openssl-VERSION\n" +"$ ./config \\\n" +" --prefix=/usr/local/custom-openssl \\\n" +" --libdir=lib \\\n" +" --openssldir=/etc/ssl\n" +"$ make -j1 depend\n" +"$ make -j8\n" +"$ make install_sw\n" +"$ popd" +msgstr "" +"$ curl -O https://www.openssl.org/source/openssl-VERSÃO.tar.gz\n" +"$ tar xzf openssl-VERSÃO\n" +"$ pushd openssl-VERSÃO\n" +"$ ./config \\\n" +" --prefix=/usr/local/custom-openssl \\\n" +" --libdir=lib \\\n" +" --openssldir=/etc/ssl\n" +"$ make -j1 depend\n" +"$ make -j8\n" +"$ make install_sw\n" +"$ popd" + +#: ../../using/unix.rst:190 msgid "" "Build Python with custom OpenSSL (see the configure ``--with-openssl`` and " "``--with-openssl-rpath`` options)" msgstr "" -"Construa Python com o OpenSSL personalizado (veja as opções configure ``--" +"Construa o Python com o OpenSSL personalizado (veja as opções configure ``--" "with-openssl`` e ``--with-openssl-rpath``)" -#: ../../using/unix.rst:180 +#: ../../using/unix.rst:193 +msgid "" +"$ pushd python-3.x.x\n" +"$ ./configure -C \\\n" +" --with-openssl=/usr/local/custom-openssl \\\n" +" --with-openssl-rpath=auto \\\n" +" --prefix=/usr/local/python-3.x.x\n" +"$ make -j8\n" +"$ make altinstall" +msgstr "" +"$ pushd python-3.x.x\n" +"$ ./configure -C \\\n" +" --with-openssl=/usr/local/custom-openssl \\\n" +" --with-openssl-rpath=auto \\\n" +" --prefix=/usr/local/python-3.x.x\n" +"$ make -j8\n" +"$ make altinstall" + +#: ../../using/unix.rst:205 msgid "" "Patch releases of OpenSSL have a backwards compatible ABI. You don't need to " "recompile Python to update OpenSSL. It's sufficient to replace the custom " diff --git a/using/windows.po b/using/windows.po index eb0e0ac2f..968cb8fc3 100644 --- a/using/windows.po +++ b/using/windows.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Danilo Lima , 2021 -# Raphael Mendonça, 2021 -# Marco Rougeth , 2021 -# felipe caridade fernandes , 2021 -# Julia Rizza , 2021 -# Claudio Rogerio Carvalho Filho , 2022 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-07-05 14:16+0000\n" -"PO-Revision-Date: 2021-06-28 01:51+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -674,6 +668,10 @@ msgstr "" "em todo o sistema, você pode usar o seguinte comando (a partir de um " "terminal de comando autorizado)::" +#: ../../using/windows.rst:239 +msgid "python-3.9.0.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0" +msgstr "python-3.9.0.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0" + #: ../../using/windows.rst:241 msgid "" "To allow users to easily install a personal copy of Python without the test " @@ -684,6 +682,14 @@ msgstr "" "suíte de testes, você pode fornecer um atalho com o seguinte comando. Isso " "irá exibir uma página inicial simplificado e bloquear a personalização::" +#: ../../using/windows.rst:245 +msgid "" +"python-3.9.0.exe InstallAllUsers=0 Include_launcher=0 Include_test=0\n" +" SimpleInstall=1 SimpleInstallDescription=\"Just for me, no test suite.\"" +msgstr "" +"python-3.9.0.exe InstallAllUsers=0 Include_launcher=0 Include_test=0\n" +" SimpleInstall=1 SimpleInstallDescription=\"Just for me, no test suite.\"" + #: ../../using/windows.rst:248 msgid "" "(Note that omitting the launcher also omits file associations, and is only " @@ -709,6 +715,26 @@ msgstr "" "elementos de texto são sempre deixados como strings. Esse arquivo de exemplo " "define as mesmas opções que o exemplo anterior:" +#: ../../using/windows.rst:258 +msgid "" +"\n" +" " +msgstr "" +"\n" +" " + #: ../../using/windows.rst:271 msgid "Installing Without Downloading" msgstr "Instalando Sem Download" @@ -744,6 +770,10 @@ msgstr "" "nos respectivos diretórios para evitar colisão entre arquivos com o mesmo " "nome." +#: ../../using/windows.rst:288 +msgid "python-3.9.0.exe /layout [optional target directory]" +msgstr "python-3.9.0.exe /layout [diretório alvo opcional]" + #: ../../using/windows.rst:290 msgid "" "You may also specify the ``/quiet`` option to hide the progress display." @@ -832,6 +862,11 @@ msgid "" "full ABI suffix. Python source files and bundled third-party dependencies " "are shared with the main install." msgstr "" +"Selecionar esta opção fará o download e instalará binários adicionais no " +"mesmo local da instalação principal do Python. O executável principal é " +"chamado ``python3.13t.exe``, e outros binários recebem um sufixo ``t`` ou um " +"sufixo ABI completo. Arquivos de origem do Python e dependências de " +"terceiros empacotadas são compartilhadas com a instalação principal." #: ../../using/windows.rst:334 msgid "" @@ -1041,6 +1076,22 @@ msgstr "" "Você pode encontrar o caminho real de qualquer arquivo existente usando :" "func:`os.path.realpath`:" +#: ../../using/windows.rst:420 +msgid "" +">>> import os\n" +">>> test_file = 'C:\\\\Users\\\\example\\\\AppData\\\\Local\\\\test.txt'\n" +">>> os.path.realpath(test_file)\n" +"'C:\\\\Users\\\\example\\\\AppData\\\\Local\\\\Packages\\" +"\\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\\\\LocalCache\\\\Local\\" +"\\test.txt'" +msgstr "" +">>> import os\n" +">>> test_file = 'C:\\\\Users\\\\exemplo\\\\AppData\\\\Local\\\\test.txt'\n" +">>> os.path.realpath(test_file)\n" +"'C:\\\\Users\\\\exemplo\\\\AppData\\\\Local\\\\Packages\\" +"\\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\\\\LocalCache\\\\Local\\" +"\\test.txt'" + #: ../../using/windows.rst:427 msgid "When writing to the Windows Registry, the following behaviors exist:" msgstr "Ao gravar no Registro do Windows, existem os seguintes comportamentos:" @@ -1076,14 +1127,14 @@ msgid "" "For more detail on the technical basis for these limitations, please consult " "Microsoft's documentation on packaged full-trust apps, currently available " "at `docs.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-behind-the-" -"scenes `_" msgstr "" "Para obter mais detalhes sobre a base técnica dessas limitações, consulte a " "documentação da Microsoft sobre aplicativos de confiança total empacotados, " "atualmente disponíveis em `docs.microsoft.com/pt-br/windows/msix/desktop/" -"desktop-to-uwp-behind-the-scenes `_" +"desktop-to-uwp-behind-the-scenes `_" #: ../../using/windows.rst:443 msgid "The nuget.org packages" @@ -1124,6 +1175,14 @@ msgstr "" "Com a ferramenta, a versão mais recente do Python para máquinas 64-bit ou 32-" "bit é instalada usando::" +#: ../../using/windows.rst:461 +msgid "" +"nuget.exe install python -ExcludeVersion -OutputDirectory .\n" +"nuget.exe install pythonx86 -ExcludeVersion -OutputDirectory ." +msgstr "" +"nuget.exe install python -ExcludeVersion -OutputDirectory .\n" +"nuget.exe install pythonx86 -ExcludeVersion -OutputDirectory ." + #: ../../using/windows.rst:464 msgid "" "To select a particular version, add a ``-Version 3.x.y``. The output " @@ -1140,6 +1199,24 @@ msgstr "" "instalada. Dentro do subdiretório está um diretório ``tools`` que contém a " "instalação do Python:" +#: ../../using/windows.rst:471 +msgid "" +"# Without -ExcludeVersion\n" +"> .\\python.3.5.2\\tools\\python.exe -V\n" +"Python 3.5.2\n" +"\n" +"# With -ExcludeVersion\n" +"> .\\python\\tools\\python.exe -V\n" +"Python 3.5.2" +msgstr "" +"# Sem -ExcludeVersion\n" +"> .\\python.3.5.2\\tools\\python.exe -V\n" +"Python 3.5.2\n" +"\n" +"# Com -ExcludeVersion\n" +"> .\\python\\tools\\python.exe -V\n" +"Python 3.5.2" + #: ../../using/windows.rst:481 msgid "" "In general, nuget packages are not upgradeable, and newer versions should be " @@ -1174,6 +1251,11 @@ msgid "" "pythonx86>`_ for the 32-bit version, and `www.nuget.org/packages/pythonarm64 " "`_ for the ARM64 version" msgstr "" +"As páginas de informação dos pacotes em nuget.org são `www.nuget.org/" +"packages/python `_ para a versão 64 " +"bits, `www.nuget.org/packages/pythonx86 `_ para a versão 32 bits e `www.nuget.org/packages/pythonarm64 " +"`_ para a versão ARM64" #: ../../using/windows.rst:499 msgid "Free-threaded packages" @@ -1233,14 +1315,14 @@ msgstr "" #: ../../using/windows.rst:537 msgid "" "The embedded distribution does not include the `Microsoft C Runtime `_ and it is the responsibility of the " "application installer to provide this. The runtime may have already been " "installed on a user's system previously or automatically via Windows Update, " "and can be detected by finding ``ucrtbase.dll`` in the system directory." msgstr "" -"A distribuição embutida não inclui o `Microsoft C Runtime `_ e é de responsabilidade do instalador da " "aplicação providenciar isso. O aplicativo de tempo de execução pode já ter " "sido instalado no sistema de um usuário previamente ou automaticamente via " @@ -1407,8 +1489,10 @@ msgstr "" "de pacotes ``conda``." #: ../../using/windows.rst:611 -msgid "`Enthought Deployment Manager `_" -msgstr "`Enthought Deployment Manager `_" +msgid "" +"`Enthought Deployment Manager `_" +msgstr "" +"`Enthought Deployment Manager `_" #: ../../using/windows.rst:612 msgid "\"The Next Generation Python Environment and Package Manager\"." @@ -1487,6 +1571,16 @@ msgstr "" "Para definir as variáveis de ambiente temporariamente, abra um Prompt de " "Comando e use o comando :command:`set`:" +#: ../../using/windows.rst:647 +msgid "" +"C:\\>set PATH=C:\\Program Files\\Python 3.9;%PATH%\n" +"C:\\>set PYTHONPATH=%PYTHONPATH%;C:\\My_python_lib\n" +"C:\\>python" +msgstr "" +"C:\\>set PATH=C:\\Program Files\\Python 3.9;%PATH%\n" +"C:\\>set PYTHONPATH=%PYTHONPATH%;C:\\My_python_lib\n" +"C:\\>python" + #: ../../using/windows.rst:653 msgid "" "These changes will apply to any further commands executed in that console, " @@ -1549,11 +1643,9 @@ msgstr "" #: ../../using/windows.rst:681 msgid "" -"https://docs.microsoft.com/en-us/windows/win32/procthread/environment-" -"variables" +"https://learn.microsoft.com/windows/win32/procthread/environment-variables" msgstr "" -"https://docs.microsoft.com/en-us/windows/win32/procthread/environment-" -"variables" +"https://learn.microsoft.com/windows/win32/procthread/environment-variables" #: ../../using/windows.rst:682 msgid "Overview of environment variables on Windows" @@ -1561,11 +1653,11 @@ msgstr "Visão geral das variáveis de ambiente no Windows" #: ../../using/windows.rst:684 msgid "" -"https://docs.microsoft.com/en-us/windows-server/administration/windows-" -"commands/set_1" +"https://learn.microsoft.com/windows-server/administration/windows-commands/" +"set_1" msgstr "" -"https://docs.microsoft.com/en-us/windows-server/administration/windows-" -"commands/set_1" +"https://learn.microsoft.com/windows-server/administration/windows-commands/" +"set_1" #: ../../using/windows.rst:685 msgid "The ``set`` command, for temporarily modifying environment variables" @@ -1574,11 +1666,11 @@ msgstr "" #: ../../using/windows.rst:687 msgid "" -"https://docs.microsoft.com/en-us/windows-server/administration/windows-" -"commands/setx" +"https://learn.microsoft.com/windows-server/administration/windows-commands/" +"setx" msgstr "" -"https://docs.microsoft.com/en-us/windows-server/administration/windows-" -"commands/setx" +"https://learn.microsoft.com/windows-server/administration/windows-commands/" +"setx" #: ../../using/windows.rst:688 msgid "The ``setx`` command, for permanently modifying environment variables" @@ -1636,6 +1728,10 @@ msgstr "" "variável exemplo pode parecer com isso (presumindo que as duas primeiras " "entradas já existem)::" +#: ../../using/windows.rst:717 +msgid "C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\Program Files\\Python 3.9" +msgstr "C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\Program Files\\Python 3.9" + #: ../../using/windows.rst:722 msgid "UTF-8 mode" msgstr "Modo UTF-8" @@ -1771,6 +1867,10 @@ msgstr "" "instalada. Para verificar se o inicializador está disponível, execute o " "seguinte comando no Prompt de Comando::" +#: ../../using/windows.rst:789 +msgid "py" +msgstr "py" + #: ../../using/windows.rst:791 msgid "" "You should find that the latest version of Python you have installed is " @@ -1791,6 +1891,10 @@ msgstr "" "version|) você deve ter notado que o Python |version| foi iniciado -- para " "iniciar o Python 3.7, use o comando::" +#: ../../using/windows.rst:799 +msgid "py -3.7" +msgstr "py -3.7" + #: ../../using/windows.rst:801 msgid "" "If you want the latest version of Python 2 you have installed, try the " @@ -1799,15 +1903,31 @@ msgstr "" "Se você quer a versão mais recente do Python 2 que você tem instalada, tente " "o comando::" +#: ../../using/windows.rst:804 +msgid "py -2" +msgstr "py -2" + #: ../../using/windows.rst:806 msgid "" "If you see the following error, you do not have the launcher installed::" msgstr "Se você ver o seguinte erro, você não tem o inicializador instalado::" +#: ../../using/windows.rst:808 +msgid "" +"'py' is not recognized as an internal or external command,\n" +"operable program or batch file." +msgstr "" +"'py' is not recognized as an internal or external command,\n" +"operable program or batch file." + #: ../../using/windows.rst:811 msgid "The command::" msgstr "O comando::" +#: ../../using/windows.rst:813 +msgid "py --list" +msgstr "py --list" + #: ../../using/windows.rst:815 msgid "displays the currently installed version(s) of Python." msgstr "exibe a(s) versão(ões) atualmente instalada(s) do Python." @@ -1838,6 +1958,26 @@ msgstr "" "selecionará de todos os provedores. Observe que omitir a barra implica uma " "tag::" +#: ../../using/windows.rst:827 +msgid "" +"# Select any '3.*' tagged runtime\n" +"py -V:3\n" +"\n" +"# Select any 'PythonCore' released runtime\n" +"py -V:PythonCore/\n" +"\n" +"# Select PythonCore's latest Python 3 runtime\n" +"py -V:PythonCore/3" +msgstr "" +"# Seleciona qualquer runtime sinalizado como '3.*'\n" +"py -V:3\n" +"\n" +"# Seleciona qualquer runtime lançado como 'PythonCore'\n" +"py -V:PythonCore/\n" +"\n" +"# Seleciona o runtime Python 3 mais recente de PythonCore\n" +"py -V:PythonCore/3" + #: ../../using/windows.rst:836 msgid "" "The short form of the argument (``-3``) only ever selects from core Python " @@ -1850,8 +1990,8 @@ msgstr "" #: ../../using/windows.rst:840 msgid "" -"The Company is matched on the full string, case-insenitive. The Tag is " -"matched oneither the full string, or a prefix, provided the next character " +"The Company is matched on the full string, case-insensitive. The Tag is " +"matched on either the full string, or a prefix, provided the next character " "is a dot or a hyphen. This allows ``-V:3.1`` to match ``3.1-32``, but not " "``3.10``. Tags are sorted using numerical ordering (``3.10`` is newer than " "``3.1``), but are compared using text (``-V:3.01`` does not match ``3.1``)." @@ -1896,10 +2036,24 @@ msgstr "" "Vamos criar um script teste de Python - crie um arquivo chamado ``hello.py`` " "com os seguintes conteúdos:" +#: ../../using/windows.rst:865 +msgid "" +"#! python\n" +"import sys\n" +"sys.stdout.write(\"hello from Python %s\\n\" % (sys.version,))" +msgstr "" +"#! python\n" +"import sys\n" +"sys.stdout.write(\"olá do Python %s\\n\" % (sys.version,))" + #: ../../using/windows.rst:871 msgid "From the directory in which hello.py lives, execute the command::" msgstr "A partir do diretório onde hello.py está, execute o comando::" +#: ../../using/windows.rst:873 +msgid "py hello.py" +msgstr "py hello.py" + #: ../../using/windows.rst:875 msgid "" "You should notice the version number of your latest Python 2.x installation " @@ -1908,6 +2062,10 @@ msgstr "" "Você deve notar que o número da versão da sua instalação mais recente do " "Python 2.x é exibido. Agora tente mudar a primeira linha para ser:" +#: ../../using/windows.rst:878 +msgid "#! python3" +msgstr "#! python3" + #: ../../using/windows.rst:882 msgid "" "Re-executing the command should now print the latest Python 3.x information. " @@ -2012,6 +2170,10 @@ msgstr "``python``" msgid "For example, if the first line of your script starts with" msgstr "Por exemplo, se a primeira linha do seu script começa com" +#: ../../using/windows.rst:926 +msgid "#! /usr/bin/python" +msgstr "#! /usr/bin/python" + #: ../../using/windows.rst:930 msgid "" "The default Python or an active virtual environment will be located and " @@ -2021,6 +2183,12 @@ msgid "" "be useful on Unix, you should use one of the shebang lines starting with ``/" "usr``." msgstr "" +"O Python padrão ou um ambiente virtual ativo será localizado e utilizado. " +"Como muitos scripts Python escritos para funcionar no Unix já terão essa " +"linha, você deve perceber que esses scripts podem ser usados pelo " +"inicializador sem modificação. Se você está escrevendo um novo script no " +"Windows que você espera que seja útil no Unix, você deve usar uma dessas " +"linhas shebang começando com ``/usr``." #: ../../using/windows.rst:936 msgid "" @@ -2031,6 +2199,12 @@ msgid "" "Python 3.7. If a virtual environment is active, the version will be ignored " "and the environment will be used." msgstr "" +"Qualquer um dos comandos virtuais acima pode ser sufixado com uma versão " +"explícita (ou apenas a maior versão, ou a maior e a menor versão). Além " +"disso, a versão de 32 bits pode ser solicitada adicionando \"-32\" após a " +"menor versão. Isto é, ``/usr/bin/python3.7-32`` irá solicitar o uso do " +"python 3.7 32-bit. Se um ambiente virtual estiver ativo, a versão será " +"ignorada e o ambiente será usado." #: ../../using/windows.rst:945 msgid "" @@ -2048,6 +2222,9 @@ msgid "" "not provably i386/32-bit\". To request a specific environment, use the new :" "samp:`-V:{TAG}` argument with the complete tag." msgstr "" +"O sufixo \"-64\" foi descontinuado e agora implica \"qualquer arquitetura " +"que não seja comprovadamente i386/32 bits\". Para solicitar um ambiente " +"específico, use o novo argumento :samp:`-V:{TAG}` com a tag completa." #: ../../using/windows.rst:957 msgid "" @@ -2056,6 +2233,10 @@ msgid "" "the shebang specifies ``/usr/bin/env python3`` but :file:`python3.exe` is " "not present in the active environment." msgstr "" +"Comandos virtuais que referenciam ``python`` agora preferem um ambiente " +"virtual ativo em vez de pesquisar :envvar:`PATH`. Isso lida com casos em que " +"o shebang especifica ``/usr/bin/env python3``, mas :file:`python3.exe` não " +"está presente no ambiente ativo." #: ../../using/windows.rst:962 msgid "" @@ -2099,6 +2280,14 @@ msgstr "" "caminho completo para o executável (argumentos adicionais especificados no ." "INI serão citados como parte do nome do arquivo)." +#: ../../using/windows.rst:981 +msgid "" +"[commands]\n" +"/bin/xpython=C:\\Program Files\\XPython\\python.exe" +msgstr "" +"[commands]\n" +"/bin/xpython=C:\\Program Files\\XPython\\python.exe" + #: ../../using/windows.rst:986 msgid "" "Any commands not found in the .INI file are treated as **Windows** " @@ -2129,6 +2318,10 @@ msgstr "" "As linhas shebang também podem especificar opções adicionais a serem " "passadas ao interpretador Python. Por exemplo, se você tem uma linha shebang:" +#: ../../using/windows.rst:1000 +msgid "#! /usr/bin/python -v" +msgstr "#! /usr/bin/python -v" + #: ../../using/windows.rst:1004 msgid "Then Python will be started with the ``-v`` option" msgstr "O Python será iniciado com a opção ``-v``" @@ -2330,6 +2523,14 @@ msgstr "Por exemplo:" msgid "Setting ``PY_PYTHON=3.7`` is equivalent to the INI file containing:" msgstr "Configurar ``PY_PYTHON=3.7`` é o equivalente ao arquivo INI contendo:" +#: ../../using/windows.rst:1093 +msgid "" +"[defaults]\n" +"python=3.7" +msgstr "" +"[defaults]\n" +"python=3.7" + #: ../../using/windows.rst:1098 msgid "" "Setting ``PY_PYTHON=3`` and ``PY_PYTHON3=3.7`` is equivalent to the INI file " @@ -2338,6 +2539,16 @@ msgstr "" "Configurar ``PY_PYTHON=3`` e ``PY_PYTHON3=3.7`` é o equivalente ao arquivo " "INI contendo:" +#: ../../using/windows.rst:1101 +msgid "" +"[defaults]\n" +"python=3\n" +"python3=3.7" +msgstr "" +"[defaults]\n" +"python=3\n" +"python3=3.7" + #: ../../using/windows.rst:1108 msgid "Diagnostics" msgstr "Diagnósticos" @@ -2361,7 +2572,7 @@ msgstr "" #: ../../using/windows.rst:1118 msgid "Dry Run" -msgstr "" +msgstr "Teste de simulação" #: ../../using/windows.rst:1120 msgid "" @@ -2372,10 +2583,16 @@ msgid "" "written to standard output is always encoded using UTF-8, and may not render " "correctly in the console." msgstr "" +"Se uma variável de ambiente :envvar:`PYLAUNCHER_DRYRUN` for definida (para " +"qualquer valor), o inicializador emitirá o comando que ele teria executado, " +"mas não iniciará o Python de fato. Isso pode ser útil para ferramentas que " +"desejam usar o inicializador para detectar e então iniciar o Python " +"diretamente. Observe que o comando escrito na saída padrão é sempre " +"codificado usando UTF-8 e pode não ser renderizado corretamente no console." #: ../../using/windows.rst:1128 msgid "Install on demand" -msgstr "" +msgstr "Instalar sob demanda" #: ../../using/windows.rst:1130 msgid "" @@ -2385,6 +2602,11 @@ msgid "" "require user interaction to complete, and you may need to run the command " "again." msgstr "" +"Se uma variável de ambiente :envvar:`PYLAUNCHER_ALLOW_INSTALL` for definida " +"(para qualquer valor), e a versão do Python solicitada não estiver " +"instalada, mas estiver disponível na Microsoft Store, o inicializador " +"tentará instalá-la. Isso pode exigir interação do usuário para ser " +"concluído, e você pode precisar executar o comando novamente." #: ../../using/windows.rst:1135 msgid "" @@ -2393,10 +2615,14 @@ msgid "" "mainly intended for testing (and should be used with :envvar:" "`PYLAUNCHER_DRYRUN`)." msgstr "" +"Uma variável adicional :envvar:`PYLAUNCHER_ALWAYS_INSTALL` faz com que o " +"inicializador sempre tente instalar o Python, mesmo se for detectado. Isso é " +"destinado principalmente para teste (e deve ser usado com :envvar:" +"`PYLAUNCHER_DRYRUN`)." #: ../../using/windows.rst:1140 msgid "Return codes" -msgstr "" +msgstr "Códigos de retorno" #: ../../using/windows.rst:1142 msgid "" @@ -2404,6 +2630,9 @@ msgid "" "Unfortunately, there is no way to distinguish these from the exit code of " "Python itself." msgstr "" +"Os seguintes códigos de saída podem ser retornados pelo inicializador do " +"Python. Infelizmente, não há como distingui-los do código de saída do " +"próprio Python." #: ../../using/windows.rst:1145 msgid "" @@ -2411,6 +2640,9 @@ msgid "" "There is no way to access or resolve them apart from reading this page. " "Entries are listed in alphabetical order of names." msgstr "" +"Os nomes dos códigos são como usados nas fontes e são apenas para " +"referência. Não há como acessá-los ou resolvê-los além de ler esta página. " +"As entradas são listadas em ordem alfabética de nomes." #: ../../using/windows.rst:1150 msgid "Value" @@ -2426,7 +2658,7 @@ msgstr "107" #: ../../using/windows.rst:1152 msgid "A :file:`pyvenv.cfg` was found but is corrupt." -msgstr "" +msgstr "Um :file:`pyvenv.cfg` foi encontrado, mas está corrompido." #: ../../using/windows.rst:1154 msgid "RC_CREATE_PROCESS" @@ -2438,7 +2670,7 @@ msgstr "101" #: ../../using/windows.rst:1154 msgid "Failed to launch Python." -msgstr "" +msgstr "Falha ao iniciar o Python." #: ../../using/windows.rst:1156 msgid "RC_INSTALLING" @@ -2453,6 +2685,8 @@ msgid "" "An install was started, but the command will need to be re-run after it " "completes." msgstr "" +"Uma instalação foi iniciada, mas o comando precisará ser executado novamente " +"após sua conclusão." #: ../../using/windows.rst:1159 msgid "RC_INTERNAL_ERROR" @@ -2464,7 +2698,7 @@ msgstr "109" #: ../../using/windows.rst:1159 msgid "Unexpected error. Please report a bug." -msgstr "" +msgstr "Erro inesperado. Por favor, relate um bug." #: ../../using/windows.rst:1161 msgid "RC_NO_COMMANDLINE" @@ -2476,7 +2710,7 @@ msgstr "108" #: ../../using/windows.rst:1161 msgid "Unable to obtain command line from the operating system." -msgstr "" +msgstr "Não é possível obter a linha de comando do sistema operacional." #: ../../using/windows.rst:1164 msgid "RC_NO_PYTHON" @@ -2488,7 +2722,7 @@ msgstr "103" #: ../../using/windows.rst:1164 msgid "Unable to locate the requested version." -msgstr "" +msgstr "Não foi possível localizar a versão solicitada." #: ../../using/windows.rst:1166 msgid "RC_NO_VENV_CFG" @@ -2500,7 +2734,7 @@ msgstr "106" #: ../../using/windows.rst:1166 msgid "A :file:`pyvenv.cfg` was required but not found." -msgstr "" +msgstr "Um :file:`pyvenv.cfg` era necessário, mas não foi encontrado." #: ../../using/windows.rst:1174 msgid "Finding modules" @@ -2511,6 +2745,8 @@ msgid "" "These notes supplement the description at :ref:`sys-path-init` with detailed " "Windows notes." msgstr "" +"Estas notas complementam a descrição em :ref:`sys-path-init` com notas " +"detalhadas do Windows." #: ../../using/windows.rst:1179 msgid "" @@ -2672,6 +2908,9 @@ msgid "" "executable, explicitly set :c:member:`PyConfig.module_search_paths` before :" "c:func:`Py_InitializeFromConfig`." msgstr "" +"Se você estiver carregando :file:`python3.dll` ou :file:`python37.dll` em " +"seu próprio executável, defina explicitamente :c:member:`PyConfig." +"module_search_paths` antes de :c:func:`Py_InitializeFromConfig`." #: ../../using/windows.rst:1243 msgid "" @@ -2717,12 +2956,16 @@ msgid "" "Add ``._pth`` file support and removes ``applocal`` option from ``pyvenv." "cfg``." msgstr "" +"Adiciona suporte a arquivos ``._pth`` e remove a opção ``applocal`` do " +"``pyvenv.cfg``." #: ../../using/windows.rst:1265 msgid "" "Add :file:`python{XX}.zip` as a potential landmark when directly adjacent to " "the executable." msgstr "" +"Adiciona :file:`python{XX}.zip` como uma possível referência quando " +"diretamente adjacente ao executável." #: ../../using/windows.rst:1270 msgid "" @@ -2731,6 +2974,10 @@ msgid "" "finder is enabled on Windows in 3.6.0 and earlier, but may need to be " "explicitly added to :data:`sys.meta_path` in the future." msgstr "" +"Módulos especificados no registro sob ``Modules`` (não ``PythonPath``) podem " +"ser importados por :class:`importlib.machinery.WindowsRegistryFinder`. Este " +"localizador está ativo no Windows no 3.6.0 e anteriores, mas pode precisar " +"ser explicitamente adicionado ao :data:`sys.meta_path` no futuro." #: ../../using/windows.rst:1276 msgid "Additional modules" @@ -2764,12 +3011,16 @@ msgid "" "The :pypi:`PyWin32` module by Mark Hammond is a collection of modules for " "advanced Windows-specific support. This includes utilities for:" msgstr "" +"O módulo :pypi:`PyWin32` de Mark Hammond é uma coleção de módulos para " +"suporte avançado específico para Windows. Isso inclui utilitários para:" #: ../../using/windows.rst:1292 msgid "" -"`Component Object Model `_ (COM)" msgstr "" +"`Component Object Model `_ (COM)" #: ../../using/windows.rst:1295 msgid "Win32 API calls" @@ -2785,9 +3036,11 @@ msgstr "Log de Eventos" #: ../../using/windows.rst:1298 msgid "" -"`Microsoft Foundation Classes `_ (MFC) user interfaces" msgstr "" +"Interfaces de usuário `Microsoft Foundation Classes `_ (MFC)" #: ../../using/windows.rst:1302 msgid "" @@ -2801,9 +3054,9 @@ msgstr "" #: ../../using/windows.rst:1308 msgid "" -"`Win32 How Do I...? `_" +"`Win32 How Do I...? `_" msgstr "" -"`Win32 How Do I...? `_" +"`Win32 How Do I...? `_" #: ../../using/windows.rst:1309 msgid "by Tim Golden" @@ -2811,7 +3064,7 @@ msgstr "por Tim Golden" #: ../../using/windows.rst:1311 msgid "`Python and COM `_" -msgstr "" +msgstr "`Python e COM `_" #: ../../using/windows.rst:1312 msgid "by David and Paul Boddie" @@ -2828,6 +3081,10 @@ msgid "" "have done this, you can distribute your application without requiring your " "users to install Python." msgstr "" +"`cx_Freeze `_ encapsula scripts " +"Python em programas executáveis do Windows (arquivos :file:`{*}.exe`). " +"Quando você tiver feito isso, você pode distribuir sua aplicação sem " +"solicitar que os seus usuários instalem o Python." #: ../../using/windows.rst:1325 msgid "Compiling Python on Windows" @@ -2840,6 +3097,10 @@ msgid "" "either the latest release's source or just grab a fresh `checkout `_." msgstr "" +"Se você quer compilar o CPython por conta própria, a primeira coisa que você " +"precisa ter é a `fonte `_. Você " +"pode fazer o download tanto da fonte da última versão quanto pegar um novo " +"`checkout `_." #: ../../using/windows.rst:1332 msgid "" @@ -2847,6 +3108,10 @@ msgid "" "Visual Studio, which is the compiler used to build the official Python " "releases. These files are in the :file:`PCbuild` directory." msgstr "" +"A árvore de fontes contém uma solução de construção e arquivos de projeto " +"para o Microsoft Visual Studio, que é o compilador usado para construir as " +"versões do Python oficiais. Esses arquivos estão no diretório :file:" +"`PCbuild`." #: ../../using/windows.rst:1336 msgid "" @@ -2881,12 +3146,18 @@ msgid "" "`__ since Python 3 (if it " "ever was)." msgstr "" +"`Windows CE `_ `não é mais suportado " +"`__ desde o Python 3 (se é " +"que foi em algum momento)." #: ../../using/windows.rst:1351 msgid "" "The `Cygwin `_ installer offers to install the `Python " "interpreter `__ as well" msgstr "" +"O instalador do `Cygwin `_ oferece instalar o " +"`interpretador do Python `__ também" #: ../../using/windows.rst:1355 msgid "" diff --git a/whatsnew/2.0.po b/whatsnew/2.0.po index eb9aa2b5f..f8d8d9d06 100644 --- a/whatsnew/2.0.po +++ b/whatsnew/2.0.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Victor Matheus Castro , 2021 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:51+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -510,10 +509,44 @@ msgstr "" "For example, the following code writes a Unicode string into a file, " "encoding it as UTF-8::" +#: ../../whatsnew/2.0.rst:232 +msgid "" +"import codecs\n" +"\n" +"unistr = u'\\u0660\\u2000ab ...'\n" +"\n" +"(UTF8_encode, UTF8_decode,\n" +" UTF8_streamreader, UTF8_streamwriter) = codecs.lookup('UTF-8')\n" +"\n" +"output = UTF8_streamwriter( open( '/tmp/output', 'wb') )\n" +"output.write( unistr )\n" +"output.close()" +msgstr "" +"import codecs\n" +"\n" +"unistr = u'\\u0660\\u2000ab ...'\n" +"\n" +"(UTF8_encode, UTF8_decode,\n" +" UTF8_streamreader, UTF8_streamwriter) = codecs.lookup('UTF-8')\n" +"\n" +"output = UTF8_streamwriter( open( '/tmp/output', 'wb') )\n" +"output.write( unistr )\n" +"output.close()" + #: ../../whatsnew/2.0.rst:243 msgid "The following code would then read UTF-8 input from the file::" msgstr "The following code would then read UTF-8 input from the file::" +#: ../../whatsnew/2.0.rst:245 +msgid "" +"input = UTF8_streamreader( open( '/tmp/output', 'rb') )\n" +"print repr(input.read())\n" +"input.close()" +msgstr "" +"input = UTF8_streamreader( open( '/tmp/output', 'rb') )\n" +"print repr(input.read())\n" +"input.close()" + #: ../../whatsnew/2.0.rst:249 msgid "" "Unicode-aware regular expressions are available through the :mod:`re` " @@ -578,6 +611,20 @@ msgstr "" "paragraph, finding all the strings in the list containing a given " "substring. You could write the following to do it::" +#: ../../whatsnew/2.0.rst:280 +msgid "" +"# Given the list L, make a list of all strings\n" +"# containing the substring S.\n" +"sublist = filter( lambda s, substring=S:\n" +" string.find(s, substring) != -1,\n" +" L)" +msgstr "" +"# Given the list L, make a list of all strings\n" +"# containing the substring S.\n" +"sublist = filter( lambda s, substring=S:\n" +" string.find(s, substring) != -1,\n" +" L)" + #: ../../whatsnew/2.0.rst:286 msgid "" "Because of Python's scoping rules, a default argument is used so that the " @@ -588,10 +635,26 @@ msgstr "" "anonymous function created by the :keyword:`lambda` expression knows what " "substring is being searched for. List comprehensions make this cleaner::" +#: ../../whatsnew/2.0.rst:290 +msgid "sublist = [ s for s in L if string.find(s, S) != -1 ]" +msgstr "sublist = [ s for s in L if string.find(s, S) != -1 ]" + #: ../../whatsnew/2.0.rst:292 msgid "List comprehensions have the form::" msgstr "List comprehensions have the form::" +#: ../../whatsnew/2.0.rst:294 +msgid "" +"[ expression for expr in sequence1\n" +" for expr2 in sequence2 ...\n" +" for exprN in sequenceN\n" +" if condition ]" +msgstr "" +"[ expression for expr in sequence1\n" +" for expr2 in sequence2 ...\n" +" for exprN in sequenceN\n" +" if condition ]" + #: ../../whatsnew/2.0.rst:299 msgid "" "The :keyword:`!for`...\\ :keyword:`!in` clauses contain the sequences to be " @@ -618,6 +681,26 @@ msgstr "" "To make the semantics very clear, a list comprehension is equivalent to the " "following Python code::" +#: ../../whatsnew/2.0.rst:310 +msgid "" +"for expr1 in sequence1:\n" +" for expr2 in sequence2:\n" +" ...\n" +" for exprN in sequenceN:\n" +" if (condition):\n" +" # Append the value of\n" +" # the expression to the\n" +" # resulting list." +msgstr "" +"for expr1 in sequence1:\n" +" for expr2 in sequence2:\n" +" ...\n" +" for exprN in sequenceN:\n" +" if (condition):\n" +" # Append the value of\n" +" # the expression to the\n" +" # resulting list." + #: ../../whatsnew/2.0.rst:319 msgid "" "This means that when there are multiple :keyword:`!for`...\\ :keyword:`!in` " @@ -630,6 +713,20 @@ msgstr "" "all the sequences. If you have two lists of length 3, the output list is 9 " "elements long::" +#: ../../whatsnew/2.0.rst:324 +msgid "" +"seq1 = 'abc'\n" +"seq2 = (1,2,3)\n" +">>> [ (x,y) for x in seq1 for y in seq2]\n" +"[('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1),\n" +"('c', 2), ('c', 3)]" +msgstr "" +"seq1 = 'abc'\n" +"seq2 = (1,2,3)\n" +">>> [ (x,y) for x in seq1 for y in seq2]\n" +"[('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1),\n" +"('c', 2), ('c', 3)]" + #: ../../whatsnew/2.0.rst:330 msgid "" "To avoid introducing an ambiguity into Python's grammar, if *expression* is " @@ -640,6 +737,18 @@ msgstr "" "creating a tuple, it must be surrounded with parentheses. The first list " "comprehension below is a syntax error, while the second one is correct::" +#: ../../whatsnew/2.0.rst:334 +msgid "" +"# Syntax error\n" +"[ x,y for x in seq1 for y in seq2]\n" +"# Correct\n" +"[ (x,y) for x in seq1 for y in seq2]" +msgstr "" +"# Syntax error\n" +"[ x,y for x in seq1 for y in seq2]\n" +"# Correct\n" +"[ (x,y) for x in seq1 for y in seq2]" + #: ../../whatsnew/2.0.rst:339 msgid "" "The idea of list comprehensions originally comes from the functional " @@ -688,6 +797,28 @@ msgstr "" "following :class:`!Number` class stores a number and supports using += to " "create a new instance with an incremented value." +#: ../../whatsnew/2.0.rst:367 +msgid "" +"class Number:\n" +" def __init__(self, value):\n" +" self.value = value\n" +" def __iadd__(self, increment):\n" +" return Number( self.value + increment)\n" +"\n" +"n = Number(5)\n" +"n += 3\n" +"print n.value" +msgstr "" +"class Number:\n" +" def __init__(self, value):\n" +" self.value = value\n" +" def __iadd__(self, increment):\n" +" return Number( self.value + increment)\n" +"\n" +"n = Number(5)\n" +"n += 3\n" +"print n.value" + #: ../../whatsnew/2.0.rst:377 msgid "" "The :meth:`!__iadd__` special method is called with the value of the " @@ -744,6 +875,22 @@ msgstr "" "manipulation functionality available through methods on both 8-bit strings " "and Unicode strings. ::" +#: ../../whatsnew/2.0.rst:404 +msgid "" +">>> 'andrew'.capitalize()\n" +"'Andrew'\n" +">>> 'hostname'.replace('os', 'linux')\n" +"'hlinuxtname'\n" +">>> 'moshe'.find('sh')\n" +"2" +msgstr "" +">>> 'andrew'.capitalize()\n" +"'Andrew'\n" +">>> 'hostname'.replace('os', 'linux')\n" +"'hlinuxtname'\n" +">>> 'moshe'.find('sh')\n" +"2" + #: ../../whatsnew/2.0.rst:411 msgid "" "One thing that hasn't changed, a noteworthy April Fools' joke " @@ -834,6 +981,14 @@ msgstr "" "Consider the simplest possible cycle, a class instance which has a " "reference to itself::" +#: ../../whatsnew/2.0.rst:452 +msgid "" +"instance = SomeClass()\n" +"instance.myself = instance" +msgstr "" +"instance = SomeClass()\n" +"instance.myself = instance" + #: ../../whatsnew/2.0.rst:455 msgid "" "After the above two lines of code have been executed, the reference count of " @@ -958,6 +1113,18 @@ msgstr "" "and clearer way to achieve the same effect. This syntax is symmetrical with " "the syntax for defining functions::" +#: ../../whatsnew/2.0.rst:513 +msgid "" +"def f(*args, **kw):\n" +" # args is a tuple of positional args,\n" +" # kw is a dictionary of keyword args\n" +" ..." +msgstr "" +"def f(*args, **kw):\n" +" # args is a tuple of positional args,\n" +" # kw is a dictionary of keyword args\n" +" ..." + #: ../../whatsnew/2.0.rst:518 msgid "" "The ``print`` statement can now have its output directed to a file-like " @@ -976,6 +1143,10 @@ msgstr "" "``sys.stdout`` and then restore the old value. For sending output to " "standard error, it's much easier to write this::" +#: ../../whatsnew/2.0.rst:526 +msgid "print >> sys.stderr, \"Warning: action field not supplied\"" +msgstr "print >> sys.stderr, \"Warning: action field not supplied\"" + #: ../../whatsnew/2.0.rst:528 msgid "" "Modules can now be renamed on importing them, using the syntax ``import " @@ -1038,6 +1209,18 @@ msgstr "" "and crashed; Jeremy Hylton rewrote the code to no longer crash, producing a " "useful result instead. For example, after this code::" +#: ../../whatsnew/2.0.rst:554 +msgid "" +"a = []\n" +"b = []\n" +"a.append(a)\n" +"b.append(b)" +msgstr "" +"a = []\n" +"b = []\n" +"a.append(a)\n" +"b.append(b)" + #: ../../whatsnew/2.0.rst:559 msgid "" "The comparison ``a==b`` returns true, because the two recursive data " @@ -1106,6 +1289,18 @@ msgstr "" "exc:`NameError`, so any existing code that expects :exc:`NameError` to be " "raised should still work. ::" +#: ../../whatsnew/2.0.rst:590 +msgid "" +"def f():\n" +" print \"i=\",i\n" +" i = i + 1\n" +"f()" +msgstr "" +"def f():\n" +" print \"i=\",i\n" +" i = i + 1\n" +"f()" + #: ../../whatsnew/2.0.rst:595 msgid "" "Two new exceptions, :exc:`TabError` and :exc:`IndentationError`, have been " @@ -1178,6 +1373,18 @@ msgstr "" "`!get` would do, and also inserts it into the dictionary as the value for " "*key*. Thus, the following lines of code::" +#: ../../whatsnew/2.0.rst:628 +msgid "" +"if dict.has_key( key ): return dict[key]\n" +"else:\n" +" dict[key] = []\n" +" return dict[key]" +msgstr "" +"if dict.has_key( key ): return dict[key]\n" +"else:\n" +" dict[key] = []\n" +" return dict[key]" + #: ../../whatsnew/2.0.rst:633 msgid "" "can be reduced to a single ``return dict.setdefault(key, [])`` statement." @@ -1618,6 +1825,16 @@ msgstr "" "For the simple case, when the software contains only .py files, a minimal :" "file:`setup.py` can be just a few lines long::" +#: ../../whatsnew/2.0.rst:837 +msgid "" +"from distutils.core import setup\n" +"setup (name = \"foo\", version = \"1.0\",\n" +" py_modules = [\"module1\", \"module2\"])" +msgstr "" +"from distutils.core import setup\n" +"setup (name = \"foo\", version = \"1.0\",\n" +" py_modules = [\"module1\", \"module2\"])" + #: ../../whatsnew/2.0.rst:841 msgid "" "The :file:`setup.py` file isn't much more complicated if the software " @@ -1626,6 +1843,16 @@ msgstr "" "The :file:`setup.py` file isn't much more complicated if the software " "consists of a few packages::" +#: ../../whatsnew/2.0.rst:844 +msgid "" +"from distutils.core import setup\n" +"setup (name = \"foo\", version = \"1.0\",\n" +" packages = [\"package\", \"package.subpackage\"])" +msgstr "" +"from distutils.core import setup\n" +"setup (name = \"foo\", version = \"1.0\",\n" +" packages = [\"package\", \"package.subpackage\"])" + #: ../../whatsnew/2.0.rst:848 msgid "" "A C extension can be the most complicated case; here's an example taken from " @@ -1634,6 +1861,34 @@ msgstr "" "A C extension can be the most complicated case; here's an example taken from " "the PyXML package::" +#: ../../whatsnew/2.0.rst:851 +msgid "" +"from distutils.core import setup, Extension\n" +"\n" +"expat_extension = Extension('xml.parsers.pyexpat',\n" +" define_macros = [('XML_NS', None)],\n" +" include_dirs = [ 'extensions/expat/xmltok',\n" +" 'extensions/expat/xmlparse' ],\n" +" sources = [ 'extensions/pyexpat.c',\n" +" 'extensions/expat/xmltok/xmltok.c',\n" +" 'extensions/expat/xmltok/xmlrole.c', ]\n" +" )\n" +"setup (name = \"PyXML\", version = \"0.5.4\",\n" +" ext_modules =[ expat_extension ] )" +msgstr "" +"from distutils.core import setup, Extension\n" +"\n" +"expat_extension = Extension('xml.parsers.pyexpat',\n" +" define_macros = [('XML_NS', None)],\n" +" include_dirs = [ 'extensions/expat/xmltok',\n" +" 'extensions/expat/xmlparse' ],\n" +" sources = [ 'extensions/pyexpat.c',\n" +" 'extensions/expat/xmltok/xmltok.c',\n" +" 'extensions/expat/xmltok/xmlrole.c', ]\n" +" )\n" +"setup (name = \"PyXML\", version = \"0.5.4\",\n" +" ext_modules =[ expat_extension ] )" + #: ../../whatsnew/2.0.rst:864 msgid "" "The Distutils can also take care of creating source and binary " @@ -1740,6 +1995,46 @@ msgstr "" "message for every starting and ending tag, and then parses the file :file:" "`hamlet.xml` using it::" +#: ../../whatsnew/2.0.rst:916 +msgid "" +"from xml import sax\n" +"\n" +"class SimpleHandler(sax.ContentHandler):\n" +" def startElement(self, name, attrs):\n" +" print 'Start of element:', name, attrs.keys()\n" +"\n" +" def endElement(self, name):\n" +" print 'End of element:', name\n" +"\n" +"# Create a parser object\n" +"parser = sax.make_parser()\n" +"\n" +"# Tell it what handler to use\n" +"handler = SimpleHandler()\n" +"parser.setContentHandler( handler )\n" +"\n" +"# Parse a file!\n" +"parser.parse( 'hamlet.xml' )" +msgstr "" +"from xml import sax\n" +"\n" +"class SimpleHandler(sax.ContentHandler):\n" +" def startElement(self, name, attrs):\n" +" print 'Start of element:', name, attrs.keys()\n" +"\n" +" def endElement(self, name):\n" +" print 'End of element:', name\n" +"\n" +"# Create a parser object\n" +"parser = sax.make_parser()\n" +"\n" +"# Tell it what handler to use\n" +"handler = SimpleHandler()\n" +"parser.setContentHandler( handler )\n" +"\n" +"# Parse a file!\n" +"parser.parse( 'hamlet.xml' )" + #: ../../whatsnew/2.0.rst:935 msgid "" "For more information, consult the Python documentation, or the XML HOWTO at " @@ -1800,6 +2095,14 @@ msgstr "" "support for XML namespaces. The :func:`!parse` and :func:`!parseString` " "convenience functions are provided for generating a DOM tree::" +#: ../../whatsnew/2.0.rst:961 +msgid "" +"from xml.dom import minidom\n" +"doc = minidom.parse('hamlet.xml')" +msgstr "" +"from xml.dom import minidom\n" +"doc = minidom.parse('hamlet.xml')" + #: ../../whatsnew/2.0.rst:964 msgid "" "``doc`` is a :class:`!Document` instance. :class:`!Document`, like all the " @@ -1820,10 +2123,28 @@ msgstr "" "and :class:`!Document` instances have a method to find all child elements " "with a given tag name. Continuing from the previous 2-line example::" +#: ../../whatsnew/2.0.rst:973 +msgid "" +"perslist = doc.getElementsByTagName( 'PERSONA' )\n" +"print perslist[0].toxml()\n" +"print perslist[1].toxml()" +msgstr "" +"perslist = doc.getElementsByTagName( 'PERSONA' )\n" +"print perslist[0].toxml()\n" +"print perslist[1].toxml()" + #: ../../whatsnew/2.0.rst:977 msgid "For the *Hamlet* XML file, the above few lines output::" msgstr "For the *Hamlet* XML file, the above few lines output::" +#: ../../whatsnew/2.0.rst:979 +msgid "" +"CLAUDIUS, king of Denmark. \n" +"HAMLET, son to the late, and nephew to the present king." +msgstr "" +"CLAUDIUS, king of Denmark. \n" +"HAMLET, son to the late, and nephew to the present king." + #: ../../whatsnew/2.0.rst:982 msgid "" "The root element of the document is available as ``doc.documentElement``, " @@ -1834,6 +2155,32 @@ msgstr "" "and its children can be easily modified by deleting, adding, or removing " "nodes::" +#: ../../whatsnew/2.0.rst:985 +msgid "" +"root = doc.documentElement\n" +"\n" +"# Remove the first child\n" +"root.removeChild( root.childNodes[0] )\n" +"\n" +"# Move the new first child to the end\n" +"root.appendChild( root.childNodes[0] )\n" +"\n" +"# Insert the new first child (originally,\n" +"# the third child) before the 20th child.\n" +"root.insertBefore( root.childNodes[0], root.childNodes[20] )" +msgstr "" +"root = doc.documentElement\n" +"\n" +"# Remove the first child\n" +"root.removeChild( root.childNodes[0] )\n" +"\n" +"# Move the new first child to the end\n" +"root.appendChild( root.childNodes[0] )\n" +"\n" +"# Insert the new first child (originally,\n" +"# the third child) before the 20th child.\n" +"root.insertBefore( root.childNodes[0], root.childNodes[20] )" + #: ../../whatsnew/2.0.rst:997 msgid "" "Again, I will refer you to the Python documentation for a complete listing " @@ -1999,7 +2346,7 @@ msgstr "" #: ../../whatsnew/2.0.rst:1075 msgid "New modules" -msgstr "New modules" +msgstr "Novos módulos" #: ../../whatsnew/2.0.rst:1077 msgid "" @@ -2289,7 +2636,7 @@ msgstr "" #: ../../whatsnew/2.0.rst:1200 msgid "Acknowledgements" -msgstr "Acknowledgements" +msgstr "Reconhecimentos" #: ../../whatsnew/2.0.rst:1202 msgid "" diff --git a/whatsnew/2.1.po b/whatsnew/2.1.po index 2c3aa928c..55c171a45 100644 --- a/whatsnew/2.1.po +++ b/whatsnew/2.1.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# (Douglas da Silva) , 2021 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:51+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -100,6 +97,22 @@ msgstr "" "surprised people because it didn't match their intuitive expectations. For " "example, a nested recursive function definition doesn't work::" +#: ../../whatsnew/2.1.rst:44 +msgid "" +"def f():\n" +" ...\n" +" def g(value):\n" +" ...\n" +" return g(value-1) + 1\n" +" ..." +msgstr "" +"def f():\n" +" ...\n" +" def g(value):\n" +" ...\n" +" return g(value-1) + 1\n" +" ..." + #: ../../whatsnew/2.1.rst:51 msgid "" "The function :func:`!g` will always raise a :exc:`NameError` exception, " @@ -120,6 +133,20 @@ msgstr "" "find local variables being copied by passing them as the default values of " "arguments. ::" +#: ../../whatsnew/2.1.rst:59 +msgid "" +"def find(self, name):\n" +" \"Return list of any entries equal to 'name'\"\n" +" L = filter(lambda x, name=name: x == name,\n" +" self.list_attribute)\n" +" return L" +msgstr "" +"def find(self, name):\n" +" \"Return list of any entries equal to 'name'\"\n" +" L = filter(lambda x, name=name: x == name,\n" +" self.list_attribute)\n" +" return L" + #: ../../whatsnew/2.1.rst:65 msgid "" "The readability of Python code written in a strongly functional style " @@ -194,6 +221,22 @@ msgstr "" msgid "To make the preceding explanation a bit clearer, here's an example::" msgstr "To make the preceding explanation a bit clearer, here's an example::" +#: ../../whatsnew/2.1.rst:98 +msgid "" +"x = 1\n" +"def f():\n" +" # The next line is a syntax error\n" +" exec 'x=2'\n" +" def g():\n" +" return x" +msgstr "" +"x = 1\n" +"def f():\n" +" # The next line is a syntax error\n" +" exec 'x=2'\n" +" def g():\n" +" return x" + #: ../../whatsnew/2.1.rst:105 msgid "" "Line 4 containing the ``exec`` statement is a syntax error, since ``exec`` " @@ -268,6 +311,10 @@ msgstr "" "name :mod:`__future__`. Nested scopes can be enabled by the following " "statement::" +#: ../../whatsnew/2.1.rst:141 +msgid "from __future__ import nested_scopes" +msgstr "from __future__ import nested_scopes" + #: ../../whatsnew/2.1.rst:143 msgid "" "While it looks like a normal :keyword:`import` statement, it's not; there " @@ -337,11 +384,11 @@ msgstr "" #: ../../whatsnew/2.1.rst:179 msgid "Operation" -msgstr "Operation" +msgstr "Operação" #: ../../whatsnew/2.1.rst:179 msgid "Method name" -msgstr "Method name" +msgstr "Nome do método" #: ../../whatsnew/2.1.rst:181 msgid "``<``" @@ -517,10 +564,26 @@ msgstr "" "For example, in Python 2.1 the :mod:`!regex` module is deprecated, so " "importing it causes a warning to be printed::" +#: ../../whatsnew/2.1.rst:251 +msgid "" +">>> import regex\n" +"__main__:1: DeprecationWarning: the regex module\n" +" is deprecated; please use the re module\n" +">>>" +msgstr "" +">>> import regex\n" +"__main__:1: DeprecationWarning: the regex module\n" +" is deprecated; please use the re module\n" +">>>" + #: ../../whatsnew/2.1.rst:256 msgid "Warnings can be issued by calling the :func:`warnings.warn` function::" msgstr "Warnings can be issued by calling the :func:`warnings.warn` function::" +#: ../../whatsnew/2.1.rst:258 +msgid "warnings.warn(\"feature X no longer supported\")" +msgstr "warnings.warn(\"feature X no longer supported\")" + #: ../../whatsnew/2.1.rst:260 msgid "" "The first parameter is the warning message; an additional optional " @@ -543,6 +606,20 @@ msgstr "" "`!regex` module and not want to spare the time to convert it to use the :mod:" "`re` module right now. The warning can be suppressed by calling ::" +#: ../../whatsnew/2.1.rst:269 +msgid "" +"import warnings\n" +"warnings.filterwarnings(action = 'ignore',\n" +" message='.*regex module is deprecated',\n" +" category=DeprecationWarning,\n" +" module = '__main__')" +msgstr "" +"import warnings\n" +"warnings.filterwarnings(action = 'ignore',\n" +" message='.*regex module is deprecated',\n" +" category=DeprecationWarning,\n" +" module = '__main__')" + #: ../../whatsnew/2.1.rst:275 msgid "" "This adds a filter that will apply only to warnings of the class :class:" @@ -707,6 +784,32 @@ msgstr "" "another function ``f(x)`` by storing the function's argument and its result " "in a dictionary::" +#: ../../whatsnew/2.1.rst:356 +msgid "" +"_cache = {}\n" +"def memoize(x):\n" +" if _cache.has_key(x):\n" +" return _cache[x]\n" +"\n" +" retval = f(x)\n" +"\n" +" # Cache the returned object\n" +" _cache[x] = retval\n" +"\n" +" return retval" +msgstr "" +"_cache = {}\n" +"def memoize(x):\n" +" if _cache.has_key(x):\n" +" return _cache[x]\n" +"\n" +" retval = f(x)\n" +"\n" +" # Cache the returned object\n" +" _cache[x] = retval\n" +"\n" +" return retval" + #: ../../whatsnew/2.1.rst:368 msgid "" "This version works for simple things such as integers, but it has a side " @@ -751,6 +854,38 @@ msgstr "" "This makes it possible to write a :func:`!memoize` function whose cache " "doesn't keep objects alive, by storing weak references in the cache. ::" +#: ../../whatsnew/2.1.rst:385 +msgid "" +"_cache = {}\n" +"def memoize(x):\n" +" if _cache.has_key(x):\n" +" obj = _cache[x]()\n" +" # If weak reference object still exists,\n" +" # return it\n" +" if obj is not None: return obj\n" +"\n" +" retval = f(x)\n" +"\n" +" # Cache a weak reference\n" +" _cache[x] = weakref.ref(retval)\n" +"\n" +" return retval" +msgstr "" +"_cache = {}\n" +"def memoize(x):\n" +" if _cache.has_key(x):\n" +" obj = _cache[x]()\n" +" # If weak reference object still exists,\n" +" # return it\n" +" if obj is not None: return obj\n" +"\n" +" retval = f(x)\n" +"\n" +" # Cache a weak reference\n" +" _cache[x] = weakref.ref(retval)\n" +"\n" +" return retval" + #: ../../whatsnew/2.1.rst:400 msgid "" "The :mod:`weakref` module also allows creating proxy objects which behave " @@ -769,6 +904,20 @@ msgstr "" "to use a proxy will cause a :exc:`!weakref.ReferenceError` exception to be " "raised. ::" +#: ../../whatsnew/2.1.rst:407 +msgid "" +"proxy = weakref.proxy(obj)\n" +"proxy.attr # Equivalent to obj.attr\n" +"proxy.meth() # Equivalent to obj.meth()\n" +"del obj\n" +"proxy.attr # raises weakref.ReferenceError" +msgstr "" +"proxy = weakref.proxy(obj)\n" +"proxy.attr # Equivalent to obj.attr\n" +"proxy.meth() # Equivalent to obj.meth()\n" +"del obj\n" +"proxy.attr # raises weakref.ReferenceError" + #: ../../whatsnew/2.1.rst:416 msgid ":pep:`205` - Weak References" msgstr ":pep:`205` - Weak References" @@ -813,19 +962,33 @@ msgstr "" "Arbitrary attributes can now be set and retrieved on functions using the " "regular Python syntax::" +#: ../../whatsnew/2.1.rst:439 +msgid "" +"def f(): pass\n" +"\n" +"f.publish = 1\n" +"f.secure = 1\n" +"f.grammar = \"A ::= B (C D)*\"" +msgstr "" +"def f(): pass\n" +"\n" +"f.publish = 1\n" +"f.secure = 1\n" +"f.grammar = \"A ::= B (C D)*\"" + #: ../../whatsnew/2.1.rst:445 msgid "" "The dictionary containing attributes can be accessed as the function's :attr:" -"`~object.__dict__`. Unlike the :attr:`~object.__dict__` attribute of class " +"`~function.__dict__`. Unlike the :attr:`~type.__dict__` attribute of class " "instances, in functions you can actually assign a new dictionary to :attr:" -"`~object.__dict__`, though the new value is restricted to a regular Python " +"`~function.__dict__`, though the new value is restricted to a regular Python " "dictionary; you *can't* be tricky and set it to a :class:`!UserDict` " "instance, or any other random object that behaves like a mapping." msgstr "" "The dictionary containing attributes can be accessed as the function's :attr:" -"`~object.__dict__`. Unlike the :attr:`~object.__dict__` attribute of class " +"`~function.__dict__`. Unlike the :attr:`~type.__dict__` attribute of class " "instances, in functions you can actually assign a new dictionary to :attr:" -"`~object.__dict__`, though the new value is restricted to a regular Python " +"`~function.__dict__`, though the new value is restricted to a regular Python " "dictionary; you *can't* be tricky and set it to a :class:`!UserDict` " "instance, or any other random object that behaves like a mapping." @@ -887,6 +1050,32 @@ msgstr "" "be called instead of :func:`repr`. For example, you can set it to a special " "pretty-printing function::" +#: ../../whatsnew/2.1.rst:488 +msgid "" +">>> # Create a recursive data structure\n" +"... L = [1,2,3]\n" +">>> L.append(L)\n" +">>> L # Show Python's default output\n" +"[1, 2, 3, [...]]\n" +">>> # Use pprint.pprint() as the display function\n" +"... import sys, pprint\n" +">>> sys.displayhook = pprint.pprint\n" +">>> L\n" +"[1, 2, 3, ]\n" +">>>" +msgstr "" +">>> # Create a recursive data structure\n" +"... L = [1,2,3]\n" +">>> L.append(L)\n" +">>> L # Show Python's default output\n" +"[1, 2, 3, [...]]\n" +">>> # Use pprint.pprint() as the display function\n" +"... import sys, pprint\n" +">>> sys.displayhook = pprint.pprint\n" +">>> L\n" +"[1, 2, 3, ]\n" +">>>" + #: ../../whatsnew/2.1.rst:503 msgid ":pep:`217` - Display Hook for Interactive Use" msgstr ":pep:`217` - Display Hook for Interactive Use" @@ -1039,7 +1228,7 @@ msgstr "" #: ../../whatsnew/2.1.rst:585 msgid "New and Improved Modules" -msgstr "New and Improved Modules" +msgstr "Módulos Novos ou Aprimorados" #: ../../whatsnew/2.1.rst:587 msgid "" @@ -1057,6 +1246,38 @@ msgstr "" "pydoc.py` to display documentation given a Python module, package, or class " "name. For example, ``pydoc xml.dom`` displays the following::" +#: ../../whatsnew/2.1.rst:594 +msgid "" +"Python Library Documentation: package xml.dom in xml\n" +"\n" +"NAME\n" +" xml.dom - W3C Document Object Model implementation for Python.\n" +"\n" +"FILE\n" +" /usr/local/lib/python2.1/xml/dom/__init__.pyc\n" +"\n" +"DESCRIPTION\n" +" The Python mapping of the Document Object Model is documented in the\n" +" Python Library Reference in the section on the xml.dom package.\n" +"\n" +" This package contains the following modules:\n" +" ..." +msgstr "" +"Python Library Documentation: package xml.dom in xml\n" +"\n" +"NAME\n" +" xml.dom - W3C Document Object Model implementation for Python.\n" +"\n" +"FILE\n" +" /usr/local/lib/python2.1/xml/dom/__init__.pyc\n" +"\n" +"DESCRIPTION\n" +" The Python mapping of the Document Object Model is documented in the\n" +" Python Library Reference in the section on the xml.dom package.\n" +"\n" +" This package contains the following modules:\n" +" ..." + #: ../../whatsnew/2.1.rst:609 msgid "" ":file:`pydoc` also includes a Tk-based interactive help browser. :file:" @@ -1239,7 +1460,7 @@ msgstr "" #: ../../whatsnew/2.1.rst:688 msgid "Other Changes and Fixes" -msgstr "Other Changes and Fixes" +msgstr "Outras alterações e correções" #: ../../whatsnew/2.1.rst:690 msgid "" @@ -1341,6 +1562,16 @@ msgstr "" "but not reading the entire file into memory as the existing :meth:`!" "readlines` method does. You'd use it like this::" +#: ../../whatsnew/2.1.rst:733 +msgid "" +"for line in sys.stdin.xreadlines():\n" +" # ... do something for each line ...\n" +" ..." +msgstr "" +"for line in sys.stdin.xreadlines():\n" +" # ... do something for each line ...\n" +" ..." + #: ../../whatsnew/2.1.rst:737 msgid "" "For a fuller discussion of the line I/O changes, see the python-dev summary " @@ -1385,6 +1616,14 @@ msgstr "" "will add them to the importing module's namespace. To fix this, simply list " "the public names in ``__all__``::" +#: ../../whatsnew/2.1.rst:755 +msgid "" +"# List public names\n" +"__all__ = ['Database', 'open']" +msgstr "" +"# List public names\n" +"__all__ = ['Database', 'open']" + #: ../../whatsnew/2.1.rst:758 msgid "" "A stricter version of this patch was first suggested and implemented by Ben " @@ -1463,7 +1702,7 @@ msgstr "" #: ../../whatsnew/2.1.rst:793 msgid "Acknowledgements" -msgstr "Acknowledgements" +msgstr "Reconhecimentos" #: ../../whatsnew/2.1.rst:795 msgid "" diff --git a/whatsnew/2.2.po b/whatsnew/2.2.po index 295d8f43d..c8c53f5f5 100644 --- a/whatsnew/2.2.po +++ b/whatsnew/2.2.po @@ -1,27 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-28 01:51+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -253,6 +251,18 @@ msgstr "" "types, has also been added so if no built-in type is suitable, you can just " "subclass :class:`object`::" +#: ../../whatsnew/2.2.rst:116 +msgid "" +"class C(object):\n" +" def __init__ (self):\n" +" ...\n" +" ..." +msgstr "" +"class C(object):\n" +" def __init__ (self):\n" +" ...\n" +" ..." + #: ../../whatsnew/2.2.rst:121 msgid "" "This means that :keyword:`class` statements that don't have any base classes " @@ -279,6 +289,18 @@ msgstr "" "`int`, :func:`float`, and :func:`str`. In 2.2, they aren't functions any " "more, but type objects that behave as factories when called. ::" +#: ../../whatsnew/2.2.rst:131 +msgid "" +">>> int\n" +"\n" +">>> int('123')\n" +"123" +msgstr "" +">>> int\n" +"\n" +">>> int('123')\n" +"123" + #: ../../whatsnew/2.2.rst:136 msgid "" "To make the set of types complete, new type objects such as :func:`dict` " @@ -289,6 +311,20 @@ msgstr "" "and :func:`!file` have been added. Here's a more interesting example, " "adding a :meth:`!lock` method to file objects::" +#: ../../whatsnew/2.2.rst:140 +msgid "" +"class LockableFile(file):\n" +" def lock (self, operation, length=0, start=0, whence=0):\n" +" import fcntl\n" +" return fcntl.lockf(self.fileno(), operation,\n" +" length, start, whence)" +msgstr "" +"class LockableFile(file):\n" +" def lock (self, operation, length=0, start=0, whence=0):\n" +" import fcntl\n" +" return fcntl.lockf(self.fileno(), operation,\n" +" length, start, whence)" + #: ../../whatsnew/2.2.rst:146 msgid "" "The now-obsolete :mod:`!posixfile` module contained a class that emulated " @@ -352,8 +388,8 @@ msgid ":attr:`~definition.__name__` is the attribute's name." msgstr ":attr:`~definition.__name__` is the attribute's name." #: ../../whatsnew/2.2.rst:174 -msgid ":attr:`!__doc__` is the attribute's docstring." -msgstr ":attr:`!__doc__` is the attribute's docstring." +msgid ":attr:`~definition.__doc__` is the attribute's docstring." +msgstr ":attr:`~definition.__doc__` is the attribute's docstring." #: ../../whatsnew/2.2.rst:176 msgid "" @@ -381,27 +417,55 @@ msgstr "" "For example, when you write ``obj.x``, the steps that Python actually " "performs are::" +#: ../../whatsnew/2.2.rst:186 +msgid "" +"descriptor = obj.__class__.x\n" +"descriptor.__get__(obj)" +msgstr "" +"descriptor = obj.__class__.x\n" +"descriptor.__get__(obj)" + #: ../../whatsnew/2.2.rst:189 msgid "" -"For methods, :meth:`!descriptor.__get__` returns a temporary object that's " -"callable, and wraps up the instance and the method to be called on it. This " -"is also why static methods and class methods are now possible; they have " -"descriptors that wrap up just the method, or the method and the class. As a " -"brief explanation of these new kinds of methods, static methods aren't " -"passed the instance, and therefore resemble regular functions. Class " -"methods are passed the class of the object, but not the object itself. " -"Static and class methods are defined like this::" -msgstr "" -"For methods, :meth:`!descriptor.__get__` returns a temporary object that's " -"callable, and wraps up the instance and the method to be called on it. This " -"is also why static methods and class methods are now possible; they have " -"descriptors that wrap up just the method, or the method and the class. As a " -"brief explanation of these new kinds of methods, static methods aren't " -"passed the instance, and therefore resemble regular functions. Class " -"methods are passed the class of the object, but not the object itself. " -"Static and class methods are defined like this::" - -#: ../../whatsnew/2.2.rst:207 +"For methods, :meth:`descriptor.__get__ ` returns a temporary " +"object that's callable, and wraps up the instance and the method to be " +"called on it. This is also why static methods and class methods are now " +"possible; they have descriptors that wrap up just the method, or the method " +"and the class. As a brief explanation of these new kinds of methods, static " +"methods aren't passed the instance, and therefore resemble regular " +"functions. Class methods are passed the class of the object, but not the " +"object itself. Static and class methods are defined like this::" +msgstr "" +"For methods, :meth:`descriptor.__get__ ` returns a temporary " +"object that's callable, and wraps up the instance and the method to be " +"called on it. This is also why static methods and class methods are now " +"possible; they have descriptors that wrap up just the method, or the method " +"and the class. As a brief explanation of these new kinds of methods, static " +"methods aren't passed the instance, and therefore resemble regular " +"functions. Class methods are passed the class of the object, but not the " +"object itself. Static and class methods are defined like this::" + +#: ../../whatsnew/2.2.rst:199 +msgid "" +"class C(object):\n" +" def f(arg1, arg2):\n" +" ...\n" +" f = staticmethod(f)\n" +"\n" +" def g(cls, arg1, arg2):\n" +" ...\n" +" g = classmethod(g)" +msgstr "" +"class C(object):\n" +" def f(arg1, arg2):\n" +" ...\n" +" f = staticmethod(f)\n" +"\n" +" def g(cls, arg1, arg2):\n" +" ...\n" +" g = classmethod(g)" + +#: ../../whatsnew/2.2.rst:208 msgid "" "The :func:`staticmethod` function takes the function :func:`!f`, and returns " "it wrapped up in a descriptor so it can be stored in the class object. You " @@ -415,7 +479,7 @@ msgstr "" "static f``, ``defstatic f()``, or something like that) but no such syntax " "has been defined yet; that's been left for future versions of Python." -#: ../../whatsnew/2.2.rst:213 +#: ../../whatsnew/2.2.rst:214 msgid "" "More new features, such as slots and properties, are also implemented as new " "kinds of descriptors, and it's not difficult to write a descriptor class " @@ -431,7 +495,39 @@ msgstr "" "and postconditions for a method. A class that used this feature might be " "defined like this::" -#: ../../whatsnew/2.2.rst:235 +#: ../../whatsnew/2.2.rst:221 +msgid "" +"from eiffel import eiffelmethod\n" +"\n" +"class C(object):\n" +" def f(self, arg1, arg2):\n" +" # The actual function\n" +" ...\n" +" def pre_f(self):\n" +" # Check preconditions\n" +" ...\n" +" def post_f(self):\n" +" # Check postconditions\n" +" ...\n" +"\n" +" f = eiffelmethod(f, pre_f, post_f)" +msgstr "" +"from eiffel import eiffelmethod\n" +"\n" +"class C(object):\n" +" def f(self, arg1, arg2):\n" +" # The actual function\n" +" ...\n" +" def pre_f(self):\n" +" # Check preconditions\n" +" ...\n" +" def post_f(self):\n" +" # Check postconditions\n" +" ...\n" +"\n" +" f = eiffelmethod(f, pre_f, post_f)" + +#: ../../whatsnew/2.2.rst:236 msgid "" "Note that a person using the new :func:`!eiffelmethod` doesn't have to " "understand anything about descriptors. This is why I think the new features " @@ -447,11 +543,11 @@ msgstr "" "the ZODB or whatever, but most users will just write code on top of the " "resulting libraries and ignore the implementation details." -#: ../../whatsnew/2.2.rst:244 +#: ../../whatsnew/2.2.rst:245 msgid "Multiple Inheritance: The Diamond Rule" msgstr "Multiple Inheritance: The Diamond Rule" -#: ../../whatsnew/2.2.rst:246 +#: ../../whatsnew/2.2.rst:247 msgid "" "Multiple inheritance has also been made more useful through changing the " "rules under which names are resolved. Consider this set of classes (diagram " @@ -461,7 +557,37 @@ msgstr "" "rules under which names are resolved. Consider this set of classes (diagram " "taken from :pep:`253` by Guido van Rossum)::" -#: ../../whatsnew/2.2.rst:264 +#: ../../whatsnew/2.2.rst:251 +msgid "" +" class A:\n" +" ^ ^ def save(self): ...\n" +" / \\\n" +" / \\\n" +" / \\\n" +" / \\\n" +"class B class C:\n" +" ^ ^ def save(self): ...\n" +" \\ /\n" +" \\ /\n" +" \\ /\n" +" \\ /\n" +" class D" +msgstr "" +" class A:\n" +" ^ ^ def save(self): ...\n" +" / \\\n" +" / \\\n" +" / \\\n" +" / \\\n" +"class B class C:\n" +" ^ ^ def save(self): ...\n" +" \\ /\n" +" \\ /\n" +" \\ /\n" +" \\ /\n" +" class D" + +#: ../../whatsnew/2.2.rst:265 msgid "" "The lookup rule for classic classes is simple but not very smart; the base " "classes are searched depth-first, going from left to right. A reference to :" @@ -479,7 +605,7 @@ msgstr "" "meth:`!save` method is saving some internal state specific to :class:`!C`, " "not calling it will result in that state never getting saved." -#: ../../whatsnew/2.2.rst:272 +#: ../../whatsnew/2.2.rst:273 msgid "" "New-style classes follow a different algorithm that's a bit more complicated " "to explain, but does the right thing in this situation. (Note that Python " @@ -493,7 +619,7 @@ msgstr "" "cases, but produces more useful results for really complicated inheritance " "graphs.)" -#: ../../whatsnew/2.2.rst:277 +#: ../../whatsnew/2.2.rst:278 msgid "" "List all the base classes, following the classic lookup rule and include a " "class multiple times if it's visited repeatedly. In the above example, the " @@ -505,7 +631,7 @@ msgstr "" "list of visited classes is [:class:`!D`, :class:`!B`, :class:`!A`, :class:`!" "C`, :class:`!A`]." -#: ../../whatsnew/2.2.rst:282 +#: ../../whatsnew/2.2.rst:283 msgid "" "Scan the list for duplicated classes. If any are found, remove all but one " "occurrence, leaving the *last* one in the list. In the above example, the " @@ -517,7 +643,7 @@ msgstr "" "list becomes [:class:`!D`, :class:`!B`, :class:`!C`, :class:`!A`] after " "dropping duplicates." -#: ../../whatsnew/2.2.rst:287 +#: ../../whatsnew/2.2.rst:288 msgid "" "Following this rule, referring to :meth:`!D.save` will return :meth:`!C." "save`, which is the behaviour we're after. This lookup rule is the same as " @@ -539,7 +665,23 @@ msgstr "" "the superclass; for example, :class:`!D`'s :meth:`!save` method would look " "like this::" -#: ../../whatsnew/2.2.rst:303 +#: ../../whatsnew/2.2.rst:297 +msgid "" +"class D (B,C):\n" +" def save (self):\n" +" # Call superclass .save()\n" +" super(D, self).save()\n" +" # Save D's private information here\n" +" ..." +msgstr "" +"class D (B,C):\n" +" def save (self):\n" +" # Call superclass .save()\n" +" super(D, self).save()\n" +" # Save D's private information here\n" +" ..." + +#: ../../whatsnew/2.2.rst:304 msgid "" ":func:`super` can also return unbound superclass objects when called as " "``super(class)`` or ``super(class1, class2)``, but this probably won't often " @@ -549,11 +691,11 @@ msgstr "" "``super(class)`` or ``super(class1, class2)``, but this probably won't often " "be useful." -#: ../../whatsnew/2.2.rst:309 +#: ../../whatsnew/2.2.rst:310 msgid "Attribute Access" msgstr "Attribute Access" -#: ../../whatsnew/2.2.rst:311 +#: ../../whatsnew/2.2.rst:312 msgid "" "A fair number of sophisticated Python classes define hooks for attribute " "access using :meth:`~object.__getattr__`; most commonly this is done for " @@ -567,7 +709,7 @@ msgstr "" "attribute access such as ``obj.parent`` into a method call such as ``obj." "get_parent``. Python 2.2 adds some new ways of controlling attribute access." -#: ../../whatsnew/2.2.rst:317 +#: ../../whatsnew/2.2.rst:318 msgid "" "First, ``__getattr__(attr_name)`` is still supported by new-style classes, " "and nothing about it has changed. As before, it will be called when an " @@ -579,7 +721,7 @@ msgstr "" "attempt is made to access ``obj.foo`` and no attribute named ``foo`` is " "found in the instance's dictionary." -#: ../../whatsnew/2.2.rst:322 +#: ../../whatsnew/2.2.rst:323 msgid "" "New-style classes also support a new method, " "``__getattribute__(attr_name)``. The difference between the two methods is " @@ -593,7 +735,7 @@ msgstr "" "attribute is accessed, while the old :meth:`~object.__getattr__` is only " "called if ``foo`` isn't found in the instance's dictionary." -#: ../../whatsnew/2.2.rst:328 +#: ../../whatsnew/2.2.rst:329 msgid "" "However, Python 2.2's support for :dfn:`properties` will often be a simpler " "way to trap attribute references. Writing a :meth:`!__getattr__` method is " @@ -615,7 +757,7 @@ msgstr "" "this in mind. Finally, calling a function on every attribute access results " "in a sizable performance loss." -#: ../../whatsnew/2.2.rst:337 +#: ../../whatsnew/2.2.rst:338 msgid "" ":class:`property` is a new built-in type that packages up three functions " "that get, set, or delete an attribute, and a docstring. For example, if you " @@ -627,7 +769,39 @@ msgstr "" "want to define a :attr:`!size` attribute that's computed, but also settable, " "you could write::" -#: ../../whatsnew/2.2.rst:357 +#: ../../whatsnew/2.2.rst:343 +msgid "" +"class C(object):\n" +" def get_size (self):\n" +" result = ... computation ...\n" +" return result\n" +" def set_size (self, size):\n" +" ... compute something based on the size\n" +" and set internal state appropriately ...\n" +"\n" +" # Define a property. The 'delete this attribute'\n" +" # method is defined as None, so the attribute\n" +" # can't be deleted.\n" +" size = property(get_size, set_size,\n" +" None,\n" +" \"Storage size of this instance\")" +msgstr "" +"class C(object):\n" +" def get_size (self):\n" +" result = ... computation ...\n" +" return result\n" +" def set_size (self, size):\n" +" ... compute something based on the size\n" +" and set internal state appropriately ...\n" +"\n" +" # Define a property. The 'delete this attribute'\n" +" # method is defined as None, so the attribute\n" +" # can't be deleted.\n" +" size = property(get_size, set_size,\n" +" None,\n" +" \"Storage size of this instance\")" + +#: ../../whatsnew/2.2.rst:358 msgid "" "That is certainly clearer and easier to write than a pair of :meth:`!" "__getattr__`/:meth:`!__setattr__` methods that check for the :attr:`!size` " @@ -643,7 +817,7 @@ msgstr "" "the only ones which have to perform the work of calling a function, so " "references to other attributes run at their usual speed." -#: ../../whatsnew/2.2.rst:364 +#: ../../whatsnew/2.2.rst:365 msgid "" "Finally, it's possible to constrain the list of attributes that can be " "referenced on an object using the new :attr:`~object.__slots__` class " @@ -661,7 +835,37 @@ msgstr "" "`~object.__slots__` to limit the legal attributes to a particular set of " "names. An example will make this clear::" -#: ../../whatsnew/2.2.rst:385 +#: ../../whatsnew/2.2.rst:372 +msgid "" +">>> class C(object):\n" +"... __slots__ = ('template', 'name')\n" +"...\n" +">>> obj = C()\n" +">>> print obj.template\n" +"None\n" +">>> obj.template = 'Test'\n" +">>> print obj.template\n" +"Test\n" +">>> obj.newattr = None\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in ?\n" +"AttributeError: 'C' object has no attribute 'newattr'" +msgstr "" +">>> class C(object):\n" +"... __slots__ = ('template', 'name')\n" +"...\n" +">>> obj = C()\n" +">>> print obj.template\n" +"None\n" +">>> obj.template = 'Test'\n" +">>> print obj.template\n" +"Test\n" +">>> obj.newattr = None\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in ?\n" +"AttributeError: 'C' object has no attribute 'newattr'" + +#: ../../whatsnew/2.2.rst:386 msgid "" "Note how you get an :exc:`AttributeError` on the attempt to assign to an " "attribute not listed in :attr:`~object.__slots__`." @@ -669,11 +873,11 @@ msgstr "" "Note how you get an :exc:`AttributeError` on the attempt to assign to an " "attribute not listed in :attr:`~object.__slots__`." -#: ../../whatsnew/2.2.rst:392 +#: ../../whatsnew/2.2.rst:393 msgid "Related Links" msgstr "Related Links" -#: ../../whatsnew/2.2.rst:394 +#: ../../whatsnew/2.2.rst:395 msgid "" "This section has just been a quick overview of the new features, giving " "enough of an explanation to start you programming, but many details have " @@ -685,7 +889,7 @@ msgstr "" "been simplified or ignored. Where should you go to get a more complete " "picture?" -#: ../../whatsnew/2.2.rst:398 +#: ../../whatsnew/2.2.rst:399 msgid "" "The :ref:`descriptorhowto` is a lengthy tutorial introduction to the " "descriptor features, written by Guido van Rossum. If my description has " @@ -697,7 +901,7 @@ msgstr "" "whetted your appetite, go read this tutorial next, because it goes into much " "more detail about the new features while still remaining quite easy to read." -#: ../../whatsnew/2.2.rst:403 +#: ../../whatsnew/2.2.rst:404 msgid "" "Next, there are two relevant PEPs, :pep:`252` and :pep:`253`. :pep:`252` is " "titled \"Making Types Look More Like Classes\", and covers the descriptor " @@ -717,7 +921,7 @@ msgstr "" "explode. Both PEPs were written and implemented by Guido van Rossum, with " "substantial assistance from the rest of the Zope Corp. team." -#: ../../whatsnew/2.2.rst:412 +#: ../../whatsnew/2.2.rst:413 msgid "" "Finally, there's the ultimate authority: the source code. Most of the " "machinery for the type handling is in :file:`Objects/typeobject.c`, but you " @@ -729,11 +933,11 @@ msgstr "" "should only resort to it after all other avenues have been exhausted, " "including posting a question to python-list or python-dev." -#: ../../whatsnew/2.2.rst:421 +#: ../../whatsnew/2.2.rst:422 msgid "PEP 234: Iterators" msgstr "PEP 234: Iterators" -#: ../../whatsnew/2.2.rst:423 +#: ../../whatsnew/2.2.rst:424 msgid "" "Another significant addition to 2.2 is an iteration interface at both the C " "and Python levels. Objects can define how they can be looped over by " @@ -743,7 +947,7 @@ msgstr "" "and Python levels. Objects can define how they can be looped over by " "callers." -#: ../../whatsnew/2.2.rst:426 +#: ../../whatsnew/2.2.rst:427 msgid "" "In Python versions up to 2.1, the usual way to make ``for item in obj`` work " "is to define a :meth:`~object.__getitem__` method that looks something like " @@ -753,7 +957,15 @@ msgstr "" "is to define a :meth:`~object.__getitem__` method that looks something like " "this::" -#: ../../whatsnew/2.2.rst:432 +#: ../../whatsnew/2.2.rst:430 +msgid "" +"def __getitem__(self, index):\n" +" return " +msgstr "" +"def __getitem__(self, index):\n" +" return " + +#: ../../whatsnew/2.2.rst:433 msgid "" ":meth:`~object.__getitem__` is more properly used to define an indexing " "operation on an object so that you can write ``obj[5]`` to retrieve the " @@ -777,7 +989,7 @@ msgstr "" "using ``file[5]`` to randomly access the sixth element will work, though it " "really should." -#: ../../whatsnew/2.2.rst:442 +#: ../../whatsnew/2.2.rst:443 msgid "" "In Python 2.2, iteration can be implemented separately, and :meth:`~object." "__getitem__` methods can be limited to classes that really do support random " @@ -795,7 +1007,7 @@ msgstr "" "sentinel)`` returns an iterator that will invoke the callable object *C* " "until it returns *sentinel* to signal that the iterator is done." -#: ../../whatsnew/2.2.rst:450 +#: ../../whatsnew/2.2.rst:451 msgid "" "Python classes can define an :meth:`!__iter__` method, which should create " "and return a new iterator for the object; if the object is its own iterator, " @@ -813,7 +1025,7 @@ msgstr "" "extension types that want to behave as iterators can define a :c:member:" "`~PyTypeObject.tp_iternext` function." -#: ../../whatsnew/2.2.rst:457 +#: ../../whatsnew/2.2.rst:458 msgid "" "So, after all this, what do iterators actually do? They have one required " "method, :meth:`next`, which takes no arguments and returns the next value. " @@ -825,7 +1037,41 @@ msgstr "" "When there are no more values to be returned, calling :meth:`next` should " "raise the :exc:`StopIteration` exception. ::" -#: ../../whatsnew/2.2.rst:478 +#: ../../whatsnew/2.2.rst:463 +msgid "" +">>> L = [1,2,3]\n" +">>> i = iter(L)\n" +">>> print i\n" +"\n" +">>> i.next()\n" +"1\n" +">>> i.next()\n" +"2\n" +">>> i.next()\n" +"3\n" +">>> i.next()\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in ?\n" +"StopIteration\n" +">>>" +msgstr "" +">>> L = [1,2,3]\n" +">>> i = iter(L)\n" +">>> print i\n" +"\n" +">>> i.next()\n" +"1\n" +">>> i.next()\n" +"2\n" +">>> i.next()\n" +"3\n" +">>> i.next()\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in ?\n" +"StopIteration\n" +">>>" + +#: ../../whatsnew/2.2.rst:479 msgid "" "In 2.2, Python's :keyword:`for` statement no longer expects a sequence; it " "expects something for which :func:`iter` will return an iterator. For " @@ -845,7 +1091,21 @@ msgstr "" "changed to use the iterator protocol. This means you can do things like " "this::" -#: ../../whatsnew/2.2.rst:492 +#: ../../whatsnew/2.2.rst:487 +msgid "" +">>> L = [1,2,3]\n" +">>> i = iter(L)\n" +">>> a,b,c = i\n" +">>> a,b,c\n" +"(1, 2, 3)" +msgstr "" +">>> L = [1,2,3]\n" +">>> i = iter(L)\n" +">>> a,b,c = i\n" +">>> a,b,c\n" +"(1, 2, 3)" + +#: ../../whatsnew/2.2.rst:493 msgid "" "Iterator support has been added to some of Python's basic types. Calling :" "func:`iter` on a dictionary will return an iterator which loops over its " @@ -855,7 +1115,43 @@ msgstr "" "func:`iter` on a dictionary will return an iterator which loops over its " "keys::" -#: ../../whatsnew/2.2.rst:512 +#: ../../whatsnew/2.2.rst:496 +msgid "" +">>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,\n" +"... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}\n" +">>> for key in m: print key, m[key]\n" +"...\n" +"Mar 3\n" +"Feb 2\n" +"Aug 8\n" +"Sep 9\n" +"May 5\n" +"Jun 6\n" +"Jul 7\n" +"Jan 1\n" +"Apr 4\n" +"Nov 11\n" +"Dec 12\n" +"Oct 10" +msgstr "" +">>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,\n" +"... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}\n" +">>> for key in m: print key, m[key]\n" +"...\n" +"Mar 3\n" +"Feb 2\n" +"Aug 8\n" +"Sep 9\n" +"May 5\n" +"Jun 6\n" +"Jul 7\n" +"Jan 1\n" +"Apr 4\n" +"Nov 11\n" +"Dec 12\n" +"Oct 10" + +#: ../../whatsnew/2.2.rst:513 msgid "" "That's just the default behaviour. If you want to iterate over keys, " "values, or key/value pairs, you can explicitly call the :meth:`!iterkeys`, :" @@ -869,7 +1165,7 @@ msgstr "" "iterator. In a minor related change, the :keyword:`in` operator now works on " "dictionaries, so ``key in dict`` is now equivalent to ``dict.has_key(key)``." -#: ../../whatsnew/2.2.rst:518 +#: ../../whatsnew/2.2.rst:519 msgid "" "Files also provide an iterator, which calls the :meth:`readline` method " "until there are no more lines in the file. This means you can now read each " @@ -879,7 +1175,17 @@ msgstr "" "until there are no more lines in the file. This means you can now read each " "line of a file using code like this::" -#: ../../whatsnew/2.2.rst:526 +#: ../../whatsnew/2.2.rst:523 +msgid "" +"for line in file:\n" +" # do something for each line\n" +" ..." +msgstr "" +"for line in file:\n" +" # do something for each line\n" +" ..." + +#: ../../whatsnew/2.2.rst:527 msgid "" "Note that you can only go forward in an iterator; there's no way to get the " "previous element, reset the iterator, or make a copy of it. An iterator " @@ -891,11 +1197,11 @@ msgstr "" "object could provide such additional capabilities, but the iterator protocol " "only requires a :meth:`next` method." -#: ../../whatsnew/2.2.rst:534 +#: ../../whatsnew/2.2.rst:535 msgid ":pep:`234` - Iterators" msgstr ":pep:`234` - Iterators" -#: ../../whatsnew/2.2.rst:535 +#: ../../whatsnew/2.2.rst:536 msgid "" "Written by Ka-Ping Yee and GvR; implemented by the Python Labs crew, mostly " "by GvR and Tim Peters." @@ -903,11 +1209,11 @@ msgstr "" "Written by Ka-Ping Yee and GvR; implemented by the Python Labs crew, mostly " "by GvR and Tim Peters." -#: ../../whatsnew/2.2.rst:542 +#: ../../whatsnew/2.2.rst:543 msgid "PEP 255: Simple Generators" msgstr "PEP 255: Simple Generators" -#: ../../whatsnew/2.2.rst:544 +#: ../../whatsnew/2.2.rst:545 msgid "" "Generators are another new feature, one that interacts with the introduction " "of iterators." @@ -915,7 +1221,7 @@ msgstr "" "Generators are another new feature, one that interacts with the introduction " "of iterators." -#: ../../whatsnew/2.2.rst:547 +#: ../../whatsnew/2.2.rst:548 msgid "" "You're doubtless familiar with how function calls work in Python or C. When " "you call a function, it gets a private namespace where its local variables " @@ -937,11 +1243,21 @@ msgstr "" "This is what generators provide; they can be thought of as resumable " "functions." -#: ../../whatsnew/2.2.rst:556 +#: ../../whatsnew/2.2.rst:557 msgid "Here's the simplest example of a generator function::" msgstr "Here's the simplest example of a generator function::" -#: ../../whatsnew/2.2.rst:562 +#: ../../whatsnew/2.2.rst:559 +msgid "" +"def generate_ints(N):\n" +" for i in range(N):\n" +" yield i" +msgstr "" +"def generate_ints(N):\n" +" for i in range(N):\n" +" yield i" + +#: ../../whatsnew/2.2.rst:563 msgid "" "A new keyword, :keyword:`yield`, was introduced for generators. Any " "function containing a :keyword:`!yield` statement is a generator function; " @@ -959,7 +1275,7 @@ msgstr "" "import generators`` statement near the top of the module's source code. In " "Python 2.3 this statement will become unnecessary." -#: ../../whatsnew/2.2.rst:570 +#: ../../whatsnew/2.2.rst:571 msgid "" "When you call a generator function, it doesn't return a single value; " "instead it returns a generator object that supports the iterator protocol. " @@ -987,11 +1303,43 @@ msgstr "" "`try`...\\ :keyword:`finally` statement; read :pep:`255` for a full " "explanation of the interaction between :keyword:`!yield` and exceptions.)" -#: ../../whatsnew/2.2.rst:583 +#: ../../whatsnew/2.2.rst:584 msgid "Here's a sample usage of the :func:`!generate_ints` generator::" msgstr "Here's a sample usage of the :func:`!generate_ints` generator::" -#: ../../whatsnew/2.2.rst:600 +#: ../../whatsnew/2.2.rst:586 +msgid "" +">>> gen = generate_ints(3)\n" +">>> gen\n" +"\n" +">>> gen.next()\n" +"0\n" +">>> gen.next()\n" +"1\n" +">>> gen.next()\n" +"2\n" +">>> gen.next()\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in ?\n" +" File \"\", line 2, in generate_ints\n" +"StopIteration" +msgstr "" +">>> gen = generate_ints(3)\n" +">>> gen\n" +"\n" +">>> gen.next()\n" +"0\n" +">>> gen.next()\n" +"1\n" +">>> gen.next()\n" +"2\n" +">>> gen.next()\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in ?\n" +" File \"\", line 2, in generate_ints\n" +"StopIteration" + +#: ../../whatsnew/2.2.rst:601 msgid "" "You could equally write ``for i in generate_ints(5)``, or ``a,b,c = " "generate_ints(3)``." @@ -999,7 +1347,7 @@ msgstr "" "You could equally write ``for i in generate_ints(5)``, or ``a,b,c = " "generate_ints(3)``." -#: ../../whatsnew/2.2.rst:603 +#: ../../whatsnew/2.2.rst:604 msgid "" "Inside a generator function, the :keyword:`return` statement can only be " "used without a value, and signals the end of the procession of values; " @@ -1017,7 +1365,7 @@ msgstr "" "indicated by raising :exc:`StopIteration` manually, or by just letting the " "flow of execution fall off the bottom of the function." -#: ../../whatsnew/2.2.rst:611 +#: ../../whatsnew/2.2.rst:612 msgid "" "You could achieve the effect of generators manually by writing your own " "class and storing all the local variables of the generator as instance " @@ -1039,7 +1387,27 @@ msgstr "" "The simplest one implements an in-order traversal of a tree using generators " "recursively. ::" -#: ../../whatsnew/2.2.rst:629 +#: ../../whatsnew/2.2.rst:621 +msgid "" +"# A recursive generator that generates Tree leaves in in-order.\n" +"def inorder(t):\n" +" if t:\n" +" for x in inorder(t.left):\n" +" yield x\n" +" yield t.label\n" +" for x in inorder(t.right):\n" +" yield x" +msgstr "" +"# A recursive generator that generates Tree leaves in in-order.\n" +"def inorder(t):\n" +" if t:\n" +" for x in inorder(t.left):\n" +" yield x\n" +" yield t.label\n" +" for x in inorder(t.right):\n" +" yield x" + +#: ../../whatsnew/2.2.rst:630 msgid "" "Two other examples in :file:`Lib/test/test_generators.py` produce solutions " "for the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that " @@ -1053,7 +1421,7 @@ msgstr "" "knight to every square of an $NxN$ chessboard without visiting any square " "twice)." -#: ../../whatsnew/2.2.rst:634 +#: ../../whatsnew/2.2.rst:635 msgid "" "The idea of generators comes from other programming languages, especially " "Icon (https://www2.cs.arizona.edu/icon/), where the idea of generators is " @@ -1069,7 +1437,15 @@ msgstr "" "Language\" at https://www2.cs.arizona.edu/icon/docs/ipd266.htm gives an idea " "of what this looks like::" -#: ../../whatsnew/2.2.rst:644 +#: ../../whatsnew/2.2.rst:642 +msgid "" +"sentence := \"Store it in the neighboring harbor\"\n" +"if (i := find(\"or\", sentence)) > 5 then write(i)" +msgstr "" +"sentence := \"Store it in the neighboring harbor\"\n" +"if (i := find(\"or\", sentence)) > 5 then write(i)" + +#: ../../whatsnew/2.2.rst:645 msgid "" "In Icon the :func:`!find` function returns the indexes at which the " "substring \"or\" is found: 3, 23, 33. In the :keyword:`if` statement, ``i`` " @@ -1085,7 +1461,7 @@ msgstr "" "5, so the comparison now succeeds, and the code prints the value 23 to the " "screen." -#: ../../whatsnew/2.2.rst:650 +#: ../../whatsnew/2.2.rst:651 msgid "" "Python doesn't go nearly as far as Icon in adopting generators as a central " "concept. Generators are considered a new part of the core Python language, " @@ -1103,11 +1479,11 @@ msgstr "" "represented as a concrete object (the iterator) that can be passed around to " "other functions or stored in a data structure." -#: ../../whatsnew/2.2.rst:661 +#: ../../whatsnew/2.2.rst:662 msgid ":pep:`255` - Simple Generators" msgstr ":pep:`255` - Simple Generators" -#: ../../whatsnew/2.2.rst:662 +#: ../../whatsnew/2.2.rst:663 msgid "" "Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland. Implemented " "mostly by Neil Schemenauer and Tim Peters, with other fixes from the Python " @@ -1117,11 +1493,11 @@ msgstr "" "mostly by Neil Schemenauer and Tim Peters, with other fixes from the Python " "Labs crew." -#: ../../whatsnew/2.2.rst:669 +#: ../../whatsnew/2.2.rst:670 msgid "PEP 237: Unifying Long Integers and Integers" msgstr "PEP 237: Unifying Long Integers and Integers" -#: ../../whatsnew/2.2.rst:671 +#: ../../whatsnew/2.2.rst:672 msgid "" "In recent versions, the distinction between regular integers, which are 32-" "bit values on most machines, and long integers, which can be of arbitrary " @@ -1143,7 +1519,7 @@ msgstr "" "be used as a slice index, and ``'abc'[1L:]`` would raise a :exc:`TypeError` " "exception with the message 'slice index must be int'." -#: ../../whatsnew/2.2.rst:681 +#: ../../whatsnew/2.2.rst:682 msgid "" "Python 2.2 will shift values from short to long integers as required. The " "'L' suffix is no longer needed to indicate a long integer literal, as now " @@ -1161,7 +1537,19 @@ msgstr "" "to raise an :exc:`OverflowError` will now return a long integer as their " "result. For example::" -#: ../../whatsnew/2.2.rst:694 +#: ../../whatsnew/2.2.rst:690 +msgid "" +">>> 1234567890123\n" +"1234567890123L\n" +">>> 2 ** 64\n" +"18446744073709551616L" +msgstr "" +">>> 1234567890123\n" +"1234567890123L\n" +">>> 2 ** 64\n" +"18446744073709551616L" + +#: ../../whatsnew/2.2.rst:695 msgid "" "In most cases, integers and long integers will now be treated identically. " "You can still distinguish them with the :func:`type` built-in function, but " @@ -1171,11 +1559,11 @@ msgstr "" "You can still distinguish them with the :func:`type` built-in function, but " "that's rarely needed." -#: ../../whatsnew/2.2.rst:701 +#: ../../whatsnew/2.2.rst:702 msgid ":pep:`237` - Unifying Long Integers and Integers" msgstr ":pep:`237` - Unifying Long Integers and Integers" -#: ../../whatsnew/2.2.rst:702 +#: ../../whatsnew/2.2.rst:703 msgid "" "Written by Moshe Zadka and Guido van Rossum. Implemented mostly by Guido " "van Rossum." @@ -1183,11 +1571,11 @@ msgstr "" "Written by Moshe Zadka and Guido van Rossum. Implemented mostly by Guido " "van Rossum." -#: ../../whatsnew/2.2.rst:709 +#: ../../whatsnew/2.2.rst:710 msgid "PEP 238: Changing the Division Operator" msgstr "PEP 238: Changing the Division Operator" -#: ../../whatsnew/2.2.rst:711 +#: ../../whatsnew/2.2.rst:712 msgid "" "The most controversial change in Python 2.2 heralds the start of an effort " "to fix an old design flaw that's been in Python from the beginning. " @@ -1209,7 +1597,7 @@ msgstr "" "the two operands and because Python is dynamically typed, it can be " "difficult to determine the possible types of the operands." -#: ../../whatsnew/2.2.rst:721 +#: ../../whatsnew/2.2.rst:722 msgid "" "(The controversy is over whether this is *really* a design flaw, and whether " "it's worth breaking existing code to fix this. It's caused endless " @@ -1225,7 +1613,7 @@ msgstr "" "either side here and will stick to describing what's implemented in 2.2. " "Read :pep:`238` for a summary of arguments and counter-arguments.)" -#: ../../whatsnew/2.2.rst:728 +#: ../../whatsnew/2.2.rst:729 msgid "" "Because this change might break code, it's being introduced very gradually. " "Python 2.2 begins the transition, but the switch won't be complete until " @@ -1235,7 +1623,7 @@ msgstr "" "Python 2.2 begins the transition, but the switch won't be complete until " "Python 3.0." -#: ../../whatsnew/2.2.rst:732 +#: ../../whatsnew/2.2.rst:733 msgid "" "First, I'll borrow some terminology from :pep:`238`. \"True division\" is " "the division that most non-programmers are familiar with: 3/2 is 1.5, 1/4 is " @@ -1255,11 +1643,11 @@ msgstr "" "operands are integers, and returns the result of true division when one of " "the operands is a floating-point number." -#: ../../whatsnew/2.2.rst:740 +#: ../../whatsnew/2.2.rst:741 msgid "Here are the changes 2.2 introduces:" msgstr "Here are the changes 2.2 introduces:" -#: ../../whatsnew/2.2.rst:742 +#: ../../whatsnew/2.2.rst:743 msgid "" "A new operator, ``//``, is the floor division operator. (Yes, we know it " "looks like C++'s comment symbol.) ``//`` *always* performs floor division " @@ -1271,7 +1659,7 @@ msgstr "" "no matter what the types of its operands are, so ``1 // 2`` is 0 and " "``1.0 // 2.0`` is also 0.0." -#: ../../whatsnew/2.2.rst:747 +#: ../../whatsnew/2.2.rst:748 msgid "" "``//`` is always available in Python 2.2; you don't need to enable it using " "a ``__future__`` statement." @@ -1279,7 +1667,7 @@ msgstr "" "``//`` is always available in Python 2.2; you don't need to enable it using " "a ``__future__`` statement." -#: ../../whatsnew/2.2.rst:750 +#: ../../whatsnew/2.2.rst:751 msgid "" "By including a ``from __future__ import division`` in a module, the ``/`` " "operator will be changed to return the result of true division, so ``1/2`` " @@ -1291,7 +1679,7 @@ msgstr "" "is 0.5. Without the ``__future__`` statement, ``/`` still means classic " "division. The default meaning of ``/`` will not change until Python 3.0." -#: ../../whatsnew/2.2.rst:755 +#: ../../whatsnew/2.2.rst:756 msgid "" "Classes can define methods called :meth:`~object.__truediv__` and :meth:" "`~object.__floordiv__` to overload the two division operators. At the C " @@ -1303,7 +1691,7 @@ msgstr "" "level, there are also slots in the :c:type:`PyNumberMethods` structure so " "extension types can define the two operators." -#: ../../whatsnew/2.2.rst:760 +#: ../../whatsnew/2.2.rst:761 msgid "" "Python 2.2 supports some command-line arguments for testing whether code " "will work with the changed division semantics. Running python with :option:" @@ -1319,11 +1707,11 @@ msgstr "" "and fix it. By default, Python 2.2 will simply perform classic division " "without a warning; the warning will be turned on by default in Python 2.3." -#: ../../whatsnew/2.2.rst:770 +#: ../../whatsnew/2.2.rst:771 msgid ":pep:`238` - Changing the Division Operator" msgstr ":pep:`238` - Changing the Division Operator" -#: ../../whatsnew/2.2.rst:771 +#: ../../whatsnew/2.2.rst:772 msgid "" "Written by Moshe Zadka and Guido van Rossum. Implemented by Guido van " "Rossum.." @@ -1331,11 +1719,11 @@ msgstr "" "Written by Moshe Zadka and Guido van Rossum. Implemented by Guido van " "Rossum.." -#: ../../whatsnew/2.2.rst:777 +#: ../../whatsnew/2.2.rst:778 msgid "Unicode Changes" msgstr "Unicode Changes" -#: ../../whatsnew/2.2.rst:779 +#: ../../whatsnew/2.2.rst:780 msgid "" "Python's Unicode support has been enhanced a bit in 2.2. Unicode strings " "are usually stored as UCS-2, as 16-bit unsigned integers. Python 2.2 can " @@ -1351,7 +1739,7 @@ msgstr "" "script. (It's also possible to specify :option:`!--disable-unicode` to " "completely disable Unicode support.)" -#: ../../whatsnew/2.2.rst:786 +#: ../../whatsnew/2.2.rst:787 msgid "" "When built to use UCS-4 (a \"wide Python\"), the interpreter can natively " "handle Unicode characters from U+000000 to U+110000, so the range of legal " @@ -1369,7 +1757,7 @@ msgstr "" "exception. This is all described in :pep:`261`, \"Support for 'wide' Unicode " "characters\"; consult it for further details." -#: ../../whatsnew/2.2.rst:794 +#: ../../whatsnew/2.2.rst:795 msgid "" "Another change is simpler to explain. Since their introduction, Unicode " "strings have supported an :meth:`!encode` method to convert the string to a " @@ -1387,7 +1775,7 @@ msgstr "" "the specified encoding and decodes it, returning whatever is returned by the " "codec." -#: ../../whatsnew/2.2.rst:801 +#: ../../whatsnew/2.2.rst:802 msgid "" "Using this new feature, codecs have been added for tasks not directly " "related to Unicode. For example, codecs have been added for uu-encoding, " @@ -1397,7 +1785,45 @@ msgstr "" "related to Unicode. For example, codecs have been added for uu-encoding, " "MIME's base64 encoding, and compression with the :mod:`zlib` module::" -#: ../../whatsnew/2.2.rst:822 +#: ../../whatsnew/2.2.rst:806 +msgid "" +">>> s = \"\"\"Here is a lengthy piece of redundant, overly verbose,\n" +"... and repetitive text.\n" +"... \"\"\"\n" +">>> data = s.encode('zlib')\n" +">>> data\n" +"'x\\x9c\\r\\xc9\\xc1\\r\\x80 \\x10\\x04\\xc0?Ul...'\n" +">>> data.decode('zlib')\n" +"'Here is a lengthy piece of redundant, overly verbose,\\nand repetitive text." +"\\n'\n" +">>> print s.encode('uu')\n" +"begin 666 \n" +"M2&5R92!I=F5R8F]S92P*86YD(')E<&5T:71I=F4@=&5X=\"X*\n" +"\n" +"end\n" +">>> \"sheesh\".encode('rot-13')\n" +"'furrfu'" +msgstr "" +">>> s = \"\"\"Here is a lengthy piece of redundant, overly verbose,\n" +"... and repetitive text.\n" +"... \"\"\"\n" +">>> data = s.encode('zlib')\n" +">>> data\n" +"'x\\x9c\\r\\xc9\\xc1\\r\\x80 \\x10\\x04\\xc0?Ul...'\n" +">>> data.decode('zlib')\n" +"'Here is a lengthy piece of redundant, overly verbose,\\nand repetitive text." +"\\n'\n" +">>> print s.encode('uu')\n" +"begin 666 \n" +"M2&5R92!I=F5R8F]S92P*86YD(')E<&5T:71I=F4@=&5X=\"X*\n" +"\n" +"end\n" +">>> \"sheesh\".encode('rot-13')\n" +"'furrfu'" + +#: ../../whatsnew/2.2.rst:823 msgid "" "To convert a class instance to Unicode, a :meth:`!__unicode__` method can be " "defined by a class, analogous to :meth:`!__str__`." @@ -1405,7 +1831,7 @@ msgstr "" "To convert a class instance to Unicode, a :meth:`!__unicode__` method can be " "defined by a class, analogous to :meth:`!__str__`." -#: ../../whatsnew/2.2.rst:825 +#: ../../whatsnew/2.2.rst:826 msgid "" ":meth:`!encode`, :meth:`!decode`, and :meth:`!__unicode__` were implemented " "by Marc-André Lemburg. The changes to support using UCS-4 internally were " @@ -1415,19 +1841,19 @@ msgstr "" "by Marc-André Lemburg. The changes to support using UCS-4 internally were " "implemented by Fredrik Lundh and Martin von Löwis." -#: ../../whatsnew/2.2.rst:832 +#: ../../whatsnew/2.2.rst:833 msgid ":pep:`261` - Support for 'wide' Unicode characters" msgstr ":pep:`261` - Support for 'wide' Unicode characters" -#: ../../whatsnew/2.2.rst:833 +#: ../../whatsnew/2.2.rst:834 msgid "Written by Paul Prescod." msgstr "Written by Paul Prescod." -#: ../../whatsnew/2.2.rst:839 +#: ../../whatsnew/2.2.rst:840 msgid "PEP 227: Nested Scopes" msgstr "PEP 227: Nested Scopes" -#: ../../whatsnew/2.2.rst:841 +#: ../../whatsnew/2.2.rst:842 msgid "" "In Python 2.1, statically nested scopes were added as an optional feature, " "to be enabled by a ``from __future__ import nested_scopes`` directive. In " @@ -1443,7 +1869,7 @@ msgstr "" "scopes from my \"What's New in Python 2.1\" document; if you read it when " "2.1 came out, you can skip the rest of this section." -#: ../../whatsnew/2.2.rst:848 +#: ../../whatsnew/2.2.rst:849 msgid "" "The largest change introduced in Python 2.1, and made complete in 2.2, is to " "Python's scoping rules. In Python 2.0, at any given time there are at most " @@ -1459,7 +1885,23 @@ msgstr "" "their intuitive expectations. For example, a nested recursive function " "definition doesn't work::" -#: ../../whatsnew/2.2.rst:862 +#: ../../whatsnew/2.2.rst:856 +msgid "" +"def f():\n" +" ...\n" +" def g(value):\n" +" ...\n" +" return g(value-1) + 1\n" +" ..." +msgstr "" +"def f():\n" +" ...\n" +" def g(value):\n" +" ...\n" +" return g(value-1) + 1\n" +" ..." + +#: ../../whatsnew/2.2.rst:863 msgid "" "The function :func:`!g` will always raise a :exc:`NameError` exception, " "because the binding of the name ``g`` isn't in either its local namespace or " @@ -1479,7 +1921,21 @@ msgstr "" "find local variables being copied by passing them as the default values of " "arguments. ::" -#: ../../whatsnew/2.2.rst:876 +#: ../../whatsnew/2.2.rst:871 +msgid "" +"def find(self, name):\n" +" \"Return list of any entries equal to 'name'\"\n" +" L = filter(lambda x, name=name: x == name,\n" +" self.list_attribute)\n" +" return L" +msgstr "" +"def find(self, name):\n" +" \"Return list of any entries equal to 'name'\"\n" +" L = filter(lambda x, name=name: x == name,\n" +" self.list_attribute)\n" +" return L" + +#: ../../whatsnew/2.2.rst:877 msgid "" "The readability of Python code written in a strongly functional style " "suffers greatly as a result." @@ -1487,7 +1943,7 @@ msgstr "" "The readability of Python code written in a strongly functional style " "suffers greatly as a result." -#: ../../whatsnew/2.2.rst:879 +#: ../../whatsnew/2.2.rst:880 msgid "" "The most significant change to Python 2.2 is that static scoping has been " "added to the language to fix this problem. As a first effect, the " @@ -1507,7 +1963,7 @@ msgstr "" "local namespace of the enclosing scope. A more detailed explanation of the " "rules, and a dissection of the implementation, can be found in the PEP." -#: ../../whatsnew/2.2.rst:888 +#: ../../whatsnew/2.2.rst:889 msgid "" "This change may cause some compatibility problems for code where the same " "variable name is used both at the module level and as a local variable " @@ -1521,7 +1977,7 @@ msgstr "" "rather unlikely though, since such code would have been pretty confusing to " "read in the first place." -#: ../../whatsnew/2.2.rst:894 +#: ../../whatsnew/2.2.rst:895 msgid "" "One side effect of the change is that the ``from module import *`` and " "``exec`` statements have been made illegal inside a function scope under " @@ -1549,11 +2005,27 @@ msgstr "" "function definitions or :keyword:`lambda` expressions with free variables, " "the compiler will flag this by raising a :exc:`SyntaxError` exception." -#: ../../whatsnew/2.2.rst:907 +#: ../../whatsnew/2.2.rst:908 msgid "To make the preceding explanation a bit clearer, here's an example::" msgstr "To make the preceding explanation a bit clearer, here's an example::" -#: ../../whatsnew/2.2.rst:916 +#: ../../whatsnew/2.2.rst:910 +msgid "" +"x = 1\n" +"def f():\n" +" # The next line is a syntax error\n" +" exec 'x=2'\n" +" def g():\n" +" return x" +msgstr "" +"x = 1\n" +"def f():\n" +" # The next line is a syntax error\n" +" exec 'x=2'\n" +" def g():\n" +" return x" + +#: ../../whatsnew/2.2.rst:917 msgid "" "Line 4 containing the ``exec`` statement is a syntax error, since ``exec`` " "would define a new local variable named ``x`` whose value should be accessed " @@ -1563,7 +2035,7 @@ msgstr "" "would define a new local variable named ``x`` whose value should be accessed " "by :func:`!g`." -#: ../../whatsnew/2.2.rst:920 +#: ../../whatsnew/2.2.rst:921 msgid "" "This shouldn't be much of a limitation, since ``exec`` is rarely used in " "most Python code (and when it is used, it's often a sign of a poor design " @@ -1573,19 +2045,19 @@ msgstr "" "most Python code (and when it is used, it's often a sign of a poor design " "anyway)." -#: ../../whatsnew/2.2.rst:927 +#: ../../whatsnew/2.2.rst:928 msgid ":pep:`227` - Statically Nested Scopes" msgstr ":pep:`227` - Statically Nested Scopes" -#: ../../whatsnew/2.2.rst:928 +#: ../../whatsnew/2.2.rst:929 msgid "Written and implemented by Jeremy Hylton." msgstr "Written and implemented by Jeremy Hylton." -#: ../../whatsnew/2.2.rst:934 +#: ../../whatsnew/2.2.rst:935 msgid "New and Improved Modules" -msgstr "New and Improved Modules" +msgstr "Módulos Novos ou Aprimorados" -#: ../../whatsnew/2.2.rst:936 +#: ../../whatsnew/2.2.rst:937 msgid "" "The :mod:`xmlrpclib ` module was contributed to the standard " "library by Fredrik Lundh, providing support for writing XML-RPC clients. " @@ -1601,7 +2073,43 @@ msgstr "" "from the O'Reilly Network, and then lists the recent headlines for one " "channel::" -#: ../../whatsnew/2.2.rst:959 +#: ../../whatsnew/2.2.rst:943 +msgid "" +"import xmlrpclib\n" +"s = xmlrpclib.Server(\n" +" 'http://www.oreillynet.com/meerkat/xml-rpc/server.php')\n" +"channels = s.meerkat.getChannels()\n" +"# channels is a list of dictionaries, like this:\n" +"# [{'id': 4, 'title': 'Freshmeat Daily News'}\n" +"# {'id': 190, 'title': '32Bits Online'},\n" +"# {'id': 4549, 'title': '3DGamers'}, ... ]\n" +"\n" +"# Get the items for one channel\n" +"items = s.meerkat.getItems( {'channel': 4} )\n" +"\n" +"# 'items' is another list of dictionaries, like this:\n" +"# [{'link': 'http://freshmeat.net/releases/52719/',\n" +"# 'description': 'A utility which converts HTML to XSL FO.',\n" +"# 'title': 'html2fo 0.3 (Default)'}, ... ]" +msgstr "" +"import xmlrpclib\n" +"s = xmlrpclib.Server(\n" +" 'http://www.oreillynet.com/meerkat/xml-rpc/server.php')\n" +"channels = s.meerkat.getChannels()\n" +"# channels is a list of dictionaries, like this:\n" +"# [{'id': 4, 'title': 'Freshmeat Daily News'}\n" +"# {'id': 190, 'title': '32Bits Online'},\n" +"# {'id': 4549, 'title': '3DGamers'}, ... ]\n" +"\n" +"# Get the items for one channel\n" +"items = s.meerkat.getItems( {'channel': 4} )\n" +"\n" +"# 'items' is another list of dictionaries, like this:\n" +"# [{'link': 'http://freshmeat.net/releases/52719/',\n" +"# 'description': 'A utility which converts HTML to XSL FO.',\n" +"# 'title': 'html2fo 0.3 (Default)'}, ... ]" + +#: ../../whatsnew/2.2.rst:960 msgid "" "The :mod:`SimpleXMLRPCServer ` module makes it easy to create " "straightforward XML-RPC servers. See http://xmlrpc.scripting.com/ for more " @@ -1611,7 +2119,7 @@ msgstr "" "straightforward XML-RPC servers. See http://xmlrpc.scripting.com/ for more " "information about XML-RPC." -#: ../../whatsnew/2.2.rst:962 +#: ../../whatsnew/2.2.rst:963 msgid "" "The new :mod:`hmac` module implements the HMAC algorithm described by :rfc:" "`2104`. (Contributed by Gerhard Häring.)" @@ -1619,7 +2127,7 @@ msgstr "" "The new :mod:`hmac` module implements the HMAC algorithm described by :rfc:" "`2104`. (Contributed by Gerhard Häring.)" -#: ../../whatsnew/2.2.rst:965 +#: ../../whatsnew/2.2.rst:966 msgid "" "Several functions that originally returned lengthy tuples now return pseudo-" "sequences that still behave like tuples but also have mnemonic attributes " @@ -1637,7 +2145,7 @@ msgstr "" "localtime`, :func:`~time.gmtime`, and :func:`~time.strptime` in the :mod:" "`time` module." -#: ../../whatsnew/2.2.rst:972 +#: ../../whatsnew/2.2.rst:973 msgid "" "For example, to obtain a file's size using the old tuples, you'd end up " "writing something like ``file_size = os.stat(filename)[stat.ST_SIZE]``, but " @@ -1649,11 +2157,11 @@ msgstr "" "now this can be written more clearly as ``file_size = os.stat(filename)." "st_size``." -#: ../../whatsnew/2.2.rst:976 +#: ../../whatsnew/2.2.rst:977 msgid "The original patch for this feature was contributed by Nick Mathewson." msgstr "The original patch for this feature was contributed by Nick Mathewson." -#: ../../whatsnew/2.2.rst:978 +#: ../../whatsnew/2.2.rst:979 msgid "" "The Python profiler has been extensively reworked and various errors in its " "output have been corrected. (Contributed by Fred L. Drake, Jr. and Tim " @@ -1663,7 +2171,7 @@ msgstr "" "output have been corrected. (Contributed by Fred L. Drake, Jr. and Tim " "Peters.)" -#: ../../whatsnew/2.2.rst:981 +#: ../../whatsnew/2.2.rst:982 msgid "" "The :mod:`socket` module can be compiled to support IPv6; specify the :" "option:`!--enable-ipv6` option to Python's configure script. (Contributed " @@ -1673,7 +2181,7 @@ msgstr "" "option:`!--enable-ipv6` option to Python's configure script. (Contributed " "by Jun-ichiro \"itojun\" Hagino.)" -#: ../../whatsnew/2.2.rst:985 +#: ../../whatsnew/2.2.rst:986 msgid "" "Two new format characters were added to the :mod:`struct` module for 64-bit " "integers on platforms that support the C :c:expr:`long long` type. ``q`` is " @@ -1685,7 +2193,7 @@ msgstr "" "for a signed 64-bit integer, and ``Q`` is for an unsigned one. The value is " "returned in Python's long integer type. (Contributed by Tim Peters.)" -#: ../../whatsnew/2.2.rst:990 +#: ../../whatsnew/2.2.rst:991 msgid "" "In the interpreter's interactive mode, there's a new built-in function :func:" "`help` that uses the :mod:`pydoc` module introduced in Python 2.1 to provide " @@ -1703,7 +2211,7 @@ msgstr "" "their help text. (Contributed by Guido van Rossum, using Ka-Ping Yee's :mod:" "`pydoc` module.)" -#: ../../whatsnew/2.2.rst:998 +#: ../../whatsnew/2.2.rst:999 msgid "" "Various bugfixes and performance improvements have been made to the SRE " "engine underlying the :mod:`re` module. For example, the :func:`re.sub` " @@ -1721,7 +2229,7 @@ msgstr "" "all the non-overlapping matches in a given string. (SRE is maintained by " "Fredrik Lundh. The BIGCHARSET patch was contributed by Martin von Löwis.)" -#: ../../whatsnew/2.2.rst:1006 +#: ../../whatsnew/2.2.rst:1007 msgid "" "The :mod:`smtplib` module now supports :rfc:`2487`, \"Secure SMTP over " "TLS\", so it's now possible to encrypt the SMTP traffic between a Python " @@ -1733,7 +2241,7 @@ msgstr "" "program and the mail transport agent being handed a message. :mod:`smtplib` " "also supports SMTP authentication. (Contributed by Gerhard Häring.)" -#: ../../whatsnew/2.2.rst:1011 +#: ../../whatsnew/2.2.rst:1012 msgid "" "The :mod:`imaplib` module, maintained by Piers Lauder, has support for " "several new extensions: the NAMESPACE extension defined in :rfc:`2342`, " @@ -1745,7 +2253,7 @@ msgstr "" "SORT, GETACL and SETACL. (Contributed by Anthony Baxter and Michel " "Pelletier.)" -#: ../../whatsnew/2.2.rst:1015 +#: ../../whatsnew/2.2.rst:1016 msgid "" "The :mod:`!rfc822` module's parsing of email addresses is now compliant " "with :rfc:`2822`, an update to :rfc:`822`. (The module's name is *not* " @@ -1759,7 +2267,7 @@ msgstr "" "been added for parsing and generating e-mail messages. (Contributed by " "Barry Warsaw, and arising out of his work on Mailman.)" -#: ../../whatsnew/2.2.rst:1021 +#: ../../whatsnew/2.2.rst:1022 msgid "" "The :mod:`difflib` module now contains a new :class:`!Differ` class for " "producing human-readable lists of changes (a \"delta\") between two " @@ -1777,7 +2285,7 @@ msgstr "" "contributed by David Goodger, from ndiff.py code by Tim Peters who then did " "the generatorization.)" -#: ../../whatsnew/2.2.rst:1028 +#: ../../whatsnew/2.2.rst:1029 msgid "" "New constants :const:`!ascii_letters`, :const:`!ascii_lowercase`, and :const:" "`!ascii_uppercase` were added to the :mod:`string` module. There were " @@ -1797,7 +2305,7 @@ msgstr "" "been fixed to use :const:`!ascii_letters` instead. (Reported by an unknown " "person; fixed by Fred L. Drake, Jr.)" -#: ../../whatsnew/2.2.rst:1037 +#: ../../whatsnew/2.2.rst:1038 msgid "" "The :mod:`mimetypes` module now makes it easier to use alternative MIME-type " "databases by the addition of a :class:`~mimetypes.MimeTypes` class, which " @@ -1807,7 +2315,7 @@ msgstr "" "databases by the addition of a :class:`~mimetypes.MimeTypes` class, which " "takes a list of filenames to be parsed. (Contributed by Fred L. Drake, Jr.)" -#: ../../whatsnew/2.2.rst:1041 +#: ../../whatsnew/2.2.rst:1042 msgid "" "A :class:`~threading.Timer` class was added to the :mod:`threading` module " "that allows scheduling an activity to happen at some future time. " @@ -1817,11 +2325,11 @@ msgstr "" "that allows scheduling an activity to happen at some future time. " "(Contributed by Itamar Shtull-Trauring.)" -#: ../../whatsnew/2.2.rst:1049 +#: ../../whatsnew/2.2.rst:1050 msgid "Interpreter Changes and Fixes" msgstr "Interpreter Changes and Fixes" -#: ../../whatsnew/2.2.rst:1051 +#: ../../whatsnew/2.2.rst:1052 msgid "" "Some of the changes only affect people who deal with the Python interpreter " "at the C level because they're writing Python extension modules, embedding " @@ -1835,7 +2343,7 @@ msgstr "" "write Python code, none of the changes described here will affect you very " "much." -#: ../../whatsnew/2.2.rst:1056 +#: ../../whatsnew/2.2.rst:1057 msgid "" "Profiling and tracing functions can now be implemented in C, which can " "operate at much higher speeds than Python-based functions and should reduce " @@ -1855,7 +2363,7 @@ msgstr "" "exist, and have simply been changed to use the new C-level interface. " "(Contributed by Fred L. Drake, Jr.)" -#: ../../whatsnew/2.2.rst:1065 +#: ../../whatsnew/2.2.rst:1066 msgid "" "Another low-level API, primarily of interest to implementers of Python " "debuggers and development tools, was added. :c:func:" @@ -1873,7 +2381,7 @@ msgstr "" "looping over all the thread states for a given interpreter. (Contributed by " "David Beazley.)" -#: ../../whatsnew/2.2.rst:1072 +#: ../../whatsnew/2.2.rst:1073 msgid "" "The C-level interface to the garbage collector has been changed to make it " "easier to write extension types that support garbage collection and to debug " @@ -1891,27 +2399,27 @@ msgstr "" "collection, so updating them for 2.2 should be considered fairly high " "priority." -#: ../../whatsnew/2.2.rst:1079 +#: ../../whatsnew/2.2.rst:1080 msgid "" "To upgrade an extension module to the new API, perform the following steps:" msgstr "" "To upgrade an extension module to the new API, perform the following steps:" -#: ../../whatsnew/2.2.rst:1081 +#: ../../whatsnew/2.2.rst:1082 msgid "Rename :c:macro:`!Py_TPFLAGS_GC` to :c:macro:`Py_TPFLAGS_HAVE_GC`." msgstr "Rename :c:macro:`!Py_TPFLAGS_GC` to :c:macro:`Py_TPFLAGS_HAVE_GC`." -#: ../../whatsnew/2.2.rst:1083 +#: ../../whatsnew/2.2.rst:1084 msgid "" "Use :c:func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar` to allocate" msgstr "" "Use :c:func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar` to allocate" -#: ../../whatsnew/2.2.rst:1084 +#: ../../whatsnew/2.2.rst:1085 msgid "objects, and :c:func:`PyObject_GC_Del` to deallocate them." msgstr "objects, and :c:func:`PyObject_GC_Del` to deallocate them." -#: ../../whatsnew/2.2.rst:1086 +#: ../../whatsnew/2.2.rst:1087 msgid "" "Rename :c:func:`!PyObject_GC_Init` to :c:func:`PyObject_GC_Track` and :c:" "func:`!PyObject_GC_Fini` to :c:func:`PyObject_GC_UnTrack`." @@ -1919,17 +2427,17 @@ msgstr "" "Rename :c:func:`!PyObject_GC_Init` to :c:func:`PyObject_GC_Track` and :c:" "func:`!PyObject_GC_Fini` to :c:func:`PyObject_GC_UnTrack`." -#: ../../whatsnew/2.2.rst:1089 +#: ../../whatsnew/2.2.rst:1090 msgid "Remove :c:macro:`!PyGC_HEAD_SIZE` from object size calculations." msgstr "Remove :c:macro:`!PyGC_HEAD_SIZE` from object size calculations." -#: ../../whatsnew/2.2.rst:1091 +#: ../../whatsnew/2.2.rst:1092 msgid "" "Remove calls to :c:func:`!PyObject_AS_GC` and :c:func:`!PyObject_FROM_GC`." msgstr "" "Remove calls to :c:func:`!PyObject_AS_GC` and :c:func:`!PyObject_FROM_GC`." -#: ../../whatsnew/2.2.rst:1093 +#: ../../whatsnew/2.2.rst:1094 msgid "" "A new ``et`` format sequence was added to :c:func:`PyArg_ParseTuple`; ``et`` " "takes both a parameter and an encoding name, and converts the parameter to " @@ -1949,7 +2457,7 @@ msgstr "" "converts them to the specified new encoding. (Contributed by M.-A. Lemburg, " "and used for the MBCS support on Windows described in the following section.)" -#: ../../whatsnew/2.2.rst:1102 +#: ../../whatsnew/2.2.rst:1103 msgid "" "A different argument parsing function, :c:func:`PyArg_UnpackTuple`, has been " "added that's simpler and presumably faster. Instead of specifying a format " @@ -1963,7 +2471,7 @@ msgstr "" "expected, and a set of pointers to :c:expr:`PyObject*` variables that will " "be filled in with argument values." -#: ../../whatsnew/2.2.rst:1108 +#: ../../whatsnew/2.2.rst:1109 msgid "" "Two new flags :c:macro:`METH_NOARGS` and :c:macro:`METH_O` are available in " "method definition tables to simplify implementation of methods with no " @@ -1979,7 +2487,7 @@ msgstr "" "`METH_VARARGS`. Also, the old :c:macro:`!METH_OLDARGS` style of writing C " "methods is now officially deprecated." -#: ../../whatsnew/2.2.rst:1114 +#: ../../whatsnew/2.2.rst:1115 msgid "" "Two new wrapper functions, :c:func:`PyOS_snprintf` and :c:func:" "`PyOS_vsnprintf` were added to provide cross-platform implementations for " @@ -1995,7 +2503,7 @@ msgstr "" "functions, the Python versions check the bounds of the buffer used to " "protect against buffer overruns. (Contributed by M.-A. Lemburg.)" -#: ../../whatsnew/2.2.rst:1121 +#: ../../whatsnew/2.2.rst:1122 msgid "" "The :c:func:`_PyTuple_Resize` function has lost an unused parameter, so now " "it takes 2 parameters instead of 3. The third argument was never used, and " @@ -2007,11 +2515,11 @@ msgstr "" "can simply be discarded when porting code from earlier versions to Python " "2.2." -#: ../../whatsnew/2.2.rst:1129 +#: ../../whatsnew/2.2.rst:1130 msgid "Other Changes and Fixes" -msgstr "Other Changes and Fixes" +msgstr "Outras alterações e correções" -#: ../../whatsnew/2.2.rst:1131 +#: ../../whatsnew/2.2.rst:1132 msgid "" "As usual there were a bunch of other improvements and bugfixes scattered " "throughout the source tree. A search through the CVS change logs finds " @@ -2025,11 +2533,11 @@ msgstr "" "2.2; 2.2.1 applied 139 patches and fixed 143 bugs; 2.2.2 applied 106 patches " "and fixed 82 bugs. These figures are likely to be underestimates." -#: ../../whatsnew/2.2.rst:1137 +#: ../../whatsnew/2.2.rst:1138 msgid "Some of the more notable changes are:" msgstr "Some of the more notable changes are:" -#: ../../whatsnew/2.2.rst:1139 +#: ../../whatsnew/2.2.rst:1140 msgid "" "The code for the MacOS port for Python, maintained by Jack Jansen, is now " "kept in the main Python CVS tree, and many changes have been made to support " @@ -2039,7 +2547,7 @@ msgstr "" "kept in the main Python CVS tree, and many changes have been made to support " "MacOS X." -#: ../../whatsnew/2.2.rst:1142 +#: ../../whatsnew/2.2.rst:1143 msgid "" "The most significant change is the ability to build Python as a framework, " "enabled by supplying the :option:`!--enable-framework` option to the " @@ -2063,7 +2571,7 @@ msgstr "" "application, porting the MacPython IDE, possibly using Python as a standard " "OSA scripting language and much more.\"" -#: ../../whatsnew/2.2.rst:1153 +#: ../../whatsnew/2.2.rst:1154 msgid "" "Most of the MacPython toolbox modules, which interface to MacOS APIs such as " "windowing, QuickTime, scripting, etc. have been ported to OS X, but they've " @@ -2075,7 +2583,7 @@ msgstr "" "been left commented out in :file:`setup.py`. People who want to experiment " "with these modules can uncomment them manually." -#: ../../whatsnew/2.2.rst:1176 +#: ../../whatsnew/2.2.rst:1177 msgid "" "Keyword arguments passed to built-in functions that don't take them now " "cause a :exc:`TypeError` exception to be raised, with the message " @@ -2085,7 +2593,7 @@ msgstr "" "cause a :exc:`TypeError` exception to be raised, with the message " "\"*function* takes no keyword arguments\"." -#: ../../whatsnew/2.2.rst:1180 +#: ../../whatsnew/2.2.rst:1181 msgid "" "Weak references, added in Python 2.1 as an extension module, are now part of " "the core because they're used in the implementation of new-style classes. " @@ -2097,7 +2605,7 @@ msgstr "" "The :exc:`ReferenceError` exception has therefore moved from the :mod:" "`weakref` module to become a built-in exception." -#: ../../whatsnew/2.2.rst:1185 +#: ../../whatsnew/2.2.rst:1186 msgid "" "A new script, :file:`Tools/scripts/cleanfuture.py` by Tim Peters, " "automatically removes obsolete ``__future__`` statements from Python source " @@ -2107,7 +2615,7 @@ msgstr "" "automatically removes obsolete ``__future__`` statements from Python source " "code." -#: ../../whatsnew/2.2.rst:1189 +#: ../../whatsnew/2.2.rst:1190 msgid "" "An additional *flags* argument has been added to the built-in function :func:" "`compile`, so the behaviour of ``__future__`` statements can now be " @@ -2121,7 +2629,7 @@ msgstr "" "other development environments. This is described in :pep:`264`. " "(Contributed by Michael Hudson.)" -#: ../../whatsnew/2.2.rst:1195 +#: ../../whatsnew/2.2.rst:1196 msgid "" "The new license introduced with Python 1.6 wasn't GPL-compatible. This is " "fixed by some minor textual changes to the 2.2 license, so it's now legal to " @@ -2137,7 +2645,7 @@ msgstr "" "BSD license, same as it always was. The license changes were also applied " "to the Python 2.0.1 and 2.1.1 releases." -#: ../../whatsnew/2.2.rst:1202 +#: ../../whatsnew/2.2.rst:1203 msgid "" "When presented with a Unicode filename on Windows, Python will now convert " "it to an MBCS encoded string, as used by the Microsoft file APIs. As MBCS " @@ -2155,13 +2663,13 @@ msgstr "" "was contributed by Mark Hammond with assistance from Marc-André Lemburg. " "Unix support was added by Martin von Löwis.)" -#: ../../whatsnew/2.2.rst:1210 +#: ../../whatsnew/2.2.rst:1211 msgid "" "Large file support is now enabled on Windows. (Contributed by Tim Peters.)" msgstr "" "Large file support is now enabled on Windows. (Contributed by Tim Peters.)" -#: ../../whatsnew/2.2.rst:1212 +#: ../../whatsnew/2.2.rst:1213 msgid "" "The :file:`Tools/scripts/ftpmirror.py` script now parses a :file:`.netrc` " "file, if you have one. (Contributed by Mike Romberg.)" @@ -2169,7 +2677,7 @@ msgstr "" "The :file:`Tools/scripts/ftpmirror.py` script now parses a :file:`.netrc` " "file, if you have one. (Contributed by Mike Romberg.)" -#: ../../whatsnew/2.2.rst:1215 +#: ../../whatsnew/2.2.rst:1216 msgid "" "Some features of the object returned by the :func:`!xrange` function are now " "deprecated, and trigger warnings when they're accessed; they'll disappear in " @@ -2191,7 +2699,7 @@ msgstr "" "fourth argument to the :c:func:`!PyRange_New` function, ``repeat``, has also " "been deprecated." -#: ../../whatsnew/2.2.rst:1224 +#: ../../whatsnew/2.2.rst:1225 msgid "" "There were a bunch of patches to the dictionary implementation, mostly to " "fix potential core dumps if a dictionary contains objects that sneakily " @@ -2207,7 +2715,7 @@ msgstr "" "case that dumped core, Tim Peters fixing the bug, Michael finding another " "case, and round and round it went." -#: ../../whatsnew/2.2.rst:1231 +#: ../../whatsnew/2.2.rst:1232 msgid "" "On Windows, Python can now be compiled with Borland C thanks to a number of " "patches contributed by Stephen Hansen, though the result isn't fully " @@ -2217,7 +2725,7 @@ msgstr "" "patches contributed by Stephen Hansen, though the result isn't fully " "functional yet. (But this *is* progress...)" -#: ../../whatsnew/2.2.rst:1235 +#: ../../whatsnew/2.2.rst:1236 msgid "" "Another Windows enhancement: Wise Solutions generously offered PythonLabs " "use of their InstallerMaster 8.1 system. Earlier PythonLabs Windows " @@ -2229,7 +2737,7 @@ msgstr "" "installers used Wise 5.0a, which was beginning to show its age. (Packaged " "up by Tim Peters.)" -#: ../../whatsnew/2.2.rst:1239 +#: ../../whatsnew/2.2.rst:1240 msgid "" "Files ending in ``.pyw`` can now be imported on Windows. ``.pyw`` is a " "Windows-only thing, used to indicate that a script needs to be run using " @@ -2245,7 +2753,7 @@ msgstr "" "such scripts, in case they're also usable as modules. (Implemented by David " "Bolen.)" -#: ../../whatsnew/2.2.rst:1245 +#: ../../whatsnew/2.2.rst:1246 msgid "" "On platforms where Python uses the C :c:func:`dlopen` function to load " "extension modules, it's now possible to set the flags used by :c:func:" @@ -2257,7 +2765,7 @@ msgstr "" "`dlopen` using the :func:`sys.getdlopenflags` and :func:`sys.setdlopenflags` " "functions. (Contributed by Bram Stolk.)" -#: ../../whatsnew/2.2.rst:1250 +#: ../../whatsnew/2.2.rst:1251 msgid "" "The :func:`pow` built-in function no longer supports 3 arguments when " "floating-point numbers are supplied. ``pow(x, y, z)`` returns ``(x**y) % " @@ -2271,11 +2779,11 @@ msgstr "" "result varies unpredictably depending on the platform. A call such as " "``pow(2.0, 8.0, 7.0)`` will now raise a :exc:`TypeError` exception." -#: ../../whatsnew/2.2.rst:1260 +#: ../../whatsnew/2.2.rst:1261 msgid "Acknowledgements" -msgstr "Acknowledgements" +msgstr "Reconhecimentos" -#: ../../whatsnew/2.2.rst:1262 +#: ../../whatsnew/2.2.rst:1263 msgid "" "The author would like to thank the following people for offering " "suggestions, corrections and assistance with various drafts of this article: " diff --git a/whatsnew/2.3.po b/whatsnew/2.3.po index 8872c6898..b94fbd343 100644 --- a/whatsnew/2.3.po +++ b/whatsnew/2.3.po @@ -1,28 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Victor Matheus Castro , 2021 -# Rafael Fontenelle , 2023 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:51+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-02-07 14:17+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -122,6 +119,23 @@ msgstr "" msgid "Here's a simple example::" msgstr "Here's a simple example::" +#: ../../whatsnew/2.3.rst:52 +msgid "" +">>> import sets\n" +">>> S = sets.Set([1,2,3])\n" +">>> S\n" +"Set([1, 2, 3])\n" +">>> 1 in S\n" +"True\n" +">>> 0 in S\n" +"False\n" +">>> S.add(5)\n" +">>> S.remove(3)\n" +">>> S\n" +"Set([1, 2, 5])\n" +">>>" +msgstr "" + #: ../../whatsnew/2.3.rst:66 msgid "" "The union and intersection of sets can be computed with the :meth:" @@ -136,6 +150,24 @@ msgstr "" "sets also have in-place versions of these methods, :meth:`!union_update` " "and :meth:`~frozenset.intersection_update`. ::" +#: ../../whatsnew/2.3.rst:71 +msgid "" +">>> S1 = sets.Set([1,2,3])\n" +">>> S2 = sets.Set([4,5,6])\n" +">>> S1.union(S2)\n" +"Set([1, 2, 3, 4, 5, 6])\n" +">>> S1 | S2 # Alternative notation\n" +"Set([1, 2, 3, 4, 5, 6])\n" +">>> S1.intersection(S2)\n" +"Set([])\n" +">>> S1 & S2 # Alternative notation\n" +"Set([])\n" +">>> S1.union_update(S2)\n" +">>> S1\n" +"Set([1, 2, 3, 4, 5, 6])\n" +">>>" +msgstr "" + #: ../../whatsnew/2.3.rst:86 msgid "" "It's also possible to take the symmetric difference of two sets. This is " @@ -152,6 +184,17 @@ msgstr "" "notation (``^``), and an in-place version with the ungainly name :meth:" "`~frozenset.symmetric_difference_update`. ::" +#: ../../whatsnew/2.3.rst:92 +msgid "" +">>> S1 = sets.Set([1,2,3,4])\n" +">>> S2 = sets.Set([3,4,5,6])\n" +">>> S1.symmetric_difference(S2)\n" +"Set([1, 2, 5, 6])\n" +">>> S1 ^ S2\n" +"Set([1, 2, 5, 6])\n" +">>>" +msgstr "" + #: ../../whatsnew/2.3.rst:100 msgid "" "There are also :meth:`!issubset` and :meth:`!issuperset` methods for " @@ -160,6 +203,19 @@ msgstr "" "There are also :meth:`!issubset` and :meth:`!issuperset` methods for " "checking whether one set is a subset or superset of another::" +#: ../../whatsnew/2.3.rst:103 +msgid "" +">>> S1 = sets.Set([1,2,3])\n" +">>> S2 = sets.Set([2,3])\n" +">>> S2.issubset(S1)\n" +"True\n" +">>> S1.issubset(S2)\n" +"False\n" +">>> S1.issuperset(S2)\n" +"True\n" +">>>" +msgstr "" + #: ../../whatsnew/2.3.rst:116 msgid ":pep:`218` - Adding a Built-In Set Object Type" msgstr ":pep:`218` - Adding a Built-In Set Object Type" @@ -220,6 +276,16 @@ msgstr "" msgid "Here's the simplest example of a generator function::" msgstr "Here's the simplest example of a generator function::" +#: ../../whatsnew/2.3.rst:147 +msgid "" +"def generate_ints(N):\n" +" for i in range(N):\n" +" yield i" +msgstr "" +"def generate_ints(N):\n" +" for i in range(N):\n" +" yield i" + #: ../../whatsnew/2.3.rst:151 msgid "" "A new keyword, :keyword:`yield`, was introduced for generators. Any " @@ -264,6 +330,24 @@ msgstr "" msgid "Here's a sample usage of the :func:`!generate_ints` generator::" msgstr "Here's a sample usage of the :func:`!generate_ints` generator::" +#: ../../whatsnew/2.3.rst:171 +msgid "" +">>> gen = generate_ints(3)\n" +">>> gen\n" +"\n" +">>> gen.next()\n" +"0\n" +">>> gen.next()\n" +"1\n" +">>> gen.next()\n" +"2\n" +">>> gen.next()\n" +"Traceback (most recent call last):\n" +" File \"stdin\", line 1, in ?\n" +" File \"stdin\", line 2, in generate_ints\n" +"StopIteration" +msgstr "" + #: ../../whatsnew/2.3.rst:186 msgid "" "You could equally write ``for i in generate_ints(5)``, or ``a,b,c = " @@ -312,6 +396,26 @@ msgstr "" "The simplest one implements an in-order traversal of a tree using generators " "recursively. ::" +#: ../../whatsnew/2.3.rst:206 +msgid "" +"# A recursive generator that generates Tree leaves in in-order.\n" +"def inorder(t):\n" +" if t:\n" +" for x in inorder(t.left):\n" +" yield x\n" +" yield t.label\n" +" for x in inorder(t.right):\n" +" yield x" +msgstr "" +"# A recursive generator that generates Tree leaves in in-order.\n" +"def inorder(t):\n" +" if t:\n" +" for x in inorder(t.left):\n" +" yield x\n" +" yield t.label\n" +" for x in inorder(t.right):\n" +" yield x" + #: ../../whatsnew/2.3.rst:215 msgid "" "Two other examples in :file:`Lib/test/test_generators.py` produce solutions " @@ -342,6 +446,14 @@ msgstr "" "Language\" at https://www2.cs.arizona.edu/icon/docs/ipd266.htm gives an idea " "of what this looks like::" +#: ../../whatsnew/2.3.rst:227 +msgid "" +"sentence := \"Store it in the neighboring harbor\"\n" +"if (i := find(\"or\", sentence)) > 5 then write(i)" +msgstr "" +"sentence := \"Store it in the neighboring harbor\"\n" +"if (i := find(\"or\", sentence)) > 5 then write(i)" + #: ../../whatsnew/2.3.rst:230 msgid "" "In Icon the :func:`!find` function returns the indexes at which the " @@ -406,6 +518,12 @@ msgstr "" "comment in the first or second line of the source file. For example, a " "UTF-8 file can be declared with::" +#: ../../whatsnew/2.3.rst:264 +msgid "" +"#!/usr/bin/env python\n" +"# -*- coding: UTF-8 -*-" +msgstr "" + #: ../../whatsnew/2.3.rst:267 msgid "" "Without such an encoding declaration, the default encoding used is 7-bit " @@ -460,6 +578,26 @@ msgstr "" "be automatically imported if a ZIP archive's filename is added to ``sys." "path``. For example:" +#: ../../whatsnew/2.3.rst:296 +msgid "" +"amk@nyman:~/src/python$ unzip -l /tmp/example.zip\n" +"Archive: /tmp/example.zip\n" +" Length Date Time Name\n" +" -------- ---- ---- ----\n" +" 8467 11-26-02 22:30 jwzthreading.py\n" +" -------- -------\n" +" 8467 1 file\n" +"amk@nyman:~/src/python$ ./python\n" +"Python 2.3 (#1, Aug 1 2003, 19:54:32)\n" +">>> import sys\n" +">>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of " +"path\n" +">>> import jwzthreading\n" +">>> jwzthreading.__file__\n" +"'/tmp/example.zip/jwzthreading.py'\n" +">>>" +msgstr "" + #: ../../whatsnew/2.3.rst:314 msgid "" "An entry in ``sys.path`` can now be the filename of a ZIP archive. The ZIP " @@ -545,14 +683,9 @@ msgid "" "Other systems also allow Unicode strings as file names but convert them to " "byte strings before passing them to the system, which can cause a :exc:" "`UnicodeError` to be raised. Applications can test whether arbitrary Unicode " -"strings are supported as file names by checking :attr:`os.path." +"strings are supported as file names by checking :const:`os.path." "supports_unicode_filenames`, a Boolean value." msgstr "" -"Other systems also allow Unicode strings as file names but convert them to " -"byte strings before passing them to the system, which can cause a :exc:" -"`UnicodeError` to be raised. Applications can test whether arbitrary Unicode " -"strings are supported as file names by checking :attr:`os.path." -"supports_unicode_filenames`, a Boolean value." #: ../../whatsnew/2.3.rst:359 msgid "Under MacOS, :func:`os.listdir` may now return Unicode filenames." @@ -656,10 +789,25 @@ msgstr "" msgid "A common idiom to change every element of a list looks like this::" msgstr "A common idiom to change every element of a list looks like this::" +#: ../../whatsnew/2.3.rst:421 +msgid "" +"for i in range(len(L)):\n" +" item = L[i]\n" +" # ... compute some result based on item ...\n" +" L[i] = result" +msgstr "" + #: ../../whatsnew/2.3.rst:426 msgid "This can be rewritten using :func:`enumerate` as::" msgstr "This can be rewritten using :func:`enumerate` as::" +#: ../../whatsnew/2.3.rst:428 +msgid "" +"for i, item in enumerate(L):\n" +" # ... compute some result based on item ...\n" +" L[i] = result" +msgstr "" + #: ../../whatsnew/2.3.rst:435 msgid ":pep:`279` - The enumerate() built-in function" msgstr ":pep:`279` - The enumerate() built-in function" @@ -726,10 +874,31 @@ msgstr "" "For simple uses, the :mod:`logging` package contains some convenience " "functions that always use the root log::" +#: ../../whatsnew/2.3.rst:467 +msgid "" +"import logging\n" +"\n" +"logging.debug('Debugging information')\n" +"logging.info('Informational message')\n" +"logging.warning('Warning:config file %s not found', 'server.conf')\n" +"logging.error('Error occurred')\n" +"logging.critical('Critical error -- shutting down')" +msgstr "" + #: ../../whatsnew/2.3.rst:475 ../../whatsnew/2.3.rst:500 msgid "This produces the following output::" msgstr "This produces the following output::" +#: ../../whatsnew/2.3.rst:477 +msgid "" +"WARNING:root:Warning:config file server.conf not found\n" +"ERROR:root:Error occurred\n" +"CRITICAL:root:Critical error -- shutting down" +msgstr "" +"WARNING:root:Alerta:arquivo de configuração server.conf não encontrado\n" +"ERROR:root:Ocorreu um erro\n" +"CRITICAL:root:Erro crítico -- shutting down" + #: ../../whatsnew/2.3.rst:481 msgid "" "In the default configuration, informational and debugging messages are " @@ -764,6 +933,24 @@ msgstr "" "recent traceback. Any of the other functions will also record the traceback " "if you specify a true value for the keyword argument *exc_info*. ::" +#: ../../whatsnew/2.3.rst:494 +msgid "" +"def f():\n" +" try: 1/0\n" +" except: logging.exception('Problem recorded')\n" +"\n" +"f()" +msgstr "" + +#: ../../whatsnew/2.3.rst:502 +msgid "" +"ERROR:root:Problem recorded\n" +"Traceback (most recent call last):\n" +" File \"t.py\", line 6, in f\n" +" 1/0\n" +"ZeroDivisionError: integer division or modulo by zero" +msgstr "" + #: ../../whatsnew/2.3.rst:508 msgid "" "Slightly more advanced programs will use a logger other than the root " @@ -776,6 +963,16 @@ msgstr "" "creating it if it doesn't exist yet. ``getLogger(None)`` returns the root " "logger. ::" +#: ../../whatsnew/2.3.rst:512 +msgid "" +"log = logging.getLogger('server')\n" +" ...\n" +"log.info('Listening on port %i', port)\n" +" ...\n" +"log.critical('Disk full')\n" +" ..." +msgstr "" + #: ../../whatsnew/2.3.rst:519 msgid "" "Log records are usually propagated up the hierarchy, so a message logged to " @@ -862,6 +1059,18 @@ msgstr "" "for it takes any Python value and converts it to :const:`True` or :const:" "`False`. ::" +#: ../../whatsnew/2.3.rst:561 +msgid "" +">>> bool(1)\n" +"True\n" +">>> bool(0)\n" +"False\n" +">>> bool([])\n" +"False\n" +">>> bool( (1,) )\n" +"True" +msgstr "" + #: ../../whatsnew/2.3.rst:570 msgid "" "Most of the standard library modules and built-in functions have been " @@ -870,6 +1079,17 @@ msgstr "" "Most of the standard library modules and built-in functions have been " "changed to return Booleans. ::" +#: ../../whatsnew/2.3.rst:573 +msgid "" +">>> obj = []\n" +">>> hasattr(obj, 'append')\n" +"True\n" +">>> isinstance(obj, list)\n" +"True\n" +">>> isinstance(obj, tuple)\n" +"False" +msgstr "" + #: ../../whatsnew/2.3.rst:581 msgid "" "Python's Booleans were added with the primary goal of making code clearer. " @@ -908,6 +1128,18 @@ msgstr "" "a subclass of the :class:`int` class so that arithmetic using a Boolean " "still works. ::" +#: ../../whatsnew/2.3.rst:596 +msgid "" +">>> True + 1\n" +"2\n" +">>> False + 1\n" +"1\n" +">>> False * 75\n" +"0\n" +">>> True * 75\n" +"75" +msgstr "" + #: ../../whatsnew/2.3.rst:605 msgid "" "To sum up :const:`True` and :const:`False` in a sentence: they're " @@ -1036,6 +1268,25 @@ msgstr "" "Here's an example :file:`setup.py` with classifiers, written to be " "compatible with older versions of the Distutils::" +#: ../../whatsnew/2.3.rst:672 +msgid "" +"from distutils import core\n" +"kw = {'name': \"Quixote\",\n" +" 'version': \"0.5.1\",\n" +" 'description': \"A highly Pythonic Web application framework\",\n" +" # ...\n" +" }\n" +"\n" +"if (hasattr(core, 'setup_keywords') and\n" +" 'classifiers' in core.setup_keywords):\n" +" kw['classifiers'] = \\\n" +" ['Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n" +" 'Environment :: No Input/Output (Daemon)',\n" +" 'Intended Audience :: Developers'],\n" +"\n" +"core.setup(**kw)" +msgstr "" + #: ../../whatsnew/2.3.rst:688 msgid "" "The full list of classifiers can be obtained by running ``python setup.py " @@ -1136,6 +1387,28 @@ msgstr "" "Pseudo-code for Python's new import logic, therefore, looks something like " "this (simplified a bit; see :pep:`302` for the full details)::" +#: ../../whatsnew/2.3.rst:738 +msgid "" +"for mp in sys.meta_path:\n" +" loader = mp(fullname)\n" +" if loader is not None:\n" +" = loader.load_module(fullname)\n" +"\n" +"for path in sys.path:\n" +" for hook in sys.path_hooks:\n" +" try:\n" +" importer = hook(path)\n" +" except ImportError:\n" +" # ImportError, so try the other path hooks\n" +" pass\n" +" else:\n" +" loader = importer.find_module(fullname)\n" +" = loader.load_module(fullname)\n" +"\n" +"# Not found!\n" +"raise ImportError" +msgstr "" + #: ../../whatsnew/2.3.rst:760 msgid ":pep:`302` - New Import Hooks" msgstr ":pep:`302` - New Import Hooks" @@ -1164,6 +1437,10 @@ msgstr "" msgid "Comma-separated format is deceptively simple at first glance::" msgstr "Comma-separated format is deceptively simple at first glance::" +#: ../../whatsnew/2.3.rst:776 +msgid "Costs,150,200,3.95" +msgstr "" + #: ../../whatsnew/2.3.rst:778 msgid "" "Read a line and call ``line.split(',')``: what could be simpler? But toss in " @@ -1172,6 +1449,10 @@ msgstr "" "Read a line and call ``line.split(',')``: what could be simpler? But toss in " "string data that can contain commas, and things get more complicated::" +#: ../../whatsnew/2.3.rst:781 +msgid "\"Costs\",150,200,3.95,\"Includes taxes, shipping, and sundry items\"" +msgstr "" + #: ../../whatsnew/2.3.rst:783 msgid "" "A big ugly regular expression can parse this, but using the new :mod:`csv` " @@ -1180,6 +1461,16 @@ msgstr "" "A big ugly regular expression can parse this, but using the new :mod:`csv` " "package is much simpler::" +#: ../../whatsnew/2.3.rst:786 +msgid "" +"import csv\n" +"\n" +"input = open('datafile', 'rb')\n" +"reader = csv.reader(input)\n" +"for line in reader:\n" +" print line" +msgstr "" + #: ../../whatsnew/2.3.rst:793 msgid "" "The :func:`~csv.reader` function takes a number of different options. The " @@ -1326,16 +1617,38 @@ msgstr "" "For example, you can now easily extract the elements of a list that have " "even indexes::" +#: ../../whatsnew/2.3.rst:871 +msgid "" +">>> L = range(10)\n" +">>> L[::2]\n" +"[0, 2, 4, 6, 8]" +msgstr "" + #: ../../whatsnew/2.3.rst:875 msgid "" "Negative values also work to make a copy of the same list in reverse order::" msgstr "" "Negative values also work to make a copy of the same list in reverse order::" +#: ../../whatsnew/2.3.rst:877 +msgid "" +">>> L[::-1]\n" +"[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]" +msgstr "" + #: ../../whatsnew/2.3.rst:880 msgid "This also works for tuples, arrays, and strings::" msgstr "This also works for tuples, arrays, and strings::" +#: ../../whatsnew/2.3.rst:882 +msgid "" +">>> s='abcd'\n" +">>> s[::2]\n" +"'ac'\n" +">>> s[::-1]\n" +"'dcba'" +msgstr "" + #: ../../whatsnew/2.3.rst:888 msgid "" "If you have a mutable sequence such as a list or an array you can assign to " @@ -1348,6 +1661,16 @@ msgstr "" "assignment to extended and regular slices. Assignment to a regular slice " "can be used to change the length of the sequence::" +#: ../../whatsnew/2.3.rst:893 +msgid "" +">>> a = range(3)\n" +">>> a\n" +"[0, 1, 2]\n" +">>> a[1:3] = [4, 5, 6]\n" +">>> a\n" +"[0, 4, 5, 6]" +msgstr "" + #: ../../whatsnew/2.3.rst:900 msgid "" "Extended slices aren't this flexible. When assigning to an extended slice, " @@ -1358,10 +1681,38 @@ msgstr "" "the list on the right hand side of the statement must contain the same " "number of items as the slice it is replacing::" +#: ../../whatsnew/2.3.rst:904 +msgid "" +">>> a = range(4)\n" +">>> a\n" +"[0, 1, 2, 3]\n" +">>> a[::2]\n" +"[0, 2]\n" +">>> a[::2] = [0, -1]\n" +">>> a\n" +"[0, 1, -1, 3]\n" +">>> a[::2] = [0,1,2]\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in ?\n" +"ValueError: attempt to assign sequence of size 3 to extended slice of size 2" +msgstr "" + #: ../../whatsnew/2.3.rst:917 msgid "Deletion is more straightforward::" msgstr "Deletion is more straightforward::" +#: ../../whatsnew/2.3.rst:919 +msgid "" +">>> a = range(4)\n" +">>> a\n" +"[0, 1, 2, 3]\n" +">>> a[::2]\n" +"[0, 2]\n" +">>> del a[::2]\n" +">>> a\n" +"[1, 3]" +msgstr "" + #: ../../whatsnew/2.3.rst:928 msgid "" "One can also now pass slice objects to the :meth:`~object.__getitem__` " @@ -1370,10 +1721,22 @@ msgstr "" "One can also now pass slice objects to the :meth:`~object.__getitem__` " "methods of the built-in sequences::" +#: ../../whatsnew/2.3.rst:931 +msgid "" +">>> range(10).__getitem__(slice(0, 5, 2))\n" +"[0, 2, 4]" +msgstr "" + #: ../../whatsnew/2.3.rst:934 msgid "Or use slice objects directly in subscripts::" msgstr "Or use slice objects directly in subscripts::" +#: ../../whatsnew/2.3.rst:936 +msgid "" +">>> range(10)[slice(0, 5, 2)]\n" +"[0, 2, 4]" +msgstr "" + #: ../../whatsnew/2.3.rst:939 msgid "" "To simplify implementing sequences that support extended slicing, slice " @@ -1392,6 +1755,20 @@ msgstr "" "innocuous phrase hides a welter of confusing details!). The method is " "intended to be used like this::" +#: ../../whatsnew/2.3.rst:946 +msgid "" +"class FakeSeq:\n" +" ...\n" +" def calc_item(self, i):\n" +" ...\n" +" def __getitem__(self, item):\n" +" if isinstance(item, slice):\n" +" indices = item.indices(len(self))\n" +" return FakeSeq([self.calc_item(i) for i in range(*indices)])\n" +" else:\n" +" return self.calc_item(i)" +msgstr "" + #: ../../whatsnew/2.3.rst:957 msgid "" "From this example you can also see that the built-in :class:`slice` object " @@ -1510,6 +1887,26 @@ msgstr "" "dictionary. If the requested key isn't present in the dictionary, *default* " "is returned if it's specified and :exc:`KeyError` raised if it isn't. ::" +#: ../../whatsnew/2.3.rst:1008 +msgid "" +">>> d = {1:2}\n" +">>> d\n" +"{1: 2}\n" +">>> d.pop(4)\n" +"Traceback (most recent call last):\n" +" File \"stdin\", line 1, in ?\n" +"KeyError: 4\n" +">>> d.pop(1)\n" +"2\n" +">>> d.pop(1)\n" +"Traceback (most recent call last):\n" +" File \"stdin\", line 1, in ?\n" +"KeyError: 'pop(): dictionary is empty'\n" +">>> d\n" +"{}\n" +">>>" +msgstr "" + #: ../../whatsnew/2.3.rst:1025 msgid "" "There's also a new class method, ``dict.fromkeys(iterable, value)``, that " @@ -1532,6 +1929,12 @@ msgstr "" "Also, the :func:`dict` constructor now accepts keyword arguments to simplify " "creating small dictionaries::" +#: ../../whatsnew/2.3.rst:1034 +msgid "" +">>> dict(red=1, blue=2, green=3, black=4)\n" +"{'blue': 2, 'black': 4, 'green': 3, 'red': 1}" +msgstr "" + #: ../../whatsnew/2.3.rst:1037 msgid "(Contributed by Just van Rossum.)" msgstr "(Contributed by Just van Rossum.)" @@ -1562,6 +1965,16 @@ msgstr "" "now use the type objects available in the :mod:`types` module.) For example, " "you can create a new module object with the following code:" +#: ../../whatsnew/2.3.rst:1052 +msgid "" +">>> import types\n" +">>> m = types.ModuleType('abc','docstring')\n" +">>> m\n" +"\n" +">>> m.__doc__\n" +"'docstring'" +msgstr "" + #: ../../whatsnew/2.3.rst:1059 msgid "" "A new warning, :exc:`PendingDeprecationWarning` was added to indicate " @@ -1672,25 +2085,32 @@ msgstr "" "``'.'`` in front of the type name. For example, in Python 2.2, if you " "created a socket and printed its :attr:`!__class__`, you'd get this output::" +#: ../../whatsnew/2.3.rst:1106 +msgid "" +">>> s = socket.socket()\n" +">>> s.__class__\n" +"" +msgstr "" + #: ../../whatsnew/2.3.rst:1110 msgid "In 2.3, you get this::" msgstr "In 2.3, you get this::" +#: ../../whatsnew/2.3.rst:1112 +msgid "" +">>> s.__class__\n" +"" +msgstr "" + #: ../../whatsnew/2.3.rst:1115 msgid "" "One of the noted incompatibilities between old- and new-style classes has " -"been removed: you can now assign to the :attr:`~definition.__name__` and :" -"attr:`~class.__bases__` attributes of new-style classes. There are some " -"restrictions on what can be assigned to :attr:`~class.__bases__` along the " -"lines of those relating to assigning to an instance's :attr:`~instance." -"__class__` attribute." +"been removed: you can now assign to the :attr:`~type.__name__` and :attr:" +"`~type.__bases__` attributes of new-style classes. There are some " +"restrictions on what can be assigned to :attr:`!__bases__` along the lines " +"of those relating to assigning to an instance's :attr:`~object.__class__` " +"attribute." msgstr "" -"One of the noted incompatibilities between old- and new-style classes has " -"been removed: you can now assign to the :attr:`~definition.__name__` and :" -"attr:`~class.__bases__` attributes of new-style classes. There are some " -"restrictions on what can be assigned to :attr:`~class.__bases__` along the " -"lines of those relating to assigning to an instance's :attr:`~instance." -"__class__` attribute." #: ../../whatsnew/2.3.rst:1125 msgid "String Changes" @@ -1710,6 +2130,16 @@ msgstr "" "and ``X in Y`` will return :const:`True` if *X* is a substring of *Y*. If " "*X* is the empty string, the result is always :const:`True`. ::" +#: ../../whatsnew/2.3.rst:1133 +msgid "" +">>> 'ab' in 'abcd'\n" +"True\n" +">>> 'ad' in 'abcd'\n" +"False\n" +">>> '' in 'abcd'\n" +"True" +msgstr "" + #: ../../whatsnew/2.3.rst:1140 msgid "" "Note that this doesn't tell you where the substring starts; if you need that " @@ -1728,6 +2158,19 @@ msgstr "" "methods now have an optional argument for specifying the characters to " "strip. The default is still to remove all whitespace characters::" +#: ../../whatsnew/2.3.rst:1147 +msgid "" +">>> ' abc '.strip()\n" +"'abc'\n" +">>> '><><><>'.strip('<>')\n" +"'abc'\n" +">>> '><><><>\\n'.strip('<>')\n" +"'abc<><><>\\n'\n" +">>> u'\\u4000\\u4001abc\\u4000'.strip(u'\\u4000')\n" +"u'\\u4001abc'\n" +">>>" +msgstr "" + #: ../../whatsnew/2.3.rst:1157 msgid "(Suggested by Simon Brunning and implemented by Walter Dörwald.)" msgstr "(Suggested by Simon Brunning and implemented by Walter Dörwald.)" @@ -1752,6 +2195,16 @@ msgstr "" "zeros on the left until it's the specified width. Note that the ``%`` " "operator is still more flexible and powerful than :meth:`~str.zfill`. ::" +#: ../../whatsnew/2.3.rst:1167 +msgid "" +">>> '45'.zfill(4)\n" +"'0045'\n" +">>> '12345'.zfill(4)\n" +"'12345'\n" +">>> 'goofy'.zfill(6)\n" +"'0goofy'" +msgstr "" + #: ../../whatsnew/2.3.rst:1174 msgid "(Contributed by Walter Dörwald.)" msgstr "(Contributed by Walter Dörwald.)" @@ -1954,6 +2407,13 @@ msgstr "" "includes the header file :file:`sample.h`, you would create the :class:`!" "Extension` object like this::" +#: ../../whatsnew/2.3.rst:1263 +msgid "" +"ext = Extension(\"samp\",\n" +" sources=[\"sampmodule.c\"],\n" +" depends=[\"sample.h\"])" +msgstr "" + #: ../../whatsnew/2.3.rst:1267 msgid "" "Modifying :file:`sample.h` would then cause the module to be recompiled. " @@ -2010,6 +2470,14 @@ msgstr "" "encountered, but in GNU-style mode processing continues, meaning that " "options and arguments can be mixed. For example::" +#: ../../whatsnew/2.3.rst:1289 +msgid "" +">>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')\n" +"([('-f', 'filename')], ['output', '-v'])\n" +">>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')\n" +"([('-f', 'filename'), ('-v', '')], ['output'])" +msgstr "" + #: ../../whatsnew/2.3.rst:1294 msgid "(Contributed by Peter Åstrand.)" msgstr "(Contributed by Peter Åstrand.)" @@ -2022,6 +2490,14 @@ msgstr "" "The :mod:`grp`, :mod:`pwd`, and :mod:`resource` modules now return enhanced " "tuples::" +#: ../../whatsnew/2.3.rst:1299 +msgid "" +">>> import grp\n" +">>> g = grp.getgrnam('amk')\n" +">>> g.gr_name, g.gr_gid\n" +"('amk', 500)" +msgstr "" + #: ../../whatsnew/2.3.rst:1304 msgid "The :mod:`gzip` module can now handle files exceeding 2 GiB." msgstr "The :mod:`gzip` module can now handle files exceeding 2 GiB." @@ -2058,6 +2534,23 @@ msgstr "" "property on top of some other mutable Python sequence type. Here's an " "example that uses a Python list::" +#: ../../whatsnew/2.3.rst:1318 +msgid "" +">>> import heapq\n" +">>> heap = []\n" +">>> for item in [3, 7, 5, 11, 1]:\n" +"... heapq.heappush(heap, item)\n" +"...\n" +">>> heap\n" +"[1, 3, 5, 11, 7]\n" +">>> heapq.heappop(heap)\n" +"1\n" +">>> heapq.heappop(heap)\n" +"3\n" +">>> heap\n" +"[5, 7, 11]" +msgstr "" + #: ../../whatsnew/2.3.rst:1332 msgid "(Contributed by Kevin O'Connor.)" msgstr "(Contributed by Kevin O'Connor.)" @@ -2164,6 +2657,15 @@ msgstr "" "stamps are still represented as integers, unless :func:`!os." "stat_float_times` is invoked to enable float return values::" +#: ../../whatsnew/2.3.rst:1376 +msgid "" +">>> os.stat(\"/tmp\").st_mtime\n" +"1034791200\n" +">>> os.stat_float_times(True)\n" +">>> os.stat(\"/tmp\").st_mtime\n" +"1034791200.6335014" +msgstr "" + #: ../../whatsnew/2.3.rst:1382 msgid "In Python 2.4, the default will change to always returning floats." msgstr "In Python 2.4, the default will change to always returning floats." @@ -2246,6 +2748,26 @@ msgstr "" "elements from the population without replacing chosen elements. *k* can be " "any value up to ``len(population)``. For example::" +#: ../../whatsnew/2.3.rst:1416 +msgid "" +">>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']\n" +">>> random.sample(days, 3) # Choose 3 elements\n" +"['St', 'Sn', 'Th']\n" +">>> random.sample(days, 7) # Choose 7 elements\n" +"['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']\n" +">>> random.sample(days, 7) # Choose 7 again\n" +"['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']\n" +">>> random.sample(days, 8) # Can't choose eight\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in ?\n" +" File \"random.py\", line 414, in sample\n" +" raise ValueError, \"sample larger than population\"\n" +"ValueError: sample larger than population\n" +">>> random.sample(xrange(1,10000,2), 10) # Choose ten odd nos. under " +"10000\n" +"[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]" +msgstr "" + #: ../../whatsnew/2.3.rst:1432 msgid "" "The :mod:`random` module now uses a new algorithm, the Mersenne Twister, " @@ -2394,6 +2916,24 @@ msgstr "" "you can guess, :func:`~textwrap.fill` is built on top of :func:`~textwrap." "wrap`. For example::" +#: ../../whatsnew/2.3.rst:1491 +msgid "" +">>> import textwrap\n" +">>> paragraph = \"Not a whit, we defy augury: ... more text ...\"\n" +">>> textwrap.wrap(paragraph, 60)\n" +"[\"Not a whit, we defy augury: there's a special providence in\",\n" +" \"the fall of a sparrow. If it be now, 'tis not to come; if it\",\n" +" ...]\n" +">>> print textwrap.fill(paragraph, 35)\n" +"Not a whit, we defy augury: there's\n" +"a special providence in the fall of\n" +"a sparrow. If it be now, 'tis not\n" +"to come; if it be not to come, it\n" +"will be now; if it be not now, yet\n" +"it will come: the readiness is all.\n" +">>>" +msgstr "" + #: ../../whatsnew/2.3.rst:1506 msgid "" "The module also contains a :class:`~textwrap.TextWrapper` class that " @@ -2426,6 +2966,14 @@ msgstr "" "modules (ones that *don't* rely on threads to run) by putting the following " "code at the top::" +#: ../../whatsnew/2.3.rst:1519 +msgid "" +"try:\n" +" import threading as _threading\n" +"except ImportError:\n" +" import dummy_threading as _threading" +msgstr "" + #: ../../whatsnew/2.3.rst:1524 msgid "" "In this example, :mod:`!_threading` is used as the module name to make it " @@ -2474,6 +3022,22 @@ msgstr "" "faster to convert an 8-bit string to Unicode by appending an empty Unicode " "string to it or by using the :func:`!unicode` function::" +#: ../../whatsnew/2.3.rst:1545 +msgid "" +"import timeit\n" +"\n" +"timer1 = timeit.Timer('unicode(\"abc\")')\n" +"timer2 = timeit.Timer('\"abc\" + u\"\"')\n" +"\n" +"# Run three trials\n" +"print timer1.repeat(repeat=3, number=100000)\n" +"print timer2.repeat(repeat=3, number=100000)\n" +"\n" +"# On my laptop this outputs:\n" +"# [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]\n" +"# [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]" +msgstr "" + #: ../../whatsnew/2.3.rst:1558 msgid "" "The :mod:`!Tix` module has received various bug fixes and updates for the " @@ -2546,6 +3110,12 @@ msgstr "" "setting the :attr:`!wantobjects` variable in the :mod:`!Tkinter` module to " "false before creating the first :class:`!tkapp` object. ::" +#: ../../whatsnew/2.3.rst:1587 +msgid "" +"import Tkinter\n" +"Tkinter.wantobjects = 0" +msgstr "" + #: ../../whatsnew/2.3.rst:1590 msgid "Any breakage caused by this change should be reported as a bug." msgstr "Any breakage caused by this change should be reported as a bug." @@ -2574,6 +3144,46 @@ msgstr "" "whenever the class defines :meth:`~object.__getitem__`, :meth:`~object." "__setitem__`, :meth:`~object.__delitem__`, and :meth:`!keys`. For example::" +#: ../../whatsnew/2.3.rst:1602 +msgid "" +">>> import UserDict\n" +">>> class SeqDict(UserDict.DictMixin):\n" +"... \"\"\"Dictionary lookalike implemented with lists.\"\"\"\n" +"... def __init__(self):\n" +"... self.keylist = []\n" +"... self.valuelist = []\n" +"... def __getitem__(self, key):\n" +"... try:\n" +"... i = self.keylist.index(key)\n" +"... except ValueError:\n" +"... raise KeyError\n" +"... return self.valuelist[i]\n" +"... def __setitem__(self, key, value):\n" +"... try:\n" +"... i = self.keylist.index(key)\n" +"... self.valuelist[i] = value\n" +"... except ValueError:\n" +"... self.keylist.append(key)\n" +"... self.valuelist.append(value)\n" +"... def __delitem__(self, key):\n" +"... try:\n" +"... i = self.keylist.index(key)\n" +"... except ValueError:\n" +"... raise KeyError\n" +"... self.keylist.pop(i)\n" +"... self.valuelist.pop(i)\n" +"... def keys(self):\n" +"... return list(self.keylist)\n" +"...\n" +">>> s = SeqDict()\n" +">>> dir(s) # See that other dictionary methods are implemented\n" +"['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',\n" +" '__init__', '__iter__', '__len__', '__module__', '__repr__',\n" +" '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',\n" +" 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',\n" +" 'setdefault', 'update', 'valuelist', 'values']" +msgstr "" + #: ../../whatsnew/2.3.rst:1639 msgid "(Contributed by Raymond Hettinger.)" msgstr "(Contributed by Raymond Hettinger.)" @@ -2628,6 +3238,12 @@ msgstr "" "has been added. The \"idna\" encoding can be used to convert between a " "Unicode domain name and the ASCII-compatible encoding (ACE) of that name. ::" +#: ../../whatsnew/2.3.rst:1661 +msgid "" +">{}>{}> u\"www.Alliancefrançaise.nu\".encode(\"idna\")\n" +"'www.xn--alliancefranaise-npb.nu'" +msgstr "" + #: ../../whatsnew/2.3.rst:1664 msgid "" "The :mod:`socket` module has also been extended to transparently convert " @@ -2708,6 +3324,18 @@ msgstr "" "Once created, instances of the date/time classes are all immutable. There " "are a number of methods for producing formatted strings from objects::" +#: ../../whatsnew/2.3.rst:1701 +msgid "" +">>> import datetime\n" +">>> now = datetime.datetime.now()\n" +">>> now.isoformat()\n" +"'2002-12-30T21:27:03.994956'\n" +">>> now.ctime() # Only available on date, datetime\n" +"'Mon Dec 30 21:27:03 2002'\n" +">>> now.strftime('%Y %d %b')\n" +"'2002 30 Dec'" +msgstr "" + #: ../../whatsnew/2.3.rst:1710 msgid "" "The :meth:`~datetime.datetime.replace` method allows modifying one or more " @@ -2718,6 +3346,16 @@ msgstr "" "fields of a :class:`~datetime.date` or :class:`~datetime.datetime` " "instance, returning a new instance::" +#: ../../whatsnew/2.3.rst:1713 +msgid "" +">>> d = datetime.datetime.now()\n" +">>> d\n" +"datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)\n" +">>> d.replace(year=2001, hour = 12)\n" +"datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)\n" +">>>" +msgstr "" + #: ../../whatsnew/2.3.rst:1720 msgid "" "Instances can be compared, hashed, and converted to strings (the result is " @@ -2770,6 +3408,20 @@ msgstr "" "You start by creating an instance of :class:`~optparse.OptionParser` and " "telling it what your program's options are. ::" +#: ../../whatsnew/2.3.rst:1745 +msgid "" +"import sys\n" +"from optparse import OptionParser\n" +"\n" +"op = OptionParser()\n" +"op.add_option('-i', '--input',\n" +" action='store', type='string', dest='input',\n" +" help='set input filename')\n" +"op.add_option('-l', '--length',\n" +" action='store', type='int', dest='length',\n" +" help='set maximum length of output')" +msgstr "" + #: ../../whatsnew/2.3.rst:1756 msgid "" "Parsing a command line is then done by calling the :meth:`~optparse." @@ -2778,6 +3430,13 @@ msgstr "" "Parsing a command line is then done by calling the :meth:`~optparse." "OptionParser.parse_args` method. ::" +#: ../../whatsnew/2.3.rst:1758 +msgid "" +"options, args = op.parse_args(sys.argv[1:])\n" +"print options\n" +"print args" +msgstr "" + #: ../../whatsnew/2.3.rst:1762 msgid "" "This returns an object containing all of the option values, and a list of " @@ -2794,10 +3453,35 @@ msgstr "" "Invoking the script with the various arguments now works as you'd expect it " "to. Note that the length argument is automatically converted to an integer." +#: ../../whatsnew/2.3.rst:1768 +msgid "" +"$ ./python opt.py -i data arg1\n" +"\n" +"['arg1']\n" +"$ ./python opt.py --input=data --length=4\n" +"\n" +"[]\n" +"$" +msgstr "" + #: ../../whatsnew/2.3.rst:1778 msgid "The help message is automatically generated for you:" msgstr "The help message is automatically generated for you:" +#: ../../whatsnew/2.3.rst:1780 +msgid "" +"$ ./python opt.py --help\n" +"usage: opt.py [options]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -iINPUT, --input=INPUT\n" +" set input filename\n" +" -lLENGTH, --length=LENGTH\n" +" set maximum length of output\n" +"$" +msgstr "" + #: ../../whatsnew/2.3.rst:1793 msgid "See the module's documentation for more details." msgstr "See the module's documentation for more details." @@ -2974,7 +3658,7 @@ msgstr "Mudanças a construções e API C" #: ../../whatsnew/2.3.rst:1878 msgid "Changes to Python's build process and to the C API include:" -msgstr "Changes to Python's build process and to the C API include:" +msgstr "As alterações no processo de construção do Python e na API C incluem:" #: ../../whatsnew/2.3.rst:1880 msgid "" @@ -3097,20 +3781,13 @@ msgstr "" #: ../../whatsnew/2.3.rst:1927 msgid "" "If you dynamically allocate type objects in your extension, you should be " -"aware of a change in the rules relating to the :attr:`!__module__` and :attr:" -"`~definition.__name__` attributes. In summary, you will want to ensure the " +"aware of a change in the rules relating to the :attr:`~type.__module__` and :" +"attr:`~type.__name__` attributes. In summary, you will want to ensure the " "type's dictionary contains a ``'__module__'`` key; making the module name " "the part of the type name leading up to the final period will no longer have " "the desired effect. For more detail, read the API reference documentation " "or the source." msgstr "" -"If you dynamically allocate type objects in your extension, you should be " -"aware of a change in the rules relating to the :attr:`!__module__` and :attr:" -"`~definition.__name__` attributes. In summary, you will want to ensure the " -"type's dictionary contains a ``'__module__'`` key; making the module name " -"the part of the type name leading up to the final period will no longer have " -"the desired effect. For more detail, read the API reference documentation " -"or the source." #: ../../whatsnew/2.3.rst:1938 msgid "Port-Specific Changes" @@ -3170,7 +3847,7 @@ msgstr "" #: ../../whatsnew/2.3.rst:1966 msgid "Other Changes and Fixes" -msgstr "Other Changes and Fixes" +msgstr "Outras alterações e correções" #: ../../whatsnew/2.3.rst:1968 msgid "" @@ -3378,6 +4055,16 @@ msgstr "" "new :func:`!get_distutil_options` function in your :file:`setup.py` and only " "uses the new keywords with a version of the Distutils that supports them::" +#: ../../whatsnew/2.3.rst:2058 +msgid "" +"from distutils import core\n" +"\n" +"kw = {'sources': 'foo.c', ...}\n" +"if hasattr(core, 'get_distutil_options'):\n" +" kw['depends'] = ['foo.h']\n" +"ext = Extension(**kw)" +msgstr "" + #: ../../whatsnew/2.3.rst:2065 msgid "" "Using ``None`` as a variable name will now result in a :exc:`SyntaxWarning` " diff --git a/whatsnew/2.4.po b/whatsnew/2.4.po index 4e55fdee7..f1da02e13 100644 --- a/whatsnew/2.4.po +++ b/whatsnew/2.4.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:51+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -104,6 +103,35 @@ msgstr "" "sequences, and for mathematical operations like unions, intersections, " "differences, and symmetric differences. ::" +#: ../../whatsnew/2.4.rst:45 +msgid "" +">>> a = set('abracadabra') # form a set from a string\n" +">>> 'z' in a # fast membership testing\n" +"False\n" +">>> a # unique letters in a\n" +"set(['a', 'r', 'b', 'c', 'd'])\n" +">>> ''.join(a) # convert back into a string\n" +"'arbcd'\n" +"\n" +">>> b = set('alacazam') # form a second set\n" +">>> a - b # letters in a but not in b\n" +"set(['r', 'd', 'b'])\n" +">>> a | b # letters in either a or b\n" +"set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])\n" +">>> a & b # letters in both a and b\n" +"set(['a', 'c'])\n" +">>> a ^ b # letters in a or b but not both\n" +"set(['r', 'd', 'b', 'm', 'z', 'l'])\n" +"\n" +">>> a.add('z') # add a new element\n" +">>> a.update('wxy') # add multiple new elements\n" +">>> a\n" +"set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])\n" +">>> a.remove('x') # take one element out\n" +">>> a\n" +"set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])" +msgstr "" + #: ../../whatsnew/2.4.rst:71 msgid "" "The :func:`frozenset` type is an immutable version of :func:`set`. Since it " @@ -204,10 +232,25 @@ msgstr "" "large. When trying to write a functionally styled program, it would be " "natural to write something like::" +#: ../../whatsnew/2.4.rst:125 +msgid "" +"links = [link for link in get_all_links() if not link.followed]\n" +"for link in links:\n" +" ..." +msgstr "" + #: ../../whatsnew/2.4.rst:129 msgid "instead of ::" msgstr "instead of ::" +#: ../../whatsnew/2.4.rst:131 +msgid "" +"for link in get_all_links():\n" +" if link.followed:\n" +" continue\n" +" ..." +msgstr "" + #: ../../whatsnew/2.4.rst:136 msgid "" "The first form is more concise and perhaps more readable, but if you're " @@ -228,6 +271,13 @@ msgstr "" "materialize the entire list; instead they create a generator that will " "return elements one by one. The above example could be written as::" +#: ../../whatsnew/2.4.rst:144 +msgid "" +"links = (link for link in get_all_links() if not link.followed)\n" +"for link in links:\n" +" ..." +msgstr "" + #: ../../whatsnew/2.4.rst:148 msgid "" "Generator expressions always have to be written inside parentheses, as in " @@ -240,6 +290,10 @@ msgstr "" "so if you want to create an iterator that will be immediately passed to a " "function you could write::" +#: ../../whatsnew/2.4.rst:153 +msgid "print sum(obj.count for obj in list_all_objects())" +msgstr "" + #: ../../whatsnew/2.4.rst:155 msgid "" "Generator expressions differ from list comprehensions in various small ways. " @@ -287,6 +341,12 @@ msgid "The usual way of substituting variables by name is the ``%`` operator::" msgstr "" "The usual way of substituting variables by name is the ``%`` operator::" +#: ../../whatsnew/2.4.rst:180 +msgid "" +">>> '%(page)i: %(title)s' % {'page':2, 'title': 'The Best of Times'}\n" +"'2: The Best of Times'" +msgstr "" + #: ../../whatsnew/2.4.rst:183 msgid "" "When writing the template string, it can be easy to forget the ``i`` or " @@ -317,6 +377,14 @@ msgstr "" "PEP 292 adds a :class:`Template` class to the :mod:`string` module that uses " "``$`` to indicate a substitution::" +#: ../../whatsnew/2.4.rst:195 +msgid "" +">>> import string\n" +">>> t = string.Template('$page: $title')\n" +">>> t.substitute({'page':2, 'title': 'The Best of Times'})\n" +"'2: The Best of Times'" +msgstr "" + #: ../../whatsnew/2.4.rst:200 msgid "" "If a key is missing from the dictionary, the :meth:`substitute` method will " @@ -327,6 +395,13 @@ msgstr "" "raise a :exc:`KeyError`. There's also a :meth:`safe_substitute` method that " "ignores missing keys::" +#: ../../whatsnew/2.4.rst:204 +msgid "" +">>> t = string.Template('$page: $title')\n" +">>> t.safe_substitute({'page':3})\n" +"'3: $title'" +msgstr "" + #: ../../whatsnew/2.4.rst:211 msgid ":pep:`292` - Simpler String Substitutions" msgstr ":pep:`292` - Simpler String Substitutions" @@ -355,6 +430,15 @@ msgstr "" "`staticmethod` or :func:`classmethod` function that would wrap up the " "function as a method of the new type. Your code would look like this::" +#: ../../whatsnew/2.4.rst:227 +msgid "" +"class C:\n" +" def meth (cls):\n" +" ...\n" +"\n" +" meth = classmethod(meth) # Rebind name to wrapped-up class method" +msgstr "" + #: ../../whatsnew/2.4.rst:233 msgid "" "If the method was very long, it would be easy to miss or forget the :func:" @@ -397,6 +481,15 @@ msgstr "" "The notation borrows from Java and uses the ``'@'`` character as an " "indicator. Using the new syntax, the example above would be written::" +#: ../../whatsnew/2.4.rst:249 +msgid "" +"class C:\n" +"\n" +" @classmethod\n" +" def meth (cls):\n" +" ..." +msgstr "" + #: ../../whatsnew/2.4.rst:256 msgid "" "The ``@classmethod`` is shorthand for the ``meth=classmethod(meth)`` " @@ -405,10 +498,25 @@ msgstr "" "The ``@classmethod`` is shorthand for the ``meth=classmethod(meth)`` " "assignment. More generally, if you have the following::" +#: ../../whatsnew/2.4.rst:259 +msgid "" +"@A\n" +"@B\n" +"@C\n" +"def f ():\n" +" ..." +msgstr "" + #: ../../whatsnew/2.4.rst:265 msgid "It's equivalent to the following pre-decorator code::" msgstr "It's equivalent to the following pre-decorator code::" +#: ../../whatsnew/2.4.rst:267 +msgid "" +"def f(): ...\n" +"f = A(B(C(f)))" +msgstr "" + #: ../../whatsnew/2.4.rst:270 msgid "" "Decorators must come on the line before a function definition, one decorator " @@ -439,6 +547,22 @@ msgstr "" "your own decorators. The following simple example just sets an attribute on " "the function object::" +#: ../../whatsnew/2.4.rst:282 +msgid "" +">>> def deco(func):\n" +"... func.attr = 'decorated'\n" +"... return func\n" +"...\n" +">>> @deco\n" +"... def f(): pass\n" +"...\n" +">>> f\n" +"\n" +">>> f.attr\n" +"'decorated'\n" +">>>" +msgstr "" + #: ../../whatsnew/2.4.rst:295 msgid "" "As a slightly more realistic example, the following decorator checks that " @@ -447,6 +571,24 @@ msgstr "" "As a slightly more realistic example, the following decorator checks that " "the supplied argument is an integer::" +#: ../../whatsnew/2.4.rst:298 +msgid "" +"def require_int (func):\n" +" def wrapper (arg):\n" +" assert isinstance(arg, int)\n" +" return func(arg)\n" +"\n" +" return wrapper\n" +"\n" +"@require_int\n" +"def p1 (arg):\n" +" print arg\n" +"\n" +"@require_int\n" +"def p2(arg):\n" +" print arg*2" +msgstr "" + #: ../../whatsnew/2.4.rst:313 msgid "" "An example in :pep:`318` contains a fancier version of this idea that lets " @@ -469,6 +611,13 @@ msgstr "" "function, as previously described. In other words, ``@A @B @C(args)`` " "becomes::" +#: ../../whatsnew/2.4.rst:321 +msgid "" +"def f(): ...\n" +"_deco = C(args)\n" +"f = A(B(_deco(f)))" +msgstr "" + #: ../../whatsnew/2.4.rst:325 msgid "" "Getting this right can be slightly brain-bending, but it's not too difficult." @@ -521,6 +670,16 @@ msgstr "" "A new built-in function, ``reversed(seq)``, takes a sequence and returns an " "iterator that loops over the elements of the sequence in reverse order. ::" +#: ../../whatsnew/2.4.rst:353 +msgid "" +">>> for i in reversed(xrange(1,4)):\n" +"... print i\n" +"...\n" +"3\n" +"2\n" +"1" +msgstr "" + #: ../../whatsnew/2.4.rst:360 msgid "" "Compared to extended slicing, such as ``range(1,4)[::-1]``, :func:`reversed` " @@ -539,6 +698,16 @@ msgstr "" "If you want to reverse an iterator, first convert it to a list with :func:" "`list`. ::" +#: ../../whatsnew/2.4.rst:367 +msgid "" +">>> input = open('/etc/passwd', 'r')\n" +">>> for line in reversed(list(input)):\n" +"... print line\n" +"...\n" +"root:*:0:0:System Administrator:/var/root:/bin/tcsh\n" +" ..." +msgstr "" + #: ../../whatsnew/2.4.rst:377 msgid ":pep:`322` - Reverse Iteration" msgstr ":pep:`322` - Reverse Iteration" @@ -581,6 +750,15 @@ msgstr "" "contains a single class called :class:`subprocess.Popen` whose constructor " "supports a number of different keyword arguments. ::" +#: ../../whatsnew/2.4.rst:399 +msgid "" +"class Popen(args, bufsize=0, executable=None,\n" +" stdin=None, stdout=None, stderr=None,\n" +" preexec_fn=None, close_fds=False, shell=False,\n" +" cwd=None, env=None, universal_newlines=False,\n" +" startupinfo=None, creationflags=0):" +msgstr "" + #: ../../whatsnew/2.4.rst:405 msgid "" "*args* is commonly a sequence of strings that will be the arguments to the " @@ -671,6 +849,17 @@ msgstr "" "status code of the subprocess. It can serve as a safer analog to :func:`os." "system`::" +#: ../../whatsnew/2.4.rst:444 +msgid "" +"sts = subprocess.call(['dpkg', '-i', '/tmp/new-package.deb'])\n" +"if sts == 0:\n" +" # Success\n" +" ...\n" +"else:\n" +" # dpkg returned an error\n" +" ..." +msgstr "" + #: ../../whatsnew/2.4.rst:452 msgid "" "The command is invoked without use of the shell. If you really do want to " @@ -681,6 +870,10 @@ msgstr "" "use the shell, you can add ``shell=True`` as a keyword argument and provide " "a string instead of a sequence::" +#: ../../whatsnew/2.4.rst:456 +msgid "sts = subprocess.call('dpkg -i /tmp/new-package.deb', shell=True)" +msgstr "" + #: ../../whatsnew/2.4.rst:458 msgid "" "The PEP takes various examples of shell and Python code and shows how they'd " @@ -801,6 +994,12 @@ msgstr "" msgid "Sometimes you can see this inaccuracy when the number is printed::" msgstr "Sometimes you can see this inaccuracy when the number is printed::" +#: ../../whatsnew/2.4.rst:518 +msgid "" +">>> 1.1\n" +"1.1000000000000001" +msgstr "" + #: ../../whatsnew/2.4.rst:521 msgid "" "The inaccuracy isn't always visible when you print the number because the FP-" @@ -867,6 +1066,15 @@ msgstr "" "represents. :class:`Decimal` instances can be created from integers or " "strings::" +#: ../../whatsnew/2.4.rst:550 +msgid "" +">>> import decimal\n" +">>> decimal.Decimal(1972)\n" +"Decimal(\"1972\")\n" +">>> decimal.Decimal(\"1.1\")\n" +"Decimal(\"1.1\")" +msgstr "" + #: ../../whatsnew/2.4.rst:556 msgid "" "You can also provide tuples containing the sign, the mantissa represented " @@ -875,6 +1083,12 @@ msgstr "" "You can also provide tuples containing the sign, the mantissa represented " "as a tuple of decimal digits, and the exponent::" +#: ../../whatsnew/2.4.rst:559 +msgid "" +">>> decimal.Decimal((1, (1, 4, 7, 5), -2))\n" +"Decimal(\"-14.75\")" +msgstr "" + #: ../../whatsnew/2.4.rst:562 msgid "" "Cautionary note: the sign bit is a Boolean value, so 0 is positive and 1 is " @@ -899,6 +1113,15 @@ msgstr "" "convert the floating-point number into a string using the desired precision " "and pass the string to the :class:`Decimal` constructor::" +#: ../../whatsnew/2.4.rst:572 +msgid "" +">>> f = 1.1\n" +">>> decimal.Decimal(str(f))\n" +"Decimal(\"1.1\")\n" +">>> decimal.Decimal('%.12f' % f)\n" +"Decimal(\"1.100000000000\")" +msgstr "" + #: ../../whatsnew/2.4.rst:578 msgid "" "Once you have :class:`Decimal` instances, you can perform the usual " @@ -909,6 +1132,26 @@ msgstr "" "mathematical operations on them. One limitation: exponentiation requires an " "integer exponent::" +#: ../../whatsnew/2.4.rst:582 +msgid "" +">>> a = decimal.Decimal('35.72')\n" +">>> b = decimal.Decimal('1.73')\n" +">>> a+b\n" +"Decimal(\"37.45\")\n" +">>> a-b\n" +"Decimal(\"33.99\")\n" +">>> a*b\n" +"Decimal(\"61.7956\")\n" +">>> a/b\n" +"Decimal(\"20.64739884393063583815028902\")\n" +">>> a ** 2\n" +"Decimal(\"1275.9184\")\n" +">>> a**b\n" +"Traceback (most recent call last):\n" +" ...\n" +"decimal.InvalidOperation: x ** (non-integer)" +msgstr "" + #: ../../whatsnew/2.4.rst:599 msgid "" "You can combine :class:`Decimal` instances with integers, but not with " @@ -917,6 +1160,18 @@ msgstr "" "You can combine :class:`Decimal` instances with integers, but not with " "floating-point numbers::" +#: ../../whatsnew/2.4.rst:602 +msgid "" +">>> a + 4\n" +"Decimal(\"39.72\")\n" +">>> a + 4.5\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: You can interact Decimal only with int, long or Decimal data " +"types.\n" +">>>" +msgstr "" + #: ../../whatsnew/2.4.rst:610 msgid "" ":class:`Decimal` numbers can be used with the :mod:`math` and :mod:`cmath` " @@ -931,6 +1186,16 @@ msgstr "" "precision and accuracy. You'll also get back a regular floating-point " "number and not a :class:`Decimal`. ::" +#: ../../whatsnew/2.4.rst:616 +msgid "" +">>> import math, cmath\n" +">>> d = decimal.Decimal('123456789012.345')\n" +">>> math.sqrt(d)\n" +"351364.18288201344\n" +">>> cmath.sqrt(-d)\n" +"351364.18288201344j" +msgstr "" + #: ../../whatsnew/2.4.rst:623 msgid "" ":class:`Decimal` instances have a :meth:`sqrt` method that returns a :class:" @@ -941,6 +1206,12 @@ msgstr "" "`Decimal`, but if you need other things such as trigonometric functions " "you'll have to implement them. ::" +#: ../../whatsnew/2.4.rst:627 +msgid "" +">>> d.sqrt()\n" +"Decimal(\"351364.1828820134592177245001\")" +msgstr "" + #: ../../whatsnew/2.4.rst:632 msgid "The :class:`Context` type" msgstr "The :class:`Context` type" @@ -991,6 +1262,17 @@ msgstr "" "default precision, rounding, or trap handling. The following example shows " "the effect of changing the precision of the default context::" +#: ../../whatsnew/2.4.rst:653 +msgid "" +">>> decimal.getcontext().prec\n" +"28\n" +">>> decimal.Decimal(1) / decimal.Decimal(7)\n" +"Decimal(\"0.1428571428571428571428571429\")\n" +">>> decimal.getcontext().prec = 9\n" +">>> decimal.Decimal(1) / decimal.Decimal(7)\n" +"Decimal(\"0.142857143\")" +msgstr "" + #: ../../whatsnew/2.4.rst:661 msgid "" "The default action for error conditions is selectable; the module can either " @@ -1001,6 +1283,18 @@ msgstr "" "return a special value such as infinity or not-a-number, or exceptions can " "be raised::" +#: ../../whatsnew/2.4.rst:665 +msgid "" +">>> decimal.Decimal(1) / decimal.Decimal(0)\n" +"Traceback (most recent call last):\n" +" ...\n" +"decimal.DivisionByZero: x / 0\n" +">>> decimal.getcontext().traps[decimal.DivisionByZero] = False\n" +">>> decimal.Decimal(1) / decimal.Decimal(0)\n" +"Decimal(\"Infinity\")\n" +">>>" +msgstr "" + #: ../../whatsnew/2.4.rst:674 msgid "" "The :class:`Context` instance also has various methods for formatting " @@ -1030,8 +1324,10 @@ msgstr "" "Raymond Hettinger, Aahz, and Tim Peters." #: ../../whatsnew/2.4.rst:687 -msgid "http://www.lahey.com/float.htm" -msgstr "http://www.lahey.com/float.htm" +msgid "" +"`http://www.lahey.com/float.htm `__" +msgstr "" #: ../../whatsnew/2.4.rst:688 msgid "" @@ -1042,8 +1338,8 @@ msgstr "" "floating-point inaccuracy can cause." #: ../../whatsnew/2.4.rst:691 -msgid "http://speleotrove.com/decimal/" -msgstr "http://speleotrove.com/decimal/" +msgid "https://speleotrove.com/decimal/" +msgstr "" #: ../../whatsnew/2.4.rst:692 msgid "" @@ -1075,6 +1371,14 @@ msgstr "" "sequence is very long, you can either write multiple imports from the same " "module, or you can use backslashes to escape the line endings like this::" +#: ../../whatsnew/2.4.rst:708 +msgid "" +"from SimpleXMLRPCServer import SimpleXMLRPCServer,\\\n" +" SimpleXMLRPCRequestHandler,\\\n" +" CGIXMLRPCRequestHandler,\\\n" +" resolve_dotted_attribute" +msgstr "" + #: ../../whatsnew/2.4.rst:713 msgid "" "The syntactic change in Python 2.4 simply allows putting the names within " @@ -1085,6 +1389,18 @@ msgstr "" "parentheses. Python ignores newlines within a parenthesized expression, so " "the backslashes are no longer needed::" +#: ../../whatsnew/2.4.rst:717 +msgid "" +"from SimpleXMLRPCServer import (SimpleXMLRPCServer,\n" +" SimpleXMLRPCRequestHandler,\n" +" CGIXMLRPCRequestHandler,\n" +" resolve_dotted_attribute)" +msgstr "" +"from SimpleXMLRPCServer import (SimpleXMLRPCServer,\n" +" SimpleXMLRPCRequestHandler,\n" +" CGIXMLRPCRequestHandler,\n" +" resolve_dotted_attribute)" + #: ../../whatsnew/2.4.rst:722 msgid "" "The PEP also proposes that all :keyword:`import` statements be absolute " @@ -1099,7 +1415,7 @@ msgstr "" #: ../../whatsnew/2.4.rst:729 msgid ":pep:`328` - Imports: Multi-Line and Absolute/Relative" -msgstr ":pep:`328` - Imports: Multi-Line and Absolute/Relative" +msgstr ":pep:`328` - Importações: Multilinha e absoluta/relativa" #: ../../whatsnew/2.4.rst:730 msgid "Written by Aahz. Multi-line imports were implemented by Dima Dorfman." @@ -1163,17 +1479,13 @@ msgstr "" #: ../../whatsnew/2.4.rst:759 msgid "" -"The code for these functions came from the GLib library (https://developer-" -"old.gnome.org/glib/2.26/), whose developers kindly relicensed the relevant " -"functions and donated them to the Python Software Foundation. The :mod:" -"`locale` module can now change the numeric locale, letting extensions such " -"as GTK+ produce the correct results." +"The code for these functions came from the GLib library (`https://developer-" +"old.gnome.org/glib/2.26/ `__), whose developers kindly relicensed the " +"relevant functions and donated them to the Python Software Foundation. The :" +"mod:`locale` module can now change the numeric locale, letting extensions " +"such as GTK+ produce the correct results." msgstr "" -"The code for these functions came from the GLib library (https://developer-" -"old.gnome.org/glib/2.26/), whose developers kindly relicensed the relevant " -"functions and donated them to the Python Software Foundation. The :mod:" -"`locale` module can now change the numeric locale, letting extensions such " -"as GTK+ produce the correct results." #: ../../whatsnew/2.4.rst:768 msgid ":pep:`331` - Locale-Independent Float/String Conversions" @@ -1257,6 +1569,14 @@ msgstr "" "`split` method but splits from the end of the string. (Contributed by Sean " "Reifschneider.) ::" +#: ../../whatsnew/2.4.rst:804 +msgid "" +">>> 'www.python.org'.split('.', 1)\n" +"['www', 'python.org']\n" +"'www.python.org'.rsplit('.', 1)\n" +"['www.python', 'org']" +msgstr "" + #: ../../whatsnew/2.4.rst:809 msgid "" "Three keyword parameters, *cmp*, *key*, and *reverse*, were added to the :" @@ -1291,6 +1611,22 @@ msgstr "" "returns a comparison key for the element. The list is then sorted using the " "comparison keys. The following example sorts a list case-insensitively::" +#: ../../whatsnew/2.4.rst:822 +msgid "" +">>> L = ['A', 'b', 'c', 'D']\n" +">>> L.sort() # Case-sensitive sort\n" +">>> L\n" +"['A', 'D', 'b', 'c']\n" +">>> # Using 'key' parameter to sort list\n" +">>> L.sort(key=lambda x: x.lower())\n" +">>> L\n" +"['A', 'b', 'c', 'D']\n" +">>> # Old-fashioned way\n" +">>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))\n" +">>> L\n" +"['A', 'b', 'c', 'D']" +msgstr "" + #: ../../whatsnew/2.4.rst:835 msgid "" "The last example, which uses the *cmp* parameter, is the old way to perform " @@ -1315,6 +1651,13 @@ msgstr "" "avoid a :keyword:`lambda` expression by using an unbound method instead. " "For example, the above case-insensitive sort is best written as::" +#: ../../whatsnew/2.4.rst:845 +msgid "" +">>> L.sort(key=str.lower)\n" +">>> L\n" +"['A', 'b', 'c', 'D']" +msgstr "" + #: ../../whatsnew/2.4.rst:849 msgid "" "Finally, the *reverse* parameter takes a Boolean value. If the value is " @@ -1365,6 +1708,28 @@ msgstr "a newly formed copy is sorted, leaving the original intact; and" msgid "the expression returns the new sorted copy" msgstr "the expression returns the new sorted copy" +#: ../../whatsnew/2.4.rst:873 +msgid "" +">>> L = [9,7,8,3,2,4,1,6,5]\n" +">>> [10+i for i in sorted(L)] # usable in a list comprehension\n" +"[11, 12, 13, 14, 15, 16, 17, 18, 19]\n" +">>> L # original is left unchanged\n" +"[9,7,8,3,2,4,1,6,5]\n" +">>> sorted('Monty Python') # any iterable may be an input\n" +"[' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y']\n" +"\n" +">>> # List the contents of a dict sorted by key values\n" +">>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)\n" +">>> for k, v in sorted(colormap.iteritems()):\n" +"... print k, v\n" +"...\n" +"black 4\n" +"blue 2\n" +"green 3\n" +"red 1\n" +"yellow 5" +msgstr "" + #: ../../whatsnew/2.4.rst:892 ../../whatsnew/2.4.rst:920 #: ../../whatsnew/2.4.rst:1213 msgid "(Contributed by Raymond Hettinger.)" @@ -1414,6 +1779,17 @@ msgstr "" "`TypeError` exception. This makes them more suitable for use with variable " "length argument lists::" +#: ../../whatsnew/2.4.rst:912 +msgid "" +">>> def transpose(array):\n" +"... return zip(*array)\n" +"...\n" +">>> transpose([(1,2,3), (4,5,6)])\n" +"[(1, 4), (2, 5), (3, 6)]\n" +">>> transpose([])\n" +"[]" +msgstr "" + #: ../../whatsnew/2.4.rst:922 msgid "" "Encountering a failure while importing a module no longer leaves a partially " @@ -1656,6 +2032,24 @@ msgstr "" "ended queue that supports efficiently adding and removing elements from " "either end::" +#: ../../whatsnew/2.4.rst:1036 +msgid "" +">>> from collections import deque\n" +">>> d = deque('ghi') # make a new deque with three items\n" +">>> d.append('j') # add a new entry to the right side\n" +">>> d.appendleft('f') # add a new entry to the left side\n" +">>> d # show the representation of the deque\n" +"deque(['f', 'g', 'h', 'i', 'j'])\n" +">>> d.pop() # return and remove the rightmost item\n" +"'j'\n" +">>> d.popleft() # return and remove the leftmost item\n" +"'f'\n" +">>> list(d) # list the contents of the deque\n" +"['g', 'h', 'i']\n" +">>> 'h' in d # search the deque\n" +"True" +msgstr "" + #: ../../whatsnew/2.4.rst:1051 msgid "" "Several modules, such as the :mod:`Queue` and :mod:`threading` modules, now " @@ -1792,6 +2186,21 @@ msgstr "" "whether a number is even or odd, so the result of :func:`groupby` is to " "return consecutive runs of odd or even numbers. ::" +#: ../../whatsnew/2.4.rst:1106 +msgid "" +">>> import itertools\n" +">>> L = [2, 4, 6, 7, 8, 9, 11, 12, 14]\n" +">>> for key_val, it in itertools.groupby(L, lambda x: x % 2):\n" +"... print key_val, list(it)\n" +"...\n" +"0 [2, 4, 6]\n" +"1 [7]\n" +"0 [8]\n" +"1 [9, 11]\n" +"0 [12, 14]\n" +">>>" +msgstr "" + #: ../../whatsnew/2.4.rst:1118 msgid "" ":func:`groupby` is typically used with sorted input. The logic for :func:" @@ -1802,6 +2211,28 @@ msgstr "" "`groupby` is similar to the Unix ``uniq`` filter which makes it handy for " "eliminating, counting, or identifying duplicate elements::" +#: ../../whatsnew/2.4.rst:1122 +msgid "" +">>> word = 'abracadabra'\n" +">>> letters = sorted(word) # Turn string into a sorted list of letters\n" +">>> letters\n" +"['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']\n" +">>> for k, g in itertools.groupby(letters):\n" +"... print k, list(g)\n" +"...\n" +"a ['a', 'a', 'a', 'a', 'a']\n" +"b ['b', 'b']\n" +"c ['c']\n" +"d ['d']\n" +"r ['r', 'r']\n" +">>> # List unique letters\n" +">>> [k for k, g in groupby(letters)]\n" +"['a', 'b', 'c', 'd', 'r']\n" +">>> # Count letter occurrences\n" +">>> [(k, len(list(g))) for k, g in groupby(letters)]\n" +"[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]" +msgstr "" + #: ../../whatsnew/2.4.rst:1141 msgid "(Contributed by Hye-Shik Chang.)" msgstr "(Contributed by Hye-Shik Chang.)" @@ -1816,6 +2247,19 @@ msgstr "" "returns *N* independent iterators that replicate *iterator*. If *N* is " "omitted, the default is 2. ::" +#: ../../whatsnew/2.4.rst:1147 +msgid "" +">>> L = [1,2,3]\n" +">>> i1, i2 = itertools.tee(L)\n" +">>> i1,i2\n" +"(, )\n" +">>> list(i1) # Run the first iterator to exhaustion\n" +"[1, 2, 3]\n" +">>> list(i2) # Run the second iterator to exhaustion\n" +"[1, 2, 3]" +msgstr "" + #: ../../whatsnew/2.4.rst:1156 msgid "" "Note that :func:`tee` has to keep copies of the values returned by the " @@ -1862,6 +2306,14 @@ msgstr "" "specified to log to a particular file, change the logging format, or set the " "logging level. For example::" +#: ../../whatsnew/2.4.rst:1176 +msgid "" +"import logging\n" +"logging.basicConfig(filename='/var/log/application.log',\n" +" level=0, # Log all messages\n" +" format='%(levelname):%(process):%(thread):%(message)')" +msgstr "" + #: ../../whatsnew/2.4.rst:1181 msgid "" "Other additions to the :mod:`logging` package include a ``log(level, msg)`` " @@ -1918,6 +2370,17 @@ msgstr "" "or item; these callables make excellent data extractors when used with :func:" "`map` or :func:`sorted`. For example::" +#: ../../whatsnew/2.4.rst:1205 +msgid "" +">>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]\n" +">>> map(operator.itemgetter(0), L)\n" +"['c', 'd', 'a', 'b']\n" +">>> map(operator.itemgetter(1), L)\n" +"[2, 1, 4, 3]\n" +">>> sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item\n" +"[('d', 1), ('c', 2), ('b', 3), ('a', 4)]" +msgstr "" + #: ../../whatsnew/2.4.rst:1215 msgid "" "The :mod:`optparse` module was updated in various ways. The module now " @@ -2110,6 +2573,15 @@ msgstr "" "thread-local data. The module contains a :class:`local` class whose " "attribute values are local to different threads. ::" +#: ../../whatsnew/2.4.rst:1292 +msgid "" +"import threading\n" +"\n" +"data = threading.local()\n" +"data.number = 42\n" +"data.url = ('www.python.org', 80)" +msgstr "" + #: ../../whatsnew/2.4.rst:1298 msgid "" "Other threads can assign and retrieve their own values for the :attr:" @@ -2230,6 +2702,22 @@ msgstr "" "The new :class:`DocTestFinder` class extracts the tests from a given " "object's docstrings::" +#: ../../whatsnew/2.4.rst:1358 +msgid "" +"def f (x, y):\n" +" \"\"\">>> f(2,2)\n" +"4\n" +">>> f(3,2)\n" +"6\n" +" \"\"\"\n" +" return x*y\n" +"\n" +"finder = doctest.DocTestFinder()\n" +"\n" +"# Get list of DocTest instances\n" +"tests = finder.find(f)" +msgstr "" + #: ../../whatsnew/2.4.rst:1371 msgid "" "The new :class:`DocTestRunner` class then runs individual tests and can " @@ -2238,10 +2726,28 @@ msgstr "" "The new :class:`DocTestRunner` class then runs individual tests and can " "produce a summary of the results::" +#: ../../whatsnew/2.4.rst:1374 +msgid "" +"runner = doctest.DocTestRunner()\n" +"for t in tests:\n" +" tried, failed = runner.run(t)\n" +"\n" +"runner.summarize(verbose=1)" +msgstr "" + #: ../../whatsnew/2.4.rst:1380 msgid "The above example produces the following output::" msgstr "The above example produces the following output::" +#: ../../whatsnew/2.4.rst:1382 +msgid "" +"1 items passed all tests:\n" +" 2 tests in f\n" +"2 tests in 1 items.\n" +"2 passed and 0 failed.\n" +"Test passed." +msgstr "" + #: ../../whatsnew/2.4.rst:1388 msgid "" ":class:`DocTestRunner` uses an instance of the :class:`OutputChecker` class " @@ -2266,10 +2772,28 @@ msgstr "" "expected output matches any substring, making it easier to accommodate " "outputs that vary in minor ways::" +#: ../../whatsnew/2.4.rst:1398 +msgid "" +"def o (n):\n" +" \"\"\">>> o(1)\n" +"<__main__.C instance at 0x...>\n" +">>>\n" +"\"\"\"" +msgstr "" + #: ../../whatsnew/2.4.rst:1404 msgid "Another special string, ````, matches a blank line::" msgstr "Another special string, ````, matches a blank line::" +#: ../../whatsnew/2.4.rst:1406 +msgid "" +"def p (n):\n" +" \"\"\">>> p(1)\n" +"\n" +">>>\n" +"\"\"\"" +msgstr "" + #: ../../whatsnew/2.4.rst:1412 msgid "" "Another new capability is producing a diff-style display of the output by " @@ -2282,6 +2806,20 @@ msgstr "" "`doctest.REPORT_CDIFF` (context diffs), or :const:`doctest.REPORT_NDIFF` " "(delta-style) option flags. For example::" +#: ../../whatsnew/2.4.rst:1417 +msgid "" +"def g (n):\n" +" \"\"\">>> g(4)\n" +"here\n" +"is\n" +"a\n" +"lengthy\n" +">>>\"\"\"\n" +" L = 'here is a rather lengthy list of words'.split()\n" +" for word in L[:n]:\n" +" print word" +msgstr "" + #: ../../whatsnew/2.4.rst:1428 msgid "" "Running the above function's tests with :const:`doctest.REPORT_UDIFF` " @@ -2290,6 +2828,21 @@ msgstr "" "Running the above function's tests with :const:`doctest.REPORT_UDIFF` " "specified, you get the following output:" +#: ../../whatsnew/2.4.rst:1431 +msgid "" +"**********************************************************************\n" +"File \"t.py\", line 15, in g\n" +"Failed example:\n" +" g(4)\n" +"Differences (unified diff with -expected +actual):\n" +" @@ -2,3 +2,3 @@\n" +" is\n" +" a\n" +" -lengthy\n" +" +rather\n" +"**********************************************************************" +msgstr "" + #: ../../whatsnew/2.4.rst:1449 msgid "Build and C API Changes" msgstr "Mudanças a construções e API C" @@ -2526,7 +3079,7 @@ msgstr "" #: ../../whatsnew/2.4.rst:1560 msgid "Acknowledgements" -msgstr "Acknowledgements" +msgstr "Reconhecimentos" #: ../../whatsnew/2.4.rst:1562 msgid "" @@ -2542,7 +3095,7 @@ msgstr "" #: ../../whatsnew/2.4.rst:415 msgid "universal newlines" -msgstr "universal newlines" +msgstr "novas linhas universais" #: ../../whatsnew/2.4.rst:415 msgid "What's new" diff --git a/whatsnew/2.5.po b/whatsnew/2.5.po index d68d1bea9..2a4008f93 100644 --- a/whatsnew/2.5.po +++ b/whatsnew/2.5.po @@ -1,33 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Victor Matheus Castro , 2021 -# Adson Rodrigues , 2021 -# Raphael Mendonça, 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Misael borges , 2021 -# Rodrigo Cândido, 2022 -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:51+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -149,6 +141,14 @@ msgstr "" "you write a single assignment statement that has the same effect as the " "following::" +#: ../../whatsnew/2.5.rst:61 +msgid "" +"if condition:\n" +" x = true_value\n" +"else:\n" +" x = false_value" +msgstr "" + #: ../../whatsnew/2.5.rst:66 msgid "" "There have been endless tedious discussions of syntax on both python-dev and " @@ -167,6 +167,10 @@ msgstr "" msgid "Guido van Rossum eventually chose a surprising syntax::" msgstr "Guido van Rossum eventually chose a surprising syntax::" +#: ../../whatsnew/2.5.rst:74 +msgid "x = true_value if condition else false_value" +msgstr "" + #: ../../whatsnew/2.5.rst:76 msgid "" "Evaluation is still lazy as in existing Boolean expressions, so the order of " @@ -201,6 +205,10 @@ msgstr "" "when the condition isn't met. The conditional syntax makes this pattern a " "bit more obvious::" +#: ../../whatsnew/2.5.rst:90 +msgid "contents = ((doc + '\\n') if doc else '')" +msgstr "" + #: ../../whatsnew/2.5.rst:92 msgid "" "I read the above statement as meaning \"here *contents* is usually assigned " @@ -225,6 +233,15 @@ msgstr "" "require parentheses in the Python language's grammar, but as a matter of " "style I think you should always use them. Consider these two statements::" +#: ../../whatsnew/2.5.rst:102 +msgid "" +"# First version -- no parens\n" +"level = 1 if logging else 0\n" +"\n" +"# Second version -- with parens\n" +"level = (1 if logging else 0)" +msgstr "" + #: ../../whatsnew/2.5.rst:108 msgid "" "In the first version, I think a reader's eye might group the statement into " @@ -305,6 +322,19 @@ msgstr "" msgid "Here's a small but realistic example::" msgstr "Aqui está um pequeno mas bem realístico exemplo::" +#: ../../whatsnew/2.5.rst:150 +msgid "" +"import functools\n" +"\n" +"def log (message, subsystem):\n" +" \"Write the contents of 'message' to the specified subsystem.\"\n" +" print '%s: %s' % (subsystem, message)\n" +" ...\n" +"\n" +"server_log = functools.partial(log, subsystem='server')\n" +"server_log('Unable to open socket')" +msgstr "" + #: ../../whatsnew/2.5.rst:160 msgid "" "Here's another example, from a program that uses PyGTK. Here a context-" @@ -317,6 +347,17 @@ msgstr "" "provided for the menu option is a partially applied version of the :meth:" "`open_item` method, where the first argument has been provided. ::" +#: ../../whatsnew/2.5.rst:165 +msgid "" +"...\n" +"class Application:\n" +" def open_item(self, path):\n" +" ...\n" +" def init (self):\n" +" open_func = functools.partial(self.open_item, item_path)\n" +" popup_menu.append( (\"Open\", open_func, 1) )" +msgstr "" + #: ../../whatsnew/2.5.rst:173 msgid "" "Another function in the :mod:`functools` module is the " @@ -331,6 +372,16 @@ msgstr "" "docstring attribute to a wrapper function so that tracebacks inside the " "wrapped function are easier to understand. For example, you might write::" +#: ../../whatsnew/2.5.rst:179 +msgid "" +"def my_decorator(f):\n" +" def wrapper(*args, **kwds):\n" +" print 'Calling decorated function'\n" +" return f(*args, **kwds)\n" +" functools.update_wrapper(wrapper, f)\n" +" return wrapper" +msgstr "" + #: ../../whatsnew/2.5.rst:186 msgid "" ":func:`wraps` is a decorator that can be used inside your own decorators to " @@ -341,6 +392,16 @@ msgstr "" "copy the wrapped function's information. An alternate version of the " "previous example would be::" +#: ../../whatsnew/2.5.rst:190 +msgid "" +"def my_decorator(f):\n" +" @functools.wraps(f)\n" +" def wrapper(*args, **kwds):\n" +" print 'Calling decorated function'\n" +" return f(*args, **kwds)\n" +" return wrapper" +msgstr "" + #: ../../whatsnew/2.5.rst:200 msgid ":pep:`309` - Partial Function Application" msgstr ":pep:`309` - Partial Function Application" @@ -383,6 +444,18 @@ msgstr "" "an entry in the package index, determine the dependencies for a package, and " "download the required packages. ::" +#: ../../whatsnew/2.5.rst:222 +msgid "" +"VERSION = '1.0'\n" +"setup(name='PyPackage',\n" +" version=VERSION,\n" +" requires=['numarray', 'zlib (>=1.1.4)'],\n" +" obsoletes=['OldPackage']\n" +" download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'\n" +" % VERSION),\n" +" )" +msgstr "" + #: ../../whatsnew/2.5.rst:231 msgid "" "Another new enhancement to the Python package index at https://pypi.org is " @@ -457,6 +530,14 @@ msgstr "" msgid "Let's say you have a package directory like this::" msgstr "Let's say you have a package directory like this::" +#: ../../whatsnew/2.5.rst:269 +msgid "" +"pkg/\n" +"pkg/__init__.py\n" +"pkg/main.py\n" +"pkg/string.py" +msgstr "" + #: ../../whatsnew/2.5.rst:274 msgid "" "This defines a package named :mod:`pkg` containing the :mod:`pkg.main` and :" @@ -541,6 +622,14 @@ msgstr "" "Relative imports are still possible by adding a leading period to the " "module name when using the ``from ... import`` form::" +#: ../../whatsnew/2.5.rst:310 +msgid "" +"# Import names from pkg.string\n" +"from .string import name1, name2\n" +"# Import pkg.string\n" +"from . import string" +msgstr "" + #: ../../whatsnew/2.5.rst:315 msgid "" "This imports the :mod:`string` module relative to the current package, so " @@ -555,6 +644,13 @@ msgstr "" "from the parent of the current package. For example, code in the :mod:`A.B." "C` module can do::" +#: ../../whatsnew/2.5.rst:320 +msgid "" +"from . import D # Imports A.B.D\n" +"from .. import E # Imports A.E\n" +"from ..F import G # Imports A.F.G" +msgstr "" + #: ../../whatsnew/2.5.rst:324 msgid "" "Leading periods cannot be used with the ``import modname`` form of the " @@ -655,6 +751,20 @@ msgstr "" "block, and this clarified what the statement should mean. In Python 2.5, " "you can now write::" +#: ../../whatsnew/2.5.rst:382 +msgid "" +"try:\n" +" block-1 ...\n" +"except Exception1:\n" +" handler-1 ...\n" +"except Exception2:\n" +" handler-2 ...\n" +"else:\n" +" else-block\n" +"finally:\n" +" final-block" +msgstr "" + #: ../../whatsnew/2.5.rst:393 msgid "" "The code in *block-1* is executed. If the code raises an exception, the " @@ -717,6 +827,15 @@ msgstr "" msgid "To refresh your memory of basic generators, here's a simple example::" msgstr "To refresh your memory of basic generators, here's a simple example::" +#: ../../whatsnew/2.5.rst:428 +msgid "" +"def counter (maximum):\n" +" i = 0\n" +" while i < maximum:\n" +" yield i\n" +" i += 1" +msgstr "" + #: ../../whatsnew/2.5.rst:434 msgid "" "When you call ``counter(10)``, the result is an iterator that returns the " @@ -743,6 +862,10 @@ msgstr "" "value. In 2.5, :keyword:`!yield` is now an expression, returning a value " "that can be assigned to a variable or otherwise operated on::" +#: ../../whatsnew/2.5.rst:444 +msgid "val = (yield i)" +msgstr "" + #: ../../whatsnew/2.5.rst:446 msgid "" "I recommend that you always put parentheses around a :keyword:`yield` " @@ -789,10 +912,41 @@ msgstr "" "Here's the previous example, modified to allow changing the value of the " "internal counter. ::" +#: ../../whatsnew/2.5.rst:466 +msgid "" +"def counter (maximum):\n" +" i = 0\n" +" while i < maximum:\n" +" val = (yield i)\n" +" # If value provided, change counter\n" +" if val is not None:\n" +" i = val\n" +" else:\n" +" i += 1" +msgstr "" + #: ../../whatsnew/2.5.rst:476 msgid "And here's an example of changing the counter::" msgstr "And here's an example of changing the counter::" +#: ../../whatsnew/2.5.rst:478 +msgid "" +">>> it = counter(10)\n" +">>> print it.next()\n" +"0\n" +">>> print it.next()\n" +"1\n" +">>> print it.send(8)\n" +"8\n" +">>> print it.next()\n" +"9\n" +">>> print it.next()\n" +"Traceback (most recent call last):\n" +" File \"t.py\", line 15, in ?\n" +" print it.next()\n" +"StopIteration" +msgstr "" + #: ../../whatsnew/2.5.rst:493 msgid "" ":keyword:`yield` will usually return :const:`None`, so you should always " @@ -983,6 +1137,12 @@ msgstr "" "The ':keyword:`with`' statement is a new control-flow structure whose basic " "structure is::" +#: ../../whatsnew/2.5.rst:574 +msgid "" +"with expression [as variable]:\n" +" with-block" +msgstr "" + #: ../../whatsnew/2.5.rst:577 msgid "" "The expression is evaluated, and it should result in an object that supports " @@ -1023,6 +1183,10 @@ msgstr "" "To enable the statement in Python 2.5, you need to add the following " "directive to your module::" +#: ../../whatsnew/2.5.rst:593 +msgid "from __future__ import with_statement" +msgstr "" + #: ../../whatsnew/2.5.rst:595 msgid "The statement will always be enabled in Python 2.6." msgstr "The statement will always be enabled in Python 2.6." @@ -1037,6 +1201,14 @@ msgstr "" "can be used with the ':keyword:`with`' statement. File objects are one " "example::" +#: ../../whatsnew/2.5.rst:600 +msgid "" +"with open('/etc/passwd', 'r') as f:\n" +" for line in f:\n" +" print line\n" +" ... more processing code ..." +msgstr "" + #: ../../whatsnew/2.5.rst:605 msgid "" "After this statement has executed, the file object in *f* will have been " @@ -1060,8 +1232,16 @@ msgid "" "The :mod:`threading` module's locks and condition variables also support " "the ':keyword:`with`' statement::" msgstr "" -"As travas e variáveis ​​de condição do módulo :mod:`threading` também oferecem " -"suporte à instrução ':keyword:`with`'::" +"The :mod:`threading` module's locks and condition variables also support the " +"':keyword:`with`' statement::" + +#: ../../whatsnew/2.5.rst:617 +msgid "" +"lock = threading.Lock()\n" +"with lock:\n" +" # Critical section of code\n" +" ..." +msgstr "" #: ../../whatsnew/2.5.rst:622 msgid "" @@ -1081,6 +1261,20 @@ msgstr "" "easy to save and restore the current decimal context, which encapsulates the " "desired precision and rounding characteristics for computations::" +#: ../../whatsnew/2.5.rst:629 +msgid "" +"from decimal import Decimal, Context, localcontext\n" +"\n" +"# Displays with default precision of 28 digits\n" +"v = Decimal('578')\n" +"print v.sqrt()\n" +"\n" +"with localcontext(Context(prec=16)):\n" +" # All code in this block uses a precision of 16 digits.\n" +" # The original context is restored on exiting the block.\n" +" print v.sqrt()" +msgstr "" + #: ../../whatsnew/2.5.rst:644 msgid "Writing Context Managers" msgstr "Writing Context Managers" @@ -1183,6 +1377,15 @@ msgstr "" "Vamos supor que exista um objeto representando uma conexão com o banco de " "dados. Nosso objetivo será permitir que o usuário escreva código como este:" +#: ../../whatsnew/2.5.rst:687 +msgid "" +"db_connection = DatabaseConnection()\n" +"with db_connection as cursor:\n" +" cursor.execute('insert into ...')\n" +" cursor.execute('delete from ...')\n" +" # ... more operations ..." +msgstr "" + #: ../../whatsnew/2.5.rst:693 msgid "" "The transaction should be committed if the code in the block runs flawlessly " @@ -1193,6 +1396,18 @@ msgstr "" "perfeitamente ou revertida se houver uma exceção. Aqui está a interface " "básica para :class:`DatabaseConnection` que presumirei::" +#: ../../whatsnew/2.5.rst:697 +msgid "" +"class DatabaseConnection:\n" +" # Database interface\n" +" def cursor (self):\n" +" \"Returns a cursor object and starts a new transaction\"\n" +" def commit (self):\n" +" \"Commits current transaction\"\n" +" def rollback (self):\n" +" \"Rolls back current transaction\"" +msgstr "" + #: ../../whatsnew/2.5.rst:706 msgid "" "The :meth:`~object.__enter__` method is pretty easy, having only to start a " @@ -1207,6 +1422,16 @@ msgstr "" "cursor`` to their ':keyword:`with`' statement to bind the cursor to a " "variable name. ::" +#: ../../whatsnew/2.5.rst:711 +msgid "" +"class DatabaseConnection:\n" +" ...\n" +" def __enter__ (self):\n" +" # Code to start a new transaction\n" +" cursor = self.cursor()\n" +" return cursor" +msgstr "" + #: ../../whatsnew/2.5.rst:718 msgid "" "The :meth:`~object.__exit__` method is the most complicated because it's " @@ -1231,6 +1456,20 @@ msgstr "" "will be re-raised automatically. If you wished, you could be more explicit " "and add a :keyword:`return` statement at the marked location. ::" +#: ../../whatsnew/2.5.rst:728 +msgid "" +"class DatabaseConnection:\n" +" ...\n" +" def __exit__ (self, type, value, tb):\n" +" if tb is None:\n" +" # No exception, so commit\n" +" self.commit()\n" +" else:\n" +" # Exception occurred, so rollback.\n" +" self.rollback()\n" +" # return False" +msgstr "" + #: ../../whatsnew/2.5.rst:743 msgid "The contextlib module" msgstr "The contextlib module" @@ -1275,6 +1514,26 @@ msgstr "" "Our database example from the previous section could be written using this " "decorator as::" +#: ../../whatsnew/2.5.rst:760 +msgid "" +"from contextlib import contextmanager\n" +"\n" +"@contextmanager\n" +"def db_transaction (connection):\n" +" cursor = connection.cursor()\n" +" try:\n" +" yield cursor\n" +" except:\n" +" connection.rollback()\n" +" raise\n" +" else:\n" +" connection.commit()\n" +"\n" +"db = DatabaseConnection()\n" +"with db_transaction(db) as cursor:\n" +" ..." +msgstr "" + #: ../../whatsnew/2.5.rst:777 msgid "" "The :mod:`contextlib` module also has a ``nested(mgr1, mgr2, ...)`` function " @@ -1289,6 +1548,13 @@ msgstr "" "with`' statement both starts a database transaction and acquires a thread " "lock::" +#: ../../whatsnew/2.5.rst:782 +msgid "" +"lock = threading.Lock()\n" +"with nested (db_transaction(db), lock) as (cursor, locked):\n" +" ..." +msgstr "" + #: ../../whatsnew/2.5.rst:786 msgid "" "Finally, the ``closing(object)`` function returns *object* so that it can be " @@ -1297,6 +1563,16 @@ msgstr "" "Finally, the ``closing(object)`` function returns *object* so that it can be " "bound to a variable, and calls ``object.close`` at the end of the block. ::" +#: ../../whatsnew/2.5.rst:789 +msgid "" +"import urllib, sys\n" +"from contextlib import closing\n" +"\n" +"with closing(urllib.urlopen('http://www.yahoo.com')) as f:\n" +" for line in f:\n" +" sys.stdout.write(line)" +msgstr "" + #: ../../whatsnew/2.5.rst:799 msgid ":pep:`343` - The \"with\" statement" msgstr ":pep:`343` - A instrução \"with\"" @@ -1341,6 +1617,15 @@ msgstr "" "The inheritance hierarchy for exceptions has been rearranged a bit. In 2.5, " "the inheritance relationships are::" +#: ../../whatsnew/2.5.rst:822 +msgid "" +"BaseException # New in Python 2.5\n" +"|- KeyboardInterrupt\n" +"|- SystemExit\n" +"|- Exception\n" +" |- (all other current built-in exceptions)" +msgstr "" + #: ../../whatsnew/2.5.rst:828 msgid "" "This rearrangement was done because people often want to catch all " @@ -1359,6 +1644,17 @@ msgstr "" "exc:`KeyboardInterrupt` and :exc:`SystemExit` in order to re-raise them. " "The usual pattern is::" +#: ../../whatsnew/2.5.rst:835 +msgid "" +"try:\n" +" ...\n" +"except (KeyboardInterrupt, SystemExit):\n" +" raise\n" +"except:\n" +" # Log error...\n" +" # Continue running program..." +msgstr "" + #: ../../whatsnew/2.5.rst:843 msgid "" "In Python 2.5, you can now write ``except Exception`` to achieve the same " @@ -1571,6 +1867,13 @@ msgstr "" "no arguments and returns an integer giving the slice index to use. For " "example::" +#: ../../whatsnew/2.5.rst:949 +msgid "" +"class C:\n" +" def __index__ (self):\n" +" return self.value" +msgstr "" + #: ../../whatsnew/2.5.rst:953 msgid "" "The return value must be either a Python integer or long integer. The " @@ -1629,6 +1932,17 @@ msgstr "" "`collections` module. The following example defines a dictionary that " "returns zero for any missing key::" +#: ../../whatsnew/2.5.rst:985 +msgid "" +"class zerodict (dict):\n" +" def __missing__ (self, key):\n" +" return 0\n" +"\n" +"d = zerodict({1:1, 2:2})\n" +"print d[1], d[2] # Prints 1, 2\n" +"print d[3], d[4] # Prints 0, 0" +msgstr "" + #: ../../whatsnew/2.5.rst:993 msgid "" "Both 8-bit and Unicode strings have new ``partition(sep)`` and " @@ -1663,6 +1977,20 @@ msgstr "" msgid "Some examples::" msgstr "Alguns exemplos:" +#: ../../whatsnew/2.5.rst:1007 +msgid "" +">>> ('http://www.python.org').partition('://')\n" +"('http', '://', 'www.python.org')\n" +">>> ('file:/usr/share/doc/index.html').partition('://')\n" +"('file:/usr/share/doc/index.html', '', '')\n" +">>> (u'Subject: a quick question').partition(':')\n" +"(u'Subject', u':', u' a quick question')\n" +">>> 'www.python.org'.rpartition('.')\n" +"('www.python', '.', 'org')\n" +">>> 'www.python.org'.rpartition(':')\n" +"('', '', 'www.python.org')" +msgstr "" + #: ../../whatsnew/2.5.rst:1018 msgid "" "(Implemented by Fredrik Lundh following a suggestion by Raymond Hettinger.)" @@ -1677,6 +2005,12 @@ msgstr "" "The :meth:`startswith` and :meth:`endswith` methods of string types now " "accept tuples of strings to check for. ::" +#: ../../whatsnew/2.5.rst:1023 +msgid "" +"def is_image_file (filename):\n" +" return filename.endswith(('.gif', '.jpg', '.tiff'))" +msgstr "" + #: ../../whatsnew/2.5.rst:1026 msgid "(Implemented by Georg Brandl following a suggestion by Tom Lynn.)" msgstr "(Implemented by Georg Brandl following a suggestion by Tom Lynn.)" @@ -1697,6 +2031,15 @@ msgstr "" "with the smallest/largest return value from this function. For example, to " "find the longest string in a list, you can do::" +#: ../../whatsnew/2.5.rst:1037 +msgid "" +"L = ['medium', 'longest', 'short']\n" +"# Prints 'longest'\n" +"print max(L, key=len)\n" +"# Prints 'short', because lexicographically 'short' has the largest value\n" +"print max(L)" +msgstr "" + #: ../../whatsnew/2.5.rst:1043 msgid "(Contributed by Steven Bethard and Raymond Hettinger.)" msgstr "(Contributed by Steven Bethard and Raymond Hettinger.)" @@ -1747,6 +2090,10 @@ msgstr "" "error. See :pep:`263` for how to declare a module's encoding; for example, " "you might add a line like this near the top of the source file::" +#: ../../whatsnew/2.5.rst:1067 +msgid "# -*- coding: latin1 -*-" +msgstr "" + #: ../../whatsnew/2.5.rst:1069 msgid "" "A new warning, :class:`UnicodeWarning`, is triggered when you attempt to " @@ -1759,6 +2106,17 @@ msgstr "" "Unicode using the default ASCII encoding. The result of the comparison is " "false::" +#: ../../whatsnew/2.5.rst:1073 +msgid "" +">>> chr(128) == unichr(128) # Can't convert chr(128) to Unicode\n" +"__main__:1: UnicodeWarning: Unicode equal comparison failed\n" +" to convert both arguments to Unicode - interpreting them\n" +" as being unequal\n" +"False\n" +">>> chr(127) == unichr(127) # chr(127) can be converted\n" +"True" +msgstr "" + #: ../../whatsnew/2.5.rst:1081 msgid "" "Previously this would raise a :class:`UnicodeDecodeError` exception, but in " @@ -1819,6 +2177,12 @@ msgstr "" "The list of base classes in a class definition can now be empty. As an " "example, this is now legal::" +#: ../../whatsnew/2.5.rst:1105 +msgid "" +"class C():\n" +" pass" +msgstr "" + #: ../../whatsnew/2.5.rst:1108 msgid "(Implemented by Brett Cannon.)" msgstr "(Implemented by Brett Cannon.)" @@ -1837,6 +2201,12 @@ msgstr "" "strings so that new users get a somewhat helpful message when they try to " "quit::" +#: ../../whatsnew/2.5.rst:1121 +msgid "" +">>> quit\n" +"'Use Ctrl-D (i.e. EOF) to exit.'" +msgstr "" + #: ../../whatsnew/2.5.rst:1124 msgid "" "In Python 2.5, ``quit`` and ``exit`` are now objects that still produce " @@ -2083,10 +2453,32 @@ msgstr "" "constructors such as :func:`list` or :func:`int`. For example, you can " "make an index of words based on their initial letter like this::" +#: ../../whatsnew/2.5.rst:1251 +msgid "" +"words = \"\"\"Nel mezzo del cammin di nostra vita\n" +"mi ritrovai per una selva oscura\n" +"che la diritta via era smarrita\"\"\".lower().split()\n" +"\n" +"index = defaultdict(list)\n" +"\n" +"for w in words:\n" +" init_letter = w[0]\n" +" index[init_letter].append(w)" +msgstr "" + #: ../../whatsnew/2.5.rst:1261 msgid "Printing ``index`` results in the following output::" msgstr "Printing ``index`` results in the following output::" +#: ../../whatsnew/2.5.rst:1263 +msgid "" +"defaultdict(, {'c': ['cammin', 'che'], 'e': ['era'],\n" +" 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],\n" +" 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],\n" +" 'p': ['per'], 's': ['selva', 'smarrita'],\n" +" 'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}" +msgstr "" + #: ../../whatsnew/2.5.rst:1269 msgid "(Contributed by Guido van Rossum.)" msgstr "(Contributed by Guido van Rossum.)" @@ -2199,6 +2591,14 @@ msgstr "" "by Josh Spoerri. It uses the same format characters as :func:`time.strptime` " "and :func:`time.strftime`::" +#: ../../whatsnew/2.5.rst:1316 +msgid "" +"from datetime import datetime\n" +"\n" +"ts = datetime.strptime('10:13:15 2006-03-07',\n" +" '%H:%M:%S %Y-%m-%d')" +msgstr "" + #: ../../whatsnew/2.5.rst:1321 msgid "" "The :meth:`SequenceMatcher.get_matching_blocks` method in the :mod:`difflib` " @@ -2291,6 +2691,16 @@ msgstr "" "by the :func:`min`/:func:`max` functions and the :meth:`sort` methods. For " "example::" +#: ../../whatsnew/2.5.rst:1366 +msgid "" +">>> import heapq\n" +">>> L = [\"short\", 'medium', 'longest', 'longer still']\n" +">>> heapq.nsmallest(2, L) # Return two lowest elements, lexicographically\n" +"['longer still', 'longest']\n" +">>> heapq.nsmallest(2, L, key=len) # Return two shortest elements\n" +"['short', 'medium']" +msgstr "" + #: ../../whatsnew/2.5.rst:1373 ../../whatsnew/2.5.rst:1382 msgid "(Contributed by Raymond Hettinger.)" msgstr "(Contributed by Raymond Hettinger.)" @@ -2305,6 +2715,12 @@ msgstr "" "step arguments. This makes it more compatible with the attributes of slice " "objects, so that you can now write the following::" +#: ../../whatsnew/2.5.rst:1379 +msgid "" +"s = slice(5) # Create slice object\n" +"itertools.islice(iterable, s.start, s.stop, s.step)" +msgstr "" + #: ../../whatsnew/2.5.rst:1384 msgid "" "The :func:`format` function in the :mod:`locale` module has been modified " @@ -2369,6 +2785,19 @@ msgstr "" "unlock the mailbox. The following example converts a maildir-format mailbox " "into an mbox-format one::" +#: ../../whatsnew/2.5.rst:1412 +msgid "" +"import mailbox\n" +"\n" +"# 'factory=None' uses email.Message.Message as the class representing\n" +"# individual messages.\n" +"src = mailbox.Maildir('maildir', factory=None)\n" +"dest = mailbox.mbox('/tmp/mbox')\n" +"\n" +"for msg in src:\n" +" dest.add(msg)" +msgstr "" + #: ../../whatsnew/2.5.rst:1422 msgid "" "(Contributed by Gregory K. Johnson. Funding was provided by Google's 2005 " @@ -2677,6 +3106,14 @@ msgstr "" "func:`unpack` functions; they'll create :class:`Struct` objects and cache " "them. Or you can use :class:`Struct` instances directly::" +#: ../../whatsnew/2.5.rst:1555 +msgid "" +"s = struct.Struct('ih3s')\n" +"\n" +"data = s.pack(1972, 187, 'abc')\n" +"year, number, name = s.unpack(data)" +msgstr "" + #: ../../whatsnew/2.5.rst:1560 msgid "" "You can also pack and unpack data to and from buffer objects directly using " @@ -2803,6 +3240,26 @@ msgstr "" "UUIDs are not specified in :rfc:`4122` and are not supported by this " "module.) ::" +#: ../../whatsnew/2.5.rst:1615 +msgid "" +">>> import uuid\n" +">>> # make a UUID based on the host ID and current time\n" +">>> uuid.uuid1()\n" +"UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')\n" +"\n" +">>> # make a UUID using an MD5 hash of a namespace UUID and a name\n" +">>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')\n" +"UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')\n" +"\n" +">>> # make a random UUID\n" +">>> uuid.uuid4()\n" +"UUID('16fd2706-8baf-433b-82eb-8c7fada847da')\n" +"\n" +">>> # make a UUID using a SHA-1 hash of a namespace UUID and a name\n" +">>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')\n" +"UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')" +msgstr "" + #: ../../whatsnew/2.5.rst:1632 msgid "(Contributed by Ka-Ping Yee.)" msgstr "(Contributed by Ka-Ping Yee.)" @@ -2913,6 +3370,14 @@ msgstr "" "that's done, you can call arbitrary functions by accessing them as " "attributes of the :class:`CDLL` object. ::" +#: ../../whatsnew/2.5.rst:1692 +msgid "" +"import ctypes\n" +"\n" +"libc = ctypes.CDLL('libc.so.6')\n" +"result = libc.printf(\"Line of output\\n\")" +msgstr "" + #: ../../whatsnew/2.5.rst:1697 msgid "" "Type constructors for the various C types are provided: :func:`c_int`, :func:" @@ -2945,6 +3410,13 @@ msgstr "" "be immutable; breaking this rule will cause puzzling bugs. When you need a " "modifiable memory area, use :func:`create_string_buffer`::" +#: ../../whatsnew/2.5.rst:1711 +msgid "" +"s = \"this is a string\"\n" +"buf = ctypes.create_string_buffer(s)\n" +"libc.strfry(buf)" +msgstr "" + #: ../../whatsnew/2.5.rst:1715 msgid "" "C functions are assumed to return integers, but you can set the :attr:" @@ -2953,6 +3425,15 @@ msgstr "" "C functions are assumed to return integers, but you can set the :attr:" "`restype` attribute of the function object to change this::" +#: ../../whatsnew/2.5.rst:1718 +msgid "" +">>> libc.atof('2.71828')\n" +"-1783957616\n" +">>> libc.atof.restype = ctypes.c_double\n" +">>> libc.atof('2.71828')\n" +"2.71828" +msgstr "" + #: ../../whatsnew/2.5.rst:1724 msgid "" ":mod:`ctypes` also provides a wrapper for Python's C API as the ``ctypes." @@ -2969,6 +3450,16 @@ msgstr "" "constructor that will create a :c:expr:`PyObject *` pointer. A simple " "usage::" +#: ../../whatsnew/2.5.rst:1730 +msgid "" +"import ctypes\n" +"\n" +"d = {}\n" +"ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),\n" +" ctypes.py_object(\"abc\"), ctypes.py_object(1))\n" +"# d is now {'abc', 1}." +msgstr "" + #: ../../whatsnew/2.5.rst:1737 msgid "" "Don't forget to use :func:`~ctypes.py_object`; if it's omitted you end up " @@ -3059,6 +3550,17 @@ msgstr "" "a string (assumed to contain a filename) or a file-like object and returns " "an :class:`ElementTree` instance::" +#: ../../whatsnew/2.5.rst:1782 +msgid "" +"from xml.etree import ElementTree as ET\n" +"\n" +"tree = ET.parse('ex-1.xml')\n" +"\n" +"feed = urllib.urlopen(\n" +" 'http://planet.python.org/rss10.xml')\n" +"tree = ET.parse(feed)" +msgstr "" + #: ../../whatsnew/2.5.rst:1790 msgid "" "Once you have an :class:`ElementTree` instance, you can call its :meth:" @@ -3079,6 +3581,14 @@ msgstr "" "provides a tidy way to incorporate XML fragments, approaching the " "convenience of an XML literal::" +#: ../../whatsnew/2.5.rst:1798 +msgid "" +"svg = ET.XML(\"\"\"\n" +" \"\"\")\n" +"svg.set('height', '320px')\n" +"svg.append(elem1)" +msgstr "" + #: ../../whatsnew/2.5.rst:1803 msgid "" "Each XML element supports some dictionary-like and some list-like access " @@ -3203,6 +3713,14 @@ msgstr "" "`Element` nodes. To check if a node is a comment or processing " "instructions::" +#: ../../whatsnew/2.5.rst:1840 +msgid "" +"if elem.tag is ET.Comment:\n" +" ...\n" +"elif elem.tag is ET.ProcessingInstruction:\n" +" ..." +msgstr "" + #: ../../whatsnew/2.5.rst:1845 msgid "" "To generate XML output, you should call the :meth:`ElementTree.write` " @@ -3213,6 +3731,16 @@ msgstr "" "method. Like :func:`parse`, it can take either a string or a file-like " "object::" +#: ../../whatsnew/2.5.rst:1848 +msgid "" +"# Encoding is US-ASCII\n" +"tree.write('output.xml')\n" +"\n" +"# Encoding is UTF-8\n" +"f = open('output.xml', 'w')\n" +"tree.write(f, encoding='utf-8')" +msgstr "" + #: ../../whatsnew/2.5.rst:1855 msgid "" "(Caution: the default encoding used for output is ASCII. For general XML " @@ -3281,6 +3809,32 @@ msgstr "" "significant difference is that the constructor functions for creating new " "hashing objects are named differently. ::" +#: ../../whatsnew/2.5.rst:1891 +msgid "" +"# Old versions\n" +"h = md5.md5()\n" +"h = md5.new()\n" +"\n" +"# New version\n" +"h = hashlib.md5()\n" +"\n" +"# Old versions\n" +"h = sha.sha()\n" +"h = sha.new()\n" +"\n" +"# New version\n" +"h = hashlib.sha1()\n" +"\n" +"# Hash that weren't previously available\n" +"h = hashlib.sha224()\n" +"h = hashlib.sha256()\n" +"h = hashlib.sha384()\n" +"h = hashlib.sha512()\n" +"\n" +"# Alternative form\n" +"h = hashlib.new('md5') # Provide algorithm as a string" +msgstr "" + #: ../../whatsnew/2.5.rst:1914 msgid "" "Once a hash object has been created, its methods are the same as before: " @@ -3361,6 +3915,10 @@ msgstr "" "represents the database. Here the data will be stored in the :file:`/tmp/" "example` file::" +#: ../../whatsnew/2.5.rst:1956 +msgid "conn = sqlite3.connect('/tmp/example')" +msgstr "" + #: ../../whatsnew/2.5.rst:1958 msgid "" "You can also supply the special name ``:memory:`` to create a database in " @@ -3377,6 +3935,20 @@ msgstr "" "Once you have a :class:`Connection`, you can create a :class:`Cursor` " "object and call its :meth:`execute` method to perform SQL commands::" +#: ../../whatsnew/2.5.rst:1963 +msgid "" +"c = conn.cursor()\n" +"\n" +"# Create table\n" +"c.execute('''create table stocks\n" +"(date text, trans text, symbol text,\n" +" qty real, price real)''')\n" +"\n" +"# Insert a row of data\n" +"c.execute(\"\"\"insert into stocks\n" +" values ('2006-01-05','BUY','RHAT',100,35.14)\"\"\")" +msgstr "" + #: ../../whatsnew/2.5.rst:1974 msgid "" "Usually your SQL operations will need to use values from Python variables. " @@ -3403,6 +3975,24 @@ msgstr "" "(Other database modules may use a different placeholder, such as ``%s`` or " "``:1``.) For example::" +#: ../../whatsnew/2.5.rst:1983 +msgid "" +"# Never do this -- insecure!\n" +"symbol = 'IBM'\n" +"c.execute(\"... where symbol = '%s'\" % symbol)\n" +"\n" +"# Do this instead\n" +"t = (symbol,)\n" +"c.execute('select * from stocks where symbol=?', t)\n" +"\n" +"# Larger example\n" +"for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),\n" +" ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),\n" +" ('2006-04-06', 'SELL', 'IBM', 500, 53.00),\n" +" ):\n" +" c.execute('insert into stocks values (?,?,?,?,?)', t)" +msgstr "" + #: ../../whatsnew/2.5.rst:1998 msgid "" "To retrieve data after executing a SELECT statement, you can either treat " @@ -3419,6 +4009,20 @@ msgstr "" msgid "This example uses the iterator form::" msgstr "This example uses the iterator form::" +#: ../../whatsnew/2.5.rst:2005 +msgid "" +">>> c = conn.cursor()\n" +">>> c.execute('select * from stocks order by price')\n" +">>> for row in c:\n" +"... print row\n" +"...\n" +"(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)\n" +"(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)\n" +"(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)\n" +"(u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)\n" +">>>" +msgstr "" + #: ../../whatsnew/2.5.rst:2016 msgid "" "For more information about the SQL dialect supported by SQLite, see https://" @@ -3485,6 +4089,18 @@ msgstr "" "this server is useful for debugging but isn't intended for production use. " "Setting up a server takes only a few lines of code::" +#: ../../whatsnew/2.5.rst:2053 +msgid "" +"from wsgiref import simple_server\n" +"\n" +"wsgi_app = ...\n" +"\n" +"host = ''\n" +"port = 8000\n" +"httpd = simple_server.make_server(host, port, wsgi_app)\n" +"httpd.serve_forever()" +msgstr "" + #: ../../whatsnew/2.5.rst:2068 msgid "" "https://web.archive.org/web/20160331090247/http://wsgi.readthedocs.org/en/" @@ -3511,7 +4127,7 @@ msgstr "Mudanças a construções e API C" #: ../../whatsnew/2.5.rst:2082 msgid "Changes to Python's build process and to the C API include:" -msgstr "Changes to Python's build process and to the C API include:" +msgstr "As alterações no processo de construção do Python e na API C incluem:" #: ../../whatsnew/2.5.rst:2084 msgid "" @@ -3571,6 +4187,18 @@ msgstr "" "`compile` built-in and specifying ``_ast.PyCF_ONLY_AST`` as the value of " "the *flags* parameter::" +#: ../../whatsnew/2.5.rst:2108 +msgid "" +"from _ast import PyCF_ONLY_AST\n" +"ast = compile(\"\"\"a=0\n" +"for i in range(10):\n" +" a += i\n" +"\"\"\", \"\", 'exec', PyCF_ONLY_AST)\n" +"\n" +"assignment = ast.body[0]\n" +"for_loop = ast.body[1]" +msgstr "" + #: ../../whatsnew/2.5.rst:2117 msgid "" "No official documentation has been written for the AST code yet, but :pep:" @@ -3757,6 +4385,12 @@ msgstr "" "unlikely case that your extensions were using it, you can replace it by " "something like the following::" +#: ../../whatsnew/2.5.rst:2199 +msgid "" +"range = PyObject_CallFunction((PyObject*) &PyRange_Type, \"lll\",\n" +" start, stop, step);" +msgstr "" + #: ../../whatsnew/2.5.rst:2208 msgid "Port-Specific Changes" msgstr "Port-Specific Changes" diff --git a/whatsnew/2.6.po b/whatsnew/2.6.po index 9c0afe82a..f5409777b 100644 --- a/whatsnew/2.6.po +++ b/whatsnew/2.6.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Raphael Mendonça, 2021 -# Victor Matheus Castro , 2021 -# Augusta Carla Klug , 2021 -# Claudio Rogerio Carvalho Filho , 2024 -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:51+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -458,6 +452,12 @@ msgstr "" "The ':keyword:`with`' statement is a control-flow structure whose basic " "structure is::" +#: ../../whatsnew/2.6.rst:266 +msgid "" +"with expression [as variable]:\n" +" with-block" +msgstr "" + #: ../../whatsnew/2.6.rst:269 msgid "" "The expression is evaluated, and it should result in an object that supports " @@ -500,6 +500,14 @@ msgstr "" "can be used with the ':keyword:`with`' statement. File objects are one " "example::" +#: ../../whatsnew/2.6.rst:285 +msgid "" +"with open('/etc/passwd', 'r') as f:\n" +" for line in f:\n" +" print line\n" +" ... more processing code ..." +msgstr "" + #: ../../whatsnew/2.6.rst:290 msgid "" "After this statement has executed, the file object in *f* will have been " @@ -526,6 +534,14 @@ msgstr "" "The :mod:`threading` module's locks and condition variables also support the " "':keyword:`with`' statement::" +#: ../../whatsnew/2.6.rst:302 +msgid "" +"lock = threading.Lock()\n" +"with lock:\n" +" # Critical section of code\n" +" ..." +msgstr "" + #: ../../whatsnew/2.6.rst:307 msgid "" "The lock is acquired before the block is executed and always released once " @@ -544,6 +560,20 @@ msgstr "" "to save and restore the current decimal context, which encapsulates the " "desired precision and rounding characteristics for computations::" +#: ../../whatsnew/2.6.rst:314 +msgid "" +"from decimal import Decimal, Context, localcontext\n" +"\n" +"# Displays with default precision of 28 digits\n" +"v = Decimal('578')\n" +"print v.sqrt()\n" +"\n" +"with localcontext(Context(prec=16)):\n" +" # All code in this block uses a precision of 16 digits.\n" +" # The original context is restored on exiting the block.\n" +" print v.sqrt()" +msgstr "" + #: ../../whatsnew/2.6.rst:329 msgid "Writing Context Managers" msgstr "Writing Context Managers" @@ -650,6 +680,15 @@ msgstr "" "Vamos supor que exista um objeto representando uma conexão com o banco de " "dados. Nosso objetivo será permitir que o usuário escreva código como este:" +#: ../../whatsnew/2.6.rst:373 +msgid "" +"db_connection = DatabaseConnection()\n" +"with db_connection as cursor:\n" +" cursor.execute('insert into ...')\n" +" cursor.execute('delete from ...')\n" +" # ... more operations ..." +msgstr "" + #: ../../whatsnew/2.6.rst:379 msgid "" "The transaction should be committed if the code in the block runs flawlessly " @@ -660,6 +699,18 @@ msgstr "" "perfeitamente ou revertida se houver uma exceção. Aqui está a interface " "básica para :class:`DatabaseConnection` que presumirei::" +#: ../../whatsnew/2.6.rst:383 +msgid "" +"class DatabaseConnection:\n" +" # Database interface\n" +" def cursor(self):\n" +" \"Returns a cursor object and starts a new transaction\"\n" +" def commit(self):\n" +" \"Commits current transaction\"\n" +" def rollback(self):\n" +" \"Rolls back current transaction\"" +msgstr "" + #: ../../whatsnew/2.6.rst:392 msgid "" "The :meth:`~object.__enter__` method is pretty easy, having only to start a " @@ -674,6 +725,16 @@ msgstr "" "cursor`` to their ':keyword:`with`' statement to bind the cursor to a " "variable name. ::" +#: ../../whatsnew/2.6.rst:397 +msgid "" +"class DatabaseConnection:\n" +" ...\n" +" def __enter__(self):\n" +" # Code to start a new transaction\n" +" cursor = self.cursor()\n" +" return cursor" +msgstr "" + #: ../../whatsnew/2.6.rst:404 msgid "" "The :meth:`~object.__exit__` method is the most complicated because it's " @@ -698,6 +759,20 @@ msgstr "" "will be re-raised automatically. If you wished, you could be more explicit " "and add a :keyword:`return` statement at the marked location. ::" +#: ../../whatsnew/2.6.rst:414 +msgid "" +"class DatabaseConnection:\n" +" ...\n" +" def __exit__(self, type, value, tb):\n" +" if tb is None:\n" +" # No exception, so commit\n" +" self.commit()\n" +" else:\n" +" # Exception occurred, so rollback.\n" +" self.rollback()\n" +" # return False" +msgstr "" + #: ../../whatsnew/2.6.rst:429 msgid "The contextlib module" msgstr "The contextlib module" @@ -740,6 +815,26 @@ msgstr "" "Using this decorator, our database example from the previous section could " "be written as::" +#: ../../whatsnew/2.6.rst:446 +msgid "" +"from contextlib import contextmanager\n" +"\n" +"@contextmanager\n" +"def db_transaction(connection):\n" +" cursor = connection.cursor()\n" +" try:\n" +" yield cursor\n" +" except:\n" +" connection.rollback()\n" +" raise\n" +" else:\n" +" connection.commit()\n" +"\n" +"db = DatabaseConnection()\n" +"with db_transaction(db) as cursor:\n" +" ..." +msgstr "" + #: ../../whatsnew/2.6.rst:463 msgid "" "The :mod:`contextlib` module also has a ``nested(mgr1, mgr2, ...)`` function " @@ -754,6 +849,13 @@ msgstr "" "with`' statement both starts a database transaction and acquires a thread " "lock::" +#: ../../whatsnew/2.6.rst:468 +msgid "" +"lock = threading.Lock()\n" +"with nested (db_transaction(db), lock) as (cursor, locked):\n" +" ..." +msgstr "" + #: ../../whatsnew/2.6.rst:472 msgid "" "Finally, the :func:`closing` function returns its argument so that it can be " @@ -764,6 +866,16 @@ msgstr "" "bound to a variable, and calls the argument's ``.close()`` method at the end " "of the block. ::" +#: ../../whatsnew/2.6.rst:476 +msgid "" +"import urllib, sys\n" +"from contextlib import closing\n" +"\n" +"with closing(urllib.urlopen('http://www.yahoo.com')) as f:\n" +" for line in f:\n" +" sys.stdout.write(line)" +msgstr "" + #: ../../whatsnew/2.6.rst:486 msgid ":pep:`343` - The \"with\" statement" msgstr ":pep:`343` - A instrução \"with\"" @@ -800,25 +912,18 @@ msgstr "" #: ../../whatsnew/2.6.rst:505 msgid "" -"The fix for Python 2.6 adds a :attr:`__package__` attribute to modules. " -"When this attribute is present, relative imports will be relative to the " -"value of this attribute instead of the :attr:`__name__` attribute." -msgstr "" -"The fix for Python 2.6 adds a :attr:`__package__` attribute to modules. When " +"The fix for Python 2.6 adds a :attr:`module.__package__` attribute. When " "this attribute is present, relative imports will be relative to the value of " -"this attribute instead of the :attr:`__name__` attribute." +"this attribute instead of the :attr:`~module.__name__` attribute." +msgstr "" #: ../../whatsnew/2.6.rst:510 msgid "" -"PEP 302-style importers can then set :attr:`__package__` as necessary. The :" -"mod:`runpy` module that implements the :option:`-m` switch now does this, so " -"relative imports will now work correctly in scripts running from inside a " -"package." +"PEP 302-style importers can then set :attr:`~module.__package__` as " +"necessary. The :mod:`runpy` module that implements the :option:`-m` switch " +"now does this, so relative imports will now work correctly in scripts " +"running from inside a package." msgstr "" -"PEP 302-style importers can then set :attr:`__package__` as necessary. The :" -"mod:`runpy` module that implements the :option:`-m` switch now does this, so " -"relative imports will now work correctly in scripts running from inside a " -"package." #: ../../whatsnew/2.6.rst:520 msgid "PEP 370: Per-user ``site-packages`` Directory" @@ -942,6 +1047,39 @@ msgstr "" "function doing the calculation is written strangely so that it takes " "significantly longer when the input argument is a multiple of 4." +#: ../../whatsnew/2.6.rst:584 +msgid "" +"import time\n" +"from multiprocessing import Process, Queue\n" +"\n" +"\n" +"def factorial(queue, N):\n" +" \"Compute a factorial.\"\n" +" # If N is a multiple of 4, this function will take much longer.\n" +" if (N % 4) == 0:\n" +" time.sleep(.05 * N/4)\n" +"\n" +" # Calculate the result\n" +" fact = 1L\n" +" for i in range(1, N+1):\n" +" fact = fact * i\n" +"\n" +" # Put the result on the queue\n" +" queue.put(fact)\n" +"\n" +"if __name__ == '__main__':\n" +" queue = Queue()\n" +"\n" +" N = 5\n" +"\n" +" p = Process(target=factorial, args=(queue, N))\n" +" p.start()\n" +" p.join()\n" +"\n" +" result = queue.get()\n" +" print 'Factorial', N, '=', result" +msgstr "" + #: ../../whatsnew/2.6.rst:614 msgid "" "A :class:`~queue.Queue` is used to communicate the result of the factorial. " @@ -976,10 +1114,33 @@ msgstr "" "`Pool` to spread requests across 5 worker processes and retrieve a list of " "results::" +#: ../../whatsnew/2.6.rst:630 +msgid "" +"from multiprocessing import Pool\n" +"\n" +"def factorial(N, dictionary):\n" +" \"Compute a factorial.\"\n" +" ...\n" +"p = Pool(5)\n" +"result = p.map(factorial, range(1, 1000, 10))\n" +"for v in result:\n" +" print v" +msgstr "" + #: ../../whatsnew/2.6.rst:640 msgid "This produces the following output::" msgstr "This produces the following output::" +#: ../../whatsnew/2.6.rst:642 +msgid "" +"1\n" +"39916800\n" +"51090942171709440000\n" +"8222838654177922817725562880000000\n" +"33452526613163807108170062053440751665152000000000\n" +"..." +msgstr "" + #: ../../whatsnew/2.6.rst:649 msgid "" "The other high-level interface, the :class:`Manager` class, creates a " @@ -1001,10 +1162,55 @@ msgstr "" "doesn't matter in this example. :class:`Manager`'s methods also include :" "meth:`Lock`, :meth:`RLock`, and :meth:`Semaphore` to create shared locks.)" +#: ../../whatsnew/2.6.rst:661 +msgid "" +"import time\n" +"from multiprocessing import Pool, Manager\n" +"\n" +"def factorial(N, dictionary):\n" +" \"Compute a factorial.\"\n" +" # Calculate the result\n" +" fact = 1L\n" +" for i in range(1, N+1):\n" +" fact = fact * i\n" +"\n" +" # Store result in dictionary\n" +" dictionary[N] = fact\n" +"\n" +"if __name__ == '__main__':\n" +" p = Pool(5)\n" +" mgr = Manager()\n" +" d = mgr.dict() # Create shared dictionary\n" +"\n" +" # Run tasks using the pool\n" +" for N in range(1, 1000, 10):\n" +" p.apply_async(factorial, (N, d))\n" +"\n" +" # Mark pool as closed -- no more tasks can be added.\n" +" p.close()\n" +"\n" +" # Wait for tasks to exit\n" +" p.join()\n" +"\n" +" # Output results\n" +" for k, v in sorted(d.items()):\n" +" print k, v" +msgstr "" + #: ../../whatsnew/2.6.rst:693 msgid "This will produce the output::" msgstr "This will produce the output::" +#: ../../whatsnew/2.6.rst:695 +msgid "" +"1 1\n" +"11 39916800\n" +"21 51090942171709440000\n" +"31 8222838654177922817725562880000000\n" +"41 33452526613163807108170062053440751665152000000000\n" +"51 15511187532873822802242430164693032110632597200169861120000..." +msgstr "" + #: ../../whatsnew/2.6.rst:704 msgid "The documentation for the :mod:`multiprocessing` module." msgstr "The documentation for the :mod:`multiprocessing` module." @@ -1047,10 +1253,28 @@ msgstr "" "formatting template uses curly brackets (``{``, ``}``) as special " "characters::" +#: ../../whatsnew/2.6.rst:726 +msgid "" +">>> # Substitute positional argument 0 into the string.\n" +">>> \"User ID: {0}\".format(\"root\")\n" +"'User ID: root'\n" +">>> # Use the named keyword arguments\n" +">>> \"User ID: {uid} Last seen: {last_login}\".format(\n" +"... uid=\"root\",\n" +"... last_login = \"5 Mar 2008 07:20\")\n" +"'User ID: root Last seen: 5 Mar 2008 07:20'" +msgstr "" + #: ../../whatsnew/2.6.rst:735 msgid "Curly brackets can be escaped by doubling them::" msgstr "Curly brackets can be escaped by doubling them::" +#: ../../whatsnew/2.6.rst:737 +msgid "" +">>> \"Empty dict: {{}}\".format()\n" +"\"Empty dict: {}\"" +msgstr "" + #: ../../whatsnew/2.6.rst:740 msgid "" "Field names can be integers indicating positional arguments, such as ``{0}" @@ -1061,6 +1285,20 @@ msgstr "" "``, ``{1}``, etc. or names of keyword arguments. You can also supply " "compound field names that read attributes or access dictionary keys::" +#: ../../whatsnew/2.6.rst:744 +msgid "" +">>> import sys\n" +">>> print 'Platform: {0.platform}\\nPython version: {0.version}'." +"format(sys)\n" +"Platform: darwin\n" +"Python version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41)\n" +"[GCC 4.0.1 (Apple Computer, Inc. build 5367)]'\n" +"\n" +">>> import mimetypes\n" +">>> 'Content-type: {0[.mp4]}'.format(mimetypes.types_map)\n" +"'Content-type: video/mp4'" +msgstr "" + #: ../../whatsnew/2.6.rst:754 msgid "" "Note that when using dictionary-style notation such as ``[.mp4]``, you don't " @@ -1085,10 +1323,34 @@ msgstr "" "resulting string. The precise formatting used is also controllable by adding " "a colon followed by a format specifier. For example::" +#: ../../whatsnew/2.6.rst:764 +msgid "" +">>> # Field 0: left justify, pad to 15 characters\n" +">>> # Field 1: right justify, pad to 6 characters\n" +">>> fmt = '{0:15} ${1:>6}'\n" +">>> fmt.format('Registration', 35)\n" +"'Registration $ 35'\n" +">>> fmt.format('Tutorial', 50)\n" +"'Tutorial $ 50'\n" +">>> fmt.format('Banquet', 125)\n" +"'Banquet $ 125'" +msgstr "" + #: ../../whatsnew/2.6.rst:774 msgid "Format specifiers can reference other fields through nesting::" msgstr "Format specifiers can reference other fields through nesting::" +#: ../../whatsnew/2.6.rst:776 +msgid "" +">>> fmt = '{0:{1}}'\n" +">>> width = 15\n" +">>> fmt.format('Invoice #1234', width)\n" +"'Invoice #1234 '\n" +">>> width = 35\n" +">>> fmt.format('Invoice #1234', width)\n" +"'Invoice #1234 '" +msgstr "" + #: ../../whatsnew/2.6.rst:784 msgid "The alignment of a field within the desired width can be specified:" msgstr "The alignment of a field within the desired width can be specified:" @@ -1143,6 +1405,14 @@ msgstr "" "the value is formatted. For example, floating-point numbers can be formatted " "as a general number or in exponential notation::" +#: ../../whatsnew/2.6.rst:799 +msgid "" +">>> '{0:g}'.format(3.75)\n" +"'3.75'\n" +">>> '{0:e}'.format(3.75)\n" +"'3.750000e+00'" +msgstr "" + #: ../../whatsnew/2.6.rst:804 msgid "" "A variety of presentation types are available. Consult the 2.6 " @@ -1257,6 +1527,15 @@ msgstr "" "Classes and types can define a :meth:`__format__` method to control how " "they're formatted. It receives a single argument, the format specifier::" +#: ../../whatsnew/2.6.rst:830 +msgid "" +"def __format__(self, format_spec):\n" +" if isinstance(format_spec, unicode):\n" +" return unicode(str(self))\n" +" else:\n" +" return str(self)" +msgstr "" + #: ../../whatsnew/2.6.rst:836 msgid "" "There's also a :func:`format` builtin that will format a single value. It " @@ -1265,6 +1544,12 @@ msgstr "" "There's also a :func:`format` builtin that will format a single value. It " "calls the type's :meth:`__format__` method with the provided specifier::" +#: ../../whatsnew/2.6.rst:840 +msgid "" +">>> format(75.6564, '.2f')\n" +"'75.66'" +msgstr "" + #: ../../whatsnew/2.6.rst:846 msgid ":ref:`formatstrings`" msgstr ":ref:`formatstrings`" @@ -1303,10 +1588,20 @@ msgstr "" "Python 2.6 has a ``__future__`` import that removes ``print`` as language " "syntax, letting you use the functional form instead. For example::" +#: ../../whatsnew/2.6.rst:866 +msgid "" +">>> from __future__ import print_function\n" +">>> print('# of entries', len(dictionary), file=sys.stderr)" +msgstr "" + #: ../../whatsnew/2.6.rst:869 msgid "The signature of the new function is::" msgstr "The signature of the new function is::" +#: ../../whatsnew/2.6.rst:871 +msgid "def print(*args, sep=' ', end='\\n', file=None)" +msgstr "" + #: ../../whatsnew/2.6.rst:874 msgid "The parameters are:" msgstr "The parameters are:" @@ -1351,6 +1646,14 @@ msgstr "" "One error that Python programmers occasionally make is writing the following " "code::" +#: ../../whatsnew/2.6.rst:897 +msgid "" +"try:\n" +" ...\n" +"except TypeError, ValueError: # Wrong!\n" +" ..." +msgstr "" + #: ../../whatsnew/2.6.rst:902 msgid "" "The author is probably trying to catch both :exc:`TypeError` and :exc:" @@ -1365,6 +1668,14 @@ msgstr "" "local name ``\"ValueError\"``. The :exc:`ValueError` exception will not be " "caught at all. The correct code specifies a tuple of exceptions::" +#: ../../whatsnew/2.6.rst:909 +msgid "" +"try:\n" +" ...\n" +"except (TypeError, ValueError):\n" +" ..." +msgstr "" + #: ../../whatsnew/2.6.rst:914 msgid "" "This error happens because the use of the comma here is ambiguous: does it " @@ -1385,6 +1696,14 @@ msgstr "" "\"as\". To catch an exception and store the exception object in the variable " "``exc``, you must write::" +#: ../../whatsnew/2.6.rst:922 +msgid "" +"try:\n" +" ...\n" +"except TypeError as exc:\n" +" ..." +msgstr "" + #: ../../whatsnew/2.6.rst:927 msgid "" "Python 3.0 will only support the use of \"as\", and therefore interprets the " @@ -1465,6 +1784,16 @@ msgstr "" "become Unicode strings. This means that ``\\u`` escape sequences can be used " "to include Unicode characters::" +#: ../../whatsnew/2.6.rst:970 +msgid "" +"from __future__ import unicode_literals\n" +"\n" +"s = ('\\u751f\\u3080\\u304e\\u3000\\u751f\\u3054'\n" +" '\\u3081\\u3000\\u751f\\u305f\\u307e\\u3054')\n" +"\n" +"print len(s) # 12 Unicode characters" +msgstr "" + #: ../../whatsnew/2.6.rst:977 msgid "" "At the C level, Python 3.0 will rename the existing 8-bit string type, " @@ -1489,6 +1818,20 @@ msgstr "" "Instances of the :class:`bytes` type are immutable just as strings are. A " "new :class:`bytearray` type stores a mutable sequence of bytes::" +#: ../../whatsnew/2.6.rst:988 +msgid "" +">>> bytearray([65, 66, 67])\n" +"bytearray(b'ABC')\n" +">>> b = bytearray(u'\\u21ef\\u3244', 'utf-8')\n" +">>> b\n" +"bytearray(b'\\xe2\\x87\\xaf\\xe3\\x89\\x84')\n" +">>> b[0] = '\\xe3'\n" +">>> b\n" +"bytearray(b'\\xe3\\x87\\xaf\\xe3\\x89\\x84')\n" +">>> unicode(str(b), 'utf-8')\n" +"u'\\u31ef \\u3244'" +msgstr "" + #: ../../whatsnew/2.6.rst:999 msgid "" "Byte arrays support most of the methods of string types, such as :meth:" @@ -1499,6 +1842,15 @@ msgstr "" "`startswith`/:meth:`endswith`, :meth:`find`/:meth:`rfind`, and some of the " "methods of lists, such as :meth:`append`, :meth:`pop`, and :meth:`reverse`." +#: ../../whatsnew/2.6.rst:1006 +msgid "" +">>> b = bytearray('ABC')\n" +">>> b.append('d')\n" +">>> b.append(ord('e'))\n" +">>> b\n" +"bytearray(b'ABCde')" +msgstr "" + #: ../../whatsnew/2.6.rst:1012 msgid "" "There's also a corresponding C API, with :c:func:`PyByteArray_FromObject`, :" @@ -1835,6 +2187,14 @@ msgstr "" "You can derive your own classes from a particular ABC to indicate they " "support that ABC's interface::" +#: ../../whatsnew/2.6.rst:1190 +msgid "" +"import collections\n" +"\n" +"class Storage(collections.MutableMapping):\n" +" ..." +msgstr "" + #: ../../whatsnew/2.6.rst:1196 msgid "" "Alternatively, you could write the class without deriving from the desired " @@ -1845,6 +2205,16 @@ msgstr "" "ABC and instead register the class by calling the ABC's :meth:`register` " "method::" +#: ../../whatsnew/2.6.rst:1200 +msgid "" +"import collections\n" +"\n" +"class Storage:\n" +" ...\n" +"\n" +"collections.MutableMapping.register(Storage)" +msgstr "" + #: ../../whatsnew/2.6.rst:1207 msgid "" "For classes that you write, deriving from the ABC is probably clearer. The :" @@ -1859,6 +2229,14 @@ msgstr "" "third-party class implements an ABC. For example, if you defined a :class:" "`PrintableType` ABC, it's legal to do::" +#: ../../whatsnew/2.6.rst:1214 +msgid "" +"# Register Python's types\n" +"PrintableType.register(int)\n" +"PrintableType.register(float)\n" +"PrintableType.register(str)" +msgstr "" + #: ../../whatsnew/2.6.rst:1219 msgid "" "Classes should obey the semantics specified by an ABC, but Python can't " @@ -1877,6 +2255,13 @@ msgstr "" "To check whether an object supports a particular interface, you can now " "write::" +#: ../../whatsnew/2.6.rst:1226 +msgid "" +"def func(d):\n" +" if not isinstance(d, collections.MutableMapping):\n" +" raise ValueError(\"Mapping object expected, not %r\" % d)" +msgstr "" + #: ../../whatsnew/2.6.rst:1230 msgid "" "Don't feel that you must now begin writing lots of checks as in the above " @@ -1901,6 +2286,26 @@ msgstr "" "You can write your own ABCs by using ``abc.ABCMeta`` as the metaclass in a " "class definition::" +#: ../../whatsnew/2.6.rst:1240 +msgid "" +"from abc import ABCMeta, abstractmethod\n" +"\n" +"class Drawable():\n" +" __metaclass__ = ABCMeta\n" +"\n" +" @abstractmethod\n" +" def draw(self, x, y, scale=1.0):\n" +" pass\n" +"\n" +" def draw_doubled(self, x, y):\n" +" self.draw(x, y, scale=2.0)\n" +"\n" +"\n" +"class Square(Drawable):\n" +" def draw(self, x, y, scale):\n" +" ..." +msgstr "" + #: ../../whatsnew/2.6.rst:1258 msgid "" "In the :class:`Drawable` ABC above, the :meth:`draw_doubled` method renders " @@ -1931,6 +2336,19 @@ msgstr "" "when you actually try to create an instance of a subclass lacking the " "method::" +#: ../../whatsnew/2.6.rst:1272 +msgid "" +">>> class Circle(Drawable):\n" +"... pass\n" +"...\n" +">>> c = Circle()\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: Can't instantiate abstract class Circle with abstract methods " +"draw\n" +">>>" +msgstr "" + #: ../../whatsnew/2.6.rst:1281 msgid "" "Abstract data attributes can be declared using the ``@abstractproperty`` " @@ -1939,6 +2357,16 @@ msgstr "" "Abstract data attributes can be declared using the ``@abstractproperty`` " "decorator::" +#: ../../whatsnew/2.6.rst:1284 +msgid "" +"from abc import abstractproperty\n" +"...\n" +"\n" +"@abstractproperty\n" +"def readonly(self):\n" +" return self._x" +msgstr "" + #: ../../whatsnew/2.6.rst:1291 msgid "Subclasses must then define a :meth:`readonly` property." msgstr "Subclasses must then define a :meth:`readonly` property." @@ -1977,6 +2405,14 @@ msgstr "" "Python 2.6 doesn't drop support for a leading 0 signalling an octal number, " "but it does add support for \"0o\" and \"0b\"::" +#: ../../whatsnew/2.6.rst:1315 +msgid "" +">>> 0o21, 2*8 + 1\n" +"(17, 17)\n" +">>> 0b101111\n" +"47" +msgstr "" + #: ../../whatsnew/2.6.rst:1320 msgid "" "The :func:`oct` builtin still returns numbers prefixed with a leading zero, " @@ -1987,6 +2423,16 @@ msgstr "" "and a new :func:`bin` builtin returns the binary representation for a " "number::" +#: ../../whatsnew/2.6.rst:1324 +msgid "" +">>> oct(42)\n" +"'052'\n" +">>> future_builtins.oct(42)\n" +"'0o52'\n" +">>> bin(173)\n" +"'0b10101101'" +msgstr "" + #: ../../whatsnew/2.6.rst:1331 msgid "" "The :func:`int` and :func:`long` builtins will now accept the \"0o\" and " @@ -1999,6 +2445,18 @@ msgstr "" "argument is zero (signalling that the base used should be determined from " "the string)::" +#: ../../whatsnew/2.6.rst:1336 +msgid "" +">>> int ('0o52', 0)\n" +"42\n" +">>> int('1101', 2)\n" +"13\n" +">>> int('0b1101', 2)\n" +"13\n" +">>> int('0b1101', 0)\n" +"13" +msgstr "" + #: ../../whatsnew/2.6.rst:1348 msgid ":pep:`3127` - Integer Literal Support and Syntax" msgstr ":pep:`3127` - Integer Literal Support and Syntax" @@ -2019,10 +2477,26 @@ msgstr "" "Decorators have been extended from functions to classes. It's now legal to " "write::" +#: ../../whatsnew/2.6.rst:1362 +msgid "" +"@foo\n" +"@bar\n" +"class A:\n" +" pass" +msgstr "" + #: ../../whatsnew/2.6.rst:1367 msgid "This is equivalent to::" msgstr "Isso equivale a::" +#: ../../whatsnew/2.6.rst:1369 +msgid "" +"class A:\n" +" pass\n" +"\n" +"A = foo(bar(A))" +msgstr "" + #: ../../whatsnew/2.6.rst:1376 msgid ":pep:`3129` - Class Decorators" msgstr ":pep:`3129` - Class Decorators" @@ -2169,15 +2643,35 @@ msgstr "" "The :class:`Fraction` constructor takes two :class:`Integral` values that " "will be the numerator and denominator of the resulting fraction. ::" +#: ../../whatsnew/2.6.rst:1445 +msgid "" +">>> from fractions import Fraction\n" +">>> a = Fraction(2, 3)\n" +">>> b = Fraction(2, 5)\n" +">>> float(a), float(b)\n" +"(0.66666666666666663, 0.40000000000000002)\n" +">>> a+b\n" +"Fraction(16, 15)\n" +">>> a/b\n" +"Fraction(5, 3)" +msgstr "" + #: ../../whatsnew/2.6.rst:1455 msgid "" "For converting floating-point numbers to rationals, the float type now has " -"an :meth:`as_integer_ratio()` method that returns the numerator and " +"an :meth:`as_integer_ratio` method that returns the numerator and " "denominator for a fraction that evaluates to the same floating-point value::" msgstr "" -"For converting floating-point numbers to rationals, the float type now has " -"an :meth:`as_integer_ratio()` method that returns the numerator and " -"denominator for a fraction that evaluates to the same floating-point value::" + +#: ../../whatsnew/2.6.rst:1460 +msgid "" +">>> (2.5) .as_integer_ratio()\n" +"(5, 2)\n" +">>> (3.1415) .as_integer_ratio()\n" +"(7074029114692207L, 2251799813685248L)\n" +">>> (1./3) .as_integer_ratio()\n" +"(6004799503160661L, 18014398509481984L)" +msgstr "" #: ../../whatsnew/2.6.rst:1467 msgid "" @@ -2249,6 +2743,18 @@ msgstr "" "arguments, you are no longer required to use a Python dictionary; any " "mapping will now work::" +#: ../../whatsnew/2.6.rst:1502 +msgid "" +">>> def f(**kw):\n" +"... print sorted(kw)\n" +"...\n" +">>> ud=UserDict.UserDict()\n" +">>> ud['a'] = 1\n" +">>> ud['b'] = 'string'\n" +">>> f(**ud)\n" +"['a', 'b']" +msgstr "" + #: ../../whatsnew/2.6.rst:1511 msgid "(Contributed by Alexander Belopolsky; :issue:`1686487`.)" msgstr "(Contributed by Alexander Belopolsky; :issue:`1686487`.)" @@ -2261,6 +2767,15 @@ msgstr "" "It's also become legal to provide keyword arguments after a ``*args`` " "argument to a function call. ::" +#: ../../whatsnew/2.6.rst:1516 +msgid "" +">>> def f(*args, **kw):\n" +"... print args, kw\n" +"...\n" +">>> f(1,2,3, *(4,5,6), keyword=13)\n" +"(1, 2, 3, 4, 5, 6) {'keyword': 13}" +msgstr "" + #: ../../whatsnew/2.6.rst:1522 msgid "" "Previously this would have been a syntax error. (Contributed by Amaury " @@ -2289,6 +2804,15 @@ msgstr "" "Tuples now have :meth:`index` and :meth:`count` methods matching the list " "type's :meth:`index` and :meth:`count` methods::" +#: ../../whatsnew/2.6.rst:1534 +msgid "" +">>> t = (0,1,2,3,4,0,1,2)\n" +">>> t.index(3)\n" +"3\n" +">>> t.count(0)\n" +"2" +msgstr "" + #: ../../whatsnew/2.6.rst:1540 msgid "(Contributed by Raymond Hettinger)" msgstr "(Contributed by Raymond Hettinger)" @@ -2317,6 +2841,31 @@ msgstr "" "getter, setter or deleter function to an existing property. You would use " "them like this::" +#: ../../whatsnew/2.6.rst:1554 +msgid "" +"class C(object):\n" +" @property\n" +" def x(self):\n" +" return self._x\n" +"\n" +" @x.setter\n" +" def x(self, value):\n" +" self._x = value\n" +"\n" +" @x.deleter\n" +" def x(self):\n" +" del self._x\n" +"\n" +"class D(C):\n" +" @C.x.getter\n" +" def x(self):\n" +" return self._x * 2\n" +"\n" +" @x.setter\n" +" def x(self, value):\n" +" self._x = value / 2" +msgstr "" + #: ../../whatsnew/2.6.rst:1576 msgid "" "Several methods of the built-in set types now accept multiple iterables: :" @@ -2327,6 +2876,15 @@ msgstr "" "meth:`intersection`, :meth:`intersection_update`, :meth:`union`, :meth:" "`update`, :meth:`difference` and :meth:`difference_update`." +#: ../../whatsnew/2.6.rst:1584 +msgid "" +">>> s=set('1234567890')\n" +">>> s.intersection('abc123', 'cdf246') # Intersection between all inputs\n" +"set(['2'])\n" +">>> s.difference('246', '789')\n" +"set(['1', '0', '3', '5'])" +msgstr "" + #: ../../whatsnew/2.6.rst:1590 ../../whatsnew/2.6.rst:1875 #: ../../whatsnew/2.6.rst:1896 msgid "(Contributed by Raymond Hettinger.)" @@ -2371,6 +2929,18 @@ msgstr "" "returns a string representation, and the ``float.fromhex()`` method converts " "a string back into a number::" +#: ../../whatsnew/2.6.rst:1610 +msgid "" +">>> a = 3.75\n" +">>> a.hex()\n" +"'0x1.e000000000000p+1'\n" +">>> float.fromhex('0x1.e000000000000p+1')\n" +"3.75\n" +">>> b=1./3\n" +">>> b.hex()\n" +"'0x1.5555555555555p-2'" +msgstr "" + #: ../../whatsnew/2.6.rst:1619 msgid "" "A numerical nicety: when creating a complex number from two floats on " @@ -2700,11 +3270,12 @@ msgid "" "file in the source tree for a more complete list of changes, or look through " "the Subversion logs for all the details." msgstr "" -"As in every release, Python's standard library received a number of " -"enhancements and bug fixes. Here's a partial list of the most notable " -"changes, sorted alphabetically by module name. Consult the :file:`Misc/NEWS` " -"file in the source tree for a more complete list of changes, or look through " -"the Subversion logs for all the details." +"Como em todas os lançamentos, a biblioteca padrão do Python recebeu diversas " +"melhorias e correções de bugs. Aqui está uma lista parcial das mudanças mais " +"notáveis, classificadas em ordem alfabética por nome do módulo. Consulte o " +"arquivo :file:`Misc/NEWS` na árvore de código-fonte para uma lista mais " +"completa de alterações, ou procure nos logs do Subversion para todos os " +"detalhes." #: ../../whatsnew/2.6.rst:1786 msgid "" @@ -2712,9 +3283,9 @@ msgid "" "maintained again, and a number of patches and bugfixes were applied. " "(Maintained by Josiah Carlson; see :issue:`1736190` for one patch.)" msgstr "" -"The :mod:`!asyncore` and :mod:`!asynchat` modules are being actively " -"maintained again, and a number of patches and bugfixes were applied. " -"(Maintained by Josiah Carlson; see :issue:`1736190` for one patch.)" +"Os módulos :mod:`!asyncore` e :mod:`!asynchat` estão sendo mantidos " +"ativamente novamente e várias correções e correções foram aplicadas. " +"(Mantido por Josiah Carlson; veja :issue:`1736190` para um patch.)" #: ../../whatsnew/2.6.rst:1791 msgid "" @@ -2856,6 +3427,27 @@ msgstr "" "fieldnames)`` is a factory function that creates subclasses of the standard " "tuple whose fields are accessible by name as well as index. For example::" +#: ../../whatsnew/2.6.rst:1852 +msgid "" +">>> var_type = collections.namedtuple('variable',\n" +"... 'id name type size')\n" +">>> # Names are separated by spaces or commas.\n" +">>> # 'id, name, type, size' would also work.\n" +">>> var_type._fields\n" +"('id', 'name', 'type', 'size')\n" +"\n" +">>> var = var_type(1, 'frequency', 'int', 4)\n" +">>> print var[0], var.id # Equivalent\n" +"1 1\n" +">>> print var[2], var.type # Equivalent\n" +"int int\n" +">>> var._asdict()\n" +"{'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}\n" +">>> v2 = var._replace(name='amplitude')\n" +">>> v2\n" +"variable(id=1, name='amplitude', type='int', size=4)" +msgstr "" + #: ../../whatsnew/2.6.rst:1870 msgid "" "Several places in the standard library that returned tuples have been " @@ -2880,6 +3472,20 @@ msgstr "" "size will be restricted to no more than *maxlen* items. Adding more items to " "a full deque causes old items to be discarded." +#: ../../whatsnew/2.6.rst:1885 +msgid "" +">>> from collections import deque\n" +">>> dq=deque(maxlen=3)\n" +">>> dq\n" +"deque([], maxlen=3)\n" +">>> dq.append(1); dq.append(2); dq.append(3)\n" +">>> dq\n" +"deque([1, 2, 3], maxlen=3)\n" +">>> dq.append(4)\n" +">>> dq\n" +"deque([2, 3, 4], maxlen=3)" +msgstr "" + #: ../../whatsnew/2.6.rst:1898 msgid "" "The :mod:`Cookie ` module's :class:`~http.cookies.Morsel` " @@ -2904,6 +3510,13 @@ msgstr "" "display attributes for a certain number of characters on a single line. " "(Contributed by Fabian Kreutz.)" +#: ../../whatsnew/2.6.rst:1909 +msgid "" +"# Boldface text starting at y=0,x=21\n" +"# and affecting the rest of the line.\n" +"stdscr.chgat(0, 21, curses.A_BOLD)" +msgstr "" + #: ../../whatsnew/2.6.rst:1913 msgid "" "The :class:`Textbox` class in the :mod:`curses.textpad` module now supports " @@ -2940,6 +3553,16 @@ msgstr "" "New features include some methods for some basic mathematical functions such " "as :meth:`exp` and :meth:`log10`::" +#: ../../whatsnew/2.6.rst:1928 +msgid "" +">>> Decimal(1).exp()\n" +"Decimal(\"2.718281828459045235360287471\")\n" +">>> Decimal(\"2.7182818\").ln()\n" +"Decimal(\"0.9999999895305022877376682436\")\n" +">>> Decimal(1000).log10()\n" +"Decimal(\"3\")" +msgstr "" + #: ../../whatsnew/2.6.rst:1935 msgid "" "The :meth:`as_tuple` method of :class:`Decimal` objects now returns a named " @@ -3031,6 +3654,12 @@ msgstr "" "new generator that returns the contents of all the iterators, also in sorted " "order. For example::" +#: ../../whatsnew/2.6.rst:1975 +msgid "" +">>> list(heapq.merge([1, 3, 5, 9], [2, 8, 16]))\n" +"[1, 2, 3, 5, 8, 9, 16]" +msgstr "" + #: ../../whatsnew/2.6.rst:1978 msgid "" "Another new function, ``heappushpop(heap, item)``, pushes *item* onto " @@ -3099,6 +3728,12 @@ msgstr "" "the elements; if some of the iterables are shorter than others, the missing " "values are set to *fillvalue*. For example::" +#: ../../whatsnew/2.6.rst:2010 +msgid "" +">>> tuple(itertools.izip_longest([1,2,3], [1,2,3,4,5]))\n" +"((1, 1), (2, 2), (3, 3), (None, 4), (None, 5))" +msgstr "" + #: ../../whatsnew/2.6.rst:2013 msgid "" "``product(iter1, iter2, ..., [repeat=N])`` returns the Cartesian product of " @@ -3109,6 +3744,14 @@ msgstr "" "the supplied iterables, a set of tuples containing every possible " "combination of the elements returned from each iterable. ::" +#: ../../whatsnew/2.6.rst:2017 +msgid "" +">>> list(itertools.product([1,2,3], [4,5,6]))\n" +"[(1, 4), (1, 5), (1, 6),\n" +" (2, 4), (2, 5), (2, 6),\n" +" (3, 4), (3, 5), (3, 6)]" +msgstr "" + #: ../../whatsnew/2.6.rst:2022 msgid "" "The optional *repeat* keyword argument is used for taking the product of an " @@ -3119,10 +3762,26 @@ msgstr "" "iterable or a set of iterables with themselves, repeated *N* times. With a " "single iterable argument, *N*-tuples are returned::" +#: ../../whatsnew/2.6.rst:2027 +msgid "" +">>> list(itertools.product([1,2], repeat=3))\n" +"[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),\n" +" (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]" +msgstr "" + #: ../../whatsnew/2.6.rst:2031 msgid "With two iterables, *2N*-tuples are returned. ::" msgstr "With two iterables, *2N*-tuples are returned. ::" +#: ../../whatsnew/2.6.rst:2033 +msgid "" +">>> list(itertools.product([1,2], [3,4], repeat=2))\n" +"[(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),\n" +" (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),\n" +" (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),\n" +" (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]" +msgstr "" + #: ../../whatsnew/2.6.rst:2039 msgid "" "``combinations(iterable, r)`` returns sub-sequences of length *r* from the " @@ -3131,6 +3790,17 @@ msgstr "" "``combinations(iterable, r)`` returns sub-sequences of length *r* from the " "elements of *iterable*. ::" +#: ../../whatsnew/2.6.rst:2042 +msgid "" +">>> list(itertools.combinations('123', 2))\n" +"[('1', '2'), ('1', '3'), ('2', '3')]\n" +">>> list(itertools.combinations('123', 3))\n" +"[('1', '2', '3')]\n" +">>> list(itertools.combinations('1234', 3))\n" +"[('1', '2', '3'), ('1', '2', '4'),\n" +" ('1', '3', '4'), ('2', '3', '4')]" +msgstr "" + #: ../../whatsnew/2.6.rst:2050 msgid "" "``permutations(iter[, r])`` returns all the permutations of length *r* of " @@ -3141,6 +3811,15 @@ msgstr "" "the iterable's elements. If *r* is not specified, it will default to the " "number of elements produced by the iterable. ::" +#: ../../whatsnew/2.6.rst:2054 +msgid "" +">>> list(itertools.permutations([1,2,3,4], 2))\n" +"[(1, 2), (1, 3), (1, 4),\n" +" (2, 1), (2, 3), (2, 4),\n" +" (3, 1), (3, 2), (3, 4),\n" +" (4, 1), (4, 2), (4, 3)]" +msgstr "" + #: ../../whatsnew/2.6.rst:2060 msgid "" "``itertools.chain(*iterables)`` is an existing function in :mod:`itertools` " @@ -3155,6 +3834,12 @@ msgstr "" "iterables. :func:`chain` will then return all the elements of the first " "iterable, then all the elements of the second, and so on. ::" +#: ../../whatsnew/2.6.rst:2067 +msgid "" +">>> list(itertools.chain.from_iterable([[1,2,3], [4,5,6]]))\n" +"[1, 2, 3, 4, 5, 6]" +msgstr "" + #: ../../whatsnew/2.6.rst:2070 msgid "(All contributed by Raymond Hettinger.)" msgstr "(All contributed by Raymond Hettinger.)" @@ -3301,6 +3986,14 @@ msgstr "" "a name and an optional set of arguments, returning a callable that will call " "the named function on any arguments passed to it. For example::" +#: ../../whatsnew/2.6.rst:2140 +msgid "" +">>> # Equivalent to lambda s: s.replace('old', 'new')\n" +">>> replacer = operator.methodcaller('replace', 'old', 'new')\n" +">>> replacer('old wine in old bottles')\n" +"'new wine in new bottles'" +msgstr "" + #: ../../whatsnew/2.6.rst:2145 msgid "(Contributed by Georg Brandl, after a suggestion by Gregory Petrosyan.)" msgstr "" @@ -3314,6 +4007,16 @@ msgstr "" "The :func:`attrgetter` function now accepts dotted names and performs the " "corresponding attribute lookups::" +#: ../../whatsnew/2.6.rst:2150 +msgid "" +">>> inst_name = operator.attrgetter(\n" +"... '__class__.__name__')\n" +">>> inst_name('')\n" +"'str'\n" +">>> inst_name(help)\n" +"'_Helper'" +msgstr "" + #: ../../whatsnew/2.6.rst:2157 msgid "(Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)" msgstr "(Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)" @@ -3462,6 +4165,20 @@ msgstr "" "returns the contents of resource files included with an installed Python " "package. For example::" +#: ../../whatsnew/2.6.rst:2225 +msgid "" +">>> import pkgutil\n" +">>> print pkgutil.get_data('test', 'exception_hierarchy.txt')\n" +"BaseException\n" +" +-- SystemExit\n" +" +-- KeyboardInterrupt\n" +" +-- GeneratorExit\n" +" +-- Exception\n" +" +-- StopIteration\n" +" +-- StandardError\n" +" ..." +msgstr "" + #: ../../whatsnew/2.6.rst:2236 msgid "(Contributed by Paul Moore; :issue:`2439`.)" msgstr "(Contributed by Paul Moore; :issue:`2439`.)" @@ -3544,13 +4261,10 @@ msgstr "" #: ../../whatsnew/2.6.rst:2276 msgid "" -"The :mod:`rlcompleter` module's :meth:`Completer.complete()` method will now " +"The :mod:`rlcompleter` module's :meth:`Completer.complete` method will now " "ignore exceptions triggered while evaluating a name. (Fixed by Lorenz " "Quack; :issue:`2250`.)" msgstr "" -"The :mod:`rlcompleter` module's :meth:`Completer.complete()` method will now " -"ignore exceptions triggered while evaluating a name. (Fixed by Lorenz " -"Quack; :issue:`2250`.)" #: ../../whatsnew/2.6.rst:2280 msgid "" @@ -3608,6 +4322,12 @@ msgstr "" "example copies a directory tree, but skips both :file:`.svn` directories and " "Emacs backup files, which have names ending with '~'::" +#: ../../whatsnew/2.6.rst:2307 +msgid "" +"shutil.copytree('Doc/library', '/tmp/library',\n" +" ignore=shutil.ignore_patterns('*~', '.svn'))" +msgstr "" + #: ../../whatsnew/2.6.rst:2310 msgid "(Contributed by Tarek Ziadé; :issue:`2663`.)" msgstr "(Contributed by Tarek Ziadé; :issue:`2663`.)" @@ -3880,6 +4600,12 @@ msgstr "" "supported. The default format is GNU tar; specify the ``format`` parameter " "to open a file using a different format::" +#: ../../whatsnew/2.6.rst:2441 +msgid "" +"tar = tarfile.open(\"output.tar\", \"w\",\n" +" format=tarfile.PAX_FORMAT)" +msgstr "" + #: ../../whatsnew/2.6.rst:2444 msgid "" "The new ``encoding`` and ``errors`` parameters specify an encoding and an " @@ -3986,6 +4712,14 @@ msgstr "" "specified list of exceptions. For example, a network test may ignore certain " "failures when connecting to an external web site::" +#: ../../whatsnew/2.6.rst:2493 +msgid "" +"with test_support.TransientResource(IOError,\n" +" errno=errno.ETIMEDOUT):\n" +" f = urllib.urlopen('https://sf.net')\n" +" ..." +msgstr "" + #: ../../whatsnew/2.6.rst:2498 msgid "" "Finally, :func:`check_warnings` resets the :mod:`warning` module's warning " @@ -3996,6 +4730,15 @@ msgstr "" "filters and returns an object that will record all warning messages " "triggered (:issue:`3781`)::" +#: ../../whatsnew/2.6.rst:2502 +msgid "" +"with test_support.check_warnings() as wrec:\n" +" warnings.simplefilter(\"always\")\n" +" # ... code that triggers a warning ...\n" +" assert str(wrec.message) == \"function is outdated\"\n" +" assert len(wrec.warnings) == 1, \"Multiple warnings raised\"" +msgstr "" + #: ../../whatsnew/2.6.rst:2508 msgid "(Contributed by Brett Cannon.)" msgstr "(Contributed by Brett Cannon.)" @@ -4010,6 +4753,23 @@ msgstr "" "beginnings and ends of the newly created lines by specifying " "``drop_whitespace=False`` as an argument::" +#: ../../whatsnew/2.6.rst:2515 +msgid "" +">>> S = \"\"\"This sentence has a bunch of\n" +"... extra whitespace.\"\"\"\n" +">>> print textwrap.fill(S, width=15)\n" +"This sentence\n" +"has a bunch\n" +"of extra\n" +"whitespace.\n" +">>> print textwrap.fill(S, drop_whitespace=False, width=15)\n" +"This sentence\n" +" has a bunch\n" +" of extra\n" +" whitespace.\n" +">>>" +msgstr "" + #: ../../whatsnew/2.6.rst:2529 msgid "(Contributed by Dwayne Bailey; :issue:`1581073`.)" msgstr "(Contributed by Dwayne Bailey; :issue:`1581073`.)" @@ -4101,8 +4861,8 @@ msgstr "" "system." #: ../../whatsnew/2.6.rst:2569 -msgid "Turtles now have an :meth:`undo()` method that can roll back actions." -msgstr "Turtles now have an :meth:`undo()` method that can roll back actions." +msgid "Turtles now have an :meth:`undo` method that can roll back actions." +msgstr "" #: ../../whatsnew/2.6.rst:2570 msgid "" @@ -4146,6 +4906,16 @@ msgstr "" "function. The parameter specifies a timeout measured in seconds. For " "example::" +#: ../../whatsnew/2.6.rst:2585 +msgid "" +">>> u = urllib2.urlopen(\"http://slow.example.com\",\n" +" timeout=3)\n" +"Traceback (most recent call last):\n" +" ...\n" +"urllib2.URLError: \n" +">>>" +msgstr "" + #: ../../whatsnew/2.6.rst:2592 msgid "(Added by Facundo Batista.)" msgstr "(Added by Facundo Batista.)" @@ -4250,6 +5020,18 @@ msgstr "" "and :meth:`extractall` methods that will unpack a single file or all the " "files in the archive to the current directory, or to a specified directory::" +#: ../../whatsnew/2.6.rst:2639 +msgid "" +"z = zipfile.ZipFile('python-251.zip')\n" +"\n" +"# Unpack a single file, writing it relative\n" +"# to the /tmp directory.\n" +"z.extract('Python/sysmodule.c', '/tmp')\n" +"\n" +"# Unpack all the files in the archive.\n" +"z.extractall()" +msgstr "" + #: ../../whatsnew/2.6.rst:2648 msgid "(Contributed by Alan McIntyre; :issue:`467924`.)" msgstr "(Contributed by Alan McIntyre; :issue:`467924`.)" @@ -4298,10 +5080,57 @@ msgstr "" "The :func:`parse` function takes an expression and returns an AST. The :func:" "`dump` function outputs a representation of a tree, suitable for debugging::" +#: ../../whatsnew/2.6.rst:2675 +msgid "" +"import ast\n" +"\n" +"t = ast.parse(\"\"\"\n" +"d = {}\n" +"for i in 'abcdefghijklm':\n" +" d[i + i] = ord(i) - ord('a') + 1\n" +"print d\n" +"\"\"\")\n" +"print ast.dump(t)" +msgstr "" + #: ../../whatsnew/2.6.rst:2685 msgid "This outputs a deeply nested tree::" msgstr "This outputs a deeply nested tree::" +#: ../../whatsnew/2.6.rst:2687 +msgid "" +"Module(body=[\n" +" Assign(targets=[\n" +" Name(id='d', ctx=Store())\n" +" ], value=Dict(keys=[], values=[]))\n" +" For(target=Name(id='i', ctx=Store()),\n" +" iter=Str(s='abcdefghijklm'), body=[\n" +" Assign(targets=[\n" +" Subscript(value=\n" +" Name(id='d', ctx=Load()),\n" +" slice=\n" +" Index(value=\n" +" BinOp(left=Name(id='i', ctx=Load()), op=Add(),\n" +" right=Name(id='i', ctx=Load()))), ctx=Store())\n" +" ], value=\n" +" BinOp(left=\n" +" BinOp(left=\n" +" Call(func=\n" +" Name(id='ord', ctx=Load()), args=[\n" +" Name(id='i', ctx=Load())\n" +" ], keywords=[], starargs=None, kwargs=None),\n" +" op=Sub(), right=Call(func=\n" +" Name(id='ord', ctx=Load()), args=[\n" +" Str(s='a')\n" +" ], keywords=[], starargs=None, kwargs=None)),\n" +" op=Add(), right=Num(n=1)))\n" +" ], orelse=[])\n" +" Print(dest=None, values=[\n" +" Name(id='d', ctx=Load())\n" +" ], nl=True)\n" +" ])" +msgstr "" + #: ../../whatsnew/2.6.rst:2718 msgid "" "The :func:`literal_eval` method takes a string or an AST representing a " @@ -4318,6 +5147,17 @@ msgstr "" "to evaluate an expression but cannot accept the security risk of using an :" "func:`eval` call, :func:`literal_eval` will handle it safely::" +#: ../../whatsnew/2.6.rst:2726 +msgid "" +">>> literal = '(\"a\", \"b\", {2:4, 3:8, 1:2})'\n" +">>> print ast.literal_eval(literal)\n" +"('a', 'b', {1: 2, 2: 4, 3: 8})\n" +">>> print ast.literal_eval('\"a\" + \"b\"')\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: malformed string" +msgstr "" + #: ../../whatsnew/2.6.rst:2734 msgid "" "The module also includes :class:`NodeVisitor` and :class:`NodeTransformer` " @@ -4404,6 +5244,17 @@ msgstr "" ":mod:`json` comes with support for decoding and encoding most built-in " "Python types. The following example encodes and decodes a dictionary::" +#: ../../whatsnew/2.6.rst:2780 +msgid "" +">>> import json\n" +">>> data = {\"spam\": \"foo\", \"parrot\": 42}\n" +">>> in_json = json.dumps(data) # Encode the data\n" +">>> in_json\n" +"'{\"parrot\": 42, \"spam\": \"foo\"}'\n" +">>> json.loads(in_json) # Decode into a Python object\n" +"{\"spam\": \"foo\", \"parrot\": 42}" +msgstr "" + #: ../../whatsnew/2.6.rst:2788 msgid "" "It's also possible to write your own decoders and encoders to support more " @@ -4447,6 +5298,31 @@ msgstr "" msgid "Using the module is simple::" msgstr "Using the module is simple::" +#: ../../whatsnew/2.6.rst:2812 +msgid "" +"import sys\n" +"import plistlib\n" +"import datetime\n" +"\n" +"# Create data structure\n" +"data_struct = dict(lastAccessed=datetime.datetime.now(),\n" +" version=1,\n" +" categories=('Personal','Shared','Private'))\n" +"\n" +"# Create string containing XML.\n" +"plist_str = plistlib.writePlistToString(data_struct)\n" +"new_struct = plistlib.readPlistFromString(plist_str)\n" +"print data_struct\n" +"print new_struct\n" +"\n" +"# Write data structure to a file and read it back.\n" +"plistlib.writePlist(data_struct, '/tmp/customizations.plist')\n" +"new_struct = plistlib.readPlist('/tmp/customizations.plist')\n" +"\n" +"# read/writePlist accepts file-like objects as well as paths.\n" +"plistlib.writePlist(data_struct, sys.stdout)" +msgstr "" + #: ../../whatsnew/2.6.rst:2837 msgid "ctypes Enhancements" msgstr "ctypes Enhancements" @@ -4683,7 +5559,7 @@ msgstr "Mudanças a construções e API C" #: ../../whatsnew/2.6.rst:2976 msgid "Changes to Python's build process and to the C API include:" -msgstr "Changes to Python's build process and to the C API include:" +msgstr "As alterações no processo de construção do Python e na API C incluem:" #: ../../whatsnew/2.6.rst:2978 msgid "" @@ -4967,7 +5843,7 @@ msgstr "" #: ../../whatsnew/2.6.rst:3118 msgid "Port-Specific Changes: Windows" -msgstr "Port-Specific Changes: Windows" +msgstr "Alterações específicas da porta: Windows" #: ../../whatsnew/2.6.rst:3120 msgid "" @@ -5069,7 +5945,7 @@ msgstr "" #: ../../whatsnew/2.6.rst:3167 msgid "Port-Specific Changes: Mac OS X" -msgstr "Port-Specific Changes: Mac OS X" +msgstr "Alterações específicas da porta: Mac OS X" #: ../../whatsnew/2.6.rst:3169 msgid "" @@ -5148,8 +6024,8 @@ msgid "" "This section lists previously described changes and other bugfixes that may " "require changes to your code:" msgstr "" -"Esta seção lista as alterações descritas anteriormente e outras correções de " -"bugs que podem exigir alterações em seu código:" +"Esta seção lista as alterações descritas anteriormente e outras correções " +"que podem exigir alterações no seu código." #: ../../whatsnew/2.6.rst:3258 msgid "" @@ -5287,7 +6163,7 @@ msgstr "" #: ../../whatsnew/2.6.rst:3323 msgid "For applications that embed Python:" -msgstr "For applications that embed Python:" +msgstr "Para aplicações que incorporam Python:" #: ../../whatsnew/2.6.rst:3325 msgid "" diff --git a/whatsnew/2.7.po b/whatsnew/2.7.po index 93b0e31e8..9acbfcbaf 100644 --- a/whatsnew/2.7.po +++ b/whatsnew/2.7.po @@ -1,32 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Vinicius Gubiani Ferreira , 2021 -# Raphael Mendonça, 2021 -# Ricardo Cappellano , 2021 -# Victor Matheus Castro , 2021 -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-28 01:51+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -437,6 +430,22 @@ msgstr "" "dicionários regulares, mas itera sobre chaves e valores em uma ordem " "garantida dependendo de quando uma chave foi inserida pela primeira vez::" +#: ../../whatsnew/2.7.rst:226 +msgid "" +">>> from collections import OrderedDict\n" +">>> d = OrderedDict([('first', 1),\n" +"... ('second', 2),\n" +"... ('third', 3)])\n" +">>> d.items()\n" +"[('first', 1), ('second', 2), ('third', 3)]" +msgstr "" +">>> from collections import OrderedDict\n" +">>> d = OrderedDict([('first', 1),\n" +"... ('second', 2),\n" +"... ('third', 3)])\n" +">>> d.items()\n" +"[('first', 1), ('second', 2), ('third', 3)]" + #: ../../whatsnew/2.7.rst:233 msgid "" "If a new entry overwrites an existing entry, the original insertion position " @@ -445,10 +454,32 @@ msgstr "" "Se uma nova entrada substituir uma entrada existente, a posição de inserção " "original permanece inalterada::" +#: ../../whatsnew/2.7.rst:236 +msgid "" +">>> d['second'] = 4\n" +">>> d.items()\n" +"[('first', 1), ('second', 4), ('third', 3)]" +msgstr "" +">>> d['second'] = 4\n" +">>> d.items()\n" +"[('first', 1), ('second', 4), ('third', 3)]" + #: ../../whatsnew/2.7.rst:240 msgid "Deleting an entry and reinserting it will move it to the end::" msgstr "Excluir uma entrada e reinseri-la irá movê-la para o final::" +#: ../../whatsnew/2.7.rst:242 +msgid "" +">>> del d['second']\n" +">>> d['second'] = 5\n" +">>> d.items()\n" +"[('first', 1), ('third', 3), ('second', 5)]" +msgstr "" +">>> del d['second']\n" +">>> d['second'] = 5\n" +">>> d.items()\n" +"[('first', 1), ('third', 3), ('second', 5)]" + #: ../../whatsnew/2.7.rst:247 msgid "" "The :meth:`~collections.OrderedDict.popitem` method has an optional *last* " @@ -461,6 +492,28 @@ msgstr "" "mais recentemente é retornada e removida; se for falso, a chave mais antiga " "é selecionada::" +#: ../../whatsnew/2.7.rst:252 +msgid "" +">>> od = OrderedDict([(x,0) for x in range(20)])\n" +">>> od.popitem()\n" +"(19, 0)\n" +">>> od.popitem()\n" +"(18, 0)\n" +">>> od.popitem(last=False)\n" +"(0, 0)\n" +">>> od.popitem(last=False)\n" +"(1, 0)" +msgstr "" +">>> od = OrderedDict([(x,0) for x in range(20)])\n" +">>> od.popitem()\n" +"(19, 0)\n" +">>> od.popitem()\n" +"(18, 0)\n" +">>> od.popitem(last=False)\n" +"(0, 0)\n" +">>> od.popitem(last=False)\n" +"(1, 0)" + #: ../../whatsnew/2.7.rst:262 msgid "" "Comparing two ordered dictionaries checks both the keys and values, and " @@ -469,6 +522,34 @@ msgstr "" "A comparação de dois dicionários ordenados verifica as chaves e os valores e " "exige que o pedido de inserção seja o mesmo::" +#: ../../whatsnew/2.7.rst:265 +msgid "" +">>> od1 = OrderedDict([('first', 1),\n" +"... ('second', 2),\n" +"... ('third', 3)])\n" +">>> od2 = OrderedDict([('third', 3),\n" +"... ('first', 1),\n" +"... ('second', 2)])\n" +">>> od1 == od2\n" +"False\n" +">>> # Move 'third' key to the end\n" +">>> del od2['third']; od2['third'] = 3\n" +">>> od1 == od2\n" +"True" +msgstr "" +">>> od1 = OrderedDict([('first', 1),\n" +"... ('second', 2),\n" +"... ('third', 3)])\n" +">>> od2 = OrderedDict([('third', 3),\n" +"... ('first', 1),\n" +"... ('second', 2)])\n" +">>> od1 == od2\n" +"False\n" +">>> # Move a chave 'third' para o fim\n" +">>> del od2['third']; od2['third'] = 3\n" +">>> od1 == od2\n" +"True" + #: ../../whatsnew/2.7.rst:278 msgid "" "Comparing an :class:`~collections.OrderedDict` with a regular dictionary " @@ -511,13 +592,13 @@ msgstr "" #: ../../whatsnew/2.7.rst:294 msgid "" -"The :meth:`~collections.somenamedtuple._asdict()` method for :func:" +"The :meth:`~collections.somenamedtuple._asdict` method for :func:" "`collections.namedtuple` now returns an ordered dictionary with the values " "appearing in the same order as the underlying tuple indices." msgstr "" -"O método :meth:`~Collections.somenamedtuple._asdict()` para :func:" -"`Collections.namedtuple` agora retorna um dicionário ordenado com os valores " -"aparecendo na mesma ordem que os índices de tupla subjacentes." +"O método :meth:`~collections.somenamedtuple._asdict` para :func:`collections." +"namedtuple` agora retorna um dicionário ordenado com os valores aparecendo " +"na mesma ordem que os índices de tupla subjacentes." #: ../../whatsnew/2.7.rst:298 msgid "" @@ -582,6 +663,14 @@ msgstr "" "minilinguagem usada pelo método :meth:`str.format`. Ao formatar um número de " "ponto flutuante, basta incluir uma vírgula entre a largura e a precisão::" +#: ../../whatsnew/2.7.rst:330 +msgid "" +">>> '{:20,.2f}'.format(18446744073709551616.0)\n" +"'18,446,744,073,709,551,616.00'" +msgstr "" +">>> '{:20,.2f}'.format(18446744073709551616.0)\n" +"'18,446,744,073,709,551,616.00'" + #: ../../whatsnew/2.7.rst:333 msgid "When formatting an integer, include the comma after the width:" msgstr "Ao formatar um número inteiro, inclua a vírgula após a largura:" @@ -655,6 +744,50 @@ msgstr "" msgid "Here's an example::" msgstr "Aqui está um exemplo::" +#: ../../whatsnew/2.7.rst:372 +msgid "" +"import argparse\n" +"\n" +"parser = argparse.ArgumentParser(description='Command-line example.')\n" +"\n" +"# Add optional switches\n" +"parser.add_argument('-v', action='store_true', dest='is_verbose',\n" +" help='produce verbose output')\n" +"parser.add_argument('-o', action='store', dest='output',\n" +" metavar='FILE',\n" +" help='direct output to FILE instead of stdout')\n" +"parser.add_argument('-C', action='store', type=int, dest='context',\n" +" metavar='NUM', default=0,\n" +" help='display NUM lines of added context')\n" +"\n" +"# Allow any number of additional arguments.\n" +"parser.add_argument(nargs='*', action='store', dest='inputs',\n" +" help='input filenames (default is stdin)')\n" +"\n" +"args = parser.parse_args()\n" +"print args.__dict__" +msgstr "" +"import argparse\n" +"\n" +"parser = argparse.ArgumentParser(description='Command-line example.')\n" +"\n" +"# Adiciona alterações opcionais\n" +"parser.add_argument('-v', action='store_true', dest='is_verbose',\n" +" help='produce verbose output')\n" +"parser.add_argument('-o', action='store', dest='output',\n" +" metavar='FILE',\n" +" help='direct output to FILE instead of stdout')\n" +"parser.add_argument('-C', action='store', type=int, dest='context',\n" +" metavar='NUM', default=0,\n" +" help='display NUM lines of added context')\n" +"\n" +"# Permite qualquer número de argumentos adicionais.\n" +"parser.add_argument(nargs='*', action='store', dest='inputs',\n" +" help='input filenames (default is stdin)')\n" +"\n" +"args = parser.parse_args()\n" +"print args.__dict__" + #: ../../whatsnew/2.7.rst:393 msgid "" "Unless you override it, :option:`!-h` and :option:`!--help` switches are " @@ -664,6 +797,38 @@ msgstr "" "são adicionadas automaticamente e produzem uma saída formatada de maneira " "organizada::" +#: ../../whatsnew/2.7.rst:396 +msgid "" +"-> ./python.exe argparse-example.py --help\n" +"usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs " +"[inputs ...]]\n" +"\n" +"Command-line example.\n" +"\n" +"positional arguments:\n" +" inputs input filenames (default is stdin)\n" +"\n" +"optional arguments:\n" +" -h, --help show this help message and exit\n" +" -v produce verbose output\n" +" -o FILE direct output to FILE instead of stdout\n" +" -C NUM display NUM lines of added context" +msgstr "" +"-> ./python.exe argparse-example.py --help\n" +"usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs " +"[inputs ...]]\n" +"\n" +"Command-line example.\n" +"\n" +"positional arguments:\n" +" inputs input filenames (default is stdin)\n" +"\n" +"optional arguments:\n" +" -h, --help show this help message and exit\n" +" -v produce verbose output\n" +" -o FILE direct output to FILE instead of stdout\n" +" -C NUM display NUM lines of added context" + #: ../../whatsnew/2.7.rst:410 msgid "" "As with :mod:`optparse`, the command-line switches and arguments are " @@ -672,6 +837,32 @@ msgstr "" "Como em :mod:`optparse`, as opções e argumentos da linha de comando são " "retornados como um objeto com atributos nomeados pelos parâmetros *dest*::" +#: ../../whatsnew/2.7.rst:413 +msgid "" +"-> ./python.exe argparse-example.py -v\n" +"{'output': None,\n" +" 'is_verbose': True,\n" +" 'context': 0,\n" +" 'inputs': []}\n" +"\n" +"-> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2\n" +"{'output': '/tmp/output',\n" +" 'is_verbose': True,\n" +" 'context': 4,\n" +" 'inputs': ['file1', 'file2']}" +msgstr "" +"-> ./python.exe argparse-example.py -v\n" +"{'output': None,\n" +" 'is_verbose': True,\n" +" 'context': 0,\n" +" 'inputs': []}\n" +"\n" +"-> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2\n" +"{'output': '/tmp/output',\n" +" 'is_verbose': True,\n" +" 'context': 4,\n" +" 'inputs': ['file1', 'file2']}" + #: ../../whatsnew/2.7.rst:425 msgid "" ":mod:`argparse` has much fancier validation than :mod:`optparse`; you can " @@ -782,6 +973,92 @@ msgstr "" "para o logger \"network\" serão gravadas em um arquivo :file:`network.log` " "que será rotacionado assim que o log atingir 1 MB." +#: ../../whatsnew/2.7.rst:476 +msgid "" +"import logging\n" +"import logging.config\n" +"\n" +"configdict = {\n" +" 'version': 1, # Configuration schema in use; must be 1 for now\n" +" 'formatters': {\n" +" 'standard': {\n" +" 'format': ('%(asctime)s %(name)-15s '\n" +" '%(levelname)-8s %(message)s')}},\n" +"\n" +" 'handlers': {'netlog': {'backupCount': 10,\n" +" 'class': 'logging.handlers.RotatingFileHandler',\n" +" 'filename': '/logs/network.log',\n" +" 'formatter': 'standard',\n" +" 'level': 'INFO',\n" +" 'maxBytes': 1000000},\n" +" 'syslog': {'class': 'logging.handlers.SysLogHandler',\n" +" 'formatter': 'standard',\n" +" 'level': 'ERROR'}},\n" +"\n" +" # Specify all the subordinate loggers\n" +" 'loggers': {\n" +" 'network': {\n" +" 'handlers': ['netlog']\n" +" }\n" +" },\n" +" # Specify properties of the root logger\n" +" 'root': {\n" +" 'handlers': ['syslog']\n" +" },\n" +"}\n" +"\n" +"# Set up configuration\n" +"logging.config.dictConfig(configdict)\n" +"\n" +"# As an example, log two error messages\n" +"logger = logging.getLogger('/')\n" +"logger.error('Database not found')\n" +"\n" +"netlogger = logging.getLogger('network')\n" +"netlogger.error('Connection failed')" +msgstr "" +"import logging\n" +"import logging.config\n" +"\n" +"configdict = {\n" +" 'version': 1, # Configuration schema in use; must be 1 for now\n" +" 'formatters': {\n" +" 'standard': {\n" +" 'format': ('%(asctime)s %(name)-15s '\n" +" '%(levelname)-8s %(message)s')}},\n" +"\n" +" 'handlers': {'netlog': {'backupCount': 10,\n" +" 'class': 'logging.handlers.RotatingFileHandler',\n" +" 'filename': '/logs/network.log',\n" +" 'formatter': 'standard',\n" +" 'level': 'INFO',\n" +" 'maxBytes': 1000000},\n" +" 'syslog': {'class': 'logging.handlers.SysLogHandler',\n" +" 'formatter': 'standard',\n" +" 'level': 'ERROR'}},\n" +"\n" +" # Especifica todos os loggers subordinados\n" +" 'loggers': {\n" +" 'network': {\n" +" 'handlers': ['netlog']\n" +" }\n" +" },\n" +" # Especifica propriedades do logger raiz\n" +" 'root': {\n" +" 'handlers': ['syslog']\n" +" },\n" +"}\n" +"\n" +"# Prepara as configurações\n" +"logging.config.dictConfig(configdict)\n" +"\n" +"# Como um exemplo, registra duas mensagens de erro\n" +"logger = logging.getLogger('/')\n" +"logger.error('Database not found')\n" +"\n" +"netlogger = logging.getLogger('network')\n" +"netlogger.error('Connection failed')" + #: ../../whatsnew/2.7.rst:518 msgid "" "Three smaller enhancements to the :mod:`logging` module, all implemented by " @@ -860,6 +1137,20 @@ msgstr "" "interrompido. Em vez disso, as versões 3.x foram adicionadas com os novos " "nomes :meth:`!viewkeys`, :meth:`!viewvalues` e :meth:`!viewitems`." +#: ../../whatsnew/2.7.rst:562 +msgid "" +">>> d = dict((i*10, chr(65+i)) for i in range(26))\n" +">>> d\n" +"{0: 'A', 130: 'N', 10: 'B', 140: 'O', 20: ..., 250: 'Z'}\n" +">>> d.viewkeys()\n" +"dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])" +msgstr "" +">>> d = dict((i*10, chr(65+i)) for i in range(26))\n" +">>> d\n" +"{0: 'A', 130: 'N', 10: 'B', 140: 'O', 20: ..., 250: 'Z'}\n" +">>> d.viewkeys()\n" +"dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])" + #: ../../whatsnew/2.7.rst:568 msgid "" "Views can be iterated over, but the key and item views also behave like " @@ -869,6 +1160,22 @@ msgstr "" "comportam como conjuntos. O operador ``&`` realiza a interseção, e o ``|`` " "realiza uma união::" +#: ../../whatsnew/2.7.rst:572 +msgid "" +">>> d1 = dict((i*10, chr(65+i)) for i in range(26))\n" +">>> d2 = dict((i**.5, i) for i in range(1000))\n" +">>> d1.viewkeys() & d2.viewkeys()\n" +"set([0.0, 10.0, 20.0, 30.0])\n" +">>> d1.viewkeys() | range(0, 30)\n" +"set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])" +msgstr "" +">>> d1 = dict((i*10, chr(65+i)) for i in range(26))\n" +">>> d2 = dict((i**.5, i) for i in range(1000))\n" +">>> d1.viewkeys() & d2.viewkeys()\n" +"set([0.0, 10.0, 20.0, 30.0])\n" +">>> d1.viewkeys() | range(0, 30)\n" +"set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])" + #: ../../whatsnew/2.7.rst:579 msgid "" "The view keeps track of the dictionary and its contents change as the " @@ -877,6 +1184,22 @@ msgstr "" "A view acompanha o dicionário e seu conteúdo muda à medida que o dicionário " "é modificado::" +#: ../../whatsnew/2.7.rst:582 +msgid "" +">>> vk = d.viewkeys()\n" +">>> vk\n" +"dict_keys([0, 130, 10, ..., 250])\n" +">>> d[260] = '&'\n" +">>> vk\n" +"dict_keys([0, 130, 260, 10, ..., 250])" +msgstr "" +">>> vk = d.viewkeys()\n" +">>> vk\n" +"dict_keys([0, 130, 10, ..., 250])\n" +">>> d[260] = '&'\n" +">>> vk\n" +"dict_keys([0, 130, 260, 10, ..., 250])" + #: ../../whatsnew/2.7.rst:589 msgid "" "However, note that you can't add or remove keys while you're iterating over " @@ -885,6 +1208,22 @@ msgstr "" "No entanto, observe que você não pode adicionar ou remover chaves enquanto " "estiver iterando na view::" +#: ../../whatsnew/2.7.rst:592 +msgid "" +">>> for k in vk:\n" +"... d[k*2] = k\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"RuntimeError: dictionary changed size during iteration" +msgstr "" +">>> for k in vk:\n" +"... d[k*2] = k\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"RuntimeError: dictionary changed size during iteration" + #: ../../whatsnew/2.7.rst:599 msgid "" "You can use the view methods in Python 2.x code, and the 2to3 converter will " @@ -919,6 +1258,32 @@ msgstr "" "O objeto :class:`memoryview` fornece uma visão do conteúdo da memória de " "outro objeto que corresponde à interface do tipo :class:`bytes`." +#: ../../whatsnew/2.7.rst:616 +msgid "" +">>> import string\n" +">>> m = memoryview(string.letters)\n" +">>> m\n" +"\n" +">>> len(m) # Returns length of underlying object\n" +"52\n" +">>> m[0], m[25], m[26] # Indexing returns one byte\n" +"('a', 'z', 'A')\n" +">>> m2 = m[0:26] # Slicing returns another memoryview\n" +">>> m2\n" +"" +msgstr "" +">>> import string\n" +">>> m = memoryview(string.letters)\n" +">>> m\n" +"\n" +">>> len(m) # Retorna o comprimento de objeto subjacente\n" +"52\n" +">>> m[0], m[25], m[26] # Indexação retorna um byte\n" +"('a', 'z', 'A')\n" +">>> m2 = m[0:26] # Fatiamento retorna outra memoryview\n" +">>> m2\n" +"" + #: ../../whatsnew/2.7.rst:631 msgid "" "The content of the view can be converted to a string of bytes or a list of " @@ -927,6 +1292,20 @@ msgstr "" "O conteúdo da viewq pode ser convertido em uma string de bytes ou uma lista " "de inteiros:" +#: ../../whatsnew/2.7.rst:634 +msgid "" +">>> m2.tobytes()\n" +"'abcdefghijklmnopqrstuvwxyz'\n" +">>> m2.tolist()\n" +"[97, 98, 99, 100, 101, 102, 103, ... 121, 122]\n" +">>>" +msgstr "" +">>> m2.tobytes()\n" +"'abcdefghijklmnopqrstuvwxyz'\n" +">>> m2.tolist()\n" +"[97, 98, 99, 100, 101, 102, 103, ... 121, 122]\n" +">>>" + #: ../../whatsnew/2.7.rst:643 msgid "" ":class:`memoryview` objects allow modifying the underlying object if it's a " @@ -935,6 +1314,34 @@ msgstr "" "Objetos :class:`memoryview` permitem modificar o objeto subjacente se for um " "objeto mutável." +#: ../../whatsnew/2.7.rst:646 +msgid "" +">>> m2[0] = 75\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: cannot modify read-only memory\n" +">>> b = bytearray(string.letters) # Creating a mutable object\n" +">>> b\n" +"bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')\n" +">>> mb = memoryview(b)\n" +">>> mb[0] = '*' # Assign to view, changing the bytearray.\n" +">>> b[0:5] # The bytearray has been changed.\n" +"bytearray(b'*bcde')\n" +">>>" +msgstr "" +">>> m2[0] = 75\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: cannot modify read-only memory\n" +">>> b = bytearray(string.letters) # Criando um objeto mutável\n" +">>> b\n" +"bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')\n" +">>> mb = memoryview(b)\n" +">>> mb[0] = '*' # Atribui para visão, alterando o bytearray.\n" +">>> b[0:5] # O bytearray foi alterado.\n" +"bytearray(b'*bcde')\n" +">>>" + #: ../../whatsnew/2.7.rst:664 msgid ":pep:`3137` - Immutable Bytes and Mutable Buffer" msgstr ":pep:`3137` - Bytes imutáveis e buffer mutável" @@ -953,7 +1360,7 @@ msgstr "Outras mudanças na linguagem" #: ../../whatsnew/2.7.rst:674 msgid "Some smaller changes made to the core Python language are:" -msgstr "Alguma das mudanças menores feitas no núcleo da linguagem Python são:" +msgstr "Algumas das mudanças menores feitas no núcleo da linguagem Python são:" #: ../../whatsnew/2.7.rst:676 msgid "" @@ -969,6 +1376,22 @@ msgstr "" "dois pontos e valores. ``{}`` continua a representar um dicionário vazio; " "use ``set()`` para um conjunto vazio." +#: ../../whatsnew/2.7.rst:683 +msgid "" +">>> {1, 2, 3, 4, 5}\n" +"set([1, 2, 3, 4, 5])\n" +">>> set() # empty set\n" +"set([])\n" +">>> {} # empty dict\n" +"{}" +msgstr "" +">>> {1, 2, 3, 4, 5}\n" +"set([1, 2, 3, 4, 5])\n" +">>> set() # conjunto vazio\n" +"set([])\n" +">>> {} # dicionário vazio\n" +"{}" + #: ../../whatsnew/2.7.rst:693 msgid "Backported by Alexandre Vassalotti; :issue:`2335`." msgstr "Portado por Alexandre Vassalotti; :issue:`2335`." @@ -983,6 +1406,18 @@ msgstr "" "generalizando as compreensões de lista/gerador para usar a sintaxe literal " "para conjuntos e dicionários." +#: ../../whatsnew/2.7.rst:699 +msgid "" +">>> {x: x*x for x in range(6)}\n" +"{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}\n" +">>> {('a'*x) for x in range(6)}\n" +"set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])" +msgstr "" +">>> {x: x*x for x in range(6)}\n" +"{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}\n" +">>> {('a'*x) for x in range(6)}\n" +"set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])" + #: ../../whatsnew/2.7.rst:707 msgid "Backported by Alexandre Vassalotti; :issue:`2333`." msgstr "Portado por Alexandre Vassalotti; :issue:`2333`." @@ -998,10 +1433,28 @@ msgstr "" "para a direita e cada um é tratado como o início de uma nova instrução :" "keyword:`!with`. Isso significa que::" +#: ../../whatsnew/2.7.rst:714 +msgid "" +"with A() as a, B() as b:\n" +" ... suite of statements ..." +msgstr "" +"with A() as a, B() as b:\n" +" ... conjunto de instruções ..." + #: ../../whatsnew/2.7.rst:717 msgid "is equivalent to::" msgstr "é equivalente a::" +#: ../../whatsnew/2.7.rst:719 +msgid "" +"with A() as a:\n" +" with B() as b:\n" +" ... suite of statements ..." +msgstr "" +"with A() as a:\n" +" with B() as b:\n" +" ... conjunto de instruções ..." + #: ../../whatsnew/2.7.rst:723 msgid "" "The :func:`!contextlib.nested` function provides a very similar function, so " @@ -1091,6 +1544,20 @@ msgstr "" "inevitavelmente perderão a precisão, o Python 2.7 agora se aproxima mais. " "Por exemplo, o Python 2.6 computou o seguinte::" +#: ../../whatsnew/2.7.rst:767 +msgid "" +">>> n = 295147905179352891391\n" +">>> float(n)\n" +"2.9514790517935283e+20\n" +">>> n - long(float(n))\n" +"65535L" +msgstr "" +">>> n = 295147905179352891391\n" +">>> float(n)\n" +"2.9514790517935283e+20\n" +">>> n - long(float(n))\n" +"65535L" + #: ../../whatsnew/2.7.rst:773 msgid "" "Python 2.7's floating-point result is larger, but much closer to the true " @@ -1099,6 +1566,20 @@ msgstr "" "O resultado de ponto flutuante do Python 2.7 é maior, mas muito mais próximo " "do valor verdadeiro::" +#: ../../whatsnew/2.7.rst:776 +msgid "" +">>> n = 295147905179352891391\n" +">>> float(n)\n" +"2.9514790517935289e+20\n" +">>> n - long(float(n))\n" +"-1L" +msgstr "" +">>> n = 295147905179352891391\n" +">>> float(n)\n" +"2.9514790517935289e+20\n" +">>> n - long(float(n))\n" +"-1L" + #: ../../whatsnew/2.7.rst:782 msgid "(Implemented by Mark Dickinson; :issue:`3166`.)" msgstr "(Implementada por Mark Dickinson; :issue:`3166`.)" @@ -1131,6 +1612,18 @@ msgstr "" "campos de substituição. Isso torna o uso de :meth:`str.format` mais parecido " "com o uso da formatação ``%s``::" +#: ../../whatsnew/2.7.rst:795 +msgid "" +">>> '{}:{}:{}'.format(2009, 04, 'Sunday')\n" +"'2009:4:Sunday'\n" +">>> '{}:{}:{day}'.format(2009, 4, day='Sunday')\n" +"'2009:4:Sunday'" +msgstr "" +">>> '{}:{}:{}'.format(2009, 04, 'Sunday')\n" +"'2009:4:Sunday'\n" +">>> '{}:{}:{day}'.format(2009, 4, day='Sunday')\n" +"'2009:4:Sunday'" + #: ../../whatsnew/2.7.rst:800 msgid "" "The auto-numbering takes the fields from left to right, so the first ``{...}" @@ -1203,6 +1696,30 @@ msgstr "" "retorna o número de bits necessários para representar seu argumento em " "binário::" +#: ../../whatsnew/2.7.rst:832 +msgid "" +">>> n = 37\n" +">>> bin(n)\n" +"'0b100101'\n" +">>> n.bit_length()\n" +"6\n" +">>> n = 2**123-1\n" +">>> n.bit_length()\n" +"123\n" +">>> (n+1).bit_length()\n" +"124" +msgstr "" +">>> n = 37\n" +">>> bin(n)\n" +"'0b100101'\n" +">>> n.bit_length()\n" +"6\n" +">>> n = 2**123-1\n" +">>> n.bit_length()\n" +"123\n" +">>> (n+1).bit_length()\n" +"124" + #: ../../whatsnew/2.7.rst:843 msgid "(Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)" msgstr "(Contribuição de Fredrik Johansson e Victor Stinner; :issue:`3439`.)" @@ -1365,6 +1882,10 @@ msgstr "" "em um erro. (A sintaxe exata para definir uma variável de ambiente varia " "entre sistemas operacionais e shells.)" +#: ../../whatsnew/2.7.rst:924 +msgid "export PYTHONWARNINGS=all,error:::Cookie:0" +msgstr "export PYTHONWARNINGS=all,error:::Cookie:0" + #: ../../whatsnew/2.7.rst:930 msgid "Optimizations" msgstr "Otimizações" @@ -1458,9 +1979,19 @@ msgstr "" "interno, fornecendo o número de bits por dígito e o tamanho em bytes do tipo " "C usado para armazenar cada dígito::" +#: ../../whatsnew/2.7.rst:974 +msgid "" +">>> import sys\n" +">>> sys.long_info\n" +"sys.long_info(bits_per_digit=30, sizeof_digit=4)" +msgstr "" +">>> import sys\n" +">>> sys.long_info\n" +"sys.long_info(bits_per_digit=30, sizeof_digit=4)" + #: ../../whatsnew/2.7.rst:978 msgid "(Contributed by Mark Dickinson; :issue:`4258`.)" -msgstr "(Contribuição de Mark Dickinson; :issue:`4258`.)" +msgstr "(Contributed by Mark Dickinson; :issue:`4258`.)" #: ../../whatsnew/2.7.rst:980 msgid "" @@ -1642,6 +2173,36 @@ msgstr "" "retornam zero para chaves ausentes em vez de levantar uma exceção :exc:" "`KeyError`:" +#: ../../whatsnew/2.7.rst:1064 +msgid "" +">>> from collections import Counter\n" +">>> c = Counter()\n" +">>> for letter in 'here is a sample of english text':\n" +"... c[letter] += 1\n" +"...\n" +">>> c\n" +"Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,\n" +"'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,\n" +"'p': 1, 'r': 1, 'x': 1})\n" +">>> c['e']\n" +"5\n" +">>> c['z']\n" +"0" +msgstr "" +">>> from collections import Counter\n" +">>> c = Counter()\n" +">>> for letter in 'here is a sample of english text':\n" +"... c[letter] += 1\n" +"...\n" +">>> c\n" +"Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,\n" +"'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,\n" +"'p': 1, 'r': 1, 'x': 1})\n" +">>> c['e']\n" +"5\n" +">>> c['z']\n" +"0" + #: ../../whatsnew/2.7.rst:1081 msgid "" "There are three additional :class:`~collections.Counter` methods. :meth:" @@ -1660,6 +2221,34 @@ msgstr "" "um para cada elemento em vez de adicionar; se o argumento for um dicionário " "ou outro :class:`Counter`, as contagens são subtraídas. ::" +#: ../../whatsnew/2.7.rst:1091 +msgid "" +">>> c.most_common(5)\n" +"[(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]\n" +">>> c.elements() ->\n" +" 'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',\n" +" 'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',\n" +" 'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',\n" +" 's', 's', 'r', 't', 't', 'x'\n" +">>> c['e']\n" +"5\n" +">>> c.subtract('very heavy on the letter e')\n" +">>> c['e'] # Count is now lower\n" +"-1" +msgstr "" +">>> c.most_common(5)\n" +"[(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]\n" +">>> c.elements() ->\n" +" 'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',\n" +" 'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',\n" +" 'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',\n" +" 's', 's', 'r', 't', 't', 'x'\n" +">>> c['e']\n" +"5\n" +">>> c.subtract('very heavy on the letter e')\n" +">>> c['e'] # Count is now lower\n" +"-1" + #: ../../whatsnew/2.7.rst:1104 msgid "Contributed by Raymond Hettinger; :issue:`1696199`." msgstr "Contribuição de Raymond Hettinger; :issue:`1696199`." @@ -1727,6 +2316,44 @@ msgstr "" "` agora recebem um parâmetro *allow_no_value*, cujo padrão é " "false; se verdadeiro, opções sem valores serão permitidas. Por exemplo::" +#: ../../whatsnew/2.7.rst:1141 +msgid "" +">>> import ConfigParser, StringIO\n" +">>> sample_config = \"\"\"\n" +"... [mysqld]\n" +"... user = mysql\n" +"... pid-file = /var/run/mysqld/mysqld.pid\n" +"... skip-bdb\n" +"... \"\"\"\n" +">>> config = ConfigParser.RawConfigParser(allow_no_value=True)\n" +">>> config.readfp(StringIO.StringIO(sample_config))\n" +">>> config.get('mysqld', 'user')\n" +"'mysql'\n" +">>> print config.get('mysqld', 'skip-bdb')\n" +"None\n" +">>> print config.get('mysqld', 'unknown')\n" +"Traceback (most recent call last):\n" +" ...\n" +"NoOptionError: No option 'unknown' in section: 'mysqld'" +msgstr "" +">>> import ConfigParser, StringIO\n" +">>> sample_config = \"\"\"\n" +"... [mysqld]\n" +"... user = mysql\n" +"... pid-file = /var/run/mysqld/mysqld.pid\n" +"... skip-bdb\n" +"... \"\"\"\n" +">>> config = ConfigParser.RawConfigParser(allow_no_value=True)\n" +">>> config.readfp(StringIO.StringIO(sample_config))\n" +">>> config.get('mysqld', 'user')\n" +"'mysql'\n" +">>> print config.get('mysqld', 'skip-bdb')\n" +"None\n" +">>> print config.get('mysqld', 'unknown')\n" +"Traceback (most recent call last):\n" +" ...\n" +"NoOptionError: No option 'unknown' in section: 'mysqld'" + #: ../../whatsnew/2.7.rst:1159 msgid "(Contributed by Mats Kindahl; :issue:`7005`.)" msgstr "(Contribuição de Mats Kindahl; :issue:`7005`.)" @@ -2113,6 +2740,34 @@ msgstr "" "parâmetros do chamável receberão cada argumento, retornando um dicionário " "mapeando nomes de argumentos para seus valores. Por exemplo::" +#: ../../whatsnew/2.7.rst:1333 +msgid "" +">>> from inspect import getcallargs\n" +">>> def f(a, b=1, *pos, **named):\n" +"... pass\n" +"...\n" +">>> getcallargs(f, 1, 2, 3)\n" +"{'a': 1, 'b': 2, 'pos': (3,), 'named': {}}\n" +">>> getcallargs(f, a=2, x=4)\n" +"{'a': 2, 'b': 1, 'pos': (), 'named': {'x': 4}}\n" +">>> getcallargs(f)\n" +"Traceback (most recent call last):\n" +"...\n" +"TypeError: f() takes at least 1 argument (0 given)" +msgstr "" +">>> from inspect import getcallargs\n" +">>> def f(a, b=1, *pos, **named):\n" +"... pass\n" +"...\n" +">>> getcallargs(f, 1, 2, 3)\n" +"{'a': 1, 'b': 2, 'pos': (3,), 'named': {}}\n" +">>> getcallargs(f, a=2, x=4)\n" +"{'a': 2, 'b': 1, 'pos': (), 'named': {'x': 4}}\n" +">>> getcallargs(f)\n" +"Traceback (most recent call last):\n" +"...\n" +"TypeError: f() takes at least 1 argument (0 given)" + #: ../../whatsnew/2.7.rst:1346 msgid "Contributed by George Sakkis; :issue:`3135`." msgstr "Contribuição de George Sakkis; :issue:`3135`." @@ -2166,6 +2821,14 @@ msgstr "" "Elementos de *data* serão retornados se o valor correspondente em " "*selectors* for verdadeiro::" +#: ../../whatsnew/2.7.rst:1368 +msgid "" +"itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>\n" +" A, C, E, F" +msgstr "" +"itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>\n" +" A, C, E, F" + #: ../../whatsnew/2.7.rst:1373 msgid "" "New function: ``itertools.combinations_with_replacement(iter, r)`` returns " @@ -2178,6 +2841,16 @@ msgstr "" "iterável. Ao contrário de :func:`~itertools.combinations`, elementos " "individuais podem ser repetidos nas combinações geradas::" +#: ../../whatsnew/2.7.rst:1378 +msgid "" +"itertools.combinations_with_replacement('abc', 2) =>\n" +" ('a', 'a'), ('a', 'b'), ('a', 'c'),\n" +" ('b', 'b'), ('b', 'c'), ('c', 'c')" +msgstr "" +"itertools.combinations_with_replacement('abc', 2) =>\n" +" ('a', 'a'), ('a', 'b'), ('a', 'c'),\n" +" ('b', 'b'), ('b', 'c'), ('c', 'c')" + #: ../../whatsnew/2.7.rst:1382 msgid "" "Note that elements are treated as unique depending on their position in the " @@ -2549,14 +3222,14 @@ msgid "" "The :func:`~ssl.SSLContext.wrap_socket` constructor function now takes a " "*ciphers* argument that's a string listing the encryption algorithms to be " "allowed; the format of the string is described `in the OpenSSL documentation " -"`__. (Added by " -"Antoine Pitrou; :issue:`8322`.)" +"`__. (Added by Antoine " +"Pitrou; :issue:`8322`.)" msgstr "" "A função construtora :func:`~ssl.SSLContext.wrap_socket` agora recebe um " "argumento *ciphers* que é uma string listando os algoritmos de criptografia " "a serem permitidos; o formato da string é descrito `na documentação do " -"OpenSSL `__. " -"(Adição de Antoine Pitrou; :issue:`8322`.)" +"OpenSSL `__. (Adição de " +"Antoine Pitrou; :issue:`8322`.)" #: ../../whatsnew/2.7.rst:1554 msgid "" @@ -2613,6 +3286,26 @@ msgstr "" "saída do comando como uma string quando o comando é executado sem erros, ou " "levanta uma exceção :exc:`~subprocess.CalledProcessError` caso contrário." +#: ../../whatsnew/2.7.rst:1582 +msgid "" +">>> subprocess.check_output(['df', '-h', '.'])\n" +"'Filesystem Size Used Avail Capacity Mounted on\\n\n" +"/dev/disk0s2 52G 49G 3.0G 94% /\\n'\n" +"\n" +">>> subprocess.check_output(['df', '-h', '/bogus'])\n" +" ...\n" +"subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-" +"zero exit status 1" +msgstr "" +">>> subprocess.check_output(['df', '-h', '.'])\n" +"'Filesystem Size Used Avail Capacity Mounted on\\n\n" +"/dev/disk0s2 52G 49G 3.0G 94% /\\n'\n" +"\n" +">>> subprocess.check_output(['df', '-h', '/bogus'])\n" +" ...\n" +"subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-" +"zero exit status 1" + #: ../../whatsnew/2.7.rst:1590 msgid "(Contributed by Gregory P. Smith.)" msgstr "(Contribuição de Gregory P. Smith.)" @@ -2651,11 +3344,11 @@ msgstr "" #: ../../whatsnew/2.7.rst:1605 msgid "" -"The :attr:`sys.version_info` value is now a named tuple, with attributes " +"The :data:`sys.version_info` value is now a named tuple, with attributes " "named :attr:`!major`, :attr:`!minor`, :attr:`!micro`, :attr:`!releaselevel`, " "and :attr:`!serial`. (Contributed by Ross Light; :issue:`4285`.)" msgstr "" -"O valor :attr:`sys.version_info` agora é uma tupla nomeada, com atributos " +"O valor :data:`sys.version_info` agora é uma tupla nomeada, com atributos " "chamados :attr:`!major`, :attr:`!minor`, :attr:`!micro`, :attr:`!" "releaselevel` e :attr:`!serial`. (Contribuição de Ross Light; :issue:`4285`.)" @@ -2763,10 +3456,30 @@ msgstr "" "contornava o comportamento antigo. Por exemplo, Python 2.6.4 ou 2.5 " "retornará o seguinte:" +#: ../../whatsnew/2.7.rst:1659 ../../whatsnew/2.7.rst:2520 +msgid "" +">>> import urlparse\n" +">>> urlparse.urlsplit('invented://host/filename?query')\n" +"('invented', '', '//host/filename?query', '', '')" +msgstr "" +">>> import urlparse\n" +">>> urlparse.urlsplit('invented://host/filename?query')\n" +"('invented', '', '//host/filename?query', '', '')" + #: ../../whatsnew/2.7.rst:1666 ../../whatsnew/2.7.rst:2527 msgid "Python 2.7 (and Python 2.6.5) will return:" msgstr "Python 2.7 (e Python 2.6.5) vai retornar:" +#: ../../whatsnew/2.7.rst:1668 ../../whatsnew/2.7.rst:2529 +msgid "" +">>> import urlparse\n" +">>> urlparse.urlsplit('invented://host/filename?query')\n" +"('invented', 'host', '/filename?query', '', '')" +msgstr "" +">>> import urlparse\n" +">>> urlparse.urlsplit('invented://host/filename?query')\n" +"('invented', 'host', '/filename?query', '', '')" + #: ../../whatsnew/2.7.rst:1675 ../../whatsnew/2.7.rst:2536 msgid "" "(Python 2.7 actually produces slightly different output, since it returns a " @@ -2785,6 +3498,16 @@ msgstr "" "IPv6 literais conforme definido pelo :rfc:`2732` (contribuição de Senthil " "Kumaran; :issue:`2987`)." +#: ../../whatsnew/2.7.rst:1681 +msgid "" +">>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')\n" +"ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',\n" +" path='/foo', params='', query='', fragment='')" +msgstr "" +">>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')\n" +"ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',\n" +" path='/foo', params='', query='', fragment='')" + #: ../../whatsnew/2.7.rst:1688 msgid "" "New class: the :class:`~weakref.WeakSet` class in the :mod:`weakref` module " @@ -2923,6 +3646,26 @@ msgstr "" msgid "Here are some examples::" msgstr "Veja alguns exemplos::" +#: ../../whatsnew/2.7.rst:1758 +msgid "" +">>> from importlib import import_module\n" +">>> anydbm = import_module('anydbm') # Standard absolute import\n" +">>> anydbm\n" +"\n" +">>> # Relative import\n" +">>> file_util = import_module('..file_util', 'distutils.command')\n" +">>> file_util\n" +"" +msgstr "" +">>> from importlib import import_module\n" +">>> anydbm = import_module('anydbm') # Importação absoluta padrão\n" +">>> anydbm\n" +"\n" +">>> # Importação relativa\n" +">>> file_util = import_module('..file_util', 'distutils.command')\n" +">>> file_util\n" +"" + #: ../../whatsnew/2.7.rst:1767 msgid "" ":mod:`importlib` was implemented by Brett Cannon and introduced in Python " @@ -3088,6 +3831,10 @@ msgstr "" "pacotes. Por exemplo, o comando a seguir irá pesquisar no subdiretório :file:" "`test/` por quaisquer arquivos de teste importáveis chamados ``test*.py``::" +#: ../../whatsnew/2.7.rst:1843 +msgid "python -m unittest discover -s test" +msgstr "python -m unittest discover -s test" + #: ../../whatsnew/2.7.rst:1845 msgid "" "Consult the :mod:`unittest` module documentation for more details. " @@ -3203,6 +3950,14 @@ msgstr "" "manipulador de contexto quando chamado sem fornecer um objeto chamável para " "ser executado. Por exemplo, você pode escrever isto::" +#: ../../whatsnew/2.7.rst:1892 +msgid "" +"with self.assertRaises(KeyError):\n" +" {}['foo']" +msgstr "" +"with self.assertRaises(KeyError):\n" +" {}['foo']" + #: ../../whatsnew/2.7.rst:1895 msgid "(Implemented by Antoine Pitrou; :issue:`4444`.)" msgstr "(implementação de Antoine Pitrou; :issue:`4444`.)" @@ -3506,6 +4261,14 @@ msgstr "" "fornecendo uma instância :class:`~xml.etree.ElementTree.XMLParser` que será " "usada. Isso torna possível substituir a codificação interna do arquivo::" +#: ../../whatsnew/2.7.rst:2024 +msgid "" +"p = ET.XMLParser(encoding='utf-8')\n" +"t = ET.XML(\"\"\"\"\"\", parser=p)" +msgstr "" +"p = ET.XMLParser(encoding='utf-8')\n" +"t = ET.XML(\"\"\"\"\"\", parser=p)" + #: ../../whatsnew/2.7.rst:2027 msgid "" "Errors in parsing XML now raise a :exc:`~xml.etree.ElementTree.ParseError` " @@ -3572,6 +4335,30 @@ msgstr "" "elemento. Os próprios elementos se comportam como sequências, por isso é " "fácil mover os filhos de um elemento para outro::" +#: ../../whatsnew/2.7.rst:2058 +msgid "" +"from xml.etree import ElementTree as ET\n" +"\n" +"t = ET.XML(\"\"\"\n" +" 1 2 3\n" +"\"\"\")\n" +"new = ET.XML('')\n" +"new.extend(t)\n" +"\n" +"# Outputs 1...\n" +"print ET.tostring(new)" +msgstr "" +"from xml.etree import ElementTree as ET\n" +"\n" +"t = ET.XML(\"\"\"\n" +" 1 2 3\n" +"\"\"\")\n" +"new = ET.XML('')\n" +"new.extend(t)\n" +"\n" +"# Outputs 1...\n" +"print ET.tostring(new)" + #: ../../whatsnew/2.7.rst:2069 msgid "" "New :class:`~xml.etree.ElementTree.Element` method: :meth:`~xml.etree." @@ -3598,6 +4385,22 @@ msgstr "" "ElementTree.Element.itertext` produz todos os pedaços de texto que são " "descendentes do elemento. Por exemplo::" +#: ../../whatsnew/2.7.rst:2080 +msgid "" +"t = ET.XML(\"\"\"\n" +" 1 2 3\n" +"\"\"\")\n" +"\n" +"# Outputs ['\\n ', '1', ' ', '2', ' ', '3', '\\n']\n" +"print list(t.itertext())" +msgstr "" +"t = ET.XML(\"\"\"\n" +" 1 2 3\n" +"\"\"\")\n" +"\n" +"# Outputs ['\\n ', '1', ' ', '2', ' ', '3', '\\n']\n" +"print list(t.itertext())" + #: ../../whatsnew/2.7.rst:2087 msgid "" "Deprecated: using an element as a Boolean (i.e., ``if elem:``) would return " @@ -4026,6 +4829,26 @@ msgstr "" "cápsulas sabem seu próprio nome , e para obter o ponteiro é necessário " "fornecer o nome:" +#: ../../whatsnew/2.7.rst:2299 +msgid "" +"void *vtable;\n" +"\n" +"if (!PyCapsule_IsValid(capsule, \"mymodule.CAPI\") {\n" +" PyErr_SetString(PyExc_ValueError, \"argument type invalid\");\n" +" return NULL;\n" +"}\n" +"\n" +"vtable = PyCapsule_GetPointer(capsule, \"mymodule.CAPI\");" +msgstr "" +"void *vtable;\n" +"\n" +"if (!PyCapsule_IsValid(capsule, \"mymodule.CAPI\") {\n" +" PyErr_SetString(PyExc_ValueError, \"argument type invalid\");\n" +" return NULL;\n" +"}\n" +"\n" +"vtable = PyCapsule_GetPointer(capsule, \"mymodule.CAPI\");" + #: ../../whatsnew/2.7.rst:2310 msgid "" "You are assured that ``vtable`` points to whatever you're expecting. If a " @@ -4287,8 +5110,8 @@ msgid "" "This section lists previously described changes and other bugfixes that may " "require changes to your code:" msgstr "" -"Esta seção lista as alterações descritas anteriormente e outras correções de " -"bugs que podem exigir alterações em seu código:" +"Esta seção lista as alterações descritas anteriormente e outras correções " +"que podem exigir alterações no seu código." #: ../../whatsnew/2.7.rst:2444 msgid "" @@ -4639,7 +5462,7 @@ msgstr "" #: ../../whatsnew/2.7.rst:2658 msgid "Bootstrapping pip By Default" -msgstr "Inicializando pip por padrão" +msgstr "Bootstrapping pip By Default" #: ../../whatsnew/2.7.rst:2660 msgid "" @@ -4689,30 +5512,32 @@ msgid "" "default, otherwise it can still be accessed through the Python launcher for " "Windows as ``py -m pip``." msgstr "" -"No Windows e Mac OS X, os instaladores do CPython agora instalam o ``pip`` " -"junto com o próprio CPython (os usuários podem optar por não instalá-lo " -"durante o processo de instalação). Os usuários do Windows precisarão optar " -"pelas modificações automáticas do ``PATH`` para ter o ``pip`` disponível na " -"linha de comando por padrão, caso contrário ele ainda poderá ser acessado " -"através do iniciador Python para Windows como ``py -m pip``." +"On Windows and Mac OS X, the CPython installers now default to installing " +"``pip`` along with CPython itself (users may opt out of installing it during " +"the installation process). Window users will need to opt in to the automatic " +"``PATH`` modifications to have ``pip`` available from the command line by " +"default, otherwise it can still be accessed through the Python launcher for " +"Windows as ``py -m pip``." #: ../../whatsnew/2.7.rst:2683 msgid "" -"As `discussed in the PEP`__, platform packagers may choose not to install " -"these commands by default, as long as, when invoked, they provide clear and " -"simple directions on how to install them on that platform (usually using the " -"system package manager)." +"As :pep:`discussed in the PEP <0477#disabling-ensurepip-by-downstream-" +"distributors>`, platform packagers may choose not to install these commands " +"by default, as long as, when invoked, they provide clear and simple " +"directions on how to install them on that platform (usually using the system " +"package manager)." msgstr "" -"Como `discutido na PEP`__, os empacotadores de plataforma podem optar por " -"não instalar estes comandos por padrão, desde que, quando invocados, " -"forneçam instruções claras e simples sobre como instalá-los naquela " -"plataforma (geralmente usando o gerenciador de pacotes do sistema). ." +"Como :pep:`discutido na PEP <0477#disabling-ensurepip-by-downstream-" +"distributors>`, os empacotadores de plataforma podem optar por não instalar " +"estes comandos por padrão, desde que, quando invocados, forneçam instruções " +"claras e simples sobre como instalá-los naquela plataforma (geralmente " +"usando o gerenciador de pacotes do sistema). ." -#: ../../whatsnew/2.7.rst:2692 +#: ../../whatsnew/2.7.rst:2690 msgid "Documentation Changes" msgstr "Mudanças na documentação" -#: ../../whatsnew/2.7.rst:2694 +#: ../../whatsnew/2.7.rst:2692 msgid "" "As part of this change, the :ref:`installing-index` and :ref:`distributing-" "index` sections of the documentation have been completely redesigned as " @@ -4721,14 +5546,14 @@ msgid "" "Packaging User Guide `__ and the documentation " "of the individual projects." msgstr "" -"Como parte desta mudança, as seções :ref:`installing-index` e :ref:" -"`distributing-index` da documentação foram completamente redesenhadas como " -"breves documentos de introdução e FAQ. A maior parte da documentação de " -"empacotamento agora foi transferida para o Python Packaging Authority, " -"mantido no `Guia de Usuário para Empacotamento de Python `__ e na documentação dos projetos individuais." +"As part of this change, the :ref:`installing-index` and :ref:`distributing-" +"index` sections of the documentation have been completely redesigned as " +"short getting started and FAQ documents. Most packaging documentation has " +"now been moved out to the Python Packaging Authority maintained `Python " +"Packaging User Guide `__ and the documentation " +"of the individual projects." -#: ../../whatsnew/2.7.rst:2702 +#: ../../whatsnew/2.7.rst:2700 msgid "" "However, as this migration is currently still incomplete, the legacy " "versions of those guides remaining available as :ref:`install-index` and :" @@ -4738,26 +5563,26 @@ msgstr "" "desses guias permanecem disponíveis como :ref:`install-index` e :ref:" "`setuptools-index`." -#: ../../whatsnew/2.7.rst:2708 +#: ../../whatsnew/2.7.rst:2706 msgid ":pep:`453` -- Explicit bootstrapping of pip in Python installations" -msgstr ":pep:`453` -- Inicialização explícita do pip em instalações Python" +msgstr ":pep:`453` -- Explicit bootstrapping of pip in Python installations" -#: ../../whatsnew/2.7.rst:2709 +#: ../../whatsnew/2.7.rst:2707 msgid "" "PEP written by Donald Stufft and Nick Coghlan, implemented by Donald Stufft, " "Nick Coghlan, Martin von Löwis and Ned Deily." msgstr "" -"PEP escrita por Donald Stufft e Nick Coghlan, implementada por Donald " -"Stufft, Nick Coghlan, Martin von Löwis e Ned Deily." +"PEP written by Donald Stufft and Nick Coghlan, implemented by Donald Stufft, " +"Nick Coghlan, Martin von Löwis and Ned Deily." -#: ../../whatsnew/2.7.rst:2713 +#: ../../whatsnew/2.7.rst:2711 msgid "" "PEP 476: Enabling certificate verification by default for stdlib http clients" msgstr "" "PEP 476: Habilitando verificação de certificado por padrão para clientes " "http stdlib" -#: ../../whatsnew/2.7.rst:2715 +#: ../../whatsnew/2.7.rst:2713 msgid "" ":pep:`476` updated :mod:`httplib ` and modules which use it, such as :" "mod:`urllib2 ` and :mod:`xmlrpclib `, to now " @@ -4774,7 +5599,7 @@ msgstr "" "significativamente a segurança para muitas aplicações. Essa alteração foi " "feita na versão 2.7.9 do Python." -#: ../../whatsnew/2.7.rst:2723 +#: ../../whatsnew/2.7.rst:2721 msgid "" "For applications which require the old previous behavior, they can pass an " "alternate context::" @@ -4782,11 +5607,37 @@ msgstr "" "Para aplicações que exigem o antigo comportamento anterior, elas podem " "passar um contexto alternativo::" -#: ../../whatsnew/2.7.rst:2740 +#: ../../whatsnew/2.7.rst:2724 +msgid "" +"import urllib2\n" +"import ssl\n" +"\n" +"# This disables all verification\n" +"context = ssl._create_unverified_context()\n" +"\n" +"# This allows using a specific certificate for the host, which doesn't need\n" +"# to be in the trust store\n" +"context = ssl.create_default_context(cafile=\"/path/to/file.crt\")\n" +"\n" +"urllib2.urlopen(\"https://invalid-cert\", context=context)" +msgstr "" +"import urllib2\n" +"import ssl\n" +"\n" +"# Isso desabilita toda verificação\n" +"context = ssl._create_unverified_context()\n" +"\n" +"# Isso permite usar um certificado específico para o host,\n" +"# o que não precisa ser no armazenamento de confiança\n" +"context = ssl.create_default_context(cafile=\"/path/to/file.crt\")\n" +"\n" +"urllib2.urlopen(\"https://invalid-cert\", context=context)" + +#: ../../whatsnew/2.7.rst:2738 msgid "PEP 493: HTTPS verification migration tools for Python 2.7" msgstr "PEP 493: Ferramentas de migração de verificação HTTPS para Python 2.7" -#: ../../whatsnew/2.7.rst:2742 +#: ../../whatsnew/2.7.rst:2740 msgid "" ":pep:`493` provides additional migration tools to support a more incremental " "infrastructure upgrade process for environments containing applications and " @@ -4800,7 +5651,7 @@ msgstr "" "permissivo de certificados de servidor ao estabelecer conexões HTTPS de " "clientes. Essas adições foram feitas na versão 2.7.12 do Python." -#: ../../whatsnew/2.7.rst:2748 +#: ../../whatsnew/2.7.rst:2746 msgid "" "These tools are intended for use in cases where affected applications and " "services can't be modified to explicitly pass a more permissive SSL context " @@ -4810,7 +5661,7 @@ msgstr "" "e serviços afetados não podem ser modificados para passar explicitamente um " "contexto SSL mais permissivo ao estabelecer a ligação." -#: ../../whatsnew/2.7.rst:2752 +#: ../../whatsnew/2.7.rst:2750 msgid "" "For applications and services which can't be modified at all, the new " "``PYTHONHTTPSVERIFY`` environment variable may be set to ``0`` to revert an " @@ -4822,7 +5673,7 @@ msgstr "" "todo um processo Python de volta ao comportamento permissivo padrão do " "Python 2.7.8 e anteriores." -#: ../../whatsnew/2.7.rst:2757 +#: ../../whatsnew/2.7.rst:2755 msgid "" "For cases where the connection establishment code can't be modified, but the " "overall application can be, the new :func:`!ssl._https_verify_certificates` " @@ -4833,11 +5684,11 @@ msgstr "" "_https_verify_certificates` pode ser usada para ajustar o comportamento " "padrão em tempo de execução." -#: ../../whatsnew/2.7.rst:2763 +#: ../../whatsnew/2.7.rst:2761 msgid "New ``make regen-all`` build target" msgstr "Novo alvo de construção ``make regen-all``" -#: ../../whatsnew/2.7.rst:2765 +#: ../../whatsnew/2.7.rst:2763 msgid "" "To simplify cross-compilation, and to ensure that CPython can reliably be " "compiled without requiring an existing version of Python to already be " @@ -4850,7 +5701,7 @@ msgstr "" "mais recompilar implicitamente os arquivos gerados com base nos tempos de " "modificação dos arquivos." -#: ../../whatsnew/2.7.rst:2770 +#: ../../whatsnew/2.7.rst:2768 msgid "" "Instead, a new ``make regen-all`` command has been added to force " "regeneration of these files when desired (e.g. after an initial version of " @@ -4860,7 +5711,7 @@ msgstr "" "a regeneração desses arquivos quando desejado (por exemplo, após uma versão " "inicial do Python já ter sido construída com base nas versões pré-geradas)." -#: ../../whatsnew/2.7.rst:2774 +#: ../../whatsnew/2.7.rst:2772 msgid "" "More selective regeneration targets are also defined - see :source:`Makefile." "pre.in` for details." @@ -4868,15 +5719,15 @@ msgstr "" "Alvos de regeneração mais seletivos também são definidos -- veja :source:" "`Makefile.pre.in` para detalhes." -#: ../../whatsnew/2.7.rst:2777 ../../whatsnew/2.7.rst:2790 +#: ../../whatsnew/2.7.rst:2775 ../../whatsnew/2.7.rst:2788 msgid "(Contributed by Victor Stinner in :issue:`23404`.)" msgstr "(Contribuição de Victor Stinner em :issue:`23404`.)" -#: ../../whatsnew/2.7.rst:2783 +#: ../../whatsnew/2.7.rst:2781 msgid "Removal of ``make touch`` build target" msgstr "Remoção do alvo de construção ``make touch``" -#: ../../whatsnew/2.7.rst:2785 +#: ../../whatsnew/2.7.rst:2783 msgid "" "The ``make touch`` build target previously used to request implicit " "regeneration of generated files by updating their modification times has " @@ -4886,15 +5737,15 @@ msgstr "" "regeneração implícita de arquivos gerados atualizando seus tempos de " "modificação foi removido." -#: ../../whatsnew/2.7.rst:2788 +#: ../../whatsnew/2.7.rst:2786 msgid "It has been replaced by the new ``make regen-all`` target." msgstr "Ele foi substituído pelo novo alvo ``make regen-all``." -#: ../../whatsnew/2.7.rst:2799 +#: ../../whatsnew/2.7.rst:2797 msgid "Acknowledgements" msgstr "Reconhecimentos" -#: ../../whatsnew/2.7.rst:2801 +#: ../../whatsnew/2.7.rst:2799 msgid "" "The author would like to thank the following people for offering " "suggestions, corrections and assistance with various drafts of this article: " diff --git a/whatsnew/3.0.po b/whatsnew/3.0.po index 7e9707bf1..98c96c55c 100644 --- a/whatsnew/3.0.po +++ b/whatsnew/3.0.po @@ -1,26 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-03 20:15+0000\n" -"PO-Revision-Date: 2021-06-29 13:04+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -114,14 +113,54 @@ msgstr "" "argumentos nomeados para substituir a maior parte da sintaxe especial da " "antiga instrução ``print`` (:pep:`3105`). Exemplos::" +#: ../../whatsnew/3.0.rst:101 +msgid "" +"Old: print \"The answer is\", 2*2\n" +"New: print(\"The answer is\", 2*2)\n" +"\n" +"Old: print x, # Trailing comma suppresses newline\n" +"New: print(x, end=\" \") # Appends a space instead of a newline\n" +"\n" +"Old: print # Prints a newline\n" +"New: print() # You must call the function!\n" +"\n" +"Old: print >>sys.stderr, \"fatal error\"\n" +"New: print(\"fatal error\", file=sys.stderr)\n" +"\n" +"Old: print (x, y) # prints repr((x, y))\n" +"New: print((x, y)) # Not the same as print(x, y)!" +msgstr "" +"Antigo: print \"The answer is\", 2*2\n" +"Novo: print(\"The answer is\", 2*2)\n" +"\n" +"Antigo: print x, # Vírgula no final suprime nova linha\n" +"Novo: print(x, end=\" \") # Anexa um espaço em vez de uma nova linha\n" +"\n" +"Antigo: print # Exibe uma nova linha\n" +"Novo: print() # Você precisa chamar a função!\n" +"\n" +"Antigo: print >>sys.stderr, \"fatal error\"\n" +"Novo: print(\"fatal error\", file=sys.stderr)\n" +"\n" +"Antigo: print (x, y) # Exibe repr((x, y))\n" +"Novo: print((x, y)) # Não é o mesmo que print(x, y)!" + #: ../../whatsnew/3.0.rst:116 msgid "You can also customize the separator between items, e.g.::" msgstr "Você também pode personalizar o separador entre itens, por exemplo::" +#: ../../whatsnew/3.0.rst:118 +msgid "print(\"There are <\", 2**32, \"> possibilities!\", sep=\"\")" +msgstr "print(\"Há <\", 2**32, \"> possibilidades!\", sep=\"\")" + #: ../../whatsnew/3.0.rst:120 msgid "which produces:" msgstr "que produz:" +#: ../../whatsnew/3.0.rst:122 +msgid "There are <4294967296> possibilities!" +msgstr "Há <4294967296> possibilidades!" + #: ../../whatsnew/3.0.rst:126 msgid "Note:" msgstr "Nota:" @@ -180,11 +219,11 @@ msgstr "" #: ../../whatsnew/3.0.rst:153 msgid "" -"Also, the :meth:`dict.iterkeys`, :meth:`dict.iteritems` and :meth:`dict." +"Also, the :meth:`!dict.iterkeys`, :meth:`!dict.iteritems` and :meth:`!dict." "itervalues` methods are no longer supported." msgstr "" -"Além disso, os métodos :meth:`dict.iterkeys`, :meth:`dict.iteritems` e :meth:" -"`dict.itervalues` não são mais suportados." +"Além disso, os métodos :meth:`!dict.iterkeys`, :meth:`!dict.iteritems` e :" +"meth:`!dict.itervalues` não são mais suportados." #: ../../whatsnew/3.0.rst:156 msgid "" @@ -223,10 +262,10 @@ msgstr "" #: ../../whatsnew/3.0.rst:173 msgid "" -":func:`range` now behaves like :func:`xrange` used to behave, except it " +":func:`range` now behaves like :func:`!xrange` used to behave, except it " "works with values of arbitrary size. The latter no longer exists." msgstr "" -":func:`range` agora se comporta como :func:`xrange` costumava se comportar, " +":func:`range` agora se comporta como :func:`!xrange` costumava se comportar, " "exceto que funciona com valores de tamanho arbitrário. Este último não " "existe mais." @@ -259,34 +298,35 @@ msgstr "" "``len <= len`` não são mais válidas e, por exemplo, ``None < None`` levanta :" "exc:`TypeError` em vez de retornar ``False``. Um corolário é que classificar " "uma lista heterogênea não faz mais sentido -- todos os elementos devem ser " -"comparáveis ​​entre si. Observe que isso não se aplica aos operadores ``==`` e " -"``!=``: objetos de diferentes tipos incomparáveis ​​sempre são comparados de " +"comparáveis entre si. Observe que isso não se aplica aos operadores ``==`` e " +"``!=``: objetos de diferentes tipos incomparáveis sempre são comparados de " "forma diferente entre si." #: ../../whatsnew/3.0.rst:195 msgid "" -":meth:`builtin.sorted` and :meth:`list.sort` no longer accept the *cmp* " -"argument providing a comparison function. Use the *key* argument instead. N." -"B. the *key* and *reverse* arguments are now \"keyword-only\"." +":meth:`sorted` and :meth:`list.sort` no longer accept the *cmp* argument " +"providing a comparison function. Use the *key* argument instead. N.B. the " +"*key* and *reverse* arguments are now \"keyword-only\"." msgstr "" -":meth:`builtin.sorted` e :meth:`list.sort` não aceitam mais o argumento " -"*cmp* fornecendo uma função de comparação. Use o argumento *key* em vez " -"disso. N.B. os argumentos *key* e *reverse* agora são \"somente-nomeados\"." +":meth:`sorted` e :meth:`list.sort` não aceitam mais o argumento *cmp* " +"fornecendo uma função de comparação. Use o argumento *key* em vez disso. N." +"B. os argumentos *key* e *reverse* agora são \"somente-nomeados\"." #: ../../whatsnew/3.0.rst:200 msgid "" -"The :func:`cmp` function should be treated as gone, and the :meth:`__cmp__` " -"special method is no longer supported. Use :meth:`__lt__` for sorting, :" -"meth:`__eq__` with :meth:`__hash__`, and other rich comparisons as needed. " -"(If you really need the :func:`cmp` functionality, you could use the " -"expression ``(a > b) - (a < b)`` as the equivalent for ``cmp(a, b)``.)" +"The :func:`!cmp` function should be treated as gone, and the :meth:`!" +"__cmp__` special method is no longer supported. Use :meth:`~object.__lt__` " +"for sorting, :meth:`~object.__eq__` with :meth:`~object.__hash__`, and other " +"rich comparisons as needed. (If you really need the :func:`!cmp` " +"functionality, you could use the expression ``(a > b) - (a < b)`` as the " +"equivalent for ``cmp(a, b)``.)" msgstr "" -"A função :func:`cmp` deve ser tratada como extinta, e o método especial :" -"meth:`__cmp__` não é mais suportado. Use :meth:`__lt__` para classificação, :" -"meth:`__eq__` com :meth:`__hash__` e outras comparações avançadas conforme " -"necessário. (Se você realmente precisa da funcionalidade :func:`cmp`, pode " -"usar a expressão ``(a > b) - (a < b)`` como o equivalente para ``cmp(a, " -"b)``.)" +"A função :func:`!cmp` deve ser tratada como extinta, e o método especial :" +"meth:`!__cmp__` não é mais suportado. Use :meth:`~object.__lt__` para " +"classificação, :meth:`~object.__eq__` com :meth:`~object.__hash__` e outras " +"comparações avançadas conforme necessário. (Se você realmente precisa da " +"funcionalidade :func:`!cmp`, pode usar a expressão ``(a > b) - (a < b)`` " +"como o equivalente para ``cmp(a, b)``.)" #: ../../whatsnew/3.0.rst:207 msgid "Integers" @@ -294,13 +334,13 @@ msgstr "Inteiros" #: ../../whatsnew/3.0.rst:209 msgid "" -":pep:`237`: Essentially, :class:`long` renamed to :class:`int`. That is, " +":pep:`237`: Essentially, :class:`!long` renamed to :class:`int`. That is, " "there is only one built-in integral type, named :class:`int`; but it behaves " -"mostly like the old :class:`long` type." +"mostly like the old :class:`!long` type." msgstr "" -":pep:`237`: Essencialmente, :class:`long` foi renomeado para :class:`int`. " +":pep:`237`: Essencialmente, :class:`!long` foi renomeado para :class:`int`. " "Ou seja, há apenas um tipo integral embutido, chamado :class:`int`; mas ele " -"se comporta principalmente como o antigo tipo :class:`long`." +"se comporta principalmente como o antigo tipo :class:`!long`." #: ../../whatsnew/3.0.rst:213 msgid "" @@ -314,18 +354,18 @@ msgstr "" #: ../../whatsnew/3.0.rst:217 msgid "" -"The :data:`sys.maxint` constant was removed, since there is no longer a " +"The :data:`!sys.maxint` constant was removed, since there is no longer a " "limit to the value of integers. However, :data:`sys.maxsize` can be used as " "an integer larger than any practical list or string index. It conforms to " "the implementation's \"natural\" integer size and is typically the same as :" -"data:`sys.maxint` in previous releases on the same platform (assuming the " +"data:`!sys.maxint` in previous releases on the same platform (assuming the " "same build options)." msgstr "" -"A constante :data:`sys.maxint` foi removida, pois não há mais um limite para " -"o valor de inteiros. No entanto, :data:`sys.maxsize` pode ser usado como um " -"inteiro maior do que qualquer lista prática ou índice de string. Ele está em " -"conformidade com o tamanho inteiro \"natural\" da implementação e é " -"tipicamente o mesmo que :data:`sys.maxint` em versões anteriores na mesma " +"A constante :data:`!sys.maxint` foi removida, pois não há mais um limite " +"para o valor de inteiros. No entanto, :data:`sys.maxsize` pode ser usado " +"como um inteiro maior do que qualquer lista prática ou índice de string. Ele " +"está em conformidade com o tamanho inteiro \"natural\" da implementação e é " +"tipicamente o mesmo que :data:`!sys.maxint` em versões anteriores na mesma " "plataforma (assumindo as mesmas opções de construção)." #: ../../whatsnew/3.0.rst:224 @@ -385,7 +425,7 @@ msgid "" "uses Unicode, encodings or binary data most likely has to change. The " "change is for the better, as in the 2.x world there were numerous bugs " "having to do with mixing encoded and unencoded text. To be prepared in " -"Python 2.x, start using :class:`unicode` for all unencoded text, and :class:" +"Python 2.x, start using :class:`!unicode` for all unencoded text, and :class:" "`str` for binary or encoded data only. Then the ``2to3`` tool will do most " "of the work for you." msgstr "" @@ -393,7 +433,7 @@ msgstr "" "usa Unicode, codificações ou dados binários provavelmente terá que mudar. A " "mudança é para melhor, pois no mundo 2.x havia vários bugs relacionados à " "mistura de texto codificado e não codificado. Para estar preparado no Python " -"2.x, comece a usar :class:`unicode` para todo texto não codificado e :class:" +"2.x, comece a usar :class:`!unicode` para todo texto não codificado e :class:" "`str` apenas para dados binários ou codificados. Então a ferramenta ``2to3`` " "fará a maior parte do trabalho para você." @@ -424,13 +464,14 @@ msgid "" "Like :class:`str`, the :class:`bytes` type is immutable. There is a " "separate *mutable* type to hold buffered binary data, :class:`bytearray`. " "Nearly all APIs that accept :class:`bytes` also accept :class:`bytearray`. " -"The mutable API is based on :class:`collections.MutableSequence`." +"The mutable API is based on :class:`collections.MutableSequence `." msgstr "" "Assim como :class:`str`, o tipo :class:`bytes` é imutável. Há um tipo " "*mutável* separado para armazenar dados binários em buffer, :class:" "`bytearray`. Quase todas as APIs que aceitam :class:`bytes` também aceitam :" "class:`bytearray`. A API mutável é baseada em :class:`collections." -"MutableSequence`." +"MutableSequence `." #: ../../whatsnew/3.0.rst:274 msgid "" @@ -450,17 +491,17 @@ msgstr "" #: ../../whatsnew/3.0.rst:281 msgid "" -"The built-in :class:`basestring` abstract type was removed. Use :class:" +"The built-in :class:`!basestring` abstract type was removed. Use :class:" "`str` instead. The :class:`str` and :class:`bytes` types don't have " "functionality enough in common to warrant a shared base class. The ``2to3`` " -"tool (see below) replaces every occurrence of :class:`basestring` with :" +"tool (see below) replaces every occurrence of :class:`!basestring` with :" "class:`str`." msgstr "" -"O tipo abstrato embutido :class:`basestring` foi removido. Use :class:`str` " +"O tipo abstrato embutido :class:`!basestring` foi removido. Use :class:`str` " "em vez disso. Os tipos :class:`str` e :class:`bytes` não têm funcionalidade " "suficiente em comum para garantir uma classe base compartilhada. A " -"ferramenta ``2to3`` (veja abaixo) substitui cada ocorrência de :class:" -"`basestring` por :class:`str`." +"ferramenta ``2to3`` (veja abaixo) substitui cada ocorrência de :class:`!" +"basestring` por :class:`str`." #: ../../whatsnew/3.0.rst:287 msgid "" @@ -489,7 +530,7 @@ msgstr "" "correto (texto ou binário) ao abrir um arquivo. Há uma codificação padrão " "dependente da plataforma, que em plataformas Unixy pode ser definida com a " "variável de ambiente ``LANG`` (e às vezes também com algumas outras " -"variáveis ​​de ambiente relacionadas à localidade específicas da plataforma). " +"variáveis de ambiente relacionadas à localidade específicas da plataforma). " "Em muitos casos, mas não em todos, o padrão do sistema é UTF-8; você nunca " "deve contar com esse padrão. Qualquer aplicação que leia ou escreva mais do " "que texto ASCII puro provavelmente deve ter uma maneira de substituir a " @@ -523,7 +564,7 @@ msgid "" "strings, filenames that cannot be decoded properly are omitted rather than " "raising :exc:`UnicodeError`." msgstr "" -"Nomes de arquivo são passados ​​e retornados de APIs como strings (Unicode). " +"Nomes de arquivo são passados e retornados de APIs como strings (Unicode). " "Isso pode apresentar problemas específicos de plataforma porque em algumas " "plataformas nomes de arquivo são strings de bytes arbitrárias. (Por outro " "lado, no Windows nomes de arquivo são armazenados nativamente como Unicode.) " @@ -547,7 +588,7 @@ msgid "" msgstr "" "Algumas APIs de sistema como :data:`os.environ` e :data:`sys.argv` também " "podem apresentar problemas quando os bytes disponibilizados pelo sistema não " -"são interpretáveis ​​usando a codificação padrão. Definir a variável ``LANG`` " +"são interpretáveis usando a codificação padrão. Definir a variável ``LANG`` " "e executar o programa novamente é provavelmente a melhor abordagem." #: ../../whatsnew/3.0.rst:330 @@ -587,7 +628,8 @@ msgstr "" #: ../../whatsnew/3.0.rst:344 msgid "See also the :ref:`unicode-howto`, which was updated for Python 3.0." msgstr "" -"Veja também o :ref:`unicode-howto`, que foi atualizado para o Python 3.0." +"Veja também o guia :ref:`unicode-howto`, que foi atualizado para o Python " +"3.0." #: ../../whatsnew/3.0.rst:348 msgid "Overview Of Syntax Changes" @@ -610,15 +652,15 @@ msgid "" ":pep:`3107`: Function argument and return value annotations. This provides " "a standardized way of annotating a function's parameters and return value. " "There are no semantics attached to such annotations except that they can be " -"introspected at runtime using the :attr:`__annotations__` attribute. The " +"introspected at runtime using the :attr:`!__annotations__` attribute. The " "intent is to encourage experimentation through metaclasses, decorators or " "frameworks." msgstr "" ":pep:`3107`: Anotações de argumento de função e valor de retorno. Isso " "fornece uma maneira padronizada de anotar os parâmetros e o valor de retorno " "de uma função. Não há semântica anexada a essas anotações, exceto que elas " -"podem ser introspectadas em tempo de execução usando o atributo :attr:" -"`__annotations__`. A intenção é encorajar a experimentação por meio de " +"podem ser introspectadas em tempo de execução usando o atributo :attr:`!" +"__annotations__`. A intenção é encorajar a experimentação por meio de " "metaclasses, decoradores ou frameworks." #: ../../whatsnew/3.0.rst:363 @@ -669,6 +711,10 @@ msgstr "" "stuff``. O objeto ``rest`` é sempre uma lista (possivelmente vazia); o lado " "direito pode ser qualquer iterável. Exemplo::" +#: ../../whatsnew/3.0.rst:383 +msgid "(a, *rest, b) = range(5)" +msgstr "(a, *rest, b) = range(5)" + #: ../../whatsnew/3.0.rst:385 msgid "This sets *a* to ``0``, *b* to ``4``, and *rest* to ``[1, 2, 3]``." msgstr "" @@ -759,19 +805,37 @@ msgstr "" msgid ":pep:`3115`: New Metaclass Syntax. Instead of::" msgstr ":pep:`3115`: Nova sintaxe de metaclasse. Em vez de::" +#: ../../whatsnew/3.0.rst:422 +msgid "" +"class C:\n" +" __metaclass__ = M\n" +" ..." +msgstr "" +"class C:\n" +" __metaclass__ = M\n" +" ..." + #: ../../whatsnew/3.0.rst:426 msgid "you must now use::" msgstr "agora você deve usar::" +#: ../../whatsnew/3.0.rst:428 +msgid "" +"class C(metaclass=M):\n" +" ..." +msgstr "" +"class C(metaclass=M):\n" +" ..." + #: ../../whatsnew/3.0.rst:431 msgid "" -"The module-global :data:`__metaclass__` variable is no longer supported. " +"The module-global :data:`!__metaclass__` variable is no longer supported. " "(It was a crutch to make it easier to default to new-style classes without " "deriving every class from :class:`object`.)" msgstr "" -"A variável global do módulo :data:`__metaclass__` não é mais suportada. (Era " -"uma ajuda para facilitar a mudança do padrão para classes de novo estilo sem " -"derivar cada classe de :class:`object`.)" +"A variável global do módulo :data:`!__metaclass__` não é mais suportada. " +"(Era uma ajuda para facilitar a mudança do padrão para classes de novo " +"estilo sem derivar cada classe de :class:`object`.)" #: ../../whatsnew/3.0.rst:436 msgid "" @@ -787,7 +851,7 @@ msgstr "" "({item1}, {item2}, ...)]` em vez disso. Observe também que as compreensões " "de lista têm semântica diferente: elas estão mais próximas do açúcar " "sintático para uma expressão geradora dentro de um construtor :func:`list` " -"e, em particular, as variáveis ​​de controle de laço não são mais vazadas para " +"e, em particular, as variáveis de controle de laço não são mais vazadas para " "o escopo circundante." #: ../../whatsnew/3.0.rst:444 @@ -959,7 +1023,7 @@ msgid "" "and has additional keyword arguments *encoding*, *errors*, *newline* and " "*closefd*. Also note that an invalid *mode* argument now raises :exc:" "`ValueError`, not :exc:`IOError`. The binary file object underlying a text " -"file object can be accessed as :attr:`f.buffer` (but beware that the text " +"file object can be accessed as :attr:`!f.buffer` (but beware that the text " "object maintains a buffer of itself in order to speed up the encoding and " "decoding operations)." msgstr "" @@ -968,16 +1032,16 @@ msgstr "" "open` e tem argumentos nomeados adicionais *encoding*, *errors*, *newline* e " "*closefd*. Observe também que um argumento *mode* inválido agora levanta :" "exc:`ValueError`, não :exc:`IOError`. O objeto arquivo binário subjacente a " -"um objeto arquivo texto pode ser acessado como :attr:`f.buffer` (mas tome " +"um objeto arquivo texto pode ser acessado como :attr:`!f.buffer` (mas tome " "cuidado, pois o objeto texto mantém um buffer de si mesmo para acelerar as " "operações de codificação e decodificação)." #: ../../whatsnew/3.0.rst:529 msgid "" -":ref:`pep-3118`. The old builtin :func:`buffer` is now really gone; the new " -"builtin :func:`memoryview` provides (mostly) similar functionality." +":ref:`pep-3118`. The old builtin :func:`!buffer` is now really gone; the " +"new builtin :func:`memoryview` provides (mostly) similar functionality." msgstr "" -":ref:`pep-3118`. A antiga função embutida :func:`buffer` agora realmente se " +":ref:`pep-3118`. A antiga função embutida :func:`!buffer` agora realmente se " "foi; a nova função embutida :func:`memoryview` fornece funcionalidade " "(principalmente) semelhante." @@ -986,14 +1050,16 @@ msgid "" ":ref:`pep-3119`. The :mod:`abc` module and the ABCs defined in the :mod:" "`collections` module plays a somewhat more prominent role in the language " "now, and built-in collection types like :class:`dict` and :class:`list` " -"conform to the :class:`collections.MutableMapping` and :class:`collections." -"MutableSequence` ABCs, respectively." +"conform to the :class:`collections.MutableMapping ` and :class:`collections.MutableSequence ` ABCs, respectively." msgstr "" ":ref:`pep-3119`. O módulo :mod:`abc` e as ABCs definidas no módulo :mod:" "`collections` desempenham um papel um pouco mais proeminente na linguagem " "agora, e tipos embutidos de coleção como :class:`dict` e :class:`list` estão " -"em conformidade com as ABCs :class:`collections.MutableMapping` e :class:" -"`collections.MutableSequence`, respectivamente." +"em conformidade com as ABCs :class:`collections.MutableMapping ` e :class:`collections.MutableSequence `, respectivamente." #: ../../whatsnew/3.0.rst:539 msgid "" @@ -1072,7 +1138,7 @@ msgstr "" #: ../../whatsnew/3.0.rst:576 msgid "Old Name" -msgstr "Antigo nome" +msgstr "Old Name" #: ../../whatsnew/3.0.rst:576 msgid "New Name" @@ -1197,12 +1263,12 @@ msgstr "" #: ../../whatsnew/3.0.rst:615 msgid "" -":mod:`tkinter` (all :mod:`Tkinter`-related modules except :mod:`turtle`). " -"The target audience of :mod:`turtle` doesn't really care about :mod:" -"`tkinter`. Also note that as of Python 2.6, the functionality of :mod:" -"`turtle` has been greatly enhanced." +":mod:`tkinter` (all ``Tkinter``-related modules except :mod:`turtle`). The " +"target audience of :mod:`turtle` doesn't really care about :mod:`tkinter`. " +"Also note that as of Python 2.6, the functionality of :mod:`turtle` has been " +"greatly enhanced." msgstr "" -":mod:`tkinter` (todos os módulos relacionados a :mod:`Tkinter`, exceto :mod:" +":mod:`tkinter` (todos os módulos relacionados a ``Tkinter``, exceto :mod:" "`turtle`). O público-alvo de :mod:`turtle` não se importa muito com :mod:" "`tkinter`. Observe também que, a partir do Python 2.6, a funcionalidade de :" "mod:`turtle` foi bastante aprimorada." @@ -1236,33 +1302,31 @@ msgstr ":mod:`!sets` eliminado. Use a classe embutida :func:`set`." #: ../../whatsnew/3.0.rst:631 msgid "" -"Cleanup of the :mod:`sys` module: removed :func:`sys.exitfunc`, :func:`sys." -"exc_clear`, :data:`sys.exc_type`, :data:`sys.exc_value`, :data:`sys." +"Cleanup of the :mod:`sys` module: removed :func:`!sys.exitfunc`, :func:`!sys." +"exc_clear`, :data:`!sys.exc_type`, :data:`!sys.exc_value`, :data:`!sys." "exc_traceback`. (Note that :data:`sys.last_type` etc. remain.)" msgstr "" -"Limpeza do módulo :mod:`sys`: removidos :func:`sys.exitfunc`, :func:`sys." -"exc_clear`, :data:`sys.exc_type`, :data:`sys.exc_value`, :data:`sys." +"Limpeza do módulo :mod:`sys`: removidos :func:`!sys.exitfunc`, :func:`!sys." +"exc_clear`, :data:`!sys.exc_type`, :data:`!sys.exc_value`, :data:`!sys." "exc_traceback`. (Observe que :data:`sys.last_type` etc. permanecem.)" #: ../../whatsnew/3.0.rst:636 msgid "" -"Cleanup of the :class:`array.array` type: the :meth:`read` and :meth:`write` " -"methods are gone; use :meth:`fromfile` and :meth:`tofile` instead. Also, " -"the ``'c'`` typecode for array is gone -- use either ``'b'`` for bytes or " -"``'u'`` for Unicode characters." +"Cleanup of the :class:`array.array` type: the :meth:`!read` and :meth:`!" +"write` methods are gone; use :meth:`~array.array.fromfile` and :meth:`~array." +"array.tofile` instead. Also, the ``'c'`` typecode for array is gone -- use " +"either ``'b'`` for bytes or ``'u'`` for Unicode characters." msgstr "" -"Limpeza do tipo :class:`array.array`: os métodos :meth:`read` e :meth:" -"`write` foram removidos; use :meth:`fromfile` e :meth:`tofile` em vez disso. " -"Além disso, o typecode ``'c'`` para vetor foi removido -- use ``'b'`` para " -"bytes ou ``'u'`` para caracteres Unicode." +"Limpeza do tipo :class:`array.array`: os métodos :meth:`!read` e :meth:`!" +"write` foram removidos; use :meth:`~array.array.fromfile` e :meth:`~array." +"array.tofile` em vez disso. Além disso, o typecode ``'c'`` para vetor foi " +"removido -- use ``'b'`` para bytes ou ``'u'`` para caracteres Unicode." #: ../../whatsnew/3.0.rst:642 msgid "" -"Cleanup of the :mod:`operator` module: removed :func:`sequenceIncludes` and :" -"func:`isCallable`." +"Cleanup of the :mod:`operator` module: removed :func:`!sequenceIncludes` " +"and :func:`!isCallable`." msgstr "" -"Limpeza do módulo :mod:`operator`: removidos :func:`sequenceIncludes` e :" -"func:`isCallable`." #: ../../whatsnew/3.0.rst:645 msgid "" @@ -1275,8 +1339,9 @@ msgstr "" "`~threading.Lock.release` em vez disso." #: ../../whatsnew/3.0.rst:649 -msgid "Cleanup of the :mod:`random` module: removed the :func:`jumpahead` API." -msgstr "Limpeza do módulo :mod:`random`: removida a API :func:`jumpahead`." +msgid "" +"Cleanup of the :mod:`random` module: removed the :func:`!jumpahead` API." +msgstr "" #: ../../whatsnew/3.0.rst:651 msgid "The :mod:`!new` module is gone." @@ -1284,11 +1349,9 @@ msgstr "O módulo :mod:`!new` foi removido." #: ../../whatsnew/3.0.rst:653 msgid "" -"The functions :func:`os.tmpnam`, :func:`os.tempnam` and :func:`os.tmpfile` " -"have been removed in favor of the :mod:`tempfile` module." +"The functions :func:`!os.tmpnam`, :func:`!os.tempnam` and :func:`!os." +"tmpfile` have been removed in favor of the :mod:`tempfile` module." msgstr "" -"As funções :func:`os.tmpnam`, :func:`os.tempnam` e :func:`os.tmpfile` foram " -"removidas em favor do módulo :mod:`tempfile`." #: ../../whatsnew/3.0.rst:657 msgid "" @@ -1301,29 +1364,20 @@ msgstr "" #: ../../whatsnew/3.0.rst:661 msgid "" -":data:`string.letters` and its friends (:data:`string.lowercase` and :data:" -"`string.uppercase`) are gone. Use :data:`string.ascii_letters` etc. " -"instead. (The reason for the removal is that :data:`string.letters` and " +":data:`!string.letters` and its friends (:data:`!string.lowercase` and :data:" +"`!string.uppercase`) are gone. Use :data:`string.ascii_letters` etc. " +"instead. (The reason for the removal is that :data:`!string.letters` and " "friends had locale-specific behavior, which is a bad idea for such " "attractively named global \"constants\".)" msgstr "" -":data:`string.letters` e seus amigos (:data:`string.lowercase` e :data:" -"`string.uppercase`) se foram. Use :data:`string.ascii_letters` etc. em vez " -"disso. (O motivo da remoção é que :data:`string.letters` e amigos tinham " -"comportamento específico de localidade, o que é uma má ideia para " -"\"constantes\" globais com nomes tão atraentes.)" #: ../../whatsnew/3.0.rst:668 msgid "" -"Renamed module :mod:`__builtin__` to :mod:`builtins` (removing the " -"underscores, adding an 's'). The :data:`__builtins__` variable found in " +"Renamed module :mod:`!__builtin__` to :mod:`builtins` (removing the " +"underscores, adding an 's'). The :data:`!__builtins__` variable found in " "most global namespaces is unchanged. To modify a builtin, you should use :" -"mod:`builtins`, not :data:`__builtins__`!" +"mod:`builtins`, not :data:`!__builtins__`!" msgstr "" -"Renomeado o módulo :mod:`__builtin__` para :mod:`builtins` (removendo os " -"sublinhados, adicionando um 's'). A variável :data:`__builtins__` encontrada " -"na maioria dos espaços de nomes globais não foi alterada. Para modificar um " -"builtin, você deve usar :mod:`builtins`, não :data:`__builtins__`!" #: ../../whatsnew/3.0.rst:675 msgid ":pep:`3101`: A New Approach To String Formatting" @@ -1387,16 +1441,14 @@ msgstr "" "`Exception`." #: ../../whatsnew/3.0.rst:705 -msgid ":exc:`StandardError` was removed." -msgstr ":exc:`StandardError` foi removida." +msgid ":exc:`!StandardError` was removed." +msgstr "" #: ../../whatsnew/3.0.rst:707 msgid "" -"Exceptions no longer behave as sequences. Use the :attr:`args` attribute " -"instead." +"Exceptions no longer behave as sequences. Use the :attr:`~BaseException." +"args` attribute instead." msgstr "" -"As exceções não se comportam mais como sequências. Use o atributo :attr:" -"`args` em vez disso." #: ../../whatsnew/3.0.rst:710 msgid "" @@ -1444,6 +1496,10 @@ msgstr "" "`~BaseException.__context__` da exceção secundária. O encadeamento explícito " "é invocado com esta sintaxe::" +#: ../../whatsnew/3.0.rst:731 +msgid "raise SecondaryException() from primary_exception" +msgstr "raise SecondaryException() from primary_exception" + #: ../../whatsnew/3.0.rst:733 msgid "" "(where *primary_exception* is any expression that produces an exception " @@ -1516,15 +1572,11 @@ msgstr "" #: ../../whatsnew/3.0.rst:768 msgid "" -":meth:`__getslice__`, :meth:`__setslice__` and :meth:`__delslice__` were " +":meth:`!__getslice__`, :meth:`!__setslice__` and :meth:`!__delslice__` were " "killed. The syntax ``a[i:j]`` now translates to ``a.__getitem__(slice(i, " -"j))`` (or :meth:`__setitem__` or :meth:`__delitem__`, when used as an " -"assignment or deletion target, respectively)." +"j))`` (or :meth:`~object.__setitem__` or :meth:`~object.__delitem__`, when " +"used as an assignment or deletion target, respectively)." msgstr "" -":meth:`__getslice__`, :meth:`__setslice__` e :meth:`__delslice__` foram " -"eliminados. A sintaxe ``a[i:j]`` agora é traduzida para ``a." -"__getitem__(slice(i, j))`` (ou :meth:`__setitem__` ou :meth:`__delitem__`, " -"quando usado como um alvo de atribuição ou exclusão, respectivamente)." #: ../../whatsnew/3.0.rst:774 msgid "" @@ -1536,17 +1588,14 @@ msgstr "" #: ../../whatsnew/3.0.rst:777 msgid "" -"The :meth:`__oct__` and :meth:`__hex__` special methods are removed -- :func:" -"`oct` and :func:`hex` use :meth:`__index__` now to convert the argument to " -"an integer." +"The :meth:`!__oct__` and :meth:`!__hex__` special methods are removed -- :" +"func:`oct` and :func:`hex` use :meth:`~object.__index__` now to convert the " +"argument to an integer." msgstr "" -"Os métodos especiais :meth:`__oct__` e :meth:`__hex__` foram removidos -- :" -"func:`oct` e :func:`hex` usam :meth:`__index__` agora para converter o " -"argumento em um inteiro." #: ../../whatsnew/3.0.rst:781 -msgid "Removed support for :attr:`__members__` and :attr:`__methods__`." -msgstr "Removido o suporte para :attr:`__members__` e :attr:`__methods__`." +msgid "Removed support for :attr:`!__members__` and :attr:`!__methods__`." +msgstr "" #: ../../whatsnew/3.0.rst:783 msgid "" @@ -1593,17 +1642,12 @@ msgstr "" #: ../../whatsnew/3.0.rst:805 msgid "" -":pep:`3111`: :func:`raw_input` was renamed to :func:`input`. That is, the " +":pep:`3111`: :func:`!raw_input` was renamed to :func:`input`. That is, the " "new :func:`input` function reads a line from :data:`sys.stdin` and returns " "it with the trailing newline stripped. It raises :exc:`EOFError` if the " "input is terminated prematurely. To get the old behavior of :func:`input`, " "use ``eval(input())``." msgstr "" -":pep:`3111`: :func:`raw_input` foi renomeada para :func:`input`. Ou seja, a " -"nova função :func:`input` lê uma linha de :data:`sys.stdin` e a retorna com " -"a nova linha final removida. Ela levanta :exc:`EOFError` se a entrada for " -"encerrada prematuramente. Para obter o comportamento antigo de :func:" -"`input`, use ``eval(input())``." #: ../../whatsnew/3.0.rst:811 msgid "" @@ -1632,68 +1676,54 @@ msgstr "" "valor do mesmo tipo que ``x`` quando chamado com dois argumentos." #: ../../whatsnew/3.0.rst:823 -msgid "Moved :func:`intern` to :func:`sys.intern`." -msgstr "Movida :func:`intern` para :func:`sys.intern`." +msgid "Moved :func:`!intern` to :func:`sys.intern`." +msgstr "" #: ../../whatsnew/3.0.rst:825 msgid "" -"Removed: :func:`apply`. Instead of ``apply(f, args)`` use ``f(*args)``." +"Removed: :func:`!apply`. Instead of ``apply(f, args)`` use ``f(*args)``." msgstr "" -"Removida: :func:`apply`. Em vez de ``apply(f, args)`` use ``f(*args)``." #: ../../whatsnew/3.0.rst:828 msgid "" "Removed :func:`callable`. Instead of ``callable(f)`` you can use " -"``isinstance(f, collections.Callable)``. The :func:`operator.isCallable` " +"``isinstance(f, collections.Callable)``. The :func:`!operator.isCallable` " "function is also gone." msgstr "" -"Removida :func:`callable`. Em vez de ``callable(f)`` você pode usar " -"``isinstance(f, collections.Callable)``. A função :func:`operator." -"isCallable` também foi removida." #: ../../whatsnew/3.0.rst:832 msgid "" -"Removed :func:`coerce`. This function no longer serves a purpose now that " +"Removed :func:`!coerce`. This function no longer serves a purpose now that " "classic classes are gone." msgstr "" -"Removida :func:`coerce`. Esta função não tem mais propósito agora que as " -"classes clássicas desapareceram." #: ../../whatsnew/3.0.rst:835 msgid "" -"Removed :func:`execfile`. Instead of ``execfile(fn)`` use ``exec(open(fn)." +"Removed :func:`!execfile`. Instead of ``execfile(fn)`` use ``exec(open(fn)." "read())``." msgstr "" -"Removida :func:`execfile`. Em vez de ``execfile(fn)`` use ``exec(open(fn)." -"read())``." #: ../../whatsnew/3.0.rst:838 msgid "" -"Removed the :class:`file` type. Use :func:`open`. There are now several " +"Removed the :class:`!file` type. Use :func:`open`. There are now several " "different kinds of streams that open can return in the :mod:`io` module." msgstr "" -"Removido o tipo :class:`file`. Use :func:`open`. Agora há vários tipos " -"diferentes de fluxos que open pode retornar no módulo :mod:`io`." #: ../../whatsnew/3.0.rst:841 msgid "" -"Removed :func:`reduce`. Use :func:`functools.reduce` if you really need it; " -"however, 99 percent of the time an explicit :keyword:`for` loop is more " +"Removed :func:`!reduce`. Use :func:`functools.reduce` if you really need " +"it; however, 99 percent of the time an explicit :keyword:`for` loop is more " "readable." msgstr "" -"Removida :func:`reduce`. Use :func:`functools.reduce` se realmente precisar; " -"no entanto, 99 por cento das vezes um laço explícito :keyword:`for` é mais " -"legível." #: ../../whatsnew/3.0.rst:845 -msgid "Removed :func:`reload`. Use :func:`!imp.reload`." -msgstr "Removida :func:`reload`. Use :func:`!imp.reload`." +msgid "Removed :func:`!reload`. Use :func:`!imp.reload`." +msgstr "" #: ../../whatsnew/3.0.rst:847 msgid "" -"Removed. :meth:`dict.has_key` -- use the :keyword:`in` operator instead." +"Removed. :meth:`!dict.has_key` -- use the :keyword:`in` operator instead." msgstr "" -"Removida. :meth:`dict.has_key` -- use o operador :keyword:`in` em vez disso." #: ../../whatsnew/3.0.rst:854 msgid "Build and C API Changes" diff --git a/whatsnew/3.1.po b/whatsnew/3.1.po index 12d3d9a8e..965a3a028 100644 --- a/whatsnew/3.1.po +++ b/whatsnew/3.1.po @@ -1,29 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Ricardo Cappellano , 2021 -# Claudio Rogerio Carvalho Filho , 2023 -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-29 13:04+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -122,6 +118,24 @@ msgstr "" "ser usada em conjunto com classificação para criar um dicionário " "classificado::" +#: ../../whatsnew/3.1.rst:86 +msgid "" +">>> # regular unsorted dictionary\n" +">>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}\n" +"\n" +">>> # dictionary sorted by key\n" +">>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n" +"OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])\n" +"\n" +">>> # dictionary sorted by value\n" +">>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))\n" +"OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])\n" +"\n" +">>> # dictionary sorted by length of the key string\n" +">>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))\n" +"OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])" +msgstr "" + #: ../../whatsnew/3.1.rst:101 msgid "" "The new sorted dictionaries maintain their sort order when entries are " @@ -148,6 +162,18 @@ msgstr "" "number with a thousands separator. That provides a way to humanize a " "program's output, improving its professional appearance and readability::" +#: ../../whatsnew/3.1.rst:114 +msgid "" +">>> format(1234567, ',d')\n" +"'1,234,567'\n" +">>> format(1234567.89, ',.2f')\n" +"'1,234,567.89'\n" +">>> format(12345.6 + 8901234.12j, ',f')\n" +"'12,345.600000+8,901,234.120000j'\n" +">>> format(Decimal('1234567.89'), ',f')\n" +"'1,234,567.89'" +msgstr "" + #: ../../whatsnew/3.1.rst:123 msgid "" "The supported types are :class:`int`, :class:`float`, :class:`complex` and :" @@ -186,7 +212,7 @@ msgstr "Outras mudanças na linguagem" #: ../../whatsnew/3.1.rst:141 msgid "Some smaller changes made to the core Python language are:" -msgstr "Alguma das mudanças menores feitas no núcleo da linguagem Python são:" +msgstr "Algumas das mudanças menores feitas no núcleo da linguagem Python são:" #: ../../whatsnew/3.1.rst:143 msgid "" @@ -210,6 +236,20 @@ msgstr "" "The :func:`int` type gained a ``bit_length`` method that returns the number " "of bits necessary to represent its argument in binary::" +#: ../../whatsnew/3.1.rst:152 +msgid "" +">>> n = 37\n" +">>> bin(37)\n" +"'0b100101'\n" +">>> n.bit_length()\n" +"6\n" +">>> n = 2**123-1\n" +">>> n.bit_length()\n" +"123\n" +">>> (n+1).bit_length()\n" +"124" +msgstr "" + #: ../../whatsnew/3.1.rst:163 msgid "" "(Contributed by Fredrik Johansson, Victor Stinner, Raymond Hettinger, and " @@ -224,6 +264,12 @@ msgid "" msgstr "" "The fields in :func:`format` strings can now be automatically numbered::" +#: ../../whatsnew/3.1.rst:169 +msgid "" +">>> 'Sir {} of {}'.format('Gallahad', 'Camelot')\n" +"'Sir Gallahad of Camelot'" +msgstr "" + #: ../../whatsnew/3.1.rst:172 msgid "" "Formerly, the string would have required numbered fields such as: ``'Sir {0} " @@ -264,6 +310,14 @@ msgstr "" "The syntax of the :keyword:`with` statement now allows multiple context " "managers in a single statement::" +#: ../../whatsnew/3.1.rst:189 +msgid "" +">>> with open('mylog.txt') as infile, open('a.out', 'w') as outfile:\n" +"... for line in infile:\n" +"... if '' in line:\n" +"... outfile.write(line)" +msgstr "" + #: ../../whatsnew/3.1.rst:194 msgid "" "With the new syntax, the :func:`!contextlib.nested` function is no longer " @@ -288,6 +342,12 @@ msgstr "" "``round(x, n)`` now returns an integer if *x* is an integer. Previously it " "returned a float::" +#: ../../whatsnew/3.1.rst:203 +msgid "" +">>> round(1123, -2)\n" +"1100" +msgstr "" + #: ../../whatsnew/3.1.rst:206 msgid "(Contributed by Mark Dickinson; :issue:`4707`.)" msgstr "(Contributed by Mark Dickinson; :issue:`4707`.)" @@ -390,6 +450,12 @@ msgstr "" "Added a :class:`collections.Counter` class to support convenient counting of " "unique items in a sequence or iterable::" +#: ../../whatsnew/3.1.rst:252 +msgid "" +">>> Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])\n" +"Counter({'blue': 3, 'red': 2, 'green': 1})" +msgstr "" + #: ../../whatsnew/3.1.rst:255 msgid "(Contributed by Raymond Hettinger; :issue:`1696199`.)" msgstr "(Contributed by Raymond Hettinger; :issue:`1696199`.)" @@ -416,6 +482,13 @@ msgstr "" "The :class:`gzip.GzipFile` and :class:`bz2.BZ2File` classes now support the " "context management protocol::" +#: ../../whatsnew/3.1.rst:266 +msgid "" +">>> # Automatically close file after writing\n" +">>> with gzip.GzipFile(filename, \"wb\") as f:\n" +"... f.write(b\"xxx\")" +msgstr "" + #: ../../whatsnew/3.1.rst:270 msgid "(Contributed by Antoine Pitrou.)" msgstr "(Contribuição de Antoine Pitrou.)" @@ -430,6 +503,12 @@ msgstr "" "from a binary :class:`float`. The conversion is exact but can sometimes be " "surprising::" +#: ../../whatsnew/3.1.rst:276 +msgid "" +">>> Decimal.from_float(1.1)\n" +"Decimal('1.100000000000000088817841970012523233890533447265625')" +msgstr "" + #: ../../whatsnew/3.1.rst:279 msgid "" "The long decimal result shows the actual binary fraction being stored for " @@ -462,6 +541,19 @@ msgstr "" "argument and can accept any type of counting sequence including :class:" "`fractions.Fraction` and :class:`decimal.Decimal`::" +#: ../../whatsnew/3.1.rst:294 +msgid "" +">>> [p+q for p,q in combinations_with_replacement('LOVE', 2)]\n" +"['LL', 'LO', 'LV', 'LE', 'OO', 'OV', 'OE', 'VV', 'VE', 'EE']\n" +"\n" +">>> list(compress(data=range(10), selectors=[0,0,1,1,0,1,0,1,0,0]))\n" +"[2, 3, 5, 7]\n" +"\n" +">>> c = count(start=Fraction(1,2), step=Fraction(1,6))\n" +">>> [next(c), next(c), next(c), next(c)]\n" +"[Fraction(1, 2), Fraction(2, 3), Fraction(5, 6), Fraction(1, 1)]" +msgstr "" + #: ../../whatsnew/3.1.rst:304 msgid "(Contributed by Raymond Hettinger.)" msgstr "(Contributed by Raymond Hettinger.)" @@ -480,6 +572,20 @@ msgstr "" "created by an external source such as a CSV header, SQL field list, or user " "input::" +#: ../../whatsnew/3.1.rst:312 +msgid "" +">>> query = input()\n" +"SELECT region, dept, count(*) FROM main GROUPBY region, dept\n" +"\n" +">>> cursor.execute(query)\n" +">>> query_fields = [desc[0] for desc in cursor.description]\n" +">>> UserQuery = namedtuple('UserQuery', query_fields, rename=True)\n" +">>> pprint.pprint([UserQuery(*row) for row in cursor])\n" +"[UserQuery(region='South', dept='Shipping', _2=185),\n" +" UserQuery(region='North', dept='Accounting', _2=37),\n" +" UserQuery(region='West', dept='Sales', _2=419)]" +msgstr "" + #: ../../whatsnew/3.1.rst:323 msgid "(Contributed by Raymond Hettinger; :issue:`1818`.)" msgstr "(Contributed by Raymond Hettinger; :issue:`1818`.)" @@ -508,6 +614,12 @@ msgstr "" "calling library code that does. Setting-up a null handler will suppress " "spurious warnings such as \"No handlers could be found for logger foo\"::" +#: ../../whatsnew/3.1.rst:335 +msgid "" +">>> h = logging.NullHandler()\n" +">>> logging.getLogger(\"foo\").addHandler(h)" +msgstr "" + #: ../../whatsnew/3.1.rst:338 msgid "(Contributed by Vinay Sajip; :issue:`4384`)." msgstr "(Contributed by Vinay Sajip; :issue:`4384`)." @@ -574,6 +686,20 @@ msgstr "" "is known to be broken, but shouldn't be counted as a failure on a " "TestResult::" +#: ../../whatsnew/3.1.rst:366 +msgid "" +"class TestGizmo(unittest.TestCase):\n" +"\n" +" @unittest.skipUnless(sys.platform.startswith(\"win\"), \"requires " +"Windows\")\n" +" def test_gizmo_on_windows(self):\n" +" ...\n" +"\n" +" @unittest.expectedFailure\n" +" def test_gimzo_without_required_library(self):\n" +" ..." +msgstr "" + #: ../../whatsnew/3.1.rst:376 msgid "" "Also, tests for exceptions have been builtout to work with context managers " @@ -582,6 +708,13 @@ msgstr "" "Also, tests for exceptions have been builtout to work with context managers " "using the :keyword:`with` statement::" +#: ../../whatsnew/3.1.rst:379 +msgid "" +"def test_division_by_zero(self):\n" +" with self.assertRaises(ZeroDivisionError):\n" +" x / 0" +msgstr "" + #: ../../whatsnew/3.1.rst:383 msgid "" "In addition, several new assertion methods were added including :meth:" @@ -616,6 +749,12 @@ msgstr "" msgid "The :data:`sys.version_info` tuple is now a named tuple::" msgstr "The :data:`sys.version_info` tuple is now a named tuple::" +#: ../../whatsnew/3.1.rst:401 +msgid "" +">>> sys.version_info\n" +"sys.version_info(major=3, minor=1, micro=0, releaselevel='alpha', serial=2)" +msgstr "" + #: ../../whatsnew/3.1.rst:404 msgid "(Contributed by Ross Light; :issue:`4285`.)" msgstr "(Contributed by Ross Light; :issue:`4285`.)" @@ -650,6 +789,15 @@ msgstr "" "remapping is turned-on by default but can be disabled with the *fix_imports* " "option::" +#: ../../whatsnew/3.1.rst:420 +msgid "" +">>> s = {1, 2, 3}\n" +">>> pickle.dumps(s, protocol=0)\n" +"b'c__builtin__\\nset\\np0\\n((lp1\\nL1L\\naL2L\\naL3L\\natp2\\nRp3\\n.'\n" +">>> pickle.dumps(s, protocol=0, fix_imports=False)\n" +"b'cbuiltins\\nset\\np0\\n((lp1\\nL1L\\naL2L\\naL3L\\natp2\\nRp3\\n.'" +msgstr "" + #: ../../whatsnew/3.1.rst:426 msgid "" "An unfortunate but unavoidable side-effect of this change is that protocol 2 " @@ -818,7 +966,7 @@ msgstr "Mudanças a construções e API C" #: ../../whatsnew/3.1.rst:502 msgid "Changes to Python's build process and to the C API include:" -msgstr "Changes to Python's build process and to the C API include:" +msgstr "As alterações no processo de construção do Python e na API C incluem:" #: ../../whatsnew/3.1.rst:504 msgid "" @@ -854,6 +1002,13 @@ msgstr "" "interno, fornecendo o número de bits por dígito e o tamanho em bytes do tipo " "C usado para armazenar cada dígito::" +#: ../../whatsnew/3.1.rst:519 +msgid "" +">>> import sys\n" +">>> sys.int_info\n" +"sys.int_info(bits_per_digit=30, sizeof_digit=4)" +msgstr "" + #: ../../whatsnew/3.1.rst:523 msgid "(Contributed by Mark Dickinson; :issue:`4258`.)" msgstr "(Contributed by Mark Dickinson; :issue:`4258`.)" @@ -932,6 +1087,29 @@ msgstr "" "The new floating-point string representations can break existing doctests. " "For example::" +#: ../../whatsnew/3.1.rst:556 +msgid "" +"def e():\n" +" '''Compute the base of natural logarithms.\n" +"\n" +" >>> e()\n" +" 2.7182818284590451\n" +"\n" +" '''\n" +" return sum(1/math.factorial(x) for x in reversed(range(30)))\n" +"\n" +"doctest.testmod()\n" +"\n" +"**********************************************************************\n" +"Failed example:\n" +" e()\n" +"Expected:\n" +" 2.7182818284590451\n" +"Got:\n" +" 2.718281828459045\n" +"**********************************************************************" +msgstr "" + #: ../../whatsnew/3.1.rst:576 msgid "" "The automatic name remapping in the pickle module for protocol 2 or lower " diff --git a/whatsnew/3.10.po b/whatsnew/3.10.po index bae027c96..d844f4855 100644 --- a/whatsnew/3.10.po +++ b/whatsnew/3.10.po @@ -1,33 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Ricardo Cappellano , 2021 -# Victor Matheus Castro , 2021 -# Raphael Mendonça, 2021 -# André Filipe de Assunção e Brito , 2021 -# Alexandre B A Villares, 2021 -# felipe caridade fernandes , 2022 -# Claudio Rogerio Carvalho Filho , 2024 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-29 13:04+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -100,7 +92,7 @@ msgstr "" #: ../../whatsnew/3.10.rst:75 msgid "New typing features:" -msgstr " Novos recursos de tipagem:" +msgstr "Novos recursos de tipagem:" #: ../../whatsnew/3.10.rst:77 msgid ":pep:`604`, Allow writing union types as X | Y" @@ -146,7 +138,7 @@ msgstr ":pep:`624`, Remove APIs codificadoras de Py_UNICODE" msgid ":pep:`597`, Add optional EncodingWarning" msgstr ":pep:`597`, Adiciona EncodingWarning opcional" -#: ../../whatsnew/3.10.rst:92 ../../whatsnew/3.10.rst:2053 +#: ../../whatsnew/3.10.rst:92 ../../whatsnew/3.10.rst:2054 msgid "New Features" msgstr "Novas funcionalidades" @@ -168,11 +160,75 @@ msgstr "" "era possível anteriormente com instruções de importação. Por exemplo, todos " "esses exemplos agora são válidos:" +#: ../../whatsnew/3.10.rst:105 +msgid "" +"with (CtxManager() as example):\n" +" ...\n" +"\n" +"with (\n" +" CtxManager1(),\n" +" CtxManager2()\n" +"):\n" +" ...\n" +"\n" +"with (CtxManager1() as example,\n" +" CtxManager2()):\n" +" ...\n" +"\n" +"with (CtxManager1(),\n" +" CtxManager2() as example):\n" +" ...\n" +"\n" +"with (\n" +" CtxManager1() as example1,\n" +" CtxManager2() as example2\n" +"):\n" +" ..." +msgstr "" +"with (CtxManager() as exemplo):\n" +" ...\n" +"\n" +"with (\n" +" CtxManager1(),\n" +" CtxManager2()\n" +"):\n" +" ...\n" +"\n" +"with (CtxManager1() as exemplo,\n" +" CtxManager2()):\n" +" ...\n" +"\n" +"with (CtxManager1(),\n" +" CtxManager2() as exemplo):\n" +" ...\n" +"\n" +"with (\n" +" CtxManager1() as exemplo1,\n" +" CtxManager2() as exemplo2\n" +"):\n" +" ..." + #: ../../whatsnew/3.10.rst:130 msgid "" "it is also possible to use a trailing comma at the end of the enclosed group:" msgstr "também é possível usar uma vírgula no final do grupo fechado:" +#: ../../whatsnew/3.10.rst:133 +msgid "" +"with (\n" +" CtxManager1() as example1,\n" +" CtxManager2() as example2,\n" +" CtxManager3() as example3,\n" +"):\n" +" ..." +msgstr "" +"with (\n" +" CtxManager1() as exemplo1,\n" +" CtxManager2() as exemplo2,\n" +" CtxManager3() as exemplo3,\n" +"):\n" +" ..." + #: ../../whatsnew/3.10.rst:142 msgid "" "This new syntax uses the non LL(1) capacities of the new parser. Check :pep:" @@ -211,6 +267,16 @@ msgstr "" "algum local incorreto. Por exemplo, considere o seguinte código (observe o " "\"{\" não fechado):" +#: ../../whatsnew/3.10.rst:160 +msgid "" +"expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,\n" +" 38: 4, 39: 4, 45: 5, 46: 5, 47: 5, 48: 5, 49: 5, 54: 6,\n" +"some_other_code = foo()" +msgstr "" +"esperado = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,\n" +" 38: 4, 39: 4, 45: 5, 46: 5, 47: 5, 48: 5, 49: 5, 54: 6,\n" +"algum_outro_codigo = foo()" + #: ../../whatsnew/3.10.rst:166 msgid "" "Previous versions of the interpreter reported confusing places as the " @@ -219,10 +285,34 @@ msgstr "" "Versões anteriores do interpretador relatavam lugares confusos como local do " "erro de sintaxe:" +#: ../../whatsnew/3.10.rst:169 +msgid "" +"File \"example.py\", line 3\n" +" some_other_code = foo()\n" +" ^\n" +"SyntaxError: invalid syntax" +msgstr "" +"File \"exemplo.py\", line 3\n" +" algum_outro_codigo = foo()\n" +" ^\n" +"SyntaxError: invalid syntax" + #: ../../whatsnew/3.10.rst:176 msgid "but in Python 3.10 a more informative error is emitted:" msgstr "mas no Python 3.10, um erro mais informativo é emitido:" +#: ../../whatsnew/3.10.rst:178 +msgid "" +"File \"example.py\", line 1\n" +" expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,\n" +" ^\n" +"SyntaxError: '{' was never closed" +msgstr "" +"File \"exemplo.py\", line 1\n" +" esperado = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,\n" +" ^\n" +"SyntaxError: '{' was never closed" + #: ../../whatsnew/3.10.rst:186 msgid "" "In a similar way, errors involving unclosed string literals (single and " @@ -259,10 +349,38 @@ msgstr "" "sintaxe, em vez de apenas onde o problema foi detectado. Desta forma, em vez " "de exibir (antes do Python 3.10):" +#: ../../whatsnew/3.10.rst:199 +msgid "" +">>> foo(x, z for z in range(10), t, w)\n" +" File \"\", line 1\n" +" foo(x, z for z in range(10), t, w)\n" +" ^\n" +"SyntaxError: Generator expression must be parenthesized" +msgstr "" +">>> foo(x, z for z in range(10), t, w)\n" +" File \"\", line 1\n" +" foo(x, z for z in range(10), t, w)\n" +" ^\n" +"SyntaxError: Generator expression must be parenthesized" + #: ../../whatsnew/3.10.rst:207 msgid "now Python 3.10 will display the exception as:" msgstr "agora o Python 3.10 vai exibir a exceção como:" +#: ../../whatsnew/3.10.rst:209 +msgid "" +">>> foo(x, z for z in range(10), t, w)\n" +" File \"\", line 1\n" +" foo(x, z for z in range(10), t, w)\n" +" ^^^^^^^^^^^^^^^^^^^^\n" +"SyntaxError: Generator expression must be parenthesized" +msgstr "" +">>> foo(x, z for z in range(10), t, w)\n" +" File \"\", line 1\n" +" foo(x, z for z in range(10), t, w)\n" +" ^^^^^^^^^^^^^^^^^^^^\n" +"SyntaxError: Generator expression must be parenthesized" + #: ../../whatsnew/3.10.rst:217 msgid "This improvement was contributed by Pablo Galindo in :issue:`43914`." msgstr "Esta melhoria foi contribuída por Pablo Galindo em :issue:`43914`." @@ -281,6 +399,20 @@ msgstr "" msgid "Missing ``:`` before blocks:" msgstr "Faltando ``:`` antes de blocos:" +#: ../../whatsnew/3.10.rst:224 +msgid "" +">>> if rocket.position > event_horizon\n" +" File \"\", line 1\n" +" if rocket.position > event_horizon\n" +" ^\n" +"SyntaxError: expected ':'" +msgstr "" +">>> if foguete.posicao > horizonte_evento\n" +" File \"\", line 1\n" +" if foguete.posicao > horizonte_evento\n" +" ^\n" +"SyntaxError: expected ':'" + #: ../../whatsnew/3.10.rst:232 msgid "(Contributed by Pablo Galindo in :issue:`42997`.)" msgstr "(Contribuição de Pablo Galindo em :issue:`42997`.)" @@ -289,6 +421,20 @@ msgstr "(Contribuição de Pablo Galindo em :issue:`42997`.)" msgid "Unparenthesised tuples in comprehensions targets:" msgstr "Tuplas sem parênteses em alvos de compreensão:" +#: ../../whatsnew/3.10.rst:236 +msgid "" +">>> {x,y for x,y in zip('abcd', '1234')}\n" +" File \"\", line 1\n" +" {x,y for x,y in zip('abcd', '1234')}\n" +" ^\n" +"SyntaxError: did you forget parentheses around the comprehension target?" +msgstr "" +">>> {x,y for x,y in zip('abcd', '1234')}\n" +" File \"\", line 1\n" +" {x,y for x,y in zip('abcd', '1234')}\n" +" ^\n" +"SyntaxError: did you forget parentheses around the comprehension target?" + #: ../../whatsnew/3.10.rst:244 msgid "(Contributed by Pablo Galindo in :issue:`43017`.)" msgstr "(Contribuição de Pablo Galindo em :issue:`43017`.)" @@ -297,6 +443,26 @@ msgstr "(Contribuição de Pablo Galindo em :issue:`43017`.)" msgid "Missing commas in collection literals and between expressions:" msgstr "Faltando vírgulas em literais de coleção e entre expressões:" +#: ../../whatsnew/3.10.rst:248 +msgid "" +">>> items = {\n" +"... x: 1,\n" +"... y: 2\n" +"... z: 3,\n" +" File \"\", line 3\n" +" y: 2\n" +" ^\n" +"SyntaxError: invalid syntax. Perhaps you forgot a comma?" +msgstr "" +">>> items = {\n" +"... x: 1,\n" +"... y: 2\n" +"... z: 3,\n" +" File \"\", line 3\n" +" y: 2\n" +" ^\n" +"SyntaxError: invalid syntax. Perhaps you forgot a comma?" + #: ../../whatsnew/3.10.rst:259 msgid "(Contributed by Pablo Galindo in :issue:`43822`.)" msgstr "(Contribuição de Pablo Galindo em :issue:`43822`.)" @@ -305,6 +471,24 @@ msgstr "(Contribuição de Pablo Galindo em :issue:`43822`.)" msgid "Multiple Exception types without parentheses:" msgstr "Vários tipos de exceção sem parênteses:" +#: ../../whatsnew/3.10.rst:263 +msgid "" +">>> try:\n" +"... build_dyson_sphere()\n" +"... except NotEnoughScienceError, NotEnoughResourcesError:\n" +" File \"\", line 3\n" +" except NotEnoughScienceError, NotEnoughResourcesError:\n" +" ^\n" +"SyntaxError: multiple exception types must be parenthesized" +msgstr "" +">>> try:\n" +"... construir_esfera_de_dyson()\n" +"... except NotEnoughScienceError, NotEnoughResourcesError:\n" +" File \"\", line 3\n" +" except NotEnoughScienceError, NotEnoughResourcesError:\n" +" ^\n" +"SyntaxError: multiple exception types must be parenthesized" + #: ../../whatsnew/3.10.rst:273 msgid "(Contributed by Pablo Galindo in :issue:`43149`.)" msgstr "(Contribuição de Pablo Galindo em :issue:`43149`.)" @@ -313,6 +497,40 @@ msgstr "(Contribuição de Pablo Galindo em :issue:`43149`.)" msgid "Missing ``:`` and values in dictionary literals:" msgstr "Faltando ``:`` em valores em literais de dicionário:" +#: ../../whatsnew/3.10.rst:277 +msgid "" +">>> values = {\n" +"... x: 1,\n" +"... y: 2,\n" +"... z:\n" +"... }\n" +" File \"\", line 4\n" +" z:\n" +" ^\n" +"SyntaxError: expression expected after dictionary key and ':'\n" +"\n" +">>> values = {x:1, y:2, z w:3}\n" +" File \"\", line 1\n" +" values = {x:1, y:2, z w:3}\n" +" ^\n" +"SyntaxError: ':' expected after dictionary key" +msgstr "" +">>> values = {\n" +"... x: 1,\n" +"... y: 2,\n" +"... z:\n" +"... }\n" +" File \"\", line 4\n" +" z:\n" +" ^\n" +"SyntaxError: expression expected after dictionary key and ':'\n" +"\n" +">>> values = {x:1, y:2, z w:3}\n" +" File \"\", line 1\n" +" values = {x:1, y:2, z w:3}\n" +" ^\n" +"SyntaxError: ':' expected after dictionary key" + #: ../../whatsnew/3.10.rst:295 msgid "(Contributed by Pablo Galindo in :issue:`43823`.)" msgstr "(Contribuição de Pablo Galindo em :issue:`43823`.)" @@ -321,6 +539,24 @@ msgstr "(Contribuição de Pablo Galindo em :issue:`43823`.)" msgid "``try`` blocks without ``except`` or ``finally`` blocks:" msgstr "Blocos ``try`` sem blocos ``except`` ou ``finally``:" +#: ../../whatsnew/3.10.rst:299 +msgid "" +">>> try:\n" +"... x = 2\n" +"... something = 3\n" +" File \"\", line 3\n" +" something = 3\n" +" ^^^^^^^^^\n" +"SyntaxError: expected 'except' or 'finally' block" +msgstr "" +">>> try:\n" +"... x = 2\n" +"... algumacoisa = 3\n" +" File \"\", line 3\n" +" algumacoisa = 3\n" +" ^^^^^^^^^^^\n" +"SyntaxError: expected 'except' or 'finally' block" + #: ../../whatsnew/3.10.rst:309 msgid "(Contributed by Pablo Galindo in :issue:`44305`.)" msgstr "(Contribuição de Pablo Galindo em :issue:`44305`.)" @@ -329,6 +565,22 @@ msgstr "(Contribuição de Pablo Galindo em :issue:`44305`.)" msgid "Usage of ``=`` instead of ``==`` in comparisons:" msgstr "Uso de ``=`` em vez de ``==`` nas comparações:" +#: ../../whatsnew/3.10.rst:313 +msgid "" +">>> if rocket.position = event_horizon:\n" +" File \"\", line 1\n" +" if rocket.position = event_horizon:\n" +" ^\n" +"SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead " +"of '='?" +msgstr "" +">>> if foguete.posicao = horizonte_evento:\n" +" File \"\", line 1\n" +" if foguete.posicao = horizonte_evento:\n" +" ^\n" +"SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead " +"of '='?" + #: ../../whatsnew/3.10.rst:321 msgid "(Contributed by Pablo Galindo in :issue:`43797`.)" msgstr "(Contribuição de Pablo Galindo em :issue:`43797`.)" @@ -337,6 +589,20 @@ msgstr "(Contribuição de Pablo Galindo em :issue:`43797`.)" msgid "Usage of ``*`` in f-strings:" msgstr "Uso de ``*`` em f-strings:" +#: ../../whatsnew/3.10.rst:325 +msgid "" +">>> f\"Black holes {*all_black_holes} and revelations\"\n" +" File \"\", line 1\n" +" (*all_black_holes)\n" +" ^\n" +"SyntaxError: f-string: cannot use starred expression here" +msgstr "" +">>> f\"Buracos negros {*all_black_holes} e revelações\"\n" +" File \"\", line 1\n" +" (*all_black_holes)\n" +" ^\n" +"SyntaxError: f-string: cannot use starred expression here" + #: ../../whatsnew/3.10.rst:333 msgid "(Contributed by Pablo Galindo in :issue:`41064`.)" msgstr "(Contribuição de Pablo Galindo em :issue:`41064`.)" @@ -355,6 +621,24 @@ msgstr "" "tipo de bloco estava esperando um indentação, incluindo a localização da " "instrução:" +#: ../../whatsnew/3.10.rst:341 +msgid "" +">>> def foo():\n" +"... if lel:\n" +"... x = 2\n" +" File \"\", line 3\n" +" x = 2\n" +" ^\n" +"IndentationError: expected an indented block after 'if' statement in line 2" +msgstr "" +">>> def foo():\n" +"... if lel:\n" +"... x = 2\n" +" File \"\", line 3\n" +" x = 2\n" +" ^\n" +"IndentationError: expected an indented block after 'if' statement in line 2" + #: ../../whatsnew/3.10.rst:353 msgid "AttributeErrors" msgstr "AttributeErrors" @@ -369,6 +653,20 @@ msgstr "" "sugestões de nomes de atributos semelhantes no objeto a partir do qual a " "exceção foi levantada:" +#: ../../whatsnew/3.10.rst:359 +msgid "" +">>> collections.namedtoplo\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"AttributeError: module 'collections' has no attribute 'namedtoplo'. Did you " +"mean: namedtuple?" +msgstr "" +">>> collections.namedtoplo\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"AttributeError: module 'collections' has no attribute 'namedtoplo'. Did you " +"mean: namedtuple?" + #: ../../whatsnew/3.10.rst:366 ../../whatsnew/3.10.rst:388 msgid "(Contributed by Pablo Galindo in :issue:`38530`.)" msgstr "(Contribuição de Pablo Galindo em :issue:`38530`.)" @@ -398,6 +696,22 @@ msgstr "" "PyErr_Display` irá oferecer sugestões de nomes de variáveis semelhantes na " "função de onde a exceção foi levantada:" +#: ../../whatsnew/3.10.rst:380 +msgid "" +">>> schwarzschild_black_hole = None\n" +">>> schwarschild_black_hole\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"NameError: name 'schwarschild_black_hole' is not defined. Did you mean: " +"schwarzschild_black_hole?" +msgstr "" +">>> buraco_negro_de_schwarzschild = None\n" +">>> buraco_negro_de_schwarschild\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"NameError: name 'buraco_negro_de_schwarschild' is not defined. Did you mean: " +"buraco_negro_de_schwarzschild?" + #: ../../whatsnew/3.10.rst:391 msgid "" "Notice this won't work if :c:func:`!PyErr_Display` is not called to display " @@ -474,6 +788,28 @@ msgstr "Sintaxe e operações" msgid "The generic syntax of pattern matching is::" msgstr "A sintaxe genérica da correspondência de padrão é::" +#: ../../whatsnew/3.10.rst:426 +msgid "" +"match subject:\n" +" case :\n" +" \n" +" case :\n" +" \n" +" case :\n" +" \n" +" case _:\n" +" " +msgstr "" +"match sujeito:\n" +" case :\n" +" \n" +" case :\n" +" \n" +" case :\n" +" \n" +" case _:\n" +" " + #: ../../whatsnew/3.10.rst:436 msgid "" "A match statement takes an expression and compares its value to successive " @@ -486,11 +822,11 @@ msgstr "" #: ../../whatsnew/3.10.rst:440 msgid "using data with type and shape (the ``subject``)" -msgstr "usando dados com tipo e forma (o ``subject``)" +msgstr "usando dados com tipo e forma (o ``sujeito``)" #: ../../whatsnew/3.10.rst:441 msgid "evaluating the ``subject`` in the ``match`` statement" -msgstr "avaliando o ``subject`` na instrução ``match``" +msgstr "avaliando o ``sujeito`` na instrução ``match``" #: ../../whatsnew/3.10.rst:442 msgid "" @@ -586,6 +922,30 @@ msgstr "" "literais representam códigos de status de solicitação. A ação associada ao " "caso é executada após uma partida:" +#: ../../whatsnew/3.10.rst:481 +msgid "" +"def http_error(status):\n" +" match status:\n" +" case 400:\n" +" return \"Bad request\"\n" +" case 404:\n" +" return \"Not found\"\n" +" case 418:\n" +" return \"I'm a teapot\"\n" +" case _:\n" +" return \"Something's wrong with the internet\"" +msgstr "" +"def http_error(status):\n" +" match status:\n" +" case 400:\n" +" return \"Bad request\"\n" +" case 404:\n" +" return \"Not found\"\n" +" case 418:\n" +" return \"I'm a teapot\"\n" +" case _:\n" +" return \"Something's wrong with the internet\"" + #: ../../whatsnew/3.10.rst:492 msgid "" "If the above function is passed a ``status`` of 418, \"I'm a teapot\" is " @@ -608,6 +968,14 @@ msgid "" msgstr "" "Você pode combinar vários literais em um único padrão usando ``|`` (\"ou\")::" +#: ../../whatsnew/3.10.rst:501 +msgid "" +"case 401 | 403 | 404:\n" +" return \"Not allowed\"" +msgstr "" +"case 401 | 403 | 404:\n" +" return \"Não permitido\"" + #: ../../whatsnew/3.10.rst:505 msgid "Behavior without the wildcard" msgstr "Comportamento sem o curinga" @@ -620,6 +988,26 @@ msgstr "" "Se modificarmos o exemplo acima removendo o último bloco case, o exemplo se " "tornará::" +#: ../../whatsnew/3.10.rst:510 +msgid "" +"def http_error(status):\n" +" match status:\n" +" case 400:\n" +" return \"Bad request\"\n" +" case 404:\n" +" return \"Not found\"\n" +" case 418:\n" +" return \"I'm a teapot\"" +msgstr "" +"def http_error(status):\n" +" match status:\n" +" case 400:\n" +" return \"Bad request\"\n" +" case 404:\n" +" return \"Not found\"\n" +" case 418:\n" +" return \"I'm a teapot\"" + #: ../../whatsnew/3.10.rst:519 msgid "" "Without the use of ``_`` in a case statement, a match may not exist. If no " @@ -644,6 +1032,34 @@ msgstr "" "ser usado para vincular variáveis. Neste exemplo, um ponto de dados pode ser " "desempacotado em sua coordenada x e coordenada y::" +#: ../../whatsnew/3.10.rst:530 +msgid "" +"# point is an (x, y) tuple\n" +"match point:\n" +" case (0, 0):\n" +" print(\"Origin\")\n" +" case (0, y):\n" +" print(f\"Y={y}\")\n" +" case (x, 0):\n" +" print(f\"X={x}\")\n" +" case (x, y):\n" +" print(f\"X={x}, Y={y}\")\n" +" case _:\n" +" raise ValueError(\"Not a point\")" +msgstr "" +"# ponto é uma tupla (x, y)\n" +"match ponto:\n" +" case (0, 0):\n" +" print(\"Origem\")\n" +" case (0, y):\n" +" print(f\"Y={y}\")\n" +" case (x, 0):\n" +" print(f\"X={x}\")\n" +" case (x, y):\n" +" print(f\"X={x}, Y={y}\")\n" +" case _:\n" +" raise ValueError(\"Não é um ponto\")" + #: ../../whatsnew/3.10.rst:543 msgid "" "The first pattern has two literals, ``(0, 0)``, and may be thought of as an " @@ -655,9 +1071,9 @@ msgstr "" "O primeiro padrão tem dois literais, ``(0, 0)``, e pode ser considerado uma " "extensão do padrão literal mostrado acima. Os próximos dois padrões combinam " "um literal e uma variável, e a variável *vincula* um valor do assunto " -"(``point``). O quarto padrão captura dois valores, o que o torna " +"(``ponto``). O quarto padrão captura dois valores, o que o torna " "conceitualmente semelhante à atribuição de desempacotamento ``(x, y) = " -"point``." +"ponto``." #: ../../whatsnew/3.10.rst:550 msgid "Patterns and classes" @@ -667,18 +1083,56 @@ msgstr "Padrões e classes" msgid "" "If you are using classes to structure your data, you can use as a pattern " "the class name followed by an argument list resembling a constructor. This " -"pattern has the ability to capture class attributes into variables::" +"pattern has the ability to capture instance attributes into variables::" msgstr "" "Se estiver usando classes para estruturar seus dados, você pode usar como " "padrão o nome da classe seguido por uma lista de argumentos semelhante a um " -"construtor. Este padrão tem a capacidade de capturar atributos de classe em " -"variáveis::" - -#: ../../whatsnew/3.10.rst:574 +"construtor. Este padrão tem a capacidade de capturar atributos da instância " +"em variáveis::" + +#: ../../whatsnew/3.10.rst:556 +msgid "" +"class Point:\n" +" def __init__(self, x, y):\n" +" self.x = x\n" +" self.y = y\n" +"\n" +"def location(point):\n" +" match point:\n" +" case Point(x=0, y=0):\n" +" print(\"Origin is the point's location.\")\n" +" case Point(x=0, y=y):\n" +" print(f\"Y={y} and the point is on the y-axis.\")\n" +" case Point(x=x, y=0):\n" +" print(f\"X={x} and the point is on the x-axis.\")\n" +" case Point():\n" +" print(\"The point is located somewhere else on the plane.\")\n" +" case _:\n" +" print(\"Not a point\")" +msgstr "" +"class Point:\n" +" def __init__(self, x, y):\n" +" self.x = x\n" +" self.y = y\n" +"\n" +"def location(point):\n" +" match point:\n" +" case Point(x=0, y=0):\n" +" print(\"O ponto está na origem.\")\n" +" case Point(x=0, y=y):\n" +" print(f \"Y={y} e o ponto está no eixo y.\")\n" +" case Point(x=x, y=0):\n" +" print(f \"X={x} e o ponto está no eixo x.\")\n" +" case Point():\n" +" print(\"O ponto está localizado em outro lugar no plano.\")\n" +" case _:\n" +" print(\"Não é um ponto\")" + +#: ../../whatsnew/3.10.rst:575 msgid "Patterns with positional parameters" msgstr "Padrões com parâmetros posicionais" -#: ../../whatsnew/3.10.rst:576 +#: ../../whatsnew/3.10.rst:577 msgid "" "You can use positional parameters with some builtin classes that provide an " "ordering for their attributes (e.g. dataclasses). You can also define a " @@ -694,11 +1148,23 @@ msgstr "" "definido como (\"x\", \"y\"), os seguintes padrões são todos equivalentes (e " "todos ligam o atributo ``y`` à variável ``var``)::" -#: ../../whatsnew/3.10.rst:588 +#: ../../whatsnew/3.10.rst:583 +msgid "" +"Point(1, var)\n" +"Point(1, y=var)\n" +"Point(x=1, y=var)\n" +"Point(y=var, x=1)" +msgstr "" +"Ponto(1, var)\n" +"Ponto(1, y=var)\n" +"Ponto(x=1, y=var)\n" +"Ponto(y=var, x=1)" + +#: ../../whatsnew/3.10.rst:589 msgid "Nested patterns" msgstr "Padrões aninhados" -#: ../../whatsnew/3.10.rst:590 +#: ../../whatsnew/3.10.rst:591 msgid "" "Patterns can be arbitrarily nested. For example, if our data is a short " "list of points, it could be matched like this::" @@ -706,11 +1172,37 @@ msgstr "" "Os padrões podem ser aninhados arbitrariamente. Por exemplo, se nossos dados " "forem uma pequena lista de pontos, eles podem ser correspondidos assim::" -#: ../../whatsnew/3.10.rst:606 +#: ../../whatsnew/3.10.rst:594 +msgid "" +"match points:\n" +" case []:\n" +" print(\"No points in the list.\")\n" +" case [Point(0, 0)]:\n" +" print(\"The origin is the only point in the list.\")\n" +" case [Point(x, y)]:\n" +" print(f\"A single point {x}, {y} is in the list.\")\n" +" case [Point(0, y1), Point(0, y2)]:\n" +" print(f\"Two points on the Y axis at {y1}, {y2} are in the list.\")\n" +" case _:\n" +" print(\"Something else is found in the list.\")" +msgstr "" +"match points:\n" +" case []:\n" +" print(\"Nenhum ponto na lista.\")\n" +" case [Point(0, 0)]:\n" +" print(\"A origem é o único ponto na lista.\")\n" +" case [Point(x, y)]:\n" +" print(f\"Um único ponto {x}, {y} está na lista.\")\n" +" case [Point(0, y1), Point(0, y2)]:\n" +" print(f\"Dois pontos no eixo Y em {y1}, {y2} estão na lista.\")\n" +" case _:\n" +" print(\"Algo diferente foi encontrado na lista.\")" + +#: ../../whatsnew/3.10.rst:607 msgid "Complex patterns and the wildcard" msgstr "Padrões complexos e o curinga" -#: ../../whatsnew/3.10.rst:608 +#: ../../whatsnew/3.10.rst:609 msgid "" "To this point, the examples have used ``_`` alone in the last case " "statement. A wildcard can be used in more complex patterns, such as " @@ -720,7 +1212,21 @@ msgstr "" "Um curinga pode ser usado em padrões mais complexos, como ``('error', code, " "_)``. Por exemplo::" -#: ../../whatsnew/3.10.rst:618 +#: ../../whatsnew/3.10.rst:613 +msgid "" +"match test_variable:\n" +" case ('warning', code, 40):\n" +" print(\"A warning has been received.\")\n" +" case ('error', code, _):\n" +" print(f\"An error {code} occurred.\")" +msgstr "" +"match test_variable:\n" +" case ('warning', code, 40):\n" +" print(\"Foi recebido um alerta.\")\n" +" case ('error', code, _):\n" +" print(f\"Ocorreu um erro {code}.\")" + +#: ../../whatsnew/3.10.rst:619 msgid "" "In the above case, ``test_variable`` will match for ('error', code, 100) and " "('error', code, 800)." @@ -728,30 +1234,43 @@ msgstr "" "No caso acima, ``test_variable`` irá corresponder a ('erro', código, 100) e " "('erro', código, 800)." -#: ../../whatsnew/3.10.rst:622 +#: ../../whatsnew/3.10.rst:623 msgid "Guard" msgstr "Guarda" -#: ../../whatsnew/3.10.rst:624 +#: ../../whatsnew/3.10.rst:625 msgid "" "We can add an ``if`` clause to a pattern, known as a \"guard\". If the " "guard is false, ``match`` goes on to try the next case block. Note that " "value capture happens before the guard is evaluated::" msgstr "" "Podemos adicionar uma cláusula ``if`` a um padrão, conhecido como " -"\"guarda\". Se a guarda for falsa, ``match`` continua para tentar o próximo " -"bloco de caso. Observe que a captura de valor ocorre antes que a guarda seja " -"avaliada::" +"\"guarda\". Se a guarda for falsa, ``match`` tenta o próximo bloco de caso. " +"Observe que a captura de valor ocorre antes que a guarda seja avaliada::" + +#: ../../whatsnew/3.10.rst:629 +msgid "" +"match point:\n" +" case Point(x, y) if x == y:\n" +" print(f\"The point is located on the diagonal Y=X at {x}.\")\n" +" case Point(x, y):\n" +" print(f\"Point is not on the diagonal.\")" +msgstr "" +"match point:\n" +" case Point(x, y) if x == y:\n" +" print(f\"O ponto está localizado em uma diagonal Y=X at {x}.\")\n" +" case Point(x, y):\n" +" print(f\"Ponto não está na diagonal.\")" -#: ../../whatsnew/3.10.rst:635 +#: ../../whatsnew/3.10.rst:636 msgid "Other Key Features" msgstr "Outros recursos-chave" -#: ../../whatsnew/3.10.rst:637 +#: ../../whatsnew/3.10.rst:638 msgid "Several other key features:" msgstr "Vários outros recursos-chave:" -#: ../../whatsnew/3.10.rst:639 +#: ../../whatsnew/3.10.rst:640 msgid "" "Like unpacking assignments, tuple and list patterns have exactly the same " "meaning and actually match arbitrary sequences. Technically, the subject " @@ -761,11 +1280,11 @@ msgid "" msgstr "" "Assim como desempacotar atribuições, os padrões de tupla e lista têm " "exatamente o mesmo significado e realmente correspondem a sequências " -"arbitrárias. Tecnicamente, o subject deve ser uma sequência. Portanto, uma " +"arbitrárias. Tecnicamente, o sujeito deve ser uma sequência. Portanto, uma " "exceção importante é que padrões não correspondem a iteradores. Também evita " "um erro comum, sequência de padrões não correspondem a strings." -#: ../../whatsnew/3.10.rst:645 +#: ../../whatsnew/3.10.rst:646 msgid "" "Sequence patterns support wildcards: ``[x, y, *rest]`` and ``(x, y, *rest)`` " "work similar to wildcards in unpacking assignments. The name after ``*`` " @@ -778,7 +1297,7 @@ msgstr "" "*_)`` corresponde a uma sequência de pelo menos dois itens sem ligar os " "itens restantes." -#: ../../whatsnew/3.10.rst:650 +#: ../../whatsnew/3.10.rst:651 msgid "" "Mapping patterns: ``{\"bandwidth\": b, \"latency\": l}`` captures the " "``\"bandwidth\"`` and ``\"latency\"`` values from a dict. Unlike sequence " @@ -786,23 +1305,27 @@ msgid "" "(But ``**_`` would be redundant, so is not allowed.)" msgstr "" "Padrões de mapeamento: ``{\"bandwidth\": b, \"latency\": l}`` captura os " -"valores ``\"bandwidth\"`` e ``\"latency\"`` de um dict. Diferente dos " +"valores ``\"bandwidth\"`` e ``\"latency\"`` de um dicionário. Diferente dos " "padrões de sequência, chaves extra são ignoradas. Um curinga ``**rest`` " "também é permitido. (Mas ``**_`` seria redundante, então não é permitido.)" -#: ../../whatsnew/3.10.rst:655 +#: ../../whatsnew/3.10.rst:656 msgid "Subpatterns may be captured using the ``as`` keyword::" msgstr "Subpadrões podem ser capturados usando a palavra reservada ``as`` ::" -#: ../../whatsnew/3.10.rst:659 +#: ../../whatsnew/3.10.rst:658 +msgid "case (Point(x1, y1), Point(x2, y2) as p2): ..." +msgstr "case (Ponto(x1, y1), Ponto(x2, y2) as p2): ..." + +#: ../../whatsnew/3.10.rst:660 msgid "" "This binds x1, y1, x2, y2 like you would expect without the ``as`` clause, " "and p2 to the entire second item of the subject." msgstr "" "Isso liga x1, y1, x2, y2 como você esperaria sem a cláusula ``as`` e p2 a " -"todo o segundo item do subject." +"todo o segundo item do sujeito." -#: ../../whatsnew/3.10.rst:662 +#: ../../whatsnew/3.10.rst:663 msgid "" "Most literals are compared by equality. However, the singletons ``True``, " "``False`` and ``None`` are compared by identity." @@ -810,7 +1333,7 @@ msgstr "" "A maioria dos literais são comparados por igualdade. No entanto, os " "singletons ``True``, ``False`` e ``None`` são comparados por identidade." -#: ../../whatsnew/3.10.rst:665 +#: ../../whatsnew/3.10.rst:666 msgid "" "Named constants may be used in patterns. These named constants must be " "dotted names to prevent the constant from being interpreted as a capture " @@ -820,7 +1343,39 @@ msgstr "" "devem ser nomes pontilhados para evitar que a constante seja interpretada " "como uma variável de captura::" -#: ../../whatsnew/3.10.rst:684 +#: ../../whatsnew/3.10.rst:670 +msgid "" +"from enum import Enum\n" +"class Color(Enum):\n" +" RED = 0\n" +" GREEN = 1\n" +" BLUE = 2\n" +"\n" +"color = Color.GREEN\n" +"match color:\n" +" case Color.RED:\n" +" print(\"I see red!\")\n" +" case Color.GREEN:\n" +" print(\"Grass is green\")\n" +" case Color.BLUE:\n" +" print(\"I'm feeling the blues :(\")" +msgstr "" +"from enum import Enum\n" +"class Color(Enum):\n" +" RED = 0\n" +" GREEN = 1\n" +" BLUE = 2\n" +"\n" +"color = Color.GREEN\n" +"match color:\n" +" case Color.RED:\n" +" print(\"Eu vejo vermelho!\")\n" +" case Color.GREEN:\n" +" print(\"A grama é verde\")\n" +" case Color.BLUE:\n" +" print(\"Eu azul de fome :(\")" + +#: ../../whatsnew/3.10.rst:685 msgid "" "For the full specification see :pep:`634`. Motivation and rationale are in :" "pep:`635`, and a longer tutorial is in :pep:`636`." @@ -829,11 +1384,11 @@ msgstr "" "o raciocínio estão na :pep:`635`, e um tutorial mais longo está na :pep:" "`636`." -#: ../../whatsnew/3.10.rst:691 +#: ../../whatsnew/3.10.rst:692 msgid "Optional ``EncodingWarning`` and ``encoding=\"locale\"`` option" msgstr "``EncodingWarning`` opcional e opção ``encoding=\"locale\"``" -#: ../../whatsnew/3.10.rst:693 +#: ../../whatsnew/3.10.rst:694 msgid "" "The default encoding of :class:`~io.TextIOWrapper` and :func:`open` is " "platform and locale dependent. Since UTF-8 is used on most Unix platforms, " @@ -845,7 +1400,17 @@ msgstr "" "Unix, omitir a opção ``encoding`` ao abrir arquivos UTF-8 (por exemplo, " "JSON, YAML, TOML, Markdown) é um bug muito comum. Por exemplo::" -#: ../../whatsnew/3.10.rst:702 +#: ../../whatsnew/3.10.rst:699 +msgid "" +"# BUG: \"rb\" mode or encoding=\"utf-8\" should be used.\n" +"with open(\"data.json\") as f:\n" +" data = json.load(f)" +msgstr "" +"# BUG: mode \"rb\" ou encoding=\"utf-8\" deve ser usado.\n" +"with open(\"data.json\") as f:\n" +" data = json.load(f)" + +#: ../../whatsnew/3.10.rst:703 msgid "" "To find this type of bug, an optional ``EncodingWarning`` is added. It is " "emitted when :data:`sys.flags.warn_default_encoding ` is true and " @@ -855,7 +1420,7 @@ msgstr "" "adicionada. É emitido quando :data:`sys.flags.warn_default_encoding ` é verdadeiro e a codificação padrão específica da localidade é usada." -#: ../../whatsnew/3.10.rst:706 +#: ../../whatsnew/3.10.rst:707 msgid "" "``-X warn_default_encoding`` option and :envvar:`PYTHONWARNDEFAULTENCODING` " "are added to enable the warning." @@ -863,15 +1428,15 @@ msgstr "" "A opção ``-X warn_default_encoding`` e :envvar:`PYTHONWARNDEFAULTENCODING` " "são adicionadas para ativar o aviso." -#: ../../whatsnew/3.10.rst:709 +#: ../../whatsnew/3.10.rst:710 msgid "See :ref:`io-text-encoding` for more information." msgstr "Veja :ref:`io-text-encoding` para mais informações." -#: ../../whatsnew/3.10.rst:714 +#: ../../whatsnew/3.10.rst:715 msgid "New Features Related to Type Hints" msgstr "Novos recursos relacionados a dicas de tipo" -#: ../../whatsnew/3.10.rst:716 +#: ../../whatsnew/3.10.rst:717 msgid "" "This section covers major changes affecting :pep:`484` type hints and the :" "mod:`typing` module." @@ -879,11 +1444,11 @@ msgstr "" "Esta seção cobre as principais mudanças que afetam as dicas de tipo da :pep:" "`484` e o módulo :mod:`typing`." -#: ../../whatsnew/3.10.rst:721 +#: ../../whatsnew/3.10.rst:722 msgid "PEP 604: New Type Union Operator" -msgstr "PEP 604: Operador de união de novo tipo" +msgstr "PEP 604: novo operador de união de tipo" -#: ../../whatsnew/3.10.rst:723 +#: ../../whatsnew/3.10.rst:724 msgid "" "A new type union operator was introduced which enables the syntax ``X | Y``. " "This provides a cleaner way of expressing 'either type X or type Y' instead " @@ -894,7 +1459,7 @@ msgstr "" "quanto o tipo Y\" ao invés de usar :data:`typing.Union`, especialmente em " "dicas de tipo." -#: ../../whatsnew/3.10.rst:727 +#: ../../whatsnew/3.10.rst:728 msgid "" "In previous versions of Python, to apply a type hint for functions accepting " "arguments of multiple types, :data:`typing.Union` was used::" @@ -902,12 +1467,28 @@ msgstr "" "Nas versões anteriores do Python, para aplicar uma dica de tipo para funções " "que aceitam argumentos de vários tipos, era usado :data:`typing.Union`::" -#: ../../whatsnew/3.10.rst:734 +#: ../../whatsnew/3.10.rst:731 +msgid "" +"def square(number: Union[int, float]) -> Union[int, float]:\n" +" return number ** 2" +msgstr "" +"def square(number: Union[int, float]) -> Union[int, float]:\n" +" return number ** 2" + +#: ../../whatsnew/3.10.rst:735 msgid "Type hints can now be written in a more succinct manner::" msgstr "" "As dicas de tipo agora podem ser escritas de uma maneira mais sucinta::" -#: ../../whatsnew/3.10.rst:740 +#: ../../whatsnew/3.10.rst:737 +msgid "" +"def square(number: int | float) -> int | float:\n" +" return number ** 2" +msgstr "" +"def square(number: int | float) -> int | float:\n" +" return number ** 2" + +#: ../../whatsnew/3.10.rst:741 msgid "" "This new syntax is also accepted as the second argument to :func:" "`isinstance` and :func:`issubclass`::" @@ -915,11 +1496,19 @@ msgstr "" "Esta nova sintaxe também é aceita como o segundo argumento para :func:" "`isinstance` e :func:`issubclass`::" -#: ../../whatsnew/3.10.rst:746 +#: ../../whatsnew/3.10.rst:744 +msgid "" +">>> isinstance(1, int | str)\n" +"True" +msgstr "" +">>> isinstance(1, int | str)\n" +"True" + +#: ../../whatsnew/3.10.rst:747 msgid "See :ref:`types-union` and :pep:`604` for more details." msgstr "Veja :ref:`types-union` e :pep:`604` para mais detalhes." -#: ../../whatsnew/3.10.rst:748 +#: ../../whatsnew/3.10.rst:749 msgid "" "(Contributed by Maggie Moss and Philippe Prados in :issue:`41428`, with " "additions by Yurii Karabas and Serhiy Storchaka in :issue:`44490`.)" @@ -927,11 +1516,11 @@ msgstr "" "(Contribuição de Maggie Moss e Philippe Prados em :issue:`41428`, com " "acréscimos por Yurii Karabas e Serhiy Storchaka em :issue:`44490`.)" -#: ../../whatsnew/3.10.rst:753 +#: ../../whatsnew/3.10.rst:754 msgid "PEP 612: Parameter Specification Variables" -msgstr "PEP 612: Variáveis de especificação de parâmetros" +msgstr "PEP 612: variáveis de especificação de parâmetros" -#: ../../whatsnew/3.10.rst:755 +#: ../../whatsnew/3.10.rst:756 msgid "" "Two new options to improve the information provided to static type checkers " "for :pep:`484`\\ 's ``Callable`` have been added to the :mod:`typing` module." @@ -940,7 +1529,7 @@ msgstr "" "de tipo estático para ``Callable`` da :pep:`484` foram adicionadas ao " "módulo :mod:`typing`." -#: ../../whatsnew/3.10.rst:758 +#: ../../whatsnew/3.10.rst:759 msgid "" "The first is the parameter specification variable. They are used to forward " "the parameter types of one callable to another callable -- a pattern " @@ -950,12 +1539,12 @@ msgid "" msgstr "" "A primeira é a variável de especificação de parâmetro. Eles são usados para " "encaminhar os tipos de parâmetro de um chamável para outro chamável -- um " -"padrão comumente encontrado em funções e decoradores de ordem superior. " +"padrão comumente encontrado em funções de ordem superior e decoradores. " "Exemplos de uso podem ser encontrados em :class:`typing.ParamSpec`. " "Anteriormente, não havia uma maneira fácil de digitar a dependência de " "anotação de tipos de parâmetro de maneira tão precisa." -#: ../../whatsnew/3.10.rst:764 +#: ../../whatsnew/3.10.rst:765 msgid "" "The second option is the new ``Concatenate`` operator. It's used in " "conjunction with parameter specification variables to type annotate a higher " @@ -967,7 +1556,7 @@ msgstr "" "ordem superior que adiciona ou remove parâmetros de outro chamável. Exemplos " "de uso podem ser encontrados em :class:`typing.Concatenate`." -#: ../../whatsnew/3.10.rst:769 +#: ../../whatsnew/3.10.rst:770 msgid "" "See :class:`typing.Callable`, :class:`typing.ParamSpec`, :class:`typing." "Concatenate`, :class:`typing.ParamSpecArgs`, :class:`typing." @@ -977,7 +1566,7 @@ msgstr "" "Concatenate`, :class:`typing.ParamSpecArgs`, :class:`typing.ParamSpecKwargs` " "e :pep:`612` para mais detalhes." -#: ../../whatsnew/3.10.rst:773 +#: ../../whatsnew/3.10.rst:774 msgid "" "(Contributed by Ken Jin in :issue:`41559`, with minor enhancements by Jelle " "Zijlstra in :issue:`43783`. PEP written by Mark Mendoza.)" @@ -985,11 +1574,11 @@ msgstr "" "(Contribuição de Ken Jin em :issue:`41559`, com pequenas melhorias por Jelle " "Zijlstra em :issue:`43783`. PEP escrita por Mark Mendoza.)" -#: ../../whatsnew/3.10.rst:778 +#: ../../whatsnew/3.10.rst:779 msgid "PEP 613: TypeAlias" msgstr "PEP 613: TypeAlias" -#: ../../whatsnew/3.10.rst:780 +#: ../../whatsnew/3.10.rst:781 msgid "" ":pep:`484` introduced the concept of type aliases, only requiring them to be " "top-level unannotated assignments. This simplicity sometimes made it " @@ -999,11 +1588,19 @@ msgid "" msgstr "" ":pep:`484` introduziu o conceito de apelidos de tipo, exigindo apenas que " "fossem atribuições não anotadas de nível superior. Essa simplicidade às " -"vezes tornava difícil para os verificadores de tipo distinguir entre " +"vezes tornava difícil para os verificadores de tipo distinguirem entre " "apelidos de tipo e atribuições comuns, especialmente quando referências " "diretas ou tipos inválidos estavam envolvidos. Compare::" -#: ../../whatsnew/3.10.rst:788 +#: ../../whatsnew/3.10.rst:786 +msgid "" +"StrCache = 'Cache[str]' # a type alias\n" +"LOG_PREFIX = 'LOG[DEBUG]' # a module constant" +msgstr "" +"StrCache = 'Cache[str]' # um apelido de tipo\n" +"LOG_PREFIX = 'LOG[DEBUG]' # uma constante do módulo" + +#: ../../whatsnew/3.10.rst:789 msgid "" "Now the :mod:`typing` module has a special value :data:`~typing.TypeAlias` " "which lets you declare type aliases more explicitly::" @@ -1011,19 +1608,27 @@ msgstr "" "Agora o módulo :mod:`typing` tem um valor especial :data:`~typing.TypeAlias` " "que permite declarar apelidos de tipo, mais explicitamente::" -#: ../../whatsnew/3.10.rst:794 +#: ../../whatsnew/3.10.rst:792 +msgid "" +"StrCache: TypeAlias = 'Cache[str]' # a type alias\n" +"LOG_PREFIX = 'LOG[DEBUG]' # a module constant" +msgstr "" +"StrCache: TypeAlias = 'Cache[str]' # um apelido de tipo\n" +"LOG_PREFIX = 'LOG[DEBUG]' # uma constante do módulo" + +#: ../../whatsnew/3.10.rst:795 msgid "See :pep:`613` for more details." msgstr "Veja :pep:`613` para mais detalhes." -#: ../../whatsnew/3.10.rst:796 +#: ../../whatsnew/3.10.rst:797 msgid "(Contributed by Mikhail Golubev in :issue:`41923`.)" msgstr "(Contribuição de Mikhail Golubev em :issue:`41923`.)" -#: ../../whatsnew/3.10.rst:799 +#: ../../whatsnew/3.10.rst:800 msgid "PEP 647: User-Defined Type Guards" -msgstr "PEP 647: Guardas de Tipo Definidas Pelo Usuário" +msgstr "PEP 647: guardas de tipo definidas pelo usuário" -#: ../../whatsnew/3.10.rst:801 +#: ../../whatsnew/3.10.rst:802 msgid "" ":data:`~typing.TypeGuard` has been added to the :mod:`typing` module to " "annotate type guard functions and improve information provided to static " @@ -1035,7 +1640,7 @@ msgstr "" "de tipo estático durante um estreitamento de tipo. Para mais informações, " "veja a documentação do :data:`~typing.TypeGuard` e a :pep:`647`." -#: ../../whatsnew/3.10.rst:806 +#: ../../whatsnew/3.10.rst:807 msgid "" "(Contributed by Ken Jin and Guido van Rossum in :issue:`43766`. PEP written " "by Eric Traut.)" @@ -1043,11 +1648,11 @@ msgstr "" "(Contribuição de Ken Jin e Guido van Rossum em :issue:`43766`. PEP escrita " "por Eric Traut.)" -#: ../../whatsnew/3.10.rst:810 +#: ../../whatsnew/3.10.rst:811 msgid "Other Language Changes" msgstr "Outras mudanças na linguagem" -#: ../../whatsnew/3.10.rst:812 +#: ../../whatsnew/3.10.rst:813 msgid "" "The :class:`int` type has a new method :meth:`int.bit_count`, returning the " "number of ones in the binary expansion of a given integer, also known as the " @@ -1058,7 +1663,7 @@ msgstr "" "como contagem da população. (Contribuição de Niklas Fiekas em :issue:" "`29882`.)" -#: ../../whatsnew/3.10.rst:816 +#: ../../whatsnew/3.10.rst:817 msgid "" "The views returned by :meth:`dict.keys`, :meth:`dict.values` and :meth:`dict." "items` now all have a ``mapping`` attribute that gives a :class:`types." @@ -1070,7 +1675,7 @@ msgstr "" "class:`types.MappingProxyType` que envolve o dicionário original. " "(Contribuição de Dennis Sweeney em :issue:`40890`.)" -#: ../../whatsnew/3.10.rst:821 +#: ../../whatsnew/3.10.rst:822 msgid "" ":pep:`618`: The :func:`zip` function now has an optional ``strict`` flag, " "used to require that all the iterables have an equal length." @@ -1079,7 +1684,7 @@ msgstr "" "``strict``, usado para exigir que todos os iteráveis tenham um comprimento " "igual." -#: ../../whatsnew/3.10.rst:824 +#: ../../whatsnew/3.10.rst:825 msgid "" "Builtin and extension functions that take integer arguments no longer " "accept :class:`~decimal.Decimal`\\ s, :class:`~fractions.Fraction`\\ s and " @@ -1093,7 +1698,7 @@ msgstr "" "exemplo, tem o método :meth:`~object.__int__`, mas não tem o método :meth:" "`~object.__index__`). (Contribuição de Serhiy Storchaka em :issue:`37999`.)" -#: ../../whatsnew/3.10.rst:831 +#: ../../whatsnew/3.10.rst:832 msgid "" "If :func:`object.__ipow__` returns :data:`NotImplemented`, the operator will " "correctly fall back to :func:`object.__pow__` and :func:`object.__rpow__` as " @@ -1103,7 +1708,7 @@ msgstr "" "corretamente recorrer ao :func:`object.__pow__` e :func:`object.__rpow__` " "como esperado. (Contribuição de Alex Shkop em :issue:`38302`.)" -#: ../../whatsnew/3.10.rst:835 +#: ../../whatsnew/3.10.rst:836 msgid "" "Assignment expressions can now be used unparenthesized within set literals " "and set comprehensions, as well as in sequence indexes (but not slices)." @@ -1112,7 +1717,7 @@ msgstr "" "literais de conjuntos e compreensões de conjuntos, bem como em índices de " "sequência (mas não em fatias)." -#: ../../whatsnew/3.10.rst:838 +#: ../../whatsnew/3.10.rst:839 msgid "" "Functions have a new ``__builtins__`` attribute which is used to look for " "builtin symbols when a function is executed, instead of looking into " @@ -1126,7 +1731,7 @@ msgstr "" "``__globals__[\"__builtins__\"]`` se existir; do contrário, a partir dos " "embutidos atuais. (Contribuição de Mark Shannon em :issue:`42990`.)" -#: ../../whatsnew/3.10.rst:844 +#: ../../whatsnew/3.10.rst:845 msgid "" "Two new builtin functions -- :func:`aiter` and :func:`anext` have been added " "to provide asynchronous counterparts to :func:`iter` and :func:`next`, " @@ -1138,7 +1743,7 @@ msgstr "" "`next`, respectivamente. (Contribuição de Joshua Bronson, Daniel Pope e " "Justin Wang em :issue:`31861`.)" -#: ../../whatsnew/3.10.rst:849 +#: ../../whatsnew/3.10.rst:850 msgid "" "Static methods (:func:`@staticmethod `) and class methods (:" "func:`@classmethod `) now inherit the method attributes " @@ -1154,7 +1759,7 @@ msgstr "" "métodos estáticos são agora chamáveis como funções comuns. (Contribuição de " "Victor Stinner em :issue:`43682`.)" -#: ../../whatsnew/3.10.rst:856 +#: ../../whatsnew/3.10.rst:857 msgid "" "Annotations for complex targets (everything beside ``simple name`` targets " "defined by :pep:`526`) no longer cause any runtime effects with ``from " @@ -1166,7 +1771,7 @@ msgstr "" "tempo de execução com ``from __future__ import annotations``. (Contribuição " "de Batuhan Taskaya em :issue:`42737`.)" -#: ../../whatsnew/3.10.rst:860 +#: ../../whatsnew/3.10.rst:861 msgid "" "Class and module objects now lazy-create empty annotations dicts on demand. " "The annotations dicts are stored in the object’s ``__dict__`` for backwards " @@ -1181,7 +1786,7 @@ msgstr "" "mais informações, veja :ref:`annotations-howto`. (Contribuição de Larry " "Hastings em :issue:`43901`.)" -#: ../../whatsnew/3.10.rst:867 +#: ../../whatsnew/3.10.rst:868 msgid "" "Annotations consist of ``yield``, ``yield from``, ``await`` or named " "expressions are now forbidden under ``from __future__ import annotations`` " @@ -1193,7 +1798,7 @@ msgstr "" "causa de seus efeitos colaterais. (Contribuição de Batuhan Taskaya em :issue:" "`42725`.)" -#: ../../whatsnew/3.10.rst:872 +#: ../../whatsnew/3.10.rst:873 msgid "" "Usage of unbound variables, ``super()`` and other expressions that might " "alter the processing of symbol table as annotations are now rendered " @@ -1205,7 +1810,7 @@ msgstr "" "processadas sem efeito sob ``from __future__ import annotations``. " "(Contribuição de Batuhan Taskaya em :issue:`42725`.)" -#: ../../whatsnew/3.10.rst:877 +#: ../../whatsnew/3.10.rst:878 msgid "" "Hashes of NaN values of both :class:`float` type and :class:`decimal." "Decimal` type now depend on object identity. Formerly, they always hashed to " @@ -1221,7 +1826,7 @@ msgstr "" "devido a colisões de hash excessivas ao criar dicionários e conjuntos " "contendo vários NaNs. (Contribuição de Raymond Hettinger em :issue:`43475`.)" -#: ../../whatsnew/3.10.rst:884 +#: ../../whatsnew/3.10.rst:885 msgid "" "A :exc:`SyntaxError` (instead of a :exc:`NameError`) will be raised when " "deleting the :const:`__debug__` constant. (Contributed by Donghee Na in :" @@ -1231,7 +1836,7 @@ msgstr "" "excluir a constante :const:`__debug__`. (Contribuição de Donghee Na em :" "issue:`45000`.)" -#: ../../whatsnew/3.10.rst:887 +#: ../../whatsnew/3.10.rst:888 msgid "" ":exc:`SyntaxError` exceptions now have ``end_lineno`` and ``end_offset`` " "attributes. They will be ``None`` if not determined. (Contributed by Pablo " @@ -1241,23 +1846,23 @@ msgstr "" "``end_offset``. Eles serão ``None`` se não forem determinados. (Contribuição " "de Pablo Galindo em :issue:`43914`.)" -#: ../../whatsnew/3.10.rst:892 +#: ../../whatsnew/3.10.rst:893 msgid "New Modules" msgstr "Novos módulos" -#: ../../whatsnew/3.10.rst:894 +#: ../../whatsnew/3.10.rst:895 msgid "None." msgstr "Nenhum." -#: ../../whatsnew/3.10.rst:898 +#: ../../whatsnew/3.10.rst:899 msgid "Improved Modules" msgstr "Módulos melhorados" -#: ../../whatsnew/3.10.rst:901 +#: ../../whatsnew/3.10.rst:902 msgid "asyncio" msgstr "asyncio" -#: ../../whatsnew/3.10.rst:903 +#: ../../whatsnew/3.10.rst:904 msgid "" "Add missing :meth:`~asyncio.events.AbstractEventLoop." "connect_accepted_socket` method. (Contributed by Alex Grönholm in :issue:" @@ -1267,11 +1872,11 @@ msgstr "" "connect_accepted_socket` até então em falta. (Contribuição de Alex Grönholm " "em :issue:`41332`.)" -#: ../../whatsnew/3.10.rst:908 +#: ../../whatsnew/3.10.rst:909 msgid "argparse" msgstr "argparse" -#: ../../whatsnew/3.10.rst:910 +#: ../../whatsnew/3.10.rst:911 msgid "" "Misleading phrase \"optional arguments\" was replaced with \"options\" in " "argparse help. Some tests might require adaptation if they rely on exact " @@ -1282,11 +1887,11 @@ msgstr "" "da correspondência de saída exata. (Contribuição de Raymond Hettinger em :" "issue:`9694`.)" -#: ../../whatsnew/3.10.rst:914 +#: ../../whatsnew/3.10.rst:915 msgid "array" msgstr "array" -#: ../../whatsnew/3.10.rst:916 +#: ../../whatsnew/3.10.rst:917 msgid "" "The :meth:`~array.array.index` method of :class:`array.array` now has " "optional *start* and *stop* parameters. (Contributed by Anders Lorentsen and " @@ -1296,11 +1901,11 @@ msgstr "" "parâmetros *start* e *stop*. (Contribuição de Anders Lorentsen e Zackery " "Spytz em :issue:`31956`.)" -#: ../../whatsnew/3.10.rst:921 +#: ../../whatsnew/3.10.rst:922 msgid "asynchat, asyncore, smtpd" msgstr "asynchat, asyncore, smtpd" -#: ../../whatsnew/3.10.rst:922 +#: ../../whatsnew/3.10.rst:923 msgid "" "These modules have been marked as deprecated in their module documentation " "since Python 3.6. An import-time :class:`DeprecationWarning` has now been " @@ -1310,11 +1915,11 @@ msgstr "" "módulo desde o Python 3.6. Uma exceção :class:`DeprecationWarning` em tempo " "de importação agora foi adicionada a todos esses três módulos." -#: ../../whatsnew/3.10.rst:927 +#: ../../whatsnew/3.10.rst:928 msgid "base64" msgstr "base64" -#: ../../whatsnew/3.10.rst:929 +#: ../../whatsnew/3.10.rst:930 msgid "" "Add :func:`base64.b32hexencode` and :func:`base64.b32hexdecode` to support " "the Base32 Encoding with Extended Hex Alphabet." @@ -1322,11 +1927,11 @@ msgstr "" "Adiciona :func:`base64.b32hexencode` e :func:`base64.b32hexdecode` para dar " "suporte a Codificação Base32 com alfabeto hexa estendido." -#: ../../whatsnew/3.10.rst:933 +#: ../../whatsnew/3.10.rst:934 msgid "bdb" msgstr "bdb" -#: ../../whatsnew/3.10.rst:935 +#: ../../whatsnew/3.10.rst:936 msgid "" "Add :meth:`~bdb.Breakpoint.clearBreakpoints` to reset all set breakpoints. " "(Contributed by Irit Katriel in :issue:`24160`.)" @@ -1335,11 +1940,11 @@ msgstr "" "pontos de interrupção definidos. (Contribuição de Irit Katriel em :issue:" "`24160`.)" -#: ../../whatsnew/3.10.rst:939 +#: ../../whatsnew/3.10.rst:940 msgid "bisect" msgstr "bisect" -#: ../../whatsnew/3.10.rst:941 +#: ../../whatsnew/3.10.rst:942 msgid "" "Added the possibility of providing a *key* function to the APIs in the :mod:" "`bisect` module. (Contributed by Raymond Hettinger in :issue:`4356`.)" @@ -1347,11 +1952,11 @@ msgstr "" "Adicionada a possibilidade de fornecer uma função *key* para as APIs no " "módulo :mod:`bisect`. (Contribuição de Raymond Hettinger em :issue:`4356`.)" -#: ../../whatsnew/3.10.rst:945 +#: ../../whatsnew/3.10.rst:946 msgid "codecs" msgstr "codecs" -#: ../../whatsnew/3.10.rst:947 +#: ../../whatsnew/3.10.rst:948 msgid "" "Add a :func:`codecs.unregister` function to unregister a codec search " "function. (Contributed by Hai Shi in :issue:`41842`.)" @@ -1360,11 +1965,11 @@ msgstr "" "uma função de pesquisa de codecs. (Contribuição de Hai Shi em :issue:" "`41842`.)" -#: ../../whatsnew/3.10.rst:951 +#: ../../whatsnew/3.10.rst:952 msgid "collections.abc" msgstr "collections.abc" -#: ../../whatsnew/3.10.rst:953 +#: ../../whatsnew/3.10.rst:954 msgid "" "The ``__args__`` of the :ref:`parameterized generic ` " "for :class:`collections.abc.Callable` are now consistent with :data:`typing." @@ -1392,11 +1997,11 @@ msgstr "" "parametrizar :class:`collections.abc.Callable` que podem ter passado " "silenciosamente no Python 3.9. (Contribuição de Ken Jin em :issue:`42195`.)" -#: ../../whatsnew/3.10.rst:966 +#: ../../whatsnew/3.10.rst:967 msgid "contextlib" msgstr "contextlib" -#: ../../whatsnew/3.10.rst:968 +#: ../../whatsnew/3.10.rst:969 msgid "" "Add a :func:`contextlib.aclosing` context manager to safely close async " "generators and objects representing asynchronously released resources. " @@ -1407,7 +2012,7 @@ msgstr "" "liberados de forma assíncrona. (Contribuição de Joongi Kim e John Belmonte " "em :issue:`41229`.)" -#: ../../whatsnew/3.10.rst:972 +#: ../../whatsnew/3.10.rst:973 msgid "" "Add asynchronous context manager support to :func:`contextlib.nullcontext`. " "(Contributed by Tom Gringauz in :issue:`41543`.)" @@ -1415,7 +2020,7 @@ msgstr "" "Adiciona suporte a gerenciador de contexto assíncrono a :func:`contextlib." "nullcontext`. (Contribuição de Tom Gringauz em :issue:`41543`.)" -#: ../../whatsnew/3.10.rst:975 +#: ../../whatsnew/3.10.rst:976 msgid "" "Add :class:`~contextlib.AsyncContextDecorator`, for supporting usage of " "async context managers as decorators." @@ -1423,11 +2028,11 @@ msgstr "" "Adiciona :class:`~contextlib.AsyncContextDecorator`, para dar suporte ao uso " "de gerenciadores de contexto assíncronos como decoradores." -#: ../../whatsnew/3.10.rst:979 +#: ../../whatsnew/3.10.rst:980 msgid "curses" msgstr "curses" -#: ../../whatsnew/3.10.rst:981 +#: ../../whatsnew/3.10.rst:982 msgid "" "The extended color functions added in ncurses 6.1 will be used transparently " "by :func:`curses.color_content`, :func:`curses.init_color`, :func:`curses." @@ -1443,7 +2048,7 @@ msgstr "" "a cores estendidas é fornecido pela biblioteca ncurses subjacente. " "(Contribuição de Jeffrey Kintscher e Hans Petter Jansson em :issue:`36982`.)" -#: ../../whatsnew/3.10.rst:988 +#: ../../whatsnew/3.10.rst:989 msgid "" "The ``BUTTON5_*`` constants are now exposed in the :mod:`curses` module if " "they are provided by the underlying curses library. (Contributed by Zackery " @@ -1453,15 +2058,15 @@ msgstr "" "forem fornecidas pela biblioteca curses subjacente. (Contribuição de Zackery " "Spytz em :issue:`39273`.)" -#: ../../whatsnew/3.10.rst:993 +#: ../../whatsnew/3.10.rst:994 msgid "dataclasses" msgstr "dataclasses" -#: ../../whatsnew/3.10.rst:996 +#: ../../whatsnew/3.10.rst:997 msgid "__slots__" msgstr "__slots__" -#: ../../whatsnew/3.10.rst:998 +#: ../../whatsnew/3.10.rst:999 msgid "" "Added ``slots`` parameter in :func:`dataclasses.dataclass` decorator. " "(Contributed by Yurii Karabas in :issue:`42269`)" @@ -1469,25 +2074,41 @@ msgstr "" "Adicionado o parâmetro ``slots`` no decorador :func:`dataclasses.dataclass`. " "(Contribuição de Yurii Karabas em :issue:`42269`)" -#: ../../whatsnew/3.10.rst:1002 +#: ../../whatsnew/3.10.rst:1003 msgid "Keyword-only fields" msgstr "Campos somente-nomeados" -#: ../../whatsnew/3.10.rst:1004 +#: ../../whatsnew/3.10.rst:1005 msgid "" "dataclasses now supports fields that are keyword-only in the generated " "__init__ method. There are a number of ways of specifying keyword-only " "fields." msgstr "" -"dataclasses agora oferece suporte a campos que são somente palavras-chave no " -"método __init__ gerado. Há várias maneiras de especificar campos somente de " -"palavras-chave." +"dataclasses agora oferece suporte a campos que são somente-nomeados no " +"método __init__ gerado. Há várias maneiras de especificar campos somente-" +"nomeados." -#: ../../whatsnew/3.10.rst:1008 +#: ../../whatsnew/3.10.rst:1009 msgid "You can say that every field is keyword-only:" msgstr "Você pode dizer que todos os campos são somente-nomeados:" -#: ../../whatsnew/3.10.rst:1019 +#: ../../whatsnew/3.10.rst:1011 +msgid "" +"from dataclasses import dataclass\n" +"\n" +"@dataclass(kw_only=True)\n" +"class Birthday:\n" +" name: str\n" +" birthday: datetime.date" +msgstr "" +"from dataclasses import dataclass\n" +"\n" +"@dataclass(kw_only=True)\n" +"class Birthday:\n" +" name: str\n" +" birthday: datetime.date" + +#: ../../whatsnew/3.10.rst:1020 msgid "" "Both ``name`` and ``birthday`` are keyword-only parameters to the generated " "__init__ method." @@ -1495,11 +2116,27 @@ msgstr "" "Ambos ``name`` e ``birthday`` são parâmetros somente-nomeados para o método " "__init__ gerado." -#: ../../whatsnew/3.10.rst:1022 +#: ../../whatsnew/3.10.rst:1023 msgid "You can specify keyword-only on a per-field basis:" msgstr "Você pode especificar somente-nomeado por campo:" -#: ../../whatsnew/3.10.rst:1033 +#: ../../whatsnew/3.10.rst:1025 +msgid "" +"from dataclasses import dataclass, field\n" +"\n" +"@dataclass\n" +"class Birthday:\n" +" name: str\n" +" birthday: datetime.date = field(kw_only=True)" +msgstr "" +"from dataclasses import dataclass, field\n" +"\n" +"@dataclass\n" +"class Birthday:\n" +" name: str\n" +" birthday: datetime.date = field(kw_only=True)" + +#: ../../whatsnew/3.10.rst:1034 msgid "" "Here only ``birthday`` is keyword-only. If you set ``kw_only`` on " "individual fields, be aware that there are rules about re-ordering fields " @@ -1509,18 +2146,40 @@ msgstr "" "Aqui apenas ``birthday`` é somente-nomeado. Se você definir ``kw_only`` em " "campos individuais, esteja ciente de que existem regras sobre a reordenação " "de campos devido a campos somente-nomeados que precisam seguir campos não " -"somente-nomeados. Consulte a documentação completa das classes de dados para " -"obter detalhes." +"somente-nomeados. Consulte a documentação completa de dataclasses para obter " +"detalhes." -#: ../../whatsnew/3.10.rst:1038 +#: ../../whatsnew/3.10.rst:1039 msgid "" "You can also specify that all fields following a KW_ONLY marker are keyword-" "only. This will probably be the most common usage:" msgstr "" -"Você também pode especificar que todos os campos que seguem um marcador " +"Você também pode especificar que todos os campos a partir de um marcador " "KW_ONLY sejam somente-nomeados. Este provavelmente será o uso mais comum:" -#: ../../whatsnew/3.10.rst:1053 +#: ../../whatsnew/3.10.rst:1042 +msgid "" +"from dataclasses import dataclass, KW_ONLY\n" +"\n" +"@dataclass\n" +"class Point:\n" +" x: float\n" +" y: float\n" +" _: KW_ONLY\n" +" z: float = 0.0\n" +" t: float = 0.0" +msgstr "" +"from dataclasses import dataclass, KW_ONLY\n" +"\n" +"@dataclass\n" +"class Point:\n" +" x: float\n" +" y: float\n" +" _: KW_ONLY\n" +" z: float = 0.0\n" +" t: float = 0.0" + +#: ../../whatsnew/3.10.rst:1054 msgid "" "Here, ``z`` and ``t`` are keyword-only parameters, while ``x`` and ``y`` are " "not. (Contributed by Eric V. Smith in :issue:`43532`.)" @@ -1528,11 +2187,11 @@ msgstr "" "Aqui, ``z`` e ``t`` são parâmetros somente-nomeados, enquanto ``x`` e ``y`` " "não são. (Contribuição de Eric V. Smith em :issue:`43532`.)" -#: ../../whatsnew/3.10.rst:1060 +#: ../../whatsnew/3.10.rst:1061 msgid "distutils" msgstr "distutils" -#: ../../whatsnew/3.10.rst:1062 +#: ../../whatsnew/3.10.rst:1063 msgid "" "The entire ``distutils`` package is deprecated, to be removed in Python " "3.12. Its functionality for specifying package builds has already been " @@ -1554,7 +2213,7 @@ msgstr "" "usando outras funções devem planejar fazer cópias privadas do código. " "Consulte :pep:`632` para discussão." -#: ../../whatsnew/3.10.rst:1072 +#: ../../whatsnew/3.10.rst:1073 msgid "" "The ``bdist_wininst`` command deprecated in Python 3.8 has been removed. The " "``bdist_wheel`` command is now recommended to distribute binary packages on " @@ -1564,12 +2223,12 @@ msgstr "" "comando ``bdist_wheel`` agora é recomendado para distribuir pacotes binários " "no Windows. (Contribuição de Victor Stinner em :issue:`42802`.)" -#: ../../whatsnew/3.10.rst:1078 +#: ../../whatsnew/3.10.rst:1079 msgid "doctest" msgstr "doctest" -#: ../../whatsnew/3.10.rst:1080 ../../whatsnew/3.10.rst:1215 -#: ../../whatsnew/3.10.rst:1242 ../../whatsnew/3.10.rst:1341 +#: ../../whatsnew/3.10.rst:1081 ../../whatsnew/3.10.rst:1216 +#: ../../whatsnew/3.10.rst:1243 ../../whatsnew/3.10.rst:1342 msgid "" "When a module does not define ``__loader__``, fall back to ``__spec__." "loader``. (Contributed by Brett Cannon in :issue:`42133`.)" @@ -1577,11 +2236,11 @@ msgstr "" "Quando um módulo não define ``__loader__``, recorre a ``__spec__.loader``. " "(Contribuição de Brett Cannon em :issue:`42133`.)" -#: ../../whatsnew/3.10.rst:1084 +#: ../../whatsnew/3.10.rst:1085 msgid "encodings" msgstr "encodings" -#: ../../whatsnew/3.10.rst:1086 +#: ../../whatsnew/3.10.rst:1087 msgid "" ":func:`encodings.normalize_encoding` now ignores non-ASCII characters. " "(Contributed by Hai Shi in :issue:`39337`.)" @@ -1589,11 +2248,11 @@ msgstr "" ":func:`encodings.normalize_encoding` agora ignora caracteres não-ASCII. " "(Contribuição de Hai Shi em :issue:`39337`.)" -#: ../../whatsnew/3.10.rst:1090 +#: ../../whatsnew/3.10.rst:1091 msgid "enum" msgstr "enum" -#: ../../whatsnew/3.10.rst:1092 +#: ../../whatsnew/3.10.rst:1093 msgid "" ":class:`~enum.Enum` :func:`~object.__repr__` now returns ``enum_name." "member_name`` and :func:`~object.__str__` now returns ``member_name``. " @@ -1606,7 +2265,7 @@ msgstr "" "``module_name.member_name``. (Contribuição de Ethan Furman em :issue:" "`40066`.)" -#: ../../whatsnew/3.10.rst:1097 +#: ../../whatsnew/3.10.rst:1098 msgid "" "Add :class:`enum.StrEnum` for enums where all members are strings. " "(Contributed by Ethan Furman in :issue:`41816`.)" @@ -1614,11 +2273,11 @@ msgstr "" "Adiciona :class:`enum.StrEnum` para enums onde todos os membros são strings. " "(Contribuição de Ethan Furman em :issue:`41816`.)" -#: ../../whatsnew/3.10.rst:1101 +#: ../../whatsnew/3.10.rst:1102 msgid "fileinput" msgstr "fileinput" -#: ../../whatsnew/3.10.rst:1103 +#: ../../whatsnew/3.10.rst:1104 msgid "" "Add *encoding* and *errors* parameters in :func:`fileinput.input` and :class:" "`fileinput.FileInput`. (Contributed by Inada Naoki in :issue:`43712`.)" @@ -1626,7 +2285,7 @@ msgstr "" "Adiciona os parâmetros *encoding* e *errors* a :func:`fileinput.input` e :" "class:`fileinput.FileInput`. (Contribuição de Inada Naoki em :issue:`43712`.)" -#: ../../whatsnew/3.10.rst:1107 +#: ../../whatsnew/3.10.rst:1108 msgid "" ":func:`fileinput.hook_compressed` now returns :class:`~io.TextIOWrapper` " "object when *mode* is \"r\" and file is compressed, like uncompressed files. " @@ -1636,11 +2295,11 @@ msgstr "" "TextIOWrapper` quando *mode* é \"r\" e o arquivo está compactado, como " "arquivos descompactados. (Contribuição de Inada Naoki em :issue:`5758`.)" -#: ../../whatsnew/3.10.rst:1112 +#: ../../whatsnew/3.10.rst:1113 msgid "faulthandler" msgstr "faulthandler" -#: ../../whatsnew/3.10.rst:1114 +#: ../../whatsnew/3.10.rst:1115 msgid "" "The :mod:`faulthandler` module now detects if a fatal error occurs during a " "garbage collector collection. (Contributed by Victor Stinner in :issue:" @@ -1650,11 +2309,11 @@ msgstr "" "coleta do coletor de lixo. (Contribuição de Victor Stinner em :issue:" "`44466`.)" -#: ../../whatsnew/3.10.rst:1119 +#: ../../whatsnew/3.10.rst:1120 msgid "gc" msgstr "gc" -#: ../../whatsnew/3.10.rst:1121 +#: ../../whatsnew/3.10.rst:1122 msgid "" "Add audit hooks for :func:`gc.get_objects`, :func:`gc.get_referrers` and :" "func:`gc.get_referents`. (Contributed by Pablo Galindo in :issue:`43439`.)" @@ -1663,11 +2322,11 @@ msgstr "" "get_referrers` e :func:`gc.get_referents`. (Contribuição de Pablo Galindo " "em :issue:`43439`.)" -#: ../../whatsnew/3.10.rst:1125 +#: ../../whatsnew/3.10.rst:1126 msgid "glob" msgstr "glob" -#: ../../whatsnew/3.10.rst:1127 +#: ../../whatsnew/3.10.rst:1128 msgid "" "Add the *root_dir* and *dir_fd* parameters in :func:`~glob.glob` and :func:" "`~glob.iglob` which allow to specify the root directory for searching. " @@ -1677,11 +2336,11 @@ msgstr "" "`~glob.iglob`, o que permite especificar o diretório raiz para a pesquisa. " "(Contribuição de Serhiy Storchaka em :issue:`38144`.)" -#: ../../whatsnew/3.10.rst:1132 +#: ../../whatsnew/3.10.rst:1133 msgid "hashlib" msgstr "hashlib" -#: ../../whatsnew/3.10.rst:1134 +#: ../../whatsnew/3.10.rst:1135 msgid "" "The hashlib module requires OpenSSL 1.1.1 or newer. (Contributed by " "Christian Heimes in :pep:`644` and :issue:`43669`.)" @@ -1689,7 +2348,7 @@ msgstr "" "O módulo hashlib requer OpenSSL 1.1.1 ou mais recente. (Contribuição de " "Christian Heimes em :pep:`644` e :issue:`43669`.)" -#: ../../whatsnew/3.10.rst:1137 +#: ../../whatsnew/3.10.rst:1138 msgid "" "The hashlib module has preliminary support for OpenSSL 3.0.0. (Contributed " "by Christian Heimes in :issue:`38820` and other issues.)" @@ -1697,7 +2356,7 @@ msgstr "" "O módulo hashlib tem suporte preliminar a OpenSSL 3.0.0. (Contribuição de " "Christian Heimes em :issue:`38820` e outras issues.)" -#: ../../whatsnew/3.10.rst:1140 +#: ../../whatsnew/3.10.rst:1141 msgid "" "The pure-Python fallback of :func:`~hashlib.pbkdf2_hmac` is deprecated. In " "the future PBKDF2-HMAC will only be available when Python has been built " @@ -1708,11 +2367,11 @@ msgstr "" "for desenvolvido com suporte a OpenSSL. (Contribuição de Christian Heimes " "em :issue:`43880`.)" -#: ../../whatsnew/3.10.rst:1146 +#: ../../whatsnew/3.10.rst:1147 msgid "hmac" msgstr "hmac" -#: ../../whatsnew/3.10.rst:1148 +#: ../../whatsnew/3.10.rst:1149 msgid "" "The hmac module now uses OpenSSL's HMAC implementation internally. " "(Contributed by Christian Heimes in :issue:`40645`.)" @@ -1720,11 +2379,11 @@ msgstr "" "O módulo hmac agora usa a implementação HMAC do OpenSSL internamente. " "(Contribuição de Christian Heimes em :issue:`40645`.)" -#: ../../whatsnew/3.10.rst:1152 +#: ../../whatsnew/3.10.rst:1153 msgid "IDLE and idlelib" msgstr "IDLE e idlelib" -#: ../../whatsnew/3.10.rst:1154 +#: ../../whatsnew/3.10.rst:1155 msgid "" "Make IDLE invoke :func:`sys.excepthook` (when started without '-n'). User " "hooks were previously ignored. (Contributed by Ken Hilton in :issue:" @@ -1734,7 +2393,7 @@ msgstr "" "Ganchos de usuário eram ignorados anteriormente. (Contribuição de Ken Hilton " "em :issue:`43008`.)" -#: ../../whatsnew/3.10.rst:1158 +#: ../../whatsnew/3.10.rst:1159 msgid "" "Rearrange the settings dialog. Split the General tab into Windows and Shell/" "Ed tabs. Move help sources, which extend the Help menu, to the Extensions " @@ -1752,11 +2411,11 @@ msgstr "" "espaço de recuo da aba Font para a nova aba Windows. (Contribuição de Mark " "Roseman e Terry Jan Reedy em :issue:`33962`.)" -#: ../../whatsnew/3.10.rst:1166 +#: ../../whatsnew/3.10.rst:1167 msgid "The changes above were backported to a 3.9 maintenance release." msgstr "As alterações acima foram portadas para uma versão de manutenção 3.9." -#: ../../whatsnew/3.10.rst:1168 +#: ../../whatsnew/3.10.rst:1169 msgid "" "Add a Shell sidebar. Move the primary prompt ('>>>') to the sidebar. Add " "secondary prompts ('...') to the sidebar. Left click and optional drag " @@ -1775,7 +2434,7 @@ msgstr "" "lateral com linhas do texto selecionado. Esta opção também aparece no menu " "de contexto para o texto. (Contribuição de Tal Einat em :issue:`37903`.)" -#: ../../whatsnew/3.10.rst:1177 +#: ../../whatsnew/3.10.rst:1178 msgid "" "Use spaces instead of tabs to indent interactive code. This makes " "interactive code entries 'look right'. Making this feasible was a major " @@ -1787,7 +2446,7 @@ msgstr "" "viável foi a principal motivação para adicionar a barra lateral do console. " "Contribuição de Terry Jan Reedy em :issue:`37892`.)" -#: ../../whatsnew/3.10.rst:1182 +#: ../../whatsnew/3.10.rst:1183 msgid "" "Highlight the new :ref:`soft keywords ` :keyword:`match`, :" "keyword:`case `, and :keyword:`_ ` in pattern-" @@ -1801,11 +2460,11 @@ msgstr "" "perfeito e estará incorreto em alguns casos raros, incluindo alguns ``_`` em " "padrões de ``case``. (Contribuição de Tal Einat em :issue:`44010`.)" -#: ../../whatsnew/3.10.rst:1188 +#: ../../whatsnew/3.10.rst:1189 msgid "New in 3.10 maintenance releases." msgstr "Novo nas versões de manutenção 3.10." -#: ../../whatsnew/3.10.rst:1190 +#: ../../whatsnew/3.10.rst:1191 msgid "" "Apply syntax highlighting to ``.pyi`` files. (Contributed by Alex Waygood " "and Terry Jan Reedy in :issue:`45447`.)" @@ -1813,7 +2472,7 @@ msgstr "" "Aplica realce de sintaxe em arquivos ``.pyi``. (Contribuição de Alex Waygood " "e Terry Jan Reedy em :issue:`45447`.)" -#: ../../whatsnew/3.10.rst:1193 +#: ../../whatsnew/3.10.rst:1194 msgid "" "Include prompts when saving Shell with inputs and outputs. (Contributed by " "Terry Jan Reedy in :gh:`95191`.)" @@ -1821,11 +2480,11 @@ msgstr "" "Inclui prompts ao salvar o console com entradas e saídas. (Contribuição de " "Terry Jan Reedy em :gh:`95191`.)" -#: ../../whatsnew/3.10.rst:1197 +#: ../../whatsnew/3.10.rst:1198 msgid "importlib.metadata" msgstr "importlib.metadata" -#: ../../whatsnew/3.10.rst:1199 +#: ../../whatsnew/3.10.rst:1200 msgid "" "Feature parity with ``importlib_metadata`` 4.6 (`history `_)." @@ -1833,7 +2492,7 @@ msgstr "" "Paridade de recursos com ``importlib_metadata`` 4.6 (`histórico `_)." -#: ../../whatsnew/3.10.rst:1202 +#: ../../whatsnew/3.10.rst:1203 msgid "" ":ref:`importlib.metadata entry points ` now provide a nicer " "experience for selecting entry points by group and name through a new :ref:" @@ -1846,7 +2505,7 @@ msgstr "" "Consulte a Nota de Compatibilidade nos documentos para obter mais " "informações sobre a descontinuação e uso." -#: ../../whatsnew/3.10.rst:1208 +#: ../../whatsnew/3.10.rst:1209 msgid "" "Added :ref:`importlib.metadata.packages_distributions() ` for resolving top-level Python modules and packages to " @@ -1856,11 +2515,11 @@ msgstr "" "distributions>` para resolver módulos e pacotes Python de alto nível com " "suas :ref:`importlib.metadata.Distribution `." -#: ../../whatsnew/3.10.rst:1213 +#: ../../whatsnew/3.10.rst:1214 msgid "inspect" msgstr "inspect" -#: ../../whatsnew/3.10.rst:1218 +#: ../../whatsnew/3.10.rst:1219 msgid "" "Add :func:`inspect.get_annotations`, which safely computes the annotations " "defined on an object. It works around the quirks of accessing the " @@ -1892,35 +2551,35 @@ msgstr "" "podem remover a string de anotações em string. (Contribuição de Larry " "Hastings em :issue:`43817`.)" -#: ../../whatsnew/3.10.rst:1234 +#: ../../whatsnew/3.10.rst:1235 msgid "itertools" msgstr "itertools" -#: ../../whatsnew/3.10.rst:1236 +#: ../../whatsnew/3.10.rst:1237 msgid "" -"Add :func:`itertools.pairwise()`. (Contributed by Raymond Hettinger in :" -"issue:`38200`.)" +"Add :func:`itertools.pairwise`. (Contributed by Raymond Hettinger in :issue:" +"`38200`.)" msgstr "" -"Adiciona :func:`itertools.pairwise()`. (Contribuição de Raymond Hettinger " -"em :issue:`38200`.)" +"Adiciona :func:`itertools.pairwise`. (Contribuição de Raymond Hettinger em :" +"issue:`38200`.)" -#: ../../whatsnew/3.10.rst:1240 +#: ../../whatsnew/3.10.rst:1241 msgid "linecache" msgstr "linecache" -#: ../../whatsnew/3.10.rst:1246 +#: ../../whatsnew/3.10.rst:1247 msgid "os" msgstr "os" -#: ../../whatsnew/3.10.rst:1248 +#: ../../whatsnew/3.10.rst:1249 msgid "" -"Add :func:`os.cpu_count()` support for VxWorks RTOS. (Contributed by Peixing " +"Add :func:`os.cpu_count` support for VxWorks RTOS. (Contributed by Peixing " "Xin in :issue:`41440`.)" msgstr "" -"Adiciona suporte a :func:`os.cpu_count()` para RTOS de VxWorks. " -"(Contribuição de Peixing Xin em :issue:`41440`.)" +"Adiciona suporte a :func:`os.cpu_count` para RTOS de VxWorks. (Contribuição " +"de Peixing Xin em :issue:`41440`.)" -#: ../../whatsnew/3.10.rst:1251 +#: ../../whatsnew/3.10.rst:1252 msgid "" "Add a new function :func:`os.eventfd` and related helpers to wrap the " "``eventfd2`` syscall on Linux. (Contributed by Christian Heimes in :issue:" @@ -1930,19 +2589,19 @@ msgstr "" "envolver a chamada de sistema ``eventfd2`` no Linux. (Contribuição de " "Christian Heimes em :issue:`41001`.)" -#: ../../whatsnew/3.10.rst:1255 +#: ../../whatsnew/3.10.rst:1256 msgid "" -"Add :func:`os.splice()` that allows to move data between two file " -"descriptors without copying between kernel address space and user address " -"space, where one of the file descriptors must refer to a pipe. (Contributed " -"by Pablo Galindo in :issue:`41625`.)" +"Add :func:`os.splice` that allows to move data between two file descriptors " +"without copying between kernel address space and user address space, where " +"one of the file descriptors must refer to a pipe. (Contributed by Pablo " +"Galindo in :issue:`41625`.)" msgstr "" -"Adiciona :func:`os.splice()` que permite mover dados entre dois descritores " -"de arquivo sem copiar entre o espaço de endereço do kernel e o espaço de " +"Adiciona :func:`os.splice` que permite mover dados entre dois descritores de " +"arquivo sem copiar entre o espaço de endereço do kernel e o espaço de " "endereço do usuário, onde um dos descritores de arquivo deve se referir a um " "encadeamento (pipe). (Contribuição de Pablo Galindo em :issue:`41625`.)" -#: ../../whatsnew/3.10.rst:1260 +#: ../../whatsnew/3.10.rst:1261 msgid "" "Add :const:`~os.O_EVTONLY`, :const:`~os.O_FSYNC`, :const:`~os.O_SYMLINK` " "and :const:`~os.O_NOFOLLOW_ANY` for macOS. (Contributed by Donghee Na in :" @@ -1952,11 +2611,11 @@ msgstr "" "O_SYMLINK` e :const:`~os.O_NOFOLLOW_ANY` para macOS. (Contribuição de " "Donghee Na em :issue:`43106`.)" -#: ../../whatsnew/3.10.rst:1265 +#: ../../whatsnew/3.10.rst:1266 msgid "os.path" msgstr "os.path" -#: ../../whatsnew/3.10.rst:1267 +#: ../../whatsnew/3.10.rst:1268 msgid "" ":func:`os.path.realpath` now accepts a *strict* keyword-only argument. When " "set to ``True``, :exc:`OSError` is raised if a path doesn't exist or a " @@ -1967,11 +2626,11 @@ msgstr "" "caminho não existe ou um loop de link simbólico é encontrado. (Contribuição " "de Barney Gale em :issue:`43757`.)" -#: ../../whatsnew/3.10.rst:1273 +#: ../../whatsnew/3.10.rst:1274 msgid "pathlib" msgstr "pathlib" -#: ../../whatsnew/3.10.rst:1275 +#: ../../whatsnew/3.10.rst:1276 msgid "" "Add slice support to :attr:`PurePath.parents `. " "(Contributed by Joshua Cannon in :issue:`35498`.)" @@ -1979,7 +2638,7 @@ msgstr "" "Adiciona suporte a fatiamento a :attr:`PurePath.parents `. (Contribuição de Joshua Cannon em :issue:`35498`.)" -#: ../../whatsnew/3.10.rst:1278 +#: ../../whatsnew/3.10.rst:1279 msgid "" "Add negative indexing support to :attr:`PurePath.parents `. (Contributed by Yaroslav Pankovych in :issue:`21041`.)" @@ -1987,7 +2646,7 @@ msgstr "" "Adiciona suporte a indexação negativa a :attr:`PurePath.parents `. (Contribuição de Yaroslav Pankovych em :issue:`21041`.)" -#: ../../whatsnew/3.10.rst:1282 +#: ../../whatsnew/3.10.rst:1283 msgid "" "Add :meth:`Path.hardlink_to ` method that " "supersedes :meth:`!link_to`. The new method has the same argument order as :" @@ -1999,7 +2658,7 @@ msgstr "" "que :meth:`~pathlib.Path.symlink_to`. (Contribuição de Barney Gale em :issue:" "`39950`.)" -#: ../../whatsnew/3.10.rst:1287 +#: ../../whatsnew/3.10.rst:1288 msgid "" ":meth:`pathlib.Path.stat` and :meth:`~pathlib.Path.chmod` now accept a " "*follow_symlinks* keyword-only argument for consistency with corresponding " @@ -2011,27 +2670,27 @@ msgstr "" "correspondentes no módulo :mod:`os`. (Contribuição de Barney Gale em :issue:" "`39906`.)" -#: ../../whatsnew/3.10.rst:1293 +#: ../../whatsnew/3.10.rst:1294 msgid "platform" msgstr "platform" -#: ../../whatsnew/3.10.rst:1295 +#: ../../whatsnew/3.10.rst:1296 msgid "" -"Add :func:`platform.freedesktop_os_release()` to retrieve operation system " +"Add :func:`platform.freedesktop_os_release` to retrieve operation system " "identification from `freedesktop.org os-release `_ standard file. (Contributed by " "Christian Heimes in :issue:`28468`.)" msgstr "" -"Adiciona :func:`platform.freedesktop_os_release()` para obter a " -"identificação do sistema operacional a partir do arquivo padrão `os-release " -"do freedesktop.org `_. (Contribuição de Christian Heimes em :issue:`28468`.)" +"Adiciona :func:`platform.freedesktop_os_release` para obter a identificação " +"do sistema operacional a partir do arquivo padrão `os-release do freedesktop." +"org `_. " +"(Contribuição de Christian Heimes em :issue:`28468`.)" -#: ../../whatsnew/3.10.rst:1301 +#: ../../whatsnew/3.10.rst:1302 msgid "pprint" msgstr "pprint" -#: ../../whatsnew/3.10.rst:1303 +#: ../../whatsnew/3.10.rst:1304 msgid "" ":func:`pprint.pprint` now accepts a new ``underscore_numbers`` keyword " "argument. (Contributed by sblondon in :issue:`42914`.)" @@ -2039,7 +2698,7 @@ msgstr "" ":func:`pprint.pprint` agora aceita um novo argumento nomeado " "``underscore_numbers``. (Contribuição de sblondon em :issue:`42914`.)" -#: ../../whatsnew/3.10.rst:1306 +#: ../../whatsnew/3.10.rst:1307 msgid "" ":mod:`pprint` can now pretty-print :class:`dataclasses.dataclass` instances. " "(Contributed by Lewis Gaul in :issue:`43080`.)" @@ -2047,11 +2706,11 @@ msgstr "" ":mod:`pprint` agora pode fazer impressão bonita de instâncias de :class:" "`dataclasses.dataclass`. (Contribuição de Lewis Gaul em :issue:`43080`.)" -#: ../../whatsnew/3.10.rst:1310 +#: ../../whatsnew/3.10.rst:1311 msgid "py_compile" msgstr "py_compile" -#: ../../whatsnew/3.10.rst:1312 +#: ../../whatsnew/3.10.rst:1313 msgid "" "Add ``--quiet`` option to command-line interface of :mod:`py_compile`. " "(Contributed by Gregory Schevchenko in :issue:`38731`.)" @@ -2059,11 +2718,11 @@ msgstr "" "Adiciona a opção ``--quiet`` à interface de linha de comando de :mod:" "`py_compile`. (Contribuição de Gregory Schevchenko em :issue:`38731`.)" -#: ../../whatsnew/3.10.rst:1316 +#: ../../whatsnew/3.10.rst:1317 msgid "pyclbr" msgstr "pyclbr" -#: ../../whatsnew/3.10.rst:1318 +#: ../../whatsnew/3.10.rst:1319 msgid "" "Add an ``end_lineno`` attribute to the ``Function`` and ``Class`` objects in " "the tree returned by :func:`pyclbr.readmodule` and :func:`pyclbr." @@ -2075,11 +2734,11 @@ msgstr "" "readmodule_ex`. Isso corresponde ao ``lineno`` (início) existente. " "(Contribuição de Aviral Srivastava em :issue:`38307`.)" -#: ../../whatsnew/3.10.rst:1324 +#: ../../whatsnew/3.10.rst:1325 msgid "shelve" msgstr "shelve" -#: ../../whatsnew/3.10.rst:1326 +#: ../../whatsnew/3.10.rst:1327 msgid "" "The :mod:`shelve` module now uses :const:`pickle.DEFAULT_PROTOCOL` by " "default instead of :mod:`pickle` protocol ``3`` when creating shelves. " @@ -2089,11 +2748,11 @@ msgstr "" "em vez do protocolo ``3`` do :mod:`pickle` ao criar \"shelves\". " "(Contribuição de Zackery Spytz em :issue:`34204`.)" -#: ../../whatsnew/3.10.rst:1331 +#: ../../whatsnew/3.10.rst:1332 msgid "statistics" msgstr "statistics" -#: ../../whatsnew/3.10.rst:1333 +#: ../../whatsnew/3.10.rst:1334 msgid "" "Add :func:`~statistics.covariance`, Pearson's :func:`~statistics." "correlation`, and simple :func:`~statistics.linear_regression` functions. " @@ -2103,15 +2762,15 @@ msgstr "" "Pearson, e funções simples :func:`~statistics.linear_regression`. " "(Contribuição de Tymoteusz Wołodźko em :issue:`38490`.)" -#: ../../whatsnew/3.10.rst:1339 +#: ../../whatsnew/3.10.rst:1340 msgid "site" msgstr "site" -#: ../../whatsnew/3.10.rst:1345 +#: ../../whatsnew/3.10.rst:1346 msgid "socket" msgstr "socket" -#: ../../whatsnew/3.10.rst:1347 +#: ../../whatsnew/3.10.rst:1348 msgid "" "The exception :exc:`socket.timeout` is now an alias of :exc:`TimeoutError`. " "(Contributed by Christian Heimes in :issue:`42413`.)" @@ -2119,7 +2778,7 @@ msgstr "" "A exceção :exc:`socket.timeout` é agora um apelido de :exc:`TimeoutError`. " "(Contribuição de Christian Heimes em :issue:`42413`.)" -#: ../../whatsnew/3.10.rst:1350 +#: ../../whatsnew/3.10.rst:1351 msgid "" "Add option to create MPTCP sockets with ``IPPROTO_MPTCP`` (Contributed by " "Rui Cunha in :issue:`43571`.)" @@ -2127,7 +2786,7 @@ msgstr "" "Adiciona a opção de criar soquetes MPTCP com ``IPPROTO_MPTCP`` (Contribuição " "de Rui Cunha em :issue:`43571`.)" -#: ../../whatsnew/3.10.rst:1353 +#: ../../whatsnew/3.10.rst:1354 msgid "" "Add ``IP_RECVTOS`` option to receive the type of service (ToS) or DSCP/ECN " "fields (Contributed by Georg Sauthoff in :issue:`44077`.)" @@ -2135,11 +2794,11 @@ msgstr "" "Adiciona a opção ``IP_RECVTOS`` para receber o tipo do serviço (ToS) ou " "campos DSCP/ECN (Contribuição de Georg Sauthoff em :issue:`44077`.)" -#: ../../whatsnew/3.10.rst:1357 +#: ../../whatsnew/3.10.rst:1358 msgid "ssl" msgstr "ssl" -#: ../../whatsnew/3.10.rst:1359 +#: ../../whatsnew/3.10.rst:1360 msgid "" "The ssl module requires OpenSSL 1.1.1 or newer. (Contributed by Christian " "Heimes in :pep:`644` and :issue:`43669`.)" @@ -2147,7 +2806,7 @@ msgstr "" "O módulo ssl requer OpenSSL 1.1.1 ou mais recente. (Contribuição de " "Christian Heimes em :pep:`644` e :issue:`43669`.)" -#: ../../whatsnew/3.10.rst:1362 +#: ../../whatsnew/3.10.rst:1363 msgid "" "The ssl module has preliminary support for OpenSSL 3.0.0 and new option :" "const:`~ssl.OP_IGNORE_UNEXPECTED_EOF`. (Contributed by Christian Heimes in :" @@ -2159,7 +2818,7 @@ msgstr "" "issue:`38820`, :issue:`43794`, :issue:`43788`, :issue:`43791`, :issue:" "`43799`, :issue:`43920`, :issue:`43789` e :issue:`43811`.)" -#: ../../whatsnew/3.10.rst:1368 +#: ../../whatsnew/3.10.rst:1369 msgid "" "Deprecated function and use of deprecated constants now result in a :exc:" "`DeprecationWarning`. :attr:`ssl.SSLContext.options` has :data:`~ssl." @@ -2176,7 +2835,7 @@ msgstr "" "recursos descontinuados. (Contribuição de Christian Heimes em :issue:" "`43880`.)" -#: ../../whatsnew/3.10.rst:1376 +#: ../../whatsnew/3.10.rst:1377 msgid "" "The ssl module now has more secure default settings. Ciphers without forward " "secrecy or SHA-1 MAC are disabled by default. Security level 2 prohibits " @@ -2192,7 +2851,7 @@ msgstr "" "protocolo TLS 1.2. As configurações são baseadas na pesquisa de Hynek " "Schlawack. (Contribuição de Christian Heimes em :issue:`43998`.)" -#: ../../whatsnew/3.10.rst:1383 +#: ../../whatsnew/3.10.rst:1384 msgid "" "The deprecated protocols SSL 3.0, TLS 1.0, and TLS 1.1 are no longer " "officially supported. Python does not block them actively. However OpenSSL " @@ -2205,7 +2864,7 @@ msgstr "" "fornecedores e suítes de criptografia podem impedir um handshake bem-" "sucedido." -#: ../../whatsnew/3.10.rst:1388 +#: ../../whatsnew/3.10.rst:1389 msgid "" "Add a *timeout* parameter to the :func:`ssl.get_server_certificate` " "function. (Contributed by Zackery Spytz in :issue:`31870`.)" @@ -2213,7 +2872,7 @@ msgstr "" "Adiciona um parâmetro *timeout* à função :func:`ssl.get_server_certificate`. " "(Contribuição de Zackery Spytz em :issue:`31870`.)" -#: ../../whatsnew/3.10.rst:1391 +#: ../../whatsnew/3.10.rst:1392 msgid "" "The ssl module uses heap-types and multi-phase initialization. (Contributed " "by Christian Heimes in :issue:`42333`.)" @@ -2221,7 +2880,7 @@ msgstr "" "O módulo ssl usa tipos de heap e inicialização multifásica. (Contribuição de " "Christian Heimes em :issue:`42333`.)" -#: ../../whatsnew/3.10.rst:1394 +#: ../../whatsnew/3.10.rst:1395 msgid "" "A new verify flag :const:`~ssl.VERIFY_X509_PARTIAL_CHAIN` has been added. " "(Contributed by l0x in :issue:`40849`.)" @@ -2229,11 +2888,11 @@ msgstr "" "Uma nova sinalização de verificação :const:`~ssl.VERIFY_X509_PARTIAL_CHAIN` " "foi adicionada. (Contribuição de l0x em :issue:`40849`.)" -#: ../../whatsnew/3.10.rst:1398 +#: ../../whatsnew/3.10.rst:1399 msgid "sqlite3" msgstr "sqlite3" -#: ../../whatsnew/3.10.rst:1400 +#: ../../whatsnew/3.10.rst:1401 msgid "" "Add audit events for :func:`~sqlite3.connect/handle`, :meth:`~sqlite3." "Connection.enable_load_extension`, and :meth:`~sqlite3.Connection." @@ -2243,11 +2902,11 @@ msgstr "" "`~sqlite3.Connection.enable_load_extension` e :meth:`~sqlite3.Connection." "load_extension`. (Contribuição de Erlend E. Aasland em :issue:`43762`.)" -#: ../../whatsnew/3.10.rst:1406 +#: ../../whatsnew/3.10.rst:1407 msgid "sys" msgstr "sys" -#: ../../whatsnew/3.10.rst:1408 +#: ../../whatsnew/3.10.rst:1409 msgid "" "Add :data:`sys.orig_argv` attribute: the list of the original command line " "arguments passed to the Python executable. (Contributed by Victor Stinner " @@ -2257,7 +2916,7 @@ msgstr "" "comando originais passada para o executável Python. (Contribuição de Victor " "Stinner em :issue:`23427`.)" -#: ../../whatsnew/3.10.rst:1412 +#: ../../whatsnew/3.10.rst:1413 msgid "" "Add :data:`sys.stdlib_module_names`, containing the list of the standard " "library module names. (Contributed by Victor Stinner in :issue:`42955`.)" @@ -2266,11 +2925,11 @@ msgstr "" "módulos da biblioteca padrão. (Contribuição de Victor Stinner em :issue:" "`42955`.)" -#: ../../whatsnew/3.10.rst:1417 +#: ../../whatsnew/3.10.rst:1418 msgid "_thread" msgstr "_thread" -#: ../../whatsnew/3.10.rst:1419 +#: ../../whatsnew/3.10.rst:1420 msgid "" ":func:`_thread.interrupt_main` now takes an optional signal number to " "simulate (the default is still :const:`signal.SIGINT`). (Contributed by " @@ -2280,11 +2939,11 @@ msgstr "" "simular (o padrão ainda é :const:`signal.SIGINT`). (Contribuição de Antoine " "Pitrou em :issue:`43356`.)" -#: ../../whatsnew/3.10.rst:1424 +#: ../../whatsnew/3.10.rst:1425 msgid "threading" msgstr "threading" -#: ../../whatsnew/3.10.rst:1426 +#: ../../whatsnew/3.10.rst:1427 msgid "" "Add :func:`threading.gettrace` and :func:`threading.getprofile` to retrieve " "the functions set by :func:`threading.settrace` and :func:`threading." @@ -2295,7 +2954,7 @@ msgstr "" "setprofile`, respectivamente. (Contribuição de Mario Corchero em :issue:" "`42251`.)" -#: ../../whatsnew/3.10.rst:1431 +#: ../../whatsnew/3.10.rst:1432 msgid "" "Add :data:`threading.__excepthook__` to allow retrieving the original value " "of :func:`threading.excepthook` in case it is set to a broken or a different " @@ -2306,11 +2965,11 @@ msgstr "" "valor quebrado ou diferente. (Contribuição de Mario Corchero em :issue:" "`42308`.)" -#: ../../whatsnew/3.10.rst:1437 +#: ../../whatsnew/3.10.rst:1438 msgid "traceback" msgstr "traceback" -#: ../../whatsnew/3.10.rst:1439 +#: ../../whatsnew/3.10.rst:1440 msgid "" "The :func:`~traceback.format_exception`, :func:`~traceback." "format_exception_only`, and :func:`~traceback.print_exception` functions can " @@ -2322,11 +2981,11 @@ msgstr "" "receber um objeto exceção como um argumento somente-posicional. " "(Contribuição de Zackery Spytz e Matthias Bussonnier em :issue:`26389`.)" -#: ../../whatsnew/3.10.rst:1446 +#: ../../whatsnew/3.10.rst:1447 msgid "types" msgstr "types" -#: ../../whatsnew/3.10.rst:1448 +#: ../../whatsnew/3.10.rst:1449 msgid "" "Reintroduce the :data:`types.EllipsisType`, :data:`types.NoneType` and :data:" "`types.NotImplementedType` classes, providing a new set of types readily " @@ -2338,15 +2997,15 @@ msgstr "" "prontamente interpretáveis pelos verificadores de tipo. (Contribuição de Bas " "van Beek em :issue:`41810`.)" -#: ../../whatsnew/3.10.rst:1454 +#: ../../whatsnew/3.10.rst:1455 msgid "typing" msgstr "typing" -#: ../../whatsnew/3.10.rst:1456 +#: ../../whatsnew/3.10.rst:1457 msgid "For major changes, see :ref:`new-feat-related-type-hints`." msgstr "Para alterações principais, veja :ref:`new-feat-related-type-hints`." -#: ../../whatsnew/3.10.rst:1458 +#: ../../whatsnew/3.10.rst:1459 msgid "" "The behavior of :class:`typing.Literal` was changed to conform with :pep:" "`586` and to match the behavior of static type checkers specified in the PEP." @@ -2355,18 +3014,18 @@ msgstr "" "conformidade com a :pep:`586` e para corresponder ao comportamento de " "verificadores de tipo estático especificados na PEP." -#: ../../whatsnew/3.10.rst:1461 +#: ../../whatsnew/3.10.rst:1462 msgid "``Literal`` now de-duplicates parameters." msgstr "``Literal`` agora elimina a duplicação de parâmetros." -#: ../../whatsnew/3.10.rst:1462 +#: ../../whatsnew/3.10.rst:1463 msgid "" "Equality comparisons between ``Literal`` objects are now order independent." msgstr "" "Comparações de igualdade entre objetos ``Literal`` agora são independentes " "da ordem." -#: ../../whatsnew/3.10.rst:1463 +#: ../../whatsnew/3.10.rst:1464 msgid "" "``Literal`` comparisons now respect types. For example, ``Literal[0] == " "Literal[False]`` previously evaluated to ``True``. It is now ``False``. To " @@ -2378,7 +3037,7 @@ msgstr "" "é ``False``. Para oferecer suporte a essa mudança, o cache de tipo usado " "internamente agora oferece suporte a tipos de diferenciação." -#: ../../whatsnew/3.10.rst:1467 +#: ../../whatsnew/3.10.rst:1468 msgid "" "``Literal`` objects will now raise a :exc:`TypeError` exception during " "equality comparisons if any of their parameters are not :term:`hashable`. " @@ -2390,11 +3049,27 @@ msgstr "" "`hasheáveis `. Observe que declarar ``Literal`` com parâmetros " "inalteráveis não acusará um erro::" -#: ../../whatsnew/3.10.rst:1479 +#: ../../whatsnew/3.10.rst:1473 +msgid "" +">>> from typing import Literal\n" +">>> Literal[{0}]\n" +">>> Literal[{0}] == Literal[{False}]\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: unhashable type: 'set'" +msgstr "" +">>> from typing import Literal\n" +">>> Literal[{0}]\n" +">>> Literal[{0}] == Literal[{False}]\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: unhashable type: 'set'" + +#: ../../whatsnew/3.10.rst:1480 msgid "(Contributed by Yurii Karabas in :issue:`42345`.)" msgstr "(Contribuição de Yurii Karabas em :issue:`42345`.)" -#: ../../whatsnew/3.10.rst:1481 +#: ../../whatsnew/3.10.rst:1482 msgid "" "Add new function :func:`typing.is_typeddict` to introspect if an annotation " "is a :class:`typing.TypedDict`. (Contributed by Patrick Reader in :issue:" @@ -2404,7 +3079,7 @@ msgstr "" "introspecção se uma anotação for uma :class:`typing.TypedDict`. " "(Contribuição de Patrick Reader em :issue:`41792`.)" -#: ../../whatsnew/3.10.rst:1485 +#: ../../whatsnew/3.10.rst:1486 msgid "" "Subclasses of ``typing.Protocol`` which only have data variables declared " "will now raise a ``TypeError`` when checked with ``isinstance`` unless they " @@ -2421,7 +3096,7 @@ msgstr "" "func:`!runtime_checkable` se quiserem protocolos de tempo de execução. " "(Contribuição de Yurii Karabas em :issue:`38908`.)" -#: ../../whatsnew/3.10.rst:1493 +#: ../../whatsnew/3.10.rst:1494 msgid "" "Importing from the ``typing.io`` and ``typing.re`` submodules will now emit :" "exc:`DeprecationWarning`. These submodules have been deprecated since " @@ -2435,11 +3110,11 @@ msgstr "" "pertencente a esses submódulos deve ser importada diretamente de :mod:" "`typing`. (Contribuição de Sebastian Rittau em :issue:`38291`.)" -#: ../../whatsnew/3.10.rst:1501 +#: ../../whatsnew/3.10.rst:1502 msgid "unittest" msgstr "unittest" -#: ../../whatsnew/3.10.rst:1503 +#: ../../whatsnew/3.10.rst:1504 msgid "" "Add new method :meth:`~unittest.TestCase.assertNoLogs` to complement the " "existing :meth:`~unittest.TestCase.assertLogs`. (Contributed by Kit Yan Choi " @@ -2449,11 +3124,11 @@ msgstr "" "complementar o existente :meth:`~unittest.TestCase.assertLogs`. " "(Contribuição de Kit Yan Choi em :issue:`39385`.)" -#: ../../whatsnew/3.10.rst:1508 +#: ../../whatsnew/3.10.rst:1509 msgid "urllib.parse" msgstr "urllib.parse" -#: ../../whatsnew/3.10.rst:1510 +#: ../../whatsnew/3.10.rst:1511 msgid "" "Python versions earlier than Python 3.10 allowed using both ``;`` and ``&`` " "as query parameter separators in :func:`urllib.parse.parse_qs` and :func:" @@ -2475,7 +3150,7 @@ msgstr "" "consulte a respectiva documentação. (Contribuição de Adam Goldschmidt, " "Senthil Kumaran e Ken Jin em :issue:`42967`.)" -#: ../../whatsnew/3.10.rst:1520 +#: ../../whatsnew/3.10.rst:1521 msgid "" "The presence of newline or tab characters in parts of a URL allows for some " "forms of attacks. Following the WHATWG specification that updates :rfc:" @@ -2492,11 +3167,11 @@ msgstr "" "uma nova variável de nível de módulo ``urllib.parse." "_UNSAFE_URL_BYTES_TO_REMOVE``. (Veja :gh:`88048`)" -#: ../../whatsnew/3.10.rst:1528 +#: ../../whatsnew/3.10.rst:1529 msgid "xml" msgstr "xml" -#: ../../whatsnew/3.10.rst:1530 +#: ../../whatsnew/3.10.rst:1531 msgid "" "Add a :class:`~xml.sax.handler.LexicalHandler` class to the :mod:`xml.sax." "handler` module. (Contributed by Jonathan Gossage and Zackery Spytz in :" @@ -2506,11 +3181,11 @@ msgstr "" "`xml.sax.handler`. (Contribuição de Jonathan Gossage e Zackery Spytz em :" "issue:`35018`.)" -#: ../../whatsnew/3.10.rst:1535 +#: ../../whatsnew/3.10.rst:1536 msgid "zipimport" msgstr "zipimport" -#: ../../whatsnew/3.10.rst:1536 +#: ../../whatsnew/3.10.rst:1537 msgid "" "Add methods related to :pep:`451`: :meth:`~zipimport.zipimporter." "find_spec`, :meth:`zipimport.zipimporter.create_module`, and :meth:" @@ -2521,7 +3196,7 @@ msgstr "" "find_spec`, :meth:`zipimport.zipimporter.create_module` e :meth:`zipimport." "zipimporter.exec_module`. (Contribuição de Brett Cannon em :issue:`42131`.)" -#: ../../whatsnew/3.10.rst:1541 +#: ../../whatsnew/3.10.rst:1542 msgid "" "Add :meth:`~zipimport.zipimporter.invalidate_caches` method. (Contributed by " "Desmond Cheong in :issue:`14678`.)" @@ -2529,11 +3204,11 @@ msgstr "" "Adiciona o método :meth:`~zipimport.zipimporter.invalidate_caches`. " "(Contribuição de Desmond Cheong em :issue:`14678`.)" -#: ../../whatsnew/3.10.rst:1546 +#: ../../whatsnew/3.10.rst:1547 msgid "Optimizations" msgstr "Otimizações" -#: ../../whatsnew/3.10.rst:1548 +#: ../../whatsnew/3.10.rst:1549 msgid "" "Constructors :func:`str`, :func:`bytes` and :func:`bytearray` are now faster " "(around 30--40% for small objects). (Contributed by Serhiy Storchaka in :" @@ -2543,7 +3218,7 @@ msgstr "" "mais rápido (cerca de 30--40% para objetos pequenos). (Contribuição de " "Serhiy Storchaka em :issue:`41334`.)" -#: ../../whatsnew/3.10.rst:1552 +#: ../../whatsnew/3.10.rst:1553 msgid "" "The :mod:`runpy` module now imports fewer modules. The ``python3 -m module-" "name`` command startup time is 1.4x faster in average. On Linux, ``python3 -" @@ -2557,7 +3232,7 @@ msgstr "" "que importa apenas 51 módulos (-18) no Python 3.10. (Contribuição de Victor " "Stinner em :issue:`41006` e :issue:`41718`.)" -#: ../../whatsnew/3.10.rst:1558 +#: ../../whatsnew/3.10.rst:1559 msgid "" "The ``LOAD_ATTR`` instruction now uses new \"per opcode cache\" mechanism. " "It is about 36% faster now for regular attributes and 44% faster for slots. " @@ -2571,7 +3246,7 @@ msgstr "" "`42093` e Guido van Rossum em :issue:`42927`, com base em ideias " "implementadas originalmente em PyPy e MicroPython.)" -#: ../../whatsnew/3.10.rst:1564 +#: ../../whatsnew/3.10.rst:1565 msgid "" "When building Python with :option:`--enable-optimizations` now ``-fno-" "semantic-interposition`` is added to both the compile and link line. This " @@ -2589,7 +3264,7 @@ msgstr "" "faster-python-3-8-run-speeds/>`_ para mais detalhes. (Contribuição de Victor " "Stinner e Pablo Galindo em :issue:`38980`.)" -#: ../../whatsnew/3.10.rst:1572 +#: ../../whatsnew/3.10.rst:1573 msgid "" "Use a new output buffer management code for :mod:`bz2` / :mod:`lzma` / :mod:" "`zlib` modules, and add ``.readall()`` function to ``_compression." @@ -2605,7 +3280,7 @@ msgstr "" "``GzipFile.read(-1)`` 1,11x ~ 1.18x mais rápida. (Contribuição de Ma Lin, " "revisada por Gregory P. Smith, em :issue:`41486`)" -#: ../../whatsnew/3.10.rst:1578 +#: ../../whatsnew/3.10.rst:1579 msgid "" "When using stringized annotations, annotations dicts for functions are no " "longer created when the function is created. Instead, they are stored as a " @@ -2621,7 +3296,7 @@ msgstr "" "necessário para definir uma função anotada. (Contribuição de Yurii Karabas e " "Inada Naoki em :issue:`42202`.)" -#: ../../whatsnew/3.10.rst:1585 +#: ../../whatsnew/3.10.rst:1586 msgid "" "Substring search functions such as ``str1 in str2`` and ``str2.find(str1)`` " "now sometimes use Crochemore & Perrin's \"Two-Way\" string searching " @@ -2633,7 +3308,7 @@ msgstr "" "Crochemore & Perrin para evitar comportamento quadrático em strings longas. " "(Contribuição de Dennis Sweeney em :issue:`41972`)" -#: ../../whatsnew/3.10.rst:1590 +#: ../../whatsnew/3.10.rst:1591 msgid "" "Add micro-optimizations to ``_PyType_Lookup()`` to improve type attribute " "cache lookup performance in the common case of cache hits. This makes the " @@ -2645,7 +3320,7 @@ msgstr "" "Isso torna o interpretador 1,04 vezes mais rápido, em média. (Contribuição " "de Dino Viehland em :issue:`43452`.)" -#: ../../whatsnew/3.10.rst:1594 +#: ../../whatsnew/3.10.rst:1595 msgid "" "The following built-in functions now support the faster :pep:`590` " "vectorcall calling convention: :func:`map`, :func:`filter`, :func:" @@ -2659,7 +3334,7 @@ msgstr "" "Donghee Na e Jeroen Demeyer em :issue:`43575`, :issue:`43287`, :issue:" "`41922`, :issue:`41873` e :issue:`41870`.)" -#: ../../whatsnew/3.10.rst:1598 +#: ../../whatsnew/3.10.rst:1599 msgid "" ":class:`~bz2.BZ2File` performance is improved by removing internal " "``RLock``. This makes :class:`!BZ2File` thread unsafe in the face of " @@ -2673,11 +3348,11 @@ msgstr "" "equivalentes em :mod:`gzip` e :mod:`lzma` têm sido. (Contribuição de Inada " "Naoki em :issue:`43785`.)" -#: ../../whatsnew/3.10.rst:1606 ../../whatsnew/3.10.rst:2212 +#: ../../whatsnew/3.10.rst:1607 ../../whatsnew/3.10.rst:2213 msgid "Deprecated" msgstr "Descontinuados" -#: ../../whatsnew/3.10.rst:1608 +#: ../../whatsnew/3.10.rst:1609 msgid "" "Currently Python accepts numeric literals immediately followed by keywords, " "for example ``0in x``, ``1or x``, ``0if 1else 2``. It allows confusing and " @@ -2700,7 +3375,7 @@ msgstr "" "e, finalmente, para erro de sintaxe. (Contribuição de Serhiy Storchaka em :" "issue:`43833`.)" -#: ../../whatsnew/3.10.rst:1619 +#: ../../whatsnew/3.10.rst:1620 msgid "" "Starting in this release, there will be a concerted effort to begin cleaning " "up old import semantics that were kept for Python 2.7 compatibility. " @@ -2730,7 +3405,7 @@ msgstr "" "levantada conforme apropriado para ajudar a identificar o código que precisa " "ser atualizado durante esta transição." -#: ../../whatsnew/3.10.rst:1636 +#: ../../whatsnew/3.10.rst:1637 msgid "" "The entire ``distutils`` namespace is deprecated, to be removed in Python " "3.12. Refer to the :ref:`module changes ` section for " @@ -2740,7 +3415,7 @@ msgstr "" "no Python 3.12. Consulte a seção de :ref:`alterações do módulo ` para mais informações." -#: ../../whatsnew/3.10.rst:1640 +#: ../../whatsnew/3.10.rst:1641 msgid "" "Non-integer arguments to :func:`random.randrange` are deprecated. The :exc:" "`ValueError` is deprecated in favor of a :exc:`TypeError`. (Contributed by " @@ -2751,7 +3426,7 @@ msgstr "" "`TypeError`. (Contribuição de Serhiy Storchaka e Raymond Hettinger em :issue:" "`37319`.)" -#: ../../whatsnew/3.10.rst:1644 +#: ../../whatsnew/3.10.rst:1645 msgid "" "The various ``load_module()`` methods of :mod:`importlib` have been " "documented as deprecated since Python 3.6, but will now also trigger a :exc:" @@ -2763,7 +3438,7 @@ msgstr "" "disparar um :exc:`DeprecationWarning`. Use :meth:`~importlib.abc.Loader." "exec_module` em vez disso. (Contribuição de Brett Cannon em :issue:`26131`.)" -#: ../../whatsnew/3.10.rst:1650 +#: ../../whatsnew/3.10.rst:1651 msgid "" ":meth:`!zimport.zipimporter.load_module` has been deprecated in preference " "for :meth:`~zipimport.zipimporter.exec_module`. (Contributed by Brett Cannon " @@ -2773,7 +3448,7 @@ msgstr "" "meth:`~zipimport.zipimporter.exec_module`. (Contribuição de Brett Cannon em :" "issue:`26131`.)" -#: ../../whatsnew/3.10.rst:1654 +#: ../../whatsnew/3.10.rst:1655 msgid "" "The use of :meth:`~importlib.abc.Loader.load_module` by the import system " "now triggers an :exc:`ImportWarning` as :meth:`~importlib.abc.Loader." @@ -2784,7 +3459,7 @@ msgstr "" "`~importlib.abc.Loader.exec_module` é preferível. (Contribuição de Brett " "Cannon em :issue:`26131`.)" -#: ../../whatsnew/3.10.rst:1659 +#: ../../whatsnew/3.10.rst:1660 msgid "" "The use of :meth:`!importlib.abc.MetaPathFinder.find_module` and :meth:`!" "importlib.abc.PathEntryFinder.find_module` by the import system now trigger " @@ -2801,7 +3476,7 @@ msgstr "" "spec_from_loader` para ajudar no port. (Contribuição de Brett Cannon em :" "issue:`42134`.)" -#: ../../whatsnew/3.10.rst:1668 +#: ../../whatsnew/3.10.rst:1669 msgid "" "The use of :meth:`!importlib.abc.PathEntryFinder.find_loader` by the import " "system now triggers an :exc:`ImportWarning` as :meth:`importlib.abc." @@ -2815,7 +3490,7 @@ msgstr "" "`importlib.util.spec_from_loader` para ajudar no port. (Contribuição de " "Brett Cannon em :issue:`43672`.)" -#: ../../whatsnew/3.10.rst:1674 +#: ../../whatsnew/3.10.rst:1675 msgid "" "The various implementations of :meth:`!importlib.abc.MetaPathFinder." "find_module` ( :meth:`!importlib.machinery.BuiltinImporter.find_module`, :" @@ -2842,7 +3517,7 @@ msgstr "" "descontinuados no Python 3.4). (Contribuição de Brett Cannon em :issue:" "`42135`.)" -#: ../../whatsnew/3.10.rst:1689 +#: ../../whatsnew/3.10.rst:1690 msgid "" ":class:`!importlib.abc.Finder` is deprecated (including its sole method, :" "meth:`!find_module`). Both :class:`importlib.abc.MetaPathFinder` and :class:" @@ -2856,7 +3531,7 @@ msgstr "" "devem herdar de uma dessas duas classes conforme apropriado. (Contribuição " "de Brett Cannon em :issue:`42135`.)" -#: ../../whatsnew/3.10.rst:1696 +#: ../../whatsnew/3.10.rst:1697 msgid "" "The deprecations of :mod:`!imp`, :func:`!importlib.find_loader`, :func:`!" "importlib.util.set_package_wrapper`, :func:`!importlib.util." @@ -2874,7 +3549,7 @@ msgstr "" "começaram a levantar :exc:`DeprecationWarning` em versões anteriores do " "Python). (Contribuição de Brett Cannon em :issue:`43720`.)" -#: ../../whatsnew/3.10.rst:1706 +#: ../../whatsnew/3.10.rst:1707 msgid "" "The import system now uses the ``__spec__`` attribute on modules before " "falling back on :meth:`!module_repr` for a module's ``__repr__()`` method. " @@ -2886,7 +3561,7 @@ msgstr "" "A remoção do uso de ``module_repr()`` está programado para Python 3.12. " "(Contribuição de Brett Cannon em :issue:`42137`.)" -#: ../../whatsnew/3.10.rst:1712 +#: ../../whatsnew/3.10.rst:1713 msgid "" ":meth:`!importlib.abc.Loader.module_repr`, :meth:`!importlib.machinery." "FrozenLoader.module_repr`, and :meth:`!importlib.machinery.BuiltinLoader." @@ -2898,7 +3573,7 @@ msgstr "" "module_repr` foram descontinuadas e programadas para remoção no Python 3.12. " "(Contribuição de Brett Cannon em :issue:`42136`.)" -#: ../../whatsnew/3.10.rst:1718 +#: ../../whatsnew/3.10.rst:1719 msgid "" "``sqlite3.OptimizedUnicode`` has been undocumented and obsolete since Python " "3.3, when it was made an alias to :class:`str`. It is now deprecated, " @@ -2910,7 +3585,7 @@ msgstr "" "`str`. Foi agora descontinuado, programado para remoção no Python 3.12. " "(Contribuição de Erlend E. Aasland em :issue:`42264`.)" -#: ../../whatsnew/3.10.rst:1723 +#: ../../whatsnew/3.10.rst:1724 msgid "" "The undocumented built-in function ``sqlite3.enable_shared_cache`` is now " "deprecated, scheduled for removal in Python 3.12. Its use is strongly " @@ -2927,49 +3602,49 @@ msgstr "" "usando o parâmetro de consulta ``cache=shared``. (Contribuição de Erlend E. " "Aasland em :issue:`24464`.)" -#: ../../whatsnew/3.10.rst:1731 +#: ../../whatsnew/3.10.rst:1732 msgid "The following ``threading`` methods are now deprecated:" msgstr "Os seguintes métodos de ``threading`` foram agora descontinuados:" -#: ../../whatsnew/3.10.rst:1733 +#: ../../whatsnew/3.10.rst:1734 msgid "``threading.currentThread`` => :func:`threading.current_thread`" msgstr "``threading.currentThread`` => :func:`threading.current_thread`" -#: ../../whatsnew/3.10.rst:1735 +#: ../../whatsnew/3.10.rst:1736 msgid "``threading.activeCount`` => :func:`threading.active_count`" msgstr "``threading.activeCount`` => :func:`threading.active_count`" -#: ../../whatsnew/3.10.rst:1737 +#: ../../whatsnew/3.10.rst:1738 msgid "" "``threading.Condition.notifyAll`` => :meth:`threading.Condition.notify_all`" msgstr "" "``threading.Condition.notifyAll`` => :meth:`threading.Condition.notify_all`" -#: ../../whatsnew/3.10.rst:1740 +#: ../../whatsnew/3.10.rst:1741 msgid "``threading.Event.isSet`` => :meth:`threading.Event.is_set`" msgstr "``threading.Event.isSet`` => :meth:`threading.Event.is_set`" -#: ../../whatsnew/3.10.rst:1742 +#: ../../whatsnew/3.10.rst:1743 msgid "``threading.Thread.setName`` => :attr:`threading.Thread.name`" msgstr "``threading.Thread.setName`` => :attr:`threading.Thread.name`" -#: ../../whatsnew/3.10.rst:1744 +#: ../../whatsnew/3.10.rst:1745 msgid "``threading.thread.getName`` => :attr:`threading.Thread.name`" msgstr "``threading.thread.getName`` => :attr:`threading.Thread.name`" -#: ../../whatsnew/3.10.rst:1746 +#: ../../whatsnew/3.10.rst:1747 msgid "``threading.Thread.isDaemon`` => :attr:`threading.Thread.daemon`" msgstr "``threading.Thread.isDaemon`` => :attr:`threading.Thread.daemon`" -#: ../../whatsnew/3.10.rst:1748 +#: ../../whatsnew/3.10.rst:1749 msgid "``threading.Thread.setDaemon`` => :attr:`threading.Thread.daemon`" msgstr "``threading.Thread.setDaemon`` => :attr:`threading.Thread.daemon`" -#: ../../whatsnew/3.10.rst:1750 +#: ../../whatsnew/3.10.rst:1751 msgid "(Contributed by Jelle Zijlstra in :gh:`87889`.)" msgstr "(Contribuição de Jelle Zijlstra em :gh:`87889`.)" -#: ../../whatsnew/3.10.rst:1752 +#: ../../whatsnew/3.10.rst:1753 msgid "" ":meth:`!pathlib.Path.link_to` is deprecated and slated for removal in Python " "3.12. Use :meth:`pathlib.Path.hardlink_to` instead. (Contributed by Barney " @@ -2979,7 +3654,7 @@ msgstr "" "Python 3.12. Use :meth:`pathlib.Path.hardlink_to` em vez disso. " "(Contribuição de Barney Gale em :issue:`39950`.)" -#: ../../whatsnew/3.10.rst:1756 +#: ../../whatsnew/3.10.rst:1757 msgid "" "``cgi.log()`` is deprecated and slated for removal in Python 3.12. " "(Contributed by Inada Naoki in :issue:`41139`.)" @@ -2987,7 +3662,7 @@ msgstr "" "``cgi.log()`` foi descontinuado e programado para remoção no Python 3.12. " "(Contribuição de Inada Naoki em :issue:`41139`.)" -#: ../../whatsnew/3.10.rst:1759 +#: ../../whatsnew/3.10.rst:1760 msgid "" "The following :mod:`ssl` features have been deprecated since Python 3.6, " "Python 3.7, or OpenSSL 1.1.0 and will be removed in 3.11:" @@ -2995,7 +3670,7 @@ msgstr "" "Os recurso a seguir do :mod:`ssl` foram descontinuados desde o Python 3.6, " "Python 3.7 ou OpenSSL 1.1.0, e serão removidos no 3.11:" -#: ../../whatsnew/3.10.rst:1762 +#: ../../whatsnew/3.10.rst:1763 msgid "" ":data:`!OP_NO_SSLv2`, :data:`!OP_NO_SSLv3`, :data:`!OP_NO_TLSv1`, :data:`!" "OP_NO_TLSv1_1`, :data:`!OP_NO_TLSv1_2`, and :data:`!OP_NO_TLSv1_3` are " @@ -3007,7 +3682,7 @@ msgstr "" "substituídos por :attr:`~ssl.SSLContext.minimum_version` e :attr:`~ssl." "SSLContext.maximum_version`." -#: ../../whatsnew/3.10.rst:1768 +#: ../../whatsnew/3.10.rst:1769 msgid "" ":data:`!PROTOCOL_SSLv2`, :data:`!PROTOCOL_SSLv3`, :data:`!PROTOCOL_SSLv23`, :" "data:`!PROTOCOL_TLSv1`, :data:`!PROTOCOL_TLSv1_1`, :data:`!" @@ -3019,20 +3694,20 @@ msgstr "" "e :const:`!PROTOCOL_TLS` foram descontinuados em favor de :const:`~ssl." "PROTOCOL_TLS_CLIENT` e :const:`~ssl.PROTOCOL_TLS_SERVER`" -#: ../../whatsnew/3.10.rst:1774 +#: ../../whatsnew/3.10.rst:1775 msgid ":func:`!wrap_socket` is replaced by :meth:`ssl.SSLContext.wrap_socket`" msgstr "" ":func:`!wrap_socket` foi substituída por :meth:`ssl.SSLContext.wrap_socket`" -#: ../../whatsnew/3.10.rst:1776 +#: ../../whatsnew/3.10.rst:1777 msgid ":func:`!match_hostname`" msgstr ":func:`!match_hostname`" -#: ../../whatsnew/3.10.rst:1778 +#: ../../whatsnew/3.10.rst:1779 msgid ":func:`!RAND_pseudo_bytes`, :func:`!RAND_egd`" msgstr ":func:`!RAND_pseudo_bytes`, :func:`!RAND_egd`" -#: ../../whatsnew/3.10.rst:1780 +#: ../../whatsnew/3.10.rst:1781 msgid "" "NPN features like :meth:`ssl.SSLSocket.selected_npn_protocol` and :meth:`ssl." "SSLContext.set_npn_protocols` are replaced by ALPN." @@ -3040,7 +3715,7 @@ msgstr "" "Recurso de NPN como :meth:`ssl.SSLSocket.selected_npn_protocol` e :meth:`ssl." "SSLContext.set_npn_protocols` foram substituídos por ALPN." -#: ../../whatsnew/3.10.rst:1783 +#: ../../whatsnew/3.10.rst:1784 msgid "" "The threading debug (:envvar:`!PYTHONTHREADDEBUG` environment variable) is " "deprecated in Python 3.10 and will be removed in Python 3.12. This feature " @@ -3052,7 +3727,7 @@ msgstr "" "recurso exige uma :ref:`construção de depuração de Python `. " "(Contribuição de Victor Stinner em :issue:`44584`.)" -#: ../../whatsnew/3.10.rst:1788 +#: ../../whatsnew/3.10.rst:1789 msgid "" "Importing from the ``typing.io`` and ``typing.re`` submodules will now emit :" "exc:`DeprecationWarning`. These submodules will be removed in a future " @@ -3066,11 +3741,11 @@ msgstr "" "diretamente de :mod:`typing`. (Contribuição de Sebastian Rittau em :issue:" "`38291`.)" -#: ../../whatsnew/3.10.rst:1797 ../../whatsnew/3.10.rst:2220 +#: ../../whatsnew/3.10.rst:1798 ../../whatsnew/3.10.rst:2221 msgid "Removed" msgstr "Removidos" -#: ../../whatsnew/3.10.rst:1799 +#: ../../whatsnew/3.10.rst:1800 msgid "" "Removed special methods ``__int__``, ``__float__``, ``__floordiv__``, " "``__mod__``, ``__divmod__``, ``__rfloordiv__``, ``__rmod__`` and " @@ -3083,7 +3758,7 @@ msgstr "" "exceção :exc:`TypeError`. (Contribuição de Serhiy Storchaka em :issue:" "`41974`.)" -#: ../../whatsnew/3.10.rst:1805 +#: ../../whatsnew/3.10.rst:1806 msgid "" "The ``ParserBase.error()`` method from the private and undocumented " "``_markupbase`` module has been removed. :class:`html.parser.HTMLParser` is " @@ -3096,7 +3771,7 @@ msgstr "" "subclasse de ``ParserBase`` e sua implementação de ``error()`` já tinha sido " "removida no Python 3.5. (Contribuição de Berker Peksag em :issue:`31844`.)" -#: ../../whatsnew/3.10.rst:1811 +#: ../../whatsnew/3.10.rst:1812 msgid "" "Removed the ``unicodedata.ucnhash_CAPI`` attribute which was an internal " "PyCapsule object. The related private ``_PyUnicode_Name_CAPI`` structure was " @@ -3108,7 +3783,7 @@ msgstr "" "movida para uma API C interna. (Contribuição de Victor Stinner em :issue:" "`42157`.)" -#: ../../whatsnew/3.10.rst:1816 +#: ../../whatsnew/3.10.rst:1817 msgid "" "Removed the ``parser`` module, which was deprecated in 3.9 due to the switch " "to the new PEG parser, as well as all the C source and header files that " @@ -3121,7 +3796,7 @@ msgstr "" "sintático antigo, incluindo ``node.h``, ``parser.h``, ``graminit.h`` e " "``grammar.h``." -#: ../../whatsnew/3.10.rst:1821 +#: ../../whatsnew/3.10.rst:1822 msgid "" "Removed the Public C API functions ``PyParser_SimpleParseStringFlags``, " "``PyParser_SimpleParseStringFlagsFilename``, " @@ -3134,7 +3809,7 @@ msgstr "" "descontinuadas no 3.9 em razão da mudança para o novo analisador sintático " "GASE." -#: ../../whatsnew/3.10.rst:1826 +#: ../../whatsnew/3.10.rst:1827 msgid "" "Removed the ``formatter`` module, which was deprecated in Python 3.4. It is " "somewhat obsolete, little used, and not tested. It was originally scheduled " @@ -3149,7 +3824,7 @@ msgstr "" "classes que usam em seu código. (Contribuição de Dong-hee Na e Terry J. " "Reedy em :issue:`42299`.)" -#: ../../whatsnew/3.10.rst:1833 +#: ../../whatsnew/3.10.rst:1834 msgid "" "Removed the :c:func:`!PyModule_GetWarningsModule` function that was useless " "now due to the :mod:`!_warnings` module was converted to a builtin module in " @@ -3159,7 +3834,7 @@ msgstr "" "porque o módulo :mod:`!_warnings` foi convertido em um módulo embutido no " "2.6. (Contribuição de Hai Shi em :issue:`42599`.)" -#: ../../whatsnew/3.10.rst:1837 +#: ../../whatsnew/3.10.rst:1838 msgid "" "Remove deprecated aliases to :ref:`collections-abstract-base-classes` from " "the :mod:`collections` module. (Contributed by Victor Stinner in :issue:" @@ -3169,7 +3844,7 @@ msgstr "" "do módulo :mod:`collections`. (Contribuição de Victor Stinner em :issue:" "`37324`.)" -#: ../../whatsnew/3.10.rst:1841 +#: ../../whatsnew/3.10.rst:1842 msgid "" "The ``loop`` parameter has been removed from most of :mod:`asyncio`\\ 's :" "doc:`high-level API <../library/asyncio-api-index>` following deprecation in " @@ -3179,11 +3854,11 @@ msgstr "" "library/asyncio-api-index>` do :mod:`asyncio` seguindo a descontinuidade no " "Python 3.8. A motivação por trás desta alteração é multifacetada:" -#: ../../whatsnew/3.10.rst:1845 +#: ../../whatsnew/3.10.rst:1846 msgid "This simplifies the high-level API." msgstr "Isso simplifica a API de alto nível." -#: ../../whatsnew/3.10.rst:1846 +#: ../../whatsnew/3.10.rst:1847 msgid "" "The functions in the high-level API have been implicitly getting the current " "thread's running event loop since Python 3.7. There isn't a need to pass " @@ -3193,7 +3868,7 @@ msgstr "" "execução do thread atual desde o Python 3.7. Não há necessidade de passar o " "laço de eventos para a API na maioria dos casos de uso normais." -#: ../../whatsnew/3.10.rst:1849 +#: ../../whatsnew/3.10.rst:1850 msgid "" "Event loop passing is error-prone especially when dealing with loops running " "in different threads." @@ -3201,7 +3876,7 @@ msgstr "" "A passagem de laço de eventos está sujeita a erros, especialmente ao lidar " "com laços em execução em diferentes threads." -#: ../../whatsnew/3.10.rst:1852 +#: ../../whatsnew/3.10.rst:1853 msgid "" "Note that the low-level API will still accept ``loop``. See :ref:`changes-" "python-api` for examples of how to replace existing code." @@ -3209,7 +3884,7 @@ msgstr "" "Observe que a API de baixo nível ainda aceitará ``loop``. Veja :ref:`changes-" "python-api` para exemplos de como substituir o código existente." -#: ../../whatsnew/3.10.rst:1855 ../../whatsnew/3.10.rst:1927 +#: ../../whatsnew/3.10.rst:1856 ../../whatsnew/3.10.rst:1928 msgid "" "(Contributed by Yurii Karabas, Andrew Svetlov, Yury Selivanov and Kyle " "Stanley in :issue:`42392`.)" @@ -3217,11 +3892,11 @@ msgstr "" "(Contribuição de Yurii Karabas, Andrew Svetlov, Yury Selivanov e Kyle " "Stanley em :issue:`42392`.)" -#: ../../whatsnew/3.10.rst:1860 ../../whatsnew/3.10.rst:2147 +#: ../../whatsnew/3.10.rst:1861 ../../whatsnew/3.10.rst:2148 msgid "Porting to Python 3.10" msgstr "Portando para Python 3.10" -#: ../../whatsnew/3.10.rst:1862 +#: ../../whatsnew/3.10.rst:1863 msgid "" "This section lists previously described changes and other bugfixes that may " "require changes to your code." @@ -3229,11 +3904,11 @@ msgstr "" "Esta seção lista as alterações descritas anteriormente e outras correções " "que podem exigir alterações no seu código." -#: ../../whatsnew/3.10.rst:1867 +#: ../../whatsnew/3.10.rst:1868 msgid "Changes in the Python syntax" msgstr "Alterações na sintaxe Python" -#: ../../whatsnew/3.10.rst:1869 +#: ../../whatsnew/3.10.rst:1870 msgid "" "Deprecation warning is now emitted when compiling previously valid syntax if " "the numeric literal is immediately followed by a keyword (like in ``0in " @@ -3250,11 +3925,11 @@ msgstr "" "um espaço entre o literal numérico e a palavra reservada seguinte. " "(Contribuição de Serhiy Storchaka em :issue:`43833`.)" -#: ../../whatsnew/3.10.rst:1880 +#: ../../whatsnew/3.10.rst:1881 msgid "Changes in the Python API" msgstr "Alterações na API Python" -#: ../../whatsnew/3.10.rst:1882 +#: ../../whatsnew/3.10.rst:1883 msgid "" "The *etype* parameters of the :func:`~traceback.format_exception`, :func:" "`~traceback.format_exception_only`, and :func:`~traceback.print_exception` " @@ -3266,20 +3941,20 @@ msgstr "" "módulo :mod:`traceback` foram renomeadas para *exc*. (Contribuição de " "Zackery Spytz e Matthias Bussonnier em :issue:`26389`.)" -#: ../../whatsnew/3.10.rst:1888 +#: ../../whatsnew/3.10.rst:1889 msgid "" ":mod:`atexit`: At Python exit, if a callback registered with :func:`atexit." "register` fails, its exception is now logged. Previously, only some " "exceptions were logged, and the last exception was always silently ignored. " "(Contributed by Victor Stinner in :issue:`42639`.)" msgstr "" -":mod:`atexit`: Ao sair do Python, se uma função de retorno registrada com :" +":mod:`atexit`: ao sair do Python, se uma função de retorno registrada com :" "func:`atexit.register` falhar, sua exceção agora é registrada nos logs. " "Anteriormente, apenas algumas exceções eram registradas nos logs e a última " "exceção era sempre ignorada silenciosamente. (Contribuição de Victor Stinner " "em :issue:`42639`.)" -#: ../../whatsnew/3.10.rst:1894 +#: ../../whatsnew/3.10.rst:1895 msgid "" ":class:`collections.abc.Callable` generic now flattens type parameters, " "similar to what :data:`typing.Callable` currently does. This means that " @@ -3301,7 +3976,7 @@ msgstr "" "class:`Collections.abc.Callable` que pode ter passada silenciosamente no " "Python 3.9. (Contribuição de Ken Jin em :issue:`42195`.)" -#: ../../whatsnew/3.10.rst:1904 +#: ../../whatsnew/3.10.rst:1905 msgid "" ":meth:`socket.htons` and :meth:`socket.ntohs` now raise :exc:`OverflowError` " "instead of :exc:`DeprecationWarning` if the given parameter will not fit in " @@ -3313,7 +3988,7 @@ msgstr "" "couber em um inteiro sem sinal de 16 bits. (Contribuição de Erlend E. " "Aasland em :issue:`42393`.)" -#: ../../whatsnew/3.10.rst:1909 +#: ../../whatsnew/3.10.rst:1910 msgid "" "The ``loop`` parameter has been removed from most of :mod:`asyncio`\\ 's :" "doc:`high-level API <../library/asyncio-api-index>` following deprecation in " @@ -3323,15 +3998,31 @@ msgstr "" "library/asyncio-api-index>` do :mod:`asyncio` seguindo a descontinuidade no " "Python 3.8." -#: ../../whatsnew/3.10.rst:1913 +#: ../../whatsnew/3.10.rst:1914 msgid "A coroutine that currently looks like this::" msgstr "A corrotina que atualmente se parece com isso::" -#: ../../whatsnew/3.10.rst:1918 +#: ../../whatsnew/3.10.rst:1916 +msgid "" +"async def foo(loop):\n" +" await asyncio.sleep(1, loop=loop)" +msgstr "" +"async def foo(loop):\n" +" await asyncio.sleep(1, loop=loop)" + +#: ../../whatsnew/3.10.rst:1919 msgid "Should be replaced with this::" msgstr "Deve ser substituída por isso::" -#: ../../whatsnew/3.10.rst:1923 +#: ../../whatsnew/3.10.rst:1921 +msgid "" +"async def foo():\n" +" await asyncio.sleep(1)" +msgstr "" +"async def foo():\n" +" await asyncio.sleep(1)" + +#: ../../whatsnew/3.10.rst:1924 msgid "" "If ``foo()`` was specifically designed *not* to run in the current thread's " "running event loop (e.g. running in another thread's event loop), consider " @@ -3342,7 +4033,7 @@ msgstr "" "eventos de outra thread), considere usar :func:`asyncio." "run_coroutine_threadsafe`." -#: ../../whatsnew/3.10.rst:1930 +#: ../../whatsnew/3.10.rst:1931 msgid "" "The :data:`types.FunctionType` constructor now inherits the current builtins " "if the *globals* dictionary has no ``\"__builtins__\"`` key, rather than " @@ -3360,11 +4051,11 @@ msgstr "" "substituídos com esta sintaxe: também herda os embutidos atuais. " "(Contribuição de Victor Stinner em :issue:`42990`.)" -#: ../../whatsnew/3.10.rst:1939 +#: ../../whatsnew/3.10.rst:1940 msgid "Changes in the C API" msgstr "Alterações na API C" -#: ../../whatsnew/3.10.rst:1941 +#: ../../whatsnew/3.10.rst:1942 msgid "" "The C API functions ``PyParser_SimpleParseStringFlags``, " "``PyParser_SimpleParseStringFlagsFilename``, " @@ -3378,30 +4069,29 @@ msgstr "" "essas funções, ``struct _node``, foram removidos em razão da mudança para o " "novo analisador sintático GASE." -#: ../../whatsnew/3.10.rst:1947 +#: ../../whatsnew/3.10.rst:1948 msgid "" "Source should be now be compiled directly to a code object using, for " "example, :c:func:`Py_CompileString`. The resulting code object can then be " "evaluated using, for example, :c:func:`PyEval_EvalCode`." msgstr "" -"O código-fonte deveria agora ser compilado diretamente para um objeto código " +"O código-fonte deve ser agora compilado diretamente para um objeto código " "usando, por exemplo, :c:func:`Py_CompileString`. O objeto código resultante " "pode ser então avaliado usando, por exemplo, :c:func:`PyEval_EvalCode`." -#: ../../whatsnew/3.10.rst:1951 +#: ../../whatsnew/3.10.rst:1952 msgid "Specifically:" msgstr "Especificamente:" -#: ../../whatsnew/3.10.rst:1953 +#: ../../whatsnew/3.10.rst:1954 msgid "" "A call to ``PyParser_SimpleParseStringFlags`` followed by ``PyNode_Compile`` " "can be replaced by calling :c:func:`Py_CompileString`." msgstr "" "Uma chamada para ``PyParser_SimpleParseStringFlags`` seguida por " -"``PyNode_Compile`` pode ser substituída por chamar :c:func:" -"`Py_CompileString`." +"``PyNode_Compile`` pode ser substituída por :c:func:`Py_CompileString`." -#: ../../whatsnew/3.10.rst:1956 +#: ../../whatsnew/3.10.rst:1957 msgid "" "There is no direct replacement for ``PyParser_SimpleParseFileFlags``. To " "compile code from a ``FILE *`` argument, you will need to read the file in C " @@ -3411,7 +4101,7 @@ msgstr "" "compilar código de um argumento ``FILE *``, você vai precisar ler o arquivo " "em C e passar o buffer resultante para :c:func:`Py_CompileString`." -#: ../../whatsnew/3.10.rst:1960 +#: ../../whatsnew/3.10.rst:1961 msgid "" "To compile a file given a ``char *`` filename, explicitly open the file, " "read it and compile the result. One way to do this is using the :py:mod:`io` " @@ -3426,7 +4116,25 @@ msgstr "" "`Py_CompileString`, como esboçado abaixo. (Declarações e tratamento de erro " "foram omitidos.) ::" -#: ../../whatsnew/3.10.rst:1973 +#: ../../whatsnew/3.10.rst:1967 +msgid "" +"io_module = Import_ImportModule(\"io\");\n" +"fileobject = PyObject_CallMethod(io_module, \"open\", \"ss\", filename, " +"\"rb\");\n" +"source_bytes_object = PyObject_CallMethod(fileobject, \"read\", \"\");\n" +"result = PyObject_CallMethod(fileobject, \"close\", \"\");\n" +"source_buf = PyBytes_AsString(source_bytes_object);\n" +"code = Py_CompileString(source_buf, filename, Py_file_input);" +msgstr "" +"io_module = Import_ImportModule(\"io\");\n" +"fileobject = PyObject_CallMethod(io_module, \"open\", \"ss\", filename, " +"\"rb\");\n" +"source_bytes_object = PyObject_CallMethod(fileobject, \"read\", \"\");\n" +"result = PyObject_CallMethod(fileobject, \"close\", \"\");\n" +"source_buf = PyBytes_AsString(source_bytes_object);\n" +"code = Py_CompileString(source_buf, filename, Py_file_input);" + +#: ../../whatsnew/3.10.rst:1974 msgid "" "For ``FrameObject`` objects, the :attr:`~frame.f_lasti` member now " "represents a wordcode offset instead of a simple offset into the bytecode " @@ -3444,11 +4152,11 @@ msgstr "" "membro :attr:`!f_lasti` de objetos ``FrameObject`` não é considerado " "estável: por favor, use :c:func:`PyFrame_GetLineNumber` em vez disso." -#: ../../whatsnew/3.10.rst:1981 +#: ../../whatsnew/3.10.rst:1982 msgid "CPython bytecode changes" msgstr "Alterações de bytecode do CPython" -#: ../../whatsnew/3.10.rst:1983 +#: ../../whatsnew/3.10.rst:1984 msgid "" "The ``MAKE_FUNCTION`` instruction now accepts either a dict or a tuple of " "strings as the function's annotations. (Contributed by Yurii Karabas and " @@ -3458,11 +4166,11 @@ msgstr "" "strings como as anotações da função. (Contribuição de Yurii Karabas e Inada " "Naoki em :issue:`42202`.)" -#: ../../whatsnew/3.10.rst:1988 +#: ../../whatsnew/3.10.rst:1989 msgid "Build Changes" -msgstr "Alterações de construção" +msgstr "Mudanças na construção" -#: ../../whatsnew/3.10.rst:1990 +#: ../../whatsnew/3.10.rst:1991 msgid "" ":pep:`644`: Python now requires OpenSSL 1.1.1 or newer. OpenSSL 1.0.2 is no " "longer supported. (Contributed by Christian Heimes in :issue:`43669`.)" @@ -3470,7 +4178,7 @@ msgstr "" ":pep:`644`: Python agora exige OpenSSL 1.1.1 ou mais novo. OpenSSL 1.0.2 não " "é mais suportado. (Contribuição de Christian Heimes em :issue:`43669`.)" -#: ../../whatsnew/3.10.rst:1994 +#: ../../whatsnew/3.10.rst:1995 msgid "" "The C99 functions :c:func:`snprintf` and :c:func:`vsnprintf` are now " "required to build Python. (Contributed by Victor Stinner in :issue:`36020`.)" @@ -3478,7 +4186,7 @@ msgstr "" "As funções C99 :c:func:`snprintf` e :c:func:`vsnprintf` agora são exigidas " "para compilar o Python. (Contribuição de Victor Stinner em :issue:`36020`.)" -#: ../../whatsnew/3.10.rst:1998 +#: ../../whatsnew/3.10.rst:1999 msgid "" ":mod:`sqlite3` requires SQLite 3.7.15 or higher. (Contributed by Sergey " "Fedoseev and Erlend E. Aasland in :issue:`40744` and :issue:`40810`.)" @@ -3486,7 +4194,7 @@ msgstr "" ":mod:`sqlite3` exige SQLite 3.7.15 ou superior. (Contribuição de Sergey " "Fedoseev e Erlend E. Aasland em :issue:`40744` e :issue:`40810`.)" -#: ../../whatsnew/3.10.rst:2001 +#: ../../whatsnew/3.10.rst:2002 msgid "" "The :mod:`atexit` module must now always be built as a built-in module. " "(Contributed by Victor Stinner in :issue:`42639`.)" @@ -3494,7 +4202,7 @@ msgstr "" "O módulo :mod:`atexit` deve agora sempre ser construído como um módulo " "embutido. (Contribuição de Victor Stinner em :issue:`42639`.)" -#: ../../whatsnew/3.10.rst:2004 +#: ../../whatsnew/3.10.rst:2005 msgid "" "Add :option:`--disable-test-modules` option to the ``configure`` script: " "don't build nor install test modules. (Contributed by Xavier de Gaye, Thomas " @@ -3504,7 +4212,7 @@ msgstr "" "não constrói nem instala módulos de teste. (Contribuição de Xavier de Gaye, " "Thomas Petazzoni e Peixing Xin em :issue:`27640`.)" -#: ../../whatsnew/3.10.rst:2008 +#: ../../whatsnew/3.10.rst:2009 msgid "" "Add :option:`--with-wheel-pkg-dir=PATH option <--with-wheel-pkg-dir>` to the " "``./configure`` script. If specified, the :mod:`ensurepip` module looks for " @@ -3518,7 +4226,7 @@ msgstr "" "ambos estiverem presentes, esses pacotes wheel são usados em vez de pacotes " "wheel empacotados por ensurepip." -#: ../../whatsnew/3.10.rst:2014 +#: ../../whatsnew/3.10.rst:2015 msgid "" "Some Linux distribution packaging policies recommend against bundling " "dependencies. For example, Fedora installs wheel packages in the ``/usr/" @@ -3530,11 +4238,11 @@ msgstr "" "wheel no diretório ``/usr/share/python-wheels/`` e não instala o pacote " "``ensurepip._bundled``." -#: ../../whatsnew/3.10.rst:2019 +#: ../../whatsnew/3.10.rst:2020 msgid "(Contributed by Victor Stinner in :issue:`42856`.)" msgstr "(Contribuição de Victor Stinner em :issue:`42856`.)" -#: ../../whatsnew/3.10.rst:2021 +#: ../../whatsnew/3.10.rst:2022 msgid "" "Add a new :option:`configure --without-static-libpython option <--without-" "static-libpython>` to not build the ``libpythonMAJOR.MINOR.a`` static " @@ -3544,11 +4252,11 @@ msgstr "" "without-static-libpython>` para não construir biblioteca estática " "``libpythonMAJOR.MINOR.a`` e não instala o arquivo objeto ``python.o``." -#: ../../whatsnew/3.10.rst:2025 +#: ../../whatsnew/3.10.rst:2026 msgid "(Contributed by Victor Stinner in :issue:`43103`.)" msgstr "(Contribuição de Victor Stinner em :issue:`43103`.)" -#: ../../whatsnew/3.10.rst:2027 +#: ../../whatsnew/3.10.rst:2028 msgid "" "The ``configure`` script now uses the ``pkg-config`` utility, if available, " "to detect the location of Tcl/Tk headers and libraries. As before, those " @@ -3562,7 +4270,7 @@ msgstr "" "configuração ``--with-tcltk-includes`` e ``--with-tcltk-libs`` . " "(Contribuição de Manolis Stamatogiannakis em :issue:`42603`.)" -#: ../../whatsnew/3.10.rst:2033 +#: ../../whatsnew/3.10.rst:2034 msgid "" "Add :option:`--with-openssl-rpath` option to ``configure`` script. The " "option simplifies building Python with a custom OpenSSL installation, e.g. " @@ -3575,15 +4283,15 @@ msgstr "" "with-openssl-rpath=auto``. (Contribuição de Christian Heimes em :issue:" "`43466`.)" -#: ../../whatsnew/3.10.rst:2040 +#: ../../whatsnew/3.10.rst:2041 msgid "C API Changes" msgstr "Alterações na API C" -#: ../../whatsnew/3.10.rst:2043 +#: ../../whatsnew/3.10.rst:2044 msgid "PEP 652: Maintaining the Stable ABI" msgstr "PEP 652: Mantendo a ABI estável" -#: ../../whatsnew/3.10.rst:2045 +#: ../../whatsnew/3.10.rst:2046 msgid "" "The Stable ABI (Application Binary Interface) for extension modules or " "embedding Python is now explicitly defined. :ref:`stable` describes C API " @@ -3595,11 +4303,11 @@ msgstr "" "as garantias de estabilidade da API C e ABI junto com as melhores práticas " "para usar a ABI estável." -#: ../../whatsnew/3.10.rst:2050 +#: ../../whatsnew/3.10.rst:2051 msgid "(Contributed by Petr Viktorin in :pep:`652` and :issue:`43795`.)" msgstr "(Contribuição de Petr Viktorin em :pep:`652` e :issue:`43795`.)" -#: ../../whatsnew/3.10.rst:2055 +#: ../../whatsnew/3.10.rst:2056 msgid "" "The result of :c:func:`PyNumber_Index` now always has exact type :class:" "`int`. Previously, the result could have been an instance of a subclass of " @@ -3609,7 +4317,7 @@ msgstr "" "`int`. Anteriormente, o resultado poderia ser uma instância de uma subclasse " "de ``int``. (Contribuição de Serhiy Storchaka em :issue:`40792`.)" -#: ../../whatsnew/3.10.rst:2059 +#: ../../whatsnew/3.10.rst:2060 msgid "" "Add a new :c:member:`~PyConfig.orig_argv` member to the :c:type:`PyConfig` " "structure: the list of the original command line arguments passed to the " @@ -3619,7 +4327,7 @@ msgstr "" "`PyConfig`: a lista dos argumentos originais da linha de comando passados " "para o executável Python. (Contribuição de Victor Stinner em :issue:`23427`.)" -#: ../../whatsnew/3.10.rst:2064 +#: ../../whatsnew/3.10.rst:2065 msgid "" "The :c:func:`PyDateTime_DATE_GET_TZINFO` and :c:func:" "`PyDateTime_TIME_GET_TZINFO` macros have been added for accessing the " @@ -3631,7 +4339,7 @@ msgstr "" "``tzinfo`` dos objetos :class:`datetime.datetime` e :class:`datetime.time`. " "(Contribuição de Zackery Spytz em :issue:`30155`.)" -#: ../../whatsnew/3.10.rst:2070 +#: ../../whatsnew/3.10.rst:2071 msgid "" "Add a :c:func:`PyCodec_Unregister` function to unregister a codec search " "function. (Contributed by Hai Shi in :issue:`41842`.)" @@ -3640,7 +4348,7 @@ msgstr "" "de uma função de pesquisa de codecs. (Contribuição de Hai Shi em :issue:" "`41842`.)" -#: ../../whatsnew/3.10.rst:2074 +#: ../../whatsnew/3.10.rst:2075 msgid "" "The :c:func:`PyIter_Send` function was added to allow sending value into " "iterator without raising ``StopIteration`` exception. (Contributed by " @@ -3650,7 +4358,7 @@ msgstr "" "para o iterador sem levantar a exceção ``StopIteration``. (Contribuição de " "Vladimir Matveev em :issue:`41756`.)" -#: ../../whatsnew/3.10.rst:2078 +#: ../../whatsnew/3.10.rst:2079 msgid "" "Add :c:func:`PyUnicode_AsUTF8AndSize` to the limited C API. (Contributed by " "Alex Gaynor in :issue:`41784`.)" @@ -3658,7 +4366,7 @@ msgstr "" "Adiciona :c:func:`PyUnicode_AsUTF8AndSize` à API C limitada. (Contribuição " "de Alex Gaynor em :issue:`41784`.)" -#: ../../whatsnew/3.10.rst:2081 +#: ../../whatsnew/3.10.rst:2082 msgid "" "Add :c:func:`PyModule_AddObjectRef` function: similar to :c:func:" "`PyModule_AddObject` but don't steal a reference to the value on success. " @@ -3668,7 +4376,7 @@ msgstr "" "`PyModule_AddObject`, mas não roube uma referência ao valor em caso de " "sucesso. (Contribuição de Victor Stinner em :issue:`1635741`.)" -#: ../../whatsnew/3.10.rst:2086 +#: ../../whatsnew/3.10.rst:2087 msgid "" "Add :c:func:`Py_NewRef` and :c:func:`Py_XNewRef` functions to increment the " "reference count of an object and return the object. (Contributed by Victor " @@ -3678,7 +4386,7 @@ msgstr "" "incrementar a contagem de referências de um objeto e retornar o objeto. " "(Contribuição de Victor Stinner em :issue:`42262`.)" -#: ../../whatsnew/3.10.rst:2090 +#: ../../whatsnew/3.10.rst:2091 msgid "" "The :c:func:`PyType_FromSpecWithBases` and :c:func:" "`PyType_FromModuleAndSpec` functions now accept a single class as the " @@ -3688,7 +4396,7 @@ msgstr "" "`PyType_FromModuleAndSpec` agora aceitam uma única classe como o argumento " "*bases*. (Contribuição de Serhiy Storchaka em :issue:`42423`.)" -#: ../../whatsnew/3.10.rst:2094 +#: ../../whatsnew/3.10.rst:2095 msgid "" "The :c:func:`PyType_FromModuleAndSpec` function now accepts NULL ``tp_doc`` " "slot. (Contributed by Hai Shi in :issue:`41832`.)" @@ -3696,7 +4404,7 @@ msgstr "" "A função :c:func:`PyType_FromModuleAndSpec` agora aceita o slot NULL " "``tp_doc``. (Contribuição de Hai Shi em :issue:`41832`.)" -#: ../../whatsnew/3.10.rst:2098 +#: ../../whatsnew/3.10.rst:2099 msgid "" "The :c:func:`PyType_GetSlot` function can accept :ref:`static types `. (Contributed by Hai Shi and Petr Viktorin in :issue:`41073`.)" @@ -3704,7 +4412,7 @@ msgstr "" "A função :c:func:`PyType_GetSlot` pode aceitar :ref:`tipos estáticos `. (Contribuição de Hai Shi e Petr Viktorin em :issue:`41073`.)" -#: ../../whatsnew/3.10.rst:2102 +#: ../../whatsnew/3.10.rst:2103 msgid "" "Add a new :c:func:`PySet_CheckExact` function to the C-API to check if an " "object is an instance of :class:`set` but not an instance of a subtype. " @@ -3714,7 +4422,7 @@ msgstr "" "se um objeto é uma instância de :class:`set`, mas não uma instância de um " "subtipo. (Contribuição de Pablo Galindo em :issue:`43277`.)" -#: ../../whatsnew/3.10.rst:2106 +#: ../../whatsnew/3.10.rst:2107 msgid "" "Add :c:func:`PyErr_SetInterruptEx` which allows passing a signal number to " "simulate. (Contributed by Antoine Pitrou in :issue:`43356`.)" @@ -3722,7 +4430,7 @@ msgstr "" "Adiciona :c:func:`PyErr_SetInterruptEx` que permite passar um número de " "sinal para simular. (Contribuição de Antoine Pitrou em :issue:`43356`.)" -#: ../../whatsnew/3.10.rst:2110 +#: ../../whatsnew/3.10.rst:2111 msgid "" "The limited C API is now supported if :ref:`Python is built in debug mode " "` (if the ``Py_DEBUG`` macro is defined). In the limited C API, " @@ -3744,7 +4452,7 @@ msgstr "" "no modo de depuração porque a estrutura :c:type:`PyObject` é a mesma no modo " "de lançamento e depuração desde o Python 3.8 (consulte :issue:`36465`)." -#: ../../whatsnew/3.10.rst:2120 +#: ../../whatsnew/3.10.rst:2121 msgid "" "The limited C API is still not supported in the :option:`--with-trace-refs` " "special build (``Py_TRACE_REFS`` macro). (Contributed by Victor Stinner in :" @@ -3754,7 +4462,7 @@ msgstr "" "with-trace-refs` (macro ``Py_TRACE_REFS``). (Contribuição de Victor Stinner " "em :issue:`43688`.)" -#: ../../whatsnew/3.10.rst:2124 +#: ../../whatsnew/3.10.rst:2125 msgid "" "Add the :c:func:`Py_Is(x, y) ` function to test if the *x* object is " "the *y* object, the same as ``x is y`` in Python. Add also the :c:func:" @@ -3770,7 +4478,7 @@ msgstr "" "``True`` ou o singleton ``False``. (Contribuição de Victor Stinner em :issue:" "`43753`.)" -#: ../../whatsnew/3.10.rst:2131 +#: ../../whatsnew/3.10.rst:2132 msgid "" "Add new functions to control the garbage collector from C code: :c:func:" "`PyGC_Enable()`, :c:func:`PyGC_Disable()`, :c:func:`PyGC_IsEnabled()`. These " @@ -3782,7 +4490,7 @@ msgstr "" "funções permitem ativar, desativar e consultar o estado do coletor de lixo " "do código C sem precisar importar o módulo :mod:`gc`." -#: ../../whatsnew/3.10.rst:2138 +#: ../../whatsnew/3.10.rst:2139 msgid "" "Add a new :c:macro:`Py_TPFLAGS_DISALLOW_INSTANTIATION` type flag to disallow " "creating type instances. (Contributed by Victor Stinner in :issue:`43916`.)" @@ -3791,7 +4499,7 @@ msgstr "" "`Py_TPFLAGS_DISALLOW_INSTANTIATION` para impedir a criação de instâncias de " "tipo. (Contribuição de Victor Stinner em :issue:`43916`.)" -#: ../../whatsnew/3.10.rst:2142 +#: ../../whatsnew/3.10.rst:2143 msgid "" "Add a new :c:macro:`Py_TPFLAGS_IMMUTABLETYPE` type flag for creating " "immutable type objects: type attributes cannot be set nor deleted. " @@ -3802,7 +4510,7 @@ msgstr "" "definidos nem excluídos. (Contribuição de Victor Stinner e Erlend E. Aasland " "em :issue:`43908`.)" -#: ../../whatsnew/3.10.rst:2149 +#: ../../whatsnew/3.10.rst:2150 msgid "" "The ``PY_SSIZE_T_CLEAN`` macro must now be defined to use :c:func:" "`PyArg_ParseTuple` and :c:func:`Py_BuildValue` formats which use ``#``: " @@ -3815,7 +4523,7 @@ msgstr "" "``et#``, ``s#``, ``u#``, ``y#``, ``z#``, ``U#`` e ``Z#``. Veja :ref:`arg-" "parsing` e :pep:`353`. (Contribuição de Victor Stinner em :issue:`40943`.)" -#: ../../whatsnew/3.10.rst:2155 +#: ../../whatsnew/3.10.rst:2156 msgid "" "Since :c:func:`Py_REFCNT()` is changed to the inline static function, " "``Py_REFCNT(obj) = new_refcnt`` must be replaced with ``Py_SET_REFCNT(obj, " @@ -3828,11 +4536,21 @@ msgstr "" "(disponível desde o Python 3.9). Para compatibilidade com versões " "anteriores, esta macro pode ser usada::" -#: ../../whatsnew/3.10.rst:2164 +#: ../../whatsnew/3.10.rst:2161 +msgid "" +"#if PY_VERSION_HEX < 0x030900A4\n" +"# define Py_SET_REFCNT(obj, refcnt) ((Py_REFCNT(obj) = (refcnt)), (void)0)\n" +"#endif" +msgstr "" +"#if PY_VERSION_HEX < 0x030900A4\n" +"# define Py_SET_REFCNT(obj, refcnt) ((Py_REFCNT(obj) = (refcnt)), (void)0)\n" +"#endif" + +#: ../../whatsnew/3.10.rst:2165 msgid "(Contributed by Victor Stinner in :issue:`39573`.)" msgstr "(Contribuição de Victor Stinner em :issue:`39573`.)" -#: ../../whatsnew/3.10.rst:2166 +#: ../../whatsnew/3.10.rst:2167 msgid "" "Calling :c:func:`PyDict_GetItem` without :term:`GIL` held had been allowed " "for historical reason. It is no longer allowed. (Contributed by Victor " @@ -3842,7 +4560,7 @@ msgstr "" "por razões históricas. Isso não é mais permitido. (Contribuição de Victor " "Stinner em :issue:`40839`.)" -#: ../../whatsnew/3.10.rst:2170 +#: ../../whatsnew/3.10.rst:2171 msgid "" "``PyUnicode_FromUnicode(NULL, size)`` and " "``PyUnicode_FromStringAndSize(NULL, size)`` raise ``DeprecationWarning`` " @@ -3854,7 +4572,7 @@ msgstr "" "para alocar objeto Unicode sem dados iniciais. (Contribuição de Inada Naoki " "em :issue:`36346`.)" -#: ../../whatsnew/3.10.rst:2175 +#: ../../whatsnew/3.10.rst:2176 msgid "" "The private ``_PyUnicode_Name_CAPI`` structure of the PyCapsule API " "``unicodedata.ucnhash_CAPI`` has been moved to the internal C API. " @@ -3864,7 +4582,7 @@ msgstr "" "ucnhash_CAPI`` foi movida para a API C interna. (Contribuição de Victor " "Stinner em :issue:`42157`.)" -#: ../../whatsnew/3.10.rst:2179 +#: ../../whatsnew/3.10.rst:2180 msgid "" ":c:func:`Py_GetPath`, :c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`, :c:" "func:`Py_GetProgramFullPath`, :c:func:`Py_GetPythonHome` and :c:func:" @@ -3880,7 +4598,7 @@ msgstr "" "inicializado). Use a nova API de :ref:`init-config` para obter a :ref:`init-" "path-config`. (Contribuição de Victor Stinner em :issue:`42260`.)" -#: ../../whatsnew/3.10.rst:2186 +#: ../../whatsnew/3.10.rst:2187 msgid "" ":c:func:`PyList_SET_ITEM`, :c:func:`PyTuple_SET_ITEM` and :c:func:" "`PyCell_SET` macros can no longer be used as l-value or r-value. For " @@ -3896,7 +4614,7 @@ msgstr "" "(PyList_SET_ITEM (a, b, c) < 0) ...``. (Contribuição de Zackery Spytz e " "Victor Stinner em :issue:`30459`.)" -#: ../../whatsnew/3.10.rst:2193 +#: ../../whatsnew/3.10.rst:2194 msgid "" "The non-limited API files ``odictobject.h``, ``parser_interface.h``, " "``picklebufobject.h``, ``pyarena.h``, ``pyctype.h``, ``pydebug.h``, ``pyfpe." @@ -3914,7 +4632,7 @@ msgstr "" "considere incluir ``Python.h`` em vez disso. (Contribuição de Nicholas Sim " "em :issue:`35134`.)" -#: ../../whatsnew/3.10.rst:2201 +#: ../../whatsnew/3.10.rst:2202 msgid "" "Use the :c:macro:`Py_TPFLAGS_IMMUTABLETYPE` type flag to create immutable " "type objects. Do not rely on :c:macro:`Py_TPFLAGS_HEAPTYPE` to decide if a " @@ -3928,7 +4646,7 @@ msgstr "" "`Py_TPFLAGS_IMMUTABLETYPE` está definido. (Contribuição de Victor Stinner e " "Erlend E. Aasland em :issue:`43908`.)" -#: ../../whatsnew/3.10.rst:2207 +#: ../../whatsnew/3.10.rst:2208 msgid "" "The undocumented function ``Py_FrozenMain`` has been removed from the " "limited API. The function is mainly useful for custom builds of Python. " @@ -3938,7 +4656,7 @@ msgstr "" "função é útil principalmente para compilações personalizadas do Python. " "(Contribuição de Petr Viktorin em :issue:`26241`.)" -#: ../../whatsnew/3.10.rst:2214 +#: ../../whatsnew/3.10.rst:2215 msgid "" "The ``PyUnicode_InternImmortal()`` function is now deprecated and will be " "removed in Python 3.12: use :c:func:`PyUnicode_InternInPlace` instead. " @@ -3948,7 +4666,7 @@ msgstr "" "removida no Python 3.12: use :c:func:`PyUnicode_InternInPlace` em vez disso. " "(Contribuição de Victor Stinner em :issue:`41692`.)" -#: ../../whatsnew/3.10.rst:2222 +#: ../../whatsnew/3.10.rst:2223 msgid "" "Removed ``Py_UNICODE_str*`` functions manipulating ``Py_UNICODE*`` strings. " "(Contributed by Inada Naoki in :issue:`41123`.)" @@ -3956,7 +4674,7 @@ msgstr "" "Removidas as funções ``Py_UNICODE_str*`` que manipulam strings " "``Py_UNICODE*``. (Contribuição de Inada Naoki em :issue:`41123`.)" -#: ../../whatsnew/3.10.rst:2225 +#: ../../whatsnew/3.10.rst:2226 msgid "" "``Py_UNICODE_strlen``: use :c:func:`PyUnicode_GetLength` or :c:macro:" "`PyUnicode_GET_LENGTH`" @@ -3964,7 +4682,7 @@ msgstr "" "``Py_UNICODE_strlen``: use :c:func:`PyUnicode_GetLength` ou :c:macro:" "`PyUnicode_GET_LENGTH`" -#: ../../whatsnew/3.10.rst:2227 +#: ../../whatsnew/3.10.rst:2228 msgid "" "``Py_UNICODE_strcat``: use :c:func:`PyUnicode_CopyCharacters` or :c:func:" "`PyUnicode_FromFormat`" @@ -3972,7 +4690,7 @@ msgstr "" "``Py_UNICODE_strcat``: use :c:func:`PyUnicode_CopyCharacters` ou :c:func:" "`PyUnicode_FromFormat`" -#: ../../whatsnew/3.10.rst:2229 +#: ../../whatsnew/3.10.rst:2230 msgid "" "``Py_UNICODE_strcpy``, ``Py_UNICODE_strncpy``: use :c:func:" "`PyUnicode_CopyCharacters` or :c:func:`PyUnicode_Substring`" @@ -3980,15 +4698,15 @@ msgstr "" "``Py_UNICODE_strcpy``, ``Py_UNICODE_strncpy``: use :c:func:" "`PyUnicode_CopyCharacters` ou :c:func:`PyUnicode_Substring`" -#: ../../whatsnew/3.10.rst:2231 +#: ../../whatsnew/3.10.rst:2232 msgid "``Py_UNICODE_strcmp``: use :c:func:`PyUnicode_Compare`" msgstr "``Py_UNICODE_strcmp``: use :c:func:`PyUnicode_Compare`" -#: ../../whatsnew/3.10.rst:2232 +#: ../../whatsnew/3.10.rst:2233 msgid "``Py_UNICODE_strncmp``: use :c:func:`PyUnicode_Tailmatch`" msgstr "``Py_UNICODE_strncmp``: use :c:func:`PyUnicode_Tailmatch`" -#: ../../whatsnew/3.10.rst:2233 +#: ../../whatsnew/3.10.rst:2234 msgid "" "``Py_UNICODE_strchr``, ``Py_UNICODE_strrchr``: use :c:func:" "`PyUnicode_FindChar`" @@ -3996,7 +4714,7 @@ msgstr "" "``Py_UNICODE_strchr``, ``Py_UNICODE_strrchr``: use :c:func:" "`PyUnicode_FindChar`" -#: ../../whatsnew/3.10.rst:2236 +#: ../../whatsnew/3.10.rst:2237 msgid "" "Removed ``PyUnicode_GetMax()``. Please migrate to new (:pep:`393`) APIs. " "(Contributed by Inada Naoki in :issue:`41103`.)" @@ -4004,7 +4722,7 @@ msgstr "" "Removida ``PyUnicode_GetMax()``. Migre para as novas APIs (:pep:`393`). " "(Contribuição de Inada Naoki em :issue:`41103`.)" -#: ../../whatsnew/3.10.rst:2239 +#: ../../whatsnew/3.10.rst:2240 msgid "" "Removed ``PyLong_FromUnicode()``. Please migrate to :c:func:" "`PyLong_FromUnicodeObject`. (Contributed by Inada Naoki in :issue:`41103`.)" @@ -4012,7 +4730,7 @@ msgstr "" "Removida ``PyLong_FromUnicode()``. Migre para :c:func:" "`PyLong_FromUnicodeObject`. (Contribuição de Inada Naoki em :issue:`41103`.)" -#: ../../whatsnew/3.10.rst:2242 +#: ../../whatsnew/3.10.rst:2243 msgid "" "Removed ``PyUnicode_AsUnicodeCopy()``. Please use :c:func:" "`PyUnicode_AsUCS4Copy` or :c:func:`PyUnicode_AsWideCharString` (Contributed " @@ -4022,7 +4740,7 @@ msgstr "" "ou :c:func:`PyUnicode_AsWideCharString` (Contribuição de Inada Naoki em :" "issue:`41103`.)" -#: ../../whatsnew/3.10.rst:2246 +#: ../../whatsnew/3.10.rst:2247 msgid "" "Removed ``_Py_CheckRecursionLimit`` variable: it has been replaced by " "``ceval.recursion_limit`` of the :c:type:`PyInterpreterState` structure. " @@ -4032,7 +4750,7 @@ msgstr "" "recursion_limit`` da estrutura :c:type:`PyInterpreterState`. (Contribuição " "de Victor Stinner em :issue:`41834`.)" -#: ../../whatsnew/3.10.rst:2250 +#: ../../whatsnew/3.10.rst:2251 msgid "" "Removed undocumented macros ``Py_ALLOW_RECURSION`` and " "``Py_END_ALLOW_RECURSION`` and the ``recursion_critical`` field of the :c:" @@ -4044,7 +4762,7 @@ msgstr "" "type:`PyInterpreterState`. (Contribuição de Serhiy Storchaka em :issue:" "`41936`.)" -#: ../../whatsnew/3.10.rst:2255 +#: ../../whatsnew/3.10.rst:2256 msgid "" "Removed the undocumented ``PyOS_InitInterrupts()`` function. Initializing " "Python already implicitly installs signal handlers: see :c:member:`PyConfig." @@ -4055,7 +4773,7 @@ msgstr "" "`PyConfig.install_signal_handlers`. (Contribuição de Victor Stinner em :" "issue:`41713`.)" -#: ../../whatsnew/3.10.rst:2260 +#: ../../whatsnew/3.10.rst:2261 msgid "" "Remove the ``PyAST_Validate()`` function. It is no longer possible to build " "a AST object (``mod_ty`` type) with the public C API. The function was " @@ -4067,36 +4785,36 @@ msgstr "" "da API C limitada (:pep:`384`). (Contribuição de Victor Stinner em :issue:" "`43244`.)" -#: ../../whatsnew/3.10.rst:2265 +#: ../../whatsnew/3.10.rst:2266 msgid "Remove the ``symtable.h`` header file and the undocumented functions:" msgstr "" "Remove o arquivo de cabeçalho ``symtable.h`` e as funções não documentadas:" -#: ../../whatsnew/3.10.rst:2267 +#: ../../whatsnew/3.10.rst:2268 msgid "``PyST_GetScope()``" msgstr "``PyST_GetScope()``" -#: ../../whatsnew/3.10.rst:2268 +#: ../../whatsnew/3.10.rst:2269 msgid "``PySymtable_Build()``" msgstr "``PySymtable_Build()``" -#: ../../whatsnew/3.10.rst:2269 +#: ../../whatsnew/3.10.rst:2270 msgid "``PySymtable_BuildObject()``" msgstr "``PySymtable_BuildObject()``" -#: ../../whatsnew/3.10.rst:2270 +#: ../../whatsnew/3.10.rst:2271 msgid "``PySymtable_Free()``" msgstr "``PySymtable_Free()``" -#: ../../whatsnew/3.10.rst:2271 +#: ../../whatsnew/3.10.rst:2272 msgid "``Py_SymtableString()``" msgstr "``Py_SymtableString()``" -#: ../../whatsnew/3.10.rst:2272 +#: ../../whatsnew/3.10.rst:2273 msgid "``Py_SymtableStringObject()``" msgstr "``Py_SymtableStringObject()``" -#: ../../whatsnew/3.10.rst:2274 +#: ../../whatsnew/3.10.rst:2275 msgid "" "The ``Py_SymtableString()`` function was part the stable ABI by mistake but " "it could not be used, because the ``symtable.h`` header file was excluded " @@ -4106,7 +4824,7 @@ msgstr "" "não pôde ser usada, porque o arquivo de cabeçalho ``symtable.h`` foi " "excluído da API C limitada." -#: ../../whatsnew/3.10.rst:2278 +#: ../../whatsnew/3.10.rst:2279 msgid "" "Use Python :mod:`symtable` module instead. (Contributed by Victor Stinner " "in :issue:`43244`.)" @@ -4114,7 +4832,7 @@ msgstr "" "Use o módulo Python :mod:`symtable` em vez disso. (Contribuição de Victor " "Stinner em :issue:`43244`.)" -#: ../../whatsnew/3.10.rst:2281 +#: ../../whatsnew/3.10.rst:2282 msgid "" "Remove :c:func:`PyOS_ReadlineFunctionPointer` from the limited C API headers " "and from ``python3.dll``, the library that provides the stable ABI on " @@ -4126,7 +4844,7 @@ msgstr "" "Windows. Como a função recebe um argumento ``FILE*``, sua estabilidade ABI " "não pode ser garantida. (Contribuição de Petr Viktorin em :issue:`43868`.)" -#: ../../whatsnew/3.10.rst:2287 +#: ../../whatsnew/3.10.rst:2288 msgid "" "Remove ``ast.h``, ``asdl.h``, and ``Python-ast.h`` header files. These " "functions were undocumented and excluded from the limited C API. Most names " @@ -4145,7 +4863,7 @@ msgstr "" "módulo Python :mod:`ast` em vez disso. (Contribuição de Victor Stinner em :" "issue:`43244`.)" -#: ../../whatsnew/3.10.rst:2295 +#: ../../whatsnew/3.10.rst:2296 msgid "" "Remove the compiler and parser functions using ``struct _mod`` type, because " "the public AST C API was removed:" @@ -4153,47 +4871,47 @@ msgstr "" "Remove as funções do compilador e do analisador usando o tipo ``struct " "_mod``, porque a API AST C pública foi removida:" -#: ../../whatsnew/3.10.rst:2298 +#: ../../whatsnew/3.10.rst:2299 msgid "``PyAST_Compile()``" msgstr "``PyAST_Compile()``" -#: ../../whatsnew/3.10.rst:2299 +#: ../../whatsnew/3.10.rst:2300 msgid "``PyAST_CompileEx()``" msgstr "``PyAST_CompileEx()``" -#: ../../whatsnew/3.10.rst:2300 +#: ../../whatsnew/3.10.rst:2301 msgid "``PyAST_CompileObject()``" msgstr "``PyAST_CompileObject()``" -#: ../../whatsnew/3.10.rst:2301 +#: ../../whatsnew/3.10.rst:2302 msgid "``PyFuture_FromAST()``" msgstr "``PyFuture_FromAST()``" -#: ../../whatsnew/3.10.rst:2302 +#: ../../whatsnew/3.10.rst:2303 msgid "``PyFuture_FromASTObject()``" msgstr "``PyFuture_FromASTObject()``" -#: ../../whatsnew/3.10.rst:2303 +#: ../../whatsnew/3.10.rst:2304 msgid "``PyParser_ASTFromFile()``" msgstr "``PyParser_ASTFromFile()``" -#: ../../whatsnew/3.10.rst:2304 +#: ../../whatsnew/3.10.rst:2305 msgid "``PyParser_ASTFromFileObject()``" msgstr "``PyParser_ASTFromFileObject()``" -#: ../../whatsnew/3.10.rst:2305 +#: ../../whatsnew/3.10.rst:2306 msgid "``PyParser_ASTFromFilename()``" msgstr "``PyParser_ASTFromFilename()``" -#: ../../whatsnew/3.10.rst:2306 +#: ../../whatsnew/3.10.rst:2307 msgid "``PyParser_ASTFromString()``" msgstr "``PyParser_ASTFromString()``" -#: ../../whatsnew/3.10.rst:2307 +#: ../../whatsnew/3.10.rst:2308 msgid "``PyParser_ASTFromStringObject()``" msgstr "``PyParser_ASTFromStringObject()``" -#: ../../whatsnew/3.10.rst:2309 +#: ../../whatsnew/3.10.rst:2310 msgid "" "These functions were undocumented and excluded from the limited C API. " "(Contributed by Victor Stinner in :issue:`43244`.)" @@ -4201,27 +4919,27 @@ msgstr "" "Essas funções não estavam documentadas e excluídas da API C limitada. " "(Contribuição de Victor Stinner em :issue:`43244`.)" -#: ../../whatsnew/3.10.rst:2312 +#: ../../whatsnew/3.10.rst:2313 msgid "Remove the ``pyarena.h`` header file with functions:" msgstr "Remove o arquivo de cabeçalho ``pyarena.h`` com funções:" -#: ../../whatsnew/3.10.rst:2314 +#: ../../whatsnew/3.10.rst:2315 msgid "``PyArena_New()``" msgstr "``PyArena_New()``" -#: ../../whatsnew/3.10.rst:2315 +#: ../../whatsnew/3.10.rst:2316 msgid "``PyArena_Free()``" msgstr "``PyArena_Free()``" -#: ../../whatsnew/3.10.rst:2316 +#: ../../whatsnew/3.10.rst:2317 msgid "``PyArena_Malloc()``" msgstr "``PyArena_Malloc()``" -#: ../../whatsnew/3.10.rst:2317 +#: ../../whatsnew/3.10.rst:2318 msgid "``PyArena_AddPyObject()``" msgstr "``PyArena_AddPyObject()``" -#: ../../whatsnew/3.10.rst:2319 +#: ../../whatsnew/3.10.rst:2320 msgid "" "These functions were undocumented, excluded from the limited C API, and were " "only used internally by the compiler. (Contributed by Victor Stinner in :" @@ -4231,7 +4949,7 @@ msgstr "" "usadas apenas internamente pelo compilador. (Contribuição de Victor Stinner " "em :issue:`43244`.)" -#: ../../whatsnew/3.10.rst:2323 +#: ../../whatsnew/3.10.rst:2324 msgid "" "The ``PyThreadState.use_tracing`` member has been removed to optimize " "Python. (Contributed by Mark Shannon in :issue:`43760`.)" @@ -4239,11 +4957,11 @@ msgstr "" "O membro ``PyThreadState.use_tracing`` foi removido para otimizar o Python. " "(Contribuição de Mark Shannon em :issue:`43760`.)" -#: ../../whatsnew/3.10.rst:2328 +#: ../../whatsnew/3.10.rst:2329 msgid "Notable security feature in 3.10.7" msgstr "Recursos de segurança notáveis no 3.10.7" -#: ../../whatsnew/3.10.rst:2330 +#: ../../whatsnew/3.10.rst:2331 msgid "" "Converting between :class:`int` and :class:`str` in bases other than 2 " "(binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal) " @@ -4266,11 +4984,11 @@ msgstr "" "inteira `. O limite padrão é de 4300 dígitos em forma de " "string." -#: ../../whatsnew/3.10.rst:2341 +#: ../../whatsnew/3.10.rst:2342 msgid "Notable security feature in 3.10.8" msgstr "Recursos de segurança notáveis no 3.10.8" -#: ../../whatsnew/3.10.rst:2343 +#: ../../whatsnew/3.10.rst:2344 msgid "" "The deprecated :mod:`!mailcap` module now refuses to inject unsafe text " "(filenames, MIME types, parameters) into shell commands. Instead of using " @@ -4284,15 +5002,15 @@ msgstr "" "fosse encontrada (ou para comandos de teste, como se o teste tivesse " "falhado). (Contribuição de Petr Viktorin em :gh:`98966`.)" -#: ../../whatsnew/3.10.rst:2350 +#: ../../whatsnew/3.10.rst:2351 msgid "Notable changes in 3.10.12" msgstr "Alterações notáveis no 3.10.12" -#: ../../whatsnew/3.10.rst:2353 +#: ../../whatsnew/3.10.rst:2354 msgid "tarfile" msgstr "tarfile" -#: ../../whatsnew/3.10.rst:2355 +#: ../../whatsnew/3.10.rst:2356 msgid "" "The extraction methods in :mod:`tarfile`, and :func:`shutil.unpack_archive`, " "have a new a *filter* argument that allows limiting tar features than may be " diff --git a/whatsnew/3.11.po b/whatsnew/3.11.po index 646e9d082..bfe24e830 100644 --- a/whatsnew/3.11.po +++ b/whatsnew/3.11.po @@ -1,35 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# 82596da39877db21448335599650eb68_ac09920 <1d2e18e2f37f0ba6c4f06b239e0670bd_848591>, 2022 -# Raphael Mendonça, 2022 -# Tiago Henrique , 2022 -# Misael borges , 2022 -# Victor Matheus Castro , 2022 -# André Filipe de Assunção e Brito , 2022 -# Victor Moura , 2022 -# Marco Rougeth , 2022 -# Rodrigo Cândido, 2022 -# Claudio Rogerio Carvalho Filho , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2022-11-05 19:49+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -118,7 +108,7 @@ msgstr "" #: ../../whatsnew/3.11.rst:86 msgid "New typing features:" -msgstr " Novos recursos de tipagem:" +msgstr "Novos recursos de tipagem:" #: ../../whatsnew/3.11.rst:88 msgid ":ref:`whatsnew311-pep646`" @@ -185,6 +175,26 @@ msgstr "" "agora apontará para a expressão exata que causou o erro, em vez de apenas a " "linha. Por exemplo:" +#: ../../whatsnew/3.11.rst:118 +msgid "" +"Traceback (most recent call last):\n" +" File \"distance.py\", line 11, in \n" +" print(manhattan_distance(p1, p2))\n" +" ^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +" File \"distance.py\", line 6, in manhattan_distance\n" +" return abs(point_1.x - point_2.x) + abs(point_1.y - point_2.y)\n" +" ^^^^^^^^^\n" +"AttributeError: 'NoneType' object has no attribute 'x'" +msgstr "" +"Traceback (most recent call last):\n" +" File \"distância.py\", line 11, in \n" +" print(distância_de_manhattan(p1, p2))\n" +" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +" File \"distância.py\", line 6, in distância_de_manhattan\n" +" return abs(ponto_1.x - ponto_2.x) + abs(ponto_1.y - ponto_2.y)\n" +" ^^^^^^^^^\n" +"AttributeError: 'NoneType' object has no attribute 'x'" + #: ../../whatsnew/3.11.rst:129 msgid "" "Previous versions of the interpreter would point to just the line, making it " @@ -197,10 +207,55 @@ msgstr "" "úteis ao lidar com objetos :class:`dict` profundamente aninhados e várias " "chamadas de função:" +#: ../../whatsnew/3.11.rst:133 +msgid "" +"Traceback (most recent call last):\n" +" File \"query.py\", line 37, in \n" +" magic_arithmetic('foo')\n" +" File \"query.py\", line 18, in magic_arithmetic\n" +" return add_counts(x) / 25\n" +" ^^^^^^^^^^^^^\n" +" File \"query.py\", line 24, in add_counts\n" +" return 25 + query_user(user1) + query_user(user2)\n" +" ^^^^^^^^^^^^^^^^^\n" +" File \"query.py\", line 32, in query_user\n" +" return 1 + query_count(db, response['a']['b']['c']['user'], retry=True)\n" +" ~~~~~~~~~~~~~~~~~~^^^^^\n" +"TypeError: 'NoneType' object is not subscriptable" +msgstr "" +"Traceback (most recent call last):\n" +" File \"consultar.py\", line 37, in \n" +" mágica_aritmética('foo')\n" +" File \"consultar.py\", line 18, in mágica_aritmética\n" +" return adicionar_contagens(x) / 25\n" +" ^^^^^^^^^^^^^\n" +" File \"consultar.py\", line 24, in adicionar_contagens\n" +" return 25 + consultar_usuário(usuário1) + consultar_usuário(usuário2)\n" +" ^^^^^^^^^^^^^^^^^\n" +" File \"consultar.consultar\", line 32, in consultar_usuário\n" +" return 1 + consultar_contagem(db, resposta['a']['b']['c']['user'], " +"tentar_novamente=True)\n" +" ~~~~~~~~~~~~~~~~~~^^^^^\n" +"TypeError: 'NoneType' object is not subscriptable" + #: ../../whatsnew/3.11.rst:149 msgid "As well as complex arithmetic expressions:" msgstr "Bem como expressões aritméticas complexas:" +#: ../../whatsnew/3.11.rst:151 +msgid "" +"Traceback (most recent call last):\n" +" File \"calculation.py\", line 54, in \n" +" result = (x / y / z) * (a / b / c)\n" +" ~~~~~~^~~\n" +"ZeroDivisionError: division by zero" +msgstr "" +"Traceback (most recent call last):\n" +" File \"cálculo.py\", line 54, in \n" +" resultado = (x / y / z) * (a / b / c)\n" +" ~~~~~~^~~\n" +"ZeroDivisionError: division by zero" + #: ../../whatsnew/3.11.rst:159 msgid "" "Additionally, the information used by the enhanced traceback feature is made " @@ -448,10 +503,38 @@ msgstr "" "são obrigatórios por padrão. Por exemplo, o seguinte especifica um :class:`!" "TypedDict` com uma chave obrigatória e uma chave não obrigatória::" +#: ../../whatsnew/3.11.rst:291 +msgid "" +"class Movie(TypedDict):\n" +" title: str\n" +" year: NotRequired[int]\n" +"\n" +"m1: Movie = {\"title\": \"Black Panther\", \"year\": 2018} # OK\n" +"m2: Movie = {\"title\": \"Star Wars\"} # OK (year is not required)\n" +"m3: Movie = {\"year\": 2022} # ERROR (missing required field title)" +msgstr "" +"class Filme(TypedDict):\n" +" título: str\n" +" ano: NotRequired[int]\n" +"\n" +"m1: Filme = {\"título\": \"Pantera Negra\", \"ano\": 2018} # OK\n" +"m2: Filme = {\"título\": \"Star Wars\"} # OK (ano não é obrigatório)\n" +"m3: Filme = {\"ano\": 2022} # ERRO (falta título, um campo obrigatório)" + #: ../../whatsnew/3.11.rst:299 msgid "The following definition is equivalent::" msgstr "A seguinte definição é equivalente::" +#: ../../whatsnew/3.11.rst:301 +msgid "" +"class Movie(TypedDict, total=False):\n" +" title: Required[str]\n" +" year: int" +msgstr "" +"class File(TypedDict, total=False):\n" +" título: Required[str]\n" +" ano: int" + #: ../../whatsnew/3.11.rst:305 msgid "See :pep:`655` for more details." msgstr "Veja :pep:`655` para mais detalhes." @@ -492,6 +575,36 @@ msgstr "" "`classmethod `\\s e métodos :meth:`~object.__enter__` que " "retornam ``self``::" +#: ../../whatsnew/3.11.rst:326 +msgid "" +"class MyLock:\n" +" def __enter__(self) -> Self:\n" +" self.lock()\n" +" return self\n" +"\n" +" ...\n" +"\n" +"class MyInt:\n" +" @classmethod\n" +" def fromhex(cls, s: str) -> Self:\n" +" return cls(int(s, 16))\n" +"\n" +" ..." +msgstr "" +"class MinhaTrava:\n" +" def __enter__(self) -> Self:\n" +" self.trava()\n" +" return self\n" +"\n" +" ...\n" +"\n" +"class MeuInt:\n" +" @classmethod\n" +" def de_hex(cls, s: str) -> Self:\n" +" return cls(int(s, 16))\n" +"\n" +" ..." + #: ../../whatsnew/3.11.rst:340 msgid "" ":data:`~typing.Self` can also be used to annotate method parameters or " @@ -539,6 +652,42 @@ msgid "For example, a SQL query function could be annotated as follows::" msgstr "" "Por exemplo, uma função de consulta SQL pode ser anotada da seguinte forma::" +#: ../../whatsnew/3.11.rst:364 +msgid "" +"def run_query(sql: LiteralString) -> ...\n" +" ...\n" +"\n" +"def caller(\n" +" arbitrary_string: str,\n" +" query_string: LiteralString,\n" +" table_name: LiteralString,\n" +") -> None:\n" +" run_query(\"SELECT * FROM students\") # ok\n" +" run_query(query_string) # ok\n" +" run_query(\"SELECT * FROM \" + table_name) # ok\n" +" run_query(arbitrary_string) # type checker error\n" +" run_query( # type checker error\n" +" f\"SELECT * FROM students WHERE name = {arbitrary_string}\"\n" +" )" +msgstr "" +"def faz_consulta(sql: LiteralString) -> ...\n" +" ...\n" +"\n" +"def chamador(\n" +" string_arbitrária: str,\n" +" string_consulta: LiteralString,\n" +" nome_tabela: LiteralString,\n" +") -> None:\n" +" faz_consulta(\"SELECT * FROM students\") # ok\n" +" faz_consulta(string_consulta) # ok\n" +" faz_consulta(\"SELECT * FROM \" + nome_tabela) # ok\n" +" faz_consulta(string_arbitrária) # erro no verificador de " +"tipo\n" +" faz_consulta( # erro no verificador de " +"tipo\n" +" f\"SELECT * FROM students WHERE name = {string_arbitrária}\"\n" +" )" + #: ../../whatsnew/3.11.rst:380 msgid "See :pep:`675` for more details." msgstr "Veja :pep:`675` para mais detalhes." @@ -574,6 +723,41 @@ msgstr "" msgid "For example::" msgstr "Por exemplo::" +#: ../../whatsnew/3.11.rst:399 +msgid "" +"# The create_model decorator is defined by a library.\n" +"@typing.dataclass_transform()\n" +"def create_model(cls: Type[T]) -> Type[T]:\n" +" cls.__init__ = ...\n" +" cls.__eq__ = ...\n" +" cls.__ne__ = ...\n" +" return cls\n" +"\n" +"# The create_model decorator can now be used to create new model classes:\n" +"@create_model\n" +"class CustomerModel:\n" +" id: int\n" +" name: str\n" +"\n" +"c = CustomerModel(id=327, name=\"Eric Idle\")" +msgstr "" +"# O decorador cria_modelo está definido por uma biblioteca.\n" +"@typing.dataclass_transform()\n" +"def cria_modelo(cls: Type[T]) -> Type[T]:\n" +" cls.__init__ = ...\n" +" cls.__eq__ = ...\n" +" cls.__ne__ = ...\n" +" return cls\n" +"\n" +"# O decorador cria_modelo agora pode ser usado para criar novas classes de " +"modelo:\n" +"@cria_modelo\n" +"class ModeloCliente:\n" +" id: int\n" +" nome: str\n" +"\n" +"c = ModeloCliente(id=327, nome=\"Eric Idle\")" + #: ../../whatsnew/3.11.rst:415 msgid "See :pep:`681` for more details." msgstr "Veja :pep:`681` para mais detalhes." @@ -1196,6 +1380,52 @@ msgstr "" ":func:`functools.singledispatch` agora suporta :data:`types.UnionType` e :" "data:`typing.Union` como anotações para o argumento de dispatch.::" +#: ../../whatsnew/3.11.rst:746 +msgid "" +">>> from functools import singledispatch\n" +">>> @singledispatch\n" +"... def fun(arg, verbose=False):\n" +"... if verbose:\n" +"... print(\"Let me just say,\", end=\" \")\n" +"... print(arg)\n" +"...\n" +">>> @fun.register\n" +"... def _(arg: int | float, verbose=False):\n" +"... if verbose:\n" +"... print(\"Strength in numbers, eh?\", end=\" \")\n" +"... print(arg)\n" +"...\n" +">>> from typing import Union\n" +">>> @fun.register\n" +"... def _(arg: Union[list, set], verbose=False):\n" +"... if verbose:\n" +"... print(\"Enumerate this:\")\n" +"... for i, elem in enumerate(arg):\n" +"... print(i, elem)\n" +"..." +msgstr "" +">>> from functools import singledispatch\n" +">>> @singledispatch\n" +"... def fun(arg, verboso=False):\n" +"... if verboso:\n" +"... print(\"Deixe-me apenas dizer,\", end=\" \")\n" +"... print(arg)\n" +"...\n" +">>> @fun.register\n" +"... def _(arg: int | float, verboso=False):\n" +"... if verboso:\n" +"... print(\"Força nos números, não é?\", end=\" \")\n" +"... print(arg)\n" +"...\n" +">>> from typing import Union\n" +">>> @fun.register\n" +"... def _(arg: Union[list, set], verbose=False):\n" +"... if verboso:\n" +"... print(\"Enumere isso:\")\n" +"... for i, elem in enumerate(arg):\n" +"... print(i, elem)\n" +"..." + #: ../../whatsnew/3.11.rst:768 msgid "(Contributed by Yurii Karabas in :issue:`46014`.)" msgstr "(Contribuição de Yurii Karabas na :issue:`46014`.)" @@ -1257,8 +1487,8 @@ msgid "" "files or file-like objects. (Contributed by Christian Heimes in :gh:`89313`.)" msgstr "" "Adiciona :func:`hashlib.file_digest`, uma função auxiliar para hash " -"eficiente de arquivos ou objetos semelhantes a arquivos. (Contribuição de " -"Christian Heimes em :gh:`89313`.)" +"eficiente de objetos arquivo ou similar. (Contribuição de Christian Heimes " +"em :gh:`89313`.)" #: ../../whatsnew/3.11.rst:810 msgid "IDLE and idlelib" @@ -1431,7 +1661,7 @@ msgstr "" #: ../../whatsnew/3.11.rst:900 msgid "operator" -msgstr "operator" +msgstr "operador" #: ../../whatsnew/3.11.rst:902 msgid "" @@ -1731,8 +1961,8 @@ msgstr "" "Objetos :class:`~tempfile.SpooledTemporaryFile` agora implementam totalmente " "os métodos de :class:`io.BufferedIOBase` ou :class:`io.TextIOBase` " "(dependendo do modo de arquivo). Isso permite que eles funcionem " -"corretamente com APIs que esperam objetos semelhantes a arquivos, como " -"módulos de compactação. (Contribuição de Carey Metcalfe em :gh:`70363`.)" +"corretamente com APIs que esperam objetos arquivo ou similar, como módulos " +"de compactação. (Contribuição de Carey Metcalfe em :gh:`70363`.)" #: ../../whatsnew/3.11.rst:1080 msgid "threading" @@ -2046,7 +2276,7 @@ msgstr "" #: ../../whatsnew/3.11.rst:1247 msgid "warnings" -msgstr "warnings" +msgstr "avisos" #: ../../whatsnew/3.11.rst:1249 msgid "" @@ -2252,6 +2482,11 @@ msgstr "" msgid "Previously in 3.10, Python module execution looked like this:" msgstr "Anteriormente na versão 3.10, a execução do módulo Python era assim:" +#: ../../whatsnew/3.11.rst:1358 +msgid "Read __pycache__ -> Unmarshal -> Heap allocated code object -> Evaluate" +msgstr "" +"Read __pycache__ -> Unmarshal -> Heap allocated code object -> Evaluate" + #: ../../whatsnew/3.11.rst:1362 msgid "" "In Python 3.11, the core modules essential for Python startup are " @@ -2264,6 +2499,10 @@ msgstr "" "bytecode) são alocados estaticamente pelo interpretador. Isso reduz as " "etapas no processo de execução do módulo para isso:" +#: ../../whatsnew/3.11.rst:1367 +msgid "Statically allocated code object -> Evaluate" +msgstr "Statically allocated code object -> Evaluate" + #: ../../whatsnew/3.11.rst:1371 msgid "" "Interpreter startup is now 10-15% faster in Python 3.11. This has a big " @@ -3713,7 +3952,7 @@ msgstr "Apelido descontinuado" #: ../../whatsnew/3.11.rst:1926 msgid "Method Name" -msgstr "Nome do método" +msgstr "Método" #: ../../whatsnew/3.11.rst:1926 msgid "Deprecated in" @@ -4041,16 +4280,16 @@ msgstr "" #: ../../whatsnew/3.11.rst:2035 msgid "" -"Removed the undocumented private :meth:`!float.__set_format__()` method, " -"previously known as :meth:`!float.__setformat__()` in Python 3.7. Its " +"Removed the undocumented private :meth:`!float.__set_format__` method, " +"previously known as :meth:`!float.__setformat__` in Python 3.7. Its " "docstring said: \"You probably don't want to use this function. It exists " "mainly to be used in Python's test suite.\" (Contributed by Victor Stinner " "in :issue:`46852`.)" msgstr "" -"Removido o método privado não documentado :meth:`!float.__set_format__()`, " -"anteriormente conhecido como :meth:`!float.__setformat__()` no Python 3.7. " -"Sua docstring dizia: \"Você provavelmente não quer usar esta função. Ela " -"existe principalmente para ser usada na conjunto de testes do Python." +"Removido o método privado não documentado :meth:`!float.__set_format__`, " +"anteriormente conhecido como :meth:`!float.__setformat__` no Python 3.7. Sua " +"docstring dizia: \"Você provavelmente não quer usar esta função. Ela existe " +"principalmente para ser usada na conjunto de testes do Python." "\" (Contribuição de Victor Stinner em :issue:`46852`.)" #: ../../whatsnew/3.11.rst:2041 @@ -4207,7 +4446,7 @@ msgstr "" #: ../../whatsnew/3.11.rst:2115 msgid "Build Changes" -msgstr "Alterações de compilação" +msgstr "Mudanças na construção" #: ../../whatsnew/3.11.rst:2117 msgid "" @@ -4668,10 +4907,50 @@ msgstr "" msgid "A tp_dealloc function that has the old macros, such as::" msgstr "Uma função tp_dealloc que possui as macros antigas, como::" +#: ../../whatsnew/3.11.rst:2332 +msgid "" +"static void\n" +"mytype_dealloc(mytype *p)\n" +"{\n" +" PyObject_GC_UnTrack(p);\n" +" Py_TRASHCAN_SAFE_BEGIN(p);\n" +" ...\n" +" Py_TRASHCAN_SAFE_END\n" +"}" +msgstr "" +"static void\n" +"dealocador_de_meutipo(meutipo *p)\n" +"{\n" +" PyObject_GC_UnTrack(p);\n" +" Py_TRASHCAN_SAFE_BEGIN(p);\n" +" ...\n" +" Py_TRASHCAN_SAFE_END\n" +"}" + #: ../../whatsnew/3.11.rst:2341 msgid "should migrate to the new macros as follows::" msgstr "deve migrar para as novas macros da seguinte forma::" +#: ../../whatsnew/3.11.rst:2343 +msgid "" +"static void\n" +"mytype_dealloc(mytype *p)\n" +"{\n" +" PyObject_GC_UnTrack(p);\n" +" Py_TRASHCAN_BEGIN(p, mytype_dealloc)\n" +" ...\n" +" Py_TRASHCAN_END\n" +"}" +msgstr "" +"static void\n" +"dealocador_de_meutipo(meutipo *p)\n" +"{\n" +" PyObject_GC_UnTrack(p);\n" +" Py_TRASHCAN_BEGIN(p, dealocador_de_meutipo);\n" +" ...\n" +" Py_TRASHCAN_END\n" +"}" + #: ../../whatsnew/3.11.rst:2352 msgid "" "Note that ``Py_TRASHCAN_BEGIN`` has a second argument which should be the " @@ -4690,6 +4969,24 @@ msgstr "" "código, você pode definir as seguintes macros e usá-las em todo o código " "(crédito: elas foram copiadas da base de código do ``mypy``)::" +#: ../../whatsnew/3.11.rst:2359 +msgid "" +"#if PY_VERSION_HEX >= 0x03080000\n" +"# define CPy_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_BEGIN(op, dealloc)\n" +"# define CPy_TRASHCAN_END(op) Py_TRASHCAN_END\n" +"#else\n" +"# define CPy_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_SAFE_BEGIN(op)\n" +"# define CPy_TRASHCAN_END(op) Py_TRASHCAN_SAFE_END(op)\n" +"#endif" +msgstr "" +"#if PY_VERSION_HEX >= 0x03080000\n" +"# define CPy_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_BEGIN(op, dealloc)\n" +"# define CPy_TRASHCAN_END(op) Py_TRASHCAN_END\n" +"#else\n" +"# define CPy_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_SAFE_BEGIN(op)\n" +"# define CPy_TRASHCAN_END(op) Py_TRASHCAN_SAFE_END(op)\n" +"#endif" + #: ../../whatsnew/3.11.rst:2367 msgid "" "The :c:func:`PyType_Ready` function now raises an error if a type is defined " @@ -4727,6 +5024,20 @@ msgstr "" "Python 3.9). Para compatibilidade com versões anteriores, esta macro pode " "ser usada::" +#: ../../whatsnew/3.11.rst:2383 +msgid "" +"#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_TYPE)\n" +"static inline void _Py_SET_TYPE(PyObject *ob, PyTypeObject *type)\n" +"{ ob->ob_type = type; }\n" +"#define Py_SET_TYPE(ob, type) _Py_SET_TYPE((PyObject*)(ob), type)\n" +"#endif" +msgstr "" +"#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_TYPE)\n" +"static inline void _Py_SET_TYPE(PyObject *ob, PyTypeObject *type)\n" +"{ ob->ob_type = type; }\n" +"#define Py_SET_TYPE(ob, type) _Py_SET_TYPE((PyObject*)(ob), type)\n" +"#endif" + #: ../../whatsnew/3.11.rst:2389 ../../whatsnew/3.11.rst:2403 msgid "(Contributed by Victor Stinner in :issue:`39573`.)" msgstr "(Contribuição de Victor Stinner em :issue:`39573`.)" @@ -4744,6 +5055,20 @@ msgstr "" "3.9). Para compatibilidade com versões anteriores, esta macro pode ser " "usada::" +#: ../../whatsnew/3.11.rst:2397 +msgid "" +"#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_SIZE)\n" +"static inline void _Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size)\n" +"{ ob->ob_size = size; }\n" +"#define Py_SET_SIZE(ob, size) _Py_SET_SIZE((PyVarObject*)(ob), size)\n" +"#endif" +msgstr "" +"#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_SIZE)\n" +"static inline void _Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size)\n" +"{ ob->ob_size = size; }\n" +"#define Py_SET_SIZE(ob, size) _Py_SET_SIZE((PyVarObject*)(ob), size)\n" +"#endif" + #: ../../whatsnew/3.11.rst:2405 msgid "" "```` no longer includes the header files ````, ``f_code);\n" +" return frame->f_code;\n" +"}\n" +"#endif" +msgstr "" +"#if PY_VERSION_HEX < 0x030900B1\n" +"static inline PyCodeObject* PyFrame_GetCode(PyFrameObject *frame)\n" +"{\n" +" Py_INCREF(frame->f_code);\n" +" return frame->f_code;\n" +"}\n" +"#endif" + #: ../../whatsnew/3.11.rst:2496 msgid "Code defining ``PyFrame_GetBack()`` on Python 3.8 and older::" msgstr "Código definindo ``PyFrame_GetBack()`` no Python 3.8 e anteriores::" +#: ../../whatsnew/3.11.rst:2498 +msgid "" +"#if PY_VERSION_HEX < 0x030900B1\n" +"static inline PyFrameObject* PyFrame_GetBack(PyFrameObject *frame)\n" +"{\n" +" Py_XINCREF(frame->f_back);\n" +" return frame->f_back;\n" +"}\n" +"#endif" +msgstr "" +"#if PY_VERSION_HEX < 0x030900B1\n" +"static inline PyFrameObject* PyFrame_GetBack(PyFrameObject *frame)\n" +"{\n" +" Py_XINCREF(frame->f_back);\n" +" return frame->f_back;\n" +"}\n" +"#endif" + #: ../../whatsnew/3.11.rst:2506 msgid "" "Or use the `pythoncapi_compat project frame);\n" +" return tstate->frame;\n" +"}\n" +"#endif" +msgstr "" +"#if PY_VERSION_HEX < 0x030900B1\n" +"static inline PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate)\n" +"{\n" +" Py_XINCREF(tstate->frame);\n" +" return tstate->frame;\n" +"}\n" +"#endif" + #: ../../whatsnew/3.11.rst:2533 msgid "" "Code defining ``PyThreadState_EnterTracing()`` and " @@ -5043,6 +5422,56 @@ msgstr "" "Código definindo ``PyThreadState_EnterTracing()`` e " "``PyThreadState_LeaveTracing()`` no Python 3.10 e anteriores::" +#: ../../whatsnew/3.11.rst:2536 +msgid "" +"#if PY_VERSION_HEX < 0x030B00A2\n" +"static inline void PyThreadState_EnterTracing(PyThreadState *tstate)\n" +"{\n" +" tstate->tracing++;\n" +"#if PY_VERSION_HEX >= 0x030A00A1\n" +" tstate->cframe->use_tracing = 0;\n" +"#else\n" +" tstate->use_tracing = 0;\n" +"#endif\n" +"}\n" +"\n" +"static inline void PyThreadState_LeaveTracing(PyThreadState *tstate)\n" +"{\n" +" int use_tracing = (tstate->c_tracefunc != NULL || tstate->c_profilefunc !" +"= NULL);\n" +" tstate->tracing--;\n" +"#if PY_VERSION_HEX >= 0x030A00A1\n" +" tstate->cframe->use_tracing = use_tracing;\n" +"#else\n" +" tstate->use_tracing = use_tracing;\n" +"#endif\n" +"}\n" +"#endif" +msgstr "" +"#if PY_VERSION_HEX < 0x030B00A2\n" +"static inline void PyThreadState_EnterTracing(PyThreadState *tstate)\n" +"{\n" +" tstate->tracing++;\n" +"#if PY_VERSION_HEX >= 0x030A00A1\n" +" tstate->cframe->use_tracing = 0;\n" +"#else\n" +" tstate->use_tracing = 0;\n" +"#endif\n" +"}\n" +"\n" +"static inline void PyThreadState_LeaveTracing(PyThreadState *tstate)\n" +"{\n" +" int use_tracing = (tstate->c_tracefunc != NULL || tstate->c_profilefunc !" +"= NULL);\n" +" tstate->tracing--;\n" +"#if PY_VERSION_HEX >= 0x030A00A1\n" +" tstate->cframe->use_tracing = use_tracing;\n" +"#else\n" +" tstate->use_tracing = use_tracing;\n" +"#endif\n" +"}\n" +"#endif" + #: ../../whatsnew/3.11.rst:2559 msgid "" "Or use `the pythoncapi-compat project , YEAR. # # Translators: -# Ricardo Cappellano , 2023 -# Marco Rougeth , 2023 -# Victor Moura , 2023 -# Italo Penaforte , 2023 -# André Filipe de Assunção e Brito , 2023 -# Victor Matheus Castro , 2023 -# Raphael Mendonça, 2023 -# Vinícius Muniz de Melo , 2023 -# Claudio Rogerio Carvalho Filho , 2023 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2023-05-24 13:08+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-16 14:58+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -65,20 +55,19 @@ msgstr "Resumo -- Destaques da versão" #: ../../whatsnew/3.12.rst:62 msgid "" -"Python 3.12 is the latest stable release of the Python programming language, " -"with a mix of changes to the language and the standard library. The library " -"changes focus on cleaning up deprecated APIs, usability, and correctness. Of " -"note, the :mod:`!distutils` package has been removed from the standard " -"library. Filesystem support in :mod:`os` and :mod:`pathlib` has seen a " -"number of improvements, and several modules have better performance." -msgstr "" -"Python 3.12 é a versão estável mais recente da linguagem de programação " -"Python, com uma combinação de alterações na linguagem e na biblioteca " -"padrão. As alterações da biblioteca se concentram na limpeza de APIs " -"descontinuadas, usabilidade e correção. É importante notar que o pacote :mod:" -"`!distutils` foi removido da biblioteca padrão. O suporte ao sistema de " -"arquivos em :mod:`os` e :mod:`pathlib` teve uma série de melhorias e vários " -"módulos têm melhor desempenho." +"Python 3.12 is a stable release of the Python programming language, with a " +"mix of changes to the language and the standard library. The library changes " +"focus on cleaning up deprecated APIs, usability, and correctness. Of note, " +"the :mod:`!distutils` package has been removed from the standard library. " +"Filesystem support in :mod:`os` and :mod:`pathlib` has seen a number of " +"improvements, and several modules have better performance." +msgstr "" +"Python 3.12 é uma versão estável da linguagem de programação Python, com uma " +"combinação de alterações na linguagem e na biblioteca padrão. As alterações " +"da biblioteca se concentram na limpeza de APIs descontinuadas, usabilidade e " +"correção. É importante notar que o pacote :mod:`!distutils` foi removido da " +"biblioteca padrão. O suporte ao sistema de arquivos em :mod:`os` e :mod:" +"`pathlib` teve uma série de melhorias e vários módulos têm melhor desempenho." #: ../../whatsnew/3.12.rst:69 msgid "" @@ -232,7 +221,7 @@ msgstr "" #: ../../whatsnew/3.12.rst:126 msgid "Security improvements:" -msgstr "Melhorias de segurança:" +msgstr "Melhorias de Segurança:" #: ../../whatsnew/3.12.rst:128 msgid "" @@ -278,7 +267,7 @@ msgstr "Implementa proteção contra estouro de pilha em plataformas suportadas" #: ../../whatsnew/3.12.rst:145 msgid "New typing features:" -msgstr " Novos recursos de tipagem:" +msgstr "Novos recursos de tipagem:" #: ../../whatsnew/3.12.rst:147 msgid "" @@ -306,18 +295,18 @@ msgstr "" #: ../../whatsnew/3.12.rst:156 msgid "" -":pep:`632`: Remove the :mod:`!distutils` package. See `the migration guide " -"`_ for advice replacing " -"the APIs it provided. The third-party `Setuptools `__ package continues to " -"provide :mod:`!distutils`, if you still require it in Python 3.12 and beyond." +":pep:`632`: Remove the :mod:`!distutils` package. See :pep:`the migration " +"guide <0632#migration-advice>` for advice replacing the APIs it provided. " +"The third-party `Setuptools `__ package continues to provide :mod:`!distutils`, if " +"you still require it in Python 3.12 and beyond." msgstr "" -":pep:`632`: Remove o pacote :mod:`!distutils`. Consulte `o guia de migração " -"`_ para obter conselhos " -"sobre a substituição das APIs fornecidas por ele. O pacote de terceiros " -"`Setuptools `__ continua fornecendo :mod:`!distutils`, se você ainda " -"precisar dele no Python 3.12 e posterior." +":pep:`632`: Remove o pacote :mod:`!distutils`. Consulte :pep:`o guia de " +"migração <0632#migration-advice>` para obter conselhos sobre a substituição " +"das APIs fornecidas por ele. O pacote de terceiros `Setuptools `__ continua " +"fornecendo :mod:`!distutils`, se você ainda precisar dele no Python 3.12 e " +"posterior." #: ../../whatsnew/3.12.rst:163 msgid "" @@ -343,7 +332,7 @@ msgstr "" "juntamente com vários `apelidos de métodos `_ de :class:`unittest.TestCase`." -#: ../../whatsnew/3.12.rst:176 ../../whatsnew/3.12.rst:1825 +#: ../../whatsnew/3.12.rst:176 ../../whatsnew/3.12.rst:1840 msgid "New Features" msgstr "Novas funcionalidades" @@ -371,6 +360,28 @@ msgstr "" "ref:`classes genéricas ` e :ref:`funções `::" +#: ../../whatsnew/3.12.rst:190 +msgid "" +"def max[T](args: Iterable[T]) -> T:\n" +" ...\n" +"\n" +"class list[T]:\n" +" def __getitem__(self, index: int, /) -> T:\n" +" ...\n" +"\n" +" def append(self, element: T) -> None:\n" +" ..." +msgstr "" +"def max[T](args: Iterable[T]) -> T:\n" +" ...\n" +"\n" +"class list[T]:\n" +" def __getitem__(self, index: int, /) -> T:\n" +" ...\n" +"\n" +" def append(self, element: T) -> None:\n" +" ..." + #: ../../whatsnew/3.12.rst:200 msgid "" "In addition, the PEP introduces a new way to declare :ref:`type aliases " @@ -381,12 +392,20 @@ msgstr "" "tipos ` usando a instrução :keyword:`type`, que cria uma " "instância de :class:`~typing.TypeAliasType`::" +#: ../../whatsnew/3.12.rst:204 +msgid "type Point = tuple[float, float]" +msgstr "type Point = tuple[float, float]" + #: ../../whatsnew/3.12.rst:206 msgid "Type aliases can also be :ref:`generic `::" msgstr "" "Os apelidos de tipo também podem ser :ref:`genéricos `::" +#: ../../whatsnew/3.12.rst:208 +msgid "type Point[T] = tuple[T, T]" +msgstr "type Point[T] = tuple[T, T]" + #: ../../whatsnew/3.12.rst:210 msgid "" "The new syntax allows declaring :class:`~typing.TypeVarTuple` and :class:" @@ -397,6 +416,19 @@ msgstr "" "e :class:`~typing.ParamSpec`, bem como os parâmetros :class:`~typing." "TypeVar` com limites ou restrições::" +#: ../../whatsnew/3.12.rst:214 +msgid "" +"type IntFunc[**P] = Callable[P, int] # ParamSpec\n" +"type LabeledTuple[*Ts] = tuple[str, *Ts] # TypeVarTuple\n" +"type HashableSequence[T: Hashable] = Sequence[T] # TypeVar with bound\n" +"type IntOrStrSequence[T: (int, str)] = Sequence[T] # TypeVar with " +"constraints" +msgstr "" +"type IntFunc[**P] = Callable[P, int] # ParamSpec\n" +"type LabeledTuple[*Ts] = tuple[str, *Ts] # TypeVarTuple\n" +"type HashableSequence[T: Hashable] = Sequence[T] # TypeVar com vínculo\n" +"type IntOrStrSequence[T: (int, str)] = Sequence[T] # TypeVar com restrições" + #: ../../whatsnew/3.12.rst:219 msgid "" "The value of type aliases and the bound and constraints of type variables " @@ -551,6 +583,20 @@ msgstr "" "do erro. Por exemplo, no Python 3.11, a seguinte f-string levanta um :exc:" "`SyntaxError`:" +#: ../../whatsnew/3.12.rst:310 +msgid "" +">>> my_string = f\"{x z y}\" + f\"{1 + 1}\"\n" +" File \"\", line 1\n" +" (x z y)\n" +" ^^^\n" +"SyntaxError: f-string: invalid syntax. Perhaps you forgot a comma?" +msgstr "" +">>> my_string = f\"{x z y}\" + f\"{1 + 1}\"\n" +" File \"\", line 1\n" +" (x z y)\n" +" ^^^\n" +"SyntaxError: f-string: invalid syntax. Perhaps you forgot a comma?" + #: ../../whatsnew/3.12.rst:318 msgid "" "but the error message doesn't include the exact location of the error within " @@ -563,6 +609,20 @@ msgstr "" "3.12, como as f-strings são analisadas com o analisador GASE, as mensagens " "de erro podem ser mais precisas e mostrar a linha inteira:" +#: ../../whatsnew/3.12.rst:322 +msgid "" +">>> my_string = f\"{x z y}\" + f\"{1 + 1}\"\n" +" File \"\", line 1\n" +" my_string = f\"{x z y}\" + f\"{1 + 1}\"\n" +" ^^^\n" +"SyntaxError: invalid syntax. Perhaps you forgot a comma?" +msgstr "" +">>> minha_string = f\"{x z y}\" + f\"{1 + 1}\"\n" +" File \"\", line 1\n" +" minha_string = f\"{x z y}\" + f\"{1 + 1}\"\n" +" ^^^\n" +"SyntaxError: invalid syntax. Perhaps you forgot a comma?" + #: ../../whatsnew/3.12.rst:330 msgid "" "(Contributed by Pablo Galindo, Batuhan Taskaya, Lysandros Nikolaou, Cristián " @@ -599,14 +659,37 @@ msgstr "" "Use a nova função :c:func:`Py_NewInterpreterFromConfig` para criar um " "interpretador com sua própria GIL:" +#: ../../whatsnew/3.12.rst:348 +msgid "" +"PyInterpreterConfig config = {\n" +" .check_multi_interp_extensions = 1,\n" +" .gil = PyInterpreterConfig_OWN_GIL,\n" +"};\n" +"PyThreadState *tstate = NULL;\n" +"PyStatus status = Py_NewInterpreterFromConfig(&tstate, &config);\n" +"if (PyStatus_Exception(status)) {\n" +" return -1;\n" +"}\n" +"/* The new interpreter is now active in the current thread. */" +msgstr "" +"PyInterpreterConfig config = {\n" +" .check_multi_interp_extensions = 1,\n" +" .gil = PyInterpreterConfig_OWN_GIL,\n" +"};\n" +"PyThreadState *tstate = NULL;\n" +"PyStatus status = Py_NewInterpreterFromConfig(&tstate, &config);\n" +"if (PyStatus_Exception(status)) {\n" +" return -1;\n" +"}\n" +"/* O novo interpretador agora está ativo na atual thread. */" + #: ../../whatsnew/3.12.rst:361 msgid "" "For further examples how to use the C-API for sub-interpreters with a per-" -"interpreter GIL, see :source:`Modules/_xxsubinterpretersmodule.c`." +"interpreter GIL, see ``Modules/_xxsubinterpretersmodule.c``." msgstr "" "Para obter mais exemplos de como usar a API C para subinterpretadores com " -"uma GIL por interpretador, consulte :source:`Modules/" -"_xxsubinterpretersmodule.c`." +"uma GIL por interpretador, consulte ``Modules/_xxsubinterpretersmodule.c``." #: ../../whatsnew/3.12.rst:364 msgid "(Contributed by Eric Snow in :gh:`104210`, etc.)" @@ -825,6 +908,24 @@ msgstr "" "A :pep:`692` especifica uma maneira mais precisa de definir tipos de " "``**kwargs``, contando com dicionários tipados::" +#: ../../whatsnew/3.12.rst:497 +msgid "" +"from typing import TypedDict, Unpack\n" +"\n" +"class Movie(TypedDict):\n" +" name: str\n" +" year: int\n" +"\n" +"def foo(**kwargs: Unpack[Movie]): ..." +msgstr "" +"from typing import TypedDict, Unpack\n" +"\n" +"class Filme(TypedDict):\n" +" nome: str\n" +" ano: int\n" +"\n" +"def foo(**kwargs: Unpack[Filme]): ..." + #: ../../whatsnew/3.12.rst:505 msgid "See :pep:`692` for more details." msgstr "Veja :pep:`692` para mais detalhes." @@ -855,6 +956,40 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" +#: ../../whatsnew/3.12.rst:522 +msgid "" +"from typing import override\n" +"\n" +"class Base:\n" +" def get_color(self) -> str:\n" +" return \"blue\"\n" +"\n" +"class GoodChild(Base):\n" +" @override # ok: overrides Base.get_color\n" +" def get_color(self) -> str:\n" +" return \"yellow\"\n" +"\n" +"class BadChild(Base):\n" +" @override # type checker error: does not override Base.get_color\n" +" def get_colour(self) -> str:\n" +" return \"red\"" +msgstr "" +"from typing import override\n" +"\n" +"class Base:\n" +" def obtém_cor(self) -> str:\n" +" return \"azul\"\n" +"\n" +"class FilhaBoa(Base):\n" +" @override # ok: substitui Base.obtém_cor\n" +" def obtém_cor(self) -> str:\n" +" return \"amarelo\"\n" +"\n" +"class FilhaRuim(Base):\n" +" @override # erro de verificador de tipo: não substitui Base.obtém_cor\n" +" def obtém_cores(self) -> str:\n" +" return \"vermelho\"" + #: ../../whatsnew/3.12.rst:538 msgid "See :pep:`698` for more details." msgstr "Consulte :pep:`698` para obter mais detalhes." @@ -1459,10 +1594,26 @@ msgstr "" "correspondência." #: ../../whatsnew/3.12.rst:815 +msgid "platform" +msgstr "platform" + +#: ../../whatsnew/3.12.rst:817 +msgid "" +"Add support for detecting Windows 11 and Windows Server releases past 2012. " +"Previously, lookups on Windows Server platforms newer than Windows Server " +"2012 and on Windows 11 would return ``Windows-10``. (Contributed by Steve " +"Dower in :gh:`89545`.)" +msgstr "" +"Adiciona suporte para detectar versões do Windows 11 e do Windows Server " +"posteriores a 2012. Anteriormente, pesquisas em plataformas Windows Server " +"mais recentes que o Windows Server 2012 e no Windows 11 retornariam " +"``Windows-10``. (Contribuição de Steve Dower em :gh:`89545`.)" + +#: ../../whatsnew/3.12.rst:823 msgid "pdb" msgstr "pdb" -#: ../../whatsnew/3.12.rst:817 +#: ../../whatsnew/3.12.rst:825 msgid "" "Add convenience variables to hold values temporarily for debug session and " "provide quick access to values like the current frame or the return value. " @@ -1472,11 +1623,11 @@ msgstr "" "para a sessão de depuração e fornece acesso rápido a valores como o quadro " "atual ou o valor de retorno. (Contribuição de Tian Gao em :gh:`103693`.)" -#: ../../whatsnew/3.12.rst:823 +#: ../../whatsnew/3.12.rst:831 msgid "random" msgstr "random" -#: ../../whatsnew/3.12.rst:825 +#: ../../whatsnew/3.12.rst:833 msgid "" "Add :func:`random.binomialvariate`. (Contributed by Raymond Hettinger in :gh:" "`81620`.)" @@ -1484,7 +1635,7 @@ msgstr "" "Adiciona :func:`random.binomialvariate`. (Contribuição de Raymond Hettinger " "em :gh:`81620`.)" -#: ../../whatsnew/3.12.rst:828 +#: ../../whatsnew/3.12.rst:836 msgid "" "Add a default of ``lambd=1.0`` to :func:`random.expovariate`. (Contributed " "by Raymond Hettinger in :gh:`100234`.)" @@ -1492,11 +1643,11 @@ msgstr "" "Adiciona um padrão de ``lambd=1.0`` a :func:`random.expovariate`. " "(Contribuição de Raymond Hettinger em :gh:`100234`.)" -#: ../../whatsnew/3.12.rst:832 +#: ../../whatsnew/3.12.rst:840 msgid "shutil" msgstr "shutil" -#: ../../whatsnew/3.12.rst:834 +#: ../../whatsnew/3.12.rst:842 msgid "" ":func:`shutil.make_archive` now passes the *root_dir* argument to custom " "archivers which support it. In this case it no longer temporarily changes " @@ -1509,7 +1660,7 @@ msgstr "" "para realizar o arquivamento. (Contribuição de Serhiy Storchaka em :gh:" "`74696`.)" -#: ../../whatsnew/3.12.rst:840 +#: ../../whatsnew/3.12.rst:848 msgid "" ":func:`shutil.rmtree` now accepts a new argument *onexc* which is an error " "handler like *onerror* but which expects an exception instance rather than a " @@ -1521,7 +1672,7 @@ msgstr "" "vez de um trio *(typ, val, tb)*. *onerror* foi descontinuado. (Contribuição " "de Irit Katriel em :gh:`102828`.)" -#: ../../whatsnew/3.12.rst:845 +#: ../../whatsnew/3.12.rst:853 msgid "" ":func:`shutil.which` now consults the *PATHEXT* environment variable to find " "matches within *PATH* on Windows even when the given *cmd* includes a " @@ -1532,7 +1683,7 @@ msgstr "" "fornecido inclui um componente de diretório. (Contribuição de Charles " "Machalow em :gh:`103179`.)" -#: ../../whatsnew/3.12.rst:850 +#: ../../whatsnew/3.12.rst:858 msgid "" ":func:`shutil.which` will call ``NeedCurrentDirectoryForExePathW`` when " "querying for executables on Windows to determine if the current working " @@ -1544,7 +1695,7 @@ msgstr "" "atual deve ser anexado ao caminho de pesquisa. (Contribuição de Charles " "Machalow em :gh:`103179`.)" -#: ../../whatsnew/3.12.rst:855 +#: ../../whatsnew/3.12.rst:863 msgid "" ":func:`shutil.which` will return a path matching the *cmd* with a component " "from ``PATHEXT`` prior to a direct match elsewhere in the search path on " @@ -1555,11 +1706,11 @@ msgstr "" "no caminho de pesquisa no Windows. (Contribuição de Charles Machalow em :gh:" "`103179`.)" -#: ../../whatsnew/3.12.rst:861 ../../whatsnew/3.12.rst:1529 +#: ../../whatsnew/3.12.rst:869 ../../whatsnew/3.12.rst:1544 msgid "sqlite3" msgstr "sqlite3" -#: ../../whatsnew/3.12.rst:863 +#: ../../whatsnew/3.12.rst:871 msgid "" "Add a :ref:`command-line interface `. (Contributed by Erlend E. " "Aasland in :gh:`77617`.)" @@ -1567,7 +1718,7 @@ msgstr "" "Adiciona uma :ref:`interface de linha de comando `. " "(Contribuição de Erlend E. Aasland em :gh:`77617`.)" -#: ../../whatsnew/3.12.rst:866 +#: ../../whatsnew/3.12.rst:874 msgid "" "Add the :attr:`sqlite3.Connection.autocommit` attribute to :class:`sqlite3." "Connection` and the *autocommit* parameter to :func:`sqlite3.connect` to " @@ -1580,7 +1731,7 @@ msgstr "" "transaction-control-autocommit>`. (Contribuição de Erlend E. Aasland em :gh:" "`83638`.)" -#: ../../whatsnew/3.12.rst:873 +#: ../../whatsnew/3.12.rst:881 msgid "" "Add *entrypoint* keyword-only parameter to :meth:`sqlite3.Connection." "load_extension`, for overriding the SQLite extension entry point. " @@ -1590,7 +1741,7 @@ msgstr "" "Connection.load_extension`, para substituir o ponto de entrada da extensão " "SQLite. (Contribuição de Erlend E. Aasland em :gh:`103015`.)" -#: ../../whatsnew/3.12.rst:878 +#: ../../whatsnew/3.12.rst:886 msgid "" "Add :meth:`sqlite3.Connection.getconfig` and :meth:`sqlite3.Connection." "setconfig` to :class:`sqlite3.Connection` to make configuration changes to a " @@ -1601,11 +1752,11 @@ msgstr "" "configuração de uma conexão de banco de dados. (Contribuição de Erlend E. " "Aasland em :gh:`103489`.)" -#: ../../whatsnew/3.12.rst:884 +#: ../../whatsnew/3.12.rst:892 msgid "statistics" msgstr "statistics" -#: ../../whatsnew/3.12.rst:886 +#: ../../whatsnew/3.12.rst:894 msgid "" "Extend :func:`statistics.correlation` to include as a ``ranked`` method for " "computing the Spearman correlation of ranked data. (Contributed by Raymond " @@ -1615,11 +1766,11 @@ msgstr "" "``ranked`` para calcular a correlação de Spearman de dados classificados. " "(Contribuição de Raymond Hettinger em :gh:`95861`.)" -#: ../../whatsnew/3.12.rst:891 +#: ../../whatsnew/3.12.rst:899 msgid "sys" msgstr "sys" -#: ../../whatsnew/3.12.rst:893 +#: ../../whatsnew/3.12.rst:901 msgid "" "Add the :mod:`sys.monitoring` namespace to expose the new :ref:`PEP 669 " "` monitoring API. (Contributed by Mark Shannon in :gh:" @@ -1629,7 +1780,7 @@ msgstr "" "monitoramento :ref:`PEP 669 `. (Contribuição de Mark " "Shannon em :gh:`103082`.)" -#: ../../whatsnew/3.12.rst:897 +#: ../../whatsnew/3.12.rst:905 msgid "" "Add :func:`sys.activate_stack_trampoline` and :func:`sys." "deactivate_stack_trampoline` for activating and deactivating stack profiler " @@ -1645,7 +1796,7 @@ msgstr "" "Galindo e Christian Heimes com contribuições de Gregory P. Smith [Google] e " "Mark Shannon em :gh:`96123`.)" -#: ../../whatsnew/3.12.rst:906 +#: ../../whatsnew/3.12.rst:914 msgid "" "Add :data:`sys.last_exc` which holds the last unhandled exception that was " "raised (for post-mortem debugging use cases). Deprecate the three fields " @@ -1659,7 +1810,7 @@ msgstr "" "`sys.last_type`, :data:`sys.last_value` e :data:`sys.last_traceback`. " "(Contribuição de Irit Katriel em :gh:`102778`.)" -#: ../../whatsnew/3.12.rst:912 ../../whatsnew/3.12.rst:1724 +#: ../../whatsnew/3.12.rst:920 ../../whatsnew/3.12.rst:1739 msgid "" ":func:`sys._current_exceptions` now returns a mapping from thread-id to an " "exception instance, rather than to a ``(typ, exc, tb)`` tuple. (Contributed " @@ -1669,7 +1820,7 @@ msgstr "" "para uma instância de exceção, ao invés de uma tupla ``(typ, exc, tb)``. " "(Contribuição de Irit Katriel em :gh:`103176`.)" -#: ../../whatsnew/3.12.rst:916 +#: ../../whatsnew/3.12.rst:924 msgid "" ":func:`sys.setrecursionlimit` and :func:`sys.getrecursionlimit`. The " "recursion limit now applies only to Python code. Builtin functions do not " @@ -1681,11 +1832,11 @@ msgstr "" "usam o limite de recursão, mas são protegidas por um mecanismo diferente que " "evita que a recursão cause uma falha na máquina virtual." -#: ../../whatsnew/3.12.rst:922 +#: ../../whatsnew/3.12.rst:930 msgid "tempfile" msgstr "tempfile" -#: ../../whatsnew/3.12.rst:924 +#: ../../whatsnew/3.12.rst:932 msgid "" "The :class:`tempfile.NamedTemporaryFile` function has a new optional " "parameter *delete_on_close* (Contributed by Evgeny Zorin in :gh:`58451`.)" @@ -1693,7 +1844,7 @@ msgstr "" "A função :class:`tempfile.NamedTemporaryFile` tem um novo parâmetro opcional " "*delete_on_close* (Contribuição de Evgeny Zorin em :gh:`58451`.)" -#: ../../whatsnew/3.12.rst:926 +#: ../../whatsnew/3.12.rst:934 msgid "" ":func:`tempfile.mkdtemp` now always returns an absolute path, even if the " "argument provided to the *dir* parameter is a relative path." @@ -1701,11 +1852,11 @@ msgstr "" ":func:`tempfile.mkdtemp` agora sempre retorna um caminho absoluto, mesmo se " "o argumento fornecido para o parâmetro *dir* for um caminho relativo." -#: ../../whatsnew/3.12.rst:930 +#: ../../whatsnew/3.12.rst:938 msgid "threading" msgstr "threading" -#: ../../whatsnew/3.12.rst:932 +#: ../../whatsnew/3.12.rst:940 msgid "" "Add :func:`threading.settrace_all_threads` and :func:`threading." "setprofile_all_threads` that allow to set tracing and profiling functions in " @@ -1717,11 +1868,11 @@ msgstr "" "criação de perfil em todos os threads em execução além do que está chamando. " "(Contribuição de Pablo Galindo em :gh:`93503`.)" -#: ../../whatsnew/3.12.rst:938 +#: ../../whatsnew/3.12.rst:946 msgid "tkinter" msgstr "tkinter" -#: ../../whatsnew/3.12.rst:940 +#: ../../whatsnew/3.12.rst:948 msgid "" "``tkinter.Canvas.coords()`` now flattens its arguments. It now accepts not " "only coordinates as separate arguments (``x1, y1, x2, y2, ...``) and a " @@ -1737,11 +1888,11 @@ msgstr "" "(x2, y2), ...]``) , como métodos ``create_*()``. (Contribuição de Serhiy " "Storchaka em :gh:`94473`.)" -#: ../../whatsnew/3.12.rst:949 +#: ../../whatsnew/3.12.rst:957 msgid "tokenize" msgstr "tokenize" -#: ../../whatsnew/3.12.rst:951 +#: ../../whatsnew/3.12.rst:959 msgid "" "The :mod:`tokenize` module includes the changes introduced in :pep:`701`. " "(Contributed by Marta Gómez Macías and Pablo Galindo in :gh:`102856`.) See :" @@ -1753,11 +1904,11 @@ msgstr "" "ref:`whatsnew312-porting-to-python312` para mais informações sobre as " "mudanças no módulo :mod:`tokenize`." -#: ../../whatsnew/3.12.rst:957 +#: ../../whatsnew/3.12.rst:965 msgid "types" msgstr "types" -#: ../../whatsnew/3.12.rst:959 +#: ../../whatsnew/3.12.rst:967 msgid "" "Add :func:`types.get_original_bases` to allow for further introspection of :" "ref:`user-defined-generics` when subclassed. (Contributed by James Hilton-" @@ -1767,11 +1918,11 @@ msgstr "" "adicional de :ref:`user-defined-generics` quando subclassificado. " "(Contribuição de James Hilton-Balfe e Alex Waygood em :gh:`101827`.)" -#: ../../whatsnew/3.12.rst:966 +#: ../../whatsnew/3.12.rst:974 msgid "typing" msgstr "typing" -#: ../../whatsnew/3.12.rst:968 +#: ../../whatsnew/3.12.rst:976 msgid "" ":func:`isinstance` checks against :func:`runtime-checkable protocols ` now use :func:`inspect.getattr_static` rather than :func:" @@ -1795,7 +1946,7 @@ msgstr "" "vice-versa. É improvável que a maioria dos usuários seja afetada por esta " "mudança. (Contribuição de Alex Waygood em :gh:`102433`.)" -#: ../../whatsnew/3.12.rst:979 +#: ../../whatsnew/3.12.rst:987 msgid "" "The members of a runtime-checkable protocol are now considered \"frozen\" at " "runtime as soon as the class has been created. Monkey-patching attributes " @@ -1809,7 +1960,45 @@ msgstr "" "nas verificações de :func:`isinstance` comparando objetos com o protocolo. " "Por exemplo::" -#: ../../whatsnew/3.12.rst:1001 +#: ../../whatsnew/3.12.rst:992 +msgid "" +">>> from typing import Protocol, runtime_checkable\n" +">>> @runtime_checkable\n" +"... class HasX(Protocol):\n" +"... x = 1\n" +"...\n" +">>> class Foo: ...\n" +"...\n" +">>> f = Foo()\n" +">>> isinstance(f, HasX)\n" +"False\n" +">>> f.x = 1\n" +">>> isinstance(f, HasX)\n" +"True\n" +">>> HasX.y = 2\n" +">>> isinstance(f, HasX) # unchanged, even though HasX now also has a \"y\" " +"attribute\n" +"True" +msgstr "" +">>> from typing import Protocol, runtime_checkable\n" +">>> @runtime_checkable\n" +"... class TemX(Protocol):\n" +"... x = 1\n" +"...\n" +">>> class Foo: ...\n" +"...\n" +">>> f = Foo()\n" +">>> isinstance(f, TemX)\n" +"False\n" +">>> f.x = 1\n" +">>> isinstance(f, TemX)\n" +"True\n" +">>> HasX.y = 2\n" +">>> isinstance(f, TemX) # inalterado, ainda que TemX agora tenha um " +"atributo \"y\"\n" +"True" + +#: ../../whatsnew/3.12.rst:1009 msgid "" "This change was made in order to speed up ``isinstance()`` checks against " "runtime-checkable protocols." @@ -1817,7 +2006,7 @@ msgstr "" "Esta mudança foi feita para acelerar as verificações de ``isinstance()`` em " "protocolos verificáveis em tempo de execução." -#: ../../whatsnew/3.12.rst:1004 +#: ../../whatsnew/3.12.rst:1012 msgid "" "The performance profile of :func:`isinstance` checks against :func:`runtime-" "checkable protocols ` has changed significantly. " @@ -1836,7 +2025,7 @@ msgstr "" "membros podem ser mais lentas do que no Python 3.11. (Contribuição de Alex " "Waygood em :gh:`74690` e :gh:`103193`.)" -#: ../../whatsnew/3.12.rst:1012 +#: ../../whatsnew/3.12.rst:1020 msgid "" "All :data:`typing.TypedDict` and :data:`typing.NamedTuple` classes now have " "the ``__orig_bases__`` attribute. (Contributed by Adrian Garcia Badaracco " @@ -1846,7 +2035,7 @@ msgstr "" "possuem o atributo ``__orig_bases__``. (Contribuição de Adrian Garcia " "Badaracco em :gh:`103699`.)" -#: ../../whatsnew/3.12.rst:1016 +#: ../../whatsnew/3.12.rst:1024 msgid "" "Add ``frozen_default`` parameter to :func:`typing.dataclass_transform`. " "(Contributed by Erik De Bonte in :gh:`99957`.)" @@ -1854,11 +2043,11 @@ msgstr "" "Adiciona o parâmetro ``frozen_default`` a :func:`typing." "dataclass_transform`. (Contribuição de Erik De Bonte em :gh:`99957`.)" -#: ../../whatsnew/3.12.rst:1020 +#: ../../whatsnew/3.12.rst:1028 msgid "unicodedata" msgstr "unicodedata" -#: ../../whatsnew/3.12.rst:1022 +#: ../../whatsnew/3.12.rst:1030 msgid "" "The Unicode database has been updated to version 15.0.0. (Contributed by " "Benjamin Peterson in :gh:`96734`)." @@ -1866,26 +2055,56 @@ msgstr "" "O banco de dados Unicode foi atualizado para a versão 15.0.0. (Contribuição " "de Benjamin Peterson em :gh:`96734`)." -#: ../../whatsnew/3.12.rst:1026 ../../whatsnew/3.12.rst:1569 +#: ../../whatsnew/3.12.rst:1034 ../../whatsnew/3.12.rst:1584 msgid "unittest" msgstr "unittest" -#: ../../whatsnew/3.12.rst:1028 +#: ../../whatsnew/3.12.rst:1036 msgid "" "Add a ``--durations`` command line option, showing the N slowest test cases::" msgstr "" "Adiciona uma opção de linha de comando ``--durations``, mostrando os N casos " "de teste mais lentos::" -#: ../../whatsnew/3.12.rst:1044 +#: ../../whatsnew/3.12.rst:1038 +msgid "" +"python3 -m unittest --durations=3 lib.tests.test_threading\n" +".....\n" +"Slowest test durations\n" +"----------------------------------------------------------------------\n" +"1.210s test_timeout (Lib.test.test_threading.BarrierTests)\n" +"1.003s test_default_timeout (Lib.test.test_threading.BarrierTests)\n" +"0.518s test_timeout (Lib.test.test_threading.EventTests)\n" +"\n" +"(0.000 durations hidden. Use -v to show these durations.)\n" +"----------------------------------------------------------------------\n" +"Ran 158 tests in 9.869s\n" +"\n" +"OK (skipped=3)" +msgstr "" +"python3 -m unittest --durations=3 lib.tests.test_threading\n" +".....\n" +"Slowest test durations\n" +"----------------------------------------------------------------------\n" +"1.210s test_timeout (Lib.test.test_threading.BarrierTests)\n" +"1.003s test_default_timeout (Lib.test.test_threading.BarrierTests)\n" +"0.518s test_timeout (Lib.test.test_threading.EventTests)\n" +"\n" +"(0.000 durations hidden. Use -v to show these durations.)\n" +"----------------------------------------------------------------------\n" +"Ran 158 tests in 9.869s\n" +"\n" +"OK (skipped=3)" + +#: ../../whatsnew/3.12.rst:1052 msgid "(Contributed by Giampaolo Rodola in :gh:`48330`)" msgstr "(Contribuição de Giampaolo Rodola em :gh:`48330`)" -#: ../../whatsnew/3.12.rst:1047 +#: ../../whatsnew/3.12.rst:1055 msgid "uuid" msgstr "uuid" -#: ../../whatsnew/3.12.rst:1049 +#: ../../whatsnew/3.12.rst:1057 msgid "" "Add a :ref:`command-line interface `. (Contributed by Adam Chhina " "in :gh:`88597`.)" @@ -1893,11 +2112,11 @@ msgstr "" "Adiciona uma :ref:`interface de linha de comando `. " "(Contribuição de Adam Chhina em :gh:`88597`.)" -#: ../../whatsnew/3.12.rst:1054 +#: ../../whatsnew/3.12.rst:1062 msgid "Optimizations" msgstr "Otimizações" -#: ../../whatsnew/3.12.rst:1056 +#: ../../whatsnew/3.12.rst:1064 msgid "" "Remove ``wstr`` and ``wstr_length`` members from Unicode objects. It reduces " "object size by 8 or 16 bytes on 64bit platform. (:pep:`623`) (Contributed by " @@ -1907,7 +2126,7 @@ msgstr "" "tamanho do objeto em 8 ou 16 bytes na plataforma de 64 bits. (:pep:`623`) " "(Contribuição de Inada Naoki em :gh:`92536`.)" -#: ../../whatsnew/3.12.rst:1060 +#: ../../whatsnew/3.12.rst:1068 msgid "" "Add experimental support for using the BOLT binary optimizer in the build " "process, which improves performance by 1-5%. (Contributed by Kevin " @@ -1917,7 +2136,7 @@ msgstr "" "processo de construção, o que melhora o desempenho de 1 a 5%. (Contribuição " "de Kevin Modzelewski em :gh:`90536` e ajuste de Donghee Na em :gh:`101525`)" -#: ../../whatsnew/3.12.rst:1064 +#: ../../whatsnew/3.12.rst:1072 msgid "" "Speed up the regular expression substitution (functions :func:`re.sub` and :" "func:`re.subn` and corresponding :class:`!re.Pattern` methods) for " @@ -1929,7 +2148,7 @@ msgstr "" "de substituição contendo referências de grupo em 2 ou 3 vezes . " "(Contribuição de Serhiy Storchaka em :gh:`91524`.)" -#: ../../whatsnew/3.12.rst:1069 +#: ../../whatsnew/3.12.rst:1077 msgid "" "Speed up :class:`asyncio.Task` creation by deferring expensive string " "formatting. (Contributed by Itamar Oren in :gh:`103793`.)" @@ -1937,7 +2156,7 @@ msgstr "" "Acelera a criação de :class:`asyncio.Task` adiando a dispendiosa formatação " "de strings. (Contribuição de Itamar Oren em :gh:`103793`.)" -#: ../../whatsnew/3.12.rst:1072 +#: ../../whatsnew/3.12.rst:1080 msgid "" "The :func:`tokenize.tokenize` and :func:`tokenize.generate_tokens` functions " "are up to 64% faster as a side effect of the changes required to cover :pep:" @@ -1949,7 +2168,7 @@ msgstr "" "cobrir :pep:`701` no módulo :mod:`tokenize` . (Contribuição de Marta Gómez " "Macías e Pablo Galindo em :gh:`102856`.)" -#: ../../whatsnew/3.12.rst:1077 +#: ../../whatsnew/3.12.rst:1085 msgid "" "Speed up :func:`super` method calls and attribute loads via the new :opcode:" "`LOAD_SUPER_ATTR` instruction. (Contributed by Carl Meyer and Vladimir " @@ -1959,11 +2178,11 @@ msgstr "" "através da nova instrução :opcode:`LOAD_SUPER_ATTR`. (Contribuição de Carl " "Meyer e Vladimir Matveev em :gh:`103497`.)" -#: ../../whatsnew/3.12.rst:1083 +#: ../../whatsnew/3.12.rst:1091 msgid "CPython bytecode changes" msgstr "Alterações de bytecode do CPython" -#: ../../whatsnew/3.12.rst:1085 +#: ../../whatsnew/3.12.rst:1093 msgid "" "Remove the :opcode:`!LOAD_METHOD` instruction. It has been merged into :" "opcode:`LOAD_ATTR`. :opcode:`LOAD_ATTR` will now behave like the old :opcode:" @@ -1975,7 +2194,7 @@ msgstr "" "instrução :opcode:`!LOAD_METHOD` se o bit inferior de seu oparg estiver " "definido. (Contribuição de Ken Jin em :gh:`93429`.)" -#: ../../whatsnew/3.12.rst:1090 +#: ../../whatsnew/3.12.rst:1098 msgid "" "Remove the :opcode:`!JUMP_IF_FALSE_OR_POP` and :opcode:`!" "JUMP_IF_TRUE_OR_POP` instructions. (Contributed by Irit Katriel in :gh:" @@ -1984,7 +2203,7 @@ msgstr "" "Remova as instruções :opcode:`!JUMP_IF_FALSE_OR_POP` e :opcode:`!" "JUMP_IF_TRUE_OR_POP`. (Contribuição de Irit Katriel em :gh:`102859`.)" -#: ../../whatsnew/3.12.rst:1093 +#: ../../whatsnew/3.12.rst:1101 msgid "" "Remove the :opcode:`!PRECALL` instruction. (Contributed by Mark Shannon in :" "gh:`92925`.)" @@ -1992,7 +2211,7 @@ msgstr "" "Remove a instrução :opcode:`!PRECALL`. (Contribuição de Mark Shannon em :gh:" "`92925`.)" -#: ../../whatsnew/3.12.rst:1096 +#: ../../whatsnew/3.12.rst:1104 msgid "" "Add the :opcode:`BINARY_SLICE` and :opcode:`STORE_SLICE` instructions. " "(Contributed by Mark Shannon in :gh:`94163`.)" @@ -2000,7 +2219,7 @@ msgstr "" "Adiciona as instruções :opcode:`BINARY_SLICE` e :opcode:`STORE_SLICE`. " "(Contribuição de Mark Shannon em :gh:`94163`.)" -#: ../../whatsnew/3.12.rst:1099 +#: ../../whatsnew/3.12.rst:1107 msgid "" "Add the :opcode:`CALL_INTRINSIC_1` instructions. (Contributed by Mark " "Shannon in :gh:`99005`.)" @@ -2008,7 +2227,7 @@ msgstr "" "Adiciona as instruções :opcode:`CALL_INTRINSIC_1`. (Contribuição de Mark " "Shannon em :gh:`99005`.)" -#: ../../whatsnew/3.12.rst:1102 +#: ../../whatsnew/3.12.rst:1110 msgid "" "Add the :opcode:`CALL_INTRINSIC_2` instruction. (Contributed by Irit Katriel " "in :gh:`101799`.)" @@ -2016,7 +2235,7 @@ msgstr "" "Adiciona a instrução :opcode:`CALL_INTRINSIC_2`. (Contribuição de Irit " "Katriel em :gh:`101799`.)" -#: ../../whatsnew/3.12.rst:1105 +#: ../../whatsnew/3.12.rst:1113 msgid "" "Add the :opcode:`CLEANUP_THROW` instruction. (Contributed by Brandt Bucher " "in :gh:`90997`.)" @@ -2024,7 +2243,7 @@ msgstr "" "Adiciona a instrução :opcode:`CLEANUP_THROW`. (Contribuição de Brandt Bucher " "em :gh:`90997`.)" -#: ../../whatsnew/3.12.rst:1108 +#: ../../whatsnew/3.12.rst:1116 msgid "" "Add the :opcode:`!END_SEND` instruction. (Contributed by Mark Shannon in :gh:" "`103082`.)" @@ -2032,7 +2251,7 @@ msgstr "" "Adiciona a instrução :opcode:`!END_SEND`. (Contribuição de Mark Shannon em :" "gh:`103082`.)" -#: ../../whatsnew/3.12.rst:1111 +#: ../../whatsnew/3.12.rst:1119 msgid "" "Add the :opcode:`LOAD_FAST_AND_CLEAR` instruction as part of the " "implementation of :pep:`709`. (Contributed by Carl Meyer in :gh:`101441`.)" @@ -2040,7 +2259,7 @@ msgstr "" "Adiciona a instrução :opcode:`LOAD_FAST_AND_CLEAR` como parte da " "implementação de :pep:`709`. (Contribuição de Carl Meyer em :gh:`101441`.)" -#: ../../whatsnew/3.12.rst:1114 +#: ../../whatsnew/3.12.rst:1122 msgid "" "Add the :opcode:`LOAD_FAST_CHECK` instruction. (Contributed by Dennis " "Sweeney in :gh:`93143`.)" @@ -2048,7 +2267,7 @@ msgstr "" "Adiciona a instrução :opcode:`LOAD_FAST_CHECK`. (Contribuição de Dennis " "Sweeney em :gh:`93143`.)" -#: ../../whatsnew/3.12.rst:1117 +#: ../../whatsnew/3.12.rst:1125 msgid "" "Add the :opcode:`LOAD_FROM_DICT_OR_DEREF`, :opcode:" "`LOAD_FROM_DICT_OR_GLOBALS`, and :opcode:`LOAD_LOCALS` opcodes as part of " @@ -2062,7 +2281,7 @@ msgstr "" "pode ser substituído por :opcode:`LOAD_LOCALS` mais :opcode:" "`LOAD_FROM_DICT_OR_DEREF`. (Contribuição de Jelle Zijlstra em :gh:`103764`.)" -#: ../../whatsnew/3.12.rst:1123 +#: ../../whatsnew/3.12.rst:1131 msgid "" "Add the :opcode:`LOAD_SUPER_ATTR` instruction. (Contributed by Carl Meyer " "and Vladimir Matveev in :gh:`103497`.)" @@ -2070,7 +2289,7 @@ msgstr "" "Adiciona a instrução :opcode:`LOAD_SUPER_ATTR`. (Contribuição de Carl Meyer " "e Vladimir Matveev em :gh:`103497`.)" -#: ../../whatsnew/3.12.rst:1126 +#: ../../whatsnew/3.12.rst:1134 msgid "" "Add the :opcode:`RETURN_CONST` instruction. (Contributed by Wenyang Wang in :" "gh:`101632`.)" @@ -2078,11 +2297,11 @@ msgstr "" "Adiciona a instrução :opcode:`RETURN_CONST`. (Contribuição de Wenyang Wang " "em :gh:`101632`.)" -#: ../../whatsnew/3.12.rst:1129 +#: ../../whatsnew/3.12.rst:1137 msgid "Demos and Tools" msgstr "Ferramentas e daemons" -#: ../../whatsnew/3.12.rst:1131 +#: ../../whatsnew/3.12.rst:1139 msgid "" "Remove the ``Tools/demo/`` directory which contained old demo scripts. A " "copy can be found in the `old-demos project `_. (Contribuição de Victor Stinner em :gh:" "`97681`.)" -#: ../../whatsnew/3.12.rst:1136 +#: ../../whatsnew/3.12.rst:1144 msgid "" "Remove outdated example scripts of the ``Tools/scripts/`` directory. A copy " "can be found in the `old-demos project `_. (Contribuição de Victor Stinner em :gh:`97669`.)" -#: ../../whatsnew/3.12.rst:1143 ../../whatsnew/3.12.rst:2127 +#: ../../whatsnew/3.12.rst:1151 ../../whatsnew/3.12.rst:2142 msgid "Deprecated" msgstr "Descontinuados" -#: ../../whatsnew/3.12.rst:1145 +#: ../../whatsnew/3.12.rst:1153 #: ../../deprecations/pending-removal-in-3.14.rst:4 msgid "" ":mod:`argparse`: The *type*, *choices*, and *metavar* parameters of :class:`!" @@ -2118,7 +2337,7 @@ msgstr "" "argparse.BooleanOptionalAction` foram descontinuados e serão removidos na " "versão 3.14. (Contribuição de Nikita Sobolev em :gh:`92248`.)" -#: ../../whatsnew/3.12.rst:1150 +#: ../../whatsnew/3.12.rst:1158 msgid "" ":mod:`ast`: The following :mod:`ast` features have been deprecated in " "documentation since Python 3.8, now cause a :exc:`DeprecationWarning` to be " @@ -2130,46 +2349,47 @@ msgstr "" "`DeprecationWarning` seja emitido em tempo de execução quando eles são " "acessados ou usados, e serão removidos no Python 3.14:" -#: ../../whatsnew/3.12.rst:1154 +#: ../../whatsnew/3.12.rst:1162 #: ../../deprecations/pending-removal-in-3.14.rst:13 msgid ":class:`!ast.Num`" msgstr ":class:`!ast.Num`" -#: ../../whatsnew/3.12.rst:1155 +#: ../../whatsnew/3.12.rst:1163 #: ../../deprecations/pending-removal-in-3.14.rst:14 msgid ":class:`!ast.Str`" msgstr ":class:`!ast.Str`" -#: ../../whatsnew/3.12.rst:1156 +#: ../../whatsnew/3.12.rst:1164 #: ../../deprecations/pending-removal-in-3.14.rst:15 msgid ":class:`!ast.Bytes`" msgstr ":class:`!ast.Bytes`" -#: ../../whatsnew/3.12.rst:1157 +#: ../../whatsnew/3.12.rst:1165 #: ../../deprecations/pending-removal-in-3.14.rst:16 msgid ":class:`!ast.NameConstant`" msgstr ":class:`!ast.NameConstant`" -#: ../../whatsnew/3.12.rst:1158 +#: ../../whatsnew/3.12.rst:1166 #: ../../deprecations/pending-removal-in-3.14.rst:17 msgid ":class:`!ast.Ellipsis`" msgstr ":class:`!ast.Ellipsis`" -#: ../../whatsnew/3.12.rst:1160 +#: ../../whatsnew/3.12.rst:1168 #: ../../deprecations/pending-removal-in-3.14.rst:19 msgid "" "Use :class:`ast.Constant` instead. (Contributed by Serhiy Storchaka in :gh:" "`90953`.)" msgstr "" -"Usa :class:`ast.Constant` em vez disso. (Contribuição de Serhiy Storchaka " +"Em vez disso, use :class:`ast.Constant`. (Contribuição de Serhiy Storchaka " "em :gh:`90953`.)" -#: ../../whatsnew/3.12.rst:1163 +#: ../../whatsnew/3.12.rst:1171 #: ../../deprecations/pending-removal-in-3.14.rst:22 +#: ../../deprecations/pending-removal-in-3.16.rst:19 msgid ":mod:`asyncio`:" msgstr ":mod:`asyncio`:" -#: ../../whatsnew/3.12.rst:1165 +#: ../../whatsnew/3.12.rst:1173 msgid "" "The child watcher classes :class:`asyncio.MultiLoopChildWatcher`, :class:" "`asyncio.FastChildWatcher`, :class:`asyncio.AbstractChildWatcher` and :class:" @@ -2181,7 +2401,7 @@ msgstr "" "class:`asyncio.SafeChildWatcher` foram descontinuadas e serão removidas no " "Python 3.14. (Contribuição de Kumar Aditya em :gh:`94597`.)" -#: ../../whatsnew/3.12.rst:1171 +#: ../../whatsnew/3.12.rst:1179 #: ../../deprecations/pending-removal-in-3.14.rst:30 msgid "" ":func:`asyncio.set_child_watcher`, :func:`asyncio.get_child_watcher`, :meth:" @@ -2194,7 +2414,7 @@ msgstr "" "AbstractEventLoopPolicy.get_child_watcher` foram descontinuados e serão " "removidos no Python 3.14. (Contribuição de Kumar Aditya em :gh:`94597`.)" -#: ../../whatsnew/3.12.rst:1177 +#: ../../whatsnew/3.12.rst:1185 #: ../../deprecations/pending-removal-in-3.14.rst:36 msgid "" "The :meth:`~asyncio.get_event_loop` method of the default event loop policy " @@ -2207,18 +2427,18 @@ msgstr "" "eventos atual definido e decidir criar um. (Contribuição de Serhiy Storchaka " "e Guido van Rossum em :gh:`100160`.)" -#: ../../whatsnew/3.12.rst:1182 -#: ../../deprecations/pending-removal-in-future.rst:42 +#: ../../whatsnew/3.12.rst:1190 +#: ../../deprecations/pending-removal-in-future.rst:39 msgid "" ":mod:`calendar`: ``calendar.January`` and ``calendar.February`` constants " "are deprecated and replaced by :data:`calendar.JANUARY` and :data:`calendar." "FEBRUARY`. (Contributed by Prince Roshan in :gh:`103636`.)" msgstr "" -":mod:`calendar`: As constantes ``calendar.January`` e ``calendar.February`` " +":mod:`calendar`: as constantes ``calendar.January`` e ``calendar.February`` " "foram descontinuadas e substituídas por :data:`calendar.JANUARY` e :data:" "`calendar.FEBRUARY`. (Contribuição de Prince Roshan em :gh:`103636`.)" -#: ../../whatsnew/3.12.rst:1186 +#: ../../whatsnew/3.12.rst:1194 msgid "" ":mod:`collections.abc`: Deprecated :class:`collections.abc.ByteString`. " "Prefer :class:`Sequence` or :class:`collections.abc.Buffer`. For use in " @@ -2230,7 +2450,7 @@ msgstr "" "Para uso em tipagem, prefira uma união, como ``bytes | bytearray`` ou :class:" "`collections.abc.Buffer`. (Contribuição de Shantanu Jain em :gh:`91896`.)" -#: ../../whatsnew/3.12.rst:1191 +#: ../../whatsnew/3.12.rst:1199 msgid "" ":mod:`datetime`: :class:`datetime.datetime`'s :meth:`~datetime.datetime." "utcnow` and :meth:`~datetime.datetime.utcfromtimestamp` are deprecated and " @@ -2247,7 +2467,7 @@ msgstr "" "datetime.fromtimestamp` com o parâmetro *tz* definido como :const:`datetime." "UTC`. (Contribuição de Paul Ganssle em :gh:`103857`.)" -#: ../../whatsnew/3.12.rst:1199 +#: ../../whatsnew/3.12.rst:1207 msgid "" ":mod:`email`: Deprecate the *isdst* parameter in :func:`email.utils." "localtime`. (Contributed by Alan Williams in :gh:`72346`.)" @@ -2255,7 +2475,7 @@ msgstr "" ":mod:`email`: Descontinua o parâmetro *isdst* em :func:`email.utils." "localtime`. (Contribuição de Alan Williams em :gh:`72346`.)" -#: ../../whatsnew/3.12.rst:1202 +#: ../../whatsnew/3.12.rst:1210 msgid "" ":mod:`importlib.abc`: Deprecated the following classes, scheduled for " "removal in Python 3.14:" @@ -2263,42 +2483,42 @@ msgstr "" ":mod:`importlib.abc`: Foram descontinuadas as seguintes classes, programadas " "para remoção no Python 3.14:" -#: ../../whatsnew/3.12.rst:1205 -#: ../../deprecations/pending-removal-in-3.14.rst:55 +#: ../../whatsnew/3.12.rst:1213 +#: ../../deprecations/pending-removal-in-3.14.rst:52 msgid ":class:`!importlib.abc.ResourceReader`" msgstr ":class:`!importlib.abc.ResourceReader`" -#: ../../whatsnew/3.12.rst:1206 -#: ../../deprecations/pending-removal-in-3.14.rst:56 +#: ../../whatsnew/3.12.rst:1214 +#: ../../deprecations/pending-removal-in-3.14.rst:53 msgid ":class:`!importlib.abc.Traversable`" msgstr ":class:`!importlib.abc.Traversable`" -#: ../../whatsnew/3.12.rst:1207 -#: ../../deprecations/pending-removal-in-3.14.rst:57 +#: ../../whatsnew/3.12.rst:1215 +#: ../../deprecations/pending-removal-in-3.14.rst:54 msgid ":class:`!importlib.abc.TraversableResources`" msgstr ":class:`!importlib.abc.TraversableResources`" -#: ../../whatsnew/3.12.rst:1209 -#: ../../deprecations/pending-removal-in-3.14.rst:59 +#: ../../whatsnew/3.12.rst:1217 +#: ../../deprecations/pending-removal-in-3.14.rst:56 msgid "Use :mod:`importlib.resources.abc` classes instead:" -msgstr "Em vez disso, use classes :mod:`importlib.resources.abc`:" +msgstr "Em vez disso, use classes de :mod:`importlib.resources.abc`:" -#: ../../whatsnew/3.12.rst:1211 -#: ../../deprecations/pending-removal-in-3.14.rst:61 +#: ../../whatsnew/3.12.rst:1219 +#: ../../deprecations/pending-removal-in-3.14.rst:58 msgid ":class:`importlib.resources.abc.Traversable`" msgstr ":class:`importlib.resources.abc.Traversable`" -#: ../../whatsnew/3.12.rst:1212 -#: ../../deprecations/pending-removal-in-3.14.rst:62 +#: ../../whatsnew/3.12.rst:1220 +#: ../../deprecations/pending-removal-in-3.14.rst:59 msgid ":class:`importlib.resources.abc.TraversableResources`" msgstr ":class:`importlib.resources.abc.TraversableResources`" -#: ../../whatsnew/3.12.rst:1214 -#: ../../deprecations/pending-removal-in-3.14.rst:64 +#: ../../whatsnew/3.12.rst:1222 +#: ../../deprecations/pending-removal-in-3.14.rst:61 msgid "(Contributed by Jason R. Coombs and Hugo van Kemenade in :gh:`93963`.)" msgstr "(Contribuição de Jason R. Coombs e Hugo van Kemenade em :gh:`93963`.)" -#: ../../whatsnew/3.12.rst:1216 +#: ../../whatsnew/3.12.rst:1224 msgid "" ":mod:`itertools`: Deprecate the support for copy, deepcopy, and pickle " "operations, which is undocumented, inefficient, historically buggy, and " @@ -2312,7 +2532,7 @@ msgstr "" "significativa no volume de código e na carga de manutenção. (Contribuição de " "Raymond Hettinger em :gh:`101588`.)" -#: ../../whatsnew/3.12.rst:1222 +#: ../../whatsnew/3.12.rst:1230 msgid "" ":mod:`multiprocessing`: In Python 3.14, the default :mod:`multiprocessing` " "start method will change to a safer one on Linux, BSDs, and other non-macOS " @@ -2333,7 +2553,7 @@ msgstr "" "seu código *requer* ``'fork'``. Veja :ref:`contextos e métodos de início " "`." -#: ../../whatsnew/3.12.rst:1232 +#: ../../whatsnew/3.12.rst:1240 msgid "" ":mod:`pkgutil`: :func:`pkgutil.find_loader` and :func:`pkgutil.get_loader` " "are deprecated and will be removed in Python 3.14; use :func:`importlib.util." @@ -2344,7 +2564,7 @@ msgstr "" "util.find_spec` em vez disso. (Contribuição de Nikita Sobolev em :gh:" "`97850`.)" -#: ../../whatsnew/3.12.rst:1237 +#: ../../whatsnew/3.12.rst:1245 msgid "" ":mod:`pty`: The module has two undocumented ``master_open()`` and " "``slave_open()`` functions that have been deprecated since Python 2 but only " @@ -2356,11 +2576,11 @@ msgstr "" "um :exc:`DeprecationWarning` adequado em 3.12. Remova-os em 3.14. " "(Contribuição de Soumendra Ganguly e Gregory P. Smith em :gh:`85984`.)" -#: ../../whatsnew/3.12.rst:1242 +#: ../../whatsnew/3.12.rst:1250 msgid ":mod:`os`:" msgstr ":mod:`os`:" -#: ../../whatsnew/3.12.rst:1244 +#: ../../whatsnew/3.12.rst:1252 msgid "" "The ``st_ctime`` fields return by :func:`os.stat` and :func:`os.lstat` on " "Windows are deprecated. In a future release, they will contain the last " @@ -2375,7 +2595,7 @@ msgstr "" "também está disponível no novo campo ``st_birthtime``. (Contribuição de " "Steve Dower em :gh:`99726`.)" -#: ../../whatsnew/3.12.rst:1250 +#: ../../whatsnew/3.12.rst:1258 msgid "" "On POSIX platforms, :func:`os.fork` can now raise a :exc:" "`DeprecationWarning` when it can detect being called from a multithreaded " @@ -2384,8 +2604,9 @@ msgid "" "warning to raise awareness as issues encountered by code doing this are " "becoming more frequent. See the :func:`os.fork` documentation for more " "details along with `this discussion on fork being incompatible with threads " -"`_ for *why* we're now surfacing this " -"longstanding platform compatibility problem to developers." +"`_ for *why* we're now surfacing this longstanding " +"platform compatibility problem to developers." msgstr "" "Nas plataformas POSIX, :func:`os.fork` agora pode levantar uma exceção :exc:" "`DeprecationWarning` quando puder detectar a chamada de um processo " @@ -2394,11 +2615,12 @@ msgstr "" "aviso para aumentar a conscientização, pois os problemas encontrados pelo " "código ao fazer isso estão se tornando mais frequentes. Veja a documentação :" "func:`os.fork` para mais detalhes junto com `esta discussão sobre fork ser " -"incompatível com threads `_ para *por " -"que* estamos agora trazendo à tona esse antigo problema de compatibilidade " -"de plataforma para os desenvolvedores." +"incompatível com threads `_ para *por que* estamos agora " +"trazendo à tona esse antigo problema de compatibilidade de plataforma para " +"os desenvolvedores." -#: ../../whatsnew/3.12.rst:1260 +#: ../../whatsnew/3.12.rst:1268 msgid "" "When this warning appears due to usage of :mod:`multiprocessing` or :mod:" "`concurrent.futures` the fix is to use a different :mod:`multiprocessing` " @@ -2408,7 +2630,7 @@ msgstr "" "`concurrent.futures`, a correção é usar um método de início de :mod:" "`multiprocessing` diferente, como ``\"spawn\"`` ou ``\"forkserver\"``." -#: ../../whatsnew/3.12.rst:1264 +#: ../../whatsnew/3.12.rst:1272 msgid "" ":mod:`shutil`: The *onerror* argument of :func:`shutil.rmtree` is " "deprecated; use *onexc* instead. (Contributed by Irit Katriel in :gh:" @@ -2418,12 +2640,12 @@ msgstr "" "descontinuado; use *onexc* em vez disso. (Contribuição de Irit Katriel em :" "gh:`102828`.)" -#: ../../whatsnew/3.12.rst:1267 -#: ../../deprecations/pending-removal-in-3.14.rst:94 +#: ../../whatsnew/3.12.rst:1275 +#: ../../deprecations/pending-removal-in-3.14.rst:91 msgid ":mod:`sqlite3`:" msgstr ":mod:`sqlite3`:" -#: ../../whatsnew/3.12.rst:1269 +#: ../../whatsnew/3.12.rst:1277 msgid "" ":ref:`default adapters and converters ` are now " "deprecated. Instead, use the :ref:`sqlite3-adapter-converter-recipes` and " @@ -2434,7 +2656,7 @@ msgstr "" "recipes` e adapte-os às suas necessidades. (Contribuição de Erlend E. " "Aasland em :gh:`90016`.)" -#: ../../whatsnew/3.12.rst:1275 +#: ../../whatsnew/3.12.rst:1283 msgid "" "In :meth:`~sqlite3.Cursor.execute`, :exc:`DeprecationWarning` is now emitted " "when :ref:`named placeholders ` are used together with " @@ -2451,7 +2673,7 @@ msgstr "" "`~sqlite3.ProgrammingError`. (Contribuição de Erlend E. Aasland em :gh:" "`101698`.)" -#: ../../whatsnew/3.12.rst:1282 +#: ../../whatsnew/3.12.rst:1290 msgid "" ":mod:`sys`: The :data:`sys.last_type`, :data:`sys.last_value` and :data:`sys." "last_traceback` fields are deprecated. Use :data:`sys.last_exc` instead. " @@ -2461,7 +2683,7 @@ msgstr "" "`sys.last_traceback` foram descontinuados. Use :data:`sys.last_exc` em vez " "disso. (Contribuição de Irit Katriel em :gh:`102778`.)" -#: ../../whatsnew/3.12.rst:1286 +#: ../../whatsnew/3.12.rst:1294 msgid "" ":mod:`tarfile`: Extracting tar archives without specifying *filter* is " "deprecated until Python 3.14, when ``'data'`` filter will become the " @@ -2471,11 +2693,12 @@ msgstr "" "descontinuado até Python 3.14, quando o filtro ``'data'`` se tornará o " "padrão. Veja :ref:`tarfile-extraction-filter` para detalhes." -#: ../../whatsnew/3.12.rst:1290 +#: ../../whatsnew/3.12.rst:1298 +#: ../../deprecations/pending-removal-in-3.15.rst:80 msgid ":mod:`typing`:" msgstr ":mod:`typing`:" -#: ../../whatsnew/3.12.rst:1292 +#: ../../whatsnew/3.12.rst:1300 msgid "" ":class:`typing.Hashable` and :class:`typing.Sized`, aliases for :class:" "`collections.abc.Hashable` and :class:`collections.abc.Sized` respectively, " @@ -2485,7 +2708,7 @@ msgstr "" "`collections.abc.Hashable` e :class:`collections.abc.Sized` respectivamente, " "foram descontinuados. (:gh:`94309`.)" -#: ../../whatsnew/3.12.rst:1296 +#: ../../whatsnew/3.12.rst:1304 msgid "" ":class:`typing.ByteString`, deprecated since Python 3.9, now causes a :exc:" "`DeprecationWarning` to be emitted when it is used. (Contributed by Alex " @@ -2495,7 +2718,7 @@ msgstr "" "que um :exc:`DeprecationWarning` seja emitida quando é usado. (Contribuição " "de Alex Waygood em :gh:`91896`.)" -#: ../../whatsnew/3.12.rst:1300 +#: ../../whatsnew/3.12.rst:1308 msgid "" ":mod:`xml.etree.ElementTree`: The module now emits :exc:`DeprecationWarning` " "when testing the truth value of an :class:`xml.etree.ElementTree.Element`. " @@ -2507,7 +2730,7 @@ msgstr "" "Antes, a implementação Python emitia :exc:`FutureWarning`, e a implementação " "C não emitia nada. (Contribuição de Jacob Walls em :gh:`83122`.)" -#: ../../whatsnew/3.12.rst:1306 +#: ../../whatsnew/3.12.rst:1314 msgid "" "The 3-arg signatures (type, value, traceback) of :meth:`coroutine throw() " "`, :meth:`generator throw() ` and :meth:" @@ -2521,51 +2744,55 @@ msgstr "" "ser removidos em uma versão futura do Python. Use as versões de argumento " "único dessas funções. (Contribuição de Ofey Chan em :gh:`89874`.)" -#: ../../whatsnew/3.12.rst:1312 +#: ../../whatsnew/3.12.rst:1320 msgid "" -":exc:`DeprecationWarning` is now raised when ``__package__`` on a module " -"differs from ``__spec__.parent`` (previously it was :exc:`ImportWarning`). " -"(Contributed by Brett Cannon in :gh:`65961`.)" +":exc:`DeprecationWarning` is now raised when :attr:`~module.__package__` on " +"a module differs from :attr:`__spec__.parent ` (previously it was :exc:`ImportWarning`). (Contributed by Brett " +"Cannon in :gh:`65961`.)" msgstr "" -":exc:`DeprecationWarning` agora é levantada quando ``__package__`` em um " -"módulo difere de ``__spec__.parent`` (anteriormente era :exc:" -"`ImportWarning`). (Contribuição de Brett Cannon em :gh:`65961`.)" +":exc:`DeprecationWarning` agora é levantada quando :attr:`~module." +"__package__` em um módulo difere de :attr:`__spec__.parent ` (anteriormente era :exc:`ImportWarning`). " +"(Contribuição de Brett Cannon em :gh:`65961`.)" -#: ../../whatsnew/3.12.rst:1317 +#: ../../whatsnew/3.12.rst:1326 msgid "" -"Setting ``__package__`` or ``__cached__`` on a module is deprecated, and " -"will cease to be set or taken into consideration by the import system in " -"Python 3.14. (Contributed by Brett Cannon in :gh:`65961`.)" +"Setting :attr:`~module.__package__` or :attr:`~module.__cached__` on a " +"module is deprecated, and will cease to be set or taken into consideration " +"by the import system in Python 3.14. (Contributed by Brett Cannon in :gh:" +"`65961`.)" msgstr "" -"Definir ``__package__`` ou ``__cached__`` em um módulo foi descontinuado e " -"deixará de ser definido ou levado em consideração pelo sistema de importação " -"no Python 3.14. (Contribuição de Brett Cannon em :gh:`65961`.)" +"Definir :attr:`~module.__package__` ou :attr:`~module.__cached__` em um " +"módulo foi descontinuado e deixará de ser definido ou levado em consideração " +"pelo sistema de importação no Python 3.14. (Contribuição de Brett Cannon em :" +"gh:`65961`.)" -#: ../../whatsnew/3.12.rst:1321 +#: ../../whatsnew/3.12.rst:1330 msgid "" "The bitwise inversion operator (``~``) on bool is deprecated. It will throw " -"an error in Python 3.14. Use ``not`` for logical negation of bools instead. " +"an error in Python 3.16. Use ``not`` for logical negation of bools instead. " "In the rare case that you really need the bitwise inversion of the " "underlying ``int``, convert to int explicitly: ``~int(x)``. (Contributed by " "Tim Hoffmann in :gh:`103487`.)" msgstr "" "O operador de inversão bit a bit (``~``) em bool foi descontinuado. Isso " -"levantará um erro no Python 3.14. Use ``not`` para negação lógica de bools. " +"levantará um erro no Python 3.16. Use ``not`` para negação lógica de bools. " "No raro caso em que você realmente precisa da inversão bit a bit do ``int`` " "subjacente, converta para int explicitamente: ``~int(x)``. (Contribuição de " "Tim Hoffmann em :gh:`103487`.)" -#: ../../whatsnew/3.12.rst:1327 +#: ../../whatsnew/3.12.rst:1336 msgid "" "Accessing :attr:`~codeobject.co_lnotab` on code objects was deprecated in " "Python 3.10 via :pep:`626`, but it only got a proper :exc:" -"`DeprecationWarning` in 3.12, therefore it will be removed in 3.14. " -"(Contributed by Nikita Sobolev in :gh:`101866`.)" +"`DeprecationWarning` in 3.12. May be removed in 3.15. (Contributed by Nikita " +"Sobolev in :gh:`101866`.)" msgstr "" "Acessar :attr:`~codeobject.co_lnotab` em objetos de código foi descontinuado " "no Python 3.10 via :pep:`626`, mas só obteve um :exc:`DeprecationWarning` " -"adequado em 3.12, portanto será removido em 3.14. (Contribuição de Nikita " -"Sobolev em :gh:`101866`.)" +"adequado em 3.12. Pode ser removido em 3.15. (Contribuição de Nikita Sobolev " +"em :gh:`101866`.)" #: ../../deprecations/pending-removal-in-3.13.rst:2 msgid "Pending Removal in Python 3.13" @@ -2733,11 +2960,11 @@ msgstr "``read_text()``" #: ../../deprecations/pending-removal-in-3.13.rst:51 msgid "" -"Use :func:`importlib.resources.files()` instead. Refer to `importlib-" +"Use :func:`importlib.resources.files` instead. Refer to `importlib-" "resources: Migrating from Legacy `_ (:gh:`106531`)" msgstr "" -"Use :func:`importlib.resources.files()` em vez disso. Confira `importlib-" +"Use :func:`importlib.resources.files` em vez disso. Confira `importlib-" "resources: Migrando do legado `_ , em inglês (:gh:`106531`)" @@ -2752,7 +2979,7 @@ msgid "" "since Python 3.8, now cause a :exc:`DeprecationWarning` to be emitted at " "runtime when they are accessed or used, and will be removed in Python 3.14:" msgstr "" -":mod:`ast`: Os seguintes recursos foram descontinuados na documentação desde " +":mod:`ast`: os seguintes recursos foram descontinuados na documentação desde " "Python 3.8, agora fazem com que um :exc:`DeprecationWarning` seja emitido em " "tempo de execução quando eles são acessados ou usados, e serão removidos no " "Python 3.14:" @@ -2791,18 +3018,10 @@ msgstr "" "localtime`. (Contribuição de Alan Williams em :gh:`72346`.)" #: ../../deprecations/pending-removal-in-3.14.rst:50 -msgid "" -":mod:`importlib`: ``__package__`` and ``__cached__`` will cease to be set or " -"taken into consideration by the import system (:gh:`97879`)." -msgstr "" -":mod:`importlib`: ``__package__`` e ``__cached__`` deixarão de ser definidos " -"ou levados em consideração pelo sistema de importação (:gh:`97879`)." - -#: ../../deprecations/pending-removal-in-3.14.rst:53 msgid ":mod:`importlib.abc` deprecated classes:" msgstr ":mod:`importlib.abc` descontinuou as classes:" -#: ../../deprecations/pending-removal-in-3.14.rst:66 +#: ../../deprecations/pending-removal-in-3.14.rst:63 msgid "" ":mod:`itertools` had undocumented, inefficient, historically buggy, and " "inconsistent support for copy, deepcopy, and pickle operations. This will be " @@ -2815,7 +3034,7 @@ msgstr "" "significativa no volume de código e na carga de manutenção. (Contribuição de " "Raymond Hettinger em :gh:`101588`.)" -#: ../../deprecations/pending-removal-in-3.14.rst:72 +#: ../../deprecations/pending-removal-in-3.14.rst:69 msgid "" ":mod:`multiprocessing`: The default start method will change to a safer one " "on Linux, BSDs, and other non-macOS POSIX platforms where ``'fork'`` is " @@ -2825,7 +3044,7 @@ msgid "" "set_start_method` APIs to explicitly specify when your code *requires* " "``'fork'``. See :ref:`multiprocessing-start-methods`." msgstr "" -":mod:`multiprocessing`: O método de inicialização padrão será alterado para " +":mod:`multiprocessing`: o método de inicialização padrão será alterado para " "um mais seguro no Linux, BSDs e outras plataformas POSIX não-macOS onde " "``'fork'`` é atualmente o padrão (:gh:`84559`). Adicionar um aviso de tempo " "de execução sobre isso foi considerado muito perturbador, pois não se espera " @@ -2834,7 +3053,7 @@ msgstr "" "explicitamente quando seu código *requer* ``'fork'``. Veja :ref:" "`multiprocessing-start-methods`." -#: ../../deprecations/pending-removal-in-3.14.rst:80 +#: ../../deprecations/pending-removal-in-3.14.rst:77 msgid "" ":mod:`pathlib`: :meth:`~pathlib.PurePath.is_relative_to` and :meth:`~pathlib." "PurePath.relative_to`: passing additional arguments is deprecated." @@ -2842,7 +3061,7 @@ msgstr "" ":mod:`pathlib`: :meth:`~pathlib.PurePath.is_relative_to` e :meth:`~pathlib." "PurePath.relative_to`: passar argumentos adicionais foi descontinuado." -#: ../../deprecations/pending-removal-in-3.14.rst:84 +#: ../../deprecations/pending-removal-in-3.14.rst:81 msgid "" ":mod:`pkgutil`: :func:`~pkgutil.find_loader` and :func:`~pkgutil.get_loader` " "now raise :exc:`DeprecationWarning`; use :func:`importlib.util.find_spec` " @@ -2852,53 +3071,33 @@ msgstr "" "agora levantam :exc:`DeprecationWarning`; use :func:`importlib.util." "find_spec` em vez disto. (Contribuição de Nikita Sobolev em :gh:`97850`.)" -#: ../../deprecations/pending-removal-in-3.14.rst:89 +#: ../../deprecations/pending-removal-in-3.14.rst:86 msgid ":mod:`pty`:" msgstr ":mod:`pty`:" -#: ../../deprecations/pending-removal-in-3.14.rst:91 +#: ../../deprecations/pending-removal-in-3.14.rst:88 msgid "``master_open()``: use :func:`pty.openpty`." msgstr "``master_open()``: use :func:`pty.openpty`." -#: ../../deprecations/pending-removal-in-3.14.rst:92 +#: ../../deprecations/pending-removal-in-3.14.rst:89 msgid "``slave_open()``: use :func:`pty.openpty`." msgstr "``slave_open()``: use :func:`pty.openpty`." -#: ../../deprecations/pending-removal-in-3.14.rst:96 +#: ../../deprecations/pending-removal-in-3.14.rst:93 msgid ":data:`~sqlite3.version` and :data:`~sqlite3.version_info`." msgstr ":data:`~sqlite3.version` e :data:`~sqlite3.version_info`." -#: ../../deprecations/pending-removal-in-3.14.rst:98 +#: ../../deprecations/pending-removal-in-3.14.rst:95 msgid "" ":meth:`~sqlite3.Cursor.execute` and :meth:`~sqlite3.Cursor.executemany` if :" "ref:`named placeholders ` are used and *parameters* is " "a sequence instead of a :class:`dict`." msgstr "" ":meth:`~sqlite3.Cursor.execute` e :meth:`~sqlite3.Cursor.executemany` se :" -"ref:`espaços reservados nomeados ` forem usados ​​e " +"ref:`espaços reservados nomeados ` forem usados e " "*parameters* for uma sequência em vez de um :class:`dict` ." -#: ../../deprecations/pending-removal-in-3.14.rst:102 -msgid "" -"date and datetime adapter, date and timestamp converter: see the :mod:" -"`sqlite3` documentation for suggested replacement recipes." -msgstr "" -"adaptador de data e hora, conversor de registro de data e hora: veja a " -"documentação de :mod:`sqlite3` para receitas de substituição sugeridas." - -#: ../../deprecations/pending-removal-in-3.14.rst:105 -msgid "" -":class:`types.CodeType`: Accessing :attr:`~codeobject.co_lnotab` was " -"deprecated in :pep:`626` since 3.10 and was planned to be removed in 3.12, " -"but it only got a proper :exc:`DeprecationWarning` in 3.12. May be removed " -"in 3.14. (Contributed by Nikita Sobolev in :gh:`101866`.)" -msgstr "" -":class:`types.CodeType`: O acesso a :attr:`~codeobject.co_lnotab` foi " -"descontinuado na :pep:`626` desde 3.10 e foi planejado para ser removido em " -"3.12, mas só recebeu uma :exc:`DeprecationWarning` adequada em 3.12. Pode " -"ser removido em 3.14. (Contribuição de Nikita Sobolev em :gh:`101866`.)" - -#: ../../deprecations/pending-removal-in-3.14.rst:112 +#: ../../deprecations/pending-removal-in-3.14.rst:99 msgid "" ":mod:`typing`: :class:`~typing.ByteString`, deprecated since Python 3.9, now " "causes a :exc:`DeprecationWarning` to be emitted when it is used." @@ -2906,7 +3105,7 @@ msgstr "" ":mod:`typing`: :class:`~typing.ByteString`, descontinuado desde Python 3.9, " "agora faz com que uma :exc:`DeprecationWarning` seja emitida quando é usado." -#: ../../deprecations/pending-removal-in-3.14.rst:115 +#: ../../deprecations/pending-removal-in-3.14.rst:102 msgid "" ":mod:`urllib`: :class:`!urllib.parse.Quoter` is deprecated: it was not " "intended to be a public API. (Contributed by Gregory P. Smith in :gh:" @@ -2922,149 +3121,330 @@ msgid "Pending Removal in Python 3.15" msgstr "Remoção pendente no Python 3.15" #: ../../deprecations/pending-removal-in-3.15.rst:4 +#: ../../deprecations/pending-removal-in-3.16.rst:4 +msgid "The import system:" +msgstr "O sistema de importação:" + +#: ../../deprecations/pending-removal-in-3.15.rst:6 msgid "" -":class:`http.server.CGIHTTPRequestHandler` will be removed along with its " -"related ``--cgi`` flag to ``python -m http.server``. It was obsolete and " -"rarely used. No direct replacement exists. *Anything* is better than CGI " -"to interface a web server with a request handler." +"Setting :attr:`~module.__cached__` on a module while failing to set :attr:" +"`__spec__.cached ` is deprecated. In " +"Python 3.15, :attr:`!__cached__` will cease to be set or take into " +"consideration by the import system or standard library. (:gh:`97879`)" msgstr "" -":class:`http.server.CGIHTTPRequestHandler` será removido junto com seu " -"sinalizador relacionado ``--cgi`` para ``python -m http.server``. Estava " -"descontinuado e raramente usado. Não existe substituição direta. *Qualquer " -"coisa* é melhor que CGI para fazer a interface de um servidor web com um " -"manipulador de solicitações." +"A definição de :attr:`~module.__cached__` em um módulo enquanto falha na " +"definição de :attr:`__spec__.cached ` " +"está descontinuado. No Python 3.15, :attr:`!__cached__` deixará de ser " +"definido ou levado em consideração pelo sistema de importação ou pela " +"biblioteca padrão. (:gh:`97879`)" -#: ../../deprecations/pending-removal-in-3.15.rst:9 +#: ../../deprecations/pending-removal-in-3.15.rst:11 msgid "" -":class:`locale`: :func:`locale.getdefaultlocale` was deprecated in Python " -"3.11 and originally planned for removal in Python 3.13 (:gh:`90817`), but " -"removal has been postponed to Python 3.15. Use :func:`locale.setlocale()`, :" -"func:`locale.getencoding()` and :func:`locale.getlocale()` instead. " -"(Contributed by Hugo van Kemenade in :gh:`111187`.)" +"Setting :attr:`~module.__package__` on a module while failing to set :attr:" +"`__spec__.parent ` is deprecated. In " +"Python 3.15, :attr:`!__package__` will cease to be set or take into " +"consideration by the import system or standard library. (:gh:`97879`)" msgstr "" -":class:`locale`: :func:`locale.getdefaultlocale` foi descontinuada no Python " -"3.11 e originalmente planejada para remoção no Python 3.13 (:gh:`90817`), " -"mas a remoção foi adiada para o Python 3.15. Use :func:`locale." -"setlocale()`, :func:`locale.getencoding()` e :func:`locale.getlocale()` em " -"vez disso. (Contribuição de Hugo van Kemenade em :gh:`111187`.)" +"A definição de :attr:`~module.__package__` em um módulo enquanto falha na " +"definição de :attr:`__spec__.parent ` " +"está descontinuado. No Python 3.15, :attr:`!__package__` deixará de ser " +"definido ou levado em consideração pelo sistema de importação ou pela " +"biblioteca padrão. (:gh:`97879`)" #: ../../deprecations/pending-removal-in-3.15.rst:16 +msgid ":mod:`ctypes`:" +msgstr ":mod:`ctypes`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:18 msgid "" -":mod:`pathlib`: :meth:`pathlib.PurePath.is_reserved` is deprecated and " -"scheduled for removal in Python 3.15. Use :func:`os.path.isreserved` to " -"detect reserved paths on Windows." +"The undocumented :func:`!ctypes.SetPointerType` function has been deprecated " +"since Python 3.13." msgstr "" -":mod:`pathlib`: :meth:`pathlib.PurePath.is_reserved` está descontinuado e " -"agendado para remoção no Python 3.15. Use :func:`os.path.isreserved` para " -"detectar caminhos reservados no Windows." +"A função não documentada :func:`!ctypes.SetPointerType` foi descontinuada " +"desde o Python 3.13." #: ../../deprecations/pending-removal-in-3.15.rst:21 +msgid ":mod:`http.server`:" +msgstr ":mod:`http.server`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:23 msgid "" -":mod:`platform`: :func:`~platform.java_ver` is deprecated and will be " -"removed in 3.15. It was largely untested, had a confusing API, and was only " -"useful for Jython support. (Contributed by Nikita Sobolev in :gh:`116349`.)" +"The obsolete and rarely used :class:`~http.server.CGIHTTPRequestHandler` has " +"been deprecated since Python 3.13. No direct replacement exists. *Anything* " +"is better than CGI to interface a web server with a request handler." msgstr "" -":mod:`platform`: :func:`~platform.java_ver` está descontinuada e será " -"removida na versão 3.15. Ela não foi testada em grande parte, tinha uma API " -"confusa e só era útil para suporte a Jython. (Contribuição de Nikita Sobolev " -"em :gh:`116349`.)" +"A classe obsoleta e raramente usada :class:`~http.server." +"CGIHTTPRequestHandler` foi descontinuada desde o Python 3.13. Não existe " +"substituição direta. *Qualquer coisa* é melhor que CGI para fazer a " +"interface de um servidor web com um manipulador de requisição." -#: ../../deprecations/pending-removal-in-3.15.rst:27 +#: ../../deprecations/pending-removal-in-3.15.rst:29 msgid "" -":mod:`threading`: Passing any arguments to :func:`threading.RLock` is now " -"deprecated. C version allows any numbers of args and kwargs, but they are " -"just ignored. Python version does not allow any arguments. All arguments " -"will be removed from :func:`threading.RLock` in Python 3.15. (Contributed by " -"Nikita Sobolev in :gh:`102029`.)" +"The :option:`!--cgi` flag to the :program:`python -m http.server` command-" +"line interface has been deprecated since Python 3.13." msgstr "" -":mod:`threading`: Passar qualquer argumento para :func:`threading.RLock` " -"agora está descontinuado. A versão C permite qualquer número de args e " -"kwargs, mas eles são simplesmente ignorados. A versão Python não permite " -"nenhum argumento. Todos os argumentos serão removidos de :func:`threading." -"RLock` no Python 3.15. (Contribuição de Nikita Sobolev em :gh:`102029`.)" +"O sinalizador :option:`!--cgi` para a interface de linha de comando :program:" +"`python -m http.server` foi descontinuado desde o Python 3.13." + +#: ../../deprecations/pending-removal-in-3.15.rst:32 +#: ../../deprecations/pending-removal-in-future.rst:56 +msgid ":mod:`importlib`:" +msgstr ":mod:`importlib`:" #: ../../deprecations/pending-removal-in-3.15.rst:34 -msgid ":class:`typing.NamedTuple`:" -msgstr ":class:`typing.NamedTuple`:" +msgid "``load_module()`` method: use ``exec_module()`` instead." +msgstr "Método ``load_module()``: use ``exec_module()``." #: ../../deprecations/pending-removal-in-3.15.rst:36 +msgid ":class:`locale`:" +msgstr ":class:`locale`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:38 msgid "" -"The undocumented keyword argument syntax for creating :class:`!NamedTuple` " -"classes (``NT = NamedTuple(\"NT\", x=int)``) is deprecated, and will be " -"disallowed in 3.15. Use the class-based syntax or the functional syntax " -"instead." +"The :func:`~locale.getdefaultlocale` function has been deprecated since " +"Python 3.11. Its removal was originally planned for Python 3.13 (:gh:" +"`90817`), but has been postponed to Python 3.15. Use :func:`~locale." +"getlocale`, :func:`~locale.setlocale`, and :func:`~locale.getencoding` " +"instead. (Contributed by Hugo van Kemenade in :gh:`111187`.)" +msgstr "" +"A função :func:`~locale.getdefaultlocale` foi descontinuada desde o Python " +"3.11. Sua remoção foi planejada originalmente para o Python 3.13 (:gh:" +"`90817`), mas foi adiada para o Python 3.15. Em vez disso, use :func:" +"`~locale.getlocale`, :func:`~locale.setlocale` e :func:`~locale." +"getencoding`. (Contribuição de Hugo van Kemenade em :gh:`111187`.)" + +#: ../../deprecations/pending-removal-in-3.15.rst:46 +msgid ":mod:`pathlib`:" +msgstr ":mod:`pathlib`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:48 +msgid "" +":meth:`.PurePath.is_reserved` has been deprecated since Python 3.13. Use :" +"func:`os.path.isreserved` to detect reserved paths on Windows." msgstr "" -"A sintaxe de argumento nomeado não documentada para criar classes :class:`!" -"NamedTuple` (``NT = NamedTuple(\"NT\", x=int)``) está descontinuada e não " -"será permitida em 3.15. Use a sintaxe baseada em classe ou a sintaxe " -"funcional." - -#: ../../deprecations/pending-removal-in-3.15.rst:40 -msgid "" -"When using the functional syntax to create a :class:`!NamedTuple` class, " -"failing to pass a value to the *fields* parameter (``NT = " -"NamedTuple(\"NT\")``) is deprecated. Passing ``None`` to the *fields* " -"parameter (``NT = NamedTuple(\"NT\", None)``) is also deprecated. Both will " -"be disallowed in Python 3.15. To create a :class:`!NamedTuple` class with 0 " -"fields, use ``class NT(NamedTuple): pass`` or ``NT = NamedTuple(\"NT\", " -"[])``." -msgstr "" -"Ao usar a sintaxe funcional para criar uma classe :class:`!NamedTuple`, " -"falhar ao passar um valor para o parâmetro *fields* (``NT = " -"NamedTuple(\"NT\")``) está descontinuada. Passar ``None`` para o parâmetro " -"*fields* (``NT = NamedTuple(\"NT\", None)``) também está descontinuada. " -"Ambos não serão permitidos no Python 3.15. Para criar uma classe :class:`!" -"NamedTuple` com 0 campos, use ``class NT(NamedTuple): pass`` ou ``NT = " -"NamedTuple(\"NT\", [])``." - -#: ../../deprecations/pending-removal-in-3.15.rst:47 -msgid "" -":class:`typing.TypedDict`: When using the functional syntax to create a :" -"class:`!TypedDict` class, failing to pass a value to the *fields* parameter " -"(``TD = TypedDict(\"TD\")``) is deprecated. Passing ``None`` to the *fields* " -"parameter (``TD = TypedDict(\"TD\", None)``) is also deprecated. Both will " -"be disallowed in Python 3.15. To create a :class:`!TypedDict` class with 0 " -"fields, use ``class TD(TypedDict): pass`` or ``TD = TypedDict(\"TD\", {})``." -msgstr "" -":class:`typing.TypedDict`: Ao usar a sintaxe funcional para criar uma " -"classe :class:`!TypedDict`, falhar ao passar um valor para o parâmetro " -"*fields* (``TD = TypedDict(\"TD\")``) está descontinuada. Passar ``None`` " -"para o parâmetro *fields* (``TD = TypedDict(\"TD\", None)``) também está " -"descontinuada. Ambos não serão permitidos no Python 3.15. Para criar uma " -"classe :class:`!TypedDict` com 0 campos, use ``class TD(TypedDict): pass`` " -"ou ``TD = TypedDict(\"TD\", {})``." +":meth:`.PurePath.is_reserved` foi descontinuado desde o Python 3.13. Use :" +"func:`os.path.isreserved` para detectar caminhos reservados no Windows." + +#: ../../deprecations/pending-removal-in-3.15.rst:52 +msgid ":mod:`platform`:" +msgstr ":mod:`platform`:" #: ../../deprecations/pending-removal-in-3.15.rst:54 msgid "" -":mod:`wave`: Deprecate the ``getmark()``, ``setmark()`` and ``getmarkers()`` " -"methods of the :class:`wave.Wave_read` and :class:`wave.Wave_write` classes. " -"They will be removed in Python 3.15. (Contributed by Victor Stinner in :gh:" -"`105096`.)" +":func:`~platform.java_ver` has been deprecated since Python 3.13. This " +"function is only useful for Jython support, has a confusing API, and is " +"largely untested." +msgstr "" +":func:`~platform.java_ver` foi descontinuada desde o Python 3.13. Esta " +"função é útil apenas para suporte Jython, tem uma API confusa e é amplamente " +"não testada." + +#: ../../deprecations/pending-removal-in-3.15.rst:58 +msgid ":mod:`sysconfig`:" +msgstr ":mod:`sysconfig`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:60 +msgid "" +"The *check_home* argument of :func:`sysconfig.is_python_build` has been " +"deprecated since Python 3.12." +msgstr "" +"O argumento *check_home* de :func:`sysconfig.is_python_build` foi " +"descontinuado desde o Python 3.12." + +#: ../../deprecations/pending-removal-in-3.15.rst:63 +msgid ":mod:`threading`:" +msgstr ":mod:`threading`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:65 +msgid "" +":func:`~threading.RLock` will take no arguments in Python 3.15. Passing any " +"arguments has been deprecated since Python 3.14, as the Python version does " +"not permit any arguments, but the C version allows any number of positional " +"or keyword arguments, ignoring every argument." +msgstr "" +":func:`~threading.RLock` não aceitará argumentos no Python 3.15. A passagem " +"quaisquer argumentos foi descontinuada desde o Python 3.14, pois a versão " +"Python não permite nenhum argumento, mas a versão C permite qualquer número " +"de argumentos posicionais ou nomeados, ignorando todos os argumentos." + +#: ../../deprecations/pending-removal-in-3.15.rst:71 +msgid ":mod:`types`:" +msgstr ":mod:`types`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:73 +msgid "" +":class:`types.CodeType`: Accessing :attr:`~codeobject.co_lnotab` was " +"deprecated in :pep:`626` since 3.10 and was planned to be removed in 3.12, " +"but it only got a proper :exc:`DeprecationWarning` in 3.12. May be removed " +"in 3.15. (Contributed by Nikita Sobolev in :gh:`101866`.)" +msgstr "" +":class:`types.CodeType`: o acesso a :attr:`~codeobject.co_lnotab` foi " +"descontinuado na :pep:`626` desde 3.10 e foi planejado para ser removido em " +"3.12, mas só recebeu uma :exc:`DeprecationWarning` adequada em 3.12. Pode " +"ser removido em 3.15. (Contribuição de Nikita Sobolev em :gh:`101866`.)" + +#: ../../deprecations/pending-removal-in-3.15.rst:82 +msgid "" +"The undocumented keyword argument syntax for creating :class:`~typing." +"NamedTuple` classes (e.g. ``Point = NamedTuple(\"Point\", x=int, y=int)``) " +"has been deprecated since Python 3.13. Use the class-based syntax or the " +"functional syntax instead." +msgstr "" +"A sintaxe de argumento nomeado não documentada para criar classes :class:" +"`~typing.NamedTuple` (por exemplo, ``Point = NamedTuple(\"Point\", x=int, " +"y=int)``) foi descontinuada desde o Python 3.13. Use a sintaxe baseada em " +"classe ou a sintaxe funcional em vez disso." + +#: ../../deprecations/pending-removal-in-3.15.rst:88 +msgid "" +"When using the functional syntax of :class:`~typing.TypedDict`\\s, failing " +"to pass a value to the *fields* parameter (``TD = TypedDict(\"TD\")``) or " +"passing ``None`` (``TD = TypedDict(\"TD\", None)``) has been deprecated " +"since Python 3.13. Use ``class TD(TypedDict): pass`` or ``TD = " +"TypedDict(\"TD\", {})`` to create a TypedDict with zero field." +msgstr "" +"Ao usar a sintaxe funcional de :class:`~typing.TypedDict`\\s, não passar um " +"valor para o parâmetro *fields* (``TD = TypedDict(\"TD\")``) ou passar " +"``None`` (``TD = TypedDict(\"TD\", None)``) foi está descontinuado desde o " +"Python 3.13. Use ``class TD(TypedDict): pass`` ou ``TD = TypedDict(\"TD\", " +"{})`` para criar uma classe TypedDict com nenhum campo." + +#: ../../deprecations/pending-removal-in-3.15.rst:95 +msgid "" +"The :func:`typing.no_type_check_decorator` decorator function has been " +"deprecated since Python 3.13. After eight years in the :mod:`typing` module, " +"it has yet to be supported by any major type checker." +msgstr "" +"A função decoradora :func:`typing.no_type_check_decorator` foi descontinuada " +"desde o Python 3.13. Após oito anos no módulo :mod:`typing`, ela ainda não " +"foi suportada por nenhum verificador de tipo importante." + +#: ../../deprecations/pending-removal-in-3.15.rst:100 +msgid ":mod:`wave`:" +msgstr ":mod:`wave`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:102 +msgid "" +"The :meth:`~wave.Wave_read.getmark`, :meth:`!setmark`, and :meth:`~wave." +"Wave_read.getmarkers` methods of the :class:`~wave.Wave_read` and :class:" +"`~wave.Wave_write` classes have been deprecated since Python 3.13." msgstr "" -":mod:`wave`: Descontinua os métodos ``getmark()``, ``setmark()`` e " -"``getmarkers()`` das classes :class:`wave.Wave_read` e :class:`wave." -"Wave_write`. Eles serão removidos no Python 3.15. (Contribuição de Victor " -"Stinner em :gh:`105096`.)" +"Os métodos :meth:`~wave.Wave_read.getmark`, :meth:`!setmark` e :meth:`~wave." +"Wave_read.getmarkers` das classes :class:`~wave.Wave_read` e :class:`~wave." +"Wave_write` foram descontinuados desde o Python 3.13." #: ../../deprecations/pending-removal-in-3.16.rst:2 -msgid "Pending Removal in Python 3.16" +msgid "Pending removal in Python 3.16" msgstr "Remoção pendente no Python 3.16" -#: ../../deprecations/pending-removal-in-3.16.rst:4 +#: ../../deprecations/pending-removal-in-3.16.rst:6 +msgid "" +"Setting :attr:`~module.__loader__` on a module while failing to set :attr:" +"`__spec__.loader ` is deprecated. In " +"Python 3.16, :attr:`!__loader__` will cease to be set or taken into " +"consideration by the import system or the standard library." +msgstr "" +"A definição de :attr:`~module.__loader__` em um módulo enquanto falha na " +"definição de :attr:`__spec__.loader ` " +"está descontinuado. No Python 3.16, :attr:`!__loader__` deixará de ser " +"definido ou levado em consideração pelo sistema de importação ou pela " +"biblioteca padrão." + +#: ../../deprecations/pending-removal-in-3.16.rst:11 +msgid ":mod:`array`:" +msgstr ":mod:`array`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:13 +msgid "" +"The ``'u'`` format code (:c:type:`wchar_t`) has been deprecated in " +"documentation since Python 3.3 and at runtime since Python 3.13. Use the " +"``'w'`` format code (:c:type:`Py_UCS4`) for Unicode characters instead." +msgstr "" +"O código de formato ``'u'`` (:c:type:`wchar_t`) foi descontinuado na " +"documentação desde o Python 3.3 e do ambiente de execução desde o Python " +"3.13. Em vez disso, use o código de formato ``'w'`` (:c:type:`Py_UCS4`) para " +"caracteres Unicode." + +#: ../../deprecations/pending-removal-in-3.16.rst:21 +msgid "" +":func:`!asyncio.iscoroutinefunction` is deprecated and will be removed in " +"Python 3.16, use :func:`inspect.iscoroutinefunction` instead. (Contributed " +"by Jiahao Li and Kumar Aditya in :gh:`122875`.)" +msgstr "" +":func:`!asyncio.iscoroutinefunction` foi descontinuado e será removido no " +"Python 3.16, use :func:`inspect.iscoroutinefunction` em vez disso. " +"(Contribuição de Jiahao Li e Kumar Aditya em :gh:`122875`.)" + +#: ../../deprecations/pending-removal-in-3.16.rst:26 +#: ../../deprecations/pending-removal-in-future.rst:10 +msgid ":mod:`builtins`:" +msgstr ":mod:`builtins`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:28 +msgid "" +"Bitwise inversion on boolean types, ``~True`` or ``~False`` has been " +"deprecated since Python 3.12, as it produces surprising and unintuitive " +"results (``-2`` and ``-1``). Use ``not x`` instead for the logical negation " +"of a Boolean. In the rare case that you need the bitwise inversion of the " +"underlying integer, convert to ``int`` explicitly (``~int(x)``)." +msgstr "" +"A inversão bit a bit em tipos booleanos, ``~True`` ou ``~False`` foi " +"descontinuada desde o Python 3.12, pois produz resultados surpreendentes e " +"não intuitivos (``-2`` e ``-1``). Em vez disso, use ``not x`` para a negação " +"lógica de um booleano. No caso raro de você precisar da inversão bit a bit " +"do inteiro subjacente, converta para ``int`` explicitamente (``~int(x)``)." + +#: ../../deprecations/pending-removal-in-3.16.rst:35 +msgid ":mod:`shutil`:" +msgstr ":mod:`shutil`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:37 +msgid "" +"The :class:`!ExecError` exception has been deprecated since Python 3.14. It " +"has not been used by any function in :mod:`!shutil` since Python 3.4, and is " +"now an alias of :exc:`RuntimeError`." +msgstr "" +"A exceção :class:`!ExecError` foi descontinuada desde o Python 3.14. Ela não " +"foi usada por nenhuma função em :mod:`!shutil` desde o Python 3.4, e agora é " +"um alias de :exc:`RuntimeError`." + +#: ../../deprecations/pending-removal-in-3.16.rst:42 +msgid ":mod:`symtable`:" +msgstr ":mod:`symtable`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:44 +msgid "" +"The :meth:`Class.get_methods ` method has been " +"deprecated since Python 3.14." +msgstr "" +"O método :meth:`Class.get_methods ` foi " +"descontinuado desde o Python 3.14." + +#: ../../deprecations/pending-removal-in-3.16.rst:47 +msgid ":mod:`sys`:" +msgstr ":mod:`sys`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:49 msgid "" -":mod:`array`: :class:`array.array` ``'u'`` type (:c:type:`wchar_t`): use the " -"``'w'`` type instead (``Py_UCS4``)." +"The :func:`~sys._enablelegacywindowsfsencoding` function has been deprecated " +"since Python 3.13. Use the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` " +"environment variable instead." msgstr "" -":mod:`array`: :class:`array.array`: tipo ``'u'`` (:c:type:`wchar_t`): use o " -"tipo ``'w'`` (``Py_UCS4``)." +"A função :func:`~sys._enablelegacywindowsfsencoding` foi descontinuada desde " +"o Python 3.13. Em vez disso, use a variável de ambiente :envvar:" +"`PYTHONLEGACYWINDOWSFSENCODING`." -#: ../../deprecations/pending-removal-in-3.16.rst:8 +#: ../../deprecations/pending-removal-in-3.16.rst:53 +msgid ":mod:`tarfile`:" +msgstr ":mod:`tarfile`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:55 msgid "" -":mod:`symtable`: Deprecate :meth:`symtable.Class.get_methods` due to the " -"lack of interest. (Contributed by Bénédikt Tran in :gh:`119698`.)" +"The undocumented and unused :attr:`!TarFile.tarfile` attribute has been " +"deprecated since Python 3.13." msgstr "" -":mod:`symtable`: Descontinua :meth:`symtable.Class.get_methods` por falta de " -"interesse. (Contribuição de Bénédikt Tran em :gh:`119698`.)" +"O atributo não documentado e não utilizado :attr:`!TarFile.tarfile` foi " +"descontinuado desde o Python 3.13." #: ../../deprecations/c-api-pending-removal-in-future.rst:2 #: ../../deprecations/pending-removal-in-future.rst:2 @@ -3087,33 +3467,21 @@ msgstr "" ":mod:`argparse`: O aninhamento de grupos de argumentos e o aninhamento de " "grupos mutuamente exclusivos estão descontinuados." -#: ../../deprecations/pending-removal-in-future.rst:10 -msgid ":mod:`array`'s ``'u'`` format code (:gh:`57281`)" -msgstr "código de formatação ``'u'`` do :mod:`array` (:gh:`57281`)" - #: ../../deprecations/pending-removal-in-future.rst:12 -msgid ":mod:`builtins`:" -msgstr ":mod:`builtins`:" - -#: ../../deprecations/pending-removal-in-future.rst:14 -msgid "``~bool``, bitwise inversion on bool." -msgstr "``~bool``, inversão bit a bit em booleanos." - -#: ../../deprecations/pending-removal-in-future.rst:15 msgid "``bool(NotImplemented)``." msgstr "``bool(NotImplemented)``." -#: ../../deprecations/pending-removal-in-future.rst:16 +#: ../../deprecations/pending-removal-in-future.rst:13 msgid "" "Generators: ``throw(type, exc, tb)`` and ``athrow(type, exc, tb)`` signature " "is deprecated: use ``throw(exc)`` and ``athrow(exc)`` instead, the single " "argument signature." msgstr "" -"Geradores: A assinatura ``throw(type, exc, tb)`` e ``athrow(type, exc, tb)`` " +"Geradores: a assinatura ``throw(type, exc, tb)`` e ``athrow(type, exc, tb)`` " "está descontinuada: use ``throw(exc)`` e ``athrow(exc)``, a assinatura do " "argumento único." -#: ../../deprecations/pending-removal-in-future.rst:19 +#: ../../deprecations/pending-removal-in-future.rst:16 msgid "" "Currently Python accepts numeric literals immediately followed by keywords, " "for example ``0in x``, ``1or x``, ``0if 1else 2``. It allows confusing and " @@ -3134,7 +3502,7 @@ msgstr "" "e :keyword:`or`. Em uma versão futura, será alterado para um erro de " "sintaxe. (:gh:`87999`)" -#: ../../deprecations/pending-removal-in-future.rst:27 +#: ../../deprecations/pending-removal-in-future.rst:24 msgid "" "Support for ``__index__()`` and ``__int__()`` method returning non-int type: " "these methods will be required to return an instance of a strict subclass " @@ -3144,7 +3512,7 @@ msgstr "" "int: esses métodos serão necessários para retornar uma instância de uma " "subclasse estrita de :class:`int`." -#: ../../deprecations/pending-removal-in-future.rst:30 +#: ../../deprecations/pending-removal-in-future.rst:27 msgid "" "Support for ``__float__()`` method returning a strict subclass of :class:" "`float`: these methods will be required to return an instance of :class:" @@ -3154,7 +3522,7 @@ msgstr "" "class:`float`: esses métodos serão necessários para retornar uma instância " "de :class:`float`." -#: ../../deprecations/pending-removal-in-future.rst:33 +#: ../../deprecations/pending-removal-in-future.rst:30 msgid "" "Support for ``__complex__()`` method returning a strict subclass of :class:" "`complex`: these methods will be required to return an instance of :class:" @@ -3164,11 +3532,11 @@ msgstr "" "class:`complex`: esses métodos serão necessários para retornar uma instância " "de :class:`complex`." -#: ../../deprecations/pending-removal-in-future.rst:36 +#: ../../deprecations/pending-removal-in-future.rst:33 msgid "Delegation of ``int()`` to ``__trunc__()`` method." msgstr "Delegação do método ``int()`` para o ``__trunc__()``." -#: ../../deprecations/pending-removal-in-future.rst:37 +#: ../../deprecations/pending-removal-in-future.rst:34 msgid "" "Passing a complex number as the *real* or *imag* argument in the :func:" "`complex` constructor is now deprecated; it should only be passed as a " @@ -3180,18 +3548,18 @@ msgstr "" "único argumento posicional. (Contribuição de Serhiy Storchaka em :gh:" "`109218`.)" -#: ../../deprecations/pending-removal-in-future.rst:47 +#: ../../deprecations/pending-removal-in-future.rst:44 msgid "" ":attr:`codeobject.co_lnotab`: use the :meth:`codeobject.co_lines` method " "instead." msgstr "" ":attr:`codeobject.co_lnotab`: use o método :meth:`codeobject.co_lines`." -#: ../../deprecations/pending-removal-in-future.rst:50 +#: ../../deprecations/pending-removal-in-future.rst:47 msgid ":mod:`datetime`:" msgstr ":mod:`datetime`:" -#: ../../deprecations/pending-removal-in-future.rst:52 +#: ../../deprecations/pending-removal-in-future.rst:49 msgid "" ":meth:`~datetime.datetime.utcnow`: use ``datetime.datetime.now(tz=datetime." "UTC)``." @@ -3199,7 +3567,7 @@ msgstr "" ":meth:`~datetime.datetime.utcnow`: use ``datetime.datetime.now(tz=datetime." "UTC)``." -#: ../../deprecations/pending-removal-in-future.rst:54 +#: ../../deprecations/pending-removal-in-future.rst:51 msgid "" ":meth:`~datetime.datetime.utcfromtimestamp`: use ``datetime.datetime." "fromtimestamp(timestamp, tz=datetime.UTC)``." @@ -3207,68 +3575,60 @@ msgstr "" ":meth:`~datetime.datetime.utcfromtimestamp`: use ``datetime.datetime." "fromtimestamp(timestamp, tz=datetime.UTC)``." -#: ../../deprecations/pending-removal-in-future.rst:57 +#: ../../deprecations/pending-removal-in-future.rst:54 msgid ":mod:`gettext`: Plural value must be an integer." -msgstr ":mod:`gettext`: O valor de plural deve ser um número inteiro." - -#: ../../deprecations/pending-removal-in-future.rst:59 -msgid ":mod:`importlib`:" -msgstr ":mod:`importlib`:" - -#: ../../deprecations/pending-removal-in-future.rst:61 -msgid "``load_module()`` method: use ``exec_module()`` instead." -msgstr "Método ``load_module()``: use ``exec_module()`` em vez disso." +msgstr ":mod:`gettext`: o valor de plural deve ser um número inteiro." -#: ../../deprecations/pending-removal-in-future.rst:62 +#: ../../deprecations/pending-removal-in-future.rst:58 msgid "" ":func:`~importlib.util.cache_from_source` *debug_override* parameter is " "deprecated: use the *optimization* parameter instead." msgstr "" "O parâmetro *debug_override* de :func:`~importlib.util.cache_from_source` " -"foi descontinuado: em vez disso, use o parâmetro *optimization*." +"foi descontinuado: use o parâmetro *optimization*." -#: ../../deprecations/pending-removal-in-future.rst:65 +#: ../../deprecations/pending-removal-in-future.rst:61 msgid ":mod:`importlib.metadata`:" msgstr ":mod:`importlib.metadata`:" -#: ../../deprecations/pending-removal-in-future.rst:67 +#: ../../deprecations/pending-removal-in-future.rst:63 msgid "``EntryPoints`` tuple interface." msgstr "Interface de tupla ``EntryPoints``." -#: ../../deprecations/pending-removal-in-future.rst:68 +#: ../../deprecations/pending-removal-in-future.rst:64 msgid "Implicit ``None`` on return values." msgstr "``None`` implícito nos valores de retorno." -#: ../../deprecations/pending-removal-in-future.rst:70 +#: ../../deprecations/pending-removal-in-future.rst:66 msgid "" ":mod:`logging`: the ``warn()`` method has been deprecated since Python 3.3, " -"use :meth:`~logging.warning()` instead." +"use :meth:`~logging.warning` instead." msgstr "" ":mod:`logging`: o método ``warn()`` foi descontinuado desde o Python 3.3, " -"use :meth:`~logging.warning()`." +"use :meth:`~logging.warning`." -#: ../../deprecations/pending-removal-in-future.rst:73 +#: ../../deprecations/pending-removal-in-future.rst:69 msgid "" ":mod:`mailbox`: Use of StringIO input and text mode is deprecated, use " "BytesIO and binary mode instead." msgstr "" -":mod:`mailbox`: O uso da entrada StringIO e do modo de texto foi " +":mod:`mailbox`: o uso da entrada StringIO e do modo de texto foi " "descontinuado; em vez disso, use BytesIO e o modo binário." -#: ../../deprecations/pending-removal-in-future.rst:76 +#: ../../deprecations/pending-removal-in-future.rst:72 msgid "" ":mod:`os`: Calling :func:`os.register_at_fork` in multi-threaded process." -msgstr ":mod:`os`: Chamar :func:`os.register_at_fork` em processo multithread." +msgstr ":mod:`os`: chame :func:`os.register_at_fork` em processo multithread." -#: ../../deprecations/pending-removal-in-future.rst:78 +#: ../../deprecations/pending-removal-in-future.rst:74 msgid "" ":class:`!pydoc.ErrorDuringImport`: A tuple value for *exc_info* parameter is " "deprecated, use an exception instance." msgstr "" -":class:`!pydoc.ErrorDuringImport`: Um valor de tupla para o parâmetro " +":class:`!pydoc.ErrorDuringImport`: um valor de tupla para o parâmetro " "*exc_info* foi descontinuado, use uma instância de exceção." -#: ../../deprecations/pending-removal-in-future.rst:81 +#: ../../deprecations/pending-removal-in-future.rst:77 msgid "" ":mod:`re`: More strict rules are now applied for numerical group references " "and group names in regular expressions. Only sequence of ASCII digits is " @@ -3276,96 +3636,88 @@ msgid "" "replacement strings can now only contain ASCII letters and digits and " "underscore. (Contributed by Serhiy Storchaka in :gh:`91760`.)" msgstr "" -":mod:`re`: Regras mais rigorosas agora são aplicadas para referências " +":mod:`re`: regras mais rigorosas agora são aplicadas para referências " "numéricas de grupos e nomes de grupos em expressões regulares. Apenas a " "sequência de dígitos ASCII agora é aceita como referência numérica. O nome " "do grupo em padrões de bytes e strings de substituição agora pode conter " "apenas letras e dígitos ASCII e sublinhado. (Contribuição de Serhiy " "Storchaka em :gh:`91760`.)" -#: ../../deprecations/pending-removal-in-future.rst:88 +#: ../../deprecations/pending-removal-in-future.rst:84 msgid "" ":mod:`!sre_compile`, :mod:`!sre_constants` and :mod:`!sre_parse` modules." msgstr "" "Módulos :mod:`!sre_compile`, :mod:`!sre_constants` e :mod:`!sre_parse`." -#: ../../deprecations/pending-removal-in-future.rst:90 +#: ../../deprecations/pending-removal-in-future.rst:86 msgid "" ":mod:`shutil`: :func:`~shutil.rmtree`'s *onerror* parameter is deprecated in " "Python 3.12; use the *onexc* parameter instead." msgstr "" -":mod:`shutil`: O parâmetro *onerror* de :func:`~shutil.rmtree` foi " +":mod:`shutil`: o parâmetro *onerror* de :func:`~shutil.rmtree` foi " "descontinuado no Python 3.12; use o parâmetro *onexc*." -#: ../../deprecations/pending-removal-in-future.rst:93 +#: ../../deprecations/pending-removal-in-future.rst:89 msgid ":mod:`ssl` options and protocols:" msgstr "Protocolos e opções de :mod:`ssl`" -#: ../../deprecations/pending-removal-in-future.rst:95 +#: ../../deprecations/pending-removal-in-future.rst:91 msgid ":class:`ssl.SSLContext` without protocol argument is deprecated." msgstr ":class:`ssl.SSLContext` sem argumento de protocolo foi descontinuado." -#: ../../deprecations/pending-removal-in-future.rst:96 +#: ../../deprecations/pending-removal-in-future.rst:92 msgid "" ":class:`ssl.SSLContext`: :meth:`~ssl.SSLContext.set_npn_protocols` and :meth:" "`!selected_npn_protocol` are deprecated: use ALPN instead." msgstr "" ":class:`ssl.SSLContext`: :meth:`~ssl.SSLContext.set_npn_protocols` e :meth:`!" -"selected_npn_protocol` foram descontinuados: use ALPN." +"selected_npn_protocol` foram descontinuados, use ALPN." -#: ../../deprecations/pending-removal-in-future.rst:99 +#: ../../deprecations/pending-removal-in-future.rst:95 msgid "``ssl.OP_NO_SSL*`` options" msgstr "Opções de ``ssl.OP_NO_SSL*``" -#: ../../deprecations/pending-removal-in-future.rst:100 +#: ../../deprecations/pending-removal-in-future.rst:96 msgid "``ssl.OP_NO_TLS*`` options" msgstr "Opções de ``ssl.OP_NO_TLS*``" -#: ../../deprecations/pending-removal-in-future.rst:101 +#: ../../deprecations/pending-removal-in-future.rst:97 msgid "``ssl.PROTOCOL_SSLv3``" msgstr "``ssl.PROTOCOL_SSLv3``" -#: ../../deprecations/pending-removal-in-future.rst:102 +#: ../../deprecations/pending-removal-in-future.rst:98 msgid "``ssl.PROTOCOL_TLS``" msgstr "``ssl.PROTOCOL_TLS``" -#: ../../deprecations/pending-removal-in-future.rst:103 +#: ../../deprecations/pending-removal-in-future.rst:99 msgid "``ssl.PROTOCOL_TLSv1``" msgstr "``ssl.PROTOCOL_TLSv1``" -#: ../../deprecations/pending-removal-in-future.rst:104 +#: ../../deprecations/pending-removal-in-future.rst:100 msgid "``ssl.PROTOCOL_TLSv1_1``" msgstr "``ssl.PROTOCOL_TLSv1_1``" -#: ../../deprecations/pending-removal-in-future.rst:105 +#: ../../deprecations/pending-removal-in-future.rst:101 msgid "``ssl.PROTOCOL_TLSv1_2``" msgstr "``ssl.PROTOCOL_TLSv1_2``" -#: ../../deprecations/pending-removal-in-future.rst:106 +#: ../../deprecations/pending-removal-in-future.rst:102 msgid "``ssl.TLSVersion.SSLv3``" msgstr "``ssl.TLSVersion.SSLv3``" -#: ../../deprecations/pending-removal-in-future.rst:107 +#: ../../deprecations/pending-removal-in-future.rst:103 msgid "``ssl.TLSVersion.TLSv1``" msgstr "``ssl.TLSVersion.TLSv1``" -#: ../../deprecations/pending-removal-in-future.rst:108 +#: ../../deprecations/pending-removal-in-future.rst:104 msgid "``ssl.TLSVersion.TLSv1_1``" msgstr "``ssl.TLSVersion.TLSv1_1``" -#: ../../deprecations/pending-removal-in-future.rst:110 -msgid "" -":func:`sysconfig.is_python_build` *check_home* parameter is deprecated and " -"ignored." -msgstr "" -"O parâmetro *check_home* de :func:`sysconfig.is_python_build` foi " -"descontinuado e é ignorado." - -#: ../../deprecations/pending-removal-in-future.rst:113 +#: ../../deprecations/pending-removal-in-future.rst:106 msgid ":mod:`threading` methods:" msgstr "Métodos de :mod:`threading`:" -#: ../../deprecations/pending-removal-in-future.rst:115 +#: ../../deprecations/pending-removal-in-future.rst:108 msgid "" ":meth:`!threading.Condition.notifyAll`: use :meth:`~threading.Condition." "notify_all`." @@ -3373,11 +3725,11 @@ msgstr "" ":meth:`!threading.Condition.notifyAll`: use :meth:`~threading.Condition." "notify_all`." -#: ../../deprecations/pending-removal-in-future.rst:116 +#: ../../deprecations/pending-removal-in-future.rst:109 msgid ":meth:`!threading.Event.isSet`: use :meth:`~threading.Event.is_set`." msgstr ":meth:`!threading.Event.isSet`: use :meth:`~threading.Event.is_set`." -#: ../../deprecations/pending-removal-in-future.rst:117 +#: ../../deprecations/pending-removal-in-future.rst:110 msgid "" ":meth:`!threading.Thread.isDaemon`, :meth:`threading.Thread.setDaemon`: use :" "attr:`threading.Thread.daemon` attribute." @@ -3385,7 +3737,7 @@ msgstr "" ":meth:`!threading.Thread.isDaemon`, :meth:`threading.Thread.setDaemon`: use " "o atributo :attr:`threading.Thread.daemon`." -#: ../../deprecations/pending-removal-in-future.rst:119 +#: ../../deprecations/pending-removal-in-future.rst:112 msgid "" ":meth:`!threading.Thread.getName`, :meth:`threading.Thread.setName`: use :" "attr:`threading.Thread.name` attribute." @@ -3393,20 +3745,20 @@ msgstr "" ":meth:`!threading.Thread.getName`, :meth:`threading.Thread.setName`: use o " "atributo :attr:`threading.Thread.name`." -#: ../../deprecations/pending-removal-in-future.rst:121 +#: ../../deprecations/pending-removal-in-future.rst:114 msgid ":meth:`!threading.currentThread`: use :meth:`threading.current_thread`." msgstr "" ":meth:`!threading.currentThread`: use :meth:`threading.current_thread`." -#: ../../deprecations/pending-removal-in-future.rst:122 +#: ../../deprecations/pending-removal-in-future.rst:115 msgid ":meth:`!threading.activeCount`: use :meth:`threading.active_count`." msgstr ":meth:`!threading.activeCount`: use :meth:`threading.active_count`." -#: ../../deprecations/pending-removal-in-future.rst:124 +#: ../../deprecations/pending-removal-in-future.rst:117 msgid ":class:`typing.Text` (:gh:`92332`)." msgstr ":class:`typing.Text` (:gh:`92332`)." -#: ../../deprecations/pending-removal-in-future.rst:126 +#: ../../deprecations/pending-removal-in-future.rst:119 msgid "" ":class:`unittest.IsolatedAsyncioTestCase`: it is deprecated to return a " "value that is not ``None`` from a test case." @@ -3414,7 +3766,7 @@ msgstr "" ":class:`unittest.IsolatedAsyncioTestCase`: foi descontinuado retornar um " "valor que não seja ``None`` de um caso de teste." -#: ../../deprecations/pending-removal-in-future.rst:129 +#: ../../deprecations/pending-removal-in-future.rst:122 msgid "" ":mod:`urllib.parse` deprecated functions: :func:`~urllib.parse.urlparse` " "instead" @@ -3422,51 +3774,51 @@ msgstr "" "Funções descontinuadas de :mod:`urllib.parse`: use :func:`~urllib.parse." "urlparse`" -#: ../../deprecations/pending-removal-in-future.rst:131 +#: ../../deprecations/pending-removal-in-future.rst:124 msgid "``splitattr()``" msgstr "``splitattr()``" -#: ../../deprecations/pending-removal-in-future.rst:132 +#: ../../deprecations/pending-removal-in-future.rst:125 msgid "``splithost()``" msgstr "``splithost()``" -#: ../../deprecations/pending-removal-in-future.rst:133 +#: ../../deprecations/pending-removal-in-future.rst:126 msgid "``splitnport()``" msgstr "``splitnport()``" -#: ../../deprecations/pending-removal-in-future.rst:134 +#: ../../deprecations/pending-removal-in-future.rst:127 msgid "``splitpasswd()``" msgstr "``splitpasswd()``" -#: ../../deprecations/pending-removal-in-future.rst:135 +#: ../../deprecations/pending-removal-in-future.rst:128 msgid "``splitport()``" msgstr "``splitport()``" -#: ../../deprecations/pending-removal-in-future.rst:136 +#: ../../deprecations/pending-removal-in-future.rst:129 msgid "``splitquery()``" msgstr "``splitquery()``" -#: ../../deprecations/pending-removal-in-future.rst:137 +#: ../../deprecations/pending-removal-in-future.rst:130 msgid "``splittag()``" msgstr "``splittag()``" -#: ../../deprecations/pending-removal-in-future.rst:138 +#: ../../deprecations/pending-removal-in-future.rst:131 msgid "``splittype()``" msgstr "``splittype()``" -#: ../../deprecations/pending-removal-in-future.rst:139 +#: ../../deprecations/pending-removal-in-future.rst:132 msgid "``splituser()``" msgstr "``splituser()``" -#: ../../deprecations/pending-removal-in-future.rst:140 +#: ../../deprecations/pending-removal-in-future.rst:133 msgid "``splitvalue()``" msgstr "``splitvalue()``" -#: ../../deprecations/pending-removal-in-future.rst:141 +#: ../../deprecations/pending-removal-in-future.rst:134 msgid "``to_bytes()``" msgstr "``to_bytes()``" -#: ../../deprecations/pending-removal-in-future.rst:143 +#: ../../deprecations/pending-removal-in-future.rst:136 msgid "" ":mod:`urllib.request`: :class:`~urllib.request.URLopener` and :class:" "`~urllib.request.FancyURLopener` style of invoking requests is deprecated. " @@ -3477,7 +3829,7 @@ msgstr "" "descontinuado. Use as mais novas funções e métodos :func:`~urllib.request." "urlopen`." -#: ../../deprecations/pending-removal-in-future.rst:147 +#: ../../deprecations/pending-removal-in-future.rst:140 msgid "" ":mod:`wsgiref`: ``SimpleHandler.stdout.write()`` should not do partial " "writes." @@ -3485,7 +3837,7 @@ msgstr "" ":mod:`wsgiref`: ``SimpleHandler.stdout.write()`` não deve fazer gravações " "parciais." -#: ../../deprecations/pending-removal-in-future.rst:150 +#: ../../deprecations/pending-removal-in-future.rst:143 msgid "" ":mod:`xml.etree.ElementTree`: Testing the truth value of an :class:`~xml." "etree.ElementTree.Element` is deprecated. In a future release it will always " @@ -3497,7 +3849,7 @@ msgstr "" "sempre retornará ``True``. Em vez disso, prefira os testes explícitos " "``len(elem)`` ou ``elem is not None``." -#: ../../deprecations/pending-removal-in-future.rst:155 +#: ../../deprecations/pending-removal-in-future.rst:148 msgid "" ":meth:`zipimport.zipimporter.load_module` is deprecated: use :meth:" "`~zipimport.zipimporter.exec_module` instead." @@ -3505,15 +3857,15 @@ msgstr "" ":meth:`zipimport.zipimporter.load_module` foi descontinuado: use :meth:" "`~zipimport.zipimporter.exec_module`." -#: ../../whatsnew/3.12.rst:1344 ../../whatsnew/3.12.rst:2222 +#: ../../whatsnew/3.12.rst:1355 ../../whatsnew/3.12.rst:2237 msgid "Removed" msgstr "Removidos" -#: ../../whatsnew/3.12.rst:1347 +#: ../../whatsnew/3.12.rst:1358 msgid "asynchat and asyncore" msgstr "asynchat e asyncore" -#: ../../whatsnew/3.12.rst:1349 +#: ../../whatsnew/3.12.rst:1360 msgid "" "These two modules have been removed according to the schedule in :pep:`594`, " "having been deprecated in Python 3.6. Use :mod:`asyncio` instead. " @@ -3523,11 +3875,11 @@ msgstr "" "tendo sido descontinuados no Python 3.6. Use :mod:`asyncio` em vez disso. " "(Contribuição de Nikita Sobolev em :gh:`96580`.)" -#: ../../whatsnew/3.12.rst:1356 +#: ../../whatsnew/3.12.rst:1367 msgid "configparser" msgstr "configparser" -#: ../../whatsnew/3.12.rst:1358 +#: ../../whatsnew/3.12.rst:1369 msgid "" "Several names deprecated in the :mod:`configparser` way back in 3.2 have " "been removed per :gh:`89336`:" @@ -3535,7 +3887,7 @@ msgstr "" "Vários nomes descontinuados no :mod:`configparser` na versão 3.2 foram " "removidos por :gh:`89336`:" -#: ../../whatsnew/3.12.rst:1361 +#: ../../whatsnew/3.12.rst:1372 msgid "" ":class:`configparser.ParsingError` no longer has a ``filename`` attribute or " "argument. Use the ``source`` attribute and argument instead." @@ -3543,7 +3895,7 @@ msgstr "" ":class:`configparser.ParsingError` não possui mais um argumento ou atributo " "``filename``. Use o atributo e o argumento ``source``." -#: ../../whatsnew/3.12.rst:1363 +#: ../../whatsnew/3.12.rst:1374 msgid "" ":mod:`configparser` no longer has a ``SafeConfigParser`` class. Use the " "shorter :class:`~configparser.ConfigParser` name instead." @@ -3551,7 +3903,7 @@ msgstr "" ":mod:`configparser` não possui mais uma classe ``SafeConfigParser``. Use o " "nome :class:`~configparser.ConfigParser` mais curto." -#: ../../whatsnew/3.12.rst:1365 +#: ../../whatsnew/3.12.rst:1376 msgid "" ":class:`configparser.ConfigParser` no longer has a ``readfp`` method. Use :" "meth:`~configparser.ConfigParser.read_file` instead." @@ -3559,11 +3911,11 @@ msgstr "" ":class:`configparser.ConfigParser` não possui mais um método ``readfp``. " "Use :meth:`~configparser.ConfigParser.read_file` em vez disso." -#: ../../whatsnew/3.12.rst:1369 +#: ../../whatsnew/3.12.rst:1382 msgid "distutils" msgstr "distutils" -#: ../../whatsnew/3.12.rst:1371 +#: ../../whatsnew/3.12.rst:1384 msgid "" "Remove the :py:mod:`!distutils` package. It was deprecated in Python 3.10 " "by :pep:`632` \"Deprecate distutils module\". For projects still using " @@ -3577,11 +3929,11 @@ msgstr "" "``setuptools`` pode ser instalado: ele ainda fornece ``distutils``. " "(Contribuição de Victor Stinner em :gh:`92584`.)" -#: ../../whatsnew/3.12.rst:1378 +#: ../../whatsnew/3.12.rst:1391 msgid "ensurepip" msgstr "ensurepip" -#: ../../whatsnew/3.12.rst:1380 +#: ../../whatsnew/3.12.rst:1393 msgid "" "Remove the bundled setuptools wheel from :mod:`ensurepip`, and stop " "installing setuptools in environments created by :mod:`venv`." @@ -3589,7 +3941,7 @@ msgstr "" "Remove o wheel de setuptools incluído em :mod:`ensurepip` e para de instalar " "setuptools em ambientes criados por :mod:`venv`." -#: ../../whatsnew/3.12.rst:1383 +#: ../../whatsnew/3.12.rst:1396 msgid "" "``pip (>= 22.1)`` does not require setuptools to be installed in the " "environment. ``setuptools``-based (and ``distutils``-based) packages can " @@ -3601,7 +3953,7 @@ msgstr "" "ser usados com ``pip install``, já que o pip fornecerá ``setuptools`` no " "ambiente de construção que ele usa para construir um pacote." -#: ../../whatsnew/3.12.rst:1389 +#: ../../whatsnew/3.12.rst:1402 msgid "" "``easy_install``, ``pkg_resources``, ``setuptools`` and ``distutils`` are no " "longer provided by default in environments created with ``venv`` or " @@ -3617,15 +3969,15 @@ msgstr "" "projeto ``setuptools`` deve ser declarado como uma dependência e instalado " "separadamente (normalmente, usando pip)." -#: ../../whatsnew/3.12.rst:1396 +#: ../../whatsnew/3.12.rst:1409 msgid "(Contributed by Pradyun Gedam in :gh:`95299`.)" msgstr "(Contribuição de Pradyun Gedam em :gh:`95299`.)" -#: ../../whatsnew/3.12.rst:1399 +#: ../../whatsnew/3.12.rst:1412 msgid "enum" msgstr "enum" -#: ../../whatsnew/3.12.rst:1401 +#: ../../whatsnew/3.12.rst:1414 msgid "" "Remove :mod:`enum`'s ``EnumMeta.__getattr__``, which is no longer needed for " "enum attribute access. (Contributed by Ethan Furman in :gh:`95083`.)" @@ -3634,11 +3986,11 @@ msgstr "" "para acesso ao atributos do enum. (Contribuição de Ethan Furman em :gh:" "`95083`.)" -#: ../../whatsnew/3.12.rst:1406 +#: ../../whatsnew/3.12.rst:1419 msgid "ftplib" msgstr "ftplib" -#: ../../whatsnew/3.12.rst:1408 +#: ../../whatsnew/3.12.rst:1421 msgid "" "Remove :mod:`ftplib`'s ``FTP_TLS.ssl_version`` class attribute: use the " "*context* parameter instead. (Contributed by Victor Stinner in :gh:`94172`.)" @@ -3647,11 +3999,11 @@ msgstr "" "parâmetro *context* em seu lugar. (Contribuição de Victor Stinner em :gh:" "`94172`.)" -#: ../../whatsnew/3.12.rst:1413 +#: ../../whatsnew/3.12.rst:1426 msgid "gzip" msgstr "gzip" -#: ../../whatsnew/3.12.rst:1415 +#: ../../whatsnew/3.12.rst:1428 msgid "" "Remove the ``filename`` attribute of :mod:`gzip`'s :class:`gzip.GzipFile`, " "deprecated since Python 2.6, use the :attr:`~gzip.GzipFile.name` attribute " @@ -3665,29 +4017,29 @@ msgstr "" "extensão de arquivo ``'.gz'`` se ela não estivesse presente. (Contribuição " "de Victor Stinner em :gh:`94196`.)" -#: ../../whatsnew/3.12.rst:1422 +#: ../../whatsnew/3.12.rst:1435 msgid "hashlib" msgstr "hashlib" -#: ../../whatsnew/3.12.rst:1424 +#: ../../whatsnew/3.12.rst:1437 msgid "" "Remove the pure Python implementation of :mod:`hashlib`'s :func:`hashlib." -"pbkdf2_hmac()`, deprecated in Python 3.10. Python 3.10 and newer requires " +"pbkdf2_hmac`, deprecated in Python 3.10. Python 3.10 and newer requires " "OpenSSL 1.1.1 (:pep:`644`): this OpenSSL version provides a C implementation " -"of :func:`~hashlib.pbkdf2_hmac()` which is faster. (Contributed by Victor " +"of :func:`~hashlib.pbkdf2_hmac` which is faster. (Contributed by Victor " "Stinner in :gh:`94199`.)" msgstr "" -"Remove a implementação Python pura de :func:`hashlib.pbkdf2_hmac()` de :mod:" +"Remove a implementação Python pura de :func:`hashlib.pbkdf2_hmac` de :mod:" "`hashlib`, descontinuado em Python 3.10. Python 3.10 e mais recente requer " "OpenSSL 1.1.1 (:pep:`644`): esta versão do OpenSSL fornece uma implementação " -"C de :func:`~hashlib.pbkdf2_hmac()` que é mais rápida. (Contribuição de " -"Victor Stinner em :gh:`94199`.)" +"C de :func:`~hashlib.pbkdf2_hmac` que é mais rápida. (Contribuição de Victor " +"Stinner em :gh:`94199`.)" -#: ../../whatsnew/3.12.rst:1431 ../../whatsnew/3.12.rst:1458 +#: ../../whatsnew/3.12.rst:1444 ../../whatsnew/3.12.rst:1473 msgid "importlib" msgstr "importlib" -#: ../../whatsnew/3.12.rst:1433 +#: ../../whatsnew/3.12.rst:1446 msgid "" "Many previously deprecated cleanups in :mod:`importlib` have now been " "completed:" @@ -3695,15 +4047,15 @@ msgstr "" "Foi concluída a remoção de muitos alvos de :mod:`importlib` que haviam sido " "descontinuados anteriormente:" -#: ../../whatsnew/3.12.rst:1436 +#: ../../whatsnew/3.12.rst:1449 msgid "" -"References to, and support for :meth:`!module_repr()` has been removed. " +"References to, and support for :meth:`!module_repr` has been removed. " "(Contributed by Barry Warsaw in :gh:`97850`.)" msgstr "" -"Referências e suporte a :meth:`!module_repr()` foram removidos. " -"(Contribuição de Barry Warsaw em :gh:`97850`.)" +"Referências e suporte a :meth:`!module_repr` foram removidos. (Contribuição " +"de Barry Warsaw em :gh:`97850`.)" -#: ../../whatsnew/3.12.rst:1439 +#: ../../whatsnew/3.12.rst:1452 msgid "" "``importlib.util.set_package``, ``importlib.util.set_loader`` and " "``importlib.util.module_for_loader`` have all been removed. (Contributed by " @@ -3713,7 +4065,7 @@ msgstr "" "util.module_for_loader`` foram todos removidos. (Contribuição de Brett " "Cannon e Nikita Sobolev em :gh:`65961` e :gh:`97850`.)" -#: ../../whatsnew/3.12.rst:1443 +#: ../../whatsnew/3.12.rst:1456 msgid "" "Support for ``find_loader()`` and ``find_module()`` APIs have been removed. " "(Contributed by Barry Warsaw in :gh:`98040`.)" @@ -3721,7 +4073,7 @@ msgstr "" "O suporte para APIs ``find_loader()`` e ``find_module()`` foi removido. " "(Contribuição de Barry Warsaw em :gh:`98040`.)" -#: ../../whatsnew/3.12.rst:1446 +#: ../../whatsnew/3.12.rst:1459 msgid "" "``importlib.abc.Finder``, ``pkgutil.ImpImporter``, and ``pkgutil.ImpLoader`` " "have been removed. (Contributed by Barry Warsaw in :gh:`98040`.)" @@ -3729,11 +4081,11 @@ msgstr "" "``importlib.abc.Finder``, ``pkgutil.ImpImporter`` e ``pkgutil.ImpLoader`` " "foram removidos. (Contribuição de Barry Warsaw em :gh:`98040`.)" -#: ../../whatsnew/3.12.rst:1450 ../../whatsnew/3.12.rst:1458 +#: ../../whatsnew/3.12.rst:1465 ../../whatsnew/3.12.rst:1473 msgid "imp" msgstr "imp" -#: ../../whatsnew/3.12.rst:1452 +#: ../../whatsnew/3.12.rst:1467 msgid "" "The :mod:`!imp` module has been removed. (Contributed by Barry Warsaw in :" "gh:`98040`.)" @@ -3741,131 +4093,161 @@ msgstr "" "O módulo :mod:`!imp` foi removido. (Contribuição de Barry Warsaw em :gh:" "`98040`.)" -#: ../../whatsnew/3.12.rst:1455 +#: ../../whatsnew/3.12.rst:1470 msgid "To migrate, consult the following correspondence table:" msgstr "Para migrar consulte a seguinte tabela de correspondência:" -#: ../../whatsnew/3.12.rst:1460 +#: ../../whatsnew/3.12.rst:1475 msgid "``imp.NullImporter``" msgstr "``imp.NullImporter``" -#: ../../whatsnew/3.12.rst:1460 +#: ../../whatsnew/3.12.rst:1475 msgid "Insert ``None`` into ``sys.path_importer_cache``" msgstr "Insere ``None`` em ``sys.path_importer_cache``" -#: ../../whatsnew/3.12.rst:1461 +#: ../../whatsnew/3.12.rst:1476 msgid "``imp.cache_from_source()``" msgstr "``imp.cache_from_source()``" -#: ../../whatsnew/3.12.rst:1461 +#: ../../whatsnew/3.12.rst:1476 msgid ":func:`importlib.util.cache_from_source`" msgstr ":func:`importlib.util.cache_from_source`" -#: ../../whatsnew/3.12.rst:1462 +#: ../../whatsnew/3.12.rst:1477 msgid "``imp.find_module()``" msgstr "``imp.find_module()``" -#: ../../whatsnew/3.12.rst:1462 +#: ../../whatsnew/3.12.rst:1477 msgid ":func:`importlib.util.find_spec`" msgstr ":func:`importlib.util.find_spec`" -#: ../../whatsnew/3.12.rst:1463 +#: ../../whatsnew/3.12.rst:1478 msgid "``imp.get_magic()``" msgstr "``imp.get_magic()``" -#: ../../whatsnew/3.12.rst:1463 -msgid ":attr:`importlib.util.MAGIC_NUMBER`" -msgstr ":attr:`importlib.util.MAGIC_NUMBER`" +#: ../../whatsnew/3.12.rst:1478 +msgid ":const:`importlib.util.MAGIC_NUMBER`" +msgstr ":const:`importlib.util.MAGIC_NUMBER`" -#: ../../whatsnew/3.12.rst:1464 +#: ../../whatsnew/3.12.rst:1479 msgid "``imp.get_suffixes()``" msgstr "``imp.get_suffixes()``" -#: ../../whatsnew/3.12.rst:1464 +#: ../../whatsnew/3.12.rst:1479 msgid "" -":attr:`importlib.machinery.SOURCE_SUFFIXES`, :attr:`importlib.machinery." -"EXTENSION_SUFFIXES`, and :attr:`importlib.machinery.BYTECODE_SUFFIXES`" +":const:`importlib.machinery.SOURCE_SUFFIXES`, :const:`importlib.machinery." +"EXTENSION_SUFFIXES`, and :const:`importlib.machinery.BYTECODE_SUFFIXES`" msgstr "" -":attr:`importlib.machinery.SOURCE_SUFFIXES`, :attr:`importlib.machinery." -"EXTENSION_SUFFIXES` e :attr:`importlib.machinery.BYTECODE_SUFFIXES`" +":const:`importlib.machinery.SOURCE_SUFFIXES`, :const:`importlib.machinery." +"EXTENSION_SUFFIXES` e :const:`importlib.machinery.BYTECODE_SUFFIXES`" -#: ../../whatsnew/3.12.rst:1465 +#: ../../whatsnew/3.12.rst:1480 msgid "``imp.get_tag()``" msgstr "``imp.get_tag()``" -#: ../../whatsnew/3.12.rst:1465 +#: ../../whatsnew/3.12.rst:1480 msgid ":attr:`sys.implementation.cache_tag `" msgstr ":attr:`sys.implementation.cache_tag `" -#: ../../whatsnew/3.12.rst:1466 +#: ../../whatsnew/3.12.rst:1481 msgid "``imp.load_module()``" msgstr "``imp.load_module()``" -#: ../../whatsnew/3.12.rst:1466 +#: ../../whatsnew/3.12.rst:1481 msgid ":func:`importlib.import_module`" msgstr ":func:`importlib.import_module`" -#: ../../whatsnew/3.12.rst:1467 +#: ../../whatsnew/3.12.rst:1482 msgid "``imp.new_module(name)``" msgstr "``imp.new_module(name)``" -#: ../../whatsnew/3.12.rst:1467 +#: ../../whatsnew/3.12.rst:1482 msgid "``types.ModuleType(name)``" msgstr "``types.ModuleType(name)``" -#: ../../whatsnew/3.12.rst:1468 +#: ../../whatsnew/3.12.rst:1483 msgid "``imp.reload()``" msgstr "``imp.reload()``" -#: ../../whatsnew/3.12.rst:1468 +#: ../../whatsnew/3.12.rst:1483 msgid ":func:`importlib.reload`" msgstr ":func:`importlib.reload`" -#: ../../whatsnew/3.12.rst:1469 +#: ../../whatsnew/3.12.rst:1484 msgid "``imp.source_from_cache()``" msgstr "``imp.source_from_cache()``" -#: ../../whatsnew/3.12.rst:1469 +#: ../../whatsnew/3.12.rst:1484 msgid ":func:`importlib.util.source_from_cache`" msgstr ":func:`importlib.util.source_from_cache`" -#: ../../whatsnew/3.12.rst:1470 +#: ../../whatsnew/3.12.rst:1485 msgid "``imp.load_source()``" msgstr "``imp.load_source()``" -#: ../../whatsnew/3.12.rst:1470 +#: ../../whatsnew/3.12.rst:1485 msgid "*See below*" msgstr "*Veja abaixo*" -#: ../../whatsnew/3.12.rst:1473 +#: ../../whatsnew/3.12.rst:1488 msgid "Replace ``imp.load_source()`` with::" msgstr "Substitua ``imp.load_source()`` com::" -#: ../../whatsnew/3.12.rst:1488 +#: ../../whatsnew/3.12.rst:1490 +msgid "" +"import importlib.util\n" +"import importlib.machinery\n" +"\n" +"def load_source(modname, filename):\n" +" loader = importlib.machinery.SourceFileLoader(modname, filename)\n" +" spec = importlib.util.spec_from_file_location(modname, filename, " +"loader=loader)\n" +" module = importlib.util.module_from_spec(spec)\n" +" # The module is always executed and not cached in sys.modules.\n" +" # Uncomment the following line to cache the module.\n" +" # sys.modules[module.__name__] = module\n" +" loader.exec_module(module)\n" +" return module" +msgstr "" +"import importlib.util\n" +"import importlib.machinery\n" +"\n" +"def load_source(modname, filename):\n" +" loader = importlib.machinery.SourceFileLoader(modname, filename)\n" +" spec = importlib.util.spec_from_file_location(modname, filename, " +"loader=loader)\n" +" module = importlib.util.module_from_spec(spec)\n" +" # O módulo é sempre executado e não colocado em cache em sys.modules.\n" +" # Descomente a linha a seguir para colocar o módulo em cache.\n" +" # sys.modules[module.__name__] = module\n" +" loader.exec_module(module)\n" +" return module" + +#: ../../whatsnew/3.12.rst:1503 msgid "Remove :mod:`!imp` functions and attributes with no replacements:" msgstr "Remove funções e atributos do :mod:`!imp` sem substituições:" -#: ../../whatsnew/3.12.rst:1490 +#: ../../whatsnew/3.12.rst:1505 msgid "Undocumented functions:" msgstr "Funções não documentadas:" -#: ../../whatsnew/3.12.rst:1492 +#: ../../whatsnew/3.12.rst:1507 msgid "``imp.init_builtin()``" msgstr "``imp.init_builtin()``" -#: ../../whatsnew/3.12.rst:1493 +#: ../../whatsnew/3.12.rst:1508 msgid "``imp.load_compiled()``" msgstr "``imp.load_compiled()``" -#: ../../whatsnew/3.12.rst:1494 +#: ../../whatsnew/3.12.rst:1509 msgid "``imp.load_dynamic()``" msgstr "``imp.load_dynamic()``" -#: ../../whatsnew/3.12.rst:1495 +#: ../../whatsnew/3.12.rst:1510 msgid "``imp.load_package()``" msgstr "``imp.load_package()``" -#: ../../whatsnew/3.12.rst:1497 +#: ../../whatsnew/3.12.rst:1512 msgid "" "``imp.lock_held()``, ``imp.acquire_lock()``, ``imp.release_lock()``: the " "locking scheme has changed in Python 3.3 to per-module locks." @@ -3873,7 +4255,7 @@ msgstr "" "``imp.lock_held()``, ``imp.acquire_lock()``, ``imp.release_lock()``: o " "esquema de trava foi alterado no Python 3.3 para travas por módulo." -#: ../../whatsnew/3.12.rst:1499 +#: ../../whatsnew/3.12.rst:1514 msgid "" "``imp.find_module()`` constants: ``SEARCH_ERROR``, ``PY_SOURCE``, " "``PY_COMPILED``, ``C_EXTENSION``, ``PY_RESOURCE``, ``PKG_DIRECTORY``, " @@ -3883,11 +4265,11 @@ msgstr "" "``PY_COMPILED``, ``C_EXTENSION``, ``PY_RESOURCE``, ``PKG_DIRECTORY``, " "``C_BUILTIN``, ``PY_FROZEN``, ``PY_CODERESOURCE``, ``IMP_HOOK``." -#: ../../whatsnew/3.12.rst:1504 +#: ../../whatsnew/3.12.rst:1519 msgid "io" msgstr "io" -#: ../../whatsnew/3.12.rst:1506 +#: ../../whatsnew/3.12.rst:1521 msgid "" "Remove :mod:`io`'s ``io.OpenWrapper`` and ``_pyio.OpenWrapper``, deprecated " "in Python 3.10: just use :func:`open` instead. The :func:`open` (:func:`io." @@ -3901,11 +4283,11 @@ msgstr "" "3.10, :func:`!_pyio.open` também é um método estático. (Contribuição de " "Victor Stinner em :gh:`94169`.)" -#: ../../whatsnew/3.12.rst:1513 +#: ../../whatsnew/3.12.rst:1528 msgid "locale" msgstr "locale" -#: ../../whatsnew/3.12.rst:1515 +#: ../../whatsnew/3.12.rst:1530 msgid "" "Remove :mod:`locale`'s :func:`!locale.format` function, deprecated in Python " "3.7: use :func:`locale.format_string` instead. (Contributed by Victor " @@ -3915,11 +4297,11 @@ msgstr "" "Python 3.7: use :func:`locale.format_string` em seu lugar. (Contribuição de " "Victor Stinner em :gh:`94226`.)" -#: ../../whatsnew/3.12.rst:1520 +#: ../../whatsnew/3.12.rst:1535 msgid "smtpd" msgstr "smtpd" -#: ../../whatsnew/3.12.rst:1522 +#: ../../whatsnew/3.12.rst:1537 msgid "" "The ``smtpd`` module has been removed according to the schedule in :pep:" "`594`, having been deprecated in Python 3.4.7 and 3.5.4. Use the :pypi:" @@ -3931,7 +4313,7 @@ msgstr "" "`aiosmtpd` ou qualquer outro servidor baseado em :mod:`asyncio`. " "(Contribuição de Oleg Iarygin em :gh:`93243`.)" -#: ../../whatsnew/3.12.rst:1531 +#: ../../whatsnew/3.12.rst:1546 msgid "" "The following undocumented :mod:`sqlite3` features, deprecated in Python " "3.10, are now removed:" @@ -3939,15 +4321,15 @@ msgstr "" "Os seguintes recursos não documentados do :mod:`sqlite3`, descontinuados no " "Python 3.10, foram agora removidos:" -#: ../../whatsnew/3.12.rst:1534 +#: ../../whatsnew/3.12.rst:1549 msgid "``sqlite3.enable_shared_cache()``" msgstr "``sqlite3.enable_shared_cache()``" -#: ../../whatsnew/3.12.rst:1535 +#: ../../whatsnew/3.12.rst:1550 msgid "``sqlite3.OptimizedUnicode``" msgstr "``sqlite3.OptimizedUnicode``" -#: ../../whatsnew/3.12.rst:1537 +#: ../../whatsnew/3.12.rst:1552 msgid "" "If a shared cache must be used, open the database in URI mode using the " "``cache=shared`` query parameter." @@ -3955,7 +4337,7 @@ msgstr "" "Se um cache compartilhado deve ser usado, abra o banco de dados no modo URI " "usando o parâmetro de consulta ``cache=shared``." -#: ../../whatsnew/3.12.rst:1540 +#: ../../whatsnew/3.12.rst:1555 msgid "" "The ``sqlite3.OptimizedUnicode`` text factory has been an alias for :class:" "`str` since Python 3.3. Code that previously set the text factory to " @@ -3967,15 +4349,15 @@ msgstr "" "de texto como ``OptimizedUnicode`` pode usar ``str`` explicitamente ou " "confiar no valor padrão que também é ``str``." -#: ../../whatsnew/3.12.rst:1545 +#: ../../whatsnew/3.12.rst:1560 msgid "(Contributed by Erlend E. Aasland in :gh:`92548`.)" msgstr "(Contribuição de Erlend E. Aasland em :gh:`92548`.)" -#: ../../whatsnew/3.12.rst:1548 +#: ../../whatsnew/3.12.rst:1563 msgid "ssl" msgstr "ssl" -#: ../../whatsnew/3.12.rst:1550 +#: ../../whatsnew/3.12.rst:1565 msgid "" "Remove :mod:`ssl`'s :func:`!ssl.RAND_pseudo_bytes` function, deprecated in " "Python 3.6: use :func:`os.urandom` or :func:`ssl.RAND_bytes` instead. " @@ -3985,7 +4367,7 @@ msgstr "" "no Python 3.6: use :func:`os.urandom` ou :func:`ssl.RAND_bytes` em seu " "lugar. (Contribuição de Victor Stinner em :gh:`94199`.)" -#: ../../whatsnew/3.12.rst:1554 +#: ../../whatsnew/3.12.rst:1569 msgid "" "Remove the :func:`!ssl.match_hostname` function. It was deprecated in Python " "3.7. OpenSSL performs hostname matching since Python 3.7, Python no longer " @@ -3997,7 +4379,7 @@ msgstr "" "Python não usa mais a função :func:`!ssl.match_hostname`. (Contribuição de " "Victor Stinner em :gh:`94199`.)" -#: ../../whatsnew/3.12.rst:1560 +#: ../../whatsnew/3.12.rst:1575 msgid "" "Remove the :func:`!ssl.wrap_socket` function, deprecated in Python 3.7: " "instead, create a :class:`ssl.SSLContext` object and call its :class:`ssl." @@ -4015,145 +4397,145 @@ msgstr "" "`295` (validação inadequada de certificado). (Contribuição de Victor Stinner " "em :gh:`94199`.)" -#: ../../whatsnew/3.12.rst:1571 +#: ../../whatsnew/3.12.rst:1586 msgid "Remove many long-deprecated :mod:`unittest` features:" msgstr "Remove recursos do :mod:`unittest` há muito tempo descontinuados:" -#: ../../whatsnew/3.12.rst:1575 +#: ../../whatsnew/3.12.rst:1590 msgid "A number of :class:`~unittest.TestCase` method aliases:" msgstr "Vários apelidos de método de :class:`~unittest.TestCase`:" -#: ../../whatsnew/3.12.rst:1578 +#: ../../whatsnew/3.12.rst:1593 msgid "Deprecated alias" msgstr "Apelido descontinuado" -#: ../../whatsnew/3.12.rst:1578 +#: ../../whatsnew/3.12.rst:1593 msgid "Method Name" msgstr "Método" -#: ../../whatsnew/3.12.rst:1578 +#: ../../whatsnew/3.12.rst:1593 msgid "Deprecated in" msgstr "Descontinuado em" -#: ../../whatsnew/3.12.rst:1580 +#: ../../whatsnew/3.12.rst:1595 msgid "``failUnless``" msgstr "``failUnless``" -#: ../../whatsnew/3.12.rst:1580 ../../whatsnew/3.12.rst:1587 +#: ../../whatsnew/3.12.rst:1595 ../../whatsnew/3.12.rst:1602 msgid ":meth:`.assertTrue`" msgstr ":meth:`.assertTrue`" -#: ../../whatsnew/3.12.rst:1580 ../../whatsnew/3.12.rst:1581 -#: ../../whatsnew/3.12.rst:1582 ../../whatsnew/3.12.rst:1583 -#: ../../whatsnew/3.12.rst:1584 ../../whatsnew/3.12.rst:1585 -#: ../../whatsnew/3.12.rst:1586 +#: ../../whatsnew/3.12.rst:1595 ../../whatsnew/3.12.rst:1596 +#: ../../whatsnew/3.12.rst:1597 ../../whatsnew/3.12.rst:1598 +#: ../../whatsnew/3.12.rst:1599 ../../whatsnew/3.12.rst:1600 +#: ../../whatsnew/3.12.rst:1601 msgid "3.1" msgstr "3.1" -#: ../../whatsnew/3.12.rst:1581 +#: ../../whatsnew/3.12.rst:1596 msgid "``failIf``" msgstr "``failIf``" -#: ../../whatsnew/3.12.rst:1581 +#: ../../whatsnew/3.12.rst:1596 msgid ":meth:`.assertFalse`" msgstr ":meth:`.assertFalse`" -#: ../../whatsnew/3.12.rst:1582 +#: ../../whatsnew/3.12.rst:1597 msgid "``failUnlessEqual``" msgstr "``failUnlessEqual``" -#: ../../whatsnew/3.12.rst:1582 ../../whatsnew/3.12.rst:1588 +#: ../../whatsnew/3.12.rst:1597 ../../whatsnew/3.12.rst:1603 msgid ":meth:`.assertEqual`" msgstr ":meth:`.assertEqual`" -#: ../../whatsnew/3.12.rst:1583 +#: ../../whatsnew/3.12.rst:1598 msgid "``failIfEqual``" msgstr "``failIfEqual``" -#: ../../whatsnew/3.12.rst:1583 ../../whatsnew/3.12.rst:1589 +#: ../../whatsnew/3.12.rst:1598 ../../whatsnew/3.12.rst:1604 msgid ":meth:`.assertNotEqual`" msgstr ":meth:`.assertNotEqual`" -#: ../../whatsnew/3.12.rst:1584 +#: ../../whatsnew/3.12.rst:1599 msgid "``failUnlessAlmostEqual``" msgstr "``failUnlessAlmostEqual``" -#: ../../whatsnew/3.12.rst:1584 ../../whatsnew/3.12.rst:1590 +#: ../../whatsnew/3.12.rst:1599 ../../whatsnew/3.12.rst:1605 msgid ":meth:`.assertAlmostEqual`" msgstr ":meth:`.assertAlmostEqual`" -#: ../../whatsnew/3.12.rst:1585 +#: ../../whatsnew/3.12.rst:1600 msgid "``failIfAlmostEqual``" msgstr "``failIfAlmostEqual``" -#: ../../whatsnew/3.12.rst:1585 ../../whatsnew/3.12.rst:1591 +#: ../../whatsnew/3.12.rst:1600 ../../whatsnew/3.12.rst:1606 msgid ":meth:`.assertNotAlmostEqual`" msgstr ":meth:`.assertNotAlmostEqual`" -#: ../../whatsnew/3.12.rst:1586 +#: ../../whatsnew/3.12.rst:1601 msgid "``failUnlessRaises``" msgstr "``failUnlessRaises``" -#: ../../whatsnew/3.12.rst:1586 +#: ../../whatsnew/3.12.rst:1601 msgid ":meth:`.assertRaises`" msgstr ":meth:`.assertRaises`" -#: ../../whatsnew/3.12.rst:1587 +#: ../../whatsnew/3.12.rst:1602 msgid "``assert_``" msgstr "``assert_``" -#: ../../whatsnew/3.12.rst:1587 ../../whatsnew/3.12.rst:1588 -#: ../../whatsnew/3.12.rst:1589 ../../whatsnew/3.12.rst:1590 -#: ../../whatsnew/3.12.rst:1591 ../../whatsnew/3.12.rst:1592 -#: ../../whatsnew/3.12.rst:1593 +#: ../../whatsnew/3.12.rst:1602 ../../whatsnew/3.12.rst:1603 +#: ../../whatsnew/3.12.rst:1604 ../../whatsnew/3.12.rst:1605 +#: ../../whatsnew/3.12.rst:1606 ../../whatsnew/3.12.rst:1607 +#: ../../whatsnew/3.12.rst:1608 msgid "3.2" msgstr "3.2" -#: ../../whatsnew/3.12.rst:1588 +#: ../../whatsnew/3.12.rst:1603 msgid "``assertEquals``" msgstr "``assertEquals``" -#: ../../whatsnew/3.12.rst:1589 +#: ../../whatsnew/3.12.rst:1604 msgid "``assertNotEquals``" msgstr "``assertNotEquals``" -#: ../../whatsnew/3.12.rst:1590 +#: ../../whatsnew/3.12.rst:1605 msgid "``assertAlmostEquals``" msgstr "``assertAlmostEquals``" -#: ../../whatsnew/3.12.rst:1591 +#: ../../whatsnew/3.12.rst:1606 msgid "``assertNotAlmostEquals``" msgstr "``assertNotAlmostEquals``" -#: ../../whatsnew/3.12.rst:1592 +#: ../../whatsnew/3.12.rst:1607 msgid "``assertRegexpMatches``" msgstr "``assertRegexpMatches``" -#: ../../whatsnew/3.12.rst:1592 +#: ../../whatsnew/3.12.rst:1607 msgid ":meth:`.assertRegex`" msgstr ":meth:`.assertRegex`" -#: ../../whatsnew/3.12.rst:1593 +#: ../../whatsnew/3.12.rst:1608 msgid "``assertRaisesRegexp``" msgstr "``assertRaisesRegexp``" -#: ../../whatsnew/3.12.rst:1593 +#: ../../whatsnew/3.12.rst:1608 msgid ":meth:`.assertRaisesRegex`" msgstr ":meth:`.assertRaisesRegex`" -#: ../../whatsnew/3.12.rst:1594 +#: ../../whatsnew/3.12.rst:1609 msgid "``assertNotRegexpMatches``" msgstr "``assertNotRegexpMatches``" -#: ../../whatsnew/3.12.rst:1594 +#: ../../whatsnew/3.12.rst:1609 msgid ":meth:`.assertNotRegex`" msgstr ":meth:`.assertNotRegex`" -#: ../../whatsnew/3.12.rst:1594 +#: ../../whatsnew/3.12.rst:1609 msgid "3.5" msgstr "3.5" -#: ../../whatsnew/3.12.rst:1597 +#: ../../whatsnew/3.12.rst:1612 msgid "" "You can use https://github.com/isidentical/teyit to automatically modernise " "your unit tests." @@ -4161,7 +4543,7 @@ msgstr "" "Você pode usar https://github.com/isidentical/teyit para modernizar " "automaticamente seus testes de unidade." -#: ../../whatsnew/3.12.rst:1600 +#: ../../whatsnew/3.12.rst:1615 msgid "" "Undocumented and broken :class:`~unittest.TestCase` method " "``assertDictContainsSubset`` (deprecated in Python 3.2)." @@ -4169,7 +4551,7 @@ msgstr "" "Método não documentado e quebrado ``assertDictContainsSubset`` de :class:" "`~unittest.TestCase` (descontinuado no Python 3.2)." -#: ../../whatsnew/3.12.rst:1603 +#: ../../whatsnew/3.12.rst:1618 msgid "" "Undocumented :meth:`TestLoader.loadTestsFromModule ` parameter *use_load_tests* (deprecated and ignored " @@ -4179,7 +4561,7 @@ msgstr "" "loadTestsFromModule ` " "(descontinuado e ignorado desde Python 3.5)." -#: ../../whatsnew/3.12.rst:1607 +#: ../../whatsnew/3.12.rst:1622 msgid "" "An alias of the :class:`~unittest.TextTestResult` class: ``_TextTestResult`` " "(deprecated in Python 3.2)." @@ -4187,15 +4569,15 @@ msgstr "" "Um apelido da classe :class:`~unittest.TextTestResult`: ``_TextTestResult`` " "(descontinuado no Python 3.2)." -#: ../../whatsnew/3.12.rst:1610 +#: ../../whatsnew/3.12.rst:1625 msgid "(Contributed by Serhiy Storchaka in :gh:`89325`.)" msgstr "(Contribuição de Serhiy Storchaka em :gh:`89325`.)" -#: ../../whatsnew/3.12.rst:1613 +#: ../../whatsnew/3.12.rst:1628 msgid "webbrowser" msgstr "webbrowser" -#: ../../whatsnew/3.12.rst:1615 +#: ../../whatsnew/3.12.rst:1630 msgid "" "Remove support for obsolete browsers from :mod:`webbrowser`. The removed " "browsers include: Grail, Mosaic, Netscape, Galeon, Skipstone, Iceape, " @@ -4205,11 +4587,11 @@ msgstr "" "navegadores removidos incluem: Grail, Mosaic, Netscape, Galeon, Skipstone, " "Iceape, Firebird e Firefox versões 35 e inferiores (:gh:`102871`)." -#: ../../whatsnew/3.12.rst:1620 +#: ../../whatsnew/3.12.rst:1635 msgid "xml.etree.ElementTree" msgstr "xml.etree.ElementTree" -#: ../../whatsnew/3.12.rst:1622 +#: ../../whatsnew/3.12.rst:1637 msgid "" "Remove the ``ElementTree.Element.copy()`` method of the pure Python " "implementation, deprecated in Python 3.10, use the :func:`copy.copy` " @@ -4223,11 +4605,11 @@ msgstr "" "``copy()``, apenas um método ``__copy__()``. (Contribuição de Victor Stinner " "em :gh:`94383`.)" -#: ../../whatsnew/3.12.rst:1629 +#: ../../whatsnew/3.12.rst:1644 msgid "zipimport" msgstr "zipimport" -#: ../../whatsnew/3.12.rst:1631 +#: ../../whatsnew/3.12.rst:1646 msgid "" "Remove :mod:`zipimport`'s ``find_loader()`` and ``find_module()`` methods, " "deprecated in Python 3.10: use the ``find_spec()`` method instead. See :pep:" @@ -4238,11 +4620,11 @@ msgstr "" "Veja :pep:`451` para o raciocínio. (Contribuição de Victor Stinner em :gh:" "`94379`.)" -#: ../../whatsnew/3.12.rst:1637 +#: ../../whatsnew/3.12.rst:1652 msgid "Others" msgstr "Outros" -#: ../../whatsnew/3.12.rst:1639 +#: ../../whatsnew/3.12.rst:1654 msgid "" "Remove the ``suspicious`` rule from the documentation :file:`Makefile` and :" "file:`Doc/tools/rstlint.py`, both in favor of `sphinx-lint `_. (Contribuição de Julien Palard em :gh:" "`98179`.)" -#: ../../whatsnew/3.12.rst:1644 +#: ../../whatsnew/3.12.rst:1659 msgid "" "Remove the *keyfile* and *certfile* parameters from the :mod:`ftplib`, :mod:" "`imaplib`, :mod:`poplib` and :mod:`smtplib` modules, and the *key_file*, " @@ -4269,7 +4651,7 @@ msgstr "" "descontinuados desde Python 3.6. Use o parâmetro *context* (*ssl_context* " "em :mod:`imaplib`). (Contribuição de Victor Stinner em :gh:`94172`.)" -#: ../../whatsnew/3.12.rst:1652 +#: ../../whatsnew/3.12.rst:1667 msgid "" "Remove ``Jython`` compatibility hacks from several stdlib modules and tests. " "(Contributed by Nikita Sobolev in :gh:`99482`.)" @@ -4277,7 +4659,7 @@ msgstr "" "Remove hacks de compatibilidade ``Jython`` de vários módulos e testes da " "stdlib. (Contribuição de Nikita Sobolev em :gh:`99482`.)" -#: ../../whatsnew/3.12.rst:1655 +#: ../../whatsnew/3.12.rst:1670 msgid "" "Remove ``_use_broken_old_ctypes_structure_semantics_`` flag from :mod:" "`ctypes` module. (Contributed by Nikita Sobolev in :gh:`99285`.)" @@ -4285,11 +4667,11 @@ msgstr "" "Remove o sinalizador ``_use_broken_old_ctypes_structure_semantics_`` do " "módulo :mod:`ctypes`. (Contribuição de Nikita Sobolev em :gh:`99285`.)" -#: ../../whatsnew/3.12.rst:1663 ../../whatsnew/3.12.rst:1987 +#: ../../whatsnew/3.12.rst:1678 ../../whatsnew/3.12.rst:2002 msgid "Porting to Python 3.12" msgstr "Portando para Python 3.12" -#: ../../whatsnew/3.12.rst:1665 +#: ../../whatsnew/3.12.rst:1680 msgid "" "This section lists previously described changes and other bugfixes that may " "require changes to your code." @@ -4297,11 +4679,11 @@ msgstr "" "Esta seção lista as alterações descritas anteriormente e outras correções " "que podem exigir alterações no seu código." -#: ../../whatsnew/3.12.rst:1669 +#: ../../whatsnew/3.12.rst:1684 msgid "Changes in the Python API" msgstr "Alterações na API Python" -#: ../../whatsnew/3.12.rst:1671 +#: ../../whatsnew/3.12.rst:1686 msgid "" "More strict rules are now applied for numerical group references and group " "names in regular expressions. Only sequence of ASCII digits is now accepted " @@ -4316,7 +4698,7 @@ msgstr "" "dígitos ASCII e sublinhado. (Contribuição de Serhiy Storchaka em :gh:" "`91760`.)" -#: ../../whatsnew/3.12.rst:1678 +#: ../../whatsnew/3.12.rst:1693 msgid "" "Remove ``randrange()`` functionality deprecated since Python 3.10. " "Formerly, ``randrange(10.0)`` losslessly converted to ``randrange(10)``. " @@ -4336,7 +4718,7 @@ msgstr "" "um intervalo maior que ``randrange(10**25)``. (Originalmente sugerido por " "Serhiy Storchaka :gh:`86388`.)" -#: ../../whatsnew/3.12.rst:1686 +#: ../../whatsnew/3.12.rst:1701 msgid "" ":class:`argparse.ArgumentParser` changed encoding and error handler for " "reading arguments from file (e.g. ``fromfile_prefix_chars`` option) from " @@ -4353,7 +4735,7 @@ msgstr "" "arquivos de argumento devem ser codificados em UTF-8 em vez de ANSI Codepage " "no Windows." -#: ../../whatsnew/3.12.rst:1692 +#: ../../whatsnew/3.12.rst:1707 msgid "" "Remove the ``asyncore``-based ``smtpd`` module deprecated in Python 3.4.7 " "and 3.5.4. A recommended replacement is the :mod:`asyncio`-based :pypi:" @@ -4363,7 +4745,7 @@ msgstr "" "3.4.7 e 3.5.4. Um substituto recomendado é o módulo PyPI baseado em :mod:" "`asyncio` :pypi:`aiosmtpd`." -#: ../../whatsnew/3.12.rst:1696 +#: ../../whatsnew/3.12.rst:1711 msgid "" ":func:`shlex.split`: Passing ``None`` for *s* argument now raises an " "exception, rather than reading :data:`sys.stdin`. The feature was deprecated " @@ -4373,7 +4755,7 @@ msgstr "" "exceção, ao invés de ler :data:`sys.stdin`. O recurso foi descontinuado no " "Python 3.9. (Contribuição de Victor Stinner em :gh:`94352`.)" -#: ../../whatsnew/3.12.rst:1701 +#: ../../whatsnew/3.12.rst:1716 msgid "" "The :mod:`os` module no longer accepts bytes-like paths, like :class:" "`bytearray` and :class:`memoryview` types: only the exact :class:`bytes` " @@ -4385,7 +4767,7 @@ msgstr "" "é aceito para strings de bytes. (Contribuição de Victor Stinner em :gh:" "`98393`.)" -#: ../../whatsnew/3.12.rst:1706 +#: ../../whatsnew/3.12.rst:1721 msgid "" ":func:`syslog.openlog` and :func:`syslog.closelog` now fail if used in " "subinterpreters. :func:`syslog.syslog` may still be used in subinterpreters, " @@ -4396,7 +4778,7 @@ msgid "" "process-global resources, which are best managed from the main interpreter. " "(Contributed by Donghee Na in :gh:`99127`.)" msgstr "" -":func:`syslog.openlog` e :func:`syslog.closelog` agora falham se usadas ​​em " +":func:`syslog.openlog` e :func:`syslog.closelog` agora falham se usadas em " "subinterpretadores. :func:`syslog.syslog` ainda pode ser usada em " "subinterpretadores, mas agora somente se :func:`syslog.openlog` já tiver " "sido chamada no interpretador principal. Estas novas restrições não se " @@ -4406,7 +4788,7 @@ msgstr "" "globais de processo, que são melhor gerenciados a partir do interpretador " "principal. (Contribuição de Donghee Na em :gh:`99127`.)" -#: ../../whatsnew/3.12.rst:1715 +#: ../../whatsnew/3.12.rst:1730 msgid "" "The undocumented locking behavior of :func:`~functools.cached_property` is " "removed, because it locked across all instances of the class, leading to " @@ -4427,7 +4809,7 @@ msgstr "" "suficiente. Se a sincronização for necessária, implemente a trava na função " "getter de propriedade em cache ou em torno de pontos de acesso multithread." -#: ../../whatsnew/3.12.rst:1728 +#: ../../whatsnew/3.12.rst:1743 msgid "" "When extracting tar files using :mod:`tarfile` or :func:`shutil." "unpack_archive`, pass the *filter* argument to limit features that may be " @@ -4438,7 +4820,7 @@ msgstr "" "surpreender ou ser perigosos. Veja :ref:`tarfile-extraction-filter` para " "detalhes." -#: ../../whatsnew/3.12.rst:1733 +#: ../../whatsnew/3.12.rst:1748 msgid "" "The output of the :func:`tokenize.tokenize` and :func:`tokenize." "generate_tokens` functions is now changed due to the changes introduced in :" @@ -4458,11 +4840,37 @@ msgstr "" "tokenização nos componentes da expressão. Por exemplo, para a f-string " "``f\"start {1+1} end\"`` a versão antiga do tokenizer emitida::" -#: ../../whatsnew/3.12.rst:1744 +#: ../../whatsnew/3.12.rst:1757 +msgid "1,0-1,18: STRING 'f\"start {1+1} end\"'" +msgstr "1,0-1,18: STRING 'f\"start {1+1} end\"'" + +#: ../../whatsnew/3.12.rst:1759 msgid "while the new version emits::" msgstr "enquanto a nova versão emite::" -#: ../../whatsnew/3.12.rst:1756 +#: ../../whatsnew/3.12.rst:1761 +msgid "" +"1,0-1,2: FSTRING_START 'f\"'\n" +"1,2-1,8: FSTRING_MIDDLE 'start '\n" +"1,8-1,9: OP '{'\n" +"1,9-1,10: NUMBER '1'\n" +"1,10-1,11: OP '+'\n" +"1,11-1,12: NUMBER '1'\n" +"1,12-1,13: OP '}'\n" +"1,13-1,17: FSTRING_MIDDLE ' end'\n" +"1,17-1,18: FSTRING_END '\"'" +msgstr "" +"1,0-1,2: FSTRING_START 'f\"'\n" +"1,2-1,8: FSTRING_MIDDLE 'start '\n" +"1,8-1,9: OP '{'\n" +"1,9-1,10: NUMBER '1'\n" +"1,10-1,11: OP '+'\n" +"1,11-1,12: NUMBER '1'\n" +"1,12-1,13: OP '}'\n" +"1,13-1,17: FSTRING_MIDDLE ' end'\n" +"1,17-1,18: FSTRING_END '\"'" + +#: ../../whatsnew/3.12.rst:1771 msgid "" "Additionally, there may be some minor behavioral changes as a consequence of " "the changes required to support :pep:`701`. Some of these changes include:" @@ -4471,7 +4879,7 @@ msgstr "" "consequência das alterações necessárias para oferecer suporte à :pep:`701`. " "Algumas dessas mudanças incluem:" -#: ../../whatsnew/3.12.rst:1759 +#: ../../whatsnew/3.12.rst:1774 msgid "" "The ``type`` attribute of the tokens emitted when tokenizing some invalid " "Python characters such as ``!`` has changed from ``ERRORTOKEN`` to ``OP``." @@ -4479,7 +4887,7 @@ msgstr "" "O atributo ``type`` dos tokens emitidos ao tokenizar alguns caracteres " "Python inválidos, como ``!``, mudou de ``ERRORTOKEN`` para ``OP``." -#: ../../whatsnew/3.12.rst:1762 +#: ../../whatsnew/3.12.rst:1777 msgid "" "Incomplete single-line strings now also raise :exc:`tokenize.TokenError` as " "incomplete multiline strings do." @@ -4487,7 +4895,7 @@ msgstr "" "Strings incompletas de linha única agora também levantam :exc:`tokenize." "TokenError` como fazem strings multilinhas incompletas." -#: ../../whatsnew/3.12.rst:1765 +#: ../../whatsnew/3.12.rst:1780 msgid "" "Some incomplete or invalid Python code now raises :exc:`tokenize.TokenError` " "instead of returning arbitrary ``ERRORTOKEN`` tokens when tokenizing it." @@ -4496,7 +4904,7 @@ msgstr "" "TokenError` em vez de retornar tokens ``ERRORTOKEN`` arbitrários ao tokenizá-" "lo." -#: ../../whatsnew/3.12.rst:1768 +#: ../../whatsnew/3.12.rst:1783 msgid "" "Mixing tabs and spaces as indentation in the same file is not supported " "anymore and will raise a :exc:`TabError`." @@ -4504,7 +4912,7 @@ msgstr "" "Misturar tabulações e espaços como indentação no mesmo arquivo não é mais " "suportado e vai levantar uma :exc:`TabError`." -#: ../../whatsnew/3.12.rst:1771 +#: ../../whatsnew/3.12.rst:1786 msgid "" "The :mod:`threading` module now expects the :mod:`!_thread` module to have " "an ``_is_main_interpreter`` attribute. It is a function with no arguments " @@ -4514,7 +4922,7 @@ msgstr "" "atributo ``_is_main_interpreter``. É uma função sem argumentos que retorna " "``True`` se o interpretador atual for o interpretador principal." -#: ../../whatsnew/3.12.rst:1776 +#: ../../whatsnew/3.12.rst:1791 msgid "" "Any library or application that provides a custom ``_thread`` module should " "provide ``_is_main_interpreter()``. (See :gh:`112826`.)" @@ -4522,11 +4930,11 @@ msgstr "" "Qualquer biblioteca ou aplicação que forneça um módulo ``_thread`` " "personalizado deve fornecer ``_is_main_interpreter()``. (Veja :gh:`112826`.)" -#: ../../whatsnew/3.12.rst:1781 +#: ../../whatsnew/3.12.rst:1796 msgid "Build Changes" -msgstr "Alterações de construção" +msgstr "Mudanças na construção" -#: ../../whatsnew/3.12.rst:1783 +#: ../../whatsnew/3.12.rst:1798 msgid "" "Python no longer uses :file:`setup.py` to build shared C extension modules. " "Build parameters like headers and libraries are detected in ``configure`` " @@ -4540,7 +4948,7 @@ msgstr "" "`Makefile`. A maioria das extensões usa ``pkg-config`` e recorre à detecção " "manual. (Contribuição de Christian Heimes em :gh:`93939`.)" -#: ../../whatsnew/3.12.rst:1789 +#: ../../whatsnew/3.12.rst:1804 msgid "" "``va_start()`` with two parameters, like ``va_start(args, format),`` is now " "required to build Python. ``va_start()`` is no longer called with a single " @@ -4550,7 +4958,7 @@ msgstr "" "necessário para construir Python. ``va_start()`` não é mais chamado com um " "único parâmetro. (Contribuição de Kumar Aditya em :gh:`93207`.)" -#: ../../whatsnew/3.12.rst:1794 +#: ../../whatsnew/3.12.rst:1809 msgid "" "CPython now uses the ThinLTO option as the default link time optimization " "policy if the Clang compiler accepts the flag. (Contributed by Donghee Na " @@ -4560,7 +4968,7 @@ msgstr "" "vincualção padrão se o compilador Clang aceitar o sinalizador. (Contribuição " "de Donghee Na em :gh:`89536`.)" -#: ../../whatsnew/3.12.rst:1798 +#: ../../whatsnew/3.12.rst:1813 msgid "" "Add ``COMPILEALL_OPTS`` variable in :file:`Makefile` to override :mod:" "`compileall` options (default: ``-j0``) in ``make install``. Also merged the " @@ -4574,31 +4982,31 @@ msgstr "" "arquivos .pyc para todos os níveis de otimização (0, 1, 2) de uma só vez. " "(Contribuição de Victor Stinner em :gh:`99289`.)" -#: ../../whatsnew/3.12.rst:1804 +#: ../../whatsnew/3.12.rst:1819 msgid "Add platform triplets for 64-bit LoongArch:" msgstr "Adiciona trios de plataforma para LoongArch de 64 bits:" -#: ../../whatsnew/3.12.rst:1806 +#: ../../whatsnew/3.12.rst:1821 msgid "loongarch64-linux-gnusf" msgstr "loongarch64-linux-gnusf" -#: ../../whatsnew/3.12.rst:1807 +#: ../../whatsnew/3.12.rst:1822 msgid "loongarch64-linux-gnuf32" msgstr "loongarch64-linux-gnuf32" -#: ../../whatsnew/3.12.rst:1808 +#: ../../whatsnew/3.12.rst:1823 msgid "loongarch64-linux-gnu" msgstr "loongarch64-linux-gnu" -#: ../../whatsnew/3.12.rst:1810 +#: ../../whatsnew/3.12.rst:1825 msgid "(Contributed by Zhang Na in :gh:`90656`.)" msgstr "(Contribuição de Zhang Na em :gh:`90656`.)" -#: ../../whatsnew/3.12.rst:1812 +#: ../../whatsnew/3.12.rst:1827 msgid "``PYTHON_FOR_REGEN`` now require Python 3.10 or newer." msgstr "``PYTHON_FOR_REGEN`` agora requer Python 3.10 ou mais novo." -#: ../../whatsnew/3.12.rst:1814 +#: ../../whatsnew/3.12.rst:1829 msgid "" "Autoconf 2.71 and aclocal 1.16.4 is now required to regenerate :file:`!" "configure`. (Contributed by Christian Heimes in :gh:`89886`.)" @@ -4606,18 +5014,18 @@ msgstr "" "Autoconf 2.71 e aclocal 1.16.4 agora são necessários para regerar :file:`!" "configure`. (Contribuição de Christian Heimes em :gh:`89886`.)" -#: ../../whatsnew/3.12.rst:1818 +#: ../../whatsnew/3.12.rst:1833 msgid "" "Windows builds and macOS installers from python.org now use OpenSSL 3.0." msgstr "" "Construções do Windows e instaladores do macOS em python.org agora usam " "OpenSSL 3.0." -#: ../../whatsnew/3.12.rst:1822 +#: ../../whatsnew/3.12.rst:1837 msgid "C API Changes" msgstr "Alterações na API C" -#: ../../whatsnew/3.12.rst:1829 +#: ../../whatsnew/3.12.rst:1844 msgid "" ":pep:`697`: Introduce the :ref:`Unstable C API tier `, " "intended for low-level tools like debuggers and JIT compilers. This API may " @@ -4630,15 +5038,15 @@ msgstr "" "descontinuação. Seu conteúdo é marcado pelo prefixo ``PyUnstable_`` nos " "nomes." -#: ../../whatsnew/3.12.rst:1835 +#: ../../whatsnew/3.12.rst:1850 msgid "Code object constructors:" msgstr "Construtores de objeto código:" -#: ../../whatsnew/3.12.rst:1837 +#: ../../whatsnew/3.12.rst:1852 msgid "``PyUnstable_Code_New()`` (renamed from ``PyCode_New``)" msgstr "``PyUnstable_Code_New()`` (renomeado de ``PyCode_New``)" -#: ../../whatsnew/3.12.rst:1838 +#: ../../whatsnew/3.12.rst:1853 msgid "" "``PyUnstable_Code_NewWithPosOnlyArgs()`` (renamed from " "``PyCode_NewWithPosOnlyArgs``)" @@ -4646,11 +5054,11 @@ msgstr "" "``PyUnstable_Code_NewWithPosOnlyArgs()`` (renomeado de " "``PyCode_NewWithPosOnlyArgs``)" -#: ../../whatsnew/3.12.rst:1840 +#: ../../whatsnew/3.12.rst:1855 msgid "Extra storage for code objects (:pep:`523`):" msgstr "Armazenamento extra para objetos código (:pep:`523`):" -#: ../../whatsnew/3.12.rst:1842 +#: ../../whatsnew/3.12.rst:1857 msgid "" "``PyUnstable_Eval_RequestCodeExtraIndex()`` (renamed from " "``_PyEval_RequestCodeExtraIndex``)" @@ -4658,15 +5066,15 @@ msgstr "" "``PyUnstable_Eval_RequestCodeExtraIndex()`` (renomeado de " "``_PyEval_RequestCodeExtraIndex``)" -#: ../../whatsnew/3.12.rst:1843 +#: ../../whatsnew/3.12.rst:1858 msgid "``PyUnstable_Code_GetExtra()`` (renamed from ``_PyCode_GetExtra``)" msgstr "``PyUnstable_Code_GetExtra()`` (renomeado de ``_PyCode_GetExtra``)" -#: ../../whatsnew/3.12.rst:1844 +#: ../../whatsnew/3.12.rst:1859 msgid "``PyUnstable_Code_SetExtra()`` (renamed from ``_PyCode_SetExtra``)" msgstr "``PyUnstable_Code_SetExtra()`` (renomeado de ``_PyCode_SetExtra``)" -#: ../../whatsnew/3.12.rst:1846 +#: ../../whatsnew/3.12.rst:1861 msgid "" "The original names will continue to be available until the respective API " "changes." @@ -4674,11 +5082,11 @@ msgstr "" "Os nomes originais continuarão disponíveis até que a respectiva API seja " "alterada." -#: ../../whatsnew/3.12.rst:1849 +#: ../../whatsnew/3.12.rst:1864 msgid "(Contributed by Petr Viktorin in :gh:`101101`.)" msgstr "(Contribuição de Petr Viktorin em :gh:`101101`.)" -#: ../../whatsnew/3.12.rst:1851 +#: ../../whatsnew/3.12.rst:1866 msgid "" ":pep:`697`: Add an API for extending types whose instance memory layout is " "opaque:" @@ -4686,7 +5094,7 @@ msgstr "" ":pep:`697`: Adiciona uma API para estender tipos cujo layout de memória de " "instância é opaco:" -#: ../../whatsnew/3.12.rst:1854 +#: ../../whatsnew/3.12.rst:1869 msgid "" ":c:member:`PyType_Spec.basicsize` can be zero or negative to specify " "inheriting or extending the base class size." @@ -4694,7 +5102,7 @@ msgstr "" ":c:member:`PyType_Spec.basicsize` pode ser zero ou negativo para especificar " "a herança ou extensão do tamanho da classe base." -#: ../../whatsnew/3.12.rst:1856 +#: ../../whatsnew/3.12.rst:1871 msgid "" ":c:func:`PyObject_GetTypeData` and :c:func:`PyType_GetTypeDataSize` added to " "allow access to subclass-specific instance data." @@ -4703,7 +5111,7 @@ msgstr "" "adicionadas para permitir acesso a dados de instância específicos da " "subclasse." -#: ../../whatsnew/3.12.rst:1858 +#: ../../whatsnew/3.12.rst:1873 msgid "" ":c:macro:`Py_TPFLAGS_ITEMS_AT_END` and :c:func:`PyObject_GetItemData` added " "to allow safely extending certain variable-sized types, including :c:var:" @@ -4713,7 +5121,7 @@ msgstr "" "adicionadas para permitir a extensão segura de certos tipos de tamanho " "variável, incluindo :c:var:`PyType_Type`." -#: ../../whatsnew/3.12.rst:1861 +#: ../../whatsnew/3.12.rst:1876 msgid "" ":c:macro:`Py_RELATIVE_OFFSET` added to allow defining :c:type:`members " "` in terms of a subclass-specific struct." @@ -4722,11 +5130,11 @@ msgstr "" "type:`membros ` em termos de uma estrutura específica da " "subclasse." -#: ../../whatsnew/3.12.rst:1864 +#: ../../whatsnew/3.12.rst:1879 msgid "(Contributed by Petr Viktorin in :gh:`103509`.)" msgstr "(Contribuição de Petr Viktorin em :gh:`103509`.)" -#: ../../whatsnew/3.12.rst:1866 +#: ../../whatsnew/3.12.rst:1881 msgid "" "Add the new :ref:`limited C API ` function :c:func:" "`PyType_FromMetaclass`, which generalizes the existing :c:func:" @@ -4738,7 +5146,7 @@ msgstr "" "existente usando um argumento de metaclasse adicional. (Contribuição de " "Wenzel Jakob em :gh:`93012`.)" -#: ../../whatsnew/3.12.rst:1871 +#: ../../whatsnew/3.12.rst:1886 msgid "" "API for creating objects that can be called using :ref:`the vectorcall " "protocol ` was added to the :ref:`Limited API `:" @@ -4746,23 +5154,23 @@ msgstr "" "API para criação de objetos que podem ser chamados usando :ref:`o protocolo " "vectorcall ` foi adicionada à :ref:`API Limitada `:" -#: ../../whatsnew/3.12.rst:1875 +#: ../../whatsnew/3.12.rst:1890 msgid ":c:macro:`Py_TPFLAGS_HAVE_VECTORCALL`" msgstr ":c:macro:`Py_TPFLAGS_HAVE_VECTORCALL`" -#: ../../whatsnew/3.12.rst:1876 +#: ../../whatsnew/3.12.rst:1891 msgid ":c:func:`PyVectorcall_NARGS`" msgstr ":c:func:`PyVectorcall_NARGS`" -#: ../../whatsnew/3.12.rst:1877 +#: ../../whatsnew/3.12.rst:1892 msgid ":c:func:`PyVectorcall_Call`" msgstr ":c:func:`PyVectorcall_Call`" -#: ../../whatsnew/3.12.rst:1878 +#: ../../whatsnew/3.12.rst:1893 msgid ":c:type:`vectorcallfunc`" msgstr ":c:type:`vectorcallfunc`" -#: ../../whatsnew/3.12.rst:1880 +#: ../../whatsnew/3.12.rst:1895 msgid "" "The :c:macro:`Py_TPFLAGS_HAVE_VECTORCALL` flag is now removed from a class " "when the class's :py:meth:`~object.__call__` method is reassigned. This " @@ -4780,19 +5188,19 @@ msgstr "" "sinalizador ``Py_TPFLAGS_HAVE_VECTORCALL``. (Contribuição de Petr Viktorin " "em :gh:`93274`.)" -#: ../../whatsnew/3.12.rst:1888 +#: ../../whatsnew/3.12.rst:1903 msgid "" "The :c:macro:`Py_TPFLAGS_MANAGED_DICT` and :c:macro:" "`Py_TPFLAGS_MANAGED_WEAKREF` flags have been added. This allows extensions " -"classes to support object ``__dict__`` and weakrefs with less bookkeeping, " -"using less memory and with faster access." +"classes to support object :attr:`~object.__dict__` and weakrefs with less " +"bookkeeping, using less memory and with faster access." msgstr "" "Os sinalizadores :c:macro:`Py_TPFLAGS_MANAGED_DICT` e :c:macro:" "`Py_TPFLAGS_MANAGED_WEAKREF` foram adicionados. Isso permite que as classes " -"de extensões ofereçam suporte a objetos ``__dict__`` e weakrefs com menos " -"trabalho, usando menos memória e com acesso mais rápido." +"de extensões ofereçam suporte a objetos :attr:`~object.__dict__` e weakrefs " +"com menos trabalho, usando menos memória e com acesso mais rápido." -#: ../../whatsnew/3.12.rst:1893 +#: ../../whatsnew/3.12.rst:1908 msgid "" "API for performing calls using :ref:`the vectorcall protocol ` " "was added to the :ref:`Limited API `:" @@ -4800,19 +5208,19 @@ msgstr "" "API para realizar chamadas usando :ref:`o protocolo vectorcall ` " "foi adicionada à :ref:`API Limitada `:" -#: ../../whatsnew/3.12.rst:1897 +#: ../../whatsnew/3.12.rst:1912 msgid ":c:func:`PyObject_Vectorcall`" msgstr ":c:func:`PyObject_Vectorcall`" -#: ../../whatsnew/3.12.rst:1898 +#: ../../whatsnew/3.12.rst:1913 msgid ":c:func:`PyObject_VectorcallMethod`" msgstr ":c:func:`PyObject_VectorcallMethod`" -#: ../../whatsnew/3.12.rst:1899 +#: ../../whatsnew/3.12.rst:1914 msgid ":c:macro:`PY_VECTORCALL_ARGUMENTS_OFFSET`" msgstr ":c:macro:`PY_VECTORCALL_ARGUMENTS_OFFSET`" -#: ../../whatsnew/3.12.rst:1901 +#: ../../whatsnew/3.12.rst:1916 msgid "" "This means that both the incoming and outgoing ends of the vector call " "protocol are now available in the :ref:`Limited API `. (Contributed " @@ -4822,7 +5230,7 @@ msgstr "" "chamada vetorial estão agora disponíveis na :ref:`API Limitada `. " "(Contribuição de Wenzel Jakob em :gh:`98586`.)" -#: ../../whatsnew/3.12.rst:1905 +#: ../../whatsnew/3.12.rst:1920 msgid "" "Add two new public functions, :c:func:`PyEval_SetProfileAllThreads` and :c:" "func:`PyEval_SetTraceAllThreads`, that allow to set tracing and profiling " @@ -4834,7 +5242,7 @@ msgstr "" "rastreamento e perfilação em todos os threads em execução, além do de " "chamada. (Contribuição de Pablo Galindo em :gh:`93503`.)" -#: ../../whatsnew/3.12.rst:1911 +#: ../../whatsnew/3.12.rst:1926 msgid "" "Add new function :c:func:`PyFunction_SetVectorcall` to the C API which sets " "the vectorcall field of a given :c:type:`PyFunctionObject`. (Contributed by " @@ -4844,7 +5252,7 @@ msgstr "" "o campo vectorcall de um determinado :c:type:`PyFunctionObject`. " "(Contribuição de Andrew Frost em :gh:`92257`.)" -#: ../../whatsnew/3.12.rst:1915 +#: ../../whatsnew/3.12.rst:1930 msgid "" "The C API now permits registering callbacks via :c:func:" "`PyDict_AddWatcher`, :c:func:`PyDict_Watch` and related APIs to be called " @@ -4858,7 +5266,7 @@ msgstr "" "otimizar interpretadores, compiladores JIT ou depuradores. (Contribuição de " "Carl Meyer em :gh:`91052`.)" -#: ../../whatsnew/3.12.rst:1921 +#: ../../whatsnew/3.12.rst:1936 msgid "" "Add :c:func:`PyType_AddWatcher` and :c:func:`PyType_Watch` API to register " "callbacks to receive notification on changes to a type. (Contributed by Carl " @@ -4868,7 +5276,7 @@ msgstr "" "registrar retornos de chamada para receber notificações sobre alterações em " "um tipo. (Contribuição de Carl Meyer em :gh:`91051`.)" -#: ../../whatsnew/3.12.rst:1925 +#: ../../whatsnew/3.12.rst:1940 msgid "" "Add :c:func:`PyCode_AddWatcher` and :c:func:`PyCode_ClearWatcher` APIs to " "register callbacks to receive notification on creation and destruction of " @@ -4879,7 +5287,7 @@ msgstr "" "destruição de objetos de código. (Contribuição de Itamar Oren em :gh:" "`91054`.)" -#: ../../whatsnew/3.12.rst:1930 +#: ../../whatsnew/3.12.rst:1945 msgid "" "Add :c:func:`PyFrame_GetVar` and :c:func:`PyFrame_GetVarString` functions to " "get a frame variable by its name. (Contributed by Victor Stinner in :gh:" @@ -4889,7 +5297,7 @@ msgstr "" "`PyFrame_GetVarString` para obter uma variável de quadro por seu nome. " "(Contribuição de Victor Stinner em :gh:`91248`.)" -#: ../../whatsnew/3.12.rst:1934 +#: ../../whatsnew/3.12.rst:1949 msgid "" "Add :c:func:`PyErr_GetRaisedException` and :c:func:" "`PyErr_SetRaisedException` for saving and restoring the current exception. " @@ -4905,7 +5313,7 @@ msgstr "" "Isso é menos sujeito a erros e um pouco mais eficiente. (Contribuição de " "Mark Shannon em :gh:`101578`.)" -#: ../../whatsnew/3.12.rst:1942 +#: ../../whatsnew/3.12.rst:1957 msgid "" "Add ``_PyErr_ChainExceptions1``, which takes an exception instance, to " "replace the legacy-API ``_PyErr_ChainExceptions``, which is now deprecated. " @@ -4915,7 +5323,7 @@ msgstr "" "substituir a API legada ``_PyErr_ChainExceptions``, que agora foi " "descontinuada. (Contribuição de Mark Shannon em :gh:`101578`.)" -#: ../../whatsnew/3.12.rst:1946 +#: ../../whatsnew/3.12.rst:1961 msgid "" "Add :c:func:`PyException_GetArgs` and :c:func:`PyException_SetArgs` as " "convenience functions for retrieving and modifying the :attr:`~BaseException." @@ -4927,7 +5335,7 @@ msgstr "" "args` passado para o construtor da exceção. (Contribuição de Mark Shannon " "em :gh:`101578`.)" -#: ../../whatsnew/3.12.rst:1951 +#: ../../whatsnew/3.12.rst:1966 msgid "" "Add :c:func:`PyErr_DisplayException`, which takes an exception instance, to " "replace the legacy-api :c:func:`!PyErr_Display`. (Contributed by Irit " @@ -4937,7 +5345,7 @@ msgstr "" "para substituir a API legada :c:func:`!PyErr_Display`. (Contribuição de Irit " "Katriel em :gh:`102755`)." -#: ../../whatsnew/3.12.rst:1957 +#: ../../whatsnew/3.12.rst:1972 msgid "" ":pep:`683`: Introduce *Immortal Objects*, which allows objects to bypass " "reference counts, and related changes to the C-API:" @@ -4945,56 +5353,56 @@ msgstr "" ":pep:`683`: Introduz *Objetos Imortais*, que permite que objetos ignorem " "contagens de referências e alterações relacionadas à API C:" -#: ../../whatsnew/3.12.rst:1960 +#: ../../whatsnew/3.12.rst:1975 msgid "``_Py_IMMORTAL_REFCNT``: The reference count that defines an object" msgstr "" "``_Py_IMMORTAL_REFCNT``: A contagem de referências que define um objeto" -#: ../../whatsnew/3.12.rst:1961 +#: ../../whatsnew/3.12.rst:1976 msgid "as immortal." msgstr "como imortal." -#: ../../whatsnew/3.12.rst:1962 +#: ../../whatsnew/3.12.rst:1977 msgid "" "``_Py_IsImmortal`` Checks if an object has the immortal reference count." msgstr "" "``_Py_IsImmortal`` Verifica se um objeto possui a contagem de referências " "imortal." -#: ../../whatsnew/3.12.rst:1963 +#: ../../whatsnew/3.12.rst:1978 msgid "``PyObject_HEAD_INIT`` This will now initialize reference count to" msgstr "" "``PyObject_HEAD_INIT`` Isso agora inicializará a contagem de referências para" -#: ../../whatsnew/3.12.rst:1964 +#: ../../whatsnew/3.12.rst:1979 msgid "``_Py_IMMORTAL_REFCNT`` when used with ``Py_BUILD_CORE``." msgstr "``_Py_IMMORTAL_REFCNT`` quando usado com ``Py_BUILD_CORE``." -#: ../../whatsnew/3.12.rst:1965 +#: ../../whatsnew/3.12.rst:1980 msgid "``SSTATE_INTERNED_IMMORTAL`` An identifier for interned unicode objects" msgstr "" "``SSTATE_INTERNED_IMMORTAL`` Um identificador para objetos unicode " "internalizados" -#: ../../whatsnew/3.12.rst:1966 +#: ../../whatsnew/3.12.rst:1981 msgid "that are immortal." msgstr "que são imortais." -#: ../../whatsnew/3.12.rst:1967 +#: ../../whatsnew/3.12.rst:1982 msgid "``SSTATE_INTERNED_IMMORTAL_STATIC`` An identifier for interned unicode" msgstr "" "``SSTATE_INTERNED_IMMORTAL_STATIC`` Um identificador para unicode " "internalizado" -#: ../../whatsnew/3.12.rst:1968 +#: ../../whatsnew/3.12.rst:1983 msgid "objects that are immortal and static" msgstr "objetos que são imortais e estáticos" -#: ../../whatsnew/3.12.rst:1969 +#: ../../whatsnew/3.12.rst:1984 msgid "``sys.getunicodeinternedsize`` This returns the total number of unicode" msgstr "``sys.getunicodeinternedsize`` Isso retorna o número total de unicode" -#: ../../whatsnew/3.12.rst:1970 +#: ../../whatsnew/3.12.rst:1985 msgid "" "objects that have been interned. This is now needed for :file:`refleak.py` " "to correctly track reference counts and allocated blocks" @@ -5002,11 +5410,11 @@ msgstr "" "objetos que foram internalizados. Isso agora é necessário para :file:" "`refleak.py` rastrear corretamente contagens de referências e blocos alocados" -#: ../../whatsnew/3.12.rst:1973 +#: ../../whatsnew/3.12.rst:1988 msgid "(Contributed by Eddie Elizondo in :gh:`84436`.)" msgstr "(Contribuição de Eddie Elizondo em :gh:`84436`.)" -#: ../../whatsnew/3.12.rst:1975 +#: ../../whatsnew/3.12.rst:1990 msgid "" ":pep:`684`: Add the new :c:func:`Py_NewInterpreterFromConfig` function and :" "c:type:`PyInterpreterConfig`, which may be used to create sub-interpreters " @@ -5018,7 +5426,7 @@ msgstr "" "subinterpretadores com suas próprias GILs. (Veja :ref:`whatsnew312-pep684` " "para mais informações.) (Contribuição de Eric Snow em :gh:`104110`.)" -#: ../../whatsnew/3.12.rst:1981 +#: ../../whatsnew/3.12.rst:1996 msgid "" "In the limited C API version 3.12, :c:func:`Py_INCREF` and :c:func:" "`Py_DECREF` functions are now implemented as opaque function calls to hide " @@ -5029,7 +5437,7 @@ msgstr "" "ocultar detalhes de implementação. (Contribuição de Victor Stinner em :gh:" "`105387`.)" -#: ../../whatsnew/3.12.rst:1989 +#: ../../whatsnew/3.12.rst:2004 msgid "" "Legacy Unicode APIs based on ``Py_UNICODE*`` representation has been " "removed. Please migrate to APIs based on UTF-8 or ``wchar_t*``." @@ -5037,7 +5445,7 @@ msgstr "" "APIs Unicode legadas baseadas na representação de ``Py_UNICODE*`` foram " "removidas. Migre para APIs baseadas em UTF-8 ou ``wchar_t*``." -#: ../../whatsnew/3.12.rst:1992 +#: ../../whatsnew/3.12.rst:2007 msgid "" "Argument parsing functions like :c:func:`PyArg_ParseTuple` doesn't support " "``Py_UNICODE*`` based format (e.g. ``u``, ``Z``) anymore. Please migrate to " @@ -5048,7 +5456,7 @@ msgstr "" "``Z``). Migre para outros formatos para Unicode como ``s``, ``z``, ``es`` e " "``U``." -#: ../../whatsnew/3.12.rst:1996 +#: ../../whatsnew/3.12.rst:2011 msgid "" "``tp_weaklist`` for all static builtin types is always ``NULL``. This is an " "internal-only field on ``PyTypeObject`` but we're pointing out the change in " @@ -5062,7 +5470,7 @@ msgstr "" "evitar quebras, considere usar a API C pública existente ou, se necessário, " "a macro ``_PyObject_GET_WEAKREFS_LISTPTR()`` (somente interna)." -#: ../../whatsnew/3.12.rst:2003 +#: ../../whatsnew/3.12.rst:2018 msgid "" "This internal-only :c:member:`PyTypeObject.tp_subclasses` may now not be a " "valid object pointer. Its type was changed to :c:expr:`void *` to reflect " @@ -5074,15 +5482,15 @@ msgstr "" "*` para refletir isso. Mencionamos isso caso alguém esteja acessando " "diretamente o campo somente interno." -#: ../../whatsnew/3.12.rst:2008 +#: ../../whatsnew/3.12.rst:2023 msgid "" -"To get a list of subclasses, call the Python method :py:meth:`~class." +"To get a list of subclasses, call the Python method :py:meth:`~type." "__subclasses__` (using :c:func:`PyObject_CallMethod`, for example)." msgstr "" -"Para obter uma lista de subclasses, chame o método Python :py:meth:`~class." +"Para obter uma lista de subclasses, chame o método Python :py:meth:`~type." "__subclasses__` (usando :c:func:`PyObject_CallMethod`, por exemplo)." -#: ../../whatsnew/3.12.rst:2012 +#: ../../whatsnew/3.12.rst:2027 msgid "" "Add support of more formatting options (left aligning, octals, uppercase " "hexadecimals, :c:type:`intmax_t`, :c:type:`ptrdiff_t`, :c:type:`wchar_t` C " @@ -5096,7 +5504,7 @@ msgstr "" "`PyUnicode_FromFormat` e :c:func:`PyUnicode_FromFormatV`. (Contribuição de " "Serhiy Storchaka em :gh:`98836`.)" -#: ../../whatsnew/3.12.rst:2018 +#: ../../whatsnew/3.12.rst:2033 msgid "" "An unrecognized format character in :c:func:`PyUnicode_FromFormat` and :c:" "func:`PyUnicode_FromFormatV` now sets a :exc:`SystemError`. In previous " @@ -5110,7 +5518,7 @@ msgstr "" "copiado como estava para a string de resultado e quaisquer argumentos extras " "descartados. (Contribuição de Serhiy Storchaka em :gh:`95781`.)" -#: ../../whatsnew/3.12.rst:2024 +#: ../../whatsnew/3.12.rst:2039 msgid "" "Fix wrong sign placement in :c:func:`PyUnicode_FromFormat` and :c:func:" "`PyUnicode_FromFormatV`. (Contributed by Philip Georgi in :gh:`95504`.)" @@ -5119,10 +5527,10 @@ msgstr "" "`PyUnicode_FromFormat` e :c:func:`PyUnicode_FromFormatV`. (Contribuição de " "Philip Georgi em :gh:`95504`.)" -#: ../../whatsnew/3.12.rst:2028 +#: ../../whatsnew/3.12.rst:2043 msgid "" -"Extension classes wanting to add a ``__dict__`` or weak reference slot " -"should use :c:macro:`Py_TPFLAGS_MANAGED_DICT` and :c:macro:" +"Extension classes wanting to add a :attr:`~object.__dict__` or weak " +"reference slot should use :c:macro:`Py_TPFLAGS_MANAGED_DICT` and :c:macro:" "`Py_TPFLAGS_MANAGED_WEAKREF` instead of ``tp_dictoffset`` and " "``tp_weaklistoffset``, respectively. The use of ``tp_dictoffset`` and " "``tp_weaklistoffset`` is still supported, but does not fully support " @@ -5132,9 +5540,9 @@ msgid "" "traverse and clear their instance's dictionaries. To clear weakrefs, call :c:" "func:`PyObject_ClearWeakRefs`, as before." msgstr "" -"Classes de extensão que desejam adicionar um ``__dict__`` ou slot de " -"referência fraca devem usar :c:macro:`Py_TPFLAGS_MANAGED_DICT` e :c:macro:" -"`Py_TPFLAGS_MANAGED_WEAKREF` em vez de ``tp_dictoffset`` e " +"Classes de extensão que desejam adicionar um :attr:`~object.__dict__` ou " +"slot de referência fraca devem usar :c:macro:`Py_TPFLAGS_MANAGED_DICT` e :c:" +"macro:`Py_TPFLAGS_MANAGED_WEAKREF` em vez de ``tp_dictoffset`` e " "``tp_weaklistoffset``, respectivamente. O uso de ``tp_dictoffset`` e " "``tp_weaklistoffset`` ainda é aceitado, mas não oferece suporte totalmente " "a herança múltipla (:gh:`95589`), e o desempenho pode ser pior. Classes que " @@ -5143,7 +5551,7 @@ msgstr "" "percorrer e limpar os dicionários de sua instância. Para limpar weakrefs " "(referências fracas), chame :c:func:`PyObject_ClearWeakRefs`, como antes." -#: ../../whatsnew/3.12.rst:2040 +#: ../../whatsnew/3.12.rst:2055 msgid "" "The :c:func:`PyUnicode_FSDecoder` function no longer accepts bytes-like " "paths, like :class:`bytearray` and :class:`memoryview` types: only the " @@ -5155,7 +5563,7 @@ msgstr "" "tipo exato :class:`bytes` é aceito para strings de bytes. (Contribuição de " "Victor Stinner em :gh:`98393`.)" -#: ../../whatsnew/3.12.rst:2045 +#: ../../whatsnew/3.12.rst:2060 msgid "" "The :c:macro:`Py_CLEAR`, :c:macro:`Py_SETREF` and :c:macro:`Py_XSETREF` " "macros now only evaluate their arguments once. If an argument has side " @@ -5167,7 +5575,7 @@ msgstr "" "colaterais, esses efeitos colaterais não serão mais duplicados. " "(Contribuição de Victor Stinner em :gh:`98724`.)" -#: ../../whatsnew/3.12.rst:2050 +#: ../../whatsnew/3.12.rst:2065 msgid "" "The interpreter's error indicator is now always normalized. This means that :" "c:func:`PyErr_SetObject`, :c:func:`PyErr_SetString` and the other functions " @@ -5179,7 +5587,7 @@ msgstr "" "outras funções que definem o indicador de erro agora normalizam a exceção " "antes de armazená-la. (Contribuição de Mark Shannon em :gh:`101578`.)" -#: ../../whatsnew/3.12.rst:2055 +#: ../../whatsnew/3.12.rst:2070 msgid "" "``_Py_RefTotal`` is no longer authoritative and only kept around for ABI " "compatibility. Note that it is an internal global and only available on " @@ -5191,7 +5599,7 @@ msgstr "" "compilações de depuração. Se acontecer de você usá-lo, você precisará " "começar a usar ``_Py_GetGlobalRefTotal()``." -#: ../../whatsnew/3.12.rst:2060 +#: ../../whatsnew/3.12.rst:2075 msgid "" "The following functions now select an appropriate metaclass for the newly " "created type:" @@ -5199,19 +5607,19 @@ msgstr "" "As seguintes funções agora selecionam uma metaclasse apropriada para o tipo " "recém-criado:" -#: ../../whatsnew/3.12.rst:2063 +#: ../../whatsnew/3.12.rst:2078 msgid ":c:func:`PyType_FromSpec`" msgstr ":c:func:`PyType_FromSpec`" -#: ../../whatsnew/3.12.rst:2064 +#: ../../whatsnew/3.12.rst:2079 msgid ":c:func:`PyType_FromSpecWithBases`" msgstr ":c:func:`PyType_FromSpecWithBases`" -#: ../../whatsnew/3.12.rst:2065 +#: ../../whatsnew/3.12.rst:2080 msgid ":c:func:`PyType_FromModuleAndSpec`" msgstr ":c:func:`PyType_FromModuleAndSpec`" -#: ../../whatsnew/3.12.rst:2067 +#: ../../whatsnew/3.12.rst:2082 msgid "" "Creating classes whose metaclass overrides :c:member:`~PyTypeObject.tp_new` " "is deprecated, and in Python 3.14+ it will be disallowed. Note that these " @@ -5223,7 +5631,7 @@ msgstr "" "permitida. Observe que essas funções ignoram ``tp_new`` da metaclasse, " "possivelmente permitindo uma inicialização incompleta." -#: ../../whatsnew/3.12.rst:2072 +#: ../../whatsnew/3.12.rst:2087 msgid "" "Note that :c:func:`PyType_FromMetaclass` (added in Python 3.12) already " "disallows creating classes whose metaclass overrides ``tp_new`` (:meth:" @@ -5233,7 +5641,7 @@ msgstr "" "não permite a criação de classes cuja metaclasse substitui ``tp_new`` (:meth:" "`~object.__new__` em Python)." -#: ../../whatsnew/3.12.rst:2076 +#: ../../whatsnew/3.12.rst:2091 msgid "" "Since ``tp_new`` overrides almost everything ``PyType_From*`` functions do, " "the two are incompatible with each other. The existing behavior -- ignoring " @@ -5247,11 +5655,11 @@ msgstr "" "vez que as (meta)classes presumem que ``tp_new`` foi chamado. Não existe uma " "solução geral simples. Um dos seguintes pode funcionar para você:" -#: ../../whatsnew/3.12.rst:2083 +#: ../../whatsnew/3.12.rst:2098 msgid "If you control the metaclass, avoid using ``tp_new`` in it:" msgstr "Se você controla a metaclasse, evite usar ``tp_new`` nela:" -#: ../../whatsnew/3.12.rst:2085 +#: ../../whatsnew/3.12.rst:2100 msgid "" "If initialization can be skipped, it can be done in :c:member:`~PyTypeObject." "tp_init` instead." @@ -5259,7 +5667,7 @@ msgstr "" "Se a inicialização puder ser ignorada, isso pode ser feito em :c:member:" "`~PyTypeObject.tp_init`." -#: ../../whatsnew/3.12.rst:2087 +#: ../../whatsnew/3.12.rst:2102 msgid "" "If the metaclass doesn't need to be instantiated from Python, set its " "``tp_new`` to ``NULL`` using the :c:macro:" @@ -5271,7 +5679,7 @@ msgstr "" "`Py_TPFLAGS_DISALLOW_INSTANTIATION`. Isso o torna aceitável para funções " "``PyType_From*``." -#: ../../whatsnew/3.12.rst:2092 +#: ../../whatsnew/3.12.rst:2107 msgid "" "Avoid ``PyType_From*`` functions: if you don't need C-specific features " "(slots or setting the instance size), create types by :ref:`calling ` " @@ -5281,7 +5689,7 @@ msgstr "" "do C (slots ou configuração do tamanho da instância), crie tipos :ref:" "`chamando ` a metaclasse." -#: ../../whatsnew/3.12.rst:2096 +#: ../../whatsnew/3.12.rst:2111 msgid "" "If you *know* the ``tp_new`` can be skipped safely, filter the deprecation " "warning out using :func:`warnings.catch_warnings` from Python." @@ -5289,7 +5697,7 @@ msgstr "" "Se você *sabe* que ``tp_new`` pode ser ignorado com segurança, filtre o " "aviso de descontinuação usando :func:`warnings.catch_warnings` do Python." -#: ../../whatsnew/3.12.rst:2099 +#: ../../whatsnew/3.12.rst:2114 msgid "" ":c:var:`PyOS_InputHook` and :c:var:`PyOS_ReadlineFunctionPointer` are no " "longer called in :ref:`subinterpreters `. This is " @@ -5302,7 +5710,7 @@ msgstr "" "(uma vez que esses retornos de chamada não têm como recuperar o estado do " "módulo de extensão)." -#: ../../whatsnew/3.12.rst:2104 +#: ../../whatsnew/3.12.rst:2119 msgid "" "This also avoids situations where extensions may find themselves running in " "a subinterpreter that they don't support (or haven't yet been loaded in). " @@ -5312,7 +5720,7 @@ msgstr "" "subinterpretador que não oferecem suporte (ou no qual ainda não foram " "carregadas). Veja :gh:`104668` para mais informações." -#: ../../whatsnew/3.12.rst:2108 +#: ../../whatsnew/3.12.rst:2123 msgid "" ":c:struct:`PyLongObject` has had its internals changed for better " "performance. Although the internals of :c:struct:`PyLongObject` are private, " @@ -5330,15 +5738,15 @@ msgstr "" "*instáveis* são fornecidas para acesso eficiente ao valor de :c:struct:" "`PyLongObject`\\s que cabe em uma única palavra de máquina:" -#: ../../whatsnew/3.12.rst:2116 +#: ../../whatsnew/3.12.rst:2131 msgid ":c:func:`PyUnstable_Long_IsCompact`" msgstr ":c:func:`PyUnstable_Long_IsCompact`" -#: ../../whatsnew/3.12.rst:2117 +#: ../../whatsnew/3.12.rst:2132 msgid ":c:func:`PyUnstable_Long_CompactValue`" msgstr ":c:func:`PyUnstable_Long_CompactValue`" -#: ../../whatsnew/3.12.rst:2119 +#: ../../whatsnew/3.12.rst:2134 msgid "" "Custom allocators, set via :c:func:`PyMem_SetAllocator`, are now required to " "be thread-safe, regardless of memory domain. Allocators that don't have " @@ -5353,7 +5761,7 @@ msgstr "" "você precisar de orientação, crie um novo relatório de problema no GitHub e " "CC ``@ericsnowcurrently``." -#: ../../whatsnew/3.12.rst:2129 +#: ../../whatsnew/3.12.rst:2144 msgid "" "In accordance with :pep:`699`, the ``ma_version_tag`` field in :c:type:" "`PyDictObject` is deprecated for extension modules. Accessing this field " @@ -5367,71 +5775,71 @@ msgstr "" "removido no Python 3.14. (Contribuição de Ramvikrams e Kumar Aditya em :gh:" "`101193`. PEP de Ken Jin.)" -#: ../../whatsnew/3.12.rst:2134 +#: ../../whatsnew/3.12.rst:2149 msgid "Deprecate global configuration variable:" msgstr "Variáveis de configuração global descontinuadas:" -#: ../../whatsnew/3.12.rst:2136 +#: ../../whatsnew/3.12.rst:2151 msgid ":c:var:`Py_DebugFlag`: use :c:member:`PyConfig.parser_debug`" msgstr ":c:var:`Py_DebugFlag`: use :c:member:`PyConfig.parser_debug`" -#: ../../whatsnew/3.12.rst:2137 +#: ../../whatsnew/3.12.rst:2152 msgid ":c:var:`Py_VerboseFlag`: use :c:member:`PyConfig.verbose`" msgstr ":c:var:`Py_VerboseFlag`: use :c:member:`PyConfig.verbose`" -#: ../../whatsnew/3.12.rst:2138 +#: ../../whatsnew/3.12.rst:2153 msgid ":c:var:`Py_QuietFlag`: use :c:member:`PyConfig.quiet`" msgstr ":c:var:`Py_QuietFlag`: use :c:member:`PyConfig.quiet`" -#: ../../whatsnew/3.12.rst:2139 +#: ../../whatsnew/3.12.rst:2154 msgid ":c:var:`Py_InteractiveFlag`: use :c:member:`PyConfig.interactive`" msgstr ":c:var:`Py_InteractiveFlag`: use :c:member:`PyConfig.interactive`" -#: ../../whatsnew/3.12.rst:2140 +#: ../../whatsnew/3.12.rst:2155 msgid ":c:var:`Py_InspectFlag`: use :c:member:`PyConfig.inspect`" msgstr ":c:var:`Py_InspectFlag`: use :c:member:`PyConfig.inspect`" -#: ../../whatsnew/3.12.rst:2141 +#: ../../whatsnew/3.12.rst:2156 msgid ":c:var:`Py_OptimizeFlag`: use :c:member:`PyConfig.optimization_level`" msgstr ":c:var:`Py_OptimizeFlag`: use :c:member:`PyConfig.optimization_level`" -#: ../../whatsnew/3.12.rst:2142 +#: ../../whatsnew/3.12.rst:2157 msgid ":c:var:`Py_NoSiteFlag`: use :c:member:`PyConfig.site_import`" msgstr ":c:var:`Py_NoSiteFlag`: use :c:member:`PyConfig.site_import`" -#: ../../whatsnew/3.12.rst:2143 +#: ../../whatsnew/3.12.rst:2158 msgid ":c:var:`Py_BytesWarningFlag`: use :c:member:`PyConfig.bytes_warning`" msgstr ":c:var:`Py_BytesWarningFlag`: use :c:member:`PyConfig.bytes_warning`" -#: ../../whatsnew/3.12.rst:2144 +#: ../../whatsnew/3.12.rst:2159 msgid ":c:var:`Py_FrozenFlag`: use :c:member:`PyConfig.pathconfig_warnings`" msgstr ":c:var:`Py_FrozenFlag`: use :c:member:`PyConfig.pathconfig_warnings`" -#: ../../whatsnew/3.12.rst:2145 +#: ../../whatsnew/3.12.rst:2160 msgid "" ":c:var:`Py_IgnoreEnvironmentFlag`: use :c:member:`PyConfig.use_environment`" msgstr "" ":c:var:`Py_IgnoreEnvironmentFlag`: use :c:member:`PyConfig.use_environment`" -#: ../../whatsnew/3.12.rst:2146 +#: ../../whatsnew/3.12.rst:2161 msgid "" ":c:var:`Py_DontWriteBytecodeFlag`: use :c:member:`PyConfig.write_bytecode`" msgstr "" ":c:var:`Py_DontWriteBytecodeFlag`: use :c:member:`PyConfig.write_bytecode`" -#: ../../whatsnew/3.12.rst:2147 +#: ../../whatsnew/3.12.rst:2162 msgid "" ":c:var:`Py_NoUserSiteDirectory`: use :c:member:`PyConfig.user_site_directory`" msgstr "" ":c:var:`Py_NoUserSiteDirectory`: use :c:member:`PyConfig.user_site_directory`" -#: ../../whatsnew/3.12.rst:2148 +#: ../../whatsnew/3.12.rst:2163 msgid "" ":c:var:`Py_UnbufferedStdioFlag`: use :c:member:`PyConfig.buffered_stdio`" msgstr "" ":c:var:`Py_UnbufferedStdioFlag`: use :c:member:`PyConfig.buffered_stdio`" -#: ../../whatsnew/3.12.rst:2149 +#: ../../whatsnew/3.12.rst:2164 msgid "" ":c:var:`Py_HashRandomizationFlag`: use :c:member:`PyConfig.use_hash_seed` " "and :c:member:`PyConfig.hash_seed`" @@ -5439,11 +5847,11 @@ msgstr "" ":c:var:`Py_HashRandomizationFlag`: use :c:member:`PyConfig.use_hash_seed` " "and :c:member:`PyConfig.hash_seed`" -#: ../../whatsnew/3.12.rst:2151 +#: ../../whatsnew/3.12.rst:2166 msgid ":c:var:`Py_IsolatedFlag`: use :c:member:`PyConfig.isolated`" msgstr ":c:var:`Py_IsolatedFlag`: use :c:member:`PyConfig.isolated`" -#: ../../whatsnew/3.12.rst:2152 +#: ../../whatsnew/3.12.rst:2167 msgid "" ":c:var:`Py_LegacyWindowsFSEncodingFlag`: use :c:member:`PyPreConfig." "legacy_windows_fs_encoding`" @@ -5451,7 +5859,7 @@ msgstr "" ":c:var:`Py_LegacyWindowsFSEncodingFlag`: use :c:member:`PyPreConfig." "legacy_windows_fs_encoding`" -#: ../../whatsnew/3.12.rst:2153 +#: ../../whatsnew/3.12.rst:2168 msgid "" ":c:var:`Py_LegacyWindowsStdioFlag`: use :c:member:`PyConfig." "legacy_windows_stdio`" @@ -5459,7 +5867,7 @@ msgstr "" ":c:var:`Py_LegacyWindowsStdioFlag`: use :c:member:`PyConfig." "legacy_windows_stdio`" -#: ../../whatsnew/3.12.rst:2154 +#: ../../whatsnew/3.12.rst:2169 msgid "" ":c:var:`!Py_FileSystemDefaultEncoding`: use :c:member:`PyConfig." "filesystem_encoding`" @@ -5467,7 +5875,7 @@ msgstr "" ":c:var:`!Py_FileSystemDefaultEncoding`: use :c:member:`PyConfig." "filesystem_encoding`" -#: ../../whatsnew/3.12.rst:2155 +#: ../../whatsnew/3.12.rst:2170 msgid "" ":c:var:`!Py_HasFileSystemDefaultEncoding`: use :c:member:`PyConfig." "filesystem_encoding`" @@ -5475,7 +5883,7 @@ msgstr "" ":c:var:`!Py_HasFileSystemDefaultEncoding`: use :c:member:`PyConfig." "filesystem_encoding`" -#: ../../whatsnew/3.12.rst:2156 +#: ../../whatsnew/3.12.rst:2171 msgid "" ":c:var:`!Py_FileSystemDefaultEncodeErrors`: use :c:member:`PyConfig." "filesystem_errors`" @@ -5483,7 +5891,7 @@ msgstr "" ":c:var:`!Py_FileSystemDefaultEncodeErrors`: use :c:member:`PyConfig." "filesystem_errors`" -#: ../../whatsnew/3.12.rst:2157 +#: ../../whatsnew/3.12.rst:2172 msgid "" ":c:var:`!Py_UTF8Mode`: use :c:member:`PyPreConfig.utf8_mode` (see :c:func:" "`Py_PreInitialize`)" @@ -5491,7 +5899,7 @@ msgstr "" ":c:var:`!Py_UTF8Mode`: use :c:member:`PyPreConfig.utf8_mode` (see :c:func:" "`Py_PreInitialize`)" -#: ../../whatsnew/3.12.rst:2159 +#: ../../whatsnew/3.12.rst:2174 msgid "" "The :c:func:`Py_InitializeFromConfig` API should be used with :c:type:" "`PyConfig` instead. (Contributed by Victor Stinner in :gh:`77782`.)" @@ -5499,7 +5907,7 @@ msgstr "" "A API :c:func:`Py_InitializeFromConfig` deve ser usada com :c:type:" "`PyConfig`. (Contribuição de Victor Stinner em :gh:`77782`.)" -#: ../../whatsnew/3.12.rst:2163 +#: ../../whatsnew/3.12.rst:2178 msgid "" "Creating :c:data:`immutable types ` with mutable " "bases is deprecated and will be disabled in Python 3.14. (:gh:`95388`)" @@ -5507,7 +5915,7 @@ msgstr "" "A criação de :c:data:`tipos imutáveis ` com bases " "mutáveis foi descontinuada e será desativada no Python 3.14. (:gh:`95388`)" -#: ../../whatsnew/3.12.rst:2166 +#: ../../whatsnew/3.12.rst:2181 msgid "" "The :file:`structmember.h` header is deprecated, though it continues to be " "available and there are no plans to remove it." @@ -5515,7 +5923,7 @@ msgstr "" "O cabeçalho :file:`structmember.h` foi descontinuado, embora continue " "disponível e não haja planos para removê-lo." -#: ../../whatsnew/3.12.rst:2169 +#: ../../whatsnew/3.12.rst:2184 msgid "" "Its contents are now available just by including :file:`Python.h`, with a " "``Py`` prefix added if it was missing:" @@ -5523,7 +5931,7 @@ msgstr "" "Seu conteúdo agora está disponível apenas incluindo :file:`Python.h`, com um " "prefixo ``Py`` adicionado se estiver faltando:" -#: ../../whatsnew/3.12.rst:2172 +#: ../../whatsnew/3.12.rst:2187 msgid "" ":c:struct:`PyMemberDef`, :c:func:`PyMember_GetOne` and :c:func:" "`PyMember_SetOne`" @@ -5531,7 +5939,7 @@ msgstr "" ":c:struct:`PyMemberDef`, :c:func:`PyMember_GetOne` e :c:func:" "`PyMember_SetOne`" -#: ../../whatsnew/3.12.rst:2174 +#: ../../whatsnew/3.12.rst:2189 msgid "" "Type macros like :c:macro:`Py_T_INT`, :c:macro:`Py_T_DOUBLE`, etc. " "(previously ``T_INT``, ``T_DOUBLE``, etc.)" @@ -5539,7 +5947,7 @@ msgstr "" "Macros de tipo como :c:macro:`Py_T_INT`, :c:macro:`Py_T_DOUBLE`, etc. " "(anteriormente ``T_INT``, ``T_DOUBLE``, etc.)" -#: ../../whatsnew/3.12.rst:2176 +#: ../../whatsnew/3.12.rst:2191 msgid "" "The flags :c:macro:`Py_READONLY` (previously ``READONLY``) and :c:macro:" "`Py_AUDIT_READ` (previously all uppercase)" @@ -5547,23 +5955,23 @@ msgstr "" "Os sinalizadores :c:macro:`Py_READONLY` (anteriormente ``READONLY``) e :c:" "macro:`Py_AUDIT_READ` (anteriormente todas em maiúsculas)" -#: ../../whatsnew/3.12.rst:2179 +#: ../../whatsnew/3.12.rst:2194 msgid "Several items are not exposed from :file:`Python.h`:" msgstr "Vários itens não são expostos em :file:`Python.h`:" -#: ../../whatsnew/3.12.rst:2181 +#: ../../whatsnew/3.12.rst:2196 msgid ":c:macro:`T_OBJECT` (use :c:macro:`Py_T_OBJECT_EX`)" msgstr ":c:macro:`T_OBJECT` (use :c:macro:`Py_T_OBJECT_EX`)" -#: ../../whatsnew/3.12.rst:2182 +#: ../../whatsnew/3.12.rst:2197 msgid ":c:macro:`T_NONE` (previously undocumented, and pretty quirky)" msgstr ":c:macro:`T_NONE` (anteriormente não documentada e bastante estranha)" -#: ../../whatsnew/3.12.rst:2183 +#: ../../whatsnew/3.12.rst:2198 msgid "The macro ``WRITE_RESTRICTED`` which does nothing." msgstr "A macro ``WRITE_RESTRICTED`` que não faz nada." -#: ../../whatsnew/3.12.rst:2184 +#: ../../whatsnew/3.12.rst:2199 msgid "" "The macros ``RESTRICTED`` and ``READ_RESTRICTED``, equivalents of :c:macro:" "`Py_AUDIT_READ`." @@ -5571,7 +5979,7 @@ msgstr "" "As macros ``RESTRICTED`` e ``READ_RESTRICTED``, equivalentes a :c:macro:" "`Py_AUDIT_READ`." -#: ../../whatsnew/3.12.rst:2186 +#: ../../whatsnew/3.12.rst:2201 msgid "" "In some configurations, ```` is not included from :file:`Python." "h`. It should be included manually when using ``offsetof()``." @@ -5579,7 +5987,7 @@ msgstr "" "Em algumas configurações, ```` não está incluído em :file:`Python." "h`. Deve ser incluído manualmente ao usar ``offsetof()``." -#: ../../whatsnew/3.12.rst:2189 +#: ../../whatsnew/3.12.rst:2204 msgid "" "The deprecated header continues to provide its original contents under the " "original names. Your old code can stay unchanged, unless the extra include " @@ -5589,7 +5997,7 @@ msgstr "" "nomes originais. Seu código antigo pode permanecer inalterado, a menos que " "as macros extras e sem namespace o incomodem muito." -#: ../../whatsnew/3.12.rst:2194 +#: ../../whatsnew/3.12.rst:2209 msgid "" "(Contributed in :gh:`47146` by Petr Viktorin, based on earlier work by " "Alexander Belopolsky and Matthias Braun.)" @@ -5597,7 +6005,7 @@ msgstr "" "(Contribuição em :gh:`47146` de Petr Viktorin, baseado em trabalhos " "anteriores de Alexander Belopolsky e Matthias Braun.)" -#: ../../whatsnew/3.12.rst:2197 +#: ../../whatsnew/3.12.rst:2212 msgid "" ":c:func:`PyErr_Fetch` and :c:func:`PyErr_Restore` are deprecated. Use :c:" "func:`PyErr_GetRaisedException` and :c:func:`PyErr_SetRaisedException` " @@ -5607,7 +6015,7 @@ msgstr "" "func:`PyErr_GetRaisedException` e :c:func:`PyErr_SetRaisedException` em vez " "disso. (Contribuição de Mark Shannon em :gh:`101578`.)" -#: ../../whatsnew/3.12.rst:2202 +#: ../../whatsnew/3.12.rst:2217 msgid "" ":c:func:`!PyErr_Display` is deprecated. Use :c:func:`PyErr_DisplayException` " "instead. (Contributed by Irit Katriel in :gh:`102755`)." @@ -5616,7 +6024,7 @@ msgstr "" "`PyErr_DisplayException` em vez disso. (Contribuição de Irit Katriel em :gh:" "`102755`)." -#: ../../whatsnew/3.12.rst:2205 +#: ../../whatsnew/3.12.rst:2220 msgid "" "``_PyErr_ChainExceptions`` is deprecated. Use ``_PyErr_ChainExceptions1`` " "instead. (Contributed by Irit Katriel in :gh:`102192`.)" @@ -5625,7 +6033,7 @@ msgstr "" "``_PyErr_ChainExceptions1`` em vez disso. (Contribuição de Irit Katriel em :" "gh:`102192`.)" -#: ../../whatsnew/3.12.rst:2208 +#: ../../whatsnew/3.12.rst:2223 msgid "" "Using :c:func:`PyType_FromSpec`, :c:func:`PyType_FromSpecWithBases` or :c:" "func:`PyType_FromModuleAndSpec` to create a class whose metaclass overrides :" @@ -5660,162 +6068,165 @@ msgstr "" "3.11:" #: ../../deprecations/c-api-pending-removal-in-3.14.rst:12 -msgid "``PySys_SetArgvEx()``: set :c:member:`PyConfig.argv` instead." -msgstr "``PySys_SetArgvEx()``: defina :c:member:`PyConfig.argv`." - -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:13 -msgid "``PySys_SetArgv()``: set :c:member:`PyConfig.argv` instead." -msgstr "``PySys_SetArgv()``: defina :c:member:`PyConfig.argv`." +msgid ":c:func:`!PySys_SetArgvEx()`: Set :c:member:`PyConfig.argv` instead." +msgstr ":c:func:`!PySys_SetArgvEx()`: defina :c:member:`PyConfig.argv`." #: ../../deprecations/c-api-pending-removal-in-3.14.rst:14 -msgid "``Py_SetProgramName()``: set :c:member:`PyConfig.program_name` instead." -msgstr "``Py_SetProgramName()``: defina :c:member:`PyConfig.program_name`." +msgid ":c:func:`!PySys_SetArgv()`: Set :c:member:`PyConfig.argv` instead." +msgstr ":c:func:`!PySys_SetArgv()`: defina :c:member:`PyConfig.argv`." + +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:16 +msgid "" +":c:func:`!Py_SetProgramName()`: Set :c:member:`PyConfig.program_name` " +"instead." +msgstr "" +":c:func:`!Py_SetProgramName()`: defina :c:member:`PyConfig.program_name`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:15 -msgid "``Py_SetPythonHome()``: set :c:member:`PyConfig.home` instead." -msgstr "``Py_SetPythonHome()``: defina :c:member:`PyConfig.home`." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:18 +msgid ":c:func:`!Py_SetPythonHome()`: Set :c:member:`PyConfig.home` instead." +msgstr ":c:func:`!Py_SetPythonHome()`: defina :c:member:`PyConfig.home`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:17 -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:45 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:21 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:71 msgid "" "The :c:func:`Py_InitializeFromConfig` API should be used with :c:type:" "`PyConfig` instead." msgstr "" -"A API :c:func:`Py_InitializeFromConfig` deve ser usada com :c:type:" -"`PyConfig`." +"Em vez disso, a API :c:func:`Py_InitializeFromConfig` deve ser usada com :c:" +"type:`PyConfig`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:20 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:24 msgid "Global configuration variables:" msgstr "Variáveis de configuração globais" -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:22 -msgid ":c:var:`Py_DebugFlag`: use :c:member:`PyConfig.parser_debug` instead." -msgstr ":c:var:`Py_DebugFlag`: use :c:member:`PyConfig.parser_debug`." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:26 +msgid ":c:var:`Py_DebugFlag`: Use :c:member:`PyConfig.parser_debug` instead." +msgstr ":c:var:`Py_DebugFlag`: Use :c:member:`PyConfig.parser_debug`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:23 -msgid ":c:var:`Py_VerboseFlag`: use :c:member:`PyConfig.verbose` instead." -msgstr ":c:var:`Py_VerboseFlag`: use :c:member:`PyConfig.verbose`." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:28 +msgid ":c:var:`Py_VerboseFlag`: Use :c:member:`PyConfig.verbose` instead." +msgstr ":c:var:`Py_VerboseFlag`: Use :c:member:`PyConfig.verbose`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:24 -msgid ":c:var:`Py_QuietFlag`: use :c:member:`PyConfig.quiet` instead." -msgstr ":c:var:`Py_QuietFlag`: use :c:member:`PyConfig.quiet`." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:30 +msgid ":c:var:`Py_QuietFlag`: Use :c:member:`PyConfig.quiet` instead." +msgstr ":c:var:`Py_QuietFlag`: Use :c:member:`PyConfig.quiet`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:25 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:32 msgid "" -":c:var:`Py_InteractiveFlag`: use :c:member:`PyConfig.interactive` instead." -msgstr ":c:var:`Py_InteractiveFlag`: use :c:member:`PyConfig.interactive`." +":c:var:`Py_InteractiveFlag`: Use :c:member:`PyConfig.interactive` instead." +msgstr ":c:var:`Py_InteractiveFlag`: Use :c:member:`PyConfig.interactive`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:26 -msgid ":c:var:`Py_InspectFlag`: use :c:member:`PyConfig.inspect` instead." -msgstr ":c:var:`Py_InspectFlag`: use :c:member:`PyConfig.inspect`." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:34 +msgid ":c:var:`Py_InspectFlag`: Use :c:member:`PyConfig.inspect` instead." +msgstr ":c:var:`Py_InspectFlag`: Use :c:member:`PyConfig.inspect`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:27 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:36 msgid "" -":c:var:`Py_OptimizeFlag`: use :c:member:`PyConfig.optimization_level` " +":c:var:`Py_OptimizeFlag`: Use :c:member:`PyConfig.optimization_level` " "instead." -msgstr ":c:var:`Py_OptimizeFlag`: use :c:member:`PyConfig.optimization_level`." +msgstr ":c:var:`Py_OptimizeFlag`: Use :c:member:`PyConfig.optimization_level`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:28 -msgid ":c:var:`Py_NoSiteFlag`: use :c:member:`PyConfig.site_import` instead." -msgstr ":c:var:`Py_NoSiteFlag`: use :c:member:`PyConfig.site_import` ." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:38 +msgid ":c:var:`Py_NoSiteFlag`: Use :c:member:`PyConfig.site_import` instead." +msgstr ":c:var:`Py_NoSiteFlag`: Use :c:member:`PyConfig.site_import`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:29 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:40 msgid "" -":c:var:`Py_BytesWarningFlag`: use :c:member:`PyConfig.bytes_warning` instead." -msgstr ":c:var:`Py_BytesWarningFlag`: use :c:member:`PyConfig.bytes_warning`." +":c:var:`Py_BytesWarningFlag`: Use :c:member:`PyConfig.bytes_warning` instead." +msgstr ":c:var:`Py_BytesWarningFlag`: Use :c:member:`PyConfig.bytes_warning`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:30 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:42 msgid "" -":c:var:`Py_FrozenFlag`: use :c:member:`PyConfig.pathconfig_warnings` instead." -msgstr ":c:var:`Py_FrozenFlag`: use :c:member:`PyConfig.pathconfig_warnings`." +":c:var:`Py_FrozenFlag`: Use :c:member:`PyConfig.pathconfig_warnings` instead." +msgstr ":c:var:`Py_FrozenFlag`: Use :c:member:`PyConfig.pathconfig_warnings`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:31 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:44 msgid "" -":c:var:`Py_IgnoreEnvironmentFlag`: use :c:member:`PyConfig.use_environment` " +":c:var:`Py_IgnoreEnvironmentFlag`: Use :c:member:`PyConfig.use_environment` " "instead." msgstr "" -":c:var:`Py_IgnoreEnvironmentFlag`: use :c:member:`PyConfig.use_environment`." +":c:var:`Py_IgnoreEnvironmentFlag`: Use :c:member:`PyConfig.use_environment`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:32 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:46 msgid "" -":c:var:`Py_DontWriteBytecodeFlag`: use :c:member:`PyConfig.write_bytecode` " +":c:var:`Py_DontWriteBytecodeFlag`: Use :c:member:`PyConfig.write_bytecode` " "instead." msgstr "" -":c:var:`Py_DontWriteBytecodeFlag`: use :c:member:`PyConfig.write_bytecode`." +":c:var:`Py_DontWriteBytecodeFlag`: Use :c:member:`PyConfig.write_bytecode`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:33 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:48 msgid "" -":c:var:`Py_NoUserSiteDirectory`: use :c:member:`PyConfig." +":c:var:`Py_NoUserSiteDirectory`: Use :c:member:`PyConfig." "user_site_directory` instead." msgstr "" -":c:var:`Py_NoUserSiteDirectory`: use :c:member:`PyConfig." +":c:var:`Py_NoUserSiteDirectory`: Use :c:member:`PyConfig." "user_site_directory`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:34 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:50 msgid "" -":c:var:`Py_UnbufferedStdioFlag`: use :c:member:`PyConfig.buffered_stdio` " +":c:var:`Py_UnbufferedStdioFlag`: Use :c:member:`PyConfig.buffered_stdio` " "instead." msgstr "" -":c:var:`Py_UnbufferedStdioFlag`: use :c:member:`PyConfig.buffered_stdio`." +":c:var:`Py_UnbufferedStdioFlag`: Use :c:member:`PyConfig.buffered_stdio`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:35 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:52 msgid "" -":c:var:`Py_HashRandomizationFlag`: use :c:member:`PyConfig.use_hash_seed` " +":c:var:`Py_HashRandomizationFlag`: Use :c:member:`PyConfig.use_hash_seed` " "and :c:member:`PyConfig.hash_seed` instead." msgstr "" -":c:var:`Py_HashRandomizationFlag`: use :c:member:`PyConfig.use_hash_seed` e :" +":c:var:`Py_HashRandomizationFlag`: Use :c:member:`PyConfig.use_hash_seed` e :" "c:member:`PyConfig.hash_seed`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:37 -msgid ":c:var:`Py_IsolatedFlag`: use :c:member:`PyConfig.isolated` instead." -msgstr ":c:var:`Py_IsolatedFlag`: use :c:member:`PyConfig.isolated`." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:55 +msgid ":c:var:`Py_IsolatedFlag`: Use :c:member:`PyConfig.isolated` instead." +msgstr ":c:var:`Py_IsolatedFlag`: Use :c:member:`PyConfig.isolated`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:38 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:57 msgid "" -":c:var:`Py_LegacyWindowsFSEncodingFlag`: use :c:member:`PyPreConfig." +":c:var:`Py_LegacyWindowsFSEncodingFlag`: Use :c:member:`PyPreConfig." "legacy_windows_fs_encoding` instead." msgstr "" -":c:var:`Py_LegacyWindowsFSEncodingFlag`: use :c:member:`PyPreConfig." +":c:var:`Py_LegacyWindowsFSEncodingFlag`: Use :c:member:`PyPreConfig." "legacy_windows_fs_encoding`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:39 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:59 msgid "" -":c:var:`Py_LegacyWindowsStdioFlag`: use :c:member:`PyConfig." +":c:var:`Py_LegacyWindowsStdioFlag`: Use :c:member:`PyConfig." "legacy_windows_stdio` instead." msgstr "" -":c:var:`Py_LegacyWindowsStdioFlag`: use :c:member:`PyConfig." +":c:var:`Py_LegacyWindowsStdioFlag`: Use :c:member:`PyConfig." "legacy_windows_stdio`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:40 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:61 msgid "" -":c:var:`!Py_FileSystemDefaultEncoding`: use :c:member:`PyConfig." +":c:var:`!Py_FileSystemDefaultEncoding`: Use :c:member:`PyConfig." "filesystem_encoding` instead." msgstr "" -":c:var:`!Py_FileSystemDefaultEncoding`: use :c:member:`PyConfig." +":c:var:`!Py_FileSystemDefaultEncoding`: Use :c:member:`PyConfig." "filesystem_encoding`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:41 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:63 msgid "" -":c:var:`!Py_HasFileSystemDefaultEncoding`: use :c:member:`PyConfig." +":c:var:`!Py_HasFileSystemDefaultEncoding`: Use :c:member:`PyConfig." "filesystem_encoding` instead." msgstr "" -":c:var:`!Py_HasFileSystemDefaultEncoding`: use :c:member:`PyConfig." +":c:var:`!Py_HasFileSystemDefaultEncoding`: Use :c:member:`PyConfig." "filesystem_encoding`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:42 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:65 msgid "" -":c:var:`!Py_FileSystemDefaultEncodeErrors`: use :c:member:`PyConfig." +":c:var:`!Py_FileSystemDefaultEncodeErrors`: Use :c:member:`PyConfig." "filesystem_errors` instead." msgstr "" -":c:var:`!Py_FileSystemDefaultEncodeErrors`: use :c:member:`PyConfig." +":c:var:`!Py_FileSystemDefaultEncodeErrors`: Use :c:member:`PyConfig." "filesystem_errors`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:43 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:67 msgid "" -":c:var:`!Py_UTF8Mode`: use :c:member:`PyPreConfig.utf8_mode` instead. (see :" +":c:var:`!Py_UTF8Mode`: Use :c:member:`PyPreConfig.utf8_mode` instead. (see :" "c:func:`Py_PreInitialize`)" msgstr "" -":c:var:`!Py_UTF8Mode`: use :c:member:`PyPreConfig.utf8_mode`. (veja :c:func:" +":c:var:`!Py_UTF8Mode`: Use :c:member:`PyPreConfig.utf8_mode`. (veja :c:func:" "`Py_PreInitialize`)" #: ../../deprecations/c-api-pending-removal-in-3.15.rst:4 @@ -5824,193 +6235,203 @@ msgstr "A cópia empacotada do ``libmpdecimal``." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:5 msgid "" -":c:func:`PyImport_ImportModuleNoBlock`: use :c:func:`PyImport_ImportModule` " -"instead." +"The :c:func:`PyImport_ImportModuleNoBlock`: Use :c:func:" +"`PyImport_ImportModule` instead." msgstr "" -":c:func:`PyImport_ImportModuleNoBlock`: use :c:func:`PyImport_ImportModule`." - -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:6 -msgid ":c:func:`PyWeakref_GET_OBJECT`: use :c:func:`PyWeakref_GetRef` instead." -msgstr ":c:func:`PyWeakref_GET_OBJECT`: use :c:func:`PyWeakref_GetRef`." +"The :c:func:`PyImport_ImportModuleNoBlock`: use :c:func:" +"`PyImport_ImportModule`." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:7 -msgid ":c:func:`PyWeakref_GetObject`: use :c:func:`PyWeakref_GetRef` instead." -msgstr ":c:func:`PyWeakref_GetObject`: use :c:func:`PyWeakref_GetRef`." - -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:8 -msgid ":c:type:`!Py_UNICODE_WIDE` type: use :c:type:`wchar_t` instead." -msgstr "O tipo :c:type:`!Py_UNICODE_WIDE`: use :c:type:`wchar_t`." +msgid "" +":c:func:`PyWeakref_GetObject` and :c:func:`PyWeakref_GET_OBJECT`: Use :c:" +"func:`PyWeakref_GetRef` instead." +msgstr "" +":c:func:`PyWeakref_GetObject` e :c:func:`PyWeakref_GET_OBJECT`: Use :c:func:" +"`PyWeakref_GetRef`." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:9 -msgid ":c:type:`Py_UNICODE` type: use :c:type:`wchar_t` instead." -msgstr "O tipo :c:type:`Py_UNICODE`: use :c:type:`wchar_t`." +msgid "" +":c:type:`Py_UNICODE` type and the :c:macro:`!Py_UNICODE_WIDE` macro: Use :c:" +"type:`wchar_t` instead." +msgstr "" +"O tipo :c:type:`Py_UNICODE` e a macro :c:macro:`!Py_UNICODE_WIDE`: use :c:" +"type:`wchar_t`." -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:10 +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:11 msgid "Python initialization functions:" msgstr "Funções de inicialização do Python" -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:12 +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:13 msgid "" -":c:func:`PySys_ResetWarnOptions`: clear :data:`sys.warnoptions` and :data:`!" +":c:func:`PySys_ResetWarnOptions`: Clear :data:`sys.warnoptions` and :data:`!" "warnings.filters` instead." msgstr "" ":c:func:`PySys_ResetWarnOptions`: apague :data:`sys.warnoptions` e :data:`!" "warnings.filters`." -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:14 -msgid ":c:func:`Py_GetExecPrefix`: get :data:`sys.exec_prefix` instead." -msgstr ":c:func:`Py_GetExecPrefix`: obtenha :data:`sys.exec_prefix`." - #: ../../deprecations/c-api-pending-removal-in-3.15.rst:15 -msgid ":c:func:`Py_GetPath`: get :data:`sys.path` instead." -msgstr ":c:func:`Py_GetPath`: obtenha :data:`sys.path`." - -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:16 -msgid ":c:func:`Py_GetPrefix`: get :data:`sys.prefix` instead." -msgstr ":c:func:`Py_GetPrefix`: obtenha :data:`sys.prefix`." +msgid "" +":c:func:`Py_GetExecPrefix`: Get :data:`sys.base_exec_prefix` and :data:`sys." +"exec_prefix` instead." +msgstr "" +":c:func:`Py_GetExecPrefix`: obtenha :data:`sys.base_exec_prefix` e :data:" +"`sys.exec_prefix`." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:17 -msgid ":c:func:`Py_GetProgramFullPath`: get :data:`sys.executable` instead." -msgstr ":c:func:`Py_GetProgramFullPath`: obtenha :data:`sys.executable`." - -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:18 -msgid ":c:func:`Py_GetProgramName`: get :data:`sys.executable` instead." -msgstr ":c:func:`Py_GetProgramName`: obtenha :data:`sys.executable`." +msgid ":c:func:`Py_GetPath`: Get :data:`sys.path` instead." +msgstr ":c:func:`Py_GetPath`: leia :data:`sys.path`." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:19 msgid "" -":c:func:`Py_GetPythonHome`: get :c:member:`PyConfig.home` or the :envvar:" +":c:func:`Py_GetPrefix`: Get :data:`sys.base_prefix` and :data:`sys.prefix` " +"instead." +msgstr "" +":c:func:`Py_GetPrefix`: obtenha :data:`sys.base_prefix` e :data:`sys.prefix`." + +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:21 +msgid ":c:func:`Py_GetProgramFullPath`: Get :data:`sys.executable` instead." +msgstr ":c:func:`Py_GetProgramFullPath`: leia :data:`sys.executable`." + +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:23 +msgid ":c:func:`Py_GetProgramName`: Get :data:`sys.executable` instead." +msgstr ":c:func:`Py_GetProgramName`: leia :data:`sys.executable`." + +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:25 +msgid "" +":c:func:`Py_GetPythonHome`: Get :c:member:`PyConfig.home` or the :envvar:" "`PYTHONHOME` environment variable instead." msgstr "" -":c:func:`Py_GetPythonHome`: obtenha :c:member:`PyConfig.home` ou a variável " -"de ambiente :envvar:`PYTHONHOME`." +":c:func:`Py_GetPythonHome`: leia :c:member:`PyConfig.home` ou a variável de " +"ambiente :envvar:`PYTHONHOME`." #: ../../deprecations/c-api-pending-removal-in-future.rst:4 msgid "" "The following APIs are deprecated and will be removed, although there is " "currently no date scheduled for their removal." msgstr "" -"As APIs a seguir foram descontinuado e serão removidas, embora atualmente " +"As APIs a seguir foram descontinuadas e serão removidas, embora atualmente " "não haja uma data agendada para sua remoção." #: ../../deprecations/c-api-pending-removal-in-future.rst:7 -msgid ":c:macro:`Py_TPFLAGS_HAVE_FINALIZE`: unneeded since Python 3.8." +msgid ":c:macro:`Py_TPFLAGS_HAVE_FINALIZE`: Unneeded since Python 3.8." msgstr ":c:macro:`Py_TPFLAGS_HAVE_FINALIZE`: desnecessária desde o Python 3.8." -#: ../../deprecations/c-api-pending-removal-in-future.rst:8 -msgid ":c:func:`PyErr_Fetch`: use :c:func:`PyErr_GetRaisedException` instead." +#: ../../deprecations/c-api-pending-removal-in-future.rst:9 +msgid ":c:func:`PyErr_Fetch`: Use :c:func:`PyErr_GetRaisedException` instead." msgstr ":c:func:`PyErr_Fetch`: use :c:func:`PyErr_GetRaisedException`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:9 +#: ../../deprecations/c-api-pending-removal-in-future.rst:11 msgid "" -":c:func:`PyErr_NormalizeException`: use :c:func:`PyErr_GetRaisedException` " +":c:func:`PyErr_NormalizeException`: Use :c:func:`PyErr_GetRaisedException` " "instead." msgstr "" ":c:func:`PyErr_NormalizeException`: use :c:func:`PyErr_GetRaisedException`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:10 +#: ../../deprecations/c-api-pending-removal-in-future.rst:13 msgid "" -":c:func:`PyErr_Restore`: use :c:func:`PyErr_SetRaisedException` instead." +":c:func:`PyErr_Restore`: Use :c:func:`PyErr_SetRaisedException` instead." msgstr ":c:func:`PyErr_Restore`: use :c:func:`PyErr_SetRaisedException`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:11 +#: ../../deprecations/c-api-pending-removal-in-future.rst:15 msgid "" -":c:func:`PyModule_GetFilename`: use :c:func:`PyModule_GetFilenameObject` " +":c:func:`PyModule_GetFilename`: Use :c:func:`PyModule_GetFilenameObject` " "instead." msgstr "" ":c:func:`PyModule_GetFilename`: use :c:func:`PyModule_GetFilenameObject`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:12 -msgid ":c:func:`PyOS_AfterFork`: use :c:func:`PyOS_AfterFork_Child` instead." -msgstr ":c:func:`PyOS_AfterFork`: use :c:func:`PyOS_AfterFork_Child`" +#: ../../deprecations/c-api-pending-removal-in-future.rst:17 +msgid ":c:func:`PyOS_AfterFork`: Use :c:func:`PyOS_AfterFork_Child` instead." +msgstr ":c:func:`PyOS_AfterFork`: use :c:func:`PyOS_AfterFork_Child`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:13 +#: ../../deprecations/c-api-pending-removal-in-future.rst:19 msgid "" -":c:func:`PySlice_GetIndicesEx`: use :c:func:`PySlice_Unpack` and :c:func:" +":c:func:`PySlice_GetIndicesEx`: Use :c:func:`PySlice_Unpack` and :c:func:" "`PySlice_AdjustIndices` instead." msgstr "" ":c:func:`PySlice_GetIndicesEx`: use :c:func:`PySlice_Unpack` e :c:func:" "`PySlice_AdjustIndices`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:14 +#: ../../deprecations/c-api-pending-removal-in-future.rst:21 msgid "" -":c:func:`!PyUnicode_AsDecodedObject`: use :c:func:`PyCodec_Decode` instead." +":c:func:`!PyUnicode_AsDecodedObject`: Use :c:func:`PyCodec_Decode` instead." msgstr ":c:func:`!PyUnicode_AsDecodedObject`: use :c:func:`PyCodec_Decode`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:15 +#: ../../deprecations/c-api-pending-removal-in-future.rst:23 msgid "" -":c:func:`!PyUnicode_AsDecodedUnicode`: use :c:func:`PyCodec_Decode` instead." -msgstr ":c:func:`!PyUnicode_AsDecodedUnicode`: use :c:func:`PyCodec_Decode`." +":c:func:`!PyUnicode_AsDecodedUnicode`: Use :c:func:`PyCodec_Decode` instead." +msgstr ":c:func:`!PyUnicode_AsDecodedUnicode`: Use :c:func:`PyCodec_Decode`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:16 +#: ../../deprecations/c-api-pending-removal-in-future.rst:25 msgid "" -":c:func:`!PyUnicode_AsEncodedObject`: use :c:func:`PyCodec_Encode` instead." +":c:func:`!PyUnicode_AsEncodedObject`: Use :c:func:`PyCodec_Encode` instead." msgstr ":c:func:`!PyUnicode_AsEncodedObject`: use :c:func:`PyCodec_Encode`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:17 +#: ../../deprecations/c-api-pending-removal-in-future.rst:27 msgid "" -":c:func:`!PyUnicode_AsEncodedUnicode`: use :c:func:`PyCodec_Encode` instead." -msgstr ":c:func:`!PyUnicode_AsEncodedUnicode`: use :c:func:`PyCodec_Encode`." +":c:func:`!PyUnicode_AsEncodedUnicode`: Use :c:func:`PyCodec_Encode` instead." +msgstr ":c:func:`!PyUnicode_AsEncodedUnicode`: Use :c:func:`PyCodec_Encode`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:18 -msgid ":c:func:`PyUnicode_READY`: unneeded since Python 3.12" +#: ../../deprecations/c-api-pending-removal-in-future.rst:29 +msgid ":c:func:`PyUnicode_READY`: Unneeded since Python 3.12" msgstr ":c:func:`PyUnicode_READY`: desnecessário desde o Python 3.12" -#: ../../deprecations/c-api-pending-removal-in-future.rst:19 -msgid ":c:func:`!PyErr_Display`: use :c:func:`PyErr_DisplayException` instead." +#: ../../deprecations/c-api-pending-removal-in-future.rst:31 +msgid ":c:func:`!PyErr_Display`: Use :c:func:`PyErr_DisplayException` instead." msgstr ":c:func:`!PyErr_Display`: use :c:func:`PyErr_DisplayException`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:20 +#: ../../deprecations/c-api-pending-removal-in-future.rst:33 msgid "" -":c:func:`!_PyErr_ChainExceptions`: use ``_PyErr_ChainExceptions1`` instead." -msgstr ":c:func:`!_PyErr_ChainExceptions`: use ``_PyErr_ChainExceptions1``." +":c:func:`!_PyErr_ChainExceptions`: Use :c:func:`!_PyErr_ChainExceptions1` " +"instead." +msgstr "" +":c:func:`!_PyErr_ChainExceptions`: use :c:func:`!_PyErr_ChainExceptions1`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:21 +#: ../../deprecations/c-api-pending-removal-in-future.rst:35 msgid "" ":c:member:`!PyBytesObject.ob_shash` member: call :c:func:`PyObject_Hash` " "instead." msgstr "" "O membro :c:member:`!PyBytesObject.ob_shash`: chame :c:func:`PyObject_Hash`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:23 +#: ../../deprecations/c-api-pending-removal-in-future.rst:37 msgid ":c:member:`!PyDictObject.ma_version_tag` member." msgstr "O membro :c:member:`!PyDictObject.ma_version_tag`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:24 +#: ../../deprecations/c-api-pending-removal-in-future.rst:38 msgid "Thread Local Storage (TLS) API:" msgstr "API do Thread Local Storage (TLS):" -#: ../../deprecations/c-api-pending-removal-in-future.rst:26 +#: ../../deprecations/c-api-pending-removal-in-future.rst:40 msgid "" -":c:func:`PyThread_create_key`: use :c:func:`PyThread_tss_alloc` instead." +":c:func:`PyThread_create_key`: Use :c:func:`PyThread_tss_alloc` instead." msgstr ":c:func:`PyThread_create_key`: use :c:func:`PyThread_tss_alloc`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:27 -msgid ":c:func:`PyThread_delete_key`: use :c:func:`PyThread_tss_free` instead." +#: ../../deprecations/c-api-pending-removal-in-future.rst:42 +msgid ":c:func:`PyThread_delete_key`: Use :c:func:`PyThread_tss_free` instead." msgstr ":c:func:`PyThread_delete_key`: use :c:func:`PyThread_tss_free`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:28 +#: ../../deprecations/c-api-pending-removal-in-future.rst:44 msgid "" -":c:func:`PyThread_set_key_value`: use :c:func:`PyThread_tss_set` instead." +":c:func:`PyThread_set_key_value`: Use :c:func:`PyThread_tss_set` instead." msgstr ":c:func:`PyThread_set_key_value`: use :c:func:`PyThread_tss_set`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:29 +#: ../../deprecations/c-api-pending-removal-in-future.rst:46 msgid "" -":c:func:`PyThread_get_key_value`: use :c:func:`PyThread_tss_get` instead." +":c:func:`PyThread_get_key_value`: Use :c:func:`PyThread_tss_get` instead." msgstr ":c:func:`PyThread_get_key_value`: use :c:func:`PyThread_tss_get`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:30 +#: ../../deprecations/c-api-pending-removal-in-future.rst:48 msgid "" -":c:func:`PyThread_delete_key_value`: use :c:func:`PyThread_tss_delete` " +":c:func:`PyThread_delete_key_value`: Use :c:func:`PyThread_tss_delete` " "instead." msgstr "" ":c:func:`PyThread_delete_key_value`: use :c:func:`PyThread_tss_delete`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:31 -msgid ":c:func:`PyThread_ReInitTLS`: unneeded since Python 3.7." +#: ../../deprecations/c-api-pending-removal-in-future.rst:50 +msgid ":c:func:`PyThread_ReInitTLS`: Unneeded since Python 3.7." msgstr ":c:func:`PyThread_ReInitTLS`: desnecessário desde o Python 3.7." -#: ../../whatsnew/3.12.rst:2224 +#: ../../whatsnew/3.12.rst:2239 msgid "" "Remove the :file:`token.h` header file. There was never any public tokenizer " "C API. The :file:`token.h` header file was only designed to be used by " @@ -6021,48 +6442,48 @@ msgstr "" "apenas para ser usado por internos do Python. (Contribuição de Victor " "Stinner em :gh:`92651`.)" -#: ../../whatsnew/3.12.rst:2229 +#: ../../whatsnew/3.12.rst:2244 msgid "Legacy Unicode APIs have been removed. See :pep:`623` for detail." msgstr "" "As APIs Unicode legadas foram removidas. Veja a :pep:`623` para detalhes." -#: ../../whatsnew/3.12.rst:2231 +#: ../../whatsnew/3.12.rst:2246 msgid ":c:macro:`!PyUnicode_WCHAR_KIND`" msgstr ":c:macro:`!PyUnicode_WCHAR_KIND`" -#: ../../whatsnew/3.12.rst:2232 +#: ../../whatsnew/3.12.rst:2247 msgid ":c:func:`!PyUnicode_AS_UNICODE`" msgstr ":c:func:`!PyUnicode_AS_UNICODE`" -#: ../../whatsnew/3.12.rst:2233 +#: ../../whatsnew/3.12.rst:2248 msgid ":c:func:`!PyUnicode_AsUnicode`" msgstr ":c:func:`!PyUnicode_AsUnicode`" -#: ../../whatsnew/3.12.rst:2234 +#: ../../whatsnew/3.12.rst:2249 msgid ":c:func:`!PyUnicode_AsUnicodeAndSize`" msgstr ":c:func:`!PyUnicode_AsUnicodeAndSize`" -#: ../../whatsnew/3.12.rst:2235 +#: ../../whatsnew/3.12.rst:2250 msgid ":c:func:`!PyUnicode_AS_DATA`" msgstr ":c:func:`!PyUnicode_AS_DATA`" -#: ../../whatsnew/3.12.rst:2236 +#: ../../whatsnew/3.12.rst:2251 msgid ":c:func:`!PyUnicode_FromUnicode`" msgstr ":c:func:`!PyUnicode_FromUnicode`" -#: ../../whatsnew/3.12.rst:2237 +#: ../../whatsnew/3.12.rst:2252 msgid ":c:func:`!PyUnicode_GET_SIZE`" msgstr ":c:func:`!PyUnicode_GET_SIZE`" -#: ../../whatsnew/3.12.rst:2238 +#: ../../whatsnew/3.12.rst:2253 msgid ":c:func:`!PyUnicode_GetSize`" msgstr ":c:func:`!PyUnicode_GetSize`" -#: ../../whatsnew/3.12.rst:2239 +#: ../../whatsnew/3.12.rst:2254 msgid ":c:func:`!PyUnicode_GET_DATA_SIZE`" msgstr ":c:func:`!PyUnicode_GET_DATA_SIZE`" -#: ../../whatsnew/3.12.rst:2241 +#: ../../whatsnew/3.12.rst:2256 msgid "" "Remove the ``PyUnicode_InternImmortal()`` function macro. (Contributed by " "Victor Stinner in :gh:`85858`.)" diff --git a/whatsnew/3.13.po b/whatsnew/3.13.po index b010ad1d9..64fe51e05 100644 --- a/whatsnew/3.13.po +++ b/whatsnew/3.13.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# André Filipe de Assunção e Brito , 2024 -# Claudio Rogerio Carvalho Filho , 2024 -# Adorilson Bezerra , 2024 -# Vinícius Muniz de Melo , 2024 -# Victor Matheus Castro , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2024-05-11 01:09+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -33,53 +28,42 @@ msgid "What's New In Python 3.13" msgstr "O que há de novo no Python 3.13" #: ../../whatsnew/3.13.rst:0 -msgid "Editor" -msgstr "Editor" +msgid "Editors" +msgstr "Editores" #: ../../whatsnew/3.13.rst:6 -msgid "Thomas Wouters" -msgstr "Thomas Wouters" +msgid "Adam Turner and Thomas Wouters" +msgstr "Adam Turner e Thomas Wouters" #: ../../whatsnew/3.13.rst:48 msgid "" "This article explains the new features in Python 3.13, compared to 3.12. " -"Python 3.13 will be released on October 1, 2024. For full details, see the :" -"ref:`changelog `." +"Python 3.13 was released on October 7, 2024. For full details, see the :ref:" +"`changelog `." msgstr "" "Este artigo explica os novos recursos no Python 3.13, em comparação com " -"3.12. Python 3.13 será lançado em 1 de outubro de 2024. Veja :ref:`changelog " +"3.12. Python 3.13 foi lançado em 7 de outubro de 2024. Veja :ref:`changelog " "` para uma lista completa de mudanças." #: ../../whatsnew/3.13.rst:54 msgid ":pep:`719` -- Python 3.13 Release Schedule" -msgstr ":pep:`719` -- Agendamento de lançamento do Python 3.13" +msgstr ":pep:`719` -- Cronograma de lançamento do Python 3.13" #: ../../whatsnew/3.13.rst:58 -msgid "" -"Prerelease users should be aware that this document is currently in draft " -"form. It will be updated substantially as Python 3.13 moves towards release, " -"so it's worth checking back even after reading earlier versions." -msgstr "" -"Os usuários de pré-lançamento devem estar cientes de que este documento está " -"atualmente em forma de rascunho. Ele será atualizado substancialmente à " -"medida que o Python 3.13 caminha para seu lançamento estável, portanto vale " -"a pena conferir mesmo depois de ler as versões anteriores." - -#: ../../whatsnew/3.13.rst:64 msgid "Summary -- Release Highlights" msgstr "Resumo -- Destaques da versão" -#: ../../whatsnew/3.13.rst:69 +#: ../../whatsnew/3.13.rst:63 msgid "" -"Python 3.13 will be the latest stable release of the Python programming " -"language, with a mix of changes to the language, the implementation and the " -"standard library. The biggest changes include a new `interactive interpreter " +"Python 3.13 is the latest stable release of the Python programming language, " +"with a mix of changes to the language, the implementation and the standard " +"library. The biggest changes include a new `interactive interpreter " "`_, experimental support for " "running in a `free-threaded mode `_ (:" "pep:`703`), and a `Just-In-Time compiler `_ (:pep:" "`744`)." msgstr "" -"O Python 3.13 será a versão estável mais recente da linguagem de programação " +"O Python 3.13 é a versão estável mais recente da linguagem de programação " "Python, com uma mistura de mudanças na linguagem, na implementação e na " "biblioteca padrão. As maiores mudanças incluem um novo `interpretador " "interativo `_, suporte " @@ -87,20 +71,20 @@ msgstr "" "threaded-cpython_>`_ (:pep:`703`) e um `compilador Just-In-Time `_ (:pep:`744`)." -#: ../../whatsnew/3.13.rst:78 +#: ../../whatsnew/3.13.rst:72 msgid "" "Error messages continue to improve, with tracebacks now highlighted in color " "by default. The :func:`locals` builtin now has :ref:`defined semantics " "` for changing the returned mapping, and type " "parameters now support default values." msgstr "" -"As mensagens de erro continuam a melhorar, com tracebacks agora realçados em " -"cores por padrão. A função embutida :func:`locals` agora tem :ref:" -"`semânticas definidas ` para alterar o " -"mapeamento retornado, e os parâmetros de tipo agora oferecem suporte a " -"valores padrão." +"As mensagens de erro continuam a melhorar, com tracebacks (situação da pilha " +"de execução) agora realçados em cores por padrão. A função embutida :func:" +"`locals` agora tem :ref:`semânticas definidas ` para alterar o mapeamento retornado, e os parâmetros de tipo " +"agora oferecem suporte a valores padrão." -#: ../../whatsnew/3.13.rst:83 +#: ../../whatsnew/3.13.rst:77 msgid "" "The library changes contain removal of deprecated APIs and modules, as well " "as the usual improvements in user-friendliness and correctness. Several " @@ -109,10 +93,10 @@ msgid "" msgstr "" "As alterações da biblioteca contêm a remoção de APIs e módulos " "descontinuados, bem como as melhorias usuais em facilidade de uso e " -"correção. Vários módulos de biblioteca padrão legados agora `foram removidos " +"correção. Vários módulos da biblioteca padrão legados agora `foram removidos " "`_ após sua descontinuação no Python 3.11 (:pep:`594`)." -#: ../../whatsnew/3.13.rst:88 +#: ../../whatsnew/3.13.rst:82 msgid "" "This article doesn't attempt to provide a complete specification of all new " "features, but instead gives a convenient overview. For full details refer to " @@ -133,11 +117,11 @@ msgstr "" "implementado. Veja `Portando para o Python 3.13`_ para orientação sobre " "atualização a partir de versões anteriores do Python." -#: ../../whatsnew/3.13.rst:104 +#: ../../whatsnew/3.13.rst:98 msgid "Interpreter improvements:" msgstr "Melhorias no interpretador:" -#: ../../whatsnew/3.13.rst:106 +#: ../../whatsnew/3.13.rst:100 msgid "" "A greatly improved :ref:`interactive interpreter ` and :ref:`improved error messages ` bastante aprimorado e :ref:`mensagens de erro aprimoradas " "`." -#: ../../whatsnew/3.13.rst:109 +#: ../../whatsnew/3.13.rst:103 msgid "" ":pep:`667`: The :func:`locals` builtin now has :ref:`defined semantics " "` when mutating the returned mapping. Python " "debuggers and similar tools may now more reliably update local variables in " "optimized scopes even during concurrent code execution." msgstr "" -":pep:`667`: A função embutida :func:`locals` agora tem :ref:`semântica " +":pep:`667`: a função embutida :func:`locals` agora tem :ref:`semântica " "definida ` ao fazer a mutação do mapeamento " "retornado. Os depuradores do Python e ferramentas semelhantes agora podem " "atualizar variáveis locais de maneira mais confiável em escopos otimizados, " "mesmo durante a execução simultânea de código." -#: ../../whatsnew/3.13.rst:114 +#: ../../whatsnew/3.13.rst:108 msgid "" ":pep:`703`: CPython 3.13 has experimental support for running with the :term:" "`global interpreter lock` disabled. See :ref:`Free-threaded CPython " @@ -171,19 +155,19 @@ msgstr "" "`CPython com threads livres ` para mais " "detalhes." -#: ../../whatsnew/3.13.rst:117 +#: ../../whatsnew/3.13.rst:111 msgid "" ":pep:`744`: A basic :ref:`JIT compiler ` was " "added. It is currently disabled by default (though we may turn it on later). " "Performance improvements are modest -- we expect to improve this over the " "next few releases." msgstr "" -":pep:`744`: Um :ref:`compilador JIT ` básico foi " +":pep:`744`: um :ref:`compilador JIT ` básico foi " "adicionado. Atualmente está desativado por padrão (embora possamos ativá-lo " "mais tarde). As melhorias de desempenho são modestas -- esperamos melhorar " "isso nas próximas versões." -#: ../../whatsnew/3.13.rst:121 +#: ../../whatsnew/3.13.rst:115 msgid "" "Color support in the new :ref:`interactive interpreter `, as well as in :ref:`tracebacks `, bem como na saída de :ref:`tracebacks " "` e de :ref:`doctest `. Isso pode ser desabilitado através das variáveis de ambiente :" "envvar:`PYTHON_COLORS` e |NO_COLOR|_." -#: ../../whatsnew/3.13.rst:128 +#: ../../whatsnew/3.13.rst:122 msgid "Python data model improvements:" msgstr "Melhorias no modelo de dados Python:" -#: ../../whatsnew/3.13.rst:130 +#: ../../whatsnew/3.13.rst:124 msgid "" -":attr:`~class.__static_attributes__` stores the names of attributes accessed " +":attr:`~type.__static_attributes__` stores the names of attributes accessed " "through ``self.X`` in any function in a class body." msgstr "" -":attr:`~class.__static_attributes__` armazena os nomes dos atributos " -"acessados ​​por meio de ``self.X`` em qualquer função no corpo da classe." +":attr:`~type.__static_attributes__` armazena os nomes dos atributos " +"acessados por meio de ``self.X`` em qualquer função no corpo da classe." -#: ../../whatsnew/3.13.rst:132 +#: ../../whatsnew/3.13.rst:126 msgid "" -":attr:`!__firstlineno__` records the first line number of a class definition." +":attr:`~type.__firstlineno__` records the first line number of a class " +"definition." msgstr "" -":attr:`!__firstlineno__` registra o número da primeira linha da definição de " -"classe." +":attr:`~type.__firstlineno__` registra o número da primeira linha da " +"definição de classe." -#: ../../whatsnew/3.13.rst:134 +#: ../../whatsnew/3.13.rst:129 msgid "Significant improvements in the standard library:" msgstr "Melhorias significativas na biblioteca padrão:" -#: ../../whatsnew/3.13.rst:136 +#: ../../whatsnew/3.13.rst:131 msgid "" "Add a new :exc:`PythonFinalizationError` exception, raised when an operation " "is blocked during :term:`finalization `." @@ -229,7 +214,7 @@ msgstr "" "uma operação é bloqueada durante a :term:`finalização `." -#: ../../whatsnew/3.13.rst:138 +#: ../../whatsnew/3.13.rst:133 msgid "" "The :mod:`argparse` module now supports deprecating command-line options, " "positional arguments, and subcommands." @@ -237,16 +222,15 @@ msgstr "" "O módulo :mod:`argparse` agora oferece suporte a descontinuar opções de " "linha de comando, argumentos posicionais e subcomandos." -#: ../../whatsnew/3.13.rst:140 +#: ../../whatsnew/3.13.rst:135 msgid "" "The new functions :func:`base64.z85encode` and :func:`base64.z85decode` " -"support encoding and decoding `Z85 data `_." +"support encoding and decoding `Z85 data`_." msgstr "" "As novas funções :func:`base64.z85encode` e :func:`base64.z85decode` " -"oferecem suporte à codificação e decodificação de `dados Z85 `_." +"oferecem suporte à codificação e decodificação de `dados Z85`_." -#: ../../whatsnew/3.13.rst:142 +#: ../../whatsnew/3.13.rst:137 msgid "" "The :mod:`copy` module now has a :func:`copy.replace` function, with support " "for many builtin types and any class defining the :func:`~object." @@ -256,19 +240,21 @@ msgstr "" "para muitos tipos embutidos e qualquer classe que defina o método :func:" "`~object.__replace__`." -#: ../../whatsnew/3.13.rst:145 -msgid "The :mod:`dbm.sqlite3` module is now the default :mod:`dbm` backend." -msgstr "O módulo :mod:`dbm.sqlite3` agora é o backend :mod:`dbm` padrão." +#: ../../whatsnew/3.13.rst:140 +msgid "" +"The new :mod:`dbm.sqlite3` module is now the default :mod:`dbm` backend." +msgstr "O novo módulo :mod:`dbm.sqlite3` agora é o backend :mod:`dbm` padrão." -#: ../../whatsnew/3.13.rst:146 +#: ../../whatsnew/3.13.rst:141 msgid "" -"The :mod:`os` module has a suite of new functions for working with Linux's " -"timer notification file descriptors." +"The :mod:`os` module has a :ref:`suite of new functions ` for " +"working with Linux's timer notification file descriptors." msgstr "" -"O módulo :mod:`os` tem um conjunto de novas funções para trabalhar com os " -"descritores de arquivo de notificação de temporizador do Linux." +"O módulo :mod:`os` tem um :ref:`conjunto de novas funções ` para " +"trabalhar com os descritores de arquivo de notificação de temporizador do " +"Linux." -#: ../../whatsnew/3.13.rst:148 +#: ../../whatsnew/3.13.rst:143 msgid "" "The :mod:`random` module now has a :ref:`command-line interface `." @@ -276,11 +262,11 @@ msgstr "" "O módulo :mod:`random` agora tem uma :ref:`interface de linha de comando " "`." -#: ../../whatsnew/3.13.rst:150 +#: ../../whatsnew/3.13.rst:145 msgid "Security improvements:" -msgstr "Melhorias de segurança:" +msgstr "Melhorias de Segurança:" -#: ../../whatsnew/3.13.rst:152 +#: ../../whatsnew/3.13.rst:147 msgid "" ":func:`ssl.create_default_context` sets :data:`ssl." "VERIFY_X509_PARTIAL_CHAIN` and :data:`ssl.VERIFY_X509_STRICT` as default " @@ -290,11 +276,11 @@ msgstr "" "VERIFY_X509_PARTIAL_CHAIN` e :data:`ssl.VERIFY_X509_STRICT` como " "sinalizadores padrão." -#: ../../whatsnew/3.13.rst:155 +#: ../../whatsnew/3.13.rst:150 msgid "C API improvements:" msgstr "Melhorias na API C:" -#: ../../whatsnew/3.13.rst:157 +#: ../../whatsnew/3.13.rst:152 msgid "" "The :c:data:`Py_mod_gil` slot is now used to indicate that an extension " "module supports running with the :term:`GIL` disabled." @@ -302,7 +288,7 @@ msgstr "" "O slot :c:data:`Py_mod_gil` agora é usado para indicar que um módulo de " "extensão oferece suporte à execução com a :term:`GIL` desabilitada." -#: ../../whatsnew/3.13.rst:159 +#: ../../whatsnew/3.13.rst:154 msgid "" "The :doc:`PyTime C API ` has been added, providing access to " "system clocks." @@ -310,32 +296,41 @@ msgstr "" "A :doc:`API C PyTime ` foi adicionada, fornecendo acesso aos " "relógios do sistema." -#: ../../whatsnew/3.13.rst:161 +#: ../../whatsnew/3.13.rst:156 msgid "" ":c:type:`PyMutex` is a new lightweight mutex that occupies a single byte." msgstr ":c:type:`PyMutex` é um novo mutex leve que ocupa um único byte." -#: ../../whatsnew/3.13.rst:163 +#: ../../whatsnew/3.13.rst:157 +msgid "" +"There is a new :ref:`suite of functions ` for generating :" +"pep:`669` monitoring events in the C API." +msgstr "" +"Há um novo :ref:`conjunto de funções ` para gerar eventos " +"de monitoramento da :pep:`669` na API C." + +#: ../../whatsnew/3.13.rst:160 msgid "New typing features:" msgstr "Novos recursos de tipagem:" -#: ../../whatsnew/3.13.rst:165 +#: ../../whatsnew/3.13.rst:162 msgid "" ":pep:`696`: Type parameters (:data:`typing.TypeVar`, :data:`typing." "ParamSpec`, and :data:`typing.TypeVarTuple`) now support defaults." msgstr "" -":pep:`696`: Parâmetros de tipo (:data:`typing.TypeVar`, :data:`typing." -"ParamSpec` e :data:`typing.TypeVarTuple`) agora oferecem suporte a padrões." +":pep:`696`: parâmetros de tipo (:data:`typing.TypeVar`, :data:`typing." +"ParamSpec` e :data:`typing.TypeVarTuple`) agora oferecem suporte a valores " +"padrão." -#: ../../whatsnew/3.13.rst:167 +#: ../../whatsnew/3.13.rst:164 msgid "" ":pep:`702`: The new :func:`warnings.deprecated` decorator adds support for " -"marking deprecations in the type system." +"marking deprecations in the type system and at runtime." msgstr "" -":pep:`702`: O novo decorador :func:`warnings.deprecated` adiciona suporte " -"para marcar descontinuações no sistema de tipos." +":pep:`702`: o novo decorador :func:`warnings.deprecated` adiciona suporte " +"para marcar descontinuações no sistema de tipos e ambiente de execução." -#: ../../whatsnew/3.13.rst:169 +#: ../../whatsnew/3.13.rst:166 msgid "" ":pep:`705`: :data:`typing.ReadOnly` can be used to mark an item of a :class:" "`typing.TypedDict` as read-only for type checkers." @@ -343,7 +338,7 @@ msgstr "" ":pep:`705`: :data:`typing.ReadOnly` pode ser usado para marcar um item de :" "class:`typing.TypedDict` como somente leitura para verificadores de tipo." -#: ../../whatsnew/3.13.rst:171 +#: ../../whatsnew/3.13.rst:168 msgid "" ":pep:`742`: :data:`typing.TypeIs` provides more intuitive type narrowing " "behavior, as an alternative to :data:`typing.TypeGuard`." @@ -351,53 +346,60 @@ msgstr "" ":pep:`742`: :data:`typing.TypeIs` fornece um comportamento de estreitamento " "de tipo mais intuitivo, como uma alternativa ao :data:`typing.TypeGuard`." -#: ../../whatsnew/3.13.rst:174 +#: ../../whatsnew/3.13.rst:171 msgid "Platform support:" -msgstr "Suporte a plataforma:" +msgstr "Suporte à plataforma:" -#: ../../whatsnew/3.13.rst:176 +#: ../../whatsnew/3.13.rst:173 msgid "" ":pep:`730`: Apple's iOS is now an :ref:`officially supported platform " -"`, at :pep:`tier 3 <11#tier-3>`. Official " -"Android support (:pep:`738`) is in the works as well." +"`, at :pep:`tier 3 <11#tier-3>`." +msgstr "" +":pep:`730`: iOS da Apple agora é uma :ref:`plataforma oficialmente com " +"suporte `, no :pep:`tier 3 <11#tier-3>`." + +#: ../../whatsnew/3.13.rst:175 +msgid "" +":pep:`738`: Android is now an :ref:`officially supported platform " +"`, at :pep:`tier 3 <11#tier-3>`." msgstr "" -":pep:`730`: O iOS da Apple agora é uma :ref:`plataforma oficialmente " -"suportada `, no :pep:`tier 3 <11#tier-3>`. O " -"suporte oficial para Android (:pep:`738`) também está em andamento." +":pep:`738`: Android é agora uma :ref:`plataforma oficialmente com suporte " +"`, no :pep:`tier 3 <11#tier-3>`." -#: ../../whatsnew/3.13.rst:179 +#: ../../whatsnew/3.13.rst:177 msgid "" "``wasm32-wasi`` is now supported as a :pep:`tier 2 <11#tier-2>` platform." msgstr "" -"``wasm32-wasi`` agora é suportado como uma plataforma :pep:`tier 2 " -"<11#tier-2>`." +"``wasm32-wasi`` agora é uma plataforma com suporte :pep:`tier 2 <11#tier-2>`." -#: ../../whatsnew/3.13.rst:180 +#: ../../whatsnew/3.13.rst:178 msgid "``wasm32-emscripten`` is no longer an officially supported platform." msgstr "" -"``wasm32-emscripten`` não é mais uma plataforma oficialmente suportada." +"``wasm32-emscripten`` não é mais uma plataforma oficialmente com suporte." -#: ../../whatsnew/3.13.rst:182 +#: ../../whatsnew/3.13.rst:180 msgid "Important removals:" msgstr "Remoções importantes:" -#: ../../whatsnew/3.13.rst:184 +#: ../../whatsnew/3.13.rst:182 msgid "" -":ref:`PEP 594 `: The remaining 19 \"dead batteries\" " -"have been removed from the standard library: :mod:`!aifc`, :mod:`!audioop`, :" -"mod:`!cgi`, :mod:`!cgitb`, :mod:`!chunk`, :mod:`!crypt`, :mod:`!imghdr`, :" -"mod:`!mailcap`, :mod:`!msilib`, :mod:`!nis`, :mod:`!nntplib`, :mod:`!" +":ref:`PEP 594 `: The remaining 19 \"dead " +"batteries\" (legacy stdlib modules) have been removed from the standard " +"library: :mod:`!aifc`, :mod:`!audioop`, :mod:`!cgi`, :mod:`!cgitb`, :mod:`!" +"chunk`, :mod:`!crypt`, :mod:`!imghdr`, :mod:`!mailcap`, :mod:`!msilib`, :mod:" +"`!nis`, :mod:`!nntplib`, :mod:`!ossaudiodev`, :mod:`!pipes`, :mod:`!" +"sndhdr`, :mod:`!spwd`, :mod:`!sunau`, :mod:`!telnetlib`, :mod:`!uu` and :mod:" +"`!xdrlib`." +msgstr "" +":ref:`PEP 594 `: as 19 \"baterias " +"descarregadas\" (módulos legados da biblioteca padrão) restantes foram " +"removidas da biblioteca padrão: :mod:`!aifc`, :mod:`!audioop`, :mod:`!cgi`, :" +"mod:`!cgitb`, :mod:`!chunk`, :mod:`!crypt`, :mod:`!imghdr`, :mod:`!" +"mailcap`, :mod:`!msilib`, :mod:`!nis`, :mod:`!nntplib`, :mod:`!" "ossaudiodev`, :mod:`!pipes`, :mod:`!sndhdr`, :mod:`!spwd`, :mod:`!sunau`, :" -"mod:`!telnetlib`, :mod:`!uu` and :mod:`!xdrlib`." -msgstr "" -":ref:`PEP 594 `: As 19 \"baterias descarregadas\" " -"restantes foram removidas da biblioteca padrão: :mod:`!aifc`, :mod:`!" -"audioop`, :mod:`!cgi`, :mod:`!cgitb`, :mod:`!chunk`, :mod:`!crypt`, :mod:`!" -"imghdr`, :mod:`!mailcap`, :mod:`!msilib`, :mod:`!nis`, :mod:`!nntplib`, :mod:" -"`!ossaudiodev`, :mod:`!pipes`, :mod:`!sndhdr`, :mod:`!spwd`, :mod:`!sunau`, :" "mod:`!telnetlib`, :mod:`!uu` e :mod:`!xdrlib`." -#: ../../whatsnew/3.13.rst:190 +#: ../../whatsnew/3.13.rst:188 msgid "" "Remove the :program:`2to3` tool and :mod:`!lib2to3` module (deprecated in " "Python 3.11)." @@ -405,27 +407,27 @@ msgstr "" "Remove a ferramenta :program:`2to3` e o módulo :mod:`!lib2to3` " "(descontinuados no Python 3.11)." -#: ../../whatsnew/3.13.rst:192 +#: ../../whatsnew/3.13.rst:190 msgid "Remove the :mod:`!tkinter.tix` module (deprecated in Python 3.6)." msgstr "Remove o módulo :mod:`!tkinter.tix` (descontinuado no Python 3.6)." -#: ../../whatsnew/3.13.rst:193 -msgid "Remove :func:`!locale.resetlocale()`." -msgstr "Remove :func:`!locale.resetlocale()`." +#: ../../whatsnew/3.13.rst:191 +msgid "Remove the :func:`!locale.resetlocale` function." +msgstr "Remove a função :func:`!locale.resetlocale`." -#: ../../whatsnew/3.13.rst:194 -msgid "Remove :mod:`!typing.io` and :mod:`!typing.re`." -msgstr "Remove :mod:`!typing.io` e :mod:`!typing.re`." +#: ../../whatsnew/3.13.rst:192 +msgid "Remove the :mod:`!typing.io` and :mod:`!typing.re` namespaces." +msgstr "Remove os espaços de nomes :mod:`!typing.io` e :mod:`!typing.re`." -#: ../../whatsnew/3.13.rst:195 +#: ../../whatsnew/3.13.rst:193 msgid "Remove chained :class:`classmethod` descriptors." msgstr "Remove descritores encadeados de :class:`classmethod`." -#: ../../whatsnew/3.13.rst:197 +#: ../../whatsnew/3.13.rst:195 msgid "Release schedule changes:" msgstr "Mudanças no cronograma de lançamento:" -#: ../../whatsnew/3.13.rst:199 +#: ../../whatsnew/3.13.rst:197 msgid "" ":pep:`602` (\"Annual Release Cycle for Python\") has been updated to extend " "the full support ('bugfix') period for new releases to two years. This " @@ -435,7 +437,7 @@ msgstr "" "estender o período de suporte total (\"bugfix\") para novos lançamentos para " "dois anos. Esta política atualizada significa que:" -#: ../../whatsnew/3.13.rst:203 +#: ../../whatsnew/3.13.rst:201 msgid "" "Python 3.9--3.12 have one and a half years of full support, followed by " "three and a half years of security fixes." @@ -443,7 +445,7 @@ msgstr "" "O Python 3.9--3.12 tem um ano e meio de suporte total, seguido por três anos " "e meio de correções de segurança." -#: ../../whatsnew/3.13.rst:205 +#: ../../whatsnew/3.13.rst:203 msgid "" "Python 3.13 and later have two years of full support, followed by three " "years of security fixes." @@ -451,29 +453,29 @@ msgstr "" "Python 3.13 e posteriores têm dois anos de suporte total, seguidos de três " "anos de correções de segurança." -#: ../../whatsnew/3.13.rst:210 ../../whatsnew/3.13.rst:1728 +#: ../../whatsnew/3.13.rst:208 ../../whatsnew/3.13.rst:2053 msgid "New Features" msgstr "Novas funcionalidades" -#: ../../whatsnew/3.13.rst:216 +#: ../../whatsnew/3.13.rst:214 msgid "A better interactive interpreter" msgstr "Um melhor interpretador interativo" -#: ../../whatsnew/3.13.rst:218 +#: ../../whatsnew/3.13.rst:216 msgid "" "Python now uses a new :term:`interactive` shell by default, based on code " "from the `PyPy project`_. When the user starts the :term:`REPL` from an " "interactive terminal, the following new features are now supported:" msgstr "" -"O Python agora usa um novo console :term:`interativo` por padrão, com base " -"no código do `projeto PyPy`_. Quando o usuário inicia o :term:`REPL` de um " -"terminal interativo, os seguintes novos recursos agora são suportados:" +"Python agora usa um novo console :term:`interativo` por padrão, com base no " +"código do `projeto PyPy`_. Quando o usuário inicia o :term:`REPL` de um " +"terminal interativo, agora os seguintes novos recursos estão disponíveis:" -#: ../../whatsnew/3.13.rst:223 +#: ../../whatsnew/3.13.rst:221 msgid "Multiline editing with history preservation." msgstr "Edição multilinha com preservação do histórico." -#: ../../whatsnew/3.13.rst:224 +#: ../../whatsnew/3.13.rst:222 msgid "" "Direct support for REPL-specific commands like :kbd:`help`, :kbd:`exit`, " "and :kbd:`quit`, without the need to call them as functions." @@ -481,7 +483,7 @@ msgstr "" "Suporte direto para comandos específicos do REPL, como :kbd:`help`, :kbd:" "`exit` e :kbd:`quit`, sem a necessidade de chamá-los como funções." -#: ../../whatsnew/3.13.rst:226 +#: ../../whatsnew/3.13.rst:224 msgid "" "Prompts and tracebacks with :ref:`color enabled by default `." @@ -489,14 +491,14 @@ msgstr "" "Prompts e tracebacks com :ref:`cores habilitadas por padrão `." -#: ../../whatsnew/3.13.rst:228 +#: ../../whatsnew/3.13.rst:226 msgid "" "Interactive help browsing using :kbd:`F1` with a separate command history." msgstr "" "Ajuda interativa para navegar usando :kbd:`F1` com um histórico de comandos " "separado." -#: ../../whatsnew/3.13.rst:230 +#: ../../whatsnew/3.13.rst:228 msgid "" "History browsing using :kbd:`F2` that skips output as well as the :term:" "`>>>` and :term:`...` prompts." @@ -504,15 +506,15 @@ msgstr "" "Navegação no histórico usando :kbd:`F2` que ignora a saída, bem como os " "prompts :term:`>>>` e :term:`...`." -#: ../../whatsnew/3.13.rst:232 +#: ../../whatsnew/3.13.rst:230 msgid "" "\"Paste mode\" with :kbd:`F3` that makes pasting larger blocks of code " "easier (press :kbd:`F3` again to return to the regular prompt)." msgstr "" -"\"Modo de colagem\" com :kbd:`F3` que facilita colar blocos maiores de " -"código (pressione :kbd:`F3` novamente para retornar ao prompt normal)." +"\"Modo de colagem\" com :kbd:`F3` que facilita colar blocos de código " +"maiores (pressione :kbd:`F3` novamente para retornar ao prompt normal)." -#: ../../whatsnew/3.13.rst:235 +#: ../../whatsnew/3.13.rst:233 msgid "" "To disable the new interactive shell, set the :envvar:`PYTHON_BASIC_REPL` " "environment variable. For more on interactive mode, see :ref:`tut-interac`." @@ -521,7 +523,7 @@ msgstr "" "envvar:`PYTHON_BASIC_REPL`. Para mais informações sobre o modo interativo, " "veja :ref:`tut-interac`." -#: ../../whatsnew/3.13.rst:239 +#: ../../whatsnew/3.13.rst:237 msgid "" "(Contributed by Pablo Galindo Salgado, Łukasz Langa, and Lysandros Nikolaou " "in :gh:`111201` based on code from the PyPy project. Windows support " @@ -531,11 +533,11 @@ msgstr "" "em :gh:`111201` baseado no código do projeto PyPy. Suporte ao Windows foi " "uma contribuição de Dino Viehland e Anthony Shaw.)" -#: ../../whatsnew/3.13.rst:248 +#: ../../whatsnew/3.13.rst:247 msgid "Improved error messages" msgstr "Mensagens de erro melhoradas" -#: ../../whatsnew/3.13.rst:250 +#: ../../whatsnew/3.13.rst:249 msgid "" "The interpreter now uses color by default when displaying tracebacks in the " "terminal. This feature :ref:`can be controlled ` " @@ -546,10 +548,10 @@ msgstr "" "O interpretador agora usa cores por padrão ao exibir tracebacks no terminal. " "Este recurso :ref:`pode ser controlado ` por " "meio da nova variável de ambiente :envvar:`PYTHON_COLORS`, bem como das " -"variáveis ​​de ambiente canônicas |NO_COLOR|_ e |FORCE_COLOR|_. (Contribuição " +"variáveis de ambiente canônicas |NO_COLOR|_ e |FORCE_COLOR|_. (Contribuição " "de Pablo Galindo Salgado em :gh:`112730`.)" -#: ../../whatsnew/3.13.rst:265 +#: ../../whatsnew/3.13.rst:264 msgid "" "A common mistake is to write a script with the same name as a standard " "library module. When this results in errors, we now display a more helpful " @@ -559,7 +561,33 @@ msgstr "" "biblioteca padrão. Quando isso resulta em erros, agora exibimos uma mensagem " "de erro mais útil:" -#: ../../whatsnew/3.13.rst:280 +#: ../../whatsnew/3.13.rst:268 +msgid "" +"$ python random.py\n" +"Traceback (most recent call last):\n" +" File \"/home/me/random.py\", line 1, in \n" +" import random\n" +" File \"/home/me/random.py\", line 3, in \n" +" print(random.randint(5))\n" +" ^^^^^^^^^^^^^^\n" +"AttributeError: module 'random' has no attribute 'randint' (consider " +"renaming '/home/me/random.py' since it has the same name as the standard " +"library module named 'random' and prevents importing that standard library " +"module)" +msgstr "" +"$ python random.py\n" +"Traceback (most recent call last):\n" +" File \"/home/me/random.py\", line 1, in \n" +" import random\n" +" File \"/home/me/random.py\", line 3, in \n" +" print(random.randint(5))\n" +" ^^^^^^^^^^^^^^\n" +"AttributeError: module 'random' has no attribute 'randint' (consider " +"renaming '/home/me/random.py' since it has the same name as the standard " +"library module named 'random' and prevents importing that standard library " +"module)" + +#: ../../whatsnew/3.13.rst:279 msgid "" "Similarly, if a script has the same name as a third-party module that it " "attempts to import and this results in errors, we also display a more " @@ -569,11 +597,35 @@ msgstr "" "que ele tentar importar e isso resultar em erros, também exibiremos uma " "mensagem de erro mais útil:" -#: ../../whatsnew/3.13.rst:295 +#: ../../whatsnew/3.13.rst:283 +msgid "" +"$ python numpy.py\n" +"Traceback (most recent call last):\n" +" File \"/home/me/numpy.py\", line 1, in \n" +" import numpy as np\n" +" File \"/home/me/numpy.py\", line 3, in \n" +" np.array([1, 2, 3])\n" +" ^^^^^^^^\n" +"AttributeError: module 'numpy' has no attribute 'array' (consider renaming '/" +"home/me/numpy.py' if it has the same name as a library you intended to " +"import)" +msgstr "" +"$ python numpy.py\n" +"Traceback (most recent call last):\n" +" File \"/home/me/numpy.py\", line 1, in \n" +" import numpy as np\n" +" File \"/home/me/numpy.py\", line 3, in \n" +" np.array([1, 2, 3])\n" +" ^^^^^^^^\n" +"AttributeError: module 'numpy' has no attribute 'array' (consider renaming '/" +"home/me/numpy.py' if it has the same name as a library you intended to " +"import)" + +#: ../../whatsnew/3.13.rst:294 msgid "(Contributed by Shantanu Jain in :gh:`95754`.)" msgstr "(Contribuição de Shantanu Jain em :gh:`95754`.)" -#: ../../whatsnew/3.13.rst:297 +#: ../../whatsnew/3.13.rst:296 msgid "" "The error message now tries to suggest the correct keyword argument when an " "incorrect keyword argument is passed to a function." @@ -581,17 +633,35 @@ msgstr "" "A mensagem de erro agora tenta sugerir o argumento nomeado correto quando um " "argumento nomeado incorreto é passado para uma função." -#: ../../whatsnew/3.13.rst:309 +#: ../../whatsnew/3.13.rst:299 +msgid "" +">>> \"Better error messages!\".split(max_split=1)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" \"Better error messages!\".split(max_split=1)\n" +" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^\n" +"TypeError: split() got an unexpected keyword argument 'max_split'. Did you " +"mean 'maxsplit'?" +msgstr "" +">>> \"Better error messages!\".split(max_split=1)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" \"Better error messages!\".split(max_split=1)\n" +" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^\n" +"TypeError: split() got an unexpected keyword argument 'max_split'. Did you " +"mean 'maxsplit'?" + +#: ../../whatsnew/3.13.rst:308 msgid "" "(Contributed by Pablo Galindo Salgado and Shantanu Jain in :gh:`107944`.)" msgstr "" "(Contribuição de Pablo Galindo Salgado e Shantanu Jain em :gh:`107944`.)" -#: ../../whatsnew/3.13.rst:315 +#: ../../whatsnew/3.13.rst:314 msgid "Free-threaded CPython" msgstr "CPython com threads livres" -#: ../../whatsnew/3.13.rst:317 +#: ../../whatsnew/3.13.rst:316 msgid "" "CPython now has experimental support for running in a free-threaded mode, " "with the :term:`global interpreter lock` (GIL) disabled. This is an " @@ -599,7 +669,7 @@ msgid "" "threaded mode requires a different executable, usually called " "``python3.13t`` or ``python3.13t.exe``. Pre-built binaries marked as *free-" "threaded* can be installed as part of the official :ref:`Windows ` and :ref:`macOS ` " +"freethreaded-windows>` and :ref:`macOS ` " "installers, or CPython can be built from source with the :option:`--disable-" "gil` option." msgstr "" @@ -613,7 +683,7 @@ msgstr "" "`, ou o CPython pode ser construído a " "partir da fonte com a opção :option:`--disable-gil`." -#: ../../whatsnew/3.13.rst:330 +#: ../../whatsnew/3.13.rst:326 msgid "" "Free-threaded execution allows for full utilization of the available " "processing power by running threads in parallel on available CPU cores. " @@ -623,7 +693,7 @@ msgid "" "it: expect some bugs and a substantial single-threaded performance hit. Free-" "threaded builds of CPython support optionally running with the GIL enabled " "at runtime using the environment variable :envvar:`PYTHON_GIL` or the " -"command-line option :option:`-X gil`." +"command-line option :option:`-X gil=1`." msgstr "" "A execução de threads livres permite a utilização total do poder de " "processamento disponível ao executar threads em paralelo nos núcleos de CPU " @@ -635,21 +705,21 @@ msgstr "" "As construções de threads livres do CPython oferecem suporte à execução " "opcional com a GIL habilitada no tempo de execução usando a variável de " "ambiente :envvar:`PYTHON_GIL` ou a opção de linha de comando :option:`-X " -"gil`." +"gil=1`." -#: ../../whatsnew/3.13.rst:340 +#: ../../whatsnew/3.13.rst:336 msgid "" "To check if the current interpreter supports free-threading, :option:`python " -"-VV <-V>` and :attr:`sys.version` contain \"experimental free-threading " +"-VV <-V>` and :data:`sys.version` contain \"experimental free-threading " "build\". The new :func:`!sys._is_gil_enabled` function can be used to check " "whether the GIL is actually disabled in the running process." msgstr "" "Para verificar se o interpretador atual oferece suporte a threads livres, :" -"option:`python -VV <-V>` e :attr:`sys.version` contêm \"experimental free-" +"option:`python -VV <-V>` e :data:`sys.version` contêm \"experimental free-" "threading build\". A nova função :func:`!sys._is_gil_enabled` pode ser usada " "para verificar se a GIL está realmente desabilitada no processo em execução." -#: ../../whatsnew/3.13.rst:345 +#: ../../whatsnew/3.13.rst:341 msgid "" "C-API extension modules need to be built specifically for the free-threaded " "build. Extensions that support running with the :term:`GIL` disabled should " @@ -672,7 +742,26 @@ msgstr "" "ou a opção :option:`-X gil=0`. pip 24.1 ou mais recentes é necessário para " "instalar pacotes com extensões C na construção de threads livres." -#: ../../whatsnew/3.13.rst:358 +#: ../../whatsnew/3.13.rst:352 +msgid "" +"This work was made possible thanks to many individuals and organizations, " +"including the large community of contributors to Python and third-party " +"projects to test and enable free-threading support. Notable contributors " +"include: Sam Gross, Ken Jin, Donghee Na, Itamar Oren, Matt Page, Brett " +"Simmers, Dino Viehland, Carl Meyer, Nathan Goldbaum, Ralf Gommers, Lysandros " +"Nikolaou, and many others. Many of these contributors are employed by Meta, " +"which has provided significant engineering resources to support this project." +msgstr "" +"Este trabalho foi possível graças a muitos indivíduos e organizações, " +"incluindo a grande comunidade de colaboradores do Python e projetos de " +"terceiros para testar e habilitar o suporte para threads livres. " +"Colaboradores notáveis incluem: Sam Gross, Ken Jin, Donghee Na, Itamar Oren, " +"Matt Page, Brett Simmers, Dino Viehland, Carl Meyer, Nathan Goldbaum, Ralf " +"Gommers, Lysandros Nikolaou e muitos outros. Muitos desses colaboradores são " +"empregados pela Meta, que forneceu recursos de engenharia significativos " +"para dar suporte a este projeto." + +#: ../../whatsnew/3.13.rst:364 msgid "" ":pep:`703` \"Making the Global Interpreter Lock Optional in CPython\" " "contains rationale and information surrounding this work." @@ -680,11 +769,21 @@ msgstr "" ":pep:`703` \"Tornando a trava global do interpretador opcional no CPython\" " "contém justificativa e informações sobre este trabalho." -#: ../../whatsnew/3.13.rst:365 +#: ../../whatsnew/3.13.rst:367 +msgid "" +"`Porting Extension Modules to Support Free-Threading `_: A community-maintained porting guide for " +"extension authors." +msgstr "" +"`Portando módulos de extensão para oferecer suporte a threads livres " +"`_: um guia de portabilidade " +"mantido pela comunidade para autores de extensões." + +#: ../../whatsnew/3.13.rst:375 msgid "An experimental just-in-time (JIT) compiler" msgstr "Um compilador just-in-time (JIT) experimental" -#: ../../whatsnew/3.13.rst:367 +#: ../../whatsnew/3.13.rst:377 msgid "" "When CPython is configured and built using the :option:`!--enable-" "experimental-jit` option, a just-in-time (JIT) compiler is added which may " @@ -701,7 +800,7 @@ msgstr "" "construção e outras informações de suporte `estão contidos em`__ :file:" "`Tools/jit/README.md`." -#: ../../whatsnew/3.13.rst:377 +#: ../../whatsnew/3.13.rst:387 msgid "" "The :option:`!--enable-experimental-jit` option takes these (optional) " "values, defaulting to ``yes`` if :option:`!--enable-experimental-jit` is " @@ -711,39 +810,34 @@ msgstr "" "(opcionais), assumindo como padrão ``yes`` se :option:`!--enable-" "experimental-jit` estiver presente sem o valor opcional." -#: ../../whatsnew/3.13.rst:381 +#: ../../whatsnew/3.13.rst:391 msgid "``no``: Disable the entire Tier 2 and JIT pipeline." -msgstr "``no``: Desativa todo o pipeline de Tier 2 e JIT." +msgstr "``no``: desativa todo o pipeline de Tier 2 e JIT." -#: ../../whatsnew/3.13.rst:382 +#: ../../whatsnew/3.13.rst:392 msgid "" "``yes``: Enable the JIT. To disable the JIT at runtime, pass the environment " -"variable ``PYTHON_JIT=0``." +"variable :envvar:`PYTHON_JIT=0 `." msgstr "" -"``yes``: Habilita o JIT. Para desabilitar o JIT em tempo de execução, passe " -"a variável de ambiente ``PYTHON_JIT=0``." -#: ../../whatsnew/3.13.rst:384 +#: ../../whatsnew/3.13.rst:394 msgid "" "``yes-off``: Build the JIT but disable it by default. To enable the JIT at " -"runtime, pass the environment variable ``PYTHON_JIT=1``." +"runtime, pass the environment variable :envvar:`PYTHON_JIT=1 `." msgstr "" -"``yes-off``: Constrói o JIT, mas desabilita-o por padrão. Para habilitar o " -"JIT em tempo de execução, passe a variável de ambiente ``PYTHON_JIT=1``." -#: ../../whatsnew/3.13.rst:386 +#: ../../whatsnew/3.13.rst:396 msgid "" "``interpreter``: Enable the Tier 2 interpreter but disable the JIT. The " -"interpreter can be disabled by running with ``PYTHON_JIT=0``." +"interpreter can be disabled by running with :envvar:`PYTHON_JIT=0 " +"`." msgstr "" -"``interpreter``: Habilita o interpretador Tier 2, mas desabilita o JIT. O " -"interpretador pode ser desabilitado executando com ``PYTHON_JIT=0``." -#: ../../whatsnew/3.13.rst:389 +#: ../../whatsnew/3.13.rst:399 msgid "The internal architecture is roughly as follows:" msgstr "A arquitetura interna é aproximadamente a seguinte:" -#: ../../whatsnew/3.13.rst:391 +#: ../../whatsnew/3.13.rst:401 msgid "" "We start with specialized *Tier 1 bytecode*. See :ref:`What's new in 3.11 " "` for details." @@ -751,17 +845,17 @@ msgstr "" "Começamos com especializado *bytecode de Tier 1*. Veja :ref:`O que há de " "novo no 3.11 ` para detalhes." -#: ../../whatsnew/3.13.rst:393 +#: ../../whatsnew/3.13.rst:403 msgid "" "When the Tier 1 bytecode gets hot enough, it gets translated to a new purely " "internal intermediate representation (IR), called the *Tier 2 IR*, and " "sometimes referred to as micro-ops (\"uops\")." msgstr "" "Quando o bytecode Tier 1 fica quente o suficiente, ele é traduzido para uma " -"nova representação intermediária (IR) puramente interna, também chamado do " +"nova representação intermediária (IR) puramente interna, também chamado de " "*IR Tier 2*, e às vezes chamada de micro-ops (\"uops\")." -#: ../../whatsnew/3.13.rst:396 +#: ../../whatsnew/3.13.rst:406 msgid "" "The Tier 2 IR uses the same stack-based virtual machine as Tier 1, but the " "instruction format is better suited to translation to machine code." @@ -769,7 +863,7 @@ msgstr "" "O IR Tier 2 usa a mesma máquina virtual baseada em pilha que o Tier 1, mas o " "formato de instrução é mais adequado para tradução em código de máquina." -#: ../../whatsnew/3.13.rst:398 +#: ../../whatsnew/3.13.rst:408 msgid "" "We have several optimization passes for Tier 2 IR, which are applied before " "it is interpreted or translated to machine code." @@ -777,7 +871,7 @@ msgstr "" "Temos vários passes de otimização para IR Tier 2, que são aplicados antes de " "serem interpretados ou traduzidos em código de máquina." -#: ../../whatsnew/3.13.rst:400 +#: ../../whatsnew/3.13.rst:410 msgid "" "There is a Tier 2 interpreter, but it is mostly intended for debugging the " "earlier stages of the optimization pipeline. The Tier 2 interpreter can be " @@ -788,7 +882,7 @@ msgstr "" "Tier 2 pode ser habilitado configurando o Python com ``--enable-experimental-" "jit=interpreter``." -#: ../../whatsnew/3.13.rst:404 +#: ../../whatsnew/3.13.rst:414 msgid "" "When the JIT is enabled, the optimized Tier 2 IR is translated to machine " "code, which is then executed." @@ -796,7 +890,7 @@ msgstr "" "Quando o JIT está habilitado, o IR Tier 2 otimizado é traduzido em código de " "máquina, que é então executado." -#: ../../whatsnew/3.13.rst:406 +#: ../../whatsnew/3.13.rst:416 msgid "" "The machine code translation process uses a technique called *copy-and-" "patch*. It has no runtime dependencies, but there is a new build-time " @@ -806,11 +900,11 @@ msgstr "" "e corrigir*. Não possui dependências de tempo de execução, mas há uma nova " "dependência de tempo de construção no LLVM." -#: ../../whatsnew/3.13.rst:410 +#: ../../whatsnew/3.13.rst:420 msgid ":pep:`744`" msgstr ":pep:`744`" -#: ../../whatsnew/3.13.rst:412 +#: ../../whatsnew/3.13.rst:422 msgid "" "(JIT by Brandt Bucher, inspired by a paper by Haoran Xu and Fredrik " "Kjolstad. Tier 2 IR by Mark Shannon and Guido van Rossum. Tier 2 optimizer " @@ -820,15 +914,15 @@ msgstr "" "Kjolstad. Tier 2 IR de Mark Shannon e Guido van Rossum. Otimizador Tier 2 de " "Ken Jin.)" -#: ../../whatsnew/3.13.rst:420 +#: ../../whatsnew/3.13.rst:430 msgid "Defined mutation semantics for :py:func:`locals`" msgstr "Definidas semânticas de mutação para :py:func:`locals`" -#: ../../whatsnew/3.13.rst:422 +#: ../../whatsnew/3.13.rst:432 msgid "" "Historically, the expected result of mutating the return value of :func:" "`locals` has been left to individual Python implementations to define. " -"Starting from Python 3.13, :pep:`667` standardises the historical behaviour " +"Starting from Python 3.13, :pep:`667` standardises the historical behavior " "of CPython for most code execution scopes, but changes :term:`optimized " "scopes ` (functions, generators, coroutines, " "comprehensions, and generator expressions) to explicitly return independent " @@ -836,19 +930,19 @@ msgid "" "referenced nonlocal variables captured in closures." msgstr "" "Historicamente, o resultado esperado da mutação do valor de retorno de :func:" -"`locals` foi deixada para as implementações individuais do Python definirem. " +"`locals` foi deixada para as implementações individuais de Python definirem. " "A partir do Python 3.13, :pep:`667` padroniza o comportamento histórico do " "CPython para a maioria dos escopos de execução de código, mas altera :term:" "`escopos otimizados ` (funções, geradores, corrotinas, " "compreensões e expressões geradoras) para retornar explicitamente " -"instantâneos independentes das variáveis ​​locais atualmente atribuídas, " -"incluindo variáveis ​​não locais referenciadas localmente capturadas em " +"instantâneos independentes das variáveis locais atualmente atribuídas, " +"incluindo variáveis não locais referenciadas localmente capturadas em " "encerramentos." -#: ../../whatsnew/3.13.rst:431 +#: ../../whatsnew/3.13.rst:441 msgid "" "This change to the semantics of :func:`locals` in optimized scopes also " -"affects the default behaviour of code execution functions that implicitly " +"affects the default behavior of code execution functions that implicitly " "target :func:`!locals` if no explicit namespace is provided (such as :func:" "`exec` and :func:`eval`). In previous versions, whether or not changes could " "be accessed by calling :func:`!locals` after calling the code execution " @@ -875,16 +969,16 @@ msgstr "" "vezes pode falhar em escopos otimizados com base em outro código (incluindo " "depuradores e ferramentas de rastreamento de execução de código), " "redefinindo potencialmente o instantâneo compartilhado nesse escopo. Agora, " -"o código sempre será executado em um instantâneo independente das variáveis ​​" +"o código sempre será executado em um instantâneo independente das variáveis " "locais em escopos otimizados e, portanto, as alterações nunca serão visíveis " "em chamadas subsequentes para :func:`!locals`. Para acessar as alterações " "feitas nesses casos, uma referência explícita de espaço de nomes deve agora " "ser passada para a função relevante. Alternativamente, pode fazer sentido " "atualizar o código afetado para usar uma API de execução de código de nível " -"superior que retorne o espaço de nomes de execução de código resultante (por " -"exemplo, :func:`runpy.run_path` ao executar arquivos Python do disco)." +"mais alto que retorne o espaço de nomes de execução de código resultante " +"(por exemplo, :func:`runpy.run_path` ao executar arquivos Python do disco)." -#: ../../whatsnew/3.13.rst:450 +#: ../../whatsnew/3.13.rst:460 msgid "" "To ensure debuggers and similar tools can reliably update local variables in " "scopes affected by this change, :attr:`FrameType.f_locals ` " @@ -894,13 +988,13 @@ msgid "" "semantics." msgstr "" "Para garantir que depuradores e ferramentas semelhantes possam atualizar de " -"forma confiável variáveis ​​locais em escopos afetados por esta mudança, :attr:" +"forma confiável variáveis locais em escopos afetados por esta mudança, :attr:" "`FrameType.f_locals ` agora retorna um proxy write-through " -"para as variáveis ​​locais e não locais referenciadas localmente do quadro " +"para as variáveis locais e não locais referenciadas localmente do quadro " "nesses escopos, em vez de retornar uma instância ``dict`` compartilhada " "atualizada inconsistentemente com semântica de tempo de execução indefinida." -#: ../../whatsnew/3.13.rst:456 +#: ../../whatsnew/3.13.rst:466 msgid "" "See :pep:`667` for more details, including related C API changes and " "deprecations. Porting notes are also provided below for the affected :ref:" @@ -912,7 +1006,7 @@ msgstr "" "para as :ref:`APIs de Python ` e as :ref:`APIs de C " "` afetadas." -#: ../../whatsnew/3.13.rst:461 +#: ../../whatsnew/3.13.rst:471 msgid "" "(PEP and implementation contributed by Mark Shannon and Tian Gao in :gh:" "`74929`. Documentation updates provided by Guido van Rossum and Alyssa " @@ -922,11 +1016,11 @@ msgstr "" "`74929`. Atualizações da documentação fornecidas por Guido van Rossum e " "Alyssa Coghlan.)" -#: ../../whatsnew/3.13.rst:469 +#: ../../whatsnew/3.13.rst:479 msgid "Support for mobile platforms" msgstr "Suporte para plataformas móveis" -#: ../../whatsnew/3.13.rst:471 +#: ../../whatsnew/3.13.rst:481 msgid "" ":pep:`730`: iOS is now a :pep:`11` supported platform, with the ``arm64-" "apple-ios`` and ``arm64-apple-ios-simulator`` targets at tier 3 (iPhone and " @@ -936,433 +1030,391 @@ msgid "" "supported platform, but will have best-effort support. (PEP written and " "implementation contributed by Russell Keith-Magee in :gh:`114099`.)" msgstr "" -":pep:`730`: O iOS agora é uma plataforma suportada conforme a :pep:`11`, com " +":pep:`730`: iOS agora é uma plataforma com suporte conforme a :pep:`11`, com " "os alvos ``arm64-apple-ios`` e ``arm64-apple-ios-simulator`` no nível 3 " "(dispositivos iPhone e iPad lançados após 2013 e o simulador Xcode iOS sendo " "executado em hardware Apple Silicon, respectivamente). ``x86_64-apple-ios-" "simulator`` (o simulador Xcode iOS sendo executado em hardware ``x86_64`` " -"mais antigo) não é uma plataforma com suporte tier 3, mas terá suporte de " -"melhor esforço. (PEP escrita e implementação como contribuição de Russell " +"mais antigo) não é uma plataforma com suporte nível 3, mas terá o melhor " +"suporte possível. (PEP escrita e implementação como contribuição de Russell " "Keith-Magee em :gh:`114099`.)" -#: ../../whatsnew/3.13.rst:481 +#: ../../whatsnew/3.13.rst:491 msgid "" -":pep:`738`: Android support is being actively worked on, but the platform is " -"not yet officially supported. (PEP written and implementation contributed by " -"Malcolm Smith in :gh:`116622`.)" +":pep:`738`: Android is now a :pep:`11` supported platform, with the " +"``aarch64-linux-android`` and ``x86_64-linux-android`` targets at tier 3. " +"The 32-bit targets ``arm-linux-androideabi`` and ``i686-linux-android`` are " +"not tier 3 supported platforms, but will have best-effort support. (PEP " +"written and implementation contributed by Malcolm Smith in :gh:`116622`.)" msgstr "" -":pep:`738`: O suporte ao Android está sendo ativamente desenvolvimento, mas " -"a plataforma ainda não é oficialmente suportada. (PEP escrita e " -"implementação como contribuição de Malcolm Smith em :gh:`116622`.)" +":pep:`738`: Android agora é uma plataforma com suporte conforme a :pep:`11`, " +"com os alvos ``aarch64-linux-android`` e ``x86_64-linux-android`` no nível " +"3. Os alvos de 32 bits ``arm-linux-androideabi`` e ``i686-linux-android`` " +"não são plataformas com suporte de nível 3, mas terão o melhor suporte " +"possível. (PEP escrita e implementação como contribuição de Malcolm Smith " +"em :gh:`116622`.)" -#: ../../whatsnew/3.13.rst:486 +#: ../../whatsnew/3.13.rst:498 msgid ":pep:`730`, :pep:`738`" msgstr ":pep:`730`, :pep:`738`" -#: ../../whatsnew/3.13.rst:490 -msgid "Incremental garbage collection" -msgstr "Coleta de lixo incremental" - -#: ../../whatsnew/3.13.rst:492 -msgid "" -"The cycle garbage collector is now incremental. This means that maximum " -"pause times are reduced by an order of magnitude or more for larger heaps." -msgstr "" -"O coletor de lixo do ciclo agora é incremental. Isso significa que os tempos " -"máximos de pausa são reduzidos em uma ordem de magnitude ou mais para heaps " -"maiores." - -#: ../../whatsnew/3.13.rst:498 +#: ../../whatsnew/3.13.rst:502 msgid "Other Language Changes" msgstr "Outras mudanças na linguagem" -#: ../../whatsnew/3.13.rst:500 -msgid "" -"Classes have a new :attr:`~class.__static_attributes__` attribute, populated " -"by the compiler, with a tuple of names of attributes of this class which are " -"assigned through ``self.X`` from any function in its body. (Contributed by " -"Irit Katriel in :gh:`115775`.)" -msgstr "" -"As classes têm um novo atributo :attr:`~class.__static_attributes__`, " -"preenchido pelo compilador, com uma tupla de nomes de atributos desta classe " -"que são atribuídos através de ``self.X`` de qualquer função em seu corpo. " -"(Contribuição de Irit Katriel em :gh:`115775`.)" - -#: ../../whatsnew/3.13.rst:505 -msgid "" -"The :func:`exec` and :func:`eval` built-ins now accept their ``globals`` and " -"``locals`` namespace arguments as keywords. (Contributed by Raphael " -"Gaschignard in :gh:`105879`)" -msgstr "" -"As funções embutidas :func:`exec` e :func:`eval` agora aceitam seus " -"argumentos de espaço de nomes ``globals`` e ``locals`` como nomeados. " -"(Contribuição de Raphael Gaschignard em :gh:`105879`)" - -#: ../../whatsnew/3.13.rst:509 -msgid "" -"Allow the *count* argument of :meth:`str.replace` to be a keyword. " -"(Contributed by Hugo van Kemenade in :gh:`106487`.)" -msgstr "" -"Permite que o argumento *count* de :meth:`str.replace` seja um argumento " -"nomeado. (Contribuição de Hugo van Kemenade em :gh:`106487`.)" - -#: ../../whatsnew/3.13.rst:512 -msgid "" -"Compiler now strip indents from docstrings. This will reduce the size of :" -"term:`bytecode cache ` (e.g. ``.pyc`` file). For example, cache " -"file size for ``sqlalchemy.orm.session`` in SQLAlchemy 2.0 is reduced by " -"about 5%. This change will affect tools using docstrings, like :mod:" -"`doctest`. (Contributed by Inada Naoki in :gh:`81283`.)" -msgstr "" -"O compilador agora remove os recuos das docstrings. Isso reduzirá o tamanho " -"do :term:`cache de bytecode ` (por exemplo, arquivo ``.pyc``). Por " -"exemplo, o tamanho do arquivo de cache para ``sqlalchemy.orm.session`` no " -"SQLAlchemy 2.0 é reduzido em cerca de 5%. Esta mudança afetará ferramentas " -"que usam docstrings, como :mod:`doctest`. (Contribuição de Inada Naoki em :" -"gh:`81283`.)" - -#: ../../whatsnew/3.13.rst:519 -msgid "" -"The :func:`compile` built-in can now accept a new flag, ``ast." -"PyCF_OPTIMIZED_AST``, which is similar to ``ast.PyCF_ONLY_AST`` except that " -"the returned ``AST`` is optimized according to the value of the ``optimize`` " -"argument. (Contributed by Irit Katriel in :gh:`108113`)." -msgstr "" -"A função embutida :func:`compile` agora pode aceitar um novo sinalizador, " -"``ast.PyCF_OPTIMIZED_AST``, que é semelhante a ``ast.PyCF_ONLY_AST`` exceto " -"que o ``AST`` retornado é otimizado de acordo com o valor do argumento " -"``optimize``. (Contribuição de Irit Katriel em :gh:`108113`)." - -#: ../../whatsnew/3.13.rst:525 -msgid "" -":mod:`multiprocessing`, :mod:`concurrent.futures`, :mod:`compileall`: " -"Replace :func:`os.cpu_count` with :func:`os.process_cpu_count` to select the " -"default number of worker threads and processes. Get the CPU affinity if " -"supported. (Contributed by Victor Stinner in :gh:`109649`.)" +#: ../../whatsnew/3.13.rst:504 +msgid "" +"The compiler now strips common leading whitespace from every line in a " +"docstring. This reduces the size of the :term:`bytecode cache ` " +"(such as ``.pyc`` files), with reductions in file size of around 5%, for " +"example in :mod:`!sqlalchemy.orm.session` from SQLAlchemy 2.0. This change " +"affects tools that use docstrings, such as :mod:`doctest`." +msgstr "" +"O compilador agora remove espaços em branco comuns de cada linha em uma " +"docstring. Isso reduz o tamanho do :term:`cache de bytecode ` " +"(como arquivos ``.pyc``), com reduções no tamanho do arquivo de cerca de 5%, " +"por exemplo, em :mod:`!sqlalchemy.orm.session` do SQLAlchemy 2.0. Essa " +"alteração afeta ferramentas que usam docstrings, como :mod:`doctest`." + +#: ../../whatsnew/3.13.rst:511 +msgid "" +">>> def spam():\n" +"... \"\"\"\n" +"... This is a docstring with\n" +"... leading whitespace.\n" +"...\n" +"... It even has multiple paragraphs!\n" +"... \"\"\"\n" +"...\n" +">>> spam.__doc__\n" +"'\\nThis is a docstring with\\n leading whitespace.\\n\\nIt even has " +"multiple paragraphs!\\n'" +msgstr "" +">>> def spam():\n" +"... \"\"\"\n" +"... Esta é uma docstring com\n" +"... espaços em branco no começo.\n" +"...\n" +"... Ela atém mesmo tem vários parágrafos!\n" +"... \"\"\"\n" +"...\n" +">>> spam.__doc__\n" +"'\\n\\nEsta é uma docstring com\\n\\n espaços em branco no começo." +"\\n\\n\\nEla atém mesmo tem vários parágrafos!\\n\\n'" + +#: ../../whatsnew/3.13.rst:524 +msgid "(Contributed by Inada Naoki in :gh:`81283`.)" +msgstr "(Contribuição de Inada Naoki em :gh:`81283`.)" + +#: ../../whatsnew/3.13.rst:526 +msgid "" +":ref:`Annotation scopes ` within class scopes can now " +"contain lambdas and comprehensions. Comprehensions that are located within " +"class scopes are not inlined into their parent scope." msgstr "" -":mod:`multiprocessing`, :mod:`concurrent.futures`, :mod:`compileall`: " -"Substitui :func:`os.cpu_count` por :func:`os.process_cpu_count` para " -"selecionar o número padrão de threads de trabalho e processos. Obtém a " -"afinidade da CPU, se houver suporte. (Contribuição de Victor Stinner em :gh:" -"`109649`.)" +":ref:`Escopos de anotação ` dentro dos escopos de classe " +"agora pode conter lambdas e compreensões. As compreensões localizadas nos " +"escopos de classe não são incorporadas ao escopo pai." #: ../../whatsnew/3.13.rst:531 msgid "" -":func:`os.path.realpath` now resolves MS-DOS style file names even if the " -"file is not accessible. (Contributed by Moonsik Park in :gh:`82367`.)" +"class C[T]:\n" +" type Alias = lambda: T" msgstr "" -":func:`os.path.realpath` agora resolve nomes de arquivos no estilo MS-DOS, " -"mesmo que o arquivo não esteja acessível. (Contribuição de Moonsik Park em :" -"gh:`82367`.)" +"class C[T]:\n" +" type Alias = lambda: T" + +#: ../../whatsnew/3.13.rst:536 +msgid "(Contributed by Jelle Zijlstra in :gh:`109118` and :gh:`118160`.)" +msgstr "(Contribuição de Jelle Zijlstra em :gh:`109118` e :gh:`118160`.)" -#: ../../whatsnew/3.13.rst:535 +#: ../../whatsnew/3.13.rst:538 msgid "" -"Fixed a bug where a :keyword:`global` declaration in an :keyword:`except` " -"block is rejected when the global is used in the :keyword:`else` block. " -"(Contributed by Irit Katriel in :gh:`111123`.)" +":ref:`Future statements ` are no longer triggered by relative " +"imports of the :mod:`__future__` module, meaning that statements of the form " +"``from .__future__ import ...`` are now simply standard relative imports, " +"with no special features activated. (Contributed by Jeremiah Gabriel Pascual " +"in :gh:`118216`.)" msgstr "" -"Corrigido um bug onde uma declaração :keyword:`global` em um bloco :keyword:" -"`except` é rejeitada quando o global é usado no bloco :keyword:`else`. " -"(Contribuição de Irit Katriel em :gh:`111123`.)" +":ref:`Instruções future ` não são mais acionadas por importações " +"relativas do módulo :mod:`__future__`, o que significa que instruções no " +"formato ``from .__future__ import ...`` agora são simplesmente importações " +"relativas padrão, sem recursos especiais ativados. (Contribuição de Jeremiah " +"Gabriel Pascual em :gh:`118216`.)" -#: ../../whatsnew/3.13.rst:539 +#: ../../whatsnew/3.13.rst:544 msgid "" -"Many functions now emit a warning if a boolean value is passed as a file " -"descriptor argument. This can help catch some errors earlier. (Contributed " -"by Serhiy Storchaka in :gh:`82626`.)" +":keyword:`global` declarations are now permitted in :keyword:`except` blocks " +"when that global is used in the :keyword:`else` block. Previously this " +"raised an erroneous :exc:`SyntaxError`. (Contributed by Irit Katriel in :gh:" +"`111123`.)" msgstr "" -"Muitas funções agora emitem um aviso se um valor booleano for passado como " -"argumento do descritor de arquivo. Isso pode ajudar a detectar alguns erros " -"mais cedo. (Contribuição de Serhiy Storchaka em :gh:`82626`.)" +"Declarações :keyword:`global` agora são permitidas em blocos :keyword:" +"`except` quando esse global é usado no bloco :keyword:`else`. Anteriormente, " +"isso erroneamente levantava uma exceção :exc:`SyntaxError`. (Contribuição de " +"Irit Katriel em :gh:`111123`.)" -#: ../../whatsnew/3.13.rst:544 +#: ../../whatsnew/3.13.rst:549 msgid "" -"Added a new environment variable :envvar:`PYTHON_FROZEN_MODULES`. It " -"determines whether or not frozen modules are ignored by the import " -"machinery, equivalent of the :option:`-X frozen_modules <-X>` command-line " -"option. (Contributed by Yilei Yang in :gh:`111374`.)" +"Add :envvar:`PYTHON_FROZEN_MODULES`, a new environment variable that " +"determines whether frozen modules are ignored by the import machinery, " +"equivalent to the :option:`-X frozen_modules <-X>` command-line option. " +"(Contributed by Yilei Yang in :gh:`111374`.)" msgstr "" -"Adicionada uma nova variável de ambiente :envvar:`PYTHON_FROZEN_MODULES`. " -"Ela determina se os módulos congelados são ou não ignorados pelo mecanismo " -"de importação, equivalente à opção de linha de comando :option:`-X " +"Adiciona :envvar:`PYTHON_FROZEN_MODULES`, uma nova variável de ambiente que " +"determina se os módulos congelados são ignorados pelo maquinário de " +"importação, equivalente à opção de linha de comando :option:`-X " "frozen_modules <-X>`. (Contribuição de Yilei Yang em :gh:`111374`.)" -#: ../../whatsnew/3.13.rst:549 +#: ../../whatsnew/3.13.rst:554 msgid "" "Add :ref:`support for the perf profiler ` working without " -"frame pointers through the new environment variable :envvar:" -"`PYTHON_PERF_JIT_SUPPORT` and command-line option :option:`-X perf_jit <-X>` " -"(Contributed by Pablo Galindo in :gh:`118518`.)" +"`frame pointers `_ through the new " +"environment variable :envvar:`PYTHON_PERF_JIT_SUPPORT` and command-line " +"option :option:`-X perf_jit <-X>`. (Contributed by Pablo Galindo in :gh:" +"`118518`.)" msgstr "" "Adicionado :ref:`suporte ao perfilador perf ` funcionando " -"sem ponteiros de quadro através da nova variável de ambiente :envvar:" -"`PYTHON_PERF_JIT_SUPPORT` e opção de linha de comando :option:`-X perf_jit <-" -"X>` (Contribuição de Pablo Galindo em :gh:`118518`.)" +"sem `ponteiros de quadro `_ " +"através da nova variável de ambiente :envvar:`PYTHON_PERF_JIT_SUPPORT` e " +"opção de linha de comando :option:`-X perf_jit <-X>`. (Contribuição de Pablo " +"Galindo em :gh:`118518`.)" -#: ../../whatsnew/3.13.rst:554 +#: ../../whatsnew/3.13.rst:560 msgid "" -"The new :envvar:`PYTHON_HISTORY` environment variable can be used to change " -"the location of a ``.python_history`` file. (Contributed by Levi Sabah, " +"The location of a :file:`.python_history` file can be changed via the new :" +"envvar:`PYTHON_HISTORY` environment variable. (Contributed by Levi Sabah, " "Zackery Spytz and Hugo van Kemenade in :gh:`73965`.)" msgstr "" -"A nova variável de ambiente :envvar:`PYTHON_HISTORY` pode ser usada para " -"alterar a localização de um arquivo ``.python_history``. (Contribuição de " +"A localização de um arquivo :file:`.python_history` pode ser alterada por " +"meio da nova variável de ambiente :envvar:`PYTHON_HISTORY`. (Contribuição de " "Levi Sabah, Zackery Spytz e Hugo van Kemenade em :gh:`73965`.)" -#: ../../whatsnew/3.13.rst:559 +#: ../../whatsnew/3.13.rst:565 msgid "" -"Add :exc:`PythonFinalizationError` exception. This exception derived from :" -"exc:`RuntimeError` is raised when an operation is blocked during the :term:" -"`Python finalization `." +"Classes have a new :attr:`~type.__static_attributes__` attribute. This is " +"populated by the compiler with a tuple of the class's attribute names which " +"are assigned through ``self.`` from any function in its body. " +"(Contributed by Irit Katriel in :gh:`115775`.)" msgstr "" -"Adiciona a exceção :exc:`PythonFinalizationError`. Esta exceção derivada " -"de :exc:`RuntimeError` é levantada quando uma operação é bloqueada durante " -"a :term:`finalização do Python `." +"As classes têm um novo atributo :attr:`~type.__static_attributes__`. Isso é " +"preenchido pelo compilador, com uma tupla de nomes de atributos da classe " +"que são atribuídos através de ``self.`` de qualquer função em seu " +"corpo. (Contribuição de Irit Katriel em :gh:`115775`.)" -#: ../../whatsnew/3.13.rst:563 +#: ../../whatsnew/3.13.rst:570 msgid "" -"The following functions now raise PythonFinalizationError, instead of :exc:" -"`RuntimeError`:" +"The compiler now creates a :attr:`!__firstlineno__` attribute on classes " +"with the line number of the first line of the class definition. (Contributed " +"by Serhiy Storchaka in :gh:`118465`.)" msgstr "" -"As seguintes funções agora levantam PythonFinalizationError, em vez de :exc:" -"`RuntimeError`:" +"O compilador agora cria um atributo :attr:`!__firstlineno__` em classes com " +"o número da primeira linha da definição de classe. (Contribuição de Serhiy " +"Storchaka em :gh:`118465`.)" -#: ../../whatsnew/3.13.rst:566 -msgid ":func:`_thread.start_new_thread`." -msgstr ":func:`_thread.start_new_thread`." - -#: ../../whatsnew/3.13.rst:567 -msgid ":class:`subprocess.Popen`." -msgstr ":class:`subprocess.Popen`." - -#: ../../whatsnew/3.13.rst:568 -msgid ":func:`os.fork`." -msgstr ":func:`os.fork`." - -#: ../../whatsnew/3.13.rst:569 -msgid ":func:`os.forkpty`." -msgstr ":func:`os.forkpty`." - -#: ../../whatsnew/3.13.rst:571 -msgid "(Contributed by Victor Stinner in :gh:`114570`.)" -msgstr "(Contribuição de Victor Stinner em :gh:`114570`.)" - -#: ../../whatsnew/3.13.rst:573 +#: ../../whatsnew/3.13.rst:574 msgid "" -"Added :attr:`!name` and :attr:`!mode` attributes for compressed and archived " -"file-like objects in modules :mod:`bz2`, :mod:`lzma`, :mod:`tarfile` and :" -"mod:`zipfile`. (Contributed by Serhiy Storchaka in :gh:`115961`.)" +"The :func:`exec` and :func:`eval` builtins now accept the *globals* and " +"*locals* arguments as keywords. (Contributed by Raphael Gaschignard in :gh:" +"`105879`)" msgstr "" -"Adicionados atributos :attr:`!name` e :attr:`!mode` para objetos arquivo ou " -"similar compactados e arquivados nos módulos :mod:`bz2`, :mod:`lzma`, :mod:" -"`tarfile` e :mod:`zipfile`. (Contribuição de Serhiy Storchaka em :gh:" -"`115961`.)" +"As funções embutidas :func:`exec` e :func:`eval` agora aceitam os argumentos " +"*globals* e *locals* como nomeados. (Contribuição de Raphael Gaschignard em :" +"gh:`105879`)" #: ../../whatsnew/3.13.rst:578 msgid "" -"Allow controlling Expat >=2.6.0 reparse deferral (:cve:`2023-52425`) by " -"adding five new methods:" +"The :func:`compile` builtin now accepts a new flag, ``ast." +"PyCF_OPTIMIZED_AST``, which is similar to ``ast.PyCF_ONLY_AST`` except that " +"the returned AST is optimized according to the value of the *optimize* " +"argument. (Contributed by Irit Katriel in :gh:`108113`)." msgstr "" -"Permite controlar o adiamento da nova análise do Expat >=2.6.0 (:cve:" -"`2023-52425`) adicionando cinco novos métodos:" - -#: ../../whatsnew/3.13.rst:581 -msgid ":meth:`xml.etree.ElementTree.XMLParser.flush`" -msgstr ":meth:`xml.etree.ElementTree.XMLParser.flush`" - -#: ../../whatsnew/3.13.rst:582 -msgid ":meth:`xml.etree.ElementTree.XMLPullParser.flush`" -msgstr ":meth:`xml.etree.ElementTree.XMLPullParser.flush`" - -#: ../../whatsnew/3.13.rst:583 -msgid ":meth:`xml.parsers.expat.xmlparser.GetReparseDeferralEnabled`" -msgstr ":meth:`xml.parsers.expat.xmlparser.GetReparseDeferralEnabled`" +"A função embutida :func:`compile` agora aceita um novo sinalizador, ``ast." +"PyCF_OPTIMIZED_AST``, que é semelhante a ``ast.PyCF_ONLY_AST`` exceto que a " +"AST retornada é otimizada de acordo com o valor do argumento *optimize*. " +"(Contribuição de Irit Katriel em :gh:`108113`)." #: ../../whatsnew/3.13.rst:584 -msgid ":meth:`xml.parsers.expat.xmlparser.SetReparseDeferralEnabled`" -msgstr ":meth:`xml.parsers.expat.xmlparser.SetReparseDeferralEnabled`" - -#: ../../whatsnew/3.13.rst:585 -msgid ":meth:`!xml.sax.expatreader.ExpatParser.flush`" -msgstr ":meth:`!xml.sax.expatreader.ExpatParser.flush`" +msgid "" +"Add a :attr:`~property.__name__` attribute on :class:`property` objects. " +"(Contributed by Eugene Toder in :gh:`101860`.)" +msgstr "" +"Adiciona um atributo :attr:`~property.__name__` em objetos :class:" +"`property`. (Contribuição de Eugene Toder em :gh:`101860`.)" #: ../../whatsnew/3.13.rst:587 -msgid "(Contributed by Sebastian Pipping in :gh:`115623`.)" -msgstr "(Contribuição de Sebastian Pipping em :gh:`115623`.)" - -#: ../../whatsnew/3.13.rst:589 msgid "" -"The :func:`ssl.create_default_context` API now includes :data:`ssl." -"VERIFY_X509_PARTIAL_CHAIN` and :data:`ssl.VERIFY_X509_STRICT` in its default " -"flags." +"Add :exc:`PythonFinalizationError`, a new exception derived from :exc:" +"`RuntimeError` and used to signal when operations are blocked during :term:" +"`finalization `. The following callables now raise :" +"exc:`!PythonFinalizationError`, instead of :exc:`RuntimeError`:" msgstr "" -"A API :func:`ssl.create_default_context` agora inclui :data:`ssl." -"VERIFY_X509_PARTIAL_CHAIN` e :data:`ssl.VERIFY_X509_STRICT` em seus " -"sinalizadores padrão." +"Adiciona :exc:`PythonFinalizationError`, uma nova exceção derivada de :exc:" +"`RuntimeError` e usada para sinalizar quando as operações são bloqueadas " +"durante a :term:`finalização `. Os seguintes chamáveis " +"agora levantam :exc:`!PythonFinalizationError`, em vez de :exc:" +"`RuntimeError`:" + +#: ../../whatsnew/3.13.rst:593 +msgid ":func:`_thread.start_new_thread`" +msgstr ":func:`_thread.start_new_thread`" + +#: ../../whatsnew/3.13.rst:594 +msgid ":func:`os.fork`" +msgstr ":func:`os.fork`" #: ../../whatsnew/3.13.rst:595 -msgid "" -":data:`ssl.VERIFY_X509_STRICT` may reject pre-:rfc:`5280` or malformed " -"certificates that the underlying OpenSSL implementation otherwise would " -"accept. While disabling this is not recommended, you can do so using::" -msgstr "" -":data:`ssl.VERIFY_X509_STRICT` pode rejeitar certificados pré-:rfc:`5280` ou " -"malformados que a implementação OpenSSL subjacente aceitaria de outra forma. " -"Embora não seja recomendado desativar isso, você pode fazer isso usando::" +msgid ":func:`os.forkpty`" +msgstr ":func:`os.forkpty`" -#: ../../whatsnew/3.13.rst:602 -msgid "(Contributed by William Woodruff in :gh:`112389`.)" -msgstr "(Contribuição de William Woodruff em :gh:`112389`.)" +#: ../../whatsnew/3.13.rst:596 +msgid ":class:`subprocess.Popen`" +msgstr ":class:`subprocess.Popen`" -#: ../../whatsnew/3.13.rst:604 -msgid "" -"The :class:`configparser.ConfigParser` now accepts unnamed sections before " -"named ones if configured to do so. (Contributed by Pedro Sousa Lacerda in :" -"gh:`66449`.)" -msgstr "" -":class:`configparser.ConfigParser` agora aceita seções sem nome antes das " -"nomeadas se configurado para isso. (Contribuição de Pedro Sousa Lacerda em :" -"gh:`66449`.)" +#: ../../whatsnew/3.13.rst:598 +msgid "(Contributed by Victor Stinner in :gh:`114570`.)" +msgstr "(Contribuição de Victor Stinner em :gh:`114570`.)" -#: ../../whatsnew/3.13.rst:608 +#: ../../whatsnew/3.13.rst:600 msgid "" -":ref:`annotation scope ` within class scopes can now " -"contain lambdas and comprehensions. Comprehensions that are located within " -"class scopes are not inlined into their parent scope. (Contributed by Jelle " -"Zijlstra in :gh:`109118` and :gh:`118160`.)" +"Allow the *count* argument of :meth:`str.replace` to be a keyword. " +"(Contributed by Hugo van Kemenade in :gh:`106487`.)" msgstr "" -":ref:`Escopo de anotação ` dentro dos escopos de classe " -"agora pode conter lambdas e compreensões. As compreensões localizadas nos " -"escopos de classe não são incorporadas ao escopo pai. (Contribuição de Jelle " -"Zijlstra em :gh:`109118` e :gh:`118160`.)" +"Permite que o argumento *count* de :meth:`str.replace` seja um argumento " +"nomeado. (Contribuição de Hugo van Kemenade em :gh:`106487`.)" -#: ../../whatsnew/3.13.rst:613 +#: ../../whatsnew/3.13.rst:603 msgid "" -"Classes have a new :attr:`!__firstlineno__` attribute, populated by the " -"compiler, with the line number of the first line of the class definition. " -"(Contributed by Serhiy Storchaka in :gh:`118465`.)" +"Many functions now emit a warning if a boolean value is passed as a file " +"descriptor argument. This can help catch some errors earlier. (Contributed " +"by Serhiy Storchaka in :gh:`82626`.)" msgstr "" -"As classes possuem um novo atributo :attr:`!__firstlineno__`, preenchido " -"pelo compilador, com o número da primeira linha da definição de classe. " -"(Contribuição de Serhiy Storchaka em :gh:`118465`.)" +"Muitas funções agora emitem um aviso se um valor booleano for passado como " +"argumento do descritor de arquivo. Isso pode ajudar a detectar alguns erros " +"mais cedo. (Contribuição de Serhiy Storchaka em :gh:`82626`.)" -#: ../../whatsnew/3.13.rst:618 +#: ../../whatsnew/3.13.rst:608 msgid "" -"``from __future__ import ...`` statements are now just normal relative " -"imports if dots are present before the module name. (Contributed by Jeremiah " -"Gabriel Pascual in :gh:`118216`.)" +"Added :attr:`!name` and :attr:`!mode` attributes for compressed and archived " +"file-like objects in the :mod:`bz2`, :mod:`lzma`, :mod:`tarfile`, and :mod:" +"`zipfile` modules. (Contributed by Serhiy Storchaka in :gh:`115961`.)" msgstr "" -"As instruções ``from __future__ import ...`` agora são apenas importações " -"relativas normais se houver pontos antes do nome do módulo. (Contribuição de " -"Jeremiah Gabriel Pascual em :gh:`118216`.)" +"Adicionados atributos :attr:`!name` e :attr:`!mode` para objetos arquivo ou " +"similar compactados e arquivados nos módulos :mod:`bz2`, :mod:`lzma`, :mod:" +"`tarfile` e :mod:`zipfile`. (Contribuição de Serhiy Storchaka em :gh:" +"`115961`.)" -#: ../../whatsnew/3.13.rst:624 +#: ../../whatsnew/3.13.rst:615 msgid "New Modules" msgstr "Novos módulos" -#: ../../whatsnew/3.13.rst:626 +#: ../../whatsnew/3.13.rst:617 msgid "" -":mod:`dbm.sqlite3`: SQLite backend for :mod:`dbm`. (Contributed by Raymond " -"Hettinger and Erlend E. Aasland in :gh:`100414`.)" +":mod:`dbm.sqlite3`: An SQLite backend for :mod:`dbm`. (Contributed by " +"Raymond Hettinger and Erlend E. Aasland in :gh:`100414`.)" msgstr "" -":mod:`dbm.sqlite3`: Backend SQLite para :mod:`dbm`. (Contribuição de Raymond " -"Hettinger e Erlend E. Aasland em :gh:`100414`.)" +":mod:`dbm.sqlite3`: um backend SQLite para :mod:`dbm`. (Contribuição de " +"Raymond Hettinger e Erlend E. Aasland em :gh:`100414`.)" -#: ../../whatsnew/3.13.rst:631 +#: ../../whatsnew/3.13.rst:622 msgid "Improved Modules" msgstr "Módulos melhorados" -#: ../../whatsnew/3.13.rst:634 +#: ../../whatsnew/3.13.rst:626 msgid "argparse" msgstr "argparse" -#: ../../whatsnew/3.13.rst:636 +#: ../../whatsnew/3.13.rst:628 msgid "" -"Add parameter *deprecated* in methods :meth:`~argparse.ArgumentParser." -"add_argument` and :meth:`!add_parser` which allows to deprecate command-line " -"options, positional arguments and subcommands. (Contributed by Serhiy " +"Add the *deprecated* parameter to the :meth:`~argparse.ArgumentParser." +"add_argument` and :meth:`!add_parser` methods, to enable deprecating command-" +"line options, positional arguments, and subcommands. (Contributed by Serhiy " "Storchaka in :gh:`83648`.)" msgstr "" -"Adiciona o parâmetro *deprecated* nos métodos :meth:`~argparse." -"ArgumentParser.add_argument` e :meth:`!add_parser` que permite descontinuar " -"opções de linha de comando, argumentos posicionais e subcomandos. " -"(Contribuição de Serhiy Storchaka em :gh:`83648`.)" +"Adiciona o parâmetro *deprecated* aos métodos :meth:`~argparse." +"ArgumentParser.add_argument` e :meth:`!add_parser`, o qual permite " +"descontinuar opções de linha de comando, argumentos posicionais e " +"subcomandos. (Contribuição de Serhiy Storchaka em :gh:`83648`.)" -#: ../../whatsnew/3.13.rst:643 +#: ../../whatsnew/3.13.rst:636 msgid "array" msgstr "array" -#: ../../whatsnew/3.13.rst:645 +#: ../../whatsnew/3.13.rst:638 msgid "" -"Add ``'w'`` type code (``Py_UCS4``) that can be used for Unicode strings. It " -"can be used instead of ``'u'`` type code, which is deprecated. (Contributed " -"by Inada Naoki in :gh:`80480`.)" +"Add the ``'w'`` type code (``Py_UCS4``) for Unicode characters. It should be " +"used instead of the deprecated ``'u'`` type code. (Contributed by Inada " +"Naoki in :gh:`80480`.)" msgstr "" -"Adiciona o código do tipo ``'w'`` (``Py_UCS4``) que pode ser usado para " -"strings Unicode. Ele pode ser usado no lugar do código do tipo ``'u'``, que " -"foi descontinuado. (Contribuição de Inada Naoki em :gh:`80480`.)" +"Adiciona o código do tipo ``'w'`` (``Py_UCS4``) para caracteres Unicode. Ele " +"deve ser usado no lugar do código do tipo ``'u'`` descontinuado. " +"(Contribuição de Inada Naoki em :gh:`80480`.)" -#: ../../whatsnew/3.13.rst:649 +#: ../../whatsnew/3.13.rst:642 msgid "" -"Add ``clear()`` method in order to implement ``MutableSequence``. " -"(Contributed by Mike Zimin in :gh:`114894`.)" +"Register :class:`array.array` as a :class:`~collections.abc.MutableSequence` " +"by implementing the :meth:`~array.array.clear` method. (Contributed by Mike " +"Zimin in :gh:`114894`.)" msgstr "" -"Adiciona o método ``clear()`` para implementar ``MutableSequence``. " -"(Contribuição de Mike Zimin em :gh:`114894`.)" +"Registra :class:`array.array` como :class:`~collections.abc.MutableSequence` " +"implementando o método :meth:`~array.array.clear`. (Contribuição de Mike " +"Zimin em :gh:`114894`.)" -#: ../../whatsnew/3.13.rst:653 +#: ../../whatsnew/3.13.rst:648 msgid "ast" msgstr "ast" -#: ../../whatsnew/3.13.rst:655 +#: ../../whatsnew/3.13.rst:650 msgid "" "The constructors of node types in the :mod:`ast` module are now stricter in " -"the arguments they accept, and have more intuitive behaviour when arguments " -"are omitted." +"the arguments they accept, with more intuitive behavior when arguments are " +"omitted." msgstr "" "Os construtores dos tipos de nós no módulo :mod:`ast` agora são mais rígidos " -"nos argumentos que aceitam e têm um comportamento mais intuitivo quando os " +"nos argumentos que aceitam, com um comportamento mais intuitivo quando os " "argumentos são omitidos." -#: ../../whatsnew/3.13.rst:659 +#: ../../whatsnew/3.13.rst:654 msgid "" "If an optional field on an AST node is not included as an argument when " "constructing an instance, the field will now be set to ``None``. Similarly, " "if a list field is omitted, that field will now be set to an empty list, and " -"if a :class:`!ast.expr_context` field is omitted, it defaults to :class:" -"`Load() `. (Previously, in all cases, the attribute would be " -"missing on the newly constructed AST node instance.)" +"if an :class:`!expr_context` field is omitted, it defaults to :class:`Load() " +"`. (Previously, in all cases, the attribute would be missing on " +"the newly constructed AST node instance.)" msgstr "" -"Se um campo opcional em um nó AST não for incluído como argumento ao " +"Se um campo opcional em um nó da AST não for incluído como argumento ao " "construir uma instância, o campo agora será definido como ``None``. Da mesma " "forma, se um campo de lista for omitido, esse campo será agora definido como " -"uma lista vazia, e se um campo :class:`!ast.expr_context` for omitido, o " -"padrão será :class:`Load() `. (Anteriormente, em todos os casos, o " -"atributo estaria ausente na instância do nó de AST recém-construída.)" - -#: ../../whatsnew/3.13.rst:667 -msgid "" -"If other arguments are omitted, a :exc:`DeprecationWarning` is emitted. This " -"will cause an exception in Python 3.15. Similarly, passing a keyword " -"argument that does not map to a field on the AST node is now deprecated, and " -"will raise an exception in Python 3.15." -msgstr "" -"Se outros argumentos forem omitidos, um :exc:`DeprecationWarning` será " -"emitido. Isso causará uma exceção no Python 3.15. Da mesma forma, passar um " -"argumento nomeado que não mapeia para um campo no nó AST agora está " +"uma lista vazia, e se um campo :class:`!expr_context` for omitido, o padrão " +"será :class:`Load() `. (Anteriormente, em todos os casos, o " +"atributo estaria ausente na instância do nó da AST recém-construída.)" + +#: ../../whatsnew/3.13.rst:662 +msgid "" +"In all other cases, where a required argument is omitted, the node " +"constructor will emit a :exc:`DeprecationWarning`. This will raise an " +"exception in Python 3.15. Similarly, passing a keyword argument to the " +"constructor that does not map to a field on the AST node is now deprecated, " +"and will raise an exception in Python 3.15." +msgstr "" +"Em todos os outros casos, nos quais um argumento é omitido, o construtor de " +"nós vai emitir uma :exc:`DeprecationWarning`. Isso vai levantar uma exceção " +"no Python 3.15. Da mesma forma, passar um argumento nomeado para o " +"construtor que não mapeia para um campo no nó da AST agora está " "descontinuado e vai levantar uma exceção no Python 3.15." -#: ../../whatsnew/3.13.rst:672 +#: ../../whatsnew/3.13.rst:669 msgid "" -"These changes do not apply to user-defined subclasses of :class:`ast.AST`, " -"unless the class opts in to the new behavior by setting the attribute :attr:" -"`ast.AST._field_types`." +"These changes do not apply to user-defined subclasses of :class:`ast.AST` " +"unless the class opts in to the new behavior by defining the :attr:`.AST." +"_field_types` mapping." msgstr "" -"Estas mudanças não se aplicam às subclasses definidas pelo usuário de :class:" -"`ast.AST`, a menos que a classe opte pelo novo comportamento definindo o " -"atributo :attr:`ast.AST._field_types`." +"Estas mudanças não se aplicam às subclasses de :class:`ast.AST` definidas " +"pelo usuário, a menos que a classe opte pelo novo comportamento definindo o " +"mapeamento :attr:`.AST._field_types`." -#: ../../whatsnew/3.13.rst:676 +#: ../../whatsnew/3.13.rst:673 msgid "" "(Contributed by Jelle Zijlstra in :gh:`105858`, :gh:`117486`, and :gh:" "`118851`.)" @@ -1370,21 +1422,37 @@ msgstr "" "(Contribuição de Jelle Zijlstra em :gh:`105858`, :gh:`117486` e :gh:" "`118851`.)" -#: ../../whatsnew/3.13.rst:678 +#: ../../whatsnew/3.13.rst:675 msgid "" ":func:`ast.parse` now accepts an optional argument *optimize* which is " -"passed on to the :func:`compile` built-in. This makes it possible to obtain " -"an optimized AST. (Contributed by Irit Katriel in :gh:`108113`.)" +"passed on to :func:`compile`. This makes it possible to obtain an optimized " +"AST. (Contributed by Irit Katriel in :gh:`108113`.)" msgstr "" ":func:`ast.parse` agora aceita um argumento opcional *optimize* que é " -"passado para o :func:`compile` embutido. Isto torna possível obter um AST " -"otimizado. (Contribuição de Irit Katriel em :gh:`108113`.)" +"passado para :func:`compile`. Isto torna possível obter uma AST otimizada. " +"(Contribuição de Irit Katriel em :gh:`108113`.)" -#: ../../whatsnew/3.13.rst:684 +#: ../../whatsnew/3.13.rst:682 msgid "asyncio" msgstr "asyncio" -#: ../../whatsnew/3.13.rst:686 +#: ../../whatsnew/3.13.rst:684 +msgid "" +":func:`asyncio.as_completed` now returns an object that is both an :term:" +"`asynchronous iterator` and a plain :term:`iterator` of :term:`awaitables " +"`. The awaitables yielded by asynchronous iteration include " +"original task or future objects that were passed in, making it easier to " +"associate results with the tasks being completed. (Contributed by Justin " +"Arthur in :gh:`77714`.)" +msgstr "" +":func:`asyncio.as_completed` agora retorna um objeto que é ao mesmo tempo " +"um :term:`iterador assíncrono` e um :term:`iterator` simples de :term:" +"`aguardáveis `. Os aguardáveis gerados pela iteração assíncrona " +"incluem tarefas originais ou objetos futuros que foram passados, facilitando " +"a associação dos resultados às tarefas que estão sendo concluídas. " +"(Contribuição de Justin Arthur em :gh:`77714`.)" + +#: ../../whatsnew/3.13.rst:692 msgid "" ":meth:`asyncio.loop.create_unix_server` will now automatically remove the " "Unix socket when the server is closed. (Contributed by Pierre Ossman in :gh:" @@ -1394,214 +1462,334 @@ msgstr "" "soquete Unix quando o servidor for fechado. (Contribuição de Pierre Ossman " "em :gh:`111246`.)" -#: ../../whatsnew/3.13.rst:690 +#: ../../whatsnew/3.13.rst:696 msgid "" -":meth:`asyncio.DatagramTransport.sendto` will now send zero-length datagrams " -"if called with an empty bytes object. The transport flow control also now " +":meth:`.DatagramTransport.sendto` will now send zero-length datagrams if " +"called with an empty bytes object. The transport flow control also now " "accounts for the datagram header when calculating the buffer size. " "(Contributed by Jamie Phan in :gh:`115199`.)" msgstr "" -":meth:`asyncio.DatagramTransport.sendto` agora enviará datagramas de " -"comprimento zero se for chamado com um objeto de bytes vazios. O controle de " -"fluxo de transporte agora também leva em conta o cabeçalho do datagrama ao " -"calcular o tamanho do buffer. (Contribuição de Jamie Phan em :gh:`115199`.)" +":meth:`.DatagramTransport.sendto` agora enviará datagramas de comprimento " +"zero se for chamado com um objeto de bytes vazios. O controle de fluxo de " +"transporte agora também leva em conta o cabeçalho do datagrama ao calcular o " +"tamanho do buffer. (Contribuição de Jamie Phan em :gh:`115199`.)" -#: ../../whatsnew/3.13.rst:696 +#: ../../whatsnew/3.13.rst:702 msgid "" -"Add :meth:`asyncio.Server.close_clients` and :meth:`asyncio.Server." -"abort_clients` methods which allow to more forcefully close an asyncio " -"server. (Contributed by Pierre Ossman in :gh:`113538`.)" +"Add :meth:`Queue.shutdown ` and :exc:`~asyncio." +"QueueShutDown` to manage queue termination. (Contributed by Laurie Opperman " +"and Yves Duprat in :gh:`104228`.)" msgstr "" -"Adiciona os métodos :meth:`asyncio.Server.close_clients` e :meth:`asyncio." -"Server.abort_clients` que permitem fechar de forma mais forçada um servidor " -"asyncio. (Contribuição de Pierre Ossman em :gh:`113538`.)" +"Adiciona :meth:`Queue.shutdown ` e :exc:`~asyncio." +"QueueShutDown` para gerenciar a terminação da fila. (Contribuição de Laurie " +"Opperman e Yves Duprat em :gh:`104228`.)" -#: ../../whatsnew/3.13.rst:701 +#: ../../whatsnew/3.13.rst:706 msgid "" -":func:`asyncio.as_completed` now returns an object that is both an :term:" -"`asynchronous iterator` and a plain :term:`iterator` of awaitables. The " -"awaitables yielded by asynchronous iteration include original task or future " -"objects that were passed in, making it easier to associate results with the " -"tasks being completed. (Contributed by Justin Arthur in :gh:`77714`.)" +"Add the :meth:`.Server.close_clients` and :meth:`.Server.abort_clients` " +"methods, which more forcefully close an asyncio server. (Contributed by " +"Pierre Ossman in :gh:`113538`.)" msgstr "" -":func:`asyncio.as_completed` agora retorna um objeto que é ao mesmo tempo " -"um :term:`iterador assíncrono` e um :term:`iterator` simples de aguardáveis. " -"Os aguardáveis ​​gerados pela iteração assíncrona incluem tarefas originais ou " -"objetos futuros que foram passados, facilitando a associação dos resultados " -"às tarefas que estão sendo concluídas. (Contribuição de Justin Arthur em :gh:" -"`77714`.)" +"Adiciona os métodos :meth:`.Server.close_clients` e :meth:`.Server." +"abort_clients`, que fecham de forma mais forçada um servidor asyncio. " +"(Contribuição de Pierre Ossman em :gh:`113538`.)" -#: ../../whatsnew/3.13.rst:708 +#: ../../whatsnew/3.13.rst:710 msgid "" -"When :func:`asyncio.TaskGroup.create_task` is called on an inactive :class:" -"`asyncio.TaskGroup`, the given coroutine will be closed (which prevents a :" -"exc:`RuntimeWarning` about the given coroutine being never awaited). " -"(Contributed by Arthur Tacca and Jason Zhang in :gh:`115957`.)" +"Accept a tuple of separators in :meth:`.StreamReader.readuntil`, stopping " +"when any one of them is encountered. (Contributed by Bruce Merry in :gh:" +"`81322`.)" msgstr "" -"Quando :func:`asyncio.TaskGroup.create_task` é chamado em um :class:`asyncio." -"TaskGroup` inativo, a corrotina fornecida será fechada (o que evita que um :" -"exc:`RuntimeWarning` sobre a corrotina fornecida nunca seja aguardado). " -"(Contribuição de Arthur Tacca e Jason Zhang em :gh:`115957`.)" +"Aceita uma tupla de separadores em :meth:`.StreamReader.readuntil`, parando " +"quando qualquer um deles for encontrado. (Contribuição de Bruce Merry em :gh:" +"`81322`.)" #: ../../whatsnew/3.13.rst:714 msgid "" -"Improved behavior of :class:`asyncio.TaskGroup` when an external " +"Improve the behavior of :class:`~asyncio.TaskGroup` when an external " "cancellation collides with an internal cancellation. For example, when two " "task groups are nested and both experience an exception in a child task " "simultaneously, it was possible that the outer task group would hang, " "because its internal cancellation was swallowed by the inner task group." msgstr "" -"Comportamento aprimorado de :class:`asyncio.TaskGroup` quando um " +"Melhora o comportamento de :class:`~asyncio.TaskGroup` quando um " "cancelamento externo colide com um cancelamento interno. Por exemplo, quando " "dois grupos de tarefas estão aninhados e ambos experimentam uma exceção em " "uma tarefa filho simultaneamente, é possível que o grupo de tarefas externo " "seja interrompido, porque seu cancelamento interno foi engolido pelo grupo " "de tarefas interno." -#: ../../whatsnew/3.13.rst:720 +#: ../../whatsnew/3.13.rst:721 msgid "" "In the case where a task group is cancelled externally and also must raise " "an :exc:`ExceptionGroup`, it will now call the parent task's :meth:`~asyncio." -"Task.cancel` method. This ensures that a :exc:`asyncio.CancelledError` will " +"Task.cancel` method. This ensures that a :exc:`~asyncio.CancelledError` will " "be raised at the next :keyword:`await`, so the cancellation is not lost." msgstr "" "No caso em que um grupo de tarefas é cancelado externamente e também deve " "levantar :exc:`ExceptionGroup`, ele agora chamará o método :meth:`~asyncio." -"Task.cancel` da tarefa pai. Isso garante que uma :exc:`asyncio." +"Task.cancel` da tarefa pai. Isso garante que uma :exc:`~asyncio." "CancelledError` será levantada no próximo :keyword:`await`, para que o " "cancelamento não seja perdido." -#: ../../whatsnew/3.13.rst:726 +#: ../../whatsnew/3.13.rst:727 msgid "" "An added benefit of these changes is that task groups now preserve the " -"cancellation count (:meth:`asyncio.Task.cancelling`)." +"cancellation count (:meth:`~asyncio.Task.cancelling`)." msgstr "" "Um benefício adicional dessas mudanças é que os grupos de tarefas agora " -"preservam a contagem de cancelamentos (:meth:`asyncio.Task.cancelling`)." +"preservam a contagem de cancelamentos (:meth:`~asyncio.Task.cancelling`)." -#: ../../whatsnew/3.13.rst:729 +#: ../../whatsnew/3.13.rst:730 msgid "" -"In order to handle some corner cases, :meth:`asyncio.Task.uncancel` may now " +"In order to handle some corner cases, :meth:`~asyncio.Task.uncancel` may now " "reset the undocumented ``_must_cancel`` flag when the cancellation count " "reaches zero." msgstr "" -"Para lidar com alguns casos extremos, :meth:`asyncio.Task.uncancel` agora " +"Para lidar com alguns casos extremos, :meth:`~asyncio.Task.uncancel` agora " "pode redefinir o sinalizador não documentado ``_must_cancel`` quando a " "contagem de cancelamentos chegar a zero." -#: ../../whatsnew/3.13.rst:733 +#: ../../whatsnew/3.13.rst:734 msgid "(Inspired by an issue reported by Arthur Tacca in :gh:`116720`.)" msgstr "" -"(Inspirado por um relatório de problema relatado por Arthur Tacca em :gh:" +"(Inspirado por um relatório de problema enviado por Arthur Tacca em :gh:" "`116720`.)" -#: ../../whatsnew/3.13.rst:735 +#: ../../whatsnew/3.13.rst:736 +msgid "" +"When :meth:`.TaskGroup.create_task` is called on an inactive :class:" +"`~asyncio.TaskGroup`, the given coroutine will be closed (which prevents a :" +"exc:`RuntimeWarning` about the given coroutine being never awaited). " +"(Contributed by Arthur Tacca and Jason Zhang in :gh:`115957`.)" +msgstr "" +"Quando :meth:`.TaskGroup.create_task` é chamado em um :class:`~asyncio." +"TaskGroup` inativo, a corrotina fornecida será fechada (o que evita um :exc:" +"`RuntimeWarning` sobre uma corrotina que nunca foi aguardada). (Contribuição " +"de Arthur Tacca e Jason Zhang em :gh:`115957`.)" + +#: ../../whatsnew/3.13.rst:742 msgid "" -"Add :meth:`asyncio.Queue.shutdown` (along with :exc:`asyncio.QueueShutDown`) " -"for queue termination. (Contributed by Laurie Opperman and Yves Duprat in :" -"gh:`104228`.)" +"The function and methods named ``create_task`` have received a new " +"``**kwargs`` argument that is passed through to the task constructor. This " +"change was accidentally added in 3.13.3, and broke the API contract for " +"custom task factories. Several third-party task factories implemented " +"workarounds for this. In 3.13.4 and later releases the old factory contract " +"is honored once again (until 3.14). To keep the workarounds working, the " +"extra ``**kwargs`` argument still allows passing additional keyword " +"arguments to :class:`~asyncio.Task` and to custom task factories." msgstr "" -"Adiciona :meth:`asyncio.Queue.shutdown` (junto com :exc:`asyncio." -"QueueShutDown`) para encerramento da fila. (Contribuição de Laurie Opperman " -"e Yves Duprat em :gh:`104228`.)" -#: ../../whatsnew/3.13.rst:739 +#: ../../whatsnew/3.13.rst:753 msgid "" -"Accept a tuple of separators in :meth:`asyncio.StreamReader.readuntil`, " -"stopping when one of them is encountered. (Contributed by Bruce Merry in :gh:" -"`81322`.)" +"This affects the following function and methods: :meth:`asyncio." +"create_task`, :meth:`asyncio.loop.create_task`, :meth:`asyncio.TaskGroup." +"create_task`. (Contributed by Thomas Grainger in :gh:`128307`.)" msgstr "" -"Aceita uma tupla de separadores em :meth:`asyncio.StreamReader.readuntil`, " -"parando quando um deles for encontrado. (Contribuição de Bruce Merry em :gh:" -"`81322`.)" -#: ../../whatsnew/3.13.rst:744 +#: ../../whatsnew/3.13.rst:760 msgid "base64" msgstr "base64" -#: ../../whatsnew/3.13.rst:746 +#: ../../whatsnew/3.13.rst:762 msgid "" -"Add :func:`base64.z85encode` and :func:`base64.z85decode` functions which " -"allow encoding and decoding Z85 data. See the `Z85 specification `_ for more information. (Contributed by Matan " -"Perelman in :gh:`75299`.)" +"Add :func:`~base64.z85encode` and :func:`~base64.z85decode` functions for " +"encoding :class:`bytes` as `Z85 data`_ and decoding Z85-encoded data to :" +"class:`!bytes`. (Contributed by Matan Perelman in :gh:`75299`.)" msgstr "" -"Adiciona funções :func:`base64.z85encode` e :func:`base64.z85decode` que " -"permitem codificar e decodificar dados Z85. Consulte a `especificação Z85 " -"`_ para obter mais informações. " -"(Contribuição de Matan Perelman em :gh:`75299`.)" - -#: ../../whatsnew/3.13.rst:752 -msgid "copy" -msgstr "copy" +"Adiciona as funções :func:`~base64.z85encode` e :func:`~base64.z85decode` " +"para codificar :class:`bytes` como `dados Z85`_ e decodificar dados " +"codificados em Z85 para :class:`!bytes`. (Contribuição de Matan Perelman em :" +"gh:`75299`.)" -#: ../../whatsnew/3.13.rst:754 -msgid "" -"Add :func:`copy.replace` function which allows to create a modified copy of " -"an object, which is especially useful for immutable objects. It supports " -"named tuples created with the factory function :func:`collections." -"namedtuple`, :class:`~dataclasses.dataclass` instances, various :mod:" -"`datetime` objects, :class:`~inspect.Signature` objects, :class:`~inspect." -"Parameter` objects, :ref:`code object `, and any user classes " -"which define the :meth:`!__replace__` method. (Contributed by Serhiy " -"Storchaka in :gh:`108751`.)" -msgstr "" -"Adiciona a função :func:`copy.replace` que permite criar uma cópia " -"modificada de um objeto, o que é especialmente útil para objetos imutáveis. " -"Ele oferece suporte a tuplas nomeadas criadas com a função de fábrica :func:" -"`collections.namedtuple`, instâncias :class:`~dataclasses.dataclass`, vários " -"objetos :mod:`datetime`, objetos :class:`~inspect.Signature`, :class:" -"`~inspect.Parameter`, :ref:`objeto código `, e quaisquer " -"classes de usuário que definam o método :meth:`!__replace__`. (Contribuição " -"de Serhiy Storchaka em :gh:`108751`.)" - -#: ../../whatsnew/3.13.rst:764 -msgid "dbm" -msgstr "dbm" +#: ../../whatsnew/3.13.rst:771 +msgid "compileall" +msgstr "compileall" -#: ../../whatsnew/3.13.rst:766 +#: ../../whatsnew/3.13.rst:773 ../../whatsnew/3.13.rst:781 +#: ../../whatsnew/3.13.rst:1040 msgid "" -"Add :meth:`dbm.gnu.gdbm.clear` and :meth:`dbm.ndbm.ndbm.clear` methods that " -"remove all items from the database. (Contributed by Donghee Na in :gh:" -"`107122`.)" +"The default number of worker threads and processes is now selected using :" +"func:`os.process_cpu_count` instead of :func:`os.cpu_count`. (Contributed by " +"Victor Stinner in :gh:`109649`.)" msgstr "" -"Adiciona os métodos :meth:`dbm.gnu.gdbm.clear` e :meth:`dbm.ndbm.ndbm.clear` " -"que removem todos os itens do banco de dados. (Contribuição de Donghee Na " -"em :gh:`107122`.)" +"O número padrão de threads e processos de trabalho é agora selecionado " +"usando :func:`os.process_cpu_count` em vez de :func:`os.cpu_count`. " +"(Contribuição de Victor Stinner em :gh:`109649`.)" + +#: ../../whatsnew/3.13.rst:779 +msgid "concurrent.futures" +msgstr "concurrent.futures" + +#: ../../whatsnew/3.13.rst:787 ../../whatsnew/3.13.rst:1689 +msgid "configparser" +msgstr "configparser" -#: ../../whatsnew/3.13.rst:770 +#: ../../whatsnew/3.13.rst:789 msgid "" -"Add new :mod:`dbm.sqlite3` backend, and make it the default :mod:`!dbm` " -"backend. (Contributed by Raymond Hettinger and Erlend E. Aasland in :gh:" -"`100414`.)" +":class:`~configparser.ConfigParser` now has support for unnamed sections, " +"which allows for top-level key-value pairs. This can be enabled with the new " +"*allow_unnamed_section* parameter. (Contributed by Pedro Sousa Lacerda in :" +"gh:`66449`.)" msgstr "" -"Adiciona o novo backend :mod:`dbm.sqlite3` e torna-o o backend padrão :mod:`!" -"dbm`. (Contribuição de Raymond Hettinger e Erlend E. Aasland em :gh:" -"`100414`.)" +":class:`~configparser.ConfigParser` agora tem suporte para seções sem nome, " +"o que permite pares de chave-valor de nível superior. Isso pode ser " +"habilitado com o novo parâmetro *allow_unnamed_section*. (Contribuição de " +"Pedro Sousa Lacerda em :gh:`66449`.)" -#: ../../whatsnew/3.13.rst:774 -msgid "dis" -msgstr "dis" +#: ../../whatsnew/3.13.rst:796 +msgid "copy" +msgstr "copy" -#: ../../whatsnew/3.13.rst:776 +#: ../../whatsnew/3.13.rst:798 msgid "" -"Change the output of :mod:`dis` module functions to show logical labels for " -"jump targets and exception handlers, rather than offsets. The offsets can be " -"added with the new ``-O`` command line option or the ``show_offsets`` " -"parameter. (Contributed by Irit Katriel in :gh:`112137`.)" +"The new :func:`~copy.replace` function and the :meth:`replace protocol " +"` make creating modified copies of objects much simpler. " +"This is especially useful when working with immutable objects. The following " +"types support the :func:`~copy.replace` function and implement the replace " +"protocol:" msgstr "" -"Altera a saída das funções do módulo :mod:`dis` para mostrar rótulos lógicos " -"para alvos de salto e manipuladores de exceção, em vez de deslocamentos. Os " -"deslocamentos podem ser adicionados com a nova opção de linha de comando ``-" -"O`` ou o parâmetro ``show_offsets``. (Contribuição de Irit Katriel em :gh:" -"`112137`.)" +"A nova função :func:`~copy.replace` e o protocolo :meth:`replace ` tornam a criação de cópias modificadas de objetos muito mais " +"simples. Isso é especialmente útil ao trabalhar com objetos imutáveis. Os " +"seguintes tipos dão suporte à função :func:`~copy.replace` e implementam o " +"protocolo replace:" + +#: ../../whatsnew/3.13.rst:804 +msgid ":func:`collections.namedtuple`" +msgstr ":func:`collections.namedtuple`" -#: ../../whatsnew/3.13.rst:782 +#: ../../whatsnew/3.13.rst:805 +msgid ":class:`dataclasses.dataclass`" +msgstr ":class:`dataclasses.dataclass`" + +#: ../../whatsnew/3.13.rst:806 msgid "" -":meth:`~dis.get_instructions` no longer represents cache entries as separate " -"instructions. Instead, it returns them as part of the :class:`~dis." -"Instruction`, in the new *cache_info* field. The *show_caches* argument to :" -"meth:`~dis.get_instructions` is deprecated and no longer has any effect. " +":class:`datetime.datetime`, :class:`datetime.date`, :class:`datetime.time`" +msgstr "" +":class:`datetime.datetime`, :class:`datetime.date`, :class:`datetime.time`" + +#: ../../whatsnew/3.13.rst:807 +msgid ":class:`inspect.Signature`, :class:`inspect.Parameter`" +msgstr ":class:`inspect.Signature`, :class:`inspect.Parameter`" + +#: ../../whatsnew/3.13.rst:808 +msgid ":class:`types.SimpleNamespace`" +msgstr ":class:`types.SimpleNamespace`" + +#: ../../whatsnew/3.13.rst:809 +msgid ":ref:`code objects `" +msgstr ":ref:`objetos código `" + +#: ../../whatsnew/3.13.rst:811 +msgid "" +"Any user-defined class can also support :func:`copy.replace` by defining " +"the :meth:`~object.__replace__` method. (Contributed by Serhiy Storchaka in :" +"gh:`108751`.)" +msgstr "" +"Qualquer classe definida pelo usuário também pode ter suporte a :func:`copy." +"replace` definindo o método :meth:`~object.__replace__`. (Contribuição de " +"Serhiy Storchaka em :gh:`108751`.)" + +#: ../../whatsnew/3.13.rst:817 +msgid "ctypes" +msgstr "ctypes" + +#: ../../whatsnew/3.13.rst:819 +msgid "" +"As a consequence of necessary internal refactoring, initialization of " +"internal metaclasses now happens in ``__init__`` rather than in ``__new__``. " +"This affects projects that subclass these internal metaclasses to provide " +"custom initialization. Generally:" +msgstr "" +"Como consequência da refatoração interna necessária, a inicialização de " +"metaclasses internas agora acontece em ``__init__`` em vez de ``__new__``. " +"Isso afeta projetos que fazem subclasse dessas metaclasses internas para " +"fornecer inicialização personalizada. De forma geral:" + +#: ../../whatsnew/3.13.rst:825 +msgid "" +"Custom logic that was done in ``__new__`` after calling ``super().__new__`` " +"should be moved to ``__init__``." +msgstr "" +"A lógica personalizada que foi feita em ``__new__`` após chamar ``super()." +"__new__`` deve ser movida para ``__init__``." + +#: ../../whatsnew/3.13.rst:827 +msgid "" +"To create a class, call the metaclass, not only the metaclass's ``__new__`` " +"method." +msgstr "" +"Para criar uma classe, chame a metaclasse, não apenas o método ``__new__`` " +"da metaclasse." + +#: ../../whatsnew/3.13.rst:830 +msgid "" +"See :gh:`124520` for discussion and links to changes in some affected " +"projects." +msgstr "" +"Veja :gh:`124520` para discussão e links para mudanças em alguns projetos " +"afetados." + +#: ../../whatsnew/3.13.rst:833 +msgid "" +":class:`ctypes.Structure` objects have a new :attr:`~ctypes.Structure." +"_align_` attribute which allows the alignment of the structure being packed " +"to/from memory to be specified explicitly. (Contributed by Matt Sanderson " +"in :gh:`112433`)" +msgstr "" +"Os objetos :class:`ctypes.Structure` têm um novo atributo :attr:`~ctypes." +"Structure._align_` que permite que o alinhamento da estrutura que está sendo " +"empacotada para/da memória seja especificado explicitamente. (Contribuição " +"de Matt Sanderson em :gh:`112433`)" + +#: ../../whatsnew/3.13.rst:839 +msgid "dbm" +msgstr "dbm" + +#: ../../whatsnew/3.13.rst:841 +msgid "" +"Add :mod:`dbm.sqlite3`, a new module which implements an SQLite backend, and " +"make it the default :mod:`!dbm` backend. (Contributed by Raymond Hettinger " +"and Erlend E. Aasland in :gh:`100414`.)" +msgstr "" +"Adiciona :mod:`dbm.sqlite3`, um novo módulo que implementa um backend " +"SQLite, e torna-o o backend padrão :mod:`!dbm`. (Contribuição de Raymond " +"Hettinger e Erlend E. Aasland em :gh:`100414`.)" + +#: ../../whatsnew/3.13.rst:845 +msgid "" +"Allow removing all items from the database through the new :meth:`.gdbm." +"clear` and :meth:`.ndbm.clear` methods. (Contributed by Donghee Na in :gh:" +"`107122`.)" +msgstr "" +"Permite a remoção de todos os itens do banco de dados por meio dos novos " +"métodos :meth:`.gdbm.clear` e :meth:`.ndbm.clear`. (Contribuição de Donghee " +"Na em :gh:`107122`.)" + +#: ../../whatsnew/3.13.rst:851 +msgid "dis" +msgstr "dis" + +#: ../../whatsnew/3.13.rst:853 +msgid "" +"Change the output of :mod:`dis` module functions to show logical labels for " +"jump targets and exception handlers, rather than offsets. The offsets can be " +"added with the new :option:`-O ` command-line option or " +"the *show_offsets* argument. (Contributed by Irit Katriel in :gh:`112137`.)" +msgstr "" +"Altera a saída das funções do módulo :mod:`dis` para mostrar rótulos lógicos " +"para alvos de salto e manipuladores de exceção, em vez de deslocamentos. Os " +"deslocamentos podem ser adicionados com a nova opção de linha de comando :" +"option:`-O ` ou o argumento *show_offsets*. " +"(Contribuição de Irit Katriel em :gh:`112137`.)" + +#: ../../whatsnew/3.13.rst:860 +msgid "" +":meth:`~dis.get_instructions` no longer represents cache entries as separate " +"instructions. Instead, it returns them as part of the :class:`~dis." +"Instruction`, in the new *cache_info* field. The *show_caches* argument to :" +"meth:`~dis.get_instructions` is deprecated and no longer has any effect. " "(Contributed by Irit Katriel in :gh:`112962`.)" msgstr "" ":meth:`~dis.get_instructions` não representa mais entradas de cache como " @@ -1610,293 +1798,241 @@ msgstr "" "para :meth:`~dis.get_instructions` foi descontinuado e não tem mais nenhum " "efeito. (Contribuição de Irit Katriel em :gh:`112962`.)" -#: ../../whatsnew/3.13.rst:792 +#: ../../whatsnew/3.13.rst:872 msgid "doctest" msgstr "doctest" -#: ../../whatsnew/3.13.rst:794 +#: ../../whatsnew/3.13.rst:874 msgid "" -"Color is added to the output by default. This can be controlled via the new :" -"envvar:`PYTHON_COLORS` environment variable as well as the canonical |" -"NO_COLOR|_ and |FORCE_COLOR|_ environment variables. See also :ref:`using-on-" -"controlling-color`. (Contributed by Hugo van Kemenade in :gh:`117225`.)" +":mod:`doctest` output is now colored by default. This can be controlled via " +"the new :envvar:`PYTHON_COLORS` environment variable as well as the " +"canonical |NO_COLOR|_ and |FORCE_COLOR|_ environment variables. See also :" +"ref:`using-on-controlling-color`. (Contributed by Hugo van Kemenade in :gh:" +"`117225`.)" msgstr "" -"A cor é adicionada à saída por padrão. Isso pode ser controlado através da " -"nova variável de ambiente :envvar:`PYTHON_COLORS`, bem como das variáveis ​​de " -"ambiente canônicas |NO_COLOR|_ e |FORCE_COLOR|_. Veja também :ref:`using-on-" -"controlling-color`. (Contribuição de Hugo van Kemenade em :gh:`117225`.)" +"A saída do :mod:`doctest` é agora colorida por padrão. Isso pode ser " +"controlado através da nova variável de ambiente :envvar:`PYTHON_COLORS`, bem " +"como das variáveis de ambiente canônicas |NO_COLOR|_ e |FORCE_COLOR|_. Veja " +"também :ref:`using-on-controlling-color`. (Contribuição de Hugo van Kemenade " +"em :gh:`117225`.)" -#: ../../whatsnew/3.13.rst:800 +#: ../../whatsnew/3.13.rst:881 msgid "" -"The :meth:`doctest.DocTestRunner.run` method now counts the number of " -"skipped tests. Add :attr:`doctest.DocTestRunner.skips` and :attr:`doctest." -"TestResults.skipped` attributes. (Contributed by Victor Stinner in :gh:" -"`108794`.)" +"The :meth:`.DocTestRunner.run` method now counts the number of skipped " +"tests. Add the :attr:`.DocTestRunner.skips` and :attr:`.TestResults.skipped` " +"attributes. (Contributed by Victor Stinner in :gh:`108794`.)" msgstr "" -"O método :meth:`doctest.DocTestRunner.run` agora conta o número de testes " -"ignorados. Adiciona os atributos :attr:`doctest.DocTestRunner.skips` e :attr:" -"`doctest.TestResults.skipped`. (Contribuição de Victor Stinner em :gh:" -"`108794`.)" +"O método :meth:`.DocTestRunner.run` agora conta o número de testes " +"ignorados. Adiciona os atributos :attr:`.DocTestRunner.skips` e :attr:`." +"TestResults.skipped`. (Contribuição de Victor Stinner em :gh:`108794`.)" -#: ../../whatsnew/3.13.rst:806 +#: ../../whatsnew/3.13.rst:887 msgid "email" msgstr "email" -#: ../../whatsnew/3.13.rst:808 -msgid "Headers with embedded newlines are now quoted on output." -msgstr "" -"Cabeçalhos com novas linhas embutidas agora são colocados entre aspas na " -"saída." - -#: ../../whatsnew/3.13.rst:810 +#: ../../whatsnew/3.13.rst:889 msgid "" -"The :mod:`~email.generator` will now refuse to serialize (write) headers " -"that are improperly folded or delimited, such that they would be parsed as " -"multiple headers or joined with adjacent data. If you need to turn this " -"safety feature off, set :attr:`~email.policy.Policy." -"verify_generated_headers`. (Contributed by Bas Bloemsaat and Petr Viktorin " -"in :gh:`121650`.)" +"Headers with embedded newlines are now quoted on output. The :mod:`~email." +"generator` will now refuse to serialize (write) headers that are improperly " +"folded or delimited, such that they would be parsed as multiple headers or " +"joined with adjacent data. If you need to turn this safety feature off, set :" +"attr:`~email.policy.Policy.verify_generated_headers`. (Contributed by Bas " +"Bloemsaat and Petr Viktorin in :gh:`121650`.)" msgstr "" -"O :mod:`~email.generator` agora se recusará a serializar (escrever) " -"cabeçalhos que são dobrados ou delimitados incorretamente, de modo que eles " -"seriam analisados ​​como vários cabeçalhos ou unidos a dados adjacentes. Se " -"você precisar desativar esse recurso de segurança, defina :attr:`~email." +"Cabeçalhos com novas linhas embutidas são agora colocadas entre aspas na " +"saída. O :mod:`~email.generator` agora se recusará a serializar (escrever) " +"cabeçalhos que estão dobrados ou delimitados incorretamente, de modo que " +"eles seriam analisados como vários cabeçalhos ou unidos a dados adjacentes. " +"Se você precisar desativar esse recurso de segurança, defina :attr:`~email." "policy.Policy.verify_generated_headers`. (Contribuição de Bas Bloemsaat e " "Petr Viktorin em :gh:`121650`.)" -#: ../../whatsnew/3.13.rst:817 -msgid "" -":func:`email.utils.getaddresses` and :func:`email.utils.parseaddr` now " -"return ``('', '')`` 2-tuples in more situations where invalid email " -"addresses are encountered instead of potentially inaccurate values. Add " -"optional *strict* parameter to these two functions: use ``strict=False`` to " -"get the old behavior, accept malformed inputs. ``getattr(email.utils, " -"'supports_strict_parsing', False)`` can be used to check if the *strict* " -"parameter is available. (Contributed by Thomas Dwyer and Victor Stinner for :" -"gh:`102988` to improve the :cve:`2023-27043` fix.)" -msgstr "" -":func:`email.utils.getaddresses` e :func:`email.utils.parseaddr` agora " -"retornam tuplas de dois elementos ``('', '')`` em mais situações onde " -"endereços de e-mail inválidos são encontrados em vez de potencialmente " -"imprecisos valores. Adiciona o parâmetro *strict* opcional a estas duas " -"funções: use ``strict=False`` para obter o comportamento antigo, aceitar " -"entradas malformadas. ``getattr(email.utils, 'supports_strict_parsing', " -"False)`` pode ser usado para verificar se o parâmetro *strict* está " -"disponível. (Contribuição de Thomas Dwyer e Victor Stinner para :gh:`102988` " -"para melhorar a correção :cve:`2023-27043`.)" - -#: ../../whatsnew/3.13.rst:828 -msgid "fractions" -msgstr "fractions" - -#: ../../whatsnew/3.13.rst:830 +#: ../../whatsnew/3.13.rst:897 msgid "" -"Formatting for objects of type :class:`fractions.Fraction` now supports the " -"standard format specification mini-language rules for fill, alignment, sign " -"handling, minimum width and grouping. (Contributed by Mark Dickinson in :gh:" -"`111320`.)" +":func:`~email.utils.getaddresses` and :func:`~email.utils.parseaddr` now " +"return ``('', '')`` pairs in more situations where invalid email addresses " +"are encountered instead of potentially inaccurate values. The two functions " +"have a new optional *strict* parameter (default ``True``). To get the old " +"behavior (accepting malformed input), use ``strict=False``. ``getattr(email." +"utils, 'supports_strict_parsing', False)`` can be used to check if the " +"*strict* parameter is available. (Contributed by Thomas Dwyer and Victor " +"Stinner for :gh:`102988` to improve the :cve:`2023-27043` fix.)" msgstr "" -"A formatação para objetos do tipo :class:`fractions.Fraction` agora oferece " -"suporte às regras de minilinguagem de especificação de formato padrão para " -"preenchimento, alinhamento, manipulação de sinais, largura mínima e " -"agrupamento. (Contribuição de Mark Dickinson em :gh:`111320`.)" +":func:`~email.utils.getaddresses` e :func:`~email.utils.parseaddr` agora " +"retornam pares ``('', '')`` em mais situações onde endereços de e-mail " +"inválidos são encontrados em vez de valores potencialmente imprecisos. As " +"duas funções têm agora um novo parâmetro opcional *strict* (padrão " +"``True``). Para obter o comportamento antigo (aceitar entrada malformada), " +"``strict=False``. ``getattr(email.utils, 'supports_strict_parsing', False)`` " +"pode ser usado para verificar se o parâmetro *strict* está disponível. " +"(Contribuição de Thomas Dwyer e Victor Stinner para :gh:`102988` para " +"melhorar a correção :cve:`2023-27043`.)" -#: ../../whatsnew/3.13.rst:836 -msgid "gc" -msgstr "gc" +#: ../../whatsnew/3.13.rst:909 +msgid "enum" +msgstr "enum" -#: ../../whatsnew/3.13.rst:838 +#: ../../whatsnew/3.13.rst:911 msgid "" -"The cyclic garbage collector is now incremental, which changes the meanings " -"of the results of :meth:`gc.get_threshold` and :meth:`gc.set_threshold` as " -"well as :meth:`gc.get_count` and :meth:`gc.get_stats`." +":class:`~enum.EnumDict` has been made public to better support subclassing :" +"class:`~enum.EnumType`." msgstr "" -"O coletor de lixo cíclico agora é incremental, o que altera o significado " -"dos resultados de :meth:`gc.get_threshold` e :meth:`gc.set_threshold`, bem " -"como de :meth:`gc.get_count` e :meth:`gc.get_stats`." - -#: ../../whatsnew/3.13.rst:842 -msgid "" -":meth:`gc.get_threshold` returns a three-item tuple for backwards " -"compatibility. The first value is the threshold for young collections, as " -"before; the second value determines the rate at which the old collection is " -"scanned (the default is 10, and higher values mean that the old collection " -"is scanned more slowly). The third value is meaningless and is always zero." -msgstr "" -":meth:`gc.get_threshold` retorna uma tupla de três itens para " -"compatibilidade com versões anteriores. O primeiro valor é o limite para " -"coleções jovens, como antes; o segundo valor determina a taxa na qual a " -"coleção antiga é verificada (o padrão é 10 e valores mais altos significam " -"que a coleção antiga é verificada mais lentamente). O terceiro valor não tem " -"sentido e é sempre zero." - -#: ../../whatsnew/3.13.rst:847 -msgid ":meth:`gc.set_threshold` ignores any items after the second." -msgstr ":meth:`gc.set_threshold` ignora quaisquer itens após o segundo." +":class:`~enum.EnumDict` foi tornada pública para melhor suporte às " +"subclasses de :class:`~enum.EnumType`." -#: ../../whatsnew/3.13.rst:848 -msgid "" -":meth:`gc.get_count` and :meth:`gc.get_stats` return the same format of " -"results as before. The only difference is that instead of the results " -"referring to the young, aging and old generations, the results refer to the " -"young generation and the aging and collecting spaces of the old generation." -msgstr "" -":meth:`gc.get_count` e :meth:`gc.get_stats` retornam o mesmo formato de " -"resultados de antes. A única diferença é que em vez dos resultados fazerem " -"referência às gerações jovens, em envelhecimento e antigas, os resultados " -"fazem referência à geração jovem e em envelhecimento, e coleta de espaços de " -"geração antigas." +#: ../../whatsnew/3.13.rst:916 +msgid "fractions" +msgstr "fractions" -#: ../../whatsnew/3.13.rst:854 +#: ../../whatsnew/3.13.rst:918 msgid "" -"In summary, code that attempted to manipulate the behavior of the cycle GC " -"may not work exactly as intended, but it is very unlikely to be harmful. All " -"other code will work just fine." +":class:`~fractions.Fraction` objects now support the standard :ref:`format " +"specification mini-language ` rules for fill, alignment, sign " +"handling, minimum width, and grouping. (Contributed by Mark Dickinson in :gh:" +"`111320`.)" msgstr "" -"Em resumo, o código que tentou manipular o comportamento do ciclo GC pode " -"não funcionar exatamente como pretendido, mas é muito improvável que seja " -"prejudicial. Todos os outros códigos funcionarão perfeitamente." +"Os objetos :class:`~fractions.Fraction` agora oferecem suporte às regras " +"padrões da :ref:`minilinguagem de especificação de formato ` " +"para preenchimento, alinhamento, manipulação de sinais, largura mínima e " +"agrupamento. (Contribuição de Mark Dickinson em :gh:`111320`.)" -#: ../../whatsnew/3.13.rst:859 +#: ../../whatsnew/3.13.rst:925 msgid "glob" msgstr "glob" -#: ../../whatsnew/3.13.rst:861 +#: ../../whatsnew/3.13.rst:927 msgid "" -"Add :func:`glob.translate` function that converts a path specification with " +"Add :func:`~glob.translate`, a function to convert a path specification with " "shell-style wildcards to a regular expression. (Contributed by Barney Gale " "in :gh:`72904`.)" msgstr "" -"Adiciona a função :func:`glob.translate` que converte uma especificação de " -"caminho com curingas estilo shell em uma expressão regular. (Contribuição de " -"Barney Gale em :gh:`72904`.)" +"Adiciona :func:`~glob.translate`, uma função que converte uma especificação " +"de caminho com curingas estilo shell em uma expressão regular. (Contribuição " +"de Barney Gale em :gh:`72904`.)" -#: ../../whatsnew/3.13.rst:866 ../../whatsnew/3.13.rst:1456 +#: ../../whatsnew/3.13.rst:933 msgid "importlib" msgstr "importlib" -#: ../../whatsnew/3.13.rst:868 +#: ../../whatsnew/3.13.rst:935 msgid "" -"Previously deprecated :mod:`importlib.resources` functions are un-deprecated:" +"The following functions in :mod:`importlib.resources` now allow accessing a " +"directory (or tree) of resources, using multiple positional arguments (the " +"*encoding* and *errors* arguments in the text-reading functions are now " +"keyword-only):" msgstr "" -"As funções :mod:`importlib.resources` anteriormente descontinuado não estão " -"mais descontinuadas:" - -#: ../../whatsnew/3.13.rst:870 -msgid ":func:`~importlib.resources.is_resource()`" -msgstr ":func:`~importlib.resources.is_resource()`" +"As seguintes funções em :mod:`importlib.resources` agora permitem acessar um " +"diretório (ou árvore) de recursos, usando múltiplos argumentos posicionais " +"(os argumentos *encoding* e *errors* nas funções de leitura de texto agora " +"são somente-nomeados):" -#: ../../whatsnew/3.13.rst:871 -msgid ":func:`~importlib.resources.open_binary()`" -msgstr ":func:`~importlib.resources.open_binary()`" +#: ../../whatsnew/3.13.rst:940 +msgid ":func:`~importlib.resources.is_resource`" +msgstr ":func:`~importlib.resources.is_resource`" -#: ../../whatsnew/3.13.rst:872 -msgid ":func:`~importlib.resources.open_text()`" -msgstr ":func:`~importlib.resources.open_text()`" +#: ../../whatsnew/3.13.rst:941 +msgid ":func:`~importlib.resources.open_binary`" +msgstr ":func:`~importlib.resources.open_binary`" -#: ../../whatsnew/3.13.rst:873 -msgid ":func:`~importlib.resources.path()`" -msgstr ":func:`~importlib.resources.path()`" +#: ../../whatsnew/3.13.rst:942 +msgid ":func:`~importlib.resources.open_text`" +msgstr ":func:`~importlib.resources.open_text`" -#: ../../whatsnew/3.13.rst:874 -msgid ":func:`~importlib.resources.read_binary()`" -msgstr ":func:`~importlib.resources.read_binary()`" +#: ../../whatsnew/3.13.rst:943 +msgid ":func:`~importlib.resources.path`" +msgstr ":func:`~importlib.resources.path`" -#: ../../whatsnew/3.13.rst:875 -msgid ":func:`~importlib.resources.read_text()`" -msgstr ":func:`~importlib.resources.read_text()`" +#: ../../whatsnew/3.13.rst:944 +msgid ":func:`~importlib.resources.read_binary`" +msgstr ":func:`~importlib.resources.read_binary`" -#: ../../whatsnew/3.13.rst:877 -msgid "" -"All now allow for a directory (or tree) of resources, using multiple " -"positional arguments." -msgstr "" -"Todos agora permitem um diretório (ou árvore) de recursos, usando múltiplos " -"argumentos posicionais." +#: ../../whatsnew/3.13.rst:945 +msgid ":func:`~importlib.resources.read_text`" +msgstr ":func:`~importlib.resources.read_text`" -#: ../../whatsnew/3.13.rst:880 +#: ../../whatsnew/3.13.rst:947 msgid "" -"For text-reading functions, the *encoding* and *errors* must now be given as " -"keyword arguments." +"These functions are no longer deprecated and are not scheduled for removal. " +"(Contributed by Petr Viktorin in :gh:`116608`.)" msgstr "" -"Para funções de leitura de texto, *encoding* e *errors* devem agora ser " -"fornecidos como argumentos nomeados." +"Essas funções não estão mais descontinuadas e não estão programadas para " +"remoção. (Contribuição de Petr Viktorin em :gh:`116608`.)" -#: ../../whatsnew/3.13.rst:883 +#: ../../whatsnew/3.13.rst:950 msgid "" -"The :func:`~importlib.resources.contents()` remains deprecated in favor of " -"the full-featured :class:`~importlib.resources.abc.Traversable` API. " -"However, there is now no plan to remove it." +":func:`~importlib.resources.contents` remains deprecated in favor of the " +"fully-featured :class:`~importlib.resources.abc.Traversable` API. However, " +"there is now no plan to remove it. (Contributed by Petr Viktorin in :gh:" +"`116608`.)" msgstr "" -"A :func:`~importlib.resources.contents()` permanece descontinuada em favor " -"da API completa :class:`~importlib.resources.abc.Traversable`. No entanto, " -"agora não há planos para removê-la." - -#: ../../whatsnew/3.13.rst:887 -msgid "(Contributed by Petr Viktorin in :gh:`106532`.)" -msgstr "(Contribuição de Petr Viktorin em :gh:`106532`.)" +"A função :func:`~importlib.resources.contents` permanece descontinuada em " +"favor da API completa :class:`~importlib.resources.abc.Traversable`. No " +"entanto, agora não há planos para removê-la. (Contribuição de Petr Viktorin " +"em :gh:`116608`.)" -#: ../../whatsnew/3.13.rst:890 +#: ../../whatsnew/3.13.rst:957 msgid "io" msgstr "io" -#: ../../whatsnew/3.13.rst:892 +#: ../../whatsnew/3.13.rst:959 msgid "" -"The :class:`io.IOBase` finalizer now logs the ``close()`` method errors " -"with :data:`sys.unraisablehook`. Previously, errors were ignored silently by " -"default, and only logged in :ref:`Python Development Mode ` or on :" -"ref:`Python built on debug mode `. (Contributed by Victor " -"Stinner in :gh:`62948`.)" +"The :class:`~io.IOBase` finalizer now logs any errors raised by the :meth:" +"`~io.IOBase.close` method with :data:`sys.unraisablehook`. Previously, " +"errors were ignored silently by default, and only logged in :ref:`Python " +"Development Mode ` or when using a :ref:`Python debug build `. (Contributed by Victor Stinner in :gh:`62948`.)" msgstr "" -"O finalizador :class:`io.IOBase` agora registra os erros do método " -"``close()`` com :data:`sys.unraisablehook`. Anteriormente, os erros eram " -"ignorados silenciosamente por padrão e registrados apenas em :ref:`Modo de " -"Desenvolvimento do Python ` ou em :ref:`Python construído em modo " -"de depuração `. (Contribuição de Victor Stinner em :gh:`62948`.)" +"O finalizador :class:`~io.IOBase` agora registra quaisquer erros levantados " +"pelo método :meth:`~io.IOBase.close` com :data:`sys.unraisablehook`. " +"Anteriormente, os erros eram ignorados silenciosamente por padrão e " +"registrados apenas em :ref:`Modo de Desenvolvimento do Python ` ou " +"ao usar uma :ref:`construção de depuração do Python `. " +"(Contribuição de Victor Stinner em :gh:`62948`.)" -#: ../../whatsnew/3.13.rst:899 +#: ../../whatsnew/3.13.rst:968 msgid "ipaddress" msgstr "ipaddress" -#: ../../whatsnew/3.13.rst:901 +#: ../../whatsnew/3.13.rst:970 msgid "" -"Add the :attr:`ipaddress.IPv4Address.ipv6_mapped` property, which returns " -"the IPv4-mapped IPv6 address. (Contributed by Charles Machalow in :gh:" -"`109466`.)" +"Add the :attr:`.IPv4Address.ipv6_mapped` property, which returns the IPv4-" +"mapped IPv6 address. (Contributed by Charles Machalow in :gh:`109466`.)" msgstr "" -"Adiciona a propriedade :attr:`ipaddress.IPv4Address.ipv6_mapped`, que " -"retorna o endereço IPv6 mapeado para IPv4. (Contribuição de Charles Machalow " -"em :gh:`109466`.)" +"Adiciona a propriedade :attr:`.IPv4Address.ipv6_mapped`, que retorna o " +"endereço IPv6 mapeado para IPv4. (Contribuição de Charles Machalow em :gh:" +"`109466`.)" -#: ../../whatsnew/3.13.rst:903 +#: ../../whatsnew/3.13.rst:974 msgid "" "Fix ``is_global`` and ``is_private`` behavior in :class:`~ipaddress." "IPv4Address`, :class:`~ipaddress.IPv6Address`, :class:`~ipaddress." -"IPv4Network` and :class:`~ipaddress.IPv6Network`." +"IPv4Network`, and :class:`~ipaddress.IPv6Network`. (Contributed by Jakub " +"Stasiak in :gh:`113171`.)" msgstr "" -"Corrige os comportamentos ``is_global`` e ``is_private`` em :class:" +"Corrige os comportamentos de ``is_global`` e ``is_private`` em :class:" "`~ipaddress.IPv4Address`, :class:`~ipaddress.IPv6Address`, :class:" -"`~ipaddress.IPv4Network` e :class:`~ipaddress.IPv6Network`." +"`~ipaddress.IPv4Network` e :class:`~ipaddress.IPv6Network`. (Contribuição de " +"Jakub Stasiak em :gh:`113171`.)" -#: ../../whatsnew/3.13.rst:910 +#: ../../whatsnew/3.13.rst:981 msgid "itertools" msgstr "itertools" -#: ../../whatsnew/3.13.rst:912 +#: ../../whatsnew/3.13.rst:983 msgid "" -"Added a ``strict`` option to :func:`itertools.batched`. This raises a :exc:" +":func:`~itertools.batched` has a new *strict* parameter, which raises a :exc:" "`ValueError` if the final batch is shorter than the specified batch size. " "(Contributed by Raymond Hettinger in :gh:`113202`.)" msgstr "" -"Adicionada uma opção ``strict`` a :func:`itertools.batched`. Isso levanta :" +":func:`~itertools.batched` tem um novo parâmetro *strict*, que levanta uma :" "exc:`ValueError` se o lote final for menor que o tamanho do lote " "especificado. (Contribuição de Raymond Hettinger em :gh:`113202`.)" -#: ../../whatsnew/3.13.rst:918 +#: ../../whatsnew/3.13.rst:990 msgid "marshal" msgstr "marshal" -#: ../../whatsnew/3.13.rst:920 +#: ../../whatsnew/3.13.rst:992 msgid "" "Add the *allow_code* parameter in module functions. Passing " "``allow_code=False`` prevents serialization and de-serialization of code " @@ -1908,391 +2044,376 @@ msgstr "" "código que são incompatíveis entre versões do Python. (Contribuição de " "Serhiy Storchaka em :gh:`113626`.)" -#: ../../whatsnew/3.13.rst:926 +#: ../../whatsnew/3.13.rst:999 msgid "math" msgstr "math" -#: ../../whatsnew/3.13.rst:928 +#: ../../whatsnew/3.13.rst:1001 msgid "" -"A new function :func:`~math.fma` for fused multiply-add operations has been " -"added. This function computes ``x * y + z`` with only a single round, and so " -"avoids any intermediate loss of precision. It wraps the ``fma()`` function " -"provided by C99, and follows the specification of the IEEE 754 " -"\"fusedMultiplyAdd\" operation for special cases. (Contributed by Mark " -"Dickinson and Victor Stinner in :gh:`73468`.)" +"The new function :func:`~math.fma` performs fused multiply-add operations. " +"This computes ``x * y + z`` with only a single round, and so avoids any " +"intermediate loss of precision. It wraps the ``fma()`` function provided by " +"C99, and follows the specification of the IEEE 754 \"fusedMultiplyAdd\" " +"operation for special cases. (Contributed by Mark Dickinson and Victor " +"Stinner in :gh:`73468`.)" msgstr "" -"Uma nova função :func:`~math.fma` para operações fundidas de multiplicação e " -"adição foi adicionada. Esta função calcula ``x * y + z`` com apenas uma " -"única rodada e, portanto, evita qualquer perda intermediária de precisão. " -"Ele envolve a função ``fma()`` fornecida pelo C99 e segue a especificação da " -"operação IEEE 754 \"fusedMultiplyAdd\" para casos especiais. (Contribuição " -"de Mark Dickinson e Victor Stinner em :gh:`73468`.)" +"A nova função :func:`~math.fma` realiza operações fundidas de multiplicação " +"e adição. Ela calcula ``x * y + z`` com apenas uma única rodada e, portanto, " +"evita qualquer perda intermediária de precisão. Ele envolve a função " +"``fma()`` fornecida pelo C99 e segue a especificação da operação IEEE 754 " +"\"fusedMultiplyAdd\" para casos especiais. (Contribuição de Mark Dickinson e " +"Victor Stinner em :gh:`73468`.)" -#: ../../whatsnew/3.13.rst:936 +#: ../../whatsnew/3.13.rst:1011 msgid "mimetypes" msgstr "mimetypes" -#: ../../whatsnew/3.13.rst:938 +#: ../../whatsnew/3.13.rst:1013 msgid "" -"Add the :func:`~mimetypes.guess_file_type` function which works with file " -"path. Passing file path instead of URL in :func:`~mimetypes.guess_type` is :" -"term:`soft deprecated`. (Contributed by Serhiy Storchaka in :gh:`66543`.)" +"Add the :func:`~mimetypes.guess_file_type` function to guess a MIME type " +"from a filesystem path. Using paths with :func:`~mimetypes.guess_type` is " +"now :term:`soft deprecated`. (Contributed by Serhiy Storchaka in :gh:" +"`66543`.)" msgstr "" -"Adiciona a função :func:`~mimetypes.guess_file_type` que funciona com o " -"caminho do arquivo. Passar o caminho do arquivo em vez da URL em :func:" -"`~mimetypes.guess_type` está :term:`suavemente descontinuado`. (Contribuição " -"de Serhiy Storchaka em :gh:`66543`.)" +"Adiciona a função :func:`~mimetypes.guess_file_type` para adivinhar um tipo " +"MIME de um caminho do sistema de arquivos. Usar caminhos com :func:" +"`~mimetypes.guess_type` agora está :term:`suavemente descontinuada " +"`. (Contribuição de Serhiy Storchaka em :gh:" +"`66543`.)" -#: ../../whatsnew/3.13.rst:943 +#: ../../whatsnew/3.13.rst:1020 msgid "mmap" msgstr "mmap" -#: ../../whatsnew/3.13.rst:945 -msgid "" -"The :class:`mmap.mmap` class now has an :meth:`~mmap.mmap.seekable` method " -"that can be used when a seekable file-like object is required. The :meth:" -"`~mmap.mmap.seek` method now returns the new absolute position. (Contributed " -"by Donghee Na and Sylvie Liberman in :gh:`111835`.)" -msgstr "" -"A classe :class:`mmap.mmap` agora tem um método :meth:`~mmap.mmap.seekable` " -"que pode ser usado quando um objeto pesquisável arquivo ou similar é " -"necessário. O método :meth:`~mmap.mmap.seek` agora retorna a nova posição " -"absoluta. (Contribuição de Donghee Na e Sylvie Liberman em :gh:`111835`.)" - -#: ../../whatsnew/3.13.rst:949 +#: ../../whatsnew/3.13.rst:1022 msgid "" -":class:`mmap.mmap` now has a *trackfd* parameter on Unix; if it is " -"``False``, the file descriptor specified by *fileno* will not be duplicated. " -"(Contributed by Zackery Spytz and Petr Viktorin in :gh:`78502`.)" +":class:`~mmap.mmap` is now protected from crashing on Windows when the " +"mapped memory is inaccessible due to file system errors or access " +"violations. (Contributed by Jannis Weigend in :gh:`118209`.)" msgstr "" -":class:`mmap.mmap` agora tem um parâmetro *trackfd* no Unix; se for " -"``False``, o descritor de arquivo especificado por *fileno* não será " -"duplicado. (Contribuição de Zackery Spytz e Petr Viktorin em :gh:`78502`.)" +":class:`~mmap.mmap` agora está protegida contra travamentos no Windows " +"quando a memória mapeada está inacessível devido a erros no sistema de " +"arquivos ou violações de acesso. (Contribuição de Jannis Weigend em :gh:" +"`118209`.)" -#: ../../whatsnew/3.13.rst:952 +#: ../../whatsnew/3.13.rst:1026 msgid "" -":class:`mmap.mmap` is now protected from crashing on Windows when the mapped " -"memory is inaccessible due to file system errors or access violations. " -"(Contributed by Jannis Weigend in :gh:`118209`.)" +":class:`~mmap.mmap` has a new :meth:`~mmap.mmap.seekable` method that can be " +"used when a seekable file-like object is required. The :meth:`~mmap.mmap." +"seek` method now returns the new absolute position. (Contributed by Donghee " +"Na and Sylvie Liberman in :gh:`111835`.)" msgstr "" -":class:`mmap.mmap` agora está protegido contra travamentos no Windows quando " -"a memória mapeada está inacessível devido a erros no sistema de arquivos ou " -"violações de acesso. (Contribuição de Jannis Weigend em :gh:`118209`.)" - -#: ../../whatsnew/3.13.rst:957 -msgid "opcode" -msgstr "opcode" +":class:`~mmap.mmap` tem um novo método :meth:`~mmap.mmap.seekable` que pode " +"ser usado quando um objeto arquivo ou similar pesquisável é necessário. O " +"método :meth:`~mmap.mmap.seek` agora retorna a nova posição absoluta. " +"(Contribuição de Donghee Na e Sylvie Liberman em :gh:`111835`.)" -#: ../../whatsnew/3.13.rst:959 +#: ../../whatsnew/3.13.rst:1031 msgid "" -"Move ``opcode.ENABLE_SPECIALIZATION`` to ``_opcode.ENABLE_SPECIALIZATION``. " -"This field was added in 3.12, it was never documented and is not intended " -"for external usage. (Contributed by Irit Katriel in :gh:`105481`.)" +"The new UNIX-only *trackfd* parameter for :class:`~mmap.mmap` controls file " +"descriptor duplication; if false, the file descriptor specified by *fileno* " +"will not be duplicated. (Contributed by Zackery Spytz and Petr Viktorin in :" +"gh:`78502`.)" msgstr "" -"Move ``opcode.ENABLE_SPECIALIZATION`` para ``_opcode." -"ENABLE_SPECIALIZATION``. Este campo foi adicionado na versão 3.12, nunca foi " -"documentado e não se destina ao uso externo. (Contribuição de Irit Katriel " -"em :gh:`105481`.)" +"O novo parâmetro *trackfd* somente para UNIX para :class:`~mmap.mmap` " +"controla a duplicação do descritor de arquivo; se falso, o descritor de " +"arquivo especificado por *fileno* não será duplicado. (Contribuição de " +"Zackery Spytz e Petr Viktorin em :gh:`78502`.)" -#: ../../whatsnew/3.13.rst:963 -msgid "" -"Removed ``opcode.is_pseudo``, ``opcode.MIN_PSEUDO_OPCODE`` and ``opcode." -"MAX_PSEUDO_OPCODE``, which were added in 3.12, were never documented or " -"exposed through ``dis``, and were not intended to be used externally." -msgstr "" -"Removidos ``opcode.is_pseudo``, ``opcode.MIN_PSEUDO_OPCODE`` e ``opcode." -"MAX_PSEUDO_OPCODE``, que foram adicionados em 3.12, nunca foram documentados " -"ou expostos através de ``dis``, e não foram planejados para serem usados " -"externamente." +#: ../../whatsnew/3.13.rst:1038 +msgid "multiprocessing" +msgstr "multiprocessing" -#: ../../whatsnew/3.13.rst:969 +#: ../../whatsnew/3.13.rst:1046 msgid "os" msgstr "os" -#: ../../whatsnew/3.13.rst:971 -msgid "" -"Add :func:`os.process_cpu_count` function to get the number of logical CPUs " -"usable by the calling thread of the current process. (Contributed by Victor " -"Stinner in :gh:`109649`.)" -msgstr "" -"Adiciona a função :func:`os.process_cpu_count` para obter o número de CPUs " -"lógicas utilizáveis ​​pelo thread de chamada do processo atual. (Contribuição " -"de Victor Stinner em :gh:`109649`.)" - -#: ../../whatsnew/3.13.rst:975 +#: ../../whatsnew/3.13.rst:1048 msgid "" -"Add a low level interface for Linux's timer notification file descriptors " -"via :func:`os.timerfd_create`, :func:`os.timerfd_settime`, :func:`os." -"timerfd_settime_ns`, :func:`os.timerfd_gettime`, and :func:`os." -"timerfd_gettime_ns`, :const:`os.TFD_NONBLOCK`, :const:`os.TFD_CLOEXEC`, :" -"const:`os.TFD_TIMER_ABSTIME`, and :const:`os.TFD_TIMER_CANCEL_ON_SET` " -"(Contributed by Masaru Tsuchiyama in :gh:`108277`.)" +"Add :func:`~os.process_cpu_count` function to get the number of logical CPU " +"cores usable by the calling thread of the current process. (Contributed by " +"Victor Stinner in :gh:`109649`.)" msgstr "" -"Adiciona uma interface de baixo nível para descritores de arquivo de " -"notificação de temporizador do Linux via :func:`os.timerfd_create`, :func:" -"`os.timerfd_settime`, :func:`os.timerfd_settime_ns`, :func:`os." -"timerfd_gettime` e :func:`os.timerfd_gettime_ns`, :const:`os.TFD_NONBLOCK`, :" -"const:`os.TFD_CLOEXEC`, :const:`os.TFD_TIMER_ABSTIME` e :const:`os." -"TFD_TIMER_CANCEL_ON_SET` (Contribuição de Masaru Tsuchiyama em :gh:`108277`.)" +"Adiciona a função :func:`~os.process_cpu_count` para obter o número de " +"núcleos lógicos de CPU utilizáveis pela thread de chamada do processo atual. " +"(Contribuição de Victor Stinner em :gh:`109649`.)" -#: ../../whatsnew/3.13.rst:983 +#: ../../whatsnew/3.13.rst:1052 msgid "" -":func:`os.cpu_count` and :func:`os.process_cpu_count` can be overridden " +":func:`~os.cpu_count` and :func:`~os.process_cpu_count` can be overridden " "through the new environment variable :envvar:`PYTHON_CPU_COUNT` or the new " "command-line option :option:`-X cpu_count <-X>`. This option is useful for " "users who need to limit CPU resources of a container system without having " -"to modify the container (application code). (Contributed by Donghee Na in :" -"gh:`109595`.)" +"to modify application code or the container itself. (Contributed by Donghee " +"Na in :gh:`109595`.)" msgstr "" -":func:`os.cpu_count` e :func:`os.process_cpu_count` podem ser substituídos " +":func:`~os.cpu_count` e :func:`~os.process_cpu_count` podem ser substituídos " "através da nova variável de ambiente :envvar:`PYTHON_CPU_COUNT` ou da nova " "opção de linha de comando :option:`-X cpu_count <-X>`. Esta opção é útil " "para usuários que precisam limitar os recursos da CPU de um sistema " -"contêiner sem precisar modificar o contêiner (código da aplicação). " +"contêiner sem precisar modificar código da aplicação ou o contêiner em si. " "(Contribuição de Donghee Na em :gh:`109595`.)" -#: ../../whatsnew/3.13.rst:989 -msgid "" -"Add support of :func:`os.lchmod` and the *follow_symlinks* argument in :func:" -"`os.chmod` on Windows. Note that the default value of *follow_symlinks* in :" -"func:`!os.lchmod` is ``False`` on Windows. (Contributed by Serhiy Storchaka " -"in :gh:`59616`.)" -msgstr "" -"Adiciona suporte para :func:`os.lchmod` e o argumento *follow_symlinks* em :" -"func:`os.chmod` no Windows. Observe que o valor padrão de *follow_symlinks* " -"em :func:`!os.lchmod` é ``False`` no Windows. (Contribuição de Serhiy " -"Storchaka em :gh:`59616`.)" - -#: ../../whatsnew/3.13.rst:995 +#: ../../whatsnew/3.13.rst:1060 msgid "" -"Add support of :func:`os.fchmod` and a file descriptor in :func:`os.chmod` " -"on Windows. (Contributed by Serhiy Storchaka in :gh:`113191`.)" +"Add a :ref:`low level interface ` to Linux's :manpage:`timer " +"file descriptors ` via :func:`~os.timerfd_create`, :func:" +"`~os.timerfd_settime`, :func:`~os.timerfd_settime_ns`, :func:`~os." +"timerfd_gettime`, :func:`~os.timerfd_gettime_ns`, :const:`~os." +"TFD_NONBLOCK`, :const:`~os.TFD_CLOEXEC`, :const:`~os.TFD_TIMER_ABSTIME`, " +"and :const:`~os.TFD_TIMER_CANCEL_ON_SET` (Contributed by Masaru Tsuchiyama " +"in :gh:`108277`.)" msgstr "" -"Adiciona suporte para :func:`os.fchmod` e um descritor de arquivo em :func:" -"`os.chmod` no Windows. (Contribuição de Serhiy Storchaka em :gh:`113191`.)" +"Adiciona uma :ref:`interface de baixo nível ` aos :manpage:" +"`descritores de arquivo de temporizador ` do Linux via :" +"func:`~os.timerfd_create`, :func:`~os.timerfd_settime`, :func:`~os." +"timerfd_settime_ns`, :func:`~os.timerfd_gettime`, :func:`~os." +"timerfd_gettime_ns`, :const:`~os.TFD_NONBLOCK`, :const:`~os.TFD_CLOEXEC`, :" +"const:`~os.TFD_TIMER_ABSTIME` e :const:`~os.TFD_TIMER_CANCEL_ON_SET` " +"(Contribuição de Masaru Tsuchiyama em :gh:`108277`.)" -#: ../../whatsnew/3.13.rst:999 +#: ../../whatsnew/3.13.rst:1069 msgid "" -":func:`os.posix_spawn` now accepts ``env=None``, which makes the newly " -"spawned process use the current process environment. (Contributed by Jakub " -"Kulik in :gh:`113119`.)" +":func:`~os.lchmod` and the *follow_symlinks* argument of :func:`~os.chmod` " +"are both now available on Windows. Note that the default value of " +"*follow_symlinks* in :func:`!lchmod` is ``False`` on Windows. (Contributed " +"by Serhiy Storchaka in :gh:`59616`.)" msgstr "" -":func:`os.posix_spawn` agora aceita ``env=None``, o que faz com que o " -"processo recém gerado use o ambiente de processo atual. (Contribuição de " -"Jakub Kulik em :gh:`113119`.)" +":func:`~os.lchmod` e o argumento *follow_symlinks* em :func:`~os.chmod` " +"estão agora disponíveis no Windows. Observe que o valor padrão de " +"*follow_symlinks* em :func:`!lchmod` é ``False`` no Windows. (Contribuição " +"de Serhiy Storchaka em :gh:`59616`.)" -#: ../../whatsnew/3.13.rst:1003 +#: ../../whatsnew/3.13.rst:1075 msgid "" -":func:`os.posix_spawn` gains an :attr:`os.POSIX_SPAWN_CLOSEFROM` attribute " -"for use in ``file_actions=`` on platforms that support :c:func:`!" -"posix_spawn_file_actions_addclosefrom_np`. (Contributed by Jakub Kulik in :" -"gh:`113117`.)" +":func:`~os.fchmod` and support for file descriptors in :func:`~os.chmod` are " +"both now available on Windows. (Contributed by Serhiy Storchaka in :gh:" +"`113191`.)" msgstr "" -":func:`os.posix_spawn` ganha um atributo :attr:`os.POSIX_SPAWN_CLOSEFROM` " -"para uso em ``file_actions=`` em plataformas que oferecem suporte a :c:func:" -"`!posix_spawn_file_actions_addclosefrom_np`. (Contribuição de Jakub Kulik " -"em :gh:`113117`.)" +":func:`~os.fchmod` e suporte para descritores de arquivo em :func:`~os." +"chmod` estão agora disponíveis no Windows. (Contribuição de Serhiy Storchaka " +"em :gh:`113191`.)" -#: ../../whatsnew/3.13.rst:1008 +#: ../../whatsnew/3.13.rst:1079 msgid "" -":func:`os.mkdir` and :func:`os.makedirs` on Windows now support passing a " +"On Windows, :func:`~os.mkdir` and :func:`~os.makedirs` now support passing a " "*mode* value of ``0o700`` to apply access control to the new directory. This " "implicitly affects :func:`tempfile.mkdtemp` and is a mitigation for :cve:" "`2024-4030`. Other values for *mode* continue to be ignored. (Contributed by " "Steve Dower in :gh:`118486`.)" msgstr "" -":func:`os.mkdir` e :func:`os.makedirs` no Windows agora oferecem suporte a " -"passar um valor *mode* de ``0o700`` para aplicar controle de acesso ao novo " -"diretório. Isso afeta implicitamente :func:`tempfile.mkdtemp` e é uma " +"No Windows, :func:`~os.mkdir` e :func:`~os.makedirs` agora oferecem suporte " +"a passar um valor *mode* de ``0o700`` para aplicar controle de acesso ao " +"novo diretório. Isso afeta implicitamente :func:`tempfile.mkdtemp` e é uma " "mitigação para :cve:`2024-4030`. Outros valores para *mode* continuam a ser " "ignorados. (Contribuição de Steve Dower em :gh:`118486`.)" -#: ../../whatsnew/3.13.rst:1015 +#: ../../whatsnew/3.13.rst:1086 +msgid "" +":func:`~os.posix_spawn` now accepts ``None`` for the *env* argument, which " +"makes the newly spawned process use the current process environment. " +"(Contributed by Jakub Kulik in :gh:`113119`.)" +msgstr "" +":func:`~os.posix_spawn` agora aceita ``None`` para o argumento *env*, o que " +"faz com que o processo recém-gerado use o ambiente de processo atual. " +"(Contribuição de Jakub Kulik em :gh:`113119`.)" + +#: ../../whatsnew/3.13.rst:1090 +msgid "" +":func:`~os.posix_spawn` can now use the :const:`~os.POSIX_SPAWN_CLOSEFROM` " +"attribute in the *file_actions* parameter on platforms that support :c:func:" +"`!posix_spawn_file_actions_addclosefrom_np`. (Contributed by Jakub Kulik in :" +"gh:`113117`.)" +msgstr "" +":func:`~os.posix_spawn` agora pode usar o atributo :const:`~os." +"POSIX_SPAWN_CLOSEFROM` no parâmetro *file_actions* em plataformas que " +"oferecem suporte a :c:func:`!posix_spawn_file_actions_addclosefrom_np`. " +"(Contribuição de Jakub Kulik em :gh:`113117`.)" + +#: ../../whatsnew/3.13.rst:1097 msgid "os.path" msgstr "os.path" -#: ../../whatsnew/3.13.rst:1017 +#: ../../whatsnew/3.13.rst:1099 msgid "" -"Add :func:`os.path.isreserved` to check if a path is reserved on the current " -"system. This function is only available on Windows. (Contributed by Barney " -"Gale in :gh:`88569`.)" +"Add :func:`~os.path.isreserved` to check if a path is reserved on the " +"current system. This function is only available on Windows. (Contributed by " +"Barney Gale in :gh:`88569`.)" msgstr "" -"Adiciona :func:`os.path.isreserved` para verificar se um caminho está " +"Adiciona :func:`~os.path.isreserved` para verificar se um caminho está " "reservado no sistema atual. Esta função está disponível apenas no Windows. " "(Contribuição de Barney Gale em :gh:`88569`.)" -#: ../../whatsnew/3.13.rst:1020 +#: ../../whatsnew/3.13.rst:1104 msgid "" -"On Windows, :func:`os.path.isabs` no longer considers paths starting with " -"exactly one (back)slash to be absolute. (Contributed by Barney Gale and Jon " -"Foster in :gh:`44626`.)" +"On Windows, :func:`~os.path.isabs` no longer considers paths starting with " +"exactly one slash (``\\`` or ``/``) to be absolute. (Contributed by Barney " +"Gale and Jon Foster in :gh:`44626`.)" msgstr "" -"No Windows, :func:`os.path.isabs` não considera mais caminhos que começam " -"com exatamente uma (contra)barra como absolutos. (Contribuição de Barney " -"Gale e Jon Foster em :gh:`44626`.)" +"No Windows, :func:`~os.path.isabs` não considera mais caminhos que começam " +"com exatamente uma barra (``\\`` ou ``/``) como absolutos. (Contribuição de " +"Barney Gale e Jon Foster em :gh:`44626`.)" -#: ../../whatsnew/3.13.rst:1024 +#: ../../whatsnew/3.13.rst:1108 msgid "" -"Add support of *dir_fd* and *follow_symlinks* keyword arguments in :func:" -"`shutil.chown`. (Contributed by Berker Peksag and Tahia K in :gh:`62308`)" +":func:`~os.path.realpath` now resolves MS-DOS style file names even if the " +"file is not accessible. (Contributed by Moonsik Park in :gh:`82367`.)" msgstr "" -"Adiciona suporte para argumentos nomeados *dir_fd* e *follow_symlinks* em :" -"func:`shutil.chown`. (Contribuição de Berker Peksag e Tahia K em :gh:`62308`)" +":func:`~os.path.realpath` agora resolve nomes de arquivos no estilo MS-DOS, " +"mesmo que o arquivo não esteja acessível. (Contribuição de Moonsik Park em :" +"gh:`82367`.)" -#: ../../whatsnew/3.13.rst:1029 ../../whatsnew/3.13.rst:1470 +#: ../../whatsnew/3.13.rst:1114 ../../whatsnew/3.13.rst:1745 msgid "pathlib" msgstr "pathlib" -#: ../../whatsnew/3.13.rst:1031 +#: ../../whatsnew/3.13.rst:1116 msgid "" -"Add :exc:`pathlib.UnsupportedOperation`, which is raised instead of :exc:" +"Add :exc:`~pathlib.UnsupportedOperation`, which is raised instead of :exc:" "`NotImplementedError` when a path operation isn't supported. (Contributed by " "Barney Gale in :gh:`89812`.)" msgstr "" -"Adiciona :exc:`pathlib.UnsupportedOperation`, que é levantado em vez de :exc:" -"`NotImplementedError` quando uma operação de caminho não é suportada. " +"Adiciona :exc:`~pathlib.UnsupportedOperation`, que é levantada em vez de :" +"exc:`NotImplementedError` quando uma operação de caminho não é possível. " "(Contribuição de Barney Gale em :gh:`89812`.)" -#: ../../whatsnew/3.13.rst:1035 +#: ../../whatsnew/3.13.rst:1120 msgid "" -"Add :meth:`pathlib.Path.from_uri`, a new constructor to create a :class:" -"`pathlib.Path` object from a 'file' URI (``file://``). (Contributed by " -"Barney Gale in :gh:`107465`.)" +"Add a new constructor for creating :class:`~pathlib.Path` objects from " +"'file' URIs (``file:///``), :meth:`.Path.from_uri`. (Contributed by Barney " +"Gale in :gh:`107465`.)" msgstr "" -"Adiciona :meth:`pathlib.Path.from_uri`, um novo construtor para criar um " -"objeto :class:`pathlib.Path` a partir de um URI 'file' (``file://``). " -"(Contribuição de Barney Gale em :gh:`107465`.)" +"Adiciona um novo construtor para criar objetos :class:`~pathlib.Path` a " +"partir de URIs 'file' (``file:///``), :meth:`.Path.from_uri`. (Contribuição " +"de Barney Gale em :gh:`107465`.)" -#: ../../whatsnew/3.13.rst:1039 +#: ../../whatsnew/3.13.rst:1124 msgid "" -"Add :meth:`pathlib.PurePath.full_match` for matching paths with shell-style " +"Add :meth:`.PurePath.full_match` for matching paths with shell-style " "wildcards, including the recursive wildcard \"``**``\". (Contributed by " "Barney Gale in :gh:`73435`.)" msgstr "" -"Adiciona :meth:`pathlib.PurePath.full_match` para corresponder caminhos com " +"Adiciona :meth:`.PurePath.full_match` para corresponder caminhos com " "curingas do tipo shell, incluindo o curinga recursivo \"``**``\". " "(Contribuição de Barney Gale em :gh:`73435`.)" -#: ../../whatsnew/3.13.rst:1043 +#: ../../whatsnew/3.13.rst:1128 msgid "" -"Add :attr:`pathlib.PurePath.parser` class attribute that stores the " -"implementation of :mod:`os.path` used for low-level path parsing and " -"joining: either ``posixpath`` or ``ntpath``." +"Add the :attr:`.PurePath.parser` class attribute to store the implementation " +"of :mod:`os.path` used for low-level path parsing and joining. This will be " +"either :mod:`!posixpath` or :mod:`!ntpath`." msgstr "" -"Adiciona o atributo de classe :attr:`pathlib.PurePath.parser` que armazena a " -"implementação de :mod:`os.path` usado para análise e junção de caminhos de " -"baixo nível: ``posixpath`` ou ``ntpath``." +"Adiciona o atributo de classe :attr:`.PurePath.parser` para armazenar a " +"implementação de :mod:`os.path` usada para análise e junção de caminhos de " +"baixo nível. Isso vai ser :mod:`!posixpath` ou :mod:`!ntpath`." -#: ../../whatsnew/3.13.rst:1047 +#: ../../whatsnew/3.13.rst:1133 msgid "" -"Add *recurse_symlinks* keyword-only argument to :meth:`pathlib.Path.glob` " -"and :meth:`~pathlib.Path.rglob`. (Contributed by Barney Gale in :gh:`77609`.)" +"Add *recurse_symlinks* keyword-only argument to :meth:`.Path.glob` and :meth:" +"`~pathlib.Path.rglob`. (Contributed by Barney Gale in :gh:`77609`.)" msgstr "" -"Adiciona o argumento somente-nomeado *recurse_symlinks* a :meth:`pathlib." -"Path.glob` e :meth:`~pathlib.Path.rglob`. (Contribuição de Barney Gale em :" -"gh:`77609`.)" +"Adiciona o argumento somente-nomeado *recurse_symlinks* a :meth:`.Path.glob` " +"e :meth:`~pathlib.Path.rglob`. (Contribuição de Barney Gale em :gh:`77609`.)" -#: ../../whatsnew/3.13.rst:1051 +#: ../../whatsnew/3.13.rst:1137 msgid "" -"Add *follow_symlinks* keyword-only argument to :meth:`~pathlib.Path." -"is_file`, :meth:`~pathlib.Path.is_dir`, :meth:`~pathlib.Path.owner`, :meth:" -"`~pathlib.Path.group`. (Contributed by Barney Gale in :gh:`105793`, and " -"Kamil Turek in :gh:`107962`.)" +":meth:`.Path.glob` and :meth:`~pathlib.Path.rglob` now return files and " +"directories when given a pattern that ends with \"``**``\". Previously, only " +"directories were returned. (Contributed by Barney Gale in :gh:`70303`.)" msgstr "" -"Adiciona o argumento somente-nomeado *follow_symlinks* a :meth:`~pathlib." -"Path.is_file`, :meth:`~pathlib.Path.is_dir`, :meth:`~pathlib.Path.owner`, :" -"meth:`~pathlib.Path.group`. (Contribuição de Barney Gale em :gh:`105793` e " -"Kamil Turek em :gh:`107962`.)" +":meth:`.Path.glob` e :meth:`~pathlib.Path.rglob` agora retornam arquivos e " +"diretórios quando recebem um padrão que termina com \"``**``\". " +"Anteriormente, apenas os diretórios eram retornados. (Contribuição de Barney " +"Gale em :gh:`70303`.)" -#: ../../whatsnew/3.13.rst:1057 +#: ../../whatsnew/3.13.rst:1142 msgid "" -"Return files and directories from :meth:`pathlib.Path.glob` and :meth:" -"`~pathlib.Path.rglob` when given a pattern that ends with \"``**``\". In " -"earlier versions, only directories were returned. (Contributed by Barney " -"Gale in :gh:`70303`.)" +"Add the *follow_symlinks* keyword-only argument to :meth:`Path.is_file " +"`, :meth:`Path.is_dir `, :meth:`." +"Path.owner`, and :meth:`.Path.group`. (Contributed by Barney Gale in :gh:" +"`105793` and Kamil Turek in :gh:`107962`.)" msgstr "" -"Retorna arquivos e diretórios de :meth:`pathlib.Path.glob` e :meth:`~pathlib." -"Path.rglob` quando recebe um padrão que termina com \"``**``\". Nas versões " -"anteriores, apenas os diretórios eram retornados. (Contribuição de Barney " -"Gale em :gh:`70303`.)" +"Adiciona o argumento somente-nomeado *follow_symlinks* a :meth:`Path.is_file " +"`, :meth:`Path.is_dir `, :meth:`." +"Path.owner` e :meth:`.Path.group`. (Contribuição de Barney Gale em :gh:" +"`105793` e Kamil Turek em :gh:`107962`.)" -#: ../../whatsnew/3.13.rst:1063 +#: ../../whatsnew/3.13.rst:1150 msgid "pdb" msgstr "pdb" -#: ../../whatsnew/3.13.rst:1065 +#: ../../whatsnew/3.13.rst:1152 msgid "" -"Add ability to move between chained exceptions during post mortem debugging " -"in :func:`~pdb.pm` using the new ``exceptions [exc_number]`` command for " -"Pdb. (Contributed by Matthias Bussonnier in :gh:`106676`.)" +":func:`breakpoint` and :func:`~pdb.set_trace` now enter the debugger " +"immediately rather than on the next line of code to be executed. This change " +"prevents the debugger from breaking outside of the context when :func:`!" +"breakpoint` is positioned at the end of the context. (Contributed by Tian " +"Gao in :gh:`118579`.)" msgstr "" -"Adiciona a capacidade de mover entre exceções encadeadas durante a depuração " -"post mortem em :func:`~pdb.pm` usando o novo comando ``exceptions " -"[número_exc]`` para Pdb. (Contribuição de Matthias Bussonnier em :gh:" -"`106676`.)" +":func:`breakpoint` e :func:`~pdb.set_trace` agora entram no depurador " +"imediatamente em vez de na próxima linha de código a ser executada. Esta " +"mudança evita que o depurador quebre fora do contexto quando :func:`!" +"breakpoint` estiver posicionado no final do contexto. (Contribuição de Tian " +"Gao em :gh:`118579`.)" -#: ../../whatsnew/3.13.rst:1069 +#: ../../whatsnew/3.13.rst:1158 msgid "" -"Expressions/statements whose prefix is a pdb command are now correctly " -"identified and executed. (Contributed by Tian Gao in :gh:`108464`.)" +"``sys.path[0]`` is no longer replaced by the directory of the script being " +"debugged when :attr:`sys.flags.safe_path` is set. (Contributed by Tian Gao " +"and Christian Walther in :gh:`111762`.)" msgstr "" -"Expressões/instruções cujo prefixo é um comando pdb agora são identificadas " -"e executadas corretamente. (Contribuição de Tian Gao em :gh:`108464`.)" +"``sys.path[0]`` não mais é substituído pelo diretório do script que está " +"sendo depurado quando :attr:`sys.flags.safe_path` está definido." +"(Contribuição de Tian Gao e Christian Walther em :gh:`111762`.)" -#: ../../whatsnew/3.13.rst:1073 +#: ../../whatsnew/3.13.rst:1162 msgid "" -"``sys.path[0]`` will no longer be replaced by the directory of the script " -"being debugged when ``sys.flags.safe_path`` is set (via the :option:`-P` " -"command line option or :envvar:`PYTHONSAFEPATH` environment variable). " -"(Contributed by Tian Gao and Christian Walther in :gh:`111762`.)" +":mod:`zipapp` is now supported as a debugging target. (Contributed by Tian " +"Gao in :gh:`118501`.)" msgstr "" -"``sys.path[0]`` não será mais substituído pelo diretório do script que está " -"sendo depurado quando ``sys.flags.safe_path`` estiver definido (através da " -"opção de linha de comando :option:`-P` ou a variável de ambiente :envvar:" -"`PYTHONSAFEPATH`). (Contribuição de Tian Gao e Christian Walther em :gh:" -"`111762`.)" +":mod:`zipapp` agora é aceito como alvo de depuração. (Contribuição de Tian " +"Gao em :gh:`118501`.)" -#: ../../whatsnew/3.13.rst:1078 +#: ../../whatsnew/3.13.rst:1165 msgid "" -":mod:`zipapp` is supported as a debugging target. (Contributed by Tian Gao " -"in :gh:`118501`.)" +"Add ability to move between chained exceptions during post-mortem debugging " +"in :func:`~pdb.pm` using the new :pdbcmd:`exceptions [exc_number] " +"` command for Pdb. (Contributed by Matthias Bussonnier in :gh:" +"`106676`.)" msgstr "" -":mod:`zipapp` é suportado como alvo de depuração. (Contribuição de Tian Gao " -"em :gh:`118501`.)" +"Adiciona a capacidade de mover entre exceções encadeadas durante a depuração " +"post-mortem em :func:`~pdb.pm` usando o novo comando :pdbcmd:`exceptions " +"[número_exc] ` para Pdb. (Contribuição de Matthias Bussonnier " +"em :gh:`106676`.)" -#: ../../whatsnew/3.13.rst:1081 +#: ../../whatsnew/3.13.rst:1170 msgid "" -"``breakpoint()`` and ``pdb.set_trace()`` now enter the debugger immediately " -"rather than on the next line of code to be executed. This change prevents " -"the debugger from breaking outside of the context when ``breakpoint()`` is " -"positioned at the end of the context. (Contributed by Tian Gao in :gh:" -"`118579`.)" +"Expressions and statements whose prefix is a pdb command are now correctly " +"identified and executed. (Contributed by Tian Gao in :gh:`108464`.)" msgstr "" -"``breakpoint()`` e ``pdb.set_trace()`` agora entram no depurador " -"imediatamente em vez de na próxima linha de código a ser executada. Esta " -"mudança evita que o depurador quebre fora do contexto quando " -"``breakpoint()`` estiver posicionado no final do contexto. (Contribuição de " -"Tian Gao em :gh:`118579`.)" +"Expressões e instruções cujo prefixo é um comando pdb agora são " +"identificadas e executadas corretamente. (Contribuição de Tian Gao em :gh:" +"`108464`.)" -#: ../../whatsnew/3.13.rst:1088 +#: ../../whatsnew/3.13.rst:1176 msgid "queue" msgstr "queue" -#: ../../whatsnew/3.13.rst:1090 +#: ../../whatsnew/3.13.rst:1178 msgid "" -"Add :meth:`queue.Queue.shutdown` (along with :exc:`queue.ShutDown`) for " -"queue termination. (Contributed by Laurie Opperman and Yves Duprat in :gh:" -"`104750`.)" +"Add :meth:`Queue.shutdown ` and :exc:`~queue.ShutDown` " +"to manage queue termination. (Contributed by Laurie Opperman and Yves Duprat " +"in :gh:`104750`.)" msgstr "" -"Adiciona :meth:`queue.Queue.shutdown` (junto com :exc:`queue.ShutDown`) para " -"encerramento da fila. (Contribuição de Laurie Opperman e Yves Duprat em :gh:" -"`104750`.)" +"Adiciona :meth:`Queue.shutdown ` e :exc:`~queue." +"ShutDown` para gerenciar a finalização da fila. (Contribuição de Laurie " +"Opperman e Yves Duprat em :gh:`104750`.)" -#: ../../whatsnew/3.13.rst:1095 +#: ../../whatsnew/3.13.rst:1184 msgid "random" msgstr "random" -#: ../../whatsnew/3.13.rst:1097 +#: ../../whatsnew/3.13.rst:1186 msgid "" "Add a :ref:`command-line interface `. (Contributed by Hugo van " "Kemenade in :gh:`118131`.)" @@ -2300,122 +2421,195 @@ msgstr "" "Adiciona uma :ref:`interface de linha de comando `. " "(Contribuição de Hugo van Kemenade em :gh:`118131`.)" -#: ../../whatsnew/3.13.rst:1101 ../../whatsnew/3.13.rst:1476 +#: ../../whatsnew/3.13.rst:1191 ../../whatsnew/3.13.rst:1753 msgid "re" msgstr "re" -#: ../../whatsnew/3.13.rst:1102 +#: ../../whatsnew/3.13.rst:1193 msgid "" -"Rename :exc:`!re.error` to :exc:`re.PatternError` for improved clarity. :exc:" -"`!re.error` is kept for backward compatibility." +"Rename :exc:`!re.error` to :exc:`~re.PatternError` for improved clarity. :" +"exc:`!re.error` is kept for backward compatibility." msgstr "" -"Renomeia :exc:`!re.error` para :exc:`re.PatternError` para maior clareza. :" +"Renomeia :exc:`!re.error` para :exc:`~re.PatternError` para maior clareza. :" "exc:`!re.error` é mantido para compatibilidade com versões anteriores." -#: ../../whatsnew/3.13.rst:1106 +#: ../../whatsnew/3.13.rst:1198 +msgid "shutil" +msgstr "shutil" + +#: ../../whatsnew/3.13.rst:1200 +msgid "" +"Support the *dir_fd* and *follow_symlinks* keyword arguments in :func:" +"`~shutil.chown`. (Contributed by Berker Peksag and Tahia K in :gh:`62308`)" +msgstr "" +"Suporte aos argumentos nomeados *dir_fd* e *follow_symlinks* em :func:" +"`~shutil.chown`. (Contribuição de Berker Peksag e Tahia K em :gh:`62308`)" + +#: ../../whatsnew/3.13.rst:1206 msgid "site" msgstr "site" -#: ../../whatsnew/3.13.rst:1108 +#: ../../whatsnew/3.13.rst:1208 msgid "" -":file:`.pth` files are now decoded by UTF-8 first, and then by the :term:" -"`locale encoding` if the UTF-8 decoding fails. (Contributed by Inada Naoki " +":file:`.pth` files are now decoded using UTF-8 first, and then with the :" +"term:`locale encoding` if UTF-8 decoding fails. (Contributed by Inada Naoki " "in :gh:`117802`.)" msgstr "" -"Os arquivos :file:`.pth` agora são decodificados primeiro por UTF-8 e depois " -"por :term:`codificação da localidade` se a decodificação UTF-8 falhar. " -"(Contribuição de Inada Naoki em :gh:`117802`.)" +"Os arquivos :file:`.pth` agora são decodificados primeiro usando UTF-8 e " +"depois usando :term:`codificação da localidade` se a decodificação UTF-8 " +"falhar. (Contribuição de Inada Naoki em :gh:`117802`.)" -#: ../../whatsnew/3.13.rst:1113 +#: ../../whatsnew/3.13.rst:1214 msgid "sqlite3" msgstr "sqlite3" -#: ../../whatsnew/3.13.rst:1115 +#: ../../whatsnew/3.13.rst:1216 msgid "" -"A :exc:`ResourceWarning` is now emitted if a :class:`sqlite3.Connection` " +"A :exc:`ResourceWarning` is now emitted if a :class:`~sqlite3.Connection` " "object is not :meth:`closed ` explicitly. " "(Contributed by Erlend E. Aasland in :gh:`105539`.)" msgstr "" -"Uma :exc:`ResourceWarning` agora é emitida se um objeto :class:`sqlite3." +"Uma :exc:`ResourceWarning` agora é emitida se um objeto :class:`~sqlite3." "Connection` não for explicitamente :meth:`fechado `. (Contribuição de Erlend E. Aasland em :gh:`105539`.)" -#: ../../whatsnew/3.13.rst:1119 +#: ../../whatsnew/3.13.rst:1220 msgid "" -"Add *filter* keyword-only parameter to :meth:`sqlite3.Connection.iterdump` " -"for filtering database objects to dump. (Contributed by Mariusz Felisiak in :" -"gh:`91602`.)" +"Add the *filter* keyword-only parameter to :meth:`.Connection.iterdump` for " +"filtering database objects to dump. (Contributed by Mariusz Felisiak in :gh:" +"`91602`.)" msgstr "" -"Adiciona o parâmetro somente-nomeado *filter* a :meth:`sqlite3.Connection." -"iterdump` para filtrar objetos de banco de dados para despejo. (Contribuição " -"de Mariusz Felisiak em :gh:`91602`.)" +"Adiciona o parâmetro somente-nomeado *filter* a :meth:`.Connection.iterdump` " +"para filtrar objetos de banco de dados para despejo. (Contribuição de " +"Mariusz Felisiak em :gh:`91602`.)" -#: ../../whatsnew/3.13.rst:1124 +#: ../../whatsnew/3.13.rst:1226 +msgid "ssl" +msgstr "ssl" + +#: ../../whatsnew/3.13.rst:1228 +msgid "" +"The :func:`~ssl.create_default_context` API now includes :data:`~ssl." +"VERIFY_X509_PARTIAL_CHAIN` and :data:`~ssl.VERIFY_X509_STRICT` in its " +"default flags." +msgstr "" +"A API :func:`~ssl.create_default_context` agora inclui :data:`~ssl." +"VERIFY_X509_PARTIAL_CHAIN` e :data:`~ssl.VERIFY_X509_STRICT` em seus " +"sinalizadores padrão." + +#: ../../whatsnew/3.13.rst:1234 +msgid "" +":data:`~ssl.VERIFY_X509_STRICT` may reject pre-:rfc:`5280` or malformed " +"certificates that the underlying OpenSSL implementation might otherwise " +"accept. Whilst disabling this is not recommended, you can do so using:" +msgstr "" +":data:`~ssl.VERIFY_X509_STRICT` pode rejeitar certificados pré-:rfc:`5280` " +"ou malformados que a implementação OpenSSL subjacente poderia aceitar. " +"Embora não seja recomendado desativar isso, você pode fazer isso usando::" + +#: ../../whatsnew/3.13.rst:1239 +msgid "" +"import ssl\n" +"\n" +"ctx = ssl.create_default_context()\n" +"ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT" +msgstr "" +"import ssl\n" +"\n" +"ctx = ssl.create_default_context()\n" +"ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT" + +#: ../../whatsnew/3.13.rst:1246 +msgid "(Contributed by William Woodruff in :gh:`112389`.)" +msgstr "(Contribuição de William Woodruff em :gh:`112389`.)" + +#: ../../whatsnew/3.13.rst:1250 msgid "statistics" msgstr "statistics" -#: ../../whatsnew/3.13.rst:1126 +#: ../../whatsnew/3.13.rst:1252 msgid "" -"Add :func:`statistics.kde` for kernel density estimation. This makes it " +"Add :func:`~statistics.kde` for kernel density estimation. This makes it " "possible to estimate a continuous probability density function from a fixed " -"number of discrete samples. Also added :func:`statistics.kde_random` for " -"sampling from the estimated probability density function. (Contributed by " -"Raymond Hettinger in :gh:`115863`.)" +"number of discrete samples. (Contributed by Raymond Hettinger in :gh:" +"`115863`.)" msgstr "" -"Adiciona :func:`statistics.kde` para estimativa de densidade do núcleo. Isto " -"torna possível estimar uma função de densidade de probabilidade contínua a " -"partir de um número fixo de amostras discretas. Também foi adicionado :func:" -"`statistics.kde_random` para amostragem da função de densidade de " -"probabilidade estimada. (Contribuição de Raymond Hettinger em :gh:`115863`.)" +"Adiciona :func:`~statistics.kde` para estimativa de densidade do núcleo. " +"Isto torna possível estimar uma função de densidade de probabilidade " +"contínua a partir de um número fixo de amostras discretas. (Contribuição de " +"Raymond Hettinger em :gh:`115863`.)" -#: ../../whatsnew/3.13.rst:1135 +#: ../../whatsnew/3.13.rst:1257 +msgid "" +"Add :func:`~statistics.kde_random` for sampling from an estimated " +"probability density function created by :func:`~statistics.kde`. " +"(Contributed by Raymond Hettinger in :gh:`115863`.)" +msgstr "" +"Adiciona :func:`~statistics.kde_random` para amostragem de uma função de " +"densidade de probabilidade estimada criada por :func:`~statistics.kde`. " +"(Contribuição de Raymond Hettinger em :gh:`115863`.)" + +#: ../../whatsnew/3.13.rst:1265 msgid "subprocess" msgstr "subprocess" -#: ../../whatsnew/3.13.rst:1137 +#: ../../whatsnew/3.13.rst:1267 msgid "" -"The :mod:`subprocess` module now uses the :func:`os.posix_spawn` function in " -"more situations. Notably in the default case of ``close_fds=True`` on more " -"recent versions of platforms including Linux, FreeBSD, and Solaris where the " -"C library provides :c:func:`!posix_spawn_file_actions_addclosefrom_np`. On " -"Linux this should perform similar to our existing Linux :c:func:`!vfork` " -"based code. A private control knob :attr:`!subprocess._USE_POSIX_SPAWN` can " -"be set to ``False`` if you need to force :mod:`subprocess` not to ever use :" -"func:`os.posix_spawn`. Please report your reason and platform details in " -"the CPython issue tracker if you set this so that we can improve our API " -"selection logic for everyone. (Contributed by Jakub Kulik in :gh:`113117`.)" -msgstr "" -"O módulo :mod:`subprocess` agora usa a função :func:`os.posix_spawn` em mais " -"situações. Notavelmente no caso padrão de ``close_fds=True`` em versões mais " -"recentes de plataformas incluindo Linux, FreeBSD e Solaris onde a biblioteca " -"C fornece :c:func:`!posix_spawn_file_actions_addclosefrom_np`. No Linux, " -"isso deve funcionar de maneira semelhante ao nosso código existente baseado " -"em Linux :c:func:`!vfork`. Um botão de controle privado :attr:`!subprocess." -"_USE_POSIX_SPAWN` pode ser definido como ``False`` se você precisar forçar :" -"mod:`subprocess` a nunca usar :func:`os.posix_spawn`. Informe o motivo e os " -"detalhes da plataforma no rastreador de problemas do CPython se você definir " -"isso para que possamos melhorar nossa lógica de seleção de API para todos. " -"(Contribuição de Jakub Kulik em :gh:`113117`.)" +"The :mod:`subprocess` module now uses the :func:`~os.posix_spawn` function " +"in more situations." +msgstr "" +"O módulo :mod:`subprocess` agora usa a função :func:`~os.posix_spawn` em " +"mais situações." -#: ../../whatsnew/3.13.rst:1150 +#: ../../whatsnew/3.13.rst:1270 +msgid "" +"Notably, when *close_fds* is ``True`` (the default), :func:`~os.posix_spawn` " +"will be used when the C library provides :c:func:`!" +"posix_spawn_file_actions_addclosefrom_np`, which includes recent versions of " +"Linux, FreeBSD, and Solaris. On Linux, this should perform similarly to the " +"existing Linux :c:func:`!vfork` based code." +msgstr "" +"Notavelmente, quando *close_fds* é ``True`` (o padrão), :func:`~os." +"posix_spawn` será usado quando a biblioteca C fornecer :c:func:`!" +"posix_spawn_file_actions_addclosefrom_np`, que inclui versões recentes do " +"Linux, FreeBSD e Solaris. No Linux, isso deve ter um desempenho semelhante " +"ao código existente baseado em :c:func:`!vfork` do Linux." + +#: ../../whatsnew/3.13.rst:1277 +msgid "" +"A private control knob :attr:`!subprocess._USE_POSIX_SPAWN` can be set to " +"``False`` if you need to force :mod:`subprocess` to never use :func:`~os." +"posix_spawn`. Please report your reason and platform details in the :ref:" +"`issue tracker ` if you set this so that we can improve " +"our API selection logic for everyone. (Contributed by Jakub Kulik in :gh:" +"`113117`.)" +msgstr "" +"Um botão de controle privado :attr:`!subprocess._USE_POSIX_SPAWN` pode ser " +"definido como ``False`` se você precisar forçar :mod:`subprocess` a nunca " +"usar :func:`~os.posix_spawn`. Por favor, informe o motivo e os detalhes da " +"plataforma no :ref:`rastreador de problemas ` se você " +"definir isso para que possamos melhorar nossa lógica de seleção de API para " +"todos. (Contribuído por Jakub Kulik em :gh:`113117`.)" + +#: ../../whatsnew/3.13.rst:1287 ../../whatsnew/3.13.rst:2827 msgid "sys" msgstr "sys" -#: ../../whatsnew/3.13.rst:1152 +#: ../../whatsnew/3.13.rst:1289 msgid "" -"Add the :func:`sys._is_interned` function to test if the string was " -"interned. This function is not guaranteed to exist in all implementations of " -"Python. (Contributed by Serhiy Storchaka in :gh:`78573`.)" +"Add the :func:`~sys._is_interned` function to test if a string was interned. " +"This function is not guaranteed to exist in all implementations of Python. " +"(Contributed by Serhiy Storchaka in :gh:`78573`.)" msgstr "" -"Adiciona a função :func:`sys._is_interned` para testar se a string foi " +"Adiciona a função :func:`~sys._is_interned` para testar se uma string foi " "internada. Não há garantia de que esta função exista em todas as " "implementações do Python. (Contribuição de Serhiy Storchaka em :gh:`78573`.)" -#: ../../whatsnew/3.13.rst:1157 +#: ../../whatsnew/3.13.rst:1295 msgid "tempfile" msgstr "tempfile" -#: ../../whatsnew/3.13.rst:1159 +#: ../../whatsnew/3.13.rst:1297 msgid "" "On Windows, the default mode ``0o700`` used by :func:`tempfile.mkdtemp` now " "limits access to the new directory due to changes to :func:`os.mkdir`. This " @@ -2427,39 +2621,40 @@ msgstr "" "Esta é uma mitigação para :cve:`2024-4030`. (Contribuição de Steve Dower em :" "gh:`118486`.)" -#: ../../whatsnew/3.13.rst:1165 +#: ../../whatsnew/3.13.rst:1304 msgid "time" msgstr "time" -#: ../../whatsnew/3.13.rst:1167 +#: ../../whatsnew/3.13.rst:1306 msgid "" -"On Windows, :func:`time.monotonic()` now uses the " -"``QueryPerformanceCounter()`` clock to have a resolution better than 1 us, " -"instead of the ``GetTickCount64()`` clock which has a resolution of 15.6 ms. " -"(Contributed by Victor Stinner in :gh:`88494`.)" +"On Windows, :func:`~time.monotonic` now uses the " +"``QueryPerformanceCounter()`` clock for a resolution of 1 microsecond, " +"instead of the ``GetTickCount64()`` clock which has a resolution of 15.6 " +"milliseconds. (Contributed by Victor Stinner in :gh:`88494`.)" msgstr "" -"No Windows, :func:`time.monotonic()` agora usa o relógio " -"``QueryPerformanceCounter()`` para ter uma resolução melhor que 1 us, em vez " -"do relógio ``GetTickCount64()`` que tem uma resolução de 15.6 ms. " +"No Windows, :func:`~time.monotonic` agora usa o relógio " +"``QueryPerformanceCounter()`` para uma resolução de 1 microssegundo, em vez " +"do relógio ``GetTickCount64()`` que tem uma resolução de 15.6 milissegundos. " "(Contribuição de Victor Stinner em :gh:`88494`.)" -#: ../../whatsnew/3.13.rst:1172 +#: ../../whatsnew/3.13.rst:1312 msgid "" -"On Windows, :func:`time.time()` now uses the " -"``GetSystemTimePreciseAsFileTime()`` clock to have a resolution better than " -"1 μs, instead of the ``GetSystemTimeAsFileTime()`` clock which has a " -"resolution of 15.6 ms. (Contributed by Victor Stinner in :gh:`63207`.)" +"On Windows, :func:`~time.time` now uses the " +"``GetSystemTimePreciseAsFileTime()`` clock for a resolution of 1 " +"microsecond, instead of the ``GetSystemTimeAsFileTime()`` clock which has a " +"resolution of 15.6 milliseconds. (Contributed by Victor Stinner in :gh:" +"`63207`.)" msgstr "" -"No Windows, :func:`time.time()` agora usa o relógio " -"``GetSystemTimePreciseAsFileTime()`` para ter uma resolução melhor que 1 μs, " +"No Windows, :func:`~time.time` agora usa o relógio " +"``GetSystemTimePreciseAsFileTime()`` para uma resolução de 1 microssegundo, " "em vez do relógio ``GetSystemTimeAsFileTime()`` que tem uma resolução de " -"15.6 ms. (Contribuição de Victor Stinner em :gh:`63207`.)" +"15.6 milissegundos. (Contribuição de Victor Stinner em :gh:`63207`.)" -#: ../../whatsnew/3.13.rst:1180 +#: ../../whatsnew/3.13.rst:1320 msgid "tkinter" msgstr "tkinter" -#: ../../whatsnew/3.13.rst:1182 +#: ../../whatsnew/3.13.rst:1322 msgid "" "Add :mod:`tkinter` widget methods: :meth:`!tk_busy_hold`, :meth:`!" "tk_busy_configure`, :meth:`!tk_busy_cget`, :meth:`!tk_busy_forget`, :meth:`!" @@ -2471,48 +2666,54 @@ msgstr "" "tk_busy_current` e :meth:`!tk_busy_status`. (Contribuição de Miguel, " "klappnase e Serhiy Storchaka em :gh:`72684`.)" -#: ../../whatsnew/3.13.rst:1188 +#: ../../whatsnew/3.13.rst:1328 msgid "" "The :mod:`tkinter` widget method :meth:`!wm_attributes` now accepts the " -"attribute name without the minus prefix to get window attributes, e.g. ``w." -"wm_attributes('alpha')`` and allows to specify attributes and values to set " -"as keyword arguments, e.g. ``w.wm_attributes(alpha=0.5)``. Add new optional " -"keyword-only parameter *return_python_dict*: calling ``w." -"wm_attributes(return_python_dict=True)`` returns the attributes as a dict " -"instead of a tuple. (Contributed by Serhiy Storchaka in :gh:`43457`.)" +"attribute name without the minus prefix to get window attributes, for " +"example ``w.wm_attributes('alpha')`` and allows specifying attributes and " +"values to set as keyword arguments, for example ``w." +"wm_attributes(alpha=0.5)``. (Contributed by Serhiy Storchaka in :gh:`43457`.)" msgstr "" "O método :meth:`!wm_attributes` de widget :mod:`tkinter` agora aceita o nome " "do atributo sem o prefixo negativo para obter atributos de janela (por " "exemplo, ``w.wm_attributes('alpha')``) e permite especificar atributos e " "valores para definir como argumentos nomeados (por exemplo, ``w." -"wm_attributes(alpha=0.5)``). Adiciona novo parâmetro opcional somente-" -"nomeado *return_python_dict*: chamar ``w." -"wm_attributes(return_python_dict=True)`` retorna os atributos como um dict " -"em vez de uma tupla. (Contribuição de Serhiy Storchaka em :gh:`43457`.)" +"wm_attributes(alpha=0.5)``). (Contribuição de Serhiy Storchaka em :gh:" +"`43457`.)" + +#: ../../whatsnew/3.13.rst:1335 +msgid "" +":meth:`!wm_attributes` can now return attributes as a :class:`dict`, by " +"using the new optional keyword-only parameter *return_python_dict*. " +"(Contributed by Serhiy Storchaka in :gh:`43457`.)" +msgstr "" +":meth:`!wm_attributes` agora pode retornar atributos como um :class:`dict`, " +"usando o novo parâmetro somente-nomeado opcional *return_python_dict*. " +"(Contribuição de Serhiy Storchaka em :gh:`43457`.)" -#: ../../whatsnew/3.13.rst:1197 +#: ../../whatsnew/3.13.rst:1339 msgid "" -"Add new optional keyword-only parameter *return_ints* in the :meth:`!Text." -"count` method. Passing ``return_ints=True`` makes it always returning the " -"single count as an integer instead of a 1-tuple or ``None``. (Contributed by " -"Serhiy Storchaka in :gh:`97928`.)" +":meth:`!Text.count` can now return a simple :class:`int` when the new " +"optional keyword-only parameter *return_ints* is used. Otherwise, the single " +"count is returned as a 1-tuple or ``None``. (Contributed by Serhiy Storchaka " +"in :gh:`97928`.)" msgstr "" -"Adiciona um novo parâmetro opcional somente-nomeado *return_ints* no método :" -"meth:`!Text.count`. Passar ``return_ints=True`` faz com que ele sempre " -"retorne a contagem única como um número inteiro em vez de uma tupla de 1 " -"elemento ou ``None``. (Contribuição de Serhiy Storchaka em :gh:`97928`.)" +":meth:`!Text.count` agora pode retornar um :class:`int` simples quando o " +"novo parâmetro somente-nomeado opcional *return_ints* é usado. Caso " +"contrário, a contagem única é retornada como uma tupla de 1 elemento ou " +"``None``. (Contribuição de Serhiy Storchaka em :gh:`97928`.)" -#: ../../whatsnew/3.13.rst:1203 +#: ../../whatsnew/3.13.rst:1344 msgid "" -"Add support of the \"vsapi\" element type in the :meth:`~tkinter.ttk.Style." +"Support the \"vsapi\" element type in the :meth:`~tkinter.ttk.Style." "element_create` method of :class:`tkinter.ttk.Style`. (Contributed by Serhiy " "Storchaka in :gh:`68166`.)" msgstr "" -"Adiciona suporte ao tipo de elemento \"vsapi\" no método :meth:`~tkinter.ttk." -"Style.element_create` de :class:`tkinter.ttk.Style`. (Contribuição de Serhiy " +"Suporte ao tipo de elemento \"vsapi\" no método :meth:`~tkinter.ttk.Style." +"element_create` de :class:`tkinter.ttk.Style`. (Contribuição de Serhiy " "Storchaka em :gh:`68166`.)" -#: ../../whatsnew/3.13.rst:1208 +#: ../../whatsnew/3.13.rst:1349 msgid "" "Add the :meth:`!after_info` method for Tkinter widgets. (Contributed by " "Cheryl Sabella in :gh:`77020`.)" @@ -2520,1022 +2721,1334 @@ msgstr "" "Adiciona o método :meth:`!after_info` para widgets do Tkinter. (Contribuição " "de Cheryl Sabella em :gh:`77020`.)" -#: ../../whatsnew/3.13.rst:1211 +#: ../../whatsnew/3.13.rst:1352 msgid "" -"Add the :class:`!PhotoImage` method :meth:`!copy_replace` to copy a region " -"from one image to other image, possibly with pixel zooming and/or " -"subsampling. Add *from_coords* parameter to :class:`!PhotoImage` methods :" -"meth:`!copy()`, :meth:`!zoom()` and :meth:`!subsample()`. Add *zoom* and " -"*subsample* parameters to :class:`!PhotoImage` method :meth:`!copy()`. " -"(Contributed by Serhiy Storchaka in :gh:`118225`.)" +"Add a new :meth:`!copy_replace` method to :class:`!PhotoImage` to copy a " +"region from one image to another, possibly with pixel zooming, subsampling, " +"or both. (Contributed by Serhiy Storchaka in :gh:`118225`.)" msgstr "" -"Adiciona o método :meth:`!copy_replace` à classe :class:`!PhotoImage` para " -"copiar uma região de uma imagem para outra imagem, possivelmente com " -"ampliação e subamostragem de pixels. Adiciona parâmetro *from_coords* para " -"os métodos :meth:`!copy()`, :meth:`!zoom()` e :meth:`!subsample()` da " -"classe :class:`!PhotoImage`. Adiciona parâmetros *zoom* e *subsample* para o " -"método :meth:`!copy()` da classe :class:`!PhotoImage`. (Contribuição de " -"Serhiy Storchaka em :gh:`118225`.)" +"Adiciona um novo método :meth:`!copy_replace` a :class:`!PhotoImage` para " +"copiar uma região de uma imagem para outra, possivelmente com zoom de pixel, " +"subamostragem ou ambos. (Contribuição de Serhiy Storchaka em :gh:`118225`.)" -#: ../../whatsnew/3.13.rst:1220 +#: ../../whatsnew/3.13.rst:1357 +msgid "" +"Add *from_coords* parameter to the :class:`!PhotoImage` methods :meth:`!" +"copy`, :meth:`!zoom` and :meth:`!subsample`. Add *zoom* and *subsample* " +"parameters to the :class:`!PhotoImage` method :meth:`!copy`. (Contributed by " +"Serhiy Storchaka in :gh:`118225`.)" +msgstr "" +"Adiciona parâmetro *from_coords* para os métodos :meth:`!copy`, :meth:`!" +"zoom` e :meth:`!subsample` da classe :class:`!PhotoImage`. Adiciona " +"parâmetros *zoom* e *subsample* para o método :meth:`!copy` da classe :class:" +"`!PhotoImage`. (Contribuição de Serhiy Storchaka em :gh:`118225`.)" + +#: ../../whatsnew/3.13.rst:1363 msgid "" "Add the :class:`!PhotoImage` methods :meth:`!read` to read an image from a " "file and :meth:`!data` to get the image data. Add *background* and " -"*grayscale* parameters to :class:`!PhotoImage` method :meth:`!write`. " -"(Contributed by Serhiy Storchaka in :gh:`118271`.)" +"*grayscale* parameters to the :meth:`!write` method. (Contributed by Serhiy " +"Storchaka in :gh:`118271`.)" msgstr "" "Adiciona os métodos :class:`!PhotoImage` :meth:`!read` para ler uma imagem " "de um arquivo e :meth:`!data` para obter os dados da imagem. Adiciona os " -"parâmetros *background* e *grayscale* ao método :meth:`!write` de :class:`!" -"PhotoImage`. (Contribuição de Serhiy Storchaka em :gh:`118271`.)" +"parâmetros *background* e *grayscale* ao método :meth:`!write`. " +"(Contribuição de Serhiy Storchaka em :gh:`118271`.)" -#: ../../whatsnew/3.13.rst:1227 +#: ../../whatsnew/3.13.rst:1371 msgid "traceback" msgstr "traceback" -#: ../../whatsnew/3.13.rst:1229 -msgid "" -"Add *show_group* parameter to :func:`traceback.TracebackException." -"format_exception_only` to format the nested exceptions of a :exc:" -"`BaseExceptionGroup` instance, recursively. (Contributed by Irit Katriel in :" -"gh:`105292`.)" -msgstr "" -"Adiciona o parâmetro *show_group* a :func:`traceback.TracebackException." -"format_exception_only` para formatar as exceções aninhadas de uma instância :" -"exc:`BaseExceptionGroup`, recursivamente. (Contribuição de Irit Katriel em :" -"gh:`105292`.)" - -#: ../../whatsnew/3.13.rst:1233 +#: ../../whatsnew/3.13.rst:1373 msgid "" -"Add the field *exc_type_str* to :class:`~traceback.TracebackException`, " -"which holds a string display of the *exc_type*. Deprecate the field " -"*exc_type* which holds the type object itself. Add parameter *save_exc_type* " +"Add the :attr:`~traceback.TracebackException.exc_type_str` attribute to :" +"class:`~traceback.TracebackException`, which holds a string display of the " +"*exc_type*. Deprecate the :attr:`~traceback.TracebackException.exc_type` " +"attribute, which holds the type object itself. Add parameter *save_exc_type* " "(default ``True``) to indicate whether ``exc_type`` should be saved. " "(Contributed by Irit Katriel in :gh:`112332`.)" msgstr "" -"Adiciona o campo *exc_type_str* a :class:`~traceback.TracebackException`, " -"que contém uma exibição de string do *exc_type*. Substitua o campo " -"*exc_type* que contém o próprio objeto de tipo. Adicione o parâmetro " +"Adiciona o atributo :attr:`~traceback.TracebackException.exc_type_str` a :" +"class:`~traceback.TracebackException`, que contém uma exibição de string do " +"*exc_type*. Descontinua o atributo :attr:`~traceback.TracebackException." +"exc_type`, que contém o próprio objeto de tipo. Adicione o parâmetro " "*save_exc_type* (padrão ``True``) para indicar se ``exc_type`` deve ser " "salvo. (Contribuição de Irit Katriel em :gh:`112332`.)" -#: ../../whatsnew/3.13.rst:1240 +#: ../../whatsnew/3.13.rst:1382 +msgid "" +"Add a new *show_group* keyword-only parameter to :meth:`.TracebackException." +"format_exception_only` to (recursively) format the nested exceptions of a :" +"exc:`BaseExceptionGroup` instance. (Contributed by Irit Katriel in :gh:" +"`105292`.)" +msgstr "" +"Adiciona um novo parâmetro somente-nomeado *show_group* a :meth:`." +"TracebackException.format_exception_only` para formatar (recursivamente) as " +"exceções aninhadas de uma instância :exc:`BaseExceptionGroup`. (Contribuição " +"de Irit Katriel em :gh:`105292`.)" + +#: ../../whatsnew/3.13.rst:1389 msgid "types" msgstr "types" -#: ../../whatsnew/3.13.rst:1242 +#: ../../whatsnew/3.13.rst:1391 msgid "" -":class:`~types.SimpleNamespace` constructor now allows specifying initial " -"values of attributes as a positional argument which must be a mapping or an " -"iterable of key-value pairs. (Contributed by Serhiy Storchaka in :gh:" +":class:`~types.SimpleNamespace` can now take a single positional argument to " +"initialise the namespace's arguments. This argument must either be a mapping " +"or an iterable of key-value pairs. (Contributed by Serhiy Storchaka in :gh:" "`108191`.)" msgstr "" -"O construtor :class:`~types.SimpleNamespace` agora permite especificar " -"valores iniciais de atributos como um argumento posicional que deve ser um " -"mapeamento ou um iterável de pares chave-valor. (Contribuição de Serhiy " -"Storchaka em :gh:`108191`.)" +":class:`~types.SimpleNamespace` agora pode receber um único argumento " +"posicional para inicializar os argumentos do espaço de nomes. Este argumento " +"deve ser um mapeamento ou um iterável de pares chave-valor. (Contribuição de " +"Serhiy Storchaka em :gh:`108191`.)" -#: ../../whatsnew/3.13.rst:1248 ../../whatsnew/3.13.rst:1492 +#: ../../whatsnew/3.13.rst:1398 ../../whatsnew/3.13.rst:1778 msgid "typing" msgstr "typing" -#: ../../whatsnew/3.13.rst:1250 +#: ../../whatsnew/3.13.rst:1400 msgid "" -"Add :func:`typing.get_protocol_members` to return the set of members " -"defining a :class:`typing.Protocol`. Add :func:`typing.is_protocol` to check " -"whether a class is a :class:`typing.Protocol`. (Contributed by Jelle " -"Zijlstra in :gh:`104873`.)" +":pep:`705`: Add :data:`~typing.ReadOnly`, a special typing construct to mark " +"a :class:`~typing.TypedDict` item as read-only for type checkers." msgstr "" -"Adiciona :func:`typing.get_protocol_members` para retornar o conjunto de " -"membros que definem um :class:`typing.Protocol`. Adiciona :func:`typing." -"is_protocol` para verificar se uma classe é um :class:`typing.Protocol`. " -"(Contribuição de Jelle Zijlstra em :gh:`104873`.)" +":pep:`705`: adiciona :data:`~typing.ReadOnly`, uma construção especial de " +"tipagem para marcar um item :class:`~typing.TypedDict` como somente leitura " +"para verificadores de tipo." -#: ../../whatsnew/3.13.rst:1255 +#: ../../whatsnew/3.13.rst:1403 msgid "" -"Add :data:`typing.ReadOnly`, a special typing construct to mark an item of " -"a :class:`typing.TypedDict` as read-only for type checkers. See :pep:`705` " -"for more details." +":pep:`742`: Add :data:`~typing.TypeIs`, a typing construct that can be used " +"to instruct a type checker how to narrow a type." msgstr "" -"Adiciona :data:`typing.ReadOnly`, uma construção especial do typing para " -"marcar um item de :class:`typing.TypedDict` como somente leitura para " -"verificadores de tipo. Veja :pep:`705` para mais detalhes." +":pep:`742`: adiciona :data:`~typing.TypeIs`, uma construção de tipagem que " +"pode ser usada para instruir um verificador de tipos sobre como restringir " +"um tipo." -#: ../../whatsnew/3.13.rst:1259 +#: ../../whatsnew/3.13.rst:1406 msgid "" -"Add :data:`typing.NoDefault`, a sentinel object used to represent the " +"Add :data:`~typing.NoDefault`, a sentinel object used to represent the " "defaults of some parameters in the :mod:`typing` module. (Contributed by " "Jelle Zijlstra in :gh:`116126`.)" msgstr "" -"Adiciona :data:`typing.NoDefault`, um objeto sinalizador usado para " +"Adiciona :data:`~typing.NoDefault`, um objeto sinalizador usado para " "representar os padrões de alguns parâmetros no módulo :mod:`typing`. " "(Contribuição de Jelle Zijlstra em :gh:`116126`.)" -#: ../../whatsnew/3.13.rst:1264 +#: ../../whatsnew/3.13.rst:1410 +msgid "" +"Add :func:`~typing.get_protocol_members` to return the set of members " +"defining a :class:`typing.Protocol`. (Contributed by Jelle Zijlstra in :gh:" +"`104873`.)" +msgstr "" +"Adicione :func:`~typing.get_protocol_members` para retornar o conjunto de " +"membros que definem uma :class:`typing.Protocol`. (Contribuição de Jelle " +"Zijlstra em :gh:`104873`.)" + +#: ../../whatsnew/3.13.rst:1414 +msgid "" +"Add :func:`~typing.is_protocol` to check whether a class is a :class:" +"`~typing.Protocol`. (Contributed by Jelle Zijlstra in :gh:`104873`.)" +msgstr "" +"Adiciona :func:`~typing.is_protocol` para verificar se uma classe é uma :" +"class:`~typing.Protocol`. (Contribuição de Jelle Zijlstra em :gh:`104873`.)" + +#: ../../whatsnew/3.13.rst:1418 +msgid "" +":data:`~typing.ClassVar` can now be nested in :data:`~typing.Final`, and " +"vice versa. (Contributed by Mehdi Drissi in :gh:`89547`.)" +msgstr "" +":data:`~typing.ClassVar` agora pode ser aninhado em :data:`~typing.Final`, e " +"vice-versa. (Contribuição de Mehdi Drissi em :gh:`89547`.)" + +#: ../../whatsnew/3.13.rst:1424 msgid "unicodedata" msgstr "unicodedata" -#: ../../whatsnew/3.13.rst:1266 +#: ../../whatsnew/3.13.rst:1426 msgid "" -"The Unicode database has been updated to version 15.1.0. (Contributed by " -"James Gerity in :gh:`109559`.)" +"Update the Unicode database to `version 15.1.0`__. (Contributed by James " +"Gerity in :gh:`109559`.)" msgstr "" -"O banco de dados Unicode foi atualizado para a versão 15.1.0. (Contribuição " -"de James Gerity em :gh:`109559`.)" +"Atualiza o banco de dados Unicode para a `versão 15.1.0`__. (Contribuição de " +"James Gerity em :gh:`109559`.)" -#: ../../whatsnew/3.13.rst:1270 +#: ../../whatsnew/3.13.rst:1433 msgid "venv" msgstr "venv" -#: ../../whatsnew/3.13.rst:1272 +#: ../../whatsnew/3.13.rst:1435 msgid "" -"Add support for adding source control management (SCM) ignore files to a " +"Add support for creating source control management (SCM) ignore files in a " "virtual environment's directory. By default, Git is supported. This is " -"implemented as opt-in via the API which can be extended to support other " -"SCMs (:class:`venv.EnvBuilder` and :func:`venv.create`), and opt-out via the " -"CLI (using ``--without-scm-ignore-files``). (Contributed by Brett Cannon in :" -"gh:`108125`.)" +"implemented as opt-in via the API, which can be extended to support other " +"SCMs (:class:`~venv.EnvBuilder` and :func:`~venv.create`), and opt-out via " +"the CLI, using :option:`!--without-scm-ignore-files`. (Contributed by Brett " +"Cannon in :gh:`108125`.)" msgstr "" -"Adiciona suporte para adicionar arquivos ignorados pelo gerenciamento de " -"controle de fontes (SCM) ao diretório de um ambiente virtual. Por padrão, o " +"Adiciona suporte para criar arquivos ignorados pelo gerenciamento de " +"controle de fontes (SCM) no diretório de um ambiente virtual. Por padrão, o " "Git é compatível. Isso está implementado como ativado por padrão por meio da " "API, que pode ser estendido para oferecer suporte a outros SCMs (:class:" -"`venv.EnvBuilder` e :func:`venv.create`) e desativado por padrão por meio da " -"CLI (usando ``--without-scm-ignore-files``). (Contribuição de Brett Cannon " -"em :gh:`108125`.)" +"`~venv.EnvBuilder` e :func:`~venv.create`) e desativado por padrão por meio " +"da CLI, usando :option:`!--without-scm-ignore-files`. (Contribuição de Brett " +"Cannon em :gh:`108125`.)" -#: ../../whatsnew/3.13.rst:1280 +#: ../../whatsnew/3.13.rst:1446 msgid "warnings" -msgstr "warnings" +msgstr "avisos" -#: ../../whatsnew/3.13.rst:1282 +#: ../../whatsnew/3.13.rst:1448 msgid "" -"The new :func:`warnings.deprecated` decorator provides a way to communicate " -"deprecations to :term:`static type checkers ` and to " -"warn on usage of deprecated classes and functions. A runtime deprecation " -"warning may also be emitted when a decorated function or class is used at " -"runtime. See :pep:`702`. (Contributed by Jelle Zijlstra in :gh:`104003`.)" +":pep:`702`: The new :func:`warnings.deprecated` decorator provides a way to " +"communicate deprecations to a :term:`static type checker` and to warn on " +"usage of deprecated classes and functions. A :exc:`DeprecationWarning` may " +"also be emitted when a decorated function or class is used at runtime. " +"(Contributed by Jelle Zijlstra in :gh:`104003`.)" msgstr "" -"O novo decorador :func:`warnings.deprecated` fornece uma maneira de " -"comunicar descontinuações para :term:`verificadores de tipo estático ` e avisar sobre o uso de classes e funções obsoletas. Um aviso " -"de descontinuação do tempo de execução também pode ser emitido quando uma " -"função ou classe decorada é usada em tempo de execução. Veja :pep:`702`. " -"(Contribuição de Jelle Zijlstra em :gh:`104003`.)" +":pep:`702`: O novo decorador :func:`warnings.deprecated` fornece uma maneira " +"de comunicar descontinuações para um :term:`verificador de tipo estático` e " +"avisar sobre o uso de classes e funções obsoletas. Um :exc:" +"`DeprecationWarning` também pode ser emitido quando uma função ou classe " +"decorada é usada em tempo de execução. (Contribuição de Jelle Zijlstra em :" +"gh:`104003`.)" -#: ../../whatsnew/3.13.rst:1289 -msgid "xml.etree.ElementTree" -msgstr "xml.etree.ElementTree" +#: ../../whatsnew/3.13.rst:1457 +msgid "xml" +msgstr "xml" -#: ../../whatsnew/3.13.rst:1291 +#: ../../whatsnew/3.13.rst:1459 msgid "" -"Add the :meth:`!close` method for the iterator returned by :func:`~xml.etree." -"ElementTree.iterparse` for explicit cleaning up. (Contributed by Serhiy " -"Storchaka in :gh:`69893`.)" +"Allow controlling Expat >=2.6.0 reparse deferral (:cve:`2023-52425`) by " +"adding five new methods:" msgstr "" -"Adiciona o método :meth:`!close` para o iterador retornado por :func:`~xml." -"etree.ElementTree.iterparse` para limpeza explícita. (Contribuição de Serhiy " -"Storchaka em :gh:`69893`.)" +"Permite controlar o adiamento da nova análise do Expat >=2.6.0 (:cve:" +"`2023-52425`) adicionando cinco novos métodos:" -#: ../../whatsnew/3.13.rst:1296 -msgid "zipimport" -msgstr "zipimport" +#: ../../whatsnew/3.13.rst:1462 +msgid ":meth:`xml.etree.ElementTree.XMLParser.flush`" +msgstr ":meth:`xml.etree.ElementTree.XMLParser.flush`" -#: ../../whatsnew/3.13.rst:1298 -msgid "" -"Gains support for ZIP64 format files. Everybody loves huge code right? " -"(Contributed by Tim Hatch in :gh:`94146`.)" -msgstr "" -"Obtém suporte para arquivos no formato ZIP64. Todo mundo adora códigos " -"enormes, certo? (Contribuição de Tim Hatch em :gh:`94146`.)" +#: ../../whatsnew/3.13.rst:1463 +msgid ":meth:`xml.etree.ElementTree.XMLPullParser.flush`" +msgstr ":meth:`xml.etree.ElementTree.XMLPullParser.flush`" -#: ../../whatsnew/3.13.rst:1304 -msgid "Optimizations" -msgstr "Otimizações" +#: ../../whatsnew/3.13.rst:1464 +msgid ":meth:`xml.parsers.expat.xmlparser.GetReparseDeferralEnabled`" +msgstr ":meth:`xml.parsers.expat.xmlparser.GetReparseDeferralEnabled`" -#: ../../whatsnew/3.13.rst:1306 +#: ../../whatsnew/3.13.rst:1465 +msgid ":meth:`xml.parsers.expat.xmlparser.SetReparseDeferralEnabled`" +msgstr ":meth:`xml.parsers.expat.xmlparser.SetReparseDeferralEnabled`" + +#: ../../whatsnew/3.13.rst:1466 +msgid ":meth:`!xml.sax.expatreader.ExpatParser.flush`" +msgstr ":meth:`!xml.sax.expatreader.ExpatParser.flush`" + +#: ../../whatsnew/3.13.rst:1468 +msgid "(Contributed by Sebastian Pipping in :gh:`115623`.)" +msgstr "(Contribuição de Sebastian Pipping em :gh:`115623`.)" + +#: ../../whatsnew/3.13.rst:1470 msgid "" -":func:`textwrap.indent` is now ~30% faster than before for large input. " -"(Contributed by Inada Naoki in :gh:`107369`.)" +"Add the :meth:`!close` method for the iterator returned by :func:`~xml.etree." +"ElementTree.iterparse` for explicit cleanup. (Contributed by Serhiy " +"Storchaka in :gh:`69893`.)" msgstr "" -":func:`textwrap.indent` agora é cerca de 30% mais rápido do que antes para " -"entradas grandes. (Contribuição de Inada Naoki em :gh:`107369`.)" +"Adiciona o método :meth:`!close` para o iterador retornado por :func:`~xml." +"etree.ElementTree.iterparse` para limpeza explícita. (Contribuição de Serhiy " +"Storchaka em :gh:`69893`.)" + +#: ../../whatsnew/3.13.rst:1476 +msgid "zipimport" +msgstr "zipimport" -#: ../../whatsnew/3.13.rst:1309 +#: ../../whatsnew/3.13.rst:1478 msgid "" -"The :mod:`subprocess` module uses :func:`os.posix_spawn` in more situations " -"including the default where ``close_fds=True`` on many modern platforms. " -"This should provide a noteworthy performance increase launching processes on " -"FreeBSD and Solaris. See the :ref:`subprocess ` " -"section above for details. (Contributed by Jakub Kulik in :gh:`113117`.)" +"Add support for ZIP64_ format files. Everybody loves huge data, right? " +"(Contributed by Tim Hatch in :gh:`94146`.)" msgstr "" -"O módulo :mod:`subprocess` usa :func:`os.posix_spawn` em mais situações, " -"incluindo o padrão sendo ``close_fds=True`` em muitas plataformas modernas. " -"Isto deve fornecer um aumento notável de desempenho ao iniciar processos no " -"FreeBSD e Solaris. Veja a seção de :ref:`subprocess ` acima para detalhes. (Contribuição de Jakub Kulik em :gh:" -"`113117`.)" +"Adiciona suporte para arquivos no formato ZIP64_. Todo mundo adora dados " +"enormes, certo? (Contribuição de Tim Hatch em :gh:`94146`.)" -#: ../../whatsnew/3.13.rst:1316 +#: ../../whatsnew/3.13.rst:1486 +msgid "Optimizations" +msgstr "Otimizações" + +#: ../../whatsnew/3.13.rst:1488 msgid "" "Several standard library modules have had their import times significantly " "improved. For example, the import time of the :mod:`typing` module has been " "reduced by around a third by removing dependencies on :mod:`re` and :mod:" "`contextlib`. Other modules to enjoy import-time speedups include :mod:" -"`importlib.metadata`, :mod:`threading`, :mod:`enum`, :mod:`functools` and :" -"mod:`email.utils`. (Contributed by Alex Waygood, Shantanu Jain, Adam Turner, " -"Daniel Hollas and others in :gh:`109653`.)" +"`email.utils`, :mod:`enum`, :mod:`functools`, :mod:`importlib.metadata`, " +"and :mod:`threading`. (Contributed by Alex Waygood, Shantanu Jain, Adam " +"Turner, Daniel Hollas, and others in :gh:`109653`.)" msgstr "" "Vários módulos de biblioteca padrão tiveram seus tempos de importação " "significativamente melhorados. Por exemplo, o tempo de importação do módulo :" "mod:`typing` foi reduzido em cerca de um terço pela remoção de dependências " "em :mod:`re` e :mod:`contextlib`. Outros módulos para aproveitar a " -"aceleração no tempo de importação incluem :mod:`importlib.metadata`, :mod:" -"`threading`, :mod:`enum`, :mod:`functools` e :mod:`email.utils`. " -"(Contribuição de Alex Waygood, Shantanu Jain, Adam Turner, Daniel Hollas e " -"outros em :gh:`109653`.)" +"aceleração no tempo de importação incluem :mod:`email.utils`, :mod:`enum`, :" +"mod:`functools`, :mod:`importlib.metadata` e :mod:`threading`. (Contribuição " +"de Alex Waygood, Shantanu Jain, Adam Turner, Daniel Hollas e outros em :gh:" +"`109653`.)" + +#: ../../whatsnew/3.13.rst:1499 +msgid "" +":func:`textwrap.indent` is now around 30% faster than before for large " +"input. (Contributed by Inada Naoki in :gh:`107369`.)" +msgstr "" +":func:`textwrap.indent` agora é cerca de 30% mais rápido do que antes para " +"entradas grandes. (Contribuição de Inada Naoki em :gh:`107369`.)" + +#: ../../whatsnew/3.13.rst:1502 +msgid "" +"The :mod:`subprocess` module now uses the :func:`~os.posix_spawn` function " +"in more situations, including when *close_fds* is ``True`` (the default) on " +"many modern platforms. This should provide a notable performance increase " +"when launching processes on FreeBSD and Solaris. See the :ref:`subprocess " +"` section above for details. (Contributed by Jakub " +"Kulik in :gh:`113117`.)" +msgstr "" +"O módulo :mod:`subprocess` agora a função :func:`~os.posix_spawn` em mais " +"situações, incluindo quando *close_fds* é ``True`` (o padrão) em muitas " +"plataformas. Isto deve fornecer um aumento notável de desempenho ao iniciar " +"processos no FreeBSD e Solaris. Veja a seção de :ref:`subprocess " +"` acima para detalhes. (Contribuição de Jakub Kulik " +"em :gh:`113117`.)" -#: ../../whatsnew/3.13.rst:1326 +#: ../../whatsnew/3.13.rst:1512 msgid "Removed Modules And APIs" msgstr "Módulos e APIs removidas" -#: ../../whatsnew/3.13.rst:1331 -msgid "PEP 594: dead batteries (and other module removals)" -msgstr "PEP 594: baterias mortas (e remoção de outros módulos)" +#: ../../whatsnew/3.13.rst:1518 +msgid "PEP 594: Remove \"dead batteries\" from the standard library" +msgstr "PEP 594: remove \"baterias descarregadas\" da biblioteca padrão" -#: ../../whatsnew/3.13.rst:1333 +#: ../../whatsnew/3.13.rst:1520 msgid "" -":pep:`594` removed 19 modules from the standard library, deprecated in " -"Python 3.11:" +":pep:`594` proposed removing 19 modules from the standard library, " +"colloquially referred to as 'dead batteries' due to their historic, " +"obsolete, or insecure status. All of the following modules were deprecated " +"in Python 3.11, and are now removed:" msgstr "" -":pep:`594` removeu 19 módulos da biblioteca padrão, descontinuados no Python " -"3.11:" +":pep:`594` propôs remover 19 módulos da biblioteca padrão, coloquialmente " +"chamados de \"baterias descarregadas\" devido ao seu status histórico, " +"obsoleto ou inseguro. Todos os módulos a seguir foram descontinuados no " +"Python 3.11 e agora foram removidos:" -#: ../../whatsnew/3.13.rst:1336 -msgid ":mod:`!aifc`. (Contributed by Victor Stinner in :gh:`104773`.)" -msgstr ":mod:`!aifc`. (Contribuição de Victor Stinner em :gh:`104773`.)" +#: ../../whatsnew/3.13.rst:1526 +msgid ":mod:`!aifc`" +msgstr ":mod:`!aifc`" -#: ../../whatsnew/3.13.rst:1339 -msgid ":mod:`!audioop`. (Contributed by Victor Stinner in :gh:`104773`.)" -msgstr ":mod:`!audioop`. (Contribuição de Victor Stinner em :gh:`104773`.)" +#: ../../whatsnew/3.13.rst:1528 +msgid "" +":pypi:`standard-aifc`: Use the redistribution of ``aifc`` library from PyPI." +msgstr "" +":pypi:`standard-aifc`: Use a redistribuição da biblioteca ``aifc`` do PyPI." -#: ../../whatsnew/3.13.rst:1342 -msgid ":mod:`!chunk`. (Contributed by Victor Stinner in :gh:`104773`.)" -msgstr ":mod:`!chunk`. (Contribuição de Victor Stinner em :gh:`104773`.)" +#: ../../whatsnew/3.13.rst:1531 +msgid ":mod:`!audioop`" +msgstr ":mod:`!audioop`" -#: ../../whatsnew/3.13.rst:1345 -msgid ":mod:`!cgi` and :mod:`!cgitb`." -msgstr ":mod:`!cgi` e :mod:`!cgitb`." +#: ../../whatsnew/3.13.rst:1533 +msgid ":pypi:`audioop-lts`: Use ``audioop-lts`` library from PyPI." +msgstr ":pypi:`audioop-lts`: Use a biblioteca ``audioop-lts`` do PyPI." -#: ../../whatsnew/3.13.rst:1347 +#: ../../whatsnew/3.13.rst:1536 +msgid ":mod:`!chunk`" +msgstr ":mod:`!chunk`" + +#: ../../whatsnew/3.13.rst:1538 msgid "" -"``cgi.FieldStorage`` can typically be replaced with :func:`urllib.parse." -"parse_qsl` for ``GET`` and ``HEAD`` requests, and the :mod:`email.message` " -"module or :pypi:`multipart` PyPI project for ``POST`` and ``PUT``." +":pypi:`standard-chunk`: Use the redistribution of ``chunk`` library from " +"PyPI." msgstr "" -"``cgi.FieldStorage`` normalmente pode ser substituído por :func:`urllib." -"parse.parse_qsl` para solicitações ``GET`` e ``HEAD``, e o módulo :mod:" -"`email.message` ou projeto :pypi:`multipart` do PyPI para ``POST`` e ``PUT``." +":pypi:`standard-chunk`: Use a redistribuição da biblioteca ``chunk`` do PyPI." -#: ../../whatsnew/3.13.rst:1352 +#: ../../whatsnew/3.13.rst:1541 +msgid ":mod:`!cgi` and :mod:`!cgitb`" +msgstr ":mod:`!cgi` e :mod:`!cgitb`" + +#: ../../whatsnew/3.13.rst:1543 +msgid "" +":class:`!cgi.FieldStorage` can typically be replaced with :func:`urllib." +"parse.parse_qsl` for ``GET`` and ``HEAD`` requests, and the :mod:`email." +"message` module or the :pypi:`multipart` library for ``POST`` and ``PUT`` " +"requests." +msgstr "" +":class:`!cgi.FieldStorage` normalmente pode ser substituído por :func:" +"`urllib.parse.parse_qsl` para solicitações ``GET`` e ``HEAD``, e o módulo :" +"mod:`email.message` ou a biblioteca :pypi:`multipart` para solicitações " +"``POST`` e ``PUT``." + +#: ../../whatsnew/3.13.rst:1548 msgid "" -"``cgi.parse()`` can be replaced by calling :func:`urllib.parse.parse_qs` " -"directly on the desired query string, except for ``multipart/form-data`` " -"input, which can be handled as described for ``cgi.parse_multipart()``." +":func:`!cgi.parse` can be replaced by calling :func:`urllib.parse.parse_qs` " +"directly on the desired query string, unless the input is ``multipart/form-" +"data``, which should be replaced as described below for :func:`!cgi." +"parse_multipart`." msgstr "" -"``cgi.parse()`` pode ser substituída chamando :func:`urllib.parse.parse_qs` " -"diretamente na string de consulta desejada, exceto para a entrada " -"``multipart/form-data``, que pode ser tratada conforme descrito para ``cgi." -"parse_multipart()``." +":func:`!cgi.parse` pode ser substituído chamando :func:`urllib.parse." +"parse_qs` diretamente na string de consulta desejada, a menos que a entrada " +"seja ``multipart/form-data``, que deve ser substituída conforme descrito " +"abaixo para :func:`!cgi.parse_multipart`." -#: ../../whatsnew/3.13.rst:1356 +#: ../../whatsnew/3.13.rst:1553 msgid "" -"``cgi.parse_header()`` can be replaced with the functionality in the :mod:" +":func:`!cgi.parse_header` can be replaced with the functionality in the :mod:" "`email` package, which implements the same MIME RFCs. For example, with :" +"class:`email.message.EmailMessage`:" +msgstr "" +":func:`!cgi.parse_header` pode ser substituído pela funcionalidade do " +"pacote :mod:`email`, que implementa os mesmos RFCs MIME. Por exemplo, com :" "class:`email.message.EmailMessage`::" + +#: ../../whatsnew/3.13.rst:1557 +msgid "" +"from email.message import EmailMessage\n" +"\n" +"msg = EmailMessage()\n" +"msg['content-type'] = 'application/json; charset=\"utf8\"'\n" +"main, params = msg.get_content_type(), msg['content-type'].params" msgstr "" -"``cgi.parse_header()`` pode ser substituído pela funcionalidade do pacote :" -"mod:`email`, que implementa os mesmos RFCs MIME. Por exemplo, com :class:" -"`email.message.EmailMessage`::" +"from email.message import EmailMessage\n" +"\n" +"msg = EmailMessage()\n" +"msg['content-type'] = 'application/json; charset=\"utf8\"'\n" +"main, params = msg.get_content_type(), msg['content-type'].params" -#: ../../whatsnew/3.13.rst:1365 +#: ../../whatsnew/3.13.rst:1565 msgid "" -"``cgi.parse_multipart()`` can be replaced with the functionality in the :mod:" -"`email` package (e.g. :class:`email.message.EmailMessage` and :class:`email." -"message.Message`) which implements the same MIME RFCs, or with the :pypi:" -"`multipart` PyPI project." +":func:`!cgi.parse_multipart` can be replaced with the functionality in the :" +"mod:`email` package, which implements the same MIME RFCs, or with the :pypi:" +"`multipart` library. For example, the :class:`email.message.EmailMessage` " +"and :class:`email.message.Message` classes." msgstr "" -"``cgi.parse_multipart()`` pode ser substituída pela funcionalidade do " -"pacote :mod:`email` (por exemplo :class:`email.message.EmailMessage` e :" -"class:`email.message.Message`) que implementa os mesmos RFCs MIME, ou com o " -"projeto :pypi:`multipart` do PyPI." +":func:`!cgi.parse_multipart` pode ser substituído pela funcionalidade no " +"pacote :mod:`email`, que implementa os mesmos RFCs de MIME, ou pela " +"biblioteca :pypi:`multipart`. Por exemplo, as classes :class:`email.message." +"EmailMessage` e :class:`email.message.Message`." -#: ../../whatsnew/3.13.rst:1370 ../../whatsnew/3.13.rst:1388 -msgid "(Contributed by Victor Stinner in :gh:`104773`.)" -msgstr "(Contribuição de Victor Stinner em :gh:`104773`.)" +#: ../../whatsnew/3.13.rst:1571 +msgid "" +":pypi:`standard-cgi`: and :pypi:`standard-cgitb`: Use the redistribution of " +"``cgi`` and ``cgitb`` library from PyPI." +msgstr "" +":pypi:`standard-cgi`: e :pypi:`standard-cgitb`: Use a redistribuição das " +"bibliotecas ``cgi`` e ``cgitb`` do PyPI." -#: ../../whatsnew/3.13.rst:1372 +#: ../../whatsnew/3.13.rst:1574 msgid "" -":mod:`!crypt` module and its private :mod:`!_crypt` extension. The :mod:" -"`hashlib` module is a potential replacement for certain use cases. " -"Otherwise, the following PyPI projects can be used:" +":mod:`!crypt` and the private :mod:`!_crypt` extension. The :mod:`hashlib` " +"module may be an appropriate replacement when simply hashing a value is " +"required. Otherwise, various third-party libraries on PyPI are available:" msgstr "" -"Módulo :mod:`!crypt` e sua extensão privada :mod:`!_crypt`. O módulo :mod:" -"`hashlib` é um substituto potencial para certos casos de uso. Caso " -"contrário, os seguintes projetos PyPI podem ser usados:" +":mod:`!crypt` e a extensão privada :mod:`!_crypt`. O módulo :mod:`hashlib` " +"pode ser uma substituição apropriada quando simplesmente fazer hash de um " +"valor é necessário. Caso contrário, várias bibliotecas de terceiros no PyPI " +"estão disponíveis:" -#: ../../whatsnew/3.13.rst:1376 +#: ../../whatsnew/3.13.rst:1579 msgid "" ":pypi:`bcrypt`: Modern password hashing for your software and your servers." msgstr "" -":pypi:`bcrypt`: Hashing de senha moderno para seu software e servidores." +":pypi:`bcrypt`: hashing de senha moderno para seu software e servidores." -#: ../../whatsnew/3.13.rst:1378 +#: ../../whatsnew/3.13.rst:1581 msgid "" ":pypi:`passlib`: Comprehensive password hashing framework supporting over 30 " "schemes." msgstr "" -":pypi:`passlib`: Framework abrangente de hash de senha com suporte para mais " +":pypi:`passlib`: framework abrangente de hash de senha com suporte para mais " "de 30 esquemas." -#: ../../whatsnew/3.13.rst:1380 +#: ../../whatsnew/3.13.rst:1583 msgid ":pypi:`argon2-cffi`: The secure Argon2 password hashing algorithm." -msgstr ":pypi:`argon2-cffi`: O algoritmo seguro de hashing de senha Argon2." +msgstr ":pypi:`argon2-cffi`: algoritmo seguro de hashing de senha Argon2." -#: ../../whatsnew/3.13.rst:1382 +#: ../../whatsnew/3.13.rst:1585 msgid "" ":pypi:`legacycrypt`: :mod:`ctypes` wrapper to the POSIX crypt library call " "and associated functionality." msgstr "" -":pypi:`legacycrypt`: Envólucro ao :mod:`ctypes` para a chamada POSIX da " +":pypi:`legacycrypt`: envólucro ao :mod:`ctypes` para a chamada POSIX da " "biblioteca de criptografia e funcionalidade associada." -#: ../../whatsnew/3.13.rst:1384 +#: ../../whatsnew/3.13.rst:1588 msgid "" ":pypi:`crypt_r`: Fork of the :mod:`!crypt` module, wrapper to the :manpage:" "`crypt_r(3)` library call and associated functionality." msgstr "" -":pypi:`crypt_r`: Fork do módulo :mod:`!crypt`, um envólucro para a chamada " +":pypi:`crypt_r`: fork do módulo :mod:`!crypt`, um envólucro para a chamada " "da biblioteca :manpage:`crypt_r(3)` e funcionalidade associada." -#: ../../whatsnew/3.13.rst:1390 +#: ../../whatsnew/3.13.rst:1592 +msgid "" +":pypi:`standard-crypt` and :pypi:`deprecated-crypt-alternative`: Use the " +"redistribution of ``crypt`` and reimplementation of ``_crypt`` libraries " +"from PyPI." +msgstr "" +":pypi:`standard-crypt` e :pypi:`deprecated-crypt-alternative`: Use a " +"redistribuição de ``crypt`` e a reimplementação das bibliotecas ``_crypt`` " +"do PyPI." + +#: ../../whatsnew/3.13.rst:1595 +msgid "" +":mod:`!imghdr`: The :pypi:`filetype`, :pypi:`puremagic`, or :pypi:`python-" +"magic` libraries should be used as replacements. For example, the :func:`!" +"puremagic.what` function can be used to replace the :func:`!imghdr.what` " +"function for all file formats that were supported by :mod:`!imghdr`." +msgstr "" +":mod:`!imghdr`: as bibliotecas :pypi:`filetype`, :pypi:`puremagic` ou :pypi:" +"`python-magic` devem ser usadas como substituições. Por exemplo, a função :" +"func:`!puremagic.what` pode ser usada para substituir a função :func:`!" +"imghdr.what` para todos os formatos de arquivo que tinham suporte de :mod:`!" +"imghdr`." + +#: ../../whatsnew/3.13.rst:1602 msgid "" -":mod:`!imghdr`: use the projects :pypi:`filetype`, :pypi:`puremagic`, or :" -"pypi:`python-magic` instead. The ``puremagic.what()`` function can be used " -"to replace the ``imghdr.what()`` function for all file formats that were " -"supported by ``imghdr``. (Contributed by Victor Stinner in :gh:`104773`.)" +":pypi:`standard-imghdr`: Use the redistribution of ``imghdr`` library from " +"PyPI." msgstr "" -":mod:`!imghdr`: use os projetos :pypi:`filetype`, :pypi:`puremagic` ou :pypi:" -"`python-magic`. A função ``puremagic.what()`` pode ser usada para substituir " -"a função ``imghdr.what()`` para todos os formatos de arquivo que eram " -"suportados por ``imghdr``. (Contribuição de Victor Stinner em :gh:`104773`.)" +":pypi:`standard-imghdr`: Use a redistribuição da biblioteca ``imghdr`` do " +"PyPI." -#: ../../whatsnew/3.13.rst:1397 +#: ../../whatsnew/3.13.rst:1605 +msgid ":mod:`!mailcap`: Use the :mod:`mimetypes` module instead." +msgstr ":mod:`!mailcap`: use o módulo :mod:`mimetypes`." + +#: ../../whatsnew/3.13.rst:1608 msgid "" -":mod:`!mailcap`. The :mod:`mimetypes` module provides an alternative. " -"(Contributed by Victor Stinner in :gh:`104773`.)" +":pypi:`standard-mailcap`: Use the redistribution of ``mailcap`` library from " +"PyPI." msgstr "" -":mod:`!mailcap`. O módulo :mod:`mimetypes` fornece uma alternativa. " -"(Contribuição de Victor Stinner em :gh:`104773`.)" +":pypi:`standard-mailcap`: Use a redistribuição da biblioteca ``mailcap`` do " +"PyPI." + +#: ../../whatsnew/3.13.rst:1611 +msgid ":mod:`!msilib`" +msgstr ":mod:`!msilib`" -#: ../../whatsnew/3.13.rst:1401 -msgid ":mod:`!msilib`. (Contributed by Zachary Ware in :gh:`104773`.)" -msgstr ":mod:`!msilib`. (Contribuição de Zachary Ware em :gh:`104773`.)" +#: ../../whatsnew/3.13.rst:1612 +msgid ":mod:`!nis`" +msgstr ":mod:`!nis`" -#: ../../whatsnew/3.13.rst:1404 -msgid ":mod:`!nis`. (Contributed by Victor Stinner in :gh:`104773`.)" -msgstr ":mod:`!nis`. (Contribuição de Victor Stinner em :gh:`104773`.)" +#: ../../whatsnew/3.13.rst:1613 +msgid ":mod:`!nntplib`: Use the :pypi:`pynntp` library from PyPI instead." +msgstr ":mod:`!nntplib`: use a biblioteca :pypi:`pynntp` do PyPI." -#: ../../whatsnew/3.13.rst:1407 +#: ../../whatsnew/3.13.rst:1616 msgid "" -":mod:`!nntplib`: the :pypi:`nntplib` PyPI project can be used instead. " -"(Contributed by Victor Stinner in :gh:`104773`.)" +":pypi:`standard-nntplib`: Use the redistribution of ``nntplib`` library from " +"PyPI." msgstr "" -":mod:`!nntplib`: o projeto :pypi:`nntplib` do PyPI pode ser usado em seu " -"lugar. (Contribuição de Victor Stinner em :gh:`104773`.)" +":pypi:`standard-nntplib`: Use a redistribuição da biblioteca ``nntplib`` do " +"PyPI." -#: ../../whatsnew/3.13.rst:1411 +#: ../../whatsnew/3.13.rst:1619 msgid "" -":mod:`!ossaudiodev`: use the `pygame project `_ for " -"audio playback. (Contributed by Victor Stinner in :gh:`104780`.)" +":mod:`!ossaudiodev`: For audio playback, use the :pypi:`pygame` library from " +"PyPI instead." msgstr "" -":mod:`!ossaudiodev`: use o `projeto pygame `_ para " -"reprodução de áudio. (Contribuição de Victor Stinner em :gh:`104780`.)" +":mod:`!ossaudiodev`: para reprodução de áudio, use a biblioteca :pypi:" +"`pygame` do PyPI." -#: ../../whatsnew/3.13.rst:1415 +#: ../../whatsnew/3.13.rst:1621 msgid "" -":mod:`!pipes`: use the :mod:`subprocess` module instead. (Contributed by " -"Victor Stinner in :gh:`104773`.)" +":mod:`!pipes`: Use the :mod:`subprocess` module instead. Use :func:`shlex." +"quote` to replace the undocumented ``pipes.quote`` function." msgstr "" -":mod:`!pipes`: use o módulo :mod:`subprocess`. (Contribuição de Victor " -"Stinner em :gh:`104773`.)" +":mod:`!pipes`: Use o módulo :mod:`subprocess` em vez disso. Use :func:`shlex." +"quote` para substituir a função não documentada ``pipes.quote``." -#: ../../whatsnew/3.13.rst:1418 +#: ../../whatsnew/3.13.rst:1626 msgid "" -":mod:`!sndhdr`: use the projects :pypi:`filetype`, :pypi:`puremagic`, or :" -"pypi:`python-magic` instead. (Contributed by Victor Stinner in :gh:`104773`.)" +":pypi:`standard-pipes`: Use the redistribution of ``pipes`` library from " +"PyPI." msgstr "" -":mod:`!sndhdr`: use os projetos :pypi:`filetype`, :pypi:`puremagic` ou :pypi:" -"`python-magic`. (Contribuição de Victor Stinner em :gh:`104773`.)" +":pypi:`standard-pipes`: Use a redistribuição da biblioteca ``pipes`` do PyPI." -#: ../../whatsnew/3.13.rst:1422 +#: ../../whatsnew/3.13.rst:1629 msgid "" -":mod:`!spwd`: the :pypi:`python-pam` project can be used instead. " -"(Contributed by Victor Stinner in :gh:`104773`.)" +":mod:`!sndhdr`: The :pypi:`filetype`, :pypi:`puremagic`, or :pypi:`python-" +"magic` libraries should be used as replacements." msgstr "" -":mod:`!spwd`: o projeto :pypi:`python-pam` pode ser usado em seu lugar. " -"(Contribuição de Victor Stinner em :gh:`104773`.)" +":mod:`!sndhdr`: as bibliotecas :pypi:`filetype`, :pypi:`puremagic` ou :pypi:" +"`python-magic` devem ser usadas como substitutas." -#: ../../whatsnew/3.13.rst:1426 -msgid ":mod:`!sunau`. (Contributed by Victor Stinner in :gh:`104773`.)" -msgstr ":mod:`!sunau`. (Contribuição de Victor Stinner em :gh:`104773`.)" +#: ../../whatsnew/3.13.rst:1633 +msgid "" +":pypi:`standard-sndhdr`: Use the redistribution of ``sndhdr`` library from " +"PyPI." +msgstr "" +":pypi:`standard-sndhdr`: Use a redistribuição da biblioteca ``sndhdr`` do " +"PyPI." + +#: ../../whatsnew/3.13.rst:1636 +msgid ":mod:`!spwd`: Use the :pypi:`python-pam` library from PyPI instead." +msgstr ":mod:`!spwd`: use a biblioteca :pypi:`python-pam` do PyPI." -#: ../../whatsnew/3.13.rst:1429 +#: ../../whatsnew/3.13.rst:1638 +msgid ":mod:`!sunau`" +msgstr ":mod:`!sunau`" + +#: ../../whatsnew/3.13.rst:1640 msgid "" -":mod:`!telnetlib`, use the projects :pypi:`telnetlib3` or :pypi:`Exscript` " -"instead. (Contributed by Victor Stinner in :gh:`104773`.)" +":pypi:`standard-sunau`: Use the redistribution of ``sunau`` library from " +"PyPI." msgstr "" -":mod:`!telnetlib`, use os projetos :pypi:`telnetlib3` ou :pypi:`Exscript`. " -"(Contribuição de Victor Stinner em :gh:`104773`.)" +":pypi:`standard-sunau`: Use a redistribuição da biblioteca ``sunau`` do PyPI." -#: ../../whatsnew/3.13.rst:1433 +#: ../../whatsnew/3.13.rst:1643 +msgid "" +":mod:`!telnetlib`, Use the :pypi:`telnetlib3` or :pypi:`Exscript` libraries " +"from PyPI instead." +msgstr "" +":mod:`!telnetlib`: use as bibliotecas :pypi:`telnetlib3` ou :pypi:`Exscript` " +"do PyPI." + +#: ../../whatsnew/3.13.rst:1646 +msgid "" +":pypi:`standard-telnetlib`: Use the redistribution of ``telnetlib`` library " +"from PyPI." +msgstr "" +":pypi:`standard-telnetlib`: Use a redistribuição da biblioteca ``telnetlib`` " +"do PyPI." + +#: ../../whatsnew/3.13.rst:1649 +msgid "" +":mod:`!uu`: Use the :mod:`base64` module instead, as a modern alternative." +msgstr ":mod:`!uu`: use o módulo :mod:`base64` como uma alternativa moderna." + +#: ../../whatsnew/3.13.rst:1652 msgid "" -":mod:`!uu`: the :mod:`base64` module is a modern alternative. (Contributed " -"by Victor Stinner in :gh:`104773`.)" +":pypi:`standard-uu`: Use the redistribution of ``uu`` library from PyPI." msgstr "" -":mod:`!uu`: o módulo :mod:`base64` é uma alternativa moderna. (Contribuição " -"de Victor Stinner em :gh:`104773`.)" +":pypi:`standard-uu`: Use a redistribuição da biblioteca ``uu`` do PyPI." -#: ../../whatsnew/3.13.rst:1436 -msgid ":mod:`!xdrlib`. (Contributed by Victor Stinner in :gh:`104773`.)" -msgstr ":mod:`!xdrlib`. (Contribuição de Victor Stinner em :gh:`104773`.)" +#: ../../whatsnew/3.13.rst:1655 +msgid ":mod:`!xdrlib`" +msgstr ":mod:`!xdrlib`" -#: ../../whatsnew/3.13.rst:1439 +#: ../../whatsnew/3.13.rst:1657 msgid "" -"Remove the ``2to3`` program and the :mod:`!lib2to3` module, deprecated in " -"Python 3.11. (Contributed by Victor Stinner in :gh:`104780`.)" +":pypi:`standard-xdrlib`: Use the redistribution of ``xdrlib`` library from " +"PyPI." msgstr "" -"Remove o programa ``2to3`` e o módulo :mod:`!lib2to3`, descontinuados no " -"Python 3.11. (Contribuição de Victor Stinner em :gh:`104780`.)" +":pypi:`standard-xdrlib`: Use a redistribuição da biblioteca ``xdrlib`` do " +"PyPI." -#: ../../whatsnew/3.13.rst:1443 +#: ../../whatsnew/3.13.rst:1660 msgid "" -"Remove the :mod:`!tkinter.tix` module, deprecated in Python 3.6. The third-" -"party Tix library which the module wrapped is unmaintained. (Contributed by " -"Zachary Ware in :gh:`75552`.)" +"(Contributed by Victor Stinner and Zachary Ware in :gh:`104773` and :gh:" +"`104780`.)" msgstr "" -"Remove o módulo :mod:`!tkinter.tix`, descontinuado no Python 3.6. A " -"biblioteca Tix de terceiros que o módulo empacota não é mantida. " -"(Contribuição de Zachary Ware em :gh:`75552`.)" +"(Contribuição de Victor Stinner e Zachary Ware em :gh:`104773` e :gh:" +"`104780`.)" -#: ../../whatsnew/3.13.rst:1448 -msgid "configparser" -msgstr "configparser" +#: ../../whatsnew/3.13.rst:1664 +msgid "2to3" +msgstr "2to3" + +#: ../../whatsnew/3.13.rst:1666 +msgid "" +"Remove the :program:`2to3` program and the :mod:`!lib2to3` module, " +"previously deprecated in Python 3.11. (Contributed by Victor Stinner in :gh:" +"`104780`.)" +msgstr "" +"Remove o programa :program:`2to3` e o módulo :mod:`!lib2to3`, já " +"descontinuados no Python 3.11. (Contribuição de Victor Stinner em :gh:" +"`104780`.)" + +#: ../../whatsnew/3.13.rst:1672 +msgid "builtins" +msgstr "builtins" + +#: ../../whatsnew/3.13.rst:1674 +msgid "" +"Remove support for chained :class:`classmethod` descriptors (introduced in :" +"gh:`63272`). These can no longer be used to wrap other descriptors, such as :" +"class:`property`. The core design of this feature was flawed and led to " +"several problems. To \"pass-through\" a :class:`classmethod`, consider using " +"the :attr:`!__wrapped__` attribute that was added in Python 3.10. " +"(Contributed by Raymond Hettinger in :gh:`89519`.)" +msgstr "" +"Remove suporte aos descritores :class:`classmethod` encadeados (introduzidos " +"em :gh:`63272`). Eles não podem mais serem usados para agrupar outros " +"descritores como :class:`property`. O design central desse recurso " +"apresentava falhas e levou a problemas. Para \"passar\" um :class:" +"`classmethod`, considere usar o atributo :attr:`!__wrapped__` que foi " +"adicionado no Python 3.10. (Contribuição de Raymond Hettinger em :gh:" +"`89519`.)" -#: ../../whatsnew/3.13.rst:1450 +#: ../../whatsnew/3.13.rst:1683 msgid "" -"Remove the undocumented :class:`!configparser.LegacyInterpolation` class, " -"deprecated in the docstring since Python 3.2, and with a deprecation warning " -"since Python 3.11. (Contributed by Hugo van Kemenade in :gh:`104886`.)" +"Raise a :exc:`RuntimeError` when calling :meth:`frame.clear` on a suspended " +"frame (as has always been the case for an executing frame). (Contributed by " +"Irit Katriel in :gh:`79932`.)" msgstr "" -"Remove a classe não documentada :class:`!configparser.LegacyInterpolation`, " -"descontinuada na docstring desde Python 3.2 e com um aviso de descontinuação " -"desde Python 3.11. (Contribuição de Hugo van Kemenade em :gh:`104886`.)" +"Chamar :meth:`frame.clear` em um quadro suspenso levanta :exc:`RuntimeError` " +"(como sempre foi o caso para um quadro em execução). (Contribuição de Irit " +"Katriel em :gh:`79932`.)" -#: ../../whatsnew/3.13.rst:1458 +#: ../../whatsnew/3.13.rst:1691 msgid "" -"Remove deprecated :meth:`~object.__getitem__` access for :class:`!importlib." -"metadata.EntryPoint` objects. (Contributed by Jason R. Coombs in :gh:" +"Remove the undocumented :class:`!LegacyInterpolation` class, deprecated in " +"the docstring since Python 3.2, and at runtime since Python 3.11. " +"(Contributed by Hugo van Kemenade in :gh:`104886`.)" +msgstr "" +"Remove a classe não documentada :class:`!LegacyInterpolation`, descontinuada " +"na docstring desde Python 3.2 e em tempo de execução desde Python 3.11. " +"(Contribuição de Hugo van Kemenade em :gh:`104886`.)" + +#: ../../whatsnew/3.13.rst:1698 +msgid "importlib.metadata" +msgstr "importlib.metadata" + +#: ../../whatsnew/3.13.rst:1700 +msgid "" +"Remove deprecated subscript (:meth:`~object.__getitem__`) access for :ref:" +"`EntryPoint ` objects. (Contributed by Jason R. Coombs in :gh:" "`113175`.)" msgstr "" -"Remova o acesso descontinuado :meth:`~object.__getitem__` para objetos :" -"class:`!importlib.metadata.EntryPoint`. (Contribuição de Jason R. Coombs em :" -"gh:`113175`.)" +"Remove o acesso descontinuado a subscrito (:meth:`~object.__getitem__`) para " +"objetos :ref:`EntryPoint `. (Contribuição de Jason R. Coombs " +"em :gh:`113175`.)" -#: ../../whatsnew/3.13.rst:1463 +#: ../../whatsnew/3.13.rst:1706 msgid "locale" msgstr "locale" -#: ../../whatsnew/3.13.rst:1465 +#: ../../whatsnew/3.13.rst:1708 msgid "" -"Remove ``locale.resetlocale()`` function deprecated in Python 3.11: use " -"``locale.setlocale(locale.LC_ALL, \"\")`` instead. (Contributed by Victor " -"Stinner in :gh:`104783`.)" +"Remove the :func:`!locale.resetlocale` function, deprecated in Python 3.11. " +"Use ``locale.setlocale(locale.LC_ALL, \"\")`` instead. (Contributed by " +"Victor Stinner in :gh:`104783`.)" msgstr "" -"Remove a função ``locale.resetlocale()`` descontinuada no Python 3.11: use " -"``locale.setlocale(locale.LC_ALL, \"\")`` em vez disso. (Contribuição de " -"Victor Stinner em :gh:`104783`.)" +"Remove a função :func:`!locale.resetlocale`, descontinuada no Python 3.11. " +"Use ``locale.setlocale(locale.LC_ALL, \"\")``. (Contribuição de Victor " +"Stinner em :gh:`104783`.)" + +#: ../../whatsnew/3.13.rst:1714 +msgid "opcode" +msgstr "opcode" -#: ../../whatsnew/3.13.rst:1472 +#: ../../whatsnew/3.13.rst:1716 msgid "" -"Remove support for using :class:`pathlib.Path` objects as context managers. " -"This functionality was deprecated and made a no-op in Python 3.9." +"Move :attr:`!opcode.ENABLE_SPECIALIZATION` to :attr:`!_opcode." +"ENABLE_SPECIALIZATION`. This field was added in 3.12, it was never " +"documented, and is not intended for external use. (Contributed by Irit " +"Katriel in :gh:`105481`.)" msgstr "" -"Remove o suporte para usar objetos :class:`pathlib.Path` como gerenciadores " -"de contexto. Esta funcionalidade foi descontinuada e tornou-se não " -"operacional no Python 3.9." +"Move :attr:`!opcode.ENABLE_SPECIALIZATION` para :attr:`!_opcode." +"ENABLE_SPECIALIZATION`. Este campo foi adicionado na versão 3.12, nunca foi " +"documentado e não se destina ao uso externo. (Contribuição de Irit Katriel " +"em :gh:`105481`.)" -#: ../../whatsnew/3.13.rst:1478 -msgid "" -"Remove undocumented, never working, and deprecated ``re.template`` function " -"and ``re.TEMPLATE`` flag (and ``re.T`` alias). (Contributed by Serhiy " -"Storchaka and Nikita Sobolev in :gh:`105687`.)" +#: ../../whatsnew/3.13.rst:1721 +msgid "" +"Remove :func:`!opcode.is_pseudo`, :attr:`!opcode.MIN_PSEUDO_OPCODE`, and :" +"attr:`!opcode.MAX_PSEUDO_OPCODE`, which were added in Python 3.12, but were " +"neither documented nor exposed through :mod:`dis`, and were not intended to " +"be used externally. (Contributed by Irit Katriel in :gh:`105481`.)" +msgstr "" +"Remove :func:`!opcode.is_pseudo`, :attr:`!opcode.MIN_PSEUDO_OPCODE` e :attr:" +"`!opcode.MAX_PSEUDO_OPCODE`, que foram adicionados no Python 3.12, mas nunca " +"foram documentados nem expostos através de :mod:`dis`, e não foram " +"planejados para serem usados externamente. (Contribuição de Irit Katriel em :" +"gh:`105481`.)" + +#: ../../whatsnew/3.13.rst:1729 +msgid "optparse" +msgstr "optparse" + +#: ../../whatsnew/3.13.rst:1731 +msgid "" +"This module is no longer considered :term:`soft deprecated`. While :mod:" +"`argparse` remains preferred for new projects that aren't using a third " +"party command line argument processing library, there are aspects of the way " +"``argparse`` works that mean the lower level ``optparse`` module may provide " +"a better foundation for *writing* argument processing libraries, and for " +"implementing command line applications which adhere more strictly than " +"``argparse`` does to various Unix command line processing conventions that " +"originate in the behaviour of the C :c:func:`!getopt` function . " +"(Contributed by Alyssa Coghlan and Serhiy Storchaka in :gh:`126180`.)" +msgstr "" +"Este módulo não é mais considerado :term:`suavemente descontinuado`. " +"Enquanto o :mod:`argparse` continua sendo o preferido para novos projetos " +"que não estão usando uma biblioteca de processamento de argumentos de linha " +"de comando de terceiros, há aspectos da maneira como ``argparse`` funciona " +"que significam que o módulo ``optparse`` de nível inferior pode fornecer uma " +"base melhor para *escrever* bibliotecas de processamento de argumentos e " +"para implementar aplicações de linha de comando que aderem mais estritamente " +"do que ``argparse`` a várias convenções de processamento de linha de comando " +"Unix que se originam no comportamento da função C :c:func:`!getopt`. " +"(Contribuição de Alyssa Coghlan e Serhiy Storchaka em :gh:`126180`.)" + +#: ../../whatsnew/3.13.rst:1747 +msgid "" +"Remove the ability to use :class:`~pathlib.Path` objects as context " +"managers. This functionality was deprecated and has had no effect since " +"Python 3.9. (Contributed by Barney Gale in :gh:`83863`.)" +msgstr "" +"Remove a capacidade de usar objetos :class:`~pathlib.Path` como " +"gerenciadores de contexto. Essa funcionalidade foi descontinuada e não tinha " +"efeito desde o Python 3.9. (Contribuição de Barney Gale em :gh:`83863`.)" + +#: ../../whatsnew/3.13.rst:1755 +msgid "" +"Remove the undocumented, deprecated, and broken :func:`!re.template` " +"function and :attr:`!re.TEMPLATE` / :attr:`!re.T` flag. (Contributed by " +"Serhiy Storchaka and Nikita Sobolev in :gh:`105687`.)" +msgstr "" +"Remove a função :func:`!re.template` não documentada, descontinuada e " +"quebrada e o sinalizador :attr:`!re.TEMPLATE` / :attr:`!re.T`. (Contribuição " +"de Serhiy Storchaka e Nikita Sobolev em :gh:`105687`.)" + +#: ../../whatsnew/3.13.rst:1761 +msgid "tkinter.tix" +msgstr "tkinter.tix" + +#: ../../whatsnew/3.13.rst:1763 +msgid "" +"Remove the :mod:`!tkinter.tix` module, deprecated in Python 3.6. The third-" +"party Tix library which the module wrapped is unmaintained. (Contributed by " +"Zachary Ware in :gh:`75552`.)" msgstr "" -"Remove a função ``re.template`` não documentada, que nunca funciona e " -"descontinuada e o sinalizador ``re.TEMPLATE`` (e o apelido ``re.T``). " -"(Contribuição de Serhiy Storchaka e Nikita Sobolev em :gh:`105687`.)" +"Remove o módulo :mod:`!tkinter.tix`, descontinuado no Python 3.6. A " +"biblioteca Tix de terceiros que o módulo empacota não é mantida. " +"(Contribuição de Zachary Ware em :gh:`75552`.)" -#: ../../whatsnew/3.13.rst:1484 +#: ../../whatsnew/3.13.rst:1769 msgid "turtle" msgstr "turtle" -#: ../../whatsnew/3.13.rst:1486 +#: ../../whatsnew/3.13.rst:1771 msgid "" -"Remove the :meth:`!turtle.RawTurtle.settiltangle` method, deprecated in docs " -"since Python 3.1 and with a deprecation warning since Python 3.11. " +"Remove the :meth:`!RawTurtle.settiltangle` method, deprecated in the " +"documentation since Python 3.1 and at runtime since Python 3.11. " "(Contributed by Hugo van Kemenade in :gh:`104876`.)" msgstr "" -"Remove o método :meth:`!turtle.RawTurtle.settiltangle`, descontinuado na " -"documentação desde o Python 3.1 e com um aviso de descontinuação desde o " -"Python 3.11. (Contribuição de Hugo van Kemenade em :gh:`104876`.)" +"Remove o método :meth:`!RawTurtle.settiltangle`, descontinuado na " +"documentação desde o Python 3.1 e em tempo de execução desde o Python 3.11. " +"(Contribuição de Hugo van Kemenade em :gh:`104876`.)" -#: ../../whatsnew/3.13.rst:1494 +#: ../../whatsnew/3.13.rst:1780 msgid "" -"Namespaces ``typing.io`` and ``typing.re``, deprecated in Python 3.8, are " -"now removed. The items in those namespaces can be imported directly from :" -"mod:`typing`. (Contributed by Sebastian Rittau in :gh:`92871`.)" +"Remove the :mod:`!typing.io` and :mod:`!typing.re` namespaces, deprecated " +"since Python 3.8. The items in those namespaces can be imported directly " +"from the :mod:`typing` module. (Contributed by Sebastian Rittau in :gh:" +"`92871`.)" msgstr "" -"Os espaços de nomes ``typing.io`` e ``typing.re``, descontinuados no Python " -"3.8, foram agora removidos. Os itens nesses espaços de nomes podem ser " -"importados diretamente de :mod:`typing`. (Contribuição de Sebastian Rittau " -"em :gh:`92871`.)" +"Remove os espaços de nomes :mod:`!typing.io` e :mod:`!typing.re`, " +"descontinuados desde o Python 3.8. Os itens nesses espaços de nomes podem " +"ser importados diretamente do módulo :mod:`typing`. (Contribuição de " +"Sebastian Rittau em :gh:`92871`.)" -#: ../../whatsnew/3.13.rst:1498 +#: ../../whatsnew/3.13.rst:1786 msgid "" -"Remove support for the keyword-argument method of creating :class:`typing." -"TypedDict` types, deprecated in Python 3.11. (Contributed by Tomas Roun in :" -"gh:`104786`.)" +"Remove the keyword-argument method of creating :class:`~typing.TypedDict` " +"types, deprecated in Python 3.11. (Contributed by Tomas Roun in :gh:" +"`104786`.)" msgstr "" -"Remove o suporte para o método de argumento nomeado de criação de tipos :" -"class:`typing.TypedDict`, descontinuados no Python 3.11. (Contribuição de " -"Tomas Roun em :gh:`104786`.)" +"Remove o método de argumento nomeado de criação de tipos :class:`~typing." +"TypedDict`, descontinuados no Python 3.11. (Contribuição de Tomas Roun em :" +"gh:`104786`.)" -#: ../../whatsnew/3.13.rst:1503 +#: ../../whatsnew/3.13.rst:1792 msgid "unittest" msgstr "unittest" -#: ../../whatsnew/3.13.rst:1505 +#: ../../whatsnew/3.13.rst:1794 msgid "" "Remove the following :mod:`unittest` functions, deprecated in Python 3.11:" msgstr "" "Remove as seguintes funções :mod:`unittest`, descontinuadas no Python 3.11:" -#: ../../whatsnew/3.13.rst:1507 +#: ../../whatsnew/3.13.rst:1796 msgid ":func:`!unittest.findTestCases`" msgstr ":func:`!unittest.findTestCases`" -#: ../../whatsnew/3.13.rst:1508 +#: ../../whatsnew/3.13.rst:1797 msgid ":func:`!unittest.makeSuite`" msgstr ":func:`!unittest.makeSuite`" -#: ../../whatsnew/3.13.rst:1509 +#: ../../whatsnew/3.13.rst:1798 msgid ":func:`!unittest.getTestCaseNames`" msgstr ":func:`!unittest.getTestCaseNames`" -#: ../../whatsnew/3.13.rst:1511 +#: ../../whatsnew/3.13.rst:1800 msgid "Use :class:`~unittest.TestLoader` methods instead:" msgstr "Em vez delas, use os métodos de :class:`~unittest.TestLoader`:" -#: ../../whatsnew/3.13.rst:1513 -msgid ":meth:`unittest.TestLoader.loadTestsFromModule`" -msgstr ":meth:`unittest.TestLoader.loadTestsFromModule`" +#: ../../whatsnew/3.13.rst:1802 +msgid ":meth:`~unittest.TestLoader.loadTestsFromModule`" +msgstr ":meth:`~unittest.TestLoader.loadTestsFromModule`" -#: ../../whatsnew/3.13.rst:1514 -msgid ":meth:`unittest.TestLoader.loadTestsFromTestCase`" -msgstr ":meth:`unittest.TestLoader.loadTestsFromTestCase`" +#: ../../whatsnew/3.13.rst:1803 +msgid ":meth:`~unittest.TestLoader.loadTestsFromTestCase`" +msgstr ":meth:`~unittest.TestLoader.loadTestsFromTestCase`" -#: ../../whatsnew/3.13.rst:1515 -msgid ":meth:`unittest.TestLoader.getTestCaseNames`" -msgstr ":meth:`unittest.TestLoader.getTestCaseNames`" +#: ../../whatsnew/3.13.rst:1804 +msgid ":meth:`~unittest.TestLoader.getTestCaseNames`" +msgstr ":meth:`~unittest.TestLoader.getTestCaseNames`" -#: ../../whatsnew/3.13.rst:1517 +#: ../../whatsnew/3.13.rst:1806 msgid "(Contributed by Hugo van Kemenade in :gh:`104835`.)" msgstr "(Contribuição de Hugo van Kemenade em :gh:`104835`.)" -#: ../../whatsnew/3.13.rst:1519 +#: ../../whatsnew/3.13.rst:1808 msgid "" -"Remove the untested and undocumented :meth:`!unittest.TestProgram.usageExit` " -"method, deprecated in Python 3.11. (Contributed by Hugo van Kemenade in :gh:" +"Remove the untested and undocumented :meth:`!TestProgram.usageExit` method, " +"deprecated in Python 3.11. (Contributed by Hugo van Kemenade in :gh:" "`104992`.)" msgstr "" -"Remove o método :meth:`!unittest.TestProgram.usageExit` não testado e não " +"Remove o método :meth:`!TestProgram.usageExit` não testado e não " "documentado, descontinuado no Python 3.11. (Contribuição de Hugo van " "Kemenade em :gh:`104992`.)" -#: ../../whatsnew/3.13.rst:1524 +#: ../../whatsnew/3.13.rst:1814 msgid "urllib" msgstr "urllib" -#: ../../whatsnew/3.13.rst:1526 +#: ../../whatsnew/3.13.rst:1816 msgid "" -"Remove *cafile*, *capath* and *cadefault* parameters of the :func:`urllib." -"request.urlopen` function, deprecated in Python 3.6: pass the *context* " -"parameter instead. Use :meth:`ssl.SSLContext.load_cert_chain` to load " -"specific certificates, or let :func:`ssl.create_default_context` select the " -"system's trusted CA certificates for you. (Contributed by Victor Stinner in :" -"gh:`105382`.)" +"Remove the *cafile*, *capath*, and *cadefault* parameters of the :func:" +"`urllib.request.urlopen` function, deprecated in Python 3.6. Use the " +"*context* parameter instead with an :class:`~ssl.SSLContext` instance. The :" +"meth:`ssl.SSLContext.load_cert_chain` function can be used to load specific " +"certificates, or let :func:`ssl.create_default_context` select the operating " +"system's trusted certificate authority (CA) certificates. (Contributed by " +"Victor Stinner in :gh:`105382`.)" msgstr "" "Remove os parâmetros *cafile*, *capath* e *cadefault* da função :func:" -"`urllib.request.urlopen`, descontinuada no Python 3.6: passe o parâmetro " -"*context* em vez disso. Use :meth:`ssl.SSLContext.load_cert_chain` para " -"carregar certificados específicos ou deixe :func:`ssl." -"create_default_context` selecionar os certificados CA confiáveis ​​do sistema " -"para você. (Contribuição de Victor Stinner em :gh:`105382`.)" - -#: ../../whatsnew/3.13.rst:1535 +"`urllib.request.urlopen`, descontinuada no Python 3.6. Em vez disso, use o " +"parâmetro *context* com uma instância de :class:`~ssl.SSLContext`. A função :" +"meth:`ssl.SSLContext.load_cert_chain` pode ser usada para carregar " +"certificados específicos ou deixe :func:`ssl.create_default_context` " +"selecionar os certificados de autoridade certificadora (AC) confiável do " +"sistema operacional. (Contribuição de Victor Stinner em :gh:`105382`.)" + +#: ../../whatsnew/3.13.rst:1827 msgid "webbrowser" msgstr "webbrowser" -#: ../../whatsnew/3.13.rst:1537 +#: ../../whatsnew/3.13.rst:1829 msgid "" -"Remove the untested and undocumented :mod:`webbrowser` :class:`!MacOSX` " -"class, deprecated in Python 3.11. Use the :class:`!MacOSXOSAScript` class " -"(introduced in Python 3.2) instead. (Contributed by Hugo van Kemenade in :gh:" -"`104804`.)" +"Remove the untested and undocumented :class:`!MacOSX` class, deprecated in " +"Python 3.11. Use the :class:`!MacOSXOSAScript` class (introduced in Python " +"3.2) instead. (Contributed by Hugo van Kemenade in :gh:`104804`.)" msgstr "" -"Remove a classe :mod:`webbrowser` :class:`!MacOSX` não testada e não " -"documentada, descontinuada no Python 3.11. Use a classe :class:`!" -"MacOSXOSAScript` (introduzida no Python 3.2). (Contribuição de Hugo van " -"Kemenade em :gh:`104804`.)" +"Remove a classe :class:`!MacOSX` não testada e não documentada, " +"descontinuada no Python 3.11. Use a classe :class:`!MacOSXOSAScript` " +"(introduzida no Python 3.2). (Contribuição de Hugo van Kemenade em :gh:" +"`104804`.)" -#: ../../whatsnew/3.13.rst:1542 +#: ../../whatsnew/3.13.rst:1834 msgid "" -"Remove deprecated ``webbrowser.MacOSXOSAScript._name`` attribute. Use :attr:" -"`webbrowser.MacOSXOSAScript.name ` attribute " -"instead. (Contributed by Nikita Sobolev in :gh:`105546`.)" +"Remove the deprecated :attr:`!MacOSXOSAScript._name` attribute. Use the :" +"attr:`MacOSXOSAScript.name ` attribute instead. " +"(Contributed by Nikita Sobolev in :gh:`105546`.)" msgstr "" -"Remove o atributo descontinuado ``webbrowser.MacOSXOSAScript._name``. Use o " -"atributo :attr:`webbrowser.MacOSXOSAScript.name ` em vez disso. (Contribuição de Nikita Sobolev em :gh:`105546`.)" +"Remove o atributo descontinuado :attr:`!MacOSXOSAScript._name`. Use o " +"atributo :attr:`MacOSXOSAScript.name `. " +"(Contribuição de Nikita Sobolev em :gh:`105546`.)" -#: ../../whatsnew/3.13.rst:1548 +#: ../../whatsnew/3.13.rst:1841 msgid "New Deprecations" msgstr "Novas descontinuações" -#: ../../whatsnew/3.13.rst:1550 +#: ../../whatsnew/3.13.rst:1843 +msgid ":ref:`User-defined functions `:" +msgstr ":ref:`Funções definidas pelo usuário `:" + +#: ../../whatsnew/3.13.rst:1845 msgid "" -"Removed chained :class:`classmethod` descriptors (introduced in :gh:" -"`63272`). This can no longer be used to wrap other descriptors such as :" -"class:`property`. The core design of this feature was flawed and caused a " -"number of downstream problems. To \"pass-through\" a :class:`classmethod`, " -"consider using the :attr:`!__wrapped__` attribute that was added in Python " -"3.10. (Contributed by Raymond Hettinger in :gh:`89519`.)" +"Deprecate assignment to a function's :attr:`~function.__code__` attribute, " +"where the new code object's type does not match the function's type. The " +"different types are: plain function, generator, async generator, and " +"coroutine. (Contributed by Irit Katriel in :gh:`81137`.)" msgstr "" -"Removidos os descritores :class:`classmethod` encadeados (introduzidos em :" -"gh:`63272`). Isto não pode mais ser usado para agrupar outros descritores " -"como :class:`property`. O design central desse recurso apresentava falhas e " -"causou vários problemas posteriores. Para \"passar\" um :class:" -"`classmethod`, considere usar o atributo :attr:`!__wrapped__` que foi " -"adicionado no Python 3.10. (Contribuição de Raymond Hettinger em :gh:" -"`89519`.)" +"A atribuição ao atributo :attr:`~function.__code__` de uma função onde o " +"tipo do novo objeto código não corresponde ao tipo da função está " +"descontinuada. Os diferentes tipos são: função simples, gerador, gerador " +"assíncrono e corrotina. (Contribuição de Irit Katriel em :gh:`81137`.)" -#: ../../whatsnew/3.13.rst:1558 +#: ../../whatsnew/3.13.rst:1851 +#: ../../deprecations/pending-removal-in-3.16.rst:11 +msgid ":mod:`array`:" +msgstr ":mod:`array`:" + +#: ../../whatsnew/3.13.rst:1853 +msgid "" +"Deprecate the ``'u'`` format code (:c:type:`wchar_t`) at runtime. This " +"format code has been deprecated in documentation since Python 3.3, and will " +"be removed in Python 3.16. Use the ``'w'`` format code (:c:type:`Py_UCS4`) " +"for Unicode characters instead. (Contributed by Hugo van Kemenade in :gh:" +"`80480`.)" +msgstr "" +"Descontinua o código de formato ``'u'`` (:c:type:`wchar_t`). Este código de " +"formato foi descontinuado na documentação desde o Python 3.3 e será removido " +"no Python 3.16. Use o código de formato ``'w'`` (:c:type:`Py_UCS4`) para " +"caracteres Unicode. (Contribuição de Hugo van Kemenade em :gh:`80480`.)" + +#: ../../whatsnew/3.13.rst:1860 +#: ../../deprecations/pending-removal-in-3.15.rst:16 +msgid ":mod:`ctypes`:" +msgstr ":mod:`ctypes`:" + +#: ../../whatsnew/3.13.rst:1862 msgid "" -":mod:`array`: :mod:`array`'s ``'u'`` format code, deprecated in docs since " -"Python 3.3, emits :exc:`DeprecationWarning` since 3.13 and will be removed " -"in Python 3.16. Use the ``'w'`` format code instead. (Contributed by Hugo " -"van Kemenade in :gh:`80480`.)" +"Deprecate the undocumented :func:`!SetPointerType` function, to be removed " +"in Python 3.15. (Contributed by Victor Stinner in :gh:`105733`.)" msgstr "" -":mod:`array`: O código de formato ``'u'`` de :mod:`array`, descontinuado em " -"documentos desde Python 3.3, emite :exc:`DeprecationWarning` desde 3.13 e " -"será removido em Python 3.16. Use o código de formato ``'w'``. (Contribuição " -"de Hugo van Kemenade em :gh:`80480`.)" +"Descontinua a função não documentada :func:`!SetPointerType`, que será " +"removida no Python 3.15. (Contribuição de Victor Stinner em :gh:`105733`.)" -#: ../../whatsnew/3.13.rst:1564 +#: ../../whatsnew/3.13.rst:1866 msgid "" -":mod:`ctypes`: Deprecate undocumented :func:`!ctypes.SetPointerType` " -"function. :term:`Soft-deprecate ` the :func:`ctypes.ARRAY` " -"function in favor of multiplication. (Contributed by Victor Stinner in :gh:" -"`105733`.)" +":term:`Soft-deprecate ` the :func:`~ctypes.ARRAY` function " +"in favour of ``type * length`` multiplication. (Contributed by Victor " +"Stinner in :gh:`105733`.)" msgstr "" -":mod:`ctypes`: Descontinua a função não documentada :func:`!ctypes." -"SetPointerType`. :term:`Descontinua suavemente ` a função :" -"func:`ctypes.ARRAY` em favor de multiplicação. (Contribuição de Victor " +":term:`Descontinua suavemente ` a função :func:`~ctypes." +"ARRAY` em favor da multiplicação ``type * length``. (Contribuição de Victor " "Stinner em :gh:`105733`.)" -#: ../../whatsnew/3.13.rst:1569 +#: ../../whatsnew/3.13.rst:1870 +msgid ":mod:`decimal`:" +msgstr ":mod:`decimal`:" + +#: ../../whatsnew/3.13.rst:1872 msgid "" -":mod:`decimal`: Deprecate non-standard format specifier \"N\" for :class:" -"`decimal.Decimal`. It was not documented and only supported in the C " +"Deprecate the non-standard and undocumented :class:`~decimal.Decimal` format " +"specifier ``'N'``, which is only supported in the :mod:`!decimal` module's C " "implementation. (Contributed by Serhiy Storchaka in :gh:`89902`.)" msgstr "" -":mod:`decimal`: Descontinua o especificador de formato não padrão \"N\" " -"para :class:`decimal.Decimal`. Não foi documentado e apenas suportado na " -"implementação C. (Contribuição de Serhiy Storchaka em :gh:`89902`.)" +"Descontinua o especificador de formato de :class:`~decimal.Decimal` não " +"padrão e não documentado ``'N'``, que só é suportado na implementação C do " +"módulo :mod:`!decimal`. (Contribuição de Serhiy Storchaka em :gh:`89902`.)" -#: ../../whatsnew/3.13.rst:1574 +#: ../../whatsnew/3.13.rst:1877 +msgid ":mod:`dis`:" +msgstr ":mod:`dis`:" + +#: ../../whatsnew/3.13.rst:1879 msgid "" -":mod:`dis`: The ``dis.HAVE_ARGUMENT`` separator is deprecated. Check " -"membership in :data:`~dis.hasarg` instead. (Contributed by Irit Katriel in :" -"gh:`109319`.)" +"Deprecate the :attr:`!HAVE_ARGUMENT` separator. Check membership in :data:" +"`~dis.hasarg` instead. (Contributed by Irit Katriel in :gh:`109319`.)" msgstr "" -":mod:`dis`: O separador ``dis.HAVE_ARGUMENT`` está descontinuado. Verifique " -"a associação em :data:`~dis.hasarg`. (Contribuição de Irit Katriel em :gh:" +"Descontinua o separador :attr:`!HAVE_ARGUMENT`. Em vez disso, Verifique a " +"associação em :data:`~dis.hasarg`. (Contribuição de Irit Katriel em :gh:" "`109319`.)" -#: ../../whatsnew/3.13.rst:1578 -msgid "" -":ref:`frame-objects`: Calling :meth:`frame.clear` on a suspended frame " -"raises :exc:`RuntimeError` (as has always been the case for an executing " -"frame). (Contributed by Irit Katriel in :gh:`79932`.)" -msgstr "" -":ref:`frame-objects`: Chamar :meth:`frame.clear` em um quadro suspenso " -"levanta :exc:`RuntimeError` (como sempre foi o caso para um quadro em " -"execução). (Contribuição de Irit Katriel em :gh:`79932`.)" +#: ../../whatsnew/3.13.rst:1883 +msgid ":mod:`gettext`:" +msgstr ":mod:`gettext`:" -#: ../../whatsnew/3.13.rst:1583 +#: ../../whatsnew/3.13.rst:1885 msgid "" -":mod:`getopt` and :mod:`optparse` modules: They are now :term:`soft " -"deprecated`: the :mod:`argparse` module should be used for new projects. " -"Previously, the :mod:`optparse` module was already deprecated, its removal " -"was not scheduled, and no warnings was emitted: so there is no change in " -"practice. (Contributed by Victor Stinner in :gh:`106535`.)" +"Deprecate non-integer numbers as arguments to functions and methods that " +"consider plural forms in the :mod:`!gettext` module, even if no translation " +"was found. (Contributed by Serhiy Storchaka in :gh:`88434`.)" msgstr "" -"Módulos :mod:`getopt` e :mod:`optparse`: Eles agora estão :term:`suavemente " -"descontinuado`: o módulo :mod:`argparse` deve ser usado para novos projetos. " -"Anteriormente, o módulo :mod:`optparse` já estava descontinuado, sua remoção " -"não foi agendada e nenhum aviso foi emitido: portanto não há mudança na " -"prática. (Contribuição de Victor Stinner em :gh:`106535`.)" +"Descontinua números não inteiros como argumentos para funções e métodos que " +"consideram formas plurais no módulo :mod:`!gettext`, ainda que nenhuma " +"tradução tenha sido encontrada. (Contribuição de Serhiy Storchaka em :gh:" +"`88434`.)" -#: ../../whatsnew/3.13.rst:1590 +#: ../../whatsnew/3.13.rst:1890 +msgid ":mod:`glob`:" +msgstr ":mod:`glob`:" + +#: ../../whatsnew/3.13.rst:1892 msgid "" -":mod:`gettext`: Emit deprecation warning for non-integer numbers in :mod:" -"`gettext` functions and methods that consider plural forms even if the " -"translation was not found. (Contributed by Serhiy Storchaka in :gh:`88434`.)" +"Deprecate the undocumented :func:`!glob0` and :func:`!glob1` functions. Use :" +"func:`~glob.glob` and pass a :term:`path-like object` specifying the root " +"directory to the *root_dir* parameter instead. (Contributed by Barney Gale " +"in :gh:`117337`.)" msgstr "" -":mod:`gettext`: Emite aviso de descontinuação para números não inteiros em " -"funções e métodos :mod:`gettext` que consideram formas plurais mesmo que a " -"tradução não tenha sido encontrada. (Contribuição de Serhiy Storchaka em :gh:" -"`88434`.)" +"Descontinua as funções não documentadas :func:`!glob0` e :func:`!glob1`. Em " +"vez disso, use :func:`~glob.glob` e passe um :term:`objeto caminho ou " +"similar` especificando o diretório raiz para o parâmetro *root_dir*. " +"(Contribuição de Barney Gale em :gh:`117337`.)" -#: ../../whatsnew/3.13.rst:1595 +#: ../../whatsnew/3.13.rst:1897 +#: ../../deprecations/pending-removal-in-3.15.rst:21 +msgid ":mod:`http.server`:" +msgstr ":mod:`http.server`:" + +#: ../../whatsnew/3.13.rst:1899 msgid "" -":mod:`glob`: The undocumented :func:`!glob.glob0` and :func:`!glob.glob1` " -"functions are deprecated. Use :func:`glob.glob` and pass a directory to its " -"*root_dir* argument instead. (Contributed by Barney Gale in :gh:`117337`.)" +"Deprecate :class:`~http.server.CGIHTTPRequestHandler`, to be removed in " +"Python 3.15. Process-based CGI HTTP servers have been out of favor for a " +"very long time. This code was outdated, unmaintained, and rarely used. It " +"has a high potential for both security and functionality bugs. (Contributed " +"by Gregory P. Smith in :gh:`109096`.)" msgstr "" -":mod:`glob`: As funções não documentadas :func:`!glob.glob0` e :func:`!glob." -"glob1` estão descontinuadas. Use :func:`glob.glob` e passe um diretório para " -"seu argumento *root_dir*. (Contribuição de Barney Gale em :gh:`117337`.)" +"Descontinua :class:`~http.server.CGIHTTPRequestHandler`, a ser removido no " +"Python 3.15. Servidores HTTP CGI baseados em processos estão fora de moda há " +"muito tempo. Este código estava desatualizado, sem manutenção e raramente " +"era usado. Ele tem um alto potencial para bugs de segurança e " +"funcionalidade. (Contribuição de Gregory P. Smith em :gh:`109096`.)" -#: ../../whatsnew/3.13.rst:1600 +#: ../../whatsnew/3.13.rst:1906 msgid "" -":mod:`http.server`: :class:`http.server.CGIHTTPRequestHandler` now emits a :" -"exc:`DeprecationWarning` as it will be removed in 3.15. Process-based CGI " -"HTTP servers have been out of favor for a very long time. This code was " -"outdated, unmaintained, and rarely used. It has a high potential for both " -"security and functionality bugs. This includes removal of the ``--cgi`` " -"flag to the ``python -m http.server`` command line in 3.15." +"Deprecate the :option:`!--cgi` flag to the :program:`python -m http.server` " +"command-line interface, to be removed in Python 3.15. (Contributed by " +"Gregory P. Smith in :gh:`109096`.)" msgstr "" -":mod:`http.server`: :class:`http.server.CGIHTTPRequestHandler` agora emite " -"uma exceção :exc:`DeprecationWarning`, pois será removida na versão 3.15. Os " -"servidores HTTP CGI baseados em processos estão em desuso há muito tempo. " -"Este código estava desatualizado, sem manutenção e raramente usado. Tem um " -"alto potencial para bugs de segurança e funcionalidade. Isso inclui a " -"remoção do sinalizador ``--cgi`` da linha de comando ``python -m http." -"server`` na versão 3.15." +"Descontinua o sinalizador :option:`!--cgi` para a interface de linha de " +"comando :program:`python -m http.server`, a ser removido no Python 3.15. " +"(Contribuição de Gregory P. Smith em :gh:`109096`.)" -#: ../../whatsnew/3.13.rst:1607 +#: ../../whatsnew/3.13.rst:1911 +msgid ":mod:`mimetypes`:" +msgstr ":mod:`mimetypes`:" + +#: ../../whatsnew/3.13.rst:1913 msgid "" -":mod:`mimetypes`: Passing file path instead of URL in :func:`~mimetypes." -"guess_type` is :term:`soft deprecated`. Use :func:`~mimetypes." -"guess_file_type` instead. (Contributed by Serhiy Storchaka in :gh:`66543`.)" +":term:`Soft-deprecate ` file path arguments to :func:" +"`~mimetypes.guess_type`, use :func:`~mimetypes.guess_file_type` instead. " +"(Contributed by Serhiy Storchaka in :gh:`66543`.)" msgstr "" -":mod:`mimetypes`: Passar o caminho do arquivo em vez da URL em :func:" -"`~mimetypes.guess_type` está :term:`suavemente descontinuado`. Use :func:" -"`~mimetypes.guess_file_type` em vez disso. (Contribuição de Serhiy Storchaka " -"em :gh:`66543`.)" +":term:`Descontinua suavemente ` argumentos caminho de " +"arquivo para :func:`~mimetypes.guess_type`, use :func:`~mimetypes." +"guess_file_type` em vez disso. (Contribuição de Serhiy Storchaka em :gh:" +"`66543`.)" -#: ../../whatsnew/3.13.rst:1611 +#: ../../whatsnew/3.13.rst:1918 +msgid ":mod:`re`:" +msgstr ":mod:`re`:" + +#: ../../whatsnew/3.13.rst:1920 msgid "" -":mod:`re`: Passing optional arguments *maxsplit*, *count* and *flags* in " -"module-level functions :func:`re.split`, :func:`re.sub` and :func:`re.subn` " -"as positional arguments is now deprecated. In future Python versions these " -"parameters will be :ref:`keyword-only `. " -"(Contributed by Serhiy Storchaka in :gh:`56166`.)" +"Deprecate passing the optional *maxsplit*, *count*, or *flags* arguments as " +"positional arguments to the module-level :func:`~re.split`, :func:`~re.sub`, " +"and :func:`~re.subn` functions. These parameters will become :ref:`keyword-" +"only ` in a future version of Python. (Contributed " +"by Serhiy Storchaka in :gh:`56166`.)" msgstr "" -":mod:`re`: Passar argumentos opcionais *maxsplit*, *count* e *flags* em " -"funções de nível de módulo :func:`re.split`, :func:`re.sub` e :func:`re." -"subn` como argumentos posicionais agora é descontinuado. Nas versões futuras " -"do Python, esses parâmetros serão :ref:`somente-nomeados `. (Contribuição de Serhiy Storchaka em :gh:`56166`.)" +"Descontinua a passagem dos argumentos opcionais *maxsplit*, *count* ou " +"*flags* como argumentos posicionais para as funções de nível de módulo :func:" +"`~re.split`, :func:`~re.sub` e :func:`~re.subn`. Esses parâmetros se " +"tornarão :ref:`somente-nomeados ` em uma versão " +"futura do Python. (Contribuição de Serhiy Storchaka em :gh:`56166`.)" -#: ../../whatsnew/3.13.rst:1617 -#: ../../deprecations/pending-removal-in-3.15.rst:16 +#: ../../whatsnew/3.13.rst:1927 +#: ../../deprecations/pending-removal-in-3.15.rst:46 +msgid ":mod:`pathlib`:" +msgstr ":mod:`pathlib`:" + +#: ../../whatsnew/3.13.rst:1929 msgid "" -":mod:`pathlib`: :meth:`pathlib.PurePath.is_reserved` is deprecated and " -"scheduled for removal in Python 3.15. Use :func:`os.path.isreserved` to " -"detect reserved paths on Windows." +"Deprecate :meth:`.PurePath.is_reserved`, to be removed in Python 3.15. Use :" +"func:`os.path.isreserved` to detect reserved paths on Windows. (Contributed " +"by Barney Gale in :gh:`88569`.)" msgstr "" -":mod:`pathlib`: :meth:`pathlib.PurePath.is_reserved` está descontinuado e " -"agendado para remoção no Python 3.15. Use :func:`os.path.isreserved` para " -"detectar caminhos reservados no Windows." +"Descontinua :meth:`.PurePath.is_reserved`, a ser removido no Python 3.15. " +"Use :func:`os.path.isreserved` para detectar caminhos reservados no Windows. " +"(Contribuição de Barney Gale em :gh:`88569`.)" -#: ../../whatsnew/3.13.rst:1622 -#: ../../deprecations/pending-removal-in-3.15.rst:21 +#: ../../whatsnew/3.13.rst:1934 +#: ../../deprecations/pending-removal-in-3.15.rst:52 +msgid ":mod:`platform`:" +msgstr ":mod:`platform`:" + +#: ../../whatsnew/3.13.rst:1936 msgid "" -":mod:`platform`: :func:`~platform.java_ver` is deprecated and will be " -"removed in 3.15. It was largely untested, had a confusing API, and was only " -"useful for Jython support. (Contributed by Nikita Sobolev in :gh:`116349`.)" +"Deprecate :func:`~platform.java_ver`, to be removed in Python 3.15. This " +"function is only useful for Jython support, has a confusing API, and is " +"largely untested. (Contributed by Nikita Sobolev in :gh:`116349`.)" msgstr "" -":mod:`platform`: :func:`~platform.java_ver` está descontinuada e será " -"removida na versão 3.15. Ela não foi testada em grande parte, tinha uma API " -"confusa e só era útil para suporte a Jython. (Contribuição de Nikita Sobolev " -"em :gh:`116349`.)" +"Descontinua :func:`~platform.java_ver`, a ser removida no Python 3.15. Esta " +"função é útil apenas para suporte a Jython, tem uma API confusa e é " +"amplamente não testada. (Contribuição de Nikita Sobolev em :gh:`116349`.)" -#: ../../whatsnew/3.13.rst:1628 +#: ../../whatsnew/3.13.rst:1942 +msgid ":mod:`pydoc`:" +msgstr ":mod:`pydoc`:" + +#: ../../whatsnew/3.13.rst:1944 msgid "" -":mod:`pydoc`: Deprecate undocumented :func:`!pydoc.ispackage` function. " -"(Contributed by Zackery Spytz in :gh:`64020`.)" +"Deprecate the undocumented :func:`!ispackage` function. (Contributed by " +"Zackery Spytz in :gh:`64020`.)" msgstr "" -":mod:`pydoc`: Descontinua a função não documentada :func:`!pydoc.ispackage`. " -"(Contribuição de Zackery Spytz em :gh:`64020`.)" +"Descontinua a função não documentada :func:`!ispackage`. (Contribuição de " +"Zackery Spytz em :gh:`64020`.)" + +#: ../../whatsnew/3.13.rst:1947 +#: ../../deprecations/pending-removal-in-3.14.rst:91 +msgid ":mod:`sqlite3`:" +msgstr ":mod:`sqlite3`:" -#: ../../whatsnew/3.13.rst:1631 +#: ../../whatsnew/3.13.rst:1949 msgid "" -":mod:`sqlite3`: Passing more than one positional argument to :func:`sqlite3." -"connect` and the :class:`sqlite3.Connection` constructor is deprecated. The " -"remaining parameters will become keyword-only in Python 3.15." +"Deprecate passing more than one positional argument to the :func:`~sqlite3." +"connect` function and the :class:`~sqlite3.Connection` constructor. The " +"remaining parameters will become keyword-only in Python 3.15. (Contributed " +"by Erlend E. Aasland in :gh:`107948`.)" msgstr "" -":mod:`sqlite3`: Passar mais de um argumento posicional para :func:`sqlite3." -"connect` e o construtor :class:`sqlite3.Connection` está descontinuado. Os " -"parâmetros restantes se tornarão somente-nomeados no Python 3.15." +"Descontinua a passagem de mais de um argumento posicional para a função :" +"func:`~sqlite3.connect` e o construtor :class:`~sqlite3.Connection`. Os " +"parâmetros restantes se tornarão somente-nomeados no Python 3.15. " +"(Contribuição de Erlend E. Aasland em :gh:`107948`.)" -#: ../../whatsnew/3.13.rst:1635 +#: ../../whatsnew/3.13.rst:1955 msgid "" "Deprecate passing name, number of arguments, and the callable as keyword " -"arguments for the following :class:`sqlite3.Connection` APIs:" +"arguments for :meth:`.Connection.create_function` and :meth:`.Connection." +"create_aggregate` These parameters will become positional-only in Python " +"3.15. (Contributed by Erlend E. Aasland in :gh:`108278`.)" msgstr "" "Descontinua a passagem de nome, número de argumentos e o chamável como " -"argumentos nomeados para as seguintes APIs de :class:`sqlite3.Connection`:" - -#: ../../whatsnew/3.13.rst:1638 -msgid ":meth:`~sqlite3.Connection.create_function`" -msgstr ":meth:`~sqlite3.Connection.create_function`" - -#: ../../whatsnew/3.13.rst:1639 -msgid ":meth:`~sqlite3.Connection.create_aggregate`" -msgstr ":meth:`~sqlite3.Connection.create_aggregate`" +"argumentos nomeados para :meth:`.Connection.create_function` e :meth:`." +"Connection.create_aggregate` Esses parâmetros se tornarão somente-" +"posicionais no Python 3.15. (Contribuição de Erlend E. Aasland em :gh:" +"`108278`.)" -#: ../../whatsnew/3.13.rst:1641 +#: ../../whatsnew/3.13.rst:1961 msgid "" -"Deprecate passing the callback callable by keyword for the following :class:" -"`sqlite3.Connection` APIs:" +"Deprecate passing the callback callable by keyword for the :meth:`~sqlite3." +"Connection.set_authorizer`, :meth:`~sqlite3.Connection." +"set_progress_handler`, and :meth:`~sqlite3.Connection.set_trace_callback` :" +"class:`~sqlite3.Connection` methods. The callback callables will become " +"positional-only in Python 3.15. (Contributed by Erlend E. Aasland in :gh:" +"`108278`.)" msgstr "" -"Descontinua a passagem do chamável de retorno de chamada como argumento " -"nomeado para as seguintes APIs de :class:`sqlite3.Connection`:" - -#: ../../whatsnew/3.13.rst:1644 -msgid ":meth:`~sqlite3.Connection.set_authorizer`" -msgstr ":meth:`~sqlite3.Connection.set_authorizer`" - -#: ../../whatsnew/3.13.rst:1645 -msgid ":meth:`~sqlite3.Connection.set_progress_handler`" -msgstr ":meth:`~sqlite3.Connection.set_progress_handler`" - -#: ../../whatsnew/3.13.rst:1646 -msgid ":meth:`~sqlite3.Connection.set_trace_callback`" -msgstr ":meth:`~sqlite3.Connection.set_trace_callback`" - -#: ../../whatsnew/3.13.rst:1648 -msgid "The affected parameters will become positional-only in Python 3.15." -msgstr "Os parâmetros afetados se tornarão somente-posicionais no Python 3.15." +"Descontinua a passagem do chamável de função de retorno como argumento " +"nomeado para os métodos :meth:`~sqlite3.Connection.set_authorizer`, :meth:" +"`~sqlite3.Connection.set_progress_handler` e :meth:`~sqlite3.Connection." +"set_trace_callback` da classe :class:`~sqlite3.Connection`. Os chamáveis de " +"função de retorno se tornarão somente-posicionais no Python 3.15. " +"(Contribuição de Erlend E. Aasland em :gh:`108278`.)" -#: ../../whatsnew/3.13.rst:1650 -msgid "(Contributed by Erlend E. Aasland in :gh:`107948` and :gh:`108278`.)" -msgstr "(Contribuição de Erlend E. Aasland em :gh:`107948` e :gh:`108278`.)" +#: ../../whatsnew/3.13.rst:1969 +#: ../../deprecations/pending-removal-in-3.16.rst:47 +msgid ":mod:`sys`:" +msgstr ":mod:`sys`:" -#: ../../whatsnew/3.13.rst:1652 +#: ../../whatsnew/3.13.rst:1971 msgid "" -":mod:`sys`: :func:`sys._enablelegacywindowsfsencoding` function. Replace it " -"with the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` environment variable. " -"(Contributed by Inada Naoki in :gh:`73427`.)" +"Deprecate the :func:`~sys._enablelegacywindowsfsencoding` function, to be " +"removed in Python 3.16. Use the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` " +"environment variable instead. (Contributed by Inada Naoki in :gh:`73427`.)" msgstr "" -":mod:`sys`: função :func:`sys._enablelegacywindowsfsencoding`. Substitua-a " -"pela variável de ambiente :envvar:`PYTHONLEGACYWINDOWSFSENCODING`. " -"(Contribuição de Inada Naoki em :gh:`73427`.)" +"Descontinua a função :func:`~sys._enablelegacywindowsfsencoding`, para ser " +"removida no Python 3.16. Em vez disso, use a variável de ambiente :envvar:" +"`PYTHONLEGACYWINDOWSFSENCODING`. (Contribuição de Inada Naoki em :gh:" +"`73427`.)" -#: ../../whatsnew/3.13.rst:1656 +#: ../../whatsnew/3.13.rst:1976 +#: ../../deprecations/pending-removal-in-3.16.rst:53 +msgid ":mod:`tarfile`:" +msgstr ":mod:`tarfile`:" + +#: ../../whatsnew/3.13.rst:1978 msgid "" -":mod:`tarfile`: The undocumented and unused ``tarfile`` attribute of :class:" -"`tarfile.TarFile` is deprecated and scheduled for removal in Python 3.16." +"Deprecate the undocumented and unused :attr:`!TarFile.tarfile` attribute, to " +"be removed in Python 3.16. (Contributed in :gh:`115256`.)" msgstr "" -":mod:`tarfile`: O atributo ``tarfile`` não documentado e não utilizado de :" -"class:`tarfile.TarFile` está descontinuado e agendado para remoção no Python " -"3.16." +"Descontinua o atributo :attr:`!TarFile.tarfile` não documentado e não " +"utilizado, a ser removido no Python 3.16. (Contribuição em :gh:`115256`.)" -#: ../../whatsnew/3.13.rst:1660 +#: ../../whatsnew/3.13.rst:1982 +msgid ":mod:`traceback`:" +msgstr ":mod:`traceback`:" + +#: ../../whatsnew/3.13.rst:1984 msgid "" -":mod:`traceback`: The field *exc_type* of :class:`traceback." -"TracebackException` is deprecated. Use *exc_type_str* instead." +"Deprecate the :attr:`.TracebackException.exc_type` attribute. Use :attr:`." +"TracebackException.exc_type_str` instead. (Contributed by Irit Katriel in :" +"gh:`112332`.)" msgstr "" -":mod:`traceback`: O campo *exc_type* de :class:`traceback." -"TracebackException` está descontinuado. Use *exc_type_str* em vez disso." +"Descontinua o atributo :attr:`.TracebackException.exc_type`. Em vez disso, " +"use :attr:`.TracebackException.exc_type_str`. (Contribuição de Irit Katriel " +"em :gh:`112332`.)" -#: ../../whatsnew/3.13.rst:1663 +#: ../../whatsnew/3.13.rst:1988 +#: ../../deprecations/pending-removal-in-3.15.rst:80 msgid ":mod:`typing`:" msgstr ":mod:`typing`:" -#: ../../whatsnew/3.13.rst:1665 +#: ../../whatsnew/3.13.rst:1990 msgid "" -"Creating a :class:`typing.NamedTuple` class using keyword arguments to " -"denote the fields (``NT = NamedTuple(\"NT\", x=int, y=int)``) is deprecated, " -"and will be disallowed in Python 3.15. Use the class-based syntax or the " +"Deprecate the undocumented keyword argument syntax for creating :class:" +"`~typing.NamedTuple` classes (e.g. ``Point = NamedTuple(\"Point\", x=int, " +"y=int)``), to be removed in Python 3.15. Use the class-based syntax or the " "functional syntax instead. (Contributed by Alex Waygood in :gh:`105566`.)" msgstr "" -"Criar uma classe :class:`typing.NamedTuple` usando argumentos nomeados para " -"denotar os campos (``NT = NamedTuple(\"NT\", x=int, y=int)``) está " -"descontinuado e não será permitido no Python 3.15. Use a sintaxe baseada em " -"classe ou a sintaxe funcional. (Contribuição de Alex Waygood em :gh:" -"`105566`.)" - -#: ../../whatsnew/3.13.rst:1670 -msgid "" -"When using the functional syntax to create a :class:`typing.NamedTuple` " -"class or a :class:`typing.TypedDict` class, failing to pass a value to the " -"'fields' parameter (``NT = NamedTuple(\"NT\")`` or ``TD = " -"TypedDict(\"TD\")``) is deprecated. Passing ``None`` to the 'fields' " -"parameter (``NT = NamedTuple(\"NT\", None)`` or ``TD = TypedDict(\"TD\", " -"None)``) is also deprecated. Both will be disallowed in Python 3.15. To " -"create a NamedTuple class with 0 fields, use ``class NT(NamedTuple): pass`` " -"or ``NT = NamedTuple(\"NT\", [])``. To create a TypedDict class with 0 " -"fields, use ``class TD(TypedDict): pass`` or ``TD = TypedDict(\"TD\", {})``. " -"(Contributed by Alex Waygood in :gh:`105566` and :gh:`105570`.)" -msgstr "" -"Ao usar a sintaxe funcional para criar uma classe :class:`typing.NamedTuple` " -"ou uma classe :class:`typing.TypedDict`, falhando ao passar um valor para o " -"parâmetro 'fields' (``NT = NamedTuple(\"NT\")`` ou ``TD = " -"TypedDict(\"TD\")``) está descontinuado. Passar ``None`` para o parâmetro " -"'fields' (``NT = NamedTuple(\"NT\", None)`` ou ``TD = TypedDict(\"TD\", " -"None)``) também está descontinuado. Ambos não serão permitidos no Python " -"3.15. Para criar uma classe NamedTuple com 0 campos, use ``class " -"NT(NamedTuple): pass`` ou ``NT = NamedTuple(\"NT\", [])``. Para criar uma " -"classe TypedDict com 0 campos, use ``class TD(TypedDict): pass`` ou ``TD = " -"TypedDict(\"TD\", {})``. (Contribuição de Alex Waygood em :gh:`105566` e :gh:" -"`105570`.)" - -#: ../../whatsnew/3.13.rst:1681 -msgid "" -":func:`typing.no_type_check_decorator` is deprecated, and scheduled for " -"removal in Python 3.15. After eight years in the :mod:`typing` module, it " -"has yet to be supported by any major type checkers. (Contributed by Alex " +"Descontinua a não-documentada sintaxe de argumento nomeado para criação de " +"classes :class:`~typing.NamedTuple` (por exemplo, ``Point = " +"NamedTuple(\"Point\", x=int, y=int)``), para ser removido no Python 3.15. Em " +"vez disso, use as sintaxes baseada em classe ou a funcional. (Contribuição " +"de Alex Waygood in :gh:`105566`.)" + +#: ../../whatsnew/3.13.rst:1997 +msgid "" +"Deprecate omitting the *fields* parameter when creating a :class:`~typing." +"NamedTuple` or :class:`typing.TypedDict` class, and deprecate passing " +"``None`` to the *fields* parameter of both types. Python 3.15 will require a " +"valid sequence for the *fields* parameter. To create a NamedTuple class with " +"zero fields, use ``class NT(NamedTuple): pass`` or ``NT = NamedTuple(\"NT\", " +"())``. To create a TypedDict class with zero fields, use ``class " +"TD(TypedDict): pass`` or ``TD = TypedDict(\"TD\", {})``. (Contributed by " +"Alex Waygood in :gh:`105566` and :gh:`105570`.)" +msgstr "" +"Descontinua a omissão do parâmetro *fields* ao criar uma classe :class:" +"`~typing.NamedTuple` ou :class:`typing.TypedDict` e descontinua a passagem " +"de ``None`` para o parâmetro *fields* de ambos os tipos. O Python 3.15 " +"exigirá uma sequência válida para o parâmetro *fields*. Para criar uma " +"classe NamedTuple com zero campos, use ``class NT(NamedTuple): pass`` ou " +"``NT = NamedTuple(\"NT\", ())``. Para criar uma classe TypedDict com zero " +"campos, use ``class TD(TypedDict): pass`` ou ``TD = TypedDict(\"TD\", {})``. " +"(Contribuição de Alex Waygood em :gh:`105566` e :gh:`105570`.)" + +#: ../../whatsnew/3.13.rst:2007 +msgid "" +"Deprecate the :func:`typing.no_type_check_decorator` decorator function, to " +"be removed in in Python 3.15. After eight years in the :mod:`typing` module, " +"it has yet to be supported by any major type checker. (Contributed by Alex " "Waygood in :gh:`106309`.)" msgstr "" -":func:`typing.no_type_check_decorator` está descontinuado e agendado para " -"remoção no Python 3.15. Depois de oito anos no módulo :mod:`typing`, ele " -"ainda não foi suportado por nenhum dos principais verificadores de tipos. " -"(Contribuição de Alex Waygood em :gh:`106309`.)" +"Descontinua o decorador de função :func:`typing.no_type_check_decorator` " +"para ser removido no Python 3.15. Depois de oito anos no módulo :mod:" +"`typing`, ele ainda não foi implementado por nenhum dos principais " +"verificadores de tipos. (Contribuição de Alex Waygood em :gh:`106309`.)" -#: ../../whatsnew/3.13.rst:1686 +#: ../../whatsnew/3.13.rst:2013 msgid "" -":data:`typing.AnyStr` is deprecated. In Python 3.16, it will be removed from " -"``typing.__all__``, and a :exc:`DeprecationWarning` will be emitted when it " -"is imported or accessed. It will be removed entirely in Python 3.18. Use the " -"new :ref:`type parameter syntax ` instead. (Contributed by " -"Michael The in :gh:`107116`.)" +"Deprecate :data:`typing.AnyStr`. In Python 3.16, it will be removed from " +"``typing.__all__``, and a :exc:`DeprecationWarning` will be emitted at " +"runtime when it is imported or accessed. It will be removed entirely in " +"Python 3.18. Use the new :ref:`type parameter syntax ` instead. " +"(Contributed by Michael The in :gh:`107116`.)" msgstr "" -":data:`typing.AnyStr` está descontinuado. No Python 3.16, ele será removido " -"de ``typing.__all__``, e uma exceção :exc:`DeprecationWarning` será emitida " -"quando for importada ou acessada. Ele será removido totalmente no Python " -"3.18. Use a nova :ref:`sintaxe de parâmetro de tipo `. " -"(Contribuição de Michael The em :gh:`107116`.)" +"Descontinua :data:`typing.AnyStr`. No Python 3.16, isso será removido de " +"``typing.__all__``, e uma :exc:`DeprecationWarning` será levantada em tempo " +"de execução quando isso for importado ou acessado. Será removido " +"completamente em Python 3.18. Em vez disso, use a nova :ref:`sintaxe de " +"parâmetro de tipo `. (Contribuição de Michael The em :gh:" +"`107116`.)" -#: ../../whatsnew/3.13.rst:1692 -msgid "" -":ref:`user-defined-funcs`: Assignment to a function's :attr:`~function." -"__code__` attribute where the new code object's type does not match the " -"function's type, is deprecated. The different types are: plain function, " -"generator, async generator and coroutine. (Contributed by Irit Katriel in :" -"gh:`81137`.)" -msgstr "" -":ref:`user-defined-funcs`: A atribuição ao atributo :attr:`~function." -"__code__` de uma função onde o tipo do novo objeto código não corresponde ao " -"tipo da função está descontinuada. Os diferentes tipos são: função simples, " -"gerador, gerador assíncrono e corrotina. (Contribuição de Irit Katriel em :" -"gh:`81137`.)" +#: ../../whatsnew/3.13.rst:2021 +#: ../../deprecations/pending-removal-in-3.15.rst:100 +msgid ":mod:`wave`:" +msgstr ":mod:`wave`:" -#: ../../whatsnew/3.13.rst:1699 -#: ../../deprecations/pending-removal-in-3.15.rst:54 +#: ../../whatsnew/3.13.rst:2023 msgid "" -":mod:`wave`: Deprecate the ``getmark()``, ``setmark()`` and ``getmarkers()`` " -"methods of the :class:`wave.Wave_read` and :class:`wave.Wave_write` classes. " -"They will be removed in Python 3.15. (Contributed by Victor Stinner in :gh:" -"`105096`.)" +"Deprecate the :meth:`~wave.Wave_read.getmark`, :meth:`!setmark`, and :meth:" +"`~wave.Wave_read.getmarkers` methods of the :class:`~wave.Wave_read` and :" +"class:`~wave.Wave_write` classes, to be removed in Python 3.15. (Contributed " +"by Victor Stinner in :gh:`105096`.)" msgstr "" -":mod:`wave`: Descontinua os métodos ``getmark()``, ``setmark()`` e " -"``getmarkers()`` das classes :class:`wave.Wave_read` e :class:`wave." -"Wave_write`. Eles serão removidos no Python 3.15. (Contribuição de Victor " -"Stinner em :gh:`105096`.)" +"Descontinua os métodos :meth:`~wave.Wave_read.getmark`, :meth:`!setmark` e :" +"meth:`~wave.Wave_read.getmarkers` das classes :class:`~wave.Wave_read` e :" +"class:`~wave.Wave_write`, a serem removidos no Python 3.15. (Contribuição de " +"Victor Stinner em :gh:`105096`.)" #: ../../deprecations/c-api-pending-removal-in-3.14.rst:2 #: ../../deprecations/pending-removal-in-3.14.rst:2 @@ -3558,7 +4071,7 @@ msgid "" "since Python 3.8, now cause a :exc:`DeprecationWarning` to be emitted at " "runtime when they are accessed or used, and will be removed in Python 3.14:" msgstr "" -":mod:`ast`: Os seguintes recursos foram descontinuados na documentação desde " +":mod:`ast`: os seguintes recursos foram descontinuados na documentação desde " "Python 3.8, agora fazem com que um :exc:`DeprecationWarning` seja emitido em " "tempo de execução quando eles são acessados ou usados, e serão removidos no " "Python 3.14:" @@ -3588,10 +4101,11 @@ msgid "" "Use :class:`ast.Constant` instead. (Contributed by Serhiy Storchaka in :gh:" "`90953`.)" msgstr "" -"Usa :class:`ast.Constant` em vez disso. (Contribuição de Serhiy Storchaka " +"Em vez disso, use :class:`ast.Constant`. (Contribuição de Serhiy Storchaka " "em :gh:`90953`.)" #: ../../deprecations/pending-removal-in-3.14.rst:22 +#: ../../deprecations/pending-removal-in-3.16.rst:19 msgid ":mod:`asyncio`:" msgstr ":mod:`asyncio`:" @@ -3602,7 +4116,7 @@ msgid "" "class:`~asyncio.SafeChildWatcher` are deprecated and will be removed in " "Python 3.14. (Contributed by Kumar Aditya in :gh:`94597`.)" msgstr "" -"As classes filhas do observador :class:`~asyncio.MultiLoopChildWatcher`, :" +"As classes filhas dos observadores :class:`~asyncio.MultiLoopChildWatcher`, :" "class:`~asyncio.FastChildWatcher`, :class:`~asyncio.AbstractChildWatcher` e :" "class:`~asyncio.SafeChildWatcher` foram descontinuadas e serão removidas no " "Python 3.14. (Contribuição de Kumar Aditya em :gh:`94597`.)" @@ -3653,46 +4167,38 @@ msgstr "" "localtime`. (Contribuição de Alan Williams em :gh:`72346`.)" #: ../../deprecations/pending-removal-in-3.14.rst:50 -msgid "" -":mod:`importlib`: ``__package__`` and ``__cached__`` will cease to be set or " -"taken into consideration by the import system (:gh:`97879`)." -msgstr "" -":mod:`importlib`: ``__package__`` e ``__cached__`` deixarão de ser definidos " -"ou levados em consideração pelo sistema de importação (:gh:`97879`)." - -#: ../../deprecations/pending-removal-in-3.14.rst:53 msgid ":mod:`importlib.abc` deprecated classes:" msgstr ":mod:`importlib.abc` descontinuou as classes:" -#: ../../deprecations/pending-removal-in-3.14.rst:55 +#: ../../deprecations/pending-removal-in-3.14.rst:52 msgid ":class:`!importlib.abc.ResourceReader`" msgstr ":class:`!importlib.abc.ResourceReader`" -#: ../../deprecations/pending-removal-in-3.14.rst:56 +#: ../../deprecations/pending-removal-in-3.14.rst:53 msgid ":class:`!importlib.abc.Traversable`" msgstr ":class:`!importlib.abc.Traversable`" -#: ../../deprecations/pending-removal-in-3.14.rst:57 +#: ../../deprecations/pending-removal-in-3.14.rst:54 msgid ":class:`!importlib.abc.TraversableResources`" msgstr ":class:`!importlib.abc.TraversableResources`" -#: ../../deprecations/pending-removal-in-3.14.rst:59 +#: ../../deprecations/pending-removal-in-3.14.rst:56 msgid "Use :mod:`importlib.resources.abc` classes instead:" -msgstr "Em vez disso, use classes :mod:`importlib.resources.abc`:" +msgstr "Em vez disso, use classes de :mod:`importlib.resources.abc`:" -#: ../../deprecations/pending-removal-in-3.14.rst:61 +#: ../../deprecations/pending-removal-in-3.14.rst:58 msgid ":class:`importlib.resources.abc.Traversable`" msgstr ":class:`importlib.resources.abc.Traversable`" -#: ../../deprecations/pending-removal-in-3.14.rst:62 +#: ../../deprecations/pending-removal-in-3.14.rst:59 msgid ":class:`importlib.resources.abc.TraversableResources`" msgstr ":class:`importlib.resources.abc.TraversableResources`" -#: ../../deprecations/pending-removal-in-3.14.rst:64 +#: ../../deprecations/pending-removal-in-3.14.rst:61 msgid "(Contributed by Jason R. Coombs and Hugo van Kemenade in :gh:`93963`.)" msgstr "(Contribuição de Jason R. Coombs e Hugo van Kemenade em :gh:`93963`.)" -#: ../../deprecations/pending-removal-in-3.14.rst:66 +#: ../../deprecations/pending-removal-in-3.14.rst:63 msgid "" ":mod:`itertools` had undocumented, inefficient, historically buggy, and " "inconsistent support for copy, deepcopy, and pickle operations. This will be " @@ -3705,7 +4211,7 @@ msgstr "" "significativa no volume de código e na carga de manutenção. (Contribuição de " "Raymond Hettinger em :gh:`101588`.)" -#: ../../deprecations/pending-removal-in-3.14.rst:72 +#: ../../deprecations/pending-removal-in-3.14.rst:69 msgid "" ":mod:`multiprocessing`: The default start method will change to a safer one " "on Linux, BSDs, and other non-macOS POSIX platforms where ``'fork'`` is " @@ -3715,7 +4221,7 @@ msgid "" "set_start_method` APIs to explicitly specify when your code *requires* " "``'fork'``. See :ref:`multiprocessing-start-methods`." msgstr "" -":mod:`multiprocessing`: O método de inicialização padrão será alterado para " +":mod:`multiprocessing`: o método de inicialização padrão será alterado para " "um mais seguro no Linux, BSDs e outras plataformas POSIX não-macOS onde " "``'fork'`` é atualmente o padrão (:gh:`84559`). Adicionar um aviso de tempo " "de execução sobre isso foi considerado muito perturbador, pois não se espera " @@ -3724,7 +4230,7 @@ msgstr "" "explicitamente quando seu código *requer* ``'fork'``. Veja :ref:" "`multiprocessing-start-methods`." -#: ../../deprecations/pending-removal-in-3.14.rst:80 +#: ../../deprecations/pending-removal-in-3.14.rst:77 msgid "" ":mod:`pathlib`: :meth:`~pathlib.PurePath.is_relative_to` and :meth:`~pathlib." "PurePath.relative_to`: passing additional arguments is deprecated." @@ -3732,7 +4238,7 @@ msgstr "" ":mod:`pathlib`: :meth:`~pathlib.PurePath.is_relative_to` e :meth:`~pathlib." "PurePath.relative_to`: passar argumentos adicionais foi descontinuado." -#: ../../deprecations/pending-removal-in-3.14.rst:84 +#: ../../deprecations/pending-removal-in-3.14.rst:81 msgid "" ":mod:`pkgutil`: :func:`~pkgutil.find_loader` and :func:`~pkgutil.get_loader` " "now raise :exc:`DeprecationWarning`; use :func:`importlib.util.find_spec` " @@ -3740,59 +4246,35 @@ msgid "" msgstr "" ":mod:`pkgutil`: :func:`~pkgutil.find_loader` e :func:`~pkgutil.get_loader` " "agora levantam :exc:`DeprecationWarning`; use :func:`importlib.util." -"find_spec` em vez disto. (Contribuição de Nikita Sobolev em :gh:`97850`.)" +"find_spec`. (Contribuição de Nikita Sobolev em :gh:`97850`.)" -#: ../../deprecations/pending-removal-in-3.14.rst:89 +#: ../../deprecations/pending-removal-in-3.14.rst:86 msgid ":mod:`pty`:" msgstr ":mod:`pty`:" -#: ../../deprecations/pending-removal-in-3.14.rst:91 +#: ../../deprecations/pending-removal-in-3.14.rst:88 msgid "``master_open()``: use :func:`pty.openpty`." msgstr "``master_open()``: use :func:`pty.openpty`." -#: ../../deprecations/pending-removal-in-3.14.rst:92 +#: ../../deprecations/pending-removal-in-3.14.rst:89 msgid "``slave_open()``: use :func:`pty.openpty`." msgstr "``slave_open()``: use :func:`pty.openpty`." -#: ../../deprecations/pending-removal-in-3.14.rst:94 -msgid ":mod:`sqlite3`:" -msgstr ":mod:`sqlite3`:" - -#: ../../deprecations/pending-removal-in-3.14.rst:96 +#: ../../deprecations/pending-removal-in-3.14.rst:93 msgid ":data:`~sqlite3.version` and :data:`~sqlite3.version_info`." msgstr ":data:`~sqlite3.version` e :data:`~sqlite3.version_info`." -#: ../../deprecations/pending-removal-in-3.14.rst:98 +#: ../../deprecations/pending-removal-in-3.14.rst:95 msgid "" ":meth:`~sqlite3.Cursor.execute` and :meth:`~sqlite3.Cursor.executemany` if :" "ref:`named placeholders ` are used and *parameters* is " "a sequence instead of a :class:`dict`." msgstr "" ":meth:`~sqlite3.Cursor.execute` e :meth:`~sqlite3.Cursor.executemany` se :" -"ref:`espaços reservados nomeados ` forem usados ​​e " +"ref:`espaços reservados nomeados ` forem usados e " "*parameters* for uma sequência em vez de um :class:`dict` ." -#: ../../deprecations/pending-removal-in-3.14.rst:102 -msgid "" -"date and datetime adapter, date and timestamp converter: see the :mod:" -"`sqlite3` documentation for suggested replacement recipes." -msgstr "" -"adaptador de data e hora, conversor de registro de data e hora: veja a " -"documentação de :mod:`sqlite3` para receitas de substituição sugeridas." - -#: ../../deprecations/pending-removal-in-3.14.rst:105 -msgid "" -":class:`types.CodeType`: Accessing :attr:`~codeobject.co_lnotab` was " -"deprecated in :pep:`626` since 3.10 and was planned to be removed in 3.12, " -"but it only got a proper :exc:`DeprecationWarning` in 3.12. May be removed " -"in 3.14. (Contributed by Nikita Sobolev in :gh:`101866`.)" -msgstr "" -":class:`types.CodeType`: O acesso a :attr:`~codeobject.co_lnotab` foi " -"descontinuado na :pep:`626` desde 3.10 e foi planejado para ser removido em " -"3.12, mas só recebeu uma :exc:`DeprecationWarning` adequada em 3.12. Pode " -"ser removido em 3.14. (Contribuição de Nikita Sobolev em :gh:`101866`.)" - -#: ../../deprecations/pending-removal-in-3.14.rst:112 +#: ../../deprecations/pending-removal-in-3.14.rst:99 msgid "" ":mod:`typing`: :class:`~typing.ByteString`, deprecated since Python 3.9, now " "causes a :exc:`DeprecationWarning` to be emitted when it is used." @@ -3800,7 +4282,7 @@ msgstr "" ":mod:`typing`: :class:`~typing.ByteString`, descontinuado desde Python 3.9, " "agora faz com que uma :exc:`DeprecationWarning` seja emitida quando é usado." -#: ../../deprecations/pending-removal-in-3.14.rst:115 +#: ../../deprecations/pending-removal-in-3.14.rst:102 msgid "" ":mod:`urllib`: :class:`!urllib.parse.Quoter` is deprecated: it was not " "intended to be a public API. (Contributed by Gregory P. Smith in :gh:" @@ -3816,165 +4298,335 @@ msgid "Pending Removal in Python 3.15" msgstr "Remoção pendente no Python 3.15" #: ../../deprecations/pending-removal-in-3.15.rst:4 -msgid "" -":class:`http.server.CGIHTTPRequestHandler` will be removed along with its " -"related ``--cgi`` flag to ``python -m http.server``. It was obsolete and " -"rarely used. No direct replacement exists. *Anything* is better than CGI " -"to interface a web server with a request handler." -msgstr "" -":class:`http.server.CGIHTTPRequestHandler` será removido junto com seu " -"sinalizador relacionado ``--cgi`` para ``python -m http.server``. Estava " -"descontinuado e raramente usado. Não existe substituição direta. *Qualquer " -"coisa* é melhor que CGI para fazer a interface de um servidor web com um " -"manipulador de solicitações." - -#: ../../deprecations/pending-removal-in-3.15.rst:9 -msgid "" -":class:`locale`: :func:`locale.getdefaultlocale` was deprecated in Python " -"3.11 and originally planned for removal in Python 3.13 (:gh:`90817`), but " -"removal has been postponed to Python 3.15. Use :func:`locale.setlocale()`, :" -"func:`locale.getencoding()` and :func:`locale.getlocale()` instead. " -"(Contributed by Hugo van Kemenade in :gh:`111187`.)" -msgstr "" -":class:`locale`: :func:`locale.getdefaultlocale` foi descontinuada no Python " -"3.11 e originalmente planejada para remoção no Python 3.13 (:gh:`90817`), " -"mas a remoção foi adiada para o Python 3.15. Use :func:`locale." -"setlocale()`, :func:`locale.getencoding()` e :func:`locale.getlocale()` em " -"vez disso. (Contribuição de Hugo van Kemenade em :gh:`111187`.)" - -#: ../../deprecations/pending-removal-in-3.15.rst:27 -msgid "" -":mod:`threading`: Passing any arguments to :func:`threading.RLock` is now " -"deprecated. C version allows any numbers of args and kwargs, but they are " -"just ignored. Python version does not allow any arguments. All arguments " -"will be removed from :func:`threading.RLock` in Python 3.15. (Contributed by " -"Nikita Sobolev in :gh:`102029`.)" -msgstr "" -":mod:`threading`: Passar qualquer argumento para :func:`threading.RLock` " -"agora está descontinuado. A versão C permite qualquer número de args e " -"kwargs, mas eles são simplesmente ignorados. A versão Python não permite " -"nenhum argumento. Todos os argumentos serão removidos de :func:`threading." -"RLock` no Python 3.15. (Contribuição de Nikita Sobolev em :gh:`102029`.)" - -#: ../../deprecations/pending-removal-in-3.15.rst:34 -msgid ":class:`typing.NamedTuple`:" -msgstr ":class:`typing.NamedTuple`:" +#: ../../deprecations/pending-removal-in-3.16.rst:4 +msgid "The import system:" +msgstr "O sistema de importação:" -#: ../../deprecations/pending-removal-in-3.15.rst:36 +#: ../../deprecations/pending-removal-in-3.15.rst:6 msgid "" -"The undocumented keyword argument syntax for creating :class:`!NamedTuple` " -"classes (``NT = NamedTuple(\"NT\", x=int)``) is deprecated, and will be " -"disallowed in 3.15. Use the class-based syntax or the functional syntax " -"instead." +"Setting :attr:`~module.__cached__` on a module while failing to set :attr:" +"`__spec__.cached ` is deprecated. In " +"Python 3.15, :attr:`!__cached__` will cease to be set or take into " +"consideration by the import system or standard library. (:gh:`97879`)" msgstr "" -"A sintaxe de argumento nomeado não documentada para criar classes :class:`!" -"NamedTuple` (``NT = NamedTuple(\"NT\", x=int)``) está descontinuada e não " -"será permitida em 3.15. Use a sintaxe baseada em classe ou a sintaxe " -"funcional." - -#: ../../deprecations/pending-removal-in-3.15.rst:40 -msgid "" -"When using the functional syntax to create a :class:`!NamedTuple` class, " -"failing to pass a value to the *fields* parameter (``NT = " -"NamedTuple(\"NT\")``) is deprecated. Passing ``None`` to the *fields* " -"parameter (``NT = NamedTuple(\"NT\", None)``) is also deprecated. Both will " -"be disallowed in Python 3.15. To create a :class:`!NamedTuple` class with 0 " -"fields, use ``class NT(NamedTuple): pass`` or ``NT = NamedTuple(\"NT\", " -"[])``." -msgstr "" -"Ao usar a sintaxe funcional para criar uma classe :class:`!NamedTuple`, " -"falhar ao passar um valor para o parâmetro *fields* (``NT = " -"NamedTuple(\"NT\")``) está descontinuada. Passar ``None`` para o parâmetro " -"*fields* (``NT = NamedTuple(\"NT\", None)``) também está descontinuada. " -"Ambos não serão permitidos no Python 3.15. Para criar uma classe :class:`!" -"NamedTuple` com 0 campos, use ``class NT(NamedTuple): pass`` ou ``NT = " -"NamedTuple(\"NT\", [])``." - -#: ../../deprecations/pending-removal-in-3.15.rst:47 -msgid "" -":class:`typing.TypedDict`: When using the functional syntax to create a :" -"class:`!TypedDict` class, failing to pass a value to the *fields* parameter " -"(``TD = TypedDict(\"TD\")``) is deprecated. Passing ``None`` to the *fields* " -"parameter (``TD = TypedDict(\"TD\", None)``) is also deprecated. Both will " -"be disallowed in Python 3.15. To create a :class:`!TypedDict` class with 0 " -"fields, use ``class TD(TypedDict): pass`` or ``TD = TypedDict(\"TD\", {})``." -msgstr "" -":class:`typing.TypedDict`: Ao usar a sintaxe funcional para criar uma " -"classe :class:`!TypedDict`, falhar ao passar um valor para o parâmetro " -"*fields* (``TD = TypedDict(\"TD\")``) está descontinuada. Passar ``None`` " -"para o parâmetro *fields* (``TD = TypedDict(\"TD\", None)``) também está " -"descontinuada. Ambos não serão permitidos no Python 3.15. Para criar uma " -"classe :class:`!TypedDict` com 0 campos, use ``class TD(TypedDict): pass`` " -"ou ``TD = TypedDict(\"TD\", {})``." +"A definição de :attr:`~module.__cached__` em um módulo enquanto falha na " +"definição de :attr:`__spec__.cached ` " +"está descontinuado. No Python 3.15, :attr:`!__cached__` deixará de ser " +"definido ou levado em consideração pelo sistema de importação ou pela " +"biblioteca padrão. (:gh:`97879`)" -#: ../../deprecations/pending-removal-in-3.16.rst:2 -msgid "Pending Removal in Python 3.16" -msgstr "Remoção pendente no Python 3.16" - -#: ../../deprecations/pending-removal-in-3.16.rst:4 +#: ../../deprecations/pending-removal-in-3.15.rst:11 msgid "" -":mod:`array`: :class:`array.array` ``'u'`` type (:c:type:`wchar_t`): use the " -"``'w'`` type instead (``Py_UCS4``)." +"Setting :attr:`~module.__package__` on a module while failing to set :attr:" +"`__spec__.parent ` is deprecated. In " +"Python 3.15, :attr:`!__package__` will cease to be set or take into " +"consideration by the import system or standard library. (:gh:`97879`)" msgstr "" -":mod:`array`: :class:`array.array`: tipo ``'u'`` (:c:type:`wchar_t`): use o " -"tipo ``'w'`` (``Py_UCS4``)." +"A definição de :attr:`~module.__package__` em um módulo enquanto falha na " +"definição de :attr:`__spec__.parent ` " +"está descontinuado. No Python 3.15, :attr:`!__package__` deixará de ser " +"definido ou levado em consideração pelo sistema de importação ou pela " +"biblioteca padrão. (:gh:`97879`)" -#: ../../deprecations/pending-removal-in-3.16.rst:8 +#: ../../deprecations/pending-removal-in-3.15.rst:18 msgid "" -":mod:`symtable`: Deprecate :meth:`symtable.Class.get_methods` due to the " -"lack of interest. (Contributed by Bénédikt Tran in :gh:`119698`.)" +"The undocumented :func:`!ctypes.SetPointerType` function has been deprecated " +"since Python 3.13." msgstr "" -":mod:`symtable`: Descontinua :meth:`symtable.Class.get_methods` por falta de " -"interesse. (Contribuição de Bénédikt Tran em :gh:`119698`.)" - -#: ../../deprecations/c-api-pending-removal-in-future.rst:2 -#: ../../deprecations/pending-removal-in-future.rst:2 -msgid "Pending Removal in Future Versions" -msgstr "Remoção pendente em versões futuras" +"A função não documentada :func:`!ctypes.SetPointerType` foi descontinuada " +"desde o Python 3.13." -#: ../../deprecations/pending-removal-in-future.rst:4 +#: ../../deprecations/pending-removal-in-3.15.rst:23 msgid "" -"The following APIs will be removed in the future, although there is " -"currently no date scheduled for their removal." +"The obsolete and rarely used :class:`~http.server.CGIHTTPRequestHandler` has " +"been deprecated since Python 3.13. No direct replacement exists. *Anything* " +"is better than CGI to interface a web server with a request handler." msgstr "" -"As APIs a seguir serão removidas no futuro, embora atualmente não haja uma " -"data agendada para sua remoção." +"A classe obsoleta e raramente usada :class:`~http.server." +"CGIHTTPRequestHandler` foi descontinuada desde o Python 3.13. Não existe " +"substituição direta. *Qualquer coisa* é melhor que CGI para fazer a " +"interface de um servidor web com um manipulador de requisição." -#: ../../deprecations/pending-removal-in-future.rst:7 +#: ../../deprecations/pending-removal-in-3.15.rst:29 msgid "" -":mod:`argparse`: Nesting argument groups and nesting mutually exclusive " -"groups are deprecated." +"The :option:`!--cgi` flag to the :program:`python -m http.server` command-" +"line interface has been deprecated since Python 3.13." msgstr "" -":mod:`argparse`: O aninhamento de grupos de argumentos e o aninhamento de " -"grupos mutuamente exclusivos estão descontinuados." +"O sinalizador :option:`!--cgi` para a interface de linha de comando :program:" +"`python -m http.server` foi descontinuado desde o Python 3.13." -#: ../../deprecations/pending-removal-in-future.rst:10 -msgid ":mod:`array`'s ``'u'`` format code (:gh:`57281`)" -msgstr "código de formatação ``'u'`` do :mod:`array` (:gh:`57281`)" +#: ../../deprecations/pending-removal-in-3.15.rst:32 +#: ../../deprecations/pending-removal-in-future.rst:56 +msgid ":mod:`importlib`:" +msgstr ":mod:`importlib`:" -#: ../../deprecations/pending-removal-in-future.rst:12 -msgid ":mod:`builtins`:" -msgstr ":mod:`builtins`:" +#: ../../deprecations/pending-removal-in-3.15.rst:34 +msgid "``load_module()`` method: use ``exec_module()`` instead." +msgstr "Método ``load_module()``: use ``exec_module()``." + +#: ../../deprecations/pending-removal-in-3.15.rst:36 +msgid ":class:`locale`:" +msgstr ":class:`locale`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:38 +msgid "" +"The :func:`~locale.getdefaultlocale` function has been deprecated since " +"Python 3.11. Its removal was originally planned for Python 3.13 (:gh:" +"`90817`), but has been postponed to Python 3.15. Use :func:`~locale." +"getlocale`, :func:`~locale.setlocale`, and :func:`~locale.getencoding` " +"instead. (Contributed by Hugo van Kemenade in :gh:`111187`.)" +msgstr "" +"A função :func:`~locale.getdefaultlocale` foi descontinuada desde o Python " +"3.11. Sua remoção foi planejada originalmente para o Python 3.13 (:gh:" +"`90817`), mas foi adiada para o Python 3.15. Em vez disso, use :func:" +"`~locale.getlocale`, :func:`~locale.setlocale` e :func:`~locale." +"getencoding`. (Contribuição de Hugo van Kemenade em :gh:`111187`.)" + +#: ../../deprecations/pending-removal-in-3.15.rst:48 +msgid "" +":meth:`.PurePath.is_reserved` has been deprecated since Python 3.13. Use :" +"func:`os.path.isreserved` to detect reserved paths on Windows." +msgstr "" +":meth:`.PurePath.is_reserved` foi descontinuado desde o Python 3.13. Use :" +"func:`os.path.isreserved` para detectar caminhos reservados no Windows." + +#: ../../deprecations/pending-removal-in-3.15.rst:54 +msgid "" +":func:`~platform.java_ver` has been deprecated since Python 3.13. This " +"function is only useful for Jython support, has a confusing API, and is " +"largely untested." +msgstr "" +":func:`~platform.java_ver` foi descontinuada desde o Python 3.13. Esta " +"função é útil apenas para suporte Jython, tem uma API confusa e é amplamente " +"não testada." + +#: ../../deprecations/pending-removal-in-3.15.rst:58 +msgid ":mod:`sysconfig`:" +msgstr ":mod:`sysconfig`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:60 +msgid "" +"The *check_home* argument of :func:`sysconfig.is_python_build` has been " +"deprecated since Python 3.12." +msgstr "" +"O argumento *check_home* de :func:`sysconfig.is_python_build` foi " +"descontinuado desde o Python 3.12." + +#: ../../deprecations/pending-removal-in-3.15.rst:63 +msgid ":mod:`threading`:" +msgstr ":mod:`threading`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:65 +msgid "" +":func:`~threading.RLock` will take no arguments in Python 3.15. Passing any " +"arguments has been deprecated since Python 3.14, as the Python version does " +"not permit any arguments, but the C version allows any number of positional " +"or keyword arguments, ignoring every argument." +msgstr "" +":func:`~threading.RLock` não aceitará argumentos no Python 3.15. A passagem " +"quaisquer argumentos foi descontinuada desde o Python 3.14, pois a versão " +"Python não permite nenhum argumento, mas a versão C permite qualquer número " +"de argumentos posicionais ou nomeados, ignorando todos os argumentos." + +#: ../../deprecations/pending-removal-in-3.15.rst:71 +msgid ":mod:`types`:" +msgstr ":mod:`types`:" + +#: ../../deprecations/pending-removal-in-3.15.rst:73 +msgid "" +":class:`types.CodeType`: Accessing :attr:`~codeobject.co_lnotab` was " +"deprecated in :pep:`626` since 3.10 and was planned to be removed in 3.12, " +"but it only got a proper :exc:`DeprecationWarning` in 3.12. May be removed " +"in 3.15. (Contributed by Nikita Sobolev in :gh:`101866`.)" +msgstr "" +":class:`types.CodeType`: o acesso a :attr:`~codeobject.co_lnotab` foi " +"descontinuado na :pep:`626` desde 3.10 e foi planejado para ser removido em " +"3.12, mas só recebeu uma :exc:`DeprecationWarning` adequada em 3.12. Pode " +"ser removido em 3.15. (Contribuição de Nikita Sobolev em :gh:`101866`.)" + +#: ../../deprecations/pending-removal-in-3.15.rst:82 +msgid "" +"The undocumented keyword argument syntax for creating :class:`~typing." +"NamedTuple` classes (e.g. ``Point = NamedTuple(\"Point\", x=int, y=int)``) " +"has been deprecated since Python 3.13. Use the class-based syntax or the " +"functional syntax instead." +msgstr "" +"A não-documentada sintaxe de argumento nomeado para criar classes :class:" +"`~typing.NamedTuple` (por exemplo, ``Point = NamedTuple(\"Point\", x=int, " +"y=int)``) foi descontinuada desde o Python 3.13. Em vez disso, use as " +"sintaxes baseada em classe ou funcional." + +#: ../../deprecations/pending-removal-in-3.15.rst:88 +msgid "" +"When using the functional syntax of :class:`~typing.TypedDict`\\s, failing " +"to pass a value to the *fields* parameter (``TD = TypedDict(\"TD\")``) or " +"passing ``None`` (``TD = TypedDict(\"TD\", None)``) has been deprecated " +"since Python 3.13. Use ``class TD(TypedDict): pass`` or ``TD = " +"TypedDict(\"TD\", {})`` to create a TypedDict with zero field." +msgstr "" +"Ao usar a sintaxe funcional de :class:`~typing.TypedDict`\\s, não passar um " +"valor para o parâmetro *fields* (``TD = TypedDict(\"TD\")``) ou passar " +"``None`` (``TD = TypedDict(\"TD\", None)``) foi está descontinuado desde o " +"Python 3.13. Use ``class TD(TypedDict): pass`` ou ``TD = TypedDict(\"TD\", " +"{})`` para criar uma classe TypedDict com nenhum campo." + +#: ../../deprecations/pending-removal-in-3.15.rst:95 +msgid "" +"The :func:`typing.no_type_check_decorator` decorator function has been " +"deprecated since Python 3.13. After eight years in the :mod:`typing` module, " +"it has yet to be supported by any major type checker." +msgstr "" +"A função decoradora :func:`typing.no_type_check_decorator` foi descontinuada " +"desde o Python 3.13. Após oito anos no módulo :mod:`typing`, ela ainda não " +"foi suportada por nenhum verificador de tipo importante." + +#: ../../deprecations/pending-removal-in-3.15.rst:102 +msgid "" +"The :meth:`~wave.Wave_read.getmark`, :meth:`!setmark`, and :meth:`~wave." +"Wave_read.getmarkers` methods of the :class:`~wave.Wave_read` and :class:" +"`~wave.Wave_write` classes have been deprecated since Python 3.13." +msgstr "" +"Os métodos :meth:`~wave.Wave_read.getmark`, :meth:`!setmark` e :meth:`~wave." +"Wave_read.getmarkers` das classes :class:`~wave.Wave_read` e :class:`~wave." +"Wave_write` foram descontinuados desde o Python 3.13." + +#: ../../deprecations/pending-removal-in-3.16.rst:2 +msgid "Pending removal in Python 3.16" +msgstr "Remoção pendente no Python 3.16" + +#: ../../deprecations/pending-removal-in-3.16.rst:6 +msgid "" +"Setting :attr:`~module.__loader__` on a module while failing to set :attr:" +"`__spec__.loader ` is deprecated. In " +"Python 3.16, :attr:`!__loader__` will cease to be set or taken into " +"consideration by the import system or the standard library." +msgstr "" +"A definição de :attr:`~module.__loader__` em um módulo enquanto falha na " +"definição de :attr:`__spec__.loader ` " +"está descontinuado. No Python 3.16, :attr:`!__loader__` deixará de ser " +"definido ou levado em consideração pelo sistema de importação ou pela " +"biblioteca padrão." + +#: ../../deprecations/pending-removal-in-3.16.rst:13 +msgid "" +"The ``'u'`` format code (:c:type:`wchar_t`) has been deprecated in " +"documentation since Python 3.3 and at runtime since Python 3.13. Use the " +"``'w'`` format code (:c:type:`Py_UCS4`) for Unicode characters instead." +msgstr "" +"O código de formato ``'u'`` (:c:type:`wchar_t`) foi descontinuado na " +"documentação desde o Python 3.3 e do ambiente de execução desde o Python " +"3.13. Em vez disso, use o código de formato ``'w'`` (:c:type:`Py_UCS4`) para " +"caracteres Unicode." + +#: ../../deprecations/pending-removal-in-3.16.rst:21 +msgid "" +":func:`!asyncio.iscoroutinefunction` is deprecated and will be removed in " +"Python 3.16, use :func:`inspect.iscoroutinefunction` instead. (Contributed " +"by Jiahao Li and Kumar Aditya in :gh:`122875`.)" +msgstr "" +":func:`!asyncio.iscoroutinefunction` foi descontinuado e será removido no " +"Python 3.16, use :func:`inspect.iscoroutinefunction` em vez disso. " +"(Contribuição de Jiahao Li e Kumar Aditya em :gh:`122875`.)" + +#: ../../deprecations/pending-removal-in-3.16.rst:26 +#: ../../deprecations/pending-removal-in-future.rst:10 +msgid ":mod:`builtins`:" +msgstr ":mod:`builtins`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:28 +msgid "" +"Bitwise inversion on boolean types, ``~True`` or ``~False`` has been " +"deprecated since Python 3.12, as it produces surprising and unintuitive " +"results (``-2`` and ``-1``). Use ``not x`` instead for the logical negation " +"of a Boolean. In the rare case that you need the bitwise inversion of the " +"underlying integer, convert to ``int`` explicitly (``~int(x)``)." +msgstr "" +"A inversão bit a bit em tipos booleanos, ``~True`` ou ``~False`` foi " +"descontinuada desde o Python 3.12, pois produz resultados surpreendentes e " +"não intuitivos (``-2`` e ``-1``). Em vez disso, use ``not x`` para a negação " +"lógica de um booleano. No caso raro de você precisar da inversão bit a bit " +"do inteiro subjacente, converta para ``int`` explicitamente (``~int(x)``)." + +#: ../../deprecations/pending-removal-in-3.16.rst:35 +msgid ":mod:`shutil`:" +msgstr ":mod:`shutil`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:37 +msgid "" +"The :class:`!ExecError` exception has been deprecated since Python 3.14. It " +"has not been used by any function in :mod:`!shutil` since Python 3.4, and is " +"now an alias of :exc:`RuntimeError`." +msgstr "" +"A exceção :class:`!ExecError` foi descontinuada desde o Python 3.14. Ela não " +"foi usada por nenhuma função em :mod:`!shutil` desde o Python 3.4, e agora é " +"um alias de :exc:`RuntimeError`." + +#: ../../deprecations/pending-removal-in-3.16.rst:42 +msgid ":mod:`symtable`:" +msgstr ":mod:`symtable`:" + +#: ../../deprecations/pending-removal-in-3.16.rst:44 +msgid "" +"The :meth:`Class.get_methods ` method has been " +"deprecated since Python 3.14." +msgstr "" +"O método :meth:`Class.get_methods ` foi " +"descontinuado desde o Python 3.14." + +#: ../../deprecations/pending-removal-in-3.16.rst:49 +msgid "" +"The :func:`~sys._enablelegacywindowsfsencoding` function has been deprecated " +"since Python 3.13. Use the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` " +"environment variable instead." +msgstr "" +"A função :func:`~sys._enablelegacywindowsfsencoding` foi descontinuada desde " +"o Python 3.13. Em vez disso, use a variável de ambiente :envvar:" +"`PYTHONLEGACYWINDOWSFSENCODING`." + +#: ../../deprecations/pending-removal-in-3.16.rst:55 +msgid "" +"The undocumented and unused :attr:`!TarFile.tarfile` attribute has been " +"deprecated since Python 3.13." +msgstr "" +"O atributo não documentado e não utilizado :attr:`!TarFile.tarfile` foi " +"descontinuado desde o Python 3.13." + +#: ../../deprecations/c-api-pending-removal-in-future.rst:2 +#: ../../deprecations/pending-removal-in-future.rst:2 +msgid "Pending Removal in Future Versions" +msgstr "Remoção pendente em versões futuras" + +#: ../../deprecations/pending-removal-in-future.rst:4 +msgid "" +"The following APIs will be removed in the future, although there is " +"currently no date scheduled for their removal." +msgstr "" +"As APIs a seguir serão removidas no futuro, embora atualmente não haja uma " +"data agendada para sua remoção." -#: ../../deprecations/pending-removal-in-future.rst:14 -msgid "``~bool``, bitwise inversion on bool." -msgstr "``~bool``, inversão bit a bit em booleanos." +#: ../../deprecations/pending-removal-in-future.rst:7 +msgid "" +":mod:`argparse`: Nesting argument groups and nesting mutually exclusive " +"groups are deprecated." +msgstr "" +":mod:`argparse`: o aninhamento de grupos de argumentos e o aninhamento de " +"grupos mutuamente exclusivos estão descontinuados." -#: ../../deprecations/pending-removal-in-future.rst:15 +#: ../../deprecations/pending-removal-in-future.rst:12 msgid "``bool(NotImplemented)``." msgstr "``bool(NotImplemented)``." -#: ../../deprecations/pending-removal-in-future.rst:16 +#: ../../deprecations/pending-removal-in-future.rst:13 msgid "" "Generators: ``throw(type, exc, tb)`` and ``athrow(type, exc, tb)`` signature " "is deprecated: use ``throw(exc)`` and ``athrow(exc)`` instead, the single " "argument signature." msgstr "" -"Geradores: A assinatura ``throw(type, exc, tb)`` e ``athrow(type, exc, tb)`` " +"Geradores: a assinatura ``throw(type, exc, tb)`` e ``athrow(type, exc, tb)`` " "está descontinuada: use ``throw(exc)`` e ``athrow(exc)``, a assinatura do " "argumento único." -#: ../../deprecations/pending-removal-in-future.rst:19 +#: ../../deprecations/pending-removal-in-future.rst:16 msgid "" "Currently Python accepts numeric literals immediately followed by keywords, " "for example ``0in x``, ``1or x``, ``0if 1else 2``. It allows confusing and " @@ -3995,7 +4647,7 @@ msgstr "" "e :keyword:`or`. Em uma versão futura, será alterado para um erro de " "sintaxe. (:gh:`87999`)" -#: ../../deprecations/pending-removal-in-future.rst:27 +#: ../../deprecations/pending-removal-in-future.rst:24 msgid "" "Support for ``__index__()`` and ``__int__()`` method returning non-int type: " "these methods will be required to return an instance of a strict subclass " @@ -4005,7 +4657,7 @@ msgstr "" "int: esses métodos serão necessários para retornar uma instância de uma " "subclasse estrita de :class:`int`." -#: ../../deprecations/pending-removal-in-future.rst:30 +#: ../../deprecations/pending-removal-in-future.rst:27 msgid "" "Support for ``__float__()`` method returning a strict subclass of :class:" "`float`: these methods will be required to return an instance of :class:" @@ -4015,7 +4667,7 @@ msgstr "" "class:`float`: esses métodos serão necessários para retornar uma instância " "de :class:`float`." -#: ../../deprecations/pending-removal-in-future.rst:33 +#: ../../deprecations/pending-removal-in-future.rst:30 msgid "" "Support for ``__complex__()`` method returning a strict subclass of :class:" "`complex`: these methods will be required to return an instance of :class:" @@ -4025,11 +4677,11 @@ msgstr "" "class:`complex`: esses métodos serão necessários para retornar uma instância " "de :class:`complex`." -#: ../../deprecations/pending-removal-in-future.rst:36 +#: ../../deprecations/pending-removal-in-future.rst:33 msgid "Delegation of ``int()`` to ``__trunc__()`` method." msgstr "Delegação do método ``int()`` para o ``__trunc__()``." -#: ../../deprecations/pending-removal-in-future.rst:37 +#: ../../deprecations/pending-removal-in-future.rst:34 msgid "" "Passing a complex number as the *real* or *imag* argument in the :func:" "`complex` constructor is now deprecated; it should only be passed as a " @@ -4041,28 +4693,28 @@ msgstr "" "único argumento posicional. (Contribuição de Serhiy Storchaka em :gh:" "`109218`.)" -#: ../../deprecations/pending-removal-in-future.rst:42 +#: ../../deprecations/pending-removal-in-future.rst:39 msgid "" ":mod:`calendar`: ``calendar.January`` and ``calendar.February`` constants " "are deprecated and replaced by :data:`calendar.JANUARY` and :data:`calendar." "FEBRUARY`. (Contributed by Prince Roshan in :gh:`103636`.)" msgstr "" -":mod:`calendar`: As constantes ``calendar.January`` e ``calendar.February`` " +":mod:`calendar`: as constantes ``calendar.January`` e ``calendar.February`` " "foram descontinuadas e substituídas por :data:`calendar.JANUARY` e :data:" "`calendar.FEBRUARY`. (Contribuição de Prince Roshan em :gh:`103636`.)" -#: ../../deprecations/pending-removal-in-future.rst:47 +#: ../../deprecations/pending-removal-in-future.rst:44 msgid "" ":attr:`codeobject.co_lnotab`: use the :meth:`codeobject.co_lines` method " "instead." msgstr "" ":attr:`codeobject.co_lnotab`: use o método :meth:`codeobject.co_lines`." -#: ../../deprecations/pending-removal-in-future.rst:50 +#: ../../deprecations/pending-removal-in-future.rst:47 msgid ":mod:`datetime`:" msgstr ":mod:`datetime`:" -#: ../../deprecations/pending-removal-in-future.rst:52 +#: ../../deprecations/pending-removal-in-future.rst:49 msgid "" ":meth:`~datetime.datetime.utcnow`: use ``datetime.datetime.now(tz=datetime." "UTC)``." @@ -4070,7 +4722,7 @@ msgstr "" ":meth:`~datetime.datetime.utcnow`: use ``datetime.datetime.now(tz=datetime." "UTC)``." -#: ../../deprecations/pending-removal-in-future.rst:54 +#: ../../deprecations/pending-removal-in-future.rst:51 msgid "" ":meth:`~datetime.datetime.utcfromtimestamp`: use ``datetime.datetime." "fromtimestamp(timestamp, tz=datetime.UTC)``." @@ -4078,68 +4730,60 @@ msgstr "" ":meth:`~datetime.datetime.utcfromtimestamp`: use ``datetime.datetime." "fromtimestamp(timestamp, tz=datetime.UTC)``." -#: ../../deprecations/pending-removal-in-future.rst:57 +#: ../../deprecations/pending-removal-in-future.rst:54 msgid ":mod:`gettext`: Plural value must be an integer." -msgstr ":mod:`gettext`: O valor de plural deve ser um número inteiro." - -#: ../../deprecations/pending-removal-in-future.rst:59 -msgid ":mod:`importlib`:" -msgstr ":mod:`importlib`:" - -#: ../../deprecations/pending-removal-in-future.rst:61 -msgid "``load_module()`` method: use ``exec_module()`` instead." -msgstr "Método ``load_module()``: use ``exec_module()`` em vez disso." +msgstr ":mod:`gettext`: o valor de plural deve ser um número inteiro." -#: ../../deprecations/pending-removal-in-future.rst:62 +#: ../../deprecations/pending-removal-in-future.rst:58 msgid "" ":func:`~importlib.util.cache_from_source` *debug_override* parameter is " "deprecated: use the *optimization* parameter instead." msgstr "" "O parâmetro *debug_override* de :func:`~importlib.util.cache_from_source` " -"foi descontinuado: em vez disso, use o parâmetro *optimization*." +"foi descontinuado: use o parâmetro *optimization*." -#: ../../deprecations/pending-removal-in-future.rst:65 +#: ../../deprecations/pending-removal-in-future.rst:61 msgid ":mod:`importlib.metadata`:" msgstr ":mod:`importlib.metadata`:" -#: ../../deprecations/pending-removal-in-future.rst:67 +#: ../../deprecations/pending-removal-in-future.rst:63 msgid "``EntryPoints`` tuple interface." msgstr "Interface de tupla ``EntryPoints``." -#: ../../deprecations/pending-removal-in-future.rst:68 +#: ../../deprecations/pending-removal-in-future.rst:64 msgid "Implicit ``None`` on return values." msgstr "``None`` implícito nos valores de retorno." -#: ../../deprecations/pending-removal-in-future.rst:70 +#: ../../deprecations/pending-removal-in-future.rst:66 msgid "" ":mod:`logging`: the ``warn()`` method has been deprecated since Python 3.3, " -"use :meth:`~logging.warning()` instead." +"use :meth:`~logging.warning` instead." msgstr "" ":mod:`logging`: o método ``warn()`` foi descontinuado desde o Python 3.3, " -"use :meth:`~logging.warning()`." +"use :meth:`~logging.warning`." -#: ../../deprecations/pending-removal-in-future.rst:73 +#: ../../deprecations/pending-removal-in-future.rst:69 msgid "" ":mod:`mailbox`: Use of StringIO input and text mode is deprecated, use " "BytesIO and binary mode instead." msgstr "" -":mod:`mailbox`: O uso da entrada StringIO e do modo de texto foi " +":mod:`mailbox`: o uso da entrada StringIO e do modo de texto foi " "descontinuado; em vez disso, use BytesIO e o modo binário." -#: ../../deprecations/pending-removal-in-future.rst:76 +#: ../../deprecations/pending-removal-in-future.rst:72 msgid "" ":mod:`os`: Calling :func:`os.register_at_fork` in multi-threaded process." -msgstr ":mod:`os`: Chamar :func:`os.register_at_fork` em processo multithread." +msgstr ":mod:`os`: chame :func:`os.register_at_fork` em processo multithread." -#: ../../deprecations/pending-removal-in-future.rst:78 +#: ../../deprecations/pending-removal-in-future.rst:74 msgid "" ":class:`!pydoc.ErrorDuringImport`: A tuple value for *exc_info* parameter is " "deprecated, use an exception instance." msgstr "" -":class:`!pydoc.ErrorDuringImport`: Um valor de tupla para o parâmetro " +":class:`!pydoc.ErrorDuringImport`: um valor de tupla para o parâmetro " "*exc_info* foi descontinuado, use uma instância de exceção." -#: ../../deprecations/pending-removal-in-future.rst:81 +#: ../../deprecations/pending-removal-in-future.rst:77 msgid "" ":mod:`re`: More strict rules are now applied for numerical group references " "and group names in regular expressions. Only sequence of ASCII digits is " @@ -4147,96 +4791,88 @@ msgid "" "replacement strings can now only contain ASCII letters and digits and " "underscore. (Contributed by Serhiy Storchaka in :gh:`91760`.)" msgstr "" -":mod:`re`: Regras mais rigorosas agora são aplicadas para referências " +":mod:`re`: regras mais rigorosas agora são aplicadas para referências " "numéricas de grupos e nomes de grupos em expressões regulares. Apenas a " "sequência de dígitos ASCII agora é aceita como referência numérica. O nome " "do grupo em padrões de bytes e strings de substituição agora pode conter " "apenas letras e dígitos ASCII e sublinhado. (Contribuição de Serhiy " "Storchaka em :gh:`91760`.)" -#: ../../deprecations/pending-removal-in-future.rst:88 +#: ../../deprecations/pending-removal-in-future.rst:84 msgid "" ":mod:`!sre_compile`, :mod:`!sre_constants` and :mod:`!sre_parse` modules." msgstr "" "Módulos :mod:`!sre_compile`, :mod:`!sre_constants` e :mod:`!sre_parse`." -#: ../../deprecations/pending-removal-in-future.rst:90 +#: ../../deprecations/pending-removal-in-future.rst:86 msgid "" ":mod:`shutil`: :func:`~shutil.rmtree`'s *onerror* parameter is deprecated in " "Python 3.12; use the *onexc* parameter instead." msgstr "" -":mod:`shutil`: O parâmetro *onerror* de :func:`~shutil.rmtree` foi " +":mod:`shutil`: o parâmetro *onerror* de :func:`~shutil.rmtree` foi " "descontinuado no Python 3.12; use o parâmetro *onexc*." -#: ../../deprecations/pending-removal-in-future.rst:93 +#: ../../deprecations/pending-removal-in-future.rst:89 msgid ":mod:`ssl` options and protocols:" msgstr "Protocolos e opções de :mod:`ssl`" -#: ../../deprecations/pending-removal-in-future.rst:95 +#: ../../deprecations/pending-removal-in-future.rst:91 msgid ":class:`ssl.SSLContext` without protocol argument is deprecated." msgstr ":class:`ssl.SSLContext` sem argumento de protocolo foi descontinuado." -#: ../../deprecations/pending-removal-in-future.rst:96 +#: ../../deprecations/pending-removal-in-future.rst:92 msgid "" ":class:`ssl.SSLContext`: :meth:`~ssl.SSLContext.set_npn_protocols` and :meth:" "`!selected_npn_protocol` are deprecated: use ALPN instead." msgstr "" ":class:`ssl.SSLContext`: :meth:`~ssl.SSLContext.set_npn_protocols` e :meth:`!" -"selected_npn_protocol` foram descontinuados: use ALPN." +"selected_npn_protocol` foram descontinuados, use ALPN." -#: ../../deprecations/pending-removal-in-future.rst:99 +#: ../../deprecations/pending-removal-in-future.rst:95 msgid "``ssl.OP_NO_SSL*`` options" msgstr "Opções de ``ssl.OP_NO_SSL*``" -#: ../../deprecations/pending-removal-in-future.rst:100 +#: ../../deprecations/pending-removal-in-future.rst:96 msgid "``ssl.OP_NO_TLS*`` options" msgstr "Opções de ``ssl.OP_NO_TLS*``" -#: ../../deprecations/pending-removal-in-future.rst:101 +#: ../../deprecations/pending-removal-in-future.rst:97 msgid "``ssl.PROTOCOL_SSLv3``" msgstr "``ssl.PROTOCOL_SSLv3``" -#: ../../deprecations/pending-removal-in-future.rst:102 +#: ../../deprecations/pending-removal-in-future.rst:98 msgid "``ssl.PROTOCOL_TLS``" msgstr "``ssl.PROTOCOL_TLS``" -#: ../../deprecations/pending-removal-in-future.rst:103 +#: ../../deprecations/pending-removal-in-future.rst:99 msgid "``ssl.PROTOCOL_TLSv1``" msgstr "``ssl.PROTOCOL_TLSv1``" -#: ../../deprecations/pending-removal-in-future.rst:104 +#: ../../deprecations/pending-removal-in-future.rst:100 msgid "``ssl.PROTOCOL_TLSv1_1``" msgstr "``ssl.PROTOCOL_TLSv1_1``" -#: ../../deprecations/pending-removal-in-future.rst:105 +#: ../../deprecations/pending-removal-in-future.rst:101 msgid "``ssl.PROTOCOL_TLSv1_2``" msgstr "``ssl.PROTOCOL_TLSv1_2``" -#: ../../deprecations/pending-removal-in-future.rst:106 +#: ../../deprecations/pending-removal-in-future.rst:102 msgid "``ssl.TLSVersion.SSLv3``" msgstr "``ssl.TLSVersion.SSLv3``" -#: ../../deprecations/pending-removal-in-future.rst:107 +#: ../../deprecations/pending-removal-in-future.rst:103 msgid "``ssl.TLSVersion.TLSv1``" msgstr "``ssl.TLSVersion.TLSv1``" -#: ../../deprecations/pending-removal-in-future.rst:108 +#: ../../deprecations/pending-removal-in-future.rst:104 msgid "``ssl.TLSVersion.TLSv1_1``" msgstr "``ssl.TLSVersion.TLSv1_1``" -#: ../../deprecations/pending-removal-in-future.rst:110 -msgid "" -":func:`sysconfig.is_python_build` *check_home* parameter is deprecated and " -"ignored." -msgstr "" -"O parâmetro *check_home* de :func:`sysconfig.is_python_build` foi " -"descontinuado e é ignorado." - -#: ../../deprecations/pending-removal-in-future.rst:113 +#: ../../deprecations/pending-removal-in-future.rst:106 msgid ":mod:`threading` methods:" msgstr "Métodos de :mod:`threading`:" -#: ../../deprecations/pending-removal-in-future.rst:115 +#: ../../deprecations/pending-removal-in-future.rst:108 msgid "" ":meth:`!threading.Condition.notifyAll`: use :meth:`~threading.Condition." "notify_all`." @@ -4244,11 +4880,11 @@ msgstr "" ":meth:`!threading.Condition.notifyAll`: use :meth:`~threading.Condition." "notify_all`." -#: ../../deprecations/pending-removal-in-future.rst:116 +#: ../../deprecations/pending-removal-in-future.rst:109 msgid ":meth:`!threading.Event.isSet`: use :meth:`~threading.Event.is_set`." msgstr ":meth:`!threading.Event.isSet`: use :meth:`~threading.Event.is_set`." -#: ../../deprecations/pending-removal-in-future.rst:117 +#: ../../deprecations/pending-removal-in-future.rst:110 msgid "" ":meth:`!threading.Thread.isDaemon`, :meth:`threading.Thread.setDaemon`: use :" "attr:`threading.Thread.daemon` attribute." @@ -4256,7 +4892,7 @@ msgstr "" ":meth:`!threading.Thread.isDaemon`, :meth:`threading.Thread.setDaemon`: use " "o atributo :attr:`threading.Thread.daemon`." -#: ../../deprecations/pending-removal-in-future.rst:119 +#: ../../deprecations/pending-removal-in-future.rst:112 msgid "" ":meth:`!threading.Thread.getName`, :meth:`threading.Thread.setName`: use :" "attr:`threading.Thread.name` attribute." @@ -4264,20 +4900,20 @@ msgstr "" ":meth:`!threading.Thread.getName`, :meth:`threading.Thread.setName`: use o " "atributo :attr:`threading.Thread.name`." -#: ../../deprecations/pending-removal-in-future.rst:121 +#: ../../deprecations/pending-removal-in-future.rst:114 msgid ":meth:`!threading.currentThread`: use :meth:`threading.current_thread`." msgstr "" ":meth:`!threading.currentThread`: use :meth:`threading.current_thread`." -#: ../../deprecations/pending-removal-in-future.rst:122 +#: ../../deprecations/pending-removal-in-future.rst:115 msgid ":meth:`!threading.activeCount`: use :meth:`threading.active_count`." msgstr ":meth:`!threading.activeCount`: use :meth:`threading.active_count`." -#: ../../deprecations/pending-removal-in-future.rst:124 +#: ../../deprecations/pending-removal-in-future.rst:117 msgid ":class:`typing.Text` (:gh:`92332`)." msgstr ":class:`typing.Text` (:gh:`92332`)." -#: ../../deprecations/pending-removal-in-future.rst:126 +#: ../../deprecations/pending-removal-in-future.rst:119 msgid "" ":class:`unittest.IsolatedAsyncioTestCase`: it is deprecated to return a " "value that is not ``None`` from a test case." @@ -4285,7 +4921,7 @@ msgstr "" ":class:`unittest.IsolatedAsyncioTestCase`: foi descontinuado retornar um " "valor que não seja ``None`` de um caso de teste." -#: ../../deprecations/pending-removal-in-future.rst:129 +#: ../../deprecations/pending-removal-in-future.rst:122 msgid "" ":mod:`urllib.parse` deprecated functions: :func:`~urllib.parse.urlparse` " "instead" @@ -4293,62 +4929,62 @@ msgstr "" "Funções descontinuadas de :mod:`urllib.parse`: use :func:`~urllib.parse." "urlparse`" -#: ../../deprecations/pending-removal-in-future.rst:131 +#: ../../deprecations/pending-removal-in-future.rst:124 msgid "``splitattr()``" msgstr "``splitattr()``" -#: ../../deprecations/pending-removal-in-future.rst:132 +#: ../../deprecations/pending-removal-in-future.rst:125 msgid "``splithost()``" msgstr "``splithost()``" -#: ../../deprecations/pending-removal-in-future.rst:133 +#: ../../deprecations/pending-removal-in-future.rst:126 msgid "``splitnport()``" msgstr "``splitnport()``" -#: ../../deprecations/pending-removal-in-future.rst:134 +#: ../../deprecations/pending-removal-in-future.rst:127 msgid "``splitpasswd()``" msgstr "``splitpasswd()``" -#: ../../deprecations/pending-removal-in-future.rst:135 +#: ../../deprecations/pending-removal-in-future.rst:128 msgid "``splitport()``" msgstr "``splitport()``" -#: ../../deprecations/pending-removal-in-future.rst:136 +#: ../../deprecations/pending-removal-in-future.rst:129 msgid "``splitquery()``" msgstr "``splitquery()``" -#: ../../deprecations/pending-removal-in-future.rst:137 +#: ../../deprecations/pending-removal-in-future.rst:130 msgid "``splittag()``" msgstr "``splittag()``" -#: ../../deprecations/pending-removal-in-future.rst:138 +#: ../../deprecations/pending-removal-in-future.rst:131 msgid "``splittype()``" msgstr "``splittype()``" -#: ../../deprecations/pending-removal-in-future.rst:139 +#: ../../deprecations/pending-removal-in-future.rst:132 msgid "``splituser()``" msgstr "``splituser()``" -#: ../../deprecations/pending-removal-in-future.rst:140 +#: ../../deprecations/pending-removal-in-future.rst:133 msgid "``splitvalue()``" msgstr "``splitvalue()``" -#: ../../deprecations/pending-removal-in-future.rst:141 +#: ../../deprecations/pending-removal-in-future.rst:134 msgid "``to_bytes()``" msgstr "``to_bytes()``" -#: ../../deprecations/pending-removal-in-future.rst:143 +#: ../../deprecations/pending-removal-in-future.rst:136 msgid "" ":mod:`urllib.request`: :class:`~urllib.request.URLopener` and :class:" "`~urllib.request.FancyURLopener` style of invoking requests is deprecated. " "Use newer :func:`~urllib.request.urlopen` functions and methods." msgstr "" -":mod:`urllib.request`: O estilo de :class:`~urllib.request.URLopener` e :" +":mod:`urllib.request`: o estilo de :class:`~urllib.request.URLopener` e :" "class:`~urllib.request.FancyURLopener` de invocar solicitações foi " "descontinuado. Use as mais novas funções e métodos :func:`~urllib.request." "urlopen`." -#: ../../deprecations/pending-removal-in-future.rst:147 +#: ../../deprecations/pending-removal-in-future.rst:140 msgid "" ":mod:`wsgiref`: ``SimpleHandler.stdout.write()`` should not do partial " "writes." @@ -4356,7 +4992,7 @@ msgstr "" ":mod:`wsgiref`: ``SimpleHandler.stdout.write()`` não deve fazer gravações " "parciais." -#: ../../deprecations/pending-removal-in-future.rst:150 +#: ../../deprecations/pending-removal-in-future.rst:143 msgid "" ":mod:`xml.etree.ElementTree`: Testing the truth value of an :class:`~xml." "etree.ElementTree.Element` is deprecated. In a future release it will always " @@ -4368,7 +5004,7 @@ msgstr "" "sempre retornará ``True``. Em vez disso, prefira os testes explícitos " "``len(elem)`` ou ``elem is not None``." -#: ../../deprecations/pending-removal-in-future.rst:155 +#: ../../deprecations/pending-removal-in-future.rst:148 msgid "" ":meth:`zipimport.zipimporter.load_module` is deprecated: use :meth:" "`~zipimport.zipimporter.exec_module` instead." @@ -4376,395 +5012,395 @@ msgstr "" ":meth:`zipimport.zipimporter.load_module` foi descontinuado: use :meth:" "`~zipimport.zipimporter.exec_module`." -#: ../../whatsnew/3.13.rst:1715 +#: ../../whatsnew/3.13.rst:2040 msgid "CPython Bytecode Changes" -msgstr "Mudanças no bytecode do CPython" +msgstr "Alterações de bytecode do CPython" -#: ../../whatsnew/3.13.rst:1717 +#: ../../whatsnew/3.13.rst:2042 msgid "" -"The oparg of ``YIELD_VALUE`` is now ``1`` if the yield is part of a yield-" -"from or await, and ``0`` otherwise. The oparg of ``RESUME`` was changed to " -"add a bit indicating whether the except-depth is 1, which is needed to " +"The oparg of :opcode:`YIELD_VALUE` is now ``1`` if the yield is part of a " +"yield-from or await, and ``0`` otherwise. The oparg of :opcode:`RESUME` was " +"changed to add a bit indicating if the except-depth is 1, which is needed to " "optimize closing of generators. (Contributed by Irit Katriel in :gh:" "`111354`.)" msgstr "" -"O oparg de ``YIELD_VALUE`` agora é ``1`` se o yield fizer parte de um yield-" -"from ou um await, e ``0`` caso contrário. O oparg de ``RESUME`` foi alterado " -"para adicionar um bit indicando se a profundidade de exceção é 1, o que é " -"necessário para otimizar o fechamento dos geradores. (Contribuição de Irit " -"Katriel em :gh:`111354`.)" +"O oparg de :opcode:`YIELD_VALUE` agora é ``1`` se o yield fizer parte de um " +"yield-from ou um await, e ``0`` caso contrário. O oparg de :opcode:`RESUME` " +"foi alterado para adicionar um bit indicando se a profundidade de exceção é " +"1, o que é necessário para otimizar o fechamento dos geradores. " +"(Contribuição de Irit Katriel em :gh:`111354`.)" -#: ../../whatsnew/3.13.rst:1725 +#: ../../whatsnew/3.13.rst:2050 msgid "C API Changes" -msgstr "Mudanças na API C" +msgstr "Alterações na API C" -#: ../../whatsnew/3.13.rst:1730 +#: ../../whatsnew/3.13.rst:2055 msgid "" -"You no longer have to define the ``PY_SSIZE_T_CLEAN`` macro before " -"including :file:`Python.h` when using ``#`` formats in :ref:`format codes " -"`. APIs accepting the format codes always " -"use ``Py_ssize_t`` for ``#`` formats. (Contributed by Inada Naoki in :gh:" -"`104922`.)" +"Add the :ref:`PyMonitoring C API ` for generating :pep:" +"`669` monitoring events:" msgstr "" -"Você não precisa mais definir a macro ``PY_SSIZE_T_CLEAN`` antes de incluir :" -"file:`Python.h` ao usar formatos ``#`` em :ref:`códigos de formato `. APIs que aceitam os códigos de formato sempre " -"usam ``Py_ssize_t`` para formatos ``#``. (Contribuição de Inada Naoki em :gh:" -"`104922`.)" +"Adiciona a :ref:`API C PyMonitoring C ` para gerar eventos " +"de monitoramento da :pep:`669`:" -#: ../../whatsnew/3.13.rst:1736 -msgid "" -"The *keywords* parameter of :c:func:`PyArg_ParseTupleAndKeywords` and :c:" -"func:`PyArg_VaParseTupleAndKeywords` now has type :c:expr:`char * const *` " -"in C and :c:expr:`const char * const *` in C++, instead of :c:expr:`char " -"**`. It makes these functions compatible with arguments of type :c:expr:" -"`const char * const *`, :c:expr:`const char **` or :c:expr:`char * const *` " -"in C++ and :c:expr:`char * const *` in C without an explicit type cast. This " -"can be overridden with the :c:macro:`PY_CXX_CONST` macro. (Contributed by " -"Serhiy Storchaka in :gh:`65210`.)" -msgstr "" -"O parâmetro *keywords* de :c:func:`PyArg_ParseTupleAndKeywords` e :c:func:" -"`PyArg_VaParseTupleAndKeywords` agora tem tipo :c:expr:`char * const *` em C " -"e :c:expr:`const char * const *` em C++, em vez de :c:expr:`char **`. Torna " -"essas funções compatíveis com argumentos do tipo :c:expr:`const char * const " -"*`, :c:expr:`const char **` ou :c:expr:`char * const *` em C++ e :c:expr:" -"`char * const *` em C sem uma conversão de tipo explícita. Isso pode ser " -"substituído pela macro :c:macro:`PY_CXX_CONST`. (Contribuição de Serhiy " -"Storchaka em :gh:`65210`.)" +#: ../../whatsnew/3.13.rst:2058 +msgid ":c:type:`PyMonitoringState`" +msgstr ":c:type:`PyMonitoringState`" -#: ../../whatsnew/3.13.rst:1746 -msgid "" -"Add :c:func:`PyImport_AddModuleRef`: similar to :c:func:" -"`PyImport_AddModule`, but return a :term:`strong reference` instead of a :" -"term:`borrowed reference`. (Contributed by Victor Stinner in :gh:`105922`.)" -msgstr "" -"Adiciona :c:func:`PyImport_AddModuleRef`: semelhante a :c:func:" -"`PyImport_AddModule`, mas retorna uma :term:`referência forte` em vez de " -"uma :term:`referência emprestada`. (Contribuição de Victor Stinner em :gh:" -"`105922`.)" +#: ../../whatsnew/3.13.rst:2059 +msgid ":c:func:`PyMonitoring_FirePyStartEvent`" +msgstr ":c:func:`PyMonitoring_FirePyStartEvent`" -#: ../../whatsnew/3.13.rst:1751 -msgid "" -"Add :c:func:`PyWeakref_GetRef` function: similar to :c:func:" -"`PyWeakref_GetObject` but returns a :term:`strong reference`, or ``NULL`` if " -"the referent is no longer live. (Contributed by Victor Stinner in :gh:" -"`105927`.)" -msgstr "" -"Adiciona a função :c:func:`PyWeakref_GetRef`: semelhante a :c:func:" -"`PyWeakref_GetObject`, mas retorna uma :term:`referência forte`, ou ``NULL`` " -"se o referente não mais existir. (Contribuição de Victor Stinner em :gh:" -"`105927`.)" +#: ../../whatsnew/3.13.rst:2060 +msgid ":c:func:`PyMonitoring_FirePyResumeEvent`" +msgstr ":c:func:`PyMonitoring_FirePyResumeEvent`" -#: ../../whatsnew/3.13.rst:1756 -msgid "" -"Add :c:func:`PyObject_GetOptionalAttr` and :c:func:" -"`PyObject_GetOptionalAttrString`, variants of :c:func:`PyObject_GetAttr` " -"and :c:func:`PyObject_GetAttrString` which don't raise :exc:`AttributeError` " -"if the attribute is not found. These variants are more convenient and faster " -"if the missing attribute should not be treated as a failure. (Contributed by " -"Serhiy Storchaka in :gh:`106521`.)" -msgstr "" -"Adiciona :c:func:`PyObject_GetOptionalAttr` e :c:func:" -"`PyObject_GetOptionalAttrString`, variantes de :c:func:`PyObject_GetAttr` e :" -"c:func:`PyObject_GetAttrString` que não levantam :exc:`AttributeError` se o " -"atributo não for encontrado. Essas variantes são mais convenientes e rápidas " -"se o atributo ausente não for tratado como uma falha. (Contribuição de " -"Serhiy Storchaka em :gh:`106521`.)" - -#: ../../whatsnew/3.13.rst:1764 -msgid "" -"Add :c:func:`PyMapping_GetOptionalItem` and :c:func:" -"`PyMapping_GetOptionalItemString`: variants of :c:func:`PyObject_GetItem` " -"and :c:func:`PyMapping_GetItemString` which don't raise :exc:`KeyError` if " -"the key is not found. These variants are more convenient and faster if the " -"missing key should not be treated as a failure. (Contributed by Serhiy " -"Storchaka in :gh:`106307`.)" -msgstr "" -"Adiciona :c:func:`PyMapping_GetOptionalItem` e :c:func:" -"`PyMapping_GetOptionalItemString`, variantes de :c:func:`PyObject_GetItem` " -"e :c:func:`PyMapping_GetItemString` que não levantam :exc:`KeyError` se a " -"chave não for encontrada. Essas variantes são mais convenientes e rápidas se " -"a chave ausente não for tratada como uma falha. (Contribuição de Serhiy " -"Storchaka em :gh:`106307`.)" - -#: ../../whatsnew/3.13.rst:1772 -msgid "Add fixed variants of functions which silently ignore errors:" -msgstr "Adiciona variantes fixas de funções que ignoram erros silenciosamente:" +#: ../../whatsnew/3.13.rst:2061 +msgid ":c:func:`PyMonitoring_FirePyReturnEvent`" +msgstr ":c:func:`PyMonitoring_FirePyReturnEvent`" -#: ../../whatsnew/3.13.rst:1774 -msgid "" -":c:func:`PyObject_HasAttrWithError` replaces :c:func:`PyObject_HasAttr`." -msgstr "" -":c:func:`PyObject_HasAttrWithError` substitui :c:func:`PyObject_HasAttr`." +#: ../../whatsnew/3.13.rst:2062 +msgid ":c:func:`PyMonitoring_FirePyYieldEvent`" +msgstr ":c:func:`PyMonitoring_FirePyYieldEvent`" -#: ../../whatsnew/3.13.rst:1775 -msgid "" -":c:func:`PyObject_HasAttrStringWithError` replaces :c:func:" -"`PyObject_HasAttrString`." -msgstr "" -":c:func:`PyObject_HasAttrStringWithError` substitui :c:func:" -"`PyObject_HasAttrString`." +#: ../../whatsnew/3.13.rst:2063 +msgid ":c:func:`PyMonitoring_FireCallEvent`" +msgstr ":c:func:`PyMonitoring_FireCallEvent`" -#: ../../whatsnew/3.13.rst:1776 -msgid "" -":c:func:`PyMapping_HasKeyWithError` replaces :c:func:`PyMapping_HasKey`." -msgstr "" -":c:func:`PyMapping_HasKeyWithError` substitui :c:func:`PyMapping_HasKey`." +#: ../../whatsnew/3.13.rst:2064 +msgid ":c:func:`PyMonitoring_FireLineEvent`" +msgstr ":c:func:`PyMonitoring_FireLineEvent`" -#: ../../whatsnew/3.13.rst:1777 -msgid "" -":c:func:`PyMapping_HasKeyStringWithError` replaces :c:func:" -"`PyMapping_HasKeyString`." -msgstr "" -":c:func:`PyMapping_HasKeyStringWithError` substitui :c:func:" -"`PyMapping_HasKeyString`." +#: ../../whatsnew/3.13.rst:2065 +msgid ":c:func:`PyMonitoring_FireJumpEvent`" +msgstr ":c:func:`PyMonitoring_FireJumpEvent`" -#: ../../whatsnew/3.13.rst:1779 -msgid "" -"New functions return not only ``1`` for true and ``0`` for false, but also " -"``-1`` for error." -msgstr "" -"Novas funções retornam não apenas ``1`` para verdadeiro e ``0`` para falso, " -"mas também ``-1`` para erro." +#: ../../whatsnew/3.13.rst:2066 +msgid ":c:func:`PyMonitoring_FireBranchEvent`" +msgstr ":c:func:`PyMonitoring_FireBranchEvent`" -#: ../../whatsnew/3.13.rst:1782 -msgid "(Contributed by Serhiy Storchaka in :gh:`108511`.)" -msgstr "(Contribuição de Serhiy Storchaka em :gh:`108511`.)" +#: ../../whatsnew/3.13.rst:2067 +msgid ":c:func:`PyMonitoring_FireCReturnEvent`" +msgstr ":c:func:`PyMonitoring_FireCReturnEvent`" -#: ../../whatsnew/3.13.rst:1784 -msgid "" -"If Python is built in :ref:`debug mode ` or :option:`with " -"assertions <--with-assertions>`, :c:func:`PyTuple_SET_ITEM` and :c:func:" -"`PyList_SET_ITEM` now check the index argument with an assertion. " -"(Contributed by Victor Stinner in :gh:`106168`.)" -msgstr "" -"Se Python for construído em :ref:`modo de depuração ` ou :" -"option:`com asserções <--with-assertions>`, :c:func:`PyTuple_SET_ITEM` e :c:" -"func:`PyList_SET_ITEM` agora verificam o argumento do índice com uma " -"asserção. (Contribuição de Victor Stinner em :gh:`106168`.)" +#: ../../whatsnew/3.13.rst:2068 +msgid ":c:func:`PyMonitoring_FirePyThrowEvent`" +msgstr ":c:func:`PyMonitoring_FirePyThrowEvent`" -#: ../../whatsnew/3.13.rst:1789 -msgid "" -"Add :c:func:`PyModule_Add` function: similar to :c:func:" -"`PyModule_AddObjectRef` and :c:func:`PyModule_AddObject` but always steals a " -"reference to the value. (Contributed by Serhiy Storchaka in :gh:`86493`.)" -msgstr "" -"Adiciona a função :c:func:`PyModule_Add`: semelhante a :c:func:" -"`PyModule_AddObjectRef` e :c:func:`PyModule_AddObject`, mas sempre rouba uma " -"referência ao valor. (Contribuição de Serhiy Storchaka em :gh:`86493`.)" +#: ../../whatsnew/3.13.rst:2069 +msgid ":c:func:`PyMonitoring_FireRaiseEvent`" +msgstr ":c:func:`PyMonitoring_FireRaiseEvent`" -#: ../../whatsnew/3.13.rst:1794 +#: ../../whatsnew/3.13.rst:2070 +msgid ":c:func:`PyMonitoring_FireCRaiseEvent`" +msgstr ":c:func:`PyMonitoring_FireCRaiseEvent`" + +#: ../../whatsnew/3.13.rst:2071 +msgid ":c:func:`PyMonitoring_FireReraiseEvent`" +msgstr ":c:func:`PyMonitoring_FireReraiseEvent`" + +#: ../../whatsnew/3.13.rst:2072 +msgid ":c:func:`PyMonitoring_FireExceptionHandledEvent`" +msgstr ":c:func:`PyMonitoring_FireExceptionHandledEvent`" + +#: ../../whatsnew/3.13.rst:2073 +msgid ":c:func:`PyMonitoring_FirePyUnwindEvent`" +msgstr ":c:func:`PyMonitoring_FirePyUnwindEvent`" + +#: ../../whatsnew/3.13.rst:2074 +msgid ":c:func:`PyMonitoring_FireStopIterationEvent`" +msgstr ":c:func:`PyMonitoring_FireStopIterationEvent`" + +#: ../../whatsnew/3.13.rst:2075 +msgid ":c:func:`PyMonitoring_EnterScope`" +msgstr ":c:func:`PyMonitoring_EnterScope`" + +#: ../../whatsnew/3.13.rst:2076 +msgid ":c:func:`PyMonitoring_ExitScope`" +msgstr ":c:func:`PyMonitoring_ExitScope`" + +#: ../../whatsnew/3.13.rst:2078 +msgid "(Contributed by Irit Katriel in :gh:`111997`)." +msgstr "(Contribuição de Irit Katriel em :gh:`111997`)." + +#: ../../whatsnew/3.13.rst:2080 msgid "" -"Add :c:func:`PyDict_GetItemRef` and :c:func:`PyDict_GetItemStringRef` " -"functions: similar to :c:func:`PyDict_GetItemWithError` but returning a :" -"term:`strong reference` instead of a :term:`borrowed reference`. Moreover, " -"these functions return -1 on error and so checking ``PyErr_Occurred()`` is " -"not needed. (Contributed by Victor Stinner in :gh:`106004`.)" +"Add :c:type:`PyMutex`, a lightweight mutex that occupies a single byte, and " +"the new :c:func:`PyMutex_Lock` and :c:func:`PyMutex_Unlock` functions. :c:" +"func:`!PyMutex_Lock` will release the :term:`GIL` (if currently held) if the " +"operation needs to block. (Contributed by Sam Gross in :gh:`108724`.)" msgstr "" -"Adiciona funções :c:func:`PyDict_GetItemRef` e :c:func:" -"`PyDict_GetItemStringRef`: semelhantes a :c:func:`PyDict_GetItemWithError`, " -"mas retornando uma :term:`referência forte` em vez de uma :term:`referência " -"emprestada` . Além disso, essas funções retornam -1 em caso de erro e, " -"portanto, a verificação de ``PyErr_Occurred()`` não é necessária. " -"(Contribuição de Victor Stinner em :gh:`106004`.)" +"Adiciona :c:type:`PyMutex`, um mutex leve que ocupa um único byte, e as " +"novas funções :c:func:`PyMutex_Lock` e :c:func:`PyMutex_Unlock`. :c:func:`!" +"PyMutex_Lock` irá liberar a :term:`GIL` (se atualmente mantida) se a " +"operação precisar de bloqueio. (Contribuição de Sam Gross em :gh:`108724`.)" -#: ../../whatsnew/3.13.rst:1801 +#: ../../whatsnew/3.13.rst:2086 msgid "" -"Added :c:func:`PyDict_SetDefaultRef`, which is similar to :c:func:" -"`PyDict_SetDefault` but returns a :term:`strong reference` instead of a :" -"term:`borrowed reference`. This function returns ``-1`` on error, ``0`` on " -"insertion, and ``1`` if the key was already present in the dictionary. " -"(Contributed by Sam Gross in :gh:`112066`.)" +"Add the :ref:`PyTime C API ` to provide access to system clocks:" msgstr "" -"Adicionada :c:func:`PyDict_SetDefaultRef`, que é semelhante a :c:func:" -"`PyDict_SetDefault`, mas retorna uma :term:`referência forte` em vez de uma :" -"term:`referência emprestada`. Esta função retorna ``-1`` em caso de erro, " -"``0`` na inserção e ``1`` se a chave já estivesse presente no dicionário. " -"(Contribuição de Sam Gross em :gh:`112066`.)" +"Adiciona a :doc:`API C PyTime `, fornecendo acesso aos relógios " +"do sistema." -#: ../../whatsnew/3.13.rst:1807 -msgid "" -"Add :c:func:`PyDict_ContainsString` function: same as :c:func:" -"`PyDict_Contains`, but *key* is specified as a :c:expr:`const char*` UTF-8 " -"encoded bytes string, rather than a :c:expr:`PyObject*`. (Contributed by " -"Victor Stinner in :gh:`108314`.)" -msgstr "" -"Adiciona a função :c:func:`PyDict_ContainsString` como :c:func:" -"`PyDict_Contains`, mas *key* é especificada como uma string de bytes :c:expr:" -"`const char*` codificada em UTF-8, em vez de um :c:expr:`PyObject*`. " -"(Contribuição de Victor Stinner em :gh:`108314`.)" +#: ../../whatsnew/3.13.rst:2088 +msgid ":c:type:`PyTime_t`." +msgstr ":c:type:`PyTime_t`." + +#: ../../whatsnew/3.13.rst:2089 +msgid ":c:var:`PyTime_MIN` and :c:var:`PyTime_MAX`." +msgstr ":c:var:`PyTime_MIN` e :c:var:`PyTime_MAX`." + +#: ../../whatsnew/3.13.rst:2090 +msgid ":c:func:`PyTime_AsSecondsDouble`." +msgstr ":c:func:`PyTime_AsSecondsDouble`." + +#: ../../whatsnew/3.13.rst:2091 +msgid ":c:func:`PyTime_Monotonic`." +msgstr ":c:func:`PyTime_Monotonic`." + +#: ../../whatsnew/3.13.rst:2092 +msgid ":c:func:`PyTime_MonotonicRaw`." +msgstr ":c:func:`PyTime_MonotonicRaw`." + +#: ../../whatsnew/3.13.rst:2093 +msgid ":c:func:`PyTime_PerfCounter`." +msgstr ":c:func:`PyTime_PerfCounter`." -#: ../../whatsnew/3.13.rst:1812 +#: ../../whatsnew/3.13.rst:2094 +msgid ":c:func:`PyTime_PerfCounterRaw`." +msgstr ":c:func:`PyTime_PerfCounterRaw`." + +#: ../../whatsnew/3.13.rst:2095 +msgid ":c:func:`PyTime_Time`." +msgstr ":c:func:`PyTime_Time`." + +#: ../../whatsnew/3.13.rst:2096 +msgid ":c:func:`PyTime_TimeRaw`." +msgstr ":c:func:`PyTime_TimeRaw`." + +#: ../../whatsnew/3.13.rst:2098 +msgid "(Contributed by Victor Stinner and Petr Viktorin in :gh:`110850`.)" +msgstr "(Contribuição de Victor Stinner e Petr Viktorin em :gh:`110850`.)" + +#: ../../whatsnew/3.13.rst:2100 msgid "" -"Added :c:func:`PyList_GetItemRef` function: similar to :c:func:" -"`PyList_GetItem` but returns a :term:`strong reference` instead of a :term:" -"`borrowed reference`." +"Add the :c:func:`PyDict_ContainsString` function with the same behavior as :" +"c:func:`PyDict_Contains`, but *key* is specified as a :c:expr:`const char*` " +"UTF-8 encoded bytes string, rather than a :c:expr:`PyObject*`. (Contributed " +"by Victor Stinner in :gh:`108314`.)" msgstr "" -"Adicionada a função :c:func:`PyList_GetItemRef`: semelhante a :c:func:" -"`PyList_GetItem`, mas retorna uma :term:`referência forte` em vez de uma :" -"term:`referência emprestada`." +"Adiciona a função :c:func:`PyDict_ContainsString` com o mesmo comportamento " +"de :c:func:`PyDict_Contains`, mas *key* é especificada como uma string de " +"bytes :c:expr:`const char*` codificada em UTF-8, em vez de um :c:expr:" +"`PyObject*`. (Contribuição de Victor Stinner em :gh:`108314`.)" -#: ../../whatsnew/3.13.rst:1816 +#: ../../whatsnew/3.13.rst:2106 msgid "" -"Add :c:func:`Py_IsFinalizing` function: check if the main Python interpreter " -"is :term:`shutting down `. (Contributed by Victor " -"Stinner in :gh:`108014`.)" -msgstr "" -"Adiciona a função :c:func:`Py_IsFinalizing`: verifica se o interpretador " -"Python principal está :term:`sendo desligado `. " -"(Contribuição de Victor Stinner em :gh:`108014`.)" +"Add the :c:func:`PyDict_GetItemRef` and :c:func:`PyDict_GetItemStringRef` " +"functions, which behave similarly to :c:func:`PyDict_GetItemWithError`, but " +"return a :term:`strong reference` instead of a :term:`borrowed reference`. " +"Moreover, these functions return ``-1`` on error, removing the need to " +"check :c:func:`!PyErr_Occurred`. (Contributed by Victor Stinner in :gh:" +"`106004`.)" +msgstr "" +"Adiciona as funções :c:func:`PyDict_GetItemRef` e :c:func:" +"`PyDict_GetItemStringRef` functions, que são semelhantes a :c:func:" +"`PyDict_GetItemWithError`, mas retornam uma :term:`referência forte` em vez " +"de uma :term:`referência emprestada`. Além disso, essas funções retornam " +"``-1`` em caso de erro, dispensando a necessidade de checar :c:func:`!" +"PyErr_Occurred`. (Contribuição de Victor Stinner em :gh:`106004`.)" + +#: ../../whatsnew/3.13.rst:2114 +msgid "" +"Add the :c:func:`PyDict_SetDefaultRef` function, which behaves similarly to :" +"c:func:`PyDict_SetDefault`, but returns a :term:`strong reference` instead " +"of a :term:`borrowed reference`. This function returns ``-1`` on error, " +"``0`` on insertion, and ``1`` if the key was already present in the " +"dictionary. (Contributed by Sam Gross in :gh:`112066`.)" +msgstr "" +"Adiciona a função :c:func:`PyDict_SetDefaultRef`, que é semelhante a :c:func:" +"`PyDict_SetDefault`, mas retorna uma :term:`referência forte` em vez de uma :" +"term:`referência emprestada`. Esta função retorna ``-1`` em caso de erro, " +"``0`` na inserção e ``1`` se a chave já estivesse presente no dicionário. " +"(Contribuição de Sam Gross em :gh:`112066`.)" -#: ../../whatsnew/3.13.rst:1820 +#: ../../whatsnew/3.13.rst:2122 msgid "" -"Add :c:func:`PyLong_AsInt` function: similar to :c:func:`PyLong_AsLong`, but " -"store the result in a C :c:expr:`int` instead of a C :c:expr:`long`. " -"Previously, it was known as the private function :c:func:`!_PyLong_AsInt` " -"(with an underscore prefix). (Contributed by Victor Stinner in :gh:`108014`.)" +"Add the :c:func:`PyDict_Pop` and :c:func:`PyDict_PopString` functions to " +"remove a key from a dictionary and optionally return the removed value. This " +"is similar to :meth:`dict.pop`, though there is no default value, and :exc:" +"`KeyError` is not raised for missing keys. (Contributed by Stefan Behnel and " +"Victor Stinner in :gh:`111262`.)" +msgstr "" +"Adiciona as funções :c:func:`PyDict_Pop` e :c:func:`PyDict_PopString` para " +"remover uma chave de um dicionário e, opcionalmente, retornam o valor " +"removido. Isto é semelhante a :meth:`dict.pop`, mas sem o valor padrão e sem " +"levantar :exc:`KeyError` se a chave estiver ausente. (Contribuição de Stefan " +"Behnel e Victor Stinner em :gh:`111262`.)" + +#: ../../whatsnew/3.13.rst:2129 +msgid "" +"Add the :c:func:`PyMapping_GetOptionalItem` and :c:func:" +"`PyMapping_GetOptionalItemString` functions as alternatives to :c:func:" +"`PyObject_GetItem` and :c:func:`PyMapping_GetItemString` respectively. The " +"new functions do not raise :exc:`KeyError` if the requested key is missing " +"from the mapping. These variants are more convenient and faster if a missing " +"key should not be treated as a failure. (Contributed by Serhiy Storchaka in :" +"gh:`106307`.)" +msgstr "" +"Adiciona as funções :c:func:`PyMapping_GetOptionalItem` e :c:func:" +"`PyMapping_GetOptionalItemString` como alternativas a :c:func:" +"`PyObject_GetAttr` e :c:func:`PyObject_GetAttrString`, respectivamente. As " +"novas funções não levantam :exc:`KeyError` se o atributo não for encontrado " +"no mapeamento. Essas variantes são mais convenientes e rápidas se o atributo " +"ausente não for tratado como uma falha. (Contribuição de Serhiy Storchaka " +"em :gh:`106307`.)" + +#: ../../whatsnew/3.13.rst:2139 +msgid "" +"Add the :c:func:`PyObject_GetOptionalAttr` and :c:func:" +"`PyObject_GetOptionalAttrString` functions as alternatives to :c:func:" +"`PyObject_GetAttr` and :c:func:`PyObject_GetAttrString` respectively. The " +"new functions do not raise :exc:`AttributeError` if the requested attribute " +"is not found on the object. These variants are more convenient and faster if " +"the missing attribute should not be treated as a failure. (Contributed by " +"Serhiy Storchaka in :gh:`106521`.)" msgstr "" -"Adiciona a função :c:func:`PyLong_AsInt`: semelhante a :c:func:" -"`PyLong_AsLong`, mas armazena o resultado em um :c:expr:`int` C em vez de " -"um :c:expr:`long` C. Anteriormente, era conhecida como função privada :c:" -"func:`!_PyLong_AsInt` (com um prefixo de sublinhado). (Contribuição de " -"Victor Stinner em :gh:`108014`.)" +"Adiciona as funções :c:func:`PyObject_GetOptionalAttr` e :c:func:" +"`PyObject_GetOptionalAttrString`, variantes de :c:func:`PyObject_GetAttr` e :" +"c:func:`PyObject_GetAttrString`, respectivamente. Essas novas funções não " +"levantam :exc:`AttributeError` se o atributo não for encontrado. Essas " +"variantes são mais convenientes e rápidas se o atributo ausente não for " +"tratado como uma falha. (Contribuição de Serhiy Storchaka em :gh:`106521`.)" -#: ../../whatsnew/3.13.rst:1826 +#: ../../whatsnew/3.13.rst:2149 msgid "" -"Python built with :file:`configure` :option:`--with-trace-refs` (tracing " -"references) now supports the :ref:`Limited API `. " -"(Contributed by Victor Stinner in :gh:`108634`.)" +"Add the :c:func:`PyErr_FormatUnraisable` function as an extension to :c:func:" +"`PyErr_WriteUnraisable` that allows customizing the warning message. " +"(Contributed by Serhiy Storchaka in :gh:`108082`.)" msgstr "" -"Python construído com :file:`configure` :option:`--with-trace-refs` " -"(referências de rastreamento) agora oferece suporte à :ref:`API Limitada " -"`. (Contribuição de Victor Stinner em :gh:`108634`.)" +"Adiciona a função :c:func:`PyErr_FormatUnraisable` como uma extensão para :c:" +"func:`PyErr_WriteUnraisable`, que permite personalizar a mensagem de aviso. " +"(Contribuição de Serhiy Storchaka em :gh:`108082`.)" -#: ../../whatsnew/3.13.rst:1830 +#: ../../whatsnew/3.13.rst:2154 msgid "" -"Add :c:func:`PyObject_VisitManagedDict` and :c:func:" -"`PyObject_ClearManagedDict` functions which must be called by the traverse " -"and clear functions of a type using :c:macro:`Py_TPFLAGS_MANAGED_DICT` " -"flag. The `pythoncapi-compat project `__ can be used to get these functions on Python 3.11 and 3.12. " -"(Contributed by Victor Stinner in :gh:`107073`.)" +"Add new functions that return a :term:`strong reference` instead of a :term:" +"`borrowed reference` for frame locals, globals, and builtins, as part of :" +"ref:`PEP 667 `:" msgstr "" -"Adiciona funções :c:func:`PyObject_VisitManagedDict` e :c:func:" -"`PyObject_ClearManagedDict` que devem ser chamadas pelas funções traverse e " -"clear de um tipo usando o sinalizador :c:macro:`Py_TPFLAGS_MANAGED_DICT`. O " -"projeto `pythoncapi-compat `__ " -"pode ser usado para obter essas funções no Python 3.11 e 3.12. (Contribuição " -"de Victor Stinner em :gh:`107073`.)" +"Adiciona novas funções que retornam uma :term:`referência forte` em vez de " +"uma :term:`referência emprestada` para quadros locais, globais, e embutidos, " +"como parte de :ref:`PEP 667 `:" -#: ../../whatsnew/3.13.rst:1838 -msgid "" -"Add :c:func:`PyUnicode_EqualToUTF8AndSize` and :c:func:" -"`PyUnicode_EqualToUTF8` functions: compare Unicode object with a :c:expr:" -"`const char*` UTF-8 encoded string and return true (``1``) if they are " -"equal, or false (``0``) otherwise. These functions do not raise exceptions. " -"(Contributed by Serhiy Storchaka in :gh:`110289`.)" +#: ../../whatsnew/3.13.rst:2158 +msgid ":c:func:`PyEval_GetFrameBuiltins` replaces :c:func:`PyEval_GetBuiltins`" msgstr "" -"Adiciona as funções :c:func:`PyUnicode_EqualToUTF8AndSize` e :c:func:" -"`PyUnicode_EqualToUTF8`: comparam o objeto Unicode com uma string :c:expr:" -"`const char*` codificada em UTF-8 e retornam true (``1``) se forem iguais, " -"ou falso (``0``) caso contrário. Essas funções não levantam exceções. " -"(Contribuição de Serhiy Storchaka em :gh:`110289`.)" - -#: ../../whatsnew/3.13.rst:1844 -msgid "" -"Add :c:func:`PyThreadState_GetUnchecked()` function: similar to :c:func:" -"`PyThreadState_Get()`, but don't kill the process with a fatal error if it " -"is NULL. The caller is responsible to check if the result is NULL. " -"Previously, the function was private and known as " -"``_PyThreadState_UncheckedGet()``. (Contributed by Victor Stinner in :gh:" -"`108867`.)" -msgstr "" -"Adiciona a função :c:func:`PyThreadState_GetUnchecked()`: semelhante a :c:" -"func:`PyThreadState_Get()`, mas não encerra forçadamente o processo com um " -"erro fatal se for NULL. O chamador é responsável por verificar se o " -"resultado é NULL. Anteriormente, a função era privada e conhecida como " -"``_PyThreadState_UncheckedGet()``. (Contribuição de Victor Stinner em :gh:" -"`108867`.)" +":c:func:`PyEval_GetFrameBuiltins` substitui :c:func:`PyEval_GetBuiltins`" -#: ../../whatsnew/3.13.rst:1851 +#: ../../whatsnew/3.13.rst:2159 +msgid ":c:func:`PyEval_GetFrameGlobals` replaces :c:func:`PyEval_GetGlobals`" +msgstr ":c:func:`PyEval_GetFrameGlobals` substitui :c:func:`PyEval_GetGlobals`" + +#: ../../whatsnew/3.13.rst:2160 +msgid ":c:func:`PyEval_GetFrameLocals` replaces :c:func:`PyEval_GetLocals`" +msgstr ":c:func:`PyEval_GetFrameLocals` substitui :c:func:`PyEval_GetLocals`" + +#: ../../whatsnew/3.13.rst:2162 +msgid "(Contributed by Mark Shannon and Tian Gao in :gh:`74929`.)" +msgstr "(Contribuição de Mark Shannon e Tian Gao em :gh:`74929`.)" + +#: ../../whatsnew/3.13.rst:2164 msgid "" -"Add :c:func:`PySys_AuditTuple` function: similar to :c:func:`PySys_Audit`, " -"but pass event arguments as a Python :class:`tuple` object. (Contributed by " -"Victor Stinner in :gh:`85283`.)" +"Add the :c:func:`Py_GetConstant` and :c:func:`Py_GetConstantBorrowed` " +"functions to get :term:`strong ` or :term:`borrowed " +"` references to constants. For example, " +"``Py_GetConstant(Py_CONSTANT_ZERO)`` returns a strong reference to the " +"constant zero. (Contributed by Victor Stinner in :gh:`115754`.)" msgstr "" -"Adiciona a função :c:func:`PySys_AuditTuple`: semelhante a :c:func:" -"`PySys_Audit`, mas passa argumentos de evento como um objeto :class:`tuple` " -"do Python. (Contribuição de Victor Stinner em :gh:`85283`.)" +"Adiciona as funções :c:func:`Py_GetConstant` e :c:func:" +"`Py_GetConstantBorrowed` para referências :term:`fortes ` " +"ou :term:`emprestadas ` para constantes. Por exemplo, " +"``Py_GetConstant(Py_CONSTANT_ZERO)`` retorna uma referência forte para a " +"constante zero. (Contribuição de Victor Stinner em :gh:`115754`.)" -#: ../../whatsnew/3.13.rst:1855 +#: ../../whatsnew/3.13.rst:2171 msgid "" -":c:func:`PyArg_ParseTupleAndKeywords` now supports non-ASCII keyword " -"parameter names. (Contributed by Serhiy Storchaka in :gh:`110815`.)" +"Add the :c:func:`PyImport_AddModuleRef` function as a replacement for :c:" +"func:`PyImport_AddModule` that returns a :term:`strong reference` instead of " +"a :term:`borrowed reference`. (Contributed by Victor Stinner in :gh:" +"`105922`.)" msgstr "" -":c:func:`PyArg_ParseTupleAndKeywords` agora oferece suporte a nomes de " -"parâmetros nomeados não-ASCII. (Contribuição de Serhiy Storchaka em :gh:" -"`110815`.)" +"Adiciona a função :c:func:`PyImport_AddModuleRef` como uma substituta para :" +"c:func:`PyImport_AddModule` mas retorna uma :term:`referência forte` em vez " +"de uma :term:`referência emprestada`. (Contribuição de Victor Stinner em :gh:" +"`105922`.)" -#: ../../whatsnew/3.13.rst:1859 +#: ../../whatsnew/3.13.rst:2176 msgid "" -"Add :c:func:`PyMem_RawMalloc`, :c:func:`PyMem_RawCalloc`, :c:func:" -"`PyMem_RawRealloc` and :c:func:`PyMem_RawFree` to the limited C API (version " -"3.13). (Contributed by Victor Stinner in :gh:`85283`.)" +"Add the :c:func:`Py_IsFinalizing` function to check whether the main Python " +"interpreter is :term:`shutting down `. (Contributed by " +"Victor Stinner in :gh:`108014`.)" msgstr "" -"Adiciona :c:func:`PyMem_RawMalloc`, :c:func:`PyMem_RawCalloc`, :c:func:" -"`PyMem_RawRealloc` e :c:func:`PyMem_RawFree` à API C limitada (versão 3.13). " -"(Contribuição de Victor Stinner em :gh:`85283`.)" +"Adiciona a função :c:func:`Py_IsFinalizing` para verificar se o " +"interpretador Python principal está :term:`sendo desligado `. (Contribuição de Victor Stinner em :gh:`108014`.)" -#: ../../whatsnew/3.13.rst:1864 +#: ../../whatsnew/3.13.rst:2181 msgid "" -"Add :c:func:`PySys_Audit` and :c:func:`PySys_AuditTuple` functions to the " -"limited C API. (Contributed by Victor Stinner in :gh:`85283`.)" +"Add the :c:func:`PyList_GetItemRef` function as a replacement for :c:func:" +"`PyList_GetItem` that returns a :term:`strong reference` instead of a :term:" +"`borrowed reference`. (Contributed by Sam Gross in :gh:`114329`.)" msgstr "" -"Adiciona as funções :c:func:`PySys_Audit` e :c:func:`PySys_AuditTuple` à API " -"C limitada. (Contribuição de Victor Stinner em :gh:`85283`.)" +"Adiciona a função :c:func:`PyList_GetItemRef` como uma substituta para :c:" +"func:`PyList_GetItem` mas que retorna uma :term:`referência forte` em vez de " +"uma :term:`referência emprestada`. (Contribuição de Sam Gross em :gh:" +"`114329`.)" -#: ../../whatsnew/3.13.rst:1868 +#: ../../whatsnew/3.13.rst:2186 msgid "" -"Add :c:func:`PyErr_FormatUnraisable` function: similar to :c:func:" -"`PyErr_WriteUnraisable`, but allow customizing the warning message. " -"(Contributed by Serhiy Storchaka in :gh:`108082`.)" +"Add the :c:func:`PyList_Extend` and :c:func:`PyList_Clear` functions, " +"mirroring the Python :meth:`!list.extend` and :meth:`!list.clear` methods. " +"(Contributed by Victor Stinner in :gh:`111138`.)" msgstr "" -"Adiciona a função :c:func:`PyErr_FormatUnraisable`: semelhante a :c:func:" -"`PyErr_WriteUnraisable`, mas permite personalizar a mensagem de aviso. " -"(Contribuição de Serhiy Storchaka em :gh:`108082`.)" +"Adiciona as funções :c:func:`PyList_Extend` e :c:func:`PyList_Clear`, " +"espelhando os métodos :meth:`!list.extend` e :meth:`!list.clear` do Python. " +"(Contribuição de Victor Stinner em :gh:`111138`.)" -#: ../../whatsnew/3.13.rst:1872 +#: ../../whatsnew/3.13.rst:2190 msgid "" -"Add :c:func:`PyList_Extend` and :c:func:`PyList_Clear` functions: similar to " -"Python ``list.extend()`` and ``list.clear()`` methods. (Contributed by " -"Victor Stinner in :gh:`111138`.)" +"Add the :c:func:`PyLong_AsInt` function. It behaves similarly to :c:func:" +"`PyLong_AsLong`, but stores the result in a C :c:expr:`int` instead of a C :" +"c:expr:`long`. (Contributed by Victor Stinner in :gh:`108014`.)" msgstr "" -"Adiciona as funções :c:func:`PyList_Extend` e :c:func:`PyList_Clear`: " -"semelhantes aos métodos ``list.extend()`` e ``list.clear()`` do Python. " -"(Contribuição de Victor Stinner em :gh:`111138`.)" +"Adiciona a função :c:func:`PyLong_AsInt`, semelhante à :c:func:" +"`PyLong_AsLong`, mas armazena o resultado em um :c:expr:`int` em vez de um :" +"c:expr:`long` em C. (Contribuição de Victor Stinner em :gh:`108014`.)" -#: ../../whatsnew/3.13.rst:1876 +#: ../../whatsnew/3.13.rst:2195 msgid "" -"Add :c:func:`PyDict_Pop` and :c:func:`PyDict_PopString` functions: remove a " -"key from a dictionary and optionally return the removed value. This is " -"similar to :meth:`dict.pop`, but without the default value and not raising :" -"exc:`KeyError` if the key is missing. (Contributed by Stefan Behnel and " -"Victor Stinner in :gh:`111262`.)" +"Add the :c:func:`PyLong_AsNativeBytes`, :c:func:`PyLong_FromNativeBytes`, " +"and :c:func:`PyLong_FromUnsignedNativeBytes` functions to simplify " +"converting between native integer types and Python :class:`int` objects. " +"(Contributed by Steve Dower in :gh:`111140`.)" msgstr "" -"Adiciona funções :c:func:`PyDict_Pop` e :c:func:`PyDict_PopString`: removem " -"uma chave de um dicionário e, opcionalmente, retornam o valor removido. Isto " -"é semelhante a :meth:`dict.pop`, mas sem o valor padrão e sem levantar :exc:" -"`KeyError` se a chave estiver ausente. (Contribuição de Stefan Behnel e " -"Victor Stinner em :gh:`111262`.)" +"Adiciona as funções :c:func:`PyLong_AsNativeBytes`, :c:func:" +"`PyLong_FromNativeBytes` e :c:func:`PyLong_FromUnsignedNativeBytes` para " +"simplificar a conversão entre tipos inteiros nativos e objetos :class:`int` " +"do Python. (Contribuição de Steve Dower em :gh:`111140`.)" -#: ../../whatsnew/3.13.rst:1882 +#: ../../whatsnew/3.13.rst:2201 msgid "" -"Add :c:func:`Py_HashPointer` function to hash a pointer. (Contributed by " -"Victor Stinner in :gh:`111545`.)" +"Add :c:func:`PyModule_Add` function, which is similar to :c:func:" +"`PyModule_AddObjectRef` and :c:func:`PyModule_AddObject`, but always steals " +"a reference to the value. (Contributed by Serhiy Storchaka in :gh:`86493`.)" msgstr "" -"Adiciona a função :c:func:`Py_HashPointer` para fazer hash de um ponteiro. " -"(Contribuição de Victor Stinner em :gh:`111545`.)" +"Adiciona a função :c:func:`PyModule_Add`, que é semelhante a :c:func:" +"`PyModule_AddObjectRef` e :c:func:`PyModule_AddObject`, mas sempre rouba uma " +"referência ao valor. (Contribuição de Serhiy Storchaka em :gh:`86493`.)" -#: ../../whatsnew/3.13.rst:1885 +#: ../../whatsnew/3.13.rst:2206 msgid "" -"Add :c:func:`PyObject_GenericHash` function that implements the default " +"Add the :c:func:`PyObject_GenericHash` function that implements the default " "hashing function of a Python object. (Contributed by Serhiy Storchaka in :gh:" "`113024`.)" msgstr "" @@ -4772,750 +5408,533 @@ msgstr "" "hashing padrão de um objeto Python. (Contribuição de Serhiy Storchaka em :gh:" "`113024`.)" -#: ../../whatsnew/3.13.rst:1889 -msgid "Add PyTime C API:" -msgstr "Adiciona a API C PyTime:" - -#: ../../whatsnew/3.13.rst:1891 -msgid ":c:type:`PyTime_t` type." -msgstr "Tipo :c:type:`PyTime_t`." - -#: ../../whatsnew/3.13.rst:1892 -msgid ":c:var:`PyTime_MIN` and :c:var:`PyTime_MAX` constants." -msgstr "Constantes :c:var:`PyTime_MIN` e :c:var:`PyTime_MAX`." - -#: ../../whatsnew/3.13.rst:1893 -msgid "Add functions:" -msgstr "Adiciona as funções:" - -#: ../../whatsnew/3.13.rst:1895 -msgid ":c:func:`PyTime_AsSecondsDouble`." -msgstr ":c:func:`PyTime_AsSecondsDouble`." - -#: ../../whatsnew/3.13.rst:1896 -msgid ":c:func:`PyTime_Monotonic`." -msgstr ":c:func:`PyTime_Monotonic`." - -#: ../../whatsnew/3.13.rst:1897 -msgid ":c:func:`PyTime_MonotonicRaw`." -msgstr ":c:func:`PyTime_MonotonicRaw`." - -#: ../../whatsnew/3.13.rst:1898 -msgid ":c:func:`PyTime_PerfCounter`." -msgstr ":c:func:`PyTime_PerfCounter`." - -#: ../../whatsnew/3.13.rst:1899 -msgid ":c:func:`PyTime_PerfCounterRaw`." -msgstr ":c:func:`PyTime_PerfCounterRaw`." - -#: ../../whatsnew/3.13.rst:1900 -msgid ":c:func:`PyTime_Time`." -msgstr ":c:func:`PyTime_Time`." - -#: ../../whatsnew/3.13.rst:1901 -msgid ":c:func:`PyTime_TimeRaw`." -msgstr ":c:func:`PyTime_TimeRaw`." - -#: ../../whatsnew/3.13.rst:1903 -msgid "(Contributed by Victor Stinner and Petr Viktorin in :gh:`110850`.)" -msgstr "(Contribuição de Victor Stinner e Petr Viktorin em :gh:`110850`.)" - -#: ../../whatsnew/3.13.rst:1905 +#: ../../whatsnew/3.13.rst:2210 msgid "" -"Add :c:func:`PyLong_AsNativeBytes`, :c:func:`PyLong_FromNativeBytes` and :c:" -"func:`PyLong_FromUnsignedNativeBytes` functions to simplify converting " -"between native integer types and Python :class:`int` objects. (Contributed " -"by Steve Dower in :gh:`111140`.)" +"Add the :c:func:`Py_HashPointer` function to hash a raw pointer. " +"(Contributed by Victor Stinner in :gh:`111545`.)" msgstr "" -"Adiciona as funções :c:func:`PyLong_AsNativeBytes`, :c:func:" -"`PyLong_FromNativeBytes` e :c:func:`PyLong_FromUnsignedNativeBytes` para " -"simplificar a conversão entre tipos inteiros nativos e objetos :class:`int` " -"do Python. (Contribuição de Steve Dower em :gh:`111140`.)" +"Adiciona a função :c:func:`Py_HashPointer` para fazer hash de um ponteiro. " +"(Contribuição de Victor Stinner em :gh:`111545`.)" -#: ../../whatsnew/3.13.rst:1910 +#: ../../whatsnew/3.13.rst:2213 msgid "" -"Add :c:func:`PyType_GetFullyQualifiedName` function to get the type's fully " -"qualified name. Equivalent to ``f\"{type.__module__}.{type." -"__qualname__}\"``, or ``type.__qualname__`` if ``type.__module__`` is not a " -"string or is equal to ``\"builtins\"``. (Contributed by Victor Stinner in :" -"gh:`111696`.)" +"Add the :c:func:`PyObject_VisitManagedDict` and :c:func:" +"`PyObject_ClearManagedDict` functions. which must be called by the traverse " +"and clear functions of a type using the :c:macro:`Py_TPFLAGS_MANAGED_DICT` " +"flag. The `pythoncapi-compat project`_ can be used to use these functions " +"with Python 3.11 and 3.12. (Contributed by Victor Stinner in :gh:`107073`.)" msgstr "" -"Adiciona a função :c:func:`PyType_GetFullyQualifiedName` para obter o nome " -"totalmente qualificado do tipo. Equivalente a ``f\"{type.__module__}.{type." -"__qualname__}\"``, ou ``type.__qualname__`` se ``type.__module__`` não for " -"uma string ou for igual a ``\"builtins\"``. (Contribuição de Victor Stinner " -"em :gh:`111696`.)" +"Adiciona as funções :c:func:`PyObject_VisitManagedDict` e :c:func:" +"`PyObject_ClearManagedDict` que devem ser chamadas pelas funções traverse e " +"clear de um tipo usando o sinalizador :c:macro:`Py_TPFLAGS_MANAGED_DICT`. O " +"`projeto pythoncapi-compat`_ pode ser usado para obter essas funções no " +"Python 3.11 e 3.12. (Contribuição de Victor Stinner em :gh:`107073`.)" -#: ../../whatsnew/3.13.rst:1916 +#: ../../whatsnew/3.13.rst:2221 msgid "" -"Add :c:func:`PyType_GetModuleName` function to get the type's module name. " -"Equivalent to getting the ``type.__module__`` attribute. (Contributed by " -"Eric Snow and Victor Stinner in :gh:`111696`.)" +"Add the :c:func:`PyRefTracer_SetTracer` and :c:func:`PyRefTracer_GetTracer` " +"functions, which enable tracking object creation and destruction in the same " +"way that the :mod:`tracemalloc` module does. (Contributed by Pablo Galindo " +"in :gh:`93502`.)" msgstr "" -"Adiciona a função :c:func:`PyType_GetModuleName` para obter o nome do módulo " -"do tipo. Equivalente a obter o atributo ``type.__module__``. (Contribuição " -"de Eric Snow e Victor Stinner em :gh:`111696`.)" +"Adiciona as funções :c:func:`PyRefTracer_SetTracer` e :c:func:" +"`PyRefTracer_GetTracer`, que permitem rastrear a criação e destruição de " +"objetos da mesma forma que o módulo :mod:`tracemalloc`. (Contribuição de " +"Pablo Galindo em :gh:`93502`.)" -#: ../../whatsnew/3.13.rst:1920 +#: ../../whatsnew/3.13.rst:2227 msgid "" -"Add support for ``%T``, ``%#T``, ``%N`` and ``%#N`` formats to :c:func:" -"`PyUnicode_FromFormat`: format the fully qualified name of an object type " -"and of a type: call :c:func:`PyType_GetModuleName`. See :pep:`737` for more " -"information. (Contributed by Victor Stinner in :gh:`111696`.)" +"Add the :c:func:`PySys_AuditTuple` function as an alternative to :c:func:" +"`PySys_Audit` that takes event arguments as a Python :class:`tuple` object. " +"(Contributed by Victor Stinner in :gh:`85283`.)" msgstr "" -"Adiciona suporte para os formatos ``%T``, ``%#T``, ``%N`` e ``%#N`` para :c:" -"func:`PyUnicode_FromFormat`: formata o nome totalmente qualificado de um " -"tipo de objeto e de um tipo: chame :c:func:`PyType_GetModuleName`. Veja :pep:" -"`737` para mais informações. (Contribuição de Victor Stinner em :gh:" -"`111696`.)" +"Adiciona a função :c:func:`PySys_AuditTuple` como uma alternativa à :c:func:" +"`PySys_Audit`, que recebe argumentos de evento como um objeto :class:`tuple` " +"do Python. (Contribuição de Victor Stinner em :gh:`85283`.)" -#: ../../whatsnew/3.13.rst:1926 +#: ../../whatsnew/3.13.rst:2232 msgid "" -"Add :c:func:`Py_GetConstant` and :c:func:`Py_GetConstantBorrowed` functions " -"to get constants. For example, ``Py_GetConstant(Py_CONSTANT_ZERO)`` returns " -"a :term:`strong reference` to the constant zero. (Contributed by Victor " -"Stinner in :gh:`115754`.)" +"Add the :c:func:`PyThreadState_GetUnchecked()` function as an alternative " +"to :c:func:`PyThreadState_Get()` that doesn't kill the process with a fatal " +"error if it is ``NULL``. The caller is responsible for checking if the " +"result is ``NULL``. (Contributed by Victor Stinner in :gh:`108867`.)" msgstr "" -"Adiciona as funções :c:func:`Py_GetConstant` e :c:func:" -"`Py_GetConstantBorrowed` para obter constantes. Por exemplo, " -"``Py_GetConstant(Py_CONSTANT_ZERO)`` retorna uma :term:`referência forte` " -"para a constante zero. (Contribuição de Victor Stinner em :gh:`115754`.)" +"Adiciona a função :c:func:`PyThreadState_GetUnchecked()` como uma " +"alternativa a :c:func:`PyThreadState_Get()` que não mata o processo com um " +"erro fatal se for ``NULL``. O chamador é responsável por verificar se o " +"resultado é ``NULL``. (Contribuição de Victor Stinner em :gh:`108867`.)" -#: ../../whatsnew/3.13.rst:1931 +#: ../../whatsnew/3.13.rst:2238 msgid "" -"Add :c:func:`PyType_GetModuleByDef` to the limited C API (Contributed by " -"Victor Stinner in :gh:`116936`.)" +"Add the :c:func:`PyType_GetFullyQualifiedName` function to get the type's " +"fully qualified name. The module name is prepended if :attr:`type." +"__module__` is a string and is not equal to either ``'builtins'`` or " +"``'__main__'``. (Contributed by Victor Stinner in :gh:`111696`.)" msgstr "" -"Adiciona :c:func:`PyType_GetModuleByDef` à API C limitada (contribuição de " -"Victor Stinner em :gh:`116936`.)" +"Adiciona a função :c:func:`PyType_GetFullyQualifiedName` para obter o nome " +"totalmente qualificado do tipo. O nome do módulo é prefixado se :attr:`type." +"__module__` for uma string e não for igual a ``'builtins'`` ou " +"``'__main__'``. (Contribuição de Victor Stinner em :gh:`111696`.)" -#: ../../whatsnew/3.13.rst:1934 +#: ../../whatsnew/3.13.rst:2244 msgid "" -"Add two new functions to the C-API, :c:func:`PyRefTracer_SetTracer` and :c:" -"func:`PyRefTracer_GetTracer`, that allows to track object creation and " -"destruction the same way the :mod:`tracemalloc` module does. (Contributed by " -"Pablo Galindo in :gh:`93502`.)" +"Add the :c:func:`PyType_GetModuleName` function to get the type's module " +"name. This is equivalent to getting the :attr:`type.__module__` attribute. " +"(Contributed by Eric Snow and Victor Stinner in :gh:`111696`.)" msgstr "" -"Adiciona duas novas funções à API C, :c:func:`PyRefTracer_SetTracer` e :c:" -"func:`PyRefTracer_GetTracer`, que permitem rastrear a criação e destruição " -"de objetos da mesma forma que o módulo :mod:`tracemalloc`. (Contribuição de " -"Pablo Galindo em :gh:`93502`.)" +"Adiciona a função :c:func:`PyType_GetModuleName` para obter o nome do módulo " +"do tipo. Isto é equivalente a obter o atributo :attr:`type.__module__`. " +"(Contribuição de Eric Snow e Victor Stinner em :gh:`111696`.)" -#: ../../whatsnew/3.13.rst:1939 +#: ../../whatsnew/3.13.rst:2249 msgid "" -"Add :c:func:`PyEval_GetFrameBuiltins`, :c:func:`PyEval_GetFrameGlobals`, " -"and :c:func:`PyEval_GetFrameLocals` to the C API. These replacements for :c:" -"func:`PyEval_GetBuiltins`, :c:func:`PyEval_GetGlobals`, and :c:func:" -"`PyEval_GetLocals` return :term:`strong references ` " -"rather than borrowed references. (Added as part of :pep:`667`.)" +"Add the :c:func:`PyUnicode_EqualToUTF8AndSize` and :c:func:" +"`PyUnicode_EqualToUTF8` functions to compare a Unicode object with a :c:expr:" +"`const char*` UTF-8 encoded string and ``1`` if they are equal or ``0`` " +"otherwise. These functions do not raise exceptions. (Contributed by Serhiy " +"Storchaka in :gh:`110289`.)" msgstr "" -"Adiciona :c:func:`PyEval_GetFrameBuiltins`, :c:func:`PyEval_GetFrameGlobals` " -"e :c:func:`PyEval_GetFrameLocals` à API C. Essas substituições para :c:func:" -"`PyEval_GetBuiltins`, :c:func:`PyEval_GetGlobals` e :c:func:" -"`PyEval_GetLocals` retornam :term:`referências fortes ` em " -"vez de referências emprestadas. (Adicionado como parte de :pep:`667`.)" +"Adiciona as funções :c:func:`PyUnicode_EqualToUTF8AndSize` e :c:func:" +"`PyUnicode_EqualToUTF8`: comparam o objeto Unicode com uma string :c:expr:" +"`const char*` codificada em UTF-8 e retornam ``1`` se forem iguais ou ``0`` " +"caso contrário. Essas funções não levantam exceções. (Contribuição de Serhiy " +"Storchaka em :gh:`110289`.)" -#: ../../whatsnew/3.13.rst:1945 +#: ../../whatsnew/3.13.rst:2256 msgid "" -"Add :c:type:`PyMutex` API, a lightweight mutex that occupies a single byte. " -"The :c:func:`PyMutex_Lock` function will release the GIL (if currently held) " -"if the operation needs to block. (Contributed by Sam Gross in :gh:`108724`.)" +"Add the :c:func:`PyWeakref_GetRef` function as an alternative to :c:func:" +"`PyWeakref_GetObject` that returns a :term:`strong reference` or ``NULL`` if " +"the referent is no longer live. (Contributed by Victor Stinner in :gh:" +"`105927`.)" msgstr "" -"Adiciona a API :c:type:`PyMutex`, um mutex leve que ocupa um único byte. A " -"função :c:func:`PyMutex_Lock` irá liberar a GIL (se atualmente mantida) se a " -"operação precisar de bloqueio. (Contribuição de Sam Gross em :gh:`108724`.)" +"Adiciona a função :c:func:`PyWeakref_GetRef` como uma alternativa a :c:func:" +"`PyWeakref_GetObject`, mas retorna uma :term:`referência forte`, ou ``NULL`` " +"se o referente não mais existir. (Contribuição de Victor Stinner em :gh:" +"`105927`.)" -#: ../../whatsnew/3.13.rst:1951 -msgid "Build Changes" -msgstr "Mudanças na construção" +#: ../../whatsnew/3.13.rst:2262 +msgid "Add fixed variants of functions which silently ignore errors:" +msgstr "Adiciona variantes fixas de funções que ignoram erros silenciosamente:" -#: ../../whatsnew/3.13.rst:1953 +#: ../../whatsnew/3.13.rst:2264 msgid "" -"The :file:`configure` option :option:`--with-system-libmpdec` now defaults " -"to ``yes``. The bundled copy of ``libmpdecimal`` will be removed in Python " -"3.15." +":c:func:`PyObject_HasAttrWithError` replaces :c:func:`PyObject_HasAttr`." msgstr "" -"A opção :option:`--with-system-libmpdec` do :file:`configure` agora tem como " -"padrão ``yes``. A cópia empacotada de ``libmpdecimal`` será removida no " -"Python 3.15." +":c:func:`PyObject_HasAttrWithError` substitui :c:func:`PyObject_HasAttr`." -#: ../../whatsnew/3.13.rst:1957 +#: ../../whatsnew/3.13.rst:2265 msgid "" -"Autoconf 2.71 and aclocal 1.16.4 are now required to regenerate the :file:" -"`configure` script. (Contributed by Christian Heimes in :gh:`89886`.)" +":c:func:`PyObject_HasAttrStringWithError` replaces :c:func:" +"`PyObject_HasAttrString`." msgstr "" -"Autoconf 2.71 e aclocal 1.16.4 agora são necessários para regerar o script :" -"file:`configure`. (Contribuição de Christian Heimes em :gh:`89886`.)" +":c:func:`PyObject_HasAttrStringWithError` substitui :c:func:" +"`PyObject_HasAttrString`." -#: ../../whatsnew/3.13.rst:1961 +#: ../../whatsnew/3.13.rst:2267 msgid "" -"SQLite 3.15.2 or newer is required to build the :mod:`sqlite3` extension " -"module. (Contributed by Erlend Aasland in :gh:`105875`.)" +":c:func:`PyMapping_HasKeyWithError` replaces :c:func:`PyMapping_HasKey`." msgstr "" -"SQLite 3.15.2 ou mais recente é necessário para construir o módulo de " -"extensão :mod:`sqlite3`. (Contribuição de Erlend Aasland em :gh:`105875`.)" +":c:func:`PyMapping_HasKeyWithError` substitui :c:func:`PyMapping_HasKey`." -#: ../../whatsnew/3.13.rst:1964 +#: ../../whatsnew/3.13.rst:2268 msgid "" -"Python built with :file:`configure` :option:`--with-trace-refs` (tracing " -"references) is now ABI compatible with the Python release build and :ref:" -"`debug build `. (Contributed by Victor Stinner in :gh:`108634`.)" +":c:func:`PyMapping_HasKeyStringWithError` replaces :c:func:" +"`PyMapping_HasKeyString`." msgstr "" -"Python construído com :file:`configure` :option:`--with-trace-refs` " -"(referências de rastreamento) tem compatibilidade de ABI com a construção de " -"lançamento do Python e a :ref:`construção de depuração `. " -"(Contribuição de Victor Stinner em :gh:`108634`.)" +":c:func:`PyMapping_HasKeyStringWithError` substitui :c:func:" +"`PyMapping_HasKeyString`." -#: ../../whatsnew/3.13.rst:1969 +#: ../../whatsnew/3.13.rst:2271 msgid "" -"Building CPython now requires a compiler with support for the C11 atomic " -"library, GCC built-in atomic functions, or MSVC interlocked intrinsics." +"The new functions return ``-1`` for errors and the standard ``1`` for true " +"and ``0`` for false." msgstr "" -"Construir CPython agora requer um compilador com suporte para a biblioteca " -"atômica C11, funções atômicas embutidas do GCC ou intrínsecos interligados " -"MSVC." +"As novas funções retornam ``-1`` para erros e o padrão ``1`` para verdadeiro " +"e ``0`` para falso." + +#: ../../whatsnew/3.13.rst:2274 +msgid "(Contributed by Serhiy Storchaka in :gh:`108511`.)" +msgstr "(Contribuição de Serhiy Storchaka em :gh:`108511`.)" + +#: ../../whatsnew/3.13.rst:2278 +msgid "Changed C APIs" +msgstr "Alterações na API C" -#: ../../whatsnew/3.13.rst:1972 +#: ../../whatsnew/3.13.rst:2280 msgid "" -"The ``errno``, ``fcntl``, ``grp``, ``md5``, ``pwd``, ``resource``, " -"``termios``, ``winsound``, ``_ctypes_test``, ``_multiprocessing." -"posixshmem``, ``_scproxy``, ``_stat``, ``_statistics``, ``_testconsole``, " -"``_testimportmultiple`` and ``_uuid`` C extensions are now built with the :" -"ref:`limited C API `. (Contributed by Victor Stinner in :gh:" -"`85283`.)" -msgstr "" -"As extensões C ``errno``, ``fcntl``, ``grp``, ``md5``, ``pwd``, " -"``resource``, ``termios``, ``winsound``, ``_ctypes_test``, " -"``_multiprocessing.posixshmem``, ``_scproxy``, ``_stat``, ``_statistics``, " -"``_testconsole``, ``_testimportmultiple`` e ``_uuid`` são agora construídas " -"com a :ref:`API C limitada `. (Contribuição de Victor Stinner " -"em :gh:`85283`.)" +"The *keywords* parameter of :c:func:`PyArg_ParseTupleAndKeywords` and :c:" +"func:`PyArg_VaParseTupleAndKeywords` now has type :c:expr:`char * const *` " +"in C and :c:expr:`const char * const *` in C++, instead of :c:expr:`char " +"**`. In C++, this makes these functions compatible with arguments of type :c:" +"expr:`const char * const *`, :c:expr:`const char **`, or :c:expr:`char * " +"const *` without an explicit type cast. In C, the functions only support " +"arguments of type :c:expr:`char * const *`. This can be overridden with the :" +"c:macro:`PY_CXX_CONST` macro. (Contributed by Serhiy Storchaka in :gh:" +"`65210`.)" +msgstr "" +"O parâmetro *keywords* das funções :c:func:`PyArg_ParseTupleAndKeywords` e :" +"c:func:`PyArg_VaParseTupleAndKeywords` agora é do tipo :c:expr:`char * const " +"*` em C e :c:expr:`const char * const *` em C++, em vez de :c:expr:`char " +"**`. Em C++, isso torna essas funções compatíveis com argumentos dos tipos :" +"c:expr:`const char * const *`, :c:expr:`const char **`, ou :c:expr:`char * " +"const *` sem uma conversão de tipo explícita. Em C, as funções aceitam " +"apenas argumentos do tipo :c:expr:`char * const *`. Isso pode ser " +"sobrescrito com a macro :c:macro:`PY_CXX_CONST`. (Contribuição de Serhiy " +"Storchaka em :gh:`65210`.)" -#: ../../whatsnew/3.13.rst:1979 +#: ../../whatsnew/3.13.rst:2292 msgid "" -"``wasm32-wasi`` is now a :pep:`11` tier 2 platform. (Contributed by Brett " -"Cannon in :gh:`115192`.)" +":c:func:`PyArg_ParseTupleAndKeywords` now supports non-ASCII keyword " +"parameter names. (Contributed by Serhiy Storchaka in :gh:`110815`.)" msgstr "" -"``wasm32-wasi`` agora é uma plataforma de nível 2 segundo a :pep:`11`. " -"(Contribuição de Brett Cannon em :gh:`115192`.)" +":c:func:`PyArg_ParseTupleAndKeywords` agora oferece suporte a nomes de " +"parâmetros nomeados não-ASCII. (Contribuição de Serhiy Storchaka em :gh:" +"`110815`.)" -#: ../../whatsnew/3.13.rst:1982 +#: ../../whatsnew/3.13.rst:2296 msgid "" -"``wasm32-emscripten`` is no longer a :pep:`11` supported platform. " -"(Contributed by Brett Cannon in :gh:`115192`.)" +"The :c:func:`!PyCode_GetFirstFree` function is now unstable API and is now " +"named :c:func:`PyUnstable_Code_GetFirstFree`. (Contributed by Bogdan " +"Romanyuk in :gh:`115781`.)" msgstr "" -"``wasm32-emscripten`` não é mais uma plataforma suportada pela :pep:`11`. " -"(Contribuição de Brett Cannon em :gh:`115192`.)" +"A função :c:func:`!PyCode_GetFirstFree` é agora uma API instável e foi " +"renomeada para :c:func:`PyUnstable_Code_GetFirstFree`. (Contribuição de " +"Bogdan Romanyuk em :gh:`115781`.)" -#: ../../whatsnew/3.13.rst:1985 +#: ../../whatsnew/3.13.rst:2300 msgid "" -"Python now bundles the `mimalloc library `__. It is licensed under the MIT license; see :ref:`mimalloc " -"license `. The bundled mimalloc has custom changes, see :" -"gh:`113141` for details. (Contributed by Dino Viehland in :gh:`109914`.)" +"The :c:func:`PyDict_GetItem`, :c:func:`PyDict_GetItemString`, :c:func:" +"`PyMapping_HasKey`, :c:func:`PyMapping_HasKeyString`, :c:func:" +"`PyObject_HasAttr`, :c:func:`PyObject_HasAttrString`, and :c:func:" +"`PySys_GetObject` functions, each of which clears all errors which occurred " +"when calling them now reports these errors using :func:`sys.unraisablehook`. " +"You may replace them with other functions as recommended in the " +"documentation. (Contributed by Serhiy Storchaka in :gh:`106672`.)" msgstr "" -"Python agora inclui a `biblioteca mimalloc `__. Está licenciada sob a licença do MIT; veja :ref:`licença do " -"mimalloc `. O mimalloc incluído tem alterações " -"personalizadas, veja :gh:`113141` para detalhes. (Contribuição de Dino " -"Viehland em :gh:`109914`.)" +"As funções :c:func:`PyDict_GetItem`, :c:func:`PyDict_GetItemString`, :c:func:" +"`PyMapping_HasKey`, :c:func:`PyMapping_HasKeyString`, :c:func:" +"`PyObject_HasAttr`, :c:func:`PyObject_HasAttrString`, e :c:func:" +"`PySys_GetObject`, que apagam todos os erros que ocorrem ao chamá-las, agora " +"reportam tais erros usando :func:`sys.unraisablehook`. Você pode substituí-" +"las por outras funções conforme recomendado na documentação. (Contribuição " +"de Serhiy Storchaka em :gh:`106672`.)" -#: ../../whatsnew/3.13.rst:1990 +#: ../../whatsnew/3.13.rst:2309 msgid "" -"On POSIX systems, the pkg-config (``.pc``) filenames now include the ABI " -"flags. For example, the free-threaded build generates ``python-3.13t.pc`` " -"and the debug build generates ``python-3.13d.pc``." +"Add support for the ``%T``, ``%#T``, ``%N`` and ``%#N`` formats to :c:func:" +"`PyUnicode_FromFormat`:" msgstr "" -"Em sistemas POSIX, os nomes de arquivos pkg-config (``.pc``) agora incluem " -"os sinalizadores de ABI. Por exemplo, a construção com threads livres gera " -"``python-3.13t.pc`` e a construção de depuração gera ``python-3.13d.pc``." +"Adiciona suporte para os formatos ``%T``, ``%#T``, ``%N`` e ``%#N`` a :c:" +"func:`PyUnicode_FromFormat`:" -#: ../../whatsnew/3.13.rst:1996 -msgid "Porting to Python 3.13" -msgstr "Portando para o Python 3.13" +#: ../../whatsnew/3.13.rst:2312 +msgid "``%T``: Get the fully qualified name of an object type" +msgstr "``%T``: Obtém o nome totalmente qualificado de um tipo de objeto" -#: ../../whatsnew/3.13.rst:1998 -msgid "" -"This section lists previously described changes and other bugfixes that may " -"require changes to your code." -msgstr "" -"Esta seção lista as alterações descritas anteriormente e outras correções " -"que podem exigir alterações no seu código." +#: ../../whatsnew/3.13.rst:2313 +msgid "``%#T``: As above, but use a colon as the separator" +msgstr "``%#T``: Como acima, mas usa dois pontos como separador" -#: ../../whatsnew/3.13.rst:2002 -msgid "Changes in the Python API" -msgstr "Mudanças na API Python" +#: ../../whatsnew/3.13.rst:2314 +msgid "``%N``: Get the fully qualified name of a type" +msgstr "``%N``: Obtém o nome totalmente qualificado de um tipo" -#: ../../whatsnew/3.13.rst:2004 -msgid "" -"An :exc:`OSError` is now raised by :func:`getpass.getuser` for any failure " -"to retrieve a username, instead of :exc:`ImportError` on non-Unix platforms " -"or :exc:`KeyError` on Unix platforms where the password database is empty." -msgstr "" -"Uma :exc:`OSError` agora é levantada por :func:`getpass.getuser` para " -"qualquer falha na recuperação de um nome de usuário, em vez de :exc:" -"`ImportError` em plataformas não-Unix ou :exc:`KeyError` em plataformas Unix " -"onde o banco de dados de senhas está vazio." +#: ../../whatsnew/3.13.rst:2315 +msgid "``%#N``: As above, but use a colon as the separator" +msgstr "``%#N``: Como acima, mas usa dois pontos como separador" -#: ../../whatsnew/3.13.rst:2008 +#: ../../whatsnew/3.13.rst:2317 msgid "" -"The :mod:`threading` module now expects the :mod:`!_thread` module to have " -"an ``_is_main_interpreter`` attribute. It is a function with no arguments " -"that returns ``True`` if the current interpreter is the main interpreter." +"See :pep:`737` for more information. (Contributed by Victor Stinner in :gh:" +"`111696`.)" msgstr "" -"O módulo :mod:`threading` agora espera que o módulo :mod:`!_thread` tenha um " -"atributo ``_is_main_interpreter``. É uma função sem argumentos que retorna " -"``True`` se o interpretador atual for o interpretador principal." +"Veja :pep:`737` para uma descrição completa. (Contribuição de Victor Stinner " +"em :gh:`111696`.)" -#: ../../whatsnew/3.13.rst:2013 +#: ../../whatsnew/3.13.rst:2320 msgid "" -"Any library or application that provides a custom ``_thread`` module must " -"provide ``_is_main_interpreter()``, just like the module's other \"private\" " -"attributes. (See :gh:`112826`.)" +"You no longer have to define the ``PY_SSIZE_T_CLEAN`` macro before " +"including :file:`Python.h` when using ``#`` formats in :ref:`format codes " +"`. APIs accepting the format codes always " +"use ``Py_ssize_t`` for ``#`` formats. (Contributed by Inada Naoki in :gh:" +"`104922`.)" msgstr "" -"Qualquer biblioteca ou aplicação que forneça um módulo ``_thread`` " -"personalizado deve obrigatoriamente fornecer ``_is_main_interpreter()``, da " -"mesma forma que outros atributos \"privados\" do módulo. (Veja :gh:`112826`.)" - -#: ../../whatsnew/3.13.rst:2018 -msgid "" -":class:`mailbox.Maildir` now ignores files with a leading dot. (Contributed " -"by Zackery Spytz in :gh:`65559`.)" -msgstr "" -":class:`mailbox.Maildir` agora ignora arquivos com um ponto inicial. " -"(Contribuição de Zackery Spytz em :gh:`65559`.)" - -#: ../../whatsnew/3.13.rst:2021 -msgid "" -":meth:`pathlib.Path.glob` and :meth:`~pathlib.Path.rglob` now return both " -"files and directories if a pattern that ends with \"``**``\" is given, " -"rather than directories only. Users may add a trailing slash to match only " -"directories." -msgstr "" -":meth:`pathlib.Path.glob` e :meth:`~pathlib.Path.rglob` agora retornam " -"arquivos e diretórios se um padrão que termina com \"``**``\" for fornecido, " -"em vez de apenas diretórios. Os usuários podem adicionar uma barra final " -"para corresponder apenas aos diretórios." - -#: ../../whatsnew/3.13.rst:2026 -msgid "" -"The value of the :attr:`!mode` attribute of :class:`gzip.GzipFile` was " -"changed from integer (``1`` or ``2``) to string (``'rb'`` or ``'wb'``). The " -"value of the :attr:`!mode` attribute of the readable file-like object " -"returned by :meth:`zipfile.ZipFile.open` was changed from ``'r'`` to " -"``'rb'``. (Contributed by Serhiy Storchaka in :gh:`115961`.)" -msgstr "" -"O valor do atributo :attr:`!mode` de :class:`gzip.GzipFile` foi alterado de " -"inteiro (``1`` ou ``2``) para string (``'rb'`` ou ``'wb'``). O valor do " -"atributo :attr:`!mode` do objeto arquivo ou similar legível retornado por :" -"meth:`zipfile.ZipFile.open` foi alterado de ``'r'`` para ``'rb'``. " -"(Contribuição de Serhiy Storchaka em :gh:`115961`.)" - -#: ../../whatsnew/3.13.rst:2032 -msgid "" -":class:`functools.partial` now emits a :exc:`FutureWarning` when it is used " -"as a method. Its behavior will be changed in future Python versions. Wrap it " -"in :func:`staticmethod` if you want to preserve the old behavior. " -"(Contributed by Serhiy Storchaka in :gh:`121027`.)" -msgstr "" -":class:`functools.partial` agora emite uma :exc:`FutureWarning` quando é " -"usado como método. Seu comportamento será alterado em versões futuras do " -"Python. Envolva-a em :func:`staticmethod` se quiser preservar o " -"comportamento antigo. (Contribuição de Serhiy Storchaka em :gh:`121027`.)" - -#: ../../whatsnew/3.13.rst:2040 -msgid "" -"Calling :func:`locals` in an :term:`optimized scope` now produces an " -"independent snapshot on each call, and hence no longer implicitly updates " -"previously returned references. Obtaining the legacy CPython behaviour now " -"requires explicit calls to update the initially returned dictionary with the " -"results of subsequent calls to :func:`!locals`. Code execution functions " -"that implicitly target :func:`!locals` (such as ``exec`` and ``eval``) must " -"be passed an explicit namespace to access their results in an optimized " -"scope. (Changed as part of :pep:`667`.)" -msgstr "" -"Chamar :func:`locals` em um :term:`escopo otimizado` agora produz uma " -"captura independente em cada chamada e, portanto, não atualiza mais " -"implicitamente as referências retornadas anteriormente. Obter o " -"comportamento legado do CPython agora requer chamadas explícitas para " -"atualizar o dicionário inicialmente retornado com os resultados de chamadas " -"subsequentes para :func:`!locals`. Funções de execução de código que visam " -"implicitamente :func:`!locals` (como ``exec`` e ``eval``) devem receber um " -"espaço de nomes explícito para acessar seus resultados em um escopo " -"otimizado. (Alterado como parte da :pep:`667`.)" - -#: ../../whatsnew/3.13.rst:2049 -msgid "" -"Calling :func:`locals` from a comprehension at module or class scope " -"(including via ``exec`` or ``eval``) once more behaves as if the " -"comprehension were running as an independent nested function (i.e. the local " -"variables from the containing scope are not included). In Python 3.12, this " -"had changed to include the local variables from the containing scope when " -"implementing :pep:`709`. (Changed as part of :pep:`667`.)" -msgstr "" -"Chamar :func:`locals` de uma compreensão no módulo ou escopo de classe " -"(inclusive via ``exec`` ou ``eval``) mais uma vez se comporta como se a " -"compreensão estivesse sendo executada como uma função aninhada independente " -"(isto é, as variáveis ​​locais de o escopo que contém não está incluído). No " -"Python 3.12, isso mudou para incluir as variáveis ​​locais do escopo que o " -"contém ao implementar a :pep:`709`. (Alterado como parte da :pep:`667`.)" - -#: ../../whatsnew/3.13.rst:2056 -msgid "" -"Accessing :attr:`FrameType.f_locals ` in an :term:`optimized " -"scope` now returns a write-through proxy rather than a snapshot that gets " -"updated at ill-specified times. If a snapshot is desired, it must be created " -"explicitly with ``dict`` or the proxy's ``.copy()`` method. (Changed as part " -"of :pep:`667`.)" -msgstr "" -"Acessar :attr:`FrameType.f_locals ` em um :term:`escopo " -"otimizado` agora retorna um proxy de \"write-through\" em vez de uma captura " -"que é atualizado em horários mal especificados. Se uma captura for desejada, " -"ela deve ser criada explicitamente com ``dict`` ou com o método ``.copy()`` " -"do proxy. (Alterado como parte da :pep:`667`.)" - -#: ../../whatsnew/3.13.rst:2063 -msgid "Changes in the C API" -msgstr "Mudanças na API C" - -#: ../../whatsnew/3.13.rst:2065 -msgid "" -"``Python.h`` no longer includes the ```` standard header. It was " -"included for the ``finite()`` function which is now provided by the ```` header. It should now be included explicitly if needed. Remove also the " -"``HAVE_IEEEFP_H`` macro. (Contributed by Victor Stinner in :gh:`108765`.)" -msgstr "" -"``Python.h`` não inclui mais o cabeçalho padrão ````. Ele foi " -"incluído para a função ``finite()`` que agora é fornecida pelo cabeçalho " -"````. Agora deve ser incluído explicitamente, se necessário. Remova " -"também a macro ``HAVE_IEEEFP_H``. (Contribuição de Victor Stinner em :gh:" -"`108765`.)" - -#: ../../whatsnew/3.13.rst:2071 -msgid "" -"``Python.h`` no longer includes these standard header files: ````, " -"```` and ````. If needed, they should now be " -"included explicitly. For example, ```` provides the ``clock()`` and " -"``gmtime()`` functions, ```` provides the ``select()`` " -"function, and ```` provides the ``futimes()``, " -"``gettimeofday()`` and ``setitimer()`` functions. (Contributed by Victor " -"Stinner in :gh:`108765`.)" -msgstr "" -"``Python.h`` não inclui mais estes arquivos de cabeçalho padrão: ````, ```` e ````. Se necessário, deverão agora " -"ser incluídos explicitamente. Por exemplo, ```` fornece as funções " -"``clock()`` e ``gmtime()``, ```` fornece o ``select()``, e " -"```` fornece as funções ``futimes()``, ``gettimeofday()`` e " -"``setitimer()``. (Contribuição de Victor Stinner em :gh:`108765`.)" +"Você não precisa mais definir a macro ``PY_SSIZE_T_CLEAN`` antes de incluir :" +"file:`Python.h` ao usar formatos ``#`` em :ref:`códigos de formato `. APIs que aceitam os códigos de formato sempre " +"usam ``Py_ssize_t`` para formatos ``#``. (Contribuição de Inada Naoki em :gh:" +"`104922`.)" -#: ../../whatsnew/3.13.rst:2079 +#: ../../whatsnew/3.13.rst:2326 msgid "" -"On Windows, ``Python.h`` no longer includes the ```` standard " -"header file. If needed, it should now be included explicitly. For example, " -"it provides ``offsetof()`` function, and ``size_t`` and ``ptrdiff_t`` types. " -"Including ```` explicitly was already needed by all other " -"platforms, the ``HAVE_STDDEF_H`` macro is only defined on Windows. " -"(Contributed by Victor Stinner in :gh:`108765`.)" +"If Python is built in :ref:`debug mode ` or :option:`with " +"assertions <--with-assertions>`, :c:func:`PyTuple_SET_ITEM` and :c:func:" +"`PyList_SET_ITEM` now check the index argument with an assertion. " +"(Contributed by Victor Stinner in :gh:`106168`.)" msgstr "" -"No Windows, ``Python.h`` não inclui mais o arquivo de cabeçalho padrão " -"````. Se necessário, deverá agora ser incluído explicitamente. Por " -"exemplo, ele fornece a função ``offsetof()`` e os tipos ``size_t`` e " -"``ptrdiff_t``. Incluindo ```` explicitamente já era necessário " -"para todas as outras plataformas, a macro ``HAVE_STDDEF_H`` só é definida no " -"Windows. (Contribuição de Victor Stinner em :gh:`108765`.)" +"Se Python for construído em :ref:`modo de depuração ` ou :" +"option:`com asserções <--with-assertions>`, :c:func:`PyTuple_SET_ITEM` e :c:" +"func:`PyList_SET_ITEM` agora verificam o argumento do índice com uma " +"asserção. (Contribuição de Victor Stinner em :gh:`106168`.)" -#: ../../whatsnew/3.13.rst:2086 -msgid "" -"If the :c:macro:`Py_LIMITED_API` macro is defined, :c:macro:`!" -"Py_BUILD_CORE`, :c:macro:`!Py_BUILD_CORE_BUILTIN` and :c:macro:`!" -"Py_BUILD_CORE_MODULE` macros are now undefined by ````. " -"(Contributed by Victor Stinner in :gh:`85283`.)" -msgstr "" -"Se a macro :c:macro:`Py_LIMITED_API` estiver definida, as macros :c:macro:`!" -"Py_BUILD_CORE`, :c:macro:`!Py_BUILD_CORE_BUILTIN` e :c:macro:`!" -"Py_BUILD_CORE_MODULE` agora são indefinidas por ````. " -"(Contribuição de Victor Stinner em :gh:`85283`.)" +#: ../../whatsnew/3.13.rst:2334 +msgid "Limited C API Changes" +msgstr "Mudanças na API C Limitada" -#: ../../whatsnew/3.13.rst:2091 -msgid "" -"The old trashcan macros ``Py_TRASHCAN_SAFE_BEGIN`` and " -"``Py_TRASHCAN_SAFE_END`` were removed. They should be replaced by the new " -"macros ``Py_TRASHCAN_BEGIN`` and ``Py_TRASHCAN_END``." -msgstr "" -"As macros antigas da lixeira ``Py_TRASHCAN_SAFE_BEGIN`` e " -"``Py_TRASHCAN_SAFE_END`` foram removidas. Elas devem ser substituídas pelas " -"novas macros ``Py_TRASHCAN_BEGIN`` e ``Py_TRASHCAN_END``." +#: ../../whatsnew/3.13.rst:2336 +msgid "The following functions are now included in the Limited C API:" +msgstr "As seguintes funções agora estão incluídas na API C limitada:" -#: ../../whatsnew/3.13.rst:2095 -msgid "A ``tp_dealloc`` function that has the old macros, such as::" -msgstr "Uma função ``tp_dealloc`` que contém as macros antigas, como::" +#: ../../whatsnew/3.13.rst:2338 +msgid ":c:func:`PyMem_RawMalloc`" +msgstr ":c:func:`PyMem_RawMalloc`" -#: ../../whatsnew/3.13.rst:2106 -msgid "should migrate to the new macros as follows::" -msgstr "deve migrar para as novas macros da seguinte forma::" +#: ../../whatsnew/3.13.rst:2339 +msgid ":c:func:`PyMem_RawCalloc`" +msgstr ":c:func:`PyMem_RawCalloc`" -#: ../../whatsnew/3.13.rst:2117 -msgid "" -"Note that ``Py_TRASHCAN_BEGIN`` has a second argument which should be the " -"deallocation function it is in. The new macros were added in Python 3.8 and " -"the old macros were deprecated in Python 3.11. (Contributed by Irit Katriel " -"in :gh:`105111`.)" -msgstr "" -"Observe que ``Py_TRASHCAN_BEGIN`` tem um segundo argumento que deve ser a " -"função de desalocação em que está. As novas macros foram adicionadas no " -"Python 3.8 e as macros antigas foram descontinuadas no Python 3.11. " -"(Contribuição de Irit Katriel em :gh:`105111`.)" +#: ../../whatsnew/3.13.rst:2340 +msgid ":c:func:`PyMem_RawRealloc`" +msgstr ":c:func:`PyMem_RawRealloc`" -#: ../../whatsnew/3.13.rst:2122 -msgid "" -"Functions :c:func:`PyDict_GetItem`, :c:func:`PyDict_GetItemString`, :c:func:" -"`PyMapping_HasKey`, :c:func:`PyMapping_HasKeyString`, :c:func:" -"`PyObject_HasAttr`, :c:func:`PyObject_HasAttrString`, and :c:func:" -"`PySys_GetObject`, which clear all errors which occurred when calling them, " -"now report them using :func:`sys.unraisablehook`. You may replace them with " -"other functions as recommended in the documentation. (Contributed by Serhiy " -"Storchaka in :gh:`106672`.)" -msgstr "" -"Funções :c:func:`PyDict_GetItem`, :c:func:`PyDict_GetItemString`, :c:func:" -"`PyMapping_HasKey`, :c:func:`PyMapping_HasKeyString`, :c:func:" -"`PyObject_HasAttr`, :c:func:`PyObject_HasAttrString`, e :c:func:" -"`PySys_GetObject`, que apagam todos os erros que ocorrem ao chamá-los, agora " -"se reportam usando :func:`sys.unraisablehook`. Você pode substituí-las por " -"outras funções conforme recomendado na documentação. (Contribuição de Serhiy " -"Storchaka em :gh:`106672`.)" +#: ../../whatsnew/3.13.rst:2341 +msgid ":c:func:`PyMem_RawFree`" +msgstr ":c:func:`PyMem_RawFree`" -#: ../../whatsnew/3.13.rst:2131 -msgid "" -":c:func:`!PyCode_GetFirstFree` is an unstable API now and has been renamed " -"to :c:func:`PyUnstable_Code_GetFirstFree`. (Contributed by Bogdan Romanyuk " -"in :gh:`115781`.)" -msgstr "" -":c:func:`!PyCode_GetFirstFree` é uma API instável agora e foi renomeada " -"para :c:func:`PyUnstable_Code_GetFirstFree`. (Contribuição de Bogdan " -"Romanyuk em :gh:`115781`.)" +#: ../../whatsnew/3.13.rst:2342 +msgid ":c:func:`PySys_Audit`" +msgstr ":c:func:`PySys_Audit`" -#: ../../whatsnew/3.13.rst:2137 -msgid "" -"The effects of mutating the dictionary returned from :c:func:" -"`PyEval_GetLocals` in an :term:`optimized scope` have changed. New dict " -"entries added this way will now *only* be visible to subsequent :c:func:" -"`PyEval_GetLocals` calls in that frame, as :c:func:`PyFrame_GetLocals`, :" -"func:`locals`, and :attr:`FrameType.f_locals ` no longer " -"access the same underlying cached dictionary. Changes made to entries for " -"actual variable names and names added via the write-through proxy interfaces " -"will be overwritten on subsequent calls to :c:func:`PyEval_GetLocals` in " -"that frame. The recommended code update depends on how the function was " -"being used, so refer to the deprecation notice on the function for details. " -"(Changed as part of :pep:`667`.)" -msgstr "" -"Os efeitos da mutação do dicionário retornado de :c:func:`PyEval_GetLocals` " -"em um :term:`escopo otimizado` foram alterados. Novas entradas de dict " -"adicionadas desta forma agora *apenas* ficarão visíveis para chamadas :c:" -"func:`PyEval_GetLocals` subsequentes nesse quadro, como :c:func:" -"`PyFrame_GetLocals`, :func:`locals` e :attr:`FrameType.f_locals ` não acessa mais o mesmo dicionário armazenado em cache " -"subjacente. As alterações feitas nas entradas para nomes de variáveis ​​reais " -"e nomes adicionados através das interfaces proxy de \"write-through\" serão " -"substituídas em chamadas subsequentes para :c:func:`PyEval_GetLocals` nesse " -"quadro. A atualização de código recomendada depende de como a função estava " -"sendo usada, portanto, consulte o aviso de descontinuação na função para " -"obter detalhes. (Alteração como parte da :pep:`667`.)" +#: ../../whatsnew/3.13.rst:2343 +msgid ":c:func:`PySys_AuditTuple`" +msgstr ":c:func:`PySys_AuditTuple`" -#: ../../whatsnew/3.13.rst:2148 -msgid "" -"Calling :c:func:`PyFrame_GetLocals` in an :term:`optimized scope` now " -"returns a write-through proxy rather than a snapshot that gets updated at " -"ill-specified times. If a snapshot is desired, it must be created explicitly " -"(e.g. with :c:func:`PyDict_Copy`) or by calling the new :c:func:" -"`PyEval_GetFrameLocals` API. (Changed as part of :pep:`667`.)" -msgstr "" -"Chamar :c:func:`PyFrame_GetLocals` em um :term:`escopo otimizado` agora " -"retorna um proxy de \"write-through\" em vez de uma captura que é atualizada " -"em horários mal especificados. Se uma captura for desejada, ela deve ser " -"criada explicitamente (por exemplo, com :c:func:`PyDict_Copy`) ou chamando a " -"nova API :c:func:`PyEval_GetFrameLocals`. (Alteração como parte da :pep:" -"`667`.)" +#: ../../whatsnew/3.13.rst:2344 +msgid ":c:func:`PyType_GetModuleByDef`" +msgstr ":c:func:`PyType_GetModuleByDef`" -#: ../../whatsnew/3.13.rst:2153 +#: ../../whatsnew/3.13.rst:2346 msgid "" -":c:func:`!PyFrame_FastToLocals` and :c:func:`!PyFrame_FastToLocalsWithError` " -"no longer have any effect. Calling these functions has been redundant since " -"Python 3.11, when :c:func:`PyFrame_GetLocals` was first introduced. (Changed " -"as part of :pep:`667`.)" +"(Contributed by Victor Stinner in :gh:`85283`, :gh:`85283`, and :gh:" +"`116936`.)" msgstr "" -":c:func:`!PyFrame_FastToLocals` e :c:func:`!PyFrame_FastToLocalsWithError` " -"não têm mais nenhum efeito. Chamar essas funções tem sido redundante desde o " -"Python 3.11, quando :c:func:`PyFrame_GetLocals` foi introduzido pela " -"primeira vez. (Alteração como parte de :pep:`667`.)" +"(Contribuição de Victor Stinner em :gh:`85283`, :gh:`85283` e :gh:`116936`.)" -#: ../../whatsnew/3.13.rst:2158 +#: ../../whatsnew/3.13.rst:2348 msgid "" -":c:func:`!PyFrame_LocalsToFast` no longer has any effect. Calling this " -"function is redundant now that :c:func:`PyFrame_GetLocals` returns a write-" -"through proxy for :term:`optimized scopes `. (Changed as " -"part of :pep:`667`.)" +"Python built with :option:`--with-trace-refs` (tracing references) now " +"supports the :ref:`Limited API `. (Contributed by Victor " +"Stinner in :gh:`108634`.)" msgstr "" -":c:func:`!PyFrame_LocalsToFast` não tem mais efeito. Chamar esta função é " -"redundante agora que :c:func:`PyFrame_GetLocals` retorna um proxy de \"write-" -"through\" para :term:`escopos otimizados `. (Alteração " -"como parte da :pep:`667`.)" +"Python construído com :option:`--with-trace-refs` (referências de " +"rastreamento) agora oferece suporte à :ref:`API Limitada `. " +"(Contribuição de Victor Stinner em :gh:`108634`.)" -#: ../../whatsnew/3.13.rst:2163 +#: ../../whatsnew/3.13.rst:2354 msgid "Removed C APIs" msgstr "APIs C removidas" -#: ../../whatsnew/3.13.rst:2165 +#: ../../whatsnew/3.13.rst:2356 msgid "" -"Remove many APIs (functions, macros, variables) with names prefixed by " -"``_Py`` or ``_PY`` (considered as private API). If your project is affected " -"by one of these removals and you consider that the removed API should remain " -"available, please open a new issue to request a public C API and add ``cc " -"@vstinner`` to the issue to notify Victor Stinner. (Contributed by Victor " -"Stinner in :gh:`106320`.)" +"Remove several functions, macros, variables, etc with names prefixed by " +"``_Py`` or ``_PY`` (which are considered private). If your project is " +"affected by one of these removals and you believe that the removed API " +"should remain available, please :ref:`open a new issue ` " +"to request a public C API and add ``cc: @vstinner`` to the issue to notify " +"Victor Stinner. (Contributed by Victor Stinner in :gh:`106320`.)" msgstr "" -"Remove muitas APIs (funções, macros, variáveis) com nomes prefixados por " +"Remove diversas funções, macros, variáveis, etc com nomes prefixados por " "``_Py`` ou ``_PY`` (consideradas como API privada). Se o seu projeto for " -"afetado por uma dessas remoções e você considerar que a API removida deve " -"permanecer disponível, abra um novo relatório de problema para solicitar uma " -"API C pública e adicione ``cc @vstinner`` ao problema para notificar Victor " -"Stinner. (Contribuição de Victor Stinner em :gh:`106320`.)" - -#: ../../whatsnew/3.13.rst:2172 -msgid "Remove functions deprecated in Python 3.9:" -msgstr "Remova funções descontinuadas no Python 3.9:" - -#: ../../whatsnew/3.13.rst:2174 -msgid "" -"``PyEval_CallObject()``, ``PyEval_CallObjectWithKeywords()``: use :c:func:" -"`PyObject_CallNoArgs` or :c:func:`PyObject_Call` instead. Warning: :c:func:" -"`PyObject_Call` positional arguments must be a :class:`tuple` and must not " -"be ``NULL``, keyword arguments must be a :class:`dict` or ``NULL``, whereas " -"removed functions checked arguments type and accepted ``NULL`` positional " -"and keyword arguments. To replace ``PyEval_CallObjectWithKeywords(func, " -"NULL, kwargs)`` with :c:func:`PyObject_Call`, pass an empty tuple as " -"positional arguments using :c:func:`PyTuple_New(0) `." -msgstr "" -"``PyEval_CallObject()``, ``PyEval_CallObjectWithKeywords()``: use :c:func:" -"`PyObject_CallNoArgs` ou :c:func:`PyObject_Call` em vez disso. Aviso: os " -"argumentos posicionais de :c:func:`PyObject_Call` devem ser :class:`tuple` e " -"não podem ser ``NULL``, os argumentos nomeados devem ser :class:`dict` ou " -"``NULL``, enquanto funções removidas verificavam o tipo de argumentos e " -"aceitavam argumentos posicionais e nomeados ``NULL``. Para substituir " -"``PyEval_CallObjectWithKeywords(func, NULL, kwargs)`` por :c:func:" -"`PyObject_Call`, passe uma tupla vazia como argumentos posicionais usando :c:" -"func:`PyTuple_New(0) `." +"afetado por uma dessas remoções e você acreditar que a API removida deve " +"permanecer disponível, por favor :ref:`abra um novo relatório de problema " +"` para solicitar uma API C pública e adicione ``cc: " +"@vstinner`` ao problema para notificar Victor Stinner. (Contribuição de " +"Victor Stinner em :gh:`106320`.)" -#: ../../whatsnew/3.13.rst:2183 -msgid "``PyEval_CallFunction()``: use :c:func:`PyObject_CallFunction` instead." -msgstr "``PyEval_CallFunction()``: use :c:func:`PyObject_CallFunction`." - -#: ../../whatsnew/3.13.rst:2184 -msgid "``PyEval_CallMethod()``: use :c:func:`PyObject_CallMethod` instead." -msgstr "``PyEval_CallMethod()``: use :c:func:`PyObject_CallMethod`." - -#: ../../whatsnew/3.13.rst:2185 -msgid "``PyCFunction_Call()``: use :c:func:`PyObject_Call` instead." -msgstr "``PyCFunction_Call()``: use :c:func:`PyObject_Call`." - -#: ../../whatsnew/3.13.rst:2187 -msgid "(Contributed by Victor Stinner in :gh:`105107`.)" -msgstr "(Contribuição de Victor Stinner em :gh:`105107`.)" - -#: ../../whatsnew/3.13.rst:2189 +#: ../../whatsnew/3.13.rst:2364 msgid "" "Remove old buffer protocols deprecated in Python 3.0. Use :ref:" "`bufferobjects` instead." msgstr "" -"Remova protocolos de buffer antigos descontinuados no Python 3.0. Use :ref:" -"`bufferobjects` em vez disso." +"Remove protocolos de buffer antigos descontinuados no Python 3.0: use :ref:" +"`bufferobjects`." -#: ../../whatsnew/3.13.rst:2191 +#: ../../whatsnew/3.13.rst:2367 msgid "" ":c:func:`!PyObject_CheckReadBuffer`: Use :c:func:`PyObject_CheckBuffer` to " -"test if the object supports the buffer protocol. Note that :c:func:" +"test whether the object supports the buffer protocol. Note that :c:func:" "`PyObject_CheckBuffer` doesn't guarantee that :c:func:`PyObject_GetBuffer` " "will succeed. To test if the object is actually readable, see the next " "example of :c:func:`PyObject_GetBuffer`." msgstr "" -":c:func:`!PyObject_CheckReadBuffer`: Use :c:func:`PyObject_CheckBuffer` para " +":c:func:`!PyObject_CheckReadBuffer`: use :c:func:`PyObject_CheckBuffer` para " "testar se o objeto oferece suporte ao protocolo de buffer. Observe que :c:" "func:`PyObject_CheckBuffer` não garante que :c:func:`PyObject_GetBuffer` " "terá sucesso. Para testar se o objeto é realmente legível, veja o próximo " "exemplo de :c:func:`PyObject_GetBuffer`." -#: ../../whatsnew/3.13.rst:2198 +#: ../../whatsnew/3.13.rst:2375 +msgid "" +":c:func:`!PyObject_AsCharBuffer`, :c:func:`!PyObject_AsReadBuffer`: Use :c:" +"func:`PyObject_GetBuffer` and :c:func:`PyBuffer_Release` instead:" +msgstr "" +":c:func:`!PyObject_AsCharBuffer`, :c:func:`!PyObject_AsReadBuffer`: use :c:" +"func:`PyObject_GetBuffer` e :c:func:`PyBuffer_Release`:" + +#: ../../whatsnew/3.13.rst:2378 msgid "" -":c:func:`!PyObject_AsCharBuffer`, :c:func:`!PyObject_AsReadBuffer`: :c:func:" -"`PyObject_GetBuffer` and :c:func:`PyBuffer_Release` instead:" +"Py_buffer view;\n" +"if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) < 0) {\n" +" return NULL;\n" +"}\n" +"// Use `view.buf` and `view.len` to read from the buffer.\n" +"// You may need to cast buf as `(const char*)view.buf`.\n" +"PyBuffer_Release(&view);" msgstr "" -":c:func:`!PyObject_AsCharBuffer`, :c:func:`!PyObject_AsReadBuffer`: :c:func:" -"`PyObject_GetBuffer` e :c:func:`PyBuffer_Release`:" +"Py_buffer view;\n" +"if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) < 0) {\n" +" return NULL;\n" +"}\n" +"// Usa `view.buf` e `view.len` para ler do buffer.\n" +"// Você pode precisar converter buf como `(const char*)view.buf`.\n" +"PyBuffer_Release(&view);" -#: ../../whatsnew/3.13.rst:2211 +#: ../../whatsnew/3.13.rst:2388 msgid "" ":c:func:`!PyObject_AsWriteBuffer`: Use :c:func:`PyObject_GetBuffer` and :c:" "func:`PyBuffer_Release` instead:" msgstr "" -":c:func:`!PyObject_AsWriteBuffer`: Use :c:func:`PyObject_GetBuffer` e :c:" +":c:func:`!PyObject_AsWriteBuffer`: use :c:func:`PyObject_GetBuffer` e :c:" "func:`PyBuffer_Release`:" -#: ../../whatsnew/3.13.rst:2223 +#: ../../whatsnew/3.13.rst:2391 +msgid "" +"Py_buffer view;\n" +"if (PyObject_GetBuffer(obj, &view, PyBUF_WRITABLE) < 0) {\n" +" return NULL;\n" +"}\n" +"// Use `view.buf` and `view.len` to write to the buffer.\n" +"PyBuffer_Release(&view);" +msgstr "" +"Py_buffer view;\n" +"if (PyObject_GetBuffer(obj, &view, PyBUF_WRITABLE) < 0) {\n" +" return NULL;\n" +"}\n" +"// Usa `view.buf` e `view.len` para gravar no buffer.\n" +"PyBuffer_Release(&view);" + +#: ../../whatsnew/3.13.rst:2400 msgid "(Contributed by Inada Naoki in :gh:`85275`.)" msgstr "(Contribuição de Inada Naoki in :gh:`85275`.)" -#: ../../whatsnew/3.13.rst:2225 +#: ../../whatsnew/3.13.rst:2402 +msgid "Remove various functions deprecated in Python 3.9:" +msgstr "Remove diversas funções descontinuadas no Python 3.9:" + +#: ../../whatsnew/3.13.rst:2404 +msgid "" +":c:func:`!PyEval_CallObject`, :c:func:`!PyEval_CallObjectWithKeywords`: Use :" +"c:func:`PyObject_CallNoArgs` or :c:func:`PyObject_Call` instead." +msgstr "" +":c:func:`!PyEval_CallObject`, :c:func:`!PyEval_CallObjectWithKeywords`: use :" +"c:func:`PyObject_CallNoArgs` ou :c:func:`PyObject_Call`." + +#: ../../whatsnew/3.13.rst:2409 +msgid "" +"In :c:func:`PyObject_Call`, positional arguments must be a :class:`tuple` " +"and must not be ``NULL``, and keyword arguments must be a :class:`dict` or " +"``NULL``, whereas the removed functions checked argument types and accepted " +"``NULL`` positional and keyword arguments. To replace " +"``PyEval_CallObjectWithKeywords(func, NULL, kwargs)`` with :c:func:" +"`PyObject_Call`, pass an empty tuple as positional arguments using :c:func:" +"`PyTuple_New(0) `." +msgstr "" +"Os argumentos posicionais de :c:func:`PyObject_Call` devem ser uma :class:" +"`tuple` e não podem ser ``NULL``, os argumentos nomeados devem ser :class:" +"`dict` ou ``NULL``, enquanto funções removidas verificavam o tipo de " +"argumentos e aceitavam argumentos posicionais e nomeados ``NULL``. Para " +"substituir ``PyEval_CallObjectWithKeywords(func, NULL, kwargs)`` por :c:func:" +"`PyObject_Call`, passe uma tupla vazia como argumentos posicionais usando :c:" +"func:`PyTuple_New(0) `." + +#: ../../whatsnew/3.13.rst:2419 +msgid "" +":c:func:`!PyEval_CallFunction`: Use :c:func:`PyObject_CallFunction` instead." +msgstr ":c:func:`!PyEval_CallFunction`: use :c:func:`PyObject_CallFunction`." + +#: ../../whatsnew/3.13.rst:2421 +msgid "" +":c:func:`!PyEval_CallMethod`: Use :c:func:`PyObject_CallMethod` instead." +msgstr ":c:func:`!PyEval_CallMethod`: use :c:func:`PyObject_CallMethod`." + +#: ../../whatsnew/3.13.rst:2423 +msgid ":c:func:`!PyCFunction_Call`: Use :c:func:`PyObject_Call` instead." +msgstr ":c:func:`!PyCFunction_Call`: use :c:func:`PyObject_Call`." + +#: ../../whatsnew/3.13.rst:2426 +msgid "(Contributed by Victor Stinner in :gh:`105107`.)" +msgstr "(Contribuição de Victor Stinner em :gh:`105107`.)" + +#: ../../whatsnew/3.13.rst:2428 msgid "" "Remove the following old functions to configure the Python initialization, " "deprecated in Python 3.11:" msgstr "" -"Remova as seguintes funções antigas da configuração de inicialização do " +"Remove as seguintes funções antigas da configuração de inicialização do " "Python, descontinuadas no Python 3.11:" -#: ../../whatsnew/3.13.rst:2228 +#: ../../whatsnew/3.13.rst:2431 msgid "" -"``PySys_AddWarnOptionUnicode()``: use :c:member:`PyConfig.warnoptions` " +":c:func:`!PySys_AddWarnOptionUnicode`: Use :c:member:`PyConfig.warnoptions` " "instead." msgstr "" -"``PySys_AddWarnOptionUnicode()``: use :c:member:`PyConfig.warnoptions`." +":c:func:`!PySys_AddWarnOptionUnicode`: use :c:member:`PyConfig.warnoptions`." -#: ../../whatsnew/3.13.rst:2229 +#: ../../whatsnew/3.13.rst:2433 msgid "" -"``PySys_AddWarnOption()``: use :c:member:`PyConfig.warnoptions` instead." -msgstr "``PySys_AddWarnOption()``: use :c:member:`PyConfig.warnoptions`." +":c:func:`!PySys_AddWarnOption`: Use :c:member:`PyConfig.warnoptions` instead." +msgstr ":c:func:`!PySys_AddWarnOption`: use :c:member:`PyConfig.warnoptions`." -#: ../../whatsnew/3.13.rst:2230 -msgid "``PySys_AddXOption()``: use :c:member:`PyConfig.xoptions` instead." -msgstr "``PySys_AddXOption()``: use :c:member:`PyConfig.xoptions`." +#: ../../whatsnew/3.13.rst:2435 +msgid ":c:func:`!PySys_AddXOption`: Use :c:member:`PyConfig.xoptions` instead." +msgstr ":c:func:`!PySys_AddXOption`: use :c:member:`PyConfig.xoptions`." -#: ../../whatsnew/3.13.rst:2231 -msgid "``PySys_HasWarnOptions()``: use :c:member:`PyConfig.xoptions` instead." -msgstr "``PySys_HasWarnOptions()``: use :c:member:`PyConfig.xoptions`." +#: ../../whatsnew/3.13.rst:2437 +msgid "" +":c:func:`!PySys_HasWarnOptions`: Use :c:member:`PyConfig.xoptions` instead." +msgstr ":c:func:`!PySys_HasWarnOptions`: use :c:member:`PyConfig.xoptions`." -#: ../../whatsnew/3.13.rst:2232 +#: ../../whatsnew/3.13.rst:2439 msgid "" -"``PySys_SetPath()``: set :c:member:`PyConfig.module_search_paths` instead." -msgstr "``PySys_SetPath()``: defina :c:member:`PyConfig.module_search_paths`." +":c:func:`!PySys_SetPath`: Set :c:member:`PyConfig.module_search_paths` " +"instead." +msgstr "" +":c:func:`!PySys_SetPath`: defina :c:member:`PyConfig.module_search_paths`." -#: ../../whatsnew/3.13.rst:2233 -msgid "``Py_SetPath()``: set :c:member:`PyConfig.module_search_paths` instead." -msgstr "``Py_SetPath()``: defina :c:member:`PyConfig.module_search_paths`." +#: ../../whatsnew/3.13.rst:2441 +msgid "" +":c:func:`!Py_SetPath`: Set :c:member:`PyConfig.module_search_paths` instead." +msgstr "" +":c:func:`!Py_SetPath`: defina :c:member:`PyConfig.module_search_paths`." -#: ../../whatsnew/3.13.rst:2234 +#: ../../whatsnew/3.13.rst:2443 msgid "" -"``Py_SetStandardStreamEncoding()``: set :c:member:`PyConfig.stdio_encoding` " -"instead, and set also maybe :c:member:`PyConfig.legacy_windows_stdio` (on " -"Windows)." +":c:func:`!Py_SetStandardStreamEncoding`: Set :c:member:`PyConfig." +"stdio_encoding` instead, and set also maybe :c:member:`PyConfig." +"legacy_windows_stdio` (on Windows)." msgstr "" -"``Py_SetStandardStreamEncoding()``: defina :c:member:`PyConfig." -"stdio_encoding` e talvez também defina :c:member:`PyConfig." -"legacy_windows_stdio` (no Windows)." +":c:func:`!Py_SetStandardStreamEncoding`: defina :c:member:`PyConfig." +"stdio_encoding`, e também talvez :c:member:`PyConfig.legacy_windows_stdio` " +"(no Windows)." -#: ../../whatsnew/3.13.rst:2237 +#: ../../whatsnew/3.13.rst:2446 msgid "" -"``_Py_SetProgramFullPath()``: set :c:member:`PyConfig.executable` instead." -msgstr "``_Py_SetProgramFullPath()``: defina :c:member:`PyConfig.executable`." +":c:func:`!_Py_SetProgramFullPath`: Set :c:member:`PyConfig.executable` " +"instead." +msgstr "" +":c:func:`!_Py_SetProgramFullPath`: defina :c:member:`PyConfig.executable`." -#: ../../whatsnew/3.13.rst:2239 +#: ../../whatsnew/3.13.rst:2449 msgid "" "Use the new :c:type:`PyConfig` API of the :ref:`Python Initialization " "Configuration ` instead (:pep:`587`), added to Python 3.8. " @@ -5525,210 +5944,215 @@ msgstr "" "Inicialização do Python ` (:pep:`587`), adicionada ao Python " "3.8. (Contribuição de Victor Stinner em :gh:`105145`.)" -#: ../../whatsnew/3.13.rst:2243 -msgid "" -"Remove ``PyEval_ThreadsInitialized()`` function, deprecated in Python 3.9. " -"Since Python 3.7, ``Py_Initialize()`` always creates the GIL: calling " -"``PyEval_InitThreads()`` does nothing and ``PyEval_ThreadsInitialized()`` " -"always returned non-zero. (Contributed by Victor Stinner in :gh:`105182`.)" -msgstr "" -"Remove a função ``PyEval_ThreadsInitialized()``, descontinuada no Python " -"3.9. Desde Python 3.7, ``Py_Initialize()`` sempre cria a GIL: chamar " -"``PyEval_InitThreads()`` não faz nada e ``PyEval_ThreadsInitialized()`` " -"sempre retorna diferente de zero. (Contribuição de Victor Stinner em :gh:" -"`105182`.)" - -#: ../../whatsnew/3.13.rst:2249 +#: ../../whatsnew/3.13.rst:2453 msgid "" -"Remove ``PyEval_AcquireLock()`` and ``PyEval_ReleaseLock()`` functions, " -"deprecated in Python 3.2. They didn't update the current thread state. They " -"can be replaced with:" +"Remove :c:func:`!PyEval_AcquireLock` and :c:func:`!PyEval_ReleaseLock` " +"functions, deprecated in Python 3.2. They didn't update the current thread " +"state. They can be replaced with:" msgstr "" -"Remove as funções ``PyEval_AcquireLock()`` e ``PyEval_ReleaseLock()``, " -"descontinuadas no Python 3.2. Eles não atualizavam o estado atual da thread. " -"Elas podem ser substituídas por:" +"Remove as funções :c:func:`!PyEval_AcquireLock` e :c:func:`!" +"PyEval_ReleaseLock`, descontinuadas no Python 3.2. Eles não atualizavam o " +"estado atual da thread. Elas podem ser substituídas por:" -#: ../../whatsnew/3.13.rst:2253 +#: ../../whatsnew/3.13.rst:2458 msgid ":c:func:`PyEval_SaveThread` and :c:func:`PyEval_RestoreThread`;" msgstr ":c:func:`PyEval_SaveThread` e :c:func:`PyEval_RestoreThread`;" -#: ../../whatsnew/3.13.rst:2254 +#: ../../whatsnew/3.13.rst:2459 msgid "" "low-level :c:func:`PyEval_AcquireThread` and :c:func:`PyEval_RestoreThread`;" msgstr "" ":c:func:`PyEval_AcquireThread` e :c:func:`PyEval_RestoreThread` de baixo " "nível;" -#: ../../whatsnew/3.13.rst:2255 +#: ../../whatsnew/3.13.rst:2460 msgid "or :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release`." msgstr "ou :c:func:`PyGILState_Ensure` e :c:func:`PyGILState_Release`." -#: ../../whatsnew/3.13.rst:2257 +#: ../../whatsnew/3.13.rst:2462 msgid "(Contributed by Victor Stinner in :gh:`105182`.)" msgstr "(Contribuição de Victor Stinner em :gh:`105182`.)" -#: ../../whatsnew/3.13.rst:2259 +#: ../../whatsnew/3.13.rst:2464 msgid "" -"Remove private ``_PyObject_FastCall()`` function: use " -"``PyObject_Vectorcall()`` which is available since Python 3.8 (:pep:`590`). " -"(Contributed by Victor Stinner in :gh:`106023`.)" +"Remove the :c:func:`!PyEval_ThreadsInitialized` function, deprecated in " +"Python 3.9. Since Python 3.7, :c:func:`!Py_Initialize` always creates the " +"GIL: calling :c:func:`!PyEval_InitThreads` does nothing and :c:func:`!" +"PyEval_ThreadsInitialized` always returns non-zero. (Contributed by Victor " +"Stinner in :gh:`105182`.)" msgstr "" -"Remove a função privada ``_PyObject_FastCall()``: use " -"``PyObject_Vectorcall()``, a qual está disponível desde Python 3.8 (:pep:" -"`590`). (Contribuição de Victor Stinner em :gh:`106023`.)" +"Remove a função :c:func:`!PyEval_ThreadsInitialized`, descontinuada no " +"Python 3.9. Desde Python 3.7, :c:func:`!Py_Initialize` sempre cria a GIL: " +"chamar :c:func:`!PyEval_InitThreads` não faz nada e :c:func:`!" +"PyEval_ThreadsInitialized` sempre retorna diferente de zero. (Contribuição " +"de Victor Stinner em :gh:`105182`.)" -#: ../../whatsnew/3.13.rst:2264 +#: ../../whatsnew/3.13.rst:2471 msgid "" -"Remove ``cpython/pytime.h`` header file: it only contained private " -"functions. (Contributed by Victor Stinner in :gh:`106316`.)" +"Remove the :c:func:`!_PyInterpreterState_Get` alias to :c:func:" +"`PyInterpreterState_Get()` which was kept for backward compatibility with " +"Python 3.8. The `pythoncapi-compat project`_ can be used to get :c:func:" +"`PyInterpreterState_Get()` on Python 3.8 and older. (Contributed by Victor " +"Stinner in :gh:`106320`.)" msgstr "" -"Remove o arquivo de cabeçalho ``cpython/pytime.h``: ele continha apenas " -"funções privadas. (Contribuição de Victor Stinner em :gh:`106316`.)" +"Remove o apelido :c:func:`!_PyInterpreterState_Get` de :c:func:" +"`PyInterpreterState_Get()` que era mantido para compatibilidade com versões " +"anteriores do Python 3.8. O projeto `pythoncapi-compat`_ pode ser usado " +"para obter :c:func:`PyInterpreterState_Get()` no Python 3.8 e versões " +"anteriores. (Contribuição de Victor Stinner em :gh:`106320`.)" -#: ../../whatsnew/3.13.rst:2267 +#: ../../whatsnew/3.13.rst:2478 msgid "" -"Remove ``_PyInterpreterState_Get()`` alias to :c:func:" -"`PyInterpreterState_Get()` which was kept for backward compatibility with " -"Python 3.8. The `pythoncapi-compat project `__ can be used to get :c:func:`PyInterpreterState_Get()` " -"on Python 3.8 and older. (Contributed by Victor Stinner in :gh:`106320`.)" +"Remove the private :c:func:`!_PyObject_FastCall` function: use :c:func:`!" +"PyObject_Vectorcall` which is available since Python 3.8 (:pep:`590`). " +"(Contributed by Victor Stinner in :gh:`106023`.)" msgstr "" -"Remove o apelido ``_PyInterpreterState_Get()`` de :c:func:" -"`PyInterpreterState_Get()` que era mantido para compatibilidade com versões " -"anteriores do Python 3.8. O projeto `pythoncapi-compat `__ pode ser usado para obter :c:func:" -"`PyInterpreterState_Get()` no Python 3.8 e versões anteriores. (Contribuição " -"de Victor Stinner em :gh:`106320`.)" +"Remove a função privada :c:func:`!_PyObject_FastCall`: use :c:func:`!" +"PyObject_Vectorcall`, a qual está disponível desde Python 3.8 (:pep:`590`). " +"(Contribuição de Victor Stinner em :gh:`106023`.)" -#: ../../whatsnew/3.13.rst:2274 +#: ../../whatsnew/3.13.rst:2483 msgid "" -"The :c:func:`PyModule_AddObject` function is now :term:`soft deprecated`: :c:" -"func:`PyModule_Add` or :c:func:`PyModule_AddObjectRef` functions should be " -"used instead. (Contributed by Serhiy Storchaka in :gh:`86493`.)" +"Remove the ``cpython/pytime.h`` header file, which only contained private " +"functions. (Contributed by Victor Stinner in :gh:`106316`.)" msgstr "" -"A função :c:func:`PyModule_AddObject` agora está :term:`suavemente " -"descontinuado`: funções :c:func:`PyModule_Add` ou :c:func:" -"`PyModule_AddObjectRef` devem ser usadas em seu lugar. (Contribuição de " -"Serhiy Storchaka em :gh:`86493`.)" +"Remove o arquivo de cabeçalho ``cpython/pytime.h``, que continha apenas " +"funções privadas. (Contribuição de Victor Stinner em :gh:`106316`.)" -#: ../../whatsnew/3.13.rst:2279 +#: ../../whatsnew/3.13.rst:2487 msgid "" -"Remove undocumented ``PY_TIMEOUT_MAX`` constant from the limited C API. " +"Remove the undocumented ``PY_TIMEOUT_MAX`` constant from the limited C API. " "(Contributed by Victor Stinner in :gh:`110014`.)" msgstr "" -"Remove a constante ``PY_TIMEOUT_MAX`` ​​não documentada da API C limitada. " +"Remove a constante não documentada ``PY_TIMEOUT_MAX`` da API C limitada. " "(Contribuição de Victor Stinner em :gh:`110014`.)" -#: ../../whatsnew/3.13.rst:2283 -msgid "Deprecated C APIs" -msgstr "APIs C descontinuadas" - -#: ../../whatsnew/3.13.rst:2285 +#: ../../whatsnew/3.13.rst:2490 msgid "" -"Deprecate the old ``Py_UNICODE`` and ``PY_UNICODE_TYPE`` types: use directly " -"the :c:type:`wchar_t` type instead. Since Python 3.3, ``Py_UNICODE`` and " -"``PY_UNICODE_TYPE`` are just aliases to :c:type:`wchar_t`. (Contributed by " -"Victor Stinner in :gh:`105156`.)" +"Remove the old trashcan macros ``Py_TRASHCAN_SAFE_BEGIN`` and " +"``Py_TRASHCAN_SAFE_END``. Replace both with the new macros " +"``Py_TRASHCAN_BEGIN`` and ``Py_TRASHCAN_END``. (Contributed by Irit Katriel " +"in :gh:`105111`.)" msgstr "" -"Descontinua os antigos tipos ``Py_UNICODE`` e ``PY_UNICODE_TYPE``: use " -"diretamente o tipo :c:type:`wchar_t`. Desde o Python 3.3, ``Py_UNICODE`` e " -"``PY_UNICODE_TYPE`` são apenas apelidos para :c:type:`wchar_t`. " -"(Contribuição de Victor Stinner em :gh:`105156`.)" +"Remove as antigas macros de trashcan ``Py_TRASHCAN_SAFE_BEGIN`` e " +"``Py_TRASHCAN_SAFE_END``. Substitua ambas pelas novas macros " +"``Py_TRASHCAN_BEGIN`` e ``Py_TRASHCAN_END``. (Contribuição de Irit Katriel " +"em :gh:`105111`.)" -#: ../../whatsnew/3.13.rst:2290 +#: ../../whatsnew/3.13.rst:2497 +msgid "Deprecated C APIs" +msgstr "APIs C descontinuadas" + +#: ../../whatsnew/3.13.rst:2499 msgid "Deprecate old Python initialization functions:" -msgstr "Descontinua antigas funções de inicialização do Python" +msgstr "Descontinua antigas funções de inicialização do Python:" -#: ../../whatsnew/3.13.rst:2292 -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:12 +#: ../../whatsnew/3.13.rst:2501 +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:13 msgid "" -":c:func:`PySys_ResetWarnOptions`: clear :data:`sys.warnoptions` and :data:`!" +":c:func:`PySys_ResetWarnOptions`: Clear :data:`sys.warnoptions` and :data:`!" "warnings.filters` instead." msgstr "" ":c:func:`PySys_ResetWarnOptions`: apague :data:`sys.warnoptions` e :data:`!" "warnings.filters`." -#: ../../whatsnew/3.13.rst:2294 -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:14 -msgid ":c:func:`Py_GetExecPrefix`: get :data:`sys.exec_prefix` instead." -msgstr ":c:func:`Py_GetExecPrefix`: obtenha :data:`sys.exec_prefix`." +#: ../../whatsnew/3.13.rst:2503 +msgid ":c:func:`Py_GetExecPrefix`: Get :data:`sys.exec_prefix` instead." +msgstr ":c:func:`Py_GetExecPrefix`: leia :data:`sys.exec_prefix`." -#: ../../whatsnew/3.13.rst:2295 -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:15 -msgid ":c:func:`Py_GetPath`: get :data:`sys.path` instead." -msgstr ":c:func:`Py_GetPath`: obtenha :data:`sys.path`." +#: ../../whatsnew/3.13.rst:2505 +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:17 +msgid ":c:func:`Py_GetPath`: Get :data:`sys.path` instead." +msgstr ":c:func:`Py_GetPath`: leia :data:`sys.path`." -#: ../../whatsnew/3.13.rst:2296 -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:16 -msgid ":c:func:`Py_GetPrefix`: get :data:`sys.prefix` instead." -msgstr ":c:func:`Py_GetPrefix`: obtenha :data:`sys.prefix`." +#: ../../whatsnew/3.13.rst:2507 +msgid ":c:func:`Py_GetPrefix`: Get :data:`sys.prefix` instead." +msgstr ":c:func:`Py_GetPrefix`: leia :data:`sys.prefix`." -#: ../../whatsnew/3.13.rst:2297 -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:17 -msgid ":c:func:`Py_GetProgramFullPath`: get :data:`sys.executable` instead." -msgstr ":c:func:`Py_GetProgramFullPath`: obtenha :data:`sys.executable`." +#: ../../whatsnew/3.13.rst:2509 +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:21 +msgid ":c:func:`Py_GetProgramFullPath`: Get :data:`sys.executable` instead." +msgstr ":c:func:`Py_GetProgramFullPath`: leia :data:`sys.executable`." -#: ../../whatsnew/3.13.rst:2298 -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:18 -msgid ":c:func:`Py_GetProgramName`: get :data:`sys.executable` instead." -msgstr ":c:func:`Py_GetProgramName`: obtenha :data:`sys.executable`." +#: ../../whatsnew/3.13.rst:2511 +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:23 +msgid ":c:func:`Py_GetProgramName`: Get :data:`sys.executable` instead." +msgstr ":c:func:`Py_GetProgramName`: leia :data:`sys.executable`." -#: ../../whatsnew/3.13.rst:2299 +#: ../../whatsnew/3.13.rst:2513 +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:25 msgid "" -":c:func:`Py_GetPythonHome`: get :c:member:`PyConfig.home` or :envvar:" +":c:func:`Py_GetPythonHome`: Get :c:member:`PyConfig.home` or the :envvar:" "`PYTHONHOME` environment variable instead." msgstr "" -":c:func:`Py_GetPythonHome`: obtenha :c:member:`PyConfig.home` ou a variável " -"de ambiente :envvar:`PYTHONHOME`." +":c:func:`Py_GetPythonHome`: leia :c:member:`PyConfig.home` ou a variável de " +"ambiente :envvar:`PYTHONHOME`." -#: ../../whatsnew/3.13.rst:2302 +#: ../../whatsnew/3.13.rst:2517 +msgid "(Contributed by Victor Stinner in :gh:`105145`.)" +msgstr "(Contribuição de Victor Stinner em :gh:`105145`.)" + +#: ../../whatsnew/3.13.rst:2519 msgid "" -"Functions scheduled for removal in Python 3.15. (Contributed by Victor " -"Stinner in :gh:`105145`.)" +":term:`Soft deprecate ` the :c:func:`PyEval_GetBuiltins`, :" +"c:func:`PyEval_GetGlobals`, and :c:func:`PyEval_GetLocals` functions, which " +"return a :term:`borrowed reference`. (Soft deprecated as part of :pep:`667`.)" msgstr "" -"Funções agendadas para remoção no Python 3.15. (Contribuição de Victor " -"Stinner em :gh:`105145`.)" +":term:`Descontinua suavemente ` as funções :c:func:" +"`PyEval_GetBuiltins`, :c:func:`PyEval_GetGlobals` e :c:func:" +"`PyEval_GetLocals`, que retornam uma :term:`referência emprestada`. " +"(Suavemente descontinuadas como parte da :pep:`667`.)" -#: ../../whatsnew/3.13.rst:2305 +#: ../../whatsnew/3.13.rst:2525 msgid "" -"Deprecate the :c:func:`PyImport_ImportModuleNoBlock` function which is just " -"an alias to :c:func:`PyImport_ImportModule` since Python 3.3. Scheduled for " -"removal in Python 3.15. (Contributed by Victor Stinner in :gh:`105396`.)" +"Deprecate the :c:func:`PyImport_ImportModuleNoBlock` function, which is just " +"an alias to :c:func:`PyImport_ImportModule` since Python 3.3. (Contributed " +"by Victor Stinner in :gh:`105396`.)" msgstr "" "Descontinua a função :c:func:`PyImport_ImportModuleNoBlock` que é apenas um " -"apelido para :c:func:`PyImport_ImportModule` desde o Python 3.3. Programado " -"para remoção no Python 3.15. (Contribuição de Victor Stinner em :gh:" -"`105396`.)" +"apelido para :c:func:`PyImport_ImportModule` desde o Python 3.3. " +"(Contribuição de Victor Stinner em :gh:`105396`.)" -#: ../../whatsnew/3.13.rst:2310 +#: ../../whatsnew/3.13.rst:2529 msgid "" -"Deprecate the :c:func:`PyWeakref_GetObject` and :c:func:" -"`PyWeakref_GET_OBJECT` functions, which return a :term:`borrowed reference`: " -"use the new :c:func:`PyWeakref_GetRef` function instead, it returns a :term:" -"`strong reference`. The `pythoncapi-compat project `__ can be used to get :c:func:`PyWeakref_GetRef` " -"on Python 3.12 and older. (Contributed by Victor Stinner in :gh:`105927`.)" +":term:`Soft deprecate ` the :c:func:`PyModule_AddObject` " +"function. It should be replaced with :c:func:`PyModule_Add` or :c:func:" +"`PyModule_AddObjectRef`. (Contributed by Serhiy Storchaka in :gh:`86493`.)" msgstr "" -"Descontinua as funções :c:func:`PyWeakref_GetObject` e :c:func:" -"`PyWeakref_GET_OBJECT`, que retornam uma :term:`referência emprestada`: use " -"a nova função :c:func:`PyWeakref_GetRef` em vez disso, ela retorna uma :term:" -"`referência forte`. O projeto `pythoncapi-compat `__ pode ser usado para obter :c:func:`PyWeakref_GetRef` " -"no Python 3.12 e versões anteriores. (Contribuição de Victor Stinner em :gh:" -"`105927`.)" +":term:`Descontinua suavemente ` a função :c:func:" +"`PyModule_AddObject`. Ela deve ser substituída por :c:func:`PyModule_Add` " +"ou :c:func:`PyModule_AddObjectRef`. (Contribuição de Serhiy Storchaka em :gh:" +"`86493`.)" -#: ../../whatsnew/3.13.rst:2318 +#: ../../whatsnew/3.13.rst:2535 msgid "" -"Deprecate the :c:func:`PyEval_GetBuiltins`, :c:func:`PyEval_GetGlobals`, " -"and :c:func:`PyEval_GetLocals` functions, which return a :term:`borrowed " -"reference`. Refer to the deprecation notices on each function for their " -"recommended replacements. (Soft deprecated as part of :pep:`667`.)" +"Deprecate the old ``Py_UNICODE`` and ``PY_UNICODE_TYPE`` types and the :c:" +"macro:`!Py_UNICODE_WIDE` define. Use the :c:type:`wchar_t` type directly " +"instead. Since Python 3.3, ``Py_UNICODE`` and ``PY_UNICODE_TYPE`` are just " +"aliases to :c:type:`!wchar_t`. (Contributed by Victor Stinner in :gh:" +"`105156`.)" msgstr "" -"Descontinua as funções :c:func:`PyEval_GetBuiltins`, :c:func:" -"`PyEval_GetGlobals` e :c:func:`PyEval_GetLocals`, que retornam uma :term:" -"`referência emprestada`. Consulte os avisos de descontinuação em cada função " -"para ver as substituições recomendadas. (Suavemente descontinuadas como " -"parte da :pep:`667`.)" +"Descontinua os tipos antigos ``Py_UNICODE`` e ``PY_UNICODE_TYPE`` e define :" +"c:macro:`!Py_UNICODE_WIDE`. Em vez disso, use o tipo :c:type:`wchar_t` " +"diretamente. Desde Python 3.3, ``Py_UNICODE`` e ``PY_UNICODE_TYPE`` são " +"apenas apelidos para :c:type:`!wchar_t`. (Contribuição de Victor Stinner em :" +"gh:`105156`.)" + +#: ../../whatsnew/3.13.rst:2542 +msgid "" +"Deprecate the :c:func:`PyWeakref_GetObject` and :c:func:" +"`PyWeakref_GET_OBJECT` functions, which return a :term:`borrowed reference`. " +"Replace them with the new :c:func:`PyWeakref_GetRef` function, which returns " +"a :term:`strong reference`. The `pythoncapi-compat project`_ can be used to " +"get :c:func:`PyWeakref_GetRef` on Python 3.12 and older. (Contributed by " +"Victor Stinner in :gh:`105927`.)" +msgstr "" +"Descontinua as funções :c:func:`PyWeakref_GetObject` e :c:func:" +"`PyWeakref_GET_OBJECT`, que retornam uma :term:`referência emprestada`. Em " +"vez disso, use a nova função :c:func:`PyWeakref_GetRef`, que retorna uma :" +"term:`referência forte`. O `projeto pythoncapi-compat`_ pode ser usado para " +"obter :c:func:`PyWeakref_GetRef` no Python 3.12 e versões anteriores. " +"(Contribuição de Victor Stinner em :gh:`105927`.)" #: ../../deprecations/c-api-pending-removal-in-3.14.rst:4 msgid "" @@ -5754,159 +6178,162 @@ msgstr "" "3.11:" #: ../../deprecations/c-api-pending-removal-in-3.14.rst:12 -msgid "``PySys_SetArgvEx()``: set :c:member:`PyConfig.argv` instead." -msgstr "``PySys_SetArgvEx()``: defina :c:member:`PyConfig.argv`." - -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:13 -msgid "``PySys_SetArgv()``: set :c:member:`PyConfig.argv` instead." -msgstr "``PySys_SetArgv()``: defina :c:member:`PyConfig.argv`." +msgid ":c:func:`!PySys_SetArgvEx()`: Set :c:member:`PyConfig.argv` instead." +msgstr ":c:func:`!PySys_SetArgvEx()`: defina :c:member:`PyConfig.argv`." #: ../../deprecations/c-api-pending-removal-in-3.14.rst:14 -msgid "``Py_SetProgramName()``: set :c:member:`PyConfig.program_name` instead." -msgstr "``Py_SetProgramName()``: defina :c:member:`PyConfig.program_name`." +msgid ":c:func:`!PySys_SetArgv()`: Set :c:member:`PyConfig.argv` instead." +msgstr ":c:func:`!PySys_SetArgv()`: defina :c:member:`PyConfig.argv`." + +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:16 +msgid "" +":c:func:`!Py_SetProgramName()`: Set :c:member:`PyConfig.program_name` " +"instead." +msgstr "" +":c:func:`!Py_SetProgramName()`: defina :c:member:`PyConfig.program_name`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:15 -msgid "``Py_SetPythonHome()``: set :c:member:`PyConfig.home` instead." -msgstr "``Py_SetPythonHome()``: defina :c:member:`PyConfig.home`." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:18 +msgid ":c:func:`!Py_SetPythonHome()`: Set :c:member:`PyConfig.home` instead." +msgstr ":c:func:`!Py_SetPythonHome()`: defina :c:member:`PyConfig.home`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:17 -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:45 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:21 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:71 msgid "" "The :c:func:`Py_InitializeFromConfig` API should be used with :c:type:" "`PyConfig` instead." msgstr "" -"A API :c:func:`Py_InitializeFromConfig` deve ser usada com :c:type:" -"`PyConfig`." +"Em vez disso, a API :c:func:`Py_InitializeFromConfig` deve ser usada com :c:" +"type:`PyConfig`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:20 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:24 msgid "Global configuration variables:" msgstr "Variáveis de configuração globais" -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:22 -msgid ":c:var:`Py_DebugFlag`: use :c:member:`PyConfig.parser_debug` instead." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:26 +msgid ":c:var:`Py_DebugFlag`: Use :c:member:`PyConfig.parser_debug` instead." msgstr ":c:var:`Py_DebugFlag`: use :c:member:`PyConfig.parser_debug`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:23 -msgid ":c:var:`Py_VerboseFlag`: use :c:member:`PyConfig.verbose` instead." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:28 +msgid ":c:var:`Py_VerboseFlag`: Use :c:member:`PyConfig.verbose` instead." msgstr ":c:var:`Py_VerboseFlag`: use :c:member:`PyConfig.verbose`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:24 -msgid ":c:var:`Py_QuietFlag`: use :c:member:`PyConfig.quiet` instead." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:30 +msgid ":c:var:`Py_QuietFlag`: Use :c:member:`PyConfig.quiet` instead." msgstr ":c:var:`Py_QuietFlag`: use :c:member:`PyConfig.quiet`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:25 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:32 msgid "" -":c:var:`Py_InteractiveFlag`: use :c:member:`PyConfig.interactive` instead." +":c:var:`Py_InteractiveFlag`: Use :c:member:`PyConfig.interactive` instead." msgstr ":c:var:`Py_InteractiveFlag`: use :c:member:`PyConfig.interactive`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:26 -msgid ":c:var:`Py_InspectFlag`: use :c:member:`PyConfig.inspect` instead." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:34 +msgid ":c:var:`Py_InspectFlag`: Use :c:member:`PyConfig.inspect` instead." msgstr ":c:var:`Py_InspectFlag`: use :c:member:`PyConfig.inspect`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:27 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:36 msgid "" -":c:var:`Py_OptimizeFlag`: use :c:member:`PyConfig.optimization_level` " +":c:var:`Py_OptimizeFlag`: Use :c:member:`PyConfig.optimization_level` " "instead." msgstr ":c:var:`Py_OptimizeFlag`: use :c:member:`PyConfig.optimization_level`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:28 -msgid ":c:var:`Py_NoSiteFlag`: use :c:member:`PyConfig.site_import` instead." -msgstr ":c:var:`Py_NoSiteFlag`: use :c:member:`PyConfig.site_import` ." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:38 +msgid ":c:var:`Py_NoSiteFlag`: Use :c:member:`PyConfig.site_import` instead." +msgstr ":c:var:`Py_NoSiteFlag`: use :c:member:`PyConfig.site_import`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:29 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:40 msgid "" -":c:var:`Py_BytesWarningFlag`: use :c:member:`PyConfig.bytes_warning` instead." +":c:var:`Py_BytesWarningFlag`: Use :c:member:`PyConfig.bytes_warning` instead." msgstr ":c:var:`Py_BytesWarningFlag`: use :c:member:`PyConfig.bytes_warning`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:30 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:42 msgid "" -":c:var:`Py_FrozenFlag`: use :c:member:`PyConfig.pathconfig_warnings` instead." +":c:var:`Py_FrozenFlag`: Use :c:member:`PyConfig.pathconfig_warnings` instead." msgstr ":c:var:`Py_FrozenFlag`: use :c:member:`PyConfig.pathconfig_warnings`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:31 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:44 msgid "" -":c:var:`Py_IgnoreEnvironmentFlag`: use :c:member:`PyConfig.use_environment` " +":c:var:`Py_IgnoreEnvironmentFlag`: Use :c:member:`PyConfig.use_environment` " "instead." msgstr "" ":c:var:`Py_IgnoreEnvironmentFlag`: use :c:member:`PyConfig.use_environment`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:32 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:46 msgid "" -":c:var:`Py_DontWriteBytecodeFlag`: use :c:member:`PyConfig.write_bytecode` " +":c:var:`Py_DontWriteBytecodeFlag`: Use :c:member:`PyConfig.write_bytecode` " "instead." msgstr "" ":c:var:`Py_DontWriteBytecodeFlag`: use :c:member:`PyConfig.write_bytecode`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:33 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:48 msgid "" -":c:var:`Py_NoUserSiteDirectory`: use :c:member:`PyConfig." +":c:var:`Py_NoUserSiteDirectory`: Use :c:member:`PyConfig." "user_site_directory` instead." msgstr "" ":c:var:`Py_NoUserSiteDirectory`: use :c:member:`PyConfig." "user_site_directory`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:34 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:50 msgid "" -":c:var:`Py_UnbufferedStdioFlag`: use :c:member:`PyConfig.buffered_stdio` " +":c:var:`Py_UnbufferedStdioFlag`: Use :c:member:`PyConfig.buffered_stdio` " "instead." msgstr "" ":c:var:`Py_UnbufferedStdioFlag`: use :c:member:`PyConfig.buffered_stdio`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:35 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:52 msgid "" -":c:var:`Py_HashRandomizationFlag`: use :c:member:`PyConfig.use_hash_seed` " +":c:var:`Py_HashRandomizationFlag`: Use :c:member:`PyConfig.use_hash_seed` " "and :c:member:`PyConfig.hash_seed` instead." msgstr "" ":c:var:`Py_HashRandomizationFlag`: use :c:member:`PyConfig.use_hash_seed` e :" "c:member:`PyConfig.hash_seed`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:37 -msgid ":c:var:`Py_IsolatedFlag`: use :c:member:`PyConfig.isolated` instead." +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:55 +msgid ":c:var:`Py_IsolatedFlag`: Use :c:member:`PyConfig.isolated` instead." msgstr ":c:var:`Py_IsolatedFlag`: use :c:member:`PyConfig.isolated`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:38 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:57 msgid "" -":c:var:`Py_LegacyWindowsFSEncodingFlag`: use :c:member:`PyPreConfig." +":c:var:`Py_LegacyWindowsFSEncodingFlag`: Use :c:member:`PyPreConfig." "legacy_windows_fs_encoding` instead." msgstr "" ":c:var:`Py_LegacyWindowsFSEncodingFlag`: use :c:member:`PyPreConfig." "legacy_windows_fs_encoding`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:39 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:59 msgid "" -":c:var:`Py_LegacyWindowsStdioFlag`: use :c:member:`PyConfig." +":c:var:`Py_LegacyWindowsStdioFlag`: Use :c:member:`PyConfig." "legacy_windows_stdio` instead." msgstr "" ":c:var:`Py_LegacyWindowsStdioFlag`: use :c:member:`PyConfig." "legacy_windows_stdio`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:40 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:61 msgid "" -":c:var:`!Py_FileSystemDefaultEncoding`: use :c:member:`PyConfig." +":c:var:`!Py_FileSystemDefaultEncoding`: Use :c:member:`PyConfig." "filesystem_encoding` instead." msgstr "" ":c:var:`!Py_FileSystemDefaultEncoding`: use :c:member:`PyConfig." "filesystem_encoding`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:41 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:63 msgid "" -":c:var:`!Py_HasFileSystemDefaultEncoding`: use :c:member:`PyConfig." +":c:var:`!Py_HasFileSystemDefaultEncoding`: Use :c:member:`PyConfig." "filesystem_encoding` instead." msgstr "" ":c:var:`!Py_HasFileSystemDefaultEncoding`: use :c:member:`PyConfig." "filesystem_encoding`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:42 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:65 msgid "" -":c:var:`!Py_FileSystemDefaultEncodeErrors`: use :c:member:`PyConfig." +":c:var:`!Py_FileSystemDefaultEncodeErrors`: Use :c:member:`PyConfig." "filesystem_errors` instead." msgstr "" ":c:var:`!Py_FileSystemDefaultEncodeErrors`: use :c:member:`PyConfig." "filesystem_errors`." -#: ../../deprecations/c-api-pending-removal-in-3.14.rst:43 +#: ../../deprecations/c-api-pending-removal-in-3.14.rst:67 msgid "" -":c:var:`!Py_UTF8Mode`: use :c:member:`PyPreConfig.utf8_mode` instead. (see :" +":c:var:`!Py_UTF8Mode`: Use :c:member:`PyPreConfig.utf8_mode` instead. (see :" "c:func:`Py_PreInitialize`)" msgstr "" ":c:var:`!Py_UTF8Mode`: use :c:member:`PyPreConfig.utf8_mode`. (veja :c:func:" @@ -5918,169 +6345,777 @@ msgstr "A cópia empacotada do ``libmpdecimal``." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:5 msgid "" -":c:func:`PyImport_ImportModuleNoBlock`: use :c:func:`PyImport_ImportModule` " -"instead." +"The :c:func:`PyImport_ImportModuleNoBlock`: Use :c:func:" +"`PyImport_ImportModule` instead." msgstr "" -":c:func:`PyImport_ImportModuleNoBlock`: use :c:func:`PyImport_ImportModule`." - -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:6 -msgid ":c:func:`PyWeakref_GET_OBJECT`: use :c:func:`PyWeakref_GetRef` instead." -msgstr ":c:func:`PyWeakref_GET_OBJECT`: use :c:func:`PyWeakref_GetRef`." +"The :c:func:`PyImport_ImportModuleNoBlock`: use :c:func:" +"`PyImport_ImportModule`." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:7 -msgid ":c:func:`PyWeakref_GetObject`: use :c:func:`PyWeakref_GetRef` instead." -msgstr ":c:func:`PyWeakref_GetObject`: use :c:func:`PyWeakref_GetRef`." - -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:8 -msgid ":c:type:`!Py_UNICODE_WIDE` type: use :c:type:`wchar_t` instead." -msgstr "O tipo :c:type:`!Py_UNICODE_WIDE`: use :c:type:`wchar_t`." +msgid "" +":c:func:`PyWeakref_GetObject` and :c:func:`PyWeakref_GET_OBJECT`: Use :c:" +"func:`PyWeakref_GetRef` instead." +msgstr "" +":c:func:`PyWeakref_GetObject` e :c:func:`PyWeakref_GET_OBJECT`: use :c:func:" +"`PyWeakref_GetRef`." #: ../../deprecations/c-api-pending-removal-in-3.15.rst:9 -msgid ":c:type:`Py_UNICODE` type: use :c:type:`wchar_t` instead." -msgstr "O tipo :c:type:`Py_UNICODE`: use :c:type:`wchar_t`." +msgid "" +":c:type:`Py_UNICODE` type and the :c:macro:`!Py_UNICODE_WIDE` macro: Use :c:" +"type:`wchar_t` instead." +msgstr "" +"O tipo :c:type:`Py_UNICODE` e a macro :c:macro:`!Py_UNICODE_WIDE`: use :c:" +"type:`wchar_t`." -#: ../../deprecations/c-api-pending-removal-in-3.15.rst:10 +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:11 msgid "Python initialization functions:" msgstr "Funções de inicialização do Python" +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:15 +msgid "" +":c:func:`Py_GetExecPrefix`: Get :data:`sys.base_exec_prefix` and :data:`sys." +"exec_prefix` instead." +msgstr "" +":c:func:`Py_GetExecPrefix`: obtenha :data:`sys.base_exec_prefix` e :data:" +"`sys.exec_prefix`." + #: ../../deprecations/c-api-pending-removal-in-3.15.rst:19 msgid "" -":c:func:`Py_GetPythonHome`: get :c:member:`PyConfig.home` or the :envvar:" -"`PYTHONHOME` environment variable instead." +":c:func:`Py_GetPrefix`: Get :data:`sys.base_prefix` and :data:`sys.prefix` " +"instead." msgstr "" -":c:func:`Py_GetPythonHome`: obtenha :c:member:`PyConfig.home` ou a variável " -"de ambiente :envvar:`PYTHONHOME`." +":c:func:`Py_GetPrefix`: obtenha :data:`sys.base_prefix` e :data:`sys.prefix`." #: ../../deprecations/c-api-pending-removal-in-future.rst:4 msgid "" "The following APIs are deprecated and will be removed, although there is " "currently no date scheduled for their removal." msgstr "" -"As APIs a seguir foram descontinuado e serão removidas, embora atualmente " +"As APIs a seguir foram descontinuadas e serão removidas, embora atualmente " "não haja uma data agendada para sua remoção." #: ../../deprecations/c-api-pending-removal-in-future.rst:7 -msgid ":c:macro:`Py_TPFLAGS_HAVE_FINALIZE`: unneeded since Python 3.8." +msgid ":c:macro:`Py_TPFLAGS_HAVE_FINALIZE`: Unneeded since Python 3.8." msgstr ":c:macro:`Py_TPFLAGS_HAVE_FINALIZE`: desnecessária desde o Python 3.8." -#: ../../deprecations/c-api-pending-removal-in-future.rst:8 -msgid ":c:func:`PyErr_Fetch`: use :c:func:`PyErr_GetRaisedException` instead." +#: ../../deprecations/c-api-pending-removal-in-future.rst:9 +msgid ":c:func:`PyErr_Fetch`: Use :c:func:`PyErr_GetRaisedException` instead." msgstr ":c:func:`PyErr_Fetch`: use :c:func:`PyErr_GetRaisedException`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:9 +#: ../../deprecations/c-api-pending-removal-in-future.rst:11 msgid "" -":c:func:`PyErr_NormalizeException`: use :c:func:`PyErr_GetRaisedException` " +":c:func:`PyErr_NormalizeException`: Use :c:func:`PyErr_GetRaisedException` " "instead." msgstr "" ":c:func:`PyErr_NormalizeException`: use :c:func:`PyErr_GetRaisedException`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:10 +#: ../../deprecations/c-api-pending-removal-in-future.rst:13 msgid "" -":c:func:`PyErr_Restore`: use :c:func:`PyErr_SetRaisedException` instead." +":c:func:`PyErr_Restore`: Use :c:func:`PyErr_SetRaisedException` instead." msgstr ":c:func:`PyErr_Restore`: use :c:func:`PyErr_SetRaisedException`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:11 +#: ../../deprecations/c-api-pending-removal-in-future.rst:15 msgid "" -":c:func:`PyModule_GetFilename`: use :c:func:`PyModule_GetFilenameObject` " +":c:func:`PyModule_GetFilename`: Use :c:func:`PyModule_GetFilenameObject` " "instead." msgstr "" ":c:func:`PyModule_GetFilename`: use :c:func:`PyModule_GetFilenameObject`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:12 -msgid ":c:func:`PyOS_AfterFork`: use :c:func:`PyOS_AfterFork_Child` instead." -msgstr ":c:func:`PyOS_AfterFork`: use :c:func:`PyOS_AfterFork_Child`" +#: ../../deprecations/c-api-pending-removal-in-future.rst:17 +msgid ":c:func:`PyOS_AfterFork`: Use :c:func:`PyOS_AfterFork_Child` instead." +msgstr ":c:func:`PyOS_AfterFork`: use :c:func:`PyOS_AfterFork_Child`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:13 +#: ../../deprecations/c-api-pending-removal-in-future.rst:19 msgid "" -":c:func:`PySlice_GetIndicesEx`: use :c:func:`PySlice_Unpack` and :c:func:" +":c:func:`PySlice_GetIndicesEx`: Use :c:func:`PySlice_Unpack` and :c:func:" "`PySlice_AdjustIndices` instead." msgstr "" ":c:func:`PySlice_GetIndicesEx`: use :c:func:`PySlice_Unpack` e :c:func:" "`PySlice_AdjustIndices`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:14 +#: ../../deprecations/c-api-pending-removal-in-future.rst:21 msgid "" -":c:func:`!PyUnicode_AsDecodedObject`: use :c:func:`PyCodec_Decode` instead." +":c:func:`!PyUnicode_AsDecodedObject`: Use :c:func:`PyCodec_Decode` instead." msgstr ":c:func:`!PyUnicode_AsDecodedObject`: use :c:func:`PyCodec_Decode`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:15 +#: ../../deprecations/c-api-pending-removal-in-future.rst:23 msgid "" -":c:func:`!PyUnicode_AsDecodedUnicode`: use :c:func:`PyCodec_Decode` instead." +":c:func:`!PyUnicode_AsDecodedUnicode`: Use :c:func:`PyCodec_Decode` instead." msgstr ":c:func:`!PyUnicode_AsDecodedUnicode`: use :c:func:`PyCodec_Decode`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:16 +#: ../../deprecations/c-api-pending-removal-in-future.rst:25 msgid "" -":c:func:`!PyUnicode_AsEncodedObject`: use :c:func:`PyCodec_Encode` instead." +":c:func:`!PyUnicode_AsEncodedObject`: Use :c:func:`PyCodec_Encode` instead." msgstr ":c:func:`!PyUnicode_AsEncodedObject`: use :c:func:`PyCodec_Encode`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:17 +#: ../../deprecations/c-api-pending-removal-in-future.rst:27 msgid "" -":c:func:`!PyUnicode_AsEncodedUnicode`: use :c:func:`PyCodec_Encode` instead." +":c:func:`!PyUnicode_AsEncodedUnicode`: Use :c:func:`PyCodec_Encode` instead." msgstr ":c:func:`!PyUnicode_AsEncodedUnicode`: use :c:func:`PyCodec_Encode`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:18 -msgid ":c:func:`PyUnicode_READY`: unneeded since Python 3.12" +#: ../../deprecations/c-api-pending-removal-in-future.rst:29 +msgid ":c:func:`PyUnicode_READY`: Unneeded since Python 3.12" msgstr ":c:func:`PyUnicode_READY`: desnecessário desde o Python 3.12" -#: ../../deprecations/c-api-pending-removal-in-future.rst:19 -msgid ":c:func:`!PyErr_Display`: use :c:func:`PyErr_DisplayException` instead." +#: ../../deprecations/c-api-pending-removal-in-future.rst:31 +msgid ":c:func:`!PyErr_Display`: Use :c:func:`PyErr_DisplayException` instead." msgstr ":c:func:`!PyErr_Display`: use :c:func:`PyErr_DisplayException`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:20 +#: ../../deprecations/c-api-pending-removal-in-future.rst:33 msgid "" -":c:func:`!_PyErr_ChainExceptions`: use ``_PyErr_ChainExceptions1`` instead." -msgstr ":c:func:`!_PyErr_ChainExceptions`: use ``_PyErr_ChainExceptions1``." +":c:func:`!_PyErr_ChainExceptions`: Use :c:func:`!_PyErr_ChainExceptions1` " +"instead." +msgstr "" +":c:func:`!_PyErr_ChainExceptions`: use :c:func:`!_PyErr_ChainExceptions1`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:21 +#: ../../deprecations/c-api-pending-removal-in-future.rst:35 msgid "" ":c:member:`!PyBytesObject.ob_shash` member: call :c:func:`PyObject_Hash` " "instead." msgstr "" "O membro :c:member:`!PyBytesObject.ob_shash`: chame :c:func:`PyObject_Hash`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:23 +#: ../../deprecations/c-api-pending-removal-in-future.rst:37 msgid ":c:member:`!PyDictObject.ma_version_tag` member." msgstr "O membro :c:member:`!PyDictObject.ma_version_tag`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:24 +#: ../../deprecations/c-api-pending-removal-in-future.rst:38 msgid "Thread Local Storage (TLS) API:" msgstr "API do Thread Local Storage (TLS):" -#: ../../deprecations/c-api-pending-removal-in-future.rst:26 +#: ../../deprecations/c-api-pending-removal-in-future.rst:40 msgid "" -":c:func:`PyThread_create_key`: use :c:func:`PyThread_tss_alloc` instead." +":c:func:`PyThread_create_key`: Use :c:func:`PyThread_tss_alloc` instead." msgstr ":c:func:`PyThread_create_key`: use :c:func:`PyThread_tss_alloc`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:27 -msgid ":c:func:`PyThread_delete_key`: use :c:func:`PyThread_tss_free` instead." +#: ../../deprecations/c-api-pending-removal-in-future.rst:42 +msgid ":c:func:`PyThread_delete_key`: Use :c:func:`PyThread_tss_free` instead." msgstr ":c:func:`PyThread_delete_key`: use :c:func:`PyThread_tss_free`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:28 +#: ../../deprecations/c-api-pending-removal-in-future.rst:44 msgid "" -":c:func:`PyThread_set_key_value`: use :c:func:`PyThread_tss_set` instead." +":c:func:`PyThread_set_key_value`: Use :c:func:`PyThread_tss_set` instead." msgstr ":c:func:`PyThread_set_key_value`: use :c:func:`PyThread_tss_set`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:29 +#: ../../deprecations/c-api-pending-removal-in-future.rst:46 msgid "" -":c:func:`PyThread_get_key_value`: use :c:func:`PyThread_tss_get` instead." +":c:func:`PyThread_get_key_value`: Use :c:func:`PyThread_tss_get` instead." msgstr ":c:func:`PyThread_get_key_value`: use :c:func:`PyThread_tss_get`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:30 +#: ../../deprecations/c-api-pending-removal-in-future.rst:48 msgid "" -":c:func:`PyThread_delete_key_value`: use :c:func:`PyThread_tss_delete` " +":c:func:`PyThread_delete_key_value`: Use :c:func:`PyThread_tss_delete` " "instead." msgstr "" ":c:func:`PyThread_delete_key_value`: use :c:func:`PyThread_tss_delete`." -#: ../../deprecations/c-api-pending-removal-in-future.rst:31 -msgid ":c:func:`PyThread_ReInitTLS`: unneeded since Python 3.7." +#: ../../deprecations/c-api-pending-removal-in-future.rst:50 +msgid ":c:func:`PyThread_ReInitTLS`: Unneeded since Python 3.7." msgstr ":c:func:`PyThread_ReInitTLS`: desnecessário desde o Python 3.7." -#: ../../whatsnew/3.13.rst:2332 +#: ../../whatsnew/3.13.rst:2562 +msgid "Build Changes" +msgstr "Mudanças na construção" + +#: ../../whatsnew/3.13.rst:2564 +msgid "" +"``arm64-apple-ios`` and ``arm64-apple-ios-simulator`` are both now :pep:`11` " +"tier 3 platforms. (:ref:`PEP 730 ` written and " +"implementation contributed by Russell Keith-Magee in :gh:`114099`.)" +msgstr "" +"``arm64-apple-ios`` e ``arm64-apple-ios-simulator`` são agora plataformas de " +"nível 3 da :pep:`11`. (Escrita e implementação da :ref:`PEP 730 ` foi uma contribuição de Russell Keith-Magee em :gh:" +"`114099`.)" + +#: ../../whatsnew/3.13.rst:2569 +msgid "" +"``aarch64-linux-android`` and ``x86_64-linux-android`` are both now :pep:" +"`11` tier 3 platforms. (:ref:`PEP 738 ` " +"written and implementation contributed by Malcolm Smith in :gh:`116622`.)" +msgstr "" +"``aarch64-linux-android`` e ``x86_64-linux-android`` são agora plataformas " +"de nível 3 da :pep:`11`. (Escrita e implementação da :ref:`PEP 738 " +"` foi uma contribuição de Malcolm Smith em :gh:" +"`116622`.)" + +#: ../../whatsnew/3.13.rst:2574 +msgid "" +"``wasm32-wasi`` is now a :pep:`11` tier 2 platform. (Contributed by Brett " +"Cannon in :gh:`115192`.)" +msgstr "" +"``wasm32-wasi`` agora é uma plataforma de nível 2 segundo a :pep:`11`. " +"(Contribuição de Brett Cannon em :gh:`115192`.)" + +#: ../../whatsnew/3.13.rst:2577 +msgid "" +"``wasm32-emscripten`` is no longer a :pep:`11` supported platform. " +"(Contributed by Brett Cannon in :gh:`115192`.)" +msgstr "" +"``wasm32-emscripten`` não é mais uma plataforma suportada pela :pep:`11`. " +"(Contribuição de Brett Cannon em :gh:`115192`.)" + +#: ../../whatsnew/3.13.rst:2580 +msgid "" +"Building CPython now requires a compiler with support for the C11 atomic " +"library, GCC built-in atomic functions, or MSVC interlocked intrinsics." +msgstr "" +"Construir CPython agora requer um compilador com suporte para a biblioteca " +"atômica C11, funções atômicas embutidas do GCC ou intrínsecos interligados " +"MSVC." + +#: ../../whatsnew/3.13.rst:2583 +msgid "" +"Autoconf 2.71 and aclocal 1.16.5 are now required to regenerate the :file:" +"`configure` script. (Contributed by Christian Heimes in :gh:`89886` and by " +"Victor Stinner in :gh:`112090`.)" +msgstr "" +"Autoconf 2.71 e aclocal 1.16.5 agora são necessários para regerar o script :" +"file:`configure`. (Contribuição de Christian Heimes em :gh:`89886` e de " +"Victor Stinner em :gh:`112090`.)" + +#: ../../whatsnew/3.13.rst:2587 +msgid "" +"SQLite 3.15.2 or newer is required to build the :mod:`sqlite3` extension " +"module. (Contributed by Erlend Aasland in :gh:`105875`.)" +msgstr "" +"SQLite 3.15.2 ou mais recente é necessário para construir o módulo de " +"extensão :mod:`sqlite3`. (Contribuição de Erlend Aasland em :gh:`105875`.)" + +#: ../../whatsnew/3.13.rst:2591 +msgid "" +"CPython now bundles the `mimalloc library`_ by default. It is licensed under " +"the MIT license; see :ref:`mimalloc license `. The bundled " +"mimalloc has custom changes, see :gh:`113141` for details. (Contributed by " +"Dino Viehland in :gh:`109914`.)" +msgstr "" +"CPython agora inclui a `biblioteca mimalloc`_ por padrão. Está licenciada " +"sob a licença do MIT; veja :ref:`licença do mimalloc `. O " +"mimalloc incluído tem alterações personalizadas, veja :gh:`113141` para " +"detalhes. (Contribuição de Dino Viehland em :gh:`109914`.)" + +#: ../../whatsnew/3.13.rst:2599 +msgid "" +"The :file:`configure` option :option:`--with-system-libmpdec` now defaults " +"to ``yes``. The bundled copy of ``libmpdecimal`` will be removed in Python " +"3.15." +msgstr "" +"A opção :option:`--with-system-libmpdec` do :file:`configure` agora tem como " +"padrão ``yes``. A cópia empacotada de ``libmpdecimal`` será removida no " +"Python 3.15." + +#: ../../whatsnew/3.13.rst:2603 +msgid "" +"Python built with :file:`configure` :option:`--with-trace-refs` (tracing " +"references) is now ABI compatible with the Python release build and :ref:" +"`debug build `. (Contributed by Victor Stinner in :gh:`108634`.)" +msgstr "" +"Python construído com :option:`--with-trace-refs` (referências de " +"rastreamento) do :file:`configure` tem compatibilidade de ABI com a " +"construção de lançamento do Python e a :ref:`construção de depuração `. (Contribuição de Victor Stinner em :gh:`108634`.)" + +#: ../../whatsnew/3.13.rst:2608 +msgid "" +"On POSIX systems, the pkg-config (``.pc``) filenames now include the ABI " +"flags. For example, the free-threaded build generates ``python-3.13t.pc`` " +"and the debug build generates ``python-3.13d.pc``." +msgstr "" +"Em sistemas POSIX, os nomes de arquivos pkg-config (``.pc``) agora incluem " +"os sinalizadores de ABI. Por exemplo, a construção com threads livres gera " +"``python-3.13t.pc`` e a construção de depuração gera ``python-3.13d.pc``." + +#: ../../whatsnew/3.13.rst:2612 +msgid "" +"The ``errno``, ``fcntl``, ``grp``, ``md5``, ``pwd``, ``resource``, " +"``termios``, ``winsound``, ``_ctypes_test``, ``_multiprocessing." +"posixshmem``, ``_scproxy``, ``_stat``, ``_statistics``, ``_testconsole``, " +"``_testimportmultiple`` and ``_uuid`` C extensions are now built with the :" +"ref:`limited C API `. (Contributed by Victor Stinner in :gh:" +"`85283`.)" +msgstr "" +"As extensões C ``errno``, ``fcntl``, ``grp``, ``md5``, ``pwd``, " +"``resource``, ``termios``, ``winsound``, ``_ctypes_test``, " +"``_multiprocessing.posixshmem``, ``_scproxy``, ``_stat``, ``_statistics``, " +"``_testconsole``, ``_testimportmultiple`` e ``_uuid`` são agora construídas " +"com a :ref:`API C limitada `. (Contribuição de Victor Stinner " +"em :gh:`85283`.)" + +#: ../../whatsnew/3.13.rst:2621 +msgid "Porting to Python 3.13" +msgstr "Portando para o Python 3.13" + +#: ../../whatsnew/3.13.rst:2623 +msgid "" +"This section lists previously described changes and other bugfixes that may " +"require changes to your code." +msgstr "" +"Esta seção lista as alterações descritas anteriormente e outras correções " +"que podem exigir alterações no seu código." + +#: ../../whatsnew/3.13.rst:2627 +msgid "Changes in the Python API" +msgstr "Alterações na API Python" + +#: ../../whatsnew/3.13.rst:2631 +msgid "" +":ref:`PEP 667 ` introduces several changes to " +"the semantics of :func:`locals` and :attr:`f_locals `:" +msgstr "" +":ref:`PEP 667 ` introduz várias mudanças na " +"semântica de :func:`locals` e :attr:`f_locals `:" + +#: ../../whatsnew/3.13.rst:2634 +msgid "" +"Calling :func:`locals` in an :term:`optimized scope` now produces an " +"independent snapshot on each call, and hence no longer implicitly updates " +"previously returned references. Obtaining the legacy CPython behavior now " +"requires explicit calls to update the initially returned dictionary with the " +"results of subsequent calls to :func:`!locals`. Code execution functions " +"that implicitly target :func:`!locals` (such as ``exec`` and ``eval``) must " +"be passed an explicit namespace to access their results in an optimized " +"scope. (Changed as part of :pep:`667`.)" +msgstr "" +"Chamar :func:`locals` em um :term:`escopo otimizado` agora produz uma " +"captura independente em cada chamada e, portanto, não atualiza mais " +"implicitamente as referências retornadas anteriormente. Obter o " +"comportamento legado do CPython agora requer chamadas explícitas para " +"atualizar o dicionário inicialmente retornado com os resultados de chamadas " +"subsequentes para :func:`!locals`. Funções de execução de código que visam " +"implicitamente :func:`!locals` (como ``exec`` e ``eval``) devem receber um " +"espaço de nomes explícito para acessar seus resultados em um escopo " +"otimizado. (Alterado como parte da :pep:`667`.)" + +#: ../../whatsnew/3.13.rst:2643 +msgid "" +"Calling :func:`locals` from a comprehension at module or class scope " +"(including via ``exec`` or ``eval``) once more behaves as if the " +"comprehension were running as an independent nested function (i.e. the local " +"variables from the containing scope are not included). In Python 3.12, this " +"had changed to include the local variables from the containing scope when " +"implementing :pep:`709`. (Changed as part of :pep:`667`.)" +msgstr "" +"Chamar :func:`locals` de uma compreensão no módulo ou escopo de classe " +"(inclusive via ``exec`` ou ``eval``) mais uma vez se comporta como se a " +"compreensão estivesse sendo executada como uma função aninhada independente " +"(isto é, as variáveis locais de o escopo que contém não está incluído). No " +"Python 3.12, isso mudou para incluir as variáveis locais do escopo que o " +"contém ao implementar a :pep:`709`. (Alterado como parte da :pep:`667`.)" + +#: ../../whatsnew/3.13.rst:2650 +msgid "" +"Accessing :attr:`FrameType.f_locals ` in an :term:`optimized " +"scope` now returns a write-through proxy rather than a snapshot that gets " +"updated at ill-specified times. If a snapshot is desired, it must be created " +"explicitly with ``dict`` or the proxy's ``.copy()`` method. (Changed as part " +"of :pep:`667`.)" +msgstr "" +"Acessar :attr:`FrameType.f_locals ` em um :term:`escopo " +"otimizado` agora retorna um proxy de \"write-through\" em vez de uma captura " +"que é atualizado em horários mal especificados. Se uma captura for desejada, " +"ela deve ser criada explicitamente com ``dict`` ou com o método ``.copy()`` " +"do proxy. (Alterado como parte da :pep:`667`.)" + +#: ../../whatsnew/3.13.rst:2656 +msgid "" +":class:`functools.partial` now emits a :exc:`FutureWarning` when used as a " +"method. The behavior will change in future Python versions. Wrap it in :func:" +"`staticmethod` if you want to preserve the old behavior. (Contributed by " +"Serhiy Storchaka in :gh:`121027`.)" +msgstr "" +":class:`functools.partial` agora emite uma :exc:`FutureWarning` quando é " +"usado como método. Seu comportamento será alterado em versões futuras do " +"Python. Envolva-a em :func:`staticmethod` se quiser preservar o " +"comportamento antigo. (Contribuição de Serhiy Storchaka em :gh:`121027`.)" + +#: ../../whatsnew/3.13.rst:2662 +msgid "" +"An :exc:`OSError` is now raised by :func:`getpass.getuser` for any failure " +"to retrieve a username, instead of :exc:`ImportError` on non-Unix platforms " +"or :exc:`KeyError` on Unix platforms where the password database is empty." +msgstr "" +"Uma exceção :exc:`OSError` agora é levantada por :func:`getpass.getuser` " +"para qualquer falha na recuperação de um nome de usuário, em vez de :exc:" +"`ImportError` em plataformas não-Unix ou :exc:`KeyError` em plataformas Unix " +"onde o banco de dados de senhas está vazio." + +#: ../../whatsnew/3.13.rst:2667 +msgid "" +"The value of the :attr:`!mode` attribute of :class:`gzip.GzipFile` is now a " +"string (``'rb'`` or ``'wb'``) instead of an integer (``1`` or ``2``). The " +"value of the :attr:`!mode` attribute of the readable file-like object " +"returned by :meth:`zipfile.ZipFile.open` is now ``'rb'`` instead of ``'r'``. " +"(Contributed by Serhiy Storchaka in :gh:`115961`.)" +msgstr "" +"O valor do atributo :attr:`!mode` de :class:`gzip.GzipFile` agora é uma " +"string (``'rb'`` ou ``'wb'``) e não mais um inteiro (``1`` ou ``2``). O " +"valor do atributo :attr:`!mode` do objeto arquivo ou similar legível " +"retornado por :meth:`zipfile.ZipFile.open` é agora ``'rb'`` e não mais " +"``'r'``. (Contribuição de Serhiy Storchaka em :gh:`115961`.)" + +#: ../../whatsnew/3.13.rst:2673 +msgid "" +":class:`mailbox.Maildir` now ignores files with a leading dot (``.``). " +"(Contributed by Zackery Spytz in :gh:`65559`.)" +msgstr "" +":class:`mailbox.Maildir` agora ignora arquivos com um ponto inicial (``.``). " +"(Contribuição de Zackery Spytz em :gh:`65559`.)" + +#: ../../whatsnew/3.13.rst:2676 +msgid "" +":meth:`pathlib.Path.glob` and :meth:`~pathlib.Path.rglob` now return both " +"files and directories if a pattern that ends with \"``**``\" is given, " +"rather than directories only. Add a trailing slash to keep the previous " +"behavior and only match directories." +msgstr "" +":meth:`pathlib.Path.glob` e :meth:`~pathlib.Path.rglob` agora retornam " +"arquivos e diretórios se um padrão que termina com \"``**``\" for fornecido, " +"em vez de apenas diretórios. Os usuários podem adicionar uma barra final " +"para manter o comportamento anterior e corresponder apenas aos diretórios." + +#: ../../whatsnew/3.13.rst:2681 +msgid "" +"The :mod:`threading` module now expects the :mod:`!_thread` module to have " +"an :func:`!_is_main_interpreter` function. This function takes no arguments " +"and returns ``True`` if the current interpreter is the main interpreter." +msgstr "" +"O módulo :mod:`threading` agora espera que o módulo :mod:`!_thread` tenha " +"uma função ``_is_main_interpreter``. É uma função sem argumentos que retorna " +"``True`` se o interpretador atual for o interpretador principal." + +#: ../../whatsnew/3.13.rst:2686 +msgid "" +"Any library or application that provides a custom :mod:`!_thread` module " +"must provide :func:`!_is_main_interpreter`, just like the module's other " +"\"private\" attributes. (:gh:`112826`.)" +msgstr "" +"Qualquer biblioteca ou aplicação que forneça um módulo :mod:`!_thread` " +"personalizado deve obrigatoriamente fornecer :func:`!_is_main_interpreter`, " +"da mesma forma que outros atributos \"privados\" do módulo. (Veja :gh:" +"`112826`.)" + +#: ../../whatsnew/3.13.rst:2693 +msgid "Changes in the C API" +msgstr "Alterações na API C" + +#: ../../whatsnew/3.13.rst:2695 +msgid "" +"``Python.h`` no longer includes the ```` standard header. It was " +"included for the :c:func:`!finite` function which is now provided by the " +"```` header. It should now be included explicitly if needed. Remove " +"also the ``HAVE_IEEEFP_H`` macro. (Contributed by Victor Stinner in :gh:" +"`108765`.)" +msgstr "" +"``Python.h`` não inclui mais o cabeçalho padrão ````. Ele foi " +"incluído para a função :c:func:`!finite` que agora é fornecida pelo " +"cabeçalho ````. Agora deve ser incluído explicitamente, se " +"necessário. Remove também a macro ``HAVE_IEEEFP_H``. (Contribuição de Victor " +"Stinner em :gh:`108765`.)" + +#: ../../whatsnew/3.13.rst:2701 +msgid "" +"``Python.h`` no longer includes these standard header files: ````, " +"```` and ````. If needed, they should now be " +"included explicitly. For example, ```` provides the :c:func:`!clock` " +"and :c:func:`!gmtime` functions, ```` provides the :c:func:`!" +"select` function, and ```` provides the :c:func:`!futimes`, :c:" +"func:`!gettimeofday` and :c:func:`!setitimer` functions. (Contributed by " +"Victor Stinner in :gh:`108765`.)" +msgstr "" +"``Python.h`` não inclui mais estes arquivos de cabeçalho padrão: ````, ```` e ````. Se necessário, deverão agora " +"ser incluídos explicitamente. Por exemplo, ```` fornece as funções :" +"c:func:`!clock` e :c:func:`!gmtime`, ```` fornece o :c:func:`!" +"select`, e ```` fornece as funções :c:func:`!futimes`, :c:func:`!" +"gettimeofday` e :c:func:`!setitimer`. (Contribuição de Victor Stinner em :gh:" +"`108765`.)" + +#: ../../whatsnew/3.13.rst:2709 +msgid "" +"On Windows, ``Python.h`` no longer includes the ```` standard " +"header file. If needed, it should now be included explicitly. For example, " +"it provides :c:func:`!offsetof` function, and ``size_t`` and ``ptrdiff_t`` " +"types. Including ```` explicitly was already needed by all other " +"platforms, the ``HAVE_STDDEF_H`` macro is only defined on Windows. " +"(Contributed by Victor Stinner in :gh:`108765`.)" +msgstr "" +"No Windows, ``Python.h`` não inclui mais o arquivo de cabeçalho padrão " +"````. Se necessário, deverá agora ser incluído explicitamente. Por " +"exemplo, ele fornece a função :c:func:`!offsetof` e os tipos ``size_t`` e " +"``ptrdiff_t``. Incluindo ```` explicitamente já era necessário " +"para todas as outras plataformas, a macro ``HAVE_STDDEF_H`` só é definida no " +"Windows. (Contribuição de Victor Stinner em :gh:`108765`.)" + +#: ../../whatsnew/3.13.rst:2716 +msgid "" +"If the :c:macro:`Py_LIMITED_API` macro is defined, :c:macro:`!" +"Py_BUILD_CORE`, :c:macro:`!Py_BUILD_CORE_BUILTIN` and :c:macro:`!" +"Py_BUILD_CORE_MODULE` macros are now undefined by ````. " +"(Contributed by Victor Stinner in :gh:`85283`.)" +msgstr "" +"Se a macro :c:macro:`Py_LIMITED_API` estiver definida, as macros :c:macro:`!" +"Py_BUILD_CORE`, :c:macro:`!Py_BUILD_CORE_BUILTIN` e :c:macro:`!" +"Py_BUILD_CORE_MODULE` agora são indefinidas por ````. " +"(Contribuição de Victor Stinner em :gh:`85283`.)" + +#: ../../whatsnew/3.13.rst:2721 +msgid "" +"The old trashcan macros ``Py_TRASHCAN_SAFE_BEGIN`` and " +"``Py_TRASHCAN_SAFE_END`` were removed. They should be replaced by the new " +"macros ``Py_TRASHCAN_BEGIN`` and ``Py_TRASHCAN_END``." +msgstr "" +"As macros antigas da lixeira ``Py_TRASHCAN_SAFE_BEGIN`` e " +"``Py_TRASHCAN_SAFE_END`` foram removidas. Elas devem ser substituídas pelas " +"novas macros ``Py_TRASHCAN_BEGIN`` e ``Py_TRASHCAN_END``." + +#: ../../whatsnew/3.13.rst:2725 +msgid "A ``tp_dealloc`` function that has the old macros, such as::" +msgstr "Uma função ``tp_dealloc`` que contém as macros antigas, como::" + +#: ../../whatsnew/3.13.rst:2727 +msgid "" +"static void\n" +"mytype_dealloc(mytype *p)\n" +"{\n" +" PyObject_GC_UnTrack(p);\n" +" Py_TRASHCAN_SAFE_BEGIN(p);\n" +" ...\n" +" Py_TRASHCAN_SAFE_END\n" +"}" +msgstr "" +"static void\n" +"dealocador_de_meutipo(meutipo *p)\n" +"{\n" +" PyObject_GC_UnTrack(p);\n" +" Py_TRASHCAN_SAFE_BEGIN(p);\n" +" ...\n" +" Py_TRASHCAN_SAFE_END\n" +"}" + +#: ../../whatsnew/3.13.rst:2736 +msgid "should migrate to the new macros as follows::" +msgstr "deve migrar para as novas macros da seguinte forma::" + +#: ../../whatsnew/3.13.rst:2738 +msgid "" +"static void\n" +"mytype_dealloc(mytype *p)\n" +"{\n" +" PyObject_GC_UnTrack(p);\n" +" Py_TRASHCAN_BEGIN(p, mytype_dealloc)\n" +" ...\n" +" Py_TRASHCAN_END\n" +"}" +msgstr "" +"static void\n" +"dealocador_de_meutipo(meutipo *p)\n" +"{\n" +" PyObject_GC_UnTrack(p);\n" +" Py_TRASHCAN_BEGIN(p, dealocador_de_meutipo);\n" +" ...\n" +" Py_TRASHCAN_END\n" +"}" + +#: ../../whatsnew/3.13.rst:2747 +msgid "" +"Note that ``Py_TRASHCAN_BEGIN`` has a second argument which should be the " +"deallocation function it is in. The new macros were added in Python 3.8 and " +"the old macros were deprecated in Python 3.11. (Contributed by Irit Katriel " +"in :gh:`105111`.)" +msgstr "" +"Observe que ``Py_TRASHCAN_BEGIN`` tem um segundo argumento que deve ser a " +"função de desalocação em que está. As novas macros foram adicionadas no " +"Python 3.8 e as macros antigas foram descontinuadas no Python 3.11. " +"(Contribuição de Irit Katriel em :gh:`105111`.)" + +#: ../../whatsnew/3.13.rst:2754 +msgid "" +":ref:`PEP 667 ` introduces several changes to " +"frame-related functions:" +msgstr "" +":ref:`PEP 667 ` introduz várias mudanças em " +"funções relacionadas a quadro:" + +#: ../../whatsnew/3.13.rst:2757 +msgid "" +"The effects of mutating the dictionary returned from :c:func:" +"`PyEval_GetLocals` in an :term:`optimized scope` have changed. New dict " +"entries added this way will now *only* be visible to subsequent :c:func:" +"`PyEval_GetLocals` calls in that frame, as :c:func:`PyFrame_GetLocals`, :" +"func:`locals`, and :attr:`FrameType.f_locals ` no longer " +"access the same underlying cached dictionary. Changes made to entries for " +"actual variable names and names added via the write-through proxy interfaces " +"will be overwritten on subsequent calls to :c:func:`PyEval_GetLocals` in " +"that frame. The recommended code update depends on how the function was " +"being used, so refer to the deprecation notice on the function for details." +msgstr "" +"Os efeitos da mutação do dicionário retornado de :c:func:`PyEval_GetLocals` " +"em um :term:`escopo otimizado` foram alterados. Novas entradas de dict " +"adicionadas desta forma agora *apenas* ficarão visíveis para chamadas :c:" +"func:`PyEval_GetLocals` subsequentes nesse quadro, como :c:func:" +"`PyFrame_GetLocals`, :func:`locals` e :attr:`FrameType.f_locals ` não acessa mais o mesmo dicionário armazenado em cache " +"subjacente. As alterações feitas nas entradas para nomes de variáveis reais " +"e nomes adicionados através das interfaces proxy de \"write-through\" serão " +"substituídas em chamadas subsequentes para :c:func:`PyEval_GetLocals` nesse " +"quadro. A atualização de código recomendada depende de como a função estava " +"sendo usada, portanto, consulte o aviso de descontinuação na função para " +"obter detalhes." + +#: ../../whatsnew/3.13.rst:2770 +msgid "" +"Calling :c:func:`PyFrame_GetLocals` in an :term:`optimized scope` now " +"returns a write-through proxy rather than a snapshot that gets updated at " +"ill-specified times. If a snapshot is desired, it must be created explicitly " +"(e.g. with :c:func:`PyDict_Copy`), or by calling the new :c:func:" +"`PyEval_GetFrameLocals` API." +msgstr "" +"Chamar :c:func:`PyFrame_GetLocals` em um :term:`escopo otimizado` agora " +"retorna um proxy de \"write-through\" em vez de uma captura que é atualizada " +"em horários mal especificados. Se uma captura for desejada, ela deve ser " +"criada explicitamente (por exemplo, com :c:func:`PyDict_Copy`) ou chamando a " +"nova API :c:func:`PyEval_GetFrameLocals`." + +#: ../../whatsnew/3.13.rst:2777 +msgid "" +":c:func:`!PyFrame_FastToLocals` and :c:func:`!PyFrame_FastToLocalsWithError` " +"no longer have any effect. Calling these functions has been redundant since " +"Python 3.11, when :c:func:`PyFrame_GetLocals` was first introduced." +msgstr "" +":c:func:`!PyFrame_FastToLocals` e :c:func:`!PyFrame_FastToLocalsWithError` " +"não têm mais nenhum efeito. Chamar essas funções tem sido redundante desde o " +"Python 3.11, quando :c:func:`PyFrame_GetLocals` foi introduzido pela " +"primeira vez." + +#: ../../whatsnew/3.13.rst:2782 +msgid "" +":c:func:`!PyFrame_LocalsToFast` no longer has any effect. Calling this " +"function is redundant now that :c:func:`PyFrame_GetLocals` returns a write-" +"through proxy for :term:`optimized scopes `." +msgstr "" +":c:func:`!PyFrame_LocalsToFast` não tem mais efeito. Chamar esta função é " +"redundante agora que :c:func:`PyFrame_GetLocals` retorna um proxy de \"write-" +"through\" para :term:`escopos otimizados `." + +#: ../../whatsnew/3.13.rst:2786 +msgid "" +"Python 3.13 removed many private functions. Some of them can be replaced " +"using these alternatives:" +msgstr "" +"O Python 3.13 removeu muitas funções privadas. Algumas delas podem ser " +"substituídas usando estas alternativas:" + +#: ../../whatsnew/3.13.rst:2789 +msgid "``_PyDict_Pop()``: :c:func:`PyDict_Pop` or :c:func:`PyDict_PopString`;" +msgstr "``_PyDict_Pop()``: :c:func:`PyDict_Pop` ou :c:func:`PyDict_PopString`;" + +#: ../../whatsnew/3.13.rst:2790 +msgid "``_PyDict_GetItemWithError()``: :c:func:`PyDict_GetItemRef`;" +msgstr "``_PyDict_GetItemWithError()``: :c:func:`PyDict_GetItemRef`;" + +#: ../../whatsnew/3.13.rst:2791 +msgid "``_PyErr_WriteUnraisableMsg()``: :c:func:`PyErr_FormatUnraisable`;" +msgstr "``_PyErr_WriteUnraisableMsg()``: :c:func:`PyErr_FormatUnraisable`;" + +#: ../../whatsnew/3.13.rst:2792 +msgid "" +"``_PyEval_SetTrace()``: :c:func:`PyEval_SetTrace` or :c:func:" +"`PyEval_SetTraceAllThreads`;" +msgstr "" +"``_PyEval_SetTrace()``: :c:func:`PyEval_SetTrace` ou :c:func:" +"`PyEval_SetTraceAllThreads`;" + +#: ../../whatsnew/3.13.rst:2793 +msgid "``_PyList_Extend()``: :c:func:`PyList_Extend`;" +msgstr "``_PyList_Extend()``: :c:func:`PyList_Extend`;" + +#: ../../whatsnew/3.13.rst:2794 +msgid "``_PyLong_AsInt()``: :c:func:`PyLong_AsInt`;" +msgstr "``_PyLong_AsInt()``: :c:func:`PyLong_AsInt`;" + +#: ../../whatsnew/3.13.rst:2795 +msgid "``_PyMem_RawStrdup()``: ``strdup()``;" +msgstr "``_PyMem_RawStrdup()``: ``strdup()``;" + +#: ../../whatsnew/3.13.rst:2796 +msgid "``_PyMem_Strdup()``: ``strdup()``;" +msgstr "``_PyMem_Strdup()``: ``strdup()``;" + +#: ../../whatsnew/3.13.rst:2797 +msgid "``_PyObject_ClearManagedDict()``: :c:func:`PyObject_ClearManagedDict`;" +msgstr "``_PyObject_ClearManagedDict()``: :c:func:`PyObject_ClearManagedDict`;" + +#: ../../whatsnew/3.13.rst:2798 +msgid "``_PyObject_VisitManagedDict()``: :c:func:`PyObject_VisitManagedDict`;" +msgstr "``_PyObject_VisitManagedDict()``: :c:func:`PyObject_VisitManagedDict`;" + +#: ../../whatsnew/3.13.rst:2799 +msgid "" +"``_PyThreadState_UncheckedGet()``: :c:func:`PyThreadState_GetUnchecked()`;" +msgstr "" +"``_PyThreadState_UncheckedGet()``: :c:func:`PyThreadState_GetUnchecked()`;" + +#: ../../whatsnew/3.13.rst:2800 +msgid "``_PyTime_AsSecondsDouble()``: :c:func:`PyTime_AsSecondsDouble`;" +msgstr "``_PyTime_AsSecondsDouble()``: :c:func:`PyTime_AsSecondsDouble`;" + +#: ../../whatsnew/3.13.rst:2801 +msgid "" +"``_PyTime_GetMonotonicClock()``: :c:func:`PyTime_Monotonic` or :c:func:" +"`PyTime_MonotonicRaw`;" +msgstr "" +"``_PyTime_GetMonotonicClock()``: :c:func:`PyTime_Monotonic` ou :c:func:" +"`PyTime_MonotonicRaw`;" + +#: ../../whatsnew/3.13.rst:2802 +msgid "" +"``_PyTime_GetPerfCounter()``: :c:func:`PyTime_PerfCounter` or :c:func:" +"`PyTime_PerfCounterRaw`;" +msgstr "" +"``_PyTime_GetPerfCounter()``: :c:func:`PyTime_PerfCounter` ou :c:func:" +"`PyTime_PerfCounterRaw`;" + +#: ../../whatsnew/3.13.rst:2803 +msgid "" +"``_PyTime_GetSystemClock()``: :c:func:`PyTime_Time` or :c:func:" +"`PyTime_TimeRaw`;" +msgstr "" +"``_PyTime_GetSystemClock()``: :c:func:`PyTime_Time` ou :c:func:" +"`PyTime_TimeRaw`;" + +#: ../../whatsnew/3.13.rst:2804 +msgid "``_PyTime_MAX``: :c:var:`PyTime_MAX`;" +msgstr "``_PyTime_MAX``: :c:var:`PyTime_MAX`;" + +#: ../../whatsnew/3.13.rst:2805 +msgid "``_PyTime_MIN``: :c:var:`PyTime_MIN`;" +msgstr "``_PyTime_MIN``: :c:var:`PyTime_MIN`;" + +#: ../../whatsnew/3.13.rst:2806 +msgid "``_PyTime_t``: :c:type:`PyTime_t`;" +msgstr "``_PyTime_t``: :c:type:`PyTime_t`;" + +#: ../../whatsnew/3.13.rst:2807 +msgid "``_Py_HashPointer()``: :c:func:`Py_HashPointer`;" +msgstr "``_Py_HashPointer()``: :c:func:`Py_HashPointer`;" + +#: ../../whatsnew/3.13.rst:2808 +msgid "``_Py_IsFinalizing()``: :c:func:`Py_IsFinalizing`." +msgstr "``_Py_IsFinalizing()``: :c:func:`Py_IsFinalizing`." + +#: ../../whatsnew/3.13.rst:2810 +msgid "" +"The `pythoncapi-compat project`_ can be used to get most of these new " +"functions on Python 3.12 and older." +msgstr "" +"O `projeto pythoncapi-compat`_ pode ser usado para obter a maioria dessas " +"novas funções no Python 3.12 e versões anteriores." + +#: ../../whatsnew/3.13.rst:2814 msgid "Regression Test Changes" msgstr "Mudanças em teste de regressão" -#: ../../whatsnew/3.13.rst:2334 +#: ../../whatsnew/3.13.rst:2816 msgid "" "Python built with :file:`configure` :option:`--with-pydebug` now supports a :" "option:`-X presite=package.module <-X>` command-line option. If used, it " @@ -6093,3 +7128,17 @@ msgstr "" "módulo <-X>`. Se usado, especifica um módulo que deve ser importado no " "início do ciclo de vida do interpretador, antes que ``site.py`` seja " "executado. (Contribuição de Łukasz Langa em :gh:`110769`.)" + +#: ../../whatsnew/3.13.rst:2824 +msgid "Notable changes in 3.13.1" +msgstr "Alterações notáveis no 3.13.1" + +#: ../../whatsnew/3.13.rst:2829 +msgid "" +"The previously undocumented special function :func:`sys.getobjects`, which " +"only exists in specialized builds of Python, may now return objects from " +"other interpreters than the one it's called in." +msgstr "" +"A função especial :func:`sys.getobjects`, anteriormente não documentada, que " +"só existe em construções especializadas do Python, agora pode retornar " +"objetos de outros interpretadores além daquele em que foi chamada." diff --git a/whatsnew/3.2.po b/whatsnew/3.2.po index e71a610f3..641e88375 100644 --- a/whatsnew/3.2.po +++ b/whatsnew/3.2.po @@ -1,32 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# 01419cbcade949a3bc5433893a160e74, 2021 -# Victor Matheus Castro , 2021 -# Raphael Mendonça, 2021 -# Ricardo Cappellano , 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Rafael Fontenelle , 2022 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-29 13:04+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -116,20 +109,103 @@ msgid "" "one or more positional arguments is present, and making a required option::" msgstr "" +#: ../../whatsnew/3.2.rst:105 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser(\n" +" description = 'Manage servers', # main description for " +"help\n" +" epilog = 'Tested on Solaris and Linux') # displayed after help\n" +"parser.add_argument('action', # argument name\n" +" choices = ['deploy', 'start', 'stop'], # three allowed values\n" +" help = 'action on each target') # help msg\n" +"parser.add_argument('targets',\n" +" metavar = 'HOSTNAME', # var name used in help " +"msg\n" +" nargs = '+', # require one or more " +"targets\n" +" help = 'url for target machines') # help msg explanation\n" +"parser.add_argument('-u', '--user', # -u or --user option\n" +" required = True, # make it a required " +"argument\n" +" help = 'login as user')" +msgstr "" + #: ../../whatsnew/3.2.rst:120 msgid "Example of calling the parser on a command string::" msgstr "" +#: ../../whatsnew/3.2.rst:122 +msgid "" +">>> cmd = 'deploy sneezy.example.com sleepy.example.com -u skycaptain'\n" +">>> result = parser.parse_args(cmd.split())\n" +">>> result.action\n" +"'deploy'\n" +">>> result.targets\n" +"['sneezy.example.com', 'sleepy.example.com']\n" +">>> result.user\n" +"'skycaptain'" +msgstr "" + #: ../../whatsnew/3.2.rst:131 msgid "Example of the parser's automatically generated help::" msgstr "" +#: ../../whatsnew/3.2.rst:133 +msgid "" +">>> parser.parse_args('-h'.split())\n" +"\n" +"usage: manage_cloud.py [-h] -u USER\n" +" {deploy,start,stop} HOSTNAME [HOSTNAME ...]\n" +"\n" +"Manage servers\n" +"\n" +"positional arguments:\n" +" {deploy,start,stop} action on each target\n" +" HOSTNAME url for target machines\n" +"\n" +"optional arguments:\n" +" -h, --help show this help message and exit\n" +" -u USER, --user USER login as user\n" +"\n" +"Tested on Solaris and Linux" +msgstr "" + #: ../../whatsnew/3.2.rst:150 msgid "" "An especially nice :mod:`argparse` feature is the ability to define " "subparsers, each with their own argument patterns and help displays::" msgstr "" +#: ../../whatsnew/3.2.rst:153 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser(prog='HELM')\n" +"subparsers = parser.add_subparsers()\n" +"\n" +"parser_l = subparsers.add_parser('launch', help='Launch Control') # first " +"subgroup\n" +"parser_l.add_argument('-m', '--missiles', action='store_true')\n" +"parser_l.add_argument('-t', '--torpedos', action='store_true')\n" +"\n" +"parser_m = subparsers.add_parser('move', help='Move Vessel', # second " +"subgroup\n" +" aliases=('steer', 'turn')) # " +"equivalent names\n" +"parser_m.add_argument('-c', '--course', type=int, required=True)\n" +"parser_m.add_argument('-s', '--speed', type=int, default=0)" +msgstr "" + +#: ../../whatsnew/3.2.rst:166 +msgid "" +"$ ./helm.py --help # top level help (launch and " +"move)\n" +"$ ./helm.py launch --help # help for launch options\n" +"$ ./helm.py launch --missiles # set missiles=True and " +"torpedos=False\n" +"$ ./helm.py steer --course 180 --speed 5 # set movement parameters" +msgstr "" + #: ../../whatsnew/3.2.rst:175 msgid ":pep:`389` - New Command Line Parsing Module" msgstr "" @@ -167,12 +243,48 @@ msgid "" "dictionary::" msgstr "" +#: ../../whatsnew/3.2.rst:197 +msgid "" +"{\"version\": 1,\n" +" \"formatters\": {\"brief\": {\"format\": \"%(levelname)-8s: %(name)-15s: " +"%(message)s\"},\n" +" \"full\": {\"format\": \"%(asctime)s %(name)-15s " +"%(levelname)-8s %(message)s\"}\n" +" },\n" +" \"handlers\": {\"console\": {\n" +" \"class\": \"logging.StreamHandler\",\n" +" \"formatter\": \"brief\",\n" +" \"level\": \"INFO\",\n" +" \"stream\": \"ext://sys.stdout\"},\n" +" \"console_priority\": {\n" +" \"class\": \"logging.StreamHandler\",\n" +" \"formatter\": \"full\",\n" +" \"level\": \"ERROR\",\n" +" \"stream\": \"ext://sys.stderr\"}\n" +" },\n" +" \"root\": {\"level\": \"DEBUG\", \"handlers\": [\"console\", " +"\"console_priority\"]}}" +msgstr "" + #: ../../whatsnew/3.2.rst:215 msgid "" "If that dictionary is stored in a file called :file:`conf.json`, it can be " "loaded and called with code like this::" msgstr "" +#: ../../whatsnew/3.2.rst:218 +msgid "" +">>> import json, logging.config\n" +">>> with open('conf.json') as f:\n" +"... conf = json.load(f)\n" +"...\n" +">>> logging.config.dictConfig(conf)\n" +">>> logging.info(\"Transaction completed normally\")\n" +"INFO : root : Transaction completed normally\n" +">>> logging.critical(\"Abnormal termination\")\n" +"2011-02-17 11:14:36,694 root CRITICAL Abnormal termination" +msgstr "" + #: ../../whatsnew/3.2.rst:230 msgid ":pep:`391` - Dictionary Based Configuration for Logging" msgstr "" @@ -239,6 +351,16 @@ msgid "" "launch of four parallel threads for copying files::" msgstr "" +#: ../../whatsnew/3.2.rst:272 +msgid "" +"import concurrent.futures, shutil\n" +"with concurrent.futures.ThreadPoolExecutor(max_workers=4) as e:\n" +" e.submit(shutil.copy, 'src1.txt', 'dest1.txt')\n" +" e.submit(shutil.copy, 'src2.txt', 'dest2.txt')\n" +" e.submit(shutil.copy, 'src3.txt', 'dest3.txt')\n" +" e.submit(shutil.copy, 'src3.txt', 'dest4.txt')" +msgstr "" + #: ../../whatsnew/3.2.rst:281 msgid ":pep:`3148` - Futures -- Execute Computations Asynchronously" msgstr "" @@ -300,8 +422,8 @@ msgstr "" #: ../../whatsnew/3.2.rst:315 msgid "" -"Imported modules now have a :attr:`__cached__` attribute which stores the " -"name of the actual file that was imported:" +"Imported modules now have a :attr:`~module.__cached__` attribute which " +"stores the name of the actual file that was imported:" msgstr "" #: ../../whatsnew/3.2.rst:322 @@ -364,12 +486,28 @@ msgid "" "installed::" msgstr "" +#: ../../whatsnew/3.2.rst:370 +msgid "" +"/usr/share/pyshared/foo.cpython-32m.so\n" +"/usr/share/pyshared/foo.cpython-33md.so" +msgstr "" + #: ../../whatsnew/3.2.rst:373 msgid "" "In Python itself, the tags are accessible from functions in the :mod:" "`sysconfig` module::" msgstr "" +#: ../../whatsnew/3.2.rst:376 +msgid "" +">>> import sysconfig\n" +">>> sysconfig.get_config_var('SOABI') # find the version tag\n" +"'cpython-32mu'\n" +">>> sysconfig.get_config_var('EXT_SUFFIX') # find the full filename " +"extension\n" +"'.cpython-32mu.so'" +msgstr "" + #: ../../whatsnew/3.2.rst:384 msgid ":pep:`3149` - ABI Version Tagged .so Files" msgstr "" @@ -455,7 +593,7 @@ msgstr "Outras mudanças na linguagem" #: ../../whatsnew/3.2.rst:438 msgid "Some smaller changes made to the core Python language are:" -msgstr "Alguma das mudanças menores feitas no núcleo da linguagem Python são:" +msgstr "Algumas das mudanças menores feitas no núcleo da linguagem Python são:" #: ../../whatsnew/3.2.rst:440 msgid "" @@ -484,6 +622,29 @@ msgid "" "meth:`__missing__` method for unknown keys::" msgstr "" +#: ../../whatsnew/3.2.rst:463 +msgid "" +">>> import shelve\n" +">>> d = shelve.open('tmp.shl')\n" +">>> 'The {project_name} status is {status} as of {date}'.format_map(d)\n" +"'The testing project status is green as of February 15, 2011'\n" +"\n" +">>> class LowerCasedDict(dict):\n" +"... def __getitem__(self, key):\n" +"... return dict.__getitem__(self, key.lower())\n" +"...\n" +">>> lcd = LowerCasedDict(part='widgets', quantity=10)\n" +">>> 'There are {QUANTITY} {Part} in stock'.format_map(lcd)\n" +"'There are 10 widgets in stock'\n" +"\n" +">>> class PlaceholderDict(dict):\n" +"... def __missing__(self, key):\n" +"... return '<{}>'.format(key)\n" +"...\n" +">>> 'Hello {name}, welcome to {location}'.format_map(PlaceholderDict())\n" +"'Hello , welcome to '" +msgstr "" + #: ../../whatsnew/3.2.rst:483 msgid "" "(Suggested by Raymond Hettinger and implemented by Eric Smith in :issue:" @@ -498,6 +659,15 @@ msgid "" "flags` attribute:" msgstr "" +#: ../../whatsnew/3.2.rst:490 +msgid "" +"$ python -q\n" +">>> sys.flags\n" +"sys.flags(debug=0, division_warning=0, inspect=0, interactive=0,\n" +"optimize=0, dont_write_bytecode=0, no_user_site=0, no_site=0,\n" +"ignore_environment=0, verbose=0, bytes_warning=0, quiet=1)" +msgstr "" + #: ../../whatsnew/3.2.rst:498 msgid "(Contributed by Marcin Wojdyr in :issue:`1772833`)." msgstr "" @@ -513,6 +683,20 @@ msgid "" "`AttributeError` and let other exceptions pass through::" msgstr "" +#: ../../whatsnew/3.2.rst:508 +msgid "" +">>> class A:\n" +"... @property\n" +"... def f(self):\n" +"... return 1 // 0\n" +"...\n" +">>> a = A()\n" +">>> hasattr(a, 'f')\n" +"Traceback (most recent call last):\n" +" ...\n" +"ZeroDivisionError: integer division or modulo by zero" +msgstr "" + #: ../../whatsnew/3.2.rst:519 msgid "" "(Discovered by Yury Selivanov and fixed by Benjamin Peterson; :issue:`9666`.)" @@ -532,7 +716,7 @@ msgstr "" #: ../../whatsnew/3.2.rst:534 msgid "" -":class:`memoryview` objects now have a :meth:`~memoryview.release()` method " +":class:`memoryview` objects now have a :meth:`~memoryview.release` method " "and they also now support the context management protocol. This allows " "timely release of any resources that were acquired when requesting a buffer " "from the original object." @@ -548,6 +732,15 @@ msgid "" "occurs as a free variable in a nested block::" msgstr "" +#: ../../whatsnew/3.2.rst:548 +msgid "" +"def outer(x):\n" +" def inner():\n" +" return x\n" +" inner()\n" +" del x" +msgstr "" + #: ../../whatsnew/3.2.rst:554 msgid "" "This is now allowed. Remember that the target of an :keyword:`except` " @@ -555,6 +748,18 @@ msgid "" "a :exc:`SyntaxError` with Python 3.1 and now works again::" msgstr "" +#: ../../whatsnew/3.2.rst:558 +msgid "" +"def f():\n" +" def print_error():\n" +" print(e)\n" +" try:\n" +" something\n" +" except Exception as e:\n" +" print_error()\n" +" # implicit \"del e\" here" +msgstr "" + #: ../../whatsnew/3.2.rst:567 msgid "(See :issue:`4617`.)" msgstr "" @@ -581,6 +786,11 @@ msgid "" "environment variable as an alternative to using ``-W`` at the command line:" msgstr "" +#: ../../whatsnew/3.2.rst:588 +msgid "" +"$ export PYTHONWARNINGS='ignore::RuntimeWarning::,once::UnicodeWarning::'" +msgstr "" + #: ../../whatsnew/3.2.rst:592 msgid "" "(Suggested by Barry Warsaw and implemented by Philip Jenvey in :issue:" @@ -614,6 +824,14 @@ msgid "" "enabling the warning from the command line:" msgstr "" +#: ../../whatsnew/3.2.rst:612 +msgid "" +"$ python -q -Wdefault\n" +">>> f = open(\"foo\", \"wb\")\n" +">>> del f\n" +"__main__:1: ResourceWarning: unclosed file <_io.BufferedWriter name='foo'>" +msgstr "" + #: ../../whatsnew/3.2.rst:619 msgid "" "(Added by Antoine Pitrou and Georg Brandl in :issue:`10093` and :issue:" @@ -631,6 +849,18 @@ msgid "" "lists::" msgstr "" +#: ../../whatsnew/3.2.rst:628 +msgid "" +">>> range(0, 100, 2).count(10)\n" +"1\n" +">>> range(0, 100, 2).index(10)\n" +"5\n" +">>> range(0, 100, 2)[5]\n" +"10\n" +">>> range(0, 100, 2)[0:5]\n" +"range(0, 10, 2)" +msgstr "" + #: ../../whatsnew/3.2.rst:637 msgid "" "(Contributed by Daniel Stutzbach in :issue:`9213`, by Alexander Belopolsky " @@ -921,6 +1151,19 @@ msgid "" "total_ordering` to fill-in *__le__*, *__gt__* and *__ge__*::" msgstr "" +#: ../../whatsnew/3.2.rst:814 +msgid "" +"@total_ordering\n" +"class Student:\n" +" def __eq__(self, other):\n" +" return ((self.lastname.lower(), self.firstname.lower()) ==\n" +" (other.lastname.lower(), other.firstname.lower()))\n" +"\n" +" def __lt__(self, other):\n" +" return ((self.lastname.lower(), self.firstname.lower()) <\n" +" (other.lastname.lower(), other.firstname.lower()))" +msgstr "" + #: ../../whatsnew/3.2.rst:824 msgid "" "With the *total_ordering* decorator, the remaining comparison methods are " @@ -1044,6 +1287,22 @@ msgstr "" msgid "Example of using barriers::" msgstr "" +#: ../../whatsnew/3.2.rst:940 +msgid "" +"from threading import Barrier, Thread\n" +"\n" +"def get_votes(site):\n" +" ballots = conduct_election(site)\n" +" all_polls_closed.wait() # do not count until all polls are " +"closed\n" +" totals = summarize(ballots)\n" +" publish(site, totals)\n" +"\n" +"all_polls_closed = Barrier(len(sites))\n" +"for site in sites:\n" +" Thread(target=get_votes, args=(site,)).start()" +msgstr "" + #: ../../whatsnew/3.2.rst:952 msgid "" "In this example, the barrier enforces a rule that votes cannot be counted at " @@ -1062,6 +1321,20 @@ msgid "" "exception is raised::" msgstr "" +#: ../../whatsnew/3.2.rst:963 +msgid "" +"def get_votes(site):\n" +" ballots = conduct_election(site)\n" +" try:\n" +" all_polls_closed.wait(timeout=midnight - time.now())\n" +" except BrokenBarrierError:\n" +" lockbox = seal_ballots(ballots)\n" +" queue.put(lockbox)\n" +" else:\n" +" totals = summarize(ballots)\n" +" publish(site, totals)" +msgstr "" + #: ../../whatsnew/3.2.rst:974 msgid "" "In this example, the barrier enforces a more robust rule. If some election " @@ -1097,6 +1370,18 @@ msgid "" "datetime objects::" msgstr "" +#: ../../whatsnew/3.2.rst:995 +msgid "" +">>> from datetime import datetime, timezone\n" +"\n" +">>> datetime.now(timezone.utc)\n" +"datetime.datetime(2010, 12, 8, 21, 4, 2, 923754, tzinfo=datetime.timezone." +"utc)\n" +"\n" +">>> datetime.strptime(\"01/01/2000 12:00 +0000\", \"%m/%d/%Y %H:%M %z\")\n" +"datetime.datetime(2000, 1, 1, 12, 0, tzinfo=datetime.timezone.utc)" +msgstr "" + #: ../../whatsnew/3.2.rst:1003 msgid "" "Also, :class:`~datetime.timedelta` objects can now be multiplied by :class:" @@ -1126,6 +1411,23 @@ msgid "" "without guesswork::" msgstr "" +#: ../../whatsnew/3.2.rst:1020 +msgid "" +">>> import time, warnings\n" +">>> warnings.resetwarnings() # remove the default warning filters\n" +"\n" +">>> time.accept2dyear = True # guess whether 11 means 11 or 2011\n" +">>> time.asctime((11, 1, 1, 12, 34, 56, 4, 1, 0))\n" +"Warning (from warnings module):\n" +" ...\n" +"DeprecationWarning: Century info guessed for a 2-digit year.\n" +"'Fri Jan 1 12:34:56 2011'\n" +"\n" +">>> time.accept2dyear = False # use the full range of allowable dates\n" +">>> time.asctime((11, 1, 1, 12, 34, 56, 4, 1, 0))\n" +"'Fri Jan 1 12:34:56 11'" +msgstr "" + #: ../../whatsnew/3.2.rst:1034 msgid "" "Several functions now have significantly expanded date ranges. When :data:`!" @@ -1173,6 +1475,19 @@ msgid "" "complementary error function, :func:`~math.erfc`, is ``1 - erf(x)``:" msgstr "" +#: ../../whatsnew/3.2.rst:1072 +msgid "" +">>> from math import erf, erfc, sqrt\n" +">>> erf(1.0/sqrt(2.0)) # portion of normal distribution within 1 standard " +"deviation\n" +"0.682689492137086\n" +">>> erfc(1.0/sqrt(2.0)) # portion of normal distribution outside 1 standard " +"deviation\n" +"0.31731050786291404\n" +">>> erf(1.0/sqrt(2.0)) + erfc(1.0/sqrt(2.0))\n" +"1.0" +msgstr "" + #: ../../whatsnew/3.2.rst:1083 msgid "" "The :func:`~math.gamma` function is a continuous extension of the factorial " @@ -1203,6 +1518,17 @@ msgid "" "implemented::" msgstr "" +#: ../../whatsnew/3.2.rst:1107 +msgid "" +"class Temperature(metaclass=abc.ABCMeta):\n" +" @abc.abstractclassmethod\n" +" def from_fahrenheit(cls, t):\n" +" ...\n" +" @abc.abstractclassmethod\n" +" def from_celsius(cls, t):\n" +" ..." +msgstr "" + #: ../../whatsnew/3.2.rst:1115 msgid "(Patch submitted by Daniel Urban; :issue:`5867`.)" msgstr "" @@ -1219,6 +1545,30 @@ msgid "" "and support for slice notation are well-suited to in-place editing::" msgstr "" +#: ../../whatsnew/3.2.rst:1125 +msgid "" +">>> REC_LEN, LOC_START, LOC_LEN = 34, 7, 11\n" +"\n" +">>> def change_location(buffer, record_number, location):\n" +"... start = record_number * REC_LEN + LOC_START\n" +"... buffer[start: start+LOC_LEN] = location\n" +"\n" +">>> import io\n" +"\n" +">>> byte_stream = io.BytesIO(\n" +"... b'G3805 storeroom Main chassis '\n" +"... b'X7899 shipping Reserve cog '\n" +"... b'L6988 receiving Primary sprocket'\n" +"... )\n" +">>> buffer = byte_stream.getbuffer()\n" +">>> change_location(buffer, 1, b'warehouse ')\n" +">>> change_location(buffer, 0, b'showroom ')\n" +">>> print(byte_stream.getvalue())\n" +"b'G3805 showroom Main chassis '\n" +"b'X7899 warehouse Reserve cog '\n" +"b'L6988 receiving Primary sprocket'" +msgstr "" + #: ../../whatsnew/3.2.rst:1146 msgid "(Contributed by Antoine Pitrou in :issue:`5506`.)" msgstr "" @@ -1244,6 +1594,20 @@ msgid "" "instead::" msgstr "" +#: ../../whatsnew/3.2.rst:1161 +msgid "" +">>> class MyList(list):\n" +"... @recursive_repr()\n" +"... def __repr__(self):\n" +"... return '<' + '|'.join(map(repr, self)) + '>'\n" +"...\n" +">>> m = MyList('abc')\n" +">>> m.append(m)\n" +">>> m.append('x')\n" +">>> print(m)\n" +"<'a'|'b'|'c'|...|'x'>" +msgstr "" + #: ../../whatsnew/3.2.rst:1172 msgid "(Contributed by Raymond Hettinger in :issue:`9826` and :issue:`9840`.)" msgstr "" @@ -1276,6 +1640,15 @@ msgid "" "are equivalent::" msgstr "" +#: ../../whatsnew/3.2.rst:1191 +msgid "" +">>> from logging import basicConfig\n" +">>> basicConfig(style='%', format=\"%(name)s -> %(levelname)s: " +"%(message)s\")\n" +">>> basicConfig(style='{', format=\"{name} -> {levelname} {message}\")\n" +">>> basicConfig(style='$', format=\"$name -> $levelname: $message\")" +msgstr "" + #: ../../whatsnew/3.2.rst:1196 msgid "" "If no configuration is set-up before a logging event occurs, there is now a " @@ -1319,6 +1692,19 @@ msgid "" "writeheader` for writing-out an initial row to document the field names::" msgstr "" +#: ../../whatsnew/3.2.rst:1223 +msgid "" +">>> import csv, sys\n" +">>> w = csv.DictWriter(sys.stdout, ['name', 'dept'], dialect='unix')\n" +">>> w.writeheader()\n" +"\"name\",\"dept\"\n" +">>> w.writerows([\n" +"... {'name': 'tom', 'dept': 'accounting'},\n" +"... {'name': 'susan', 'dept': 'Salesl'}])\n" +"\"tom\",\"accounting\"\n" +"\"susan\",\"sales\"" +msgstr "" + #: ../../whatsnew/3.2.rst:1233 msgid "" "(New dialect suggested by Jay Talbot in :issue:`5975`, and the new method " @@ -1361,14 +1747,43 @@ msgid "" "single definition::" msgstr "" +#: ../../whatsnew/3.2.rst:1259 +msgid "" +"from contextlib import contextmanager\n" +"import logging\n" +"\n" +"logging.basicConfig(level=logging.INFO)\n" +"\n" +"@contextmanager\n" +"def track_entry_and_exit(name):\n" +" logging.info('Entering: %s', name)\n" +" yield\n" +" logging.info('Exiting: %s', name)" +msgstr "" + #: ../../whatsnew/3.2.rst:1270 msgid "Formerly, this would have only been usable as a context manager::" msgstr "" +#: ../../whatsnew/3.2.rst:1272 +msgid "" +"with track_entry_and_exit('widget loader'):\n" +" print('Some time consuming activity goes here')\n" +" load_widget()" +msgstr "" + #: ../../whatsnew/3.2.rst:1276 msgid "Now, it can be used as a decorator as well::" msgstr "" +#: ../../whatsnew/3.2.rst:1278 +msgid "" +"@track_entry_and_exit('widget loader')\n" +"def activity():\n" +" print('Some time consuming activity goes here')\n" +" load_widget()" +msgstr "" + #: ../../whatsnew/3.2.rst:1283 msgid "" "Trying to fulfill two roles at once places some limitations on the " @@ -1399,6 +1814,12 @@ msgid "" "actual values are equal (:issue:`8188`)::" msgstr "" +#: ../../whatsnew/3.2.rst:1300 +msgid "" +"assert hash(Fraction(3, 2)) == hash(1.5) == \\\n" +" hash(Decimal(\"1.5\")) == hash(complex(1.5, 0))" +msgstr "" + #: ../../whatsnew/3.2.rst:1303 msgid "" "Some of the hashing details are exposed through a new attribute, :data:`sys." @@ -1442,7 +1863,7 @@ msgstr "" #: ../../whatsnew/3.2.rst:1327 msgid "" "Similar changes were made to :class:`fractions.Fraction` so that the :meth:" -"`~fractions.Fraction.from_float()` and :meth:`~fractions.Fraction." +"`~fractions.Fraction.from_float` and :meth:`~fractions.Fraction." "from_decimal` methods are no longer needed (:issue:`8294`):" msgstr "" @@ -1469,12 +1890,33 @@ msgid "" "FTP connection when done::" msgstr "" +#: ../../whatsnew/3.2.rst:1352 +msgid "" +">>> from ftplib import FTP\n" +">>> with FTP(\"ftp1.at.proftpd.org\") as ftp:\n" +" ftp.login()\n" +" ftp.dir()\n" +"\n" +"'230 Anonymous login ok, restrictions apply.'\n" +"dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 .\n" +"dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 ..\n" +"dr-xr-xr-x 5 ftp ftp 4096 May 6 10:43 CentOS\n" +"dr-xr-xr-x 3 ftp ftp 18 Jul 10 2008 Fedora" +msgstr "" + #: ../../whatsnew/3.2.rst:1363 msgid "" "Other file-like objects such as :class:`mmap.mmap` and :func:`fileinput." "input` also grew auto-closing context managers::" msgstr "" +#: ../../whatsnew/3.2.rst:1366 +msgid "" +"with fileinput.input(files=('log1.txt', 'log2.txt')) as f:\n" +" for line in f:\n" +" process(line)" +msgstr "" + #: ../../whatsnew/3.2.rst:1370 msgid "" "(Contributed by Tarek Ziadé and Giampaolo Rodolà in :issue:`4972`, and by " @@ -1587,6 +2029,26 @@ msgid "" "function can return ``None``::" msgstr "" +#: ../../whatsnew/3.2.rst:1454 +msgid "" +">>> import tarfile, glob\n" +"\n" +">>> def myfilter(tarinfo):\n" +"... if tarinfo.isfile(): # only save real files\n" +"... tarinfo.uname = 'monty' # redact the user name\n" +"... return tarinfo\n" +"\n" +">>> with tarfile.open(name='myarchive.tar.gz', mode='w:gz') as tf:\n" +"... for filename in glob.glob('*.txt'):\n" +"... tf.add(filename, filter=myfilter)\n" +"... tf.list()\n" +"-rw-r--r-- monty/501 902 2011-01-26 17:59:11 annotations.txt\n" +"-rw-r--r-- monty/501 123 2011-01-26 17:59:11 general_questions.txt\n" +"-rw-r--r-- monty/501 3514 2011-01-26 17:59:11 prion.txt\n" +"-rw-r--r-- monty/501 124 2011-01-26 17:59:11 py_todo.txt\n" +"-rw-r--r-- monty/501 1399 2011-01-26 17:59:11 semaphore_notes.txt" +msgstr "" + #: ../../whatsnew/3.2.rst:1471 msgid "" "(Proposed by Tarek Ziadé and implemented by Lars Gustäbel in :issue:`6856`.)" @@ -1603,6 +2065,21 @@ msgid "" "available on the current implementation::" msgstr "" +#: ../../whatsnew/3.2.rst:1480 +msgid "" +">>> import hashlib\n" +"\n" +">>> hashlib.algorithms_guaranteed\n" +"{'sha1', 'sha224', 'sha384', 'sha256', 'sha512', 'md5'}\n" +"\n" +">>> hashlib.algorithms_available\n" +"{'md2', 'SHA256', 'SHA512', 'dsaWithSHA', 'mdc2', 'SHA224', 'MD4', " +"'sha256',\n" +"'sha512', 'ripemd160', 'SHA1', 'MDC2', 'SHA', 'SHA384', 'MD2',\n" +"'ecdsa-with-SHA1','md4', 'md5', 'sha1', 'DSA-SHA', 'sha224',\n" +"'dsaEncryption', 'DSA', 'RIPEMD160', 'sha', 'MD5', 'sha384'}" +msgstr "" + #: ../../whatsnew/3.2.rst:1491 msgid "(Suggested by Carl Chenet in :issue:`7418`.)" msgstr "" @@ -1621,6 +2098,21 @@ msgid "" "numbers, tuples, lists, dicts, sets, booleans, and ``None``." msgstr "" +#: ../../whatsnew/3.2.rst:1505 +msgid "" +">>> from ast import literal_eval\n" +"\n" +">>> request = \"{'req': 3, 'func': 'pow', 'args': (2, 0.5)}\"\n" +">>> literal_eval(request)\n" +"{'args': (2, 0.5), 'req': 3, 'func': 'pow'}\n" +"\n" +">>> request = \"os.system('do something harmful')\"\n" +">>> literal_eval(request)\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: malformed node or string: <_ast.Call object at 0x101739a10>" +msgstr "" + #: ../../whatsnew/3.2.rst:1517 msgid "(Implemented by Benjamin Peterson and Georg Brandl.)" msgstr "" @@ -1698,6 +2190,32 @@ msgid "" "non-destructive (the original files are left unchanged)." msgstr "" +#: ../../whatsnew/3.2.rst:1569 +msgid "" +">>> import shutil, pprint\n" +"\n" +">>> os.chdir('mydata') # change to the source directory\n" +">>> f = shutil.make_archive('/var/backup/mydata',\n" +"... 'zip') # archive the current directory\n" +">>> f # show the name of archive\n" +"'/var/backup/mydata.zip'\n" +">>> os.chdir('tmp') # change to an unpacking\n" +">>> shutil.unpack_archive('/var/backup/mydata.zip') # recover the data\n" +"\n" +">>> pprint.pprint(shutil.get_archive_formats()) # display known formats\n" +"[('bztar', \"bzip2'ed tar-file\"),\n" +" ('gztar', \"gzip'ed tar-file\"),\n" +" ('tar', 'uncompressed tar file'),\n" +" ('zip', 'ZIP file')]\n" +"\n" +">>> shutil.register_archive_format( # register a new archive format\n" +"... name='xz',\n" +"... function=xz.compress, # callable archiving function\n" +"... extra_args=[('level', 8)], # arguments to the function\n" +"... description='xz compression'\n" +"... )" +msgstr "" + #: ../../whatsnew/3.2.rst:1595 msgid "sqlite3" msgstr "sqlite3" @@ -1747,7 +2265,7 @@ msgstr "" #: ../../whatsnew/3.2.rst:1625 msgid "" -"Socket objects now have a :meth:`~socket.socket.detach()` method which puts " +"Socket objects now have a :meth:`~socket.socket.detach` method which puts " "the socket into closed state without actually closing the underlying file " "descriptor. The latter can then be reused for other purposes. (Added by " "Antoine Pitrou; :issue:`8524`.)" @@ -1790,8 +2308,8 @@ msgid "" "The :func:`ssl.wrap_socket() ` constructor " "function now takes a *ciphers* argument. The *ciphers* string lists the " "allowed encryption algorithms using the format described in the `OpenSSL " -"documentation `__." +"documentation `__." msgstr "" #: ../../whatsnew/3.2.rst:1655 @@ -1957,6 +2475,10 @@ msgid "" "and a directory to start discovery with ``-s``:" msgstr "" +#: ../../whatsnew/3.2.rst:1755 +msgid "$ python -m unittest discover -s my_proj_dir -p _test.py" +msgstr "" + #: ../../whatsnew/3.2.rst:1759 ../../whatsnew/3.2.rst:1768 #: ../../whatsnew/3.2.rst:1924 msgid "(Contributed by Michael Foord.)" @@ -1975,6 +2497,12 @@ msgid "" "a given warning type is triggered by the code under test::" msgstr "" +#: ../../whatsnew/3.2.rst:1775 +msgid "" +"with self.assertWarns(DeprecationWarning):\n" +" legacy_function('XYZ')" +msgstr "" + #: ../../whatsnew/3.2.rst:1778 msgid "(Contributed by Antoine Pitrou, :issue:`9754`.)" msgstr "" @@ -1987,6 +2515,12 @@ msgid "" "regardless of order)::" msgstr "" +#: ../../whatsnew/3.2.rst:1785 +msgid "" +"def test_anagram(self):\n" +" self.assertCountEqual('algorithm', 'logarithm')" +msgstr "" + #: ../../whatsnew/3.2.rst:1790 msgid "" "A principal feature of the unittest module is an effort to produce " @@ -2131,11 +2665,11 @@ msgstr "asyncore" #: ../../whatsnew/3.2.rst:1861 msgid "" -":class:`!asyncore.dispatcher` now provides a :meth:`!handle_accepted()` " -"method returning a ``(sock, addr)`` pair which is called when a connection " -"has actually been established with a new remote endpoint. This is supposed " -"to be used as a replacement for old :meth:`!handle_accept()` and avoids the " -"user to call :meth:`!accept()` directly." +":class:`!asyncore.dispatcher` now provides a :meth:`!handle_accepted` method " +"returning a ``(sock, addr)`` pair which is called when a connection has " +"actually been established with a new remote endpoint. This is supposed to be " +"used as a replacement for old :meth:`!handle_accept` and avoids the user to " +"call :meth:`!accept` directly." msgstr "" #: ../../whatsnew/3.2.rst:1868 @@ -2153,6 +2687,12 @@ msgid "" "directories::" msgstr "" +#: ../../whatsnew/3.2.rst:1877 +msgid "" +"with tempfile.TemporaryDirectory() as tmpdirname:\n" +" print('created temporary dir:', tmpdirname)" +msgstr "" + #: ../../whatsnew/3.2.rst:1880 msgid "(Contributed by Neil Schemenauer and Nick Coghlan; :issue:`5178`.)" msgstr "" @@ -2168,6 +2708,24 @@ msgid "" "iterator::" msgstr "" +#: ../../whatsnew/3.2.rst:1889 +msgid "" +">>> from inspect import getgeneratorstate\n" +">>> def gen():\n" +"... yield 'demo'\n" +"...\n" +">>> g = gen()\n" +">>> getgeneratorstate(g)\n" +"'GEN_CREATED'\n" +">>> next(g)\n" +"'demo'\n" +">>> getgeneratorstate(g)\n" +"'GEN_SUSPENDED'\n" +">>> next(g, None)\n" +">>> getgeneratorstate(g)\n" +"'GEN_CLOSED'" +msgstr "" + #: ../../whatsnew/3.2.rst:1904 msgid "(Contributed by Rodolpho Eckhardt and Nick Coghlan, :issue:`10220`.)" msgstr "" @@ -2180,6 +2738,22 @@ msgid "" "guaranteed not to change state while it is searching::" msgstr "" +#: ../../whatsnew/3.2.rst:1911 +msgid "" +">>> class A:\n" +"... @property\n" +"... def f(self):\n" +"... print('Running')\n" +"... return 10\n" +"...\n" +">>> a = A()\n" +">>> getattr(a, 'f')\n" +"Running\n" +"10\n" +">>> inspect.getattr_static(a, 'f')\n" +"" +msgstr "" + #: ../../whatsnew/3.2.rst:1927 msgid "pydoc" msgstr "pydoc" @@ -2191,6 +2765,10 @@ msgid "" "window to display that server:" msgstr "" +#: ../../whatsnew/3.2.rst:1933 +msgid "$ pydoc3.2 -b" +msgstr "" + #: ../../whatsnew/3.2.rst:1937 msgid "(Contributed by Ron Adam; :issue:`2001`.)" msgstr "" @@ -2207,6 +2785,32 @@ msgid "" "code object. The former returns a string and the latter prints it::" msgstr "" +#: ../../whatsnew/3.2.rst:1947 +msgid "" +">>> import dis, random\n" +">>> dis.show_code(random.choice)\n" +"Name: choice\n" +"Filename: /Library/Frameworks/Python.framework/Versions/3.2/lib/" +"python3.2/random.py\n" +"Argument count: 2\n" +"Kw-only arguments: 0\n" +"Number of locals: 3\n" +"Stack size: 11\n" +"Flags: OPTIMIZED, NEWLOCALS, NOFREE\n" +"Constants:\n" +" 0: 'Choose a random element from a non-empty sequence.'\n" +" 1: 'Cannot choose from an empty sequence'\n" +"Names:\n" +" 0: _randbelow\n" +" 1: len\n" +" 2: ValueError\n" +" 3: IndexError\n" +"Variable names:\n" +" 0: self\n" +" 1: seq\n" +" 2: i" +msgstr "" + #: ../../whatsnew/3.2.rst:1969 msgid "" "In addition, the :func:`~dis.dis` function now accepts string arguments so " @@ -2214,6 +2818,27 @@ msgid "" "``dis(s)``::" msgstr "" +#: ../../whatsnew/3.2.rst:1973 +msgid "" +">>> dis('3*x+1 if x%2==1 else x//2')\n" +" 1 0 LOAD_NAME 0 (x)\n" +" 3 LOAD_CONST 0 (2)\n" +" 6 BINARY_MODULO\n" +" 7 LOAD_CONST 1 (1)\n" +" 10 COMPARE_OP 2 (==)\n" +" 13 POP_JUMP_IF_FALSE 28\n" +" 16 LOAD_CONST 2 (3)\n" +" 19 LOAD_NAME 0 (x)\n" +" 22 BINARY_MULTIPLY\n" +" 23 LOAD_CONST 1 (1)\n" +" 26 BINARY_ADD\n" +" 27 RETURN_VALUE\n" +" >> 28 LOAD_NAME 0 (x)\n" +" 31 LOAD_CONST 0 (2)\n" +" 34 BINARY_FLOOR_DIVIDE\n" +" 35 RETURN_VALUE" +msgstr "" + #: ../../whatsnew/3.2.rst:1991 msgid "" "Taken together, these improvements make it easier to explore how CPython is " @@ -2276,12 +2901,34 @@ msgid "" "directory path." msgstr "" +#: ../../whatsnew/3.2.rst:2025 +msgid "" +">>> import site\n" +">>> site.getsitepackages()\n" +"['/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-" +"packages',\n" +" '/Library/Frameworks/Python.framework/Versions/3.2/lib/site-python',\n" +" '/Library/Python/3.2/site-packages']\n" +">>> site.getuserbase()\n" +"'/Users/raymondhettinger/Library/Python/3.2'\n" +">>> site.getusersitepackages()\n" +"'/Users/raymondhettinger/Library/Python/3.2/lib/python/site-packages'" +msgstr "" + #: ../../whatsnew/3.2.rst:2035 msgid "" "Conveniently, some of site's functionality is accessible directly from the " "command-line:" msgstr "" +#: ../../whatsnew/3.2.rst:2038 +msgid "" +"$ python -m site --user-base\n" +"/Users/raymondhettinger/.local\n" +"$ python -m site --user-site\n" +"/Users/raymondhettinger/.local/lib/python3.2/site-packages" +msgstr "" + #: ../../whatsnew/3.2.rst:2045 msgid "(Contributed by Tarek Ziadé in :issue:`6693`.)" msgstr "" @@ -2338,6 +2985,45 @@ msgstr "" msgid "There is also a convenient command-line interface:" msgstr "" +#: ../../whatsnew/3.2.rst:2073 +msgid "" +"C:\\Python32>python -m sysconfig\n" +"Platform: \"win32\"\n" +"Python version: \"3.2\"\n" +"Current installation scheme: \"nt\"\n" +"\n" +"Paths:\n" +" data = \"C:\\Python32\"\n" +" include = \"C:\\Python32\\Include\"\n" +" platinclude = \"C:\\Python32\\Include\"\n" +" platlib = \"C:\\Python32\\Lib\\site-packages\"\n" +" platstdlib = \"C:\\Python32\\Lib\"\n" +" purelib = \"C:\\Python32\\Lib\\site-packages\"\n" +" scripts = \"C:\\Python32\\Scripts\"\n" +" stdlib = \"C:\\Python32\\Lib\"\n" +"\n" +"Variables:\n" +" BINDIR = \"C:\\Python32\"\n" +" BINLIBDEST = \"C:\\Python32\\Lib\"\n" +" EXE = \".exe\"\n" +" INCLUDEPY = \"C:\\Python32\\Include\"\n" +" LIBDEST = \"C:\\Python32\\Lib\"\n" +" SO = \".pyd\"\n" +" VERSION = \"32\"\n" +" abiflags = \"\"\n" +" base = \"C:\\Python32\"\n" +" exec_prefix = \"C:\\Python32\"\n" +" platbase = \"C:\\Python32\"\n" +" prefix = \"C:\\Python32\"\n" +" projectbase = \"C:\\Python32\"\n" +" py_version = \"3.2\"\n" +" py_version_nodot = \"32\"\n" +" py_version_short = \"3.2\"\n" +" srcdir = \"C:\\Python32\"\n" +" userbase = \"C:\\Documents and Settings\\Raymond\\Application " +"Data\\Python\"" +msgstr "" + #: ../../whatsnew/3.2.rst:2110 msgid "(Moved out of Distutils by Tarek Ziadé.)" msgstr "" @@ -2413,6 +3099,35 @@ msgstr "" msgid "Config parsers gained a new API based on the mapping protocol::" msgstr "" +#: ../../whatsnew/3.2.rst:2144 +msgid "" +">>> parser = ConfigParser()\n" +">>> parser.read_string(\"\"\"\n" +"... [DEFAULT]\n" +"... location = upper left\n" +"... visible = yes\n" +"... editable = no\n" +"... color = blue\n" +"...\n" +"... [main]\n" +"... title = Main Menu\n" +"... color = green\n" +"...\n" +"... [options]\n" +"... title = Options\n" +"... \"\"\")\n" +">>> parser['main']['color']\n" +"'green'\n" +">>> parser['main']['editable']\n" +"'no'\n" +">>> section = parser['options']\n" +">>> section['title']\n" +"'Options'\n" +">>> section['title'] = 'Options (editable: %(editable)s)'\n" +">>> section['title']\n" +"'Options (editable: no)'" +msgstr "" + #: ../../whatsnew/3.2.rst:2170 msgid "" "The new API is implemented on top of the classical API, so custom parser " @@ -2432,6 +3147,39 @@ msgid "" "interpolation handler :class:`~configparser.ExtendedInterpolation`::" msgstr "" +#: ../../whatsnew/3.2.rst:2180 +msgid "" +">>> parser = ConfigParser(interpolation=ExtendedInterpolation())\n" +">>> parser.read_dict({'buildout': {'directory': '/home/ambv/zope9'},\n" +"... 'custom': {'prefix': '/usr/local'}})\n" +">>> parser.read_string(\"\"\"\n" +"... [buildout]\n" +"... parts =\n" +"... zope9\n" +"... instance\n" +"... find-links =\n" +"... ${buildout:directory}/downloads/dist\n" +"...\n" +"... [zope9]\n" +"... recipe = plone.recipe.zope9install\n" +"... location = /opt/zope\n" +"...\n" +"... [instance]\n" +"... recipe = plone.recipe.zope9instance\n" +"... zope9-location = ${zope9:location}\n" +"... zope-conf = ${custom:prefix}/etc/zope.conf\n" +"... \"\"\")\n" +">>> parser['buildout']['find-links']\n" +"'\\n/home/ambv/zope9/downloads/dist'\n" +">>> parser['instance']['zope-conf']\n" +"'/usr/local/etc/zope.conf'\n" +">>> instance = parser['instance']\n" +">>> instance['zope-conf']\n" +"'/usr/local/etc/zope.conf'\n" +">>> instance['zope9-location']\n" +"'/opt/zope'" +msgstr "" + #: ../../whatsnew/3.2.rst:2210 msgid "" "A number of smaller features were also introduced, like support for " @@ -2465,6 +3213,17 @@ msgid "" "tuple`::" msgstr "" +#: ../../whatsnew/3.2.rst:2237 +msgid "" +">>> r = urllib.parse.urldefrag('http://python.org/about/#target')\n" +">>> r\n" +"DefragResult(url='http://python.org/about/', fragment='target')\n" +">>> r[0]\n" +"'http://python.org/about/'\n" +">>> r.fragment\n" +"'target'" +msgstr "" + #: ../../whatsnew/3.2.rst:2245 msgid "" "And, the :func:`~urllib.parse.urlencode` function is now much more flexible, " @@ -2473,6 +3232,15 @@ msgid "" "func:`~urllib.parse.quote_plus` for encoding::" msgstr "" +#: ../../whatsnew/3.2.rst:2250 +msgid "" +">>> urllib.parse.urlencode([\n" +"... ('type', 'telenovela'),\n" +"... ('name', '¿Dónde Está Elisa?')],\n" +"... encoding='latin-1')\n" +"'type=telenovela&name=%BFD%F3nde+Est%E1+Elisa%3F'" +msgstr "" + #: ../../whatsnew/3.2.rst:2256 msgid "" "As detailed in :ref:`parsing-ascii-encoded-bytes`, all the :mod:`urllib." @@ -2556,6 +3324,10 @@ msgid "" "from the command-line:" msgstr "" +#: ../../whatsnew/3.2.rst:2309 +msgid "$ python -m turtledemo" +msgstr "" + #: ../../whatsnew/3.2.rst:2313 msgid "" "(Moved from the Demo directory by Alexander Belopolsky in :issue:`10199`.)" @@ -2574,7 +3346,7 @@ msgid "" "ensuing system calls. The notion of a \"check interval\" to allow thread " "switches has been abandoned and replaced by an absolute duration expressed " "in seconds. This parameter is tunable through :func:`sys." -"setswitchinterval()`. It currently defaults to 5 milliseconds." +"setswitchinterval`. It currently defaults to 5 milliseconds." msgstr "" #: ../../whatsnew/3.2.rst:2327 @@ -2633,6 +3405,13 @@ msgid "" "and operationally fast::" msgstr "" +#: ../../whatsnew/3.2.rst:2362 +msgid "" +"extension = name.rpartition('.')[2]\n" +"if extension in {'xml', 'html', 'xhtml', 'css'}:\n" +" handle(name)" +msgstr "" + #: ../../whatsnew/3.2.rst:2366 msgid "" "(Patch and additional tests contributed by Dave Malcolm; :issue:`6690`)." @@ -3182,6 +3961,14 @@ msgid "" "when one of them raises an exception::" msgstr "" +#: ../../whatsnew/3.2.rst:2692 +msgid "" +"with open('mylog.txt') as infile, open('a.out', 'w') as outfile:\n" +" for line in infile:\n" +" if '' in line:\n" +" outfile.write(line)" +msgstr "" + #: ../../whatsnew/3.2.rst:2697 msgid "" "(Contributed by Georg Brandl and Mattias Brändström; `appspot issue 53094 " diff --git a/whatsnew/3.3.po b/whatsnew/3.3.po index 5b33b0e0b..a57f7d296 100644 --- a/whatsnew/3.3.po +++ b/whatsnew/3.3.po @@ -1,35 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Ricardo Cappellano , 2021 -# Victor Matheus Castro , 2021 -# Vinícius Muniz de Melo , 2021 -# Raphael Mendonça, 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# a76d6fb6142d7607ab0526dcbddb02d7_7bf0da0 <3b5fb0f281c8dfb4c0170f2ee2a6cfcf_843623>, 2021 -# Patricia Rosa, 2022 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-29 13:04+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -148,7 +138,7 @@ msgstr "" #: ../../whatsnew/3.3.rst:100 msgid "PEP 405: Virtual Environments" -msgstr "" +msgstr "PEP 405: Ambientes Virtuais" #: ../../whatsnew/3.3.rst:102 msgid "" @@ -171,7 +161,7 @@ msgstr "" #: ../../whatsnew/3.3.rst:118 msgid ":pep:`405` - Python Virtual Environments" -msgstr "" +msgstr ":pep:`405` - Ambientes Virtuais Python" #: ../../whatsnew/3.3.rst:119 msgid "PEP written by Carl Meyer; implementation by Carl Meyer and Vinay Sajip" @@ -233,7 +223,7 @@ msgid "" "dimensional NumPy-style arrays is explained." msgstr "" -#: ../../whatsnew/3.3.rst:161 ../../whatsnew/3.3.rst:1123 +#: ../../whatsnew/3.3.rst:161 ../../whatsnew/3.3.rst:1125 msgid "Features" msgstr "Recursos" @@ -270,9 +260,9 @@ msgid "" "now possible to reverse a memoryview in *O*\\ (1) by using a negative step." msgstr "" -#: ../../whatsnew/3.3.rst:180 ../../whatsnew/3.3.rst:1133 +#: ../../whatsnew/3.3.rst:180 ../../whatsnew/3.3.rst:1135 msgid "API changes" -msgstr "" +msgstr "Mudanças na API" #: ../../whatsnew/3.3.rst:182 msgid "The maximum number of dimensions is officially limited to 64." @@ -399,7 +389,7 @@ msgstr "" #: ../../whatsnew/3.3.rst:259 msgid "Performance and resource usage" -msgstr "" +msgstr "Desempenho e utilização de recursos" #: ../../whatsnew/3.3.rst:261 msgid "" @@ -595,19 +585,46 @@ msgid "" "avoided. For example, the following code written for Python 3.2::" msgstr "" +#: ../../whatsnew/3.3.rst:366 +msgid "" +"from errno import ENOENT, EACCES, EPERM\n" +"\n" +"try:\n" +" with open(\"document.txt\") as f:\n" +" content = f.read()\n" +"except IOError as err:\n" +" if err.errno == ENOENT:\n" +" print(\"document.txt file is missing\")\n" +" elif err.errno in (EACCES, EPERM):\n" +" print(\"You are not allowed to read document.txt\")\n" +" else:\n" +" raise" +msgstr "" + #: ../../whatsnew/3.3.rst:379 msgid "" "can now be written without the :mod:`errno` import and without manual " "inspection of exception attributes::" msgstr "" +#: ../../whatsnew/3.3.rst:382 +msgid "" +"try:\n" +" with open(\"document.txt\") as f:\n" +" content = f.read()\n" +"except FileNotFoundError:\n" +" print(\"document.txt file is missing\")\n" +"except PermissionError:\n" +" print(\"You are not allowed to read document.txt\")" +msgstr "" + #: ../../whatsnew/3.3.rst:392 msgid ":pep:`3151` - Reworking the OS and IO Exception Hierarchy" msgstr "" #: ../../whatsnew/3.3.rst:393 msgid "PEP written and implemented by Antoine Pitrou" -msgstr "" +msgstr "PEP escrita e implmentada por Antoine Pitrou" #: ../../whatsnew/3.3.rst:402 msgid "PEP 380: Syntax for Delegating to a Subgenerator" @@ -635,6 +652,16 @@ msgid "" "shortened form of ``for item in iterable: yield item``::" msgstr "" +#: ../../whatsnew/3.3.rst:417 +msgid "" +">>> def g(x):\n" +"... yield from range(x, 0, -1)\n" +"... yield from range(x)\n" +"...\n" +">>> list(g(5))\n" +"[5, 4, 3, 2, 1, 0, 1, 2, 3, 4]" +msgstr "" + #: ../../whatsnew/3.3.rst:424 msgid "" "However, unlike an ordinary loop, ``yield from`` allows subgenerators to " @@ -642,6 +669,36 @@ msgid "" "final value to the outer generator::" msgstr "" +#: ../../whatsnew/3.3.rst:428 +msgid "" +">>> def accumulate():\n" +"... tally = 0\n" +"... while 1:\n" +"... next = yield\n" +"... if next is None:\n" +"... return tally\n" +"... tally += next\n" +"...\n" +">>> def gather_tallies(tallies):\n" +"... while 1:\n" +"... tally = yield from accumulate()\n" +"... tallies.append(tally)\n" +"...\n" +">>> tallies = []\n" +">>> acc = gather_tallies(tallies)\n" +">>> next(acc) # Ensure the accumulator is ready to accept values\n" +">>> for i in range(4):\n" +"... acc.send(i)\n" +"...\n" +">>> acc.send(None) # Finish the first tally\n" +">>> for i in range(5):\n" +"... acc.send(i)\n" +"...\n" +">>> acc.send(None) # Finish the second tally\n" +">>> tallies\n" +"[6, 10]" +msgstr "" + #: ../../whatsnew/3.3.rst:455 msgid "" "The main principle driving this change is to allow even generators that are " @@ -672,12 +729,54 @@ msgid "" "applications that convert between exception types::" msgstr "" +#: ../../whatsnew/3.3.rst:475 +msgid "" +">>> class D:\n" +"... def __init__(self, extra):\n" +"... self._extra_attributes = extra\n" +"... def __getattr__(self, attr):\n" +"... try:\n" +"... return self._extra_attributes[attr]\n" +"... except KeyError:\n" +"... raise AttributeError(attr) from None\n" +"...\n" +">>> D({}).x\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" File \"\", line 8, in __getattr__\n" +"AttributeError: x" +msgstr "" + #: ../../whatsnew/3.3.rst:490 msgid "" "Without the ``from None`` suffix to suppress the cause, the original " "exception would be displayed by default::" msgstr "" +#: ../../whatsnew/3.3.rst:493 +msgid "" +">>> class C:\n" +"... def __init__(self, extra):\n" +"... self._extra_attributes = extra\n" +"... def __getattr__(self, attr):\n" +"... try:\n" +"... return self._extra_attributes[attr]\n" +"... except KeyError:\n" +"... raise AttributeError(attr)\n" +"...\n" +">>> C({}).x\n" +"Traceback (most recent call last):\n" +" File \"\", line 6, in __getattr__\n" +"KeyError: 'x'\n" +"\n" +"During handling of the above exception, another exception occurred:\n" +"\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" File \"\", line 8, in __getattr__\n" +"AttributeError: x" +msgstr "" + #: ../../whatsnew/3.3.rst:514 msgid "" "No debugging capability is lost, as the original exception context remains " @@ -685,6 +784,16 @@ msgid "" "suppressed valuable underlying details)::" msgstr "" +#: ../../whatsnew/3.3.rst:518 +msgid "" +">>> try:\n" +"... D({}).x\n" +"... except AttributeError as exc:\n" +"... print(repr(exc.__context__))\n" +"...\n" +"KeyError('x',)" +msgstr "" + #: ../../whatsnew/3.3.rst:527 msgid ":pep:`409` - Suppressing exception context" msgstr "" @@ -723,45 +832,95 @@ msgstr "" #: ../../whatsnew/3.3.rst:552 msgid "" -"Functions and class objects have a new ``__qualname__`` attribute " -"representing the \"path\" from the module top-level to their definition. " -"For global functions and classes, this is the same as ``__name__``. For " -"other functions and classes, it provides better information about where they " -"were actually defined, and how they might be accessible from the global " -"scope." +"Functions and class objects have a new :attr:`~definition.__qualname__` " +"attribute representing the \"path\" from the module top-level to their " +"definition. For global functions and classes, this is the same as :attr:" +"`~definition.__name__`. For other functions and classes, it provides better " +"information about where they were actually defined, and how they might be " +"accessible from the global scope." msgstr "" -#: ../../whatsnew/3.3.rst:558 +#: ../../whatsnew/3.3.rst:560 msgid "Example with (non-bound) methods::" msgstr "" -#: ../../whatsnew/3.3.rst:569 +#: ../../whatsnew/3.3.rst:562 +msgid "" +">>> class C:\n" +"... def meth(self):\n" +"... pass\n" +"...\n" +">>> C.meth.__name__\n" +"'meth'\n" +">>> C.meth.__qualname__\n" +"'C.meth'" +msgstr "" + +#: ../../whatsnew/3.3.rst:571 msgid "Example with nested classes::" msgstr "" -#: ../../whatsnew/3.3.rst:585 +#: ../../whatsnew/3.3.rst:573 +msgid "" +">>> class C:\n" +"... class D:\n" +"... def meth(self):\n" +"... pass\n" +"...\n" +">>> C.D.__name__\n" +"'D'\n" +">>> C.D.__qualname__\n" +"'C.D'\n" +">>> C.D.meth.__name__\n" +"'meth'\n" +">>> C.D.meth.__qualname__\n" +"'C.D.meth'" +msgstr "" + +#: ../../whatsnew/3.3.rst:587 msgid "Example with nested functions::" msgstr "" -#: ../../whatsnew/3.3.rst:597 +#: ../../whatsnew/3.3.rst:589 +msgid "" +">>> def outer():\n" +"... def inner():\n" +"... pass\n" +"... return inner\n" +"...\n" +">>> outer().__name__\n" +"'inner'\n" +">>> outer().__qualname__\n" +"'outer..inner'" +msgstr "" + +#: ../../whatsnew/3.3.rst:599 msgid "" "The string representation of those objects is also changed to include the " "new, more precise information::" msgstr "" -#: ../../whatsnew/3.3.rst:607 +#: ../../whatsnew/3.3.rst:602 +msgid "" +">>> str(C.D)\n" +"\"\"\n" +">>> str(C.D.meth)\n" +"''" +msgstr "" + +#: ../../whatsnew/3.3.rst:609 msgid ":pep:`3155` - Qualified name for classes and functions" msgstr "" -#: ../../whatsnew/3.3.rst:608 +#: ../../whatsnew/3.3.rst:610 msgid "PEP written and implemented by Antoine Pitrou." msgstr "PEP escrita e implementada por Antoine Pitrou." -#: ../../whatsnew/3.3.rst:614 +#: ../../whatsnew/3.3.rst:616 msgid "PEP 412: Key-Sharing Dictionary" msgstr "" -#: ../../whatsnew/3.3.rst:616 +#: ../../whatsnew/3.3.rst:618 msgid "" "Dictionaries used for the storage of objects' attributes are now able to " "share part of their internal storage between each other (namely, the part " @@ -769,19 +928,19 @@ msgid "" "consumption of programs creating many instances of non-builtin types." msgstr "" -#: ../../whatsnew/3.3.rst:623 +#: ../../whatsnew/3.3.rst:625 msgid ":pep:`412` - Key-Sharing Dictionary" msgstr "" -#: ../../whatsnew/3.3.rst:624 +#: ../../whatsnew/3.3.rst:626 msgid "PEP written and implemented by Mark Shannon." msgstr "" -#: ../../whatsnew/3.3.rst:628 +#: ../../whatsnew/3.3.rst:630 msgid "PEP 362: Function Signature Object" msgstr "" -#: ../../whatsnew/3.3.rst:630 +#: ../../whatsnew/3.3.rst:632 msgid "" "A new function :func:`inspect.signature` makes introspection of python " "callables easy and straightforward. A broad range of callables is " @@ -793,21 +952,21 @@ msgid "" "code that validates or amends calling signatures or arguments." msgstr "" -#: ../../whatsnew/3.3.rst:641 +#: ../../whatsnew/3.3.rst:643 msgid ":pep:`362`: - Function Signature Object" msgstr "" -#: ../../whatsnew/3.3.rst:642 +#: ../../whatsnew/3.3.rst:644 msgid "" "PEP written by Brett Cannon, Yury Selivanov, Larry Hastings, Jiwon Seo; " "implemented by Yury Selivanov." msgstr "" -#: ../../whatsnew/3.3.rst:647 +#: ../../whatsnew/3.3.rst:649 msgid "PEP 421: Adding sys.implementation" msgstr "" -#: ../../whatsnew/3.3.rst:649 +#: ../../whatsnew/3.3.rst:651 msgid "" "A new attribute on the :mod:`sys` module exposes details specific to the " "implementation of the currently running interpreter. The initial set of " @@ -815,7 +974,7 @@ msgid "" "``hexversion``, and ``cache_tag``." msgstr "" -#: ../../whatsnew/3.3.rst:654 +#: ../../whatsnew/3.3.rst:656 msgid "" "The intention of ``sys.implementation`` is to consolidate into one namespace " "the implementation-specific data used by the standard library. This allows " @@ -825,7 +984,7 @@ msgid "" "ratio will shift in order to make the standard library more portable." msgstr "" -#: ../../whatsnew/3.3.rst:661 +#: ../../whatsnew/3.3.rst:663 msgid "" "One example of improved standard library portability is ``cache_tag``. As " "of Python 3.3, ``sys.implementation.cache_tag`` is used by :mod:`importlib` " @@ -834,11 +993,11 @@ msgid "" "control the caching behavior for modules." msgstr "" -#: ../../whatsnew/3.3.rst:668 +#: ../../whatsnew/3.3.rst:670 msgid "SimpleNamespace" msgstr "" -#: ../../whatsnew/3.3.rst:670 +#: ../../whatsnew/3.3.rst:672 msgid "" "The implementation of ``sys.implementation`` also introduces a new type to " "Python: :class:`types.SimpleNamespace`. In contrast to a mapping-based " @@ -848,19 +1007,19 @@ msgid "" "through normal attribute access." msgstr "" -#: ../../whatsnew/3.3.rst:679 +#: ../../whatsnew/3.3.rst:681 msgid ":pep:`421` - Adding sys.implementation" msgstr "" -#: ../../whatsnew/3.3.rst:680 +#: ../../whatsnew/3.3.rst:682 msgid "PEP written and implemented by Eric Snow." msgstr "PEP written and implemented by Eric Snow." -#: ../../whatsnew/3.3.rst:686 +#: ../../whatsnew/3.3.rst:688 msgid "Using importlib as the Implementation of Import" msgstr "" -#: ../../whatsnew/3.3.rst:687 +#: ../../whatsnew/3.3.rst:689 msgid "" ":issue:`2377` - Replace __import__ w/ importlib.__import__ :issue:`13959` - " "Re-implement parts of :mod:`!imp` in pure Python :issue:`14605` - Make " @@ -868,7 +1027,7 @@ msgid "" "and __package__" msgstr "" -#: ../../whatsnew/3.3.rst:692 +#: ../../whatsnew/3.3.rst:694 msgid "" "The :func:`__import__` function is now powered by :func:`importlib." "__import__`. This work leads to the completion of \"phase 2\" of :pep:`302`. " @@ -880,7 +1039,7 @@ msgid "" "import, allowing for future growth to occur." msgstr "" -#: ../../whatsnew/3.3.rst:701 +#: ../../whatsnew/3.3.rst:703 msgid "" "For the common user, there should be no visible change in semantics. For " "those whose code currently manipulates import or calls import " @@ -888,18 +1047,18 @@ msgid "" "covered in the `Porting Python code`_ section of this document." msgstr "" -#: ../../whatsnew/3.3.rst:707 +#: ../../whatsnew/3.3.rst:709 msgid "New APIs" msgstr "" -#: ../../whatsnew/3.3.rst:708 +#: ../../whatsnew/3.3.rst:710 msgid "" "One of the large benefits of this work is the exposure of what goes into " "making the import statement work. That means the various importers that were " "once implicit are now fully exposed as part of the :mod:`importlib` package." msgstr "" -#: ../../whatsnew/3.3.rst:712 +#: ../../whatsnew/3.3.rst:714 msgid "" "The abstract base classes defined in :mod:`importlib.abc` have been expanded " "to properly delineate between :term:`meta path finders ` " @@ -910,14 +1069,14 @@ msgid "" "requirements." msgstr "" -#: ../../whatsnew/3.3.rst:720 +#: ../../whatsnew/3.3.rst:722 msgid "" "In terms of finders, :class:`importlib.machinery.FileFinder` exposes the " "mechanism used to search for source and bytecode files of a module. " "Previously this class was an implicit member of :data:`sys.path_hooks`." msgstr "" -#: ../../whatsnew/3.3.rst:724 +#: ../../whatsnew/3.3.rst:726 msgid "" "For loaders, the new abstract base class :class:`importlib.abc.FileLoader` " "helps write a loader that uses the file system as the storage mechanism for " @@ -927,7 +1086,7 @@ msgid "" "ExtensionFileLoader`) are now available for direct use." msgstr "" -#: ../../whatsnew/3.3.rst:732 +#: ../../whatsnew/3.3.rst:734 msgid "" ":exc:`ImportError` now has ``name`` and ``path`` attributes which are set " "when there is relevant data to provide. The message for failed imports will " @@ -935,24 +1094,24 @@ msgid "" "the module's name." msgstr "" -#: ../../whatsnew/3.3.rst:737 +#: ../../whatsnew/3.3.rst:739 msgid "" "The :func:`importlib.invalidate_caches` function will now call the method " "with the same name on all finders cached in :data:`sys.path_importer_cache` " "to help clean up any stored state as necessary." msgstr "" -#: ../../whatsnew/3.3.rst:742 +#: ../../whatsnew/3.3.rst:744 msgid "Visible Changes" msgstr "" -#: ../../whatsnew/3.3.rst:744 +#: ../../whatsnew/3.3.rst:746 msgid "" "For potential required changes to code, see the `Porting Python code`_ " "section." msgstr "" -#: ../../whatsnew/3.3.rst:747 +#: ../../whatsnew/3.3.rst:749 msgid "" "Beyond the expanse of what :mod:`importlib` now exposes, there are other " "visible changes to import. The biggest is that :data:`sys.meta_path` and :" @@ -963,7 +1122,7 @@ msgid "" "fit one's needs." msgstr "" -#: ../../whatsnew/3.3.rst:754 +#: ../../whatsnew/3.3.rst:756 msgid "" "Another change is that all modules have a ``__loader__`` attribute, storing " "the loader used to create the module. :pep:`302` has been updated to make " @@ -973,14 +1132,14 @@ msgid "" "load." msgstr "" -#: ../../whatsnew/3.3.rst:760 +#: ../../whatsnew/3.3.rst:762 msgid "" "Loaders are also now expected to set the ``__package__`` attribute from :pep:" "`366`. Once again, import itself is already setting this on all loaders " "from :mod:`importlib` and import itself is setting the attribute post-load." msgstr "" -#: ../../whatsnew/3.3.rst:764 +#: ../../whatsnew/3.3.rst:766 msgid "" "``None`` is now inserted into :data:`sys.path_importer_cache` when no finder " "can be found on :data:`sys.path_hooks`. Since :class:`!imp.NullImporter` is " @@ -988,66 +1147,66 @@ msgid "" "upon to always be available to use as a value representing no finder found." msgstr "" -#: ../../whatsnew/3.3.rst:769 +#: ../../whatsnew/3.3.rst:771 msgid "" "All other changes relate to semantic changes which should be taken into " "consideration when updating code for Python 3.3, and thus should be read " "about in the `Porting Python code`_ section of this document." msgstr "" -#: ../../whatsnew/3.3.rst:773 +#: ../../whatsnew/3.3.rst:775 msgid "(Implementation by Brett Cannon)" msgstr "" -#: ../../whatsnew/3.3.rst:777 +#: ../../whatsnew/3.3.rst:779 msgid "Other Language Changes" msgstr "Outras mudanças na linguagem" -#: ../../whatsnew/3.3.rst:779 +#: ../../whatsnew/3.3.rst:781 msgid "Some smaller changes made to the core Python language are:" -msgstr "Alguma das mudanças menores feitas no núcleo da linguagem Python são:" +msgstr "Algumas das mudanças menores feitas no núcleo da linguagem Python são:" -#: ../../whatsnew/3.3.rst:781 +#: ../../whatsnew/3.3.rst:783 msgid "" "Added support for Unicode name aliases and named sequences. Both :func:" -"`unicodedata.lookup()` and ``'\\N{...}'`` now resolve name aliases, and :" -"func:`unicodedata.lookup()` resolves named sequences too." +"`unicodedata.lookup` and ``'\\N{...}'`` now resolve name aliases, and :func:" +"`unicodedata.lookup` resolves named sequences too." msgstr "" -#: ../../whatsnew/3.3.rst:785 +#: ../../whatsnew/3.3.rst:787 msgid "(Contributed by Ezio Melotti in :issue:`12753`.)" msgstr "" -#: ../../whatsnew/3.3.rst:787 +#: ../../whatsnew/3.3.rst:789 msgid "Unicode database updated to UCD version 6.1.0" msgstr "" -#: ../../whatsnew/3.3.rst:789 +#: ../../whatsnew/3.3.rst:791 msgid "" "Equality comparisons on :func:`range` objects now return a result reflecting " "the equality of the underlying sequences generated by those range objects. (:" "issue:`13201`)" msgstr "" -#: ../../whatsnew/3.3.rst:793 +#: ../../whatsnew/3.3.rst:795 msgid "" "The ``count()``, ``find()``, ``rfind()``, ``index()`` and ``rindex()`` " "methods of :class:`bytes` and :class:`bytearray` objects now accept an " "integer between 0 and 255 as their first argument." msgstr "" -#: ../../whatsnew/3.3.rst:797 +#: ../../whatsnew/3.3.rst:799 msgid "(Contributed by Petri Lehtinen in :issue:`12170`.)" msgstr "" -#: ../../whatsnew/3.3.rst:799 +#: ../../whatsnew/3.3.rst:801 msgid "" "The ``rjust()``, ``ljust()``, and ``center()`` methods of :class:`bytes` " "and :class:`bytearray` now accept a :class:`bytearray` for the ``fill`` " "argument. (Contributed by Petri Lehtinen in :issue:`12380`.)" msgstr "" -#: ../../whatsnew/3.3.rst:803 +#: ../../whatsnew/3.3.rst:805 msgid "" "New methods have been added to :class:`list` and :class:`bytearray`: " "``copy()`` and ``clear()`` (:issue:`10516`). Consequently, :class:" @@ -1055,40 +1214,40 @@ msgid "" "abc.MutableSequence.clear` method (:issue:`11388`)." msgstr "" -#: ../../whatsnew/3.3.rst:808 +#: ../../whatsnew/3.3.rst:810 msgid "" "Raw bytes literals can now be written ``rb\"...\"`` as well as ``br\"...\"``." msgstr "" -#: ../../whatsnew/3.3.rst:810 +#: ../../whatsnew/3.3.rst:812 msgid "(Contributed by Antoine Pitrou in :issue:`13748`.)" msgstr "" -#: ../../whatsnew/3.3.rst:812 +#: ../../whatsnew/3.3.rst:814 msgid "" ":meth:`dict.setdefault` now does only one lookup for the given key, making " "it atomic when used with built-in types." msgstr "" -#: ../../whatsnew/3.3.rst:815 +#: ../../whatsnew/3.3.rst:817 msgid "(Contributed by Filip Gruszczyński in :issue:`13521`.)" msgstr "" -#: ../../whatsnew/3.3.rst:817 +#: ../../whatsnew/3.3.rst:819 msgid "" "The error messages produced when a function call does not match the function " "signature have been significantly improved." msgstr "" -#: ../../whatsnew/3.3.rst:820 +#: ../../whatsnew/3.3.rst:822 msgid "(Contributed by Benjamin Peterson.)" msgstr "" -#: ../../whatsnew/3.3.rst:824 +#: ../../whatsnew/3.3.rst:826 msgid "A Finer-Grained Import Lock" msgstr "" -#: ../../whatsnew/3.3.rst:826 +#: ../../whatsnew/3.3.rst:828 msgid "" "Previous versions of CPython have always relied on a global import lock. " "This led to unexpected annoyances, such as deadlocks when importing a module " @@ -1097,7 +1256,7 @@ msgid "" "`PyImport_ImportModuleNoBlock` C API function." msgstr "" -#: ../../whatsnew/3.3.rst:832 +#: ../../whatsnew/3.3.rst:834 msgid "" "In Python 3.3, importing a module takes a per-module lock. This correctly " "serializes importation of a given module from multiple threads (preventing " @@ -1105,15 +1264,15 @@ msgid "" "aforementioned annoyances." msgstr "" -#: ../../whatsnew/3.3.rst:837 +#: ../../whatsnew/3.3.rst:839 msgid "(Contributed by Antoine Pitrou in :issue:`9260`.)" msgstr "" -#: ../../whatsnew/3.3.rst:841 +#: ../../whatsnew/3.3.rst:843 msgid "Builtin functions and types" msgstr "" -#: ../../whatsnew/3.3.rst:843 +#: ../../whatsnew/3.3.rst:845 msgid "" ":func:`open` gets a new *opener* parameter: the underlying file descriptor " "for the file object is then obtained by calling *opener* with (*file*, " @@ -1122,26 +1281,26 @@ msgid "" "the file already exists." msgstr "" -#: ../../whatsnew/3.3.rst:848 +#: ../../whatsnew/3.3.rst:850 msgid "" ":func:`print`: added the *flush* keyword argument. If the *flush* keyword " "argument is true, the stream is forcibly flushed." msgstr "" -#: ../../whatsnew/3.3.rst:850 +#: ../../whatsnew/3.3.rst:852 msgid "" ":func:`hash`: hash randomization is enabled by default, see :meth:`object." "__hash__` and :envvar:`PYTHONHASHSEED`." msgstr "" -#: ../../whatsnew/3.3.rst:852 +#: ../../whatsnew/3.3.rst:854 msgid "" "The :class:`str` type gets a new :meth:`~str.casefold` method: return a " "casefolded copy of the string, casefolded strings may be used for caseless " "matching. For example, ``'ß'.casefold()`` returns ``'ss'``." msgstr "" -#: ../../whatsnew/3.3.rst:855 +#: ../../whatsnew/3.3.rst:857 msgid "" "The sequence documentation has been substantially rewritten to better " "explain the binary/text sequence distinction and to provide specific " @@ -1149,15 +1308,15 @@ msgid "" "`4966`)." msgstr "" -#: ../../whatsnew/3.3.rst:862 +#: ../../whatsnew/3.3.rst:864 msgid "New Modules" msgstr "Novos módulos" -#: ../../whatsnew/3.3.rst:865 +#: ../../whatsnew/3.3.rst:867 msgid "faulthandler" msgstr "faulthandler" -#: ../../whatsnew/3.3.rst:867 +#: ../../whatsnew/3.3.rst:869 msgid "" "This new debug module :mod:`faulthandler` contains functions to dump Python " "tracebacks explicitly, on a fault (a crash like a segmentation fault), after " @@ -1168,49 +1327,63 @@ msgid "" "by using :option:`-X` ``faulthandler`` command line option." msgstr "" -#: ../../whatsnew/3.3.rst:875 +#: ../../whatsnew/3.3.rst:877 msgid "Example of a segmentation fault on Linux:" msgstr "" -#: ../../whatsnew/3.3.rst:891 +#: ../../whatsnew/3.3.rst:879 +msgid "" +"$ python -q -X faulthandler\n" +">>> import ctypes\n" +">>> ctypes.string_at(0)\n" +"Fatal Python error: Segmentation fault\n" +"\n" +"Current thread 0x00007fb899f39700:\n" +" File \"/home/python/cpython/Lib/ctypes/__init__.py\", line 486 in " +"string_at\n" +" File \"\", line 1 in \n" +"Segmentation fault" +msgstr "" + +#: ../../whatsnew/3.3.rst:893 msgid "ipaddress" msgstr "ipaddress" -#: ../../whatsnew/3.3.rst:893 +#: ../../whatsnew/3.3.rst:895 msgid "" "The new :mod:`ipaddress` module provides tools for creating and manipulating " "objects representing IPv4 and IPv6 addresses, networks and interfaces (i.e. " "an IP address associated with a specific IP subnet)." msgstr "" -#: ../../whatsnew/3.3.rst:897 +#: ../../whatsnew/3.3.rst:899 msgid "(Contributed by Google and Peter Moody in :pep:`3144`.)" msgstr "" -#: ../../whatsnew/3.3.rst:900 +#: ../../whatsnew/3.3.rst:902 msgid "lzma" msgstr "lzma" -#: ../../whatsnew/3.3.rst:902 +#: ../../whatsnew/3.3.rst:904 msgid "" "The newly added :mod:`lzma` module provides data compression and " "decompression using the LZMA algorithm, including support for the ``.xz`` " "and ``.lzma`` file formats." msgstr "" -#: ../../whatsnew/3.3.rst:906 +#: ../../whatsnew/3.3.rst:908 msgid "(Contributed by Nadeem Vawda and Per Øyvind Karlsen in :issue:`6715`.)" msgstr "" -#: ../../whatsnew/3.3.rst:910 +#: ../../whatsnew/3.3.rst:912 msgid "Improved Modules" msgstr "Módulos melhorados" -#: ../../whatsnew/3.3.rst:913 +#: ../../whatsnew/3.3.rst:915 msgid "abc" msgstr "abc" -#: ../../whatsnew/3.3.rst:915 +#: ../../whatsnew/3.3.rst:917 msgid "" "Improved support for abstract base classes containing descriptors composed " "with abstract methods. The recommended approach to declaring abstract " @@ -1218,53 +1391,53 @@ msgid "" "updated property. The built-in descriptors have been updated accordingly." msgstr "" -#: ../../whatsnew/3.3.rst:920 ../../whatsnew/3.3.rst:2246 +#: ../../whatsnew/3.3.rst:922 ../../whatsnew/3.3.rst:2248 msgid "" ":class:`abc.abstractproperty` has been deprecated, use :class:`property` " "with :func:`abc.abstractmethod` instead." msgstr "" -#: ../../whatsnew/3.3.rst:922 ../../whatsnew/3.3.rst:2248 +#: ../../whatsnew/3.3.rst:924 ../../whatsnew/3.3.rst:2250 msgid "" ":class:`abc.abstractclassmethod` has been deprecated, use :class:" "`classmethod` with :func:`abc.abstractmethod` instead." msgstr "" -#: ../../whatsnew/3.3.rst:924 ../../whatsnew/3.3.rst:2250 +#: ../../whatsnew/3.3.rst:926 ../../whatsnew/3.3.rst:2252 msgid "" ":class:`abc.abstractstaticmethod` has been deprecated, use :class:" "`staticmethod` with :func:`abc.abstractmethod` instead." msgstr "" -#: ../../whatsnew/3.3.rst:927 +#: ../../whatsnew/3.3.rst:929 msgid "(Contributed by Darren Dale in :issue:`11610`.)" msgstr "" -#: ../../whatsnew/3.3.rst:929 +#: ../../whatsnew/3.3.rst:931 msgid "" ":meth:`abc.ABCMeta.register` now returns the registered subclass, which " "means it can now be used as a class decorator (:issue:`10868`)." msgstr "" -#: ../../whatsnew/3.3.rst:934 +#: ../../whatsnew/3.3.rst:936 msgid "array" msgstr "array" -#: ../../whatsnew/3.3.rst:936 +#: ../../whatsnew/3.3.rst:938 msgid "" "The :mod:`array` module supports the :c:expr:`long long` type using ``q`` " "and ``Q`` type codes." msgstr "" -#: ../../whatsnew/3.3.rst:939 +#: ../../whatsnew/3.3.rst:941 msgid "(Contributed by Oren Tirosh and Hirokazu Yamamoto in :issue:`1172711`.)" msgstr "" -#: ../../whatsnew/3.3.rst:943 +#: ../../whatsnew/3.3.rst:945 msgid "base64" msgstr "base64" -#: ../../whatsnew/3.3.rst:945 +#: ../../whatsnew/3.3.rst:947 msgid "" "ASCII-only Unicode strings are now accepted by the decoding functions of " "the :mod:`base64` modern interface. For example, ``base64." @@ -1272,44 +1445,44 @@ msgid "" "issue:`13641`.)" msgstr "" -#: ../../whatsnew/3.3.rst:951 +#: ../../whatsnew/3.3.rst:953 msgid "binascii" msgstr "binascii" -#: ../../whatsnew/3.3.rst:953 +#: ../../whatsnew/3.3.rst:955 msgid "" "In addition to the binary objects they normally accept, the ``a2b_`` " "functions now all also accept ASCII-only strings as input. (Contributed by " "Antoine Pitrou in :issue:`13637`.)" msgstr "" -#: ../../whatsnew/3.3.rst:959 +#: ../../whatsnew/3.3.rst:961 msgid "bz2" msgstr "bz2" -#: ../../whatsnew/3.3.rst:961 +#: ../../whatsnew/3.3.rst:963 msgid "" "The :mod:`bz2` module has been rewritten from scratch. In the process, " "several new features have been added:" msgstr "" -#: ../../whatsnew/3.3.rst:964 +#: ../../whatsnew/3.3.rst:966 msgid "" "New :func:`bz2.open` function: open a bzip2-compressed file in binary or " "text mode." msgstr "" -#: ../../whatsnew/3.3.rst:967 +#: ../../whatsnew/3.3.rst:969 msgid "" ":class:`bz2.BZ2File` can now read from and write to arbitrary file-like " "objects, by means of its constructor's *fileobj* argument." msgstr "" -#: ../../whatsnew/3.3.rst:970 +#: ../../whatsnew/3.3.rst:972 msgid "(Contributed by Nadeem Vawda in :issue:`5863`.)" msgstr "" -#: ../../whatsnew/3.3.rst:972 +#: ../../whatsnew/3.3.rst:974 msgid "" ":class:`bz2.BZ2File` and :func:`bz2.decompress` can now decompress multi-" "stream inputs (such as those produced by the :program:`pbzip2` tool). :class:" @@ -1317,21 +1490,21 @@ msgid "" "``'a'`` (append) mode." msgstr "" -#: ../../whatsnew/3.3.rst:977 +#: ../../whatsnew/3.3.rst:979 msgid "(Contributed by Nir Aides in :issue:`1625`.)" msgstr "" -#: ../../whatsnew/3.3.rst:979 +#: ../../whatsnew/3.3.rst:981 msgid "" ":class:`bz2.BZ2File` now implements all of the :class:`io.BufferedIOBase` " "API, except for the :meth:`detach` and :meth:`truncate` methods." msgstr "" -#: ../../whatsnew/3.3.rst:984 +#: ../../whatsnew/3.3.rst:986 msgid "codecs" msgstr "codecs" -#: ../../whatsnew/3.3.rst:986 +#: ../../whatsnew/3.3.rst:988 msgid "" "The :mod:`~encodings.mbcs` codec has been rewritten to handle correctly " "``replace`` and ``ignore`` error handlers on all Windows versions. The :mod:" @@ -1339,7 +1512,7 @@ msgid "" "``replace`` to encode and ``ignore`` to decode." msgstr "" -#: ../../whatsnew/3.3.rst:991 +#: ../../whatsnew/3.3.rst:993 msgid "" "A new Windows-only codec has been added: ``cp65001`` (:issue:`13216`). It is " "the Windows code page 65001 (Windows UTF-8, ``CP_UTF8``). For example, it " @@ -1347,7 +1520,7 @@ msgid "" "(e.g., using ``chcp 65001`` command)." msgstr "" -#: ../../whatsnew/3.3.rst:996 +#: ../../whatsnew/3.3.rst:998 msgid "" "Multibyte CJK decoders now resynchronize faster. They only ignore the first " "byte of an invalid byte sequence. For example, ``b'\\xff\\n'." @@ -1355,42 +1528,51 @@ msgid "" "character." msgstr "" -#: ../../whatsnew/3.3.rst:1000 +#: ../../whatsnew/3.3.rst:1002 msgid "(:issue:`12016`)" msgstr "" -#: ../../whatsnew/3.3.rst:1002 +#: ../../whatsnew/3.3.rst:1004 msgid "" "Incremental CJK codec encoders are no longer reset at each call to their " "encode() methods. For example::" msgstr "" -#: ../../whatsnew/3.3.rst:1010 +#: ../../whatsnew/3.3.rst:1007 +msgid "" +">>> import codecs\n" +">>> encoder = codecs.getincrementalencoder('hz')('strict')\n" +">>> b''.join(encoder.encode(x) for x in '\\u52ff\\u65bd\\u65bc\\u4eba\\u3002 " +"Bye.')\n" +"b'~{NpJ)l6HK!#~} Bye.'" +msgstr "" + +#: ../../whatsnew/3.3.rst:1012 msgid "" "This example gives ``b'~{Np~}~{J)~}~{l6~}~{HK~}~{!#~} Bye.'`` with older " "Python versions." msgstr "" -#: ../../whatsnew/3.3.rst:1013 +#: ../../whatsnew/3.3.rst:1015 msgid "(:issue:`12100`)" msgstr "" -#: ../../whatsnew/3.3.rst:1015 +#: ../../whatsnew/3.3.rst:1017 msgid "The ``unicode_internal`` codec has been deprecated." msgstr "" -#: ../../whatsnew/3.3.rst:1019 +#: ../../whatsnew/3.3.rst:1021 msgid "collections" msgstr "collections" -#: ../../whatsnew/3.3.rst:1021 +#: ../../whatsnew/3.3.rst:1023 msgid "" "Addition of a new :class:`~collections.ChainMap` class to allow treating a " "number of mappings as a single unit. (Written by Raymond Hettinger for :" "issue:`11089`, made public in :issue:`11297`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1025 +#: ../../whatsnew/3.3.rst:1027 msgid "" "The abstract base classes have been moved in a new :mod:`collections.abc` " "module, to better differentiate between the abstract and the concrete " @@ -1398,18 +1580,18 @@ msgid "" "`collections` module to preserve existing imports. (:issue:`11085`)" msgstr "" -#: ../../whatsnew/3.3.rst:1032 +#: ../../whatsnew/3.3.rst:1034 msgid "" "The :class:`~collections.Counter` class now supports the unary ``+`` and ``-" "`` operators, as well as the in-place operators ``+=``, ``-=``, ``|=``, and " "``&=``. (Contributed by Raymond Hettinger in :issue:`13121`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1038 +#: ../../whatsnew/3.3.rst:1040 msgid "contextlib" msgstr "contextlib" -#: ../../whatsnew/3.3.rst:1040 +#: ../../whatsnew/3.3.rst:1042 msgid "" ":class:`~contextlib.ExitStack` now provides a solid foundation for " "programmatic manipulation of context managers and similar cleanup " @@ -1421,103 +1603,103 @@ msgid "" "module)." msgstr "" -#: ../../whatsnew/3.3.rst:1049 +#: ../../whatsnew/3.3.rst:1051 msgid "(:issue:`13585`)" msgstr "" -#: ../../whatsnew/3.3.rst:1053 +#: ../../whatsnew/3.3.rst:1055 msgid "crypt" msgstr "crypt" -#: ../../whatsnew/3.3.rst:1055 +#: ../../whatsnew/3.3.rst:1057 msgid "" "Addition of salt and modular crypt format (hashing method) and the :func:`!" "mksalt` function to the :mod:`!crypt` module." msgstr "" -#: ../../whatsnew/3.3.rst:1058 +#: ../../whatsnew/3.3.rst:1060 msgid "(:issue:`10924`)" msgstr "" -#: ../../whatsnew/3.3.rst:1061 +#: ../../whatsnew/3.3.rst:1063 msgid "curses" msgstr "curses" -#: ../../whatsnew/3.3.rst:1063 +#: ../../whatsnew/3.3.rst:1065 msgid "" "If the :mod:`curses` module is linked to the ncursesw library, use Unicode " "functions when Unicode strings or characters are passed (e.g. :c:func:" "`waddwstr`), and bytes functions otherwise (e.g. :c:func:`waddstr`)." msgstr "" -#: ../../whatsnew/3.3.rst:1066 +#: ../../whatsnew/3.3.rst:1068 msgid "Use the locale encoding instead of ``utf-8`` to encode Unicode strings." msgstr "" -#: ../../whatsnew/3.3.rst:1067 +#: ../../whatsnew/3.3.rst:1069 msgid "" ":class:`curses.window` has a new :attr:`curses.window.encoding` attribute." msgstr "" -#: ../../whatsnew/3.3.rst:1068 +#: ../../whatsnew/3.3.rst:1070 msgid "" "The :class:`curses.window` class has a new :meth:`~curses.window.get_wch` " "method to get a wide character" msgstr "" -#: ../../whatsnew/3.3.rst:1070 +#: ../../whatsnew/3.3.rst:1072 msgid "" "The :mod:`curses` module has a new :meth:`~curses.unget_wch` function to " "push a wide character so the next :meth:`~curses.window.get_wch` will return " "it" msgstr "" -#: ../../whatsnew/3.3.rst:1074 +#: ../../whatsnew/3.3.rst:1076 msgid "(Contributed by Iñigo Serna in :issue:`6755`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1077 +#: ../../whatsnew/3.3.rst:1079 msgid "datetime" msgstr "datetime" -#: ../../whatsnew/3.3.rst:1079 +#: ../../whatsnew/3.3.rst:1081 msgid "" "Equality comparisons between naive and aware :class:`~datetime.datetime` " "instances now return :const:`False` instead of raising :exc:`TypeError` (:" "issue:`15006`)." msgstr "" -#: ../../whatsnew/3.3.rst:1082 +#: ../../whatsnew/3.3.rst:1084 msgid "" "New :meth:`datetime.datetime.timestamp` method: Return POSIX timestamp " "corresponding to the :class:`~datetime.datetime` instance." msgstr "" -#: ../../whatsnew/3.3.rst:1084 +#: ../../whatsnew/3.3.rst:1086 msgid "" "The :meth:`datetime.datetime.strftime` method supports formatting years " "older than 1000." msgstr "" -#: ../../whatsnew/3.3.rst:1086 +#: ../../whatsnew/3.3.rst:1088 msgid "" "The :meth:`datetime.datetime.astimezone` method can now be called without " "arguments to convert datetime instance to the system timezone." msgstr "" -#: ../../whatsnew/3.3.rst:1094 +#: ../../whatsnew/3.3.rst:1096 msgid "decimal" msgstr "decimal" -#: ../../whatsnew/3.3.rst:1096 +#: ../../whatsnew/3.3.rst:1098 msgid ":issue:`7652` - integrate fast native decimal arithmetic." msgstr "" -#: ../../whatsnew/3.3.rst:1097 +#: ../../whatsnew/3.3.rst:1099 msgid "C-module and libmpdec written by Stefan Krah." msgstr "" -#: ../../whatsnew/3.3.rst:1099 +#: ../../whatsnew/3.3.rst:1101 msgid "" "The new C version of the decimal module integrates the high speed libmpdec " "library for arbitrary precision correctly rounded decimal floating-point " @@ -1529,7 +1711,7 @@ msgstr "" "arithmetic. libmpdec conforms to IBM's General Decimal Arithmetic " "Specification." -#: ../../whatsnew/3.3.rst:1103 +#: ../../whatsnew/3.3.rst:1105 msgid "" "Performance gains range from 10x for database applications to 100x for " "numerically intensive applications. These numbers are expected gains for " @@ -1543,136 +1725,136 @@ msgstr "" "precision is user configurable, the exact figures may vary. For example, in " "integer bignum arithmetic the differences can be significantly higher." -#: ../../whatsnew/3.3.rst:1109 +#: ../../whatsnew/3.3.rst:1111 msgid "" "The following table is meant as an illustration. Benchmarks are available at " "https://www.bytereef.org/mpdecimal/quickstart.html." msgstr "" -#: ../../whatsnew/3.3.rst:1113 +#: ../../whatsnew/3.3.rst:1115 msgid "decimal.py" msgstr "" -#: ../../whatsnew/3.3.rst:1113 +#: ../../whatsnew/3.3.rst:1115 msgid "_decimal" msgstr "" -#: ../../whatsnew/3.3.rst:1113 +#: ../../whatsnew/3.3.rst:1115 msgid "speedup" msgstr "" -#: ../../whatsnew/3.3.rst:1115 +#: ../../whatsnew/3.3.rst:1117 msgid "pi" msgstr "" -#: ../../whatsnew/3.3.rst:1115 +#: ../../whatsnew/3.3.rst:1117 msgid "42.02s" msgstr "" -#: ../../whatsnew/3.3.rst:1115 +#: ../../whatsnew/3.3.rst:1117 msgid "0.345s" msgstr "" -#: ../../whatsnew/3.3.rst:1115 +#: ../../whatsnew/3.3.rst:1117 msgid "120x" msgstr "" -#: ../../whatsnew/3.3.rst:1117 +#: ../../whatsnew/3.3.rst:1119 msgid "telco" msgstr "" -#: ../../whatsnew/3.3.rst:1117 +#: ../../whatsnew/3.3.rst:1119 msgid "172.19s" msgstr "" -#: ../../whatsnew/3.3.rst:1117 +#: ../../whatsnew/3.3.rst:1119 msgid "5.68s" msgstr "" -#: ../../whatsnew/3.3.rst:1117 +#: ../../whatsnew/3.3.rst:1119 msgid "30x" msgstr "" -#: ../../whatsnew/3.3.rst:1119 +#: ../../whatsnew/3.3.rst:1121 msgid "psycopg" msgstr "" -#: ../../whatsnew/3.3.rst:1119 +#: ../../whatsnew/3.3.rst:1121 msgid "3.57s" msgstr "" -#: ../../whatsnew/3.3.rst:1119 +#: ../../whatsnew/3.3.rst:1121 msgid "0.29s" msgstr "" -#: ../../whatsnew/3.3.rst:1119 +#: ../../whatsnew/3.3.rst:1121 msgid "12x" msgstr "" -#: ../../whatsnew/3.3.rst:1125 +#: ../../whatsnew/3.3.rst:1127 msgid "" "The :exc:`~decimal.FloatOperation` signal optionally enables stricter " "semantics for mixing floats and Decimals." msgstr "" -#: ../../whatsnew/3.3.rst:1128 +#: ../../whatsnew/3.3.rst:1130 msgid "" "If Python is compiled without threads, the C version automatically disables " "the expensive thread local context machinery. In this case, the variable :" "const:`~decimal.HAVE_THREADS` is set to ``False``." msgstr "" -#: ../../whatsnew/3.3.rst:1135 +#: ../../whatsnew/3.3.rst:1137 msgid "" "The C module has the following context limits, depending on the machine " "architecture:" msgstr "" -#: ../../whatsnew/3.3.rst:1139 +#: ../../whatsnew/3.3.rst:1141 msgid "32-bit" msgstr "32 bits" -#: ../../whatsnew/3.3.rst:1139 +#: ../../whatsnew/3.3.rst:1141 msgid "64-bit" msgstr "64 bits" -#: ../../whatsnew/3.3.rst:1141 +#: ../../whatsnew/3.3.rst:1143 msgid ":const:`MAX_PREC`" msgstr ":const:`MAX_PREC`" -#: ../../whatsnew/3.3.rst:1141 ../../whatsnew/3.3.rst:1143 +#: ../../whatsnew/3.3.rst:1143 ../../whatsnew/3.3.rst:1145 msgid "``425000000``" msgstr "``425000000``" -#: ../../whatsnew/3.3.rst:1141 ../../whatsnew/3.3.rst:1143 +#: ../../whatsnew/3.3.rst:1143 ../../whatsnew/3.3.rst:1145 msgid "``999999999999999999``" msgstr "``999999999999999999``" -#: ../../whatsnew/3.3.rst:1143 +#: ../../whatsnew/3.3.rst:1145 msgid ":const:`MAX_EMAX`" msgstr ":const:`MAX_EMAX`" -#: ../../whatsnew/3.3.rst:1145 +#: ../../whatsnew/3.3.rst:1147 msgid ":const:`MIN_EMIN`" msgstr ":const:`MIN_EMIN`" -#: ../../whatsnew/3.3.rst:1145 +#: ../../whatsnew/3.3.rst:1147 msgid "``-425000000``" msgstr "``-425000000``" -#: ../../whatsnew/3.3.rst:1145 +#: ../../whatsnew/3.3.rst:1147 msgid "``-999999999999999999``" msgstr "``-999999999999999999``" -#: ../../whatsnew/3.3.rst:1148 +#: ../../whatsnew/3.3.rst:1150 msgid "" -"In the context templates (:class:`~decimal.DefaultContext`, :class:`~decimal." -"BasicContext` and :class:`~decimal.ExtendedContext`) the magnitude of :attr:" +"In the context templates (:const:`~decimal.DefaultContext`, :const:`~decimal." +"BasicContext` and :const:`~decimal.ExtendedContext`) the magnitude of :attr:" "`~decimal.Context.Emax` and :attr:`~decimal.Context.Emin` has changed to " "``999999``." msgstr "" -#: ../../whatsnew/3.3.rst:1153 +#: ../../whatsnew/3.3.rst:1155 msgid "" "The :class:`~decimal.Decimal` constructor in decimal.py does not observe the " "context limits and converts values with arbitrary exponents or precision " @@ -1683,7 +1865,7 @@ msgid "" "obtain a rounded or inexact value." msgstr "" -#: ../../whatsnew/3.3.rst:1162 +#: ../../whatsnew/3.3.rst:1164 msgid "" "The power function in decimal.py is always correctly rounded. In the C " "version, it is defined in terms of the correctly rounded :meth:`~decimal." @@ -1691,7 +1873,7 @@ msgid "" "is only \"almost always correctly rounded\"." msgstr "" -#: ../../whatsnew/3.3.rst:1168 +#: ../../whatsnew/3.3.rst:1170 msgid "" "In the C version, the context dictionary containing the signals is a :class:" "`~collections.abc.MutableMapping`. For speed reasons, :attr:`~decimal." @@ -1702,33 +1884,33 @@ msgid "" "do not reference the RHS dictionary." msgstr "" -#: ../../whatsnew/3.3.rst:1178 +#: ../../whatsnew/3.3.rst:1180 msgid "" "Pickling a :class:`~decimal.Context` produces a different output in order to " "have a common interchange format for the Python and C versions." msgstr "" -#: ../../whatsnew/3.3.rst:1182 +#: ../../whatsnew/3.3.rst:1184 msgid "" "The order of arguments in the :class:`~decimal.Context` constructor has been " "changed to match the order displayed by :func:`repr`." msgstr "" -#: ../../whatsnew/3.3.rst:1186 +#: ../../whatsnew/3.3.rst:1188 msgid "" "The ``watchexp`` parameter in the :meth:`~decimal.Decimal.quantize` method " "is deprecated." msgstr "" -#: ../../whatsnew/3.3.rst:1193 +#: ../../whatsnew/3.3.rst:1195 msgid "email" msgstr "email" -#: ../../whatsnew/3.3.rst:1196 +#: ../../whatsnew/3.3.rst:1198 msgid "Policy Framework" msgstr "" -#: ../../whatsnew/3.3.rst:1198 +#: ../../whatsnew/3.3.rst:1200 msgid "" "The email package now has a :mod:`~email.policy` framework. A :class:" "`~email.policy.Policy` is an object with several methods and properties that " @@ -1744,52 +1926,52 @@ msgid "" "data:`~email.policy.compat32`." msgstr "" -#: ../../whatsnew/3.3.rst:1211 +#: ../../whatsnew/3.3.rst:1213 msgid "The minimum set of controls implemented by all ``policy`` objects are:" msgstr "" -#: ../../whatsnew/3.3.rst:1216 +#: ../../whatsnew/3.3.rst:1218 msgid "max_line_length" msgstr "" -#: ../../whatsnew/3.3.rst:1216 +#: ../../whatsnew/3.3.rst:1218 msgid "" "The maximum length, excluding the linesep character(s), individual lines may " "have when a ``Message`` is serialized. Defaults to 78." msgstr "" -#: ../../whatsnew/3.3.rst:1220 +#: ../../whatsnew/3.3.rst:1222 msgid "linesep" msgstr "" -#: ../../whatsnew/3.3.rst:1220 +#: ../../whatsnew/3.3.rst:1222 msgid "" "The character used to separate individual lines when a ``Message`` is " "serialized. Defaults to ``\\n``." msgstr "" -#: ../../whatsnew/3.3.rst:1223 +#: ../../whatsnew/3.3.rst:1225 msgid "cte_type" msgstr "" -#: ../../whatsnew/3.3.rst:1223 +#: ../../whatsnew/3.3.rst:1225 msgid "" "``7bit`` or ``8bit``. ``8bit`` applies only to a ``Bytes`` ``generator``, " "and means that non-ASCII may be used where allowed by the protocol (or where " "it exists in the original input)." msgstr "" -#: ../../whatsnew/3.3.rst:1228 +#: ../../whatsnew/3.3.rst:1230 msgid "raise_on_defect" msgstr "" -#: ../../whatsnew/3.3.rst:1228 +#: ../../whatsnew/3.3.rst:1230 msgid "" "Causes a ``parser`` to raise error when defects are encountered instead of " "adding them to the ``Message`` object's ``defects`` list." msgstr "" -#: ../../whatsnew/3.3.rst:1233 +#: ../../whatsnew/3.3.rst:1235 msgid "" "A new policy instance, with new settings, is created using the :meth:`~email." "policy.Policy.clone` method of policy objects. ``clone`` takes any of the " @@ -1799,6 +1981,10 @@ msgid "" msgstr "" #: ../../whatsnew/3.3.rst:1241 +msgid "mypolicy = compat32.clone(linesep='\\r\\n')" +msgstr "" + +#: ../../whatsnew/3.3.rst:1243 msgid "" "Policies can be used to make the generation of messages in the format needed " "by your application simpler. Instead of having to remember to specify " @@ -1811,11 +1997,11 @@ msgid "" "when you create the ``generator``." msgstr "" -#: ../../whatsnew/3.3.rst:1253 +#: ../../whatsnew/3.3.rst:1255 msgid "Provisional Policy with New Header API" msgstr "" -#: ../../whatsnew/3.3.rst:1255 +#: ../../whatsnew/3.3.rst:1257 msgid "" "While the policy framework is worthwhile all by itself, the main motivation " "for introducing it is to allow the creation of new policies that implement " @@ -1827,17 +2013,17 @@ msgid "" "the core developers." msgstr "" -#: ../../whatsnew/3.3.rst:1263 +#: ../../whatsnew/3.3.rst:1265 msgid "" "The new policies are instances of :class:`~email.policy.EmailPolicy`, and " "add the following additional controls:" msgstr "" -#: ../../whatsnew/3.3.rst:1269 +#: ../../whatsnew/3.3.rst:1271 msgid "refold_source" msgstr "" -#: ../../whatsnew/3.3.rst:1269 +#: ../../whatsnew/3.3.rst:1271 msgid "" "Controls whether or not headers parsed by a :mod:`~email.parser` are " "refolded by the :mod:`~email.generator`. It can be ``none``, ``long``, or " @@ -1846,17 +2032,17 @@ msgid "" "get refolded, and ``all`` means that all lines get refolded." msgstr "" -#: ../../whatsnew/3.3.rst:1278 +#: ../../whatsnew/3.3.rst:1280 msgid "header_factory" msgstr "" -#: ../../whatsnew/3.3.rst:1278 +#: ../../whatsnew/3.3.rst:1280 msgid "" "A callable that take a ``name`` and ``value`` and produces a custom header " "object." msgstr "" -#: ../../whatsnew/3.3.rst:1282 +#: ../../whatsnew/3.3.rst:1284 msgid "" "The ``header_factory`` is the key to the new features provided by the new " "policies. When one of the new policies is used, any header retrieved from a " @@ -1868,7 +2054,30 @@ msgid "" "now do things like this::" msgstr "" -#: ../../whatsnew/3.3.rst:1310 +#: ../../whatsnew/3.3.rst:1293 +msgid "" +">>> m = Message(policy=SMTP)\n" +">>> m['To'] = 'Éric '\n" +">>> m['to']\n" +"'Éric '\n" +">>> m['to'].addresses\n" +"(Address(display_name='Éric', username='foo', domain='example.com'),)\n" +">>> m['to'].addresses[0].username\n" +"'foo'\n" +">>> m['to'].addresses[0].display_name\n" +"'Éric'\n" +">>> m['Date'] = email.utils.localtime()\n" +">>> m['Date'].datetime\n" +"datetime.datetime(2012, 5, 25, 21, 39, 24, 465484, tzinfo=datetime." +"timezone(datetime.timedelta(-1, 72000), 'EDT'))\n" +">>> m['Date']\n" +"'Fri, 25 May 2012 21:44:27 -0400'\n" +">>> print(m)\n" +"To: =?utf-8?q?=C3=89ric?= \n" +"Date: Fri, 25 May 2012 21:44:27 -0400" +msgstr "" + +#: ../../whatsnew/3.3.rst:1312 msgid "" "You will note that the unicode display name is automatically encoded as " "``utf-8`` when the message is serialized, but that when the header is " @@ -1877,22 +2086,55 @@ msgid "" "meth:`~email.header.make_header` functions." msgstr "" -#: ../../whatsnew/3.3.rst:1316 +#: ../../whatsnew/3.3.rst:1318 msgid "You can also create addresses from parts::" msgstr "" -#: ../../whatsnew/3.3.rst:1326 +#: ../../whatsnew/3.3.rst:1320 +msgid "" +">>> m['cc'] = [Group('pals', [Address('Bob', 'bob', 'example.com'),\n" +"... Address('Sally', 'sally', 'example.com')]),\n" +"... Address('Bonzo', addr_spec='bonz@laugh.com')]\n" +">>> print(m)\n" +"To: =?utf-8?q?=C3=89ric?= \n" +"Date: Fri, 25 May 2012 21:44:27 -0400\n" +"cc: pals: Bob , Sally ;, Bonzo " +"" +msgstr "" + +#: ../../whatsnew/3.3.rst:1328 msgid "Decoding to unicode is done automatically::" msgstr "" -#: ../../whatsnew/3.3.rst:1332 +#: ../../whatsnew/3.3.rst:1330 +msgid "" +">>> m2 = message_from_string(str(m))\n" +">>> m2['to']\n" +"'Éric '" +msgstr "" + +#: ../../whatsnew/3.3.rst:1334 msgid "" "When you parse a message, you can use the ``addresses`` and ``groups`` " "attributes of the header objects to access the groups and individual " "addresses::" msgstr "" -#: ../../whatsnew/3.3.rst:1341 +#: ../../whatsnew/3.3.rst:1338 +msgid "" +">>> m2['cc'].addresses\n" +"(Address(display_name='Bob', username='bob', domain='example.com'), " +"Address(display_name='Sally', username='sally', domain='example.com'), " +"Address(display_name='Bonzo', username='bonz', domain='laugh.com'))\n" +">>> m2['cc'].groups\n" +"(Group(display_name='pals', addresses=(Address(display_name='Bob', " +"username='bob', domain='example.com'), Address(display_name='Sally', " +"username='sally', domain='example.com')), Group(display_name=None, " +"addresses=(Address(display_name='Bonzo', username='bonz', domain='laugh." +"com'),))" +msgstr "" + +#: ../../whatsnew/3.3.rst:1343 msgid "" "In summary, if you use one of the new policies, header manipulation works " "the way it ought to: your application works with unicode strings, and the " @@ -1900,35 +2142,35 @@ msgid "" "RFC standard Content Transfer Encodings." msgstr "" -#: ../../whatsnew/3.3.rst:1347 +#: ../../whatsnew/3.3.rst:1349 msgid "Other API Changes" msgstr "" -#: ../../whatsnew/3.3.rst:1349 +#: ../../whatsnew/3.3.rst:1351 msgid "" "New :class:`~email.parser.BytesHeaderParser`, added to the :mod:`~email." "parser` module to complement :class:`~email.parser.HeaderParser` and " "complete the Bytes API." msgstr "" -#: ../../whatsnew/3.3.rst:1353 +#: ../../whatsnew/3.3.rst:1355 msgid "New utility functions:" msgstr "" -#: ../../whatsnew/3.3.rst:1355 +#: ../../whatsnew/3.3.rst:1357 msgid "" ":func:`~email.utils.format_datetime`: given a :class:`~datetime.datetime`, " "produce a string formatted for use in an email header." msgstr "" -#: ../../whatsnew/3.3.rst:1358 +#: ../../whatsnew/3.3.rst:1360 msgid "" ":func:`~email.utils.parsedate_to_datetime`: given a date string from an " "email header, convert it into an aware :class:`~datetime.datetime`, or a " "naive :class:`~datetime.datetime` if the offset is ``-0000``." msgstr "" -#: ../../whatsnew/3.3.rst:1362 +#: ../../whatsnew/3.3.rst:1364 msgid "" ":func:`~email.utils.localtime`: With no argument, returns the current local " "time as an aware :class:`~datetime.datetime` using the local :class:" @@ -1937,11 +2179,11 @@ msgid "" "`~datetime.timezone`." msgstr "" -#: ../../whatsnew/3.3.rst:1370 +#: ../../whatsnew/3.3.rst:1372 msgid "ftplib" msgstr "ftplib" -#: ../../whatsnew/3.3.rst:1372 +#: ../../whatsnew/3.3.rst:1374 msgid "" ":class:`ftplib.FTP` now accepts a ``source_address`` keyword argument to " "specify the ``(host, port)`` to use as the source address in the bind call " @@ -1949,7 +2191,7 @@ msgid "" "issue:`8594`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1377 +#: ../../whatsnew/3.3.rst:1379 msgid "" "The :class:`~ftplib.FTP_TLS` class now provides a new :func:`~ftplib.FTP_TLS." "ccc` function to revert control channel back to plaintext. This can be " @@ -1958,18 +2200,18 @@ msgid "" "in :issue:`12139`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1383 +#: ../../whatsnew/3.3.rst:1385 msgid "" "Added :meth:`ftplib.FTP.mlsd` method which provides a parsable directory " "listing format and deprecates :meth:`ftplib.FTP.nlst` and :meth:`ftplib.FTP." "dir`. (Contributed by Giampaolo Rodolà in :issue:`11072`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1389 +#: ../../whatsnew/3.3.rst:1391 msgid "functools" msgstr "functools" -#: ../../whatsnew/3.3.rst:1391 +#: ../../whatsnew/3.3.rst:1393 msgid "" "The :func:`functools.lru_cache` decorator now accepts a ``typed`` keyword " "argument (that defaults to ``False`` to ensure that it caches values of " @@ -1977,32 +2219,32 @@ msgid "" "Raymond Hettinger in :issue:`13227`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1398 +#: ../../whatsnew/3.3.rst:1400 msgid "gc" msgstr "gc" -#: ../../whatsnew/3.3.rst:1400 +#: ../../whatsnew/3.3.rst:1402 msgid "" "It is now possible to register callbacks invoked by the garbage collector " "before and after collection using the new :data:`~gc.callbacks` list." msgstr "" -#: ../../whatsnew/3.3.rst:1405 +#: ../../whatsnew/3.3.rst:1407 msgid "hmac" msgstr "hmac" -#: ../../whatsnew/3.3.rst:1407 +#: ../../whatsnew/3.3.rst:1409 msgid "" "A new :func:`~hmac.compare_digest` function has been added to prevent side " "channel attacks on digests through timing analysis. (Contributed by Nick " "Coghlan and Christian Heimes in :issue:`15061`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1413 +#: ../../whatsnew/3.3.rst:1415 msgid "http" msgstr "http" -#: ../../whatsnew/3.3.rst:1415 +#: ../../whatsnew/3.3.rst:1417 msgid "" ":class:`http.server.BaseHTTPRequestHandler` now buffers the headers and " "writes them all at once when :meth:`~http.server.BaseHTTPRequestHandler." @@ -2012,24 +2254,24 @@ msgid "" "`3709`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1421 +#: ../../whatsnew/3.3.rst:1423 msgid "" ":class:`http.server` now produces valid ``HTML 4.01 strict`` output. " "(Contributed by Ezio Melotti in :issue:`13295`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1424 +#: ../../whatsnew/3.3.rst:1426 msgid "" ":class:`http.client.HTTPResponse` now has a :meth:`~http.client.HTTPResponse." "readinto` method, which means it can be used as an :class:`io.RawIOBase` " "class. (Contributed by John Kuhn in :issue:`13464`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1431 +#: ../../whatsnew/3.3.rst:1433 msgid "html" msgstr "html" -#: ../../whatsnew/3.3.rst:1433 +#: ../../whatsnew/3.3.rst:1435 msgid "" ":class:`html.parser.HTMLParser` is now able to parse broken markup without " "raising errors, therefore the *strict* argument of the constructor and the :" @@ -2042,7 +2284,7 @@ msgid "" "`12888`, :issue:`7311`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1443 +#: ../../whatsnew/3.3.rst:1445 msgid "" "A new :data:`~html.entities.html5` dictionary that maps HTML5 named " "character references to the equivalent Unicode character(s) (e.g. " @@ -2051,25 +2293,25 @@ msgid "" "(Contributed by Ezio Melotti in :issue:`11113` and :issue:`15156`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1451 +#: ../../whatsnew/3.3.rst:1453 msgid "imaplib" msgstr "imaplib" -#: ../../whatsnew/3.3.rst:1453 +#: ../../whatsnew/3.3.rst:1455 msgid "" "The :class:`~imaplib.IMAP4_SSL` constructor now accepts an SSLContext " "parameter to control parameters of the secure channel." msgstr "" -#: ../../whatsnew/3.3.rst:1456 +#: ../../whatsnew/3.3.rst:1458 msgid "(Contributed by Sijin Joseph in :issue:`8808`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1460 +#: ../../whatsnew/3.3.rst:1462 msgid "inspect" msgstr "inspect" -#: ../../whatsnew/3.3.rst:1462 +#: ../../whatsnew/3.3.rst:1464 msgid "" "A new :func:`~inspect.getclosurevars` function has been added. This function " "reports the current binding of all names referenced from the function body " @@ -2077,11 +2319,11 @@ msgid "" "internal state when testing code that relies on stateful closures." msgstr "" -#: ../../whatsnew/3.3.rst:1467 +#: ../../whatsnew/3.3.rst:1469 msgid "(Contributed by Meador Inge and Nick Coghlan in :issue:`13062`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1469 +#: ../../whatsnew/3.3.rst:1471 msgid "" "A new :func:`~inspect.getgeneratorlocals` function has been added. This " "function reports the current binding of local variables in the generator's " @@ -2089,26 +2331,26 @@ msgid "" "generators." msgstr "" -#: ../../whatsnew/3.3.rst:1474 +#: ../../whatsnew/3.3.rst:1476 msgid "(Contributed by Meador Inge in :issue:`15153`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1477 +#: ../../whatsnew/3.3.rst:1479 msgid "io" msgstr "io" -#: ../../whatsnew/3.3.rst:1479 +#: ../../whatsnew/3.3.rst:1481 msgid "" "The :func:`~io.open` function has a new ``'x'`` mode that can be used to " "exclusively create a new file, and raise a :exc:`FileExistsError` if the " "file already exists. It is based on the C11 'x' mode to fopen()." msgstr "" -#: ../../whatsnew/3.3.rst:1483 +#: ../../whatsnew/3.3.rst:1485 msgid "(Contributed by David Townshend in :issue:`12760`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1485 +#: ../../whatsnew/3.3.rst:1487 msgid "" "The constructor of the :class:`~io.TextIOWrapper` class has a new " "*write_through* optional argument. If *write_through* is ``True``, calls to :" @@ -2117,28 +2359,28 @@ msgid "" "its underlying binary buffer." msgstr "" -#: ../../whatsnew/3.3.rst:1493 +#: ../../whatsnew/3.3.rst:1495 msgid "itertools" msgstr "itertools" -#: ../../whatsnew/3.3.rst:1495 +#: ../../whatsnew/3.3.rst:1497 msgid "" ":func:`~itertools.accumulate` now takes an optional ``func`` argument for " "providing a user-supplied binary function." msgstr "" -#: ../../whatsnew/3.3.rst:1500 +#: ../../whatsnew/3.3.rst:1502 msgid "logging" msgstr "logging" -#: ../../whatsnew/3.3.rst:1502 +#: ../../whatsnew/3.3.rst:1504 msgid "" "The :func:`~logging.basicConfig` function now supports an optional " "``handlers`` argument taking an iterable of handlers to be added to the root " "logger." msgstr "" -#: ../../whatsnew/3.3.rst:1505 +#: ../../whatsnew/3.3.rst:1507 msgid "" "A class level attribute :attr:`~logging.handlers.SysLogHandler.append_nul` " "has been added to :class:`~logging.handlers.SysLogHandler` to allow control " @@ -2147,25 +2389,25 @@ msgid "" "log." msgstr "" -#: ../../whatsnew/3.3.rst:1513 +#: ../../whatsnew/3.3.rst:1515 msgid "math" msgstr "math" -#: ../../whatsnew/3.3.rst:1515 +#: ../../whatsnew/3.3.rst:1517 msgid "" "The :mod:`math` module has a new function, :func:`~math.log2`, which " "returns the base-2 logarithm of *x*." msgstr "" -#: ../../whatsnew/3.3.rst:1518 +#: ../../whatsnew/3.3.rst:1520 msgid "(Written by Mark Dickinson in :issue:`11888`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1522 +#: ../../whatsnew/3.3.rst:1524 msgid "mmap" msgstr "mmap" -#: ../../whatsnew/3.3.rst:1524 +#: ../../whatsnew/3.3.rst:1526 msgid "" "The :meth:`~mmap.mmap.read` method is now more compatible with other file-" "like objects: if the argument is omitted or specified as ``None``, it " @@ -2173,39 +2415,39 @@ msgid "" "(Contributed by Petri Lehtinen in :issue:`12021`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1531 +#: ../../whatsnew/3.3.rst:1533 msgid "multiprocessing" msgstr "multiprocessing" -#: ../../whatsnew/3.3.rst:1533 +#: ../../whatsnew/3.3.rst:1535 msgid "" "The new :func:`multiprocessing.connection.wait` function allows polling " "multiple objects (such as connections, sockets and pipes) with a timeout. " "(Contributed by Richard Oudkerk in :issue:`12328`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1537 +#: ../../whatsnew/3.3.rst:1539 msgid "" ":class:`multiprocessing.Connection` objects can now be transferred over " "multiprocessing connections. (Contributed by Richard Oudkerk in :issue:" "`4892`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1541 +#: ../../whatsnew/3.3.rst:1543 msgid "" ":class:`multiprocessing.Process` now accepts a ``daemon`` keyword argument " "to override the default behavior of inheriting the ``daemon`` flag from the " "parent process (:issue:`6064`)." msgstr "" -#: ../../whatsnew/3.3.rst:1545 +#: ../../whatsnew/3.3.rst:1547 msgid "" "New attribute :data:`multiprocessing.Process.sentinel` allows a program to " "wait on multiple :class:`~multiprocessing.Process` objects at one time using " "the appropriate OS primitives (for example, :mod:`select` on posix systems)." msgstr "" -#: ../../whatsnew/3.3.rst:1550 +#: ../../whatsnew/3.3.rst:1552 msgid "" "New methods :meth:`multiprocessing.pool.Pool.starmap` and :meth:" "`~multiprocessing.pool.Pool.starmap_async` provide :func:`itertools.starmap` " @@ -2214,26 +2456,37 @@ msgid "" "Schlawack in :issue:`12708`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1559 +#: ../../whatsnew/3.3.rst:1561 msgid "nntplib" msgstr "nntplib" -#: ../../whatsnew/3.3.rst:1561 +#: ../../whatsnew/3.3.rst:1563 msgid "" "The :class:`!nntplib.NNTP` class now supports the context management " "protocol to unconditionally consume :exc:`socket.error` exceptions and to " "close the NNTP connection when done::" msgstr "" -#: ../../whatsnew/3.3.rst:1572 +#: ../../whatsnew/3.3.rst:1567 +msgid "" +">>> from nntplib import NNTP\n" +">>> with NNTP('news.gmane.org') as n:\n" +"... n.group('gmane.comp.python.committers')\n" +"...\n" +"('211 1755 1 1755 gmane.comp.python.committers', 1755, 1, 1755, 'gmane.comp." +"python.committers')\n" +">>>" +msgstr "" + +#: ../../whatsnew/3.3.rst:1574 msgid "(Contributed by Giampaolo Rodolà in :issue:`9795`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1576 +#: ../../whatsnew/3.3.rst:1578 msgid "os" msgstr "os" -#: ../../whatsnew/3.3.rst:1578 +#: ../../whatsnew/3.3.rst:1580 msgid "" "The :mod:`os` module has a new :func:`~os.pipe2` function that makes it " "possible to create a pipe with :const:`~os.O_CLOEXEC` or :const:`~os." @@ -2241,7 +2494,7 @@ msgid "" "conditions in multi-threaded programs." msgstr "" -#: ../../whatsnew/3.3.rst:1583 +#: ../../whatsnew/3.3.rst:1585 msgid "" "The :mod:`os` module has a new :func:`~os.sendfile` function which provides " "an efficient \"zero-copy\" way for copying data from one file (or socket) " @@ -2252,12 +2505,12 @@ msgid "" "socket, e.g. for downloading a file." msgstr "" -#: ../../whatsnew/3.3.rst:1591 +#: ../../whatsnew/3.3.rst:1593 msgid "" "(Patch submitted by Ross Lagerwall and Giampaolo Rodolà in :issue:`10882`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1593 +#: ../../whatsnew/3.3.rst:1595 msgid "" "To avoid race conditions like symlink attacks and issues with temporary " "files and directories, it is more reliable (and also faster) to manipulate " @@ -2266,14 +2519,14 @@ msgid "" "`4761`, :issue:`10755` and :issue:`14626`)." msgstr "" -#: ../../whatsnew/3.3.rst:1599 +#: ../../whatsnew/3.3.rst:1601 msgid "" "The :mod:`os` module has a new :func:`~os.fwalk` function similar to :func:" "`~os.walk` except that it also yields file descriptors referring to the " "directories visited. This is especially useful to avoid symlink races." msgstr "" -#: ../../whatsnew/3.3.rst:1603 +#: ../../whatsnew/3.3.rst:1605 msgid "" "The following functions get new optional *dir_fd* (:ref:`paths relative to " "directory descriptors `) and/or *follow_symlinks* (:ref:`not " @@ -2287,7 +2540,7 @@ msgid "" "`os.supports_follows_symlinks`." msgstr "" -#: ../../whatsnew/3.3.rst:1614 +#: ../../whatsnew/3.3.rst:1616 msgid "" "The following functions now support a file descriptor for their path " "argument: :func:`~os.chdir`, :func:`~os.chmod`, :func:`~os.chown`, :func:" @@ -2296,7 +2549,7 @@ msgid "" "support for this can be checked via the :data:`os.supports_fd` set." msgstr "" -#: ../../whatsnew/3.3.rst:1620 +#: ../../whatsnew/3.3.rst:1622 msgid "" ":func:`~os.access` accepts an ``effective_ids`` keyword argument to turn on " "using the effective uid/gid rather than the real uid/gid in the access " @@ -2304,7 +2557,7 @@ msgid "" "supports_effective_ids` set." msgstr "" -#: ../../whatsnew/3.3.rst:1625 +#: ../../whatsnew/3.3.rst:1627 msgid "" "The :mod:`os` module has two new functions: :func:`~os.getpriority` and :" "func:`~os.setpriority`. They can be used to get or set process niceness/" @@ -2312,11 +2565,11 @@ msgid "" "processes instead of just the current one." msgstr "" -#: ../../whatsnew/3.3.rst:1630 +#: ../../whatsnew/3.3.rst:1632 msgid "(Patch submitted by Giampaolo Rodolà in :issue:`10784`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1632 +#: ../../whatsnew/3.3.rst:1634 msgid "" "The new :func:`os.replace` function allows cross-platform renaming of a file " "with overwriting the destination. With :func:`os.rename`, an existing " @@ -2324,7 +2577,7 @@ msgid "" "Windows. (Contributed by Antoine Pitrou in :issue:`8828`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1638 +#: ../../whatsnew/3.3.rst:1640 msgid "" "The stat family of functions (:func:`~os.stat`, :func:`~os.fstat`, and :func:" "`~os.lstat`) now support reading a file's timestamps with nanosecond " @@ -2333,7 +2586,7 @@ msgid "" "`14127`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1644 +#: ../../whatsnew/3.3.rst:1646 msgid "" "The new :func:`os.get_terminal_size` function queries the size of the " "terminal attached to a file descriptor. See also :func:`shutil." @@ -2341,14 +2594,14 @@ msgid "" "`13609`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1651 +#: ../../whatsnew/3.3.rst:1653 msgid "" "New functions to support Linux extended attributes (:issue:`12720`): :func:" "`~os.getxattr`, :func:`~os.listxattr`, :func:`~os.removexattr`, :func:`~os." "setxattr`." msgstr "" -#: ../../whatsnew/3.3.rst:1655 +#: ../../whatsnew/3.3.rst:1657 msgid "" "New interface to the scheduler. These functions control how a process is " "allocated CPU time by the operating system. New functions: :func:`~os." @@ -2359,90 +2612,90 @@ msgid "" "sched_setscheduler`, :func:`~os.sched_yield`," msgstr "" -#: ../../whatsnew/3.3.rst:1664 +#: ../../whatsnew/3.3.rst:1666 msgid "New functions to control the file system:" msgstr "" -#: ../../whatsnew/3.3.rst:1666 +#: ../../whatsnew/3.3.rst:1668 msgid "" ":func:`~os.posix_fadvise`: Announces an intention to access data in a " "specific pattern thus allowing the kernel to make optimizations." msgstr "" -#: ../../whatsnew/3.3.rst:1668 +#: ../../whatsnew/3.3.rst:1670 msgid "" ":func:`~os.posix_fallocate`: Ensures that enough disk space is allocated for " "a file." msgstr "" -#: ../../whatsnew/3.3.rst:1670 +#: ../../whatsnew/3.3.rst:1672 msgid ":func:`~os.sync`: Force write of everything to disk." msgstr "" -#: ../../whatsnew/3.3.rst:1672 +#: ../../whatsnew/3.3.rst:1674 msgid "Additional new posix functions:" msgstr "" -#: ../../whatsnew/3.3.rst:1674 +#: ../../whatsnew/3.3.rst:1676 msgid "" ":func:`~os.lockf`: Apply, test or remove a POSIX lock on an open file " "descriptor." msgstr "" -#: ../../whatsnew/3.3.rst:1675 +#: ../../whatsnew/3.3.rst:1677 msgid "" ":func:`~os.pread`: Read from a file descriptor at an offset, the file offset " "remains unchanged." msgstr "" -#: ../../whatsnew/3.3.rst:1677 +#: ../../whatsnew/3.3.rst:1679 msgid "" ":func:`~os.pwrite`: Write to a file descriptor from an offset, leaving the " "file offset unchanged." msgstr "" -#: ../../whatsnew/3.3.rst:1679 +#: ../../whatsnew/3.3.rst:1681 msgid "" ":func:`~os.readv`: Read from a file descriptor into a number of writable " "buffers." msgstr "" -#: ../../whatsnew/3.3.rst:1680 +#: ../../whatsnew/3.3.rst:1682 msgid "" ":func:`~os.truncate`: Truncate the file corresponding to *path*, so that it " "is at most *length* bytes in size." msgstr "" -#: ../../whatsnew/3.3.rst:1682 +#: ../../whatsnew/3.3.rst:1684 msgid "" ":func:`~os.waitid`: Wait for the completion of one or more child processes." msgstr "" -#: ../../whatsnew/3.3.rst:1683 +#: ../../whatsnew/3.3.rst:1685 msgid "" ":func:`~os.writev`: Write the contents of *buffers* to a file descriptor, " "where *buffers* is an arbitrary sequence of buffers." msgstr "" -#: ../../whatsnew/3.3.rst:1685 +#: ../../whatsnew/3.3.rst:1687 msgid "" ":func:`~os.getgrouplist` (:issue:`9344`): Return list of group ids that " "specified user belongs to." msgstr "" -#: ../../whatsnew/3.3.rst:1688 +#: ../../whatsnew/3.3.rst:1690 msgid "" ":func:`~os.times` and :func:`~os.uname`: Return type changed from a tuple to " "a tuple-like object with named attributes." msgstr "" -#: ../../whatsnew/3.3.rst:1691 +#: ../../whatsnew/3.3.rst:1693 msgid "" "Some platforms now support additional constants for the :func:`~os.lseek` " "function, such as ``os.SEEK_HOLE`` and ``os.SEEK_DATA``." msgstr "" -#: ../../whatsnew/3.3.rst:1694 +#: ../../whatsnew/3.3.rst:1696 msgid "" "New constants :const:`~os.RTLD_LAZY`, :const:`~os.RTLD_NOW`, :const:`~os." "RTLD_GLOBAL`, :const:`~os.RTLD_LOCAL`, :const:`~os.RTLD_NODELETE`, :const:" @@ -2452,70 +2705,70 @@ msgid "" "mod:`DLFCN`. (Contributed by Victor Stinner in :issue:`13226`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1702 +#: ../../whatsnew/3.3.rst:1704 msgid "" ":func:`os.symlink` now accepts (and ignores) the ``target_is_directory`` " "keyword argument on non-Windows platforms, to ease cross-platform support." msgstr "" -#: ../../whatsnew/3.3.rst:1707 +#: ../../whatsnew/3.3.rst:1709 msgid "pdb" msgstr "pdb" -#: ../../whatsnew/3.3.rst:1709 +#: ../../whatsnew/3.3.rst:1711 msgid "" "Tab-completion is now available not only for command names, but also their " "arguments. For example, for the ``break`` command, function and file names " "are completed." msgstr "" -#: ../../whatsnew/3.3.rst:1713 +#: ../../whatsnew/3.3.rst:1715 msgid "(Contributed by Georg Brandl in :issue:`14210`)" msgstr "" -#: ../../whatsnew/3.3.rst:1717 +#: ../../whatsnew/3.3.rst:1719 msgid "pickle" msgstr "pickle" -#: ../../whatsnew/3.3.rst:1719 +#: ../../whatsnew/3.3.rst:1721 msgid "" ":class:`pickle.Pickler` objects now have an optional :attr:`~pickle.Pickler." "dispatch_table` attribute allowing per-pickler reduction functions to be set." msgstr "" -#: ../../whatsnew/3.3.rst:1723 +#: ../../whatsnew/3.3.rst:1725 msgid "(Contributed by Richard Oudkerk in :issue:`14166`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1727 +#: ../../whatsnew/3.3.rst:1729 msgid "pydoc" msgstr "pydoc" -#: ../../whatsnew/3.3.rst:1729 +#: ../../whatsnew/3.3.rst:1731 msgid "" "The Tk GUI and the :func:`~pydoc.serve` function have been removed from the :" "mod:`pydoc` module: ``pydoc -g`` and :func:`~pydoc.serve` have been " "deprecated in Python 3.2." msgstr "" -#: ../../whatsnew/3.3.rst:1735 +#: ../../whatsnew/3.3.rst:1737 msgid "re" msgstr "re" -#: ../../whatsnew/3.3.rst:1737 +#: ../../whatsnew/3.3.rst:1739 msgid "" ":class:`str` regular expressions now support ``\\u`` and ``\\U`` escapes." msgstr "" -#: ../../whatsnew/3.3.rst:1739 +#: ../../whatsnew/3.3.rst:1741 msgid "(Contributed by Serhiy Storchaka in :issue:`3665`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1743 +#: ../../whatsnew/3.3.rst:1745 msgid "sched" msgstr "" -#: ../../whatsnew/3.3.rst:1745 +#: ../../whatsnew/3.3.rst:1747 msgid "" ":meth:`~sched.scheduler.run` now accepts a *blocking* parameter which when " "set to false makes the method execute the scheduled events due to expire " @@ -2524,49 +2777,49 @@ msgid "" "(Contributed by Giampaolo Rodolà in :issue:`13449`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1751 +#: ../../whatsnew/3.3.rst:1753 msgid "" ":class:`~sched.scheduler` class can now be safely used in multi-threaded " "environments. (Contributed by Josiah Carlson and Giampaolo Rodolà in :issue:" "`8684`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1755 +#: ../../whatsnew/3.3.rst:1757 msgid "" "*timefunc* and *delayfunct* parameters of :class:`~sched.scheduler` class " "constructor are now optional and defaults to :func:`time.time` and :func:" "`time.sleep` respectively. (Contributed by Chris Clark in :issue:`13245`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1760 +#: ../../whatsnew/3.3.rst:1762 msgid "" ":meth:`~sched.scheduler.enter` and :meth:`~sched.scheduler.enterabs` " "*argument* parameter is now optional. (Contributed by Chris Clark in :issue:" "`13245`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1764 +#: ../../whatsnew/3.3.rst:1766 msgid "" ":meth:`~sched.scheduler.enter` and :meth:`~sched.scheduler.enterabs` now " "accept a *kwargs* parameter. (Contributed by Chris Clark in :issue:`13245`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1770 +#: ../../whatsnew/3.3.rst:1772 msgid "select" msgstr "select" -#: ../../whatsnew/3.3.rst:1772 +#: ../../whatsnew/3.3.rst:1774 msgid "" "Solaris and derivative platforms have a new class :class:`select.devpoll` " "for high performance asynchronous sockets via :file:`/dev/poll`. " "(Contributed by Jesús Cea Avión in :issue:`6397`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1778 +#: ../../whatsnew/3.3.rst:1780 msgid "shlex" msgstr "shlex" -#: ../../whatsnew/3.3.rst:1780 +#: ../../whatsnew/3.3.rst:1782 msgid "" "The previously undocumented helper function ``quote`` from the :mod:`!pipes` " "modules has been moved to the :mod:`shlex` module and documented. :func:" @@ -2574,35 +2827,35 @@ msgid "" "otherwise given special meaning by the shell." msgstr "" -#: ../../whatsnew/3.3.rst:1787 +#: ../../whatsnew/3.3.rst:1789 msgid "shutil" msgstr "shutil" -#: ../../whatsnew/3.3.rst:1789 +#: ../../whatsnew/3.3.rst:1791 msgid "New functions:" msgstr "Novas Funções:" -#: ../../whatsnew/3.3.rst:1791 +#: ../../whatsnew/3.3.rst:1793 msgid "" ":func:`~shutil.disk_usage`: provides total, used and free disk space " "statistics. (Contributed by Giampaolo Rodolà in :issue:`12442`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1793 +#: ../../whatsnew/3.3.rst:1795 msgid "" ":func:`~shutil.chown`: allows one to change user and/or group of the given " "path also specifying the user/group names and not only their numeric ids. " "(Contributed by Sandro Tosi in :issue:`12191`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1796 +#: ../../whatsnew/3.3.rst:1798 msgid "" ":func:`shutil.get_terminal_size`: returns the size of the terminal window to " "which the interpreter is attached. (Contributed by Zbigniew Jędrzejewski-" "Szmek in :issue:`13609`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1800 +#: ../../whatsnew/3.3.rst:1802 msgid "" ":func:`~shutil.copy2` and :func:`~shutil.copystat` now preserve file " "timestamps with nanosecond precision on platforms that support it. They also " @@ -2610,7 +2863,7 @@ msgid "" "Hastings in :issue:`14127` and :issue:`15238`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1805 +#: ../../whatsnew/3.3.rst:1807 msgid "" "Several functions now take an optional ``symlinks`` argument: when that " "parameter is true, symlinks aren't dereferenced and the operation instead " @@ -2618,7 +2871,7 @@ msgid "" "Hynek Schlawack in :issue:`12715`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1810 +#: ../../whatsnew/3.3.rst:1812 msgid "" "When copying files to a different file system, :func:`~shutil.move` now " "handles symlinks the way the posix ``mv`` command does, recreating the " @@ -2627,7 +2880,7 @@ msgid "" "the ``dst`` argument as its result." msgstr "" -#: ../../whatsnew/3.3.rst:1816 +#: ../../whatsnew/3.3.rst:1818 msgid "" ":func:`~shutil.rmtree` is now resistant to symlink attacks on platforms " "which support the new ``dir_fd`` parameter in :func:`os.open` and :func:`os." @@ -2635,80 +2888,80 @@ msgid "" "`4489`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1823 +#: ../../whatsnew/3.3.rst:1825 msgid "signal" msgstr "signal" -#: ../../whatsnew/3.3.rst:1825 +#: ../../whatsnew/3.3.rst:1827 msgid "The :mod:`signal` module has new functions:" msgstr "" -#: ../../whatsnew/3.3.rst:1827 +#: ../../whatsnew/3.3.rst:1829 msgid "" ":func:`~signal.pthread_sigmask`: fetch and/or change the signal mask of the " "calling thread (Contributed by Jean-Paul Calderone in :issue:`8407`);" msgstr "" -#: ../../whatsnew/3.3.rst:1829 +#: ../../whatsnew/3.3.rst:1831 msgid ":func:`~signal.pthread_kill`: send a signal to a thread;" msgstr "" -#: ../../whatsnew/3.3.rst:1830 +#: ../../whatsnew/3.3.rst:1832 msgid ":func:`~signal.sigpending`: examine pending functions;" msgstr "" -#: ../../whatsnew/3.3.rst:1831 +#: ../../whatsnew/3.3.rst:1833 msgid ":func:`~signal.sigwait`: wait a signal;" msgstr "" -#: ../../whatsnew/3.3.rst:1832 +#: ../../whatsnew/3.3.rst:1834 msgid "" ":func:`~signal.sigwaitinfo`: wait for a signal, returning detailed " "information about it;" msgstr "" -#: ../../whatsnew/3.3.rst:1834 +#: ../../whatsnew/3.3.rst:1836 msgid "" ":func:`~signal.sigtimedwait`: like :func:`~signal.sigwaitinfo` but with a " "timeout." msgstr "" -#: ../../whatsnew/3.3.rst:1837 +#: ../../whatsnew/3.3.rst:1839 msgid "" "The signal handler writes the signal number as a single byte instead of a " "nul byte into the wakeup file descriptor. So it is possible to wait more " "than one signal and know which signals were raised." msgstr "" -#: ../../whatsnew/3.3.rst:1841 +#: ../../whatsnew/3.3.rst:1843 msgid "" ":func:`signal.signal` and :func:`signal.siginterrupt` raise an OSError, " "instead of a RuntimeError: OSError has an errno attribute." msgstr "" -#: ../../whatsnew/3.3.rst:1846 +#: ../../whatsnew/3.3.rst:1848 msgid "smtpd" msgstr "smtpd" -#: ../../whatsnew/3.3.rst:1848 +#: ../../whatsnew/3.3.rst:1850 msgid "" "The :mod:`!smtpd` module now supports :rfc:`5321` (extended SMTP) and :rfc:" "`1870` (size extension). Per the standard, these extensions are enabled if " "and only if the client initiates the session with an ``EHLO`` command." msgstr "" -#: ../../whatsnew/3.3.rst:1852 +#: ../../whatsnew/3.3.rst:1854 msgid "" "(Initial ``ELHO`` support by Alberto Trevino. Size extension by Juhana " "Jauhiainen. Substantial additional work on the patch contributed by Michele " "Orrù and Dan Boswell. :issue:`8739`)" msgstr "" -#: ../../whatsnew/3.3.rst:1858 +#: ../../whatsnew/3.3.rst:1860 msgid "smtplib" msgstr "smtplib" -#: ../../whatsnew/3.3.rst:1860 +#: ../../whatsnew/3.3.rst:1862 msgid "" "The :class:`~smtplib.SMTP`, :class:`~smtplib.SMTP_SSL`, and :class:`~smtplib." "LMTP` classes now accept a ``source_address`` keyword argument to specify " @@ -2717,62 +2970,62 @@ msgid "" "`11281`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1866 +#: ../../whatsnew/3.3.rst:1868 msgid "" ":class:`~smtplib.SMTP` now supports the context management protocol, " "allowing an ``SMTP`` instance to be used in a ``with`` statement. " "(Contributed by Giampaolo Rodolà in :issue:`11289`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1870 +#: ../../whatsnew/3.3.rst:1872 msgid "" "The :class:`~smtplib.SMTP_SSL` constructor and the :meth:`~smtplib.SMTP." "starttls` method now accept an SSLContext parameter to control parameters of " "the secure channel. (Contributed by Kasun Herath in :issue:`8809`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1876 +#: ../../whatsnew/3.3.rst:1878 msgid "socket" msgstr "socket" -#: ../../whatsnew/3.3.rst:1878 +#: ../../whatsnew/3.3.rst:1880 msgid "" "The :class:`~socket.socket` class now exposes additional methods to process " "ancillary data when supported by the underlying platform:" msgstr "" -#: ../../whatsnew/3.3.rst:1881 +#: ../../whatsnew/3.3.rst:1883 msgid ":func:`~socket.socket.sendmsg`" msgstr ":func:`~socket.socket.sendmsg`" -#: ../../whatsnew/3.3.rst:1882 +#: ../../whatsnew/3.3.rst:1884 msgid ":func:`~socket.socket.recvmsg`" msgstr ":func:`~socket.socket.recvmsg`" -#: ../../whatsnew/3.3.rst:1883 +#: ../../whatsnew/3.3.rst:1885 msgid ":func:`~socket.socket.recvmsg_into`" msgstr ":func:`~socket.socket.recvmsg_into`" -#: ../../whatsnew/3.3.rst:1885 +#: ../../whatsnew/3.3.rst:1887 msgid "" "(Contributed by David Watson in :issue:`6560`, based on an earlier patch by " "Heiko Wundram)" msgstr "" -#: ../../whatsnew/3.3.rst:1888 +#: ../../whatsnew/3.3.rst:1890 msgid "" "The :class:`~socket.socket` class now supports the PF_CAN protocol family " "(https://en.wikipedia.org/wiki/Socketcan), on Linux (https://lwn.net/" "Articles/253425)." msgstr "" -#: ../../whatsnew/3.3.rst:1892 +#: ../../whatsnew/3.3.rst:1894 msgid "" "(Contributed by Matthias Fuchs, updated by Tiago Gonçalves in :issue:" "`10141`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1894 +#: ../../whatsnew/3.3.rst:1896 msgid "" "The :class:`~socket.socket` class now supports the PF_RDS protocol family " "(https://en.wikipedia.org/wiki/Reliable_Datagram_Sockets and `https://oss." @@ -2780,24 +3033,24 @@ msgid "" "oss.oracle.com/projects/rds/>`__)." msgstr "" -#: ../../whatsnew/3.3.rst:1898 +#: ../../whatsnew/3.3.rst:1900 msgid "" "The :class:`~socket.socket` class now supports the ``PF_SYSTEM`` protocol " "family on OS X. (Contributed by Michael Goderbauer in :issue:`13777`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1901 +#: ../../whatsnew/3.3.rst:1903 msgid "" "New function :func:`~socket.sethostname` allows the hostname to be set on " "Unix systems if the calling process has sufficient privileges. (Contributed " "by Ross Lagerwall in :issue:`10866`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1907 +#: ../../whatsnew/3.3.rst:1909 msgid "socketserver" msgstr "socketserver" -#: ../../whatsnew/3.3.rst:1909 +#: ../../whatsnew/3.3.rst:1911 msgid "" ":class:`~socketserver.BaseServer` now has an overridable method :meth:" "`~socketserver.BaseServer.service_actions` that is called by the :meth:" @@ -2806,54 +3059,54 @@ msgid "" "processes. (Contributed by Justin Warkentin in :issue:`11109`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1917 +#: ../../whatsnew/3.3.rst:1919 msgid "sqlite3" msgstr "sqlite3" -#: ../../whatsnew/3.3.rst:1919 +#: ../../whatsnew/3.3.rst:1921 msgid "" "New :class:`sqlite3.Connection` method :meth:`~sqlite3.Connection." "set_trace_callback` can be used to capture a trace of all sql commands " "processed by sqlite. (Contributed by Torsten Landschoff in :issue:`11688`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1926 +#: ../../whatsnew/3.3.rst:1928 msgid "ssl" msgstr "ssl" -#: ../../whatsnew/3.3.rst:1928 +#: ../../whatsnew/3.3.rst:1930 msgid "The :mod:`ssl` module has two new random generation functions:" msgstr "" -#: ../../whatsnew/3.3.rst:1930 +#: ../../whatsnew/3.3.rst:1932 msgid "" ":func:`~ssl.RAND_bytes`: generate cryptographically strong pseudo-random " "bytes." msgstr "" -#: ../../whatsnew/3.3.rst:1932 +#: ../../whatsnew/3.3.rst:1934 msgid ":func:`~ssl.RAND_pseudo_bytes`: generate pseudo-random bytes." msgstr "" -#: ../../whatsnew/3.3.rst:1934 +#: ../../whatsnew/3.3.rst:1936 msgid "(Contributed by Victor Stinner in :issue:`12049`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1936 +#: ../../whatsnew/3.3.rst:1938 msgid "" "The :mod:`ssl` module now exposes a finer-grained exception hierarchy in " "order to make it easier to inspect the various kinds of errors. (Contributed " "by Antoine Pitrou in :issue:`11183`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1940 +#: ../../whatsnew/3.3.rst:1942 msgid "" ":meth:`~ssl.SSLContext.load_cert_chain` now accepts a *password* argument to " "be used if the private key is encrypted. (Contributed by Adam Simpkins in :" "issue:`12803`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1944 +#: ../../whatsnew/3.3.rst:1946 msgid "" "Diffie-Hellman key exchange, both regular and Elliptic Curve-based, is now " "supported through the :meth:`~ssl.SSLContext.load_dh_params` and :meth:`~ssl." @@ -2861,14 +3114,14 @@ msgid "" "`13626` and :issue:`13627`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1949 +#: ../../whatsnew/3.3.rst:1951 msgid "" "SSL sockets have a new :meth:`~ssl.SSLSocket.get_channel_binding` method " "allowing the implementation of certain authentication mechanisms such as " "SCRAM-SHA-1-PLUS. (Contributed by Jacek Konieczny in :issue:`12551`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1953 +#: ../../whatsnew/3.3.rst:1955 msgid "" "You can query the SSL compression algorithm used by an SSL socket, thanks to " "its new :meth:`~ssl.SSLSocket.compression` method. The new attribute :const:" @@ -2876,123 +3129,123 @@ msgid "" "Antoine Pitrou in :issue:`13634`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1958 +#: ../../whatsnew/3.3.rst:1960 msgid "" "Support has been added for the Next Protocol Negotiation extension using " "the :meth:`ssl.SSLContext.set_npn_protocols` method. (Contributed by Colin " "Marc in :issue:`14204`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1962 +#: ../../whatsnew/3.3.rst:1964 msgid "" "SSL errors can now be introspected more easily thanks to :attr:`~ssl." "SSLError.library` and :attr:`~ssl.SSLError.reason` attributes. (Contributed " "by Antoine Pitrou in :issue:`14837`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1966 +#: ../../whatsnew/3.3.rst:1968 msgid "" "The :func:`~ssl.get_server_certificate` function now supports IPv6. " "(Contributed by Charles-François Natali in :issue:`11811`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1969 +#: ../../whatsnew/3.3.rst:1971 msgid "" "New attribute :const:`~ssl.OP_CIPHER_SERVER_PREFERENCE` allows setting SSLv3 " "server sockets to use the server's cipher ordering preference rather than " "the client's (:issue:`13635`)." msgstr "" -#: ../../whatsnew/3.3.rst:1975 +#: ../../whatsnew/3.3.rst:1977 msgid "stat" msgstr "stat" -#: ../../whatsnew/3.3.rst:1977 +#: ../../whatsnew/3.3.rst:1979 msgid "" "The undocumented tarfile.filemode function has been moved to :func:`stat." "filemode`. It can be used to convert a file's mode to a string of the form '-" "rwxrwxrwx'." msgstr "" -#: ../../whatsnew/3.3.rst:1981 +#: ../../whatsnew/3.3.rst:1983 msgid "(Contributed by Giampaolo Rodolà in :issue:`14807`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1985 +#: ../../whatsnew/3.3.rst:1987 msgid "struct" msgstr "struct" -#: ../../whatsnew/3.3.rst:1987 +#: ../../whatsnew/3.3.rst:1989 msgid "" "The :mod:`struct` module now supports :c:type:`ssize_t` and :c:type:`size_t` " "via the new codes ``n`` and ``N``, respectively. (Contributed by Antoine " "Pitrou in :issue:`3163`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1993 +#: ../../whatsnew/3.3.rst:1995 msgid "subprocess" msgstr "subprocess" -#: ../../whatsnew/3.3.rst:1995 +#: ../../whatsnew/3.3.rst:1997 msgid "" "Command strings can now be bytes objects on posix platforms. (Contributed " "by Victor Stinner in :issue:`8513`.)" msgstr "" -#: ../../whatsnew/3.3.rst:1998 +#: ../../whatsnew/3.3.rst:2000 msgid "" "A new constant :const:`~subprocess.DEVNULL` allows suppressing output in a " "platform-independent fashion. (Contributed by Ross Lagerwall in :issue:" "`5870`.)" msgstr "" -#: ../../whatsnew/3.3.rst:2004 +#: ../../whatsnew/3.3.rst:2006 msgid "sys" msgstr "sys" -#: ../../whatsnew/3.3.rst:2006 +#: ../../whatsnew/3.3.rst:2008 msgid "" "The :mod:`sys` module has a new :data:`~sys.thread_info` :term:`named tuple` " "holding information about the thread implementation (:issue:`11223`)." msgstr "" -#: ../../whatsnew/3.3.rst:2012 +#: ../../whatsnew/3.3.rst:2014 msgid "tarfile" msgstr "tarfile" -#: ../../whatsnew/3.3.rst:2014 +#: ../../whatsnew/3.3.rst:2016 msgid "" ":mod:`tarfile` now supports ``lzma`` encoding via the :mod:`lzma` module. " "(Contributed by Lars Gustäbel in :issue:`5689`.)" msgstr "" -#: ../../whatsnew/3.3.rst:2019 +#: ../../whatsnew/3.3.rst:2021 msgid "tempfile" msgstr "tempfile" -#: ../../whatsnew/3.3.rst:2021 +#: ../../whatsnew/3.3.rst:2023 msgid "" ":class:`tempfile.SpooledTemporaryFile`\\'s :meth:`~tempfile." "SpooledTemporaryFile.truncate` method now accepts a ``size`` parameter. " "(Contributed by Ryan Kelly in :issue:`9957`.)" msgstr "" -#: ../../whatsnew/3.3.rst:2027 +#: ../../whatsnew/3.3.rst:2029 msgid "textwrap" msgstr "textwrap" -#: ../../whatsnew/3.3.rst:2029 +#: ../../whatsnew/3.3.rst:2031 msgid "" "The :mod:`textwrap` module has a new :func:`~textwrap.indent` that makes it " "straightforward to add a common prefix to selected lines in a block of text " "(:issue:`13857`)." msgstr "" -#: ../../whatsnew/3.3.rst:2035 +#: ../../whatsnew/3.3.rst:2037 msgid "threading" msgstr "threading" -#: ../../whatsnew/3.3.rst:2037 +#: ../../whatsnew/3.3.rst:2039 msgid "" ":class:`threading.Condition`, :class:`threading.Semaphore`, :class:" "`threading.BoundedSemaphore`, :class:`threading.Event`, and :class:" @@ -3001,14 +3254,14 @@ msgid "" "Araujo in :issue:`10968`.)" msgstr "" -#: ../../whatsnew/3.3.rst:2043 +#: ../../whatsnew/3.3.rst:2045 msgid "" "The :class:`threading.Thread` constructor now accepts a ``daemon`` keyword " "argument to override the default behavior of inheriting the ``daemon`` flag " "value from the parent thread (:issue:`6064`)." msgstr "" -#: ../../whatsnew/3.3.rst:2047 +#: ../../whatsnew/3.3.rst:2049 msgid "" "The formerly private function ``_thread.get_ident`` is now available as the " "public function :func:`threading.get_ident`. This eliminates several cases " @@ -3017,76 +3270,76 @@ msgid "" "public interface." msgstr "" -#: ../../whatsnew/3.3.rst:2055 +#: ../../whatsnew/3.3.rst:2057 msgid "time" msgstr "time" -#: ../../whatsnew/3.3.rst:2057 +#: ../../whatsnew/3.3.rst:2059 msgid "The :pep:`418` added new functions to the :mod:`time` module:" msgstr "" -#: ../../whatsnew/3.3.rst:2059 +#: ../../whatsnew/3.3.rst:2061 msgid ":func:`~time.get_clock_info`: Get information on a clock." msgstr "" -#: ../../whatsnew/3.3.rst:2060 +#: ../../whatsnew/3.3.rst:2062 msgid "" ":func:`~time.monotonic`: Monotonic clock (cannot go backward), not affected " "by system clock updates." msgstr "" -#: ../../whatsnew/3.3.rst:2062 +#: ../../whatsnew/3.3.rst:2064 msgid "" ":func:`~time.perf_counter`: Performance counter with the highest available " "resolution to measure a short duration." msgstr "" -#: ../../whatsnew/3.3.rst:2064 +#: ../../whatsnew/3.3.rst:2066 msgid "" ":func:`~time.process_time`: Sum of the system and user CPU time of the " "current process." msgstr "" -#: ../../whatsnew/3.3.rst:2067 +#: ../../whatsnew/3.3.rst:2069 msgid "Other new functions:" msgstr "" -#: ../../whatsnew/3.3.rst:2069 +#: ../../whatsnew/3.3.rst:2071 msgid "" ":func:`~time.clock_getres`, :func:`~time.clock_gettime` and :func:`~time." "clock_settime` functions with :samp:`CLOCK_{xxx}` constants. (Contributed by " "Victor Stinner in :issue:`10278`.)" msgstr "" -#: ../../whatsnew/3.3.rst:2073 +#: ../../whatsnew/3.3.rst:2075 msgid "" "To improve cross platform consistency, :func:`~time.sleep` now raises a :exc:" "`ValueError` when passed a negative sleep value. Previously this was an " "error on posix, but produced an infinite sleep on Windows." msgstr "" -#: ../../whatsnew/3.3.rst:2079 +#: ../../whatsnew/3.3.rst:2081 msgid "types" msgstr "types" -#: ../../whatsnew/3.3.rst:2081 +#: ../../whatsnew/3.3.rst:2083 msgid "" "Add a new :class:`types.MappingProxyType` class: Read-only proxy of a " "mapping. (:issue:`14386`)" msgstr "" -#: ../../whatsnew/3.3.rst:2085 +#: ../../whatsnew/3.3.rst:2087 msgid "" "The new functions :func:`types.new_class` and :func:`types.prepare_class` " "provide support for :pep:`3115` compliant dynamic type creation. (:issue:" "`14588`)" msgstr "" -#: ../../whatsnew/3.3.rst:2090 +#: ../../whatsnew/3.3.rst:2092 msgid "unittest" msgstr "unittest" -#: ../../whatsnew/3.3.rst:2092 +#: ../../whatsnew/3.3.rst:2094 msgid "" ":meth:`.assertRaises`, :meth:`.assertRaisesRegex`, :meth:`.assertWarns`, " "and :meth:`.assertWarnsRegex` now accept a keyword argument *msg* when used " @@ -3094,17 +3347,17 @@ msgid "" "issue:`10775`.)" msgstr "" -#: ../../whatsnew/3.3.rst:2097 +#: ../../whatsnew/3.3.rst:2099 msgid "" ":meth:`unittest.TestCase.run` now returns the :class:`~unittest.TestResult` " "object." msgstr "" -#: ../../whatsnew/3.3.rst:2102 +#: ../../whatsnew/3.3.rst:2104 msgid "urllib" msgstr "urllib" -#: ../../whatsnew/3.3.rst:2104 +#: ../../whatsnew/3.3.rst:2106 msgid "" "The :class:`~urllib.request.Request` class, now accepts a *method* argument " "used by :meth:`~urllib.request.Request.get_method` to determine what HTTP " @@ -3112,14 +3365,18 @@ msgid "" msgstr "" #: ../../whatsnew/3.3.rst:2110 +msgid ">>> urlopen(Request('https://www.python.org', method='HEAD'))" +msgstr "" + +#: ../../whatsnew/3.3.rst:2112 msgid "(:issue:`1673007`)" msgstr "" -#: ../../whatsnew/3.3.rst:2114 +#: ../../whatsnew/3.3.rst:2116 msgid "webbrowser" msgstr "webbrowser" -#: ../../whatsnew/3.3.rst:2116 +#: ../../whatsnew/3.3.rst:2118 msgid "" "The :mod:`webbrowser` module supports more \"browsers\": Google Chrome " "(named :program:`chrome`, :program:`chromium`, :program:`chrome-browser` or :" @@ -3130,11 +3387,11 @@ msgid "" "latter by Matthias Klose in :issue:`14493`.)" msgstr "" -#: ../../whatsnew/3.3.rst:2126 +#: ../../whatsnew/3.3.rst:2128 msgid "xml.etree.ElementTree" msgstr "xml.etree.ElementTree" -#: ../../whatsnew/3.3.rst:2128 +#: ../../whatsnew/3.3.rst:2130 msgid "" "The :mod:`xml.etree.ElementTree` module now imports its C accelerator by " "default; there is no longer a need to explicitly import :mod:`xml.etree." @@ -3145,140 +3402,140 @@ msgid "" "detailed reference." msgstr "" -#: ../../whatsnew/3.3.rst:2138 +#: ../../whatsnew/3.3.rst:2140 msgid "zlib" msgstr "zlib" -#: ../../whatsnew/3.3.rst:2140 +#: ../../whatsnew/3.3.rst:2142 msgid "" "New attribute :attr:`zlib.Decompress.eof` makes it possible to distinguish " "between a properly formed compressed stream and an incomplete or truncated " "one. (Contributed by Nadeem Vawda in :issue:`12646`.)" msgstr "" -#: ../../whatsnew/3.3.rst:2144 +#: ../../whatsnew/3.3.rst:2146 msgid "" "New attribute :const:`zlib.ZLIB_RUNTIME_VERSION` reports the version string " "of the underlying ``zlib`` library that is loaded at runtime. (Contributed " "by Torsten Landschoff in :issue:`12306`.)" msgstr "" -#: ../../whatsnew/3.3.rst:2150 +#: ../../whatsnew/3.3.rst:2152 msgid "Optimizations" msgstr "Otimizações" -#: ../../whatsnew/3.3.rst:2152 +#: ../../whatsnew/3.3.rst:2154 msgid "Major performance enhancements have been added:" msgstr "Major performance enhancements have been added:" -#: ../../whatsnew/3.3.rst:2154 +#: ../../whatsnew/3.3.rst:2156 msgid "" "Thanks to :pep:`393`, some operations on Unicode strings have been optimized:" msgstr "" -#: ../../whatsnew/3.3.rst:2156 +#: ../../whatsnew/3.3.rst:2158 msgid "the memory footprint is divided by 2 to 4 depending on the text" msgstr "" -#: ../../whatsnew/3.3.rst:2157 +#: ../../whatsnew/3.3.rst:2159 msgid "" "encode an ASCII string to UTF-8 doesn't need to encode characters anymore, " "the UTF-8 representation is shared with the ASCII representation" msgstr "" -#: ../../whatsnew/3.3.rst:2159 +#: ../../whatsnew/3.3.rst:2161 msgid "the UTF-8 encoder has been optimized" msgstr "" -#: ../../whatsnew/3.3.rst:2160 +#: ../../whatsnew/3.3.rst:2162 msgid "" "repeating a single ASCII letter and getting a substring of an ASCII string " "is 4 times faster" msgstr "" -#: ../../whatsnew/3.3.rst:2163 +#: ../../whatsnew/3.3.rst:2165 msgid "UTF-8 is now 2x to 4x faster. UTF-16 encoding is now up to 10x faster." msgstr "" -#: ../../whatsnew/3.3.rst:2165 +#: ../../whatsnew/3.3.rst:2167 msgid "" "(Contributed by Serhiy Storchaka, :issue:`14624`, :issue:`14738` and :issue:" "`15026`.)" msgstr "" -#: ../../whatsnew/3.3.rst:2170 +#: ../../whatsnew/3.3.rst:2172 msgid "Build and C API Changes" msgstr "Mudanças a construções e API C" -#: ../../whatsnew/3.3.rst:2172 +#: ../../whatsnew/3.3.rst:2174 msgid "Changes to Python's build process and to the C API include:" -msgstr "Changes to Python's build process and to the C API include:" +msgstr "As alterações no processo de construção do Python e na API C incluem:" -#: ../../whatsnew/3.3.rst:2174 +#: ../../whatsnew/3.3.rst:2176 msgid "New :pep:`3118` related function:" msgstr "" -#: ../../whatsnew/3.3.rst:2176 +#: ../../whatsnew/3.3.rst:2178 msgid ":c:func:`PyMemoryView_FromMemory`" msgstr ":c:func:`PyMemoryView_FromMemory`" -#: ../../whatsnew/3.3.rst:2178 +#: ../../whatsnew/3.3.rst:2180 msgid ":pep:`393` added new Unicode types, macros and functions:" msgstr "" -#: ../../whatsnew/3.3.rst:2180 +#: ../../whatsnew/3.3.rst:2182 msgid "High-level API:" msgstr "" -#: ../../whatsnew/3.3.rst:2182 +#: ../../whatsnew/3.3.rst:2184 msgid ":c:func:`PyUnicode_CopyCharacters`" msgstr ":c:func:`PyUnicode_CopyCharacters`" -#: ../../whatsnew/3.3.rst:2183 +#: ../../whatsnew/3.3.rst:2185 msgid ":c:func:`PyUnicode_FindChar`" msgstr ":c:func:`PyUnicode_FindChar`" -#: ../../whatsnew/3.3.rst:2184 +#: ../../whatsnew/3.3.rst:2186 msgid ":c:func:`PyUnicode_GetLength`, :c:macro:`PyUnicode_GET_LENGTH`" msgstr ":c:func:`PyUnicode_GetLength`, :c:macro:`PyUnicode_GET_LENGTH`" -#: ../../whatsnew/3.3.rst:2185 +#: ../../whatsnew/3.3.rst:2187 msgid ":c:func:`PyUnicode_New`" msgstr ":c:func:`PyUnicode_New`" -#: ../../whatsnew/3.3.rst:2186 +#: ../../whatsnew/3.3.rst:2188 msgid ":c:func:`PyUnicode_Substring`" msgstr ":c:func:`PyUnicode_Substring`" -#: ../../whatsnew/3.3.rst:2187 +#: ../../whatsnew/3.3.rst:2189 msgid ":c:func:`PyUnicode_ReadChar`, :c:func:`PyUnicode_WriteChar`" msgstr ":c:func:`PyUnicode_ReadChar`, :c:func:`PyUnicode_WriteChar`" -#: ../../whatsnew/3.3.rst:2189 +#: ../../whatsnew/3.3.rst:2191 msgid "Low-level API:" msgstr "" -#: ../../whatsnew/3.3.rst:2191 +#: ../../whatsnew/3.3.rst:2193 msgid ":c:type:`Py_UCS1`, :c:type:`Py_UCS2`, :c:type:`Py_UCS4` types" msgstr "" -#: ../../whatsnew/3.3.rst:2192 +#: ../../whatsnew/3.3.rst:2194 msgid ":c:type:`PyASCIIObject` and :c:type:`PyCompactUnicodeObject` structures" msgstr "" -#: ../../whatsnew/3.3.rst:2193 +#: ../../whatsnew/3.3.rst:2195 msgid ":c:macro:`PyUnicode_READY`" msgstr ":c:macro:`PyUnicode_READY`" -#: ../../whatsnew/3.3.rst:2194 +#: ../../whatsnew/3.3.rst:2196 msgid ":c:func:`PyUnicode_FromKindAndData`" msgstr ":c:func:`PyUnicode_FromKindAndData`" -#: ../../whatsnew/3.3.rst:2195 +#: ../../whatsnew/3.3.rst:2197 msgid ":c:func:`PyUnicode_AsUCS4`, :c:func:`PyUnicode_AsUCS4Copy`" msgstr ":c:func:`PyUnicode_AsUCS4`, :c:func:`PyUnicode_AsUCS4Copy`" -#: ../../whatsnew/3.3.rst:2196 +#: ../../whatsnew/3.3.rst:2198 msgid "" ":c:macro:`PyUnicode_DATA`, :c:macro:`PyUnicode_1BYTE_DATA`, :c:macro:" "`PyUnicode_2BYTE_DATA`, :c:macro:`PyUnicode_4BYTE_DATA`" @@ -3286,14 +3543,14 @@ msgstr "" ":c:macro:`PyUnicode_DATA`, :c:macro:`PyUnicode_1BYTE_DATA`, :c:macro:" "`PyUnicode_2BYTE_DATA`, :c:macro:`PyUnicode_4BYTE_DATA`" -#: ../../whatsnew/3.3.rst:2198 +#: ../../whatsnew/3.3.rst:2200 msgid "" ":c:macro:`PyUnicode_KIND` with :c:enum:`PyUnicode_Kind` enum: :c:data:`!" "PyUnicode_WCHAR_KIND`, :c:data:`PyUnicode_1BYTE_KIND`, :c:data:" "`PyUnicode_2BYTE_KIND`, :c:data:`PyUnicode_4BYTE_KIND`" msgstr "" -#: ../../whatsnew/3.3.rst:2201 +#: ../../whatsnew/3.3.rst:2203 msgid "" ":c:macro:`PyUnicode_READ`, :c:macro:`PyUnicode_READ_CHAR`, :c:macro:" "`PyUnicode_WRITE`" @@ -3301,56 +3558,56 @@ msgstr "" ":c:macro:`PyUnicode_READ`, :c:macro:`PyUnicode_READ_CHAR`, :c:macro:" "`PyUnicode_WRITE`" -#: ../../whatsnew/3.3.rst:2202 +#: ../../whatsnew/3.3.rst:2204 msgid ":c:macro:`PyUnicode_MAX_CHAR_VALUE`" msgstr ":c:macro:`PyUnicode_MAX_CHAR_VALUE`" -#: ../../whatsnew/3.3.rst:2204 +#: ../../whatsnew/3.3.rst:2206 msgid "" ":c:macro:`PyArg_ParseTuple` now accepts a :class:`bytearray` for the ``c`` " "format (:issue:`12380`)." msgstr "" -#: ../../whatsnew/3.3.rst:2210 +#: ../../whatsnew/3.3.rst:2212 msgid "Deprecated" msgstr "Descontinuados" -#: ../../whatsnew/3.3.rst:2213 +#: ../../whatsnew/3.3.rst:2215 msgid "Unsupported Operating Systems" msgstr "" -#: ../../whatsnew/3.3.rst:2215 +#: ../../whatsnew/3.3.rst:2217 msgid "OS/2 and VMS are no longer supported due to the lack of a maintainer." msgstr "" -#: ../../whatsnew/3.3.rst:2217 +#: ../../whatsnew/3.3.rst:2219 msgid "" "Windows 2000 and Windows platforms which set ``COMSPEC`` to ``command.com`` " "are no longer supported due to maintenance burden." msgstr "" -#: ../../whatsnew/3.3.rst:2220 +#: ../../whatsnew/3.3.rst:2222 msgid "OSF support, which was deprecated in 3.2, has been completely removed." msgstr "" -#: ../../whatsnew/3.3.rst:2224 +#: ../../whatsnew/3.3.rst:2226 msgid "Deprecated Python modules, functions and methods" msgstr "" -#: ../../whatsnew/3.3.rst:2226 +#: ../../whatsnew/3.3.rst:2228 msgid "" "Passing a non-empty string to ``object.__format__()`` is deprecated, and " "will produce a :exc:`TypeError` in Python 3.4 (:issue:`9856`)." msgstr "" -#: ../../whatsnew/3.3.rst:2228 +#: ../../whatsnew/3.3.rst:2230 msgid "" "The ``unicode_internal`` codec has been deprecated because of the :pep:" "`393`, use UTF-8, UTF-16 (``utf-16-le`` or ``utf-16-be``), or UTF-32 " "(``utf-32-le`` or ``utf-32-be``)" msgstr "" -#: ../../whatsnew/3.3.rst:2231 +#: ../../whatsnew/3.3.rst:2233 msgid "" ":meth:`ftplib.FTP.nlst` and :meth:`ftplib.FTP.dir`: use :meth:`ftplib.FTP." "mlsd`" @@ -3358,45 +3615,45 @@ msgstr "" ":meth:`ftplib.FTP.nlst` and :meth:`ftplib.FTP.dir`: use :meth:`ftplib.FTP." "mlsd`" -#: ../../whatsnew/3.3.rst:2233 +#: ../../whatsnew/3.3.rst:2235 msgid "" ":func:`platform.popen`: use the :mod:`subprocess` module. Check especially " "the :ref:`subprocess-replacements` section (:issue:`11377`)." msgstr "" -#: ../../whatsnew/3.3.rst:2235 +#: ../../whatsnew/3.3.rst:2237 msgid "" ":issue:`13374`: The Windows bytes API has been deprecated in the :mod:`os` " "module. Use Unicode filenames, instead of bytes filenames, to not depend on " "the ANSI code page anymore and to support any filename." msgstr "" -#: ../../whatsnew/3.3.rst:2238 +#: ../../whatsnew/3.3.rst:2240 msgid "" ":issue:`13988`: The :mod:`xml.etree.cElementTree` module is deprecated. The " "accelerator is used automatically whenever available." msgstr "" -#: ../../whatsnew/3.3.rst:2240 +#: ../../whatsnew/3.3.rst:2242 msgid "" "The behaviour of :func:`time.clock` depends on the platform: use the new :" "func:`time.perf_counter` or :func:`time.process_time` function instead, " "depending on your requirements, to have a well defined behaviour." msgstr "" -#: ../../whatsnew/3.3.rst:2243 +#: ../../whatsnew/3.3.rst:2245 msgid "The :func:`os.stat_float_times` function is deprecated." msgstr "" -#: ../../whatsnew/3.3.rst:2244 +#: ../../whatsnew/3.3.rst:2246 msgid ":mod:`abc` module:" msgstr "" -#: ../../whatsnew/3.3.rst:2253 +#: ../../whatsnew/3.3.rst:2255 msgid ":mod:`importlib` package:" msgstr "" -#: ../../whatsnew/3.3.rst:2255 +#: ../../whatsnew/3.3.rst:2257 msgid "" ":meth:`importlib.abc.SourceLoader.path_mtime` is now deprecated in favour " "of :meth:`importlib.abc.SourceLoader.path_stats` as bytecode files now store " @@ -3404,189 +3661,189 @@ msgid "" "compiled from." msgstr "" -#: ../../whatsnew/3.3.rst:2265 +#: ../../whatsnew/3.3.rst:2267 msgid "Deprecated functions and types of the C API" msgstr "" -#: ../../whatsnew/3.3.rst:2267 +#: ../../whatsnew/3.3.rst:2269 msgid "" "The :c:type:`Py_UNICODE` has been deprecated by :pep:`393` and will be " "removed in Python 4. All functions using this type are deprecated:" msgstr "" -#: ../../whatsnew/3.3.rst:2270 +#: ../../whatsnew/3.3.rst:2272 msgid "" "Unicode functions and methods using :c:type:`Py_UNICODE` and :c:expr:" "`Py_UNICODE*` types:" msgstr "" -#: ../../whatsnew/3.3.rst:2273 +#: ../../whatsnew/3.3.rst:2275 msgid "" ":c:macro:`!PyUnicode_FromUnicode`: use :c:func:`PyUnicode_FromWideChar` or :" "c:func:`PyUnicode_FromKindAndData`" msgstr "" -#: ../../whatsnew/3.3.rst:2275 +#: ../../whatsnew/3.3.rst:2277 msgid "" ":c:macro:`!PyUnicode_AS_UNICODE`, :c:func:`!PyUnicode_AsUnicode`, :c:func:`!" "PyUnicode_AsUnicodeAndSize`: use :c:func:`PyUnicode_AsWideCharString`" msgstr "" -#: ../../whatsnew/3.3.rst:2277 +#: ../../whatsnew/3.3.rst:2279 msgid "" ":c:macro:`!PyUnicode_AS_DATA`: use :c:macro:`PyUnicode_DATA` with :c:macro:" "`PyUnicode_READ` and :c:macro:`PyUnicode_WRITE`" msgstr "" -#: ../../whatsnew/3.3.rst:2279 +#: ../../whatsnew/3.3.rst:2281 msgid "" ":c:macro:`!PyUnicode_GET_SIZE`, :c:func:`!PyUnicode_GetSize`: use :c:macro:" "`PyUnicode_GET_LENGTH` or :c:func:`PyUnicode_GetLength`" msgstr "" -#: ../../whatsnew/3.3.rst:2281 +#: ../../whatsnew/3.3.rst:2283 msgid "" ":c:macro:`!PyUnicode_GET_DATA_SIZE`: use ``PyUnicode_GET_LENGTH(str) * " "PyUnicode_KIND(str)`` (only work on ready strings)" msgstr "" -#: ../../whatsnew/3.3.rst:2284 +#: ../../whatsnew/3.3.rst:2286 msgid "" ":c:func:`!PyUnicode_AsUnicodeCopy`: use :c:func:`PyUnicode_AsUCS4Copy` or :c:" "func:`PyUnicode_AsWideCharString`" msgstr "" -#: ../../whatsnew/3.3.rst:2286 +#: ../../whatsnew/3.3.rst:2288 msgid ":c:func:`!PyUnicode_GetMax`" msgstr "" -#: ../../whatsnew/3.3.rst:2289 +#: ../../whatsnew/3.3.rst:2291 msgid "Functions and macros manipulating Py_UNICODE* strings:" msgstr "" -#: ../../whatsnew/3.3.rst:2291 +#: ../../whatsnew/3.3.rst:2293 msgid "" ":c:macro:`!Py_UNICODE_strlen()`: use :c:func:`PyUnicode_GetLength` or :c:" "macro:`PyUnicode_GET_LENGTH`" msgstr "" -#: ../../whatsnew/3.3.rst:2293 +#: ../../whatsnew/3.3.rst:2295 msgid "" ":c:macro:`!Py_UNICODE_strcat()`: use :c:func:`PyUnicode_CopyCharacters` or :" "c:func:`PyUnicode_FromFormat`" msgstr "" -#: ../../whatsnew/3.3.rst:2295 +#: ../../whatsnew/3.3.rst:2297 msgid "" ":c:macro:`!Py_UNICODE_strcpy()`, :c:macro:`!Py_UNICODE_strncpy()`, :c:macro:" "`!Py_UNICODE_COPY()`: use :c:func:`PyUnicode_CopyCharacters` or :c:func:" "`PyUnicode_Substring`" msgstr "" -#: ../../whatsnew/3.3.rst:2298 +#: ../../whatsnew/3.3.rst:2300 msgid ":c:macro:`!Py_UNICODE_strcmp()`: use :c:func:`PyUnicode_Compare`" msgstr "" -#: ../../whatsnew/3.3.rst:2299 +#: ../../whatsnew/3.3.rst:2301 msgid ":c:macro:`!Py_UNICODE_strncmp()`: use :c:func:`PyUnicode_Tailmatch`" msgstr "" -#: ../../whatsnew/3.3.rst:2300 +#: ../../whatsnew/3.3.rst:2302 msgid "" ":c:macro:`!Py_UNICODE_strchr()`, :c:macro:`!Py_UNICODE_strrchr()`: use :c:" "func:`PyUnicode_FindChar`" msgstr "" -#: ../../whatsnew/3.3.rst:2302 +#: ../../whatsnew/3.3.rst:2304 msgid ":c:macro:`!Py_UNICODE_FILL()`: use :c:func:`PyUnicode_Fill`" msgstr "" -#: ../../whatsnew/3.3.rst:2303 +#: ../../whatsnew/3.3.rst:2305 msgid ":c:macro:`!Py_UNICODE_MATCH`" msgstr "" -#: ../../whatsnew/3.3.rst:2305 +#: ../../whatsnew/3.3.rst:2307 msgid "Encoders:" msgstr "" -#: ../../whatsnew/3.3.rst:2307 +#: ../../whatsnew/3.3.rst:2309 msgid ":c:func:`!PyUnicode_Encode`: use :c:func:`!PyUnicode_AsEncodedObject`" msgstr "" -#: ../../whatsnew/3.3.rst:2308 +#: ../../whatsnew/3.3.rst:2310 msgid ":c:func:`!PyUnicode_EncodeUTF7`" msgstr "" -#: ../../whatsnew/3.3.rst:2309 +#: ../../whatsnew/3.3.rst:2311 msgid "" ":c:func:`!PyUnicode_EncodeUTF8`: use :c:func:`PyUnicode_AsUTF8` or :c:func:" "`PyUnicode_AsUTF8String`" msgstr "" -#: ../../whatsnew/3.3.rst:2311 +#: ../../whatsnew/3.3.rst:2313 msgid ":c:func:`!PyUnicode_EncodeUTF32`" msgstr "" -#: ../../whatsnew/3.3.rst:2312 +#: ../../whatsnew/3.3.rst:2314 msgid ":c:func:`!PyUnicode_EncodeUTF16`" msgstr "" -#: ../../whatsnew/3.3.rst:2313 +#: ../../whatsnew/3.3.rst:2315 msgid "" ":c:func:`!PyUnicode_EncodeUnicodeEscape` use :c:func:" "`PyUnicode_AsUnicodeEscapeString`" msgstr "" -#: ../../whatsnew/3.3.rst:2315 +#: ../../whatsnew/3.3.rst:2317 msgid "" ":c:func:`!PyUnicode_EncodeRawUnicodeEscape` use :c:func:" "`PyUnicode_AsRawUnicodeEscapeString`" msgstr "" -#: ../../whatsnew/3.3.rst:2317 +#: ../../whatsnew/3.3.rst:2319 msgid "" ":c:func:`!PyUnicode_EncodeLatin1`: use :c:func:`PyUnicode_AsLatin1String`" msgstr "" -#: ../../whatsnew/3.3.rst:2318 +#: ../../whatsnew/3.3.rst:2320 msgid ":c:func:`!PyUnicode_EncodeASCII`: use :c:func:`PyUnicode_AsASCIIString`" msgstr "" -#: ../../whatsnew/3.3.rst:2319 +#: ../../whatsnew/3.3.rst:2321 msgid ":c:func:`!PyUnicode_EncodeCharmap`" msgstr "" -#: ../../whatsnew/3.3.rst:2320 +#: ../../whatsnew/3.3.rst:2322 msgid ":c:func:`!PyUnicode_TranslateCharmap`" msgstr "" -#: ../../whatsnew/3.3.rst:2321 +#: ../../whatsnew/3.3.rst:2323 msgid "" ":c:func:`!PyUnicode_EncodeMBCS`: use :c:func:`PyUnicode_AsMBCSString` or :c:" "func:`PyUnicode_EncodeCodePage` (with ``CP_ACP`` code_page)" msgstr "" -#: ../../whatsnew/3.3.rst:2323 +#: ../../whatsnew/3.3.rst:2325 msgid "" ":c:func:`!PyUnicode_EncodeDecimal`, :c:func:`!" "PyUnicode_TransformDecimalToASCII`" msgstr "" -#: ../../whatsnew/3.3.rst:2328 +#: ../../whatsnew/3.3.rst:2330 msgid "Deprecated features" msgstr "" -#: ../../whatsnew/3.3.rst:2330 +#: ../../whatsnew/3.3.rst:2332 msgid "" "The :mod:`array` module's ``'u'`` format code is now deprecated and will be " "removed in Python 4 together with the rest of the (:c:type:`Py_UNICODE`) API." msgstr "" -#: ../../whatsnew/3.3.rst:2335 +#: ../../whatsnew/3.3.rst:2337 msgid "Porting to Python 3.3" msgstr "" -#: ../../whatsnew/3.3.rst:2337 +#: ../../whatsnew/3.3.rst:2339 msgid "" "This section lists previously described changes and other bugfixes that may " "require changes to your code." @@ -3594,18 +3851,18 @@ msgstr "" "Esta seção lista as alterações descritas anteriormente e outras correções " "que podem exigir alterações no seu código." -#: ../../whatsnew/3.3.rst:2343 +#: ../../whatsnew/3.3.rst:2345 msgid "Porting Python code" msgstr "" -#: ../../whatsnew/3.3.rst:2345 +#: ../../whatsnew/3.3.rst:2347 msgid "" "Hash randomization is enabled by default. Set the :envvar:`PYTHONHASHSEED` " "environment variable to ``0`` to disable hash randomization. See also the :" "meth:`object.__hash__` method." msgstr "" -#: ../../whatsnew/3.3.rst:2349 +#: ../../whatsnew/3.3.rst:2351 msgid "" ":issue:`12326`: On Linux, sys.platform doesn't contain the major version " "anymore. It is now always 'linux', instead of 'linux2' or 'linux3' depending " @@ -3614,7 +3871,7 @@ msgid "" "if you don't need to support older Python versions." msgstr "" -#: ../../whatsnew/3.3.rst:2355 +#: ../../whatsnew/3.3.rst:2357 msgid "" ":issue:`13847`, :issue:`14180`: :mod:`time` and :mod:`datetime`: :exc:" "`OverflowError` is now raised instead of :exc:`ValueError` if a timestamp is " @@ -3622,7 +3879,7 @@ msgid "" "or :c:func:`localtime` failed." msgstr "" -#: ../../whatsnew/3.3.rst:2360 +#: ../../whatsnew/3.3.rst:2362 msgid "" "The default finders used by import now utilize a cache of what is contained " "within a specific directory. If you create a Python source file or " @@ -3631,7 +3888,7 @@ msgid "" "file." msgstr "" -#: ../../whatsnew/3.3.rst:2365 +#: ../../whatsnew/3.3.rst:2367 msgid "" ":exc:`ImportError` now uses the full name of the module that was attempted " "to be imported. Doctests that check ImportErrors' message will need to be " @@ -3639,7 +3896,7 @@ msgid "" "name." msgstr "" -#: ../../whatsnew/3.3.rst:2370 +#: ../../whatsnew/3.3.rst:2372 msgid "" "The *index* argument to :func:`__import__` now defaults to 0 instead of -1 " "and no longer support negative values. It was an oversight when :pep:`328` " @@ -3650,20 +3907,20 @@ msgid "" "import_module` rather than call :func:`__import__` directly." msgstr "" -#: ../../whatsnew/3.3.rst:2378 +#: ../../whatsnew/3.3.rst:2380 msgid "" ":func:`__import__` no longer allows one to use an index value other than 0 " "for top-level modules. E.g. ``__import__('sys', level=1)`` is now an error." msgstr "" -#: ../../whatsnew/3.3.rst:2381 +#: ../../whatsnew/3.3.rst:2383 msgid "" "Because :data:`sys.meta_path` and :data:`sys.path_hooks` now have finders on " "them by default, you will most likely want to use :meth:`list.insert` " "instead of :meth:`list.append` to add to those lists." msgstr "" -#: ../../whatsnew/3.3.rst:2385 +#: ../../whatsnew/3.3.rst:2387 msgid "" "Because ``None`` is now inserted into :data:`sys.path_importer_cache`, if " "you are clearing out entries in the dictionary of paths that do not have a " @@ -3674,7 +3931,7 @@ msgid "" "finders, but semantically it should not change anything." msgstr "" -#: ../../whatsnew/3.3.rst:2393 +#: ../../whatsnew/3.3.rst:2395 msgid "" ":class:`!importlib.abc.Finder` no longer specifies a ``find_module()`` " "abstract method that must be implemented. If you were relying on subclasses " @@ -3683,7 +3940,7 @@ msgid "" "in the case of working with :term:`path entry finders `." msgstr "" -#: ../../whatsnew/3.3.rst:2399 +#: ../../whatsnew/3.3.rst:2401 msgid "" ":mod:`pkgutil` has been converted to use :mod:`importlib` internally. This " "eliminates many edge cases where the old behaviour of the :pep:`302` import " @@ -3694,7 +3951,7 @@ msgid "" "do not provide the non-standard ``iter_modules()`` method." msgstr "" -#: ../../whatsnew/3.3.rst:2407 +#: ../../whatsnew/3.3.rst:2409 msgid "" "A longstanding RFC-compliance bug (:issue:`1079`) in the parsing done by :" "func:`email.header.decode_header` has been fixed. Code that uses the " @@ -3708,7 +3965,7 @@ msgid "" "already present in the input strings." msgstr "" -#: ../../whatsnew/3.3.rst:2418 +#: ../../whatsnew/3.3.rst:2420 msgid "" ":func:`email.utils.formataddr` now does the correct content transfer " "encoding when passed non-``ASCII`` display names. Any code that depended on " @@ -3716,7 +3973,7 @@ msgid "" "formatted output string will need to be changed (:issue:`1690608`)." msgstr "" -#: ../../whatsnew/3.3.rst:2423 +#: ../../whatsnew/3.3.rst:2425 msgid "" ":meth:`poplib.POP3.quit` may now raise protocol errors like all other " "``poplib`` methods. Code that assumes ``quit`` does not raise :exc:`poplib." @@ -3724,57 +3981,57 @@ msgid "" "encountered by a particular application (:issue:`11291`)." msgstr "" -#: ../../whatsnew/3.3.rst:2428 +#: ../../whatsnew/3.3.rst:2430 msgid "" "The ``strict`` argument to :class:`email.parser.Parser`, deprecated since " "Python 2.4, has finally been removed." msgstr "" -#: ../../whatsnew/3.3.rst:2431 +#: ../../whatsnew/3.3.rst:2433 msgid "" "The deprecated method ``unittest.TestCase.assertSameElements`` has been " "removed." msgstr "" -#: ../../whatsnew/3.3.rst:2434 +#: ../../whatsnew/3.3.rst:2436 msgid "The deprecated variable ``time.accept2dyear`` has been removed." msgstr "" -#: ../../whatsnew/3.3.rst:2436 +#: ../../whatsnew/3.3.rst:2438 msgid "" "The deprecated ``Context._clamp`` attribute has been removed from the :mod:" "`decimal` module. It was previously replaced by the public attribute :attr:" "`~decimal.Context.clamp`. (See :issue:`8540`.)" msgstr "" -#: ../../whatsnew/3.3.rst:2440 +#: ../../whatsnew/3.3.rst:2442 msgid "" "The undocumented internal helper class ``SSLFakeFile`` has been removed " "from :mod:`smtplib`, since its functionality has long been provided directly " "by :meth:`socket.socket.makefile`." msgstr "" -#: ../../whatsnew/3.3.rst:2444 +#: ../../whatsnew/3.3.rst:2446 msgid "" "Passing a negative value to :func:`time.sleep` on Windows now raises an " "error instead of sleeping forever. It has always raised an error on posix." msgstr "" -#: ../../whatsnew/3.3.rst:2447 +#: ../../whatsnew/3.3.rst:2449 msgid "" "The ``ast.__version__`` constant has been removed. If you need to make " "decisions affected by the AST version, use :data:`sys.version_info` to make " "the decision." msgstr "" -#: ../../whatsnew/3.3.rst:2451 +#: ../../whatsnew/3.3.rst:2453 msgid "" "Code that used to work around the fact that the :mod:`threading` module used " "factory functions by subclassing the private classes will need to change to " "subclass the now-public classes." msgstr "" -#: ../../whatsnew/3.3.rst:2455 +#: ../../whatsnew/3.3.rst:2457 msgid "" "The undocumented debugging machinery in the threading module has been " "removed, simplifying the code. This should have no effect on production " @@ -3782,24 +4039,24 @@ msgid "" "interacting with it (:issue:`13550`)." msgstr "" -#: ../../whatsnew/3.3.rst:2462 +#: ../../whatsnew/3.3.rst:2464 msgid "Porting C code" msgstr "" -#: ../../whatsnew/3.3.rst:2464 +#: ../../whatsnew/3.3.rst:2466 msgid "" "In the course of changes to the buffer API the undocumented :c:member:`!" "smalltable` member of the :c:type:`Py_buffer` structure has been removed and " "the layout of the :c:type:`PyMemoryViewObject` has changed." msgstr "" -#: ../../whatsnew/3.3.rst:2469 +#: ../../whatsnew/3.3.rst:2471 msgid "" "All extensions relying on the relevant parts in ``memoryobject.h`` or " "``object.h`` must be rebuilt." msgstr "" -#: ../../whatsnew/3.3.rst:2472 +#: ../../whatsnew/3.3.rst:2474 msgid "" "Due to :ref:`PEP 393 `, the :c:type:`Py_UNICODE` type and all " "functions using this type are deprecated (but will stay available for at " @@ -3809,7 +4066,7 @@ msgid "" "doc:`Unicode API <../c-api/unicode>`." msgstr "" -#: ../../whatsnew/3.3.rst:2479 +#: ../../whatsnew/3.3.rst:2481 msgid "" "However, if you only have been using high-level functions such as :c:func:" "`PyUnicode_Concat()`, :c:func:`PyUnicode_Join` or :c:func:" @@ -3817,11 +4074,11 @@ msgid "" "new unicode representations." msgstr "" -#: ../../whatsnew/3.3.rst:2484 +#: ../../whatsnew/3.3.rst:2486 msgid ":c:func:`PyImport_GetMagicNumber` now returns ``-1`` upon failure." msgstr "" -#: ../../whatsnew/3.3.rst:2486 +#: ../../whatsnew/3.3.rst:2488 msgid "" "As a negative value for the *level* argument to :func:`__import__` is no " "longer valid, the same now holds for :c:func:`PyImport_ImportModuleLevel`. " @@ -3829,11 +4086,11 @@ msgid "" "`PyImport_ImportModuleEx` is now ``0`` instead of ``-1``." msgstr "" -#: ../../whatsnew/3.3.rst:2493 +#: ../../whatsnew/3.3.rst:2495 msgid "Building C extensions" msgstr "" -#: ../../whatsnew/3.3.rst:2495 +#: ../../whatsnew/3.3.rst:2497 msgid "" "The range of possible file names for C extensions has been narrowed. Very " "rarely used spellings have been suppressed: under POSIX, files named " @@ -3843,32 +4100,32 @@ msgid "" "remove the ``module`` string from the file names)." msgstr "" -#: ../../whatsnew/3.3.rst:2503 +#: ../../whatsnew/3.3.rst:2505 msgid "(implemented in :issue:`14040`.)" msgstr "" -#: ../../whatsnew/3.3.rst:2507 +#: ../../whatsnew/3.3.rst:2509 msgid "Command Line Switch Changes" msgstr "" -#: ../../whatsnew/3.3.rst:2509 +#: ../../whatsnew/3.3.rst:2511 msgid "" "The -Q command-line flag and related artifacts have been removed. Code " "checking sys.flags.division_warning will need updating." msgstr "" -#: ../../whatsnew/3.3.rst:2512 +#: ../../whatsnew/3.3.rst:2514 msgid "(:issue:`10998`, contributed by Éric Araujo.)" msgstr "" -#: ../../whatsnew/3.3.rst:2514 +#: ../../whatsnew/3.3.rst:2516 msgid "" "When :program:`python` is started with :option:`-S`, ``import site`` will no " "longer add site-specific paths to the module search paths. In previous " "versions, it did." msgstr "" -#: ../../whatsnew/3.3.rst:2518 +#: ../../whatsnew/3.3.rst:2520 msgid "" "(:issue:`11591`, contributed by Carl Meyer with editions by Éric Araujo.)" msgstr "" diff --git a/whatsnew/3.4.po b/whatsnew/3.4.po index dc3b55ed5..b4100b297 100644 --- a/whatsnew/3.4.po +++ b/whatsnew/3.4.po @@ -1,29 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Victor Matheus Castro , 2021 -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2023 -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-29 13:04+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-02-21 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -229,7 +225,7 @@ msgstr "The :mod:`ipaddress` module API has been declared stable" #: ../../whatsnew/3.4.rst:132 msgid "Security improvements:" -msgstr "Melhorias de segurança:" +msgstr "Melhorias de Segurança:" #: ../../whatsnew/3.4.rst:134 msgid "" @@ -446,17 +442,19 @@ msgstr "" #: ../../whatsnew/3.4.rst:218 msgid "" -"As `discussed in the PEP`__, platform packagers may choose not to install " -"these commands by default, as long as, when invoked, they provide clear and " -"simple directions on how to install them on that platform (usually using the " -"system package manager)." +"As :pep:`discussed in the PEP <0453#recommendations-for-downstream-" +"distributors>` platform packagers may choose not to install these commands " +"by default, as long as, when invoked, they provide clear and simple " +"directions on how to install them on that platform (usually using the system " +"package manager)." msgstr "" -"As `discussed in the PEP`__, platform packagers may choose not to install " -"these commands by default, as long as, when invoked, they provide clear and " -"simple directions on how to install them on that platform (usually using the " -"system package manager)." +"As :pep:`discussed in the PEP <0453#recommendations-for-downstream-" +"distributors>` platform packagers may choose not to install these commands " +"by default, as long as, when invoked, they provide clear and simple " +"directions on how to install them on that platform (usually using the system " +"package manager)." -#: ../../whatsnew/3.4.rst:227 +#: ../../whatsnew/3.4.rst:226 msgid "" "To avoid conflicts between parallel Python 2 and Python 3 installations, " "only the versioned ``pip3`` and ``pip3.4`` commands are bootstrapped by " @@ -476,11 +474,11 @@ msgstr "" "the ``-m`` switch rather than directly to avoid ambiguity on systems with " "multiple Python installations." -#: ../../whatsnew/3.4.rst:238 +#: ../../whatsnew/3.4.rst:237 msgid "Documentation Changes" msgstr "Mudanças na documentação" -#: ../../whatsnew/3.4.rst:240 +#: ../../whatsnew/3.4.rst:239 msgid "" "As part of this change, the :ref:`installing-index` and :ref:`distributing-" "index` sections of the documentation have been completely redesigned as " @@ -496,7 +494,7 @@ msgstr "" "Packaging User Guide `__ and the documentation " "of the individual projects." -#: ../../whatsnew/3.4.rst:248 +#: ../../whatsnew/3.4.rst:247 msgid "" "However, as this migration is currently still incomplete, the legacy " "versions of those guides remaining available as :ref:`install-index` and :" @@ -506,11 +504,11 @@ msgstr "" "desses guias permanecem disponíveis como :ref:`install-index` e :ref:" "`setuptools-index`." -#: ../../whatsnew/3.4.rst:254 +#: ../../whatsnew/3.4.rst:253 msgid ":pep:`453` -- Explicit bootstrapping of pip in Python installations" msgstr ":pep:`453` -- Explicit bootstrapping of pip in Python installations" -#: ../../whatsnew/3.4.rst:255 +#: ../../whatsnew/3.4.rst:254 msgid "" "PEP written by Donald Stufft and Nick Coghlan, implemented by Donald Stufft, " "Nick Coghlan, Martin von Löwis and Ned Deily." @@ -518,11 +516,11 @@ msgstr "" "PEP written by Donald Stufft and Nick Coghlan, implemented by Donald Stufft, " "Nick Coghlan, Martin von Löwis and Ned Deily." -#: ../../whatsnew/3.4.rst:262 +#: ../../whatsnew/3.4.rst:261 msgid "PEP 446: Newly Created File Descriptors Are Non-Inheritable" msgstr "PEP 446: Newly Created File Descriptors Are Non-Inheritable" -#: ../../whatsnew/3.4.rst:264 +#: ../../whatsnew/3.4.rst:263 msgid "" ":pep:`446` makes newly created file descriptors :ref:`non-inheritable " "`. In general, this is the behavior an application will " @@ -536,7 +534,7 @@ msgstr "" "the new process can lead to all sorts of hard to find bugs, and potentially " "to security issues." -#: ../../whatsnew/3.4.rst:270 +#: ../../whatsnew/3.4.rst:269 msgid "" "However, there are occasions when inheritance is desired. To support these " "cases, the following new functions and methods are available:" @@ -544,33 +542,33 @@ msgstr "" "However, there are occasions when inheritance is desired. To support these " "cases, the following new functions and methods are available:" -#: ../../whatsnew/3.4.rst:273 +#: ../../whatsnew/3.4.rst:272 msgid ":func:`os.get_inheritable`, :func:`os.set_inheritable`" msgstr ":func:`os.get_inheritable`, :func:`os.set_inheritable`" -#: ../../whatsnew/3.4.rst:274 +#: ../../whatsnew/3.4.rst:273 msgid ":func:`os.get_handle_inheritable`, :func:`os.set_handle_inheritable`" msgstr ":func:`os.get_handle_inheritable`, :func:`os.set_handle_inheritable`" -#: ../../whatsnew/3.4.rst:275 +#: ../../whatsnew/3.4.rst:274 msgid "" ":meth:`socket.socket.get_inheritable`, :meth:`socket.socket.set_inheritable`" msgstr "" ":meth:`socket.socket.get_inheritable`, :meth:`socket.socket.set_inheritable`" -#: ../../whatsnew/3.4.rst:279 +#: ../../whatsnew/3.4.rst:278 msgid ":pep:`446` -- Make newly created file descriptors non-inheritable" msgstr ":pep:`446` -- Make newly created file descriptors non-inheritable" -#: ../../whatsnew/3.4.rst:280 ../../whatsnew/3.4.rst:1812 +#: ../../whatsnew/3.4.rst:279 ../../whatsnew/3.4.rst:1811 msgid "PEP written and implemented by Victor Stinner." msgstr "PEP escrito e implementado por Victor Stinner." -#: ../../whatsnew/3.4.rst:286 +#: ../../whatsnew/3.4.rst:285 msgid "Improvements to Codec Handling" msgstr "Melhorias no manuseio de Codecs" -#: ../../whatsnew/3.4.rst:288 +#: ../../whatsnew/3.4.rst:287 msgid "" "Since it was first introduced, the :mod:`codecs` module has always been " "intended to operate as a type-neutral dynamic encoding and decoding system. " @@ -584,7 +582,7 @@ msgstr "" "restricted convenience methods on the builtin :class:`str`, :class:`bytes` " "and :class:`bytearray` types, has historically obscured that fact." -#: ../../whatsnew/3.4.rst:295 +#: ../../whatsnew/3.4.rst:294 msgid "" "As a key step in clarifying the situation, the :meth:`codecs.encode` and :" "meth:`codecs.decode` convenience functions are now properly documented in " @@ -598,7 +596,7 @@ msgstr "" "module (and have been covered by the regression test suite) since Python " "2.4, but were previously only discoverable through runtime introspection." -#: ../../whatsnew/3.4.rst:301 +#: ../../whatsnew/3.4.rst:300 msgid "" "Unlike the convenience methods on :class:`str`, :class:`bytes` and :class:" "`bytearray`, the :mod:`codecs` convenience functions support arbitrary " @@ -612,7 +610,7 @@ msgstr "" "text encodings (in Python 3) or ``basestring`` <-> ``basestring`` " "conversions (in Python 2)." -#: ../../whatsnew/3.4.rst:307 +#: ../../whatsnew/3.4.rst:306 msgid "" "In Python 3.4, the interpreter is able to identify the known non-text " "encodings provided in the standard library and direct users towards these " @@ -622,7 +620,45 @@ msgstr "" "encodings provided in the standard library and direct users towards these " "general purpose convenience functions when appropriate::" -#: ../../whatsnew/3.4.rst:326 +#: ../../whatsnew/3.4.rst:310 +msgid "" +">>> b\"abcdef\".decode(\"hex\")\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"LookupError: 'hex' is not a text encoding; use codecs.decode() to handle " +"arbitrary codecs\n" +"\n" +">>> \"hello\".encode(\"rot13\")\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"LookupError: 'rot13' is not a text encoding; use codecs.encode() to handle " +"arbitrary codecs\n" +"\n" +">>> open(\"foo.txt\", encoding=\"hex\")\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"LookupError: 'hex' is not a text encoding; use codecs.open() to handle " +"arbitrary codecs" +msgstr "" +">>> b\"abcdef\".decode(\"hex\")\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"LookupError: 'hex' is not a text encoding; use codecs.decode() to handle " +"arbitrary codecs\n" +"\n" +">>> \"hello\".encode(\"rot13\")\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"LookupError: 'rot13' is not a text encoding; use codecs.encode() to handle " +"arbitrary codecs\n" +"\n" +">>> open(\"foo.txt\", encoding=\"hex\")\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"LookupError: 'hex' is not a text encoding; use codecs.open() to handle " +"arbitrary codecs" + +#: ../../whatsnew/3.4.rst:325 msgid "" "In a related change, whenever it is feasible without breaking backwards " "compatibility, exceptions raised during encoding and decoding operations are " @@ -634,7 +670,73 @@ msgstr "" "wrapped in a chained exception of the same type that mentions the name of " "the codec responsible for producing the error::" -#: ../../whatsnew/3.4.rst:359 +#: ../../whatsnew/3.4.rst:330 +msgid "" +">>> import codecs\n" +"\n" +">>> codecs.decode(b\"abcdefgh\", \"hex\")\n" +"Traceback (most recent call last):\n" +" File \"/usr/lib/python3.4/encodings/hex_codec.py\", line 20, in " +"hex_decode\n" +" return (binascii.a2b_hex(input), len(input))\n" +"binascii.Error: Non-hexadecimal digit found\n" +"\n" +"The above exception was the direct cause of the following exception:\n" +"\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"binascii.Error: decoding with 'hex' codec failed (Error: Non-hexadecimal " +"digit found)\n" +"\n" +">>> codecs.encode(\"hello\", \"bz2\")\n" +"Traceback (most recent call last):\n" +" File \"/usr/lib/python3.4/encodings/bz2_codec.py\", line 17, in " +"bz2_encode\n" +" return (bz2.compress(input), len(input))\n" +" File \"/usr/lib/python3.4/bz2.py\", line 498, in compress\n" +" return comp.compress(data) + comp.flush()\n" +"TypeError: 'str' does not support the buffer interface\n" +"\n" +"The above exception was the direct cause of the following exception:\n" +"\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: encoding with 'bz2' codec failed (TypeError: 'str' does not " +"support the buffer interface)" +msgstr "" +">>> import codecs\n" +"\n" +">>> codecs.decode(b\"abcdefgh\", \"hex\")\n" +"Traceback (most recent call last):\n" +" File \"/usr/lib/python3.4/encodings/hex_codec.py\", line 20, in " +"hex_decode\n" +" return (binascii.a2b_hex(input), len(input))\n" +"binascii.Error: Non-hexadecimal digit found\n" +"\n" +"The above exception was the direct cause of the following exception:\n" +"\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"binascii.Error: decoding with 'hex' codec failed (Error: Non-hexadecimal " +"digit found)\n" +"\n" +">>> codecs.encode(\"hello\", \"bz2\")\n" +"Traceback (most recent call last):\n" +" File \"/usr/lib/python3.4/encodings/bz2_codec.py\", line 17, in " +"bz2_encode\n" +" return (bz2.compress(input), len(input))\n" +" File \"/usr/lib/python3.4/bz2.py\", line 498, in compress\n" +" return comp.compress(data) + comp.flush()\n" +"TypeError: 'str' does not support the buffer interface\n" +"\n" +"The above exception was the direct cause of the following exception:\n" +"\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: encoding with 'bz2' codec failed (TypeError: 'str' does not " +"support the buffer interface)" + +#: ../../whatsnew/3.4.rst:358 msgid "" "Finally, as the examples above show, these improvements have permitted the " "restoration of the convenience aliases for the non-Unicode codecs that were " @@ -646,7 +748,21 @@ msgstr "" "themselves restored in Python 3.2. This means that encoding binary data to " "and from its hexadecimal representation (for example) can now be written as::" -#: ../../whatsnew/3.4.rst:371 +#: ../../whatsnew/3.4.rst:364 +msgid "" +">>> from codecs import encode, decode\n" +">>> encode(b\"hello\", \"hex\")\n" +"b'68656c6c6f'\n" +">>> decode(b\"68656c6c6f\", \"hex\")\n" +"b'hello'" +msgstr "" +">>> from codecs import encode, decode\n" +">>> encode(b\"hello\", \"hex\")\n" +"b'68656c6c6f'\n" +">>> decode(b\"68656c6c6f\", \"hex\")\n" +"b'hello'" + +#: ../../whatsnew/3.4.rst:370 msgid "" "The binary and text transforms provided in the standard library are detailed " "in :ref:`binary-transforms` and :ref:`text-transforms`." @@ -654,7 +770,7 @@ msgstr "" "The binary and text transforms provided in the standard library are detailed " "in :ref:`binary-transforms` and :ref:`text-transforms`." -#: ../../whatsnew/3.4.rst:374 +#: ../../whatsnew/3.4.rst:373 msgid "" "(Contributed by Nick Coghlan in :issue:`7475`, :issue:`17827`, :issue:" "`17828` and :issue:`19619`.)" @@ -662,11 +778,11 @@ msgstr "" "(Contributed by Nick Coghlan in :issue:`7475`, :issue:`17827`, :issue:" "`17828` and :issue:`19619`.)" -#: ../../whatsnew/3.4.rst:381 +#: ../../whatsnew/3.4.rst:380 msgid "PEP 451: A ModuleSpec Type for the Import System" msgstr "PEP 451: A ModuleSpec Type for the Import System" -#: ../../whatsnew/3.4.rst:383 +#: ../../whatsnew/3.4.rst:382 msgid "" ":pep:`451` provides an encapsulation of the information about a module that " "the import machinery will use to load it (that is, a module specification). " @@ -680,7 +796,7 @@ msgstr "" "related APIs. The change is also a stepping stone for `several future import-" "related improvements`__." -#: ../../whatsnew/3.4.rst:391 +#: ../../whatsnew/3.4.rst:390 msgid "" "The public-facing changes from the PEP are entirely backward-compatible. " "Furthermore, they should be transparent to everyone but importer authors. " @@ -698,19 +814,19 @@ msgstr "" "ref:`deprecated-3.4` section for a list of methods that should be replaced " "and their replacements." -#: ../../whatsnew/3.4.rst:401 +#: ../../whatsnew/3.4.rst:400 msgid "Other Language Changes" msgstr "Outras mudanças na linguagem" -#: ../../whatsnew/3.4.rst:403 +#: ../../whatsnew/3.4.rst:402 msgid "Some smaller changes made to the core Python language are:" msgstr "Algumas das mudanças menores feitas no núcleo da linguagem Python são:" -#: ../../whatsnew/3.4.rst:405 +#: ../../whatsnew/3.4.rst:404 msgid "Unicode database updated to UCD version 6.3." msgstr "Unicode database updated to UCD version 6.3." -#: ../../whatsnew/3.4.rst:407 +#: ../../whatsnew/3.4.rst:406 msgid "" ":func:`min` and :func:`max` now accept a *default* keyword-only argument " "that can be used to specify the value they return if the iterable they are " @@ -721,12 +837,12 @@ msgstr "" "that can be used to specify the value they return if the iterable they are " "evaluating has no elements. (Contributed by Julian Berman in :issue:`18111`.)" -#: ../../whatsnew/3.4.rst:412 +#: ../../whatsnew/3.4.rst:411 msgid "Module objects are now :ref:`weakly referenceable `." msgstr "" "Objetos módulo são agora :ref:`fracamente referenciáveis `." -#: ../../whatsnew/3.4.rst:414 +#: ../../whatsnew/3.4.rst:413 msgid "" "Module ``__file__`` attributes (and related values) should now always " "contain absolute paths by default, with the sole exception of ``__main__." @@ -738,7 +854,7 @@ msgstr "" "__file__`` when a script has been executed directly using a relative path. " "(Contributed by Brett Cannon in :issue:`18416`.)" -#: ../../whatsnew/3.4.rst:419 +#: ../../whatsnew/3.4.rst:418 msgid "" "All the UTF-\\* codecs (except UTF-7) now reject surrogates during both " "encoding and decoding unless the ``surrogatepass`` error handler is used, " @@ -754,7 +870,7 @@ msgstr "" "characters). (Contributed by Victor Stinner, Kang-Hao (Kenny) Lu and Serhiy " "Storchaka in :issue:`12892`.)" -#: ../../whatsnew/3.4.rst:426 +#: ../../whatsnew/3.4.rst:425 msgid "" "New German EBCDIC :ref:`codec ` ``cp273``. (Contributed " "by Michael Bierenfeld and Andrew Kuchling in :issue:`1097797`.)" @@ -762,7 +878,7 @@ msgstr "" "New German EBCDIC :ref:`codec ` ``cp273``. (Contributed " "by Michael Bierenfeld and Andrew Kuchling in :issue:`1097797`.)" -#: ../../whatsnew/3.4.rst:429 +#: ../../whatsnew/3.4.rst:428 msgid "" "New Ukrainian :ref:`codec ` ``cp1125``. (Contributed by " "Serhiy Storchaka in :issue:`19668`.)" @@ -770,7 +886,7 @@ msgstr "" "New Ukrainian :ref:`codec ` ``cp1125``. (Contributed by " "Serhiy Storchaka in :issue:`19668`.)" -#: ../../whatsnew/3.4.rst:432 +#: ../../whatsnew/3.4.rst:431 msgid "" ":class:`bytes`.join() and :class:`bytearray`.join() now accept arbitrary " "buffer objects as arguments. (Contributed by Antoine Pitrou in :issue:" @@ -780,7 +896,7 @@ msgstr "" "buffer objects as arguments. (Contributed by Antoine Pitrou in :issue:" "`15958`.)" -#: ../../whatsnew/3.4.rst:436 +#: ../../whatsnew/3.4.rst:435 msgid "" "The :class:`int` constructor now accepts any object that has an " "``__index__`` method for its *base* argument. (Contributed by Mark " @@ -790,7 +906,7 @@ msgstr "" "``__index__`` method for its *base* argument. (Contributed by Mark Dickinson " "in :issue:`16772`.)" -#: ../../whatsnew/3.4.rst:440 +#: ../../whatsnew/3.4.rst:439 msgid "" "Frame objects now have a :func:`~frame.clear` method that clears all " "references to local variables from the frame. (Contributed by Antoine " @@ -800,7 +916,7 @@ msgstr "" "references to local variables from the frame. (Contributed by Antoine Pitrou " "in :issue:`17934`.)" -#: ../../whatsnew/3.4.rst:444 +#: ../../whatsnew/3.4.rst:443 msgid "" ":class:`memoryview` is now registered as a :class:`Sequence `, and supports the :func:`reversed` builtin. (Contributed by Nick " @@ -810,7 +926,7 @@ msgstr "" "abc>`, and supports the :func:`reversed` builtin. (Contributed by Nick " "Coghlan and Claudiu Popa in :issue:`18690` and :issue:`19078`.)" -#: ../../whatsnew/3.4.rst:448 +#: ../../whatsnew/3.4.rst:447 msgid "" "Signatures reported by :func:`help` have been modified and improved in " "several cases as a result of the introduction of Argument Clinic and other " @@ -820,7 +936,7 @@ msgstr "" "several cases as a result of the introduction of Argument Clinic and other " "changes to the :mod:`inspect` and :mod:`pydoc` modules." -#: ../../whatsnew/3.4.rst:452 +#: ../../whatsnew/3.4.rst:451 msgid "" ":meth:`~object.__length_hint__` is now part of the formal language " "specification (see :pep:`424`). (Contributed by Armin Ronacher in :issue:" @@ -830,15 +946,15 @@ msgstr "" "specification (see :pep:`424`). (Contributed by Armin Ronacher in :issue:" "`16148`.)" -#: ../../whatsnew/3.4.rst:458 +#: ../../whatsnew/3.4.rst:457 msgid "New Modules" msgstr "Novos módulos" -#: ../../whatsnew/3.4.rst:464 +#: ../../whatsnew/3.4.rst:463 msgid "asyncio" msgstr "asyncio" -#: ../../whatsnew/3.4.rst:466 +#: ../../whatsnew/3.4.rst:465 msgid "" "The new :mod:`asyncio` module (defined in :pep:`3156`) provides a standard " "pluggable event loop model for Python, providing solid asynchronous IO " @@ -850,24 +966,24 @@ msgstr "" "support in the standard library, and making it easier for other event loop " "implementations to interoperate with the standard library and each other." -#: ../../whatsnew/3.4.rst:471 ../../whatsnew/3.4.rst:534 +#: ../../whatsnew/3.4.rst:470 ../../whatsnew/3.4.rst:533 msgid "For Python 3.4, this module is considered a :term:`provisional API`." msgstr "For Python 3.4, this module is considered a :term:`provisional API`." -#: ../../whatsnew/3.4.rst:475 +#: ../../whatsnew/3.4.rst:474 msgid ":pep:`3156` -- Asynchronous IO Support Rebooted: the \"asyncio\" Module" msgstr "" ":pep:`3156` -- Asynchronous IO Support Rebooted: the \"asyncio\" Module" -#: ../../whatsnew/3.4.rst:476 +#: ../../whatsnew/3.4.rst:475 msgid "PEP written and implementation led by Guido van Rossum." msgstr "PEP written and implementation led by Guido van Rossum." -#: ../../whatsnew/3.4.rst:482 +#: ../../whatsnew/3.4.rst:481 msgid "ensurepip" msgstr "ensurepip" -#: ../../whatsnew/3.4.rst:484 +#: ../../whatsnew/3.4.rst:483 msgid "" "The new :mod:`ensurepip` module is the primary infrastructure for the :pep:" "`453` implementation. In the normal course of events end users will not " @@ -881,7 +997,7 @@ msgstr "" "``pip`` if the automated bootstrapping into an installation or virtual " "environment was declined." -#: ../../whatsnew/3.4.rst:490 +#: ../../whatsnew/3.4.rst:489 msgid "" ":mod:`ensurepip` includes a bundled copy of ``pip``, up-to-date as of the " "first release candidate of the release of CPython with which it ships (this " @@ -901,7 +1017,7 @@ msgstr "" "version of ``pip`` is considered to be a separately installed package and " "will not be removed if Python is uninstalled.)" -#: ../../whatsnew/3.4.rst:499 +#: ../../whatsnew/3.4.rst:498 msgid "" "The module is named *ensure*\\ pip because if called when ``pip`` is already " "installed, it does nothing. It also has an ``--upgrade`` option that will " @@ -913,11 +1029,11 @@ msgstr "" "cause it to install the bundled copy of ``pip`` if the existing installed " "version of ``pip`` is older than the bundled copy." -#: ../../whatsnew/3.4.rst:508 +#: ../../whatsnew/3.4.rst:507 msgid "enum" msgstr "enum" -#: ../../whatsnew/3.4.rst:510 +#: ../../whatsnew/3.4.rst:509 msgid "" "The new :mod:`enum` module (defined in :pep:`435`) provides a standard " "implementation of enumeration types, allowing other modules (such as :mod:" @@ -931,11 +1047,11 @@ msgstr "" "support by replacing opaque integer constants with backwards compatible " "enumeration values." -#: ../../whatsnew/3.4.rst:518 +#: ../../whatsnew/3.4.rst:517 msgid ":pep:`435` -- Adding an Enum type to the Python standard library" msgstr ":pep:`435` -- Adding an Enum type to the Python standard library" -#: ../../whatsnew/3.4.rst:519 +#: ../../whatsnew/3.4.rst:518 msgid "" "PEP written by Barry Warsaw, Eli Bendersky and Ethan Furman, implemented by " "Ethan Furman." @@ -943,11 +1059,11 @@ msgstr "" "PEP written by Barry Warsaw, Eli Bendersky and Ethan Furman, implemented by " "Ethan Furman." -#: ../../whatsnew/3.4.rst:526 +#: ../../whatsnew/3.4.rst:525 msgid "pathlib" msgstr "pathlib" -#: ../../whatsnew/3.4.rst:528 +#: ../../whatsnew/3.4.rst:527 msgid "" "The new :mod:`pathlib` module offers classes representing filesystem paths " "with semantics appropriate for different operating systems. Path classes " @@ -961,19 +1077,19 @@ msgstr "" "without I/O, and *concrete paths*, which inherit from pure paths but also " "provide I/O operations." -#: ../../whatsnew/3.4.rst:538 +#: ../../whatsnew/3.4.rst:537 msgid ":pep:`428` -- The pathlib module -- object-oriented filesystem paths" msgstr ":pep:`428` -- The pathlib module -- object-oriented filesystem paths" -#: ../../whatsnew/3.4.rst:539 ../../whatsnew/3.4.rst:1835 +#: ../../whatsnew/3.4.rst:538 ../../whatsnew/3.4.rst:1834 msgid "PEP written and implemented by Antoine Pitrou." msgstr "PEP escrita e implementada por Antoine Pitrou." -#: ../../whatsnew/3.4.rst:545 +#: ../../whatsnew/3.4.rst:544 msgid "selectors" msgstr "selectors" -#: ../../whatsnew/3.4.rst:547 +#: ../../whatsnew/3.4.rst:546 msgid "" "The new :mod:`selectors` module (created as part of implementing :pep:" "`3156`) allows high-level and efficient I/O multiplexing, built upon the :" @@ -983,11 +1099,11 @@ msgstr "" "`3156`) allows high-level and efficient I/O multiplexing, built upon the :" "mod:`select` module primitives." -#: ../../whatsnew/3.4.rst:555 +#: ../../whatsnew/3.4.rst:554 msgid "statistics" msgstr "statistics" -#: ../../whatsnew/3.4.rst:557 +#: ../../whatsnew/3.4.rst:556 msgid "" "The new :mod:`statistics` module (defined in :pep:`450`) offers some core " "statistics functionality directly in the standard library. This module " @@ -999,19 +1115,19 @@ msgstr "" "supports calculation of the mean, median, mode, variance and standard " "deviation of a data series." -#: ../../whatsnew/3.4.rst:564 +#: ../../whatsnew/3.4.rst:563 msgid ":pep:`450` -- Adding A Statistics Module To The Standard Library" msgstr ":pep:`450` -- Adding A Statistics Module To The Standard Library" -#: ../../whatsnew/3.4.rst:565 +#: ../../whatsnew/3.4.rst:564 msgid "PEP written and implemented by Steven D'Aprano" msgstr "PEP written and implemented by Steven D'Aprano" -#: ../../whatsnew/3.4.rst:571 +#: ../../whatsnew/3.4.rst:570 msgid "tracemalloc" msgstr "tracemalloc" -#: ../../whatsnew/3.4.rst:573 +#: ../../whatsnew/3.4.rst:572 msgid "" "The new :mod:`tracemalloc` module (defined in :pep:`454`) is a debug tool to " "trace memory blocks allocated by Python. It provides the following " @@ -1021,11 +1137,11 @@ msgstr "" "trace memory blocks allocated by Python. It provides the following " "information:" -#: ../../whatsnew/3.4.rst:576 +#: ../../whatsnew/3.4.rst:575 msgid "Trace where an object was allocated" msgstr "Trace where an object was allocated" -#: ../../whatsnew/3.4.rst:577 +#: ../../whatsnew/3.4.rst:576 msgid "" "Statistics on allocated memory blocks per filename and per line number: " "total size, number and average size of allocated memory blocks" @@ -1033,29 +1149,29 @@ msgstr "" "Statistics on allocated memory blocks per filename and per line number: " "total size, number and average size of allocated memory blocks" -#: ../../whatsnew/3.4.rst:579 +#: ../../whatsnew/3.4.rst:578 msgid "Compute the differences between two snapshots to detect memory leaks" msgstr "Compute the differences between two snapshots to detect memory leaks" -#: ../../whatsnew/3.4.rst:583 +#: ../../whatsnew/3.4.rst:582 msgid "" ":pep:`454` -- Add a new tracemalloc module to trace Python memory allocations" msgstr "" ":pep:`454` -- Add a new tracemalloc module to trace Python memory allocations" -#: ../../whatsnew/3.4.rst:584 +#: ../../whatsnew/3.4.rst:583 msgid "PEP written and implemented by Victor Stinner" -msgstr "PEP escrita e implementada por Victor Stinner" +msgstr "PEP escrito e implementado por Victor Stinner" -#: ../../whatsnew/3.4.rst:589 +#: ../../whatsnew/3.4.rst:588 msgid "Improved Modules" msgstr "Módulos melhorados" -#: ../../whatsnew/3.4.rst:593 +#: ../../whatsnew/3.4.rst:592 msgid "abc" msgstr "abc" -#: ../../whatsnew/3.4.rst:595 +#: ../../whatsnew/3.4.rst:594 msgid "" "New function :func:`abc.get_cache_token` can be used to know when to " "invalidate caches that are affected by changes in the object graph. " @@ -1065,7 +1181,7 @@ msgstr "" "invalidate caches that are affected by changes in the object graph. " "(Contributed by Łukasz Langa in :issue:`16832`.)" -#: ../../whatsnew/3.4.rst:599 +#: ../../whatsnew/3.4.rst:598 msgid "" "New class :class:`~abc.ABC` has :class:`~abc.ABCMeta` as its meta class. " "Using ``ABC`` as a base class has essentially the same effect as specifying " @@ -1077,11 +1193,11 @@ msgstr "" "``metaclass=abc.ABCMeta``, but is simpler to type and easier to read. " "(Contributed by Bruno Dupuis in :issue:`16049`.)" -#: ../../whatsnew/3.4.rst:606 +#: ../../whatsnew/3.4.rst:605 msgid "aifc" msgstr "aifc" -#: ../../whatsnew/3.4.rst:608 +#: ../../whatsnew/3.4.rst:607 msgid "" "The :meth:`!getparams` method now returns a namedtuple rather than a plain " "tuple. (Contributed by Claudiu Popa in :issue:`17818`.)" @@ -1089,7 +1205,7 @@ msgstr "" "The :meth:`!getparams` method now returns a namedtuple rather than a plain " "tuple. (Contributed by Claudiu Popa in :issue:`17818`.)" -#: ../../whatsnew/3.4.rst:611 +#: ../../whatsnew/3.4.rst:610 msgid "" ":func:`!aifc.open` now supports the context management protocol: when used " "in a :keyword:`with` block, the :meth:`!close` method of the returned object " @@ -1101,7 +1217,7 @@ msgstr "" "will be called automatically at the end of the block. (Contributed by " "Serhiy Storchacha in :issue:`16486`.)" -#: ../../whatsnew/3.4.rst:616 ../../whatsnew/3.4.rst:1543 +#: ../../whatsnew/3.4.rst:615 ../../whatsnew/3.4.rst:1542 msgid "" "The :meth:`!writeframesraw` and :meth:`!writeframes` methods now accept any :" "term:`bytes-like object`. (Contributed by Serhiy Storchaka in :issue:" @@ -1111,11 +1227,11 @@ msgstr "" "term:`bytes-like object`. (Contributed by Serhiy Storchaka in :issue:" "`8311`.)" -#: ../../whatsnew/3.4.rst:622 +#: ../../whatsnew/3.4.rst:621 msgid "argparse" msgstr "argparse" -#: ../../whatsnew/3.4.rst:624 +#: ../../whatsnew/3.4.rst:623 msgid "" "The :class:`~argparse.FileType` class now accepts *encoding* and *errors* " "arguments, which are passed through to :func:`open`. (Contributed by Lucas " @@ -1125,11 +1241,11 @@ msgstr "" "arguments, which are passed through to :func:`open`. (Contributed by Lucas " "Maystre in :issue:`11175`.)" -#: ../../whatsnew/3.4.rst:630 +#: ../../whatsnew/3.4.rst:629 msgid "audioop" msgstr "audioop" -#: ../../whatsnew/3.4.rst:632 +#: ../../whatsnew/3.4.rst:631 msgid "" ":mod:`!audioop` now supports 24-bit samples. (Contributed by Serhiy " "Storchaka in :issue:`12866`.)" @@ -1137,7 +1253,7 @@ msgstr "" ":mod:`!audioop` now supports 24-bit samples. (Contributed by Serhiy " "Storchaka in :issue:`12866`.)" -#: ../../whatsnew/3.4.rst:635 +#: ../../whatsnew/3.4.rst:634 msgid "" "New :func:`!byteswap` function converts big-endian samples to little-endian " "and vice versa. (Contributed by Serhiy Storchaka in :issue:`19641`.)" @@ -1145,7 +1261,7 @@ msgstr "" "New :func:`!byteswap` function converts big-endian samples to little-endian " "and vice versa. (Contributed by Serhiy Storchaka in :issue:`19641`.)" -#: ../../whatsnew/3.4.rst:639 +#: ../../whatsnew/3.4.rst:638 msgid "" "All :mod:`!audioop` functions now accept any :term:`bytes-like object`. " "Strings are not accepted: they didn't work before, now they raise an error " @@ -1155,11 +1271,11 @@ msgstr "" "Strings are not accepted: they didn't work before, now they raise an error " "right away. (Contributed by Serhiy Storchaka in :issue:`16685`.)" -#: ../../whatsnew/3.4.rst:645 +#: ../../whatsnew/3.4.rst:644 msgid "base64" msgstr "base64" -#: ../../whatsnew/3.4.rst:647 +#: ../../whatsnew/3.4.rst:646 msgid "" "The encoding and decoding functions in :mod:`base64` now accept any :term:" "`bytes-like object` in cases where it previously required a :class:`bytes` " @@ -1171,7 +1287,7 @@ msgstr "" "or :class:`bytearray` instance. (Contributed by Nick Coghlan in :issue:" "`17839`.)" -#: ../../whatsnew/3.4.rst:652 +#: ../../whatsnew/3.4.rst:651 msgid "" "New functions :func:`~base64.a85encode`, :func:`~base64.a85decode`, :func:" "`~base64.b85encode`, and :func:`~base64.b85decode` provide the ability to " @@ -1189,11 +1305,11 @@ msgstr "" "encoding, including the Adobe variant. (Contributed by Martin Morrison, the " "Mercurial project, Serhiy Storchaka, and Antoine Pitrou in :issue:`17618`.)" -#: ../../whatsnew/3.4.rst:662 +#: ../../whatsnew/3.4.rst:661 msgid "collections" msgstr "collections" -#: ../../whatsnew/3.4.rst:664 +#: ../../whatsnew/3.4.rst:663 msgid "" "The :meth:`.ChainMap.new_child` method now accepts an *m* argument " "specifying the child map to add to the chain. This allows an existing " @@ -1205,11 +1321,11 @@ msgstr "" "mapping and/or a custom mapping type to be used for the child. (Contributed " "by Vinay Sajip in :issue:`16613`.)" -#: ../../whatsnew/3.4.rst:671 +#: ../../whatsnew/3.4.rst:670 msgid "colorsys" msgstr "colorsys" -#: ../../whatsnew/3.4.rst:673 +#: ../../whatsnew/3.4.rst:672 msgid "" "The number of digits in the coefficients for the RGB --- YIQ conversions " "have been expanded so that they match the FCC NTSC versions. The change in " @@ -1221,11 +1337,11 @@ msgstr "" "results should be less than 1% and may better match results found elsewhere. " "(Contributed by Brian Landers and Serhiy Storchaka in :issue:`14323`.)" -#: ../../whatsnew/3.4.rst:680 +#: ../../whatsnew/3.4.rst:679 msgid "contextlib" msgstr "contextlib" -#: ../../whatsnew/3.4.rst:682 +#: ../../whatsnew/3.4.rst:681 msgid "" "The new :class:`contextlib.suppress` context manager helps to clarify the " "intent of code that deliberately suppresses exceptions from a single " @@ -1237,7 +1353,7 @@ msgstr "" "statement. (Contributed by Raymond Hettinger in :issue:`15806` and Zero " "Piraeus in :issue:`19266`.)" -#: ../../whatsnew/3.4.rst:687 +#: ../../whatsnew/3.4.rst:686 msgid "" "The new :func:`contextlib.redirect_stdout` context manager makes it easier " "for utility scripts to handle inflexible APIs that write their output to :" @@ -1259,7 +1375,7 @@ msgstr "" "recommended only for utility scripts because it affects the global state of :" "data:`sys.stdout`. (Contributed by Raymond Hettinger in :issue:`15805`.)" -#: ../../whatsnew/3.4.rst:698 +#: ../../whatsnew/3.4.rst:697 msgid "" "The :mod:`contextlib` documentation has also been updated to include a :ref:" "`discussion ` of the differences " @@ -1269,11 +1385,11 @@ msgstr "" "`discussion ` of the differences " "between single use, reusable and reentrant context managers." -#: ../../whatsnew/3.4.rst:704 +#: ../../whatsnew/3.4.rst:703 msgid "dbm" msgstr "dbm" -#: ../../whatsnew/3.4.rst:706 +#: ../../whatsnew/3.4.rst:705 msgid "" ":func:`dbm.open` objects now support the context management protocol. When " "used in a :keyword:`with` statement, the ``close`` method of the database " @@ -1285,11 +1401,11 @@ msgstr "" "object will be called automatically at the end of the block. (Contributed by " "Claudiu Popa and Nick Coghlan in :issue:`19282`.)" -#: ../../whatsnew/3.4.rst:713 +#: ../../whatsnew/3.4.rst:712 msgid "dis" msgstr "dis" -#: ../../whatsnew/3.4.rst:715 +#: ../../whatsnew/3.4.rst:714 msgid "" "Functions :func:`~dis.show_code`, :func:`~dis.dis`, :func:`~dis.distb`, and :" "func:`~dis.disassemble` now accept a keyword-only *file* argument that " @@ -1299,7 +1415,7 @@ msgstr "" "func:`~dis.disassemble` now accept a keyword-only *file* argument that " "controls where they write their output." -#: ../../whatsnew/3.4.rst:719 +#: ../../whatsnew/3.4.rst:718 msgid "" "The :mod:`dis` module is now built around an :class:`~dis.Instruction` class " "that provides object oriented access to the details of each individual " @@ -1309,7 +1425,7 @@ msgstr "" "that provides object oriented access to the details of each individual " "bytecode operation." -#: ../../whatsnew/3.4.rst:723 +#: ../../whatsnew/3.4.rst:722 msgid "" "A new method, :func:`~dis.get_instructions`, provides an iterator that emits " "the Instruction stream for a given piece of Python code. Thus it is now " @@ -1323,7 +1439,25 @@ msgstr "" "in ways different from those provided by the :mod:`~dis` module itself. For " "example::" -#: ../../whatsnew/3.4.rst:737 +#: ../../whatsnew/3.4.rst:728 +msgid "" +">>> import dis\n" +">>> for instr in dis.get_instructions(lambda x: x + 1):\n" +"... print(instr.opname)\n" +"LOAD_FAST\n" +"LOAD_CONST\n" +"BINARY_ADD\n" +"RETURN_VALUE" +msgstr "" +">>> import dis\n" +">>> for instr in dis.get_instructions(lambda x: x + 1):\n" +"... print(instr.opname)\n" +"LOAD_FAST\n" +"LOAD_CONST\n" +"BINARY_ADD\n" +"RETURN_VALUE" + +#: ../../whatsnew/3.4.rst:736 msgid "" "The various display tools in the :mod:`dis` module have been rewritten to " "use these new components." @@ -1331,7 +1465,7 @@ msgstr "" "The various display tools in the :mod:`dis` module have been rewritten to " "use these new components." -#: ../../whatsnew/3.4.rst:740 +#: ../../whatsnew/3.4.rst:739 msgid "" "In addition, a new application-friendly class :class:`~dis.Bytecode` " "provides an object-oriented API for inspecting bytecode in both in human-" @@ -1351,7 +1485,35 @@ msgstr "" "also has a :mod:`~dis.Bytecode.dis` method, equivalent to calling :mod:`~dis." "dis` on the constructor argument, but returned as a multi-line string::" -#: ../../whatsnew/3.4.rst:762 +#: ../../whatsnew/3.4.rst:748 +msgid "" +">>> bytecode = dis.Bytecode(lambda x: x + 1, current_offset=3)\n" +">>> for instr in bytecode:\n" +"... print('{} ({})'.format(instr.opname, instr.opcode))\n" +"LOAD_FAST (124)\n" +"LOAD_CONST (100)\n" +"BINARY_ADD (23)\n" +"RETURN_VALUE (83)\n" +">>> bytecode.dis().splitlines()\n" +"[' 1 0 LOAD_FAST 0 (x)',\n" +" ' --> 3 LOAD_CONST 1 (1)',\n" +" ' 6 BINARY_ADD',\n" +" ' 7 RETURN_VALUE']" +msgstr "" +">>> bytecode = dis.Bytecode(lambda x: x + 1, current_offset=3)\n" +">>> for instr in bytecode:\n" +"... print('{} ({})'.format(instr.opname, instr.opcode))\n" +"LOAD_FAST (124)\n" +"LOAD_CONST (100)\n" +"BINARY_ADD (23)\n" +"RETURN_VALUE (83)\n" +">>> bytecode.dis().splitlines()\n" +"[' 1 0 LOAD_FAST 0 (x)',\n" +" ' --> 3 LOAD_CONST 1 (1)',\n" +" ' 6 BINARY_ADD',\n" +" ' 7 RETURN_VALUE']" + +#: ../../whatsnew/3.4.rst:761 msgid "" ":class:`~dis.Bytecode` also has a class method, :meth:`~dis.Bytecode." "from_traceback`, that provides the ability to manipulate a traceback (that " @@ -1363,7 +1525,7 @@ msgstr "" "is, ``print(Bytecode.from_traceback(tb).dis())`` is equivalent to " "``distb(tb)``)." -#: ../../whatsnew/3.4.rst:767 +#: ../../whatsnew/3.4.rst:766 msgid "" "(Contributed by Nick Coghlan, Ryan Kelly and Thomas Kluyver in :issue:" "`11816` and Claudiu Popa in :issue:`17916`.)" @@ -1371,7 +1533,7 @@ msgstr "" "(Contributed by Nick Coghlan, Ryan Kelly and Thomas Kluyver in :issue:" "`11816` and Claudiu Popa in :issue:`17916`.)" -#: ../../whatsnew/3.4.rst:770 +#: ../../whatsnew/3.4.rst:769 msgid "" "New function :func:`~dis.stack_effect` computes the effect on the Python " "stack of a given opcode and argument, information that is not otherwise " @@ -1381,11 +1543,11 @@ msgstr "" "stack of a given opcode and argument, information that is not otherwise " "available. (Contributed by Larry Hastings in :issue:`19722`.)" -#: ../../whatsnew/3.4.rst:776 +#: ../../whatsnew/3.4.rst:775 msgid "doctest" msgstr "doctest" -#: ../../whatsnew/3.4.rst:778 +#: ../../whatsnew/3.4.rst:777 msgid "" "A new :ref:`option flag `, :const:`~doctest.FAIL_FAST`, " "halts test running as soon as the first failure is detected. (Contributed " @@ -1395,7 +1557,7 @@ msgstr "" "halts test running as soon as the first failure is detected. (Contributed " "by R. David Murray and Daniel Urban in :issue:`16522`.)" -#: ../../whatsnew/3.4.rst:782 +#: ../../whatsnew/3.4.rst:781 msgid "" "The :mod:`doctest` command line interface now uses :mod:`argparse`, and has " "two new options, ``-o`` and ``-f``. ``-o`` allows :ref:`doctest options " @@ -1410,7 +1572,7 @@ msgstr "" "shorthand for ``-o FAIL_FAST`` (to parallel the similar option supported by " "the :mod:`unittest` CLI). (Contributed by R. David Murray in :issue:`11390`.)" -#: ../../whatsnew/3.4.rst:788 +#: ../../whatsnew/3.4.rst:787 msgid "" ":mod:`doctest` will now find doctests in extension module ``__doc__`` " "strings. (Contributed by Zachary Ware in :issue:`3158`.)" @@ -1418,11 +1580,11 @@ msgstr "" ":mod:`doctest` will now find doctests in extension module ``__doc__`` " "strings. (Contributed by Zachary Ware in :issue:`3158`.)" -#: ../../whatsnew/3.4.rst:793 +#: ../../whatsnew/3.4.rst:792 msgid "email" msgstr "email" -#: ../../whatsnew/3.4.rst:795 +#: ../../whatsnew/3.4.rst:794 msgid "" ":meth:`~email.message.Message.as_string` now accepts a *policy* argument to " "override the default policy of the message when generating a string " @@ -1438,7 +1600,7 @@ msgstr "" "in order to pass formatting parameters to its ``flatten`` method. " "(Contributed by R. David Murray in :issue:`18600`.)" -#: ../../whatsnew/3.4.rst:802 +#: ../../whatsnew/3.4.rst:801 msgid "" "New method :meth:`~email.message.Message.as_bytes` added to produce a bytes " "representation of the message in a fashion similar to how ``as_string`` " @@ -1458,7 +1620,7 @@ msgstr "" "result: a bytes object containing the fully formatted message. (Contributed " "by R. David Murray in :issue:`18600`.)" -#: ../../whatsnew/3.4.rst:811 +#: ../../whatsnew/3.4.rst:810 msgid "" "The :meth:`.Message.set_param` message now accepts a *replace* keyword " "argument. When specified, the associated header will be updated without " @@ -1471,7 +1633,7 @@ msgstr "" "changing its location in the list of headers. For backward compatibility, " "the default is ``False``. (Contributed by R. David Murray in :issue:`18891`.)" -#: ../../whatsnew/3.4.rst:819 +#: ../../whatsnew/3.4.rst:818 msgid "" "A pair of new subclasses of :class:`~email.message.Message` have been added " "(:class:`.EmailMessage` and :class:`.MIMEPart`), along with a new sub-" @@ -1501,11 +1663,11 @@ msgstr "" "in Python 3.5 (possibly with a few minor additions in the area of error " "handling). (Contributed by R. David Murray in :issue:`18891`.)" -#: ../../whatsnew/3.4.rst:835 +#: ../../whatsnew/3.4.rst:834 msgid "filecmp" msgstr "filecmp" -#: ../../whatsnew/3.4.rst:837 +#: ../../whatsnew/3.4.rst:836 msgid "" "A new :func:`~filecmp.clear_cache` function provides the ability to clear " "the :mod:`filecmp` comparison cache, which uses :func:`os.stat` information " @@ -1521,7 +1683,7 @@ msgstr "" "less time than the resolution of a particular filesystem's file modification " "time field. (Contributed by Mark Levitt in :issue:`18149`.)" -#: ../../whatsnew/3.4.rst:844 +#: ../../whatsnew/3.4.rst:843 msgid "" "New module attribute :const:`~filecmp.DEFAULT_IGNORES` provides the list of " "directories that are used as the default value for the *ignore* parameter of " @@ -1533,11 +1695,11 @@ msgstr "" "the :func:`~filecmp.dircmp` function. (Contributed by Eli Bendersky in :" "issue:`15442`.)" -#: ../../whatsnew/3.4.rst:851 +#: ../../whatsnew/3.4.rst:850 msgid "functools" msgstr "functools" -#: ../../whatsnew/3.4.rst:853 +#: ../../whatsnew/3.4.rst:852 msgid "" "The new :func:`~functools.partialmethod` descriptor brings partial argument " "application to descriptors, just as :func:`~functools.partial` provides for " @@ -1553,7 +1715,7 @@ msgstr "" "normal instance methods when included in a class definition. (Contributed by " "Alon Horev and Nick Coghlan in :issue:`4331`.)" -#: ../../whatsnew/3.4.rst:862 +#: ../../whatsnew/3.4.rst:861 msgid "" "The new :func:`~functools.singledispatch` decorator brings support for " "single-dispatch generic functions to the Python standard library. Where " @@ -1569,15 +1731,15 @@ msgstr "" "multiple implementations of an operation that allows it to work with " "*different* kinds of data." -#: ../../whatsnew/3.4.rst:871 +#: ../../whatsnew/3.4.rst:870 msgid ":pep:`443` -- Single-dispatch generic functions" msgstr ":pep:`443` -- Single-dispatch generic functions" -#: ../../whatsnew/3.4.rst:872 +#: ../../whatsnew/3.4.rst:871 msgid "PEP written and implemented by Łukasz Langa." msgstr "PEP escrita e implementada por Łukasz Langa." -#: ../../whatsnew/3.4.rst:874 +#: ../../whatsnew/3.4.rst:873 msgid "" ":func:`~functools.total_ordering` now supports a return value of :data:" "`NotImplemented` from the underlying comparison function. (Contributed by " @@ -1587,7 +1749,7 @@ msgstr "" "`NotImplemented` from the underlying comparison function. (Contributed by " "Katie Miller in :issue:`10042`.)" -#: ../../whatsnew/3.4.rst:878 +#: ../../whatsnew/3.4.rst:877 msgid "" "A pure-python version of the :func:`~functools.partial` function is now in " "the stdlib; in CPython it is overridden by the C accelerated version, but it " @@ -1599,11 +1761,11 @@ msgstr "" "is available for other implementations to use. (Contributed by Brian Thorne " "in :issue:`12428`.)" -#: ../../whatsnew/3.4.rst:885 +#: ../../whatsnew/3.4.rst:884 msgid "gc" msgstr "gc" -#: ../../whatsnew/3.4.rst:887 +#: ../../whatsnew/3.4.rst:886 msgid "" "New function :func:`~gc.get_stats` returns a list of three per-generation " "dictionaries containing the collections statistics since interpreter " @@ -1613,11 +1775,11 @@ msgstr "" "dictionaries containing the collections statistics since interpreter " "startup. (Contributed by Antoine Pitrou in :issue:`16351`.)" -#: ../../whatsnew/3.4.rst:893 +#: ../../whatsnew/3.4.rst:892 msgid "glob" msgstr "glob" -#: ../../whatsnew/3.4.rst:895 +#: ../../whatsnew/3.4.rst:894 msgid "" "A new function :func:`~glob.escape` provides a way to escape special " "characters in a filename so that they do not become part of the globbing " @@ -1629,11 +1791,11 @@ msgstr "" "expansion but are instead matched literally. (Contributed by Serhiy " "Storchaka in :issue:`8402`.)" -#: ../../whatsnew/3.4.rst:901 +#: ../../whatsnew/3.4.rst:900 msgid "hashlib" msgstr "hashlib" -#: ../../whatsnew/3.4.rst:903 +#: ../../whatsnew/3.4.rst:902 msgid "" "A new :func:`hashlib.pbkdf2_hmac` function provides the `PKCS#5 password-" "based key derivation function 2 `_. " @@ -1643,7 +1805,7 @@ msgstr "" "based key derivation function 2 `_. " "(Contributed by Christian Heimes in :issue:`18582`.)" -#: ../../whatsnew/3.4.rst:908 +#: ../../whatsnew/3.4.rst:907 msgid "" "The :attr:`~hashlib.hash.name` attribute of :mod:`hashlib` hash objects is " "now a formally supported interface. It has always existed in CPython's :mod:" @@ -1659,11 +1821,11 @@ msgstr "" "implementations have not previously supported it. (Contributed by Jason R. " "Coombs in :issue:`18532`.)" -#: ../../whatsnew/3.4.rst:917 +#: ../../whatsnew/3.4.rst:916 msgid "hmac" msgstr "hmac" -#: ../../whatsnew/3.4.rst:919 +#: ../../whatsnew/3.4.rst:918 msgid "" ":mod:`hmac` now accepts ``bytearray`` as well as ``bytes`` for the *key* " "argument to the :func:`~hmac.new` function, and the *msg* parameter to both " @@ -1677,7 +1839,7 @@ msgstr "" "accepts any type supported by the :mod:`hashlib` module. (Contributed by " "Jonas Borgström in :issue:`18240`.)" -#: ../../whatsnew/3.4.rst:925 +#: ../../whatsnew/3.4.rst:924 msgid "" "The *digestmod* argument to the :func:`hmac.new` function may now be any " "hash digest name recognized by :mod:`hashlib`. In addition, the current " @@ -1691,7 +1853,7 @@ msgstr "" "deprecated: in a future version of Python there will be no default value. " "(Contributed by Christian Heimes in :issue:`17276`.)" -#: ../../whatsnew/3.4.rst:931 +#: ../../whatsnew/3.4.rst:930 msgid "" "With the addition of :attr:`~hmac.HMAC.block_size` and :attr:`~hmac.HMAC." "name` attributes (and the formal documentation of the :attr:`~hmac.HMAC." @@ -1703,11 +1865,11 @@ msgstr "" "digest_size` attribute), the :mod:`hmac` module now conforms fully to the :" "pep:`247` API. (Contributed by Christian Heimes in :issue:`18775`.)" -#: ../../whatsnew/3.4.rst:938 +#: ../../whatsnew/3.4.rst:937 msgid "html" msgstr "html" -#: ../../whatsnew/3.4.rst:940 +#: ../../whatsnew/3.4.rst:939 msgid "" "New function :func:`~html.unescape` function converts HTML5 character " "references to the corresponding Unicode characters. (Contributed by Ezio " @@ -1717,7 +1879,7 @@ msgstr "" "references to the corresponding Unicode characters. (Contributed by Ezio " "Melotti in :issue:`2927`.)" -#: ../../whatsnew/3.4.rst:944 +#: ../../whatsnew/3.4.rst:943 msgid "" ":class:`~html.parser.HTMLParser` accepts a new keyword argument " "*convert_charrefs* that, when ``True``, automatically converts all character " @@ -1733,7 +1895,7 @@ msgstr "" "to set it explicitly and update your code to use this new feature. " "(Contributed by Ezio Melotti in :issue:`13633`.)" -#: ../../whatsnew/3.4.rst:951 +#: ../../whatsnew/3.4.rst:950 msgid "" "The *strict* argument of :class:`~html.parser.HTMLParser` is now deprecated. " "(Contributed by Ezio Melotti in :issue:`15114`.)" @@ -1741,11 +1903,11 @@ msgstr "" "The *strict* argument of :class:`~html.parser.HTMLParser` is now deprecated. " "(Contributed by Ezio Melotti in :issue:`15114`.)" -#: ../../whatsnew/3.4.rst:956 +#: ../../whatsnew/3.4.rst:955 msgid "http" msgstr "http" -#: ../../whatsnew/3.4.rst:958 +#: ../../whatsnew/3.4.rst:957 msgid "" ":meth:`~http.server.BaseHTTPRequestHandler.send_error` now accepts an " "optional additional *explain* parameter which can be used to provide an " @@ -1761,7 +1923,7 @@ msgstr "" "`~http.server.HTTP.error_message_format` attribute and sent as the body of " "the error response. (Contributed by Karl Cow in :issue:`12921`.)" -#: ../../whatsnew/3.4.rst:965 +#: ../../whatsnew/3.4.rst:964 msgid "" "The :mod:`http.server` :ref:`command line interface ` now " "has a ``-b/--bind`` option that causes the server to listen on a specific " @@ -1771,11 +1933,11 @@ msgstr "" "has a ``-b/--bind`` option that causes the server to listen on a specific " "address. (Contributed by Malte Swart in :issue:`17764`.)" -#: ../../whatsnew/3.4.rst:971 +#: ../../whatsnew/3.4.rst:970 msgid "idlelib and IDLE" msgstr "idlelib e IDLE" -#: ../../whatsnew/3.4.rst:973 +#: ../../whatsnew/3.4.rst:972 msgid "" "Since idlelib implements the IDLE shell and editor and is not intended for " "import by other programs, it gets improvements with every release. See :file:" @@ -1789,11 +1951,11 @@ msgstr "" "as changes made in future 3.4.x releases. This file is also available from " "the IDLE :menuselection:`Help --> About IDLE` dialog." -#: ../../whatsnew/3.4.rst:981 +#: ../../whatsnew/3.4.rst:980 msgid "importlib" msgstr "importlib" -#: ../../whatsnew/3.4.rst:983 +#: ../../whatsnew/3.4.rst:982 msgid "" "The :class:`~importlib.abc.InspectLoader` ABC defines a new method, :meth:" "`~importlib.abc.InspectLoader.source_to_code` that accepts source data and a " @@ -1807,7 +1969,7 @@ msgstr "" "``compile(data, path, 'exec', dont_inherit=True)``. (Contributed by Eric " "Snow and Brett Cannon in :issue:`15627`.)" -#: ../../whatsnew/3.4.rst:989 +#: ../../whatsnew/3.4.rst:988 msgid "" ":class:`~importlib.abc.InspectLoader` also now has a default implementation " "for the :meth:`~importlib.abc.InspectLoader.get_code` method. However, it " @@ -1819,7 +1981,7 @@ msgstr "" "will normally be desirable to override the default implementation for " "performance reasons. (Contributed by Brett Cannon in :issue:`18072`.)" -#: ../../whatsnew/3.4.rst:994 +#: ../../whatsnew/3.4.rst:993 msgid "" "The :func:`~importlib.reload` function has been moved from :mod:`!imp` to :" "mod:`importlib` as part of the :mod:`!imp` module deprecation. (Contributed " @@ -1829,19 +1991,19 @@ msgstr "" "mod:`importlib` as part of the :mod:`!imp` module deprecation. (Contributed " "by Berker Peksag in :issue:`18193`.)" -#: ../../whatsnew/3.4.rst:998 +#: ../../whatsnew/3.4.rst:997 msgid "" -":mod:`importlib.util` now has a :data:`~importlib.util.MAGIC_NUMBER` " +":mod:`importlib.util` now has a :const:`~importlib.util.MAGIC_NUMBER` " "attribute providing access to the bytecode version number. This replaces " "the :func:`!get_magic` function in the deprecated :mod:`!imp` module. " "(Contributed by Brett Cannon in :issue:`18192`.)" msgstr "" -":mod:`importlib.util` now has a :data:`~importlib.util.MAGIC_NUMBER` " +":mod:`importlib.util` now has a :const:`~importlib.util.MAGIC_NUMBER` " "attribute providing access to the bytecode version number. This replaces " "the :func:`!get_magic` function in the deprecated :mod:`!imp` module. " "(Contributed by Brett Cannon in :issue:`18192`.)" -#: ../../whatsnew/3.4.rst:1003 +#: ../../whatsnew/3.4.rst:1002 msgid "" "New :mod:`importlib.util` functions :func:`~importlib.util." "cache_from_source` and :func:`~importlib.util.source_from_cache` replace the " @@ -1853,7 +2015,7 @@ msgstr "" "same-named functions in the deprecated :mod:`!imp` module. (Contributed by " "Brett Cannon in :issue:`18194`.)" -#: ../../whatsnew/3.4.rst:1008 +#: ../../whatsnew/3.4.rst:1007 msgid "" "The :mod:`importlib` bootstrap :class:`.NamespaceLoader` now conforms to " "the :class:`.InspectLoader` ABC, which means that ``runpy`` and ``python -" @@ -1865,7 +2027,7 @@ msgstr "" "m`` can now be used with namespace packages. (Contributed by Brett Cannon " "in :issue:`18058`.)" -#: ../../whatsnew/3.4.rst:1013 +#: ../../whatsnew/3.4.rst:1012 msgid "" ":mod:`importlib.util` has a new function :func:`~importlib.util." "decode_source` that decodes source from bytes using universal newline " @@ -1877,7 +2039,7 @@ msgstr "" "processing. This is useful for implementing :meth:`.InspectLoader." "get_source` methods." -#: ../../whatsnew/3.4.rst:1017 +#: ../../whatsnew/3.4.rst:1016 msgid "" ":class:`importlib.machinery.ExtensionFileLoader` now has a :meth:`~importlib." "machinery.ExtensionFileLoader.get_filename` method. This was inadvertently " @@ -1889,11 +2051,11 @@ msgstr "" "omitted in the original implementation. (Contributed by Eric Snow in :issue:" "`19152`.)" -#: ../../whatsnew/3.4.rst:1024 +#: ../../whatsnew/3.4.rst:1023 msgid "inspect" msgstr "inspect" -#: ../../whatsnew/3.4.rst:1026 +#: ../../whatsnew/3.4.rst:1025 msgid "" "The :mod:`inspect` module now offers a basic :ref:`command line interface " "` to quickly display source code and other information " @@ -1905,7 +2067,7 @@ msgstr "" "for modules, classes and functions. (Contributed by Claudiu Popa and Nick " "Coghlan in :issue:`18626`.)" -#: ../../whatsnew/3.4.rst:1031 +#: ../../whatsnew/3.4.rst:1030 msgid "" ":func:`~inspect.unwrap` makes it easy to unravel wrapper function chains " "created by :func:`functools.wraps` (and any other API that sets the " @@ -1917,7 +2079,7 @@ msgstr "" "``__wrapped__`` attribute on a wrapper function). (Contributed by Daniel " "Urban, Aaron Iles and Nick Coghlan in :issue:`13266`.)" -#: ../../whatsnew/3.4.rst:1036 +#: ../../whatsnew/3.4.rst:1035 msgid "" "As part of the implementation of the new :mod:`enum` module, the :mod:" "`inspect` module now has substantially better support for custom ``__dir__`` " @@ -1929,7 +2091,7 @@ msgstr "" "methods and dynamic class attributes provided through metaclasses. " "(Contributed by Ethan Furman in :issue:`18929` and :issue:`19030`.)" -#: ../../whatsnew/3.4.rst:1042 +#: ../../whatsnew/3.4.rst:1041 msgid "" ":func:`~inspect.getfullargspec` and :func:`~inspect.getargspec` now use the :" "func:`~inspect.signature` API. This allows them to support a much broader " @@ -1951,7 +2113,7 @@ msgstr "" "use :func:`~inspect.signature` directly if those features are desired. " "(Contributed by Yury Selivanov in :issue:`17481`.)" -#: ../../whatsnew/3.4.rst:1053 +#: ../../whatsnew/3.4.rst:1052 msgid "" ":func:`~inspect.signature` now supports duck types of CPython functions, " "which adds support for functions compiled with Cython. (Contributed by " @@ -1961,11 +2123,11 @@ msgstr "" "which adds support for functions compiled with Cython. (Contributed by " "Stefan Behnel and Yury Selivanov in :issue:`17159`.)" -#: ../../whatsnew/3.4.rst:1059 +#: ../../whatsnew/3.4.rst:1058 msgid "ipaddress" msgstr "ipaddress" -#: ../../whatsnew/3.4.rst:1061 +#: ../../whatsnew/3.4.rst:1060 msgid "" ":mod:`ipaddress` was added to the standard library in Python 3.3 as a :term:" "`provisional API`. With the release of Python 3.4, this qualification has " @@ -1977,7 +2139,7 @@ msgstr "" "been removed: :mod:`ipaddress` is now considered a stable API, covered by " "the normal standard library requirements to maintain backwards compatibility." -#: ../../whatsnew/3.4.rst:1067 +#: ../../whatsnew/3.4.rst:1066 msgid "" "A new :attr:`~ipaddress.IPv4Address.is_global` property is ``True`` if an " "address is globally routeable. (Contributed by Peter Moody in :issue:" @@ -1987,11 +2149,11 @@ msgstr "" "address is globally routeable. (Contributed by Peter Moody in :issue:" "`17400`.)" -#: ../../whatsnew/3.4.rst:1073 +#: ../../whatsnew/3.4.rst:1072 msgid "logging" msgstr "logging" -#: ../../whatsnew/3.4.rst:1075 +#: ../../whatsnew/3.4.rst:1074 msgid "" "The :class:`~logging.handlers.TimedRotatingFileHandler` has a new *atTime* " "parameter that can be used to specify the time of day when rollover should " @@ -2001,7 +2163,7 @@ msgstr "" "parameter that can be used to specify the time of day when rollover should " "happen. (Contributed by Ronald Oussoren in :issue:`9556`.)" -#: ../../whatsnew/3.4.rst:1079 +#: ../../whatsnew/3.4.rst:1078 msgid "" ":class:`~logging.handlers.SocketHandler` and :class:`~logging.handlers." "DatagramHandler` now support Unix domain sockets (by setting *port* to " @@ -2011,7 +2173,7 @@ msgstr "" "DatagramHandler` now support Unix domain sockets (by setting *port* to " "``None``). (Contributed by Vinay Sajip in commit ce46195b56a9.)" -#: ../../whatsnew/3.4.rst:1084 +#: ../../whatsnew/3.4.rst:1083 msgid "" ":func:`~logging.config.fileConfig` now accepts a :class:`configparser." "RawConfigParser` subclass instance for the *fname* parameter. This " @@ -2027,7 +2189,7 @@ msgstr "" "modifies the configuration before passing it to :func:`~logging.config." "fileConfig`. (Contributed by Vinay Sajip in :issue:`16110`.)" -#: ../../whatsnew/3.4.rst:1092 +#: ../../whatsnew/3.4.rst:1091 msgid "" "Logging configuration data received from a socket via the :func:`logging." "config.listen` function can now be validated before being processed by " @@ -2039,11 +2201,11 @@ msgstr "" "supplying a verification function as the argument to the new *verify* " "keyword argument. (Contributed by Vinay Sajip in :issue:`15452`.)" -#: ../../whatsnew/3.4.rst:1101 +#: ../../whatsnew/3.4.rst:1100 msgid "marshal" msgstr "marshal" -#: ../../whatsnew/3.4.rst:1103 +#: ../../whatsnew/3.4.rst:1102 msgid "" "The default :mod:`marshal` version has been bumped to 3. The code " "implementing the new version restores the Python2 behavior of recording only " @@ -2065,11 +2227,11 @@ msgstr "" "Jónsson in :issue:`16475`, with additional speedups by Antoine Pitrou in :" "issue:`19219`.)" -#: ../../whatsnew/3.4.rst:1114 +#: ../../whatsnew/3.4.rst:1113 msgid "mmap" msgstr "mmap" -#: ../../whatsnew/3.4.rst:1116 +#: ../../whatsnew/3.4.rst:1115 msgid "" "mmap objects are now :ref:`weakly referenceable `. (Contributed " "by Valerie Lambert in :issue:`4885`.)" @@ -2077,11 +2239,11 @@ msgstr "" "mmap objects are now :ref:`weakly referenceable `. (Contributed " "by Valerie Lambert in :issue:`4885`.)" -#: ../../whatsnew/3.4.rst:1121 +#: ../../whatsnew/3.4.rst:1120 msgid "multiprocessing" msgstr "multiprocessing" -#: ../../whatsnew/3.4.rst:1125 +#: ../../whatsnew/3.4.rst:1124 msgid "" "On Unix two new :ref:`start methods `, " "``spawn`` and ``forkserver``, have been added for starting processes using :" @@ -2103,7 +2265,7 @@ msgstr "" "and :func:`~multiprocessing.set_start_method` sets the start method. " "(Contributed by Richard Oudkerk in :issue:`8713`.)" -#: ../../whatsnew/3.4.rst:1135 +#: ../../whatsnew/3.4.rst:1134 msgid "" ":mod:`multiprocessing` also now has the concept of a ``context``, which " "determines how child processes are created. New function :func:" @@ -2125,7 +2287,7 @@ msgstr "" "multiprocessing without interfering with each other. (Contributed by Richard " "Oudkerk in :issue:`18999`.)" -#: ../../whatsnew/3.4.rst:1145 +#: ../../whatsnew/3.4.rst:1144 msgid "" "Except when using the old *fork* start method, child processes no longer " "inherit unneeded handles/file descriptors from their parents (part of :issue:" @@ -2135,7 +2297,7 @@ msgstr "" "inherit unneeded handles/file descriptors from their parents (part of :issue:" "`8713`)." -#: ../../whatsnew/3.4.rst:1149 +#: ../../whatsnew/3.4.rst:1148 msgid "" ":mod:`multiprocessing` now relies on :mod:`runpy` (which implements the ``-" "m`` switch) to initialise ``__main__`` appropriately in child processes when " @@ -2151,11 +2313,11 @@ msgstr "" "explicit relative imports could cause obscure failures in child processes. " "(Contributed by Nick Coghlan in :issue:`19946`.)" -#: ../../whatsnew/3.4.rst:1158 +#: ../../whatsnew/3.4.rst:1157 msgid "operator" msgstr "operador" -#: ../../whatsnew/3.4.rst:1160 +#: ../../whatsnew/3.4.rst:1159 msgid "" "New function :func:`~operator.length_hint` provides an implementation of the " "specification for how the :meth:`~object.__length_hint__` special method " @@ -2167,7 +2329,7 @@ msgstr "" "should be used, as part of the :pep:`424` formal specification of this " "language feature. (Contributed by Armin Ronacher in :issue:`16148`.)" -#: ../../whatsnew/3.4.rst:1165 +#: ../../whatsnew/3.4.rst:1164 msgid "" "There is now a pure-python version of the :mod:`operator` module available " "for reference and for use by alternate implementations of Python. " @@ -2177,11 +2339,11 @@ msgstr "" "for reference and for use by alternate implementations of Python. " "(Contributed by Zachary Ware in :issue:`16694`.)" -#: ../../whatsnew/3.4.rst:1171 +#: ../../whatsnew/3.4.rst:1170 msgid "os" msgstr "os" -#: ../../whatsnew/3.4.rst:1173 +#: ../../whatsnew/3.4.rst:1172 msgid "" "There are new functions to get and set the :ref:`inheritable flag " "` of a file descriptor (:func:`os.get_inheritable`, :func:" @@ -2193,7 +2355,7 @@ msgstr "" "`os.set_inheritable`) or a Windows handle (:func:`os." "get_handle_inheritable`, :func:`os.set_handle_inheritable`)." -#: ../../whatsnew/3.4.rst:1178 +#: ../../whatsnew/3.4.rst:1177 msgid "" "New function :func:`~os.cpu_count` reports the number of CPUs available on " "the platform on which Python is running (or ``None`` if the count can't be " @@ -2208,7 +2370,7 @@ msgstr "" "implemented in terms of this function). (Contributed by Trent Nelson, Yogesh " "Chaudhari, Victor Stinner, and Charles-François Natali in :issue:`17914`.)" -#: ../../whatsnew/3.4.rst:1184 +#: ../../whatsnew/3.4.rst:1183 msgid "" ":func:`os.path.samestat` is now available on the Windows platform (and the :" "func:`os.path.samefile` implementation is now shared between Unix and " @@ -2218,7 +2380,7 @@ msgstr "" "func:`os.path.samefile` implementation is now shared between Unix and " "Windows). (Contributed by Brian Curtin in :issue:`11939`.)" -#: ../../whatsnew/3.4.rst:1188 +#: ../../whatsnew/3.4.rst:1187 msgid "" ":func:`os.path.ismount` now recognizes volumes mounted below a drive root on " "Windows. (Contributed by Tim Golden in :issue:`9035`.)" @@ -2226,7 +2388,7 @@ msgstr "" ":func:`os.path.ismount` now recognizes volumes mounted below a drive root on " "Windows. (Contributed by Tim Golden in :issue:`9035`.)" -#: ../../whatsnew/3.4.rst:1191 +#: ../../whatsnew/3.4.rst:1190 msgid "" ":func:`os.open` supports two new flags on platforms that provide them, :" "const:`~os.O_PATH` (un-opened file descriptor), and :const:`~os.O_TMPFILE` " @@ -2242,11 +2404,11 @@ msgstr "" "(Contributed by Christian Heimes in :issue:`18673` and Benjamin Peterson, " "respectively.)" -#: ../../whatsnew/3.4.rst:1199 +#: ../../whatsnew/3.4.rst:1198 msgid "pdb" msgstr "pdb" -#: ../../whatsnew/3.4.rst:1201 +#: ../../whatsnew/3.4.rst:1200 msgid "" ":mod:`pdb` has been enhanced to handle generators, :keyword:`yield`, and " "``yield from`` in a more useful fashion. This is especially helpful when " @@ -2258,7 +2420,7 @@ msgstr "" "debugging :mod:`asyncio` based programs. (Contributed by Andrew Svetlov and " "Xavier de Gaye in :issue:`16596`.)" -#: ../../whatsnew/3.4.rst:1206 +#: ../../whatsnew/3.4.rst:1205 msgid "" "The ``print`` command has been removed from :mod:`pdb`, restoring access to " "the Python :func:`print` function from the pdb command line. Python2's " @@ -2280,11 +2442,11 @@ msgstr "" "function, making it inaccessible at the ``pdb`` prompt. (Contributed by " "Connor Osborn in :issue:`18764`.)" -#: ../../whatsnew/3.4.rst:1220 +#: ../../whatsnew/3.4.rst:1219 msgid "pickle" msgstr "pickle" -#: ../../whatsnew/3.4.rst:1222 +#: ../../whatsnew/3.4.rst:1221 msgid "" ":mod:`pickle` now supports (but does not use by default) a new pickle " "protocol, protocol 4. This new protocol addresses a number of issues that " @@ -2300,19 +2462,19 @@ msgstr "" "`__new__` method takes keyword-only arguments. It also provides some " "efficiency improvements." -#: ../../whatsnew/3.4.rst:1230 +#: ../../whatsnew/3.4.rst:1229 msgid ":pep:`3154` -- Pickle protocol 4" msgstr ":pep:`3154` -- Pickle protocol 4" -#: ../../whatsnew/3.4.rst:1231 +#: ../../whatsnew/3.4.rst:1230 msgid "PEP written by Antoine Pitrou and implemented by Alexandre Vassalotti." msgstr "PEP written by Antoine Pitrou and implemented by Alexandre Vassalotti." -#: ../../whatsnew/3.4.rst:1235 +#: ../../whatsnew/3.4.rst:1234 msgid "plistlib" msgstr "plistlib" -#: ../../whatsnew/3.4.rst:1237 +#: ../../whatsnew/3.4.rst:1236 msgid "" ":mod:`plistlib` now has an API that is similar to the standard pattern for " "stdlib serialization protocols, with new :func:`~plistlib.load`, :func:" @@ -2330,11 +2492,11 @@ msgstr "" "supports the binary plist format (:const:`~plistlib.FMT_BINARY`). " "(Contributed by Ronald Oussoren and others in :issue:`14455`.)" -#: ../../whatsnew/3.4.rst:1247 +#: ../../whatsnew/3.4.rst:1246 msgid "poplib" msgstr "poplib" -#: ../../whatsnew/3.4.rst:1249 +#: ../../whatsnew/3.4.rst:1248 msgid "" "Two new methods have been added to :mod:`poplib`: :meth:`~poplib.POP3.capa`, " "which returns the list of capabilities advertised by the POP server, and :" @@ -2348,11 +2510,11 @@ msgstr "" "encrypted POP3 session if the POP server supports it. (Contributed by " "Lorenzo Catucci in :issue:`4473`.)" -#: ../../whatsnew/3.4.rst:1257 +#: ../../whatsnew/3.4.rst:1256 msgid "pprint" msgstr "pprint" -#: ../../whatsnew/3.4.rst:1259 +#: ../../whatsnew/3.4.rst:1258 msgid "" "The :mod:`pprint` module's :class:`~pprint.PrettyPrinter` class and its :" "func:`~pprint.pformat`, and :func:`~pprint.pprint` functions have a new " @@ -2368,7 +2530,7 @@ msgstr "" "many sequence elements as will fit within *width* on each (indented) line. " "(Contributed by Serhiy Storchaka in :issue:`19132`.)" -#: ../../whatsnew/3.4.rst:1266 +#: ../../whatsnew/3.4.rst:1265 msgid "" "Long strings are now wrapped using Python's normal line continuation " "syntax. (Contributed by Antoine Pitrou in :issue:`17150`.)" @@ -2376,11 +2538,11 @@ msgstr "" "Long strings are now wrapped using Python's normal line continuation syntax. " "(Contributed by Antoine Pitrou in :issue:`17150`.)" -#: ../../whatsnew/3.4.rst:1271 +#: ../../whatsnew/3.4.rst:1270 msgid "pty" msgstr "pty" -#: ../../whatsnew/3.4.rst:1273 +#: ../../whatsnew/3.4.rst:1272 msgid "" ":func:`pty.spawn` now returns the status value from :func:`os.waitpid` on " "the child process, instead of ``None``. (Contributed by Gregory P. Smith.)" @@ -2388,11 +2550,11 @@ msgstr "" ":func:`pty.spawn` now returns the status value from :func:`os.waitpid` on " "the child process, instead of ``None``. (Contributed by Gregory P. Smith.)" -#: ../../whatsnew/3.4.rst:1278 +#: ../../whatsnew/3.4.rst:1277 msgid "pydoc" msgstr "pydoc" -#: ../../whatsnew/3.4.rst:1280 +#: ../../whatsnew/3.4.rst:1279 msgid "" "The :mod:`pydoc` module is now based directly on the :func:`inspect." "signature` introspection API, allowing it to provide signature information " @@ -2406,7 +2568,7 @@ msgstr "" "``__wrapped__`` attributes are now taken into account when displaying help " "information. (Contributed by Larry Hastings in :issue:`19674`.)" -#: ../../whatsnew/3.4.rst:1286 +#: ../../whatsnew/3.4.rst:1285 msgid "" "The :mod:`pydoc` module no longer displays the ``self`` parameter for " "already bound methods. Instead, it aims to always display the exact current " @@ -2418,7 +2580,7 @@ msgstr "" "signature of the supplied callable. (Contributed by Larry Hastings in :issue:" "`20710`.)" -#: ../../whatsnew/3.4.rst:1291 +#: ../../whatsnew/3.4.rst:1290 msgid "" "In addition to the changes that have been made to :mod:`pydoc` directly, its " "handling of custom ``__dir__`` methods and various descriptor behaviours has " @@ -2430,7 +2592,7 @@ msgstr "" "also been improved substantially by the underlying changes in the :mod:" "`inspect` module." -#: ../../whatsnew/3.4.rst:1296 +#: ../../whatsnew/3.4.rst:1295 msgid "" "As the :func:`help` builtin is based on :mod:`pydoc`, the above changes also " "affect the behaviour of :func:`help`." @@ -2438,11 +2600,11 @@ msgstr "" "As the :func:`help` builtin is based on :mod:`pydoc`, the above changes also " "affect the behaviour of :func:`help`." -#: ../../whatsnew/3.4.rst:1301 +#: ../../whatsnew/3.4.rst:1300 msgid "re" msgstr "re" -#: ../../whatsnew/3.4.rst:1303 +#: ../../whatsnew/3.4.rst:1302 msgid "" "New :func:`~re.fullmatch` function and :meth:`.regex.fullmatch` method " "anchor the pattern at both ends of the string to match. This provides a way " @@ -2458,7 +2620,7 @@ msgstr "" "alternatives to an existing regular expression. (Contributed by Matthew " "Barnett in :issue:`16203`.)" -#: ../../whatsnew/3.4.rst:1310 +#: ../../whatsnew/3.4.rst:1309 msgid "" "The repr of :ref:`regex objects ` now includes the pattern and " "the flags; the repr of :ref:`match objects ` now includes the " @@ -2470,11 +2632,11 @@ msgstr "" "start, end, and the part of the string that matched. (Contributed by Hugo " "Lopes Tavares and Serhiy Storchaka in :issue:`13592` and :issue:`17087`.)" -#: ../../whatsnew/3.4.rst:1318 +#: ../../whatsnew/3.4.rst:1317 msgid "resource" msgstr "resource" -#: ../../whatsnew/3.4.rst:1320 +#: ../../whatsnew/3.4.rst:1319 msgid "" "New :func:`~resource.prlimit` function, available on Linux platforms with a " "kernel version of 2.6.36 or later and glibc of 2.13 or later, provides the " @@ -2486,7 +2648,7 @@ msgstr "" "ability to query or set the resource limits for processes other than the one " "making the call. (Contributed by Christian Heimes in :issue:`16595`.)" -#: ../../whatsnew/3.4.rst:1325 +#: ../../whatsnew/3.4.rst:1324 msgid "" "On Linux kernel version 2.6.36 or later, there are also some new Linux " "specific constants: :const:`~resource.RLIMIT_MSGQUEUE`, :const:`~resource." @@ -2500,7 +2662,7 @@ msgstr "" "RLIMIT_RTTIME`, and :const:`~resource.RLIMIT_SIGPENDING`. (Contributed by " "Christian Heimes in :issue:`19324`.)" -#: ../../whatsnew/3.4.rst:1331 +#: ../../whatsnew/3.4.rst:1330 msgid "" "On FreeBSD version 9 and later, there some new FreeBSD specific constants: :" "const:`~resource.RLIMIT_SBSIZE`, :const:`~resource.RLIMIT_SWAP`, and :const:" @@ -2510,11 +2672,11 @@ msgstr "" "const:`~resource.RLIMIT_SBSIZE`, :const:`~resource.RLIMIT_SWAP`, and :const:" "`~resource.RLIMIT_NPTS`. (Contributed by Claudiu Popa in :issue:`19343`.)" -#: ../../whatsnew/3.4.rst:1338 +#: ../../whatsnew/3.4.rst:1337 msgid "select" msgstr "select" -#: ../../whatsnew/3.4.rst:1340 +#: ../../whatsnew/3.4.rst:1339 msgid "" ":class:`~select.epoll` objects now support the context management protocol. " "When used in a :keyword:`with` statement, the :meth:`~select.epoll.close` " @@ -2526,7 +2688,7 @@ msgstr "" "method will be called automatically at the end of the block. (Contributed by " "Serhiy Storchaka in :issue:`16488`.)" -#: ../../whatsnew/3.4.rst:1345 +#: ../../whatsnew/3.4.rst:1344 msgid "" ":class:`~select.devpoll` objects now have :meth:`~select.devpoll.fileno` " "and :meth:`~select.devpoll.close` methods, as well as a new attribute :attr:" @@ -2536,11 +2698,11 @@ msgstr "" "and :meth:`~select.devpoll.close` methods, as well as a new attribute :attr:" "`~select.devpoll.closed`. (Contributed by Victor Stinner in :issue:`18794`.)" -#: ../../whatsnew/3.4.rst:1352 +#: ../../whatsnew/3.4.rst:1351 msgid "shelve" msgstr "shelve" -#: ../../whatsnew/3.4.rst:1354 +#: ../../whatsnew/3.4.rst:1353 msgid "" ":class:`~shelve.Shelf` instances may now be used in :keyword:`with` " "statements, and will be automatically closed at the end of the :keyword:`!" @@ -2550,11 +2712,11 @@ msgstr "" "statements, and will be automatically closed at the end of the :keyword:`!" "with` block. (Contributed by Filip Gruszczyński in :issue:`13896`.)" -#: ../../whatsnew/3.4.rst:1360 +#: ../../whatsnew/3.4.rst:1359 msgid "shutil" msgstr "shutil" -#: ../../whatsnew/3.4.rst:1362 +#: ../../whatsnew/3.4.rst:1361 msgid "" ":func:`~shutil.copyfile` now raises a specific :exc:`~shutil.Error` " "subclass, :exc:`~shutil.SameFileError`, when the source and destination are " @@ -2568,11 +2730,11 @@ msgstr "" "this specific error. (Contributed by Atsuo Ishimoto and Hynek Schlawack in :" "issue:`1492704`.)" -#: ../../whatsnew/3.4.rst:1370 +#: ../../whatsnew/3.4.rst:1369 msgid "smtpd" msgstr "smtpd" -#: ../../whatsnew/3.4.rst:1372 +#: ../../whatsnew/3.4.rst:1371 msgid "" "The :class:`!SMTPServer` and :class:`!SMTPChannel` classes now accept a " "*map* keyword argument which, if specified, is passed in to :class:`!" @@ -2586,11 +2748,11 @@ msgstr "" "avoid affecting the global socket map. (Contributed by Vinay Sajip in :" "issue:`11959`.)" -#: ../../whatsnew/3.4.rst:1380 +#: ../../whatsnew/3.4.rst:1379 msgid "smtplib" msgstr "smtplib" -#: ../../whatsnew/3.4.rst:1382 +#: ../../whatsnew/3.4.rst:1381 msgid "" ":exc:`~smtplib.SMTPException` is now a subclass of :exc:`OSError`, which " "allows both socket level errors and SMTP protocol level errors to be caught " @@ -2602,11 +2764,11 @@ msgstr "" "in one try/except statement by code that only cares whether or not an error " "occurred. (Contributed by Ned Jackson Lovely in :issue:`2118`.)" -#: ../../whatsnew/3.4.rst:1389 +#: ../../whatsnew/3.4.rst:1388 msgid "socket" msgstr "socket" -#: ../../whatsnew/3.4.rst:1391 +#: ../../whatsnew/3.4.rst:1390 msgid "" "The socket module now supports the :const:`~socket.CAN_BCM` protocol on " "platforms that support it. (Contributed by Brian Thorne in :issue:`15359`.)" @@ -2614,7 +2776,7 @@ msgstr "" "The socket module now supports the :const:`~socket.CAN_BCM` protocol on " "platforms that support it. (Contributed by Brian Thorne in :issue:`15359`.)" -#: ../../whatsnew/3.4.rst:1394 +#: ../../whatsnew/3.4.rst:1393 msgid "" "Socket objects have new methods to get or set their :ref:`inheritable flag " "`, :meth:`~socket.socket.get_inheritable` and :meth:`~socket." @@ -2624,7 +2786,7 @@ msgstr "" "`, :meth:`~socket.socket.get_inheritable` and :meth:`~socket." "socket.set_inheritable`." -#: ../../whatsnew/3.4.rst:1398 +#: ../../whatsnew/3.4.rst:1397 msgid "" "The ``socket.AF_*`` and ``socket.SOCK_*`` constants are now enumeration " "values using the new :mod:`enum` module. This allows meaningful names to be " @@ -2634,11 +2796,11 @@ msgstr "" "values using the new :mod:`enum` module. This allows meaningful names to be " "printed during debugging, instead of integer \"magic numbers\"." -#: ../../whatsnew/3.4.rst:1402 +#: ../../whatsnew/3.4.rst:1401 msgid "The :const:`~socket.AF_LINK` constant is now available on BSD and OSX." msgstr "The :const:`~socket.AF_LINK` constant is now available on BSD and OSX." -#: ../../whatsnew/3.4.rst:1404 +#: ../../whatsnew/3.4.rst:1403 msgid "" ":func:`~socket.inet_pton` and :func:`~socket.inet_ntop` are now supported on " "Windows. (Contributed by Atsuo Ishimoto in :issue:`7171`.)" @@ -2646,11 +2808,11 @@ msgstr "" ":func:`~socket.inet_pton` and :func:`~socket.inet_ntop` are now supported on " "Windows. (Contributed by Atsuo Ishimoto in :issue:`7171`.)" -#: ../../whatsnew/3.4.rst:1409 +#: ../../whatsnew/3.4.rst:1408 msgid "sqlite3" msgstr "sqlite3" -#: ../../whatsnew/3.4.rst:1411 +#: ../../whatsnew/3.4.rst:1410 msgid "" "A new boolean parameter to the :func:`~sqlite3.connect` function, *uri*, can " "be used to indicate that the *database* parameter is a ``uri`` (see the " @@ -2662,11 +2824,11 @@ msgstr "" "`SQLite URI documentation `_). (Contributed " "by poq in :issue:`13773`.)" -#: ../../whatsnew/3.4.rst:1418 +#: ../../whatsnew/3.4.rst:1417 msgid "ssl" msgstr "ssl" -#: ../../whatsnew/3.4.rst:1422 +#: ../../whatsnew/3.4.rst:1421 msgid "" ":data:`~ssl.PROTOCOL_TLSv1_1` and :data:`~ssl.PROTOCOL_TLSv1_2` (TLSv1.1 and " "TLSv1.2 support) have been added; support for these protocols is only " @@ -2678,7 +2840,7 @@ msgstr "" "available if Python is linked with OpenSSL 1.0.1 or later. (Contributed by " "Michele Orrù and Antoine Pitrou in :issue:`16692`.)" -#: ../../whatsnew/3.4.rst:1429 +#: ../../whatsnew/3.4.rst:1428 msgid "" "New function :func:`~ssl.create_default_context` provides a standard way to " "obtain an :class:`~ssl.SSLContext` whose settings are intended to be a " @@ -2702,7 +2864,7 @@ msgstr "" "it if needed, and then pass it as the *context* argument of the appropriate " "stdlib API. (Contributed by Christian Heimes in :issue:`19689`.)" -#: ../../whatsnew/3.4.rst:1441 +#: ../../whatsnew/3.4.rst:1440 msgid "" ":class:`~ssl.SSLContext` method :meth:`~ssl.SSLContext." "load_verify_locations` accepts a new optional argument *cadata*, which can " @@ -2714,7 +2876,7 @@ msgstr "" "be used to provide PEM or DER encoded certificates directly via strings or " "bytes, respectively. (Contributed by Christian Heimes in :issue:`18138`.)" -#: ../../whatsnew/3.4.rst:1446 +#: ../../whatsnew/3.4.rst:1445 msgid "" "New function :func:`~ssl.get_default_verify_paths` returns a named tuple of " "the paths and environment variables that the :meth:`~ssl.SSLContext." @@ -2728,7 +2890,7 @@ msgstr "" "and ``capath``. This can be an aid in debugging default verification issues. " "(Contributed by Christian Heimes in :issue:`18143`.)" -#: ../../whatsnew/3.4.rst:1453 +#: ../../whatsnew/3.4.rst:1452 msgid "" ":class:`~ssl.SSLContext` has a new method, :meth:`~ssl.SSLContext." "cert_store_stats`, that reports the number of loaded ``X.509`` certs, " @@ -2744,7 +2906,7 @@ msgstr "" "loaded ``CA`` certificates. (Contributed by Christian Heimes in :issue:" "`18147`.)" -#: ../../whatsnew/3.4.rst:1460 +#: ../../whatsnew/3.4.rst:1459 msgid "" "If OpenSSL 0.9.8 or later is available, :class:`~ssl.SSLContext` has a new " "attribute :attr:`~ssl.SSLContext.verify_flags` that can be used to control " @@ -2762,7 +2924,7 @@ msgstr "" "`~ssl.VERIFY_X509_STRICT`. OpenSSL does not do any CRL verification by " "default. (Contributed by Christien Heimes in :issue:`8813`.)" -#: ../../whatsnew/3.4.rst:1468 +#: ../../whatsnew/3.4.rst:1467 msgid "" "New :class:`~ssl.SSLContext` method :meth:`~ssl.SSLContext." "load_default_certs` loads a set of default \"certificate authority\" (CA) " @@ -2782,7 +2944,7 @@ msgstr "" "certificates (``purpose=``:data:`~ssl.Purpose.CLIENT_AUTH`). (Contributed by " "Christian Heimes in :issue:`19292`.)" -#: ../../whatsnew/3.4.rst:1479 +#: ../../whatsnew/3.4.rst:1478 msgid "" "Two new windows-only functions, :func:`~ssl.enum_certificates` and :func:" "`~ssl.enum_crls` provide the ability to retrieve certificates, certificate " @@ -2794,7 +2956,7 @@ msgstr "" "information, and CRLs from the Windows cert store. (Contributed by Christian " "Heimes in :issue:`17134`.)" -#: ../../whatsnew/3.4.rst:1486 +#: ../../whatsnew/3.4.rst:1485 msgid "" "Support for server-side SNI (Server Name Indication) using the new :meth:" "`ssl.SSLContext.set_servername_callback` method. (Contributed by Daniel " @@ -2804,7 +2966,7 @@ msgstr "" "`ssl.SSLContext.set_servername_callback` method. (Contributed by Daniel " "Black in :issue:`8109`.)" -#: ../../whatsnew/3.4.rst:1490 +#: ../../whatsnew/3.4.rst:1489 msgid "" "The dictionary returned by :meth:`.SSLSocket.getpeercert` contains " "additional ``X509v3`` extension items: ``crlDistributionPoints``, " @@ -2816,11 +2978,11 @@ msgstr "" "``calIssuers``, and ``OCSP`` URIs. (Contributed by Christian Heimes in :" "issue:`18379`.)" -#: ../../whatsnew/3.4.rst:1496 +#: ../../whatsnew/3.4.rst:1495 msgid "stat" msgstr "stat" -#: ../../whatsnew/3.4.rst:1498 +#: ../../whatsnew/3.4.rst:1497 msgid "" "The :mod:`stat` module is now backed by a C implementation in :mod:`!_stat`. " "A C implementation is required as most of the values aren't standardized and " @@ -2830,7 +2992,7 @@ msgstr "" "A C implementation is required as most of the values aren't standardized and " "are platform-dependent. (Contributed by Christian Heimes in :issue:`11016`.)" -#: ../../whatsnew/3.4.rst:1502 +#: ../../whatsnew/3.4.rst:1501 msgid "" "The module supports new :mod:`~stat.ST_MODE` flags, :mod:`~stat.S_IFDOOR`, :" "const:`~stat.S_IFPORT`, and :const:`~stat.S_IFWHT`. (Contributed by " @@ -2840,11 +3002,11 @@ msgstr "" "const:`~stat.S_IFPORT`, and :const:`~stat.S_IFWHT`. (Contributed by " "Christian Hiemes in :issue:`11016`.)" -#: ../../whatsnew/3.4.rst:1508 +#: ../../whatsnew/3.4.rst:1507 msgid "struct" msgstr "struct" -#: ../../whatsnew/3.4.rst:1510 +#: ../../whatsnew/3.4.rst:1509 msgid "" "New function :mod:`~struct.iter_unpack` and a new :meth:`struct.Struct." "iter_unpack` method on compiled formats provide streamed unpacking of a " @@ -2856,11 +3018,11 @@ msgstr "" "buffer containing repeated instances of a given format of data. (Contributed " "by Antoine Pitrou in :issue:`17804`.)" -#: ../../whatsnew/3.4.rst:1517 +#: ../../whatsnew/3.4.rst:1516 msgid "subprocess" msgstr "subprocess" -#: ../../whatsnew/3.4.rst:1519 +#: ../../whatsnew/3.4.rst:1518 msgid "" ":func:`~subprocess.check_output` now accepts an *input* argument that can be " "used to provide the contents of ``stdin`` for the command that is run. " @@ -2870,7 +3032,7 @@ msgstr "" "used to provide the contents of ``stdin`` for the command that is run. " "(Contributed by Zack Weinberg in :issue:`16624`.)" -#: ../../whatsnew/3.4.rst:1523 +#: ../../whatsnew/3.4.rst:1522 msgid "" ":func:`~subprocess.getstatus` and :func:`~subprocess.getstatusoutput` now " "work on Windows. This change was actually inadvertently made in 3.3.4. " @@ -2880,11 +3042,11 @@ msgstr "" "work on Windows. This change was actually inadvertently made in 3.3.4. " "(Contributed by Tim Golden in :issue:`10197`.)" -#: ../../whatsnew/3.4.rst:1529 +#: ../../whatsnew/3.4.rst:1528 msgid "sunau" msgstr "sunau" -#: ../../whatsnew/3.4.rst:1531 +#: ../../whatsnew/3.4.rst:1530 msgid "" "The :meth:`!getparams` method now returns a namedtuple rather than a plain " "tuple. (Contributed by Claudiu Popa in :issue:`18901`.)" @@ -2892,7 +3054,7 @@ msgstr "" "The :meth:`!getparams` method now returns a namedtuple rather than a plain " "tuple. (Contributed by Claudiu Popa in :issue:`18901`.)" -#: ../../whatsnew/3.4.rst:1534 +#: ../../whatsnew/3.4.rst:1533 msgid "" ":meth:`!sunau.open` now supports the context management protocol: when used " "in a :keyword:`with` block, the ``close`` method of the returned object will " @@ -2904,7 +3066,7 @@ msgstr "" "be called automatically at the end of the block. (Contributed by Serhiy " "Storchaka in :issue:`18878`.)" -#: ../../whatsnew/3.4.rst:1539 +#: ../../whatsnew/3.4.rst:1538 msgid "" ":meth:`.AU_write.setsampwidth` now supports 24 bit samples, thus adding " "support for writing 24 sample using the module. (Contributed by Serhiy " @@ -2914,11 +3076,11 @@ msgstr "" "support for writing 24 sample using the module. (Contributed by Serhiy " "Storchaka in :issue:`19261`.)" -#: ../../whatsnew/3.4.rst:1549 +#: ../../whatsnew/3.4.rst:1548 msgid "sys" msgstr "sys" -#: ../../whatsnew/3.4.rst:1551 +#: ../../whatsnew/3.4.rst:1550 msgid "" "New function :func:`sys.getallocatedblocks` returns the current number of " "blocks allocated by the interpreter. (In CPython with the default ``--with-" @@ -2934,7 +3096,7 @@ msgstr "" "especially if automated via a test suite. (Contributed by Antoine Pitrou in :" "issue:`13390`.)" -#: ../../whatsnew/3.4.rst:1558 +#: ../../whatsnew/3.4.rst:1557 msgid "" "When the Python interpreter starts in :ref:`interactive mode `, it checks for an :data:`~sys.__interactivehook__` attribute " @@ -2962,11 +3124,11 @@ msgstr "" "mod:`sys` (or setting it to some other callable). (Contributed by Éric " "Araujo and Antoine Pitrou in :issue:`5845`.)" -#: ../../whatsnew/3.4.rst:1573 +#: ../../whatsnew/3.4.rst:1572 msgid "tarfile" msgstr "tarfile" -#: ../../whatsnew/3.4.rst:1575 +#: ../../whatsnew/3.4.rst:1574 msgid "" "The :mod:`tarfile` module now supports a simple :ref:`tarfile-commandline` " "when called as a script directly or via ``-m``. This can be used to create " @@ -2978,11 +3140,11 @@ msgstr "" "and extract tarfile archives. (Contributed by Berker Peksag in :issue:" "`13477`.)" -#: ../../whatsnew/3.4.rst:1581 +#: ../../whatsnew/3.4.rst:1580 msgid "textwrap" msgstr "textwrap" -#: ../../whatsnew/3.4.rst:1583 +#: ../../whatsnew/3.4.rst:1582 msgid "" "The :class:`~textwrap.TextWrapper` class has two new attributes/constructor " "arguments: :attr:`~textwrap.TextWrapper.max_lines`, which limits the number " @@ -3006,11 +3168,11 @@ msgstr "" "(Contributed by Antoine Pitrou and Serhiy Storchaka in :issue:`18585` and :" "issue:`18725`.)" -#: ../../whatsnew/3.4.rst:1595 +#: ../../whatsnew/3.4.rst:1594 msgid "threading" msgstr "threading" -#: ../../whatsnew/3.4.rst:1597 +#: ../../whatsnew/3.4.rst:1596 msgid "" "The :class:`~threading.Thread` object representing the main thread can be " "obtained from the new :func:`~threading.main_thread` function. In normal " @@ -3022,11 +3184,11 @@ msgstr "" "conditions this will be the thread from which the Python interpreter was " "started. (Contributed by Andrew Svetlov in :issue:`18882`.)" -#: ../../whatsnew/3.4.rst:1604 +#: ../../whatsnew/3.4.rst:1603 msgid "traceback" msgstr "traceback" -#: ../../whatsnew/3.4.rst:1606 +#: ../../whatsnew/3.4.rst:1605 msgid "" "A new :func:`traceback.clear_frames` function takes a traceback object and " "clears the local variables in all of the frames it references, reducing the " @@ -3038,11 +3200,11 @@ msgstr "" "amount of memory consumed. (Contributed by Andrew Kuchling in :issue:" "`1565525`.)" -#: ../../whatsnew/3.4.rst:1613 +#: ../../whatsnew/3.4.rst:1612 msgid "types" msgstr "types" -#: ../../whatsnew/3.4.rst:1615 +#: ../../whatsnew/3.4.rst:1614 msgid "" "A new :func:`~types.DynamicClassAttribute` descriptor provides a way to " "define an attribute that acts normally when looked up through an instance " @@ -3058,11 +3220,11 @@ msgstr "" "have virtual attributes on the class with the same name (see :mod:`Enum` for " "an example). (Contributed by Ethan Furman in :issue:`19030`.)" -#: ../../whatsnew/3.4.rst:1624 +#: ../../whatsnew/3.4.rst:1623 msgid "urllib" msgstr "urllib" -#: ../../whatsnew/3.4.rst:1626 +#: ../../whatsnew/3.4.rst:1625 msgid "" ":mod:`urllib.request` now supports ``data:`` URLs via the :class:`~urllib." "request.DataHandler` class. (Contributed by Mathias Panzenböck in :issue:" @@ -3072,7 +3234,7 @@ msgstr "" "request.DataHandler` class. (Contributed by Mathias Panzenböck in :issue:" "`16423`.)" -#: ../../whatsnew/3.4.rst:1630 +#: ../../whatsnew/3.4.rst:1629 msgid "" "The http method that will be used by a :class:`~urllib.request.Request` " "class can now be specified by setting a :class:`~urllib.request.Request." @@ -3084,7 +3246,7 @@ msgstr "" "method` class attribute on the subclass. (Contributed by Jason R Coombs in :" "issue:`18978`.)" -#: ../../whatsnew/3.4.rst:1635 +#: ../../whatsnew/3.4.rst:1634 msgid "" ":class:`~urllib.request.Request` objects are now reusable: if the :attr:" "`~urllib.request.Request.full_url` or :attr:`~urllib.request.Request.data` " @@ -3110,7 +3272,7 @@ msgstr "" "Alexey Kachayev in :issue:`16464`, Daniel Wozniak in :issue:`17485`, and " "Damien Brecht and Senthil Kumaran in :issue:`17272`.)" -#: ../../whatsnew/3.4.rst:1648 +#: ../../whatsnew/3.4.rst:1647 msgid "" ":class:`~urllib.error.HTTPError` objects now have a :attr:`~urllib.error." "HTTPError.headers` attribute that provides access to the HTTP response " @@ -3122,11 +3284,11 @@ msgstr "" "headers associated with the error. (Contributed by Berker Peksag in :issue:" "`15701`.)" -#: ../../whatsnew/3.4.rst:1655 +#: ../../whatsnew/3.4.rst:1654 msgid "unittest" msgstr "unittest" -#: ../../whatsnew/3.4.rst:1657 +#: ../../whatsnew/3.4.rst:1656 msgid "" "The :class:`~unittest.TestCase` class has a new method, :meth:`~unittest." "TestCase.subTest`, that produces a context manager whose :keyword:`with` " @@ -3144,7 +3306,21 @@ msgstr "" "indefinite number of separately identified and separately counted tests, all " "of which will run even if one or more of them fail. For example::" -#: ../../whatsnew/3.4.rst:1671 +#: ../../whatsnew/3.4.rst:1664 +msgid "" +"class NumbersTest(unittest.TestCase):\n" +" def test_even(self):\n" +" for i in range(6):\n" +" with self.subTest(i=i):\n" +" self.assertEqual(i % 2, 0)" +msgstr "" +"class NumbersTest(unittest.TestCase):\n" +" def test_even(self):\n" +" for i in range(6):\n" +" with self.subTest(i=i):\n" +" self.assertEqual(i % 2, 0)" + +#: ../../whatsnew/3.4.rst:1670 msgid "" "will result in six subtests, each identified in the unittest verbose output " "with a label consisting of the variable name ``i`` and a particular value " @@ -3156,7 +3332,7 @@ msgstr "" "for that variable (``i=0``, ``i=1``, etc). See :ref:`subtests` for the full " "version of this example. (Contributed by Antoine Pitrou in :issue:`16997`.)" -#: ../../whatsnew/3.4.rst:1676 +#: ../../whatsnew/3.4.rst:1675 msgid "" ":func:`unittest.main` now accepts an iterable of test names for " "*defaultTest*, where previously it only accepted a single test name as a " @@ -3166,7 +3342,7 @@ msgstr "" "*defaultTest*, where previously it only accepted a single test name as a " "string. (Contributed by Jyrki Pulliainen in :issue:`15132`.)" -#: ../../whatsnew/3.4.rst:1680 +#: ../../whatsnew/3.4.rst:1679 msgid "" "If :class:`~unittest.SkipTest` is raised during test discovery (that is, at " "the module level in the test file), it is now reported as a skip instead of " @@ -3176,7 +3352,7 @@ msgstr "" "the module level in the test file), it is now reported as a skip instead of " "an error. (Contributed by Zach Ware in :issue:`16935`.)" -#: ../../whatsnew/3.4.rst:1684 +#: ../../whatsnew/3.4.rst:1683 msgid "" ":meth:`~unittest.TestLoader.discover` now sorts the discovered files to " "provide consistent test ordering. (Contributed by Martin Melin and Jeff " @@ -3186,7 +3362,7 @@ msgstr "" "provide consistent test ordering. (Contributed by Martin Melin and Jeff " "Ramnani in :issue:`16709`.)" -#: ../../whatsnew/3.4.rst:1688 +#: ../../whatsnew/3.4.rst:1687 msgid "" ":class:`~unittest.TestSuite` now drops references to tests as soon as the " "test has been run, if the test is successful. On Python interpreters that " @@ -3204,7 +3380,7 @@ msgstr "" "custom ``_removeTestAtIndex`` method. (Contributed by Tom Wardill, Matt " "McClure, and Andrew Svetlov in :issue:`11798`.)" -#: ../../whatsnew/3.4.rst:1696 +#: ../../whatsnew/3.4.rst:1695 msgid "" "A new test assertion context-manager, :meth:`~unittest.TestCase.assertLogs`, " "will ensure that a given block of code emits a log message using the :mod:" @@ -3224,7 +3400,7 @@ msgstr "" "formatted messages that were logged. (Contributed by Antoine Pitrou in :" "issue:`18937`.)" -#: ../../whatsnew/3.4.rst:1705 +#: ../../whatsnew/3.4.rst:1704 msgid "" "Test discovery now works with namespace packages (Contributed by Claudiu " "Popa in :issue:`17457`.)" @@ -3232,7 +3408,7 @@ msgstr "" "Test discovery now works with namespace packages (Contributed by Claudiu " "Popa in :issue:`17457`.)" -#: ../../whatsnew/3.4.rst:1708 +#: ../../whatsnew/3.4.rst:1707 msgid "" ":mod:`unittest.mock` objects now inspect their specification signatures when " "matching calls, which means an argument can now be matched by either " @@ -3244,7 +3420,7 @@ msgstr "" "position or name, instead of only by position. (Contributed by Antoine " "Pitrou in :issue:`17015`.)" -#: ../../whatsnew/3.4.rst:1713 +#: ../../whatsnew/3.4.rst:1712 msgid "" ":func:`~mock.mock_open` objects now have ``readline`` and ``readlines`` " "methods. (Contributed by Toshio Kuratomi in :issue:`17467`.)" @@ -3252,11 +3428,11 @@ msgstr "" ":func:`~mock.mock_open` objects now have ``readline`` and ``readlines`` " "methods. (Contributed by Toshio Kuratomi in :issue:`17467`.)" -#: ../../whatsnew/3.4.rst:1718 +#: ../../whatsnew/3.4.rst:1717 msgid "venv" msgstr "venv" -#: ../../whatsnew/3.4.rst:1720 +#: ../../whatsnew/3.4.rst:1719 msgid "" ":mod:`venv` now includes activation scripts for the ``csh`` and ``fish`` " "shells. (Contributed by Andrew Svetlov in :issue:`15417`.)" @@ -3264,7 +3440,7 @@ msgstr "" ":mod:`venv` now includes activation scripts for the ``csh`` and ``fish`` " "shells. (Contributed by Andrew Svetlov in :issue:`15417`.)" -#: ../../whatsnew/3.4.rst:1723 +#: ../../whatsnew/3.4.rst:1722 msgid "" ":class:`~venv.EnvBuilder` and the :func:`~venv.create` convenience function " "take a new keyword argument *with_pip*, which defaults to ``False``, that " @@ -3278,11 +3454,11 @@ msgstr "" "installed in the virtual environment. (Contributed by Nick Coghlan in :issue:" "`19552` as part of the :pep:`453` implementation.)" -#: ../../whatsnew/3.4.rst:1731 +#: ../../whatsnew/3.4.rst:1730 msgid "wave" msgstr "wave" -#: ../../whatsnew/3.4.rst:1733 +#: ../../whatsnew/3.4.rst:1732 msgid "" "The :meth:`~wave.getparams` method now returns a namedtuple rather than a " "plain tuple. (Contributed by Claudiu Popa in :issue:`17487`.)" @@ -3290,7 +3466,7 @@ msgstr "" "The :meth:`~wave.getparams` method now returns a namedtuple rather than a " "plain tuple. (Contributed by Claudiu Popa in :issue:`17487`.)" -#: ../../whatsnew/3.4.rst:1736 +#: ../../whatsnew/3.4.rst:1735 msgid "" ":meth:`wave.open` now supports the context management protocol. " "(Contributed by Claudiu Popa in :issue:`17616`.)" @@ -3298,7 +3474,7 @@ msgstr "" ":meth:`wave.open` now supports the context management protocol. (Contributed " "by Claudiu Popa in :issue:`17616`.)" -#: ../../whatsnew/3.4.rst:1739 +#: ../../whatsnew/3.4.rst:1738 msgid "" ":mod:`wave` can now :ref:`write output to unseekable files `. (Contributed by David Jones, Guilherme Polo, and Serhiy " @@ -3308,7 +3484,7 @@ msgstr "" "objects>`. (Contributed by David Jones, Guilherme Polo, and Serhiy Storchaka " "in :issue:`5202`.)" -#: ../../whatsnew/3.4.rst:1743 +#: ../../whatsnew/3.4.rst:1742 msgid "" "The :meth:`~wave.Wave_write.writeframesraw` and :meth:`~wave.Wave_write." "writeframes` methods now accept any :term:`bytes-like object`. (Contributed " @@ -3318,11 +3494,11 @@ msgstr "" "writeframes` methods now accept any :term:`bytes-like object`. (Contributed " "by Serhiy Storchaka in :issue:`8311`.)" -#: ../../whatsnew/3.4.rst:1749 +#: ../../whatsnew/3.4.rst:1748 msgid "weakref" msgstr "weakref" -#: ../../whatsnew/3.4.rst:1751 +#: ../../whatsnew/3.4.rst:1750 msgid "" "New :class:`~weakref.WeakMethod` class simulates weak references to bound " "methods. (Contributed by Antoine Pitrou in :issue:`14631`.)" @@ -3330,7 +3506,7 @@ msgstr "" "New :class:`~weakref.WeakMethod` class simulates weak references to bound " "methods. (Contributed by Antoine Pitrou in :issue:`14631`.)" -#: ../../whatsnew/3.4.rst:1754 +#: ../../whatsnew/3.4.rst:1753 msgid "" "New :class:`~weakref.finalize` class makes it possible to register a " "callback to be invoked when an object is garbage collected, without needing " @@ -3342,7 +3518,7 @@ msgstr "" "to carefully manage the lifecycle of the weak reference itself. (Contributed " "by Richard Oudkerk in :issue:`15528`.)" -#: ../../whatsnew/3.4.rst:1759 +#: ../../whatsnew/3.4.rst:1758 msgid "" "The callback, if any, associated with a :class:`~weakref.ref` is now exposed " "via the :attr:`~weakref.ref.__callback__` attribute. (Contributed by Mark " @@ -3352,11 +3528,11 @@ msgstr "" "via the :attr:`~weakref.ref.__callback__` attribute. (Contributed by Mark " "Dickinson in :issue:`17643`.)" -#: ../../whatsnew/3.4.rst:1765 +#: ../../whatsnew/3.4.rst:1764 msgid "xml.etree" msgstr "xml.etree" -#: ../../whatsnew/3.4.rst:1767 +#: ../../whatsnew/3.4.rst:1766 msgid "" "A new parser, :class:`~xml.etree.ElementTree.XMLPullParser`, allows a non-" "blocking applications to parse XML documents. An example can be seen at :" @@ -3368,7 +3544,7 @@ msgstr "" "`elementtree-pull-parsing`. (Contributed by Antoine Pitrou in :issue:" "`17741`.)" -#: ../../whatsnew/3.4.rst:1772 +#: ../../whatsnew/3.4.rst:1771 msgid "" "The :mod:`xml.etree.ElementTree` :func:`~xml.etree.ElementTree.tostring` " "and :func:`~xml.etree.ElementTree.tostringlist` functions, and the :class:" @@ -3388,11 +3564,11 @@ msgstr "" "expanded (````) form. (Contributed by Ariel Poliak and Serhiy " "Storchaka in :issue:`14377`.)" -#: ../../whatsnew/3.4.rst:1783 +#: ../../whatsnew/3.4.rst:1782 msgid "zipfile" msgstr "zipfile" -#: ../../whatsnew/3.4.rst:1785 +#: ../../whatsnew/3.4.rst:1784 msgid "" "The :meth:`~zipfile.PyZipFile.writepy` method of the :class:`~zipfile." "PyZipFile` class has a new *filterfunc* option that can be used to control " @@ -3406,7 +3582,7 @@ msgstr "" "could be used to exclude test files from the archive. (Contributed by " "Christian Tismer in :issue:`19274`.)" -#: ../../whatsnew/3.4.rst:1791 +#: ../../whatsnew/3.4.rst:1790 msgid "" "The *allowZip64* parameter to :class:`~zipfile.ZipFile` and :class:`~zipfile." "PyZipfile` is now ``True`` by default. (Contributed by William Mallard in :" @@ -3416,15 +3592,15 @@ msgstr "" "PyZipfile` is now ``True`` by default. (Contributed by William Mallard in :" "issue:`17201`.)" -#: ../../whatsnew/3.4.rst:1798 +#: ../../whatsnew/3.4.rst:1797 msgid "CPython Implementation Changes" msgstr "CPython Implementation Changes" -#: ../../whatsnew/3.4.rst:1804 +#: ../../whatsnew/3.4.rst:1803 msgid "PEP 445: Customization of CPython Memory Allocators" msgstr "PEP 445: Customization of CPython Memory Allocators" -#: ../../whatsnew/3.4.rst:1806 +#: ../../whatsnew/3.4.rst:1805 msgid "" ":pep:`445` adds new C level interfaces to customize memory allocation in the " "CPython interpreter." @@ -3432,15 +3608,15 @@ msgstr "" ":pep:`445` adds new C level interfaces to customize memory allocation in the " "CPython interpreter." -#: ../../whatsnew/3.4.rst:1811 +#: ../../whatsnew/3.4.rst:1810 msgid ":pep:`445` -- Add new APIs to customize Python memory allocators" msgstr ":pep:`445` -- Add new APIs to customize Python memory allocators" -#: ../../whatsnew/3.4.rst:1818 +#: ../../whatsnew/3.4.rst:1817 msgid "PEP 442: Safe Object Finalization" msgstr "PEP 442: Safe Object Finalization" -#: ../../whatsnew/3.4.rst:1820 +#: ../../whatsnew/3.4.rst:1819 msgid "" ":pep:`442` removes the current limitations and quirks of object finalization " "in CPython. With it, objects with :meth:`__del__` methods, as well as " @@ -3452,7 +3628,7 @@ msgstr "" "generators with :keyword:`finally` clauses, can be finalized when they are " "part of a reference cycle." -#: ../../whatsnew/3.4.rst:1825 +#: ../../whatsnew/3.4.rst:1824 msgid "" "As part of this change, module globals are no longer forcibly set to :const:" "`None` during interpreter shutdown in most cases, instead relying on the " @@ -3466,15 +3642,15 @@ msgstr "" "of interpreter-shutdown-time errors, usually involving ``__del__`` methods, " "that have plagued Python since the cyclic GC was first introduced." -#: ../../whatsnew/3.4.rst:1834 +#: ../../whatsnew/3.4.rst:1833 msgid ":pep:`442` -- Safe object finalization" msgstr ":pep:`442` -- Safe object finalization" -#: ../../whatsnew/3.4.rst:1841 +#: ../../whatsnew/3.4.rst:1840 msgid "PEP 456: Secure and Interchangeable Hash Algorithm" msgstr "PEP 456: Secure and Interchangeable Hash Algorithm" -#: ../../whatsnew/3.4.rst:1843 +#: ../../whatsnew/3.4.rst:1842 msgid "" ":pep:`456` follows up on earlier security fix work done on Python's hash " "algorithm to address certain DOS attacks to which public facing APIs backed " @@ -3494,7 +3670,7 @@ msgstr "" "platforms that have a 64 bit data type. Any performance differences in " "comparison with the older FNV algorithm are trivial." -#: ../../whatsnew/3.4.rst:1852 +#: ../../whatsnew/3.4.rst:1851 msgid "" "The PEP adds additional fields to the :data:`sys.hash_info` named tuple to " "describe the hash algorithm in use by the currently executing binary. " @@ -3504,11 +3680,11 @@ msgstr "" "describe the hash algorithm in use by the currently executing binary. " "Otherwise, the PEP does not alter any existing CPython APIs." -#: ../../whatsnew/3.4.rst:1860 +#: ../../whatsnew/3.4.rst:1859 msgid "PEP 436: Argument Clinic" msgstr "PEP 436: Argument Clinic" -#: ../../whatsnew/3.4.rst:1862 +#: ../../whatsnew/3.4.rst:1861 msgid "" "\"Argument Clinic\" (:pep:`436`) is now part of the CPython build process " "and can be used to simplify the process of defining and maintaining accurate " @@ -3520,7 +3696,7 @@ msgstr "" "signatures for builtins and standard library extension modules implemented " "in C." -#: ../../whatsnew/3.4.rst:1867 +#: ../../whatsnew/3.4.rst:1866 msgid "" "Some standard library extension modules have been converted to use Argument " "Clinic in Python 3.4, and :mod:`pydoc` and :mod:`inspect` have been updated " @@ -3530,7 +3706,7 @@ msgstr "" "Clinic in Python 3.4, and :mod:`pydoc` and :mod:`inspect` have been updated " "accordingly." -#: ../../whatsnew/3.4.rst:1871 +#: ../../whatsnew/3.4.rst:1870 msgid "" "It is expected that signature metadata for programmatic introspection will " "be added to additional callables implemented in C as part of Python 3.4 " @@ -3540,7 +3716,7 @@ msgstr "" "be added to additional callables implemented in C as part of Python 3.4 " "maintenance releases." -#: ../../whatsnew/3.4.rst:1876 +#: ../../whatsnew/3.4.rst:1875 msgid "" "The Argument Clinic PEP is not fully up to date with the state of the " "implementation. This has been deemed acceptable by the release manager and " @@ -3552,19 +3728,19 @@ msgstr "" "core development team in this case, as Argument Clinic will not be made " "available as a public API for third party use in Python 3.4." -#: ../../whatsnew/3.4.rst:1883 +#: ../../whatsnew/3.4.rst:1882 msgid ":pep:`436` -- The Argument Clinic DSL" msgstr ":pep:`436` -- The Argument Clinic DSL" -#: ../../whatsnew/3.4.rst:1884 +#: ../../whatsnew/3.4.rst:1883 msgid "PEP written and implemented by Larry Hastings." msgstr "PEP written and implemented by Larry Hastings." -#: ../../whatsnew/3.4.rst:1888 +#: ../../whatsnew/3.4.rst:1887 msgid "Other Build and C API Changes" msgstr "Other Alterações a compilações e API C" -#: ../../whatsnew/3.4.rst:1890 +#: ../../whatsnew/3.4.rst:1889 msgid "" "The new :c:func:`PyType_GetSlot` function has been added to the stable ABI, " "allowing retrieval of function pointers from named type slots when using the " @@ -3574,7 +3750,7 @@ msgstr "" "allowing retrieval of function pointers from named type slots when using the " "limited API. (Contributed by Martin von Löwis in :issue:`17162`.)" -#: ../../whatsnew/3.4.rst:1894 +#: ../../whatsnew/3.4.rst:1893 msgid "" "The new :c:func:`!Py_SetStandardStreamEncoding` pre-initialization API " "allows applications embedding the CPython interpreter to reliably force a " @@ -3586,7 +3762,7 @@ msgstr "" "particular encoding and error handler for the standard streams. (Contributed " "by Bastien Montagne and Nick Coghlan in :issue:`16129`.)" -#: ../../whatsnew/3.4.rst:1899 +#: ../../whatsnew/3.4.rst:1898 msgid "" "Most Python C APIs that don't mutate string arguments are now correctly " "marked as accepting ``const char *`` rather than ``char *``. (Contributed " @@ -3596,7 +3772,7 @@ msgstr "" "marked as accepting ``const char *`` rather than ``char *``. (Contributed by " "Serhiy Storchaka in :issue:`1772673`.)" -#: ../../whatsnew/3.4.rst:1903 +#: ../../whatsnew/3.4.rst:1902 msgid "" "A new shell version of ``python-config`` can be used even when a python " "interpreter is not available (for example, in cross compilation scenarios)." @@ -3604,7 +3780,7 @@ msgstr "" "A new shell version of ``python-config`` can be used even when a python " "interpreter is not available (for example, in cross compilation scenarios)." -#: ../../whatsnew/3.4.rst:1906 +#: ../../whatsnew/3.4.rst:1905 msgid "" ":c:func:`PyUnicode_FromFormat` now supports width and precision " "specifications for ``%s``, ``%A``, ``%U``, ``%V``, ``%S``, and ``%R``. " @@ -3614,7 +3790,7 @@ msgstr "" "specifications for ``%s``, ``%A``, ``%U``, ``%V``, ``%S``, and ``%R``. " "(Contributed by Ysj Ray and Victor Stinner in :issue:`7330`.)" -#: ../../whatsnew/3.4.rst:1910 +#: ../../whatsnew/3.4.rst:1909 msgid "" "New function :c:func:`PyStructSequence_InitType2` supplements the existing :" "c:func:`PyStructSequence_InitType` function. The difference is that it " @@ -3624,7 +3800,7 @@ msgstr "" "c:func:`PyStructSequence_InitType` function. The difference is that it " "returns ``0`` on success and ``-1`` on failure." -#: ../../whatsnew/3.4.rst:1914 +#: ../../whatsnew/3.4.rst:1913 msgid "" "The CPython source can now be compiled using the address sanity checking " "features of recent versions of GCC and clang: the false alarms in the small " @@ -3636,7 +3812,7 @@ msgstr "" "object allocator have been silenced. (Contributed by Dhiru Kholia in :issue:" "`18596`.)" -#: ../../whatsnew/3.4.rst:1919 +#: ../../whatsnew/3.4.rst:1918 msgid "" "The Windows build now uses `Address Space Layout Randomization `_ and `Data Execution " @@ -3648,7 +3824,7 @@ msgstr "" "Prevention `_. " "(Contributed by Christian Heimes in :issue:`16632`.)" -#: ../../whatsnew/3.4.rst:1924 +#: ../../whatsnew/3.4.rst:1923 msgid "" "New function :c:func:`PyObject_LengthHint` is the C API equivalent of :func:" "`operator.length_hint`. (Contributed by Armin Ronacher in :issue:`16148`.)" @@ -3656,11 +3832,11 @@ msgstr "" "New function :c:func:`PyObject_LengthHint` is the C API equivalent of :func:" "`operator.length_hint`. (Contributed by Armin Ronacher in :issue:`16148`.)" -#: ../../whatsnew/3.4.rst:1932 +#: ../../whatsnew/3.4.rst:1931 msgid "Other Improvements" msgstr "Other Improvements" -#: ../../whatsnew/3.4.rst:1936 +#: ../../whatsnew/3.4.rst:1935 msgid "" "The :ref:`python ` command has a new :ref:`option `, ``-I``, which causes it to run in \"isolated mode\", " @@ -3684,7 +3860,7 @@ msgstr "" "most POSIX systems it can and should be used in the ``#!`` line of system " "scripts. (Contributed by Christian Heimes in :issue:`16499`.)" -#: ../../whatsnew/3.4.rst:1947 +#: ../../whatsnew/3.4.rst:1946 msgid "" "Tab-completion is now enabled by default in the interactive interpreter on " "systems that support :mod:`readline`. History is also enabled by default, " @@ -3696,7 +3872,7 @@ msgstr "" "and is written to (and read from) the file :file:`~/.python-history`. " "(Contributed by Antoine Pitrou and Éric Araujo in :issue:`5845`.)" -#: ../../whatsnew/3.4.rst:1952 +#: ../../whatsnew/3.4.rst:1951 msgid "" "Invoking the Python interpreter with ``--version`` now outputs the version " "to standard output instead of standard error (:issue:`18338`). Similar " @@ -3708,7 +3884,7 @@ msgstr "" "changes were made to :mod:`argparse` (:issue:`18920`) and other modules that " "have script-like invocation capabilities (:issue:`18922`)." -#: ../../whatsnew/3.4.rst:1957 +#: ../../whatsnew/3.4.rst:1956 msgid "" "The CPython Windows installer now adds ``.py`` to the :envvar:`PATHEXT` " "variable when extensions are registered, allowing users to run a python " @@ -3720,33 +3896,33 @@ msgstr "" "script at the windows command prompt by just typing its name without the ``." "py`` extension. (Contributed by Paul Moore in :issue:`18569`.)" -#: ../../whatsnew/3.4.rst:1962 +#: ../../whatsnew/3.4.rst:1961 msgid "" "A new ``make`` target `coverage-report `_ will build python, run " "the test suite, and generate an HTML coverage report for the C codebase " -"using ``gcov`` and `lcov `_." +"using ``gcov`` and `lcov `_." msgstr "" "A new ``make`` target `coverage-report `_ will build python, run " "the test suite, and generate an HTML coverage report for the C codebase " -"using ``gcov`` and `lcov `_." +"using ``gcov`` and `lcov `_." -#: ../../whatsnew/3.4.rst:1968 +#: ../../whatsnew/3.4.rst:1967 msgid "" "The ``-R`` option to the :ref:`python regression test suite ` now " "also checks for memory allocation leaks, using :func:`sys." -"getallocatedblocks()`. (Contributed by Antoine Pitrou in :issue:`13390`.)" +"getallocatedblocks`. (Contributed by Antoine Pitrou in :issue:`13390`.)" msgstr "" "The ``-R`` option to the :ref:`python regression test suite ` now " "also checks for memory allocation leaks, using :func:`sys." -"getallocatedblocks()`. (Contributed by Antoine Pitrou in :issue:`13390`.)" +"getallocatedblocks`. (Contributed by Antoine Pitrou in :issue:`13390`.)" -#: ../../whatsnew/3.4.rst:1973 +#: ../../whatsnew/3.4.rst:1972 msgid "``python -m`` now works with namespace packages." msgstr "``python -m`` now works with namespace packages." -#: ../../whatsnew/3.4.rst:1975 +#: ../../whatsnew/3.4.rst:1974 msgid "" "The :mod:`stat` module is now implemented in C, which means it gets the " "values for its constants from the C header files, instead of having the " @@ -3756,7 +3932,7 @@ msgstr "" "values for its constants from the C header files, instead of having the " "values hard-coded in the python module as was previously the case." -#: ../../whatsnew/3.4.rst:1979 +#: ../../whatsnew/3.4.rst:1978 msgid "" "Loading multiple python modules from a single OS module (``.so``, ``.dll``) " "now works correctly (previously it silently returned the first python module " @@ -3766,19 +3942,19 @@ msgstr "" "now works correctly (previously it silently returned the first python module " "in the file). (Contributed by Václav Šmilauer in :issue:`16421`.)" -#: ../../whatsnew/3.4.rst:1983 +#: ../../whatsnew/3.4.rst:1982 msgid "" -"A new opcode, :opcode:`LOAD_CLASSDEREF`, has been added to fix a bug in the " +"A new opcode, :opcode:`!LOAD_CLASSDEREF`, has been added to fix a bug in the " "loading of free variables in class bodies that could be triggered by certain " "uses of :ref:`__prepare__ `. (Contributed by Benjamin Peterson in :" "issue:`17853`.)" msgstr "" -"A new opcode, :opcode:`LOAD_CLASSDEREF`, has been added to fix a bug in the " +"A new opcode, :opcode:`!LOAD_CLASSDEREF`, has been added to fix a bug in the " "loading of free variables in class bodies that could be triggered by certain " "uses of :ref:`__prepare__ `. (Contributed by Benjamin Peterson in :" "issue:`17853`.)" -#: ../../whatsnew/3.4.rst:1988 +#: ../../whatsnew/3.4.rst:1987 msgid "" "A number of MemoryError-related crashes were identified and fixed by Victor " "Stinner using his :pep:`445`-based ``pyfailmalloc`` tool (:issue:`18408`, :" @@ -3788,7 +3964,7 @@ msgstr "" "Stinner using his :pep:`445`-based ``pyfailmalloc`` tool (:issue:`18408`, :" "issue:`18520`)." -#: ../../whatsnew/3.4.rst:1992 +#: ../../whatsnew/3.4.rst:1991 msgid "" "The ``pyvenv`` command now accepts a ``--copies`` option to use copies " "rather than symlinks even on systems where symlinks are the default. " @@ -3798,7 +3974,7 @@ msgstr "" "rather than symlinks even on systems where symlinks are the default. " "(Contributed by Vinay Sajip in :issue:`18807`.)" -#: ../../whatsnew/3.4.rst:1996 +#: ../../whatsnew/3.4.rst:1995 msgid "" "The ``pyvenv`` command also accepts a ``--without-pip`` option to suppress " "the otherwise-automatic bootstrapping of pip into the virtual environment. " @@ -3810,7 +3986,7 @@ msgstr "" "(Contributed by Nick Coghlan in :issue:`19552` as part of the :pep:`453` " "implementation.)" -#: ../../whatsnew/3.4.rst:2001 +#: ../../whatsnew/3.4.rst:2000 msgid "" "The encoding name is now optional in the value set for the :envvar:" "`PYTHONIOENCODING` environment variable. This makes it possible to set just " @@ -3822,7 +3998,7 @@ msgstr "" "the error handler, without changing the default encoding. (Contributed by " "Serhiy Storchaka in :issue:`18818`.)" -#: ../../whatsnew/3.4.rst:2006 +#: ../../whatsnew/3.4.rst:2005 msgid "" "The :mod:`bz2`, :mod:`lzma`, and :mod:`gzip` module ``open`` functions now " "support ``x`` (exclusive creation) mode. (Contributed by Tim Heaney and " @@ -3832,11 +4008,11 @@ msgstr "" "support ``x`` (exclusive creation) mode. (Contributed by Tim Heaney and " "Vajrasky Kok in :issue:`19201`, :issue:`19222`, and :issue:`19223`.)" -#: ../../whatsnew/3.4.rst:2012 +#: ../../whatsnew/3.4.rst:2011 msgid "Significant Optimizations" msgstr "Otimizações Relevantes" -#: ../../whatsnew/3.4.rst:2014 +#: ../../whatsnew/3.4.rst:2013 msgid "" "The UTF-32 decoder is now 3x to 4x faster. (Contributed by Serhiy Storchaka " "in :issue:`14625`.)" @@ -3844,7 +4020,7 @@ msgstr "" "The UTF-32 decoder is now 3x to 4x faster. (Contributed by Serhiy Storchaka " "in :issue:`14625`.)" -#: ../../whatsnew/3.4.rst:2017 +#: ../../whatsnew/3.4.rst:2016 msgid "" "The cost of hash collisions for sets is now reduced. Each hash table probe " "now checks a series of consecutive, adjacent key/hash pairs before " @@ -3866,7 +4042,7 @@ msgstr "" "Set LINEAR_PROBES=0 to turn-off linear probing entirely. (Contributed by " "Raymond Hettinger in :issue:`18771`.)" -#: ../../whatsnew/3.4.rst:2028 +#: ../../whatsnew/3.4.rst:2027 msgid "" "The interpreter starts about 30% faster. A couple of measures lead to the " "speedup. The interpreter loads fewer modules on startup, e.g. the :mod:" @@ -3884,7 +4060,7 @@ msgstr "" "Heimes and Victor Stinner in :issue:`19219`, :issue:`19218`, :issue:" "`19209`, :issue:`19205` and :issue:`9548`.)" -#: ../../whatsnew/3.4.rst:2036 +#: ../../whatsnew/3.4.rst:2035 msgid "" ":class:`bz2.BZ2File` is now as fast or faster than the Python2 version for " "most cases. :class:`lzma.LZMAFile` has also been optimized. (Contributed " @@ -3894,7 +4070,7 @@ msgstr "" "most cases. :class:`lzma.LZMAFile` has also been optimized. (Contributed by " "Serhiy Storchaka and Nadeem Vawda in :issue:`16034`.)" -#: ../../whatsnew/3.4.rst:2040 +#: ../../whatsnew/3.4.rst:2039 msgid "" ":func:`random.getrandbits` is 20%-40% faster for small integers (the most " "common use case). (Contributed by Serhiy Storchaka in :issue:`16674`.)" @@ -3902,7 +4078,7 @@ msgstr "" ":func:`random.getrandbits` is 20%-40% faster for small integers (the most " "common use case). (Contributed by Serhiy Storchaka in :issue:`16674`.)" -#: ../../whatsnew/3.4.rst:2043 +#: ../../whatsnew/3.4.rst:2042 msgid "" "By taking advantage of the new storage format for strings, pickling of " "strings is now significantly faster. (Contributed by Victor Stinner and " @@ -3912,7 +4088,7 @@ msgstr "" "strings is now significantly faster. (Contributed by Victor Stinner and " "Antoine Pitrou in :issue:`15596`.)" -#: ../../whatsnew/3.4.rst:2047 +#: ../../whatsnew/3.4.rst:2046 msgid "" "A performance issue in :meth:`io.FileIO.readall` has been solved. This " "particularly affects Windows, and significantly speeds up the case of piping " @@ -3924,7 +4100,7 @@ msgstr "" "significant amounts of data through :mod:`subprocess`. (Contributed by " "Richard Oudkerk in :issue:`15758`.)" -#: ../../whatsnew/3.4.rst:2052 +#: ../../whatsnew/3.4.rst:2051 msgid "" ":func:`html.escape` is now 10x faster. (Contributed by Matt Bryant in :" "issue:`18020`.)" @@ -3932,7 +4108,7 @@ msgstr "" ":func:`html.escape` is now 10x faster. (Contributed by Matt Bryant in :issue:" "`18020`.)" -#: ../../whatsnew/3.4.rst:2055 +#: ../../whatsnew/3.4.rst:2054 msgid "" "On Windows, the native ``VirtualAlloc`` is now used instead of the CRT " "``malloc`` in ``obmalloc``. Artificial benchmarks show about a 3% memory " @@ -3942,7 +4118,7 @@ msgstr "" "``malloc`` in ``obmalloc``. Artificial benchmarks show about a 3% memory " "savings." -#: ../../whatsnew/3.4.rst:2059 +#: ../../whatsnew/3.4.rst:2058 msgid "" ":func:`os.urandom` now uses a lazily opened persistent file descriptor so as " "to avoid using many file descriptors when run in parallel from multiple " @@ -3952,11 +4128,11 @@ msgstr "" "to avoid using many file descriptors when run in parallel from multiple " "threads. (Contributed by Antoine Pitrou in :issue:`18756`.)" -#: ../../whatsnew/3.4.rst:2067 +#: ../../whatsnew/3.4.rst:2066 msgid "Deprecated" msgstr "Descontinuados" -#: ../../whatsnew/3.4.rst:2069 +#: ../../whatsnew/3.4.rst:2068 msgid "" "This section covers various APIs and other features that have been " "deprecated in Python 3.4, and will be removed in Python 3.5 or later. In " @@ -3970,11 +4146,11 @@ msgstr "" "`DeprecationWarning` when the interpreter is run with deprecation warnings " "enabled (for example, by using ``-Wd``)." -#: ../../whatsnew/3.4.rst:2077 +#: ../../whatsnew/3.4.rst:2076 msgid "Deprecations in the Python API" msgstr "Deprecations in the Python API" -#: ../../whatsnew/3.4.rst:2079 +#: ../../whatsnew/3.4.rst:2078 msgid "" "As mentioned in :ref:`whatsnew-pep-451`, a number of :mod:`importlib` " "methods and functions are deprecated: :meth:`!importlib.find_loader` is " @@ -4016,7 +4192,7 @@ msgstr "" "importlib.util.set_package` are no longer needed because their functions are " "now handled automatically by the import system." -#: ../../whatsnew/3.4.rst:2104 +#: ../../whatsnew/3.4.rst:2103 msgid "" "The :mod:`!imp` module is pending deprecation. To keep compatibility with " "Python 2/3 code bases, the module's removal is currently not scheduled." @@ -4024,7 +4200,7 @@ msgstr "" "The :mod:`!imp` module is pending deprecation. To keep compatibility with " "Python 2/3 code bases, the module's removal is currently not scheduled." -#: ../../whatsnew/3.4.rst:2107 +#: ../../whatsnew/3.4.rst:2106 msgid "" "The :mod:`formatter` module is pending deprecation and is slated for removal " "in Python 3.6." @@ -4032,7 +4208,7 @@ msgstr "" "The :mod:`formatter` module is pending deprecation and is slated for removal " "in Python 3.6." -#: ../../whatsnew/3.4.rst:2110 +#: ../../whatsnew/3.4.rst:2109 msgid "" "``MD5`` as the default *digestmod* for the :func:`hmac.new` function is " "deprecated. Python 3.6 will require an explicit digest name or constructor " @@ -4042,7 +4218,7 @@ msgstr "" "deprecated. Python 3.6 will require an explicit digest name or constructor " "as *digestmod* argument." -#: ../../whatsnew/3.4.rst:2114 +#: ../../whatsnew/3.4.rst:2113 msgid "" "The internal ``Netrc`` class in the :mod:`ftplib` module has been documented " "as deprecated in its docstring for quite some time. It now emits a :exc:" @@ -4052,7 +4228,7 @@ msgstr "" "as deprecated in its docstring for quite some time. It now emits a :exc:" "`DeprecationWarning` and will be removed completely in Python 3.5." -#: ../../whatsnew/3.4.rst:2118 +#: ../../whatsnew/3.4.rst:2117 msgid "" "The undocumented *endtime* argument to :meth:`subprocess.Popen.wait` should " "not have been exposed and is hopefully not in use; it is deprecated and will " @@ -4062,13 +4238,13 @@ msgstr "" "not have been exposed and is hopefully not in use; it is deprecated and will " "mostly likely be removed in Python 3.5." -#: ../../whatsnew/3.4.rst:2122 +#: ../../whatsnew/3.4.rst:2121 msgid "" "The *strict* argument of :class:`~html.parser.HTMLParser` is deprecated." msgstr "" "The *strict* argument of :class:`~html.parser.HTMLParser` is deprecated." -#: ../../whatsnew/3.4.rst:2124 +#: ../../whatsnew/3.4.rst:2123 msgid "" "The :mod:`plistlib` :func:`~plistlib.readPlist`, :func:`~plistlib." "writePlist`, :func:`~plistlib.readPlistFromBytes`, and :func:`~plistlib." @@ -4084,7 +4260,7 @@ msgstr "" "`~plistlib.loads`, and :func:`~plistlib.dumps`. :func:`~plistlib.Data` is " "deprecated in favor of just using the :class:`bytes` constructor." -#: ../../whatsnew/3.4.rst:2131 +#: ../../whatsnew/3.4.rst:2130 msgid "" "The :mod:`sysconfig` key ``SO`` is deprecated, it has been replaced by " "``EXT_SUFFIX``." @@ -4092,7 +4268,7 @@ msgstr "" "The :mod:`sysconfig` key ``SO`` is deprecated, it has been replaced by " "``EXT_SUFFIX``." -#: ../../whatsnew/3.4.rst:2134 +#: ../../whatsnew/3.4.rst:2133 msgid "" "The ``U`` mode accepted by various ``open`` functions is deprecated. In " "Python3 it does not do anything useful, and should be replaced by " @@ -4104,7 +4280,7 @@ msgstr "" "appropriate uses of :class:`io.TextIOWrapper` (if needed) and its *newline* " "argument." -#: ../../whatsnew/3.4.rst:2139 +#: ../../whatsnew/3.4.rst:2138 msgid "" "The *parser* argument of :func:`xml.etree.ElementTree.iterparse` has been " "deprecated, as has the *html* argument of :func:`~xml.etree.ElementTree." @@ -4116,11 +4292,11 @@ msgstr "" "XMLParser`. To prepare for the removal of the latter, all arguments to " "``XMLParser`` should be passed by keyword." -#: ../../whatsnew/3.4.rst:2146 +#: ../../whatsnew/3.4.rst:2145 msgid "Deprecated Features" msgstr "Deprecated Features" -#: ../../whatsnew/3.4.rst:2148 +#: ../../whatsnew/3.4.rst:2147 msgid "" "Running :ref:`idle` with the ``-n`` flag (no subprocess) is deprecated. " "However, the feature will not be removed until :issue:`18823` is resolved." @@ -4128,7 +4304,7 @@ msgstr "" "Running :ref:`idle` with the ``-n`` flag (no subprocess) is deprecated. " "However, the feature will not be removed until :issue:`18823` is resolved." -#: ../../whatsnew/3.4.rst:2151 +#: ../../whatsnew/3.4.rst:2150 msgid "" "The site module adding a \"site-python\" directory to sys.path, if it " "exists, is deprecated (:issue:`19375`)." @@ -4136,15 +4312,15 @@ msgstr "" "The site module adding a \"site-python\" directory to sys.path, if it " "exists, is deprecated (:issue:`19375`)." -#: ../../whatsnew/3.4.rst:2157 +#: ../../whatsnew/3.4.rst:2156 msgid "Removed" msgstr "Removidos" -#: ../../whatsnew/3.4.rst:2161 +#: ../../whatsnew/3.4.rst:2160 msgid "Operating Systems No Longer Supported" msgstr "Operating Systems No Longer Supported" -#: ../../whatsnew/3.4.rst:2163 +#: ../../whatsnew/3.4.rst:2162 msgid "" "Support for the following operating systems has been removed from the source " "and build tools:" @@ -4152,29 +4328,29 @@ msgstr "" "Support for the following operating systems has been removed from the source " "and build tools:" -#: ../../whatsnew/3.4.rst:2166 +#: ../../whatsnew/3.4.rst:2165 msgid "OS/2 (:issue:`16135`)." msgstr "OS/2 (:issue:`16135`)." -#: ../../whatsnew/3.4.rst:2167 +#: ../../whatsnew/3.4.rst:2166 msgid "Windows 2000 (changeset e52df05b496a)." msgstr "Windows 2000 (changeset e52df05b496a)." -#: ../../whatsnew/3.4.rst:2168 +#: ../../whatsnew/3.4.rst:2167 msgid "" "Windows systems where ``COMSPEC`` points to ``command.com`` (:issue:`14470`)." msgstr "" "Windows systems where ``COMSPEC`` points to ``command.com`` (:issue:`14470`)." -#: ../../whatsnew/3.4.rst:2169 +#: ../../whatsnew/3.4.rst:2168 msgid "VMS (:issue:`16136`)." msgstr "VMS (:issue:`16136`)." -#: ../../whatsnew/3.4.rst:2173 +#: ../../whatsnew/3.4.rst:2172 msgid "API and Feature Removals" msgstr "Remoção de APIs e recursos" -#: ../../whatsnew/3.4.rst:2175 +#: ../../whatsnew/3.4.rst:2174 msgid "" "The following obsolete and previously deprecated APIs and features have been " "removed:" @@ -4182,7 +4358,7 @@ msgstr "" "The following obsolete and previously deprecated APIs and features have been " "removed:" -#: ../../whatsnew/3.4.rst:2178 +#: ../../whatsnew/3.4.rst:2177 msgid "" "The unmaintained ``Misc/TextMate`` and ``Misc/vim`` directories have been " "removed (see the `devguide `_ for suggestions " @@ -4192,7 +4368,7 @@ msgstr "" "removed (see the `devguide `_ for suggestions " "on what to use instead)." -#: ../../whatsnew/3.4.rst:2182 +#: ../../whatsnew/3.4.rst:2181 msgid "" "The ``SO`` makefile macro is removed (it was replaced by the " "``SHLIB_SUFFIX`` and ``EXT_SUFFIX`` macros) (:issue:`16754`)." @@ -4200,7 +4376,7 @@ msgstr "" "The ``SO`` makefile macro is removed (it was replaced by the " "``SHLIB_SUFFIX`` and ``EXT_SUFFIX`` macros) (:issue:`16754`)." -#: ../../whatsnew/3.4.rst:2185 +#: ../../whatsnew/3.4.rst:2184 msgid "" "The ``PyThreadState.tick_counter`` field has been removed; its value has " "been meaningless since Python 3.2, when the \"new GIL\" was introduced (:" @@ -4210,7 +4386,7 @@ msgstr "" "been meaningless since Python 3.2, when the \"new GIL\" was introduced (:" "issue:`19199`)." -#: ../../whatsnew/3.4.rst:2189 +#: ../../whatsnew/3.4.rst:2188 msgid "" "``PyLoader`` and ``PyPycLoader`` have been removed from :mod:`importlib`. " "(Contributed by Taras Lyapun in :issue:`15641`.)" @@ -4218,7 +4394,7 @@ msgstr "" "``PyLoader`` and ``PyPycLoader`` have been removed from :mod:`importlib`. " "(Contributed by Taras Lyapun in :issue:`15641`.)" -#: ../../whatsnew/3.4.rst:2192 +#: ../../whatsnew/3.4.rst:2191 msgid "" "The *strict* argument to :class:`~http.client.HTTPConnection` and :class:" "`~http.client.HTTPSConnection` has been removed. HTTP 0.9-style \"Simple " @@ -4228,7 +4404,7 @@ msgstr "" "`~http.client.HTTPSConnection` has been removed. HTTP 0.9-style \"Simple " "Responses\" are no longer supported." -#: ../../whatsnew/3.4.rst:2196 +#: ../../whatsnew/3.4.rst:2195 msgid "" "The deprecated :mod:`urllib.request.Request` getter and setter methods " "``add_data``, ``has_data``, ``get_data``, ``get_type``, ``get_host``, " @@ -4240,7 +4416,7 @@ msgstr "" "``get_selector``, ``set_proxy``, ``get_origin_req_host``, and " "``is_unverifiable`` have been removed (use direct attribute access instead)." -#: ../../whatsnew/3.4.rst:2201 +#: ../../whatsnew/3.4.rst:2200 msgid "" "Support for loading the deprecated ``TYPE_INT64`` has been removed from :mod:" "`marshal`. (Contributed by Dan Riti in :issue:`15480`.)" @@ -4248,7 +4424,7 @@ msgstr "" "Support for loading the deprecated ``TYPE_INT64`` has been removed from :mod:" "`marshal`. (Contributed by Dan Riti in :issue:`15480`.)" -#: ../../whatsnew/3.4.rst:2204 +#: ../../whatsnew/3.4.rst:2203 msgid "" ":class:`inspect.Signature`: positional-only parameters are now required to " "have a valid name." @@ -4256,7 +4432,7 @@ msgstr "" ":class:`inspect.Signature`: positional-only parameters are now required to " "have a valid name." -#: ../../whatsnew/3.4.rst:2207 +#: ../../whatsnew/3.4.rst:2206 msgid "" ":meth:`object.__format__` no longer accepts non-empty format strings, it now " "raises a :exc:`TypeError` instead. Using a non-empty string has been " @@ -4276,7 +4452,7 @@ msgstr "" "objects that do not have a __format__ method that handles it. See :issue:" "`7994` for background." -#: ../../whatsnew/3.4.rst:2216 +#: ../../whatsnew/3.4.rst:2215 msgid "" ":meth:`difflib.SequenceMatcher.isbjunk` and :meth:`difflib.SequenceMatcher." "isbpopular` were deprecated in 3.2, and have now been removed: use ``x in sm." @@ -4288,11 +4464,11 @@ msgstr "" "bjunk`` and ``x in sm.bpopular``, where *sm* is a :class:`~difflib." "SequenceMatcher` object (:issue:`13248`)." -#: ../../whatsnew/3.4.rst:2224 +#: ../../whatsnew/3.4.rst:2223 msgid "Code Cleanups" msgstr "Code Cleanups" -#: ../../whatsnew/3.4.rst:2226 +#: ../../whatsnew/3.4.rst:2225 msgid "" "The unused and undocumented internal ``Scanner`` class has been removed from " "the :mod:`pydoc` module." @@ -4300,7 +4476,7 @@ msgstr "" "The unused and undocumented internal ``Scanner`` class has been removed from " "the :mod:`pydoc` module." -#: ../../whatsnew/3.4.rst:2229 +#: ../../whatsnew/3.4.rst:2228 msgid "" "The private and effectively unused ``_gestalt`` module has been removed, " "along with the private :mod:`platform` functions ``_mac_ver_lookup``, " @@ -4312,7 +4488,7 @@ msgstr "" "``_mac_ver_gstalt``, and ``_bcd2str``, which would only have ever been " "called on badly broken OSX systems (see :issue:`18393`)." -#: ../../whatsnew/3.4.rst:2234 +#: ../../whatsnew/3.4.rst:2233 msgid "" "The hardcoded copies of certain :mod:`stat` constants that were included in " "the :mod:`tarfile` module namespace have been removed." @@ -4320,11 +4496,11 @@ msgstr "" "The hardcoded copies of certain :mod:`stat` constants that were included in " "the :mod:`tarfile` module namespace have been removed." -#: ../../whatsnew/3.4.rst:2240 +#: ../../whatsnew/3.4.rst:2239 msgid "Porting to Python 3.4" msgstr "Porting to Python 3.4" -#: ../../whatsnew/3.4.rst:2242 +#: ../../whatsnew/3.4.rst:2241 msgid "" "This section lists previously described changes and other bugfixes that may " "require changes to your code." @@ -4332,11 +4508,11 @@ msgstr "" "Esta seção lista as alterações descritas anteriormente e outras correções " "que podem exigir alterações no seu código." -#: ../../whatsnew/3.4.rst:2247 +#: ../../whatsnew/3.4.rst:2246 msgid "Changes in 'python' Command Behavior" msgstr "Changes in 'python' Command Behavior" -#: ../../whatsnew/3.4.rst:2249 +#: ../../whatsnew/3.4.rst:2248 msgid "" "In a posix shell, setting the :envvar:`PATH` environment variable to an " "empty value is equivalent to not setting it at all. However, setting :" @@ -4354,7 +4530,7 @@ msgstr "" "how :envvar:`PATH` works. The behavior now conforms to the posix convention " "for :envvar:`PATH`." -#: ../../whatsnew/3.4.rst:2257 +#: ../../whatsnew/3.4.rst:2256 msgid "" "The [X refs, Y blocks] output of a debug (``--with-pydebug``) build of the " "CPython interpreter is now off by default. It can be re-enabled using the " @@ -4364,7 +4540,7 @@ msgstr "" "CPython interpreter is now off by default. It can be re-enabled using the ``-" "X showrefcount`` option. (Contributed by Ezio Melotti in :issue:`17323`.)" -#: ../../whatsnew/3.4.rst:2261 +#: ../../whatsnew/3.4.rst:2260 msgid "" "The python command and most stdlib scripts (as well as :mod:`argparse`) now " "output ``--version`` information to ``stdout`` instead of ``stderr`` (for " @@ -4374,11 +4550,11 @@ msgstr "" "output ``--version`` information to ``stdout`` instead of ``stderr`` (for " "issue list see :ref:`other-improvements-3.4` above)." -#: ../../whatsnew/3.4.rst:2267 +#: ../../whatsnew/3.4.rst:2266 msgid "Changes in the Python API" msgstr "Alterações na API Python" -#: ../../whatsnew/3.4.rst:2269 +#: ../../whatsnew/3.4.rst:2268 msgid "" "The ABCs defined in :mod:`importlib.abc` now either raise the appropriate " "exception or return a default value instead of raising :exc:" @@ -4392,17 +4568,17 @@ msgstr "" "`super` and falling through all the way to the ABCs. For compatibility, " "catch both :exc:`NotImplementedError` or the appropriate exception as needed." -#: ../../whatsnew/3.4.rst:2275 +#: ../../whatsnew/3.4.rst:2274 msgid "" -"The module type now initializes the :attr:`__package__` and :attr:" -"`__loader__` attributes to ``None`` by default. To determine if these " -"attributes were set in a backwards-compatible fashion, use e.g. " +"The module type now initializes the :attr:`~module.__package__` and :attr:" +"`~module.__loader__` attributes to ``None`` by default. To determine if " +"these attributes were set in a backwards-compatible fashion, use e.g. " "``getattr(module, '__loader__', None) is not None``. (:issue:`17115`.)" msgstr "" -"The module type now initializes the :attr:`__package__` and :attr:" -"`__loader__` attributes to ``None`` by default. To determine if these " -"attributes were set in a backwards-compatible fashion, use e.g. " -"``getattr(module, '__loader__', None) is not None``. (:issue:`17115`.)" +"The module type now initializes the :attr:`~module.__package__` and :attr:" +"`~module.__loader__` attributes to ``None`` by default. To determine if " +"these attributes were set in a backwards-compatible fashion, use e.g. " +"``getattr(module, '__loader__', None) is not None``. (:issue:`17115`.)" #: ../../whatsnew/3.4.rst:2280 msgid "" @@ -4978,3 +5154,29 @@ msgid "" msgstr "" "Para aplicações que exigem o antigo comportamento anterior, elas podem " "passar um contexto alternativo::" + +#: ../../whatsnew/3.4.rst:2535 +msgid "" +"import urllib.request\n" +"import ssl\n" +"\n" +"# This disables all verification\n" +"context = ssl._create_unverified_context()\n" +"\n" +"# This allows using a specific certificate for the host, which doesn't need\n" +"# to be in the trust store\n" +"context = ssl.create_default_context(cafile=\"/path/to/file.crt\")\n" +"\n" +"urllib.request.urlopen(\"https://invalid-cert\", context=context)" +msgstr "" +"import urllib.request\n" +"import ssl\n" +"\n" +"# This disables all verification\n" +"context = ssl._create_unverified_context()\n" +"\n" +"# This allows using a specific certificate for the host, which doesn't need\n" +"# to be in the trust store\n" +"context = ssl.create_default_context(cafile=\"/path/to/file.crt\")\n" +"\n" +"urllib.request.urlopen(\"https://invalid-cert\", context=context)" diff --git a/whatsnew/3.5.po b/whatsnew/3.5.po index 4fc665dda..30478c5dd 100644 --- a/whatsnew/3.5.po +++ b/whatsnew/3.5.po @@ -1,31 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Ricardo Cappellano , 2021 -# Raphael Mendonça, 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Italo Penaforte , 2021 -# Victor Matheus Castro , 2021 -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-16 14:15+0000\n" -"PO-Revision-Date: 2021-06-29 13:04+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -35,7 +29,7 @@ msgstr "O que há de novo no Python 3.5" #: ../../whatsnew/3.5.rst:0 msgid "Editors" -msgstr "" +msgstr "Editores" #: ../../whatsnew/3.5.rst:5 msgid "Elvis Pranskevichus , Yury Selivanov " @@ -256,6 +250,12 @@ msgid "" "Coroutine functions are declared using the new :keyword:`async def` syntax::" msgstr "" +#: ../../whatsnew/3.5.rst:178 +msgid "" +">>> async def coro():\n" +"... return 'spam'" +msgstr "" + #: ../../whatsnew/3.5.rst:181 msgid "" "Inside a coroutine function, the new :keyword:`await` expression can be used " @@ -274,16 +274,72 @@ msgstr "" msgid "An example of a rudimentary HTTP client written using the new syntax::" msgstr "" +#: ../../whatsnew/3.5.rst:191 +msgid "" +"import asyncio\n" +"\n" +"async def http_get(domain):\n" +" reader, writer = await asyncio.open_connection(domain, 80)\n" +"\n" +" writer.write(b'\\r\\n'.join([\n" +" b'GET / HTTP/1.1',\n" +" b'Host: %b' % domain.encode('latin-1'),\n" +" b'Connection: close',\n" +" b'', b''\n" +" ]))\n" +"\n" +" async for line in reader:\n" +" print('>>>', line)\n" +"\n" +" writer.close()\n" +"\n" +"loop = asyncio.get_event_loop()\n" +"try:\n" +" loop.run_until_complete(http_get('example.com'))\n" +"finally:\n" +" loop.close()" +msgstr "" + #: ../../whatsnew/3.5.rst:215 msgid "" "Similarly to asynchronous iteration, there is a new syntax for asynchronous " "context managers. The following script::" msgstr "" +#: ../../whatsnew/3.5.rst:218 +msgid "" +"import asyncio\n" +"\n" +"async def coro(name, lock):\n" +" print('coro {}: waiting for lock'.format(name))\n" +" async with lock:\n" +" print('coro {}: holding the lock'.format(name))\n" +" await asyncio.sleep(1)\n" +" print('coro {}: releasing the lock'.format(name))\n" +"\n" +"loop = asyncio.get_event_loop()\n" +"lock = asyncio.Lock()\n" +"coros = asyncio.gather(coro(1, lock), coro(2, lock))\n" +"try:\n" +" loop.run_until_complete(coros)\n" +"finally:\n" +" loop.close()" +msgstr "" + #: ../../whatsnew/3.5.rst:235 msgid "will output::" msgstr "" +#: ../../whatsnew/3.5.rst:237 +msgid "" +"coro 2: waiting for lock\n" +"coro 2: holding the lock\n" +"coro 1: waiting for lock\n" +"coro 2: releasing the lock\n" +"coro 1: holding the lock\n" +"coro 1: releasing the lock" +msgstr "" + #: ../../whatsnew/3.5.rst:244 msgid "" "Note that both :keyword:`async for` and :keyword:`async with` can only be " @@ -336,14 +392,42 @@ msgid "" "cleaner code::" msgstr "" +#: ../../whatsnew/3.5.rst:285 +msgid "S = (H @ beta - r).T @ inv(H @ V @ H.T) @ (H @ beta - r)" +msgstr "" + #: ../../whatsnew/3.5.rst:287 msgid "instead of::" msgstr "" +#: ../../whatsnew/3.5.rst:289 +msgid "" +"S = dot((dot(H, beta) - r).T,\n" +" dot(inv(dot(dot(H, V), H.T)), dot(H, beta) - r))" +msgstr "" + #: ../../whatsnew/3.5.rst:292 msgid "NumPy 1.10 has support for the new operator::" msgstr "" +#: ../../whatsnew/3.5.rst:294 +msgid "" +">>> import numpy\n" +"\n" +">>> x = numpy.ones(3)\n" +">>> x\n" +"array([ 1., 1., 1.])\n" +"\n" +">>> m = numpy.eye(3)\n" +">>> m\n" +"array([[ 1., 0., 0.],\n" +" [ 0., 1., 0.],\n" +" [ 0., 0., 1.]])\n" +"\n" +">>> x @ m\n" +"array([ 1., 1., 1.])" +msgstr "" + #: ../../whatsnew/3.5.rst:312 msgid ":pep:`465` -- A dedicated infix operator for matrix multiplication" msgstr "" @@ -363,12 +447,40 @@ msgid "" "arbitrary number of unpackings in :ref:`function calls `::" msgstr "" +#: ../../whatsnew/3.5.rst:325 +msgid "" +">>> print(*[1], *[2], 3, *[4, 5])\n" +"1 2 3 4 5\n" +"\n" +">>> def fn(a, b, c, d):\n" +"... print(a, b, c, d)\n" +"...\n" +"\n" +">>> fn(**{'a': 1, 'c': 3}, **{'b': 2, 'd': 4})\n" +"1 2 3 4" +msgstr "" + #: ../../whatsnew/3.5.rst:335 msgid "" "Similarly, tuple, list, set, and dictionary displays allow multiple " "unpackings (see :ref:`exprlists` and :ref:`dict`)::" msgstr "" +#: ../../whatsnew/3.5.rst:338 +msgid "" +">>> *range(4), 4\n" +"(0, 1, 2, 3, 4)\n" +"\n" +">>> [*range(4), 4]\n" +"[0, 1, 2, 3, 4]\n" +"\n" +">>> {*range(4), 4, *(5, 6, 7)}\n" +"{0, 1, 2, 3, 4, 5, 6, 7}\n" +"\n" +">>> {'x': 1, **{'y': 2}}\n" +"{'x': 1, 'y': 2}" +msgstr "" + #: ../../whatsnew/3.5.rst:352 msgid ":pep:`448` -- Additional Unpacking Generalizations" msgstr "" @@ -403,12 +515,33 @@ msgstr "" msgid "Examples::" msgstr "Exemplos::" +#: ../../whatsnew/3.5.rst:375 +msgid "" +">>> b'Hello %b!' % b'World'\n" +"b'Hello World!'\n" +"\n" +">>> b'x=%i y=%f' % (1, 2.5)\n" +"b'x=1 y=2.500000'" +msgstr "" + #: ../../whatsnew/3.5.rst:381 msgid "" "Unicode is not allowed for ``%b``, but it is accepted by ``%a`` (equivalent " "of ``repr(obj).encode('ascii', 'backslashreplace')``)::" msgstr "" +#: ../../whatsnew/3.5.rst:384 +msgid "" +">>> b'Hello %b!' % 'World'\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: %b requires bytes, or an object that implements __bytes__, not " +"'str'\n" +"\n" +">>> b'price: %a' % '10€'\n" +"b\"price: '10\\\\u20ac'\"" +msgstr "" + #: ../../whatsnew/3.5.rst:392 msgid "" "Note that ``%s`` and ``%r`` conversion types, although supported, should " @@ -456,10 +589,16 @@ msgid "" "declared in the annotations::" msgstr "" +#: ../../whatsnew/3.5.rst:422 +msgid "" +"def greeting(name: str) -> str:\n" +" return 'Hello ' + name" +msgstr "" + #: ../../whatsnew/3.5.rst:425 msgid "" "While these annotations are available at runtime through the usual :attr:" -"`__annotations__` attribute, *no automatic type checking happens at " +"`~object.__annotations__` attribute, *no automatic type checking happens at " "runtime*. Instead, it is assumed that a separate off-line type checker (e." "g. `mypy `_) will be used for on-demand source code " "analysis." @@ -524,6 +663,13 @@ msgid "" "generally not make an additional system call::" msgstr "" +#: ../../whatsnew/3.5.rst:466 +msgid "" +"for entry in os.scandir(path):\n" +" if not entry.name.startswith('.') and entry.is_file():\n" +" print(entry.name)" +msgstr "" + #: ../../whatsnew/3.5.rst:472 msgid "" ":pep:`471` -- os.scandir() function -- a better and faster directory iterator" @@ -563,10 +709,24 @@ msgid "" "Compare::" msgstr "" +#: ../../whatsnew/3.5.rst:494 +msgid "print(\"Hello World\")" +msgstr "" + #: ../../whatsnew/3.5.rst:496 msgid "and::" msgstr "e::" +#: ../../whatsnew/3.5.rst:498 +msgid "" +"while True:\n" +" try:\n" +" print(\"Hello World\")\n" +" break\n" +" except InterruptedError:\n" +" continue" +msgstr "" + #: ../../whatsnew/3.5.rst:505 msgid "" ":pep:`475` implements automatic retry of system calls on ``EINTR``. This " @@ -673,6 +833,26 @@ msgid "" "term:`__future__` import is necessary::" msgstr "" +#: ../../whatsnew/3.5.rst:578 +msgid "" +">>> from __future__ import generator_stop\n" +"\n" +">>> def gen():\n" +"... next(iter([]))\n" +"... yield\n" +"...\n" +">>> next(gen())\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in gen\n" +"StopIteration\n" +"\n" +"The above exception was the direct cause of the following exception:\n" +"\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"RuntimeError: generator raised StopIteration" +msgstr "" + #: ../../whatsnew/3.5.rst:595 msgid "" "Without a ``__future__`` import, a :exc:`PendingDeprecationWarning` will be " @@ -704,12 +884,34 @@ msgid "" "the larger absolute value::" msgstr "" +#: ../../whatsnew/3.5.rst:617 +msgid "" +">>> import math\n" +">>> a = 5.0\n" +">>> b = 4.99998\n" +">>> math.isclose(a, b, rel_tol=1e-5)\n" +"True\n" +">>> math.isclose(a, b, rel_tol=1e-6)\n" +"False" +msgstr "" + #: ../../whatsnew/3.5.rst:625 msgid "" "It is also possible to compare two values using absolute tolerance, which " "must be a non-negative value::" msgstr "" +#: ../../whatsnew/3.5.rst:628 +msgid "" +">>> import math\n" +">>> a = 5.0\n" +">>> b = 4.99998\n" +">>> math.isclose(a, b, abs_tol=0.00003)\n" +"True\n" +">>> math.isclose(a, b, abs_tol=0.00001)\n" +"False" +msgstr "" + #: ../../whatsnew/3.5.rst:638 msgid ":pep:`485` -- A function for testing approximate equality" msgstr ":pep:`485` -- Uma função para testar igualdade aproximada" @@ -798,7 +1000,7 @@ msgstr "Outras mudanças na linguagem" #: ../../whatsnew/3.5.rst:703 msgid "Some smaller changes made to the core Python language are:" -msgstr "Alguma das mudanças menores feitas no núcleo da linguagem Python são:" +msgstr "Algumas das mudanças menores feitas no núcleo da linguagem Python são:" #: ../../whatsnew/3.5.rst:705 msgid "" @@ -867,6 +1069,12 @@ msgid "" "running:" msgstr "" +#: ../../whatsnew/3.5.rst:747 +msgid "" +"$ python -m zipapp myapp\n" +"$ python myapp.pyz" +msgstr "" + #: ../../whatsnew/3.5.rst:752 msgid "" "The module implementation has been contributed by Paul Moore in :issue:" @@ -1127,6 +1335,14 @@ msgid "" "Docstrings produced by :func:`~collections.namedtuple` can now be updated::" msgstr "" +#: ../../whatsnew/3.5.rst:923 +msgid "" +"Point = namedtuple('Point', ['x', 'y'])\n" +"Point.__doc__ += ': Cartesian coordinate'\n" +"Point.x.__doc__ = 'abscissa'\n" +"Point.y.__doc__ = 'ordinate'" +msgstr "" + #: ../../whatsnew/3.5.rst:928 msgid "(Contributed by Berker Peksag in :issue:`24064`.)" msgstr "" @@ -1236,6 +1452,25 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" +#: ../../whatsnew/3.5.rst:1000 +msgid "" +">>> import configparser\n" +">>> conv = {}\n" +">>> conv['list'] = lambda v: [e.strip() for e in v.split() if e.strip()]\n" +">>> cfg = configparser.ConfigParser(converters=conv)\n" +">>> cfg.read_string(\"\"\"\n" +"... [s]\n" +"... list = a b c d e f g\n" +"... \"\"\")\n" +">>> cfg.get('s', 'list')\n" +"'a b c d e f g'\n" +">>> cfg.getlist('s', 'list')\n" +"['a', 'b', 'c', 'd', 'e', 'f', 'g']\n" +">>> section = cfg['s']\n" +">>> section.getlist('list')\n" +"['a', 'b', 'c', 'd', 'e', 'f', 'g']" +msgstr "" + #: ../../whatsnew/3.5.rst:1016 msgid "(Contributed by Łukasz Langa in :issue:`18159`.)" msgstr "" @@ -1252,6 +1487,17 @@ msgid "" "don't provide any options to redirect it::" msgstr "" +#: ../../whatsnew/3.5.rst:1027 +msgid "" +">>> import contextlib, io, logging\n" +">>> f = io.StringIO()\n" +">>> with contextlib.redirect_stderr(f):\n" +"... logging.warning('warning')\n" +"...\n" +">>> f.getvalue()\n" +"'WARNING:root:warning\\n'" +msgstr "" + #: ../../whatsnew/3.5.rst:1035 msgid "(Contributed by Berker Peksag in :issue:`22389`.)" msgstr "" @@ -1385,6 +1631,15 @@ msgid "" "initial number of enum values if only *names* are provided::" msgstr "" +#: ../../whatsnew/3.5.rst:1128 +msgid "" +">>> Animal = enum.Enum('Animal', 'cat dog', start=10)\n" +">>> Animal.cat\n" +"\n" +">>> Animal.dog\n" +"" +msgstr "" + #: ../../whatsnew/3.5.rst:1134 msgid "(Contributed by Ethan Furman in :issue:`21706`.)" msgstr "" @@ -1446,6 +1701,17 @@ msgid "" "comparison::" msgstr "" +#: ../../whatsnew/3.5.rst:1181 +msgid "" +">>> import heapq\n" +">>> a = ['9', '777', '55555']\n" +">>> b = ['88', '6666']\n" +">>> list(heapq.merge(a, b, key=len))\n" +"['9', '88', '777', '6666', '55555']\n" +">>> list(heapq.merge(reversed(a), reversed(b), key=len, reverse=True))\n" +"['55555', '6666', '777', '88', '9']" +msgstr "" + #: ../../whatsnew/3.5.rst:1189 msgid "(Contributed by Raymond Hettinger in :issue:`13742`.)" msgstr "" @@ -1475,13 +1741,25 @@ msgid "" "the next request::" msgstr "" +#: ../../whatsnew/3.5.rst:1210 +msgid "" +"import http.client\n" +"conn = http.client.HTTPConnection('www.python.org')\n" +"for retries in range(3):\n" +" try:\n" +" conn.request('GET', '/')\n" +" resp = conn.getresponse()\n" +" except http.client.RemoteDisconnected:\n" +" pass" +msgstr "" + #: ../../whatsnew/3.5.rst:1219 msgid "(Contributed by Martin Panter in :issue:`3566`.)" msgstr "" #: ../../whatsnew/3.5.rst:1223 msgid "idlelib and IDLE" -msgstr "idlelib and IDLE" +msgstr "idlelib e IDLE" #: ../../whatsnew/3.5.rst:1225 msgid "" @@ -1585,6 +1863,15 @@ msgid "" "arguments::" msgstr "" +#: ../../whatsnew/3.5.rst:1293 +msgid "" +">>> def foo(a, b='ham', *args): pass\n" +">>> ba = inspect.signature(foo).bind('spam')\n" +">>> ba.apply_defaults()\n" +">>> ba.arguments\n" +"OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])" +msgstr "" + #: ../../whatsnew/3.5.rst:1299 msgid "(Contributed by Yury Selivanov in :issue:`24190`.)" msgstr "" @@ -1645,6 +1932,15 @@ msgid "" "construct network objects from existing addresses::" msgstr "" +#: ../../whatsnew/3.5.rst:1342 +msgid "" +">>> import ipaddress\n" +">>> ipaddress.IPv4Network(('127.0.0.0', 8))\n" +"IPv4Network('127.0.0.0/8')\n" +">>> ipaddress.IPv4Network(('127.0.0.0', '255.0.0.0'))\n" +"IPv4Network('127.0.0.0/8')" +msgstr "" + #: ../../whatsnew/3.5.rst:1348 msgid "(Contributed by Peter Moody and Antoine Pitrou in :issue:`16531`.)" msgstr "" @@ -1656,6 +1952,17 @@ msgid "" "returns the name of the reverse DNS PTR record::" msgstr "" +#: ../../whatsnew/3.5.rst:1354 +msgid "" +">>> import ipaddress\n" +">>> addr = ipaddress.IPv4Address('127.0.0.1')\n" +">>> addr.reverse_pointer\n" +"'1.0.0.127.in-addr.arpa'\n" +">>> addr6 = ipaddress.IPv6Address('::1')\n" +">>> addr6.reverse_pointer\n" +"'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa'" +msgstr "" + #: ../../whatsnew/3.5.rst:1362 msgid "(Contributed by Leon Weber in :issue:`20480`.)" msgstr "" @@ -1703,6 +2010,19 @@ msgid "" "account::" msgstr "" +#: ../../whatsnew/3.5.rst:1394 +msgid "" +">>> import locale\n" +">>> locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8')\n" +"'de_DE.UTF-8'\n" +">>> locale.delocalize('1.234,56')\n" +"'1234.56'\n" +">>> locale.setlocale(locale.LC_NUMERIC, 'en_US.UTF-8')\n" +"'en_US.UTF-8'\n" +">>> locale.delocalize('1,234.56')\n" +"'1234.56'" +msgstr "" + #: ../../whatsnew/3.5.rst:1404 msgid "(Contributed by Cédric Krier in :issue:`13918`.)" msgstr "" @@ -1719,6 +2039,16 @@ msgid "" "*exc_info* argument, in addition to boolean values and exception tuples::" msgstr "" +#: ../../whatsnew/3.5.rst:1416 +msgid "" +">>> import logging\n" +">>> try:\n" +"... 1/0\n" +"... except ZeroDivisionError as ex:\n" +"... logging.error('exception', exc_info=ex)\n" +"ERROR:root:exception" +msgstr "" + #: ../../whatsnew/3.5.rst:1423 msgid "(Contributed by Yury Selivanov in :issue:`20537`.)" msgstr "" @@ -1854,6 +2184,20 @@ msgid "" "commonprefix` function, it always returns a valid path::" msgstr "" +#: ../../whatsnew/3.5.rst:1512 +msgid "" +">>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])\n" +"'/usr/l'\n" +"\n" +">>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])\n" +"'/usr'" +msgstr "" +">>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])\n" +"'/usr/l'\n" +"\n" +">>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])\n" +"'/usr'" + #: ../../whatsnew/3.5.rst:1518 msgid "(Contributed by Rafik Draoui and Serhiy Storchaka in :issue:`10395`.)" msgstr "" @@ -1869,6 +2213,15 @@ msgid "" "be either another :class:`~pathlib.Path` object, or a string::" msgstr "" +#: ../../whatsnew/3.5.rst:1528 +msgid "" +">>> import pathlib\n" +">>> p1 = pathlib.Path('/etc/hosts')\n" +">>> p2 = pathlib.Path('/etc/../etc/hosts')\n" +">>> p1.samefile(p2)\n" +"True" +msgstr "" + #: ../../whatsnew/3.5.rst:1534 msgid "(Contributed by Vajrasky Kok and Antoine Pitrou in :issue:`19775`.)" msgstr "" @@ -1909,6 +2262,14 @@ msgid "" "spam42``::" msgstr "" +#: ../../whatsnew/3.5.rst:1558 +msgid "" +">>> import pathlib\n" +">>> p = pathlib.Path('~/spam42')\n" +">>> p.expanduser().write_text('ham')\n" +"3" +msgstr "" + #: ../../whatsnew/3.5.rst:1563 msgid "(Contributed by Christopher Welborn in :issue:`20218`.)" msgstr "" @@ -1946,6 +2307,16 @@ msgid "" "allowed in lookbehind assertions::" msgstr "" +#: ../../whatsnew/3.5.rst:1589 +msgid "" +">>> import re\n" +">>> pat = re.compile(r'(a|b).(?<=\\1)c')\n" +">>> pat.match('aac')\n" +"<_sre.SRE_Match object; span=(0, 3), match='aac'>\n" +">>> pat.match('bbc')\n" +"<_sre.SRE_Match object; span=(0, 3), match='bbc'>" +msgstr "" + #: ../../whatsnew/3.5.rst:1596 msgid "(Contributed by Serhiy Storchaka in :issue:`9179`.)" msgstr "" @@ -1971,6 +2342,17 @@ msgid "" "information about the error::" msgstr "" +#: ../../whatsnew/3.5.rst:1611 +msgid "" +">>> re.compile(\"\"\"\n" +"... (?x)\n" +"... .++\n" +"... \"\"\")\n" +"Traceback (most recent call last):\n" +" ...\n" +"sre_constants.error: multiple repeat at position 16 (line 3, column 7)" +msgstr "" + #: ../../whatsnew/3.5.rst:1619 msgid "(Contributed by Serhiy Storchaka in :issue:`22578`.)" msgstr "" @@ -2041,7 +2423,7 @@ msgid "" "Both the :class:`!SMTPServer` and :class:`!SMTPChannel` classes now accept a " "*decode_data* keyword argument to determine if the ``DATA`` portion of the " "SMTP transaction is decoded using the ``\"utf-8\"`` codec or is instead " -"provided to the :meth:`!SMTPServer.process_message()` method as a byte " +"provided to the :meth:`!SMTPServer.process_message` method as a byte " "string. The default is ``True`` for backward compatibility reasons, but " "will change to ``False`` in Python 3.6. If *decode_data* is set to " "``False``, the ``process_message`` method must be prepared to accept keyword " @@ -2053,8 +2435,8 @@ msgid "" "The :class:`!SMTPServer` class now advertises the ``8BITMIME`` extension (:" "rfc:`6152`) if *decode_data* has been set ``True``. If the client specifies " "``BODY=8BITMIME`` on the ``MAIL`` command, it is passed to :meth:`!" -"SMTPServer.process_message()` via the *mail_options* keyword. (Contributed " -"by Milan Oberkirch and R. David Murray in :issue:`21795`.)" +"SMTPServer.process_message` via the *mail_options* keyword. (Contributed by " +"Milan Oberkirch and R. David Murray in :issue:`21795`.)" msgstr "" #: ../../whatsnew/3.5.rst:1684 @@ -2062,7 +2444,7 @@ msgid "" "The :class:`!SMTPServer` class now also supports the ``SMTPUTF8`` extension " "(:rfc:`6531`: Internationalized Email). If the client specified ``SMTPUTF8 " "BODY=8BITMIME`` on the ``MAIL`` command, they are passed to :meth:`!" -"SMTPServer.process_message()` via the *mail_options* keyword. It is the " +"SMTPServer.process_message` via the *mail_options* keyword. It is the " "responsibility of the ``process_message`` method to correctly handle the " "``SMTPUTF8`` data. (Contributed by Milan Oberkirch in :issue:`21725`.)" msgstr "" @@ -2295,6 +2677,22 @@ msgid "" "(Contributed by Thomas Kluyver in :issue:`23342`.)" msgstr "" +#: ../../whatsnew/3.5.rst:1850 +msgid "" +">>> subprocess.run([\"ls\", \"-l\"]) # doesn't capture output\n" +"CompletedProcess(args=['ls', '-l'], returncode=0)\n" +"\n" +">>> subprocess.run(\"exit 1\", shell=True, check=True)\n" +"Traceback (most recent call last):\n" +" ...\n" +"subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit " +"status 1\n" +"\n" +">>> subprocess.run([\"ls\", \"-l\", \"/dev/null\"], stdout=subprocess.PIPE)\n" +"CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,\n" +"stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\\n')" +msgstr "" + #: ../../whatsnew/3.5.rst:1864 msgid "sys" msgstr "sys" @@ -3110,6 +3508,12 @@ msgid "" "following syntax::" msgstr "" +#: ../../whatsnew/3.5.rst:2389 +msgid "" +"f(1 for x in [1], *args)\n" +"f(1 for x in [1], **kwargs)" +msgstr "" + #: ../../whatsnew/3.5.rst:2392 msgid "" "Python 3.5 now correctly raises a :exc:`SyntaxError`, as generator " @@ -3137,7 +3541,7 @@ msgstr "" #: ../../whatsnew/3.5.rst:2408 msgid "" -"The :meth:`ssl.SSLSocket.send()` method now raises either :exc:`ssl." +"The :meth:`ssl.SSLSocket.send` method now raises either :exc:`ssl." "SSLWantReadError` or :exc:`ssl.SSLWantWriteError` on a non-blocking socket " "if the operation would block. Previously, it would return ``0``. " "(Contributed by Nikolaus Rath in :issue:`20951`.)" @@ -3319,10 +3723,11 @@ msgstr "" #: ../../whatsnew/3.5.rst:2529 msgid "" -"Because the lack of the :attr:`__module__` attribute breaks pickling and " -"introspection, a deprecation warning is now raised for builtin types without " -"the :attr:`__module__` attribute. This would be an AttributeError in the " -"future. (Contributed by Serhiy Storchaka in :issue:`20204`.)" +"Because the lack of the :attr:`~type.__module__` attribute breaks pickling " +"and introspection, a deprecation warning is now raised for builtin types " +"without the :attr:`~type.__module__` attribute. This will be an :exc:" +"`AttributeError` in the future. (Contributed by Serhiy Storchaka in :issue:" +"`20204`.)" msgstr "" #: ../../whatsnew/3.5.rst:2535 diff --git a/whatsnew/3.6.po b/whatsnew/3.6.po index c6fb32747..dbf0bdc68 100644 --- a/whatsnew/3.6.po +++ b/whatsnew/3.6.po @@ -1,30 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Raphael Mendonça, 2021 -# Ricardo Cappellano , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Victor Matheus Castro , 2021 -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-29 13:04+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -34,7 +29,7 @@ msgstr "What's New In Python 3.6" #: ../../whatsnew/3.6.rst:0 msgid "Editors" -msgstr "" +msgstr "Editores" #: ../../whatsnew/3.6.rst:5 msgid "Elvis Pranskevichus , Yury Selivanov " @@ -330,6 +325,18 @@ msgstr "" "which are evaluated at run time, and then formatted using the :func:`format` " "protocol::" +#: ../../whatsnew/3.6.rst:192 +msgid "" +">>> name = \"Fred\"\n" +">>> f\"He said his name is {name}.\"\n" +"'He said his name is Fred.'\n" +">>> width = 10\n" +">>> precision = 4\n" +">>> value = decimal.Decimal(\"12.34567\")\n" +">>> f\"result: {value:{width}.{precision}}\" # nested fields\n" +"'result: 12.35'" +msgstr "" + #: ../../whatsnew/3.6.rst:203 msgid ":pep:`498` -- Literal String Interpolation." msgstr ":pep:`498` -- Literal String Interpolation." @@ -356,6 +363,16 @@ msgstr "" "parameters, a.k.a. type hints. This PEP adds syntax to Python for annotating " "the types of variables including class variables and instance variables::" +#: ../../whatsnew/3.6.rst:218 +msgid "" +"primes: List[int] = []\n" +"\n" +"captain: str # Note: no initial value!\n" +"\n" +"class Starship:\n" +" stats: Dict[str, int] = {}" +msgstr "" + #: ../../whatsnew/3.6.rst:225 msgid "" "Just as for function annotations, the Python interpreter does not attach any " @@ -408,6 +425,14 @@ msgstr "" ":pep:`515` adds the ability to use underscores in numeric literals for " "improved readability. For example::" +#: ../../whatsnew/3.6.rst:253 +msgid "" +">>> 1_000_000_000_000_000\n" +"1000000000000000\n" +">>> 0x_FF_FF_FF_FF\n" +"4294967295" +msgstr "" + #: ../../whatsnew/3.6.rst:258 msgid "" "Single underscores are allowed between digits and after any base specifier. " @@ -430,6 +455,14 @@ msgstr "" "type ``'d'``. For integer presentation types ``'b'``, ``'o'``, ``'x'``, and " "``'X'``, underscores will be inserted every 4 digits::" +#: ../../whatsnew/3.6.rst:269 +msgid "" +">>> '{:_}'.format(1000000)\n" +"'1_000_000'\n" +">>> '{:_x}'.format(0xFFFFFFFF)\n" +"'ffff_ffff'" +msgstr "" + #: ../../whatsnew/3.6.rst:276 msgid ":pep:`515` -- Underscores in Numeric Literals" msgstr ":pep:`515` -- Underscores in Numeric Literals" @@ -456,6 +489,15 @@ msgstr "" "the same function body. In Python 3.6 this restriction has been lifted, " "making it possible to define *asynchronous generators*::" +#: ../../whatsnew/3.6.rst:291 +msgid "" +"async def ticker(delay, to):\n" +" \"\"\"Yield numbers from 0 to *to* every *delay* seconds.\"\"\"\n" +" for i in range(to):\n" +" yield i\n" +" await asyncio.sleep(delay)" +msgstr "" + #: ../../whatsnew/3.6.rst:297 msgid "The new syntax allows for faster and more concise code." msgstr "The new syntax allows for faster and more concise code." @@ -480,6 +522,10 @@ msgstr "" ":pep:`530` adds support for using ``async for`` in list, set, dict " "comprehensions and generator expressions::" +#: ../../whatsnew/3.6.rst:313 +msgid "result = [i async for i in aiter() if i % 2]" +msgstr "" + #: ../../whatsnew/3.6.rst:315 msgid "" "Additionally, ``await`` expressions are supported in all kinds of " @@ -488,6 +534,10 @@ msgstr "" "Additionally, ``await`` expressions are supported in all kinds of " "comprehensions::" +#: ../../whatsnew/3.6.rst:318 +msgid "result = [await fun() for fun in funcs if await condition()]" +msgstr "" + #: ../../whatsnew/3.6.rst:322 msgid ":pep:`530` -- Asynchronous Comprehensions" msgstr ":pep:`530` -- Asynchronous Comprehensions" @@ -506,6 +556,22 @@ msgstr "" "The new ``__init_subclass__`` classmethod will be called on the base class " "whenever a new subclass is created::" +#: ../../whatsnew/3.6.rst:335 +msgid "" +"class PluginBase:\n" +" subclasses = []\n" +"\n" +" def __init_subclass__(cls, **kwargs):\n" +" super().__init_subclass__(**kwargs)\n" +" cls.subclasses.append(cls)\n" +"\n" +"class Plugin1(PluginBase):\n" +" pass\n" +"\n" +"class Plugin2(PluginBase):\n" +" pass" +msgstr "" + #: ../../whatsnew/3.6.rst:348 msgid "" "In order to allow zero-argument :func:`super` calls to work correctly from :" @@ -541,6 +607,25 @@ msgid "" "in the owner class::" msgstr "" +#: ../../whatsnew/3.6.rst:374 +msgid "" +"class IntField:\n" +" def __get__(self, instance, owner):\n" +" return instance.__dict__[self.name]\n" +"\n" +" def __set__(self, instance, value):\n" +" if not isinstance(value, int):\n" +" raise ValueError(f'expecting integer in {self.name}')\n" +" instance.__dict__[self.name] = value\n" +"\n" +" # this is the new initializer:\n" +" def __set_name__(self, owner, name):\n" +" self.name = name\n" +"\n" +"class Model:\n" +" int_field = IntField()" +msgstr "" + #: ../../whatsnew/3.6.rst:396 msgid ":ref:`Feature documentation `" msgstr ":ref:`Feature documentation `" @@ -598,6 +683,22 @@ msgid "" "Path` to be used more easily and transparently with pre-existing code::" msgstr "" +#: ../../whatsnew/3.6.rst:444 +msgid "" +">>> import pathlib\n" +">>> with open(pathlib.Path(\"README\")) as f:\n" +"... contents = f.read()\n" +"...\n" +">>> import os.path\n" +">>> os.path.splitext(pathlib.Path(\"some_file.txt\"))\n" +"('some_file', '.txt')\n" +">>> os.path.join(\"/a/b\", pathlib.Path(\"c\"))\n" +"'/a/b/c'\n" +">>> import os\n" +">>> os.fspath(pathlib.Path(\"some_file.txt\"))\n" +"'some_file.txt'" +msgstr "" + #: ../../whatsnew/3.6.rst:457 msgid "" "(Implemented by Brett Cannon, Ethan Furman, Dusty Phillips, and Jelle " @@ -640,6 +741,30 @@ msgstr "" "datetime` and :class:`datetime.time` classes to differentiate between two " "moments in time for which local times are the same::" +#: ../../whatsnew/3.6.rst:480 +msgid "" +">>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)\n" +">>> for i in range(4):\n" +"... u = u0 + i*HOUR\n" +"... t = u.astimezone(Eastern)\n" +"... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)\n" +"...\n" +"04:00:00 UTC = 00:00:00 EDT 0\n" +"05:00:00 UTC = 01:00:00 EDT 0\n" +"06:00:00 UTC = 01:00:00 EST 1\n" +"07:00:00 UTC = 02:00:00 EST 0" +msgstr "" +">>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)\n" +">>> for i in range(4):\n" +"... u = u0 + i*HOUR\n" +"... t = u.astimezone(Eastern)\n" +"... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)\n" +"...\n" +"04:00:00 UTC = 00:00:00 EDT 0\n" +"05:00:00 UTC = 01:00:00 EDT 0\n" +"06:00:00 UTC = 01:00:00 EST 1\n" +"07:00:00 UTC = 02:00:00 EST 0" + #: ../../whatsnew/3.6.rst:491 msgid "" "The values of the :attr:`fold ` attribute have the " @@ -681,26 +806,17 @@ msgid "" "Prior to Python 3.6, data loss could result when using bytes paths on " "Windows. With this change, using bytes to represent paths is now supported " "on Windows, provided those bytes are encoded with the encoding returned by :" -"func:`sys.getfilesystemencoding()`, which now defaults to ``'utf-8'``." +"func:`sys.getfilesystemencoding`, which now defaults to ``'utf-8'``." msgstr "" -"Prior to Python 3.6, data loss could result when using bytes paths on " -"Windows. With this change, using bytes to represent paths is now supported " -"on Windows, provided those bytes are encoded with the encoding returned by :" -"func:`sys.getfilesystemencoding()`, which now defaults to ``'utf-8'``." #: ../../whatsnew/3.6.rst:516 msgid "" "Applications that do not use str to represent paths should use :func:`os." -"fsencode()` and :func:`os.fsdecode()` to ensure their bytes are correctly " +"fsencode` and :func:`os.fsdecode` to ensure their bytes are correctly " "encoded. To revert to the previous behaviour, set :envvar:" "`PYTHONLEGACYWINDOWSFSENCODING` or call :func:`sys." "_enablelegacywindowsfsencoding`." msgstr "" -"Applications that do not use str to represent paths should use :func:`os." -"fsencode()` and :func:`os.fsdecode()` to ensure their bytes are correctly " -"encoded. To revert to the previous behaviour, set :envvar:" -"`PYTHONLEGACYWINDOWSFSENCODING` or call :func:`sys." -"_enablelegacywindowsfsencoding`." #: ../../whatsnew/3.6.rst:522 msgid "" @@ -747,11 +863,8 @@ msgstr "PEP 520: Preserving Class Attribute Definition Order" msgid "" "Attributes in a class definition body have a natural ordering: the same " "order in which the names appear in the source. This order is now preserved " -"in the new class's :attr:`~object.__dict__` attribute." +"in the new class's :attr:`~type.__dict__` attribute." msgstr "" -"Attributes in a class definition body have a natural ordering: the same " -"order in which the names appear in the source. This order is now preserved " -"in the new class's :attr:`~object.__dict__` attribute." #: ../../whatsnew/3.6.rst:554 msgid "" @@ -981,6 +1094,44 @@ msgstr "" "Example of fatal error on buffer overflow using ``python3.6 -X " "tracemalloc=5`` (store 5 frames in traces)::" +#: ../../whatsnew/3.6.rst:673 +msgid "" +"Debug memory block at address p=0x7fbcd41666f8: API 'o'\n" +" 4 bytes originally requested\n" +" The 7 pad bytes at p-7 are FORBIDDENBYTE, as expected.\n" +" The 8 pad bytes at tail=0x7fbcd41666fc are not all FORBIDDENBYTE " +"(0xfb):\n" +" at tail+0: 0x02 *** OUCH\n" +" at tail+1: 0xfb\n" +" at tail+2: 0xfb\n" +" at tail+3: 0xfb\n" +" at tail+4: 0xfb\n" +" at tail+5: 0xfb\n" +" at tail+6: 0xfb\n" +" at tail+7: 0xfb\n" +" The block was made by call #1233329 to debug malloc/realloc.\n" +" Data at p: 1a 2b 30 00\n" +"\n" +"Memory block allocated at (most recent call first):\n" +" File \"test/test_bytes.py\", line 323\n" +" File \"unittest/case.py\", line 600\n" +" File \"unittest/case.py\", line 648\n" +" File \"unittest/suite.py\", line 122\n" +" File \"unittest/suite.py\", line 84\n" +"\n" +"Fatal Python error: bad trailing pad byte\n" +"\n" +"Current thread 0x00007fbcdbd32700 (most recent call first):\n" +" File \"test/test_bytes.py\", line 323 in test_hex\n" +" File \"unittest/case.py\", line 600 in run\n" +" File \"unittest/case.py\", line 648 in __call__\n" +" File \"unittest/suite.py\", line 122 in run\n" +" File \"unittest/suite.py\", line 84 in __call__\n" +" File \"unittest/suite.py\", line 122 in run\n" +" File \"unittest/suite.py\", line 84 in __call__\n" +" ..." +msgstr "" + #: ../../whatsnew/3.6.rst:707 msgid "(Contributed by Victor Stinner in :issue:`26516` and :issue:`26564`.)" msgstr "(Contributed by Victor Stinner in :issue:`26516` and :issue:`26564`.)" @@ -1042,7 +1193,7 @@ msgstr "Outras mudanças na linguagem" #: ../../whatsnew/3.6.rst:740 msgid "Some smaller changes made to the core Python language are:" -msgstr "Alguma das mudanças menores feitas no núcleo da linguagem Python são:" +msgstr "Algumas das mudanças menores feitas no núcleo da linguagem Python são:" #: ../../whatsnew/3.6.rst:742 msgid "" @@ -1119,11 +1270,8 @@ msgstr "" msgid "" "Note that the pseudo-random generators in the :mod:`random` module should " "*NOT* be used for security purposes. Use :mod:`secrets` on Python 3.6+ and :" -"func:`os.urandom()` on Python 3.5 and earlier." +"func:`os.urandom` on Python 3.5 and earlier." msgstr "" -"Note that the pseudo-random generators in the :mod:`random` module should " -"*NOT* be used for security purposes. Use :mod:`secrets` on Python 3.6+ and :" -"func:`os.urandom()` on Python 3.5 and earlier." #: ../../whatsnew/3.6.rst:787 msgid ":pep:`506` -- Adding A Secrets Module To The Standard Library" @@ -1399,9 +1547,9 @@ msgstr "" #: ../../whatsnew/3.6.rst:935 msgid "" "The :func:`~collections.namedtuple` function now accepts an optional keyword " -"argument *module*, which, when specified, is used for the ``__module__`` " -"attribute of the returned named tuple class. (Contributed by Raymond " -"Hettinger in :issue:`17941`.)" +"argument *module*, which, when specified, is used for the :attr:`~type." +"__module__` attribute of the returned named tuple class. (Contributed by " +"Raymond Hettinger in :issue:`17941`.)" msgstr "" #: ../../whatsnew/3.6.rst:940 ../../whatsnew/3.6.rst:2295 @@ -1501,6 +1649,14 @@ msgid "" "positive denominator::" msgstr "" +#: ../../whatsnew/3.6.rst:1004 +msgid "" +">>> Decimal('-3.14').as_integer_ratio()\n" +"(-157, 50)" +msgstr "" +">>> Decimal('-3.14').as_integer_ratio()\n" +"(-157, 50)" + #: ../../whatsnew/3.6.rst:1007 msgid "(Contributed by Stefan Krah amd Mark Dickinson in :issue:`25928`.)" msgstr "" @@ -1588,6 +1744,18 @@ msgid "" "members automatically::" msgstr "" +#: ../../whatsnew/3.6.rst:1065 +msgid "" +">>> from enum import Enum, auto\n" +">>> class Color(Enum):\n" +"... red = auto()\n" +"... blue = auto()\n" +"... green = auto()\n" +"...\n" +">>> list(Color)\n" +"[, , ]" +msgstr "" + #: ../../whatsnew/3.6.rst:1076 msgid "faulthandler" msgstr "faulthandler" @@ -1659,7 +1827,7 @@ msgstr "" #: ../../whatsnew/3.6.rst:1123 msgid "idlelib and IDLE" -msgstr "idlelib and IDLE" +msgstr "idlelib e IDLE" #: ../../whatsnew/3.6.rst:1125 msgid "" @@ -1950,7 +2118,7 @@ msgstr "" #: ../../whatsnew/3.6.rst:1319 msgid "" -":func:`pickletools.dis()` now outputs the implicit memo index for the " +":func:`pickletools.dis` now outputs the implicit memo index for the " "``MEMOIZE`` opcode. (Contributed by Serhiy Storchaka in :issue:`25382`.)" msgstr "" @@ -2306,6 +2474,20 @@ msgid "" "the following example::" msgstr "" +#: ../../whatsnew/3.6.rst:1573 +msgid "" +">>> def f(): f()\n" +"...\n" +">>> f()\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" File \"\", line 1, in f\n" +" File \"\", line 1, in f\n" +" File \"\", line 1, in f\n" +" [Previous line repeated 995 more times]\n" +"RecursionError: maximum recursion depth exceeded" +msgstr "" + #: ../../whatsnew/3.6.rst:1584 msgid "(Contributed by Emanuel Barry in :issue:`26823`.)" msgstr "" @@ -2386,6 +2568,18 @@ msgid "" "lightweight distinct types for annotations::" msgstr "" +#: ../../whatsnew/3.6.rst:1637 +msgid "" +"from typing import NewType\n" +"\n" +"UserId = NewType('UserId', int)\n" +"some_id = UserId(524313)" +msgstr "" +"from typing import NewType\n" +"\n" +"UserId = NewType('UserId', int)\n" +"some_id = UserId(524313)" + #: ../../whatsnew/3.6.rst:1642 msgid "" "The static type checker will treat the new type as if it were a subclass of " @@ -2484,10 +2678,33 @@ msgstr "" msgid "Example with the script ``example.py``::" msgstr "" +#: ../../whatsnew/3.6.rst:1712 +msgid "" +"import warnings\n" +"\n" +"def func():\n" +" return open(__file__)\n" +"\n" +"f = func()\n" +"f = None" +msgstr "" + #: ../../whatsnew/3.6.rst:1720 msgid "Output of the command ``python3.6 -Wd -X tracemalloc=5 example.py``::" msgstr "" +#: ../../whatsnew/3.6.rst:1722 +msgid "" +"example.py:7: ResourceWarning: unclosed file <_io.TextIOWrapper " +"name='example.py' mode='r' encoding='UTF-8'>\n" +" f = None\n" +"Object allocated at (most recent call first):\n" +" File \"example.py\", lineno 4\n" +" return open(__file__)\n" +" File \"example.py\", lineno 6\n" +" f = func()" +msgstr "" + #: ../../whatsnew/3.6.rst:1730 msgid "" "The \"Object allocated at\" traceback is new and is only displayed if :mod:" @@ -2698,7 +2915,7 @@ msgstr "" #: ../../whatsnew/3.6.rst:1864 msgid "Build and C API Changes" -msgstr "Alterações a compilações e API C" +msgstr "Mudanças a construções e API C" #: ../../whatsnew/3.6.rst:1866 msgid "" @@ -2789,6 +3006,13 @@ msgid "" "Python prints :data:`sys.version` for detailed information." msgstr "" +#: ../../whatsnew/3.6.rst:1919 +msgid "" +"$ ./python -VV\n" +"Python 3.6.0b4+ (3.6:223967b49e49+, Nov 21 2016, 20:55:04)\n" +"[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]" +msgstr "" + #: ../../whatsnew/3.6.rst:1927 msgid "Deprecated" msgstr "Descontinuados" @@ -3258,6 +3482,12 @@ msgid "" "containing the following:" msgstr "" +#: ../../whatsnew/3.6.rst:2270 +msgid "" +"[sdist]\n" +"formats=zip" +msgstr "" + #: ../../whatsnew/3.6.rst:2275 msgid "" "This behavior has also been backported to earlier Python versions by " @@ -3394,8 +3624,8 @@ msgstr "" #: ../../whatsnew/3.6.rst:2369 msgid "" -"The new :opcode:`FORMAT_VALUE` and :opcode:`BUILD_STRING` opcodes as part of " -"the :ref:`formatted string literal ` implementation. " +"The new :opcode:`!FORMAT_VALUE` and :opcode:`BUILD_STRING` opcodes as part " +"of the :ref:`formatted string literal ` implementation. " "(Contributed by Eric Smith in :issue:`25483` and Serhiy Storchaka in :issue:" "`27078`.)" msgstr "" @@ -3410,10 +3640,10 @@ msgstr "" #: ../../whatsnew/3.6.rst:2378 msgid "" "The function call opcodes have been heavily reworked for better performance " -"and simpler implementation. The :opcode:`MAKE_FUNCTION`, :opcode:" -"`CALL_FUNCTION`, :opcode:`CALL_FUNCTION_KW` and :opcode:" -"`BUILD_MAP_UNPACK_WITH_CALL` opcodes have been modified, the new :opcode:" -"`CALL_FUNCTION_EX` and :opcode:`BUILD_TUPLE_UNPACK_WITH_CALL` have been " +"and simpler implementation. The :opcode:`MAKE_FUNCTION`, :opcode:`!" +"CALL_FUNCTION`, :opcode:`!CALL_FUNCTION_KW` and :opcode:`!" +"BUILD_MAP_UNPACK_WITH_CALL` opcodes have been modified, the new :opcode:" +"`CALL_FUNCTION_EX` and :opcode:`!BUILD_TUPLE_UNPACK_WITH_CALL` have been " "added, and ``CALL_FUNCTION_VAR``, ``CALL_FUNCTION_VAR_KW`` and " "``MAKE_CLOSURE`` opcodes have been removed. (Contributed by Demur Rumed in :" "issue:`27095`, and Serhiy Storchaka in :issue:`27213`, :issue:`28257`.)" @@ -3421,7 +3651,7 @@ msgstr "" #: ../../whatsnew/3.6.rst:2389 msgid "" -"The new :opcode:`SETUP_ANNOTATIONS` and :opcode:`STORE_ANNOTATION` opcodes " +"The new :opcode:`SETUP_ANNOTATIONS` and :opcode:`!STORE_ANNOTATION` opcodes " "have been added to support the new :term:`variable annotation` syntax. " "(Contributed by Ivan Levkivskyi in :issue:`27985`.)" msgstr "" diff --git a/whatsnew/3.7.po b/whatsnew/3.7.po index 83378f985..2edce1aef 100644 --- a/whatsnew/3.7.po +++ b/whatsnew/3.7.po @@ -1,34 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hemílio Lauro , 2021 -# Raphael Mendonça, 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# André Filipe de Assunção e Brito , 2021 -# Italo Penaforte , 2021 -# Victor Matheus Castro , 2021 -# Vinícius Muniz de Melo , 2021 -# Rafael Fontenelle , 2024 -# Adorilson Bezerra , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-29 13:04+0000\n" -"Last-Translator: Adorilson Bezerra , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -298,6 +289,30 @@ msgstr "" "Em termos de usabilidade, as anotações agora suportam referências futuras, " "tornando a seguinte sintaxe válida::" +#: ../../whatsnew/3.7.rst:158 +msgid "" +"class C:\n" +" @classmethod\n" +" def from_string(cls, source: str) -> C:\n" +" ...\n" +"\n" +" def validate_b(self, obj: B) -> bool:\n" +" ...\n" +"\n" +"class B:\n" +" ..." +msgstr "" +"class C:\n" +" @classmethod\n" +" def from_string(cls, source: str) -> C:\n" +" ...\n" +"\n" +" def validate_b(self, obj: B) -> bool:\n" +" ...\n" +"\n" +"class B:\n" +" ..." + #: ../../whatsnew/3.7.rst:169 msgid "" "Since this change breaks compatibility, the new behavior needs to be enabled " @@ -307,6 +322,10 @@ msgstr "" "habilitado por módulo no Python 3.7 usando uma importação de :mod:" "`__future__` ::" +#: ../../whatsnew/3.7.rst:172 +msgid "from __future__ import annotations" +msgstr "from __future__ import annotations" + #: ../../whatsnew/3.7.rst:174 msgid "It will become the default in Python 3.10." msgstr "Ele se tornará o padrão no Python 3.10." @@ -676,13 +695,13 @@ msgstr "" #: ../../whatsnew/3.7.rst:356 msgid "" -"`Measurements `_ show that on Linux and Windows the resolution of :func:`time." -"time_ns` is approximately 3 times better than that of :func:`time.time`." +":pep:`Measurements <0564#annex-clocks-resolution-in-python>` show that on " +"Linux and Windows the resolution of :func:`time.time_ns` is approximately 3 " +"times better than that of :func:`time.time`." msgstr "" -"`Medições `_ mostram que no Linux e no Windows a resolução de :func:`time." -"time_ns` é aproximadamente 3 vezes melhor do que :func:`time.time`." +":pep:`Medições <0564#annex-clocks-resolution-in-python>` mostram que no " +"Linux e no Windows a resolução de :func:`time.time_ns` é aproximadamente 3 " +"vezes melhor do que :func:`time.time`." #: ../../whatsnew/3.7.rst:362 msgid ":pep:`564` -- Add new time functions with nanosecond resolution" @@ -1112,6 +1131,26 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" +#: ../../whatsnew/3.7.rst:582 +msgid "" +"@dataclass\n" +"class Point:\n" +" x: float\n" +" y: float\n" +" z: float = 0.0\n" +"\n" +"p = Point(1.5, 2.5)\n" +"print(p) # produces \"Point(x=1.5, y=2.5, z=0.0)\"" +msgstr "" +"@dataclass\n" +"class Point:\n" +" x: float\n" +" y: float\n" +" z: float = 0.0\n" +"\n" +"p = Point(1.5, 2.5)\n" +"print(p) # produces \"Point(x=1.5, y=2.5, z=0.0)\"" + #: ../../whatsnew/3.7.rst:593 msgid ":pep:`557` -- Data Classes" msgstr ":pep:`557` -- Classes de dados" @@ -1130,7 +1169,7 @@ msgid "" "new ABC for access to, opening, and reading *resources* inside packages. " "Resources are roughly similar to files inside packages, but they needn't be " "actual files on the physical file system. Module loaders can provide a :" -"meth:`get_resource_reader()` function which returns a :class:`importlib.abc." +"meth:`get_resource_reader` function which returns a :class:`importlib.abc." "ResourceReader` instance to support this new API. Built-in file path " "loaders and zip file loaders both support this." msgstr "" @@ -1138,10 +1177,10 @@ msgstr "" "novo ABC para acesso, abertura e leitura de *recursos* dentro de pacotes. Os " "recursos são aproximadamente semelhantes aos arquivos dentro dos pacotes, " "mas não precisam ser arquivos reais no sistema de arquivos físico. Os " -"carregadores de módulo podem fornecer uma função :meth:" -"`get_resource_reader()` que retorna uma instância :class:`importlib.abc." -"ResourceReader` para suportar esta nova API. Carregadores embutidos de " -"caminho de arquivo e carregadores de arquivo zip oferecem suporte a isso." +"carregadores de módulo podem fornecer uma função :meth:`get_resource_reader` " +"que retorna uma instância :class:`importlib.abc.ResourceReader` para " +"suportar esta nova API. Carregadores embutidos de caminho de arquivo e " +"carregadores de arquivo zip oferecem suporte a isso." #: ../../whatsnew/3.7.rst:610 msgid "Contributed by Barry Warsaw and Brett Cannon in :issue:`32248`." @@ -1356,6 +1395,22 @@ msgstr "" "servidor estiver servindo. Os objetos :class:`~asyncio.Server` agora são " "gerenciadores de contexto assíncronos::" +#: ../../whatsnew/3.7.rst:716 +msgid "" +"srv = await loop.create_server(...)\n" +"\n" +"async with srv:\n" +" # some code\n" +"\n" +"# At this point, srv is closed and no longer accepts new connections." +msgstr "" +"srv = await loop.create_server(...)\n" +"\n" +"async with srv:\n" +" # algum código\n" +"\n" +"# Neste ponto, srv é fechado e não mais aceita novas conexões." + #: ../../whatsnew/3.7.rst:723 msgid "(Contributed by Yury Selivanov in :issue:`32662`.)" msgstr "(Contribuição de Yury Selivanov em :issue:`32662`.)" @@ -1427,6 +1482,12 @@ msgid "" "pause_reading() ` are now idempotent. " "(Contributed by Yury Selivanov in :issue:`32356`.)" msgstr "" +"O novo método :meth:`ReadTransport.is_reading() ` pode ser usado para determinar o estado de leitura do " +"transporte. Além disso, chamadas para :meth:`ReadTransport.resume_reading() " +"` e :meth:`ReadTransport." +"pause_reading() ` agora são " +"idempotentes. (Contribuição de Yury Selivanov em :issue:`32356`.)" #: ../../whatsnew/3.7.rst:760 msgid "" @@ -1734,7 +1795,7 @@ msgstr "" #: ../../whatsnew/3.7.rst:978 msgid "idlelib and IDLE" -msgstr "idlelib and IDLE" +msgstr "idlelib e IDLE" #: ../../whatsnew/3.7.rst:980 msgid "" @@ -1978,8 +2039,8 @@ msgstr "" #: ../../whatsnew/3.7.rst:1136 msgid "" -"The new :meth:`!Database.Close()` method can be used to close the :abbr:" -"`MSI` database. (Contributed by Berker Peksag in :issue:`20486`.)" +"The new :meth:`!Database.Close` method can be used to close the :abbr:`MSI` " +"database. (Contributed by Berker Peksag in :issue:`20486`.)" msgstr "" #: ../../whatsnew/3.7.rst:1142 @@ -2887,7 +2948,7 @@ msgstr "" #: ../../whatsnew/3.7.rst:1758 msgid "Build Changes" -msgstr "Alterações de compilação" +msgstr "Mudanças na construção" #: ../../whatsnew/3.7.rst:1760 msgid "" @@ -3244,9 +3305,9 @@ msgstr "" #: ../../whatsnew/3.7.rst:2019 msgid "" -"Methods :meth:`!MetaPathFinder.find_module()` (replaced by :meth:" +"Methods :meth:`!MetaPathFinder.find_module` (replaced by :meth:" "`MetaPathFinder.find_spec() `) and :" -"meth:`!PathEntryFinder.find_loader()` (replaced by :meth:`PathEntryFinder." +"meth:`!PathEntryFinder.find_loader` (replaced by :meth:`PathEntryFinder." "find_spec() `) both deprecated in " "Python 3.4 now emit :exc:`DeprecationWarning`. (Contributed by Matthias " "Bussonnier in :issue:`29576`.)" @@ -3570,6 +3631,14 @@ msgid "" "following syntax::" msgstr "" +#: ../../whatsnew/3.7.rst:2255 +msgid "" +"f(1 for x in [1],)\n" +"\n" +"class C(1 for x in [1]):\n" +" pass" +msgstr "" + #: ../../whatsnew/3.7.rst:2260 msgid "" "Python 3.7 now correctly raises a :exc:`SyntaxError`, as a generator " @@ -3726,7 +3795,7 @@ msgstr "" #: ../../whatsnew/3.7.rst:2369 msgid "" -":func:`re.sub()` now replaces empty matches adjacent to a previous non-empty " +":func:`re.sub` now replaces empty matches adjacent to a previous non-empty " "match. For example ``re.sub('x*', '-', 'abxd')`` returns now ``'-a-b--d-'`` " "instead of ``'-a-b-d-'`` (the first minus between 'b' and 'd' replaces 'x', " "and the second minus replaces an empty string between 'x' and 'd')." @@ -3812,7 +3881,7 @@ msgstr "" #: ../../whatsnew/3.7.rst:2428 msgid "" -":meth:`ast.literal_eval()` is now stricter. Addition and subtraction of " +":meth:`ast.literal_eval` is now stricter. Addition and subtraction of " "arbitrary numbers are no longer allowed. (Contributed by Serhiy Storchaka " "in :issue:`31778`.)" msgstr "" @@ -3882,14 +3951,14 @@ msgstr "Alterações de bytecode do CPython" #: ../../whatsnew/3.7.rst:2479 msgid "" -"There are two new opcodes: :opcode:`LOAD_METHOD` and :opcode:`CALL_METHOD`. " +"There are two new opcodes: :opcode:`LOAD_METHOD` and :opcode:`!CALL_METHOD`. " "(Contributed by Yury Selivanov and INADA Naoki in :issue:`26110`.)" msgstr "" #: ../../whatsnew/3.7.rst:2482 msgid "" -"The :opcode:`STORE_ANNOTATION` opcode has been removed. (Contributed by Mark " -"Shannon in :issue:`32550`.)" +"The :opcode:`!STORE_ANNOTATION` opcode has been removed. (Contributed by " +"Mark Shannon in :issue:`32550`.)" msgstr "" #: ../../whatsnew/3.7.rst:2489 diff --git a/whatsnew/3.8.po b/whatsnew/3.8.po index 2ce88c0c8..e0eb56e0f 100644 --- a/whatsnew/3.8.po +++ b/whatsnew/3.8.po @@ -1,33 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# André Filipe de Assunção e Brito , 2021 -# Marco Rougeth , 2021 -# Italo Penaforte , 2021 -# Victor Matheus Castro , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# Vinícius Muniz de Melo , 2021 -# Vitor Buxbaum Orlandi, 2023 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-09 16:36+0000\n" -"PO-Revision-Date: 2021-06-29 13:04+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -86,6 +78,14 @@ msgstr "" "Neste exemplo, a expressão de atribuição ajuda a evitar a chamada de :func:" "`len` duas vezes::" +#: ../../whatsnew/3.8.rst:85 +msgid "" +"if (n := len(a)) > 10:\n" +" print(f\"List is too long ({n} elements, expected <= 10)\")" +msgstr "" +"if (n := len(a)) > 10:\n" +" print(f\"List is too long ({n} elements, expected <= 10)\")" + #: ../../whatsnew/3.8.rst:88 msgid "" "A similar benefit arises during regular expression matching where match " @@ -97,6 +97,16 @@ msgstr "" "uma vez para testar se ocorreu uma correspondência e outra para extrair um " "subgrupo::" +#: ../../whatsnew/3.8.rst:92 +msgid "" +"discount = 0.0\n" +"if (mo := re.search(r'(\\d+)% discount', advertisement)):\n" +" discount = float(mo.group(1)) / 100.0" +msgstr "" +"discount = 0.0\n" +"if (mo := re.search(r'(\\d+)% discount', advertisement)):\n" +" discount = float(mo.group(1)) / 100.0" + #: ../../whatsnew/3.8.rst:96 msgid "" "The operator is also useful with while-loops that compute a value to test " @@ -107,6 +117,16 @@ msgstr "" "finalização do loop e, em seguida, precisam desse mesmo valor novamente no " "corpo do loop::" +#: ../../whatsnew/3.8.rst:100 +msgid "" +"# Loop over fixed length blocks\n" +"while (block := f.read(256)) != '':\n" +" process(block)" +msgstr "" +"# Loop over fixed length blocks\n" +"while (block := f.read(256)) != '':\n" +" process(block)" + #: ../../whatsnew/3.8.rst:104 msgid "" "Another motivating use case arises in list comprehensions where a value " @@ -116,6 +136,14 @@ msgstr "" "calculado em uma condição de filtragem também é necessário no corpo da " "expressão::" +#: ../../whatsnew/3.8.rst:108 +msgid "" +"[clean_name.title() for name in names\n" +" if (clean_name := normalize('NFC', name)) in allowed_names]" +msgstr "" +"[clean_name.title() for name in names\n" +" if (clean_name := normalize('NFC', name)) in allowed_names]" + #: ../../whatsnew/3.8.rst:111 msgid "" "Try to limit use of the walrus operator to clean cases that reduce " @@ -160,14 +188,34 @@ msgstr "" "enquanto *c* ou *d* podem ser posicionais ou nomeados e *e* ou *f* são " "obrigatoriamente nomeados::" +#: ../../whatsnew/3.8.rst:132 +msgid "" +"def f(a, b, /, c, d, *, e, f):\n" +" print(a, b, c, d, e, f)" +msgstr "" +"def f(a, b, /, c, d, *, e, f):\n" +" print(a, b, c, d, e, f)" + #: ../../whatsnew/3.8.rst:135 msgid "The following is a valid call::" msgstr "A seguir, uma chamada válida::" +#: ../../whatsnew/3.8.rst:137 +msgid "f(10, 20, 30, d=40, e=50, f=60)" +msgstr "f(10, 20, 30, d=40, e=50, f=60)" + #: ../../whatsnew/3.8.rst:139 msgid "However, these are invalid calls::" msgstr "Porém, essas chamadas são inválidas::" +#: ../../whatsnew/3.8.rst:141 +msgid "" +"f(10, b=20, c=30, d=40, e=50, f=60) # b cannot be a keyword argument\n" +"f(10, 20, 30, 40, 50, f=60) # e must be a keyword argument" +msgstr "" +"f(10, b=20, c=30, d=40, e=50, f=60) # b não pode ser um argumento nomeado\n" +"f(10, 20, 30, 40, 50, f=60) # e deve ser um argumento nomeado" + #: ../../whatsnew/3.8.rst:144 msgid "" "One use case for this notation is that it allows pure Python functions to " @@ -179,6 +227,16 @@ msgstr "" "existentes. Por exemplo, a função embutida :func:`divmod` não aceita " "argumentos nomeados::" +#: ../../whatsnew/3.8.rst:148 +msgid "" +"def divmod(a, b, /):\n" +" \"Emulate the built in divmod() function\"\n" +" return (a // b, a % b)" +msgstr "" +"def divmod(a, b, /):\n" +" \"Emula a função embutida divmod()\"\n" +" return (a // b, a % b)" + #: ../../whatsnew/3.8.rst:152 msgid "" "Another use case is to preclude keyword arguments when the parameter name is " @@ -189,6 +247,11 @@ msgstr "" "não for útil. Por exemplo, a função embutida :func:`len` possui a assinatura " "``len(obj, /)``. Isso exclui chamadas estranhas, como::" +#: ../../whatsnew/3.8.rst:156 +msgid "len(obj='hello') # The \"obj\" keyword argument impairs readability" +msgstr "" +"len(obj='hello') # O argumento nomeado \"obj\" prejudica a legibilidade" + #: ../../whatsnew/3.8.rst:158 msgid "" "A further benefit of marking a parameter as positional-only is that it " @@ -203,6 +266,14 @@ msgstr "" "nome do parâmetro *dist* pode ser alterado no futuro. Isso foi possível com " "a seguinte especificação de função::" +#: ../../whatsnew/3.8.rst:164 +msgid "" +"def quantiles(dist, /, *, n=4, method='exclusive')\n" +" ..." +msgstr "" +"def quantiles(dist, /, *, n=4, method='exclusive')\n" +" ..." + #: ../../whatsnew/3.8.rst:167 msgid "" "Since the parameters to the left of ``/`` are not exposed as possible " @@ -212,6 +283,20 @@ msgstr "" "palavras-chave, os nomes dos parâmetros permanecem disponíveis para uso em " "``**kwargs``::" +#: ../../whatsnew/3.8.rst:170 +msgid "" +">>> def f(a, b, /, **kwargs):\n" +"... print(a, b, kwargs)\n" +"...\n" +">>> f(10, 20, a=1, b=2, c=3) # a and b are used in two ways\n" +"10 20 {'a': 1, 'b': 2, 'c': 3}" +msgstr "" +">>> def f(a, b, /, **kwargs):\n" +"... print(a, b, kwargs)\n" +"...\n" +">>> f(10, 20, a=1, b=2, c=3) # a e b são usados de duas formas\n" +"10 20 {'a': 1, 'b': 2, 'c': 3}" + #: ../../whatsnew/3.8.rst:176 msgid "" "This greatly simplifies the implementation of functions and methods that " @@ -222,6 +307,18 @@ msgstr "" "aceitar argumentos nomeados arbitrários. Por exemplo, aqui está um trecho do " "código no módulo :mod:`collections`::" +#: ../../whatsnew/3.8.rst:180 +msgid "" +"class Counter(dict):\n" +"\n" +" def __init__(self, iterable=None, /, **kwds):\n" +" # Note \"iterable\" is a possible keyword argument" +msgstr "" +"class Counter(dict):\n" +"\n" +" def __init__(self, iterable=None, /, **kwds):\n" +" # Observe que \"iterable\" é um possível argumento nomeado" + #: ../../whatsnew/3.8.rst:185 msgid "See :pep:`570` for a full description." msgstr "Consulte a :pep:`570` para uma descrição completa." @@ -383,6 +480,16 @@ msgstr "" "O habitual :ref:`f-string especificadores de formato ` permite " "mais controle sobre como o resultado da expressão é exibido::" +#: ../../whatsnew/3.8.rst:270 +msgid "" +">>> delta = date.today() - member_since\n" +">>> f'{user=!s} {delta.days=:,d}'\n" +"'user=eric_idle delta.days=16,075'" +msgstr "" +">>> delta = date.today() - member_since\n" +">>> f'{user=!s} {delta.days=:,d}'\n" +"'user=eric_idle delta.days=16,075'" + #: ../../whatsnew/3.8.rst:274 msgid "" "The ``=`` specifier will display the whole expression so that calculations " @@ -391,6 +498,14 @@ msgstr "" "O especificador ``=`` exibirá toda a expressão para que os cálculos possam " "ser mostrados::" +#: ../../whatsnew/3.8.rst:277 +msgid "" +">>> print(f'{theta=} {cos(radians(theta))=:.3f}')\n" +"theta=30 cos(radians(theta))=0.866" +msgstr "" +">>> print(f'{theta=} {cos(radians(theta))=:.3f}')\n" +"theta=30 cos(radians(theta))=0.866" + #: ../../whatsnew/3.8.rst:280 msgid "(Contributed by Eric V. Smith and Larry Hastings in :issue:`36817`.)" msgstr "(Contribuição de Eric V. Smith e Larry Hastings em :issue:`36817`.)" @@ -712,6 +827,18 @@ msgstr "" "Adicionado suporte a escapes :samp:`\\\\N\\\\{{name}\\\\}` em :mod:" "`expressões regulares `::" +#: ../../whatsnew/3.8.rst:409 +msgid "" +">>> notice = 'Copyright © 2019'\n" +">>> copyright_year_pattern = re.compile(r'\\N{copyright sign}\\s*(\\d{4})')\n" +">>> int(copyright_year_pattern.search(notice).group(1))\n" +"2019" +msgstr "" +">>> notice = 'Copyright © 2019'\n" +">>> copyright_year_pattern = re.compile(r'\\N{copyright sign}\\s*(\\d{4})')\n" +">>> int(copyright_year_pattern.search(notice).group(1))\n" +"2019" + #: ../../whatsnew/3.8.rst:414 msgid "" "(Contributed by Jonathan Eunice and Serhiy Storchaka in :issue:`30688`.)" @@ -750,6 +877,22 @@ msgstr "" "e :keyword:`return` não requer mais parênteses. Isso traz a sintaxe *yield* " "e *return* uma melhor concordância com a sintaxe de atribuição normal::" +#: ../../whatsnew/3.8.rst:430 +msgid "" +">>> def parse(family):\n" +" lastname, *members = family.split()\n" +" return lastname.upper(), *members\n" +"\n" +">>> parse('simpsons homer marge bart lisa maggie')\n" +"('SIMPSONS', 'homer', 'marge', 'bart', 'lisa', 'maggie')" +msgstr "" +">>> def parse(family):\n" +" lastname, *members = family.split()\n" +" return lastname.upper(), *members\n" +"\n" +">>> parse('simpsons homer marge bart lisa maggie')\n" +"('SIMPSONS', 'homer', 'marge', 'bart', 'lisa', 'maggie')" + #: ../../whatsnew/3.8.rst:437 msgid "(Contributed by David Cuthbert and Jordan Chapman in :issue:`32117`.)" msgstr "(Contribuição de David Cuthbert e Jordan Chapman em :issue:`32117`.)" @@ -823,6 +966,28 @@ msgstr "" "Aqui está um exemplo que altera a função :func:`Statistics.mean` para " "impedir que o parâmetro *data* seja usado como argumento nomeado::" +#: ../../whatsnew/3.8.rst:470 +msgid "" +">>> from statistics import mean\n" +">>> mean(data=[10, 20, 90])\n" +"40\n" +">>> mean.__code__ = mean.__code__.replace(co_posonlyargcount=1)\n" +">>> mean(data=[10, 20, 90])\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: mean() got some positional-only arguments passed as keyword " +"arguments: 'data'" +msgstr "" +">>> from statistics import mean\n" +">>> mean(data=[10, 20, 90])\n" +"40\n" +">>> mean.__code__ = mean.__code__.replace(co_posonlyargcount=1)\n" +">>> mean(data=[10, 20, 90])\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: mean() got some positional-only arguments passed as keyword " +"arguments: 'data'" + #: ../../whatsnew/3.8.rst:479 msgid "(Contributed by Victor Stinner in :issue:`37032`.)" msgstr "(Contribuição de Victor Stinner em :issue:`37032`.)" @@ -845,6 +1010,18 @@ msgstr "" "multiplicativo modular `_ de 38 módulo 137, escreva::" +#: ../../whatsnew/3.8.rst:490 +msgid "" +">>> pow(38, -1, 137)\n" +"119\n" +">>> 119 * 38 % 137\n" +"1" +msgstr "" +">>> pow(38, -1, 137)\n" +"119\n" +">>> 119 * 38 % 137\n" +"1" + #: ../../whatsnew/3.8.rst:495 msgid "" "Modular inverses arise in the solution of `linear Diophantine equations " @@ -869,6 +1046,32 @@ msgstr "" "As compreensões de dict foram sincronizadas com literais de dict, para que a " "chave seja computada primeiro e o valor em segundo::" +#: ../../whatsnew/3.8.rst:510 +msgid "" +">>> # Dict comprehension\n" +">>> cast = {input('role? '): input('actor? ') for i in range(2)}\n" +"role? King Arthur\n" +"actor? Chapman\n" +"role? Black Knight\n" +"actor? Cleese\n" +"\n" +">>> # Dict literal\n" +">>> cast = {input('role? '): input('actor? ')}\n" +"role? Sir Robin\n" +"actor? Eric Idle" +msgstr "" +">>> # Compreensão de dicionário\n" +">>> cast = {input('role? '): input('actor? ') for i in range(2)}\n" +"role? King Arthur\n" +"actor? Chapman\n" +"role? Black Knight\n" +"actor? Cleese\n" +"\n" +">>> # Literal de dicionário\n" +">>> cast = {input('role? '): input('actor? ')}\n" +"role? Sir Robin\n" +"actor? Eric Idle" + #: ../../whatsnew/3.8.rst:522 msgid "" "The guaranteed execution order is helpful with assignment expressions " @@ -879,6 +1082,20 @@ msgstr "" "variáveis atribuídas na expressão de chave estarão disponíveis na expressão " "de valor::" +#: ../../whatsnew/3.8.rst:526 +msgid "" +">>> names = ['Martin von Löwis', 'Łukasz Langa', 'Walter Dörwald']\n" +">>> {(n := normalize('NFC', name)).casefold() : n for name in names}\n" +"{'martin von löwis': 'Martin von Löwis',\n" +" 'łukasz langa': 'Łukasz Langa',\n" +" 'walter dörwald': 'Walter Dörwald'}" +msgstr "" +">>> names = ['Martin von Löwis', 'Łukasz Langa', 'Walter Dörwald']\n" +">>> {(n := normalize('NFC', name)).casefold() : n for name in names}\n" +"{'martin von löwis': 'Martin von Löwis',\n" +" 'łukasz langa': 'Łukasz Langa',\n" +" 'walter dörwald': 'Walter Dörwald'}" + #: ../../whatsnew/3.8.rst:532 msgid "(Contributed by Jörn Heissler in :issue:`35224`.)" msgstr "(Contribuição de Jörn Heissler em :issue:`35224`.)" @@ -916,6 +1133,38 @@ msgstr "" "o número da versão de um pacote instalado, a lista de pontos de entrada e " "muito mais::" +#: ../../whatsnew/3.8.rst:549 +msgid "" +">>> # Note following example requires that the popular \"requests\"\n" +">>> # package has been installed.\n" +">>>\n" +">>> from importlib.metadata import version, requires, files\n" +">>> version('requests')\n" +"'2.22.0'\n" +">>> list(requires('requests'))\n" +"['chardet (<3.1.0,>=3.0.2)']\n" +">>> list(files('requests'))[:5]\n" +"[PackagePath('requests-2.22.0.dist-info/INSTALLER'),\n" +" PackagePath('requests-2.22.0.dist-info/LICENSE'),\n" +" PackagePath('requests-2.22.0.dist-info/METADATA'),\n" +" PackagePath('requests-2.22.0.dist-info/RECORD'),\n" +" PackagePath('requests-2.22.0.dist-info/WHEEL')]" +msgstr "" +">>> # Note o exemplo a seguir requer que o pacote popular\n" +">>> # \"requests\" tenha sido instalado.\n" +">>>\n" +">>> from importlib.metadata import version, requires, files\n" +">>> version('requests')\n" +"'2.22.0'\n" +">>> list(requires('requests'))\n" +"['chardet (<3.1.0,>=3.0.2)']\n" +">>> list(files('requests'))[:5]\n" +"[PackagePath('requests-2.22.0.dist-info/INSTALLER'),\n" +" PackagePath('requests-2.22.0.dist-info/LICENSE'),\n" +" PackagePath('requests-2.22.0.dist-info/METADATA'),\n" +" PackagePath('requests-2.22.0.dist-info/RECORD'),\n" +" PackagePath('requests-2.22.0.dist-info/WHEEL')]" + #: ../../whatsnew/3.8.rst:564 msgid "(Contributed by Barry Warsaw and Jason R. Coombs in :issue:`34632`.)" msgstr "(Contribuição de Barry Warsaw e Jason R. Coombs em :issue:`34632`.)" @@ -998,10 +1247,58 @@ msgstr "" "pode ser usada para executar uma :term:`corrotina ` e retornar o " "resultado enquanto gerencia automaticamente o loop de eventos. Por exemplo::" +#: ../../whatsnew/3.8.rst:604 +msgid "" +"import asyncio\n" +"\n" +"async def main():\n" +" await asyncio.sleep(0)\n" +" return 42\n" +"\n" +"asyncio.run(main())" +msgstr "" +"import asyncio\n" +"\n" +"async def main():\n" +" await asyncio.sleep(0)\n" +" return 42\n" +"\n" +"asyncio.run(main())" + #: ../../whatsnew/3.8.rst:612 msgid "This is *roughly* equivalent to::" msgstr "Isso é *aproximadamente* equivalente a::" +#: ../../whatsnew/3.8.rst:614 +msgid "" +"import asyncio\n" +"\n" +"async def main():\n" +" await asyncio.sleep(0)\n" +" return 42\n" +"\n" +"loop = asyncio.new_event_loop()\n" +"asyncio.set_event_loop(loop)\n" +"try:\n" +" loop.run_until_complete(main())\n" +"finally:\n" +" asyncio.set_event_loop(None)\n" +" loop.close()" +msgstr "" +"import asyncio\n" +"\n" +"async def main():\n" +" await asyncio.sleep(0)\n" +" return 42\n" +"\n" +"loop = asyncio.new_event_loop()\n" +"asyncio.set_event_loop(loop)\n" +"try:\n" +" loop.run_until_complete(main())\n" +"finally:\n" +" asyncio.set_event_loop(None)\n" +" loop.close()" + #: ../../whatsnew/3.8.rst:629 msgid "" "The actual implementation is significantly more complex. Thus, :func:" @@ -1026,6 +1323,26 @@ msgstr "" "keyword:`await`. Não é mais necessário chamar diretamente ``asyncio.run()``, " "o que geraria um novo loop de evento a cada chamada:" +#: ../../whatsnew/3.8.rst:639 +msgid "" +"$ python -m asyncio\n" +"asyncio REPL 3.8.0\n" +"Use \"await\" directly instead of \"asyncio.run()\".\n" +"Type \"help\", \"copyright\", \"credits\" or \"license\" for more " +"information.\n" +">>> import asyncio\n" +">>> await asyncio.sleep(10, result='hello')\n" +"hello" +msgstr "" +"$ python -m asyncio\n" +"asyncio REPL 3.8.0\n" +"Use \"await\" directly instead of \"asyncio.run()\".\n" +"Type \"help\", \"copyright\", \"credits\" or \"license\" for more " +"information.\n" +">>> import asyncio\n" +">>> await asyncio.sleep(10, result='hello')\n" +"hello" + #: ../../whatsnew/3.8.rst:649 msgid "(Contributed by Yury Selivanov in :issue:`37028`.)" msgstr "(Contribuição de Yury Selivanov em :issue:`37028`.)" @@ -1165,6 +1482,20 @@ msgstr "" "A classe :class:`cProfile.Profile ` agora pode ser usada " "como um gerenciador de contexto. Perfile um bloco de código executando::" +#: ../../whatsnew/3.8.rst:716 +msgid "" +"import cProfile\n" +"\n" +"with cProfile.Profile() as profiler:\n" +" # code to be profiled\n" +" ..." +msgstr "" +"import cProfile\n" +"\n" +"with cProfile.Profile() as profiler:\n" +" # código as ser analisada o desempenho\n" +" ..." + #: ../../whatsnew/3.8.rst:722 msgid "(Contributed by Scott Sanderson in :issue:`29235`.)" msgstr "(Contribuição de Scott Sanderson em :issue:`29235`.)" @@ -1253,6 +1584,24 @@ msgstr "" "não como uma função retornando um decorador. Portanto, agora ambos são " "suportados::" +#: ../../whatsnew/3.8.rst:769 +msgid "" +"@lru_cache\n" +"def f(x):\n" +" ...\n" +"\n" +"@lru_cache(maxsize=256)\n" +"def f(x):\n" +" ..." +msgstr "" +"@lru_cache\n" +"def f(x):\n" +" ...\n" +"\n" +"@lru_cache(maxsize=256)\n" +"def f(x):\n" +" ..." + #: ../../whatsnew/3.8.rst:777 msgid "(Contributed by Raymond Hettinger in :issue:`36772`.)" msgstr "(Contribuição de Raymond Hettinger em :issue:`36772`.)" @@ -1266,6 +1615,30 @@ msgstr "" "propriedades computadas armazenadas em cache durante toda a vida útil da " "instância. ::" +#: ../../whatsnew/3.8.rst:782 +msgid "" +"import functools\n" +"import statistics\n" +"\n" +"class Dataset:\n" +" def __init__(self, sequence_of_numbers):\n" +" self.data = sequence_of_numbers\n" +"\n" +" @functools.cached_property\n" +" def variance(self):\n" +" return statistics.variance(self.data)" +msgstr "" +"import functools\n" +"import statistics\n" +"\n" +"class Dataset:\n" +" def __init__(self, sequence_of_numbers):\n" +" self.data = sequence_of_numbers\n" +"\n" +" @functools.cached_property\n" +" def variance(self):\n" +" return statistics.variance(self.data)" + #: ../../whatsnew/3.8.rst:793 msgid "(Contributed by Carl Meyer in :issue:`21145`)" msgstr "(Contribuição de Carl Meyer em :issue:`21145`)" @@ -1280,6 +1653,44 @@ msgstr "" "converte métodos em :term:`funções genéricas ` usando :" "term:`despacho único `::" +#: ../../whatsnew/3.8.rst:800 +msgid "" +"from functools import singledispatchmethod\n" +"from contextlib import suppress\n" +"\n" +"class TaskManager:\n" +"\n" +" def __init__(self, tasks):\n" +" self.tasks = list(tasks)\n" +"\n" +" @singledispatchmethod\n" +" def discard(self, value):\n" +" with suppress(ValueError):\n" +" self.tasks.remove(value)\n" +"\n" +" @discard.register(list)\n" +" def _(self, tasks):\n" +" targets = set(tasks)\n" +" self.tasks = [x for x in self.tasks if x not in targets]" +msgstr "" +"from functools import singledispatchmethod\n" +"from contextlib import suppress\n" +"\n" +"class TaskManager:\n" +"\n" +" def __init__(self, tasks):\n" +" self.tasks = list(tasks)\n" +"\n" +" @singledispatchmethod\n" +" def discard(self, value):\n" +" with suppress(ValueError):\n" +" self.tasks.remove(value)\n" +"\n" +" @discard.register(list)\n" +" def _(self, tasks):\n" +" targets = set(tasks)\n" +" self.tasks = [x for x in self.tasks if x not in targets]" + #: ../../whatsnew/3.8.rst:818 msgid "(Contributed by Ethan Smith in :issue:`32380`)" msgstr "(Contribuição de Ethan Smith em :issue:`32380`)" @@ -1448,6 +1859,22 @@ msgstr "" "docstrings. Isso fornece opções de documentação semelhantes às que já temos " "para :func:`property`, :func:`classmethod` e :func:`staticmethod`::" +#: ../../whatsnew/3.8.rst:897 +msgid "" +"class AudioClip:\n" +" __slots__ = {'bit_rate': 'expressed in kilohertz to one decimal place',\n" +" 'duration': 'in seconds, rounded up to an integer'}\n" +" def __init__(self, bit_rate, duration):\n" +" self.bit_rate = round(bit_rate / 1000.0, 1)\n" +" self.duration = ceil(duration)" +msgstr "" +"class AudioClip:\n" +" __slots__ = {'bit_rate': 'expressed in kilohertz to one decimal place',\n" +" 'duration': 'in seconds, rounded up to an integer'}\n" +" def __init__(self, bit_rate, duration):\n" +" self.bit_rate = round(bit_rate / 1000.0, 1)\n" +" self.duration = ceil(duration)" + #: ../../whatsnew/3.8.rst:904 msgid "(Contributed by Raymond Hettinger in :issue:`36326`.)" msgstr "(Contribuição de Raymond Hettinger em :issue:`36326`.)" @@ -1481,6 +1908,16 @@ msgstr "" "A função :func:`itertools.accumulate` adicionou uma opção de argumento " "nomeado *initial* para especificar um valor inicial::" +#: ../../whatsnew/3.8.rst:922 +msgid "" +">>> from itertools import accumulate\n" +">>> list(accumulate([10, 5, 30, 15], initial=1000))\n" +"[1000, 1010, 1015, 1045, 1060]" +msgstr "" +">>> from itertools import accumulate\n" +">>> list(accumulate([10, 5, 30, 15], initial=1000))\n" +"[1000, 1010, 1015, 1045, 1060]" + #: ../../whatsnew/3.8.rst:926 msgid "(Contributed by Lisa Roach in :issue:`34659`.)" msgstr "(Contribuído por Lisa Roach em :issue:`34659`.)" @@ -1503,12 +1940,12 @@ msgstr "logging" #: ../../whatsnew/3.8.rst:939 msgid "" -"Added a *force* keyword argument to :func:`logging.basicConfig()` When set " -"to true, any existing handlers attached to the root logger are removed and " +"Added a *force* keyword argument to :func:`logging.basicConfig`. When set to " +"true, any existing handlers attached to the root logger are removed and " "closed before carrying out the configuration specified by the other " "arguments." msgstr "" -"Adicionado um argumento nomeado *force* em :func:`logging.basicConfig()` " +"Adicionado um argumento nomeado *force* a :func:`logging.basicConfig`. " "Quando definido como true, qualquer manipulador existente anexado ao logger " "raiz é removido e fechado antes de executar a configuração especificada " "pelos outros argumentos." @@ -1567,6 +2004,18 @@ msgstr "" "que retorna o produto de um valor 'start' (padrão: 1) vezes uma iterável de " "números::" +#: ../../whatsnew/3.8.rst:968 +msgid "" +">>> prior = 0.8\n" +">>> likelihoods = [0.625, 0.84, 0.30]\n" +">>> math.prod(likelihoods, start=prior)\n" +"0.126" +msgstr "" +">>> prior = 0.8\n" +">>> likelihoods = [0.625, 0.84, 0.30]\n" +">>> math.prod(likelihoods, start=prior)\n" +"0.126" + #: ../../whatsnew/3.8.rst:973 msgid "(Contributed by Pablo Galindo in :issue:`35606`.)" msgstr "(Contribuição de Pablo Galindo em :issue:`35606`.)" @@ -1579,6 +2028,18 @@ msgstr "" "Adicionadas duas novas funções combinatórias :func:`math.perm` e :func:`math." "comb`::" +#: ../../whatsnew/3.8.rst:977 +msgid "" +">>> math.perm(10, 3) # Permutations of 10 things taken 3 at a time\n" +"720\n" +">>> math.comb(10, 3) # Combinations of 10 things taken 3 at a time\n" +"120" +msgstr "" +">>> math.perm(10, 3) # Permutações de 10 coisas, 3 por vez\n" +"720\n" +">>> math.comb(10, 3) # Combinações de 10 coisas, 3 por vez\n" +"120" + #: ../../whatsnew/3.8.rst:982 msgid "" "(Contributed by Yash Aggarwal, Keller Fuchs, Serhiy Storchaka, and Raymond " @@ -1599,6 +2060,22 @@ msgstr "" "números inteiros arbitrariamente grandes. É mais rápido que " "``floor(sqrt(n))``, mas mais lento que :func:`math.sqrt`::" +#: ../../whatsnew/3.8.rst:990 +msgid "" +">>> r = 650320427\n" +">>> s = r ** 2\n" +">>> isqrt(s - 1) # correct\n" +"650320426\n" +">>> floor(sqrt(s - 1)) # incorrect\n" +"650320427" +msgstr "" +">>> r = 650320427\n" +">>> s = r ** 2\n" +">>> isqrt(s - 1) # correto\n" +"650320426\n" +">>> floor(sqrt(s - 1)) # incorreto\n" +"650320427" + #: ../../whatsnew/3.8.rst:997 msgid "(Contributed by Mark Dickinson in :issue:`36887`.)" msgstr "(Contribuição de Mark Dickinson em :issue:`36887`.)" @@ -1769,34 +2246,33 @@ msgstr "pathlib" #: ../../whatsnew/3.8.rst:1079 msgid "" ":mod:`pathlib.Path` methods that return a boolean result like :meth:" -"`~pathlib.Path.exists()`, :meth:`~pathlib.Path.is_dir()`, :meth:`~pathlib." -"Path.is_file()`, :meth:`~pathlib.Path.is_mount()`, :meth:`~pathlib.Path." -"is_symlink()`, :meth:`~pathlib.Path.is_block_device()`, :meth:`~pathlib.Path." -"is_char_device()`, :meth:`~pathlib.Path.is_fifo()`, :meth:`~pathlib.Path." -"is_socket()` now return ``False`` instead of raising :exc:`ValueError` or " -"its subclass :exc:`UnicodeEncodeError` for paths that contain characters " -"unrepresentable at the OS level. (Contributed by Serhiy Storchaka in :issue:" +"`~pathlib.Path.exists`, :meth:`~pathlib.Path.is_dir`, :meth:`~pathlib.Path." +"is_file`, :meth:`~pathlib.Path.is_mount`, :meth:`~pathlib.Path.is_symlink`, :" +"meth:`~pathlib.Path.is_block_device`, :meth:`~pathlib.Path.is_char_device`, :" +"meth:`~pathlib.Path.is_fifo`, :meth:`~pathlib.Path.is_socket` now return " +"``False`` instead of raising :exc:`ValueError` or its subclass :exc:" +"`UnicodeEncodeError` for paths that contain characters unrepresentable at " +"the OS level. (Contributed by Serhiy Storchaka in :issue:`33721`.)" +msgstr "" +"Os métodos :mod:`pathlib.Path` que retornam um resultado booleano como :meth:" +"`~pathlib.Path.exists`, :meth:`~pathlib.Path.is_dir`, :meth:`~pathlib.Path." +"is_file`, :meth:`~pathlib.Path.is_mount`, :meth:`~pathlib.Path.is_symlink`, :" +"meth:`~pathlib.Path.is_block_device`, :meth:`~pathlib.Path.is_char_device`, :" +"meth:`~pathlib.Path.is_fifo`, :meth:`~pathlib.Path.is_socket` agora retornam " +"``False`` em vez de levantar :exc:`ValueError` ou sua subclasse :exc:" +"`UnicodeEncodeError` para caminhos que contêm caracteres não representáveis " +"no nível do sistema operacional. (Contribuição de Serhiy Storchaka em :issue:" "`33721`.)" -msgstr "" -":mod:`pathlib.Path` métodos que retornam um resultado booleano como :meth:" -"`~pathlib.Path.exists()`, :meth:`~pathlib.Path.is_dir()`, :meth:`~pathlib." -"Path.is_file()`, :meth:`~pathlib.Path.is_mount()`, :meth:`~pathlib.Path." -"is_symlink()`, :meth:`~pathlib.Path.is_block_device()`, :meth:`~pathlib.Path." -"is_char_device()`, :meth:`~pathlib.Path.is_fifo()`, :meth:`~pathlib.Path." -"is_socket()` agora retorna ``False`` ao invés de levantar :exc:`ValueError` " -"ou sua subclasse :exc:`UnicodeEncodeError` para caminhos que contêm " -"caracteres não representáveis no nível do SO. (Contribuição de Serhiy " -"Storchaka em :issue:`33721`.)" #: ../../whatsnew/3.8.rst:1089 msgid "" -"Added :meth:`!pathlib.Path.link_to()` which creates a hard link pointing to " -"a path. (Contributed by Joannah Nanjekye in :issue:`26978`) Note that " +"Added :meth:`!pathlib.Path.link_to` which creates a hard link pointing to a " +"path. (Contributed by Joannah Nanjekye in :issue:`26978`) Note that " "``link_to`` was deprecated in 3.10 and removed in 3.12 in favor of a " "``hardlink_to`` method added in 3.10 which matches the semantics of the " "existing ``symlink_to`` method." msgstr "" -"Adicionado :meth:`!pathlib.Path.link_to()` que cria um link físico apontando " +"Adicionado :meth:`!pathlib.Path.link_to` que cria um link físico apontando " "para um caminho. (Contribuição de Joannah Nanjekye em :issue:`26978`) " "Observe que ``link_to`` foi descontinuado na versão 3.10 e removido na " "versão 3.12 em favor de um método ``hardlink_to`` adicionado na versão 3.10 " @@ -1860,6 +2336,32 @@ msgstr "" "como :func:`pprint.pprint`, mas com *sort_dicts* padronizando como " "``False``::" +#: ../../whatsnew/3.8.rst:1126 +msgid "" +">>> from pprint import pprint, pp\n" +">>> d = dict(source='input.txt', operation='filter', destination='output." +"txt')\n" +">>> pp(d, width=40) # Original order\n" +"{'source': 'input.txt',\n" +" 'operation': 'filter',\n" +" 'destination': 'output.txt'}\n" +">>> pprint(d, width=40) # Keys sorted alphabetically\n" +"{'destination': 'output.txt',\n" +" 'operation': 'filter',\n" +" 'source': 'input.txt'}" +msgstr "" +">>> from pprint import pprint, pp\n" +">>> d = dict(source='input.txt', operation='filter', destination='output." +"txt')\n" +">>> pp(d, width=40) # Ordem original\n" +"{'source': 'input.txt',\n" +" 'operation': 'filter',\n" +" 'destination': 'output.txt'}\n" +">>> pprint(d, width=40) # Chaves ordenadas alfabeticamente\n" +"{'destination': 'output.txt',\n" +" 'operation': 'filter',\n" +" 'source': 'input.txt'}" + #: ../../whatsnew/3.8.rst:1137 msgid "(Contributed by Rémi Lapeyre in :issue:`30670`.)" msgstr "(Contribuição de Rémi Lapeyre em :issue:`30670`.)" @@ -1928,26 +2430,25 @@ msgstr "socket" #: ../../whatsnew/3.8.rst:1173 msgid "" -"Added :meth:`~socket.create_server()` and :meth:`~socket." -"has_dualstack_ipv6()` convenience functions to automate the necessary tasks " -"usually involved when creating a server socket, including accepting both " -"IPv4 and IPv6 connections on the same socket. (Contributed by Giampaolo " -"Rodolà in :issue:`17561`.)" +"Added :meth:`~socket.create_server` and :meth:`~socket.has_dualstack_ipv6` " +"convenience functions to automate the necessary tasks usually involved when " +"creating a server socket, including accepting both IPv4 and IPv6 connections " +"on the same socket. (Contributed by Giampaolo Rodolà in :issue:`17561`.)" msgstr "" -"Adicionadas as funções de conveniência :meth:`~socket.create_server()` e :" -"meth:`~socket.has_dualstack_ipv6()` para automatizar as tarefas necessárias " +"Adicionadas as funções de conveniência :meth:`~socket.create_server` e :meth:" +"`~socket.has_dualstack_ipv6` para automatizar as tarefas necessárias " "geralmente envolvidas na criação de um soquete de servidor, incluindo a " "aceitação de conexões IPv4 e IPv6 no mesmo soquete. (Contribuição de " "Giampaolo Rodolà em :issue:`17561`.)" #: ../../whatsnew/3.8.rst:1178 msgid "" -"The :func:`socket.if_nameindex()`, :func:`socket.if_nametoindex()`, and :" -"func:`socket.if_indextoname()` functions have been implemented on Windows. " +"The :func:`socket.if_nameindex`, :func:`socket.if_nametoindex`, and :func:" +"`socket.if_indextoname` functions have been implemented on Windows. " "(Contributed by Zackery Spytz in :issue:`37007`.)" msgstr "" -"As funções :func:`socket.if_nameindex()`, :func:`socket.if_nametoindex()` e :" -"func:`socket.if_indextoname()` foram agora implementadas no Windows. " +"As funções :func:`socket.if_nameindex`, :func:`socket.if_nametoindex` e :" +"func:`socket.if_indextoname` foram agora implementadas no Windows. " "(Contribuição de Zackery Spytz em :issue:`37007`.)" #: ../../whatsnew/3.8.rst:1184 @@ -1972,20 +2473,20 @@ msgstr "statistics" #: ../../whatsnew/3.8.rst:1195 msgid "" "Added :func:`statistics.fmean` as a faster, floating-point variant of :func:" -"`statistics.mean()`. (Contributed by Raymond Hettinger and Steven D'Aprano " +"`statistics.mean`. (Contributed by Raymond Hettinger and Steven D'Aprano " "in :issue:`35904`.)" msgstr "" "Adicionada :func:`statistics.fmean` como uma variante de ponto flutuante " -"mais rápida de :func:`statistics.mean()`. (Contribuição de Raymond Hettinger " -"e Steven D'Aprano em :issue:`35904`.)" +"mais rápida de :func:`statistics.mean`. (Contribuição de Raymond Hettinger e " +"Steven D'Aprano em :issue:`35904`.)" #: ../../whatsnew/3.8.rst:1199 msgid "" -"Added :func:`statistics.geometric_mean()` (Contributed by Raymond Hettinger " +"Added :func:`statistics.geometric_mean` (Contributed by Raymond Hettinger " "in :issue:`27181`.)" msgstr "" -"Adicionada :func:`statistics.geometric_mean()` (Contribuição de Raymond " -"Hettinger em :issue:`27181`.)" +"Adicionada :func:`statistics.geometric_mean` (Contribuição de Raymond " +"Hettinger em :issue:`27181`." #: ../../whatsnew/3.8.rst:1202 msgid "" @@ -2015,6 +2516,52 @@ msgstr "" "manipular distribuições normais de uma variável aleatória. (Contribuição de " "Raymond Hettinger em :issue:`36018`.)" +#: ../../whatsnew/3.8.rst:1215 +msgid "" +">>> temperature_feb = NormalDist.from_samples([4, 12, -3, 2, 7, 14])\n" +">>> temperature_feb.mean\n" +"6.0\n" +">>> temperature_feb.stdev\n" +"6.356099432828281\n" +"\n" +">>> temperature_feb.cdf(3) # Chance of being under 3 degrees\n" +"0.3184678262814532\n" +">>> # Relative chance of being 7 degrees versus 10 degrees\n" +">>> temperature_feb.pdf(7) / temperature_feb.pdf(10)\n" +"1.2039930378537762\n" +"\n" +">>> el_niño = NormalDist(4, 2.5)\n" +">>> temperature_feb += el_niño # Add in a climate effect\n" +">>> temperature_feb\n" +"NormalDist(mu=10.0, sigma=6.830080526611674)\n" +"\n" +">>> temperature_feb * (9/5) + 32 # Convert to Fahrenheit\n" +"NormalDist(mu=50.0, sigma=12.294144947901014)\n" +">>> temperature_feb.samples(3) # Generate random samples\n" +"[7.672102882379219, 12.000027119750287, 4.647488369766392]" +msgstr "" +">>> temperature_feb = NormalDist.from_samples([4, 12, -3, 2, 7, 14])\n" +">>> temperature_feb.mean\n" +"6.0\n" +">>> temperature_feb.stdev\n" +"6.356099432828281\n" +"\n" +">>> temperature_feb.cdf(3) # Chance de ser manos de 3 graus\n" +"0.3184678262814532\n" +">>> # Chance relativa de ser 7 graus contra 10 graus\n" +">>> temperature_feb.pdf(7) / temperature_feb.pdf(10)\n" +"1.2039930378537762\n" +"\n" +">>> el_niño = NormalDist(4, 2.5)\n" +">>> temperature_feb += el_niño # Adiciona em um efeito do clima\n" +">>> temperature_feb\n" +"NormalDist(mu=10.0, sigma=6.830080526611674)\n" +"\n" +">>> temperature_feb * (9/5) + 32 # Converte para Fahrenheit\n" +"NormalDist(mu=50.0, sigma=12.294144947901014)\n" +">>> temperature_feb.samples(3) # Gera amostras aleatórias\n" +"[7.672102882379219, 12.000027119750287, 4.647488369766392]" + #: ../../whatsnew/3.8.rst:1239 msgid "sys" msgstr "sys" @@ -2166,6 +2713,18 @@ msgstr "" "que todas as chaves estejam presentes. Especifique \"total=False\" para " "permitir que as chaves sejam opcionais::" +#: ../../whatsnew/3.8.rst:1322 +msgid "" +"class Location(TypedDict, total=False):\n" +" lat_long: tuple\n" +" grid_square: str\n" +" xy_coordinate: tuple" +msgstr "" +"class Location(TypedDict, total=False):\n" +" lat_long: tuple\n" +" grid_square: str\n" +" xy_coordinate: tuple" + #: ../../whatsnew/3.8.rst:1327 msgid "" "Literal types. See :pep:`586` and :class:`typing.Literal`. Literal types " @@ -2176,6 +2735,14 @@ msgstr "" "indicam que um parâmetro ou valor de retorno está restrito a um ou mais " "valores literais específicos::" +#: ../../whatsnew/3.8.rst:1331 +msgid "" +"def get_status(port: int) -> Literal['connected', 'disconnected']:\n" +" ..." +msgstr "" +"def get_status(port: int) -> Literal['connected', 'disconnected']:\n" +" ..." + #: ../../whatsnew/3.8.rst:1334 msgid "" "\"Final\" variables, functions, methods and classes. See :pep:`591`, :class:" @@ -2187,6 +2754,10 @@ msgstr "" "verificador de tipo estático a restringir criação de subclasse, substituição " "ou reatribuição::" +#: ../../whatsnew/3.8.rst:1339 +msgid "pi: Final[float] = 3.1415926536" +msgstr "pi: Final[float] = 3.1415926536" + #: ../../whatsnew/3.8.rst:1341 msgid "" "Protocol definitions. See :pep:`544`, :class:`typing.Protocol` and :func:" @@ -2247,14 +2818,14 @@ msgstr "" #: ../../whatsnew/3.8.rst:1370 msgid "" -"Added :func:`~unittest.addModuleCleanup()` and :meth:`~unittest.TestCase." -"addClassCleanup()` to unittest to support cleanups for :func:`~unittest." -"setUpModule()` and :meth:`~unittest.TestCase.setUpClass()`. (Contributed by " -"Lisa Roach in :issue:`24412`.)" +"Added :func:`~unittest.addModuleCleanup` and :meth:`~unittest.TestCase." +"addClassCleanup` to unittest to support cleanups for :func:`~unittest." +"setUpModule` and :meth:`~unittest.TestCase.setUpClass`. (Contributed by Lisa " +"Roach in :issue:`24412`.)" msgstr "" -"Adicionados :func:`~unittest.addModuleCleanup()` e :meth:`~unittest.TestCase." -"addClassCleanup()` a unittest para dar suporte a limpezas para :func:" -"`~unittest.setUpModule()` e :meth:`~unittest.TestCase.setUpClass()`. " +"Adicionados :func:`~unittest.addModuleCleanup` e :meth:`~unittest.TestCase." +"addClassCleanup` a unittest para dar suporte a limpezas para :func:" +"`~unittest.setUpModule` e :meth:`~unittest.TestCase.setUpClass`. " "(Contribuição de Lisa Roach em :issue:`24412`.)" #: ../../whatsnew/3.8.rst:1376 @@ -2280,6 +2851,46 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" +#: ../../whatsnew/3.8.rst:1385 +msgid "" +"import unittest\n" +"\n" +"\n" +"class TestRequest(unittest.IsolatedAsyncioTestCase):\n" +"\n" +" async def asyncSetUp(self):\n" +" self.connection = await AsyncConnection()\n" +"\n" +" async def test_get(self):\n" +" response = await self.connection.get(\"https://example.com\")\n" +" self.assertEqual(response.status_code, 200)\n" +"\n" +" async def asyncTearDown(self):\n" +" await self.connection.close()\n" +"\n" +"\n" +"if __name__ == \"__main__\":\n" +" unittest.main()" +msgstr "" +"import unittest\n" +"\n" +"\n" +"class TestRequest(unittest.IsolatedAsyncioTestCase):\n" +"\n" +" async def asyncSetUp(self):\n" +" self.connection = await AsyncConnection()\n" +"\n" +" async def test_get(self):\n" +" response = await self.connection.get(\"https://example.com\")\n" +" self.assertEqual(response.status_code, 200)\n" +"\n" +" async def asyncTearDown(self):\n" +" await self.connection.close()\n" +"\n" +"\n" +"if __name__ == \"__main__\":\n" +" unittest.main()" + #: ../../whatsnew/3.8.rst:1406 msgid "venv" msgstr "venv" @@ -2337,12 +2948,12 @@ msgstr "" #: ../../whatsnew/3.8.rst:1434 msgid "" "The :mod:`xml.etree.ElementTree` module provides a new function :func:`–xml." -"etree.ElementTree.canonicalize()` that implements C14N 2.0. (Contributed by " +"etree.ElementTree.canonicalize` that implements C14N 2.0. (Contributed by " "Stefan Behnel in :issue:`13611`.)" msgstr "" "O módulo :mod:`xml.etree.ElementTree` fornece uma nova função :func:`–xml." -"etree.ElementTree.canonicalize()` que implementa o C14N 2.0. (Contribuição " -"de Stefan Behnel em :issue:`13611`.)" +"etree.ElementTree.canonicalize` que implementa o C14N 2.0. (Contribuição de " +"Stefan Behnel em :issue:`13611`.)" #: ../../whatsnew/3.8.rst:1438 msgid "" @@ -2561,7 +3172,7 @@ msgstr "" #: ../../whatsnew/3.8.rst:1537 msgid "Build and C API Changes" -msgstr "Alterações a compilações e API C" +msgstr "Mudanças a construções e API C" #: ../../whatsnew/3.8.rst:1539 msgid "" @@ -2979,10 +3590,10 @@ msgstr "" #: ../../whatsnew/3.8.rst:1715 msgid "" -"The :meth:`~threading.Thread.isAlive()` method of :class:`threading.Thread` " +"The :meth:`~threading.Thread.isAlive` method of :class:`threading.Thread` " "has been deprecated. (Contributed by Donghee Na in :issue:`35283`.)" msgstr "" -"O método :meth:`~threading.Thread.isAlive()` da classe :class:`threading." +"O método :meth:`~threading.Thread.isAlive` da classe :class:`threading." "Thread` foi descontinuado. (Contribuição de Donghee Na em :issue:`35283`.)" #: ../../whatsnew/3.8.rst:1719 @@ -3077,12 +3688,12 @@ msgid "" "Starting with Python 3.3, importing ABCs from :mod:`collections` was " "deprecated, and importing should be done from :mod:`collections.abc`. Being " "able to import from collections was marked for removal in 3.8, but has been " -"delayed to 3.9. (See :issue:`36952`.)" +"delayed to 3.9. (See :gh:`81134`.)" msgstr "" "A partir do Python 3.3, a importação de ABCs de :mod:`collections` foi " "descontinuada e a importação deve ser feita de :mod:`collections.abc`. A " "possibilidade de importar de coleções foi marcada para remoção em 3.8, mas " -"foi adiada para 3.9. (Veja :issue:`36952`.)" +"foi adiada para 3.9. (Veja :gh:`81134`.)" #: ../../whatsnew/3.8.rst:1760 msgid "" @@ -3744,6 +4355,33 @@ msgstr "" msgid "Example:" msgstr "Exemplo:" +#: ../../whatsnew/3.8.rst:2071 +msgid "" +"static foo_struct *\n" +"foo_new(PyObject *type) {\n" +" foo_struct *foo = PyObject_GC_New(foo_struct, (PyTypeObject *) type);\n" +" if (foo == NULL)\n" +" return NULL;\n" +"#if PY_VERSION_HEX < 0x03080000\n" +" // Workaround for Python issue 35810; no longer necessary in Python 3.8\n" +" PY_INCREF(type)\n" +"#endif\n" +" return foo;\n" +"}" +msgstr "" +"static foo_struct *\n" +"foo_new(PyObject *type) {\n" +" foo_struct *foo = PyObject_GC_New(foo_struct, (PyTypeObject *) type);\n" +" if (foo == NULL)\n" +" return NULL;\n" +"#if PY_VERSION_HEX < 0x03080000\n" +" // Solução de contorno para o issue 35810 do Python; não mais necessário " +"no Python 3.8\n" +" PY_INCREF(type)\n" +"#endif\n" +" return foo;\n" +"}" + #: ../../whatsnew/3.8.rst:2085 msgid "" "Ensure that all custom ``tp_dealloc`` functions of heap-allocated types " @@ -3752,6 +4390,28 @@ msgstr "" "Certifica-se de que todas as funções ``tp_dealloc`` personalizadas de tipos " "alocados em heap diminuam a contagem de referências do tipo." +#: ../../whatsnew/3.8.rst:2090 +msgid "" +"static void\n" +"foo_dealloc(foo_struct *instance) {\n" +" PyObject *type = Py_TYPE(instance);\n" +" PyObject_GC_Del(instance);\n" +"#if PY_VERSION_HEX >= 0x03080000\n" +" // This was not needed before Python 3.8 (Python issue 35810)\n" +" Py_DECREF(type);\n" +"#endif\n" +"}" +msgstr "" +"static void\n" +"foo_dealloc(foo_struct *instance) {\n" +" PyObject *type = Py_TYPE(instance);\n" +" PyObject_GC_Del(instance);\n" +"#if PY_VERSION_HEX >= 0x03080000\n" +" // Isso não era necessário antes do Python 3.8 (issue 35810 do Python)\n" +" Py_DECREF(type);\n" +"#endif\n" +"}" + #: ../../whatsnew/3.8.rst:2102 msgid "(Contributed by Eddie Elizondo in :issue:`35810`.)" msgstr "(Contribuição de Eddie Elizondo em :issue:`35810`.)" @@ -3764,6 +4424,10 @@ msgstr "" "A macro :c:macro:`Py_DEPRECATED()` foi implementada para MSVC. A macro agora " "deve ser colocada antes do nome do símbolo." +#: ../../whatsnew/3.8.rst:2109 +msgid "Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);" +msgstr "Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);" + #: ../../whatsnew/3.8.rst:2113 msgid "(Contributed by Zackery Spytz in :issue:`33407`.)" msgstr "(Contribuição de Zackery Spytz em :issue:`33407`.)" @@ -3811,6 +4475,14 @@ msgstr "" "ser gerado com as ferramentas ``gendef`` e ``dlltool``, que fazem parte do " "pacote binutils do MinGW:" +#: ../../whatsnew/3.8.rst:2132 +msgid "" +"gendef - python38.dll > tmp.def\n" +"dlltool --dllname python38.dll --def tmp.def --output-lib libpython38.a" +msgstr "" +"gendef - python38.dll > tmp.def\n" +"dlltool --dllname python38.dll --def tmp.def --output-lib libpython38.a" + #: ../../whatsnew/3.8.rst:2137 msgid "" "The location of an installed :file:`pythonXY.dll` will depend on the " @@ -3847,17 +4519,17 @@ msgstr "" #: ../../whatsnew/3.8.rst:2155 msgid "" -"Removed opcodes :opcode:`BREAK_LOOP`, :opcode:`CONTINUE_LOOP`, :opcode:" -"`SETUP_LOOP` and :opcode:`SETUP_EXCEPT`. Added new opcodes :opcode:" -"`ROT_FOUR`, :opcode:`BEGIN_FINALLY`, :opcode:`CALL_FINALLY` and :opcode:" -"`POP_FINALLY`. Changed the behavior of :opcode:`END_FINALLY` and :opcode:" -"`WITH_CLEANUP_START`." +"Removed opcodes :opcode:`!BREAK_LOOP`, :opcode:`!CONTINUE_LOOP`, :opcode:`!" +"SETUP_LOOP` and :opcode:`!SETUP_EXCEPT`. Added new opcodes :opcode:`!" +"ROT_FOUR`, :opcode:`!BEGIN_FINALLY`, :opcode:`!CALL_FINALLY` and :opcode:`!" +"POP_FINALLY`. Changed the behavior of :opcode:`!END_FINALLY` and :opcode:`!" +"WITH_CLEANUP_START`." msgstr "" -"Removidos os códigos de operação :opcode:`BREAK_LOOP`, :opcode:" -"`CONTINUE_LOOP`, :opcode:`SETUP_LOOP` e :opcode:`SETUP_EXCEPT`. Adicionados " -"novos códigos de operação :opcode:`ROT_FOUR`, :opcode:`BEGIN_FINALLY`, :" -"opcode:`CALL_FINALLY` e :opcode:`POP_FINALLY`. Alterado o comportamento de :" -"opcode:`END_FINALLY` e :opcode:`WITH_CLEANUP_START`." +"Removidos os códigos de operação :opcode:`!BREAK_LOOP`, :opcode:`!" +"CONTINUE_LOOP`, :opcode:`!SETUP_LOOP` e :opcode:`!SETUP_EXCEPT`. Adicionados " +"novos códigos de opção :opcode:`!ROT_FOUR`, :opcode:`!BEGIN_FINALLY`, :" +"opcode:`!CALL_FINALLY` e :opcode:`!POP_FINALLY`. Alterado o comportamento " +"de :opcode:`!END_FINALLY` e :opcode:`!WITH_CLEANUP_START`." #: ../../whatsnew/3.8.rst:2161 msgid "" @@ -3907,6 +4579,154 @@ msgstr "" msgid "Here's a summary of performance improvements since Python 3.3:" msgstr "Aqui está um resumo das melhorias de desempenho desde Python 3.3:" +#: ../../whatsnew/3.8.rst:2183 +msgid "" +"Python version 3.3 3.4 3.5 3.6 3.7 " +"3.8\n" +"-------------- --- --- --- --- --- " +"---\n" +"\n" +"Variable and attribute read access:\n" +" read_local 4.0 7.1 7.1 5.4 5.1 " +"3.9\n" +" read_nonlocal 5.3 7.1 8.1 5.8 5.4 " +"4.4\n" +" read_global 13.3 15.5 19.0 14.3 13.6 " +"7.6\n" +" read_builtin 20.0 21.1 21.6 18.5 19.0 " +"7.5\n" +" read_classvar_from_class 20.5 25.6 26.5 20.7 19.5 " +"18.4\n" +" read_classvar_from_instance 18.5 22.8 23.5 18.8 17.1 " +"16.4\n" +" read_instancevar 26.8 32.4 33.1 28.0 26.3 " +"25.4\n" +" read_instancevar_slots 23.7 27.8 31.3 20.8 20.8 " +"20.2\n" +" read_namedtuple 68.5 73.8 57.5 45.0 46.8 " +"18.4\n" +" read_boundmethod 29.8 37.6 37.9 29.6 26.9 " +"27.7\n" +"\n" +"Variable and attribute write access:\n" +" write_local 4.6 8.7 9.3 5.5 5.3 " +"4.3\n" +" write_nonlocal 7.3 10.5 11.1 5.6 5.5 " +"4.7\n" +" write_global 15.9 19.7 21.2 18.0 18.0 " +"15.8\n" +" write_classvar 81.9 92.9 96.0 104.6 102.1 " +"39.2\n" +" write_instancevar 36.4 44.6 45.8 40.0 38.9 " +"35.5\n" +" write_instancevar_slots 28.7 35.6 36.1 27.3 26.6 " +"25.7\n" +"\n" +"Data structure read access:\n" +" read_list 19.2 24.2 24.5 20.8 20.8 " +"19.0\n" +" read_deque 19.9 24.7 25.5 20.2 20.6 " +"19.8\n" +" read_dict 19.7 24.3 25.7 22.3 23.0 " +"21.0\n" +" read_strdict 17.9 22.6 24.3 19.5 21.2 " +"18.9\n" +"\n" +"Data structure write access:\n" +" write_list 21.2 27.1 28.5 22.5 21.6 " +"20.0\n" +" write_deque 23.8 28.7 30.1 22.7 21.8 " +"23.5\n" +" write_dict 25.9 31.4 33.3 29.3 29.2 " +"24.7\n" +" write_strdict 22.9 28.4 29.9 27.5 25.2 " +"23.1\n" +"\n" +"Stack (or queue) operations:\n" +" list_append_pop 144.2 93.4 112.7 75.4 74.2 " +"50.8\n" +" deque_append_pop 30.4 43.5 57.0 49.4 49.2 " +"42.5\n" +" deque_append_popleft 30.8 43.7 57.3 49.7 49.7 " +"42.8\n" +"\n" +"Timing loop:\n" +" loop_overhead 0.3 0.5 0.6 0.4 0.3 " +"0.3" +msgstr "" +"Python version 3.3 3.4 3.5 3.6 3.7 " +"3.8\n" +"-------------- --- --- --- --- --- " +"---\n" +"\n" +"Variable and attribute read access:\n" +" read_local 4.0 7.1 7.1 5.4 5.1 " +"3.9\n" +" read_nonlocal 5.3 7.1 8.1 5.8 5.4 " +"4.4\n" +" read_global 13.3 15.5 19.0 14.3 13.6 " +"7.6\n" +" read_builtin 20.0 21.1 21.6 18.5 19.0 " +"7.5\n" +" read_classvar_from_class 20.5 25.6 26.5 20.7 19.5 " +"18.4\n" +" read_classvar_from_instance 18.5 22.8 23.5 18.8 17.1 " +"16.4\n" +" read_instancevar 26.8 32.4 33.1 28.0 26.3 " +"25.4\n" +" read_instancevar_slots 23.7 27.8 31.3 20.8 20.8 " +"20.2\n" +" read_namedtuple 68.5 73.8 57.5 45.0 46.8 " +"18.4\n" +" read_boundmethod 29.8 37.6 37.9 29.6 26.9 " +"27.7\n" +"\n" +"Variable and attribute write access:\n" +" write_local 4.6 8.7 9.3 5.5 5.3 " +"4.3\n" +" write_nonlocal 7.3 10.5 11.1 5.6 5.5 " +"4.7\n" +" write_global 15.9 19.7 21.2 18.0 18.0 " +"15.8\n" +" write_classvar 81.9 92.9 96.0 104.6 102.1 " +"39.2\n" +" write_instancevar 36.4 44.6 45.8 40.0 38.9 " +"35.5\n" +" write_instancevar_slots 28.7 35.6 36.1 27.3 26.6 " +"25.7\n" +"\n" +"Data structure read access:\n" +" read_list 19.2 24.2 24.5 20.8 20.8 " +"19.0\n" +" read_deque 19.9 24.7 25.5 20.2 20.6 " +"19.8\n" +" read_dict 19.7 24.3 25.7 22.3 23.0 " +"21.0\n" +" read_strdict 17.9 22.6 24.3 19.5 21.2 " +"18.9\n" +"\n" +"Data structure write access:\n" +" write_list 21.2 27.1 28.5 22.5 21.6 " +"20.0\n" +" write_deque 23.8 28.7 30.1 22.7 21.8 " +"23.5\n" +" write_dict 25.9 31.4 33.3 29.3 29.2 " +"24.7\n" +" write_strdict 22.9 28.4 29.9 27.5 25.2 " +"23.1\n" +"\n" +"Stack (or queue) operations:\n" +" list_append_pop 144.2 93.4 112.7 75.4 74.2 " +"50.8\n" +" deque_append_pop 30.4 43.5 57.0 49.4 49.2 " +"42.5\n" +" deque_append_popleft 30.8 43.7 57.3 49.7 49.7 " +"42.8\n" +"\n" +"Timing loop:\n" +" loop_overhead 0.3 0.5 0.6 0.4 0.3 " +"0.3" + #: ../../whatsnew/3.8.rst:2228 msgid "" "The benchmarks were measured on an `Intel® Core™ i7-4960HQ processor " diff --git a/whatsnew/3.9.po b/whatsnew/3.9.po index c21b29be5..dcf0b5b83 100644 --- a/whatsnew/3.9.po +++ b/whatsnew/3.9.po @@ -1,34 +1,25 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Hildeberto Abreu Magalhães , 2021 -# André Filipe de Assunção e Brito , 2021 -# i17obot , 2021 -# Raphael Mendonça, 2021 -# Marco Rougeth , 2021 -# Italo Penaforte , 2021 -# Victor Matheus Castro , 2021 -# Claudio Rogerio Carvalho Filho , 2024 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-07 14:15+0000\n" -"PO-Revision-Date: 2021-06-29 13:04+0000\n" -"Last-Translator: Rafael Fontenelle , 2024\n" +"POT-Creation-Date: 2025-01-03 14:16+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -262,7 +253,7 @@ msgstr "" "removidos nesta versão do Python. Consulte a seção :ref:`removed-in-" "python-39`." -#: ../../whatsnew/3.9.rst:140 ../../whatsnew/3.9.rst:1270 +#: ../../whatsnew/3.9.rst:140 ../../whatsnew/3.9.rst:1271 msgid "New Features" msgstr "Novas funcionalidades" @@ -284,6 +275,24 @@ msgstr "" msgid "Example::" msgstr "Exemplo::" +#: ../../whatsnew/3.9.rst:151 +msgid "" +">>> x = {\"key1\": \"value1 from x\", \"key2\": \"value2 from x\"}\n" +">>> y = {\"key2\": \"value2 from y\", \"key3\": \"value3 from y\"}\n" +">>> x | y\n" +"{'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'}\n" +">>> y | x\n" +"{'key2': 'value2 from x', 'key3': 'value3 from y', 'key1': 'value1 from x'}" +msgstr "" +">>> x = {\"chave1\": \"valor1 from x\", \"chave2\": \"valor2 from x\"}\n" +">>> y = {\"chave2\": \"valor2 from y\", \"chave3\": \"valor3 from y\"}\n" +">>> x | y\n" +"{'chave1': 'valor1 from x', 'chave2': 'valor2 from y', 'chave3': 'valor3 " +"from y'}\n" +">>> y | x\n" +"{'chave2': 'valor2 from x', 'chave3': 'valor3 from y', 'chave1': 'valor1 " +"from x'}" + #: ../../whatsnew/3.9.rst:158 msgid "" "See :pep:`584` for a full description. (Contributed by Brandt Bucher in :" @@ -330,10 +339,20 @@ msgstr "" "``typing``. Agora, outros tipos na biblioteca padrão também são genéricos, " "por exemplo, ``queue.Queue``." -#: ../../whatsnew/3.9.rst:180 ../../whatsnew/3.9.rst:1158 +#: ../../whatsnew/3.9.rst:180 ../../whatsnew/3.9.rst:1159 msgid "Example:" msgstr "Exemplo:" +#: ../../whatsnew/3.9.rst:182 +msgid "" +"def greet_all(names: list[str]) -> None:\n" +" for name in names:\n" +" print(\"Hello\", name)" +msgstr "" +"def cumprimentar_todos(nomes: list[str]) -> None:\n" +" for nome in nomes:\n" +" print(\"Olá\", nome)" + #: ../../whatsnew/3.9.rst:188 msgid "" "See :pep:`585` for more details. (Contributed by Guido van Rossum, Ethan " @@ -355,13 +374,13 @@ msgid "" "when it comes to designing new language features. We'll start using this " "flexibility in Python 3.10 and later." msgstr "" -"O Python 3.9 usa um novo analisador, baseado em `GASE `_ " -"em vez de `LL(1) `_. O desempenho do novo analisador é " -"aproximadamente comparável ao do analisador antigo, mas o formalismo do GASE " -"é mais flexível que do LL(1) quando se trata de projetar novos recursos de " -"linguagem. Começaremos a usar essa flexibilidade no Python 3.10 e posterior." +"O Python 3.9 usa um novo analisador sintático, baseado em `GASE `_ em vez de " +"`LL(1) `_. O " +"desempenho do novo analisador sintático é aproximadamente comparável ao do " +"analisador sintático antigo, mas o formalismo do GASE é mais flexível que do " +"LL(1) quando se trata de projetar novos recursos de linguagem. Começaremos a " +"usar essa flexibilidade no Python 3.10 e posterior." #: ../../whatsnew/3.9.rst:202 msgid "" @@ -539,6 +558,44 @@ msgstr "" "uma implementação concreta :class:`datetime.tzinfo`, apoiada pelos dados do " "fuso horário do sistema." +#: ../../whatsnew/3.9.rst:284 +msgid "" +">>> from zoneinfo import ZoneInfo\n" +">>> from datetime import datetime, timedelta\n" +"\n" +">>> # Daylight saving time\n" +">>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo(\"America/" +"Los_Angeles\"))\n" +">>> print(dt)\n" +"2020-10-31 12:00:00-07:00\n" +">>> dt.tzname()\n" +"'PDT'\n" +"\n" +">>> # Standard time\n" +">>> dt += timedelta(days=7)\n" +">>> print(dt)\n" +"2020-11-07 12:00:00-08:00\n" +">>> print(dt.tzname())\n" +"PST" +msgstr "" +">>> from zoneinfo import ZoneInfo\n" +">>> from datetime import datetime, timedelta\n" +"\n" +">>> # Tempo em fuso horário com horário de verão\n" +">>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo(\"America/" +"Los_Angeles\"))\n" +">>> print(dt)\n" +"2020-10-31 12:00:00-07:00\n" +">>> dt.tzname()\n" +"'PDT'\n" +"\n" +">>> # Tempo padrão\n" +">>> dt += timedelta(days=7)\n" +">>> print(dt)\n" +"2020-11-07 12:00:00-08:00\n" +">>> print(dt.tzname())\n" +"PST" + #: ../../whatsnew/3.9.rst:302 msgid "" "As a fall-back source of data for platforms that don't ship the IANA " @@ -786,13 +843,13 @@ msgstr "datetime" #: ../../whatsnew/3.9.rst:411 msgid "" -"The :meth:`~datetime.date.isocalendar()` of :class:`datetime.date` and :meth:" -"`~datetime.datetime.isocalendar()` of :class:`datetime.datetime` methods now " +"The :meth:`~datetime.date.isocalendar` of :class:`datetime.date` and :meth:" +"`~datetime.datetime.isocalendar` of :class:`datetime.datetime` methods now " "returns a :func:`~collections.namedtuple` instead of a :class:`tuple`. " "(Contributed by Donghee Na in :issue:`24416`.)" msgstr "" -"Os métodos :meth:`~datetime.date.isocalendar()` de :class:`datetime.date` e :" -"meth:`~datetime.datetime.isocalendar()` de :class:`datetime.datetime` agora " +"Os métodos :meth:`~datetime.date.isocalendar` de :class:`datetime.date` e :" +"meth:`~datetime.datetime.isocalendar` de :class:`datetime.datetime` agora " "retornam uma :func:`~collections.namedtuple` em vez de uma :class:`tuple`. " "(Contribuição de Donghee Na em :issue:`24416`.)" @@ -1227,11 +1284,11 @@ msgstr "pathlib" #: ../../whatsnew/3.9.rst:613 msgid "" -"Added :meth:`pathlib.Path.readlink()` which acts similarly to :func:`os." +"Added :meth:`pathlib.Path.readlink` which acts similarly to :func:`os." "readlink`. (Contributed by Girts Folkmanis in :issue:`30618`)" msgstr "" -"Adicionado :meth:`pathlib.Path.readlink ()`, que age de maneira semelhante " -"a :func:`os.readlink`. (Contribuição de Girts Folkmanis em :issue: `30618`)" +"Adicionado :meth:`pathlib.Path.readlink`, que age de maneira semelhante a :" +"func:`os.readlink`. (Contribuição de Girts Folkmanis em :issue:`30618`)" #: ../../whatsnew/3.9.rst:618 msgid "pdb" @@ -1280,18 +1337,18 @@ msgstr "pydoc" #: ../../whatsnew/3.9.rst:639 msgid "" "The documentation string is now shown not only for class, function, method " -"etc, but for any object that has its own ``__doc__`` attribute. (Contributed " -"by Serhiy Storchaka in :issue:`40257`.)" +"etc, but for any object that has its own :attr:`~definition.__doc__` " +"attribute. (Contributed by Serhiy Storchaka in :issue:`40257`.)" msgstr "" "A string de documentação agora é mostrada não apenas para classe, função, " -"método etc, mas para qualquer objeto que tenha seu próprio atributo " -"``__doc__``. (Contribuição de Serhiy Storchaka em :issue:`40257`.)" +"método etc, mas para qualquer objeto que tenha seu próprio atributo :attr:" +"`~definition.__doc__`. (Contribuição de Serhiy Storchaka em :issue:`40257`.)" -#: ../../whatsnew/3.9.rst:644 +#: ../../whatsnew/3.9.rst:645 msgid "random" msgstr "random" -#: ../../whatsnew/3.9.rst:646 +#: ../../whatsnew/3.9.rst:647 msgid "" "Added a new :attr:`random.Random.randbytes` method: generate random bytes. " "(Contributed by Victor Stinner in :issue:`40286`.)" @@ -1299,11 +1356,11 @@ msgstr "" "Adicionado um novo método :attr:`random.Random.randbytes`: gera bytes " "aleatórios. (Contribuição de Victor Stinner em :issue:`40286`.)" -#: ../../whatsnew/3.9.rst:650 +#: ../../whatsnew/3.9.rst:651 msgid "signal" msgstr "signal" -#: ../../whatsnew/3.9.rst:652 +#: ../../whatsnew/3.9.rst:653 msgid "" "Exposed the Linux-specific :func:`signal.pidfd_send_signal` for sending to " "signals to a process using a file descriptor instead of a pid. (:issue:" @@ -1313,11 +1370,11 @@ msgstr "" "sinais a um processo usando um descritor de arquivo em vez de um pid. (:" "issue:`38712`)" -#: ../../whatsnew/3.9.rst:656 +#: ../../whatsnew/3.9.rst:657 msgid "smtplib" msgstr "smtplib" -#: ../../whatsnew/3.9.rst:658 +#: ../../whatsnew/3.9.rst:659 msgid "" ":class:`~smtplib.SMTP` and :class:`~smtplib.SMTP_SSL` now raise a :class:" "`ValueError` if the given timeout for their constructor is zero to prevent " @@ -1329,7 +1386,7 @@ msgstr "" "zero para impedir a criação de um soquete sem bloqueio. (Contribuição de " "Dong-hee Na em :issue:`39259`.)" -#: ../../whatsnew/3.9.rst:662 +#: ../../whatsnew/3.9.rst:663 msgid "" ":class:`~smtplib.LMTP` constructor now has an optional *timeout* parameter. " "(Contributed by Donghee Na in :issue:`39329`.)" @@ -1337,11 +1394,11 @@ msgstr "" "O construtor de :class:`~smtplib.LMTP` agora tem um parâmetro opcional " "*timeout*. (Contribuição de Dong-hee Na em :issue:`39329`.)" -#: ../../whatsnew/3.9.rst:666 +#: ../../whatsnew/3.9.rst:667 msgid "socket" msgstr "socket" -#: ../../whatsnew/3.9.rst:668 +#: ../../whatsnew/3.9.rst:669 msgid "" "The :mod:`socket` module now exports the :const:`~socket." "CAN_RAW_JOIN_FILTERS` constant on Linux 4.1 and greater. (Contributed by " @@ -1351,7 +1408,7 @@ msgstr "" "CAN_RAW_JOIN_FILTERS` no Linux 4.1 e superior. (Contribuição de Stefan " "Tatschner e Zackery Spytz em :issue:`25780`.)" -#: ../../whatsnew/3.9.rst:672 +#: ../../whatsnew/3.9.rst:673 msgid "" "The socket module now supports the :const:`~socket.CAN_J1939` protocol on " "platforms that support it. (Contributed by Karl Ding in :issue:`40291`.)" @@ -1359,7 +1416,7 @@ msgstr "" "O módulo socket agora suporta o protocolo :const:`~socket.CAN_J1939` nas " "plataformas que o suportam. (Contribuição de Karl Ding em :issue:`40291`.)" -#: ../../whatsnew/3.9.rst:675 +#: ../../whatsnew/3.9.rst:676 msgid "" "The socket module now has the :func:`socket.send_fds` and :func:`socket." "recv_fds` functions. (Contributed by Joannah Nanjekye, Shinya Okano and " @@ -1369,11 +1426,11 @@ msgstr "" "recv_fds`. (Contribuição de Joannah Nanjekye, Shinya Okano e Victor Stinner " "em :issue:`28724`.)" -#: ../../whatsnew/3.9.rst:681 +#: ../../whatsnew/3.9.rst:682 msgid "time" msgstr "time" -#: ../../whatsnew/3.9.rst:683 +#: ../../whatsnew/3.9.rst:684 msgid "" "On AIX, :func:`~time.thread_time` is now implemented with " "``thread_cputime()`` which has nanosecond resolution, rather than " @@ -1385,11 +1442,11 @@ msgstr "" "``clock_gettime(CLOCK_THREAD_CPUTIME_ID)``, que tem uma resolução de 10 " "milissegundos. (Contribuição de Batuhan Taskaya em :issue:`40192`)" -#: ../../whatsnew/3.9.rst:689 +#: ../../whatsnew/3.9.rst:690 msgid "sys" msgstr "sys" -#: ../../whatsnew/3.9.rst:691 +#: ../../whatsnew/3.9.rst:692 msgid "" "Added a new :data:`sys.platlibdir` attribute: name of the platform-specific " "library directory. It is used to build the path of standard library and the " @@ -1405,7 +1462,7 @@ msgstr "" "``\"lib64\"`` nas plataformas de 64 bits. (Contribuição de Jan Matějek, " "Matěj Cepl, Charalampos Stratakis e Victor Stinner em :issue:`1294959`.)" -#: ../../whatsnew/3.9.rst:697 +#: ../../whatsnew/3.9.rst:698 msgid "" "Previously, :data:`sys.stderr` was block-buffered when non-interactive. Now " "``stderr`` defaults to always being line-buffered. (Contributed by Jendrik " @@ -1415,11 +1472,11 @@ msgstr "" "interativo. Agora, ``stderr`` assume como padrão sempre o buffer de linha. " "(Contribuição de Jendrik Seipp em :issue:`13601`.)" -#: ../../whatsnew/3.9.rst:702 +#: ../../whatsnew/3.9.rst:703 msgid "tracemalloc" msgstr "tracemalloc" -#: ../../whatsnew/3.9.rst:704 +#: ../../whatsnew/3.9.rst:705 msgid "" "Added :func:`tracemalloc.reset_peak` to set the peak size of traced memory " "blocks to the current size, to measure the peak of specific pieces of code. " @@ -1430,11 +1487,11 @@ msgstr "" "partes específicas do código. (Contribuição de Huon Wilson em :issue:" "`40630`.)" -#: ../../whatsnew/3.9.rst:709 ../../whatsnew/3.9.rst:1492 +#: ../../whatsnew/3.9.rst:710 ../../whatsnew/3.9.rst:1493 msgid "typing" msgstr "typing" -#: ../../whatsnew/3.9.rst:711 +#: ../../whatsnew/3.9.rst:712 msgid "" ":pep:`593` introduced an :data:`typing.Annotated` type to decorate existing " "types with context-specific metadata and new ``include_extras`` parameter " @@ -1447,22 +1504,22 @@ msgstr "" "metadados em tempo de execução. (Contribuição de Till Varoquaux e Konstantin " "Kashin.)" -#: ../../whatsnew/3.9.rst:717 +#: ../../whatsnew/3.9.rst:718 msgid "unicodedata" msgstr "unicodedata" -#: ../../whatsnew/3.9.rst:719 +#: ../../whatsnew/3.9.rst:720 msgid "" "The Unicode database has been updated to version 13.0.0. (:issue:`39926`)." msgstr "" "O banco de dados Unicode foi atualizado para a versão 13.0.0. (:issue:" "`39926`)." -#: ../../whatsnew/3.9.rst:722 +#: ../../whatsnew/3.9.rst:723 msgid "venv" msgstr "venv" -#: ../../whatsnew/3.9.rst:724 +#: ../../whatsnew/3.9.rst:725 msgid "" "The activation scripts provided by :mod:`venv` now all specify their prompt " "customization consistently by always using the value specified by " @@ -1478,11 +1535,11 @@ msgstr "" "era o caso padrão) e um usava ``__VENV_NAME__``. (Contribuição de Brett " "Cannon em :issue:`37663`.)" -#: ../../whatsnew/3.9.rst:732 +#: ../../whatsnew/3.9.rst:733 msgid "xml" msgstr "xml" -#: ../../whatsnew/3.9.rst:734 +#: ../../whatsnew/3.9.rst:735 msgid "" "White space characters within attributes are now preserved when serializing :" "mod:`xml.etree.ElementTree` to XML file. EOLNs are no longer normalized to " @@ -1495,11 +1552,11 @@ msgstr "" "interpretar a seção 2.11 da especificação XML. (Contribuição de Mefistotelis " "em :issue:`39011`.)" -#: ../../whatsnew/3.9.rst:742 +#: ../../whatsnew/3.9.rst:743 msgid "Optimizations" msgstr "Otimizações" -#: ../../whatsnew/3.9.rst:744 +#: ../../whatsnew/3.9.rst:745 msgid "" "Optimized the idiom for assignment a temporary variable in comprehensions. " "Now ``for y in [expr]`` in comprehensions is as fast as a simple assignment " @@ -1509,11 +1566,11 @@ msgstr "" "compreensões. Agora ``for y in [expr]`` nas compreensões é tão rápido quanto " "uma atribuição simples ``y = expr``. Por exemplo:" -#: ../../whatsnew/3.9.rst:748 +#: ../../whatsnew/3.9.rst:749 msgid "sums = [s for s in [0] for x in data for s in [s + x]]" msgstr "sums = [s for s in [0] for x in data for s in [s + x]]" -#: ../../whatsnew/3.9.rst:750 +#: ../../whatsnew/3.9.rst:751 msgid "" "Unlike the ``:=`` operator this idiom does not leak a variable to the outer " "scope." @@ -1521,11 +1578,11 @@ msgstr "" "Ao contrário do operador ``:=``, este idioma não vaza uma variável para o " "escopo externo." -#: ../../whatsnew/3.9.rst:753 +#: ../../whatsnew/3.9.rst:754 msgid "(Contributed by Serhiy Storchaka in :issue:`32856`.)" msgstr "(Contribuição de Serhiy Storchaka em :issue:`32856`.)" -#: ../../whatsnew/3.9.rst:755 +#: ../../whatsnew/3.9.rst:756 msgid "" "Optimized signal handling in multithreaded applications. If a thread " "different than the main thread gets a signal, the bytecode evaluation loop " @@ -1539,7 +1596,7 @@ msgstr "" "verificar se há sinais pendentes que não podem ser manipulados. Somente o " "segmento principal do interpretador principal pode manipular sinais." -#: ../../whatsnew/3.9.rst:761 +#: ../../whatsnew/3.9.rst:762 msgid "" "Previously, the bytecode evaluation loop was interrupted at each instruction " "until the main thread handles signals. (Contributed by Victor Stinner in :" @@ -1549,7 +1606,7 @@ msgstr "" "instrução até que a thread principal lidasse com os sinais. (Contribuição de " "Victor Stinner em :issue:`40010`.)" -#: ../../whatsnew/3.9.rst:765 +#: ../../whatsnew/3.9.rst:766 msgid "" "Optimized the :mod:`subprocess` module on FreeBSD using ``closefrom()``. " "(Contributed by Ed Maste, Conrad Meyer, Kyle Evans, Kubilay Kocak and Victor " @@ -1559,7 +1616,7 @@ msgstr "" "(Contribuição de Ed Maste, Conrad Meyer, Kyle Evans, Kubilay Kocak e Victor " "Stinner em :issue:`38061`.)" -#: ../../whatsnew/3.9.rst:769 +#: ../../whatsnew/3.9.rst:770 msgid "" ":c:func:`PyLong_FromDouble` is now up to 1.87x faster for values that fit " "into :c:expr:`long`. (Contributed by Sergey Fedoseev in :issue:`37986`.)" @@ -1568,7 +1625,7 @@ msgstr "" "que cabem em um :c:expr:`long`. (Contribuição de Sergey Fedoseev em :issue:" "`37986`.)" -#: ../../whatsnew/3.9.rst:773 +#: ../../whatsnew/3.9.rst:774 msgid "" "A number of Python builtins (:class:`range`, :class:`tuple`, :class:`set`, :" "class:`frozenset`, :class:`list`, :class:`dict`) are now sped up by using :" @@ -1580,7 +1637,7 @@ msgstr "" "acelerados usando o protocolo vectorcall da :pep:`590`. (Contribuição de " "Donghee Na, Mark Shannon, Jeroen Demeyer e Petr Viktorin em :issue:`37207`.)" -#: ../../whatsnew/3.9.rst:778 +#: ../../whatsnew/3.9.rst:779 msgid "" "Optimized :func:`~set.difference_update` for the case when the other set is " "much larger than the base set. (Suggested by Evgeny Kapun with code " @@ -1590,7 +1647,7 @@ msgstr "" "conjunto é muito maior do que o conjunto base. (Sugestão de Evgeny Kapun com " "contribuição de código de Michele Orrù em :issue:`8425`.)" -#: ../../whatsnew/3.9.rst:782 +#: ../../whatsnew/3.9.rst:783 msgid "" "Python's small object allocator (``obmalloc.c``) now allows (no more than) " "one empty arena to remain available for immediate reuse, without returning " @@ -1604,7 +1661,7 @@ msgstr "" "loops simples, onde uma arena pode ser criada e destruída novamente em cada " "iteração. (Contribuição de Tim Peters em :issue:`37257`.)" -#: ../../whatsnew/3.9.rst:788 +#: ../../whatsnew/3.9.rst:789 msgid "" ":term:`floor division` of float operation now has a better performance. Also " "the message of :exc:`ZeroDivisionError` for this operation is updated. " @@ -1615,7 +1672,7 @@ msgstr "" "para esta operação foi atualizada. (Contribuição de Donghee Na em :issue:" "`39434`.)" -#: ../../whatsnew/3.9.rst:792 +#: ../../whatsnew/3.9.rst:793 msgid "" "Decoding short ASCII strings with UTF-8 and ascii codecs is now about 15% " "faster. (Contributed by Inada Naoki in :issue:`37348`.)" @@ -1623,14 +1680,162 @@ msgstr "" "A decodificação de strings curtas ASCII com codecs UTF-8 e ascii é agora " "cerca de 15% mais rápida. (Contribuição de Inada Naoki em :issue:`37348`.)" -#: ../../whatsnew/3.9.rst:795 +#: ../../whatsnew/3.9.rst:796 msgid "" "Here's a summary of performance improvements from Python 3.4 through Python " "3.9:" msgstr "" "Aqui está um resumo das melhorias de desempenho do Python 3.4 ao Python 3.9:" -#: ../../whatsnew/3.9.rst:842 +#: ../../whatsnew/3.9.rst:798 +msgid "" +"Python version 3.4 3.5 3.6 3.7 3.8 " +"3.9\n" +"-------------- --- --- --- --- --- " +"---\n" +"\n" +"Variable and attribute read access:\n" +" read_local 7.1 7.1 5.4 5.1 3.9 " +"3.9\n" +" read_nonlocal 7.1 8.1 5.8 5.4 4.4 " +"4.5\n" +" read_global 15.5 19.0 14.3 13.6 7.6 " +"7.8\n" +" read_builtin 21.1 21.6 18.5 19.0 7.5 " +"7.8\n" +" read_classvar_from_class 25.6 26.5 20.7 19.5 18.4 " +"17.9\n" +" read_classvar_from_instance 22.8 23.5 18.8 17.1 16.4 " +"16.9\n" +" read_instancevar 32.4 33.1 28.0 26.3 25.4 " +"25.3\n" +" read_instancevar_slots 27.8 31.3 20.8 20.8 20.2 " +"20.5\n" +" read_namedtuple 73.8 57.5 45.0 46.8 18.4 " +"18.7\n" +" read_boundmethod 37.6 37.9 29.6 26.9 27.7 " +"41.1\n" +"\n" +"Variable and attribute write access:\n" +" write_local 8.7 9.3 5.5 5.3 4.3 " +"4.3\n" +" write_nonlocal 10.5 11.1 5.6 5.5 4.7 " +"4.8\n" +" write_global 19.7 21.2 18.0 18.0 15.8 " +"16.7\n" +" write_classvar 92.9 96.0 104.6 102.1 39.2 " +"39.8\n" +" write_instancevar 44.6 45.8 40.0 38.9 35.5 " +"37.4\n" +" write_instancevar_slots 35.6 36.1 27.3 26.6 25.7 " +"25.8\n" +"\n" +"Data structure read access:\n" +" read_list 24.2 24.5 20.8 20.8 19.0 " +"19.5\n" +" read_deque 24.7 25.5 20.2 20.6 19.8 " +"20.2\n" +" read_dict 24.3 25.7 22.3 23.0 21.0 " +"22.4\n" +" read_strdict 22.6 24.3 19.5 21.2 18.9 " +"21.5\n" +"\n" +"Data structure write access:\n" +" write_list 27.1 28.5 22.5 21.6 20.0 " +"20.0\n" +" write_deque 28.7 30.1 22.7 21.8 23.5 " +"21.7\n" +" write_dict 31.4 33.3 29.3 29.2 24.7 " +"25.4\n" +" write_strdict 28.4 29.9 27.5 25.2 23.1 " +"24.5\n" +"\n" +"Stack (or queue) operations:\n" +" list_append_pop 93.4 112.7 75.4 74.2 50.8 " +"50.6\n" +" deque_append_pop 43.5 57.0 49.4 49.2 42.5 " +"44.2\n" +" deque_append_popleft 43.7 57.3 49.7 49.7 42.8 " +"46.4\n" +"\n" +"Timing loop:\n" +" loop_overhead 0.5 0.6 0.4 0.3 0.3 " +"0.3" +msgstr "" +"Versão do Python 3.4 3.5 3.6 3.7 3.8 " +"3.9\n" +"-------------- --- --- --- --- --- " +"---\n" +"\n" +"Acesso de leitura a variável e atributo:\n" +" read_local 7.1 7.1 5.4 5.1 3.9 " +"3.9\n" +" read_nonlocal 7.1 8.1 5.8 5.4 4.4 " +"4.5\n" +" read_global 15.5 19.0 14.3 13.6 7.6 " +"7.8\n" +" read_builtin 21.1 21.6 18.5 19.0 7.5 " +"7.8\n" +" read_classvar_from_class 25.6 26.5 20.7 19.5 18.4 " +"17.9\n" +" read_classvar_from_instance 22.8 23.5 18.8 17.1 16.4 " +"16.9\n" +" read_instancevar 32.4 33.1 28.0 26.3 25.4 " +"25.3\n" +" read_instancevar_slots 27.8 31.3 20.8 20.8 20.2 " +"20.5\n" +" read_namedtuple 73.8 57.5 45.0 46.8 18.4 " +"18.7\n" +" read_boundmethod 37.6 37.9 29.6 26.9 27.7 " +"41.1\n" +"\n" +"Acesso de escrita a variável e atributo:\n" +" write_local 8.7 9.3 5.5 5.3 4.3 " +"4.3\n" +" write_nonlocal 10.5 11.1 5.6 5.5 4.7 " +"4.8\n" +" write_global 19.7 21.2 18.0 18.0 15.8 " +"16.7\n" +" write_classvar 92.9 96.0 104.6 102.1 39.2 " +"39.8\n" +" write_instancevar 44.6 45.8 40.0 38.9 35.5 " +"37.4\n" +" write_instancevar_slots 35.6 36.1 27.3 26.6 25.7 " +"25.8\n" +"\n" +"Acesso de leitura a estrutura de dados:\n" +" read_list 24.2 24.5 20.8 20.8 19.0 " +"19.5\n" +" read_deque 24.7 25.5 20.2 20.6 19.8 " +"20.2\n" +" read_dict 24.3 25.7 22.3 23.0 21.0 " +"22.4\n" +" read_strdict 22.6 24.3 19.5 21.2 18.9 " +"21.5\n" +"\n" +"Acesso de escrita a estrutura de dados:\n" +" write_list 27.1 28.5 22.5 21.6 20.0 " +"20.0\n" +" write_deque 28.7 30.1 22.7 21.8 23.5 " +"21.7\n" +" write_dict 31.4 33.3 29.3 29.2 24.7 " +"25.4\n" +" write_strdict 28.4 29.9 27.5 25.2 23.1 " +"24.5\n" +"\n" +"Operações em pilha (ou fila):\n" +" list_append_pop 93.4 112.7 75.4 74.2 50.8 " +"50.6\n" +" deque_append_pop 43.5 57.0 49.4 49.2 42.5 " +"44.2\n" +" deque_append_popleft 43.7 57.3 49.7 49.7 42.8 " +"46.4\n" +"\n" +"Tempo de laços:\n" +" loop_overhead 0.5 0.6 0.4 0.3 0.3 " +"0.3" + +#: ../../whatsnew/3.9.rst:843 msgid "" "These results were generated from the variable access benchmark script at: " "``Tools/scripts/var_access_benchmark.py``. The benchmark script displays " @@ -1648,11 +1853,11 @@ msgstr "" "html>`_ executando as compilações do macOS de 64 bits encontradas em `python." "org `_." -#: ../../whatsnew/3.9.rst:852 +#: ../../whatsnew/3.9.rst:853 msgid "Deprecated" msgstr "Descontinuados" -#: ../../whatsnew/3.9.rst:854 +#: ../../whatsnew/3.9.rst:855 msgid "" "The distutils ``bdist_msi`` command is now deprecated, use ``bdist_wheel`` " "(wheel packages) instead. (Contributed by Hugo van Kemenade in :issue:" @@ -1662,7 +1867,7 @@ msgstr "" "``bdist_wheel`` (pacotes wheel). (Contribuição de Hugo van Kemenade em :" "issue:`39586`.)" -#: ../../whatsnew/3.9.rst:858 +#: ../../whatsnew/3.9.rst:859 msgid "" "Currently :func:`math.factorial` accepts :class:`float` instances with non-" "negative integer values (like ``5.0``). It raises a :exc:`ValueError` for " @@ -1677,7 +1882,7 @@ msgstr "" "`TypeError` para todos os flutuadores. (Contribuição de Serhiy Storchaka em :" "issue:`37315`.)" -#: ../../whatsnew/3.9.rst:864 +#: ../../whatsnew/3.9.rst:865 msgid "" "The :mod:`!parser` and :mod:`!symbol` modules are deprecated and will be " "removed in future versions of Python. For the majority of use cases, users " @@ -1689,7 +1894,7 @@ msgstr "" "usuários podem aproveitar o estágio de geração e compilação da Árvore de " "Sintaxe Abstrata (AST), usando o módulo :mod:`ast`." -#: ../../whatsnew/3.9.rst:869 +#: ../../whatsnew/3.9.rst:870 msgid "" "The Public C API functions :c:func:`!PyParser_SimpleParseStringFlags`, :c:" "func:`!PyParser_SimpleParseStringFlagsFilename`, :c:func:`!" @@ -1702,7 +1907,7 @@ msgstr "" "descontinuados e serão removidos no Python 3.10 junto com o analisador " "sintático antigo." -#: ../../whatsnew/3.9.rst:874 +#: ../../whatsnew/3.9.rst:875 msgid "" "Using :data:`NotImplemented` in a boolean context has been deprecated, as it " "is almost exclusively the result of incorrect rich comparator " @@ -1714,7 +1919,7 @@ msgstr "" "comparadores avançados. Isso será tornado em uma :exc:`TypeError` em uma " "versão futura do Python. (Contribuição de Josh Rosenberg em :issue:`35712`.)" -#: ../../whatsnew/3.9.rst:880 +#: ../../whatsnew/3.9.rst:881 msgid "" "The :mod:`random` module currently accepts any hashable type as a possible " "seed value. Unfortunately, some of those types are not guaranteed to have a " @@ -1728,7 +1933,7 @@ msgstr "" "restringirá suas sementes a :const:`None`, :class:`int`, :class:`float`, :" "class:`str`, :class:`bytes` e :class:`bytearray`." -#: ../../whatsnew/3.9.rst:886 +#: ../../whatsnew/3.9.rst:887 msgid "" "Opening the :class:`~gzip.GzipFile` file for writing without specifying the " "*mode* argument is deprecated. In future Python versions it will always be " @@ -1742,7 +1947,7 @@ msgstr "" "para abri-lo para escrever e silenciar um aviso. (Contribuição de Serhiy " "Storchaka em :issue:`28286`.)" -#: ../../whatsnew/3.9.rst:892 +#: ../../whatsnew/3.9.rst:893 msgid "" "Deprecated the ``split()`` method of :class:`!_tkinter.TkappType` in favour " "of the ``splitlist()`` method which has more consistent and predictable " @@ -1752,7 +1957,7 @@ msgstr "" "do método ``splitlist()`` que possui um comportamento mais consistente e " "previsível. (Contribuição de Serhiy Storchaka em :issue:`38371`.)" -#: ../../whatsnew/3.9.rst:897 +#: ../../whatsnew/3.9.rst:898 msgid "" "The explicit passing of coroutine objects to :func:`asyncio.wait` has been " "deprecated and will be removed in version 3.11. (Contributed by Yury " @@ -1762,7 +1967,7 @@ msgstr "" "descontinuada e será removida na versão 3.11. (Contribuição de Yury " "Selivanov e Kyle Stanley em :issue:`34790`.)" -#: ../../whatsnew/3.9.rst:901 +#: ../../whatsnew/3.9.rst:902 msgid "" "binhex4 and hexbin4 standards are now deprecated. The :mod:`!binhex` module " "and the following :mod:`binascii` functions are now deprecated:" @@ -1770,19 +1975,19 @@ msgstr "" "Os padrões binhex4 e hexbin4 agora foram descontinuados. O módulo :mod:`!" "binhex` e as seguintes funções :mod:`binascii` foram descontinuadas:" -#: ../../whatsnew/3.9.rst:904 +#: ../../whatsnew/3.9.rst:905 msgid ":func:`!b2a_hqx`, :func:`!a2b_hqx`" msgstr ":func:`!b2a_hqx`, :func:`!a2b_hqx`" -#: ../../whatsnew/3.9.rst:905 +#: ../../whatsnew/3.9.rst:906 msgid ":func:`!rlecode_hqx`, :func:`!rledecode_hqx`" msgstr ":func:`!rlecode_hqx`, :func:`!rledecode_hqx`" -#: ../../whatsnew/3.9.rst:907 +#: ../../whatsnew/3.9.rst:908 msgid "(Contributed by Victor Stinner in :issue:`39353`.)" msgstr "(Contribuição de Victor Stinner em :issue:`39353`.)" -#: ../../whatsnew/3.9.rst:909 +#: ../../whatsnew/3.9.rst:910 msgid "" ":mod:`ast` classes ``slice``, ``Index`` and ``ExtSlice`` are considered " "deprecated and will be removed in future Python versions. ``value`` itself " @@ -1796,7 +2001,7 @@ msgstr "" "``Tuple(slices, Load())`` deve ser usada em vez de ``ExtSlice(slices)``. " "(Contribuição de Serhiy Storchaka em :issue:`34822`.)" -#: ../../whatsnew/3.9.rst:915 +#: ../../whatsnew/3.9.rst:916 msgid "" ":mod:`ast` classes ``Suite``, ``Param``, ``AugLoad`` and ``AugStore`` are " "considered deprecated and will be removed in future Python versions. They " @@ -1810,7 +2015,7 @@ msgstr "" "pelo gerador de código no Python 3. (Contribuição de Batuhan Taskaya em :" "issue:`39639` e :issue:`39969` e Serhiy Storchaka em :issue:`39988`.)" -#: ../../whatsnew/3.9.rst:922 +#: ../../whatsnew/3.9.rst:923 msgid "" "The :c:func:`!PyEval_InitThreads` and :c:func:`!PyEval_ThreadsInitialized` " "functions are now deprecated and will be removed in Python 3.11. Calling :c:" @@ -1824,7 +2029,7 @@ msgstr "" "term:`GIL` é inicializada por :c:func:`Py_Initialize` desde o Python 3.7. " "(Contribuição de Victor Stinner em :issue:`39877`.)" -#: ../../whatsnew/3.9.rst:928 +#: ../../whatsnew/3.9.rst:929 msgid "" "Passing ``None`` as the first argument to the :func:`shlex.split` function " "has been deprecated. (Contributed by Zackery Spytz in :issue:`33262`.)" @@ -1832,7 +2037,7 @@ msgstr "" "Passar ``None`` como o primeiro argumento para a função :func:`shlex.split` " "foi descontinuada. (Contribuição de Zackery Spytz em :issue:`33262`.)" -#: ../../whatsnew/3.9.rst:931 +#: ../../whatsnew/3.9.rst:932 msgid "" ":func:`!smtpd.MailmanProxy` is now deprecated as it is unusable without an " "external module, ``mailman``. (Contributed by Samuel Colvin in :issue:" @@ -1842,7 +2047,7 @@ msgstr "" "sem um módulo externo, ``mailman``. (Contribuição de Samuel Colvin em :" "issue:`35800`.)" -#: ../../whatsnew/3.9.rst:934 +#: ../../whatsnew/3.9.rst:935 msgid "" "The :mod:`!lib2to3` module now emits a :exc:`PendingDeprecationWarning`. " "Python 3.9 switched to a PEG parser (see :pep:`617`), and Python 3.10 may " @@ -1859,7 +2064,7 @@ msgstr "" "alternativas de terceiros, como `LibCST`_ ou `parso`_. (Contribuição de Carl " "Meyer em :issue:`40360`.)" -#: ../../whatsnew/3.9.rst:942 +#: ../../whatsnew/3.9.rst:943 msgid "" "The *random* parameter of :func:`random.shuffle` has been deprecated. " "(Contributed by Raymond Hettinger in :issue:`40465`)" @@ -1867,16 +2072,16 @@ msgstr "" "Adicionado o parâmetro *random* da :func:`random.shuffle` foi descontinuado. " "(Contribuição de Raymond Hettinger em :issue:`40465`)" -#: ../../whatsnew/3.9.rst:951 ../../whatsnew/3.9.rst:1406 +#: ../../whatsnew/3.9.rst:952 ../../whatsnew/3.9.rst:1407 msgid "Removed" msgstr "Removidos" -#: ../../whatsnew/3.9.rst:953 +#: ../../whatsnew/3.9.rst:954 msgid "" "The erroneous version at :data:`!unittest.mock.__version__` has been removed." msgstr "A versão errônea em :data:`!unittest.mock.__version__` foi removida." -#: ../../whatsnew/3.9.rst:955 +#: ../../whatsnew/3.9.rst:956 msgid "" ":class:`!nntplib.NNTP`: ``xpath()`` and ``xgtitle()`` methods have been " "removed. These methods are deprecated since Python 3.3. Generally, these " @@ -1892,7 +2097,7 @@ msgstr "" "NNTP.descriptions` ou :meth:`!nntplib.NNTP.description`. (Contribuição de " "Donghee Na em :issue:`39366`.)" -#: ../../whatsnew/3.9.rst:962 +#: ../../whatsnew/3.9.rst:963 msgid "" ":class:`array.array`: ``tostring()`` and ``fromstring()`` methods have been " "removed. They were aliases to ``tobytes()`` and ``frombytes()``, deprecated " @@ -1903,7 +2108,7 @@ msgstr "" "descontinuado desde Python 3.2. (Contribuição de Victor Stinner em :issue:" "`38916`.)" -#: ../../whatsnew/3.9.rst:967 +#: ../../whatsnew/3.9.rst:968 msgid "" "The undocumented ``sys.callstats()`` function has been removed. Since Python " "3.7, it was deprecated and always returned :const:`None`. It required a " @@ -1915,7 +2120,7 @@ msgstr "" "opção de compilação especial ``CALL_PROFILE`` que já foi removida no Python " "3.7. (Contribuição de Victor Stinner em :issue:`37414`.)" -#: ../../whatsnew/3.9.rst:972 +#: ../../whatsnew/3.9.rst:973 msgid "" "The ``sys.getcheckinterval()`` and ``sys.setcheckinterval()`` functions have " "been removed. They were deprecated since Python 3.2. Use :func:`sys." @@ -1927,7 +2132,7 @@ msgstr "" "getswitchinterval` e :func:`sys.setswitchinterval` em seu lugar. " "(Contribuição de Victor Stinner em :issue:`37392`.)" -#: ../../whatsnew/3.9.rst:977 +#: ../../whatsnew/3.9.rst:978 msgid "" "The C function ``PyImport_Cleanup()`` has been removed. It was documented " "as: \"Empty the module table. For internal use only.\" (Contributed by " @@ -1937,7 +2142,7 @@ msgstr "" "\"Esvazia a tabela do módulo. Apenas para uso interno.\" (Contribuição de " "Victor Stinner em :issue:`36710`.)" -#: ../../whatsnew/3.9.rst:981 +#: ../../whatsnew/3.9.rst:982 msgid "" "``_dummy_thread`` and ``dummy_threading`` modules have been removed. These " "modules were deprecated since Python 3.7 which requires threading support. " @@ -1947,29 +2152,29 @@ msgstr "" "módulos foram descontinuados desde o Python 3.7, que requer suporte a " "threading. (Contribuição de Victor Stinner em :issue:`37312`.)" -#: ../../whatsnew/3.9.rst:985 +#: ../../whatsnew/3.9.rst:986 msgid "" "``aifc.openfp()`` alias to ``aifc.open()``, ``sunau.openfp()`` alias to " -"``sunau.open()``, and ``wave.openfp()`` alias to :func:`wave.open()` have " -"been removed. They were deprecated since Python 3.7. (Contributed by Victor " +"``sunau.open()``, and ``wave.openfp()`` alias to :func:`wave.open` have been " +"removed. They were deprecated since Python 3.7. (Contributed by Victor " "Stinner in :issue:`37320`.)" msgstr "" -"``aifc.openfp()`` alias para ``aifc.open()``, ``sunau.openfp()`` alias para " -"``sunau.open()`` e ``wave.openfp()`` alias para :func:`wave.open()` foi " -"removido. Eles foram descontinuados desde o Python 3.7. (Contribuição de " -"Victor Stinner em :issue:`37320`.)" +"O apelido ``aifc.openfp()`` para ``aifc.open()``, o apelido ``sunau." +"openfp()`` para ``sunau.open()`` e o apelido ``wave.openfp()`` para :func:" +"`wave.open` foram removidos. Eles estavam descontinuados desde o Python 3.7. " +"(Contribuição de Victor Stinner em :issue:`37320`.)" -#: ../../whatsnew/3.9.rst:990 +#: ../../whatsnew/3.9.rst:991 msgid "" -"The :meth:`!isAlive()` method of :class:`threading.Thread` has been removed. " -"It was deprecated since Python 3.8. Use :meth:`~threading.Thread.is_alive()` " +"The :meth:`!isAlive` method of :class:`threading.Thread` has been removed. " +"It was deprecated since Python 3.8. Use :meth:`~threading.Thread.is_alive` " "instead. (Contributed by Donghee Na in :issue:`37804`.)" msgstr "" -"O método :meth:`!isAlive()` de :class:`threading.Thread` foi removido. Ele " -"foi descontinuado desde o Python 3.8. Use :meth:`~threading.Thread." -"is_alive()` ao invés. (Contribuição de Donghee Na em :issue:`37804`.)" +"O método :meth:`!isAlive` de :class:`threading.Thread` foi removido. Ele foi " +"descontinuado desde o Python 3.8. Use :meth:`~threading.Thread.is_alive` ao " +"invés. (Contribuição de Donghee Na em :issue:`37804`.)" -#: ../../whatsnew/3.9.rst:995 +#: ../../whatsnew/3.9.rst:996 msgid "" "Methods ``getchildren()`` and ``getiterator()`` of classes :class:`~xml." "etree.ElementTree.ElementTree` and :class:`~xml.etree.ElementTree.Element` " @@ -1985,7 +2190,7 @@ msgstr "" "getchildren()`` e ``x.iter()`` ou ``list(x.iter())`` em vez de ``x." "getiterator()``. (Contribuição Serhiy Storchaka no :issue:`36543`.)" -#: ../../whatsnew/3.9.rst:1003 +#: ../../whatsnew/3.9.rst:1004 msgid "" "The old :mod:`plistlib` API has been removed, it was deprecated since Python " "3.4. Use the :func:`~plistlib.load`, :func:`~plistlib.loads`, :func:" @@ -2000,7 +2205,7 @@ msgstr "" "são sempre usados em seu lugar. (Contribuição de Jon Janzen em :issue:" "`36409`.)" -#: ../../whatsnew/3.9.rst:1009 +#: ../../whatsnew/3.9.rst:1010 msgid "" "The C function ``PyGen_NeedsFinalizing`` has been removed. It was not " "documented, tested, or used anywhere within CPython after the implementation " @@ -2012,7 +2217,7 @@ msgstr "" "de :pep:`442`. Patch de Joannah Nanjekye. (Contribuição de Joannah Nanjekye " "em :issue:`15088`)" -#: ../../whatsnew/3.9.rst:1014 +#: ../../whatsnew/3.9.rst:1015 msgid "" "``base64.encodestring()`` and ``base64.decodestring()``, aliases deprecated " "since Python 3.1, have been removed: use :func:`base64.encodebytes` and :" @@ -2024,7 +2229,7 @@ msgstr "" "encodebytes` e :func:`base64.decodebytes`. (Contribuição de Victor Stinner " "em :issue:`39351`.)" -#: ../../whatsnew/3.9.rst:1019 +#: ../../whatsnew/3.9.rst:1020 msgid "" "``fractions.gcd()`` function has been removed, it was deprecated since " "Python 3.5 (:issue:`22486`): use :func:`math.gcd` instead. (Contributed by " @@ -2034,7 +2239,7 @@ msgstr "" "3.5 (:issue:`22486`): use :func:`math.gcd` em seu lugar. (Contribuição de " "Victor Stinner em :issue:`39350`.)" -#: ../../whatsnew/3.9.rst:1023 +#: ../../whatsnew/3.9.rst:1024 msgid "" "The *buffering* parameter of :class:`bz2.BZ2File` has been removed. Since " "Python 3.0, it was ignored and using it emitted a :exc:`DeprecationWarning`. " @@ -2046,7 +2251,7 @@ msgstr "" "Passe um objeto arquivo aberto para controlar como o arquivo é aberto. " "(Contribuição de Victor Stinner em :issue:`39357`.)" -#: ../../whatsnew/3.9.rst:1028 +#: ../../whatsnew/3.9.rst:1029 msgid "" "The *encoding* parameter of :func:`json.loads` has been removed. As of " "Python 3.1, it was deprecated and ignored; using it has emitted a :exc:" @@ -2058,7 +2263,7 @@ msgstr "" "`DeprecationWarning` desde Python 3.8. (Contribuição de Inada Naoki em :" "issue:`39377`)" -#: ../../whatsnew/3.9.rst:1033 +#: ../../whatsnew/3.9.rst:1034 msgid "" "``with (await asyncio.lock):`` and ``with (yield from asyncio.lock):`` " "statements are not longer supported, use ``async with lock`` instead. The " @@ -2070,7 +2275,7 @@ msgstr "" "aplica para ``asyncio.Condition`` e ``asyncio.Semaphore``. (Contribuição de " "Andrew Svetlov em :issue:`34793`.)" -#: ../../whatsnew/3.9.rst:1038 +#: ../../whatsnew/3.9.rst:1039 msgid "" "The :func:`!sys.getcounts` function, the ``-X showalloccount`` command line " "option and the ``show_alloc_count`` field of the C structure :c:type:" @@ -2084,7 +2289,7 @@ msgstr "" "definindo a macro ``COUNT_ALLOCS``. (Contribuição de Victor Stinner em :" "issue:`39489`.)" -#: ../../whatsnew/3.9.rst:1044 +#: ../../whatsnew/3.9.rst:1045 msgid "" "The ``_field_types`` attribute of the :class:`typing.NamedTuple` class has " "been removed. It was deprecated since Python 3.8. Use the " @@ -2095,7 +2300,7 @@ msgstr "" "removido. Ele foi descontinuado desde o Python 3.8. Use o atributo " "``__annotations__``. (Contribuição de Serhiy Storchaka em :issue:`40182`.)" -#: ../../whatsnew/3.9.rst:1049 +#: ../../whatsnew/3.9.rst:1050 msgid "" "The :meth:`!symtable.SymbolTable.has_exec` method has been removed. It was " "deprecated since 2006, and only returning ``False`` when it's called. " @@ -2105,7 +2310,7 @@ msgstr "" "descontinuado desde 2006, e retornando apenas ``False`` quando é chamado. " "(Contribuição de Batuhan Taskaya em :issue:`40208`)" -#: ../../whatsnew/3.9.rst:1053 +#: ../../whatsnew/3.9.rst:1054 msgid "" "The :meth:`!asyncio.Task.current_task` and :meth:`!asyncio.Task.all_tasks` " "have been removed. They were deprecated since Python 3.7 and you can use :" @@ -2117,7 +2322,7 @@ msgstr "" "você pode usar :func:`asyncio.current_task` e :func:`asyncio.all_tasks` em " "seu lugar. (Contribuição de Rémi Lapeyre em :issue:`40967`)" -#: ../../whatsnew/3.9.rst:1058 +#: ../../whatsnew/3.9.rst:1059 msgid "" "The ``unescape()`` method in the :class:`html.parser.HTMLParser` class has " "been removed (it was deprecated since Python 3.4). :func:`html.unescape` " @@ -2129,11 +2334,11 @@ msgstr "" "ser usada para converter referências de caracteres para os caracteres " "Unicode correspondentes." -#: ../../whatsnew/3.9.rst:1065 ../../whatsnew/3.9.rst:1332 +#: ../../whatsnew/3.9.rst:1066 ../../whatsnew/3.9.rst:1333 msgid "Porting to Python 3.9" msgstr "Portando para Python 3.9" -#: ../../whatsnew/3.9.rst:1067 +#: ../../whatsnew/3.9.rst:1068 msgid "" "This section lists previously described changes and other bugfixes that may " "require changes to your code." @@ -2141,11 +2346,11 @@ msgstr "" "Esta seção lista as alterações descritas anteriormente e outras correções " "que podem exigir alterações no seu código." -#: ../../whatsnew/3.9.rst:1072 +#: ../../whatsnew/3.9.rst:1073 msgid "Changes in the Python API" msgstr "Alterações na API Python" -#: ../../whatsnew/3.9.rst:1074 +#: ../../whatsnew/3.9.rst:1075 msgid "" ":func:`__import__` and :func:`importlib.util.resolve_name` now raise :exc:" "`ImportError` where it previously raised :exc:`ValueError`. Callers catching " @@ -2158,7 +2363,7 @@ msgstr "" "anteriores precisarão capturar ambas usando ``except (ImportError, " "ValueError):``." -#: ../../whatsnew/3.9.rst:1079 +#: ../../whatsnew/3.9.rst:1080 msgid "" "The :mod:`venv` activation scripts no longer special-case when " "``__VENV_PROMPT__`` is set to ``\"\"``." @@ -2166,7 +2371,7 @@ msgstr "" "Os scripts de ativação :mod:`venv` não são mais casos especiais quando " "``__VENV_PROMPT__`` está definido como ``\"\"``." -#: ../../whatsnew/3.9.rst:1082 +#: ../../whatsnew/3.9.rst:1083 msgid "" "The :meth:`select.epoll.unregister` method no longer ignores the :const:" "`~errno.EBADF` error. (Contributed by Victor Stinner in :issue:`39239`.)" @@ -2174,7 +2379,7 @@ msgstr "" "O método :meth:`select.epoll.unregister` não ignora mais o erro :const:" "`~errno.EBADF`. (Contribuição de Victor Stinner em :issue:`39239`.)" -#: ../../whatsnew/3.9.rst:1086 +#: ../../whatsnew/3.9.rst:1087 msgid "" "The *compresslevel* parameter of :class:`bz2.BZ2File` became keyword-only, " "since the *buffering* parameter has been removed. (Contributed by Victor " @@ -2184,7 +2389,7 @@ msgstr "" "somente-nomeado, uma vez que o parâmetro *buffering* foi removido. " "(Contribuição de Victor Stinner em :issue:`39357`.)" -#: ../../whatsnew/3.9.rst:1090 +#: ../../whatsnew/3.9.rst:1091 msgid "" "Simplified AST for subscription. Simple indices will be represented by their " "value, extended slices will be represented as tuples. ``Index(value)`` will " @@ -2197,7 +2402,7 @@ msgstr "" "retornará ``Tuple(slices, Load())``. (Contribuição de Serhiy Storchaka em :" "issue:`34822`.)" -#: ../../whatsnew/3.9.rst:1096 +#: ../../whatsnew/3.9.rst:1097 msgid "" "The :mod:`importlib` module now ignores the :envvar:`PYTHONCASEOK` " "environment variable when the :option:`-E` or :option:`-I` command line " @@ -2207,7 +2412,7 @@ msgstr "" "`PYTHONCASEOK` quando as opções de linha de comando :option:`-E` ou :option:" "`-I` estão sendo usadas." -#: ../../whatsnew/3.9.rst:1100 +#: ../../whatsnew/3.9.rst:1101 msgid "" "The *encoding* parameter has been added to the classes :class:`ftplib.FTP` " "and :class:`ftplib.FTP_TLS` as a keyword-only parameter, and the default " @@ -2217,7 +2422,7 @@ msgstr "" "class:`ftplib.FTP_TLS` como um parâmetro somente-nomeado, e a codificação " "padrão foi alterada de Latin-1 para UTF-8 para siga :rfc:`2640`." -#: ../../whatsnew/3.9.rst:1104 +#: ../../whatsnew/3.9.rst:1105 msgid "" ":meth:`asyncio.loop.shutdown_default_executor` has been added to :class:" "`~asyncio.AbstractEventLoop`, meaning alternative event loops that inherit " @@ -2229,7 +2434,7 @@ msgstr "" "que herdam dele devem ter este método definido. (Contribuição de Kyle " "Stanley em :issue:`34037`.)" -#: ../../whatsnew/3.9.rst:1109 +#: ../../whatsnew/3.9.rst:1110 msgid "" "The constant values of future flags in the :mod:`__future__` module is " "updated in order to prevent collision with compiler flags. Previously " @@ -2241,7 +2446,7 @@ msgstr "" "Anteriormente, ``PyCF_ALLOW_TOP_LEVEL_AWAIT`` estava em conflito com " "``CO_FUTURE_DIVISION``. (Contribuição de Batuhan Taskaya em :issue:`39562`)" -#: ../../whatsnew/3.9.rst:1114 +#: ../../whatsnew/3.9.rst:1115 msgid "" "``array('u')`` now uses :c:type:`wchar_t` as C type instead of " "``Py_UNICODE``. This change doesn't affect to its behavior because " @@ -2253,7 +2458,7 @@ msgstr "" "``Py_UNICODE`` é um apelido de :c:type:`wchar_t` desde Python 3.3. " "(Contribuição de Inada Naoki em :issue:`34538`.)" -#: ../../whatsnew/3.9.rst:1119 +#: ../../whatsnew/3.9.rst:1120 msgid "" "The :func:`logging.getLogger` API now returns the root logger when passed " "the name ``'root'``, whereas previously it returned a non-root logger named " @@ -2270,7 +2475,7 @@ msgstr "" "superior chamado ``'root.py'``. (Contribuição de Vinay Sajip em :issue:" "`37742`.)" -#: ../../whatsnew/3.9.rst:1126 +#: ../../whatsnew/3.9.rst:1127 msgid "" "Division handling of :class:`~pathlib.PurePath` now returns :data:" "`NotImplemented` instead of raising a :exc:`TypeError` when passed something " @@ -2284,7 +2489,7 @@ msgstr "" "Isso permite a criação de classes compatíveis que não herdam desses tipos " "mencionados. (Contribuição de Roger Aiudi em :issue:`34775`)." -#: ../../whatsnew/3.9.rst:1132 +#: ../../whatsnew/3.9.rst:1133 msgid "" "Starting with Python 3.9.5 the :mod:`ipaddress` module no longer accepts any " "leading zeros in IPv4 address strings. Leading zeros are ambiguous and " @@ -2301,7 +2506,7 @@ msgstr "" "não aceita nenhum zeros à esquerda. (Contribuição de Christian Heimes em :" "issue:`36384`)." -#: ../../whatsnew/3.9.rst:1140 +#: ../../whatsnew/3.9.rst:1141 msgid "" ":func:`codecs.lookup` now normalizes the encoding name the same way as :func:" "`encodings.normalize_encoding`, except that :func:`codecs.lookup` also " @@ -2315,11 +2520,11 @@ msgstr "" "nome de codificação agora está normalizado para ``\"latex_latin1\"``. " "(Contribuição de Jordon Xu em :issue:`37751`.)" -#: ../../whatsnew/3.9.rst:1148 +#: ../../whatsnew/3.9.rst:1149 msgid "Changes in the C API" msgstr "Alterações na API C" -#: ../../whatsnew/3.9.rst:1150 +#: ../../whatsnew/3.9.rst:1151 msgid "" "Instances of :ref:`heap-allocated types ` (such as those created " "with :c:func:`PyType_FromSpec` and similar APIs) hold a reference to their " @@ -2338,7 +2543,28 @@ msgstr "" "todas as funções ``tp_traverse`` personalizadas de tipos alocados por heap " "visitam o tipo do objeto." -#: ../../whatsnew/3.9.rst:1171 +#: ../../whatsnew/3.9.rst:1161 +msgid "" +"int\n" +"foo_traverse(foo_struct *self, visitproc visit, void *arg) {\n" +"// Rest of the traverse function\n" +"#if PY_VERSION_HEX >= 0x03090000\n" +" // This was not needed before Python 3.9 (Python issue 35810 and 40217)\n" +" Py_VISIT(Py_TYPE(self));\n" +"#endif\n" +"}" +msgstr "" +"int\n" +"travessia_foo(foo_struct *self, visitproc visit, void *arg) {\n" +"// Resto da função de travessia\n" +"#if PY_VERSION_HEX >= 0x03090000\n" +" // Isso não era necessário antes do Python 3.9 (problemas 35810 e 40217 " +"do Python)\n" +" Py_VISIT(Py_TYPE(self));\n" +"#endif\n" +"}" + +#: ../../whatsnew/3.9.rst:1172 msgid "" "If your traverse function delegates to ``tp_traverse`` of its base class (or " "another type), ensure that ``Py_TYPE(self)`` is visited only once. Note that " @@ -2350,19 +2576,43 @@ msgstr "" "vez. Observe que apenas os :ref:`tipos de heap ` devem visitar o " "tipo em ``tp_traverse``." -#: ../../whatsnew/3.9.rst:1176 +#: ../../whatsnew/3.9.rst:1177 msgid "For example, if your ``tp_traverse`` function includes:" msgstr "Por exemplo, se sua função ``tp_traverse`` inclui:" -#: ../../whatsnew/3.9.rst:1182 +#: ../../whatsnew/3.9.rst:1179 +msgid "base->tp_traverse(self, visit, arg)" +msgstr "base->tp_traverse(self, visit, arg)" + +#: ../../whatsnew/3.9.rst:1183 msgid "then add:" msgstr "adicione:" -#: ../../whatsnew/3.9.rst:1195 +#: ../../whatsnew/3.9.rst:1185 +msgid "" +"#if PY_VERSION_HEX >= 0x03090000\n" +" // This was not needed before Python 3.9 (bpo-35810 and bpo-40217)\n" +" if (base->tp_flags & Py_TPFLAGS_HEAPTYPE) {\n" +" // a heap type's tp_traverse already visited Py_TYPE(self)\n" +" } else {\n" +" Py_VISIT(Py_TYPE(self));\n" +" }\n" +"#else" +msgstr "" +"#if PY_VERSION_HEX >= 0x03090000\n" +" // Isso não era necessário antes do Python 3.9 (bpo-35810 e bpo-40217)\n" +" if (base->tp_flags & Py_TPFLAGS_HEAPTYPE) {\n" +" // tp_traverse de um tipo de heap já visitou Py_TYPE(self)\n" +" } else {\n" +" Py_VISIT(Py_TYPE(self));\n" +" }\n" +"#else" + +#: ../../whatsnew/3.9.rst:1196 msgid "(See :issue:`35810` and :issue:`40217` for more information.)" msgstr "(Veja :issue:`35810` e :issue:`40217` para mais informações.)" -#: ../../whatsnew/3.9.rst:1197 +#: ../../whatsnew/3.9.rst:1198 msgid "" "The functions ``PyEval_CallObject``, ``PyEval_CallFunction``, " "``PyEval_CallMethod`` and ``PyEval_CallObjectWithKeywords`` are deprecated. " @@ -2374,11 +2624,11 @@ msgstr "" "descontinuadas. Use :c:func:`PyObject_Call` e suas variantes. (Veja mais " "detalhes em :issue:`29548`.)" -#: ../../whatsnew/3.9.rst:1203 +#: ../../whatsnew/3.9.rst:1204 msgid "CPython bytecode changes" msgstr "Alterações de bytecode do CPython" -#: ../../whatsnew/3.9.rst:1205 +#: ../../whatsnew/3.9.rst:1206 msgid "" "The :opcode:`LOAD_ASSERTION_ERROR` opcode was added for handling the :" "keyword:`assert` statement. Previously, the assert statement would not work " @@ -2390,41 +2640,41 @@ msgstr "" "funcionava corretamente se a exceção :exc:`AssertionError` estivesse sendo " "ocultada. (Contribuição de Zackery Spytz em :issue:`34880`.)" -#: ../../whatsnew/3.9.rst:1210 +#: ../../whatsnew/3.9.rst:1211 msgid "" "The :opcode:`COMPARE_OP` opcode was split into four distinct instructions:" msgstr "" "O código de operação :opcode:`COMPARE_OP` foi dividido em quatro instruções " "distintas:" -#: ../../whatsnew/3.9.rst:1212 +#: ../../whatsnew/3.9.rst:1213 msgid "``COMPARE_OP`` for rich comparisons" msgstr "``COMPARE_OP`` para comparações ricas" -#: ../../whatsnew/3.9.rst:1213 +#: ../../whatsnew/3.9.rst:1214 msgid "``IS_OP`` for 'is' and 'is not' tests" msgstr "``IS_OP`` para testes \"is\" e \"is not\"" -#: ../../whatsnew/3.9.rst:1214 +#: ../../whatsnew/3.9.rst:1215 msgid "``CONTAINS_OP`` for 'in' and 'not in' tests" msgstr "``CONTAINS_OP`` para testes \"in\" e \"not in\"" -#: ../../whatsnew/3.9.rst:1215 +#: ../../whatsnew/3.9.rst:1216 msgid "" "``JUMP_IF_NOT_EXC_MATCH`` for checking exceptions in 'try-except' statements." msgstr "" "``JUMP_IF_NOT_EXC_MATCH`` para verificar exceções em instruções \"try-" "except\"." -#: ../../whatsnew/3.9.rst:1218 +#: ../../whatsnew/3.9.rst:1219 msgid "(Contributed by Mark Shannon in :issue:`39156`.)" msgstr "(Contribuição de Mark Shannon em :issue:`39156`.)" -#: ../../whatsnew/3.9.rst:1222 +#: ../../whatsnew/3.9.rst:1223 msgid "Build Changes" -msgstr "Alterações de compilação" +msgstr "Mudanças na construção" -#: ../../whatsnew/3.9.rst:1224 +#: ../../whatsnew/3.9.rst:1225 msgid "" "Added ``--with-platlibdir`` option to the ``configure`` script: name of the " "platform-specific library directory, stored in the new :data:`sys." @@ -2438,7 +2688,7 @@ msgstr "" "mais informações. (Contribuição de Jan Matějek, Matěj Cepl, Charalampos " "Stratakis e Victor Stinner em :issue:`1294959`.)" -#: ../../whatsnew/3.9.rst:1230 +#: ../../whatsnew/3.9.rst:1231 msgid "" "The ``COUNT_ALLOCS`` special build macro has been removed. (Contributed by " "Victor Stinner in :issue:`39489`.)" @@ -2446,7 +2696,7 @@ msgstr "" "A macro especial de construção ``COUNT_ALLOCS`` foi removida. (Contribuição " "de Victor Stinner em :issue:`39489`.)" -#: ../../whatsnew/3.9.rst:1233 +#: ../../whatsnew/3.9.rst:1234 msgid "" "On non-Windows platforms, the :c:func:`!setenv` and :c:func:`!unsetenv` " "functions are now required to build Python. (Contributed by Victor Stinner " @@ -2456,7 +2706,7 @@ msgstr "" "unsetenv` agora são necessárias para construir o Python. (Contribuição de " "Victor Stinner em :issue:`39395`.)" -#: ../../whatsnew/3.9.rst:1237 +#: ../../whatsnew/3.9.rst:1238 msgid "" "On non-Windows platforms, creating ``bdist_wininst`` installers is now " "officially unsupported. (See :issue:`10945` for more details.)" @@ -2464,7 +2714,7 @@ msgstr "" "Em plataformas não-Windows, a criação de instaladores ``bdist_wininst`` não " "possui mais suporte oficial. (Veja :issue:`10945` para mais detalhes.)" -#: ../../whatsnew/3.9.rst:1240 +#: ../../whatsnew/3.9.rst:1241 msgid "" "When building Python on macOS from source, ``_tkinter`` now links with non-" "system Tcl and Tk frameworks if they are installed in ``/Library/" @@ -2483,7 +2733,7 @@ msgstr "" "include`` e ``--with-tcltk-libs``. (Contribuição de Ned Deily em :issue:" "`34956`.)" -#: ../../whatsnew/3.9.rst:1249 +#: ../../whatsnew/3.9.rst:1250 msgid "" "Python can now be built for Windows 10 ARM64. (Contributed by Steve Dower " "in :issue:`33125`.)" @@ -2491,7 +2741,7 @@ msgstr "" "Python pode agora ser construído para Windows 10 ARM64. (Contribuição de " "Steve Dower em :issue:`33125`.)" -#: ../../whatsnew/3.9.rst:1252 +#: ../../whatsnew/3.9.rst:1253 msgid "" "Some individual tests are now skipped when ``--pgo`` is used. The tests in " "question increased the PGO task time significantly and likely didn't help " @@ -2521,11 +2771,11 @@ msgstr "" "ferramentas do compilador. (Veja :issue:`36044` e :issue:`37707` para mais " "detalhes.)" -#: ../../whatsnew/3.9.rst:1267 +#: ../../whatsnew/3.9.rst:1268 msgid "C API Changes" msgstr "Alterações na API C" -#: ../../whatsnew/3.9.rst:1272 +#: ../../whatsnew/3.9.rst:1273 msgid "" ":pep:`573`: Added :c:func:`PyType_FromModuleAndSpec` to associate a module " "with a class; :c:func:`PyType_GetModule` and :c:func:`PyType_GetModuleState` " @@ -2540,7 +2790,7 @@ msgstr "" "classe na qual ela foi definida. (Contribuição de Marcel Plch e Petr " "Viktorin em :issue:`38787`.)" -#: ../../whatsnew/3.9.rst:1279 +#: ../../whatsnew/3.9.rst:1280 msgid "" "Added :c:func:`PyFrame_GetCode` function: get a frame code. Added :c:func:" "`PyFrame_GetBack` function: get the frame next outer frame. (Contributed by " @@ -2550,7 +2800,7 @@ msgstr "" "Adiciona a função :c:func:`PyFrame_GetBack`: obtém o próximo quadro externo. " "(Contribuição de Victor Stinner em :issue:`40421`.)" -#: ../../whatsnew/3.9.rst:1283 +#: ../../whatsnew/3.9.rst:1284 msgid "" "Added :c:func:`PyFrame_GetLineNumber` to the limited C API. (Contributed by " "Victor Stinner in :issue:`40421`.)" @@ -2558,7 +2808,7 @@ msgstr "" "Adicionada :c:func:`PyFrame_GetLineNumber` à API C limitada. (Contribuição " "de Victor Stinner em :issue:`40421`.)" -#: ../../whatsnew/3.9.rst:1286 +#: ../../whatsnew/3.9.rst:1287 msgid "" "Added :c:func:`PyThreadState_GetInterpreter` and :c:func:" "`PyInterpreterState_Get` functions to get the interpreter. Added :c:func:" @@ -2574,7 +2824,7 @@ msgstr "" "identificador único de um estado de thread do Python. (Contribuição de " "Victor Stinner em :issue:`39947`.)" -#: ../../whatsnew/3.9.rst:1294 +#: ../../whatsnew/3.9.rst:1295 msgid "" "Added a new public :c:func:`PyObject_CallNoArgs` function to the C API, " "which calls a callable Python object without any arguments. It is the most " @@ -2586,13 +2836,13 @@ msgstr "" "eficiente de chamar um objeto chamável Python sem nenhum argumento. " "(Contribuição de Victor Stinner em :issue:`37194`.)" -#: ../../whatsnew/3.9.rst:1299 ../../whatsnew/3.9.rst:1417 +#: ../../whatsnew/3.9.rst:1300 ../../whatsnew/3.9.rst:1418 msgid "Changes in the limited C API (if ``Py_LIMITED_API`` macro is defined):" msgstr "" "Alterações na API C limitada (se a macro ``Py_LIMITED_API`` estiver " "definida):" -#: ../../whatsnew/3.9.rst:1301 +#: ../../whatsnew/3.9.rst:1302 msgid "" "Provide :c:func:`Py_EnterRecursiveCall` and :c:func:`Py_LeaveRecursiveCall` " "as regular functions for the limited API. Previously, there were defined as " @@ -2606,7 +2856,7 @@ msgstr "" "pode acessar o campo ``PyThreadState.recursion_depth`` (a estrutura não é " "visível na API C limitada)." -#: ../../whatsnew/3.9.rst:1307 +#: ../../whatsnew/3.9.rst:1308 msgid "" "``PyObject_INIT()`` and ``PyObject_INIT_VAR()`` become regular \"opaque\" " "function to hide implementation details." @@ -2614,11 +2864,11 @@ msgstr "" "``PyObject_INIT()`` e ``PyObject_INIT_VAR()`` se uma função regular não " "visível para ocultar os detalhes da implementação." -#: ../../whatsnew/3.9.rst:1310 ../../whatsnew/3.9.rst:1444 +#: ../../whatsnew/3.9.rst:1311 ../../whatsnew/3.9.rst:1445 msgid "(Contributed by Victor Stinner in :issue:`38644` and :issue:`39542`.)" msgstr "(Contribuição de Victor Stinner em :issue:`38644` e :issue:`39542`.)" -#: ../../whatsnew/3.9.rst:1312 +#: ../../whatsnew/3.9.rst:1313 msgid "" "The :c:func:`PyModule_AddType` function is added to help adding a type to a " "module. (Contributed by Donghee Na in :issue:`40024`.)" @@ -2626,7 +2876,7 @@ msgstr "" "A função :c:func:`PyModule_AddType` é adicionado para ajudar a adicionar um " "tipo a um módulo. (Contribuição de Donghee Na em :issue:`40024`.)" -#: ../../whatsnew/3.9.rst:1316 +#: ../../whatsnew/3.9.rst:1317 msgid "" "Added the functions :c:func:`PyObject_GC_IsTracked` and :c:func:" "`PyObject_GC_IsFinalized` to the public API to allow to query if Python " @@ -2639,7 +2889,7 @@ msgstr "" "objetos Python estão sendo rastreados ou já foram finalizados pelo coletor " "de lixo, respectivamente. (Contribuição de Pablo Galindo em :issue:`40241`.)" -#: ../../whatsnew/3.9.rst:1322 +#: ../../whatsnew/3.9.rst:1323 msgid "" "Added :c:func:`!_PyObject_FunctionStr` to get a user-friendly string " "representation of a function-like object. (Patch by Jeroen Demeyer in :issue:" @@ -2649,7 +2899,7 @@ msgstr "" "amigável para o usuário de strings de um objeto função ou similar. (Patch " "por Jeroen Demeyer em :issue:`37645`.)" -#: ../../whatsnew/3.9.rst:1326 +#: ../../whatsnew/3.9.rst:1327 msgid "" "Added :c:func:`PyObject_CallOneArg` for calling an object with one " "positional argument (Patch by Jeroen Demeyer in :issue:`37483`.)" @@ -2657,7 +2907,7 @@ msgstr "" "Adicionada :c:func:`PyObject_CallOneArg` para chamar um objeto com um " "argumento posicional (Patch de Jeroen Demeyer em :issue:`37483`.)" -#: ../../whatsnew/3.9.rst:1334 +#: ../../whatsnew/3.9.rst:1335 msgid "" "``PyInterpreterState.eval_frame`` (:pep:`523`) now requires a new mandatory " "*tstate* parameter (``PyThreadState*``). (Contributed by Victor Stinner in :" @@ -2667,7 +2917,7 @@ msgstr "" "*tstate* obrigatório (``PyThreadState*``). (Contribuição de Victor Stinner " "em :issue:`38500`.)" -#: ../../whatsnew/3.9.rst:1338 +#: ../../whatsnew/3.9.rst:1339 msgid "" "Extension modules: :c:member:`~PyModuleDef.m_traverse`, :c:member:" "`~PyModuleDef.m_clear` and :c:member:`~PyModuleDef.m_free` functions of :c:" @@ -2687,14 +2937,14 @@ msgstr "" "m_size` for maior que 0 e o estado do módulo (como retornado por :c:func:" "`PyModule_GetState`) for ``NULL``." -#: ../../whatsnew/3.9.rst:1347 +#: ../../whatsnew/3.9.rst:1348 msgid "" "Extension modules without module state (``m_size <= 0``) are not affected." msgstr "" "Módulos de extensão sem um estado de módulo (``m_size <= 0``) não são " "afetados." -#: ../../whatsnew/3.9.rst:1349 +#: ../../whatsnew/3.9.rst:1350 msgid "" "If :c:func:`Py_AddPendingCall` is called in a subinterpreter, the function " "is now scheduled to be called from the subinterpreter, rather than being " @@ -2707,7 +2957,7 @@ msgstr "" "agora tem sua própria lista de chamadas programadas. (Contribuição de Victor " "Stinner em :issue:`39984`.)" -#: ../../whatsnew/3.9.rst:1355 +#: ../../whatsnew/3.9.rst:1356 msgid "" "The Windows registry is no longer used to initialize :data:`sys.path` when " "the ``-E`` option is used (if :c:member:`PyConfig.use_environment` is set to " @@ -2719,7 +2969,7 @@ msgstr "" "estiver definido como ``0``). Isso é significativo ao incorporar Python no " "Windows. (Contribuição de Zackery Spytz na :issue:`8901`.)" -#: ../../whatsnew/3.9.rst:1360 +#: ../../whatsnew/3.9.rst:1361 msgid "" "The global variable :c:data:`PyStructSequence_UnnamedField` is now a " "constant and refers to a constant string. (Contributed by Serhiy Storchaka " @@ -2729,7 +2979,7 @@ msgstr "" "constante e se refere a uma string constante. (Contribuição de Serhiy " "Storchaka em :issue:`38650`.)" -#: ../../whatsnew/3.9.rst:1364 +#: ../../whatsnew/3.9.rst:1365 msgid "" "The :c:type:`!PyGC_Head` structure is now opaque. It is only defined in the " "internal C API (``pycore_gc.h``). (Contributed by Victor Stinner in :issue:" @@ -2739,7 +2989,7 @@ msgstr "" "interna (``pycore_gc.h``). (Contribuição de Victor Stinner em :issue:" "`40241`.)" -#: ../../whatsnew/3.9.rst:1368 +#: ../../whatsnew/3.9.rst:1369 msgid "" "The ``Py_UNICODE_COPY``, ``Py_UNICODE_FILL``, ``PyUnicode_WSTR_LENGTH``, :c:" "func:`!PyUnicode_FromUnicode`, :c:func:`!PyUnicode_AsUnicode`, " @@ -2753,7 +3003,7 @@ msgstr "" "marcadas como descontinuadas no C. Elas foram descontinuadas pela :pep:`393` " "desde Python 3.3. (Contribuição de Inada Naoki em :issue:`36346`.)" -#: ../../whatsnew/3.9.rst:1375 +#: ../../whatsnew/3.9.rst:1376 msgid "" "The :c:func:`Py_FatalError` function is replaced with a macro which logs " "automatically the name of the current function, unless the " @@ -2765,7 +3015,7 @@ msgstr "" "``Py_LIMITED_API`` seja definida. (Contribuição de Victor Stinner em :issue:" "`39882`.)" -#: ../../whatsnew/3.9.rst:1380 +#: ../../whatsnew/3.9.rst:1381 msgid "" "The vectorcall protocol now requires that the caller passes only strings as " "keyword names. (See :issue:`37540` for more information.)" @@ -2773,18 +3023,18 @@ msgstr "" "O protocolo vectorcall agora exige que o chamador passe apenas strings como " "nomes de argumentos. (Veja :issue:`37540` para mais informações.)" -#: ../../whatsnew/3.9.rst:1383 +#: ../../whatsnew/3.9.rst:1384 msgid "" "Implementation details of a number of macros and functions are now hidden:" msgstr "" "Os detalhes de implementação de uma série de macros e funções agora estão " "ocultos:" -#: ../../whatsnew/3.9.rst:1385 +#: ../../whatsnew/3.9.rst:1386 msgid ":c:func:`PyObject_IS_GC` macro was converted to a function." msgstr "A macro :c:func:`PyObject_IS_GC` foi convertida para uma função." -#: ../../whatsnew/3.9.rst:1387 +#: ../../whatsnew/3.9.rst:1388 msgid "" "The :c:func:`!PyObject_NEW` macro becomes an alias to the :c:macro:" "`PyObject_New` macro, and the :c:func:`!PyObject_NEW_VAR` macro becomes an " @@ -2796,7 +3046,7 @@ msgstr "" "para a macro :c:macro:`PyObject_NewVar`. Elas não acessam mais diretamente o " "membro :c:member:`PyTypeObject.tp_basicsize`." -#: ../../whatsnew/3.9.rst:1392 +#: ../../whatsnew/3.9.rst:1393 msgid "" ":c:func:`!PyObject_GET_WEAKREFS_LISTPTR` macro was converted to a function: " "the macro accessed directly the :c:member:`PyTypeObject.tp_weaklistoffset` " @@ -2806,7 +3056,7 @@ msgstr "" "função: a macro acessava diretamente o membro :c:member:`PyTypeObject." "tp_weaklistoffset`." -#: ../../whatsnew/3.9.rst:1396 +#: ../../whatsnew/3.9.rst:1397 msgid "" ":c:func:`PyObject_CheckBuffer` macro was converted to a function: the macro " "accessed directly the :c:member:`PyTypeObject.tp_as_buffer` member." @@ -2814,7 +3064,7 @@ msgstr "" "A macro :c:func:`PyObject_CheckBuffer` foi convertida para uma função: a " "macro acessava diretamente o membro :c:member:`PyTypeObject.tp_as_buffer`." -#: ../../whatsnew/3.9.rst:1399 +#: ../../whatsnew/3.9.rst:1400 msgid "" ":c:func:`PyIndex_Check` is now always declared as an opaque function to hide " "implementation details: removed the ``PyIndex_Check()`` macro. The macro " @@ -2824,11 +3074,11 @@ msgstr "" "ocultar detalhes da implementação: removida a macro ``PyIndex_Check()``. A " "macro acessava diretamente o membro :c:member:`PyTypeObject.tp_as_number`." -#: ../../whatsnew/3.9.rst:1403 +#: ../../whatsnew/3.9.rst:1404 msgid "(See :issue:`40170` for more details.)" msgstr "(Veja :issue:`40170` para mais detalhes.)" -#: ../../whatsnew/3.9.rst:1408 +#: ../../whatsnew/3.9.rst:1409 msgid "" "Excluded ``PyFPE_START_PROTECT()`` and ``PyFPE_END_PROTECT()`` macros of " "``pyfpe.h`` from the limited C API. (Contributed by Victor Stinner in :issue:" @@ -2838,7 +3088,7 @@ msgstr "" "``pyfpe.h`` da API C limitada. (Contribuição por Victor Stinner em :issue:" "`38835`.)" -#: ../../whatsnew/3.9.rst:1412 +#: ../../whatsnew/3.9.rst:1413 msgid "" "The ``tp_print`` slot of :ref:`PyTypeObject ` has been " "removed. It was used for printing objects to files in Python 2.7 and before. " @@ -2850,11 +3100,11 @@ msgstr "" "Desde Python 3.0, ele era ignorado e não utilizado. (Contribuição de Jeroen " "Demeyer em :issue:`36974`.)" -#: ../../whatsnew/3.9.rst:1419 +#: ../../whatsnew/3.9.rst:1420 msgid "Excluded the following functions from the limited C API:" msgstr "Excluídas as seguintes funções da API C limitada:" -#: ../../whatsnew/3.9.rst:1421 +#: ../../whatsnew/3.9.rst:1422 msgid "" "``PyThreadState_DeleteCurrent()`` (Contributed by Joannah Nanjekye in :issue:" "`37878`.)" @@ -2862,80 +3112,80 @@ msgstr "" "``PyThreadState_DeleteCurrent()`` (Contribuição de Joannah Nanjekye em :" "issue:`37878`.)" -#: ../../whatsnew/3.9.rst:1423 +#: ../../whatsnew/3.9.rst:1424 msgid "``_Py_CheckRecursionLimit``" msgstr "``_Py_CheckRecursionLimit``" -#: ../../whatsnew/3.9.rst:1424 +#: ../../whatsnew/3.9.rst:1425 msgid "``_Py_NewReference()``" msgstr "``_Py_NewReference()``" -#: ../../whatsnew/3.9.rst:1425 +#: ../../whatsnew/3.9.rst:1426 msgid "``_Py_ForgetReference()``" msgstr "``_Py_ForgetReference()``" -#: ../../whatsnew/3.9.rst:1426 +#: ../../whatsnew/3.9.rst:1427 msgid "``_PyTraceMalloc_NewReference()``" msgstr "``_PyTraceMalloc_NewReference()``" -#: ../../whatsnew/3.9.rst:1427 +#: ../../whatsnew/3.9.rst:1428 msgid "``_Py_GetRefTotal()``" msgstr "``_Py_GetRefTotal()``" -#: ../../whatsnew/3.9.rst:1428 +#: ../../whatsnew/3.9.rst:1429 msgid "The trashcan mechanism which never worked in the limited C API." msgstr "O mecanismo trashcan que nunca funcionou na API C limitada." -#: ../../whatsnew/3.9.rst:1429 +#: ../../whatsnew/3.9.rst:1430 msgid "``PyTrash_UNWIND_LEVEL``" msgstr "``PyTrash_UNWIND_LEVEL``" -#: ../../whatsnew/3.9.rst:1430 +#: ../../whatsnew/3.9.rst:1431 msgid "``Py_TRASHCAN_BEGIN_CONDITION``" msgstr "``Py_TRASHCAN_BEGIN_CONDITION``" -#: ../../whatsnew/3.9.rst:1431 +#: ../../whatsnew/3.9.rst:1432 msgid "``Py_TRASHCAN_BEGIN``" msgstr "``Py_TRASHCAN_BEGIN``" -#: ../../whatsnew/3.9.rst:1432 +#: ../../whatsnew/3.9.rst:1433 msgid "``Py_TRASHCAN_END``" msgstr "``Py_TRASHCAN_END``" -#: ../../whatsnew/3.9.rst:1433 +#: ../../whatsnew/3.9.rst:1434 msgid "``Py_TRASHCAN_SAFE_BEGIN``" msgstr "``Py_TRASHCAN_SAFE_BEGIN``" -#: ../../whatsnew/3.9.rst:1434 +#: ../../whatsnew/3.9.rst:1435 msgid "``Py_TRASHCAN_SAFE_END``" msgstr "``Py_TRASHCAN_SAFE_END``" -#: ../../whatsnew/3.9.rst:1436 +#: ../../whatsnew/3.9.rst:1437 msgid "Moved following functions and definitions to the internal C API:" msgstr "Movidas as seguintes funções e definições para a API C interna:" -#: ../../whatsnew/3.9.rst:1438 +#: ../../whatsnew/3.9.rst:1439 msgid "``_PyDebug_PrintTotalRefs()``" msgstr "``_PyDebug_PrintTotalRefs()``" -#: ../../whatsnew/3.9.rst:1439 +#: ../../whatsnew/3.9.rst:1440 msgid "``_Py_PrintReferences()``" msgstr "``_Py_PrintReferences()``" -#: ../../whatsnew/3.9.rst:1440 +#: ../../whatsnew/3.9.rst:1441 msgid "``_Py_PrintReferenceAddresses()``" msgstr "``_Py_PrintReferenceAddresses()``" -#: ../../whatsnew/3.9.rst:1441 +#: ../../whatsnew/3.9.rst:1442 msgid "``_Py_tracemalloc_config``" msgstr "``_Py_tracemalloc_config``" -#: ../../whatsnew/3.9.rst:1442 +#: ../../whatsnew/3.9.rst:1443 msgid "``_Py_AddToAllObjects()`` (specific to ``Py_TRACE_REFS`` build)" msgstr "" "``_Py_AddToAllObjects()`` (específico para construção de ``Py_TRACE_REFS``)" -#: ../../whatsnew/3.9.rst:1446 +#: ../../whatsnew/3.9.rst:1447 msgid "" "Removed ``_PyRuntime.getframe`` hook and removed ``_PyThreadState_GetFrame`` " "macro which was an alias to ``_PyRuntime.getframe``. They were only exposed " @@ -2947,7 +3197,7 @@ msgstr "" "Eles eram os únicos expostos pela API C interna. Removido também o tipo " "``PyThreadFrameGetter``. (Contribuição de Victor Stinner em :issue:`39946`.)" -#: ../../whatsnew/3.9.rst:1451 +#: ../../whatsnew/3.9.rst:1452 msgid "" "Removed the following functions from the C API. Call :c:func:`PyGC_Collect` " "explicitly to clear all free lists. (Contributed by Inada Naoki and Victor " @@ -2957,31 +3207,31 @@ msgstr "" "explicitamente para limpar todas as listas livres. (Contribuição de Inada " "Naoki e Victor Stinner em :issue:`37340`, :issue:`38896` e :issue:`40428`.)" -#: ../../whatsnew/3.9.rst:1456 +#: ../../whatsnew/3.9.rst:1457 msgid "``PyAsyncGen_ClearFreeLists()``" msgstr "``PyAsyncGen_ClearFreeLists()``" -#: ../../whatsnew/3.9.rst:1457 +#: ../../whatsnew/3.9.rst:1458 msgid "``PyContext_ClearFreeList()``" msgstr "``PyContext_ClearFreeList()``" -#: ../../whatsnew/3.9.rst:1458 +#: ../../whatsnew/3.9.rst:1459 msgid "``PyDict_ClearFreeList()``" msgstr "``PyDict_ClearFreeList()``" -#: ../../whatsnew/3.9.rst:1459 +#: ../../whatsnew/3.9.rst:1460 msgid "``PyFloat_ClearFreeList()``" msgstr "``PyFloat_ClearFreeList()``" -#: ../../whatsnew/3.9.rst:1460 +#: ../../whatsnew/3.9.rst:1461 msgid "``PyFrame_ClearFreeList()``" msgstr "``PyFrame_ClearFreeList()``" -#: ../../whatsnew/3.9.rst:1461 +#: ../../whatsnew/3.9.rst:1462 msgid "``PyList_ClearFreeList()``" msgstr "``PyList_ClearFreeList()``" -#: ../../whatsnew/3.9.rst:1462 +#: ../../whatsnew/3.9.rst:1463 msgid "" "``PyMethod_ClearFreeList()`` and ``PyCFunction_ClearFreeList()``: the free " "lists of bound method objects have been removed." @@ -2989,18 +3239,18 @@ msgstr "" "``PyMethod_ClearFreeList()`` e ``PyCFunction_ClearFreeList()``: as listas " "livres de objetos de método vinculado foram removidas." -#: ../../whatsnew/3.9.rst:1464 +#: ../../whatsnew/3.9.rst:1465 msgid "" "``PySet_ClearFreeList()``: the set free list has been removed in Python 3.4." msgstr "" "``PySet_ClearFreeList()``: a definição de lista livres foi removida no " "Python 3.4." -#: ../../whatsnew/3.9.rst:1466 +#: ../../whatsnew/3.9.rst:1467 msgid "``PyTuple_ClearFreeList()``" msgstr "``PyTuple_ClearFreeList()``" -#: ../../whatsnew/3.9.rst:1467 +#: ../../whatsnew/3.9.rst:1468 msgid "" "``PyUnicode_ClearFreeList()``: the Unicode free list has been removed in " "Python 3.3." @@ -3008,7 +3258,7 @@ msgstr "" "``PyUnicode_ClearFreeList()``: a lista livre de Unicode foi removida no " "Python 3.3." -#: ../../whatsnew/3.9.rst:1470 +#: ../../whatsnew/3.9.rst:1471 msgid "" "Removed ``_PyUnicode_ClearStaticStrings()`` function. (Contributed by Victor " "Stinner in :issue:`39465`.)" @@ -3016,7 +3266,7 @@ msgstr "" "Removida a função ``_PyUnicode_ClearStaticStrings()``. (Contribuição de " "Victor Stinner em :issue:`39465`.)" -#: ../../whatsnew/3.9.rst:1473 +#: ../../whatsnew/3.9.rst:1474 msgid "" "Removed ``Py_UNICODE_MATCH``. It has been deprecated by :pep:`393`, and " "broken since Python 3.3. The :c:func:`PyUnicode_Tailmatch` function can be " @@ -3026,7 +3276,7 @@ msgstr "" "quebrado desde o Python 3.3. A função :c:func:`PyUnicode_Tailmatch` pode ser " "usada em seu lugar. (Contribuição de Inada Naoki em :issue:`36346`.)" -#: ../../whatsnew/3.9.rst:1478 +#: ../../whatsnew/3.9.rst:1479 msgid "" "Cleaned header files of interfaces defined but with no implementation. The " "public API symbols being removed are: " @@ -3048,11 +3298,11 @@ msgstr "" "``PyNoArgsFunction``. (Contribuição de Pablo Galindo Salgado em :issue:" "`39372`.)" -#: ../../whatsnew/3.9.rst:1489 +#: ../../whatsnew/3.9.rst:1490 msgid "Notable changes in Python 3.9.1" msgstr "Alterações notáveis no Python 3.9.1" -#: ../../whatsnew/3.9.rst:1494 +#: ../../whatsnew/3.9.rst:1495 msgid "" "The behavior of :class:`typing.Literal` was changed to conform with :pep:" "`586` and to match the behavior of static type checkers specified in the PEP." @@ -3061,18 +3311,18 @@ msgstr "" "conformidade com a :pep:`586` e para corresponder ao comportamento de " "verificadores de tipo estático especificados na PEP." -#: ../../whatsnew/3.9.rst:1497 +#: ../../whatsnew/3.9.rst:1498 msgid "``Literal`` now de-duplicates parameters." msgstr "``Literal`` agora elimina a duplicação de parâmetros." -#: ../../whatsnew/3.9.rst:1498 +#: ../../whatsnew/3.9.rst:1499 msgid "" "Equality comparisons between ``Literal`` objects are now order independent." msgstr "" "Comparações de igualdade entre objetos ``Literal`` agora são independentes " "da ordem." -#: ../../whatsnew/3.9.rst:1499 +#: ../../whatsnew/3.9.rst:1500 msgid "" "``Literal`` comparisons now respect types. For example, ``Literal[0] == " "Literal[False]`` previously evaluated to ``True``. It is now ``False``. To " @@ -3084,7 +3334,7 @@ msgstr "" "é ``False``. Para oferecer suporte a essa mudança, o cache de tipo usado " "internamente agora oferece suporte a tipos de diferenciação." -#: ../../whatsnew/3.9.rst:1503 +#: ../../whatsnew/3.9.rst:1504 msgid "" "``Literal`` objects will now raise a :exc:`TypeError` exception during " "equality comparisons if any of their parameters are not :term:`hashable`. " @@ -3096,15 +3346,31 @@ msgstr "" "`hasheável`. Observe que declarar ``Literal`` com parâmetros mutáveis não " "gerará um erro::" -#: ../../whatsnew/3.9.rst:1515 +#: ../../whatsnew/3.9.rst:1509 +msgid "" +">>> from typing import Literal\n" +">>> Literal[{0}]\n" +">>> Literal[{0}] == Literal[{False}]\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: unhashable type: 'set'" +msgstr "" +">>> from typing import Literal\n" +">>> Literal[{0}]\n" +">>> Literal[{0}] == Literal[{False}]\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: unhashable type: 'set'" + +#: ../../whatsnew/3.9.rst:1516 msgid "(Contributed by Yurii Karabas in :issue:`42345`.)" msgstr "(Contribuição de Yurii Karabas em :issue:`42345`.)" -#: ../../whatsnew/3.9.rst:1518 +#: ../../whatsnew/3.9.rst:1519 msgid "macOS 11.0 (Big Sur) and Apple Silicon Mac support" msgstr "Suporte a macOS 11.0 (Big Sur) e Apple Silicon Mac" -#: ../../whatsnew/3.9.rst:1520 +#: ../../whatsnew/3.9.rst:1521 msgid "" "As of 3.9.1, Python now fully supports building and running on macOS 11.0 " "(Big Sur) and on Apple Silicon Macs (based on the ``ARM64`` architecture). A " @@ -3126,19 +3392,19 @@ msgstr "" "disponíveis condicionalmente com base na versão do sistema operacional em " "uso no tempo de execução (\"ligação fraca\")" -#: ../../whatsnew/3.9.rst:1529 +#: ../../whatsnew/3.9.rst:1530 msgid "(Contributed by Ronald Oussoren and Lawrence D'Anna in :issue:`41100`.)" msgstr "(Contribuição de Ronald Oussoren e Lawrence D'Anna em :issue:`41100`.)" -#: ../../whatsnew/3.9.rst:1532 +#: ../../whatsnew/3.9.rst:1533 msgid "Notable changes in Python 3.9.2" msgstr "Alterações notáveis no Python 3.9.2" -#: ../../whatsnew/3.9.rst:1535 +#: ../../whatsnew/3.9.rst:1536 msgid "collections.abc" msgstr "collections.abc" -#: ../../whatsnew/3.9.rst:1537 +#: ../../whatsnew/3.9.rst:1538 msgid "" ":class:`collections.abc.Callable` generic now flattens type parameters, " "similar to what :data:`typing.Callable` currently does. This means that " @@ -3167,11 +3433,11 @@ msgstr "" "uma :exc:`TypeError` no Python 3.10. (Contribuição de Ken Jin em :issue:" "`42195`.)" -#: ../../whatsnew/3.9.rst:1551 ../../whatsnew/3.9.rst:1576 +#: ../../whatsnew/3.9.rst:1552 ../../whatsnew/3.9.rst:1577 msgid "urllib.parse" msgstr "urllib.parse" -#: ../../whatsnew/3.9.rst:1553 +#: ../../whatsnew/3.9.rst:1554 msgid "" "Earlier Python versions allowed using both ``;`` and ``&`` as query " "parameter separators in :func:`urllib.parse.parse_qs` and :func:`urllib." @@ -3192,11 +3458,11 @@ msgstr "" "obter mais detalhes, consulte sua respectiva documentação. (Contribuição de " "Adam Goldschmidt, Senthil Kumaran e Ken Jin em :issue:`42967`.)" -#: ../../whatsnew/3.9.rst:1564 +#: ../../whatsnew/3.9.rst:1565 msgid "Notable changes in Python 3.9.3" msgstr "Alterações notáveis no Python 3.9.3" -#: ../../whatsnew/3.9.rst:1566 +#: ../../whatsnew/3.9.rst:1567 msgid "" "A security fix alters the :class:`ftplib.FTP` behavior to not trust the IPv4 " "address sent from the remote server when setting up a passive data channel. " @@ -3211,11 +3477,11 @@ msgstr "" "atributo ``trust_server_pasv_ipv4_address`` em sua instância de FTP para " "``True``. (Veja :gh:`87451`)" -#: ../../whatsnew/3.9.rst:1573 +#: ../../whatsnew/3.9.rst:1574 msgid "Notable changes in Python 3.9.5" msgstr "Alterações notáveis no Python 3.9.5" -#: ../../whatsnew/3.9.rst:1578 +#: ../../whatsnew/3.9.rst:1579 msgid "" "The presence of newline or tab characters in parts of a URL allows for some " "forms of attacks. Following the WHATWG specification that updates :rfc:" @@ -3232,11 +3498,11 @@ msgstr "" "uma nova variável de nível de módulo ``urllib.parse." "_UNSAFE_URL_BYTES_TO_REMOVE``. (Veja :gh:`88048`)" -#: ../../whatsnew/3.9.rst:1586 +#: ../../whatsnew/3.9.rst:1587 msgid "Notable security feature in 3.9.14" msgstr "Recursos de segurança notáveis no 3.9.14" -#: ../../whatsnew/3.9.rst:1588 +#: ../../whatsnew/3.9.rst:1589 msgid "" "Converting between :class:`int` and :class:`str` in bases other than 2 " "(binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal) " @@ -3259,15 +3525,15 @@ msgstr "" "inteira `. O limite padrão é de 4300 dígitos em forma de " "string." -#: ../../whatsnew/3.9.rst:1599 +#: ../../whatsnew/3.9.rst:1600 msgid "Notable changes in 3.9.17" msgstr "Alterações notáveis no 3.9.17" -#: ../../whatsnew/3.9.rst:1602 +#: ../../whatsnew/3.9.rst:1603 msgid "tarfile" msgstr "tarfile" -#: ../../whatsnew/3.9.rst:1604 +#: ../../whatsnew/3.9.rst:1605 msgid "" "The extraction methods in :mod:`tarfile`, and :func:`shutil.unpack_archive`, " "have a new a *filter* argument that allows limiting tar features than may be " diff --git a/whatsnew/changelog.po b/whatsnew/changelog.po index b19aa49a5..c7a41b327 100644 --- a/whatsnew/changelog.po +++ b/whatsnew/changelog.po @@ -1,29 +1,81946 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software Foundation +# Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: -# Claudio Rogerio Carvalho Filho , 2021 +# Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-24 14:15+0000\n" -"PO-Revision-Date: 2021-06-29 13:04+0000\n" -"Last-Translator: Claudio Rogerio Carvalho Filho , " -"2021\n" +"POT-Creation-Date: 2025-05-23 14:55+0000\n" +"PO-Revision-Date: 2025-05-08 05:10+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" -#: ../../whatsnew/changelog.rst:5 +#: ../../whatsnew/changelog.rst:7 msgid "Changelog" msgstr "Changelog" + +#: ../NEWS:3 +msgid "Python next" +msgstr "Python seguinte" + +#: ../NEWS:5 +msgid "*Release date: XXXX-XX-XX*" +msgstr "*Data de lançamento: XXXX-XX-XX*" + +#: ../NEWS:8 ../NEWS:322 ../NEWS:702 ../NEWS:1064 ../NEWS:1787 ../NEWS:1950 +#: ../NEWS:3010 ../NEWS:3628 ../NEWS:4105 ../NEWS:4590 ../NEWS:5100 +#: ../NEWS:5959 ../NEWS:6540 ../NEWS:8781 ../NEWS:9997 ../NEWS:10374 +#: ../NEWS:10660 ../NEWS:10946 ../NEWS:11343 ../NEWS:11681 ../NEWS:12106 +#: ../NEWS:14067 ../NEWS:15061 ../NEWS:15654 ../NEWS:16139 ../NEWS:16519 +#: ../NEWS:16962 ../NEWS:17446 ../NEWS:17903 ../NEWS:19677 ../NEWS:20497 +#: ../NEWS:20950 ../NEWS:21222 ../NEWS:21499 ../NEWS:22321 ../NEWS:22760 +#: ../NEWS:23790 ../NEWS:24259 ../NEWS:24719 ../NEWS:25177 ../NEWS:25568 +#: ../NEWS:26346 ../NEWS:27958 ../NEWS:29026 ../NEWS:29535 ../NEWS:29904 +#: ../NEWS:30149 ../NEWS:32739 ../NEWS:33284 ../NEWS:33667 ../NEWS:33875 +#: ../NEWS:34122 ../NEWS:34461 ../NEWS:34767 ../NEWS:35302 ../NEWS:37412 +#: ../NEWS:38009 ../NEWS:38340 ../NEWS:38751 ../NEWS:39129 ../NEWS:39700 +#: ../NEWS:39949 ../NEWS:40079 ../NEWS:40369 ../NEWS:40610 ../NEWS:41140 +#: ../NEWS:41372 ../NEWS:41875 ../NEWS:43144 ../NEWS:43649 ../NEWS:44283 +#: ../NEWS:45078 ../NEWS:45125 ../NEWS:45582 ../NEWS:46871 ../NEWS:48685 +msgid "Windows" +msgstr "Windows" + +#: ../NEWS:10 +msgid "" +":gh:`130727`: Fix a race in internal calls into WMI that can result in an " +"\"invalid handle\" exception under high load. Patch by Chris Eibl." +msgstr "" + +#: ../NEWS:13 +msgid "" +":gh:`76023`: Make :func:`os.path.realpath` ignore Windows error 1005 when in " +"non-strict mode." +msgstr "" + +#: ../NEWS:16 +msgid "" +":gh:`133626`: Ensures packages are not accidentally bundled into the " +"traditional installer." +msgstr "" +":gh:`133626`: Garante que os pacotes não sejam acidentalmente agrupados no " +"instalador tradicional." + +#: ../NEWS:19 +msgid "" +":gh:`133512`: Add warnings to :ref:`launcher` about use of subcommands " +"belonging to the Python install manager." +msgstr "" + +#: ../NEWS:23 ../NEWS:346 ../NEWS:718 ../NEWS:1101 ../NEWS:1799 ../NEWS:1969 +#: ../NEWS:2220 ../NEWS:2340 ../NEWS:2981 ../NEWS:4069 ../NEWS:4532 +#: ../NEWS:5075 ../NEWS:5890 ../NEWS:6482 ../NEWS:8446 ../NEWS:9937 +#: ../NEWS:10356 ../NEWS:10630 ../NEWS:10907 ../NEWS:11313 ../NEWS:11638 +#: ../NEWS:12050 ../NEWS:13831 ../NEWS:15015 ../NEWS:15598 ../NEWS:16087 +#: ../NEWS:16435 ../NEWS:16888 ../NEWS:17296 ../NEWS:17799 ../NEWS:19509 +#: ../NEWS:20465 ../NEWS:20919 ../NEWS:21193 ../NEWS:21463 ../NEWS:21816 +#: ../NEWS:22262 ../NEWS:22737 ../NEWS:23718 ../NEWS:24240 ../NEWS:24681 +#: ../NEWS:25144 ../NEWS:25554 ../NEWS:26281 ../NEWS:27716 ../NEWS:28967 +#: ../NEWS:29420 ../NEWS:29877 ../NEWS:30116 ../NEWS:32454 ../NEWS:33490 +#: ../NEWS:33644 ../NEWS:33860 ../NEWS:34112 ../NEWS:34426 ../NEWS:34758 +#: ../NEWS:35242 ../NEWS:37237 ../NEWS:37981 ../NEWS:38094 ../NEWS:38319 +#: ../NEWS:38709 ../NEWS:39107 ../NEWS:39686 ../NEWS:39997 ../NEWS:40248 +#: ../NEWS:40383 ../NEWS:40654 ../NEWS:41084 ../NEWS:41357 ../NEWS:41611 +#: ../NEWS:41865 ../NEWS:43038 ../NEWS:43598 ../NEWS:44252 ../NEWS:44373 +#: ../NEWS:44996 ../NEWS:45558 ../NEWS:45802 ../NEWS:45979 ../NEWS:46288 +#: ../NEWS:46517 ../NEWS:46727 ../NEWS:48538 +msgid "Tests" +msgstr "Testes" + +#: ../NEWS:25 +msgid "" +":gh:`133744`: Fix multiprocessing interrupt test. Add an event to " +"synchronize the parent process with the child process: wait until the child " +"process starts sleeping. Patch by Victor Stinner." +msgstr "" + +#: ../NEWS:29 +msgid "" +":gh:`133639`: Fix ``TestPyReplAutoindent.test_auto_indent_default()`` " +"doesn't run ``input_code``." +msgstr "" +":gh:`133639`: Corrige ``TestPyReplAutoindent.test_auto_indent_default()`` " +"não executa ``input_code``." + +#: ../NEWS:32 +msgid "" +":gh:`133131`: The iOS testbed will now select the most recently released " +"\"SE-class\" device for testing if a device isn't explicitly specified." +msgstr "" +":gh:`133131`: O ambiente de testes do iOS agora selecionará o dispositivo " +"\"classe SE\" lançado mais recentemente para testes, caso um dispositivo não " +"seja especificado explicitamente." + +#: ../NEWS:35 +msgid "" +":gh:`109981`: The test helper that counts the list of open file descriptors " +"now uses the optimised ``/dev/fd`` approach on all Apple platforms, not just " +"macOS. This avoids crashes caused by guarded file descriptors." +msgstr "" +":gh:`109981`: O auxiliar de teste que conta a lista de descritores de " +"arquivo abertos agora usa a abordagem otimizada ``/dev/fd`` em todas as " +"plataformas Apple, não apenas no macOS. Isso evita travamentos causados ​​por " +"descritores de arquivo protegidos." + +#: ../NEWS:40 ../NEWS:363 ../NEWS:729 ../NEWS:1114 ../NEWS:1978 ../NEWS:2230 +#: ../NEWS:2768 ../NEWS:3068 ../NEWS:4205 ../NEWS:4649 ../NEWS:5205 +#: ../NEWS:6724 ../NEWS:9203 ../NEWS:10400 ../NEWS:10721 ../NEWS:11403 +#: ../NEWS:11738 ../NEWS:12173 ../NEWS:14393 ../NEWS:18014 ../NEWS:19918 +#: ../NEWS:20623 ../NEWS:21048 ../NEWS:21282 ../NEWS:21906 ../NEWS:22479 +#: ../NEWS:22829 ../NEWS:23998 ../NEWS:24351 ../NEWS:24803 ../NEWS:25309 +#: ../NEWS:26010 ../NEWS:26395 ../NEWS:28348 ../NEWS:29106 ../NEWS:29650 +#: ../NEWS:30181 ../NEWS:33711 ../NEWS:33929 ../NEWS:35657 ../NEWS:38110 +#: ../NEWS:38877 ../NEWS:39341 ../NEWS:39368 ../NEWS:41412 ../NEWS:41623 +#: ../NEWS:41914 ../NEWS:43210 ../NEWS:43269 ../NEWS:43686 ../NEWS:44389 +msgid "Security" +msgstr "Segurança" + +#: ../NEWS:42 +msgid "" +":gh:`133767`: Fix use-after-free in the \"unicode-escape\" decoder with a " +"non-\"strict\" error handler." +msgstr "" + +#: ../NEWS:46 ../NEWS:383 ../NEWS:762 ../NEWS:1127 ../NEWS:1804 ../NEWS:1986 +#: ../NEWS:2245 ../NEWS:2358 ../NEWS:2598 ../NEWS:2843 ../NEWS:3271 +#: ../NEWS:3825 ../NEWS:4281 ../NEWS:4767 ../NEWS:5373 ../NEWS:6260 +#: ../NEWS:7385 ../NEWS:9437 ../NEWS:10189 ../NEWS:10501 ../NEWS:10795 +#: ../NEWS:11088 ../NEWS:11486 ../NEWS:11912 ../NEWS:12827 ../NEWS:14596 +#: ../NEWS:15267 ../NEWS:15906 ../NEWS:16300 ../NEWS:16719 ../NEWS:17132 +#: ../NEWS:17597 ../NEWS:18561 ../NEWS:20105 ../NEWS:20737 ../NEWS:21120 +#: ../NEWS:21344 ../NEWS:21618 ../NEWS:22015 ../NEWS:22570 ../NEWS:23190 +#: ../NEWS:24062 ../NEWS:24450 ../NEWS:24937 ../NEWS:25397 ../NEWS:25759 +#: ../NEWS:26105 ../NEWS:26761 ../NEWS:28527 ../NEWS:29194 ../NEWS:29737 +#: ../NEWS:30032 ../NEWS:30783 ../NEWS:33191 ../NEWS:33224 ../NEWS:33352 +#: ../NEWS:33560 ../NEWS:33751 ../NEWS:33956 ../NEWS:34254 ../NEWS:34575 +#: ../NEWS:34900 ../NEWS:35490 ../NEWS:36150 ../NEWS:37820 ../NEWS:38166 +#: ../NEWS:38532 ../NEWS:38856 ../NEWS:38959 ../NEWS:39422 ../NEWS:39809 +#: ../NEWS:40112 ../NEWS:40194 ../NEWS:40297 ../NEWS:40467 ../NEWS:40802 +#: ../NEWS:41220 ../NEWS:41438 ../NEWS:41675 ../NEWS:42212 ../NEWS:43239 +#: ../NEWS:43257 ../NEWS:43345 ../NEWS:43826 ../NEWS:44541 ../NEWS:45205 +#: ../NEWS:45643 ../NEWS:45670 ../NEWS:45708 ../NEWS:45728 ../NEWS:45835 +#: ../NEWS:45929 ../NEWS:46025 ../NEWS:46100 ../NEWS:46358 ../NEWS:46581 +#: ../NEWS:46754 ../NEWS:47112 +msgid "Library" +msgstr "Biblioteca" + +#: ../NEWS:48 +msgid "" +":gh:`114177`: Fix :mod:`asyncio` to not close subprocess pipes which would " +"otherwise error out when the event loop is already closed." +msgstr "" + +#: ../NEWS:51 +msgid "" +":gh:`62184`: Remove import of C implementation of :class:`io.FileIO` from " +"Python implementation which has its own implementation" +msgstr "" + +#: ../NEWS:54 +msgid "" +":gh:`133982`: Emit :exc:`RuntimeWarning` in the Python implementation of :" +"mod:`io` when the :term:`file-like object ` is not closed " +"explicitly in the presence of multiple I/O layers." +msgstr "" + +#: ../NEWS:58 +msgid "" +":gh:`133890`: The :mod:`tarfile` module now handles :exc:" +"`UnicodeEncodeError` in the same way as :exc:`OSError` when cannot extract a " +"member." +msgstr "" + +#: ../NEWS:61 +msgid "" +":gh:`134097`: Fix interaction of the new :term:`REPL` and :option:`-X " +"showrefcount <-X>` command line option." +msgstr "" + +#: ../NEWS:64 +msgid "" +":gh:`133889`: The generated directory listing page in :class:`http.server." +"SimpleHTTPRequestHandler` now only shows the decoded path component of the " +"requested URL, and not the query and fragment." +msgstr "" + +#: ../NEWS:68 +msgid "" +":gh:`134098`: Fix handling paths that end with a percent-encoded slash " +"(``%2f`` or ``%2F``) in :class:`http.server.SimpleHTTPRequestHandler`." +msgstr "" + +#: ../NEWS:71 +msgid "" +":gh:`134062`: :mod:`ipaddress`: fix collisions in :meth:`~object.__hash__` " +"for :class:`~ipaddress.IPv4Network` and :class:`~ipaddress.IPv6Network` " +"objects." +msgstr "" + +#: ../NEWS:75 +msgid "" +":gh:`133745`: In 3.13.3 we accidentally changed the signature of the asyncio " +"``create_task()`` family of methods and how it calls a custom task factory " +"in a backwards incompatible way. Since some 3rd party libraries have already " +"made changes to work around the issue that might break if we simply reverted " +"the changes, we're instead changing things to be backwards compatible with " +"3.13.2 while still supporting those workarounds for 3.13.3. In particular, " +"the special-casing of ``name`` and ``context`` is back (until 3.14) and " +"consequently eager tasks may still find that their name hasn't been set " +"before they execute their first yielding await." +msgstr "" + +#: ../NEWS:85 +msgid "" +":gh:`71253`: Raise :exc:`ValueError` in :func:`open` if *opener* returns a " +"negative file-descriptor in the Python implementation of :mod:`io` to match " +"the C implementation." +msgstr "" + +#: ../NEWS:89 +msgid "" +":gh:`77057`: Fix handling of invalid markup declarations in :class:`html." +"parser.HTMLParser`." +msgstr "" + +#: ../NEWS:92 +msgid "" +":gh:`133290`: Fix attribute caching issue when setting :attr:`ctypes." +"_Pointer._type_` in the undocumented and deprecated :func:`!ctypes." +"SetPointerType` function and the undocumented :meth:`!set_type` method." +msgstr "" +":gh:`133290`: Corrige problema de armazenamento em cache de atributo ao " +"definir :attr:`ctypes._Pointer._type_` na função não documentada e " +"descontinuada :func:`!ctypes.SetPointerType` e no método não documentado :" +"meth:`!set_type`." + +#: ../NEWS:97 +msgid "" +":gh:`133089`: Use original timeout value for :exc:`subprocess." +"TimeoutExpired` when the func :meth:`subprocess.run` is called with a " +"timeout instead of sometimes a confusing partial remaining time out value " +"used internally on the final ``wait()``." +msgstr "" +":gh:`133089`: Usa o valor de tempo limite original para :exc:`subprocess." +"TimeoutExpired` quando a função :meth:`subprocess.run` for chamada com um " +"tempo limite em vez de, às vezes, um valor de tempo limite parcial restante " +"confuso usado internamente no ``wait()`` final." + +#: ../NEWS:102 +msgid "" +":gh:`133009`: :mod:`xml.etree.ElementTree`: Fix a crash in :meth:`Element." +"__deepcopy__ ` when the element is concurrently " +"mutated. Patch by Bénédikt Tran." +msgstr "" + +#: ../NEWS:106 +msgid "" +":gh:`132995`: Bump the version of pip bundled in ensurepip to version 25.1.1" +msgstr "" +":gh:`132995`: Aumenta a versão do pip incluído no EnsurePip para a versão " +"25.1.1" + +#: ../NEWS:108 +msgid "" +":gh:`132017`: Fix error when ``pyrepl`` is suspended, then resumed and " +"terminated." +msgstr "" +":gh:`132017`: Corrige erro quando ``pyrepl`` é suspenso e depois retomado e " +"encerrado." + +#: ../NEWS:111 +msgid "" +":gh:`132673`: Fix a crash when using ``_align_ = 0`` and ``_fields_ = []`` " +"in a :class:`ctypes.Structure`." +msgstr "" +":gh:`132673`: Corrige uma falha ao usar ``_align_ = 0`` e ``_fields_ = []`` " +"em uma :class:`ctypes.Structure`." + +#: ../NEWS:114 +msgid "" +":gh:`132527`: Include the valid typecode 'w' in the error message when an " +"invalid typecode is passed to :class:`array.array`." +msgstr "" +":gh:`132527`: Inclui o typecode válido 'w' na mensagem de erro quando um " +"typecode inválido for passado para :class:`array.array`." + +#: ../NEWS:117 +msgid "" +":gh:`132439`: Fix ``PyREPL`` on Windows: characters entered via AltGr are " +"swallowed. Patch by Chris Eibl." +msgstr "" +":gh:`132439`: Corrigido ``PyREPL`` no Windows: caracteres inseridos via " +"AltGr são engolidos. Patch por Chris Eibl." + +#: ../NEWS:120 +msgid "" +":gh:`132429`: Fix support of Bluetooth sockets on NetBSD and DragonFly BSD." +msgstr "" +":gh:`132429`: Corrige o suporte de soquetes Bluetooth no NetBSD e no " +"DragonFly BSD." + +#: ../NEWS:122 +msgid "" +":gh:`132106`: :meth:`QueueListener.start ` now raises a :exc:`RuntimeError` if the listener is already started." +msgstr "" +":gh:`132106`: :meth:`QueueListener.start ` agora levanta uma :exc:`RuntimeError` se o listener já estiver " +"iniciado." + +#: ../NEWS:126 +msgid "" +":gh:`132417`: Fix a ``NULL`` pointer dereference when a C function called " +"using :mod:`ctypes` with ``restype`` :class:`~ctypes.py_object` returns " +"``NULL``." +msgstr "" +":gh:`132417`: Corrige uma desreferência de ponteiro ``NULL`` quando uma " +"função C chamada usando :mod:`ctypes` com ``restype`` :class:`~ctypes." +"py_object` retorna ``NULL``." + +#: ../NEWS:130 +msgid "" +":gh:`132385`: Fix instance error suggestions trigger potential exceptions " +"in :meth:`object.__getattr__` in :mod:`traceback`." +msgstr "" +":gh:`132385`: Corrige sugestões de erro de instância que acionam possíveis " +"exceções em :meth:`object.__getattr__` em :mod:`traceback`." + +#: ../NEWS:133 +msgid "" +":gh:`132308`: A :class:`traceback.TracebackException` now correctly renders " +"the ``__context__`` and ``__cause__`` attributes from :ref:`falsey ` :" +"class:`Exception`, and the ``exceptions`` attribute from falsey :class:" +"`ExceptionGroup`." +msgstr "" +":gh:`132308`: Uma exceção :class:`traceback.TracebackException` agora " +"renderiza corretamente os atributos ``__context__`` e ``__cause__`` da :" +"class:`Exception` :ref:`falsa `, e o atributo ``exceptions`` de " +"falsey :class:`ExceptionGroup`." + +#: ../NEWS:138 +msgid "" +":gh:`132250`: Fixed the :exc:`SystemError` in :mod:`cProfile` when locating " +"the actual C function of a method raises an exception." +msgstr "" +":gh:`132250`: Corrigida a :exc:`SystemError` em :mod:`cProfile` quando " +"localizar a função C real de um método levanta uma exceção." + +#: ../NEWS:141 +msgid "" +":gh:`132063`: Prevent exceptions that evaluate as falsey (namely, when their " +"``__bool__`` method returns ``False`` or their ``__len__`` method returns 0) " +"from being ignored by :class:`concurrent.futures.ProcessPoolExecutor` and :" +"class:`concurrent.futures.ThreadPoolExecutor`." +msgstr "" +":gh:`132063`: Evita que exceções avaliadas como falsas (ou seja, quando o " +"método ``__bool__`` retorna ``False`` ou o método ``__len__`` retorna 0) " +"sejam ignoradas por :class:`concurrent.futures.ProcessPoolExecutor` e :class:" +"`concurrent.futures.ThreadPoolExecutor`." + +#: ../NEWS:146 +msgid "" +":gh:`119605`: Respect ``follow_wrapped`` for :meth:`!__init__` and :meth:`!" +"__new__` methods when getting the class signature for a class with :func:" +"`inspect.signature`. Preserve class signature after wrapping with :func:" +"`warnings.deprecated`. Patch by Xuehai Pan." +msgstr "" +":gh:`119605`: Respeita ``follow_wrapped`` para os métodos :meth:`!__init__` " +"e :meth:`!__new__` ao obter a assinatura de classe para uma classe com :func:" +"`inspect.signature`. Preserva a assinatura de classe após o encapsulamento " +"com :func:`warnings.deprecated`. Patch por Xuehai Pan." + +#: ../NEWS:151 +msgid "" +":gh:`91555`: Ignore log messages generated during handling of log messages, " +"to avoid deadlock or infinite recursion." +msgstr "" + +#: ../NEWS:154 +msgid "" +":gh:`131434`: Improve error reporting for incorrect format in :func:`time." +"strptime`." +msgstr "" +":gh:`131434`: Melhora o relatório de erros para formato incorreto em :func:" +"`time.strptime`." + +#: ../NEWS:157 +msgid ":gh:`131127`: Systems using LibreSSL now successfully build." +msgstr "" +":gh:`131127`: Sistemas que usam LibreSSL agora são construídos com sucesso." + +#: ../NEWS:159 +msgid "" +":gh:`130941`: Fix :class:`configparser.ConfigParser` parsing empty " +"interpolation with ``allow_no_value`` set to ``True``." +msgstr "" +":gh:`130941`: Corrige :class:`configparser.ConfigParser` analisando " +"interpolação vazia com ``allow_no_value`` definido como ``True``." + +#: ../NEWS:162 +msgid "" +":gh:`129098`: Fix REPL traceback reporting when using :func:`compile` with " +"an inexisting file. Patch by Bénédikt Tran." +msgstr "" +":gh:`129098`: Corrige o relatório de traceback do REPL ao usar :func:" +"`compile` com um arquivo inexistente. Patch por Bénédikt Tran." + +#: ../NEWS:165 +msgid "" +":gh:`130631`: :func:`!http.cookiejar.join_header_words` is now more similar " +"to the original Perl version. It now quotes the same set of characters and " +"always quote values that end with ``\"\\n\"``." +msgstr "" +":gh:`130631`: :func:`!http.cookiejar.join_header_words` agora é mais " +"semelhante à versão original do Perl. Agora, ele coloca aspas o mesmo " +"conjunto de caracteres e sempre coloca aspas em valores que terminam com " +"``\"\\n\"``." + +#: ../NEWS:169 +msgid "" +":gh:`129719`: Fix missing :data:`!socket.CAN_RAW_ERR_FILTER` constant in the " +"socket module on Linux systems. It was missing since Python 3.11." +msgstr "" +":gh:`129719`: Corrige a constante :data:`!socket.CAN_RAW_ERR_FILTER` ausente " +"no módulo socket em sistemas Linux. Ela estava ausente desde o Python 3.11." + +#: ../NEWS:172 +msgid "" +":gh:`124096`: Turn on virtual terminal mode and enable bracketed paste in " +"REPL on Windows console. (If the terminal does not support bracketed paste, " +"enabling it does nothing.)" +msgstr "" + +#: ../NEWS:176 +msgid "" +":gh:`122559`: Remove :meth:`!__reduce__` and :meth:`!__reduce_ex__` methods " +"that always raise :exc:`TypeError` in the C implementation of :class:`io." +"FileIO`, :class:`io.BufferedReader`, :class:`io.BufferedWriter` and :class:" +"`io.BufferedRandom` and replace them with default :meth:`!__getstate__` " +"methods that raise :exc:`!TypeError`. This restores fine details of behavior " +"of Python 3.11 and older versions." +msgstr "" +":gh:`122559`: Remove os métodos :meth:`!__reduce__` e :meth:`!__reduce_ex__` " +"que sempre levantam :exc:`TypeError` na implementação em C de :class:`io." +"FileIO`, :class:`io.BufferedReader`, :class:`io.BufferedWriter` e :class:`io." +"BufferedRandom` e substitua-os pelos métodos padrão :meth:`!__getstate__` " +"que levantam :exc:`!TypeError`. Isso restaura detalhes precisos do " +"comportamento do Python 3.11 e versões anteriores." + +#: ../NEWS:183 +msgid "" +":gh:`122179`: :func:`hashlib.file_digest` now raises :exc:`BlockingIOError` " +"when no data is available during non-blocking I/O. Before, it added spurious " +"null bytes to the digest." +msgstr "" +":gh:`122179`: :func:`hashlib.file_digest` agora levanta :exc:" +"`BlockingIOError` quando não há dados disponíveis durante E/S não " +"bloqueantes. Antes, ele adicionava bytes nulos espúrios ao resumo." + +#: ../NEWS:187 +msgid "" +":gh:`86155`: :meth:`html.parser.HTMLParser.close` no longer loses data when " +"the ``